Documentation
¶
Overview ¶
Package browser defines the persistent browser session metadata model used by the planned `tap browser ...` workflow.
Phase 1 establishes the durable state contract before the runtime is added:
- A session is one persistent browser instance, either local or remote.
- A tab is a named tracked browser target within a session.
- Stored metadata is the source of truth for names and selection defaults.
- Each command must reconcile metadata against live targets before acting.
- Untracked live browser tabs are ignored by default.
- Missing tracked targets become stale until they are recreated or removed.
The package also defines the initial local-vs-remote capability matrix used by CLI help text and README documentation:
- Local sessions own their browser process and profile directory.
- Remote sessions bind metadata to an explicit CDP WebSocket endpoint.
- Remote session creation validates the endpoint up front.
- Remote session close removes tap metadata only and never kills the remote browser process.
Package browser manages alternative browser backends for CDP-based automation.
Index ¶
- Constants
- Variables
- func CapabilitiesForMode(mode Mode) map[Operation]Capability
- func CheckProcess(record *ProcessRecord) error
- func CheckProcessContext(ctx context.Context, record *ProcessRecord) error
- func ClearIntercept(ctx context.Context, debugURL string, targetID string) error
- func CloseTarget(ctx context.Context, debugURL string, targetID string) error
- func CreateTarget(ctx context.Context, debugURL string, url string) (string, error)
- func DefaultStateRoot() (string, error)
- func EnableNetworkLog(ctx context.Context, debugURL string, targetID string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
- func EvalTarget(ctx context.Context, debugURL string, targetID string, js string) (any, error)
- func FillTarget(ctx context.Context, debugURL string, targetID string, fields []FillField, ...) error
- func GetResponseBody(ctx context.Context, debugURL string, targetID string, requestID string) ([]byte, error)
- func KillProcess(record *ProcessRecord) error
- func NavigateTarget(ctx context.Context, debugURL string, targetID string, url string) error
- func ScreenshotTarget(ctx context.Context, debugURL string, targetID string) ([]byte, error)
- func SetInterceptRules(ctx context.Context, debugURL string, targetID string, rules []InterceptRule) (func(), error)
- func ValidateInterceptRules(rules []InterceptRule) error
- func ValidateSessionName(name string) error
- func ValidateTabName(name string) error
- type Capability
- type FillField
- type FormField
- type InterceptRule
- type Lightpanda
- type LocalConfig
- type Manager
- func (m *Manager) CloseSession(_ context.Context, name string) error
- func (m *Manager) CloseTab(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) CreateSession(ctx context.Context, name string, mode Mode, opts SessionOptions) error
- func (m *Manager) CreateTab(ctx context.Context, sessionName string, tabName string, url string) error
- func (m *Manager) Evaluate(ctx context.Context, sessionName string, tabName string, js string) (any, error)
- func (m *Manager) Fill(ctx context.Context, sessionName string, tabName string, fields []FillField, ...) error
- func (m *Manager) Forms(ctx context.Context, sessionName string, tabName string) ([]FormField, error)
- func (m *Manager) GetSession(_ context.Context, name string) (*SessionRecord, error)
- func (m *Manager) ListSessions(_ context.Context) (*SessionList, error)
- func (m *Manager) ListTabs(_ context.Context, sessionName string) (*TabList, error)
- func (m *Manager) Navigate(ctx context.Context, sessionName string, tabName string, url string) error
- func (m *Manager) NetworkClearIntercept(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) NetworkGetBody(ctx context.Context, sessionName string, tabName string, requestID string) ([]byte, error)
- func (m *Manager) NetworkIntercept(ctx context.Context, sessionName string, tabName string, rules []InterceptRule) error
- func (m *Manager) NetworkLog(ctx context.Context, sessionName string, tabName string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
- func (m *Manager) NetworkWait(ctx context.Context, sessionName string, tabName string, filter NetworkFilter, ...) (*NetworkEntry, error)
- func (m *Manager) Reconcile(ctx context.Context, sessionName string) error
- func (m *Manager) Screenshot(ctx context.Context, sessionName string, tabName string) (*ScreenshotResult, error)
- func (m *Manager) SelectSession(_ context.Context, name string) error
- func (m *Manager) SelectTab(_ context.Context, sessionName string, tabName string) error
- type Mode
- type NetworkEntry
- type NetworkFilter
- type Operation
- type ProcessRecord
- type RemoteConfig
- type ScreenshotResult
- type SessionList
- type SessionOptions
- type SessionRecord
- type State
- func (s *State) CreateSession(session *SessionRecord) error
- func (s *State) DeleteSession(name string) error
- func (s *State) DeleteTab(sessionName string, tabName string) error
- func (s *State) Normalize()
- func (s *State) ReconcileSession(sessionName string, liveTargetIDs []string, now time.Time) error
- func (s *State) ResolveSession(name string) (*SessionRecord, error)
- func (s *State) SelectSession(name string) error
- func (s *State) SelectTab(sessionName string, tabName string) error
- func (s *State) UpsertTab(sessionName string, tab *TabRecord) error
- func (s *State) Validate() error
- type Store
- func (s *Store) Load() (*State, error)
- func (s *Store) Root() string
- func (s *Store) Save(state *State) error
- func (s *Store) Update(fn func(*State) error) error
- func (s *Store) UpdateSession(sessionName string, fn func(*State, *SessionRecord) error) error
- func (s *Store) WithSessionLock(sessionName string, fn func() error) error
- type TabList
- type TabRecord
- type TabStatus
- type TargetInfo
Constants ¶
const ( // StateVersion is the current on-disk schema version for browser metadata. StateVersion = 1 // EnvStateRoot overrides the default durable state directory. EnvStateRoot = "TAP_BROWSER_STATE_DIR" )
const TargetTypePage = "page"
Variables ¶
var ( ErrNoSessions = errors.New("no browser sessions found") ErrAmbiguousSession = errors.New("browser session selection is ambiguous") ErrSessionNotFound = errors.New("browser session not found") ErrNoTabs = errors.New("no tracked tabs found") ErrAmbiguousTab = errors.New("browser tab selection is ambiguous") ErrTabNotFound = errors.New("browser tab not found") ErrClosedTabSelected = errors.New("browser tab is closed") ErrStaleTabSelected = errors.New("browser tab is stale") )
Functions ¶
func CapabilitiesForMode ¶ added in v0.1.7
func CapabilitiesForMode(mode Mode) map[Operation]Capability
CapabilitiesForMode returns the documented capability contract for the given mode.
func CheckProcess ¶ added in v0.1.7
func CheckProcess(record *ProcessRecord) error
CheckProcess verifies that the process described by record is alive and its debug endpoint is reachable.
func CheckProcessContext ¶ added in v0.1.7
func CheckProcessContext(ctx context.Context, record *ProcessRecord) error
CheckProcessContext is like CheckProcess but accepts a context for cancellation.
func ClearIntercept ¶ added in v0.2.0
ClearIntercept disables the Fetch domain on a target.
func CloseTarget ¶ added in v0.1.7
CloseTarget closes the browser tab identified by targetID.
func CreateTarget ¶ added in v0.1.7
CreateTarget creates a new browser tab navigated to url and returns its target ID.
func DefaultStateRoot ¶ added in v0.1.7
DefaultStateRoot returns the durable directory used for browser metadata. Uses $XDG_CACHE_HOME/tap/browser, falling back to ~/.cache/tap/browser.
func EnableNetworkLog ¶ added in v0.2.0
func EnableNetworkLog(ctx context.Context, debugURL string, targetID string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
EnableNetworkLog enables the Network domain on a target and streams completed request/response entries to the returned channel. The channel is buffered (256 entries); if the buffer fills, new entries are dropped.
Call the returned cancel func to stop capturing and close the channel. The caller should drain the channel or call cancel to avoid goroutine leaks.
func EvalTarget ¶ added in v0.1.7
EvalTarget evaluates JavaScript in the context of an existing browser tab and returns the result.
func FillTarget ¶ added in v0.1.7
func FillTarget(ctx context.Context, debugURL string, targetID string, fields []FillField, submitSelector string) error
FillTarget fills form fields in a browser tab using React-compatible value setting.
func GetResponseBody ¶ added in v0.2.0
func GetResponseBody(ctx context.Context, debugURL string, targetID string, requestID string) ([]byte, error)
GetResponseBody fetches the response body for a completed request by its ID.
func KillProcess ¶ added in v0.1.7
func KillProcess(record *ProcessRecord) error
KillProcess terminates the Chrome process described by record. It sends a graceful shutdown signal first and falls back to forceful termination after a grace period.
func NavigateTarget ¶ added in v0.1.7
NavigateTarget navigates an existing browser tab to url and waits for the body to be ready.
func ScreenshotTarget ¶ added in v0.1.7
ScreenshotTarget captures a full-page screenshot of an existing browser tab and returns the PNG bytes.
func SetInterceptRules ¶ added in v0.2.0
func SetInterceptRules(ctx context.Context, debugURL string, targetID string, rules []InterceptRule) (func(), error)
SetInterceptRules enables Fetch domain interception with the given rules. It replaces any previously set rules. The returned cancel func stops the interception goroutine and disables the Fetch domain.
Pass nil/empty rules to effectively disable interception (or use ClearIntercept).
func ValidateInterceptRules ¶ added in v0.2.0
func ValidateInterceptRules(rules []InterceptRule) error
ValidateInterceptRules checks that rules are well-formed.
func ValidateSessionName ¶ added in v0.1.7
ValidateSessionName checks the user-facing session naming rules.
func ValidateTabName ¶ added in v0.1.7
ValidateTabName checks the user-facing tab naming rules.
Types ¶
type Capability ¶ added in v0.1.7
Capability describes whether an operation is supported for a session mode.
type FormField ¶ added in v0.1.7
type FormField struct {
Selector string `json:"selector"`
Tag string `json:"tag"`
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Value string `json:"value,omitempty"`
Label string `json:"label,omitempty"`
Required bool `json:"required,omitempty"`
Disabled bool `json:"disabled,omitempty"`
Role string `json:"role,omitempty"`
}
FormField describes a fillable form element on the page.
type InterceptRule ¶ added in v0.2.0
type InterceptRule struct {
Filter NetworkFilter `json:"filter"`
Block bool `json:"block,omitempty"`
AddHeaders map[string]string `json:"addHeaders,omitempty"`
MockStatus int `json:"mockStatus,omitempty"`
MockBody string `json:"mockBody,omitempty"`
MockHeaders map[string]string `json:"mockHeaders,omitempty"`
}
InterceptRule defines how to modify or block requests matching a filter. Block and MockBody are mutually exclusive.
type Lightpanda ¶
type Lightpanda struct {
// contains filtered or unexported fields
}
Lightpanda manages the Lightpanda browser process.
func NewLightpanda ¶
func NewLightpanda(binDir, port string) *Lightpanda
NewLightpanda creates a new Lightpanda manager. binDir is where the binary is stored; if empty, defaults to ~/.cache/tap/lightpanda/. port is the CDP port; if empty, defaults to 9222.
func (*Lightpanda) Cleanup ¶
func (lp *Lightpanda) Cleanup() error
Cleanup removes the downloaded binary.
func (*Lightpanda) EnsureInstalled ¶
func (lp *Lightpanda) EnsureInstalled(ctx context.Context) error
EnsureInstalled downloads the Lightpanda binary if it doesn't exist or is empty.
func (*Lightpanda) Running ¶
func (lp *Lightpanda) Running() bool
Running reports whether the Lightpanda server is currently running.
func (*Lightpanda) Start ¶
func (lp *Lightpanda) Start(ctx context.Context) error
Start launches the Lightpanda server and waits for it to be ready. It is safe to call multiple times — subsequent calls are no-ops if already running.
func (*Lightpanda) WSURL ¶
func (lp *Lightpanda) WSURL() string
WSURL returns the WebSocket URL for the running Lightpanda instance.
type LocalConfig ¶ added in v0.1.7
LocalConfig freezes local launch settings into session metadata.
type Manager ¶ added in v0.1.7
type Manager struct {
// contains filtered or unexported fields
}
Manager coordinates browser session lifecycle, tab management, and browser actions using the metadata store and CDP transport layer.
func NewManager ¶ added in v0.1.7
NewManager creates a session manager backed by the given store.
func (*Manager) CloseSession ¶ added in v0.1.7
CloseSession terminates a browser session, kills the local process if applicable, and removes all related metadata.
func (*Manager) CloseTab ¶ added in v0.1.7
CloseTab closes a browser tab and removes it from session metadata.
func (*Manager) CreateSession ¶ added in v0.1.7
func (m *Manager) CreateSession(ctx context.Context, name string, mode Mode, opts SessionOptions) error
CreateSession launches or connects to a browser and persists session metadata.
func (*Manager) CreateTab ¶ added in v0.1.7
func (m *Manager) CreateTab(ctx context.Context, sessionName string, tabName string, url string) error
CreateTab opens a new browser tab and tracks it in session metadata.
func (*Manager) Evaluate ¶ added in v0.1.7
func (m *Manager) Evaluate(ctx context.Context, sessionName string, tabName string, js string) (any, error)
Evaluate runs JavaScript in a tracked tab and returns the result.
func (*Manager) Fill ¶ added in v0.1.7
func (m *Manager) Fill(ctx context.Context, sessionName string, tabName string, fields []FillField, submitSelector string) error
Fill sets values in form fields of a tracked tab.
func (*Manager) Forms ¶ added in v0.1.7
func (m *Manager) Forms(ctx context.Context, sessionName string, tabName string) ([]FormField, error)
Forms discovers fillable form elements in a tracked tab.
func (*Manager) GetSession ¶ added in v0.1.7
GetSession resolves a session by name (or falls back to the selected/only session).
func (*Manager) ListSessions ¶ added in v0.1.7
func (m *Manager) ListSessions(_ context.Context) (*SessionList, error)
ListSessions returns all tracked sessions sorted by name.
func (*Manager) ListTabs ¶ added in v0.1.7
ListTabs returns all tracked tabs for a session sorted by creation time.
func (*Manager) Navigate ¶ added in v0.1.7
func (m *Manager) Navigate(ctx context.Context, sessionName string, tabName string, url string) error
Navigate changes the URL of a tracked tab.
func (*Manager) NetworkClearIntercept ¶ added in v0.2.0
func (m *Manager) NetworkClearIntercept(ctx context.Context, sessionName string, tabName string) error
NetworkClearIntercept removes all Fetch domain interception rules from a tracked tab.
func (*Manager) NetworkGetBody ¶ added in v0.2.0
func (m *Manager) NetworkGetBody(ctx context.Context, sessionName string, tabName string, requestID string) ([]byte, error)
NetworkGetBody fetches the response body for a completed request by its request ID from a tracked tab.
func (*Manager) NetworkIntercept ¶ added in v0.2.0
func (m *Manager) NetworkIntercept(ctx context.Context, sessionName string, tabName string, rules []InterceptRule) error
NetworkIntercept sets Fetch domain interception rules on a tracked tab. Replaces any previously set rules (cancels the old interception goroutine).
func (*Manager) NetworkLog ¶ added in v0.2.0
func (m *Manager) NetworkLog(ctx context.Context, sessionName string, tabName string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
NetworkLog starts capturing network requests for a tracked tab and streams completed entries to the returned channel. Call cancel to stop capturing.
func (*Manager) NetworkWait ¶ added in v0.2.0
func (m *Manager) NetworkWait(ctx context.Context, sessionName string, tabName string, filter NetworkFilter, includeBody bool) (*NetworkEntry, error)
NetworkWait blocks until a network request matching the filter completes in a tracked tab. If includeBody is true, the response body is fetched before returning. The caller controls the timeout via ctx.
func (*Manager) Reconcile ¶ added in v0.1.7
Reconcile refreshes tab liveness by comparing metadata against live CDP targets.
func (*Manager) Screenshot ¶ added in v0.1.7
func (m *Manager) Screenshot(ctx context.Context, sessionName string, tabName string) (*ScreenshotResult, error)
Screenshot captures a full-page PNG of a tracked tab.
func (*Manager) SelectSession ¶ added in v0.1.7
SelectSession persists the default session used when --session is omitted.
type NetworkEntry ¶ added in v0.2.0
type NetworkEntry struct {
RequestID string `json:"requestId"`
URL string `json:"url"`
Method string `json:"method"`
Status int64 `json:"status"`
MIMEType string `json:"mimeType,omitempty"`
ResourceType string `json:"resourceType,omitempty"`
ReqHeaders map[string]string `json:"reqHeaders,omitempty"`
ResHeaders map[string]string `json:"resHeaders,omitempty"`
Body string `json:"body,omitempty"`
Error string `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
NetworkEntry represents a captured network request/response pair.
func WaitForRequest ¶ added in v0.2.0
func WaitForRequest(ctx context.Context, debugURL string, targetID string, filter NetworkFilter, includeBody bool) (*NetworkEntry, error)
WaitForRequest enables the Network domain and blocks until a request matching the filter completes (response received + loading finished/failed). It returns the first matching NetworkEntry. If includeBody is true, the response body is fetched before returning.
The caller controls the timeout via ctx (e.g. context.WithTimeout).
type NetworkFilter ¶ added in v0.2.0
type NetworkFilter struct {
URLPattern string `json:"urlPattern,omitempty"`
Methods []string `json:"methods,omitempty"`
ResourceTypes []string `json:"resourceTypes,omitempty"`
}
NetworkFilter specifies criteria for matching network requests.
type Operation ¶ added in v0.1.7
type Operation string
Operation is a user-facing browser action supported by the session manager.
type ProcessRecord ¶ added in v0.1.7
type ProcessRecord struct {
PID int `json:"pid,omitempty"`
DebugURL string `json:"debug_url,omitempty"`
OwnershipToken string `json:"ownership_token,omitempty"`
StartedAt time.Time `json:"started_at,omitempty"`
}
ProcessRecord stores the launch markers needed for later ownership checks.
func LaunchBrowser ¶ added in v0.1.7
func LaunchBrowser(ctx context.Context, config LocalConfig) (*ProcessRecord, error)
LaunchBrowser starts a managed Chrome process with remote debugging enabled. The returned ProcessRecord contains the PID, debug WebSocket URL, and an ownership token that later calls can use for verification.
type RemoteConfig ¶ added in v0.1.7
type RemoteConfig struct {
WSURL string `json:"ws_url"`
}
RemoteConfig freezes the remote reconnect endpoint into session metadata.
type ScreenshotResult ¶ added in v0.1.7
ScreenshotResult holds the screenshot data and resolved names.
type SessionList ¶ added in v0.1.7
type SessionList struct {
Sessions []*SessionRecord
SelectedSession string
}
SessionList holds the result of listing sessions including the current selection.
type SessionOptions ¶ added in v0.1.7
type SessionOptions struct {
// Headless controls whether a local browser launches headlessly.
Headless bool
// WSURL is the remote browser WebSocket endpoint (remote mode only).
WSURL string
}
SessionOptions holds optional settings for session creation.
type SessionRecord ¶ added in v0.1.7
type SessionRecord struct {
Name string `json:"name"`
Mode Mode `json:"mode"`
Local *LocalConfig `json:"local,omitempty"`
Remote *RemoteConfig `json:"remote,omitempty"`
Process *ProcessRecord `json:"process,omitempty"`
SelectedTab string `json:"selected_tab,omitempty"`
Tabs map[string]*TabRecord `json:"tabs,omitempty"`
Capabilities map[Operation]Capability `json:"capabilities,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastReconciledAt time.Time `json:"last_reconciled_at,omitempty"`
}
SessionRecord stores one persistent browser session and its tracked tabs.
func NewLocalSession ¶ added in v0.1.7
func NewLocalSession(name string, profileDir string, headless bool, now time.Time) (*SessionRecord, error)
NewLocalSession builds a validated local session record.
func NewRemoteSession ¶ added in v0.1.7
NewRemoteSession builds a validated remote session record.
func (*SessionRecord) ResolveTab ¶ added in v0.1.7
func (s *SessionRecord) ResolveTab(name string) (*TabRecord, error)
ResolveTab returns an explicit tab, the selected tab, or the only live tracked tab when exactly one live tab exists.
type State ¶ added in v0.1.7
type State struct {
Version int `json:"version"`
SelectedSession string `json:"selected_session,omitempty"`
Sessions map[string]*SessionRecord `json:"sessions"`
}
State is the durable browser session metadata written to disk.
func NewState ¶ added in v0.1.7
func NewState() *State
NewState returns an empty metadata state with initialized maps.
func (*State) CreateSession ¶ added in v0.1.7
func (s *State) CreateSession(session *SessionRecord) error
CreateSession adds a new named session and selects it if it is the first one.
func (*State) DeleteSession ¶ added in v0.1.7
DeleteSession removes a session and clears the selected session when needed.
func (*State) DeleteTab ¶ added in v0.1.7
DeleteTab removes a tracked tab and advances selection to the next live tab.
func (*State) Normalize ¶ added in v0.1.7
func (s *State) Normalize()
Normalize repairs nil maps and empty versions loaded from disk.
func (*State) ReconcileSession ¶ added in v0.1.7
ReconcileSession updates tab liveness after reloading or reconnecting a browser session.
func (*State) ResolveSession ¶ added in v0.1.7
func (s *State) ResolveSession(name string) (*SessionRecord, error)
ResolveSession returns the explicit session, the selected session, or the only available session when there is exactly one.
func (*State) SelectSession ¶ added in v0.1.7
SelectSession persists the default session used when --session is omitted.
func (*State) SelectTab ¶ added in v0.1.7
SelectTab persists the default live tab used when --tab is omitted.
type Store ¶ added in v0.1.7
type Store struct {
// contains filtered or unexported fields
}
Store manages durable browser metadata with atomic writes and file locks.
func NewStore ¶ added in v0.1.7
NewStore initializes a metadata store rooted at the provided directory.
func (*Store) Update ¶ added in v0.1.7
Update takes an exclusive store lock, mutates the current state, and saves it.
func (*Store) UpdateSession ¶ added in v0.1.7
UpdateSession combines session-scoped locking with durable store mutation.
type TabList ¶ added in v0.1.7
TabList holds the result of listing tabs including the current selection.
type TabRecord ¶ added in v0.1.7
type TabRecord struct {
Name string `json:"name"`
TargetID string `json:"target_id,omitempty"`
URL string `json:"url,omitempty"`
Status TabStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastSeenAt time.Time `json:"last_seen_at,omitempty"`
}
TabRecord stores the durable metadata for a tracked browser target.
type TabStatus ¶ added in v0.1.7
type TabStatus string
TabStatus tracks whether a named tab can be used directly.
type TargetInfo ¶ added in v0.1.7
TargetInfo holds metadata about a CDP target (browser tab).
func ListTargets ¶ added in v0.1.7
func ListTargets(ctx context.Context, debugURL string) ([]TargetInfo, error)
ListTargets enumerates page targets in a browser reachable at debugURL.