Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote): 桌面与手机存档在预检前立即响应
Dash917f47ffdbd4
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 19646851b9..fa6475a4af 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -3183,55 +3183,59 @@ function ExpandedView({// 例外:worktree 有未提交改动(归档会顺带回收 worktree)、或任务绑定了// active 自动化(归档后会暂停),这时升级到确认弹窗展示对应提醒。if (isArchiveLike) {- // 接管拦截先结算:被接管时不该弹任何归档确认。- if (await blockedByAttachment()) return;- // 自动化绑定读本地缓存,放在 worktree 预检之前,不占用预检之后的窗口。- const scheduleNames =- (await loadActiveBoundScheduleNames([- { id: sessionId, deviceLinkDeviceId: session?.deviceLinkDeviceId },- ])).get(sessionId) ?? [];- // **worktree 预检必须是最后一个前置条件**(codex review):它之后再 await- // 任何东西(比如原来排在后面的接管查询),都会给「clean 结论」留一段失效- // 窗口 —— 编辑器或收尾中的 agent 在那段时间写脏工作区,归档就不带警告地- // 过去了。并行没有丢:菜单打开 / 亮出 Confirm 胶囊时的 prefetch 已经把查询- // 发出去并热了 git cache,而这里 resolve 对 clean 一律重查(见- // worktreeRemovalWarning 的非对称复用),拿到的是此刻的结论。- //- // 窗口不可能压到零 —— 从这次查询返回到 main 侧真正 `git worktree remove`- // 之间还有写库和回收链;那一段由 main 在删除前重新检测 + auto-stash 兜住- // (WorktreeManager.removeWorktreeForSession),renderer 这层负责的是「别拿- // 明显过期的结论免掉确认」。- //- // 预检与确认期间保留列表行和当前任务;只有确定归档后才隐藏并跳离。- const preflight = await resolveWorktreeRemovalPreflight(- sessionId,- session?.deviceLinkDeviceId,- );- // 免确认的判据是「**确认**干净」,不是「不是脏的」:'unknown'(预检失败)- // 同样要弹确认框,否则归档会静默回收可能带着未提交改动的 worktree- // (greptile review)。'unknown' 时不摆 dirty 警告文案 —— 那会谎称有改动,- // 走的是普通归档确认。- if (preflight !== 'clean' || scheduleNames.length > 0) {- setConfirm({- open: true,- sessionId,- action: 'archive',- dirtyWorktree: preflight === 'dirty',- scheduleNames,- sharedTaskId,- });- return;- }- // 重定向判定用 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;- }await runSessionAction(sessionId, 'archive', {activeSessionId: viewedSessionIdRef.current,+ prepareArchive: async (isCurrent) => {+ // 接管拦截先结算:被接管时不该弹任何归档确认。+ if (await blockedByAttachment()) return false;+ // 自动化绑定读本地缓存,放在 worktree 预检之前,不占用预检之后的窗口。+ const scheduleNames =+ (await loadActiveBoundScheduleNames([+ { id: sessionId, deviceLinkDeviceId: session?.deviceLinkDeviceId },+ ])).get(sessionId) ?? [];+ // **worktree 预检必须是最后一个前置条件**(codex review):它之后再 await+ // 任何东西(比如原来排在后面的接管查询),都会给「clean 结论」留一段失效+ // 窗口 —— 编辑器或收尾中的 agent 在那段时间写脏工作区,归档就不带警告地+ // 过去了。并行没有丢:菜单打开 / 亮出 Confirm 胶囊时的 prefetch 已经把查询+ // 发出去并热了 git cache,而这里 resolve 对 clean 一律重查(见+ // worktreeRemovalWarning 的非对称复用),拿到的是此刻的结论。+ //+ // 窗口不可能压到零 —— 从这次查询返回到 main 侧真正 `git worktree remove`+ // 之间还有写库和回收链;那一段由 main 在删除前重新检测 + auto-stash 兜住+ // (WorktreeManager.removeWorktreeForSession),renderer 这层负责的是「别拿+ // 明显过期的结论免掉确认」。+ //+ // 远程列表行已经乐观换桶;预检失败或需要确认时由执行层恢复,详情尚未跳离。+ const preflight = await resolveWorktreeRemovalPreflight(+ sessionId,+ session?.deviceLinkDeviceId,+ );+ if (!isCurrent()) return false;+ // 免确认的判据是「**确认**干净」,不是「不是脏的」:'unknown'(预检失败)+ // 同样要弹确认框,否则归档会静默回收可能带着未提交改动的 worktree+ // (greptile review)。'unknown' 时不摆 dirty 警告文案 —— 那会谎称有改动,+ // 走的是普通归档确认。+ if (preflight !== 'clean' || scheduleNames.length > 0) {+ setConfirm({+ open: true,+ sessionId,+ action: 'archive',+ dirtyWorktree: preflight === 'dirty',+ scheduleNames,+ sharedTaskId,+ });+ return false;+ }+ // 重定向判定用 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 false;+ if (!(await closeOwnedSharedTask(sharedTaskId))) {+ return false;+ }+ return true;+ },});return;}diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsxindex 29d7e354b7..66f15fcba2 100644--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx@@ -472,47 +472,51 @@ export function SessionContentHeader({toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));return;}- // 接管查询先发不 await,让它与菜单打开时那次 prefetch 在链路上重叠;- // resolveSession 失败降级为「未接管」,不阻断归档(与 sidebar 同口径)。- const attachedPromise = window.electronAPI.binding- .resolveSession(session.id)- .then((binding) => binding.attached)- .catch(() => false);- if (await attachedPromise) {- toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));- return;- }- // 绑定了 active 自动化:归档后会暂停,需要确认。读本地缓存,排在 worktree 预检之前。- const scheduleNames =- (await loadActiveBoundScheduleNames([- { id: session.id, deviceLinkDeviceId: session.deviceLinkDeviceId },- ])).get(session.id) ?? [];- // **worktree 预检必须是最后一个前置条件**(codex review):原来这里用 Promise.all- // 一起等,dirty 先返回 clean、接管查询还在飞的那段时间就是 clean 结论的失效窗口。- // 改成接管结算之后再 resolve —— clean 一律重查(见 worktreeRemovalWarning),- // 拿到的是此刻的结论;菜单打开时的 prefetch 仍然热了 git cache。- // 预检与确认期间保留当前任务,确定归档后再由 runSessionAction 隐藏并跳离。- const preflight = await resolveWorktreeRemovalPreflight(session.id, session.deviceLinkDeviceId);- // 归档不弹确认框 —— 可逆操作(菜单里就有「恢复」),与 sidebar 同口径。- // 免确认的判据是「**确认**干净」:worktree 脏、或预检失败拿不到结论('unknown')- // 都要确认 —— 归档会顺带回收 worktree,不能静默带走改动(greptile review)。- // 'unknown' 只弹普通归档确认,不摆 dirty 警告文案(那会谎称有未提交改动)。- if (preflight !== 'clean' || scheduleNames.length > 0) {- const ok = await confirmDialog({- title: t('ccAgent.sidebar.confirmArchive.title'),- description: archiveConfirmDescription(t, {- dirtyWorktree: preflight === 'dirty',- scheduleNames,- }),- confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),- cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),- });- if (!ok) {- return;- }- }await runSessionAction(session.id, 'archive', {activeSessionId: session.id,+ prepareArchive: async (isCurrent) => {+ // 接管查询先发不 await,让它与菜单打开时那次 prefetch 在链路上重叠;+ // resolveSession 失败降级为「未接管」,不阻断归档(与 sidebar 同口径)。+ const attachedPromise = window.electronAPI.binding+ .resolveSession(session.id)+ .then((binding) => binding.attached)+ .catch(() => false);+ if (await attachedPromise) {+ toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));+ return false;+ }+ // 绑定了 active 自动化:归档后会暂停,需要确认。读本地缓存,排在 worktree 预检之前。+ const scheduleNames =+ (await loadActiveBoundScheduleNames([+ { id: session.id, deviceLinkDeviceId: session.deviceLinkDeviceId },+ ])).get(session.id) ?? [];+ // **worktree 预检必须是最后一个前置条件**(codex review):原来这里用 Promise.all+ // 一起等,dirty 先返回 clean、接管查询还在飞的那段时间就是 clean 结论的失效窗口。+ // 改成接管结算之后再 resolve —— clean 一律重查(见 worktreeRemovalWarning),+ // 拿到的是此刻的结论;菜单打开时的 prefetch 仍然热了 git cache。+ // 远程列表已经乐观换桶;预检与确认期间保留当前详情,取消时恢复行。+ const preflight = await resolveWorktreeRemovalPreflight(session.id, session.deviceLinkDeviceId);+ if (!isCurrent()) return false;+ // 归档不弹确认框 —— 可逆操作(菜单里就有「恢复」),与 sidebar 同口径。+ // 免确认的判据是「**确认**干净」:worktree 脏、或预检失败拿不到结论('unknown')+ // 都要确认 —— 归档会顺带回收 worktree,不能静默带走改动(greptile review)。+ // 'unknown' 只弹普通归档确认,不摆 dirty 警告文案(那会谎称有未提交改动)。+ if (preflight !== 'clean' || scheduleNames.length > 0) {+ const ok = await confirmDialog({+ title: t('ccAgent.sidebar.confirmArchive.title'),+ description: archiveConfirmDescription(t, {+ dirtyWorktree: preflight === 'dirty',+ scheduleNames,+ }),+ confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),+ cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),+ });+ if (!ok) {+ return false;+ }+ }+ return true;+ },});}, [confirmDialog,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 b6e7757517..65a74b26b4 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@@ -40,7 +40,11 @@ function harness(result: unknown, reject = false, sharedTaskId: string | undefinarchiveBlockedByRunning,viewedSessionIdRef: { current: 'other' }, viewedSessionId: 'other',resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),- runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },+ runSessionAction: async (id: string, action: string, options: { prepareArchive?: (isCurrent: () => boolean) => Promise<boolean> }) => {+ if (options.prepareArchive && !(await options.prepareArchive(() => true))) return;+ const { prepareArchive: _, ...confirmedOptions } = options;+ runSessionAction(id, action, confirmedOptions);+ }, setConfirm, CONFIRM_INITIAL: { open: false },};const closeOwnedSharedTask = callback('closeOwnedSharedTask', bindings);return {@@ -137,7 +141,7 @@ describe('archive preserves the current task until preflight and confirmation fi// 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 runSessionAction = vi.fn((..._args: unknown[]) => leaveTask());const setConfirm = vi.fn();const confirmDialog = vi.fn(() => decision.promise);const resolvePreflight = vi.fn(() => preflight.promise);@@ -153,7 +157,15 @@ describe('archive preserves the current task until preflight and confirmation fiarchiveConfirmDescription: () => 'description',viewedSessionIdRef: { current: 'task' }, viewedSessionId: 'task',resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),- runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },+ runSessionAction: async (id: string, action: string, options: { prepareArchive?: (isCurrent: () => boolean) => Promise<boolean> }) => {+ rowVisible = false;+ if (options.prepareArchive && !(await options.prepareArchive(() => true))) {+ rowVisible = true;+ return;+ }+ const { prepareArchive: _, ...confirmedOptions } = options;+ runSessionAction(id, action, confirmedOptions);+ }, setConfirm, CONFIRM_INITIAL: { open: false },beginRemoteArchive, cancelRemoteArchive: vi.fn(),closeOwnedSharedTask: async () => true,archiveBlockedByRunning: () => false,@@ -186,7 +198,7 @@ describe('archive preserves the current task until preflight and confirmation fiawait vi.waitFor(() => {expect(h.resolvePreflight).toHaveBeenCalledWith('task', 'device-1');expect(h.selected()).toBe('task');- expect(h.visible()).toBe(true);+ expect(h.visible()).toBe(false);expect(h.beginRemoteArchive).not.toHaveBeenCalled();expect(h.runSessionAction).not.toHaveBeenCalled();});@@ -196,7 +208,6 @@ describe('archive preserves the current task until preflight and confirmation fiexpect(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);}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 4fdf73ce6f..6e81c9304f 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@@ -21,6 +21,7 @@ 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(),@@ -63,6 +64,7 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({beginPendingStatus: mocks.beginPendingStatus,completePendingStatus: mocks.completePendingStatus,rollbackPendingStatus: mocks.rollbackPendingStatus,+ isPendingStatusCurrent: mocks.isPendingStatusCurrent,},}));@@ -134,6 +136,7 @@ beforeEach(() => {);mocks.completePendingStatus.mockReturnValue(true);mocks.rollbackPendingStatus.mockReturnValue(true);+ mocks.isPendingStatusCurrent.mockReturnValue(true);mocks.rollbackStatusTransition.mockReturnValue(true);mocks.refreshSessions.mockResolvedValue([]);mocks.cleanupSessionImages.mockResolvedValue(undefined);@@ -144,6 +147,45 @@ beforeEach(() => {});describe('archive uses current state after asynchronous checks', () => {+ // Regression: remote preflight used to block the optimistic row update.+ // Unit: a deferred preflight must hide the row before any write/navigation,+ // then cancellation/failure restores it; a newer intent prevents a late write.+ it.each(['confirm', 'cancel', 'fail', 'superseded', 'running'] as const)(+ 'updates the remote list during preflight and handles %s', async (outcome) => {+ mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'device-link', deviceId: 'device-1' });+ let resolve!: (confirmed: boolean) => void;+ let reject!: (error: Error) => void;+ const preparation = new Promise<boolean>((done, fail) => { resolve = done; reject = fail; });+ const { result } = renderHook(() => useSessionLifecycleActions());+ let action!: Promise<void>;+ await act(async () => {+ action = result.current.runSessionAction('session-1', 'archive', {+ activeSessionId: 'session-1', prepareArchive: () => preparation,+ });+ });+ expect(mocks.beginPendingStatus).toHaveBeenCalledWith('device-1', 'session-1', 'archived');+ expect(mocks.setStatus).not.toHaveBeenCalled();+ expect(mocks.navigate).not.toHaveBeenCalled();+ expect(mocks.purgeSession).not.toHaveBeenCalled();+ await act(async () => {+ if (outcome === 'superseded') mocks.isPendingStatusCurrent.mockReturnValue(false);+ if (outcome === 'running') mocks.getRunningSnapshot.mockReturnValue(new Map([['session-1', { isRunning: true }]]));+ if (outcome === 'fail') reject(new Error('preflight failed'));+ else resolve(outcome !== 'cancel');+ await action;+ });+ if (outcome === 'confirm') {+ expect(mocks.setStatus).toHaveBeenCalledOnce();+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/new');+ expect(mocks.completePendingStatus).toHaveBeenCalledOnce();+ } else {+ expect(mocks.setStatus).not.toHaveBeenCalled();+ expect(mocks.navigate).not.toHaveBeenCalled();+ expect(mocks.purgeSession).not.toHaveBeenCalled();+ expect(mocks.rollbackPendingStatus).toHaveBeenCalledTimes(outcome === 'superseded' ? 0 : 1);+ }+ },+ );it('shares a live running guard with callers before they close sharing', () => {const { result } = renderHook(() => useSessionLifecycleActions());const guard = result.current.archiveBlockedByRunning;diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.tsindex 94b3136d42..ab5aa3f8d0 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts@@ -5,9 +5,8 @@* - CCAgentSidebarUpper:会话列表右键菜单 / 行内 archive 快捷按钮* - SessionContentHeader:右栏顶栏 ··· 菜单*- * 本 hook 只封装"确认之后的执行序列"(关子进程 / 写库 / 乐观补丁 / 释放内存 /- * 清 composer draft / refresh 列表与 worktree / 必要时跳转)。**前置检查- * (IM 接管拦截)和确认弹窗留在调用方**;运行态判据由本 hook 统一提供,+ * 本 hook 封装乐观补丁、预检、写库与收尾。前置检查(IM 接管拦截)和确认弹窗+ * 由调用方通过 prepareArchive 提供;运行态判据由本 hook 统一提供,* 调用方在关闭共享前复用,执行层在异步等待后复核。两处的确认交互形态不同* (sidebar 是受控 ConfirmDialog + 行内两步确认,header 是 imperative* confirmDialog),强行收进来反而耦合。@@ -17,7 +16,7 @@** 远程(device-link)任务的归档 / 恢复走 remoteProjectsStore 的状态迁移叠加层,与本机* sessionsStore 状态事务对称:行当帧换桶,写库成功后落被控端返回的行,失败回滚。- * 调用方完成 worktree 预检与必要的确认后才进入本 hook;等待期间保留任务行与选中状态。+ * 远程预检通过 prepareArchive 在乐观换桶之后执行;取消或失败恢复行,确认后才跳离详情。** includeArchived 必须与调用方自己的 useCCSessions 桶一致:unarchive 的 refreshSessions* 只刷当前桶,sidebar 处于 archived / all 桶时删除行后若刷的是默认 active@@ -78,6 +77,8 @@ function setStatusInOrder(}export interface RunSessionActionOptions {+ /** 归档预检与确认。远程任务先乐观换桶,未获确认不写入、不清理或跳离详情。 */+ prepareArchive?: (isCurrent: () => boolean) => Promise<boolean>;/** 当前活跃会话 id —— 决定 archive / delete 后是否需要跳走。 */activeSessionId: string | null | undefined;/**@@ -142,7 +143,7 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListStaasync (sessionId: string,action: 'delete' | 'archive',- { activeSessionId, deleteRedirectRoute }: RunSessionActionOptions,+ { activeSessionId, deleteRedirectRoute, prepareArchive }: RunSessionActionOptions,) => {const actionStartedAt = performance.now();const targetStatus: SessionStatus = action === 'delete' ? 'deleted' : 'archived';@@ -157,8 +158,34 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta// sessions:patched 回流。let remoteStatus: RemotePendingStatusToken | null = null;+ if (action === 'archive' && prepareArchive) {+ if (isDeviceLinkSession) {+ remoteStatus = beginRemoteArchive(sessionId, statusWriteTarget.deviceId, null);+ }+ try {+ const confirmed = await prepareArchive(+ () => !remoteStatus || remoteProjectsStore.isPendingStatusCurrent(remoteStatus),+ );+ if (!confirmed || archiveBlockedByRunning(sessionId, deviceId)) {+ if (remoteStatus) remoteProjectsStore.rollbackPendingStatus(remoteStatus);+ return;+ }+ // 恢复、删除或设备移除已经取代了本次意图时,迟到预检不能再发归档。+ if (remoteStatus && !remoteProjectsStore.isPendingStatusCurrent(remoteStatus)) return;+ } catch (err) {+ if (remoteStatus) remoteProjectsStore.rollbackPendingStatus(remoteStatus);+ log.error('[archive preparation]', err);+ toast.error(t('ccAgent.sidebar.archiveFailed'));+ return;+ }+ }+if (action === 'archive' && isDeviceLinkSession) {- remoteStatus = beginRemoteArchive(sessionId, statusWriteTarget.deviceId, activeSessionId);+ if (!remoteStatus) {+ remoteStatus = beginRemoteArchive(sessionId, statusWriteTarget.deviceId, activeSessionId);+ } else if (sessionId === activeSessionId && isSessionRemovalRouteCurrent(sessionId)) {+ navigate('/cc-agent/new');+ }} else if (action === 'archive') {// 乐观更新的顺序取决于**被归档的行还会不会留在当前列表里**,两种情况相反://diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.tsindex db51392ccc..5b8feae380 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts@@ -70,35 +70,41 @@ export function useSessionHardwareTaskActions({toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));return;}- const attached = await window.electronAPI.binding- .resolveSession(sessionId)- .then((binding) => binding.attached)- .catch(() => false);- if (attached) {- toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));- return;- }- const scheduleNames =- (await loadActiveBoundScheduleNames([{ id: sessionId, deviceLinkDeviceId }])).get(- sessionId,- ) ?? [];- // 预检与确认期间保留当前任务,确定归档后再隐藏并跳离。- const preflight = await resolveWorktreeRemovalPreflight(sessionId, deviceLinkDeviceId);- if (preflight !== 'clean' || scheduleNames.length > 0) {- const ok = await confirmDialog({- title: t('ccAgent.sidebar.confirmArchive.title'),- description: archiveConfirmDescription(t, {- dirtyWorktree: preflight === 'dirty',- scheduleNames,- }),- confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),- cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),- });- if (!ok) {- return;- }- }- await runSessionAction(sessionId, 'archive', { activeSessionId: sessionId });+ await runSessionAction(sessionId, 'archive', {+ activeSessionId: sessionId,+ prepareArchive: async (isCurrent) => {+ const attached = await window.electronAPI.binding+ .resolveSession(sessionId)+ .then((binding) => binding.attached)+ .catch(() => false);+ if (attached) {+ toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));+ return false;+ }+ const scheduleNames =+ (await loadActiveBoundScheduleNames([{ id: sessionId, deviceLinkDeviceId }])).get(+ sessionId,+ ) ?? [];+ // 远程列表先乐观换桶;确认前保留详情,取消后恢复行。+ const preflight = await resolveWorktreeRemovalPreflight(sessionId, deviceLinkDeviceId);+ if (!isCurrent()) return false;+ if (preflight !== 'clean' || scheduleNames.length > 0) {+ const ok = await confirmDialog({+ title: t('ccAgent.sidebar.confirmArchive.title'),+ description: archiveConfirmDescription(t, {+ dirtyWorktree: preflight === 'dirty',+ scheduleNames,+ }),+ confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),+ cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),+ });+ if (!ok) {+ return false;+ }+ }+ return true;+ },+ });}, [confirmDialog,deviceLinkDeviceId,diff --git a/apps/mobile/src/__tests__/SessionMenuRenameEntry.test.tsx b/apps/mobile/src/__tests__/SessionMenuRenameEntry.test.tsxindex c7f67cc533..fd5f1920e4 100644--- a/apps/mobile/src/__tests__/SessionMenuRenameEntry.test.tsx+++ b/apps/mobile/src/__tests__/SessionMenuRenameEntry.test.tsx@@ -95,8 +95,12 @@ vi.mock("@/components/MobilePrimitives", async () => {createElement("button", { key: action.testID, "data-testid": action.testID, onClick: action.onPress }))),};});+const sheetLifecycle = vi.hoisted(() => ({ closed: undefined as (() => void) | undefined }));vi.mock("@/session/SheetModal", () => ({- SheetModal: ({ children }: { children: ReactNode }) => children,+ SheetModal: ({ children, onClosed }: { children: ReactNode; onClosed?: () => void }) => {+ sheetLifecycle.closed = onClosed;+ return children;+ },}));vi.mock("@/session/SheetSurface", () => ({SheetSurface: ({ children, footer }: { children: ReactNode; footer?: ReactNode }) => <>{children}{footer}</>,@@ -152,6 +156,28 @@ it("opening at rename goes straight to the editor and cancel closes the sheet",}});+// Unit: a slow archive preflight used to hold the menu open. The actual menu+// must close immediately, but wait for native dismissal before opening an Alert.+it.each([true, false])("archive closes the menu before a delayed decision (%s)", async (confirmed) => {+ let decide!: (ok: boolean) => void;+ const decision = new Promise<boolean>((resolve) => { decide = resolve; });+ const props = baseProps({ initialView: "menu", onArchive: vi.fn(), confirmArchive: vi.fn(() => decision),+ session: { id: "a", title: "Task", status: "active" } as SessionMenuSheetProps['session'] });+ const { root, click } = await renderSheet(props);+ try {+ await click("session.archiveButton");+ expect(props.onClose).toHaveBeenCalledOnce();+ expect(props.confirmArchive).not.toHaveBeenCalled();+ await act(async () => sheetLifecycle.closed?.());+ expect(props.confirmArchive).toHaveBeenCalledOnce();+ expect(props.onArchive).not.toHaveBeenCalled();+ await act(async () => { decide(confirmed); });+ expect(props.onArchive).toHaveBeenCalledTimes(confirmed ? 1 : 0);+ } finally {+ await act(async () => root.unmount());+ }+});+it("confirming a direct rename closes the sheet", async () => {const props = baseProps();const { root, click } = await renderSheet(props);diff --git a/apps/mobile/src/__tests__/orphanSessionActions.test.ts b/apps/mobile/src/__tests__/orphanSessionActions.test.tsindex 2f0542f2b7..dfb6bc3291 100644--- a/apps/mobile/src/__tests__/orphanSessionActions.test.ts+++ b/apps/mobile/src/__tests__/orphanSessionActions.test.ts@@ -39,7 +39,7 @@ function fixture() {currentSession: session, deviceId: 'rpc', sessionId: session.id,resolveSessionWriteDevices: () => ({ rpcDeviceId: 'rpc', shardId: 'shard' }),sessionMetaWriteGuard: { begin: () => ({ isLatest }) },- sessionMetaWriteQueue: { enqueue: () => pending },+ sessionMetaWriteQueue: { enqueue: vi.fn(() => pending) },sessionPendingWrites: { track: () => release },remoteSessionStore: store, isExplicitRemoteNotFoundError, pickWriteFields, writeGuardFields,goBackToHome: vi.fn(), Alert: { alert: vi.fn() }, humanizeRemoteError: String,@@ -52,6 +52,30 @@ const gone = () => new Error('[NOT_FOUND] Session does not exist');const tick = () => new Promise((done) => setTimeout(done, 0));describe('orphan task status actions', () => {+ // Unit regression: archive must leave the list while its remote schedule+ // lookup is pending, without committing before confirmation. Existing cases+ // exercised only the RPC result, not the pre-write wait/cancel boundary.+ it.each(['cancel', 'superseded', 'fail'] as const)('optimistic archive handles preflight %s', async (outcome) => {+ const f = fixture();+ let finish!: (confirmed: boolean) => void;+ let fail!: (error: Error) => void;+ const preparation = new Promise<boolean>((resolve, reject) => { finish = resolve; fail = reject; });+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', f.bindings);+ const request = patch(session, { status: 'archived' }, () => preparation);+ expect(f.store.applySessionPatch).toHaveBeenCalledWith('shard', 's1', { status: 'archived' }, { deferRemovalCleanup: true });+ expect(f.bindings.sessionMetaWriteQueue.enqueue).not.toHaveBeenCalled();+ if (outcome === 'superseded') f.isLatest.mockReturnValue(false);+ if (outcome === 'fail') {+ fail(new Error('preflight failed'));+ await expect(request).rejects.toThrow('preflight failed');+ } else {+ finish(outcome !== 'cancel');+ await request;+ }+ expect(f.bindings.sessionMetaWriteQueue.enqueue).not.toHaveBeenCalled();+ expect(f.store.upsertDeviceSession).toHaveBeenCalledTimes(outcome === 'superseded' ? 0 : 1);+ expect(f.release).toHaveBeenCalled();+ });it.each(['archived', 'deleted', 'active'])('list status %s retires the mirror without rollback', async (status) => {const f = fixture();const patch = callback('src/session/useSessionListActions.ts', 'patchSession', f.bindings);diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex cc067c798a..3c6353d714 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -41,6 +41,29 @@ function message(id: string, sessionId: string): RemoteMessage {};}+// Unit regression: preflight now runs after optimistic removal. Cancellation+// must retain conversation content; successful removal must still release it.+it('keeps messages through archive preflight cancellation and cleans up after success', () => {+ remoteSessionStore.clear();+ const row = session('s1');+ remoteSessionStore.setDeviceSessions('dev-1', 'Computer', [row]);+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);+ const removed = vi.fn();+ const off = remoteSessionStore.onSessionRemoved(removed);+ try {+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' }, { deferRemovalCleanup: true });+ expect(remoteSessionStore.getSessions()).toEqual([]);+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ expect(removed).not.toHaveBeenCalled();+ remoteSessionStore.upsertDeviceSession('dev-1', 'Computer', row);+ expect(remoteSessionStore.getMessages('s1')[0].content).toBe('hello');+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' }, { deferRemovalCleanup: true });+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' });+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ expect(removed).toHaveBeenCalledExactlyOnceWith('dev-1', 's1');+ } finally { off(); remoteSessionStore.clear(); }+});+// Unit: side-chat details are omitted by the Host list. A list refresh must// retain opened details without leaking them into Home, and deletion must still// remove them. Existing tests only cover ordinary listed task reconciliation.diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsxindex e496a7741d..052221abdb 100644--- a/apps/mobile/src/session/SessionMenuSheet.tsx+++ b/apps/mobile/src/session/SessionMenuSheet.tsx@@ -169,7 +169,7 @@ export interface SessionMenuSheetProps {leavingSharing?: boolean;onTogglePinned(): void;onArchive(): void;- /** 归档前的确认(如绑定了自动化);返回 false 时保留菜单、不归档。 */+ /** 菜单收起后执行归档确认(如绑定了自动化);返回 false 时留在当前任务、不归档。 */confirmArchive?: () => Promise<boolean>;onRestore(): void;onDelete(): void;@@ -222,6 +222,13 @@ export function SessionMenuSheet({const styles = useThemedStyles(makeStyles);const { colors } = useTheme();const { t, i18n: i18nInstance } = useTranslation();+ const pendingArchiveRef = useRef<(() => void) | null>(null);+ const handleClosed = useCallback(() => {+ const archive = pendingArchiveRef.current;+ pendingArchiveRef.current = null;+ onClosed?.();+ archive?.();+ }, [onClosed]);const menuUsage = useSessionMenuUsage(session,usageReader,@@ -499,12 +506,13 @@ export function SessionMenuSheet({onClose();return;}- // 与删除同序:确认弹窗在菜单仍展开时弹出,确认后再收起并归档。- void (confirmArchive?.() ?? Promise.resolve(true)).then((ok) => {- if (!ok) return;- onArchive();- onClose();- });+ // 先响应点击收起菜单,关闭动画结束后再查询/弹确认,避免原生 Modal 吞掉 Alert。+ pendingArchiveRef.current = () => {+ void (confirmArchive?.() ?? Promise.resolve(true)).then((ok) => {+ if (ok) onArchive();+ });+ };+ onClose();return;case 'delete':confirmDelete();@@ -611,7 +619,7 @@ export function SessionMenuSheet({);}, [codexRateLimits, codexResetBusy, onResetCodexRateLimits, resetSummary, t]);- const tagsSheet = useTaskTagsSheet(visible, onClosed);+ const tagsSheet = useTaskTagsSheet(visible, handleClosed);const menuContent = (<View style={styles.menuBody} testID="session.menuSheetBody">{renaming ? (diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 813e0b7046..00a72d7c7a 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -3316,6 +3316,21 @@ function sweepDevicesOffline(deviceIds: readonly string[]): boolean {return changed;}+function cleanupRemovedSession(deviceId: string, sessionId: string, deleted: boolean): void {+ protectedQuestions.delete(sessionId);+ visibleInteractionCache.delete(sessionId);+ void clearHistoryDisk(deviceId, sessionId);+ clearRemoteHistoryViews(deviceId, sessionId);+ deleteSessionLiveActivity(sessionId);+ dropPendingTitlePreview(sessionId);+ let messageStateChanged = invalidateSessionMessageWindowState(sessionId, false);+ messageStateChanged = releaseSessionDetailProjections(sessionId) || messageStateChanged;+ sessionMessageLifecycle.forget(sessionId);+ sessionsOpenedInDetail.delete(sessionId);+ if (deleted) clearSessionMessageCache(sessionId, deviceId);+ if (messageStateChanged) bumpMessageVersion(sessionId);+}+export const remoteSessionStore = {/** Coalesce notifications for one logically atomic remote snapshot. */batch<T>(work: () => T): T {@@ -3654,7 +3669,12 @@ export const remoteSessionStore = {recomputeSessions();},- applySessionPatch(deviceId: string, sessionId: string, patch: Partial<RemoteSession>): void {+ applySessionPatch(+ deviceId: string,+ sessionId: string,+ patch: Partial<RemoteSession>,+ options?: { deferRemovalCleanup?: boolean },+ ): void {// Local optimistic removals must fence a late startup cache just like remote pushes,// even when the removed row has not reached this shard yet.if (patch.status === 'deleted' || patch.status === 'archived') bumpDeviceSessionListMutationEpoch(deviceId);@@ -3662,7 +3682,10 @@ export const remoteSessionStore = {const idx = shard?.sessions.findIndex((s) => s.id === sessionId) ?? -1;if (!shard || idx === -1) {if (patch.status === 'deleted' || patch.status === 'archived') {- sessionRemovalListeners.forEach(listener => listener(deviceId, sessionId));+ if (!options?.deferRemovalCleanup) {+ cleanupRemovedSession(deviceId, sessionId, patch.status === 'deleted');+ sessionRemovalListeners.forEach(listener => listener(deviceId, sessionId));+ }}// Separate host-owned lists can include children never opened in this mirror.// Terminal changes invalidate those lists just as unseen creations do.@@ -3674,19 +3697,10 @@ export const remoteSessionStore = {let shouldReseedAfterPatch = false;const turnEnded = historyTurnEnded(shard.sessions[idx], patch);if (patch.status === 'deleted' || patch.status === 'archived') {- protectedQuestions.delete(sessionId);- visibleInteractionCache.delete(sessionId);- void clearHistoryDisk(deviceId, sessionId);- clearRemoteHistoryViews(deviceId, sessionId);shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);- deleteSessionLiveActivity(sessionId);- dropPendingTitlePreview(sessionId);- let messageStateChanged = invalidateSessionMessageWindowState(sessionId, false);- messageStateChanged = releaseSessionDetailProjections(sessionId) || messageStateChanged;- sessionMessageLifecycle.forget(sessionId);- sessionsOpenedInDetail.delete(sessionId);- if (patch.status === 'deleted') clearSessionMessageCache(sessionId, deviceId);- if (messageStateChanged) bumpMessageVersion(sessionId);+ if (!options?.deferRemovalCleanup) {+ cleanupRemovedSession(deviceId, sessionId, patch.status === 'deleted');+ }} else {const wasPinned = shard.sessions[idx].pinnedAt != null;const unpinned = Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;@@ -3714,7 +3728,7 @@ export const remoteSessionStore = {shouldReseedAfterPatch = wasPinned && unpinned;}recomputeSessions();- if (patch.status === 'deleted' || patch.status === 'archived') {+ if ((patch.status === 'deleted' || patch.status === 'archived') && !options?.deferRemovalCleanup) {sessionRemovalListeners.forEach(listener => listener(deviceId, sessionId));}if (turnEnded && patch.status !== 'deleted' && patch.status !== 'archived') {diff --git a/apps/mobile/src/session/useSessionListActions.ts b/apps/mobile/src/session/useSessionListActions.tsindex f6c857e6cf..29c27173d1 100644--- a/apps/mobile/src/session/useSessionListActions.ts+++ b/apps/mobile/src/session/useSessionListActions.ts@@ -47,20 +47,48 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()const [renameSessionDraft, setRenameSessionDraft] = useState('');const pendingSheetActionRef = useRef<(() => void) | null>(null);- const patchSession = useCallback(async (session: RemoteSession, patch: SessionMetaPatch) => {+ const patchSession = useCallback(async (+ session: RemoteSession,+ patch: SessionMetaPatch,+ prepare?: (isLatest: () => boolean) => Promise<boolean>,+ ) => {const devices = resolveSessionWriteDevices(session.id, session);if (!devices) throw new Error(t('devices.list.error.sessionDeviceNotFound'));const { rpcDeviceId, shardId } = devices;const fields = Object.keys(patch);const write = sessionMetaWriteGuard.begin(session.id, writeGuardFields(patch));- const applyOptimistic = () => remoteSessionStore.applySessionPatch(shardId, session.id, patch);+ // 查询/确认期间只移走行,取消不应清掉已有消息与历史缓存。+ const applyOptimistic = () => remoteSessionStore.applySessionPatch(+ shardId, session.id, patch, prepare ? { deferRemovalCleanup: true } : undefined,+ );if ((patch.status !== undefined || patch.pinnedAt !== undefined) && animateListChange) {animateListChange(applyOptimistic);} else {applyOptimistic();}const releasePending = sessionPendingWrites.track(session.id, fields);+ const restoreSession = () => {+ const shardName = remoteSessionStore.getSessions()+ .find((s) => s.deviceLinkDeviceId === shardId)?.deviceLinkDeviceName+ ?? session.deviceLinkDeviceName+ ?? shardId;+ releasePending();+ const rollback = () => {+ remoteSessionStore.upsertDeviceSession(shardId, shardName, session);+ remoteSessionStore.requestReseed(shardId);+ };+ if (animateListChange) animateListChange(rollback);+ else rollback();+ };try {+ if (prepare) {+ const confirmed = await prepare(write.isLatest);+ if (!write.isLatest()) return;+ if (!confirmed) {+ restoreSession();+ return;+ }+ }const updated = await withNewSessionCreationRemoval(session.id, rpcDeviceId, patch.status,() => sessionMetaWriteQueue.enqueue(session.id, fields, () => retryPatchWhileLatest(write.isLatest,@@ -91,18 +119,8 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()remoteSessionStore.requestReseed(shardId);return;}- const shardName = remoteSessionStore.getSessions()- .find((s) => s.deviceLinkDeviceId === shardId)?.deviceLinkDeviceName- ?? session.deviceLinkDeviceName- ?? shardId;// 先释放本笔在途登记:upsertDeviceSession 会挡掉 status 在途、已被乐观移出的行。- releasePending();- const rollback = () => {- remoteSessionStore.upsertDeviceSession(shardId, shardName, session);- remoteSessionStore.requestReseed(shardId);- };- if (animateListChange) animateListChange(rollback);- else rollback();+ restoreSession();} else {const rollback = () => {const currentUpdatedAt = remoteSessionStore.getSessions()@@ -128,29 +146,17 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()}, [animateListChange, invoke, t]);const runSwipeAction = useCallback((session: RemoteSession, action: Exclude<SessionSwipeAction, 'rename'>) => {- void patchSession(session, swipeActionPatch(action)).catch((err: unknown) => {+ void patchSession(session, swipeActionPatch(action), action === 'archive' ? async (isLatest) => {+ const devices = resolveSessionWriteDevices(session.id, session);+ const names = devices ? await loadActiveBoundScheduleNames({+ deviceId: devices.rpcDeviceId, invoke, sessionId: session.id, source: session.source,+ }) : [];+ return isLatest() && confirmArchiveWithSchedules(t, names);+ } : undefined).catch((err: unknown) => {swipeRegistry.closeOpenRow();Alert.alert(t('devices.list.alert.actionFailed'), humanizeRemoteError(err));});- }, [patchSession, swipeRegistry, t]);-- // 绑定了 active 自动化的任务归档前先确认(归档后电脑会暂停它们);普通任务直接归档。- const archiveWithScheduleConfirm = useCallback(async (session: RemoteSession) => {- const devices = resolveSessionWriteDevices(session.id, session);- const names = devices- ? await loadActiveBoundScheduleNames({- deviceId: devices.rpcDeviceId,- invoke,- sessionId: session.id,- source: session.source,- })- : [];- if (!(await confirmArchiveWithSchedules(t, names))) {- swipeRegistry.closeOpenRow();- return;- }- runSwipeAction(session, 'archive');- }, [invoke, runSwipeAction, swipeRegistry, t]);+ }, [invoke, patchSession, swipeRegistry, t]);const applySessionSheetAction = useCallback((session: RemoteSession, action: SessionSwipeAction) => {if (action === 'delete') {@@ -167,12 +173,8 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()setRenameSessionTarget(session);return;}- if (action === 'archive') {- void archiveWithScheduleConfirm(session);- return;- }runSwipeAction(session, action);- }, [archiveWithScheduleConfirm, runSwipeAction, t]);+ }, [runSwipeAction, t]);const handleSessionSheetAction = useCallback((action: SessionSwipeAction) => {const session = actionSheetSession;@@ -215,9 +217,8 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()const archiveSession = useCallback((session: RemoteSession) => {const { action } = statusToggleAction(session.status);- if (action === 'archive') void archiveWithScheduleConfirm(session);- else runSwipeAction(session, action);- }, [archiveWithScheduleConfirm, runSwipeAction]);+ runSwipeAction(session, action);+ }, [runSwipeAction]);const showSessionOptions = useCallback((session: RemoteSession) => {setActionSheetSession(session);diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 4dca911e2a..1161dd86cf 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -40,6 +40,18 @@ Cindy 的产品形态不止本地桌面单机。同一个功能可能运行在同步 topic 路由;不登记,手机/远程控制端就永远调不通。3. 手机版需不需要对应的入口/UI/交互?+## 远程任务存档的即时反馈++桌面与手机的远程任务列表在点击存档后立即乐观移走任务行,不能等待远程预检或写入+返回才更新。既有的运行态、接管、worktree 与自动化确认仍在真正写入前执行;取消、+拦截或失败恢复列表,迟到的预检不能覆盖用户后续的恢复操作。预检期间保留任务内容,+不提前清理消息或草稿;详情页在确认通过后再退出。手机详情菜单先收起,关闭动画结束后+再查询并弹确认,避免远程等待卡住菜单或原生弹窗被关闭动画吞掉。++实现与回归:Desktop `useSessionLifecycleActions`、`sharedTaskArchiveGuard.test.ts`;+Mobile `useSessionListActions`、`SessionMenuSheet`、`orphanSessionActions.test.ts` 与+`remoteSessionStore.test.ts`。+## 代输入的多端适配(2026-10-13)产品规则见 [`../product-rules/input-handoff.md`](../product-rules/input-handoff.md)。三种形态的落点: