Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 关闭共享前复核归档运行状态
Dashaa9780110399
diff --git a/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx b/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsxindex d8d9377a39..d1df01e008 100644--- a/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx+++ b/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx@@ -34,7 +34,7 @@ export function WorkbenchSessionList({useSessionRunningStatus(undefined);const attached = useAttachedSessionIds();const { displayRunningSessionIds } = useSessionDisplayRunningState(sessions, runningSessionIds);- const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({+ const { runSessionAction, unarchiveSession, archiveBlockedByRunning } = useSessionLifecycleActions({includeArchived: 'all',});const byId = useMemo(() => new Map(sessions.map((row) => [row.id, row])), [sessions]);@@ -62,10 +62,7 @@ export function WorkbenchSessionList({return;}const archive = kind !== 'delete';- 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) ||@@ -92,6 +89,7 @@ export function WorkbenchSessionList({})))return;+ if (archive && archiveBlockedByRunning(id, byId.get(id)?.deviceLinkDeviceId)) return;if (sharedTaskId) {const result = (await window.electronAPI.sharedTask.account({action: 'close',@@ -110,7 +108,7 @@ export function WorkbenchSessionList({);}},- [byId, attached, confirm, onChanged, runSessionAction, runningSessionIds, t, unarchiveSession],+ [byId, attached, confirm, onChanged, runSessionAction, archiveBlockedByRunning, t, unarchiveSession],);const rename = useCallback(async (id: string, title: string) => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsxindex da5d6a46a0..35d6eedce0 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx@@ -14,6 +14,7 @@ const m = vi.hoisted(() => ({attached: new Set<string>(),changed: vi.fn(),warning: vi.fn(),+ archiveBlockedByRunning: vi.fn(),}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s }) }));vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));@@ -27,7 +28,10 @@ vi.mock('@/features/cc-agent/sidebar/SessionCard', () => ({),}));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 }),@@ -63,6 +67,11 @@ const row = {beforeEach(() => {vi.clearAllMocks();m.running = new Set();+ m.archiveBlockedByRunning.mockImplementation((id: string) => {+ if (!m.running.has(id)) return false;+ m.warning('ccAgent.sidebar.archiveBlocked.running');+ return true;+ });m.attached = new Set();m.confirm.mockResolvedValue(true);m.preflight.mockResolvedValue('clean');@@ -74,6 +83,20 @@ 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'));+ 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'));+ 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');diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex b9fe7a13e3..ec374ce56e 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -3009,7 +3009,7 @@ function ExpandedView({*/// includeArchived 跟随当前列表桶(filter.status)—— archived / all 桶里// 删除后要刷对应桶,否则已删行残留(见 hook 文件头注释)。- const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({+ const { runSessionAction, unarchiveSession, archiveBlockedByRunning } = useSessionLifecycleActions({includeArchived: filter.status,});@@ -3044,10 +3044,7 @@ function ExpandedView({}const isArchiveLike = action === 'archive' || action === 'archive-now';// 执行中的 session 不允许归档 —— 让用户先停下当前任务- if (isArchiveLike && runningSessionIds.has(sessionId)) {- toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));- return;- }+ if (isArchiveLike && archiveBlockedByRunning(sessionId, session?.deviceLinkDeviceId)) return;// 被 IM 接管中的 session 不允许归档 —— 接管方还在操控,先收回再归档。// sidebar 常驻订阅的 attached 集合与 binding:resolve-session 同源// (binding:list-attached = 全量 resolve, binding:changed 驱动 refresh),@@ -3113,6 +3110,8 @@ function ExpandedView({// 重定向判定用 viewedSessionId:files 路由下归档「正在浏览的会话」也要// 跳离失效的文件视图(codex review;正常路由下两者恒等)。经 ref 读:它随// 路由切换而变,留在 deps 里会让本 handler 每次切换都重建、打穿整表 memo。+ // Preflight may have outlived the idle state; sharing must stay open when blocked.+ if (archiveBlockedByRunning(sessionId, session?.deviceLinkDeviceId)) return;if (!(await closeOwnedSharedTask(sharedTaskId))) {return;}@@ -3140,7 +3139,7 @@ function ExpandedView({},[closeOwnedSharedTask,- runningSessionIds,+ archiveBlockedByRunning,runSessionAction,unarchiveSession,t,@@ -3155,6 +3154,10 @@ function ExpandedView({setConfirm(CONFIRM_INITIAL);return;}+ if (action === 'archive' && archiveBlockedByRunning(sessionId, session?.deviceLinkDeviceId)) {+ setConfirm(CONFIRM_INITIAL);+ return;+ }if (!(await closeOwnedSharedTask(sharedTaskId))) {return;}@@ -3170,7 +3173,7 @@ function ExpandedView({deleteRedirectRoute,});setConfirm(CONFIRM_INITIAL);- }, [closeOwnedSharedTask, viewedSessionId, confirm, resolveSessionRemovalRedirect, runSessionAction, sessionsById, t]);+ }, [closeOwnedSharedTask, archiveBlockedByRunning, viewedSessionId, confirm, resolveSessionRemovalRedirect, runSessionAction, sessionsById, t]);const handleCancelConfirm = useCallback(() => {setConfirm(CONFIRM_INITIAL);diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.tsindex fc28cc4c91..b897baa4d4 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts@@ -27,20 +27,23 @@ function harness(result: unknown, reject = false, sharedTaskId: string | undefinconst runSessionAction = vi.fn();const setConfirm = vi.fn();const toast = { error: vi.fn(), warning: vi.fn() };- const session = { id: 'task' };+ const session = { id: 'task', deviceLinkDeviceId: 'device-1' };+ const archiveBlockedByRunning = vi.fn(() => false);+ const preflight = vi.fn(async () => 'clean');const bindings = {window: { electronAPI: { sharedTask: { account }, binding: { resolveSession: async () => ({ attached: false }) } } },toast, t: (key: string) => key, sharedTaskErrorKey: () => 'sharedTask.retry',sessionsById: new Map([['task', session]]), sessionsByIdRef: { current: new Map([['task', session]]) },runningSessionIds: new Set(), attachedSessionIdsRef: { current: new Set() },- isRemoteSessionWriteBlocked: () => false, resolveWorktreeRemovalPreflight: async () => 'clean',+ isRemoteSessionWriteBlocked: () => false, resolveWorktreeRemovalPreflight: preflight,+ archiveBlockedByRunning,viewedSessionIdRef: { current: 'other' }, viewedSessionId: 'other',resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },};const closeOwnedSharedTask = callback('closeOwnedSharedTask', bindings);return {- account, runSessionAction, toast, setConfirm,+ account, runSessionAction, toast, setConfirm, archiveBlockedByRunning, preflight,archive: () => callback('handleActionClick', { ...bindings, closeOwnedSharedTask })('task', 'archive', sharedTaskId),confirm: (action: string) => callback('handleConfirm', { ...bindings, closeOwnedSharedTask,confirm: { sessionId: 'task', action, sharedTaskId },@@ -49,6 +52,32 @@ function harness(result: unknown, reject = false, sharedTaskId: string | undefin}describe('sidebar shared-task archive/delete guard', () => {+ it.each(['clean', 'dirty', 'unknown'])('preserves sharing when a task starts during %s preflight or confirmation', async (preflight) => {+ const h = harness({ closed: ['share'] });+ const pending = deferred<string>();+ h.preflight.mockReturnValueOnce(pending.promise);+ const archive = h.archive();+ await vi.waitFor(() => expect(h.preflight).toHaveBeenCalled());+ if (preflight === 'clean') h.archiveBlockedByRunning.mockReturnValue(true);+ pending.resolve(preflight);+ await archive;+ if (preflight !== 'clean') {+ expect(h.setConfirm).toHaveBeenCalledWith(expect.objectContaining({ open: true, sharedTaskId: 'share' }));+ h.archiveBlockedByRunning.mockReturnValue(true);+ await h.confirm('archive');+ }+ expect(h.archiveBlockedByRunning).toHaveBeenLastCalledWith('task', 'device-1');+ expect(h.account).not.toHaveBeenCalled();+ expect(h.runSessionAction).not.toHaveBeenCalled();+ });+ it('keeps confirmed deletion independent from the archive running guard', async () => {+ const h = harness({ closed: ['share'] });+ h.archiveBlockedByRunning.mockReturnValue(true);+ await h.confirm('delete');+ expect(h.archiveBlockedByRunning).not.toHaveBeenCalled();+ expect(h.account).toHaveBeenCalledOnce();+ expect(h.runSessionAction).toHaveBeenCalledWith('task', 'delete', expect.anything());+ });it.each(['archive', 'confirmed-archive', 'delete'])('blocks %s on a resolved close failure', async (action) => {const h = harness({ closed: [], failed: [{ sharedTaskId: 'share' }] });if (action === 'archive') await h.archive();@@ -123,6 +152,7 @@ describe('archive preserves the current task until preflight and confirmation firunSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },beginRemoteArchive, cancelRemoteArchive: vi.fn(),closeOwnedSharedTask: async () => true,+ archiveBlockedByRunning: () => false,confirm: { sessionId: 'task', action: 'archive' },session, sessionId: session.id, deviceLinkDeviceId: session.deviceLinkDeviceId,confirmDialog,diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsxindex 4254420bbb..4fdf73ce6f 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx@@ -144,6 +144,19 @@ beforeEach(() => {});describe('archive uses current state after asynchronous checks', () => {+ it('shares a live running guard with callers before they close sharing', () => {+ const { result } = renderHook(() => useSessionLifecycleActions());+ const guard = result.current.archiveBlockedByRunning;+ expect(guard('session-1', 'device-1')).toBe(false);+ mocks.getRunningSnapshot.mockReturnValue(new Map([['session-1', { isRunning: true }]]));+ expect(guard('session-1')).toBe(true);+ mocks.getRunningSnapshot.mockReturnValue(new Map());+ applyRemoteSessionActivity('device-1', { sessionId: 'session-1', phase: 'needs-interaction' });+ expect(guard('session-1', 'device-1')).toBe(true);+ expect(guard('session-1', 'other-device')).toBe(false);+ clearRemoteSessionActivity();+ expect(guard('session-1', 'device-1')).toBe(false);+ });it.each(['local', 'device-link'] as const)('does not interrupt a newly running %s task', async (kind) => {let finishTarget!: (target: unknown) => void;mocks.resolveStatusWriteTarget.mockImplementationOnce(() => new Promise((resolve) => {diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.tsindex bf94030403..94b3136d42 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts@@ -7,7 +7,8 @@** 本 hook 只封装"确认之后的执行序列"(关子进程 / 写库 / 乐观补丁 / 释放内存 /* 清 composer draft / refresh 列表与 worktree / 必要时跳转)。**前置检查- * (running / IM 接管拦截)和确认弹窗留在调用方** —— 两处的确认交互形态不同+ * (IM 接管拦截)和确认弹窗留在调用方**;运行态判据由本 hook 统一提供,+ * 调用方在关闭共享前复用,执行层在异步等待后复核。两处的确认交互形态不同* (sidebar 是受控 ConfirmDialog + 行内两步确认,header 是 imperative* confirmDialog),强行收进来反而耦合。*@@ -98,6 +99,14 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta// (行渲染隔离不变量,见 SessionItem.tsx)。const listFilter: ListStatusFilter = options?.includeArchived ?? 'active';+ // Read stores at the side-effect boundary, never the render-time running set.+ const archiveBlockedByRunning = useCallback((sessionId: string, deviceId?: string | null) => {+ const running = makerChatStore.getRunningSnapshot().get(sessionId)?.isRunning ||+ (deviceId && isRemoteSessionActivityActive(getRemoteSessionActivity(sessionId, deviceId)));+ if (running) toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));+ return Boolean(running);+ }, [t]);+/*** 远程任务归档的乐观起点:叠加层把行移出 active 桶,并按 runSessionAction 同一顺序* 跳离(行留在列表时先跳再换桶,否则先换桶再跳,理由见下方 archive 段注释)。@@ -140,15 +149,8 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListStaconst statusWriteTarget = await sessionService.resolveStatusWriteTarget(sessionId);const isDeviceLinkSession = statusWriteTarget.kind === 'device-link';// Preflight/confirmation and write-target resolution may outlive the initial running check.- const archiveBlockedByRunning = () => {- const running = makerChatStore.getRunningSnapshot().get(sessionId)?.isRunning ||- (statusWriteTarget.kind === 'device-link' && isRemoteSessionActivityActive(- getRemoteSessionActivity(sessionId, statusWriteTarget.deviceId),- ));- if (running) toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));- return Boolean(running);- };- if (action === 'archive' && archiveBlockedByRunning()) return;+ const deviceId = statusWriteTarget.kind === 'device-link' ? statusWriteTarget.deviceId : undefined;+ if (action === 'archive' && archiveBlockedByRunning(sessionId, deviceId)) return;let statusTransition: SessionStatusTransitionToken | null = null;// device-link 远程会话:status 写经隧道(setStatus 内部按来源路由 patch-meta)。归档走// remoteProjectsStore 的状态迁移叠加层乐观换桶,写库成功即落被控端返回的行,不等@@ -195,7 +197,7 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta},(begin) => {// A previous local status write can keep us waiting after the check above.- if (archiveBlockedByRunning()) return null;+ if (archiveBlockedByRunning(sessionId, deviceId)) return null;if (archivedRowStaysInList) flushSync(leaveArchivedSession);let transition: SessionStatusTransitionToken | null = null;flushSync(() => {@@ -302,7 +304,7 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListStanavigate(deleteRedirectRoute ?? '/cc-agent');}},- [navigate, patchLocal, listFilter, beginRemoteArchive, t],+ [navigate, patchLocal, listFilter, beginRemoteArchive, archiveBlockedByRunning, t],);/**@@ -342,5 +344,5 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta[refreshSessions, t],);- return { runSessionAction, unarchiveSession };+ return { runSessionAction, unarchiveSession, archiveBlockedByRunning };}