Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

26.4 KB
Raw Blame
// @vitest-environment jsdom

import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createElement } from 'react';
import type { MouseEvent, ReactElement, ReactNode } from 'react';
import type { NavigateFunction } from 'react-router-dom';

import { searchConversations } from '@/lib/conversationSearchService';
import { ConversationSearchBox } from '@/features/cc-agent/sidebar/ConversationSearchBox';
import type { ProjectNode as ProjectNodeData } from '@/features/cc-agent/lib/projectGrouping';

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, options?: Record<string, unknown>) => {
      if (key === 'ccAgent.search.filter.active') return `filters:${String(options?.count)}`;
      if (key === 'ccAgent.sidebar.filterSelectedProjects') {
        return `${String(options?.count)} projects`;
      }
      if (key === 'ccAgent.search.filterAria') return 'filter';
      if (key === 'ccAgent.search.sortAria') return 'sort';
      return key;
    },
  }),
}));

vi.mock('@/lib/conversationSearchService', () => ({
  searchConversations: vi.fn(),
}));

vi.mock('@/lib/orcaSessionIdentity', async (importOriginal) => ({
  ...await importOriginal<typeof import('@/lib/orcaSessionIdentity')>(),
  resolveSessionRoute: vi.fn(),
}));

vi.mock('@/components/ui/popover', async () => {
  const React = await import('react');
  const PopoverContext = React.createContext<{
    open: boolean;
    onOpenChange: (next: boolean) => void;
  } | null>(null);

  return {
    Popover: ({
      open,
      onOpenChange,
      children,
    }: {
      open: boolean;
      onOpenChange: (next: boolean) => void;
      children: ReactNode;
    }) =>
      React.createElement(
        PopoverContext.Provider,
        { value: { open, onOpenChange } },
        children,
      ),
    PopoverTrigger: ({ children }: { asChild?: boolean; children: ReactNode }) => {
      const ctx = React.useContext(PopoverContext);
      const child = React.Children.only(children) as ReactElement<{
        onClick?: (event: MouseEvent<HTMLElement>) => void;
      }>;
      return React.cloneElement(child, {
        onClick: (event: MouseEvent<HTMLElement>) => {
          child.props.onClick?.(event);
          ctx?.onOpenChange(!ctx.open);
        },
      });
    },
    PopoverContent: ({ children }: { children: ReactNode }) => {
      const ctx = React.useContext(PopoverContext);
      if (!ctx?.open) return null;
      return React.createElement('div', { 'data-testid': 'conversation-search-popover' }, children);
    },
  };
});

vi.mock('@/components/ui/dropdown-menu', async () => {
  const React = await import('react');

  type SelectEvent = {
    preventDefault: () => void;
    stopPropagation: () => void;
  };
  type MenuItemProps = {
    children: ReactNode;
    disabled?: boolean;
    onSelect?: (event: SelectEvent) => void;
  };
  const passthrough = ({ children }: { children: ReactNode }) =>
    React.createElement(React.Fragment, null, children);

  return {
    DropdownMenu: passthrough,
    DropdownMenuContent: passthrough,
    DropdownMenuSub: passthrough,
    DropdownMenuSubContent: passthrough,
    DropdownMenuTrigger: passthrough,
    DropdownMenuSeparator: () => React.createElement('hr'),
    DropdownMenuSubTrigger: ({ children }: { children: ReactNode }) =>
      React.createElement('button', { type: 'button' }, children),
    DropdownMenuItem: ({ children, disabled, onSelect }: MenuItemProps) =>
      React.createElement(
        'button',
        {
          type: 'button',
          disabled,
          onClick: (event: MouseEvent<HTMLButtonElement>) => {
            onSelect?.(event);
          },
        },
        children,
      ),
  };
});

const source = readFileSync(
  resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'ConversationSearchBox.tsx'),
  'utf8',
);
const projectNodeSource = readFileSync(
  resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'ProjectNode.tsx'),
  'utf8',
);
const SEARCH_WAIT_TIMEOUT_MS = 1500;

const projects: ProjectNodeData[] = [
  {
    projectKey: 'local:/repo-a',
    scope: 'local',
    workingDir: '/repo-a',
    remoteHostId: null,
    deviceLinkDeviceId: null,
    deviceLinkDeviceName: null,
    deviceLinkConnectionStatus: null,
    displayName: 'Repo A',
    segments: 1,
    sessions: [
      { id: 'session-a1' } as ProjectNodeData['sessions'][number],
      { id: 'session-a2' } as ProjectNodeData['sessions'][number],
    ],
    latestActivityAt: '2026-06-14T00:00:00.000Z',
  },
  {
    projectKey: 'local:/repo-b',
    scope: 'local',
    workingDir: '/repo-b',
    remoteHostId: null,
    deviceLinkDeviceId: null,
    deviceLinkDeviceName: null,
    deviceLinkConnectionStatus: null,
    displayName: 'Repo B',
    segments: 1,
    sessions: [{ id: 'session-b1' } as ProjectNodeData['sessions'][number]],
    latestActivityAt: '2026-06-14T00:00:00.000Z',
  },
];

