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。

feat(desktop): 支持按自动化批量归档任务

DavidShen6f90db189cbd
diff --git a/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx b/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx
index 38cb62691c..325db3a127 100644
--- a/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sessionGroupArchive.test.tsx
@@ -14,6 +14,9 @@ import { makerChatStore } from '@/lib/makerChatStore';
import { emitRefresh } from '@/lib/sessionsBus';
import { toast } from '@/lib/toast';
import type { ConfirmOptions } from '@/components/ui/confirm-dialog-provider';
+import type { AutomationScheduleSessionInfo } from '@/features/cc-agent/lib/automationSidebarGrouping';
+
+const liveRunning = vi.hoisted(() => new Map<string, { isRunning: boolean }>());
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -21,15 +24,46 @@ vi.mock('react-i18next', () => ({
args ? `${key}:${JSON.stringify(args)}` : key,
}),
}));
-vi.mock('@/lib/sessionService', () => ({ setStatus: vi.fn(), restoreIfArchived: vi.fn() }));
+vi.mock('@/lib/sessionService', () => ({
+ setStatus: vi.fn(),
+ restoreIfArchived: vi.fn(),
+ resolveStatusWriteTarget: vi.fn(),
+}));
vi.mock('@/lib/makerChatStore', () => ({
- makerChatStore: { closeSessionQuery: vi.fn(), purgeSession: vi.fn() },
+ makerChatStore: {
+ closeSessionQuery: vi.fn(),
+ purgeSession: vi.fn(),
+ getRunningSnapshot: () => liveRunning,
+ },
}));
vi.mock('@/lib/composerDraftStore', () => ({ discardDraft: vi.fn() }));
vi.mock('@/lib/sessionsBus', () => ({ emitRefresh: vi.fn() }));
vi.mock('@/lib/toast', () => ({ toast: { warning: vi.fn(), success: vi.fn(), error: vi.fn() } }));
const worktreeRemovalPreview = vi.fn();
+const resolveSession = vi.fn();
+
+function automationScope(members: Session[]) {
+ return {
+ kind: 'automation' as const,
+ group: {
+ id: 'schedule:automation',
+ scheduleId: 'automation',
+ title: 'Automation',
+ sessions: members,
+ attentionSessionIds: [],
+ },
+ scheduleSessionIndex: new Map(
+ members.map((s) => [
+ s.id,
+ {
+ scheduleId: 'automation',
+ scheduleName: 'Automation',
+ } as AutomationScheduleSessionInfo,
+ ]),
+ ),
+ };
+}
// Value: invoke the production group lifecycle and inspect persisted writes,
// confirmation scope and cleanup. The existing candidate-selector unit tests
@@ -76,8 +110,11 @@ function mount(sessions: Session[], status: FilterStatus = 'active') {
beforeEach(() => {
vi.clearAllMocks();
+ liveRunning.clear();
+ vi.mocked(sessionService.resolveStatusWriteTarget).mockResolvedValue({ kind: 'local' });
+ resolveSession.mockReset().mockResolvedValue({ attached: false });
worktreeRemovalPreview.mockReset().mockResolvedValue({ hasWorktree: true, dirty: false });
- vi.stubGlobal('electronAPI', { worktreeRemovalPreview });
+ vi.stubGlobal('electronAPI', { worktreeRemovalPreview, binding: { resolveSession } });
});
afterEach(() => {
cleanup();
@@ -85,6 +122,202 @@ afterEach(() => {
});
describe('session group bulk lifecycle', () => {
+ // Review P1 regression: the new automation entry bypassed IM takeover checks
+ // and used candidates fixed before confirmation. Earlier tests had neither
+ // attached records nor state changes during awaits. Exercise real hook writes,
+ // query shutdown and result counts. Minimal input: one protected + one idle run.
+ // Tier: unit; deferred promises model confirmation/IPC timing without sleeps.
+ it.each([false, true])(
+ 'excludes attached runs before confirmation (all attached=%s)',
+ async (allAttached) => {
+ const runs = [
+ session('eligible', { source: 'scheduler' }),
+ session('attached', { source: 'scheduler' }),
+ ];
+ const view = mount(runs);
+ resolveSession.mockImplementation(async (id) => ({
+ attached: allAttached || id === 'attached',
+ }));
+ await act(async () => {
+ await view.result.current(automationScope(runs));
+ });
+ expect(view.writes.get('attached')?.status).toBe('active');
+ expect(makerChatStore.closeSessionQuery).not.toHaveBeenCalledWith('attached');
+ expect(worktreeRemovalPreview).not.toHaveBeenCalledWith('attached');
+ if (allAttached) {
+ expect(view.options.confirmDialog).not.toHaveBeenCalled();
+ expect(sessionService.setStatus).not.toHaveBeenCalled();
+ expect(toast.warning).toHaveBeenCalledWith(expect.stringContaining('skipAttached'));
+ } else {
+ expect(view.writes.get('eligible')?.status).toBe('archived');
+ expect(view.options.confirmDialog.mock.calls[0][0].description).toContain('skipAttached');
+ expect(toast.success).toHaveBeenCalledWith(
+ 'ccAgent.sidebar.archiveAll.archived:{"count":1}',
+ );
+ }
+ },
+ );
+
+ it.each(['running', 'attached'] as const)(
+ 'preserves a run that becomes %s while confirmation is open',
+ async (change) => {
+ const runs = [
+ session('eligible', { source: 'scheduler' }),
+ session('other', { source: 'scheduler' }),
+ ];
+ const view = mount(runs);
+ let confirm!: (ok: boolean) => void;
+ view.options.confirmDialog.mockReturnValue(
+ new Promise((resolve) => {
+ confirm = resolve;
+ }),
+ );
+ let archive!: Promise<void>;
+ await act(async () => {
+ archive = view.result.current(automationScope(runs));
+ });
+ expect(view.options.confirmDialog).toHaveBeenCalledOnce();
+ await act(async () => {
+ if (change === 'running') {
+ liveRunning.set('eligible', { isRunning: true });
+ view.options.runningSessionIds = new Set(['running', 'eligible']);
+ view.rerender();
+ } else {
+ resolveSession.mockImplementation(async (id) => ({ attached: id === 'eligible' }));
+ }
+ confirm(true);
+ await archive;
+ });
+ expect(view.writes.get('eligible')?.status).toBe('active');
+ expect(view.writes.get('other')?.status).toBe('archived');
+ expect(makerChatStore.closeSessionQuery).not.toHaveBeenCalledWith('eligible');
+ expect(makerChatStore.purgeSession).not.toHaveBeenCalledWith('eligible');
+ expect(view.options.navigate).not.toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalledWith('ccAgent.sidebar.archiveAll.archived:{"count":1}');
+ expect(toast.warning).toHaveBeenCalledWith(
+ expect.stringContaining(change === 'running' ? 'skipRunning' : 'skipAttached'),
+ );
+ },
+ );
+
+ it('checks live running state after the binding lookup and before closing a query', async () => {
+ const runs = [session('eligible', { source: 'scheduler' })];
+ const view = mount(runs);
+ let binding!: (value: { attached: boolean }) => void;
+ resolveSession.mockResolvedValueOnce({ attached: false }).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ binding = resolve;
+ }),
+ );
+ let archive!: Promise<void>;
+ await act(async () => {
+ archive = view.result.current(automationScope(runs));
+ });
+ expect(resolveSession).toHaveBeenCalledTimes(2);
+ await act(async () => {
+ liveRunning.set('eligible', { isRunning: true });
+ binding({ attached: false });
+ await archive;
+ });
+ expect(view.writes.get('eligible')?.status).toBe('active');
+ expect(makerChatStore.closeSessionQuery).not.toHaveBeenCalled();
+ expect(sessionService.setStatus).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it('preserves a later member that starts running during an earlier archive write', async () => {
+ const runs = [
+ session('first', { source: 'scheduler' }),
+ session('eligible', { source: 'scheduler' }),
+ ];
+ const view = mount(runs);
+ vi.mocked(sessionService.setStatus).mockImplementation(async (id, status) => {
+ const updated = { ...view.writes.get(id)!, status };
+ view.writes.set(id, updated);
+ liveRunning.set('eligible', { isRunning: true });
+ return updated;
+ });
+ await act(async () => {
+ await view.result.current(automationScope(runs));
+ });
+ expect(view.writes.get('first')?.status).toBe('archived');
+ expect(view.writes.get('eligible')?.status).toBe('active');
+ expect(makerChatStore.closeSessionQuery).toHaveBeenCalledExactlyOnceWith('first');
+ expect(view.options.navigate).not.toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalledWith('ccAgent.sidebar.archiveAll.archived:{"count":1}');
+ });
+
+ // Feature: archive an automation from its group menu. Existing dialogue/project
+ // tests cannot detect matching by title or limiting writes to visible children.
+ // Minimal input: one displayed run, one hidden run and a same-title foreign run.
+ // Tier: unit, exercising the production hook with in-memory persistence.
+ // Standalone validation: Vitest 2.13s, tests 22ms (2026-10-27).
+ it('archives the whole automation by identity, including hidden runs, without restoring archived runs', async () => {
+ const runs = ['eligible', 'hidden', 'running', 'pinned', 'archived', 'foreign', 'remote'].map(
+ (id) =>
+ session(id, {
+ source: 'scheduler',
+ title: 'Same name',
+ ...(id === 'pinned' ? { pinnedAt: '2026-10-27' } : {}),
+ ...(id === 'archived' ? { status: 'archived' as const } : {}),
+ ...(id === 'remote' ? { deviceLinkDeviceId: 'other-computer' } : {}),
+ }),
+ );
+ const scheduleSessionIndex = new Map(
+ runs.map((run) => [
+ run.id,
+ {
+ scheduleId: run.id === 'foreign' ? 'other' : 'automation',
+ scheduleName: 'Same name',
+ } as AutomationScheduleSessionInfo,
+ ]),
+ );
+ const view = mount(runs, 'all');
+ await act(async () => {
+ await view.result.current({
+ kind: 'automation',
+ group: {
+ id: 'schedule:automation',
+ scheduleId: 'automation',
+ title: 'Same name',
+ sessions: [runs[0]],
+ attentionSessionIds: [],
+ },
+ scheduleSessionIndex,
+ });
+ });
+ expect(
+ [...view.writes.values()].filter((s) => s.status === 'archived').map((s) => s.id),
+ ).toEqual(['eligible', 'hidden', 'archived']);
+ expect(view.options.confirmDialog.mock.calls[0][0].description).toContain(
+ 'automationArchiveAll.descriptionWithSkip:{"count":2',
+ );
+ expect(sessionService.restoreIfArchived).not.toHaveBeenCalled();
+ expect(view.options.navigate).toHaveBeenCalledWith('/cc-agent');
+ });
+
+ it('rejects an automation owned by another computer before confirming or writing', async () => {
+ const runs = [session('eligible')];
+ const view = mount(runs);
+ await act(async () => {
+ await view.result.current({
+ kind: 'automation',
+ group: {
+ id: 'schedule:automation',
+ title: 'Automation',
+ deviceLinkDeviceId: 'other-computer',
+ sessions: runs,
+ attentionSessionIds: [],
+ },
+ scheduleSessionIndex: new Map(),
+ });
+ });
+ expect(view.options.confirmDialog).not.toHaveBeenCalled();
+ expect(sessionService.setStatus).not.toHaveBeenCalled();
+ expect(toast.warning).toHaveBeenCalledWith('ccAgent.remoteSession.actionsUnavailable');
+ });
+
it.each([false, true])(
'archives only eligible dialogue members with dirty=%s warning and normal cleanup',
async (dirty) => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index ea289ccc78..9118adb6f9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -990,8 +990,8 @@ function ExpandedView({
};
}, []);
- const handleScheduleAction = useCallback(
- async (group: AutomationSessionGroup, action: AutomationScheduleAction) => {
+ const handleAutomationScheduleAction = useCallback(
+ async (group: AutomationSessionGroup, action: Exclude<AutomationScheduleAction, 'archive-all'>) => {
// 远程分组的操作发到任务所属电脑执行;本机分组仍走本机 IPC。
const deviceId = group.deviceLinkDeviceId;
const invokeSchedule = <T,>(channel: string, localCall: () => Promise<T>, id: string) =>
@@ -3593,6 +3593,14 @@ function ExpandedView({
viewedSessionId,
navigate,
});
+
+ const handleScheduleAction = useCallback(
+ (group: AutomationSessionGroup, action: AutomationScheduleAction) =>
+ action === 'archive-all'
+ ? archiveSessionGroup({ kind: 'automation', group, scheduleSessionIndex })
+ : handleAutomationScheduleAction(group, action),
+ [archiveSessionGroup, handleAutomationScheduleAction, scheduleSessionIndex],
+ );
const handleArchiveAllInProject = useCallback(
(project: ProjectNode) => archiveSessionGroup({ kind: 'project', project }),
[archiveSessionGroup],
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts
index aaa918c8c4..c8e3d2eec8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts
@@ -18,11 +18,32 @@ import {
selectProjectBulkArchiveCandidates,
} from '../lib/projectBulkArchiveAction';
import type { FilterStatus } from './useSidebarFilter';
+import {
+ getAutomationSidebarGroupInfo,
+ type AutomationSessionGroup,
+ type AutomationScheduleSessionInfo,
+} from '../lib/automationSidebarGrouping';
const log = createLogger('SessionGroupArchive');
+/** Read takeover first, then the live running store after that asynchronous boundary. */
+async function archiveBlockReason(sessionId: string): Promise<'attached' | 'running' | null> {
+ try {
+ if ((await window.electronAPI.binding.resolveSession(sessionId)).attached) return 'attached';
+ } catch {
+ // Match the existing single-session and selection archive preflight fallback.
+ }
+ return makerChatStore.getRunningSnapshot().get(sessionId)?.isRunning ? 'running' : null;
+}
+
type SessionGroupArchiveScope =
- { kind: 'project'; project: ProjectNode } | { kind: 'dialogue'; sessions: readonly Session[] };
+ | { kind: 'project'; project: ProjectNode }
+ | { kind: 'dialogue'; sessions: readonly Session[] }
+ | {
+ kind: 'automation';
+ group: AutomationSessionGroup;
+ scheduleSessionIndex: ReadonlyMap<string, AutomationScheduleSessionInfo>;
+ };
interface SessionGroupArchiveOptions {
sessions: readonly Session[];
@@ -35,7 +56,7 @@ interface SessionGroupArchiveOptions {
navigate: NavigateFunction;
}
-/** Shared project/dialogue bulk lifecycle. Scope membership never depends on visible fold limits. */
+/** Shared group bulk lifecycle. Scope membership never depends on visible fold limits. */
export function useSessionGroupArchive({
sessions,
runningSessionIds,
@@ -52,35 +73,50 @@ export function useSessionGroupArchive({
if (
scope.kind === 'project'
? isDeviceLinkWriteBlocked(scope.project)
- : scope.sessions.some((session) => session.deviceLinkDeviceId)
+ : scope.kind === 'automation'
+ ? scope.group.deviceLinkDeviceId ||
+ scope.group.sessions.some((s) => s.deviceLinkDeviceId)
+ : scope.sessions.some((session) => session.deviceLinkDeviceId)
) {
toast.warning(
t(
- scope.kind === 'project'
+ scope.kind !== 'dialogue'
? 'ccAgent.remoteSession.actionsUnavailable'
: 'ccAgent.sidebar.dialogueAction.remoteBulkUnavailable',
),
);
return;
}
- const action = projectBulkArchiveActionForStatus(status);
+ const action =
+ scope.kind === 'automation' ? 'archive' : 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';
+ : scope.kind === 'automation'
+ ? !session.deviceLinkDeviceId &&
+ getAutomationSidebarGroupInfo(session, scope.scheduleSessionIndex)?.key ===
+ scope.group.id
+ : memberIds!.has(session.id);
+ const archiveCopy =
+ scope.kind === 'project'
+ ? 'archiveAll'
+ : scope.kind === 'automation'
+ ? 'automationArchiveAll'
+ : '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(
+ // All group types share candidate selection, confirmation and lifecycle cleanup.
+ const selection = selectProjectBulkArchiveCandidates(
sessions,
action,
runningSessionIds,
belongsToGroup,
);
+ let { candidates, skippedRunning } = selection;
+ const { skippedPinned } = selection;
if (action === 'unarchive') {
if (candidates.length === 0) {
@@ -134,8 +170,32 @@ export function useSessionGroupArchive({
return;
}
+ let skippedAttached = 0;
+ const checked = await Promise.all(
+ candidates.map(async (session) => {
+ const reason = await archiveBlockReason(session.id);
+ if (reason === 'attached') skippedAttached++;
+ if (reason === 'running') skippedRunning++;
+ return reason ? null : session;
+ }),
+ );
+ candidates = checked.filter((session): session is Session => session !== null);
+
+ const skipNotesFor = (running: number, pinned: number, attached: number): string[] => {
+ const notes: string[] = [];
+ if (running > 0)
+ notes.push(t('ccAgent.sidebar.archiveAll.skipRunning', { count: running }));
+ if (pinned > 0) notes.push(t('ccAgent.sidebar.archiveAll.skipPinned', { count: pinned }));
+ if (attached > 0)
+ notes.push(t('ccAgent.sidebar.bulkSelection.skipAttached', { count: attached }));
+ return notes;
+ };
+ const skipSep = t('ccAgent.sidebar.archiveAll.skipSeparator');
+ const skipNotes = skipNotesFor(skippedRunning, skippedPinned, skippedAttached);
if (candidates.length === 0) {
- if (skippedPinned > 0 && skippedRunning > 0) {
+ if (skippedAttached > 0) {
+ toast.warning(t('ccAgent.sidebar.archiveAll.skipped', { skip: skipNotes.join(skipSep) }));
+ } else if (skippedPinned > 0 && skippedRunning > 0) {
toast.warning(t(`ccAgent.sidebar.${archiveCopy}.allPinnedOrRunning`));
} else if (skippedPinned > 0) {
toast.warning(t(`ccAgent.sidebar.${archiveCopy}.allPinned`));
@@ -150,12 +210,6 @@ export function useSessionGroupArchive({
const scheduleWarning = await archiveScheduleWarningMany(t, candidates);
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`, {
@@ -183,11 +237,23 @@ export function useSessionGroupArchive({
// 失败的 id 收集起来,最后统一 toast;其余继续走完,不让一条失败拖累整批。
const failed: string[] = [];
+ const succeededIds = new Set<string>();
+ let newlyRunning = 0;
+ let newlyAttached = 0;
for (const s of candidates) {
- // 关掉 SDK subprocess + 清 in-memory state,与单条 archive 行为一致
- makerChatStore.closeSessionQuery(s.id);
try {
- await sessionService.setStatus(s.id, 'archived');
+ const statusWriteTarget = await sessionService.resolveStatusWriteTarget(s.id);
+ // Confirmation, earlier writes and target resolution can outlive preflight.
+ // No further asynchronous preparation may precede closing this query.
+ const reason = await archiveBlockReason(s.id);
+ if (reason) {
+ if (reason === 'attached') newlyAttached++;
+ else newlyRunning++;
+ continue;
+ }
+ makerChatStore.closeSessionQuery(s.id);
+ await sessionService.setStatus(s.id, 'archived', statusWriteTarget);
+ succeededIds.add(s.id);
// 写入后同步各状态桶,再清理该任务的运行视图与草稿。
patchLocal(s.id, { status: 'archived', pinnedAt: null });
makerChatStore.purgeSession(s.id);
@@ -198,9 +264,6 @@ export function useSessionGroupArchive({
}
}
- 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
@@ -209,9 +272,9 @@ export function useSessionGroupArchive({
navigate('/cc-agent');
}
- if (failed.length === 0) {
+ if (failed.length === 0 && succeededIds.size > 0) {
toast.success(t('ccAgent.sidebar.archiveAll.archived', { count: succeededIds.size }));
- } else {
+ } else if (failed.length > 0) {
toast.error(
t('ccAgent.sidebar.archiveAll.partialFailure', {
ok: succeededIds.size,
@@ -219,6 +282,12 @@ export function useSessionGroupArchive({
}),
);
}
+ const lateSkipNotes = skipNotesFor(newlyRunning, 0, newlyAttached);
+ if (lateSkipNotes.length > 0) {
+ toast.warning(
+ t('ccAgent.sidebar.archiveAll.skipped', { skip: lateSkipNotes.join(skipSep) }),
+ );
+ }
},
[
sessions,
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
index e6a7de2825..b3f89c90ca 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
@@ -78,7 +78,8 @@ export function getEntryActivityMs(entry: SidebarSessionEntry): number {
return entry.group.sessions.reduce((max, s) => Math.max(max, sessionActivityMs(s)), 0);
}
-export type AutomationScheduleAction = 'run' | 'edit' | 'toggle-pause' | 'delete' | 'mark-read';
+export type AutomationScheduleAction =
+ 'run' | 'edit' | 'toggle-pause' | 'delete' | 'mark-read' | 'archive-all';
interface ScopedAutomationGroupKey {
key: string;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index bb017afd68..41fe3c0090 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -819,6 +819,17 @@ export const AutomationSessionGroupItem = withSidebarNavigation<AutomationSessio
{!isRemoteGroup && (
<>
<DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => onScheduleAction(group, 'archive-all')}
+ disabled={
+ !group.sessions.some(
+ (session) => session.status === 'active',
+ )
+ }
+ className={MENU_ITEM_CLASS}
+ >
+ {t('ccAgent.sidebar.projectAction.archivedAll')}
+ </DropdownMenuItem>
<DropdownMenuItem
onSelect={() => onScheduleAction(group, 'delete')}
disabled={
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx
index 27b163118a..ab7cf7ed12 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx
@@ -19,6 +19,10 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
+import type {
+ AutomationScheduleAction,
+ AutomationSessionGroup,
+} from '../../lib/automationSidebarGrouping';
import { addSessionAttention, clearSessionAttention } from '@/lib/sessionAttentionStore';
import {
applyRemoteSessionActivity,
@@ -57,8 +61,16 @@ vi.mock('@/components/ui/tooltip', () => ({
vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => children,
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => children,
- DropdownMenuContent: () => null,
- DropdownMenuItem: () => null,
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuItem: ({
+ children,
+ onSelect,
+ disabled,
+ }: {
+ children: React.ReactNode;
+ onSelect?: () => void;
+ disabled?: boolean;
+ }) => createElement('button', { role: 'menuitem', onClick: onSelect, disabled }, children),
DropdownMenuSeparator: () => null,
}));
@@ -117,12 +129,16 @@ function GroupHarness({
urgentSessionIds,
initialCollapsed,
onSessionClick = noop,
+ onScheduleAction = noop,
+ deviceLinkDeviceId,
}: {
sessions: Session[];
notifications: string[];
urgentSessionIds: ReadonlySet<string>;
initialCollapsed: boolean;
onSessionClick?: (sessionId: string) => void;
+ onScheduleAction?: (group: AutomationSessionGroup, action: AutomationScheduleAction) => void;
+ deviceLinkDeviceId?: string;
}) {
const [collapsed, setCollapsed] = useState(initialCollapsed);
return createElement(SessionAttentionUrgencyProvider, {
@@ -132,6 +148,7 @@ function GroupHarness({
id: 'schedule:sched-1',
scheduleId: 'sched-1',
scheduleStatus: 'active',
+ deviceLinkDeviceId,
title: '产品决策巡检',
sessions,
attentionSessionIds: notifications,
@@ -145,7 +162,7 @@ function GroupHarness({
onAction: noop,
onRename: noop,
onTogglePin: noop,
- onScheduleAction: noop,
+ onScheduleAction,
}),
});
}
@@ -190,6 +207,47 @@ beforeEach(() => {
});
describe('AutomationSessionGroupItem — 收起态的未处理告警', () => {
+ // Feature regression (unit): the actual group menu must dispatch all members,
+ // even while collapsed. Existing alert tests do not exercise menu actions.
+ // Minimal input: two hidden runs; remote and archived-only groups cannot archive.
+ // Standalone validation: Vitest 2.71s, tests 159ms (2026-10-27).
+ it.each(['local', 'remote', 'archived'] as const)(
+ 'offers bulk archive only for active local groups (%s)',
+ (kind) => {
+ const onScheduleAction = vi.fn();
+ const sessions = RUNS.slice(0, 2).map((run) => ({
+ ...run,
+ status: kind === 'archived' ? ('archived' as const) : ('active' as const),
+ }));
+ const { container } = render(
+ createElement(GroupHarness, {
+ sessions,
+ notifications: [],
+ urgentSessionIds: new Set<string>(),
+ initialCollapsed: true,
+ onScheduleAction,
+ deviceLinkDeviceId: kind === 'remote' ? 'other-computer' : undefined,
+ }),
+ );
+ expect(childRunIds(container)).toEqual([]);
+ const menuItem = screen.queryByRole('menuitem', {
+ name: 'ccAgent.sidebar.projectAction.archivedAll',
+ });
+ if (kind === 'remote') {
+ expect(menuItem).toBeNull();
+ } else {
+ expect(menuItem).not.toBeNull();
+ fireEvent.click(menuItem!);
+ if (kind === 'archived') expect(onScheduleAction).not.toHaveBeenCalled();
+ else
+ expect(onScheduleAction).toHaveBeenCalledWith(
+ expect.objectContaining({ sessions }),
+ 'archive-all',
+ );
+ }
+ },
+ );
+
it('无告警时收起就是收起:组头不点状态、不渲染子行', () => {
const { container } = renderGroup();
expect(childRunIds(container)).toEqual([]);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 946fbe7e8b..f98013c7db 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -13103,6 +13103,14 @@
"description": "Restore {{count}} archived sessions in this chat group? They will move from Archived to Active.",
"empty": "No archived sessions in this chat group can be restored"
},
+ "automationArchiveAll": {
+ "description": "Archive {{count}} sessions created by this automation. The automation will continue to run as scheduled.",
+ "descriptionWithSkip": "Archive {{count}} sessions created by this automation, skipping {{skip}} sessions. The automation will continue to run as scheduled.",
+ "allPinnedOrRunning": "All sessions from this automation are pinned or running. Nothing to archive.",
+ "allPinned": "All sessions from this automation are pinned. Nothing to archive.",
+ "allRunning": "All sessions from this automation are running. Nothing to archive yet.",
+ "empty": "This automation has no sessions to archive."
+ },
"archiveAll": {
"title": "Archive all sessions",
"confirm": "Archive all",
@@ -13112,6 +13120,7 @@
"skipRunning": "{{count}} running",
"skipPinned": "{{count}} pinned",
"skipSeparator": ", ",
+ "skipped": "Skipped {{skip}} sessions",
"archived_one": "Archived {{count}} session",
"archived_other": "Archived {{count}} sessions",
"partialFailure": "Archived {{ok}}, {{fail}} failed, please retry",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4f6beedfe0..0de26711f0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -13049,6 +13049,14 @@
"description": "この「会話」グループのアーカイブ済みセッション {{count}} 件を復元します。復元後は「アーカイブ済み」から「アクティブ」に移動します。",
"empty": "この「会話」グループに復元できるセッションはありません"
},
+ "automationArchiveAll": {
+ "description": "この自動化で作成された {{count}} 件のセッションをアーカイブします。自動化は引き続き予定どおり実行されます。",
+ "descriptionWithSkip": "この自動化で作成された {{count}} 件のセッションをアーカイブし、{{skip}}のセッションはスキップします。自動化は引き続き予定どおり実行されます。",
+ "allPinnedOrRunning": "この自動化のセッションはすべてピン留め済みまたは実行中のため、アーカイブできません",
+ "allPinned": "この自動化のセッションはすべてピン留め済みのため、アーカイブしません",
+ "allRunning": "この自動化のセッションはすべて実行中のため、今はアーカイブできません",
+ "empty": "この自動化にはアーカイブできるセッションがありません"
+ },
"archiveAll": {
"title": "すべてのセッションをアーカイブ",
"confirm": "すべてアーカイブ",
@@ -13058,6 +13066,7 @@
"skipRunning": "{{count}} 件は実行中",
"skipPinned": "{{count}} 件はピン留め",
"skipSeparator": "、",
+ "skipped": "{{skip}}のセッションをスキップしました",
"archived_one": "{{count}} 件のセッションをアーカイブしました",
"archived_other": "{{count}} 件のセッションをアーカイブしました",
"partialFailure": "{{ok}} 件アーカイブ、{{fail}} 件失敗。再試行してください",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index df8840ac90..39180e4037 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -13049,6 +13049,14 @@
"description": "이 대화 그룹의 보관된 세션 {{count}}개를 복원합니다. 복원 후 '보관됨' 목록에서 '활성' 목록으로 이동합니다.",
"empty": "이 대화 그룹에 복원할 수 있는 세션이 없습니다"
},
+ "automationArchiveAll": {
+ "description": "이 자동화가 만든 세션 {{count}}개를 보관합니다. 자동화는 계속 예정대로 실행됩니다.",
+ "descriptionWithSkip": "이 자동화가 만든 세션 {{count}}개를 보관하며, {{skip}} 세션은 건너뜁니다. 자동화는 계속 예정대로 실행됩니다.",
+ "allPinnedOrRunning": "이 자동화의 세션이 모두 고정되었거나 실행 중이므로 보관할 항목이 없습니다",
+ "allPinned": "이 자동화의 세션이 모두 고정되어 있어 보관하지 않습니다",
+ "allRunning": "이 자동화의 세션이 모두 실행 중이므로 지금은 보관할 항목이 없습니다",
+ "empty": "이 자동화에는 보관할 세션이 없습니다"
+ },
"archiveAll": {
"title": "모든 세션 보관",
"confirm": "모두 보관",
@@ -13058,6 +13066,7 @@
"skipRunning": "{{count}}개 실행 중",
"skipPinned": "{{count}}개 고정됨",
"skipSeparator": ", ",
+ "skipped": "{{skip}} 세션을 건너뛰었습니다",
"archived_one": "{{count}}개 세션을 보관했습니다",
"archived_other": "{{count}}개 세션을 보관했습니다",
"partialFailure": "{{ok}}개 보관, {{fail}}개 실패. 다시 시도하세요",
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 527c8e1ccc..838822890e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -13049,6 +13049,14 @@
"description": "将恢复此对话组内 {{count}} 个已归档任务。恢复后将从“已归档”列表移除,并回到“活跃”列表。",
"empty": "此对话组内没有可恢复的任务"
},
+ "automationArchiveAll": {
+ "description": "将归档此自动化生成的 {{count}} 个任务。自动化仍会按计划运行。",
+ "descriptionWithSkip": "将归档此自动化生成的 {{count}} 个任务,跳过{{skip}}的任务。自动化仍会按计划运行。",
+ "allPinnedOrRunning": "此自动化的任务全部已置顶或在运行中,无可归档项",
+ "allPinned": "此自动化的任务全部已置顶,不会归档",
+ "allRunning": "此自动化的任务全部在运行中,暂无可归档项",
+ "empty": "此自动化没有可归档的任务"
+ },
"archiveAll": {
"title": "归档全部任务",
"confirm": "归档全部",
@@ -13058,6 +13066,7 @@
"skipRunning": "{{count}} 个运行中",
"skipPinned": "{{count}} 个已置顶",
"skipSeparator": "、",
+ "skipped": "已跳过{{skip}}的任务",
"archived_one": "已归档 {{count}} 个任务",
"archived_other": "已归档 {{count}} 个任务",
"partialFailure": "已归档 {{ok}} 个,{{fail}} 个失败,请重试",
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 9a36a0369a..d2f5a4c5df 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -13049,6 +13049,14 @@
"description": "將恢復此對話群組內 {{count}} 個已歸檔任務。恢復後將從「已歸檔」列表移除,並回到「活躍」列表。",
"empty": "此對話群組內沒有可恢復的任務"
},
+ "automationArchiveAll": {
+ "description": "將歸檔此自動化產生的 {{count}} 個任務。自動化仍會按排程執行。",
+ "descriptionWithSkip": "將歸檔此自動化產生的 {{count}} 個任務,略過{{skip}}的任務。自動化仍會按排程執行。",
+ "allPinnedOrRunning": "此自動化的任務全部已置頂或正在執行,無可歸檔項目",
+ "allPinned": "此自動化的任務全部已置頂,不會歸檔",
+ "allRunning": "此自動化的任務全部正在執行,暫無可歸檔項目",
+ "empty": "此自動化沒有可歸檔的任務"
+ },
"archiveAll": {
"title": "歸檔全部任務",
"confirm": "歸檔全部",
@@ -13058,6 +13066,7 @@
"skipRunning": "{{count}} 個執行中",
"skipPinned": "{{count}} 個已置頂",
"skipSeparator": "、",
+ "skipped": "已略過{{skip}}的任務",
"archived_one": "已歸檔 {{count}} 個任務",
"archived_other": "已歸檔 {{count}} 個任務",
"partialFailure": "已歸檔 {{ok}} 個,{{fail}} 個失敗,請重試",