Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/browser"

Package browser is zelk’s own browser: a headless Chrome the agent drives over the DevTools Protocol to debug web apps and check its own work (docs/design/browser.md). Chrome runs on the host or, with a sandbox, in bwrap’s browser profile under the session’s network mode, and is reached only through a pipe pair, never a port. Hosts opt in; core never starts a browser on its own. On Windows the pipe carries CDP through inherited handles and a Job Object owns Chrome’s process tree.

It also drives the user’s own Chrome through zelk’s extension (docs/design/user-browser.md): Attach takes the extension’s connection, Linked holds it for one session at a time, and UserTools gives the user_browser_* tools, which work only in zelk’s tab group and never type or show credentials; UserSkill and UserPrompt go with them. There zelk also runs page script, reads bodies, downloads, watches pages to wake a session, paces its input as a person’s, and exports a site’s sign-in with the user’s click (docs/design/browser-automation.md). On Windows a native messaging host relays the extension’s encrypted link.

Example

Start a browser, report what it is, and close it. Without a sandbox in the config, Chrome runs on the host.

ctx := context.Background()
b, err := browser.Start(ctx, browser.Config{Path: "/opt/chrome/chrome", Data: "/var/lib/zelk/browser"})
if errors.Is(err, browser.ErrExited) {
fmt.Println("Chrome couldn't start:", err)
return
}
if err != nil {
fmt.Println(err)
return
}
defer b.Close(ctx)
fmt.Println(b.Version().Product)
const (
LevelError = "error"
LevelWarning = "warning"
LevelInfo = "info"
LevelLog = "log"
LevelDebug = "debug"
)

Console levels.

const (
DownloadInProgress = "inProgress"
DownloadCompleted = "completed"
DownloadCanceled = "canceled"
)

Download states.

const (
DefaultFindLimit = 10
MaxFindLimit = 50
)

DefaultFindLimit and MaxFindLimit bound the elements Find gives refs.

const (
// DefaultRecordFrames is how many frames a recording keeps unless
// its options say otherwise.
DefaultRecordFrames = 300
// DefaultRecordSide is the longest side of a recorded frame unless
// the options say otherwise: big enough to read a page, small enough
// that a minute of frames stays a few megabytes.
DefaultRecordSide = 800
)

Recording bounds.

const (
// DefaultSnapshotLines and DefaultSnapshotBytes cap a snapshot
// unless its options say otherwise. A large page's outline fits; a
// page past them gets a note on how to narrow it.
DefaultSnapshotLines = 500
DefaultSnapshotBytes = 24 << 10
)

Snapshot caps and frame bounds.

const DefaultConnectWait = 35 * time.Second

DefaultConnectWait is how long a call waits for zelk’s extension to connect. The extension’s worker sleeps when idle and wakes to dial every 30 seconds, so the wait covers one wake.

const (
// DefaultConsoleLimit is how many entries Console returns unless the
// query says otherwise: the latest that match.
DefaultConsoleLimit = 100
)

Console bounds.

const DefaultIdle = 30 * time.Minute

DefaultIdle is how long a pooled browser stays open with no browser call (docs/design/browser.md, D7): it holds 300 MB or more, and 15 minutes would drop a logged-in test account while the user reviews a change.

const (
// DefaultNetworkLimit is how many requests Network returns unless
// the query says otherwise: the latest that match.
DefaultNetworkLimit = 100
)

Network log bounds.

const DefaultPort = link.DefaultPort

DefaultPort is the loopback port zelk and its extension meet on unless a pairing names another.

const DefaultTolerance = 16

DefaultTolerance is how far apart, in any colour channel (0 to 255), two pixels may be and still count as the same: antialiasing and compression move edges by a few levels between renders.

const DefaultWatchInterval = time.Minute

DefaultWatchInterval is the least time between a watch’s wakes unless it asks for another (WatchOptions.MinInterval).

const LinkPorts = 8

LinkPorts is how many ports, from the pairing’s, zelk processes listen on: as many may share the user’s browser at once.

const MaxSavedValue = 64 << 20

MaxSavedValue bounds a value EvaluateWith returns for saving to a file, which doesn’t go through the model’s context.

const NativeMessagingHost = "com.zelk.browser"

NativeMessagingHost is the Windows host name registered for zelk’s extension.

const PairingTime = 10 * time.Minute

PairingTime is how long a pairing code is good for.

var (
// ErrNotActionable reports an element that can't take the action:
// hidden, disabled, covered, moving, or of the wrong kind. The
// error says which, and nothing was done.
ErrNotActionable = errors.New("element can't take the action")
// ErrMayHaveRun reports an action cut short after its first input
// reached the page: it may have run, in part or whole. It is never
// sent again on its own; check the page before repeating it.
ErrMayHaveRun = errors.New("the action may have run: check the page before repeating it")
)

Errors of acting on an element.

var (
// ErrBlocked reports a page the session's network policy refused.
ErrBlocked = errors.New("blocked by the network policy")
// ErrNoHistory reports a back or forward with nowhere to go.
ErrNoHistory = errors.New("no page to go to in the tab's history")
// ErrLocalPort reports a page on this machine's loopback, at a port
// the sandbox doesn't reach: only those the user named do
// (Config.Local).
ErrLocalPort = errors.New("this machine's port isn't open to the sandboxed browser")
)

Errors of navigation.

var (
// ErrTabClosed reports a tab that was closed, by the agent or by its
// page. Its number is not reused.
ErrTabClosed = errors.New("tab is closed")
// ErrTabCrashed reports a tab whose page crashed. Closing it is all
// that is left to do.
ErrTabCrashed = errors.New("tab crashed")
// ErrDialog reports a dialog the page opened, which holds the tab
// until it is answered. The error is a *DialogError.
ErrDialog = errors.New("the page opened a dialog")
)

Errors of a tab.

var ErrChecksum = errors.New("download doesn't match zelk's pin")

ErrChecksum reports a download that isn’t the pinned archive: another size or SHA-256. Nothing of it was opened or installed.

var ErrCoverage = errors.New("coverage is already running in this tab")

ErrCoverage reports coverage started while it runs in the tab.

var ErrCredentialField = errors.New("in the user's browser zelk types into no password, one-time-code, card or masked field")

ErrCredentialField reports input zelk refused in the user’s browser: its target, or the focus, is a password, one-time-code, card or masked field. Signing in is the user’s (docs/design/user-browser.md, Hard limits).

var ErrDisconnected = errors.New("the user's browser is not connected")

ErrDisconnected reports that the user’s browser is out of reach: the connection to zelk’s extension in it ended (its worker restarted, the browser quit, the user stopped it). Unlike ErrExited, nothing of zelk’s was lost: the browser and its tabs are the user’s and live on.

var ErrExited = errors.New("browser exited")

ErrExited reports a browser that is no longer running: it exited or crashed, or was closed. Its pages are gone; a new browser starts empty.

var ErrExportDeclined = errors.New("the user declined to export their sign-in")

ErrExportDeclined is the user’s Deny on a session export.

var ErrHeapSnapshot = errors.New("a heap snapshot is already being taken in this tab")

ErrHeapSnapshot reports a heap snapshot taken while one is taken in the tab.

var ErrInUse = errors.New("another zelk session is using the user's browser")

ErrInUse reports that another root session holds the user’s browser: one session at a time works in it (docs/design/user-browser.md, U8).

var ErrLinkedClosed = errors.New("the link to the user's browser is closed")

ErrLinkedClosed reports a call after the link was closed.

var ErrNoRequest = errors.New("no such request")

ErrNoRequest reports a request the tab doesn’t have: never made, or long enough ago that newer ones took its place.

var ErrNoRoute = errors.New("no such route")

ErrNoRoute reports a route ID the tab doesn’t have.

var ErrNoWake = errors.New("this zelk can't be woken by a watch: run it where a session stays open, such as the TUI")

ErrNoWake is a watch asked of a browser whose host gave it no way to wake a session (AttachConfig.Wake).

var ErrNotInUserBrowser = errors.New("zelk doesn't do this in the user's browser")

ErrNotInUserBrowser reports something zelk never does in the user’s browser, whatever asks: it would read what their session holds or change what their real sites do (docs/design/user-browser.md, U5).

var ErrNotInstalled = errors.New("browser not installed")

ErrNotInstalled reports that the pinned Chrome isn’t installed; zelk browser setup installs it.

var ErrNotPaired = errors.New("zelk isn't paired with its extension in your browser: run zelk browser pair")

ErrNotPaired reports that zelk and its extension in the user’s browser haven’t paired.

var ErrNothingCovered = errors.New("none of the page's own scripts or styles ran during the coverage")

ErrNothingCovered reports coverage during which none of the page’s own code ran. The driver’s evaluations don’t count: they aren’t the page’s.

var ErrOtherExtension = errors.New("another extension's frame is in the page, such as a password manager's menu on a field, and the browser lets zelk work only in pages without one: ask the user to close it (Esc, or a click elsewhere on the page), then try again; the tab keeps its number")

ErrOtherExtension reports that another extension’s frame in the page, such as a password manager’s menu on a field, keeps zelk out of the tab: Chrome lets no extension’s debugger stay in such a page. The tab is taken again, under its number, once the frame is gone.

var ErrOtherSite = errors.New("the link is to another site than the page's: zelk fetches only the page's own site's files in the user's browser")

ErrOtherSite is a link to a site other than the page’s own.

