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。

fix(desktop): 为“对话”分组提供专属菜单 #6575

DavidShen18c9d897bd5e
diff --git a/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx b/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx
index 0bb7271e9e..dacf883e33 100644
--- a/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
-import type { ReactNode } from 'react';
+import { useState, type ReactNode } from 'react';
import Sortable, { type SortableEvent } from 'sortablejs';
-import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { act, cleanup, createEvent, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getStartingSessionIds, markSessionStarting, resetSessionStartingStoreForTests, useStartingSessionIds } from '@/lib/sessionStartingStore';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
@@ -12,12 +12,15 @@ import {
clearRemoteSessionActivity,
} from '@/features/device-link/remoteSessionActivityStore';
import { ProjectsSection, type ProjectsSectionProps } from '../features/cc-agent/sidebar/sections/ProjectsSection';
+import { useConversationSearch } from '../features/cc-agent/sidebar/ConversationSearchBox';
+import { SidebarInlineSearch } from '../features/cc-agent/sidebar/SidebarInlineSearch';
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/components/ui/tooltip', () => ({ Tip: ({ children }: { children: ReactNode }) => children }));
vi.mock('@/features/device-link/useMachineSwitcher', () => ({ useEffectiveSelectedMachineId: () => 'all' }));
vi.mock('@/hooks/useReducedMotion', () => ({ useReducedMotion: () => true }));
vi.mock('@/hooks/useSidebarCardMode', () => ({ useSidebarMainViewMode: () => ({ mode: 'text' }) }));
+vi.mock('@cindy/maker-shared/cindy-make-feature', () => ({ CINDY_MAKE_ENABLED: true }));
vi.mock('../features/cc-agent/hooks/useRemoteHostProjectOrders', () => ({
projectOrderWriteScopeForSelection: () => ({ kind: 'viewer' }),
useLocalHostProjectOrder: () => ({ snapshot: { manualProjectOrder: [] } }),
@@ -64,6 +67,7 @@ function props(groupDevice: boolean): ProjectsSectionProps {
onCollapseAll: vi.fn(), onExpandAll: vi.fn(), onCreateInProject: vi.fn(), onOpenConversationSearch: vi.fn(),
onOpenInExplorer: vi.fn(), onLinkCodexProject: vi.fn(), linkingCodexProject: null, onBrowseFiles: vi.fn(),
onArchiveAll: vi.fn(), onCreateDialogue: vi.fn(),
+ onSearchDialogues: vi.fn(), onArchiveAllDialogues: vi.fn(),
};
}
@@ -84,6 +88,164 @@ function activity(phase: typeof phases[number]) {
applyRemoteSessionActivity('remote', { sessionId: 'lit', phase, attention: true, compactDetail: '' });
}
+// Issue #6575: render real ProjectsSection headers and observe the contextmenu
+// boundary that opens the ancestor's organize menu. Existing lamp/drag tests do
+// not right-click headers. Minimal regression input: one grouped dialogue and a
+// bubbling, cancelable contextmenu event. Reuse this unit fixture to cover both
+// device layouts, shared Bot/Make headers and the real ProjectNode menu.
+// Standalone: 6.16s including pnpm (Vitest 4.25s, 2.36s collection); reuses
+// the existing component fixture without another jsdom file or module resets.
+describe('Sidebar group context menus', () => {
+ // Issue #6575 P1 / DESIGN §14.2: the actual header is distinct from Radix's
+ // positioning anchor. Existing key tests dispatched to an unfocused header,
+ // hiding the lost focus. Unit: real menu opened by either keyboard shortcut.
+ it.each(['ContextMenu', 'F10'])('returns focus to the dialogue header after %s then Escape', async (key) => {
+ const p = props(false);
+ p.bots = [];
+ p.dialogues = [{ id: 'dialogue', title: 'Dialogue task', status: 'active', workspaceKind: 'dialogue' } as Session];
+ render(<ProjectsSection {...p} />);
+ const header = screen.getByText('ccAgent.sidebar.dialogues').closest<HTMLElement>('[role="button"]')!;
+ header.focus();
+ fireEvent.keyDown(header, { key, shiftKey: key === 'F10' });
+ const menu = await screen.findByRole('menu');
+ fireEvent.keyDown(menu, { key: 'Escape' });
+ // Radix schedules close-auto-focus after its focus scope unmounts.
+ await act(async () => { await new Promise<void>((resolve) => setTimeout(resolve, 0)); });
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(document.activeElement).toBe(header);
+ fireEvent.keyDown(document.activeElement!, { key: 'Enter' });
+ expect(header.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.keyDown(document.activeElement!, { key: ' ' });
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('keeps focus in the search field opened by a dialogue menu action', async () => {
+ const p = props(false);
+ p.bots = [];
+ p.dialogues = [{ id: 'dialogue', title: 'Dialogue task', status: 'active', workspaceKind: 'dialogue' } as Session];
+ function SidebarWithSearch() {
+ const [openSignal, setOpenSignal] = useState(0);
+ const search = useConversationSearch({ enabled: true, navigate: vi.fn(), allKnownProjects: [] });
+ return <>
+ <ProjectsSection {...p} onSearchDialogues={() => setOpenSignal((value) => value + 1)} />
+ <SidebarInlineSearch search={search} allKnownProjects={[]} openSignal={openSignal} />
+ </>;
+ }
+ render(<SidebarWithSearch />);
+ const header = screen.getByText('ccAgent.sidebar.dialogues').closest<HTMLElement>('[role="button"]')!;
+ header.focus();
+ fireEvent.keyDown(header, { key: 'ContextMenu' });
+ const menu = await screen.findByRole('menu');
+ fireEvent.click(within(menu).getByText('ccAgent.sidebar.dialogueAction.search'));
+ await act(async () => { await new Promise<void>((resolve) => setTimeout(resolve, 0)); });
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'ccAgent.search.placeholder' }));
+ });
+
+ // The dedicated menu must act on the full group, including folded rows, and
+ // never expose project actions or silently archive a local subset of a mixed group.
+ it.each(['active', 'archived'] as const)('offers scoped search and bulk %s actions for local dialogues', async (status) => {
+ const p = props(false);
+ p.bots = [];
+ p.filter.status = status;
+ p.dialogues = ['first', 'folded'].map((id) => ({
+ id, title: id, status, workspaceKind: 'dialogue', pinnedAt: null,
+ createdAt: '2026-09-03', updatedAt: '2026-09-03',
+ } as Session));
+ render(<ProjectsSection {...p} />);
+ const header = screen.getByText('ccAgent.sidebar.dialogues').closest('[role="button"]')!;
+ expect(screen.queryByTestId('row-folded')).toBeNull();
+ fireEvent.contextMenu(header);
+ let menu = await screen.findByRole('menu');
+ expect(within(menu).getAllByRole('menuitem')).toHaveLength(2);
+ fireEvent.click(within(menu).getByText('ccAgent.sidebar.dialogueAction.search'));
+ expect(p.onSearchDialogues).toHaveBeenCalledWith(p.dialogues);
+ fireEvent.contextMenu(header);
+ menu = await screen.findByRole('menu');
+ fireEvent.click(within(menu).getByText(status === 'archived'
+ ? 'ccAgent.sidebar.dialogueAction.restoreAll'
+ : 'ccAgent.sidebar.projectAction.archivedAll'));
+ expect(p.onArchiveAllDialogues).toHaveBeenCalledWith(p.dialogues);
+ });
+
+ it.each([false, true])('disables bulk actions when a dialogue group contains remote tasks, mixed %s', async (mixed) => {
+ const p = props(false);
+ p.dialogues = [{ ...p.bots![0].sessions[0], id: 'remote-dialogue' }];
+ p.bots = [];
+ if (mixed) p.dialogues.push({ ...p.dialogues[0], id: 'local-dialogue', deviceLinkDeviceId: undefined });
+ render(<ProjectsSection {...p} />);
+ fireEvent.contextMenu(screen.getByText('ccAgent.sidebar.dialogues').closest('[role="button"]')!);
+ const menu = await screen.findByRole('menu');
+ const archive = within(menu).getByRole('menuitem', { name: /ccAgent.sidebar.projectAction.archivedAll/ });
+ expect(archive.getAttribute('aria-disabled')).toBe('true');
+ expect(within(menu).getByText('ccAgent.sidebar.dialogueAction.remoteBulkUnavailable')).toBeTruthy();
+ fireEvent.click(archive);
+ expect(p.onArchiveAllDialogues).not.toHaveBeenCalled();
+ fireEvent.click(within(menu).getByText('ccAgent.sidebar.dialogueAction.search'));
+ expect(p.onSearchDialogues).toHaveBeenCalledWith(p.dialogues);
+ });
+
+ it.each([false, true])('contains dialogue right-clicks and preserves its controls, device grouping %s', async (groupDevice) => {
+ const p = props(groupDevice);
+ p.dialogues = [{ ...p.bots![0].sessions[0], id: 'dialogue', title: 'Dialogue task' }];
+ const onSidebarContextMenu = vi.fn();
+ render(<div onContextMenu={onSidebarContextMenu}><ProjectsSection {...p} /></div>);
+ const header = screen.getByText('ccAgent.sidebar.dialogues').closest<HTMLElement>('[role="button"]')!;
+ const event = createEvent.contextMenu(header);
+ fireEvent(header, event);
+ expect(event.defaultPrevented).toBe(true);
+ expect(onSidebarContextMenu).not.toHaveBeenCalled();
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+ fireEvent.keyDown(await screen.findByRole('menu'), { key: 'Escape' });
+
+ fireEvent.click(header);
+ expect(header.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.keyDown(header, { key: 'Enter' });
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+ fireEvent.keyDown(header, { key: ' ' });
+ expect(header.getAttribute('aria-expanded')).toBe('false');
+
+ const create = within(header).getByRole('button', { name: 'ccAgent.sidebar.newDialogue' });
+ fireEvent.contextMenu(create);
+ expect(onSidebarContextMenu).not.toHaveBeenCalled();
+ fireEvent.click(create);
+ expect(p.onCreateDialogue).toHaveBeenCalledWith(
+ groupDevice ? { deviceId: 'remote', deviceName: 'Remote device' } : undefined,
+ );
+ expect(header.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('preserves shared Bot/Make headers, blank-area events and the project menu', async () => {
+ const p = props(false);
+ p.dialogues = [{ ...p.bots![0].sessions[0], id: 'make', source: 'cindy-make' }];
+ p.projects = [{
+ projectKey: 'local:/Project', workingDir: '/Project', displayName: 'Project',
+ scope: 'local', sessions: [], segments: 1, latestActivityAt: '2026-09-03T00:00:00Z',
+ remoteHostId: null, deviceLinkDeviceId: null,
+ deviceLinkDeviceName: null, deviceLinkConnectionStatus: null,
+ }];
+ p.allKnownProjects = p.projects;
+ p.allProjectKeysForOrder = p.projects.map((project) => project.projectKey);
+ const onSidebarContextMenu = vi.fn();
+ render(<div onContextMenu={onSidebarContextMenu}>
+ <ProjectsSection {...p} />
+ <span>Sidebar blank area</span>
+ </div>);
+ for (const title of ['Demo Bot', 'settings.cindyMake.title']) {
+ const header = screen.getByText(title).closest<HTMLElement>('[role="button"]')!;
+ const event = createEvent.contextMenu(header);
+ fireEvent(header, event);
+ expect(event.defaultPrevented).toBe(false);
+ }
+ fireEvent.contextMenu(screen.getByText('Sidebar blank area'));
+ expect(onSidebarContextMenu).toHaveBeenCalledTimes(3);
+
+ fireEvent.contextMenu(screen.getByText('Project').closest('[data-project-header]')!);
+ expect(await screen.findByRole('menu')).toBeTruthy();
+ expect(onSidebarContextMenu).toHaveBeenCalledTimes(3);
+ });
+});
+
// PR #6196 / manualProjectSortDrag: the historical handle/filter overlap made
// every project header reject drag start. Existing lamp tests use activity order,
// so they never mount SortableList. Reuse this real ProjectsSection/ProjectNode
diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.ts
index ee5e4d7605..1bb87e65e3 100644
--- a/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.ts
+++ b/apps/desktop/src/renderer/__tests__/conversationSearchLifecycle.test.ts
@@ -5,6 +5,13 @@ import { useConversationSearch } from '@/features/cc-agent/sidebar/ConversationS
import { searchConversations } from '@/lib/conversationSearchService';
import type { ConversationSearchResponse } from '../../shared/conversationSearch';
import type { ProjectNode } from '@/features/cc-agent/lib/projectGrouping';
+import type { Session } from '@/lib/ccAgent.types';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import {
+ consumeConversationSearchRequest,
+ requestConversationSearch,
+ useConversationSearchRequest,
+} from '@/state/conversationSearchRequest';
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/lib/conversationSearchService', () => ({ searchConversations: vi.fn() }));
@@ -81,10 +88,63 @@ beforeEach(() => {
});
afterEach(() => {
cleanup();
+ consumeConversationSearchRequest();
+ remoteProjectsStore.removeDevice('remote');
vi.useRealTimers();
Reflect.deleteProperty(window, 'electronAPI');
});
+// Dedicated dialogue menu: the real request store and search hook must send
+// explicit group IDs to the correct local/remote origins. Existing lifecycle
+// tests only cover global/project searches. Minimal input: one local and one
+// remote group member without a project identity. Unit, fake timers.
+// Standalone Vitest: 2.79s (1.86s collection).
+describe('dialogue group search scope', () => {
+ it('keeps mixed group searches scoped through filter reset, then unlocks back to global search', async () => {
+ remoteProjectsStore.setDeviceSessions('remote', 'Mac', [{ id: 'remote-dialogue' } as Session]);
+ vi.mocked(searchConversations).mockResolvedValue(page());
+ const view = renderHook(() => useConversationSearch({
+ enabled: true, navigate: vi.fn(), allKnownProjects: [], searchDevices: devices,
+ projectFilterRequest: useConversationSearchRequest(),
+ }));
+ act(() => requestConversationSearch({
+ kind: 'session-group', groupName: 'Chat',
+ sessionIds: ['remote-dialogue', 'local-dialogue', 'local-dialogue'],
+ }));
+ expect(view.result.current.lockedProjectKey).toBeNull();
+ expect(view.result.current.lockedSessionGroupName).toBe('Chat');
+ act(() => view.result.current.resetFilters());
+ act(() => view.result.current.setQuery('needle'));
+ await act(async () => { await vi.advanceTimersByTimeAsync(900); });
+ const [request, options] = vi.mocked(searchConversations).mock.calls[0];
+ expect(request.filters?.sessionIds).toEqual(['local-dialogue', 'remote-dialogue']);
+ expect(options?.origins).toMatchObject([
+ { kind: 'local', sessionIds: ['local-dialogue'] },
+ { kind: 'remote', deviceId: 'remote', deviceName: 'Mac', connected: true, sessionIds: ['remote-dialogue'] },
+ ]);
+ act(() => view.result.current.clearLock());
+ await act(async () => { await vi.advanceTimersByTimeAsync(900); });
+ expect(vi.mocked(searchConversations).mock.lastCall?.[0].filters?.sessionIds).toBeNull();
+ expect(view.result.current.lockedSessionGroupName).toBeNull();
+ });
+
+ it('does not expand an empty group into a global search and releases its lock when the machine changes', async () => {
+ vi.mocked(searchConversations).mockResolvedValue(page());
+ const view = renderHook(({ machineSelection }) => useConversationSearch({
+ enabled: true, navigate: vi.fn(), allKnownProjects: [], searchDevices: devices,
+ machineSelection, projectFilterRequest: useConversationSearchRequest(),
+ }), { initialProps: { machineSelection: 'all' as 'all' | string[] } });
+ act(() => requestConversationSearch({ kind: 'session-group', groupName: 'Chat', sessionIds: [] }));
+ act(() => view.result.current.setQuery('needle'));
+ await act(async () => { await vi.advanceTimersByTimeAsync(900); });
+ expect(vi.mocked(searchConversations).mock.lastCall?.[0].filters?.sessionIds).toEqual([]);
+ expect(vi.mocked(searchConversations).mock.lastCall?.[1]?.origins).toEqual([]);
+ view.rerender({ machineSelection: ['remote'] });
+ expect(view.result.current.lockedSessionGroupName).toBeNull();
+ expect(view.result.current.query).toBe('');
+ });
+});
+
describe('conversation search request lifecycle', () => {
it.each(['keyword', 'hybrid'])(
'merges both pages when %s finishes first after both start',
diff --git a/apps/desktop/src/renderer/__tests__/onlineDeviceHeaders.test.tsx b/apps/desktop/src/renderer/__tests__/onlineDeviceHeaders.test.tsx
index a39cf20e9a..58e34b48be 100644
--- a/apps/desktop/src/renderer/__tests__/onlineDeviceHeaders.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/onlineDeviceHeaders.test.tsx
@@ -133,6 +133,8 @@ function props(groupDevice: boolean): ProjectsSectionProps {
linkingCodexProject: null,
onBrowseFiles: vi.fn(),
onArchiveAll: vi.fn(),
+ onSearchDialogues: vi.fn(),
+ onArchiveAllDialogues: vi.fn(),
onCreateDialogue: vi.fn(),
};
}
diff --git a/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx b/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx
new file mode 100644
index 0000000000..2b3321899b
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx
@@ -0,0 +1,189 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useSessionGroupArchive } from '@/features/cc-agent/hooks/useSessionGroupArchive';
+import {
+ projectIdentityKeyForSession,
+ type ProjectNode,
+} from '@/features/cc-agent/lib/projectGrouping';
+import type { FilterStatus } from '@/features/cc-agent/hooks/useSidebarFilter';
+import type { Session } from '@/lib/ccAgent.types';
+import * as sessionService from '@/lib/sessionService';
+import { makerChatStore } from '@/lib/makerChatStore';
+import { emitRefresh } from '@/lib/sessionsBus';
+import { toast } from '@/lib/toast';
+import type { ConfirmOptions } from '@/components/ui/confirm-dialog-provider';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, args?: Record<string, unknown>) =>
+ args ? `${key}:${JSON.stringify(args)}` : key,
+ }),
+}));
+vi.mock('@/lib/sessionService', () => ({ setStatus: vi.fn(), restoreIfArchived: vi.fn() }));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: { closeSessionQuery: vi.fn(), purgeSession: vi.fn() },
+}));
+vi.mock('@/lib/composerDraftStore', () => ({ discardDraft: vi.fn() }));
+vi.mock('@/lib/worktreeRemovalWarning', () => ({
+ countDirtyWorktreesForRemoval: vi.fn(async () => 0),
+}));
+vi.mock('@/lib/sessionsBus', () => ({ emitRefresh: vi.fn() }));
+vi.mock('@/lib/toast', () => ({ toast: { warning: vi.fn(), success: vi.fn(), error: vi.fn() } }));
+
+// Value: invoke the production group lifecycle and inspect persisted writes,
+// confirmation scope and cleanup. The existing candidate-selector unit tests
+// do not exercise this orchestration. Rule: dedicated dialogue menu must not
+// affect project/Bot/Make tasks or a local subset of a remote/mixed group.
+// Minimal input: one eligible member plus pinned/running/foreign records.
+// Tier: unit; in-memory persistence and immediate confirmations, no real waits.
+// Standalone Vitest: 2.53s (1.51s collection).
+function session(id: string, patch: Partial<Session> = {}): Session {
+ return {
+ id,
+ title: id,
+ status: 'active',
+ workspaceKind: 'dialogue',
+ pinnedAt: null,
+ workingDir: `/dialogues/${id}`,
+ ...patch,
+ } as Session;
+}
+
+function mount(sessions: Session[], status: FilterStatus = 'active') {
+ const writes = new Map(sessions.map((s) => [s.id, s]));
+ vi.mocked(sessionService.setStatus).mockImplementation(async (id, nextStatus) => {
+ const updated = { ...writes.get(id)!, status: nextStatus };
+ writes.set(id, updated);
+ return updated;
+ });
+ const options = {
+ sessions,
+ status,
+ runningSessionIds: new Set(['running']),
+ viewedSessionId: 'eligible',
+ confirmDialog: vi.fn<(options: ConfirmOptions) => Promise<boolean>>(async () => true),
+ refreshSessions: vi.fn(async () => undefined),
+ patchLocal: vi.fn(),
+ navigate: vi.fn(),
+ };
+ const view = renderHook(() => useSessionGroupArchive(options));
+ return { ...view, options, writes };
+}
+
+beforeEach(() => vi.clearAllMocks());
+afterEach(cleanup);
+
+describe('session group bulk lifecycle', () => {
+ it('archives only eligible group members, with dialogue confirmation and normal cleanup', async () => {
+ const members = [
+ session('eligible'),
+ session('running'),
+ session('pinned', { pinnedAt: '2026-10-21' }),
+ session('archived', { status: 'archived' }),
+ ];
+ const foreign = [
+ session('project', { workspaceKind: 'project' }),
+ session('bot'),
+ session('make'),
+ ];
+ const view = mount([...members, ...foreign]);
+ await act(async () => {
+ await view.result.current({ kind: 'dialogue', sessions: members });
+ });
+ expect(view.writes.get('eligible')?.status).toBe('archived');
+ expect(
+ [...view.writes.values()].filter((s) => s.status === 'archived').map((s) => s.id),
+ ).toEqual(['eligible', 'archived']);
+ const description = view.options.confirmDialog.mock.calls[0][0].description;
+ expect(description).toContain('ccAgent.sidebar.dialogueArchiveAll.descriptionWithSkip');
+ expect(description).toContain('"count":1');
+ expect(description).toContain('skipPinned');
+ expect(description).toContain('skipRunning');
+ expect(makerChatStore.closeSessionQuery).toHaveBeenCalledExactlyOnceWith('eligible');
+ expect(makerChatStore.purgeSession).toHaveBeenCalledExactlyOnceWith('eligible');
+ expect(view.options.navigate).toHaveBeenCalledWith('/cc-agent');
+ });
+
+ it('leaves records and active queries untouched when the confirmation is cancelled', async () => {
+ const members = [session('eligible')];
+ const view = mount(members);
+ view.options.confirmDialog.mockResolvedValue(false);
+ await act(async () => {
+ await view.result.current({ kind: 'dialogue', sessions: members });
+ });
+ expect(view.writes.get('eligible')?.status).toBe('active');
+ expect(makerChatStore.closeSessionQuery).not.toHaveBeenCalled();
+ expect(view.options.refreshSessions).not.toHaveBeenCalled();
+ });
+
+ it('restores archived members with identity checks and reports partial failures without archiving active tasks', async () => {
+ const members = [
+ session('eligible'),
+ session('restored', { status: 'archived' }),
+ session('moved', { status: 'archived' }),
+ session('failed', { status: 'archived' }),
+ ];
+ const view = mount(members, 'archived');
+ vi.mocked(sessionService.restoreIfArchived)
+ .mockResolvedValueOnce({ ...members[1], status: 'active' })
+ .mockResolvedValueOnce(null)
+ .mockRejectedValueOnce(new Error('write failed'));
+ await act(async () => {
+ await view.result.current({ kind: 'dialogue', sessions: members });
+ });
+ expect(vi.mocked(sessionService.restoreIfArchived).mock.calls).toEqual(
+ members.slice(1).map((s) => [s.id, s]),
+ );
+ expect(view.options.patchLocal).toHaveBeenCalledExactlyOnceWith('restored', {
+ status: 'active',
+ });
+ expect(view.options.confirmDialog.mock.calls[0][0].description).toContain(
+ 'dialogueRestoreAll.description',
+ );
+ expect(toast.error).toHaveBeenCalledWith(
+ 'ccAgent.sidebar.unarchiveAll.partialFailure:{"ok":1,"fail":2}',
+ );
+ expect(emitRefresh).toHaveBeenCalledOnce();
+ expect(sessionService.setStatus).not.toHaveBeenCalled();
+ expect(makerChatStore.closeSessionQuery).not.toHaveBeenCalled();
+ });
+
+ it.each(['active', 'archived'] as const)(
+ 'rejects remote/mixed groups before any %s writes even when invoked directly',
+ async (status) => {
+ const members = [
+ session('eligible', { status }),
+ session('remote', { status, deviceLinkDeviceId: 'remote' }),
+ ];
+ const view = mount(members, status);
+ await act(async () => {
+ await view.result.current({ kind: 'dialogue', sessions: members });
+ });
+ expect(view.options.confirmDialog).not.toHaveBeenCalled();
+ expect(sessionService.setStatus).not.toHaveBeenCalled();
+ expect(sessionService.restoreIfArchived).not.toHaveBeenCalled();
+ expect(toast.warning).toHaveBeenCalledWith(
+ 'ccAgent.sidebar.dialogueAction.remoteBulkUnavailable',
+ );
+ },
+ );
+
+ it('retains project scope and project wording through the shared lifecycle', async () => {
+ const projectTask = session('project', { workspaceKind: 'project', workingDir: '/repo' });
+ const view = mount([projectTask, session('dialogue')]);
+ const project = {
+ projectKey: projectIdentityKeyForSession(projectTask),
+ sessions: [projectTask],
+ } as ProjectNode;
+ await act(async () => {
+ await view.result.current({ kind: 'project', project });
+ });
+ expect(view.writes.get('project')?.status).toBe('archived');
+ expect(view.writes.get('dialogue')?.status).toBe('active');
+ expect(view.options.confirmDialog.mock.calls[0][0].description).toContain(
+ 'ccAgent.sidebar.archiveAll.description',
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx b/apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx
index 3e98683542..373171923b 100644
--- a/apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx
+++ b/apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx
@@ -26,8 +26,12 @@ export interface TeammateSearchMatch {
* 侧栏总搜索里的伙伴 / 群聊命中(2026-10-13:伙伴段不再有独立搜索框)。
* 本机伙伴按名字、简介、技能匹配,含已隐藏、不含已停止;远程伙伴按名字、简介、电脑名;
* 群聊按群名与成员名,含已归档的群(段内不列出,在这里找回)。只读已有的名册投影,不发起额外查询。
+ * 锁定任务分组时不搜索名册,避免组内搜索混入伙伴或群聊。
*/
-export function useTeammateSearchMatches(rawQuery: string): TeammateSearchMatch[] {
+export function useTeammateSearchMatches(
+ rawQuery: string,
+ lockedSessionGroupName: string | null,
+): TeammateSearchMatch[] {
const cloud = useCompanionCloud();
const allBots = useBotProfiles();
const rosterRemoteBots = useRemoteBots();
@@ -37,7 +41,7 @@ export function useTeammateSearchMatches(rawQuery: string): TeammateSearchMatch[
const { groups } = useBotGroupList();
return useMemo(() => {
const query = rawQuery.trim().toLocaleLowerCase();
- if (!query) return [];
+ if (!query || lockedSessionGroupName !== null) return [];
const includes = (...values: Array<string | null | undefined>) =>
values.some((value) => Boolean(value) && value!.toLocaleLowerCase().includes(query));
const local = filterBotRoster(
@@ -73,7 +77,7 @@ export function useTeammateSearchMatches(rawQuery: string): TeammateSearchMatch[
avatar: group.members[0] ?? null,
}));
return [...local, ...remote, ...groupMatches];
- }, [bots, remoteBots, groups, rawQuery]);
+ }, [bots, remoteBots, groups, rawQuery, lockedSessionGroupName]);
}
/** 与会话结果行同几何(rounded-lg、px-3 py-2.5、20px 标记、13 号标题、类型小标签)。 */
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/teammateSearchResults.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/teammateSearchResults.test.tsx
index 1528867e48..be3323e4b5 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/teammateSearchResults.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/teammateSearchResults.test.tsx
@@ -45,9 +45,32 @@ afterEach(() => {
});
const names = (query: string) =>
- renderHook(() => useTeammateSearchMatches(query)).result.current.map((match) => match.name);
+ renderHook(() => useTeammateSearchMatches(query, null)).result.current.map((match) => match.name);
describe('teammates in the sidebar-wide search', () => {
+ // Issue #6575 P1: task-ID filtering did not constrain the leading roster hits.
+ // Existing global-query tests never lock a dialogue group. Unit regression:
+ // one matching local bot, remote bot and group must disappear while locked,
+ // then become navigable again after unlocking through the real hook/results.
+ // Standalone: 3.02s including pnpm (Vitest 1.18s), no module resets.
+ it('excludes teammates and group chats while search is locked to a dialogue group', () => {
+ mocks.profiles = [bot('local', 'Needle local')];
+ mocks.remoteBots = [{ id: 'remote', deviceId: 'mac', deviceName: 'Mac', name: 'Needle remote', description: '' }];
+ mocks.groups = [{ id: 'group', name: 'Needle group', members: [] }];
+ function Results({ groupName }: { groupName: string | null }) {
+ const matches = useTeammateSearchMatches('needle', groupName);
+ return <TeammateSearchResults matches={matches} />;
+ }
+ const view = render(<Results groupName="Chat" />);
+ expect(screen.queryAllByRole('button')).toHaveLength(0);
+ view.rerender(<Results groupName={null} />);
+ expect(screen.getAllByRole('button')).toHaveLength(3);
+ fireEvent.click(screen.getByRole('button', { name: /Needle remote/ }));
+ expect(mocks.navigate).toHaveBeenCalledWith('/bots/remote/mac/remote');
+ view.rerender(<Results groupName="Chat" />);
+ expect(screen.queryAllByRole('button')).toHaveLength(0);
+ });
+
it('matches nothing for an empty query', () => {
expect(names(' ')).toEqual([]);
});
@@ -65,7 +88,7 @@ describe('teammates in the sidebar-wide search', () => {
];
expect(names('旅行')).toEqual(['已完成的旅行']);
expect(names(' PLANNER ')).toEqual(['已完成的旅行']);
- const matches = renderHook(() => useTeammateSearchMatches('旅行')).result.current;
+ const matches = renderHook(() => useTeammateSearchMatches('旅行', null)).result.current;
render(<TeammateSearchResults matches={matches} />);
expect(screen.getByText('bots.archived')).toBeTruthy();
fireEvent.click(screen.getByText('已完成的旅行'));
@@ -81,7 +104,7 @@ describe('teammates in the sidebar-wide search', () => {
mocks.groups = [{ id: 'dissolved', name: '周末出游', archived: true,
dissolvedAt: '2026-10-15T12:00:00Z', members: [{ botId: 'lead', name: 'Trip Planner' }] }];
expect(names('planner')).toEqual(['周末出游']);
- const matches = renderHook(() => useTeammateSearchMatches('出游')).result.current;
+ const matches = renderHook(() => useTeammateSearchMatches('出游', null)).result.current;
render(<TeammateSearchResults matches={matches} />);
fireEvent.click(screen.getByRole('button', { name: /周末出游/ }));
expect(mocks.navigate).toHaveBeenCalledWith('/bots/groups/dissolved');
@@ -96,7 +119,7 @@ describe('teammates in the sidebar-wide search', () => {
it('opens the chosen chat and lets the popover close itself', () => {
const onSelected = vi.fn();
- const { result } = renderHook(() => useTeammateSearchMatches('e'));
+ const { result } = renderHook(() => useTeammateSearchMatches('e', null));
render(<TeammateSearchResults matches={result.current} onSelected={onSelected} />);
fireEvent.click(screen.getByRole('button', { name: /Cloud helper/ }));
@@ -107,7 +130,7 @@ describe('teammates in the sidebar-wide search', () => {
});
it('labels group chats apart from teammates', () => {
- const { result } = renderHook(() => useTeammateSearchMatches('出游'));
+ const { result } = renderHook(() => useTeammateSearchMatches('出游', null));
render(<TeammateSearchResults matches={result.current} />);
fireEvent.click(screen.getByRole('button', { name: /周末出游/ }));
expect(mocks.navigate).toHaveBeenLastCalledWith('/bots/groups/trip');
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index c44d19ab7f..9f10a8b6ed 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -159,10 +159,7 @@ import {
type ProjectNode,
} from './lib/projectGrouping';
import { projectDisplayLabelWithMachine } from './lib/remoteProjectIdentity';
-import {
- projectBulkArchiveActionForStatus,
- selectProjectBulkArchiveCandidates,
-} from './lib/projectBulkArchiveAction';
+import { useSessionGroupArchive } from './hooks/useSessionGroupArchive';
import { sessionActivityMs } from './lib/dateSessionGrouping';
import { matchesSidebarSessionStatus } from './lib/sidebarSessionStatusFilter';
import { observeSidebarTaskChanges } from './lib/sidebarTaskObserver';
@@ -933,8 +930,17 @@ function ExpandedView({
deviceLinkDeviceId: project.deviceLinkDeviceId,
});
}, []);
- // Archived All(右键菜单)走全局 ConfirmDialogProvider —— 与单条 archive 的 inline
- // ConfirmDialog 解耦,避免共用 confirm state 时语义混乱。
+ const handleSearchDialogues = useCallback(
+ (groupSessions: readonly Session[]) => {
+ requestConversationSearch({
+ kind: 'session-group',
+ groupName: t('ccAgent.sidebar.dialogues'),
+ sessionIds: groupSessions.map((session) => session.id),
+ });
+ },
+ [t],
+ );
+ // 批量菜单走全局确认弹窗,与单条操作的 inline ConfirmDialog 解耦。
const { confirm: confirmDialog } = useConfirmDialog();
const handleScheduleDeleted = useCallback(
async ({ disposition, affectedSessionIds }: DeletedScheduleGeneratedSessionResult) => {
@@ -1644,7 +1650,7 @@ function ExpandedView({
// query 非空时同一份顶部导航 sticky 钉住,结果替换下方列表,不再用 overlay 盖输入框。
const { search, openSignal } = useConversationSearchContext();
// 伙伴 / 群聊并入侧栏总搜索,命中排在会话结果之前。
- const teammateMatches = useTeammateSearchMatches(search.trimmed);
+ const teammateMatches = useTeammateSearchMatches(search.trimmed, search.lockedSessionGroupName);
const gcProjectKeys = useMemo(
() => projectUniverse.projects.map((p) => p.projectKey),
[projectUniverse.projects],
@@ -2166,8 +2172,8 @@ function ExpandedView({
* 任意扩展主题天然正确,不需要按主题取色。
*/
/**
- * 空白处右键打开的整理菜单(2026-08-12 用户裁决)。会话行 / 项目行 / 对话组头
- * 都在自己的 onContextMenu 里 stopPropagation,冒泡到滚动容器的必然是空白区域。
+ * 空白处右键打开的整理菜单(2026-08-12 用户裁决)。任务行 / 项目行 / 对话组头
+ * 各自处理菜单,并在自己的 onContextMenu 里 stopPropagation。
*/
const [organizeMenuPos, setOrganizeMenuPos] = useState<{ x: number; y: number } | null>(null);
const handleSidebarBlankContextMenu = useCallback((event: React.MouseEvent) => {
@@ -3509,180 +3515,24 @@ function ExpandedView({
t,
]);
- /* ---- Project 批量归档动作 ----
- * active / all 筛选:归档该 project 下所有可归档的 active session;
- * archived 筛选:恢复该 project 下所有 archived session。
- * 两个方向都逐条写入,单条失败不会阻断其余会话,最后统一 refresh。
- */
+ const archiveSessionGroup = useSessionGroupArchive({
+ sessions,
+ runningSessionIds,
+ status: filter.status,
+ confirmDialog,
+ refreshSessions,
+ patchLocal,
+ viewedSessionId,
+ navigate,
+ });
const handleArchiveAllInProject = useCallback(
- async (project: ProjectNode) => {
- if (isDeviceLinkWriteBlocked(project)) {
- toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
- return;
- }
- const targetProjectKey = project.projectKey;
- const action = projectBulkArchiveActionForStatus(filter.status);
- const belongsToProject = (session: Session): boolean =>
- projectIdentityKeyForSession(session) === targetProjectKey;
-
- // 只对**本地** sessions 归档:device-link 远程会话的运行态不在本渲染进程(runningSessionIds 是
- // 本地 makerChatStore 的),无法像本地那样把「正在运行」的排除掉 —— 批量归档时可能把被控端正在
- // 跑的会话也归档掉。安全起见远程项目的「归档全部」维持 #331 前的本地口径(对纯远程项目即空操作);
- // 要安全支持远程批量归档需被控端侧的「运行态感知批量归档」命令,留作 follow-up。
- // pinned 是用户主动表达 "留住这个会话",archive all 必须排除(跟 running 是两个独立维度)。
- // 既 pinned 又 running 的:归到 pinned 那类(用户意图明确,running 只是临时状态)。
- const { candidates, skippedPinned, skippedRunning } = selectProjectBulkArchiveCandidates(
- sessions,
- action,
- runningSessionIds,
- belongsToProject,
- );
-
- if (action === 'unarchive') {
- if (candidates.length === 0) {
- toast.warning(t('ccAgent.sidebar.unarchiveAll.empty'));
- return;
- }
-
- const ok = await confirmDialog({
- title: t('ccAgent.sidebar.unarchiveAll.title'),
- description: t('ccAgent.sidebar.unarchiveAll.description', { count: candidates.length }),
- confirmText: t('ccAgent.sidebar.unarchiveAll.confirm'),
- cancelText: t('ccAgent.sidebar.unarchiveAll.cancel'),
- });
- if (!ok) return;
-
- const failed: string[] = [];
- for (const session of candidates) {
- try {
- // 确认框是异步边界:由持久层在单条 UPDATE 中同时校验 archived 状态和
- // 原项目身份,避免 get + update 在两次异步调用之间仍可被并发写穿。
- const restored = await sessionService.restoreIfArchived(session.id, session);
- if (!restored) {
- failed.push(session.id);
- continue;
- }
- patchLocal(restored.id, { status: 'active' });
- } catch (err) {
- log.error('[unarchive all]', err);
- failed.push(session.id);
- }
- }
-
- const succeededCount = candidates.length - failed.length;
- await refreshSessions();
- // 批量恢复跨 archived → active 桶,强制刷新其余缓存桶,确保 active / all
- // 视图切换后立即看到恢复结果。
- emitRefresh();
-
- if (failed.length === 0) {
- toast.success(t('ccAgent.sidebar.unarchiveAll.unarchived', { count: succeededCount }));
- } else {
- toast.error(
- t('ccAgent.sidebar.unarchiveAll.partialFailure', {
- ok: succeededCount,
- fail: failed.length,
- }),
- );
- }
- return;
- }
-
- if (candidates.length === 0) {
- if (skippedPinned > 0 && skippedRunning > 0) {
- toast.warning(t('ccAgent.sidebar.archiveAll.allPinnedOrRunning'));
- } else if (skippedPinned > 0) {
- toast.warning(t('ccAgent.sidebar.archiveAll.allPinned'));
- } else if (skippedRunning > 0) {
- toast.warning(t('ccAgent.sidebar.archiveAll.allRunning'));
- } else {
- toast.warning(t('ccAgent.sidebar.archiveAll.empty'));
- }
- return;
- }
-
- const dirtyCount = await countDirtyWorktreesForRemoval(candidates);
-
- const skipNotes: string[] = [];
- if (skippedRunning > 0)
- skipNotes.push(t('ccAgent.sidebar.archiveAll.skipRunning', { count: skippedRunning }));
- if (skippedPinned > 0)
- skipNotes.push(t('ccAgent.sidebar.archiveAll.skipPinned', { count: skippedPinned }));
- const skipSep = t('ccAgent.sidebar.archiveAll.skipSeparator');
- const baseDescription =
- skipNotes.length > 0
- ? t('ccAgent.sidebar.archiveAll.descriptionWithSkip', {
- count: candidates.length,
- skip: skipNotes.join(skipSep),
- })
- : t('ccAgent.sidebar.archiveAll.description', { count: candidates.length });
- const description =
- baseDescription +
- (dirtyCount > 0
- ? ' ' +
- t('ccAgent.sidebar.bulkSelection.confirmArchive.dirtyWorktreeWarning', {
- count: dirtyCount,
- })
- : '');
-
- const ok = await confirmDialog({
- title: t('ccAgent.sidebar.archiveAll.title'),
- description,
- confirmText: t('ccAgent.sidebar.archiveAll.confirm'),
- cancelText: t('ccAgent.sidebar.archiveAll.cancel'),
- });
- if (!ok) return;
-
- // 失败的 id 收集起来,最后统一 toast;其余继续走完,不让一条失败拖累整批。
- const failed: string[] = [];
- for (const s of candidates) {
- // 关掉 SDK subprocess + 清 in-memory state,与单条 archive 行为一致
- makerChatStore.closeSessionQuery(s.id);
- try {
- await sessionService.setStatus(s.id, 'archived');
- // 跨 bucket 同步:见 handleConfirm 同位置注释。
- patchLocal(s.id, { status: 'archived', pinnedAt: null });
- makerChatStore.purgeSession(s.id);
- discardComposerDraft(s.id);
- } catch (err) {
- log.error('[archive all]', err);
- failed.push(s.id);
- }
- }
-
- const failedIds = new Set(failed);
- const succeededIds = new Set(candidates.filter((s) => !failedIds.has(s.id)).map((s) => s.id));
-
- await refreshSessions();
-
- // 当前注视中的 session 被归档了 → 走 /cc-agent 让 CCAgentIndexRedirect
- // 做 Orca-aware 的「选下一条 / 空则跳 new」决策(见 runSessionAction 同位置注释)。
- if (viewedSessionId && succeededIds.has(viewedSessionId)) {
- navigate('/cc-agent');
- }
-
- if (failed.length === 0) {
- toast.success(t('ccAgent.sidebar.archiveAll.archived', { count: succeededIds.size }));
- } else {
- toast.error(
- t('ccAgent.sidebar.archiveAll.partialFailure', {
- ok: succeededIds.size,
- fail: failed.length,
- }),
- );
- }
- },
- [
- sessions,
- runningSessionIds,
- confirmDialog,
- refreshSessions,
- viewedSessionId,
- navigate,
- patchLocal,
- filter.status,
- t,
- ],
+ (project: ProjectNode) => archiveSessionGroup({ kind: 'project', project }),
+ [archiveSessionGroup],
+ );
+ const handleArchiveAllDialogues = useCallback(
+ (groupSessions: readonly Session[]) =>
+ archiveSessionGroup({ kind: 'dialogue', sessions: groupSessions }),
+ [archiveSessionGroup],
);
const bulkActionInProgressLabel = t('ccAgent.sidebar.bulkSelection.actionInProgress');
const bulkArchiveActionLabel = t('ccAgent.sidebar.bulkSelection.archive');
@@ -3808,9 +3658,8 @@ function ExpandedView({
<div
ref={sidebarScrollRef}
className="flex flex-col gap-2 pt-0 pb-4 overflow-y-auto flex-1"
- // 空白处右键 = 打开整理菜单(2026-08-12 用户裁决)。命中会话行 / 项目行 /
- // 对话组头时不接管——那些行有各自的右键菜单,由它们 stopPropagation 后
- // 自行处理;这里只兜「没有任何行响应」的空白区域。
+ // 空白处右键 = 打开整理菜单(2026-08-12 用户裁决)。任务行 / 项目行 /
+ // 对话组头各自处理菜单,由各自的 stopPropagation 阻止这里接管。
onContextMenu={handleSidebarBlankContextMenu}
style={
{
@@ -4036,6 +3885,8 @@ function ExpandedView({
linkingCodexProject={linkingCodexProject}
onBrowseFiles={handleBrowseFiles}
onArchiveAll={handleArchiveAllInProject}
+ onSearchDialogues={handleSearchDialogues}
+ onArchiveAllDialogues={handleArchiveAllDialogues}
remoteDeviceIndex={remoteDeviceIndex}
onCreateDialogue={handleCreateDialogue}
isCreateDialogueDisabled={dialogueCreatePending}
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts
new file mode 100644
index 0000000000..af5150959e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts
@@ -0,0 +1,232 @@
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import type { NavigateFunction } from 'react-router-dom';
+import type { ConfirmOptions } from '@/components/ui/confirm-dialog-provider';
+import type { Session } from '@/lib/ccAgent.types';
+import * as sessionService from '@/lib/sessionService';
+import { makerChatStore } from '@/lib/makerChatStore';
+import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';
+import { countDirtyWorktreesForRemoval } from '@/lib/worktreeRemovalWarning';
+import { emitRefresh } from '@/lib/sessionsBus';
+import { toast } from '@/lib/toast';
+import { createLogger } from '@/lib/logger';
+import { projectIdentityKeyForSession, type ProjectNode } from '../lib/projectGrouping';
+import { isDeviceLinkWriteBlocked } from '../lib/remoteSessionWriteGuard';
+import {
+ projectBulkArchiveActionForStatus,
+ selectProjectBulkArchiveCandidates,
+} from '../lib/projectBulkArchiveAction';
+import type { FilterStatus } from './useSidebarFilter';
+
+const log = createLogger('SessionGroupArchive');
+
+type SessionGroupArchiveScope =
+ { kind: 'project'; project: ProjectNode } | { kind: 'dialogue'; sessions: readonly Session[] };
+
+interface SessionGroupArchiveOptions {
+ sessions: readonly Session[];
+ runningSessionIds: ReadonlySet<string>;
+ status: FilterStatus;
+ confirmDialog: (options: ConfirmOptions) => Promise<boolean>;
+ refreshSessions: () => Promise<unknown>;
+ patchLocal: (id: string, patch: Partial<Session>) => void;
+ viewedSessionId?: string;
+ navigate: NavigateFunction;
+}
+
+/** Shared project/dialogue bulk lifecycle. Scope membership never depends on visible fold limits. */
+export function useSessionGroupArchive({
+ sessions,
+ runningSessionIds,
+ status,
+ confirmDialog,
+ refreshSessions,
+ patchLocal,
+ viewedSessionId,
+ navigate,
+}: SessionGroupArchiveOptions) {
+ const { t } = useTranslation();
+ return useCallback(
+ async (scope: SessionGroupArchiveScope) => {
+ if (
+ scope.kind === 'project'
+ ? isDeviceLinkWriteBlocked(scope.project)
+ : scope.sessions.some((session) => session.deviceLinkDeviceId)
+ ) {
+ toast.warning(
+ t(
+ scope.kind === 'project'
+ ? 'ccAgent.remoteSession.actionsUnavailable'
+ : 'ccAgent.sidebar.dialogueAction.remoteBulkUnavailable',
+ ),
+ );
+ return;
+ }
+ const action = projectBulkArchiveActionForStatus(status);
+ const memberIds =
+ scope.kind === 'dialogue' ? new Set(scope.sessions.map((session) => session.id)) : null;
+ const belongsToGroup = (session: Session): boolean =>
+ scope.kind === 'project'
+ ? projectIdentityKeyForSession(session) === scope.project.projectKey
+ : memberIds!.has(session.id);
+ const archiveCopy = scope.kind === 'project' ? 'archiveAll' : 'dialogueArchiveAll';
+ const restoreCopy = scope.kind === 'project' ? 'unarchiveAll' : 'dialogueRestoreAll';
+
+ // Only local records are written; remote batches require runtime checks on their owning computer.
+ // Both group types share candidate selection, confirmation and lifecycle cleanup.
+ const { candidates, skippedPinned, skippedRunning } = selectProjectBulkArchiveCandidates(
+ sessions,
+ action,
+ runningSessionIds,
+ belongsToGroup,
+ );
+
+ if (action === 'unarchive') {
+ if (candidates.length === 0) {
+ toast.warning(t(`ccAgent.sidebar.${restoreCopy}.empty`));
+ return;
+ }
+
+ const ok = await confirmDialog({
+ title: t('ccAgent.sidebar.unarchiveAll.title'),
+ description: t(`ccAgent.sidebar.${restoreCopy}.description`, {
+ count: candidates.length,
+ }),
+ confirmText: t('ccAgent.sidebar.unarchiveAll.confirm'),
+ cancelText: t('ccAgent.sidebar.unarchiveAll.cancel'),
+ });
+ if (!ok) return;
+
+ const failed: string[] = [];
+ for (const session of candidates) {
+ try {
+ // 确认框是异步边界:由持久层在单条 UPDATE 中同时校验 archived 状态和
+ // 原任务归属,避免 get + update 在两次异步调用之间仍可被并发写穿。
+ const restored = await sessionService.restoreIfArchived(session.id, session);
+ if (!restored) {
+ failed.push(session.id);
+ continue;
+ }
+ patchLocal(restored.id, { status: 'active' });
+ } catch (err) {
+ log.error('[unarchive all]', err);
+ failed.push(session.id);
+ }
+ }
+
+ const succeededCount = candidates.length - failed.length;
+ await refreshSessions();
+ // 批量恢复跨 archived → active 桶,强制刷新其余缓存桶,确保 active / all
+ // 视图切换后立即看到恢复结果。
+ emitRefresh();
+
+ if (failed.length === 0) {
+ toast.success(t('ccAgent.sidebar.unarchiveAll.unarchived', { count: succeededCount }));
+ } else {
+ toast.error(
+ t('ccAgent.sidebar.unarchiveAll.partialFailure', {
+ ok: succeededCount,
+ fail: failed.length,
+ }),
+ );
+ }
+ return;
+ }
+
+ if (candidates.length === 0) {
+ if (skippedPinned > 0 && skippedRunning > 0) {
+ toast.warning(t(`ccAgent.sidebar.${archiveCopy}.allPinnedOrRunning`));
+ } else if (skippedPinned > 0) {
+ toast.warning(t(`ccAgent.sidebar.${archiveCopy}.allPinned`));
+ } else if (skippedRunning > 0) {
+ toast.warning(t(`ccAgent.sidebar.${archiveCopy}.allRunning`));
+ } else {
+ toast.warning(t(`ccAgent.sidebar.${archiveCopy}.empty`));
+ }
+ return;
+ }
+
+ const dirtyCount = await countDirtyWorktreesForRemoval(candidates);
+
+ const skipNotes: string[] = [];
+ if (skippedRunning > 0)
+ skipNotes.push(t('ccAgent.sidebar.archiveAll.skipRunning', { count: skippedRunning }));
+ if (skippedPinned > 0)
+ skipNotes.push(t('ccAgent.sidebar.archiveAll.skipPinned', { count: skippedPinned }));
+ const skipSep = t('ccAgent.sidebar.archiveAll.skipSeparator');
+ const baseDescription =
+ skipNotes.length > 0
+ ? t(`ccAgent.sidebar.${archiveCopy}.descriptionWithSkip`, {
+ count: candidates.length,
+ skip: skipNotes.join(skipSep),
+ })
+ : t(`ccAgent.sidebar.${archiveCopy}.description`, { count: candidates.length });
+ const description =
+ baseDescription +
+ (dirtyCount > 0
+ ? ' ' +
+ t('ccAgent.sidebar.bulkSelection.confirmArchive.dirtyWorktreeWarning', {
+ count: dirtyCount,
+ })
+ : '');
+
+ const ok = await confirmDialog({
+ title: t('ccAgent.sidebar.archiveAll.title'),
+ description,
+ confirmText: t('ccAgent.sidebar.archiveAll.confirm'),
+ cancelText: t('ccAgent.sidebar.archiveAll.cancel'),
+ });
+ if (!ok) return;
+
+ // 失败的 id 收集起来,最后统一 toast;其余继续走完,不让一条失败拖累整批。
+ const failed: string[] = [];
+ for (const s of candidates) {
+ // 关掉 SDK subprocess + 清 in-memory state,与单条 archive 行为一致
+ makerChatStore.closeSessionQuery(s.id);
+ try {
+ await sessionService.setStatus(s.id, 'archived');
+ // 写入后同步各状态桶,再清理该任务的运行视图与草稿。
+ patchLocal(s.id, { status: 'archived', pinnedAt: null });
+ makerChatStore.purgeSession(s.id);
+ discardComposerDraft(s.id);
+ } catch (err) {
+ log.error('[archive all]', err);
+ failed.push(s.id);
+ }
+ }
+
+ const failedIds = new Set(failed);
+ const succeededIds = new Set(candidates.filter((s) => !failedIds.has(s.id)).map((s) => s.id));
+
+ await refreshSessions();
+
+ // 当前注视中的 session 被归档了 → 走 /cc-agent 让 CCAgentIndexRedirect
+ // 做 Orca-aware 的「选下一条 / 空则跳 new」决策。
+ if (viewedSessionId && succeededIds.has(viewedSessionId)) {
+ navigate('/cc-agent');
+ }
+
+ if (failed.length === 0) {
+ toast.success(t('ccAgent.sidebar.archiveAll.archived', { count: succeededIds.size }));
+ } else {
+ toast.error(
+ t('ccAgent.sidebar.archiveAll.partialFailure', {
+ ok: succeededIds.size,
+ fail: failed.length,
+ }),
+ );
+ }
+ },
+ [
+ sessions,
+ runningSessionIds,
+ confirmDialog,
+ refreshSessions,
+ viewedSessionId,
+ navigate,
+ patchLocal,
+ status,
+ t,
+ ],
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
index 71e8b05d51..7d811510e5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
@@ -24,7 +24,10 @@ import type { NavigateFunction } from 'react-router-dom';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
-import { consumeConversationSearchRequest } from '@/state/conversationSearchRequest';
+import {
+ consumeConversationSearchRequest,
+ type ConversationSearchScopeRequest,
+} from '@/state/conversationSearchRequest';
import {
DropdownMenu,
DropdownMenuContent,
@@ -160,14 +163,7 @@ export interface UseConversationSearchParams {
allKnownProjects: ProjectNodeData[];
/** 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;
+ projectFilterRequest?: ConversationSearchScopeRequest | null;
machineSelection?: MachineSelection;
searchDevices?: readonly ConversationSearchDevice[];
/** 收到「在此项目内搜索」请求(锁定项目)时回调:popover 用它打开面板,内联用它聚焦输入。 */
@@ -213,19 +209,31 @@ export function useConversationSearch({
const [lockedProjectSessionIds, setLockedProjectSessionIds] = useState<string[]>([]);
const [lockedProjectWorkingDir, setLockedProjectWorkingDir] = useState<string | null>(null);
const [lockedProjectDeviceId, setLockedProjectDeviceId] = useState<string | null>(null);
+ const [lockedSessionGroup, setLockedSessionGroup] = useState<{
+ name: string;
+ sessionIds: string[];
+ machineSelectionKey: string;
+ } | null>(null);
const [status, setStatus] = useState<'idle' | 'searching' | 'done' | 'error'>('idle');
const [response, setResponse] = useState<ConversationSearchResponse | null>(null);
const requestSeqRef = useRef(0);
- const requestProjectKey = projectFilterRequest?.projectKey ?? null;
- const requestProjectName = projectFilterRequest?.projectName ?? null;
+ const projectRequest = projectFilterRequest?.kind === 'session-group' ? null : projectFilterRequest;
+ const groupRequest = projectFilterRequest?.kind === 'session-group' ? projectFilterRequest : null;
+ const requestProjectKey = projectRequest?.projectKey ?? null;
+ const requestProjectName = projectRequest?.projectName ?? null;
const requestProjectSessionIds = projectFilterRequest?.sessionIds ?? EMPTY_SESSION_IDS;
- const requestProjectWorkingDir = projectFilterRequest?.workingDir ?? null;
- const requestProjectDeviceId = projectFilterRequest?.deviceLinkDeviceId ?? null;
+ const requestProjectWorkingDir = projectRequest?.workingDir ?? null;
+ const requestProjectDeviceId = projectRequest?.deviceLinkDeviceId ?? null;
+ const requestGroupName = groupRequest?.groupName ?? null;
+ const machineSelectionKey = JSON.stringify(
+ machineSelection === MACHINE_ALL ? machineSelection : [...machineSelection].sort(),
+ );
const requestId = projectFilterRequest?.requestId ?? 0;
const trimmed = query.trim();
void _allowedSessionIds;
const selectedProjectSessionIds = useMemo(() => {
+ if (lockedSessionGroup) return lockedSessionGroup.sessionIds;
if (projectSelection === 'all') return null;
const selected = buildProjectKeyComparisonSet(projectSelection, localPlatform);
const selectedProjects = allKnownProjects.filter((project) => {
@@ -260,8 +268,10 @@ export function useConversationSearch({
lockedProjectSessionIds,
localPlatform,
projectSelection,
+ lockedSessionGroup,
]);
const selectedProjectTargets = useMemo(() => {
+ if (lockedSessionGroup) return null;
if (projectSelection === 'all') return null;
const selected = buildProjectKeyComparisonSet(projectSelection, localPlatform);
const fromVisible = allKnownProjects
@@ -297,6 +307,7 @@ export function useConversationSearch({
lockedProjectKey,
lockedProjectWorkingDir,
projectSelection,
+ lockedSessionGroup,
]);
const searchOrigins = useMemo(
() =>
@@ -329,18 +340,25 @@ export function useConversationSearch({
if (statusFilter !== 'all') count += 1;
if (agentFilter !== 'all') count += 1;
if (lastActivityFilter !== 'all') count += 1;
- if (projectSelection !== 'all') count += 1;
+ if (projectSelection !== 'all' || lockedSessionGroup) count += 1;
return count;
- }, [agentFilter, lastActivityFilter, projectSelection, statusFilter]);
+ }, [agentFilter, lastActivityFilter, projectSelection, statusFilter, lockedSessionGroup]);
useEffect(() => {
- if (!requestProjectKey) return;
+ if (!requestProjectKey && requestGroupName === null) return;
+ setLockedSessionGroup(
+ requestGroupName === null ? null : {
+ name: requestGroupName,
+ sessionIds: [...new Set(requestProjectSessionIds)].sort(),
+ machineSelectionKey,
+ },
+ );
setLockedProjectKey(requestProjectKey);
setLockedProjectName(requestProjectName);
setLockedProjectSessionIds([...new Set(requestProjectSessionIds)]);
setLockedProjectWorkingDir(requestProjectWorkingDir);
setLockedProjectDeviceId(requestProjectDeviceId);
- setProjectSelection([requestProjectKey]);
+ setProjectSelection(requestProjectKey ? [requestProjectKey] : 'all');
onProgrammaticOpen?.(); // popover:打开面板并上报托盘;内联:聚焦输入框
setQuery('');
setResponse(null);
@@ -355,6 +373,8 @@ export function useConversationSearch({
requestProjectSessionIds,
requestProjectWorkingDir,
requestProjectDeviceId,
+ requestGroupName,
+ machineSelectionKey,
onProgrammaticOpen,
]);
@@ -492,16 +512,25 @@ export function useConversationSearch({
setStatus('idle');
}, []);
- /** 清除项目锁定,回到全局搜索(popover 触发钮点击时调用)。 */
+ /** 清除项目或任务组锁定,回到全局搜索。 */
const clearLock = useCallback(() => {
- if (!lockedProjectKey) return;
+ if (!lockedProjectKey && !lockedSessionGroup) return;
+ setLockedSessionGroup(null);
setLockedProjectKey(null);
setLockedProjectName(null);
setLockedProjectSessionIds([]);
setLockedProjectWorkingDir(null);
setLockedProjectDeviceId(null);
setProjectSelection('all');
- }, [lockedProjectKey]);
+ }, [lockedProjectKey, lockedSessionGroup]);
+
+ // A group lock is an explicit snapshot, not a synthetic project. Changing the
+ // machine scope releases it, just as leaving a locked project's machine does.
+ useEffect(() => {
+ if (!lockedSessionGroup || lockedSessionGroup.machineSelectionKey === machineSelectionKey) return;
+ reset();
+ clearLock();
+ }, [lockedSessionGroup, machineSelectionKey, reset, clearLock]);
/** 筛选面板「重置」:清空各筛选;有项目锁定时回落到锁定项目。 */
const resetFilters = useCallback(() => {
@@ -574,6 +603,7 @@ export function useConversationSearch({
setProjectSelection,
lockedProjectKey,
lockedProjectName,
+ lockedSessionGroupName: lockedSessionGroup?.name ?? null,
activeFilterCount,
status,
results,
@@ -678,14 +708,7 @@ export interface ConversationSearchBoxProps {
allKnownProjects: ProjectNodeData[];
allowedSessionIds: readonly string[];
hiddenProjectKeys: ReadonlySet<string>;
- projectFilterRequest?: {
- projectKey: string;
- projectName: string;
- sessionIds: string[];
- workingDir?: string | null;
- deviceLinkDeviceId?: string | null;
- requestId: number;
- } | null;
+ projectFilterRequest?: ConversationSearchScopeRequest | null;
machineSelection?: MachineSelection;
searchDevices?: readonly ConversationSearchDevice[];
/** icon variant 触发钮 className 覆盖——rail 用 SIDEBAR_RAIL_ICON_BUTTON_CLASS。 */
@@ -865,6 +888,7 @@ export function ConversationSearchBox({
activeCount={search.activeFilterCount}
lockedProjectKey={search.lockedProjectKey}
lockedProjectName={search.lockedProjectName}
+ lockedSessionGroupName={search.lockedSessionGroupName}
onStatusChange={search.setStatusFilter}
onAgentKindChange={search.setAgentFilter}
onLastActivityChange={search.setLastActivityFilter}
@@ -903,6 +927,7 @@ export function SearchFilterMenu({
activeCount,
lockedProjectKey,
lockedProjectName,
+ lockedSessionGroupName,
onStatusChange,
onAgentKindChange,
onLastActivityChange,
@@ -921,6 +946,7 @@ export function SearchFilterMenu({
activeCount: number;
lockedProjectKey: string | null;
lockedProjectName: string | null;
+ lockedSessionGroupName?: string | null;
onStatusChange: (value: ConversationSearchStatusFilter) => void;
onAgentKindChange: (value: ConversationSearchAgentFilter) => void;
onLastActivityChange: (value: ConversationSearchLastActivityFilter) => void;
@@ -950,14 +976,16 @@ export function SearchFilterMenu({
? projectDisplayLabelWithMachine(lockedProject)
: lockedProjectName;
const projectValue =
- lockedProjectKey && lockedProjectLabel
- ? lockedProjectLabel
- : projects === 'all'
- ? t('ccAgent.search.filter.allProjects')
- : t('ccAgent.sidebar.filterSelectedProjects', { count: projects.length });
+ lockedSessionGroupName ?? (
+ lockedProjectKey && lockedProjectLabel
+ ? lockedProjectLabel
+ : projects === 'all'
+ ? t('ccAgent.search.filter.allProjects')
+ : t('ccAgent.sidebar.filterSelectedProjects', { count: projects.length })
+ );
const selectedProjects =
projects === 'all' ? null : buildProjectKeyComparisonSet(projects, localPlatform);
- const projectsLocked = lockedProjectKey !== null;
+ const projectsLocked = lockedProjectKey !== null || lockedSessionGroupName != null;
return (
<DropdownMenu onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/DialogueGroupMenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/DialogueGroupMenu.tsx
new file mode 100644
index 0000000000..2f95db9fc1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/DialogueGroupMenu.tsx
@@ -0,0 +1,52 @@
+import { useTranslation } from 'react-i18next';
+import {
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+} from '@/components/ui/dropdown-menu';
+import type { Session } from '@/lib/ccAgent.types';
+import type { FilterStatus } from '../hooks/useSidebarFilter';
+import { projectBulkArchiveActionForStatus } from '../lib/projectBulkArchiveAction';
+import { MENU_ITEM_CLASS } from './menuStyles';
+
+/** The dialogue category has group actions, but no project identity or shared directory. */
+export function DialogueGroupMenu({
+ sessions,
+ statusFilter,
+ onSearch,
+ onArchiveAll,
+}: {
+ sessions: readonly Session[];
+ statusFilter: FilterStatus;
+ onSearch: () => void;
+ onArchiveAll: () => void;
+}) {
+ const { t } = useTranslation();
+ const hasRemoteTasks = sessions.some((session) => Boolean(session.deviceLinkDeviceId));
+ return (
+ <>
+ <DropdownMenuItem className={MENU_ITEM_CLASS} onSelect={onSearch}>
+ {t('ccAgent.sidebar.dialogueAction.search')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className={MENU_ITEM_CLASS}
+ disabled={hasRemoteTasks}
+ onSelect={onArchiveAll}
+ >
+ <span>
+ {t(
+ projectBulkArchiveActionForStatus(statusFilter) === 'unarchive'
+ ? 'ccAgent.sidebar.dialogueAction.restoreAll'
+ : 'ccAgent.sidebar.projectAction.archivedAll',
+ )}
+ </span>
+ </DropdownMenuItem>
+ {hasRemoteTasks && (
+ <DropdownMenuLabel className="max-w-60 whitespace-normal text-xs font-normal">
+ {t('ccAgent.sidebar.dialogueAction.remoteBulkUnavailable')}
+ </DropdownMenuLabel>
+ )}
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarInlineSearch.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarInlineSearch.tsx
index c2c00be9eb..5760238f04 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarInlineSearch.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarInlineSearch.tsx
@@ -76,7 +76,7 @@ export function SidebarInlineSearch({
: null;
const lockedProjectLabel = lockedProject
? projectDisplayLabelWithMachine(lockedProject)
- : search.lockedProjectName;
+ : search.lockedSessionGroupName ?? search.lockedProjectName;
// 程序化展开信号:展开并聚焦输入框(input 在展开态才挂载,置 forceOpen 触发挂载后再 focus)。
useEffect(() => {
@@ -137,7 +137,7 @@ export function SidebarInlineSearch({
<Search size={15} strokeWidth={1.8} className="shrink-0 text-[var(--sidebar-nav-text)]" />
{expanded ? (
<>
- {search.lockedProjectKey && (
+ {(search.lockedProjectKey || search.lockedSessionGroupName) && (
// 锁定项目 chip:展开态显示「在此项目内搜索」锁定的项目名 + 解锁 X。
<span className="flex min-w-0 max-w-[48%] shrink items-center gap-1 rounded-full bg-[var(--surface-chip)] py-0.5 pl-2 pr-0.5 text-xs text-[var(--text-secondary)]">
<span className="min-w-0 truncate">{lockedProjectLabel}</span>
@@ -204,6 +204,7 @@ export function SidebarInlineSearch({
activeCount={search.activeFilterCount}
lockedProjectKey={search.lockedProjectKey}
lockedProjectName={search.lockedProjectName}
+ lockedSessionGroupName={search.lockedSessionGroupName}
onStatusChange={search.setStatusFilter}
onAgentKindChange={search.setAgentFilter}
onLastActivityChange={search.setLastActivityFilter}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
index c29579ef4a..e209f18a68 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
@@ -49,6 +49,12 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { Tip } from '@/components/ui/tooltip';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { DialogueGroupMenu } from '../DialogueGroupMenu';
import { useEffectiveSelectedMachineId } from '@/features/device-link/useMachineSwitcher';
import { useRemoteDevices } from '@/features/device-link/remoteProjectsStore';
import {
@@ -265,6 +271,9 @@ export interface ProjectsSectionProps {
onBrowseFiles: (project: ProjectNodeData) => void;
/** 右键菜单 → 归档该 project 下所有非执行中的 session(带二次确认)。 */
onArchiveAll: (project: ProjectNodeData) => void;
+ /** 专属对话菜单使用完整组成员,不受组内折叠条数影响。 */
+ onSearchDialogues: (sessions: readonly Session[]) => void;
+ onArchiveAllDialogues: (sessions: readonly Session[]) => void;
/**
* E 期「按设备分组」:远程设备的展示顺序与名称/在线状态(设备切换栏同源)。
* 含断线缓存设备;null / 空 map = 没有可选远程设备 → 设备分组选项隐藏、不切段。
@@ -321,6 +330,8 @@ export function ProjectsSection({
linkingCodexProject,
onBrowseFiles,
onArchiveAll,
+ onSearchDialogues,
+ onArchiveAllDialogues,
remoteDeviceIndex = null,
onCreateDialogue,
isCreateDialogueDisabled = false,
@@ -1055,6 +1066,16 @@ export function ProjectsSection({
lamp={lampAgg(entry.sessions)}
foldExemptSessionIds={lampFoldExemptIds}
groupTitle={isMake ? t('settings.cindyMake.title') : undefined}
+ headerMenu={
+ isMake ? undefined : (
+ <DialogueGroupMenu
+ sessions={entry.sessions}
+ statusFilter={filter.status}
+ onSearch={() => onSearchDialogues(entry.sessions)}
+ onArchiveAll={() => onArchiveAllDialogues(entry.sessions)}
+ />
+ )
+ }
groupIcon={
isMake ? (
<Hammer size={15} strokeWidth={1.8} className="shrink-0" aria-hidden />
@@ -1367,6 +1388,7 @@ export function SessionGroupNode({
foldExemptSessionIds,
collapsed,
onToggle,
+ headerMenu,
onCreateDialogue,
groupIcon,
groupRunningMarker = 'icon',
@@ -1399,6 +1421,8 @@ export function SessionGroupNode({
foldExemptSessionIds?: ReadonlySet<string>;
collapsed: boolean;
onToggle: () => void;
+ /** 可选菜单内容;仅提供时拦截组头右键,其余复用组保留原行为。 */
+ headerMenu?: ReactNode;
/**
* 组头图标与标题。省略 = 「对话」组(本组件的原始形态)。
*
@@ -1409,7 +1433,7 @@ export function SessionGroupNode({
/** 仅不继承 currentColor 的头像需要运行色描边;线条图标直接变色。 */
groupRunningMarker?: 'icon' | 'ring';
groupTitle?: string;
- /** 新建按钮的 tooltip / aria 文案。省略 = 「新建对话」。 */
+ /** 新建按钮的 tooltip / aria 文案。省略 = 「新任务」。 */
createLabel?: string;
/**
* 组头右侧的新建入口(与项目行 SquarePen 等位):新建不绑项目的对话任务。
@@ -1437,6 +1461,9 @@ export function SessionGroupNode({
sessionVariant: 'text' | 'list';
}) {
const { t } = useTranslation();
+ const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);
+ const headerRef = useRef<HTMLDivElement>(null);
+ const restoreHeaderFocusOnClose = useRef(false);
// 与 ProjectNode 同款:标题右侧 hover 渐显的展开/收起指示箭头。
const Chevron = collapsed ? ChevronRight : ChevronDown;
const showRunning = collapsed && lamp?.running;
@@ -1444,14 +1471,27 @@ export function SessionGroupNode({
<div className="relative flex w-full select-none flex-col" data-no-drag>
{/* 段头:与 ProjectNode Header 同款规格(h-8 药丸 hover / pl-3 pr-2 /
gap-2.5 / 15px 图标 / meta 灰 font-normal),仅图标换 MessagesSquare、
- 无重命名与右键菜单(「对话」是固定分类名,没有项目那套操作)。 */}
+ 菜单内容由调用方提供,固定分类不继承项目专属操作。 */}
<div
+ ref={headerRef}
role="button"
tabIndex={0}
aria-expanded={!collapsed}
onClick={onToggle}
+ onContextMenu={
+ headerMenu ? (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setMenuPos({ x: event.clientX, y: event.clientY });
+ } : undefined
+ }
onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
+ if (headerMenu && (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10'))) {
+ e.preventDefault();
+ e.stopPropagation();
+ const rect = e.currentTarget.getBoundingClientRect();
+ setMenuPos({ x: rect.left, y: rect.bottom });
+ } else if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onToggle();
}
@@ -1497,7 +1537,7 @@ export function SessionGroupNode({
</div>
)}
{/* 悬浮工具组:与 ProjectNode Header 同款——常态隐藏,hover 整行淡入。
- 对话组没有项目那套 More 菜单,只保留新建(SquarePen,与项目行等位)。 */}
+ 新建(SquarePen)与项目行等位,右键菜单独立于新建与折叠操作。 */}
{onCreateDialogue && (
<div
className={cn(
@@ -1563,6 +1603,39 @@ export function SessionGroupNode({
/>
</div>
</SectionCollapse>
+ {headerMenu && (
+ <DropdownMenu
+ open={menuPos !== null}
+ onOpenChange={(open) => { if (!open) setMenuPos(null); }}
+ >
+ <DropdownMenuTrigger asChild>
+ <span
+ aria-hidden
+ style={{
+ position: 'fixed', left: menuPos?.x ?? 0, top: menuPos?.y ?? 0,
+ width: 0, height: 0, pointerEvents: 'none',
+ }}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ sideOffset={2}
+ className="min-w-[160px]"
+ onEscapeKeyDown={() => { restoreHeaderFocusOnClose.current = true; }}
+ onCloseAutoFocus={(event) => {
+ // The Radix trigger only anchors the right-click coordinates.
+ // Escape returns to the visible header; menu actions keep their
+ // search/dialog focus, and outside clicks keep the clicked target.
+ event.preventDefault();
+ if (restoreHeaderFocusOnClose.current) headerRef.current?.focus();
+ restoreHeaderFocusOnClose.current = false;
+ }}
+ onContextMenu={(event) => { event.preventDefault(); event.stopPropagation(); }}
+ >
+ {headerMenu}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</div>
);
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b1e3740fa7..803f5bae16 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -12654,6 +12654,23 @@
"confirm": "Confirm",
"cancel": "Cancel"
},
+ "dialogueAction": {
+ "search": "Search This Chat Group",
+ "restoreAll": "Restore All",
+ "remoteBulkUnavailable": "Bulk actions are not yet supported for groups containing remote tasks"
+ },
+ "dialogueArchiveAll": {
+ "description": "Archive all {{count}} tasks in this chat group? Archived tasks will be removed from the list.",
+ "descriptionWithSkip": "Archive {{count}} tasks in this chat group? {{skip}} tasks will be skipped. Archived tasks will be removed from the list.",
+ "allPinnedOrRunning": "All tasks in this chat group are pinned or running. No tasks can be archived.",
+ "allPinned": "All tasks in this chat group are pinned and will be kept.",
+ "allRunning": "All tasks in this chat group are running. Stop them before archiving.",
+ "empty": "No tasks in this chat group can be archived"
+ },
+ "dialogueRestoreAll": {
+ "description": "Restore {{count}} archived tasks in this chat group? They will move from Archived to Active.",
+ "empty": "No archived tasks in this chat group can be restored"
+ },
"archiveAll": {
"title": "Archive all sessions",
"confirm": "Archive all",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3a1f93b378..8c75ad1c3c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -12601,6 +12601,23 @@
"confirm": "確認",
"cancel": "キャンセル"
},
+ "dialogueAction": {
+ "search": "「会話」グループ内を検索",
+ "restoreAll": "すべて復元",
+ "remoteBulkUnavailable": "リモートセッションを含むグループの一括操作にはまだ対応していません"
+ },
+ "dialogueArchiveAll": {
+ "description": "この「会話」グループのセッション {{count}} 件をすべてアーカイブします。アーカイブ後は一覧から非表示になります。",
+ "descriptionWithSkip": "この「会話」グループのセッション {{count}} 件をアーカイブします({{skip}}はスキップされます)。アーカイブ後は一覧から非表示になります。",
+ "allPinnedOrRunning": "この「会話」グループのセッションはすべてピン留め済みか実行中のため、アーカイブできません",
+ "allPinned": "この「会話」グループのセッションはすべてピン留め済みのため、アーカイブされません",
+ "allRunning": "この「会話」グループのセッションはすべて実行中です。停止してからアーカイブしてください",
+ "empty": "この「会話」グループにアーカイブできるセッションはありません"
+ },
+ "dialogueRestoreAll": {
+ "description": "この「会話」グループのアーカイブ済みセッション {{count}} 件を復元します。復元後は「アーカイブ済み」から「アクティブ」に移動します。",
+ "empty": "この「会話」グループに復元できるセッションはありません"
+ },
"archiveAll": {
"title": "すべてのセッションをアーカイブ",
"confirm": "すべてアーカイブ",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 27768ef70c..601dc5e9f8 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -12601,6 +12601,23 @@
"confirm": "확인",
"cancel": "취소"
},
+ "dialogueAction": {
+ "search": "이 대화 그룹에서 검색",
+ "restoreAll": "모두 복원",
+ "remoteBulkUnavailable": "원격 세션이 포함된 그룹의 일괄 작업은 아직 지원하지 않습니다"
+ },
+ "dialogueArchiveAll": {
+ "description": "이 대화 그룹의 세션 {{count}}개를 모두 보관합니다. 보관 후 목록에서 숨겨집니다.",
+ "descriptionWithSkip": "이 대화 그룹의 세션 {{count}}개를 보관합니다({{skip}}는 건너뜁니다). 보관 후 목록에서 숨겨집니다.",
+ "allPinnedOrRunning": "이 대화 그룹의 모든 세션이 고정되었거나 실행 중이므로 보관할 수 없습니다",
+ "allPinned": "이 대화 그룹의 모든 세션이 고정되어 있어 보관되지 않습니다",
+ "allRunning": "이 대화 그룹의 모든 세션이 실행 중입니다. 중지한 후 보관하세요",
+ "empty": "이 대화 그룹에 보관할 수 있는 세션이 없습니다"
+ },
+ "dialogueRestoreAll": {
+ "description": "이 대화 그룹의 보관된 세션 {{count}}개를 복원합니다. 복원 후 '보관됨' 목록에서 '활성' 목록으로 이동합니다.",
+ "empty": "이 대화 그룹에 복원할 수 있는 세션이 없습니다"
+ },
"archiveAll": {
"title": "모든 세션 보관",
"confirm": "모두 보관",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 109529e46f..4b3989d4c4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12601,6 +12601,23 @@
"confirm": "确认",
"cancel": "取消"
},
+ "dialogueAction": {
+ "search": "在对话中搜索",
+ "restoreAll": "全部恢复",
+ "remoteBulkUnavailable": "暂不支持含远程任务的批量操作"
+ },
+ "dialogueArchiveAll": {
+ "description": "将归档此对话组内全部 {{count}} 个任务。归档后将从列表中移除。",
+ "descriptionWithSkip": "将归档此对话组内 {{count}} 个任务,{{skip}}的任务会被跳过。归档后将从列表中移除。",
+ "allPinnedOrRunning": "此对话组内任务全部已置顶或在运行中,无可归档项",
+ "allPinned": "此对话组内任务全部已置顶,不会归档",
+ "allRunning": "此对话组内所有任务都在运行中,请先停止后再归档",
+ "empty": "此对话组内没有可归档的任务"
+ },
+ "dialogueRestoreAll": {
+ "description": "将恢复此对话组内 {{count}} 个已归档任务。恢复后将从“已归档”列表移除,并回到“活跃”列表。",
+ "empty": "此对话组内没有可恢复的任务"
+ },
"archiveAll": {
"title": "归档全部任务",
"confirm": "归档全部",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 96d792aca3..c44a7742db 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12601,6 +12601,23 @@
"confirm": "確認",
"cancel": "取消"
},
+ "dialogueAction": {
+ "search": "在對話中搜尋",
+ "restoreAll": "全部恢復",
+ "remoteBulkUnavailable": "暫不支援含遠端任務的批次操作"
+ },
+ "dialogueArchiveAll": {
+ "description": "將歸檔此對話群組內全部 {{count}} 個任務。歸檔後將從列表中移除。",
+ "descriptionWithSkip": "將歸檔此對話群組內 {{count}} 個任務,{{skip}}的任務會被跳過。歸檔後將從列表中移除。",
+ "allPinnedOrRunning": "此對話群組內任務全部已置頂或在執行中,無可歸檔項",
+ "allPinned": "此對話群組內任務全部已置頂,不會歸檔",
+ "allRunning": "此對話群組內所有任務都在執行中,請先停止後再歸檔",
+ "empty": "此對話群組內沒有可歸檔的任務"
+ },
+ "dialogueRestoreAll": {
+ "description": "將恢復此對話群組內 {{count}} 個已歸檔任務。恢復後將從「已歸檔」列表移除,並回到「活躍」列表。",
+ "empty": "此對話群組內沒有可恢復的任務"
+ },
"archiveAll": {
"title": "歸檔全部任務",
"confirm": "歸檔全部",
diff --git a/apps/desktop/src/renderer/state/conversationSearchRequest.ts b/apps/desktop/src/renderer/state/conversationSearchRequest.ts
index 5b93d25b0b..6cb29c4ace 100644
--- a/apps/desktop/src/renderer/state/conversationSearchRequest.ts
+++ b/apps/desktop/src/renderer/state/conversationSearchRequest.ts
@@ -1,5 +1,5 @@
/**
- * conversationSearchRequest —— "请求在某个 project 内打开会话搜索" 的跨层信号
+ * conversationSearchRequest —— 请求在项目或任务组内打开搜索的跨层信号。
*
* 背景:展开侧栏的会话搜索是常驻内联框(CCAgentSidebarUpper 的 SidebarInlineSearch
* + useConversationSearch);rail 态是 ConversationSearchBox 图标弹窗。"在此项目内搜索"
@@ -14,6 +14,7 @@
import { useSyncExternalStore } from 'react';
export interface ConversationSearchProjectRequest {
+ kind?: 'project';
projectKey: string;
projectName: string;
sessionIds: string[];
@@ -22,7 +23,17 @@ export interface ConversationSearchProjectRequest {
requestId: number;
}
-let current: ConversationSearchProjectRequest | null = null;
+export interface ConversationSearchSessionGroupRequest {
+ kind: 'session-group';
+ groupName: string;
+ sessionIds: string[];
+ requestId: number;
+}
+
+export type ConversationSearchScopeRequest =
+ ConversationSearchProjectRequest | ConversationSearchSessionGroupRequest;
+
+let current: ConversationSearchScopeRequest | null = null;
let nextRequestId = 1;
const listeners = new Set<() => void>();
@@ -30,19 +41,17 @@ function emit(): void {
for (const l of listeners) l();
}
-/** 生产者:项目 ⋮ → "在此项目内搜索"。内部自增 requestId,触发消费方打开搜索。 */
-export function requestConversationSearch(req: {
- projectKey: string;
- projectName: string;
- sessionIds: string[];
- workingDir?: string | null;
- deviceLinkDeviceId?: string | null;
-}): void {
+/** 项目或任务组菜单发起搜索;自增 requestId 保证同一范围可反复打开。 */
+export function requestConversationSearch(
+ req:
+ | Omit<ConversationSearchProjectRequest, 'requestId'>
+ | Omit<ConversationSearchSessionGroupRequest, 'requestId'>,
+): void {
current = { ...req, requestId: nextRequestId++ };
emit();
}
-export function getConversationSearchRequest(): ConversationSearchProjectRequest | null {
+export function getConversationSearchRequest(): ConversationSearchScopeRequest | null {
return current;
}
@@ -52,8 +61,12 @@ function subscribe(cb: () => void): () => void {
}
/** Hook —— 消费方(useConversationSearch)用它订阅 projectFilterRequest。 */
-export function useConversationSearchRequest(): ConversationSearchProjectRequest | null {
- return useSyncExternalStore(subscribe, getConversationSearchRequest, getConversationSearchRequest);
+export function useConversationSearchRequest(): ConversationSearchScopeRequest | null {
+ return useSyncExternalStore(
+ subscribe,
+ getConversationSearchRequest,
+ getConversationSearchRequest,
+ );
}
/**
diff --git a/docs/product-rules/sidebar-redesign-plan.md b/docs/product-rules/sidebar-redesign-plan.md
index e84da433b6..0b74a78de0 100644
--- a/docs/product-rules/sidebar-redesign-plan.md
+++ b/docs/product-rules/sidebar-redesign-plan.md
@@ -79,6 +79,13 @@
空白处右键。前两处打开同一份段头菜单,**点击展开**(2026-08-12 用户裁决,
推翻早前的 hover 自动展开);按钮配色与段头其余按钮同源,hover 只出 tooltip。
+右键「对话」组头打开专属精简菜单,不冒泡触发全局显示设置:只提供「在对话中搜索」和
+「全部归档」,已归档视图将后者替换为「全部恢复」。范围为当前组的完整成员,不受组内
+折叠条数影响,不混入项目、伙伴或 Cindy Make 任务。归档跳过运行中和已置顶的任务,并
+显示数量与确认提示;含 device-link 远程任务的组(包括本机与远程混合组)暂时禁用批量
+归档/恢复并显示原因,搜索仍可用。复用菜单与批量生命周期;项目行、伙伴与 Cindy Make
+分组保留各自既有行为。
+
菜单**不带自身标题行**(2026-08-12 用户裁决,节约高度;与远程机器菜单同规)——
触发按钮的 tooltip 已经说明这是什么。菜单高度按 Radix 给出的可用空间收口并允许
纵向滚动:渲染进程画不到 BrowserWindow 外面,窗口矮时菜单放不下,若不收口