const navigate = vi.fn() as unknown as NavigateFunction;
const hiddenProjectKeys = new Set<string>();

function renderSearchBox({
  requestId = null,
  allKnownProjects = projects,
  sessionIds = ['session-a1', 'session-a2'],
}: {
  requestId?: number | null;
  allKnownProjects?: ProjectNodeData[];
  sessionIds?: string[];
} = {}) {
  return render(
    createElement(ConversationSearchBox, {
      allowedSessionIds: Array.from(
        new Set([
          ...allKnownProjects.flatMap((project) => project.sessions.map((session) => session.id)),
          ...sessionIds,
        ]),
      ),
      hiddenProjectKeys,
      navigate,
      allKnownProjects,
      projectFilterRequest:
        requestId == null
          ? null
          : {
              projectKey: 'local:/repo-a',
              projectName: 'Repo A',
              sessionIds,
              requestId,
            },
    }),
  );
}

function allProjectsOption(): HTMLButtonElement {
  return screen.getByRole('button', {
    name: 'ccAgent.search.filter.allProjects',
  }) as HTMLButtonElement;
}

beforeEach(() => {
  Object.defineProperty(window, 'electronAPI', {
    configurable: true,
    value: { platform: 'win32' },
  });
});

afterEach(() => {
  cleanup();
  Reflect.deleteProperty(window, 'electronAPI');
  vi.clearAllMocks();
  vi.useRealTimers();
});