var ErrPoolClosed = errors.New("the browser pool is closed")

ErrPoolClosed reports a call after the pool was closed.

var ErrProfiling = errors.New("a CPU profile is already running in this tab")

ErrProfiling reports a CPU profile started while one runs in the tab.

var ErrRecording = errors.New("the tab is already being recorded")

ErrRecording reports a tab already being recorded.

var ErrRefusedURL = errors.New("the browser doesn't open this URL")

ErrRefusedURL reports a URL the driver won’t open: a file outside the directories pages may load, or a scheme that isn’t for pages.

var ErrSecretInResult = errors.New("the script's value holds what is typed in a password, one-time-code or card field, which zelk doesn't read in the user's browser")

ErrSecretInResult is a script’s value that carries what the user typed into a password, one-time-code or card field.

var ErrSessionGone = errors.New("the watch's session no longer exists")

ErrSessionGone reports a session that no longer exists; its watch ends.

var ErrStaleRef = errors.New("stale ref")

ErrStaleRef reports a ref that no longer names an element: the page navigated, or the element was removed. A new snapshot gives current refs.

var ErrStopped = errors.New("the user stopped zelk's use of their browser: ask them before going on")

ErrStopped reports that the user stopped zelk’s use of their browser, in the extension’s panel or with Cancel on Chrome’s bar. It holds until they press Resume; zelk asks them before going on.

var ErrTampered = errors.New("installed browser changed since setup")

ErrTampered reports an install whose files no longer match what setup recorded: changed or removed since. Setup replaces it.

var ErrTracing = errors.New("a trace is already running")

ErrTracing reports a trace started while one runs.

var ErrWatchEnded = errors.New("the watch source has ended")

ErrWatchEnded reports a source that has already ended; it is not reinstalled.

func CookieJSON(cs []Cookie) ([]byte, error)

CookieJSON is cs as a JSON array of objects with the names Chrome’s and Playwright’s cookies use: name, value, domain, path, expires (in seconds since 1970, -1 for a session cookie), httpOnly, secure and sameSite.

func CookieJar(cs []Cookie) []byte

CookieJar is cs in the Netscape cookie-jar format curl’s -b and Python’s http.cookiejar.MozillaCookieJar read. HttpOnly cookies are written as curl writes them, #HttpOnly_ before the domain. A cookie that lasts the browser session is written to expire in 2038, the latest time every reader takes: curl’s own 0 is one Python keeps only when told to and then never sends, and an empty field is a line curl skips. The site still decides when the sign-in ends.

func DeviceNames() []string

DeviceNames lists the device presets.

func ExtensionID() string

ExtensionID is the ID of zelk’s extension wherever it is loaded: its manifest’s key fixes it.

func FailReasons() []string

FailReasons lists the network errors a route can fail requests with.

func MissingLibraries(ctx context.Context, exe string, dirs ...string) ([]string, error)

MissingLibraries returns the shared libraries the executable at exe needs that neither the system’s library cache nor exe’s directory nor dirs, the directories of LD_LIBRARY_PATH, holds. It reads exe’s ELF header and never runs it: ldd can run the program it inspects.

func NetworkProfiles() []string

NetworkProfiles lists the network throttling profiles.

func NewPairingCode() string

NewPairingCode returns a one-time code for Pair, written XXXX-XXXX, for the user to type into the extension.

func PairingDocument(path string, opts ...secret.Option) *secret.Document

PairingDocument returns the secret document the pairing at path is kept in, with opts, for listing it and moving it between a file and a keychain.

func Prompt() string

Prompt is what a session’s system prompt says of the browser when a host gives it the tools: that the agent has one, when to use it, and how to treat what pages say. The skill holds the rest, and the deferred tools are found through ToolSearch.

func ServeNativeMessaging(ctx context.Context, stream io.ReadWriteCloser) (result error)

ServeNativeMessaging relays the extension’s link over a native messaging stream. The caller authenticates Chromium’s invocation and gives the host a stream whose Close interrupts both reads and writes. The first frame names a loopback port. Pairing, peer proofs and encryption stay between the extension and zelk; the relay never sees the pairing key. The stream is closed when either peer disconnects or ctx ends.

func Skill() skill.Source

Skill is the built-in skill that teaches the model the browser tools: the snapshot, act, check loop, refs, waits, what to read before guessing, recipes and what each error means. A host gives it with the tools (zelk.WithSkills). It is host-trusted, so a project skill of the same name doesn’t replace it.

func Tools(src Source) ([]*tool.Tool, error)

Tools returns the browser tools: the eleven always offered first, then the deferred ones, which the model finds through ToolSearch. Each session (each subagent too) has its own current tab; tabs a page opens can be taken up by any.

Example

Give an agent the browser tools: eleven always offered, the rest found through ToolSearch.

ctx := context.Background()
b, err := browser.Start(ctx, browser.Config{Path: "/opt/chrome/chrome", Data: "/var/lib/zelk/browser"})
if err != nil {
fmt.Println(err)
return
}
defer b.Close(ctx)
tools, err := browser.Tools(fixed{b})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(tools), "tools, the first", tools[0].Spec().Name)
// Pass them to zelk.New with zelk.WithTools(tools...).
func UserPrompt() string

UserPrompt is what a session’s system prompt says of the user’s own browser when a host gives the user_browser_* tools. With Prompt too, each names its own browser, so the model can tell them apart.

func UserSkill() skill.Source

UserSkill is the built-in skill for the user’s own browser’s tools (UserTools): what differs from zelk’s own browser, why signing in is the user’s, handing steps over, and what each refusal means. A host gives it with those tools. It is host-trusted, like Skill.

func UserTools(src Source) ([]*tool.Tool, error)

UserTools returns the tools for the user’s own browser, reached through zelk’s extension: user_browser_*, the same tools as Tools less what would read or change what the user’s session holds (docs/design/user-browser.md, U5), offered and deferred as zelk’s own are. src gives each session the attached browser it uses.

func WriteExtension(dir string) error

WriteExtension writes zelk’s extension for the user’s browser into dir, for the user to load unpacked (docs/design/user-browser.md, U10). dir is created if missing; one that holds anything but an earlier copy of the extension is refused, so nothing of the user’s is overwritten.

func WriteNativeExtension(dir, host string) error

WriteNativeExtension writes the Windows extension, which opens host through the browser’s native messaging API. The caller registers that host to run NativeMessaging. Use NativeMessagingHost for a regular install.

type AttachConfig struct {
// Data is zelk's own directory for the browser: an existing,
// canonical directory where captures go (traces, recordings). Unlike
// Config.Data it holds no profile: the browser's is the user's.
Data string
// MapPath maps where the browser says it saved a download to a path
// zelk can open: a Windows path, for a zelk under WSL. Nil keeps it.
MapPath func(string) string
// Wake delivers a watch's wakes to its session; nil for a host that
// can't be woken, whose tabs can't be watched.
Wake func(context.Context, Wake) error
// WatchSources records source lifecycle for watches; nil for raw wake hosts.
WatchSources WatchSources
// Pace is how input goes: a person's pace unless Off
// (docs/design/browser-automation.md, A7).
Pace Pace
// contains filtered or unexported fields
}

AttachConfig says how to use a browser zelk attaches to.

type Audit struct {
// Engine is the checker and its version.
Engine string
// Violations are the rules elements fail, the most severe first.
Violations []Violation
// Incomplete counts the rules axe couldn't decide, which need a
// person to look.
Incomplete int
// Frames counts the frames audited; Skipped says which couldn't be,
// and why.
Frames int
Skipped []string
}

Audit is an accessibility audit’s result. Everything in it but the rules’ own text comes from the page and is untrusted.

type AuditNode struct {
// Ref names the element, as a snapshot's refs do; "" if it couldn't
// be found again.
Ref string
// Target is axe's selector for it; HTML, the start of its markup.
Target, HTML string
// Summary says what to fix.
Summary string
}

AuditNode is an element that fails a rule.

type AuditOptions struct {
// Ref, if set, audits only that element and what it holds.
Ref string
// Tags, if set, runs only the rules with these axe tags, as wcag2aa
// or best-practice; Rules, if set, only these rules by ID, as
// color-contrast. Neither: axe's default rules.
Tags, Rules []string
}

AuditOptions say what to audit.

type BoxModel struct {
Content, Padding, Border, Margin Rect
}

BoxModel is an element’s boxes, from the inside out.

type Browser struct {
// contains filtered or unexported fields
}

Browser is a running browser. Its methods are safe for concurrent use.

func Attach(ctx context.Context, t Transport, cfg AttachConfig) (*Browser, error)

Attach uses the browser at the other end of t, which zelk didn’t start and never closes: the user’s own, reached through zelk’s extension (docs/design/user-browser.md). Close lets go of the tabs zelk attached to and of t, and nothing else. The browser’s downloads are left as the user set them; those zelk’s tabs start are listed as the extension reports them. Pages load no files. When t ends, calls fail with ErrDisconnected and Exited is closed. Attach owns t once it is called with a valid config. Hosts can supply a transport on Windows as well.

func Start(ctx context.Context, cfg Config) (*Browser, error)

Start starts a browser and waits, as long as ctx allows, until it answers. A browser that exits first fails Start with ErrExited and the end of what it wrote to standard error, which names a missing library or a sandbox it couldn’t set up.

func (b *Browser) CaptureDir() string

CaptureDir is where the browser keeps traces, profiles and heap snapshots.

