Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(tasks): 统一任务移动并支持跨电脑复制 (#5112)
Dash0bf55124a7df
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex 6955ad680e..a89a87c72b 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -17,6 +17,7 @@ vi.mock('electron', () => ({app: { getVersion: () => '1.0.0' },}));// This suite exercises dispatch authorization, not authenticated ICE HTTP setup.+vi.mock('../task-migration/service', () => ({ requestTaskMigration: vi.fn() }));vi.mock('../remote-desktop/iceConfig', () => ({ loadDesktopIceServers: vi.fn(async () => []) }));// media:fetch 拦截走 mediaFetch.fetchLocalMediaToOss;mock 掉避免拉起 OSS/cache-store 真实依赖。const fetchLocalMediaToOssMock = vi.hoisted(() => vi.fn());diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 05a01d3e0e..93014f2807 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1,5 +1,6 @@import { listWorktreeRecycleStatus, controlWorktreeRecycle } from './worktree/recycleControls';import { registerFilePeerIpc } from './device-link/filePeer';+import { registerTaskMigrationIpc } from './task-migration/service';import { registerLoginItemIpc } from './login-item-ipc.js';import {createLatestSourceVersionReader,@@ -62,7 +63,7 @@ import {type WebContents,} from 'electron';import { resolveVibrancyConfig } from './vibrancyConfig';-import { getSessionThinkingSnapshots, getHistoryToolName } from './messagePersistBroadcaster';+import { getSessionThinkingSnapshots, getHistoryToolName, drainPersistQueue } from './messagePersistBroadcaster';import { applyVibrancyToSecondaryWindows } from './secondary-windows';import { rememberResolvedAppTheme, resolveAppThemeIsDark } from './resolved-app-theme';import {@@ -763,6 +764,7 @@ import {registerMakerIpc as registerMakerCoreIpc,restoreBotRuntimeForCurrentOwner,isSessionTurnPendingCompletion,+ isSessionInTurn,stopOrcaIdleWatcher,setGoalClearObserver,setGoalDeferredResumeCancelObserver,@@ -771,6 +773,7 @@ import {setGoalAskAnswerObserver,withSendToSessionLock,} from './maker-ipc/register.js';+import { moveSessionProjectFromHost } from './mcp-integrations/moveSession.js';import { cleanupActiveReviewArtifactSnapshots } from './reviewer/reviewArtifactSnapshot.js';import { MAKER_INVOKE as MAKER_IPC_INVOKE, MAKER_PUSH, MAKER_SEND } from './maker-ipc/channels.js';import {@@ -9614,6 +9617,13 @@ app.on('ready', async () => {// owning modules above; future collections/actions do not add tunnel channels.registerRemoteResourcesIpc();registerDeviceLinkIpc();+ registerTaskMigrationIpc((sessionId, workingDir, assertAuthority) =>+ moveSessionProjectFromHost(isSessionInTurn, sessionId, workingDir, assertAuthority),+ {+ isBusy: (id) => isSessionInTurn(id) || isSessionTurnPendingCompletion(id),+ drain: drainPersistQueue,+ },+ );registerSharedTaskIpc(isSharedTaskAvailable, () => getDeviceLinkStatus() === 'online');registerFilePeerIpc();registerRemoteDesktopIpc(isGlobalVoiceInputOverlaySender);diff --git a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.tsindex 9b4d511984..1792dba854 100644--- a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts@@ -546,6 +546,13 @@ describe('uploadBuffer — 内存字节(base64 附件)', () => {});describe('downloadToFile — 原子完整性校验', () => {+ it('拒绝超出声明大小的流,不发布目标文件', async () => {+ netFetchMock.mockResolvedValue({ ok: true, status: 200, body: webBody(Uint8Array.from([1, 2, 3])) });+ await expect(downloadToFile(KEY, '/tmp/final.bin', { size: 1, sha256: 'a'.repeat(64) }))+ .rejects.toThrow('附件下载超出声明大小');+ expect(renameMock).not.toHaveBeenCalled();+ expect(rmMock).toHaveBeenCalledWith(expect.stringMatching(/\.part$/), { force: true });+ });it('大小和 SHA-256 都匹配后才发布目标文件', async () => {const bytes = Uint8Array.from([1, 2, 3]);netFetchMock.mockResolvedValue({ ok: true, status: 200, body: webBody(bytes) });diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex a6839f7319..99f577cff6 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -2,10 +2,12 @@ import { executeTaskTags, TASK_TAG_CHANNEL } from '../localDb/ipc/taskTags.js';import type { TaskTagRequest } from '@cindy/maker-shared';import {FILE_PEER_CHANNEL,+ TASK_MIGRATION_CHANNEL,encodeSessionTagCatalog,decodeSessionTagCatalog,} from '@cindy/device-link';import { requestFilePeer, stopFilePeers } from './filePeer';+import { requestTaskMigration } from '../task-migration/service';import { normalizeProviderOrder } from "../../shared/providerOrder.js";/*** dispatch —— device-link 被控端隧道层。@@ -3761,6 +3763,19 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefintry { return { ok: true, result: await requestFilePeer(src, payload.args?.[0], (channel, args) => runInvoke(src, { channel, args })) }; }catch { return { ok: false, error: { code: 'IPC_ERROR', message: 'FILE_PEER_UNAVAILABLE' } }; }}+ if (payload.channel === TASK_MIGRATION_CHANNEL) {+ try {+ if (isSharedTaskPeer(src)) throw new Error('MIGRATION_ACCESS_REVOKED');+ const result = await runDeviceLinkInvokeContext(+ { controllerDeviceId: src, channel: payload.channel },+ () => requestTaskMigration(payload.args?.[0]),+ );+ return { ok: true, result };+ } catch (error) {+ const code = /\bMIGRATION_[A-Z_]+\b/.exec(error instanceof Error ? error.message : '')?.[0] ?? 'MIGRATION_FAILED';+ return { ok: false, error: { code: 'IPC_ERROR', message: code } };+ }+ }if (payload.channel === PLUGIN_OAUTH_CHANNEL) {if (payload.args?.length !== 1) return { ok: false, error: { code: 'IPC_ERROR', message: '[INVALID_PARAMS] Invalid OAuth transaction' } };try { return { ok: true, result: await requestPluginOauth(src, payload.args[0]) }; }diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.tsindex 9af61dc61a..5feea39b37 100644--- a/apps/desktop/src/main/device-link/mediaTransfer.ts+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts@@ -48,7 +48,7 @@ const STREAM_THRESHOLD = 64 * 1024 * 1024;* content-length,故在客户端(本机 main = 实际上传方)按真实字节数自校并拒绝超限,* 让大小上限对正常上传路径真实生效(server 端再校验声称的 size 作第二道)。*/-const MAX_MEDIA_BYTES = 2 * 1024 * 1024 * 1024;+export const MAX_MEDIA_BYTES = 2 * 1024 * 1024 * 1024;const PRESIGN_PUT_PATH = '/api/device-link/media/presign-put';const PRESIGN_GET_PATH = '/api/device-link/media/presign-get';@@ -623,6 +623,10 @@ export async function downloadToFile(const counter = new Transform({transform(chunk: Buffer, _enc, cb) {size += chunk.length;+ if (expected && size > expected.size) {+ cb(new AttachmentIntegrityError('size', '附件下载超出声明大小。'));+ return;+ }hasher.update(chunk);onProgress?.(size);cb(null, chunk);diff --git a/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.ts b/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.tsindex dd00088f6c..c24b71a880 100644--- a/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.ts@@ -88,6 +88,31 @@ describe('importSharedCodexThread', () => {threadSpawnEdges: [],});+ it('atomically replaces an interrupted migration-owned rollout on retry', async () => {+ const target = path.join(codexHome, 'sessions', 'migration.jsonl');+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, '{partial');+ const bytes = Buffer.from('{"complete":true}\n');+ const write = fs.writeFileSync.bind(fs);+ const partial = vi.spyOn(fs, 'writeFileSync').mockImplementationOnce((file, _data, options) => {+ write(file, '{partial-temp', options);+ throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });+ });+ try {+ await expect(importSharedCodexThread({+ migration: true, threadId: THREAD_ID, stateRows: stateRows(),+ rolloutBuffer: bytes, rolloutFilename: 'migration.jsonl', newCwd: '/target', title: 'migrated', updatedAt: 1,+ })).rejects.toMatchObject({ code: 'ENOSPC' });+ expect(fs.readFileSync(target, 'utf8')).toBe('{partial');+ expect(fs.readdirSync(path.dirname(target))).toEqual(['migration.jsonl']);+ } finally { partial.mockRestore(); }+ const result = await importSharedCodexThread({+ migration: true, threadId: THREAD_ID, stateRows: stateRows(),+ rolloutBuffer: bytes, rolloutFilename: 'migration.jsonl', newCwd: '/target', title: 'migrated', updatedAt: 1,+ });+ expect(fs.readFileSync(target)).toEqual(bytes);+ expect(result.rolloutWritten).toBe(true);+ });it('writes rollout + state rows with cwd/rollout_path overrides and appends session index', async () => {const result = await importSharedCodexThread({threadId: THREAD_ID,diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.tsindex dbe13d30cc..2cd71643e7 100644--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts@@ -7,6 +7,7 @@*/import { app } from 'electron';+import { atomicWriteFileSync } from '../utils/atomicWriteFile';import type Database from 'better-sqlite3';import fs from 'node:fs';import { promises as fsp } from 'node:fs';@@ -1675,6 +1676,8 @@ function serializeSqlRow(row: SqlRow): Record<string, unknown> {}export interface ImportSharedCodexThreadParams {+ /** The incoming handoff owns this independent native ID until activation. */+ migration?: boolean;threadId: string;/** dumpCodexThreadStateRows 的序列化形态(Buffer 已包 base64 标记)。 */stateRows: {@@ -1742,10 +1745,11 @@ export async function importSharedCodexThread(// wx 独占写:同名 rollout 已在盘上(典型是删除 Maker 会话后重导同一分享包)// 时不覆盖、直接复用——盘上副本可能包含删除前 resume 产生的更新内容。try {- await fsp.writeFile(rolloutPath, params.rolloutBuffer, { flag: 'wx' });+ if (params.migration) atomicWriteFileSync(rolloutPath, params.rolloutBuffer.toString('utf8'));+ else await fsp.writeFile(rolloutPath, params.rolloutBuffer, { flag: 'wx' });rolloutWritten = true;} catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;+ if (params.migration || (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/mcp-integrations/__tests__/moveSession.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.tsindex 234b118834..27542eade7 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts@@ -59,7 +59,7 @@ vi.mock('../../im/binding.js', () => ({}));vi.mock('../../localDb/ipc/sessions.js', () => ({ updateSessionInDb: h.update }));-import { createMoveSession } from '../moveSession.js';+import { createMoveSession, moveSessionProjectFromHost } from '../moveSession.js';describe('moveSession host', () => {let directory: string;@@ -100,6 +100,25 @@ describe('moveSession host', () => {workingDir,});+ it('keeps agent self-moves forbidden while the trusted UI uses the same guarded update', async () => {+ const agent = createMoveSession((id) => h.running.has(id));+ expect(await agent({ callerSessionId: 'target', sessionId: 'target', workingDir: directory })).toMatchObject({ ok: false });+ expect(h.update).not.toHaveBeenCalled();+ expect(await moveSessionProjectFromHost((id) => h.running.has(id), 'target', directory, () => {})).toMatchObject({ ok: true, workspaceKind: 'project' });+ h.saved.mockClear();+ h.running.add('target');+ expect(await moveSessionProjectFromHost((id) => h.running.has(id), 'target', null, () => {})).toMatchObject({ ok: false });+ expect(h.saved).not.toHaveBeenCalled();+ });+ it.each(['lock', 'commit'])('rechecks remote authority at %s before moving', async phase => {+ let revoked = false;+ (phase === 'lock' ? h.enterLock : h.beforeCommit).mockImplementationOnce(() => { revoked = true; });+ expect(await moveSessionProjectFromHost(() => false, 'target', directory, () => {+ if (revoked) throw new Error('MIGRATION_ACCESS_REVOKED');+ })).toMatchObject({ ok: false });+ expect(h.saved).not.toHaveBeenCalled();+ });+it('uses the shared update path for moving projects and preserves cwd when removing grouping', async () => {// recent_workdirs stores logical project identities with forward slashes on all platforms.expect(await run(directory)).toMatchObject({diff --git a/apps/desktop/src/main/mcp-integrations/moveSession.ts b/apps/desktop/src/main/mcp-integrations/moveSession.tsindex 61bbadb746..170207267e 100644--- a/apps/desktop/src/main/mcp-integrations/moveSession.ts+++ b/apps/desktop/src/main/mcp-integrations/moveSession.ts@@ -22,77 +22,105 @@ export function createMoveSession(message: 'Cannot move the calling task while it is running.',};}- const directory = workingDir === null ? null : validateLocalProjectDirectory(workingDir);- if (directory && !directory.ok) return directory;- const targetDir = directory?.workingDir ?? null;- return withLocalProjectContext(callerSessionId, async (context) => {- const assertMoveAllowed = async () => {- context.assertCurrent();- const [target] = await context.client.drizzle- .select()- .from(sessions)- .where(eq(sessions.id, sessionId))- .limit(1);- context.assertCurrent();- if (!target) throwIpcError('NOT_FOUND', 'Task does not exist in this account.');- if (target.remoteHostId)- throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote tasks cannot be moved.');- if (target.status !== 'active')- throwIpcError('PRECONDITION_FAILED', 'Only active tasks can be moved.');- // Review immutability is also enforced by updateSessionInDb for all callers.- if (target.source === 'review')- throwIpcError(- 'UNSUPPORTED_CAPABILITY',- 'Review task settings are fixed to the source task.',- );- // Bot runtime resolves its workspace from the ownership link, including legacy tasks.- const [botLink] = await context.client.drizzle- .select({ botId: botSessionLinks.botId })- .from(botSessionLinks)- .where(eq(botSessionLinks.sessionId, sessionId))- .limit(1);- context.assertCurrent();- if (target.source === 'bot' || botLink)- throwIpcError('UNSUPPORTED_CAPABILITY', 'Bot tasks use their own managed workspace.');- if (targetDir) {- const physicalDirectory = await validateExistingLocalProjectDirectory(targetDir);- if (!physicalDirectory.ok) throwIpcError('INVALID_PARAMS', physicalDirectory.message);- }- // Re-read active team membership at each checkpoint, including after- // transcript copying/runtime close. Do not retain the pre-move snapshot.- const workers = await context.client.drizzle- .select({ sessionId: orcaWorkers.sessionId })- .from(orcaWorkers)- .innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))- .where(and(eq(orcaTeams.leadSessionId, sessionId), eq(orcaTeams.status, 'active')));- context.assertCurrent();- if (- isSessionRunning(sessionId) ||- workers.some((worker) => isSessionRunning(worker.sessionId))- ) {- throwIpcError(- 'PRECONDITION_FAILED',- 'Running tasks or leads with running workers cannot be moved.',- );- }- if (bindingStore.findByTarget(sessionId))- throwIpcError('PRECONDITION_FAILED', 'IM-controlled tasks cannot be moved.');- };- const patch =- targetDir === null- ? { workspaceKind: 'dialogue' }- : { workspaceKind: 'project', workingDir: targetDir };- const updated = await updateSessionInDb(sessionId, patch, undefined, {- assertCurrent: context.assertCurrent,- beforeUpdate: assertMoveAllowed,- beforeWrite: assertMoveAllowed,- });- return {- ok: true,- sessionId: updated.id,- workingDir: updated.workingDir ?? null,- workspaceKind: updated.workspaceKind ?? 'project',- };- });+ return moveSessionProject(isSessionRunning, callerSessionId, sessionId, workingDir);};}++/** Trusted UI entry: identity/remote-control authority is checked by the host route.+ * Unlike a running agent, the UI may move its selected task itself.+ */+export function moveSessionProjectFromHost(+ isSessionRunning: (sessionId: string) => boolean,+ sessionId: string,+ workingDir: string | null,+ assertAuthority: () => void,+) {+ assertAuthority();+ return moveSessionProject(isSessionRunning, sessionId, sessionId, workingDir, assertAuthority);+}++async function moveSessionProject(+ isSessionRunning: (sessionId: string) => boolean,+ contextSessionId: string,+ sessionId: string,+ workingDir: string | null,+ assertAuthority: () => void = () => {},+) {+ const directory = workingDir === null ? null : validateLocalProjectDirectory(workingDir);+ if (directory && !directory.ok) return directory;+ const targetDir = directory?.workingDir ?? null;+ return withLocalProjectContext(contextSessionId, async (context) => {+ const assertCurrent = () => {+ context.assertCurrent();+ assertAuthority();+ };+ assertCurrent();+ const assertMoveAllowed = async () => {+ assertCurrent();+ const [target] = await context.client.drizzle+ .select()+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ assertCurrent();+ if (!target) throwIpcError('NOT_FOUND', 'Task does not exist in this account.');+ if (target.remoteHostId)+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote tasks cannot be moved.');+ if (target.status !== 'active')+ throwIpcError('PRECONDITION_FAILED', 'Only active tasks can be moved.');+ // Review immutability is also enforced by updateSessionInDb for all callers.+ if (target.source === 'review')+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ 'Review task settings are fixed to the source task.',+ );+ // Bot runtime resolves its workspace from the ownership link, including legacy tasks.+ const [botLink] = await context.client.drizzle+ .select({ botId: botSessionLinks.botId })+ .from(botSessionLinks)+ .where(eq(botSessionLinks.sessionId, sessionId))+ .limit(1);+ assertCurrent();+ if (target.source === 'bot' || botLink)+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Bot tasks use their own managed workspace.');+ if (targetDir) {+ const physicalDirectory = await validateExistingLocalProjectDirectory(targetDir);+ if (!physicalDirectory.ok) throwIpcError('INVALID_PARAMS', physicalDirectory.message);+ }+ // Re-read active team membership at each checkpoint, including after+ // transcript copying/runtime close. Do not retain the pre-move snapshot.+ const workers = await context.client.drizzle+ .select({ sessionId: orcaWorkers.sessionId })+ .from(orcaWorkers)+ .innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))+ .where(and(eq(orcaTeams.leadSessionId, sessionId), eq(orcaTeams.status, 'active')));+ assertCurrent();+ if (+ isSessionRunning(sessionId) ||+ workers.some((worker) => isSessionRunning(worker.sessionId))+ ) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Running tasks or leads with running workers cannot be moved.',+ );+ }+ if (bindingStore.findByTarget(sessionId))+ throwIpcError('PRECONDITION_FAILED', 'IM-controlled tasks cannot be moved.');+ };+ const patch =+ targetDir === null+ ? { workspaceKind: 'dialogue' }+ : { workspaceKind: 'project', workingDir: targetDir };+ const updated = await updateSessionInDb(sessionId, patch, undefined, {+ assertCurrent,+ beforeUpdate: assertMoveAllowed,+ beforeWrite: assertMoveAllowed,+ });+ return {+ ok: true,+ sessionId: updated.id,+ workingDir: updated.workingDir ?? null,+ workspaceKind: updated.workspaceKind ?? 'project',+ };+ });+}diff --git a/apps/desktop/src/main/session-share/__tests__/migrationNativeContext.test.ts b/apps/desktop/src/main/session-share/__tests__/migrationNativeContext.test.tsnew file mode 100644index 0000000000..2b5618b93d--- /dev/null+++ b/apps/desktop/src/main/session-share/__tests__/migrationNativeContext.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';+import { migrationNativeContext } from '../migrationNativeContext';+const original = '12345678-1234-4234-a234-123456789012';+describe('independent migration context identities', () => {+ it.each(['switched to another agent', '{broken', 'null', '[1]', '"legacy"', ''])('preserves legacy metadata verbatim: %s', raw => {+ expect(migrationNativeContext('migration', [original]).metadata(raw)).toBe(raw);+ });+ it.each(['cc', 'codex'] as const)('preserves malformed and non-object %s transcript lines', agent => {+ const copy = migrationNativeContext('migration', [original]);+ const raw = 'null\n[1]\n"legacy"\n42\ntrue\nlegacy text\n{partial';+ expect(copy.transcript(Buffer.from(raw), agent).toString()).toBe(raw);+ });+ it('preserves native fork turn anchors while mapping them to the copied context', () => {+ const copy = migrationNativeContext('migration', [original]);+ const anchor = { agentKind: 'codex', sdkSessionId: original, kind: 'turn', id: 'turn-1' };+ expect(JSON.parse(copy.metadata(JSON.stringify({ nativeForkAnchor: anchor }))!)).toEqual({+ nativeForkAnchor: { ...anchor, sdkSessionId: copy.id(original) },+ });+ });+ it('is stable on retry and different on the next move', () => {+ const first = migrationNativeContext('migration-A', [original]).id(original);+ expect(migrationNativeContext('migration-A', [original]).id(original)).toBe(first);+ expect(migrationNativeContext('migration-B', [original]).id(original)).not.toBe(first);+ expect(first).toMatch(/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-a[a-f0-9]{3}-[a-f0-9]{12}$/);+ });+ it('changes only the Claude envelope identity, preserving message IDs and user content', () => {+ const copy = migrationNativeContext('migration', [original]);+ const row = {+ message: { sessionId: original, content: original },+ sessionId: original,+ uuid: 'message-id',+ parentUuid: 'parent-id',+ };+ const result = JSON.parse(+ copy.transcript(Buffer.from(JSON.stringify(row) + '\n'), 'cc').toString(),+ );+ expect(result).toEqual({ ...row, sessionId: copy.id(original) });+ });+ it('preserves Codex event bytes and offsets outside its session metadata ID', () => {+ const copy = migrationNativeContext('migration', [original]);+ const header = JSON.stringify({+ timestamp: '2026-09-26',+ type: 'session_meta',+ payload: { id: original, cwd: '/source' },+ });+ const event = JSON.stringify({+ type: 'response_item',+ payload: { id: original, content: original },+ });+ const bytes = Buffer.from(header + '\n' + event + '\n');+ const result = copy.transcript(bytes, 'codex');+ expect(result.length).toBe(bytes.length);+ expect(result.toString().split('\n')[1]).toBe(event);+ expect(JSON.parse(result.toString().split('\n')[0]).payload.id).toBe(copy.id(original));+ expect(+ copy.stateRows({+ threads: [{ id: original }],+ threadDynamicTools: [{ thread_id: original, schema: original }],+ threadSpawnEdges: [{ parent_thread_id: original, child_thread_id: 'other' }],+ }),+ ).toEqual({+ threads: [{ id: copy.id(original) }],+ threadDynamicTools: [{ thread_id: copy.id(original), schema: original }],+ threadSpawnEdges: [{ parent_thread_id: copy.id(original), child_thread_id: 'other' }],+ });+ });+});diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.tsindex d231423a52..44e558b938 100644--- a/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts@@ -471,84 +471,108 @@ describe('exportSessionShare', () => {expect(manifest.orca).toBeUndefined();});- it('orca lead export bundles workers under prefixes with team graph, minReaderVersion 2', async () => {- sessionRowRef.row = { ...baseSession(), orcaRole: 'lead' };- activeTeamRef.row = { id: 'team-1', status: 'active' };- workerRowsRef.rows = [- { sessionId: 'worker-s-1', status: 'done', label: 'dev-1', role: 'developer', focused: 1 },- // 已归档 Worker 不在当前协同列表中,导出也应排除,避免导入后复活。- { sessionId: 'worker-s-archived', status: 'done', label: 'dev-2', role: 'reviewer', focused: 0 },- ];- workerSessionsById.set('worker-s-1', {- ...baseSession(),- id: 'worker-s-1',- title: 'Worker 1',- agentKind: 'codex',- orcaRole: 'worker',- sdkSessionId: 'thread-1',- });- workerSessionsById.set('worker-s-archived', {- ...baseSession(),- id: 'worker-s-archived',- status: 'archived',- orcaRole: 'worker',- });- workerMessagesBySession.set('worker-s-1', [- {- id: 'wm1',- clientId: 'wc1',- role: 'user',- content: JSON.stringify([{ type: 'text', text: '派活' }]),- toolUseId: null,- agentMeta: null,+ it.each([false, true])(+ 'orca lead export preserves the team graph (migration=%s)',+ async (migration) => {+ sessionRowRef.row = { ...baseSession(), orcaRole: 'lead' };+ activeTeamRef.row = { id: 'team-1', status: 'active' };+ workerRowsRef.rows = [+ { sessionId: 'worker-s-1', status: 'done', label: 'dev-1', role: 'developer', focused: 1 },+ // 已归档 Worker 不在当前协同列表中,导出也应排除,避免导入后复活。+ {+ sessionId: 'worker-s-archived',+ status: 'done',+ label: 'dev-2',+ role: 'reviewer',+ focused: 0,+ },+ ];+ workerSessionsById.set('worker-s-1', {+ ...baseSession(),+ id: 'worker-s-1',+ title: 'Worker 1',agentKind: 'codex',- createdAt: 1700000000300,- rewindAt: null,- },- ]);- workerMessagesBySession.set('worker-s-archived', []);-- const target = path.join(tmpRoot, 'out-orca.xdtshare');- const outcome = await exportSessionShare({ sessionId: 'xdt-session-1', targetPath: target });- expect(outcome.status).toBe('ok');- if (outcome.status !== 'ok') return;- expect(getActiveTeamByLeadMock).toHaveBeenCalledWith('xdt-session-1');- expect(outcome.orcaWorkers).toBe(1);- expect(outcome.fidelity).toBe('full');-- const zip = await unzipOf(target);- const manifest = validateManifest(JSON.parse(await zip.file('manifest.json')!.async('string')));- expect(manifest.formatVersion).toBe(2);- expect(manifest.minReaderVersion).toBe(2);- expect(manifest.agentKind).toBe('cc'); // 顶层仍描述 lead- expect(manifest.orca).toBeDefined();- expect(manifest.orca!.teamStatus).toBe('active');- expect(manifest.orca!.workers).toHaveLength(1);- const worker = manifest.orca!.workers[0];- expect(worker.index).toBe(0);- expect(worker.agentKind).toBe('codex');- expect(worker.role).toBe('developer');- expect(worker.label).toBe('dev-1');- expect(worker.status).toBe('done');- expect(worker.focused).toBe(true);- expect(worker.activeSdkSessionId).toBe('thread-1');- expect(worker.counts.messages).toBe(1);- expect(worker.transcripts).toEqual([- { sdkSessionId: 'thread-1', path: 'orca/workers/0/transcripts/codex/rollout-1-thread-1.jsonl' },- ]);-- // Worker 数据落在前缀目录下,lead 顶层结构保持不变- expect(zip.file('orca/workers/0/session.json')).toBeTruthy();- expect(zip.file('orca/workers/0/messages.jsonl')).toBeTruthy();- expect(zip.file('orca/workers/0/transcripts/codex/rollout-1-thread-1.jsonl')).toBeTruthy();- expect(zip.file('orca/workers/0/codex-state/thread.json')).toBeTruthy();- expect(zip.file('session.json')).toBeTruthy();- expect(zip.file('transcripts/claude/sid-b.jsonl')).toBeTruthy();- const workerSnapshot = JSON.parse(- await zip.file('orca/workers/0/session.json')!.async('string'),- ) as Record<string, unknown>;- expect(workerSnapshot.agentKind).toBe('codex');- });+ orcaRole: 'worker',+ sdkSessionId: 'thread-1',+ });+ workerSessionsById.set('worker-s-archived', {+ ...baseSession(),+ id: 'worker-s-archived',+ status: 'archived',+ orcaRole: 'worker',+ });+ workerMessagesBySession.set('worker-s-1', [+ {+ id: 'wm1',+ clientId: 'wc1',+ role: 'user',+ content: JSON.stringify([{ type: 'text', text: '派活' }]),+ toolUseId: null,+ agentMeta: null,+ agentKind: 'codex',+ createdAt: 1700000000300,+ rewindAt: null,+ },+ ]);+ workerMessagesBySession.set('worker-s-archived', []);++ const target = path.join(tmpRoot, 'out-orca.xdtshare');+ const outcome = await exportSessionShare({+ sessionId: 'xdt-session-1',+ targetPath: target,+ migration,+ });+ expect(outcome.status).toBe('ok');+ if (outcome.status !== 'ok') return;+ expect(getActiveTeamByLeadMock).toHaveBeenCalledWith('xdt-session-1');+ expect(outcome.orcaWorkers).toBe(migration ? 2 : 1);+ expect(outcome.fidelity).toBe('full');++ const zip = await unzipOf(target);+ const manifest = validateManifest(+ JSON.parse(await zip.file('manifest.json')!.async('string')),+ );+ expect(manifest.formatVersion).toBe(2);+ expect(manifest.minReaderVersion).toBe(2);+ expect(manifest.agentKind).toBe('cc'); // 顶层仍描述 lead+ expect(manifest.orca).toBeDefined();+ expect(manifest.orca!.teamStatus).toBe('active');+ expect(manifest.orca!.workers).toHaveLength(migration ? 2 : 1);+ const worker = manifest.orca!.workers[0];+ expect(worker.index).toBe(0);+ expect(worker.agentKind).toBe('codex');+ expect(worker.role).toBe('developer');+ expect(worker.label).toBe('dev-1');+ expect(worker.status).toBe('done');+ expect(worker.focused).toBe(true);+ expect(worker.activeSdkSessionId).toBe('thread-1');+ expect(worker.counts.messages).toBe(1);+ expect(worker.transcripts).toEqual([+ {+ sdkSessionId: 'thread-1',+ path: 'orca/workers/0/transcripts/codex/rollout-1-thread-1.jsonl',+ },+ ]);++ // Worker 数据落在前缀目录下,lead 顶层结构保持不变+ expect(zip.file('orca/workers/0/session.json')).toBeTruthy();+ expect(zip.file('orca/workers/0/messages.jsonl')).toBeTruthy();+ expect(zip.file('orca/workers/0/transcripts/codex/rollout-1-thread-1.jsonl')).toBeTruthy();+ expect(zip.file('orca/workers/0/codex-state/thread.json')).toBeTruthy();+ expect(zip.file('session.json')).toBeTruthy();+ expect(zip.file('transcripts/claude/sid-b.jsonl')).toBeTruthy();+ const workerSnapshot = JSON.parse(+ await zip.file('orca/workers/0/session.json')!.async('string'),+ ) as Record<string, unknown>;+ expect(workerSnapshot.agentKind).toBe('codex');+ if (migration) {+ expect(workerSnapshot.migrationSourceId).toBe('worker-s-1');+ expect(+ JSON.parse(await zip.file('orca/workers/1/session.json')!.async('string')),+ ).toMatchObject({ migrationSourceId: 'worker-s-archived', status: 'archived' });+ } else expect(workerSnapshot).not.toHaveProperty('migrationSourceId');+ },+ );it('orca lead export fails closed when an active team Worker session is missing or deleted', async () => {sessionRowRef.row = { ...baseSession(), orcaRole: 'lead' };diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.tsindex 530332efdf..0bcbd707f9 100644--- a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts@@ -11,6 +11,8 @@ import os from 'node:os';import path from 'node:path';import JSZip from 'jszip';+import { sanitizeClaudeProjectKey } from '@cindy/maker-core';+import { migrationNativeContext } from '../migrationNativeContext';import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import { DB_TRANSPORT_OUTCOME_UNKNOWN } from '../../localDb/client/DbTransport.js';@@ -183,10 +185,17 @@ vi.mock('../../cindy-media/ledger.js', () => ({},}));const worktreeMock = vi.hoisted(() => ({- detect: null as+ detect: null as null | {+ isGitRepo: boolean;+ isInsideWorktree: boolean;+ gitInstalled: boolean;+ repoRoot?: string;+ currentBranch?: string;+ },+ createResult: null as| null- | { isGitRepo: boolean; isInsideWorktree: boolean; gitInstalled: boolean; repoRoot?: string; currentBranch?: string },- createResult: null as null | { ok: true; meta: { path: string } } | { ok: false; error: { kind: string; message?: string } },+ | { ok: true; meta: { path: string } }+ | { ok: false; error: { kind: string; message?: string } },suggestedName: 'imported-wt' as string | null,createCalls: [] as Array<{ sessionId: string; baseRepo: string; name: string; sourceBranch: string }>,removeCalls: [] as string[],@@ -212,8 +221,12 @@ const {} = sessionShareImportModule;const mockedDbClientModule = await import('../../localDb/client/current.js');const rawCommitShareImport = sessionShareImportModule.commitShareImport;-const commitShareImport = (opts: Parameters<typeof rawCommitShareImport>[0]) =>+const commitShareImport = (+ opts: Parameters<typeof rawCommitShareImport>[0],+ migration?: Parameters<typeof rawCommitShareImport>[1]['migration'],+) =>rawCommitShareImport(opts, {+ migration,dbClient: mockedDbClientModule.getDbClient(),assertStillValid: () => undefined,refCompensationScope: {@@ -255,7 +268,11 @@ interface BundleOverrides {/** v1 旧包没有逐消息 agentKind。 */omitMessageAgentKind?: boolean;/** 协同包:附带一个 Worker(cc 或 codex),manifest 升到 v2 + orca 段。 */- orcaWorker?: { agentKind: 'cc' | 'codex'; status?: 'idle' | 'running' | 'done' | 'error' };+ orcaWorker?: {+ agentKind: 'cc' | 'codex';+ status?: 'idle' | 'running' | 'done' | 'error';+ snapshot?: Record<string, unknown>;+ };}const WORKER_SID = 'bbbbbbbb-1111-2222-3333-555555555555';@@ -359,7 +376,13 @@ async function buildBundle(overrides: BundleOverrides = {}): Promise<Buffer> {: `orca/workers/0/transcripts/codex/rollout-w-${WORKER_SID}.jsonl`;zip.file('orca/workers/0/session.json',- JSON.stringify({ title: 'Worker 快照', createdAt: 1700000001000, userSendAt: 1700000001100, totalTokenUsage: 42 }),+ JSON.stringify({+ title: 'Worker 快照',+ createdAt: 1700000001000,+ userSendAt: 1700000001100,+ totalTokenUsage: 42,+ ...overrides.orcaWorker.snapshot,+ }),);zip.file('orca/workers/0/messages.jsonl',@@ -554,6 +577,86 @@ describe('sessionShareImport', () => {expect(fs.existsSync(path.join(sharedMediaRoot, result.sessionId, '2-doc.pdf'))).toBe(true);});+ it('checks inflated context against the host memory budget before import', async () => {+ const zip = await JSZip.loadAsync(await buildBundle());+ zip.file('large-extra.txt', 'a'.repeat(100_000));+ const compressed = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });+ const filePath = await writeBundleFile(compressed);+ const fileSize = (await fsp.stat(filePath)).size;+ expect(fileSize).toBeLessThan(100_000);+ await expect(inspectShareFile(filePath, { resourceBudgetBytes: fileSize + 1000 })).rejects.toThrow('MIGRATION_NO_MEMORY');+ await expect(inspectShareFile(filePath, { resourceBudgetBytes: 200_000 })).resolves.toMatchObject({ encrypted: false });+ });++ it.each(['cc', 'codex', 'pi'] as const)('migration assigns an independent %s context without replacing the retained source', async agentKind => {+ const filePath = await writeBundleFile(await buildBundle({ agentKind }));+ const inspect = await inspectShareFile(filePath);+ if (inspect.encrypted) throw new Error('unexpected encrypted fixture');+ const migrationId = '11111111-2222-4333-a444-555555555555';+ dbMock.conflictRow = { id: 'retained-source', status: 'active' };+ dbMock.conflictForResumeId = agentKind === 'pi' ? path.join(piSessionsRoot, PI_SID) : SID;+ codexMock.importResult.rolloutPath = path.join(tmpRoot, 'migrated.jsonl');+ const result = await commitShareImport({ draftId: inspect.draftId, workingDir: newWorkdir,+ projectsRootOverride: projectsRoot, piSessionsRootOverride: piSessionsRoot,+ sharedMediaRootOverride: sharedMediaRoot }, { sessionId: migrationId, workingDir: newWorkdir });+ expect(result.sessionId).toBe(migrationId);+ expect(result.fidelity).toBe('full');+ const args = dbMock.txCalls.find(call => call.name === 'session.importShare')!.args as {+ session: { id: string; sdkSessionId: string }; messages: Array<{ agentMeta: string | null }>;+ };+ expect(args.session.sdkSessionId).not.toBe(dbMock.conflictForResumeId);+ expect(args.messages[1].agentMeta).toContain(args.session.sdkSessionId.replace(/\\/g, '\\\\'));+ expect(closeSharedTaskForTask).not.toHaveBeenCalled();+ if (agentKind === 'codex') {+ const call = codexMock.importCalls[0] as { threadId: string; stateRows: { threads: Array<{ id: string }> }; rolloutFilename: string };+ expect(call.threadId).toBe(args.session.sdkSessionId);+ expect(call.stateRows.threads[0].id).toBe(call.threadId);+ expect(call.rolloutFilename).toContain(call.threadId);+ }+ });++ it.each(['cc', 'codex'] as const)('copies %s transcripts containing damaged historical lines', async agentKind => {+ const zip = await JSZip.loadAsync(await buildBundle({ agentKind }));+ const transcriptPath = agentKind === 'cc' ? `transcripts/claude/${SID}.jsonl` : `transcripts/codex/rollout-x-${SID}.jsonl`;+ const header = agentKind === 'cc' ? { sessionId: SID } : { type: 'session_meta', payload: { id: SID } };+ const tail = '\nnull\n[1]\nlegacy text\n{partial';+ zip.file(transcriptPath, JSON.stringify(header) + tail);+ const inspect = await inspectShareFile(await writeBundleFile(await zip.generateAsync({ type: 'nodebuffer' })));+ if (inspect.encrypted) throw new Error('unexpected encrypted fixture');+ const migrationId = '11111111-2222-4333-a444-555555555555';+ codexMock.importResult.rolloutPath = path.join(tmpRoot, 'copied.jsonl');+ const result = await commitShareImport({ draftId: inspect.draftId, workingDir: newWorkdir,+ projectsRootOverride: projectsRoot, sharedMediaRootOverride: sharedMediaRoot },+ { sessionId: migrationId, workingDir: newWorkdir });+ expect(result.fidelity).toBe('full');+ 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();+ expect(restored).toBe(JSON.stringify(agentKind === 'cc' ? { sessionId: nativeId } : { type: 'session_meta', payload: { id: nativeId } }) + tail);+ });+ 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 };+ const attempt = async () => {+ const inspected = await inspectShareFile(filePath);+ if (inspected.encrypted) throw new Error('unexpected encrypted fixture');+ return commitShareImport({ draftId: inspected.draftId, workingDir: newWorkdir,+ projectsRootOverride: projectsRoot, piSessionsRootOverride: piSessionsRoot,+ sharedMediaRootOverride: sharedMediaRoot }, migration);+ };+ const nativeId = migrationNativeContext(migration.sessionId, [SID]).id(SID);+ const target = agentKind === 'pi' ? path.join(piSessionsRoot, migration.sessionId, PI_SID)+ : path.join(projectsRoot, newWorkdir.replace(/[^a-zA-Z0-9]/g, '-'), `${nativeId}.jsonl`);+ await fsp.mkdir(path.dirname(target), { recursive: true });+ await fsp.writeFile(target, '{partial');+ dbMock.txError = null;+ expect((await attempt()).fidelity).toBe('full');+ const restored = await fsp.readFile(target, 'utf8');+ expect(restored).not.toContain('partial');+ expect(() => restored.trim().split('\n').forEach(line => JSON.parse(line))).not.toThrow();+ });+it('legacy bundle without message agentKind imports rows as NULL', async () => {const filePath = await writeBundleFile(await buildBundle({ omitMessageAgentKind: true }));const inspect = await inspectShareFile(filePath);@@ -1480,6 +1583,80 @@ describe('sessionShareImport', () => {expect(worker.messages[0].content).not.toContain('xdt-image://');});+ it.each(['cc', 'codex'] as const)(+ 'migrates %s workers with independent identities, directories and target model routes',+ async (agentKind) => {+ const workerDir = path.join(tmpRoot, `migrated-${agentKind}-worker`);+ await fsp.mkdir(workerDir, { recursive: true });+ const inspected = await inspectShareFile(+ await writeBundleFile(+ await buildBundle({+ agentKind: 'pi',+ orcaWorker: {+ agentKind,+ snapshot: {+ migrationSourceId: 'source-worker',+ status: 'archived',+ workspaceKind: 'project',+ },+ },+ }),+ ),+ );+ const result = await commitShareImport(+ {+ draftId: inspected.draftId,+ workingDir: newWorkdir,+ projectsRootOverride: projectsRoot,+ sharedMediaRootOverride: sharedMediaRoot,+ piSessionsRootOverride: piSessionsRoot,+ },+ {+ sessionId: `migration-${agentKind}`,+ workingDir: newWorkdir,+ workers: [+ { sourceSessionId: 'source-worker', sessionId: 'target-worker', workingDir: workerDir },+ ],+ agentPrefs: {+ [agentKind]: {+ model: 'worker-model',+ providerId: 'worker-provider',+ effort: 'high',+ permissionMode: 'ask',+ },+ },+ },+ );+ expect(result.fidelity).toBe('full');+ const args = dbMock.txCalls[0].args as OrcaTxArgs;+ const worker = args.orca!.workers[0].session;+ expect(worker).toMatchObject({+ id: 'target-worker',+ workingDir: workerDir,+ status: 'archived',+ model: 'worker-model',+ providerId: 'worker-provider',+ permissionMode: agentKind === 'cc' ? 'default' : 'ask',+ });+ expect(worker.sdkSessionId).not.toBe(WORKER_SID);+ if (agentKind === 'cc')+ expect(+ fs.existsSync(+ path.join(+ projectsRoot,+ workerDir.replace(/[^a-zA-Z0-9]/g, '-'),+ `${worker.sdkSessionId}.jsonl`,+ ),+ ),+ ).toBe(true);+ else+ expect(codexMock.importCalls[0]).toMatchObject({+ threadId: worker.sdkSessionId,+ newCwd: workerDir,+ });+ },+ );+it('orca bundle: worker resume id conflict → SHARE_CONFLICT; overwrite soft-deletes it', async () => {dbMock.conflictForResumeId = WORKER_SID;const filePath = await writeBundleFile(diff --git a/apps/desktop/src/main/session-share/migrationNativeContext.ts b/apps/desktop/src/main/session-share/migrationNativeContext.tsnew file mode 100644index 0000000000..004fd79887--- /dev/null+++ b/apps/desktop/src/main/session-share/migrationNativeContext.ts@@ -0,0 +1,110 @@+import { createHash } from 'node:crypto';++/** New native identities for migration copies, deterministic across retries of one handoff.+ * Only unindexed incoming bytes are rewritten; existing vendor files are never modified. */+export function migrationNativeContext(migrationId: string, nativeIds: readonly string[]) {+ const ids = new Map(+ nativeIds.map((id) => {+ const hex = createHash('sha256').update(`${migrationId}\0${id}`).digest('hex');+ return [+ id,+ `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`,+ ];+ }),+ );+ const id = (value: string) => ids.get(value) ?? value;+ const metadata = (raw: string | null): string | null => {+ if (!raw) return raw;+ let value: Record<string, unknown>;+ try {+ value = JSON.parse(raw) as Record<string, unknown>;+ } catch {+ // Legacy switch messages and optional metadata can be plain text.+ // Preserve those bytes, just as the ordinary transcript reader does.+ return raw;+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) return raw;+ let changed = false;+ for (const key of [+ 'sdkSessionId',+ 'fromSdkSessionId',+ 'toSdkSessionId',+ 'sourceSdkSessionId',+ ]) {+ if (typeof value[key] === 'string' && ids.has(value[key])) {+ value[key] = id(value[key]);+ changed = true;+ }+ }+ const anchor = value.nativeForkAnchor;+ if (anchor && typeof anchor === 'object' && !Array.isArray(anchor)) {+ const nativeAnchor = anchor as Record<string, unknown>;+ if (typeof nativeAnchor.sdkSessionId === 'string' && ids.has(nativeAnchor.sdkSessionId)) {+ value.nativeForkAnchor = { ...nativeAnchor, sdkSessionId: id(nativeAnchor.sdkSessionId) };+ changed = true;+ }+ }+ return changed ? JSON.stringify(value) : raw;+ };+ 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;+ })+ .join('\n'),+ );+ const stateRows = <+ T extends {+ threads: Array<Record<string, unknown>>;+ threadDynamicTools: Array<Record<string, unknown>>;+ threadSpawnEdges: Array<Record<string, unknown>>;+ },+ >(+ rows: T,+ ): T => {+ const rewrite = (row: Record<string, unknown>, fields: string[]) =>+ Object.fromEntries(+ Object.entries(row).map(([key, value]) => [+ key,+ fields.includes(key) && typeof value === 'string' ? id(value) : value,+ ]),+ );+ return {+ ...rows,+ threads: rows.threads.map((row) => rewrite(row, ['id'])),+ threadDynamicTools: rows.threadDynamicTools.map((row) => rewrite(row, ['thread_id'])),+ threadSpawnEdges: rows.threadSpawnEdges.map((row) =>+ rewrite(row, ['parent_thread_id', 'child_thread_id']),+ ),+ };+ };+ return { id, metadata, transcript, stateRows };+}diff --git a/apps/desktop/src/main/session-share/sessionShareExport.ts b/apps/desktop/src/main/session-share/sessionShareExport.tsindex 1bc7f0b816..530c7a97aa 100644--- a/apps/desktop/src/main/session-share/sessionShareExport.ts+++ b/apps/desktop/src/main/session-share/sessionShareExport.ts@@ -79,13 +79,16 @@ export interface SessionShareExportOptions {password?: string | null;/** 超限重试时由 renderer 显式传入:跳过全部媒体,只保消息文本与转录。 */excludeMedia?: boolean;- /** 仅测试用:覆盖体积上限(默认 SHARE_EXPORT_SIZE_LIMIT_BYTES)。 */+ /** Host resource budget override; ordinary sharing retains its default limit. */sizeLimitBytes?: number;+ /** Host-only migration includes archived members without reviving them. */+ migration?: boolean;}export type SessionShareExportOutcome =| {status: 'ok';+ unpackedBytes: number;filePath: string;fidelity: XdtshareFidelity;/** 导出端没找到转录的 sdkSessionId 列表(cc fork 链部分缺失时非空)。 */@@ -386,6 +389,7 @@ async function readSessionPhaseB(a: SessionPhaseA): Promise<SessionPhaseB> {/** lead 的 active team + Worker 会话收集;无 active team 返回 null(按普通会话导出)。 */async function collectOrcaWorkerSources(leadSessionId: string,+ includeArchived = false,): Promise<{ teamStatus: XdtshareOrcaManifest['teamStatus']; workers: OrcaWorkerSource[] } | null> {// 与运行期使用同一个 active team 选择与去重入口。历史 migration / drift// 可能留下多个 active team;直接 LIMIT 1 会导出用户当前看不到的旧 Worker 图。@@ -415,7 +419,7 @@ async function collectOrcaWorkerSources(`orca worker session is missing or deleted: ${record.sessionId}`,);}- if (workerSession.status === 'archived') {+ if (workerSession.status === 'archived' && !includeArchived) {log.info('archived orca worker excluded from export', {workerSessionId: record.sessionId,});@@ -472,7 +476,7 @@ export async function exportSessionShare(// ── 协同收集:lead 的 active team 全部 Worker 随包(stale lead 无 active// team 时按普通会话导出)。Worker 允许 0 条消息(刚创建未派活)。──const orcaSources =- session.orcaRole === 'lead' ? await collectOrcaWorkerSources(session.id) : null;+ session.orcaRole === 'lead' ? await collectOrcaWorkerSources(session.id, opts.migration) : null;const workerSources = orcaSources?.workers ?? [];// ── 阶段 A(lead + 每个 Worker) ──@@ -624,7 +628,14 @@ export async function exportSessionShare(const addSessionEntries = async (a: SessionPhaseA, b: SessionPhaseB): Promise<void> => {await addEntry(`${a.zipPrefix}session.json`,- JSON.stringify(buildSessionSnapshot(a.session, b.activeSdkSessionId), null, 2),+ JSON.stringify(+ {+ ...buildSessionSnapshot(a.session, b.activeSdkSessionId),+ ...(opts.migration ? { migrationSourceId: a.session.id, status: a.session.status } : {}),+ },+ null,+ 2,+ ),);await addEntry(`${a.zipPrefix}messages.jsonl`,@@ -693,6 +704,11 @@ export async function exportSessionShare(};zip.file('manifest.json', JSON.stringify(manifest, null, 2));+ 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 };+const zipBytes = await zip.generateAsync({type: 'nodebuffer',compression: 'DEFLATE',@@ -732,6 +748,7 @@ export async function exportSessionShare(});return {status: 'ok',+ unpackedBytes,filePath: opts.targetPath,fidelity,missingTranscripts,diff --git a/apps/desktop/src/main/session-share/sessionShareImport.ts b/apps/desktop/src/main/session-share/sessionShareImport.tsindex 9fe089b3c6..e82fa476e0 100644--- a/apps/desktop/src/main/session-share/sessionShareImport.ts+++ b/apps/desktop/src/main/session-share/sessionShareImport.ts@@ -20,6 +20,8 @@ import { promises as fsp } from 'node:fs';import path from 'node:path';import JSZip from 'jszip';+import { atomicWriteFileSync } from '../utils/atomicWriteFile';+import { migrationNativeContext } from './migrationNativeContext';import { isClaudeProjectKeyExact, sanitizeClaudeProjectKey } from '@cindy/maker-core';import { app } from 'electron';@@ -139,10 +141,23 @@ function toPreview(manifest: XdtshareManifest): SharePreview {async function loadZipAndManifest(zipBytes: Buffer,+ resourceBudgetBytes?: number,): Promise<{ zip: JSZip; manifest: XdtshareManifest }> {const zip = await JSZip.loadAsync(zipBytes).catch(() => {throw new XdtshareError('SHARE_FILE_INVALID', 'payload is not a readable zip');});+ if (resourceBudgetBytes !== undefined) {+ let inflated = 0;+ for (const entry of Object.values(zip.files)) {+ if (entry.dir) continue;+ // JSZip's loaded central-directory sizes are available before inflating any entry.+ const size = (entry as unknown as { _data?: { uncompressedSize?: number } })._data?.uncompressedSize;+ if (!Number.isSafeInteger(size) || size! < 0) throw codedError('SHARE_FILE_INVALID', 'invalid zip size');+ inflated += size!;+ if (!Number.isSafeInteger(inflated) || inflated > resourceBudgetBytes)+ throw codedError('SHARE_FILE_INVALID', 'MIGRATION_NO_MEMORY');+ }+ }const manifestFile = zip.file('manifest.json');if (!manifestFile) throw new XdtshareError('SHARE_FILE_INVALID', 'manifest.json missing');let parsed: unknown;@@ -155,12 +170,13 @@ async function loadZipAndManifest(}/** 第一段:读文件、解头。明文直接出预览;加密只报 encrypted,等 unlock。 */-export async function inspectShareFile(filePath: string): Promise<InspectResult> {+export async function inspectShareFile(filePath: string, hostResources?: { resourceBudgetBytes: number }): Promise<InspectResult> {sweepExpiredDrafts();const stat = await fsp.stat(filePath).catch(() => null);if (!stat?.isFile()) throw codedError('SHARE_FILE_INVALID', 'file not found');- if (stat.size > SHARE_FILE_READ_LIMIT_BYTES) {- throw codedError('SHARE_FILE_INVALID', 'file too large');+ const readLimit = hostResources?.resourceBudgetBytes ?? SHARE_FILE_READ_LIMIT_BYTES;+ if (!Number.isSafeInteger(readLimit) || readLimit < 0 || stat.size > readLimit) {+ throw codedError('SHARE_FILE_INVALID', hostResources ? 'MIGRATION_NO_MEMORY' : 'file too large');}const fileBytes = await fsp.readFile(filePath);const draftId = randomUUID();@@ -184,7 +200,7 @@ export async function inspectShareFile(filePath: string): Promise<InspectResult>throw err;}- const { zip, manifest } = await loadZipAndManifest(opened.zipBytes);+ const { zip, manifest } = await loadZipAndManifest(opened.zipBytes, hostResources?.resourceBudgetBytes);drafts.set(draftId, {filePath,lockedBytes: null,@@ -259,6 +275,13 @@ export interface CommitShareImportOptions {/** Stable owner-bound resources captured synchronously by the production IPC entry. */export interface CommitShareImportRuntimeScope {dbClient: DbClient;+ /** Host-only handoff identity. Never accepted from the ordinary share-import IPC. */+ migration?: {+ sessionId: string;+ workingDir: string;+ workers?: Array<{ sourceSessionId: string; sessionId: string; workingDir: string }>;+ agentPrefs?: Partial<Record<'cc' | 'codex' | 'pi', ShareImportDraftPrefs>>;+ };assertStillValid(): void;refCompensationScope: MediaRefCompensationScope;/** Persist cleanup intent before an overwrite transaction marks old sessions deleted. */@@ -305,6 +328,7 @@ interface WorkerImportPlan {bundledTranscripts?: BundledTranscript[];/** pi 便携 id 已映射为本机绝对路径;codex/cc 为包内 id 原样。 */activeSdkSessionId: string | null;+ workingDir?: string;}/**@@ -379,12 +403,33 @@ export async function commitShareImport(}}+ if (runtimeScope.migration) {+ const workers = runtimeScope.migration.workers ?? [];+ if (workers.length !== workerPlans.length || (runtimeScope.migration.workers !== undefined) !== !!manifest.orca)+ throw codedError('SHARE_IMPORT_FAILED', 'MIGRATION_TEAM_CHANGED');+ const matched = new Set<string>();+ for (const plan of workerPlans) {+ if (!runtimeScope.migration.agentPrefs?.[plan.manifest.agentKind])+ throw codedError('SHARE_IMPORT_FAILED', 'MIGRATION_TARGET_MODEL_UNAVAILABLE');+ const member = workers.find(+ (worker) => worker.sourceSessionId === plan.snapshot.migrationSourceId,+ );+ if (!member || matched.has(member.sessionId))+ throw codedError('SHARE_IMPORT_FAILED', 'MIGRATION_TEAM_CHANGED');+ matched.add(member.sessionId);+ plan.newId = member.sessionId;+ plan.workingDir = member.workingDir;+ if (!(await guarded(() => fsp.stat(member.workingDir))).isDirectory())+ throw codedError('SHARE_IMPORT_FAILED', 'MIGRATION_WORKSPACE_CHANGED');+ }+ }+// ── 前置校验 ──const now = Date.now();- const newId = randomUUID();+ const newId = runtimeScope.migration?.sessionId ?? randomUUID();let workingDir: string;- if (manifest.workspaceKind === 'project') {- const dir = typeof opts.workingDir === 'string' ? opts.workingDir.trim() : '';+ if (manifest.workspaceKind === 'project' || runtimeScope.migration) {+ const dir = runtimeScope.migration?.workingDir ?? (typeof opts.workingDir === 'string' ? opts.workingDir.trim() : '');if (!dir) throw codedError('INVALID_PARAMS', 'workingDir is required for project sessions');const stat = await guarded(() => fsp.stat(dir).catch(() => null));if (!stat?.isDirectory()) {@@ -426,7 +471,20 @@ export async function commitShareImport(}return bundled;};- const bundledTranscripts = filterBundled(manifest.transcripts, 'transcripts');+ const originalBundledTranscripts = filterBundled(manifest.transcripts, 'transcripts');+ const migratedContext = runtimeScope.migration+ ? migrationNativeContext(+ runtimeScope.migration.sessionId,+ [manifest, ...workerPlans.map((plan) => plan.manifest)]+ .filter((member) => member.agentKind !== 'pi')+ .flatMap((member) => member.transcripts.map((t) => t.sdkSessionId)),+ )+ : null;+ const bundledTranscripts = originalBundledTranscripts.map((transcript) =>+ migratedContext && manifest.agentKind !== 'pi'+ ? { ...transcript, sdkSessionId: migratedContext.id(transcript.sdkSessionId) }+ : transcript,+ );for (const plan of workerPlans) {if (plan.manifest.activeSdkSessionId && !isSafePathSegment(plan.manifest.activeSdkSessionId)) {throw new XdtshareError(@@ -437,6 +495,10 @@ export async function commitShareImport(plan.bundledTranscripts = filterBundled(plan.manifest.transcripts,`orca.workers[${plan.manifest.index}].transcripts`,+ ).map((transcript) =>+ migratedContext && plan.manifest.agentKind !== 'pi'+ ? { ...transcript, sdkSessionId: migratedContext.id(transcript.sdkSessionId) }+ : transcript,);}const piSessionsRoot = path.resolve(@@ -452,7 +514,7 @@ export async function commitShareImport(if (zip.file(transcript.path)) {piTranscriptTargets.set(transcript.sdkSessionId,- path.join(piSessionsRoot, transcript.sdkSessionId),+ path.join(piSessionsRoot, ...(runtimeScope.migration ? [runtimeScope.migration.sessionId] : []), transcript.sdkSessionId),);}}@@ -469,7 +531,7 @@ export async function commitShareImport(? portableId? (piTranscriptTargets.get(portableId) ?? null): null- : portableId;+ : portableId ? migratedContext?.id(portableId) ?? portableId : null;const activeSdkSessionId = resolveActiveSdkSessionId(manifest.agentKind,portableActiveSdkSessionId,@@ -636,22 +698,8 @@ export async function commitShareImport(// worktree 步之后计算。盘上已有同名转录不算冲突(典型是删除 Maker 会话后// 重导——软删不清理转录):写入步用 wx 独占写,已存在则复用盘上副本,绝不// 覆盖(sdk id 是 UUID,同名即同一会话,且盘上副本可能含删除前 resume 产生- // 的更新内容)。协同包的 cc Worker 与 lead 落同一转码目录(同 workingDir)。- const hasCcTranscripts =- (manifest.agentKind === 'cc' && bundledTranscripts.length > 0) ||- workerPlans.some(- (plan) => plan.manifest.agentKind === 'cc' && (plan.bundledTranscripts?.length ?? 0) > 0,- );- let claudeTargetDir: string | null = null;+ // 的更新内容)。普通分享共用目录;迁移按成员恢复各自目录。let transcriptsPlaceable = true;- if (hasCcTranscripts) {- if (!isClaudeProjectKeyExact(workingDir)) {- // 超长路径无法精确复算转码目录:降档为仅历史,不阻断导入。- transcriptsPlaceable = false;- } else {- claudeTargetDir = path.join(projectsRoot, sanitizeClaudeProjectKey(workingDir));- }- }// 1. 媒体还原 + URL 重写规则收集。session 图片按「原 URL → 新 URL」逐条进// urlMap(而非单一 host 替换):fork 链会话可能同时带多个旧 session host@@ -712,6 +760,7 @@ export async function commitShareImport(title: string;bundled: BundledTranscript[];activeSdkSessionId: string | null;+ workingDir: string;}> = [{agentKind: manifest.agentKind,@@ -719,6 +768,7 @@ export async function commitShareImport(title: manifest.title,bundled: bundledTranscripts,activeSdkSessionId,+ workingDir,},...workerPlans.map((plan) => ({agentKind: plan.manifest.agentKind,@@ -726,6 +776,7 @@ export async function commitShareImport(title: plan.manifest.title,bundled: plan.bundledTranscripts ?? [],activeSdkSessionId: plan.activeSdkSessionId,+ workingDir: plan.workingDir ?? workingDir,})),];@@ -734,10 +785,18 @@ export async function commitShareImport(// 只删本次真实写入的文件。复用同样计入 transcriptsWritten(resume 可用,// 保真度不降档)。let transcriptsWritten = 0;- if (claudeTargetDir && transcriptsPlaceable) {- await guarded(() => fsp.mkdir(claudeTargetDir, { recursive: true }).then(() => undefined));+ {for (const restore of restorePlans) {- if (restore.agentKind !== 'cc') continue;+ if (restore.agentKind !== 'cc' || !restore.bundled.length) continue;+ if (!isClaudeProjectKeyExact(restore.workingDir)) {+ transcriptsPlaceable = false;+ continue;+ }+ const claudeTargetDir = path.join(+ projectsRoot,+ sanitizeClaudeProjectKey(restore.workingDir),+ );+ await guarded(() => fsp.mkdir(claudeTargetDir, { recursive: true }).then(() => undefined));for (const t of restore.bundled) {const file = zip.file(t.path);if (!file) continue;@@ -745,13 +804,16 @@ export async function commitShareImport(try {const transcriptBytes = Buffer.from(await guarded(() => file.async('nodebuffer')));assertStillValid();- await fsp.writeFile(target, transcriptBytes, { flag: 'wx' });+ 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' });journal.push(async () => {await fsp.rm(target, { force: true });});assertStillValid();} catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;+ if (migratedContext || (err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;log.info('transcript already on disk, reusing', { sdkSessionId: t.sdkSessionId });assertStillValid();}@@ -776,6 +838,7 @@ export async function commitShareImport(Buffer.from(await guarded(() => file.async('nodebuffer'))),journal,assertStillValid,+ Boolean(migratedContext),);transcriptsWritten += 1;}@@ -801,10 +864,16 @@ export async function commitShareImport(assertStillValid();const written = await importSharedCodexThread({threadId,- stateRows,- rolloutBuffer,- rolloutFilename: rolloutRef ? path.posix.basename(rolloutRef.path) : null,- newCwd: workingDir,+ migration: Boolean(migratedContext),+ stateRows: migratedContext ? migratedContext.stateRows(stateRows) : stateRows,+ rolloutBuffer: migratedContext && rolloutBuffer ? migratedContext.transcript(rolloutBuffer, 'codex') : rolloutBuffer,+ 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,+ (nativeId) => migratedContext?.id(nativeId) ?? nativeId,+ )+ : null,+ newCwd: restore.workingDir,title: restore.title,updatedAt: now,});@@ -835,12 +904,13 @@ export async function commitShareImport(id: randomUUID(),clientId: m.clientId,role: m.role,- content: rewriteMediaUrls(m.content, rewriteRules),+ content: rewriteMediaUrls(migratedContext && m.role === 'agent_switch'+ ? migratedContext.metadata(m.content) ?? m.content : m.content, rewriteRules),toolUseId: m.toolUseId,agentMeta:agentKind === 'pi'? rewritePiAgentMetaForImport(m.agentMeta, piTranscriptTargets)- : m.agentMeta,+ : migratedContext ? migratedContext.metadata(m.agentMeta) : m.agentMeta,agentKind: m.agentKind,createdAt: m.createdAt,rewindAt: m.rewindAt,@@ -885,15 +955,28 @@ export async function commitShareImport((typeof plan.snapshot.title === 'string' && plan.snapshot.title) ||plan.manifest.title ||'Worker',- workspaceKind: manifest.workspaceKind,+ workspaceKind:+ runtimeScope.migration && typeof plan.snapshot.workspaceKind === 'string'+ ? plan.snapshot.workspaceKind+ : manifest.workspaceKind,orcaRole: 'worker' as const,snapshot: plan.snapshot,- draftPrefs,+ draftPrefs:+ runtimeScope.migration?.agentPrefs?.[plan.manifest.agentKind] ?? draftPrefs,// 导入端草稿偏好按 vendor 存,跨 vendor 的 Worker 用内置兜底模型。- applyDraftPrefs: plan.manifest.agentKind === manifest.agentKind,- // 与 OrcaWorkerCreationService 同口径:Worker 固定 auto,不继承。- permissionModeOverride: 'auto',- workingDir,+ applyDraftPrefs:+ !!runtimeScope.migration || plan.manifest.agentKind === manifest.agentKind,+ // 普通分享沿用 auto;迁移不继承源机器的权限授权。+ permissionModeOverride: runtimeScope.migration+ ? plan.manifest.agentKind === 'cc'+ ? 'default'+ : 'ask'+ : 'auto',+ status:+ runtimeScope.migration && plan.snapshot.status === 'archived'+ ? 'archived'+ : 'active',+ workingDir: plan.workingDir ?? workingDir,worktreePath,activeSdkSessionId: plan.activeSdkSessionId,now,@@ -907,6 +990,11 @@ export async function commitShareImport(conflictExisting.map((session) => session.id),async () => {assertStillValid();+ if (runtimeScope.migration && (manifest.exportFidelity !== 'full' || !transcriptsPlaceable || notes.includes('codexStateSkipped') ||+ transcriptsWritten < new Set(restorePlans.flatMap((restore) =>+ restore.bundled.map((transcript) => `${restore.agentKind}:${transcript.sdkSessionId}`))).size)) {+ throw codedError('SHARE_IMPORT_FAILED', 'MIGRATION_INCOMPLETE_CONTEXT');+ }finalTxState.outcome = 'in-flight';await dbClient.tx('session.importShare', {session: buildSessionRow({@@ -956,7 +1044,7 @@ export async function commitShareImport(bundledCount: bundledKeys.size,transcriptsWritten,});- if (hasCcTranscripts && !transcriptsPlaceable) notes.push('workdirKeyInexact');+ if (!transcriptsPlaceable) notes.push('workdirKeyInexact');log.info('session share imported', {newId,agentKind: manifest.agentKind,@@ -1272,18 +1360,20 @@ 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 {- await fsp.writeFile(target, buffer, { flag: 'wx' });+ if (migration) atomicWriteFileSync(target, buffer.toString('utf8'));+ else await fsp.writeFile(target, buffer, { flag: 'wx' });journal.push(async () => {await fsp.rm(target, { force: true });});assertStillValid();} catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;+ if (migration || (err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;assertStillValid();}}@@ -1328,6 +1418,7 @@ function buildSessionRow(params: {draftPrefs: ShareImportDraftPrefs | null;applyDraftPrefs: boolean;permissionModeOverride?: string;+ status?: 'active' | 'archived';workingDir: string;worktreePath: string | null;activeSdkSessionId: string | null;@@ -1364,7 +1455,7 @@ function buildSessionRow(params: {typeof draftPrefs?.providerId === 'string' && draftPrefs.providerId.length > 0? draftPrefs.providerId: null,- status: 'active',+ status: params.status ?? 'active',sdkSessionId: activeSdkSessionId,totalTokenUsage: num(snapshot.totalTokenUsage, 0),totalCostUsd: num(snapshot.totalCostUsd, 0),diff --git a/apps/desktop/src/main/task-migration/__tests__/handoff.test.ts b/apps/desktop/src/main/task-migration/__tests__/handoff.test.tsnew file mode 100644index 0000000000..3e535b9b68--- /dev/null+++ b/apps/desktop/src/main/task-migration/__tests__/handoff.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest';+import { advanceHandoff, canCancelHandoff, type MigrationHandoff } from '../handoff';++function fixture(stage: MigrationHandoff['stage'] = 'preparing') {+ let durable: MigrationHandoff = {+ id: 'migration',+ sessionId: 'fork',+ sourceDeviceId: 'A',+ targetDeviceId: 'B',+ targetSessionId: 'child',+ targetProject: null,+ workingDir: '/shared',+ stage,+ };+ const calls: string[] = [];+ const deps = {+ save: async (r: MigrationHandoff) => {+ durable = structuredClone(r);+ calls.push(r.stage);+ },+ prepare: async () => {+ calls.push('snapshot');+ },+ import: async () => {+ calls.push('import');+ },+ cleanup: async () => {+ expect(durable.stage).toBe('transferring');+ calls.push('cleanup');+ },+ assertCurrent: () => {},+ };+ return { record: structuredClone(durable), deps, calls, durable: () => durable };+}++describe('task copy progress', () => {+ it('snapshots, imports and cleans up before recording completion', async () => {+ const f = fixture();+ await advanceHandoff(f.record, f.deps);+ expect(f.calls).toEqual(['snapshot', 'transferring', 'import', 'cleanup', 'complete']);+ expect(f.durable().workingDir).toBe('/shared');+ });+ it('keeps retryable progress after the target reply is lost', async () => {+ const f = fixture('transferring');+ f.deps.import = async () => {+ throw new Error('lost acknowledgement');+ };+ await expect(advanceHandoff(f.record, f.deps)).rejects.toThrow('lost acknowledgement');+ expect(f.durable().stage).toBe('transferring');+ expect(canCancelHandoff(f.record)).toBe(false);+ });+ it('replays the idempotent import when cleanup was interrupted', async () => {+ const f = fixture('transferring');+ f.deps.cleanup = async () => {+ throw new Error('reply lost');+ };+ await expect(advanceHandoff(f.record, f.deps)).rejects.toThrow();+ const restart = fixture(f.durable().stage);+ await advanceHandoff(restart.record, restart.deps);+ expect(restart.calls).toEqual(['import', 'cleanup', 'complete']);+ });+ it('keeps progress retryable if recording completion fails', async () => {+ const f = fixture('transferring');+ f.deps.save = async () => {+ throw new Error('disk full');+ };+ await expect(advanceHandoff(f.record, f.deps)).rejects.toThrow('disk full');+ expect(f.calls).toEqual(['import', 'cleanup']);+ expect(f.record.stage).toBe('transferring');+ });+ it('allows cancellation only before any target import could have started', () => {+ expect(canCancelHandoff(fixture().record)).toBe(true);+ for (const stage of ['transferring', 'complete', 'cancelled'] as const)+ expect(canCancelHandoff(fixture(stage).record)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/task-migration/__tests__/resources.test.ts b/apps/desktop/src/main/task-migration/__tests__/resources.test.tsnew file mode 100644index 0000000000..abe85db369--- /dev/null+++ b/apps/desktop/src/main/task-migration/__tests__/resources.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import v8 from 'node:v8';+import { assertDiskCapacity, assertMemoryCapacity } from '../resources';+afterEach(() => vi.restoreAllMocks());+const GB = 1024 ** 3;+function disk(free: number, separate = false) {+ vi.spyOn(fs, 'stat').mockImplementation(+ async (name) => ({ dev: separate && name === '/project' ? 2n : 1n }) as never,+ );+ vi.spyOn(fs, 'statfs').mockResolvedValue({ bavail: BigInt(free), bsize: 1n } as never);+}+describe('migration resource budgets', () => {+ it('permits projects larger than 2 GB when the destination has space', async () => {+ disk(20 * GB);+ await expect(+ assertDiskCapacity([{ path: '/project', bytes: 8 * GB }]),+ ).resolves.toBeUndefined();+ });+ it('combines staging and project allocations on one disk', async () => {+ disk(10 * GB);+ await expect(+ assertDiskCapacity([+ { path: '/staging', bytes: 5 * GB },+ { path: '/project', bytes: 5 * GB },+ ]),+ ).rejects.toThrow('MIGRATION_NO_SPACE');+ });+ it('checks separate destination volumes independently', async () => {+ disk(10 * GB, true);+ await expect(+ assertDiskCapacity([+ { path: '/staging', bytes: 5 * GB },+ { path: '/project', bytes: 5 * GB },+ ]),+ ).resolves.toBeUndefined();+ });+ it('adapts context budget to available memory and heap rather than 256 MB', () => {+ vi.spyOn(os, 'freemem').mockReturnValue(16 * GB);+ vi.spyOn(process, 'availableMemory').mockReturnValue(16 * GB);+ vi.spyOn(v8, 'getHeapStatistics').mockReturnValue({+ heap_size_limit: 8 * GB,+ used_heap_size: GB,+ } as never);+ expect(() => assertMemoryCapacity(GB)).not.toThrow();+ vi.mocked(os.freemem).mockReturnValue(GB);+ expect(() => assertMemoryCapacity(GB)).toThrow('MIGRATION_NO_MEMORY');+ });+});diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.tsnew file mode 100644index 0000000000..73c3454049--- /dev/null+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts@@ -0,0 +1,766 @@+vi.mock('../../mcp-integrations/moveSession', () => ({ moveSessionProjectFromHost: vi.fn() }));+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import syncFs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { createHash } from 'node:crypto';+import { AsyncLocalStorage } from 'node:async_hooks';+import { parseAttachmentOssRef } from '@cindy/device-link';++const state = vi.hoisted(() => ({+ root: '',+ context: null as unknown as AsyncLocalStorage<{ device: string; peer?: string }>,+ dbs: new Map<string, { query: ReturnType<typeof vi.fn>; queryOne: ReturnType<typeof vi.fn> }>(),+ rows: new Map<string, Map<string, Record<string, unknown>>>(),+ files: new Map<string, string>(),+ imports: vi.fn(),+ created: vi.fn(),+ snapshot: vi.fn(),+ close: vi.fn(),+ remove: vi.fn(),+ boundaryBusy: false,+ drain: vi.fn(),+ exported: vi.fn(),+ loseReply: '' as string,+ importsFail: false,+ siblingRunning: false,+ noSpace: false,+ restoresFail: false,+ sharingLatest: [] as Array<{+ shared_task_id: string;+ session_id: string;+ terminal: number;+ snapshot: null;+ }>,+ workers: [] as string[],+}));+vi.mock('../../localDb/ipc/sessionCreatedBroadcast', () => ({+ emitSessionCreated: (id: string) => state.created(id),+}));+vi.mock('electron', () => ({ app: { getPath: () => state.root }, ipcMain: { handle: vi.fn() } }));+vi.mock('../resources', async (original) => {+ const actual = await original<typeof import('../resources')>();+ return {+ ...actual,+ assertDiskCapacity: async (allocations: Parameters<typeof actual.assertDiskCapacity>[0]) => {+ if (state.noSpace && device() === 'B') throw new Error('MIGRATION_NO_SPACE');+ return actual.assertDiskCapacity(allocations);+ },+ };+});+function device() {+ return state.context.getStore()?.device ?? 'A';+}+vi.mock('../../appSessionState', () => ({+ ownerScopedUserDataPath: (...parts: string[]) => path.join(state.root, device(), ...parts),+ activeOwnerScopeKey: () => `${device()}:owner`,+ isAppSessionBoundaryPending: () => false,+}));+vi.mock('../../localDb/client/current', () => ({+ getDbClient: () => state.dbs.get(device()),+ tryGetDbClient: () => state.dbs.get(device()),+}));+vi.mock('../../localDb/sessionRouteLock', () => ({+ withSessionRouteLock: (_id: string, fn: () => unknown) => fn(),+ withSessionRouteLocks: (_ids: string[], fn: () => unknown) => fn(),+}));+vi.mock('../../localDb/orcaTeamStore', () => ({+ getActiveTeamByLead: async () => ({ id: 'team' }),+}));+vi.mock('../../device-link/invoke-context', () => ({+ getDeviceLinkInvokeContext: () => {+ const peer = state.context.getStore()?.peer;+ return peer ? { controllerDeviceId: peer } : null;+ },+}));+vi.mock('../../device-link/settings-store', () => ({+ readDeviceLinkSettings: () => ({ remoteControlEnabled: true, revokedControllers: [] }),+}));+vi.mock('../../device-link', () => ({+ getSelfDeviceId: device,+ remoteInvoke: async (+ target: string,+ _channel: string,+ args: Array<{ action: string }>,+ opts?: { preSend(): void },+ ) => {+ opts?.preSend();+ const peer = device();+ const result = await state.context.run({ device: target, peer }, () =>+ requestTaskMigration(args[0]),+ );+ if (state.loseReply === args[0].action) {+ state.loseReply = '';+ throw new Error('connection lost after commit');+ }+ return { ok: true, result };+ },+}));+vi.mock('../../device-link/filePeer', () => ({ tryUploadPeerAttachment: async () => null }));+vi.mock('../../device-link/mediaTransfer', () => ({+ MAX_MEDIA_BYTES: 2 * 1024 ** 3,+ removeRemote: (key: string) => state.remove(key),+ uploadLocalFile: async (file: string) => {+ const bytes = await fs.readFile(file),+ key = `migration/${state.files.size}`;+ state.files.set(key, file);+ return { key, size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };+ },+}));+vi.mock('../../device-link/remoteAttachment', () => ({+ parseRemoteAttachmentRef: (ref: string) => parseAttachmentOssRef(ref),+ materializeRemoteAttachment: (ref: { ossKey: string }, destination: string) =>+ fs.copyFile(state.files.get(ref.ossKey)!, destination),+}));+vi.mock('../../security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent() {} }));+vi.mock('../../cindy-media/refCompensationJournal', () => ({+ captureMediaRefCompensationScope: () => ({}),+}));+vi.mock('../../im/binding', () => ({ bindingStore: { findByTarget: () => null } }));+vi.mock('../../maker-host', () => ({+ getMakerIfReady: () => ({+ getSession: () => null,+ closeSession: state.close,+ getCapabilities: () => ({ availableModels: [] }),+ listActiveSessions: () =>+ state.siblingRunning ? [{ id: 'sibling', isTurnRunning: () => true }] : [],+ }),+}));+vi.mock('../../maker-host/createDesktopProviderService', () => ({+ getDesktopProviderService: () => ({ listProviders: async () => [] }),+}));+vi.mock('../../maker-host/model-route-guard', () => ({+ pickEnabledFallbackModel: () => ({ model: 'target-model', providerId: 'target-provider' }),+}));+vi.mock('../../worktree/resourceLock', async (original) => ({+ ...(await original<typeof import('../../worktree/resourceLock')>()),+ withWorktreeResourceLock: (_cwd: string, fn: () => unknown) => fn(),+ 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', mediaMissing: false };+ },+}));+vi.mock('../../session-share/sessionShareImport', () => ({+ inspectShareFile: async () => ({+ draftId: 'draft',+ encrypted: false,+ preview: { fidelity: 'full', orcaWorkerCount: state.workers.length, agentKind: 'cc' },+ }),+ cancelShareDraft() {},+ commitShareImport: async (+ _opts: unknown,+ scope: {+ migration: {+ sessionId: string;+ workingDir: string;+ workers?: Array<{ sessionId: string; sourceSessionId: string; workingDir: string }>;+ };+ },+ ) => {+ state.imports();+ const { sessionId, workingDir } = scope.migration;+ state.rows.get(device())!.set(sessionId, {+ id: sessionId,+ workingDir,+ remoteHostId: null,+ status: 'active',+ source: 'shared',+ agentKind: 'cc',+ orcaRole: null,+ });+ for (const worker of scope.migration.workers ?? []) {+ state.rows.get(device())!.set(worker.sessionId, {+ id: worker.sessionId,+ workingDir: worker.workingDir,+ remoteHostId: null,+ status: 'active',+ source: 'shared',+ agentKind: 'cc',+ orcaRole: 'worker',+ });+ }+ if (state.importsFail) {+ state.importsFail = false;+ throw new Error('DB committed but acknowledgement lost');+ }+ return { fidelity: 'full' };+ },+}));+vi.mock('../workspace', () => ({+ snapshotWorkspace: async (source: string, directory: string) => {+ state.snapshot();+ await fs.mkdir(directory, { recursive: true });+ await fs.copyFile(path.join(source, 'draft'), path.join(directory, 'a.tar.gz.enc'));+ return { unpackedBytes: 8, archive: { file: 'a.tar.gz.enc', files: {} } };+ },+ restoreWorkspace: async (_manifest: unknown, directory: string, target: string) => {+ await fs.copyFile(path.join(directory, 'a.tar.gz.enc'), path.join(target, 'draft'));+ if (state.restoresFail) throw new Error('restore interrupted');+ },+}));+import { requestTaskMigration, registerTaskMigrationIpc } from '../service';+import { moveSessionProjectFromHost } from '../../mcp-integrations/moveSession';+import { migrationScope } from '../journal';++async function settled(sessionId = 'fork') {+ // Match vitest.config.ts's platform budget rather than waitFor's 1-second default.+ await vi.waitFor(+ async () => {+ const status = await requestTaskMigration({ action: 'status', sessionId });+ expect(status.running).not.toBe(true);+ },+ { timeout: process.platform === 'win32' ? 60_000 : 5_000 },+ );+ return requestTaskMigration({ action: 'status', sessionId });+}+describe('resumable cross-computer copy', () => {+ beforeEach(async () => {+ registerTaskMigrationIpc(+ (id, dir, authority) => moveSessionProjectFromHost(() => false, id, dir, authority),+ { isBusy: () => state.boundaryBusy, drain: state.drain },+ );+ state.boundaryBusy = false;+ state.drain.mockReset();+ state.exported.mockClear();+ state.root = await fs.realpath(+ await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-migration-service-')),+ );+ state.context = new AsyncLocalStorage();+ state.rows.clear();+ state.dbs.clear();+ state.files.clear();+ state.imports.mockClear();+ state.created.mockReset();+ state.snapshot.mockClear();+ state.close.mockClear();+ state.remove.mockReset();+ state.loseReply = '';+ state.importsFail = false;+ state.siblingRunning = false;+ state.noSpace = false;+ state.restoresFail = false;+ state.sharingLatest = [];+ state.workers = [];+ const cwd = path.join(state.root, 'shared');+ await fs.mkdir(cwd);+ await fs.writeFile(path.join(cwd, 'draft'), 'original');+ for (const d of ['A', 'B', 'C']) {+ const rows = new Map<string, Record<string, unknown>>();+ state.rows.set(d, rows);+ state.dbs.set(d, {+ query: vi.fn(async (sql: string) =>+ sql.includes('shared_task_events')+ ? state.sharingLatest+ : sql.includes('FROM orca_workers')+ ? state.workers.map((sessionId) => ({ sessionId }))+ : [],+ ),+ queryOne: vi.fn(async (sql: string, args: string[]) =>+ sql.includes(' AS n') ? { n: 0 } : (rows.get(args[0]) ?? null),+ ),+ });+ }+ for (const id of ['fork', 'sibling'])+ state.rows.get('A')!.set(id, {+ id,+ workingDir: cwd,+ remoteHostId: null,+ status: 'active',+ source: 'desktop',+ agentKind: 'cc',+ orcaRole: null,+ });+ });+ afterEach(async () => {+ // A failed assertion must not tear down directories while a background transfer writes.+ for (const [device, rows] of state.rows) {+ await state.context.run({ device }, async () => {+ for (const id of rows.keys()) await settled(id);+ });+ }+ await fs.rm(state.root, { recursive: true, force: true });+ });+ const start = () =>+ requestTaskMigration({ action: 'start', sessionId: 'fork', targetDeviceId: 'B' });++ async function team() {+ const rows = state.rows.get('A')!;+ rows.get('fork')!.orcaRole = 'lead';+ const separate = path.join(state.root, 'worker-project');+ await fs.mkdir(separate);+ await fs.writeFile(path.join(separate, 'draft'), 'worker files');+ state.workers = ['shared-worker', 'separate-worker'];+ for (const id of state.workers)+ rows.set(id, {+ ...rows.get('fork'),+ id,+ orcaRole: 'worker',+ workingDir: id === 'shared-worker' ? rows.get('fork')!.workingDir : separate,+ });+ return separate;+ }++ it('flushes journal files using writable handles without truncation', async () => {+ const open = vi.spyOn(syncFs, 'openSync');+ const flush = syncFs.fsyncSync.bind(syncFs);+ const fsync = vi.spyOn(syncFs, 'fsyncSync').mockImplementation((fd) => {+ const index = open.mock.results.findLastIndex(+ (result) => result.type === 'return' && result.value === fd,+ );+ if (syncFs.fstatSync(fd).isFile()) {+ // Emulate Windows: FlushFileBuffers rejects a read-only file handle.+ expect(open.mock.calls[index]?.[1]).toBe('r+');+ }+ flush(fd);+ });+ try {+ await start();+ const result = await settled();+ expect(result.stage).toBe('complete');+ expect(migrationScope().read('fork')?.stage).toBe('complete');+ expect(fsync).toHaveBeenCalled();+ } finally {+ fsync.mockRestore();+ open.mockRestore();+ }+ });+ it('routes a remote project move through the source host helper without starting a transfer', async () => {+ vi.mocked(moveSessionProjectFromHost).mockResolvedValueOnce({+ ok: true,+ sessionId: 'fork',+ workingDir: '/another',+ workspaceKind: 'project',+ });+ const result = await state.context.run({ device: 'A', peer: 'B' }, () =>+ requestTaskMigration({ action: 'move-project', sessionId: 'fork', workingDir: '/another' }),+ );+ expect(moveSessionProjectFromHost).toHaveBeenLastCalledWith(+ expect.any(Function),+ 'fork',+ '/another',+ expect.any(Function),+ );+ expect(result).toMatchObject({+ deviceId: 'A',+ projectMove: { sessionId: 'fork', workingDir: '/another', workspaceKind: 'project' },+ });+ expect(state.snapshot).not.toHaveBeenCalled();+ expect(state.imports).not.toHaveBeenCalled();+ });+ it('replaces only preparation staging on retry instead of accumulating archive copies', async () => {+ state.noSpace = true;+ await start();+ const first = await settled();+ expect(first.stage).toBe('preparing');+ const dir = path.join(migrationScope().root, 'outgoing', first.targetSessionId!);+ await fs.writeFile(path.join(dir, 'superseded.tar.gz.enc'), 'old snapshot');+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ await settled();+ await expect(fs.stat(path.join(dir, 'superseded.tar.gz.enc'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');+ });+ it('filters stale project history and rechecks a directory removed after listing', async () => {+ const existing = path.join(state.root, 'shared');+ const missing = path.join(state.root, 'missing');+ const file = path.join(existing, 'draft');+ const removable = path.join(state.root, 'removable');+ await fs.mkdir(removable);+ state.dbs+ .get('B')!+ .query.mockResolvedValue([existing, missing, file, removable].map((path) => ({ path })));+ const caps = await state.context.run({ device: 'B' }, () =>+ requestTaskMigration({ action: 'caps' }),+ );+ expect(caps.projects).toEqual([existing, removable]);+ await fs.rmdir(removable);+ await expect(+ state.context.run({ device: 'B' }, () =>+ requestTaskMigration({+ action: 'preflight',+ targetProject: removable,+ resources: {+ transferBytes: 0,+ unpackedBytes: 0,+ contextBytes: 0,+ manifestBytes: 0,+ repositoryBytes: 0,+ entries: 0,+ },+ }),+ ),+ ).rejects.toThrow('MIGRATION_TARGET_UNKNOWN');+ await expect(+ requestTaskMigration({+ action: 'start',+ sessionId: 'fork',+ targetDeviceId: 'B',+ targetProject: file,+ }),+ ).rejects.toThrow('MIGRATION_TARGET_UNKNOWN');+ expect(state.snapshot).not.toHaveBeenCalled();+ });++ it('rejects an idle runtime whose terminal delivery or accepted queue is still pending', async () => {+ state.boundaryBusy = true;+ await expect(start()).rejects.toThrow('MIGRATION_TASK_RUNNING');+ expect(state.close).not.toHaveBeenCalled();+ expect(state.exported).not.toHaveBeenCalled();+ });+ it('waits for pending message persistence before exporting the conversation', async () => {+ let release!: () => void;+ state.drain.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ release = resolve;+ }),+ );+ await start();+ await vi.waitFor(() => expect(state.drain).toHaveBeenCalledOnce());+ expect(state.exported).not.toHaveBeenCalled();+ release();+ expect((await settled()).stage).toBe('complete');+ expect(state.exported).toHaveBeenCalledOnce();+ });++ it('keeps cleanup failures replayable without importing again or touching source files', async () => {+ state.remove.mockRejectedValueOnce(new Error('cleanup interrupted'));+ await start();+ const interrupted = await settled();+ expect(interrupted.stage).toBe('transferring');+ const directory = path.join(migrationScope().root, 'outgoing', interrupted.targetSessionId!);+ expect(await fs.readdir(directory)).toContain('workspace.json');+ const imports = state.imports.mock.calls.length;+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ await expect(fs.stat(directory)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(state.imports.mock.calls.length).toBe(imports);+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');+ });++ it('retains every failed receive directory in the existing receipt after a successful retry', async () => {+ state.restoresFail = true;+ await start();+ const first = await settled();+ expect(first.stage).toBe('transferring');+ const receipt = () =>+ state.context.run({ device: 'B' }, () =>+ migrationScope().readIncoming(first.targetSessionId!)!,+ );+ const firstDir = receipt().workingDir;+ await fs.writeFile(path.join(firstDir, 'draft'), 'user recovery edit');+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ await settled();+ const secondDir = receipt().workingDir;+ expect(receipt().retainedWorkingDirs).toEqual([firstDir]);+ state.restoresFail = false;+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ expect(receipt().retainedWorkingDirs).toEqual([firstDir, secondDir]);+ expect(await fs.readFile(path.join(firstDir, 'draft'), 'utf8')).toBe('user recovery edit');+ expect(await fs.readFile(path.join(secondDir, 'draft'), 'utf8')).toBe('original');+ expect(receipt().workingDir).not.toBe(firstDir);+ expect(receipt().workingDir).not.toBe(secondDir);+ });+ it('rejects insufficient destination space before uploading and remains cancellable', async () => {+ state.noSpace = true;+ await start();+ const status = await settled();+ expect(status.stage).toBe('preparing');+ expect(status.error).toBe('MIGRATION_NO_SPACE');+ expect(state.files.size).toBe(0);+ expect(state.imports).not.toHaveBeenCalled();+ await requestTaskMigration({ action: 'cancel', sessionId: 'fork' });+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');+ });+ it('keeps cancellation retryable when staging cleanup fails', async () => {+ state.noSpace = true;+ await start();+ const status = await settled();+ const directory = path.join(+ state.root,+ 'A',+ 'task-copies',+ 'outgoing',+ status.targetSessionId!,+ );+ const snapshot = await fs.readFile(path.join(directory, 'session.cshare'));+ const remove = fs.rm.bind(fs);+ const failCleanup = vi.spyOn(fs, 'rm').mockImplementation(async (file, options) => {+ if (String(file) === directory) throw new Error('cleanup denied');+ return remove(file, options);+ });+ try {+ await expect(requestTaskMigration({ action: 'cancel', sessionId: 'fork' })).rejects.toThrow(+ 'cleanup denied',+ );+ expect((await settled()).stage).toBe('preparing');+ await expect(start()).rejects.toThrow('MIGRATION_ALREADY_STARTED');+ expect(await fs.readFile(path.join(directory, 'session.cshare'))).toEqual(snapshot);+ } finally {+ failCleanup.mockRestore();+ }+ expect((await requestTaskMigration({ action: 'cancel', sessionId: 'fork' })).stage).toBe(+ 'cancelled',+ );+ await expect(fs.stat(directory)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');+ state.noSpace = false;+ await start();+ expect((await settled()).stage).toBe('complete');+ });+ it('reclaims interrupted upload parts before resource checks, preserving snapshots and other handoffs', async () => {+ const workerDir = await team();+ state.restoresFail = true;+ await start();+ const interrupted = await settled();+ expect(interrupted.stage).toBe('transferring');+ const directory = path.join(+ state.root,+ 'A',+ 'task-copies',+ 'outgoing',+ interrupted.targetSessionId!,+ );+ const leftovers = [directory, path.join(directory, '1')].map((dir) =>+ path.join(dir, 'parts-Ab12Cd'),+ );+ const unrelated = path.join(+ state.root,+ 'A',+ 'task-copies',+ 'outgoing',+ 'another-handoff',+ 'parts-Ab12Cd',+ );+ const sourceParts = path.join(workerDir, 'parts-Ab12Cd');+ for (const dir of [...leftovers, unrelated, sourceParts]) {+ await fs.mkdir(dir, { recursive: true });+ await fs.writeFile(path.join(dir, 'part'), 'retained bytes');+ }+ const snapshot = await fs.readFile(path.join(directory, 'session.cshare'));+ const uploads = state.files.size;+ const remove = fs.rm.bind(fs);+ const failCleanup = vi.spyOn(fs, 'rm').mockImplementation(async (file, options) => {+ if (String(file) === leftovers[0]) throw new Error('cleanup denied');+ return remove(file, options);+ });+ try {+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('transferring');+ expect(state.files.size).toBe(uploads);+ expect(await fs.readFile(path.join(leftovers[0], 'part'), 'utf8')).toBe('retained bytes');+ } finally {+ failCleanup.mockRestore();+ }+ state.noSpace = true;+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).error).toBe('MIGRATION_NO_SPACE');+ for (const dir of leftovers)+ await expect(fs.stat(dir)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readFile(path.join(directory, 'session.cshare'))).toEqual(snapshot);+ expect(state.files.size).toBe(uploads);+ state.noSpace = false;+ state.restoresFail = false;+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ for (const dir of [unrelated, sourceParts])+ expect(await fs.readFile(path.join(dir, 'part'), 'utf8')).toBe('retained bytes');+ expect(await fs.readFile(path.join(workerDir, 'draft'), 'utf8')).toBe('worker files');+ });+ it('adopts a committed import after its database reply is lost', async () => {+ state.importsFail = true;+ await start();+ expect((await settled()).stage).toBe('transferring');+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ expect(state.imports).toHaveBeenCalledTimes(1);+ });++ it('copies tasks with automation bindings without modifying the source', async () => {+ const db = state.dbs.get('A')!;+ const original = db.queryOne.getMockImplementation()!;+ db.queryOne.mockImplementation(async (sql, args) =>+ sql.includes('schedules') ? { n: 4 } : original(sql, args),+ );+ const before = structuredClone(state.rows.get('A')!.get('fork'));+ await start();+ const result = await settled();+ expect(result.stage).toBe('complete');+ expect(state.rows.get('A')!.get('fork')).toEqual(before);+ expect(state.close).not.toHaveBeenCalled();+ expect(db.queryOne.mock.calls.some(([sql]) => sql.includes('schedules'))).toBe(false);+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');+ });+ it('copies the complete team and keeps independent target directories', async () => {+ const separate = await team();+ const before = structuredClone([...state.rows.get('A')!]);+ await start();+ const result = await settled();+ expect(result.stage).toBe('complete');+ expect(state.snapshot).toHaveBeenCalledTimes(2);+ expect([...state.rows.get('A')!]).toEqual(before);+ const receipt = state.context.run({ device: 'B' }, () =>+ migrationScope().readIncoming(result.targetSessionId!)!,+ );+ expect(receipt.stage).toBe('active');+ expect(receipt.workers).toHaveLength(2);+ expect(receipt.workers![0].workingDir).toBe(receipt.workingDir);+ expect(receipt.workers![1].workingDir).not.toBe(separate);+ expect(await fs.readFile(path.join(separate, 'draft'), 'utf8')).toBe('worker files');+ expect(state.created).toHaveBeenCalledTimes(3);+ });+ it('recovers a lost receive reply without a second import or source retirement', async () => {+ state.loseReply = 'receive';+ await start();+ const interrupted = await settled();+ expect(interrupted.stage).toBe('transferring');+ const receipt = state.context.run({ device: 'B' }, () =>+ migrationScope().readIncoming(interrupted.targetSessionId!)!,+ );+ expect(receipt.stage).toBe('active');+ expect(state.rows.get('A')!.get('fork')!.status).toBe('active');+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ expect(state.imports).toHaveBeenCalledTimes(1);+ });+ it('allows another independent copy after completion', async () => {+ await start();+ const first = await settled();+ await start();+ const second = await settled();+ expect(second.stage).toBe('complete');+ expect(second.targetSessionId).not.toBe(first.targetSessionId);+ expect(state.rows.get('B')!.size).toBe(2);+ });+ it('does not scan unrelated or legacy journals when reading copy progress', async () => {+ const root = migrationScope().root;+ await fs.mkdir(path.join(root, 'records'), { recursive: true });+ await fs.writeFile(path.join(root, 'records', 'unrelated.json'), '{broken');+ expect(migrationScope().read('fork')).toBeNull();+ await start();+ expect((await settled()).stage).toBe('complete');+ });+ it('adopts the complete team after a lost import acknowledgement without duplicating workers', async () => {+ await team();+ state.importsFail = true;+ await start();+ expect((await settled()).stage).toBe('transferring');+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ expect(state.imports).toHaveBeenCalledTimes(1);+ expect(state.rows.get('B')!.size).toBe(3);+ });++ it('rejects the whole team when any worker has queued input and keeps the lead writable', async () => {+ await team();+ state.rows.get('A')!.get('separate-worker')!.payload = JSON.stringify([{ text: 'pending' }]);+ await expect(start()).rejects.toThrow('MIGRATION_TASK_QUEUED');+ expect(state.exported).not.toHaveBeenCalled();+ });++ it.each(['receiving', 'committed', 'imported'])(+ 'reclaims interrupted receive staging before retrying a %s receipt',+ async (stage) => {+ state.restoresFail = stage === 'receiving';+ state.importsFail = stage === 'committed';+ const remove = fs.rm.bind(fs);+ let staging = '';+ // Leave actual transfer artifacts behind as a process exit would. A completed+ // import must not confirm completion while cleanup still needs a retry.+ const cleanup = vi.spyOn(fs, 'rm').mockImplementation(async (target, options) => {+ if (+ device() === 'B' &&+ (await fs.stat(path.join(String(target), 'workspace.json')).catch(() => null))+ ) {+ staging = String(target);+ throw new Error('receive cleanup interrupted');+ }+ return remove(target, options);+ });+ try {+ await start();+ const interrupted = await settled();+ expect(interrupted.stage).toBe('transferring');+ expect(staging).not.toBe('');+ const receipt = state.context.run({ device: 'B' }, () =>+ migrationScope().readIncoming(interrupted.targetSessionId!)!,+ );+ expect(receipt.stage).toBe('receiving');+ const otherStaging = path.join(path.dirname(staging), 'other-migration');+ await fs.mkdir(otherStaging);+ await fs.writeFile(path.join(otherStaging, 'keep'), 'other transfer');+ await fs.writeFile(path.join(receipt.workingDir, 'draft'), 'user recovery edit');+ expect(await fs.readdir(staging)).toContain('workspace.json');+ const imports = state.imports.mock.calls.length;+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('transferring');+ expect(state.imports).toHaveBeenCalledTimes(imports);+ cleanup.mockRestore();+ state.restoresFail = false;+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ await expect(fs.stat(staging)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readFile(path.join(otherStaging, 'keep'), 'utf8')).toBe('other transfer');+ expect(state.imports).toHaveBeenCalledTimes(1);+ expect(await fs.readFile(path.join(receipt.workingDir, 'draft'), 'utf8')).toBe(+ 'user recovery edit',+ );+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe(+ 'original',+ );+ } finally {+ cleanup.mockRestore();+ }+ },+ );++ it('copies a Feishu task while leaving its source identity intact', async () => {+ state.rows.get('A')!.get('fork')!.source = 'feishu';+ await start();+ const result = await settled();+ expect(result.stage).toBe('complete');+ expect(state.rows.get('A')!.get('fork')!.source).toBe('feishu');+ expect(state.rows.get('B')!.get(result.targetSessionId!)!.source).toBe('shared');+ });+ it('does not disclose another source device receipt', async () => {+ await start();+ const result = await settled();+ await expect(+ state.context.run({ device: 'B', peer: 'C' }, () =>+ requestTaskMigration({+ action: 'receipt',+ id: result.targetSessionId!,+ sourceSessionId: 'fork',+ }),+ ),+ ).rejects.toThrow('MIGRATION_ID_CONFLICT');+ });++ it('discards a snapshot when a new turn finishes during preparation', async () => {+ state.snapshot.mockImplementationOnce(() => {+ state.rows.get('A')!.get('fork')!.updatedAt = 123;+ });+ await start();+ expect(await settled()).toMatchObject({+ stage: 'preparing',+ error: 'MIGRATION_SOURCE_CHANGED',+ });+ expect(state.imports).not.toHaveBeenCalled();+ expect(state.files.size).toBe(0);+ await requestTaskMigration({ action: 'retry', sessionId: 'fork' });+ expect((await settled()).stage).toBe('complete');+ });+ 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);+ expect((await settled()).stage).toBe('complete');+ expect(state.imports).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/task-migration/__tests__/transferParts.test.ts b/apps/desktop/src/main/task-migration/__tests__/transferParts.test.tsnew file mode 100644index 0000000000..3b43489b35--- /dev/null+++ b/apps/desktop/src/main/task-migration/__tests__/transferParts.test.ts@@ -0,0 +1,51 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import fs from 'node:fs/promises';+import path from 'node:path';+import os from 'node:os';+import { createHash } from 'node:crypto';+import { sendParts, receiveParts } from '../transferParts';+describe('migration through existing attachment-sized transfers', () => {+ let root: string;+ beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-migration-parts-'));+ });+ afterEach(async () => {+ await fs.rm(root, { recursive: true, force: true });+ });+ it('reassembles validated segments in order and keeps the source intact', async () => {+ const bytes = Buffer.from('project bytes spanning several objects');+ const source = path.join(root, 'source'),+ target = path.join(root, 'target');+ await fs.writeFile(source, bytes);+ const objects = new Map<string, Buffer>();+ const file = await sendParts(source, 7, async (part) => {+ const content = await fs.readFile(part),+ ref = String(objects.size);+ objects.set(ref, content);+ expect(content.length).toBeLessThanOrEqual(7);+ return {+ ref,+ size: content.length,+ sha256: createHash('sha256').update(content).digest('hex'),+ };+ });+ await receiveParts(file, target, async (part, destination) => {+ await fs.writeFile(destination, objects.get(part.ref)!);+ });+ expect(await fs.readFile(target)).toEqual(bytes);+ expect(await fs.readFile(source)).toEqual(bytes);+ expect((await fs.readdir(root)).sort()).toEqual(['source', 'target']);+ });+ it('stops on a truncated segment without consuming source data', async () => {+ await expect(+ receiveParts(+ { size: 8, parts: [{ ref: 'one', size: 8, sha256: 'a'.repeat(64) }] },+ path.join(root, 'target'),+ async (_part, destination) => {+ await fs.writeFile(destination, 'bad');+ },+ ),+ ).rejects.toThrow('MIGRATION_INVALID_FILE');+ expect(await fs.readdir(root)).toEqual(['target']);+ });+});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.tsnew file mode 100644index 0000000000..5c34a60f04--- /dev/null+++ b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts@@ -0,0 +1,161 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import path from 'node:path';+import os from 'node:os';+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('../../logger', () => ({+ createLogger: () => ({ debug() {}, info() {}, warn() {}, error() {} }),+}));+const state = vi.hoisted(() => ({ root: '' }));+vi.mock('../../worktree/gitExec', async (original) => {+ const actual = await original<typeof import('../../worktree/gitExec')>();+ return {+ ...actual,+ gitExec: (+ args: string[],+ cwd: string,+ options?: import('../../worktree/gitExec').GitExecOpts,+ ) =>+ actual.gitExec(args, cwd, {+ ...options,+ extraEnv: {+ ...options?.extraEnv,+ GIT_CONFIG_GLOBAL: path.join(state.root, 'git-global'),+ GIT_CONFIG_NOSYSTEM: '1',+ },+ }),+ };+});+import { snapshotWorkspace, restoreWorkspace, validateWorkspaceEntries } from '../workspace';+import { inventoryWorktree } from '../../worktree/recoveryArchiveIO';++const exec = promisify(execFile);+const git = async (cwd: string, ...args: string[]) =>+ (+ await exec('git', args, {+ cwd,+ env: {+ ...process.env,+ GIT_CONFIG_GLOBAL: path.join(state.root, 'git-global'),+ GIT_CONFIG_NOSYSTEM: '1',+ },+ })+ ).stdout;+describe('cross-machine project snapshots', () => {+ let source: string, target: string, artifacts: string;+ beforeEach(async () => {+ state.root = await fs.realpath(+ await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-migration-test-')),+ );+ source = path.join(state.root, 'source');+ target = path.join(state.root, 'target');+ artifacts = path.join(state.root, 'artifacts');+ await Promise.all([source, target, artifacts].map((p) => fs.mkdir(p)));+ });+ afterEach(async () => {+ await fs.rm(state.root, { recursive: true, force: true });+ });++ it('copies ordinary directory bytes without consuming the shared source', async () => {+ await fs.mkdir(path.join(source, 'ignored'));+ await fs.writeFile(path.join(source, 'ignored', 'local.env'), 'not tracked\n');+ await fs.writeFile(path.join(source, 'draft'), 'uncommitted\n');+ const before = await inventoryWorktree(source);+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());+ await restoreWorkspace(snapshot, artifacts, target);+ expect(await inventoryWorktree(target)).toEqual(before);+ expect(await inventoryWorktree(source)).toEqual(before);+ await fs.writeFile(path.join(target, 'draft'), 'new machine edit');+ expect(await fs.readFile(path.join(source, 'draft'), 'utf8')).toBe('uncommitted\n');+ });+ it('restores linked worktrees with HEAD, staged changes, unstaged changes and ignored files intact', async () => {+ await git(source, 'init', '-b', 'main');+ await git(source, 'config', 'user.name', 'Migration test');+ await git(source, 'config', 'user.email', 'migration@localhost');+ await fs.writeFile(path.join(source, 'tracked'), 'base\n');+ await fs.writeFile(path.join(source, '.gitignore'), 'ignored\n');+ await git(source, 'add', '.');+ await git(source, 'commit', '-m', 'fixture');+ const linked = path.join(state.root, 'fork');+ await git(source, 'worktree', 'add', '-b', 'fork', linked);+ await fs.writeFile(path.join(linked, 'tracked'), 'staged\n');+ await git(linked, 'add', 'tracked');+ await fs.writeFile(path.join(linked, 'tracked'), 'unstaged\n');+ await fs.writeFile(path.join(linked, 'ignored'), 'local file\n');+ await fs.writeFile(path.join(linked, 'untracked'), 'draft\n');+ const before = await inventoryWorktree(linked);+ const staged = await git(linked, 'diff', '--cached');+ const unstaged = await git(linked, 'diff');+ const head = await git(linked, 'rev-parse', 'HEAD');+ const snapshot = await snapshotWorkspace(linked, artifacts, randomUUID());+ expect(await git(linked, 'for-each-ref', 'refs/cindy/migration')).toBe('');+ await restoreWorkspace(snapshot, artifacts, target);+ expect(await git(target, 'for-each-ref', 'refs/cindy/migration')).toBe('');+ expect(await git(target, 'rev-parse', 'HEAD')).toBe(head);+ expect(await git(target, 'symbolic-ref', 'HEAD')).toBe('refs/heads/fork\n');+ expect(await git(target, 'diff', '--cached')).toBe(staged);+ expect(await git(target, 'diff')).toBe(unstaged);+ expect((await fs.stat(path.join(target, '.git'))).isDirectory()).toBe(true);+ expect(await inventoryWorktree(target)).toEqual(before);+ expect(await inventoryWorktree(linked)).toEqual(before);+ expect(await git(linked, 'diff', '--cached')).toBe(staged);+ expect(await fs.readFile(path.join(source, 'tracked'), 'utf8')).toBe('base\n');+ }, 30_000);+ it('refuses to overwrite a destination directory', async () => {+ await fs.writeFile(path.join(source, 'source'), 'copy');+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());+ await fs.writeFile(path.join(target, 'existing'), 'keep');+ await expect(restoreWorkspace(snapshot, artifacts, target)).rejects.toThrow(+ 'MIGRATION_TARGET_NOT_EMPTY',+ );+ expect(await fs.readFile(path.join(target, 'existing'), 'utf8')).toBe('keep');+ expect(await fs.readFile(path.join(source, 'source'), 'utf8')).toBe('copy');+ });+ 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');+ await git(source, 'config', 'user.email', 'migration@localhost');+ await fs.writeFile(path.join(source, 'tracked'), 'keep');+ await git(source, 'add', '.');+ await git(source, 'commit', '-m', 'fixture');+ await fs.mkdir(path.join(artifacts, 'repository.bundle'));+ await expect(snapshotWorkspace(source, artifacts, randomUUID())).rejects.toThrow();+ expect(await git(source, 'for-each-ref', 'refs/cindy/migration')).toBe('');+ expect(await fs.readFile(path.join(source, 'tracked'), 'utf8')).toBe('keep');+ expect(await git(source, 'status', '--porcelain')).toBe('');+ });+ it('rejects corrupted archives before writing destination files', async () => {+ await fs.writeFile(path.join(source, 'source'), 'copy');+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());+ const archivePath = path.join(artifacts, snapshot.archive.file);+ const bytes = await fs.readFile(archivePath);+ bytes[0] ^= 1;+ await fs.writeFile(archivePath, bytes);+ await expect(restoreWorkspace(snapshot, artifacts, target)).rejects.toThrow();+ expect(await fs.readdir(target)).toEqual([]);+ expect(await fs.readFile(path.join(source, 'source'), 'utf8')).toBe('copy');+ });+ it('handles empty project directories', async () => {+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());+ await restoreWorkspace(snapshot, artifacts, target);+ expect(await fs.readdir(target)).toEqual([]);+ });+ it('rejects traversal, colliding names and external symlinks', () => {+ const file = { kind: 'file' as const, mode: 0o644, hash: 'a'.repeat(64) };+ for (const name of ['../escape', '/absolute', 'a/.git/config', 'a\\b', 'CON'])+ expect(() => validateWorkspaceEntries({ [name]: file })).toThrow();+ expect(() => validateWorkspaceEntries({ A: file, a: file })).toThrow(+ 'MIGRATION_PATH_COLLISION',+ );+ expect(() =>+ validateWorkspaceEntries({ link: { kind: 'link', mode: 0o777, hash: '../outside' } }),+ ).toThrow('MIGRATION_EXTERNAL_LINK');+ });+});diff --git a/apps/desktop/src/main/task-migration/handoff.ts b/apps/desktop/src/main/task-migration/handoff.tsnew file mode 100644index 0000000000..6de10f0ff0--- /dev/null+++ b/apps/desktop/src/main/task-migration/handoff.ts@@ -0,0 +1,51 @@+/** Resumable copy progress. The source task is never retired. */+export type MigrationStage = 'preparing' | 'transferring' | 'complete' | 'cancelled';+export interface MigrationHandoff {+ id: string;+ sessionId: string;+ sourceDeviceId: string;+ targetDeviceId: string;+ targetSessionId: string;+ targetProject: string | null;+ workingDir: string;+ /** One copy record tracks the entire team; members never advance independently. */+ workers?: Array<{ sessionId: string; targetSessionId: string; workingDir: string }>;+ stage: MigrationStage;+ error?: string;+}+export interface HandoffDependencies {+ save(record: MigrationHandoff): Promise<void>;+ prepare(record: MigrationHandoff): Promise<void>;+ import(record: MigrationHandoff): Promise<void>;+ cleanup(record: MigrationHandoff): Promise<void>;+ assertCurrent(): void;+}++/** Every stage is replayable. Target import is idempotent by id and leaves the source task untouched. */+export async function advanceHandoff(+ record: MigrationHandoff,+ deps: HandoffDependencies,+): Promise<void> {+ const transition = async (stage: MigrationStage) => {+ deps.assertCurrent();+ const next = { ...record, stage, error: undefined };+ await deps.save(next);+ Object.assign(record, next);+ deps.assertCurrent();+ };+ deps.assertCurrent();+ if (record.stage === 'preparing') {+ await deps.prepare(record);+ await transition('transferring');+ }+ if (record.stage === 'transferring') {+ await deps.import(record);+ await deps.cleanup(record);+ await transition('complete');+ }+}++export function canCancelHandoff(record: MigrationHandoff): boolean {+ // No target side effect has been attempted in preparing. Once transferring, query/retry only.+ return record.stage === 'preparing';+}diff --git a/apps/desktop/src/main/task-migration/journal.ts b/apps/desktop/src/main/task-migration/journal.tsnew file mode 100644index 0000000000..e1c053a443--- /dev/null+++ b/apps/desktop/src/main/task-migration/journal.ts@@ -0,0 +1,104 @@+import fs from 'node:fs';+import path from 'node:path';+import {+ ownerScopedUserDataPath,+ activeOwnerScopeKey,+ isAppSessionBoundaryPending,+} from '../appSessionState';+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';+import type { MigrationHandoff } from './handoff';++export interface IncomingMigration {+ kind: 'incoming';+ id: string;+ sessionId: string;+ sourceDeviceId: string;+ sourceSessionId: string;+ stage: 'receiving' | 'active';+ workingDir: string;+ workers?: Array<{ sessionId: string; sourceSessionId: string; workingDir: string }>;+ /** Retained failed attempts; never delete or overwrite files a user may have opened. */+ retainedWorkingDirs?: string[];+}+export type MigrationRecord = (MigrationHandoff & { kind: 'outgoing' }) | IncomingMigration;+const validId = (value: string) => /^[a-zA-Z0-9_-]{1,128}$/.test(value);++export function migrationScope() {+ const owner = activeOwnerScopeKey();+ const root = ownerScopedUserDataPath('task-copies');+ const assertCurrent = () => {+ if (!owner || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())+ throw new Error('MIGRATION_OWNER_CHANGED');+ };+ const file = (sessionId: string, incoming = false) => {+ if (!validId(sessionId)) throw new Error('MIGRATION_INVALID_ID');+ return path.join(root, incoming ? 'receipts' : 'records', `${sessionId}.json`);+ };+ const readRecord = (sessionId: string, incoming = false): MigrationRecord | null => {+ assertCurrent();+ const raw = readAtomicFileSync(file(sessionId, incoming));+ if (!raw) return null;+ const record = JSON.parse(raw) as MigrationRecord;+ if (+ record.sessionId !== sessionId ||+ !['outgoing', 'incoming'].includes(record.kind) ||+ !/^[a-f0-9-]{36}$/.test(record.id) ||+ typeof record.workingDir !== 'string' ||+ !path.isAbsolute(record.workingDir) ||+ !validId(record.sourceDeviceId) ||+ (record.workers !== undefined &&+ (!Array.isArray(record.workers) ||+ record.workers.some(+ (worker) =>+ !validId(worker.sessionId) ||+ typeof worker.workingDir !== 'string' ||+ !path.isAbsolute(worker.workingDir) ||+ ('targetSessionId' in worker+ ? !validId(worker.targetSessionId)+ : !validId(worker.sourceSessionId)),+ ))) ||+ (record.kind === 'incoming'+ ? !['receiving', 'active'].includes(record.stage) ||+ !validId(record.sourceSessionId) ||+ (record.retainedWorkingDirs !== undefined &&+ (!Array.isArray(record.retainedWorkingDirs) ||+ record.retainedWorkingDirs.some(+ (dir) => typeof dir !== 'string' || !path.isAbsolute(dir),+ )))+ : !['preparing', 'transferring', 'complete', 'cancelled'].includes(record.stage) ||+ !validId(record.targetDeviceId) ||+ record.targetSessionId !== record.id)+ )+ throw new Error('MIGRATION_JOURNAL_INVALID');+ return record;+ };+ const readIncoming = (id: string) => readRecord(id, true) as IncomingMigration | null;+ const read = (id: string): MigrationRecord | null => readRecord(id) ?? readIncoming(id);+ return {+ root,+ assertCurrent,+ read,+ readIncoming,+ save(record: MigrationRecord) {+ assertCurrent();+ const target = file(record.sessionId, record.kind === 'incoming');+ atomicWriteFileSync(target, JSON.stringify(record));+ // A remote activation must never outrun the persisted source fence.+ const sync = (name: string, flags = 'r') => {+ const fd = fs.openSync(name, flags);+ try {+ fs.fsyncSync(fd);+ } finally {+ fs.closeSync(fd);+ }+ };+ // Windows FlushFileBuffers requires a writable handle; r+ preserves contents.+ sync(target, 'r+');+ if (process.platform !== 'win32') {+ sync(path.dirname(target));+ sync(root);+ sync(path.dirname(root));+ }+ },+ };+}diff --git a/apps/desktop/src/main/task-migration/resources.ts b/apps/desktop/src/main/task-migration/resources.tsnew file mode 100644index 0000000000..4d158017fc--- /dev/null+++ b/apps/desktop/src/main/task-migration/resources.ts@@ -0,0 +1,49 @@+import fs from 'node:fs/promises';+import os from 'node:os';+import v8 from 'node:v8';+import { constants } from 'node:buffer';++/** 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,+ ),+ );+}+export function assertMemoryCapacity(bytes: number): void {+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > memoryBudget())+ throw new Error('MIGRATION_NO_MEMORY');+}++/** Combine simultaneous allocations on the same filesystem, including separate mount paths. */+export async function assertDiskCapacity(+ allocations: Array<{ path: string; bytes: number }>,+): Promise<void> {+ const volumes = new Map<string, { free: bigint; required: bigint }>();+ for (const allocation of allocations) {+ if (!Number.isSafeInteger(allocation.bytes) || allocation.bytes < 0)+ throw new Error('MIGRATION_INVALID_MANIFEST');+ const [stat, space] = await Promise.all([+ fs.stat(allocation.path, { bigint: true }),+ fs.statfs(allocation.path, { bigint: true }),+ ]);+ const free = space.bavail * space.bsize;+ const previous = volumes.get(String(stat.dev));+ volumes.set(String(stat.dev), {+ free: previous && previous.free < free ? previous.free : free,+ required: (previous?.required ?? 0n) + BigInt(allocation.bytes),+ });+ }+ for (const { free, required } of volumes.values()) {+ // Relative reserve accounts for filesystem overhead and concurrent writes; no size ceiling.+ if (required + required / 10n > free) throw new Error('MIGRATION_NO_SPACE');+ }+}diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.tsnew file mode 100644index 0000000000..4444c9c2b9--- /dev/null+++ b/apps/desktop/src/main/task-migration/service.ts@@ -0,0 +1,1027 @@+import { randomUUID } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { app, ipcMain } from 'electron';+import {+ TASK_MIGRATION_CHANNEL,+ TASK_MIGRATION_LOCAL_CHANNEL,+ parseTaskMigrationRequest,+ buildAttachmentOssRef,+ parsePeerAttachmentRef,+ isSharedTaskPeer,+ FILE_PEER_MAX_BYTES,+ type MigrationFile,+ type MigrationResources,+ type MigrationFileRef,+ type MigrationFiles,+ type TaskMigrationRequest,+ type TaskMigrationView,+} from '@cindy/device-link';+import { getDbClient, tryGetDbClient } from '../localDb/client/current';+import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast';+import { withSessionRouteLocks } from '../localDb/sessionRouteLock';+import { getActiveTeamByLead } from '../localDb/orcaTeamStore';+import { getSelfDeviceId, remoteInvoke } from '../device-link';+import { getDeviceLinkInvokeContext } from '../device-link/invoke-context';+import { readDeviceLinkSettings } from '../device-link/settings-store';+import { withCrossProcessLock } from '../device-link/crossProcessLock';+import { tryUploadPeerAttachment } from '../device-link/filePeer';+import { uploadLocalFile, removeRemote, MAX_MEDIA_BYTES } from '../device-link/mediaTransfer';+import {+ materializeRemoteAttachment,+ parseRemoteAttachmentRef,+} from '../device-link/remoteAttachment';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';+import { throwIpcError } from '../utils/ipcValidate';+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';+import { captureMediaRefCompensationScope } from '../cindy-media/refCompensationJournal';+import { exportSessionShare } from '../session-share/sessionShareExport';+import {+ commitShareImport,+ inspectShareFile,+ cancelShareDraft,+ type ShareImportDraftPrefs,+} from '../session-share/sessionShareImport';+import type { moveSessionProjectFromHost } from '../mcp-integrations/moveSession';+import { physicalWorktreeKey, withWorktreeResourceLocks } from '../worktree/resourceLock';+import { getMakerIfReady } from '../maker-host';+import { getDesktopProviderService } from '../maker-host/createDesktopProviderService';+import { pickEnabledFallbackModel } from '../maker-host/model-route-guard';+import { advanceHandoff, canCancelHandoff, type MigrationHandoff } from './handoff';+import { migrationScope, type MigrationRecord, type IncomingMigration } from './journal';+import { snapshotWorkspace, restoreWorkspace, type PortableWorkspace } from './workspace';++import { memoryBudget, assertMemoryCapacity, assertDiskCapacity } from './resources';+import { sendParts, receiveParts } from './transferParts';++type MoveProject = (+ sessionId: string,+ workingDir: string | null,+ assertAuthority: () => void,+) => ReturnType<typeof moveSessionProjectFromHost>;+// Bootstrap supplies the existing business handler; importing maker IPC here creates a cycle.+let moveProjectOnHost: MoveProject | undefined;+let sourceBoundary: { isBusy(sessionId: string): boolean; drain(): Promise<void> } | undefined;+const running = new Set<string>();+const errorCode = (error: unknown): string => {+ if ((error as NodeJS.ErrnoException)?.code === 'ENOSPC') return 'MIGRATION_NO_SPACE';+ const message = error instanceof Error ? error.message : '';+ return /\bMIGRATION_[A-Z_]+\b/.exec(message)?.[0] ?? 'MIGRATION_FAILED';+};+function selfId(): string {+ const id = getSelfDeviceId();+ if (!id) throw new Error('MIGRATION_NOT_CONNECTED');+ return id;+}+function captureScope() {+ const scope = migrationScope(),+ db = getDbClient();+ const caller = getDeviceLinkInvokeContext();+ const assertCurrent = () => {+ scope.assertCurrent();+ if (db !== tryGetDbClient()) throw new Error('MIGRATION_OWNER_CHANGED');+ if (caller) {+ const settings = readDeviceLinkSettings();+ if (+ caller.sharedTask ||+ isSharedTaskPeer(caller.controllerDeviceId) ||+ !settings.remoteControlEnabled ||+ settings.revokedControllers.includes(caller.controllerDeviceId)+ )+ throw new Error('MIGRATION_ACCESS_REVOKED');+ }+ };+ assertCurrent();+ return { ...scope, db, assertCurrent };+}+type Scope = ReturnType<typeof captureScope>;+async function projects(scope: Scope): Promise<string[]> {+ const rows = await scope.db.query<{ path: string }>(+ 'SELECT path FROM recent_workdirs ORDER BY last_used_at DESC LIMIT 100',+ [],+ );+ scope.assertCurrent();+ const available: string[] = [];+ // Recent paths are history, not proof that a mount or directory still exists.+ // Reuse this check for capabilities, preflight and receive-time validation.+ for (const row of rows) {+ if (+ await fs.stat(row.path).then(+ (stat) => stat.isDirectory(),+ () => false,+ )+ )+ available.push(row.path);+ }+ scope.assertCurrent();+ return available;+}+async function invoke(+ device: string,+ request: TaskMigrationRequest,+ scope: Scope,+): Promise<TaskMigrationView> {+ scope.assertCurrent();+ const response = await remoteInvoke(device, TASK_MIGRATION_CHANNEL, [request], {+ preSend: scope.assertCurrent,+ });+ scope.assertCurrent();+ if (!response.ok)+ throw new Error(+ response.error.code === 'CHANNEL_NOT_ALLOWED'+ ? 'MIGRATION_UNSUPPORTED'+ : errorCode(new Error(response.error.message)),+ );+ const result = response.result as TaskMigrationView;+ if (result?.supported !== true || result.deviceId !== device)+ throw new Error('MIGRATION_UNSUPPORTED');+ return result;+}+function view(scope: Scope, record: MigrationRecord | null): TaskMigrationView {+ return {+ supported: true,+ deviceId: selfId(),+ ...(record+ ? {+ stage: record.stage,+ running: running.has(`${scope.root}:${record.sessionId}`),+ ...(record.kind === 'outgoing'+ ? {+ targetDeviceId: record.targetDeviceId,+ targetSessionId: record.targetSessionId,+ ...(record.error ? { error: record.error } : {}),+ }+ : {}),+ }+ : {}),+ };+}++interface SourceSession {+ id: string;+ workingDir: string;+ remoteHostId: string | null;+ status: string;+ source: string;+ orcaRole: string | null;+ agentKind: 'cc' | 'codex' | 'pi';+ updatedAt: number;+}+async function assertSource(+ scope: Scope,+ sessionId: string,+ worker = false,+): Promise<SourceSession> {+ const row = await scope.db.queryOne<SourceSession>(+ 'SELECT id, working_dir AS workingDir, remote_host_id AS remoteHostId, status, source, orca_role AS orcaRole, agent_kind AS agentKind, updated_at AS updatedAt FROM sessions WHERE id = ?',+ [sessionId],+ );+ scope.assertCurrent();+ if (+ !row ||+ !(row.status === 'active' || (worker && row.status === 'archived')) ||+ !row.workingDir ||+ row.remoteHostId ||+ (worker ? row.orcaRole !== 'worker' : row.orcaRole === 'worker') ||+ !['desktop', 'shared', 'feishu'].includes(row.source)+ )+ throw new Error('MIGRATION_TASK_UNSUPPORTED');+ const queued = await scope.db.queryOne<{ payload: string }>(+ 'SELECT payload FROM agent_input_queue_snapshots WHERE session_id = ?',+ [sessionId],+ );+ scope.assertCurrent();+ if (queued?.payload) {+ let messages: unknown;+ try {+ messages = JSON.parse(queued.payload);+ } catch {+ throw new Error('MIGRATION_TASK_QUEUED');+ }+ if (!Array.isArray(messages) || messages.length) throw new Error('MIGRATION_TASK_QUEUED');+ }+ const live = getMakerIfReady()?.getSession(sessionId);+ if (!sourceBoundary) throw new Error('MIGRATION_HOST_NOT_READY');+ if (live?.isTurnRunning() || sourceBoundary.isBusy(sessionId))+ throw new Error('MIGRATION_TASK_RUNNING');+ return row;+}++async function sourceGroup(scope: Scope, sessionId: string): Promise<SourceSession[]> {+ const lead = await assertSource(scope, sessionId);+ if (lead.orcaRole !== 'lead') return [lead];+ const team = await getActiveTeamByLead(sessionId);+ scope.assertCurrent();+ if (!team) throw new Error('MIGRATION_TEAM_CHANGED');+ const reservations = await scope.db.queryOne<{ n: number }>(+ 'SELECT count(*) AS n FROM orca_worker_creation_reservations WHERE team_id = ? AND expires_at > ?',+ [team.id, Date.now()],+ );+ if (reservations?.n) throw new Error('MIGRATION_TASK_BUSY');+ const rows = await scope.db.query<{ sessionId: string }>(+ 'SELECT session_id AS sessionId FROM orca_workers WHERE team_id = ? ORDER BY created_at ASC, id ASC',+ [team.id],+ );+ const members = [lead];+ for (const row of rows) members.push(await assertSource(scope, row.sessionId, true));+ scope.assertCurrent();+ return members;+}++interface WorkspaceBundle extends PortableWorkspace {+ additionalWorkspaces?: PortableWorkspace[];+ workers?: Array<{ sourceSessionId: string; sessionId: string; workspace: number }>;+}+const workspaces = (workspace: WorkspaceBundle) => [+ workspace,+ ...(workspace.additionalWorkspaces ?? []),+];+const workspaceDirectory = (root: string, index: number) =>+ index ? path.join(root, String(index)) : root;+const transferFiles = (files: MigrationFiles) => [+ files.session,+ files.manifest,+ files.workspace,+ ...(files.repository ? [files.repository] : []),+ ...(files.additionalWorkspaces ?? []).flatMap((entry) => [+ entry.workspace,+ ...(entry.repository ? [entry.repository] : []),+ ]),+];++async function prepare(scope: Scope, record: MigrationHandoff) {+ const members = await sourceGroup(scope, record.sessionId);+ const sourceRevision = JSON.stringify(members);+ const expected = [+ { sessionId: record.sessionId, workingDir: record.workingDir },+ ...(record.workers ?? []),+ ];+ if (+ members.length !== expected.length ||+ (record.workers !== undefined) !== (members[0].orcaRole === 'lead') ||+ members.some(+ (member, index) =>+ member.id !== expected[index].sessionId || member.workingDir !== expected[index].workingDir,+ )+ )+ throw new Error('MIGRATION_TEAM_CHANGED');+ const directory = path.join(scope.root, 'outgoing', record.id);+ // Preparing owns no published transfer references. Replace only its staging copy.+ await fs.rm(directory, { recursive: true, force: true });+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });+ await withWorktreeResourceLocks(+ members.map((member) => member.workingDir),+ async () => {+ scope.assertCurrent();+ // Fork siblings can share cwd. Never snapshot while any known task is writing that tree.+ const sourceKeys = [+ ...new Set(+ await Promise.all(members.map((member) => physicalWorktreeKey(member.workingDir))),+ ),+ ];+ for (const session of getMakerIfReady()?.listActiveSessions() ?? []) {+ if (!session.isTurnRunning() && !sourceBoundary!.isBusy(session.id)) continue;+ const row = await scope.db.queryOne<{+ workingDir: string | null;+ remoteHostId: string | null;+ }>(+ 'SELECT working_dir AS workingDir, remote_host_id AS remoteHostId FROM sessions WHERE id = ?',+ [session.id],+ );+ if (row?.workingDir && !row.remoteHostId) {+ const key = await physicalWorktreeKey(row.workingDir);+ if (+ sourceKeys.some(+ (sourceKey) =>+ key === sourceKey ||+ key.startsWith(sourceKey + path.sep) ||+ sourceKey.startsWith(key + path.sep),+ )+ )+ throw new Error('MIGRATION_SHARED_DIRECTORY_BUSY');+ }+ }+ scope.assertCurrent();+ await sourceBoundary!.drain();+ scope.assertCurrent();+ if (members.some((member) => sourceBoundary!.isBusy(member.id)))+ throw new Error('MIGRATION_TASK_RUNNING');+ const result = await exportSessionShare({+ sessionId: record.sessionId,+ targetPath: path.join(directory, 'session.cshare'),+ sizeLimitBytes: memoryBudget(),+ migration: true,+ });+ scope.assertCurrent();+ if (result.status === 'oversize') throw new Error('MIGRATION_NO_MEMORY');+ if (result.status !== 'ok' || result.fidelity !== 'full' || result.mediaMissing)+ throw new Error('MIGRATION_INCOMPLETE_CONTEXT');+ const snapshots: PortableWorkspace[] = [];+ for (const [index, dir] of sourceKeys.entries())+ snapshots.push(+ await snapshotWorkspace(dir, workspaceDirectory(directory, index), record.id),+ );+ // Copy does not freeze input. Discard preparation if the task or team changed+ // while capturing conversation and files, including a turn that already finished.+ await sourceBoundary!.drain();+ if (JSON.stringify(await sourceGroup(scope, record.sessionId)) !== sourceRevision)+ throw new Error('MIGRATION_SOURCE_CHANGED');+ const workspace: WorkspaceBundle = {+ ...snapshots[0],+ ...(record.workers+ ? {+ additionalWorkspaces: snapshots.slice(1),+ workers: await Promise.all(+ record.workers.map(async (worker) => ({+ sourceSessionId: worker.sessionId,+ sessionId: worker.targetSessionId,+ workspace: sourceKeys.indexOf(await physicalWorktreeKey(worker.workingDir)),+ })),+ ),+ }+ : {}),+ };+ scope.assertCurrent();+ workspace.contextBytes =+ result.unpackedBytes ?? (await fs.stat(path.join(directory, 'session.cshare'))).size;+ atomicWriteFileSync(path.join(directory, 'workspace.json'), JSON.stringify(workspace));+ await preflight(scope, record, workspace, directory);+ },+ );+}++async function sendFile(+ scope: Scope,+ device: string,+ file: string,+ artifacts = path.dirname(file),+): Promise<MigrationFile> {+ const space = await fs.statfs(path.dirname(file));+ const partBytes = Math.floor(+ Math.min(FILE_PEER_MAX_BYTES, MAX_MEDIA_BYTES, (space.bavail * space.bsize) / 4),+ );+ return sendParts(file, partBytes, (part) => sendPart(scope, device, part, artifacts));+}+async function sendPart(+ scope: Scope,+ device: string,+ file: string,+ artifacts: string,+): Promise<MigrationFileRef> {+ scope.assertCurrent();+ const peer = await tryUploadPeerAttachment(+ device,+ file,+ 'application/octet-stream',+ (deviceId, channel, args) =>+ remoteInvoke(deviceId, channel, args, { preSend: scope.assertCurrent }),+ );+ scope.assertCurrent();+ if (peer) {+ const result = parsePeerAttachmentRef(peer);+ if (!result) throw new Error('MIGRATION_TRANSFER_FAILED');+ return { ref: peer, size: result.size, sha256: result.sha256 };+ }+ const result = await uploadLocalFile(file, { maxBytes: (await fs.stat(file)).size });+ scope.assertCurrent();+ const keysFile = path.join(artifacts, 'transfer-keys.json');+ const keys = JSON.parse(readAtomicFileSync(keysFile) ?? '[]') as string[];+ atomicWriteFileSync(keysFile, JSON.stringify([...keys, result.key]));+ return {+ ref: buildAttachmentOssRef({ ossKey: result.key, size: result.size, sha256: result.sha256 }),+ size: result.size,+ sha256: result.sha256,+ };+}+async function preflight(+ scope: Scope,+ record: MigrationHandoff,+ workspace: WorkspaceBundle,+ directory: string,+) {+ const sizes = await Promise.all(+ [+ 'session.cshare',+ 'workspace.json',+ ...workspaces(workspace).flatMap((entry, index) => [+ 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),+ );+ const resources: MigrationResources = {+ transferBytes: sizes.reduce((a, b) => a + b, 0),+ unpackedBytes: workspaces(workspace).reduce((sum, entry) => sum + entry.unpackedBytes, 0),+ contextBytes: Math.max(workspace.contextBytes ?? sizes[0], sizes[0]),+ manifestBytes: sizes[1],+ repositoryBytes: (+ await Promise.all(+ workspaces(workspace).map(async (entry, index) =>+ entry.git+ ? (await fs.stat(path.join(workspaceDirectory(directory, index), 'repository.bundle')))+ .size+ : 0,+ ),+ )+ ).reduce((a, b) => a + b, 0),+ entries: workspaces(workspace).reduce(+ (sum, entry) => sum + Object.keys(entry.archive.files ?? {}).length,+ 0,+ ),+ };+ await invoke(+ record.targetDeviceId,+ { action: 'preflight', targetProject: record.targetProject, resources },+ scope,+ );+}+async function checkTargetResources(+ scope: Scope,+ targetProject: string | null,+ resources: MigrationResources,+) {+ if (targetProject && !(await projects(scope)).includes(targetProject))+ throw new Error('MIGRATION_TARGET_UNKNOWN');+ assertMemoryCapacity(resources.contextBytes + resources.manifestBytes);+ await fs.mkdir(scope.root, { recursive: true });+ await assertDiskCapacity([+ { path: scope.root, bytes: resources.transferBytes * 2 + resources.contextBytes * 2 },+ {+ path: targetProject ?? scope.root,+ bytes: resources.unpackedBytes + resources.repositoryBytes * 3 + resources.entries * 4096,+ },+ {+ path: app.getPath('temp'),+ bytes: Math.min(resources.transferBytes, FILE_PEER_MAX_BYTES) * 2,+ },+ ]);+ scope.assertCurrent();+}+async function transfer(scope: Scope, record: MigrationHandoff) {+ const existing = await invoke(+ record.targetDeviceId,+ { action: 'receipt', id: record.id, sourceSessionId: record.sessionId },+ scope,+ );+ if (existing.stage === 'active') return;+ const directory = path.join(scope.root, 'outgoing', record.id);+ const workspace = JSON.parse(+ readAtomicFileSync(path.join(directory, 'workspace.json')) ?? 'null',+ ) as WorkspaceBundle;+ if (!workspace) throw new Error('MIGRATION_SNAPSHOT_MISSING');+ // startBackground holds this handoff's existing cross-process lock. A crash+ // skips sendParts' finally; reclaim only its temporary directories, including+ // separate Worker workspaces, before disk budgets or uploads are retried.+ for (const [index] of workspaces(workspace).entries()) {+ const artifacts = workspaceDirectory(directory, index);+ for (const entry of await fs.readdir(artifacts, { withFileTypes: true })) {+ if (!entry.isDirectory() || !/^parts-[A-Za-z0-9]{6}$/.test(entry.name)) continue;+ scope.assertCurrent();+ await fs.rm(path.join(artifacts, entry.name), { recursive: true, force: true });+ }+ }+ scope.assertCurrent();+ await preflight(scope, record, workspace, directory);+ const files: MigrationFiles = {+ session: await sendFile(scope, record.targetDeviceId, path.join(directory, 'session.cshare')),+ workspace: await sendFile(+ scope,+ record.targetDeviceId,+ path.join(directory, workspace.archive.file),+ ),+ manifest: await sendFile(scope, record.targetDeviceId, path.join(directory, 'workspace.json')),+ ...(workspace.git+ ? {+ repository: await sendFile(+ scope,+ record.targetDeviceId,+ path.join(directory, 'repository.bundle'),+ ),+ }+ : {}),+ };+ if (workspace.additionalWorkspaces?.length) {+ files.additionalWorkspaces = [];+ for (const [index, entry] of workspace.additionalWorkspaces.entries()) {+ const dir = workspaceDirectory(directory, index + 1);+ files.additionalWorkspaces.push({+ workspace: await sendFile(+ scope,+ record.targetDeviceId,+ path.join(dir, entry.archive.file),+ directory,+ ),+ ...(entry.git+ ? {+ repository: await sendFile(+ scope,+ record.targetDeviceId,+ path.join(dir, 'repository.bundle'),+ directory,+ ),+ }+ : {}),+ });+ }+ }+ const result = await invoke(+ record.targetDeviceId,+ {+ action: 'receive',+ id: record.id,+ sourceSessionId: record.sessionId,+ targetProject: record.targetProject,+ files,+ },+ scope,+ );+ if (result.stage !== 'active') throw new Error('MIGRATION_TARGET_NOT_READY');+}++function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {+ const key = `${scope.root}:${record.sessionId}`;+ if (running.has(key)) return;+ running.add(key);+ void withCrossProcessLock(+ path.join(scope.root, `source-${record.sessionId}.lock`),+ { label: 'task-migration', waitMs: 0 },+ async (lock) => {+ if (!lock.held) return;+ const current = scope.read(record.sessionId);+ if (!current || current.kind !== 'outgoing' || current.id !== record.id) return;+ await advanceHandoff(current, {+ assertCurrent: scope.assertCurrent,+ save: async (next) => scope.save({ ...next, kind: 'outgoing' }),+ prepare: (r) => prepare(scope, r),+ import: (r) => transfer(scope, r),+ cleanup: async (r) => {+ const directory = path.join(scope.root, 'outgoing', r.id);+ const keys = JSON.parse(+ readAtomicFileSync(path.join(directory, 'transfer-keys.json')) ?? '[]',+ ) as string[];+ for (const key of keys) {+ scope.assertCurrent();+ // Existing OSS lifecycle rules backstop best-effort remote deletion.+ await removeRemote(key);+ }+ scope.assertCurrent();+ await fs.rm(directory, { recursive: true, force: true });+ },+ });+ },+ )+ .catch((error) => {+ try {+ scope.assertCurrent();+ const latest = scope.read(record.sessionId);+ if (latest?.kind === 'outgoing' && latest.id === record.id)+ scope.save({ ...latest, error: errorCode(error) });+ } catch {+ /* Preserve the old-owner journal; never write under a replacement account. */+ }+ })+ .finally(() => running.delete(key));+}++async function receiveFile(scope: Scope, file: MigrationFile, destination: string) {+ await assertDiskCapacity([{ path: path.dirname(destination), bytes: file.size * 2 }]);+ return receiveParts(file, destination, (part, target) => receivePart(scope, part, target));+}+async function receivePart(scope: Scope, file: MigrationFileRef, destination: string) {+ const ref = parseRemoteAttachmentRef(file.ref);+ if (!ref || ref.size !== file.size || ref.sha256 !== file.sha256)+ throw new Error('MIGRATION_INVALID_FILE');+ scope.assertCurrent();+ await materializeRemoteAttachment(ref, destination, { size: file.size, sha256: file.sha256 });+ scope.assertCurrent();+}+async function receive(+ scope: Scope,+ request: Extract<TaskMigrationRequest, { action: 'receive' }>,+ peer: string,+) {+ await fs.mkdir(scope.root, { recursive: true, mode: 0o700 });+ scope.assertCurrent();+ return withCrossProcessLock(+ path.join(scope.root, `${request.id}.lock`),+ { label: 'task-migration', waitMs: 0 },+ async (lock) => {+ if (!lock.held) throw new Error('MIGRATION_TARGET_BUSY');+ let record = scope.readIncoming(request.id);+ if (+ record &&+ (record.kind !== 'incoming' ||+ record.sourceDeviceId !== peer ||+ record.sourceSessionId !== request.sourceSessionId)+ )+ throw new Error('MIGRATION_ID_CONFLICT');+ // The existing receipt lock owns one staging path across attempts. Reclaim an+ // interrupted receive before either reimporting or adopting an already committed task.+ const directory = path.join(scope.root, 'incoming', request.id);+ await fs.rm(directory, { recursive: true, force: true });+ scope.assertCurrent();+ if (record?.stage === 'active') return view(scope, record);+ const existing = await scope.db.queryOne<{ workingDir: string }>(+ 'SELECT working_dir AS workingDir FROM sessions WHERE id = ?',+ [request.id],+ );+ scope.assertCurrent();+ // Lost final DB acknowledgement: adopt only the row identified by our persisted incoming intent.+ if (existing) {+ if (!record || existing.workingDir !== record.workingDir)+ throw new Error('MIGRATION_ID_CONFLICT');+ for (const worker of record.workers ?? []) {+ const row = await scope.db.queryOne<{ workingDir: string }>(+ 'SELECT working_dir AS workingDir FROM sessions WHERE id = ?',+ [worker.sessionId],+ );+ if (row?.workingDir !== worker.workingDir) throw new Error('MIGRATION_ID_CONFLICT');+ }+ record = { ...record, stage: 'active' } as IncomingMigration;+ scope.save(record);+ for (const id of [record.sessionId, ...(record.workers ?? []).map((w) => w.sessionId)])+ emitSessionCreated(id);+ return view(scope, record);+ }+ const knownProjects = await projects(scope);+ if (request.targetProject && !knownProjects.includes(request.targetProject))+ throw new Error('MIGRATION_TARGET_UNKNOWN');+ const parent = request.targetProject ?? path.join(scope.root, 'projects');+ if (request.targetProject) {+ if (!(await fs.stat(parent)).isDirectory()) throw new Error('MIGRATION_TARGET_UNKNOWN');+ } else await fs.mkdir(parent, { recursive: true, mode: 0o700 });+ scope.assertCurrent();+ // Each failed attempt owns only its new directory. It never replaces a user's existing folder.+ const workingDir = path.join(parent, `cindy-${request.id.slice(0, 8)}-${randomUUID()}`);+ const retainedWorkingDirs = record+ ? [+ ...new Set([+ ...(record.retainedWorkingDirs ?? []),+ record.workingDir,+ ...(record.workers ?? []).map((worker) => worker.workingDir),+ ]),+ ]+ : [];+ record = {+ kind: 'incoming',+ id: request.id,+ sessionId: request.id,+ sourceDeviceId: peer,+ sourceSessionId: request.sourceSessionId,+ stage: 'receiving',+ workingDir,+ ...(retainedWorkingDirs.length ? { retainedWorkingDirs } : {}),+ };+ scope.save(record);+ await fs.mkdir(workingDir);+ try {+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });+ assertMemoryCapacity(request.files.manifest.size);+ await receiveFile(scope, request.files.manifest, path.join(directory, 'workspace.json'));+ const workspace = JSON.parse(+ await fs.readFile(path.join(directory, 'workspace.json'), 'utf8'),+ ) as WorkspaceBundle;+ if (+ !workspace ||+ (workspace.additionalWorkspaces !== undefined &&+ !Array.isArray(workspace.additionalWorkspaces)) ||+ (workspace.workers !== undefined && !Array.isArray(workspace.workers))+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ const snapshots = workspaces(workspace);+ if (+ snapshots.some(+ (entry) =>+ !/^[a-f0-9-]+\.tar\.gz\.enc$/.test(entry?.archive?.file ?? '') ||+ !Number.isSafeInteger(entry.unpackedBytes) ||+ entry.unpackedBytes < 0,+ ) ||+ snapshots.length !== 1 + (request.files.additionalWorkspaces?.length ?? 0)+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ const memberIds = new Set([request.id]);+ const sourceIds = new Set([request.sourceSessionId]);+ for (const worker of workspace.workers ?? []) {+ if (+ !worker ||+ !/^[a-f0-9-]{36}$/.test(worker.sessionId) ||+ !/^[a-zA-Z0-9_-]{1,128}$/.test(worker.sourceSessionId) ||+ memberIds.has(worker.sessionId) ||+ sourceIds.has(worker.sourceSessionId) ||+ !Number.isInteger(worker.workspace) ||+ worker.workspace < 0 ||+ worker.workspace >= snapshots.length+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ memberIds.add(worker.sessionId);+ sourceIds.add(worker.sourceSessionId);+ if (await scope.db.queryOne('SELECT id FROM sessions WHERE id = ?', [worker.sessionId]))+ throw new Error('MIGRATION_ID_CONFLICT');+ }+ if (+ snapshots.some(+ (_entry, index) =>+ index > 0 && !workspace.workers?.some((worker) => worker.workspace === index),+ )+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ await checkTargetResources(scope, request.targetProject, {+ transferBytes: transferFiles(request.files).reduce((sum, file) => sum + file.size, 0),+ unpackedBytes: snapshots.reduce((sum, entry) => sum + entry.unpackedBytes, 0),+ contextBytes: Math.max(+ workspace.contextBytes ?? request.files.session.size,+ request.files.session.size,+ ),+ manifestBytes: request.files.manifest.size,+ repositoryBytes: [request.files, ...(request.files.additionalWorkspaces ?? [])].reduce(+ (sum, entry) => sum + (entry.repository?.size ?? 0),+ 0,+ ),+ entries: snapshots.reduce(+ (sum, entry) => sum + Object.keys(entry.archive.files ?? {}).length,+ 0,+ ),+ });+ const targetDirs = [workingDir];+ for (let index = 1; index < snapshots.length; index++) {+ const target = path.join(parent, `cindy-${request.id.slice(0, 8)}-${randomUUID()}`);+ // Persist intent before allocation: even a process exit cannot orphan a directory.+ record = {+ ...record,+ retainedWorkingDirs: [...(record.retainedWorkingDirs ?? []), target],+ };+ scope.save(record);+ await fs.mkdir(target);+ targetDirs.push(target);+ }+ record = {+ ...record,+ retainedWorkingDirs: record.retainedWorkingDirs?.filter(+ (dir) => !targetDirs.includes(dir),+ ),+ workers: workspace.workers?.map((worker) => ({+ sourceSessionId: worker.sourceSessionId,+ sessionId: worker.sessionId,+ workingDir: targetDirs[worker.workspace],+ })),+ };+ scope.save(record);+ for (const [index, entry] of snapshots.entries()) {+ const dir = workspaceDirectory(directory, index);+ await fs.mkdir(dir, { recursive: true });+ const files = index ? request.files.additionalWorkspaces![index - 1] : request.files;+ await receiveFile(scope, files.workspace, path.join(dir, entry.archive.file));+ if (entry.git) {+ if (!files.repository) throw new Error('MIGRATION_INVALID_MANIFEST');+ await receiveFile(scope, files.repository, path.join(dir, 'repository.bundle'));+ }+ await restoreWorkspace(entry, dir, targetDirs[index]);+ }+ await receiveFile(scope, request.files.session, path.join(directory, 'session.cshare'));+ scope.assertCurrent();+ const inspected = await inspectShareFile(path.join(directory, 'session.cshare'), {+ resourceBudgetBytes: memoryBudget(),+ });+ try {+ if (+ inspected.encrypted ||+ inspected.preview.fidelity !== 'full' ||+ inspected.preview.orcaWorkerCount !== (record.workers?.length ?? 0)+ )+ throw new Error('MIGRATION_INCOMPLETE_CONTEXT');+ const agentKind =+ inspected.preview.agentKind === 'cc' ? 'claude-code' : inspected.preview.agentKind;+ const providers = await getDesktopProviderService().listProviders({+ allowSideEffects: true,+ });+ scope.assertCurrent();+ const route = pickEnabledFallbackModel(providers, agentKind);+ if (!route) throw new Error('MIGRATION_TARGET_MODEL_UNAVAILABLE');+ const effort =+ getMakerIfReady()+ ?.getCapabilities(agentKind)+ .availableModels.find((m) => m.id === route.model)?.defaultEffort ?? 'high';+ const agentPrefs: Partial<Record<'cc' | 'codex' | 'pi', ShareImportDraftPrefs>> = {};+ for (const agent of ['cc', 'codex', 'pi'] as const) {+ const kind = agent === 'cc' ? 'claude-code' : agent;+ const selected = pickEnabledFallbackModel(providers, kind);+ if (selected)+ agentPrefs[agent] = {+ ...selected,+ effort:+ getMakerIfReady()+ ?.getCapabilities(kind)+ .availableModels.find((m) => m.id === selected.model)?.defaultEffort ?? 'high',+ permissionMode: agent === 'cc' ? 'default' : 'ask',+ planMode: false,+ fastMode: false,+ };+ }+ const result = await commitShareImport(+ {+ draftId: inspected.draftId,+ workingDir,+ draftPrefs: {+ ...route,+ effort,+ permissionMode: agentKind === 'claude-code' ? 'default' : 'ask',+ planMode: false,+ fastMode: false,+ },+ },+ {+ dbClient: scope.db,+ assertStillValid: scope.assertCurrent,+ refCompensationScope: captureMediaRefCompensationScope(),+ migration: { sessionId: request.id, workingDir, workers: record.workers, agentPrefs },+ },+ );+ if (result.fidelity !== 'full') throw new Error('MIGRATION_INCOMPLETE_CONTEXT');+ } finally {+ cancelShareDraft(inspected.draftId);+ }+ } finally {+ // These are transfer artifacts only. Keep project files on all outcomes, including an unknown DB commit.+ // Confirm the active copy only after cleanup: the source can query the receipt after a lost reply.+ await fs.rm(directory, { recursive: true, force: true });+ }+ scope.assertCurrent();+ record = { ...record, stage: 'active' } as IncomingMigration;+ scope.save(record);+ for (const id of [record.sessionId, ...(record.workers ?? []).map((w) => w.sessionId)])+ emitSessionCreated(id);+ return view(scope, record);+ },+ );+}++export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationView> {+ const request = parseTaskMigrationRequest(raw),+ scope = captureScope();+ if (request.action === 'move-project') {+ if (!moveProjectOnHost) throw new Error('MIGRATION_HOST_NOT_READY');+ const result = await moveProjectOnHost(+ request.sessionId,+ request.workingDir,+ scope.assertCurrent,+ );+ scope.assertCurrent();+ if (!result.ok) throw new Error(`MIGRATION_PROJECT_${result.errorCode}`);+ return {+ ...view(scope, null),+ projectMove: {+ sessionId: result.sessionId,+ workingDir: result.workingDir,+ workspaceKind: result.workspaceKind,+ },+ };+ }+ if (request.action === 'preflight') {+ await checkTargetResources(scope, request.targetProject, request.resources);+ return view(scope, null);+ }+ if (request.action === 'caps') {+ const providers = await getDesktopProviderService().listProviders({ allowSideEffects: true });+ scope.assertCurrent();+ return {+ ...view(scope, null),+ projects: await projects(scope),+ teamMigration: true,+ agents: (['cc', 'codex', 'pi'] as const).filter(+ (agent) => !!pickEnabledFallbackModel(providers, agent === 'cc' ? 'claude-code' : agent),+ ),+ };+ }+ 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);+ const record = scope.readIncoming(request.id);+ if (request.action === 'receipt') {+ if (+ record &&+ (record.sourceDeviceId !== peer || record.sourceSessionId !== request.sourceSessionId)+ )+ throw new Error('MIGRATION_ID_CONFLICT');+ return view(scope, record);+ }+ throw new Error('MIGRATION_INVALID_REQUEST');+ }+ if (request.action === 'status') return view(scope, scope.read(request.sessionId));+ await fs.mkdir(scope.root, { recursive: true, mode: 0o700 });+ scope.assertCurrent();+ const initialMembers =+ request.action === 'start' ? await sourceGroup(scope, request.sessionId) : [];+ let nextCopy: (MigrationHandoff & { kind: 'outgoing' }) | undefined;+ const result = await withSessionRouteLocks(+ [request.sessionId, ...initialMembers.map((member) => member.id)],+ () =>+ withCrossProcessLock(+ path.join(scope.root, `source-${request.sessionId}.lock`),+ { label: 'task-copy', waitMs: 0 },+ async (lock) => {+ if (!lock.held) throw new Error('MIGRATION_TASK_BUSY');+ scope.assertCurrent();+ let record = scope.read(request.sessionId);+ if (request.action === 'cancel') {+ if (+ !record ||+ record.kind !== 'outgoing' ||+ !canCancelHandoff(record) ||+ running.has(`${scope.root}:${record.sessionId}`)+ )+ throw new Error('MIGRATION_CANNOT_CANCEL');+ const cancelled = { ...record, stage: 'cancelled' as const, error: undefined };+ // Keep the journal retryable until its staging data is gone.+ await fs.rm(path.join(scope.root, 'outgoing', record.id), {+ recursive: true,+ force: true,+ });+ scope.assertCurrent();+ scope.save(cancelled);+ return view(scope, cancelled);+ }++ if (request.action === 'start') {+ if (+ record &&+ !(record.kind === 'outgoing' && ['cancelled', 'complete'].includes(record.stage)) &&+ !(record.kind === 'incoming' && record.stage === 'active')+ )+ throw new Error('MIGRATION_ALREADY_STARTED');+ if (request.targetDeviceId === selfId() || isSharedTaskPeer(request.targetDeviceId))+ throw new Error('MIGRATION_TARGET_INVALID');+ const target = await invoke(request.targetDeviceId, { action: 'caps' }, scope);+ if (request.targetProject && !target.projects?.includes(request.targetProject))+ throw new Error('MIGRATION_TARGET_UNKNOWN');+ const members = await sourceGroup(scope, request.sessionId);+ if (+ members.length !== initialMembers.length ||+ members.some((member, index) => member.id !== initialMembers[index].id)+ )+ throw new Error('MIGRATION_TEAM_CHANGED');+ const source = members[0];+ if (source.orcaRole === 'lead' && target.teamMigration !== true)+ throw new Error('MIGRATION_UNSUPPORTED');+ if (members.some((member) => !target.agents?.includes(member.agentKind)))+ throw new Error('MIGRATION_TARGET_MODEL_UNAVAILABLE');+ const id = randomUUID();+ record = {+ kind: 'outgoing',+ id,+ sessionId: request.sessionId,+ sourceDeviceId: selfId(),+ targetDeviceId: request.targetDeviceId,+ targetSessionId: id,+ targetProject: request.targetProject ?? null,+ workingDir: source.workingDir,+ ...(source.orcaRole === 'lead'+ ? {+ workers: members.slice(1).map((member) => ({+ sessionId: member.id,+ targetSessionId: randomUUID(),+ workingDir: member.workingDir,+ })),+ }+ : {}),+ stage: 'preparing',+ };+ scope.save(record);+ }+ if (!record || record.kind !== 'outgoing') throw new Error('MIGRATION_NOT_FOUND');+ nextCopy = record;+ return view(scope, record);+ },+ ),+ );+ // Release admission before starting the background operation on the same lock.+ if (nextCopy) launch(scope, nextCopy);+ return result;+}++export function registerTaskMigrationIpc(+ moveProject: MoveProject,+ boundary: { isBusy(sessionId: string): boolean; drain(): Promise<void> },+) {+ moveProjectOnHost = moveProject;+ sourceBoundary = boundary;+ ipcMain.handle(TASK_MIGRATION_LOCAL_CHANNEL, async (event, device: unknown, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ const request = parseTaskMigrationRequest(raw);+ if (request.action === 'receive' || request.action === 'receipt')+ throwIpcError('PERMISSION_DENIED', 'MIGRATION_ACCESS_REVOKED');+ try {+ if (device == null || device === getSelfDeviceId())+ return await requestTaskMigration(request);+ if (+ typeof device !== 'string' ||+ !/^[a-zA-Z0-9_-]{1,128}$/.test(device) ||+ isSharedTaskPeer(device)+ )+ throw new Error('MIGRATION_TARGET_INVALID');+ return await invoke(device, request, captureScope());+ } catch (error) {+ throwIpcError('PRECONDITION_FAILED', errorCode(error));+ }+ });+}diff --git a/apps/desktop/src/main/task-migration/transferParts.ts b/apps/desktop/src/main/task-migration/transferParts.tsnew file mode 100644index 0000000000..7b7afb9209--- /dev/null+++ b/apps/desktop/src/main/task-migration/transferParts.ts@@ -0,0 +1,64 @@+import fs from 'node:fs/promises';+import { createReadStream, createWriteStream } from 'node:fs';+import path from 'node:path';+import { pipeline } from 'node:stream/promises';+import type { MigrationFile, MigrationFileRef } from '@cindy/device-link';+import { assertDiskCapacity } from './resources';++/** Segments reuse the existing attachment transport and its per-object limits. */+export async function sendParts(+ file: string,+ maxPartBytes: number,+ send: (file: string) => Promise<MigrationFileRef>,+): Promise<MigrationFile> {+ const size = (await fs.stat(file)).size;+ if (!Number.isSafeInteger(maxPartBytes) || maxPartBytes < 1)+ throw new Error('MIGRATION_NO_SPACE');+ if (size <= maxPartBytes) return send(file);+ const directory = await fs.mkdtemp(path.join(path.dirname(file), 'parts-'));+ const parts: MigrationFileRef[] = [];+ try {+ for (let offset = 0; offset < size; offset += maxPartBytes) {+ const length = Math.min(maxPartBytes, size - offset);+ await assertDiskCapacity([{ path: directory, bytes: length }]);+ const part = path.join(directory, 'part');+ await pipeline(+ createReadStream(file, { start: offset, end: offset + length - 1 }),+ createWriteStream(part, { flags: 'wx', mode: 0o600 }),+ );+ const sent = await send(part);+ if (sent.size !== length) throw new Error('MIGRATION_WORKSPACE_CHANGED');+ parts.push(sent);+ await fs.unlink(part);+ }+ return { size, parts };+ } finally {+ await fs.rm(directory, { recursive: true, force: true });+ }+}++export async function receiveParts(+ file: MigrationFile,+ destination: string,+ receive: (part: MigrationFileRef, destination: string) => Promise<void>,+): Promise<void> {+ if (!('parts' in file)) return receive(file, destination);+ const part = destination + '.part';+ let size = 0;+ try {+ await fs.writeFile(destination, '', { flag: 'wx', mode: 0o600 });+ for (const item of file.parts) {+ await assertDiskCapacity([+ { path: path.dirname(destination), bytes: file.size - size + item.size },+ ]);+ await receive(item, part);+ if ((await fs.stat(part)).size !== item.size) throw new Error('MIGRATION_INVALID_FILE');+ await pipeline(createReadStream(part), createWriteStream(destination, { flags: 'a' }));+ size += item.size;+ await fs.unlink(part);+ }+ if (size !== file.size) throw new Error('MIGRATION_INVALID_FILE');+ } finally {+ await fs.rm(part, { force: true });+ }+}diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.tsnew file mode 100644index 0000000000..81d12be77c--- /dev/null+++ b/apps/desktop/src/main/task-migration/workspace.ts@@ -0,0 +1,237 @@+import { randomBytes } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { runRecoveryArchiveTask } from '../worktree/recoveryArchiveWorkerClient';+import type { FileEvidence, WorktreeRecoveryArchive } from '../worktree/recoveryArchiveIO';+import {+ captureWorktreeContent,+ worktreeContentBaselineMatches,+} from '../worktree/contentSnapshot';+import { gitExec, GitExecError } from '../worktree/gitExec';+import { assertDiskCapacity } from './resources';++export interface PortableWorkspace {+ version: 1;+ archive: WorktreeRecoveryArchive;+ key: string;+ unpackedBytes: number;+ contextBytes?: number;+ git?: { head: string; headRef: string | null; indexTree: string; ref: string };+}++/** 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>();++ for (const [name, entry] of Object.entries(files)) {+ const parts = name.split('/');+ if (+ !name ||+ name.length > 4096 ||+ name.includes('\\') ||+ parts.some(+ (part) =>+ !part ||+ part === '.' ||+ part === '..' ||+ part.toLowerCase() === '.git' ||+ /[\x00-\x1f:*?"<>|]/.test(part) ||+ /[ .]$/.test(part) ||+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part),+ )+ ) {+ throw new Error('MIGRATION_NONPORTABLE_PATH');+ }+ const key = name.normalize('NFC').toLowerCase();+ if (folded.has(key)) throw new Error('MIGRATION_PATH_COLLISION');+ folded.add(key);+ if (+ !entry ||+ !['file', 'directory', 'link'].includes(entry.kind) ||+ !Number.isInteger(entry.mode) ||+ entry.mode < 0 ||+ entry.mode > 0o777 ||+ typeof entry.hash !== 'string'+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ if (entry.kind === 'file' && !/^[a-f0-9]{64}$/.test(entry.hash))+ throw new Error('MIGRATION_INVALID_MANIFEST');+ if (entry.kind === 'directory' && entry.hash !== '')+ throw new Error('MIGRATION_INVALID_MANIFEST');+ if (entry.kind === 'link') {+ if (+ !entry.hash ||+ entry.hash.includes('\\') ||+ path.posix.isAbsolute(entry.hash) ||+ /^[a-z]:/i.test(entry.hash)+ )+ throw new Error('MIGRATION_EXTERNAL_LINK');+ 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');+ // 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');+ }+ for (let i = 1; i < parts.length; i++) {+ if (files[parts.slice(0, i).join('/')]?.kind !== 'directory')+ throw new Error('MIGRATION_INVALID_MANIFEST');+ }+ }+}++/** No checkout, reset, stash, or source deletion. Existing recovery code preserves ignored bytes too. */+export async function snapshotWorkspace(+ root: string,+ directory: string,+ id: string,+): Promise<PortableWorkspace> {+ if ((await fs.lstat(root)).isSymbolicLink()) root = await fs.realpath(root);+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });+ let git: PortableWorkspace['git'];+ let baseline: Awaited<ReturnType<typeof captureWorktreeContent>> | undefined;+ try {+ const probe = await gitExec(['rev-parse', '--show-toplevel'], root, {+ extraEnv: { LC_ALL: 'C' },+ });+ if ((await fs.realpath(probe.stdout.trim())) !== (await fs.realpath(root)))+ throw new Error('MIGRATION_REQUIRES_REPOSITORY_ROOT');+ const entries = await gitExec(['ls-files', '--stage', '-z'], root);+ if (entries.stdout.split('\0').some((entry) => entry.startsWith('160000 ')))+ throw new Error('MIGRATION_SUBMODULE_UNSUPPORTED');+ const ref = `refs/cindy/migration/${id}`;+ try {+ baseline = await captureWorktreeContent(root, ref);+ git = {+ head: baseline.head,+ headRef: baseline.headRef ?? null,+ indexTree: baseline.indexTree,+ ref: baseline.ref,+ };+ await gitExec(+ ['bundle', 'create', path.join(directory, 'repository.bundle'), baseline.ref],+ root,+ );+ } finally {+ // The bundle owns these objects now; never retain recovery commits in the source.+ await gitExec(['update-ref', '-d', ref], root);+ }+ } catch (error) {+ // Only a positive "not a repository" verdict means plain directory. Other Git failures are real.+ if (!(error instanceof GitExecError) || !error.stderr.includes('not a git repository'))+ throw error;+ }+ const key = randomBytes(32);+ try {+ const space = await fs.statfs(directory);+ const archive = await runRecoveryArchiveTask({+ operation: 'create',+ root,+ directory,+ resourceId: id,+ key: new Uint8Array(key),+ encryptedKey: '',+ iv: randomBytes(12),+ maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),+ });+ archive.files = Object.fromEntries(+ Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),+ );+ validateWorkspaceEntries(archive.files);+ let unpackedBytes = 0;+ for (const [name, entry] of Object.entries(archive.files)) {+ 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)))+ throw new Error('MIGRATION_WORKSPACE_CHANGED');+ return {+ version: 1,+ archive,+ key: key.toString('base64'),+ unpackedBytes,+ ...(git ? { git } : {}),+ };+ } catch (error) {+ if (error instanceof Error && error.message.includes('MIGRATION_FILE_TOO_LARGE'))+ throw new Error('MIGRATION_NO_SPACE');+ throw error;+ } finally {+ key.fill(0);+ }+}++/** Caller supplies a newly-created private directory, never an existing user checkout. */+export async function restoreWorkspace(+ snapshot: PortableWorkspace,+ directory: string,+ target: string,+): Promise<void> {+ if (+ snapshot.version !== 1 ||+ !Number.isSafeInteger(snapshot.unpackedBytes) ||+ snapshot.unpackedBytes < 0 ||+ !/^[a-f0-9-]+\.tar\.gz\.enc$/.test(snapshot.archive.file) ||+ !/^[A-Za-z0-9+/]{43}=$/.test(snapshot.key)+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ validateWorkspaceEntries(snapshot.archive.files);+ if ((await fs.readdir(target)).length) throw new Error('MIGRATION_TARGET_NOT_EMPTY');+ const repositoryBytes = snapshot.git+ ? (await fs.stat(path.join(directory, 'repository.bundle'))).size+ : 0;+ await assertDiskCapacity([+ {+ path: target,+ bytes:+ snapshot.unpackedBytes ++ repositoryBytes * 3 ++ Object.keys(snapshot.archive.files).length * 4096,+ },+ ]);+ const archive = {+ ...snapshot.archive,+ files: Object.fromEntries(+ Object.entries(snapshot.archive.files).map(([name, entry]) => [+ name.split('/').join(path.sep),+ { ...entry, mode: entry.mode & (process.platform === 'win32' ? 0o666 : 0o777) },+ ]),+ ),+ };+ const key = Buffer.from(snapshot.key, 'base64');+ try {+ await runRecoveryArchiveTask({+ operation: 'extract',+ archive,+ directory,+ staging: target,+ keep: false,+ key: new Uint8Array(key),+ maxBytes: snapshot.unpackedBytes,+ });+ } finally {+ key.fill(0);+ }+ const git = snapshot.git;+ if (git) {+ if (+ ![git.head, git.indexTree].every((value) => /^[a-f0-9]{40,64}$/.test(value)) ||+ !/^refs\/cindy\/migration\/[a-f0-9-]{36}$/.test(git.ref) ||+ (git.headRef !== null && !git.headRef.startsWith('refs/heads/'))+ )+ throw new Error('MIGRATION_INVALID_MANIFEST');+ // Rebuild Git metadata locally; never copy source .git links, hooks, credentials or config.+ await gitExec(['init', '--template=', target], directory);+ await gitExec(+ ['fetch', '--no-tags', '--no-write-fetch-head', path.join(directory, 'repository.bundle'), git.ref],+ target,+ );+ if (git.headRef) {+ await gitExec(['check-ref-format', git.headRef], target);+ await gitExec(['update-ref', git.headRef, git.head], target);+ await gitExec(['symbolic-ref', 'HEAD', git.headRef], target);+ } else await gitExec(['update-ref', '--no-deref', 'HEAD', git.head], target);+ // Restore index separately from working files, retaining staged-only and unstaged changes.+ await gitExec(['read-tree', git.indexTree], target);+ }+}diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.tsindex a2a5acbedc..7679e34682 100644--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts@@ -25,8 +25,9 @@ function restorableMode(mode: number): number {return mode & (process.platform === 'win32' ? 0o666 : 0o777);}-export async function inventoryWorktree(root: string): Promise<Record<string, FileEvidence>> {+export async function inventoryWorktree(root: string, maxBytes?: number): Promise<Record<string, FileEvidence>> {const files: Record<string, FileEvidence> = Object.create(null);+ let bytes = 0;const walk = async (directory: string): Promise<void> => {for (const name of await fs.readdir(directory)) {if (directory === root && name === '.git') continue;@@ -40,6 +41,8 @@ export async function inventoryWorktree(root: string): Promise<Record<string, Fifiles[relative] = { kind: 'directory', hash: '', mode };await walk(absolute);} else if (stat.isFile()) {+ bytes += stat.size;+ if (maxBytes !== undefined && bytes > maxBytes) throw new Error('MIGRATION_FILE_TOO_LARGE');const hash = createHash('sha256');for await (const chunk of createReadStream(absolute)) hash.update(chunk);files[relative] = { kind: 'file', hash: hash.digest('hex'), mode };@@ -76,16 +79,27 @@ function decryptArchive(archive: WorktreeRecoveryArchive, key: Uint8Array) {}/** Fully authenticate before any restore is allowed to emit plaintext files. */-export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive, directory: string, key: Uint8Array): Promise<void> {+export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive, directory: string, key: Uint8Array, maxBytes?: number): Promise<void> {const files: Record<string, FileEvidence> = Object.create(null);const entries: Promise<void>[] = [];+ const seen = new Set<string>();+ let bytes = 0;const parser = tar.t({strict: true,onReadEntry(entry) {+ bytes += entry.size ?? 0;+ if (maxBytes !== undefined && bytes > maxBytes) throw new Error('MIGRATION_FILE_TOO_LARGE');const name = path.normalize(entry.path).replace(/[\\/]+$/, '');+ // An empty tree is represented by its root directory header (tar rejects zero-entry archives).+ if (name === '.' && entry.type === 'Directory' && Object.keys(archive.files).length === 0) {+ entry.resume();+ return;+ }if (path.isAbsolute(name) || name === '..' || name.startsWith(`..${path.sep}`) || name === '.git') {throw new Error('unsafe worktree archive entry');}+ if (!Object.hasOwn(archive.files, name) || seen.has(name)) throw new Error('unexpected worktree archive entry');+ seen.add(name);const check = (async () => {if (files[name]) throw new Error('duplicate worktree archive entry');const hash = createHash('sha256');@@ -114,22 +128,26 @@ export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive, diif (!sameWorktreeFiles(files, archive.files)) throw new Error('archive content does not match worktree inventory');}-export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array): Promise<WorktreeRecoveryArchive> {- const files = await inventoryWorktree(root);+export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array, maxBytes?: number): Promise<WorktreeRecoveryArchive> {+ const files = await inventoryWorktree(root, maxBytes);const cipher = createCipheriv('aes-256-gcm', key, iv);const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;await fs.mkdir(directory, { recursive: true });const target = archivePath(directory, { file });try {+ const names = Object.keys(files);+ // Keep one root header for an empty tree; noDirRecurse prevents capturing later additions.+ const packOptions = { cwd: root, gzip: true, follow: false, noDirRecurse: true, strict: true };+ const contents = tar.c(packOptions, names.length ? names : ['.']);await pipeline(- tar.c({ cwd: root, gzip: true, follow: false, noDirRecurse: true, strict: true }, Object.keys(files)),+ contents,cipher,createWriteStream(target, { flags: 'wx', mode: 0o600 }),);const handle = await fs.open(target, 'r+');try { await handle.sync(); } finally { await handle.close(); }const archive = { file, encryptedKey, iv: Buffer.from(iv).toString('base64'), tag: cipher.getAuthTag().toString('base64'), files };- await verifyRecoveryArchive(archive, directory, key);+ await verifyRecoveryArchive(archive, directory, key, maxBytes);if (!sameWorktreeFiles(await inventoryWorktree(root), files)) throw new Error('worktree changed during archive');return archive;} catch (error) {@@ -139,8 +157,8 @@ export async function createRecoveryArchive(root: string, resourceId: string, di}/** Authenticate first; keep mode fills only missing bytes of a verified partial restore. */-export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep: boolean, directory: string, key: Uint8Array): Promise<void> {- await verifyRecoveryArchive(archive, directory, key);+export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep: boolean, directory: string, key: Uint8Array, maxBytes?: number): Promise<void> {+ await verifyRecoveryArchive(archive, directory, key, maxBytes);await pipeline(createReadStream(archivePath(directory, archive)), decryptArchive(archive, key),tar.x({ cwd: staging, strict: true, preservePaths: false, unlink: !keep, keep }),diff --git a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts b/apps/desktop/src/main/worktree/recoveryArchiveTask.tsindex 9001da4f8e..3035300b89 100644--- a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts+++ b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts@@ -1,10 +1,10 @@import * as io from './recoveryArchiveIO';import type { FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO';-type ArchiveInput = { archive: WorktreeRecoveryArchive; directory: string; key: Uint8Array };+type ArchiveInput = { archive: WorktreeRecoveryArchive; directory: string; key: Uint8Array; maxBytes?: number };export type RecoveryArchiveTask =| { operation: 'inventory'; root: string }- | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array }+ | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array; maxBytes?: number }| ({ operation: 'verify' } & ArchiveInput)| ({ operation: 'extract'; staging: string; keep: boolean } & ArchiveInput);export type RecoveryArchiveResult<T extends RecoveryArchiveTask> =@@ -16,9 +16,9 @@ export async function executeRecoveryArchiveTask(task: RecoveryArchiveTask) {try {switch (task.operation) {case 'inventory': return await io.inventoryWorktree(task.root);- case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv);- case 'verify': return await io.verifyRecoveryArchive(task.archive, task.directory, task.key);- case 'extract': return await io.extractRecoveryArchive(task.archive, task.staging, task.keep, task.directory, task.key);+ case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv, task.maxBytes);+ case 'verify': return await io.verifyRecoveryArchive(task.archive, task.directory, task.key, task.maxBytes);+ case 'extract': return await io.extractRecoveryArchive(task.archive, task.staging, task.keep, task.directory, task.key, task.maxBytes);}} finally {if ('key' in task) task.key.fill(0);diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 2fcaae8c3c..906b7fc31f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1,3 +1,4 @@+import { TASK_MIGRATION_LOCAL_CHANNEL } from '@cindy/device-link';import type { WorktreeRecycleAction, WorktreeRecycleStatus } from '../shared/worktreeRecycle';import { FAVORITE_HOST_READY, FAVORITE_HOST_REQUEST, FAVORITE_HOST_REPLY, FAVORITE_HOST_CHANGED, type ModelFavoritesHostApi } from '../shared/modelFavoritesSync';import { invokeOpenPath } from './openPath';@@ -4428,6 +4429,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('shared-task:account', command),},deviceLink: {+ taskMigration: (deviceId: string | null, request: import('@cindy/device-link').TaskMigrationRequest): Promise<import('@cindy/device-link').TaskMigrationView> =>+ ipcRenderer.invoke(TASK_MIGRATION_LOCAL_CHANNEL, deviceId, request),getState: (): Promise<{remoteControlEnabled: boolean;keepAwake: boolean;diff --git a/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx b/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsxindex 7ec75ad57f..c03c548333 100644--- a/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx@@ -66,6 +66,10 @@ interface Props {* 未指名(从通用入口打开)时才由用户自己在下拉里选。*/initialDeviceId?: string | null;+ fixedDeviceId?: string;+ title?: string;+ confirmText?: string;+ errorText?: string;/*** 当前 draft 选中的 agent(由父层的 VendorSegmentedSwitcher 决定,dialog 不选 vendor)。* 轮 35 CRITICAL:Pi 已支持 SSH 远端(startSession 全量支持 remoteHostId)——@@ -80,6 +84,10 @@ export function AddRemoteProjectDialog({open,onOpenChange,initialDeviceId,+ fixedDeviceId,+ title,+ confirmText,+ errorText,agentVendor,onProjectAdded,}: Props) {@@ -118,8 +126,10 @@ export function AddRemoteProjectDialog({deviceName: d.name,label: d.name,}));- return [...ssh, ...dev];- }, [excludeSsh, sshHosts, devices]);+ return fixedDeviceId+ ? dev.filter(target => target.kind === 'device' && target.deviceId === fixedDeviceId)+ : [...ssh, ...dev];+ }, [excludeSsh, sshHosts, devices, fixedDeviceId]);const sshTargets = useMemo(() => targets.filter((tg) => tg.kind === 'ssh'), [targets]);const deviceTargets = useMemo(() => targets.filter((tg) => tg.kind === 'device'), [targets]);@@ -330,7 +340,7 @@ export function AddRemoteProjectDialog({}onOpenChange(false);} catch (err) {- toast.error(t(+ toast.error(errorText ?? t(err instanceof SshModelSelectionError? sshModelSelectionErrorKeys[err.reason]: mapIpcErrorToI18nKey(err, { fallback: 'newChat.addRemoteProject.toast.addFailed' }),@@ -338,7 +348,7 @@ export function AddRemoteProjectDialog({} finally {setBusy(false);}- }, [selectedTarget, adapter, path, confirm, onProjectAdded, onOpenChange, t]);+ }, [selectedTarget, adapter, path, confirm, onProjectAdded, onOpenChange, t, errorText]);const noTargets = targets.length === 0;// Pi 过滤掉 SSH 后无任何可用目标时,通用空态提示「加个 SSH 主机」是误导(Pi 用不了 SSH)。@@ -384,7 +394,7 @@ export function AddRemoteProjectDialog({className="text-15 font-medium"style={{ color: 'var(--text-primary)' }}>- {t('newChat.addRemoteProject.title')}+ {title ?? t('newChat.addRemoteProject.title')}</Dialog.Title><Dialog.Close asChild disabled={busy}><button@@ -473,7 +483,7 @@ export function AddRemoteProjectDialog({{/* Mode toggle — 默认「已有项目」,「浏览文件夹」为次要入口 */}<SegmentedControlclassName="shrink-0"- aria-label={t('newChat.addRemoteProject.title')}+ aria-label={title ?? t('newChat.addRemoteProject.title')}value={mode}disabled={busy}fullWidth@@ -689,7 +699,7 @@ export function AddRemoteProjectDialog({disabled={busy || noTargets || !selectedTarget || !path.trim()}className="min-w-[96px]">- {t('newChat.addRemoteProject.add')}+ {confirmText ?? t('newChat.addRemoteProject.add')}</Button></div></Dialog.Content>diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/AddRemoteProjectDialog.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/AddRemoteProjectDialog.test.tsxindex 86cef3cd46..3ddc50479d 100644--- a/apps/desktop/src/renderer/components/new-chat/__tests__/AddRemoteProjectDialog.test.tsx+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/AddRemoteProjectDialog.test.tsx@@ -3,7 +3,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libraimport { afterEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({- devices: [],+ devices: [] as Array<{ deviceId: string; name: string }>,sessions: [],t: (key: string) => key,listDir: vi.fn(async () => ({ parent: null, entries: [] })),@@ -25,6 +25,7 @@ import { AddRemoteProjectDialog } from '../AddRemoteProjectDialog';afterEach(() => {cleanup();+ mocks.devices = [];vi.unstubAllGlobals();vi.clearAllMocks();});@@ -81,3 +82,21 @@ describe('remote project mode selection', () => {});});});++it('locks the move folder picker to the task host and never falls back to another computer', async () => {+ mocks.devices = [{ deviceId: 'A', name: 'Source Mac' }, { deviceId: 'B', name: 'Other Mac' }];+ vi.stubGlobal('electronAPI', {+ remoteSsh: { list: async () => ({ hosts: [] }) },+ deviceLink: { invoke: async () => [] },+ });+ const props = { open: true, onOpenChange: vi.fn(), onProjectAdded: vi.fn(), initialDeviceId: 'A', fixedDeviceId: 'A', title: 'Move task', confirmText: 'Move' };+ const view = render(<AddRemoteProjectDialog {...props} />);+ await waitFor(() => expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('device:A'));+ expect(screen.queryByRole('option', { name: 'Other Mac' })).toBeNull();+ expect(screen.getByRole('heading', { name: 'Move task' })).toBeTruthy();+ mocks.devices = [{ deviceId: 'B', name: 'Other Mac' }];+ view.rerender(<AddRemoteProjectDialog {...props} />);+ await waitFor(() => expect((screen.getByRole('button', { name: 'Move' }) as HTMLButtonElement).disabled).toBe(true));+ expect(screen.queryByRole('option', { name: 'Other Mac' })).toBeNull();+ expect(props.onProjectAdded).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsxindex 9f981af12e..4f38d70d7e 100644--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx@@ -1,4 +1,5 @@import { SessionTaskMenu } from './sidebar/SessionTaskMenu';+import { TaskMigrationStatus } from './TaskMigrationStatus';/*** SessionContentHeader — 会话视图注入 ContentHeader 的中部内容* ---------------------------------------------------------------------------@@ -642,32 +643,18 @@ export function SessionContentHeader({}move={canMoveToProject && (- <DropdownMenuSub>- <DropdownMenuSubTrigger className={MENU_ROW_CLASS}>- <span className="flex-1">{t('ccAgent.sidebar.sessionMenu.moveToProject')}</span>- <ChevronRight- size={14}- className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]"- />- </DropdownMenuSubTrigger>- <DropdownMenuSubContent- sideOffset={4}- className={cn(MENU_SUB_CONTENT_CLASS, 'w-[320px] overflow-hidden')}- >- <SessionProjectMoveSubmenu- projectOptions={projectOptions}- currentWorkingDir={- session.workspaceKind === 'project' ? session.workingDir : null- }- isDialogue={session.workspaceKind === 'dialogue'}- onSelectProject={(workingDir) =>- void handleMoveSession({ kind: 'project', workingDir })- }- onBrowseProject={() => void handleMoveSession({ kind: 'browseProject' })}- onMoveToDialogue={() => void handleMoveSession({ kind: 'dialogue' })}- />- </DropdownMenuSubContent>- </DropdownMenuSub>+ <SessionProjectMoveSubmenu+ projectOptions={projectOptions}+ currentWorkingDir={+ session.workspaceKind === 'project' ? session.workingDir : null+ }+ isDialogue={session.workspaceKind === 'dialogue'}+ onSelectProject={(workingDir) =>+ void handleMoveSession({ kind: 'project', workingDir })+ }+ onBrowseProject={() => void handleMoveSession({ kind: 'browseProject' })}+ onMoveToDialogue={() => void handleMoveSession({ kind: 'dialogue' })}+ />)}/>@@ -676,6 +663,7 @@ export function SessionContentHeader({{/* session-git-pr-context:当前分支 + 关联 PR 徽标(项目任务与对话一致;非 git 目录且无 PR 时自动隐藏) */}<GitContextBadge session={session} />+ <TaskMigrationStatus session={session} />{tagEditorOpen && <TaskTagEditor session={session} onClose={() => setTagEditorOpen(false)} />}diff --git a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsxnew file mode 100644index 0000000000..5cf5fd6ba7--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx@@ -0,0 +1,62 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { isSharedTaskPeer, type TaskMigrationView } from '@cindy/device-link';+import type { Session } from '@/lib/ccAgent.types';+import { Button } from '@/components/ui/button';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';+import { TaskMigrationDialog } from './sidebar/TaskMigrationDialog';++/** Observe only mounted task details or open menus/editors, never idle sidebar rows. */+export function useTaskMigrationStatus(session: Session) {+ const [status, setStatus] = useState<TaskMigrationView | null>(null);+ useEffect(() => {+ setStatus(null);+ if (session.remoteHostId || isSharedTaskPeer(session.deviceLinkDeviceId ?? '')) return;+ const owner = getDataOwnerGeneration();+ let disposed = false,+ timer: ReturnType<typeof setTimeout> | undefined;+ const refresh = async () => {+ try {+ const next = await window.electronAPI.deviceLink.taskMigration(+ session.deviceLinkDeviceId ?? null,+ { action: 'status', sessionId: session.id },+ );+ if (!disposed && isDataOwnerGenerationCurrent(owner)) setStatus(next);+ } catch {+ /* Old or disconnected hosts keep their existing connection UI. */+ }+ if (!disposed && isDataOwnerGenerationCurrent(owner))+ timer = setTimeout(() => void refresh(), 10_000);+ };+ void refresh();+ return () => {+ disposed = true;+ clearTimeout(timer);+ };+ }, [session.id, session.deviceLinkDeviceId, session.remoteHostId]);+ return status;+}++export function TaskMigrationStatus({ session }: { session: Session }) {+ const { t } = useTranslation();+ const status = useTaskMigrationStatus(session);+ const [open, setOpen] = useState(false);+ useEffect(() => setOpen(false), [session.id, session.deviceLinkDeviceId]);+ if (!status?.stage || ['active', 'cancelled'].includes(status.stage)) return null;+ return (+ <>+ <Button+ size="sm"+ variant="secondary"+ className="max-w-64 truncate [-webkit-app-region:no-drag]"+ onClick={() => setOpen(true)}+ >+ {t(`taskMigration.stages.${status.stage}`)}+ </Button>+ {open && <TaskMigrationDialog session={session} onDismiss={() => setOpen(false)} />}+ </>+ );+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsxindex bfdffe73b8..1b29dc9e29 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx@@ -559,25 +559,14 @@ export const SessionCard = withSidebarNavigation<SessionCardProps>(function Sesssession.status !== 'archived';const moveToProjectSubmenu = canMoveToProject ? (- <DropdownMenuSub>- <DropdownMenuSubTrigger className={MENU_ROW_CLASS}>- <span className="flex-1">{t('ccAgent.sidebar.sessionMenu.moveToProject')}</span>- <ChevronRight size={14} className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]" />- </DropdownMenuSubTrigger>- <DropdownMenuSubContent- sideOffset={4}- className={cn(MENU_SUB_CONTENT_CLASS, 'w-[320px] overflow-hidden')}- >- <SessionProjectMoveSubmenu- projectOptions={projectOptions}- currentWorkingDir={session.workspaceKind === 'project' ? session.workingDir : null}- isDialogue={session.workspaceKind === 'dialogue'}- onSelectProject={handleMoveToProjectSelect}- onBrowseProject={handleMoveToProjectBrowse}- onMoveToDialogue={handleMoveToDialogue}- />- </DropdownMenuSubContent>- </DropdownMenuSub>+ <SessionProjectMoveSubmenu+ projectOptions={projectOptions}+ currentWorkingDir={session.workspaceKind === 'project' ? session.workingDir : null}+ isDialogue={session.workspaceKind === 'dialogue'}+ onSelectProject={handleMoveToProjectSelect}+ onBrowseProject={handleMoveToProjectBrowse}+ onMoveToDialogue={handleMoveToDialogue}+ />) : null;const statusIconNode = (diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsxindex 76e9a39812..af864a7d11 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx@@ -828,25 +828,14 @@ export const SessionItem = withSidebarNavigation<SessionItemProps>(function Sess) : null;const moveToProjectSubmenu = canMoveToProject ? (- <DropdownMenuSub>- <DropdownMenuSubTrigger className={MENU_ROW_CLASS}>- <span className="flex-1">{t('ccAgent.sidebar.sessionMenu.moveToProject')}</span>- <ChevronRight size={14} className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]" />- </DropdownMenuSubTrigger>- <DropdownMenuSubContent- sideOffset={4}- className={cn(MENU_SUB_CONTENT_CLASS, 'w-[320px] overflow-hidden')}- >- <SessionProjectMoveSubmenu- projectOptions={projectOptions}- currentWorkingDir={session.workspaceKind === 'project' ? session.workingDir : null}- isDialogue={session.workspaceKind === 'dialogue'}- onSelectProject={handleMoveToProjectSelect}- onBrowseProject={handleMoveToProjectBrowse}- onMoveToDialogue={handleMoveToDialogue}- />- </DropdownMenuSubContent>- </DropdownMenuSub>+ <SessionProjectMoveSubmenu+ projectOptions={projectOptions}+ currentWorkingDir={session.workspaceKind === 'project' ? session.workingDir : null}+ isDialogue={session.workspaceKind === 'dialogue'}+ onSelectProject={handleMoveToProjectSelect}+ onBrowseProject={handleMoveToProjectBrowse}+ onMoveToDialogue={handleMoveToDialogue}+ />) : null;const showAutomationRunAction =diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionProjectMoveSubmenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionProjectMoveSubmenu.tsxindex 0df4373eb5..3bdb51de5f 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionProjectMoveSubmenu.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionProjectMoveSubmenu.tsx@@ -6,12 +6,13 @@ import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdowimport { cn } from '@/lib/utils';export interface SessionProjectMoveSubmenuProps {+ heading?: string;projectOptions: readonly FolderPickerOption[];currentWorkingDir?: string | null;isDialogue: boolean;onSelectProject: (workingDir: string) => void;- onBrowseProject: () => void;- onMoveToDialogue: () => void;+ onBrowseProject?: () => void;+ onMoveToDialogue?: () => void;}function normalizePath(value: string | null | undefined): string | null {@@ -20,6 +21,7 @@ function normalizePath(value: string | null | undefined): string | null {}export function SessionProjectMoveSubmenu({+ heading,projectOptions,currentWorkingDir,isDialogue,@@ -33,7 +35,7 @@ export function SessionProjectMoveSubmenu({return (<><div className="px-3 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">- {t('ccAgent.sidebar.sessionMenu.moveToProjectHeading')}+ {heading ?? t('ccAgent.sidebar.sessionMenu.moveToProjectHeading')}</div><div className="pending-queue-scroll -mr-1 max-h-[224px] overflow-x-hidden overflow-y-auto pr-1">{projectOptions.length > 0 ? (@@ -68,23 +70,31 @@ export function SessionProjectMoveSubmenu({</div>)}</div>- <DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />- <DropdownMenuItem- onSelect={() => onBrowseProject()}- className="h-8 px-3 rounded-md text-sm text-[var(--msg-assistant-text)] focus:bg-[var(--cmd-palette-item-hover)]"- >- <FolderPlus size={16} className="mr-2 shrink-0 text-[var(--folder-item-icon)]" />- {t('ccAgent.sidebar.sessionMenu.browseProjectFolder')}- </DropdownMenuItem>- <DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />- <DropdownMenuItem- disabled={isDialogue}- onSelect={() => onMoveToDialogue()}- className="h-8 px-3 rounded-md text-sm text-[var(--msg-assistant-text)] focus:bg-[var(--cmd-palette-item-hover)] data-[disabled]:opacity-50 data-[disabled]:pointer-events-none"- >- <MessageCircle size={16} className="mr-2 shrink-0 text-[var(--folder-item-icon)]" />- {t('ccAgent.sidebar.sessionMenu.moveToDialogue')}- </DropdownMenuItem>+ {(onBrowseProject || onMoveToDialogue) && (+ <DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />+ )}+ {onBrowseProject && (+ <DropdownMenuItem+ onSelect={onBrowseProject}+ className="h-8 px-3 rounded-md text-sm text-[var(--msg-assistant-text)] focus:bg-[var(--cmd-palette-item-hover)]"+ >+ <FolderPlus size={16} className="mr-2 shrink-0 text-[var(--folder-item-icon)]" />+ {t('ccAgent.sidebar.sessionMenu.browseProjectFolder')}+ </DropdownMenuItem>+ )}+ {onMoveToDialogue && (+ <DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />+ )}+ {onMoveToDialogue && (+ <DropdownMenuItem+ disabled={isDialogue}+ onSelect={onMoveToDialogue}+ className="h-8 px-3 rounded-md text-sm text-[var(--msg-assistant-text)] focus:bg-[var(--cmd-palette-item-hover)] data-[disabled]:opacity-50 data-[disabled]:pointer-events-none"+ >+ <MessageCircle size={16} className="mr-2 shrink-0 text-[var(--folder-item-icon)]" />+ {t('ccAgent.sidebar.sessionMenu.moveToDialogue')}+ </DropdownMenuItem>+ )}</>);}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsxindex 446098b56c..e5aa0c3858 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTaskMenu.tsx@@ -1,12 +1,22 @@import { useEffect, useRef, useState, type ReactNode } from 'react';import { ChevronRight } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { parseSharedTaskPeer, SHARED_TASK_HOST_CHANNEL, type SharedTaskHostState } from '@cindy/device-link';+import {+ parseSharedTaskPeer,+ SHARED_TASK_HOST_CHANNEL,+ type SharedTaskHostState,+} from '@cindy/device-link';import type { Session } from '@/lib/ccAgent.types';import { SharedTaskButton } from '@/features/device-link/SharedTaskButton';-import { SharedTaskExitDialog, type SharedTaskExitTarget } from '@/features/device-link/SharedTaskExitDialog';+import {+ SharedTaskExitDialog,+ type SharedTaskExitTarget,+} from '@/features/device-link/SharedTaskExitDialog';import { useAuth } from '@/contexts/AuthContext';-import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';import { toast } from '@/lib/toast';import { sharedTaskErrorKey } from '@/features/device-link/sharedTaskCompatibility';import {@@ -18,7 +28,20 @@ import {DropdownMenuSubContent,} from '@/components/ui/dropdown-menu';import { isEmptyDraftSession } from '../lib/sessionDisplayTitle';-import { MENU_CONTENT_CLASS, MENU_ITEM_CLASS, MENU_ROW_CLASS, MENU_SEPARATOR_CLASS, MENU_SUB_CONTENT_CLASS } from './menuStyles';+import { AddRemoteProjectDialog } from '@/components/new-chat/AddRemoteProjectDialog';+import {+ TaskMoveSubmenu,+ moveRemoteTaskProject,+ type TaskMoveDestination,+} from './TaskMoveSubmenu';+import { TaskMigrationDialog } from './TaskMigrationDialog';+import {+ MENU_CONTENT_CLASS,+ MENU_ITEM_CLASS,+ MENU_ROW_CLASS,+ MENU_SEPARATOR_CLASS,+ MENU_SUB_CONTENT_CLASS,+} from './menuStyles';interface Props {session: Session;@@ -38,7 +61,11 @@ interface Props {exportShare: ReactNode;}-type SharingDialog = { kind: 'manage' } | SharedTaskExitTarget;+type SharingDialog =+ | { kind: 'manage' }+ | { kind: 'migration'; destination?: TaskMoveDestination }+ | { kind: 'browse-project' }+ | SharedTaskExitTarget;/** One menu order for the header, text rows and cards. Keep row-specific action handlers. */export function SessionTaskMenu(props: Props) {@@ -80,8 +107,11 @@ function ActiveSessionTaskMenu({const copyPending = useRef(false);const copyEpoch = useRef(0);useEffect(() => {- copyPending.current = false; setCopying(false);- return () => { copyEpoch.current++; };+ copyPending.current = false;+ setCopying(false);+ return () => {+ copyEpoch.current++;+ };}, [dataOwnerId, ownerGeneration]);useEffect(() => {if (!open || guest || session.status !== 'active') return;@@ -91,40 +121,80 @@ function ActiveSessionTaskMenu({const command = { action: 'state' as const, sessionId: session.id };const load = async () => {try {- const result = await (session.deviceLinkDeviceId- ? window.electronAPI.deviceLink.invoke(session.deviceLinkDeviceId, SHARED_TASK_HOST_CHANNEL, [command])- : window.electronAPI.sharedTask.host(command)) as SharedTaskHostState;+ const result = (await (session.deviceLinkDeviceId+ ? window.electronAPI.deviceLink.invoke(+ session.deviceLinkDeviceId,+ SHARED_TASK_HOST_CHANNEL,+ [command],+ )+ : window.electronAPI.sharedTask.host(command))) as SharedTaskHostState;if (!disposed && isDataOwnerGenerationCurrent(owner)) setSharing(result);- } catch { /* Management retains its existing retry and upgrade UI. */ }+ } catch {+ /* Management retains its existing retry and upgrade UI. */+ }};void load();- return () => { disposed = true; };- }, [open, guest, session.id, session.status, session.deviceLinkDeviceId, dataOwnerId, ownerGeneration]);+ return () => {+ disposed = true;+ };+ }, [+ open,+ guest,+ session.id,+ session.status,+ session.deviceLinkDeviceId,+ dataOwnerId,+ ownerGeneration,+ ]);const hosted = sharing?.detail?.status === 'active' ? sharing.detail : null;const copyInvitation = async () => {if (!hosted || copyPending.current) return;- copyPending.current = true; setCopying(true);+ copyPending.current = true;+ setCopying(true);const owner = getDataOwnerGeneration();const captured = copyEpoch.current;const current = () => captured === copyEpoch.current && isDataOwnerGenerationCurrent(owner);try {const command = { action: 'invite' as const, sharedTaskId: hosted.sharedTaskId };- const result = await (session.deviceLinkDeviceId- ? window.electronAPI.deviceLink.invoke(session.deviceLinkDeviceId, SHARED_TASK_HOST_CHANNEL, [command])- : window.electronAPI.sharedTask.host(command)) as { invitation: string };+ const result = (await (session.deviceLinkDeviceId+ ? window.electronAPI.deviceLink.invoke(+ session.deviceLinkDeviceId,+ SHARED_TASK_HOST_CHANNEL,+ [command],+ )+ : window.electronAPI.sharedTask.host(command))) as { invitation: string };if (!current()) return;- try { await navigator.clipboard.writeText(result.invitation); }- catch { if (current()) toast.error(t('sharedTask.invitationCopyFailed')); return; }+ try {+ await navigator.clipboard.writeText(result.invitation);+ } catch {+ if (current()) toast.error(t('sharedTask.invitationCopyFailed'));+ return;+ }if (current()) toast.success(t('sharedTask.invitationCopied'));} catch (error) {if (current()) toast.error(t(sharedTaskErrorKey(error)));} finally {- if (current()) { copyPending.current = false; setCopying(false); }+ if (current()) {+ copyPending.current = false;+ setCopying(false);+ }}};const openSharing = () => {- if (guest && peer) setDialog({ kind: 'leave', sharedTaskId: peer.sharedTaskId, title: session.title, peer: session.deviceLinkDeviceId! });- else if (hosted) setDialog({ kind: 'close', sharedTaskId: hosted.sharedTaskId, title: session.title, hostDeviceId: session.deviceLinkDeviceId || undefined });+ if (guest && peer)+ setDialog({+ kind: 'leave',+ sharedTaskId: peer.sharedTaskId,+ title: session.title,+ peer: session.deviceLinkDeviceId!,+ });+ else if (hosted)+ setDialog({+ kind: 'close',+ sharedTaskId: hosted.sharedTaskId,+ title: session.title,+ hostDeviceId: session.deviceLinkDeviceId || undefined,+ });else setDialog({ kind: 'manage' });};const dismissSharing = () => {@@ -157,51 +227,89 @@ function ActiveSessionTaskMenu({if (dialog) event.preventDefault();}}>- {!guest && <>- {!archived &&- !empty &&- item(session.pinnedAt != null ? 'unpin' : 'pin', onPin, ownerActionsBlocked)}- {item('rename', onRename, ownerActionsBlocked)}- {move}- {tags}- {separator}- {copy}- </>}- {session.status === 'active' && (hosted && !guest ? (- <DropdownMenuSub>- <DropdownMenuSubTrigger className={MENU_ROW_CLASS}>- <span className="flex-1">{t('sharedTask.manageSharing')}</span>- <ChevronRight size={14} className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]" aria-hidden />- </DropdownMenuSubTrigger>- <DropdownMenuSubContent sideOffset={4} className={`${MENU_SUB_CONTENT_CLASS} min-w-40`}>- <DropdownMenuItem className={MENU_ITEM_CLASS} disabled={copying || writeBlocked}- onSelect={event => { event.preventDefault(); void copyInvitation(); }}>{t('sharedTask.invite')}</DropdownMenuItem>- <DropdownMenuItem className={MENU_ITEM_CLASS} disabled={copying}- onSelect={() => setDialog({ kind: 'manage' })}>{t('sharedTask.manageMembers')}</DropdownMenuItem>- {separator}- <DropdownMenuItem className={MENU_ITEM_CLASS} disabled={copying}- onSelect={openSharing}>{t('sharedTask.cancelSharing')}</DropdownMenuItem>- </DropdownMenuSubContent>- </DropdownMenuSub>- ) : (- <DropdownMenuItem className={MENU_ITEM_CLASS} onSelect={openSharing}>- {t(guest ? 'sharedTask.leaveShort' : 'sharedTask.title')}- </DropdownMenuItem>- ))}- {!guest && <>- {exportShare}- {!archived && !empty && (- <>- {separator}- {item('openInNewWindow', onOpenInNewWindow, ownerActionsBlocked)}- </>- )}- {separator}- {archived- ? item('unarchive', onUnarchive, ownerActionsBlocked)- : !empty && item('archived', onArchive, ownerActionsBlocked)}- {item('delete', onDelete, ownerActionsBlocked)}- </>}+ {!guest && (+ <>+ {!archived &&+ !empty &&+ item(session.pinnedAt != null ? 'unpin' : 'pin', onPin, ownerActionsBlocked)}+ {item('rename', onRename, ownerActionsBlocked)}+ {tags}+ {separator}+ {copy}+ </>+ )}+ {session.status === 'active' &&+ (hosted && !guest ? (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className={MENU_ROW_CLASS}>+ <span className="flex-1">{t('sharedTask.manageSharing')}</span>+ <ChevronRight+ size={14}+ className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]"+ aria-hidden+ />+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={4}+ className={`${MENU_SUB_CONTENT_CLASS} min-w-40`}+ >+ <DropdownMenuItem+ className={MENU_ITEM_CLASS}+ disabled={copying || writeBlocked}+ onSelect={(event) => {+ event.preventDefault();+ void copyInvitation();+ }}+ >+ {t('sharedTask.invite')}+ </DropdownMenuItem>+ <DropdownMenuItem+ className={MENU_ITEM_CLASS}+ disabled={copying}+ onSelect={() => setDialog({ kind: 'manage' })}+ >+ {t('sharedTask.manageMembers')}+ </DropdownMenuItem>+ {separator}+ <DropdownMenuItem+ className={MENU_ITEM_CLASS}+ disabled={copying}+ onSelect={openSharing}+ >+ {t('sharedTask.cancelSharing')}+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ ) : (+ <DropdownMenuItem className={MENU_ITEM_CLASS} onSelect={openSharing}>+ {t(guest ? 'sharedTask.leaveShort' : 'sharedTask.title')}+ </DropdownMenuItem>+ ))}+ {!guest && (+ <>+ {!archived && !empty && !session.remoteHostId && (+ <TaskMoveSubmenu+ session={session}+ disabled={ownerActionsBlocked}+ localProjects={move}+ onMigration={(destination) => setDialog({ kind: 'migration', destination })}+ onBrowseRemote={() => setDialog({ kind: 'browse-project' })}+ />+ )}+ {exportShare}+ {!archived && !empty && (+ <>+ {separator}+ {item('openInNewWindow', onOpenInNewWindow, ownerActionsBlocked)}+ </>+ )}+ {separator}+ {archived+ ? item('unarchive', onUnarchive, ownerActionsBlocked)+ : !empty && item('archived', onArchive, ownerActionsBlocked)}+ {item('delete', onDelete, ownerActionsBlocked)}+ </>+ )}</DropdownMenuContent>{dialog?.kind === 'manage' && (<SharedTaskButton@@ -212,8 +320,41 @@ function ActiveSessionTaskMenu({}}/>)}- {dialog && dialog.kind !== 'manage' && <SharedTaskExitDialog target={dialog}- onDismiss={dismissSharing} onComplete={dismissSharing} />}+ {dialog?.kind === 'migration' && (+ <TaskMigrationDialog+ session={session}+ destination={dialog.destination}+ onDismiss={dismissSharing}+ />+ )}+ {dialog?.kind === 'browse-project' && session.deviceLinkDeviceId && (+ <AddRemoteProjectDialog+ open+ onOpenChange={(open) => {+ if (!open) dismissSharing();+ }}+ initialDeviceId={session.deviceLinkDeviceId}+ fixedDeviceId={session.deviceLinkDeviceId}+ title={t('ccAgent.sidebar.sessionMenu.moveToProject')}+ confirmText={t('ccAgent.sidebar.sessionMenu.moveToProject')}+ errorText={t('taskMove.failed')}+ onProjectAdded={async (target) => {+ if (target.kind !== 'device-link' || target.deviceId !== session.deviceLinkDeviceId)+ throw new Error('MIGRATION_ACCESS_REVOKED');+ await moveRemoteTaskProject(session, target.path);+ }}+ />+ )}+ {dialog &&+ dialog.kind !== 'browse-project' &&+ dialog.kind !== 'manage' &&+ dialog.kind !== 'migration' && (+ <SharedTaskExitDialog+ target={dialog}+ onDismiss={dismissSharing}+ onComplete={dismissSharing}+ />+ )}</div>);}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsxnew file mode 100644index 0000000000..96d61e3fd3--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx@@ -0,0 +1,321 @@+import { useEffect, useRef, useState } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';+import type { TaskMigrationRequest, TaskMigrationView } from '@cindy/device-link';+import type { Session } from '@/lib/ccAgent.types';+import type { TaskMoveDestination } from './TaskMoveSubmenu';+import { Button } from '@/components/ui/button';+import { Select } from '@/components/ui/select';+import { FormField } from '@/components/ui/form-field';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';++export function TaskMigrationDialog({+ session,+ onDismiss,+ destination,+}: {+ session: Session;+ onDismiss(): void;+ destination?: TaskMoveDestination;+}) {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const [devices, setDevices] = useState<DeviceLinkDeviceView[]>([]);+ const [target, setTarget] = useState(destination?.deviceId ?? '');+ const [projects, setProjects] = useState<string[]>([]);+ const [project, setProject] = useState(destination?.project ?? '');+ const [status, setStatus] = useState<TaskMigrationView | null>(null);+ const [busy, setBusy] = useState(false);+ const [readyTarget, setReadyTarget] = useState('');+ const [error, setError] = useState('');+ const [self, setSelf] = useState('');+ const pending = useRef(false);+ const mutationEpoch = useRef(0);+ const owner = useRef(getDataOwnerGeneration()).current;+ const live = useRef(true);+ const current = () => live.current && isDataOwnerGenerationCurrent(owner);+ const request = (command: TaskMigrationRequest) =>+ window.electronAPI.deviceLink.taskMigration(session.deviceLinkDeviceId ?? null, command);+ const showError = (e: unknown) => {+ if (current())+ setError(+ /\bMIGRATION_[A-Z_]+\b/.exec(e instanceof Error ? e.message : String(e))?.[0] ??+ 'MIGRATION_FAILED',+ );+ };+ useEffect(() => {+ live.current = true;+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const poll = async () => {+ const epoch = mutationEpoch.current;+ try {+ const next = await request({ action: 'status', sessionId: session.id });+ if (!disposed && current() && epoch === mutationEpoch.current && !pending.current)+ setStatus(next);+ } catch (e) {+ if (!disposed) showError(e);+ }+ if (!disposed && current()) timer = setTimeout(() => void poll(), 2000);+ };+ void Promise.all([+ window.electronAPI.deviceLink.listDevices(),+ window.electronAPI.deviceLink.taskMigration(null, { action: 'caps' }),+ request({ action: 'caps' }),+ ])+ .then(([list, local, source]) => {+ if (disposed || !current()) return;+ setSelf(local.deviceId);+ setDevices(+ list.devices.filter(+ (d) =>+ d.deviceId !== source.deviceId &&+ d.online &&+ d.remoteControlEnabled &&+ d.controlEnabled &&+ !['ios', 'android'].includes(d.platform ?? ''),+ ),+ );+ })+ .catch((e) => {+ if (!disposed) showError(e);+ });+ void poll();+ return () => {+ disposed = true;+ live.current = false;+ clearTimeout(timer);+ };+ }, [session.id, session.deviceLinkDeviceId]);+ useEffect(() => {+ let disposed = false;+ setReadyTarget('');+ setProjects([]);+ setProject(destination?.project ?? '');+ if (target)+ void window.electronAPI.deviceLink+ .taskMigration(destination?.isSelf || target === self ? null : target, { action: 'caps' })+ .then((caps) => {+ if (!disposed && current()) {+ setProjects(caps.projects ?? []);+ setReadyTarget(target);+ setError('');+ }+ })+ .catch((e) => {+ if (!disposed) showError(e);+ });+ return () => {+ disposed = true;+ };+ }, [target, self]);+ const act = async (command: TaskMigrationRequest) => {+ if (pending.current || !current()) return;+ pending.current = true;+ mutationEpoch.current++;+ setBusy(true);+ setError('');+ try {+ const next = await request(command);+ if (current()) setStatus(next);+ } catch (e) {+ showError(e);+ } finally {+ pending.current = false;+ if (current()) setBusy(false);+ }+ };+ const started = !!status?.stage && !['cancelled', 'active', 'complete'].includes(status.stage);+ const openTarget = async () => {+ if (!status?.targetSessionId || !status.targetDeviceId || pending.current || !current()) return;+ pending.current = true;+ setBusy(true);+ setError('');+ try {+ const device = status.targetDeviceId,+ id = status.targetSessionId;+ if (device !== self) {+ await window.electronAPI.deviceLink.openLink(device);+ if (!current()) return;+ const valid = remoteProjectsStore.captureSessionRead(device, id);+ const row = (await window.electronAPI.deviceLink.invoke(device, 'local-db:sessions:get', [+ id,+ ])) as Session;+ if (!current()) return;+ if (!valid() || row?.id !== id) throw new Error('MIGRATION_TARGET_NOT_READY');+ remoteProjectsStore.mergeDeviceSessions(+ device,+ devices.find((d) => d.deviceId === device)?.name ?? device,+ [valid.mergeActivity(row)],+ );+ }+ navigate('/cc-agent/' + encodeURIComponent(id));+ onDismiss();+ } catch (e) {+ showError(e);+ } finally {+ pending.current = false;+ if (current()) setBusy(false);+ }+ };+ const failure = error || status?.error;+ const errorKey =+ failure && t(`taskMigration.errors.${failure}`, { defaultValue: t('taskMigration.failed') });+ return (+ <Dialog.Root+ open+ onOpenChange={(open) => {+ if (!open) onDismiss();+ }}+ >+ <Dialog.Portal>+ <Dialog.Overlay+ className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]"+ onClick={(e) => e.stopPropagation()}+ />+ <Dialog.Content+ className="fixed left-1/2 top-1/2 z-[10000] w-[calc(100%-32px)] max-w-[480px] -translate-x-1/2 -translate-y-1/2 rounded-xl bg-[var(--confirm-bg)] p-4 shadow-[var(--confirm-shadow)] [-webkit-app-region:no-drag]"+ onClick={(e) => e.stopPropagation()}+ onPointerDown={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ >+ <Dialog.Title className="text-lg font-medium text-[var(--confirm-title)]">+ {t('taskMigration.title')}+ </Dialog.Title>+ <Dialog.Description className="mt-2 text-sm text-[var(--confirm-desc)]">+ {t('taskMigration.description')}+ </Dialog.Description>+ <p className="mt-2 text-sm text-[var(--confirm-desc)]">+ {t('taskMigration.bindingsNotice')}+ </p>+ {!started && destination && (+ <div className="mt-4 space-y-2 text-sm text-[var(--confirm-title)]">+ <p>+ {t('taskMigration.device')}: {destination.deviceName}+ {(destination.isSelf || destination.deviceId === self) && (+ <span className="ml-2 text-[var(--confirm-desc)]">+ {t('settings.devices.thisDevice')}+ </span>+ )}+ </p>+ <p className="break-all">+ {t('taskMigration.project')}:{' '}+ {destination.project ?? t('taskMigration.defaultFolder')}+ </p>+ <p className="text-[var(--confirm-desc)]">{t('taskMigration.newFolder')}</p>+ </div>+ )}+ {!started && !destination && (+ <div className="mt-4 flex flex-col gap-3">+ <p className="text-sm text-[var(--confirm-desc)]">{t('taskMigration.limits')}</p>+ <FormField label={t('taskMigration.device')}>+ {(control) => (+ <Select+ {...control}+ label={t('taskMigration.device')}+ value={target}+ disabled={busy}+ options={devices.map((d) => ({+ value: d.deviceId,+ label:+ d.isSelf || d.deviceId === self+ ? `${d.name} · ${t('settings.devices.thisDevice')}`+ : d.name,+ }))}+ onValueChange={setTarget}+ />+ )}+ </FormField>+ {!devices.length && (+ <p className="text-sm text-[var(--confirm-desc)]">{t('taskMigration.noDevices')}</p>+ )}+ <FormField label={t('taskMigration.project')} hint={t('taskMigration.newFolder')}>+ {(control) => (+ <Select+ {...control}+ label={t('taskMigration.project')}+ value={project || '__default__'}+ disabled={busy || !target || readyTarget !== target}+ options={[+ { value: '__default__', label: t('taskMigration.defaultFolder') },+ ...projects.map((p) => ({ value: p, label: p })),+ ]}+ onValueChange={(value) => setProject(value === '__default__' ? '' : value)}+ />+ )}+ </FormField>+ </div>+ )}+ {started && (+ <p className="mt-4 text-sm text-[var(--confirm-title)]" role="status">+ {t(`taskMigration.stages.${status?.stage}`)}+ </p>+ )}+ {failure && (+ <p className="mt-3 text-sm text-[var(--error-fg)]" role="alert">+ {errorKey}+ </p>+ )}+ {started && (+ <p className="mt-3 text-sm text-[var(--confirm-desc)]">+ {t('taskMigration.background')}+ </p>+ )}+ {status?.stage === 'complete' && status.targetSessionId && (+ <div className="mt-3">+ <Button disabled={busy} onClick={() => void openTarget()}>+ {t('taskMigration.openTarget')}+ </Button>+ </div>+ )}+ <div className="mt-4 flex flex-wrap justify-end gap-2">+ <Button variant="secondary" onClick={onDismiss}>+ {t('taskMigration.close')}+ </Button>+ {started &&+ !status?.running &&+ ['preparing', 'transferring'].includes(status?.stage ?? '') && (+ <>+ {status?.stage === 'preparing' && (+ <Button+ variant="secondary"+ disabled={busy}+ onClick={() => void act({ action: 'cancel', sessionId: session.id })}+ >+ {t('taskMigration.cancel')}+ </Button>+ )}+ <Button+ disabled={busy}+ onClick={() => void act({ action: 'retry', sessionId: session.id })}+ >+ {t('taskMigration.retry')}+ </Button>+ </>+ )}+ {!started && (+ <Button+ disabled={!status || busy || readyTarget !== target || !target}+ onClick={() =>+ void act({+ action: 'start',+ sessionId: session.id,+ targetDeviceId: target,+ targetProject: project || null,+ })+ }+ >+ {t('taskMigration.start')}+ </Button>+ )}+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMoveSubmenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMoveSubmenu.tsxnew file mode 100644index 0000000000..3bc4a6ba0e--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMoveSubmenu.tsx@@ -0,0 +1,332 @@+import { useEffect, useState, type ReactNode } from 'react';+import { ChevronRight, Monitor } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { Session } from '@/lib/ccAgent.types';+import {+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from '@/components/ui/dropdown-menu';+import {+ loadDeviceLinkExistingProjects,+ recentWorkdirsToProjects,+} from '@/components/new-chat/remoteExistingProjects';+import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import { toast } from '@/lib/toast';+import { SessionProjectMoveSubmenu } from './SessionProjectMoveSubmenu';+import {+ MENU_ITEM_CLASS,+ MENU_ROW_CLASS,+ MENU_SEPARATOR_CLASS,+ MENU_SUB_CONTENT_CLASS,+} from './menuStyles';++export interface TaskMoveDestination {+ deviceId: string;+ deviceName: string;+ isSelf?: boolean;+ project: string | null;+}++/** Same source-host business operation for recent projects, dialogue, and the folder picker. */+export async function moveRemoteTaskProject(session: Session, workingDir: string | null) {+ const device = session.deviceLinkDeviceId;+ if (!device) throw new Error('MIGRATION_FAILED');+ const owner = getDataOwnerGeneration();+ const result = await window.electronAPI.deviceLink+ .taskMigration(device, {+ action: 'move-project',+ sessionId: session.id,+ workingDir,+ })+ .catch((error) => {+ if (String(error).includes('MIGRATION_INVALID_REQUEST'))+ throw new Error('MIGRATION_UNSUPPORTED');+ throw error;+ });+ if (!isDataOwnerGenerationCurrent(owner)) return;+ if (result.projectMove?.sessionId !== session.id) throw new Error('MIGRATION_FAILED');+ // Refresh through the existing remote projection, retaining its push-vs-read race guard.+ const valid = remoteProjectsStore.captureSessionRead(device, session.id);+ const row = (await window.electronAPI.deviceLink.invoke(device, 'local-db:sessions:get', [+ session.id,+ ])) as Session;+ if (!isDataOwnerGenerationCurrent(owner) || !valid()) return;+ if (row?.id !== session.id) throw new Error('MIGRATION_FAILED');+ remoteProjectsStore.mergeDeviceSessions(+ device,+ remoteProjectsStore.getDeviceName(device) ?? device,+ [valid.mergeActivity(row)],+ );+}++export function TaskMoveSubmenu({+ session,+ disabled,+ localProjects,+ onMigration,+ onBrowseRemote,+}: {+ session: Session;+ disabled: boolean;+ localProjects: ReactNode;+ onMigration(destination: TaskMoveDestination): void;+ onBrowseRemote(): void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const [devices, setDevices] = useState<DeviceLinkDeviceView[]>([]);+ const [projects, setProjects] = useState<FolderPickerOption[]>([]);+ const [loading, setLoading] = useState(false);+ const [deviceError, setDeviceError] = useState(false);+ const [projectError, setProjectError] = useState(false);+ const [retry, setRetry] = useState(0);+ useEffect(() => {+ if (!open) return;+ let disposed = false;+ const owner = getDataOwnerGeneration();+ const current = () => !disposed && isDataOwnerGenerationCurrent(owner);+ setLoading(true);+ setProjects([]);+ setDevices([]);+ setDeviceError(false);+ setProjectError(false);+ void Promise.allSettled([+ window.electronAPI.deviceLink+ .listDevices()+ .then((list) => {+ if (current())+ setDevices(+ list.devices.filter(+ (d) =>+ (session.deviceLinkDeviceId+ ? d.deviceId !== session.deviceLinkDeviceId+ : !d.isSelf) &&+ d.controlEnabled &&+ !['ios', 'android'].includes(d.platform ?? '') &&+ d.online &&+ d.remoteControlEnabled,+ ),+ );+ })+ .catch(() => {+ if (current()) setDeviceError(true);+ }),+ session.deviceLinkDeviceId+ ? loadDeviceLinkExistingProjects(session.deviceLinkDeviceId)+ .then((rows) => {+ if (current())+ setProjects(+ rows+ .filter((row) => row.exists !== false)+ .map((row) => ({ ...row, description: row.path })),+ );+ })+ .catch(() => {+ if (current()) setProjectError(true);+ })+ : Promise.resolve(),+ ]).then(() => {+ if (current()) setLoading(false);+ });+ return () => {+ disposed = true;+ };+ }, [open, session.deviceLinkDeviceId, retry]);+ const move = (path: string | null) => {+ const owner = getDataOwnerGeneration();+ void moveRemoteTaskProject(session, path)+ .then(() => {+ if (isDataOwnerGenerationCurrent(owner)) toast.success(t('taskMove.moved'));+ })+ .catch((error) => {+ if (!isDataOwnerGenerationCurrent(owner)) return;+ const code = /MIGRATION_[A-Z_]+/.exec(String(error))?.[0];+ toast.error(t(`taskMigration.errors.${code}`, { defaultValue: t('taskMove.failed') }));+ });+ };+ return (+ <DropdownMenuSub open={open} onOpenChange={setOpen}>+ <DropdownMenuSubTrigger disabled={disabled} className={MENU_ROW_CLASS}>+ <span className="flex-1">{t('ccAgent.sidebar.sessionMenu.moveToProject')}</span>+ <ChevronRight size={14} className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]" />+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={4}+ className={`${MENU_SUB_CONTENT_CLASS} w-[320px] overflow-hidden`}+ >+ {session.deviceLinkDeviceId ? (+ <>+ {loading && <div className={MENU_ITEM_CLASS}>{t('taskMove.loading')}</div>}+ {projectError && (+ <DropdownMenuItem+ className={MENU_ITEM_CLASS}+ onSelect={(e) => {+ e.preventDefault();+ setRetry((n) => n + 1);+ }}+ >+ {t('taskMove.retry')}+ </DropdownMenuItem>+ )}+ <SessionProjectMoveSubmenu+ heading={t('taskMove.sourceProjects')}+ projectOptions={projects}+ currentWorkingDir={session.workspaceKind === 'project' ? session.workingDir : null}+ isDialogue={session.workspaceKind === 'dialogue'}+ onSelectProject={move}+ onBrowseProject={onBrowseRemote}+ onMoveToDialogue={() => move(null)}+ />+ </>+ ) : (+ localProjects+ )}+ {['desktop', 'shared', 'feishu'].includes(session.source ?? 'desktop') &&+ session.orcaRole !== 'worker' && (+ <>+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ <div className="px-3 py-1.5 text-xs text-[var(--cmd-palette-item-meta)]">+ {t('taskMove.otherComputers')}+ </div>+ {deviceError ? (+ <DropdownMenuItem+ className={MENU_ITEM_CLASS}+ onSelect={(e) => {+ e.preventDefault();+ setRetry((n) => n + 1);+ }}+ >+ {t('taskMove.retry')}+ </DropdownMenuItem>+ ) : (+ devices.map((device) => (+ <DeviceProjects+ key={device.deviceId}+ device={device}+ team={session.orcaRole === 'lead'}+ onSelect={onMigration}+ />+ ))+ )}+ {!loading && !deviceError && !devices.length && (+ <div className="px-3 py-2 text-sm text-[var(--cmd-palette-item-meta)]">+ {t('taskMigration.noDevices')}+ </div>+ )}+ </>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+}++function DeviceProjects({+ device,+ team,+ onSelect,+}: {+ device: DeviceLinkDeviceView;+ team: boolean;+ onSelect(value: TaskMoveDestination): void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const [projects, setProjects] = useState<FolderPickerOption[] | null>(null);+ const [error, setError] = useState<'upgrade' | 'retry' | null>(null);+ const [retry, setRetry] = useState(0);+ useEffect(() => {+ if (!open) return;+ let disposed = false;+ const owner = getDataOwnerGeneration();+ setProjects(null);+ setError(null);+ void window.electronAPI.deviceLink+ .taskMigration(device.isSelf ? null : device.deviceId, { action: 'caps' })+ .then((caps) => {+ if (team && caps.teamMigration !== true) throw new Error('MIGRATION_UNSUPPORTED');+ if (!disposed && isDataOwnerGenerationCurrent(owner))+ setProjects(+ recentWorkdirsToProjects(+ (caps.projects ?? []).map((path) => ({ path, lastUsedAt: '' })),+ ).map((row) => ({ ...row, description: row.path })),+ );+ })+ .catch((error) => {+ if (!disposed && isDataOwnerGenerationCurrent(owner)) {+ // The host normalizes explicit missing capabilities to MIGRATION_UNSUPPORTED.+ // Connection failures and timeouts do not imply an outdated application.+ setError(/\bMIGRATION_UNSUPPORTED\b/.test(String(error)) ? 'upgrade' : 'retry');+ }+ });+ return () => {+ disposed = true;+ };+ }, [open, device.deviceId, device.isSelf, retry, team]);+ const choose = (project: string | null) =>+ onSelect({+ deviceId: device.deviceId,+ deviceName: device.name,+ isSelf: device.isSelf,+ project,+ });+ return (+ <DropdownMenuSub open={open} onOpenChange={setOpen}>+ <DropdownMenuSubTrigger disabled={!device.online} className={MENU_ROW_CLASS}>+ <Monitor size={14} className="mr-2 shrink-0" />+ <span className="flex-1 truncate">{device.name}</span>+ {device.isSelf && (+ <span className="ml-2 shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">+ {t('settings.devices.thisDevice')}+ </span>+ )}+ {!device.online ? (+ <span className="ml-2 text-xs">{t('taskMove.offline')}</span>+ ) : (+ <ChevronRight size={14} className="ml-2 shrink-0" />+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={4}+ className={`${MENU_SUB_CONTENT_CLASS} w-[320px] overflow-hidden`}+ >+ {error === 'upgrade' ? (+ <div role="status" className="px-3 py-2 text-sm text-[var(--cmd-palette-item-meta)]">+ {t('taskMove.upgradeComputer', { name: device.name })}+ </div>+ ) : error ? (+ <DropdownMenuItem+ className={MENU_ITEM_CLASS}+ onSelect={(e) => {+ e.preventDefault();+ setRetry((n) => n + 1);+ }}+ >+ {t('taskMove.retry')}+ </DropdownMenuItem>+ ) : projects ? (+ <>+ <DropdownMenuItem className={MENU_ITEM_CLASS} onSelect={() => choose(null)}>+ {t('taskMigration.defaultFolder')}+ </DropdownMenuItem>+ <SessionProjectMoveSubmenu+ heading={t('taskMigration.project')}+ projectOptions={projects}+ isDialogue={false}+ onSelectProject={choose}+ />+ </>+ ) : (+ <div className={MENU_ITEM_CLASS}>{t('taskMove.loading')}</div>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsxindex f9b88d5e47..e66293804e 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionTaskMenu.test.tsx@@ -22,7 +22,7 @@ const state = vi.hoisted(() => ({writeClipboard: vi.fn(),}));vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key.split('.').at(-1) }),+ useTranslation: () => ({ t: (key: string) => key.startsWith('taskMigration.') ? key : key.split('.').at(-1) }),}));vi.mock('@/features/device-link/remoteProjectsStore', () => ({remoteProjectsStore: { removeDevice: state.removeDevice, getDeviceName: () => undefined },@@ -100,10 +100,10 @@ it('loads only on open and groups task organization, sharing, viewing and removaexpect(labels()).toEqual(['pin','rename',- 'move','tags','copy','title',+ 'moveToProject','export','openInNewWindow','archived',@@ -126,10 +126,10 @@ it('shows unpin without a branch entry even for a forked Pi task', () => {expect(labels()).toEqual(['unpin','rename',- 'move','tags','copy','title',+ 'moveToProject','export','openInNewWindow','archived',@@ -201,7 +201,7 @@ it('shows stop sharing for an active host and closes only after confirmation', astate.host.mockResolvedValue({ available: true, detail: { sharedTaskId: 'share', status: 'active' } });render(<Harness />); openMenu();await screen.findByRole('menuitem', { name: 'manageSharing' });- expect(labels()).toEqual(['pin', 'rename', 'move', 'tags', 'copy', 'manageSharing', 'export', 'openInNewWindow', 'archived', 'delete']);+ expect(labels()).toEqual(['pin', 'rename', 'tags', 'copy', 'manageSharing', 'moveToProject', 'export', 'openInNewWindow', 'archived', 'delete']);expect(screen.queryByRole('menuitem', { name: 'cancelSharing' })).toBeNull();await openSharingSubmenu();fireEvent.click(screen.getByRole('menuitem', { name: 'cancelSharing' }));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.tsxnew file mode 100644index 0000000000..6a86a2b57a--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx@@ -0,0 +1,170 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { MemoryRouter } from 'react-router-dom';+import type { Session } from '@/lib/ccAgent.types';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { TaskMigrationDialog } from '../TaskMigrationDialog';+const state = vi.hoisted(() => ({+ request: vi.fn(),+ invoke: vi.fn(),+ openLink: vi.fn(),+ merge: vi.fn(),+ dismiss: vi.fn(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/features/device-link/remoteProjectsStore', () => ({+ remoteProjectsStore: {+ captureSessionRead: () => Object.assign(() => true, { mergeActivity: (row: unknown) => row }),+ mergeDeviceSessions: state.merge,+ },+}));+vi.mock('@/components/ui/select', () => ({+ Select: (props: {+ label: string;+ value: string;+ disabled: boolean;+ options: Array<{ value: string; label: string }>;+ onValueChange(value: string): void;+ }) => (+ <select+ aria-label={props.label}+ value={props.value}+ disabled={props.disabled}+ onChange={(e) => props.onValueChange(e.target.value)}+ >+ <option value="" />+ {props.options.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ ),+}));+const source = { id: 'task', title: 'Task', status: 'active', deviceLinkDeviceId: 'A' } as Session;+beforeEach(() => {+ vi.clearAllMocks();+ setDataOwnerGeneration('owner');+ state.request.mockImplementation(async (device: string | null, command: { action: string }) => ({+ supported: true,+ deviceId: device ?? 'local',+ ...(command.action === 'caps' ? { projects: ['B-project'] } : {}),+ }));+ state.openLink.mockResolvedValue(undefined);+ Object.assign(window, {+ electronAPI: {+ deviceLink: {+ taskMigration: state.request,+ invoke: state.invoke,+ openLink: state.openLink,+ listDevices: async () => ({+ devices: ['local', 'A', 'B', 'offline', 'phone'].map((deviceId) => ({+ deviceId,+ name: deviceId,+ online: deviceId !== 'offline',+ remoteControlEnabled: true,+ controlEnabled: true,+ platform: deviceId === 'phone' ? 'ios' : 'darwin',+ })),+ }),+ },+ },+ });+});+afterEach(cleanup);+const mount = () =>+ render(+ <MemoryRouter>+ <TaskMigrationDialog session={source} onDismiss={state.dismiss} />+ </MemoryRouter>,+ );+it('uses the source host for commands and the target host for destination projects, with no duplicate start', async () => {+ mount();+ await screen.findByRole('option', { name: 'B' });+ expect(screen.queryByRole('option', { name: 'A' })).toBeNull();+ expect(screen.queryByRole('option', { name: 'offline' })).toBeNull();+ expect(screen.queryByRole('option', { name: 'phone' })).toBeNull();+ expect(screen.getByRole('option', { name: 'local · settings.devices.thisDevice' })).toBeTruthy();+ fireEvent.change(screen.getByRole('combobox', { name: 'taskMigration.device' }), {+ target: { value: 'B' },+ });+ await screen.findByRole('option', { name: 'B-project' });+ await waitFor(() =>+ expect(+ (screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled,+ ).toBe(false),+ );+ state.request.mockImplementation(async (device: string | null, command: { action: string }) => {+ if (command.action === 'start') return new Promise(() => {});+ return { supported: true, deviceId: device ?? 'local' };+ });+ const start = screen.getByRole('button', { name: 'taskMigration.start' });+ fireEvent.click(start);+ fireEvent.click(start);+ expect(state.request.mock.calls.filter(([, command]) => command.action === 'start')).toEqual([+ ['A', { action: 'start', sessionId: 'task', targetDeviceId: 'B', targetProject: null }],+ ]);+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.close' }));+ expect(state.dismiss).toHaveBeenCalledOnce();+ expect(state.request.mock.calls.some(([, command]) => command.action === 'cancel')).toBe(false);+});+it('offers retry, without cancellation, when a copy transfer was interrupted', async () => {+ state.request.mockImplementation(async (device: string | null, command: { action: string }) => ({+ supported: true,+ deviceId: device ?? 'local',+ ...(command.action === 'status'+ ? {+ stage: 'transferring',+ running: false,+ error: 'MIGRATION_FAILED',+ targetDeviceId: 'B',+ targetSessionId: 'migrated',+ }+ : {}),+ }));+ mount();+ const retry = await screen.findByRole('button', { name: 'taskMigration.retry' });+ expect(screen.queryByRole('button', { name: 'taskMigration.cancel' })).toBeNull();+ fireEvent.click(retry);+ await waitFor(() =>+ expect(state.request).toHaveBeenCalledWith('A', { action: 'retry', sessionId: 'task' }),+ );+});+it('loads the completed task from the target computer before navigation and dismisses the dialog', async () => {+ state.request.mockImplementation(async (device: string | null, command: { action: string }) => ({+ supported: true,+ deviceId: device ?? 'local',+ ...(command.action === 'status'+ ? {+ stage: 'complete',+ running: false,+ targetDeviceId: 'B',+ targetSessionId: 'migrated',+ }+ : {}),+ }));+ state.invoke.mockResolvedValue({ id: 'migrated', status: 'active' });+ mount();+ await screen.findByRole('button', { name: 'taskMigration.openTarget' });+ expect(screen.getByRole('button', { name: 'taskMigration.start' })).toBeTruthy();+ expect(screen.getByText('taskMigration.bindingsNotice')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.openTarget' }));+ await waitFor(() => expect(state.dismiss).toHaveBeenCalledOnce());+ expect(state.openLink).toHaveBeenCalledWith('B');+ expect(state.invoke).toHaveBeenCalledWith('B', 'local-db:sessions:get', ['migrated']);+ expect(state.merge).toHaveBeenCalledWith('B', 'B', [{ id: 'migrated', status: 'active' }]);+});++it('confirms the project selected in the menu without asking for a second selection', async () => {+ render(<MemoryRouter><TaskMigrationDialog session={source} onDismiss={state.dismiss}+ destination={{ deviceId: 'B', deviceName: 'Work Mac', project: 'B-project' }} /></MemoryRouter>);+ await waitFor(() => expect((screen.getByRole('button', { name: 'taskMigration.start' }) as HTMLButtonElement).disabled).toBe(false));+ expect(screen.queryByRole('combobox')).toBeNull();+ expect(screen.getByText(/Work Mac/)).toBeTruthy();+ expect(screen.getByText(/B-project/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'taskMigration.start' }));+ await waitFor(() => expect(state.request).toHaveBeenCalledWith('A', {+ action: 'start', sessionId: 'task', targetDeviceId: 'B', targetProject: 'B-project',+ }));+});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMoveSubmenu.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMoveSubmenu.test.tsxnew file mode 100644index 0000000000..917ddba718--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMoveSubmenu.test.tsx@@ -0,0 +1,208 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { Session } from '@/lib/ccAgent.types';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { TaskMoveSubmenu, moveRemoteTaskProject } from '../TaskMoveSubmenu';+const h = vi.hoisted(() => ({+ request: vi.fn(),+ invoke: vi.fn(),+ merge: vi.fn(),+ destination: vi.fn(),+ browse: vi.fn(),+ list: vi.fn(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+vi.mock('@/features/device-link/remoteProjectsStore', () => ({+ remoteProjectsStore: {+ captureSessionRead: () => Object.assign(() => true, { mergeActivity: (row: unknown) => row }),+ getDeviceName: () => 'Source Mac',+ mergeDeviceSessions: h.merge,+ },+}));+const session = {+ id: 'task',+ title: 'Task',+ status: 'active',+ workspaceKind: 'project',+ workingDir: '/source/current',+ deviceLinkDeviceId: 'A',+} as Session;+beforeEach(() => {+ vi.clearAllMocks();+ setDataOwnerGeneration('owner');+ h.list.mockResolvedValue({+ devices: ['A', 'B', 'offline', 'local'].map((deviceId) => ({+ deviceId,+ name: deviceId,+ online: deviceId !== 'offline',+ isSelf: deviceId === 'local',+ controlEnabled: true,+ remoteControlEnabled: true,+ platform: 'darwin',+ })),+ });+ h.request.mockImplementation(async (device, command) => ({+ supported: true,+ deviceId: device ?? 'local',+ ...(command.action === 'caps'+ ? { projects: ['/destination/project'] }+ : {+ projectMove: {+ sessionId: 'task',+ workingDir: command.workingDir,+ workspaceKind: 'project',+ },+ }),+ }));+ h.invoke.mockImplementation(async (_device, channel) =>+ channel === 'local-db:recent-workdirs:list'+ ? [+ { path: '/source/current', lastUsedAt: '' },+ { path: '/source/another', lastUsedAt: '' },+ ]+ : { ...session, workingDir: '/source/another' },+ );+ Object.assign(window, {+ electronAPI: {+ deviceLink: { taskMigration: h.request, invoke: h.invoke, listDevices: h.list },+ },+ });+});+afterEach(cleanup);+async function mount(task = session) {+ render(+ <DropdownMenu defaultOpen>+ <DropdownMenuTrigger>More</DropdownMenuTrigger>+ <DropdownMenuContent>+ <TaskMoveSubmenu+ session={task}+ disabled={false}+ localProjects={null}+ onMigration={h.destination}+ onBrowseRemote={h.browse}+ />+ </DropdownMenuContent>+ </DropdownMenu>,+ );+ fireEvent.keyDown(+ screen.getByRole('menuitem', { name: 'ccAgent.sidebar.sessionMenu.moveToProject' }),+ { key: 'ArrowRight' },+ );+ await screen.findByRole('menuitem', { name: /another/ });+}+it('moves a remote task to a project on its source computer using the host business action', async () => {+ await mount();+ expect(+ screen+ .getByRole('menuitem', { name: /current\/source\/current/ })+ .getAttribute('aria-disabled'),+ ).toBe('true');+ fireEvent.click(screen.getByRole('menuitem', { name: /another/ }));+ await waitFor(() =>+ expect(h.request).toHaveBeenCalledWith('A', {+ action: 'move-project',+ sessionId: 'task',+ workingDir: '/source/another',+ }),+ );+ await waitFor(() =>+ expect(h.merge).toHaveBeenCalledWith('A', 'Source Mac', [+ expect.objectContaining({ workingDir: '/source/another' }),+ ]),+ );+});+it('opens the source folder picker and hides offline devices', async () => {+ await mount();+ expect(screen.queryByRole('menuitem', { name: 'A' })).toBeNull();+ expect(screen.queryByRole('menuitem', { name: /offline/ })).toBeNull();+ fireEvent.click(+ screen.getByRole('menuitem', { name: 'ccAgent.sidebar.sessionMenu.browseProjectFolder' }),+ );+ expect(h.browse).toHaveBeenCalledOnce();+ expect(h.request).not.toHaveBeenCalled();+});+it('selects a computer project directly and supports moving back to the controller', async () => {+ await mount();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'localsettings.devices.thisDevice' }), {+ key: 'ArrowRight',+ });+ fireEvent.click(await screen.findByRole('menuitem', { name: /project\/destination\/project/ }));+ expect(h.request).toHaveBeenCalledWith(null, { action: 'caps' });+ expect(h.destination).toHaveBeenCalledWith({+ deviceId: 'local',+ deviceName: 'local',+ isSelf: true,+ project: '/destination/project',+ });+ expect(h.request.mock.calls.some(([, command]) => command.action === 'start')).toBe(false);+});+it('does not merge a move response into a different account', async () => {+ h.request.mockImplementationOnce(async () => {+ setDataOwnerGeneration('different-owner');+ return { projectMove: { sessionId: 'task' } };+ });+ await moveRemoteTaskProject(session, null);+ expect(h.invoke).not.toHaveBeenCalled();+ expect(h.merge).not.toHaveBeenCalled();+});++it.each(['bot'] as const)(+ 'hides cross-computer migration for a %s task',+ async (source) => {+ await mount({ ...session, source });+ expect(screen.queryByText('taskMove.otherComputers')).toBeNull();+ expect(screen.queryByRole('menuitem', { name: 'B' })).toBeNull();+ expect(h.destination).not.toHaveBeenCalled();+ },+);++it.each(['desktop', 'shared', 'feishu'] as const)(+ 'keeps cross-computer migration for a %s task',+ async (source) => {+ await mount({ ...session, source });+ expect(screen.getByRole('menuitem', { name: 'B' })).toBeTruthy();+ },+);++it('explains missing migration support without offering a misleading load retry', async () => {+ h.request.mockRejectedValueOnce(new Error('[PRECONDITION_FAILED] MIGRATION_UNSUPPORTED'));+ await mount();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'B' }), { key: 'ArrowRight' });+ expect(await screen.findByText('taskMove.upgradeComputer')).toBeTruthy();+ expect(screen.queryByRole('menuitem', { name: 'taskMove.retry' })).toBeNull();+ expect(screen.queryByRole('menuitem', { name: 'taskMigration.defaultFolder' })).toBeNull();+});+it('keeps transient connection failures retryable without claiming an old version', async () => {+ h.request.mockRejectedValueOnce(new Error('MIGRATION_FAILED'));+ await mount();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'B' }), { key: 'ArrowRight' });+ fireEvent.click(await screen.findByRole('menuitem', { name: 'taskMove.retry' }));+ expect(await screen.findByRole('menuitem', { name: 'taskMigration.defaultFolder' })).toBeTruthy();+ expect(screen.queryByText('taskMove.upgradeComputer')).toBeNull();+});++it.each([false, true])(+ 'shows other computers for a lead and requires team migration support: %s',+ async (supported) => {+ h.request.mockResolvedValue({+ supported: true,+ deviceId: 'B',+ projects: [],+ ...(supported ? { teamMigration: true } : {}),+ });+ await mount({ ...session, orcaRole: 'lead' });+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'B' }), { key: 'ArrowRight' });+ if (supported)+ expect(+ await screen.findByRole('menuitem', { name: 'taskMigration.defaultFolder' }),+ ).toBeTruthy();+ else expect(await screen.findByText('taskMove.upgradeComputer')).toBeTruthy();+ },+);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ad1f6eae8b..5104c589fd 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,4 +1,55 @@{+ "taskMove": {+ "upgradeComputer": "This computer’s Cindy version does not support moving tasks. Update Cindy on “{{name}}” to use this feature.",+ "sourceProjects": "Projects on the task’s computer",+ "otherComputers": "Copy to another computer",+ "offline": "Offline",+ "loading": "Loading…",+ "retry": "Could not load. Retry",+ "moved": "Task moved",+ "failed": "Could not move the task. Stop it, check the destination directory and retry."+ },+ "taskMigration": {+ "title": "Copy to another computer…",+ "description": "Create an independent copy on the destination computer. The original task and files stay here.",+ "bindingsNotice": "Automations and messaging connections stay on the source computer and are not copied.",+ "limits": "Both computers need this feature and remote control enabled. Stop tasks using this directory first. Available disk space and memory on the destination are checked before transfer. The destination uses its own model settings; Cindy sign-in credentials and machine settings are not transferred.",+ "device": "Destination computer",+ "project": "Destination location",+ "newFolder": "Creates a new folder without overwriting existing files.",+ "defaultFolder": "Cindy’s default location",+ "noDevices": "No available computers. Connect another computer and enable remote control on both computers.",+ "background": "You can close this window and reopen it from the task menu. If interrupted, retry the same copy.",+ "openTarget": "Open task on destination",+ "close": "Close",+ "cancel": "Cancel copy",+ "retry": "Retry copy",+ "start": "Copy task",+ "failed": "Could not complete the copy. Source files are kept. Check both computers and retry.",+ "stages": {+ "preparing": "Preparing a snapshot…",+ "transferring": "Transferring and checking files…",+ "complete": "Copy complete. The original task and files are kept.",+ "cancelled": "Copy cancelled.",+ "receiving": "Receiving files…",+ "active": "Task is ready on this computer."+ },+ "errors": {+ "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_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.",+ "MIGRATION_SUBMODULE_UNSUPPORTED": "Projects with Git submodules cannot be copied yet.",+ "MIGRATION_NO_SPACE": "Not enough space on the destination computer.",+ "MIGRATION_TARGET_MODEL_UNAVAILABLE": "The destination has no available model for this task’s engine. Connect a provider there first.",+ "MIGRATION_UNSUPPORTED": "Update both computers to a version that supports task copy.",+ "MIGRATION_TASK_QUEUED": "This task has queued messages. Finish or remove them before copying it.",+ "MIGRATION_SOURCE_CHANGED": "The source task changed during preparation. Retry the copy."+ }+ },"sharedTask": {"manageSharing": "Manage Sharing","manageMembers": "Manage Members…",@@ -10328,8 +10379,8 @@"pin": "Pin","unpin": "Unpin","archived": "Archived",- "moveToProject": "Move to project",- "moveToProjectHeading": "Select project",+ "moveToProject": "Move task",+ "moveToProjectHeading": "Projects on this computer","browseProjectFolder": "Choose project folder","moveToDialogue": "Move to Chat","noProjects": "No recent projects",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 00dd23a0e2..0c8eaba4b3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,4 +1,55 @@{+ "taskMove": {+ "upgradeComputer": "このコンピューターの Cindy はタスクの移動に対応していません。「{{name}}」の Cindy を更新してください。",+ "sourceProjects": "タスクのコンピューターのプロジェクト",+ "otherComputers": "別のコンピューターにコピー",+ "offline": "オフライン",+ "loading": "読み込み中…",+ "retry": "読み込めませんでした。再試行",+ "moved": "タスクを移動しました",+ "failed": "タスクを移動できませんでした。タスクを停止し、移動先フォルダーを確認して再試行してください。"+ },+ "taskMigration": {+ "title": "別のコンピューターにコピー…",+ "description": "コピー先に独立したタスクを作成します。元のタスクとファイルは保持されます。",+ "bindingsNotice": "自動実行とメッセージ連携は元のコンピューターに残り、コピーされません。",+ "limits": "両方のコンピューターでこの機能とリモート操作を有効にする必要があります。このフォルダーを使用するタスクを先に停止してください。コピー前にコピー先のディスク空き容量と利用可能なメモリを確認します。コピー先のモデル設定を使用し、Cindy のログイン情報やマシン設定は転送しません。",+ "device": "コピー先のコンピューター",+ "project": "保存先",+ "newFolder": "新しいフォルダーを作成し、既存ファイルは上書きしません。",+ "defaultFolder": "Cindy の既定の場所",+ "noDevices": "利用可能なコンピューターがありません。別のコンピューターに接続し、両方でリモート操作を有効にしてください。",+ "background": "このウィンドウを閉じても、タスクメニューから再度開けます。中断された場合は同じコピーを再試行してください。",+ "openTarget": "コピー先のタスクを開く",+ "close": "閉じる",+ "cancel": "コピーをキャンセル",+ "retry": "コピーを再試行",+ "start": "タスクをコピー",+ "failed": "コピーを完了できませんでした。元のファイルは保持されています。両方のコンピューターを確認して再試行してください。",+ "stages": {+ "preparing": "スナップショットを準備中…",+ "transferring": "ファイルを転送・検証中…",+ "complete": "コピーが完了しました。元のタスクとファイルは保持されています。",+ "cancelled": "コピーをキャンセルしました。",+ "receiving": "ファイルを受信中…",+ "active": "このコンピューターでタスクを続けられます。"+ },+ "errors": {+ "MIGRATION_TASK_RUNNING": "コピーする前にタスクを停止してください。",+ "MIGRATION_SHARED_DIRECTORY_BUSY": "別のタスクがこのフォルダーを使用しています。停止してから再試行してください。",+ "MIGRATION_TASK_UNSUPPORTED": "このタスクの種類または現在の状態では、別のコンピューターにコピーできません。",+ "MIGRATION_NO_MEMORY": "タスク履歴全体を処理するためのメモリが不足しています。メモリを解放して再試行してください。",+ "MIGRATION_INCOMPLETE_CONTEXT": "タスク履歴が不完全なため、コピーを停止しました。",+ "MIGRATION_EXTERNAL_LINK": "フォルダー外へのリンク、または未対応のリンクチェーンがあります。元のファイルは変更されていません。",+ "MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git プロジェクトでは、タスクのフォルダーがリポジトリのルートである必要があります。",+ "MIGRATION_SUBMODULE_UNSUPPORTED": "Git サブモジュールを含むプロジェクトのコピーは未対応です。",+ "MIGRATION_NO_SPACE": "コピー先の空き容量が不足しています。",+ "MIGRATION_TARGET_MODEL_UNAVAILABLE": "コピー先にこのタスクのエンジンで利用できるモデルがありません。先にプロバイダーを接続してください。",+ "MIGRATION_UNSUPPORTED": "両方のコンピューターをタスクのコピーに対応したバージョンに更新してください。",+ "MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。",+ "MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。"+ }+ },"sharedTask": {"manageSharing": "共有管理","manageMembers": "メンバーを管理…",@@ -10313,8 +10364,8 @@"pin": "ピン留め","unpin": "ピン留め解除","archived": "アーカイブ済み",- "moveToProject": "プロジェクトへ移動",- "moveToProjectHeading": "プロジェクトを選択",+ "moveToProject": "タスクを移動",+ "moveToProjectHeading": "現在のコンピューターのプロジェクト","browseProjectFolder": "プロジェクトフォルダーを選択","moveToDialogue": "対話へ移動","noProjects": "最近使ったプロジェクトはありません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 3f4267d498..4dc1c8c3a3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,4 +1,55 @@{+ "taskMove": {+ "upgradeComputer": "이 컴퓨터의 Cindy 버전은 작업 이동을 지원하지 않습니다. “{{name}}”의 Cindy를 업데이트해 주세요.",+ "sourceProjects": "작업이 있는 컴퓨터의 프로젝트",+ "otherComputers": "다른 컴퓨터로 복사",+ "offline": "오프라인",+ "loading": "불러오는 중…",+ "retry": "불러오지 못했습니다. 다시 시도",+ "moved": "작업을 이동했습니다",+ "failed": "작업을 이동할 수 없습니다. 작업을 중지하고 대상 폴더를 확인한 후 다시 시도하세요."+ },+ "taskMigration": {+ "title": "다른 컴퓨터로 복사…",+ "description": "대상 컴퓨터에 독립된 사본을 만듭니다. 원본 작업과 파일은 유지됩니다.",+ "bindingsNotice": "자동 실행과 메시지 연결은 원본 컴퓨터에 남으며 복사되지 않습니다.",+ "limits": "두 컴퓨터 모두 이 기능을 지원하고 원격 제어가 켜져 있어야 합니다. 먼저 이 폴더를 사용하는 작업을 중지하세요. 복사 전에 대상 컴퓨터의 디스크 여유 공간과 사용 가능한 메모리를 확인합니다. 대상 컴퓨터의 모델 설정을 사용하며 Cindy 로그인 정보와 컴퓨터 설정은 전송하지 않습니다.",+ "device": "대상 컴퓨터",+ "project": "저장 위치",+ "newFolder": "새 폴더를 만들며 기존 파일은 덮어쓰지 않습니다.",+ "defaultFolder": "Cindy 기본 위치",+ "noDevices": "사용 가능한 컴퓨터가 없습니다. 다른 컴퓨터를 연결하고 두 컴퓨터 모두 원격 제어를 켜세요.",+ "background": "이 창을 닫아도 작업 메뉴에서 다시 열 수 있습니다. 중단된 경우 같은 복사을 재시도하세요.",+ "openTarget": "대상 컴퓨터의 작업 열기",+ "close": "닫기",+ "cancel": "복사 취소",+ "retry": "복사 재시도",+ "start": "작업 복사",+ "failed": "복사을 완료하지 못했습니다. 원본 파일은 유지됩니다. 두 컴퓨터를 확인한 후 다시 시도하세요.",+ "stages": {+ "preparing": "스냅샷 준비 중…",+ "transferring": "파일 전송 및 검증 중…",+ "complete": "복사가 완료되었습니다. 원본 작업과 파일은 유지됩니다.",+ "cancelled": "복사이 취소되었습니다.",+ "receiving": "파일 수신 중…",+ "active": "이 컴퓨터에서 작업을 계속할 수 있습니다."+ },+ "errors": {+ "MIGRATION_TASK_RUNNING": "복사하기 전에 작업을 중지하세요.",+ "MIGRATION_SHARED_DIRECTORY_BUSY": "다른 작업이 이 폴더를 사용 중입니다. 중지한 후 다시 시도하세요.",+ "MIGRATION_TASK_UNSUPPORTED": "이 작업의 유형 또는 현재 상태에서는 다른 컴퓨터로 복사할 수 없습니다.",+ "MIGRATION_NO_MEMORY": "전체 작업 기록을 처리할 메모리가 부족합니다. 메모리를 확보한 후 다시 시도하세요.",+ "MIGRATION_INCOMPLETE_CONTEXT": "전체 작업 기록을 가져올 수 없어 복사을 중지했습니다.",+ "MIGRATION_EXTERNAL_LINK": "폴더 외부 링크 또는 지원되지 않는 링크 체인이 있습니다. 원본 파일은 변경되지 않았습니다.",+ "MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git 프로젝트의 작업 폴더는 저장소 루트여야 합니다.",+ "MIGRATION_SUBMODULE_UNSUPPORTED": "Git 하위 모듈이 있는 프로젝트는 아직 복사할 수 없습니다.",+ "MIGRATION_NO_SPACE": "대상 컴퓨터의 저장 공간이 부족합니다.",+ "MIGRATION_TARGET_MODEL_UNAVAILABLE": "대상 컴퓨터에 이 작업 엔진에서 사용할 수 있는 모델이 없습니다. 먼저 제공자를 연결하세요.",+ "MIGRATION_UNSUPPORTED": "두 컴퓨터 모두 작업 복사을 지원하는 버전으로 업데이트하세요.",+ "MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.",+ "MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요."+ }+ },"sharedTask": {"manageSharing": "공유 관리","manageMembers": "멤버 관리…",@@ -10313,8 +10364,8 @@"pin": "고정","unpin": "고정 해제","archived": "보관됨",- "moveToProject": "프로젝트로 이동",- "moveToProjectHeading": "프로젝트 선택",+ "moveToProject": "작업 이동",+ "moveToProjectHeading": "현재 컴퓨터의 프로젝트","browseProjectFolder": "프로젝트 폴더 선택","moveToDialogue": "대화로 이동","noProjects": "최근 프로젝트 없음",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex c1e0087ef8..531a92076c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,4 +1,55 @@{+ "taskMove": {+ "upgradeComputer": "这台电脑的 Cindy 版本暂不支持移动任务。请更新「{{name}}」上的 Cindy 后再试。",+ "sourceProjects": "任务所在电脑的项目",+ "otherComputers": "复制到其他电脑",+ "offline": "离线",+ "loading": "加载中…",+ "retry": "加载失败,重试",+ "moved": "任务已移动",+ "failed": "无法移动任务。请停止任务,检查目标目录后重试。"+ },+ "taskMigration": {+ "title": "复制到其他电脑…",+ "description": "在目标电脑创建独立副本,原任务和文件保留。",+ "bindingsNotice": "自动任务和消息渠道仍在源电脑运行,不会随任务复制。",+ "limits": "两台电脑都需支持此功能并开启远程控制。请先停止使用该目录的任务。复制前会检查目标电脑的磁盘空间和可用内存。目标电脑使用自己的模型设置,不传输 Cindy 登录凭证和机器设置。",+ "device": "目标电脑",+ "project": "目标位置",+ "newFolder": "新建文件夹,不覆盖已有文件。",+ "defaultFolder": "Cindy 默认位置",+ "noDevices": "暂无可用电脑。请连接另一台电脑,并在两台电脑上开启远程控制。",+ "background": "可以关闭窗口,稍后从任务菜单重新打开。中断后请重试同一次复制。",+ "openTarget": "打开目标电脑上的任务",+ "close": "关闭",+ "cancel": "取消复制",+ "retry": "重试复制",+ "start": "复制任务",+ "failed": "复制未完成,源文件已保留。请检查两台电脑后重试。",+ "stages": {+ "preparing": "正在准备快照…",+ "transferring": "正在传输并校验文件…",+ "complete": "复制完成,原任务和文件保留。",+ "cancelled": "已取消复制。",+ "receiving": "正在接收文件…",+ "active": "任务已可在此电脑继续。"+ },+ "errors": {+ "MIGRATION_TASK_RUNNING": "请先停止任务再复制。",+ "MIGRATION_SHARED_DIRECTORY_BUSY": "其他任务正在使用此目录,请停止后重试。",+ "MIGRATION_TASK_UNSUPPORTED": "此任务的类型或当前状态暂不支持跨电脑复制。",+ "MIGRATION_NO_MEMORY": "可用内存不足以处理完整任务历史,请释放内存后重试。",+ "MIGRATION_INCOMPLETE_CONTEXT": "无法取得完整任务历史,已停止复制以免丢失上下文。",+ "MIGRATION_EXTERNAL_LINK": "项目包含指向目录外部的链接或暂不支持的链接链,源文件未改动。",+ "MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git 项目的任务目录必须是仓库根目录。",+ "MIGRATION_SUBMODULE_UNSUPPORTED": "暂不支持复制含 Git 子模块的项目。",+ "MIGRATION_NO_SPACE": "目标电脑可用空间不足。",+ "MIGRATION_TARGET_MODEL_UNAVAILABLE": "目标电脑没有可用于此任务引擎的模型,请先在目标电脑连接供应商。",+ "MIGRATION_UNSUPPORTED": "请将两台电脑更新至支持任务复制的版本。",+ "MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。",+ "MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。"+ }+ },"sharedTask": {"manageSharing": "共享管理","manageMembers": "管理成员…",@@ -10313,8 +10364,8 @@"pin": "置顶","unpin": "取消置顶","archived": "归档",- "moveToProject": "移动到项目",- "moveToProjectHeading": "选择项目",+ "moveToProject": "移动任务",+ "moveToProjectHeading": "当前电脑的项目","browseProjectFolder": "选择项目文件夹","moveToDialogue": "移到对话","noProjects": "暂无最近项目",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 58c6a7229e..ff0602eae2 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,4 +1,55 @@{+ "taskMove": {+ "upgradeComputer": "這台電腦的 Cindy 版本暫不支援移動任務。請更新「{{name}}」上的 Cindy 後再試。",+ "sourceProjects": "任務所在電腦的專案",+ "otherComputers": "複製到其他電腦",+ "offline": "離線",+ "loading": "載入中…",+ "retry": "載入失敗,重試",+ "moved": "任務已移動",+ "failed": "無法移動任務。請停止任務,檢查目標目錄後重試。"+ },+ "taskMigration": {+ "title": "複製到其他電腦…",+ "description": "在目標電腦建立獨立副本,原任務和檔案保留。",+ "bindingsNotice": "自動任務和訊息管道仍在來源電腦執行,不會隨任務複製。",+ "limits": "兩台電腦都需支援此功能並開啟遠端控制。請先停止使用該目錄的任務。複製前會檢查目標電腦的磁碟空間和可用記憶體。目標電腦使用自己的模型設定,不傳輸 Cindy 登入憑證和電腦設定。",+ "device": "目標電腦",+ "project": "目標位置",+ "newFolder": "建立新資料夾,不覆寫現有檔案。",+ "defaultFolder": "Cindy 預設位置",+ "noDevices": "目前沒有可用電腦。請連接另一台電腦,並在兩台電腦上開啟遠端控制。",+ "background": "可以關閉視窗,稍後從任務選單重新開啟。中斷後請重試同一次複製。",+ "openTarget": "開啟目標電腦上的任務",+ "close": "關閉",+ "cancel": "取消複製",+ "retry": "重試複製",+ "start": "複製任務",+ "failed": "複製未完成,來源檔案已保留。請檢查兩台電腦後重試。",+ "stages": {+ "preparing": "正在準備快照…",+ "transferring": "正在傳輸並驗證檔案…",+ "complete": "複製完成,原任務和檔案保留。",+ "cancelled": "已取消複製。",+ "receiving": "正在接收檔案…",+ "active": "任務已可在此電腦繼續。"+ },+ "errors": {+ "MIGRATION_TASK_RUNNING": "請先停止任務再複製。",+ "MIGRATION_SHARED_DIRECTORY_BUSY": "其他任務正在使用此目錄,請停止後重試。",+ "MIGRATION_TASK_UNSUPPORTED": "此任務的類型或目前狀態尚不支援跨電腦複製。",+ "MIGRATION_NO_MEMORY": "可用記憶體不足以處理完整任務歷史,請釋放記憶體後重試。",+ "MIGRATION_INCOMPLETE_CONTEXT": "無法取得完整任務歷史,已停止複製以免遺失上下文。",+ "MIGRATION_EXTERNAL_LINK": "專案包含指向目錄外部的連結或尚不支援的連結鏈,來源檔案未變更。",+ "MIGRATION_REQUIRES_REPOSITORY_ROOT": "Git 專案的任務目錄必須是儲存庫根目錄。",+ "MIGRATION_SUBMODULE_UNSUPPORTED": "尚不支援複製含 Git 子模組的專案。",+ "MIGRATION_NO_SPACE": "目標電腦可用空間不足。",+ "MIGRATION_TARGET_MODEL_UNAVAILABLE": "目標電腦沒有可用於此任務引擎的模型,請先在目標電腦連接供應商。",+ "MIGRATION_UNSUPPORTED": "請將兩台電腦更新至支援任務複製的版本。",+ "MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。",+ "MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。"+ }+ },"sharedTask": {"manageSharing": "共享管理","manageMembers": "管理成員…",@@ -10313,8 +10364,8 @@"pin": "置頂","unpin": "取消置頂","archived": "歸檔",- "moveToProject": "移動到專案",- "moveToProjectHeading": "選擇專案",+ "moveToProject": "移動任務",+ "moveToProjectHeading": "目前電腦的專案","browseProjectFolder": "選擇專案資料夾","moveToDialogue": "移到對話","noProjects": "暫無最近專案",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 2f23532cc8..c33d52c680 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3922,6 +3922,7 @@ interface ElectronAPI {account(command: import('@cindy/device-link').SharedTaskAccountCommand): Promise<unknown>;};deviceLink: {+ taskMigration: (deviceId: string | null, request: import('@cindy/device-link').TaskMigrationRequest) => Promise<import('@cindy/device-link').TaskMigrationView>;getState: () => Promise<{remoteControlEnabled: boolean;keepAwake: boolean;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 03bd6a261f..dddeb8ae11 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -13,6 +13,17 @@## 电脑互联的消息文件与历史变更+跨电脑任务复制使用同账号业务通道 `maker:task-copy`,受信 Renderer 使用 `task-copy:request`。+不开放裸导入、数据库或路径写入;共享访客不准入。该通道与旧 `maker:task-migration` 交接协议+隔离,旧端拒绝时提示升级,不退回旧交接协议或控制端执行。新端也不接收旧协议的 activate。+源任务和文件保留可用,自动任务及消息渠道不转移。数据复用 peer 附件与 OSS;复制记录及目标回执+仅用于幂等重试,不管理源任务执行权。写请求不进入自动重试白名单,无需服务端变更。+`preflight` 检查目标实时资源;文件描述可为单附件或有序分段附件,每段复用已有协议和校验,+复制不设固定总量上限。整组 Orca 沿用可选 `teamMigration: true` 能力声明,缺省不支持;+`receive.files.additionalWorkspaces` 沿用同一文件描述,manifest 记录成员到目录的映射。+双方必须支持复制通道;收到整组能力声明才发送团队,不尝试部分导入。+范围、恢复与源目录保护见 [同机移动与跨电脑复制任务](../product-rules/task-device-migration.md)。+设备互联生成文件沿用远端文件服务的 stat 与修改时间,控制端按被控端消息时间窗校验命令产物;仅有文件存在、缺失时间戳或读取失败不构成命令产物证据。不增加 relay 协议字段。SSH 保持仅展示经过存在性复核的工具产物,不把 Desktop 消息时间与 SSH 主机文件时间比较。@@ -472,3 +483,7 @@ canonical 主任务时,宿主额外追加 `resourceCollectionId=teammates&reso该块后带 `query` 重读同一资源。旧控制端不声明也不传 `query`,列表页原样可用;旧主机忽略 `query`,也不提供记忆页面,新手机显示原有升级提示。未新增 channel、relay 类型、allowlist、权限、数据库迁移或Mobile 原生 fingerprint 输入,服务端无需改动。++任务迁移业务通道的 `move-project` action 在任务所属宿主复用项目移动校验与更新,+仅接受任务 ID 和明确的目录(null 表示移到对话)。不开放远程 sessions 原始 patch;+旧宿主拒绝未知 action,不回退到控制端本机执行。diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.mdnew file mode 100644index 0000000000..82e3d487df--- /dev/null+++ b/docs/product-rules/task-device-migration.md@@ -0,0 +1,53 @@+# 同机移动与跨电脑复制任务++任务菜单保留同机「移动任务」的项目、选择文件夹及移到对话行为;「复制到其他电脑」在目标+创建独立副本。选定电脑及位置后,确认框说明原任务和文件保留,自动任务和消息渠道仍在源电脑+运行、不随副本复制。自动任务、飞书路由、共享或 Goal 绑定不阻止复制,也不转交给副本。+源任务不会归档、变成只读或失去执行权;不删除源项目及 fork 共用目录。++离线电脑不显示。明确不支持复制协议时才提示更新;连接失败不推断为版本过旧。+远程任务的同机项目切换仍发送到任务所属电脑,复用已有 `moveSession` 宿主业务路径,+不开放远程原始 DB patch。同机移动不会传输文件,其既有绑定及运行状态校验保持不变。++## 复制内容与流程++1. 复制普通 Desktop、共享来源或飞书来源的任务,以及从主任务发起的整组 Orca 任务。+ SSH、Review、其它消息渠道和伙伴任务不在当前范围。不能单独复制 Worker;整组包含已归档成员。+ 准备时检查成员、排队输入及运行状态,等待已有消息落盘。自动运行的绑定本身不构成阻止条件。+ 导出与目录快照完成后复核成员、运行/排队状态和任务更新时间;发生变化则留在准备阶段重试,+ 不发布这次副本。该检查不冻结输入,也不承诺外部编辑器与数据库的跨进程原子快照。+ 复制是一次快照,不持续同步;源任务后续变化不会更新副本。快照遇到文件变化会失败并允许重试。+2. 复用任务分享导出、原生上下文恢复及 worktree 快照。包含未提交、未跟踪和忽略文件;+ Git 保留 HEAD、暂存区和工作文件差别,不复制本机 Git 配置、hooks 或凭证。+ 目标始终创建独立目录,不覆盖已有项目。整组共享物理目录只复制一份,独立目录分别创建。+3. 复用 peer 直传及 OSS 回退、冷却。按实时磁盘和可用内存预算准备、发送、接收及解包,+ 不设任务总大小上限;大文件按现有单对象传输容量分段,校验大小及 SHA-256 后解包。+4. 目标以复制 ID 幂等导入,整组沿用已有团队事务。导入成功即可使用目标任务,+ 不等待源端让出执行权,也不自动开始模型回合。任务使用目标模型设置,权限回到需要确认的模式。+5. 源端清理本次暂存和传输文件后记录完成。中断可从任务菜单重试同一次复制,回执丢失不重复导入。+ 完成后可再次复制并生成新的独立副本。++源端仅记录 `preparing → transferring → complete`(准备阶段可取消);目标记录接收与完成。+开始、取消和后台复制复用同一个源任务标识的既有跨进程锁,防止多实例覆盖同一进度。+进度日志不用于限制源任务的输入、改名、标签、Goal、共享或团队操作,不扫描其它任务日志。+旧交接日志不会让任务只读。新副本不复制调度、渠道和共享授权绑定;原绑定继续使用原任务。++准备中断后先清理本次旧暂存再重建;传输重试先清理本次旧分段再检查容量。+目标提交结果未知时保留恢复目录,重试按固定任务 ID 和目录核实。失败目录不会自动删除,+避免丢掉用户已经打开或编辑的文件;路径保存在当前账号 `task-copies/receipts/<复制 ID>.json`+的 `retainedWorkingDirs`。确认不需要后可手工清理旧目录,勿删除当前任务及 Worker 的工作目录。++## 边界与兼容++- 本机到远端、远端到本机及远端到另一台电脑均通过同账号 Desktop 设备互联。Mobile 没有新增入口。+- 新通道 `maker:task-copy` 与旧交接协议隔离,避免新客户端误调用旧主机的移动语义。+ `task-copy:request` 仅供受信 Desktop Renderer,不能提交接收或回执请求;共享访客不可调用。+ 接收绑定源设备、源任务和复制 ID,持续复核账号代次、DB 实例及远控授权。+- 不转移 Cindy 登录或供应商凭证。项目内 `.env` 等忽略文件属于用户项目快照。+- 原生上下文必须完整,为 CC、Codex、Pi 分配独立标识;不降级为只有可见消息的副本。+- Git 目录须为仓库根;暂不支持子模块、嵌套 Git 元数据、无首个提交仓库、目录外链接或链接链,+ 以及目标系统无法表示的文件名和大小写冲突。空间或内存不足时提示并保留源文件。+- 失败仅影响本次复制,不重启 relay、不关闭其它设备链路、不重放无关请求。接收预算 30 分钟,+ 其它请求 30 秒;写请求没有通用自动重试。没有服务端或数据库 schema 变更。++两台真实电脑端到端、Windows 实机与 Light/Dark 实际目检尚未完成;单元测试不替代这些验证。diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex 9123185fee..5389f2c42d 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -3,6 +3,7 @@* 这是远程控制的安全闸门,回归必须显式。*/import { describe, it, expect } from 'vitest';+import { TASK_MIGRATION_CHANNEL } from '../taskMigration.js';import {REMOTE_INVOKE_ALLOWLIST,REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS,@@ -375,7 +376,9 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {// - `maker:api-key:present` 是 presence-only 探测:只回 { present: boolean },// 不回、也永不扩展为读取密钥材料(handler 见 desktop authHandlers.ts)。密钥类// 通用读写(api-key:save/get、safe-storage)仍被本模式看住,禁止再加同前缀通道。- const FORBIDDEN_EXEMPT = new Set(['maker:goal:set', 'maker:api-key:present']);+ // 单任务迁移仅允许同账号控制端,通过校验后的快照附件与持久交接状态机执行;+ // 不提供通用导入、调用方指定任意目标路径或裸写库接口。+ const FORBIDDEN_EXEMPT = new Set(['maker:goal:set', 'maker:api-key:present', TASK_MIGRATION_CHANNEL]);for (const ch of REMOTE_INVOKE_ALLOWLIST) {if (FORBIDDEN_EXEMPT.has(ch)) continue;for (const { re, why } of FORBIDDEN) {diff --git a/packages/device-link/src/__tests__/taskMigration.test.ts b/packages/device-link/src/__tests__/taskMigration.test.tsnew file mode 100644index 0000000000..bb8620be52--- /dev/null+++ b/packages/device-link/src/__tests__/taskMigration.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vitest";+import {+ TASK_MIGRATION_CHANNEL,+ TASK_MIGRATION_LOCAL_CHANNEL,+ parseTaskMigrationRequest,+} from "../taskMigration.js";+import { REMOTE_INVOKE_ALLOWLIST } from "../allowlist.js";+import {+ isCompletedInvokeRetryableReadChannel,+ isPeerResetRetryableReadChannel,+ resolveRemoteInvokeTimeoutMs,+} from "../invokePolicy.js";++describe("task copy protocol", () => {+ it("cannot dispatch the previous ownership-handoff protocol", () => {+ expect(TASK_MIGRATION_CHANNEL).toBe("maker:task-copy");+ expect(REMOTE_INVOKE_ALLOWLIST.has("maker:task-migration")).toBe(false);+ expect(() => parseTaskMigrationRequest({ action: "activate", id: "01234567-0123-4123-a123-012345678901", sourceSessionId: "source" })).toThrow();+ });+ it("accepts only explicit project or dialogue moves on the narrow host action", () => {+ for (const workingDir of [null, "/projects/new", "C:/projects/new"])+ expect(parseTaskMigrationRequest({ action: "move-project", sessionId: "task", workingDir })).toEqual({ action: "move-project", sessionId: "task", workingDir });+ for (const workingDir of [undefined, "", "bad\0path", 12])+ expect(() => parseTaskMigrationRequest({ action: "move-project", sessionId: "task", workingDir })).toThrow();+ });+ it("exposes only the narrow remote business channel, without automatic write retries", () => {+ expect(REMOTE_INVOKE_ALLOWLIST.has(TASK_MIGRATION_CHANNEL)).toBe(true);+ expect(REMOTE_INVOKE_ALLOWLIST.has(TASK_MIGRATION_LOCAL_CHANNEL)).toBe(+ false,+ );+ expect(isPeerResetRetryableReadChannel(TASK_MIGRATION_CHANNEL)).toBe(false);+ expect(isCompletedInvokeRetryableReadChannel(TASK_MIGRATION_CHANNEL)).toBe(+ false,+ );+ for (const platform of ["desktop", "mobile"] as const) {+ expect(+ resolveRemoteInvokeTimeoutMs(+ TASK_MIGRATION_CHANNEL,+ [{ action: "receive" }],+ platform,+ ),+ ).toBe(30 * 60_000);+ expect(+ resolveRemoteInvokeTimeoutMs(+ TASK_MIGRATION_CHANNEL,+ [{ action: "status" }],+ platform,+ ),+ ).toBe(30_000);+ }+ });+ it("rejects unsafe identifiers and invalid sizes without a fixed total limit", () => {+ for (const sessionId of ["../other", "", "a/b", "a\\b"])+ expect(() =>+ parseTaskMigrationRequest({+ action: "start",+ sessionId,+ targetDeviceId: "B",+ }),+ ).toThrow();+ 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 },+ };+ expect(parseTaskMigrationRequest(receive)).toEqual(receive);+ expect(+ parseTaskMigrationRequest({+ ...receive,+ files: {+ ...receive.files,+ additionalWorkspaces: [{ workspace: file, repository: file }],+ },+ }),+ ).toBeDefined();+ for (const additionalWorkspaces of [+ null,+ {},+ [null],+ [{}],+ [{ workspace: { ...file, size: -1 } }],+ ])+ expect(() =>+ parseTaskMigrationRequest({+ ...receive,+ files: { ...receive.files, additionalWorkspaces },+ }),+ ).toThrow();+ expect(+ parseTaskMigrationRequest({+ ...receive,+ files: {+ ...receive.files,+ session: { ...file, size: 512 * 1024 ** 2 },+ workspace: {+ size: 6 * 1024 ** 3,+ parts: Array.from({ length: 3 }, () => ({+ ...file,+ size: 2 * 1024 ** 3,+ })),+ },+ },+ }),+ ).toBeDefined();+ for (const size of [-1, 0, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])+ expect(() =>+ parseTaskMigrationRequest({+ ...receive,+ files: { ...receive.files, workspace: { ...file, size } },+ }),+ ).toThrow();+ expect(() =>+ parseTaskMigrationRequest({+ ...receive,+ files: { ...receive.files, workspace: { size: 101, parts: [file] } },+ }),+ ).toThrow();+ expect(() =>+ parseTaskMigrationRequest({ ...receive, targetProject: "bad\0path" }),+ ).toThrow();+ });+});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex e0a063166d..fa9539dbb1 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -13,7 +13,8 @@* updater / release-notes、被控端全局设置写(maker:compat-mode:set 等 *_SET 设置类——* 远程改被控端全局设置越权)、local-db 裸写(sessions:create/update、messages:create——* 写库必须经业务 handler,不开裸写)、maker:execute-desktop-command(UI 副作用)、- * migration / session-import、skillhub 写操作。+ * 通用 migration / session-import、skillhub 写操作。任务迁移仅放行下述受限业务通道,+ * 不开放通用导入、任意路径写入或裸数据库迁移。** 双层校验:控制端发送前(快速失败)+ 被控端执行前(权威)。* 新增 channel 不进表即天然不可远程调用(代码保证确定性)。@@ -24,6 +25,7 @@* Renderer 可调用。它由业务 dispatch 拦截,绝不放行通用 UI / shell IPC。*/import { FILE_PEER_CHANNEL } from './filePeer.js';+import { TASK_MIGRATION_CHANNEL } from './taskMigration.js';import { SESSION_ACTIVITY_CHANNEL, SESSION_SYNC_CHANNEL } from './topics.js';import { REMOTE_DESKTOP_INVOKE_MS } from './remoteDesktopIce.js';import {@@ -320,6 +322,7 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// 入方向媒体取件(被控端 dispatch 拦截执行,不落 ipcMain handler;契约登记 + 能力探测)。DL_MEDIA_FETCH_CHANNEL,FILE_PEER_CHANNEL,+ TASK_MIGRATION_CHANNEL,// 出方向语音转写(被控端 dispatch 拦截执行,不落 ipcMain handler;复用被控端 ASR 配置)。DL_VOICE_TRANSCRIBE_CHANNEL,// 临时 voice credential 同步(被控端 dispatch 拦截执行,不落 ipcMain handler;禁止泛化)。diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex 1c41e3cca8..69332bce0e 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -52,3 +52,4 @@ export * from "./pluginConnectionSubmission.js";export * from "./pluginDeviceAuthorization.js";export * from "./pluginOauthAuthentication.js";export * from "./inputDelivery.js";+export * from "./taskMigration.js";diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.tsindex b5e78f64a6..2cab305e67 100644--- a/packages/device-link/src/invokePolicy.ts+++ b/packages/device-link/src/invokePolicy.ts@@ -1,4 +1,5 @@import { INVOKE_TIMEOUT_OVERRIDES_MS } from './allowlist.js';+import { TASK_MIGRATION_CHANNEL } from './taskMigration.js';import type { InvokePayload } from './protocol.js';/**@@ -75,6 +76,11 @@ export function resolveRemoteInvokeTimeoutMs(args?: unknown[],platform: 'desktop' | 'mobile' = 'desktop',): number | undefined {+ if (channel === TASK_MIGRATION_CHANNEL) {+ const request = args?.[0];+ return request && typeof request === 'object' && 'action' in request && request.action === 'receive'+ ? 30 * 60_000 : 30_000;+ }if (platform === 'desktop') return INVOKE_TIMEOUT_OVERRIDES_MS[channel];// Renewals must settle before the 12s lease, independently of slow media offers.const request = args?.[0];diff --git a/packages/device-link/src/taskMigration.ts b/packages/device-link/src/taskMigration.tsnew file mode 100644index 0000000000..90bcf54646--- /dev/null+++ b/packages/device-link/src/taskMigration.ts@@ -0,0 +1,214 @@+/** Same-account independent task copy. File bytes use existing peer attachments / OSS, never relay frames. */+export const TASK_MIGRATION_CHANNEL = "maker:task-copy";+export const TASK_MIGRATION_LOCAL_CHANNEL = "task-copy:request";+export interface MigrationFileRef {+ ref: string;+ size: number;+ sha256: string;+}+export type MigrationFile =+ MigrationFileRef | { size: number; parts: MigrationFileRef[] };+export interface MigrationResources {+ transferBytes: number;+ unpackedBytes: number;+ contextBytes: number;+ manifestBytes: number;+ repositoryBytes: number;+ entries: number;+}+export interface MigrationFiles {+ session: MigrationFile;+ workspace: MigrationFile;+ manifest: MigrationFile;+ repository?: MigrationFile;+ additionalWorkspaces?: Array<{+ workspace: MigrationFile;+ repository?: MigrationFile;+ }>;+}+export type TaskMigrationRequest =+ | {+ action: "preflight";+ targetProject: string | null;+ resources: MigrationResources;+ }+ | { action: "caps" }+ | { action: "move-project"; sessionId: string; workingDir: string | null }+ | {+ action: "start";+ sessionId: string;+ targetDeviceId: string;+ targetProject?: string | null;+ }+ | { action: "status" | "retry" | "cancel"; sessionId: string }+ | {+ action: "receive";+ id: string;+ sourceSessionId: string;+ targetProject: string | null;+ files: MigrationFiles;+ }+ | { action: "receipt"; id: string; sourceSessionId: string };+export interface TaskMigrationView {+ supported: true;+ deviceId: string;+ projectMove?: {+ sessionId: string;+ workingDir: string | null;+ workspaceKind: string;+ };+ stage?:+ | "preparing"+ | "transferring"+ | "complete"+ | "cancelled"+ | "receiving"+ | "active";+ running?: boolean;+ targetDeviceId?: string;+ targetSessionId?: string;+ error?: string;+ projects?: string[];+ agents?: Array<"cc" | "codex" | "pi">;+ /** Entire Orca graph, native contexts and per-member workspaces. Absence means unsupported. */+ teamMigration?: true;+}++export function parseTaskMigrationRequest(+ value: unknown,+): TaskMigrationRequest {+ if (!value || typeof value !== "object")+ throw new Error("MIGRATION_INVALID_REQUEST");+ const r = value as Record<string, unknown>;+ const id = (v: unknown): v is string =>+ typeof v === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(v);+ const uuid = (v: unknown): v is string =>+ typeof v === "string" && /^[a-f0-9-]{36}$/.test(v);+ const project = (v: unknown) =>+ v == null ||+ (typeof v === "string" &&+ v.length > 0 &&+ v.length <= 4096 &&+ !v.includes("\0"));+ if (+ r.action === "move-project" &&+ id(r.sessionId) &&+ r.workingDir !== undefined &&+ project(r.workingDir)+ )+ return {+ action: "move-project",+ sessionId: r.sessionId,+ workingDir: r.workingDir as string | null,+ };+ if (r.action === "caps") return { action: "caps" };+ if (+ r.action === "preflight" &&+ project(r.targetProject) &&+ r.resources &&+ typeof r.resources === "object"+ ) {+ const resources = r.resources as MigrationResources;+ for (const key of [+ "transferBytes",+ "unpackedBytes",+ "contextBytes",+ "manifestBytes",+ "repositoryBytes",+ "entries",+ ] as const)+ if (!Number.isSafeInteger(resources[key]) || resources[key] < 0)+ throw new Error("MIGRATION_INVALID_REQUEST");+ return {+ action: "preflight",+ targetProject: (r.targetProject as string | null) ?? null,+ resources,+ };+ }++ if (+ ["status", "retry", "cancel"].includes(String(r.action)) &&+ id(r.sessionId)+ )+ return {+ action: r.action as "status" | "retry" | "cancel",+ sessionId: r.sessionId,+ };+ if (+ r.action === "start" &&+ id(r.sessionId) &&+ id(r.targetDeviceId) &&+ project(r.targetProject)+ )+ return {+ action: "start",+ sessionId: r.sessionId,+ targetDeviceId: r.targetDeviceId,+ targetProject: r.targetProject as string | null,+ };+ if (+ r.action === "receipt" &&+ uuid(r.id) &&+ id(r.sourceSessionId)+ )+ return { action: r.action, id: r.id, sourceSessionId: r.sourceSessionId };+ if (+ r.action === "receive" &&+ uuid(r.id) &&+ id(r.sourceSessionId) &&+ project(r.targetProject) &&+ r.files &&+ typeof r.files === "object"+ ) {+ const files = r.files as MigrationFiles;+ if (+ files.additionalWorkspaces !== undefined &&+ (!Array.isArray(files.additionalWorkspaces) ||+ files.additionalWorkspaces.some(+ (entry) => !entry || typeof entry !== "object",+ ))+ )+ throw new Error("MIGRATION_INVALID_REQUEST");+ const allFiles = [+ files.session,+ files.workspace,+ files.manifest,+ ...(files.repository ? [files.repository] : []),+ ...(files.additionalWorkspaces ?? []).flatMap((entry) => [+ entry.workspace,+ ...(entry.repository ? [entry.repository] : []),+ ]),+ ];+ for (const file of allFiles) {+ if (!file || !Number.isSafeInteger(file.size) || file.size <= 0)+ throw new Error("MIGRATION_INVALID_REQUEST");+ const parts = "parts" in file ? file.parts : [file];+ if (!Array.isArray(parts) || !parts.length)+ throw new Error("MIGRATION_INVALID_REQUEST");+ let size = 0;+ for (const part of parts) {+ if (+ !part ||+ typeof part.ref !== "string" ||+ part.ref.length > 16384 ||+ !Number.isSafeInteger(part.size) ||+ part.size <= 0 ||+ typeof part.sha256 !== "string" ||+ !/^[a-f0-9]{64}$/.test(part.sha256)+ )+ throw new Error("MIGRATION_INVALID_REQUEST");+ size += part.size;+ }+ if (!Number.isSafeInteger(size) || size !== file.size)+ throw new Error("MIGRATION_INVALID_REQUEST");+ }+ return {+ action: "receive",+ id: r.id,+ sourceSessionId: r.sourceSessionId,+ targetProject: (r.targetProject as string | null) ?? null,+ files,+ };+ }+ throw new Error("MIGRATION_INVALID_REQUEST");+}