Skip to content

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

TypeScript

feat(desktop): add global and contextual search shortcuts

Josué191cbb42e22c
diff --git a/desktop-app/src/__tests__/pluginSdkSurface.test.ts b/desktop-app/src/__tests__/pluginSdkSurface.test.ts
index f0d7faa15..d5e4dfd46 100644
--- a/desktop-app/src/__tests__/pluginSdkSurface.test.ts
+++ b/desktop-app/src/__tests__/pluginSdkSurface.test.ts
@@ -154,6 +154,13 @@ describe('embed preload contract', () => {
expect(source, `preload has no wrapper for ${id}`).toContain(`'${id}'`)
}
})
+
+ it('does not expose host shortcut or native find privileges to plugin code', async () => {
+ const source = await fs.readFile(PRELOAD_PATH, 'utf8')
+ expect(source).not.toContain('findInPage')
+ expect(source).not.toContain('stopFindInPage')
+ expect(source).not.toContain('shortcuts:command')
+ })
})
describe('gfs:// links from an embed', () => {
diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.ts
index b9170376c..5e4c59478 100644
--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
SANDBOX_UI_COOKIE_NAME,
applySandboxUiClientRoute,
+ beginSandboxUiFind,
canApplySandboxUiClientRoute,
extractSandboxUiCookie,
extractSandboxUiPath,
@@ -12,6 +13,56 @@ import {
resolveSandboxUiSharePath,
} from '../sandboxUiDriver.js'
+describe('sandbox WebContents local find', () => {
+ it('uses the native producer, filters request IDs, minimizes results, and removes its listener', () => {
+ let listener: ((event: Electron.Event, result: Electron.FoundInPageResult) => void) | undefined
+ const webContents = {
+ findInPage: vi.fn(() => 41),
+ on: vi.fn((_name: string, callback: typeof listener) => {
+ listener = callback
+ return webContents
+ }),
+ removeListener: vi.fn(() => webContents),
+ }
+ const onResult = vi.fn()
+ const session = beginSandboxUiFind(
+ webContents as never,
+ 'invoice',
+ { forward: false, findNext: true },
+ onResult
+ )
+
+ expect(session.requestId).toBe(41)
+ expect(webContents.findInPage).toHaveBeenCalledWith('invoice', {
+ forward: false,
+ findNext: true,
+ })
+ listener?.({} as Electron.Event, {
+ requestId: 40,
+ activeMatchOrdinal: 1,
+ matches: 9,
+ selectionArea: { x: 0, y: 0, width: 1, height: 1 },
+ finalUpdate: true,
+ })
+ expect(onResult).not.toHaveBeenCalled()
+ listener?.({} as Electron.Event, {
+ requestId: 41,
+ activeMatchOrdinal: 2,
+ matches: 4,
+ selectionArea: { x: 8, y: 8, width: 100, height: 40 },
+ finalUpdate: true,
+ })
+ expect(onResult).toHaveBeenCalledWith({
+ requestId: 41,
+ activeMatchOrdinal: 2,
+ matches: 4,
+ finalUpdate: true,
+ })
+ session.cleanup()
+ expect(webContents.removeListener).toHaveBeenCalledWith('found-in-page', listener)
+ })
+})
+
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/appService.ts b/desktop-app/src/appService.ts
index 032923840..dfd97ca85 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -3216,6 +3216,20 @@ export class AppService {
return captureSandboxUiPreview()
}
+ async findInActiveSandboxUi(
+ query: string,
+ options: { forward: boolean; findNext: boolean },
+ onResult: (result: import('./sandboxUiDriver.js').SandboxUiFindResult) => void
+ ): Promise<number | null> {
+ const { findInActiveSandboxUi } = await import('./sandboxUiDriver.js')
+ return findInActiveSandboxUi(query, options, onResult)
+ }
+
+ async stopActiveSandboxUiFind(): Promise<void> {
+ const { stopActiveSandboxUiFind } = await import('./sandboxUiDriver.js')
+ stopActiveSandboxUiFind()
+ }
+
/**
* Embed-side refresh request. The IPC layer hands us the sender's
* `webContents.id`; we delegate to the refresh module which gates the
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index bd5248dca..b88b7c145 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -1544,6 +1544,32 @@ export function registerIpcHandlers(service: AppService): void {
return service.captureSandboxUiPreview()
})
+ ipcMain.handle(
+ 'sandboxUi:findInPage',
+ async (event, payload: { query?: unknown; forward?: unknown; findNext?: unknown }) => {
+ assertTrustedSender(event)
+ const query = typeof payload?.query === 'string' ? payload.query : ''
+ 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')
+ }
+ return service.findInActiveSandboxUi(
+ query,
+ { forward: payload.forward, findNext: payload.findNext },
+ result => {
+ if (!event.sender.isDestroyed()) event.sender.send('sandboxUi:findResult', result)
+ }
+ )
+ }
+ )
+
+ ipcMain.handle('sandboxUi:stopFindInPage', async event => {
+ assertTrustedSender(event)
+ await service.stopActiveSandboxUiFind()
+ })
+
// 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, not
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 29d591cbf..2f47f88f4 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -464,6 +464,36 @@ 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 }) =>
+ ipcRenderer.invoke('sandboxUi:findInPage', { query, ...options }) as Promise<number | null>,
+ stopFindInPage: () => ipcRenderer.invoke('sandboxUi:stopFindInPage') as Promise<void>,
+ onFindResult: (
+ callback: (result: {
+ requestId: number
+ activeMatchOrdinal: number
+ matches: number
+ finalUpdate: boolean
+ }) => void
+ ) => {
+ const listener = (_event: unknown, result: unknown) => {
+ const value = result as Record<string, unknown>
+ if (
+ Number.isInteger(value?.requestId) &&
+ Number.isInteger(value?.activeMatchOrdinal) &&
+ Number.isInteger(value?.matches) &&
+ typeof value?.finalUpdate === 'boolean'
+ ) {
+ callback({
+ requestId: Number(value.requestId),
+ activeMatchOrdinal: Number(value.activeMatchOrdinal),
+ matches: Number(value.matches),
+ finalUpdate: value.finalUpdate,
+ })
+ }
+ }
+ ipcRenderer.on('sandboxUi:findResult', listener)
+ return () => ipcRenderer.off('sandboxUi:findResult', listener)
+ },
onDeepLink: (callback: (args: SandboxUiDeepLinkEnvelope) => void) => {
const listener = (_event: unknown, args: SandboxUiDeepLinkEnvelope) => callback(args)
ipcRenderer.on('sandboxUi:deepLink', listener)
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index b37e1a8ce..1167c73e9 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -554,6 +554,19 @@ declare global {
}) => Promise<void>
setVisible: (visible: boolean) => Promise<void>
capturePreview: () => Promise<string | null>
+ findInPage: (
+ query: string,
+ options: { forward: boolean; findNext: boolean }
+ ) => Promise<number | null>
+ stopFindInPage: () => Promise<void>
+ onFindResult: (
+ callback: (result: {
+ requestId: number
+ activeMatchOrdinal: number
+ matches: number
+ finalUpdate: boolean
+ }) => void
+ ) => () => void
onDeepLink: (callback: (args: SandboxUiDeepLinkEnvelope) => void) => () => void
onClosed: (callback: (args: { appRef: string }) => void) => () => void
onRefreshError: (
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index d39f21764..00e4d8832 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -48,6 +48,13 @@ export type SandboxUiBounds = {
dpr?: number
}
+export type SandboxUiFindResult = {
+ requestId: number
+ activeMatchOrdinal: number
+ matches: number
+ finalUpdate: boolean
+}
+
function toViewBounds(
bounds: SandboxUiBounds,
parentWindow: BrowserWindow
@@ -108,6 +115,8 @@ type ActiveView = {
cleanupClientRouteHandoff?: () => void
cleanupParentClosed?: () => void
cleanupShortcutRouting?: () => void
+ cleanupFindResults?: () => void
+ activeFindRequestId?: number
}
let active: ActiveView | null = null
@@ -280,6 +289,10 @@ async function teardownActive(reason: 'replaced' | 'closed' | 'parent_closed'):
current.cleanupClientRouteHandoff?.()
current.cleanupParentClosed?.()
current.cleanupShortcutRouting?.()
+ current.cleanupFindResults?.()
+ if (!current.view.webContents.isDestroyed()) {
+ current.view.webContents.stopFindInPage('clearSelection')
+ }
// contentView.removeChildView is the documented teardown step; it both
// detaches the view from layout AND severs the parent's ownership ref.
if (!current.parentWindow.isDestroyed()) {
@@ -677,6 +690,67 @@ export function setSandboxUiVisible(visible: boolean): void {
active.view.setVisible(visible)
}
+type FindableSandboxWebContents = Pick<
+ WebContentsView['webContents'],
+ 'findInPage' | 'on' | 'removeListener'
+>
+
+export function beginSandboxUiFind(
+ webContents: FindableSandboxWebContents,
+ query: string,
+ options: { forward: boolean; findNext: boolean },
+ onResult: (result: SandboxUiFindResult) => void,
+ isCurrent: () => boolean = () => true
+): { requestId: number; cleanup: () => void } {
+ let requestId = -1
+ const listener = (_event: Electron.Event, result: Electron.FoundInPageResult) => {
+ if (!isCurrent() || result.requestId !== requestId) return
+ onResult({
+ requestId: result.requestId,
+ activeMatchOrdinal: result.activeMatchOrdinal,
+ matches: result.matches,
+ finalUpdate: result.finalUpdate,
+ })
+ }
+ webContents.on('found-in-page', listener)
+ requestId = webContents.findInPage(query, options)
+ return {
+ requestId,
+ cleanup: () => webContents.removeListener('found-in-page', listener),
+ }
+}
+
+export function findInActiveSandboxUi(
+ query: string,
+ options: { forward: boolean; findNext: boolean },
+ onResult: (result: SandboxUiFindResult) => void
+): number | null {
+ if (!active || active.view.webContents.isDestroyed()) return null
+ const current = active
+ const webContents = current.view.webContents
+ current.cleanupFindResults?.()
+ const session = beginSandboxUiFind(
+ webContents,
+ query,
+ options,
+ onResult,
+ () => active === current
+ )
+ current.cleanupFindResults = session.cleanup
+ current.activeFindRequestId = session.requestId
+ return session.requestId
+}
+
+export function stopActiveSandboxUiFind(): void {
+ if (!active) return
+ active.cleanupFindResults?.()
+ active.cleanupFindResults = undefined
+ active.activeFindRequestId = undefined
+ if (!active.view.webContents.isDestroyed()) {
+ active.view.webContents.stopFindInPage('clearSelection')
+ }
+}
+
export async function captureSandboxUiPreview(): Promise<string | null> {
if (!active) return null
if (active.view.webContents.isDestroyed()) return null
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index 645029908..07d2f8af0 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -118,6 +118,8 @@ describe('ipc host status stream handlers', () => {
listMyAgents: vi.fn(),
createGfsShare: vi.fn(),
setSandboxUiVisible: vi.fn(),
+ findInActiveSandboxUi: vi.fn().mockResolvedValue(9),
+ stopActiveSandboxUiFind: vi.fn().mockResolvedValue(undefined),
}
beforeEach(async () => {
@@ -154,6 +156,42 @@ describe('ipc host status stream handlers', () => {
expect(service.setSandboxUiVisible).toHaveBeenCalledWith(false)
})
+ it('validates and forwards only bounded trusted sandbox find requests', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('sandboxUi:findInPage')
+
+ await expect(
+ Promise.resolve(handler?.(event, { query: '', forward: true, findNext: false }))
+ ).rejects.toThrow('find query')
+ await expect(
+ Promise.resolve(handler?.(event, { query: 'x', forward: 'yes', findNext: false }))
+ ).rejects.toThrow('direction')
+ expect(service.findInActiveSandboxUi).not.toHaveBeenCalled()
+
+ await expect(
+ Promise.resolve(handler?.(event, { query: 'invoice', forward: false, findNext: true }))
+ ).resolves.toBe(9)
+ expect(service.findInActiveSandboxUi).toHaveBeenCalledWith(
+ 'invoice',
+ { forward: false, findNext: true },
+ expect.any(Function)
+ )
+ })
+
+ it('stops active sandbox find through a trusted sender only', async () => {
+ const handler = testState.handlers.get('sandboxUi:stopFindInPage')
+ await Promise.resolve(handler?.(makeTrustedEvent().event))
+ expect(service.stopActiveSandboxUiFind).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.tsx
index 60f2ab802..aae483f76 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -11,6 +11,7 @@ import {
} from '@contexts/index'
import { AppHeader } from '@components/AppHeader'
import { BootSplash } from '@components/BootSplash'
+import { ChatLocalSearch } from '@components/ChatLocalSearch'
import { ChatTabs } from '@components/ChatTabs'
import { Button, ToastStack } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
@@ -253,6 +254,10 @@ export function App() {
)
const chatViewTabsRef = React.useRef(chatViewTabs)
const [composerFocusRequestId, setComposerFocusRequestId] = React.useState(0)
+ const [globalSearchFocusRequestId, setGlobalSearchFocusRequestId] = React.useState(0)
+ const [chatLocalSearchOpen, setChatLocalSearchOpen] = React.useState(false)
+ const [sandboxLocalSearchRequestId, setSandboxLocalSearchRequestId] = React.useState(0)
+ const chatLocalSearchPreviousFocusRef = React.useRef<HTMLElement | null>(null)
const contentPanelRef = React.useRef<HTMLElement | null>(null)
const activeConversationOriginRef = React.useRef<SandboxUiConversationOrigin | null>(null)
const processingSandboxUiDeepLinkIdRef = React.useRef<number | null>(null)
@@ -318,6 +323,15 @@ export function App() {
revealChatViewTab(activeChatViewTab(next))
}, [nextChatTabId, revealChatViewTab, vm.selectedAgent])
+ const closeChatLocalSearch = React.useCallback((restoreFocus = true) => {
+ setChatLocalSearchOpen(false)
+ if (!restoreFocus) return
+ const previous = chatLocalSearchPreviousFocusRef.current
+ requestAnimationFrame(() => {
+ if (previous?.isConnected) previous.focus()
+ })
+ }, [])
+
const handleSelectChatAgentWithTabs = React.useCallback(
(
agentName: string,
@@ -1018,6 +1032,9 @@ export function App() {
nextChatTabSequenceRef.current = 2
setChatViewTabs(createChatViewTabsState('chat-tab-1'))
setComposerFocusRequestId(0)
+ setGlobalSearchFocusRequestId(0)
+ setChatLocalSearchOpen(false)
+ setSandboxLocalSearchRequestId(0)
}, [vm.authenticatedPrincipalIdentity])
React.useEffect(() => {
@@ -1029,10 +1046,12 @@ export function App() {
const command = getDesktopCommand(commandId)
const state = chatViewTabsRef.current
if (commandId === 'chat.newTab') {
+ closeChatLocalSearch(false)
handleNewChatViewTab()
return
}
if (commandId === 'chat.closeTab') {
+ closeChatLocalSearch(false)
handleCloseChatViewTab(state.activeTabId)
return
}
@@ -1058,11 +1077,36 @@ export function App() {
return
}
if (commandId === 'composer.focus') {
+ closeChatLocalSearch(false)
revealChatViewTab(activeChatViewTab(state))
setComposerFocusRequestId(value => value + 1)
+ return
+ }
+ if (commandId === 'search.open') {
+ closeChatLocalSearch(false)
+ setGlobalSearchFocusRequestId(value => value + 1)
+ return
+ }
+ if (commandId === 'search.current') {
+ if (activeSandboxUiApp && vm.navItem === DESKTOP_ROUTES.apps) {
+ closeChatLocalSearch(false)
+ setSandboxLocalSearchRequestId(value => value + 1)
+ } else if (vm.navItem === DESKTOP_ROUTES.chat && vm.activeChatId) {
+ chatLocalSearchPreviousFocusRef.current = document.activeElement as HTMLElement | null
+ setChatLocalSearchOpen(true)
+ }
}
})
- }, [handleCloseChatViewTab, handleNewChatViewTab, revealChatViewTab, vm.isAuthenticated])
+ }, [
+ activeSandboxUiApp,
+ closeChatLocalSearch,
+ handleCloseChatViewTab,
+ handleNewChatViewTab,
+ revealChatViewTab,
+ vm.activeChatId,
+ vm.isAuthenticated,
+ vm.navItem,
+ ])
const sandboxUiBoundsRefreshKey = `${sidebarCollapsed ? 'collapsed' : 'expanded'}:${
appNotificationDrawerOpen ? 'notification-drawer-open' : 'notification-drawer-closed'
@@ -1546,6 +1590,7 @@ export function App() {
}`}
>
<AppHeader
+ searchFocusRequestId={globalSearchFocusRequestId}
notificationTrayMode={
notificationTrayUsesDrawer ? 'drawer' : 'overlay'
}
@@ -1562,6 +1607,12 @@ export function App() {
onSelect={handleSelectChatViewTab}
onClose={handleCloseChatViewTab}
/>
+ {chatLocalSearchOpen ? (
+ <ChatLocalSearch
+ messages={vm.activeMessages}
+ onClose={closeChatLocalSearch}
+ />
+ ) : null}
<ChatPage scrollContainerRef={contentPanelRef} />
</section>
)}
@@ -1591,6 +1642,7 @@ export function App() {
toastShellOverlayOpen={vm.toasts.length > 0}
shortcutApp={activeSandboxUiApp}
shortcutOpenRequestId={sandboxUiShortcutOpenRequestId}
+ localSearchRequestId={sandboxLocalSearchRequestId}
onBackToConversation={handleSandboxUiBackToConversation}
onEmbeddedAppOpening={handleSandboxUiOpening}
onEmbeddedAppBack={handleSandboxUiClosed}
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index ed213e933..03ec0324e 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -16,9 +16,16 @@ const confirmDialogHarness = vi.hoisted(() => ({
},
}))
+const appHeaderHarness = vi.hoisted(() => ({
+ props: null as null | { searchFocusRequestId?: number },
+}))
+
+const chatLocalSearchHarness = vi.hoisted(() => ({ rendered: vi.fn() }))
+
const sandboxUiPageHarness = vi.hoisted(() => ({
props: null as null | {
shortcutOpenRequestId?: number
+ localSearchRequestId?: number
onEmbeddedAppOpening?: (app: {
appRef: string
label: string
@@ -41,7 +48,18 @@ vi.mock('@hooks/useAgentChatActionsValue', () => ({
useAgentChatActionsValue: () => ({}),
}))
-vi.mock('@components/AppHeader', () => ({ AppHeader: () => null }))
+vi.mock('@components/AppHeader', () => ({
+ AppHeader: (props: NonNullable<typeof appHeaderHarness.props>) => {
+ appHeaderHarness.props = props
+ return null
+ },
+}))
+vi.mock('@components/ChatLocalSearch', () => ({
+ ChatLocalSearch: () => {
+ chatLocalSearchHarness.rendered()
+ return null
+ },
+}))
vi.mock('@components/BootSplash', () => ({ BootSplash: () => null }))
vi.mock('@components/Common', () => ({ Button: () => null, ToastStack: () => null }))
vi.mock('@components/ConfirmDialog', () => ({
@@ -168,6 +186,8 @@ describe('App deep-link orchestration', () => {
beforeEach(() => {
vi.clearAllMocks()
confirmDialogHarness.props = null
+ appHeaderHarness.props = null
+ chatLocalSearchHarness.rendered.mockReset()
sandboxUiPageHarness.props = null
acknowledgeDeepLink.mockResolvedValue(undefined)
listApps.mockResolvedValue({ apps: [] })
@@ -223,6 +243,43 @@ describe('App deep-link orchestration', () => {
})
})
+ it('keeps global and contextual search commands on distinct host surfaces', () => {
+ currentController = makeController({
+ initialExperienceLoading: false,
+ selectedAgent: 'alpha',
+ activeChatId: 'chat-1',
+ } as Partial<AppController>)
+ render(<App />)
+
+ act(() => emitCommand?.('search.open'))
+ expect(appHeaderHarness.props?.searchFocusRequestId).toBe(1)
+ expect(chatLocalSearchHarness.rendered).not.toHaveBeenCalled()
+
+ act(() => emitCommand?.('search.current'))
+ expect(chatLocalSearchHarness.rendered).toHaveBeenCalled()
+ expect(appHeaderHarness.props?.searchFocusRequestId).toBe(1)
+ })
+
+ it('routes contextual search to the current sandbox app without opening global search', () => {
+ currentController = makeController({
+ initialExperienceLoading: false,
+ navItem: DESKTOP_ROUTES.apps,
+ selectedAgent: 'alpha',
+ } as Partial<AppController>)
+ render(<App />)
+ act(() => {
+ sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
+ appRef: 'ns/app',
+ label: 'App',
+ defaultPath: '/',
+ })
+ })
+
+ act(() => emitCommand?.('search.current'))
+ expect(sandboxUiPageHarness.props?.localSearchRequestId).toBe(1)
+ expect(appHeaderHarness.props?.searchFocusRequestId).toBe(0)
+ })
+
afterEach(() => {
vi.useRealTimers()
})
diff --git a/desktop-app/ui/src/components/AppHeader/__tests__/notifications.test.tsx b/desktop-app/ui/src/components/AppHeader/__tests__/notifications.test.tsx
index 9bf06a244..57c7ae466 100644
--- a/desktop-app/ui/src/components/AppHeader/__tests__/notifications.test.tsx
+++ b/desktop-app/ui/src/components/AppHeader/__tests__/notifications.test.tsx
@@ -242,4 +242,18 @@ describe('AppHeader notification tray presentation', () => {
'Search teams, contexts, members, agents or connectors...'
)
})
+
+ it('opens and focuses the existing global search for a command request', () => {
+ const { rerender } = render(<AppHeader searchFocusRequestId={0} />)
+ const other = document.createElement('button')
+ document.body.append(other)
+ other.focus()
+
+ rerender(<AppHeader searchFocusRequestId={1} />)
+
+ const search = screen.getByRole('textbox', { name: 'Search' })
+ expect(document.activeElement).toBe(search)
+ expect(search.getAttribute('aria-label')).toBe('Search')
+ other.remove()
+ })
})
diff --git a/desktop-app/ui/src/components/AppHeader/index.tsx b/desktop-app/ui/src/components/AppHeader/index.tsx
index e1a973a82..3f85079c1 100644
--- a/desktop-app/ui/src/components/AppHeader/index.tsx
+++ b/desktop-app/ui/src/components/AppHeader/index.tsx
@@ -83,6 +83,7 @@ function notificationPillLabel(kind: AppNotificationKind): string {
}
export const AppHeader = React.memo(function AppHeader({
+ searchFocusRequestId = 0,
notificationTrayMode = 'overlay',
notificationTrayReady = true,
onNotificationTrayOpenChange,
@@ -129,6 +130,7 @@ export const AppHeader = React.memo(function AppHeader({
() => window.innerWidth <= COMPACT_SEARCH_BREAKPOINT
)
const searchRef = useRef<HTMLDivElement | null>(null)
+ const searchInputRef = useRef<HTMLInputElement | null>(null)
const notificationsRef = useRef<HTMLDivElement | null>(null)
const searchDirectoryInFlightRef = useRef(false)
const searchDirectoryRefreshQueryRef = useRef('')
@@ -152,6 +154,13 @@ export const AppHeader = React.memo(function AppHeader({
useClickOutside(searchRef, searchOpen, () => setSearchOpen(false))
useClickOutside(notificationsRef, notificationsOpen, () => setNotificationsOpen(false))
+ useEffect(() => {
+ if (searchFocusRequestId <= 0) return
+ setNotificationsOpen(false)
+ setSearchOpen(true)
+ searchInputRef.current?.focus()
+ }, [searchFocusRequestId])
+
React.useLayoutEffect(() => {
onShellOverlayOpenChange?.(searchOpen || (notificationsOpen && !notificationTrayUsesDrawer))
onNotificationTrayOpenChange?.(notificationsOpen)
@@ -538,6 +547,7 @@ export const AppHeader = React.memo(function AppHeader({
<div className="header-left">
<div className="global-search" ref={searchRef}>
<TextInput
+ ref={searchInputRef}
type="text"
placeholder={compactSearch ? COMPACT_SEARCH_PLACEHOLDER : FULL_SEARCH_PLACEHOLDER}
className="search-input"
diff --git a/desktop-app/ui/src/components/AppHeader/types.ts b/desktop-app/ui/src/components/AppHeader/types.ts
index fc7fcb49b..59dcda261 100644
--- a/desktop-app/ui/src/components/AppHeader/types.ts
+++ b/desktop-app/ui/src/components/AppHeader/types.ts
@@ -1,4 +1,5 @@
export type AppHeaderProps = {
+ searchFocusRequestId?: number
notificationTrayMode?: 'overlay' | 'drawer'
notificationTrayReady?: boolean
onNotificationTrayOpenChange?: (open: boolean) => void
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx b/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
new file mode 100644
index 000000000..cc3b5936a
--- /dev/null
+++ b/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
@@ -0,0 +1,58 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { chatMessageDomId } from '@lib/chatLocalSearch'
+import { ChatLocalSearch } from '.'
+
+describe('ChatLocalSearch', () => {
+ const loadSessionMessages = vi.fn()
+ const loadMessages = vi.fn()
+
+ beforeEach(() => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { rpc: { loadSessionMessages }, chat: { loadMessages } },
+ })
+ HTMLElement.prototype.scrollIntoView = vi.fn()
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+ delete (window as Partial<typeof window>).clerum
+ })
+
+ it('navigates and wraps loaded matches without fetching history or mutating chat state', () => {
+ const first = document.createElement('article')
+ first.id = chatMessageDomId('one')
+ document.body.append(first)
+ const second = document.createElement('article')
+ second.id = chatMessageDomId('two')
+ document.body.append(second)
+ const onClose = vi.fn()
+ render(
+ <ChatLocalSearch
+ messages={[
+ { id: 'one', role: 'user', content: 'Needle once', timestamp: 1 },
+ { id: 'two', role: 'assistant', content: 'needle twice needle', timestamp: 2 },
+ ]}
+ onClose={onClose}
+ />
+ )
+ const input = screen.getByRole('textbox', { name: 'Find in current chat' })
+ fireEvent.change(input, { target: { value: 'NEEDLE' } })
+ expect(screen.getByRole('status').textContent).toBe('1/3')
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(screen.getByRole('status').textContent).toBe('2/3')
+ fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
+ expect(screen.getByRole('status').textContent).toBe('1/3')
+ fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
+ expect(screen.getByRole('status').textContent).toBe('3/3')
+ fireEvent.keyDown(input, { key: 'Escape' })
+ expect(onClose).toHaveBeenCalledOnce()
+ expect(loadSessionMessages).not.toHaveBeenCalled()
+ expect(loadMessages).not.toHaveBeenCalled()
+ first.remove()
+ second.remove()
+ })
+})
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/index.tsx b/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
new file mode 100644
index 000000000..68f34f7c7
--- /dev/null
+++ b/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
@@ -0,0 +1,96 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { Button, TextInput } from '@components/Common'
+import {
+ chatMessageDomId,
+ findLoadedChatMessageMatches,
+ wrapMatchIndex,
+} from '@lib/chatLocalSearch'
+import type { ChatLocalSearchProps } from './types'
+
+export function ChatLocalSearch({ messages, onClose }: ChatLocalSearchProps) {
+ const [query, setQuery] = useState('')
+ const [currentIndex, setCurrentIndex] = useState(0)
+ const inputRef = useRef<HTMLInputElement | null>(null)
+ const matches = useMemo(() => findLoadedChatMessageMatches(messages, query), [messages, query])
+ const currentMatch = matches[currentIndex] ?? null
+
+ useEffect(() => {
+ inputRef.current?.focus()
+ }, [])
+
+ useEffect(() => {
+ setCurrentIndex(index => (matches.length ? Math.min(index, matches.length - 1) : 0))
+ }, [matches.length])
+
+ useEffect(() => {
+ const previous = document.querySelector<HTMLElement>('[data-current-search-match="true"]')
+ previous?.removeAttribute('data-current-search-match')
+ if (!currentMatch) return undefined
+ const target = document.getElementById(chatMessageDomId(currentMatch.messageId))
+ target?.setAttribute('data-current-search-match', 'true')
+ target?.scrollIntoView?.({ block: 'center' })
+ return () => target?.removeAttribute('data-current-search-match')
+ }, [currentMatch])
+
+ const move = (delta: 1 | -1) => {
+ setCurrentIndex(index => wrapMatchIndex(index, matches.length, delta))
+ }
+
+ return (
+ <div className="current-content-search" role="search" aria-label="Search loaded chat messages">
+ <TextInput
+ ref={inputRef}
+ aria-label="Find in current chat"
+ className="current-content-search__input"
+ onChange={event => {
+ setQuery(event.currentTarget.value)
+ setCurrentIndex(0)
+ }}
+ onKeyDown={event => {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ onClose()
+ } else if (event.key === 'Enter') {
+ event.preventDefault()
+ move(event.shiftKey ? -1 : 1)
+ }
+ }}
+ placeholder="Find in loaded messages"
+ value={query}
+ />
+ <span className="current-content-search__count" role="status" aria-live="polite">
+ {matches.length ? currentIndex + 1 : 0}/{matches.length}
+ </span>
+ <Button
+ aria-label="Previous match"
+ color="neutral"
+ onClick={() => move(-1)}
+ size="xs"
+ variant="ghost"
+ >
+ ↑
+ </Button>
+ <Button
+ aria-label="Next match"
+ color="neutral"
+ onClick={() => move(1)}
+ size="xs"
+ variant="ghost"
+ >
+ ↓
+ </Button>
+ <Button
+ aria-label="Close current chat search"
+ color="neutral"
+ onClick={onClose}
+ size="xs"
+ variant="ghost"
+ >
+ ×
+ </Button>
+ <span className="visually-hidden">
+ Only messages already loaded in this chat are searched.
+ </span>
+ </div>
+ )
+}
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/types.ts b/desktop-app/ui/src/components/ChatLocalSearch/types.ts
new file mode 100644
index 000000000..449d9527b
--- /dev/null
+++ b/desktop-app/ui/src/components/ChatLocalSearch/types.ts
@@ -0,0 +1,6 @@
+import type { AgentChatMessage } from '@/uiTypes'
+
+export type ChatLocalSearchProps = {
+ messages: AgentChatMessage[]
+ onClose: () => void
+}
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index 701593e8f..e1061da4d 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -33,6 +33,7 @@ import {
} from '@constants/agents'
import { HTML_PREVIEW_INLINE_MAX_BYTES } from '@constants/htmlPreview'
import type { ChatMessageAttachment } from '../../../../src/types'
+import { chatMessageDomId } from '../../lib/chatLocalSearch'
import {
getChatMessageAttachmentTypeLabel,
parseChatMessageDisplay,
@@ -610,6 +611,8 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
return (
<article
key={message.messageKey}
+ id={chatMessageDomId(message.id)}
+ data-chat-message-id={message.id}
data-testid={message.role === 'assistant' ? 'agent-response' : undefined}
className={`chat-bubble ${message.role}${message.isError ? ' chat-bubble--error' : ''}${
htmlPreview || hasHtmlArtifactMention ? ' chat-bubble--wide' : ''
diff --git a/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts b/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts
new file mode 100644
index 000000000..ef437a8c4
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+import type { AgentChatMessage } from '../../uiTypes'
+import { findLoadedChatMessageMatches, wrapMatchIndex } from '../chatLocalSearch'
+
+function message(id: string, content: string, role: AgentChatMessage['role'] = 'assistant') {
+ return { id, content, role, timestamp: 1 } satisfies AgentChatMessage
+}
+
+describe('loaded chat local search', () => {
+ it('matches case-insensitively across renderer-owned loaded message data', () => {
+ expect(
+ findLoadedChatMessageMatches(
+ [message('one', 'Alpha alpha'), message('two', 'BETA Alpha')],
+ 'ALPHA'
+ )
+ ).toEqual([
+ { messageId: 'one', occurrence: 0 },
+ { messageId: 'one', occurrence: 1 },
+ { messageId: 'two', occurrence: 0 },
+ ])
+ })
+
+ it('uses visible user text rather than hidden attachment prompt content', () => {
+ const content =
+ 'Visible question\n\nUSER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.\nPlugins: hidden-search-plugin.'
+ expect(
+ findLoadedChatMessageMatches([message('user', content, 'user')], 'visible')
+ ).toHaveLength(1)
+ expect(
+ findLoadedChatMessageMatches([message('user', content, 'user')], 'hidden-search')
+ ).toEqual([])
+ })
+
+ it('wraps forward and backward through loaded matches', () => {
+ expect(wrapMatchIndex(2, 3, 1)).toBe(0)
+ expect(wrapMatchIndex(0, 3, -1)).toBe(2)
+ expect(wrapMatchIndex(0, 0, 1)).toBe(0)
+ })
+})
diff --git a/desktop-app/ui/src/lib/chatLocalSearch.ts b/desktop-app/ui/src/lib/chatLocalSearch.ts
new file mode 100644
index 000000000..d92374ac3
--- /dev/null
+++ b/desktop-app/ui/src/lib/chatLocalSearch.ts
@@ -0,0 +1,42 @@
+import type { AgentChatMessage } from '../uiTypes'
+import { parseChatMessageDisplay } from './chatMessageAttachments'
+
+export type ChatLocalMatch = {
+ messageId: string
+ occurrence: number
+}
+
+export function chatMessageDomId(messageId: string): string {
+ return `chat-message-${encodeURIComponent(messageId)}`
+}
+
+export function findLoadedChatMessageMatches(
+ messages: AgentChatMessage[],
+ query: string
+): ChatLocalMatch[] {
+ const needle = query.trim().toLocaleLowerCase()
+ if (!needle) return []
+ const matches: ChatLocalMatch[] = []
+ for (const message of messages) {
+ const displayed =
+ message.role === 'user'
+ ? (parseChatMessageDisplay(message.content)?.content ?? message.content)
+ : message.content
+ const haystack = displayed.toLocaleLowerCase()
+ let offset = 0
+ let occurrence = 0
+ while (offset <= haystack.length - needle.length) {
+ const index = haystack.indexOf(needle, offset)
+ if (index < 0) break
+ matches.push({ messageId: message.id, occurrence })
+ occurrence += 1
+ offset = index + Math.max(1, needle.length)
+ }
+ }
+ return matches
+}
+
+export function wrapMatchIndex(index: number, total: number, delta: 1 | -1): number {
+ if (total <= 0) return 0
+ return (index + delta + total) % total
+}
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index bd5b8945e..89112e9a3 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
-import { Button, StatusBanner } from '@components/Common'
+import { Button, StatusBanner, TextInput } from '@components/Common'
import {
IconChat,
IconClose,
@@ -154,6 +154,7 @@ export function SandboxUiPage({
toastShellOverlayOpen = false,
shortcutApp = null,
shortcutOpenRequestId = 0,
+ localSearchRequestId = 0,
onBackToConversation,
onEmbeddedAppOpening,
onEmbeddedAppBack,
@@ -168,7 +169,14 @@ export function SandboxUiPage({
const [refreshError, setRefreshError] = useState<{ appRef: string; message: string } | null>(null)
const [appsPage, setAppsPage] = useState(0)
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 embedSlotRef = useRef<HTMLDivElement>(null)
+ const localSearchInputRef = useRef<HTMLInputElement>(null)
+ const activeFindRequestIdRef = useRef<number | null>(null)
+ const lastLocalSearchRequestIdRef = useRef(0)
+ const localSearchPreviousFocusRef = useRef<HTMLElement | null>(null)
const lastShortcutOpenRequestIdRef = useRef(0)
const shellOverlayOpen =
headerShellOverlayOpen || sidebarShellOverlayOpen || toastShellOverlayOpen
@@ -213,6 +221,53 @@ export function SandboxUiPage({
return window.clerum.sandboxUi.onRefreshError(args => setRefreshError(args))
}, [])
+ useEffect(() => {
+ return window.clerum.sandboxUi.onFindResult(result => {
+ if (result.requestId !== activeFindRequestIdRef.current) return
+ setLocalSearchResult({ current: result.activeMatchOrdinal, total: result.matches })
+ })
+ }, [])
+
+ const stopLocalSearch = useCallback(() => {
+ activeFindRequestIdRef.current = null
+ setLocalSearchOpen(false)
+ setLocalSearchQuery('')
+ setLocalSearchResult({ current: 0, total: 0 })
+ void window.clerum.sandboxUi.stopFindInPage().catch(() => undefined)
+ const previous = localSearchPreviousFocusRef.current
+ requestAnimationFrame(() => {
+ if (previous?.isConnected) previous.focus()
+ })
+ }, [])
+
+ const runLocalSearch = useCallback(
+ async (query: string, options: { forward: boolean; findNext: boolean }) => {
+ if (!query.trim()) {
+ activeFindRequestIdRef.current = null
+ setLocalSearchResult({ current: 0, total: 0 })
+ await window.clerum.sandboxUi.stopFindInPage()
+ return
+ }
+ activeFindRequestIdRef.current = await window.clerum.sandboxUi.findInPage(query, options)
+ },
+ []
+ )
+
+ useEffect(() => {
+ if (localSearchRequestId <= lastLocalSearchRequestIdRef.current || launch.kind !== 'mounted') {
+ return
+ }
+ lastLocalSearchRequestIdRef.current = localSearchRequestId
+ localSearchPreviousFocusRef.current = document.activeElement as HTMLElement | null
+ setLocalSearchOpen(true)
+ requestAnimationFrame(() => localSearchInputRef.current?.focus())
+ }, [launch.kind, localSearchRequestId])
+
+ useEffect(() => {
+ if (launch.kind === 'mounted' || !localSearchOpen) return
+ stopLocalSearch()
+ }, [launch.kind, localSearchOpen, stopLocalSearch])
+
// Tear down the embed when this page unmounts (user navigates away).
useLayoutEffect(() => {
if (pendingSandboxUiUnmountCleanup !== null) {
@@ -486,6 +541,68 @@ export function SandboxUiPage({
text={`Session refresh failed: ${refreshError.message}. Close and re-open the app to continue.`}
/>
)}
+ {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, { forward: true, findNext: false })
+ }}
+ onKeyDown={event => {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ stopLocalSearch()
+ } else if (event.key === 'Enter') {
+ event.preventDefault()
+ void runLocalSearch(localSearchQuery, {
+ forward: !event.shiftKey,
+ findNext: true,
+ })
+ }
+ }}
+ placeholder="Find in current app"
+ value={localSearchQuery}
+ />
+ <span className="current-content-search__count" role="status" aria-live="polite">
+ {localSearchResult.current}/{localSearchResult.total}
+ </span>
+ <Button
+ aria-label="Previous app match"
+ color="neutral"
+ onClick={() =>
+ void runLocalSearch(localSearchQuery, { forward: false, findNext: true })
+ }
+ size="xs"
+ variant="ghost"
+ >
+ ↑
+ </Button>
+ <Button
+ aria-label="Next app match"
+ color="neutral"
+ onClick={() =>
+ void runLocalSearch(localSearchQuery, { forward: true, findNext: true })
+ }
+ size="xs"
+ variant="ghost"
+ >
+ ↓
+ </Button>
+ <Button
+ aria-label="Close current app search"
+ color="neutral"
+ onClick={stopLocalSearch}
+ size="xs"
+ variant="ghost"
+ >
+ ×
+ </Button>
+ </div>
+ ) : null}
{/* The slot div is the rectangle the WebContentsView floats above
after the selected app completes its initial load. */}
<div ref={embedSlotRef} className="sandbox-ui-embed-slot">
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.types.ts b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
index d1a632803..d863df1a6 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.types.ts
+++ b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
@@ -24,6 +24,7 @@ export type SandboxUiPageProps = {
toastShellOverlayOpen?: boolean
shortcutApp?: ActiveSandboxUiApp | null
shortcutOpenRequestId?: number
+ localSearchRequestId?: number
onBackToConversation?: () => void | Promise<void>
onEmbeddedAppOpening?: (app: ActiveSandboxUiApp) => void
onEmbeddedAppBack?: () => void
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
index 84fd0b753..375135d91 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
@@ -13,6 +13,9 @@ const sandboxUi = {
setBounds: vi.fn(),
setVisible: vi.fn(),
capturePreview: vi.fn(),
+ findInPage: vi.fn(),
+ stopFindInPage: vi.fn(),
+ onFindResult: vi.fn(() => vi.fn()),
onClosed: vi.fn(() => vi.fn()),
onRefreshError: vi.fn(() => vi.fn()),
}
@@ -26,6 +29,8 @@ describe('SandboxUiPage', () => {
vi.clearAllMocks()
sandboxUi.setBounds.mockResolvedValue(undefined)
sandboxUi.setVisible.mockResolvedValue(undefined)
+ sandboxUi.findInPage.mockResolvedValue(17)
+ sandboxUi.stopFindInPage.mockResolvedValue(undefined)
installClerumApi()
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
cb(0)
@@ -165,6 +170,41 @@ describe('SandboxUiPage', () => {
expect(screen.getAllByRole('button', { name: /^Back to / })).toHaveLength(1)
})
+ it('runs contextual find only against the mounted active WebContents contract', 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)
+
+ 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' } })
+ await waitFor(() => {
+ expect(sandboxUi.findInPage).toHaveBeenCalledWith('invoice', {
+ forward: true,
+ findNext: false,
+ })
+ })
+ fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
+ expect(sandboxUi.findInPage).toHaveBeenLastCalledWith('invoice', {
+ forward: false,
+ findNext: true,
+ })
+ fireEvent.keyDown(input, { key: 'Escape' })
+ expect(sandboxUi.stopFindInPage).toHaveBeenCalled()
+ expect(screen.queryByRole('textbox', { name: 'Find in current app' })).toBeNull()
+ })
+
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)
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index edbbd56ad..4460b3433 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -14822,3 +14822,33 @@ pre {
.chat-view-workspace {
display: contents;
}
+
+/* Contextual find surfaces remain in trusted Desktop chrome. */
+.current-content-search {
+ align-items: center;
+ align-self: flex-end;
+ background: var(--surface-strong);
+ border: 1px solid var(--border-soft);
+ border-radius: var(--radius-md);
+ display: flex;
+ gap: var(--space-1);
+ margin: var(--space-2) var(--space-3) 0;
+ padding: var(--space-1);
+ position: relative;
+ z-index: var(--layer-header);
+}
+
+.current-content-search__input {
+ min-width: 220px;
+}
+
+.current-content-search__count {
+ color: var(--text-muted);
+ font-size: var(--font-size-sm);
+ min-width: 44px;
+ text-align: center;
+}
+
+.chat-bubble[data-current-search-match='true'] {
+ box-shadow: 0 0 0 2px rgba(var(--focus-rgb), 0.9);
+}