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。

Merge main and preserve workbench archive guards

Chris1f59dfb10d25
diff --cc apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionActions.test.tsx
index bbb40af715,35d6eedce0..cf63aec766
--- a/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionActions.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionActions.test.tsx
@@@ -16,15 -14,34 +16,17 @@@ const m = vi.hoisted(() => (
attached: new Set<string>(),
changed: vi.fn(),
warning: vi.fn(),
+ error: vi.fn(),
+ archiveBlockedByRunning: vi.fn(),
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s }) }));
vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));
-vi.mock('@/features/cc-agent/sidebar/SessionCard', () => ({
- SessionCard: (p: any) => (
- <div data-testid="native-row" data-variant={p.variant} data-status={p.session.status}>
- <button onClick={() => p.onClick(p.session.id)}>open</button>
- <button onClick={() => p.onAction(p.session.id, 'unarchive')}>restore</button>
- <button onClick={() => p.onAction(p.session.id, 'archive', 'shared')}>archive</button>
- </div>
- ),
-}));
vi.mock('@/features/cc-agent/hooks/useSessionLifecycleActions', () => ({
- useSessionLifecycleActions: () => ({ runSessionAction: m.run, unarchiveSession: m.unarchive }),
- useSessionLifecycleActions: () => ({
- runSessionAction: m.run, unarchiveSession: m.unarchive,
- archiveBlockedByRunning: m.archiveBlockedByRunning,
- }),
-}));
-vi.mock('@/features/cc-agent/hooks/useSessionDisplayRunningState', () => ({
- useSessionDisplayRunningState: () => ({ displayRunningSessionIds: m.running }),
++ useSessionLifecycleActions: () => ({ runSessionAction: m.run, unarchiveSession: m.unarchive,
++ archiveBlockedByRunning: m.archiveBlockedByRunning }),
}));
vi.mock('@/hooks/useSessionRunningStatus', () => ({
- useSessionRunningStatus: () => ({
- runningSessionIds: m.running,
- notifications: new Set(),
- clearNotification: vi.fn(),
- }),
+ useSessionRunningStatus: () => ({ runningSessionIds: m.running, clearNotification: vi.fn() }),
}));
vi.mock('@/hooks/useAttachedSessionIds', () => ({ useAttachedSessionIds: () => m.attached }));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
@@@ -69,10 -83,24 +76,29 @@@ beforeEach(() =>
});
});
afterEach(cleanup);
+
+ it.each(['clean', 'dirty', 'unknown'])('keeps sharing when a task starts during %s preflight or confirmation', async (preflight) => {
+ let finish!: (value: any) => void;
+ const pending = new Promise((resolve) => { finish = resolve; });
+ m.preflight.mockReturnValue(preflight === 'clean' ? pending : Promise.resolve(preflight));
+ m.confirm.mockReturnValue(pending);
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- fireEvent.click(screen.getByText('archive'));
++ const result = setup();
++ let action!: Promise<void>;
++ act(() => { action = result.current.action('live', 'archive', 'shared'); });
+ await waitFor(() => expect(preflight === 'clean' ? m.preflight : m.confirm).toHaveBeenCalled());
- m.running.add('original');
- finish(preflight === 'clean' ? 'clean' : true);
- await waitFor(() => expect(m.warning).toHaveBeenCalledWith('ccAgent.sidebar.archiveBlocked.running'));
++ m.running.add('live');
++ await act(async () => {
++ finish(preflight === 'clean' ? 'clean' : true);
++ await action;
++ });
++ expect(m.warning).toHaveBeenCalledWith('ccAgent.sidebar.archiveBlocked.running');
+ expect(m.close).not.toHaveBeenCalled();
+ expect(m.run).not.toHaveBeenCalled();
+ });
-it('opens the original archived session through the native row without restoring it', async () => {
- render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);
- expect(screen.getByTestId('native-row').getAttribute('data-variant')).toBe('list');
- fireEvent.click(screen.getByText('open'));
++
+it('opens the original archived session in the task page without restoring it', async () => {
+ const result = setup();
+ act(() => result.current.open('original'));
await waitFor(() => expect(m.navigate).toHaveBeenCalledWith('/cc-agent/original'));
expect(m.unarchive).not.toHaveBeenCalled();
expect(m.run).not.toHaveBeenCalled();
diff --cc apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts
index a249ceda08,0000000000..d86f71f02b
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts
+++ b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts
@@@ -1,127 -1,0 +1,125 @@@
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import type { Session } from '@/lib/ccAgent.types';
+import { useSessionLifecycleActions } from '@/features/cc-agent/hooks/useSessionLifecycleActions';
+import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
+import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { resolveWorktreeRemovalPreflight } from '@/lib/worktreeRemovalWarning';
+import { sessionsStore } from '@/lib/sessionsStore';
+import * as service from '@/lib/sessionService';
+import { isRemoteSessionWriteBlocked } from '@/features/cc-agent/lib/remoteSessionWriteGuard';
+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { persistManualPinnedOrder } from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';
+import { toast } from '@/lib/toast';
+
+export type WorkbenchSessionActionKind = 'archive' | 'unarchive' | 'delete';
+
+/**
+ * 工作台条目「…」里的任务操作:与任务侧栏同一套生命周期 API 与守卫(运行中 / 被终端占用时
+ * 不归档、worktree 有改动或未知时先确认、共享任务先关闭共享),本身不持有任何任务状态。
+ * 打开只是看,不恢复归档;恢复只走明确的「恢复」。
+ */
+export function useWorkbenchSessionActions(sessions: readonly Session[], onChanged: () => void) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { confirm } = useConfirmDialog();
- const { runningSessionIds, clearNotification } = useSessionRunningStatus(undefined);
++ const { clearNotification } = useSessionRunningStatus(undefined);
+ const attached = useAttachedSessionIds();
- const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({ includeArchived: 'all' });
++ const { runSessionAction, unarchiveSession, archiveBlockedByRunning } = useSessionLifecycleActions({ includeArchived: 'all' });
+ const byId = useMemo(() => new Map(sessions.map((row) => [row.id, row])), [sessions]);
+
+ const open = useCallback(
+ (id: string) => {
+ clearNotification(id);
+ void resolveSessionRoute(id, byId.get(id)).then((route) => navigate(route));
+ },
+ [byId, clearNotification, navigate],
+ );
+
+ const action = useCallback(
+ async (id: string, kind: WorkbenchSessionActionKind, sharedTaskId?: string) => {
+ try {
+ if (isRemoteSessionWriteBlocked(byId.get(id))) {
+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
+ return;
+ }
+ if (kind === 'unarchive') {
+ await unarchiveSession(id);
+ onChanged();
+ return;
+ }
+ const archive = kind === 'archive';
- if (archive && runningSessionIds.has(id)) {
- toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));
- return;
- }
++ if (archive && archiveBlockedByRunning(id, byId.get(id)?.deviceLinkDeviceId)) return;
+ if (
+ archive &&
+ (attached.has(id) ||
+ (await window.electronAPI.binding.resolveSession(id).catch(() => ({ attached: false }))).attached)
+ ) {
+ toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));
+ return;
+ }
+ const preflight = await resolveWorktreeRemovalPreflight(id, byId.get(id)?.deviceLinkDeviceId);
+ const prefix = archive ? 'ccAgent.sidebar.confirmArchive' : 'ccAgent.sidebar.confirmDelete';
+ if (
+ (!archive || preflight !== 'clean') &&
+ !(await confirm({
+ title: t(prefix + '.title'),
+ description:
+ t(prefix + '.description') + (preflight === 'dirty' ? ' ' + t(prefix + '.dirtyWorktreeWarning') : ''),
+ confirmText: t(prefix + '.confirm'),
+ cancelText: t(prefix + '.cancel'),
+ }))
+ )
+ return;
++ if (archive && archiveBlockedByRunning(id, byId.get(id)?.deviceLinkDeviceId)) return;
+ if (sharedTaskId) {
+ const result = (await window.electronAPI.sharedTask.account({ action: 'close', sharedTaskId })) as {
+ closed?: string[];
+ };
+ if (!result.closed?.includes(sharedTaskId)) {
+ toast.error(t('sharedTask.closeFailedToast', { count: 1 }));
+ return;
+ }
+ }
+ await runSessionAction(id, archive ? 'archive' : 'delete', { activeSessionId: null });
+ onChanged();
+ } catch {
+ toast.error(t(kind === 'delete' ? 'ccAgent.sidebar.deleteFailed' : 'ccAgent.sidebar.archiveFailed'));
+ }
+ },
- [byId, attached, confirm, onChanged, runSessionAction, runningSessionIds, t, unarchiveSession],
++ [byId, attached, confirm, onChanged, runSessionAction, archiveBlockedByRunning, t, unarchiveSession],
+ );
+
+ const togglePin = useCallback(
+ async (id: string) => {
+ const row = byId.get(id);
+ if (!row) return;
+ if (isRemoteSessionWriteBlocked(row)) {
+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
+ return;
+ }
+ const pinned = Boolean(row.pinnedAt);
+ const owner = getDataOwnerGeneration();
+ try {
+ const patch = { pinnedAt: pinned ? null : new Date().toISOString() };
+ await service.patchMeta(id, patch);
+ sessionsStore.patchLocal(id, pinned ? { ...patch, summary: null } : patch);
+ if (!pinned) {
+ await persistManualPinnedOrder(
+ { kind: 'promote', entryId: id },
+ { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },
+ );
+ }
+ onChanged();
+ } catch {
+ toast.error(t('ccAgent.sidebar.pinFailed'));
+ }
+ },
+ [byId, onChanged, t],
+ );
+
+ return { open, action, togglePin, byId };
+}