perceive

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: 22 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 perceive turns a page into a compact, model-friendly outline: landmarks, headings and interactive elements with stable refs (e12). The engine joins the Chrome accessibility tree (semantics, names, states; flattens open and closed shadow DOM) with DOMSnapshot layout (visibility, viewport position, listener-only clickables) by backendNodeId.

Fetching (take.go) is separated from the pure building/formatting (outline.go) so the latter is unit-tested without a browser. See docs/spikes/snapshot.md for the measurements behind it.

Index

Constants

View Source
const Hidden = "(hidden)"

Hidden is what replaces a redacted value or text.

View Source
const OverlayTag = "daisybell-cockpit"

OverlayTag is the host element of the Cockpit's in-page overlay (ghost cursor, caption, pill, take-over banner). It is Daisybell's own UI, not the page: perception and hit testing ignore it.

View Source
const ReadPageSize = 3000

ReadPageSize is how many characters one page of read text holds (≈ 750 tokens).

Variables

This section is empty.

Functions

func CleanName

func CleanName(s string) string

CleanName is an accessible name as people read it: icon-font glyphs (private-use code points, `" Login"`) dropped and whitespace trimmed. The feed and the replay show names this way.

func CleanText

func CleanText(s string) string

CleanText normalizes innerText: trims lines, collapses runs of blank lines and spaces.

func Fetch

func Fetch(ctx context.Context, src Source) (*Tree, *Layout, error)

Fetch reads the stitched accessibility tree and layout of the main session and every out-of-process iframe (parents before children; frames whose parent is gone are skipped).

func FieldValues

func FieldValues(ctx context.Context, src Source) (map[string]bool, error)

FieldValues reads the values of every input, textarea and contenteditable of the page behind src (its frames included), for a handoff's baseline and its result. The values stay on the server.

func FindText

func FindText(text, query string, limit int) (passages []Passage, total int, kind Match)

FindText returns up to limit passages (~240 chars) around case-insensitive matches of query: the exact phrase; failing that, passages holding all of its words (on one line or within wordWindow); failing that, passages with some of its words, most words first. A near-miss query ("Releases Latest" for "Releases · v0.19.1 · Latest") still finds its passage, and the Match tells the caller which it was.

func HidesValue

func HidesValue(f FieldInfo, label string, typed map[string]bool) bool

HidesValue reports whether a field's value must not be shown. label is the field's accessible name (the DOM snapshot has no label text). typed are the values the human typed in a handoff.

func Quote

func Quote(s string, max int) string

Quote is how names are quoted everywhere the AI reads them (outline, result lines): whitespace (no-break spaces included) collapsed, truncated to max runes, inner double quotes made single.

func Scrub

func Scrub(s string, typed map[string]bool) string

Scrub replaces in s every typed value of minScrub runes or more with Hidden.

func SnapshotScale

func SnapshotScale(snap *domsnapshot.CaptureSnapshotResult, cssContentWidth float64) float64

SnapshotScale returns the DOMSnapshot units per CSS pixel of a capture, comparing the top document's content width (snapshot units) with the CSS content width from Page.getLayoutMetrics. It is 1 unless the two clearly differ (device scale factor 2 on a Retina display).

func TextPage

func TextPage(text string, n, size int) (string, int)

TextPage returns page n (1-based) of text, cut at line or word boundaries, and the number of pages.

func TypedNow

func TypedNow(typed, baseline map[string]bool, l *Layout) map[string]bool

TypedNow is the set of values to treat as typed by the human: typed (finished handoffs) plus, while a handoff is open (baseline non-nil: the field values at its start), every field value of the layout that was not there when it began.

Types

type AXNode

type AXNode struct {
	ID    string
	Role  string
	Name  string
	Value string
	// Description is the accessible description (title attribute, aria-describedby).
	Description string
	Ignored     bool
	Backend     int64
	// Frame is the ref namespace of the node: "" for the tab's session, the session id of an
	// out-of-process iframe otherwise. backendNodeIds are only unique within one session.
	Frame    string
	Props    map[string]string
	Children []string
}

AXNode is the subset of an accessibility node the outline needs.

func (*AXNode) Key

func (n *AXNode) Key() NodeKey

Key returns the node's identity for refs and layout.

type Box

