Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(search): 修复本机与远程任务搜索结果反复闪现 (#4357)
Dash04e59143ca29
diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.tsindex 9543f55be3..3d5e9e04e6 100644--- a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts+++ b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts@@ -224,30 +224,6 @@ describe('ConversationSearchBox live search', () => {expect(hybridMode).toBeGreaterThan(keywordMode);});- it('reuses the first remote page for hybrid and still merges late remote hits', () => {- const hybridMode = source.indexOf("semanticMode: 'hybrid'");- const reuseRemote = source.indexOf('reuseRemoteResults');- const mergeLateRemote = source.indexOf('mergeConversationSearchFanout');-- expect(source).toContain('semanticStartedSeqRef');- expect(reuseRemote).toBeGreaterThan(hybridMode);- expect(mergeLateRemote).toBeGreaterThan(-1);- expect(source).toContain('if (semanticStartedSeqRef.current === seq)');- expect(source).toContain('results: remoteResultsRef.current');- expect(source).toContain('next.remoteResults');- });-- it('restores a terminal state if the hybrid refresh fails first', () => {- const hybridCatch = source.indexOf("semanticMode: 'hybrid'");- const resetSemanticGuard = source.indexOf('semanticStartedSeqRef.current = 0;', hybridCatch);- const terminalStatus = source.indexOf(- "setStatus((current) => current === 'searching' ? 'error' : current);",- hybridCatch,- );-- expect(resetSemanticGuard).toBeGreaterThan(hybridCatch);- expect(terminalStatus).toBeGreaterThan(resetSemanticGuard);- });it('opens with a locked project filter and searches only that project at runtime', async () => {vi.mocked(searchConversations).mockResolvedValue({diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.tsnew file mode 100644index 0000000000..ee5e4d7605--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.ts@@ -0,0 +1,272 @@+// @vitest-environment jsdom+import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useConversationSearch } from '@/features/cc-agent/sidebar/ConversationSearchBox';+import { searchConversations } from '@/lib/conversationSearchService';+import type { ConversationSearchResponse } from '../../shared/conversationSearch';+import type { ProjectNode } from '@/features/cc-agent/lib/projectGrouping';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/lib/conversationSearchService', () => ({ searchConversations: vi.fn() }));++function deferred() {+ let resolve!: (value: ConversationSearchResponse) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<ConversationSearchResponse>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+function page(id?: string, remote = false): ConversationSearchResponse {+ return {+ query: 'needle',+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ results: id+ ? [+ {+ session: {+ id,+ title: id,+ agentKind: 'cc',+ status: 'active',+ workingDir: '/repo',+ workspaceKind: 'project',+ userSendAt: null,+ createdAt: '2026-09-01',+ updatedAt: '2026-09-01',+ ...(remote ? { deviceLinkDeviceId: 'remote' } : {}),+ _count: { messages: 1 },+ },+ matchKind: 'title',+ titleMatchIndices: [],+ titleScore: 1,+ contentHit: null,+ contentHits: [],+ rankScore: 1,+ },+ ]+ : [],+ };+}+const devices = [{ deviceId: 'remote', deviceName: 'Mac', connected: true }];+function mount(machineSelection: 'all' | string[] = 'all') {+ return renderHook(+ ({ projects, searchDevices }) =>+ useConversationSearch({+ enabled: true,+ navigate: vi.fn(),+ allKnownProjects: projects,+ searchDevices,+ machineSelection,+ }),+ { initialProps: { projects: [] as ProjectNode[], searchDevices: devices } },+ );+}+async function start(view: ReturnType<typeof mount>) {+ act(() => view.result.current.setQuery('needle'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(900);+ });+}+beforeEach(() => {+ vi.useFakeTimers();+ vi.mocked(searchConversations).mockReset();+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { platform: 'darwin' },+ });+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+ Reflect.deleteProperty(window, 'electronAPI');+});++describe('conversation search request lifecycle', () => {+ it.each(['keyword', 'hybrid'])(+ 'merges both pages when %s finishes first after both start',+ async (first) => {+ const keyword = deferred();+ const hybrid = deferred();+ vi.mocked(searchConversations).mockImplementation((request) =>+ request.semanticMode === 'keyword' ? keyword.promise : hybrid.promise,+ );+ const view = mount();+ await start(view);+ const keywordPage = page('keyword');+ keywordPage.results.push(...page('remote-hit', true).results);+ await act(async () =>+ (first === 'keyword' ? keyword : hybrid).resolve(+ first === 'keyword' ? keywordPage : page('semantic'),+ ),+ );+ expect(view.result.current.results.map((item) => item.session.id)).toContain(+ first === 'keyword' ? 'keyword' : 'semantic',+ );+ await act(async () =>+ (first === 'keyword' ? hybrid : keyword).resolve(+ first === 'keyword' ? page('semantic') : keywordPage,+ ),+ );+ expect(view.result.current.results.map((item) => item.session.id).sort()).toEqual([+ 'remote-hit',+ 'semantic',+ ]);+ },+ );+ it('does not publish an empty local hybrid page while remote keyword results are pending', async () => {+ const keyword = deferred();+ vi.mocked(searchConversations).mockImplementation((request) =>+ request.semanticMode === 'keyword' ? keyword.promise : Promise.resolve(page()),+ );+ const view = mount();+ await start(view);+ expect(view.result.current.status).toBe('searching');+ await act(async () => keyword.resolve(page('remote-hit', true)));+ expect(view.result.current.results[0]?.session.id).toBe('remote-hit');+ });+ it('does not run a synthetic hybrid request for a remote-only search', async () => {+ const keyword = deferred();+ vi.mocked(searchConversations).mockReturnValue(keyword.promise);+ const view = mount(['remote']);+ await start(view);+ expect(searchConversations).toHaveBeenCalledTimes(1);+ expect(view.result.current.status).toBe('searching');+ await act(async () => keyword.resolve(page('remote-hit', true)));+ expect(view.result.current.status).toBe('done');+ });+ it.each(['hit', 'empty', 'failure'])(+ 'waits for the semantic %s after an early empty keyword page',+ async (outcome) => {+ const hybrid = deferred();+ vi.mocked(searchConversations).mockImplementation((request) =>+ request.semanticMode === 'keyword' ? Promise.resolve(page()) : hybrid.promise,+ );+ const view = mount();+ act(() => view.result.current.setQuery('needle'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(view.result.current.status).toBe('searching');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(650);+ });+ expect(view.result.current.status).toBe('searching');+ await act(async () => {+ if (outcome === 'failure') hybrid.reject(new Error('offline'));+ else hybrid.resolve(page(outcome === 'hit' ? 'semantic' : undefined));+ });+ expect(view.result.current.status).toBe('done');+ expect(view.result.current.results.map((item) => item.session.id)).toEqual(+ outcome === 'hit' ? ['semantic'] : [],+ );+ },+ );+ it('publishes a remote-only empty page without waiting for an inapplicable semantic stage', async () => {+ vi.mocked(searchConversations).mockResolvedValue(page());+ const view = mount(['remote']);+ await start(view);+ expect(view.result.current.status).toBe('done');+ expect(view.result.current.results).toEqual([]);+ expect(searchConversations).toHaveBeenCalledTimes(1);+ });+ it.each(['keyword', 'hybrid'])('retains the successful page when %s fails', async (failed) => {+ vi.mocked(searchConversations).mockImplementation((request) =>+ request.semanticMode === failed+ ? Promise.reject(new Error('offline'))+ : Promise.resolve(page('hit')),+ );+ const view = mount();+ await start(view);+ expect(view.result.current.status).toBe('done');+ expect(view.result.current.results[0]?.session.id).toBe('hit');+ });+ it('reports failure when both pages fail', async () => {+ vi.mocked(searchConversations).mockRejectedValue(new Error('offline'));+ const view = mount();+ await start(view);+ expect(view.result.current.status).toBe('error');+ });+ it('keeps results and request count stable across equivalent device snapshots', async () => {+ vi.mocked(searchConversations).mockResolvedValue(page('hit'));+ const view = mount();+ await start(view);+ view.rerender({ projects: [], searchDevices: devices.map((device) => ({ ...device })) });+ expect(view.result.current.status).toBe('done');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(searchConversations).toHaveBeenCalledTimes(2);+ });+ it('ignores both late pages after the query is cleared', async () => {+ const keyword = deferred();+ const hybrid = deferred();+ vi.mocked(searchConversations).mockImplementation((request) =>+ request.semanticMode === 'keyword' ? keyword.promise : hybrid.promise,+ );+ const view = mount();+ await start(view);+ act(() => view.result.current.setQuery(''));+ await act(async () => {+ keyword.resolve(page('old'));+ hybrid.resolve(page('old'));+ });+ expect(view.result.current.status).toBe('idle');+ expect(view.result.current.results).toEqual([]);+ });+ it('keeps remote project search stable when recent activity reorders selected projects', async () => {+ vi.mocked(searchConversations).mockResolvedValue(page('hit', true));+ const projects = ['a', 'b'].map(+ (name) =>+ ({+ projectKey: `device:remote:/${name}`,+ workingDir: `/${name}`,+ deviceLinkDeviceId: 'remote',+ sessions: [],+ scope: 'local',+ }) as unknown as ProjectNode,+ );+ const view = mount();+ view.rerender({ projects, searchDevices: devices });+ act(() =>+ view.result.current.setProjectSelection(projects.map((project) => project.projectKey)),+ );+ await start(view);+ view.rerender({ projects: [...projects].reverse(), searchDevices: devices });+ expect(view.result.current.status).toBe('done');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(searchConversations).toHaveBeenCalledTimes(1);+ });+ it('keeps project search stable when task activity reorders the same sessions', async () => {+ vi.mocked(searchConversations).mockResolvedValue(page('hit'));+ const project = {+ projectKey: 'local:/repo',+ workingDir: '/repo',+ scope: 'local',+ sessions: [{ id: 'a' }, { id: 'b' }],+ } as ProjectNode;+ const view = mount();+ view.rerender({ projects: [project], searchDevices: devices });+ act(() => view.result.current.setProjectSelection(['local:/repo']));+ await start(view);+ view.rerender({+ projects: [{ ...project, sessions: [...project.sessions].reverse() }],+ searchDevices: devices,+ });+ expect(view.result.current.status).toBe('done');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(searchConversations).toHaveBeenCalledTimes(2);+ view.rerender({+ projects: [{ ...project, sessions: [project.sessions[0]] }],+ searchDevices: devices,+ });+ expect(view.result.current.status).toBe('searching');+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsxindex 7156c6fddc..54d1668491 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx@@ -233,8 +233,6 @@ export function useConversationSearch({const [status, setStatus] = useState<'idle' | 'searching' | 'done' | 'error'>('idle');const [response, setResponse] = useState<ConversationSearchResponse | null>(null);const requestSeqRef = useRef(0);- const semanticStartedSeqRef = useRef(0);- const remoteResultsRef = useRef<ConversationSearchResultItem[]>([]);const requestProjectKey = projectFilterRequest?.projectKey ?? null;const requestProjectName = projectFilterRequest?.projectName ?? null;const requestProjectSessionIds = projectFilterRequest?.sessionIds ?? EMPTY_SESSION_IDS;@@ -267,7 +265,7 @@ export function useConversationSearch({) {indexedSessionIds = lockedProjectSessionIds;}- if (indexedSessionIds.length > 0) return indexedSessionIds;+ if (indexedSessionIds.length > 0) return [...new Set(indexedSessionIds)].sort();const selectedRemoteOnly =selectedProjects.some((project) => project.deviceLinkDeviceId != null) ||Boolean(lockedProjectDeviceId && lockedMatchesSelection);@@ -328,6 +326,21 @@ export function useConversationSearch({}),[machineSelection, searchDevices, selectedProjectSessionIds, selectedProjectTargets],);+ // Store refreshes rebuild arrays even when the actual search scope is unchanged.+ const searchScopeKey = JSON.stringify({+ origins: searchOrigins+ .map((origin) => ({+ ...origin,+ sessionIds: origin.sessionIds ? [...origin.sessionIds].sort() : null,+ workingDirs: origin.workingDirs ? [...origin.workingDirs].sort() : null,+ }))+ .sort((a, b) => {+ const aKey = a.kind === 'local' ? '' : a.deviceId;+ const bKey = b.kind === 'local' ? '' : b.deviceId;+ return aKey.localeCompare(bKey);+ }),+ sessionIds: selectedProjectSessionIds,+ });const activeFilterCount = useMemo(() => {let count = 0;if (statusFilter !== 'all') count += 1;@@ -365,14 +378,16 @@ export function useConversationSearch({useEffect(() => {requestSeqRef.current += 1;const seq = requestSeqRef.current;- semanticStartedSeqRef.current = 0;if (!enabled || !trimmed) {setStatus('idle');setResponse(null);return;}setStatus('searching');- remoteResultsRef.current = [];+ const scope = JSON.parse(searchScopeKey) as {+ origins: ReturnType<typeof resolveConversationSearchOrigins>;+ sessionIds: string[] | null;+ };const request = {query: trimmed,limit: SEARCH_LIMIT,@@ -382,80 +397,89 @@ export function useConversationSearch({status: statusFilter,agentKind: agentFilter,lastActivity: lastActivityFilter,- sessionIds: selectedProjectSessionIds,+ sessionIds: scope.sessionIds,},} as const;+ let keywordPage: ConversationSearchResponse | null = null;+ let semanticPage: ConversationSearchResponse | null = null;+ let keywordSettled = false;+ const hasLocalOrigin = scope.origins.some((origin) => origin.kind === 'local');+ let semanticSettled = !hasLocalOrigin;+ const publishResults = () => {+ if (seq !== requestSeqRef.current) return;+ const localPage = semanticPage ?? keywordPage;+ if (!localPage) {+ if (keywordSettled && semanticSettled) setStatus('error');+ return;+ }+ // Only a completed hybrid page supersedes local keyword hits. Remote+ // hits always come from the keyword page, regardless of completion order.+ const next = mergeConversationSearchFanout(+ [+ {+ ...localPage,+ results: localPage.results.filter((item) => !item.session.deviceLinkDeviceId),+ },+ {+ query: trimmed,+ results:+ keywordPage?.remoteResults ??+ keywordPage?.results.filter((item) => item.session.deviceLinkDeviceId) ??+ [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: keywordPage?.poolCapped ?? false,+ },+ ],+ SEARCH_LIMIT,+ sortBy,+ );+ // Empty results are definitive only after every applicable stage settles.+ // Either keyword or semantic search may still contribute a late hit.+ if (next.results.length === 0 && (!keywordSettled || !semanticSettled)) return;+ setResponse(next);+ setStatus('done');+ };const keywordTimer = window.setTimeout(() => {- searchConversations({- ...request,- semanticMode: 'keyword',- }, { origins: searchOrigins })+ searchConversations(+ {+ ...request,+ semanticMode: 'keyword',+ },+ { origins: scope.origins },+ ).then((next) => {- if (seq !== requestSeqRef.current) return;- const remoteResults = next.remoteResults ?? next.results.filter((item) => item.session.deviceLinkDeviceId);- remoteResultsRef.current = remoteResults;- if (semanticStartedSeqRef.current === seq) {- setResponse((current) => mergeConversationSearchFanout([- {- query: trimmed,- results: (current?.results ?? []).filter((item) => !item.session.deviceLinkDeviceId),- vectorUsed: current?.vectorUsed === true,- vectorSkipReason: current?.vectorSkipReason ?? null,- poolCapped: current?.poolCapped === true,- },- {- query: trimmed,- results: remoteResults,- vectorUsed: false,- vectorSkipReason: null,- poolCapped: false,- },- ], SEARCH_LIMIT, sortBy));- setStatus('done');- return;- }- setResponse(next);- setStatus('done');+ keywordPage = next;})- .catch(() => {- if (seq !== requestSeqRef.current) return;- if (semanticStartedSeqRef.current === seq) return;- setStatus('error');+ .catch(() => {})+ .finally(() => {+ keywordSettled = true;+ publishResults();});}, DEBOUNCE_MS);const semanticTimer = window.setTimeout(() => {- semanticStartedSeqRef.current = seq;- searchConversations({- ...request,- semanticMode: 'hybrid',- }, {- origins: searchOrigins,- reuseRemoteResults: remoteResultsRef.current,- })+ if (!hasLocalOrigin) return;+ searchConversations(+ {+ ...request,+ semanticMode: 'hybrid',+ },+ {+ origins: scope.origins,+ reuseRemoteResults: [],+ },+ ).then((next) => {- if (seq !== requestSeqRef.current) return;- // Hybrid only refreshes local. Remotes stay on the keyword page;- // merge the latest ref here so a slower local hybrid cannot wipe- // hits that arrived after this request started.- setResponse(mergeConversationSearchFanout([- next,- {- query: trimmed,- results: remoteResultsRef.current,- vectorUsed: false,- vectorSkipReason: null,- poolCapped: false,- },- ], SEARCH_LIMIT, sortBy));- setStatus('done');+ semanticPage = next;})- .catch(() => {- if (seq !== requestSeqRef.current) return;- semanticStartedSeqRef.current = 0;- setStatus((current) => current === 'searching' ? 'error' : current);+ .catch(() => {})+ .finally(() => {+ semanticSettled = true;+ publishResults();});}, SEMANTIC_SEARCH_DEBOUNCE_MS);return () => {+ requestSeqRef.current += 1;window.clearTimeout(keywordTimer);window.clearTimeout(semanticTimer);};@@ -463,9 +487,7 @@ export function useConversationSearch({agentFilter,lastActivityFilter,enabled,- searchOrigins,- selectedProjectSessionIds,- selectedProjectTargets,+ searchScopeKey,sortBy,statusFilter,trimmed,diff --git a/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsx b/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsxnew file mode 100644index 0000000000..84c8972dca--- /dev/null+++ b/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsx@@ -0,0 +1,150 @@+// @vitest-environment jsdom+import { act, createElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useConversationSearch } from '@/session/useConversationSearch';+import {+ searchConversationsAcrossDevices,+ shouldReplaceListWithSearchResults,+} from '@/session/conversationSearch';+import type { ConversationSearchResponse } from '@cindy/maker-shared/conversation-search';++vi.mock('react-i18next', async (original) => ({+ ...(await original<typeof import('react-i18next')>()),+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock('@/device-link/DeviceLinkContext', () => ({+ useDeviceLink: () => ({ invoke }),+}));+vi.mock('@/session/remoteSessionStore', () => ({+ remoteSessionStore: { getSessions: () => [] },+}));+vi.mock('@/session/conversationSearch', async (original) => ({+ ...(await original<typeof import('@/session/conversationSearch')>()),+ searchConversationsAcrossDevices: vi.fn(),+}));+const invoke = vi.fn();+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let root: Root;+let search: ReturnType<typeof useConversationSearch>;+function Probe({ count = 1, reachable = true }: { count?: number; reachable?: boolean }) {+ search = useConversationSearch({+ enabled: true,+ origins: [{ deviceId: 'mac', deviceName: 'Mac', reachable }],+ projects: [+ {+ deviceId: 'mac',+ deviceName: 'Mac',+ key: 'mac:/repo',+ title: 'Repo',+ workingDir: '/repo',+ count,+ },+ ],+ });+ return createElement(+ 'div',+ null,+ shouldReplaceListWithSearchResults(search.query, search.status) ? 'indexed' : 'fallback',+ );+}+const page: ConversationSearchResponse = {+ query: 'needle',+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ results: [+ {+ session: {+ id: 'body-match',+ title: 'Unrelated title',+ agentKind: 'cc',+ status: 'active',+ workingDir: '/repo',+ deviceLinkDeviceId: 'mac',+ workspaceKind: 'project',+ userSendAt: null,+ deviceLinkDeviceName: 'Mac',+ createdAt: '2026-09-01',+ updatedAt: '2026-09-01',+ _count: { messages: 1 },+ },+ matchKind: 'title',+ titleMatchIndices: [],+ titleScore: 1,+ contentHit: null,+ contentHits: [],+ rankScore: 1,+ },+ ],+};+beforeEach(() => {+ vi.useFakeTimers();+ vi.mocked(searchConversationsAcrossDevices).mockReset().mockResolvedValue(page);+ root = createRoot(document.createElement('div'));+});+afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});+async function render(count = 1, reachable = true) {+ await act(async () => root.render(createElement(Probe, { count, reachable })));+}+async function start() {+ await render();+ act(() => search.setQuery('needle'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+}+describe('mobile search scope refresh', () => {+ it('keeps the indexed page visible when project counts and object references refresh', async () => {+ await start();+ expect(search.status).toBe('ready');+ await render(2);+ expect(shouldReplaceListWithSearchResults(search.query, search.status)).toBe(true);+ expect(search.results[0]?.session.id).toBe('body-match');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(searchConversationsAcrossDevices).toHaveBeenCalledTimes(1);+ });+ it('does not starve a pending search when equivalent snapshots arrive within the debounce', async () => {+ await render();+ act(() => search.setQuery('needle'));+ for (let count = 2; count <= 5; count++) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100);+ });+ await render(count);+ }+ expect(searchConversationsAcrossDevices).toHaveBeenCalledTimes(1);+ expect(search.status).toBe('ready');+ });+ it('still searches again for actual query and connectivity changes', async () => {+ await start();+ await render(1, false);+ expect(search.status).toBe('searching');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ act(() => search.setQuery('different'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(searchConversationsAcrossDevices).toHaveBeenCalledTimes(3);+ });+ it('ignores a late response after the query is cleared', async () => {+ let resolve!: (value: ConversationSearchResponse) => void;+ vi.mocked(searchConversationsAcrossDevices).mockReturnValue(+ new Promise((yes) => {+ resolve = yes;+ }),+ );+ await start();+ act(() => search.setQuery(''));+ await act(async () => resolve(page));+ expect(search.status).toBe('idle');+ expect(search.results).toEqual([]);+ });+});diff --git a/apps/mobile/src/session/useConversationSearch.ts b/apps/mobile/src/session/useConversationSearch.tsindex 15a3330871..43e26763ec 100644--- a/apps/mobile/src/session/useConversationSearch.ts+++ b/apps/mobile/src/session/useConversationSearch.ts@@ -18,6 +18,7 @@ import {type ConversationSearchProjectSelection,} from '@/session/conversationSearch';import { remoteSessionStore } from '@/session/remoteSessionStore';+import { useStableValue } from '@/utils/useStableValue';import type {ConversationSearchAgentFilter,ConversationSearchLastActivityFilter,@@ -80,15 +81,21 @@ export function useConversationSearch({() => (lockedWorkingDirs?.length ? [...lockedWorkingDirs] : null),[lockedWorkingDirs?.join('|') ?? ''],);- const scopedOrigins = useMemo(- () => (lockedDirs ? [...origins] : scopedConversationSearchOrigins(origins, projectSelection, projects ?? [])),- [lockedDirs, origins, projectSelection, projects],- );- const originKey = useMemo(- () => scopedOrigins.map((origin) => (- `${origin.deviceId}:${origin.reachable ? '1' : '0'}:${(origin.workingDirs ?? []).join(',')}`- )).join('|'),- [scopedOrigins],+ const scopedOrigins = useStableValue(+ useMemo(+ () =>+ (lockedDirs+ ? [...origins]+ : scopedConversationSearchOrigins(origins, projectSelection, projects ?? [])+ )+ .map((origin) => ({+ ...origin,+ workingDirs: origin.workingDirs ? [...origin.workingDirs].sort() : null,+ }))+ .sort((a, b) => a.deviceId.localeCompare(b.deviceId)),+ [lockedDirs, origins, projectSelection, projects],+ ),+ (a, b) => JSON.stringify(a) === JSON.stringify(b),);useEffect(() => {@@ -167,6 +174,7 @@ export function useConversationSearch({}, CONVERSATION_SEARCH_DEBOUNCE_MS);return () => {+ requestSeq.current += 1;clearTimeout(timer);};}, [@@ -174,7 +182,6 @@ export function useConversationSearch({enabled,invoke,lastActivityFilter,- originKey,scopedOrigins,query,sortBy,