Skip to content

Commit 385d4d6

Browse files
committed
chore(desktop-browser): one bounded ref store per page and driver, shared frame and observe helpers
1 parent 9d14981 commit 385d4d6

5 files changed

Lines changed: 106 additions & 101 deletions

File tree

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

Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3155,35 +3155,32 @@ describe('credential protection', () => {
31553155
it.each([
31563156
['browser_snapshot', 'true'],
31573157
['browser_find', 'false'],
3158-
] as const)(
3159-
'passes the current root ref to %s',
3160-
async (tool, markNew) => {
3161-
const contents = await openPage()
3162-
respondWith(contents, {
3163-
collectSnapshot: {
3164-
url: 'https://example.com/login',
3165-
title: 'Scoped',
3166-
scoped: true,
3167-
outline: '- button "Save" [ref=1]',
3168-
truncated: false,
3169-
refIds: [1],
3170-
refLineIndexes: { 1: 0 },
3171-
nextElementId: 2,
3172-
},
3173-
})
3174-
const result = await driver.executeTool('chat-test', tool, { elementId: 0, query: 'Save' })
3175-
expect(result).toMatchObject({ ok: true, result: { scoped: true } })
3176-
expect(
3177-
vi
3178-
.mocked(contents.executeJavaScript)
3179-
.mock.calls.some(
3180-
([expression]) =>
3181-
isPageCall(expression, 'collectSnapshot') &&
3182-
expression.includes(`.apply(null, [1,0,${markNew},`)
3183-
)
3184-
).toBe(true)
3185-
}
3186-
)
3158+
] as const)('passes the current root ref to %s', async (tool, markNew) => {
3159+
const contents = await openPage()
3160+
respondWith(contents, {
3161+
collectSnapshot: {
3162+
url: 'https://example.com/login',
3163+
title: 'Scoped',
3164+
scoped: true,
3165+
outline: '- button "Save" [ref=1]',
3166+
truncated: false,
3167+
refIds: [1],
3168+
refLineIndexes: { 1: 0 },
3169+
nextElementId: 2,
3170+
},
3171+
})
3172+
const result = await driver.executeTool('chat-test', tool, { elementId: 0, query: 'Save' })
3173+
expect(result).toMatchObject({ ok: true, result: { scoped: true } })
3174+
expect(
3175+
vi
3176+
.mocked(contents.executeJavaScript)
3177+
.mock.calls.some(
3178+
([expression]) =>
3179+
isPageCall(expression, 'collectSnapshot') &&
3180+
expression.includes(`.apply(null, [1,0,${markNew},`)
3181+
)
3182+
).toBe(true)
3183+
})
31873184

31883185
it.each([
31893186
{ kind: 'input:checkbox', checked: true, disabled: false, readOnly: false },

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

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { interruptibleSleep, sleep } from '@sim/utils/helpers'
3737
import { isRecordLike, omit, toArray, toRecord } from '@sim/utils/object'
3838
import type { BrowserWindow, MenuItemConstructorOptions, WebContents, WebFrameMain } from 'electron'
3939
import { Menu } from 'electron'
40+
import { LRUCache } from 'lru-cache'
4041
import * as cdp from '@/main/browser-agent/cdp'
4142
import { steppedZoomFactor, zoomPercentOf } from '@/main/browser-agent/context-menu'
4243
import { ToolError } from '@/main/browser-agent/errors'
@@ -88,7 +89,7 @@ import {
8889
} from '@/main/browser-agent/page-prompts'
8990
import { isPanelVisible, panelWindow } from '@/main/browser-agent/panel'
9091
import {
91-
observesAfterAction,
92+
observeRequest,
9293
withFailedPostActionObservation,
9394
withPostActionObservation,
9495
} from '@/main/browser-agent/post-action-observation'
@@ -145,10 +146,18 @@ function isBrowserWaitElementState(value: string): value is BrowserWaitElementSt
145146

146147
type PageExecutionTarget = WebContents | WebFrameMain
147148

149+
/** Matches the page's own memory of issued refs; an evicted ref simply gets a new id. */
150+
const ISSUED_REF_MEMORY = 5000
151+
148152
/** Whether two targets are the same page or frame; Electron may hand out separate wrappers for one frame. */
149-
function samePageTarget(left: PageExecutionTarget | undefined, right: PageExecutionTarget): boolean {
153+
function samePageTarget(
154+
left: PageExecutionTarget | undefined,
155+
right: PageExecutionTarget
156+
): boolean {
150157
if (left === right) return true
151-
return left !== undefined && 'routingId' in left && 'routingId' in right && sameWebFrame(left, right)
158+
return (
159+
left !== undefined && 'routingId' in left && 'routingId' in right && sameWebFrame(left, right)
160+
)
152161
}
153162

154163
type BrowserActionOutcome = { status: 'pending' } | { status: 'acknowledged'; result: unknown }
@@ -334,7 +343,7 @@ interface DriverScopeState {
334343
/** Monotonic ref floor shared by every frame in this browser scope. */
335344
nextElementRefId: number
336345
/** Every ref this scope issued and its frame: a later snapshot may reuse it there, and an action may still name it. */
337-
issuedRefTargets: Map<number, PageExecutionTarget>
346+
issuedRefTargets: LRUCache<number, PageExecutionTarget>
338347
/** Invalidates captures that finish after a tab/navigation/timeout race. */
339348
snapshotCaptureEpoch: number
340349
/** Cancels a timed-out multi-step action before any later native dispatch. */
@@ -376,7 +385,7 @@ function createDriverScopeState(): DriverScopeState {
376385
snapshotTabId: null,
377386
snapshotTargets: new Map(),
378387
nextElementRefId: 0,
379-
issuedRefTargets: new Map(),
388+
issuedRefTargets: new LRUCache({ max: ISSUED_REF_MEMORY }),
380389
snapshotCaptureEpoch: 0,
381390
toolExecutionEpoch: 0,
382391
}
@@ -1789,9 +1798,7 @@ function elementTarget(elementId: number): PageExecutionTarget | undefined {
17891798
const contents = session.automationTab()?.view.webContents
17901799
if (!issued || !contents || contents.isDestroyed()) return undefined
17911800
if (!('routingId' in issued)) return issued === contents ? contents : undefined
1792-
return contents.mainFrame.framesInSubtree.find(
1793-
(candidate) => !candidate.isDestroyed() && sameWebFrame(candidate, issued)
1794-
)
1801+
return liveFrameInTab(contents, issued)
17951802
}
17961803

17971804
function pageTargetForElement(elementId: number): PageExecutionTarget {
@@ -1905,6 +1912,13 @@ function focusedPageTarget(contents: WebContents): PageExecutionTarget {
19051912
return focused && focused !== contents.mainFrame && !focused.isDestroyed() ? focused : contents
19061913
}
19071914

1915+
/** The tab's current wrapper for a frame, if the frame is still live in that tab. */
1916+
function liveFrameInTab(contents: WebContents, frame: WebFrameMain): WebFrameMain | undefined {
1917+
return contents.mainFrame.framesInSubtree.find(
1918+
(candidate) => !candidate.isDestroyed() && sameWebFrame(candidate, frame)
1919+
)
1920+
}
1921+
19081922
function sameWebFrame(left: WebFrameMain, right: WebFrameMain): boolean {
19091923
if (left === right) return true
19101924
if (Number.isSafeInteger(left.frameTreeNodeId) && Number.isSafeInteger(right.frameTreeNodeId)) {
@@ -1927,11 +1941,7 @@ function assertFocusedTargetUnchanged(
19271941
expectedFrameNavigationEpoch?: number
19281942
): void {
19291943
const focused = focusedPageTarget(contents)
1930-
const unchanged =
1931-
target === contents
1932-
? focused === contents
1933-
: focused !== contents && sameWebFrame(focused as WebFrameMain, target as WebFrameMain)
1934-
if (!unchanged) {
1944+
if (!samePageTarget(focused, target)) {
19351945
throw new ToolError(
19361946
'Focus moved to a different page or frame before the keystroke. No retry was attempted; inspect the page first.'
19371947
)
@@ -1943,7 +1953,7 @@ function assertFocusedTargetUnchanged(
19431953
frame.detached ||
19441954
(expectedFrameNavigationEpoch !== undefined &&
19451955
frameNavigationEpoch(contents, frame) !== expectedFrameNavigationEpoch) ||
1946-
!contents.mainFrame.framesInSubtree.some((candidate) => sameWebFrame(candidate, frame))
1956+
!liveFrameInTab(contents, frame)
19471957
) {
19481958
throw new ToolError(
19491959
'The focused frame navigated or was replaced before the keystroke. Inspect the page before continuing.'
@@ -2480,10 +2490,8 @@ async function captureSnapshot(
24802490
) {
24812491
throw new ToolError('The page returned an incomplete snapshot. Try browser_snapshot again.')
24822492
}
2483-
const mainRefs = validateSnapshotRefs(
2484-
mainSnapshot,
2485-
mainStartingElementId,
2486-
(ref) => samePageTarget(state.issuedRefTargets.get(ref), contents)
2493+
const mainRefs = validateSnapshotRefs(mainSnapshot, mainStartingElementId, (ref) =>
2494+
samePageTarget(state.issuedRefTargets.get(ref), contents)
24872495
)
24882496
if (!mainRefs) {
24892497
throw new ToolError('The page returned invalid element ids. Try browser_snapshot again.')
@@ -2545,10 +2553,8 @@ async function captureSnapshot(
25452553
unreadableCrossOriginFrames++
25462554
continue
25472555
}
2548-
const frameRefs = validateSnapshotRefs(
2549-
frameSnapshot,
2550-
frameStartingElementId,
2551-
(ref) => samePageTarget(state.issuedRefTargets.get(ref), frame)
2556+
const frameRefs = validateSnapshotRefs(frameSnapshot, frameStartingElementId, (ref) =>
2557+
samePageTarget(state.issuedRefTargets.get(ref), frame)
25522558
)
25532559
if (!frameRefs) {
25542560
unreadableCrossOriginFrames++
@@ -5390,7 +5396,7 @@ export async function executeTool(
53905396
actionOutcome = outcome
53915397
}
53925398
)
5393-
if (observesAfterAction(tool, params)) {
5399+
if (observeRequest(tool, params) !== undefined) {
53945400
actionOutcome = { status: 'acknowledged', result }
53955401
}
53965402
return result
@@ -5417,7 +5423,7 @@ export async function executeTool(
54175423
tool === 'browser_snapshot' ||
54185424
tool === 'browser_open_url' ||
54195425
tool === 'browser_find' ||
5420-
observesAfterAction(tool, params)
5426+
observeRequest(tool, params) !== undefined
54215427
) {
54225428
invalidateSnapshot(state)
54235429
}
@@ -5427,7 +5433,7 @@ export async function executeTool(
54275433
observedResult = await guardedExecution
54285434
} catch (error) {
54295435
if (!actionOutcome) {
5430-
if (observesAfterAction(tool, params)) cancelPendingSnapshotCapture(state)
5436+
if (observeRequest(tool, params) !== undefined) cancelPendingSnapshotCapture(state)
54315437
throw error
54325438
}
54335439
invalidateSnapshot(state)

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -353,13 +353,17 @@ describe('combobox typing surfaces', () => {
353353
})
354354

355355
it('types into a top-page field a promo card covers, naming the cover', () => {
356-
document.body.innerHTML = '<input type="search" aria-label="Search" /><div>Shop for your home</div>'
356+
document.body.innerHTML =
357+
'<input type="search" aria-label="Search" /><div>Shop for your home</div>'
357358
const input = visible(document.querySelector('input') as HTMLInputElement)
358359
const card = visible(document.querySelector('div') as HTMLDivElement)
359360
register(input)
360361
Object.defineProperty(document, 'elementFromPoint', { configurable: true, value: () => card })
361362

362-
expect(focusElementForTyping(0)).toMatchObject({ focused: true, coveredBy: 'Shop for your home' })
363+
expect(focusElementForTyping(0)).toMatchObject({
364+
focused: true,
365+
coveredBy: 'Shop for your home',
366+
})
363367
expect(typeIntoElement(0, 'cooking pot', false)).toMatchObject({ dispatched: true })
364368
expect(input.value).toBe('cooking pot')
365369
})
@@ -705,7 +709,8 @@ describe('collectSnapshot', () => {
705709
const menu = visible(document.querySelector('[role="button"]') as HTMLDivElement)
706710
const ref = refFor(outlineOf(collectSnapshot()), 'Products ▾')
707711

708-
;(menu.querySelector('ul') as HTMLUListElement).innerHTML = ' <li>Starter</li> <li>Business</li>'
712+
;(menu.querySelector('ul') as HTMLUListElement).innerHTML =
713+
' <li>Starter</li> <li>Business</li>'
709714

710715
expect(clickElement(ref)).toMatchObject({ dispatched: true })
711716
})

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

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,13 @@ declare global {
5454
observedRoots: WeakSet<ParentNode>
5555
}>
5656
__simAgentNextElementId?: number
57-
/** Each element's ref and the identity it was issued for, so a later snapshot keeps the ref. */
58-
__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 }>
57+
/** Every ref this document issued, resolvable while its element keeps that identity. */
58+
__simAgentIssuedRefs?: Map<
59+
number,
60+
{ element: WeakRef<Element>; locator: SnapshotRefLocator; namespace: number }
61+
>
62+
/** The ref each element was last issued, so an unchanged element keeps it. */
63+
__simAgentRefOfElement?: WeakMap<Element, number>
6164
/** Elements an earlier snapshot of this document listed; a later snapshot marks the rest `new`. */
6265
__simAgentShownElements?: WeakSet<Element>
6366
/** Installed by {@link installPageHelpers} before every page function; cached per call. */
@@ -596,17 +599,13 @@ export function collectSnapshot(
596599
return ''
597600
}
598601

599-
// A ref the model already holds stays valid while its element keeps the
600-
// identity it was issued for; a changed or replaced element gets a new ref,
601-
// so an id never comes to mean a different element. Refs are reused only
602-
// within the browser scope (refNamespace) that issued them.
603-
const issuedRefs = window.__simAgentIssuedRefs ?? new WeakMap()
602+
// An unchanged element keeps its ref, and a ref stays resolvable after a
603+
// later snapshot leaves it out; a changed element gets a new ref.
604+
const issuedRefs = window.__simAgentIssuedRefs ?? new Map()
604605
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
606+
const refOfElement = window.__simAgentRefOfElement ?? new WeakMap()
607+
window.__simAgentRefOfElement = refOfElement
608+
const issuedRefCap = 5000
610609
const registerElement = (el: Element, role: string, name: string): number => {
611610
const locator = {
612611
url: pageUrlFor(el),
@@ -617,22 +616,28 @@ export function collectSnapshot(
617616
ancestor: ancestorSignature(el),
618617
context: contextSignature(el),
619618
}
620-
const identity = JSON.stringify([locator.tag, locator.role, locator.name, locator.attributes])
621-
const issued = issuedRefs.get(el)
619+
const priorId = refOfElement.get(el)
620+
const prior = priorId === undefined ? undefined : issuedRefs.get(priorId)
621+
const unchanged =
622+
prior !== undefined &&
623+
prior.namespace === refNamespace &&
624+
prior.locator.tag === locator.tag &&
625+
prior.locator.role === locator.role &&
626+
prior.locator.name === locator.name &&
627+
Object.keys({ ...prior.locator.attributes, ...locator.attributes }).every(
628+
(key) => prior.locator.attributes[key] === locator.attributes[key]
629+
)
622630
const id =
623-
issued &&
624-
issued.namespace === refNamespace &&
625-
issued.identity === identity &&
626-
registry[issued.id] === undefined
627-
? issued.id
631+
unchanged && priorId !== undefined && registry[priorId] === undefined
632+
? priorId
628633
: nextElementId++
629-
issuedRefs.set(el, { id, identity, namespace: refNamespace })
634+
refOfElement.set(el, id)
630635
registry[id] = el
631636
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)
637+
issuedRefs.delete(id)
638+
issuedRefs.set(id, { element: new WeakRef(el), locator, namespace: refNamespace })
639+
const oldest = issuedRefs.keys().next()
640+
if (issuedRefs.size > issuedRefCap && !oldest.done) issuedRefs.delete(oldest.value)
636641
refCount++
637642
window.__simAgentNextElementId = nextElementId
638643
return id
@@ -724,8 +729,7 @@ export function collectSnapshot(
724729
160
725730
)
726731
if (!text) return
727-
// Identity uses the name the resolver recomputes, not the displayed text,
728-
// which differs for aria-labelled leaves and past the name's length cap.
732+
// The resolver recomputes nameFor, which differs from the shown text for aria-labelled or long leaves.
729733
const id = registerElement(el, roleFor(el), nameFor(el))
730734
textLineCount++
731735
const marker = isNew(el) ? ' new' : ''
@@ -889,8 +893,8 @@ export function collectSnapshot(
889893
window.__simAgentStaleReason = 'the scoped snapshot root left the DOM'
890894
return null
891895
}
892-
const earlier = locators[id] ? undefined : earlierRefs.get(id)
893-
const locator = locators[id] ?? earlier?.locator
896+
const issued = issuedRefs.get(id)
897+
const locator = issued?.locator
894898
if (!locator) {
895899
window.__simAgentStaleReason = `id ${id} is not in the current snapshot's registry`
896900
return null
@@ -1021,7 +1025,7 @@ export function collectSnapshot(
10211025
return true
10221026
}
10231027

1024-
const current = registry[id] ?? earlier?.element.deref()
1028+
const current = registry[id] ?? issued?.element.deref()
10251029
if (current?.isConnected) {
10261030
if (!identityMatches(current, true)) {
10271031
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)}")`
@@ -1911,12 +1915,8 @@ export function focusElementForTyping(id: number, moveFocus = true): unknown {
19111915
coveredByRelatedPopup = true
19121916
}
19131917
}
1914-
// Typing reaches a focused top-page field through the keyboard, never the
1915-
// pointer, so an overlay over it (a promo card, a sticky banner) does not
1916-
// stop the text, as Playwright's fill does not hit-test either. Modal
1917-
// dialogs still refuse: their background is aria-hidden or inert, which the
1918-
// visibility and focus checks above reject. Framed fields keep the strict
1919-
// check because the driver maps their point through the parent page.
1918+
// Top-page typing goes through keyboard focus, so a non-modal overlay does not block it (modals
1919+
// fail the aria-hidden/inert checks above); framed fields keep the check for their mapped point.
19201920
const topPageField = view === window && window.top === window
19211921
let coveredBy: string | undefined
19221922
if (!chosenPoint && topPageField && blockedPoints.length > 0) {

0 commit comments

Comments
 (0)