Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(task-copy): pause status polling while disconnected
Zhao Dengfengf85c5827fa75
diff --git a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsxindex 13ba570af2..97daa9023f 100644--- a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx@@ -14,29 +14,71 @@ export function useTaskMigrationStatus(session: Session) {const [status, setStatus] = useState<TaskMigrationView | null>(null);useEffect(() => {setStatus(null);- if (session.remoteHostId || isSharedTaskPeer(session.deviceLinkDeviceId ?? '')) return;+ if (+ session.remoteHostId ||+ isSharedTaskPeer(session.deviceLinkDeviceId ?? '') ||+ (session.deviceLinkDeviceId && session.deviceLinkConnectionStatus === 'disconnected')+ )+ return;const owner = getDataOwnerGeneration();let disposed = false,timer: ReturnType<typeof setTimeout> | undefined;- const refresh = async () => {+ let online = false;+ let connectionGeneration = 0;+ let receivedStatusPush = false;+ const current = () => !disposed && isDataOwnerGenerationCurrent(owner);+ const canPoll = (generation: number) =>+ current() && online && generation === connectionGeneration;+ const refresh = async (generation: number) => {+ if (!canPoll(generation)) return;try {const next = await window.electronAPI.deviceLink.taskMigration(session.deviceLinkDeviceId ?? null,{ action: 'status', sessionId: session.id },);- if (!disposed && isDataOwnerGenerationCurrent(owner)) setStatus(next);+ if (canPoll(generation)) setStatus(next);} catch {/* Old or disconnected hosts keep their existing connection UI. */}- if (!disposed && isDataOwnerGenerationCurrent(owner))- timer = setTimeout(() => void refresh(), 10_000);+ if (canPoll(generation)) timer = setTimeout(() => void refresh(generation), 10_000);};- void refresh();+ const updateConnection = (nextOnline: boolean) => {+ if (!current() || online === nextOnline) return;+ online = nextOnline;+ connectionGeneration += 1;+ clearTimeout(timer);+ if (online) void refresh(connectionGeneration);+ else setStatus(null);+ };+ // Local mode has a machine ID but no relay identity. Observe readiness before+ // querying task-copy, and let pushes win over a delayed initial snapshot.+ const offStatus = window.electronAPI.deviceLink.onStatusChanged(({ status }) => {+ receivedStatusPush = true;+ updateConnection(status === 'online');+ });+ const readConnection = async () => {+ if (!current() || receivedStatusPush) return;+ try {+ const state = await window.electronAPI.deviceLink.getState();+ if (!receivedStatusPush) updateConnection(state.linkStatus === 'online');+ } catch {+ // Retry only the readiness read if bootstrap failed; never assume online.+ if (current() && !receivedStatusPush)+ timer = setTimeout(() => void readConnection(), 10_000);+ }+ };+ void readConnection();return () => {disposed = true;+ offStatus();clearTimeout(timer);};- }, [session.id, session.deviceLinkDeviceId, session.remoteHostId]);+ }, [+ session.id,+ session.deviceLinkDeviceId,+ session.deviceLinkConnectionStatus,+ session.remoteHostId,+ ]);return status;}diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/TaskMigrationStatus.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/TaskMigrationStatus.test.tsxnew file mode 100644index 0000000000..bdcbcb2442--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/TaskMigrationStatus.test.tsx@@ -0,0 +1,209 @@+// @vitest-environment jsdom++import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { sharedTaskHostPeer, type TaskMigrationView } from '@cindy/device-link';+import type { Session } from '@/lib/ccAgent.types';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { useTaskMigrationStatus } from '../TaskMigrationStatus';++// Exercise the production observer without loading the separate copy editor.+vi.mock('../sidebar/TaskMigrationDialog', () => ({ TaskMigrationDialog: () => null }));++type LinkStatus = 'stopped' | 'connecting' | 'online';+type Listener = (event: { status: LinkStatus }) => void;+const listeners = new Set<Listener>();+const getState = vi.fn();+const taskMigration = vi.fn();+const session = { id: 'task', status: 'active' } as Session;+const complete: TaskMigrationView = { supported: true, deviceId: 'self', stage: 'complete' };++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++async function push(status: LinkStatus) {+ await act(async () => {+ for (const listener of listeners) listener({ status });+ });+}++async function advance(ms = 10_000) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+}++beforeEach(() => {+ vi.useFakeTimers();+ listeners.clear();+ getState.mockReset().mockResolvedValue({ linkStatus: 'online' });+ taskMigration.mockReset().mockResolvedValue(complete);+ setDataOwnerGeneration('owner');+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ deviceLink: {+ getState,+ taskMigration,+ onStatusChanged: (listener: Listener) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ },+ },+ });+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++// #5546: the mounted task header queried task-copy every 10s even in local mode.+// No previous test covered this observer; fake timers expose IPC traffic and stale results.+it.each(['stopped', 'connecting'] as const)(+ 'does not query task-copy while the relay is %s',+ async (linkStatus) => {+ getState.mockResolvedValue({ linkStatus });+ const { result } = renderHook(() => useTaskMigrationStatus(session));+ await advance(30_000);+ expect(taskMigration).not.toHaveBeenCalled();+ expect(result.current).toBeNull();++ await push('online');+ expect(taskMigration).toHaveBeenCalledExactlyOnceWith(null, {+ action: 'status',+ sessionId: 'task',+ });+ expect(result.current).toEqual(complete);+ await advance();+ expect(taskMigration).toHaveBeenCalledTimes(2);+ },+);++it.each([+ { pushed: 'online', snapshot: 'stopped', calls: 2 },+ { pushed: 'stopped', snapshot: 'online', calls: 0 },+] as const)(+ 'keeps a $pushed push authoritative over a late $snapshot snapshot',+ async ({ pushed, snapshot, calls }) => {+ const initial = deferred<{ linkStatus: LinkStatus }>();+ getState.mockReturnValue(initial.promise);+ renderHook(() => useTaskMigrationStatus(session));+ await push(pushed);+ await act(async () => {+ initial.resolve({ linkStatus: snapshot });+ });+ await advance();+ expect(taskMigration).toHaveBeenCalledTimes(calls);+ },+);++it('resumes after reconnect without waiting for an obsolete request or accepting its result', async () => {+ const old = deferred<TaskMigrationView>();+ taskMigration.mockReturnValueOnce(old.promise);+ const { result, unmount } = renderHook(() => useTaskMigrationStatus(session));+ await advance(0);+ expect(taskMigration).toHaveBeenCalledTimes(1);+ await push('connecting');+ await advance(30_000);+ expect(taskMigration).toHaveBeenCalledTimes(1);+ await push('online');+ expect(taskMigration).toHaveBeenCalledTimes(2);+ expect(result.current).toEqual(complete);+ await act(async () => {+ old.resolve({ ...complete, stage: 'preparing' });+ });+ await push('online');+ expect(result.current).toEqual(complete);+ await advance();+ expect(taskMigration).toHaveBeenCalledTimes(3);+ unmount();+ await push('online');+ await advance(30_000);+ expect(taskMigration).toHaveBeenCalledTimes(3);+ expect(listeners.size).toBe(0);+});++it('retries a failed connection snapshot and preserves recovery from a transient query error', async () => {+ getState.mockRejectedValueOnce(new Error('snapshot unavailable'));+ taskMigration.mockRejectedValueOnce(new Error('[PRECONDITION_FAILED] MIGRATION_FAILED'));+ const { result } = renderHook(() => useTaskMigrationStatus(session));+ await advance(0);+ expect(taskMigration).not.toHaveBeenCalled();+ await advance();+ expect(taskMigration).toHaveBeenCalledTimes(1);+ expect(result.current).toBeNull();+ await advance();+ expect(result.current).toEqual(complete);+});++it('pauses only the disconnected remote task while another target keeps polling', async () => {+ const remote = (id: string, connection: 'connected' | 'disconnected'): Session => ({+ ...session,+ id,+ deviceLinkDeviceId: id,+ deviceLinkConnectionStatus: connection,+ });+ const first = renderHook(({ task }) => useTaskMigrationStatus(task), {+ initialProps: { task: remote('A', 'connected') },+ });+ const second = renderHook(() => useTaskMigrationStatus(remote('B', 'connected')));+ await advance(0);+ first.rerender({ task: remote('A', 'disconnected') });+ taskMigration.mockClear();+ await advance();+ expect(taskMigration).toHaveBeenCalledExactlyOnceWith('B', { action: 'status', sessionId: 'B' });+ expect(second.result.current).toEqual(complete);+ first.rerender({ task: remote('A', 'connected') });+ await advance(0);+ expect(taskMigration).toHaveBeenLastCalledWith('A', { action: 'status', sessionId: 'A' });+ expect(first.result.current).toEqual(complete);+});++it.each([+ { remoteHostId: 'ssh-host' },+ { deviceLinkDeviceId: sharedTaskHostPeer('shared-task', 'host') },+])('keeps unsupported tasks out of the observer: %j', async (fields) => {+ renderHook(() => useTaskMigrationStatus({ ...session, ...fields }));+ await advance(30_000);+ expect(taskMigration).not.toHaveBeenCalled();+ expect(getState).not.toHaveBeenCalled();+ expect(listeners.size).toBe(0);+});++it('does not let a previous task response overwrite the newly selected task', async () => {+ const old = deferred<TaskMigrationView>();+ taskMigration.mockReturnValueOnce(old.promise);+ const { result, rerender } = renderHook(({ task }) => useTaskMigrationStatus(task), {+ initialProps: { task: session },+ });+ await advance(0);+ rerender({ task: { ...session, id: 'next' } });+ await advance(0);+ await act(async () => {+ old.resolve({ ...complete, stage: 'preparing' });+ });+ expect(result.current).toEqual(complete);+ taskMigration.mockClear();+ await advance();+ expect(taskMigration).toHaveBeenCalledExactlyOnceWith(null, {+ action: 'status',+ sessionId: 'next',+ });+});++it('does not dispatch a queued poll after the data owner changes', async () => {+ renderHook(() => useTaskMigrationStatus(session));+ await advance(0);+ setDataOwnerGeneration('different-owner');+ await advance(30_000);+ expect(taskMigration).toHaveBeenCalledTimes(1);+});