Skip to content

Commit 91aa3d5

Browse files
committed
improvement(desktop-browser): resolve refs from earlier snapshots while their element lives
1 parent 7959115 commit 91aa3d5

4 files changed

Lines changed: 112 additions & 21 deletions

File tree

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

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3121,11 +3121,42 @@ describe('credential protection', () => {
31213121
expect(forged).toMatchObject({ ok: false })
31223122
})
31233123

3124+
it('acts on a ref an earlier snapshot of the same page issued', async () => {
3125+
const contents = await openPage()
3126+
respondWith(contents, {
3127+
collectSnapshot: {
3128+
url: 'https://example.com/',
3129+
title: 'Example',
3130+
outline: '- button "Pins" [ref=4]\n- button "Files" [ref=5]',
3131+
truncated: false,
3132+
refIds: [4, 5],
3133+
refLineIndexes: { 4: 0, 5: 1 },
3134+
nextElementId: 6,
3135+
},
3136+
})
3137+
await driver.executeTool('chat-test', 'browser_snapshot', {})
3138+
respondWith(contents, {
3139+
collectSnapshot: {
3140+
url: 'https://example.com/',
3141+
title: 'Example',
3142+
outline: '- dialog "Pick a time" [ref=6]',
3143+
truncated: false,
3144+
refIds: [6],
3145+
refLineIndexes: { 6: 0 },
3146+
nextElementId: 7,
3147+
},
3148+
})
3149+
await driver.executeTool('chat-test', 'browser_find', { query: 'time' })
3150+
3151+
const clicked = await driver.executeTool('chat-test', 'browser_click', { elementId: 4 })
3152+
expect(clicked).toMatchObject({ ok: true, result: { dispatched: true } })
3153+
})
3154+
31243155
it.each([
31253156
['browser_snapshot', 'true'],
31263157
['browser_find', 'false'],
31273158
] as const)(
3128-
'passes the current root ref to %s and invalidates previous refs',
3159+
'passes the current root ref to %s',
31293160
async (tool, markNew) => {
31303161
const contents = await openPage()
31313162
respondWith(contents, {
@@ -3151,8 +3182,6 @@ describe('credential protection', () => {
31513182
expression.includes(`.apply(null, [1,0,${markNew},`)
31523183
)
31533184
).toBe(true)
3154-
const stale = await driver.executeTool('chat-test', 'browser_click', { elementId: 0 })
3155-
expect(stale).toMatchObject({ ok: false })
31563185
}
31573186
)
31583187

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

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -334,8 +334,8 @@ interface DriverScopeState {
334334
snapshotTargets: Map<number, PageExecutionTarget>
335335
/** Monotonic ref floor shared by every frame in this browser scope. */
336336
nextElementRefId: number
337-
/** Every ref this scope issued and the frame it belongs to, so a later snapshot may reuse it there. */
338-
issuedRefTargets: Map<number, string>
337+
/** Every ref this scope issued and its frame: a later snapshot may reuse it there, and an action may still name it. */
338+
issuedRefTargets: Map<number, { key: string; target: PageExecutionTarget }>
339339
/** Invalidates captures that finish after a tab/navigation/timeout race. */
340340
snapshotCaptureEpoch: number
341341
/** Cancels a timed-out multi-step action before any later native dispatch. */
@@ -1777,9 +1777,28 @@ function requireSnapshotForElementAction(): void {
17771777
)
17781778
}
17791779

1780+
/**
1781+
* The frame that owns a ref: the latest snapshot's, or for a ref an earlier
1782+
* snapshot issued, its frame while that frame still belongs to the tab the
1783+
* latest snapshot covered. The page then confirms the element itself.
1784+
*/
1785+
function elementTarget(elementId: number): PageExecutionTarget | undefined {
1786+
const state = driverScopeState()
1787+
const latest = state.snapshotTargets.get(elementId)
1788+
if (latest) return latest
1789+
const issued = state.issuedRefTargets.get(elementId)
1790+
const contents = session.automationTab()?.view.webContents
1791+
if (!issued || !contents || contents.isDestroyed()) return undefined
1792+
if (!('routingId' in issued.target)) return issued.target === contents ? contents : undefined
1793+
const frame = issued.target
1794+
return contents.mainFrame.framesInSubtree.find(
1795+
(candidate) => !candidate.isDestroyed() && sameWebFrame(candidate, frame)
1796+
)
1797+
}
1798+
17801799
function pageTargetForElement(elementId: number): PageExecutionTarget {
17811800
requireSnapshotForElementAction()
1782-
const target = driverScopeState().snapshotTargets.get(elementId)
1801+
const target = elementTarget(elementId)
17831802
if (!target || ('isDestroyed' in target && target.isDestroyed())) {
17841803
throw new ToolError(
17851804
'That element id is not present in the current snapshot. Call browser_snapshot and use a visible ref from that result.'
@@ -1876,7 +1895,13 @@ function assertElementActionCurrent(
18761895
assertActiveContents(contents)
18771896
const state = driverScopeState()
18781897
const active = session.automationTab()
1879-
if (state.snapshotTabId !== active?.id || state.snapshotTargets.get(elementId) !== target) {
1898+
const owner = elementTarget(elementId)
1899+
if (
1900+
state.snapshotTabId !== active?.id ||
1901+
!owner ||
1902+
(owner !== target &&
1903+
!('routingId' in owner && 'routingId' in target && sameWebFrame(owner, target)))
1904+
) {
18801905
throw new ToolError(
18811906
'The page changed before input could be dispatched. Take a fresh browser_snapshot and try again.'
18821907
)
@@ -2466,7 +2491,7 @@ async function captureSnapshot(
24662491
const mainRefs = validateSnapshotRefs(
24672492
mainSnapshot,
24682493
mainStartingElementId,
2469-
(ref) => state.issuedRefTargets.get(ref) === pageTargetKey(contents)
2494+
(ref) => state.issuedRefTargets.get(ref)?.key === pageTargetKey(contents)
24702495
)
24712496
if (!mainRefs) {
24722497
throw new ToolError('The page returned invalid element ids. Try browser_snapshot again.')
@@ -2531,7 +2556,7 @@ async function captureSnapshot(
25312556
const frameRefs = validateSnapshotRefs(
25322557
frameSnapshot,
25332558
frameStartingElementId,
2534-
(ref) => state.issuedRefTargets.get(ref) === pageTargetKey(frame)
2559+
(ref) => state.issuedRefTargets.get(ref)?.key === pageTargetKey(frame)
25352560
)
25362561
if (!frameRefs) {
25372562
unreadableCrossOriginFrames++
@@ -2585,7 +2610,9 @@ async function captureSnapshot(
25852610
(targetLineIndexes.get(elementId) ?? Number.POSITIVE_INFINITY) < visibleOutlineLines.length
25862611
)
25872612
)
2588-
for (const [ref, target] of targets) state.issuedRefTargets.set(ref, pageTargetKey(target))
2613+
for (const [ref, target] of targets) {
2614+
state.issuedRefTargets.set(ref, { key: pageTargetKey(target), target })
2615+
}
25892616
state.snapshotTabId = capturedTabId
25902617
return {
25912618
...omit(mainSnapshot, ['refIds', 'refLineIndexes', 'nextElementId']),

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,26 @@ describe('collectSnapshot', () => {
721721
expect(clickElement(refFor(first, 'Pins'))).toMatchObject({ dispatched: true })
722722
})
723723

724+
it('acts on a ref from an earlier snapshot that a later scoped snapshot left out', () => {
725+
document.body.innerHTML = '<button>Pins</button><section><button>Files</button></section>'
726+
for (const button of Array.from(document.querySelectorAll('button'))) visible(button)
727+
const pins = refFor(outlineOf(collectSnapshot()), 'Pins')
728+
const section = refFor(outlineOf(collectSnapshot()), 'Files')
729+
collectSnapshot(100, section)
730+
731+
expect(clickElement(pins)).toMatchObject({ dispatched: true })
732+
})
733+
734+
it('refuses a ref from an earlier snapshot once its element left the DOM', () => {
735+
document.body.innerHTML = '<button>Pins</button><button>Files</button>'
736+
for (const button of Array.from(document.querySelectorAll('button'))) visible(button)
737+
const pins = refFor(outlineOf(collectSnapshot()), 'Pins')
738+
;(document.querySelector('button') as HTMLButtonElement).remove()
739+
collectSnapshot()
740+
741+
expect(clickElement(pins)).toMatchObject({ error: 'stale' })
742+
})
743+
724744
it('never gives a ref to a different element across snapshots', () => {
725745
document.body.innerHTML = '<button>Pins</button>'
726746
const original = visible(document.querySelector('button') as HTMLButtonElement)

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

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,17 @@
2828
* the keystroke refusal that read it.
2929
*/
3030

31+
/** What a snapshot recorded about an element, so a later action can confirm it is the same one. */
32+
interface SnapshotRefLocator {
33+
url: string
34+
tag: string
35+
role: string
36+
name: string
37+
attributes: Record<string, string>
38+
ancestor: string
39+
context: string
40+
}
41+
3142
declare global {
3243
interface Window {
3344
__simAgentElements?: Element[]
@@ -45,6 +56,8 @@ declare global {
4556
__simAgentNextElementId?: number
4657
/** Each element's ref and the identity it was issued for, so a later snapshot keeps the ref. */
4758
__simAgentIssuedRefs?: WeakMap<Element, { id: number; identity: string; namespace: number }>
59+
/** Refs issued by earlier snapshots of this document, resolvable while their element lives. */
60+
__simAgentEarlierRefs?: Map<number, { element: WeakRef<Element>; locator: SnapshotRefLocator }>
4861
/** Elements an earlier snapshot of this document listed; a later snapshot marks the rest `new`. */
4962
__simAgentShownElements?: WeakSet<Element>
5063
/** Installed by {@link installPageHelpers} before every page function; cached per call. */
@@ -311,15 +324,7 @@ export function collectSnapshot(
311324

312325
const registry: Element[] = []
313326
const refLineIndexes: Record<number, number> = {}
314-
const locators: Array<{
315-
url: string
316-
tag: string
317-
role: string
318-
name: string
319-
attributes: Record<string, string>
320-
ancestor: string
321-
context: string
322-
}> = []
327+
const locators: SnapshotRefLocator[] = []
323328
window.__simAgentElements = registry
324329
const previouslyShown = window.__simAgentShownElements
325330
const shown = previouslyShown ?? new WeakSet<Element>()
@@ -597,6 +602,11 @@ export function collectSnapshot(
597602
// within the browser scope (refNamespace) that issued them.
598603
const issuedRefs = window.__simAgentIssuedRefs ?? new WeakMap()
599604
window.__simAgentIssuedRefs = issuedRefs
605+
// A ref from an earlier snapshot still resolves while its element lives,
606+
// even when a later scoped, query, or modal-covered snapshot left it out.
607+
const earlierRefs = window.__simAgentEarlierRefs ?? new Map()
608+
window.__simAgentEarlierRefs = earlierRefs
609+
const earlierRefCap = 5000
600610
const registerElement = (el: Element, role: string, name: string): number => {
601611
const locator = {
602612
url: pageUrlFor(el),
@@ -619,6 +629,10 @@ export function collectSnapshot(
619629
issuedRefs.set(el, { id, identity, namespace: refNamespace })
620630
registry[id] = el
621631
locators[id] = locator
632+
earlierRefs.delete(id)
633+
earlierRefs.set(id, { element: new WeakRef(el), locator })
634+
const oldest = earlierRefs.keys().next()
635+
if (earlierRefs.size > earlierRefCap && !oldest.done) earlierRefs.delete(oldest.value)
622636
refCount++
623637
window.__simAgentNextElementId = nextElementId
624638
return id
@@ -875,7 +889,8 @@ export function collectSnapshot(
875889
window.__simAgentStaleReason = 'the scoped snapshot root left the DOM'
876890
return null
877891
}
878-
const locator = locators[id]
892+
const earlier = locators[id] ? undefined : earlierRefs.get(id)
893+
const locator = locators[id] ?? earlier?.locator
879894
if (!locator) {
880895
window.__simAgentStaleReason = `id ${id} is not in the current snapshot's registry`
881896
return null
@@ -1006,7 +1021,7 @@ export function collectSnapshot(
10061021
return true
10071022
}
10081023

1009-
const current = registry[id]
1024+
const current = registry[id] ?? earlier?.element.deref()
10101025
if (current?.isConnected) {
10111026
if (!identityMatches(current, true)) {
10121027
window.__simAgentStaleReason = `the node is still mounted but its identity drifted (now <${String(current.tagName || '').toLowerCase()}> role=${roleFor(current) || 'none'} name="${nameFor(current).slice(0, 60)}")`

0 commit comments

Comments
 (0)