describe('ConversationSearchBox live search', () => {
  it('runs the live prefix pass as keyword-only before the delayed hybrid refresh', () => {
    const keywordMode = source.indexOf("semanticMode: 'keyword'");
    const hybridMode = source.indexOf("semanticMode: 'hybrid'");

    expect(source).toContain('SEMANTIC_SEARCH_DEBOUNCE_MS');
    expect(keywordMode).toBeGreaterThan(-1);
    expect(hybridMode).toBeGreaterThan(keywordMode);
  });


  it('opens with a locked project filter and searches only that project at runtime', async () => {
    vi.mocked(searchConversations).mockResolvedValue({
      query: 'needle',
      results: [],
      vectorUsed: false,
      vectorSkipReason: null,
      poolCapped: false,
    });

    renderSearchBox({ requestId: 1 });

    await screen.findByTestId('conversation-search-popover');
    expect(allProjectsOption().disabled).toBe(true);
    expect(
      screen
        .getAllByRole('button', { name: /Repo A/ })
        .some((button) => (button as HTMLButtonElement).disabled),
    ).toBe(true);

    fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {
      target: { value: 'needle' },
    });

    await waitFor(() => {
      expect(searchConversations).toHaveBeenCalledWith(
        expect.objectContaining({
          query: 'needle',
          semanticMode: 'keyword',
          filters: expect.objectContaining({
            sessionIds: ['session-a1', 'session-a2'],
          }),
        }),
        expect.objectContaining({
          origins: [
            expect.objectContaining({
              kind: 'local',
              sessionIds: ['session-a1', 'session-a2'],
            }),
          ],
        }),
      );
    }, { timeout: SEARCH_WAIT_TIMEOUT_MS });
  });

  it('falls back to the project menu session IDs before the all-project index is loaded', async () => {
    vi.mocked(searchConversations).mockResolvedValue({
      query: 'needle',
      results: [],
      vectorUsed: false,
      vectorSkipReason: null,
      poolCapped: false,
    });

    renderSearchBox({
      requestId: 1,
      allKnownProjects: [],
      sessionIds: ['visible-session-a1', 'visible-session-a2'],
    });

    await screen.findByTestId('conversation-search-popover');

    fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {
      target: { value: 'needle' },
    });

    await waitFor(() => {
      expect(searchConversations).toHaveBeenCalledWith(
        expect.objectContaining({
          query: 'needle',
          semanticMode: 'keyword',
          filters: expect.objectContaining({
            sessionIds: ['visible-session-a1', 'visible-session-a2'],
          }),
        }),
        expect.anything(),
      );
    }, { timeout: SEARCH_WAIT_TIMEOUT_MS });
  });

  it('prunes hidden projects from a normal rail project filter', async () => {
    const view = renderSearchBox();
    fireEvent.click(screen.getByLabelText('ccAgent.search.open'));
    await screen.findByTestId('conversation-search-popover');

    fireEvent.click(screen.getByText('Repo A').closest('button') as HTMLButtonElement);
    fireEvent.click(screen.getByText('Repo B').closest('button') as HTMLButtonElement);
    expect(screen.getByText('2 projects')).toBeTruthy();

    view.rerender(
      createElement(ConversationSearchBox, {
        navigate,
        allKnownProjects: projects.slice(1),
        allowedSessionIds: ['session-b1'],
        hiddenProjectKeys: new Set(['local:/repo-a']),
        projectFilterRequest: null,
      }),
    );

    await waitFor(() => expect(screen.getByText('1 projects')).toBeTruthy());

    view.rerender(
      createElement(ConversationSearchBox, {
        navigate,
        allKnownProjects: [],
        allowedSessionIds: [],
        hiddenProjectKeys: new Set(['local:/repo-a', 'local:/repo-b']),
        projectFilterRequest: null,
      }),
    );

    await waitFor(() => {
      expect(screen.getByLabelText('filter').getAttribute('aria-pressed')).toBe('false');
    });
  });

  it('keeps an equivalent Windows project selected when its visible key casing changes', async () => {
    vi.mocked(searchConversations).mockResolvedValue({
      query: 'needle',
      results: [],
      vectorUsed: false,
      vectorSkipReason: null,
      poolCapped: false,
    });
    const windowsProject = {
      ...projects[0],
      projectKey: 'local:C:/Repo-A',
      workingDir: 'C:/Repo-A',
      displayName: 'Windows Repo',
    };
    const recasedWindowsProject = {
      ...windowsProject,
      projectKey: 'local:c:/repo-a',
      workingDir: 'c:/repo-a',
    };
    const view = renderSearchBox({ allKnownProjects: [windowsProject], sessionIds: [] });
    fireEvent.click(screen.getByLabelText('ccAgent.search.open'));
    await screen.findByTestId('conversation-search-popover');
    fireEvent.click(screen.getByText('Windows Repo').closest('button') as HTMLButtonElement);
    expect(screen.getByText('1 projects')).toBeTruthy();

    view.rerender(
      createElement(ConversationSearchBox, {
        navigate,
        allKnownProjects: [recasedWindowsProject],
        allowedSessionIds: ['session-a1', 'session-a2'],
        hiddenProjectKeys,
        projectFilterRequest: null,
      }),
    );

    await waitFor(() => {
      expect(screen.getByLabelText('filter').getAttribute('aria-pressed')).toBe('true');
      expect(screen.getByText('1 projects')).toBeTruthy();
    });

    const recasedProjectButton = screen
      .getByText('Windows Repo')
      .closest('button') as HTMLButtonElement;
    expect(recasedProjectButton.querySelector('.lucide-check')).not.toBeNull();

    fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {
      target: { value: 'needle' },
    });
    await waitFor(() => {
      expect(searchConversations).toHaveBeenCalledWith(
        expect.objectContaining({
          semanticMode: 'keyword',
          filters: expect.objectContaining({
            sessionIds: ['session-a1', 'session-a2'],
          }),
        }),
        expect.objectContaining({
          origins: [
            expect.objectContaining({
              kind: 'local',
              sessionIds: ['session-a1', 'session-a2'],
            }),
          ],
        }),
      );
    }, { timeout: SEARCH_WAIT_TIMEOUT_MS });

    fireEvent.click(recasedProjectButton);
    await waitFor(() => {
      expect(screen.getByLabelText('filter').getAttribute('aria-pressed')).toBe('false');
      expect(screen.queryByText('2 projects')).toBeNull();
    });
  });

  it('clears a locked Windows project when the hidden key uses different casing', async () => {
    const windowsProject = {
      ...projects[0],
      projectKey: 'local:C:/Repo-A',
      workingDir: 'C:/Repo-A',
      displayName: 'Windows Repo',
    };
    const view = render(
      createElement(ConversationSearchBox, {
        navigate,
        allKnownProjects: [windowsProject],
        allowedSessionIds: ['session-a1', 'session-a2'],
        hiddenProjectKeys,
        projectFilterRequest: {
          projectKey: windowsProject.projectKey,
          projectName: windowsProject.displayName,
          sessionIds: ['session-a1', 'session-a2'],
          requestId: 1,
        },
      }),
    );
    await screen.findByTestId('conversation-search-popover');
    expect(allProjectsOption().disabled).toBe(true);

    view.rerender(
      createElement(ConversationSearchBox, {
        navigate,
        allKnownProjects: [],
        allowedSessionIds: [],
        hiddenProjectKeys: new Set(['local:c:/repo-a']),
        projectFilterRequest: null,
      }),
    );

    await waitFor(() => expect(allProjectsOption().disabled).toBe(false));
  });

  // 搜索结果行是「列表之外」的第二个标题出口:本 PR 早前只投影了侧边栏 / 会话头 / tab,
  // 结果行仍渲染原始 title,于是列表写「未命名任务」、搜索结果写 "New Maker"。
  // 匹配串(main 算下标)与渲染串(这里)必须是同一个 conversationSearchTitle 的结果。
  it('未起名会话在结果行里显示兜底文案,并把 unnamedLabel 带进请求', async () => {
    vi.mocked(searchConversations).mockResolvedValue({
      query: 'needle',
      results: [
        {
          session: {
            id: 'session-draft',
            // main 返回的 summary 仍是**原始存储值**(投影只发生在渲染这一刻)。
            title: 'New Maker',
            workingDir: '/repo-a',
            workspaceKind: 'project',
            agentKind: 'cc',
            status: 'active',
            userSendAt: null,
            updatedAt: '2026-06-14T00:00:00.000Z',
            createdAt: '2026-06-14T00:00:00.000Z',
            _count: { messages: 2 },
          },
          matchKind: 'title',
          titleMatchIndices: [],
          titleScore: 1,
          contentHit: null,
          contentHits: [],
          rankScore: 1,
        },
      ],
      vectorUsed: false,
      vectorSkipReason: null,
      poolCapped: false,
    });

    renderSearchBox({ 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({ unnamedLabel: 'ccAgent.common.unnamedSession' }),
        expect.anything(),
      );
    }, { timeout: SEARCH_WAIT_TIMEOUT_MS });

    // mock 的 t 对未识别 key 原样返回 key,所以兜底文案就是这个 key 串。
    await waitFor(() => {
      expect(screen.getAllByText('ccAgent.common.unnamedSession').length).toBeGreaterThan(0);
    }, { timeout: SEARCH_WAIT_TIMEOUT_MS });
    expect(screen.queryByText('New Maker')).toBeNull();
  });

  it('reapplies a same-project menu request when only requestId changes', async () => {
    const view = renderSearchBox({ requestId: 1 });

    await screen.findByTestId('conversation-search-popover');
    expect(allProjectsOption().disabled).toBe(true);

    fireEvent.click(screen.getByLabelText('ccAgent.search.open'));
    await waitFor(() => expect(screen.queryByTestId('conversation-search-popover')).toBeNull());

    fireEvent.click(screen.getByLabelText('ccAgent.search.open'));
    await screen.findByTestId('conversation-search-popover');
    expect(allProjectsOption().disabled).toBe(false);

    view.rerender(
      createElement(ConversationSearchBox, {
        navigate,
        allKnownProjects: projects,
        allowedSessionIds: projects.flatMap((project) =>
          project.sessions.map((session) => session.id),
        ),
        hiddenProjectKeys,
        projectFilterRequest: {
          projectKey: 'local:/repo-a',
          projectName: 'Repo A',
          sessionIds: ['session-a1', 'session-a2'],
          requestId: 2,
        },
      }),
    );

    await waitFor(() => expect(allProjectsOption().disabled).toBe(true));
  });

  it('routes the project menu search action to the shared conversation search', () => {
    expect(projectNodeSource).toContain('onOpenConversationSearch(project);');
    expect(projectNodeSource).not.toContain('useSessionSearch');
    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/,
    );
  });
});

