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
- Variables
- func AcceptLanguages(lang string) string
- func Args(profileDir string, opts Options) []string
- func DefaultDownloadsDir(home string) string
- func PageLang(lang string) string
- func SanitizeFilename(name string) string
- func SaveProfileState(ctx context.Context, opts Options) (storagestate.State, error)
- type Browser
- type Device
- type Dialog
- type Download
- type Downloads
- type Emulation
- type Frame
- type History
- type Manager
- func (m *Manager) Active(ctx context.Context) (*Tab, error)
- func (m *Manager) Browser() *Browser
- func (m *Manager) Close() error
- func (m *Manager) CloseTab(ctx context.Context, id string) error
- func (m *Manager) Downloads() *Downloads
- func (m *Manager) Emulation() Emulation
- func (m *Manager) NewTab(ctx context.Context, url string) (*Tab, error)
- func (m *Manager) Page(ctx context.Context) (*Tab, error)
- func (m *Manager) ProfileName() string
- func (m *Manager) ReapplyScreen(ctx context.Context) error
- func (m *Manager) SaveState(ctx context.Context) (storagestate.State, error)
- func (m *Manager) SetEmulation(ctx context.Context, e Emulation) error
- func (m *Manager) SwitchTab(ctx context.Context, id string) (*Tab, error)
- func (m *Manager) TabEvents() (opened []*Tab, closed []string)
- func (m *Manager) Tabs() []*Tab
- func (m *Manager) WaitNewTab(ctx context.Context, d time.Duration) bool
- type NavigateResult
- type NetworkProfile
- type Options
- type Tab
- func (t *Tab) BringToFront(ctx context.Context) error
- func (t *Tab) Closed() bool
- func (t *Tab) DialogSignal() <-chan struct{}
- func (t *Tab) DocGen() int
- func (t *Tab) DrainNotices() []string
- func (t *Tab) EnsureFront(ctx context.Context) error
- func (t *Tab) EvalJSON(ctx context.Context, expr string, out any) error
- func (t *Tab) EvalWorld(ctx context.Context, s *cdp.Session, expr string, out any) error
- func (t *Tab) FrameBySession(id string) *Frame
- func (t *Tab) Frames() []*Frame
- func (t *Tab) GoHistory(ctx context.Context, h History, loadTimeout time.Duration) (NavigateResult, error)
- func (t *Tab) HandleDialog(ctx context.Context, accept bool, text string) (*Dialog, error)
- func (t *Tab) Loading() (bool, <-chan struct{})
- func (t *Tab) Location(ctx context.Context) (url, title string, err error)
- func (t *Tab) MainFrame() cdproto.FrameID
- func (t *Tab) Navigate(ctx context.Context, url string, loadTimeout time.Duration) (NavigateResult, error)
- func (t *Tab) Notice(s string)
- func (t *Tab) OpenDialog() *Dialog
- func (t *Tab) RequestBody(ctx context.Context, r observe.Request) ([]byte, error)
- func (t *Tab) ResponseBody(ctx context.Context, r observe.Request) ([]byte, error)
- func (t *Tab) Screenshot(ctx context.Context, clip *page.Viewport, hires bool) (data []byte, mime string, err error)
- func (t *Tab) SessionByID(id string) *cdp.Session
- func (t *Tab) SignInOpen() bool
- func (t *Tab) TakeFileChooser() int64
- func (t *Tab) Title() string
- func (t *Tab) URL() string
- func (t *Tab) Visible(ctx context.Context) bool
- func (t *Tab) World(ctx context.Context, s *cdp.Session, frame cdproto.FrameID) (runtime.ExecutionContextID, error)
Constants ¶
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 ¶
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.
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.
ErrNavigation is wrapped by navigation failures reported by the browser (DNS, refused, ...).
var ErrNoDialog = errors.New("no dialog is open")
ErrNoDialog is returned when there is no JavaScript dialog to answer.
var ErrNoHistory = errors.New("no history entry in that direction")
ErrNoHistory is returned when there is no entry to go back or forward to.
var ErrNoTab = errors.New("no such tab")
ErrNoTab is returned for an unknown tab id.
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).
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 ¶
AcceptLanguages is the Accept-Language list for a page language: "pt-BR" → "pt-BR,pt", "en-US" → "en-US,en".
func DefaultDownloadsDir ¶
DefaultDownloadsDir is ~/Downloads/daisybell.
func SanitizeFilename ¶
SanitizeFilename keeps only the base name and replaces characters that are unsafe in file names on any platform.
func SaveProfileState ¶
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 (*Browser) Close ¶
Close asks Chrome to exit, kills it if it does not within a few seconds, and releases the 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).
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 ¶
NewDownloads tracks downloads saved into dir.
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.
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 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 ¶
NewManager returns a manager; nothing is launched until Active is called.
func (*Manager) Active ¶
Active returns the tab the agent is driving, launching the browser if needed.
func (*Manager) Close ¶
Close shuts the browser down, if it was launched, and drops the session's mocks.
func (*Manager) NewTab ¶
NewTab opens a tab at url and waits until it is attached. It does not change the active tab.
func (*Manager) ProfileName ¶
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 ¶
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 ¶
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 ¶
SetEmulation applies e to every open tab (and to tabs opened later). The zero value resets.
func (*Manager) SwitchTab ¶
SwitchTab makes the tab with the short id active and brings it to the front.
type NavigateResult ¶
type NavigateResult struct {
// before the timeout; the page may still be usable.
Loaded bool
// 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 ¶
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 ¶
BringToFront shows the tab in its window.
func (*Tab) DialogSignal ¶
func (t *Tab) DialogSignal() <-chan struct{}
DialogSignal returns a channel closed when the next dialog opens.
func (*Tab) DocGen ¶
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 ¶
DrainNotices returns and clears the queued notices.
func (*Tab) EnsureFront ¶
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 ¶
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 ¶
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 ¶
FrameBySession returns the out-of-process frame behind a session id, or nil for the tab.
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 ¶
HandleDialog accepts or dismisses the open dialog; text answers a prompt.
func (*Tab) Loading ¶
Loading reports whether the main frame is loading, and a channel closed when it stops.
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) OpenDialog ¶
OpenDialog returns the open confirm/prompt dialog, or nil.
func (*Tab) RequestBody ¶
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 ¶
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 ¶
SessionByID returns the tab session or one of its iframe sessions.
func (*Tab) SignInOpen ¶
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 ¶
TakeFileChooser returns the file input whose native chooser was intercepted since the last call (0 if none).
func (*Tab) Visible ¶
Visible reports whether the tab is the one its window shows (document.visibilityState). Errors and timeouts count as not visible.
func (*Tab) World ¶
func (t *Tab) World(ctx context.Context, s *cdp.Session, frame cdproto.FrameID) (runtime.ExecutionContextID, error)
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.
Source Files
¶
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. |