Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): preserve command overlay focus lifecycle
Josué2be6bcf68b98
diff --git a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.tsindex a6d88a3d0..b84e6745a 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 {+ focusActiveSandboxUi,installSandboxUiCookie,mountSandboxUiView,unmountSandboxUiView,@@ -22,6 +23,7 @@ const electronMocks = vi.hoisted(() => {})setWindowOpenHandler = vi.fn()stopFindInPage = vi.fn()+ focus = vi.fn()on(event: string, handler: (...args: unknown[]) => void): this {if (!this.listeners.has(event)) this.listeners.set(event, new Set())@@ -201,6 +203,15 @@ describe('mountSandboxUiView lifecycle cleanup', () => {expect(onClosed).not.toHaveBeenCalled()})+ it('focuses only the currently mounted native view', async () => {+ expect(focusActiveSandboxUi()).toBe(false)+ const parentWindow = new FakeParentWindow()+ await mountSandboxUiView(mountArgs({ parentWindow }))++ expect(focusActiveSandboxUi()).toBe(true)+ expect(electronMocks.views[0]?.webContents.focus).toHaveBeenCalledOnce()+ })+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/__tests__/shortcutRouter.test.ts b/desktop-app/src/__tests__/shortcutRouter.test.tsindex 7fb752a0e..ad441df64 100644--- a/desktop-app/src/__tests__/shortcutRouter.test.ts+++ b/desktop-app/src/__tests__/shortcutRouter.test.ts@@ -52,6 +52,7 @@ describe('main-process Desktop shortcut routing', () => {expect(preventDefault).toHaveBeenCalledOnce()expect(current.trustedRenderer.send).toHaveBeenCalledWith('shortcuts:command', {commandId: 'search.open',+ source: 'sandbox',})current.isCurrentSource = () => false@@ -65,9 +66,11 @@ describe('main-process Desktop shortcut routing', () => {routeDesktopShortcut(current, { preventDefault: vi.fn() }, input({ shift: true }))expect(current.trustedRenderer.send).toHaveBeenNthCalledWith(1, 'shortcuts:command', {commandId: 'search.open',+ source: 'sandbox',})expect(current.trustedRenderer.send).toHaveBeenNthCalledWith(2, 'shortcuts:command', {commandId: 'search.current',+ source: 'sandbox',})})diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex dfd97ca85..45fbb8cfc 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -3230,6 +3230,11 @@ export class AppService {stopActiveSandboxUiFind()}+ async focusActiveSandboxUi(): Promise<boolean> {+ const { focusActiveSandboxUi } = await import('./sandboxUiDriver.js')+ return focusActiveSandboxUi()+ }+/*** Embed-side refresh request. The IPC layer hands us the sender's* `webContents.id`; we delegate to the refresh module which gates thediff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex b88b7c145..61e9cc12e 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -1570,6 +1570,11 @@ export function registerIpcHandlers(service: AppService): void {await service.stopActiveSandboxUiFind()})+ ipcMain.handle('sandboxUi:focusActive', async event => {+ assertTrustedSender(event)+ return service.focusActiveSandboxUi()+ })+// Embed-side refresh request. NOTE: this IPC is exposed to *untrusted*// recipe JS via the embed preload, so we deliberately do NOT call// `assertTrustedSender` (the embed loads from the rpc-proxy URL, notdiff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 2f47f88f4..fa14b14d4 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -1,5 +1,9 @@import { contextBridge, ipcRenderer } from 'electron'-import { type DesktopCommandId, isDesktopCommandId } from './desktopCommands.js'+import {+ type DesktopCommandId,+ type DesktopCommandSource,+ isDesktopCommandId,+} from './desktopCommands.js'import type { PluginConsentRequest } from './pluginSdkProtocol.js'import type {HostMessageRequest,@@ -9,9 +13,17 @@ import type {const clerum = Object.freeze({shortcuts: {- onCommand: (callback: (commandId: DesktopCommandId) => void) => {- const listener = (_event: Electron.IpcRendererEvent, payload: { commandId?: unknown }) => {- if (isDesktopCommandId(payload?.commandId)) callback(payload.commandId)+ onCommand: (callback: (commandId: DesktopCommandId, source: DesktopCommandSource) => void) => {+ const listener = (+ _event: Electron.IpcRendererEvent,+ payload: { commandId?: unknown; source?: unknown }+ ) => {+ if (+ isDesktopCommandId(payload?.commandId) &&+ (payload?.source === 'host' || payload?.source === 'sandbox')+ ) {+ callback(payload.commandId, payload.source)+ }}ipcRenderer.on('shortcuts:command', listener)return () => ipcRenderer.off('shortcuts:command', listener)@@ -467,6 +479,7 @@ const clerum = Object.freeze({findInPage: (query: string, options: { forward: boolean; findNext: boolean }) =>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: numberdiff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 1167c73e9..ab155851b 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -1,4 +1,4 @@-import type { DesktopCommandId } from './desktopCommands.js'+import type { DesktopCommandId, DesktopCommandSource } from './desktopCommands.js'import type {PluginAuditEntryView,PluginConsentRequest,@@ -55,7 +55,9 @@ declare global {interface Window {clerum: {shortcuts: {- onCommand: (callback: (commandId: DesktopCommandId) => void) => () => void+ onCommand: (+ callback: (commandId: DesktopCommandId, source: DesktopCommandSource) => void+ ) => () => void}auth: {getSessionState: () => Promise<SessionState>@@ -559,6 +561,7 @@ declare global {options: { forward: boolean; findNext: boolean }) => Promise<number | null>stopFindInPage: () => Promise<void>+ focusActive: () => Promise<boolean>onFindResult: (callback: (result: {requestId: numberdiff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex 00e4d8832..e6732a48f 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -751,6 +751,12 @@ export function stopActiveSandboxUiFind(): void {}}+export function focusActiveSandboxUi(): boolean {+ if (!active || active.view.webContents.isDestroyed()) return false+ active.view.webContents.focus()+ return true+}+export async function captureSandboxUiPreview(): Promise<string | null> {if (!active) return nullif (active.view.webContents.isDestroyed()) return nulldiff --git a/desktop-app/src/shortcutRouter.ts b/desktop-app/src/shortcutRouter.tsindex 5e55426f3..6fe81558b 100644--- a/desktop-app/src/shortcutRouter.ts+++ b/desktop-app/src/shortcutRouter.ts@@ -41,7 +41,10 @@ export function routeDesktopShortcut()if (!command) return falseevent.preventDefault()- route.trustedRenderer.send('shortcuts:command', { commandId: command.id })+ route.trustedRenderer.send('shortcuts:command', {+ commandId: command.id,+ source: route.source,+ })return true}diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex 07d2f8af0..a5ca10d25 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -120,6 +120,7 @@ describe('ipc host status stream handlers', () => {setSandboxUiVisible: vi.fn(),findInActiveSandboxUi: vi.fn().mockResolvedValue(9),stopActiveSandboxUiFind: vi.fn().mockResolvedValue(undefined),+ focusActiveSandboxUi: vi.fn().mockResolvedValue(true),}beforeEach(async () => {@@ -192,6 +193,20 @@ describe('ipc host status stream handlers', () => {).rejects.toThrow('Untrusted IPC sender')})+ it('restores focus to an active sandbox only for the trusted renderer', async () => {+ const handler = testState.handlers.get('sandboxUi:focusActive')+ await expect(Promise.resolve(handler?.(makeTrustedEvent().event))).resolves.toBe(true)+ expect(service.focusActiveSandboxUi).toHaveBeenCalledOnce()+ await expect(+ Promise.resolve(+ handler?.({+ senderFrame: { url: 'https://evil.example.com' },+ sender: { id: 1, send: vi.fn(), once: vi.fn() },+ })+ )+ ).rejects.toThrow('Untrusted IPC sender')+ })+it.each([NaN, Infinity, 1.5, 0, -1, Number.MAX_SAFE_INTEGER + 1])('rejects invalid session catalog limit %s before calling the service',async limit => {diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsxindex 3333287f0..5130bfd3c 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -264,6 +264,7 @@ export function App() {const [chatLocalSearchOpen, setChatLocalSearchOpen] = React.useState(false)const [sandboxLocalSearchRequestId, setSandboxLocalSearchRequestId] = React.useState(0)const [commandPaletteOpen, setCommandPaletteOpen] = React.useState(false)+ const [commandPaletteReturnToSandbox, setCommandPaletteReturnToSandbox] = React.useState(false)const [settingsShortcutsRequestId, setSettingsShortcutsRequestId] = React.useState(0)const chatLocalSearchPreviousFocusRef = React.useRef<HTMLElement | null>(null)const contentPanelRef = React.useRef<HTMLElement | null>(null)@@ -1044,6 +1045,7 @@ export function App() {setChatLocalSearchOpen(false)setSandboxLocalSearchRequestId(0)setCommandPaletteOpen(false)+ setCommandPaletteReturnToSandbox(false)setSettingsShortcutsRequestId(0)}, [vm.authenticatedPrincipalIdentity])@@ -1067,14 +1069,28 @@ export function App() {[desktopCommandContext])+ const closeCommandPalette = React.useCallback(() => {+ const returnToSandbox = commandPaletteReturnToSandbox+ setCommandPaletteOpen(false)+ setCommandPaletteReturnToSandbox(false)+ if (returnToSandbox) {+ requestAnimationFrame(() => {+ void window.clerum.sandboxUi.focusActive().catch(() => undefined)+ })+ }+ }, [commandPaletteReturnToSandbox])+const executeDesktopCommand = React.useCallback(- (commandId: DesktopCommandId, source: 'shortcut' | 'palette' = 'shortcut') => {+ (+ commandId: DesktopCommandId,+ origin: 'shortcut-host' | 'shortcut-sandbox' | 'palette' = 'shortcut-host'+ ) => {if (!vm.isAuthenticated) return- if (source === 'shortcut' && commandPaletteOpen) {- if (commandId === 'commands.open') setCommandPaletteOpen(false)+ if (origin !== 'palette' && commandPaletteOpen) {+ if (commandId === 'commands.open') closeCommandPalette()return}- if (source === 'shortcut' && document.querySelector('[role="dialog"][aria-modal="true"]')) {+ if (origin !== 'palette' && document.querySelector('[role="dialog"][aria-modal="true"]')) {return}const command = getDesktopCommand(commandId)@@ -1082,9 +1098,19 @@ export function App() {if (!isDesktopCommandEligible(command, desktopCommandContext)) returnif (commandId === 'commands.open') {closeChatLocalSearch(false)- setCommandPaletteOpen(true)+ if (origin === 'palette') {+ setCommandPaletteOpen(false)+ setCommandPaletteReturnToSandbox(false)+ } else {+ setCommandPaletteReturnToSandbox(origin === 'shortcut-sandbox')+ setCommandPaletteOpen(true)+ }return}+ if (origin === 'palette') {+ setCommandPaletteOpen(false)+ setCommandPaletteReturnToSandbox(false)+ }if (commandId === 'settings.shortcuts') {closeChatLocalSearch(false)setCommandPaletteOpen(false)@@ -1147,6 +1173,7 @@ export function App() {[activeSandboxUiApp,closeChatLocalSearch,+ closeCommandPalette,commandPaletteOpen,desktopCommandContext,handleCloseChatViewTab,@@ -1161,7 +1188,9 @@ export function App() {React.useEffect(() => {if (!window.clerum.shortcuts) return undefined- return window.clerum.shortcuts.onCommand(commandId => executeDesktopCommand(commandId))+ return window.clerum.shortcuts.onCommand((commandId, source) =>+ executeDesktopCommand(commandId, source === 'sandbox' ? 'shortcut-sandbox' : 'shortcut-host')+ )}, [executeDesktopCommand])const sandboxUiBoundsRefreshKey = `${sidebarCollapsed ? 'collapsed' : 'expanded'}:${@@ -1742,8 +1771,9 @@ export function App() {<CommandPaletteplatform={platformFromNavigator(navigator.platform)}isEligible={isCommandEligible}- onClose={() => setCommandPaletteOpen(false)}+ onClose={closeCommandPalette}onExecute={commandId => executeDesktopCommand(commandId, 'palette')}+ restorePreviousFocus={!commandPaletteReturnToSandbox}/>) : null}{desktopUpdateRequiredDialog}diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsxindex f3a25cb66..7f8743de3 100644--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx@@ -199,7 +199,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {describe('App deep-link orchestration', () => {let currentController: AppControllerlet emitDeepLink: ((link: SandboxUiDeepLinkEnvelope) => void) | null- let emitCommand: ((commandId: DesktopCommandId) => void) | null+ let emitCommand: ((commandId: DesktopCommandId, source?: 'host' | 'sandbox') => void) | nullconst clearPendingDeepLinks = vi.fn().mockResolvedValue(undefined)const acknowledgeDeepLink = vi.fn().mockResolvedValue(undefined)const listApps = vi.fn().mockResolvedValue({ apps: [] })@@ -227,10 +227,12 @@ describe('App deep-link orchestration', () => {configurable: true,value: {shortcuts: {- onCommand: vi.fn((callback: (commandId: DesktopCommandId) => void) => {- emitCommand = callback- return vi.fn()- }),+ onCommand: vi.fn(+ (callback: (commandId: DesktopCommandId, source: 'host' | 'sandbox') => void) => {+ emitCommand = (commandId, source = 'host') => callback(commandId, source)+ return vi.fn()+ }+ ),},app: {rendererReady: vi.fn().mockResolvedValue(undefined),@@ -241,6 +243,7 @@ describe('App deep-link orchestration', () => {clearPendingDeepLinks,acknowledgeDeepLink,close: closeSandboxUi,+ focusActive: vi.fn().mockResolvedValue(true),onDeepLink: vi.fn((callback: (link: SandboxUiDeepLinkEnvelope) => void) => {emitDeepLink = callbackreturn vi.fn()@@ -318,7 +321,7 @@ describe('App deep-link orchestration', () => {label: 'App',defaultPath: '/',})- emitCommand?.('commands.open')+ emitCommand?.('commands.open', 'sandbox')})expect(commandPaletteHarness.props).not.toBeNull()@@ -327,6 +330,19 @@ describe('App deep-link orchestration', () => {act(() => commandPaletteHarness.props?.onExecute('search.open'))expect(appHeaderHarness.props?.searchFocusRequestId).toBe(1)+ expect(document.querySelector('[aria-label="Command palette"]')).toBeNull()+ })++ it('restores native app focus when a sandbox-opened palette is dismissed', async () => {+ currentController = makeController({+ initialExperienceLoading: false,+ navItem: DESKTOP_ROUTES.apps,+ } as Partial<AppController>)+ render(<App />)+ act(() => emitCommand?.('commands.open', 'sandbox'))+ act(() => commandPaletteHarness.props?.onClose())++ await waitFor(() => expect(window.clerum.sandboxUi.focusActive).toHaveBeenCalledOnce())})it('opens Settings Shortcuts through the registered palette action', () => {diff --git a/desktop-app/ui/src/components/CommandPalette/CommandPalette.test.tsx b/desktop-app/ui/src/components/CommandPalette/CommandPalette.test.tsxindex 5bfaa12b2..e33baa962 100644--- a/desktop-app/ui/src/components/CommandPalette/CommandPalette.test.tsx+++ b/desktop-app/ui/src/components/CommandPalette/CommandPalette.test.tsx@@ -35,7 +35,7 @@ describe('CommandPalette', () => {expect(onClose).toHaveBeenCalledOnce()})- it('supports click, wrapping arrows, focus trap, and focus restoration', () => {+ it('supports click, wrapping arrows, and the focus trap', () => {const previous = document.createElement('button')document.body.append(previous)previous.focus()@@ -61,6 +61,31 @@ describe('CommandPalette', () => {fireEvent.keyDown(input, { key: 'Tab', shiftKey: true })expect(document.activeElement).not.toBe(input)unmount()+ return new Promise<void>(resolve =>+ requestAnimationFrame(() => {+ expect(document.activeElement).not.toBe(previous)+ previous.remove()+ resolve()+ })+ )+ })++ it('restores previous focus when dismissed without executing a command', () => {+ const previous = document.createElement('button')+ document.body.append(previous)+ previous.focus()+ let close = () => undefined+ const rendered = render(+ <CommandPalette+ platform="darwin"+ isEligible={() => true}+ onClose={() => close()}+ onExecute={vi.fn()}+ />+ )+ close = rendered.unmount++ fireEvent.keyDown(screen.getByRole('dialog', { name: 'Command palette' }), { key: 'Escape' })return new Promise<void>(resolve =>requestAnimationFrame(() => {expect(document.activeElement).toBe(previous)diff --git a/desktop-app/ui/src/components/CommandPalette/index.tsx b/desktop-app/ui/src/components/CommandPalette/index.tsxindex 6fcdc7962..e5d0c3944 100644--- a/desktop-app/ui/src/components/CommandPalette/index.tsx+++ b/desktop-app/ui/src/components/CommandPalette/index.tsx@@ -7,12 +7,19 @@ import {} from '../../../../src/desktopCommands'import type { CommandPaletteProps } from './types'-export function CommandPalette({ platform, isEligible, onClose, onExecute }: CommandPaletteProps) {+export function CommandPalette({+ platform,+ isEligible,+ onClose,+ onExecute,+ restorePreviousFocus = true,+}: CommandPaletteProps) {const [query, setQuery] = useState('')const [selectedId, setSelectedId] = useState<DesktopCommandId | null>(null)const dialogRef = useRef<HTMLDivElement | null>(null)const inputRef = useRef<HTMLInputElement | null>(null)const previousFocusRef = useRef<HTMLElement | null>(null)+ const restoreFocusOnUnmountRef = useRef(restorePreviousFocus)const commands = useMemo(() => {const normalized = query.trim().toLocaleLowerCase()return DESKTOP_COMMANDS.filter(command => command.visibleInPalette)@@ -32,9 +39,11 @@ export function CommandPalette({ platform, isEligible, onClose, onExecute }: CominputRef.current?.focus()return () => {const previous = previousFocusRef.current- requestAnimationFrame(() => {- if (previous?.isConnected) previous.focus()- })+ if (restoreFocusOnUnmountRef.current) {+ requestAnimationFrame(() => {+ if (previous?.isConnected) previous.focus()+ })+ }}}, [])@@ -55,6 +64,7 @@ export function CommandPalette({ platform, isEligible, onClose, onExecute }: Comconst execute = (commandId: DesktopCommandId) => {if (!isEligible(commandId)) return+ restoreFocusOnUnmountRef.current = falseonExecute(commandId)}diff --git a/desktop-app/ui/src/components/CommandPalette/types.ts b/desktop-app/ui/src/components/CommandPalette/types.tsindex 281e7b24d..72150619f 100644--- a/desktop-app/ui/src/components/CommandPalette/types.ts+++ b/desktop-app/ui/src/components/CommandPalette/types.ts@@ -5,4 +5,5 @@ export type CommandPaletteProps = {isEligible: (commandId: DesktopCommandId) => booleanonClose: () => voidonExecute: (commandId: DesktopCommandId) => void+ restorePreviousFocus?: boolean}diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsxindex 89112e9a3..76c8c1367 100644--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx@@ -229,15 +229,22 @@ export function SandboxUiPage({}, [])const stopLocalSearch = useCallback(() => {+ const previous = localSearchPreviousFocusRef.currentactiveFindRequestIdRef.current = nullsetLocalSearchOpen(false)setLocalSearchQuery('')setLocalSearchResult({ current: 0, total: 0 })- void window.clerum.sandboxUi.stopFindInPage().catch(() => undefined)- const previous = localSearchPreviousFocusRef.current- requestAnimationFrame(() => {- if (previous?.isConnected) previous.focus()- })+ void window.clerum.sandboxUi+ .stopFindInPage()+ .then(() => window.clerum.sandboxUi.focusActive())+ .then(focused => {+ if (!focused) {+ requestAnimationFrame(() => {+ if (previous?.isConnected) previous.focus()+ })+ }+ })+ .catch(() => undefined)}, [])const runLocalSearch = useCallback(diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsxindex 375135d91..000d2bbf0 100644--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx@@ -15,6 +15,7 @@ const sandboxUi = {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()),@@ -31,6 +32,7 @@ describe('SandboxUiPage', () => {sandboxUi.setVisible.mockResolvedValue(undefined)sandboxUi.findInPage.mockResolvedValue(17)sandboxUi.stopFindInPage.mockResolvedValue(undefined)+ sandboxUi.focusActive.mockResolvedValue(true)installClerumApi()vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {cb(0)@@ -201,7 +203,10 @@ describe('SandboxUiPage', () => {findNext: true,})fireEvent.keyDown(input, { key: 'Escape' })- expect(sandboxUi.stopFindInPage).toHaveBeenCalled()+ await waitFor(() => {+ expect(sandboxUi.stopFindInPage).toHaveBeenCalled()+ expect(sandboxUi.focusActive).toHaveBeenCalled()+ })expect(screen.queryByRole('textbox', { name: 'Find in current app' })).toBeNull()})