type Box struct{ X, Y, W, H float64 }

Box is a rectangle in top-level document coordinates (CSS pixels).

func RedactBoxes

func RedactBoxes(l *Layout, label func(NodeKey) string, typed map[string]bool) []Box

RedactBoxes returns the boxes (top-level document CSS px) of the fields whose value is hidden and not empty: screenshot paints over them. label gives a field's accessible name.

func (Box) Empty

func (b Box) Empty() bool

Empty reports a zero-area box.

type Candidate

type Candidate struct {
	Key     NodeKey
	Role    string
	Name    string
	Context string
	FP      string
}

Candidate is a node the outline wants a ref for.

type Counter

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

Counter numbers refs. Tabs share one so a ref is unique across tabs and a ref from another tab can never alias an element of the current one.

type Diff

type Diff struct {
	URL, Title   string
	TitleChanged bool
	Added        []string
	Removed      []string
	Changed      []string
	// Grew reports content that appeared outside the outline (infinite scroll, "load more").
	Grew []string
	// LeftView counts controls that are still on the page but scrolled out of the band.
	LeftView int
	// Footer is the new viewport footer when it changed ("" otherwise).
	Footer string
}

Diff is what changed between two outlines of the same document.

func Compare

func Compare(prev, cur *Snapshot) Diff

Compare diffs two snapshots of the same document. Controls are matched by ref (a changed line with the same ref is "~"), other lines by text.

func (Diff) Empty

func (d Diff) Empty() bool

Empty reports that nothing visible changed.

func (Diff) Format

func (d Diff) Format() string

Format renders the diff; "" when empty.

type FieldInfo

type FieldInfo struct {
	Field credential.Field
	Value string
}

FieldInfo is a form field of the page as redaction sees it: its description for the detector and its current value (kept on the server: it is never printed when the field is redacted).

type Frame

type Frame struct {
	// Key is the ref namespace of the frame's nodes (its session id).
	Key     string
	Session cdproto.Session
	// ID is the frame id (equal to the iframe target id).
	ID cdproto.FrameID
	// ParentKey/Parent identify the session whose document holds the <iframe> element.
	ParentKey string
	Parent    cdproto.Session
}

Frame is an out-of-process iframe with its own CDP session.

type Layout

type Layout struct {
	Boxes     map[NodeKey]Box
	Clickable map[NodeKey]bool
	// Draggable and Hover are role-less targets too: draggable="true" elements and elements that
	// react to the pointer hovering them (see targets.go).
	Draggable map[NodeKey]bool
	Hover     map[NodeKey]bool
	// Excluded are Daisybell's own elements (the Cockpit overlay host): Fetch prunes them, and
	// everything below them, from the tree.
	Excluded map[NodeKey]bool
	// Concealed are nodes a person can't see although they are laid out: transparent, clipped,
	// tiny, off-screen or the color of their background (see conceal.go).
	Concealed map[NodeKey]bool
	// Fields are the input, textarea and contenteditable elements with their attributes and
	// current value (for redaction, see redact.go; values never reach the outline of a redacted
	// field).
	Fields   map[NodeKey]FieldInfo
	Viewport Box
	// Scale is how many DOMSnapshot units make one CSS pixel. DOMSnapshot layout bounds are in
	// device pixels when the device scale factor is not 1 (a visible window on a HiDPI screen),
	// while everything else here is CSS pixels. 0 means 1.
	Scale float64
}

Layout is what the outline needs from DOMSnapshot: element boxes and listener-only clickables, plus the current viewport.

func FetchLayout

func FetchLayout(ctx context.Context, s cdproto.Session) (*Layout, error)

FetchLayout captures DOMSnapshot layout and the visual viewport of the tab's session.

func LayoutFromSnapshot

func LayoutFromSnapshot(snap *domsnapshot.CaptureSnapshotResult, viewport Box, scale float64) *Layout

LayoutFromSnapshot indexes a DOMSnapshot.captureSnapshot result of the tab's own session.

func NewLayout

func NewLayout(viewport Box) *Layout

NewLayout returns an empty layout for the given viewport.

func (*Layout) Add

func (l *Layout) Add(snap *domsnapshot.CaptureSnapshotResult, frame string, origin Box)

