Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复重启后远程任务恢复与红点残留
MagicLizia9c7163aadb3
diff --git a/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts b/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.tsindex bef03ba072..1abc22554b 100644--- a/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts@@ -587,6 +587,62 @@ afterEach(async () => {});describe('remote connection pool with a real host', () => {+ // 回归:重启恢复遇到 1.5s 建连超时就失败;原用例只覆盖已连上的打开/连回。+ // 生产入口 startRemoteAgentSession,最小输入为 caps 连续两次 NOT_CONNECTED;+ // unit,假计时器验证等待期间另一控制端仍可请求,且恢复后只打开一个 run。+ it('waits for a reconnect before opening, without blocking another controller', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const ready = deps();+ let attempts = 0;+ const pending = startRemoteAgentSession('claude-code', {+ sessionId: 'restored-task', workingDir: project, model: 'm1', resumeSessionId: 'native-before-restart',+ } as StartSessionOptions, {+ ...ready,+ invoke: async (args) => {+ if ((args[0] as { op: string }).op === 'caps' && ++attempts <= 2) {+ throw Object.assign(new Error('not online within 1500ms'), { code: 'NOT_CONNECTED' });+ }+ return ready.invoke(args);+ },+ });+ void pending.catch(() => undefined);+ try {+ await vi.waitFor(() => expect(attempts).toBe(1));+ expect(opens).toBe(0);+ await expect(host.handle('another-controller', { op: 'caps' })).resolves.toMatchObject({ virtualWorkspace: true });+ await vi.waitFor(() => expect(attempts).toBe(3));+ vi.useRealTimers();+ const handle = await pending;+ opened.push(handle);+ expect(opens).toBe(1);+ expect(scenario.started[0].options.resumeSessionId).toBe('native-before-restart');+ } finally {+ vi.useRealTimers();+ }+ });++ // 同一入口的停止分支:授权拒绝立即结束;open 的结果不明时不重放写入。+ it.each(['caps', 'open'] as const)('does not replay %s after a permanent denial or uncertain write', async (phase) => {+ const ready = deps();+ let attempts = 0;+ await expect(startRemoteAgentSession('claude-code', {+ sessionId: 'failed-resume', workingDir: project, model: 'm1',+ } as StartSessionOptions, {+ ...ready,+ invoke: async (args) => {+ if ((args[0] as { op: string }).op === phase) {+ attempts += 1;+ throw Object.assign(new Error(phase === 'caps' ? 'share paused' : 'reply lost'), {+ code: phase === 'caps' ? 'REMOTE_AGENT_SHARE_PAUSED' : 'NOT_CONNECTED',+ });+ }+ return ready.invoke(args);+ },+ })).rejects.toThrow();+ expect(attempts).toBe(1);+ expect(scenario.started).toHaveLength(0);+ });+it('makes room when full, then reconnects the released task to the same conversation', async () => {const pool = newPool();const a = await start(pool);diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex 20209ce673..499ef9ab6e 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -22,6 +22,7 @@ import {type RemoteAgentStreamItem,} from '@cindy/device-link';import type { AgentEvent, AgentSessionHandle, Effort, StartSessionOptions } from '@cindy/maker-core';+import { withTransientRemoteRetry } from '@cindy/maker-shared/device-link-contract';import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';import { credentialGrantPermission, type CredentialGrantRecord } from '../executor/credentialGrants';@@ -680,7 +681,14 @@ export async function startRemoteAgentSession(reconnect: boolean,onOpened: (started: RemoteStartedInfo) => void,): Promise<RemoteAgentRunClient> {- const caps = await RemoteAgentRunClient.caps(deps.invoke);+ // 重启恢复可能撞上 relay 尚未上线/拥堵冷却;只重试无副作用的能力读取,+ // 等既有链路自行恢复。open/upload/send 的交付不确定时不能整次重放。+ const caps = await withTransientRemoteRetry(() => {+ if (linkState === 'closed') {+ throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');+ }+ return RemoteAgentRunClient.caps(deps.invoke);+ });if (caps.virtualWorkspace !== true) {throw new Error('[REMOTE_AGENT_UNSUPPORTED] The other computer does not support the virtual workspace required to protect local paths.');}diff --git a/apps/desktop/src/renderer/hooks/__tests__/usePendingAlertAttention.test.ts b/apps/desktop/src/renderer/hooks/__tests__/usePendingAlertAttention.test.tsindex c1cb084270..e152f9a3a1 100644--- a/apps/desktop/src/renderer/hooks/__tests__/usePendingAlertAttention.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/usePendingAlertAttention.test.ts@@ -32,6 +32,7 @@ const interruptedPendingMock = vi.fn<() => Promise<string[]>>();const createdListeners: Array<(payload: { sessionId: string; message: { role?: string; agentMeta?: unknown } }, ownerStamp?: unknown) => void> = [];+const patchedListeners: Array<(payload: { sessionId: string; patch: Record<string, unknown> }) => void> = [];/** 驱动一次错误尾行重算并等它收敛完成。 */async function reconcile(ids: string[]): Promise<void> {@@ -43,6 +44,7 @@ describe('usePendingAlertAttention (派生收敛)', () => {beforeEach(() => {_resetPendingAlertAttentionForTests();createdListeners.length = 0;+ patchedListeners.length = 0;(window as unknown as { electronAPI: unknown }).electronAPI = {localDb: {sessions: {@@ -50,7 +52,10 @@ describe('usePendingAlertAttention (派生收敛)', () => {interruptedPending: interruptedPendingMock,},sessionsPush: {- onPatched: () => () => {},+ onPatched: (cb: typeof patchedListeners[number]) => {+ patchedListeners.push(cb);+ return () => {};+ },},messages: {onErrorPersisted: () => () => {},@@ -323,4 +328,43 @@ describe('usePendingAlertAttention (派生收敛)', () => {await Promise.resolve();expect(errorTailPendingMock).not.toHaveBeenCalled();});++ // 回归:批量续跑没有打开任务视图,启动时同时认领中断和错误尾行的红点可能残留。+ // 生产入口 usePendingAlertAttention;现有用例没有覆盖 dispatch ack 后的双账本收敛。+ // 最小输入为一次 lastTurnEndedAt patch;unit,成功清点,新错误和未恢复任务仍保留。+ it.each([false, true])('批量续跑确认后复核旧错误尾行,新错误保留=%s', async (newError) => {+ interruptedPendingMock.mockResolvedValue(['resumed', 'waiting']);+ errorTailPendingMock.mockResolvedValue(['resumed']);+ renderHook(() => usePendingAlertAttention());+ await vi.waitFor(() => expect(addMock).toHaveBeenCalledWith('waiting', 'error'));+ clearMock.mockClear();+ errorTailPendingMock.mockClear();+ errorTailPendingMock.mockResolvedValue(newError ? ['resumed'] : []);++ patchedListeners[0]!({ sessionId: 'resumed', patch: { lastTurnEndedAt: Date.now() } });+ await vi.waitFor(() => expect(errorTailPendingMock).toHaveBeenCalled());+ await refreshPendingAlerts();++ if (newError) expect(clearMock).not.toHaveBeenCalledWith('resumed', expect.anything());+ else expect(clearMock).toHaveBeenCalledWith('resumed', { intent: 'explicit' });+ expect(clearMock).not.toHaveBeenCalledWith('waiting', expect.anything());+ });++ // 同一回归的启动时序:旧首拉结果迟于续跑回执返回,不得把已经恢复的任务重新打红点。+ it('首拉尚未返回时收到续跑确认,也会复核并丢弃过期错误尾行', async () => {+ let finishInitial!: (ids: string[]) => void;+ interruptedPendingMock.mockResolvedValue(['resumed', 'waiting']);+ errorTailPendingMock.mockReturnValueOnce(new Promise<string[]>((resolve) => {+ finishInitial = resolve;+ }));+ renderHook(() => usePendingAlertAttention());+ errorTailPendingMock.mockResolvedValue([]);++ patchedListeners[0]!({ sessionId: 'resumed', patch: { lastTurnEndedAt: Date.now() } });+ await vi.waitFor(() => expect(errorTailPendingMock).toHaveBeenCalledTimes(2));+ await refreshPendingAlerts();+ finishInitial(['resumed']);+ await vi.waitFor(() => expect(addMock).toHaveBeenCalledWith('waiting', 'error'));+ expect(addMock).not.toHaveBeenCalledWith('resumed', 'error');+ });});diff --git a/apps/desktop/src/renderer/hooks/usePendingAlertAttention.ts b/apps/desktop/src/renderer/hooks/usePendingAlertAttention.tsindex 43eb596f45..ed0b8a144b 100644--- a/apps/desktop/src/renderer/hooks/usePendingAlertAttention.ts+++ b/apps/desktop/src/renderer/hooks/usePendingAlertAttention.ts@@ -247,6 +247,11 @@ export function usePendingAlertAttention(): void {if (!isDataOwnerPushCurrent(ownerStamp)) return;if (patch && typeof patch === 'object' && 'lastTurnEndedAt' in patch) {noteInterruptedAck(sessionId);+ // 批量恢复不必打开任务视图。旧错误尾行可能仍在启动账本里,+ // 不能仅因它还被认领就永远保留红点;在 durable ack 后复核真源。+ // 首拉尚未应用时也复核,让过期结果被代数守卫挡住。新的错误仍由查询+ // 认领,未恢复任务的中断点也不会被清掉。+ if (_errorTailOwned.has(sessionId) || _appliedGen === 0) void refreshPendingAlerts();}});}, []);diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex b60ad13807..c44f3be941 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -115,7 +115,9 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即1. **故障层级**:只处理同一台被控端的事件拉取。`poll` 遇到 peer reset、超时、背压或链路暂断时,用同样的游标重拉(0.5s 起指数退避,上限 5s;另一个在途 poll 成功即提前恢复);连续 2 分钟拉不到才结束这台被控端上的任务并提示对方不可达。单个任务的流数据与游标对不上时只结束那一个任务。- 其余 op 不自动重放。+ 打开或连回 Agent 前的只读 `caps` 查询复用共享瞬态重试策略(最多 6 次),等待启动建连或拥堵冷却+ 结束;授权拒绝、旧端不支持等非瞬态错误立即结束。只重读这台电脑的能力,不重建 link、不重启 relay,+ 不重放 `open`、上传或发送。回归见 `remote-agent/__tests__/connectionPool.test.ts`。其余 op 不自动重放。2. **动作层级**:与故障同半径——只影响这台被控端的拉取器,不重建 link、不断开 relay、不影响其它被控端和普通远控请求。被控端侧对无人拉取的任务按任务超时(3 分钟)收尾,不波及其它任务。3. **多 peer**:被控端按 `(控制端, runId)` 隔离任务;默认每台控制设备最多 16 个任务、整机最多 64 个,