Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 侧栏任务搜索覆盖 device-link 远程会话 (#3018)
Dashea6b71be6f22
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.tsindex c0f6222e22..545d644acf 100644--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts@@ -29,4 +29,20 @@ describe('conversationSearch source invariants', () => {it('keeps the raw stored title in the session summary', () => {expect(conversationSearchSource).toContain('title: row.title,');});++ it('applies grouping-normalized workingDirs so remote project search is not window-bound', () => {+ expect(conversationSearchSource).toContain('applyWorkingDirFilter');+ expect(conversationSearchSource).toContain('normalizeWorkingDirForGrouping');+ });++ it('excludes Orca workers from searchable sessions', () => {+ expect(conversationSearchSource).toContain("ne(sessions.orcaRole, 'worker')");+ });++ it('scopes content retrieval to searchable session ids including global search', () => {+ expect(conversationSearchSource).toContain('sessionIds: allowedSessionIds');+ expect(conversationSearchSource).not.toContain(+ 'filters.sessionIds !== null || filters.workingDirs !== null',+ );+ });});diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.tsindex dcf43d650b..3e6638975e 100644--- a/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.ts@@ -43,6 +43,21 @@ beforeEach(() => {});});+describe('local-db:conversations:search — workingDirs 透传', () => {+ it('keeps filters.workingDirs so project search is not widened to all sessions', async () => {+ await handler()(null, {+ query: 'needle',+ filters: { workingDirs: ['/repo-remote'] },+ });++ expect(h.searchConversations).toHaveBeenCalledWith(+ expect.objectContaining({+ filters: expect.objectContaining({ workingDirs: ['/repo-remote'] }),+ }),+ );+ });+});+describe('local-db:conversations:search — unnamedLabel 透传', () => {it('把 renderer 的已解析文案原样带给 searchConversations', async () => {await handler()(null, { query: 'needle', unnamedLabel: '未命名任务' });diff --git a/apps/desktop/src/main/localDb/conversationSearch.ts b/apps/desktop/src/main/localDb/conversationSearch.tsindex adbc141ab9..f3ecba4a0f 100644--- a/apps/desktop/src/main/localDb/conversationSearch.ts+++ b/apps/desktop/src/main/localDb/conversationSearch.ts@@ -14,6 +14,7 @@ import type {} from '../../shared/conversationSearch.js';import { conversationSearchTitle } from '../../shared/conversationSearch.js';import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';+import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';import { getDbClient } from './client/current.js';import { messages, sessions } from './schema.js';import { searchChatHistoryHybrid } from './chatHistorySearch.js';@@ -73,7 +74,7 @@ export async function searchConversations(poolCapped: false,};}- const sessionRows = await listSearchableSessions(filters);+ const sessionRows = applyWorkingDirFilter(await listSearchableSessions(filters), filters.workingDirs);if (sessionRows.length === 0) {return {query,@@ -180,7 +181,7 @@ async function searchContentUntilUniqueSessions({targetUniqueSessions,fetchPage: ({ limit: pageLimit, offset }) => searchChatHistoryHybrid({query,- sessionIds: filters.sessionIds !== null ? allowedSessionIds : null,+ sessionIds: allowedSessionIds,workdir: null,fromMs: null,toMs: null,@@ -207,6 +208,7 @@ interface NormalizedConversationSearchFilters {agentKind: ConversationSearchAgentFilter;lastActivity: ConversationSearchLastActivityFilter;sessionIds: string[] | null;+ workingDirs: string[] | null;}function normalizeFilters(request: ConversationSearchRequest): NormalizedConversationSearchFilters {@@ -215,7 +217,8 @@ function normalizeFilters(request: ConversationSearchRequest): NormalizedConversconst agentKind = normalizeAgentFilter(input.agentKind);const lastActivity = normalizeLastActivity(input.lastActivity);const sessionIds = normalizeSessionIds(input.sessionIds);- return { status, agentKind, lastActivity, sessionIds };+ const workingDirs = normalizeWorkingDirs(input.workingDirs);+ return { status, agentKind, lastActivity, sessionIds, workingDirs };}function normalizeStatusFilter(@@ -255,6 +258,32 @@ function normalizeSessionIds(value: ConversationSearchFilters['sessionIds']): streturn out;}+function normalizeWorkingDirs(value: ConversationSearchFilters['workingDirs']): string[] | null {+ if (value == null || !Array.isArray(value)) return null;+ const seen = new Set<string>();+ const out: string[] = [];+ for (const item of value) {+ if (typeof item !== 'string') continue;+ const normalized = normalizeWorkingDirForGrouping(item);+ if (!normalized || seen.has(normalized)) continue;+ seen.add(normalized);+ out.push(normalized);+ }+ return out.length > 0 ? out : null;+}++function applyWorkingDirFilter(+ rows: SessionRow[],+ workingDirs: string[] | null,+): SessionRow[] {+ if (workingDirs == null) return rows;+ const allowed = new Set(workingDirs);+ return rows.filter((row) => {+ const key = normalizeWorkingDirForGrouping(row.workingDir);+ return key != null && allowed.has(key);+ });+}+function normalizeSortBy(value: ConversationSearchSortBy | undefined): ConversationSearchSortBy {return value === 'activityDesc' || value === 'activityAsc' ? value : 'relevance';}@@ -264,6 +293,7 @@ async function listSearchableSessions(filters: NormalizedConversationSearchFilteconst statusCond = statusCondition(filters.status);const agentCond = filters.agentKind === 'all' ? undefined : eq(sessions.agentKind, filters.agentKind);const sessionIdsCond = filters.sessionIds ? inArray(sessions.id, filters.sessionIds) : undefined;+ const workerCond = or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker'));const activityCutoff = cutoffForLastActivity(filters.lastActivity);// 兼容存量 DB 行:旧版 touchUserSendInDb 只写 user_send_at 不 bump updated_at,// 侧栏排序用 max(userSendAt, updatedAt),这里也同步用 OR 避免漏掉这些行。@@ -278,6 +308,7 @@ async function listSearchableSessions(filters: NormalizedConversationSearchFiltestatusCond,agentCond,sessionIdsCond,+ workerCond,activityCond,)).orderBy(desc(sessions.updatedAt));diff --git a/apps/desktop/src/main/localDb/ipc/search.ts b/apps/desktop/src/main/localDb/ipc/search.tsindex 27720f2637..310863ab14 100644--- a/apps/desktop/src/main/localDb/ipc/search.ts+++ b/apps/desktop/src/main/localDb/ipc/search.ts@@ -104,5 +104,16 @@ function parseFilters(value: unknown): ConversationSearchFilters | undefined {return id.trim();});}+ if (body.workingDirs !== undefined && body.workingDirs !== null) {+ if (!Array.isArray(body.workingDirs)) {+ throwIpcError('INVALID_PARAMS', 'filters.workingDirs must be an array');+ }+ filters.workingDirs = body.workingDirs.map((dir, index) => {+ if (typeof dir !== 'string' || dir.trim() === '') {+ throwIpcError('INVALID_PARAMS', `filters.workingDirs[${index}] must be a non-empty string`);+ }+ return dir;+ });+ }return filters;}diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.tsindex c10eabcca4..9543f55be3 100644--- a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts+++ b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts@@ -224,15 +224,17 @@ describe('ConversationSearchBox live search', () => {expect(hybridMode).toBeGreaterThan(keywordMode);});- it('ignores delayed keyword results once the hybrid refresh has started', () => {- const keywordStaleGuard = source.indexOf('if (semanticStartedSeqRef.current === seq) return;');- const hybridStartedMark = source.indexOf('semanticStartedSeqRef.current = seq;');+ 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(keywordStaleGuard).toBeGreaterThan(-1);- expect(hybridStartedMark).toBeGreaterThan(keywordStaleGuard);- expect(hybridStartedMark).toBeLessThan(hybridMode);+ 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', () => {@@ -279,6 +281,14 @@ describe('ConversationSearchBox live search', () => {sessionIds: ['session-a1', 'session-a2'],}),}),+ expect.objectContaining({+ origins: [+ expect.objectContaining({+ kind: 'local',+ sessionIds: ['session-a1', 'session-a2'],+ }),+ ],+ }),);}, { timeout: SEARCH_WAIT_TIMEOUT_MS });});@@ -313,6 +323,7 @@ describe('ConversationSearchBox live search', () => {sessionIds: ['visible-session-a1', 'visible-session-a2'],}),}),+ expect.anything(),);}, { timeout: SEARCH_WAIT_TIMEOUT_MS });});@@ -409,6 +420,14 @@ describe('ConversationSearchBox live search', () => {sessionIds: ['session-a1', 'session-a2'],}),}),+ expect.objectContaining({+ origins: [+ expect.objectContaining({+ kind: 'local',+ sessionIds: ['session-a1', 'session-a2'],+ }),+ ],+ }),);}, { timeout: SEARCH_WAIT_TIMEOUT_MS });@@ -500,6 +519,7 @@ describe('ConversationSearchBox live search', () => {await waitFor(() => {expect(searchConversations).toHaveBeenCalledWith(expect.objectContaining({ unnamedLabel: 'ccAgent.common.unnamedSession' }),+ expect.anything(),);}, { timeout: SEARCH_WAIT_TIMEOUT_MS });@@ -549,4 +569,209 @@ describe('ConversationSearchBox live search', () => {expect(projectNodeSource).not.toContain('search.isOpen');expect(projectNodeSource).not.toContain('search.open();');});++ it('keeps SSH project identity when a local project shares the same workingDir', async () => {+ vi.mocked(searchConversations).mockResolvedValue({+ query: 'needle',+ results: [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ });+ const localTwin: ProjectNodeData = {+ ...projects[0],+ projectKey: 'local:/workspace/repo',+ workingDir: '/workspace/repo',+ displayName: 'Local Repo',+ sessions: [{ id: 'local-same-path' } as ProjectNodeData['sessions'][number]],+ };+ const sshTwin: ProjectNodeData = {+ ...projects[0],+ projectKey: 'remote:ssh-host:/workspace/repo',+ scope: 'remote',+ workingDir: '/workspace/repo',+ remoteHostId: 'ssh-host',+ displayName: 'SSH Repo',+ sessions: [{ id: 'ssh-same-path' } as ProjectNodeData['sessions'][number]],+ };+ render(+ createElement(ConversationSearchBox, {+ navigate,+ allKnownProjects: [localTwin, sshTwin],+ allowedSessionIds: ['local-same-path', 'ssh-same-path'],+ hiddenProjectKeys,+ }),+ );+ fireEvent.click(screen.getByLabelText('ccAgent.search.open'));+ await screen.findByTestId('conversation-search-popover');+ fireEvent.click(screen.getByText('SSH Repo').closest('button') as HTMLButtonElement);+ fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {+ target: { value: 'needle' },+ });+ await waitFor(() => {+ expect(searchConversations).toHaveBeenCalledWith(+ expect.objectContaining({+ semanticMode: 'keyword',+ filters: expect.objectContaining({ sessionIds: ['ssh-same-path'] }),+ }),+ expect.objectContaining({+ origins: [+ expect.objectContaining({+ kind: 'local',+ sessionIds: ['ssh-same-path'],+ }),+ ],+ }),+ );+ }, { timeout: SEARCH_WAIT_TIMEOUT_MS });+ expect(searchConversations).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ origins: [expect.objectContaining({ workingDirs: ['/workspace/repo'] })],+ }),+ );+ });++ it('searches a filter-selected remote project by workingDir instead of mirrored ids', async () => {+ vi.mocked(searchConversations).mockResolvedValue({+ query: 'needle',+ results: [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ });+ const remoteProject: ProjectNodeData = {+ projectKey: 'device:dev-a:/repo-remote',+ scope: 'remote',+ workingDir: '/repo-remote',+ remoteHostId: null,+ deviceLinkDeviceId: 'dev-a',+ deviceLinkDeviceName: 'Studio',+ deviceLinkConnectionStatus: 'connected',+ displayName: 'Repo Remote',+ segments: 1,+ sessions: [{ id: 'mirrored-only' } as ProjectNodeData['sessions'][number]],+ latestActivityAt: '2026-06-14T00:00:00.000Z',+ };+ render(+ createElement(ConversationSearchBox, {+ navigate,+ allKnownProjects: [remoteProject],+ allowedSessionIds: ['mirrored-only'],+ hiddenProjectKeys,+ searchDevices: [{ deviceId: 'dev-a', deviceName: 'Studio', connected: true }],+ }),+ );+ fireEvent.click(screen.getByLabelText('ccAgent.search.open'));+ await screen.findByTestId('conversation-search-popover');+ fireEvent.click(screen.getByText('Repo Remote').closest('button') as HTMLButtonElement);+ fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {+ target: { value: 'needle' },+ });+ await waitFor(() => {+ expect(searchConversations).toHaveBeenCalledWith(+ expect.objectContaining({+ semanticMode: 'keyword',+ filters: expect.objectContaining({ sessionIds: null }),+ }),+ expect.objectContaining({+ origins: [+ expect.objectContaining({+ kind: 'remote',+ deviceId: 'dev-a',+ sessionIds: null,+ workingDirs: ['/repo-remote'],+ }),+ ],+ }),+ );+ }, { timeout: SEARCH_WAIT_TIMEOUT_MS });+ });++ it('searches a remote project by workingDir instead of the mirrored session window', async () => {+ vi.mocked(searchConversations).mockResolvedValue({+ query: 'needle',+ results: [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ });+ const remoteProject: ProjectNodeData = {+ projectKey: 'device:dev-a:/repo-remote',+ scope: 'remote',+ workingDir: '/repo-remote',+ remoteHostId: null,+ deviceLinkDeviceId: 'dev-a',+ deviceLinkDeviceName: 'Studio',+ deviceLinkConnectionStatus: 'connected',+ displayName: 'Repo Remote',+ segments: 1,+ sessions: [{ id: 'mirrored-only' } as ProjectNodeData['sessions'][number]],+ latestActivityAt: '2026-06-14T00:00:00.000Z',+ };+ render(+ createElement(ConversationSearchBox, {+ navigate,+ allKnownProjects: [remoteProject],+ allowedSessionIds: ['mirrored-only'],+ hiddenProjectKeys,+ searchDevices: [{ deviceId: 'dev-a', deviceName: 'Studio', connected: true }],+ projectFilterRequest: {+ projectKey: remoteProject.projectKey,+ projectName: 'Repo Remote',+ sessionIds: ['mirrored-only'],+ workingDir: '/repo-remote',+ deviceLinkDeviceId: 'dev-a',+ requestId: 1,+ },+ }),+ );+ await screen.findByTestId('conversation-search-popover');+ fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {+ target: { value: 'needle' },+ });+ await waitFor(() => {+ expect(searchConversations).toHaveBeenCalledWith(+ expect.objectContaining({+ semanticMode: 'keyword',+ filters: expect.objectContaining({ sessionIds: null }),+ }),+ expect.objectContaining({+ origins: [+ expect.objectContaining({+ kind: 'remote',+ deviceId: 'dev-a',+ sessionIds: null,+ workingDirs: ['/repo-remote'],+ }),+ ],+ }),+ );+ }, { timeout: SEARCH_WAIT_TIMEOUT_MS });+ });++ it('includes device-link remote sessions in the sidebar search universe', () => {+ const contextSource = readFileSync(+ resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'conversationSearchContext.tsx'),+ 'utf8',+ );+ const sidebarSource = readFileSync(+ resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),+ 'utf8',+ );+ expect(contextSource).toContain('useRemoteProjectSessions');+ expect(contextSource).toContain('selectVisibleSessions');+ expect(contextSource).toContain('shouldReleaseConversationSearchLock');+ expect(contextSource).toContain("requestRemoteSessionStatus(device.deviceId, 'archived')");+ expect(sidebarSource).toContain('useRemoteProjectSessions');+ expect(sidebarSource).toContain('workingDir: project.workingDir');+ expect(sidebarSource).toContain('deviceLinkDeviceId: project.deviceLinkDeviceId');+ expect(sidebarSource).toContain('useConversationSearchRequest');+ expect(sidebarSource).toContain(+ 'projectFilterRequest={isCollapsed ? projectFilterRequest : null}',+ );+ expect(sidebarSource).toMatch(+ /searchProjectSessions[\s\S]*selectVisibleSessions\([\s\S]*allSessionsForAttention[\s\S]*remoteProjectSessions/,+ );+ });});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 58da5ee3e0..e2f4b0f595 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -108,7 +108,8 @@ import {} from '@/lib/sessionAttentionStore';import { patchDraft as patchNewMakerDraft } from '@/state/newMakerDraft';import { consumePendingProjectFocus, usePendingProjectFocus } from '@/state/pendingProjectFocus';-import { requestConversationSearch } from '@/state/conversationSearchRequest';+import { requestConversationSearch, useConversationSearchRequest } from '@/state/conversationSearchRequest';+import { searchDevicesFromSwitcher } from '@/lib/conversationSearchFanout';import { emitRefresh, onPatch } from '@/lib/sessionsBus';@@ -411,9 +412,17 @@ export function CCAgentSidebarUpper() {const includeArchived = filter.status;const sessionsHook = useCCSessions({ includeArchived });const { sessions: allSessionsForAttention } = useCCSessions({ includeArchived: 'all' });+ const remoteProjectSessions = useRemoteProjectSessions();+ const remoteDevices = useRemoteDevices();+ const selectedMachineId = useEffectiveSelectedMachineId();const searchProjectSessions = useMemo(- () => allSessionsForAttention.filter((s) => !isOrcaWorkerSession(s)),- [allSessionsForAttention],+ () =>+ selectVisibleSessions(+ allSessionsForAttention,+ remoteProjectSessions,+ selectedMachineId,+ ).filter((session) => !isOrcaWorkerSession(session)),+ [allSessionsForAttention, remoteProjectSessions, selectedMachineId],);const projectAliases = useProjectAliases();const searchProjectGroups = useProjectGroups(searchProjectSessions, projectAliases.aliases);@@ -581,9 +590,6 @@ export function CCAgentSidebarUpper() {// 否则置顶的远程会话一拖进 rail 模式就消失、也无法从 rail 打开(codex review)。// 机器切换栏选中某机器后按 selectedMachineId 整体过滤(本机 → 只本地;远程 → 只该机器),// rail 与展开态共用同一选择态,保证 rail 折叠后仍尊重选中机器。- const remoteProjectSessions = useRemoteProjectSessions();- const remoteDevices = useRemoteDevices();- const selectedMachineId = useEffectiveSelectedMachineId();useEffect(() => {if (filter.status === 'active') return;const selectedRemoteIds =@@ -932,6 +938,8 @@ function ExpandedView({projectKey: project.projectKey,projectName: projectDisplayLabelWithMachine(project),sessionIds: project.sessions.map((session) => session.id),+ workingDir: project.workingDir,+ deviceLinkDeviceId: project.deviceLinkDeviceId,});}, []);// Archived All(右键菜单)走全局 ConfirmDialogProvider —— 与单条 archive 的 inline@@ -3768,6 +3776,14 @@ function CollapsedView({manualPinnedOrder,onReorderPinned,}: CollapsedProps) {+ const isCollapsed = useSidebarCollapsedState();+ const projectFilterRequest = useConversationSearchRequest();+ const selectedMachineId = useEffectiveSelectedMachineId();+ const switcherDevices = useSwitcherDevices();+ const searchDevices = useMemo(+ () => searchDevicesFromSwitcher(switcherDevices),+ [switcherDevices],+ );const { t } = useTranslation();// 只读 running 快照——**不传 options**:通知副作用(onSessionDone 等)由// ExpandedView 的实例独家持有,两个视图常驻挂载,双回调会重复发桌面通知。@@ -3868,6 +3884,9 @@ function CollapsedView({allKnownProjects={allSearchProjects}allowedSessionIds={searchableSessionIds}hiddenProjectKeys={hiddenProjectKeys}+ projectFilterRequest={isCollapsed ? projectFilterRequest : null}+ machineSelection={selectedMachineId}+ searchDevices={searchDevices}triggerClassName={SIDEBAR_RAIL_ICON_BUTTON_CLASS}/>diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsxindex 2f2a2d5701..031870e025 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx@@ -35,6 +35,16 @@ import {} from '@/components/ui/dropdown-menu';import { cn } from '@/lib/utils';import { searchConversations } from '@/lib/conversationSearchService';+import {+ mergeConversationSearchFanout,+ resolveConversationSearchOrigins,+ shouldReleaseConversationSearchLock,+ type ConversationSearchDevice,+} from '@/lib/conversationSearchFanout';+import {+ MACHINE_ALL,+ type MachineSelection,+} from '@/features/device-link/selectedMachineStore';import { formatSidebarTime } from '../lib/formatSidebarTime';import {getSearchSortBy,@@ -52,6 +62,8 @@ import type {import { conversationSearchTitle } from '../../../../shared/conversationSearch';import { highlightSegments } from '../lib/highlightSegments';import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import { conversationSearchResultKey } from '@/lib/conversationSearchFanout';import {projectKeyComparisonKey,type ProjectNode as ProjectNodeData,@@ -70,6 +82,7 @@ const SEMANTIC_SEARCH_DEBOUNCE_MS = 900;const SEARCH_LIMIT = 24;const MAX_VISIBLE_HITS_PER_RESULT = 3;const EMPTY_SESSION_IDS: string[] = [];+const EMPTY_SEARCH_DEVICES: ConversationSearchDevice[] = [];type ProjectSelection = 'all' | string[];type Option<T extends string> = {@@ -159,14 +172,18 @@ export interface UseConversationSearchParams {enabled: boolean;navigate: NavigateFunction;allKnownProjects: ProjectNodeData[];- /** Bounds explicit project-scoped searches; global search remains unbounded. */+ /** Kept for callers; explicit local/SSH project scope uses the project node sessions. */allowedSessionIds?: readonly string[];projectFilterRequest?: {projectKey: string;projectName: string;sessionIds: string[];+ workingDir?: string | null;+ deviceLinkDeviceId?: string | null;requestId: number;} | null;+ machineSelection?: MachineSelection;+ searchDevices?: readonly ConversationSearchDevice[];/** 收到「在此项目内搜索」请求(锁定项目)时回调:popover 用它打开面板,内联用它聚焦输入。 */onProgrammaticOpen?: () => void;/** 选中某条结果后回调(navigate 之前):popover 用它关闭面板并上报托盘。 */@@ -183,8 +200,10 @@ export function useConversationSearch({enabled,navigate,allKnownProjects,- allowedSessionIds,+ allowedSessionIds: _allowedSessionIds,projectFilterRequest,+ machineSelection = MACHINE_ALL,+ searchDevices = EMPTY_SEARCH_DEVICES,onProgrammaticOpen,onResultChosen,}: UseConversationSearchParams) {@@ -206,49 +225,106 @@ export function useConversationSearch({const [lockedProjectKey, setLockedProjectKey] = useState<string | null>(null);const [lockedProjectName, setLockedProjectName] = useState<string | null>(null);const [lockedProjectSessionIds, setLockedProjectSessionIds] = useState<string[]>([]);+ const [lockedProjectWorkingDir, setLockedProjectWorkingDir] = useState<string | null>(null);+ const [lockedProjectDeviceId, setLockedProjectDeviceId] = useState<string | null>(null);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;+ const requestProjectWorkingDir = projectFilterRequest?.workingDir ?? null;+ const requestProjectDeviceId = projectFilterRequest?.deviceLinkDeviceId ?? null;const requestId = projectFilterRequest?.requestId ?? 0;const trimmed = query.trim();- const allowedSessionIdSet = useMemo(- () => (allowedSessionIds == null ? null : new Set(allowedSessionIds)),- [allowedSessionIds],- );+ void _allowedSessionIds;const selectedProjectSessionIds = useMemo(() => {if (projectSelection === 'all') return null;const selected = buildProjectKeyComparisonSet(projectSelection, localPlatform);- let indexedSessionIds = allKnownProjects- .filter((project) => {- const comparisonKey = projectKeyComparisonKey(project.projectKey, localPlatform);- return comparisonKey != null && selected.has(comparisonKey);- })+ const selectedProjects = allKnownProjects.filter((project) => {+ const comparisonKey = projectKeyComparisonKey(project.projectKey, localPlatform);+ return comparisonKey != null && selected.has(comparisonKey);+ });+ let indexedSessionIds = selectedProjects+ .filter((project) => project.deviceLinkDeviceId == null).flatMap((project) => project.sessions.map((session) => session.id));const lockedProjectComparisonKey = projectKeyComparisonKey(lockedProjectKey, localPlatform);+ const lockedMatchesSelection =+ lockedProjectComparisonKey != null &&+ selected.size === 1 &&+ selected.has(lockedProjectComparisonKey);if (indexedSessionIds.length === 0 &&- lockedProjectComparisonKey &&- selected.size === 1 &&- selected.has(lockedProjectComparisonKey) &&+ !lockedProjectDeviceId &&+ lockedMatchesSelection &&lockedProjectSessionIds.length > 0) {indexedSessionIds = lockedProjectSessionIds;}- if (allowedSessionIdSet == null) return indexedSessionIds;- return indexedSessionIds.filter((sessionId) => allowedSessionIdSet.has(sessionId));+ if (indexedSessionIds.length > 0) return indexedSessionIds;+ const selectedRemoteOnly =+ selectedProjects.some((project) => project.deviceLinkDeviceId != null) ||+ Boolean(lockedProjectDeviceId && lockedMatchesSelection);+ return selectedRemoteOnly ? null : [];}, [allKnownProjects,- allowedSessionIdSet,+ lockedProjectDeviceId,lockedProjectKey,lockedProjectSessionIds,localPlatform,projectSelection,]);+ const selectedProjectTargets = useMemo(() => {+ if (projectSelection === 'all') return null;+ const selected = buildProjectKeyComparisonSet(projectSelection, localPlatform);+ const fromVisible = allKnownProjects+ .filter((project) => {+ const comparisonKey = projectKeyComparisonKey(project.projectKey, localPlatform);+ return comparisonKey != null && selected.has(comparisonKey);+ })+ .flatMap((project) => {+ const deviceId = project.deviceLinkDeviceId?.trim();+ const workingDir = project.workingDir?.trim();+ if (!deviceId || !workingDir) return [];+ return [{ deviceId, workingDir }];+ });+ if (fromVisible.length > 0) return fromVisible;+ const lockedComparison = projectKeyComparisonKey(lockedProjectKey, localPlatform);+ if (+ lockedProjectDeviceId &&+ lockedProjectWorkingDir &&+ lockedComparison &&+ selected.size === 1 &&+ selected.has(lockedComparison)+ ) {+ return [{+ deviceId: lockedProjectDeviceId,+ workingDir: lockedProjectWorkingDir,+ }];+ }+ return null;+ }, [+ allKnownProjects,+ localPlatform,+ lockedProjectDeviceId,+ lockedProjectKey,+ lockedProjectWorkingDir,+ projectSelection,+ ]);+ const searchOrigins = useMemo(+ () =>+ resolveConversationSearchOrigins({+ machineSelection,+ sessionIds: selectedProjectSessionIds,+ projectTargets: selectedProjectTargets,+ devices: searchDevices,+ getSessionDeviceId: (sessionId) => remoteProjectsStore.getSessionDeviceId(sessionId),+ }),+ [machineSelection, searchDevices, selectedProjectSessionIds, selectedProjectTargets],+ );const activeFilterCount = useMemo(() => {let count = 0;if (statusFilter !== 'all') count += 1;@@ -263,6 +339,8 @@ export function useConversationSearch({setLockedProjectKey(requestProjectKey);setLockedProjectName(requestProjectName);setLockedProjectSessionIds([...new Set(requestProjectSessionIds)]);+ setLockedProjectWorkingDir(requestProjectWorkingDir);+ setLockedProjectDeviceId(requestProjectDeviceId);setProjectSelection([requestProjectKey]);onProgrammaticOpen?.(); // popover:打开面板并上报托盘;内联:聚焦输入框setQuery('');@@ -271,7 +349,15 @@ export function useConversationSearch({// 处理完即清零跨层请求:否则切到 rail(本组件卸载)再切回(重挂)时,本 effect 会在挂载// 阶段读到 stale current,把搜索框误弹出来(PR #246 review,镜像 pendingProjectFocus 的 consume)。consumeConversationSearchRequest();- }, [requestId, requestProjectKey, requestProjectName, requestProjectSessionIds, onProgrammaticOpen]);+ }, [+ requestId,+ requestProjectKey,+ requestProjectName,+ requestProjectSessionIds,+ requestProjectWorkingDir,+ requestProjectDeviceId,+ onProgrammaticOpen,+ ]);useEffect(() => {requestSeqRef.current += 1;@@ -283,6 +369,7 @@ export function useConversationSearch({return;}setStatus('searching');+ remoteResultsRef.current = [];const request = {query: trimmed,limit: SEARCH_LIMIT,@@ -299,10 +386,31 @@ export function useConversationSearch({searchConversations({...request,semanticMode: 'keyword',- })+ }, { origins: searchOrigins }).then((next) => {if (seq !== requestSeqRef.current) return;- if (semanticStartedSeqRef.current === seq) 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');})@@ -317,10 +425,25 @@ export function useConversationSearch({searchConversations({...request,semanticMode: 'hybrid',+ }, {+ origins: searchOrigins,+ reuseRemoteResults: remoteResultsRef.current,}).then((next) => {if (seq !== requestSeqRef.current) return;- setResponse(next);+ // 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');}).catch(() => {@@ -337,7 +460,9 @@ export function useConversationSearch({agentFilter,lastActivityFilter,enabled,+ searchOrigins,selectedProjectSessionIds,+ selectedProjectTargets,sortBy,statusFilter,trimmed,@@ -365,6 +490,8 @@ export function useConversationSearch({setLockedProjectKey(null);setLockedProjectName(null);setLockedProjectSessionIds([]);+ setLockedProjectWorkingDir(null);+ setLockedProjectDeviceId(null);setProjectSelection('all');}, [lockedProjectKey]);@@ -382,6 +509,10 @@ export function useConversationSearch({hitOverride?: ConversationSearchResultItem['contentHit'],) => {try {+ const remoteDeviceId = item.session.deviceLinkDeviceId;+ if (remoteDeviceId) {+ remoteProjectsStore.pinSessionOrigin(remoteDeviceId, item.session.id);+ }const baseRoute = await resolveSessionRoute(item.session.id, item.session);const hit = hitOverride ?? item.contentHit;// popover 形态:onResultChosen 关闭面板并通知托盘(SidebarActionBar 减 openChildCount),@@ -486,7 +617,12 @@ export function SearchResultsBody({return (<div className={cn('overflow-y-auto p-2', maxHeightClass)}>{results.map((item) => (- <SearchResultRow key={item.session.id} item={item} query={trimmed} onSelect={onSelect} />+ <SearchResultRow+ key={conversationSearchResultKey(item)}+ item={item}+ query={trimmed}+ onSelect={onSelect}+ />))}</div>);@@ -501,8 +637,12 @@ export interface ConversationSearchBoxProps {projectKey: string;projectName: string;sessionIds: string[];+ workingDir?: string | null;+ deviceLinkDeviceId?: string | null;requestId: number;} | null;+ machineSelection?: MachineSelection;+ searchDevices?: readonly ConversationSearchDevice[];/** icon variant 触发钮 className 覆盖——rail 用 SIDEBAR_RAIL_ICON_BUTTON_CLASS。 */triggerClassName?: string;/** Popover open 态变化上报(供 SidebarActionBar 的 openChildCount 守卫;含程序化打开)。 */@@ -520,6 +660,8 @@ export function ConversationSearchBox({allowedSessionIds,hiddenProjectKeys,projectFilterRequest,+ machineSelection = MACHINE_ALL,+ searchDevices = EMPTY_SEARCH_DEVICES,triggerClassName,onOpenChange,}: ConversationSearchBoxProps) {@@ -549,6 +691,8 @@ export function ConversationSearchBox({allowedSessionIds,allKnownProjects,projectFilterRequest,+ machineSelection,+ searchDevices,onProgrammaticOpen: handleProgrammaticOpen,onResultChosen: handleResultChosen,});@@ -561,7 +705,13 @@ export function ConversationSearchBox({lockedProjectKey,hiddenProjectKeys,window.electronAPI.platform,- )+ ) ||+ shouldReleaseConversationSearchLock({+ lockedProjectKey,+ visibleProjects: allKnownProjects,+ localPlatform: window.electronAPI.platform,+ machineSelection,+ })) {search.reset();search.clearLock();@@ -582,6 +732,7 @@ export function ConversationSearchBox({}, [allKnownProjects,hiddenProjectKeys,+ machineSelection,search.clearLock,search.lockedProjectKey,search.projectSelection,@@ -1026,9 +1177,11 @@ function SearchResultRow({const activityIso = item.session.updatedAt;const activityText = formatSidebarTime(activityIso, t);const sourceText = primaryHit ? searchSourceLabel(primaryHit, t) : t('ccAgent.search.source.titleOnly');+ const deviceLabel = item.session.deviceLinkDeviceName?.trim() || null;const meta = [sourceText,activityText,+ deviceLabel,item.session.workingDir,].filter(Boolean).join(' · ');const tooltip = (diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/conversationSearchSort.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/conversationSearchSort.test.tsxindex a80364ea37..bcb17831ee 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/conversationSearchSort.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/conversationSearchSort.test.tsx@@ -127,7 +127,7 @@ describe('useConversationSearch sort persistence', () => {});describe('useConversationSearch visibility scope', () => {- it('keeps global search unbounded while bounding an explicit project selection', async () => {+ it('keeps global search unbounded while scoping an explicit local project by session ids', async () => {vi.useFakeTimers();const searchMock = vi.mocked(searchConversations);const project: ProjectNodeData = {@@ -164,6 +164,9 @@ describe('useConversationSearch visibility scope', () => {semanticMode: 'keyword',filters: expect.objectContaining({ sessionIds: null }),}),+ expect.objectContaining({+ origins: [expect.objectContaining({ kind: 'local', sessionIds: null })],+ }),);searchMock.mockClear();@@ -173,7 +176,17 @@ describe('useConversationSearch visibility scope', () => {});expect(searchMock).toHaveBeenLastCalledWith(expect.objectContaining({- filters: expect.objectContaining({ sessionIds: ['loaded'] }),+ filters: expect.objectContaining({+ sessionIds: ['loaded', 'outside-sidebar-cache'],+ }),+ }),+ expect.objectContaining({+ origins: [+ expect.objectContaining({+ kind: 'local',+ sessionIds: ['loaded', 'outside-sidebar-cache'],+ }),+ ],}),);});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsxindex c68d525dc8..ac7a3839e8 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx@@ -9,9 +9,10 @@* - SidebarTopNav 的搜索行(输入 / 排序 / 筛选 / hover 展开);* - ExpandedView 的结果列表(读 query / status / results)。*- * allKnownProjects 在此就地计算(与 CCAgentSidebarUpper 的 projectUniverse 同口径:全量- * 会话、排除 Orca worker),供筛选面板列举项目与项目内搜索会话集解析。rail 态的搜索是- * CollapsedView 里独立的 ConversationSearchBox 图标弹窗,不走本 context。+ * allKnownProjects 在此就地计算(与 CCAgentSidebarUpper 同口径:本机 ∪ device-link+ * 远程镜像,按机器切换栏过滤,排除 Orca worker),供筛选面板列举项目与项目内搜索+ * 会话集解析。rail 态的搜索是 CollapsedView 里独立的 ConversationSearchBox 图标弹窗,+ * 不走本 context。*/import {@@ -27,6 +28,19 @@ import { useNavigate } from 'react-router-dom';import { useCCSessions } from '@/hooks/useCCSessions';import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';+import {+ requestRemoteSessionStatus,+ useRemoteProjectSessions,+} from '@/features/device-link/remoteProjectsStore';+import { selectVisibleSessions } from '@/features/device-link/selectedMachineStore';+import {+ useEffectiveSelectedMachineId,+ useSwitcherDevices,+} from '@/features/device-link/useMachineSwitcher';+import {+ searchDevicesFromSwitcher,+ shouldReleaseConversationSearchLock,+} from '@/lib/conversationSearchFanout';import { useConversationSearchRequest } from '@/state/conversationSearchRequest';import { useProjectAliases } from '../hooks/useProjectAliases';import { useHiddenProjects } from '../hooks/useHiddenProjects';@@ -58,19 +72,35 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }const projectFilterRequest = useConversationSearchRequest();const [openSignal, setOpenSignal] = useState(0);- // allKnownProjects:全量会话(含归档)、排除 Orca worker,与 CCAgentSidebarUpper 同口径。+ // allKnownProjects:本机 ∪ 远程镜像(含归档)、按机器切换栏过滤、排除 Orca worker。const { sessions } = useCCSessions({ includeArchived: 'all' });+ const remoteProjectSessions = useRemoteProjectSessions();+ const selectedMachineId = useEffectiveSelectedMachineId();+ const switcherDevices = useSwitcherDevices();+ const searchDevices = useMemo(+ () => searchDevicesFromSwitcher(switcherDevices),+ [switcherDevices],+ );+ // Search status defaults to all. Pull archived remote buckets so a remote+ // project that only has archived tasks still appears in the project filter.+ useEffect(() => {+ for (const device of searchDevices) {+ if (!device.connected) continue;+ requestRemoteSessionStatus(device.deviceId, 'archived');+ }+ }, [searchDevices]);const { aliases } = useProjectAliases();const { hiddenProjectKeys } = useHiddenProjects();- const searchSessions = useMemo(() => sessions.filter((s) => !isOrcaWorkerSession(s)), [sessions]);- const { projects } = useProjectGroups(searchSessions, aliases);- const visibleProjects = useMemo(+ const searchSessions = useMemo(() =>- visibleSidebarProjects(- projects,- hiddenProjectKeys,- window.electronAPI.platform,+ selectVisibleSessions(sessions, remoteProjectSessions, selectedMachineId).filter(+ (session) => !isOrcaWorkerSession(session),),+ [remoteProjectSessions, selectedMachineId, sessions],+ );+ const { projects } = useProjectGroups(searchSessions, aliases);+ const visibleProjects = useMemo(+ () => visibleSidebarProjects(projects, hiddenProjectKeys, window.electronAPI.platform),[projects, hiddenProjectKeys],);const allowedSessionIds = useMemo(@@ -92,6 +122,8 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }allKnownProjects: visibleProjects,allowedSessionIds,projectFilterRequest,+ machineSelection: selectedMachineId,+ searchDevices,onProgrammaticOpen: handleProgrammaticOpen,});@@ -101,16 +133,19 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }useEffect(() => {if (search.lockedProjectKey &&- isProjectHidden(- search.lockedProjectKey,- hiddenProjectKeys,- window.electronAPI.platform,- )+ (isProjectHidden(search.lockedProjectKey, hiddenProjectKeys, window.electronAPI.platform) ||+ shouldReleaseConversationSearchLock({+ lockedProjectKey: search.lockedProjectKey,+ visibleProjects,+ localPlatform: window.electronAPI.platform,+ machineSelection: selectedMachineId,+ }))) {search.reset();search.clearLock();return;}+ if (search.lockedProjectKey) return;if (search.projectSelection === 'all') return;const next = reconcileProjectSelectionWithVisibleProjects(search.projectSelection,@@ -120,10 +155,12 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }if (next.length === search.projectSelection.length &&next.every((projectKey, index) => projectKey === search.projectSelection[index])- ) return;+ )+ return;search.setProjectSelection(next.length > 0 ? next : 'all');}, [hiddenProjectKeys,+ selectedMachineId,visibleProjects,search.clearLock,search.lockedProjectKey,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 80a55cfeef..b7ca0c9da5 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7849,7 +7849,7 @@"syncCodexAlreadyLinked": "Codex sessions for this project are already linked","syncCodexNone": "No Codex sessions found for this project","syncCodexFailed": "Codex sync failed: {{error}}",- "search": "Search sessions"+ "search": "Search sessions in this project"},"deepLink": {"copied": "Deep link copied",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2e9ccb5eaf..8cf33c012e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7864,7 +7864,7 @@"openInExplorer": "ファイルマネージャーで開く","newInDirectory": "このディレクトリで新規セッション","copyDeepLink": "ディープリンクをコピー",- "search": "セッションを検索"+ "search": "このプロジェクト内のセッションを検索"},"deepLink": {"copied": "ディープリンクをコピーしました",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 56cfa93782..56fc05b4eb 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7864,7 +7864,7 @@"openInExplorer": "파일 관리자에서 열기","newInDirectory": "이 디렉터리에서 새 세션","copyDeepLink": "딥 링크 복사",- "search": "세션 검색"+ "search": "이 프로젝트에서 세션 검색"},"deepLink": {"copied": "딥 링크가 복사되었습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex bc0b92b48e..60aa346ec2 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7837,7 +7837,7 @@"syncCodexAlreadyLinked": "此项目的 Codex 任务已经链接过了","syncCodexNone": "没有找到此项目的 Codex 任务","syncCodexFailed": "Codex 同步失败:{{error}}",- "search": "搜索任务"+ "search": "在项目内搜索任务"},"deepLink": {"copied": "已复制深度链接",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 55f1e9d124..0780e36a9e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7864,7 +7864,7 @@"syncCodexAlreadyLinked": "此專案的 Codex 任務已經連結過了","syncCodexNone": "沒有找到此專案的 Codex 任務","syncCodexFailed": "Codex 同步失敗:{{error}}",- "search": "搜尋任務"+ "search": "在專案內搜尋任務"},"deepLink": {"copied": "已複製深度連結",diff --git a/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.ts b/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.tsnew file mode 100644index 0000000000..a3d622c021--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.ts@@ -0,0 +1,637 @@+import { describe, expect, it, vi } from 'vitest';++import type { Session } from '@/lib/ccAgent.types';+import {+ conversationSearchResultKey,+ emptyConversationSearchResponse,+ filterResultsByRequestFilters,+ filterResultsByWorkingDirs,+ remoteIndexedSearchIgnoredWorkingDirs,+ mergeConversationSearchFanout,+ remoteResultsFromFanoutPages,+ requestForOrigin,+ resolveConversationSearchOrigins,+ searchCachedSessionsByTitle,+ searchDevicesFromSwitcher,+ shouldReleaseConversationSearchLock,+ stampRemoteSearchResponse,+} from '@/lib/conversationSearchFanout';+import { searchConversationsAcrossOrigins } from '@/lib/conversationSearchService';+import type {+ ConversationSearchRequest,+ ConversationSearchResponse,+ ConversationSearchResultItem,+} from '../../../shared/conversationSearch';+import { MACHINE_ALL, MACHINE_LOCAL } from '@/features/device-link/selectedMachineStore';++function session(partial: Partial<Session> & Pick<Session, 'id' | 'title'>): Session {+ return {+ workingDir: '/repo',+ workspaceKind: 'project',+ model: 'x',+ effort: 'medium',+ permissionMode: 'default',+ sdkSessionId: null,+ totalTokenUsage: 0,+ totalCostUsd: 0,+ contextTokens: 0,+ contextWindow: 0,+ fastMode: false,+ clearedAt: null,+ pinnedAt: null,+ userSendAt: '2026-08-19T00:00:00.000Z',+ status: 'active',+ agentKind: 'cc',+ extraDirs: [],+ createdAt: '2026-08-19T00:00:00.000Z',+ updatedAt: '2026-08-19T00:00:00.000Z',+ userId: 'u',+ ...partial,+ } as Session;+}++function result(+ id: string,+ rankScore: number,+ extras: Partial<ConversationSearchResultItem['session']> = {},+): ConversationSearchResultItem {+ return {+ session: {+ id,+ title: id,+ workingDir: '/repo',+ workspaceKind: 'project',+ agentKind: 'cc',+ status: 'active',+ userSendAt: '2026-08-19T00:00:00.000Z',+ updatedAt: '2026-08-19T00:00:00.000Z',+ createdAt: '2026-08-19T00:00:00.000Z',+ _count: { messages: 1 },+ ...extras,+ },+ matchKind: 'title',+ titleMatchIndices: [0],+ titleScore: 1,+ contentHit: null,+ contentHits: [],+ rankScore,+ };+}++function response(results: ConversationSearchResultItem[]): ConversationSearchResponse {+ return {+ query: 'needle',+ results,+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ };+}++const devices = [+ { deviceId: 'dev-a', deviceName: 'Studio', connected: true },+ { deviceId: 'dev-b', deviceName: 'Laptop', connected: false },+];++describe('resolveConversationSearchOrigins', () => {+ it('searches local plus every known device when the machine filter is all', () => {+ expect(+ resolveConversationSearchOrigins({+ machineSelection: MACHINE_ALL,+ sessionIds: null,+ devices,+ getSessionDeviceId: () => undefined,+ }),+ ).toEqual([+ { kind: 'local', sessionIds: null },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ },+ {+ kind: 'remote',+ deviceId: 'dev-b',+ deviceName: 'Laptop',+ connected: false,+ sessionIds: null,+ },+ ]);+ });++ it('keeps a single-machine filter on that device only', () => {+ expect(+ resolveConversationSearchOrigins({+ machineSelection: ['dev-a'],+ sessionIds: null,+ devices,+ getSessionDeviceId: () => undefined,+ }),+ ).toEqual([+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ },+ ]);+ });++ it('partitions an explicit project session set by origin', () => {+ expect(+ resolveConversationSearchOrigins({+ machineSelection: [MACHINE_LOCAL],+ sessionIds: ['local-1', 'remote-1', 'remote-2'],+ devices,+ getSessionDeviceId: (id) => (id.startsWith('remote') ? 'dev-a' : undefined),+ }),+ ).toEqual([+ { kind: 'local', sessionIds: ['local-1'] },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: ['remote-1', 'remote-2'],+ },+ ]);+ });++ it('returns no origins for an empty explicit session set', () => {+ expect(+ resolveConversationSearchOrigins({+ machineSelection: MACHINE_ALL,+ sessionIds: [],+ devices,+ getSessionDeviceId: () => undefined,+ }),+ ).toEqual([]);+ });++ it('scopes a remote project by workingDir instead of mirrored session ids', () => {+ expect(+ resolveConversationSearchOrigins({+ machineSelection: [MACHINE_LOCAL],+ sessionIds: ['mirrored-only'],+ projectTargets: [{ deviceId: 'dev-a', workingDir: '/repo-remote' }],+ devices,+ getSessionDeviceId: () => 'dev-a',+ }),+ ).toEqual([+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ workingDirs: ['/repo-remote'],+ },+ ]);+ });++ it('keeps local/SSH session ids when mixed with a device-link project target', () => {+ expect(+ resolveConversationSearchOrigins({+ machineSelection: MACHINE_ALL,+ sessionIds: ['ssh-hit'],+ projectTargets: [{ deviceId: 'dev-a', workingDir: '/workspace/repo' }],+ devices,+ getSessionDeviceId: () => undefined,+ }),+ ).toEqual([+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ workingDirs: ['/workspace/repo'],+ },+ { kind: 'local', sessionIds: ['ssh-hit'] },+ ]);+ });++ it('does not fall back to local when only a connecting device is selected', () => {+ const connecting = searchDevicesFromSwitcher([+ { deviceId: 'dev-connecting', name: 'New Box', status: 'connecting' },+ ]);+ expect(+ resolveConversationSearchOrigins({+ machineSelection: ['dev-connecting'],+ sessionIds: null,+ devices: connecting,+ getSessionDeviceId: () => undefined,+ }),+ ).toEqual([+ {+ kind: 'remote',+ deviceId: 'dev-connecting',+ deviceName: 'New Box',+ connected: true,+ sessionIds: null,+ },+ ]);+ });+});++describe('shouldReleaseConversationSearchLock', () => {+ it('releases a lock when the project leaves the current machine scope', () => {+ expect(+ shouldReleaseConversationSearchLock({+ lockedProjectKey: 'device:dev-a:/repo',+ visibleProjects: [{ projectKey: 'local:/other' }],+ localPlatform: 'darwin',+ }),+ ).toBe(true);+ });++ it('keeps a lock while the project catalogue has not loaded', () => {+ expect(+ shouldReleaseConversationSearchLock({+ lockedProjectKey: 'device:dev-a:/repo',+ visibleProjects: [],+ localPlatform: 'darwin',+ machineSelection: ['dev-a'],+ }),+ ).toBe(false);+ });++ it('releases a lock when switching to a settled empty machine that does not own it', () => {+ expect(+ shouldReleaseConversationSearchLock({+ lockedProjectKey: 'device:dev-a:/repo',+ visibleProjects: [],+ localPlatform: 'darwin',+ machineSelection: ['dev-b'],+ }),+ ).toBe(true);+ });++ it('keeps a lock while the project is still visible', () => {+ expect(+ shouldReleaseConversationSearchLock({+ lockedProjectKey: 'device:dev-a:/repo',+ visibleProjects: [{ projectKey: 'device:dev-a:/repo' }],+ localPlatform: 'darwin',+ }),+ ).toBe(false);+ });+});++describe('merge and stamp', () => {+ it('keeps same-id hits from different devices and stamps origin', () => {+ const remote = stampRemoteSearchResponse(response([result('same', 10)]), {+ deviceId: 'dev-a',+ deviceName: 'Studio',+ });+ const merged = mergeConversationSearchFanout([response([result('same', 3)]), remote], 24);+ expect(merged.results.map((item) => conversationSearchResultKey(item)).sort()).toEqual([+ 'dev-a:same',+ 'local:same',+ ]);+ expect(+ merged.results.find((item) => item.session.deviceLinkDeviceId === 'dev-a')?.session+ .deviceLinkDeviceName,+ ).toBe('Studio');+ });+});++describe('searchCachedSessionsByTitle', () => {+ it('matches visible titles and skips workers', () => {+ const request: ConversationSearchRequest = { query: 'remote', limit: 10 };+ const page = searchCachedSessionsByTitle(+ [+ session({ id: 'hit', title: 'Remote planning', deviceLinkDeviceId: 'dev-a' }),+ session({+ id: 'worker',+ title: 'Remote worker',+ orcaRole: 'worker',+ deviceLinkDeviceId: 'dev-a',+ }),+ session({ id: 'miss', title: 'Local notes' }),+ ],+ request,+ );+ expect(page.results.map((item) => item.session.id)).toEqual(['hit']);+ expect(page.results[0]?.matchKind).toBe('title');+ });+});++describe('searchConversationsAcrossOrigins', () => {+ const request: ConversationSearchRequest = {+ query: 'needle',+ limit: 10,+ sortBy: 'relevance',+ semanticMode: 'hybrid',+ };++ it('fans out, forces keyword on remotes, and survives a failed device', async () => {+ const invokeRemote = vi.fn(async (deviceId: string) => {+ if (deviceId === 'dev-b') throw new Error('[DEVICE_LINK_NOT_CONNECTED] closed');+ return response([result('remote-hit', 50)]);+ });+ const page = await searchConversationsAcrossOrigins(request, {+ origins: [+ { kind: 'local', sessionIds: null },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ },+ {+ kind: 'remote',+ deviceId: 'dev-b',+ deviceName: 'Laptop',+ connected: true,+ sessionIds: null,+ },+ ],+ searchLocal: async () => response([result('local-hit', 20)]),+ invokeRemote,+ listCachedRemoteSessions: (deviceId) => [+ session({+ id: 'cached-hit',+ title: 'Needle on laptop',+ deviceLinkDeviceId: deviceId,+ deviceLinkDeviceName: 'Laptop',+ }),+ ],+ });++ expect(invokeRemote).toHaveBeenCalledWith('dev-a', 'local-db:conversations:search', [+ expect.objectContaining({ semanticMode: 'keyword' }),+ ]);+ expect(page.results.map((item) => item.session.id).sort()).toEqual([+ 'cached-hit',+ 'local-hit',+ 'remote-hit',+ ]);+ });++ it('falls back to sessions:list when the search channel is missing', async () => {+ const invokeRemote = vi.fn(async (_deviceId: string, channel: string) => {+ if (channel === 'local-db:conversations:search') {+ throw new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] not allowlisted');+ }+ return [session({ id: 'legacy', title: 'Needle legacy', deviceLinkDeviceId: 'dev-a' })];+ });+ const page = await searchConversationsAcrossOrigins(request, {+ origins: [+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ },+ ],+ searchLocal: async () => emptyConversationSearchResponse('needle'),+ invokeRemote,+ listCachedRemoteSessions: () => [],+ });+ expect(invokeRemote).toHaveBeenNthCalledWith(2, 'dev-a', 'local-db:sessions:list', [+ 100,+ 'all',+ ]);+ expect(page.results.map((item) => item.session.id)).toEqual(['legacy']);+ });++ it('falls back to sessions:list when the indexed page ignored workingDirs', async () => {+ const invokeRemote = vi.fn(async (_deviceId: string, channel: string) => {+ if (channel === 'local-db:conversations:search') {+ return response([result('other-project', 50, { workingDir: '/other' })]);+ }+ return [session({ id: 'legacy', title: 'Needle legacy', workingDir: '/repo-remote' })];+ });+ const page = await searchConversationsAcrossOrigins(request, {+ origins: [+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ workingDirs: ['/repo-remote'],+ },+ ],+ searchLocal: async () => emptyConversationSearchResponse('needle'),+ invokeRemote,+ listCachedRemoteSessions: () => [],+ });+ expect(invokeRemote).toHaveBeenCalledWith('dev-a', 'local-db:sessions:list', [100, 'all']);+ expect(page.results.map((item) => item.session.id)).toEqual(['legacy']);+ });++ it('skips remote invokes when hybrid reuses the first remote page', async () => {+ const invokeRemote = vi.fn();+ const page = await searchConversationsAcrossOrigins(+ { ...request, semanticMode: 'hybrid' },+ {+ origins: [+ { kind: 'local', sessionIds: null },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ },+ ],+ reuseRemoteResults: [result('remote-hit', 50, { deviceLinkDeviceId: 'dev-a' })],+ searchLocal: async () => response([result('local-hit', 20)]),+ invokeRemote,+ listCachedRemoteSessions: () => [],+ },+ );+ expect(invokeRemote).not.toHaveBeenCalled();+ expect(page.results.map((item) => item.session.id).sort()).toEqual([+ 'local-hit',+ 'remote-hit',+ ]);+ });++ it('keeps remote hits for hybrid reuse after the merged page is truncated', async () => {+ const locals = Array.from({ length: 24 }, (_, index) => result(`local-${index}`, 100 - index));+ const page = await searchConversationsAcrossOrigins(+ { ...request, limit: 24 },+ {+ origins: [+ { kind: 'local', sessionIds: null },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ },+ ],+ searchLocal: async () => response(locals),+ invokeRemote: async () => response([+ result('remote-squeezed', 1, { deviceLinkDeviceId: 'dev-a' }),+ ]),+ listCachedRemoteSessions: () => [],+ },+ );+ expect(page.results.map((item) => item.session.id)).not.toContain('remote-squeezed');+ expect(page.remoteResults?.map((item) => item.session.id)).toEqual(['remote-squeezed']);+ expect(+ remoteResultsFromFanoutPages([+ response(locals),+ response([result('remote-squeezed', 1, { deviceLinkDeviceId: 'dev-a' })]),+ ]).map((item) => item.session.id),+ ).toEqual(['remote-squeezed']);+ });++ it('rejects a failed local hybrid instead of publishing an empty reuse page', async () => {+ await expect(+ searchConversationsAcrossOrigins(+ { ...request, semanticMode: 'hybrid' },+ {+ origins: [{ kind: 'local', sessionIds: null }],+ reuseRemoteResults: [],+ searchLocal: async () => {+ throw new Error('hybrid down');+ },+ invokeRemote: vi.fn(),+ listCachedRemoteSessions: () => [],+ },+ ),+ ).rejects.toMatchObject({ code: 'UNKNOWN' });+ });++ it('returns an empty page when there are no origins', async () => {+ const page = await searchConversationsAcrossOrigins(request, {+ origins: [],+ searchLocal: async () => response([result('local-hit', 1)]),+ invokeRemote: vi.fn(),+ listCachedRemoteSessions: () => [],+ });+ expect(page.results).toEqual([]);+ });+});++describe('requestForOrigin', () => {+ it('does not send a mixed session id set to a remote origin', () => {+ const next = requestForOrigin(+ { query: 'x', semanticMode: 'hybrid', filters: { sessionIds: ['a', 'b'] } },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: ['b'],+ },+ );+ expect(next.semanticMode).toBe('keyword');+ expect(next.filters?.sessionIds).toEqual(['b']);+ });++ it('sends workingDirs so the host can search outside the controller mirror', () => {+ const next = requestForOrigin(+ { query: 'x', semanticMode: 'keyword' },+ {+ kind: 'remote',+ deviceId: 'dev-a',+ deviceName: 'Studio',+ connected: true,+ sessionIds: null,+ workingDirs: ['/repo-remote'],+ },+ );+ expect(next.filters?.sessionIds).toBeNull();+ expect(next.filters?.workingDirs).toEqual(['/repo-remote']);+ });+});++describe('filterResultsByWorkingDirs', () => {+ it('drops remote hits that belong to another project', () => {+ const page = filterResultsByWorkingDirs(+ response([+ result('keep', 1, { workingDir: '/repo-remote' }),+ result('drop', 1, { workingDir: '/other' }),+ ]),+ ['/repo-remote'],+ );+ expect(page.results.map((item) => item.session.id)).toEqual(['keep']);+ });+});++describe('filterResultsByRequestFilters', () => {+ it('drops remote hits that ignore status, agent, or activity filters', () => {+ const recent = new Date().toISOString();+ const page = filterResultsByRequestFilters(+ response([+ result('keep', 1, {+ agentKind: 'codex',+ status: 'archived',+ userSendAt: recent,+ }),+ result('wrong-agent', 1, {+ agentKind: 'cc',+ status: 'archived',+ userSendAt: recent,+ }),+ result('wrong-status', 1, {+ agentKind: 'codex',+ status: 'active',+ userSendAt: recent,+ }),+ result('too-old', 1, {+ agentKind: 'codex',+ status: 'archived',+ userSendAt: '2020-01-01T00:00:00.000Z',+ updatedAt: '2020-01-01T00:00:00.000Z',+ }),+ ]),+ {+ filters: {+ status: 'archived',+ agentKind: 'codex',+ lastActivity: '7d',+ },+ },+ );+ expect(page.results.map((item) => item.session.id)).toEqual(['keep']);+ });++ it('keeps a remote hit when updatedAt is recent but userSendAt is old', () => {+ const page = filterResultsByRequestFilters(+ response([+ result('keep', 1, {+ userSendAt: '2020-01-01T00:00:00.000Z',+ updatedAt: new Date().toISOString(),+ }),+ ]),+ { filters: { lastActivity: '7d' } },+ );+ expect(page.results.map((item) => item.session.id)).toEqual(['keep']);+ });+});++describe('remoteIndexedSearchIgnoredWorkingDirs', () => {+ it('detects an old host that searched globally and filled the page from other projects', () => {+ expect(+ remoteIndexedSearchIgnoredWorkingDirs(+ response([+ result('other', 1, { workingDir: '/other' }),+ result('keep', 1, { workingDir: '/repo-remote' }),+ ]),+ ['/repo-remote'],+ ),+ ).toBe(true);+ });++ it('does not treat an in-project page as unsupported', () => {+ expect(+ remoteIndexedSearchIgnoredWorkingDirs(+ response([result('keep', 1, { workingDir: '/repo-remote' })]),+ ['/repo-remote'],+ ),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/lib/conversationSearchFanout.ts b/apps/desktop/src/renderer/lib/conversationSearchFanout.tsnew file mode 100644index 0000000000..f0a348648b--- /dev/null+++ b/apps/desktop/src/renderer/lib/conversationSearchFanout.ts@@ -0,0 +1,602 @@+/**+ * conversationSearchFanout —— 侧栏任务搜索的本机 / device-link fan-out。+ *+ * 被控端任务不进控制端 SQLite。本机 IPC 与 `local-db:conversations:search` 隧道+ * 共用同一份 request,控制端按机器切换栏 / 项目锁定拆 origin 后再合并。+ * 纯函数 + 注入依赖,方便单测,不直接碰 store / Electron。+ */++import { conversationSearchTitle } from '../../shared/conversationSearch';+import type {+ ConversationSearchLastActivityFilter,+ ConversationSearchRequest,+ ConversationSearchResponse,+ ConversationSearchResultItem,+ ConversationSearchSessionStatus,+ ConversationSearchSessionSummary,+ ConversationSearchSortBy,+ ConversationSearchStatusFilter,+} from '../../shared/conversationSearch';+import type { Session } from '@/lib/ccAgent.types';+import { fuzzyMatch } from '@/features/cc-agent/lib/fuzzyMatch';+import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';+import {+ MACHINE_ALL,+ MACHINE_LOCAL,+ type MachineSelection,+} from '@/features/device-link/selectedMachineStore';+import {+ normalizeProjectKey,+ projectKeyComparisonKey,+} from '../../shared/projectKeys';+import { normalizeWorkingDirForGrouping } from '../../shared/workingDir';++export interface ConversationSearchDevice {+ deviceId: string;+ deviceName: string;+ connected: boolean;+}++export function searchDevicesFromSwitcher(+ devices: readonly { deviceId: string; name: string; status: string }[],+): ConversationSearchDevice[] {+ return devices+ .filter((device) => device.status !== 'rejected')+ .map((device) => ({+ deviceId: device.deviceId,+ deviceName: device.name,+ connected: device.status === 'connected' || device.status === 'connecting',+ }));+}++export interface ConversationSearchProjectTarget {+ /** device-link 设备。本机 / SSH 项目不走这条路径,避免丢掉 remoteHostId。 */+ deviceId: string;+ workingDir: string;+}++export type ConversationSearchOrigin =+ | {+ kind: 'local';+ sessionIds: string[] | null;+ workingDirs?: string[] | null;+ }+ | {+ kind: 'remote';+ deviceId: string;+ deviceName: string | null;+ connected: boolean;+ sessionIds: string[] | null;+ workingDirs?: string[] | null;+ };++const LAST_ACTIVITY_DAY_COUNTS: Record<+ Exclude<ConversationSearchLastActivityFilter, 'all'>,+ number+> = {+ '1d': 1,+ '3d': 3,+ '7d': 7,+ '30d': 30,+};+const DAY_MS = 24 * 60 * 60 * 1000;+const LEGACY_REMOTE_LIST_LIMIT = 100;++export function emptyConversationSearchResponse(query = ''): ConversationSearchResponse {+ return {+ query,+ results: [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ };+}++export function resolveConversationSearchOrigins(args: {+ machineSelection: MachineSelection;+ sessionIds?: string[] | null;+ projectTargets?: readonly ConversationSearchProjectTarget[] | null;+ devices: readonly ConversationSearchDevice[];+ getSessionDeviceId: (sessionId: string) => string | undefined;+}): ConversationSearchOrigin[] {+ const targetOrigins =+ args.projectTargets && args.projectTargets.length > 0+ ? originsFromProjectTargets(args.projectTargets, args.devices)+ : [];+ const sessionIds = normalizeSessionIds(args.sessionIds);+ if (sessionIds && sessionIds.length === 0 && targetOrigins.length === 0) return [];++ if (sessionIds && sessionIds.length > 0) {+ return mergeProjectAndSessionOrigins(+ targetOrigins,+ originsFromSessionIds(sessionIds, args.devices, args.getSessionDeviceId),+ );+ }+ if (targetOrigins.length > 0) return targetOrigins;++ return originsFromMachineSelection(args.machineSelection, args.devices);+}++function originsFromProjectTargets(+ targets: readonly ConversationSearchProjectTarget[],+ devices: readonly ConversationSearchDevice[],+): ConversationSearchOrigin[] {+ const deviceById = new Map(devices.map((device) => [device.deviceId, device]));+ const remoteDirs = new Map<string, string[]>();++ for (const target of targets) {+ const deviceId = target.deviceId.trim();+ const workingDir = normalizeWorkingDirForGrouping(target.workingDir);+ if (!deviceId || workingDir == null) continue;+ const bucket = remoteDirs.get(deviceId);+ if (bucket) {+ if (!bucket.includes(workingDir)) bucket.push(workingDir);+ } else {+ remoteDirs.set(deviceId, [workingDir]);+ }+ }++ return [...remoteDirs].map(([deviceId, workingDirs]) => {+ const device = deviceById.get(deviceId);+ return {+ kind: 'remote' as const,+ deviceId,+ deviceName: device?.deviceName ?? null,+ connected: device?.connected === true,+ sessionIds: null,+ workingDirs,+ };+ });+}++function mergeProjectAndSessionOrigins(+ targetOrigins: ConversationSearchOrigin[],+ sessionOrigins: ConversationSearchOrigin[],+): ConversationSearchOrigin[] {+ const targetDeviceIds = new Set(+ targetOrigins.flatMap((origin) => (origin.kind === 'remote' ? [origin.deviceId] : [])),+ );+ return [+ ...targetOrigins,+ ...sessionOrigins.filter(+ (origin) => origin.kind === 'local' || !targetDeviceIds.has(origin.deviceId),+ ),+ ];+}++function originsFromSessionIds(+ sessionIds: string[],+ devices: readonly ConversationSearchDevice[],+ getSessionDeviceId: (sessionId: string) => string | undefined,+): ConversationSearchOrigin[] {+ const deviceById = new Map(devices.map((device) => [device.deviceId, device]));+ const localIds: string[] = [];+ const remoteIds = new Map<string, string[]>();++ for (const sessionId of sessionIds) {+ const deviceId = getSessionDeviceId(sessionId);+ if (!deviceId) {+ localIds.push(sessionId);+ continue;+ }+ const bucket = remoteIds.get(deviceId);+ if (bucket) bucket.push(sessionId);+ else remoteIds.set(deviceId, [sessionId]);+ }++ const origins: ConversationSearchOrigin[] = [];+ if (localIds.length > 0) {+ origins.push({ kind: 'local', sessionIds: localIds });+ }+ for (const [deviceId, ids] of remoteIds) {+ const device = deviceById.get(deviceId);+ origins.push({+ kind: 'remote',+ deviceId,+ deviceName: device?.deviceName ?? null,+ connected: device?.connected === true,+ sessionIds: ids,+ });+ }+ return origins;+}++function originsFromMachineSelection(+ selection: MachineSelection,+ devices: readonly ConversationSearchDevice[],+): ConversationSearchOrigin[] {+ const includeLocal = selection === MACHINE_ALL || selection.includes(MACHINE_LOCAL);+ const selectedRemoteIds =+ selection === MACHINE_ALL ? null : new Set(selection.filter((id) => id !== MACHINE_LOCAL));+ const origins: ConversationSearchOrigin[] = [];+ if (includeLocal) {+ origins.push({ kind: 'local', sessionIds: null });+ }+ for (const device of devices) {+ if (selectedRemoteIds && !selectedRemoteIds.has(device.deviceId)) continue;+ origins.push({+ kind: 'remote',+ deviceId: device.deviceId,+ deviceName: device.deviceName,+ connected: device.connected,+ sessionIds: null,+ });+ }+ return origins;+}++export function stampRemoteSearchResponse(+ response: ConversationSearchResponse,+ device: { deviceId: string; deviceName?: string | null },+): ConversationSearchResponse {+ const results = Array.isArray(response?.results) ? response.results : [];+ return {+ query: response?.query ?? '',+ vectorUsed: response?.vectorUsed === true,+ vectorSkipReason: response?.vectorSkipReason ?? null,+ poolCapped: response?.poolCapped === true,+ results: results.map((item) => ({+ ...item,+ session: {+ ...item.session,+ deviceLinkDeviceId: device.deviceId,+ deviceLinkDeviceName: device.deviceName ?? item.session.deviceLinkDeviceName ?? null,+ },+ })),+ };+}++export function conversationSearchResultKey(item: ConversationSearchResultItem): string {+ return `${item.session.deviceLinkDeviceId ?? 'local'}:${item.session.id}`;+}++/** Remote hits from origin pages, before the merged display page is truncated. */+export function remoteResultsFromFanoutPages(+ pages: readonly ConversationSearchResponse[],+): ConversationSearchResultItem[] {+ const byKey = new Map<string, ConversationSearchResultItem>();+ for (const page of pages) {+ for (const item of page.results) {+ if (!item.session.deviceLinkDeviceId) continue;+ const key = conversationSearchResultKey(item);+ const existing = byKey.get(key);+ if (!existing || item.rankScore > existing.rankScore) {+ byKey.set(key, item);+ }+ }+ }+ return [...byKey.values()];+}++export function mergeConversationSearchFanout(+ pages: readonly ConversationSearchResponse[],+ limit: number,+ sortBy: ConversationSearchSortBy = 'relevance',+): ConversationSearchResponse {+ const byKey = new Map<string, ConversationSearchResultItem>();+ for (const page of pages) {+ for (const item of page.results) {+ const key = conversationSearchResultKey(item);+ const existing = byKey.get(key);+ if (!existing || item.rankScore > existing.rankScore) {+ byKey.set(key, item);+ }+ }+ }++ const results = [...byKey.values()]+ .sort((a, b) => compareSearchResults(a, b, sortBy))+ .slice(0, Math.max(1, limit));++ return {+ query: pages[0]?.query ?? '',+ results,+ vectorUsed: pages.some((page) => page.vectorUsed),+ vectorSkipReason: pages.find((page) => page.vectorSkipReason)?.vectorSkipReason ?? null,+ poolCapped: pages.some((page) => page.poolCapped),+ };+}++export function searchCachedSessionsByTitle(+ sessions: readonly Session[],+ request: ConversationSearchRequest,+): ConversationSearchResponse {+ const query = request.query.trim();+ if (!query) return emptyConversationSearchResponse('');++ const filters = request.filters ?? {};+ const sessionIds = normalizeSessionIds(filters.sessionIds);+ if (sessionIds && sessionIds.length === 0) {+ return emptyConversationSearchResponse(query);+ }+ const allowed = sessionIds ? new Set(sessionIds) : null;+ const workingDirs = normalizeWorkingDirSet(filters.workingDirs);+ const activityCutoff = cutoffForLastActivity(filters.lastActivity ?? 'all');+ const titleMatches: Array<{+ session: ConversationSearchSessionSummary;+ score: number;+ indices: number[];+ index: number;+ }> = [];++ sessions.forEach((session, index) => {+ if (isOrcaWorkerSession(session)) return;+ if (allowed && !allowed.has(session.id)) return;+ if (!matchesWorkingDirSet(session.workingDir, workingDirs)) return;+ if (!matchesStatus(session.status, filters.status ?? 'all')) return;+ if (+ filters.agentKind &&+ filters.agentKind !== 'all' &&+ session.agentKind !== filters.agentKind+ ) {+ return;+ }+ if (activityCutoff !== null && sessionActivityMs(session) < activityCutoff) return;+ const title = conversationSearchTitle(session.title, request.unnamedLabel);+ const match = fuzzyMatch(title, query);+ if (!match) return;+ titleMatches.push({+ session: sessionToSearchSummary(session),+ score: match.score,+ indices: match.indices,+ index,+ });+ });++ titleMatches.sort(+ (a, b) =>+ b.score - a.score ||+ sessionActivityMs(b.session) - sessionActivityMs(a.session) ||+ a.index - b.index,+ );++ const limit = clampLimit(request.limit);+ const results: ConversationSearchResultItem[] = titleMatches+ .slice(0, limit)+ .map((match, index) => ({+ session: match.session,+ matchKind: 'title',+ titleMatchIndices: match.indices,+ titleScore: match.score,+ contentHit: null,+ contentHits: [],+ rankScore: 2_000_000 + match.score * 100 - index,+ }));++ return {+ query,+ results: sortByRequest(results, request.sortBy),+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ };+}++export function requestForOrigin(+ request: ConversationSearchRequest,+ origin: ConversationSearchOrigin,+): ConversationSearchRequest {+ return {+ ...request,+ semanticMode: origin.kind === 'remote' ? 'keyword' : request.semanticMode,+ filters: {+ ...request.filters,+ sessionIds: origin.sessionIds,+ workingDirs: origin.workingDirs ?? null,+ },+ };+}++export function remoteIndexedSearchIgnoredWorkingDirs(+ response: ConversationSearchResponse,+ workingDirs: string[] | null | undefined,+): boolean {+ const allowed = normalizeWorkingDirSet(workingDirs);+ if (allowed == null) return false;+ const results = Array.isArray(response?.results) ? response.results : [];+ return results.some((item) => !matchesWorkingDirSet(item.session.workingDir, allowed));+}++export function filterResultsByWorkingDirs(+ response: ConversationSearchResponse,+ workingDirs: string[] | null | undefined,+): ConversationSearchResponse {+ return filterResultsByRequestFilters(response, { filters: { workingDirs } });+}++/** Drop remote hits that ignore status / agent / activity / project filters. */+export function filterResultsByRequestFilters(+ response: ConversationSearchResponse,+ request: Pick<ConversationSearchRequest, 'filters'>,+): ConversationSearchResponse {+ const filters = request.filters ?? {};+ const allowedDirs = normalizeWorkingDirSet(filters.workingDirs);+ const activityCutoff = cutoffForLastActivity(filters.lastActivity ?? 'all');+ const status = filters.status ?? 'all';+ const agentKind = filters.agentKind ?? 'all';+ return {+ ...response,+ results: response.results.filter((item) => {+ if (!matchesWorkingDirSet(item.session.workingDir, allowedDirs)) return false;+ if (isOrcaWorkerSession(item.session)) return false;+ if (!matchesStatus(item.session.status, status)) return false;+ if (agentKind !== 'all' && item.session.agentKind !== agentKind) return false;+ if (activityCutoff !== null && sessionActivityMs(item.session) < activityCutoff) {+ return false;+ }+ return true;+ }),+ };+}++export function shouldReleaseConversationSearchLock(args: {+ lockedProjectKey: string | null;+ visibleProjects: readonly { projectKey: string }[];+ localPlatform: string;+ machineSelection?: MachineSelection;+}): boolean {+ if (!args.lockedProjectKey) return false;+ if (+ args.machineSelection != null &&+ !lockMatchesMachineSelection(args.lockedProjectKey, args.machineSelection)+ ) {+ return true;+ }+ // Catalogue still empty (first paint / index not loaded): keep the lock so+ // the project-menu fallback session ids / workingDir can apply.+ if (args.visibleProjects.length === 0) return false;+ const lockedComparison = projectKeyComparisonKey(+ args.lockedProjectKey,+ args.localPlatform,+ );+ if (lockedComparison == null) return true;+ return !args.visibleProjects.some((project) => {+ const comparison = projectKeyComparisonKey(project.projectKey, args.localPlatform);+ return comparison != null && comparison === lockedComparison;+ });+}++function lockMatchesMachineSelection(+ projectKey: string,+ selection: MachineSelection,+): boolean {+ if (selection === MACHINE_ALL) return true;+ const deviceId = deviceIdFromProjectKey(projectKey);+ if (deviceId == null) return selection.includes(MACHINE_LOCAL);+ return selection.includes(deviceId);+}++function deviceIdFromProjectKey(projectKey: string): string | null {+ const normalized = normalizeProjectKey(projectKey);+ if (normalized == null || !normalized.startsWith('device:')) return null;+ const rest = normalized.slice('device:'.length);+ const sep = rest.indexOf(':');+ if (sep <= 0) return null;+ try {+ return decodeURIComponent(rest.slice(0, sep));+ } catch {+ return null;+ }+}++export const LEGACY_REMOTE_SESSION_LIST_LIMIT = LEGACY_REMOTE_LIST_LIMIT;++export function sessionToSearchSummary(session: Session): ConversationSearchSessionSummary {+ return {+ id: session.id,+ title: session.title,+ workingDir: session.workingDir,+ workspaceKind: session.workspaceKind,+ agentKind: session.agentKind,+ status: session.status,+ source: session.source,+ orcaRole: session.orcaRole,+ parentSessionId: session.parentSessionId,+ userSendAt: session.userSendAt,+ updatedAt: session.updatedAt,+ createdAt: session.createdAt,+ _count: { messages: session._count?.messages ?? 0 },+ deviceLinkDeviceId: session.deviceLinkDeviceId ?? null,+ deviceLinkDeviceName: session.deviceLinkDeviceName ?? null,+ };+}++function normalizeWorkingDirSet(value: string[] | null | undefined): Set<string> | null {+ if (value == null || !Array.isArray(value)) return null;+ const out = new Set<string>();+ for (const item of value) {+ const normalized = normalizeWorkingDirForGrouping(item);+ if (normalized) out.add(normalized);+ }+ return out.size > 0 ? out : null;+}++function matchesWorkingDirSet(+ workingDir: string | null | undefined,+ allowed: Set<string> | null,+): boolean {+ if (allowed == null) return true;+ const key = normalizeWorkingDirForGrouping(workingDir);+ return key != null && allowed.has(key);+}++function normalizeSessionIds(value: string[] | null | undefined): string[] | null {+ if (value == null) return null;+ if (!Array.isArray(value)) return null;+ const seen = new Set<string>();+ const out: string[] = [];+ for (const item of value) {+ if (typeof item !== 'string') continue;+ const trimmed = item.trim();+ if (!trimmed || seen.has(trimmed)) continue;+ seen.add(trimmed);+ out.push(trimmed);+ }+ return out;+}++function matchesStatus(+ status: ConversationSearchSessionStatus | string,+ filter: ConversationSearchStatusFilter,+): boolean {+ if (status === 'deleted') return false;+ if (filter === 'all') return status === 'active' || status === 'archived';+ return status === filter;+}++function cutoffForLastActivity(lastActivity: ConversationSearchLastActivityFilter): number | null {+ if (lastActivity === 'all') return null;+ return Date.now() - LAST_ACTIVITY_DAY_COUNTS[lastActivity] * DAY_MS;+}++function sessionActivityMs(+ session: Pick<Session, 'userSendAt' | 'updatedAt'> | ConversationSearchSessionSummary,+): number {+ return Math.max(parseActivityMs(session.userSendAt), parseActivityMs(session.updatedAt));+}++function parseActivityMs(value: string | null | undefined): number {+ if (!value) return 0;+ const ms = Date.parse(value);+ return Number.isFinite(ms) ? ms : 0;+}++function clampLimit(value: unknown): number {+ if (typeof value !== 'number' || !Number.isFinite(value)) return 24;+ return Math.max(1, Math.min(Math.floor(value), 50));+}++function sortByRequest(+ results: ConversationSearchResultItem[],+ sortBy: ConversationSearchSortBy | undefined,+): ConversationSearchResultItem[] {+ return [...results].sort((a, b) => compareSearchResults(a, b, sortBy ?? 'relevance'));+}++function compareSearchResults(+ a: ConversationSearchResultItem,+ b: ConversationSearchResultItem,+ sortBy: ConversationSearchSortBy,+): number {+ if (sortBy === 'activityDesc') {+ return sessionActivityMs(b.session) - sessionActivityMs(a.session) || relevanceCompare(a, b);+ }+ if (sortBy === 'activityAsc') {+ return sessionActivityMs(a.session) - sessionActivityMs(b.session) || relevanceCompare(a, b);+ }+ return relevanceCompare(a, b);+}++function relevanceCompare(+ a: ConversationSearchResultItem,+ b: ConversationSearchResultItem,+): number {+ const groupA = a.matchKind === 'title' || a.matchKind === 'both' ? 1 : 0;+ const groupB = b.matchKind === 'title' || b.matchKind === 'both' ? 1 : 0;+ return (+ groupB - groupA ||+ b.rankScore - a.rankScore ||+ sessionActivityMs(b.session) - sessionActivityMs(a.session) ||+ a.session.id.localeCompare(b.session.id)+ );+}diff --git a/apps/desktop/src/renderer/lib/conversationSearchService.ts b/apps/desktop/src/renderer/lib/conversationSearchService.tsindex 40a649f194..7dba5c54bf 100644--- a/apps/desktop/src/renderer/lib/conversationSearchService.ts+++ b/apps/desktop/src/renderer/lib/conversationSearchService.ts@@ -2,8 +2,23 @@ import type {ConversationSearchRequest,ConversationSearchResponse,} from '../../shared/conversationSearch';+import type { Session } from '@/lib/ccAgent.types';import { ApiError } from '@/lib/httpClient';import { extractIpcError } from '@/utils/ipcError';+import {+ emptyConversationSearchResponse,+ filterResultsByRequestFilters,+ LEGACY_REMOTE_SESSION_LIST_LIMIT,+ remoteIndexedSearchIgnoredWorkingDirs,+ mergeConversationSearchFanout,+ remoteResultsFromFanoutPages,+ requestForOrigin,+ searchCachedSessionsByTitle,+ stampRemoteSearchResponse,+ type ConversationSearchOrigin,+} from './conversationSearchFanout';+import type { ConversationSearchResultItem } from '../../shared/conversationSearch';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';function wrap<T>(p: Promise<T>): Promise<T> {return p.catch((err: unknown) => {@@ -18,8 +33,196 @@ function wrap<T>(p: Promise<T>): Promise<T> {});}+export interface ConversationSearchFanoutDeps {+ origins: ConversationSearchOrigin[];+ searchLocal: (request: ConversationSearchRequest) => Promise<ConversationSearchResponse>;+ invokeRemote: (deviceId: string, channel: string, args: unknown[]) => Promise<unknown>;+ listCachedRemoteSessions: (deviceId: string) => Session[];+}++export async function searchConversationsAcrossOrigins(+ request: ConversationSearchRequest,+ deps: ConversationSearchFanoutDeps & {+ reuseRemoteResults?: ConversationSearchResultItem[];+ },+): Promise<ConversationSearchResponse> {+ const query = request.query.trim();+ if (!query) return emptyConversationSearchResponse('');+ const reuseRemote = deps.reuseRemoteResults != null;+ const origins = reuseRemote+ ? deps.origins.filter((origin) => origin.kind === 'local')+ : deps.origins;+ if (origins.length === 0 && !reuseRemote) return emptyConversationSearchResponse(query);++ const pages = await Promise.all(+ origins.map((origin) => searchOneOrigin(request, origin, deps)),+ );+ const present = pages.filter((page): page is ConversationSearchResponse => page !== null);+ if (reuseRemote) {+ if (origins.length > 0 && present.length === 0) {+ throw new ApiError('UNKNOWN', 0, 'conversation search failed');+ }+ present.push({+ query,+ results: deps.reuseRemoteResults ?? [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ });+ }+ if (present.length === 0) {+ throw new ApiError('UNKNOWN', 0, 'conversation search failed');+ }+ const merged = mergeConversationSearchFanout(+ present,+ request.limit ?? 24,+ request.sortBy ?? 'relevance',+ );+ return {+ ...merged,+ remoteResults: remoteResultsFromFanoutPages(present),+ };+}++async function searchOneOrigin(+ request: ConversationSearchRequest,+ origin: ConversationSearchOrigin,+ deps: ConversationSearchFanoutDeps,+): Promise<ConversationSearchResponse | null> {+ const originRequest = requestForOrigin(request, origin);+ if (origin.kind === 'local') {+ try {+ return await deps.searchLocal(originRequest);+ } catch {+ return null;+ }+ }++ if (!origin.connected) {+ return finalizeRemoteResponse(+ searchCachedSessionsByTitle(deps.listCachedRemoteSessions(origin.deviceId), originRequest),+ origin,+ originRequest,+ );+ }++ try {+ const response = await searchRemoteIndexed(origin.deviceId, originRequest, deps.invokeRemote);+ if (remoteIndexedSearchIgnoredWorkingDirs(response, origin.workingDirs)) {+ return finalizeRemoteResponse(+ await searchRemoteLegacyByTitle(origin.deviceId, originRequest, deps),+ origin,+ originRequest,+ );+ }+ return finalizeRemoteResponse(response, origin, originRequest);+ } catch (error) {+ if (isDeviceLinkNotConnected(error)) {+ return finalizeRemoteResponse(+ searchCachedSessionsByTitle(deps.listCachedRemoteSessions(origin.deviceId), originRequest),+ origin,+ originRequest,+ );+ }+ if (isChannelNotAllowed(error)) {+ return finalizeRemoteResponse(+ await searchRemoteLegacyByTitle(origin.deviceId, originRequest, deps),+ origin,+ originRequest,+ );+ }+ return finalizeRemoteResponse(+ searchCachedSessionsByTitle(deps.listCachedRemoteSessions(origin.deviceId), originRequest),+ origin,+ originRequest,+ );+ }+}++async function searchRemoteIndexed(+ deviceId: string,+ request: ConversationSearchRequest,+ invokeRemote: ConversationSearchFanoutDeps['invokeRemote'],+): Promise<ConversationSearchResponse> {+ const response = await invokeRemote(deviceId, 'local-db:conversations:search', [request]);+ return response as ConversationSearchResponse;+}++async function searchRemoteLegacyByTitle(+ deviceId: string,+ request: ConversationSearchRequest,+ deps: ConversationSearchFanoutDeps,+): Promise<ConversationSearchResponse> {+ try {+ const sessions = await listRemoteSessions(deviceId, request, deps.invokeRemote);+ return searchCachedSessionsByTitle(sessions, request);+ } catch {+ return searchCachedSessionsByTitle(deps.listCachedRemoteSessions(deviceId), request);+ }+}++async function listRemoteSessions(+ deviceId: string,+ request: ConversationSearchRequest,+ invokeRemote: ConversationSearchFanoutDeps['invokeRemote'],+): Promise<Session[]> {+ const status =+ request.filters?.status === 'active' || request.filters?.status === 'archived'+ ? request.filters.status+ : 'all';+ return (await invokeRemote(deviceId, 'local-db:sessions:list', [+ LEGACY_REMOTE_SESSION_LIST_LIMIT,+ status,+ ])) as Session[];+}++function finalizeRemoteResponse(+ response: ConversationSearchResponse,+ origin: Extract<ConversationSearchOrigin, { kind: 'remote' }>,+ originRequest: ConversationSearchRequest,+): ConversationSearchResponse {+ return filterResultsByRequestFilters(+ stampRemoteSearchResponse(response, {+ deviceId: origin.deviceId,+ deviceName: origin.deviceName,+ }),+ originRequest,+ );+}++function isChannelNotAllowed(error: unknown): boolean {+ const code = extractIpcError(error)?.code ?? (error instanceof ApiError ? error.code : null);+ if (code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') return true;+ return error instanceof Error && /CHANNEL_NOT_ALLOWED/.test(error.message);+}++function isDeviceLinkNotConnected(error: unknown): boolean {+ const code = extractIpcError(error)?.code ?? (error instanceof ApiError ? error.code : null);+ return code === 'DEVICE_LINK_NOT_CONNECTED';+}+export function searchConversations(request: ConversationSearchRequest,+ options?: {+ origins?: ConversationSearchOrigin[];+ reuseRemoteResults?: ConversationSearchResultItem[];+ },): Promise<ConversationSearchResponse> {- return wrap(window.electronAPI.localDb.conversations.search(request));+ return searchConversationsAcrossOrigins(request, {+ origins: options?.origins ?? [+ {+ kind: 'local',+ sessionIds: request.filters?.sessionIds ?? null,+ workingDirs: request.filters?.workingDirs ?? null,+ },+ ],+ reuseRemoteResults: options?.reuseRemoteResults,+ searchLocal: (next) => wrap(window.electronAPI.localDb.conversations.search(next)),+ invokeRemote: (deviceId, channel, args) =>+ window.electronAPI.deviceLink.invoke(deviceId, channel, args),+ listCachedRemoteSessions: (deviceId) =>+ remoteProjectsStore+ .getMergedRemoteSessions()+ .filter((session) => session.deviceLinkDeviceId === deviceId),+ });}diff --git a/apps/desktop/src/renderer/state/conversationSearchRequest.ts b/apps/desktop/src/renderer/state/conversationSearchRequest.tsindex dcec23b7ae..5b93d25b0b 100644--- a/apps/desktop/src/renderer/state/conversationSearchRequest.ts+++ b/apps/desktop/src/renderer/state/conversationSearchRequest.ts@@ -17,6 +17,8 @@ export interface ConversationSearchProjectRequest {projectKey: string;projectName: string;sessionIds: string[];+ workingDir?: string | null;+ deviceLinkDeviceId?: string | null;requestId: number;}@@ -33,6 +35,8 @@ export function requestConversationSearch(req: {projectKey: string;projectName: string;sessionIds: string[];+ workingDir?: string | null;+ deviceLinkDeviceId?: string | null;}): void {current = { ...req, requestId: nextRequestId++ };emit();diff --git a/apps/desktop/src/shared/conversationSearch.ts b/apps/desktop/src/shared/conversationSearch.tsindex 1e886a7b9a..c540cd2c51 100644--- a/apps/desktop/src/shared/conversationSearch.ts+++ b/apps/desktop/src/shared/conversationSearch.ts@@ -7,13 +7,7 @@ export type ConversationSearchWorkspaceKind = 'project' | 'dialogue';export type ConversationSearchSessionStatus = 'active' | 'archived' | 'deleted';export type ConversationSearchOrcaRole = 'lead' | 'worker';export type ConversationSearchMessageRole =- | 'user'- | 'assistant'- | 'tool_use'- | 'tool_result'- | 'ask_user'- | 'plan_review'- | 'thinking';+ 'user' | 'assistant' | 'tool_use' | 'tool_result' | 'ask_user' | 'plan_review' | 'thinking';export interface ConversationSearchRequest {query: string;@@ -49,6 +43,11 @@ export interface ConversationSearchFilters {* filtering so search follows the exact same project grouping as the sidebar.*/sessionIds?: string[] | null;+ /**+ * Optional project workingDir set (grouping-normalized). Remote project+ * search uses this instead of the controller's mirrored session-id window.+ */+ workingDirs?: string[] | null;}export type ConversationSearchMatchKind = 'title' | 'content' | 'both';@@ -67,6 +66,9 @@ export interface ConversationSearchSessionSummary {updatedAt: string;createdAt: string;_count: { messages: number };+ /** device-link origin stamped by the controller after a remote search. */+ deviceLinkDeviceId?: string | null;+ deviceLinkDeviceName?: string | null;}export interface ConversationSearchContentHit {@@ -113,4 +115,6 @@ export interface ConversationSearchResponse {vectorUsed: boolean;vectorSkipReason: string | null;poolCapped: boolean;+ /** Controller fan-out only: remote hits before the merged page is truncated. */+ remoteResults?: ConversationSearchResultItem[];}diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex d36ac48555..9c8181e3a8 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -245,9 +245,10 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// —— 读模型(被控端本地 DB 是数据真相)——'local-db:sessions:list','local-db:sessions:get',- // Read-only indexed task search for the remote Composer @ palette. Older- // controlled clients reject this channel and the controller falls back to- // the bounded legacy sessions:list projection.+ // Read-only indexed task search for the remote Composer @ palette and the+ // controller sidebar task search. Older controlled clients reject this+ // channel and the controller falls back to the bounded legacy sessions:list+ // projection.'local-db:conversations:search',DL_HISTORY_MESSAGES_CHANNEL,'local-db:messages:list',