func (b *Browser) Close(ctx context.Context) error

Close asks the browser to shut down, kills what is left of it after a short grace or when ctx is done, waits for its process and removes its profile. A browser zelk attached to is only let go: its tabs are detached and the connection ends. It is safe to call more than once and after the browser exited; later calls return the first’s result.

func (b *Browser) CompareHeaps(before, after string) (HeapDiff, error)

CompareHeaps finds what grew between two heap snapshots the browser took, named by their paths.

func (b *Browser) DownloadDir() string

DownloadDir is where the browser’s downloads go: the downloads directory of its Config.Data.

func (b *Browser) Downloads() []Download

Downloads lists the browser’s downloads, oldest first. In the user’s browser they are those zelk’s tabs started, as its extension reports them.

func (b *Browser) Exited() <-chan struct{}

Exited is closed when the browser’s process has exited, or, for a browser zelk attached to, when the connection to it ended.

func (b *Browser) NewTab(ctx context.Context) (*Tab, error)

NewTab opens a blank tab.

func (b *Browser) Tab(ctx context.Context, id int) (*Tab, error)

Tab returns tab number id, which may be one a page opened.

func (b *Browser) Tabs(ctx context.Context) ([]TabInfo, error)

Tabs lists the browser’s tabs, numbered in the order they were first seen: those the agent opened and those its pages opened.

func (b *Browser) Unwatch(id string) error

Unwatch ends watch id for good, telling no one.

func (b *Browser) UnwatchContext(ctx context.Context, id string) error

UnwatchContext records a quiet source end before forgetting id. A recording failure leaves the watch available to retry; it never starts a model run.

func (b *Browser) Version() Version

Version returns what the browser said it is when it started.

func (b *Browser) Watches() []WatchInfo

Watches lists the browser’s watches, oldest first.

type ClickOptions struct {
// Button is left (the default), right or middle.
Button string
// Count is 1 (the default) for a click, 2 for a double click.
Count int
// Modifiers held during the click: Alt, Control, Meta, Shift.
Modifiers []string
}

ClickOptions say how to click.

type Condition struct {
// contains filtered or unexported fields
}

Condition is something a tab can wait for.

func UntilLoaded(state LoadState) Condition

UntilLoaded waits for the tab’s page to reach state.

func UntilRef(ref string, state RefState) Condition

UntilRef waits for the element ref names to reach state.

func UntilText(text string) Condition

UntilText waits for the page’s visible text to contain text.

func UntilTextGone(text string) Condition

UntilTextGone waits for the page’s visible text not to contain text.

func UntilURL(pattern string) Condition

UntilURL waits for the tab’s address to match pattern: contain it, or, if it has a *, match it whole, each * standing for any run of characters.

func (c Condition) String() string
type Config struct {
// Path is Chrome's or Chromium's absolute path.
Path string
// Env is the browser's whole environment, as KEY=value pairs, such
// as LD_LIBRARY_PATH for libraries beside the install. A sandbox
// keeps only what it keeps for a command. On Windows zelk supplies
// the user's Local AppData for Chrome's AppContainers and a
// private temporary directory under Chrome's profile.
Env []string
// Data is the browser's own directory: an existing, canonical
// directory holding its profile, downloads and captures, and nothing
// another program trusts. Each browser makes its profile in it, and
// removes it when it closes. On Windows its ACL must keep other
// users from accessing its contents.
Data string
// Sandbox, if set, confines the browser; nil runs it on the host.
Sandbox Sandbox
// ReadOnly, Workspace, Helper and Local are passed to the sandbox
// (launcher.Browser); without one they are unused. Path's directory
// is bound read-only too.
ReadOnly []string
Workspace string
Helper string
Local []launcher.LocalPort
// Files are directories, besides Workspace and Data, whose files
// pages may load as file: URLs, such as the session's scratch
// directory. No page loads a file anywhere else, whether a tab is
// sent there or a page links or embeds it.
Files []string
// Egress, set when the browser's traffic goes through zelk's egress
// proxy (allowlist mode), is its policy. The driver uses it only to
// say a page was blocked by it rather than unreachable.
Egress Egress
// contains filtered or unexported fields
}

Config says which browser to start and how.

type ConsoleEntry struct {
// Seq numbers the tab's entries in order, from 1.
Seq int
// Level is error, warning, info, log or debug.
Level string
// Source is console, exception or browser.
Source string
Text string
// URL, Line and Column say where it came from, if known; Line and
// Column count from 1.
URL string
Line, Column int
// Stack is where it was logged or thrown, innermost first.
Stack []StackFrame
}

ConsoleEntry is a message the page logged, an exception it didn’t catch, or a message of the browser’s own about the page (a failed load, a blocked request). Everything in it comes from the page and is untrusted.

type ConsoleLog struct {
Entries []ConsoleEntry
// Last is the Seq of the tab's latest entry: pass it as Since to see
// only what comes after.
Last int
// Omitted counts entries that matched but past Limit; Missed those
// after Since the tab no longer keeps.
Omitted, Missed int
}

ConsoleLog is what Console found.

type ConsoleQuery struct {
// Since, if set, keeps entries after that Seq.
Since int
// Levels, if set, keeps entries at those levels.
Levels []string
// Text, if set, keeps entries whose text holds it, ignoring case.
Text string
// Limit is how many of the latest matching entries to return
// (DefaultConsoleLimit if 0).
Limit int
}

ConsoleQuery picks entries.

type Cookie struct {
Name, Value string
Domain, Path string
// Expires is when it expires; zero for a cookie that lasts the
// session.
Expires time.Time
HTTPOnly, Secure bool
// SameSite is Strict, Lax, None or "".
SameSite string
}

Cookie is a cookie in the browser. In zelk’s own browser, whose profile is its own, it is one its pages set; in the user’s, only ExportSession gives one, with the user’s click.

type Coverage struct {
// contains filtered or unexported fields
}

Coverage is code coverage being recorded in a tab.

func (c *Coverage) Stop(ctx context.Context) (CoverageReport, error)

Stop ends the recording and reports the coverage.

type CoverageReport struct {
// JSTotal and JSUnused are bytes of script, and of it never run;
// CSSTotal and CSSUnused, of style sheets, and of them outside every
// rule used, as DevTools counts it.
JSTotal, JSUnused int64
CSSTotal, CSSUnused int64
// Files are the files with the most unused bytes, most first.
Files []FileCoverage
// Incomplete reports style sheets missed, from a page that added
// more than could be followed.
Incomplete bool
// CSSOnly reports a recording without JavaScript: in the user's
// browser, where Chrome refuses an extension the profiler.
CSSOnly bool
}

CoverageReport is how much of the page’s JavaScript and CSS ran or applied. URLs come from the page and are untrusted.

type Dialog struct {
Type string `json:"type"`
Message string `json:"message"`
DefaultPrompt string `json:"defaultPrompt"`
URL string `json:"url"`
}

Dialog is a JavaScript dialog a page opened: alert, confirm, prompt or beforeunload. It holds its tab, and only its tab, until answered.

type DialogError struct{ Dialog Dialog }

DialogError is an action stopped by a dialog the page opened.

func (e *DialogError) Error() string
func (e *DialogError) Is(target error) bool

Is makes errors.Is(err, ErrDialog) true.

type Diff struct {
// Changed is the share of pixels that differ, from 0 to 1, over the
// larger of the two images.
Changed float64
// Pixels counts them.
Pixels int
// Box holds every changed pixel, in the after image's pixels; zero
// when nothing changed.
Box Rect
// SizeChanged reports images of different sizes: what one has and
// the other doesn't counts as changed.
SizeChanged bool
// Image is a PNG of the after image faded, with the changed pixels
// red; nil when nothing changed.
Image []byte
}

Diff is how two screenshots differ.

func Compare(before, after []byte, tolerance int) (Diff, error)

Compare compares two PNG screenshots pixel by pixel. A tolerance of 0 is DefaultTolerance; pass -1 for exact.

type Download struct {
// ID is Chrome's for it.
ID string
URL string
// Name is the file's name, as the page suggested it, made safe.
Name string
// Path is where it is, once completed; "" before.
Path string
// State is inProgress, completed or canceled.
State string
Received, Total int64
Started time.Time
// Target is the tab that started it, in the user's browser, and
// Error why it stopped, as the browser says it.
Target, Error string
}

Download is a file a page downloaded.

type Egress interface {
Allowed(host, port string) bool
}

Egress is the network policy of the egress proxy the browser goes through. *egress.Proxy implements it.

type Emulation struct {
// Device, if set, is a preset (DeviceNames lists them): its viewport,
// scale, touch and user agent, under any of the fields below.
Device string
// Width and Height, if set, are the viewport in CSS pixels.
Width, Height int
// Scale is the device pixel ratio (1 if 0).
Scale float64
// Mobile lays the page out as on a phone (meta viewport, overlay
// scrollbars); Touch sends touch input support.
Mobile, Touch bool
// UserAgent, if set, replaces the browser's.
UserAgent string
// ColorScheme is light, dark or "" (the browser's).
ColorScheme string
// ReducedMotion asks pages for less motion.
ReducedMotion bool
// Locale, as en-GB, and TimeZone, as Europe/Berlin, if set.
Locale, TimeZone string
// Offline cuts the page off the network; Network, if set, throttles
// it to a profile (NetworkProfiles lists them).
Offline bool
Network string
// CPUSlowdown, if more than 1, slows the page's CPU that many times.
CPUSlowdown float64
}

Emulation is what a tab pretends to be. Emulate sets all of it: a field left zero is Chrome’s own, so an emulation never lingers unseen.

type EvalError struct {
// Message is the exception as the page describes it, with its stack.
Message string
}

EvalError is an exception the evaluated script threw.

func (e *EvalError) Error() string
type EvalOptions struct {
// Isolated runs the script in a world of zelk's own in the tab's
// main frame: it sees the DOM, not the page's JavaScript objects, and
// the page can't see or change it.
Isolated bool
// Max bounds the value's JSON, up to MaxSavedValue; maxValue if 0.
Max int
}

EvalOptions changes how EvaluateWith runs a script.

type Export struct {
// Site is the tab's registrable domain, as the user was shown it.
Site string
Cookies []Cookie
}

Export is a site’s session, as the user let zelk have it.

type Fetched struct {
// Name is the file's name, as the response's Content-Disposition
// gives it or else the URL's last segment; it may be empty.
Name string
// Type is the response's Content-Type.
Type string
Body []byte
}

Fetched is a file a page’s own request got.

type FileCoverage struct {
// URL is the file's; an inline script or sheet has its page's, and
// a sheet a script made has "(constructed)".
URL string
// Kind is js or css.
Kind string
Total, Unused int64
}

FileCoverage is one file’s coverage.

type FindOptions struct {
Selector string
Text string
Limit int
}

FindOptions say what Find looks for: elements matching Selector, a CSS selector, or holding Text, or both. Limit caps the elements returned, DefaultFindLimit if 0.

type Found struct {
Elements []FoundElement
Total int
}

Found is what Find found: the first matches, with refs, and how many matched in all.

type FoundElement struct {
Ref string
// Tag is its tag with its id and first classes, as div#drop.zone.
Tag string
// Text is the start of its text.
Text string
// Box is where it is in its frame's viewport, nil if not rendered.
Box *Rect
// Frame is its frame's URL, "" for the page's own.
Frame string
// Origin is its frame's origin, which acting on it takes.
Origin string
}

FoundElement is an element Find gave a ref.

type Frame struct {
// At is when the page showed it, from the recording's start.
At time.Duration
// JPEG is the frame.
JPEG []byte
}

Frame is one recorded frame.

type FrameInfo struct {
ID string
// Parent is the frame holding it, "" for the page's own.
Parent string
URL string
Name string
// Origin is its security origin.
Origin string
// OutOfProcess reports a frame from another site, run in a process
// of its own.
OutOfProcess bool
// Ref is its iframe element's ref, once a snapshot gave one.
Ref string
}

FrameInfo describes one frame of a page.

type Gap struct {
// From is when it stopped; zero when zelk ended without saying.
From time.Time `json:"from"`
// To is when it was installed again.
To time.Time `json:"to"`
// Why says what stopped it.
Why string `json:"why"`
}

Gap is a time a watch wasn’t running.

type HandoffResult string

HandoffResult is how a handoff ended.

const (
// HandoffDone: the user pressed Done, saying they did the step.
HandoffDone HandoffResult = "done"
// HandoffDeclined: the user pressed Decline: they won't do it.
HandoffDeclined HandoffResult = "declined"
// HandoffClosed: the user closed the tab.
HandoffClosed HandoffResult = "closed"
)

How a handoff ends.

type HeapClass struct {
// Name is the constructor's, or the kind's in parentheses, as
// (closure) or (string).
Name string
Count int
Size int64
}

HeapClass is one kind of object in the heap.

type HeapDiff struct {
SizeBefore, SizeAfter int64
DetachedBefore, DetachedAfter int
// Grew are the classes that grew most, by size, then count.
Grew []HeapGrowth
}

HeapDiff is what grew between two heap snapshots.

type HeapGrowth struct {
Name string
CountBefore, CountAfter int
SizeBefore, SizeAfter int64
}

HeapGrowth is how one class changed.

type HeapSnapshot struct {
// Path is the snapshot file (.heapsnapshot), which DevTools opens
// and CompareHeaps compares.
Path string
// Nodes counts the objects; Size is their self size in bytes.
Nodes int
Size int64
// Detached counts DOM nodes out of every document that something
// still holds: the usual sign of a leak.
Detached int
// Classes are the largest classes by self size.
Classes []HeapClass
}

HeapSnapshot sums up the page’s JavaScript heap. Class names come from the page and are untrusted.

type HotFunction struct {
// Frame is where the function starts, source-mapped when its script
// has a map.
Frame StackFrame
// Self is time in the function itself; Total includes what it called.
Self, Total time.Duration
}

HotFunction is a function’s share of a profile.

type Image struct {
// PNG is the image.
PNG []byte
// Width and Height are the image's size in pixels.
Width, Height int
// Cut reports a full page taller than a screenshot can be, cut at
// its bottom.
Cut bool
}

Image is a screenshot.

type InspectOptions struct {
// Styles, if set, are the computed styles to return instead of the
// default set.
Styles []string
}

InspectOptions say what to inspect.

type Inspection struct {
Ref string
// Tag is its tag name, lower case.
Tag string
// Attributes are its attributes in order, as name="value".
Attributes []string
// Styles are its computed styles, by property.
Styles map[string]string
// Box is its box model in its frame's viewport, CSS pixels: nil for
// an element that isn't laid out.
Box *BoxModel
// Listeners are the event listeners on the element itself.
Listeners []Listener
// Text is the start of its text, as it shows.
Text string
}

Inspection is one element’s details. Everything in it comes from the page and is untrusted.

type Installed struct {
// Dir is the install's directory; Executable the browser in it.
Dir string
Executable string
Version string
Platform string
}

Installed is a browser installed by Install.

func Install(ctx context.Context, client *http.Client, dir string, pin Pin) (_ Installed, err error)

Install installs pin’s browser under dir and returns it. It downloads the archive over HTTPS with client, from pin.URL’s host only, reads no more than pin.Size bytes, and refuses it (ErrChecksum) unless its size and SHA-256 match the pin; only then does it extract it, defensively, into a temporary directory that becomes the install by one rename. An intact install of pin is kept as it is; a changed one is replaced, and installs of other versions are removed. Concurrent Installs under dir take turns. dir must be an absolute directory zelk owns.

func OpenInstall(dir string, pin Pin) (Installed, error)

OpenInstall returns pin’s install under dir after checking that its executable is the one setup installed, by hash: a quick check before each start. Verify checks every file.

func (in Installed) Verify() error

Verify checks that the install is still the build it was and every file is as setup recorded, with nothing added.

type LinkStatus struct {
// Holder is the root session holding the browser, "" if none.
Holder string
// Listening says zelk waits for the extension; Connected that it is
// connected.
Listening, Connected bool
// Port is the port zelk listens on, of the pairing's range, while
// Listening.
Port int
// Stopped says the user stopped zelk's use of their browser, in the
// extension or with Cancel or the close button on Chrome's bar: it
// holds until Resume, and zelk's watches are paused until then.
Stopped bool
// StoppedBy is how the user stopped it, while Stopped: StopPanel or
// StopBar, or "" from an extension that doesn't say.
StoppedBy Stop
// WatchesError is why the watches couldn't be saved, last time: they
// run, but a new zelk won't install them again.
WatchesError error
}

LinkStatus is where the link to the user’s browser stands.

type Linked struct {
// contains filtered or unexported fields
}

Linked is the Source for the user’s own browser, reached through zelk’s extension (docs/design/user-browser.md, Lifecycle). It listens on the first free loopback port of the pairing’s range, from Listen or the first call, and holds the extension’s link to this process for one root session, shared by its subagents; other zelk processes have links of their own (docs/design/browser-processes.md). A connection that ends (the extension’s worker restarted) is waited for again, and the tabs keep their numbers. It lets go of the browser and stops listening on CloseSession, Close and the idle time, so the extension shows zelk is done. It never closes the user’s browser. It is safe for concurrent use.

func NewLinked(p Pairing, data string, opts ...LinkedOption) (*Linked, error)

NewLinked returns the source for the user’s browser paired as p. data is zelk’s own directory for it (AttachConfig.Data).

func (l *Linked) Browser(ctx context.Context, c tool.Call) (*Browser, error)

Browser returns the user’s browser for c’s root session, waiting for the extension to connect if it isn’t. Another root session holding it is ErrInUse; no connection within the wait is ErrDisconnected.

func (l *Linked) Changes() <-chan struct{}

Changes is signalled when the status may have changed: a host reads Status again. One signal stands for any number of changes.

func (l *Linked) Close(ctx context.Context) error

Close lets go of the user’s browser, stops listening and refuses further calls. It waits for idle releases under way.

func (l *Linked) CloseSession(ctx context.Context, session string) error

CloseSession lets go of the user’s browser if session’s root session holds it, as stopping the session’s background work or deleting it does.

func (l *Linked) EndWatch(id string) error

EndWatch ends watch id for good, as the user may from a host: it stops running, telling no one, and isn’t kept.

func (l *Linked) EndWatchContext(ctx context.Context, id string) error

EndWatchContext records a quiet source end, then forgets a running or kept watch. Recording failures leave the watch available for another attempt.

func (l *Linked) Hold(ctx context.Context, session string) error

