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): 复制失败可诊断,打包不再被 git status 误判为目录变化 (#5331)

Dash57d30d85dab3
diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
index 066797319b..2342eae13f 100644
--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts
+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
@@ -1741,6 +1741,11 @@ export interface ImportSharedCodexThreadParams {
threadSpawnEdges: Array<Record<string, unknown>>;
};
rolloutBuffer: Buffer | null;
+ /**
+ * Migration alternative to `rolloutBuffer` for rollouts too large to hold in memory:
+ * writes the rollout to the given path atomically, replacing an interrupted attempt.
+ */
+ writeRollout?: (target: string) => Promise<void>;
rolloutFilename: string | null;
newCwd: string;
title: string;
@@ -1787,7 +1792,7 @@ export async function importSharedCodexThread(
const home = getDesktopCodexHome();
let rolloutPath: string | null = null;
let rolloutWritten = false;
- if (params.rolloutBuffer) {
+ if (params.rolloutBuffer || params.writeRollout) {
const candidate = params.rolloutFilename && /^[\w.-]+\.jsonl$/.test(params.rolloutFilename)
? params.rolloutFilename
: `rollout-imported-${params.threadId}.jsonl`;
@@ -1800,11 +1805,13 @@ export async function importSharedCodexThread(
// wx 独占写:同名 rollout 已在盘上(典型是删除 Maker 会话后重导同一分享包)
// 时不覆盖、直接复用——盘上副本可能包含删除前 resume 产生的更新内容。
try {
- if (params.migration) atomicWriteFileSync(rolloutPath, params.rolloutBuffer.toString('utf8'));
- else await fsp.writeFile(rolloutPath, params.rolloutBuffer, { flag: 'wx' });
+ if (params.writeRollout) await params.writeRollout(rolloutPath);
+ else if (params.migration) atomicWriteFileSync(rolloutPath, params.rolloutBuffer!.toString('utf8'));
+ else await fsp.writeFile(rolloutPath, params.rolloutBuffer!, { flag: 'wx' });
rolloutWritten = true;
} catch (err) {
- if (params.migration || (err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
+ if (params.migration || params.writeRollout || (err as NodeJS.ErrnoException).code !== 'EEXIST')
+ throw err;
log.info('import shared codex thread: rollout already on disk, reusing', {
threadId: params.threadId,
});
diff --git a/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts b/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts
new file mode 100644
index 0000000000..b07f7df74f
--- /dev/null
+++ b/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts
@@ -0,0 +1,105 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { migrationNativeContext } from '../migrationNativeContext';
+import { writeMigratedTranscript } from '../migrationTranscriptWriter';
+
+const original = '12345678-1234-4234-a234-123456789012';
+let dir = '';
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-transcript-writer-'));
+});
+afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+/** Deliver `bytes` in fixed-size chunks so lines and characters straddle chunk boundaries. */
+const chunked = (bytes: Buffer, size: number) =>
+ Readable.from(
+ (function* () {
+ for (let i = 0; i < bytes.length; i += size) yield bytes.subarray(i, i + size);
+ })(),
+ );
+
+const ccRow = JSON.stringify({ sessionId: original, uuid: 'u', message: { content: '雪 ☃ 😀' } });
+const codexMeta = JSON.stringify({ type: 'session_meta', payload: { id: original, cwd: '/源' } });
+const samples: Record<string, string> = {
+ empty: '',
+ 'no trailing newline': `${ccRow}\n${codexMeta}`,
+ crlf: `${ccRow}\r\n${codexMeta}\r\n`,
+ 'blank and malformed': `\n \n{partial\nnull\n[1]\n${ccRow}\n\n`,
+ bom: `${ccRow}\n${codexMeta}\n`,
+ 'multi-byte without ids': '雪 ☃ 😀 ü\n'.repeat(5),
+ 'id only in content': `${JSON.stringify({ type: 'event', payload: { content: original } })}\n`,
+};
+
+describe('writeMigratedTranscript', () => {
+ for (const [name, text] of Object.entries(samples)) {
+ it.each([
+ ['cc', 1],
+ ['cc', 3],
+ ['codex', 7],
+ ['codex', 1],
+ ] as const)(`matches transcript() for ${name} (%s, %i-byte chunks)`, async (agent, size) => {
+ const context = migrationNativeContext('migration', [original]);
+ const bytes = Buffer.from(text);
+ const target = path.join(dir, 'copy.jsonl');
+ await writeMigratedTranscript(chunked(bytes, size), target, { context, agent });
+ expect(fs.readFileSync(target).equals(context.transcript(bytes, agent))).toBe(true);
+ });
+ }
+
+ it('keeps bytes of lines it does not rewrite, even when they are not valid UTF-8', async () => {
+ const context = migrationNativeContext('migration', [original]);
+ const bytes = Buffer.concat([Buffer.from([0xff, 0xfe, 0x41, 0x0a]), Buffer.from(ccRow)]);
+ const target = path.join(dir, 'copy.jsonl');
+ await writeMigratedTranscript(chunked(bytes, 2), target, { context, agent: 'cc' });
+ const written = fs.readFileSync(target);
+ expect(written.subarray(0, 4).equals(bytes.subarray(0, 4))).toBe(true);
+ expect(JSON.parse(written.subarray(4).toString()).sessionId).toBe(context.id(original));
+ });
+
+ it('copies bytes unchanged without a rewrite and replaces a leftover target', async () => {
+ const target = path.join(dir, 'nested', 'copy.jsonl');
+ fs.mkdirSync(path.dirname(target));
+ fs.writeFileSync(target, 'interrupted attempt');
+ const bytes = Buffer.from(`${ccRow}\n`);
+ await writeMigratedTranscript(chunked(bytes, 5), target, null);
+ expect(fs.readFileSync(target).equals(bytes)).toBe(true);
+ });
+
+ it('leaves neither a target nor a temp file when the source fails', async () => {
+ const target = path.join(dir, 'copy.jsonl');
+ const failing = new Readable({
+ read() {
+ this.push(Buffer.from(ccRow));
+ this.destroy(new Error('source lost'));
+ },
+ });
+ await expect(writeMigratedTranscript(failing, target, null)).rejects.toThrow('source lost');
+ expect(fs.readdirSync(dir)).toEqual([]);
+ });
+
+ it('does not publish when the import is no longer current', async () => {
+ const target = path.join(dir, 'copy.jsonl');
+ await expect(
+ writeMigratedTranscript(chunked(Buffer.from(ccRow), 4), target, null, () => {
+ throw new Error('MIGRATION_OWNER_CHANGED');
+ }),
+ ).rejects.toThrow('MIGRATION_OWNER_CHANGED');
+ expect(fs.readdirSync(dir)).toEqual([]);
+ });
+
+ it('withdraws the published file when the import stops being current during the rename', async () => {
+ const target = path.join(dir, 'copy.jsonl');
+ let checks = 0;
+ await expect(
+ writeMigratedTranscript(chunked(Buffer.from(ccRow), 4), target, null, () => {
+ checks += 1;
+ if (checks > 1) throw new Error('MIGRATION_OWNER_CHANGED');
+ }),
+ ).rejects.toThrow('MIGRATION_OWNER_CHANGED');
+ expect(checks).toBe(2);
+ expect(fs.readdirSync(dir)).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts
index d5c9d99bfa..48ba24f842 100644
--- a/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts
+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts
@@ -2,6 +2,7 @@
* 导出编排集成测试:mock DB / bridge / 媒体 store,用 temp projectsRoot 放真实
* jsonl,走完整 exportSessionShare → openPayload → JSZip 解包验证内容。
*/
+import { createHash } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { promises as fsp } from 'node:fs';
import os from 'node:os';
@@ -407,6 +408,114 @@ describe('exportSessionShare', () => {
expect(`${manifestText}\n${sessionText}\n${messagesText}`).not.toContain(missingPiSessionFile);
});
+ describe('external transcripts for a migration', () => {
+ const rollout = `${JSON.stringify({ type: 'session_meta', payload: { id: 'thread-1' } })}\n${'x'.repeat(4096)}\n`;
+ const exportExternal = (name: string, extra: Partial<Parameters<typeof exportSessionShare>[0]> = {}) => {
+ const dir = path.join(tmpRoot, `staged-${name}`);
+ return {
+ dir,
+ outcome: exportSessionShare({
+ sessionId: 'xdt-session-1',
+ targetPath: path.join(tmpRoot, `out-${name}.xdtshare`),
+ migration: true,
+ externalTranscripts: { dir, minBytes: 1024 },
+ ...extra,
+ }),
+ };
+ };
+
+ it('streams large transcripts beside the package and keeps small ones inside', async () => {
+ await fsp.writeFile(path.join(tmpRoot, 'rollout-1-thread-1.jsonl'), rollout);
+ sessionRowRef.row = { ...baseSession(), agentKind: 'codex', sdkSessionId: 'thread-1' };
+ // The limit admits the messages but not the rollout: only in-memory bytes count.
+ const { dir, outcome: pending } = exportExternal('codex-external', { sizeLimitBytes: 4096 });
+ const outcome = await pending;
+ expect(outcome.status).toBe('ok');
+ if (outcome.status !== 'ok') return;
+ expect(outcome.fidelity).toBe('full');
+ const zipPath = 'transcripts/codex/rollout-1-thread-1.jsonl';
+ expect(outcome.externalTranscripts).toEqual([
+ {
+ path: zipPath,
+ file: expect.stringMatching(/^transcript-0-[a-f0-9]{8}\.jsonl$/),
+ bytes: Buffer.byteLength(rollout),
+ sha256: createHash('sha256').update(rollout).digest('hex'),
+ },
+ ]);
+ const staged = await fsp.readFile(path.join(dir, outcome.externalTranscripts![0].file), 'utf8');
+ expect(staged).toBe(rollout);
+ const zip = await unzipOf(path.join(tmpRoot, 'out-codex-external.xdtshare'));
+ expect(zip.file(zipPath)).toBeNull();
+ const manifest = validateManifest(JSON.parse(await zip.file('manifest.json')!.async('string')));
+ expect(manifest.transcripts).toEqual([{ sdkSessionId: 'thread-1', path: zipPath }]);
+ expect(manifest.entries.some((entry) => entry.path === zipPath)).toBe(false);
+ expect(outcome.unpackedBytes).toBeLessThan(4096);
+
+ // Claude transcripts under the threshold stay in the zip as before.
+ sessionRowRef.row = baseSession();
+ const small = exportExternal('cc-small');
+ const smallOutcome = await small.outcome;
+ expect(smallOutcome.status === 'ok' && smallOutcome.externalTranscripts).toEqual([]);
+ const smallZip = await unzipOf(path.join(tmpRoot, 'out-cc-small.xdtshare'));
+ expect(smallZip.file('transcripts/claude/sid-a.jsonl')).toBeTruthy();
+ });
+
+ it('derives the Pi portable id from the streamed bytes', async () => {
+ const piSessionFile = path.join(tmpRoot, 'pi-agent-home', 'sessions', 'large.jsonl');
+ const content = `${'{"type":"message"}\n'.repeat(200)}`;
+ await fsp.mkdir(path.dirname(piSessionFile), { recursive: true });
+ await fsp.writeFile(piSessionFile, content);
+ sessionRowRef.row = { ...baseSession(), agentKind: 'pi', sdkSessionId: piSessionFile };
+ messagesRef.rows = baseMessages().map((message) => ({ ...message, agentKind: 'pi' }));
+ const { outcome: pending } = exportExternal('pi-external');
+ const outcome = await pending;
+ expect(outcome.status).toBe('ok');
+ if (outcome.status !== 'ok') return;
+ const portableId = `pi-${createHash('sha256').update(content).digest('hex').slice(0, 32)}.jsonl`;
+ expect(outcome.externalTranscripts?.map((t) => t.path)).toEqual([`transcripts/pi/${portableId}`]);
+ const zip = await unzipOf(path.join(tmpRoot, 'out-pi-external.xdtshare'));
+ const manifest = validateManifest(JSON.parse(await zip.file('manifest.json')!.async('string')));
+ expect(manifest.activeSdkSessionId).toBe(portableId);
+ });
+
+ it('ignores the option outside a migration and reports where an oversize package went', async () => {
+ await fsp.writeFile(path.join(tmpRoot, 'rollout-1-thread-1.jsonl'), rollout);
+ sessionRowRef.row = { ...baseSession(), agentKind: 'codex', sdkSessionId: 'thread-1' };
+ const { dir, outcome } = exportExternal('not-migration', { migration: false, sizeLimitBytes: 4096 });
+ expect(await outcome).toMatchObject({
+ status: 'oversize',
+ limitBytes: 4096,
+ transcriptBytes: Buffer.byteLength(rollout),
+ externalTranscriptBytes: 0,
+ });
+ await expect(fsp.stat(dir)).rejects.toThrow();
+ });
+
+ // Permission bits do not restrict Windows or root.
+ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
+ 'fails instead of reporting missing context when the copy cannot be written',
+ async () => {
+ await fsp.writeFile(path.join(tmpRoot, 'rollout-1-thread-1.jsonl'), rollout);
+ sessionRowRef.row = { ...baseSession(), agentKind: 'codex', sdkSessionId: 'thread-1' };
+ const dir = path.join(tmpRoot, 'staged-readonly');
+ await fsp.mkdir(dir, { recursive: true });
+ await fsp.chmod(dir, 0o500);
+ try {
+ await expect(
+ exportSessionShare({
+ sessionId: 'xdt-session-1',
+ targetPath: path.join(tmpRoot, 'out-readonly.xdtshare'),
+ migration: true,
+ externalTranscripts: { dir, minBytes: 1024 },
+ }),
+ ).rejects.toThrow();
+ } finally {
+ await fsp.chmod(dir, 0o700);
+ }
+ },
+ );
+ });
+
it('oversize returns structured outcome without writing file', async () => {
const target = path.join(tmpRoot, 'out-oversize.xdtshare');
const outcome = await exportSessionShare({
diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts
index 0bcbd707f9..82b6980cb0 100644
--- a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts
+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts
@@ -632,9 +632,84 @@ describe('sessionShareImport', () => {
const nativeId = migrationNativeContext(migrationId, [SID]).id(SID);
const restored = agentKind === 'cc'
? await fsp.readFile(path.join(projectsRoot, sanitizeClaudeProjectKey(newWorkdir), `${nativeId}.jsonl`), 'utf8')
- : (codexMock.importCalls[0] as { rolloutBuffer: Buffer }).rolloutBuffer.toString();
+ : await (async () => {
+ // A migration streams the rollout through writeRollout instead of a buffer.
+ const call = codexMock.importCalls[0] as {
+ rolloutBuffer: Buffer | null;
+ writeRollout: (target: string) => Promise<void>;
+ };
+ expect(call.rolloutBuffer).toBeNull();
+ const target = path.join(tmpRoot, 'streamed-rollout.jsonl');
+ await call.writeRollout(target);
+ return fsp.readFile(target, 'utf8');
+ })();
expect(restored).toBe(JSON.stringify(agentKind === 'cc' ? { sessionId: nativeId } : { type: 'session_meta', payload: { id: nativeId } }) + tail);
});
+ describe('transcripts delivered beside a migration package', () => {
+ const migrationId = '11111111-2222-4333-a444-555555555555';
+ const transcriptPathOf = (agentKind: 'cc' | 'codex' | 'pi') =>
+ agentKind === 'cc'
+ ? `transcripts/claude/${SID}.jsonl`
+ : agentKind === 'codex'
+ ? `transcripts/codex/rollout-x-${SID}.jsonl`
+ : `transcripts/pi/${PI_SID}`;
+ /** The package without its transcript entry, plus the transcript as a separate file. */
+ const external = async (agentKind: 'cc' | 'codex' | 'pi', content: string) => {
+ const zip = await JSZip.loadAsync(await buildBundle({ agentKind }));
+ zip.remove(transcriptPathOf(agentKind));
+ const inspect = await inspectShareFile(await writeBundleFile(await zip.generateAsync({ type: 'nodebuffer' })));
+ if (inspect.encrypted) throw new Error('unexpected encrypted fixture');
+ const file = path.join(tmpRoot, `delivered-${agentKind}.jsonl`);
+ await fsp.writeFile(file, content);
+ return { draftId: inspect.draftId, file };
+ };
+ const commit = (draftId: string, externalTranscripts: Map<string, string>) =>
+ commitShareImport({ draftId, workingDir: newWorkdir, projectsRootOverride: projectsRoot,
+ piSessionsRootOverride: piSessionsRoot, sharedMediaRootOverride: sharedMediaRoot },
+ { sessionId: migrationId, workingDir: newWorkdir, externalTranscripts });
+
+ it.each(['cc', 'codex', 'pi'] as const)('restores a %s transcript from the delivered file', async agentKind => {
+ const header = agentKind === 'cc' ? { sessionId: SID } : agentKind === 'codex'
+ ? { type: 'session_meta', payload: { id: SID } } : { type: 'session' };
+ const content = `${JSON.stringify(header)}\n${'{"type":"event"}\n'.repeat(3)}`;
+ const { draftId, file } = await external(agentKind, content);
+ codexMock.importResult.rolloutPath = path.join(tmpRoot, 'external-rollout.jsonl');
+ const result = await commit(draftId, new Map([[transcriptPathOf(agentKind), file]]));
+ expect(result.fidelity).toBe('full');
+ const nativeId = migrationNativeContext(migrationId, [SID]).id(SID);
+ const rewritten = agentKind === 'pi' ? content
+ : content.replace(JSON.stringify(header), JSON.stringify(
+ agentKind === 'cc' ? { sessionId: nativeId } : { type: 'session_meta', payload: { id: nativeId } }));
+ let restored: string;
+ if (agentKind === 'cc') {
+ restored = await fsp.readFile(path.join(projectsRoot, sanitizeClaudeProjectKey(newWorkdir), `${nativeId}.jsonl`), 'utf8');
+ } else if (agentKind === 'pi') {
+ restored = await fsp.readFile(path.join(piSessionsRoot, migrationId, PI_SID), 'utf8');
+ } else {
+ const call = codexMock.importCalls[0] as { rolloutBuffer: Buffer | null; rolloutFilename: string;
+ writeRollout: (target: string) => Promise<void> };
+ expect(call.rolloutBuffer).toBeNull();
+ expect(call.rolloutFilename).toBe(`rollout-x-${nativeId}.jsonl`);
+ const target = path.join(tmpRoot, 'external-rollout.jsonl');
+ await call.writeRollout(target);
+ restored = await fsp.readFile(target, 'utf8');
+ }
+ expect(restored).toBe(rewritten);
+ });
+
+ it('fails a migration whose transcript was neither packaged nor delivered', async () => {
+ const { draftId } = await external('cc', '{}\n');
+ await expect(commit(draftId, new Map())).rejects.toThrow('MIGRATION_INCOMPLETE_CONTEXT');
+ });
+
+ it('rejects a delivered file that no transcript in the package refers to', async () => {
+ const { draftId, file } = await external('cc', '{}\n');
+ await expect(
+ commit(draftId, new Map([[transcriptPathOf('cc'), file], ['transcripts/claude/other.jsonl', file]])),
+ ).rejects.toThrow('MIGRATION_INVALID_MANIFEST');
+ });
+ });
+
it.each(['cc', 'pi'] as const)('repairs a partial %s migration transcript on retry', async agentKind => {
const filePath = await writeBundleFile(await buildBundle({ agentKind }));
const migration = { sessionId: '11111111-2222-4333-a444-555555555555', workingDir: newWorkdir };
diff --git a/apps/desktop/src/main/session-share/migrationNativeContext.ts b/apps/desktop/src/main/session-share/migrationNativeContext.ts
index 004fd79887..aada381493 100644
--- a/apps/desktop/src/main/session-share/migrationNativeContext.ts
+++ b/apps/desktop/src/main/session-share/migrationNativeContext.ts
@@ -46,39 +46,47 @@ export function migrationNativeContext(migrationId: string, nativeIds: readonly
}
return changed ? JSON.stringify(value) : raw;
};
+ /** One transcript line (without its `\n`). */
+ const line = (text: string, agent: 'cc' | 'codex'): string => {
+ if (!text.trim()) return text;
+ let row;
+ try {
+ row = JSON.parse(text);
+ } catch {
+ // Native readers tolerate interrupted/legacy lines; copying must preserve them.
+ return text;
+ }
+ if (!row || typeof row !== 'object' || Array.isArray(row)) return text;
+ if (agent === 'cc' && typeof row.sessionId === 'string' && ids.has(row.sessionId)) {
+ return JSON.stringify({ ...row, sessionId: id(row.sessionId) });
+ }
+ if (
+ agent === 'codex' &&
+ row.type === 'session_meta' &&
+ typeof row.payload?.id === 'string' &&
+ ids.has(row.payload.id)
+ ) {
+ // Codex native IDs are equal-length UUIDs. Preserve all other bytes and line offsets.
+ return text.replace(
+ /("id"\s*:\s*)("(?:[^"\\]|\\.)*")/g,
+ (_match, prefix: string, value: string) =>
+ `${prefix}${JSON.stringify(id(JSON.parse(value)))}`,
+ );
+ }
+ return text;
+ };
+ /**
+ * Whether `line` can change the bytes. Rewrites need a mapped ID as a JSON string value,
+ * and native writers never escape UUID characters, so other lines can be copied as bytes.
+ */
+ const mayRewrite = (bytes: Buffer): boolean =>
+ [...ids.keys()].some((nativeId) => bytes.includes(nativeId));
const transcript = (bytes: Buffer, agent: 'cc' | 'codex'): Buffer =>
Buffer.from(
bytes
.toString('utf8')
.split('\n')
- .map((line) => {
- if (!line.trim()) return line;
- let row;
- try {
- row = JSON.parse(line);
- } catch {
- // Native readers tolerate interrupted/legacy lines; copying must preserve them.
- return line;
- }
- if (!row || typeof row !== 'object' || Array.isArray(row)) return line;
- if (agent === 'cc' && typeof row.sessionId === 'string' && ids.has(row.sessionId)) {
- return JSON.stringify({ ...row, sessionId: id(row.sessionId) });
- }
- if (
- agent === 'codex' &&
- row.type === 'session_meta' &&
- typeof row.payload?.id === 'string' &&
- ids.has(row.payload.id)
- ) {
- // Codex native IDs are equal-length UUIDs. Preserve all other bytes and line offsets.
- return line.replace(
- /("id"\s*:\s*)("(?:[^"\\]|\\.)*")/g,
- (_match, prefix: string, value: string) =>
- `${prefix}${JSON.stringify(id(JSON.parse(value)))}`,
- );
- }
- return line;
- })
+ .map((text) => line(text, agent))
.join('\n'),
);
const stateRows = <
@@ -106,5 +114,5 @@ export function migrationNativeContext(migrationId: string, nativeIds: readonly
),
};
};
- return { id, metadata, transcript, stateRows };
+ return { id, metadata, line, mayRewrite, transcript, stateRows };
}
diff --git a/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts b/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts
new file mode 100644
index 0000000000..9c208c67d6
--- /dev/null
+++ b/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts
@@ -0,0 +1,96 @@
+import { randomBytes } from 'node:crypto';
+import { createWriteStream, promises as fsp } from 'node:fs';
+import path from 'node:path';
+import { Transform, type Readable } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+
+import type { migrationNativeContext } from './migrationNativeContext.js';
+
+export interface TranscriptRewrite {
+ context: ReturnType<typeof migrationNativeContext>;
+ agent: 'cc' | 'codex';
+}
+
+const NEWLINE = Buffer.from('\n');
+
+/**
+ * Same output as `context.transcript(bytes, agent)` without holding the transcript in memory:
+ * a native transcript can exceed V8's string limit. Splits on the `\n` byte, which never
+ * occurs inside a multi-byte UTF-8 sequence, and decodes only lines that can change, so other
+ * lines keep their exact bytes. Memory is bounded by the longest line.
+ */
+class TranscriptLines extends Transform {
+ private carry: Buffer[] = [];
+
+ constructor(private readonly rewrite: TranscriptRewrite) {
+ super();
+ }
+
+ override _transform(chunk: Buffer, _encoding: BufferEncoding, done: (error?: Error) => void) {
+ let start = 0;
+ for (let end = chunk.indexOf(0x0a); end !== -1; end = chunk.indexOf(0x0a, start)) {
+ this.carry.push(chunk.subarray(start, end));
+ this.push(this.takeLine());
+ this.push(NEWLINE);
+ start = end + 1;
+ }
+ // Copy: the tail outlives this chunk.
+ if (start < chunk.length) this.carry.push(Buffer.from(chunk.subarray(start)));
+ done();
+ }
+
+ override _flush(done: (error?: Error) => void) {
+ // No trailing newline is added, matching `split('\n').join('\n')`.
+ if (this.carry.length) this.push(this.takeLine());
+ done();
+ }
+
+ private takeLine(): Buffer {
+ const bytes = this.carry.length === 1 ? this.carry[0] : Buffer.concat(this.carry);
+ this.carry = [];
+ const { context, agent } = this.rewrite;
+ if (!context.mayRewrite(bytes)) return bytes;
+ return Buffer.from(context.line(bytes.toString('utf8'), agent));
+ }
+}
+
+/**
+ * Write a copied native transcript to `target` atomically: a hidden temp file in the same
+ * directory (never `*.jsonl`, so vendor scanners skip leftovers), then rename. `rewrite` maps
+ * native IDs; null copies the bytes unchanged.
+ */
+export async function writeMigratedTranscript(
+ source: Readable,
+ target: string,
+ rewrite: TranscriptRewrite | null,
+ assertStillValid?: () => void,
+): Promise<void> {
+ const dir = path.dirname(target);
+ await fsp.mkdir(dir, { recursive: true });
+ const temp = path.join(dir, `.${path.basename(target)}.${randomBytes(6).toString('hex')}.tmp`);
+ try {
+ const steps = rewrite ? [new TranscriptLines(rewrite)] : [];
+ await pipeline(source, ...steps, createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
+ assertStillValid?.();
+ try {
+ await fsp.rename(temp, target);
+ } catch (error) {
+ // Windows cannot rename over an existing file. Only a crashed attempt of this same
+ // copy can own `target` (copied native IDs are unique per copy), so replace it.
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== 'EPERM' && code !== 'EEXIST') throw error;
+ await fsp.rm(target, { force: true });
+ await fsp.rename(temp, target);
+ }
+ // The import may have lost ownership during the rename; the caller then throws before
+ // journaling `target`, so withdraw it here instead of leaving it orphaned.
+ try {
+ assertStillValid?.();
+ } catch (error) {
+ await fsp.rm(target, { force: true });
+ throw error;
+ }
+ } finally {
+ await fsp.rm(temp, { force: true });
+ }
+}
diff --git a/apps/desktop/src/main/session-share/sessionShareExport.ts b/apps/desktop/src/main/session-share/sessionShareExport.ts
index a0b3cb965f..2cb3cc8fc2 100644
--- a/apps/desktop/src/main/session-share/sessionShareExport.ts
+++ b/apps/desktop/src/main/session-share/sessionShareExport.ts
@@ -22,8 +22,10 @@
* 写盘用「同目录 .tmp + rename」保证目标文件原子出现。
*/
import { createHash, randomBytes } from 'node:crypto';
-import { promises as fsp } from 'node:fs';
+import { createWriteStream, promises as fsp } from 'node:fs';
import path from 'node:path';
+import { Transform } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
import { setImmediate as yieldToEventLoop } from 'node:timers/promises';
import JSZip from 'jszip';
@@ -85,6 +87,22 @@ export interface SessionShareExportOptions {
sizeLimitBytes?: number;
/** Host-only migration includes archived members without reviving them. */
migration?: boolean;
+ /**
+ * Migration only: vendor transcripts of at least `minBytes` are streamed into `dir` instead
+ * of the in-memory zip, so their size is bounded by disk rather than memory or V8 strings.
+ * Their refs keep the zip path, which the importer resolves to the delivered file.
+ */
+ externalTranscripts?: { dir: string; minBytes: number };
+}
+
+/** A transcript left out of the zip (see `externalTranscripts`). */
+export interface ExternalTranscript {
+ /** The transcript ref path it stands for. */
+ path: string;
+ /** File name inside `externalTranscripts.dir`. */
+ file: string;
+ bytes: number;
+ sha256: string;
}
export type SessionShareExportOutcome =
@@ -92,6 +110,8 @@ export type SessionShareExportOutcome =
status: 'ok';
unpackedBytes: number;
filePath: string;
+ /** Present when `externalTranscripts` was requested. */
+ externalTranscripts?: ExternalTranscript[];
fidelity: XdtshareFidelity;
/** 导出端没找到转录的 sdkSessionId 列表(cc fork 链部分缺失时非空)。 */
missingTranscripts: string[];
@@ -102,7 +122,18 @@ export type SessionShareExportOutcome =
/** 随包携带的协同 Worker 会话数(非协同包为 0)。 */
orcaWorkers: number;
}
- | { status: 'oversize'; totalBytes: number; mediaBytes: number; limitBytes: number };
+ | {
+ status: 'oversize';
+ totalBytes: number;
+ mediaBytes: number;
+ limitBytes: number;
+ /** Breakdown for diagnostics; transcript bytes count only those kept in the zip. */
+ messagesBytes?: number;
+ transcriptBytes?: number;
+ /** Each in-zip transcript's size, so callers can tell which ones a threshold would move. */
+ transcriptFileBytes?: number[];
+ externalTranscriptBytes?: number;
+ };
/** media-map.json 的条目(导入端按它落位与重写 URL)。 */
export interface MediaMapEntry {
@@ -166,8 +197,12 @@ function portablePiSessionId(buffer: Buffer): string {
// ID 与真正打包的同一份冻结字节计算,避免“先 hash、后文件继续写、再 read”
// 的 TOCTOU 让清单 id 与包内内容不一致。读失败时不再用绝对路径摘要兜底:
// 那会复活 path-only 冲突,并把不可验证的转录伪装成可恢复。
- const basis = createHash('sha256').update(buffer).digest('hex').slice(0, 32);
- return `pi-${basis}.jsonl`;
+ return piSessionIdFromDigest(createHash('sha256').update(buffer).digest('hex'));
+}
+
+/** Same id as {@link portablePiSessionId}, from a digest computed while streaming. */
+function piSessionIdFromDigest(sha256: string): string {
+ return `pi-${sha256.slice(0, 32)}.jsonl`;
}
/** Pi 的 agentMeta 不能把源机绝对 sessionFile 路径带进分享包。 */
@@ -196,6 +231,57 @@ interface TranscriptCandidate {
zipPath: string;
absPath: string;
bytes: number;
+ /** Streamed to disk rather than read into the zip (migration, large files). */
+ external?: boolean;
+}
+
+/** Where external transcripts are staged, and the ones staged so far across all members. */
+interface ExternalStaging {
+ dir: string;
+ staged: ExternalTranscript[];
+}
+
+/**
+ * Copy a transcript into `dest` while hashing it, never holding it in memory. A failure to read
+ * the source returns null, so the caller degrades exactly as for an unreadable in-zip transcript;
+ * a failure to write the copy (e.g. ENOSPC) is a real error and throws.
+ */
+async function stageTranscript(
+ absPath: string,
+ dest: string,
+): Promise<{ bytes: number; sha256: string } | null> {
+ const handle = await fsp.open(absPath, 'r').catch(() => null);
+ if (!handle) return null;
+ const hash = createHash('sha256');
+ let bytes = 0;
+ // pipeline() destroys every stream with the first error, so only the first one tells the side.
+ let failedSide: 'read' | 'write' | null = null;
+ const source = handle.createReadStream();
+ source.on('error', () => (failedSide ??= 'read'));
+ const destination = createWriteStream(dest, { flags: 'wx', mode: 0o600 });
+ destination.on('error', () => (failedSide ??= 'write'));
+ try {
+ await pipeline(
+ source,
+ new Transform({
+ transform(chunk: Buffer, _encoding, done) {
+ hash.update(chunk);
+ bytes += chunk.length;
+ done(null, chunk);
+ },
+ }),
+ destination,
+ );
+ } catch (err) {
+ await fsp.rm(dest, { force: true });
+ if (failedSide === 'read') return null;
+ throw err;
+ }
+ if (bytes === 0) {
+ await fsp.rm(dest, { force: true });
+ return null;
+ }
+ return { bytes, sha256: hash.digest('hex') };
}
/** 单会话的阶段 A 收集结果(lead 与协同 Worker 复用同一套流程)。 */
@@ -358,7 +444,10 @@ async function collectSessionPhaseA(
* 不让单文件问题炸掉整次导出;转录读失败同步把 ref 回落 null,保真度按
* 实际落包结果判。
*/
-async function readSessionPhaseB(a: SessionPhaseA): Promise<SessionPhaseB> {
+async function readSessionPhaseB(
+ a: SessionPhaseA,
+ external?: ExternalStaging,
+): Promise<SessionPhaseB> {
const { session, zipPrefix } = a;
const sdkSessionIds = [...a.sdkSessionIds];
const refs = a.refs.map((r) => ({ ...r }));
@@ -368,20 +457,39 @@ async function readSessionPhaseB(a: SessionPhaseA): Promise<SessionPhaseB> {
const piPortableIds = new Map<string, string>();
const seenPiPortableIds = new Set<string>();
for (const candidate of a.candidates) {
- const buffer = await fsp.readFile(candidate.absPath).catch(() => null);
- if (buffer && buffer.length > 0) {
+ let content: { buffer: Buffer } | { file: string; bytes: number; sha256: string } | null;
+ if (candidate.external && external) {
+ const file = `transcript-${external.staged.length}-${randomBytes(4).toString('hex')}.jsonl`;
+ const staged = await stageTranscript(candidate.absPath, path.join(external.dir, file));
+ content = staged && { file, ...staged };
+ } else {
+ const buffer = await fsp.readFile(candidate.absPath).catch(() => null);
+ content = buffer && buffer.length > 0 ? { buffer } : null;
+ }
+ // In-zip entries carry their bytes; external ones are listed for the transfer.
+ const keep = (zipPath: string) => {
+ if (!content) return;
+ if ('buffer' in content) transcriptFiles.push({ zipPath, buffer: content.buffer });
+ else external!.staged.push({ path: zipPath, ...content });
+ };
+ if (content) {
if (session.agentKind === 'pi') {
- const portableId = portablePiSessionId(buffer);
+ const portableId =
+ 'buffer' in content
+ ? portablePiSessionId(content.buffer)
+ : piSessionIdFromDigest(content.sha256);
piPortableIds.set(candidate.absPath, portableId);
if (!seenPiPortableIds.has(portableId)) {
seenPiPortableIds.add(portableId);
const zipPath = `${zipPrefix}transcripts/pi/${portableId}`;
sdkSessionIds.push(portableId);
refs.push({ sdkSessionId: portableId, path: zipPath });
- transcriptFiles.push({ zipPath, buffer });
+ keep(zipPath);
+ } else if ('file' in content) {
+ await fsp.rm(path.join(external!.dir, content.file), { force: true });
}
} else {
- transcriptFiles.push({ zipPath: candidate.zipPath, buffer });
+ keep(candidate.zipPath);
}
} else {
// Pi 读失败时没有内容可生成安全便携 id,直接省略该转录并把 message meta
@@ -513,6 +621,12 @@ export async function exportSessionShare(
);
}
const allA = [leadA, ...workersA];
+ const externalOption = opts.migration ? opts.externalTranscripts : undefined;
+ if (externalOption) {
+ for (const a of allA)
+ for (const candidate of a.candidates)
+ candidate.external = candidate.bytes >= externalOption.minBytes;
+ }
const mediaMap: MediaMapEntry[] = [];
const mediaCandidates: Array<{
@@ -601,21 +715,41 @@ export async function exportSessionShare(
(sum, a) => sum + a.messages.reduce((s, m) => s + Buffer.byteLength(m.content), 0),
0,
);
- const transcriptBytes = allA.reduce(
- (sum, a) => sum + a.candidates.reduce((s, f) => s + f.bytes, 0),
- 0,
- );
+ const transcriptBytesOf = (external: boolean) =>
+ allA.reduce(
+ (sum, a) =>
+ sum + a.candidates.reduce((s, f) => s + (!!f.external === external ? f.bytes : 0), 0),
+ 0,
+ );
+ // External transcripts are streamed to disk and never held in memory.
+ const transcriptBytes = transcriptBytesOf(false);
+ const externalTranscriptBytes = transcriptBytesOf(true);
const mediaBytes = mediaCandidates.reduce((sum, f) => sum + f.bytes, 0);
const totalBytes = messagesBytes + transcriptBytes + mediaBytes;
const limitBytes = opts.sizeLimitBytes ?? SHARE_EXPORT_SIZE_LIMIT_BYTES;
+ const transcriptFileBytes = allA.flatMap((a) =>
+ a.candidates.filter((f) => !f.external).map((f) => f.bytes),
+ );
+ const sizes = {
+ mediaBytes,
+ limitBytes,
+ messagesBytes,
+ transcriptBytes,
+ transcriptFileBytes,
+ externalTranscriptBytes,
+ };
if (totalBytes > limitBytes) {
- return { status: 'oversize', totalBytes, mediaBytes, limitBytes };
+ return { status: 'oversize', totalBytes, ...sizes };
}
// ── 阶段 B(lead + 每个 Worker) ──
- const leadB = await readSessionPhaseB(leadA);
+ const external: ExternalStaging | undefined = externalOption
+ ? { dir: externalOption.dir, staged: [] }
+ : undefined;
+ if (external) await fsp.mkdir(external.dir, { recursive: true });
+ const leadB = await readSessionPhaseB(leadA, external);
const workersB: SessionPhaseB[] = [];
- for (const a of workersA) workersB.push(await readSessionPhaseB(a));
+ for (const a of workersA) workersB.push(await readSessionPhaseB(a, external));
const allB = [leadB, ...workersB];
const mediaFiles: Array<{ zipPath: string; buffer: Buffer }> = [];
@@ -745,7 +879,7 @@ export async function exportSessionShare(
const unpackedBytes = entries.reduce((sum, entry) => sum + entry.bytes, 0) +
Buffer.byteLength(JSON.stringify(manifest, null, 2));
if (opts.sizeLimitBytes !== undefined && unpackedBytes > limitBytes)
- return { status: 'oversize', totalBytes: unpackedBytes, mediaBytes, limitBytes };
+ return { status: 'oversize', totalBytes: unpackedBytes, ...sizes };
const zipBytes = await zip.generateAsync({
type: 'nodebuffer',
@@ -781,6 +915,8 @@ export async function exportSessionShare(
messages: messages.length,
orcaWorkers: workerSources.length,
transcripts: allB.reduce((sum, b) => sum + b.transcriptFiles.length, 0),
+ externalTranscripts: external?.staged.length ?? 0,
+ externalTranscriptBytes: external?.staged.reduce((sum, t) => sum + t.bytes, 0) ?? 0,
missingTranscripts: missingTranscripts.length,
media: mediaFiles.length,
mediaMissing,
@@ -792,6 +928,7 @@ export async function exportSessionShare(
status: 'ok',
unpackedBytes,
filePath: opts.targetPath,
+ ...(external ? { externalTranscripts: external.staged } : {}),
fidelity,
missingTranscripts,
mediaMissing,
diff --git a/apps/desktop/src/main/session-share/sessionShareImport.ts b/apps/desktop/src/main/session-share/sessionShareImport.ts
index e82fa476e0..021dc69e9d 100644
--- a/apps/desktop/src/main/session-share/sessionShareImport.ts
+++ b/apps/desktop/src/main/session-share/sessionShareImport.ts
@@ -16,12 +16,13 @@
* 里 running 归一为 idle(导入端没有正在跑的 turn)。
*/
import { createHash, randomUUID } from 'node:crypto';
-import { promises as fsp } from 'node:fs';
+import { createReadStream, promises as fsp } from 'node:fs';
import path from 'node:path';
+import type { Readable } from 'node:stream';
import JSZip from 'jszip';
-import { atomicWriteFileSync } from '../utils/atomicWriteFile';
import { migrationNativeContext } from './migrationNativeContext';
+import { writeMigratedTranscript } from './migrationTranscriptWriter';
import { isClaudeProjectKeyExact, sanitizeClaudeProjectKey } from '@cindy/maker-core';
import { app } from 'electron';
@@ -281,6 +282,8 @@ export interface CommitShareImportRuntimeScope {
workingDir: string;
workers?: Array<{ sourceSessionId: string; sessionId: string; workingDir: string }>;
agentPrefs?: Partial<Record<'cc' | 'codex' | 'pi', ShareImportDraftPrefs>>;
+ /** Transcript ref path → delivered file, for transcripts the exporter kept out of the zip. */
+ externalTranscripts?: ReadonlyMap<string, string>;
};
assertStillValid(): void;
refCompensationScope: MediaRefCompensationScope;
@@ -501,6 +504,25 @@ export async function commitShareImport(
: transcript,
);
}
+ const externalTranscripts: ReadonlyMap<string, string> =
+ runtimeScope.migration?.externalTranscripts ?? new Map();
+ // A delivered file must stand for a transcript this package references.
+ const referencedTranscriptPaths = new Set(
+ [bundledTranscripts, ...workerPlans.map((plan) => plan.bundledTranscripts ?? [])]
+ .flat()
+ .map((transcript) => transcript.path),
+ );
+ for (const transcriptPath of externalTranscripts.keys()) {
+ if (!referencedTranscriptPaths.has(transcriptPath))
+ throw new XdtshareError('SHARE_FILE_INVALID', 'MIGRATION_INVALID_MANIFEST');
+ }
+ /** A transcript's bytes: the file delivered beside the package, else its zip entry. */
+ const transcriptSource = (zipPath: string): (() => Readable) | null => {
+ const file = externalTranscripts.get(zipPath);
+ if (file) return () => createReadStream(file);
+ const entry = zip.file(zipPath);
+ return entry ? () => entry.nodeStream('nodebuffer') as unknown as Readable : null;
+ };
const piSessionsRoot = path.resolve(
opts.piSessionsRootOverride ??
path.join(app.getPath('userData'), 'pi-agent-home', 'sessions', 'shared'),
@@ -511,7 +533,7 @@ export async function commitShareImport(
const registerPiTargets = (bundled: BundledTranscript[]): void => {
for (const transcript of bundled) {
// 只有包内实际存在的转录才映射成可 resume 的本机绝对路径。
- if (zip.file(transcript.path)) {
+ if (transcriptSource(transcript.path)) {
piTranscriptTargets.set(
transcript.sdkSessionId,
path.join(piSessionsRoot, ...(runtimeScope.migration ? [runtimeScope.migration.sessionId] : []), transcript.sdkSessionId),
@@ -798,22 +820,37 @@ export async function commitShareImport(
);
await guarded(() => fsp.mkdir(claudeTargetDir, { recursive: true }).then(() => undefined));
for (const t of restore.bundled) {
- const file = zip.file(t.path);
- if (!file) continue;
+ const source = transcriptSource(t.path);
+ if (!source) continue;
const target = path.join(claudeTargetDir, `${t.sdkSessionId}.jsonl`);
+ if (migratedContext) {
+ // This handoff owns its new native ID; retries replace incomplete copies atomically.
+ // Streamed: a native transcript can exceed memory and V8's string limit.
+ await guarded(() =>
+ writeMigratedTranscript(
+ source(),
+ target,
+ { context: migratedContext, agent: 'cc' },
+ assertStillValid,
+ ),
+ );
+ journal.push(async () => {
+ await fsp.rm(target, { force: true });
+ });
+ transcriptsWritten += 1;
+ continue;
+ }
+ const file = zip.file(t.path)!;
try {
const transcriptBytes = Buffer.from(await guarded(() => file.async('nodebuffer')));
assertStillValid();
- if (migratedContext) {
- // This handoff owns its new native ID; retries replace incomplete copies atomically.
- atomicWriteFileSync(target, migratedContext.transcript(transcriptBytes, 'cc').toString('utf8'));
- } else await fsp.writeFile(target, transcriptBytes, { flag: 'wx' });
+ await fsp.writeFile(target, transcriptBytes, { flag: 'wx' });
journal.push(async () => {
await fsp.rm(target, { force: true });
});
assertStillValid();
} catch (err) {
- if (migratedContext || (err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
log.info('transcript already on disk, reusing', { sdkSessionId: t.sdkSessionId });
assertStillValid();
}
@@ -830,16 +867,24 @@ export async function commitShareImport(
if (restore.agentKind !== 'pi') continue;
for (const transcript of restore.bundled) {
const target = piTranscriptTargets.get(transcript.sdkSessionId);
- const file = zip.file(transcript.path);
- if (!target || !file || piTargetsWritten.has(target)) continue;
+ const source = transcriptSource(transcript.path);
+ if (!target || !source || piTargetsWritten.has(target)) continue;
piTargetsWritten.add(target);
- await writeIfMissing(
- target,
- Buffer.from(await guarded(() => file.async('nodebuffer'))),
- journal,
- assertStillValid,
- Boolean(migratedContext),
- );
+ if (migratedContext) {
+ // Pi IDs are content hashes, so the bytes are copied unchanged; retries replace them.
+ await guarded(() => writeMigratedTranscript(source(), target, null, assertStillValid));
+ journal.push(async () => {
+ await fsp.rm(target, { force: true });
+ });
+ } else {
+ const file = zip.file(transcript.path)!;
+ await writeIfMissing(
+ target,
+ Buffer.from(await guarded(() => file.async('nodebuffer'))),
+ journal,
+ assertStillValid,
+ );
+ }
transcriptsWritten += 1;
}
}
@@ -857,7 +902,19 @@ export async function commitShareImport(
})
: { threads: [], threadDynamicTools: [], threadSpawnEdges: [] };
const rolloutRef = restore.bundled[0] ?? null;
- const rolloutFile = rolloutRef ? zip.file(rolloutRef.path) : null;
+ const rolloutSource = rolloutRef ? transcriptSource(rolloutRef.path) : null;
+ // A migration streams the rollout (it can exceed memory and V8's string limit).
+ const writeRollout =
+ migratedContext && rolloutSource
+ ? (target: string) =>
+ writeMigratedTranscript(
+ rolloutSource(),
+ target,
+ { context: migratedContext, agent: 'codex' },
+ assertStillValid,
+ )
+ : undefined;
+ const rolloutFile = !migratedContext && rolloutRef ? zip.file(rolloutRef.path) : null;
const rolloutBuffer = rolloutFile
? Buffer.from(await guarded(() => rolloutFile.async('nodebuffer')))
: null;
@@ -866,7 +923,8 @@ export async function commitShareImport(
threadId,
migration: Boolean(migratedContext),
stateRows: migratedContext ? migratedContext.stateRows(stateRows) : stateRows,
- rolloutBuffer: migratedContext && rolloutBuffer ? migratedContext.transcript(rolloutBuffer, 'codex') : rolloutBuffer,
+ rolloutBuffer,
+ ...(writeRollout ? { writeRollout } : {}),
rolloutFilename: rolloutRef
? path.posix.basename(rolloutRef.path).replace(
/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?=\.jsonl$)/i,
@@ -1360,20 +1418,18 @@ async function writeIfMissing(
buffer: Buffer,
journal: Array<() => Promise<void>>,
assertStillValid: () => void,
- migration = false,
): Promise<void> {
assertStillValid();
await fsp.mkdir(path.dirname(target), { recursive: true });
assertStillValid();
try {
- if (migration) atomicWriteFileSync(target, buffer.toString('utf8'));
- else await fsp.writeFile(target, buffer, { flag: 'wx' });
+ await fsp.writeFile(target, buffer, { flag: 'wx' });
journal.push(async () => {
await fsp.rm(target, { force: true });
});
assertStillValid();
} catch (err) {
- if (migration || (err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
assertStillValid();
}
}
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 e4a4f7340a..5d064e9a48 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -11,6 +11,7 @@ import {
TASK_MIGRATION_ESTIMATE_TIMEOUT_MS,
TASK_MIGRATION_LOCAL_CHANNEL,
TASK_MIGRATION_MAX_FILES,
+ TASK_MIGRATION_MAX_TRANSCRIPTS,
} from '@cindy/device-link';
const state = vi.hoisted(() => ({
@@ -44,7 +45,30 @@ const state = vi.hoisted(() => ({
estimateLimits: [] as number[],
timeoutAction: '' as string,
exclusions: [] as string[],
+ migrationWarn: vi.fn(),
+ /** Native transcript the export streams beside the package when the target supports it. */
+ transcript: '' as string,
+ transcriptCount: 1,
+ exportOversize: null as null | {
+ totalBytes: number;
+ limitBytes: number;
+ transcriptBytes: number;
+ transcriptFileBytes?: number[];
+ },
+ /** Target without the `externalTranscripts` capability. */
+ oldTarget: false,
+ importedTranscripts: [] as Array<{ path: string; content: string }>,
}));
+vi.mock('../../logger', async (original) => {
+ const actual = await original<typeof import('../../logger')>();
+ return {
+ ...actual,
+ createLogger: (scope: string) =>
+ scope === 'task-migration'
+ ? { ...actual.createLogger(scope), warn: state.migrationWarn }
+ : actual.createLogger(scope),
+ };
+});
vi.mock('../../localDb/ipc/sessionCreatedBroadcast', () => ({
emitSessionCreated: (id: string) => state.created(id),
}));
@@ -104,6 +128,7 @@ vi.mock('../../device-link', () => ({
const result = await state.context.run({ device: target, peer }, () =>
requestTaskMigration(args[0]),
);
+ if (state.oldTarget && args[0].action === 'caps') delete result.externalTranscripts;
if (state.loseReply === args[0].action) {
state.loseReply = '';
throw new Error('connection lost after commit');
@@ -155,10 +180,33 @@ vi.mock('../../worktree/resourceLock', async (original) => ({
withWorktreeResourceLocks: (_cwds: string[], fn: () => unknown) => fn(),
}));
vi.mock('../../session-share/sessionShareExport', () => ({
- exportSessionShare: async ({ targetPath }: { targetPath: string }) => {
- state.exported();
- await fs.writeFile(targetPath, 'conversation');
- return { status: 'ok', fidelity: 'full', ...state.exportMedia };
+ exportSessionShare: async (opts: {
+ targetPath: string;
+ externalTranscripts?: { dir: string; minBytes: number };
+ }) => {
+ state.exported(opts);
+ if (state.exportOversize) return { status: 'oversize', mediaBytes: 0, ...state.exportOversize };
+ await fs.writeFile(opts.targetPath, 'conversation');
+ const external = opts.externalTranscripts;
+ const staged =
+ external && state.transcript
+ ? Array.from({ length: state.transcriptCount }, (_, index) => ({
+ path: index
+ ? `transcripts/codex/rollout-${index}.jsonl`
+ : 'transcripts/codex/rollout.jsonl',
+ file: `transcript-${index}-0a1b2c3d.jsonl`,
+ bytes: Buffer.byteLength(state.transcript),
+ sha256: createHash('sha256').update(state.transcript).digest('hex'),
+ }))
+ : [];
+ for (const transcript of staged)
+ await fs.writeFile(path.join(external!.dir, transcript.file), state.transcript);
+ return {
+ status: 'ok',
+ fidelity: 'full',
+ ...state.exportMedia,
+ ...(external ? { externalTranscripts: staged } : {}),
+ };
},
}));
vi.mock('../../session-share/sessionShareImport', () => ({
@@ -175,10 +223,16 @@ vi.mock('../../session-share/sessionShareImport', () => ({
sessionId: string;
workingDir: string;
workers?: Array<{ sessionId: string; sourceSessionId: string; workingDir: string }>;
+ externalTranscripts?: ReadonlyMap<string, string>;
};
},
) => {
state.imports();
+ for (const [transcriptPath, file] of scope.migration.externalTranscripts ?? [])
+ state.importedTranscripts.push({
+ path: transcriptPath,
+ content: await fs.readFile(file, 'utf8'),
+ });
const { sessionId, workingDir } = scope.migration;
state.rows.get(device())!.set(sessionId, {
id: sessionId,
@@ -210,6 +264,7 @@ vi.mock('../../session-share/sessionShareImport', () => ({
vi.mock('../workspace', async (original) => ({
isExcludedFromWorkspace: (await original<typeof import('../workspace')>())
.isExcludedFromWorkspace,
+ MigrationPathError: (await original<typeof import('../workspace')>()).MigrationPathError,
managedWorktreeExclusions: async () => state.exclusions,
estimateWorkspace: async (_root: string, check: () => void, maxFiles: number) => {
state.estimateLimits.push(maxFiles);
@@ -275,6 +330,12 @@ describe('resumable cross-computer copy', () => {
state.estimateLimits = [];
state.timeoutAction = '';
state.exclusions = [];
+ state.transcript = '';
+ state.transcriptCount = 1;
+ state.exportOversize = null;
+ state.oldTarget = false;
+ state.importedTranscripts = [];
+ state.migrationWarn.mockClear();
const cwd = path.join(state.root, 'shared');
await fs.mkdir(cwd);
await fs.writeFile(path.join(cwd, 'draft'), 'original');
@@ -625,9 +686,15 @@ describe('resumable cross-computer copy', () => {
const status = await settled();
expect(status.stage).toBe('preparing');
expect(status.error).toBe('MIGRATION_NO_SPACE');
+ expect(state.migrationWarn).toHaveBeenCalledWith(
+ 'task copy failed',
+ expect.objectContaining({ copyId: status.targetSessionId, code: 'MIGRATION_NO_SPACE' }),
+ );
expect(state.files.size).toBe(0);
expect(state.imports).not.toHaveBeenCalled();
- await requestTaskMigration({ action: 'cancel', sessionId: 'fork' });
+ // Closing the failure dialog cancels the copy; the code must survive as the only trace.
+ const cancelled = await requestTaskMigration({ action: 'cancel', sessionId: 'fork' });
+ expect(cancelled).toMatchObject({ stage: 'cancelled', error: 'MIGRATION_NO_SPACE' });
expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');
});
it('keeps cancellation retryable when staging cleanup fails', async () => {
@@ -935,6 +1002,110 @@ describe('resumable cross-computer copy', () => {
await requestTaskMigration({ action: 'retry', sessionId: 'fork' });
expect((await settled()).stage).toBe('complete');
});
+ it('reports which project entry blocked packing until a retry succeeds', async () => {
+ const { MigrationPathError } = await import('../workspace');
+ state.snapshot.mockImplementationOnce(() => {
+ throw new MigrationPathError('MIGRATION_NONPORTABLE_PATH', 'apps/desktop/C:');
+ });
+ await start();
+ expect(await settled()).toMatchObject({
+ stage: 'preparing',
+ error: 'MIGRATION_NONPORTABLE_PATH',
+ errorPath: 'apps/desktop/C:',
+ });
+ expect(state.migrationWarn).toHaveBeenCalledWith(
+ 'task copy failed',
+ expect.objectContaining({
+ code: 'MIGRATION_NONPORTABLE_PATH',
+ error: expect.stringContaining('apps/desktop/C:'),
+ }),
+ );
+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });
+ const done = await settled();
+ expect(done.stage).toBe('complete');
+ expect(done.error).toBeUndefined();
+ expect(done.errorPath).toBeUndefined();
+ });
+ it('sends a large native transcript beside the package and restores it', async () => {
+ state.transcript = '{"type":"session_meta"}\n'.repeat(4);
+ await start();
+ expect((await settled()).stage).toBe('complete');
+ expect(state.exported.mock.calls[0][0].externalTranscripts).toMatchObject({
+ minBytes: 32 * 1024 * 1024,
+ });
+ expect(state.importedTranscripts).toEqual([
+ { path: 'transcripts/codex/rollout.jsonl', content: state.transcript },
+ ]);
+ // Its upload is tracked with the others, so completing the copy deletes it too.
+ const transcriptKey = [...state.files].find(([, file]) => file.includes('transcript-0-'))![0];
+ expect(state.remove.mock.calls.map(([key]) => key)).toContain(transcriptKey);
+ });
+ it('stops before uploading more transcripts than the target accepts', async () => {
+ state.transcript = 'native history';
+ state.transcriptCount = TASK_MIGRATION_MAX_TRANSCRIPTS + 1;
+ await start();
+ expect(await settled()).toMatchObject({ stage: 'preparing', error: 'MIGRATION_NO_MEMORY' });
+ expect(state.files.size).toBe(0);
+ });
+ it('keeps transcripts inside the package for a target without the capability', async () => {
+ state.transcript = 'native history';
+ state.oldTarget = true;
+ await start();
+ expect((await settled()).stage).toBe('complete');
+ expect(state.exported.mock.calls[0][0].externalTranscripts).toBeUndefined();
+ expect(state.importedTranscripts).toEqual([]);
+ });
+ it('explains a package that exceeds the memory budget until a retry succeeds', async () => {
+ state.exportOversize = { totalBytes: 900, limitBytes: 100, transcriptBytes: 0 };
+ await start();
+ expect(await settled()).toMatchObject({
+ stage: 'preparing',
+ error: 'MIGRATION_NO_MEMORY',
+ errorSize: { needed: 900, limit: 100 },
+ });
+ expect(state.migrationWarn).toHaveBeenCalledWith(
+ 'task copy package exceeds the memory budget',
+ expect.objectContaining({
+ totalBytes: 900,
+ limitBytes: 100,
+ budget: expect.objectContaining({ budget: expect.any(Number) }),
+ }),
+ );
+ state.exportOversize = null;
+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });
+ const done = await settled();
+ expect(done.stage).toBe('complete');
+ expect(done.errorSize).toBeUndefined();
+ });
+ it('asks to update an older target only when moving large transcripts would fit', async () => {
+ const MB = 1024 ** 2;
+ state.oldTarget = true;
+ state.exportOversize = {
+ totalBytes: 900 * MB,
+ limitBytes: 100 * MB,
+ transcriptBytes: 850 * MB,
+ transcriptFileBytes: [850 * MB],
+ };
+ await start();
+ expect(await settled()).toMatchObject({ error: 'MIGRATION_UNSUPPORTED' });
+ expect((await settled()).errorSize).toBeUndefined();
+ });
+ it('reports the size when an updated target would still keep small transcripts inside', async () => {
+ const MB = 1024 ** 2;
+ state.oldTarget = true;
+ // Thirty 28 MB transcripts stay in the package even on an updated target.
+ state.exportOversize = {
+ totalBytes: 900 * MB,
+ limitBytes: 100 * MB,
+ transcriptBytes: 840 * MB,
+ transcriptFileBytes: Array.from({ length: 30 }, () => 28 * MB),
+ };
+ await start();
+ expect(await settled()).toMatchObject({
+ error: 'MIGRATION_NO_MEMORY',
+ errorSize: { needed: 900 * MB, limit: 100 * MB },
+ });
+ });
it('serializes admission even without process-local route locks', async () => {
const results = await Promise.allSettled([start(), start()]);
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
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 8ce6e7373b..06f3e68daa 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
@@ -6,31 +6,45 @@ import { randomUUID } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
-vi.mock('../../worktree/recoveryArchiveWorkerClient', async () => ({
- runRecoveryArchiveTask: (await import('../../worktree/recoveryArchiveTask'))
- .executeRecoveryArchiveTask,
-}));
+vi.mock('../../worktree/recoveryArchiveWorkerClient', async () => {
+ const { executeRecoveryArchiveTask } = await import('../../worktree/recoveryArchiveTask');
+ return {
+ runRecoveryArchiveTask: async (...args: Parameters<typeof executeRecoveryArchiveTask>) => {
+ // Other tasks keep working in the source while its files are archived.
+ if (args[0].operation === 'create') await state.duringArchive?.();
+ return executeRecoveryArchiveTask(...args);
+ },
+ };
+});
vi.mock('../../logger', () => ({
createLogger: () => ({ debug() {}, info() {}, warn() {}, error() {} }),
}));
-const state = vi.hoisted(() => ({ root: '' }));
+const state = vi.hoisted(() => ({
+ root: '',
+ duringArchive: undefined as (() => Promise<void>) | undefined,
+ /** Runs right after the capture publishes its snapshot ref, before its consistency check. */
+ duringCapture: undefined as (() => Promise<void>) | undefined,
+}));
vi.mock('../../worktree/gitExec', async (original) => {
const actual = await original<typeof import('../../worktree/gitExec')>();
return {
...actual,
- gitExec: (
+ gitExec: async (
args: string[],
cwd: string,
options?: import('../../worktree/gitExec').GitExecOpts,
- ) =>
- actual.gitExec(args, cwd, {
+ ) => {
+ const result = await actual.gitExec(args, cwd, {
...options,
extraEnv: {
...options?.extraEnv,
GIT_CONFIG_GLOBAL: path.join(state.root, 'git-global'),
GIT_CONFIG_NOSYSTEM: '1',
},
- }),
+ });
+ if (args[0] === 'update-ref' && args[1] !== '-d') await state.duringCapture?.();
+ return result;
+ },
};
});
import {
@@ -38,8 +52,13 @@ import {
snapshotWorkspace,
restoreWorkspace,
validateWorkspaceEntries,
+ MigrationPathError,
} from '../workspace';
import { inventoryWorktree } from '../../worktree/recoveryArchiveIO';
+import {
+ captureWorktreeContent,
+ WorktreeChangedDuringSnapshotError,
+} from '../../worktree/contentSnapshot';
const exec = promisify(execFile);
const git = async (cwd: string, ...args: string[]) =>
@@ -65,6 +84,8 @@ describe('cross-machine project snapshots', () => {
await Promise.all([source, target, artifacts].map((p) => fs.mkdir(p)));
});
afterEach(async () => {
+ state.duringArchive = undefined;
+ state.duringCapture = undefined;
await fs.rm(state.root, { recursive: true, force: true });
});
@@ -201,6 +222,65 @@ describe('cross-machine project snapshots', () => {
expect(await fs.readFile(path.join(target, 'existing'), 'utf8')).toBe('keep');
expect(await fs.readFile(path.join(source, 'source'), 'utf8')).toBe('copy');
});
+ it('tolerates an index rewrite that keeps staged content, but not a staging change', 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, 'tracked'), 'base\n');
+ await git(source, 'add', '.');
+ await git(source, 'commit', '-m', 'fixture');
+ const index = path.join(source, '.git', 'index');
+ state.duringArchive = async () => {
+ // A `git status` from another task refreshes stat data and rewrites the index bytes.
+ const before = await fs.readFile(index);
+ const later = new Date(Date.now() + 60_000);
+ await fs.utimes(path.join(source, 'tracked'), later, later);
+ await git(source, 'status', '--porcelain');
+ expect((await fs.readFile(index)).equals(before)).toBe(false);
+ };
+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
+ await restoreWorkspace(snapshot, artifacts, target);
+ expect(await fs.readFile(path.join(target, 'tracked'), 'utf8')).toBe('base\n');
+
+ await fs.rm(artifacts, { recursive: true });
+ await fs.writeFile(path.join(source, 'tracked'), 'staged mid-copy\n');
+ state.duringArchive = () => git(source, 'add', 'tracked').then(() => undefined);
+ await expect(snapshotWorkspace(source, artifacts, randomUUID())).rejects.toThrow(
+ 'MIGRATION_WORKSPACE_CHANGED',
+ );
+ expect(await git(source, 'for-each-ref', 'refs/cindy/migration')).toBe('');
+ }, 30_000);
+ it('applies the same content rule while capturing, and keeps recycling byte-strict', 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, 'tracked'), 'base\n');
+ await git(source, 'add', '.');
+ await git(source, 'commit', '-m', 'fixture');
+ let later = Date.now();
+ const refreshIndex = async () => {
+ // `git status` from another task rewrites the index bytes without changing its content.
+ later += 60_000;
+ await fs.utimes(path.join(source, 'tracked'), new Date(later), new Date(later));
+ await git(source, 'status', '--porcelain');
+ };
+
+ state.duringCapture = refreshIndex;
+ await snapshotWorkspace(source, artifacts, randomUUID());
+ // Recycling deletes worktrees, so its default capture stays conservative.
+ await expect(
+ captureWorktreeContent(source, 'refs/cindy/worktree-recovery/test'),
+ ).rejects.toBeInstanceOf(WorktreeChangedDuringSnapshotError);
+ await git(source, 'update-ref', '-d', 'refs/cindy/worktree-recovery/test');
+
+ await fs.rm(artifacts, { recursive: true });
+ await fs.writeFile(path.join(source, 'tracked'), 'staged mid-capture\n');
+ state.duringCapture = () => git(source, 'add', 'tracked').then(() => undefined);
+ await expect(snapshotWorkspace(source, artifacts, randomUUID())).rejects.toThrow(
+ 'MIGRATION_WORKSPACE_CHANGED',
+ );
+ expect(await git(source, 'for-each-ref', 'refs/cindy')).toBe('');
+ }, 30_000);
it('releases the source snapshot ref when bundle creation fails', async () => {
await git(source, 'init', '-b', 'main');
await git(source, 'config', 'user.name', 'Migration test');
@@ -241,4 +321,24 @@ describe('cross-machine project snapshots', () => {
validateWorkspaceEntries({ link: { kind: 'link', mode: 0o777, hash: '../outside' } }),
).toThrow('MIGRATION_EXTERNAL_LINK');
});
+ it('names the entry that blocks the copy', () => {
+ const dir = { kind: 'directory' as const, mode: 0o755, hash: '' };
+ const blamed = (files: Parameters<typeof validateWorkspaceEntries>[0]) => {
+ try {
+ validateWorkspaceEntries(files);
+ } catch (error) {
+ return error instanceof MigrationPathError ? [error.code, error.relPath] : error;
+ }
+ };
+ // A Windows-style path once created as a relative folder by a macOS test run.
+ expect(blamed({ apps: dir, 'apps/C:': dir })).toEqual([
+ 'MIGRATION_NONPORTABLE_PATH',
+ 'apps/C:',
+ ]);
+ expect(blamed({ A: dir, a: dir })).toEqual(['MIGRATION_PATH_COLLISION', 'a']);
+ expect(blamed({ link: { kind: 'link', mode: 0o777, hash: '../outside' } })).toEqual([
+ 'MIGRATION_EXTERNAL_LINK',
+ 'link',
+ ]);
+ });
});
diff --git a/apps/desktop/src/main/task-migration/handoff.ts b/apps/desktop/src/main/task-migration/handoff.ts
index 45e6b6358f..c67deb5c1b 100644
--- a/apps/desktop/src/main/task-migration/handoff.ts
+++ b/apps/desktop/src/main/task-migration/handoff.ts
@@ -12,6 +12,10 @@ export interface MigrationHandoff {
workers?: Array<{ sessionId: string; targetSessionId: string; workingDir: string }>;
stage: MigrationStage;
error?: string;
+ /** Project-relative entry that caused `error`, when one entry is to blame. */
+ errorPath?: string;
+ /** Bytes needed vs the limit, when `error` is a size failure. */
+ errorSize?: { needed: number; limit: number };
}
export interface HandoffDependencies {
save(record: MigrationHandoff): Promise<void>;
@@ -28,7 +32,7 @@ export async function advanceHandoff(
): Promise<void> {
const transition = async (stage: MigrationStage) => {
deps.assertCurrent();
- const next = { ...record, stage, error: undefined };
+ const next = { ...record, stage, error: undefined, errorPath: undefined, errorSize: undefined };
await deps.save(next);
Object.assign(record, next);
deps.assertCurrent();
diff --git a/apps/desktop/src/main/task-migration/resources.ts b/apps/desktop/src/main/task-migration/resources.ts
index 4d158017fc..065474ac2f 100644
--- a/apps/desktop/src/main/task-migration/resources.ts
+++ b/apps/desktop/src/main/task-migration/resources.ts
@@ -3,24 +3,38 @@ import os from 'node:os';
import v8 from 'node:v8';
import { constants } from 'node:buffer';
+/** Each input to {@link memoryBudget}, for logs explaining a `MIGRATION_NO_MEMORY`. */
+export function memoryBudgetDetail() {
+ const heap = v8.getHeapStatistics();
+ const inputs = {
+ freeMemory: os.freemem(),
+ availableMemory: process.availableMemory(),
+ heapRemaining: heap.heap_size_limit - heap.used_heap_size,
+ maxBufferLength: constants.MAX_LENGTH,
+ };
+ return { ...inputs, budget: Math.max(0, Math.floor(Math.min(...Object.values(inputs)) / 4)) };
+}
+
/** JSZip keeps input, inflated content and JS strings alive together. Reserve headroom. */
export function memoryBudget(): number {
- const heap = v8.getHeapStatistics();
- return Math.max(
- 0,
- Math.floor(
- Math.min(
- os.freemem(),
- process.availableMemory(),
- heap.heap_size_limit - heap.used_heap_size,
- constants.MAX_LENGTH,
- ) / 4,
- ),
- );
+ return memoryBudgetDetail().budget;
}
+
+/** Work that does not fit the budget; the numbers explain the failure in logs and the UI. */
+export class MigrationSizeError extends Error {
+ constructor(
+ readonly code: string,
+ readonly neededBytes: number,
+ readonly limitBytes: number,
+ ) {
+ super(`${code}: needs ${neededBytes} bytes, limit ${limitBytes} bytes`);
+ }
+}
+
export function assertMemoryCapacity(bytes: number): void {
- if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > memoryBudget())
- throw new Error('MIGRATION_NO_MEMORY');
+ const budget = memoryBudget();
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > budget)
+ throw new MigrationSizeError('MIGRATION_NO_MEMORY', bytes, budget);
}
/** Combine simultaneous allocations on the same filesystem, including separate mount paths. */
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index 902a4db1f1..4c547237ad 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -6,6 +6,7 @@ import {
TASK_MIGRATION_CHANNEL,
TASK_MIGRATION_LOCAL_CHANNEL,
TASK_MIGRATION_MAX_FILES,
+ TASK_MIGRATION_MAX_TRANSCRIPTS,
TASK_MIGRATION_ESTIMATE_TIMEOUT_MS,
DeviceLinkError,
parseTaskMigrationRequest,
@@ -34,6 +35,7 @@ import {
materializeRemoteAttachment,
parseRemoteAttachmentRef,
} from '../device-link/remoteAttachment';
+import { createLogger } from '../logger';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';
import { throwIpcError } from '../utils/ipcValidate';
import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
@@ -47,6 +49,7 @@ import {
} from '../session-share/sessionShareImport';
import type { moveSessionProjectFromHost } from '../mcp-integrations/moveSession';
import { physicalWorktreeKey, withWorktreeResourceLocks } from '../worktree/resourceLock';
+import { GitExecError } from '../worktree/gitExec';
import { getMakerIfReady } from '../maker-host';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService';
import { pickEnabledFallbackModel } from '../maker-host/model-route-guard';
@@ -58,12 +61,23 @@ import {
estimateWorkspace,
isExcludedFromWorkspace,
managedWorktreeExclusions,
+ MigrationPathError,
type PortableWorkspace,
} from './workspace';
-import { memoryBudget, assertMemoryCapacity, assertDiskCapacity } from './resources';
+import {
+ memoryBudget,
+ memoryBudgetDetail,
+ assertMemoryCapacity,
+ assertDiskCapacity,
+ MigrationSizeError,
+} from './resources';
import { sendParts, receiveParts } from './transferParts';
+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;
+
type MoveProject = (
sessionId: string,
workingDir: string | null,
@@ -79,6 +93,18 @@ interface RunningCopy {
cancelRequested?: boolean;
}
const running = new Map<string, RunningCopy>();
+/** The target's cause never crosses the wire (only its code does), so keep it in this log. */
+const logTargetFailure =
+ (action: 'preflight' | 'receive', copyId: string | null) =>
+ (error: unknown): never => {
+ log.warn('task copy target step failed', {
+ action,
+ copyId,
+ code: errorCode(error),
+ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
+ });
+ throw error;
+ };
const errorCode = (error: unknown): string => {
if ((error as NodeJS.ErrnoException)?.code === 'ENOSPC') return 'MIGRATION_NO_SPACE';
const message = error instanceof Error ? error.message : '';
@@ -181,6 +207,13 @@ function view(scope: Scope, record: MigrationRecord | null): TaskMigrationView {
targetDeviceId: record.targetDeviceId,
targetSessionId: record.targetSessionId,
...(record.error ? { error: record.error } : {}),
+ ...(record.error && record.errorPath ? { errorPath: record.errorPath } : {}),
+ ...(record.error &&
+ record.errorSize &&
+ Number.isSafeInteger(record.errorSize.needed) &&
+ Number.isSafeInteger(record.errorSize.limit)
+ ? { errorSize: record.errorSize }
+ : {}),
}
: {}),
}
@@ -262,6 +295,11 @@ async function sourceGroup(scope: Scope, sessionId: string): Promise<SourceSessi
interface WorkspaceBundle extends PortableWorkspace {
additionalWorkspaces?: PortableWorkspace[];
workers?: Array<{ sourceSessionId: string; sessionId: string; workspace: number }>;
+ /**
+ * Native transcripts sent beside the package (`files.transcripts`, same order): `path` is the
+ * transcript ref they stand for, `file` the staged name in the outgoing directory.
+ */
+ transcripts?: Array<{ path: string; file: string; bytes: number }>;
}
const workspaces = (workspace: WorkspaceBundle) => [
workspace,
@@ -278,6 +316,7 @@ const transferFiles = (files: MigrationFiles) => [
entry.workspace,
...(entry.repository ? [entry.repository] : []),
]),
+ ...(files.transcripts ?? []),
];
async function prepare(scope: Scope, record: MigrationHandoff) {
@@ -340,16 +379,44 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
scope.assertCurrent();
if (members.some((member) => sourceBoundary!.isBusy(member.id)))
throw new Error('MIGRATION_TASK_RUNNING');
+ // Decided per preparation (not at start), so retrying after updating the target uses it.
+ const external =
+ (await invoke(record.targetDeviceId, { action: 'caps' }, scope)).externalTranscripts ===
+ true;
const result = await exportSessionShare({
sessionId: record.sessionId,
targetPath: path.join(directory, 'session.cshare'),
sizeLimitBytes: memoryBudget(),
migration: true,
+ ...(external
+ ? {
+ externalTranscripts: { dir: directory, minBytes: EXTERNAL_TRANSCRIPT_MIN_BYTES },
+ }
+ : {}),
});
scope.assertCurrent();
- if (result.status === 'oversize') throw new Error('MIGRATION_NO_MEMORY');
+ if (result.status === 'oversize') {
+ const { status: _status, ...sizes } = result;
+ log.warn('task copy package exceeds the memory budget', {
+ copyId: record.id,
+ externalTranscripts: external,
+ ...sizes,
+ budget: memoryBudgetDetail(),
+ });
+ // An older target needs transcripts inside the package. Ask to update it only when the
+ // transcripts an updated target would move out actually bring the package within budget.
+ const movable = (result.transcriptFileBytes ?? [])
+ .filter((bytes) => bytes >= EXTERNAL_TRANSCRIPT_MIN_BYTES)
+ .reduce((sum, bytes) => sum + bytes, 0);
+ if (!external && movable > 0 && result.totalBytes - movable <= result.limitBytes)
+ throw new Error('MIGRATION_UNSUPPORTED');
+ throw new MigrationSizeError('MIGRATION_NO_MEMORY', result.totalBytes, result.limitBytes);
+ }
if (result.status !== 'ok' || result.fidelity !== 'full' || result.mediaDropped)
throw new Error('MIGRATION_INCOMPLETE_CONTEXT');
+ // The target rejects more transcripts than the protocol allows; stop before uploading them.
+ 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(
@@ -362,6 +429,15 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
throw new Error('MIGRATION_SOURCE_CHANGED');
const workspace: WorkspaceBundle = {
...snapshots[0],
+ ...(result.externalTranscripts?.length
+ ? {
+ transcripts: result.externalTranscripts.map(({ path: ref, file, bytes }) => ({
+ path: ref,
+ file,
+ bytes,
+ })),
+ }
+ : {}),
...(record.workers
? {
additionalWorkspaces: snapshots.slice(1),
@@ -446,6 +522,7 @@ async function preflight(
workspace: WorkspaceBundle,
directory: string,
) {
+ const statSize = async (name: string) => (await fs.stat(path.join(directory, name))).size;
const sizes = await Promise.all(
[
'session.cshare',
@@ -454,10 +531,15 @@ async function preflight(
path.join(index ? String(index) : '', entry.archive.file),
...(entry.git ? [path.join(index ? String(index) : '', 'repository.bundle')] : []),
]),
- ].map(async (name) => (await fs.stat(path.join(directory, name))).size),
+ ].map(statSize),
+ );
+ const transcriptSizes = await Promise.all(
+ (workspace.transcripts ?? []).map((transcript) => statSize(transcript.file)),
);
+ const transcriptBytes = transcriptSizes.reduce((a, b) => a + b, 0);
const resources: MigrationResources = {
- transferBytes: sizes.reduce((a, b) => a + b, 0),
+ ...(transcriptSizes.length ? { transcriptBytes } : {}),
+ transferBytes: sizes.reduce((a, b) => a + b, 0) + transcriptBytes,
unpackedBytes: workspaces(workspace).reduce((sum, entry) => sum + entry.unpackedBytes, 0),
contextBytes: Math.max(workspace.contextBytes ?? sizes[0], sizes[0]),
manifestBytes: sizes[1],
@@ -502,6 +584,10 @@ async function checkTargetResources(
path: app.getPath('temp'),
bytes: Math.min(resources.transferBytes, FILE_PEER_MAX_BYTES) * 2,
},
+ // Restored native transcripts land under the user's agent homes (codex-home, ~/.claude, Pi).
+ ...(resources.transcriptBytes
+ ? [{ path: app.getPath('home'), bytes: resources.transcriptBytes }]
+ : []),
]);
scope.assertCurrent();
}
@@ -580,6 +666,11 @@ async function transfer(scope: Scope, record: MigrationHandoff) {
});
}
}
+ if (workspace.transcripts?.length) {
+ files.transcripts = [];
+ for (const transcript of workspace.transcripts)
+ files.transcripts.push(await send(path.join(directory, transcript.file)));
+ }
live.progress = { ...live.progress!, phase: 'finishing', bytesPerSecond: 0 };
// A cancel accepted before this point still aborts in invoke's preSend check.
live.committing = true;
@@ -648,16 +739,41 @@ function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {
if (latest?.kind !== 'outgoing' || latest.id !== record.id) return;
await cleanupOutgoing(scope, latest);
scope.assertCurrent();
- scope.save({ ...latest, stage: 'cancelled', error: undefined });
+ scope.save({
+ ...latest,
+ stage: 'cancelled',
+ error: undefined,
+ errorPath: undefined,
+ errorSize: undefined,
+ });
}
},
)
.catch((error) => {
+ // The journal keeps the code and any blamed entry; the cause (git stderr, fs errno) exists only here.
+ log.warn('task copy failed', {
+ copyId: record.id,
+ code: errorCode(error),
+ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
+ ...(error instanceof GitExecError
+ ? { gitArgs: error.args.slice(0, 2).join(' '), stderr: error.stderr.slice(0, 2000) }
+ : {}),
+ });
try {
scope.assertCurrent();
const latest = scope.read(record.sessionId);
if (latest?.kind === 'outgoing' && latest.id === record.id)
- scope.save({ ...latest, error: errorCode(error) });
+ scope.save({
+ ...latest,
+ error: errorCode(error),
+ // A name can be up to 4096 characters; the start is enough to find it.
+ errorPath:
+ error instanceof MigrationPathError ? error.relPath.slice(0, 1024) : undefined,
+ errorSize:
+ error instanceof MigrationSizeError
+ ? { needed: error.neededBytes, limit: error.limitBytes }
+ : undefined,
+ });
} catch {
/* Preserve the old-owner journal; never write under a replacement account. */
}
@@ -807,7 +923,27 @@ async function receive(
)
)
throw new Error('MIGRATION_INVALID_MANIFEST');
+ // Each delivered transcript is listed once, in order, with its transcript ref path.
+ const transcripts = workspace.transcripts ?? [];
+ const transcriptFiles = request.files.transcripts ?? [];
+ if (
+ !Array.isArray(transcripts) ||
+ transcripts.length !== transcriptFiles.length ||
+ new Set(transcripts.map((transcript) => transcript?.path)).size !== transcripts.length ||
+ transcripts.some(
+ (transcript, index) =>
+ !transcript ||
+ typeof transcript.path !== 'string' ||
+ !transcript.path ||
+ transcript.path.length > 1024 ||
+ transcript.bytes !== transcriptFiles[index].size,
+ )
+ )
+ throw new Error('MIGRATION_INVALID_MANIFEST');
await checkTargetResources(scope, request.targetProject, {
+ ...(transcriptFiles.length
+ ? { transcriptBytes: transcriptFiles.reduce((sum, file) => sum + file.size, 0) }
+ : {}),
transferBytes: transferFiles(request.files).reduce((sum, file) => sum + file.size, 0),
unpackedBytes: snapshots.reduce((sum, entry) => sum + entry.unpackedBytes, 0),
contextBytes: Math.max(
@@ -860,6 +996,13 @@ async function receive(
await restoreWorkspace(entry, dir, targetDirs[index]);
}
await receiveFile(scope, request.files.session, path.join(directory, 'session.cshare'));
+ // Names come from the index, never from the source-supplied ref paths.
+ const externalTranscripts = new Map<string, string>();
+ for (const [index, transcript] of transcripts.entries()) {
+ const file = path.join(directory, `transcript-${index}.jsonl`);
+ await receiveFile(scope, transcriptFiles[index], file);
+ externalTranscripts.set(transcript.path, file);
+ }
scope.assertCurrent();
const inspected = await inspectShareFile(path.join(directory, 'session.cshare'), {
resourceBudgetBytes: memoryBudget(),
@@ -915,7 +1058,13 @@ async function receive(
dbClient: scope.db,
assertStillValid: scope.assertCurrent,
refCompensationScope: captureMediaRefCompensationScope(),
- migration: { sessionId: request.id, workingDir, workers: record.workers, agentPrefs },
+ migration: {
+ sessionId: request.id,
+ workingDir,
+ workers: record.workers,
+ agentPrefs,
+ externalTranscripts,
+ },
},
);
if (result.fidelity !== 'full') throw new Error('MIGRATION_INCOMPLETE_CONTEXT');
@@ -984,7 +1133,9 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
return { ...view(scope, null), estimate };
}
if (request.action === 'preflight') {
- await checkTargetResources(scope, request.targetProject, request.resources);
+ await checkTargetResources(scope, request.targetProject, request.resources).catch(
+ logTargetFailure('preflight', null),
+ );
return view(scope, null);
}
if (request.action === 'caps') {
@@ -994,6 +1145,7 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
...view(scope, null),
projects: await projects(scope),
teamMigration: true,
+ externalTranscripts: true,
copyEstimate: true,
agents: (['cc', 'codex', 'pi'] as const).filter(
(agent) => !!pickEnabledFallbackModel(providers, agent === 'cc' ? 'claude-code' : agent),
@@ -1003,7 +1155,8 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
if (request.action === 'receive' || request.action === 'receipt') {
const peer = getDeviceLinkInvokeContext()?.controllerDeviceId;
if (!peer || isSharedTaskPeer(peer)) throw new Error('MIGRATION_ACCESS_REVOKED');
- if (request.action === 'receive') return receive(scope, request, peer);
+ if (request.action === 'receive')
+ return receive(scope, request, peer).catch(logTargetFailure('receive', request.id));
const record = scope.readIncoming(request.id);
if (request.action === 'receipt') {
if (
@@ -1048,7 +1201,8 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
running.has(`${scope.root}:${record.sessionId}`)
)
throw new Error('MIGRATION_CANNOT_CANCEL');
- const cancelled = { ...record, stage: 'cancelled' as const, error: undefined };
+ // Closing a failed copy cancels it; keep its error code as the only trace of why.
+ const cancelled = { ...record, stage: 'cancelled' as const };
// Keep the journal retryable until its staging data is gone.
await cleanupOutgoing(scope, record);
scope.assertCurrent();
diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.ts
index ddbf4fe7c2..b925093acd 100644
--- a/apps/desktop/src/main/task-migration/workspace.ts
+++ b/apps/desktop/src/main/task-migration/workspace.ts
@@ -5,7 +5,8 @@ import { runRecoveryArchiveTask } from '../worktree/recoveryArchiveWorkerClient'
import type { FileEvidence, WorktreeRecoveryArchive } from '../worktree/recoveryArchiveIO';
import {
captureWorktreeContent,
- worktreeContentBaselineMatches,
+ worktreeStagedContentMatches,
+ WorktreeChangedDuringSnapshotError,
} from '../worktree/contentSnapshot';
import { gitExec, GitExecError } from '../worktree/gitExec';
import { assertDiskCapacity } from './resources';
@@ -69,6 +70,17 @@ export interface PortableWorkspace {
git?: { head: string; headRef: string | null; indexTree: string; ref: string };
}
+/** A project entry that blocks the copy; the path tells the user what to rename or remove. */
+export class MigrationPathError extends Error {
+ constructor(
+ readonly code: string,
+ /** Project-relative, `/`-separated. */
+ readonly relPath: string,
+ ) {
+ super(`${code}: ${relPath}`);
+ }
+}
+
/** Portable names only. In particular, links must never lead extraction outside its new root. */
export function validateWorkspaceEntries(files: Record<string, FileEvidence>): void {
const folded = new Set<string>();
@@ -90,10 +102,10 @@ export function validateWorkspaceEntries(files: Record<string, FileEvidence>): v
/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part),
)
) {
- throw new Error('MIGRATION_NONPORTABLE_PATH');
+ throw new MigrationPathError('MIGRATION_NONPORTABLE_PATH', name);
}
const key = name.normalize('NFC').toLowerCase();
- if (folded.has(key)) throw new Error('MIGRATION_PATH_COLLISION');
+ if (folded.has(key)) throw new MigrationPathError('MIGRATION_PATH_COLLISION', name);
folded.add(key);
if (
!entry ||
@@ -115,13 +127,14 @@ export function validateWorkspaceEntries(files: Record<string, FileEvidence>): v
path.posix.isAbsolute(entry.hash) ||
/^[a-z]:/i.test(entry.hash)
)
- throw new Error('MIGRATION_EXTERNAL_LINK');
+ 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 Error('MIGRATION_EXTERNAL_LINK');
+ 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 Error('MIGRATION_EXTERNAL_LINK');
+ 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')
@@ -152,7 +165,14 @@ export async function snapshotWorkspace(
throw new Error('MIGRATION_SUBMODULE_UNSUPPORTED');
const ref = `refs/cindy/migration/${id}`;
try {
- baseline = await captureWorktreeContent(root, ref);
+ // A copy only needs the captured content; another task's `git status` must not fail it.
+ baseline = await captureWorktreeContent(root, ref, { stagedContentOnly: true }).catch(
+ (error: unknown) => {
+ if (error instanceof WorktreeChangedDuringSnapshotError)
+ throw new Error('MIGRATION_WORKSPACE_CHANGED');
+ throw error;
+ },
+ );
git = {
head: baseline.head,
headRef: baseline.headRef ?? null,
@@ -195,7 +215,7 @@ export async function snapshotWorkspace(
if (entry.kind === 'file') unpackedBytes += (await fs.lstat(path.join(root, name))).size;
}
if (!Number.isSafeInteger(unpackedBytes)) throw new Error('MIGRATION_INVALID_MANIFEST');
- if (baseline && !(await worktreeContentBaselineMatches(root, baseline)))
+ if (baseline && !(await worktreeStagedContentMatches(root, baseline)))
throw new Error('MIGRATION_WORKSPACE_CHANGED');
return {
version: 1,
diff --git a/apps/desktop/src/main/worktree/contentSnapshot.ts b/apps/desktop/src/main/worktree/contentSnapshot.ts
index 285840aecc..25ed616e77 100644
--- a/apps/desktop/src/main/worktree/contentSnapshot.ts
+++ b/apps/desktop/src/main/worktree/contentSnapshot.ts
@@ -33,10 +33,57 @@ export async function worktreeContentBaselineMatches(
&& (snapshot.headRef === undefined || await readWorktreeHeadRef(worktreePath) === snapshot.headRef);
}
-/** Snapshot the actual HEAD, index and file tree without stashing or changing the live checkout. */
+/** Staged content of the live index, read from a copy so the live index is never locked or rewritten. */
+async function stagedTree(worktreePath: string): Promise<string | null> {
+ const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-index-'));
+ const index = path.join(temp, 'index');
+ try {
+ const { stdout: indexPath } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);
+ await fs.copyFile(indexPath.trim(), index);
+ const { stdout } = await gitExec(['write-tree'], worktreePath, {
+ extraEnv: { GIT_INDEX_FILE: index, GIT_OPTIONAL_LOCKS: '0' },
+ });
+ return stdout.trim();
+ } catch (error) {
+ // An index that no longer yields a tree (e.g. new merge conflicts) has changed.
+ if (error instanceof GitExecError) return null;
+ throw error;
+ } finally {
+ await fs.rm(temp, { recursive: true, force: true });
+ }
+}
+
+/**
+ * Same HEAD and staged content as the baseline. Unlike the byte hash above, this tolerates
+ * stat-cache refreshes (`git status` from another task rewrites the index without changing it),
+ * so a long snapshot of a repository in active use is not discarded for nothing.
+ */
+export async function worktreeStagedContentMatches(
+ worktreePath: string,
+ snapshot: NonNullable<WorktreeRecycleRecord['snapshot']>,
+): Promise<boolean> {
+ const { stdout } = await gitExec(['rev-parse', 'HEAD'], worktreePath);
+ return stdout.trim() === snapshot.head
+ && (snapshot.headRef === undefined || await readWorktreeHeadRef(worktreePath) === snapshot.headRef)
+ && await stagedTree(worktreePath) === snapshot.indexTree;
+}
+
+/** HEAD or the index moved while a snapshot was being captured. */
+export class WorktreeChangedDuringSnapshotError extends Error {
+ constructor() {
+ super('worktree HEAD or index changed during snapshot');
+ }
+}
+
+/**
+ * Snapshot the actual HEAD, index and file tree without stashing or changing the live checkout.
+ * `stagedContentOnly` checks consistency like {@link worktreeStagedContentMatches}, for callers
+ * that only need the captured content; the default byte comparison suits destructive recycling.
+ */
export async function captureWorktreeContent(
worktreePath: string,
ref: string,
+ { stagedContentOnly = false }: { stagedContentOnly?: boolean } = {},
): Promise<NonNullable<WorktreeRecycleRecord['snapshot']>> {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-index-'));
const index = path.join(temp, 'index');
@@ -70,7 +117,10 @@ export async function captureWorktreeContent(
const commit = commitOutput.trim();
await gitExec(['update-ref', ref, commit], worktreePath);
const snapshot = { head, headRef, tree, indexTree, commit, ref, indexHash: originalIndexHash };
- if (!(await worktreeContentBaselineMatches(worktreePath, snapshot))) throw new Error('worktree HEAD or index changed during snapshot');
+ const unchanged = stagedContentOnly
+ ? await worktreeStagedContentMatches(worktreePath, snapshot)
+ : await worktreeContentBaselineMatches(worktreePath, snapshot);
+ if (!unchanged) throw new WorktreeChangedDuringSnapshotError();
return snapshot;
} finally {
await fs.rm(temp, { recursive: true, force: true });
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 89e6082271..80ac288919 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
@@ -275,16 +275,25 @@ export function TaskMigrationDialog({
? t('taskMigration.estimateTimeout')
: estimateError === 'MIGRATION_TOO_MANY_FILES'
? t('taskMigration.estimateTooManyFiles', { limit: TASK_MIGRATION_MAX_FILES })
- : estimateError
+ : estimateError === 'MIGRATION_FAILED'
? t('taskMigration.estimateFailed')
- : estimate
- ? t('taskMigration.fileSummary', {
- count: estimate.fileCount,
- size: bytes(estimate.bytes),
+ : estimateError
+ ? // The source refused for a stated reason (e.g. queued input); never blame the connection.
+ t(`taskMigration.errors.${estimateError}`, {
+ defaultValue: t('taskMigration.estimateFailedWithCode', { code: estimateError }),
})
- : t('taskMigration.estimating');
+ : estimate
+ ? t('taskMigration.fileSummary', {
+ count: estimate.fileCount,
+ size: bytes(estimate.bytes),
+ })
+ : t('taskMigration.estimating');
const errorKey =
- failure && t(`taskMigration.errors.${failure}`, { defaultValue: t('taskMigration.failed') });
+ failure &&
+ t(`taskMigration.errors.${failure}`, {
+ // The code is the only lead once the dialog closes; keep it visible for unmapped errors.
+ defaultValue: t('taskMigration.failed', { code: failure }),
+ });
return (
<Dialog.Root
open
@@ -439,6 +448,20 @@ export function TaskMigrationDialog({
{failure && (
<p className="mt-3 text-sm text-[var(--error-fg)]" role="alert">
{errorKey}
+ {/* The path belongs to the source's recorded error, never to a local action error. */}
+ {failure === status?.error && status.errorPath && (
+ <span className="mt-1 block break-all">
+ {t('taskMigration.errorPath', { path: status.errorPath })}
+ </span>
+ )}
+ {failure === status?.error && status.errorSize && (
+ <span className="mt-1 block">
+ {t('taskMigration.errorSize', {
+ needed: bytes(status.errorSize.needed),
+ limit: bytes(status.errorSize.limit),
+ })}
+ </span>
+ )}
</p>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.i18n.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.i18n.test.tsx
new file mode 100644
index 0000000000..b7fdd0e7e7
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.i18n.test.tsx
@@ -0,0 +1,161 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router-dom';
+import { createInstance } from 'i18next';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import en from '@/i18n/locales/en/common.json';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+import type { Session } from '@/lib/ccAgent.types';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { TaskMigrationDialog } from '../TaskMigrationDialog';
+
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ remoteProjectsStore: {
+ captureSessionRead: () => Object.assign(() => true, { mergeActivity: (row: unknown) => row }),
+ mergeDeviceSessions: vi.fn(),
+ },
+}));
+
+const source = { id: 'task', title: 'Task', status: 'active', deviceLinkDeviceId: 'A' } as Session;
+let failure = '';
+let failurePath: string | undefined;
+let failureSize: { needed: number; limit: number } | undefined;
+let estimateFailure = '';
+beforeEach(() => {
+ failure = '';
+ failurePath = undefined;
+ failureSize = undefined;
+ estimateFailure = '';
+ setDataOwnerGeneration('owner');
+ Object.assign(window, {
+ electronAPI: {
+ deviceLink: {
+ taskMigration: async (device: string | null, command: { action: string }) => {
+ // Same encoding the main-process IPC error reaches the renderer with.
+ if (command.action === 'estimate' && estimateFailure)
+ throw new Error(`[PRECONDITION_FAILED] ${estimateFailure}`);
+ return {
+ supported: true,
+ deviceId: device ?? 'local',
+ ...(command.action === 'caps' ? { copyEstimate: true } : {}),
+ // A copy that stopped with an error, as the source reports it after a failure.
+ ...(command.action === 'status' && failure
+ ? {
+ stage: 'preparing',
+ running: false,
+ error: failure,
+ ...(failurePath ? { errorPath: failurePath } : {}),
+ ...(failureSize ? { errorSize: failureSize } : {}),
+ targetDeviceId: 'B',
+ targetSessionId: 'migrated',
+ }
+ : {}),
+ };
+ },
+ invoke: vi.fn(),
+ openLink: vi.fn(),
+ listDevices: async () => ({ devices: [] }),
+ },
+ },
+ });
+});
+afterEach(cleanup);
+
+const resources = [
+ ['en', en],
+ ['zh-CN', zhCN],
+ ['zh-TW', zhTW],
+ ['ja', ja],
+ ['ko', ko],
+] as const;
+
+async function mount(locale: string, resource: object) {
+ const i18n = createInstance();
+ await i18n.use(initReactI18next).init({
+ lng: locale,
+ resources: { [locale]: { translation: resource } },
+ interpolation: { escapeValue: false },
+ });
+ render(
+ <I18nextProvider i18n={i18n}>
+ <MemoryRouter>
+ <TaskMigrationDialog session={source} onDismiss={() => {}} />
+ </MemoryRouter>
+ </I18nextProvider>,
+ );
+}
+
+it.each(resources)(
+ 'keeps the code of an error without dedicated copy visible in %s',
+ async (locale, resource) => {
+ failure = 'MIGRATION_SNAPSHOT_MISSING';
+ await mount(locale, resource);
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toBe(
+ resource.taskMigration.failed.replace('{{code}}', 'MIGRATION_SNAPSHOT_MISSING'),
+ );
+ },
+);
+
+it.each(resources)('explains a workspace change during packing in %s', async (locale, resource) => {
+ failure = 'MIGRATION_WORKSPACE_CHANGED';
+ await mount(locale, resource);
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toBe(resource.taskMigration.errors.MIGRATION_WORKSPACE_CHANGED);
+ expect(alert.textContent).not.toContain('MIGRATION_');
+});
+
+it.each(resources)('names the blocking project entry in %s', async (locale, resource) => {
+ failure = 'MIGRATION_NONPORTABLE_PATH';
+ failurePath = 'apps/desktop/C:';
+ await mount(locale, resource);
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toBe(
+ resource.taskMigration.errors.MIGRATION_NONPORTABLE_PATH +
+ resource.taskMigration.errorPath.replace('{{path}}', 'apps/desktop/C:'),
+ );
+});
+
+it.each(resources)(
+ 'shows why the source refused to count files instead of blaming the connection in %s',
+ async (locale, resource) => {
+ const copy = resource.taskMigration;
+ const cases = [
+ // Queued input on the source task: its own reason, no connection/version hint.
+ ['MIGRATION_TASK_QUEUED', copy.errors.MIGRATION_TASK_QUEUED],
+ // No dedicated copy: keep the generic hint but name the code.
+ [
+ 'MIGRATION_OWNER_CHANGED',
+ copy.estimateFailedWithCode.replace('{{code}}', 'MIGRATION_OWNER_CHANGED'),
+ ],
+ // Old or unreachable source: the original connection/version hint.
+ ['MIGRATION_FAILED', copy.estimateFailed],
+ ] as const;
+ for (const [code, text] of cases) {
+ estimateFailure = code;
+ await mount(locale, resource);
+ expect((await screen.findByText(text)).getAttribute('role')).toBe('status');
+ cleanup();
+ }
+ },
+);
+
+it.each(resources)(
+ 'states how far a task history exceeds the copy limit in %s',
+ async (locale, resource) => {
+ failure = 'MIGRATION_NO_MEMORY';
+ failureSize = { needed: 950 * 1024 ** 2, limit: 512 * 1024 ** 2 };
+ await mount(locale, resource);
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toBe(
+ resource.taskMigration.errors.MIGRATION_NO_MEMORY +
+ resource.taskMigration.errorSize
+ .replace('{{needed}}', '950.0 MB')
+ .replace('{{limit}}', '512.0 MB'),
+ );
+ },
+);
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 1fd5e39bd4..654a522e40 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
@@ -403,6 +403,8 @@ it.each([
['[PRECONDITION_FAILED] MIGRATION_TIMEOUT', 'taskMigration.estimateTimeout'],
['[PRECONDITION_FAILED] MIGRATION_TOO_MANY_FILES', 'taskMigration.estimateTooManyFiles'],
['[PRECONDITION_FAILED] MIGRATION_FAILED', 'taskMigration.estimateFailed'],
+ // A refusal with its own reason must not be reported as a connection/version problem.
+ ['[PRECONDITION_FAILED] MIGRATION_TASK_QUEUED', 'taskMigration.errors.MIGRATION_TASK_QUEUED'],
])('explains why inventory failed (%s) and keeps Copy disabled', async (message, text) => {
const original = state.request.getMockImplementation()!;
state.request.mockImplementation((device, command) =>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5d69b4a8ed..a922ae102e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -23,7 +23,9 @@
"close": "Close",
"cancel": "Cancel",
"start": "Copy task",
- "failed": "Copy did not finish. Check both computers before copying again.",
+ "failed": "Copy did not finish. Check both computers before copying again. ({{code}})",
+ "errorPath": "File: {{path}}",
+ "errorSize": "Needs about {{needed}}; the limit is about {{limit}}.",
"stages": {
"preparing": "Preparing a snapshot…",
"transferring": "Transferring and checking files…",
@@ -36,7 +38,7 @@
"MIGRATION_TASK_RUNNING": "Stop the task before copying it.",
"MIGRATION_SHARED_DIRECTORY_BUSY": "Another task is using this directory. Stop it before retrying.",
"MIGRATION_TASK_UNSUPPORTED": "This task's type or current state does not support copying to another computer.",
- "MIGRATION_NO_MEMORY": "Not enough available memory to process the complete task history. Free up memory and retry.",
+ "MIGRATION_NO_MEMORY": "The task history is too large for a copy to process.",
"MIGRATION_INCOMPLETE_CONTEXT": "The complete task history is unavailable. Copy stopped to avoid losing context.",
"MIGRATION_EXTERNAL_LINK": "The project contains links outside this directory or unsupported link chains. Source files are unchanged.",
"MIGRATION_REQUIRES_REPOSITORY_ROOT": "For Git projects, the task directory must be the repository root.",
@@ -47,7 +49,13 @@
"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_CANNOT_CANCEL": "The target computer has started creating the task. The copy can no longer be cancelled."
+ "MIGRATION_CANNOT_CANCEL": "The target computer has started creating the task. The copy can no longer be cancelled.",
+ "MIGRATION_WORKSPACE_CHANGED": "The project's Git commit or staged changes changed while packing. Try copying again later.",
+ "MIGRATION_TEAM_CHANGED": "The members of this collaboration task changed. Start the copy again.",
+ "MIGRATION_NONPORTABLE_PATH": "The project contains file names that other systems cannot use. Source files are unchanged.",
+ "MIGRATION_PATH_COLLISION": "The project contains file names that differ only in letter case. Source files are unchanged.",
+ "MIGRATION_NOT_CONNECTED": "This computer is not connected. Make sure you are signed in and remote control is on, then try again.",
+ "MIGRATION_TASK_BUSY": "This task is already being copied or is in use by another operation. Try again later."
},
"successTitle": "Copy successful",
"successDescription": "Copied to {{name}}.",
@@ -66,6 +74,7 @@
"fileSummary": "Project files: {{count}}, totaling {{size}}",
"estimateNote": "Pre-copy estimate including hidden files. Git history, conversation and attachments are copied separately and excluded from this size. Files may change before copying.",
"estimateFailed": "Could not count files. Check the source computer’s connection and version, then close and try again.",
+ "estimateFailedWithCode": "Could not count files. Check the source computer’s connection and version, then close and try again. ({{code}})",
"estimateTimeout": "Counting timed out: the project has too many files for the source computer to finish in time. Try copying a project with fewer files.",
"estimateTooManyFiles": "The project has more than {{limit, number}} files and cannot be copied. Copy a project with fewer files instead."
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6117443ee7..14ae1eff0a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -23,7 +23,9 @@
"close": "閉じる",
"cancel": "キャンセル",
"start": "タスクをコピー",
- "failed": "コピーが完了しませんでした。両方のコンピューターを確認してから再度コピーしてください。",
+ "failed": "コピーが完了しませんでした。両方のコンピューターを確認してから再度コピーしてください。({{code}})",
+ "errorPath": "該当ファイル:{{path}}",
+ "errorSize": "必要量 約 {{needed}}、上限 約 {{limit}}。",
"stages": {
"preparing": "スナップショットを準備中…",
"transferring": "ファイルを転送・検証中…",
@@ -36,7 +38,7 @@
"MIGRATION_TASK_RUNNING": "コピーする前にタスクを停止してください。",
"MIGRATION_SHARED_DIRECTORY_BUSY": "別のタスクがこのフォルダーを使用しています。停止してから再試行してください。",
"MIGRATION_TASK_UNSUPPORTED": "このタスクの種類または現在の状態では、別のコンピューターにコピーできません。",
- "MIGRATION_NO_MEMORY": "タスク履歴全体を処理するためのメモリが不足しています。メモリを解放して再試行してください。",
+ "MIGRATION_NO_MEMORY": "タスク履歴が大きすぎて、コピー時に処理できる上限を超えています。",
"MIGRATION_INCOMPLETE_CONTEXT": "タスク履歴が不完全なため、コピーを停止しました。",
"MIGRATION_EXTERNAL_LINK": "フォルダー外へのリンク、または未対応のリンクチェーンがあります。元のファイルは変更されていません。",
"MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git プロジェクトでは、タスクのフォルダーがリポジトリのルートである必要があります。",
@@ -47,7 +49,13 @@
"MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。",
"MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。",
"MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。",
- "MIGRATION_CANNOT_CANCEL": "移行先のコンピューターでタスクの作成が始まったため、キャンセルできません。"
+ "MIGRATION_CANNOT_CANCEL": "移行先のコンピューターでタスクの作成が始まったため、キャンセルできません。",
+ "MIGRATION_WORKSPACE_CHANGED": "パッケージ作成中にプロジェクトの Git コミットまたはステージ済みの内容が変更されました。しばらくしてからコピーを再試行してください。",
+ "MIGRATION_TEAM_CHANGED": "協同タスクのメンバーが変更されました。コピーをやり直してください。",
+ "MIGRATION_NONPORTABLE_PATH": "ほかのシステムで使用できないファイル名が含まれています。元のファイルは変更されていません。",
+ "MIGRATION_PATH_COLLISION": "大文字と小文字だけが異なる同名ファイルが含まれています。元のファイルは変更されていません。",
+ "MIGRATION_NOT_CONNECTED": "このコンピューターは接続されていません。ログインしてリモート操作がオンになっていることを確認してから再試行してください。",
+ "MIGRATION_TASK_BUSY": "このタスクはコピー中か、別の操作で使用中です。しばらくしてから再試行してください。"
},
"successTitle": "コピー完了",
"successDescription": "{{name}}にコピーしました。",
@@ -66,6 +74,7 @@
"fileSummary": "プロジェクトファイル:{{count}} 個、合計 {{size}}",
"estimateNote": "隠しファイルを含むコピー前の推定値です。別途コピーする Git 履歴、タスクの会話と添付ファイルは含みません。ファイルの変更により最終サイズは変わります。",
"estimateFailed": "集計できませんでした。コピー元の接続とバージョンを確認し、閉じて再試行してください。",
+ "estimateFailedWithCode": "集計できませんでした。コピー元の接続とバージョンを確認し、閉じて再試行してください。({{code}})",
"estimateTimeout": "集計がタイムアウトしました。プロジェクトのファイルが多すぎるため、コピー元が時間内に集計を完了できませんでした。ファイル数の少ないプロジェクトをコピーしてください。",
"estimateTooManyFiles": "プロジェクトのファイルが {{limit, number}} 個を超えているため、コピーできません。ファイル数の少ないプロジェクトをコピーしてください。"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e69f25d19d..236f5d01d3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -23,7 +23,9 @@
"close": "닫기",
"cancel": "취소",
"start": "작업 복사",
- "failed": "복사가 완료되지 않았습니다. 두 컴퓨터를 확인한 후 다시 복사하세요.",
+ "failed": "복사가 완료되지 않았습니다. 두 컴퓨터를 확인한 후 다시 복사하세요. ({{code}})",
+ "errorPath": "문제 파일: {{path}}",
+ "errorSize": "필요한 용량 약 {{needed}}, 한도 약 {{limit}}.",
"stages": {
"preparing": "스냅샷 준비 중…",
"transferring": "파일 전송 및 검증 중…",
@@ -36,7 +38,7 @@
"MIGRATION_TASK_RUNNING": "복사하기 전에 작업을 중지하세요.",
"MIGRATION_SHARED_DIRECTORY_BUSY": "다른 작업이 이 폴더를 사용 중입니다. 중지한 후 다시 시도하세요.",
"MIGRATION_TASK_UNSUPPORTED": "이 작업의 유형 또는 현재 상태에서는 다른 컴퓨터로 복사할 수 없습니다.",
- "MIGRATION_NO_MEMORY": "전체 작업 기록을 처리할 메모리가 부족합니다. 메모리를 확보한 후 다시 시도하세요.",
+ "MIGRATION_NO_MEMORY": "작업 기록이 너무 커서 복사할 때 처리할 수 있는 한도를 넘었습니다.",
"MIGRATION_INCOMPLETE_CONTEXT": "전체 작업 기록을 가져올 수 없어 복사을 중지했습니다.",
"MIGRATION_EXTERNAL_LINK": "폴더 외부 링크 또는 지원되지 않는 링크 체인이 있습니다. 원본 파일은 변경되지 않았습니다.",
"MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git 프로젝트의 작업 폴더는 저장소 루트여야 합니다.",
@@ -47,7 +49,13 @@
"MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.",
"MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요.",
"MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요.",
- "MIGRATION_CANNOT_CANCEL": "대상 컴퓨터에서 작업 생성이 시작되어 더 이상 취소할 수 없습니다."
+ "MIGRATION_CANNOT_CANCEL": "대상 컴퓨터에서 작업 생성이 시작되어 더 이상 취소할 수 없습니다.",
+ "MIGRATION_WORKSPACE_CHANGED": "패키징 중 프로젝트의 Git 커밋 또는 스테이징된 내용이 변경되었습니다. 잠시 후 다시 복사하세요.",
+ "MIGRATION_TEAM_CHANGED": "협업 작업의 구성원이 변경되었습니다. 복사를 다시 시작하세요.",
+ "MIGRATION_NONPORTABLE_PATH": "다른 시스템에서 사용할 수 없는 파일 이름이 있습니다. 원본 파일은 변경되지 않았습니다.",
+ "MIGRATION_PATH_COLLISION": "대소문자만 다른 같은 이름의 파일이 있습니다. 원본 파일은 변경되지 않았습니다.",
+ "MIGRATION_NOT_CONNECTED": "이 컴퓨터가 연결되어 있지 않습니다. 로그인되어 있고 원격 제어가 켜져 있는지 확인한 후 다시 시도하세요.",
+ "MIGRATION_TASK_BUSY": "이 작업은 이미 복사 중이거나 다른 작업에서 사용 중입니다. 잠시 후 다시 시도하세요."
},
"successTitle": "복사 완료",
"successDescription": "{{name}}에 복사했습니다.",
@@ -66,6 +74,7 @@
"fileSummary": "프로젝트 파일: {{count}}개, 총 {{size}}",
"estimateNote": "숨김 파일을 포함한 복사 전 예상치입니다. 별도로 복사하는 Git 기록, 작업 대화 및 첨부 파일은 제외됩니다. 파일 변경에 따라 최종 크기가 달라질 수 있습니다.",
"estimateFailed": "파일을 집계하지 못했습니다. 원본 컴퓨터의 연결과 버전을 확인한 후 닫고 다시 시도하세요.",
+ "estimateFailedWithCode": "파일을 집계하지 못했습니다. 원본 컴퓨터의 연결과 버전을 확인한 후 닫고 다시 시도하세요. ({{code}})",
"estimateTimeout": "집계 시간이 초과되었습니다. 프로젝트 파일이 너무 많아 원본 컴퓨터가 제한 시간 내에 집계하지 못했습니다. 파일이 더 적은 프로젝트를 복사해 보세요.",
"estimateTooManyFiles": "프로젝트 파일이 {{limit, number}}개를 넘어 복사할 수 없습니다. 파일이 더 적은 프로젝트를 복사하세요."
},
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 f5fdec1947..3140b1615c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -23,7 +23,9 @@
"close": "关闭",
"cancel": "取消",
"start": "复制任务",
- "failed": "复制未完成,请检查两台电脑后重新复制。",
+ "failed": "复制未完成,请检查两台电脑后重新复制。({{code}})",
+ "errorPath": "问题文件:{{path}}",
+ "errorSize": "需要约 {{needed}},上限约 {{limit}}。",
"stages": {
"preparing": "正在准备快照…",
"transferring": "正在传输并校验文件…",
@@ -36,7 +38,7 @@
"MIGRATION_TASK_RUNNING": "请先停止任务再复制。",
"MIGRATION_SHARED_DIRECTORY_BUSY": "其他任务正在使用此目录,请停止后重试。",
"MIGRATION_TASK_UNSUPPORTED": "此任务的类型或当前状态暂不支持跨电脑复制。",
- "MIGRATION_NO_MEMORY": "可用内存不足以处理完整任务历史,请释放内存后重试。",
+ "MIGRATION_NO_MEMORY": "任务历史太大,超出了复制时能处理的上限。",
"MIGRATION_INCOMPLETE_CONTEXT": "无法取得完整任务历史,已停止复制以免丢失上下文。",
"MIGRATION_EXTERNAL_LINK": "项目包含指向目录外部的链接或暂不支持的链接链,源文件未改动。",
"MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git 项目的任务目录必须是仓库根目录。",
@@ -47,7 +49,13 @@
"MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。",
"MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。",
"MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。",
- "MIGRATION_CANNOT_CANCEL": "目标电脑已开始创建任务,无法再取消。"
+ "MIGRATION_CANNOT_CANCEL": "目标电脑已开始创建任务,无法再取消。",
+ "MIGRATION_WORKSPACE_CHANGED": "打包期间项目的 Git 提交或已暂存内容发生变化,请稍后重试复制。",
+ "MIGRATION_TEAM_CHANGED": "协同任务的成员发生变化,请重新发起复制。",
+ "MIGRATION_NONPORTABLE_PATH": "项目包含其他系统无法使用的文件名,源文件未改动。",
+ "MIGRATION_PATH_COLLISION": "项目包含仅大小写不同的同名文件,源文件未改动。",
+ "MIGRATION_NOT_CONNECTED": "这台电脑尚未连接,请确认已登录并开启远程控制后重试。",
+ "MIGRATION_TASK_BUSY": "此任务正在复制或被其他操作占用,请稍后重试。"
},
"successTitle": "复制成功",
"successDescription": "已复制到{{name}}。",
@@ -66,6 +74,7 @@
"fileSummary": "项目文件:{{count}} 个,共 {{size}}",
"estimateNote": "复制前估算,含隐藏文件;不含另行复制的 Git 历史、任务对话及附件。文件变化可能影响最终大小。",
"estimateFailed": "无法统计文件。请检查任务所在电脑的连接和版本,然后关闭重试。",
+ "estimateFailedWithCode": "无法统计文件。请检查任务所在电脑的连接和版本,然后关闭重试。({{code}})",
"estimateTimeout": "统计超时:项目文件过多,任务所在电脑未能在时限内完成统计。可以改为复制文件更少的项目。",
"estimateTooManyFiles": "项目文件超过 {{limit, number}} 个,无法复制。请改为复制文件更少的项目。"
},
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 54f83be2e1..17a5ce7598 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -23,7 +23,9 @@
"close": "關閉",
"cancel": "取消",
"start": "複製任務",
- "failed": "複製未完成,請檢查兩台電腦後重新複製。",
+ "failed": "複製未完成,請檢查兩台電腦後重新複製。({{code}})",
+ "errorPath": "問題檔案:{{path}}",
+ "errorSize": "需要約 {{needed}},上限約 {{limit}}。",
"stages": {
"preparing": "正在準備快照…",
"transferring": "正在傳輸並驗證檔案…",
@@ -36,7 +38,7 @@
"MIGRATION_TASK_RUNNING": "請先停止任務再複製。",
"MIGRATION_SHARED_DIRECTORY_BUSY": "其他任務正在使用此目錄,請停止後重試。",
"MIGRATION_TASK_UNSUPPORTED": "此任務的類型或目前狀態尚不支援跨電腦複製。",
- "MIGRATION_NO_MEMORY": "可用記憶體不足以處理完整任務歷史,請釋放記憶體後重試。",
+ "MIGRATION_NO_MEMORY": "任務歷史太大,超出了複製時能處理的上限。",
"MIGRATION_INCOMPLETE_CONTEXT": "無法取得完整任務歷史,已停止複製以免遺失上下文。",
"MIGRATION_EXTERNAL_LINK": "專案包含指向目錄外部的連結或尚不支援的連結鏈,來源檔案未變更。",
"MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git 專案的任務目錄必須是儲存庫根目錄。",
@@ -47,7 +49,13 @@
"MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。",
"MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。",
"MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。",
- "MIGRATION_CANNOT_CANCEL": "目標電腦已開始建立任務,無法再取消。"
+ "MIGRATION_CANNOT_CANCEL": "目標電腦已開始建立任務,無法再取消。",
+ "MIGRATION_WORKSPACE_CHANGED": "打包期間專案的 Git 提交或已暫存內容發生變更,請稍後重試複製。",
+ "MIGRATION_TEAM_CHANGED": "協同任務的成員發生變更,請重新發起複製。",
+ "MIGRATION_NONPORTABLE_PATH": "專案包含其他系統無法使用的檔案名稱,來源檔案未變更。",
+ "MIGRATION_PATH_COLLISION": "專案包含僅大小寫不同的同名檔案,來源檔案未變更。",
+ "MIGRATION_NOT_CONNECTED": "這台電腦尚未連線,請確認已登入並開啟遠端控制後重試。",
+ "MIGRATION_TASK_BUSY": "此任務正在複製或被其他操作佔用,請稍後重試。"
},
"successTitle": "複製成功",
"successDescription": "已複製到{{name}}。",
@@ -66,6 +74,7 @@
"fileSummary": "專案檔案:{{count}} 個,共 {{size}}",
"estimateNote": "複製前估算,含隱藏檔案;不含另行複製的 Git 歷史、任務對話及附件。檔案變化可能影響最終大小。",
"estimateFailed": "無法統計檔案。請檢查任務所在電腦的連線和版本,然後關閉重試。",
+ "estimateFailedWithCode": "無法統計檔案。請檢查任務所在電腦的連線和版本,然後關閉重試。({{code}})",
"estimateTimeout": "統計逾時:專案檔案過多,任務所在電腦未能在時限內完成統計。可以改為複製檔案較少的專案。",
"estimateTooManyFiles": "專案檔案超過 {{limit, number}} 個,無法複製。請改為複製檔案較少的專案。"
},
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1224b99245..5df5299b90 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -246,6 +246,26 @@ OSS 保底仍受服务端 presign 单对象上限(`OSS_ATTACHMENT_MAX_BYTES`
文件读取(`open`)仍沿用 `FILE_PEER_MAX_BYTES`。不新增 channel、relay 类型或持久化 schema,
服务端无需改动。
+## 任务复制的外置会话记录与超限大小
+
+`maker:task-copy` 的 `caps` 追加 `externalTranscripts: true`。源端在每次准备时询问;目标声明后,
+32 MiB 以上的原生会话记录不放进任务包,`receive` 的 `files` 追加可选 `transcripts: MigrationFile[]`
+(至多 256 个,逐项校验大小与分段之和;源端准备时超出即报 `MIGRATION_NO_MEMORY`,不先上传),顺序与对应关系记在随包的 `workspace.json`
+`transcripts[{path, file, bytes}]`;`path` 是包内会话记录引用的路径,目标只把它当映射键,
+落盘文件名由目标按序号生成。`preflight` 的 `resources` 追加可选 `transcriptBytes`,目标据此预检
+暂存与用户目录所在磁盘。旧目标不声明能力,源端继续随包携带;旧源端不发新字段。
+
+状态追加可选 `errorSize: {needed, limit}`:源端判定内存超限时的字节数,与 `errorPath` 同样只随
+`error` 下发并一并清除。目标端失败只回传错误码,原始报错与数字记在目标日志。
+
+## 任务复制失败的问题路径
+
+`maker:task-copy` 的状态(`TaskMigrationView`)在 `error` 之外追加可选 `errorPath`:源端打包时
+文件名不可移植、仅大小写不同或链接越界,导致复制失败的那一项的项目内相对路径(`/` 分隔,至多
+1024 字符)。只在 `error` 存在时下发,进入下一阶段或重新发起复制时与 `error` 一并清除;源端复制
+记录里同名可选字段,旧记录缺省。旧源端不下发,控制端只显示错误提示;旧控制端忽略该字段。
+不新增 channel、relay 类型或持久化 schema,服务端无需改动。
+
## 事实来源
| 内容 | 权威来源 |
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index a7adbc9559..3f58ee361e 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -16,6 +16,7 @@
导出与目录快照完成后复核成员、运行/排队状态和任务更新时间;发生变化则留在准备阶段重试,
不发布这次副本。该检查不冻结输入,也不承诺外部编辑器与数据库的跨进程原子快照。
复制是一次快照,不持续同步;源任务后续变化不会更新副本。快照遇到文件变化会失败并允许重试。
+ Git 项目以 HEAD、分支与暂存区内容判定变化;其它任务的 `git status` 等只刷新 index 缓存、不改内容,不算变化。
2. 复用任务分享导出、原生上下文恢复及 worktree 快照。包含未提交、未跟踪和忽略文件;
仓库已登记、位于 `.cindy-worktrees`(旧名 `.xdt-worktrees`)下的其它任务 worktree 不随副本复制,
也不计入统计;在这些 worktree 里运行的任务不阻止复制。这些文件夹里的其它内容、非 Git 目录照常复制。
@@ -23,11 +24,16 @@
目标始终创建独立目录,不覆盖已有项目。整组共享物理目录只复制一份,独立目录分别创建。
3. 复用 peer 直传及 OSS 回退、冷却。按实时磁盘和可用内存预算准备、发送、接收及解包,
不设任务总大小上限;大文件按现有单对象传输容量分段,校验大小及 SHA-256 后解包。
+ 目标声明 `externalTranscripts` 时,32 MiB 以上的原生会话记录(Codex rollout、Claude、Pi,含 Worker)
+ 不进内存里的任务包,流式暂存、单独发送,目标逐行改写会话 ID 后原子落位,内存只随其中最长的一行增长(单行接近字符串上限属已知边界);
+ 能力在每次准备时询问,旧目标仍随包携带。Cindy 消息与附件仍整体在内存中处理。
4. 目标以复制 ID 幂等导入,整组沿用已有团队事务。导入成功即可使用目标任务,
不等待源端让出执行权,也不自动开始模型回合。任务使用目标模型设置,权限回到需要确认的模式。
5. 确认页使用接收电脑名称或“本机”,展示项目文件数量与复制前估算大小(含隐藏/忽略文件,整组共享目录去重)。
Git 历史、任务对话与附件另行复制,不计入项目文件统计;统计完成前不能开始复制。
`copyEstimate` 能力存在时才调用 `estimate`;旧源端无法统计时明确提示连接/版本检查,不开始复制。
+ 源端以明确原因拒绝统计(如任务有排队中的消息 `MIGRATION_TASK_QUEUED`)时显示该原因,不提示连接/版本;
+ 没有专门文案的错误码仍提示连接/版本并附错误码。
统计在任务所在电脑上按 3 分钟截止(本机任务同样适用;文件系统调用本身卡住时无法中断,属已知边界),超时时提示项目文件过多,不提示连接/版本;项目文件超过 50 万个时提前停止统计,
提示改为复制文件更少的项目,不开始复制。该上限只是确认页的准入检查,复制本身仍不设总量上限。
6. 复制进行中的弹窗可通过「后台继续」或 Esc 关闭,关闭不中断复制,之后从原任务顶部的复制状态重新查看进度
@@ -39,6 +45,12 @@
OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。
文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。
成功页只提供关闭和“打开新复制的任务”。失败页只提供关闭,关闭会复用完成路径清理已上传的 OSS 对象及本地暂存,结束本次源端复制;目标端可能已提交的副本不会回滚。
+ 失败页优先显示对应原因;没有专门文案的错误显示通用提示并附错误码。文件名不可移植、仅大小写不同
+ 或链接指向目录外时,同时显示出问题的项目内相对路径。源端把原始报错写入日志,
+ 关闭后复制记录仍保留错误码,直到再次发起复制,便于事后排查。
+ 任务历史超出内存上限时说明是历史过大(不提示释放内存),源端判定时附「需要约 X,上限约 Y」,
+ 日志记录预算各组成;目标版本旧、需随包携带原生会话记录而超限,且拆出 32 MiB 以上的会话记录后即可装下时,提示更新两台电脑;
+ 拆出后仍超限则照常报历史过大。
再次复制从任务菜单发起。宿主异常退出后的既有幂等恢复协议保留,不自动重试。
源端仅记录 `preparing → transferring → complete`(运行中在目标接收前、或停止运行后可结束为 `cancelled`);目标记录接收与完成。
diff --git a/packages/device-link/src/__tests__/taskMigration.test.ts b/packages/device-link/src/__tests__/taskMigration.test.ts
index 4e27d7175e..fe50b6735b 100644
--- a/packages/device-link/src/__tests__/taskMigration.test.ts
+++ b/packages/device-link/src/__tests__/taskMigration.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
TASK_MIGRATION_CHANNEL,
TASK_MIGRATION_LOCAL_CHANNEL,
+ TASK_MIGRATION_MAX_TRANSCRIPTS,
parseTaskMigrationRequest,
} from "../taskMigration.js";
import { REMOTE_INVOKE_ALLOWLIST } from "../allowlist.js";
@@ -155,4 +156,65 @@ describe("task copy protocol", () => {
parseTaskMigrationRequest({ ...receive, targetProject: "bad\0path" }),
).toThrow();
});
+ it("validates native transcripts sent beside the package", () => {
+ const file = { ref: "reference", size: 100, sha256: "a".repeat(64) };
+ const receive = {
+ action: "receive",
+ id: "01234567-0123-4123-a123-012345678901",
+ sourceSessionId: "source",
+ targetProject: null,
+ files: { session: file, manifest: file, workspace: file },
+ };
+ const large = {
+ size: 4 * 1024 ** 3,
+ parts: [
+ { ...file, size: 2 * 1024 ** 3 },
+ { ...file, size: 2 * 1024 ** 3 },
+ ],
+ };
+ expect(
+ parseTaskMigrationRequest({
+ ...receive,
+ files: { ...receive.files, transcripts: [file, large] },
+ }),
+ ).toMatchObject({ files: { transcripts: [file, large] } });
+ for (const transcripts of [
+ null,
+ {},
+ [null],
+ [{ ...file, size: 0 }],
+ [{ size: 101, parts: [file] }],
+ Array.from({ length: TASK_MIGRATION_MAX_TRANSCRIPTS + 1 }, () => file),
+ ])
+ expect(() =>
+ parseTaskMigrationRequest({
+ ...receive,
+ files: { ...receive.files, transcripts },
+ }),
+ ).toThrow();
+ const resources = {
+ transferBytes: 1,
+ unpackedBytes: 1,
+ contextBytes: 1,
+ manifestBytes: 1,
+ repositoryBytes: 0,
+ entries: 1,
+ };
+ for (const transcriptBytes of [undefined, 0, 900 * 1024 ** 2])
+ expect(
+ parseTaskMigrationRequest({
+ action: "preflight",
+ targetProject: null,
+ resources: { ...resources, transcriptBytes },
+ }),
+ ).toBeDefined();
+ for (const transcriptBytes of [-1, 1.5, "1"])
+ expect(() =>
+ parseTaskMigrationRequest({
+ action: "preflight",
+ targetProject: null,
+ resources: { ...resources, transcriptBytes },
+ }),
+ ).toThrow();
+ });
});
diff --git a/packages/device-link/src/taskMigration.ts b/packages/device-link/src/taskMigration.ts
index 79d560c8a6..3b701e8bd4 100644
--- a/packages/device-link/src/taskMigration.ts
+++ b/packages/device-link/src/taskMigration.ts
@@ -5,6 +5,8 @@ export const TASK_MIGRATION_LOCAL_CHANNEL = "task-copy:request";
export const TASK_MIGRATION_MAX_FILES = 500_000;
export const TASK_MIGRATION_ESTIMATE_TIMEOUT_MS = 3 * 60_000;
export const TASK_MIGRATION_RECEIVE_TIMEOUT_MS = 30 * 60_000;
+/** Most transcripts one copy sends beside its conversation package. */
+export const TASK_MIGRATION_MAX_TRANSCRIPTS = 256;
export interface MigrationFileRef {
ref: string;
size: number;
@@ -19,6 +21,8 @@ export interface MigrationResources {
manifestBytes: number;
repositoryBytes: number;
entries: number;
+ /** Native transcripts sent as separate files; absent from older sources. */
+ transcriptBytes?: number;
}
export interface MigrationFiles {
session: MigrationFile;
@@ -29,6 +33,11 @@ export interface MigrationFiles {
workspace: MigrationFile;
repository?: MigrationFile;
}>;
+ /**
+ * Native transcripts kept out of the conversation package, in the order the copy's
+ * workspace manifest lists them. Only sent to targets declaring `externalTranscripts`.
+ */
+ transcripts?: MigrationFile[];
}
export type TaskMigrationRequest =
| {
@@ -85,10 +94,16 @@ export interface TaskMigrationView {
targetDeviceId?: string;
targetSessionId?: string;
error?: string;
+ /** Project-relative entry blamed for `error` (e.g. a non-portable name). Absent on older hosts. */
+ errorPath?: string;
projects?: string[];
agents?: Array<"cc" | "codex" | "pi">;
/** Entire Orca graph, native contexts and per-member workspaces. Absence means unsupported. */
teamMigration?: true;
+ /** Accepts `files.transcripts` (large native transcripts streamed outside the package). */
+ externalTranscripts?: true;
+ /** Bytes needed vs the limit, when `error` is a size failure. Absent on older hosts. */
+ errorSize?: { needed: number; limit: number };
}
export function parseTaskMigrationRequest(
@@ -136,6 +151,12 @@ export function parseTaskMigrationRequest(
] as const)
if (!Number.isSafeInteger(resources[key]) || resources[key] < 0)
throw new Error("MIGRATION_INVALID_REQUEST");
+ if (
+ resources.transcriptBytes !== undefined &&
+ (!Number.isSafeInteger(resources.transcriptBytes) ||
+ resources.transcriptBytes < 0)
+ )
+ throw new Error("MIGRATION_INVALID_REQUEST");
return {
action: "preflight",
targetProject: (r.targetProject as string | null) ?? null,
@@ -182,6 +203,12 @@ export function parseTaskMigrationRequest(
))
)
throw new Error("MIGRATION_INVALID_REQUEST");
+ if (
+ files.transcripts !== undefined &&
+ (!Array.isArray(files.transcripts) ||
+ files.transcripts.length > TASK_MIGRATION_MAX_TRANSCRIPTS)
+ )
+ throw new Error("MIGRATION_INVALID_REQUEST");
const allFiles = [
files.session,
files.workspace,
@@ -191,6 +218,7 @@ export function parseTaskMigrationRequest(
entry.workspace,
...(entry.repository ? [entry.repository] : []),
]),
+ ...(files.transcripts ?? []),
];
for (const file of allFiles) {
if (!file || !Number.isSafeInteger(file.size) || file.size <= 0)