Skip to content

Commit f69d049

Browse files
committed
improvement(desktop-browser): keep an element on the same ref across snapshots
1 parent c59e83f commit f69d049

4 files changed

Lines changed: 101 additions & 14 deletions

File tree

‎apps/desktop/src/main/browser-agent/driver.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3098,6 +3098,29 @@ describe('credential protection', () => {
30983098
})
30993099
})
31003100

3101+
it('accepts a later snapshot that keeps refs this scope issued for the same page', async () => {
3102+
const contents = await openPage()
3103+
const snapshot = (refIds: number[], nextElementId: number) => ({
3104+
url: 'https://example.com/',
3105+
title: 'Example',
3106+
outline: refIds.map((ref) => `- button "B${ref}" [ref=${ref}]`).join('\n'),
3107+
truncated: false,
3108+
refIds,
3109+
refLineIndexes: Object.fromEntries(refIds.map((ref, index) => [ref, index])),
3110+
nextElementId,
3111+
})
3112+
respondWith(contents, { collectSnapshot: snapshot([4, 5], 6) })
3113+
await driver.executeTool('chat-test', 'browser_snapshot', {})
3114+
respondWith(contents, { collectSnapshot: snapshot([4, 6], 7) })
3115+
3116+
const kept = await driver.executeTool('chat-test', 'browser_snapshot', {})
3117+
expect(kept).toMatchObject({ ok: true })
3118+
respondWith(contents, { collectSnapshot: snapshot([2], 7) })
3119+
3120+
const forged = await driver.executeTool('chat-test', 'browser_snapshot', {})
3121+
expect(forged).toMatchObject({ ok: false })
3122+
})
3123+
31013124
it.each([
31023125
['browser_snapshot', 'true'],
31033126
['browser_find', 'false'],
@@ -3125,7 +3148,7 @@ describe('credential protection', () => {
31253148
.mock.calls.some(
31263149
([expression]) =>
31273150
isPageCall(expression, 'collectSnapshot') &&
3128-
expression.includes(`.apply(null, [1,0,${markNew}])`)
3151+
expression.includes(`.apply(null, [1,0,${markNew},`)
31293152
)
31303153
).toBe(true)
31313154
const stale = await driver.executeTool('chat-test', 'browser_click', { elementId: 0 })

‎apps/desktop/src/main/browser-agent/driver.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,13 @@ function isBrowserWaitElementState(value: string): value is BrowserWaitElementSt
144144

145145
type PageExecutionTarget = WebContents | WebFrameMain
146146

147+
/** Identifies a frame across the separate WebFrameMain wrappers Electron may hand out for it. */
148+
function pageTargetKey(target: PageExecutionTarget): string {
149+
return 'routingId' in target
150+
? `frame:${target.processId}:${target.routingId}`
151+
: `contents:${target.id}`
152+
}
153+
147154
type BrowserActionOutcome = { status: 'pending' } | { status: 'acknowledged'; result: unknown }
148155

149156
type FormField =
@@ -326,6 +333,8 @@ interface DriverScopeState {
326333
snapshotTargets: Map<number, PageExecutionTarget>
327334
/** Monotonic ref floor shared by every frame in this browser scope. */
328335
nextElementRefId: number
336+
/** Every ref this scope issued and the frame it belongs to, so a later snapshot may reuse it there. */
337+
issuedRefTargets: Map<number, string>
329338
/** Invalidates captures that finish after a tab/navigation/timeout race. */
330339
snapshotCaptureEpoch: number
331340
/** Cancels a timed-out multi-step action before any later native dispatch. */
@@ -367,6 +376,7 @@ function createDriverScopeState(): DriverScopeState {
367376
snapshotTabId: null,
368377
snapshotTargets: new Map(),
369378
nextElementRefId: 0,
379+
issuedRefTargets: new Map(),
370380
snapshotCaptureEpoch: 0,
371381
toolExecutionEpoch: 0,
372382
}
@@ -2338,7 +2348,8 @@ async function readWholePageText(
23382348

23392349
function validateSnapshotRefs(
23402350
snapshot: Record<string, unknown>,
2341-
startingElementId: number
2351+
startingElementId: number,
2352+
issuedHere: (ref: number) => boolean
23422353
): { refs: number[]; nextElementId: number; lineIndexes: Map<number, number> } | null {
23432354
if (typeof snapshot.outline !== 'string' || snapshot.outline.length > 500_000) return null
23442355
if (!Array.isArray(snapshot.refIds) || snapshot.refIds.length > 300) return null
@@ -2362,7 +2373,7 @@ function validateSnapshotRefs(
23622373
if (
23632374
typeof value !== 'number' ||
23642375
!Number.isSafeInteger(value) ||
2365-
value < startingElementId ||
2376+
(value < startingElementId && !issuedHere(value)) ||
23662377
value >= nextElementId ||
23672378
unique.has(value)
23682379
) {
@@ -2436,7 +2447,7 @@ async function captureSnapshot(
24362447
await execInPage(
24372448
contents,
24382449
collectSnapshot,
2439-
[mainStartingElementId, elementId ?? null, markNew],
2450+
[mainStartingElementId, elementId ?? null, markNew, state.generation],
24402451
false,
24412452
notAfter
24422453
)
@@ -2451,7 +2462,11 @@ async function captureSnapshot(
24512462
) {
24522463
throw new ToolError('The page returned an incomplete snapshot. Try browser_snapshot again.')
24532464
}
2454-
const mainRefs = validateSnapshotRefs(mainSnapshot, mainStartingElementId)
2465+
const mainRefs = validateSnapshotRefs(
2466+
mainSnapshot,
2467+
mainStartingElementId,
2468+
(ref) => state.issuedRefTargets.get(ref) === pageTargetKey(contents)
2469+
)
24552470
if (!mainRefs) {
24562471
throw new ToolError('The page returned invalid element ids. Try browser_snapshot again.')
24572472
}
@@ -2493,7 +2508,7 @@ async function captureSnapshot(
24932508
const frameSnapshot = await execInPage(
24942509
frame,
24952510
collectSnapshot,
2496-
[frameStartingElementId, null, markNew],
2511+
[frameStartingElementId, null, markNew, state.generation],
24972512
false,
24982513
notAfter
24992514
)
@@ -2512,7 +2527,11 @@ async function captureSnapshot(
25122527
unreadableCrossOriginFrames++
25132528
continue
25142529
}
2515-
const frameRefs = validateSnapshotRefs(frameSnapshot, frameStartingElementId)
2530+
const frameRefs = validateSnapshotRefs(
2531+
frameSnapshot,
2532+
frameStartingElementId,
2533+
(ref) => state.issuedRefTargets.get(ref) === pageTargetKey(frame)
2534+
)
25162535
if (!frameRefs) {
25172536
unreadableCrossOriginFrames++
25182537
continue
@@ -2565,6 +2584,7 @@ async function captureSnapshot(
25652584
(targetLineIndexes.get(elementId) ?? Number.POSITIVE_INFINITY) < visibleOutlineLines.length
25662585
)
25672586
)
2587+
for (const [ref, target] of targets) state.issuedRefTargets.set(ref, pageTargetKey(target))
25682588
state.snapshotTabId = capturedTabId
25692589
return {
25702590
...omit(mainSnapshot, ['refIds', 'refLineIndexes', 'nextElementId']),

‎apps/desktop/src/main/browser-agent/page-functions.test.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -710,16 +710,41 @@ describe('collectSnapshot', () => {
710710
expect(clickElement(ref)).toMatchObject({ error: 'stale' })
711711
})
712712

713-
it('never recycles numeric refs across snapshots', () => {
713+
it('keeps an unchanged element on the same ref across snapshots', () => {
714+
document.body.innerHTML = '<button>Pins</button><button>Files</button>'
715+
for (const button of Array.from(document.querySelectorAll('button'))) visible(button)
716+
const first = outlineOf(collectSnapshot())
717+
const second = outlineOf(collectSnapshot())
718+
719+
expect(refFor(second, 'Pins')).toBe(refFor(first, 'Pins'))
720+
expect(refFor(second, 'Files')).toBe(refFor(first, 'Files'))
721+
expect(clickElement(refFor(first, 'Pins'))).toMatchObject({ dispatched: true })
722+
})
723+
724+
it('never gives a ref to a different element across snapshots', () => {
714725
document.body.innerHTML = '<button>Pins</button>'
715-
visible(document.querySelector('button') as HTMLButtonElement)
726+
const original = visible(document.querySelector('button') as HTMLButtonElement)
716727
const firstRef = refFor(outlineOf(collectSnapshot()), 'Pins')
717-
const secondRef = refFor(outlineOf(collectSnapshot()), 'Pins')
728+
original.replaceWith(visible(document.createElement('button')))
729+
;(document.querySelector('button') as HTMLButtonElement).textContent = 'Files'
730+
const secondRef = refFor(outlineOf(collectSnapshot()), 'Files')
718731

719732
expect(secondRef).toBeGreaterThan(firstRef)
720733
expect(clickElement(firstRef)).toMatchObject({ error: 'stale' })
721734
expect(clickElement(secondRef)).toMatchObject({ dispatched: true })
722735
})
736+
737+
it('gives a recycled row a new ref when its identity changed in place', () => {
738+
document.body.innerHTML = '<div role="listitem" data-key="channel-1">eng-bugs</div>'
739+
const row = visible(document.querySelector('[role="listitem"]') as HTMLDivElement)
740+
const firstRef = refFor(outlineOf(collectSnapshot()), 'eng-bugs')
741+
row.textContent = 'random'
742+
row.dataset.key = 'channel-2'
743+
const secondRef = refFor(outlineOf(collectSnapshot()), 'random')
744+
745+
expect(secondRef).not.toBe(firstRef)
746+
expect(clickElement(firstRef)).toMatchObject({ error: 'stale' })
747+
})
723748
})
724749

725750
describe('semantic control state', () => {

‎apps/desktop/src/main/browser-agent/page-functions.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ declare global {
4343
observedRoots: WeakSet<ParentNode>
4444
}>
4545
__simAgentNextElementId?: number
46+
/** Each element's ref and the identity it was issued for, so a later snapshot keeps the ref. */
47+
__simAgentIssuedRefs?: WeakMap<Element, { id: number; identity: string; namespace: number }>
4648
/** Elements an earlier snapshot of this document listed; a later snapshot marks the rest `new`. */
4749
__simAgentShownElements?: WeakSet<Element>
4850
/** Installed by {@link installPageHelpers} before every page function; cached per call. */
@@ -210,7 +212,8 @@ export function installPageHelpers(): void {
210212
export function collectSnapshot(
211213
startingElementId = 0,
212214
elementId: number | null = null,
213-
markNew = true
215+
markNew = true,
216+
refNamespace = 0
214217
): unknown {
215218
const resolver = window.__simAgentResolveElement
216219
const scopedRoot =
@@ -588,10 +591,14 @@ export function collectSnapshot(
588591
return ''
589592
}
590593

594+
// A ref the model already holds stays valid while its element keeps the
595+
// identity it was issued for; a changed or replaced element gets a new ref,
596+
// so an id never comes to mean a different element. Refs are reused only
597+
// within the browser scope (refNamespace) that issued them.
598+
const issuedRefs = window.__simAgentIssuedRefs ?? new WeakMap()
599+
window.__simAgentIssuedRefs = issuedRefs
591600
const registerElement = (el: Element, role: string, name: string): number => {
592-
const id = nextElementId++
593-
registry[id] = el
594-
locators[id] = {
601+
const locator = {
595602
url: pageUrlFor(el),
596603
tag: el.tagName.toUpperCase(),
597604
role,
@@ -600,6 +607,18 @@ export function collectSnapshot(
600607
ancestor: ancestorSignature(el),
601608
context: contextSignature(el),
602609
}
610+
const identity = JSON.stringify([locator.tag, locator.role, locator.name, locator.attributes])
611+
const issued = issuedRefs.get(el)
612+
const id =
613+
issued &&
614+
issued.namespace === refNamespace &&
615+
issued.identity === identity &&
616+
registry[issued.id] === undefined
617+
? issued.id
618+
: nextElementId++
619+
issuedRefs.set(el, { id, identity, namespace: refNamespace })
620+
registry[id] = el
621+
locators[id] = locator
603622
refCount++
604623
window.__simAgentNextElementId = nextElementId
605624
return id

0 commit comments

Comments
 (0)