Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): r3-m1 focus contextual app search after mount

Josué03700d70d1e3
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 4b32ae2c9..b76db7d60 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -15,6 +15,7 @@
"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",
+ "test:native:sandbox-shortcut-focus": "npm run build:main --silent && node ./scripts/run-native-sandbox-shortcut-focus.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-shortcut-focus.mjs b/desktop-app/scripts/run-native-sandbox-shortcut-focus.mjs
new file mode 100644
index 000000000..bdc39c994
--- /dev/null
+++ b/desktop-app/scripts/run-native-sandbox-shortcut-focus.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-shortcut-focus.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/test/native/sandbox-shortcut-focus.fixture.cjs b/desktop-app/test/native/sandbox-shortcut-focus.fixture.cjs
new file mode 100644
index 000000000..6a19bd59f
--- /dev/null
+++ b/desktop-app/test/native/sandbox-shortcut-focus.fixture.cjs
@@ -0,0 +1,90 @@
+const assert = require('node:assert/strict')
+const { app, BrowserWindow, WebContentsView } = require('electron')
+
+async function waitFor(check, message) {
+ const deadline = Date.now() + 5000
+ while (Date.now() < deadline) {
+ if (await check()) return
+ await new Promise(resolve => setTimeout(resolve, 25))
+ }
+ throw new Error(message)
+}
+
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({
+ show: true,
+ x: -10000,
+ y: -10000,
+ width: 600,
+ height: 400,
+ webPreferences: { contextIsolation: false, nodeIntegration: true },
+ })
+ let view = null
+ try {
+ await window.loadURL(
+ `data:text/html;charset=utf-8,${encodeURIComponent(`
+ <input id="find" hidden aria-label="Find in current app" />
+ <script>
+ const { ipcRenderer } = require('electron')
+ ipcRenderer.on('shortcuts:command', (_event, command) => {
+ if (command.commandId !== 'search.current') return
+ const input = document.getElementById('find')
+ input.hidden = false
+ input.focus()
+ })
+ </script>
+ `)}`
+ )
+
+ view = new WebContentsView({
+ webPreferences: { contextIsolation: true, nodeIntegration: false, 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('<input value="sandbox owns focus" />')}`
+ )
+
+ const { wireDesktopShortcutRouting } = await import('../../dist/shortcutRouter.js')
+ const dispose = wireDesktopShortcutRouting({
+ platform: 'darwin',
+ source: 'sandbox',
+ sourceWebContents: view.webContents,
+ trustedRenderer: window.webContents,
+ })
+
+ view.webContents.focus()
+ assert.equal(view.webContents.isFocused(), true, 'sandbox starts with native focus')
+ view.webContents.sendInputEvent({
+ type: 'keyDown',
+ keyCode: 'F',
+ modifiers: ['meta', 'shift'],
+ })
+
+ await waitFor(
+ () => window.webContents.executeJavaScript("document.activeElement?.id === 'find'"),
+ 'trusted current-content input did not receive focus after one shortcut'
+ )
+ window.webContents.sendInputEvent({ type: 'char', keyCode: 'i' })
+ await waitFor(
+ () => window.webContents.executeJavaScript("document.getElementById('find').value === 'i'"),
+ 'trusted current-content input was not ready for immediate typing'
+ )
+
+ view.webContents.focus()
+ assert.equal(view.webContents.isFocused(), true, 'close path restores native sandbox focus')
+ dispose()
+ window.contentView.removeChildView(view)
+ view.webContents.close()
+ view = null
+ console.log('sandbox shortcut focus native fixture: PASS')
+ app.exit(0)
+ } catch (error) {
+ console.error(error)
+ if (view && !view.webContents.isDestroyed()) {
+ window.contentView.removeChildView(view)
+ view.webContents.close()
+ }
+ app.exit(1)
+ }
+})
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 12701bcae..ed9eb4a3a 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -574,6 +574,7 @@ export function App() {
}, [vm.authenticatedPrincipalIdentity])
const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp) => {
+ setSandboxLocalSearchRequestId(0)
setSandboxUiMounted(false)
setActiveSandboxUiApp(app)
}, [])
@@ -1284,7 +1285,7 @@ export function App() {
return
}
if (commandId === 'search.current') {
- if (activeSandboxUiApp && vm.navItem === DESKTOP_ROUTES.apps) {
+ if (activeSandboxUiApp && sandboxUiMounted && vm.navItem === DESKTOP_ROUTES.apps) {
closeChatLocalSearch(false)
setSandboxLocalSearchRequestId(value => value + 1)
} else if (vm.navItem === DESKTOP_ROUTES.chat && vm.activeChatId) {
@@ -1303,6 +1304,7 @@ export function App() {
handleNewChatViewTab,
handleSidebarNavSelect,
revealChatViewTab,
+ sandboxUiMounted,
vm.activeChatId,
vm.handleNavSelect,
vm.handleLogout,
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index 7784a5174..4303ecdc9 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -333,6 +333,9 @@ describe('App deep-link orchestration', () => {
})
})
+ act(() => emitCommand?.('search.current'))
+ expect(sandboxUiPageHarness.props?.localSearchRequestId).toBe(0)
+ act(() => sandboxUiPageHarness.props?.onEmbeddedAppMounted?.())
act(() => emitCommand?.('search.current'))
expect(sandboxUiPageHarness.props?.localSearchRequestId).toBe(1)
expect(appHeaderHarness.props?.searchFocusRequestId).toBe(0)
diff --git a/desktop-app/ui/src/components/SandboxCurrentContentSearch/index.tsx b/desktop-app/ui/src/components/SandboxCurrentContentSearch/index.tsx
new file mode 100644
index 000000000..e8c141b4c
--- /dev/null
+++ b/desktop-app/ui/src/components/SandboxCurrentContentSearch/index.tsx
@@ -0,0 +1,82 @@
+import { useLayoutEffect, useRef } from 'react'
+import { Button, TextInput } from '@components/Common'
+import type { SandboxCurrentContentSearchProps } from './types'
+
+export default function SandboxCurrentContentSearch({
+ focusRequestId,
+ onClose,
+ onMove,
+ onQueryChange,
+ query,
+ state,
+}: SandboxCurrentContentSearchProps) {
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ useLayoutEffect(() => {
+ inputRef.current?.focus()
+ }, [focusRequestId])
+
+ return (
+ <div className="current-content-search" role="search" aria-label="Search current app">
+ <TextInput
+ ref={inputRef}
+ aria-label="Find in current app"
+ className="current-content-search__input"
+ onChange={event => onQueryChange(event.currentTarget.value)}
+ onKeyDown={event => {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ onClose()
+ } else if (event.key === 'Enter') {
+ event.preventDefault()
+ onMove(event.shiftKey ? 'previous' : 'next')
+ }
+ }}
+ placeholder="Find in current app"
+ value={query}
+ />
+ <span className="current-content-search__count" role="status" aria-live="polite">
+ {state.status === 'pending'
+ ? 'Searching…'
+ : state.status === 'results'
+ ? `${state.current}/${state.total}`
+ : state.status === 'empty'
+ ? '0/0'
+ : state.status === 'unavailable'
+ ? state.reason
+ : state.status === 'error'
+ ? 'Search failed'
+ : '—'}
+ </span>
+ <Button
+ aria-label="Previous app match"
+ color="neutral"
+ disabled={state.status !== 'results'}
+ onClick={() => onMove('previous')}
+ size="xs"
+ variant="ghost"
+ >
+ ↑
+ </Button>
+ <Button
+ aria-label="Next app match"
+ color="neutral"
+ disabled={state.status !== 'results'}
+ onClick={() => onMove('next')}
+ size="xs"
+ variant="ghost"
+ >
+ ↓
+ </Button>
+ <Button
+ aria-label="Close current app search"
+ color="neutral"
+ onClick={onClose}
+ size="xs"
+ variant="ghost"
+ >
+ ×
+ </Button>
+ </div>
+ )
+}
diff --git a/desktop-app/ui/src/components/SandboxCurrentContentSearch/types.ts b/desktop-app/ui/src/components/SandboxCurrentContentSearch/types.ts
new file mode 100644
index 000000000..70034a214
--- /dev/null
+++ b/desktop-app/ui/src/components/SandboxCurrentContentSearch/types.ts
@@ -0,0 +1,16 @@
+export type AppFindState =
+ | { status: 'idle' }
+ | { status: 'pending' }
+ | { status: 'results'; current: number; total: number }
+ | { status: 'empty' }
+ | { status: 'unavailable'; reason: string }
+ | { status: 'error'; message: string }
+
+export type SandboxCurrentContentSearchProps = {
+ focusRequestId: number
+ onClose: () => void
+ onMove: (operation: 'next' | 'previous') => void
+ onQueryChange: (query: string) => void
+ query: string
+ state: AppFindState
+}
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 3c20cc9a1..2b3c5cbfe 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -1,5 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
-import { Button, StatusBanner, TextInput } from '@components/Common'
+import { Button, StatusBanner } from '@components/Common'
+import SandboxCurrentContentSearch from '../components/SandboxCurrentContentSearch'
+import type { AppFindState } from '../components/SandboxCurrentContentSearch/types'
import {
IconChat,
IconClose,
@@ -146,14 +148,6 @@ const APP_PAGE_SIZE = 6
let pendingSandboxUiUnmountCleanup: number | null = null
let 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({
actionRequest = null,
boundsRefreshKey = 0,
@@ -184,7 +178,6 @@ export function SandboxUiPage({
const [localSearchQuery, setLocalSearchQuery] = useState('')
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)
@@ -322,7 +315,6 @@ export function SandboxUiPage({
lastLocalSearchRequestIdRef.current = localSearchRequestId
localSearchPreviousFocusRef.current = document.activeElement as HTMLElement | null
setLocalSearchOpen(true)
- requestAnimationFrame(() => localSearchInputRef.current?.focus())
}, [launch.kind, localSearchRequestId])
useEffect(() => {
@@ -618,71 +610,17 @@ export function SandboxUiPage({
/>
)}
{localSearchOpen ? (
- <div className="current-content-search" role="search" aria-label="Search current app">
- <TextInput
- ref={localSearchInputRef}
- aria-label="Find in current app"
- className="current-content-search__input"
- onChange={event => {
- const query = event.currentTarget.value
- setLocalSearchQuery(query)
- void runLocalSearch(query, 'start')
- }}
- onKeyDown={event => {
- if (event.key === 'Escape') {
- event.preventDefault()
- stopLocalSearch()
- } else if (event.key === 'Enter') {
- event.preventDefault()
- 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">
- {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>
- <Button
- aria-label="Previous app match"
- color="neutral"
- disabled={localSearchState.status !== 'results'}
- onClick={() => void runLocalSearch(localSearchQuery, 'previous')}
- size="xs"
- variant="ghost"
- >
- ↑
- </Button>
- <Button
- aria-label="Next app match"
- color="neutral"
- disabled={localSearchState.status !== 'results'}
- onClick={() => void runLocalSearch(localSearchQuery, 'next')}
- size="xs"
- variant="ghost"
- >
- ↓
- </Button>
- <Button
- aria-label="Close current app search"
- color="neutral"
- onClick={stopLocalSearch}
- size="xs"
- variant="ghost"
- >
- ×
- </Button>
- </div>
+ <SandboxCurrentContentSearch
+ focusRequestId={localSearchRequestId}
+ onClose={stopLocalSearch}
+ onMove={operation => void runLocalSearch(localSearchQuery, operation)}
+ onQueryChange={query => {
+ setLocalSearchQuery(query)
+ void runLocalSearch(query, 'start')
+ }}
+ query={localSearchQuery}
+ state={localSearchState}
+ />
) : null}
{/* The slot div is the rectangle the WebContentsView floats above
after the selected app completes its initial load. */}
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx
new file mode 100644
index 000000000..e58b1250a
--- /dev/null
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx
@@ -0,0 +1,133 @@
+// @vitest-environment jsdom
+import React from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { SandboxUiPage } from '../SandboxUiPage'
+
+const sandboxUi = {
+ listApps: vi.fn(),
+ open: vi.fn(),
+ close: vi.fn(),
+ reload: vi.fn(),
+ copyDeepLink: vi.fn(),
+ setBounds: vi.fn(),
+ setVisible: vi.fn(),
+ capturePreview: vi.fn(),
+ findInPage: vi.fn(),
+ stopFindInPage: vi.fn(),
+ focusActive: vi.fn(),
+ onFindResult: vi.fn(() => vi.fn()),
+ onClosed: vi.fn(() => vi.fn()),
+ onRefreshError: vi.fn(() => vi.fn()),
+}
+
+const apps = [
+ {
+ appRef: 'sandbox-recipes/sales-crm',
+ title: 'Sales CRM',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ updatedAt: null,
+ },
+]
+
+function installSandboxBridge(): void {
+ ;(window as unknown as { clerum: unknown }).clerum = { sandboxUi }
+}
+
+async function openApp(): Promise<void> {
+ fireEvent.click(await screen.findByRole('button', { name: 'Open Sales CRM' }))
+ await screen.findByRole('button', { name: 'Back to apps' })
+}
+
+describe('SandboxUiPage contextual-search focus ownership', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ sandboxUi.listApps.mockResolvedValue({ apps })
+ sandboxUi.open.mockResolvedValue(undefined)
+ sandboxUi.close.mockResolvedValue(undefined)
+ sandboxUi.setBounds.mockResolvedValue(undefined)
+ sandboxUi.setVisible.mockResolvedValue(undefined)
+ sandboxUi.capturePreview.mockResolvedValue(null)
+ sandboxUi.findInPage.mockResolvedValue({ status: 'started', requestId: 17 })
+ sandboxUi.stopFindInPage.mockResolvedValue(undefined)
+ sandboxUi.focusActive.mockResolvedValue(true)
+ installSandboxBridge()
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ callback(0)
+ return 1
+ })
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = vi.fn()
+ unobserve = vi.fn()
+ disconnect = vi.fn()
+ }
+ )
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 12,
+ left: 16,
+ right: 416,
+ bottom: 312,
+ width: 400,
+ height: 300,
+ toJSON: () => ({}),
+ } as DOMRect)
+ })
+
+ afterEach(async () => {
+ cleanup()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('focuses the committed input on the first request and preserves its query on repeat', async () => {
+ const rendered = render(<SandboxUiPage localSearchRequestId={0} />)
+ await openApp()
+
+ rendered.rerender(<SandboxUiPage localSearchRequestId={1} />)
+ const input = await screen.findByRole('textbox', { name: 'Find in current app' })
+ expect(document.activeElement).toBe(input)
+
+ fireEvent.change(input, { target: { value: 'invoice' } })
+ screen.getByRole('button', { name: 'Refresh' }).focus()
+ rendered.rerender(<SandboxUiPage localSearchRequestId={2} />)
+
+ expect(document.activeElement).toBe(input)
+ expect(input).toHaveProperty('value', 'invoice')
+ })
+
+ it('stops the find session and restores native app focus when closed', async () => {
+ const rendered = render(<SandboxUiPage localSearchRequestId={0} />)
+ await openApp()
+ rendered.rerender(<SandboxUiPage localSearchRequestId={1} />)
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Close current app search' }))
+
+ await waitFor(() => {
+ expect(sandboxUi.stopFindInPage).toHaveBeenCalledOnce()
+ expect(sandboxUi.focusActive).toHaveBeenCalledOnce()
+ })
+ expect(screen.queryByRole('textbox', { name: 'Find in current app' })).toBeNull()
+ })
+
+ it('does not replay a stale focus request after the page remounts', async () => {
+ const first = render(<SandboxUiPage localSearchRequestId={0} />)
+ await openApp()
+ first.rerender(<SandboxUiPage localSearchRequestId={1} />)
+ await screen.findByRole('textbox', { name: 'Find in current app' })
+ first.unmount()
+
+ render(<SandboxUiPage localSearchRequestId={0} />)
+ await openApp()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+
+ expect(screen.queryByRole('textbox', { name: 'Find in current app' })).toBeNull()
+ })
+})