Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(task-copy): 用 Git 实际判断决定排除,复制前复查文件数上限,未知条目类型回退 lstat
Dash32acb5ab113e
diff --git a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.tsindex ed1856fe28..45769e39fc 100644--- a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts+++ b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts@@ -2,6 +2,7 @@ import { expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';+import { execFileSync } from 'node:child_process';import { estimateWorkspace } from '../workspace';it('counts hidden and nested files, skips root Git metadata and does not count directories', async () => {@@ -32,9 +33,12 @@ it("skips other tasks' managed worktree directories only at a repository root",}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.+ // 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.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 });@@ -81,3 +85,27 @@ it('counts a wide, deep tree and stops once the file cap is exceeded', async ()await fs.rm(root, { recursive: true, force: true });}});++it('classifies entries of unknown type with lstat instead of rejecting them', async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));+ const readdir = fs.readdir.bind(fs);+ const unknown = vi.spyOn(fs, 'readdir').mockImplementation((async (+ directory: string,+ options: unknown,+ ) =>+ (await readdir(directory, options as { withFileTypes: true })).map((entry) => ({+ name: entry.name,+ isDirectory: () => false,+ isFile: () => false,+ isSymbolicLink: () => false,+ }))) as never);+ try {+ await fs.mkdir(path.join(root, 'sub'));+ await fs.writeFile(path.join(root, 'sub', 'file'), '12345');+ await fs.writeFile(path.join(root, 'top'), 'ab');+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 2, bytes: 7 });+ } finally {+ unknown.mockRestore();+ 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.tsindex 5f99170e2b..7a6e67e6fa 100644--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts@@ -2,6 +2,7 @@ vi.mock('../../mcp-integrations/moveSession', () => ({ moveSessionProjectFromHosimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import syncFs from 'node:fs';+import { execFileSync } from 'node:child_process';import path from 'node:path';import os from 'node:os';import { createHash } from 'node:crypto';@@ -41,6 +42,7 @@ 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),@@ -211,6 +213,7 @@ vi.mock('../workspace', async (original) => ({.excludedRootDirectories,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) => {@@ -270,6 +273,7 @@ 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');@@ -516,12 +520,19 @@ describe('resumable cross-computer copy', () => {const cwd = rows.get('fork')!.workingDir as string;const managed = path.join(cwd, '.cindy-worktrees', 'other');await fs.mkdir(managed, { recursive: true });- await fs.mkdir(path.join(cwd, '.git'));+ execFileSync('git', ['init', '-q', cwd]);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/service.ts b/apps/desktop/src/main/task-migration/service.tsindex 37c1855038..62a0621962 100644--- a/apps/desktop/src/main/task-migration/service.ts+++ b/apps/desktop/src/main/task-migration/service.ts@@ -327,6 +327,9 @@ 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'),@@ -371,6 +374,21 @@ 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,@@ -922,16 +940,7 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationVconst 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,- TASK_MIGRATION_MAX_FILES - estimate.fileCount,- );- estimate.fileCount += next.fileCount;- estimate.bytes += next.bytes;- }+ const estimate = await estimateRoots(scope, roots);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.tsindex 78109488c9..c5ced98535 100644--- a/apps/desktop/src/main/task-migration/workspace.ts+++ b/apps/desktop/src/main/task-migration/workspace.ts@@ -16,15 +16,20 @@ 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 a plain directory keeps same-named- * folders. Callers skip only directories with these names, never files.+ * 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.*/export async function excludedRootDirectories(root: string): Promise<string[]> {try {- await fs.lstat(path.join(root, '.git'));- return [...MANAGED_WORKTREE_DIR_NAMES];+ 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]+ : [];} catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];+ if (error instanceof GitExecError && error.stderr.includes('not a git repository')) return [];throw error;}}@@ -164,7 +169,8 @@ export async function snapshotWorkspace(encryptedKey: '',iv: randomBytes(12),maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),- excludeRootNames: await excludedRootDirectories(root),+ // `git` is set exactly when the probe above found `root` to be a repository root.+ excludeRootNames: git ? [...MANAGED_WORKTREE_DIR_NAMES] : [],});archive.files = Object.fromEntries(Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),@@ -293,9 +299,14 @@ export async function estimateWorkspace(check();if (directory === root && entry.name === '.git') continue;const file = path.join(directory, entry.name);- if (entry.isDirectory()) {+ // Some filesystems (e.g. network mounts) report DT_UNKNOWN; classify those with lstat.+ const kind =+ entry.isDirectory() || entry.isFile() || entry.isSymbolicLink()+ ? entry+ : await fs.lstat(file);+ if (kind.isDirectory()) {if (directory !== root || !excluded.includes(entry.name)) pending.push(file);- } else if (entry.isFile() || entry.isSymbolicLink()) files.push(file);+ } else if (kind.isFile() || kind.isSymbolicLink()) files.push(file);else throw new Error('MIGRATION_NONPORTABLE_PATH');}// Count before stat so an oversized directory stops without statting every entry.diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsxindex a42f80764e..ca00a84759 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx@@ -271,7 +271,11 @@ export function TaskMigrationDialog({}): t('taskMigration.estimating');const errorKey =- failure && t(`taskMigration.errors.${failure}`, { defaultValue: t('taskMigration.failed') });+ failure &&+ t(`taskMigration.errors.${failure}`, {+ defaultValue: t('taskMigration.failed'),+ limit: TASK_MIGRATION_MAX_FILES,+ });return (<Dialog.Rootopendiff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7be3b54240..776570ae1d 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -46,7 +46,8 @@"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_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."},"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.jsonindex 3b8d8f90ee..222426831f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -46,7 +46,8 @@"MIGRATION_UNSUPPORTED": "両方のコンピューターをタスクのコピーに対応したバージョンに更新してください。","MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。","MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。",- "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。"+ "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。",+ "MIGRATION_TOO_MANY_FILES": "プロジェクトのファイルが {{limit, number}} 個を超えたため、コピーを中止しました。ファイル数の少ないプロジェクトをコピーしてください。"},"successTitle": "コピー完了","successDescription": "{{name}}にコピーしました。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 9b6ffb23a9..5310f79a0c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -46,7 +46,8 @@"MIGRATION_UNSUPPORTED": "두 컴퓨터 모두 작업 복사을 지원하는 버전으로 업데이트하세요.","MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.","MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요.",- "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요."+ "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요.",+ "MIGRATION_TOO_MANY_FILES": "프로젝트 파일이 {{limit, number}}개를 넘어 복사를 중단했습니다. 파일이 더 적은 프로젝트를 복사하세요."},"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.jsonindex 344f9dfb29..45c9bdd380 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -46,7 +46,8 @@"MIGRATION_UNSUPPORTED": "请将两台电脑更新至支持任务复制的版本。","MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。","MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。",- "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。"+ "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。",+ "MIGRATION_TOO_MANY_FILES": "项目文件已超过 {{limit, number}} 个,已停止复制。请改为复制文件更少的项目。"},"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.jsonindex f80bed929a..acdce9b439 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -46,7 +46,8 @@"MIGRATION_UNSUPPORTED": "請將兩台電腦更新至支援任務複製的版本。","MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。","MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。",- "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。"+ "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。",+ "MIGRATION_TOO_MANY_FILES": "專案檔案已超過 {{limit, number}} 個,已停止複製。請改為複製檔案較少的專案。"},"successTitle": "複製成功","successDescription": "已複製到{{name}}。",diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.mdindex 9c2450ea10..a93587e13c 100644--- a/docs/product-rules/task-device-migration.md+++ b/docs/product-rules/task-device-migration.md@@ -30,7 +30,8 @@Git 历史、任务对话与附件另行复制,不计入项目文件统计;统计完成前不能开始复制。`copyEstimate` 能力存在时才调用 `estimate`;旧源端无法统计时明确提示连接/版本检查,不开始复制。统计请求超时时提示项目文件过多,不提示连接/版本;项目文件超过 50 万个时提前停止统计,- 提示改为复制文件更少的项目,不开始复制。+ 提示改为复制文件更少的项目,不开始复制。开始快照前按同一上限重新统计一次,期间文件增长到+ 超限时停止复制并提示原因。6. 复制全程保留弹窗,不提供隐藏到后台的入口;准备阶段显示不定进度,发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。