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): 项目内链接链与断开链接照常复制,个别问题条目跳过并在完成时列出 (#5373)

Dash5d844b411df4
diff --git a/apps/desktop/src/main/task-migration/__tests__/portableEntries.test.ts b/apps/desktop/src/main/task-migration/__tests__/portableEntries.test.ts
new file mode 100644
index 0000000000..57ef2aeb0d
--- /dev/null
+++ b/apps/desktop/src/main/task-migration/__tests__/portableEntries.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest';
+import type { FileEvidence } from '../../worktree/recoveryArchiveIO';
+import { selectPortableEntries } from '../portableEntries';
+
+const dir: FileEvidence = { kind: 'directory', mode: 0o755, hash: '' };
+const file: FileEvidence = { kind: 'file', mode: 0o644, hash: 'a'.repeat(64) };
+const link = (target: string): FileEvidence => ({ kind: 'link', mode: 0o777, hash: target });
+const select = (files: Record<string, FileEvidence>, unsupported: string[] = []) =>
+ selectPortableEntries(files, unsupported, '/');
+
+describe('selectPortableEntries', () => {
+ it('keeps framework-style link chains and links into a missing build output', () => {
+ // The CocoaPods layout that used to block a copy outright.
+ const files = {
+ Fw: dir,
+ 'Fw/Versions': dir,
+ 'Fw/Versions/A': dir,
+ 'Fw/Versions/A/Headers': dir,
+ 'Fw/Versions/A/Headers/x.h': file,
+ 'Fw/Versions/Current': link('A'),
+ 'Fw/Headers': link('Versions/Current/Headers'),
+ Pods: dir,
+ 'Pods/gen.h': link('../build/generated/gen.h'),
+ };
+ expect(select(files)).toEqual({ files, skipped: [] });
+ });
+
+ it('refuses only links whose resolution leaves the root or reaches .git', () => {
+ const { files, skipped } = select({
+ a: dir,
+ 'a/up': link('..'),
+ 'a/escape': link('up/../outside'),
+ 'a/chain': link('escape'),
+ 'a/hop': link('../a/up'),
+ 'a/via-hop': link('hop/x'),
+ 'a/inside': link('up/a'),
+ 'a/absolute': link('/etc/passwd'),
+ 'a/drive': link('C:/x'),
+ 'a/git': link('../.git/config'),
+ 'a/loop': link('loop2'),
+ 'a/loop2': link('loop'),
+ });
+ // Chains that stay inside are kept, including one that only dangles at the end.
+ expect(Object.keys(files)).toEqual(['a', 'a/up', 'a/hop', 'a/via-hop', 'a/inside']);
+ expect(skipped).toEqual(
+ ['a/escape', 'a/chain', 'a/absolute', 'a/drive', 'a/git', 'a/loop', 'a/loop2'].map(
+ (path) => ({ path, code: 'MIGRATION_EXTERNAL_LINK' }),
+ ),
+ );
+ });
+
+ it('reports a skipped directory once and leaves its subtree behind', () => {
+ const { files, skipped } = select(
+ {
+ 'bad ': dir,
+ 'bad /inner': file,
+ 'bad /deeper': dir,
+ 'bad /deeper/x': file,
+ Readme: file,
+ README: file,
+ 'into-bad': link('bad /inner'),
+ },
+ ['dev.sock'],
+ );
+ expect(Object.keys(files)).toEqual(['Readme', 'into-bad']);
+ expect(skipped).toEqual([
+ { path: 'dev.sock', code: 'MIGRATION_UNSUPPORTED_ENTRY' },
+ { path: 'bad ', code: 'MIGRATION_NONPORTABLE_PATH' },
+ { path: 'README', code: 'MIGRATION_PATH_COLLISION' },
+ ]);
+ });
+
+ it('decides parents first, so a skipped folder never costs the kept one its files', () => {
+ const { files, skipped } = select(
+ { foo: dir, Foo: dir, 'Foo/x': file, 'foo/x': file, 'Foo/up': link('../..') },
+ ['Foo/pipe'],
+ );
+ expect(Object.keys(files)).toEqual(['foo', 'foo/x']);
+ expect(skipped).toEqual([{ path: 'Foo', code: 'MIGRATION_PATH_COLLISION' }]);
+ });
+
+ it('treats a link into a skipped folder as dangling, not external', () => {
+ const { files, skipped } = select({
+ 'bad ': dir,
+ 'bad /up': link('../..'),
+ via: link('bad /up/x'),
+ });
+ expect(Object.keys(files)).toEqual(['via']);
+ expect(skipped).toEqual([{ path: 'bad ', code: 'MIGRATION_NONPORTABLE_PATH' }]);
+ });
+
+ it('resolves links case-insensitively, as a folding target filesystem would', () => {
+ const { files, skipped } = select({ a: dir, 'a/up': link('../..'), sneaky: link('A/UP/x') });
+ expect(Object.keys(files)).toEqual(['a']);
+ expect(skipped.map((entry) => entry.path)).toEqual(['a/up', 'sneaky']);
+ });
+
+ it('accepts platform separators and returns the original keys', () => {
+ const { files, skipped } = selectPortableEntries(
+ { a: dir, 'a\\b': file, 'a\\c': link('b') },
+ ['a\\pipe'],
+ '\\',
+ );
+ expect(Object.keys(files)).toEqual(['a', 'a\\b', 'a\\c']);
+ expect(skipped).toEqual([{ path: 'a/pipe', code: 'MIGRATION_UNSUPPORTED_ENTRY' }]);
+ });
+
+ it('still treats a malformed manifest as corruption', () => {
+ expect(() => select({ x: { kind: 'file', mode: 0o644, hash: 'nope' } })).toThrow(
+ 'MIGRATION_INVALID_MANIFEST',
+ );
+ expect(() => select({ 'missing/child': file })).toThrow('MIGRATION_INVALID_MANIFEST');
+ expect(() => select({ l: link('.'), 'l/child': file })).toThrow('MIGRATION_INVALID_MANIFEST');
+ });
+});
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 5d064e9a48..aeeb5589ee 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -45,6 +45,8 @@ const state = vi.hoisted(() => ({
estimateLimits: [] as number[],
timeoutAction: '' as string,
exclusions: [] as string[],
+ /** Entries each snapshot reports it left behind. */
+ skipped: [] as Array<{ path: string; code: string }>,
migrationWarn: vi.fn(),
/** Native transcript the export streams beside the package when the target supports it. */
transcript: '' as string,
@@ -275,7 +277,11 @@ vi.mock('../workspace', async (original) => ({
state.snapshot();
await fs.mkdir(directory, { recursive: true });
await fs.copyFile(path.join(source, 'draft'), path.join(directory, 'a.tar.gz.enc'));
- return { unpackedBytes: 8, archive: { file: 'a.tar.gz.enc', files: {} } };
+ return {
+ unpackedBytes: 8,
+ archive: { file: 'a.tar.gz.enc', files: {} },
+ skipped: state.skipped,
+ };
},
restoreWorkspace: async (_manifest: unknown, directory: string, target: string) => {
await fs.copyFile(path.join(directory, 'a.tar.gz.enc'), path.join(target, 'draft'));
@@ -317,6 +323,7 @@ describe('resumable cross-computer copy', () => {
state.imports.mockClear();
state.created.mockReset();
state.snapshot.mockClear();
+ state.skipped = [];
state.close.mockClear();
state.remove.mockReset();
state.loseReply = '';
@@ -861,6 +868,19 @@ describe('resumable cross-computer copy', () => {
expect((await settled()).stage).toBe('complete');
expect(state.imports).toHaveBeenCalledTimes(1);
});
+ it('finishes despite skipped entries and reports them until the next copy', async () => {
+ state.skipped = [{ path: 'Pods/out.h', code: 'MIGRATION_EXTERNAL_LINK' }];
+ await start();
+ const first = await settled();
+ expect(first.stage).toBe('complete');
+ expect(first.error).toBeUndefined();
+ expect(first.skipped).toEqual({ total: 1, entries: state.skipped });
+ state.skipped = [];
+ await start();
+ const second = await settled();
+ expect(second.stage).toBe('complete');
+ expect(second.skipped).toBeUndefined();
+ });
it('allows another independent copy after completion', async () => {
await start();
const first = await settled();
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 06f3e68daa..66ab266355 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
@@ -101,6 +101,55 @@ describe('cross-machine project snapshots', () => {
await fs.writeFile(path.join(target, 'draft'), 'new machine edit');
expect(await fs.readFile(path.join(source, 'draft'), 'utf8')).toBe('uncommitted\n');
});
+ it('copies link chains, dangling links and modes, leaving external links behind', async () => {
+ // The CocoaPods / framework layout that used to block the whole copy.
+ await fs.mkdir(path.join(source, 'Fw', 'Versions', 'A', 'Headers'), { recursive: true });
+ await fs.writeFile(path.join(source, 'Fw', 'Versions', 'A', 'Headers', 'x.h'), 'x');
+ await fs.symlink('A', path.join(source, 'Fw', 'Versions', 'Current'), 'dir');
+ await fs.symlink('Versions/Current/Headers', path.join(source, 'Fw', 'Headers'), 'dir');
+ await fs.mkdir(path.join(source, 'Pods'));
+ await fs.symlink('../build/generated/gen.h', path.join(source, 'Pods', 'gen.h'));
+ // Archived after the link it passes through, which tar alone refuses to extract.
+ await fs.symlink('Fw/Versions', path.join(source, 'alias'), 'dir');
+ await fs.symlink('alias/Current/Headers/x.h', path.join(source, 'via'));
+ // Xcode leaves world-writable folders; the restore must not narrow them by the local umask.
+ await fs.mkdir(path.join(source, 'shared'));
+ await fs.writeFile(path.join(source, 'shared', 'open'), 'x');
+ await fs.chmod(path.join(source, 'shared'), 0o777);
+ await fs.chmod(path.join(source, 'shared', 'open'), 0o666);
+ await fs.symlink('../outside', path.join(source, 'out'));
+ const before = await inventoryWorktree(source);
+
+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
+ expect(snapshot.skipped).toEqual([{ path: 'out', code: 'MIGRATION_EXTERNAL_LINK' }]);
+ await restoreWorkspace(snapshot, artifacts, target);
+
+ const expected = { ...before };
+ delete expected.out;
+ expect({ ...(await inventoryWorktree(target)) }).toEqual(expected);
+ expect(await fs.readFile(path.join(target, 'Fw', 'Headers', 'x.h'), 'utf8')).toBe('x');
+ expect(await fs.readFile(path.join(target, 'via'), 'utf8')).toBe('x');
+ expect(await fs.readlink(path.join(target, 'Pods', 'gen.h'))).toBe('../build/generated/gen.h');
+ });
+ // symlink-platform-skip: Windows cannot create a FIFO or a directory name ending in a space.
+ it.skipIf(process.platform === 'win32')(
+ 'leaves special files and unportable names behind and reports them',
+ async () => {
+ await fs.writeFile(path.join(source, 'kept'), 'x');
+ await fs.mkdir(path.join(source, 'trailing '));
+ await fs.writeFile(path.join(source, 'trailing ', 'inner'), 'x');
+ await fs.symlink('trailing /inner', path.join(source, 'into-skipped'));
+ await exec('mkfifo', [path.join(source, 'pipe')]);
+
+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
+ expect([...snapshot.skipped].sort((a, b) => a.path.localeCompare(b.path))).toEqual([
+ { path: 'pipe', code: 'MIGRATION_UNSUPPORTED_ENTRY' },
+ { path: 'trailing ', code: 'MIGRATION_NONPORTABLE_PATH' },
+ ]);
+ await restoreWorkspace(snapshot, artifacts, target);
+ expect((await fs.readdir(target)).sort()).toEqual(['into-skipped', 'kept']);
+ },
+ );
it('restores linked worktrees with HEAD, staged changes, unstaged changes and ignored files intact', async () => {
await git(source, 'init', '-b', 'main');
await git(source, 'config', 'user.name', 'Migration test');
diff --git a/apps/desktop/src/main/task-migration/handoff.ts b/apps/desktop/src/main/task-migration/handoff.ts
index c67deb5c1b..154b217372 100644
--- a/apps/desktop/src/main/task-migration/handoff.ts
+++ b/apps/desktop/src/main/task-migration/handoff.ts
@@ -1,3 +1,5 @@
+import type { SkippedEntry } from './portableEntries';
+
/** Resumable copy progress. The source task is never retired. */
export type MigrationStage = 'preparing' | 'transferring' | 'complete' | 'cancelled';
export interface MigrationHandoff {
@@ -16,6 +18,8 @@ export interface MigrationHandoff {
errorPath?: string;
/** Bytes needed vs the limit, when `error` is a size failure. */
errorSize?: { needed: number; limit: number };
+ /** Entries the prepared copy leaves behind; `entries` is capped, `total` is not. */
+ skipped?: { total: number; entries: SkippedEntry[] };
}
export interface HandoffDependencies {
save(record: MigrationHandoff): Promise<void>;
diff --git a/apps/desktop/src/main/task-migration/portableEntries.ts b/apps/desktop/src/main/task-migration/portableEntries.ts
new file mode 100644
index 0000000000..90a1bf4966
--- /dev/null
+++ b/apps/desktop/src/main/task-migration/portableEntries.ts
@@ -0,0 +1,150 @@
+import path from 'node:path';
+import type { FileEvidence } from '../worktree/recoveryArchiveIO';
+
+/** Why one project entry was left out of a task copy. */
+export type SkipCode =
+ | 'MIGRATION_NONPORTABLE_PATH'
+ | 'MIGRATION_PATH_COLLISION'
+ | 'MIGRATION_EXTERNAL_LINK'
+ | 'MIGRATION_UNSUPPORTED_ENTRY';
+/** `path` is project-relative and `/`-separated; a skipped directory stands for its whole subtree. */
+export interface SkippedEntry {
+ path: string;
+ code: SkipCode;
+}
+
+// Same bound as POSIX SYMLOOP_MAX on common systems.
+const MAX_LINK_HOPS = 40;
+
+function nonportable(name: string): boolean {
+ const parts = name.split('/');
+ return (
+ !name ||
+ name.length > 4096 ||
+ name.includes('\\') ||
+ parts.some(
+ (part) =>
+ !part ||
+ part === '.' ||
+ part === '..' ||
+ part.toLowerCase() === '.git' ||
+ // eslint-disable-next-line no-control-regex -- control characters are not portable names.
+ /[\x00-\x1f:*?"<>|]/.test(part) ||
+ /[ .]$/.test(part) ||
+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part),
+ )
+ );
+}
+
+function unsafeLinkText(target: string): boolean {
+ return (
+ !target || target.includes('\\') || path.posix.isAbsolute(target) || /^[a-z]:/i.test(target)
+ );
+}
+
+/** Case- and normalization-insensitive key: the target filesystem may fold either way. */
+const fold = (name: string) => name.normalize('NFC').toLowerCase();
+
+function ancestorsOf(name: string): string[] {
+ const parts = name.split('/');
+ return parts.slice(0, -1).map((_, index) => parts.slice(0, index + 1).join('/'));
+}
+
+/**
+ * Resolve `link` the way the filesystem would, following links through `folded` (kept
+ * entries by `fold`ed path, so a case variant cannot slip past a link on a folding target).
+ * Inside means every step stays under the root and never touches `.git`; a missing
+ * component is fine (a dangling link cannot reach anything), so it continues lexically.
+ */
+function linkStaysInside(folded: Map<string, FileEvidence>, link: string): boolean {
+ const resolved = link.split('/').slice(0, -1);
+ let pending = folded.get(fold(link))!.hash.split('/');
+ let hops = 0;
+ while (pending.length) {
+ const part = pending.shift()!;
+ if (!part || part === '.') continue;
+ if (part === '..') {
+ if (!resolved.length) return false;
+ resolved.pop();
+ continue;
+ }
+ if (part.toLowerCase() === '.git') return false;
+ resolved.push(part);
+ const entry = folded.get(fold(resolved.join('/')));
+ if (entry?.kind !== 'link') continue;
+ if (++hops > MAX_LINK_HOPS || unsafeLinkText(entry.hash)) return false;
+ resolved.pop();
+ pending = [...entry.hash.split('/'), ...pending];
+ }
+ return true;
+}
+
+function assertEvidence(entry: FileEvidence | undefined): void {
+ if (
+ !entry ||
+ !['file', 'directory', 'link'].includes(entry.kind) ||
+ !Number.isInteger(entry.mode) ||
+ entry.mode < 0 ||
+ entry.mode > 0o777 ||
+ typeof entry.hash !== 'string' ||
+ (entry.kind === 'file' && !/^[a-f0-9]{64}$/.test(entry.hash)) ||
+ (entry.kind === 'directory' && entry.hash !== '')
+ )
+ throw new Error('MIGRATION_INVALID_MANIFEST');
+}
+
+/**
+ * Split a workspace inventory into what a copy can carry and what it leaves behind.
+ * Keys may use the platform separator; kept keys are returned unchanged. Only links whose
+ * resolution leaves the root are refused — chains and dangling links inside it are copied
+ * as they are. A malformed manifest still throws: that is corruption, not a project entry.
+ */
+export function selectPortableEntries(
+ files: Record<string, FileEvidence>,
+ unsupported: readonly string[] = [],
+ separator = path.sep,
+): { files: Record<string, FileEvidence>; skipped: SkippedEntry[] } {
+ const posix = (name: string) => (separator === '/' ? name : name.split(separator).join('/'));
+ const byPosix: Record<string, FileEvidence> = Object.create(null);
+ for (const [name, entry] of Object.entries(files)) {
+ assertEvidence(entry);
+ byPosix[posix(name)] = entry;
+ }
+ const reason = new Map<string, SkipCode>();
+ // A skipped directory takes its subtree with it: those entries are neither kept nor reported.
+ const dropped = (name: string) => ancestorsOf(name).some((ancestor) => reason.has(ancestor));
+ // Parents decide first, so a skipped directory's subtree never competes with what is kept.
+ const byDepth = Object.keys(byPosix).sort((a, b) => a.split('/').length - b.split('/').length);
+ const folded = new Map<string, FileEvidence>();
+ for (const name of byDepth) {
+ if (dropped(name)) continue;
+ if (nonportable(name)) reason.set(name, 'MIGRATION_NONPORTABLE_PATH');
+ else if (folded.has(fold(name))) reason.set(name, 'MIGRATION_PATH_COLLISION');
+ else folded.set(fold(name), byPosix[name]);
+ }
+ // Resolve links against what the target will hold; a link into a skipped entry just dangles.
+ for (const name of byDepth) {
+ const entry = byPosix[name];
+ if (entry.kind !== 'link' || reason.has(name) || dropped(name)) continue;
+ if (unsafeLinkText(entry.hash) || !linkStaysInside(folded, name))
+ reason.set(name, 'MIGRATION_EXTERNAL_LINK');
+ }
+ const skipped: SkippedEntry[] = unsupported
+ .map(posix)
+ .filter((name) => !dropped(name))
+ .map((name) => ({ path: name, code: 'MIGRATION_UNSUPPORTED_ENTRY' }));
+ const kept: Record<string, FileEvidence> = Object.create(null);
+ for (const [name, entry] of Object.entries(files)) {
+ const relative = posix(name);
+ if (dropped(relative)) continue;
+ const code = reason.get(relative);
+ if (code) {
+ skipped.push({ path: relative, code });
+ continue;
+ }
+ if (ancestorsOf(relative).some((ancestor) => byPosix[ancestor]?.kind !== 'directory'))
+ throw new Error('MIGRATION_INVALID_MANIFEST');
+ kept[name] = entry;
+ }
+ return { files: kept, skipped };
+}
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index 4c547237ad..1e17138c0a 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -73,10 +73,13 @@ import {
MigrationSizeError,
} from './resources';
import { sendParts, receiveParts } from './transferParts';
+import type { SkippedEntry } from './portableEntries';
const log = createLogger('task-migration');
/** Native transcripts this large travel as separate streamed files, not inside the package. */
const EXTERNAL_TRANSCRIPT_MIN_BYTES = 32 * 1024 * 1024;
+/** The finished copy lists this many left-behind entries; the count covers the rest. */
+const MAX_REPORTED_SKIPPED = 100;
type MoveProject = (
sessionId: string,
@@ -208,6 +211,7 @@ function view(scope: Scope, record: MigrationRecord | null): TaskMigrationView {
targetSessionId: record.targetSessionId,
...(record.error ? { error: record.error } : {}),
...(record.error && record.errorPath ? { errorPath: record.errorPath } : {}),
+ ...(record.skipped ? { skipped: record.skipped } : {}),
...(record.error &&
record.errorSize &&
Number.isSafeInteger(record.errorSize.needed) &&
@@ -418,10 +422,26 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
if ((result.externalTranscripts?.length ?? 0) > TASK_MIGRATION_MAX_TRANSCRIPTS)
throw new Error('MIGRATION_NO_MEMORY');
const snapshots: PortableWorkspace[] = [];
- for (const [index, dir] of sourceKeys.entries())
- snapshots.push(
- await snapshotWorkspace(dir, workspaceDirectory(directory, index), record.id),
+ const skipped: SkippedEntry[] = [];
+ for (const [index, dir] of sourceKeys.entries()) {
+ const { skipped: left, ...snapshot } = await snapshotWorkspace(
+ dir,
+ workspaceDirectory(directory, index),
+ record.id,
);
+ snapshots.push(snapshot);
+ // Other members' worktrees are named by folder; the task's own paths stay project-relative.
+ for (const entry of left)
+ skipped.push(index ? { ...entry, path: `${path.basename(dir)}/${entry.path}` } : entry);
+ }
+ if (skipped.length)
+ log.warn('task copy leaves entries behind', {
+ copyId: record.id,
+ count: skipped.length,
+ });
+ record.skipped = skipped.length
+ ? { total: skipped.length, entries: skipped.slice(0, MAX_REPORTED_SKIPPED) }
+ : undefined;
// 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();
diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.ts
index b925093acd..0f4ec71c2f 100644
--- a/apps/desktop/src/main/task-migration/workspace.ts
+++ b/apps/desktop/src/main/task-migration/workspace.ts
@@ -11,6 +11,7 @@ import {
import { gitExec, GitExecError } from '../worktree/gitExec';
import { assertDiskCapacity } from './resources';
import { MANAGED_WORKTREE_DIR_NAMES } from '../../shared/managedWorktreePaths';
+import { selectPortableEntries, type SkippedEntry } from './portableEntries';
const ESTIMATE_CONCURRENCY = 32;
const STAT_BATCH = 64;
@@ -81,66 +82,11 @@ export class MigrationPathError extends Error {
}
}
-/** Portable names only. In particular, links must never lead extraction outside its new root. */
+/** Target-side guard: a received manifest must already be portable (the source leaves the rest
+ * behind). Links may chain or dangle, but must never resolve outside the new root. */
export function validateWorkspaceEntries(files: Record<string, FileEvidence>): void {
- const folded = new Set<string>();
-
- for (const [name, entry] of Object.entries(files)) {
- const parts = name.split('/');
- if (
- !name ||
- name.length > 4096 ||
- name.includes('\\') ||
- parts.some(
- (part) =>
- !part ||
- part === '.' ||
- part === '..' ||
- part.toLowerCase() === '.git' ||
- /[\x00-\x1f:*?"<>|]/.test(part) ||
- /[ .]$/.test(part) ||
- /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part),
- )
- ) {
- throw new MigrationPathError('MIGRATION_NONPORTABLE_PATH', name);
- }
- const key = name.normalize('NFC').toLowerCase();
- if (folded.has(key)) throw new MigrationPathError('MIGRATION_PATH_COLLISION', name);
- folded.add(key);
- if (
- !entry ||
- !['file', 'directory', 'link'].includes(entry.kind) ||
- !Number.isInteger(entry.mode) ||
- entry.mode < 0 ||
- entry.mode > 0o777 ||
- typeof entry.hash !== 'string'
- )
- throw new Error('MIGRATION_INVALID_MANIFEST');
- if (entry.kind === 'file' && !/^[a-f0-9]{64}$/.test(entry.hash))
- throw new Error('MIGRATION_INVALID_MANIFEST');
- if (entry.kind === 'directory' && entry.hash !== '')
- throw new Error('MIGRATION_INVALID_MANIFEST');
- if (entry.kind === 'link') {
- if (
- !entry.hash ||
- entry.hash.includes('\\') ||
- path.posix.isAbsolute(entry.hash) ||
- /^[a-z]:/i.test(entry.hash)
- )
- throw new MigrationPathError('MIGRATION_EXTERNAL_LINK', name);
- const target = path.posix.normalize(path.posix.join(path.posix.dirname(name), entry.hash));
- if (target === '..' || target.startsWith('../') || target.split('/').includes('.git'))
- throw new MigrationPathError('MIGRATION_EXTERNAL_LINK', name);
- // Do not accept a link chain or a directory-link ancestor during extraction.
- const targetEntry = files[target];
- if (!targetEntry || targetEntry.kind === 'link')
- throw new MigrationPathError('MIGRATION_EXTERNAL_LINK', name);
- }
- for (let i = 1; i < parts.length; i++) {
- if (files[parts.slice(0, i).join('/')]?.kind !== 'directory')
- throw new Error('MIGRATION_INVALID_MANIFEST');
- }
- }
+ const [first] = selectPortableEntries(files, [], '/').skipped;
+ if (first) throw new MigrationPathError(first.code, first.path);
}
/** No checkout, reset, stash, or source deletion. Existing recovery code preserves ignored bytes too;
@@ -149,7 +95,7 @@ export async function snapshotWorkspace(
root: string,
directory: string,
id: string,
-): Promise<PortableWorkspace> {
+): Promise<PortableWorkspace & { skipped: SkippedEntry[] }> {
if ((await fs.lstat(root)).isSymbolicLink()) root = await fs.realpath(root);
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
let git: PortableWorkspace['git'];
@@ -195,7 +141,7 @@ export async function snapshotWorkspace(
const key = randomBytes(32);
try {
const space = await fs.statfs(directory);
- const archive = await runRecoveryArchiveTask({
+ const { skipped = [], ...archive } = await runRecoveryArchiveTask({
operation: 'create',
root,
directory,
@@ -205,6 +151,7 @@ export async function snapshotWorkspace(
iv: randomBytes(12),
maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),
excludePaths: await managedWorktreeExclusions(root),
+ portable: true,
});
archive.files = Object.fromEntries(
Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),
@@ -223,6 +170,7 @@ export async function snapshotWorkspace(
key: key.toString('base64'),
unpackedBytes,
...(git ? { git } : {}),
+ skipped: skipped as SkippedEntry[],
};
} catch (error) {
if (error instanceof Error && error.message.includes('MIGRATION_FILE_TOO_LARGE'))
@@ -280,6 +228,7 @@ export async function restoreWorkspace(
keep: false,
key: new Uint8Array(key),
maxBytes: snapshot.unpackedBytes,
+ exactCopy: true,
});
} finally {
key.fill(0);
@@ -346,7 +295,8 @@ export async function estimateWorkspace(
// 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');
files.push(file);
- } else throw new Error('MIGRATION_NONPORTABLE_PATH');
+ }
+ // Sockets, FIFOs and devices are left behind by the copy, so they are not counted.
}
for (let index = 0; index < files.length; index += STAT_BATCH) {
check();
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
index 8b0ab4cd4e..8e0759fae2 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
@@ -1,5 +1,5 @@
import { createCipheriv, createDecipheriv, createHash, randomUUID } from 'node:crypto';
-import { createReadStream, createWriteStream } from 'node:fs';
+import { createReadStream, createWriteStream, type Stats } from 'node:fs';
import fs from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
@@ -25,8 +25,9 @@ function restorableMode(mode: number): number {
return mode & (process.platform === 'win32' ? 0o666 : 0o777);
}
-/** `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>> {
+/** `excludePaths` skips these root-relative directories (never files) — task copy leaves other tasks' worktrees behind.
+ * Sockets, FIFOs and devices throw unless `unsupported` collects their relative paths instead. */
+export async function inventoryWorktree(root: string, maxBytes?: number, excludePaths: readonly string[] = [], unsupported?: string[]): Promise<Record<string, FileEvidence>> {
const files: Record<string, FileEvidence> = Object.create(null);
let bytes = 0;
const walk = async (directory: string): Promise<void> => {
@@ -48,6 +49,8 @@ export async function inventoryWorktree(root: string, maxBytes?: number, exclude
const hash = createHash('sha256');
for await (const chunk of createReadStream(absolute)) hash.update(chunk);
files[relative] = { kind: 'file', hash: hash.digest('hex'), mode };
+ } else if (unsupported) {
+ unsupported.push(relative);
} else {
throw new Error('worktree contains an unsupported filesystem entry');
}
@@ -130,8 +133,17 @@ 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, excludePaths: readonly string[] = []): Promise<WorktreeRecoveryArchive> {
- const files = await inventoryWorktree(root, maxBytes, excludePaths);
+export interface ArchiveSelection {
+ files: Record<string, FileEvidence>;
+ skipped: Array<{ path: string; code: string }>;
+}
+
+/** `select` narrows what is packed (task copy leaves non-portable entries behind and reports them). */
+export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number, excludePaths: readonly string[] = [], select?: (files: Record<string, FileEvidence>, unsupported: string[]) => ArchiveSelection): Promise<WorktreeRecoveryArchive & { skipped?: ArchiveSelection['skipped'] }> {
+ const unsupported = select ? [] as string[] : undefined;
+ const inventory = await inventoryWorktree(root, maxBytes, excludePaths, unsupported);
+ const selection = select?.(inventory, unsupported!);
+ const files = selection?.files ?? inventory;
const cipher = createCipheriv('aes-256-gcm', key, iv);
const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;
await fs.mkdir(directory, { recursive: true });
@@ -150,21 +162,55 @@ 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, excludePaths), files)) throw new Error('worktree changed during archive');
- return archive;
+ if (!sameWorktreeFiles(await inventoryWorktree(root, undefined, excludePaths, unsupported && []), inventory)) throw new Error('worktree changed during archive');
+ return selection ? { ...archive, skipped: selection.skipped } : archive;
} catch (error) {
await fs.rm(target, { force: true });
throw error;
}
}
-/** Authenticate first; keep mode fills only missing bytes of a verified partial restore. */
-export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep: boolean, directory: string, key: Uint8Array, maxBytes?: number): Promise<void> {
+/** Authenticate first; keep mode fills only missing bytes of a verified partial restore.
+ * `exactCopy` (task copy to another computer) creates symbolic links from the verified inventory
+ * after every file and directory — tar refuses a link whose target crosses an already-extracted
+ * link, so chains would depend on archive order — then restores archived modes the local umask
+ * narrowed. Every parent is a verified directory; creating a link never writes through it. */
+export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep: boolean, directory: string, key: Uint8Array, maxBytes?: number, exactCopy = false): Promise<void> {
await verifyRecoveryArchive(archive, directory, key, maxBytes);
+ const skipLinks = (_path: string, entry: tar.ReadEntry | Stats) => !('type' in entry && entry.type === 'SymbolicLink');
await pipeline(
createReadStream(archivePath(directory, archive)), decryptArchive(archive, key),
- tar.x({ cwd: staging, strict: true, preservePaths: false, unlink: !keep, keep }),
+ tar.x({ cwd: staging, strict: true, preservePaths: false, unlink: !keep, keep, ...(exactCopy ? { filter: skipLinks } : {}) }),
);
+ if (exactCopy) {
+ const entries = Object.entries(archive.files);
+ let pending = [];
+ for (const [name, file] of entries) {
+ if (file.kind !== 'link') continue;
+ const target = path.join(staging, name);
+ if (!keep || !await fs.lstat(target).then(() => true, () => false)) pending.push({ target, link: file.hash });
+ }
+ // Windows fixes a link's file/directory type when it is created, judged by whether its target
+ // exists. Create links whose targets resolve first so chains get the right type; dangling last.
+ while (pending.length) {
+ const waiting = [];
+ for (const entry of pending) {
+ if (await fs.stat(path.resolve(path.dirname(entry.target), entry.link)).then(() => true, () => false)) await fs.symlink(entry.link, entry.target);
+ else waiting.push(entry);
+ }
+ if (waiting.length === pending.length) {
+ for (const entry of waiting) await fs.symlink(entry.link, entry.target);
+ break;
+ }
+ pending = waiting;
+ }
+ // Children before parents, so a read-only directory cannot block what lies beneath it.
+ for (const [name, file] of entries.reverse()) {
+ if (file.kind === 'link') continue;
+ const target = path.join(staging, name);
+ if (restorableMode((await fs.lstat(target)).mode) !== file.mode) await fs.chmod(target, file.mode);
+ }
+ }
if (!sameWorktreeFiles(await inventoryWorktree(staging), archive.files)) {
throw new Error('restored worktree files do not match recovery archive');
}
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
index 5ec155ed27..432fa59af6 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts
@@ -1,24 +1,25 @@
import * as io from './recoveryArchiveIO';
-import type { FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO';
+import type { ArchiveSelection, FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO';
+import { selectPortableEntries } from '../task-migration/portableEntries';
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; excludePaths?: string[] }
+ | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number; excludePaths?: string[]; portable?: true }
| ({ operation: 'verify' } & ArchiveInput)
- | ({ operation: 'extract'; staging: string; keep: boolean } & ArchiveInput);
+ | ({ operation: 'extract'; staging: string; keep: boolean; exactCopy?: true } & ArchiveInput);
export type RecoveryArchiveResult<T extends RecoveryArchiveTask> =
T extends { operation: 'inventory' } ? Record<string, FileEvidence> :
- T extends { operation: 'create' } ? WorktreeRecoveryArchive : void;
+ T extends { operation: 'create' } ? WorktreeRecoveryArchive & { skipped?: ArchiveSelection['skipped'] } : void;
/** Run only with physical filesystem semantics (Node, or the isolated Electron worker). */
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.excludePaths);
+ case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes, task.excludePaths, task.portable ? selectPortableEntries : undefined);
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);
+ case 'extract': return await io.extractRecoveryArchive(task.archive, task.staging, task.keep, task.directory, task.key, task.maxBytes, task.exactCopy);
}
} finally {
if ('key' in task) task.key.fill(0);
diff --git a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx
index 5cf5fd6ba7..e54dfb8dfa 100644
--- a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx
@@ -54,7 +54,9 @@ export function TaskMigrationStatus({ session }: { session: Session }) {
className="max-w-64 truncate [-webkit-app-region:no-drag]"
onClick={() => setOpen(true)}
>
- {t(`taskMigration.stages.${status.stage}`)}
+ {status.stage === 'complete' && status.skipped
+ ? t('taskMigration.completeWithSkipped', { count: status.skipped.total })
+ : t(`taskMigration.stages.${status.stage}`)}
</Button>
{open && <TaskMigrationDialog session={session} onDismiss={() => setOpen(false)} />}
</>
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 80ac288919..d480eb9e42 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
@@ -335,6 +335,29 @@ export function TaskMigrationDialog({
? t('taskMigration.failureDescription')
: t('taskMigration.description', { name: computerName })}
</Dialog.Description>
+ {complete && status?.skipped && (
+ <div className="mt-3 text-sm text-[var(--confirm-desc)]">
+ <p>{t('taskMigration.skippedTitle', { count: status.skipped.total })}</p>
+ <ul className="mt-2 max-h-48 space-y-1 overflow-y-auto">
+ {status.skipped.entries.map((entry) => (
+ <li key={entry.path} className="break-all">
+ <span className="text-[var(--confirm-title)]">{entry.path}</span>
+ {' · '}
+ {t(`taskMigration.skippedReasons.${entry.code}`, {
+ defaultValue: entry.code,
+ })}
+ </li>
+ ))}
+ </ul>
+ {status.skipped.total > status.skipped.entries.length && (
+ <p className="mt-1">
+ {t('taskMigration.skippedMore', {
+ count: status.skipped.total - status.skipped.entries.length,
+ })}
+ </p>
+ )}
+ </div>
+ )}
{confirming && (
<p className="mt-2 text-sm text-[var(--confirm-desc)]">
{t('taskMigration.bindingsNotice')}
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 654a522e40..1470d31995 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
@@ -162,6 +162,34 @@ it('loads the completed task from the target computer before navigation and dism
expect(state.merge).toHaveBeenCalledWith('B', 'B', [{ id: 'migrated', status: 'active' }]);
});
+it('lists what a finished copy left behind, with the count of unlisted entries', async () => {
+ state.request.mockImplementation(async (device: string | null, command: { action: string }) => ({
+ supported: true,
+ deviceId: device ?? 'local',
+ ...(command.action === 'status'
+ ? {
+ stage: 'complete',
+ running: false,
+ targetDeviceId: 'B',
+ targetSessionId: 'migrated',
+ skipped: {
+ total: 3,
+ entries: [
+ { path: 'Pods/out.h', code: 'MIGRATION_EXTERNAL_LINK' },
+ { path: 'dev.sock', code: 'MIGRATION_UNSUPPORTED_ENTRY' },
+ ],
+ },
+ }
+ : {}),
+ }));
+ mount();
+ await screen.findByText('taskMigration.skippedTitle');
+ expect(screen.getByText('Pods/out.h')).toBeTruthy();
+ expect(screen.getByText('dev.sock')).toBeTruthy();
+ expect(screen.getByText('taskMigration.skippedMore')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'taskMigration.openTarget' })).toBeTruthy();
+ expect(screen.queryByRole('alert')).toBeNull();
+});
it('confirms the project selected in the menu without asking for a second selection', async () => {
render(
<MemoryRouter>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4755af37d4..d920b48191 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -59,6 +59,18 @@
},
"successTitle": "Copy successful",
"successDescription": "Copied to {{name}}.",
+ "skippedTitle_one": "{{count}} file or folder was not copied. Everything else was copied in full:",
+ "skippedTitle_other": "{{count}} files or folders were not copied. Everything else was copied in full:",
+ "skippedMore_one": "{{count}} more not listed.",
+ "skippedMore_other": "{{count}} more not listed.",
+ "completeWithSkipped_one": "Copied, {{count}} item skipped",
+ "completeWithSkipped_other": "Copied, {{count}} items skipped",
+ "skippedReasons": {
+ "MIGRATION_EXTERNAL_LINK": "Link points outside the project folder",
+ "MIGRATION_NONPORTABLE_PATH": "Name is not usable on other systems",
+ "MIGRATION_PATH_COLLISION": "Differs from another file only in letter case",
+ "MIGRATION_UNSUPPORTED_ENTRY": "Special file (such as a socket or pipe) that cannot be copied"
+ },
"copyingTitle": "Copying to {{name}}",
"keepOpen": "Copying to {{name}}. Closing this window won't stop the copy; check progress at the top of the original task.",
"runInBackground": "Continue in background",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1936d82888..4e68e3913a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -59,6 +59,18 @@
},
"successTitle": "コピー完了",
"successDescription": "{{name}}にコピーしました。",
+ "skippedTitle_one": "次の {{count}} 件のファイルまたはフォルダーはコピーされませんでした。その他はすべてコピーしました:",
+ "skippedTitle_other": "次の {{count}} 件のファイルまたはフォルダーはコピーされませんでした。その他はすべてコピーしました:",
+ "skippedMore_one": "ほか {{count}} 件は表示していません。",
+ "skippedMore_other": "ほか {{count}} 件は表示していません。",
+ "completeWithSkipped_one": "コピー完了({{count}} 件はコピーされず)",
+ "completeWithSkipped_other": "コピー完了({{count}} 件はコピーされず)",
+ "skippedReasons": {
+ "MIGRATION_EXTERNAL_LINK": "プロジェクトフォルダー外を指すリンク",
+ "MIGRATION_NONPORTABLE_PATH": "ほかのシステムで使用できない名前",
+ "MIGRATION_PATH_COLLISION": "別のファイルと大文字・小文字だけが異なる",
+ "MIGRATION_UNSUPPORTED_ENTRY": "コピーできない特殊ファイル(ソケット、パイプなど)"
+ },
"copyingTitle": "{{name}}にコピー中",
"keepOpen": "{{name}}にコピーしています。このウィンドウを閉じてもコピーは続行され、元のタスク上部で進捗を確認できます。",
"runInBackground": "バックグラウンドで続行",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 9ea4891d8a..b27687ef91 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -59,6 +59,18 @@
},
"successTitle": "복사 완료",
"successDescription": "{{name}}에 복사했습니다.",
+ "skippedTitle_one": "다음 {{count}}개 파일 또는 폴더는 복사되지 않았습니다. 나머지는 모두 복사했습니다:",
+ "skippedTitle_other": "다음 {{count}}개 파일 또는 폴더는 복사되지 않았습니다. 나머지는 모두 복사했습니다:",
+ "skippedMore_one": "{{count}}개 항목은 표시되지 않았습니다.",
+ "skippedMore_other": "{{count}}개 항목은 표시되지 않았습니다.",
+ "completeWithSkipped_one": "복사 완료, {{count}}개 항목 제외",
+ "completeWithSkipped_other": "복사 완료, {{count}}개 항목 제외",
+ "skippedReasons": {
+ "MIGRATION_EXTERNAL_LINK": "프로젝트 폴더 외부를 가리키는 링크",
+ "MIGRATION_NONPORTABLE_PATH": "다른 시스템에서 사용할 수 없는 이름",
+ "MIGRATION_PATH_COLLISION": "다른 파일과 대소문자만 다름",
+ "MIGRATION_UNSUPPORTED_ENTRY": "복사할 수 없는 특수 파일(소켓, 파이프 등)"
+ },
"copyingTitle": "{{name}}로 복사 중",
"keepOpen": "{{name}}로 복사 중입니다. 창을 닫아도 복사는 계속되며, 원본 작업 상단에서 진행 상황을 확인할 수 있습니다.",
"runInBackground": "백그라운드에서 계속",
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 ff55463d28..82c4baa679 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -59,6 +59,18 @@
},
"successTitle": "复制成功",
"successDescription": "已复制到{{name}}。",
+ "skippedTitle_one": "以下 {{count}} 个文件或文件夹没有复制,其余内容已完整复制:",
+ "skippedTitle_other": "以下 {{count}} 个文件或文件夹没有复制,其余内容已完整复制:",
+ "skippedMore_one": "另有 {{count}} 项未列出。",
+ "skippedMore_other": "另有 {{count}} 项未列出。",
+ "completeWithSkipped_one": "复制成功,{{count}} 项未复制",
+ "completeWithSkipped_other": "复制成功,{{count}} 项未复制",
+ "skippedReasons": {
+ "MIGRATION_EXTERNAL_LINK": "链接指向项目目录外部",
+ "MIGRATION_NONPORTABLE_PATH": "文件名在其他系统上无法使用",
+ "MIGRATION_PATH_COLLISION": "与另一个文件仅大小写不同",
+ "MIGRATION_UNSUPPORTED_ENTRY": "特殊文件(如套接字、管道),无法复制"
+ },
"copyingTitle": "正在复制到{{name}}",
"keepOpen": "正在复制到{{name}}。关闭窗口不会中断复制,可在原任务顶部查看进度。",
"runInBackground": "后台继续",
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 61b89706e3..dd988ccf6a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -59,6 +59,18 @@
},
"successTitle": "複製成功",
"successDescription": "已複製到{{name}}。",
+ "skippedTitle_one": "以下 {{count}} 個檔案或資料夾未複製,其餘內容已完整複製:",
+ "skippedTitle_other": "以下 {{count}} 個檔案或資料夾未複製,其餘內容已完整複製:",
+ "skippedMore_one": "另有 {{count}} 項未列出。",
+ "skippedMore_other": "另有 {{count}} 項未列出。",
+ "completeWithSkipped_one": "複製成功,{{count}} 項未複製",
+ "completeWithSkipped_other": "複製成功,{{count}} 項未複製",
+ "skippedReasons": {
+ "MIGRATION_EXTERNAL_LINK": "連結指向專案目錄外部",
+ "MIGRATION_NONPORTABLE_PATH": "檔案名稱在其他系統上無法使用",
+ "MIGRATION_PATH_COLLISION": "與另一個檔案僅大小寫不同",
+ "MIGRATION_UNSUPPORTED_ENTRY": "特殊檔案(如通訊端、管道),無法複製"
+ },
"copyingTitle": "正在複製到{{name}}",
"keepOpen": "正在複製到{{name}}。關閉視窗不會中斷複製,可在原任務頂部查看進度。",
"runInBackground": "背景繼續",
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 5df5299b90..11cecac9e3 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -68,6 +68,8 @@ warn/warning 状态检查项、等待或处理中的检查项和 warning issue
`receive.files.additionalWorkspaces` 沿用同一文件描述,manifest 记录成员到目录的映射。
双方必须支持复制通道;收到整组能力声明才发送团队,不尝试部分导入。
运行中取消由源端状态的可选 `cancellable` / `cancelling` 声明,旧源端缺省时控制端不提供取消。
+源端状态的可选 `skipped: { total, entries[{ path, code }] }` 列出本次复制跳过的条目,旧源端缺省、旧控制端忽略;
+新源端会发送项目内链接链与断开链接,旧目标仍按旧规则拒收(`MIGRATION_EXTERNAL_LINK`),需更新目标。
范围、恢复与源目录保护见 [同机移动与跨电脑复制任务](../product-rules/task-device-migration.md)。
设备互联生成文件沿用远端文件服务的 stat 与修改时间,控制端按被控端消息时间窗校验命令产物;
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index 3f58ee361e..1268185f6b 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -44,9 +44,10 @@
(`MIGRATION_CANNOT_CANCEL`),不回滚目标;重试中的复制在回执确认目标没有这次复制的接收记录前同样不可取消。旧源端不声明 `cancellable`,只提供后台继续。
OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。
文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。
- 成功页只提供关闭和“打开新复制的任务”。失败页只提供关闭,关闭会复用完成路径清理已上传的 OSS 对象及本地暂存,结束本次源端复制;目标端可能已提交的副本不会回滚。
- 失败页优先显示对应原因;没有专门文案的错误显示通用提示并附错误码。文件名不可移植、仅大小写不同
- 或链接指向目录外时,同时显示出问题的项目内相对路径。源端把原始报错写入日志,
+ 成功页只提供关闭和“打开新复制的任务”;有未复制的条目时,成功页逐条列出项目内相对路径与原因
+ (最多 100 条,其余只计数),原任务顶部的状态按钮显示「复制成功,N 项未复制」并可打开该页。失败页只提供关闭,关闭会复用完成路径清理已上传的 OSS 对象及本地暂存,结束本次源端复制;目标端可能已提交的副本不会回滚。
+ 失败页优先显示对应原因;没有专门文案的错误显示通用提示并附错误码。目标端拒收文件名不可移植、
+ 仅大小写不同或链接指向目录外的条目时(如旧版目标),同时显示出问题的项目内相对路径。源端把原始报错写入日志,
关闭后复制记录仍保留错误码,直到再次发起复制,便于事后排查。
任务历史超出内存上限时说明是历史过大(不提示释放内存),源端判定时附「需要约 X,上限约 Y」,
日志记录预算各组成;目标版本旧、需随包携带原生会话记录而超限,且拆出 32 MiB 以上的会话记录后即可装下时,提示更新两台电脑;
@@ -71,8 +72,15 @@
接收绑定源设备、源任务和复制 ID,持续复核账号代次、DB 实例及远控授权。
- 不转移 Cindy 登录或供应商凭证。项目内 `.env` 等忽略文件属于用户项目快照。
- 原生上下文必须完整,为 CC、Codex、Pi 分配独立标识;不降级为只有可见消息的副本。
-- Git 目录须为仓库根;暂不支持子模块、嵌套 Git 元数据、无首个提交仓库、目录外链接或链接链,
- 以及目标系统无法表示的文件名和大小写冲突。空间或内存不足时提示并保留源文件。
+- Git 目录须为仓库根;暂不支持子模块、嵌套 Git 元数据、无首个提交仓库。空间或内存不足时提示并保留源文件。
+- 复制允许有瑕疵(2026-10-02 用户要求):单个条目无法复制时不阻止整次复制,源端打包时跳过并在成功页告知。
+ 跳过的只有:解析后指向目录外部或 `.git`(含绝对路径、循环链接)的链接、其他系统无法表示的文件名、
+ 仅大小写不同的同名条目(保留先遇到的一个),以及套接字、管道等特殊文件;被跳过的目录连同其内容一起跳过、只列目录本身。
+ 项目内的链接链(如 CocoaPods 与 `.framework` 的 `Versions/Current`)和指向项目内暂不存在位置的断开链接原样复制。
+ 目标端仍严格校验收到的清单,并在解包时最后按清单创建链接、按源端权限恢复文件与目录模式,不受本机 umask 收窄。
+ 旧版目标仍会拒收链接链,报 `MIGRATION_EXTERNAL_LINK`,此时需更新目标电脑。
+ 跳过按目录自上而下判定,被跳过目录的内容不参与大小写冲突与链接判断;链接解析按不区分大小写比对,偏保守。
+ 已知边界:被跳过的子树仍计入复制前的文件数估算与源端暂存空间核算,只在该子树极大时才会影响结果,暂不单独剪枝。
- 失败仅影响本次复制,不重启 relay、不关闭其它设备链路、不重放无关请求。接收预算 30 分钟,
文件统计 3 分钟,其它请求 30 秒;写请求没有通用自动重试。没有服务端或数据库 schema 变更。
diff --git a/packages/device-link/src/taskMigration.ts b/packages/device-link/src/taskMigration.ts
index 3b701e8bd4..8b8aa38007 100644
--- a/packages/device-link/src/taskMigration.ts
+++ b/packages/device-link/src/taskMigration.ts
@@ -96,6 +96,11 @@ export interface TaskMigrationView {
error?: string;
/** Project-relative entry blamed for `error` (e.g. a non-portable name). Absent on older hosts. */
errorPath?: string;
+ /**
+ * Entries the copy left behind (a directory stands for its subtree), with why; `entries` is
+ * capped and `total` counts them all. Absent when nothing was skipped or on older hosts.
+ */
+ skipped?: { total: number; entries: Array<{ path: string; code: string }> };
projects?: string[];
agents?: Array<"cc" | "codex" | "pi">;
/** Entire Orca graph, native contexts and per-member workspaces. Absence means unsupported. */