browser

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 35 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package browser launches and owns Daisybell's managed Chrome for Testing.

Invariant (SPEC §2.1): the only executable this package ever starts is the pinned Chrome for Testing installed under the browsers directory, always with a profile under Daisybell's own profiles directory. There is no attach mode and no system-browser fallback; launch refuses any executable outside the browsers directory.

Index

Constants

View Source
const WorldName = "__daisybell"

WorldName is the isolated JavaScript world Daisybell runs its helpers in. Isolated worlds share the DOM with the page but not its globals, so pages can neither see nor tamper with them.

Variables

View Source
var DefaultDenied = []string{"geolocation", "notifications", "camera", "microphone", "midi", "clipboard-read", "display-capture", "local-fonts", "window-management", "idle-detection", "storage-access"}

DefaultDenied are the permissions denied to every site unless --permissions grants them: their prompts are browser bubbles over the page.

View Source
var Devices = map[string]Device{
	"mobile": {Width: 390, Height: 844, Mobile: true,
		UserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"},
	"tablet": {Width: 820, Height: 1180, Mobile: true,
		UserAgent: "Mozilla/5.0 (iPad; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"},
}

Devices are the screen profiles emulate accepts.

View Source
var ErrNavigation = errors.New("navigation failed")

ErrNavigation is wrapped by navigation failures reported by the browser (DNS, refused, ...).

View Source
var ErrNoDialog = errors.New("no dialog is open")

ErrNoDialog is returned when there is no JavaScript dialog to answer.

View Source
var ErrNoHistory = errors.New("no history entry in that direction")

ErrNoHistory is returned when there is no entry to go back or forward to.

View Source
var ErrNoTab = errors.New("no such tab")

ErrNoTab is returned for an unknown tab id.

View Source
var LoadGrace = 1500 * time.Millisecond

LoadGrace is how long a navigation waits for the load event once DOMContentLoaded fired. Pages are usually usable at DOMContentLoaded; the load event can lag by seconds behind a slow image or ad (P2-10).

View Source
var NetworkProfiles = map[string]NetworkProfile{
	"offline": {Offline: true, Download: -1, Upload: -1},
	"slow3g":  {LatencyMs: 2000, Download: 50_000, Upload: 50_000},
	"fast3g":  {LatencyMs: 563, Download: 180_000, Upload: 84_375},
}

NetworkProfiles are the network conditions emulate accepts.

Functions

func AcceptLanguages

func AcceptLanguages(lang string) string

AcceptLanguages is the Accept-Language list for a page language: "pt-BR" → "pt-BR,pt", "en-US" → "en-US,en".

func Args

func Args(profileDir string, opts Options) []string

Args builds the Chrome command line (excluding the transport flag added per platform).

func DefaultDownloadsDir

func DefaultDownloadsDir(home string) string

DefaultDownloadsDir is ~/Downloads/daisybell.

func PageLang

func PageLang(lang string) string

PageLang returns the page language: lang, or en-US when empty.

func SanitizeFilename

func SanitizeFilename(name string) string

SanitizeFilename keeps only the base name and replaces characters that are unsafe in file names on any platform.

func SaveProfileState

func SaveProfileState(ctx context.Context, opts Options) (storagestate.State, error)

SaveProfileState launches the managed browser headless on profileDir (which must not be in use), captures its login state and closes it: `daisybell session save` when no conversation has the profile open.

Types

type Browser

type Browser struct {
	Conn    *cdp.Conn
	Profile *profile.Profile
	// Exe is the executable that was launched.
	Exe string
	// contains filtered or unexported fields
}

Browser is a running managed Chrome for Testing.

func Launch

func Launch(ctx context.Context, opts Options) (*Browser, error)

Launch installs (if needed) and starts the managed browser.

func (*Browser) Close

func (b *Browser) Close() error

Close asks Chrome to exit, kills it if it does not within a few seconds, and releases the profile.

func (*Browser) Done

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

Done is closed when the browser process exits.

func (*Browser) PageTarget

func (b *Browser) PageTarget(ctx context.Context) (*cdp.Session, *target.Info, error)

PageTarget attaches to the first regular page target, opening a new tab if there is none.

type Device

type Device struct {
	Width, Height int
	Mobile        bool
	UserAgent     string
}

Device is a screen profile.

type Dialog

type Dialog struct {
	Type          string
	Message       string
	DefaultPrompt string
	URL           string
	// contains filtered or unexported fields
}

Dialog is an open JavaScript dialog (alert, confirm, prompt, beforeunload).

func (*Dialog) Describe

func (d *Dialog) Describe() string

Describe is the one-line description used in responses.

type Download

type Download struct {
	Seq   int
	GUID  string
	Name  string // final file name
	URL   string
	Path  string // final path, set when completed
	State string // inProgress, completed, canceled
	Bytes int64
}

Download is a file the page downloaded into the downloads directory.

type Downloads

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

Downloads tracks downloads. Chrome saves each file under its GUID ("allowAndName"); when it completes it is renamed to a unique, sanitized version of the suggested name, so the reported path is exact and nothing outside the directory can be written.

func NewDownloads

func NewDownloads(dir string) *Downloads

NewDownloads tracks downloads saved into dir.

func (*Downloads) Begin

func (d *Downloads) Begin(guid, url, suggested string)

Begin records Browser.downloadWillBegin.

func (*Downloads) Dir

func (d *Downloads) Dir() string

Dir is the downloads directory.

func (*Downloads) Mark

func (d *Downloads) Mark() int

Mark returns the current sequence number.

func (*Downloads) Progress

func (d *Downloads) Progress(guid, state string, received float64) error

Progress records Browser.downloadProgress; on completion the file is moved to its final name.

func (*Downloads) Since

func (d *Downloads) Since(mark int) []Download

Since returns copies of the downloads started after mark.

type Emulation

type Emulation struct {
	Device    string // mobile, tablet, custom ("" none)
	Width     int    // CSS px
	Height    int    // CSS px
	Mobile    bool   // mobile viewport, touch, mobile user agent
	UserAgent string
	Network   string // a NetworkProfiles name ("" none)
}

Emulation is what the emulate tool (debug group) changed: a screen (device metrics, touch and user agent) and network conditions. The zero value is "no emulation". The manager applies it to every tab, including the ones opened later.

The device pixel ratio stays the screen's: with an emulated ratio, every screenshot (the recorder takes one per action) makes Chrome lay the page out at its physical size for the capture (a 390 px phone at 3x becomes 1170 px wide at 1x) and restore it afterwards, and input sent meanwhile lands at 1/ratio of its coordinates (measured: a click meant for 74,251 hit 25,84). The CSS viewport, touch and user agent are what responsive layouts depend on.

func (Emulation) IsZero

func (e Emulation) IsZero() bool

IsZero reports whether nothing is emulated.

type Frame

type Frame struct {
	ID      cdproto.FrameID // equals the iframe target id
	Session *cdp.Session
	// Parent is the session whose document contains the <iframe> element.
	Parent *cdp.Session
	URL    string
}

Frame is an out-of-process iframe attached through Target.setAutoAttach (flatten mode).

type History

type History string

History is a history navigation.

const (
	Back    History = "back"
	Forward History = "forward"
	Reload  History = "reload"
)

type Manager

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

Manager launches the browser lazily on first use, relaunches it if it died (for example because the human closed the window), and keeps the set of tabs: every page target, including popups and tabs opened by the page, is attached automatically. The agent's active tab only changes through SwitchTab (the tabs tool), never because a popup appeared.

func NewManager

func NewManager(opts Options) *Manager

NewManager returns a manager; nothing is launched until Active is called.

func (*Manager) Active

func (m *Manager) Active(ctx context.Context) (*Tab, error)

Active returns the tab the agent is driving, launching the browser if needed.

func (*Manager) Browser

func (m *Manager) Browser() *Browser

Browser returns the running browser or nil.

func (*Manager) Close

func (m *Manager) Close() error

Close shuts the browser down, if it was launched, and drops the session's mocks.

func (*Manager) CloseTab

func (m *Manager) CloseTab(ctx context.Context, id string) error

CloseTab closes the tab with the short id.

func (*Manager) Downloads

func (m *Manager) Downloads() *Downloads

Downloads returns the download tracker (nil before launch).

func (*Manager) Emulation

func (m *Manager) Emulation() Emulation

Emulation returns what is emulated now.

func (*Manager) NewTab

func (m *Manager) NewTab(ctx context.Context, url string) (*Tab, error)

NewTab opens a tab at url and waits until it is attached. It does not change the active tab.

func (*Manager) Page

func (m *Manager) Page(ctx context.Context) (*Tab, error)

Page returns the active tab (kept for callers that only need one page).

func (*Manager) ProfileName

func (m *Manager) ProfileName() string

ProfileName is the name of the profile in use: the --profile name, "default", or "" for a --profile-dir outside the profiles directory. Per-profile data (site maps) keys on it. An ephemeral profile (second instance, --session) still reports the name it stands in for.

func (*Manager) ReapplyScreen

func (m *Manager) ReapplyScreen(ctx context.Context) error

ReapplyScreen sets the current screen emulation again on every tab. A screenshot taken while the metrics change (the recorder pictures every action) makes Chrome restore the metrics it saw before the capture, undoing the change: the emulate tool re-applies when the viewport does not settle.

func (*Manager) SaveState

func (m *Manager) SaveState(ctx context.Context) (storagestate.State, error)

SaveState captures the running browser's login state (launching it on the profile if needed). The caller names it, stores it and shows only its Summary.

func (*Manager) SetEmulation

func (m *Manager) SetEmulation(ctx context.Context, e Emulation) error

SetEmulation applies e to every open tab (and to tabs opened later). The zero value resets.

func (*Manager) SwitchTab

func (m *Manager) SwitchTab(ctx context.Context, id string) (*Tab, error)

SwitchTab makes the tab with the short id active and brings it to the front.

func (*Manager) TabEvents

func (m *Manager) TabEvents() (opened []*Tab, closed []string)

TabEvents returns and clears tabs opened by pages and tabs closed since the last call.

func (*Manager) Tabs

func (m *Manager) Tabs() []*Tab

Tabs lists the open tabs in creation order.

func (*Manager) WaitNewTab

func (m *Manager) WaitNewTab(ctx context.Context, d time.Duration) bool

WaitNewTab waits up to d for a page-opened tab to be attached (popups attach asynchronously right after the click that opened them).

type NavigateResult struct {
	URL   string
	Title string
	// Loaded is false when neither the load event nor DOMContentLoaded (plus LoadGrace) came
	// before the timeout; the page may still be usable.
	Loaded bool
	// Interactive: the document was parsed (DOMContentLoaded) but its load event (images, ads,
	// slow third-party scripts) hadn't fired after LoadGrace. The caller's settle wait covers
	// the rest.
	Interactive bool
}

NavigateResult describes a finished navigation.

type NetworkProfile

type NetworkProfile struct {
	Offline          bool
	LatencyMs        float64
	Download, Upload float64
}

NetworkProfile is a DevTools throttling profile (bytes per second; -1 no limit).

type Options

type Options struct {
	// BrowsersDir holds installed Chrome for Testing versions (~/.daisybell/browsers).
	BrowsersDir string
	// ProfileDir is the user-data-dir. Empty means ProfilesDir/default with ephemeral fallback.
	ProfileDir string
	// ProfilesDir is the root for the default and ephemeral profiles (~/.daisybell/profiles).
	ProfilesDir string
	Headless    bool
	// WindowWidth/Height default to 1280x900.
	WindowWidth, WindowHeight int
	// ExtraArgs are appended to the Chrome command line (used by spikes for extensions).
	ExtraArgs []string
	// StartURL is opened in the initial tab (default about:blank).
	StartURL string
	// PageLang is the language pages see and the browser renders its own page UI in (file input
	// buttons, validation bubbles): Accept-Language, navigator.language, Intl. Default en-US,
	// whatever the OS locale, so the AI reads the same names on every machine. The Cockpit's
	// language is separate (--lang).
	PageLang string
	// Permissions are granted to every site (--permissions: geolocation, notifications, camera,
	// microphone…); every other permission prompt is denied without showing a bubble.
	Permissions []string
	// DownloadsDir receives files the pages download (default ~/Downloads/daisybell).
	DownloadsDir string
	// Progress receives download progress (stderr). May be nil.
	Progress io.Writer
	Logger   *slog.Logger

	// PrepareProfile runs on the profile directory before Chrome starts (the cockpit writes
	// preferences there). An error is logged, not fatal.
	PrepareProfile func(profileDir string) error
	// AllowURL, when set, restricts the main-frame navigations of every tab (--allowed-hosts):
	// other document requests are failed before they are sent, and popups on blocked URLs closed.
	AllowURL func(rawURL string) bool
	// Mocks are the fake responses of the mock tool (debug group; nil: none). Every tab pauses the
	// requests their patterns match; the manager clears them on Close.
	Mocks *mock.Registry
	// AfterLaunch runs once the CDP connection is up (the cockpit loads its extension). An error is
	// logged, not fatal: the browser stays usable without the cockpit.
	AfterLaunch func(ctx context.Context, b *Browser) error

	// ProfileName is the name of the profile in use (--profile; "default"; "" for a --profile-dir
	// outside the profiles directory). Informational: ProfileDir/ProfilesDir pick the directory.
	ProfileName string
	// Ephemeral launches on a fresh profile under ProfilesDir, deleted on exit (--session).
	Ephemeral bool
	// Session is a saved login state (--session) the manager restores into every launch, before
	// the first page loads. Its values are never logged.
	Session *storagestate.State
}

Options configures a launch.

type Tab

type Tab struct {
	// ID is the short id shown to the model (t1, t2...).
	ID       string
	TargetID target.ID
	Session  *cdp.Session
	Opener   target.ID
	Net      *observe.Net
	Console  *observe.Console
	// contains filtered or unexported fields
}

Tab is one browser tab Daisybell is attached to, with its out-of-process iframes.

func (*Tab) BringToFront

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

BringToFront shows the tab in its window.

func (*Tab) Closed

func (t *Tab) Closed() bool

Closed reports whether the target went away.

func (*Tab) DialogSignal

func (t *Tab) DialogSignal() <-chan struct{}

DialogSignal returns a channel closed when the next dialog opens.

func (*Tab) DocGen

func (t *Tab) DocGen() int

DocGen increases with every main-frame document (navigations started by Daisybell or by the page). Refs are only valid within one generation.

func (*Tab) DrainNotices

func (t *Tab) DrainNotices() []string

DrainNotices returns and clears the queued notices.

func (*Tab) EnsureFront

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

EnsureFront brings the tab to the foreground if it is hidden (for example because a popup opened on top of it). Hidden tabs do not produce frames, so pointer input would not reach out-of-process iframes and the human would not see what the agent does.

func (*Tab) EvalJSON

func (t *Tab) EvalJSON(ctx context.Context, expr string, out any) error

EvalJSON evaluates expr in the page's main world and decodes the JSON value into out. Use it only for tests and diagnostics: page globals can be tampered with; helpers belong in the isolated world (EvalWorld).

func (*Tab) EvalWorld

func (t *Tab) EvalWorld(ctx context.Context, s *cdp.Session, expr string, out any) error

EvalWorld evaluates expr in the isolated world of the session's main frame and decodes the JSON result into out (may be nil).

func (*Tab) FrameBySession

func (t *Tab) FrameBySession(id string) *Frame

FrameBySession returns the out-of-process frame behind a session id, or nil for the tab.

func (*Tab) Frames

func (t *Tab) Frames() []*Frame

Frames returns the out-of-process iframes currently attached.

func (*Tab) GoHistory

func (t *Tab) GoHistory(ctx context.Context, h History, loadTimeout time.Duration) (NavigateResult, error)

GoHistory goes back, forward or reloads, waiting for the load event.

func (*Tab) HandleDialog

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

HandleDialog accepts or dismisses the open dialog; text answers a prompt.

func (*Tab) Loading

func (t *Tab) Loading() (bool, <-chan struct{})

Loading reports whether the main frame is loading, and a channel closed when it stops.

func (*Tab) Location

func (t *Tab) Location(ctx context.Context) (url, title string, err error)

Location returns the current URL and title.

func (*Tab) MainFrame

func (t *Tab) MainFrame() cdproto.FrameID

MainFrame returns the id of the main frame.

func (*Tab) Navigate

func (t *Tab) Navigate(ctx context.Context, url string, loadTimeout time.Duration) (NavigateResult, error)

Navigate loads url and waits for the load event (up to loadTimeout).

func (*Tab) Notice

func (t *Tab) Notice(s string)

Notice queues a line to report in the next tool response.

func (*Tab) OpenDialog

func (t *Tab) OpenDialog() *Dialog

OpenDialog returns the open confirm/prompt dialog, or nil.

func (*Tab) RequestBody

func (t *Tab) RequestBody(ctx context.Context, r observe.Request) ([]byte, error)

RequestBody returns the body a request sent: what requestWillBeSent carried, else asked from the browser (large bodies). nil when it had none.

func (*Tab) ResponseBody

func (t *Tab) ResponseBody(ctx context.Context, r observe.Request) ([]byte, error)

ResponseBody asks the browser for a finished request's response body (it keeps the bodies of recent requests of the current documents only).

func (*Tab) Screenshot

func (t *Tab) Screenshot(ctx context.Context, clip *page.Viewport, hires bool) (data []byte, mime string, err error)

Screenshot captures the viewport, or clip (a region of the document in CSS pixels; may be nil). By default the image is a JPEG at CSS-pixel size: on a HiDPI screen a device-pixel capture is 4× the pixels (vision tokens) for no extra legibility. hires returns a lossless PNG at device resolution instead, for fine detail.

func (*Tab) SessionByID

func (t *Tab) SessionByID(id string) *cdp.Session

SessionByID returns the tab session or one of its iframe sessions.

func (*Tab) SignInOpen

func (t *Tab) SignInOpen() bool

SignInOpen reports whether the browser's HTTP sign-in dialog is probably open: a challenge was shown to the human and the page hasn't navigated since.

func (*Tab) TakeFileChooser

func (t *Tab) TakeFileChooser() int64

TakeFileChooser returns the file input whose native chooser was intercepted since the last call (0 if none).

func (*Tab) Title

func (t *Tab) Title() string

Title is the last known title.

func (*Tab) URL

func (t *Tab) URL() string

URL is the last known main-frame URL.

func (*Tab) Visible

func (t *Tab) Visible(ctx context.Context) bool

Visible reports whether the tab is the one its window shows (document.visibilityState). Errors and timeouts count as not visible.

func (*Tab) World

World returns the isolated-world execution context of frame in session s, creating it if the page has not reported one yet. frame "" means the session's main frame.

Directories

Path Synopsis
Package install downloads, verifies and installs the pinned Chrome for Testing build that Daisybell drives.
Package install downloads, verifies and installs the pinned Chrome for Testing build that Daisybell drives.
Package profile owns Daisybell's browser profile directories and guarantees that at most one Daisybell process uses a profile at a time.
Package profile owns Daisybell's browser profile directories and guarantees that at most one Daisybell process uses a profile at a time.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL