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。

feat(agent): preserve native sessions when moving between computers

Dash49aa67ecc1bb
diff --git a/apps/desktop/scripts/fixtures/agent-relocation/agent-relocation-fixture.tsx b/apps/desktop/scripts/fixtures/agent-relocation/agent-relocation-fixture.tsx
new file mode 100644
index 0000000000..7ef17f3b74
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/agent-relocation/agent-relocation-fixture.tsx
@@ -0,0 +1,15 @@
+import { mountPage } from '../../ui-page/harness';
+import { SystemCard } from '../../../src/renderer/components/chat/SystemCard';
+
+mountPage({
+ render: ctx => (
+ <main className="p-4">
+ <SystemCard cardType="agent-switch" data={{
+ fromAgentKind: 'codex', toAgentKind: 'codex', toModel: 'gpt-6-astra',
+ fromAgentDeviceId: null, toAgentDeviceId: 'mini', toAgentDeviceName: 'Mac mini',
+ resumed: !ctx.data.fallback, nativeHistory: ctx.data.fallback ? 'fallback' : 'restored',
+ handoff: ctx.data.fallback ? 'Earlier requirements and latest tool outcome.' : 'Native history restored; continue with the current environment.',
+ }} />
+ </main>
+ ),
+});
diff --git a/apps/desktop/scripts/fixtures/agent-relocation/ui-page.mjs b/apps/desktop/scripts/fixtures/agent-relocation/ui-page.mjs
new file mode 100644
index 0000000000..2582632acd
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/agent-relocation/ui-page.mjs
@@ -0,0 +1,26 @@
+import assert from 'node:assert/strict';
+export default {
+ name: 'agent-relocation',
+ entry: './agent-relocation-fixture.tsx',
+ viewport: { width: 680, height: 340 },
+ real: 'SystemCard agent-switch branch and localized native-resume / summary-fallback badges',
+ notCovered: 'Actual device transport, Harness startup and native mobile rendering. Uses fixture history.',
+ stubs: {
+ 'src/renderer/features/bots/useRemoteBots': 'export const useRemoteBots = () => [];',
+ 'src/renderer/features/bots/BotCollaborationCard': 'export const BotTaskCard = () => null; export const BotSessionTaskCard = () => null; export const BotSessionTaskMessageTrace = () => null;',
+ 'src/renderer/features/learn/LearnStatusCard': 'export const LearnStatusCard = () => null;',
+ },
+ cases: {
+ default: { about: 'Native history resumed on the target computer' },
+ fallback: { about: 'Explicit summary fallback', data: { fallback: true } },
+ narrow: { about: 'Summary badge at 320px', data: { fallback: true }, viewport: { width: 320, height: 340 } },
+ },
+ async ready(page) { await page.getByRole('separator').waitFor(); },
+ async check(page, ui) {
+ const key = ui.data.fallback ? 'fallbackBadge' : 'resumedBadge';
+ assert.equal(await page.getByText(await ui.t(`chat.systemCard.agentSwitch.${key}`), { exact: true }).count(), 1);
+ await page.getByRole('button').click();
+ await page.getByText(ui.data.fallback ? 'Earlier requirements and latest tool outcome.' : 'Native history restored; continue with the current environment.', { exact: true }).waitFor();
+ await ui.capture('expanded');
+ },
+};
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
index cd39bd125b..5e776c0ed2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
@@ -110,6 +110,21 @@ describe('extractAgentIslandPromptText', () => {
describe('buildHandoffText', () => {
const opts = { fromLabel: 'Claude Code', toLabel: 'Codex' };
+ it('retains trailing user corrections and tool outcomes within the unchanged total budget', () => {
+ const text = buildHandoffText([
+ msg('user', `Original goal\n${'background '.repeat(1000)}\nFinal correction: do not publish`),
+ { ...msg('tool_use', { toolName: 'shell', input: { command: 'test' } }), toolUseId: 'test-call' },
+ { ...msg('tool_result', `Test log\n${'log '.repeat(2000)}\nexit code 1: database fixture failed`), toolUseId: 'test-call' },
+ msg('assistant', `Investigation\n${'detail '.repeat(1000)}\nNext: fix the fixture`),
+ ], opts);
+ expect(text).toContain('Original goal');
+ expect(text).toContain('Final correction: do not publish');
+ expect(text).toContain('[Tool result id=test-call;');
+ expect(text).toContain('exit code 1: database fixture failed');
+ expect(text).toContain('Next: fix the fixture');
+ expect(text.length).toBeLessThanOrEqual(16000);
+ });
+
it('framing 包含续接指令与双引擎名,并以结束标记收尾', () => {
const text = buildHandoffText([msg('user', '第一个问题'), msg('assistant', '第一个回答')], opts);
expect(text).toContain('Claude Code');
@@ -218,7 +233,7 @@ describe('buildHandoffText', () => {
expect(text).not.toContain('[User]\n问题0');
});
- it('工具调用渲染为 name + input 摘要,tool_result/thinking 不进正文', () => {
+ it('显式省略工具结果时仅保留调用,thinking 不进正文', () => {
const text = buildHandoffText(
[
msg('user', '改一下代码'),
@@ -227,7 +242,7 @@ describe('buildHandoffText', () => {
msg('thinking', { kind: 'thinking', text: '内心戏' }),
msg('assistant', '改好了'),
],
- opts,
+ { ...opts, includeToolResults: false },
);
expect(text).toContain('[Tool] Read: {"file_path":"/a.ts"}');
expect(text).not.toContain('内心戏');
@@ -805,7 +820,7 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>
expect(text).not.toContain('== Work ledger');
});
- it('把命令与 tool_result 成败收进 ledger,不把整段 stdout 写进去', () => {
+ it('把命令与 tool_result 成败收进 ledger,同时保留有界结果与末尾退出码', () => {
const text = buildHandoffText(
[
msg('user', '跑测试'),
@@ -817,7 +832,7 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>
},
{
role: 'tool_result',
- content: `${'FAIL src/foo.test.ts\n'.repeat(40)}exit code 1`,
+ content: `${'FAIL src/foo.test.ts\n'.repeat(400)}exit code 1`,
createdAt: 1,
toolUseId: 't1',
},
@@ -827,7 +842,9 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>
expect(text).toContain('- pnpm test:unit → exit 1');
expect(text).toContain('Failed attempts:');
expect(text).toContain('src/foo.test.ts');
- expect(text).not.toContain('FAIL src/foo.test.ts\nFAIL src/foo.test.ts');
+ expect(text).toContain('[Tool result id=t1;');
+ expect(text).toContain('exit code 1');
+ expect(text).not.toContain('FAIL src/foo.test.ts\n'.repeat(100));
});
it('framing 包含「先核对工作区、以工作区为准」纪律', () => {
@@ -968,7 +985,9 @@ describe('buildHandoffText 超限收缩保住首尾', () => {
toLabel: 'Codex',
sessionId: 'sess-cap',
});
- expect(text.length).toBe(16_000); // 确实顶到上限 = 确实走了兜底分支
+ expect(text.length).toBeLessThanOrEqual(16_000);
+ expect(text).toContain('[User]\nQ24');
+ expect(text).toContain('[Assistant]\nA24');
expect(text).toContain('"session_ids":["sess-cap"]');
expect(text).toContain('"limit":10');
expect(text).toContain('"limit":20');
@@ -983,7 +1002,9 @@ describe('buildHandoffText 超限收缩保住首尾', () => {
sessionId: 'sess-cap',
reason: 'message-deletion',
});
- expect(text.length).toBe(16_000);
+ expect(text.length).toBeLessThanOrEqual(16_000);
+ expect(text).toContain('[User]\nQ24');
+ expect(text).toContain('[Assistant]\nA24');
expect(text.trimEnd().endsWith("== End of rebuild note; the user's new message follows =="))
.toBe(true);
});
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 37865910f3..eadf0e2f5c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -39,6 +39,7 @@ function makeDeps(overrides: Partial<MakerSessionAgentSwitchHandlerDeps> = {}):
} {
const calls: string[] = [];
const deps: MakerSessionAgentSwitchHandlerDeps = {
+ confirmNativeHistoryFallback: vi.fn(async () => true),
getSessionRow: vi.fn(async () => makeRow()),
getLiveSession: vi.fn(() => ({ isTurnRunning: () => false })),
closeSession: vi.fn(async () => {
@@ -81,6 +82,159 @@ const validParams = {
providerId: null,
};
+describe('same-harness native relocation', () => {
+ // Quota balancing is now automatic only while native context survives. Exercise the
+ // real switch entry: refusal after a failed resume must restore the original route.
+ it.each(['missing', 'rejected', 'silent'] as const)('asks before summary fallback after %s native history and preserves the source on refusal', async failure => {
+ let row = makeRow({ workingDir: '/project', sdkSessionId: 'source-native', agentDeviceId: null });
+ const original = { ...row };
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => ({ ...row })),
+ relocateNativeHistory: vi.fn(async () => failure === 'missing' ? null : 'transferred'),
+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => { row = { ...row, ...patch, providerId: patch.providerId ?? null }; }),
+ getLiveSession: () => ({ isTurnRunning: () => false, sdkSessionId: failure === 'silent' ? 'fresh' : row.sdkSessionId ?? undefined }),
+ bootstrapSwitchedSession: vi.fn(async () => { if (failure === 'rejected') throw new Error('cannot resume'); }),
+ confirmNativeHistoryFallback: vi.fn(async () => {
+ expect(row).toMatchObject({ sdkSessionId: original.sdkSessionId, agentDeviceId: original.agentDeviceId, providerId: original.providerId });
+ return false;
+ }),
+ });
+ await expect(performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini',
+ applyNow: true, skipBootstrap: true, providerGroupSwitchReason: 'quota-rebalance' })).rejects.toThrow('NATIVE_HISTORY_FALLBACK_DECLINED');
+ expect(deps.confirmNativeHistoryFallback).toHaveBeenCalledOnce();
+ expect(deps.insertBoundaryMessage).not.toHaveBeenCalled();
+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();
+ expect(row.sdkSessionId).toBe('source-native');
+ });
+
+ it.each([false, true])('publishes an automatic native switch without asking, or a confirmed summary (%s)', async resumeFails => {
+ let row = makeRow({ workingDir: '/project', sdkSessionId: 'source-native' });
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => ({ ...row })),
+ relocateNativeHistory: vi.fn(async () => 'transferred'),
+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => { row = { ...row, ...patch, providerId: patch.providerId ?? null }; }),
+ getLiveSession: () => ({ isTurnRunning: () => false, sdkSessionId: row.sdkSessionId ?? undefined }),
+ bootstrapSwitchedSession: vi.fn(async () => { if (resumeFails) throw new Error('cannot resume'); }),
+ });
+ await performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini',
+ applyNow: true, skipBootstrap: true, providerGroupSwitchReason: 'quota-rebalance' });
+ expect(deps.confirmNativeHistoryFallback).toHaveBeenCalledTimes(resumeFails ? 1 : 0);
+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledOnce();
+ expect(deps.insertBoundaryMessage).toHaveBeenCalledWith('s1', expect.objectContaining({ nativeHistory: resumeFails ? 'fallback' : 'restored' }));
+ expect(row.agentDeviceId).toBe('mini');
+ expect(row.sdkSessionId).toBe(resumeFails ? null : 'transferred');
+ });
+
+ it('restores the source on cancellation during the native probe without asking', async () => {
+ let row = makeRow({ workingDir: '/project', sdkSessionId: 'source-native' });
+ const controller = new AbortController();
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => ({ ...row })),
+ relocateNativeHistory: vi.fn(async () => 'transferred'),
+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => { row = { ...row, ...patch, providerId: patch.providerId ?? null }; }),
+ bootstrapSwitchedSession: vi.fn(async () => { controller.abort(); }),
+ });
+ await expect(performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini',
+ applyNow: true, providerGroupSwitchReason: 'quota-rebalance', signal: controller.signal })).rejects.toThrow();
+ expect(row.sdkSessionId).toBe('source-native');
+ expect(row.agentDeviceId).toBeNull();
+ expect(deps.confirmNativeHistoryFallback).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['claude-code', 'cc', null, 'mini'], ['codex', 'codex', 'mini', null], ['pi', 'pi', 'mini', 'studio'],
+ ] as const)('restores %s history from %s between computers before dispatch', async (kind, dbKind, from, to) => {
+ let nativeId = 'original';
+ const row = makeRow({ agentKind: dbKind, agentDeviceId: from, workingDir: '/project', sdkSessionId: nativeId });
+ const relocateNativeHistory = vi.fn(async () => 'transferred');
+ const { deps, calls } = makeDeps({
+ getSessionRow: vi.fn(async () => row), relocateNativeHistory,
+ getLiveSession: () => ({ isTurnRunning: () => false, sdkSessionId: nativeId }),
+ applyAgentSwitchToDb: vi.fn(async (_sessionId, patch) => { calls.push('db'); nativeId = patch.sdkSessionId!; }),
+ });
+ await performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: kind, agentDeviceId: to, applyNow: true, skipBootstrap: true });
+ expect(relocateNativeHistory).toHaveBeenCalledWith(expect.objectContaining({ fromDevice: from, toDevice: to, nativeId: 'original', workingDir: '/project' }));
+ expect(vi.mocked(deps.closeSession).mock.invocationCallOrder[0]).toBeLessThan(relocateNativeHistory.mock.invocationCallOrder[0]);
+ expect(deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ sdkSessionId: 'transferred' }));
+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledOnce();
+ expect(deps.insertBoundaryMessage).toHaveBeenCalledWith('s1', expect.objectContaining({ resumed: true, handoff: expect.not.stringContaining('你好') }));
+ expect(deps.applyResumeFallbackAtomically).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])('falls back with visible handoff metadata when restore fails or silently starts fresh (%s)', async (silent) => {
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project' })),
+ relocateNativeHistory: vi.fn(async () => 'transferred'),
+ bootstrapSwitchedSession: silent ? vi.fn(async () => {}) : vi.fn().mockRejectedValueOnce(new Error('native format unavailable')).mockResolvedValue(undefined),
+ });
+ await performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini', applyNow: true });
+ expect(deps.applyResumeFallbackAtomically).toHaveBeenCalledWith('s1', 'boundary-client-1', expect.objectContaining({ resumed: false, handoff: expect.stringContaining('你好') }));
+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not commit native history after clear or cancellation during transfer', async () => {
+ let generation = 0;
+ const { deps } = makeDeps({
+ readPendingHandoffGeneration: () => generation,
+ getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project' })),
+ relocateNativeHistory: vi.fn(async input => { generation++; input.assertCurrent(); return 'transferred'; }),
+ });
+ await expect(performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini', applyNow: true })).rejects.toThrow('history changed');
+ expect(deps.applyAgentSwitchToDb).not.toHaveBeenCalled();
+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();
+ });
+
+ it('keeps context from a previous switch that has not reached the native session yet', async () => {
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project' })),
+ relocateNativeHistory: vi.fn(async () => 'transferred'),
+ peekPendingHandoff: vi.fn(async () => 'Important context waiting for the first native send'),
+ getLiveSession: () => ({ isTurnRunning: () => false, sdkSessionId: 'transferred' }),
+ });
+ await performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini', applyNow: true });
+ expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', expect.stringContaining('Important context waiting for the first native send'), undefined);
+ expect(deps.applyResumeFallbackAtomically).not.toHaveBeenCalled();
+ });
+
+ it('does not treat an account switch during transfer as an ordinary fallback', async () => {
+ let owner = 1;
+ const { deps } = makeDeps({
+ readOwnerGeneration: () => owner,
+ getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project' })),
+ relocateNativeHistory: vi.fn(async () => { owner++; throw new Error('owner changed'); }),
+ });
+ await expect(performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini', applyNow: true })).rejects.toThrow('REMOTE_AGENT_ACCOUNT_CHANGED');
+ expect(deps.applyAgentSwitchToDb).not.toHaveBeenCalled();
+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();
+ });
+
+ it('resumes native history on startup relocation and atomically falls back if opening it fails', async () => {
+ const { deps } = makeDeps({
+ getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project', agentDeviceId: 'target' })),
+ relocateNativeHistory: vi.fn(async () => 'restored-native'),
+ });
+ const result = await relocateForFreshStart(deps, { sessionId: 's1', agentDeviceId: 'target', providerId: null,
+ from: { agentDeviceId: 'source', providerId: null } });
+ expect(result.nativeId).toBe('restored-native');
+ expect(deps.relocateNativeHistory).toHaveBeenCalledWith(expect.objectContaining({ fromDevice: 'source', toDevice: 'target' }));
+ expect(deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ sdkSessionId: 'restored-native' }));
+ expect(deps.insertBoundaryMessage).toHaveBeenCalledWith('s1', expect.objectContaining({ nativeHistory: 'restored', resumed: true }));
+ await result.fallback!();
+ expect(deps.applyResumeFallbackAtomically).toHaveBeenCalledWith('s1', 'boundary-client-1', expect.objectContaining({
+ resumed: false, nativeHistory: 'fallback', handoff: expect.stringContaining('你好'),
+ }));
+ expect(deps.setPendingHandoff).toHaveBeenLastCalledWith('s1', expect.stringContaining('你好'), undefined);
+ });
+
+ it('keeps cross-harness switching on the existing handoff path', async () => {
+ const relocateNativeHistory = vi.fn();
+ const { deps } = makeDeps({ relocateNativeHistory, getSessionRow: vi.fn(async () => makeRow({ workingDir: '/project' })) });
+ await performSessionAgentSwitch(deps, { ...validParams, agentDeviceId: 'mini', applyNow: true });
+ expect(relocateNativeHistory).not.toHaveBeenCalled();
+ expect(deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ sdkSessionId: null }));
+ });
+});
+
const orcaAgents = [
{ kind: 'claude-code', dbKind: 'cc', model: 'claude-fable-5', providerId: 'anthropic' },
{ kind: 'codex', dbKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' },
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index 8f36d8581a..069098d713 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -66,7 +66,7 @@ export interface BuildHandoffOptions {
* 会话过期等不可检测场景),增量交接也保有全局工作现场,不至于失明。
*/
workStateMessages?: HandoffSourceMessage[];
- /** 图片历史恢复要保留工具结果摘要,不能把调用记录误当作已经成功执行。 */
+ /** 默认保留有界、带调用关联的文本结果;显式 false 可省略。调用记录不代表成功。 */
includeToolResults?: boolean;
/**
* 交接触发原因。message-deletion 表示同一引擎因本地消息被删除而重建原生
@@ -157,6 +157,15 @@ function truncate(text: string, cap: number): string {
return `${text.slice(0, cap)}…(truncated)`;
}
+/** Preserve both the request/setup and the final correction/outcome within the same budget. */
+function excerpt(text: string, cap: number): string {
+ if (text.length <= cap) return text;
+ const marker = '\n…(middle omitted)…\n';
+ if (cap <= marker.length) return text.slice(0, cap);
+ const head = Math.ceil((cap - marker.length) / 2);
+ return text.slice(0, head) + marker + text.slice(-(cap - marker.length - head));
+}
+
/** 折叠换行成单行(提要区用)。 */
function oneLine(text: string): string {
return text.replace(/\s+/g, ' ').trim();
@@ -489,7 +498,7 @@ function imContextForHandoff(message: HandoffSourceMessage): string[] {
}
/** 把消息流按 user 行切成轮次。首个 user 行之前的孤儿行并入首轮 detail。 */
-function splitTurns(messages: HandoffSourceMessage[], includeToolResults = false): Turn[] {
+function splitTurns(messages: HandoffSourceMessage[], includeToolResults = true): Turn[] {
const turns: Turn[] = [];
let current: Turn | null = null;
for (const msg of messages) {
@@ -516,7 +525,7 @@ function splitTurns(messages: HandoffSourceMessage[], includeToolResults = false
const groupSource = readMessageSourceGroup(parseJsonObjectString(msg.agentMeta))
? describeHandoffUserSource(msg) : null;
const label = groupSource ? `[Assistant · ${groupSource}]` : '[Assistant]';
- current.detailLines.push(`${label}\n${truncate(text, RECENT_TEXT_CAP)}`);
+ current.detailLines.push(`${label}\n${excerpt(text, RECENT_TEXT_CAP)}`);
current.lastAssistantText = groupSource ? `${label} ${text}` : text;
}
break;
@@ -531,7 +540,7 @@ function splitTurns(messages: HandoffSourceMessage[], includeToolResults = false
inputDigest = '';
}
const id = includeToolResults ? toolUseIdOf(msg, c) : '';
- current.detailLines.push(`[Tool] ${name}${id ? ` (id=${id})` : ''}${inputDigest ? `: ${truncate(inputDigest, TOOL_INPUT_CAP)}` : ''}`);
+ current.detailLines.push(`[Tool] ${name}${id ? ` (id=${id})` : ''}${inputDigest ? `: ${excerpt(inputDigest, TOOL_INPUT_CAP)}` : ''}`);
break;
}
case 'tool_result': {
@@ -543,7 +552,7 @@ function splitTurns(messages: HandoffSourceMessage[], includeToolResults = false
const text = toolResultText(c?.fullText ?? c?.output ?? c?.content ?? msg.content)
.replace(/data:image\/[\w.+-]+;base64,[A-Za-z0-9+/=]+/g, '[image omitted]');
const status = c?.isError === true ? 'failed' : 'recorded; verify outcome from result';
- current.detailLines.push(`[Tool result${id ? ` id=${id}` : ''}; ${status}]\n${truncate(text || '(no text result retained)', 1000)}`);
+ current.detailLines.push(`[Tool result${id ? ` id=${id}` : ''}; ${status}]\n${excerpt(text || '(no text result retained)', 1000)}`);
break;
}
case 'error': {
@@ -570,7 +579,7 @@ function splitTurns(messages: HandoffSourceMessage[], includeToolResults = false
function collapseDetailLines(lines: string[]): string[] {
const totalChars = lines.reduce((sum, line) => sum + line.length + 1, 0);
const normalized = totalChars > DETAIL_LINES_CHAR_BUDGET
- ? lines.map((line) => truncate(line, DETAIL_LINE_COMPACT_CAP))
+ ? lines.map((line) => excerpt(line, DETAIL_LINE_COMPACT_CAP))
: lines;
const kept = DETAIL_LINES_EDGE_CAP * 2;
if (normalized.length <= kept) return normalized;
@@ -718,7 +727,15 @@ function capPreservingTerminator(text: string, opts: BuildHandoffOptions): strin
const separator = '\n\n';
const room = HANDOFF_HARD_CAP - tail.length - separator.length;
if (room <= 0) return tail.slice(0, HANDOFF_HARD_CAP);
- return `${body.slice(0, room)}${separator}${tail}`;
+ // The latest request and outcome outrank the old ledger/index. Previously slicing the
+ // prefix could discard the entire recent conversation when the working-memory tail grew.
+ const recentAt = Math.max(body.lastIndexOf('== Recent conversation =='), body.lastIndexOf('== Conversation while you were away =='));
+ if (recentAt >= 0 && room > 1000) {
+ const prefix = excerpt(body.slice(0, recentAt).trimEnd(), Math.min(3000, Math.floor(room / 3)));
+ const recent = excerpt(body.slice(recentAt), room - prefix.length - separator.length);
+ return `${prefix}${separator}${recent}${separator}${tail}`;
+ }
+ return `${excerpt(body, room)}${separator}${tail}`;
}
function assembleHandoffText(
@@ -817,10 +834,10 @@ function assembleHandoffText(
const lines: string[] = [];
for (const t of earlier) {
if (t.userText) {
- lines.push(`- User${t.userSource ? ` · ${t.userSource}` : ''}: ${truncate(oneLine(t.userText), DIGEST_LINE_CAP)}`);
+ lines.push(`- User${t.userSource ? ` · ${t.userSource}` : ''}: ${oneLine(excerpt(oneLine(t.userText), DIGEST_LINE_CAP))}`);
}
if (t.lastAssistantText) {
- lines.push(` Reply: ${truncate(oneLine(t.lastAssistantText), DIGEST_LINE_CAP)}`);
+ lines.push(` Reply: ${oneLine(excerpt(oneLine(t.lastAssistantText), DIGEST_LINE_CAP))}`);
}
}
// 预算内保留最新的提要行,最旧的先丢
@@ -848,7 +865,7 @@ function assembleHandoffText(
for (const t of recent) {
const parts: string[] = [];
if (t.userText) {
- parts.push(`[User${t.userSource ? ` · ${t.userSource}` : ''}]\n${truncate(t.userText, RECENT_TEXT_CAP)}`);
+ parts.push(`[User${t.userSource ? ` · ${t.userSource}` : ''}]\n${excerpt(t.userText, RECENT_TEXT_CAP)}`);
}
parts.push(...collapseDetailLines(t.detailLines));
if (parts.length > 0) blocks.push(parts.join('\n'));
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 614549f0fd..202d95d50a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -71,6 +71,7 @@ import { getHostSourceDevice, getSelfDeviceId, remoteBackgroundInvoke, remoteInv
import { readDeviceProviderViews, readRemoteProviderRoute } from '../remote-agent/controller/deviceCatalog.js';
import { checkDeviceRoute } from '../remote-agent/controller/deviceRouteCheck.js';
import { cancelPendingRemoteStart } from '../remote-agent/controller/startRemote.js';
+import { createNativeHistoryRelocator } from '../remote-agent/controller/relocateNativeHistory.js';
import { forgetCredentialGrants } from '../remote-agent/executor/credentialGrants.js';
import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';
import {
@@ -8935,7 +8936,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return context;
}
- async function bootstrapSession(o: CreateOpts, assertAccess?: () => void): Promise<{
+ async function bootstrapSession(o: CreateOpts, assertAccess?: () => void, nativeHistoryResume = false): Promise<{
session: Awaited<ReturnType<typeof maker.createSession>>;
didInjectOrcaInstructions: boolean;
didInjectProjectContext: boolean;
@@ -9059,10 +9060,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!agentOnOtherDevice) await admitLocalRoute();
assertAccess?.();
let session: Awaited<ReturnType<typeof maker.createSession>> | undefined;
+ let nativeRelocation: Awaited<ReturnType<typeof relocateForFreshStart>> | undefined;
while (!session) {
try {
session = await maker.createSession(o);
+ if (nativeRelocation?.nativeId && session.sdkSessionId !== nativeRelocation.nativeId) {
+ const opened = session;
+ session = undefined;
+ await withRehydrateCloseSuppressed(opened.id, () => maker.closeSession(opened.id, 'agent-switch'));
+ throw new Error('Native history resume did not restore the transferred session');
+ }
+ nativeRelocation = undefined;
} catch (error) {
+ if (nativeRelocation?.fallback) {
+ const fallback = nativeRelocation.fallback;
+ nativeRelocation = undefined;
+ assertAccess?.();
+ await fallback();
+ o.resumeSessionId = undefined;
+ continue;
+ }
+ // 原生迁移由切换事务先处理恢复失败,避免嵌套换电脑覆盖它的边界与 SDK ID。
+ if (nativeHistoryResume) throw error;
// 供应商组刚分配的电脑没能启动 Agent(连不上、登录失效等):换组里下一台再试,
// 每台最多一次;不该换或没有下一台时照常报错。
const failedRoute = { agentDeviceId: o.agentDeviceId ?? null, providerId: o.providerId ?? null };
@@ -9080,20 +9099,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const guestRelocation = !next && o.id && o.resumeSessionId && isProviderShareAgentDeviceId(o.agentDeviceId)
&& providerGroupService?.claimGuestStartSwitch(o.id) === true;
if (!next && !guestRelocation) throw error;
- // 有原生会话要续接:会话在原来那台上,换过去先交接(全量交接 + 全新原生会话 + 分隔条),这次发送带上交接,
- // 不拿原来那台的会话 id 去别处打开(那边认不出,会悄悄开一个没有上下文的新会话)。
+ // 同 Harness 先搬原生记录;源端不可用或目标不支持时交接,绝不将旧电脑的 ID 直接用于目标端。
if (o.id && o.resumeSessionId) {
const target = next
? next.route
: { agentDeviceId: o.agentDeviceId ?? null, providerId: o.providerId ?? null };
- await relocateForFreshStart(agentSwitchDeps, {
+ nativeRelocation = await relocateForFreshStart(agentSwitchDeps, {
sessionId: o.id,
agentDeviceId: target.agentDeviceId,
providerId: target.providerId,
from: failedRoute,
+ assertCurrent: assertAccess,
...(guestRelocation ? { sharedRelocation: true } : {}),
});
- o.resumeSessionId = undefined;
+ o.resumeSessionId = nativeRelocation.nativeId ?? undefined;
if (o.vendorOptions) {
const fresh = { ...o.vendorOptions };
for (const key of ['resumeSessionAt', 'forkSession', 'threadId', 'tailTurnsToDrop']) delete fresh[key];
@@ -11056,6 +11075,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = {
+ readOwnerGeneration: () => getActiveAppSession().generation,
+ confirmNativeHistoryFallback: async (sessionId, targetDeviceId) => {
+ const label = describeAgentDevice(targetDeviceId) ?? t('sharedTask.otherDevice');
+ const result = await taskActionConfirmBridge.request(sessionId, {
+ title: t('providerGroup.rebalance.fallbackTitle').replace('{{label}}', () => label),
+ description: t('providerGroup.rebalance.fallbackDescription'),
+ action: { toolName: 'session_history_fallback', input: { computer: label }, confirmation: 'native_history_fallback' },
+ });
+ return result.confirmed;
+ },
+ peekPendingHandoff: sessionId => agentHandoffPending.peek(sessionId),
+ relocateNativeHistory: createNativeHistoryRelocator(app.getPath('userData'), remoteBackgroundInvoke),
// 换到供应商组那一项时由组选一台能用的电脑(provider-groups.md §6)。
resolveProviderGroupTarget: (sessionId, target) =>
providerGroupService ? providerGroupService.resolveSwitchTarget(sessionId, target) : Promise.resolve(null),
@@ -11084,6 +11115,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
orcaRole: sessions.orcaRole,
orcaRemoteLead: sessions.orcaRemoteLead,
sdkSessionId: sessions.sdkSessionId,
+ workingDir: sessions.workingDir,
source: sessions.source,
agentDeviceId: sessions.agentDeviceId,
})
@@ -11143,6 +11175,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
},
bootstrapSwitchedSession: async (sessionId, opts) => {
+ const ownerGeneration = getActiveAppSession().generation;
+ const assertOwner = () => {
+ if (getActiveAppSession().generation !== ownerGeneration) throw new Error('REMOTE_AGENT_ACCOUNT_CHANGED');
+ };
// 切换已提交,从 DB 行(新引擎值)重建 live session。resumeSessionId 直接取
// 行上的 sdk_session_id:切换事务在有停泊绑定时已把它落成停泊 id(Phase 2
// 切回续接),否则为 null = 全新原生会话,上下文由交接注入承接——与
@@ -11196,8 +11232,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const writableDirs = await readSessionWritableDirsFromDb(sessionId).catch(() => []);
if (writableDirs.length > 0) co.writableDirs = writableDirs;
}
+ assertOwner();
await ensureRemoteReadyForSessionStart({ createOpts: co });
- await bootstrapSession(co);
+ await bootstrapSession(co, assertOwner, opts?.nativeHistoryResume);
broadcastSessionCreated(sessionId);
},
withCloseSuppressed: withRehydrateCloseSuppressed,
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 600343219a..5e6bd32966 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -7,7 +7,7 @@
* 校验 → 查目标引擎停泊绑定(Phase 2)→ 构造交接文本(纯代码,
* agentHandoff.buildHandoffText:有停泊绑定 = 增量模式,否则全量)
* → 关旧 live session → DB 提交(agent_kind + model + provider_id + effort/fast;
- * sdk_session_id 落停泊 id 或 null)→ 插 agent_switch 边界行(交接全文持久化
+ * sdk_session_id 落迁移/停泊 id 或 null)→ 插 agent_switch 边界行(交接全文持久化
* 于此,UI 可展开)→ 登记 pending 注入 →(resume 时)立即重建新引擎 session。
*
* Phase 2(双会话停泊/切回续接):每家引擎的原生会话在离场时"停泊"——离场
@@ -29,13 +29,14 @@
* turn 进行中登记 pending 推迟到下一条消息发送时刻执行。
*
* 远程 Agent 换电脑(agentDeviceId 变化,null = 任务所在电脑):原生会话记录在原来运行 Agent
- * 的那台电脑上,换位置无法续接,即使引擎相同也按跨引擎同一流程走(全量交接 + 全新原生会话);
+ * 的那台电脑上;同引擎优先迁移原生历史并恢复,不可用时回落到有界交接;
* 目标是另一台电脑时,登记与落地前都按那台的目录校验,不留一个发送时必然失败的意图。
*/
import type { AgentKind } from '@cindy/maker-core';
import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../device-link/invoke-context.js';
import { parseOrcaRemoteLead } from '../../shared/orcaRemoteWorker.js';
+import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';
import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
import { MAKER_INVOKE } from './channels.js';
@@ -150,6 +151,19 @@ export interface AgentSwitchBoundaryContent {
* (原电脑没出问题,provider-groups.md §6.2「任务进行中换号」)。旧端忽略,照常显示「Agent 已改到 X 上运行」。
*/
switchReason?: 'quota-rebalance';
+ /** Distinguishes native relocation from a lossy fallback; absent on old boundaries. */
+ nativeHistory?: 'restored' | 'fallback';
+}
+
+const NATIVE_RELOCATION_NOTE = '[Session location changed] Your native conversation history was restored on another computer. '
+ + 'Continue the current task. Use the current environment and tools for file paths and running processes; '
+ + 'historical machine-local paths and process handles may no longer apply.';
+
+function nativeRelocationHandoff(pending: string | null | undefined): string {
+ if (!pending) return NATIVE_RELOCATION_NOTE;
+ // A previous switch may have opened a native session without sending its pending context yet.
+ // Repeated relocations reuse the same location note instead of growing a chain of notes.
+ return pending.startsWith(NATIVE_RELOCATION_NOTE) ? pending : `${NATIVE_RELOCATION_NOTE}\n\n${pending}`;
}
export interface AgentSwitchSessionRow {
@@ -163,6 +177,7 @@ export interface AgentSwitchSessionRow {
/** Execution-device Worker binding; these tasks have no local orcaRole. */
orcaRemoteLead?: string | null;
sdkSessionId: string | null;
+ workingDir?: string | null;
source?: string | null;
/** Agent 在哪台电脑运行(null / 缺省 = 任务所在电脑)。 */
agentDeviceId?: string | null;
@@ -237,7 +252,13 @@ export interface MakerSessionAgentSwitchHandlerDeps {
/** 分隔条展示用的电脑名(null = 任务所在电脑)。缺省 = 不记名称。 */
describeAgentDevice?(deviceId: string | null): string | null;
getSessionRow(sessionId: string): Promise<AgentSwitchSessionRow | null>;
- getLiveSession(sessionId: string): { isTurnRunning(): boolean } | null | undefined;
+ getLiveSession(sessionId: string): { isTurnRunning(): boolean; sdkSessionId?: string } | null | undefined;
+ readOwnerGeneration?(): number;
+ confirmNativeHistoryFallback?(sessionId: string, targetDeviceId: string | null): Promise<boolean>;
+ relocateNativeHistory?(input: {
+ sessionId: string; kind: 'claude-code' | 'codex' | 'pi'; nativeId: string; workingDir: string;
+ fromDevice: string | null; toDevice: string | null; assertCurrent(): void;
+ }): Promise<string | null>;
closeSession(sessionId: string): Promise<void>;
/** after = 停泊水位线(Phase 2 增量交接):只取严格晚于该边界行的消息。 */
listMessagesForHandoff(
@@ -302,6 +323,7 @@ export interface MakerSessionAgentSwitchHandlerDeps {
setPendingHandoff(sessionId: string, handoff: string, expectedGeneration?: number): void;
/** 读交接注册表的当前代次(在读历史之前取一次)。 */
readPendingHandoffGeneration?(sessionId: string): number;
+ peekPendingHandoff?(sessionId: string): Promise<string | null>;
/** 从 DB 行(切换已提交后的新值)重建 live session;抛错 = 引擎未就绪。 */
/** 记录用户对目标模型的思考开关选择(跨引擎切换提交后落本机偏好镜像)。 */
rememberThinkingIntent?(input: {
@@ -310,7 +332,7 @@ export interface MakerSessionAgentSwitchHandlerDeps {
model: string;
thinking: boolean;
}): void;
- bootstrapSwitchedSession(sessionId: string, opts?: { thinkingEnabled?: boolean }): Promise<void>;
+ bootstrapSwitchedSession(sessionId: string, opts?: { thinkingEnabled?: boolean; nativeHistoryResume?: boolean }): Promise<void>;
/**
* close→bootstrap 窗口的 onClose 重副作用抑制(desktop 注入
* withRehydrateCloseSuppressed)——切换的瞬态 close 绝不能触发 worktree
@@ -504,7 +526,7 @@ export async function applySetModelThenCancelAgentSwitchIntent<T>(
/**
* 打开任务时 Agent 没能启动、要换到另一个位置重新打开(供应商组启动阶段换电脑,docs/product-rules/provider-groups.md §6):
- * 原生会话在原来那个位置上,换过去不能续接,与换电脑同一套交接——全量交接 + 全新原生会话 + 分隔条。没有开着的会话
+ * 同 Harness 优先迁移原生记录;源端不可用或目标端不支持时回落有界交接。没有开着的会话
* (这次就是要打开它),也不在这里启动:调用方正在启动 Agent,按返回后的任务记录接着打开,这次发送带上交接。
* `sharedRelocation`:位置仍是同一个分享、由分享者的组换一台(分隔条不写电脑名称)。
*/
@@ -519,6 +541,10 @@ export async function relocateForFreshStart(
| 'insertBoundaryMessage'
| 'setPendingHandoff'
| 'readPendingHandoffGeneration'
+ | 'peekPendingHandoff'
+ | 'relocateNativeHistory'
+ | 'readOwnerGeneration'
+ | 'applyResumeFallbackAtomically'
| 'describeAgentDevice'
| 'log'
>,
@@ -529,8 +555,10 @@ export async function relocateForFreshStart(
/** 原来那个位置(调用方可能已把任务记录改到了目标位置);不给 = 按任务记录。 */
from?: { agentDeviceId: string | null; providerId: string | null };
sharedRelocation?: boolean;
+ assertCurrent?: () => void;
},
-): Promise<void> {
+): Promise<{ nativeId: string | null; fallback?: () => Promise<void> }> {
+ const ownerGeneration = deps.readOwnerGeneration?.();
const { sessionId, agentDeviceId, providerId } = params;
const row = await deps.getSessionRow(sessionId);
if (!row || row.status === 'deleted') throwIpcError('NOT_FOUND', `Session ${sessionId} not found`);
@@ -538,7 +566,7 @@ export async function relocateForFreshStart(
const model = row.model;
const dbKind = normalizeDbAgentKind(row.agentKind);
const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);
- const handoff = buildHandoffText(await deps.listMessagesForHandoff(sessionId), {
+ const fullHandoff = buildHandoffText(await deps.listMessagesForHandoff(sessionId), {
fromLabel: `${agentEngineLabel(dbKind)} (on a different computer)`,
toLabel: agentEngineLabel(dbKind),
sessionId,
@@ -546,11 +574,31 @@ export async function relocateForFreshStart(
});
const fromAgentDeviceId = params.from ? params.from.agentDeviceId : row.agentDeviceId ?? null;
const fromProviderId = params.from ? params.from.providerId : row.providerId;
+ const assertCurrent = () => {
+ params.assertCurrent?.();
+ if (deps.readOwnerGeneration?.() !== ownerGeneration) throw new Error('REMOTE_AGENT_ACCOUNT_CHANGED');
+ if (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration) {
+ throw new Error('Session history changed during agent relocation');
+ }
+ };
+ let nativeId: string | null = null;
+ if (!params.sharedRelocation && fromAgentDeviceId !== agentDeviceId && row.sdkSessionId && row.workingDir && deps.relocateNativeHistory) {
+ try {
+ nativeId = await deps.relocateNativeHistory({ sessionId, kind: dbToMakerAgentKind(dbKind),
+ nativeId: row.sdkSessionId, workingDir: row.workingDir, fromDevice: fromAgentDeviceId, toDevice: agentDeviceId, assertCurrent });
+ } catch (error) {
+ assertCurrent();
+ deps.log.warn('agent-switch: native history unavailable on startup relocation', { sessionId, error: String(error) });
+ }
+ }
+ assertCurrent();
+ const handoff = nativeId ? nativeRelocationHandoff(await deps.peekPendingHandoff?.(sessionId)) : fullHandoff;
+ assertCurrent();
await deps.applyAgentSwitchToDb(sessionId, {
agentKind: dbKind,
model,
providerId,
- sdkSessionId: null,
+ sdkSessionId: nativeId,
agentDeviceId,
});
deps.setSessionProvider(sessionId, providerId);
@@ -563,15 +611,17 @@ export async function relocateForFreshStart(
toProviderId: providerId,
fromSdkSessionId: row.sdkSessionId,
handoff,
- resumed: false,
+ resumed: !!nativeId,
+ nativeHistory: nativeId ? 'restored' : 'fallback',
consumed: false,
fromAgentDeviceId,
toAgentDeviceId: agentDeviceId,
fromAgentDeviceName: params.sharedRelocation ? null : deps.describeAgentDevice?.(fromAgentDeviceId) ?? null,
toAgentDeviceName: params.sharedRelocation ? null : deps.describeAgentDevice?.(agentDeviceId) ?? null,
};
+ let boundaryId: string | null = null;
try {
- await deps.insertBoundaryMessage(sessionId, boundaryContent);
+ boundaryId = await deps.insertBoundaryMessage(sessionId, boundaryContent);
} catch (err) {
deps.log.warn('agent-switch: boundary message insert failed on fresh-start relocation (degraded)', {
sessionId,
@@ -584,6 +634,14 @@ export async function relocateForFreshStart(
handoffChars: handoff.length,
agentDeviceChange: params.sharedRelocation ? 'reassigned-by-provider-group' : agentDeviceId ? 'other-device' : 'task-device',
});
+ return { nativeId, ...(nativeId ? { fallback: async () => {
+ assertCurrent();
+ if (!boundaryId) throw new Error('Cannot replace native relocation without its boundary record');
+ await deps.applyResumeFallbackAtomically(sessionId, boundaryId, {
+ ...boundaryContent, resumed: false, nativeHistory: 'fallback', handoff: fullHandoff,
+ });
+ deps.setPendingHandoff(sessionId, fullHandoff, handoffGeneration);
+ } } : {}) };
}
/** 带思考意图重建?不传时保持单参调用形状(既有调用方/断言都不受影响)。 */
@@ -591,7 +649,9 @@ function bootstrapSwitchedSessionWithThinking(
deps: MakerSessionAgentSwitchHandlerDeps,
sessionId: string,
thinkingEnabled: boolean | undefined,
+ nativeHistoryResume = false,
): Promise<void> {
+ if (nativeHistoryResume) return deps.bootstrapSwitchedSession(sessionId, { thinkingEnabled, nativeHistoryResume: true });
return thinkingEnabled === undefined
? deps.bootstrapSwitchedSession(sessionId)
: deps.bootstrapSwitchedSession(sessionId, { thinkingEnabled });
@@ -660,6 +720,7 @@ export async function performSessionAgentSwitch(
providerGroupSwitchReason?: 'quota-rebalance';
},
): Promise<SessionAgentSwitchResult> {
+ const ownerGeneration = deps.readOwnerGeneration?.();
const { sessionId, targetAgentKind, model, providerId, signal } = params;
// Pi 跨引擎重建时同样要带上思考开关意图:不传就容易落到被控端镜像/默认值,
// 与用户在意图期内刚改的开关不一致(device-link 远程场景最明显)。
@@ -747,7 +808,7 @@ export async function performSessionAgentSwitch(
const currentAgentDeviceId = row.agentDeviceId ?? null;
let targetAgentDeviceId =
requestedAgentDeviceId === undefined ? currentAgentDeviceId : requestedAgentDeviceId;
- // 换到供应商组那一项、要换电脑:交接反正要做,由组按它此刻的状态选一台能用的电脑,不直接落到组所在电脑本身
+ // 换到供应商组那一项、要换电脑:由组按它此刻的状态选一台能用的电脑,不直接落到组所在电脑本身
// (docs/product-rules/provider-groups.md §6,2026-10-11 用户反馈)。登记意图时不选,真正提交时按那一刻的状态选。
let groupResolvedToCurrentPosition = false;
let commitProviderGroupBinding: (() => Promise<void>) | undefined;
@@ -945,7 +1006,7 @@ export async function performSessionAgentSwitch(
// 交接素材与停泊绑定先于任何状态变更取得(失败不留半切换状态)。
// Phase 2:目标引擎有停泊原生会话 → resume + 增量交接(只补离开期间的进展,
// 工作状态区仍按全量历史提取);无绑定 → v1 全量交接 + 全新原生会话。
- // 换电脑时停泊的原生会话在原来那台电脑上,目标电脑接不上,一律全量交接。
+ // 换电脑不复用目标电脑旧的停泊记录;关闭当前会话后迁移最新原生历史。
const parked = deps.findParkedEngineSession && !relocating && !orcaGroupReturnRebuild
? await deps.findParkedEngineSession(sessionId, toDbKind)
: null;
@@ -999,28 +1060,116 @@ export async function performSessionAgentSwitch(
}
}
- // 停用轴:提交点重裁决(PR #744 review 第十五轮)—— parked 数据加载、handoff
- // 构建、closeSession 都是长 await,入口裁决可能已过期。此刻拒绝仍安全:DB 未写,
- // 旧会话即使已关也只是下一次发送按旧路由懒重建,不产生新的停用路由请求。
- if (deps.assertModelRouteUsable) {
+ let relocatedNativeId: string | null = null;
+ let sourceNativeId = row.sdkSessionId;
+ let nativeBootstrapReady = false;
+ const confirmSummary = params.providerGroupSwitchReason === 'quota-rebalance'
+ && relocating && fromDbKind === toDbKind && !forcedRelocation
+ && !isProviderShareAgentDeviceId(currentAgentDeviceId)
+ && !isProviderShareAgentDeviceId(targetAgentDeviceId);
+ const assertTransferCurrent = () => {
+ if (deps.readOwnerGeneration?.() !== ownerGeneration) throw new Error('REMOTE_AGENT_ACCOUNT_CHANGED');
+ throwIfAgentSwitchAborted(signal);
+ params.assertSelectionCurrent?.();
+ if (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration) {
+ throw new Error('Session history changed during agent relocation');
+ }
+ };
+ if (relocating && !forcedRelocation && fromDbKind === toDbKind && deps.relocateNativeHistory) {
+ // Close flushes the last native ID. Never snapshot the pre-close ID after a native fork/compact.
+ const fresh = await deps.getSessionRow(sessionId);
+ assertTransferCurrent();
+ if (!fresh) throw new Error('Session no longer exists');
+ sourceNativeId = fresh.sdkSessionId;
+ if (fresh.sdkSessionId && fresh.workingDir) {
+ try {
+ relocatedNativeId = await deps.relocateNativeHistory({
+ sessionId, kind: targetAgentKind, nativeId: fresh.sdkSessionId, workingDir: fresh.workingDir,
+ fromDevice: currentAgentDeviceId, toDevice: targetAgentDeviceId, assertCurrent: assertTransferCurrent,
+ });
+ } catch (error) {
+ assertTransferCurrent();
+ deps.log.warn('agent-switch: native history unavailable; using bounded handoff', {
+ sessionId, error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (relocatedNativeId) {
+ // History is already in the native session. Only explain the changed execution environment.
+ handoff = nativeRelocationHandoff(await deps.peekPendingHandoff?.(sessionId));
+ }
+ }
+ if (relocating) assertTransferCurrent();
+
+ // Revalidate before probing and after any user confirmation, which may take time.
+ const revalidateRoute = async () => {
+ if (!deps.assertModelRouteUsable) return;
const rerouteAtCommit = await deps.assertModelRouteUsable(
- targetAgentKind,
- model,
- typeof normalizedProviderId === 'string' ? normalizedProviderId : null,
- sessionId,
- requestedAgentDeviceId,
+ targetAgentKind, model, typeof normalizedProviderId === 'string' ? normalizedProviderId : null,
+ sessionId, requestedAgentDeviceId,
);
- if (rerouteAtCommit && typeof normalizedProviderId !== 'string') {
- normalizedProviderId = rerouteAtCommit;
+ if (rerouteAtCommit && typeof normalizedProviderId !== 'string') normalizedProviderId = rerouteAtCommit;
+ };
+ await revalidateRoute();
+ if (relocating) assertTransferCurrent();
+
+ if (confirmSummary) {
+ // Probe native resume before publishing a switch boundary or replacing pending
+ // context. A failed probe restores the source route before asking the user.
+ if (relocatedNativeId) {
+ await deps.applyAgentSwitchToDb(sessionId, {
+ agentKind: toDbKind, model, providerId: normalizedProviderId,
+ sdkSessionId: relocatedNativeId, agentDeviceId: targetAgentDeviceId,
+ });
+ if (normalizedProviderId !== undefined) deps.setSessionProvider(sessionId, normalizedProviderId);
+ try {
+ assertTransferCurrent();
+ await bootstrapSwitchedSessionWithThinking(deps, sessionId, thinkingEnabled, true);
+ assertTransferCurrent();
+ if (deps.getLiveSession(sessionId)?.sdkSessionId !== relocatedNativeId) {
+ throw new Error('Native history resume did not restore the transferred session');
+ }
+ nativeBootstrapReady = true;
+ } catch (error) {
+ // Cancellation must not strand the task on a failed native copy. Do not
+ // restore stale history after clear or write into a different account.
+ if (deps.readOwnerGeneration?.() !== ownerGeneration
+ || (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {
+ throw error;
+ }
+ if (deps.getLiveSession(sessionId)) await deps.closeSession(sessionId);
+ if (deps.readOwnerGeneration?.() !== ownerGeneration
+ || (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {
+ throw error;
+ }
+ await deps.applyAgentSwitchToDb(sessionId, {
+ agentKind: fromDbKind, model: row.model ?? model, providerId: row.providerId,
+ sdkSessionId: sourceNativeId, agentDeviceId: currentAgentDeviceId,
+ });
+ deps.setSessionProvider(sessionId, row.providerId);
+ assertTransferCurrent();
+ relocatedNativeId = null;
+ handoff = buildFullHandoff();
+ deps.log.warn('agent-switch: native quota relocation failed; restored source before summary confirmation', {
+ sessionId, error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (!relocatedNativeId) {
+ const confirmed = await deps.confirmNativeHistoryFallback?.(sessionId, targetAgentDeviceId);
+ assertTransferCurrent();
+ if (!confirmed) throw new Error('NATIVE_HISTORY_FALLBACK_DECLINED');
+ await revalidateRoute();
}
}
+ if (relocating) assertTransferCurrent();
// ---- commit point:此后切换生效 ----
await deps.applyAgentSwitchToDb(sessionId, {
agentKind: toDbKind,
model,
providerId: normalizedProviderId,
- sdkSessionId: parked?.sdkSessionId ?? null,
+ sdkSessionId: relocatedNativeId ?? parked?.sdkSessionId ?? null,
...(typeof params.effort === 'string' && params.effort ? { effort: params.effort } : {}),
...((typeof params.fastMode === 'boolean' || params.fastMode === 'ultrafast') ? { fastMode: params.fastMode } : {}),
// 组选回的当前位置在另一台电脑时也带上位置:提交按它判断窗口该查哪台的目录,不能拿本机目录。
@@ -1058,7 +1207,8 @@ export async function performSessionAgentSwitch(
normalizedProviderId === undefined ? row.providerId : normalizedProviderId,
fromSdkSessionId: row.sdkSessionId,
handoff,
- resumed: !!parked,
+ resumed: !!(relocatedNativeId || parked),
+ ...(relocating && fromDbKind === toDbKind ? { nativeHistory: relocatedNativeId ? 'restored' as const : 'fallback' as const } : {}),
consumed: false,
...(relocating
? {
@@ -1085,23 +1235,29 @@ export async function performSessionAgentSwitch(
let engineReady = true;
let bootstrapError: string | undefined;
- let resumed = !!parked;
+ let resumed = !!(relocatedNativeId || parked);
let retryPending = false;
// resume 模式无视 skipBootstrap:只有 eager spawn 才能确定性观测 resume 失败
// 并在同一事务内回落全量交接;交给 lazy-create 的话,失效的停泊 id 会让之后
// 每次发送反复失败且无人回落。
- if (parked || !params.skipBootstrap) {
+ if (!nativeBootstrapReady && (relocatedNativeId || parked || !params.skipBootstrap)) {
try {
- await bootstrapSwitchedSessionWithThinking(deps, sessionId, thinkingEnabled);
+ await bootstrapSwitchedSessionWithThinking(deps, sessionId, thinkingEnabled, !!relocatedNativeId);
+ if (relocating) assertTransferCurrent();
+ if (relocatedNativeId && deps.getLiveSession(sessionId)?.sdkSessionId !== relocatedNativeId) {
+ throw new Error('Native history resume did not restore the transferred session');
+ }
} catch (err) {
- if (parked) {
+ if (relocating) assertTransferCurrent();
+ if (relocatedNativeId || parked) {
+ if (relocatedNativeId && deps.getLiveSession(sessionId)) await deps.closeSession(sessionId);
// ---- resume 回落:清停泊 id → 换全量交接 → 全新原生会话重试 ----
// 停泊原生会话可能已失效(transcript 被清理、CLI 升级不兼容等),这些
// 只有 spawn 时才暴露。回落是确定性代码路径,不留半 resume 状态。
deps.log.warn('agent-switch: resume parked session failed; fallback to fresh + full handoff', {
sessionId,
targetAgentKind,
- parkedSdkSessionId: parked.sdkSessionId,
+ parkedSdkSessionId: relocatedNativeId ?? parked?.sdkSessionId,
err: err instanceof Error ? err.message : String(err),
});
resumed = false;
@@ -1110,6 +1266,7 @@ export async function performSessionAgentSwitch(
...boundaryContent,
handoff: fullHandoff,
resumed: false,
+ ...(relocatedNativeId ? { nativeHistory: 'fallback' as const } : {}),
};
let fallbackCommitted = false;
if (boundaryClientId) {
diff --git a/apps/desktop/src/main/provider-group/__tests__/service.test.ts b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
index 1d47876cfd..fc0fd47b49 100644
--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
@@ -1280,10 +1280,10 @@ describe('switching accounts between messages to balance quota', () => {
return { ...h, usage };
}
- it('offers the account to use first and moves there on the next message only after the user confirms', async () => {
+ it('automatically offers native relocation and binds the move to the next user message', async () => {
const h = paced();
expect(await h.service.rebalanceSuggestion('s1')).toMatchObject({
- kind: 'ask',
+ kind: 'auto',
memberKey: MINI.key,
quota: { usedPercent: 20, resetAtMs: 87_400_000 },
});
@@ -1357,7 +1357,7 @@ describe('switching accounts between messages to balance quota', () => {
await h.service.rebalanceDecision('s1', MINI.key, true, 'message-a');
expect(h.deps.writeAutoRebalance).toHaveBeenCalledWith('s1');
expect(await h.service.rebalanceSuggestion('s1')).toMatchObject({ kind: 'auto', memberKey: MINI.key });
- expect(await h.service.rebalanceSuggestion('s2')).toMatchObject({ kind: 'ask', memberKey: MINI.key });
+ expect(await h.service.rebalanceSuggestion('s2')).toMatchObject({ kind: 'auto', memberKey: MINI.key });
});
// §6.2:A 确认后离开而未发送,B 取消或没有提议时不能继承 A 的换号;此前只按任务 id 暂存。
diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.ts
index b1acf00072..23dedcf118 100644
--- a/apps/desktop/src/main/provider-group/service.ts
+++ b/apps/desktop/src/main/provider-group/service.ts
@@ -8,8 +8,8 @@
* 恢复:按退避最多重试 5 次,恢复了就留在原电脑继续,都不行再换。别的电脑上的组读不到(常见是任务就在组所在
* 电脑上、它自己断了)时换不了电脑,只等任务所在那台恢复。
* 3. **发送前**:已归组的任务所在那台现在不能用时,先交接到下一台,这条消息直接发到新电脑;离线时同样先等。
- * 用户自己发消息前确认过换号(电脑与手机的提示,或这个任务选过「以后自动换」)时,先换到那台再发
- * (2026-10-21 用户裁决:换号会丢一部分上下文,只在用户知情确认时换)。
+ * 用户自己发消息时,同账号换号优先自动恢复原生历史,实际需要摘要才确认;共享来源沿用确认或已记住的选择
+ * (2026-10-28 用户裁决,电脑与手机共用)。
*
* 没归过组、但正用着组那一项的老任务(建组前就在用,或运行过之后才换到组那一项)在启动 Agent 前纳入组,
* 不挪动它;当时没纳入的(一直开着、或启动时问不到组所在电脑)出错时再补上,然后照常换电脑。
@@ -1021,7 +1021,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
}
/**
- * 发送前换号(用户确认过,provider-groups.md §6.2「任务进行中换号」):任务所在那台能用,只是 `target` 的配额更该先用。
+ * 发送前换号(provider-groups.md §6.2「任务进行中换号」):任务所在那台能用,只是 `target` 的配额更该先用。
* 只试这一台,不记「这一轮试过」(原电脑没出问题,之后出错时仍可以换回来);它此刻接不了或交接失败就照常发到原电脑、
* 不报错,这台 PROVIDER_GROUP_REBALANCE_BACKOFF_MS 内不再提议。交接期间进行中行显示「正在换一台电脑继续」,
* 分隔条写明是为了先用那台的配额。
@@ -2004,7 +2004,13 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
rebalanceExclusion(source, binding.providerId, config, current),
);
if (!target) return null;
- return { kind: deps.readAutoRebalance?.(sessionId) ? 'auto' : 'ask', ...target };
+ const member = config.members.find((candidate) => candidate.key === target.memberKey);
+ const route = member ? source.routeOf(member, row.providerId) : null;
+ const ownDevices = route && !isProviderShareAgentDeviceId(row.agentDeviceId)
+ && !isProviderShareAgentDeviceId(route.agentDeviceId);
+ // Same-account relocation tries the native history first. The switch handler asks
+ // only if it would actually need a summary, including a native resume failure.
+ return { kind: ownDevices || deps.readAutoRebalance?.(sessionId) ? 'auto' : 'ask', ...target };
},
async rebalanceDecision(sessionId, memberKey, remember, clientId) {
diff --git a/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryStorage.test.ts b/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryStorage.test.ts
new file mode 100644
index 0000000000..5d91370201
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryStorage.test.ts
@@ -0,0 +1,87 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { nativeHistoryStorage } from '../nativeHistoryStorage';
+import { nativeHistoryDigest, type NativeHistoryManifest } from '../nativeHistoryTransfer';
+
+const mocks = vi.hoisted(() => ({ root: '', find: vi.fn(), dump: vi.fn(), importThread: vi.fn(), removeThread: vi.fn() }));
+vi.mock('@cindy/maker-core', () => ({ findClaudeSessionJsonl: mocks.find, sanitizeClaudeProjectKey: () => '-target-project' }));
+vi.mock('../../maker-orchestration/claudeTranscriptAnchors', () => ({ defaultClaudeConfigDirCandidates: () => [mocks.root] }));
+vi.mock('../controller/projectFiles', () => ({ claudeConfigDir: () => mocks.root }));
+vi.mock('../../maker-host/codex-thread-storage', () => ({ readCodexThreadStorageReadOnly: async () => undefined }));
+vi.mock('../../maker-host/codex-local-sessions', () => ({ dumpCodexThreadStateRows: mocks.dump, importSharedCodexThread: mocks.importThread, removeSharedCodexThread: mocks.removeThread }));
+const nativeId = '11111111-1111-4111-8111-111111111111';
+beforeEach(async () => { vi.clearAllMocks(); mocks.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-native-storage-test-')); });
+afterEach(async () => { await fs.rm(mocks.root, { recursive: true, force: true }); });
+async function fixture(kind: NativeHistoryManifest['kind'], content: string): Promise<{ file: string; manifest: NativeHistoryManifest }> {
+ const file = path.join(mocks.root, 'source.jsonl');
+ await fs.writeFile(file, content);
+ return { file, manifest: { kind, nativeId, bytes: Buffer.byteLength(content), sha256: await nativeHistoryDigest(file) } };
+}
+
+it('restores Claude messages, compaction and tool output under a new native identity without changing the source', async () => {
+ const rows = [
+ { type: 'user', sessionId: nativeId, uuid: 'user-message', message: { content: 'Keep the exact original requirements' } },
+ { type: 'system', sessionId: nativeId, subtype: 'compact_boundary', compactMetadata: { trigger: 'auto' } },
+ { type: 'user', sessionId: nativeId, message: { content: [{ type: 'tool_result', tool_use_id: 'call', content: 'ALL OUTPUT\n'.repeat(10000) }] } },
+ ];
+ const content = rows.map(row => JSON.stringify(row)).join('\n') + '\n';
+ const { file, manifest } = await fixture('claude-code', content);
+ mocks.find.mockResolvedValue(file);
+ const storage = nativeHistoryStorage(mocks.root);
+ expect(await storage.locate('claude-code', nativeId)).toEqual({ file });
+ const restored = await storage.restore(file, manifest, '/target/project', () => {});
+ expect(restored).not.toBe(nativeId);
+ const written = await fs.readFile(path.join(mocks.root, 'projects', '-target-project', `${restored}.jsonl`), 'utf8');
+ expect(written.trim().split('\n').map(line => JSON.parse(line))).toEqual(rows.map(row => ({ ...row, sessionId: restored })));
+ expect(await fs.readFile(file, 'utf8')).toBe(content);
+});
+
+it('restores all Codex rollout records and rewrites the native state identity together', async () => {
+ const content = JSON.stringify({ type: 'session_meta', payload: { id: nativeId, cwd: '/old/project' } }) + '\n'
+ + JSON.stringify({ type: 'response_item', payload: { type: 'function_call_output', call_id: 'call', output: 'full result'.repeat(2000) } }) + '\n'
+ + JSON.stringify({ type: 'compacted', payload: { message: 'native summary', replacement_history: [] } }) + '\n';
+ const { file, manifest } = await fixture('codex', content);
+ manifest.state = { threads: [{ id: nativeId }], threadDynamicTools: [{ thread_id: nativeId, name: 'tool' }], threadSpawnEdges: [] };
+ const target = path.join(mocks.root, 'codex', 'rollout.jsonl');
+ mocks.importThread.mockImplementation(async input => { await input.writeRollout(target); return { rolloutPath: target, statePresent: true }; });
+ const restored = await nativeHistoryStorage(mocks.root).restore(file, manifest, '/target/project', () => {});
+ expect(restored).not.toBe(nativeId);
+ expect(await fs.readFile(target, 'utf8')).toBe(content.replace(nativeId, restored));
+ // Real app-server thread/resume rejects noncanonical names even when the state row exists.
+ const filename = mocks.importThread.mock.calls[0][0].rolloutFilename;
+ expect(filename).toMatch(/^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[a-f0-9-]{36}\.jsonl$/);
+ expect(filename.endsWith(`-${restored}.jsonl`)).toBe(true);
+ expect(mocks.importThread).toHaveBeenCalledWith(expect.objectContaining({ threadId: restored, newCwd: '/target/project', stateRows: {
+ threads: [{ id: restored }], threadDynamicTools: [{ thread_id: restored, name: 'tool' }], threadSpawnEdges: [],
+ } }));
+ expect(await fs.readFile(file, 'utf8')).toBe(content);
+});
+
+it('relocates the Pi header while preserving history and refusing source paths outside its native home', async () => {
+ const storage = nativeHistoryStorage(mocks.root);
+ const content = '{"type":"session","id":"pi-original","cwd":"/source-only/project"}\n{"type":"compaction","summary":"kept"}\n';
+ const { file, manifest } = await fixture('pi', content);
+ await fs.mkdir(path.join(mocks.root, 'pi-agent-home'), { recursive: true });
+ await expect(storage.locate('pi', file)).rejects.toThrow('NATIVE_HISTORY_INVALID_ID');
+ const restored = await storage.restore(file, manifest, '/target/project', () => {});
+ expect(await storage.locate('pi', restored)).toEqual({ file: await fs.realpath(restored) });
+ const written = await fs.readFile(restored, 'utf8');
+ const header = JSON.parse(written.split('\n')[0]);
+ expect(header).toEqual({ type: 'session', id: expect.any(String), cwd: '/target/project' });
+ expect(header.id).not.toBe('pi-original');
+ expect(path.basename(restored)).toBe(`relocated-${header.id}.jsonl`);
+ expect(written.slice(written.indexOf('\n'))).toBe(content.slice(content.indexOf('\n')));
+ expect(await fs.readFile(file, 'utf8')).toBe(content);
+});
+
+
+it('does not claim complete Codex restoration when the native state could not be installed', async () => {
+ const { file, manifest } = await fixture('codex', '{"type":"session_meta"}\n');
+ manifest.state = { threads: [{ id: nativeId }], threadDynamicTools: [], threadSpawnEdges: [] };
+ const receipt = { rolloutPath: '/test/rollout', statePresent: false };
+ mocks.importThread.mockResolvedValue(receipt);
+ await expect(nativeHistoryStorage(mocks.root).restore(file, manifest, '/target', () => {})).rejects.toThrow('NATIVE_HISTORY_INCOMPLETE');
+ expect(mocks.removeThread).toHaveBeenCalledWith(expect.any(String), receipt);
+});
diff --git a/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts b/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts
new file mode 100644
index 0000000000..10723daf36
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/nativeHistoryTransfer.test.ts
@@ -0,0 +1,105 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createNativeHistoryTransfer, NATIVE_HISTORY_CHUNK_BYTES, transferNativeHistory, type NativeHistoryManifest } from '../nativeHistoryTransfer';
+import { createRemoteAgentHost } from '../host/runHost';
+
+const nativeId = '11111111-1111-4111-8111-111111111111';
+let root: string;
+beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-native-history-test-')); });
+afterEach(async () => { await fs.rm(root, { recursive: true, force: true }); });
+
+function setup(bytes = Buffer.from('native tool results, compacted context and reasoning')) {
+ const sourceFile = path.join(root, 'source.jsonl');
+ const targetFile = path.join(root, 'restored.jsonl');
+ const restore = vi.fn(async (file: string, _manifest: NativeHistoryManifest, _cwd: string, assertCurrent: () => void) => {
+ assertCurrent();
+ await fs.copyFile(file, targetFile);
+ return '22222222-2222-4222-8222-222222222222';
+ });
+ const storage = { locate: async () => ({ file: sourceFile }), restore };
+ const source = createNativeHistoryTransfer(path.join(root, 'source-staging'), storage);
+ const target = createNativeHistoryTransfer(path.join(root, 'target-staging'), storage);
+ const manifest: NativeHistoryManifest = { kind: 'codex', nativeId, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
+ return { bytes, sourceFile, targetFile, source, target, restore, manifest };
+}
+
+describe('native history transfer', () => {
+ it('streams every byte across multiple chunks, keeps the source, and cleans staging', async () => {
+ const h = setup(Buffer.from('原生上下文\n'.repeat(NATIVE_HISTORY_CHUNK_BYTES / 4)));
+ await fs.writeFile(h.sourceFile, h.bytes);
+ const result = await transferNativeHistory(
+ command => h.source('owner:task', command, root, () => {}),
+ command => h.target('owner:task', command, root, () => {}), 'codex', nativeId, () => {},
+ );
+ expect(result).toBe('22222222-2222-4222-8222-222222222222');
+ expect((await fs.readFile(h.targetFile)).equals(h.bytes)).toBe(true);
+ expect((await fs.readFile(h.sourceFile)).equals(h.bytes)).toBe(true);
+ expect(await fs.readdir(path.join(root, 'source-staging'))).toEqual([]);
+ expect(await fs.readdir(path.join(root, 'target-staging'))).toEqual([]);
+ });
+
+ it('does not publish partial or corrupted history', async () => {
+ const h = setup(Buffer.from('original'));
+ const { id } = await h.target('scope', { action: 'import', manifest: h.manifest }, root, () => {}) as { id: string };
+ await expect(h.target('scope', { action: 'restore', id }, root, () => {})).rejects.toThrow('NATIVE_HISTORY_INCOMPLETE');
+ await expect(h.target('scope', { action: 'write', id, offset: 2, data: Buffer.from('bad').toString('base64') }, root, () => {})).rejects.toThrow('REMOTE_AGENT_INVALID');
+ await h.target('scope', { action: 'write', id, offset: 0, data: Buffer.from('corrupt!').toString('base64') }, root, () => {});
+ await expect(h.target('scope', { action: 'restore', id }, root, () => {})).rejects.toThrow('NATIVE_HISTORY_INCOMPLETE');
+ expect(h.restore).not.toHaveBeenCalled();
+ });
+
+ it('binds handles to the original task and owner generation', async () => {
+ const h = setup();
+ let current = true;
+ const assertOwner = () => { if (!current) throw new Error('owner changed'); };
+ const { id } = await h.target('scope', { action: 'import', manifest: h.manifest }, root, assertOwner) as { id: string };
+ await expect(h.target('other-task', { action: 'release', id }, root, () => {})).rejects.toThrow('REMOTE_AGENT_NOT_FOUND');
+ current = false;
+ await expect(h.target('scope', { action: 'restore', id }, root, () => {})).rejects.toThrow('owner changed');
+ expect(h.restore).not.toHaveBeenCalled();
+ });
+
+ it('cancellation after a chunk leaves the original intact and never restores a partial session', async () => {
+ const h = setup(Buffer.alloc(NATIVE_HISTORY_CHUNK_BYTES + 10, 97));
+ await fs.writeFile(h.sourceFile, h.bytes);
+ let cancelled = false;
+ await expect(transferNativeHistory(
+ command => h.source('scope', command, root, () => {}),
+ async command => {
+ const result = await h.target('scope', command, root, () => {});
+ if (command.action === 'write') cancelled = true;
+ return result;
+ }, 'codex', nativeId, () => { if (cancelled) throw new Error('cancelled'); },
+ )).rejects.toThrow('cancelled');
+ expect(h.restore).not.toHaveBeenCalled();
+ expect((await fs.readFile(h.sourceFile)).equals(h.bytes)).toBe(true);
+ expect(await fs.readdir(path.join(root, 'target-staging'))).toEqual([]);
+ });
+
+ it('does not let an incoming Codex manifest inject other threads', async () => {
+ const h = setup();
+ await expect(h.target('scope', { action: 'import', manifest: {
+ ...h.manifest, state: { threads: [{ id: 'another-thread' }], threadDynamicTools: [], threadSpawnEdges: [] },
+ } }, root, () => {})).rejects.toThrow('REMOTE_AGENT_INVALID');
+ });
+});
+
+it('only advertises and accepts native transfer for same-account callers', async () => {
+ const nativeHistory = vi.fn(async () => ({ ok: true }));
+ const host = createRemoteAgentHost({
+ nativeHistory, isAgentAvailable: () => true, startHosted: vi.fn(),
+ isControllerAuthorized: () => true, controllerTrust: controller => controller === 'guest' ? 'guest' : 'owner',
+ captureOwner: () => 'owner', isOwnerCurrent: () => true, runsRoot: root,
+ });
+ try {
+ expect(await host.handle('owner-device', { op: 'caps' })).toMatchObject({ nativeHistoryTransfer: true });
+ expect(await host.handle('guest', { op: 'caps' })).not.toHaveProperty('nativeHistoryTransfer');
+ await expect(host.handle('guest', { op: 'native-history', sessionId: 'task', command: { action: 'export', kind: 'codex', nativeId } })).rejects.toThrow('REMOTE_AGENT_UNSUPPORTED');
+ expect(nativeHistory).not.toHaveBeenCalled();
+ await host.handle('owner-device', { op: 'native-history', sessionId: 'task', command: { action: 'export', kind: 'codex', nativeId } });
+ expect(nativeHistory).toHaveBeenCalledOnce();
+ } finally { host.dispose(); }
+});
diff --git a/apps/desktop/src/main/remote-agent/__tests__/relocateNativeHistory.test.ts b/apps/desktop/src/main/remote-agent/__tests__/relocateNativeHistory.test.ts
new file mode 100644
index 0000000000..76d3f9d6ea
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/relocateNativeHistory.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+import { createNativeHistoryRelocator } from '../controller/relocateNativeHistory';
+
+const h = vi.hoisted(() => ({ generation: 1, caps: vi.fn(), remote: vi.fn(), transfer: vi.fn(), local: vi.fn() }));
+vi.mock('../../appSessionState', () => ({ getActiveAppSession: () => ({ generation: h.generation }) }));
+vi.mock('../nativeHistoryStorage', () => ({ nativeHistoryStorage: () => ({}) }));
+vi.mock('../nativeHistoryTransfer', () => ({ createNativeHistoryTransfer: () => h.local, transferNativeHistory: h.transfer }));
+vi.mock('../controller/runClient', () => ({
+ remoteAgentInvoker: (device: string) => async (args: unknown[]) => h.remote(device, args),
+ RemoteAgentRunClient: { caps: h.caps },
+}));
+beforeEach(() => { vi.resetAllMocks(); h.generation = 1; });
+const input = { sessionId: 'task', kind: 'codex' as const, nativeId: 'native', workingDir: '/project',
+ fromDevice: null, toDevice: 'mini', assertCurrent: () => {} };
+
+it('leaves old peers on the existing handoff path without starting a snapshot', async () => {
+ h.caps.mockResolvedValue({});
+ expect(await createNativeHistoryRelocator('/test-user-data', vi.fn())(input)).toBeNull();
+ expect(h.transfer).not.toHaveBeenCalled();
+ expect(h.local).not.toHaveBeenCalled();
+});
+
+it('requires support at both endpoints before transferring between remote computers', async () => {
+ h.caps.mockResolvedValueOnce({ nativeHistoryTransfer: true }).mockResolvedValueOnce({});
+ expect(await createNativeHistoryRelocator('/test-user-data', vi.fn())({ ...input, fromDevice: 'studio' })).toBeNull();
+ expect(h.transfer).not.toHaveBeenCalled();
+});
+
+it('routes the entire transfer through the source and target of this task', async () => {
+ h.caps.mockResolvedValue({ nativeHistoryTransfer: true });
+ h.transfer.mockImplementation(async (source, target, _kind, _id, assertCurrent) => {
+ assertCurrent();
+ await source({ action: 'export', kind: 'codex', nativeId: 'native' });
+ await target({ action: 'restore', id: 'handle' });
+ return 'restored';
+ });
+ expect(await createNativeHistoryRelocator('/test-user-data', vi.fn())({ ...input, fromDevice: 'studio' })).toBe('restored');
+ expect(h.remote.mock.calls).toEqual([
+ ['studio', [{ op: 'native-history', sessionId: 'task', command: { action: 'export', kind: 'codex', nativeId: 'native' } }]],
+ ['mini', [{ op: 'native-history', sessionId: 'task', command: { action: 'restore', id: 'handle' } }]],
+ ]);
+});
+
+it('rejects a late capability result from a previous account', async () => {
+ h.caps.mockImplementation(async () => { h.generation++; return { nativeHistoryTransfer: true }; });
+ await expect(createNativeHistoryRelocator('/test-user-data', vi.fn())(input)).rejects.toThrow('REMOTE_AGENT_ACCOUNT_CHANGED');
+ expect(h.transfer).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/remote-agent/controller/relocateNativeHistory.ts b/apps/desktop/src/main/remote-agent/controller/relocateNativeHistory.ts
new file mode 100644
index 0000000000..63ed38793f
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/controller/relocateNativeHistory.ts
@@ -0,0 +1,37 @@
+import path from 'node:path';
+import { isProviderSharePeer } from '@cindy/device-link';
+import { getActiveAppSession } from '../../appSessionState';
+import { createNativeHistoryTransfer, transferNativeHistory, type NativeHistoryEndpoint } from '../nativeHistoryTransfer';
+import { nativeHistoryStorage } from '../nativeHistoryStorage';
+import { remoteAgentInvoker, RemoteAgentRunClient } from './runClient';
+import type { DeviceAgentServiceDeps } from './service';
+
+export function createNativeHistoryRelocator(userDataDir: string, invoke: DeviceAgentServiceDeps['remoteInvoke']) {
+ const local = createNativeHistoryTransfer(path.join(userDataDir, 'native-history-transfers'), nativeHistoryStorage(userDataDir));
+ return async (input: {
+ sessionId: string; kind: 'claude-code' | 'codex' | 'pi'; nativeId: string; workingDir: string;
+ fromDevice: string | null; toDevice: string | null; assertCurrent(): void;
+ }): Promise<string | null> => {
+ // Sharing relays have different ownership and storage. They retain the existing handoff fallback.
+ if ([input.fromDevice, input.toDevice].some(device => device && isProviderSharePeer(device))) return null;
+ const owner = getActiveAppSession();
+ const assertCurrent = () => {
+ input.assertCurrent();
+ if (getActiveAppSession().generation !== owner.generation) throw new Error('REMOTE_AGENT_ACCOUNT_CHANGED');
+ };
+ const endpoint = async (device: string | null): Promise<NativeHistoryEndpoint | null> => {
+ if (!device) return command => local(`${owner.generation}:${input.sessionId}`, command, input.workingDir, assertCurrent);
+ const remote = remoteAgentInvoker(device, invoke);
+ const caps = await RemoteAgentRunClient.caps(remote);
+ assertCurrent();
+ if (!caps.nativeHistoryTransfer) return null;
+ return command => remote([{ op: 'native-history', sessionId: input.sessionId, command }]);
+ };
+ // Verify the destination before creating a potentially large source snapshot.
+ const target = await endpoint(input.toDevice);
+ if (!target) return null;
+ const source = await endpoint(input.fromDevice);
+ if (!source) return null;
+ return transferNativeHistory(source, target, input.kind, input.nativeId, assertCurrent);
+ };
+}
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index e16d8b8f5d..32468ba129 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -186,6 +186,7 @@ export interface OwnerProviderRouteBinding {
}
export interface RemoteAgentHostDeps {
+ nativeHistory?(scope: string, command: unknown, workingDir: string, assertCurrent: () => void): Promise<unknown>;
fastPolicy?(controller: string, command: import('@cindy/device-link').RemoteAgentFastPolicy): Promise<unknown>;
/** Prepare native bytes; retain recovery ownership only for receipted controllers. */
prepareImageEvent?(hostSessionId: string, event: AgentEvent, upstream: GeneratedImageUpstream | undefined, retainForRecovery: boolean): Promise<AgentEvent>;
@@ -2480,6 +2481,24 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
const request = parseRemoteAgentRequest(raw);
if (!deps.isControllerAuthorized(controller)) fail('REMOTE_AGENT_UNAVAILABLE', 'remote control is not allowed');
switch (request.op) {
+ case 'native-history': {
+ if (trustOf(controller) !== 'owner' || !deps.nativeHistory) fail('REMOTE_AGENT_UNSUPPORTED', 'native history transfer is unavailable');
+ const owner = deps.captureOwner();
+ const assertCurrent = () => {
+ if (!deps.isOwnerCurrent(owner) || !deps.isControllerAuthorized(controller) || trustOf(controller) !== 'owner') {
+ fail('REMOTE_AGENT_UNAVAILABLE', 'remote control is not allowed');
+ }
+ };
+ const hostSessionId = hostSessionIdFor(controller, request.sessionId);
+ // The controller closes the source run before requesting a snapshot. Never copy a live writer.
+ for (const run of runs.values()) {
+ if (run.controller === controller && run.hostSessionId === hostSessionId && run.closedAt === undefined) fail('REMOTE_AGENT_BUSY', 'close the running session before transferring its history');
+ }
+ const workingDir = path.join(shadowSessionRoot(controller, hostSessionId), 'fs', 'workspace', ...Array.from({ length: MAX_ANCESTOR_LEVELS }, () => 'p'));
+ const result = await deps.nativeHistory!(`${controller}:${request.sessionId}`, request.command, workingDir, assertCurrent);
+ assertCurrent();
+ return result;
+ }
case 'fast-policy':
if (!deps.fastPolicy) fail('REMOTE_AGENT_UNSUPPORTED', 'subscription Fast policy is not supported');
return deps.fastPolicy!(controller, request);
@@ -2617,6 +2636,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
maxPayloadBytes: REMOTE_AGENT_MAX_PAYLOAD_BYTES,
virtualWorkspace: true,
...(deps.forkHosted ? { nativeFork: true } : {}),
+ ...(!guest && deps.nativeHistory ? { nativeHistoryTransfer: true } : {}),
...(deps.imageArtifacts ? { imageRecovery: true, imageRecoveryRelay: true } : {}),
// 能按受邀者隔离运行(供应商级授权与出站边界都已接上),才接受组所在电脑中转过来的受邀者任务。
...(deps.providerAccess && deps.bindGuestProviderRoute ? { guestRelay: true } : {}),
diff --git a/apps/desktop/src/main/remote-agent/host/service.ts b/apps/desktop/src/main/remote-agent/host/service.ts
index ad755aa9c1..4177837353 100644
--- a/apps/desktop/src/main/remote-agent/host/service.ts
+++ b/apps/desktop/src/main/remote-agent/host/service.ts
@@ -5,6 +5,8 @@ import { readRemoteAgentLimitsState } from './limitsStore.js';
* 供应商分享的受邀者(其他账号)另按分享快照准入,只能用分享给它的那个供应商。
*/
import path from 'node:path';
+import { createNativeHistoryTransfer } from '../nativeHistoryTransfer';
+import { nativeHistoryStorage } from '../nativeHistoryStorage';
import { isProviderSharePeer, parseProviderSharePeer } from '@cindy/device-link';
import type { Maker, StartSessionOptions } from '@cindy/maker-core';
@@ -133,6 +135,7 @@ export function installRemoteAgentHost(options: { getMaker: () => Maker; userDat
log,
});
host = createRemoteAgentHost({
+ nativeHistory: createNativeHistoryTransfer(path.join(options.userDataDir, 'native-history-transfers'), nativeHistoryStorage(options.userDataDir)),
fastPolicy: receiveGroupFastPolicy,
prepareImageEvent: (sessionId, event, upstream, retainForRecovery) => prepareGeneratedImageTransport(`remote:${sessionId}`, event, { upstream, retainForRecovery, invoke: remoteBackgroundInvoke }),
imageArtifacts: async (sessionId, request) => {
diff --git a/apps/desktop/src/main/remote-agent/nativeHistoryStorage.ts b/apps/desktop/src/main/remote-agent/nativeHistoryStorage.ts
new file mode 100644
index 0000000000..d22cad18dc
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/nativeHistoryStorage.ts
@@ -0,0 +1,73 @@
+import { randomUUID } from 'node:crypto';
+import { createReadStream, promises as fs } from 'node:fs';
+import path from 'node:path';
+import { findClaudeSessionJsonl, sanitizeClaudeProjectKey } from '@cindy/maker-core';
+import { defaultClaudeConfigDirCandidates } from '../maker-orchestration/claudeTranscriptAnchors';
+import { readCodexThreadStorageReadOnly } from '../maker-host/codex-thread-storage';
+import { dumpCodexThreadStateRows, importSharedCodexThread, removeSharedCodexThread } from '../maker-host/codex-local-sessions';
+import { migrationNativeContext } from '../session-share/migrationNativeContext';
+import { writeMigratedTranscript } from '../session-share/migrationTranscriptWriter';
+import { claudeConfigDir } from './controller/projectFiles';
+import type { NativeHistoryStorage } from './nativeHistoryTransfer';
+
+/** Reuses the task-copy native writers without importing a second Cindy task or any credentials. */
+export function nativeHistoryStorage(userDataDir: string): NativeHistoryStorage {
+ return {
+ async locate(kind, nativeId) {
+ if (kind !== 'pi' && !/^[a-f0-9-]{36}$/i.test(nativeId)) throw new Error('NATIVE_HISTORY_INVALID_ID');
+ if (kind === 'claude-code') {
+ let file: string | null = null;
+ for (const dir of defaultClaudeConfigDirCandidates()) {
+ file = await findClaudeSessionJsonl(nativeId, undefined, path.join(dir, 'projects'));
+ if (file) break;
+ }
+ if (!file) throw new Error('NATIVE_HISTORY_MISSING');
+ return { file };
+ }
+ if (kind === 'codex') {
+ const storage = await readCodexThreadStorageReadOnly(nativeId);
+ const { rolloutPath, ...state } = await dumpCodexThreadStateRows(nativeId, storage);
+ if (!rolloutPath) throw new Error('NATIVE_HISTORY_MISSING');
+ return { file: rolloutPath, state };
+ }
+ // Pi resumes by absolute JSONL path. Only native history within Cindy's Pi home is transferable.
+ const root = await fs.realpath(path.join(userDataDir, 'pi-agent-home'));
+ const file = await fs.realpath(nativeId);
+ const relative = path.relative(root, file);
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative) || !file.endsWith('.jsonl')) throw new Error('NATIVE_HISTORY_INVALID_ID');
+ return { file };
+ },
+ async restore(file, manifest, workingDir, assertCurrent) {
+ const context = migrationNativeContext(randomUUID(), [manifest.nativeId]);
+ const nativeId = context.id(manifest.nativeId);
+ assertCurrent();
+ if (manifest.kind === 'codex') {
+ // Codex's paginated rollout reader requires rollout-<timestamp>-<uuid>.jsonl.
+ // A descriptive prefix such as rollout-relocated is not resumable.
+ const updatedAt = Date.now();
+ const timestamp = new Date(updatedAt).toISOString().slice(0, 19).replaceAll(':', '-');
+ const written = await importSharedCodexThread({
+ migration: true, threadId: nativeId,
+ stateRows: context.stateRows(manifest.state ?? { threads: [], threadDynamicTools: [], threadSpawnEdges: [] }),
+ rolloutBuffer: null,
+ writeRollout: target => writeMigratedTranscript(createReadStream(file), target, { context, agent: 'codex' }, assertCurrent),
+ rolloutFilename: `rollout-${timestamp}-${nativeId}.jsonl`, newCwd: workingDir, title: '', updatedAt,
+ });
+ try {
+ assertCurrent();
+ if (!written.rolloutPath || (manifest.state?.threads.length && !written.statePresent)) {
+ throw new Error('NATIVE_HISTORY_INCOMPLETE');
+ }
+ return nativeId;
+ } catch (error) { await removeSharedCodexThread(nativeId, written); throw error; }
+ }
+ const target = manifest.kind === 'claude-code'
+ ? path.join(claudeConfigDir(), 'projects', sanitizeClaudeProjectKey(workingDir), `${nativeId}.jsonl`)
+ : path.join(userDataDir, 'pi-agent-home', 'sessions', `relocated-${nativeId}.jsonl`);
+ await writeMigratedTranscript(createReadStream(file), target,
+ manifest.kind === 'claude-code' ? { context, agent: 'cc' }
+ : { agent: 'pi', sessionId: nativeId, cwd: workingDir }, assertCurrent);
+ return manifest.kind === 'pi' ? target : nativeId;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts b/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts
new file mode 100644
index 0000000000..51654bc723
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/nativeHistoryTransfer.ts
@@ -0,0 +1,225 @@
+/** Native history transport. Only the authenticated same-account host may call this API.
+ * Copies are streamed in bounded chunks; source records are never modified or removed. */
+import { createHash, randomUUID } from 'node:crypto';
+import { createReadStream, promises as fs } from 'node:fs';
+import path from 'node:path';
+
+export const NATIVE_HISTORY_CHUNK_BYTES = 512 * 1024;
+const TTL_MS = 10 * 60_000;
+type Kind = 'claude-code' | 'codex' | 'pi';
+export interface NativeHistoryManifest {
+ kind: Kind;
+ nativeId: string;
+ bytes: number;
+ sha256: string;
+ state?: {
+ threads: Array<Record<string, unknown>>;
+ threadDynamicTools: Array<Record<string, unknown>>;
+ threadSpawnEdges: Array<Record<string, unknown>>;
+ };
+}
+export type NativeHistoryCommand =
+ | { action: 'export'; kind: Kind; nativeId: string }
+ | { action: 'import'; manifest: NativeHistoryManifest }
+ | { action: 'read'; id: string; offset: number }
+ | { action: 'write'; id: string; offset: number; data: string }
+ | { action: 'restore'; id: string }
+ | { action: 'release'; id: string };
+
+function invalid(): never { throw new Error('REMOTE_AGENT_INVALID'); }
+function record(value: unknown): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) invalid();
+ return value as Record<string, unknown>;
+}
+function text(value: unknown, max = 4096): string {
+ if (typeof value !== 'string' || !value || value.length > max || value.includes('\0')) invalid();
+ return value as string;
+}
+function count(value: unknown): number {
+ if (!Number.isSafeInteger(value) || (value as number) < 0) invalid();
+ return value as number;
+}
+function kind(value: unknown): Kind {
+ if (value !== 'claude-code' && value !== 'codex' && value !== 'pi') invalid();
+ return value as Kind;
+}
+export function parseNativeHistoryManifest(value: unknown): NativeHistoryManifest {
+ const v = record(value);
+ const result: NativeHistoryManifest = {
+ kind: kind(v.kind), nativeId: text(v.nativeId), bytes: count(v.bytes), sha256: text(v.sha256, 64),
+ };
+ if (!result.bytes || !/^[a-f0-9]{64}$/.test(result.sha256)) invalid();
+ if (result.kind !== 'pi' && !/^[a-f0-9-]{36}$/i.test(result.nativeId)) invalid();
+ if (v.state !== undefined) {
+ const state = record(v.state);
+ if (result.kind !== 'codex' || JSON.stringify(state).length > 512 * 1024) invalid();
+ const rows = (value: unknown) => {
+ if (!Array.isArray(value) || value.length > 4096) invalid();
+ return (value as unknown[]).map(record);
+ };
+ result.state = { threads: rows(state.threads), threadDynamicTools: rows(state.threadDynamicTools), threadSpawnEdges: rows(state.threadSpawnEdges) };
+ if (result.state.threads.some(row => row.id !== result.nativeId)
+ || result.state.threadDynamicTools.some(row => row.thread_id !== result.nativeId)
+ || result.state.threadSpawnEdges.some(row => row.parent_thread_id !== result.nativeId && row.child_thread_id !== result.nativeId)) invalid();
+ }
+ return result;
+}
+export function parseNativeHistoryCommand(value: unknown): NativeHistoryCommand {
+ const v = record(value);
+ if (v.action === 'export') return { action: 'export', kind: kind(v.kind), nativeId: text(v.nativeId) };
+ if (v.action === 'import') return { action: 'import', manifest: parseNativeHistoryManifest(v.manifest) };
+ const id = text(v.id, 36);
+ if (!/^[a-f0-9-]{36}$/.test(id)) invalid();
+ if (v.action === 'release' || v.action === 'restore') return { action: v.action, id };
+ const offset = count(v.offset);
+ if (v.action === 'read') return { action: 'read', id, offset };
+ if (v.action === 'write') {
+ const data = text(v.data, Math.ceil(NATIVE_HISTORY_CHUNK_BYTES / 3) * 4);
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data) || Buffer.from(data, 'base64').toString('base64') !== data) invalid();
+ return { action: 'write', id, offset, data };
+ }
+ return invalid();
+}
+
+export async function nativeHistoryDigest(file: string): Promise<string> {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+export interface NativeHistoryStorage {
+ locate(kind: Kind, nativeId: string): Promise<{ file: string; state?: NativeHistoryManifest['state'] }>;
+ restore(file: string, manifest: NativeHistoryManifest, workingDir: string, assertCurrent: () => void): Promise<string>;
+}
+
+/** Transfer handles are bound to the owner generation, device and task by the caller. */
+export function createNativeHistoryTransfer(root: string, storage: NativeHistoryStorage) {
+ const transfers = new Map<string, {
+ scope: string; file: string; manifest: NativeHistoryManifest; direction: 'export' | 'import';
+ offset: number; touched: number; busy: boolean; assertOwner: () => void;
+ }>();
+ const expiry = new Map<string, ReturnType<typeof setTimeout>>();
+ const remove = async (id: string) => {
+ clearTimeout(expiry.get(id));
+ expiry.delete(id);
+ const entry = transfers.get(id);
+ transfers.delete(id);
+ if (entry) await fs.rm(path.dirname(entry.file), { recursive: true, force: true });
+ };
+ const renew = (id: string) => {
+ clearTimeout(expiry.get(id));
+ const timer = setTimeout(() => {
+ if (transfers.get(id)?.busy) renew(id);
+ else void remove(id).catch(() => {});
+ }, TTL_MS);
+ timer.unref?.();
+ expiry.set(id, timer);
+ };
+ return async (scope: string, raw: unknown, workingDir: string, assertCurrent: () => void): Promise<unknown> => {
+ const command = parseNativeHistoryCommand(raw);
+ assertCurrent();
+ for (const [id, entry] of transfers) {
+ 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');
+ try {
+ let manifest: NativeHistoryManifest;
+ if (command.action === 'export') {
+ const source = await storage.locate(command.kind, command.nativeId);
+ const before = await fs.stat(source.file);
+ if (!before.isFile()) invalid();
+ await fs.copyFile(source.file, file);
+ await fs.chmod(file, 0o600);
+ const after = await fs.stat(source.file);
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw new Error('NATIVE_HISTORY_CHANGED');
+ manifest = parseNativeHistoryManifest({ kind: command.kind, nativeId: command.nativeId,
+ bytes: before.size, sha256: await nativeHistoryDigest(file), ...(source.state ? { state: source.state } : {}) });
+ } else {
+ manifest = command.manifest;
+ await fs.writeFile(file, '', { flag: 'wx', mode: 0o600 });
+ }
+ assertCurrent();
+ transfers.set(id, { scope, file, manifest, direction: command.action, offset: 0, touched: Date.now(), busy: false, assertOwner: assertCurrent });
+ renew(id);
+ return { id, manifest };
+ } catch (error) {
+ await fs.rm(dir, { recursive: true, force: true });
+ throw error;
+ }
+ }
+ const entry = transfers.get(command.id);
+ if (!entry || entry.scope !== scope) throw new Error('REMOTE_AGENT_NOT_FOUND');
+ entry.assertOwner();
+ if (entry.busy) throw new Error('REMOTE_AGENT_BUSY');
+ entry.busy = true;
+ entry.touched = Date.now();
+ renew(command.id);
+ try {
+ if (command.action === 'release') { await remove(command.id); return { ok: true }; }
+ if (command.action === 'read') {
+ if (entry.direction !== 'export' || command.offset >= entry.manifest.bytes) invalid();
+ const handle = await fs.open(entry.file, 'r');
+ try {
+ const buffer = Buffer.alloc(Math.min(NATIVE_HISTORY_CHUNK_BYTES, entry.manifest.bytes - command.offset));
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, command.offset);
+ assertCurrent();
+ return { data: buffer.subarray(0, bytesRead).toString('base64') };
+ } finally { await handle.close(); }
+ }
+ if (entry.direction !== 'import') invalid();
+ if (command.action === 'write') {
+ const bytes = Buffer.from(command.data, 'base64');
+ if (command.offset !== entry.offset || bytes.length > NATIVE_HISTORY_CHUNK_BYTES || entry.offset + bytes.length > entry.manifest.bytes) invalid();
+ await fs.appendFile(entry.file, bytes);
+ entry.offset += bytes.length;
+ assertCurrent();
+ return { offset: entry.offset };
+ }
+ if (entry.offset !== entry.manifest.bytes || await nativeHistoryDigest(entry.file) !== entry.manifest.sha256) throw new Error('NATIVE_HISTORY_INCOMPLETE');
+ assertCurrent();
+ const nativeId = await storage.restore(entry.file, entry.manifest, workingDir, assertCurrent);
+ assertCurrent();
+ await remove(command.id);
+ return { nativeId };
+ } finally { entry.busy = false; }
+ };
+}
+
+export type NativeHistoryEndpoint = (command: NativeHistoryCommand) => Promise<unknown>;
+export async function transferNativeHistory(source: NativeHistoryEndpoint, target: NativeHistoryEndpoint,
+ kind: Kind, nativeId: string, assertCurrent: () => void): Promise<string> {
+ let exported: string | undefined;
+ let imported: string | undefined;
+ try {
+ assertCurrent();
+ const snapshot = record(await source({ action: 'export', kind, nativeId }));
+ exported = text(snapshot.id, 36);
+ const manifest = parseNativeHistoryManifest(snapshot.manifest);
+ if (manifest.kind !== kind || manifest.nativeId !== nativeId) invalid();
+ assertCurrent();
+ imported = text(record(await target({ action: 'import', manifest })).id, 36);
+ for (let offset = 0; offset < manifest.bytes;) {
+ assertCurrent();
+ const data = text(record(await source({ action: 'read', id: exported, offset })).data, Math.ceil(NATIVE_HISTORY_CHUNK_BYTES / 3) * 4);
+ const bytes = Buffer.from(data, 'base64');
+ if (!bytes.length || bytes.length > NATIVE_HISTORY_CHUNK_BYTES || offset + bytes.length > manifest.bytes) invalid();
+ const receipt = record(await target({ action: 'write', id: imported, offset, data }));
+ offset += bytes.length;
+ if (receipt.offset !== offset) invalid();
+ }
+ assertCurrent();
+ const restored = text(record(await target({ action: 'restore', id: imported })).nativeId);
+ assertCurrent();
+ return restored;
+ } finally {
+ await Promise.allSettled([
+ ...(exported ? [source({ action: 'release', id: exported })] : []),
+ ...(imported ? [target({ action: 'release', id: imported })] : []),
+ ]);
+ }
+}
diff --git a/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts b/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts
index b07f7df74f..a87c05fcf9 100644
--- a/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts
+++ b/apps/desktop/src/main/session-share/__tests__/migrationTranscriptWriter.test.ts
@@ -34,6 +34,17 @@ const samples: Record<string, string> = {
};
describe('writeMigratedTranscript', () => {
+ it.each([1, 7, 65536])('relocates only the Pi header across %i-byte chunks', async (size) => {
+ const header = { type: 'session', version: 3, id: original, timestamp: '2026-10-28T00:00:00Z', cwd: '/source-only/project' };
+ const tail = '\n' + JSON.stringify({ type: 'message', id: 'entry', parentId: null,
+ message: { role: 'toolResult', content: [{ type: 'text', text: '雪 ☃ full tool output\n'.repeat(5000) }] } })
+ + '\n{"type":"compaction","id":"compact","parentId":"entry","firstKeptEntryId":"entry","summary":"kept"}\n';
+ const target = path.join(dir, 'pi.jsonl');
+ await writeMigratedTranscript(chunked(Buffer.from(JSON.stringify(header) + tail), size), target,
+ { agent: 'pi', sessionId: 'new-native-id', cwd: '/target/project' });
+ expect(fs.readFileSync(target, 'utf8')).toBe(JSON.stringify({ ...header, id: 'new-native-id', cwd: '/target/project' }) + tail);
+ });
+
for (const [name, text] of Object.entries(samples)) {
it.each([
['cc', 1],
diff --git a/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts b/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts
index 9c208c67d6..840a4d355a 100644
--- a/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts
+++ b/apps/desktop/src/main/session-share/migrationTranscriptWriter.ts
@@ -6,10 +6,10 @@ import { pipeline } from 'node:stream/promises';
import type { migrationNativeContext } from './migrationNativeContext.js';
-export interface TranscriptRewrite {
+export type TranscriptRewrite = {
context: ReturnType<typeof migrationNativeContext>;
agent: 'cc' | 'codex';
-}
+} | { agent: 'pi'; sessionId: string; cwd: string };
const NEWLINE = Buffer.from('\n');
@@ -21,6 +21,7 @@ const NEWLINE = Buffer.from('\n');
*/
class TranscriptLines extends Transform {
private carry: Buffer[] = [];
+ private firstLine = true;
constructor(private readonly rewrite: TranscriptRewrite) {
super();
@@ -48,6 +49,20 @@ class TranscriptLines extends Transform {
private takeLine(): Buffer {
const bytes = this.carry.length === 1 ? this.carry[0] : Buffer.concat(this.carry);
this.carry = [];
+ const firstLine = this.firstLine;
+ this.firstLine = false;
+ if (this.rewrite.agent === 'pi') {
+ // Pi resumes in the header's cwd and refuses a missing source-machine directory.
+ // Relocate only the copied session header; preserve the entry tree and message bytes.
+ if (!firstLine) return bytes;
+ try {
+ const header = JSON.parse(bytes.toString('utf8'));
+ if (header?.type === 'session') {
+ return Buffer.from(JSON.stringify({ ...header, id: this.rewrite.sessionId, cwd: this.rewrite.cwd }));
+ }
+ } catch { /* Preserve malformed native history for the native reader to diagnose. */ }
+ return bytes;
+ }
const { context, agent } = this.rewrite;
if (!context.mayRewrite(bytes)) return bytes;
return Buffer.from(context.line(bytes.toString('utf8'), agent));
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts
index b8f6731ea4..09e37901e2 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts
@@ -175,6 +175,22 @@ describe('voice call history projection', () => {
});
describe('agent switch 历史投影', () => {
+ it.each(['restored', 'fallback'] as const)('重新打开任务保留换电脑信息与 %s 状态', async (nativeHistory) => {
+ const id = sid(`agent-relocation-${nativeHistory}`);
+ const relocation = {
+ nativeHistory, resumed: nativeHistory === 'restored',
+ toAgentDeviceId: 'test-macbook', toAgentDeviceName: 'Test MacBook',
+ switchReason: 'quota-rebalance',
+ };
+ transportMocks.listMessages.mockResolvedValueOnce([{
+ id: 'relocation-row', clientId: 'relocation', sessionId: id, role: 'agent_switch',
+ content: { fromAgentKind: 'codex', toAgentKind: 'codex', ...relocation }, createdAt: Date.now(),
+ }] as never);
+ makerChatStore.ensureInitialMessages(id);
+ await vi.waitFor(() => expect(makerChatStore.getSnapshot(id).historyLoaded).toBe(true));
+ expect(makerChatStore.getSnapshot(id).messages[0].systemCardData).toMatchObject(relocation);
+ });
+
it('保留 resumed=true,让桌面端显示已续接原生会话', async () => {
const id = sid('agent-switch-resumed');
transportMocks.listMessages.mockResolvedValueOnce([
@@ -204,6 +220,7 @@ describe('agent switch 历史投影', () => {
.getSnapshot(id)
.messages.find((message) => message.systemCardType === 'agent-switch');
expect(card?.systemCardData).toMatchObject({ resumed: true });
+ expect(card?.systemCardData).not.toHaveProperty('toAgentDeviceId');
});
});
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index f3eec9f885..c8a1368b0e 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -1197,10 +1197,10 @@ function AgentSwitchCard({ data, sessionId }: { data?: Record<string, unknown>;
</span>
</>
)}
- {Boolean(data?.resumed) && (
+ {(Boolean(data?.resumed) || data?.nativeHistory === 'fallback') && (
<>
<span className="opacity-50">·</span>
- <span>{t('chat.systemCard.agentSwitch.resumedBadge')}</span>
+ <span className="shrink-0 whitespace-nowrap">{t(data?.nativeHistory === 'fallback' ? 'chat.systemCard.agentSwitch.fallbackBadge' : 'chat.systemCard.agentSwitch.resumedBadge')}</span>
</>
)}
{handoff && (
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx
index c6a3a8bf17..d30032f98e 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx
@@ -105,3 +105,18 @@ describe('command card localization boundaries', () => {
.toEqual([cmdLine, spawnError, stdout, stderr]);
});
});
+
+
+it.each(SUPPORTED_LOCALES)('distinguishes a summary fallback from native resume: %s', async locale => {
+ await i18n.changeLanguage(locale);
+ const { rerender } = render(<SystemCard cardType="agent-switch" data={{
+ fromAgentKind: 'codex', toAgentKind: 'codex', toAgentDeviceId: 'mini', nativeHistory: 'fallback', resumed: false,
+ }} />);
+ expect(screen.getByText(i18n.t('chat.systemCard.agentSwitch.fallbackBadge'))).toBeTruthy();
+ expect(screen.queryByText(i18n.t('chat.systemCard.agentSwitch.resumedBadge'))).toBeNull();
+ rerender(<SystemCard cardType="agent-switch" data={{
+ fromAgentKind: 'codex', toAgentKind: 'codex', toAgentDeviceId: 'mini', nativeHistory: 'restored', resumed: true,
+ }} />);
+ expect(screen.getByText(i18n.t('chat.systemCard.agentSwitch.resumedBadge'))).toBeTruthy();
+ expect(screen.queryByText(i18n.t('chat.systemCard.agentSwitch.fallbackBadge'))).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f45b747362..a4c9b69957 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -820,6 +820,8 @@
},
"rebalance": {
"title": "Continue on {{label}}?",
+ "fallbackTitle": "Continue on {{label}} with a summary?",
+ "fallbackDescription": "The original conversation could not be fully restored. A summary may omit earlier details and tool results. Cancel to send on the original computer.",
"description": "To use every account’s quota evenly, send this message from {{label}} ({{quota}}). The last few messages and a summary carry over; older details may be lost.",
"quota": "{{left}}% left",
"quotaReset": "{{left}}% left · {{reset}}",
@@ -12561,6 +12563,7 @@
"toggleHint": "View handoff context",
"handoffTitle": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)",
"handoffTitleEnglishSource": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)",
+ "fallbackBadge": "Continued from summary",
"resumedBadge": "session resumed",
"relocatedHere": "Agent now runs on this computer",
"relocatedTo": "Agent now runs on {{device}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9b578ab7bf..c468435b96 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -810,6 +810,8 @@
},
"rebalance": {
"title": "{{label}} に切り替えて続けますか?",
+ "fallbackTitle": "要約を使って {{label}} で続けますか?",
+ "fallbackDescription": "元の会話を完全に復元できませんでした。要約では以前の詳細やツールの結果が省略される場合があります。キャンセルすると元のコンピューターで送信します。",
"description": "各アカウントのクォータを均等に使い切るため、このメッセージは {{label}} から送ることをおすすめします({{quota}})。直近数回のやり取りと要約は引き継がれますが、それより前の細部は失われることがあります。",
"quota": "残り {{left}}%",
"quotaReset": "残り {{left}}%・{{reset}}",
@@ -12516,6 +12518,7 @@
"toggleHint": "引き継ぎ内容を表示",
"handoffTitle": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",
"handoffTitleEnglishSource": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",
+ "fallbackBadge": "要約から続行",
"resumedBadge": "セッション再開",
"relocatedHere": "Agent をこのパソコンで実行するようにしました",
"relocatedTo": "Agent を {{device}} で実行するようにしました",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5e887a5d47..54e973947a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -810,6 +810,8 @@
},
"rebalance": {
"title": "{{label}}(으)로 바꿔서 계속할까요?",
+ "fallbackTitle": "요약으로 {{label}}에서 계속할까요?",
+ "fallbackDescription": "기존 대화를 완전히 복원하지 못했습니다. 요약에는 이전 세부 사항과 도구 결과가 누락될 수 있습니다. 취소하면 원래 컴퓨터에서 전송합니다.",
"description": "각 계정의 할당량을 고르게 쓰기 위해 이 메시지는 {{label}}에서 보내는 것을 권장합니다({{quota}}). 최근 몇 번의 대화와 요약은 이어지지만, 그 이전의 세부 내용은 빠질 수 있습니다.",
"quota": "{{left}}% 남음",
"quotaReset": "{{left}}% 남음 · {{reset}}",
@@ -12516,6 +12518,7 @@
"toggleHint": "인계 내용 보기",
"handoffTitle": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",
"handoffTitleEnglishSource": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",
+ "fallbackBadge": "요약으로 이어감",
"resumedBadge": "세션 재개됨",
"relocatedHere": "이제 Agent가 이 컴퓨터에서 실행됩니다",
"relocatedTo": "이제 Agent가 {{device}}에서 실행됩니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index cfb8b9aee7..8b38299cf1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -810,6 +810,8 @@
},
"rebalance": {
"title": "换到 {{label}} 继续?",
+ "fallbackTitle": "用摘要换到 {{label}} 继续?",
+ "fallbackDescription": "无法完整接续原来的对话。使用摘要继续可能遗漏早期细节和工具结果;取消则留在原电脑发送。",
"description": "为了均匀用完各账号的配额,建议这条消息换到 {{label}} 发送({{quota}})。换过去会带上最近几轮对话和摘要,更早的细节可能记不全。",
"quota": "还剩 {{left}}%",
"quotaReset": "还剩 {{left}}%,{{reset}}",
@@ -12516,6 +12518,7 @@
"toggleHint": "查看交接内容",
"handoffTitle": "交接内容——切换时发送给新引擎的上下文摘要(不计入对话记录,仅在此展示)",
"handoffTitleEnglishSource": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",
+ "fallbackBadge": "已用摘要接续",
"resumedBadge": "已续接原任务",
"relocatedHere": "Agent 已改到这台电脑上运行",
"relocatedTo": "Agent 已改到 {{device}} 上运行",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 342e1a0b53..540a7d8aa2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -810,6 +810,8 @@
},
"rebalance": {
"title": "換到 {{label}} 繼續?",
+ "fallbackTitle": "用摘要換到 {{label}} 繼續?",
+ "fallbackDescription": "無法完整接續原來的對話。使用摘要繼續可能遺漏早期細節和工具結果;取消則留在原電腦傳送。",
"description": "為了平均用完各帳號的配額,建議這則訊息換到 {{label}} 傳送({{quota}})。換過去會帶上最近幾輪對話和摘要,更早的細節可能記不全。",
"quota": "還剩 {{left}}%",
"quotaReset": "還剩 {{left}}%,{{reset}}",
@@ -12515,6 +12517,7 @@
"toggleHint": "檢視交接內容",
"handoffTitle": "交接內容——切換時傳送給新引擎的上下文摘要(不計入對話記錄,僅在此展示)",
"handoffTitleEnglishSource": "交接內容——切換時傳送給新引擎的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)",
+ "fallbackBadge": "已用摘要接續",
"resumedBadge": "已續接原任務",
"relocatedHere": "Agent 已改到這台電腦上執行",
"relocatedTo": "Agent 已改到 {{device}} 上執行",
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index 24d7480579..4caeed3420 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -533,6 +533,11 @@ export interface AgentSwitchContent {
handoff: string;
/** Phase 2:true = 目标引擎续接(resume)了自己的停泊原生会话,交接为增量模式。 */
resumed?: boolean;
+ /** Same-Harness cross-computer restoration result; omitted for legacy switches. */
+ nativeHistory?: 'restored' | 'fallback';
+ toAgentDeviceId?: string | null;
+ toAgentDeviceName?: string | null;
+ switchReason?: 'quota-rebalance';
}
export interface Message {
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 7623414089..38dff3767d 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -19472,6 +19472,13 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
toModel: typeof c.toModel === 'string' ? c.toModel : null,
handoff: typeof c.handoff === 'string' ? c.handoff : '',
resumed: c.resumed === true,
+ ...(c.nativeHistory === 'restored' || c.nativeHistory === 'fallback'
+ ? { nativeHistory: c.nativeHistory } : {}),
+ ...(c.toAgentDeviceId === null || typeof c.toAgentDeviceId === 'string'
+ ? { toAgentDeviceId: c.toAgentDeviceId } : {}),
+ ...(typeof c.toAgentDeviceName === 'string'
+ ? { toAgentDeviceName: c.toAgentDeviceName } : {}),
+ ...(c.switchReason === 'quota-rebalance' ? { switchReason: c.switchReason } : {}),
},
};
}
diff --git a/apps/desktop/src/shared/providerGroup.ts b/apps/desktop/src/shared/providerGroup.ts
index f53ef1c0d0..4df131e7af 100644
--- a/apps/desktop/src/shared/providerGroup.ts
+++ b/apps/desktop/src/shared/providerGroup.ts
@@ -155,7 +155,8 @@ export function readProviderGroupMemberQuota(value: unknown): ProviderGroupMembe
/**
* 任务进行中换号的提议(provider-groups.md §6.2「任务进行中换号」):用户自己发下一条消息前问任务所在的电脑。
- * `ask` = 弹窗问;`auto` = 这个任务选过「以后自动换」,不再问,直接确认这个提议。`label` 是要换去的那台(带账号名)。
+ * `ask` = 弹窗问;`auto` = 同账号先尝试原生接续,或任务已有自动换号偏好。原生失败由宿主单独确认摘要回退。
+ * `label` 是要换去的那台(带账号名)。旧客户端已支持 auto,无需新增协议字段。
*/
export type ProviderGroupRebalanceSuggestion =
| { kind: 'ask' | 'auto'; memberKey: string; label: string; quota: ProviderGroupMemberQuota }
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index af4df77988..8e0814af36 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -104,6 +104,7 @@
"subagentSummary": "Subagent summary",
"agentSwitchLabel": "Switched from {{from}} to {{to}}",
"agentSwitchViewHandoff": "{{label}}, view handoff",
+ "sessionFallbackPill": "Continued from summary",
"sessionResumedPill": "Resumed original session",
"handoffContentDesc": "Handoff — context summary sent to the new engine when switching (not part of the chat transcript; shown only here)",
"handoffContentDescEnglishSource": "Handoff — context summary sent to the new engine when switching (not part of the chat transcript; shown only here)",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 6c0424bf34..7202a0189e 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -104,6 +104,7 @@
"subagentSummary": "サブエージェントの要約",
"agentSwitchLabel": "{{from}} から {{to}} に切り替えました",
"agentSwitchViewHandoff": "{{label}}、引き継ぎ内容を表示",
+ "sessionFallbackPill": "要約から続行",
"sessionResumedPill": "元のセッションを再開しました",
"handoffContentDesc": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",
"handoffContentDescEnglishSource": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 4d4c4d4333..bbdabeb804 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -104,6 +104,7 @@
"subagentSummary": "하위 에이전트 요약",
"agentSwitchLabel": "{{from}}에서 {{to}}(으)로 전환됨",
"agentSwitchViewHandoff": "{{label}}, 인계 내용 보기",
+ "sessionFallbackPill": "요약으로 이어감",
"sessionResumedPill": "원래 세션을 재개함",
"handoffContentDesc": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",
"handoffContentDescEnglishSource": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index 36967e07c1..5dc16024ce 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -104,6 +104,7 @@
"subagentSummary": "Subagent 小结",
"agentSwitchLabel": "已从 {{from}} 切换到 {{to}}",
"agentSwitchViewHandoff": "{{label}},查看交接内容",
+ "sessionFallbackPill": "已用摘要接续",
"sessionResumedPill": "已续接原任务",
"handoffContentDesc": "交接内容——切换时发送给新引擎的上下文摘要(不计入对话记录,仅在此展示)",
"handoffContentDescEnglishSource": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index 1168860278..b15feee2db 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -104,6 +104,7 @@
"subagentSummary": "Subagent 小結",
"agentSwitchLabel": "已從 {{from}} 切換到 {{to}}",
"agentSwitchViewHandoff": "{{label}},檢視交接內容",
+ "sessionFallbackPill": "已用摘要接續",
"sessionResumedPill": "已續接原任務",
"handoffContentDesc": "交接內容——切換時傳送給新引擎的上下文摘要(不計入對話記錄,僅在此展示)",
"handoffContentDescEnglishSource": "交接內容——切換時傳送給新引擎的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)",
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 25d2867871..338f56c55f 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -5487,10 +5487,10 @@ function MobileAgentSwitchCard({ data }: { data?: Record<string, unknown> }) {
<Text style={styles.agentSwitchModel} numberOfLines={1}>{toModel}</Text>
</>
) : null}
- {resumed ? (
+ {resumed || data?.nativeHistory === 'fallback' ? (
<>
<Text style={styles.agentSwitchDot}>·</Text>
- <Text style={styles.agentSwitchPillText} numberOfLines={1}>{t('message.renderer.sessionResumedPill')}</Text>
+ <Text style={styles.agentSwitchPillText} numberOfLines={1}>{t(data?.nativeHistory === 'fallback' ? 'message.renderer.sessionFallbackPill' : 'message.renderer.sessionResumedPill')}</Text>
</>
) : null}
{handoff ? (
diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.ts
index a4e5fc43f6..26bb8084b4 100644
--- a/apps/mobile/src/session/systemCard.ts
+++ b/apps/mobile/src/session/systemCard.ts
@@ -241,7 +241,8 @@ function formatAgentSwitchCard(data: Record<string, unknown> | undefined): Syste
const toModel = typeof data?.toModel === 'string' ? data.toModel : '';
const rows = toModel ? [{ label: i18n.t('message.systemCard.modelLabel'), value: toModel }] : [];
// Phase 2:resumed = 目标引擎续接了自己的停泊原生会话(增量交接)。
- if (data?.resumed === true) rows.push({ label: i18n.t('message.systemCard.sessionLabel'), value: i18n.t('message.systemCard.sessionResumed') });
+ if (data?.nativeHistory === 'fallback') rows.push({ label: i18n.t('message.systemCard.sessionLabel'), value: i18n.t('message.renderer.sessionFallbackPill') });
+ else if (data?.resumed === true) rows.push({ label: i18n.t('message.systemCard.sessionLabel'), value: i18n.t('message.systemCard.sessionResumed') });
return {
title: formatAgentSwitchLocationLabel(data, (key, options) => i18n.t(key, options))
?? i18n.t('message.systemCard.agentSwitch', { from, to }),
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 7361f9cc80..8d054500b4 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -176,7 +176,8 @@ Cindy 保底压缩是**一套**交接重建流程。装得进当前约束就不
(可剥的超大内联图)或 token 预算破了,都直接交接重建。Codex 索引历史归原生运行时
所有,不再先尝试改写历史/剥图。决定函数见 `cindyContextCompression.ts`。
字节预算目前只有 Codex 能测量。工具输出不另开一档:图片恢复的交接保留受长度限制、
-带调用关联的文本结果摘要,省略图片数据;伙伴主对话及显式重启也保留这些结果,其他交接沿用原规则。
+带调用关联的文本结果摘要,省略图片数据;普通跨引擎交接也默认保留有界工具结果(调用方可显式关闭)。
+长消息与结果保留首尾,超总预算时优先保留最近请求与结果、检索指引和结束标记;仍为 16,000 字符预算,不额外调用模型。
可剥图不足一半的混合大尾巴有意不救。打开会话不触发;只在终态错误或下次发送时
由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援摘要不得依赖额外模型调用。
伙伴主对话、话题和 IM 专线与普通 Session 一样依赖原生压缩,不按空闲时长或 70%/90%
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index bd29fa8d76..7a755463e7 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1,5 +1,21 @@
# 跨端协议兼容
+## 同 Harness 换电脑接续原生记录
+
+`remote-agent` caps 增加可选 `nativeHistoryTransfer: true`,仅同账号 owner 可用;缺省、旧端或分享中转继续使用 handoff。
+同通道新增 `native-history` 操作,携带任务 ID 与 export/import/read/write/restore/release 命令。
+接收端自行决定原生目录,不接收目标路径;Pi 源路径必须在本机 Pi home 内。临时句柄绑定账号代次、控制端与任务,
+每段至多 512 KiB,顺序与 SHA-256 完整性校验通过才导入;原生 ID 重新生成,源记录不修改。
+Pi 只改写副本首行的 session ID 与 cwd,使其指向接收端工作目录;消息、工具结果、分支与压缩记录保持原字节。
+临时转录放 userData/native-history-transfers 的私有目录,结束后清理,空闲 10 分钟回收。
+这些命令不加入只读/断链自动重放名单。恢复失败回落已有的原子 resume fallback,不把切账号或清空历史当普通失败。
+边界消息增加可选 `nativeHistory: restored | fallback`,桌面与手机在 fallback 时显示「已用摘要接续」;旧客户端忽略新增字段,
+仍能读取原有 handoff/resumed。无服务端、数据库 schema、环境变量或 Mobile 原生配置变化。
+回归:`nativeHistoryTransfer.test.ts`、`nativeHistoryStorage.test.ts`、`sessionAgentSwitchHandler.test.ts`、device-link `remoteAgent.test.ts`。
+配额均衡的同账号提议复用既有 `kind: auto`,桌面与手机不弹常规换电脑确认。实际需要摘要时,宿主通过既有 permission
+确认卡(`hostOwnedConfirmation: native_history_fallback`)询问,支持同账号远控回答;取消、超时保留原电脑与原生记录。
+旧客户端已支持 auto 和通用 permission 卡;共享来源仍沿用原来的 ask/记住偏好,不自动扩大授权。
+
## 接受已保存的伙伴模型
既有 `local-db:bots:update` 可选接收 `acceptSavedModelSelectionVersion`(读取到的正整数
diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.md
index afb76e8ed7..ccfd2538c2 100644
--- a/docs/product-rules/provider-groups.md
+++ b/docs/product-rules/provider-groups.md
@@ -36,7 +36,7 @@
> 配额先比改为比「剩下的配额 ÷ 剩下的时间」,最急的先用,见 §5「配额先比」;组内电脑每行显示配额进度条(已用多少、按时间该用到哪、
> 多久后重置),数据由组所在电脑随组状态发给同账号电脑(同日用户确认),见 §10。同日还评估过「任务进行中自动换账号」:
> 换电脑的交接只带最近几轮原文与前面的摘要,会丢工具输出与推理细节,用户决定不自动换;随后改为**上一轮结束、用户发下一条消息时
-> 弹窗问要不要换号**,可以为这个任务选「以后自动换」,手机与电脑一致,见 §6.2。
+> 弹窗问要不要换号**,可以为这个任务选「以后自动换」,手机与电脑一致。此确认规则已由 2026-10-28 的原生接续裁决更新,见 §6.2。
> 2026-10-22 用户裁决(取代上一条的配额进度条):**组内电脑行不再画配额进度条**——收起时挤在一行里看不懂,又和展开后的剩余配额
> 重复,要看各账号用到哪就展开那一行。「快作废的先用、各账号平均」的排序不变;组所在电脑照常随组状态发出配额窗口,只供 §6.2
> 的换号提议使用,见 §10。
@@ -250,8 +250,8 @@
重试选电脑时清掉短缓存。账号切换后丢弃旧账号的读取结果。
- **分享边界**:不读取别人分享来的电脑的订阅配额,按未知用量处理,仍复用现有可用性与失败后换电脑;
组所在电脑为受邀者选电脑时可以使用自己组内的同账号配额,但不向受邀者返回配额。
- - 正常运行的任务不因用量差距自动迁移;新任务和需要换电脑时按此策略分配,上一轮结束后用户发下一条消息时可以在用户确认后
- 换号(§6.2)。
+ - 正在回复的任务不因用量差距迁移;新任务和需要换电脑时按此策略分配,上一轮结束后用户发下一条消息时,同账号原生接续
+ 自动换号,实际需要摘要时才确认(§6.2)。
- 已经绑定的任务在发送前由组所在电脑按本次模型重新核对额度;总窗口或该模型专属周窗口耗尽时换电脑,
OpenAI 同时核对任务框架,快照未知时不因额度判断阻塞发送。
- **冷却**:组内电脑上的任务报用量上限时,仅该任务模型进入冷却(Claude 按同一模型家族合并别名),其他模型仍可分配;
@@ -283,8 +283,8 @@
- 任务第一次在组里运行时按 §5 的组策略选定一台组内电脑,之后固定在这台:对话记录保存在那台电脑上。只有正常运行时才保持
固定;那台电脑出问题时按下面的规则**自动换电脑**,不需要用户操作。
-- 正在正常运行的任务不会因为组策略变化或其他电脑空闲而自动迁移;为配额换号只在上一轮结束、用户发下一条消息并确认后
- 进行(换电脑的交接只带最近几轮原文与前面的摘要,会丢工具输出与推理细节),见 §6.2。
+- 正在回复的任务不会因为组策略变化或其他电脑空闲而自动迁移;为配额换号只在上一轮结束、用户发下一条消息时
+ 进行;同 Harness 的同账号换电脑自动接续原生记录,无法恢复时先确认再使用有界交接,见 §6.2。
- 只给从没运行过的任务按 §5 选电脑。已经运行过、正用着组那一项的任务不按策略挪走:留在原处并纳入组,之后出问题时
照常自动换电脑(2026-10-10 用户要求:老任务也要生效)。包括:
- 建组前就在用这个供应商的任务、回退或清空后原生会话被清掉的任务;
@@ -294,14 +294,17 @@
- 纳入的时机:启动 Agent 时(问组所在电脑最多等 3 秒,问不到就照常启动);当时没纳入的(一直开着没重新启动、
或启动时问不到)在因 §6.1 的原因失败时先纳入,再照常换电脑,所以已经开着的老任务点重试也会换。
- 问组所在电脑超时只算「读不到」,不算组已删除:组所在电脑慢一点不会把已归组的任务移出组(2026-10-11)。
-- **有原生会话要续接的任务在启动阶段换电脑时先交接**(2026-10-11):会话在原来那台上,别处认不出它的会话 id,直接拿去别处打开会
- 悄悄开一个没有上下文的新会话。重新打开(重启 Cindy、会话被回收后)时原电脑不能用,由发送前检查(§6.1「发送前」)先等或带交接
- 换过去;打开时原电脑的 Agent 没能启动的,换到组里下一台之前先交接(全量交接 + 全新原生会话 + 分隔条,与运行中换电脑相同),
- 这条消息带着交接发到新电脑。没有原生会话要续接的(从没运行过、回退或清空后)直接换下一台。
+- **同 Harness 换电脑优先接续原生记录**(2026-10-28):同账号的 Claude Code、Codex、Pi 先关闭源端会话,
+ 复制完整原生转录(包括工具结果及原生压缩记录),以新的原生 ID 在目标电脑恢复;Cindy 任务不复制,源记录与工作目录不删除。
+ 目标必须声明原生传输能力,记录经分段与完整性校验后才导入,启动后还要确认实际恢复的 ID。只有成功才标「已续接原任务」。
+ 上一次切换尚未注入原生会话的待发送交接也必须保留,不能用已迁移原生记录替代这部分尚未送达的上下文。
+ 源端离线、记录缺失、旧版目标、不兼容或恢复失败时使用有界 handoff,并标「已用摘要接续」;跨 Harness 与分享中转仍走 handoff。
+ 原生已压缩掉的内容不会凭空恢复,进程句柄等运行状态不随记录迁移。传输期间清空历史、取消发送、换账号或改选时不提交旧结果。
+ 启动失败换下一台也共用此规则,不直接拿原电脑的 ID 到别处打开。没有原生记录的任务直接新建。
- 不纳入:直接选组里某台电脑或分享来的供应商的任务(用的不是组那一项,§4);因组内电脑被移出、或组被删除而解除过
这个组的任务(§9.4,任务所在的电脑按组记下,之后同一台重新加入、或重建同一个组也不纳入)。
- **在模型选择里把任务换到组那一项、要换电脑时由组选电脑**(2026-10-11 用户反馈:此前直接落到组所在电脑本身,它撞了周上限,
- 先报错才换):交接反正要做,发送这条消息、真正换过去的那一刻按组此刻的状态与组策略选一台能用的电脑(与新任务同一套),
+ 先报错才换):发送这条消息、真正换过去的那一刻按组此刻的状态与组策略选一台能用的电脑(与新任务同一套),
直接换到那台并纳入组;组里都不能用时直接提示「供应商组里的电脑现在都不能运行这个任务」,不换、不发,选择保留。选中的就是
任务此刻所在那台电脑、但用的不是组里那个供应商时,照用户选的位置换。组读不到时照用户选的位置换。
- 用户在模型选择里把任务挪到组外的电脑或换成别的供应商,任务即退出组:之后不再自动换电脑,也不把那台的失败
@@ -338,7 +341,7 @@
不拦组所在电脑自己的任务。连不上时先等原电脑恢复的规则不变。
- **还没开始运行**(打开任务、Agent 启动阶段)失败:直接换下一台,没有可感知的中断。
- **运行中失败**:把这台标为不可用(用量上限进入冷却,§5),复用现有的跨电脑交接,把任务交接到按上述规则选出的
- 下一台:新建会话并带上交接上下文,然后继续这一轮——这一轮还没有产出就重发原消息,已经有产出就发续跑指令,
+ 下一台:优先迁移原生记录,不能恢复时新建会话并带上交接上下文,然后继续这一轮——这一轮还没有产出就重发原消息,已经有产出就发续跑指令,
与 [用量上限自动继续](usage-limit-auto-continue.md) 的续跑口径一致。消息流里显示一行活动记录
「{原电脑} {原因},已换到 {新电脑} 继续」(受邀者那边写「已自动换一台电脑继续」,§8),不计为用户发送。
- **连不上先等它恢复**(2026-10-11):那台是连不上(离线、断线)时先不换:现读一次那台的状态,确实连不上才等,
@@ -405,10 +408,10 @@
- 交接失败按同一个判定:问题出在目标电脑本身(连不上、分享暂停、Agent 起不来、登录失效等)时把那台记为试过(账号的问题
才冷却),换下一台再试;任务正在运行、已被删除等与目标无关的失败直接结束本次换电脑。换过去的那台交接成功、Agent 却没能
启动时同样按换不过去处理、换下一台,不把续跑交给起不来的电脑。都不行时交回原有的报错与额度重置后自动继续。
-- **代价与告知**:每换一次电脑都是一次交接——原会话的提示缓存失效,新会话按交接上下文继续,细节可能比原会话少,
- 也会多消耗一些 token。自动换电脑默认开启,组设置里可以关掉;关掉后照现有方式报错,用户可以在模型选择里
+- **代价与告知**:同 Harness 的同账号换电脑优先保留完整原生记录;摘要接续可能遗漏细节。换电脑后提示缓存可能需要重建,
+ 因此可能多消耗 token。出问题时自动换电脑默认开启,组设置里可以关掉;关掉后照现有方式报错,用户可以在模型选择里
手动换到另一台电脑。
-- **实现**:运行中的换电脑复用「已建任务换 Agent 所在电脑」(`performSessionAgentSwitch`,全量交接 + 全新原生会话),
+- **实现**:运行中的换电脑复用「已建任务换 Agent 所在电脑」(`performSessionAgentSwitch`,优先原生恢复,失败时有界交接),
续跑复用额度重置后自动继续的同一条路径(`continueAfterUsageLimitReset`),活动记录在这条续跑记录上带
`agentSwitch`(原电脑、新电脑、原因);旧版本手机与桌面不认识该字段,显示成「用量已恢复,已自动继续」。
Agent 还没开始运行就失败(打开任务阶段)时,在启动入口直接换下一台。代码在 `apps/desktop/src/main/provider-group/`。
@@ -451,8 +454,10 @@
### 6.2 任务进行中换号
-2026-10-21 用户裁决(取代同日「任务进行中不换账号」):同一个任务里,上一轮已经结束、用户发下一条消息时也做负载均衡,
-但换号会丢一部分上下文,**必须先弹窗问用户**;用户可以为这个任务选「以后自动换,不再询问」。
+2026-10-28 用户裁决(更新 2026-10-21 的发送前确认):同一个任务里,上一轮结束、用户发下一条消息时也做负载均衡。
+**同 Harness、同账号电脑间的原生接续自动切换,不再弹常规确认**;只有实际无法恢复、需要摘要接续时再确认。
+传输成功但目标 CLI 恢复失败也属于需要确认的情况。取消或确认超时则留在原电脑发送,保留源原生历史。
+共享来源仍沿用原来的知情确认与已有「以后自动换」偏好,不扩大跨账号原生传输范围。
- **什么时候问**:用户自己在电脑或手机上发下一条消息、上一轮已经结束时,问任务所在的电脑。它按 §5 同一把尺子比较:
组里另一台电脑的配额明显更该先用才提议——两台「急不急」的差乘以那台剩下的时间(百分比)不小于 15,即重置时间相同时
@@ -460,25 +465,25 @@
未暂停、不在冷却、5 小时配额不紧(§5 第 0 条)、读得到配额;任务所在那台本身也要正常(有问题时交给 §6.1)。
- **不拖慢发送**:点发送要立刻发出、不多等一次网络往返(手机尤其如此),所以电脑与手机在任务空闲时预先问好——上一轮结束、
打开任务时问一次,空闲期间每 5 分钟再问;问到的提议 10 分钟内有效,只用于下一条消息。没问到、问不到或任务所在电脑是旧版本时
- 不弹窗,照常发送。只有真要换号时才等用户选择、等任务所在电脑记下决定再发。
+ 照常发送。只有真要换号时才等任务所在电脑记下这条消息的换号决定;原生接续不等用户选择,实际需要摘要或共享来源时才询问。
- **不问、不换**:正在回复时排队或插话的消息、定时任务的消息、IM 渠道发来的消息;手机上前面还有没发出的消息或断线时;
只能换到同一台电脑上的另一个账号时(交接只能换电脑);伙伴、共享中、目标模式管着限额等待等不由组自动换电脑的任务(与 §6.1
同一个判定)。
-- **弹窗**:写明要换去哪台(同一台电脑上有几个账号时带账号名)、那台的配额还剩多少、多久重置,以及换过去只带最近几轮对话
- 和摘要、更早的细节可能记不全。电脑上是「换过去」「取消」两个按钮加一个默认不勾的复选框「以后自动换,不再询问(仅本任务)」;
+- **原生接续**:宿主先复制并验证原生恢复,成功后聊天保留换电脑及配额均衡原因记录。失败先恢复原位置,再通过已有宿主确认卡询问摘要接续;桌面、手机与同账号远控共同回应,不由模型代答。取消不产生成功换电脑分隔条,也不写入摘要。
+- **共享来源弹窗**:写明要换去哪台(同一台电脑上有几个账号时带账号名)、那台的配额还剩多少、多久重置,以及交接摘要可能遗漏细节。电脑上是「换过去」「取消」两个按钮加一个默认不勾的复选框「以后自动换,不再询问(仅本任务)」;
手机系统弹窗没有复选框,用三个按钮「换过去」「换过去,以后自动换(仅本任务)」「取消」(用户要求与电脑一致)。
-- **选择的结果**:
+- **共享来源选择的结果**:
- 换过去:这条消息发出前先换到那台(进行中行显示「正在换一台电脑继续」),消息里的分隔条写
「Agent 已改到 {电脑} 上运行 · 这个账号的配额更该先用」。不勾复选框时这个任务以后遇到同样情况每次仍会问。
- 勾了「以后自动换」再换过去:这个任务以后不再弹窗,直接换,分隔条照常写一行。只记这个任务,记录存在任务所在的电脑上,
换一台电脑或在手机上看这个任务也一样;任务删除后记录不再有用,超过 4000 条时丢掉最早的。
- 取消(含关闭弹窗):不换,这条消息照常发到原来的账号;下一条消息仍会再问。
- 无论选什么,这条消息都照常发出。
-- **确认的归属**:换号确认绑定具体这条消息;离开任务而未发送,或另一台控制端随后发消息,都不能把这次确认用到另一条消息上。
-- **换不过去**:用户确认后 2 分钟内没发出去的(停止、断线)不留到以后;实际选路时重新检查目标负载、配额和换号收益门槛。
+- **决定的归属**:自动或经确认的换号决定绑定具体这条消息;离开任务而未发送,或另一台控制端随后发消息,都不能把这次决定用到另一条消息上。
+- **换不过去**:登记换号后 2 分钟内没发出去的(停止、断线)不留到以后;实际选路时重新检查目标负载、配额和换号收益门槛。
那台此刻接不了、不再值得换或交接失败时照常发到原来的账号、
不报错,那台 30 分钟内不再提议。这次换号不算 §6.1 的「这一轮试过」,之后原电脑出问题照常可以换回来。
-- 用户确认的换号不受「出问题时自动换电脑」开关影响(开关管的是出问题时不问就换)。
+- 发送前配额均衡不受「出问题时自动换电脑」开关影响(开关管的是故障时自动换电脑)。
- **实现**:判断与执行在任务所在电脑的 `apps/desktop/src/main/provider-group/service.ts`(`rebalanceSuggestion`、
`rebalanceDecision`、`beforeSend`),尺子是 `usage.ts` 的 `providerGroupRebalanceTarget`;「以后自动换」存在
`provider-group/sessionPrefs.ts`。电脑在 `features/provider-group/sessionRebalancePrompt.ts`(发送前由
@@ -768,7 +773,7 @@
`manage-group` / `manage-share`(§10)。其余沿用现有协议,不改服务端。兼容做法见 §14,登记见
`docs/dev-rules/protocol-compatibility.md`「供应商组」。
- [跨电脑复制任务](task-device-migration.md) 与已建任务换 Agent 所在电脑:§6.1 的自动换电脑与手动「换一台继续」
- 都复用现有交接,不新增交接机制。
+ 复用原生转录的导入/导出与有界交接兜底;仅迁移 Agent 时不复制任务、工作文件或凭证。
- [用量上限自动继续](usage-limit-auto-continue.md):冷却的重置时刻口径与之一致;有组时先换电脑,组里所有电脑都失败且其中有
撞上限的,才按该文等最早恢复的一台;组内电脑冷却期间,自动继续不会分到这台。
- 手机端:模型列表与桌面一样收起组里的电脑(§10);供应商组的设置、组内电脑状态与用量只在电脑上。
@@ -795,7 +800,7 @@
活动记录;同一轮每台最多试一次,全部失败才报错并逐台列出原因;其中有撞上限的,等最早恢复的一台自动继续。
4. 用户停止、权限被拒、上下文超限、请求无效、内容被拒、工具出错时不换电脑;其余失败都换(含认不出的)。「故障 × 阶段」的判定表
见 `provider-group/__tests__/failurePolicy.test.ts`,所有路径用同一个判定。本机的操作(切换焦点、改目录、改档位)不打断进行中的
- 远程一轮;组所在电脑慢一点不把任务移出组;有原生会话要续接的任务换电脑都带交接。
+ 远程一轮;组所在电脑慢一点不把任务移出组;同 Harness 换电脑优先恢复原生记录,不能恢复时明确使用摘要。
5. 经组转发到组内电脑的任务不会再进入那台电脑的供应商组。
6. 两个使用方用相同的任务或会话标识也不能读到、续接或关闭对方的任务。
7. 关闭或删除对某人的分享后,此人的任务立即停止且不换电脑;移出组内电脑后不再给它分新任务,已在它上面的任务留在那台。
diff --git a/packages/device-link/src/__tests__/remoteAgent.test.ts b/packages/device-link/src/__tests__/remoteAgent.test.ts
index 3917526aec..bbae9c7735 100644
--- a/packages/device-link/src/__tests__/remoteAgent.test.ts
+++ b/packages/device-link/src/__tests__/remoteAgent.test.ts
@@ -302,3 +302,17 @@ it('negotiates native image recovery and validates scoped chunk requests', () =>
expect(() => parseRemoteAgentRequest({ op: 'images', sessionId: runId, action: 'read', imageId: 'a'.repeat(64), offset: 0, ...patch })).toThrow('REMOTE_AGENT_INVALID');
}
});
+
+
+it('negotiates native-history transfer without making mutations retryable on old peers', () => {
+ const caps = { version: 1, agents: [], maxRuns: 1, uploadChunkBytes: 1024, maxPayloadBytes: 2048 };
+ expect(parseRemoteAgentCaps(caps).nativeHistoryTransfer).toBeUndefined();
+ expect(parseRemoteAgentCaps({ ...caps, nativeHistoryTransfer: true }).nativeHistoryTransfer).toBe(true);
+ expect(parseRemoteAgentCaps({ ...caps, nativeHistoryTransfer: 'yes' }).nativeHistoryTransfer).toBeUndefined();
+ const request = { op: 'native-history', sessionId: 'task', command: { action: 'export', kind: 'codex', nativeId: runId } };
+ expect(parseRemoteAgentRequest({ ...request, workingDir: '/owner' })).toEqual(request);
+ expect(() => parseRemoteAgentRequest({ ...request, sessionId: '../task' })).toThrow('REMOTE_AGENT_INVALID');
+ expect(() => parseRemoteAgentRequest({ ...request, command: null })).toThrow('REMOTE_AGENT_INVALID');
+ expect(isRemoteAgentReadInvoke(REMOTE_AGENT_CHANNEL, [request])).toBe(false);
+ expect(isPeerResetRetryableInvoke(REMOTE_AGENT_CHANNEL, [request])).toBe(false);
+});
diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.ts
index 00c092dbb6..1bdf01e799 100644
--- a/packages/device-link/src/remoteAgent.ts
+++ b/packages/device-link/src/remoteAgent.ts
@@ -152,6 +152,8 @@ export const REMOTE_AGENT_MAX_PUSH_CHARS = 3 * 1024 * 1024;
export type RemoteAgentRequest =
| { op: 'caps' }
+ /** Same-account native history transfer. The host validates commands before accessing storage. */
+ | { op: 'native-history'; sessionId: string; command: unknown }
/** Authenticated group owner updates only its own task speed constraints, never model grants. */
| ({ op: 'fast-policy' } & RemoteAgentFastPolicy)
| ({ op: 'fork' } & RemoteAgentForkRequest)
@@ -269,6 +271,7 @@ export interface RemoteAgentForkResult {
}
export interface RemoteAgentCaps {
+ nativeHistoryTransfer?: boolean;
subscriptionFastPolicy?: true;
nativeFork?: boolean;
imageRecovery?: boolean;
@@ -441,6 +444,10 @@ export function parseRemoteAgentRequest(value: unknown): RemoteAgentRequest {
switch (v.op) {
case 'caps':
return { op: 'caps' };
+ case 'native-history': {
+ if (typeof v.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(v.sessionId)) invalid();
+ return { op: 'native-history', sessionId: v.sessionId as string, command: record(v.command) };
+ }
case 'fast-policy': {
if (typeof v.group !== 'string' || !/^[A-Za-z0-9_.:-]{1,256}$/.test(v.group)
|| typeof v.allowFast !== 'boolean') invalid();
@@ -662,6 +669,7 @@ export function parseRemoteAgentCaps(value: unknown): RemoteAgentCaps {
maxPayloadBytes: count(v.maxPayloadBytes, Number.MAX_SAFE_INTEGER),
...(v.virtualWorkspace === true ? { virtualWorkspace: true } : {}),
...(v.nativeFork === true ? { nativeFork: true } : {}),
+ ...(v.nativeHistoryTransfer === true ? { nativeHistoryTransfer: true } : {}),
...(v.imageRecovery === true ? { imageRecovery: true } : {}),
...(v.imageRecoveryRelay === true ? { imageRecoveryRelay: true } : {}),
...(v.guestRelay === true ? { guestRelay: true } : {}),