Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(snapshot): spend the token budget on what the agent can act on

Darshan Jainb41f361890f9
diff --git a/docs/reference/snapshot.md b/docs/reference/snapshot.md
index ca0006e0..597e0f2b 100644
--- a/docs/reference/snapshot.md
+++ b/docs/reference/snapshot.md
@@ -107,11 +107,25 @@ matching, so a `compact` snapshot leaves them exactly as capable as a JSON one.
## What `maxTokens` guarantees
-`maxTokens` is a ceiling, not a hint. The nodes returned are the longest prefix whose
-rendered output fits the budget in the format you asked for, so the response never exceeds
-what you asked for and stops one node short of it at worst. Measured across `compact`,
-`text`, `json` and `yaml` on a page of realistic interactive nodes, a budget that actually
-constrains the result delivers 87–100% of it.
+`maxTokens` is a ceiling, not a hint. The response never exceeds what you asked for, and
+nothing is left on the table: every node left out was too big for what remained. Measured
+across `compact`, `text`, `json` and `yaml` on a page of realistic interactive nodes, a
+budget that actually constrains the result delivers 87–100% of it.
+
+When the budget cannot fit the whole tree, it is spent on what the page can be **acted
+on** with before what it can be read with: interactive roles first, then headings, media
+and table cells, then everything else. Nodes are returned in document order, so the reply
+still reads like the page.
+
+This matters because document order is not value order. A page whose controls sit below
+its copy — a form under terms, a search box under a nav blurb, pagination under results —
+used to return a budget's worth of prose and no refs at all, which is a snapshot nothing
+can be done with. On a 71-node page with 9 controls at the end, budgets of 120, 200 and
+300 tokens each returned 0 of the 9; they now return all 9 in the same space.
+
+Refs are assigned after the budget is applied and cached for the tab, so every ref in a
+truncated snapshot resolves to the element it names — a truncated tree is fully
+actionable.
The cost is measured, not modelled: each node is charged the bytes its own format emits —
rendered for `compact` and `text`, marshalled for `json` and `yaml` — so a change to a
diff --git a/internal/bridge/observe/snapshot_budget_test.go b/internal/bridge/observe/snapshot_budget_test.go
index 8ade5f52..54d1be87 100644
--- a/internal/bridge/observe/snapshot_budget_test.go
+++ b/internal/bridge/observe/snapshot_budget_test.go
@@ -80,11 +80,18 @@ func renderedTokens(t *testing.T, nodes []A11yNode, format string) int {
// budget rather than a hint:
//
// 1. the output never exceeds it, and
-// 2. nothing is left on the table — the first node that was dropped would not have fit.
+// 2. nothing is left on the table — no node that was dropped would have fit.
//
// Property 2 is what a percentage floor cannot express. A shortfall is only legitimate
-// when the next node was too big for the remainder, and that is checkable exactly, so
+// when the dropped node was too big for the remainder, and that is checkable exactly, so
// there is no tolerance here to quietly widen until the current constants pass.
+//
+// It used to be phrased against nodes[:len(kept)+1], which reads the property off the
+// assumption that kept is a PREFIX of nodes. TruncateToTokens selects by budget tier
+// now, so kept is a subset and that index names an unrelated node — the check would
+// have gone on passing while testing nothing. Stated over the dropped set instead, it
+// is both correct for a subset and strictly stronger: every omission has to be
+// justified, not just the one at the boundary.
func TestTruncateToTokensDeliversTheBudgetItWasAsked(t *testing.T) {
nodes := budgetProbeNodes(40)
@@ -105,10 +112,20 @@ func TestTruncateToTokensDeliversTheBudgetItWasAsked(t *testing.T) {
}
if truncated {
- withNext := renderedTokens(t, nodes[:len(kept)+1], format)
- if withNext <= budget {
- t.Errorf("%s budget=%d stopped at %d/%d nodes (~%d tokens) although the next node would have fit in ~%d: the caller was short-changed",
- format, budget, len(kept), len(nodes), actual, withNext)
+ keptRefs := make(map[string]bool, len(kept))
+ for _, n := range kept {
+ keptRefs[n.Ref] = true
+ }
+ cost := nodeCost(format)
+ for _, n := range nodes {
+ if keptRefs[n.Ref] {
+ continue
+ }
+ if withNode := renderedTokens(t, append(append([]A11yNode{}, kept...), n), format); withNode <= budget {
+ t.Errorf("%s budget=%d kept %d/%d nodes (~%d tokens) but dropped %s:%s, which costs ~%d tokens and would have fit in ~%d: the caller was short-changed",
+ format, budget, len(kept), len(nodes), actual, n.Ref, n.Role, estimateTokens(cost(n)), withNode)
+ break
+ }
}
}
})
@@ -267,3 +284,142 @@ func TestNodeLayoutIsWrittenDownExactlyOnce(t *testing.T) {
})
}
}
+
+// pageShapedNodes is the layout the prefix allocator could not serve: a long run of
+// copy, then the controls. Terms above a signup form, a nav blurb above a search box,
+// results above pagination — the actionable part of a page is routinely the last part
+// of it.
+func pageShapedNodes(prose int) []A11yNode {
+ nodes := make([]A11yNode, 0, prose+6)
+ for i := 0; i < prose; i++ {
+ nodes = append(nodes,
+ A11yNode{Ref: fmt.Sprintf("h%d", i), Role: "heading", Name: fmt.Sprintf("Section %d", i)},
+ A11yNode{Ref: fmt.Sprintf("p%d", i), Role: "paragraph", Name: "Body copy the agent cannot act on, at some length."},
+ )
+ }
+ return append(nodes,
+ A11yNode{Ref: "c0", Role: "textbox", Name: "Email"},
+ A11yNode{Ref: "c1", Role: "textbox", Name: "Password"},
+ A11yNode{Ref: "c2", Role: "combobox", Name: "Plan"},
+ A11yNode{Ref: "c3", Role: "checkbox", Name: "I accept the terms"},
+ A11yNode{Ref: "c4", Role: "button", Name: "Create account"},
+ A11yNode{Ref: "c5", Role: "link", Name: "Need help?"},
+ )
+}
+
+// prefixToTokens is the allocator this replaced: the longest run of nodes from the
+// start that fits. Kept here so the improvement is measured against the real previous
+// behaviour rather than described.
+func prefixToTokens(nodes []A11yNode, maxTokens int, format string) []A11yNode {
+ cost := nodeCost(format)
+ used := 0
+ for i, n := range nodes {
+ used += cost(n)
+ if estimateTokens(used) > maxTokens {
+ return nodes[:i]
+ }
+ }
+ return nodes
+}
+
+func actionableCount(nodes []A11yNode) int {
+ n := 0
+ for _, node := range nodes {
+ if InteractiveRoles[node.Role] {
+ n++
+ }
+ }
+ return n
+}
+
+// The property the budget exists to protect: a snapshot the agent can still act on.
+//
+// A reply that spends its whole budget on prose is not a smaller answer, it is a
+// useless one — there is nothing in it to click. That is what the prefix allocator
+// returned on this shape, and on the real 71-node page it was measured against: 0 of 9
+// controls at budgets of 120, 200 and 300 tokens.
+//
+// Two things are asserted, both robust across formats. The allocator is never worse
+// than the prefix it replaced, and it never returns an unusable snapshot while a
+// control would have fit. How MANY controls survive is a function of the budget and
+// the format's per-node cost — yaml spends ~100 tokens on a single node — so that is
+// logged rather than asserted.
+func TestBudgetKeepsWhatTheAgentCanActOn(t *testing.T) {
+ nodes := pageShapedNodes(60)
+ total := actionableCount(nodes)
+
+ for _, format := range []string{"compact", "text", "json", "yaml"} {
+ for _, budget := range []int{120, 200, 300} {
+ t.Run(fmt.Sprintf("%s/%d", format, budget), func(t *testing.T) {
+ kept, truncated := TruncateToTokens(nodes, budget, format)
+ if !truncated {
+ t.Fatalf("budget=%d did not constrain a %d-node page; the test proves nothing", budget, len(nodes))
+ }
+
+ got := actionableCount(kept)
+ was := actionableCount(prefixToTokens(nodes, budget, format))
+ t.Logf("%-8s budget=%3d -> controls %d/%d (prefix allocator: %d/%d)", format, budget, got, total, was, total)
+
+ if got < was {
+ t.Errorf("%s budget=%d kept %d controls, fewer than the %d the prefix allocator kept: this must never be a regression",
+ format, budget, got, was)
+ }
+
+ // Does even one control fit on its own? Then returning none is a
+ // snapshot with nothing to act on, which is the whole defect.
+ cost := nodeCost(format)
+ fits := false
+ for _, n := range nodes {
+ if InteractiveRoles[n.Role] && estimateTokens(cost(n)) <= budget {
+ fits = true
+ break
+ }
+ }
+ if fits && got == 0 {
+ t.Errorf("%s budget=%d returned %d nodes and not one control, though a control fits in the budget: the reply cannot be acted on",
+ format, budget, len(kept))
+ }
+ })
+ }
+ }
+}
+
+// Selection reorders nothing. The reply has to read like the page, so an agent can
+// still reason about what sits above what.
+func TestBudgetKeepsDocumentOrder(t *testing.T) {
+ nodes := pageShapedNodes(40)
+ kept, truncated := TruncateToTokens(nodes, 200, "compact")
+ if !truncated {
+ t.Fatal("expected the budget to constrain this page")
+ }
+
+ position := make(map[string]int, len(nodes))
+ for i, n := range nodes {
+ position[n.Ref] = i
+ }
+ for i := 1; i < len(kept); i++ {
+ if position[kept[i-1].Ref] >= position[kept[i].Ref] {
+ t.Fatalf("kept[%d]=%s came after kept[%d]=%s in the page but before it in the reply",
+ i-1, kept[i-1].Ref, i, kept[i].Ref)
+ }
+ }
+}
+
+// A snapshot the budget never constrained must come back exactly as it was: same
+// nodes, same order, and truncated=false. Prioritising only ever decides between nodes
+// that were going to be dropped anyway.
+func TestBudgetLeavesAnUnconstrainedSnapshotAlone(t *testing.T) {
+ nodes := pageShapedNodes(5)
+ kept, truncated := TruncateToTokens(nodes, 100000, "compact")
+ if truncated {
+ t.Fatal("reported truncation for a snapshot that fit")
+ }
+ if len(kept) != len(nodes) {
+ t.Fatalf("kept %d of %d nodes although everything fit", len(kept), len(nodes))
+ }
+ for i := range nodes {
+ if kept[i].Ref != nodes[i].Ref {
+ t.Fatalf("node %d changed from %s to %s", i, nodes[i].Ref, kept[i].Ref)
+ }
+ }
+}
diff --git a/internal/bridge/observe/snapshot_format.go b/internal/bridge/observe/snapshot_format.go
index d4f77906..6df9f904 100644
--- a/internal/bridge/observe/snapshot_format.go
+++ b/internal/bridge/observe/snapshot_format.go
@@ -195,17 +195,86 @@ func renderedNodeCost(style nodeStyle) func(A11yNode) int {
}
}
-// TruncateToTokens keeps the longest prefix of nodes whose rendered output fits in
-// maxTokens. The budget is a ceiling, never a target to overshoot: it stops at the last
-// node that fits, so the only shortfall possible is the one node that did not.
+// Budget tiers, ordered by what an agent loses when the node is dropped.
+//
+// An agent reads a snapshot to decide what to DO next, and the only nodes it can
+// act on are the ones carrying an interactive role. Static text is orientation;
+// a button is the whole reason the snapshot was requested.
+const (
+ tierActionable = iota // roles the agent can click, type into or select
+ tierContext // headings, media, table cells: where it is on the page
+ tierRemainder // prose and containers
+)
+
+func budgetTier(n A11yNode) int {
+ switch {
+ case InteractiveRoles[n.Role]:
+ return tierActionable
+ case ContextRoles[n.Role]:
+ return tierContext
+ default:
+ return tierRemainder
+ }
+}
+
+// TruncateToTokens fits nodes into maxTokens, spending the budget on what the page
+// can be acted on with before what it can be read with.
+//
+// It used to keep the longest PREFIX that fit, which spends the budget in document
+// order. Document order is not value order. On any page whose controls sit below its
+// copy — a form under terms, a search box under a nav blurb, pagination under results
+// — the prefix is entirely prose and the reply contains no refs at all. Measured on a
+// 71-node page with 9 controls at the end, budgets of 120, 200 and 300 tokens each
+// returned 0 of the 9: a snapshot the agent cannot act on, produced precisely when the
+// budget made every token count.
+//
+// Nodes are selected by tier and emitted in document order, so the reply reads like
+// the page and not like a ranking. Both properties the prefix form guaranteed are
+// kept, and the second one strengthens:
+//
+// 1. the output never exceeds the budget, and
+// 2. nothing is left on the table — every node that was dropped was too big for
+// what remained, which now holds over the whole set rather than just the next
+// node along.
+//
+// An unconstrained snapshot is returned untouched, so this only ever decides between
+// nodes that were going to be lost anyway.
func TruncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNode, bool) {
cost := nodeCost(format)
+
+ costs := make([]int, len(nodes))
+ total := 0
+ for i, n := range nodes {
+ costs[i] = cost(n)
+ total += costs[i]
+ }
+ if estimateTokens(total) <= maxTokens {
+ return nodes, false
+ }
+
+ keep := make([]bool, len(nodes))
bytesUsed := 0
+ for tier := tierActionable; tier <= tierRemainder; tier++ {
+ for i, n := range nodes {
+ if keep[i] || budgetTier(n) != tier {
+ continue
+ }
+ // Skip rather than stop: one oversized node must not evict every
+ // smaller one behind it, which is how a single long label used to
+ // cost an agent the rest of the form.
+ if estimateTokens(bytesUsed+costs[i]) > maxTokens {
+ continue
+ }
+ keep[i] = true
+ bytesUsed += costs[i]
+ }
+ }
+
+ kept := make([]A11yNode, 0, len(nodes))
for i, n := range nodes {
- bytesUsed += cost(n)
- if estimateTokens(bytesUsed) > maxTokens {
- return nodes[:i], true
+ if keep[i] {
+ kept = append(kept, n)
}
}
- return nodes, false
+ return kept, true
}