Skip to content

The agent that grows with you

fix(desktop): scope Ctrl+F find to the current chat view (#81726)

Chen Jinab3b7394b19b
diff --git a/apps/desktop/src/components/find-bar.test.tsx b/apps/desktop/src/components/find-bar.test.tsx
index 56886a33105..1325d51a3e5 100644
--- a/apps/desktop/src/components/find-bar.test.tsx
+++ b/apps/desktop/src/components/find-bar.test.tsx
@@ -31,9 +31,13 @@ vi.mock('@/themes/context', () => ({
}))
// ── Bridge double ───────────────────────────────────────────────────────────
-// Stands in for the preload `hermesDesktop` surface. `onFoundInPage` records
-// its subscribers so the tests can assert the listener refcount and drive
-// results back into the store the way the main process would.
+// Stands in for the preload `hermesDesktop` surface. The primary window's
+// renderer-side walker no longer calls `findInPage` / `stopFindInPage`
+// (#81726); only `onFoundInPage` is still wired, for secondary session
+// windows that drive the search through Electron. `findInPage` /
+// `stopFindInPage` remain on the bridge for those secondary windows —
+// regression: the listener-refcount tests still want the bridge surface
+// defined so a multi-window secondary renderer could install it.
interface FoundResult {
activeMatchOrdinal: number
@@ -79,6 +83,25 @@ function drainListeners() {
resetFindInPageListenerForTest()
}
+/**
+ * Plant a chat surface in the DOM. The scoped walker resolves its scope from
+ * the foreground `[data-chat-surface]`, so any test that exercises a real
+ * search needs one — even just an empty container — to make sure the store
+ * has something to walk. `releaseFindScope` is called in afterEach via
+ * `cleanup` + a body reset, but tests that close the bar mid-flight also
+ * rely on `document.body.innerHTML = ''` between cases (see pane-visibility
+ * tests for the same pattern).
+ */
+function plantSurface(id = 'surface') {
+ const root = document.createElement('div')
+
+ root.setAttribute('data-chat-surface', '')
+ root.id = id
+ document.body.appendChild(root)
+
+ return root
+}
+
let bridge: ReturnType<typeof installBridge>
beforeEach(() => {
@@ -88,6 +111,7 @@ beforeEach(() => {
afterEach(() => {
cleanup()
+ document.body.innerHTML = ''
resetStore()
drainListeners()
vi.restoreAllMocks()
@@ -241,82 +265,236 @@ describe('find-in-page keybind registration', () => {
describe('find-in-page store', () => {
it('opens with a cleared query and counters', () => {
updateFindResults(3, 12)
+ plantSurface()
openFindBar()
expect($findInPage.get()).toEqual({ active: true, query: '', matchOrdinal: 0, matchCount: 0 })
})
- it('closing clears state and stops the native find (clears selection)', () => {
+ it('closing clears state and tears down the scoped highlights', () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle in a haystack, needle again'
openFindBar()
setFindQuery('needle')
- updateFindResults(2, 7)
+
+ expect($findInPage.get().matchCount).toBe(2)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
closeFindBar()
expect($findInPage.get().active).toBe(false)
expect($findInPage.get().query).toBe('')
expect($findInPage.get().matchCount).toBe(0)
- expect(bridge.stopFindInPage).toHaveBeenCalledTimes(1)
+ // Highlights are unwrapped; the original text is restored.
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect(surface.textContent).toBe('needle in a haystack, needle again')
})
- it('closing an already-closed bar does not re-issue stopFindInPage', () => {
+ it('closing an already-closed bar does not re-strip highlights', () => {
+ plantSurface()
openFindBar()
closeFindBar()
closeFindBar()
- expect(bridge.stopFindInPage).toHaveBeenCalledTimes(1)
+ // No thrown exception, no doubled DOM churn — the early return in
+ // closeFindBar short-circuits when the bar is already inactive.
+ expect($findInPage.get().active).toBe(false)
})
- it('a fresh query searches from scratch (findNext false)', () => {
+ it('a fresh query wraps matches and counts them', () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle haystack needle hay needle'
openFindBar()
setFindQuery('needle')
- expect(bridge.findInPage).toHaveBeenCalledWith('needle', { forward: true, findNext: false })
+ expect($findInPage.get().query).toBe('needle')
+ expect($findInPage.get().matchCount).toBe(3)
+ expect($findInPage.get().matchOrdinal).toBe(1)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(3)
})
- it('clearing the query stops the find instead of searching for empty', () => {
+ it('clearing the query unwraps highlights and zeroes the counter', () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle haystack needle'
openFindBar()
setFindQuery('needle')
- bridge.findInPage.mockClear()
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
setFindQuery('')
- expect(bridge.findInPage).not.toHaveBeenCalled()
- expect(bridge.stopFindInPage).toHaveBeenCalled()
expect($findInPage.get().matchCount).toBe(0)
+ expect($findInPage.get().query).toBe('')
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect(surface.textContent).toBe('needle haystack needle')
})
- it('findNext steps forward and findPrevious steps backward on the same query', () => {
+ it('findNext advances the active ordinal and findPrevious walks it back', () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle needle needle'
openFindBar()
setFindQuery('needle')
- bridge.findInPage.mockClear()
+
+ expect($findInPage.get().matchOrdinal).toBe(1)
findNext()
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: true, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(2)
+
+ findNext()
+ expect($findInPage.get().matchOrdinal).toBe(3)
+
+ // Wraps around at the end.
+ findNext()
+ expect($findInPage.get().matchOrdinal).toBe(1)
+
+ findPrevious()
+ // Wraps backward from 1 → 3.
+ expect($findInPage.get().matchOrdinal).toBe(3)
findPrevious()
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: false, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(2)
})
it('stepping with no query is a no-op (never searches invisibly)', () => {
+ plantSurface()
openFindBar()
findNext()
findPrevious()
- expect(bridge.findInPage).not.toHaveBeenCalled()
+ expect($findInPage.get().matchOrdinal).toBe(0)
+ expect($findInPage.get().matchCount).toBe(0)
})
it('setFindQuery on a closed bar never searches', () => {
// A debounce timer that already fired, or any late caller, must not
// re-highlight the page after the user dismissed the bar.
+ const surface = plantSurface()
+ surface.textContent = 'needle needle'
+
setFindQuery('needle')
- expect(bridge.findInPage).not.toHaveBeenCalled()
expect($findInPage.get().query).toBe('')
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ })
+
+ it('scopes the search to the active chat surface, never the whole document', () => {
+ // Regression (#81726): every active chat surface is mounted at once
+ // (keep-alive), so a global Ctrl+F used to match across all of them.
+ // The scoped walker must only wrap matches inside the surface the bar
+ // was opened against.
+ const foreground = plantSurface('foreground')
+ const hidden = document.createElement('div')
+
+ hidden.setAttribute('data-pane-hidden', '')
+ hidden.setAttribute('data-chat-surface', '')
+ hidden.id = 'background'
+ hidden.textContent = 'needle in background chat needle'
+ document.body.appendChild(hidden)
+
+ foreground.textContent = 'needle in foreground chat needle'
+
+ openFindBar()
+ setFindQuery('needle')
+
+ // Foreground: both matches wrapped. Background: untouched.
+ expect(foreground.querySelectorAll('mark.find-hit').length).toBe(2)
+ expect(hidden.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect($findInPage.get().matchCount).toBe(2)
+
+ closeFindBar()
+ expect(foreground.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect(hidden.querySelectorAll('mark.find-hit').length).toBe(0)
+ })
+
+ it('opening the bar twice on different surfaces retargets the scope', () => {
+ // The walker resolves the scope at openFindBar() time, so a bar opened
+ // while the foreground pane is chat-A searches chat-A, and a fresh bar
+ // opened after the pane flips to chat-B searches chat-B. The previous
+ // bar's highlights are already cleared by closeFindBar().
+ const surfaceA = plantSurface('a')
+ const surfaceB = document.createElement('div')
+
+ surfaceB.setAttribute('data-chat-surface', '')
+ surfaceB.id = 'b'
+ surfaceB.textContent = 'target-b needle'
+ document.body.appendChild(surfaceB)
+
+ surfaceA.textContent = 'target-a needle'
+
+ openFindBar()
+ setFindQuery('needle')
+
+ // Surface A is foreground; only its hit is wrapped.
+ expect(surfaceA.querySelectorAll('mark.find-hit').length).toBe(1)
+ expect(surfaceB.querySelectorAll('mark.find-hit').length).toBe(0)
+ closeFindBar()
+
+ // Flip visibility: surface B is now the foreground.
+ surfaceA.setAttribute('data-pane-hidden', '')
+
+ openFindBar()
+ setFindQuery('needle')
+
+ expect(surfaceA.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect(surfaceB.querySelectorAll('mark.find-hit').length).toBe(1)
+ expect($findInPage.get().matchCount).toBe(1)
+ })
+
+ it('a no-match query leaves the count at zero and the DOM untouched', () => {
+ const surface = plantSurface()
+ surface.textContent = 'hello world'
+
+ openFindBar()
+ setFindQuery('nothing-here')
+
+ expect($findInPage.get().matchCount).toBe(0)
+ expect($findInPage.get().matchOrdinal).toBe(0)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
})
- it('found-in-page results land on the store', () => {
+ it('match is case-insensitive', () => {
+ const surface = plantSurface()
+ surface.textContent = 'NEEDLE needle Needle'
+
+ openFindBar()
+ setFindQuery('needle')
+
+ expect($findInPage.get().matchCount).toBe(3)
+ })
+
+ it('a fresh query against existing highlights rewrites the marks (no leak)', () => {
+ const surface = plantSurface()
+ surface.textContent = 'alpha beta alpha beta'
+ openFindBar()
+ setFindQuery('alpha')
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
+
+ setFindQuery('beta')
+
+ // The previous marks were unwrapped before the new query highlighted.
+ expect($findInPage.get().matchCount).toBe(2)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
+ // Original text intact (no doubled marks / no lost text).
+ expect(surface.textContent).toBe('alpha beta alpha beta')
+ })
+
+ it('a query typed with no chat surface stays zero-count (parity with the bridge path)', () => {
+ // No chat surface in the DOM. The bar still tracks the typed query
+ // (matches the contract users had with the Electron bridge), but
+ // obviously cannot find anything — the view is whatever they're in.
+ openFindBar()
+ setFindQuery('needle')
+
+ expect($findInPage.get().query).toBe('needle')
+ expect($findInPage.get().matchCount).toBe(0)
+ expect($findInPage.get().matchOrdinal).toBe(0)
+ })
+
+ it('found-in-page results from a secondary window still land on the store', () => {
+ // Retained path: secondary session windows drive the Electron bridge,
+ // not the renderer-side walker. The bridge event still maps onto the
+ // same store shape.
+ plantSurface()
openFindBar()
setFindQuery('needle')
const release = initFindInPageListener()
@@ -411,6 +589,8 @@ describe('FindBar', () => {
})
it('renders input, counter and close button when open with results', async () => {
+ const surface = plantSurface()
+ surface.textContent = 'one two three four'
openFindBar()
renderFindBar()
@@ -425,11 +605,12 @@ describe('FindBar', () => {
// Counter appears once a query + results exist.
expect(screen.queryByText('3/12')).toBeNull()
- actStore(() => $findInPage.set({ active: true, query: 'needle', matchOrdinal: 3, matchCount: 12 }))
- await waitFor(() => expect(screen.getByText('3/12')).toBeTruthy())
+ actStore(() => $findInPage.set({ active: true, query: 'two', matchOrdinal: 1, matchCount: 1 }))
+ await waitFor(() => expect(screen.getByText('1/1')).toBeTruthy())
})
it('focuses the input on open', async () => {
+ plantSurface()
openFindBar()
renderFindBar()
@@ -438,8 +619,10 @@ describe('FindBar', () => {
await waitFor(() => expect(document.activeElement).toBe(input))
})
- it('debounces typing into a single findInPage call', async () => {
+ it('debounces typing into a single scoped find', async () => {
vi.useFakeTimers()
+ const surface = plantSurface()
+ surface.textContent = 'one nee needle'
try {
openFindBar()
@@ -450,15 +633,18 @@ describe('FindBar', () => {
fireEvent.change(input, { target: { value: 'ne' } })
fireEvent.change(input, { target: { value: 'nee' } })
- expect(bridge.findInPage).not.toHaveBeenCalled()
+ // No marks yet — debounced.
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
// Flushing the debounce updates the store, which re-renders the bar.
act(() => {
vi.advanceTimersByTime(200)
})
- expect(bridge.findInPage).toHaveBeenCalledTimes(1)
- expect(bridge.findInPage).toHaveBeenCalledWith('nee', { forward: true, findNext: false })
+ // Now the scoped walker has wrapped the matches.
+ expect($findInPage.get().query).toBe('nee')
+ expect($findInPage.get().matchCount).toBe(2)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
} finally {
vi.useRealTimers()
}
@@ -496,6 +682,8 @@ describe('FindBar', () => {
it('does not fire a pending search after the bar closes', async () => {
vi.useFakeTimers()
+ const surface = plantSurface()
+ surface.textContent = 'needle'
try {
openFindBar()
@@ -508,70 +696,97 @@ describe('FindBar', () => {
actStore(closeFindBar)
vi.advanceTimersByTime(500)
- expect(bridge.findInPage).not.toHaveBeenCalled()
+ // The debounced timer that already fired is gated by `active`, so
+ // closing the bar prevents the walker from running.
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect($findInPage.get().query).toBe('')
} finally {
vi.useRealTimers()
}
})
- it('Enter dispatches next and Shift+Enter dispatches previous', async () => {
- $findInPage.set({ active: true, query: 'needle', matchOrdinal: 1, matchCount: 4 })
- renderFindBar()
+ it('Enter dispatches next and Shift+Enter dispatches previous', () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle needle needle'
+ $findInPage.set({ active: true, query: 'needle', matchOrdinal: 1, matchCount: 3 })
+ // Manually replay the open+query path so the marks exist for stepping.
+ openFindBar()
+ setFindQuery('needle')
+ renderFindBar()
const input = screen.getByRole('searchbox', { name: /find in page/i })
fireEvent.keyDown(input, { key: 'Enter' })
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: true, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(2)
fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: false, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(1)
})
it('Cmd+G / Cmd+Shift+G step from outside the input while the bar is open', async () => {
- $findInPage.set({ active: true, query: 'needle', matchOrdinal: 1, matchCount: 4 })
+ const surface = plantSurface()
+ surface.textContent = 'needle needle needle'
+
+ openFindBar()
+ setFindQuery('needle')
+ expect($findInPage.get().matchOrdinal).toBe(1)
+
renderFindBar()
// Fired on window (not the input) — the accelerator must not require focus.
fireEvent.keyDown(window, { key: 'g', metaKey: true })
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: true, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(2)
fireEvent.keyDown(window, { key: 'G', metaKey: true, shiftKey: true })
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: false, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(1)
})
- it('Escape closes the bar and clears the native selection', async () => {
+ it('Escape closes the bar and unwraps the highlights', async () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle haystack'
openFindBar()
- renderFindBar()
+ setFindQuery('needle')
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
+ renderFindBar()
fireEvent.keyDown(window, { key: 'Escape' })
expect($findInPage.get().active).toBe(false)
- expect(bridge.stopFindInPage).toHaveBeenCalledTimes(1)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
await waitFor(() => expect(screen.queryByRole('search')).toBeNull())
})
- it('the close button clears state and stops the find', async () => {
+ it('the close button clears state and unwraps the highlights', async () => {
+ const surface = plantSurface()
+ surface.textContent = 'needle haystack'
openFindBar()
- renderFindBar()
+ setFindQuery('needle')
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
+ renderFindBar()
fireEvent.click(screen.getByRole('button', { name: /close/i }))
expect($findInPage.get().active).toBe(false)
- expect(bridge.stopFindInPage).toHaveBeenCalledTimes(1)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
})
it('the next / previous buttons dispatch a step', () => {
- $findInPage.set({ active: true, query: 'needle', matchOrdinal: 1, matchCount: 4 })
+ const surface = plantSurface()
+ surface.textContent = 'needle needle needle'
+ openFindBar()
+ setFindQuery('needle')
+
renderFindBar()
fireEvent.click(screen.getByRole('button', { name: /next match/i }))
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: true, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(2)
fireEvent.click(screen.getByRole('button', { name: /previous match/i }))
- expect(bridge.findInPage).toHaveBeenLastCalledWith('needle', { forward: false, findNext: true })
+ expect($findInPage.get().matchOrdinal).toBe(1)
})
it('keeps exactly one bridge subscription across an open/close cycle', async () => {
+ plantSurface()
renderFindBar()
// Mounted-but-closed already holds the subscription: results for an
@@ -592,6 +807,7 @@ describe('FindBar', () => {
it('unmount releases the bridge subscription (no leak across route changes)', () => {
const { unmount } = renderFindBar()
+
expect(bridge.subscribers.size).toBe(1)
unmount()
@@ -612,43 +828,54 @@ describe('FindBar', () => {
})
it('the window key listener is removed on unmount', () => {
+ plantSurface()
openFindBar()
const { unmount } = renderFindBar()
+ expect($findInPage.get().active).toBe(true)
+
unmount()
- bridge.stopFindInPage.mockClear()
- // Reopen the store WITHOUT a mounted bar; a leaked listener would still
- // handle Escape and call into the bridge.
+ // Reopen the store WITHOUT a mounted bar; a leaked listener would
+ // intercept Escape and call closeFindBar, flipping $findInPage back to
+ // inactive. With the listener removed, the Escape bubbles into the
+ // void and the store stays open — proving the bar's capture-phase
+ // window listener did not leak.
actStore(openFindBar)
fireEvent.keyDown(window, { key: 'Escape' })
- expect(bridge.stopFindInPage).not.toHaveBeenCalled()
+ expect($findInPage.get().active).toBe(true)
})
it('navigating to another route closes the bar and clears the highlights', async () => {
- const { navigate } = renderFindBarWithNavigation('/session/a')
+ const surface = plantSurface()
+ surface.textContent = 'needle haystack'
+ openFindBar()
+ setFindQuery('needle')
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
- actStore(openFindBar)
- actStore(() => $findInPage.set({ active: true, query: 'needle', matchOrdinal: 2, matchCount: 7 }))
+ const { navigate } = renderFindBarWithNavigation('/session/a')
await waitFor(() => expect(screen.getByRole('search')).toBeTruthy())
navigate('/session/b')
- // Bar gone, state reset, and the native selection cleared — stale
- // highlights must not survive a session switch.
+ // Bar gone, state reset, and the highlights stripped — stale marks
+ // must not survive a session switch.
await waitFor(() => expect(screen.queryByRole('search')).toBeNull())
expect($findInPage.get()).toEqual({ active: false, query: '', matchOrdinal: 0, matchCount: 0 })
- expect(bridge.stopFindInPage).toHaveBeenCalledTimes(1)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
})
it('navigation while the bar is closed does not reach into the bridge', async () => {
+ plantSurface()
const { navigate } = renderFindBarWithNavigation('/session/a')
navigate('/session/b')
await waitFor(() => expect(screen.queryByRole('search')).toBeNull())
- expect(bridge.stopFindInPage).not.toHaveBeenCalled()
+ // No thrown exception, no DOM churn — the route-change cleanup is a
+ // no-op when there's no bar to close.
+ expect($findInPage.get().active).toBe(false)
})
it('does not render on overlay routes (settings, command center, …)', () => {
diff --git a/apps/desktop/src/lib/find-in-page-scope.test.ts b/apps/desktop/src/lib/find-in-page-scope.test.ts
new file mode 100644
index 00000000000..3741fcf8b29
--- /dev/null
+++ b/apps/desktop/src/lib/find-in-page-scope.test.ts
@@ -0,0 +1,247 @@
+/**
+ * Unit tests for the renderer-side find walker.
+ *
+ * These tests plant DOM by hand and drive the walker directly so the
+ * behavior is auditable without spinning up the React store. The end-to-
+ * end behavior (open / setFindQuery / step) is covered by find-bar.test.tsx.
+ */
+
+import { afterEach, describe, expect, it } from 'vitest'
+
+import {
+ captureFindScope,
+ currentFindScope,
+ performScopedFind,
+ releaseFindScope,
+ resolveCurrentFindScope
+} from './find-in-page-scope'
+
+function plantSurface(id: string, html: string, hidden = false): HTMLElement {
+ const root = document.createElement('div')
+
+ root.id = id
+ root.setAttribute('data-chat-surface', '')
+
+ if (hidden) {
+ root.setAttribute('data-pane-hidden', '')
+ }
+
+ root.innerHTML = html
+ document.body.appendChild(root)
+
+ return root
+}
+
+afterEach(() => {
+ document.body.innerHTML = ''
+})
+
+describe('resolveCurrentFindScope', () => {
+ it('returns the foreground chat surface and skips hidden ones', () => {
+ plantSurface('background', 'hidden chat', true)
+ const foreground = plantSurface('foreground', 'visible chat')
+
+ expect(resolveCurrentFindScope()?.id).toBe('foreground')
+ // Marking it lets currentFindScope find it without re-resolving.
+ captureFindScope()
+ expect(currentFindScope()?.id).toBe('foreground')
+ })
+
+ it('returns null when no chat surface is mounted', () => {
+ expect(resolveCurrentFindScope()).toBeNull()
+ })
+
+ it('returns the FIRST visible chat surface in document order', () => {
+ // queryVisible follows document order — the first matching surface
+ // wins. Visibility (hidden panes are skipped) is the only filter.
+ plantSurface('first', 'one')
+ plantSurface('second', 'two')
+
+ expect(resolveCurrentFindScope()?.id).toBe('first')
+ })
+})
+
+describe('performScopedFind', () => {
+ it('wraps every (case-insensitive) match in a <mark> and counts them', () => {
+ const surface = plantSurface('surface', '<p>NEEDLE needle Needle</p>')
+
+ const result = performScopedFind(surface, 'needle', { forward: true, findNext: false })
+
+ expect(result.count).toBe(3)
+ expect(result.activeOrdinal).toBe(1)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(3)
+ // The first <mark> carries the active marker.
+ expect(surface.querySelectorAll('mark.find-hit[data-find-active]').length).toBe(1)
+ })
+
+ it('returns zero counts when the query has no matches and leaves the DOM untouched', () => {
+ const surface = plantSurface('surface', '<p>hello world</p>')
+
+ const result = performScopedFind(surface, 'nothing', { forward: true, findNext: false })
+
+ expect(result).toEqual({ count: 0, activeOrdinal: 0 })
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect(surface.querySelector('p')?.textContent).toBe('hello world')
+ })
+
+ it('clears highlights and zeroes the counter when the query is empty', () => {
+ const surface = plantSurface('surface', '<p>needle in a haystack</p>')
+ performScopedFind(surface, 'needle', { forward: true, findNext: false })
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
+
+ const result = performScopedFind(surface, '', { forward: true, findNext: false })
+
+ expect(result).toEqual({ count: 0, activeOrdinal: 0 })
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ // Original text restored.
+ expect(surface.querySelector('p')?.textContent).toBe('needle in a haystack')
+ })
+
+ it('advances the active mark on findNext and walks back on findPrevious', () => {
+ const surface = plantSurface('surface', '<p>a a a a</p>')
+ performScopedFind(surface, 'a', { forward: true, findNext: false })
+
+ const first = surface.querySelectorAll('mark.find-hit')
+ expect(first.length).toBe(4)
+ expect(first[0].hasAttribute('data-find-active')).toBe(true)
+
+ // Step forward twice; the active ordinal cycles 1 → 2 → 3.
+ let result = performScopedFind(surface, 'a', { forward: true, findNext: true })
+ expect(result.activeOrdinal).toBe(2)
+ result = performScopedFind(surface, 'a', { forward: true, findNext: true })
+ expect(result.activeOrdinal).toBe(3)
+
+ // Step backward once → 2.
+ result = performScopedFind(surface, 'a', { forward: false, findNext: true })
+ expect(result.activeOrdinal).toBe(2)
+
+ // Wrap: from the last match forward wraps to 1.
+ performScopedFind(surface, 'a', { forward: true, findNext: true })
+ performScopedFind(surface, 'a', { forward: true, findNext: true }) // → 4
+ result = performScopedFind(surface, 'a', { forward: true, findNext: true }) // → wraps to 1
+ expect(result.activeOrdinal).toBe(1)
+
+ // Backward wrap: from 1 → 4.
+ result = performScopedFind(surface, 'a', { forward: false, findNext: true })
+ expect(result.activeOrdinal).toBe(4)
+ })
+
+ it('lands on the LAST match when entering find mode backwards', () => {
+ const surface = plantSurface('surface', '<p>a a a</p>')
+ const result = performScopedFind(surface, 'a', { forward: false, findNext: false })
+
+ expect(result.activeOrdinal).toBe(3)
+ })
+
+ it('does not re-wrap when stepping with the same query (findNext fast path)', () => {
+ const surface = plantSurface('surface', '<p>a a a a</p>')
+ performScopedFind(surface, 'a', { forward: true, findNext: false })
+
+ const before = [...surface.querySelectorAll('mark.find-hit')]
+ const result = performScopedFind(surface, 'a', { forward: true, findNext: true })
+
+ // Same elements — the walker advanced the active marker rather than
+ // tearing the DOM down and rebuilding it.
+ const after = [...surface.querySelectorAll('mark.find-hit')]
+ expect(after.length).toBe(before.length)
+ expect(after.every(el => before.includes(el))).toBe(true)
+ expect(result.count).toBe(4)
+ expect(result.activeOrdinal).toBe(2)
+ })
+
+ it('re-wraps when the query changes (marks are not reused across queries)', () => {
+ const surface = plantSurface('surface', '<p>alpha beta alpha</p>')
+ performScopedFind(surface, 'alpha', { forward: true, findNext: false })
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
+
+ performScopedFind(surface, 'beta', { forward: true, findNext: false })
+
+ // The alpha marks are gone; the beta mark is wrapped.
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
+ expect(surface.querySelector('mark.find-hit')?.textContent).toBe('beta')
+ expect(surface.querySelector('p')?.textContent).toBe('alpha beta alpha')
+ })
+
+ it('ignores text inside the FindBar search input itself (no self-match)', () => {
+ // The walker skips any subtree that carries role="search" so a user
+ // typing "needle" never matches the placeholder text in the input.
+ const surface = plantSurface('surface', '')
+ surface.innerHTML = `
+ <div role="search"><input placeholder="needle placeholder" /></div>
+ <p>needle haystack</p>
+ `
+
+ const result = performScopedFind(surface, 'needle', { forward: true, findNext: false })
+
+ expect(result.count).toBe(1)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
+ // The mark lives inside the <p>, not inside the search overlay.
+ expect(surface.querySelector('mark.find-hit')?.closest('p')).toBeTruthy()
+ })
+
+ it('does not match inside <script> / <style> nodes', () => {
+ const surface = plantSurface('surface', '')
+ surface.innerHTML = `
+ <script>const needle = 'literal'</script>
+ <style>.needle { color: red }</style>
+ <p>needle visible</p>
+ `
+
+ const result = performScopedFind(surface, 'needle', { forward: true, findNext: false })
+
+ expect(result.count).toBe(1)
+ expect(surface.querySelector('mark.find-hit')?.textContent).toBe('needle')
+ })
+
+ it('does not double-match when re-running the SAME query in findNext mode', () => {
+ const surface = plantSurface('surface', '<p>needle needle</p>')
+ performScopedFind(surface, 'needle', { forward: true, findNext: false })
+
+ // The walker must recognize that the existing marks already represent
+ // this query and advance the active marker without rebuilding.
+ const result = performScopedFind(surface, 'needle', { forward: true, findNext: true })
+
+ expect(result.count).toBe(2)
+ expect(result.activeOrdinal).toBe(2)
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(2)
+ })
+})
+
+describe('scope lifecycle', () => {
+ it('captureFindScope marks the foreground surface for the walker', () => {
+ const surface = plantSurface('surface', 'needle')
+ captureFindScope()
+
+ expect(currentFindScope()).toBe(surface)
+ expect(surface.hasAttribute('data-find-root')).toBe(true)
+ })
+
+ it('releaseFindScope unwraps every highlight and clears the scope marker', () => {
+ const surface = plantSurface('surface', '<p>needle in a haystack</p>')
+ captureFindScope()
+ performScopedFind(surface, 'needle', { forward: true, findNext: false })
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(1)
+
+ releaseFindScope()
+
+ expect(surface.querySelectorAll('mark.find-hit').length).toBe(0)
+ expect(surface.querySelector('[data-find-root]')).toBeNull()
+ expect(currentFindScope()).toBeNull()
+ // Original text restored.
+ expect(surface.querySelector('p')?.textContent).toBe('needle in a haystack')
+ })
+
+ it('keeps the scope targeting the FOREGROUND surface even when a hidden one matches the selector first', () => {
+ // Regression (#81726): the visible chat is the SECOND surface in
+ // document order, but it must still win the scope resolution.
+ plantSurface('background', '<p>background needle</p>', true)
+ const foreground = plantSurface('foreground', '<p>foreground needle</p>')
+
+ captureFindScope()
+ expect(currentFindScope()).toBe(foreground)
+
+ // The walker only wraps the foreground's match.
+ const result = performScopedFind(foreground, 'needle', { forward: true, findNext: false })
+ expect(result.count).toBe(1)
+ })
+})
\ No newline at end of file
diff --git a/apps/desktop/src/lib/find-in-page-scope.ts b/apps/desktop/src/lib/find-in-page-scope.ts
new file mode 100644
index 00000000000..7d21222af7f
--- /dev/null
+++ b/apps/desktop/src/lib/find-in-page-scope.ts
@@ -0,0 +1,358 @@
+/**
+ * Renderer-side find-in-page that scopes matches to the CURRENT VIEW — the
+ * active chat surface — instead of the whole document.
+ *
+ * Background. Electron's `webContents.findInPage` searches the renderer's
+ * entire DOM. The desktop chat shell mounts every ever-active chat surface
+ * simultaneously (see apps/desktop/AGENTS.md and the keep-alive comment in
+ * apps/desktop/src/app/chat/index.tsx), so a global search matches across
+ * every conversation, every background tile, and every other pane that
+ * happens to render a transcript. That is not what the user expects when
+ * they press ⌘F in a chat — they expect to search the chat they are reading
+ * (#81726).
+ *
+ * Strategy. At bar-open time, capture the active chat surface element and
+ * remember it for the lifetime of the find bar. Subsequent queries highlight
+ * only text nodes inside that subtree. ⌘G / ⌘⇧G step between highlights
+ * inside the same subtree. Closing the bar unwraps the highlights.
+ *
+ * "Current view" is the foreground `[data-chat-surface]` element after
+ * filtering out inactive keep-alive tabs. That is the same policy every
+ * other document-wide lookup obeys (see pane-visibility.ts), so this can be
+ * reasoned about as "find wherever the user is reading".
+ *
+ * Implementation notes:
+ * - We wrap each match in a `<mark class="find-hit">` so the active match is
+ * a single class toggle. Walking raw text nodes lets us split a node that
+ * spans a match boundary without disturbing the surrounding React tree
+ * (text nodes are inert for React reconciliation until the parent changes).
+ * - The active ordinal is the 1-indexed position of the match whose
+ * `<mark>` carries `data-active`. We re-derive it on every step instead of
+ * keeping a counter, so a stale count after a DOM mutation self-heals on
+ * the next search.
+ * - We do NOT call `webContents.findInPage` from here. That bridge still
+ * exists for multi-window secondary sessions (each window searches its
+ * own webContents), but for the primary window it cannot be scoped, so
+ * the renderer-side walker is the only path that satisfies the issue.
+ */
+
+import { queryVisible } from '@/components/pane-shell/pane-visibility'
+
+const SCOPE_SELECTOR = '[data-chat-surface]'
+const HIGHLIGHT_CLASS = 'find-hit'
+const ACTIVE_ATTR = 'data-find-active'
+const ROOT_ATTR = 'data-find-root'
+
+/**
+ * The element the open FindBar should search. Captured at bar-open time and
+ * reused for every query / step until the bar closes. Reading the visible
+ * chat surface here means the scope follows the user's current focus —
+ * pressing ⌘F in chat A searches chat A even if the route later flips to
+ * chat B before the user finishes typing (a typed query still targets A;
+ * route-change cleanup in FindBar closes the bar first).
+ */
+export function resolveCurrentFindScope(): HTMLElement | null {
+ return queryVisible<HTMLElement>(SCOPE_SELECTOR)
+}
+
+/** Capture the current view as the find scope. Called when the bar opens. */
+export function captureFindScope(): HTMLElement | null {
+ const root = resolveCurrentFindScope()
+
+ if (root) {
+ root.setAttribute(ROOT_ATTR, '')
+ }
+
+ return root
+}
+
+/** The scope captured by the open bar, or null if none is active. */
+export function currentFindScope(): HTMLElement | null {
+ const roots = document.querySelectorAll<HTMLElement>(`[${ROOT_ATTR}]`)
+
+ for (const root of roots) {
+ if (!isElementInHiddenPane(root)) {
+ return root
+ }
+ }
+
+ return null
+}
+
+/** Same predicate pane-visibility exposes, kept local so this module is
+ * independently testable without an import cycle in the renderer. */
+function isElementInHiddenPane(element: Element): boolean {
+ return Boolean(element.closest('[data-pane-hidden]'))
+}
+
+/**
+ * Walk `root`'s text nodes in document order, wrapping every (case-
+ * insensitive) occurrence of `query` in a `<mark class="find-hit">`.
+ *
+ * Splits text nodes that span a match boundary so React (or any other
+ * framework holding the parent) sees the text-node change as a normal DOM
+ * mutation. Returns the marks in document order — the same order the step
+ * functions use to walk forward / backward.
+ *
+ * Implementation: walk forward, accumulating the global text offset and the
+ * active text node as we go. When we hit a match, split the text node,
+ * wrap the matched slice, and JUMP the offset past the wrapped region so we
+ * don't re-match inside our own `<mark>`. Crucially, we update the text-
+ * node pointer AFTER the wrap, so the next search step sees the new node
+ * layout rather than the (now detached) original.
+ */
+function highlightMatches(root: Element, query: string): HTMLElement[] {
+ const marks: HTMLElement[] = []
+ const lowerQuery = query.toLowerCase()
+
+ if (!lowerQuery) {
+ return marks
+ }
+
+ let current: Node | null = root.firstChild
+ let textNode: Text | null = null
+
+ // Outer loop: walk element children until we have a text node to search.
+ while (current) {
+ if (current.nodeType === Node.TEXT_NODE) {
+ textNode = current as Text
+ } else if (current.nodeType === Node.ELEMENT_NODE) {
+ const el = current as Element
+
+ // Skip elements we never want to search into. The walker is
+ // deliberately flat (no recursion); a nested <p> in a <section>
+ // becomes a fresh descendant scan via the recursive call below.
+ if (shouldSkipElement(el)) {
+ current = el.nextSibling
+
+ continue
+ }
+
+ // Recurse into the element's descendants.
+ const inner = highlightMatches(el, query)
+
+ marks.push(...inner)
+ current = el.nextSibling
+
+ continue
+ } else {
+ current = current.nextSibling
+
+ continue
+ }
+
+ if (!textNode || !textNode.parentNode) {
+ current = textNode?.nextSibling ?? null
+
+ continue
+ }
+
+ // Search within this text node. Splits may invalidate `textNode`'s
+ // identity, so we re-read it from the parent each iteration.
+ let nodeValue = textNode.nodeValue ?? ''
+
+ while (true) {
+ const lower = nodeValue.toLowerCase()
+ const idx = lower.indexOf(lowerQuery)
+
+ if (idx === -1) {
+ break
+ }
+
+ const before = nodeValue.slice(0, idx)
+ const matchText = nodeValue.slice(idx, idx + lowerQuery.length)
+ const after = nodeValue.slice(idx + lowerQuery.length)
+ const parent = textNode.parentNode
+
+ if (!parent) {
+ break
+ }
+
+ const fragment = document.createDocumentFragment()
+
+ if (before) {
+ fragment.appendChild(document.createTextNode(before))
+ }
+
+ const mark = document.createElement('mark')
+
+ mark.className = HIGHLIGHT_CLASS
+ mark.textContent = matchText
+ fragment.appendChild(mark)
+
+ // Capture the after-sibling BEFORE replaceChild — replaceChild moves
+ // the fragment's children into the parent and empties the fragment,
+ // so looking at `fragment.lastChild` afterwards would point at a
+ // detached `<mark>` (or null if `before` was empty).
+ const afterNode = after ? document.createTextNode(after) : null
+
+ if (afterNode) {
+ fragment.appendChild(afterNode)
+ }
+
+ parent.replaceChild(fragment, textNode)
+
+ marks.push(mark)
+
+ if (!afterNode) {
+ // Whole text node consumed — nothing left to scan in this region.
+ textNode = null
+
+ break
+ }
+
+ textNode = afterNode
+ nodeValue = afterNode.nodeValue ?? ''
+ }
+
+ current = textNode ? textNode.nextSibling : null
+ }
+
+ return marks
+}
+
+/** Elements we never want to descend into during a search. Mirrors the
+ * filter the TreeWalker applied in the original design. */
+function shouldSkipElement(el: Element): boolean {
+ const tag = el.tagName
+
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT') {
+ return true
+ }
+
+ if (el.closest(`mark.${HIGHLIGHT_CLASS}`)) {
+ return true
+ }
+
+ if (el.closest('[role="search"]')) {
+ return true
+ }
+
+ return false
+}
+
+/** Remove every find-hit mark we previously added, restoring original text. */
+function clearHighlights(root: Element): void {
+ const marks = root.querySelectorAll<HTMLElement>(`mark.${HIGHLIGHT_CLASS}`)
+
+ for (const mark of marks) {
+ const parent = mark.parentNode
+
+ if (!parent) {
+ continue
+ }
+
+ while (mark.firstChild) {
+ parent.insertBefore(mark.firstChild, mark)
+ }
+
+ parent.removeChild(mark)
+ parent.normalize()
+ }
+}
+
+/** Mark one element as the active match and scroll it into view. */
+function setActiveMark(mark: HTMLElement | null): void {
+ document.querySelectorAll(`mark[${ACTIVE_ATTR}]`).forEach(el => el.removeAttribute(ACTIVE_ATTR))
+
+ if (!mark) {
+ return
+ }
+
+ mark.setAttribute(ACTIVE_ATTR, '')
+ // Block: 'nearest' so a match already on screen doesn't twitch, but a
+ // match below the fold scrolls into view instead of silently landing off-
+ // screen. Inline: 'nearest' for the same reason. Guarded: jsdom does not
+ // implement scrollIntoView, and the bar still needs to highlight even
+ // when the renderer side has no layout (tests, headless boot, …).
+ if (typeof mark.scrollIntoView === 'function') {
+ mark.scrollIntoView({ block: 'nearest', inline: 'nearest' })
+ }
+}
+
+/** Result of a find / step — the same shape the bar already shows. */
+export interface ScopedFindResult {
+ count: number
+ activeOrdinal: number
+}
+
+export interface ScopedFindOptions {
+ forward: boolean
+ findNext: boolean
+}
+
+const DEFAULT_RESULT: ScopedFindResult = { count: 0, activeOrdinal: 0 }
+
+/**
+ * Run a scoped find against `root`. When `findNext` is true, advance / step
+ * the active mark without re-highlighting (the query has not changed). When
+ * false, drop prior highlights and re-wrap matches for `query`.
+ *
+ * Returns the (count, activeOrdinal) the bar should display. Returning a
+ * plain object instead of pushing into the store keeps this helper testable
+ * without a nanostores harness — the store wires it up.
+ */
+export function performScopedFind(
+ root: Element,
+ query: string,
+ options: ScopedFindOptions
+): ScopedFindResult {
+ if (!query) {
+ clearHighlights(root)
+ setActiveMark(null)
+
+ return DEFAULT_RESULT
+ }
+
+ const existingMarks = [...root.querySelectorAll<HTMLElement>(`mark.${HIGHLIGHT_CLASS}`)]
+ const sameQuery =
+ options.findNext &&
+ existingMarks.length > 0 &&
+ existingMarks.every(mark => mark.textContent === query)
+
+ let marks = existingMarks
+
+ if (!sameQuery) {
+ clearHighlights(root)
+ marks = highlightMatches(root, query)
+ }
+
+ if (marks.length === 0) {
+ setActiveMark(null)
+
+ return DEFAULT_RESULT
+ }
+
+ const previousActive = root.querySelector<HTMLElement>(`mark[${ACTIVE_ATTR}]`)
+ let nextIndex = 0
+
+ if (previousActive) {
+ const previousIndex = marks.indexOf(previousActive)
+
+ if (previousIndex !== -1) {
+ nextIndex = options.forward
+ ? (previousIndex + 1) % marks.length
+ : (previousIndex - 1 + marks.length) % marks.length
+ }
+ } else if (!options.forward) {
+ // Entering find mode backwards (Shift+Enter on first press): land on the
+ // last match, matching browser convention.
+ nextIndex = marks.length - 1
+ }
+
+ setActiveMark(marks[nextIndex] ?? null)
+
+ return { count: marks.length, activeOrdinal: nextIndex + 1 }
+}
+
+/** Tear down highlights and the scope marker — called when the bar closes. */
+export function releaseFindScope(): void {
+ const roots = document.querySelectorAll<HTMLElement>(`[${ROOT_ATTR}]`)
+
+ for (const root of roots) {
+ clearHighlights(root)
+ root.removeAttribute(ROOT_ATTR)
+ }
+
+ setActiveMark(null)
+}
\ No newline at end of file
diff --git a/apps/desktop/src/store/find-in-page.ts b/apps/desktop/src/store/find-in-page.ts
index d106a081881..037d4daa30b 100644
--- a/apps/desktop/src/store/find-in-page.ts
+++ b/apps/desktop/src/store/find-in-page.ts
@@ -1,5 +1,12 @@
import { atom } from 'nanostores'
+import {
+ captureFindScope,
+ currentFindScope,
+ performScopedFind,
+ releaseFindScope
+} from '@/lib/find-in-page-scope'
+
export interface FindInPageState {
active: boolean
query: string
@@ -11,21 +18,33 @@ const EMPTY: FindInPageState = { active: false, query: '', matchOrdinal: 0, matc
export const $findInPage = atom<FindInPageState>({ ...EMPTY })
+/**
+ * Open the find bar and capture the CURRENT VIEW as the search scope.
+ *
+ * Capturing once at open time (rather than re-resolving on every keystroke)
+ * means a mid-search route change can't silently re-home the highlights onto
+ * a different session — the FindBar's `useLocation` cleanup closes the bar
+ * before the route flips, so the scope the user actually sees in the input
+ * is the only one ever searched. See apps/desktop/src/components/find-bar.tsx
+ * for the route-change close logic; see lib/find-in-page-scope.ts for the
+ * "current view" predicate (#81726).
+ */
export function openFindBar(): void {
$findInPage.set({ ...EMPTY, active: true })
+ captureFindScope()
}
export function closeFindBar(): void {
- // Already closed: don't re-issue stopFindInPage. Escape is a shared gesture
- // (the switcher and dialogs claim it too), so a stray second close must not
- // reach into Electron again.
+ // Already closed: don't re-issue clear. Escape is a shared gesture (the
+ // switcher and dialogs claim it too), so a stray second close must not
+ // re-strip highlights from a bar that has already been torn down.
if (!$findInPage.get().active) {
return
}
$findInPage.set({ ...EMPTY })
- // Clears both the search and the native highlight/selection in the page.
- void window.hermesDesktop?.stopFindInPage()
+ // Strip highlights and the scope marker from the DOM we previously wrapped.
+ releaseFindScope()
}
export async function setFindQuery(query: string): Promise<void> {
@@ -33,39 +52,70 @@ export async function setFindQuery(query: string): Promise<void> {
// Never search for a closed bar. The component clears its debounce on
// close, but a timer that already fired (or any late caller) must not
- // re-issue a find and re-highlight the page after the user pressed Escape.
+ // re-wrap matches after the user pressed Escape.
if (!prev.active) {
return
}
if (!query) {
$findInPage.set({ ...prev, query: '', matchOrdinal: 0, matchCount: 0 })
- void window.hermesDesktop?.stopFindInPage()
+ const scope = currentFindScope()
+
+ if (scope) {
+ // Re-run the scoped walker with an empty query — same code path,
+ // strips highlights + zeroes the counter without special-casing.
+ performScopedFind(scope, '', { forward: true, findNext: false })
+ }
return
}
- $findInPage.set({ ...prev, query })
- await window.hermesDesktop?.findInPage(query, { forward: true, findNext: false })
-}
+ const scope = currentFindScope()
-export function findNext(): void {
- const { query } = $findInPage.get()
+ if (!scope) {
+ // No chat surface to search (e.g. settings page, command center). The
+ // bar still accepts a query for parity with the bridge-driven path, but
+ // matches will be zero — there's nothing on screen that IS a "view".
+ $findInPage.set({ ...prev, query, matchOrdinal: 0, matchCount: 0 })
- if (query) {
- void window.hermesDesktop?.findInPage(query, { forward: true, findNext: true })
+ return
}
+
+ const result = performScopedFind(scope, query, { forward: true, findNext: false })
+
+ $findInPage.set({ ...prev, query, matchOrdinal: result.activeOrdinal, matchCount: result.count })
+}
+
+export function findNext(): void {
+ step(true)
}
export function findPrevious(): void {
+ step(false)
+}
+
+function step(forward: boolean): void {
const { query } = $findInPage.get()
- if (query) {
- void window.hermesDesktop?.findInPage(query, { forward: false, findNext: true })
+ if (!query) {
+ return
+ }
+
+ const scope = currentFindScope()
+
+ if (!scope) {
+ return
}
+
+ const result = performScopedFind(scope, query, { forward, findNext: true })
+
+ $findInPage.set({ ...$findInPage.get(), matchOrdinal: result.activeOrdinal, matchCount: result.count })
}
-/** Called by the preload bridge when `found-in-page` fires on webContents. */
+/** Called by the preload bridge when `found-in-page` fires on webContents.
+ * Retained for the multi-window case (a secondary session window still uses
+ * the Electron bridge — see electron/find-in-page.ts); the renderer-side
+ * walker for the primary window never fires this. */
export function updateFindResults(activeMatch: number, count: number): void {
const prev = $findInPage.get()
$findInPage.set({ ...prev, matchOrdinal: activeMatch, matchCount: count })
@@ -84,6 +134,10 @@ let detachListener: (() => void) | undefined
* Subscribe to `found-in-page` results. Returns a release fn; the underlying
* bridge listener is installed on the first subscriber and removed when the
* last one releases. Safe to call from an effect with a `[]` dep list.
+ *
+ * Kept for secondary-window renderers that still drive search via the
+ * Electron bridge. The primary window's renderer-side walker calls
+ * `updateFindResults` synchronously and never wires this listener.
*/
export function initFindInPageListener(): () => void {
listenerRefs += 1