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): 归档确认期间保留当前任务选中状态

Dash2f75d6612c2f
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index c42ae8a87c..b9fe7a13e3 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -208,7 +208,6 @@ import {
getSessionDeviceId,
remoteProjectsStore,
useRemoteScheduleIndex,
- type RemotePendingStatusToken,
} from '@/features/device-link/remoteProjectsStore';
import {
getRemoteSessionActivity,
@@ -1158,10 +1157,6 @@ function ExpandedView({
);
const [confirm, setConfirm] = useState<ConfirmState>(CONFIRM_INITIAL);
- // 远程任务归档确认弹窗期间行已提前隐藏(见 handleActionClick);凭据放 ref 而非 confirm
- // state:确认按钮的 onClick 要先同步认领它,Radix 随后触发的 onOpenChange(false) →
- // handleCancelConfirm 才不会把正在写库的那次归档回滚掉。
- const confirmRemoteArchiveRef = useRef<RemotePendingStatusToken | null>(null);
// 系统级通知触发:sessions 数组每次渲染都新引用,但 callback 读 ref,
// 不会因此重跑 transition effect。通道、失焦与灵动岛去重由共享入口收口。
@@ -3014,21 +3009,9 @@ function ExpandedView({
*/
// includeArchived 跟随当前列表桶(filter.status)—— archived / all 桶里
// 删除后要刷对应桶,否则已删行残留(见 hook 文件头注释)。
- const { runSessionAction, unarchiveSession, beginRemoteArchive, cancelRemoteArchive } =
- useSessionLifecycleActions({
- includeArchived: filter.status,
- });
-
- // 新确认框顶替旧确认框时(两次预检交错返回),旧框提前隐藏的远程任务已无处取消,
- // 先让它回到列表,再登记新框的凭据。
- const replaceConfirmRemoteArchive = useCallback(
- (token: RemotePendingStatusToken | null) => {
- const previous = confirmRemoteArchiveRef.current;
- confirmRemoteArchiveRef.current = token;
- if (previous && previous !== token) cancelRemoteArchive(previous);
- },
- [cancelRemoteArchive],
- );
+ const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({
+ includeArchived: filter.status,
+ });
const closeOwnedSharedTask = useCallback(async (sharedTaskId?: string): Promise<boolean> => {
if (!sharedTaskId) return true;
@@ -3108,13 +3091,7 @@ function ExpandedView({
// (WorktreeManager.removeWorktreeForSession),renderer 这层负责的是「别拿
// 明显过期的结论免掉确认」。
//
- // 远程任务的预检是一次完整隧道往返(被控端跑 git status),不再让用户干等:
- // 先乐观隐藏行并跳离,再等预检。干净 → 沿用同一叠加层直接写库;需要确认 →
- // 行保持隐藏弹确认框,取消再让行回来(已跳离的视图不跳回)。本机任务预检
- // 很快,维持原顺序。
- const remoteArchiveToken = session?.deviceLinkDeviceId
- ? beginRemoteArchive(sessionId, session.deviceLinkDeviceId, viewedSessionIdRef.current)
- : null;
+ // 预检与确认期间保留列表行和当前任务;只有确定归档后才隐藏并跳离。
const preflight = await resolveWorktreeRemovalPreflight(
sessionId,
session?.deviceLinkDeviceId,
@@ -3124,7 +3101,6 @@ function ExpandedView({
// (greptile review)。'unknown' 时不摆 dirty 警告文案 —— 那会谎称有改动,
// 走的是普通归档确认。
if (preflight !== 'clean') {
- replaceConfirmRemoteArchive(remoteArchiveToken);
setConfirm({
open: true,
sessionId,
@@ -3138,12 +3114,10 @@ function ExpandedView({
// 跳离失效的文件视图(codex review;正常路由下两者恒等)。经 ref 读:它随
// 路由切换而变,留在 deps 里会让本 handler 每次切换都重建、打穿整表 memo。
if (!(await closeOwnedSharedTask(sharedTaskId))) {
- if (remoteArchiveToken) cancelRemoteArchive(remoteArchiveToken);
return;
}
await runSessionAction(sessionId, 'archive', {
activeSessionId: viewedSessionIdRef.current,
- remoteArchiveToken,
});
return;
}
@@ -3156,7 +3130,6 @@ function ExpandedView({
'dirty';
// Keep the existing confirm-state shape for the normal delete flow, then attach
// the shared-task scope in a functional update so cancellation still leaves it open.
- replaceConfirmRemoteArchive(null);
setConfirm({ open: true, sessionId, action, dirtyWorktree });
if (sharedTaskId) {
setConfirm((previous) => ({ ...previous, sharedTaskId }));
@@ -3166,10 +3139,7 @@ function ExpandedView({
await unarchiveSession(sessionId);
},
[
- beginRemoteArchive,
- cancelRemoteArchive,
closeOwnedSharedTask,
- replaceConfirmRemoteArchive,
runningSessionIds,
runSessionAction,
unarchiveSession,
@@ -3179,18 +3149,13 @@ function ExpandedView({
const handleConfirm = useCallback(async () => {
const { sessionId, action, sharedTaskId } = confirm;
- // 同步认领提前隐藏的远程归档,见 confirmRemoteArchiveRef。
- const remoteArchiveToken = confirmRemoteArchiveRef.current;
- confirmRemoteArchiveRef.current = null;
const session = sessionsById.get(sessionId);
if (isRemoteSessionWriteBlocked(session)) {
- if (remoteArchiveToken) cancelRemoteArchive(remoteArchiveToken);
toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
setConfirm(CONFIRM_INITIAL);
return;
}
if (!(await closeOwnedSharedTask(sharedTaskId))) {
- if (remoteArchiveToken) cancelRemoteArchive(remoteArchiveToken);
return;
}
// 重定向判定统一用 viewedSessionId(files 路由下 = 被浏览文件的会话,
@@ -3203,18 +3168,13 @@ function ExpandedView({
await runSessionAction(sessionId, action, {
activeSessionId: viewedSessionId,
deleteRedirectRoute,
- remoteArchiveToken,
});
setConfirm(CONFIRM_INITIAL);
- }, [cancelRemoteArchive, closeOwnedSharedTask, viewedSessionId, confirm, resolveSessionRemovalRedirect, runSessionAction, sessionsById, t]);
+ }, [closeOwnedSharedTask, viewedSessionId, confirm, resolveSessionRemovalRedirect, runSessionAction, sessionsById, t]);
const handleCancelConfirm = useCallback(() => {
- // 取消 / 点外部关闭:提前隐藏的远程任务回到列表。
- const remoteArchiveToken = confirmRemoteArchiveRef.current;
- confirmRemoteArchiveRef.current = null;
- if (remoteArchiveToken) cancelRemoteArchive(remoteArchiveToken);
setConfirm(CONFIRM_INITIAL);
- }, [cancelRemoteArchive]);
+ }, []);
const handleBulkDelete = useCallback(async () => {
if (bulkActionPending !== null) return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index f505a72eba..70095ab0ae 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -191,8 +191,7 @@ export function SessionContentHeader({
const sharedGuest = isSharedTaskPeer(session.deviceLinkDeviceId ?? '');
const { runningSessionIds } = useSessionRunningStatus(session.id);
const { confirm: confirmDialog } = useConfirmDialog();
- const { runSessionAction, unarchiveSession, beginRemoteArchive, cancelRemoteArchive } =
- useSessionLifecycleActions();
+ const { runSessionAction, unarchiveSession } = useSessionLifecycleActions();
const isPinned = session.pinnedAt != null;
const isArchived = session.status === 'archived';
@@ -480,11 +479,7 @@ export function SessionContentHeader({
// 一起等,dirty 先返回 clean、接管查询还在飞的那段时间就是 clean 结论的失效窗口。
// 改成接管结算之后再 resolve —— clean 一律重查(见 worktreeRemovalWarning),
// 拿到的是此刻的结论;菜单打开时的 prefetch 仍然热了 git cache。
- // 远程任务的预检是一次完整隧道往返:先乐观隐藏行并跳离,预检干净则沿用同一叠加层
- // 写库,需要确认时取消再让行回来(与 sidebar 同口径,见 handleActionClick)。
- const remoteArchiveToken = session.deviceLinkDeviceId
- ? beginRemoteArchive(session.id, session.deviceLinkDeviceId, session.id)
- : null;
+ // 预检与确认期间保留当前任务,确定归档后再由 runSessionAction 隐藏并跳离。
const preflight = await resolveWorktreeRemovalPreflight(session.id, session.deviceLinkDeviceId);
// 归档不弹确认框 —— 可逆操作(菜单里就有「恢复」),与 sidebar 同口径。
// 免确认的判据是「**确认**干净」:worktree 脏、或预检失败拿不到结论('unknown')
@@ -502,17 +497,13 @@ export function SessionContentHeader({
cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),
});
if (!ok) {
- if (remoteArchiveToken) cancelRemoteArchive(remoteArchiveToken);
return;
}
}
await runSessionAction(session.id, 'archive', {
activeSessionId: session.id,
- remoteArchiveToken,
});
}, [
- beginRemoteArchive,
- cancelRemoteArchive,
confirmDialog,
remoteWritesBlocked,
runSessionAction,
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.ts
index 1bb4aab172..fc28cc4c91 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
@@ -6,17 +6,17 @@ import { describe, expect, it, vi } from 'vitest';
// Execute the actual sidebar callbacks without mounting its unrelated stores.
const source = ts.createSourceFile('sidebar.tsx', readFileSync(resolve(process.cwd(),
'src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-function callback(name: string, bindings: Record<string, unknown>) {
+function callback(name: string, bindings: Record<string, unknown>, callbackSource = source) {
let expression: ts.Node | undefined;
const visit = (node: ts.Node) => {
- if (ts.isVariableDeclaration(node) && node.name.getText(source) === name && node.initializer && ts.isCallExpression(node.initializer)) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(callbackSource) === name && node.initializer && ts.isCallExpression(node.initializer)) {
expression = node.initializer.arguments[0];
}
ts.forEachChild(node, visit);
};
- visit(source);
+ visit(callbackSource);
if (!expression) throw new Error('Missing sidebar callback: ' + name);
- const js = ts.transpileModule('const callback = ' + expression.getText(source), {
+ const js = ts.transpileModule('const callback = ' + expression.getText(callbackSource), {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText;
return new Function(...Object.keys(bindings), js + '; return callback;')(...Object.values(bindings));
@@ -37,8 +37,6 @@ function harness(result: unknown, reject = false, sharedTaskId: string | undefin
viewedSessionIdRef: { current: 'other' }, viewedSessionId: 'other',
resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),
runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },
- confirmRemoteArchiveRef: { current: null }, beginRemoteArchive: vi.fn(), cancelRemoteArchive: vi.fn(),
- replaceConfirmRemoteArchive: vi.fn(),
};
const closeOwnedSharedTask = callback('closeOwnedSharedTask', bindings);
return {
@@ -85,92 +83,116 @@ describe('sidebar shared-task archive/delete guard', () => {
});
});
-describe('sidebar remote archive hides the row before the worktree preflight', () => {
- function remoteHarness(preflight: 'clean' | 'dirty' | 'unknown') {
- const token = { deviceId: 'device-1', sessionId: 'task', status: 'archived' };
- const order: string[] = [];
- const runSessionAction = vi.fn();
- const setConfirm = vi.fn();
- const beginRemoteArchive = vi.fn(() => { order.push('begin'); return token; });
- const cancelRemoteArchive = vi.fn();
- const confirmRemoteArchiveRef = { current: null as unknown };
- const replaceConfirmRemoteArchive = callback('replaceConfirmRemoteArchive', {
- confirmRemoteArchiveRef, cancelRemoteArchive,
- });
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+describe('archive preserves the current task until preflight and confirmation finish', () => {
+ const entrypoints = [
+ { name: 'sidebar', file: 'CCAgentSidebarUpper.tsx', handler: 'handleActionClick' },
+ { name: 'header', file: 'SessionContentHeader.tsx', handler: 'handleArchive' },
+ { name: 'hardware shortcut', file: 'lib/sessionHardwareTaskActions.ts', handler: 'archive' },
+ ];
+
+ function archiveHarness(entry: typeof entrypoints[number]) {
+ const entrySource = ts.createSourceFile(entry.file, readFileSync(resolve(process.cwd(),
+ 'src/renderer/features/cc-agent', entry.file), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const preflight = deferred<'clean' | 'dirty' | 'unknown'>();
+ const decision = deferred<boolean>();
const session = { id: 'task', deviceLinkDeviceId: 'device-1' };
+ let selectedTask: string | null = 'task';
+ let rowVisible = true;
+ // Both the previous optimistic entry and the actual archive change selection.
+ const leaveTask = () => { selectedTask = null; rowVisible = false; };
+ const beginRemoteArchive = vi.fn(leaveTask);
+ const runSessionAction = vi.fn(leaveTask);
+ const setConfirm = vi.fn();
+ const confirmDialog = vi.fn(() => decision.promise);
+ const resolvePreflight = vi.fn(() => preflight.promise);
const bindings = {
- window: { electronAPI: { sharedTask: { account: vi.fn() }, binding: { resolveSession: async () => ({ attached: false }) } } },
- toast: { error: vi.fn(), warning: vi.fn() }, t: (key: string) => key, sharedTaskErrorKey: () => 'sharedTask.retry',
+ window: { electronAPI: { binding: { resolveSession: async () => ({ attached: false }) } } },
+ toast: { error: vi.fn(), warning: vi.fn() }, t: (key: string) => key,
sessionsById: new Map([['task', session]]), sessionsByIdRef: { current: new Map([['task', session]]) },
runningSessionIds: new Set(), attachedSessionIdsRef: { current: new Set() },
- isRemoteSessionWriteBlocked: () => false,
- resolveWorktreeRemovalPreflight: async () => { order.push('preflight'); return preflight; },
+ isRemoteSessionWriteBlocked: () => false, remoteWritesBlocked: false,
+ resolveWorktreeRemovalPreflight: resolvePreflight,
viewedSessionIdRef: { current: 'task' }, viewedSessionId: 'task',
resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),
runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },
- confirmRemoteArchiveRef, beginRemoteArchive, cancelRemoteArchive, replaceConfirmRemoteArchive,
+ beginRemoteArchive, cancelRemoteArchive: vi.fn(),
closeOwnedSharedTask: async () => true,
confirm: { sessionId: 'task', action: 'archive' },
+ session, sessionId: session.id, deviceLinkDeviceId: session.deviceLinkDeviceId,
+ confirmDialog,
};
return {
- token, order, runSessionAction, setConfirm, beginRemoteArchive, cancelRemoteArchive, confirmRemoteArchiveRef,
- archive: () => callback('handleActionClick', bindings)('task', 'archive'),
- confirm: () => callback('handleConfirm', bindings)(),
- cancel: () => callback('handleCancelConfirm', bindings)(),
+ preflight, resolvePreflight, decision, runSessionAction, beginRemoteArchive, setConfirm, confirmDialog,
+ selected: () => selectedTask, visible: () => rowVisible,
+ archive: () => callback(entry.handler, bindings, entrySource)('task', 'archive'),
+ finish: async (confirmed: boolean) => {
+ if (entry.name === 'sidebar') {
+ if (confirmed) {
+ const saving = callback('handleConfirm', bindings)();
+ // Radix closes the dialog immediately after the confirm click.
+ callback('handleCancelConfirm', bindings)();
+ await saving;
+ } else callback('handleCancelConfirm', bindings)();
+ } else decision.resolve(confirmed);
+ },
};
}
- it('reuses the same overlay for a clean preflight', async () => {
- const h = remoteHarness('clean');
- await h.archive();
- expect(h.order).toEqual(['begin', 'preflight']);
- expect(h.beginRemoteArchive).toHaveBeenCalledWith('task', 'device-1', 'task');
- expect(h.runSessionAction).toHaveBeenCalledWith('task', 'archive', {
- activeSessionId: 'task',
- remoteArchiveToken: h.token,
+ for (const entry of entrypoints) {
+ it.each(['clean', 'dirty', 'unknown'] as const)(entry.name + ' keeps selection during %s preflight and cancellation', async (preflight) => {
+ const h = archiveHarness(entry);
+ const pending = h.archive();
+ // Allow the attachment check to settle while worktree preflight is still pending.
+ await vi.waitFor(() => {
+ expect(h.resolvePreflight).toHaveBeenCalledWith('task', 'device-1');
+ expect(h.selected()).toBe('task');
+ expect(h.visible()).toBe(true);
+ expect(h.beginRemoteArchive).not.toHaveBeenCalled();
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ });
+ h.preflight.resolve(preflight);
+ if (preflight !== 'clean') {
+ await vi.waitFor(() => {
+ expect(entry.name === 'sidebar' ? h.setConfirm : h.confirmDialog).toHaveBeenCalled();
+ });
+ expect(h.selected()).toBe('task');
+ expect(h.visible()).toBe(true);
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ await h.finish(false);
+ }
+ await pending;
+ expect(h.beginRemoteArchive).not.toHaveBeenCalled();
+ if (preflight === 'clean') {
+ expect(h.runSessionAction).toHaveBeenCalledWith('task', 'archive', { activeSessionId: 'task' });
+ expect(h.selected()).toBeNull();
+ } else {
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ expect(h.selected()).toBe('task');
+ expect(h.visible()).toBe(true);
+ }
});
- expect(h.cancelRemoteArchive).not.toHaveBeenCalled();
- });
-
- it.each(['dirty', 'unknown'] as const)('restores the row when a %s preflight is cancelled', async (preflight) => {
- const h = remoteHarness(preflight);
- await h.archive();
- expect(h.order).toEqual(['begin', 'preflight']);
- expect(h.setConfirm).toHaveBeenCalledWith(expect.objectContaining({ open: true, action: 'archive' }));
- expect(h.confirmRemoteArchiveRef.current).toBe(h.token);
- expect(h.runSessionAction).not.toHaveBeenCalled();
- h.cancel();
- expect(h.cancelRemoteArchive).toHaveBeenCalledWith(h.token);
- expect(h.confirmRemoteArchiveRef.current).toBeNull();
- });
-
- it('claims the hidden row on confirm so the dialog closing does not roll it back', async () => {
- const h = remoteHarness('dirty');
- await h.archive();
- const confirmed = h.confirm();
- // Radix 在确认按钮 onClick 之后同步触发 onOpenChange(false) → handleCancelConfirm。
- h.cancel();
- await confirmed;
- expect(h.cancelRemoteArchive).not.toHaveBeenCalled();
- expect(h.beginRemoteArchive).toHaveBeenCalledTimes(1);
- expect(h.runSessionAction).toHaveBeenCalledWith('task', 'archive', expect.objectContaining({
- remoteArchiveToken: h.token,
- }));
- });
-
- it('restores an earlier hidden row when a later confirm dialog replaces it', async () => {
- const h = remoteHarness('dirty');
- await h.archive();
- const later = { ...h.token, sessionId: 'later' };
- h.beginRemoteArchive.mockImplementationOnce(() => later);
- await h.archive();
- // 第一次的确认框已被顶替,它隐藏的行没有入口可取消 —— 先回到列表。
- expect(h.cancelRemoteArchive).toHaveBeenCalledTimes(1);
- expect(h.cancelRemoteArchive).toHaveBeenCalledWith(h.token);
- expect(h.confirmRemoteArchiveRef.current).toBe(later);
-
- h.cancel();
- expect(h.cancelRemoteArchive).toHaveBeenLastCalledWith(later);
- });
+ it.each(['dirty', 'unknown'] as const)(entry.name + ' archives only after confirming %s', async (preflight) => {
+ const h = archiveHarness(entry);
+ const pending = h.archive();
+ h.preflight.resolve(preflight);
+ await vi.waitFor(() => {
+ expect(entry.name === 'sidebar' ? h.setConfirm : h.confirmDialog).toHaveBeenCalled();
+ });
+ expect(h.selected()).toBe('task');
+ expect(h.runSessionAction).not.toHaveBeenCalled();
+ await h.finish(true);
+ await pending;
+ expect(h.runSessionAction).toHaveBeenCalledTimes(1);
+ expect(h.runSessionAction).toHaveBeenCalledWith('task', 'archive', expect.objectContaining({ activeSessionId: 'task' }));
+ expect(h.selected()).toBeNull();
+ expect(h.visible()).toBe(false);
+ });
+ }
});
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.tsx
index 1a5dc6c988..64eedcc9ae 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
@@ -20,7 +20,6 @@ const mocks = vi.hoisted(() => ({
beginPendingStatus: vi.fn(),
completePendingStatus: vi.fn(),
rollbackPendingStatus: vi.fn(),
- isPendingStatusCurrent: vi.fn(),
clearComposerDraft: vi.fn(),
cleanupSessionLayoutPrefs: vi.fn(),
cleanupSessionImages: vi.fn(),
@@ -60,7 +59,6 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({
beginPendingStatus: mocks.beginPendingStatus,
completePendingStatus: mocks.completePendingStatus,
rollbackPendingStatus: mocks.rollbackPendingStatus,
- isPendingStatusCurrent: mocks.isPendingStatusCurrent,
},
}));
@@ -127,7 +125,6 @@ beforeEach(() => {
);
mocks.completePendingStatus.mockReturnValue(true);
mocks.rollbackPendingStatus.mockReturnValue(true);
- mocks.isPendingStatusCurrent.mockReturnValue(true);
mocks.rollbackStatusTransition.mockReturnValue(true);
mocks.refreshSessions.mockResolvedValue([]);
mocks.cleanupSessionImages.mockResolvedValue(undefined);
@@ -355,27 +352,6 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
);
});
- it('drops a pre-begun remote archive that a later restore superseded during the preflight', async () => {
- mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'device-link', deviceId: 'device-1' });
- // 「全部」筛选里预检期间用户已点了恢复:预先隐藏的归档凭据已被取代。
- mocks.isPendingStatusCurrent.mockReturnValue(false);
- const token = { deviceId: 'device-1', sessionId: 'remote-session', status: 'archived' as const };
- const { result } = renderHook(() => useSessionLifecycleActions({ includeArchived: 'all' }));
-
- await act(async () => {
- await result.current.runSessionAction('remote-session', 'archive', {
- activeSessionId: null,
- remoteArchiveToken: token,
- });
- });
-
- expect(mocks.isPendingStatusCurrent).toHaveBeenCalledWith(token);
- expect(mocks.setStatus).not.toHaveBeenCalled();
- expect(mocks.completePendingStatus).not.toHaveBeenCalled();
- expect(mocks.rollbackPendingStatus).not.toHaveBeenCalled();
- expect(mocks.toastError).not.toHaveBeenCalled();
- });
-
it('sends an unarchive only after the in-flight remote archive of the same task settles', async () => {
const target = { kind: 'device-link', deviceId: 'device-1' };
mocks.resolveStatusWriteTarget.mockResolvedValue(target);
@@ -444,93 +420,34 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
);
});
- it('reuses a pre-begun remote archive without hiding or navigating twice', async () => {
- mocks.resolveStatusWriteTarget.mockResolvedValue({
- kind: 'device-link',
- deviceId: 'device-1',
- });
- const { result } = renderHook(() =>
- useSessionLifecycleActions({ includeArchived: 'active' }),
- );
-
- let token: unknown;
- act(() => {
- token = result.current.beginRemoteArchive('remote-session', 'device-1', 'remote-session');
- });
- // 预检之前:行已消失、视图已跳离。
- expect(mocks.beginPendingStatus).toHaveBeenCalledTimes(1);
- expect(mocks.beginPendingStatus.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.navigate.mock.invocationCallOrder[0],
- );
- expect(mocks.navigate).toHaveBeenCalledTimes(1);
-
+ it('navigates before moving an archived remote row in the all bucket', async () => {
+ mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'device-link', deviceId: 'device-1' });
+ const { result } = renderHook(() => useSessionLifecycleActions({ includeArchived: 'all' }));
await act(async () => {
await result.current.runSessionAction('remote-session', 'archive', {
activeSessionId: 'remote-session',
- remoteArchiveToken: token as never,
});
});
-
- expect(mocks.beginPendingStatus).toHaveBeenCalledTimes(1);
expect(mocks.navigate).toHaveBeenCalledTimes(1);
- expect(mocks.completePendingStatus).toHaveBeenCalledWith(
- token,
- expect.objectContaining({ status: 'archived' }),
- );
- });
-
- it('navigates before hiding a pre-begun remote row that stays in the all bucket', () => {
- const { result } = renderHook(() => useSessionLifecycleActions({ includeArchived: 'all' }));
-
- act(() => {
- result.current.beginRemoteArchive('remote-session', 'device-1', 'remote-session');
- });
-
+ expect(mocks.beginPendingStatus).toHaveBeenCalledTimes(1);
expect(mocks.navigate.mock.invocationCallOrder[0]).toBeLessThan(
mocks.beginPendingStatus.mock.invocationCallOrder[0],
);
});
- it('restores a pre-begun remote row when the caller cancels', () => {
- const { result } = renderHook(() =>
- useSessionLifecycleActions({ includeArchived: 'active' }),
- );
-
- act(() => {
- const token = result.current.beginRemoteArchive('remote-session', 'device-1', null);
- result.current.cancelRemoteArchive(token);
- });
-
- expect(mocks.rollbackPendingStatus).toHaveBeenCalledWith({
- deviceId: 'device-1',
- sessionId: 'remote-session',
- status: 'archived',
- });
- expect(mocks.navigate).not.toHaveBeenCalled();
- expect(mocks.setStatus).not.toHaveBeenCalled();
- });
-
- it('drops a pre-begun remote overlay when the write resolves to a local row', async () => {
+ it('uses the local status bucket when a copied remote task resolves to a local row', async () => {
mocks.resolveStatusWriteTarget.mockResolvedValueOnce({ kind: 'local' });
- const { result } = renderHook(() =>
- useSessionLifecycleActions({ includeArchived: 'active' }),
- );
- const token = { deviceId: 'device-1', sessionId: 'copied', status: 'archived' as const };
-
+ const { result } = renderHook(() => useSessionLifecycleActions({ includeArchived: 'active' }));
await act(async () => {
- await result.current.runSessionAction('copied', 'archive', {
- activeSessionId: null,
- remoteArchiveToken: token,
- });
+ await result.current.runSessionAction('copied', 'archive', { activeSessionId: null });
});
-
- expect(mocks.rollbackPendingStatus).toHaveBeenCalledWith(token);
expect(mocks.beginStatusTransition).toHaveBeenCalledWith('copied', {
- status: 'archived',
- pinnedAt: null,
+ status: 'archived', pinnedAt: null,
});
+ expect(mocks.beginPendingStatus).not.toHaveBeenCalled();
expect(mocks.completePendingStatus).not.toHaveBeenCalled();
});
+
});
describe('useSessionLifecycleActions delete cache invalidation', () => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
index 6c050314fa..4165e8a654 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
@@ -16,9 +16,7 @@
*
* 远程(device-link)任务的归档 / 恢复走 remoteProjectsStore 的状态迁移叠加层,与本机
* sessionsStore 状态事务对称:行当帧换桶,写库成功后落被控端返回的行,失败回滚。
- * 远程归档的 worktree 预检是一次完整隧道往返,调用方可先 `beginRemoteArchive`
- * (行消失 + 跳离)再等预检,确认后把凭据经 `remoteArchiveToken` 交回 runSessionAction
- * 复用;取消则 `cancelRemoteArchive` 让行回来(不跳回原任务)。
+ * 调用方完成 worktree 预检与必要的确认后才进入本 hook;等待期间保留任务行与选中状态。
*
* includeArchived 必须与调用方自己的 useCCSessions 桶一致:unarchive 的 refreshSessions
* 只刷当前桶,sidebar 处于 archived / all 桶时删除行后若刷的是默认 active
@@ -81,11 +79,6 @@ export interface RunSessionActionOptions {
* "下一条 / 上一条 / 新建";没有列表上下文的入口继续回落到 /cc-agent。
*/
deleteRedirectRoute?: string | null;
- /**
- * 调用方已用 beginRemoteArchive 提前隐藏远程任务(并已跳离)时交回的凭据:
- * 归档沿用同一叠加层直接写库,不再重复 begin / 跳转,避免行闪烁。
- */
- remoteArchiveToken?: RemotePendingStatusToken | null;
}
export function useSessionLifecycleActions(options?: { includeArchived?: ListStatusFilter }) {
@@ -103,7 +96,7 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
/**
* 远程任务归档的乐观起点:叠加层把行移出 active 桶,并按 runSessionAction 同一顺序
* 跳离(行留在列表时先跳再换桶,否则先换桶再跳,理由见下方 archive 段注释)。
- * 返回的凭据由调用方交给 runSessionAction(remoteArchiveToken)或 cancelRemoteArchive。
+ * 只在已确认的 runSessionAction 内开始,返回凭据供写库成功或失败时结算。
*/
const beginRemoteArchive = useCallback(
(
@@ -126,11 +119,6 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
[navigate, listFilter],
);
- /** 用户取消 / 前置条件失败:撤掉提前隐藏,行回到列表。已跳离的视图不跳回。 */
- const cancelRemoteArchive = useCallback((token: RemotePendingStatusToken) => {
- remoteProjectsStore.rollbackPendingStatus(token);
- }, []);
-
/**
* archive / delete 实际执行序列。不关心确认弹窗的开合状态——由调用方负责。
*/
@@ -138,36 +126,20 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
async (
sessionId: string,
action: 'delete' | 'archive',
- { activeSessionId, deleteRedirectRoute, remoteArchiveToken }: RunSessionActionOptions,
+ { activeSessionId, deleteRedirectRoute }: RunSessionActionOptions,
) => {
const actionStartedAt = performance.now();
const targetStatus: SessionStatus = action === 'delete' ? 'deleted' : 'archived';
const statusWriteTarget = await sessionService.resolveStatusWriteTarget(sessionId);
const isDeviceLinkSession = statusWriteTarget.kind === 'device-link';
- // 预先隐藏的远程归档在等预检 / 确认期间已被更新的操作取代(「全部」筛选里行仍可见,
- // 用户可能已点了恢复):以最后一次操作为准,这次过时的归档不再写库。检查放在最后一个
- // await 之后,从这里到 setStatusInOrder 入队全程同步,恢复插不进来。
- if (
- remoteArchiveToken &&
- isDeviceLinkSession &&
- !remoteProjectsStore.isPendingStatusCurrent(remoteArchiveToken)
- ) {
- return;
- }
let statusTransition: SessionStatusTransitionToken | null = null;
// device-link 远程会话:status 写经隧道(setStatus 内部按来源路由 patch-meta)。归档走
// remoteProjectsStore 的状态迁移叠加层乐观换桶,写库成功即落被控端返回的行,不等
// sessions:patched 回流。
let remoteStatus: RemotePendingStatusToken | null = null;
- if (remoteArchiveToken && !isDeviceLinkSession) {
- // 远程 id 撞上本机行(该设备已停用控制)时改走本机状态桶,提前登记的远程叠加层作废。
- remoteProjectsStore.rollbackPendingStatus(remoteArchiveToken);
- }
if (action === 'archive' && isDeviceLinkSession) {
- remoteStatus =
- remoteArchiveToken ??
- beginRemoteArchive(sessionId, statusWriteTarget.deviceId, activeSessionId);
+ remoteStatus = beginRemoteArchive(sessionId, statusWriteTarget.deviceId, activeSessionId);
} else if (action === 'archive') {
// 乐观更新的顺序取决于**被归档的行还会不会留在当前列表里**,两种情况相反:
//
@@ -351,5 +323,5 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
[refreshSessions, t],
);
- return { runSessionAction, unarchiveSession, beginRemoteArchive, cancelRemoteArchive };
+ return { runSessionAction, unarchiveSession };
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts
index 21b00b2b8c..e209ade335 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts
@@ -29,8 +29,7 @@ export function useSessionHardwareTaskActions({
} {
const { t } = useTranslation();
const { confirm: confirmDialog } = useConfirmDialog();
- const { runSessionAction, beginRemoteArchive, cancelRemoteArchive } =
- useSessionLifecycleActions();
+ const { runSessionAction } = useSessionLifecycleActions();
const { runningSessionIds } = useSessionRunningStatus(session?.id);
const sessionId = session?.id ?? null;
const pinnedAt = session?.pinnedAt ?? null;
@@ -75,10 +74,7 @@ export function useSessionHardwareTaskActions({
toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));
return;
}
- // 远程任务先乐观隐藏行并跳离,再等隧道预检(与 sidebar handleActionClick 同口径)。
- const remoteArchiveToken = deviceLinkDeviceId
- ? beginRemoteArchive(sessionId, deviceLinkDeviceId, sessionId)
- : null;
+ // 预检与确认期间保留当前任务,确定归档后再隐藏并跳离。
const preflight = await resolveWorktreeRemovalPreflight(sessionId, deviceLinkDeviceId);
if (preflight !== 'clean') {
const ok = await confirmDialog({
@@ -92,14 +88,11 @@ export function useSessionHardwareTaskActions({
cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),
});
if (!ok) {
- if (remoteArchiveToken) cancelRemoteArchive(remoteArchiveToken);
return;
}
}
- await runSessionAction(sessionId, 'archive', { activeSessionId: sessionId, remoteArchiveToken });
+ await runSessionAction(sessionId, 'archive', { activeSessionId: sessionId });
}, [
- beginRemoteArchive,
- cancelRemoteArchive,
confirmDialog,
deviceLinkDeviceId,
onRemoteWriteBlocked,