Hold makes session’s root session the one zelk holds the user’s browser for, before any call needs it: it listens, and when the extension connects it tells the extension which session it holds, as the first call would, and does so again when the extension connects anew. A host that knows its root session calls it so the user can share a tab in the extension before the agent first uses the browser. It returns at once; the connecting goes on until the session lets go (CloseSession, the idle time) or Close. Another root session holding the browser is ErrInUse; holding again is a no-op.

func (l *Linked) Kept() []WatchInfo

Kept lists the watches kept for every session, running or not, as a host shows them, each with its wakes.

func (l *Linked) Listen(ctx context.Context) error

Listen starts listening for the extension, if it isn’t already, so it can connect before the first call needs it. Listening stops with the next release.

func (l *Linked) Rewatch(ctx context.Context, session string) error

Rewatch installs session’s kept watches again, connecting to the user’s browser for it, as a host does when it resumes the session in a new zelk. A session with none kept needs nothing.

func (l *Linked) Running() []string

Running lists the root session holding the user’s browser, if one does.

func (l *Linked) SetPace(p Pace)

SetPace sets how input goes in the user’s browser from the next action on, as a host does when its user changes it while zelk runs; an action under way keeps its pace.

func (l *Linked) SetPairing(ctx context.Context, p Pairing) error

SetPairing makes p the pairing the extension proves, as pairing anew while zelk runs does. Listening, zelk takes p’s key at once and lets go of the connection proven with the old one: the extension, paired anew, closed its connections and connects again with the new key, and one holding the old key is refused. The session holding the browser keeps it, so its watches are installed again when the extension connects, and a call waiting for the extension is answered by that connection. A pairing on another port listens there instead; a call waiting on the old port ends.

It doesn’t wait for a call under way: it holds l.mu only.

func (l *Linked) Status() LinkStatus

Status says where the link stands now.

func (l *Linked) Watches() []WatchInfo

Watches lists the watches running in the user’s browser, for a host’s status; those kept while it isn’t connected are listed by Watching.

func (l *Linked) Watching() []string

Watching lists the root sessions with watches kept, which a host installs again with Rewatch when it resumes one.

type LinkedOption func(*Linked)

LinkedOption configures a Linked.

func WithConnectWait(d time.Duration) LinkedOption

WithConnectWait waits d for the extension to connect, instead of DefaultConnectWait.

func WithLinkLabel(label string) LinkedOption

WithLinkLabel names this zelk to the user in the extension: its tab group’s title and its part of the side panel, such as “zelk · shop” for the workspace shop. The default is “zelk”.

func WithLinkedIdle(d time.Duration) LinkedOption

WithLinkedIdle lets go of the browser after d with no call, instead of DefaultIdle.

func WithPace(p Pace) LinkedOption

WithPace sets how input goes in the user’s browser: a person’s pace unless p.Off (AttachConfig.Pace).

func WithPathMap(f func(string) string) LinkedOption

WithPathMap maps where the user’s browser says it saved a download to a path zelk can open (AttachConfig.MapPath).

func WithTrust(t Trust) LinkedOption

WithTrust shows t’s sites in the extension’s panel while zelk is connected, and revokes one there when the user asks.

func WithWake(f func(context.Context, Wake) error) LinkedOption

WithWake lets the agent watch tabs (Tab.Watch), each wake delivered by f to the session that made the watch: a host wakes an idle session with it, as a finished background job does.

func WithWatchSources(sources WatchSources) LinkedOption

WithWatchSources records durable watch sources through sources. The host supplies it together with WithWake; it retains ownership of the implementation.

type Listener struct {
// Type is the event, as click.
Type string
// Handler is the start of the function's source.
Handler string
// Line and Column are where the function is in its script, from 1.
Line, Column int
Capture, Passive, Once bool
}

Listener is an event listener.

type LoadState string

LoadState is how far a page gets before a navigation counts as done.

const (
// LoadPage waits for the page's load event: its document, images,
// scripts and styles are in. It is the default.
LoadPage LoadState = "load"
// LoadDOM waits only for the document to be parsed.
LoadDOM LoadState = "domcontentloaded"
// LoadNetworkIdle waits for the load event and then for no request
// in flight for 500 ms, for pages that fetch their content.
LoadNetworkIdle LoadState = "networkidle"
)

Load states.

type LongTask struct {
// Start is from the trace's start.
Start, Duration time.Duration
// Script is the call that took most of it, if a script ran.
Script *StackFrame
}

LongTask is a task that blocked the page’s main thread.

type NavigationError struct {
URL string
// Reason is Chrome's, such as net::ERR_NAME_NOT_RESOLVED.
Reason string
}

NavigationError is a page that couldn’t be loaded.

func (e *NavigationError) Error() string
type NetworkLog struct {
Requests []Request
// Last is the Seq of the tab's latest request.
Last int
// Omitted counts requests that matched but past Limit; Missed those
// after Since the tab no longer keeps.
Omitted, Missed int
}

NetworkLog is what Network found.

type NetworkQuery struct {
// Since, if set, keeps requests after that Seq.
Since int
// URL, if set, keeps requests whose URL holds it.
URL string
// Types, if set, keeps requests of those types.
Types []string
// MinStatus and MaxStatus, if set, keep responses in that range.
MinStatus, MaxStatus int
// Failed keeps only requests that failed or got a status of 400 or
// more.
Failed bool
// Limit is how many of the latest matching requests to return
// (DefaultNetworkLimit if 0).
Limit int
}

NetworkQuery picks requests.

type Pace struct {
// Off sends input at once, as in zelk's own browser.
Off bool
// Source is the variation's randomness; a random seed if nil. Tests
// give a fixed one.
Source rand.Source
// Sleep waits d, or less when ctx is done; a timer if nil. Tests
// record the waits instead.
Sleep func(ctx context.Context, d time.Duration) error
}

Pace makes the driver’s input in the user’s browser a person’s (docs/design/browser-automation.md, A7): the pointer travels a curved path, speeding up and slowing down, to a point inside its target that isn’t the centre, and rests before it presses; keys go one at a time at a varied pace, longer at the end of a word; the wheel turns in steps; and actions are a person’s pause apart. Pages that read input timing see nothing that sets the user’s tabs apart from the user.

type Page struct {
URL string
Title string
// Status is the HTTP status of the page's document, or 0 when it had
// none: a file, about:blank, or a navigation within the document.
Status int
}

Page is where a tab is after a navigation.

type Pairing struct {
Key []byte `json:"key"`
Port int `json:"port"`
}

Pairing is what zelk keeps of its pairing with the extension: the key both hold and the port they meet on. The key lets whoever has it drive the user’s browser, so it lives in an owner-only file the host keeps from tools.

func LoadPairing(ctx context.Context, path string, opts ...secret.Option) (Pairing, error)

LoadPairing reads the pairing saved at path; ErrNotPaired if there is none. opts give the keychain the pairing may be kept in.

func Pair(ctx context.Context, path, code string, port int, listening func(at int), opts ...secret.Option) (Pairing, error)

Pair listens on the first free port of the range from port, on 127.0.0.1, until the extension pairs with code, for PairingTime at most, and saves the pairing to path, replacing any before it, with the range’s first port. opts choose a keychain (secret.WithVault, secret.WithNewIn). listening is called once zelk listens, with the port, for the host to show the code. Five wrong codes void it (design, Pairing and the connection).

type Pin struct {
Version string
Platform string // Chrome for Testing's name: linux64, mac-arm64, win64
URL string // https only
Size int64 // the archive's size in bytes
SHA256 string // the archive's SHA-256, lower-case hex
// Executable is the browser's path inside the archive, with '/'.
Executable string
}

Pin is one platform’s Chrome for Testing build, as zelk pins it in its source (docs/design/browser.md, Setup). Nothing at setup time can change a pin.

func PinFor(goos, goarch string) (Pin, bool)

PinFor returns zelk’s pin of Chrome for Testing for a Go platform, goos and goarch, and whether there is one: Linux and macOS on amd64 and arm64, and Windows on amd64.

The pins are made with the chromepin suite (pin_tool_test.go), never by hand, and each update’s commit carries the suite’s report. macOS pins are candidates first (testdata/macpins.json), which the macOS job installs on a Mac; Google doesn’t sign Chrome for Testing for macOS, so they rest on the same checks as Linux’s (docs/design/browser.md, Setup).

type Pool struct {
// contains filtered or unexported fields
}

Pool is a Source that gives each root session a browser of its own, shared by its subagents (the sessions whose IDs event.ChildSessionID derives from it; an ID that merely has a slash is a root session of its own): started on its first browser call, started again if Chrome exited, and closed once no call used it for the idle time. It is safe for concurrent use.

func NewPool(start StartFunc, opts ...PoolOption) (*Pool, error)

NewPool returns a pool that starts browsers with start.

func (p *Pool) Browser(ctx context.Context, c tool.Call) (*Browser, error)

Browser returns c’s root session’s browser, starting one if it has none or the last one exited.

func (p *Pool) Close(ctx context.Context) error

Close closes every browser and refuses further calls. It waits for idle closes under way.

func (p *Pool) CloseSession(ctx context.Context, session string) error

CloseSession closes the browser of session’s root session, if it has one, as stopping the session’s background work does. Its next browser call starts a fresh one.

func (p *Pool) Running() []string

Running lists the root sessions whose browsers are open.

type PoolOption func(*Pool)

PoolOption configures a Pool.

func WithIdle(d time.Duration) PoolOption

