Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): r2-h1 correct sandbox find session lifecycle
Josué0a0352eb12a6
diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 1b144708b..aeb68307b 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -14,6 +14,7 @@"test": "vitest run","test:e2e": "vitest run --config test/e2e/vitest.config.ts","test:e2e:playwright": "npm run build && playwright test --config test/e2e-playwright/playwright.config.ts",+ "test:native:sandbox-find": "npm run build:main --silent && node ./scripts/run-native-sandbox-find.mjs","qa:recorder:auth": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-auth.spec.ts","qa:recorder:navigation": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-navigation.spec.ts","qa:recorder:agents": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-agents.spec.ts",diff --git a/desktop-app/scripts/run-native-sandbox-find.mjs b/desktop-app/scripts/run-native-sandbox-find.mjsnew file mode 100644index 000000000..011a56706--- /dev/null+++ b/desktop-app/scripts/run-native-sandbox-find.mjs@@ -0,0 +1,19 @@+import electronPath from 'electron'+import { spawn } from 'node:child_process'++const childEnvironment = { ...process.env }+delete childEnvironment.ELECTRON_RUN_AS_NODE++const child = spawn(electronPath, ['./test/native/sandbox-find.fixture.cjs'], {+ cwd: new URL('..', import.meta.url),+ env: childEnvironment,+ stdio: 'inherit',+})++child.on('error', error => {+ console.error(error)+ process.exitCode = 1+})+child.on('exit', code => {+ process.exitCode = code ?? 1+})diff --git a/desktop-app/src/__tests__/sandboxFindSession.test.ts b/desktop-app/src/__tests__/sandboxFindSession.test.tsnew file mode 100644index 000000000..ef077a7e6--- /dev/null+++ b/desktop-app/src/__tests__/sandboxFindSession.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it, vi } from 'vitest'+import { createSandboxFindResultGate } from '../sandboxFindSession.js'++describe('sandbox native find result gate', () => {+ it('keeps a provisional final zero pending when a real final result follows', () => {+ vi.useFakeTimers()+ const deliver = vi.fn()+ const gate = createSandboxFindResultGate(deliver)+ gate.accept({ requestId: 1, activeMatchOrdinal: 0, matches: 0, finalUpdate: true })+ expect(deliver).not.toHaveBeenCalled()+ gate.accept({ requestId: 1, activeMatchOrdinal: 1, matches: 2, finalUpdate: true })+ expect(deliver).toHaveBeenCalledOnce()+ expect(deliver).toHaveBeenLastCalledWith(+ expect.objectContaining({ activeMatchOrdinal: 1, matches: 2 })+ )+ vi.runAllTimers()+ expect(deliver).toHaveBeenCalledOnce()+ vi.useRealTimers()+ })++ it('delivers a genuine final zero after the producer settling window', () => {+ vi.useFakeTimers()+ const deliver = vi.fn()+ const gate = createSandboxFindResultGate(deliver)+ gate.accept({ requestId: 2, activeMatchOrdinal: 0, matches: 0, finalUpdate: true })+ vi.advanceTimersByTime(49)+ expect(deliver).not.toHaveBeenCalled()+ vi.advanceTimersByTime(1)+ expect(deliver).toHaveBeenCalledWith(+ expect.objectContaining({ requestId: 2, matches: 0, finalUpdate: true })+ )+ vi.useRealTimers()+ })++ it('drops a pending zero when the session is disposed', () => {+ vi.useFakeTimers()+ const deliver = vi.fn()+ const gate = createSandboxFindResultGate(deliver)+ gate.accept({ requestId: 3, activeMatchOrdinal: 0, matches: 0, finalUpdate: true })+ gate.dispose()+ vi.runAllTimers()+ expect(deliver).not.toHaveBeenCalled()+ vi.useRealTimers()+ })+})diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.tsindex 5a9ac7cb5..75953ffc6 100644--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts@@ -11,6 +11,7 @@ import {reloadSandboxUiWebContents,resolveSandboxUiDefaultPath,resolveSandboxUiSharePath,+ sandboxFindOptionsForOperation,} from '../sandboxUiDriver.js'describe('sandbox WebContents local find', () => {@@ -36,12 +37,7 @@ describe('sandbox WebContents local find', () => {}const onResult = vi.fn()- beginSandboxUiFind(- webContents as never,- 'invoice',- { forward: true, findNext: false },- onResult- )+ beginSandboxUiFind(webContents as never, 'invoice', { forward: true, findNext: true }, onResult)expect(onResult).toHaveBeenCalledWith({requestId: 41,@@ -100,6 +96,17 @@ describe('sandbox WebContents local find', () => {})})+describe('sandbox find operation mapping', () => {+ it('maps semantic operations to Electron find session flags', () => {+ expect(sandboxFindOptionsForOperation('start')).toEqual({ forward: true, findNext: true })+ expect(sandboxFindOptionsForOperation('next')).toEqual({ forward: true, findNext: false })+ expect(sandboxFindOptionsForOperation('previous')).toEqual({+ forward: false,+ findNext: false,+ })+ })+})+describe('applySandboxUiClientRoute', () => {it('hands a nested route to the loaded app without requesting it from the server', async () => {const executeJavaScript = vi.fn().mockResolvedValue(true)diff --git a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.tsindex b84e6745a..982ae8a1e 100644--- a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {+ findInActiveSandboxUi,focusActiveSandboxUi,installSandboxUiCookie,mountSandboxUiView,@@ -23,6 +24,7 @@ const electronMocks = vi.hoisted(() => {})setWindowOpenHandler = vi.fn()stopFindInPage = vi.fn()+ findInPage = vi.fn(() => 41)focus = vi.fn()on(event: string, handler: (...args: unknown[]) => void): this {@@ -212,6 +214,49 @@ describe('mountSandboxUiView lifecycle cleanup', () => {expect(electronMocks.views[0]?.webContents.focus).toHaveBeenCalledOnce()})+ it('gates find by document readiness and invalidates it on main-frame navigation', async () => {+ const parentWindow = new FakeParentWindow()+ await mountSandboxUiView(mountArgs({ parentWindow }))+ const webContents = electronMocks.views[0]!.webContents+ const onResult = vi.fn()++ expect(findInActiveSandboxUi('invoice', 'start', 1, onResult)).toEqual({+ status: 'unavailable',+ reason: 'document-loading',+ })++ webContents.emit('did-finish-load')+ expect(findInActiveSandboxUi('invoice', 'start', 1, onResult)).toEqual({+ status: 'started',+ requestId: 41,+ })+ expect(webContents.findInPage).toHaveBeenCalledWith('invoice', {+ forward: true,+ findNext: true,+ })+ webContents.emit('found-in-page', {} as Electron.Event, {+ requestId: 41,+ activeMatchOrdinal: 1,+ matches: 2,+ selectionArea: { x: 0, y: 0, width: 1, height: 1 },+ finalUpdate: true,+ })+ expect(findInActiveSandboxUi('invoice', 'next', 1, onResult).status).toBe('started')++ webContents.emit(+ 'did-start-navigation',+ {} as Electron.Event,+ 'https://rpc.example/next',+ false,+ true+ )+ expect(webContents.stopFindInPage).toHaveBeenCalledWith('clearSelection')+ expect(findInActiveSandboxUi('invoice', 'next', 1, onResult)).toEqual({+ status: 'unavailable',+ reason: 'document-loading',+ })+ })+it('keeps only the newest view when cookie writes complete out of order', async () => {const parentWindow = new FakeParentWindow()let resolveFirstCookie!: () => voiddiff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 45fbb8cfc..950cb3b6d 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -3218,11 +3218,12 @@ export class AppService {async findInActiveSandboxUi(query: string,- options: { forward: boolean; findNext: boolean },+ operation: import('./sandboxUiDriver.js').SandboxUiFindOperation,+ clientRequestId: number,onResult: (result: import('./sandboxUiDriver.js').SandboxUiFindResult) => void- ): Promise<number | null> {+ ): Promise<import('./sandboxUiDriver.js').SandboxUiFindStartResult> {const { findInActiveSandboxUi } = await import('./sandboxUiDriver.js')- return findInActiveSandboxUi(query, options, onResult)+ return findInActiveSandboxUi(query, operation, clientRequestId, onResult)}async stopActiveSandboxUiFind(): Promise<void> {diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 360bd14e9..3f64ae786 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -1550,8 +1550,7 @@ export function registerIpcHandlers(service: AppService): void {event,payload: {query?: unknown- forward?: unknown- findNext?: unknown+ operation?: unknownclientRequestId?: unknown}) => {@@ -1560,8 +1559,8 @@ export function registerIpcHandlers(service: AppService): void {if (!query.trim() || query.length > 500) {throw new Error('find query must contain 1 to 500 characters')}- if (typeof payload?.forward !== 'boolean' || typeof payload?.findNext !== 'boolean') {- throw new Error('find direction options must be boolean')+ if (!['start', 'next', 'previous'].includes(String(payload?.operation))) {+ throw new Error('find operation must be start, next, or previous')}if (!Number.isSafeInteger(payload?.clientRequestId) || Number(payload.clientRequestId) <= 0) {throw new Error('find client request ID must be a positive safe integer')@@ -1569,7 +1568,8 @@ export function registerIpcHandlers(service: AppService): void {const clientRequestId = Number(payload.clientRequestId)return service.findInActiveSandboxUi(query,- { forward: payload.forward, findNext: payload.findNext },+ payload.operation as 'start' | 'next' | 'previous',+ clientRequestId,result => {if (!event.sender.isDestroyed()) {event.sender.send('sandboxUi:findResult', { ...result, clientRequestId })diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex bf8c81c9e..d761e70ad 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -502,9 +502,12 @@ const clerum = Object.freeze({capturePreview: () => ipcRenderer.invoke('sandboxUi:capturePreview'),findInPage: (query: string,- options: { forward: boolean; findNext: boolean; clientRequestId: number }+ options: { operation: 'start' | 'next' | 'previous'; clientRequestId: number }) =>- ipcRenderer.invoke('sandboxUi:findInPage', { query, ...options }) as Promise<number | null>,+ ipcRenderer.invoke('sandboxUi:findInPage', { query, ...options }) as Promise<+ | { status: 'started'; requestId: number }+ | { status: 'unavailable'; reason: 'no-active-view' | 'document-loading' | 'no-session' }+ >,stopFindInPage: () => ipcRenderer.invoke('sandboxUi:stopFindInPage') as Promise<void>,focusActive: () => ipcRenderer.invoke('sandboxUi:focusActive') as Promise<boolean>,onFindResult: (diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 8747bca52..388d6901c 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -558,8 +558,17 @@ declare global {capturePreview: () => Promise<string | null>findInPage: (query: string,- options: { forward: boolean; findNext: boolean; clientRequestId: number }- ) => Promise<number | null>+ options: {+ operation: 'start' | 'next' | 'previous'+ clientRequestId: number+ }+ ) => Promise<+ | { status: 'started'; requestId: number }+ | {+ status: 'unavailable'+ reason: 'no-active-view' | 'document-loading' | 'no-session'+ }+ >stopFindInPage: () => Promise<void>focusActive: () => Promise<boolean>onFindResult: (diff --git a/desktop-app/src/sandboxFindSession.ts b/desktop-app/src/sandboxFindSession.tsnew file mode 100644index 000000000..078694e81--- /dev/null+++ b/desktop-app/src/sandboxFindSession.ts@@ -0,0 +1,43 @@+export type NativeFindUpdate = {+ requestId: number+ activeMatchOrdinal: number+ matches: number+ finalUpdate: boolean+}++/**+ * Chromium can synchronously report a final zero before asynchronously+ * reporting the real result set for a newly started WebContentsView search.+ * Keep that provisional zero pending briefly; any substantive update for the+ * same native request supersedes it. A genuine zero becomes empty once the+ * producer has stayed quiescent for the settling window.+ */+export function createSandboxFindResultGate(+ deliver: (result: NativeFindUpdate) => void,+ settleMs = 50+): { accept: (result: NativeFindUpdate) => void; dispose: () => void } {+ let pendingZero: ReturnType<typeof setTimeout> | null = null+ let disposed = false+ const clearPending = () => {+ if (pendingZero !== null) clearTimeout(pendingZero)+ pendingZero = null+ }+ return {+ accept(result) {+ if (disposed) return+ clearPending()+ if (result.finalUpdate && result.matches === 0) {+ pendingZero = setTimeout(() => {+ pendingZero = null+ if (!disposed) deliver(result)+ }, settleMs)+ return+ }+ deliver(result)+ },+ dispose() {+ disposed = true+ clearPending()+ },+ }+}diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex 445fc8bf9..a214c6f2a 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -1,6 +1,7 @@import { BrowserWindow, WebContentsView, screen, session } from 'electron'import path from 'node:path'import { getActiveEnvKey } from './config.js'+import { createSandboxFindResultGate } from './sandboxFindSession.js'import { extractSandboxUiViewRoute, normalizeSandboxUiRoute } from './sandboxUiDeepLinks.js'import { touchSandboxUiPartition } from './sandboxUiPartitionGc.js'import {@@ -55,6 +56,21 @@ export type SandboxUiFindResult = {finalUpdate: boolean}+export type SandboxUiFindOperation = 'start' | 'next' | 'previous'++export type SandboxUiFindStartResult =+ | { status: 'started'; requestId: number }+ | { status: 'unavailable'; reason: 'no-active-view' | 'document-loading' | 'no-session' }++export function sandboxFindOptionsForOperation(operation: SandboxUiFindOperation): {+ forward: boolean+ findNext: boolean+} {+ return operation === 'start'+ ? { forward: true, findNext: true }+ : { forward: operation === 'next', findNext: false }+}+function toViewBounds(bounds: SandboxUiBounds,parentWindow: BrowserWindow@@ -115,8 +131,17 @@ type ActiveView = {cleanupClientRouteHandoff?: () => voidcleanupParentClosed?: () => voidcleanupShortcutRouting?: () => void+ cleanupDocumentLifecycle?: () => voidcleanupFindResults?: () => void- activeFindRequestId?: number+ documentGeneration: number+ documentReady: boolean+ findSession?: {+ query: string+ clientRequestId: number+ documentGeneration: number+ nativeRequestId: number+ complete: boolean+ }}let active: ActiveView | null = null@@ -289,6 +314,7 @@ async function teardownActive(reason: 'replaced' | 'closed' | 'parent_closed'):current.cleanupClientRouteHandoff?.()current.cleanupParentClosed?.()current.cleanupShortcutRouting?.()+ current.cleanupDocumentLifecycle?.()current.cleanupFindResults?.()if (!current.view.webContents.isDestroyed()) {current.view.webContents.stopFindInPage('clearSelection')@@ -425,6 +451,32 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidparentWindow,rpcProxyOrigin: proxyOriginUrl,cleanupParentClosed,+ documentGeneration: 0,+ documentReady: false,+ }++ const invalidateFindForNavigation = (): void => {+ if (!active || active.view !== view) return+ active.documentGeneration += 1+ active.documentReady = false+ stopActiveSandboxUiFind()+ }+ const onDidStartNavigation = (+ _event: Electron.Event,+ _url: string,+ _isInPlace: boolean,+ isMainFrame: boolean+ ): void => {+ if (isMainFrame) invalidateFindForNavigation()+ }+ const onDocumentReady = (): void => {+ if (active?.view === view) active.documentReady = true+ }+ view.webContents.on('did-start-navigation', onDidStartNavigation)+ view.webContents.on('did-finish-load', onDocumentReady)+ active.cleanupDocumentLifecycle = () => {+ view.webContents.removeListener('did-start-navigation', onDidStartNavigation)+ view.webContents.removeListener('did-finish-load', onDocumentReady)}active.cleanupShortcutRouting = wireDesktopShortcutRouting({@@ -729,30 +781,72 @@ export function beginSandboxUiFind(export function findInActiveSandboxUi(query: string,- options: { forward: boolean; findNext: boolean },+ operation: SandboxUiFindOperation,+ clientRequestId: number,onResult: (result: SandboxUiFindResult) => void-): number | null {- if (!active || active.view.webContents.isDestroyed()) return null+): SandboxUiFindStartResult {+ if (!active || active.view.webContents.isDestroyed()) {+ return { status: 'unavailable', reason: 'no-active-view' }+ }const current = active+ if (!current.documentReady) {+ return { status: 'unavailable', reason: 'document-loading' }+ }+ const continuing = operation !== 'start'+ if (+ continuing &&+ (!current.findSession ||+ !current.findSession.complete ||+ current.findSession.query !== query ||+ current.findSession.clientRequestId !== clientRequestId ||+ current.findSession.documentGeneration !== current.documentGeneration)+ ) {+ return { status: 'unavailable', reason: 'no-session' }+ }const webContents = current.view.webContentscurrent.cleanupFindResults?.()+ if (operation === 'start') webContents.stopFindInPage('clearSelection')+ const options = sandboxFindOptionsForOperation(operation)+ let completedSynchronously = false+ const documentGeneration = current.documentGeneration+ const resultGate = createSandboxFindResultGate(result => {+ if (result.finalUpdate && active === current) {+ completedSynchronously = true+ if (current.findSession?.nativeRequestId === result.requestId) {+ current.findSession.complete = true+ }+ }+ onResult(result)+ })const session = beginSandboxUiFind(webContents,query,options,- onResult,- () => active === current+ resultGate.accept,+ () =>+ active === current &&+ current.documentReady &&+ documentGeneration === current.documentGeneration)- current.cleanupFindResults = session.cleanup- current.activeFindRequestId = session.requestId- return session.requestId+ current.cleanupFindResults = () => {+ resultGate.dispose()+ session.cleanup()+ }+ current.findSession = {+ query,+ clientRequestId,+ documentGeneration,+ nativeRequestId: session.requestId,+ complete: completedSynchronously,+ }+ return { status: 'started', requestId: session.requestId }}export function stopActiveSandboxUiFind(): void {if (!active) returnactive.cleanupFindResults?.()active.cleanupFindResults = undefined- active.activeFindRequestId = undefined+ active.findSession = undefinedif (!active.view.webContents.isDestroyed()) {active.view.webContents.stopFindInPage('clearSelection')}diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex a31b9ca51..c6195ecd2 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -163,17 +163,16 @@ describe('ipc host status stream handlers', () => {const handler = testState.handlers.get('sandboxUi:findInPage')await expect(- Promise.resolve(handler?.(event, { query: '', forward: true, findNext: false }))+ Promise.resolve(handler?.(event, { query: '', operation: 'start', clientRequestId: 1 }))).rejects.toThrow('find query')await expect(- Promise.resolve(handler?.(event, { query: 'x', forward: 'yes', findNext: false }))- ).rejects.toThrow('direction')+ Promise.resolve(handler?.(event, { query: 'x', operation: 'sideways', clientRequestId: 1 }))+ ).rejects.toThrow('operation')await expect(Promise.resolve(handler?.(event, {query: 'invoice',- forward: true,- findNext: false,+ operation: 'start',clientRequestId: 0,}))@@ -184,18 +183,18 @@ describe('ipc host status stream handlers', () => {Promise.resolve(handler?.(event, {query: 'invoice',- forward: false,- findNext: true,+ operation: 'previous',clientRequestId: 4,}))).resolves.toBe(9)expect(service.findInActiveSandboxUi).toHaveBeenCalledWith('invoice',- { forward: false, findNext: true },+ 'previous',+ 4,expect.any(Function))- const onResult = service.findInActiveSandboxUi.mock.calls.at(-1)?.[2]+ const onResult = service.findInActiveSandboxUi.mock.calls.at(-1)?.[3]onResult?.({ requestId: 9, activeMatchOrdinal: 1, matches: 2, finalUpdate: true })expect(sender.send).toHaveBeenCalledWith('sandboxUi:findResult', {requestId: 9,diff --git a/desktop-app/test/native/sandbox-find.fixture.cjs b/desktop-app/test/native/sandbox-find.fixture.cjsnew file mode 100644index 000000000..b7e3725a1--- /dev/null+++ b/desktop-app/test/native/sandbox-find.fixture.cjs@@ -0,0 +1,117 @@+const { app, BrowserWindow, WebContentsView } = require('electron')+const assert = require('node:assert/strict')++function findFinal(webContents, query, options, createResultGate) {+ return new Promise((resolve, reject) => {+ let requestId = null+ const buffered = []+ const timeout = setTimeout(() => {+ webContents.removeListener('found-in-page', listener)+ reject(new Error(`Timed out finding ${JSON.stringify(query)}`))+ }, 5000)+ const finish = result => {+ if (!result.finalUpdate) return+ clearTimeout(timeout)+ webContents.removeListener('found-in-page', listener)+ gate.dispose()+ resolve(result)+ }+ const gate = createResultGate(finish)+ const inspect = result => {+ if (requestId === null) {+ buffered.push(result)+ return+ }+ if (result.requestId !== requestId) return+ gate.accept(result)+ }+ const listener = (_event, result) => inspect(result)+ webContents.on('found-in-page', listener)+ requestId = webContents.findInPage(query, options)+ buffered.splice(0).forEach(inspect)+ })+}++async function loadedView(window, body) {+ const view = new WebContentsView({+ webPreferences: { nodeIntegration: false, contextIsolation: true, sandbox: true },+ })+ window.contentView.addChildView(view)+ view.setBounds({ x: 0, y: 0, width: 500, height: 300 })+ await view.webContents.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(body)}`)+ return view+}++app.whenReady().then(async () => {+ const window = new BrowserWindow({ show: true, x: -10000, y: -10000, width: 600, height: 400 })+ try {+ const { createSandboxFindResultGate } = await import('../../dist/sandboxFindSession.js')+ let view = await loadedView(window, '<main>invoice invoice receipt</main>')+ const first = await findFinal(+ view.webContents,+ 'invoice',+ { forward: true, findNext: true },+ createSandboxFindResultGate+ )+ assert.equal(first.matches, 2, 'fresh find session returns both matches')+ assert.equal(first.activeMatchOrdinal, 1, 'fresh find selects first match')++ const next = await findFinal(+ view.webContents,+ 'invoice',+ { forward: true, findNext: false },+ createSandboxFindResultGate+ )+ assert.equal(next.activeMatchOrdinal, 2, 'same-query next advances')+ const previous = await findFinal(+ view.webContents,+ 'invoice',+ { forward: false, findNext: false },+ createSandboxFindResultGate+ )+ assert.equal(previous.activeMatchOrdinal, 1, 'previous reverses selection')++ const replacement = await findFinal(+ view.webContents,+ 'receipt',+ { forward: true, findNext: true },+ createSandboxFindResultGate+ )+ assert.equal(replacement.matches, 1, 'replacement query starts a fresh session')+ const empty = await findFinal(+ view.webContents,+ 'missing',+ { forward: true, findNext: true },+ createSandboxFindResultGate+ )+ assert.equal(empty.matches, 0, 'final zero is reported explicitly')++ view.setVisible(false)+ const hidden = await findFinal(+ view.webContents,+ 'invoice',+ { forward: true, findNext: true },+ createSandboxFindResultGate+ )+ assert.equal(hidden.matches, 2, 'hidden active WebContentsView remains searchable')++ view.webContents.stopFindInPage('clearSelection')+ window.contentView.removeChildView(view)+ view.webContents.close()+ view = await loadedView(window, '<main>replacement app value</main>')+ const remounted = await findFinal(+ view.webContents,+ 'replacement',+ { forward: true, findNext: true },+ createSandboxFindResultGate+ )+ assert.equal(remounted.matches, 1, 'a remounted view starts independently')+ window.contentView.removeChildView(view)+ view.webContents.close()+ console.log('sandbox find native fixture: PASS')+ app.exit(0)+ } catch (error) {+ console.error(error)+ app.exit(1)+ }+})diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsxindex 1cd5227f2..52f7e912c 100644--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx@@ -146,6 +146,14 @@ const APP_PAGE_SIZE = 6let pendingSandboxUiUnmountCleanup: number | null = nulllet nextSandboxFindClientRequestId = 0+type AppFindState =+ | { status: 'idle' }+ | { status: 'pending' }+ | { status: 'results'; current: number; total: number }+ | { status: 'empty' }+ | { status: 'unavailable'; reason: string }+ | { status: 'error'; message: string }+export function SandboxUiPage({boundsRefreshKey = 0,conversationOrigin = null,@@ -172,10 +180,11 @@ export function SandboxUiPage({const [embedPreviewDataUrl, setEmbedPreviewDataUrl] = useState<string | null>(null)const [localSearchOpen, setLocalSearchOpen] = useState(false)const [localSearchQuery, setLocalSearchQuery] = useState('')- const [localSearchResult, setLocalSearchResult] = useState({ current: 0, total: 0 })+ const [localSearchState, setLocalSearchState] = useState<AppFindState>({ status: 'idle' })const embedSlotRef = useRef<HTMLDivElement>(null)const localSearchInputRef = useRef<HTMLInputElement>(null)const activeFindClientRequestIdRef = useRef<number | null>(null)+ const localSearchStateRef = useRef<AppFindState>({ status: 'idle' })const lastLocalSearchRequestIdRef = useRef(0)const localSearchPreviousFocusRef = useRef<HTMLElement | null>(null)const lastShortcutOpenRequestIdRef = useRef(0)@@ -225,7 +234,13 @@ export function SandboxUiPage({useEffect(() => {return window.clerum.sandboxUi.onFindResult(result => {if (result.clientRequestId !== activeFindClientRequestIdRef.current) return- setLocalSearchResult({ current: result.activeMatchOrdinal, total: result.matches })+ if (!result.finalUpdate) return+ const next: AppFindState =+ result.matches > 0+ ? { status: 'results', current: result.activeMatchOrdinal, total: result.matches }+ : { status: 'empty' }+ localSearchStateRef.current = next+ setLocalSearchState(next)})}, [])@@ -234,7 +249,8 @@ export function SandboxUiPage({activeFindClientRequestIdRef.current = nullsetLocalSearchOpen(false)setLocalSearchQuery('')- setLocalSearchResult({ current: 0, total: 0 })+ localSearchStateRef.current = { status: 'idle' }+ setLocalSearchState({ status: 'idle' })void window.clerum.sandboxUi.stopFindInPage().then(() => window.clerum.sandboxUi.focusActive())@@ -249,17 +265,49 @@ export function SandboxUiPage({}, [])const runLocalSearch = useCallback(- async (query: string, options: { forward: boolean; findNext: boolean }) => {+ async (query: string, operation: 'start' | 'next' | 'previous') => {if (!query.trim()) {activeFindClientRequestIdRef.current = null- setLocalSearchResult({ current: 0, total: 0 })+ localSearchStateRef.current = { status: 'idle' }+ setLocalSearchState({ status: 'idle' })await window.clerum.sandboxUi.stopFindInPage()return}- if (!options.findNext) setLocalSearchResult({ current: 0, total: 0 })- const clientRequestId = ++nextSandboxFindClientRequestId+ if (operation !== 'start' && localSearchStateRef.current.status !== 'results') return+ const clientRequestId =+ operation === 'start'+ ? ++nextSandboxFindClientRequestId+ : activeFindClientRequestIdRef.current+ if (clientRequestId === null) returnactiveFindClientRequestIdRef.current = clientRequestId- await window.clerum.sandboxUi.findInPage(query, { ...options, clientRequestId })+ localSearchStateRef.current = { status: 'pending' }+ setLocalSearchState({ status: 'pending' })+ try {+ const response = await window.clerum.sandboxUi.findInPage(query, {+ operation,+ clientRequestId,+ })+ if (clientRequestId !== activeFindClientRequestIdRef.current) return+ if (response.status === 'unavailable') {+ const next: AppFindState = {+ status: 'unavailable',+ reason:+ response.reason === 'document-loading'+ ? 'App is still loading'+ : 'Search is not available',+ }+ localSearchStateRef.current = next+ setLocalSearchState(next)+ }+ } catch (error) {+ if (clientRequestId !== activeFindClientRequestIdRef.current) return+ const next: AppFindState = {+ status: 'error',+ message: error instanceof Error ? error.message : 'Search failed',+ }+ localSearchStateRef.current = next+ setLocalSearchState(next)+ }},[])@@ -561,7 +609,7 @@ export function SandboxUiPage({onChange={event => {const query = event.currentTarget.valuesetLocalSearchQuery(query)- void runLocalSearch(query, { forward: true, findNext: false })+ void runLocalSearch(query, 'start')}}onKeyDown={event => {if (event.key === 'Escape') {@@ -569,24 +617,30 @@ export function SandboxUiPage({stopLocalSearch()} else if (event.key === 'Enter') {event.preventDefault()- void runLocalSearch(localSearchQuery, {- forward: !event.shiftKey,- findNext: true,- })+ void runLocalSearch(localSearchQuery, event.shiftKey ? 'previous' : 'next')}}}placeholder="Find in current app"value={localSearchQuery}/><span className="current-content-search__count" role="status" aria-live="polite">- {localSearchResult.current}/{localSearchResult.total}+ {localSearchState.status === 'pending'+ ? 'Searching…'+ : localSearchState.status === 'results'+ ? `${localSearchState.current}/${localSearchState.total}`+ : localSearchState.status === 'empty'+ ? '0/0'+ : localSearchState.status === 'unavailable'+ ? localSearchState.reason+ : localSearchState.status === 'error'+ ? 'Search failed'+ : '—'}</span><Buttonaria-label="Previous app match"color="neutral"- onClick={() =>- void runLocalSearch(localSearchQuery, { forward: false, findNext: true })- }+ disabled={localSearchState.status !== 'results'}+ onClick={() => void runLocalSearch(localSearchQuery, 'previous')}size="xs"variant="ghost">@@ -595,9 +649,8 @@ export function SandboxUiPage({<Buttonaria-label="Next app match"color="neutral"- onClick={() =>- void runLocalSearch(localSearchQuery, { forward: true, findNext: true })- }+ disabled={localSearchState.status !== 'results'}+ onClick={() => void runLocalSearch(localSearchQuery, 'next')}size="xs"variant="ghost">diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsxindex a4afe9b6d..e35e5955e 100644--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx@@ -39,7 +39,7 @@ describe('SandboxUiPage', () => {vi.clearAllMocks()sandboxUi.setBounds.mockResolvedValue(undefined)sandboxUi.setVisible.mockResolvedValue(undefined)- sandboxUi.findInPage.mockResolvedValue(17)+ sandboxUi.findInPage.mockResolvedValue({ status: 'started', requestId: 17 })sandboxUi.onFindResult.mockImplementation(callback => {emitFindResult = callbackreturn vi.fn()@@ -206,16 +206,24 @@ describe('SandboxUiPage', () => {fireEvent.change(input, { target: { value: 'invoice' } })await waitFor(() => {expect(sandboxUi.findInPage).toHaveBeenCalledWith('invoice', {- forward: true,- findNext: false,+ operation: 'start',clientRequestId: expect.any(Number),})})+ expect(screen.getByRole('status').textContent).toBe('Searching…')+ const startOptions = sandboxUi.findInPage.mock.calls.at(-1)?.[1]+ emitFindResult?.({+ requestId: 17,+ clientRequestId: startOptions.clientRequestId,+ activeMatchOrdinal: 1,+ matches: 2,+ finalUpdate: true,+ })+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('1/2'))fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })expect(sandboxUi.findInPage).toHaveBeenLastCalledWith('invoice', {- forward: false,- findNext: true,- clientRequestId: expect.any(Number),+ operation: 'previous',+ clientRequestId: startOptions.clientRequestId,})fireEvent.keyDown(input, { key: 'Escape' })await waitFor(() => {@@ -268,7 +276,7 @@ describe('SandboxUiPage', () => {matches: 9,finalUpdate: true,})- expect(screen.getByRole('status').textContent).toBe('0/0')+ expect(screen.getByRole('status').textContent).toBe('Searching…')emitFindResult?.({requestId: 18,clientRequestId: nextOptions.clientRequestId,@@ -319,7 +327,7 @@ describe('SandboxUiPage', () => {matches: 7,finalUpdate: true,})- expect(screen.getByRole('status').textContent).toBe('0/0')+ expect(screen.getByRole('status').textContent).toBe('Searching…')})it('opens a deep-linked app at its stable entry point before handing off the client route', async () => {