Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(task-copy): 统计跳过托管 worktree,超时单独提示并加文件数上限

Dash99b722722d79
diff --git a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
index f9c50228d2..60be7aeb0b 100644
--- a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
@@ -22,3 +22,38 @@ it('counts hidden and nested files, skips root Git metadata and does not count d
await fs.rm(root, { recursive: true, force: true });
}
});
+
+it("skips other tasks' managed worktrees only at the project root", async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));
+ try {
+ for (const name of ['.cindy-worktrees', '.xdt-worktrees']) {
+ await fs.mkdir(path.join(root, name, 'other-task'), { recursive: true });
+ await fs.writeFile(path.join(root, name, 'other-task', 'file'), 'not copied');
+ }
+ await fs.mkdir(path.join(root, 'sub', '.cindy-worktrees'), { recursive: true });
+ await fs.writeFile(path.join(root, 'sub', '.cindy-worktrees', 'file'), '1234');
+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 1, bytes: 4 });
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+});
+
+it('counts a wide, deep tree and stops once the file cap is exceeded', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));
+ try {
+ for (let i = 0; i < 40; i++) {
+ const directory = path.join(root, `d${i}`, 'nested');
+ await fs.mkdir(directory, { recursive: true });
+ await Promise.all(
+ [0, 1, 2].map((j) => fs.writeFile(path.join(directory, `f${j}`), 'x'.repeat(j))),
+ );
+ }
+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 120, bytes: 120 });
+ expect(await estimateWorkspace(root, () => {}, 120)).toEqual({ fileCount: 120, bytes: 120 });
+ await expect(estimateWorkspace(root, () => {}, 119)).rejects.toThrow(
+ 'MIGRATION_TOO_MANY_FILES',
+ );
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
index b4f03d9cb7..7e6aa9bb39 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -6,7 +6,11 @@ import path from 'node:path';
import os from 'node:os';
import { createHash } from 'node:crypto';
import { AsyncLocalStorage } from 'node:async_hooks';
-import { parseAttachmentOssRef } from '@cindy/device-link';
+import {
+ parseAttachmentOssRef,
+ TASK_MIGRATION_LOCAL_CHANNEL,
+ TASK_MIGRATION_MAX_FILES,
+} from '@cindy/device-link';
const state = vi.hoisted(() => ({
root: '',
@@ -35,6 +39,8 @@ const state = vi.hoisted(() => ({
snapshot: null;
}>,
workers: [] as string[],
+ estimateLimits: [] as number[],
+ timeoutAction: '' as string,
}));
vi.mock('../../localDb/ipc/sessionCreatedBroadcast', () => ({
emitSessionCreated: (id: string) => state.created(id),
@@ -87,6 +93,10 @@ vi.mock('../../device-link', () => ({
opts?: { preSend(): void },
) => {
opts?.preSend();
+ if (state.timeoutAction === args[0].action) {
+ const { DeviceLinkError } = await import('@cindy/device-link');
+ throw new DeviceLinkError('INVOKE_TIMEOUT', 'no invoke-result within 180000ms');
+ }
const peer = device();
const result = await state.context.run({ device: target, peer }, () =>
requestTaskMigration(args[0]),
@@ -194,8 +204,13 @@ vi.mock('../../session-share/sessionShareImport', () => ({
return { fidelity: 'full' };
},
}));
-vi.mock('../workspace', () => ({
- estimateWorkspace: async () => ({ fileCount: 1, bytes: 8 }),
+vi.mock('../workspace', async (original) => ({
+ isExcludedFromWorkspace: (await original<typeof import('../workspace')>())
+ .isExcludedFromWorkspace,
+ estimateWorkspace: async (_root: string, _check: () => void, maxFiles: number) => {
+ state.estimateLimits.push(maxFiles);
+ return { fileCount: 1, bytes: 8 };
+ },
snapshotWorkspace: async (source: string, directory: string) => {
state.snapshot();
await fs.mkdir(directory, { recursive: true });
@@ -251,6 +266,8 @@ describe('resumable cross-computer copy', () => {
state.restoresFail = false;
state.sharingLatest = [];
state.workers = [];
+ state.estimateLimits = [];
+ state.timeoutAction = '';
const cwd = path.join(state.root, 'shared');
await fs.mkdir(cwd);
await fs.writeFile(path.join(cwd, 'draft'), 'original');
@@ -477,9 +494,40 @@ describe('resumable cross-computer copy', () => {
await team();
const result = await requestTaskMigration({ action: 'estimate', sessionId: 'fork' });
expect(result.estimate).toEqual({ fileCount: 2, bytes: 16 });
+ // The file cap applies to the whole team, not to each directory separately.
+ expect(state.estimateLimits).toEqual([TASK_MIGRATION_MAX_FILES, TASK_MIGRATION_MAX_FILES - 1]);
expect(state.exported).not.toHaveBeenCalled();
expect(state.files.size).toBe(0);
});
+ it('reports a timed-out remote request as MIGRATION_TIMEOUT instead of a generic failure', async () => {
+ const { ipcMain } = await import('electron');
+ const handler = vi
+ .mocked(ipcMain.handle)
+ .mock.calls.findLast(([channel]) => channel === TASK_MIGRATION_LOCAL_CHANNEL)![1];
+ state.timeoutAction = 'estimate';
+ await expect(
+ handler({} as never, 'B', { action: 'estimate', sessionId: 'fork' }),
+ ).rejects.toThrow('MIGRATION_TIMEOUT');
+ });
+ it('ignores tasks running in other managed worktrees under the copied root', async () => {
+ const rows = state.rows.get('A')!;
+ const cwd = rows.get('fork')!.workingDir as string;
+ const managed = path.join(cwd, '.cindy-worktrees', 'other');
+ await fs.mkdir(managed, { recursive: true });
+ rows.get('sibling')!.workingDir = managed;
+ state.siblingRunning = true;
+ await start();
+ expect((await settled()).stage).toBe('complete');
+ });
+ it('still refuses while another task runs in an ordinary subdirectory of the copied root', async () => {
+ const rows = state.rows.get('A')!;
+ const nested = path.join(rows.get('fork')!.workingDir as string, 'packages');
+ await fs.mkdir(nested);
+ rows.get('sibling')!.workingDir = nested;
+ state.siblingRunning = true;
+ await start();
+ expect((await settled()).error).toBe('MIGRATION_SHARED_DIRECTORY_BUSY');
+ });
it('acknowledges start and retry with the registered running state', async () => {
state.noSpace = true;
expect((await start()).running).toBe(true);
diff --git a/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
index 5c34a60f04..6046fefbe5 100644
--- a/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
@@ -108,6 +108,22 @@ describe('cross-machine project snapshots', () => {
expect(await git(linked, 'diff', '--cached')).toBe(staged);
expect(await fs.readFile(path.join(source, 'tracked'), 'utf8')).toBe('base\n');
}, 30_000);
+ it("leaves other tasks' managed worktrees behind", async () => {
+ await fs.writeFile(path.join(source, 'draft'), 'mine\n');
+ for (const name of ['.cindy-worktrees', '.xdt-worktrees']) {
+ await fs.mkdir(path.join(source, name, 'other-task'), { recursive: true });
+ // Nested Git metadata would otherwise make the whole snapshot non-portable.
+ await fs.writeFile(path.join(source, name, 'other-task', '.git'), 'gitdir: elsewhere\n');
+ await fs.writeFile(path.join(source, name, 'other-task', 'file'), 'not mine\n');
+ }
+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
+ expect(Object.keys(snapshot.archive.files)).toEqual(['draft']);
+ await restoreWorkspace(snapshot, artifacts, target);
+ expect(await fs.readdir(target)).toEqual(['draft']);
+ expect(
+ await fs.readFile(path.join(source, '.cindy-worktrees', 'other-task', 'file'), 'utf8'),
+ ).toBe('not mine\n');
+ });
it('refuses to overwrite a destination directory', async () => {
await fs.writeFile(path.join(source, 'source'), 'copy');
const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index a0789208a5..c4446949bf 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -5,6 +5,8 @@ import { app, ipcMain } from 'electron';
import {
TASK_MIGRATION_CHANNEL,
TASK_MIGRATION_LOCAL_CHANNEL,
+ TASK_MIGRATION_MAX_FILES,
+ DeviceLinkError,
parseTaskMigrationRequest,
buildAttachmentOssRef,
parsePeerAttachmentRef,
@@ -53,6 +55,7 @@ import {
snapshotWorkspace,
restoreWorkspace,
estimateWorkspace,
+ isExcludedFromWorkspace,
type PortableWorkspace,
} from './workspace';
@@ -127,9 +130,17 @@ async function invoke(
scope: Scope,
): Promise<TaskMigrationView> {
scope.assertCurrent();
- const response = await remoteInvoke(device, TASK_MIGRATION_CHANNEL, [request], {
- preSend: scope.assertCurrent,
- });
+ let response: Awaited<ReturnType<typeof remoteInvoke>>;
+ try {
+ response = await remoteInvoke(device, TASK_MIGRATION_CHANNEL, [request], {
+ preSend: scope.assertCurrent,
+ });
+ } catch (error) {
+ // The source may still be working; tell the user it was slow, not that it is offline.
+ if (error instanceof DeviceLinkError && error.code === 'INVOKE_TIMEOUT')
+ throw new Error('MIGRATION_TIMEOUT');
+ throw error;
+ }
scope.assertCurrent();
if (!response.ok)
throw new Error(
@@ -300,7 +311,8 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
sourceKeys.some(
(sourceKey) =>
key === sourceKey ||
- key.startsWith(sourceKey + path.sep) ||
+ (key.startsWith(sourceKey + path.sep) &&
+ !isExcludedFromWorkspace(sourceKey, key)) ||
sourceKey.startsWith(key + path.sep),
)
)
@@ -909,7 +921,11 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
);
const estimate = { fileCount: 0, bytes: 0 };
for (const root of roots) {
- const next = await estimateWorkspace(root, scope.assertCurrent);
+ const next = await estimateWorkspace(
+ root,
+ scope.assertCurrent,
+ TASK_MIGRATION_MAX_FILES - estimate.fileCount,
+ );
estimate.fileCount += next.fileCount;
estimate.bytes += next.bytes;
}
diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.ts
index 325fcb8533..5703e0b346 100644
--- a/apps/desktop/src/main/task-migration/workspace.ts
+++ b/apps/desktop/src/main/task-migration/workspace.ts
@@ -9,6 +9,18 @@ import {
} from '../worktree/contentSnapshot';
import { gitExec, GitExecError } from '../worktree/gitExec';
import { assertDiskCapacity } from './resources';
+import { MANAGED_WORKTREE_DIR_NAMES } from '../../shared/managedWorktreePaths';
+
+/** Other tasks' Cindy worktrees live under the repository root; a copy never carries them. */
+const EXCLUDED_ROOT_NAMES: readonly string[] = MANAGED_WORKTREE_DIR_NAMES;
+const ESTIMATE_CONCURRENCY = 32;
+
+/** Whether `file` lies in a top-level directory that copies of `root` leave behind. */
+export function isExcludedFromWorkspace(root: string, file: string): boolean {
+ const relative = path.relative(root, file);
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return false;
+ return EXCLUDED_ROOT_NAMES.includes(relative.split(path.sep)[0]);
+}
export interface PortableWorkspace {
version: 1;
@@ -80,7 +92,8 @@ export function validateWorkspaceEntries(files: Record<string, FileEvidence>): v
}
}
-/** No checkout, reset, stash, or source deletion. Existing recovery code preserves ignored bytes too. */
+/** No checkout, reset, stash, or source deletion. Existing recovery code preserves ignored bytes too;
+ * only other tasks' managed worktrees under the root are left out. */
export async function snapshotWorkspace(
root: string,
directory: string,
@@ -133,6 +146,7 @@ export async function snapshotWorkspace(
encryptedKey: '',
iv: randomBytes(12),
maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),
+ excludeRootNames: [...EXCLUDED_ROOT_NAMES],
});
archive.files = Object.fromEntries(
Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),
@@ -243,28 +257,62 @@ export async function restoreWorkspace(
}
/** Read-only pre-copy inventory: includes hidden/ignored files, never follows links.
- * Root Git metadata is rebuilt separately by snapshotWorkspace, not copied as files.
+ * Root Git metadata is rebuilt separately by snapshotWorkspace and other tasks' managed
+ * worktrees are not copied, so neither is counted. Stops once `maxFiles` is exceeded.
*/
export async function estimateWorkspace(
root: string,
check: () => void,
+ maxFiles = Number.POSITIVE_INFINITY,
): 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)) {
+ const pending = [root];
+ const visit = async (directory: string): Promise<void> => {
+ const files: string[] = [];
+ for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
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');
+ if (directory === root && (entry.name === '.git' || EXCLUDED_ROOT_NAMES.includes(entry.name)))
+ continue;
+ const file = path.join(directory, entry.name);
+ if (entry.isDirectory()) pending.push(file);
+ else if (entry.isFile() || entry.isSymbolicLink()) files.push(file);
+ else throw new Error('MIGRATION_NONPORTABLE_PATH');
}
- }
- await walk(root);
+ for (const stat of await Promise.all(files.map((file) => fs.lstat(file)))) {
+ result.fileCount++;
+ result.bytes += stat.size;
+ }
+ if (result.fileCount > maxFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
+ };
+ // A sequential walk of a dependency-heavy project takes minutes; unbounded recursion
+ // would hold the whole tree in memory. Visit a bounded number of directories at once.
+ await new Promise<void>((resolve, reject) => {
+ let active = 0;
+ let settled = false;
+ const pump = () => {
+ if (settled) return;
+ if (!pending.length && !active) {
+ settled = true;
+ resolve();
+ return;
+ }
+ while (active < ESTIMATE_CONCURRENCY && pending.length) {
+ active++;
+ visit(pending.pop()!).then(
+ () => {
+ active--;
+ pump();
+ },
+ (error: unknown) => {
+ settled = true;
+ reject(error);
+ },
+ );
+ }
+ };
+ pump();
+ });
check();
return result;
}
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
index 7679e34682..a2f3f88da3 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
@@ -25,12 +25,13 @@ function restorableMode(mode: number): number {
return mode & (process.platform === 'win32' ? 0o666 : 0o777);
}
-export async function inventoryWorktree(root: string, maxBytes?: number): Promise<Record<string, FileEvidence>> {
+/** `excludeRootNames` skips extra top-level entries (task copy leaves other tasks' worktrees behind). */
+export async function inventoryWorktree(root: string, maxBytes?: number, excludeRootNames: readonly string[] = []): Promise<Record<string, FileEvidence>> {
const files: Record<string, FileEvidence> = Object.create(null);
let bytes = 0;
const walk = async (directory: string): Promise<void> => {
for (const name of await fs.readdir(directory)) {
- if (directory === root && name === '.git') continue;
+ if (directory === root && (name === '.git' || excludeRootNames.includes(name))) continue;
const absolute = path.join(directory, name);
const stat = await fs.lstat(absolute);
const relative = path.relative(root, absolute);
@@ -128,8 +129,8 @@ export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive, di
if (!sameWorktreeFiles(files, archive.files)) throw new Error('archive content does not match worktree inventory');
}
-export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number): Promise<WorktreeRecoveryArchive> {
- const files = await inventoryWorktree(root, maxBytes);
+export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number, excludeRootNames: readonly string[] = []): Promise<WorktreeRecoveryArchive> {
+ const files = await inventoryWorktree(root, maxBytes, excludeRootNames);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;
await fs.mkdir(directory, { recursive: true });
@@ -148,7 +149,7 @@ export async function createRecoveryArchive(root: string, resourceId: string, di
try { await handle.sync(); } finally { await handle.close(); }
const archive = { file, encryptedKey, iv: Buffer.from(iv).toString('base64'), tag: cipher.getAuthTag().toString('base64'), files };
await verifyRecoveryArchive(archive, directory, key, maxBytes);
- if (!sameWorktreeFiles(await inventoryWorktree(root), files)) throw new Error('worktree changed during archive');
+ if (!sameWorktreeFiles(await inventoryWorktree(root, undefined, excludeRootNames), files)) throw new Error('worktree changed during archive');
return archive;
} catch (error) {
await fs.rm(target, { force: true });
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
index 3035300b89..a0a8d1444d 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
@@ -4,7 +4,7 @@ import type { FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO'
type ArchiveInput = { archive: WorktreeRecoveryArchive; directory: string; key: Uint8Array; maxBytes?: number };
export type RecoveryArchiveTask =
| { operation: 'inventory'; root: string }
- | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number }
+ | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number; excludeRootNames?: string[] }
| ({ operation: 'verify' } & ArchiveInput)
| ({ operation: 'extract'; staging: string; keep: boolean } & ArchiveInput);
export type RecoveryArchiveResult<T extends RecoveryArchiveTask> =
@@ -16,7 +16,7 @@ export async function executeRecoveryArchiveTask(task: RecoveryArchiveTask) {
try {
switch (task.operation) {
case 'inventory': return await io.inventoryWorktree(task.root);
- case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes);
+ case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes, task.excludeRootNames);
case 'verify': return await io.verifyRecoveryArchive(task.archive, task.directory, task.key, task.maxBytes);
case 'extract': return await io.extractRecoveryArchive(task.archive, task.staging, task.keep, task.directory, task.key, task.maxBytes);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
index a1945c6d67..a42f80764e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
@@ -2,7 +2,11 @@ import { useEffect, useRef, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
-import type { TaskMigrationRequest, TaskMigrationView } from '@cindy/device-link';
+import {
+ TASK_MIGRATION_MAX_FILES,
+ type TaskMigrationRequest,
+ type TaskMigrationView,
+} from '@cindy/device-link';
import type { Session } from '@/lib/ccAgent.types';
import type { TaskMoveDestination } from './TaskMoveSubmenu';
import { Button } from '@/components/ui/button';
@@ -37,7 +41,7 @@ export function TaskMigrationDialog({
const [pollError, setPollError] = useState('');
const [self, setSelf] = useState('');
const [estimate, setEstimate] = useState<TaskMigrationView['estimate']>();
- const [estimateError, setEstimateError] = useState(false);
+ const [estimateError, setEstimateError] = useState('');
const pending = useRef(false);
const observingCopy = useRef(!destination);
const previousCopy = useRef<string | undefined>(undefined);
@@ -204,7 +208,7 @@ export function TaskMigrationDialog({
if (!confirming) return;
let disposed = false;
setEstimate(undefined);
- setEstimateError(false);
+ setEstimateError('');
void request({ action: 'caps' })
.then(async (caps) => {
if (!caps.copyEstimate) throw new Error('Estimate unavailable');
@@ -221,8 +225,8 @@ export function TaskMigrationDialog({
throw new Error('Invalid estimate');
if (!disposed && current()) setEstimate(result.estimate);
})
- .catch(() => {
- if (!disposed && current()) setEstimateError(true);
+ .catch((e: unknown) => {
+ if (!disposed && current()) setEstimateError(errorCode(e));
});
return () => {
disposed = true;
@@ -253,6 +257,19 @@ export function TaskMigrationDialog({
if (value >= 1024 ** 2) return `${(value / 1024 ** 2).toFixed(1)} MB`;
return `${(Math.max(0, value) / 1024).toFixed(1)} KB`;
};
+ const estimateText =
+ estimateError === 'MIGRATION_TIMEOUT'
+ ? t('taskMigration.estimateTimeout')
+ : estimateError === 'MIGRATION_TOO_MANY_FILES'
+ ? t('taskMigration.estimateTooManyFiles', { limit: TASK_MIGRATION_MAX_FILES })
+ : estimateError
+ ? t('taskMigration.estimateFailed')
+ : estimate
+ ? t('taskMigration.fileSummary', {
+ count: estimate.fileCount,
+ size: bytes(estimate.bytes),
+ })
+ : t('taskMigration.estimating');
const errorKey =
failure && t(`taskMigration.errors.${failure}`, { defaultValue: t('taskMigration.failed') });
return (
@@ -355,14 +372,7 @@ export function TaskMigrationDialog({
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')}
+ {estimateText}
</p>
{estimate && (
<p className="mt-2 text-[var(--confirm-desc)]">{t('taskMigration.estimateNote')}</p>
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.tsx
index e44a93a66f..e37f6d8522 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
@@ -370,6 +370,22 @@ it('does not copy when the source does not support inventory', async () => {
expect(state.request.mock.calls.some(([, c]) => c.action === 'estimate')).toBe(false);
});
+it.each([
+ ['[PRECONDITION_FAILED] MIGRATION_TIMEOUT', 'taskMigration.estimateTimeout'],
+ ['[PRECONDITION_FAILED] MIGRATION_TOO_MANY_FILES', 'taskMigration.estimateTooManyFiles'],
+ ['[PRECONDITION_FAILED] MIGRATION_FAILED', 'taskMigration.estimateFailed'],
+])('explains why inventory failed (%s) and keeps Copy disabled', async (message, text) => {
+ const original = state.request.getMockImplementation()!;
+ state.request.mockImplementation((device, command) =>
+ command.action === 'estimate' ? Promise.reject(new Error(message)) : original(device, command),
+ );
+ mount();
+ await screen.findByText(text);
+ expect(
+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+});
+
it.each(['confirm', 'complete'])(
'clears recovered status errors on %s without erasing action errors',
async (stage) => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d05c009027..7be3b54240 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -45,7 +45,8 @@
"MIGRATION_TARGET_MODEL_UNAVAILABLE": "The destination has no available model for this task’s engine. Connect a provider there first.",
"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."
+ "MIGRATION_SOURCE_CHANGED": "The source task changed during preparation. Retry the copy.",
+ "MIGRATION_TIMEOUT": "The source computer did not respond in time. Try again later."
},
"successTitle": "Copy successful",
"successDescription": "Copied to {{name}}.",
@@ -60,7 +61,9 @@
"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."
+ "estimateFailed": "Could not count files. Check the source computer’s connection and version, then close and try again.",
+ "estimateTimeout": "Counting timed out: the project has too many files for the source computer to finish in time. Try copying a project with fewer files.",
+ "estimateTooManyFiles": "The project has more than {{limit, number}} files and cannot be copied. Copy a project with fewer files instead."
},
"sharedTask": {
"selfJoin": "You started this shared task, so you don’t need to join. Open it from “Shared by Me”.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6aba0141b1..3b8d8f90ee 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -45,7 +45,8 @@
"MIGRATION_TARGET_MODEL_UNAVAILABLE": "コピー先にこのタスクのエンジンで利用できるモデルがありません。先にプロバイダーを接続してください。",
"MIGRATION_UNSUPPORTED": "両方のコンピューターをタスクのコピーに対応したバージョンに更新してください。",
"MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。",
- "MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。"
+ "MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。",
+ "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。"
},
"successTitle": "コピー完了",
"successDescription": "{{name}}にコピーしました。",
@@ -60,7 +61,9 @@
"estimating": "ファイル数とサイズを計算中…",
"fileSummary": "プロジェクトファイル:{{count}} 個、合計 {{size}}",
"estimateNote": "隠しファイルを含むコピー前の推定値です。別途コピーする Git 履歴、タスクの会話と添付ファイルは含みません。ファイルの変更により最終サイズは変わります。",
- "estimateFailed": "集計できませんでした。コピー元の接続とバージョンを確認し、閉じて再試行してください。"
+ "estimateFailed": "集計できませんでした。コピー元の接続とバージョンを確認し、閉じて再試行してください。",
+ "estimateTimeout": "集計がタイムアウトしました。プロジェクトのファイルが多すぎるため、コピー元が時間内に集計を完了できませんでした。ファイル数の少ないプロジェクトをコピーしてください。",
+ "estimateTooManyFiles": "プロジェクトのファイルが {{limit, number}} 個を超えているため、コピーできません。ファイル数の少ないプロジェクトをコピーしてください。"
},
"sharedTask": {
"selfJoin": "これは自分が開始した共有タスクのため、参加する必要はありません。「自分が共有中」から開いてください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7a19826c93..9b6ffb23a9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -45,7 +45,8 @@
"MIGRATION_TARGET_MODEL_UNAVAILABLE": "대상 컴퓨터에 이 작업 엔진에서 사용할 수 있는 모델이 없습니다. 먼저 제공자를 연결하세요.",
"MIGRATION_UNSUPPORTED": "두 컴퓨터 모두 작업 복사을 지원하는 버전으로 업데이트하세요.",
"MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.",
- "MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요."
+ "MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요.",
+ "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요."
},
"successTitle": "복사 완료",
"successDescription": "{{name}}에 복사했습니다.",
@@ -60,7 +61,9 @@
"estimating": "파일 수와 크기 계산 중…",
"fileSummary": "프로젝트 파일: {{count}}개, 총 {{size}}",
"estimateNote": "숨김 파일을 포함한 복사 전 예상치입니다. 별도로 복사하는 Git 기록, 작업 대화 및 첨부 파일은 제외됩니다. 파일 변경에 따라 최종 크기가 달라질 수 있습니다.",
- "estimateFailed": "파일을 집계하지 못했습니다. 원본 컴퓨터의 연결과 버전을 확인한 후 닫고 다시 시도하세요."
+ "estimateFailed": "파일을 집계하지 못했습니다. 원본 컴퓨터의 연결과 버전을 확인한 후 닫고 다시 시도하세요.",
+ "estimateTimeout": "집계 시간이 초과되었습니다. 프로젝트 파일이 너무 많아 원본 컴퓨터가 제한 시간 내에 집계하지 못했습니다. 파일이 더 적은 프로젝트를 복사해 보세요.",
+ "estimateTooManyFiles": "프로젝트 파일이 {{limit, number}}개를 넘어 복사할 수 없습니다. 파일이 더 적은 프로젝트를 복사하세요."
},
"sharedTask": {
"selfJoin": "내가 시작한 공유 작업이므로 참여할 필요가 없습니다. “내가 공유한 항목”에서 여세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 91402d750d..344f9dfb29 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -45,7 +45,8 @@
"MIGRATION_TARGET_MODEL_UNAVAILABLE": "目标电脑没有可用于此任务引擎的模型,请先在目标电脑连接供应商。",
"MIGRATION_UNSUPPORTED": "请将两台电脑更新至支持任务复制的版本。",
"MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。",
- "MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。"
+ "MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。",
+ "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。"
},
"successTitle": "复制成功",
"successDescription": "已复制到{{name}}。",
@@ -60,7 +61,9 @@
"estimating": "正在统计文件数量和大小…",
"fileSummary": "项目文件:{{count}} 个,共 {{size}}",
"estimateNote": "复制前估算,含隐藏文件;不含另行复制的 Git 历史、任务对话及附件。文件变化可能影响最终大小。",
- "estimateFailed": "无法统计文件。请检查任务所在电脑的连接和版本,然后关闭重试。"
+ "estimateFailed": "无法统计文件。请检查任务所在电脑的连接和版本,然后关闭重试。",
+ "estimateTimeout": "统计超时:项目文件过多,任务所在电脑未能在时限内完成统计。可以改为复制文件更少的项目。",
+ "estimateTooManyFiles": "项目文件超过 {{limit, number}} 个,无法复制。请改为复制文件更少的项目。"
},
"sharedTask": {
"selfJoin": "这是你发起的共享任务,无需加入。请从“我发起的”打开",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index a9d4f19981..f80bed929a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -45,7 +45,8 @@
"MIGRATION_TARGET_MODEL_UNAVAILABLE": "目標電腦沒有可用於此任務引擎的模型,請先在目標電腦連接供應商。",
"MIGRATION_UNSUPPORTED": "請將兩台電腦更新至支援任務複製的版本。",
"MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。",
- "MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。"
+ "MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。",
+ "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。"
},
"successTitle": "複製成功",
"successDescription": "已複製到{{name}}。",
@@ -60,7 +61,9 @@
"estimating": "正在統計檔案數量和大小…",
"fileSummary": "專案檔案:{{count}} 個,共 {{size}}",
"estimateNote": "複製前估算,含隱藏檔案;不含另行複製的 Git 歷史、任務對話及附件。檔案變化可能影響最終大小。",
- "estimateFailed": "無法統計檔案。請檢查任務所在電腦的連線和版本,然後關閉重試。"
+ "estimateFailed": "無法統計檔案。請檢查任務所在電腦的連線和版本,然後關閉重試。",
+ "estimateTimeout": "統計逾時:專案檔案過多,任務所在電腦未能在時限內完成統計。可以改為複製檔案較少的專案。",
+ "estimateTooManyFiles": "專案檔案超過 {{limit, number}} 個,無法複製。請改為複製檔案較少的專案。"
},
"sharedTask": {
"selfJoin": "這是你發起的共享任務,無需加入。請從「我發起的」開啟",
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index f96d266380..386aef1d00 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -45,7 +45,9 @@ warn/warning 状态检查项、等待或处理中的检查项和 warning issue
源任务和文件保留可用,自动任务及消息渠道不转移。数据复用 peer 附件与 OSS;复制记录及目标回执
仅用于幂等重试,不管理源任务执行权。写请求不进入自动重试白名单,无需服务端变更。
`preflight` 检查目标实时资源;文件描述可为单附件或有序分段附件,每段复用已有协议和校验,
-复制不设固定总量上限。整组 Orca 沿用可选 `teamMigration: true` 能力声明,缺省不支持;
+复制不设固定总量上限;`estimate` 超过 `TASK_MIGRATION_MAX_FILES`(50 万)个项目文件时返回
+`MIGRATION_TOO_MANY_FILES`,控制端据此不开始复制,旧源端不返回该错误码。
+整组 Orca 沿用可选 `teamMigration: true` 能力声明,缺省不支持;
`receive.files.additionalWorkspaces` 沿用同一文件描述,manifest 记录成员到目录的映射。
双方必须支持复制通道;收到整组能力声明才发送团队,不尝试部分导入。
范围、恢复与源目录保护见 [同机移动与跨电脑复制任务](../product-rules/task-device-migration.md)。
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index 62f5497872..bf8092bbe3 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -17,6 +17,8 @@
不发布这次副本。该检查不冻结输入,也不承诺外部编辑器与数据库的跨进程原子快照。
复制是一次快照,不持续同步;源任务后续变化不会更新副本。快照遇到文件变化会失败并允许重试。
2. 复用任务分享导出、原生上下文恢复及 worktree 快照。包含未提交、未跟踪和忽略文件;
+ 项目根目录下其它任务的 Cindy 托管 worktree(`.cindy-worktrees`,旧名 `.xdt-worktrees`)
+ 不随副本复制,也不计入统计;在这些 worktree 里运行的任务不阻止复制。
Git 保留 HEAD、暂存区和工作文件差别,不复制本机 Git 配置、hooks 或凭证。
目标始终创建独立目录,不覆盖已有项目。整组共享物理目录只复制一份,独立目录分别创建。
3. 复用 peer 直传及 OSS 回退、冷却。按实时磁盘和可用内存预算准备、发送、接收及解包,
@@ -26,6 +28,8 @@
5. 确认页使用接收电脑名称或“本机”,展示项目文件数量与复制前估算大小(含隐藏/忽略文件,整组共享目录去重)。
Git 历史、任务对话与附件另行复制,不计入项目文件统计;统计完成前不能开始复制。
`copyEstimate` 能力存在时才调用 `estimate`;旧源端无法统计时明确提示连接/版本检查,不开始复制。
+ 统计请求超时时提示项目文件过多,不提示连接/版本;项目文件超过 50 万个时提前停止统计,
+ 提示改为复制文件更少的项目,不开始复制。
6. 复制全程保留弹窗,不提供隐藏到后台的入口;准备阶段显示不定进度,发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。
OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。
文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。
@@ -53,6 +57,6 @@
- Git 目录须为仓库根;暂不支持子模块、嵌套 Git 元数据、无首个提交仓库、目录外链接或链接链,
以及目标系统无法表示的文件名和大小写冲突。空间或内存不足时提示并保留源文件。
- 失败仅影响本次复制,不重启 relay、不关闭其它设备链路、不重放无关请求。接收预算 30 分钟,
- 其它请求 30 秒;写请求没有通用自动重试。没有服务端或数据库 schema 变更。
+ 文件统计 3 分钟,其它请求 30 秒;写请求没有通用自动重试。没有服务端或数据库 schema 变更。
两台真实电脑端到端、Windows 实机与 Light/Dark 实际目检尚未完成;单元测试不替代这些验证。
diff --git a/packages/device-link/src/__tests__/invokePolicy.test.ts b/packages/device-link/src/__tests__/invokePolicy.test.ts
index d74a96d52d..7905dcbe44 100644
--- a/packages/device-link/src/__tests__/invokePolicy.test.ts
+++ b/packages/device-link/src/__tests__/invokePolicy.test.ts
@@ -4,6 +4,7 @@ import {
isPeerResetRetryableReadChannel,
isCompletedInvokeRetryableReadChannel,
resolveRemoteInvokeTimeoutMs,
+ TASK_MIGRATION_CHANNEL,
} from '../index.js';
describe('remote invoke policy boundaries', () => {
@@ -60,4 +61,12 @@ describe('remote invoke policy boundaries', () => {
expect(resolveRemoteInvokeTimeoutMs('device-link:remote-desktop:v1', [{ op: 'heartbeat' }], 'desktop')).toBe(59_000);
expect(resolveRemoteInvokeTimeoutMs('unknown:read', [], 'mobile')).toBeUndefined();
});
+ it('gives the read-only task copy estimate a longer budget than other copy requests', () => {
+ const budget = (action: string) =>
+ resolveRemoteInvokeTimeoutMs(TASK_MIGRATION_CHANNEL, [{ action, sessionId: 's' }], 'desktop');
+ expect(budget('estimate')).toBe(3 * 60_000);
+ expect(budget('receive')).toBe(30 * 60_000);
+ expect(budget('status')).toBe(30_000);
+ expect(budget('caps')).toBe(30_000);
+ });
});
diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.ts
index f2aac76408..875743426c 100644
--- a/packages/device-link/src/invokePolicy.ts
+++ b/packages/device-link/src/invokePolicy.ts
@@ -1,5 +1,5 @@
import { INVOKE_TIMEOUT_OVERRIDES_MS } from './allowlist.js';
-import { TASK_MIGRATION_CHANNEL } from './taskMigration.js';
+import { TASK_MIGRATION_CHANNEL, TASK_MIGRATION_ESTIMATE_TIMEOUT_MS } from './taskMigration.js';
import type { InvokePayload } from './protocol.js';
/**
@@ -88,8 +88,11 @@ export function resolveRemoteInvokeTimeoutMs(
): number | undefined {
if (channel === TASK_MIGRATION_CHANNEL) {
const request = args?.[0];
- return request && typeof request === 'object' && 'action' in request && request.action === 'receive'
- ? 30 * 60_000 : 30_000;
+ const action = request && typeof request === 'object' && 'action' in request ? request.action : undefined;
+ if (action === 'receive') return 30 * 60_000;
+ // Read-only inventory of a large project (dependencies included) can legitimately exceed 30s.
+ if (action === 'estimate') return TASK_MIGRATION_ESTIMATE_TIMEOUT_MS;
+ return 30_000;
}
if (platform === 'desktop') return INVOKE_TIMEOUT_OVERRIDES_MS[channel];
// Renewals must settle before the 12s lease, independently of slow media offers.
diff --git a/packages/device-link/src/taskMigration.ts b/packages/device-link/src/taskMigration.ts
index 8d655a1923..abe61d1080 100644
--- a/packages/device-link/src/taskMigration.ts
+++ b/packages/device-link/src/taskMigration.ts
@@ -1,6 +1,9 @@
/** Same-account independent task copy. File bytes use existing peer attachments / OSS, never relay frames. */
export const TASK_MIGRATION_CHANNEL = "maker:task-copy";
export const TASK_MIGRATION_LOCAL_CHANNEL = "task-copy:request";
+/** `estimate` stops early with MIGRATION_TOO_MANY_FILES above this many project files. */
+export const TASK_MIGRATION_MAX_FILES = 500_000;
+export const TASK_MIGRATION_ESTIMATE_TIMEOUT_MS = 3 * 60_000;
export interface MigrationFileRef {
ref: string;
size: number;