WithIdle closes a browser after d with no browser call, instead of DefaultIdle.

type Profile struct {
// contains filtered or unexported fields
}

Profile is a CPU profile being recorded in a tab.

func (p *Profile) Stop(ctx context.Context) (ProfileSummary, error)

Stop ends the profile, writes it to a file in the browser’s captures directory, and sums it up.

type ProfileSummary struct {
// Path is the profile file (.cpuprofile), which DevTools opens.
Path string
Duration time.Duration
Samples int
// Idle, Program and GC are time idle, in the browser's own code, and
// collecting garbage.
Idle, Program, GC time.Duration
// Functions are the functions with the most self time, most first.
Functions []HotFunction
}

ProfileSummary is where the page’s main thread spent its time. Its names and URLs come from the page and are untrusted.

type RecordOptions struct {
// MaxFrames is how many frames to keep (DefaultRecordFrames if 0);
// later ones are counted, not kept.
MaxFrames int
// MaxSide is the longest side of a frame in pixels
// (DefaultRecordSide if 0).
MaxSide int
}

RecordOptions bound a recording.

type Recorded struct {
Frames []Frame
// Length is how long the recording ran.
Length time.Duration
// Dropped counts frames past MaxFrames, not kept.
Dropped int
}

Recorded is what a recording saw: a frame each time the page drew something new, and last the page as it was at Stop.

func (r Recorded) GIF() ([]byte, error)

GIF returns the frames as an animated GIF, each shown until the next, the last for a second.

type Recording struct {
// contains filtered or unexported fields
}

Recording is a recording of a tab in progress. Stop ends it.

func (r *Recording) Stop(ctx context.Context) (Recorded, error)

Stop ends the recording and returns what it saw, ending with the page as it is now: Chrome sends a frame only some time after the page draws, so the last change could otherwise be missing. A recording the tab or browser ended returns what it saw with why it ended.

type Rect struct{ X, Y, Width, Height float64 }

Rect is a rectangle in CSS pixels.

func (r Rect) String() string
type RefState string

RefState is a state an element can be waited for to reach.

const (
RefVisible RefState = "visible"
RefHidden RefState = "hidden"
RefEnabled RefState = "enabled"
RefDisabled RefState = "disabled"
RefChecked RefState = "checked"
RefUnchecked RefState = "unchecked"
// RefGone waits for the element to leave the page.
RefGone RefState = "gone"
)

Element states.

type Request struct {
// Seq numbers the tab's requests in order, from 1; each redirect is
// a request of its own.
Seq int
Method string
URL string
// Type is what the page wanted it for: Document, Script, Stylesheet,
// Image, Font, XHR, Fetch, EventSource, WebSocket, Other ...
Type string
// Status is the response's status, 0 until a response or with none.
Status int
StatusText string
MIME string
// Size is the bytes received, headers included.
Size int
// Started is when it was sent; Duration how long it took, 0 while it
// is in flight.
Started time.Time
Duration time.Duration
// Done reports that it finished or failed.
Done bool
// Failed is why it failed, as Chrome says (net::ERR_...), or "".
Failed string
// Blocked reports a request the session's network policy refused.
Blocked bool
// FromCache reports a response from a cache, not the network.
FromCache bool
// RedirectedTo is where a redirect sent it.
RedirectedTo string
// Initiator is what made the request: a script's URL and line, the
// document, or "".
Initiator string
// Route is the ID of the route that answered, failed or held it; 0
// if none did.
Route int
}

Request is a request the page made. Everything in it comes from the page and is untrusted.

type RequestDetail struct {
Request
RequestHeaders, ResponseHeaders map[string]string
// PostData is what was sent, if anything; PostNote says why it isn't
// shown.
PostData []byte
PostNote string
// Body is the response body; BodyNote says why there is none or it
// is cut short.
Body []byte
BodyNote string
}

RequestDetail is one request with its headers and bodies.

type Route struct {
// Pattern matches a request's whole URL: * stands for any run of
// characters and everything else for itself, as
// "*://api.example.com/items*" or "*/api/*".
Pattern string
// Method, if set, matches only requests with it.
Method string
// Status, if set, answers with this status, Headers and Body.
Status int
Headers map[string]string
Body []byte
// Fail, if set, fails the request with this network error (FailReasons
// lists them).
Fail string
// Delay holds each request this long first.
Delay time.Duration
// Times, if set, removes the route once it has matched that many
// requests.
Times int
}

Route changes the requests whose URL matches Pattern: it answers them without the network (Status), fails them (Fail), or holds them (Delay) before either or before letting them through. Requests from the page and its iframes are routed; those of workers are not.

type RouteInfo struct {
ID int
Route
// Hits counts the requests it matched.
Hits int
}

RouteInfo is a route the tab has.

type Sandbox interface {
WrapBrowser(ctx context.Context, br launcher.Browser) (launcher.Spec, error)
}

Sandbox confines the browser’s process. *launcher.Bwrap, *launcher.Seatbelt and *launcher.MXC implement it.

type ScreenshotOptions struct {
// Ref, if set, captures only that element, scrolled into view.
Ref string
// FullPage captures the whole page, not only what is on screen.
FullPage bool
}

ScreenshotOptions say what to capture: the viewport unless FullPage or Ref says otherwise.

type ScriptTime struct {
URL string
Time time.Duration
}

ScriptTime is the time one script ran.

type Snapshot struct {
// Text is the outline, ending in a note on what was left out and
// how to narrow it, if anything was.
Text string
// Lines is how many lines Text's outline has; Omitted how many more
// the caps left out.
Lines, Omitted int
}

Snapshot is a page’s outline: one line per element that says something, indented by nesting, as `@e12 button “Save” disabled`. Elements one can act on, and the page’s parts, have refs. Everything in it comes from the page and is untrusted.

type SnapshotOptions struct {
// Ref, if set (e12 or @e12), shows only that element and what is
// inside it.
Ref string
// Depth, if positive, is how many levels below the top to show.
Depth int
// Viewport shows only what is in the viewport.
Viewport bool
// Boxes adds each ref's box: [x,y wxh] in page CSS pixels.
Boxes bool
// MaxLines and MaxBytes cap the snapshot (the defaults if 0).
MaxLines, MaxBytes int
}

SnapshotOptions narrow a snapshot.

type Source interface {
// Browser returns the browser for c's session, starting one if it
// has none or the last one exited. It must be safe for concurrent
// use.
Browser(ctx context.Context, c tool.Call) (*Browser, error)
}

Source gives each session the browser it uses. A host implements it: one browser per root session, shared by its subagents, started on the first call and closed when idle (docs/design/browser.md, D7).

type StackFrame struct {
Function string
URL string
Line, Column int // from 1
// Original is where the source map says the code came from, as
// "name src/cart.ts:13:5", or "" when there is no map.
Original string
}

StackFrame is one call in a stack.

func (f StackFrame) String() string
type StartFunc func(ctx context.Context, root, scratch string) (*Browser, error)

StartFunc starts the browser for a root session. scratch is the session’s scratch directory, “” if it has none: the place for the browser’s data (Config.Data and Config.Files), so its captures can be read back and go with the session.

type Stop string

Stop is how the user stopped zelk’s use of their browser.

const (
// StopPanel is the Stop button in zelk's extension.
StopPanel Stop = "panel"
// StopBar is the browser's debugging bar: its Cancel or close button,
// which Chrome reports alike.
StopBar Stop = "bar"
)

The user’s stops.

type StorageKind string

StorageKind is a page’s local or session storage.

const (
LocalStorage StorageKind = "local"
SessionStorage StorageKind = "session"
)

Storage kinds.

type Tab struct {
// contains filtered or unexported fields
}

Tab is one tab of the browser. Its methods are safe for concurrent use; actions on one tab never wait for another.

func (t *Tab) AddRoute(ctx context.Context, r Route) (int, error)

AddRoute adds a route to the tab and returns its ID. The newest route matching a request is the one applied.

func (t *Tab) AnswerDialog(ctx context.Context, accept bool, text string) error

AnswerDialog answers the dialog holding the tab: accept or dismiss it, with text for a prompt that is accepted.

func (t *Tab) Audit(ctx context.Context, o AuditOptions) (Audit, error)

Audit checks the page, or the element o.Ref names, for accessibility problems with axe-core. axe runs in each frame in a world of its own, where the page’s scripts can neither see nor change it.

func (t *Tab) Back(ctx context.Context, until LoadState) (Page, error)

Back goes to the previous page of the tab’s history.

func (t *Tab) Check(ctx context.Context, ref string, checked bool) error

Check sets the checkbox, radio button or switch ref names to checked, clicking it if it isn’t already, and confirms the click took.

func (t *Tab) ClearCookies(ctx context.Context) error

ClearCookies deletes the cookies the page itself would send. Other sites’ cookies stay, whether in its frames or in other tabs: one site’s clearing mustn’t sign the browser out of another.

func (t *Tab) ClearStorage(ctx context.Context, kind StorageKind, key string) error

ClearStorage empties the page’s local or session storage, or removes only key if it is set.

func (t *Tab) Click(ctx context.Context, ref string, o ClickOptions) error

Click clicks the element ref names at its centre, once it is visible, still and not covered. Input is real: the page sees trusted events.

Example

Fill in a form by the refs a snapshot gives, then submit it.

