Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): preserve first sandbox find result (R1-M3)
Josué0ff9ca2491b1
diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.tsindex 5e4c59478..5a9ac7cb5 100644--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts@@ -14,6 +14,43 @@ import {} from '../sandboxUiDriver.js'describe('sandbox WebContents local find', () => {+ it('does not lose a native result delivered as the first request starts', () => {+ let listener: ((event: Electron.Event, result: Electron.FoundInPageResult) => void) | undefined+ const result = {+ requestId: 41,+ activeMatchOrdinal: 1,+ matches: 2,+ selectionArea: { x: 0, y: 0, width: 1, height: 1 },+ finalUpdate: true,+ }+ const webContents = {+ findInPage: vi.fn(() => {+ listener?.({} as Electron.Event, result)+ return 41+ }),+ on: vi.fn((_name: string, callback: typeof listener) => {+ listener = callback+ return webContents+ }),+ removeListener: vi.fn(() => webContents),+ }+ const onResult = vi.fn()++ beginSandboxUiFind(+ webContents as never,+ 'invoice',+ { forward: true, findNext: false },+ onResult+ )++ expect(onResult).toHaveBeenCalledWith({+ requestId: 41,+ activeMatchOrdinal: 1,+ matches: 2,+ finalUpdate: true,+ })+ })+it('uses the native producer, filters request IDs, minimizes results, and removes its listener', () => {let listener: ((event: Electron.Event, result: Electron.FoundInPageResult) => void) | undefinedconst webContents = {diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 61e9cc12e..360bd14e9 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -1546,7 +1546,15 @@ export function registerIpcHandlers(service: AppService): void {ipcMain.handle('sandboxUi:findInPage',- async (event, payload: { query?: unknown; forward?: unknown; findNext?: unknown }) => {+ async (+ event,+ payload: {+ query?: unknown+ forward?: unknown+ findNext?: unknown+ clientRequestId?: unknown+ }+ ) => {assertTrustedSender(event)const query = typeof payload?.query === 'string' ? payload.query : ''if (!query.trim() || query.length > 500) {@@ -1555,11 +1563,17 @@ export function registerIpcHandlers(service: AppService): void {if (typeof payload?.forward !== 'boolean' || typeof payload?.findNext !== 'boolean') {throw new Error('find direction options must be boolean')}+ if (!Number.isSafeInteger(payload?.clientRequestId) || Number(payload.clientRequestId) <= 0) {+ throw new Error('find client request ID must be a positive safe integer')+ }+ const clientRequestId = Number(payload.clientRequestId)return service.findInActiveSandboxUi(query,{ forward: payload.forward, findNext: payload.findNext },result => {- if (!event.sender.isDestroyed()) event.sender.send('sandboxUi:findResult', 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 0738f32ba..bf8c81c9e 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -500,13 +500,17 @@ const clerum = Object.freeze({ipcRenderer.invoke('sandboxUi:setBounds', { bounds }),setVisible: (visible: boolean) => ipcRenderer.invoke('sandboxUi:setVisible', { visible }),capturePreview: () => ipcRenderer.invoke('sandboxUi:capturePreview'),- findInPage: (query: string, options: { forward: boolean; findNext: boolean }) =>+ findInPage: (+ query: string,+ options: { forward: boolean; findNext: boolean; clientRequestId: number }+ ) =>ipcRenderer.invoke('sandboxUi:findInPage', { query, ...options }) as Promise<number | null>,stopFindInPage: () => ipcRenderer.invoke('sandboxUi:stopFindInPage') as Promise<void>,focusActive: () => ipcRenderer.invoke('sandboxUi:focusActive') as Promise<boolean>,onFindResult: (callback: (result: {requestId: number+ clientRequestId: numberactiveMatchOrdinal: numbermatches: numberfinalUpdate: boolean@@ -516,12 +520,15 @@ const clerum = Object.freeze({const value = result as Record<string, unknown>if (Number.isInteger(value?.requestId) &&+ Number.isSafeInteger(value?.clientRequestId) &&+ Number(value.clientRequestId) > 0 &&Number.isInteger(value?.activeMatchOrdinal) &&Number.isInteger(value?.matches) &&typeof value?.finalUpdate === 'boolean') {callback({requestId: Number(value.requestId),+ clientRequestId: Number(value.clientRequestId),activeMatchOrdinal: Number(value.activeMatchOrdinal),matches: Number(value.matches),finalUpdate: value.finalUpdate,diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex ab155851b..8747bca52 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -558,13 +558,14 @@ declare global {capturePreview: () => Promise<string | null>findInPage: (query: string,- options: { forward: boolean; findNext: boolean }+ options: { forward: boolean; findNext: boolean; clientRequestId: number }) => Promise<number | null>stopFindInPage: () => Promise<void>focusActive: () => Promise<boolean>onFindResult: (callback: (result: {requestId: number+ clientRequestId: numberactiveMatchOrdinal: numbermatches: numberfinalUpdate: booleandiff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex e6732a48f..445fc8bf9 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -702,8 +702,13 @@ export function beginSandboxUiFind(onResult: (result: SandboxUiFindResult) => void,isCurrent: () => boolean = () => true): { requestId: number; cleanup: () => void } {- let requestId = -1- const listener = (_event: Electron.Event, result: Electron.FoundInPageResult) => {+ let requestId: number | null = null+ const pendingResults: Electron.FoundInPageResult[] = []+ const deliver = (result: Electron.FoundInPageResult) => {+ if (requestId === null) {+ pendingResults.push(result)+ return+ }if (!isCurrent() || result.requestId !== requestId) returnonResult({requestId: result.requestId,@@ -712,8 +717,10 @@ export function beginSandboxUiFind(finalUpdate: result.finalUpdate,})}+ const listener = (_event: Electron.Event, result: Electron.FoundInPageResult) => deliver(result)webContents.on('found-in-page', listener)requestId = webContents.findInPage(query, options)+ for (const result of pendingResults.splice(0)) deliver(result)return {requestId,cleanup: () => webContents.removeListener('found-in-page', listener),diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex a5ca10d25..a31b9ca51 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -24,6 +24,7 @@ function makeTrustedEvent(senderId = 77) {const destroyedCallbacks: Array<() => void> = []const sender = {id: senderId,+ isDestroyed: vi.fn(() => false),send: vi.fn(),once: vi.fn((eventName: string, callback: () => void) => {if (eventName === 'destroyed') destroyedCallbacks.push(callback)@@ -158,7 +159,7 @@ describe('ipc host status stream handlers', () => {})it('validates and forwards only bounded trusted sandbox find requests', async () => {- const { event } = makeTrustedEvent()+ const { event, sender } = makeTrustedEvent()const handler = testState.handlers.get('sandboxUi:findInPage')await expect(@@ -167,16 +168,42 @@ describe('ipc host status stream handlers', () => {await expect(Promise.resolve(handler?.(event, { query: 'x', forward: 'yes', findNext: false }))).rejects.toThrow('direction')+ await expect(+ Promise.resolve(+ handler?.(event, {+ query: 'invoice',+ forward: true,+ findNext: false,+ clientRequestId: 0,+ })+ )+ ).rejects.toThrow('client request ID')expect(service.findInActiveSandboxUi).not.toHaveBeenCalled()await expect(- Promise.resolve(handler?.(event, { query: 'invoice', forward: false, findNext: true }))+ Promise.resolve(+ handler?.(event, {+ query: 'invoice',+ forward: false,+ findNext: true,+ clientRequestId: 4,+ })+ )).resolves.toBe(9)expect(service.findInActiveSandboxUi).toHaveBeenCalledWith('invoice',{ forward: false, findNext: true },expect.any(Function))+ const onResult = service.findInActiveSandboxUi.mock.calls.at(-1)?.[2]+ onResult?.({ requestId: 9, activeMatchOrdinal: 1, matches: 2, finalUpdate: true })+ expect(sender.send).toHaveBeenCalledWith('sandboxUi:findResult', {+ requestId: 9,+ clientRequestId: 4,+ activeMatchOrdinal: 1,+ matches: 2,+ finalUpdate: true,+ })})it('stops active sandbox find through a trusted sender only', async () => {diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsxindex 76c8c1367..92f7783bb 100644--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx@@ -174,7 +174,8 @@ export function SandboxUiPage({const [localSearchResult, setLocalSearchResult] = useState({ current: 0, total: 0 })const embedSlotRef = useRef<HTMLDivElement>(null)const localSearchInputRef = useRef<HTMLInputElement>(null)- const activeFindRequestIdRef = useRef<number | null>(null)+ const nextFindClientRequestIdRef = useRef(0)+ const activeFindClientRequestIdRef = useRef<number | null>(null)const lastLocalSearchRequestIdRef = useRef(0)const localSearchPreviousFocusRef = useRef<HTMLElement | null>(null)const lastShortcutOpenRequestIdRef = useRef(0)@@ -223,14 +224,14 @@ export function SandboxUiPage({useEffect(() => {return window.clerum.sandboxUi.onFindResult(result => {- if (result.requestId !== activeFindRequestIdRef.current) return+ if (result.clientRequestId !== activeFindClientRequestIdRef.current) returnsetLocalSearchResult({ current: result.activeMatchOrdinal, total: result.matches })})}, [])const stopLocalSearch = useCallback(() => {const previous = localSearchPreviousFocusRef.current- activeFindRequestIdRef.current = null+ activeFindClientRequestIdRef.current = nullsetLocalSearchOpen(false)setLocalSearchQuery('')setLocalSearchResult({ current: 0, total: 0 })@@ -250,12 +251,15 @@ export function SandboxUiPage({const runLocalSearch = useCallback(async (query: string, options: { forward: boolean; findNext: boolean }) => {if (!query.trim()) {- activeFindRequestIdRef.current = null+ activeFindClientRequestIdRef.current = nullsetLocalSearchResult({ current: 0, total: 0 })await window.clerum.sandboxUi.stopFindInPage()return}- activeFindRequestIdRef.current = await window.clerum.sandboxUi.findInPage(query, options)+ if (!options.findNext) setLocalSearchResult({ current: 0, total: 0 })+ const clientRequestId = ++nextFindClientRequestIdRef.current+ activeFindClientRequestIdRef.current = clientRequestId+ await window.clerum.sandboxUi.findInPage(query, { ...options, clientRequestId })},[])diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsxindex 000d2bbf0..724578147 100644--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx@@ -20,6 +20,15 @@ const sandboxUi = {onClosed: vi.fn(() => vi.fn()),onRefreshError: vi.fn(() => vi.fn()),}+let emitFindResult:+ | ((result: {+ requestId: number+ clientRequestId: number+ activeMatchOrdinal: number+ matches: number+ finalUpdate: boolean+ }) => void)+ | null = nullfunction installClerumApi(): void {;(window as unknown as { clerum: unknown }).clerum = { sandboxUi }@@ -31,6 +40,10 @@ describe('SandboxUiPage', () => {sandboxUi.setBounds.mockResolvedValue(undefined)sandboxUi.setVisible.mockResolvedValue(undefined)sandboxUi.findInPage.mockResolvedValue(17)+ sandboxUi.onFindResult.mockImplementation(callback => {+ emitFindResult = callback+ return vi.fn()+ })sandboxUi.stopFindInPage.mockResolvedValue(undefined)sandboxUi.focusActive.mockResolvedValue(true)installClerumApi()@@ -195,12 +208,14 @@ describe('SandboxUiPage', () => {expect(sandboxUi.findInPage).toHaveBeenCalledWith('invoice', {forward: true,findNext: false,+ clientRequestId: expect.any(Number),})})fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })expect(sandboxUi.findInPage).toHaveBeenLastCalledWith('invoice', {forward: false,findNext: true,+ clientRequestId: expect.any(Number),})fireEvent.keyDown(input, { key: 'Escape' })await waitFor(() => {@@ -210,6 +225,60 @@ describe('SandboxUiPage', () => {expect(screen.queryByRole('textbox', { name: 'Find in current app' })).toBeNull()})+ it('accepts the first native find result before the invoke response resolves', async () => {+ sandboxUi.listApps.mockResolvedValueOnce({+ apps: [+ {+ appRef: 'sandbox-recipes/sales-crm',+ title: "Andy's Sales CRM",+ defaultPath: '/',+ ready: true,+ phase: 'active',+ updatedAt: null,+ },+ ],+ })+ sandboxUi.open.mockResolvedValueOnce(undefined)+ sandboxUi.findInPage.mockReturnValueOnce(new Promise(() => undefined))++ render(<SandboxUiPage localSearchRequestId={1} />)+ fireEvent.click(await screen.findByRole('button', { name: "Open Andy's Sales CRM" }))+ const input = await screen.findByRole('textbox', { name: 'Find in current app' })+ fireEvent.change(input, { target: { value: 'invoice' } })+ const options = sandboxUi.findInPage.mock.calls.at(-1)?.[1]+ expect(options?.clientRequestId).toEqual(expect.any(Number))++ emitFindResult?.({+ requestId: 17,+ clientRequestId: options.clientRequestId,+ activeMatchOrdinal: 1,+ matches: 2,+ finalUpdate: true,+ })++ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('1/2'))++ fireEvent.change(input, { target: { value: 'receipt' } })+ const nextOptions = sandboxUi.findInPage.mock.calls.at(-1)?.[1]+ expect(nextOptions.clientRequestId).not.toBe(options.clientRequestId)+ emitFindResult?.({+ requestId: 17,+ clientRequestId: options.clientRequestId,+ activeMatchOrdinal: 2,+ matches: 9,+ finalUpdate: true,+ })+ expect(screen.getByRole('status').textContent).toBe('0/0')+ emitFindResult?.({+ requestId: 18,+ clientRequestId: nextOptions.clientRequestId,+ activeMatchOrdinal: 1,+ matches: 1,+ finalUpdate: true,+ })+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('1/1'))+ })+it('opens a deep-linked app at its stable entry point before handing off the client route', async () => {sandboxUi.listApps.mockResolvedValueOnce({ apps: [] })sandboxUi.open.mockResolvedValueOnce(undefined)