Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 整理任务复制弹窗并展示文件统计与进度 (#5186)
Dash0e419f44e798
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.tsindex 3f337aecd0..423490ee78 100644--- a/apps/desktop/src/main/device-link/filePeer.ts+++ b/apps/desktop/src/main/device-link/filePeer.ts@@ -621,6 +621,7 @@ export async function tryUploadPeerAttachment(source: string | Buffer,mimeType: string | undefined,invoke: Invoke,+ onProgress?: (bytes: number) => void,): Promise<string | null> {refreshCooldownOwner();const owner = captureDataOwnerBroadcastScope();@@ -675,6 +676,7 @@ export async function tryUploadPeerAttachment(return response.result;},check,+ onProgress,);const ms = Date.now() - transferStartedAt;log.debug(diff --git a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.tsnew file mode 100644index 0000000000..f9c50228d2--- /dev/null+++ b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts@@ -0,0 +1,24 @@+import { expect, it } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { estimateWorkspace } from '../workspace';++it('counts hidden and nested files, skips root Git metadata and does not count directories', async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));+ try {+ await fs.mkdir(path.join(root, '.git'));+ await fs.writeFile(path.join(root, '.git', 'objects'), 'excluded');+ await fs.writeFile(path.join(root, '.env'), 'abc');+ await fs.mkdir(path.join(root, 'sub'));+ await fs.writeFile(path.join(root, 'sub', 'file'), '12345');+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 2, bytes: 8 });+ await expect(+ estimateWorkspace(root, () => {+ throw new Error('owner changed');+ }),+ ).rejects.toThrow('owner changed');+ } finally {+ await fs.rm(root, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/src/main/task-migration/__tests__/handoff.test.ts b/apps/desktop/src/main/task-migration/__tests__/handoff.test.tsindex 3e535b9b68..f0c8579fc4 100644--- a/apps/desktop/src/main/task-migration/__tests__/handoff.test.ts+++ b/apps/desktop/src/main/task-migration/__tests__/handoff.test.ts@@ -47,7 +47,7 @@ describe('task copy progress', () => {};await expect(advanceHandoff(f.record, f.deps)).rejects.toThrow('lost acknowledgement');expect(f.durable().stage).toBe('transferring');- expect(canCancelHandoff(f.record)).toBe(false);+ expect(canCancelHandoff(f.record)).toBe(true);});it('replays the idempotent import when cleanup was interrupted', async () => {const f = fixture('transferring');@@ -68,9 +68,10 @@ describe('task copy progress', () => {expect(f.calls).toEqual(['import', 'cleanup']);expect(f.record.stage).toBe('transferring');});- it('allows cancellation only before any target import could have started', () => {+ it('allows abandoning either unfinished source stage without rolling back the target', () => {expect(canCancelHandoff(fixture().record)).toBe(true);- for (const stage of ['transferring', 'complete', 'cancelled'] as const)+ expect(canCancelHandoff(fixture('transferring').record)).toBe(true);+ for (const stage of ['complete', 'cancelled'] as const)expect(canCancelHandoff(fixture(stage).record)).toBe(false);});});diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.tsindex 73c3454049..b4f03d9cb7 100644--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts@@ -22,6 +22,7 @@ const state = vi.hoisted(() => ({boundaryBusy: false,drain: vi.fn(),exported: vi.fn(),+ uploadedProgress: vi.fn(),loseReply: '' as string,importsFail: false,siblingRunning: false,@@ -101,9 +102,11 @@ vi.mock('../../device-link/filePeer', () => ({ tryUploadPeerAttachment: async ()vi.mock('../../device-link/mediaTransfer', () => ({MAX_MEDIA_BYTES: 2 * 1024 ** 3,removeRemote: (key: string) => state.remove(key),- uploadLocalFile: async (file: string) => {+ uploadLocalFile: async (file: string, opts: { onProgress?: (bytes: number) => void }) => {const bytes = await fs.readFile(file),key = `migration/${state.files.size}`;+ opts.onProgress?.(bytes.length);+ await state.uploadedProgress(bytes.length);state.files.set(key, file);return { key, size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };},@@ -192,6 +195,7 @@ vi.mock('../../session-share/sessionShareImport', () => ({},}));vi.mock('../workspace', () => ({+ estimateWorkspace: async () => ({ fileCount: 1, bytes: 8 }),snapshotWorkspace: async (source: string, directory: string) => {state.snapshot();await fs.mkdir(directory, { recursive: true });@@ -227,6 +231,7 @@ describe('resumable cross-computer copy', () => {state.boundaryBusy = false;state.drain.mockReset();state.exported.mockClear();+ state.uploadedProgress.mockReset();state.root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-migration-service-')),);@@ -468,6 +473,61 @@ describe('resumable cross-computer copy', () => {expect(receipt().workingDir).not.toBe(firstDir);expect(receipt().workingDir).not.toBe(secondDir);});+ it('estimates each physical team workspace once without exporting or uploading', async () => {+ await team();+ const result = await requestTaskMigration({ action: 'estimate', sessionId: 'fork' });+ expect(result.estimate).toEqual({ fileCount: 2, bytes: 16 });+ expect(state.exported).not.toHaveBeenCalled();+ expect(state.files.size).toBe(0);+ });+ it('acknowledges start and retry with the registered running state', async () => {+ state.noSpace = true;+ expect((await start()).running).toBe(true);+ expect((await settled()).error).toBe('MIGRATION_NO_SPACE');+ const retry = await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect(retry.running).toBe(true);+ await settled();+ });+ it('reports actual upload bytes across files, then drops live telemetry on completion', async () => {+ let sent = 0;+ state.uploadedProgress.mockImplementation(async (size: number) => {+ sent += size;+ const status = await requestTaskMigration({ action: 'status', sessionId: 'fork' });+ expect(status.running).toBe(true);+ expect(status.progress?.phase).toBe('sending');+ expect(status.progress?.sentBytes).toBe(sent);+ expect(status.progress!.totalBytes).toBeGreaterThanOrEqual(sent);+ expect(status.progress!.bytesPerSecond).toBeGreaterThan(0);+ });+ await start();+ const result = await settled();+ expect(result.stage).toBe('complete');+ expect(state.uploadedProgress).toHaveBeenCalled();+ expect(result.progress).toBeUndefined();+ });+ it('closing a failed transfer removes source staging without deleting an already committed target', async () => {+ state.loseReply = 'receive';+ await start();+ const result = await settled();+ expect(result.stage).toBe('transferring');+ const target = state.rows.get('B')!.get(result.targetSessionId!)!;+ const targetFile = path.join(target.workingDir as string, 'draft');+ expect(await fs.readFile(targetFile, 'utf8')).toBe('original');+ const uploadedKeys = [...state.files.keys()];+ expect(uploadedKeys.length).toBeGreaterThan(0);+ state.remove.mockClear();+ expect((await requestTaskMigration({ action: 'cancel', sessionId: 'fork' })).stage).toBe(+ 'cancelled',+ );+ expect(state.remove.mock.calls.map(([key]) => key)).toEqual(uploadedKeys);+ await expect(+ fs.stat(path.join(state.root, 'A', 'task-copies', 'outgoing', result.targetSessionId!)),+ ).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readFile(targetFile, 'utf8')).toBe('original');+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');+ await start();+ expect((await settled()).stage).toBe('complete');+ });it('rejects insufficient destination space before uploading and remains cancellable', async () => {state.noSpace = true;await start();diff --git a/apps/desktop/src/main/task-migration/handoff.ts b/apps/desktop/src/main/task-migration/handoff.tsindex 6de10f0ff0..68c0720efe 100644--- a/apps/desktop/src/main/task-migration/handoff.ts+++ b/apps/desktop/src/main/task-migration/handoff.ts@@ -46,6 +46,7 @@ export async function advanceHandoff(}export function canCancelHandoff(record: MigrationHandoff): boolean {- // No target side effect has been attempted in preparing. Once transferring, query/retry only.- return record.stage === 'preparing';+ // Abandon only source staging. Never roll back a target that may have committed.+ // The service rejects cancellation while a local transfer is still running.+ return record.stage === 'preparing' || record.stage === 'transferring';}diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.tsindex 4444c9c2b9..a0789208a5 100644--- a/apps/desktop/src/main/task-migration/service.ts+++ b/apps/desktop/src/main/task-migration/service.ts@@ -49,7 +49,12 @@ import { getDesktopProviderService } from '../maker-host/createDesktopProviderSeimport { pickEnabledFallbackModel } from '../maker-host/model-route-guard';import { advanceHandoff, canCancelHandoff, type MigrationHandoff } from './handoff';import { migrationScope, type MigrationRecord, type IncomingMigration } from './journal';-import { snapshotWorkspace, restoreWorkspace, type PortableWorkspace } from './workspace';+import {+ snapshotWorkspace,+ restoreWorkspace,+ estimateWorkspace,+ type PortableWorkspace,+} from './workspace';import { memoryBudget, assertMemoryCapacity, assertDiskCapacity } from './resources';import { sendParts, receiveParts } from './transferParts';@@ -62,7 +67,7 @@ type MoveProject = (// Bootstrap supplies the existing business handler; importing maker IPC here creates a cycle.let moveProjectOnHost: MoveProject | undefined;let sourceBoundary: { isBusy(sessionId: string): boolean; drain(): Promise<void> } | undefined;-const running = new Set<string>();+const running = new Map<string, { progress?: TaskMigrationView['progress'] }>();const errorCode = (error: unknown): string => {if ((error as NodeJS.ErrnoException)?.code === 'ENOSPC') return 'MIGRATION_NO_SPACE';const message = error instanceof Error ? error.message : '';@@ -145,6 +150,7 @@ function view(scope: Scope, record: MigrationRecord | null): TaskMigrationView {? {stage: record.stage,running: running.has(`${scope.root}:${record.sessionId}`),+ progress: running.get(`${scope.root}:${record.sessionId}`)?.progress,...(record.kind === 'outgoing'? {targetDeviceId: record.targetDeviceId,@@ -355,18 +361,28 @@ async function sendFile(device: string,file: string,artifacts = path.dirname(file),+ onProgress?: (bytes: number) => void,): Promise<MigrationFile> {const space = await fs.statfs(path.dirname(file));const partBytes = Math.floor(Math.min(FILE_PEER_MAX_BYTES, MAX_MEDIA_BYTES, (space.bavail * space.bsize) / 4),);- return sendParts(file, partBytes, (part) => sendPart(scope, device, part, artifacts));+ let completed = 0;+ return sendParts(file, partBytes, async (part) => {+ const result = await sendPart(scope, device, part, artifacts, (bytes) =>+ onProgress?.(completed + bytes),+ );+ completed += result.size;+ onProgress?.(completed);+ return result;+ });}async function sendPart(scope: Scope,device: string,file: string,artifacts: string,+ onProgress?: (bytes: number) => void,): Promise<MigrationFileRef> {scope.assertCurrent();const peer = await tryUploadPeerAttachment(@@ -375,6 +391,7 @@ async function sendPart('application/octet-stream',(deviceId, channel, args) =>remoteInvoke(deviceId, channel, args, { preSend: scope.assertCurrent }),+ onProgress,);scope.assertCurrent();if (peer) {@@ -382,7 +399,8 @@ async function sendPart(if (!result) throw new Error('MIGRATION_TRANSFER_FAILED');return { ref: peer, size: result.size, sha256: result.sha256 };}- const result = await uploadLocalFile(file, { maxBytes: (await fs.stat(file)).size });+ onProgress?.(0); // OSS fallback starts this part again, not a second completed part.+ const result = await uploadLocalFile(file, { maxBytes: (await fs.stat(file)).size, onProgress });scope.assertCurrent();const keysFile = path.join(artifacts, 'transfer-keys.json');const keys = JSON.parse(readAtomicFileSync(keysFile) ?? '[]') as string[];@@ -434,6 +452,7 @@ async function preflight({ action: 'preflight', targetProject: record.targetProject, resources },scope,);+ return resources;}async function checkTargetResources(scope: Scope,@@ -481,22 +500,36 @@ async function transfer(scope: Scope, record: MigrationHandoff) {}}scope.assertCurrent();- await preflight(scope, record, workspace, directory);+ const resources = await preflight(scope, record, workspace, directory);+ const live = running.get(`${scope.root}:${record.sessionId}`)!;+ const startedAt = Date.now();+ let completed = 0;+ live.progress = {+ phase: 'sending',+ sentBytes: 0,+ totalBytes: resources.transferBytes,+ bytesPerSecond: 0,+ };+ const send = async (file: string, artifacts = path.dirname(file)) => {+ const result = await sendFile(scope, record.targetDeviceId, file, artifacts, (bytes) => {+ const sentBytes = Math.min(resources.transferBytes, completed + bytes);+ live.progress = {+ phase: 'sending',+ sentBytes,+ totalBytes: resources.transferBytes,+ bytesPerSecond: (sentBytes * 1000) / Math.max(1, Date.now() - startedAt),+ };+ });+ completed += result.size;+ return result;+ };const files: MigrationFiles = {- session: await sendFile(scope, record.targetDeviceId, path.join(directory, 'session.cshare')),- workspace: await sendFile(- scope,- record.targetDeviceId,- path.join(directory, workspace.archive.file),- ),- manifest: await sendFile(scope, record.targetDeviceId, path.join(directory, 'workspace.json')),+ session: await send(path.join(directory, 'session.cshare')),+ workspace: await send(path.join(directory, workspace.archive.file)),+ manifest: await send(path.join(directory, 'workspace.json')),...(workspace.git? {- repository: await sendFile(- scope,- record.targetDeviceId,- path.join(directory, 'repository.bundle'),- ),+ repository: await send(path.join(directory, 'repository.bundle')),}: {}),};@@ -505,25 +538,16 @@ async function transfer(scope: Scope, record: MigrationHandoff) {for (const [index, entry] of workspace.additionalWorkspaces.entries()) {const dir = workspaceDirectory(directory, index + 1);files.additionalWorkspaces.push({- workspace: await sendFile(- scope,- record.targetDeviceId,- path.join(dir, entry.archive.file),- directory,- ),+ workspace: await send(path.join(dir, entry.archive.file), directory),...(entry.git? {- repository: await sendFile(- scope,- record.targetDeviceId,- path.join(dir, 'repository.bundle'),- directory,- ),+ repository: await send(path.join(dir, 'repository.bundle'), directory),}: {}),});}}+ live.progress = { ...live.progress!, phase: 'finishing', bytesPerSecond: 0 };const result = await invoke(record.targetDeviceId,{@@ -538,10 +562,24 @@ async function transfer(scope: Scope, record: MigrationHandoff) {if (result.stage !== 'active') throw new Error('MIGRATION_TARGET_NOT_READY');}+async function cleanupOutgoing(scope: Scope, record: MigrationHandoff) {+ const directory = path.join(scope.root, 'outgoing', record.id);+ const keys = JSON.parse(+ readAtomicFileSync(path.join(directory, 'transfer-keys.json')) ?? '[]',+ ) as string[];+ for (const key of keys) {+ scope.assertCurrent();+ // Reuse the existing best-effort deletion and OSS lifecycle backstop.+ await removeRemote(key);+ }+ scope.assertCurrent();+ await fs.rm(directory, { recursive: true, force: true });+}+function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {const key = `${scope.root}:${record.sessionId}`;if (running.has(key)) return;- running.add(key);+ running.set(key, {});void withCrossProcessLock(path.join(scope.root, `source-${record.sessionId}.lock`),{ label: 'task-migration', waitMs: 0 },@@ -554,19 +592,7 @@ function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {save: async (next) => scope.save({ ...next, kind: 'outgoing' }),prepare: (r) => prepare(scope, r),import: (r) => transfer(scope, r),- cleanup: async (r) => {- const directory = path.join(scope.root, 'outgoing', r.id);- const keys = JSON.parse(- readAtomicFileSync(path.join(directory, 'transfer-keys.json')) ?? '[]',- ) as string[];- for (const key of keys) {- scope.assertCurrent();- // Existing OSS lifecycle rules backstop best-effort remote deletion.- await removeRemote(key);- }- scope.assertCurrent();- await fs.rm(directory, { recursive: true, force: true });- },+ cleanup: (r) => cleanupOutgoing(scope, r),});},)@@ -876,6 +902,20 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV},};}+ if (request.action === 'estimate') {+ const members = await sourceGroup(scope, request.sessionId);+ const roots = new Set(+ await Promise.all(members.map((member) => physicalWorktreeKey(member.workingDir))),+ );+ const estimate = { fileCount: 0, bytes: 0 };+ for (const root of roots) {+ const next = await estimateWorkspace(root, scope.assertCurrent);+ estimate.fileCount += next.fileCount;+ estimate.bytes += next.bytes;+ }+ scope.assertCurrent();+ return { ...view(scope, null), estimate };+ }if (request.action === 'preflight') {await checkTargetResources(scope, request.targetProject, request.resources);return view(scope, null);@@ -887,6 +927,7 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV...view(scope, null),projects: await projects(scope),teamMigration: true,+ copyEstimate: true,agents: (['cc', 'codex', 'pi'] as const).filter((agent) => !!pickEnabledFallbackModel(providers, agent === 'cc' ? 'claude-code' : agent),),@@ -933,10 +974,7 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationVthrow new Error('MIGRATION_CANNOT_CANCEL');const cancelled = { ...record, stage: 'cancelled' as const, error: undefined };// Keep the journal retryable until its staging data is gone.- await fs.rm(path.join(scope.root, 'outgoing', record.id), {- recursive: true,- force: true,- });+ await cleanupOutgoing(scope, record);scope.assertCurrent();scope.save(cancelled);return view(scope, cancelled);@@ -995,7 +1033,11 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV),);// Release admission before starting the background operation on the same lock.- if (nextCopy) launch(scope, nextCopy);+ if (nextCopy) {+ launch(scope, nextCopy);+ // Start/retry acknowledgements must include the operation just registered by launch.+ return view(scope, nextCopy);+ }return result;}diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.tsindex 81d12be77c..325fcb8533 100644--- a/apps/desktop/src/main/task-migration/workspace.ts+++ b/apps/desktop/src/main/task-migration/workspace.ts@@ -223,7 +223,13 @@ export async function restoreWorkspace(// Rebuild Git metadata locally; never copy source .git links, hooks, credentials or config.await gitExec(['init', '--template=', target], directory);await gitExec(- ['fetch', '--no-tags', '--no-write-fetch-head', path.join(directory, 'repository.bundle'), git.ref],+ [+ 'fetch',+ '--no-tags',+ '--no-write-fetch-head',+ path.join(directory, 'repository.bundle'),+ git.ref,+ ],target,);if (git.headRef) {@@ -235,3 +241,30 @@ export async function restoreWorkspace(await gitExec(['read-tree', git.indexTree], target);}}++/** Read-only pre-copy inventory: includes hidden/ignored files, never follows links.+ * Root Git metadata is rebuilt separately by snapshotWorkspace, not copied as files.+ */+export async function estimateWorkspace(+ root: string,+ check: () => void,+): Promise<{ fileCount: number; bytes: number }> {+ root = await fs.realpath(root);+ const result = { fileCount: 0, bytes: 0 };+ async function walk(directory: string): Promise<void> {+ for (const name of await fs.readdir(directory)) {+ check();+ if (directory === root && name === '.git') continue;+ const file = path.join(directory, name);+ const stat = await fs.lstat(file);+ if (stat.isDirectory()) await walk(file);+ else if (stat.isFile() || stat.isSymbolicLink()) {+ result.fileCount++;+ result.bytes += stat.size;+ } else throw new Error('MIGRATION_NONPORTABLE_PATH');+ }+ }+ await walk(root);+ check();+ return result;+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsxindex 96d61e3fd3..a1945c6d67 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx@@ -31,22 +31,27 @@ export function TaskMigrationDialog({const [project, setProject] = useState(destination?.project ?? '');const [status, setStatus] = useState<TaskMigrationView | null>(null);const [busy, setBusy] = useState(false);+ const [starting, setStarting] = useState(false);const [readyTarget, setReadyTarget] = useState('');const [error, setError] = useState('');+ const [pollError, setPollError] = useState('');const [self, setSelf] = useState('');+ const [estimate, setEstimate] = useState<TaskMigrationView['estimate']>();+ const [estimateError, setEstimateError] = useState(false);const pending = useRef(false);+ const observingCopy = useRef(!destination);+ const previousCopy = useRef<string | undefined>(undefined);const mutationEpoch = useRef(0);const owner = useRef(getDataOwnerGeneration()).current;const live = useRef(true);const current = () => live.current && isDataOwnerGenerationCurrent(owner);const request = (command: TaskMigrationRequest) =>window.electronAPI.deviceLink.taskMigration(session.deviceLinkDeviceId ?? null, command);+ const errorCode = (e: unknown) =>+ /\bMIGRATION_[A-Z_]+\b/.exec(e instanceof Error ? e.message : String(e))?.[0] ??+ 'MIGRATION_FAILED';const showError = (e: unknown) => {- if (current())- setError(- /\bMIGRATION_[A-Z_]+\b/.exec(e instanceof Error ? e.message : String(e))?.[0] ??- 'MIGRATION_FAILED',- );+ if (current()) setError(errorCode(e));};useEffect(() => {live.current = true;@@ -56,12 +61,28 @@ export function TaskMigrationDialog({const epoch = mutationEpoch.current;try {const next = await request({ action: 'status', sessionId: session.id });- if (!disposed && current() && epoch === mutationEpoch.current && !pending.current)- setStatus(next);+ if (!disposed && current() && epoch === mutationEpoch.current && !pending.current) {+ if (!observingCopy.current) {+ if (epoch === 0) previousCopy.current = next.targetSessionId;+ const newCopy =+ epoch > 0 && next.targetSessionId && next.targetSessionId !== previousCopy.current;+ const unfinished =+ next.stage && !['complete', 'active', 'cancelled'].includes(next.stage);+ if (newCopy || unfinished) {+ observingCopy.current = true;+ // A changed copy ID recovers a lost start acknowledgement, even if already complete.+ if (newCopy) setError('');+ }+ }+ // A fresh menu selection starts a new copy, not the previous success screen.+ setStatus(observingCopy.current ? next : { supported: true, deviceId: next.deviceId });+ setPollError('');+ }} catch (e) {- if (!disposed) showError(e);+ if (!disposed && current() && epoch === mutationEpoch.current && !pending.current)+ setPollError(errorCode(e));}- if (!disposed && current()) timer = setTimeout(() => void poll(), 2000);+ if (!disposed && current()) timer = setTimeout(() => void poll(), 1000);};void Promise.all([window.electronAPI.deviceLink.listDevices(),@@ -114,20 +135,28 @@ export function TaskMigrationDialog({disposed = true;};}, [target, self]);- const act = async (command: TaskMigrationRequest) => {+ const act = async (command: TaskMigrationRequest, dismissOnSuccess = false) => {if (pending.current || !current()) return;pending.current = true;mutationEpoch.current++;+ setStarting(command.action === 'start');setBusy(true);setError('');try {const next = await request(command);- if (current()) setStatus(next);+ if (current()) {+ if (command.action === 'start') observingCopy.current = true;+ setStatus(next);+ if (dismissOnSuccess) onDismiss();+ }} catch (e) {showError(e);} finally {pending.current = false;- if (current()) setBusy(false);+ if (current()) {+ setBusy(false);+ setStarting(false);+ }}};const started = !!status?.stage && !['cancelled', 'active', 'complete'].includes(status.stage);@@ -160,17 +189,77 @@ export function TaskMigrationDialog({showError(e);} finally {pending.current = false;- if (current()) setBusy(false);+ if (current()) {+ setBusy(false);+ setStarting(false);+ }}};- const failure = error || status?.error;+ const complete = status?.stage === 'complete' || status?.stage === 'active';+ const copying = starting || !!status?.running;+ const failure =+ error || pollError || status?.error || (started && !copying ? 'MIGRATION_FAILED' : '');+ const confirming = !started && !complete && !failure && !busy;+ useEffect(() => {+ if (!confirming) return;+ let disposed = false;+ setEstimate(undefined);+ setEstimateError(false);+ void request({ action: 'caps' })+ .then(async (caps) => {+ if (!caps.copyEstimate) throw new Error('Estimate unavailable');+ return request({ action: 'estimate', sessionId: session.id });+ })+ .then((result) => {+ if (+ !result.estimate ||+ !Number.isSafeInteger(result.estimate.fileCount) ||+ result.estimate.fileCount < 0 ||+ !Number.isSafeInteger(result.estimate.bytes) ||+ result.estimate.bytes < 0+ )+ throw new Error('Invalid estimate');+ if (!disposed && current()) setEstimate(result.estimate);+ })+ .catch(() => {+ if (!disposed && current()) setEstimateError(true);+ });+ return () => {+ disposed = true;+ };+ }, [confirming, session.id, session.deviceLinkDeviceId]);+ const displayDevice =+ status?.targetDeviceId && observingCopy.current ? status.targetDeviceId : target;+ const computerName =+ displayDevice === self || (displayDevice === destination?.deviceId && destination?.isSelf)+ ? t('taskMigration.thisComputer')+ : (devices.find((device) => device.deviceId === displayDevice)?.name ??+ (displayDevice === destination?.deviceId+ ? destination.deviceName+ : t('taskMigration.selectedComputer')));+ const closeCancels = started && !status?.running;+ const dismiss = () => {+ if (pending.current || copying) return;+ if (closeCancels) void act({ action: 'cancel', sessionId: session.id }, true);+ else onDismiss();+ };+ const progress = status?.progress;+ const percent =+ progress && progress.totalBytes > 0+ ? Math.min(100, Math.max(0, Math.floor((progress.sentBytes / progress.totalBytes) * 100)))+ : undefined;+ const bytes = (value: number) => {+ if (value >= 1024 ** 3) return `${(value / 1024 ** 3).toFixed(1)} GB`;+ if (value >= 1024 ** 2) return `${(value / 1024 ** 2).toFixed(1)} MB`;+ return `${(Math.max(0, value) / 1024).toFixed(1)} KB`;+ };const errorKey =failure && t(`taskMigration.errors.${failure}`, { defaultValue: t('taskMigration.failed') });return (<Dialog.RootopenonOpenChange={(open) => {- if (!open) onDismiss();+ if (!open) dismiss();}}><Dialog.Portal>@@ -185,24 +274,33 @@ export function TaskMigrationDialog({onKeyDown={(e) => e.stopPropagation()}><Dialog.Title className="text-lg font-medium text-[var(--confirm-title)]">- {t('taskMigration.title')}+ {t(+ complete+ ? 'taskMigration.successTitle'+ : copying+ ? 'taskMigration.copyingTitle'+ : failure+ ? 'taskMigration.failureTitle'+ : 'taskMigration.title',+ { name: computerName },+ )}</Dialog.Title><Dialog.Description className="mt-2 text-sm text-[var(--confirm-desc)]">- {t('taskMigration.description')}+ {complete+ ? t('taskMigration.successDescription', { name: computerName })+ : copying+ ? t('taskMigration.keepOpen', { name: computerName })+ : failure+ ? t('taskMigration.failureDescription')+ : t('taskMigration.description', { name: computerName })}</Dialog.Description>- <p className="mt-2 text-sm text-[var(--confirm-desc)]">- {t('taskMigration.bindingsNotice')}- </p>- {!started && destination && (+ {confirming && (+ <p className="mt-2 text-sm text-[var(--confirm-desc)]">+ {t('taskMigration.bindingsNotice')}+ </p>+ )}+ {confirming && destination && (<div className="mt-4 space-y-2 text-sm text-[var(--confirm-title)]">- <p>- {t('taskMigration.device')}: {destination.deviceName}- {(destination.isSelf || destination.deviceId === self) && (- <span className="ml-2 text-[var(--confirm-desc)]">- {t('settings.devices.thisDevice')}- </span>- )}- </p><p className="break-all">{t('taskMigration.project')}:{' '}{destination.project ?? t('taskMigration.defaultFolder')}@@ -210,7 +308,7 @@ export function TaskMigrationDialog({<p className="text-[var(--confirm-desc)]">{t('taskMigration.newFolder')}</p></div>)}- {!started && !destination && (+ {confirming && !destination && (<div className="mt-4 flex flex-col gap-3"><p className="text-sm text-[var(--confirm-desc)]">{t('taskMigration.limits')}</p><FormField label={t('taskMigration.device')}>@@ -251,56 +349,72 @@ export function TaskMigrationDialog({</FormField></div>)}- {started && (- <p className="mt-4 text-sm text-[var(--confirm-title)]" role="status">- {t(`taskMigration.stages.${status?.stage}`)}- </p>+ {confirming && (+ <div className="mt-4 text-sm">+ <p+ role="status"+ className={estimateError ? 'text-[var(--error-fg)]' : 'text-[var(--confirm-title)]'}+ >+ {estimateError+ ? t('taskMigration.estimateFailed')+ : estimate+ ? t('taskMigration.fileSummary', {+ count: estimate.fileCount,+ size: bytes(estimate.bytes),+ })+ : t('taskMigration.estimating')}+ </p>+ {estimate && (+ <p className="mt-2 text-[var(--confirm-desc)]">{t('taskMigration.estimateNote')}</p>+ )}+ </div>+ )}+ {copying && (+ <div className="mt-4 space-y-2">+ <p className="text-sm text-[var(--confirm-title)]" role="status">+ {t(+ progress?.phase === 'finishing'+ ? 'taskMigration.finishing'+ : `taskMigration.stages.${status?.stage ?? 'preparing'}`,+ { name: computerName },+ )}+ </p>+ <progress+ className="w-full accent-[var(--confirm-title)]"+ aria-label={t('taskMigration.copyingTitle', { name: computerName })}+ max={100}+ value={percent}+ />+ {progress?.phase === 'sending' && (+ <p className="text-sm tabular-nums text-[var(--confirm-desc)]">+ {t('taskMigration.transferProgress', {+ sent: bytes(progress.sentBytes),+ total: bytes(progress.totalBytes),+ speed: bytes(progress.bytesPerSecond),+ })}+ </p>+ )}+ </div>)}{failure && (<p className="mt-3 text-sm text-[var(--error-fg)]" role="alert">{errorKey}</p>)}- {started && (- <p className="mt-3 text-sm text-[var(--confirm-desc)]">- {t('taskMigration.background')}- </p>- )}- {status?.stage === 'complete' && status.targetSessionId && (- <div className="mt-3">+ <div className="mt-4 flex flex-wrap justify-end gap-2">+ {!copying && (+ <Button variant="secondary" disabled={busy} onClick={dismiss}>+ {t(confirming ? 'taskMigration.cancel' : 'taskMigration.close')}+ </Button>+ )}+ {complete && status?.targetSessionId && (<Button disabled={busy} onClick={() => void openTarget()}>{t('taskMigration.openTarget')}</Button>- </div>- )}- <div className="mt-4 flex flex-wrap justify-end gap-2">- <Button variant="secondary" onClick={onDismiss}>- {t('taskMigration.close')}- </Button>- {started &&- !status?.running &&- ['preparing', 'transferring'].includes(status?.stage ?? '') && (- <>- {status?.stage === 'preparing' && (- <Button- variant="secondary"- disabled={busy}- onClick={() => void act({ action: 'cancel', sessionId: session.id })}- >- {t('taskMigration.cancel')}- </Button>- )}- <Button- disabled={busy}- onClick={() => void act({ action: 'retry', sessionId: session.id })}- >- {t('taskMigration.retry')}- </Button>- </>- )}- {!started && (+ )}+ {confirming && (<Button- disabled={!status || busy || readyTarget !== target || !target}+ disabled={!status || !estimate || busy || readyTarget !== target || !target}onClick={() =>void act({action: 'start',diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsxindex 6a86a2b57a..e44a93a66f 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx@@ -49,7 +49,8 @@ beforeEach(() => {state.request.mockImplementation(async (device: string | null, command: { action: string }) => ({supported: true,deviceId: device ?? 'local',- ...(command.action === 'caps' ? { projects: ['B-project'] } : {}),+ ...(command.action === 'caps' ? { copyEstimate: true, projects: ['B-project'] } : {}),+ ...(command.action === 'estimate' ? { estimate: { fileCount: 3, bytes: 1200 } } : {}),}));state.openLink.mockResolvedValue(undefined);Object.assign(window, {@@ -105,11 +106,12 @@ it('uses the source host for commands and the target host for destination projecexpect(state.request.mock.calls.filter(([, command]) => command.action === 'start')).toEqual([['A', { action: 'start', sessionId: 'task', targetDeviceId: 'B', targetProject: null }],]);- fireEvent.click(screen.getByRole('button', { name: 'taskMigration.close' }));- expect(state.dismiss).toHaveBeenCalledOnce();+ expect(screen.queryByRole('button', { name: 'taskMigration.close' })).toBeNull();+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });+ expect(state.dismiss).not.toHaveBeenCalled();expect(state.request.mock.calls.some(([, command]) => command.action === 'cancel')).toBe(false);});-it('offers retry, without cancellation, when a copy transfer was interrupted', async () => {+it('ends an interrupted transfer through Close without offering retry', async () => {state.request.mockImplementation(async (device: string | null, command: { action: string }) => ({supported: true,deviceId: device ?? 'local',@@ -124,11 +126,13 @@ it('offers retry, without cancellation, when a copy transfer was interrupted', a: {}),}));mount();- const retry = await screen.findByRole('button', { name: 'taskMigration.retry' });+ await screen.findByRole('alert');+ expect(screen.getAllByRole('button')).toHaveLength(1);+ const close = screen.getByRole('button', { name: 'taskMigration.close' });expect(screen.queryByRole('button', { name: 'taskMigration.cancel' })).toBeNull();- fireEvent.click(retry);+ fireEvent.click(close);await waitFor(() =>- expect(state.request).toHaveBeenCalledWith('A', { action: 'retry', sessionId: 'task' }),+ expect(state.request).toHaveBeenCalledWith('A', { action: 'cancel', sessionId: 'task' }),);});it('loads the completed task from the target computer before navigation and dismisses the dialog', async () => {@@ -147,8 +151,10 @@ it('loads the completed task from the target computer before navigation and dismstate.invoke.mockResolvedValue({ id: 'migrated', status: 'active' });mount();await screen.findByRole('button', { name: 'taskMigration.openTarget' });- expect(screen.getByRole('button', { name: 'taskMigration.start' })).toBeTruthy();- expect(screen.getByText('taskMigration.bindingsNotice')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'taskMigration.start' })).toBeNull();+ expect(screen.queryByText('taskMigration.bindingsNotice')).toBeNull();+ expect(screen.getByText('taskMigration.successTitle')).toBeTruthy();+ expect(screen.queryByRole('combobox')).toBeNull();fireEvent.click(screen.getByRole('button', { name: 'taskMigration.openTarget' }));await waitFor(() => expect(state.dismiss).toHaveBeenCalledOnce());expect(state.openLink).toHaveBeenCalledWith('B');@@ -157,14 +163,306 @@ it('loads the completed task from the target computer before navigation and dism});it('confirms the project selected in the menu without asking for a second selection', async () => {- render(<MemoryRouter><TaskMigrationDialog session={source} onDismiss={state.dismiss}- destination={{ deviceId: 'B', deviceName: 'Work Mac', project: 'B-project' }} /></MemoryRouter>);- await waitFor(() => expect((screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled).toBe(false));+ render(+ <MemoryRouter>+ <TaskMigrationDialog+ session={source}+ onDismiss={state.dismiss}+ destination={{ deviceId: 'B', deviceName: 'Work Mac', project: 'B-project' }}+ />+ </MemoryRouter>,+ );+ await waitFor(() =>+ expect(+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,+ ).toBe(false),+ );expect(screen.queryByRole('combobox')).toBeNull();- expect(screen.getByText(/Work Mac/)).toBeTruthy();+ expect(screen.getByText('taskMigration.title')).toBeTruthy();expect(screen.getByText(/B-project/)).toBeTruthy();fireEvent.click(screen.getByRole('button', { name: 'taskMigration.start' }));- await waitFor(() => expect(state.request).toHaveBeenCalledWith('A', {- action: 'start', sessionId: 'task', targetDeviceId: 'B', targetProject: 'B-project',- }));+ await waitFor(() =>+ expect(state.request).toHaveBeenCalledWith('A', {+ action: 'start',+ sessionId: 'task',+ targetDeviceId: 'B',+ targetProject: 'B-project',+ }),+ );+});++it.each(['button', 'escape'])(+ 'cancels failed preparation before dismissing via %s',+ async (method) => {+ let finishCancel!: (value: unknown) => void;+ state.request.mockImplementation(async (_device, command) => {+ if (command.action === 'cancel')+ return new Promise((resolve) => {+ finishCancel = resolve;+ });+ return command.action === 'status'+ ? { stage: 'preparing', running: false, error: 'MIGRATION_SOURCE_BUSY' }+ : { deviceId: 'local', projects: [] };+ });+ mount();+ await screen.findByRole('alert');+ expect(screen.getAllByRole('button')).toHaveLength(1);+ expect(screen.queryByText('taskMigration.background')).toBeNull();+ const close = screen.getByRole('button', { name: 'taskMigration.close' });+ if (method === 'escape') fireEvent.keyDown(close, { key: 'Escape' });+ else fireEvent.click(close);+ await waitFor(() =>+ expect(state.request).toHaveBeenCalledWith('A', { action: 'cancel', sessionId: 'task' }),+ );+ expect(state.dismiss).not.toHaveBeenCalled();+ fireEvent.click(close);+ expect(+ state.request.mock.calls.filter(([, command]) => command.action === 'cancel'),+ ).toHaveLength(1);+ finishCancel({ stage: 'cancelled' });+ await waitFor(() => expect(state.dismiss).toHaveBeenCalledOnce());+ },+);++it('keeps failed cleanup visible and lets Close retry cancellation', async () => {+ let cancellations = 0;+ state.request.mockImplementation(async (_device, command) => {+ if (command.action === 'cancel') {+ if (++cancellations === 1) throw new Error('MIGRATION_FAILED');+ return { stage: 'cancelled' };+ }+ return command.action === 'status'+ ? { stage: 'preparing', running: false, error: 'MIGRATION_SOURCE_BUSY' }+ : { deviceId: 'local', projects: [] };+ });+ mount();+ await screen.findByRole('alert');+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.close' }));+ await screen.findByText('taskMigration.errors.MIGRATION_FAILED');+ expect(state.dismiss).not.toHaveBeenCalled();+ expect(screen.getAllByRole('button')).toHaveLength(1);+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.close' }));+ await waitFor(() => expect(state.dismiss).toHaveBeenCalledOnce());+ expect(cancellations).toBe(2);+});++it('keeps transfer progress in the dialog until the target completes, including older hosts', async () => {+ let snapshot: Record<string, unknown> = { stage: 'preparing', running: true };+ state.request.mockImplementation(async (_device, command) =>+ command.action === 'status' ? snapshot : { deviceId: 'local', projects: [] },+ );+ mount();+ await screen.findByRole('progressbar');+ expect(screen.getByRole('progressbar').hasAttribute('value')).toBe(false);+ expect(screen.queryByRole('button', { name: 'taskMigration.close' })).toBeNull();+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });+ expect(state.dismiss).not.toHaveBeenCalled();+ snapshot = {+ stage: 'transferring',+ running: true,+ progress: {+ phase: 'sending',+ sentBytes: 25,+ totalBytes: 100,+ bytesPerSecond: 10,+ },+ };+ await waitFor(() => expect(screen.getByRole('progressbar').getAttribute('value')).toBe('25'), {+ timeout: 2500,+ });+ expect(screen.getByText('taskMigration.transferProgress')).toBeTruthy();+ snapshot = {+ stage: 'transferring',+ running: true,+ progress: {+ phase: 'finishing',+ sentBytes: 100,+ totalBytes: 100,+ bytesPerSecond: 0,+ },+ };+ await screen.findByText('taskMigration.finishing', {}, { timeout: 2500 });+ expect(screen.queryByText('taskMigration.successTitle')).toBeNull();+ snapshot = { stage: 'complete', running: false, targetSessionId: 'copy', targetDeviceId: 'B' };+ await screen.findByText('taskMigration.successTitle', {}, { timeout: 2500 });+ expect(screen.queryByRole('progressbar')).toBeNull();+ expect(screen.queryByRole('button', { name: 'taskMigration.start' })).toBeNull();+ expect(screen.getAllByRole('button')).toHaveLength(2);+});++it('a new destination selection does not reopen the previous copy success screen', async () => {+ state.request.mockImplementation(async (_device, command) =>+ command.action === 'status'+ ? {+ supported: true,+ deviceId: 'A',+ stage: 'complete',+ targetSessionId: 'old-copy',+ targetDeviceId: 'B',+ }+ : {+ supported: true,+ deviceId: 'B',+ projects: [],+ copyEstimate: true,+ estimate: { fileCount: 1, bytes: 8 },+ },+ );+ render(+ <MemoryRouter>+ <TaskMigrationDialog+ session={source}+ onDismiss={state.dismiss}+ destination={{ deviceId: 'B', deviceName: 'Work Mac', project: 'B-project' }}+ />+ </MemoryRouter>,+ );+ await waitFor(() =>+ expect(+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,+ ).toBe(false),+ );+ expect(screen.queryByText('taskMigration.successTitle')).toBeNull();+ expect(screen.queryByRole('button', { name: 'taskMigration.openTarget' })).toBeNull();});++it('waits for source file inventory before enabling Copy', async () => {+ let finish!: (value: unknown) => void;+ const original = state.request.getMockImplementation()!;+ state.request.mockImplementation((device, command) =>+ command.action === 'estimate'+ ? new Promise((resolve) => {+ finish = resolve;+ })+ : original(device, command),+ );+ render(+ <MemoryRouter>+ <TaskMigrationDialog+ session={source}+ onDismiss={state.dismiss}+ destination={{ deviceId: 'B', deviceName: 'Work Mac', project: null }}+ />+ </MemoryRouter>,+ );+ await screen.findByText('taskMigration.estimating');+ expect(+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,+ ).toBe(true);+ await waitFor(() => expect(finish).toBeTypeOf('function'));+ finish({ estimate: { fileCount: 100, bytes: 2048 } });+ await screen.findByText('taskMigration.fileSummary');+ await waitFor(() =>+ expect(+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,+ ).toBe(false),+ );+ expect(state.request).toHaveBeenCalledWith('A', { action: 'estimate', sessionId: 'task' });+});++it('does not copy when the source does not support inventory', async () => {+ state.request.mockResolvedValue({ supported: true, deviceId: 'A' });+ mount();+ await screen.findByText('taskMigration.estimateFailed');+ expect(+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,+ ).toBe(true);+ expect(state.request.mock.calls.some(([, c]) => c.action === 'estimate')).toBe(false);+});++it.each(['confirm', 'complete'])(+ 'clears recovered status errors on %s without erasing action errors',+ async (stage) => {+ let fail = true;+ const original = state.request.getMockImplementation()!;+ state.request.mockImplementation((device, command) => {+ if (command.action !== 'status') return original(device, command);+ if (fail) return Promise.reject(new Error('MIGRATION_DISCONNECTED'));+ return Promise.resolve(+ stage === 'complete'+ ? { stage: 'complete', running: false, targetSessionId: 'copy', targetDeviceId: 'B' }+ : { supported: true, deviceId: 'A' },+ );+ });+ mount();+ await screen.findByText('taskMigration.errors.MIGRATION_DISCONNECTED');+ fail = false;+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull(), { timeout: 2500 });+ if (stage === 'complete') {+ state.openLink.mockRejectedValueOnce(new Error('MIGRATION_OPEN_FAILED'));+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.openTarget' }));+ await screen.findByText('taskMigration.errors.MIGRATION_OPEN_FAILED');+ const count = state.request.mock.calls.filter(([, c]) => c.action === 'status').length;+ await waitFor(+ () =>+ expect(+ state.request.mock.calls.filter(([, c]) => c.action === 'status').length,+ ).toBeGreaterThan(count),+ { timeout: 2500 },+ );+ expect(screen.getByText('taskMigration.errors.MIGRATION_OPEN_FAILED')).toBeTruthy();+ } else expect(await screen.findByRole('button', { name: 'taskMigration.start' })).toBeTruthy();+ },+);++it.each(['rejected', 'lost-ack', 'accepted'])(+ 'only shows the current copy after a %s start over an old completion',+ async (outcome) => {+ let copyId = 'old-copy';+ const original = state.request.getMockImplementation()!;+ state.request.mockImplementation(async (device, command) => {+ const snapshot = () => ({+ supported: true,+ deviceId: 'A',+ stage: 'complete',+ running: false,+ targetSessionId: copyId,+ targetDeviceId: 'B',+ });+ if (command.action === 'status') return snapshot();+ if (command.action === 'start') {+ if (outcome !== 'rejected') copyId = 'new-copy';+ if (outcome !== 'accepted') throw new Error('MIGRATION_START_FAILED');+ return snapshot();+ }+ return original(device, command);+ });+ render(+ <MemoryRouter>+ <TaskMigrationDialog+ session={source}+ onDismiss={state.dismiss}+ destination={{ deviceId: 'B', deviceName: 'Work Mac', project: null }}+ />+ </MemoryRouter>,+ );+ const start = await screen.findByRole('button', { name: 'taskMigration.start' });+ await waitFor(() => expect((start as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(start);+ if (outcome !== 'accepted')+ await screen.findByText('taskMigration.errors.MIGRATION_START_FAILED');+ const polls = state.request.mock.calls.filter(([, c]) => c.action === 'status').length;+ await waitFor(+ () =>+ expect(+ state.request.mock.calls.filter(([, c]) => c.action === 'status').length,+ ).toBeGreaterThan(polls),+ { timeout: 2500 },+ );+ if (outcome === 'rejected') {+ expect(screen.getByText('taskMigration.failureTitle')).toBeTruthy();+ expect(screen.queryByText('taskMigration.successTitle')).toBeNull();+ expect(screen.queryByRole('button', { name: 'taskMigration.openTarget' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.close' }));+ expect(state.request.mock.calls.some(([, c]) => c.action === 'cancel')).toBe(false);+ } else {+ expect(await screen.findByText('taskMigration.successTitle')).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ state.invoke.mockResolvedValue({ id: 'new-copy', status: 'active' });+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.openTarget' }));+ await waitFor(() =>+ expect(state.invoke).toHaveBeenCalledWith('B', 'local-db:sessions:get', ['new-copy']),+ );+ }+ },+);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9b59287e3b..615d14d3de 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10,26 +10,24 @@"failed": "Could not move the task. Stop it, check the destination directory and retry."},"taskMigration": {- "title": "Copy to another computer…",- "description": "Create an independent copy on the destination computer. The original task and files stay here.",+ "title": "Copy to {{name}}",+ "description": "Create a task copy on {{name}}.","bindingsNotice": "Automations and messaging connections stay on the source computer and are not copied.","limits": "Both computers need this feature and remote control enabled. Stop tasks using this directory first. Available disk space and memory on the destination are checked before transfer. The destination uses its own model settings; Cindy sign-in credentials and machine settings are not transferred.",- "device": "Destination computer",- "project": "Destination location",+ "device": "Copy to",+ "project": "Save location","newFolder": "Creates a new folder without overwriting existing files.","defaultFolder": "Cindy’s default location","noDevices": "No available computers. Connect another computer and enable remote control on both computers.",- "background": "You can close this window and reopen it from the task menu. If interrupted, retry the same copy.",- "openTarget": "Open task on destination",+ "openTarget": "Open newly copied task","close": "Close",- "cancel": "Cancel copy",- "retry": "Retry copy",+ "cancel": "Cancel","start": "Copy task",- "failed": "Could not complete the copy. Source files are kept. Check both computers and retry.",+ "failed": "Copy did not finish. Check both computers before copying again.","stages": {"preparing": "Preparing a snapshot…","transferring": "Transferring and checking files…",- "complete": "Copy complete. The original task and files are kept.",+ "complete": "Copy successful","cancelled": "Copy cancelled.","receiving": "Receiving files…","active": "Task is ready on this computer."@@ -48,7 +46,21 @@"MIGRATION_UNSUPPORTED": "Update both computers to a version that supports task copy.","MIGRATION_TASK_QUEUED": "This task has queued messages. Finish or remove them before copying it.","MIGRATION_SOURCE_CHANGED": "The source task changed during preparation. Retry the copy."- }+ },+ "successTitle": "Copy successful",+ "successDescription": "Copied to {{name}}.",+ "copyingTitle": "Copying to {{name}}",+ "keepOpen": "Copying to {{name}}. Please wait until it finishes.",+ "failureTitle": "Copy failed",+ "failureDescription": "Close this window and start a new copy from the task menu.",+ "finishing": "{{name}} is receiving, checking and creating the task…",+ "transferProgress": "Upload progress {{sent}} / {{total}} · Average {{speed}}/s (reception not yet complete)",+ "thisComputer": "this computer",+ "selectedComputer": "selected computer",+ "estimating": "Counting files and calculating size…",+ "fileSummary": "Project files: {{count}}, totaling {{size}}",+ "estimateNote": "Pre-copy estimate including hidden files. Git history, conversation and attachments are copied separately and excluded from this size. Files may change before copying.",+ "estimateFailed": "Could not count files. Check the source computer’s connection and version, then close and try again."},"sharedTask": {"manageSharing": "Manage Sharing",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex cc391d708b..ec17f5a035 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10,26 +10,24 @@"failed": "タスクを移動できませんでした。タスクを停止し、移動先フォルダーを確認して再試行してください。"},"taskMigration": {- "title": "別のコンピューターにコピー…",- "description": "コピー先に独立したタスクを作成します。元のタスクとファイルは保持されます。",+ "title": "{{name}}にコピー",+ "description": "{{name}}にタスクのコピーを作成します。","bindingsNotice": "自動実行とメッセージ連携は元のコンピューターに残り、コピーされません。","limits": "両方のコンピューターでこの機能とリモート操作を有効にする必要があります。このフォルダーを使用するタスクを先に停止してください。コピー前にコピー先のディスク空き容量と利用可能なメモリを確認します。コピー先のモデル設定を使用し、Cindy のログイン情報やマシン設定は転送しません。",- "device": "コピー先のコンピューター",+ "device": "コピー先","project": "保存先","newFolder": "新しいフォルダーを作成し、既存ファイルは上書きしません。","defaultFolder": "Cindy の既定の場所","noDevices": "利用可能なコンピューターがありません。別のコンピューターに接続し、両方でリモート操作を有効にしてください。",- "background": "このウィンドウを閉じても、タスクメニューから再度開けます。中断された場合は同じコピーを再試行してください。",- "openTarget": "コピー先のタスクを開く",+ "openTarget": "新しくコピーしたタスクを開く","close": "閉じる",- "cancel": "コピーをキャンセル",- "retry": "コピーを再試行",+ "cancel": "キャンセル","start": "タスクをコピー",- "failed": "コピーを完了できませんでした。元のファイルは保持されています。両方のコンピューターを確認して再試行してください。",+ "failed": "コピーが完了しませんでした。両方のコンピューターを確認してから再度コピーしてください。","stages": {"preparing": "スナップショットを準備中…","transferring": "ファイルを転送・検証中…",- "complete": "コピーが完了しました。元のタスクとファイルは保持されています。",+ "complete": "コピー完了","cancelled": "コピーをキャンセルしました。","receiving": "ファイルを受信中…","active": "このコンピューターでタスクを続けられます。"@@ -48,7 +46,21 @@"MIGRATION_UNSUPPORTED": "両方のコンピューターをタスクのコピーに対応したバージョンに更新してください。","MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。","MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。"- }+ },+ "successTitle": "コピー完了",+ "successDescription": "{{name}}にコピーしました。",+ "copyingTitle": "{{name}}にコピー中",+ "keepOpen": "{{name}}にコピーしています。完了までお待ちください。",+ "failureTitle": "コピー失敗",+ "failureDescription": "閉じた後、タスクメニューから新しくコピーできます。",+ "finishing": "{{name}}で受信・検証し、タスクを作成中…",+ "transferProgress": "アップロード {{sent}} / {{total}} · 平均 {{speed}}/s(受信は未完了)",+ "thisComputer": "このコンピューター",+ "selectedComputer": "選択したコンピューター",+ "estimating": "ファイル数とサイズを計算中…",+ "fileSummary": "プロジェクトファイル:{{count}} 個、合計 {{size}}",+ "estimateNote": "隠しファイルを含むコピー前の推定値です。別途コピーする Git 履歴、タスクの会話と添付ファイルは含みません。ファイルの変更により最終サイズは変わります。",+ "estimateFailed": "集計できませんでした。コピー元の接続とバージョンを確認し、閉じて再試行してください。"},"sharedTask": {"manageSharing": "共有管理",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 008d8ccb92..8a4b44a14a 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10,26 +10,24 @@"failed": "작업을 이동할 수 없습니다. 작업을 중지하고 대상 폴더를 확인한 후 다시 시도하세요."},"taskMigration": {- "title": "다른 컴퓨터로 복사…",- "description": "대상 컴퓨터에 독립된 사본을 만듭니다. 원본 작업과 파일은 유지됩니다.",+ "title": "{{name}}로 복사",+ "description": "{{name}}에 작업 사본을 만듭니다.","bindingsNotice": "자동 실행과 메시지 연결은 원본 컴퓨터에 남으며 복사되지 않습니다.","limits": "두 컴퓨터 모두 이 기능을 지원하고 원격 제어가 켜져 있어야 합니다. 먼저 이 폴더를 사용하는 작업을 중지하세요. 복사 전에 대상 컴퓨터의 디스크 여유 공간과 사용 가능한 메모리를 확인합니다. 대상 컴퓨터의 모델 설정을 사용하며 Cindy 로그인 정보와 컴퓨터 설정은 전송하지 않습니다.",- "device": "대상 컴퓨터",+ "device": "복사 위치","project": "저장 위치","newFolder": "새 폴더를 만들며 기존 파일은 덮어쓰지 않습니다.","defaultFolder": "Cindy 기본 위치","noDevices": "사용 가능한 컴퓨터가 없습니다. 다른 컴퓨터를 연결하고 두 컴퓨터 모두 원격 제어를 켜세요.",- "background": "이 창을 닫아도 작업 메뉴에서 다시 열 수 있습니다. 중단된 경우 같은 복사을 재시도하세요.",- "openTarget": "대상 컴퓨터의 작업 열기",+ "openTarget": "새로 복사한 작업 열기","close": "닫기",- "cancel": "복사 취소",- "retry": "복사 재시도",+ "cancel": "취소","start": "작업 복사",- "failed": "복사을 완료하지 못했습니다. 원본 파일은 유지됩니다. 두 컴퓨터를 확인한 후 다시 시도하세요.",+ "failed": "복사가 완료되지 않았습니다. 두 컴퓨터를 확인한 후 다시 복사하세요.","stages": {"preparing": "스냅샷 준비 중…","transferring": "파일 전송 및 검증 중…",- "complete": "복사가 완료되었습니다. 원본 작업과 파일은 유지됩니다.",+ "complete": "복사 완료","cancelled": "복사이 취소되었습니다.","receiving": "파일 수신 중…","active": "이 컴퓨터에서 작업을 계속할 수 있습니다."@@ -48,7 +46,21 @@"MIGRATION_UNSUPPORTED": "두 컴퓨터 모두 작업 복사을 지원하는 버전으로 업데이트하세요.","MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.","MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요."- }+ },+ "successTitle": "복사 완료",+ "successDescription": "{{name}}에 복사했습니다.",+ "copyingTitle": "{{name}}로 복사 중",+ "keepOpen": "{{name}}로 복사 중입니다. 완료될 때까지 기다려 주세요.",+ "failureTitle": "복사 실패",+ "failureDescription": "창을 닫은 후 작업 메뉴에서 새로 복사할 수 있습니다.",+ "finishing": "{{name}}에서 수신, 검증 및 작업 생성 중…",+ "transferProgress": "업로드 {{sent}} / {{total}} · 평균 {{speed}}/s (수신 미완료)",+ "thisComputer": "이 컴퓨터",+ "selectedComputer": "선택한 컴퓨터",+ "estimating": "파일 수와 크기 계산 중…",+ "fileSummary": "프로젝트 파일: {{count}}개, 총 {{size}}",+ "estimateNote": "숨김 파일을 포함한 복사 전 예상치입니다. 별도로 복사하는 Git 기록, 작업 대화 및 첨부 파일은 제외됩니다. 파일 변경에 따라 최종 크기가 달라질 수 있습니다.",+ "estimateFailed": "파일을 집계하지 못했습니다. 원본 컴퓨터의 연결과 버전을 확인한 후 닫고 다시 시도하세요."},"sharedTask": {"manageSharing": "공유 관리",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 86be956739..4490ece177 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10,26 +10,24 @@"failed": "无法移动任务。请停止任务,检查目标目录后重试。"},"taskMigration": {- "title": "复制到其他电脑…",- "description": "在目标电脑创建独立副本,原任务和文件保留。",+ "title": "复制到{{name}}",+ "description": "将在{{name}}创建任务副本。","bindingsNotice": "自动任务和消息渠道仍在源电脑运行,不会随任务复制。","limits": "两台电脑都需支持此功能并开启远程控制。请先停止使用该目录的任务。复制前会检查目标电脑的磁盘空间和可用内存。目标电脑使用自己的模型设置,不传输 Cindy 登录凭证和机器设置。",- "device": "目标电脑",- "project": "目标位置",+ "device": "复制到",+ "project": "保存位置","newFolder": "新建文件夹,不覆盖已有文件。","defaultFolder": "Cindy 默认位置","noDevices": "暂无可用电脑。请连接另一台电脑,并在两台电脑上开启远程控制。",- "background": "可以关闭窗口,稍后从任务菜单重新打开。中断后请重试同一次复制。",- "openTarget": "打开目标电脑上的任务",+ "openTarget": "打开新复制的任务","close": "关闭",- "cancel": "取消复制",- "retry": "重试复制",+ "cancel": "取消","start": "复制任务",- "failed": "复制未完成,源文件已保留。请检查两台电脑后重试。",+ "failed": "复制未完成,请检查两台电脑后重新复制。","stages": {"preparing": "正在准备快照…","transferring": "正在传输并校验文件…",- "complete": "复制完成,原任务和文件保留。",+ "complete": "复制成功","cancelled": "已取消复制。","receiving": "正在接收文件…","active": "任务已可在此电脑继续。"@@ -48,7 +46,21 @@"MIGRATION_UNSUPPORTED": "请将两台电脑更新至支持任务复制的版本。","MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。","MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。"- }+ },+ "successTitle": "复制成功",+ "successDescription": "已复制到{{name}}。",+ "copyingTitle": "正在复制到{{name}}",+ "keepOpen": "正在复制到{{name}},请等待完成。",+ "failureTitle": "复制失败",+ "failureDescription": "关闭后可从任务菜单重新发起复制。",+ "finishing": "{{name}}正在接收、校验并创建任务…",+ "transferProgress": "上传进度 {{sent}} / {{total}} · 平均 {{speed}}/s(尚未完成接收)",+ "thisComputer": "本机",+ "selectedComputer": "所选电脑",+ "estimating": "正在统计文件数量和大小…",+ "fileSummary": "项目文件:{{count}} 个,共 {{size}}",+ "estimateNote": "复制前估算,含隐藏文件;不含另行复制的 Git 历史、任务对话及附件。文件变化可能影响最终大小。",+ "estimateFailed": "无法统计文件。请检查任务所在电脑的连接和版本,然后关闭重试。"},"sharedTask": {"manageSharing": "共享管理",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 858ebeca01..24eb959772 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10,26 +10,24 @@"failed": "無法移動任務。請停止任務,檢查目標目錄後重試。"},"taskMigration": {- "title": "複製到其他電腦…",- "description": "在目標電腦建立獨立副本,原任務和檔案保留。",+ "title": "複製到{{name}}",+ "description": "將在{{name}}建立任務副本。","bindingsNotice": "自動任務和訊息管道仍在來源電腦執行,不會隨任務複製。","limits": "兩台電腦都需支援此功能並開啟遠端控制。請先停止使用該目錄的任務。複製前會檢查目標電腦的磁碟空間和可用記憶體。目標電腦使用自己的模型設定,不傳輸 Cindy 登入憑證和電腦設定。",- "device": "目標電腦",- "project": "目標位置",+ "device": "複製到",+ "project": "儲存位置","newFolder": "建立新資料夾,不覆寫現有檔案。","defaultFolder": "Cindy 預設位置","noDevices": "目前沒有可用電腦。請連接另一台電腦,並在兩台電腦上開啟遠端控制。",- "background": "可以關閉視窗,稍後從任務選單重新開啟。中斷後請重試同一次複製。",- "openTarget": "開啟目標電腦上的任務",+ "openTarget": "開啟新複製的任務","close": "關閉",- "cancel": "取消複製",- "retry": "重試複製",+ "cancel": "取消","start": "複製任務",- "failed": "複製未完成,來源檔案已保留。請檢查兩台電腦後重試。",+ "failed": "複製未完成,請檢查兩台電腦後重新複製。","stages": {"preparing": "正在準備快照…","transferring": "正在傳輸並驗證檔案…",- "complete": "複製完成,原任務和檔案保留。",+ "complete": "複製成功","cancelled": "已取消複製。","receiving": "正在接收檔案…","active": "任務已可在此電腦繼續。"@@ -48,7 +46,21 @@"MIGRATION_UNSUPPORTED": "請將兩台電腦更新至支援任務複製的版本。","MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。","MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。"- }+ },+ "successTitle": "複製成功",+ "successDescription": "已複製到{{name}}。",+ "copyingTitle": "正在複製到{{name}}",+ "keepOpen": "正在複製到{{name}},請等待完成。",+ "failureTitle": "複製失敗",+ "failureDescription": "關閉後可從任務選單重新發起複製。",+ "finishing": "{{name}}正在接收、驗證並建立任務…",+ "transferProgress": "上傳進度 {{sent}} / {{total}} · 平均 {{speed}}/s(尚未完成接收)",+ "thisComputer": "本機",+ "selectedComputer": "所選電腦",+ "estimating": "正在統計檔案數量和大小…",+ "fileSummary": "專案檔案:{{count}} 個,共 {{size}}",+ "estimateNote": "複製前估算,含隱藏檔案;不含另行複製的 Git 歷史、任務對話及附件。檔案變化可能影響最終大小。",+ "estimateFailed": "無法統計檔案。請檢查任務所在電腦的連線和版本,然後關閉重試。"},"sharedTask": {"manageSharing": "共享管理",diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.mdindex 82e3d487df..62f5497872 100644--- a/docs/product-rules/task-device-migration.md+++ b/docs/product-rules/task-device-migration.md@@ -1,8 +1,7 @@# 同机移动与跨电脑复制任务任务菜单保留同机「移动任务」的项目、选择文件夹及移到对话行为;「复制到其他电脑」在目标-创建独立副本。选定电脑及位置后,确认框说明原任务和文件保留,自动任务和消息渠道仍在源电脑-运行、不随副本复制。自动任务、飞书路由、共享或 Goal 绑定不阻止复制,也不转交给副本。+创建独立副本。选定电脑及位置后,确认框只简短说明自动任务和消息渠道不随副本复制,不强调原任务保留。自动任务、飞书路由、共享或 Goal 绑定不阻止复制,也不转交给副本。源任务不会归档、变成只读或失去执行权;不删除源项目及 fork 共用目录。离线电脑不显示。明确不支持复制协议时才提示更新;连接失败不推断为版本过旧。@@ -24,10 +23,16 @@不设任务总大小上限;大文件按现有单对象传输容量分段,校验大小及 SHA-256 后解包。4. 目标以复制 ID 幂等导入,整组沿用已有团队事务。导入成功即可使用目标任务,不等待源端让出执行权,也不自动开始模型回合。任务使用目标模型设置,权限回到需要确认的模式。-5. 源端清理本次暂存和传输文件后记录完成。中断可从任务菜单重试同一次复制,回执丢失不重复导入。- 完成后可再次复制并生成新的独立副本。--源端仅记录 `preparing → transferring → complete`(准备阶段可取消);目标记录接收与完成。+5. 确认页使用接收电脑名称或“本机”,展示项目文件数量与复制前估算大小(含隐藏/忽略文件,整组共享目录去重)。+ Git 历史、任务对话与附件另行复制,不计入项目文件统计;统计完成前不能开始复制。+ `copyEstimate` 能力存在时才调用 `estimate`;旧源端无法统计时明确提示连接/版本检查,不开始复制。+6. 复制全程保留弹窗,不提供隐藏到后台的入口;准备阶段显示不定进度,发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。+ OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。+ 文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。+ 成功页只提供关闭和“打开新复制的任务”。失败页只提供关闭,关闭会复用完成路径清理已上传的 OSS 对象及本地暂存,结束本次源端复制;目标端可能已提交的副本不会回滚。+ 再次复制从任务菜单发起。宿主异常退出后的既有幂等恢复协议保留,不自动重试。++源端仅记录 `preparing → transferring → complete`(停止运行后可结束本次复制);目标记录接收与完成。开始、取消和后台复制复用同一个源任务标识的既有跨进程锁,防止多实例覆盖同一进度。进度日志不用于限制源任务的输入、改名、标签、Goal、共享或团队操作,不扫描其它任务日志。旧交接日志不会让任务只读。新副本不复制调度、渠道和共享授权绑定;原绑定继续使用原任务。diff --git a/packages/device-link/src/__tests__/peerAcceleration.test.ts b/packages/device-link/src/__tests__/peerAcceleration.test.tsindex fa050280cb..e8013a0814 100644--- a/packages/device-link/src/__tests__/peerAcceleration.test.ts+++ b/packages/device-link/src/__tests__/peerAcceleration.test.ts@@ -43,6 +43,26 @@ describe("peer acceleration policy", () => {).toBe(false);expect(canUsePeerInvoke("maker:send", [{}])).toBe(false);});+ it("reports only acknowledged chunks, not bytes merely read or rejected", async () => {+ const progress = vi.fn();+ let writes = 0;+ await expect(+ uploadPeerAttachment(+ { size: 2 * 1024 * 1024, sha256: "a".repeat(64) },+ async () => "YQ==",+ async (request) => {+ if (request.op === "begin")+ return { ticket: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" };+ if (request.op === "write" && ++writes === 2)+ throw new Error("disconnected");+ return {};+ },+ () => {},+ progress,+ ),+ ).rejects.toThrow("disconnected");+ expect(progress.mock.calls).toEqual([[1024 * 1024]]);+ });it("finishes byte staging before returning a reference; cancellation never finishes", async () => {const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";const metadata = { size: 1, sha256: "a".repeat(64), originalName: "a.txt" };diff --git a/packages/device-link/src/__tests__/taskMigration.test.ts b/packages/device-link/src/__tests__/taskMigration.test.tsindex bb8620be52..4e27d7175e 100644--- a/packages/device-link/src/__tests__/taskMigration.test.ts+++ b/packages/device-link/src/__tests__/taskMigration.test.ts@@ -12,16 +12,49 @@ import {} from "../invokePolicy.js";describe("task copy protocol", () => {+ it("accepts a source session estimate without accepting arbitrary paths", () => {+ expect(+ parseTaskMigrationRequest({+ action: "estimate",+ sessionId: "source",+ path: "/private",+ }),+ ).toEqual({ action: "estimate", sessionId: "source" });+ expect(() =>+ parseTaskMigrationRequest({+ action: "estimate",+ sessionId: "../private",+ }),+ ).toThrow();+ });it("cannot dispatch the previous ownership-handoff protocol", () => {expect(TASK_MIGRATION_CHANNEL).toBe("maker:task-copy");expect(REMOTE_INVOKE_ALLOWLIST.has("maker:task-migration")).toBe(false);- expect(() => parseTaskMigrationRequest({ action: "activate", id: "01234567-0123-4123-a123-012345678901", sourceSessionId: "source" })).toThrow();+ expect(() =>+ parseTaskMigrationRequest({+ action: "activate",+ id: "01234567-0123-4123-a123-012345678901",+ sourceSessionId: "source",+ }),+ ).toThrow();});it("accepts only explicit project or dialogue moves on the narrow host action", () => {for (const workingDir of [null, "/projects/new", "C:/projects/new"])- expect(parseTaskMigrationRequest({ action: "move-project", sessionId: "task", workingDir })).toEqual({ action: "move-project", sessionId: "task", workingDir });+ expect(+ parseTaskMigrationRequest({+ action: "move-project",+ sessionId: "task",+ workingDir,+ }),+ ).toEqual({ action: "move-project", sessionId: "task", workingDir });for (const workingDir of [undefined, "", "bad\0path", 12])- expect(() => parseTaskMigrationRequest({ action: "move-project", sessionId: "task", workingDir })).toThrow();+ expect(() =>+ parseTaskMigrationRequest({+ action: "move-project",+ sessionId: "task",+ workingDir,+ }),+ ).toThrow();});it("exposes only the narrow remote business channel, without automatic write retries", () => {expect(REMOTE_INVOKE_ALLOWLIST.has(TASK_MIGRATION_CHANNEL)).toBe(true);diff --git a/packages/device-link/src/peerAttachment.ts b/packages/device-link/src/peerAttachment.tsindex 20cdacd616..5d049cbaff 100644--- a/packages/device-link/src/peerAttachment.ts+++ b/packages/device-link/src/peerAttachment.ts@@ -52,6 +52,7 @@ export async function uploadPeerAttachment(read: (offset: number, length: number) => Promise<string>,invoke: (request: Record<string, unknown>) => Promise<unknown>,check: () => void,+ onProgress?: (bytes: number) => void,): Promise<string> {check();const { ticket } = (await invoke({ op: "begin", ...metadata })) as {@@ -68,6 +69,7 @@ export async function uploadPeerAttachment();check();await invoke({ op: "write", ticket, offset, data });+ onProgress?.(Math.min(offset + 1024 * 1024, metadata.size));}check();await invoke({ op: "finish", ticket });diff --git a/packages/device-link/src/taskMigration.ts b/packages/device-link/src/taskMigration.tsindex 90bcf54646..8d655a1923 100644--- a/packages/device-link/src/taskMigration.ts+++ b/packages/device-link/src/taskMigration.ts@@ -40,7 +40,7 @@ export type TaskMigrationRequest =targetDeviceId: string;targetProject?: string | null;}- | { action: "status" | "retry" | "cancel"; sessionId: string }+ | { action: "status" | "retry" | "cancel" | "estimate"; sessionId: string }| {action: "receive";id: string;@@ -64,7 +64,16 @@ export interface TaskMigrationView {| "cancelled"| "receiving"| "active";+ estimate?: { fileCount: number; bytes: number };+ copyEstimate?: true;running?: boolean;+ /** Optional live source-side upload telemetry; absent on older hosts. Never persisted. */+ progress?: {+ phase: "sending" | "finishing";+ sentBytes: number;+ totalBytes: number;+ bytesPerSecond: number;+ };targetDeviceId?: string;targetSessionId?: string;error?: string;@@ -127,11 +136,11 @@ export function parseTaskMigrationRequest(}if (- ["status", "retry", "cancel"].includes(String(r.action)) &&+ ["status", "retry", "cancel", "estimate"].includes(String(r.action)) &&id(r.sessionId))return {- action: r.action as "status" | "retry" | "cancel",+ action: r.action as "status" | "retry" | "cancel" | "estimate",sessionId: r.sessionId,};if (@@ -146,11 +155,7 @@ export function parseTaskMigrationRequest(targetDeviceId: r.targetDeviceId,targetProject: r.targetProject as string | null,};- if (- r.action === "receipt" &&- uuid(r.id) &&- id(r.sourceSessionId)- )+ if (r.action === "receipt" && uuid(r.id) && id(r.sourceSessionId))return { action: r.action, id: r.id, sourceSessionId: r.sourceSessionId };if (r.action === "receive" &&