ctx := context.Background()
b, err := browser.Start(ctx, browser.Config{Path: "/opt/chrome/chrome", Data: "/var/lib/zelk/browser"})
if err != nil {
fmt.Println(err)
return
}
defer b.Close(ctx)
tab, err := b.NewTab(ctx)
if err != nil {
fmt.Println(err)
return
}
if _, err := tab.Navigate(ctx, "http://localhost:3000/signup", browser.LoadPage); err != nil {
fmt.Println(err)
return
}
// @e3 textbox "Email"
// @e5 checkbox "Accept the terms" not checked
// @e6 button "Sign up"
if _, err := tab.Snapshot(ctx, browser.SnapshotOptions{}); err != nil {
fmt.Println(err)
return
}
if err := tab.Fill(ctx, "e3", "ada@example.com"); err != nil {
fmt.Println(err)
return
}
if err := tab.Check(ctx, "e5", true); err != nil {
fmt.Println(err)
return
}
err = tab.Click(ctx, "e6", browser.ClickOptions{})
switch {
case errors.Is(err, browser.ErrNotActionable):
// Nothing was done; the error says why: covered by a banner,
// disabled, hidden.
fmt.Println(err)
case errors.Is(err, browser.ErrMayHaveRun):
// Cut short after the click reached the page: look before
// clicking again.
fmt.Println(err)
case err != nil:
fmt.Println(err)
}
func (t *Tab) Close(ctx context.Context) error

Close closes the tab. Closing a tab that is gone does nothing. In the user’s browser the extension closes only a tab zelk opened; one the user shared is let go and leaves zelk’s group, and stays open.

func (t *Tab) Console(ctx context.Context, q ConsoleQuery) (ConsoleLog, error)

Console returns the tab’s console entries q picks, oldest first, with their stacks mapped through the scripts’ source maps, which are fetched through Chrome.

func (t *Tab) Cookies(ctx context.Context) ([]Cookie, error)

Cookies returns the cookies the page’s frames would send.

func (t *Tab) Dialog() (Dialog, bool)

Dialog returns the dialog holding the tab, if one is.

func (t *Tab) Drag(ctx context.Context, from, to string) error

Drag drags the element from names onto the element to names, with the mouse: pages that follow the pointer see it move, and HTML drag and drop gets its drag events.

func (t *Tab) Emulate(ctx context.Context, e Emulation) error

Emulate makes the tab pretend to be e, replacing what it was before. The page isn’t reloaded: what it decided at load (a mobile layout, its locale) may need a reload to change. In the user’s browser it runs only in tabs zelk opened, and without Locale and TimeZone (U14).

func (t *Tab) Emulation() Emulation

Emulation returns the tab’s current emulation.

func (t *Tab) Evaluate(ctx context.Context, expression string) (json.RawMessage, error)

Evaluate runs expression in the tab’s page, as the user would (so it may open a popup or play media), waits for it if it returns a promise, and returns its value as JSON. Each call is a script of its own, so its declarations may repeat the last one’s. A value that isn’t JSON (a function, a DOM node) is an error saying what it is. The value comes from the page and is untrusted.

func (t *Tab) EvaluateOn(ctx context.Context, ref, function string) (json.RawMessage, error)

EvaluateOn runs function, a JavaScript function declaration, with the element ref names as this, in the element’s own frame, and returns its value as Evaluate does: “el => el.value” or “function () { return this.dataset }”.

func (t *Tab) EvaluateWith(ctx context.Context, expression string, o EvalOptions) (json.RawMessage, error)

EvaluateWith is Evaluate with options: in an isolated world, or with a larger value.

func (t *Tab) ExportSession(ctx context.Context) (Export, error)

ExportSession asks the user, in zelk’s extension, to let zelk have the cookies of the tab’s site, and waits for their answer (docs/design/browser-automation.md, A9). Only the panel’s Allow gives them: nothing zelk or the page sends can, and the extension reads them itself. Deny is ErrExportDeclined; the user’s stop, ErrStopped; the tab’s close, ErrTabClosed; ctx’s end withdraws the request. The values are the user’s account: a caller writes them where only the user reads them and never shows them. Only in the user’s browser.

func (t *Tab) Fill(ctx context.Context, ref, text string) error

Fill replaces the text of the field ref names (an input, a textarea or an editable element) with text, typed as one insertion, as a paste would. In the user’s browser a field a password manager offers to fill (an email, a username, an address, a card) gets its value set, and the page told, without focusing it: the manager’s inline menu comes with the focus, and Chrome lets no extension’s debugger stay in a page holding another extension’s frame. Other fields are typed at a person’s pace.

func (t *Tab) Find(ctx context.Context, o FindOptions) (Found, error)

Find gives refs to elements a snapshot may not show, such as a plain <div> used as a drop zone: those matching o.Selector or holding o.Text, in every frame, the page’s own first. It looks in a world of its own in each frame, where the page’s scripts can’t change what it sees; it doesn’t look inside shadow roots. The refs work with every action, as a snapshot’s do.

func (t *Tab) Forward(ctx context.Context, until LoadState) (Page, error)

Forward goes to the next page of the tab’s history.

func (t *Tab) Frames(ctx context.Context) ([]FrameInfo, error)

Frames lists the page’s frames, the page’s own first, each before the frames it holds.

func (t *Tab) Handoff(ctx context.Context, message string) (HandoffResult, error)

Handoff asks the user to do a step in the tab themselves (sign in, pass a check, confirm a payment) and waits until they answer in zelk’s extension, whose side panel shows message with Done and Decline. Nothing the page does can answer: the page can’t reach the extension’s UI (docs/design/user-browser.md, U13). The user’s stop ends the wait with ErrStopped; ctx’s end withdraws the request. Only in the user’s browser.

func (t *Tab) HeapSnapshot(ctx context.Context) (HeapSnapshot, error)

HeapSnapshot collects garbage, then snapshots the page’s JavaScript heap to a file in the browser’s captures directory and sums it up. Iframes from other sites have heaps of their own and aren’t in it.

func (t *Tab) Hover(ctx context.Context, ref string) error

Hover moves the mouse over the element ref names.

func (t *Tab) ID() int

ID is the tab’s number, unique for the browser’s life.

func (t *Tab) Info(ctx context.Context) (Page, error)

Info describes the tab’s page as it is now.

func (t *Tab) Inspect(ctx context.Context, ref string, o InspectOptions) (Inspection, error)

Inspect returns the details of the element ref names: attributes, computed styles, box model and event listeners.

func (t *Tab) Navigate(ctx context.Context, rawURL string, until LoadState) (Page, error)

Navigate opens rawURL in the tab and waits until the page reaches until (LoadPage if empty). A dialog the page opens on the way ends the wait with a *DialogError; a wait cut short by ctx’s deadline is a *WaitError saying how far the page got.

URLs other than web pages are refused with ErrRefusedURL: a file: URL outside Config’s directories, javascript:, and chrome: pages but a few.

Example

Open a page in a new tab and wait for the app to say it is ready.

ctx := context.Background()
b, err := browser.Start(ctx, browser.Config{Path: "/opt/chrome/chrome", Data: "/var/lib/zelk/browser"})
if err != nil {
fmt.Println(err)
return
}
defer b.Close(ctx)
tab, err := b.NewTab(ctx)
if err != nil {
fmt.Println(err)
return
}
page, err := tab.Navigate(ctx, "http://localhost:3000/", browser.LoadNetworkIdle)
var dialog *browser.DialogError
switch {
case errors.Is(err, browser.ErrBlocked):
fmt.Println("the session's network policy refused it:", err)
return
case errors.As(err, &dialog):
// The page asks something; dismiss it and go on.
if err := tab.AnswerDialog(ctx, false, ""); err != nil {
fmt.Println(err)
return
}
case err != nil:
fmt.Println(err)
return
}
fmt.Println(page.Status, page.Title)
if err := tab.Wait(ctx, browser.UntilText("Ready")); err != nil {
fmt.Println(err)
}
func (t *Tab) Network(q NetworkQuery) NetworkLog

Network returns the tab’s requests q picks, oldest first.

func (t *Tab) PageFetch(ctx context.Context, link string) (Fetched, error)

PageFetch gets link, a URL or a path relative to the page, with the page’s own request and the user’s session: an “Export CSV” link’s file, with no download dialog and nothing in the browser’s downloads (docs/design/browser-automation.md, A10). The link must be on the page’s own site, over http or https. It runs in a world of zelk’s own, so the page’s scripts can’t change fetch.

func (t *Tab) Press(ctx context.Context, ref, keys string) error

Press presses keys, chords like “Enter”, “Control+A” or “Shift+Tab Enter”, to the element ref names, focused first, or to whatever has focus if ref is empty.

func (t *Tab) Record(ctx context.Context, o RecordOptions) (*Recording, error)

Record starts recording what the tab shows, a frame each time the page draws something new, until Stop. A tab has one recording at a time.

func (t *Tab) Reload(ctx context.Context, until LoadState) (Page, error)

Reload loads the tab’s page again, fetching every resource anew as a hard reload does: what a cache kept would hide edits to the files.

func (t *Tab) RemoveRoute(ctx context.Context, id int) error

RemoveRoute removes the route with the ID, or every route for 0.

func (t *Tab) Request(ctx context.Context, seq int) (RequestDetail, error)

Request returns the request numbered seq with its headers and bodies. In the user’s browser it has no bodies, and the extension has removed the values of credential headers. The response body comes from Chrome’s buffer, which keeps the latest bodies: an old one may be gone, and BodyNote says so.