// Explicit search opens the exact ordinary task regardless of companion role;
// the selected message anchor survives even without a loaded roster. Unit tier.
it.each(['canonical', 'history', 'channel'] as const)('opens %s companion search results without the loaded roster', async role => {
  const hit = { messageId: 'message', messageClientId: 'client', role: 'assistant' as const,
    createdAt: '2026-10-20T00:00:00Z', snippet: null, preview: 'needle reply', score: 1, ftsRank: 1, vectorRank: null };
  vi.mocked(searchConversations).mockResolvedValue({ query: 'needle', results: [{
    session: { id: 'chat', title: 'needle thread', workingDir: null, workspaceKind: 'dialogue',
      agentKind: 'pi', status: role === 'history' ? 'archived' : 'active', source: 'bot',
      userSendAt: null, updatedAt: '2026-10-20T00:00:00Z', createdAt: '2026-10-20T00:00:00Z', _count: { messages: 1 },
      companion: { id: 'bot', name: 'Melody', role, readOnly: role !== 'canonical' } },
    matchKind: 'content', titleMatchIndices: [], titleScore: null, contentHit: hit, contentHits: [hit], rankScore: 1,
  }], vectorUsed: false, vectorSkipReason: null, poolCapped: false });
  renderSearchBox();
  fireEvent.click(screen.getByLabelText('ccAgent.search.open'));
  fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), { target: { value: 'needle' } });
  const result = await screen.findByRole('button', { name: /needle thread/ });
  expect(result.textContent).toContain('Melody');
  fireEvent.click(result);
  await waitFor(() => expect(navigate).toHaveBeenCalledWith(
    '/cc-agent/chat',
    { state: { searchJump: { kind: 'conversation-search', sessionId: 'chat', messageId: 'message', messageClientId: 'client' } } },
  ));
});