Add indexes a captureSnapshot result taken in the session namespaced by frame, whose top-level document starts at origin (top-level document coordinates). Boxes of nested same-process documents are translated using their owner element's box.

func (*Layout) Values

func (l *Layout) Values() map[string]bool

Values lists the non-empty values of the layout's fields (a handoff's baseline).

type Line

type Line struct {
	Depth int
	Text  string
	// Ref and Key are set on control lines, with the control's role and accessible name.
	Ref        string
	Key        NodeKey
	Role, Name string
	// Container lines end with ":" and introduce indented content.
	Container bool
	// contains filtered or unexported fields
}

Line is one outline line.

type Match

type Match int

Match says how FindText found its passages.

const (
	// MatchNone: nothing found.
	MatchNone Match = iota
	// MatchExact: the query as a phrase.
	MatchExact
	// MatchAllWords: every word of the query on one line or close together.
	MatchAllWords
	// MatchSomeWords: some of the words (the best passages first); neither of the above found.
	MatchSomeWords
)

type NodeKey

type NodeKey struct {
	Frame   string
	Backend int64
}

NodeKey identifies a DOM node across frames: backendNodeIds are unique per CDP session only, so out-of-process iframes (their own sessions) are namespaced by Frame.

type Options

type Options struct {
	// Full includes the whole page; otherwise only the viewport plus a margin of 25% of its
	// height above and below, with counts of what was left out.
	Full bool
	// Text includes short standalone text (prices, status lines). Long paragraphs are never
	// included; they belong to the read tool.
	Text bool
	// MaxLines caps the output (0 means 300).
	MaxLines int
	// Scope restricts the outline to one subtree (implies Full).
	Scope Scope
	// Unfold keeps every line: no run of rows, list items or alike controls is folded. Searches
	// over the outline (snapshot find=, flows) need every ref; scoped outlines are never folded.
	Unfold bool
	// Typed are the values the human typed during a handoff: never shown back (redact.go).
	Typed map[string]bool
	// Baseline is set while a handoff is open: the field values at its start. Any other value
	// in a field is the human's (TypedNow).
	Baseline map[string]bool
}

Options tunes Build.

type Passage

type Passage struct {
	Page int
	// Offset is the match's position in the text, in characters (runes).
	Offset int
	Text   string
}

Passage is a match of a query in the text.

type RefInfo

type RefInfo struct {
	Ref  string
	Key  NodeKey
	Role string
	Name string
	// Context is the row or landmark the node was found in (for messages like
	// `button "Edit" in row "Invoice #12"`).
	Context string
	// contains filtered or unexported fields
}

RefInfo is what Daisybell knows about a ref's node.

func (RefInfo) Occurrence

func (i RefInfo) Occurrence() int

Occurrence is the node's 1-based position among the document's nodes with the same role, name and context (0 when unknown). Saved flows use it to tell identical buttons apart.

type Refs

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

Refs maps short refs (e1, e2, …) to DOM nodes. Refs live only in Go — nothing is written into the page, so pages cannot see or forge them.

Identity is the node key (session namespace + backendNodeId), so a node keeps its ref for as long as it lives. When a framework re-renders and replaces nodes, the new node inherits the ref of the vanished node with the same fingerprint (role, name, row/landmark context and occurrence index), so refs survive re-renders. Numbers are never reused within a Refs, so a ref from a previous page can never silently point at something else.

func NewRefs

func NewRefs() *Refs

NewRefs returns an empty ref table with its own counter.

func NewRefsWith

func NewRefsWith(c *Counter) *Refs

NewRefsWith returns an empty ref table numbering refs with c.

func (*Refs) Assign

func (r *Refs) Assign(cands []Candidate, live func(NodeKey) bool) []string

Assign returns the refs of cands (same order). live reports whether a key still exists in the current document; refs of dead nodes are rebound to candidates with the same fingerprint.

func (*Refs) Len

func (r *Refs) Len() int

Len is the number of live refs.

func (*Refs) Lookup

func (r *Refs) Lookup(ref string) (RefInfo, bool)

Lookup resolves a ref.

func (*Refs) RefOf

func (r *Refs) RefOf(key NodeKey) (string, bool)

RefOf returns the ref already assigned to key, if any.

func (*Refs) Reset

func (r *Refs) Reset()

