Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(task-copy): 多账号 Codex 任务可跨电脑复制,失效媒体引用不再挡住复制 (#5315)

Dashbbcaf1e168ab
diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
index 2bee661482..05ead07c59 100644
--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
@@ -36,6 +36,8 @@ import {
scanExternalCodexSessions,
prepareExternalCodexSessionForResume,
readCodexThreadStorageForArchive,
+ dumpCodexThreadStateRows,
+ classifyCodexHistoryOversized,
} from '../maker-host/codex-local-sessions';
import { clearCurrentDbClient, setCurrentDbClient } from '../localDb/client/current';
import type { DbClient } from '../localDb/client/DbClient';
@@ -358,6 +360,64 @@ describe('Codex local session import', () => {
expect(fs.readFileSync(rolloutPath, 'utf8')).toBe('');
});
+ it('dumps multi-account thread state only from its indexed storage', async () => {
+ // 多账号线程存放在 codex-accounts/<owner>/<账号>/,desktop 与外部 HOME 都找不到它。
+ const accountHome = path.join(targetUserData, 'codex-accounts', 'owner', 'openai-a');
+ const dbPath = createStateDb(accountHome);
+ const rolloutPath = path.join(accountHome, 'sessions', `rollout-2026-09-16-${threadId}.jsonl`);
+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
+ fs.writeFileSync(rolloutPath, '{"type":"session_meta"}\n');
+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });
+
+ const legacy = await dumpCodexThreadStateRows(threadId);
+ expect(legacy.threads).toEqual([]);
+ expect(legacy.rolloutPath).toBeNull();
+
+ const indexed = await dumpCodexThreadStateRows(threadId, { sqliteHome: accountHome, rolloutPath });
+ expect(indexed.threads.map((row) => row.id)).toEqual([threadId]);
+ expect(indexed.rolloutPath).toBe(rolloutPath);
+
+ fs.rmSync(rolloutPath);
+ const missing = await dumpCodexThreadStateRows(threadId, { sqliteHome: accountHome, rolloutPath });
+ expect(missing.rolloutPath).toBeNull();
+ });
+
+ it('treats an unreadable indexed state DB as incomplete, but a rollout-only home as valid', async () => {
+ const accountHome = path.join(targetUserData, 'codex-accounts', 'owner', 'openai-b');
+ const rolloutPath = path.join(accountHome, 'sessions', `rollout-2026-09-16-${threadId}.jsonl`);
+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
+ fs.writeFileSync(rolloutPath, '{"type":"session_meta"}\n');
+
+ // 纯 rollout 的存储(没有状态库)是合法的空 state。
+ const rolloutOnly = await dumpCodexThreadStateRows(threadId, { sqliteHome: accountHome, rolloutPath });
+ expect(rolloutOnly.threads).toEqual([]);
+ expect(rolloutOnly.rolloutPath).toBe(rolloutPath);
+
+ // 状态库损坏:不能当成空 state 带着 rollout 判完整。
+ fs.writeFileSync(path.join(accountHome, 'state_5.sqlite'), 'not a sqlite database');
+ const corrupt = await dumpCodexThreadStateRows(threadId, { sqliteHome: accountHome, rolloutPath });
+ expect(corrupt.rolloutPath).toBeNull();
+
+ // 记录的状态目录不存在同样按读不出处理。
+ const missingHome = await dumpCodexThreadStateRows(threadId, {
+ sqliteHome: path.join(accountHome, 'gone'),
+ rolloutPath,
+ });
+ expect(missingHome.rolloutPath).toBeNull();
+ });
+
+ it('classifies multi-account history size only from its indexed rollout', async () => {
+ const accountHome = path.join(targetUserData, 'codex-accounts', 'owner', 'openai-a');
+ const rolloutPath = path.join(accountHome, 'sessions', `rollout-2026-09-16-${threadId}.jsonl`);
+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
+ fs.writeFileSync(rolloutPath, `${rolloutLine(threadId, 'user', 'hi', '2026-09-16T00:00:00.000Z')}\n`);
+
+ expect(await classifyCodexHistoryOversized(threadId)).toBe('unknown');
+ expect(await classifyCodexHistoryOversized(threadId, { rolloutPath })).toBe('healthy');
+ fs.rmSync(rolloutPath);
+ expect(await classifyCodexHistoryOversized(threadId, { rolloutPath })).toBe('unknown');
+ });
+
it('defensively removes complete IDE context from Codex user messages', () => {
const ideContext = '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>';
const cleaned = parseCodexRolloutMessageLine(
diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
index 557e2f5034..066797319b 100644
--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts
+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
@@ -1564,10 +1564,14 @@ export interface CodexThreadStateDump {
/**
* 会话分享导出:dump 一个 codex thread 的 state 三表行 + rollout 文件位置。
- * 查找顺序与 resume 恢复链一致:desktop codex home 的 state DB 优先,
+ * 调用方给出 storage(多账号线程的 thread-index 位置)时只读那一处,不回退别的
+ * HOME,与 resume 同口径;未给出时 desktop codex home 的 state DB 优先,
* 缺行/缺文件再回退外部 CODEX_HOME(~/.codex、Codex.app)。全程只读。
*/
-export async function dumpCodexThreadStateRows(threadId: string): Promise<CodexThreadStateDump> {
+export async function dumpCodexThreadStateRows(
+ threadId: string,
+ storage?: { sqliteHome: string; rolloutPath?: string },
+): Promise<CodexThreadStateDump> {
const empty: CodexThreadStateDump = {
threads: [],
threadDynamicTools: [],
@@ -1576,6 +1580,24 @@ export async function dumpCodexThreadStateRows(threadId: string): Promise<CodexT
};
if (!isLikelyThreadId(threadId)) return empty;
+ if (storage) {
+ // 记录位置的状态库读不出(目录不可访问、库损坏)不等于「本就没有 state」:
+ // 不返回 rollout,让导出按缺转录降档,而不是带着空 state 判成完整。
+ // 没有状态库(纯 rollout 的外部线程)仍是合法的空 state。
+ try {
+ fs.accessSync(storage.sqliteHome, fs.constants.R_OK | fs.constants.X_OK);
+ } catch {
+ return empty;
+ }
+ const dbPath = findLatestStateDb(storage.sqliteHome);
+ const rows = dbPath ? readThreadStateRows(dbPath, threadId) : empty;
+ if (!rows) return empty;
+ return {
+ ...rows,
+ rolloutPath: storage.rolloutPath && fs.existsSync(storage.rolloutPath) ? storage.rolloutPath : null,
+ };
+ }
+
const dbCandidates: string[] = [];
const desktopDb = findLatestStateDb(getDesktopCodexHome());
if (desktopDb) dbCandidates.push(desktopDb);
@@ -1585,7 +1607,7 @@ export async function dumpCodexThreadStateRows(threadId: string): Promise<CodexT
let dump = empty;
for (const dbPath of dbCandidates) {
const rows = readThreadStateRows(dbPath, threadId);
- if (rows.threads.length > 0) {
+ if (rows && rows.threads.length > 0) {
dump = { ...rows, rolloutPath: null };
break;
}
@@ -1666,7 +1688,7 @@ export function reserveCodexForkCleanup(
function readThreadStateRows(
dbPath: string,
threadId: string,
-): Pick<CodexThreadStateDump, 'threads' | 'threadDynamicTools' | 'threadSpawnEdges'> {
+): Pick<CodexThreadStateDump, 'threads' | 'threadDynamicTools' | 'threadSpawnEdges'> | null {
let db: Database.Database | null = null;
try {
db = openReadonlyDb(dbPath);
@@ -1683,14 +1705,14 @@ function readThreadStateRows(
threadSpawnEdges: readTable('thread_spawn_edges', 'parent_thread_id'),
};
} catch (err) {
- // DB 锁 / 权限 / schema 漂移都会走到这:返回空让导出降档,但必须留痕,
+ // DB 锁 / 权限 / schema 漂移都会走到这:返回 null 交调用方决定降档,但必须留痕,
// 否则"为什么 codex state 没进包"无从排查(review bot 指出)。
log.warn('readThreadStateRows failed, exporting without codex state', {
dbPath,
threadId,
error: err instanceof Error ? err.message : String(err),
});
- return { threads: [], threadDynamicTools: [], threadSpawnEdges: [] };
+ return null;
} finally {
closeDbQuietly(db);
}
@@ -3625,12 +3647,16 @@ function dropUndefined<T extends Record<string, unknown>>(obj: T): Partial<T> {
export type CodexHistoryOversizedClass = 'oversized' | 'healthy' | 'unknown';
-/** 只读测量本地 Codex rollout 活尾巴。找不到文件或读失败归 unknown,不得当成健康。 */
+/**
+ * 只读测量本地 Codex rollout 活尾巴。找不到文件或读失败归 unknown,不得当成健康。
+ * 调用方给出 storage(多账号线程的 thread-index 位置)时只认那一处 rollout。
+ */
export async function classifyCodexHistoryOversized(
threadId: string,
+ storage?: { rolloutPath?: string },
): Promise<CodexHistoryOversizedClass> {
if (!threadId) return 'unknown';
- const rolloutPath = resolveRolloutPath(threadId);
+ const rolloutPath = storage ? storage.rolloutPath : resolveRolloutPath(threadId);
if (!rolloutPath) return 'unknown';
try {
const stats = await measureRolloutLiveTailStats(rolloutPath);
diff --git a/apps/desktop/src/main/maker-host/codex-thread-storage.ts b/apps/desktop/src/main/maker-host/codex-thread-storage.ts
new file mode 100644
index 0000000000..b85413aa51
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/codex-thread-storage.ts
@@ -0,0 +1,22 @@
+import path from 'node:path';
+import { getActiveAppSession } from '../appSessionState.js';
+import { codexAccountHome } from './codex-account-auth.js';
+import { readCodexThreadStorageForArchive } from './codex-local-sessions.js';
+import { CodexThreadLocations } from './codex-thread-locations.js';
+
+/** Thread locations of the active owner. Multi-account history lives outside the desktop Codex home. */
+export function ownerCodexThreadLocations(): CodexThreadLocations {
+ return new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));
+}
+
+/**
+ * Locate a thread's existing history without adopting, copying or recording it.
+ * Indexed (account) storage wins; unindexed threads resolve their original storage.
+ */
+export async function readCodexThreadStorageReadOnly(threadId: string): Promise<
+ { historyHome: string; sqliteHome: string; rolloutPath?: string } | undefined
+> {
+ if (!getActiveAppSession().dataOwnerId) return readCodexThreadStorageForArchive(threadId);
+ return await ownerCodexThreadLocations().readStorage(threadId)
+ ?? readCodexThreadStorageForArchive(threadId);
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 7880f51755..7337a0d258 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -17,8 +17,8 @@ import { clearCodexAccountUsageSnapshot } from '../usageBroadcaster.js';
*/
import { createMediaDownloadContext } from '../cindy-media/mediaDownloadApproval.js';
-import { isCodexAccountProvider, codexAccountHome, setCodexAccountRetirement } from './codex-account-auth.js';
-import { CodexThreadLocations } from './codex-thread-locations.js';
+import { isCodexAccountProvider, setCodexAccountRetirement } from './codex-account-auth.js';
+import { ownerCodexThreadLocations, readCodexThreadStorageReadOnly } from './codex-thread-storage.js';
import { createSessionArchiveSync, prepareArchiveSessions } from './session-archive-sync.js';
import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
import { setSessionArchiveSyncRequester } from '../localDb/sessionArchiveSync.js';
@@ -1962,16 +1962,14 @@ export function getMaker(): Maker {
unregisterCodexMcpThreadContext,
prepareCodexResumeSession: async (threadId) => {
if (!getActiveAppSession().dataOwnerId) return prepareExternalCodexSessionForResume(threadId);
- const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));
- return locations.prepareResume(threadId, prepareExternalCodexSessionForResume);
+ return ownerCodexThreadLocations().prepareResume(threadId, prepareExternalCodexSessionForResume);
},
resolveCodexThreadStorage: async (threadId, options) => {
if (!getActiveAppSession().dataOwnerId) return options?.readOnly ? readCodexThreadStorageForArchive(threadId) : undefined;
const ownerScope = activeOwnerScopeKey();
- const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));
const storage = options?.readOnly
- ? await locations.readStorage(threadId) ?? readCodexThreadStorageForArchive(threadId)
- : await locations.readStorage(threadId, {
+ ? await readCodexThreadStorageReadOnly(threadId)
+ : await ownerCodexThreadLocations().readStorage(threadId, {
home: getCodexHome(),
prepare: prepareExternalCodexSessionForResume,
});
@@ -2005,8 +2003,7 @@ export function getMaker(): Maker {
},
recordCodexThreadLocation: async (threadId, storageHome, rolloutPath) => {
if (!rolloutPath || !getActiveAppSession().dataOwnerId) return;
- const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));
- await locations.record(threadId, rolloutPath, storageHome);
+ await ownerCodexThreadLocations().record(threadId, rolloutPath, storageHome);
},
registerCodexSystemPromptForThread: ({
sessionId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 96266e441d..ff4ceca01a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -860,6 +860,7 @@ import {
classifyCodexHistoryOversized,
reserveCodexForkCleanup,
} from '../maker-host/codex-local-sessions.js';
+import { readCodexThreadStorageReadOnly } from '../maker-host/codex-thread-storage.js';
import { hydrateQueuedAgentReferences } from './agentInputReferences.js';
import { agentHandoffPending } from './agentHandoffPendingSingleton.js';
import {
@@ -13314,7 +13315,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
classifyCodexHistory: async (threadId) => {
const ownerScope = captureDataOwnerBroadcastScope();
const dbSnapshot = getCurrentDbClientSnapshot();
- const result = await classifyCodexHistoryOversized(threadId);
+ // 多账号线程的 rollout 在 codex-accounts 下,只有 thread-index 记着位置;
+ // 记录读不出时不回退旧 HOME(可能是过期副本),按 unknown 处理。
+ const storage = await readCodexThreadStorageReadOnly(threadId).catch(() => null);
+ const result = storage === null ? 'unknown' : await classifyCodexHistoryOversized(threadId, storage);
if (
!dbSnapshot || !isDataOwnerBroadcastScopeCurrent(ownerScope) ||
getCurrentDbClientSnapshot()?.clientEpoch !== dbSnapshot.clientEpoch
diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts
index 44e558b938..d5c9d99bfa 100644
--- a/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts
+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareExport.test.ts
@@ -61,24 +61,37 @@ vi.mock('../../maker-host/claude-transcript-relocation.js', () => ({
activeId: 'sid-b',
}),
}));
+const dumpCodexThreadStateRowsMock = vi.fn(async (_threadId: string, _storage?: unknown) => ({
+ threads: [{ id: 'thread-1', cwd: '/old/cwd' }],
+ threadDynamicTools: [],
+ threadSpawnEdges: [],
+ rolloutPath: path.join(tmpRoot, 'rollout-1-thread-1.jsonl'),
+}));
vi.mock('../../maker-host/codex-local-sessions.js', () => ({
- dumpCodexThreadStateRows: async () => ({
- threads: [{ id: 'thread-1', cwd: '/old/cwd' }],
- threadDynamicTools: [],
- threadSpawnEdges: [],
- rolloutPath: path.join(tmpRoot, 'rollout-1-thread-1.jsonl'),
- }),
+ dumpCodexThreadStateRows: dumpCodexThreadStateRowsMock,
+}));
+const readCodexThreadStorageReadOnlyMock = vi.fn(
+ async (_threadId: string): Promise<{ historyHome: string; sqliteHome: string; rolloutPath?: string } | undefined> =>
+ undefined,
+);
+vi.mock('../../maker-host/codex-thread-storage.js', () => ({
+ readCodexThreadStorageReadOnly: readCodexThreadStorageReadOnlyMock,
}));
const configDirCandidatesRef = { dirs: [path.join(tmpRoot, 'claude-home')] };
vi.mock('../../maker-orchestration/claudeTranscriptAnchors.js', () => ({
defaultClaudeConfigDirCandidates: () => configDirCandidatesRef.dirs,
}));
+const imagePathRef = { path: path.join(tmpRoot, 'img.png') };
vi.mock('../../imageCacheStore.js', () => ({
resolveSafe: (url: string) => {
if (!url.startsWith('xdt-image://')) throw new Error('bad url');
- return { absPath: path.join(tmpRoot, 'img.png'), mimeType: 'image/png' };
+ return { absPath: imagePathRef.path, mimeType: 'image/png' };
},
}));
+const ownerScopeRef = { keys: [] as string[] };
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => ownerScopeRef.keys.shift() ?? 'owner:a:1',
+}));
vi.mock('../../videoCacheStore.js', () => ({
resolveSafe: () => ({ absPath: path.join(tmpRoot, 'missing-video.mp4'), mimeType: 'video/mp4' }),
}));
@@ -162,6 +175,11 @@ describe('exportSessionShare', () => {
messagesRef.rows = baseMessages();
activeTeamRef.row = null;
getActiveTeamByLeadMock.mockClear();
+ dumpCodexThreadStateRowsMock.mockClear();
+ imagePathRef.path = path.join(tmpRoot, 'img.png');
+ ownerScopeRef.keys = [];
+ readCodexThreadStorageReadOnlyMock.mockReset();
+ readCodexThreadStorageReadOnlyMock.mockResolvedValue(undefined);
workerRowsRef.rows = [];
workerSessionsById.clear();
workerMessagesBySession.clear();
@@ -255,6 +273,39 @@ describe('exportSessionShare', () => {
expect(state.threads[0].id).toBe('thread-1');
});
+ it('codex export reads multi-account history from the thread location index', async () => {
+ // 多账号线程的历史在 codex-accounts/<owner>/<账号>/ 下,只有 thread-index 知道位置。
+ const storage = {
+ historyHome: path.join(tmpRoot, 'codex-accounts', 'owner', 'openai-a'),
+ sqliteHome: path.join(tmpRoot, 'codex-accounts', 'owner', 'openai-a'),
+ rolloutPath: path.join(tmpRoot, 'codex-accounts', 'owner', 'openai-a', 'sessions', 'rollout.jsonl'),
+ };
+ readCodexThreadStorageReadOnlyMock.mockResolvedValue(storage);
+ sessionRowRef.row = { ...baseSession(), agentKind: 'codex', sdkSessionId: 'thread-1' };
+ const outcome = await exportSessionShare({
+ sessionId: 'xdt-session-1',
+ targetPath: path.join(tmpRoot, 'out-codex-indexed.xdtshare'),
+ });
+ expect(outcome.status).toBe('ok');
+ expect(readCodexThreadStorageReadOnlyMock).toHaveBeenCalledWith('thread-1');
+ expect(dumpCodexThreadStateRowsMock).toHaveBeenCalledWith('thread-1', storage);
+ });
+
+ it('codex export never substitutes legacy history when the location index is unreadable', async () => {
+ // 记录存在却读不出:旧 HOME 可能留着同一线程的过期副本,不得回退去拿。
+ readCodexThreadStorageReadOnlyMock.mockRejectedValue(new Error('Invalid Codex thread location'));
+ sessionRowRef.row = { ...baseSession(), agentKind: 'codex', sdkSessionId: 'thread-1' };
+ const outcome = await exportSessionShare({
+ sessionId: 'xdt-session-1',
+ targetPath: path.join(tmpRoot, 'out-codex-index-error.xdtshare'),
+ });
+ expect(outcome.status).toBe('ok');
+ if (outcome.status !== 'ok') return;
+ expect(dumpCodexThreadStateRowsMock).not.toHaveBeenCalled();
+ expect(outcome.fidelity).toBe('db-only');
+ expect(outcome.missingTranscripts).toEqual(['thread-1']);
+ });
+
it('pi export replaces absolute session paths with portable ids', async () => {
const piSessionFile = path.join(tmpRoot, 'pi-agent-home', 'sessions', 'source-session.jsonl');
await fsp.mkdir(path.dirname(piSessionFile), { recursive: true });
@@ -378,11 +429,14 @@ describe('exportSessionShare', () => {
const pastedUrl = `xdt-file://local/?path=${encodeURIComponent(pastedDoc)}`;
const plantedUrl = `xdt-file://local/?path=${encodeURIComponent(plantedDoc)}`;
const managedUrl = `xdt-audio://local/?path=${encodeURIComponent(managedAudio)}`;
+ const absentUrl = `xdt-file://local/?path=${encodeURIComponent(path.join(tmpRoot, 'never-existed.pdf'))}`;
messagesRef.rows = [
{ ...baseMessages()[0], content: JSON.stringify([{ type: 'text', text: `粘贴的 ${pastedUrl}` }]) },
{
...baseMessages()[1],
- content: JSON.stringify([{ type: 'text', text: `工具输出 ${plantedUrl} 与生成音频 ${managedUrl}` }]),
+ content: JSON.stringify([
+ { type: 'text', text: `工具输出 ${plantedUrl} 与生成音频 ${managedUrl} 示例 ${absentUrl}` },
+ ]),
},
];
const target = path.join(tmpRoot, 'out-loose.xdtshare');
@@ -397,6 +451,11 @@ describe('exportSessionShare', () => {
expect(byUrl.get(pastedUrl)).toBeNull();
expect(byUrl.get(plantedUrl)).toBeNull(); // assistant 输出的任意路径:拒绝
expect(byUrl.get(managedUrl)).toMatch(/^media\/loose\//); // 受管媒体区:放行
+ expect(byUrl.get(absentUrl)).toBeNull();
+ if (outcome.status !== 'ok') return;
+ expect(outcome.mediaMissing).toBe(3);
+ // 源机器上真实存在却被拦下的两份才算丢失;本就不存在的示例地址不算。
+ expect(outcome.mediaDropped).toBe(2);
});
it('cleared session: pre-clear messages and their fork transcripts stay out of the bundle', async () => {
@@ -428,11 +487,45 @@ describe('exportSessionShare', () => {
expect(outcome.status).toBe('ok');
if (outcome.status !== 'ok') return;
expect(outcome.mediaMissing).toBe(1);
+ // 源端本就缺失:复制不会让它更缺,迁移不应据此拦截。
+ expect(outcome.mediaDropped).toBe(0);
const zip = await unzipOf(target);
const mediaMap = JSON.parse(await zip.file('media-map.json')!.async('string'));
expect(mediaMap.entries[0].zipPath).toBeNull();
});
+ it.skipIf(process.platform === 'win32')(
+ 'media whose state cannot be read counts as dropped, not as already missing',
+ async () => {
+ const lockedDir = path.join(tmpRoot, 'locked');
+ await fsp.mkdir(lockedDir, { recursive: true });
+ await fsp.writeFile(path.join(lockedDir, 'img.png'), Buffer.from([0x89, 0x50]));
+ imagePathRef.path = path.join(lockedDir, 'img.png');
+ await fsp.chmod(lockedDir, 0o000);
+ try {
+ const outcome = await exportSessionShare({
+ sessionId: 'xdt-session-1',
+ targetPath: path.join(tmpRoot, 'out-locked-media.xdtshare'),
+ });
+ expect(outcome.status).toBe('ok');
+ if (outcome.status !== 'ok') return;
+ expect(outcome.mediaMissing).toBe(1);
+ expect(outcome.mediaDropped).toBe(1);
+ } finally {
+ await fsp.chmod(lockedDir, 0o755);
+ }
+ },
+ );
+
+ it('aborts without writing when the account changes during export', async () => {
+ ownerScopeRef.keys = ['owner:a:1', 'owner:b:2'];
+ const target = path.join(tmpRoot, 'out-owner-changed.xdtshare');
+ await expect(exportSessionShare({ sessionId: 'xdt-session-1', targetPath: target })).rejects.toThrow(
+ 'account changed during export',
+ );
+ await expect(fsp.stat(target)).rejects.toThrow();
+ });
+
it('rejects remote / orca worker / deleted / empty sessions', async () => {
sessionRowRef.row = { ...baseSession(), remoteHostId: 'host-1' };
await expect(
diff --git a/apps/desktop/src/main/session-share/sessionShareExport.ts b/apps/desktop/src/main/session-share/sessionShareExport.ts
index 530c7a97aa..a0b3cb965f 100644
--- a/apps/desktop/src/main/session-share/sessionShareExport.ts
+++ b/apps/desktop/src/main/session-share/sessionShareExport.ts
@@ -29,6 +29,7 @@ import { setImmediate as yieldToEventLoop } from 'node:timers/promises';
import JSZip from 'jszip';
import { findClaudeSessionJsonl } from '@cindy/maker-core';
+import { activeOwnerScopeKey } from '../appSessionState.js';
import { getDbClient } from '../localDb/client/current.js';
import { getActiveTeamByLead } from '../localDb/orcaTeamStore.js';
import { createLogger } from '../logger.js';
@@ -37,6 +38,7 @@ import {
dumpCodexThreadStateRows,
type CodexThreadStateDump,
} from '../maker-host/codex-local-sessions.js';
+import { readCodexThreadStorageReadOnly } from '../maker-host/codex-thread-storage.js';
import { defaultClaudeConfigDirCandidates } from '../maker-orchestration/claudeTranscriptAnchors.js';
import { resolveSafe as resolveImageUrl } from '../imageCacheStore.js';
import { resolveSafe as resolveVideoUrl } from '../videoCacheStore.js';
@@ -95,6 +97,8 @@ export type SessionShareExportOutcome =
missingTranscripts: string[];
/** 引用了但文件已不存在的媒体数。 */
mediaMissing: number;
+ /** 其中源机器上仍存在、只是没能打进包的媒体数(迁移据此判定会丢内容)。 */
+ mediaDropped: number;
/** 随包携带的协同 Worker 会话数(非协同包为 0)。 */
orcaWorkers: number;
}
@@ -315,7 +319,21 @@ async function collectSessionPhaseA(
activeSdkSessionId = session.sdkSessionId;
sdkSessionIds = session.sdkSessionId ? [session.sdkSessionId] : [];
if (session.sdkSessionId) {
- codexState = await dumpCodexThreadStateRows(session.sdkSessionId);
+ // 多账号线程的 state/rollout 在 codex-accounts 下,只有 thread-index 记着位置;
+ // 与 resume 共用只读定位,没有记录时才走旧的 desktop/外部 HOME 查找。记录存在
+ // 却读不出时不回退:旧 HOME 里可能留着同一线程的过期副本,按缺转录降档。
+ let lookupFailed = false;
+ const storage = await readCodexThreadStorageReadOnly(session.sdkSessionId).catch((err) => {
+ log.warn('codex thread storage lookup failed, exporting without its history', {
+ sessionId: session.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ lookupFailed = true;
+ return undefined;
+ });
+ codexState = lookupFailed
+ ? { threads: [], threadDynamicTools: [], threadSpawnEdges: [], rolloutPath: null }
+ : await dumpCodexThreadStateRows(session.sdkSessionId, storage);
const bytes = codexState.rolloutPath ? await statSize(codexState.rolloutPath) : null;
if (codexState.rolloutPath && bytes) {
const zipPath = `${zipPrefix}transcripts/codex/${path.basename(codexState.rolloutPath)}`;
@@ -447,6 +465,9 @@ async function collectOrcaWorkerSources(
export async function exportSessionShare(
opts: SessionShareExportOptions,
): Promise<SessionShareExportOutcome> {
+ // 会话行、消息与 Codex thread-index 都按当前账号读取;中途换账号会把两个账号
+ // 的数据拼进同一个包,落盘前复核(scope 含代次,A→B→A 同样能识别)。
+ const ownerScope = activeOwnerScopeKey();
const session = await readSessionRow(opts.sessionId);
if (!session) throw codedError('NOT_FOUND', `session not found: ${opts.sessionId}`);
if (session.status === 'deleted') {
@@ -500,6 +521,9 @@ export async function exportSessionShare(
folder: string;
bytes: number;
}> = [];
+ // 源机器上存在却没进包的媒体(受管区外的 loose 文件、读失败)。源端本就缺失
+ // 的引用(文件已删、正文里仅以文字出现的地址)不计入:复制不会让它们更缺。
+ let mediaDropped = 0;
if (!opts.excludeMedia) {
// loose(xdt-file/xdt-audio)的 ?path= 指向本机任意绝对路径。为防被塞进消息
// 文本的 URL 把无关本地文件(如凭证)静默打进分享包,只放行 userData/cc-agent
@@ -529,6 +553,16 @@ export async function exportSessionShare(
const stat = await fsp.stat(absPath).catch(() => null);
return stat?.isFile() && stat.size > 0 ? stat.size : null;
};
+ // 只有确认源端没有内容才算「本就缺失」;权限/IO 错误读不到状态时按未打包计。
+ const confirmedAbsent = async (absPath: string): Promise<boolean> => {
+ try {
+ const stat = await fsp.stat(absPath);
+ return !stat.isFile() || stat.size === 0;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ return code === 'ENOENT' || code === 'ENOTDIR';
+ }
+ };
const seenUrls = new Set<string>();
// 协同包:媒体收集覆盖 lead 与全部 Worker 的消息(URL 全局去重,media-map
// 仍是包级单份——xdt-image 按 URL host 解析,与展示会话无关)。
@@ -544,6 +578,9 @@ export async function exportSessionShare(
(!resolved.absPath || !(await isManagedMediaPath(resolved.absPath)));
const bytes = !looseBlocked && resolved.absPath ? await statSize(resolved.absPath) : null;
if (!bytes) {
+ if (resolved.absPath && !(await confirmedAbsent(resolved.absPath))) {
+ mediaDropped += 1;
+ }
mediaMap.push({ ...resolved.entry, zipPath: null });
continue;
}
@@ -586,6 +623,7 @@ export async function exportSessionShare(
for (const candidate of mediaCandidates) {
const buffer = await fsp.readFile(candidate.absPath).catch(() => null);
if (!buffer || buffer.length === 0) {
+ mediaDropped += 1;
mediaMap.push({ ...candidate.entry, zipPath: null });
continue;
}
@@ -722,6 +760,9 @@ export async function exportSessionShare(
// tmp 名带随机段 + 'wx' 独占创建:固定 `${target}.tmp` 可被共享目录里预先
// 种下的同名 symlink 劫持(writeFile 跟随链接覆盖任意目标,review bot 指出),
// 随机名不可预测,wx 在路径已存在(含 symlink)时直接 EEXIST 拒写。
+ if (activeOwnerScopeKey() !== ownerScope) {
+ throw codedError('SHARE_EXPORT_FAILED', 'account changed during export');
+ }
const tmpPath = `${opts.targetPath}.${randomBytes(8).toString('hex')}.tmp`;
try {
await fsp.writeFile(tmpPath, fileBytes, { flag: 'wx' });
@@ -743,6 +784,7 @@ export async function exportSessionShare(
missingTranscripts: missingTranscripts.length,
media: mediaFiles.length,
mediaMissing,
+ mediaDropped,
encrypted: !!opts.password,
fileBytes: fileBytes.length,
});
@@ -753,6 +795,7 @@ export async function exportSessionShare(
fidelity,
missingTranscripts,
mediaMissing,
+ mediaDropped,
orcaWorkers: workerSources.length,
};
}
diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
index b4f03d9cb7..5cd11b44b4 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -28,6 +28,7 @@ const state = vi.hoisted(() => ({
siblingRunning: false,
noSpace: false,
restoresFail: false,
+ exportMedia: { mediaMissing: 0, mediaDropped: 0 },
sharingLatest: [] as Array<{
shared_task_id: string;
session_id: string;
@@ -145,7 +146,7 @@ vi.mock('../../session-share/sessionShareExport', () => ({
exportSessionShare: async ({ targetPath }: { targetPath: string }) => {
state.exported();
await fs.writeFile(targetPath, 'conversation');
- return { status: 'ok', fidelity: 'full', mediaMissing: false };
+ return { status: 'ok', fidelity: 'full', ...state.exportMedia };
},
}));
vi.mock('../../session-share/sessionShareImport', () => ({
@@ -249,6 +250,7 @@ describe('resumable cross-computer copy', () => {
state.siblingRunning = false;
state.noSpace = false;
state.restoresFail = false;
+ state.exportMedia = { mediaMissing: 0, mediaDropped: 0 };
state.sharingLatest = [];
state.workers = [];
const cwd = path.join(state.root, 'shared');
@@ -803,6 +805,17 @@ describe('resumable cross-computer copy', () => {
).rejects.toThrow('MIGRATION_ID_CONFLICT');
});
+ it('copies a task whose only missing media were already missing on the source', async () => {
+ state.exportMedia = { mediaMissing: 3, mediaDropped: 0 };
+ await start();
+ expect((await settled()).stage).toBe('complete');
+ });
+ it('stops copying when source media exists but could not be packaged', async () => {
+ state.exportMedia = { mediaMissing: 1, mediaDropped: 1 };
+ await start();
+ expect(await settled()).toMatchObject({ stage: 'preparing', error: 'MIGRATION_INCOMPLETE_CONTEXT' });
+ expect(state.imports).not.toHaveBeenCalled();
+ });
it('discards a snapshot when a new turn finishes during preparation', async () => {
state.snapshot.mockImplementationOnce(() => {
state.rows.get('A')!.get('fork')!.updatedAt = 123;
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index a0789208a5..3b40c8125c 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -320,7 +320,7 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
});
scope.assertCurrent();
if (result.status === 'oversize') throw new Error('MIGRATION_NO_MEMORY');
- if (result.status !== 'ok' || result.fidelity !== 'full' || result.mediaMissing)
+ if (result.status !== 'ok' || result.fidelity !== 'full' || result.mediaDropped)
throw new Error('MIGRATION_INCOMPLETE_CONTEXT');
const snapshots: PortableWorkspace[] = [];
for (const [index, dir] of sourceKeys.entries())