Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 后台任务终态事件丢失后按 main 快照对账收口 (#2003)
DavidShenXDbe8072f2569d
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreBackgroundTaskReconcile.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreBackgroundTaskReconcile.test.tsnew file mode 100644index 0000000000..57a7779d17--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreBackgroundTaskReconcile.test.ts@@ -0,0 +1,422 @@+/**+ * makerChatStoreBackgroundTaskReconcile.test.ts+ * ---------------------------------------------------------------------------+ * 后台任务 stale running 对账自愈(终态 agent_task_update 丢失后的收口):+ * - seedBackgroundTaskSnapshots + staleRunningCandidates:候选集内、仍+ * running、不在快照中的 claude-code 条目收口为 stopped;快照命中 / 非候选 /+ * 非 claude-code / 已终态条目一律不动;收口后迟到的真实事件仍能覆盖。+ * - captureRunningClaudeTaskIds:候选集捕获口径。+ * - initGlobalListeners 的活动熄灭触发:active:false → 延迟拉快照对账;+ * active:true 取消;远程会话豁免;无 running 条目不发 IPC。+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/lib/messageService', () => ({+ list: vi.fn(async () => []),+ create: vi.fn(async () => ({}) as unknown),+ updateContent: vi.fn(async () => ({}) as unknown),+}));++vi.mock('@/lib/sessionService', () => ({+ get: vi.fn(async () => ({+ agentKind: 'cc',+ remoteHostId: null,+ sdkSessionId: null,+ fastMode: false,+ contextTokens: 0,+ contextWindow: 0,+ totalCostUsd: 0,+ })),+ update: vi.fn(async () => ({})),+ touchUserSend: vi.fn(async () => ({})),+}));++vi.mock('@/lib/sessionsBus', () => ({+ emitPatch: vi.fn(),+}));++vi.mock('@/lib/userPromptStore', () => ({+ getUserPrompt: () => '',+}));++vi.mock('@/lib/memorySettingsStore', () => ({+ getMakerMemoryEnabled: () => true,+}));++vi.mock('@/lib/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));++vi.mock('@/lib/imageRef', () => ({+ parseUserContent: vi.fn((c: string) => ({ text: c, images: [], files: [] })),+ stringifyUserContent: vi.fn((text: string, images = [], files = []) =>+ JSON.stringify({ text, images, files }),+ ),+}));++vi.mock('@/lib/composerDraftStore', () => ({+ saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),+ plainTextToTiptapDoc: (s: string) => ({+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],+ }),+}));++// 远程判定按 id 前缀 + 可动态标记的集合,便于测「远程会话豁免对账」以及+// 「调度后、触发前才识别为远程」的粘滞复查分支。+const transportMocks = vi.hoisted(() => ({ dynamicRemoteIds: new Set<string>() }));+const isMockRemote = (sessionId: string): boolean =>+ sessionId.startsWith('remote-') || transportMocks.dynamicRemoteIds.has(sessionId);++vi.mock('@/lib/makerTransport', () => ({+ makerApiFor: () => ({+ input: {+ stop: vi.fn(async () => ({ queue: [], paused: false })),+ clearSession: vi.fn(async () => ({ queue: [], paused: false })),+ },+ closeSession: vi.fn(async () => undefined),+ }),+ getSessionFor: vi.fn(async () => ({})),+ listMessagesFor: vi.fn(async () => []),+ aroundMessagesFor: vi.fn(async () => []),+ aroundMessagesByClientIdFor: vi.fn(async () => []),+ isRemoteSession: (sessionId: string) => isMockRemote(sessionId),+ isRemoteSessionSticky: (sessionId: string) => isMockRemote(sessionId),+}));++import { makerChatStore } from '@/lib/makerChatStore';++const applyTask = (sessionId: string, data: Record<string, unknown>): void => {+ makerChatStore.__applyStreamEventForTest(sessionId, {+ sessionId,+ type: 'agent_task_update',+ source: 'claude-code',+ data: { provider: 'claude-code', ...data },+ } as CCAgentStreamEvent);+};++describe('seedBackgroundTaskSnapshots stale running 对账', () => {+ it('候选集内不在快照的 running 条目收口为 stopped;别名双键共享同一对象', () => {+ const sid = `rec-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, {+ taskId: 't-stale',+ parentToolUseId: 'tu-stale',+ status: 'running',+ taskType: 'local_agent',+ });+ const candidates = makerChatStore.captureRunningClaudeTaskIds(sid);+ expect(candidates.has('t-stale')).toBe(true);++ makerChatStore.seedBackgroundTaskSnapshots(sid, [], {+ staleRunningCandidates: candidates,+ });++ const tasks = makerChatStore.getSnapshot(sid).taskUpdates;+ expect(tasks?.get('t-stale')?.status).toBe('stopped');+ expect(tasks?.get('tu-stale')?.status).toBe('stopped');+ // 别名键共享同一新对象(isSameAgentTaskAlias 语义不被破坏)+ expect(tasks?.get('t-stale')).toBe(tasks?.get('tu-stale'));+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('快照命中(taskId 或 toolUseId 别名)的候选条目保持 running', () => {+ const sid = `rec2-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't-alive', status: 'running', taskType: 'local_agent' });+ applyTask(sid, {+ taskId: 't-alias',+ parentToolUseId: 'tu-alias',+ status: 'running',+ taskType: 'local_bash',+ });+ const candidates = makerChatStore.captureRunningClaudeTaskIds(sid);++ makerChatStore.seedBackgroundTaskSnapshots(+ sid,+ [+ { taskId: 't-alive' },+ // main 侧快照以 toolUseId 报同一任务(别名命中同样算存活)+ { taskId: 't-alias-renamed', toolUseId: 'tu-alias' },+ ],+ { staleRunningCandidates: candidates },+ );++ const tasks = makerChatStore.getSnapshot(sid).taskUpdates;+ expect(tasks?.get('t-alive')?.status).toBe('running');+ expect(tasks?.get('t-alias')?.status).toBe('running');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('候选集外的 running(请求在飞窗口内新启动)与已终态条目不动;codex 条目不受空快照影响', () => {+ const sid = `rec3-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't-old', status: 'running', taskType: 'local_agent' });+ const candidates = makerChatStore.captureRunningClaudeTaskIds(sid);+ // 候选捕获之后才启动的任务(模拟请求在飞窗口)+ applyTask(sid, { taskId: 't-fresh', status: 'running', taskType: 'local_agent' });+ // 已终态条目+ applyTask(sid, { taskId: 't-done', status: 'completed', taskType: 'local_agent' });+ // codex 任务:快照通道只覆盖 claude-code,空快照对它没有含义+ makerChatStore.__applyStreamEventForTest(sid, {+ sessionId: sid,+ type: 'agent_task_update',+ source: 'codex',+ data: { provider: 'codex', taskId: 't-codex', status: 'running' },+ } as CCAgentStreamEvent);++ makerChatStore.seedBackgroundTaskSnapshots(sid, [], {+ staleRunningCandidates: candidates,+ });++ const tasks = makerChatStore.getSnapshot(sid).taskUpdates;+ expect(tasks?.get('t-old')?.status).toBe('stopped');+ expect(tasks?.get('t-fresh')?.status).toBe('running');+ expect(tasks?.get('t-done')?.status).toBe('completed');+ expect(tasks?.get('t-codex')?.status).toBe('running');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('收口非终局:迟到的真实事件仍能覆盖(终态 → completed / 进度 → running)', () => {+ const sid = `rec4-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't-late', status: 'running', taskType: 'local_agent' });+ applyTask(sid, { taskId: 't-back', status: 'running', taskType: 'local_bash' });+ const candidates = makerChatStore.captureRunningClaudeTaskIds(sid);+ makerChatStore.seedBackgroundTaskSnapshots(sid, [], {+ staleRunningCandidates: candidates,+ });+ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t-late')?.status).toBe('stopped');++ // 迟到的 task_notification 终态:stopped → completed(真实结局胜出)+ applyTask(sid, { taskId: 't-late', status: 'completed' });+ // 迟到的 task_progress:任务实际存活,翻回 running(自愈,不误杀)+ applyTask(sid, { taskId: 't-back', status: 'running' });++ const tasks = makerChatStore.getSnapshot(sid).taskUpdates;+ expect(tasks?.get('t-late')?.status).toBe('completed');+ expect(tasks?.get('t-back')?.status).toBe('running');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('captureRunningClaudeTaskIds 只含 running 的 claude-code 任务,按 taskId 去重', () => {+ const sid = `cap-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, {+ taskId: 't-run',+ parentToolUseId: 'tu-run',+ status: 'running',+ taskType: 'local_agent',+ });+ applyTask(sid, { taskId: 't-done', status: 'completed' });+ makerChatStore.__applyStreamEventForTest(sid, {+ sessionId: sid,+ type: 'agent_task_update',+ source: 'codex',+ data: { provider: 'codex', taskId: 't-codex', status: 'running' },+ } as CCAgentStreamEvent);++ const ids = makerChatStore.captureRunningClaudeTaskIds(sid);+ expect([...ids]).toEqual(['t-run']);+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('seed 与对账同次完成:快照新任务补进、stale 候选同时收口', () => {+ const sid = `rec5-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't-stale', status: 'running', taskType: 'local_agent' });+ const candidates = makerChatStore.captureRunningClaudeTaskIds(sid);++ makerChatStore.seedBackgroundTaskSnapshots(+ sid,+ [{ taskId: 't-new', taskType: 'local_bash', title: 'dev server' }],+ { staleRunningCandidates: candidates },+ );++ const tasks = makerChatStore.getSnapshot(sid).taskUpdates;+ expect(tasks?.get('t-new')?.status).toBe('running');+ expect(tasks?.get('t-stale')?.status).toBe('stopped');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });+});++// ── 活动熄灭触发的延迟自动对账(initGlobalListeners)─────────────────────────++type FanOutCb = (data: unknown) => void;++function makeElectronApiStub(listTasks: ReturnType<typeof vi.fn>) {+ let activityCb: FanOutCb | null = null;+ const fanOut = () => () => () => {};+ const stub = {+ maker: {+ onEvent: fanOut(),+ onStatusChanged: fanOut(),+ onInputProjection: fanOut(),+ onInteractionRequest: fanOut(),+ onInteractionDismissed: fanOut(),+ onSessionBackgroundActivityChanged: (cb: FanOutCb) => {+ activityCb = cb;+ return () => {+ activityCb = null;+ };+ },+ listSessionBackgroundTasks: listTasks,+ input: {+ getProjection: vi.fn(async () => Promise.reject(new Error('n/a in test'))),+ },+ },+ localDb: { messages: { onCreated: fanOut() } },+ deviceLink: { onRemotePush: fanOut() },+ };+ return { stub, emitActivity: (payload: unknown) => activityCb?.(payload) };+}++describe('活动熄灭触发的 stale running 对账', () => {+ let emitActivity: (payload: unknown) => void;+ let listTasks: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.useFakeTimers();+ listTasks = vi.fn(async () => ({ tasks: [] }));+ const made = makeElectronApiStub(listTasks);+ emitActivity = made.emitActivity;+ (globalThis as { window?: unknown }).window = { electronAPI: made.stub };+ makerChatStore.initGlobalListeners();+ });++ afterEach(() => {+ makerChatStore.__teardownGlobalListeners();+ delete (globalThis as { window?: unknown }).window;+ transportMocks.dynamicRemoteIds.clear();+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ it('active:false → 延迟拉快照,stale running 收口为 stopped', async () => {+ const sid = `act-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });++ emitActivity({ sessionId: sid, active: false });+ expect(listTasks).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(3000);+ expect(listTasks).toHaveBeenCalledWith(sid);+ // list promise → seed 的微任务落地+ await vi.advanceTimersByTimeAsync(0);++ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t1')?.status).toBe('stopped');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('到点前 active:true 取消对账;仍在快照中的任务不被收口', async () => {+ const sid = `act2-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });++ emitActivity({ sessionId: sid, active: false });+ emitActivity({ sessionId: sid, active: true });+ await vi.advanceTimersByTimeAsync(3000);+ expect(listTasks).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t1')?.status).toBe('running');++ // 再次熄灭:这次快照证明任务仍在(main 表有它)→ 保持 running+ listTasks.mockResolvedValueOnce({ tasks: [{ taskId: 't1' }] });+ emitActivity({ sessionId: sid, active: false });+ await vi.advanceTimersByTimeAsync(3000);+ await vi.advanceTimersByTimeAsync(0);+ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t1')?.status).toBe('running');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('调度后、触发前才识别为远程(重连窗口误放行)→ 触发沿粘滞复查拦下,不发本机 IPC', async () => {+ const sid = `late-remote-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });++ // 调度沿:此刻远程注册表尚未水合,会话被当成本机 → 定时器挂上+ emitActivity({ sessionId: sid, active: false });+ // 触发前:注册表水合,会话被识别为远程+ transportMocks.dynamicRemoteIds.add(sid);+ await vi.advanceTimersByTimeAsync(3000);++ // 触发沿粘滞复查必须拦下:不发本机 IPC,镜像里的 running 不被空快照错误收口+ expect(listTasks).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t1')?.status).toBe('running');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('在飞窗口:快照响应落地前会话被识别为远程 → 丢弃本机快照,镜像 running 不被收口', async () => {+ const sid = `inflight-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(sid, { taskId: 't1', status: 'running', taskType: 'local_agent' });+ let resolveList!: (v: unknown) => void;+ listTasks.mockReturnValue(+ new Promise((r) => {+ resolveList = r;+ }),+ );++ emitActivity({ sessionId: sid, active: false });+ // timer 到点:粘滞复查通过(此刻仍判本机)、候选捕获、请求发出+ await vi.advanceTimersByTimeAsync(3000);+ expect(listTasks).toHaveBeenCalledWith(sid);++ // 请求在飞期间远程注册表完成会话水合,随后本机空表才落地+ transportMocks.dynamicRemoteIds.add(sid);+ resolveList({ tasks: [] });+ await vi.advanceTimersByTimeAsync(0);++ expect(makerChatStore.getSnapshot(sid).taskUpdates?.get('t1')?.status).toBe('running');+ } finally {+ makerChatStore.purgeSession(sid);+ }+ });++ it('远程会话豁免;无 running 条目不发 IPC', async () => {+ const remoteSid = 'remote-act3';+ const idleSid = `act4-${Math.random().toString(36).slice(2, 8)}`;+ try {+ applyTask(remoteSid, { taskId: 't1', status: 'running', taskType: 'local_agent' });+ emitActivity({ sessionId: remoteSid, active: false });+ await vi.advanceTimersByTimeAsync(3000);+ expect(listTasks).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(remoteSid).taskUpdates?.get('t1')?.status).toBe(+ 'running',+ );++ // 本机会话但没有 running 条目:调度前粗筛直接跳过+ applyTask(idleSid, { taskId: 't2', status: 'completed', taskType: 'local_agent' });+ emitActivity({ sessionId: idleSid, active: false });+ await vi.advanceTimersByTimeAsync(3000);+ expect(listTasks).not.toHaveBeenCalled();+ } finally {+ makerChatStore.purgeSession(remoteSid);+ makerChatStore.purgeSession(idleSid);+ }+ });+});diff --git a/apps/desktop/src/renderer/__tests__/useBackgroundBashTasksSeed.test.ts b/apps/desktop/src/renderer/__tests__/useBackgroundBashTasksSeed.test.tsnew file mode 100644index 0000000000..70bd3d3ae5--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useBackgroundBashTasksSeed.test.ts@@ -0,0 +1,124 @@+// @vitest-environment jsdom++/**+ * useBackgroundBashTasks 快照水合接线:候选集在发起 IPC 前捕获并透传给+ * seedBackgroundTaskSnapshots(stale running 对账);空快照 + 空候选不打扰+ * store;远程镜像会话整条链路关闭。+ */++import { renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ captureRunningClaudeTaskIds: vi.fn((): ReadonlySet<string> => new Set<string>()),+ seedBackgroundTaskSnapshots: vi.fn(),+ // 粘滞判定可独立标记:覆盖「非粘滞误判本机、粘滞仍认远程」的重连窗口分支。+ stickyRemoteIds: new Set<string>(),+}));++vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: {+ captureRunningClaudeTaskIds: mocks.captureRunningClaudeTaskIds,+ seedBackgroundTaskSnapshots: mocks.seedBackgroundTaskSnapshots,+ },+}));++vi.mock('@/lib/makerTransport', () => ({+ isRemoteSession: (sessionId: string) => sessionId.startsWith('remote-'),+ isRemoteSessionSticky: (sessionId: string) =>+ sessionId.startsWith('remote-') || mocks.stickyRemoteIds.has(sessionId),+}));++import { useBackgroundBashTasks } from '@/hooks/useBackgroundBashTasks';++describe('useBackgroundBashTasks 快照水合 + 对账接线', () => {+ let listTasks: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ // clearAllMocks 不清 mockReturnValue,显式回位空候选集,避免用例间串状态。+ mocks.captureRunningClaudeTaskIds.mockReturnValue(new Set<string>());+ listTasks = vi.fn(async () => ({ tasks: [] }));+ (window as unknown as { electronAPI: unknown }).electronAPI = {+ maker: { listSessionBackgroundTasks: listTasks },+ };+ });++ afterEach(() => {+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;+ mocks.stickyRemoteIds.clear();+ vi.clearAllMocks();+ });++ it('候选集在发起 IPC 前捕获,空快照 + 非空候选仍触发 seed(对账信号)', async () => {+ const candidates = new Set(['t-stale']);+ mocks.captureRunningClaudeTaskIds.mockReturnValue(candidates);++ renderHook(() => useBackgroundBashTasks('s1', new Map(), true));++ await waitFor(() => {+ expect(mocks.seedBackgroundTaskSnapshots).toHaveBeenCalledWith('s1', [], {+ staleRunningCandidates: candidates,+ });+ });+ // 捕获必须先于 IPC 发起(时序契约:请求在飞窗口内新启动的任务不得进候选集)+ expect(mocks.captureRunningClaudeTaskIds.mock.invocationCallOrder[0]).toBeLessThan(+ listTasks.mock.invocationCallOrder[0],+ );+ });++ it('空快照 + 空候选:不打扰 store', async () => {+ renderHook(() => useBackgroundBashTasks('s2', new Map(), true));+ await waitFor(() => expect(listTasks).toHaveBeenCalled());+ expect(mocks.seedBackgroundTaskSnapshots).not.toHaveBeenCalled();+ });++ it('远程镜像会话:不拉快照也不对账', async () => {+ renderHook(() => useBackgroundBashTasks('remote-s3', new Map(), true));+ await Promise.resolve();+ expect(listTasks).not.toHaveBeenCalled();+ expect(mocks.captureRunningClaudeTaskIds).not.toHaveBeenCalled();+ });++ it('在飞窗口:响应落地前会话被识别为远程 → 整体丢弃本机快照,不收口', async () => {+ const sid = 's5-inflight';+ mocks.captureRunningClaudeTaskIds.mockReturnValue(new Set(['t-mirror']));+ let resolveList!: (v: { tasks: unknown[] }) => void;+ listTasks.mockReturnValue(+ new Promise((r) => {+ resolveList = r;+ }),+ );++ renderHook(() => useBackgroundBashTasks(sid, new Map(), true));+ await waitFor(() => expect(listTasks).toHaveBeenCalledWith(sid));++ // 请求在飞期间远程注册表完成会话水合+ mocks.stickyRemoteIds.add(sid);+ resolveList({ tasks: [] });+ await waitFor(() => expect(listTasks).toHaveBeenCalled());+ await Promise.resolve();++ expect(mocks.seedBackgroundTaskSnapshots).not.toHaveBeenCalled();+ });++ it('重连窗口(非粘滞误判本机、粘滞仍认远程):只 seed 不对账,空快照不收口', async () => {+ const sid = 's4-blip';+ mocks.stickyRemoteIds.add(sid);+ mocks.captureRunningClaudeTaskIds.mockReturnValue(new Set(['t-mirror-running']));++ renderHook(() => useBackgroundBashTasks(sid, new Map(), true));+ await waitFor(() => expect(listTasks).toHaveBeenCalledWith(sid));++ // 粘滞命中远程:候选集不捕获;本机空快照下 seed 不被调用(不得收口镜像任务)+ expect(mocks.captureRunningClaudeTaskIds).not.toHaveBeenCalled();+ expect(mocks.seedBackgroundTaskSnapshots).not.toHaveBeenCalled();++ // 快照非空(理论分支:本机撞 id)同样整体丢弃 —— 本机来源快照对远程会话+ // 无意义,响应侧粘滞复查统一拦截,不 seed。+ listTasks.mockResolvedValueOnce({ tasks: [{ taskId: 't-new' }] });+ renderHook(() => useBackgroundBashTasks(sid, new Map(), false));+ await waitFor(() => expect(listTasks).toHaveBeenCalledTimes(2));+ await Promise.resolve();+ expect(mocks.seedBackgroundTaskSnapshots).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsxindex d7396b00db..afcfac81c5 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx@@ -15,7 +15,8 @@* - 面板不可见(非激活 tab / 壳子隐藏)时订阅挂空,恢复可见时重订阅自动补读。* - 快照水合:挂载时对本机会话调一次 listSessionBackgroundTasks 经* seedBackgroundTaskSnapshots 补存量(与 useBackgroundBashTasks 同口径,只复用- * store 公开函数);device-link 远程会话跳过(main 拿不到 handle,快照必空)。+ * store 公开函数);本机会话同一次快照兼做 stale running 对账(终态事件丢失+ * 的自愈),device-link 远程会话只 seed 不对账(降级空表不可当权威)。* - wf 文件辅源:详情视图挂载时拉一次 getWorkflowProgressFor,任务从 running 翻* 终态时再拉一次;不轮询。远程/老被控端自动降级返回 null。* - 停止:gating = running + claude-code + 有 taskId + 非远程会话;在飞防连点、@@ -536,13 +537,35 @@ export function BackgroundTasksBody({useEffect(() => {if (!sessionId) return;let disposed = false;+ // 同一次快照兼做 stale running 对账(终态事件丢失的自愈)。候选集在发起+ // 请求前捕获(时序论证见 store 的 reconcileStaleRunningTasks);仅本机会话+ // 参与 —— device-link 远程快照有老被控端降级空表窗口,无法与「没有任务」+ // 区分,不可当权威(粘滞判定与 Stop gating 同口径)。+ const staleRunningCandidates = isRemoteSessionSticky(sessionId)+ ? undefined+ : makerChatStore.captureRunningClaudeTaskIds(sessionId);void listSessionBackgroundTasksFor(sessionId).then(({ tasks }) => {- if (disposed || !Array.isArray(tasks) || tasks.length === 0) return;- makerChatStore.seedBackgroundTaskSnapshots(sessionId, tasks);+ if (disposed || !Array.isArray(tasks)) return;+ // 响应落地前复查粘滞判定:请求在飞期间远程注册表才完成会话水合的话,+ // 快照实际来自本机 main(路由在发起时已定),「查无此会话」的空表不可+ // 用于收口 → 丢弃候选集;seed 保留(远程会话的常规水合不受影响,该+ // 空表本就 seed 不出东西)。+ const candidates =+ staleRunningCandidates && !isRemoteSessionSticky(sessionId)+ ? staleRunningCandidates+ : undefined;+ if (tasks.length === 0 && !(candidates && candidates.size > 0)) {+ return;+ }+ makerChatStore.seedBackgroundTaskSnapshots(+ sessionId,+ tasks,+ candidates ? { staleRunningCandidates: candidates } : undefined,+ );}).catch(() => {- // 静默:与 useBackgroundBashTasks 的快照失败同口径。+ // 静默:与 useBackgroundBashTasks 的快照失败同口径(失败不对账)。});return () => {disposed = true;diff --git a/apps/desktop/src/renderer/hooks/useBackgroundBashTasks.ts b/apps/desktop/src/renderer/hooks/useBackgroundBashTasks.tsindex f729feb863..1112371846 100644--- a/apps/desktop/src/renderer/hooks/useBackgroundBashTasks.ts+++ b/apps/desktop/src/renderer/hooks/useBackgroundBashTasks.ts@@ -17,7 +17,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { makerChatStore } from '@/lib/makerChatStore';import type { AgentTaskUpdate } from '@/lib/makerChatStore';-import { isRemoteSession } from '@/lib/makerTransport';+import { isRemoteSession, isRemoteSessionSticky } from '@/lib/makerTransport';export interface RunningBashTask {taskId: string;@@ -66,19 +66,39 @@ export function useBackgroundBashTasks(// 快照水合:挂载 / 切会话 / 历史重载完成后拉一次存量。maker 未 init 等瞬态失败// 保持现状 —— 实时事件流仍会自然补上。+ // 同一次快照兼做 stale running 对账:候选集必须在**发起请求前**捕获(时序论证+ // 见 store 的 reconcileStaleRunningTasks),空表 + 非空候选正是「全部已收口」+ // 的信号,不得 early-return。对账 gating 用**粘滞版**远程判定(与+ // BackgroundTasksBody、Stop gating 同口径):relay 瞬断窗口 remoteMirror+ // (非粘滞)会把远程会话误判成本机,本机空快照会把镜像里真实在跑的任务错误+ // 收口 —— 粘滞判定命中远程时只 seed 不对账。useEffect(() => {if (!sessionId || remoteMirror) return;const api = window.electronAPI?.maker;if (!api?.listSessionBackgroundTasks) return;let disposed = false;+ const staleRunningCandidates = isRemoteSessionSticky(sessionId)+ ? undefined+ : makerChatStore.captureRunningClaudeTaskIds(sessionId);void api.listSessionBackgroundTasks(sessionId).then(({ tasks }) => {- if (disposed || !Array.isArray(tasks) || tasks.length === 0) return;- makerChatStore.seedBackgroundTaskSnapshots(sessionId, tasks);+ if (disposed || !Array.isArray(tasks)) return;+ // 响应落地前复查粘滞判定:请求在飞期间远程注册表才完成会话水合的话,+ // 本机 main「查无此会话」的空表不可再套用(候选集是按本机误判捕获的,+ // 套用会误收镜像里真实在跑的任务)。本 hook 不服务远程会话,整体丢弃。+ if (isRemoteSessionSticky(sessionId)) return;+ if (tasks.length === 0 && !(staleRunningCandidates && staleRunningCandidates.size > 0)) {+ return;+ }+ makerChatStore.seedBackgroundTaskSnapshots(+ sessionId,+ tasks,+ staleRunningCandidates ? { staleRunningCandidates } : undefined,+ );}).catch(() => {- // 静默:与 useSessionBackgroundActivity 的快照失败同口径。+ // 静默:与 useSessionBackgroundActivity 的快照失败同口径(失败不对账)。});return () => {disposed = true;diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 40b2b507ed..6e34415fe4 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -4255,6 +4255,60 @@ function stopRunningAgentTasks(return changed ? next : tasks;}+/**+ * 快照对账收口:把「早于快照请求就已 running、但 main 权威表里已不存在」的+ * claude-code 条目标 stopped —— 终态 agent_task_update 丢失时的自愈路径+ * (此前 taskUpdates 不在任何 reconcile 覆盖内,终态掉帧 = spinner 永久转)。+ *+ * 时序安全性(为何不会误杀在跑任务):main 的 runningBackgroundTasks 在+ * translator push 事件时旁路更新,严格先于事件抵达 renderer——store 里能看到+ * running 的任务,main 表在更早时刻必然有它。candidates 限定为**发起快照请求+ * 之前**就已 running 的 taskId:请求在飞窗口内新启动的任务不在候选集,不收;+ * 候选任务若不在其后拉到的快照里,说明 main 侧已出表(终态/被停/会话不活跃),+ * 收口正确。即便极端竞态下收错,后续真实事件(task_progress → running /+ * task_notification → 终态)仍会覆盖回来,非终局性错误。+ *+ * 仅 provider==='claude-code'(快照通道只覆盖 claude-code 的任务表;codex /+ * pi 条目对空快照没有任何含义)。别名键(taskId / parentToolUseId)共享同一+ * 新对象,口径 = stopRunningAgentTasks。+ */+function reconcileStaleRunningTasks(+ state: SessionChatState,+ snapshot: ReadonlyArray<{ taskId: string; toolUseId?: string }>,+ candidates: ReadonlySet<string>,+): SessionChatState {+ const tasks = state.taskUpdates;+ if (!tasks || tasks.size === 0) return state;+ const alive = new Set<string>();+ for (const t of snapshot) {+ if (t && typeof t.taskId === 'string' && t.taskId) alive.add(t.taskId);+ if (t && typeof t.toolUseId === 'string' && t.toolUseId) alive.add(t.toolUseId);+ }+ let changed = false;+ const replaced = new Map<AgentTaskUpdate, AgentTaskUpdate>();+ const next = new Map<string, AgentTaskUpdate>();+ for (const [key, task] of tasks) {+ const stale =+ task.status === 'running' &&+ task.provider === 'claude-code' &&+ candidates.has(task.taskId) &&+ !alive.has(task.taskId) &&+ !(task.parentToolUseId && alive.has(task.parentToolUseId));+ if (!stale) {+ next.set(key, task);+ continue;+ }+ let stopped = replaced.get(task);+ if (!stopped) {+ stopped = { ...task, status: 'stopped' as const };+ replaced.set(task, stopped);+ }+ next.set(key, stopped);+ changed = true;+ }+ return changed ? { ...state, taskUpdates: next } : state;+}+function isSameAgentTaskAlias(left: AgentTaskUpdate, right: AgentTaskUpdate): boolean {if (left.taskId === right.taskId) return true;if (left.parentToolUseId && left.parentToolUseId === right.taskId) return true;@@ -5615,6 +5669,55 @@ type PendingTextDeltaBatch = {const pendingTextDeltaBatches = new Map<string, PendingTextDeltaBatch>();let textDeltaFlushTimer: ReturnType<typeof setTimeout> | null = null;+// ── 后台任务对账定时器(活动熄灭触发的 stale running 自愈)────────────────+// 触发沿:onSessionBackgroundActivityChanged 的 active:false(CC 子进程停止调+// 模型 —— 正是终态事件若丢失、stale running 开始显形的时刻)。延迟给正常终态+// 事件 / wake turn 落地留窗口,到点后拉一次快照走 seed+对账;每会话至多一个+// 待执行定时器(防抖),active:true 到达即取消。只在翻转沿触发,不轮询。+const BACKGROUND_TASK_RECONCILE_DELAY_MS = 3000;+const backgroundTaskReconcileTimers = new Map<string, ReturnType<typeof setTimeout>>();++function cancelBackgroundTaskReconcile(sessionId: string): void {+ const timer = backgroundTaskReconcileTimers.get(sessionId);+ if (timer !== undefined) {+ clearTimeout(timer);+ backgroundTaskReconcileTimers.delete(sessionId);+ }+}++function scheduleBackgroundTaskReconcile(sessionId: string): void {+ cancelBackgroundTaskReconcile(sessionId);+ backgroundTaskReconcileTimers.set(+ sessionId,+ setTimeout(() => {+ backgroundTaskReconcileTimers.delete(sessionId);+ // 触发沿复查远程归属(粘滞版):调度沿已筛过,但 3s 窗口内会话可能被识别+ // 为远程(启动期 registry 迟到水合等)。误放行的代价是拿本机空快照把镜像+ // 里真实在跑的任务错误收口,必须再拦一次。+ if (isRemoteSessionSticky(sessionId)) return;+ // 候选集在发起请求前捕获(时序论证见 reconcileStaleRunningTasks);此刻+ // 已无 running 条目则无账可对,不发无谓 IPC。定时器只在 store 对象初始化+ // 之后才可能到点,前向引用 makerChatStore 安全。+ const staleRunningCandidates = makerChatStore.captureRunningClaudeTaskIds(sessionId);+ if (staleRunningCandidates.size === 0) return;+ const api = window.electronAPI?.maker;+ if (!api?.listSessionBackgroundTasks) return;+ void api+ .listSessionBackgroundTasks(sessionId)+ .then(({ tasks }) => {+ if (!Array.isArray(tasks)) return;+ // 响应落地前再复查一次:请求在飞期间远程注册表才完成会话水合的话,+ // 本机「查无此会话」的空表不可用于收口镜像任务。+ if (isRemoteSessionSticky(sessionId)) return;+ makerChatStore.seedBackgroundTaskSnapshots(sessionId, tasks, { staleRunningCandidates });+ })+ .catch(() => {+ // 静默:与其余快照拉取失败同口径(失败不对账,下次翻转沿 / 挂载重试)。+ });+ }, BACKGROUND_TASK_RECONCILE_DELAY_MS),+ );+}+/*** Defensive wrapper: contextBridge proxies may not preserve the return type.* Ensures we always get a callable unsubscribe function and pushes it onto@@ -7376,6 +7479,32 @@ function initGlobalListeners(): void {},'ghosts-preview-open',);++ // ── 后台活动熄灭 → stale running 对账(终态事件丢失的自动自愈)──+ // 数据源与 sessionBackgroundActivityStore 同一广播;这里只做调度,拉取与+ // 收口逻辑在 scheduleBackgroundTaskReconcile。仅本机会话:device-link 镜像+ // 会话的快照有降级空表窗口,不可当权威(与远程豁免 running 折算同口径)。+ // 远程判定用**粘滞版**(与面板水合、Stop gating 同口径):relay 瞬断重连会+ // 清空注册表,非粘滞判定在该窗口把远程会话误判成本机 → 到点拿本机空快照把+ // 镜像里真实在跑的任务错误收口;触发沿(timer 到点)还会再复查一次。+ // 可选调用兜底:老 preload 没有该 fanOut 时不得让 initGlobalListeners 整体崩掉。+ bindIpc(+ (cb: (data: unknown) => void) =>+ window.electronAPI?.maker?.onSessionBackgroundActivityChanged?.(cb),+ (raw: unknown) => {+ const p = raw as { sessionId?: string; active?: boolean } | null;+ if (!p || typeof p.sessionId !== 'string' || !p.sessionId) return;+ if (p.active) {+ cancelBackgroundTaskReconcile(p.sessionId);+ return;+ }+ if (isRemoteSessionSticky(p.sessionId)) return;+ // 调度前粗筛:没有 running 条目就不必挂定时器;到点后还会再次捕获候选集。+ if (makerChatStore.captureRunningClaudeTaskIds(p.sessionId).size === 0) return;+ scheduleBackgroundTaskReconcile(p.sessionId);+ },+ 'session-background-activity-reconcile',+ );}/** Primarily for tests — tears down the global listeners. */@@ -7386,6 +7515,8 @@ function __teardownGlobalListeners(): void {_stopDemoteTimer();clearTextDeltaFlushTimer();pendingTextDeltaBatches.clear();+ for (const timer of backgroundTaskReconcileTimers.values()) clearTimeout(timer);+ backgroundTaskReconcileTimers.clear();clearDeferredStateNotificationTimer();pendingDeferredStateNotifications.clear();pendingMessageCreatedPatches.clear();@@ -13612,17 +13743,40 @@ export const makerChatStore = {setAskUserDraft,setTitleUpdateCallback,syncActiveTurnsFromMain,+ /**+ * 当前 running 的 claude-code 后台任务 taskId 集合(按 taskId 归一,别名键去重)。+ * 用途:快照对账的候选集捕获 —— 必须在发起 listSessionBackgroundTasks **之前**+ * 调用,请求在飞窗口内新启动的任务才不会被误收(见 reconcileStaleRunningTasks)。+ */+ captureRunningClaudeTaskIds: (sessionId: string): ReadonlySet<string> => {+ const tasks = sessions.get(sessionId)?.taskUpdates;+ const out = new Set<string>();+ if (!tasks) return out;+ for (const task of tasks.values()) {+ if (task.status === 'running' && task.provider === 'claude-code') out.add(task.taskId);+ }+ return out;+ },/*** 后台任务快照水合:把 main 的 listSessionBackgroundTasks 结果补进 taskUpdates。* 只补「store 里完全没见过」的任务 —— 事件流是唯一实时源,快照可能落后于刚到* 的终态事件,已存在的条目(无论何状态)绝不用快照的 running 覆盖复活。- * 消费方:useBackgroundBashTasks(会话挂载 / reloadMessages 清空 taskUpdates 后)。+ * 消费方:useBackgroundBashTasks(会话挂载 / reloadMessages 清空 taskUpdates 后)、+ * BackgroundTasksBody(面板挂载)、活动熄灭触发的延迟对账。+ *+ * opts.staleRunningCandidates(可选):对账收口 —— 调用方在**发起快照请求前**+ * 从 store 捕获的 running claude-code taskId 集合;seed 完成后,候选集内仍+ * running 且不在快照中的条目标 stopped(终态事件丢失的自愈,时序论证见+ * reconcileStaleRunningTasks)。仅本机会话可传:device-link 镜像会话的快照+ * 有降级空表窗口,不可当权威(与远程豁免 running 折算同口径)。*/seedBackgroundTaskSnapshots: (sessionId: string,tasks: Array<{ taskId: string; taskType?: string; toolUseId?: string; title?: string }>,+ opts?: { staleRunningCandidates?: ReadonlySet<string> },): void => {- if (!tasks.length) return;+ const candidates = opts?.staleRunningCandidates;+ if (!tasks.length && !(candidates && candidates.size > 0)) return;setState(sessionId, (s) => {let next = s;for (const t of tasks) {@@ -13645,6 +13799,9 @@ export const makerChatStore = {},} as CCAgentStreamEvent);}+ if (candidates && candidates.size > 0) {+ next = reconcileStaleRunningTasks(next, tasks, candidates);+ }return next;});},