@@ -37,6 +37,7 @@ import { interruptibleSleep, sleep } from '@sim/utils/helpers'
3737import { isRecordLike , omit , toArray , toRecord } from '@sim/utils/object'
3838import type { BrowserWindow , MenuItemConstructorOptions , WebContents , WebFrameMain } from 'electron'
3939import { Menu } from 'electron'
40+ import { LRUCache } from 'lru-cache'
4041import * as cdp from '@/main/browser-agent/cdp'
4142import { steppedZoomFactor , zoomPercentOf } from '@/main/browser-agent/context-menu'
4243import { ToolError } from '@/main/browser-agent/errors'
@@ -88,7 +89,7 @@ import {
8889} from '@/main/browser-agent/page-prompts'
8990import { isPanelVisible , panelWindow } from '@/main/browser-agent/panel'
9091import {
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
146147type 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
154163type 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
17971804function 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+
19081922function 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 )
0 commit comments