Reset forgets every ref (call on a new document). Numbers keep increasing so old refs never alias new elements.

func (*Refs) Stale

func (r *Refs) Stale(ref string) bool

Stale reports whether ref belonged to a previous document.

type Scope

type Scope struct {
	Key      *NodeKey
	Landmark string
}

Scope selects a subtree: a node (from a ref) or a landmark/container given as `main`, `nav`, `dialog`, `nav "Primary"` or just its name.

type Snapshot

type Snapshot struct {
	URL, Title   string
	Lines        []Line
	Above, Below int // interactive elements left out by the viewport filter
	Truncated    int // lines dropped by MaxLines
	// Boxes are the layout boxes (top-level document coordinates) of the refs in Lines.
	Boxes map[string]Box
	// ScopeMissing is set when the requested scope was not found.
	ScopeMissing bool
	// Scoped is set when the outline covers a subtree only.
	Scoped bool
	// Hidden are texts left out because a person can't see them (Layout.Concealed); callers scan
	// them for instructions aimed at AIs.
	Hidden []string
	// contains filtered or unexported fields
}

Snapshot is a built outline.

func Build

func Build(t *Tree, l *Layout, refs *Refs, opts Options) *Snapshot

Build produces the outline from an accessibility tree and layout.

func Take

func Take(ctx context.Context, src Source, refs *Refs, opts Options) (*Snapshot, error)

Take fetches and builds a snapshot of the page behind src.

func (*Snapshot) Body

func (s *Snapshot) Body() string

Body renders the outline lines with indentation.

func (*Snapshot) Footer

func (s *Snapshot) Footer() string

Footer is the viewport/truncation hint, or "".

func (*Snapshot) Format

func (s *Snapshot) Format() string

Format renders the whole snapshot for the model.

func (*Snapshot) Live

func (s *Snapshot) Live(key NodeKey) bool

Live reports whether key exists in the snapshot's document (in or out of view).

func (*Snapshot) Mark

func (s *Snapshot) Mark(tag func(role, name string) string)

Mark appends " "+tag to each control line for which tag(role, name) is not empty. The tools use it to flag controls whose click will ask the human ("[asks]"), so the AI can plan for it. A folded table or list line tags the kinds of the controls it hides (`button "Delete" ×12 [asks]`); runs of alike controls (days, page numbers) are not tagged.

func (*Snapshot) RowOf

func (s *Snapshot) RowOf(i int) string

RowOf is the header of the table row holding line i (`row "Invoice #12 · $30.00"`), or "".

type Source

type Source struct {
	Main   cdproto.Session
	Frames []Frame
	// World returns Daisybell's isolated world in the session with the given id ("" is Main), where
	// page scripts can't interfere with the helpers. Optional: the page's main world is used then.
	World func(ctx context.Context, session string) (runtime.ExecutionContextID, error)
}

Source is what a snapshot reads: the tab's session plus its out-of-process iframes.

type Tree

type Tree struct {
	Root  string
	Nodes map[string]*AXNode
}

Tree is an accessibility tree, possibly stitched from several frames.

func FetchTree

func FetchTree(ctx context.Context, s cdproto.Session, key string) (*Tree, error)

FetchTree fetches the accessibility tree of the main frame and of every same-process child frame, stitching child frames under their <iframe> nodes.

func TreeFromCDP

func TreeFromCDP(nodes []*accessibility.Node, prefix, frame string) *Tree

TreeFromCDP converts one frame's getFullAXTree result. prefix keeps node ids unique when several frames are stitched together; frame is the ref namespace (see AXNode.Frame).

func (*Tree) Graft

func (t *Tree) Graft(owner NodeKey, child *Tree) bool

Graft attaches child (another frame's tree) under the node of t whose DOM node is the frame owner (the <iframe> element). It reports whether the owner was found.

func (*Tree) Labels

func (t *Tree) Labels() func(NodeKey) string

Labels maps the tree's DOM nodes to their accessible names (for RedactBoxes).

func (*Tree) Prune

func (t *Tree) Prune(drop map[NodeKey]bool)

Prune removes the nodes whose DOM node is in drop, with their whole subtrees (for a shadow host, that includes its shadow tree), and unlinks them from their parents.

Jump to

Keyboard shortcuts

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