func (t *Tab) RequestBodies(ctx context.Context, seq int) (RequestDetail, error)

RequestBodies is Request with the bodies in the user’s browser too, for a site the user trusts (docs/design/browser-automation.md, A4): what was sent comes with the values of credential-named fields removed, or not at all when it isn’t JSON or a form.

func (t *Tab) Routes() []RouteInfo

Routes lists the tab’s routes, oldest first.

func (t *Tab) Screenshot(ctx context.Context, o ScreenshotOptions) (Image, error)

Screenshot captures the tab’s page as a PNG. The image is the page’s and untrusted.

func (t *Tab) Scroll(ctx context.Context, ref string, dx, dy float64) error

Scroll scrolls by dx, dy CSS pixels. With a ref it turns the mouse wheel over that element, scrolled into view first, which scrolls what a person’s wheel would: the element, or what holds it once it can go no further. With no ref it scrolls the page itself, as its scrollbar would, whatever is under the middle of the screen. It waits for the scrolling to stop.

func (t *Tab) Select(ctx context.Context, ref string, values []string) ([]string, error)

Select chooses the options of the <select> ref names whose value or visible text is among values, and only those, and returns the texts of the options now selected.

func (t *Tab) SetCookie(ctx context.Context, c Cookie) error

SetCookie sets a cookie for the page’s URL, or for c.Domain and c.Path if set.

func (t *Tab) SetStorage(ctx context.Context, kind StorageKind, key, value string) error

SetStorage sets key to value in the page’s local or session storage.

func (t *Tab) Shared(ctx context.Context) (bool, error)

Shared reports whether the user shared the tab with zelk, in the user’s browser; false in zelk’s own.

func (t *Tab) Snapshot(ctx context.Context, o SnapshotOptions) (Snapshot, error)

Snapshot returns the outline of the tab’s page, with its iframes, same-site or not, in place.

func (t *Tab) StartCoverage(ctx context.Context) (*Coverage, error)

StartCoverage starts recording which of the page’s JavaScript runs and which of its CSS rules apply. Load or use the page, then Stop. Iframes from other sites aren’t covered. In the user’s browser only CSS is recorded (CoverageReport.CSSOnly).

func (t *Tab) StartProfile(ctx context.Context) (*Profile, error)

StartProfile starts sampling the page’s JavaScript. Iframes from other sites run in processes of their own and aren’t sampled.

func (t *Tab) StartTrace(ctx context.Context) (*Trace, error)

StartTrace starts recording a performance trace of the tab. Reload or act on the page, then Stop. A browser records one trace at a time.

func (t *Tab) Storage(ctx context.Context, kind StorageKind) (map[string]string, error)

Storage returns the page’s local or session storage, for its own origin. The values come from the page and are untrusted.

func (t *Tab) Upload(ctx context.Context, ref string, paths []string) error

Upload sets the files of the file input ref names. paths must be absolute and readable by the browser: in a sandbox, inside its data directory.

func (t *Tab) Wait(ctx context.Context, c Condition) error

Wait waits until c holds, as long as ctx allows. A deadline that ends it first gives a *WaitError; a dialog that opens a *DialogError.

func (t *Tab) Watch(ctx context.Context, session string, o WatchOptions) (WatchInfo, error)

Watch installs a watch on the tab for session: its script runs now and again on each document the tab loads on the same site, and each value it passes to notify wakes the session (docs/design/browser-automation.md, A2). It ends on Once’s first wake, Unwatch, the tab closing or leaving the site. In the user’s browser a watch outlives the connection and zelk itself: Linked installs it again.

type TabInfo struct {
ID int
URL string
Title string
// Shared, in the user's browser, says the user shared the tab: zelk
// didn't open it, so closing it lets it go and it stays open.
Shared bool
}

TabInfo describes a tab: its number, address and title.

type Trace struct {
// contains filtered or unexported fields
}

Trace is a performance trace being recorded in a tab.

func (tr *Trace) Stop(ctx context.Context) (TraceSummary, error)

Stop ends the trace, writes it to a file in the browser’s captures directory, and sums it up.

type TraceSummary struct {
// Path is the trace file, which Chrome's DevTools can open.
Path string
// Duration is how long the trace ran.
Duration time.Duration
// Navigated reports that the page loaded during the trace: FCP and
// LCP are measured from its last load, and are zero without one.
Navigated bool
FCP, LCP time.Duration
// LCPType is what the largest paint was, image or text; LCPSize its
// area in CSS pixels.
LCPType string
LCPSize int
// CLS is cumulative layout shift; Shifts counts the shifts.
CLS float64
Shifts int
// TBT is total blocking time after FCP.
TBT time.Duration
// INP is interaction to next paint over the interactions in the
// trace, zero with none.
INP time.Duration
Interactions int
// LongTasks are the longest tasks over 50 ms on the page's main
// thread; LongTaskCount counts them all.
LongTasks []LongTask
LongTaskCount int
// Scripts are the scripts that ran longest on the main thread.
Scripts []ScriptTime
// Incomplete reports a trace cut off at the capture bound, or that
// Chrome lost events of.
Incomplete bool
}

TraceSummary is what a trace says about the page’s performance. Its URLs come from the page and are untrusted.

type Transport interface {
// ReadMessage returns the browser's next message; io.EOF means its
// end closed between messages.
ReadMessage() ([]byte, error)
// WriteMessage sends one message.
WriteMessage(msg []byte) error
// Close ends the transport both ways.
Close() error
}

Transport carries whole CDP messages between zelk and a browser it didn’t start, such as the WebSocket from zelk’s extension in the user’s browser. Its methods follow the rules of a connection’s transport: one reader, one writer, and a Close, called once, that ends a read or write in progress.

type Trust interface {
// Sites returns the trusted sites.
Sites() ([]string, error)
// Revoke ends the trust in site.
Revoke(site string) error
}

Trust is the host’s list of the sites the user trusted their browser’s tools on, which it keeps with the user’s rules (docs/design/browser-automation.md, A5).

type Version struct {
Product string `json:"product"`
Protocol string `json:"protocolVersion"`
Revision string `json:"revision"`
// UserAgent is the browser's own user agent.
UserAgent string `json:"userAgent"`
}

Version is the browser’s own account of itself.

type Violation struct {
// Rule is axe's ID for it.
Rule string
// Impact is minor, moderate, serious or critical.
Impact string
// Help says what the rule asks for; HelpURL explains it.
Help, HelpURL string
Tags []string
// Count is how many elements fail it; Nodes lists the first ones.
Count int
Nodes []AuditNode
}

Violation is a rule some elements fail.

type WaitError struct {
Condition string
Saw string
Err error
}

WaitError is a wait that ended before its condition held: it says what it last saw.

func (e *WaitError) Error() string
func (e *WaitError) Unwrap() error
type Wake struct {
Watch string
Session string
Tab int
Site string
At time.Time
// Since is the watch creation instant, retained across reconnects for source identity.
Since time.Time
// Value is the JSON notify was given, cut to 2,000 bytes; "" for an
// end.
Value string
// Folded counts the values this one replaced, which came sooner than
// the watch's interval allowed.
Folded int
// Ended says why the watch ended; "" while it runs.
Ended string
// Last says this value's wake ended the watch, as Once asks.
Last bool
// Gaps are the times since its last wake that it wasn't running, as
// while the user's stop paused it or zelk was closed: changes then
// went unseen, and its script started over after each.
Gaps []Gap
}

Wake is a watch’s word to the session that made it: a value its script passed to notify, or that it ended. The host records it in the source inbox; admission wakes an idle session.

func (w Wake) SourceID() string

SourceID returns the source identity carried from the watch’s creation.

func (w Wake) Text() string

Text is the wake as the model reads it, the page’s value framed as untrusted data.

type WatchInfo struct {
ID string
Session string
Tab int
// Site is the registrable domain the watch stays on.
Site string
Since time.Time
// Wakes counts the wakes it sent since it was made, across
// connections and zelks.
Wakes int
Once bool
// Running says it runs in the browser now; a kept watch that doesn't
// is installed again when the session resumes (Linked.Rewatch).
Running bool
// WakeError is why its last wake couldn't be delivered, while zelk
// tries it again; "" once it is.
WakeError string
}

WatchInfo describes a watch.

func (w WatchInfo) SourceID() string

SourceID identifies the watch’s source permanently within its session. It is stable across reconnections and distinct when a display ID is reused later.

type WatchOptions struct {
// Script is the body of a function given notify(value); it sets up
// what to watch (a MutationObserver, the page's own feed) and
// returns. It runs in an isolated world of its own: it sees the DOM,
// not the page's JavaScript objects, and the page can't see it.
Script string
// Once ends the watch after its first wake.
Once bool
// MinInterval is the least time between wakes: those sooner are held,
// and the latest goes when it ends. DefaultWatchInterval if 0.
MinInterval time.Duration
}

WatchOptions is what a watch runs and how often it may wake.

type WatchSources interface {
Start(ctx context.Context, watch WatchInfo) error
End(ctx context.Context, watch WatchInfo) error
}

WatchSources records a watch’s source before observation and ends it on an explicit stop. Start must be idempotent across reconnection; End must record a quiet terminal occurrence without requiring the session lease. A terminal Wake (Last or Ended) itself ends the source, so End is not called for it. Implementations must be safe for concurrent use and honor cancellation.