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。

refactor(task-copy): 只排除 Git 登记的托管 worktree,撤回复制阶段的文件数上限

Dash14f589bdb24a
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 56d03e26c4..fdbaa096cf 100644
--- a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
@@ -24,26 +24,37 @@ it('counts hidden and nested files, skips root Git metadata and does not count d
}
});
-it("skips other tasks' managed worktree directories only at a repository root", async () => {
- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));
+it("skips only other tasks' registered worktrees, never other content of those folders", async () => {
+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-')));
+ const git = (...args: string[]) =>
+ execFileSync('git', [
+ '-c',
+ 'user.name=t',
+ '-c',
+ 'user.email=t@localhost',
+ '-c',
+ 'commit.gpgsign=false',
+ '-C',
+ root,
+ ...args,
+ ]);
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');
- // A plain directory never holds Cindy worktrees: same-named folders are user files,
- // even when stray (invalid) `.git` metadata is left at the root.
- expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 3, bytes: 24 });
+ await fs.writeFile(path.join(root, 'a'), 'a');
+ await fs.mkdir(path.join(root, '.cindy-worktrees', 'notes'), { recursive: true });
+ await fs.writeFile(path.join(root, '.cindy-worktrees', 'notes', 'n'), 'xy');
+ await fs.mkdir(path.join(root, '.xdt-worktrees', 'stale'), { recursive: true });
+ await fs.writeFile(path.join(root, '.xdt-worktrees', 'stale', 'old'), 'zzz');
+ // A plain directory excludes nothing, even with stray `.git` metadata at its root.
await fs.mkdir(path.join(root, '.git'));
- expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 3, bytes: 24 });
- execFileSync('git', ['init', '-q', root]);
- expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 1, bytes: 4 });
- // Only directories are skipped; a same-named file is still project content.
- await fs.rm(path.join(root, '.xdt-worktrees'), { recursive: true });
- await fs.writeFile(path.join(root, '.xdt-worktrees'), '12');
- expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 2, bytes: 6 });
+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 3, bytes: 6 });
+ await fs.rm(path.join(root, '.git'), { recursive: true });
+ git('init', '-q');
+ git('add', 'a');
+ git('commit', '-q', '-m', 'fixture');
+ git('worktree', 'add', '-q', '-b', 'other', path.join('.cindy-worktrees', 'other-task'));
+ // Only the registered worktree is skipped; user folders beside it and an unregistered
+ // folder in a managed container are still project content.
+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 3, bytes: 6 });
} 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 0b32399654..a6dcaeb254 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -42,7 +42,6 @@ const state = vi.hoisted(() => ({
workers: [] as string[],
estimateLimits: [] as number[],
timeoutAction: '' as string,
- tooManyFiles: false,
}));
vi.mock('../../localDb/ipc/sessionCreatedBroadcast', () => ({
emitSessionCreated: (id: string) => state.created(id),
@@ -209,25 +208,17 @@ vi.mock('../../session-share/sessionShareImport', () => ({
vi.mock('../workspace', async (original) => ({
isExcludedFromWorkspace: (await original<typeof import('../workspace')>())
.isExcludedFromWorkspace,
- excludedRootDirectories: (await original<typeof import('../workspace')>())
- .excludedRootDirectories,
+ managedWorktreeExclusions: (await original<typeof import('../workspace')>())
+ .managedWorktreeExclusions,
estimateWorkspace: async (_root: string, _check: () => void, maxFiles: number) => {
state.estimateLimits.push(maxFiles);
- if (state.tooManyFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
return { fileCount: 1, bytes: 8 };
},
- snapshotWorkspace: async (source: string, directory: string, _id: string, maxFiles: number) => {
- state.snapshot(maxFiles);
+ snapshotWorkspace: async (source: string, directory: string) => {
+ state.snapshot();
await fs.mkdir(directory, { recursive: true });
await fs.copyFile(path.join(source, 'draft'), path.join(directory, 'a.tar.gz.enc'));
- const file = { kind: 'file', mode: 0o644, hash: 'a'.repeat(64) };
- return {
- unpackedBytes: 8,
- archive: {
- file: 'a.tar.gz.enc',
- files: { dir: { kind: 'directory', mode: 0o755, hash: '' }, 'dir/a': file, b: file },
- },
- };
+ return { unpackedBytes: 8, archive: { file: 'a.tar.gz.enc', files: {} } };
},
restoreWorkspace: async (_manifest: unknown, directory: string, target: string) => {
await fs.copyFile(path.join(directory, 'a.tar.gz.enc'), path.join(target, 'draft'));
@@ -280,7 +271,6 @@ describe('resumable cross-computer copy', () => {
state.workers = [];
state.estimateLimits = [];
state.timeoutAction = '';
- state.tooManyFiles = false;
const cwd = path.join(state.root, 'shared');
await fs.mkdir(cwd);
await fs.writeFile(path.join(cwd, 'draft'), 'original');
@@ -503,16 +493,6 @@ describe('resumable cross-computer copy', () => {
expect(receipt().workingDir).not.toBe(firstDir);
expect(receipt().workingDir).not.toBe(secondDir);
});
- it('hands each team snapshot only the file allowance the earlier ones left', async () => {
- await team();
- await start();
- expect((await settled()).stage).toBe('complete');
- // Two files per mocked snapshot; directories do not count toward the cap.
- expect(state.snapshot.mock.calls).toEqual([
- [TASK_MIGRATION_MAX_FILES],
- [TASK_MIGRATION_MAX_FILES - 2],
- ]);
- });
it('estimates each physical team workspace once without exporting or uploading', async () => {
await team();
const result = await requestTaskMigration({ action: 'estimate', sessionId: 'fork' });
@@ -532,24 +512,31 @@ describe('resumable cross-computer copy', () => {
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 () => {
+ it('ignores tasks running in other registered worktrees under the copied root', async () => {
const rows = state.rows.get('A')!;
const cwd = rows.get('fork')!.workingDir as string;
+ const git = (...args: string[]) =>
+ execFileSync('git', [
+ '-c',
+ 'user.name=t',
+ '-c',
+ 'user.email=t@localhost',
+ '-c',
+ 'commit.gpgsign=false',
+ '-C',
+ cwd,
+ ...args,
+ ]);
+ git('init', '-q');
+ git('add', 'draft');
+ git('commit', '-q', '-m', 'fixture');
const managed = path.join(cwd, '.cindy-worktrees', 'other');
- await fs.mkdir(managed, { recursive: true });
- execFileSync('git', ['init', '-q', cwd]);
+ git('worktree', 'add', '-q', '-b', 'other', managed);
rows.get('sibling')!.workingDir = managed;
state.siblingRunning = true;
await start();
expect((await settled()).stage).toBe('complete');
});
- it('re-checks the file cap before exporting, since files may grow after the estimate', async () => {
- state.tooManyFiles = true;
- await start();
- expect((await settled()).error).toBe('MIGRATION_TOO_MANY_FILES');
- expect(state.exported).not.toHaveBeenCalled();
- expect(state.snapshot).not.toHaveBeenCalled();
- });
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');
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 476caa8d29..8bca69cd65 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,23 +108,36 @@ 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 in a repository", async () => {
+ it("leaves other tasks' registered worktrees behind but keeps user files beside them", async () => {
await git(source, 'init', '-b', 'main');
await git(source, 'config', 'user.name', 'Migration test');
await git(source, 'config', 'user.email', 'migration@localhost');
await fs.writeFile(path.join(source, 'draft'), 'mine\n');
await git(source, 'add', 'draft');
await git(source, 'commit', '-m', 'fixture');
- 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');
- }
+ await git(
+ source,
+ 'worktree',
+ 'add',
+ '-b',
+ 'other',
+ path.join('.cindy-worktrees', 'other-task'),
+ );
+ await fs.writeFile(path.join(source, '.cindy-worktrees', 'other-task', 'file'), 'not mine\n');
+ await fs.mkdir(path.join(source, '.cindy-worktrees', 'notes'));
+ await fs.writeFile(path.join(source, '.cindy-worktrees', 'notes', 'n'), 'mine too\n');
const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
- expect(Object.keys(snapshot.archive.files)).toEqual(['draft']);
+ expect(Object.keys(snapshot.archive.files).sort()).toEqual([
+ '.cindy-worktrees',
+ '.cindy-worktrees/notes',
+ '.cindy-worktrees/notes/n',
+ 'draft',
+ ]);
await restoreWorkspace(snapshot, artifacts, target);
- expect((await fs.readdir(target)).sort()).toEqual(['.git', 'draft']);
+ expect(await fs.readFile(path.join(target, '.cindy-worktrees', 'notes', 'n'), 'utf8')).toBe(
+ 'mine too\n',
+ );
+ await expect(fs.stat(path.join(target, '.cindy-worktrees', 'other-task'))).rejects.toThrow();
expect(
await fs.readFile(path.join(source, '.cindy-worktrees', 'other-task', 'file'), 'utf8'),
).toBe('not mine\n');
@@ -138,36 +151,6 @@ describe('cross-machine project snapshots', () => {
expect(await inventoryWorktree(target)).toEqual(before);
expect(Object.keys(before)).toContain(path.join('.cindy-worktrees', 'notes'));
});
- it('stops the snapshot walk once the file allowance is exceeded', async () => {
- await fs.mkdir(path.join(source, 'sub'));
- for (const name of ['a', 'b', path.join('sub', 'c')])
- await fs.writeFile(path.join(source, name), name);
- await expect(snapshotWorkspace(source, artifacts, randomUUID(), 2)).rejects.toThrow(
- 'MIGRATION_TOO_MANY_FILES',
- );
- const snapshot = await snapshotWorkspace(source, artifacts, randomUUID(), 3);
- expect(Object.keys(snapshot.archive.files).sort()).toEqual(['a', 'b', 'sub', 'sub/c']);
- });
- it('keeps the file allowance when files appear while the archive is written', async () => {
- await fs.writeFile(path.join(source, 'a'), 'a');
- const open = fs.open.bind(fs);
- let grown = false;
- // The archive is fsynced via fs.open after packing; grow the tree at that moment.
- const grow = vi.spyOn(fs, 'open').mockImplementation(async (...args) => {
- grow.mockRestore();
- grown = true;
- for (const name of ['b', 'c']) await fs.writeFile(path.join(source, name), name);
- return open(...(args as Parameters<typeof open>));
- });
- try {
- await expect(snapshotWorkspace(source, artifacts, randomUUID(), 2)).rejects.toThrow(
- 'MIGRATION_TOO_MANY_FILES',
- );
- expect(grown).toBe(true);
- } finally {
- grow.mockRestore();
- }
- });
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 5afb01abfa..150075b2a9 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -56,7 +56,7 @@ import {
restoreWorkspace,
estimateWorkspace,
isExcludedFromWorkspace,
- excludedRootDirectories,
+ managedWorktreeExclusions,
type PortableWorkspace,
} from './workspace';
@@ -298,7 +298,7 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
),
];
// A task inside another managed worktree under a copied root does not touch copied files.
- const excluded = await Promise.all(sourceKeys.map(excludedRootDirectories));
+ const excluded = await Promise.all(sourceKeys.map(managedWorktreeExclusions));
for (const session of getMakerIfReady()?.listActiveSessions() ?? []) {
if (!session.isTurnRunning() && !sourceBoundary!.isBusy(session.id)) continue;
const row = await scope.db.queryOne<{
@@ -327,9 +327,6 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
scope.assertCurrent();
if (members.some((member) => sourceBoundary!.isBusy(member.id)))
throw new Error('MIGRATION_TASK_RUNNING');
- // The confirmation estimate is not a lasting admission: files may have grown since.
- await estimateRoots(scope, sourceKeys);
- scope.assertCurrent();
const result = await exportSessionShare({
sessionId: record.sessionId,
targetPath: path.join(directory, 'session.cshare'),
@@ -341,20 +338,10 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
if (result.status !== 'ok' || result.fidelity !== 'full' || result.mediaMissing)
throw new Error('MIGRATION_INCOMPLETE_CONTEXT');
const snapshots: PortableWorkspace[] = [];
- // Files can still appear after the re-check above; bound the snapshot walk itself too.
- let remainingFiles = TASK_MIGRATION_MAX_FILES;
- for (const [index, dir] of sourceKeys.entries()) {
- const snapshot = await snapshotWorkspace(
- dir,
- workspaceDirectory(directory, index),
- record.id,
- remainingFiles,
+ for (const [index, dir] of sourceKeys.entries())
+ snapshots.push(
+ await snapshotWorkspace(dir, workspaceDirectory(directory, index), record.id),
);
- remainingFiles -= Object.values(snapshot.archive.files).filter(
- (entry) => entry.kind !== 'directory',
- ).length;
- snapshots.push(snapshot);
- }
// Copy does not freeze input. Discard preparation if the task or team changed
// while capturing conversation and files, including a turn that already finished.
await sourceBoundary!.drain();
@@ -384,21 +371,6 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
);
}
-/** The file cap covers every copied directory together; MIGRATION_TOO_MANY_FILES above it. */
-async function estimateRoots(scope: Scope, roots: Iterable<string>) {
- const estimate = { fileCount: 0, bytes: 0 };
- for (const root of roots) {
- const next = await estimateWorkspace(
- root,
- scope.assertCurrent,
- TASK_MIGRATION_MAX_FILES - estimate.fileCount,
- );
- estimate.fileCount += next.fileCount;
- estimate.bytes += next.bytes;
- }
- return estimate;
-}
-
async function sendFile(
scope: Scope,
device: string,
@@ -950,7 +922,17 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
const roots = new Set(
await Promise.all(members.map((member) => physicalWorktreeKey(member.workingDir))),
);
- const estimate = await estimateRoots(scope, roots);
+ const estimate = { fileCount: 0, bytes: 0 };
+ for (const root of roots) {
+ // The cap covers every copied directory together.
+ const next = await estimateWorkspace(
+ root,
+ scope.assertCurrent,
+ TASK_MIGRATION_MAX_FILES - estimate.fileCount,
+ );
+ estimate.fileCount += next.fileCount;
+ estimate.bytes += next.bytes;
+ }
scope.assertCurrent();
return { ...view(scope, null), estimate };
}
diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.ts
index 01f228c1df..93fc5f175d 100644
--- a/apps/desktop/src/main/task-migration/workspace.ts
+++ b/apps/desktop/src/main/task-migration/workspace.ts
@@ -15,34 +15,45 @@ const ESTIMATE_CONCURRENCY = 32;
const STAT_BATCH = 64;
/**
- * Top-level directory names a copy of `root` leaves behind: other tasks' Cindy worktrees.
- * Cindy only creates them inside Git repositories, so only a Git repository root (the same
- * verdict snapshotWorkspace's probe reaches) excludes them; a plain directory, including one
- * with stray `.git` metadata, keeps same-named folders. Callers skip directories, never files.
+ * Directories (relative to `root`) a copy leaves behind: other tasks' Cindy worktrees, i.e.
+ * linked worktrees Git has registered for this repository that live in a managed container
+ * (`.cindy-worktrees/<name>`). Anything else in those folders is ordinary project content,
+ * and a root that is not itself a repository root excludes nothing.
*/
-export async function excludedRootDirectories(root: string): Promise<string[]> {
+export async function managedWorktreeExclusions(root: string): Promise<string[]> {
+ let listing: string;
try {
+ root = await fs.realpath(root);
const probe = await gitExec(['rev-parse', '--show-toplevel'], root, {
extraEnv: { LC_ALL: 'C' },
});
- return (await fs.realpath(probe.stdout.trim())) === (await fs.realpath(root))
- ? [...MANAGED_WORKTREE_DIR_NAMES]
- : [];
+ if ((await fs.realpath(probe.stdout.trim())) !== root) return [];
+ listing = (await gitExec(['worktree', 'list', '--porcelain'], root)).stdout;
} catch (error) {
if (error instanceof GitExecError && error.stderr.includes('not a git repository')) return [];
throw error;
}
+ const excluded: string[] = [];
+ for (const line of listing.split('\n')) {
+ if (!line.startsWith('worktree ')) continue;
+ // A registered worktree whose directory is gone has nothing to copy or skip.
+ const worktree = await fs.realpath(line.slice('worktree '.length)).catch(() => null);
+ const relative = worktree && path.relative(root, worktree);
+ const parts = relative ? relative.split(path.sep) : [];
+ if (parts.length >= 2 && (MANAGED_WORKTREE_DIR_NAMES as readonly string[]).includes(parts[0]))
+ excluded.push(relative!);
+ }
+ return excluded;
}
-/** Whether `file` lies in one of `root`'s `excluded` top-level directories. */
+/** Whether `file` lies in (or is) one of `root`'s `excluded` relative directories. */
export function isExcludedFromWorkspace(
root: string,
file: string,
excluded: readonly string[],
): boolean {
const relative = path.relative(root, file);
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return false;
- return excluded.includes(relative.split(path.sep)[0]);
+ return excluded.some((entry) => relative === entry || relative.startsWith(entry + path.sep));
}
export interface PortableWorkspace {
@@ -121,7 +132,6 @@ export async function snapshotWorkspace(
root: string,
directory: string,
id: string,
- maxFiles?: number,
): Promise<PortableWorkspace> {
if ((await fs.lstat(root)).isSymbolicLink()) root = await fs.realpath(root);
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
@@ -170,9 +180,7 @@ export async function snapshotWorkspace(
encryptedKey: '',
iv: randomBytes(12),
maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),
- // `git` is set exactly when the probe above found `root` to be a repository root.
- excludeRootNames: git ? [...MANAGED_WORKTREE_DIR_NAMES] : [],
- maxFiles,
+ excludePaths: await managedWorktreeExclusions(root),
});
archive.files = Object.fromEntries(
Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),
@@ -292,7 +300,9 @@ export async function estimateWorkspace(
maxFiles = Number.POSITIVE_INFINITY,
): Promise<{ fileCount: number; bytes: number }> {
root = await fs.realpath(root);
- const excluded = await excludedRootDirectories(root);
+ const excluded = new Set(
+ (await managedWorktreeExclusions(root)).map((entry) => path.join(root, entry)),
+ );
const result = { fileCount: 0, bytes: 0 };
const pending = [root];
const visit = async (directory: string): Promise<void> => {
@@ -307,7 +317,7 @@ export async function estimateWorkspace(
? entry
: await fs.lstat(file);
if (kind.isDirectory()) {
- if (directory !== root || !excluded.includes(entry.name)) pending.push(file);
+ if (!excluded.has(file)) pending.push(file);
} else if (kind.isFile() || kind.isSymbolicLink()) {
// Count as each file is recognised, before any per-file work beyond the cap.
if (++result.fileCount > maxFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
index d9b852a973..8b0ab4cd4e 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
@@ -25,21 +25,18 @@ function restorableMode(mode: number): number {
return mode & (process.platform === 'win32' ? 0o666 : 0o777);
}
-/** `excludeRootNames` skips top-level directories (never files) — task copy leaves other tasks' worktrees behind.
- * `maxFiles` bounds files plus links, stopping the walk as soon as it is exceeded. */
-export async function inventoryWorktree(root: string, maxBytes?: number, excludeRootNames: readonly string[] = [], maxFiles?: number): Promise<Record<string, FileEvidence>> {
+/** `excludePaths` skips these root-relative directories (never files) — task copy leaves other tasks' worktrees behind. */
+export async function inventoryWorktree(root: string, maxBytes?: number, excludePaths: readonly string[] = []): Promise<Record<string, FileEvidence>> {
const files: Record<string, FileEvidence> = Object.create(null);
let bytes = 0;
- let count = 0;
const walk = async (directory: string): Promise<void> => {
for (const name of await fs.readdir(directory)) {
if (directory === root && name === '.git') continue;
const absolute = path.join(directory, name);
const stat = await fs.lstat(absolute);
- if (directory === root && stat.isDirectory() && excludeRootNames.includes(name)) continue;
const relative = path.relative(root, absolute);
+ if (stat.isDirectory() && excludePaths.includes(relative)) continue;
const mode = restorableMode(stat.mode);
- if (!stat.isDirectory() && maxFiles !== undefined && ++count > maxFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
if (stat.isSymbolicLink()) {
files[relative] = { kind: 'link', hash: await fs.readlink(absolute), mode };
} else if (stat.isDirectory()) {
@@ -133,8 +130,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, excludeRootNames: readonly string[] = [], maxFiles?: number): Promise<WorktreeRecoveryArchive> {
- const files = await inventoryWorktree(root, maxBytes, excludeRootNames, maxFiles);
+export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number, excludePaths: readonly string[] = []): Promise<WorktreeRecoveryArchive> {
+ const files = await inventoryWorktree(root, maxBytes, excludePaths);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;
await fs.mkdir(directory, { recursive: true });
@@ -153,7 +150,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, undefined, excludeRootNames, maxFiles), files)) throw new Error('worktree changed during archive');
+ if (!sameWorktreeFiles(await inventoryWorktree(root, undefined, excludePaths), 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 d7d3897c64..5ec155ed27 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; excludeRootNames?: string[]; maxFiles?: number }
+ | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number; excludePaths?: 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, task.excludeRootNames, task.maxFiles);
+ case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes, task.excludePaths);
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 ca00a84759..a42f80764e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
@@ -271,11 +271,7 @@ export function TaskMigrationDialog({
})
: t('taskMigration.estimating');
const errorKey =
- failure &&
- t(`taskMigration.errors.${failure}`, {
- defaultValue: t('taskMigration.failed'),
- limit: TASK_MIGRATION_MAX_FILES,
- });
+ failure && t(`taskMigration.errors.${failure}`, { defaultValue: t('taskMigration.failed') });
return (
<Dialog.Root
open
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 776570ae1d..7be3b54240 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -46,8 +46,7 @@
"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_TIMEOUT": "The source computer did not respond in time. Try again later.",
- "MIGRATION_TOO_MANY_FILES": "The project now has more than {{limit, number}} files, so copying stopped. Copy a project with fewer files instead."
+ "MIGRATION_TIMEOUT": "The source computer did not respond in time. Try again later."
},
"successTitle": "Copy successful",
"successDescription": "Copied to {{name}}.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 222426831f..3b8d8f90ee 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -46,8 +46,7 @@
"MIGRATION_UNSUPPORTED": "両方のコンピューターをタスクのコピーに対応したバージョンに更新してください。",
"MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。",
"MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。",
- "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。",
- "MIGRATION_TOO_MANY_FILES": "プロジェクトのファイルが {{limit, number}} 個を超えたため、コピーを中止しました。ファイル数の少ないプロジェクトをコピーしてください。"
+ "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。"
},
"successTitle": "コピー完了",
"successDescription": "{{name}}にコピーしました。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5310f79a0c..9b6ffb23a9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -46,8 +46,7 @@
"MIGRATION_UNSUPPORTED": "두 컴퓨터 모두 작업 복사을 지원하는 버전으로 업데이트하세요.",
"MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.",
"MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요.",
- "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요.",
- "MIGRATION_TOO_MANY_FILES": "프로젝트 파일이 {{limit, number}}개를 넘어 복사를 중단했습니다. 파일이 더 적은 프로젝트를 복사하세요."
+ "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요."
},
"successTitle": "복사 완료",
"successDescription": "{{name}}에 복사했습니다.",
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 45c9bdd380..344f9dfb29 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -46,8 +46,7 @@
"MIGRATION_UNSUPPORTED": "请将两台电脑更新至支持任务复制的版本。",
"MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。",
"MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。",
- "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。",
- "MIGRATION_TOO_MANY_FILES": "项目文件已超过 {{limit, number}} 个,已停止复制。请改为复制文件更少的项目。"
+ "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。"
},
"successTitle": "复制成功",
"successDescription": "已复制到{{name}}。",
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 acdce9b439..f80bed929a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -46,8 +46,7 @@
"MIGRATION_UNSUPPORTED": "請將兩台電腦更新至支援任務複製的版本。",
"MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。",
"MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。",
- "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。",
- "MIGRATION_TOO_MANY_FILES": "專案檔案已超過 {{limit, number}} 個,已停止複製。請改為複製檔案較少的專案。"
+ "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。"
},
"successTitle": "複製成功",
"successDescription": "已複製到{{name}}。",
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index a93587e13c..8dddf54321 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -17,9 +17,8 @@
不发布这次副本。该检查不冻结输入,也不承诺外部编辑器与数据库的跨进程原子快照。
复制是一次快照,不持续同步;源任务后续变化不会更新副本。快照遇到文件变化会失败并允许重试。
2. 复用任务分享导出、原生上下文恢复及 worktree 快照。包含未提交、未跟踪和忽略文件;
- Git 仓库根目录下其它任务的 Cindy 托管 worktree 目录(`.cindy-worktrees`,旧名 `.xdt-worktrees`)
- 不随副本复制,也不计入统计;在这些 worktree 里运行的任务不阻止复制。非 Git 目录中的同名文件夹
- 及任何同名文件照常复制。
+ 仓库已登记、位于 `.cindy-worktrees`(旧名 `.xdt-worktrees`)下的其它任务 worktree 不随副本复制,
+ 也不计入统计;在这些 worktree 里运行的任务不阻止复制。这些文件夹里的其它内容、非 Git 目录照常复制。
Git 保留 HEAD、暂存区和工作文件差别,不复制本机 Git 配置、hooks 或凭证。
目标始终创建独立目录,不覆盖已有项目。整组共享物理目录只复制一份,独立目录分别创建。
3. 复用 peer 直传及 OSS 回退、冷却。按实时磁盘和可用内存预算准备、发送、接收及解包,
@@ -30,8 +29,7 @@
Git 历史、任务对话与附件另行复制,不计入项目文件统计;统计完成前不能开始复制。
`copyEstimate` 能力存在时才调用 `estimate`;旧源端无法统计时明确提示连接/版本检查,不开始复制。
统计请求超时时提示项目文件过多,不提示连接/版本;项目文件超过 50 万个时提前停止统计,
- 提示改为复制文件更少的项目,不开始复制。开始快照前按同一上限重新统计一次,期间文件增长到
- 超限时停止复制并提示原因。
+ 提示改为复制文件更少的项目,不开始复制。该上限只是确认页的准入检查,复制本身仍不设总量上限。
6. 复制全程保留弹窗,不提供隐藏到后台的入口;准备阶段显示不定进度,发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。
OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。
文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。