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(agent): await native Claude resume before completing relocation

Dash7e14c3ea14da
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index eadf0e2f5c..07da82f16c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -233,6 +233,22 @@ describe('same-harness native relocation', () => {
expect(relocateNativeHistory).not.toHaveBeenCalled();
expect(deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ sdkSessionId: null }));
});
+
+ it('restores the source before opening a native copy whose fallback boundary could not be saved', async () => {
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project', sdkSessionId: 'source-native', agentDeviceId: 'source' })),
+ relocateNativeHistory: vi.fn(async () => 'transferred'),
+ insertBoundaryMessage: vi.fn(async () => { throw new Error('boundary write failed'); }),
+ });
+ await expect(relocateForFreshStart(deps, { sessionId: 's1', agentDeviceId: 'target', providerId: null }))
+ .rejects.toThrow('boundary write failed');
+ expect(deps.applyAgentSwitchToDb).toHaveBeenLastCalledWith('s1', expect.objectContaining({
+ sdkSessionId: 'source-native', agentDeviceId: 'source', providerId: 'xd',
+ }));
+ expect(deps.setSessionProvider).toHaveBeenLastCalledWith('s1', 'xd');
+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();
+ expect(deps.bootstrapSwitchedSession).not.toHaveBeenCalled();
+ });
});
const orcaAgents = [
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 202d95d50a..0d1ac219c8 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -9063,6 +9063,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
let nativeRelocation: Awaited<ReturnType<typeof relocateForFreshStart>> | undefined;
while (!session) {
try {
+ // Claude's ID is prefilled before the CLI accepts resume. Require its
+ // native initialization handshake for every transferred copy, including
+ // a copy chosen by the startup-failure loop. Fresh fallback removes it.
+ const vendorOptions = { ...o.vendorOptions };
+ delete vendorOptions._cindyRequireNativeResume;
+ if (nativeHistoryResume || nativeRelocation?.nativeId) vendorOptions._cindyRequireNativeResume = true;
+ o.vendorOptions = vendorOptions;
session = await maker.createSession(o);
if (nativeRelocation?.nativeId && session.sdkSessionId !== nativeRelocation.nativeId) {
const opened = session;
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 5e6bd32966..b39694edea 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -623,6 +623,18 @@ export async function relocateForFreshStart(
try {
boundaryId = await deps.insertBoundaryMessage(sessionId, boundaryContent);
} catch (err) {
+ if (nativeId) {
+ // A native copy cannot be published without the boundary needed for an
+ // atomic fallback. Abort before opening it and retain the source identity.
+ assertCurrent();
+ await deps.applyAgentSwitchToDb(sessionId, {
+ agentKind: dbKind, model, providerId: fromProviderId,
+ sdkSessionId: row.sdkSessionId, agentDeviceId: fromAgentDeviceId,
+ });
+ assertCurrent();
+ deps.setSessionProvider(sessionId, fromProviderId);
+ throw err;
+ }
deps.log.warn('agent-switch: boundary message insert failed on fresh-start relocation (degraded)', {
sessionId,
err: err instanceof Error ? err.message : String(err),
diff --git a/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts b/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts
index 10723daf36..644cd294ea 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts
@@ -51,6 +51,33 @@ describe('native history transfer', () => {
expect(h.restore).not.toHaveBeenCalled();
});
+ it('counts exports still being created and releases capacity after failed creation', async () => {
+ const h = setup();
+ await fs.writeFile(h.sourceFile, h.bytes);
+ let entered = 0;
+ let allEntered!: () => void;
+ let release!: () => void;
+ const pending = new Promise<void>(resolve => { release = resolve; });
+ const ready = new Promise<void>(resolve => { allEntered = resolve; });
+ const endpoint = createNativeHistoryTransfer(path.join(root, 'concurrent'), {
+ locate: async () => {
+ if (++entered === 16) allEntered();
+ await pending;
+ throw new Error('snapshot failed');
+ },
+ restore: h.restore,
+ });
+ const attempts = Array.from({ length: 16 }, () => endpoint('scope', { action: 'export', kind: 'codex', nativeId }, root, () => {}));
+ const settled = Promise.allSettled(attempts);
+ try {
+ await ready;
+ await expect(endpoint('scope', { action: 'import', manifest: h.manifest }, root, () => {})).rejects.toThrow('REMOTE_AGENT_BUSY');
+ } finally { release(); }
+ expect((await settled).every(result => result.status === 'rejected')).toBe(true);
+ const receipts = await Promise.all(Array.from({ length: 16 }, () => endpoint('scope', { action: 'import', manifest: h.manifest }, root, () => {}))) as Array<{ id: string }>;
+ await Promise.all(receipts.map(({ id }) => endpoint('scope', { action: 'release', id }, root, () => {})));
+ });
+
it('binds handles to the original task and owner generation', async () => {
const h = setup();
let current = true;
diff --git a/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts b/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts
index 51654bc723..c727e78a2b 100644
--- a/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts
+++ b/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts
@@ -94,6 +94,7 @@ export interface NativeHistoryStorage {
/** Transfer handles are bound to the owner generation, device and task by the caller. */
export function createNativeHistoryTransfer(root: string, storage: NativeHistoryStorage) {
+ let creating = 0;
const transfers = new Map<string, {
scope: string; file: string; manifest: NativeHistoryManifest; direction: 'export' | 'import';
offset: number; touched: number; busy: boolean; assertOwner: () => void;
@@ -122,12 +123,14 @@ export function createNativeHistoryTransfer(root: string, storage: NativeHistory
if (!entry.busy && Date.now() - entry.touched > TTL_MS) await remove(id);
}
if (command.action === 'export' || command.action === 'import') {
- if (transfers.size >= 16) throw new Error('REMOTE_AGENT_BUSY');
- await fs.mkdir(root, { recursive: true, mode: 0o700 });
- const id = randomUUID();
- const dir = await fs.mkdtemp(path.join(root, 'history-'));
- const file = path.join(dir, 'history.jsonl');
+ if (transfers.size + creating >= 16) throw new Error('REMOTE_AGENT_BUSY');
+ creating += 1;
+ let dir: string | undefined;
try {
+ const id = randomUUID();
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
+ dir = await fs.mkdtemp(path.join(root, 'history-'));
+ const file = path.join(dir, 'history.jsonl');
let manifest: NativeHistoryManifest;
if (command.action === 'export') {
const source = await storage.locate(command.kind, command.nativeId);
@@ -148,8 +151,10 @@ export function createNativeHistoryTransfer(root: string, storage: NativeHistory
renew(id);
return { id, manifest };
} catch (error) {
- await fs.rm(dir, { recursive: true, force: true });
+ if (dir) await fs.rm(dir, { recursive: true, force: true });
throw error;
+ } finally {
+ creating -= 1;
}
}
const entry = transfers.get(command.id);
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7a755463e7..224660c102 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -8,6 +8,9 @@
每段至多 512 KiB,顺序与 SHA-256 完整性校验通过才导入;原生 ID 重新生成,源记录不修改。
Pi 只改写副本首行的 session ID 与 cwd,使其指向接收端工作目录;消息、工具结果、分支与压缩记录保持原字节。
临时转录放 userData/native-history-transfers 的私有目录,结束后清理,空闲 10 分钟回收。
+16 个传输的上限同时计算创建中的快照,创建失败释放名额。Claude 原生迁移通过已有 vendorOptions 传递内部
+`_cindyRequireNativeResume`:适配器等待 CLI 的初始化握手并拒绝静默新建,恢复失败交回宿主切换事务。
+该标记覆盖手动、配额均衡与启动失败换电脑;普通 Claude 无效会话自愈保持原语义。启动迁移无法保存原子回退所需的边界时,先还原源位置与 ID,再返回失败,不打开副本。
这些命令不加入只读/断链自动重放名单。恢复失败回落已有的原子 resume fallback,不把切账号或清空历史当普通失败。
边界消息增加可选 `nativeHistory: restored | fallback`,桌面与手机在 fallback 时显示「已用摘要接续」;旧客户端忽略新增字段,
仍能读取原有 handoff/resumed。无服务端、数据库 schema、环境变量或 Mobile 原生配置变化。
diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.md
index ccfd2538c2..06bb03618f 100644
--- a/docs/product-rules/provider-groups.md
+++ b/docs/product-rules/provider-groups.md
@@ -297,6 +297,7 @@
- **同 Harness 换电脑优先接续原生记录**(2026-10-28):同账号的 Claude Code、Codex、Pi 先关闭源端会话,
复制完整原生转录(包括工具结果及原生压缩记录),以新的原生 ID 在目标电脑恢复;Cindy 任务不复制,源记录与工作目录不删除。
目标必须声明原生传输能力,记录经分段与完整性校验后才导入,启动后还要确认实际恢复的 ID。只有成功才标「已续接原任务」。
+ Claude Code 先等 CLI 初始化握手确认,不能把启动前预填的 ID 当作成功;原生恢复失败由宿主决定摘要回退,不允许适配器静默新建空会话。
上一次切换尚未注入原生会话的待发送交接也必须保留,不能用已迁移原生记录替代这部分尚未送达的上下文。
源端离线、记录缺失、旧版目标、不兼容或恢复失败时使用有界 handoff,并标「已用摘要接续」;跨 Harness 与分享中转仍走 handoff。
原生已压缩掉的内容不会凭空恢复,进程句柄等运行状态不随记录迁移。传输期间清空历史、取消发送、换账号或改选时不提交旧结果。
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts
index 1db5cb27ff..2f3d25b7e4 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts
@@ -148,6 +148,8 @@ async function startHarness(args: {
transcriptExists: boolean;
onInvalidResumeSession: StartSessionOptions['onInvalidResumeSession'];
forkSession?: boolean;
+ requireNativeResume?: boolean;
+ initialize?: (stream: ReturnType<typeof createControlledStream>) => Promise<void>;
}) {
const configDir = await makeTempDir();
const workingDir = await makeTempDir();
@@ -158,6 +160,8 @@ async function startHarness(args: {
const streams = [createControlledStream(), createControlledStream(), createControlledStream()];
const queries = streams.map(createFakeQuery);
+ const initializationResult = vi.fn(() => args.initialize?.(streams[0]) ?? Promise.resolve());
+ Object.assign(queries[0], { initializationResult });
const queryOptions: Array<Record<string, unknown>> = [];
const consumedInputs: unknown[][] = [];
sdkMock.query.mockImplementation((options: unknown) => {
@@ -188,7 +192,10 @@ async function startHarness(args: {
permissionMode: 'acceptEdits',
resumeSessionId: args.resumeSessionId,
onInvalidResumeSession: args.onInvalidResumeSession,
- vendorOptions: args.forkSession ? { forkSession: true } : undefined,
+ vendorOptions: {
+ ...(args.forkSession ? { forkSession: true } : {}),
+ ...(args.requireNativeResume ? { _cindyRequireNativeResume: true } : {}),
+ },
});
const events: AgentEvent[] = [];
const collected = (async () => {
@@ -203,6 +210,7 @@ async function startHarness(args: {
events,
collected,
debug,
+ initializationResult,
};
}
@@ -220,6 +228,45 @@ afterEach(async () => {
});
describe('Claude invalid-resume recovery', () => {
+ it('does not publish transferred history before the CLI accepts its resume', async () => {
+ let release!: () => void;
+ const handshake = new Promise<void>(resolve => { release = resolve; });
+ const initialize = vi.fn(() => handshake);
+ let published = false;
+ const starting = startHarness({ resumeSessionId: 'sdk-source', transcriptExists: true,
+ onInvalidResumeSession: vi.fn(async () => true), requireNativeResume: true, initialize })
+ .then(h => { published = true; return h; });
+ await vi.waitFor(() => expect(initialize).toHaveBeenCalledOnce());
+ expect(published).toBe(false);
+ release();
+ const h = await starting;
+ expect(h.handle.id).toBe('sdk-source');
+ await h.handle.close();
+ h.streams[0].end();
+ await h.collected;
+ });
+
+ it.each(['rejected', 'different-id'] as const)('returns a %s native resume to the host without a fresh retry', async failure => {
+ const onInvalidResumeSession = vi.fn(async () => true);
+ await expect(startHarness({ resumeSessionId: 'sdk-source', transcriptExists: true,
+ onInvalidResumeSession, requireNativeResume: true,
+ initialize: async stream => {
+ if (failure === 'rejected') {
+ const error = new Error('No conversation found with session ID: sdk-source');
+ stream.fail(error);
+ await Promise.resolve();
+ throw error;
+ }
+ stream.emit({ type: 'system', subtype: 'init', session_id: 'fresh-empty' });
+ await Promise.resolve();
+ await Promise.resolve();
+ },
+ })).rejects.toThrow(failure === 'rejected' ? 'No conversation found' : 'Native history resume');
+ expect(onInvalidResumeSession).not.toHaveBeenCalled();
+ expect(sdkMock.query).toHaveBeenCalledOnce();
+ expect(sdkMock.query.mock.calls[0][0].options.abortController.signal.aborted).toBe(true);
+ });
+
it('binds a new native session before SDK init so its first request can resolve the provider', async () => {
const h = await startHarness({ transcriptExists: false, onInvalidResumeSession: undefined });
const sessionId = h.queryOptions[0].sessionId;
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 303346306a..79c9924857 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1740,6 +1740,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// 再开后 Lead 工具仍指向第一次的 workflow / worker"的 bug。必须用 Object.assign
// 原地改, 让所有持有这个 ref 的闭包共享同一份最新状态。
const vo: Record<string, unknown> = { ...(opts.vendorOptions ?? {}) };
+ const requireNativeResume = vo._cindyRequireNativeResume === true && !!opts.resumeSessionId;
log.info('startSession', {
model: sdkModel,
@@ -6024,7 +6025,10 @@ export class ClaudeCodeAgent extends BaseAgent {
expectedResumeSessionId: string,
source: 'transcript_preflight' | 'sdk_runtime',
): Promise<boolean> {
- if (resumeRecoveryAttempted || !opts.onInvalidResumeSession) return false;
+ // Transferred history belongs to the host switch transaction. It must
+ // choose/confirm fallback; the adapter cannot silently erase that history.
+ if ((requireNativeResume && resumeValidationPending)
+ || resumeRecoveryAttempted || !opts.onInvalidResumeSession) return false;
try {
const cleared = await opts.onInvalidResumeSession(expectedResumeSessionId);
if (!cleared) {
@@ -7927,6 +7931,19 @@ export class ClaudeCodeAgent extends BaseAgent {
},
};
+ if (requireNativeResume) {
+ try {
+ // query() returns before resume is checked; the CLI rejects a bad resume
+ // through initializationResult(), even with no user turn dispatched.
+ await q.initializationResult();
+ if (closed || sdkSessionId !== opts.resumeSessionId) {
+ throw new Error('Native history resume did not restore the transferred session');
+ }
+ } catch (error) {
+ await handle.close();
+ throw error;
+ }
+ }
return handle;
}