Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): hand off context overflow across local agents (#3114)
Dash6ccc880f4565
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.tsindex 179ef532ad..0fa0837817 100644--- a/apps/desktop/src/main/__tests__/fork.test.ts+++ b/apps/desktop/src/main/__tests__/fork.test.ts@@ -65,6 +65,13 @@ const txMock = vi.fn((name: string, args: unknown) => {const queryOneMock = vi.fn(async () => null as Record<string, unknown> | null);const queryMock = vi.fn(async () => [] as Array<{ role: string; content: string }>);+const commitContextRebuildMock = vi.fn(async () => ({ updatedAt: Date.now() }));+const createMessageMock = vi.fn(async () => ({}));+vi.mock('../localDb/ipc/messages.js', () => ({+ commitContextRebuild: commitContextRebuildMock as never,+ createMessage: createMessageMock as never,+}));+vi.mock('../localDb/client/current', () => ({getDbClient: () => ({drizzle: fakeDb,@@ -92,6 +99,8 @@ beforeEach(async () => {queryOneMock.mockResolvedValue(null);queryMock.mockReset();queryMock.mockResolvedValue([]);+ commitContextRebuildMock.mockClear();+ createMessageMock.mockClear();forkSdkSessionMock.mockReset();// 默认空 uuidMap 让 agentMeta 字段被去掉 (无映射)。具体测试按需 override。forkSdkSessionMock.mockResolvedValue({@@ -203,9 +212,9 @@ describe('forkSessionAtMessage', () => {createdAt: 2000,});- selectQueue.push([makeSourceRow()]); // source session- selectQueue.push([target]); // target message- selectQueue.push([priorUser, priorAssistant]); // prior messages asc (for bulk copy)+ selectQueue.push([makeSourceRow()]); // source session+ selectQueue.push([target]); // target message+ selectQueue.push([priorUser, priorAssistant]); // prior messages asc (for bulk copy)selectQueue.push([makeSourceRow({id: 'expected-new-id', // 仅占位; 实际 id 由 createBusinessSessionId() 生成 UUID@@ -287,20 +296,24 @@ describe('forkSessionAtMessage', () => {createdAt: 2500,});- selectQueue.push([makeSourceRow({- agentKind: 'codex',- model: 'gpt-5.4',- sdkSessionId: 'codex-thread-source',- codexHistoryHasProductPrompt: false,- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'gpt-5.4',+ sdkSessionId: 'codex-thread-source',+ codexHistoryHasProductPrompt: false,+ }),+ ]);selectQueue.push([target]);selectQueue.push([priorUser, priorAssistant]); // bulk copy: only target之前- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'codex-thread-new',- parentSessionId: 'src-session',- forkedAtMessageId: 'target-user',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-new',+ parentSessionId: 'src-session',+ forkedAtMessageId: 'target-user',+ }),+ ]);forkSdkSessionMock.mockResolvedValue({newSdkSessionId: 'codex-thread-new',@@ -409,17 +422,17 @@ describe('forkSessionAtMessage', () => {it('codex path: maps preparation or thread/fork failures to a diagnosable error', async () => {const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'imported-codex-thread',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'imported-codex-thread',+ }),+ ]);selectQueue.push([target]);queryMock.mockResolvedValue([{ role: 'user', content: '"target"' }]);forkSdkSessionMock.mockRejectedValueOnce(new Error('thread not found in current Codex home'));- await expect(- forkSessionAtMessage('src-session', 'target-user'),- ).rejects.toMatchObject({+ await expect(forkSessionAtMessage('src-session', 'target-user')).rejects.toMatchObject({code: 'CODEX_FORK_STATE_UNAVAILABLE',message: 'thread not found in current Codex home',});@@ -428,19 +441,19 @@ describe('forkSessionAtMessage', () => {it('codex path: projects a blocked resume preparation without exposing diagnostics', async () => {const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'imported-codex-thread',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'imported-codex-thread',+ }),+ ]);selectQueue.push([target]);queryMock.mockResolvedValue([{ role: 'user', content: '"target"' }]);forkSdkSessionMock.mockRejectedValueOnce(new CodexResumePreparationBlockedError('live writer at /private/codex/rollout.jsonl'),);- await expect(- forkSessionAtMessage('src-session', 'target-user'),- ).rejects.toMatchObject({+ await expect(forkSessionAtMessage('src-session', 'target-user')).rejects.toMatchObject({code: 'CODEX_FORK_STATE_UNAVAILABLE',message: CODEX_RESUME_NOT_READY_WIRE_MESSAGE,});@@ -458,13 +471,15 @@ describe('forkSessionAtMessage', () => {selectQueue.push([source]); // source sessionselectQueue.push([first, second]); // source messages for max + ids- selectQueue.push([makeSourceRow({- agentKind: 'codex',- title: '[Fork·已剥离] Project A',- sdkSessionId: 'codex-thread-new',- parentSessionId: 'src-session',- forkedAtMessageId: null,- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ title: '[Fork·已剥离] Project A',+ sdkSessionId: 'codex-thread-new',+ parentSessionId: 'src-session',+ forkedAtMessageId: null,+ }),+ ]);forkSdkSessionMock.mockResolvedValue({newSdkSessionId: 'codex-thread-new',@@ -508,13 +523,15 @@ describe('forkSessionAtMessage', () => {// 否则 B → C 时反查到的 uuid 在 B jsonl 找不到, SDK forkSession 会报错。// ClaudeCodeAgent.forkSdkSession 内部已经把建好的 uuidMap 直接返回, 这里只测// fork 用 uuidMap 正确 remap 了 agentMeta 列。- await writeClaudeJsonl('sdk-uuid-source', '/work', [{- type: 'assistant',- uuid: 'old-asst-uuid',- parentUuid: 'old-user-uuid',- sessionId: 'sdk-uuid-source',- message: { id: 'old-asst-request', content: [{ type: 'text', text: 'hi back' }] },- }]);+ await writeClaudeJsonl('sdk-uuid-source', '/work', [+ {+ type: 'assistant',+ uuid: 'old-asst-uuid',+ parentUuid: 'old-user-uuid',+ sessionId: 'sdk-uuid-source',+ message: { id: 'old-asst-request', content: [{ type: 'text', text: 'hi back' }] },+ },+ ]);const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });const priorUser = makeMessageRow({id: 'user-1',@@ -564,9 +581,9 @@ describe('forkSessionAtMessage', () => {selectQueue.push([makeSourceRow({ sdkSessionId: null })]);selectQueue.push([makeMessageRow({ clientId: 'any-msg' })]);- await expect(- forkSessionAtMessage('src-session', 'any-msg'),- ).rejects.toMatchObject({ code: 'SOURCE_NEVER_RAN' });+ await expect(forkSessionAtMessage('src-session', 'any-msg')).rejects.toMatchObject({+ code: 'SOURCE_NEVER_RAN',+ });expect(forkSdkSessionMock).not.toHaveBeenCalled();expect(txCalls).toHaveLength(0);@@ -580,40 +597,137 @@ describe('forkSessionAtMessage', () => {createdAt: 2500,rowid: 20,});- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'current-codex-thread',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'current-codex-thread',+ }),+ ]);selectQueue.push([target]);queryOneMock.mockResolvedValueOnce({ id: 'later-context-rebuild' });- await expect(- forkSessionAtMessage('src-session', 'stale-history-client'),- ).rejects.toMatchObject({ code: 'UNSUPPORTED_HISTORY' });-- expect(queryOneMock).toHaveBeenCalledWith(- expect.stringContaining("role = 'context_rebuild'"),- ['src-session', 2500, 2500, 20],+ await expect(forkSessionAtMessage('src-session', 'stale-history-client')).rejects.toMatchObject(+ { code: 'UNSUPPORTED_HISTORY' },);++ expect(queryOneMock).toHaveBeenCalledWith(expect.stringContaining("role = 'context_rebuild'"), [+ 'src-session',+ 2500,+ 2500,+ 20,+ ]);expect(forkSdkSessionMock).not.toHaveBeenCalled();expect(txCalls).toHaveLength(0);});- it('rejects a historical engine boundary without a parked native session id', async () => {+ it('forks overflow-rebuilt history as a fresh native session with handoff', async () => {const target = makeMessageRow({- id: 'historical-assistant',- clientId: 'historical-assistant-client',+ id: 'stale-history',+ clientId: 'stale-history-client',role: 'assistant',createdAt: 2500,rowid: 20,});- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'current-codex-thread',- })]);+ const priorUser = makeMessageRow({+ id: 'user-1',+ clientId: 'user-1-client',+ role: 'user',+ createdAt: 2000,+ rowid: 10,+ });+ selectQueue.push([+ makeSourceRow({+ agentKind: 'pi',+ sdkSessionId: 'fresh-after-rebuild',+ }),+ ]);+ selectQueue.push([target]);+ selectQueue.push([]);+ selectQueue.push([priorUser, target]);+ selectQueue.push([+ makeSourceRow({+ id: 'forked-id',+ title: '[Fork] Project A',+ agentKind: 'pi',+ sdkSessionId: null,+ parentSessionId: 'src-session',+ }),+ ]);+ queryOneMock.mockResolvedValueOnce({+ id: 'later-overflow-rebuild',+ content: JSON.stringify({+ reason: 'context-overflow',+ handoff: 'hidden',+ consumed: true,+ }),+ });++ await forkSessionAtMessage('src-session', 'stale-history-client');++ expect(forkSdkSessionMock).not.toHaveBeenCalled();+ expect(txCalls.some((call) => call.name === 'fork.session')).toBe(true);+ expect(commitContextRebuildMock).toHaveBeenCalledWith(+ expect.any(String),+ expect.stringContaining("exceeded the model's context window"),+ expect.objectContaining({+ reason: 'context-overflow',+ sourceAgentKind: 'pi',+ sourceModel: 'claude-sonnet-4-6',+ sourceProviderId: 'xd',+ }),+ );+ expect(createMessageMock).toHaveBeenCalled();+ });++ it('uses the rebuild boundary engine when history crosses a later engine switch', async () => {+ const target = makeMessageRow({+ id: 'historical-claude-assistant',+ clientId: 'historical-claude-assistant-client',+ role: 'assistant',+ agentKind: 'cc',+ createdAt: 2500,+ rowid: 20,+ });+ const priorUser = makeMessageRow({+ id: 'historical-claude-user',+ clientId: 'historical-claude-user-client',+ role: 'user',+ agentKind: 'cc',+ createdAt: 2000,+ rowid: 10,+ });+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'gpt-5.6',+ sdkSessionId: 'current-codex-thread',+ }),+ ]);selectQueue.push([target]);+ selectQueue.push([]);+ selectQueue.push([priorUser, target]);+ selectQueue.push([+ makeSourceRow({+ id: 'forked-id',+ title: '[Fork] Project A',+ agentKind: 'cc',+ model: 'claude-sonnet-4-6',+ sdkSessionId: null,+ parentSessionId: 'src-session',+ }),+ ]);queryOneMock- .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ id: 'context-rebuild-boundary',+ content: JSON.stringify({+ reason: 'context-overflow',+ sourceAgentKind: 'cc',+ sourceModel: 'claude-sonnet-4-6',+ sourceProviderId: null,+ }),+ created_at: 3000,+ rowid: 30,+ }).mockResolvedValueOnce({content: JSON.stringify({fromAgentKind: 'cc',@@ -621,10 +735,45 @@ describe('forkSessionAtMessage', () => {fromModel: 'claude-sonnet-4-6',fromSdkSessionId: null,}),- created_at: 2800,- rowid: 30,+ created_at: 4000,+ rowid: 40,});+ await forkSessionAtMessage('src-session', 'historical-claude-assistant-client');++ const txArgs = txCalls.find((call) => call.name === 'fork.session')!.args as {+ newSession: Record<string, unknown>;+ };+ expect(txArgs.newSession.agentKind).toBe('cc');+ expect(txArgs.newSession.model).toBe('claude-sonnet-4-6');+ expect(forkSdkSessionMock).not.toHaveBeenCalled();+ });+ it('rejects a historical engine boundary without a parked native session id', async () => {+ const target = makeMessageRow({+ id: 'historical-assistant',+ clientId: 'historical-assistant-client',+ role: 'assistant',+ createdAt: 2500,+ rowid: 20,+ });+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'current-codex-thread',+ }),+ ]);+ selectQueue.push([target]);+ queryOneMock.mockResolvedValueOnce(null).mockResolvedValueOnce({+ content: JSON.stringify({+ fromAgentKind: 'cc',+ toAgentKind: 'codex',+ fromModel: 'claude-sonnet-4-6',+ fromSdkSessionId: null,+ }),+ created_at: 2800,+ rowid: 30,+ });+await expect(forkSessionAtMessage('src-session', 'historical-assistant-client'),).rejects.toMatchObject({ code: 'UNSUPPORTED_HISTORY' });@@ -650,20 +799,24 @@ describe('forkSessionAtMessage', () => {createdAt: 2000,rowid: 10,});- selectQueue.push([makeSourceRow({- agentKind: 'codex',- model: 'gpt-5.4',- sdkSessionId: 'current-codex-thread',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'gpt-5.4',+ sdkSessionId: 'current-codex-thread',+ }),+ ]);selectQueue.push([target]);selectQueue.push([]); // no next user before the engine leavesselectQueue.push([priorUser, target]);- selectQueue.push([makeSourceRow({- agentKind: 'cc',- model: 'claude-sonnet-4-6',- sdkSessionId: 'forked-historical-claude',- parentSessionId: 'src-session',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'cc',+ model: 'claude-sonnet-4-6',+ sdkSessionId: 'forked-historical-claude',+ parentSessionId: 'src-session',+ }),+ ]);queryOneMock.mockResolvedValueOnce(null) // no context_rebuild after target.mockResolvedValueOnce({@@ -734,11 +887,13 @@ describe('forkSessionAtMessage', () => {selectQueue.push([makeSourceRow({ sdkSessionId: 'fresh-claude-session' })]);selectQueue.push([target]);selectQueue.push([boundary]);- selectQueue.push([makeSourceRow({- sdkSessionId: null,- parentSessionId: 'src-session',- forkedAtMessageId: 'first-claude-user-client',- })]);+ selectQueue.push([+ makeSourceRow({+ sdkSessionId: null,+ parentSessionId: 'src-session',+ forkedAtMessageId: 'first-claude-user-client',+ }),+ ]);await forkSessionAtMessage('src-session', 'first-claude-user-client');@@ -782,36 +937,41 @@ describe('forkSessionAtMessage', () => {fromSdkSessionId: 'parked-codex-thread',handoff: 'handoff',};- selectQueue.push([makeSourceRow({- agentKind: 'cc',- sdkSessionId: 'current-claude-session',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'cc',+ sdkSessionId: 'current-claude-session',+ }),+ ]);selectQueue.push([target]);selectQueue.push([nextCodexUser]);selectQueue.push([priorUser, target]);- selectQueue.push([makeSourceRow({- agentKind: 'codex',- model: 'gpt-5.4',- sdkSessionId: 'forked-codex-thread',- parentSessionId: 'src-session',- })]);- queryOneMock- .mockResolvedValueOnce(null)- .mockResolvedValueOnce({- content: JSON.stringify(parkedCodexBoundary),- created_at: 2800,- rowid: 30,- });+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ model: 'gpt-5.4',+ sdkSessionId: 'forked-codex-thread',+ parentSessionId: 'src-session',+ }),+ ]);+ queryOneMock.mockResolvedValueOnce(null).mockResolvedValueOnce({+ content: JSON.stringify(parkedCodexBoundary),+ created_at: 2800,+ rowid: 30,+ });queryMock.mockResolvedValue([{ role: 'user', content: '"current Claude"' },{ role: 'agent_switch', content: JSON.stringify(parkedCodexBoundary) },{ role: 'user', content: '"resumed Codex"' },- { role: 'agent_switch', content: JSON.stringify({- fromAgentKind: 'cc',- toAgentKind: 'codex',- fromModel: 'claude-sonnet-4-6',- fromSdkSessionId: 'current-claude-session',- }) },+ {+ role: 'agent_switch',+ content: JSON.stringify({+ fromAgentKind: 'cc',+ toAgentKind: 'codex',+ fromModel: 'claude-sonnet-4-6',+ fromSdkSessionId: 'current-claude-session',+ }),+ },{ role: 'user', content: '"middle Claude"' },{ role: 'agent_switch', content: JSON.stringify(parkedCodexBoundary) },{ role: 'user', content: '"next Codex"' },@@ -861,9 +1021,9 @@ describe('forkSessionAtMessage', () => {const nextUser = makeMessageRow({ id: 'user-next', role: 'user', createdAt: 3000 });const priorUser = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 2000 });- selectQueue.push([makeSourceRow()]); // source session- selectQueue.push([target]); // target message- selectQueue.push([nextUser]); // next user after target+ selectQueue.push([makeSourceRow()]); // source session+ selectQueue.push([target]); // target message+ selectQueue.push([nextUser]); // next user after targetselectQueue.push([priorUser, target, turnFinalAssistant]); // bulk copy (含 target 所在 turn)selectQueue.push([makeSourceRow({@@ -924,9 +1084,7 @@ describe('forkSessionAtMessage', () => {const priorUser = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 2000 });forkSdkSessionMock.mockResolvedValue({newSdkSessionId: 'sdk-new-session-uuid',- uuidMap: new Map([- ['4652fd61-a4df-411a-87e7-cdc0b311cc39', 'new-real-assistant-uuid'],- ]),+ uuidMap: new Map([['4652fd61-a4df-411a-87e7-cdc0b311cc39', 'new-real-assistant-uuid']]),});selectQueue.push([makeSourceRow()]);@@ -947,12 +1105,15 @@ describe('forkSessionAtMessage', () => {});const txCall = txCalls.find((c) => c.name === 'fork.session');expect(txCall).toBeDefined();- expect((txCall!.args as { uuidMap: Array<[string, string]> }).uuidMap).toEqual(expect.arrayContaining([- ['4652fd61-a4df-411a-87e7-cdc0b311cc39', 'new-real-assistant-uuid'],- ['4652fd61-a4df-411a-87e7-000000000001', 'new-real-assistant-uuid'],- ]));- expect((txCall!.args as { legacyTranscriptParentUuids: string[] }).legacyTranscriptParentUuids)- .toContain('4652fd61-a4df-411a-87e7-000000000001');+ expect((txCall!.args as { uuidMap: Array<[string, string]> }).uuidMap).toEqual(+ expect.arrayContaining([+ ['4652fd61-a4df-411a-87e7-cdc0b311cc39', 'new-real-assistant-uuid'],+ ['4652fd61-a4df-411a-87e7-000000000001', 'new-real-assistant-uuid'],+ ]),+ );+ expect(+ (txCall!.args as { legacyTranscriptParentUuids: string[] }).legacyTranscriptParentUuids,+ ).toContain('4652fd61-a4df-411a-87e7-000000000001');});it('assistant target (claude): repairs legacy imported parentUuid using the transcript index', async () => {@@ -1025,14 +1186,19 @@ describe('forkSessionAtMessage', () => {tempDirs.push(userDataDir);delete process.env.CLAUDE_CONFIG_DIR;process.env.XDT_USER_DATA_DIR = userDataDir;- await writeClaudeJsonlInConfigDir(path.join(userDataDir, 'claude-home'), 'sdk-uuid-source', '/work', [- {- type: 'assistant',- uuid: 'isolated-real-assistant-uuid',- sessionId: 'sdk-uuid-source',- message: { id: 'msg_isolated_real', content: [{ type: 'text', text: 'hi' }] },- },- ]);+ await writeClaudeJsonlInConfigDir(+ path.join(userDataDir, 'claude-home'),+ 'sdk-uuid-source',+ '/work',+ [+ {+ type: 'assistant',+ uuid: 'isolated-real-assistant-uuid',+ sessionId: 'sdk-uuid-source',+ message: { id: 'msg_isolated_real', content: [{ type: 'text', text: 'hi' }] },+ },+ ],+ );const target = makeMessageRow({id: 'asst-isolated',clientId: 'asst-isolated-cid',@@ -1116,8 +1282,10 @@ describe('forkSessionAtMessage', () => {remoteHostId: null,});const txCall = txCalls.find((call) => call.name === 'fork.session');- expect(((txCall?.args as { legacyTranscriptParentUuids?: string[] }).legacyTranscriptParentUuids ?? []))- .not.toContain('4652fd61-a4df-411a-87e7-000000000002');+ expect(+ (txCall?.args as { legacyTranscriptParentUuids?: string[] }).legacyTranscriptParentUuids ??+ [],+ ).not.toContain('4652fd61-a4df-411a-87e7-000000000002');});it('assistant target at session tail (claude): no next user → copies everything', async () => {@@ -1130,10 +1298,10 @@ describe('forkSessionAtMessage', () => {});const priorUser = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 2000 });- selectQueue.push([makeSourceRow()]); // source- selectQueue.push([target]); // target- selectQueue.push([]); // no next user- selectQueue.push([priorUser, target]); // bulk copy = 全部+ selectQueue.push([makeSourceRow()]); // source+ selectQueue.push([target]); // target+ selectQueue.push([]); // no next user+ selectQueue.push([priorUser, target]); // bulk copy = 全部selectQueue.push([makeSourceRow({ sdkSessionId: 'sdk-new-session-uuid' })]);await forkSessionAtMessage('src-session', 'asst-last-cid');@@ -1162,17 +1330,21 @@ describe('forkSessionAtMessage', () => {const nextUser = makeMessageRow({ id: 'user-next', role: 'user', createdAt: 3000 });const priorUser = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 2000 });- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'codex-thread-source',- })]);+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-source',+ }),+ ]);selectQueue.push([target]);- selectQueue.push([nextUser]); // next user after target- selectQueue.push([priorUser, target]); // bulk copy (含 target 所在 turn)- selectQueue.push([makeSourceRow({- agentKind: 'codex',- sdkSessionId: 'codex-thread-new',- })]);+ selectQueue.push([nextUser]); // next user after target+ selectQueue.push([priorUser, target]); // bulk copy (含 target 所在 turn)+ selectQueue.push([+ makeSourceRow({+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-new',+ }),+ ]);forkSdkSessionMock.mockResolvedValue({newSdkSessionId: 'codex-thread-new',@@ -1201,9 +1373,9 @@ describe('forkSessionAtMessage', () => {selectQueue.push([makeSourceRow()]);selectQueue.push([target]);- await expect(- forkSessionAtMessage('src-session', 'tool-1'),- ).rejects.toMatchObject({ code: 'NOT_USER_MESSAGE' });+ await expect(forkSessionAtMessage('src-session', 'tool-1')).rejects.toMatchObject({+ code: 'NOT_USER_MESSAGE',+ });expect(forkSdkSessionMock).not.toHaveBeenCalled();expect(txCalls).toHaveLength(0);@@ -1213,12 +1385,12 @@ describe('forkSessionAtMessage', () => {const target = makeMessageRow({ id: 'first-user', role: 'user', createdAt: 1500 });selectQueue.push([makeSourceRow()]); // source- selectQueue.push([target]); // target- selectQueue.push([]); // prior assistants — empty+ selectQueue.push([target]); // target+ selectQueue.push([]); // prior assistants — empty- await expect(- forkSessionAtMessage('src-session', 'first-user'),- ).rejects.toMatchObject({ code: 'NO_PRIOR_ASSISTANT' });+ await expect(forkSessionAtMessage('src-session', 'first-user')).rejects.toMatchObject({+ code: 'NO_PRIOR_ASSISTANT',+ });expect(forkSdkSessionMock).not.toHaveBeenCalled();expect(txCalls).toHaveLength(0);diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 8f6ed2fd56..fff865f6b0 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -275,6 +275,11 @@ describe('sendToSession ordering', () => {'if (!targetSessionId) {','const prev = sendToSessionLocks.get(targetSessionId);',);+ expectOrder(+ block,+ 'prepareUnhealthySession(targetSessionId)',+ 'live = maker.getSession(targetSessionId);',+ );const liveBranch = extractBetween(block,'live = maker.getSession(targetSessionId);',@@ -505,7 +510,8 @@ describe('sendToSession ordering', () => {'const release = await acquireSendToSessionLock(sessionId);','applyPendingAgentSwitchIfIdle(',);- expectOrder(directSendSwitchBlock, 'applyPendingAgentSwitchIfIdle(', 'return release;');+ expectOrder(directSendSwitchBlock, 'applyPendingAgentSwitchIfIdle(', 'prepareUnhealthySession');+ expectOrder(directSendSwitchBlock, 'prepareUnhealthySession', 'return release;');});it('仅 Device Link 归一化 SET_MODEL 的 JSON null 可选占位,本地仍走严格校验', () => {diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex d1ed57e8d5..bd23eec120 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -110,6 +110,7 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({}));vi.mock('../../maker-ipc/register.js', () => ({beginTurnChangeSetAtDispatch: h.beginTurnChangeSetAtDispatch,+ prepareUnhealthySessionForSend: vi.fn(async () => undefined),wireSessionToIpc: vi.fn(),isSessionInTurn: () => false,installDesktopInteractionListener: h.installDesktopInteractionListener,diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 1a0f0caaee..764322c284 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -54,6 +54,7 @@ import { resolveLenientRoute } from '../maker-host/model-route-guard.js';import { resolveLenientSessionRoute } from '../maker-host/model-route-guard-live.js';import {beginTurnChangeSetAtDispatch,+ prepareUnhealthySessionForSend,wireSessionToIpc,isSessionInTurn,noteSilentStopUserSend,@@ -636,6 +637,7 @@ export function createMakerHookSessionRunner(deps: {resumeSessionId,};try {+ await prepareUnhealthySessionForSend(req.sessionId);session = await maker.createSession(createOpts);} catch (err) {// session 未建成: 若有预建 worktree 则回收(同 maker-ipc/register.ts@@ -1003,6 +1005,7 @@ export function createMakerHookSessionRunner(deps: {content: req.replacementPrompt,createdAt: previousMessages[0].createdAt - 1,agentMeta: null,+ toolUseId: null,},...previousMessages,];@@ -1022,6 +1025,7 @@ export function createMakerHookSessionRunner(deps: {content: req.replacementPrompt,createdAt: startedAt,agentMeta: null,+ toolUseId: null,},];} else {diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex f59a1812ae..ff0a5b8a57 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -313,6 +313,8 @@ function dispatchTx(readyDb, payload) {return sessionsSetStatus(readyDb, request.args);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(readyDb, request.args);+ case 'context.rebuild':+ return contextRebuild(readyDb, request.args);case 'message.delete':return messageDelete(readyDb, request.args);case 'im.deleteBindings':@@ -406,6 +408,35 @@ function sessionAgentSwitchFallback(readyDb, args) {})();}+// ⚠️ 与 worker/opHandlers/tx.ts 的同名事务保持一致。+function contextRebuild(readyDb, args) {+ const payload = asRecord(args, 'context.rebuild args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const markerId = expectString(payload.markerId, 'markerId');+ const markerClientId = expectString(payload.markerClientId, 'markerClientId');+ const markerContent = expectString(payload.markerContent, 'markerContent');+ const markerCreatedAt = expectNumber(payload.markerCreatedAt, 'markerCreatedAt');+ const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ const expectedClearedAt =+ payload.expectedClearedAt === undefined || payload.expectedClearedAt === null+ ? null+ : expectNumber(payload.expectedClearedAt, 'expectedClearedAt');+ return readyDb.transaction(() => {+ const sessionResult = readyDb.prepare(+ 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ? WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',+ ).run(updatedAt, sessionId, expectedClearedAt);+ if (sessionResult.changes !== 1) {+ throw Object.assign(new Error('Session missing or clear-boundary changed: ' + sessionId), {+ code: 'PRECONDITION_FAILED',+ });+ }+ // 只追加新边界。删掉更早的 context_rebuild 会让 fork 丢掉中间失效点。+ readyDb.prepare(+ "INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, 'context_rebuild', ?, ?, ?)",+ ).run(markerId, markerClientId, sessionId, markerContent, markerCreatedAt, markerCreatedAt);+ })();+}+// ⚠️ 与 worker/opHandlers/tx.ts 的同名事务保持一致。function messageDelete(readyDb, args) {const payload = asRecord(args, 'message.delete args');diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 0d70489f3e..77d76cd2f8 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -1314,6 +1314,50 @@ describe('db worker tx handlers', () => {});});+ it('context.rebuild appends markers instead of deleting earlier rebuild boundaries', async () => {+ await withClient(async (client) => {+ await seedSession(client, 's1');+ await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['native-a', 's1']);+ await client.tx('context.rebuild', {+ sessionId: 's1',+ markerId: 'rebuild-1',+ markerClientId: 'rebuild-1',+ markerContent: '{"reason":"context-overflow","sourceAgentKind":"cc"}',+ markerCreatedAt: 1000,+ updatedAt: 1000,+ });+ await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['native-b', 's1']);+ await client.tx('context.rebuild', {+ sessionId: 's1',+ markerId: 'rebuild-2',+ markerClientId: 'rebuild-2',+ markerContent: '{"reason":"context-overflow","sourceAgentKind":"codex"}',+ markerCreatedAt: 2000,+ updatedAt: 2000,+ });+ await expect(+ client.query<{ id: string; content: string; rewind_at: number | null }>(+ 'SELECT id, content, rewind_at FROM messages WHERE session_id = ? AND role = ? ORDER BY created_at',+ ['s1', 'context_rebuild'],+ ),+ ).resolves.toEqual([+ {+ id: 'rebuild-1',+ content: '{"reason":"context-overflow","sourceAgentKind":"cc"}',+ rewind_at: 1000,+ },+ {+ id: 'rebuild-2',+ content: '{"reason":"context-overflow","sourceAgentKind":"codex"}',+ rewind_at: 2000,+ },+ ]);+ await expect(+ client.queryOne('SELECT sdk_session_id, updated_at FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({ sdk_session_id: null, updated_at: 2000 });+ });+ });+it('session.agentSwitchFallback missing boundary rolls back sdk id clear', async () => {await withClient(async (client) => {await seedSession(client, 's1');diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex f3f62999e8..a44cd9d087 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -20,6 +20,7 @@ export type DbTxName =| 'sessions.renameTitles'| 'sessions.setStatus'| 'session.agentSwitchFallback'+ | 'context.rebuild'| 'message.delete'| 'im.deleteBindings'| 'im.replaceBinding'@@ -301,6 +302,18 @@ export interface SessionAgentSwitchFallbackArgs {updatedAt: number;}+/** 上下文超限后同一任务换干净原生会话:清 sdk 绑定并追加隐藏 context_rebuild。 */+export interface ContextRebuildArgs {+ sessionId: string;+ markerId: string;+ markerClientId: string;+ markerContent: string;+ markerCreatedAt: number;+ updatedAt: number;+ /** 读历史时看到的 sessions.cleared_at;提交时必须仍相同,否则 /clear 竞态整单回滚。 */+ expectedClearedAt?: number | null;+}+/*** 一次消息删除动作涉及的全部本地记录。删除 assistant 时,这里会包含同一真实* 用户轮中的 thinking / tool / 自动续跑 / 多段 assistant;删除 user 时只有目标行。@@ -758,6 +771,7 @@ export type DbTxArgsByName = {'sessions.renameTitles': SessionsRenameTitlesArgs;'sessions.setStatus': SessionsSetStatusArgs;'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;+ 'context.rebuild': ContextRebuildArgs;'message.delete': MessageDeleteArgs;'im.deleteBindings': ImDeleteBindingsArgs;'im.replaceBinding': ImReplaceBindingArgs;@@ -803,6 +817,7 @@ export type DbTxResultByName = {'sessions.renameTitles': SessionsRenameTitleResult[];'sessions.setStatus': SessionsSetStatusResultItem[];'session.agentSwitchFallback': undefined;+ 'context.rebuild': undefined;'message.delete': MessageDeleteResult;'im.deleteBindings': undefined;'im.replaceBinding': undefined;diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex b38459bc3c..3665896d0f 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -21,10 +21,7 @@ import {import { throwIpcError, requireString } from '../../utils/ipcValidate';import * as broadcastTap from '../../device-link/broadcast-tap';import { createLogger } from '../../logger';-import {- collectCindyMediaHashes,- commitMessageMediaRefs,-} from '../../cindy-media/chatAttachments';+import { collectCindyMediaHashes, commitMessageMediaRefs } from '../../cindy-media/chatAttachments';import {removeRefs as removeMediaRefs,removeSessionAttachmentRefIfUnreferencedByLiveMessage,@@ -442,8 +439,7 @@ export function registerMessageIpc(): void {),);const entries = extractEstimatedSessionValueEntries(rows);- const totalValueMoney =- addCompatibleRegionalMoney(entries.map((entry) => entry.money));+ const totalValueMoney = addCompatibleRegionalMoney(entries.map((entry) => entry.money));const hasCompleteUsdProjection = entries.every((entry) => typeof entry.costUsd === 'number');return {totalValueMoney,@@ -619,11 +615,19 @@ export function broadcastMessageRow(const ownerStamp = ownerStampForBroadcast(ownerScope);if (ownerStamp === null) return;if (ownerScope !== undefined && ownerScope !== null) {- broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg }, ownerStamp);+ broadcastTap.tapWindowBroadcast(+ 'local-db:messages:created',+ { sessionId, message: msg },+ ownerStamp,+ );} else if (ownerStamp === undefined) {broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg });} else {- broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg }, ownerStamp);+ broadcastTap.tapWindowBroadcast(+ 'local-db:messages:created',+ { sessionId, message: msg },+ ownerStamp,+ );}const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;for (const win of BrowserWindow.getAllWindows()) {@@ -946,6 +950,81 @@ export async function commitMessageDeletion(};}+export async function commitContextRebuild(+ sessionId: string,+ handoff: string,+ meta: {+ reason: 'context-overflow' | 'pi-prompt-timeout';+ sourceUserClientId: string | null;+ sourceAgentKind?: 'cc' | 'codex' | 'pi';+ sourceModel?: string | null;+ sourceProviderId?: string | null;+ expectedClearedAt?: number | null;+ },+): Promise<{ updatedAt: number }> {+ const now = Date.now();+ await getDbClient().tx('context.rebuild', {+ sessionId,+ markerId: createId(),+ markerClientId: `context-rebuild:${createId()}`,+ markerContent: JSON.stringify({+ handoff,+ consumed: false,+ reason: meta.reason,+ sourceUserClientId: meta.sourceUserClientId,+ ...(meta.sourceAgentKind ? { sourceAgentKind: meta.sourceAgentKind } : {}),+ ...(meta.sourceModel !== undefined ? { sourceModel: meta.sourceModel } : {}),+ ...(meta.sourceProviderId !== undefined ? { sourceProviderId: meta.sourceProviderId } : {}),+ }),+ markerCreatedAt: now,+ updatedAt: now,+ expectedClearedAt: meta.expectedClearedAt ?? null,+ });+ return { updatedAt: now };+}++export async function findLatestContextRebuildMeta(sessionId: string): Promise<{+ reason?: string;+ sourceUserClientId?: string | null;+ sourceAgentKind?: 'cc' | 'codex' | 'pi';+ sourceModel?: string | null;+ sourceProviderId?: string | null;+} | null> {+ const db = getDbClient().drizzle;+ const [row] = await db+ .select({ content: messages.content })+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.role, 'context_rebuild')))+ .orderBy(desc(messages.createdAt), desc(messageRowid))+ .limit(1);+ if (!row) return null;+ try {+ const parsed = JSON.parse(row.content) as {+ reason?: unknown;+ sourceUserClientId?: unknown;+ sourceAgentKind?: unknown;+ sourceModel?: unknown;+ sourceProviderId?: unknown;+ };+ return {+ reason: typeof parsed.reason === 'string' ? parsed.reason : undefined,+ sourceUserClientId:+ typeof parsed.sourceUserClientId === 'string' ? parsed.sourceUserClientId : null,+ ...(parsed.sourceAgentKind === 'cc' ||+ parsed.sourceAgentKind === 'codex' ||+ parsed.sourceAgentKind === 'pi'+ ? { sourceAgentKind: parsed.sourceAgentKind }+ : {}),+ ...(typeof parsed.sourceModel === 'string' ? { sourceModel: parsed.sourceModel } : {}),+ ...(typeof parsed.sourceProviderId === 'string'+ ? { sourceProviderId: parsed.sourceProviderId }+ : {}),+ };+ } catch {+ return null;+ }+}+export function broadcastMessageDeleted(payload: MessageDeletedPayload,ownerScope?: DataOwnerBroadcastScope | null,@@ -1127,9 +1206,7 @@ export async function supersedeRetriedUserTurn(const [retryRow] = await db.select({ createdAt: messages.createdAt, rowid: messageRowid }).from(messages)- .where(- and(eq(messages.sessionId, sessionId), eq(messages.clientId, args.retryUserClientId)),- )+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, args.retryUserClientId))).limit(1);if (!oldRow || !retryRow) return [];// 窗口两端都用 (created_at, rowid) 双键:error 行的 createdAt 取"本轮最后行 + 1",@@ -1310,7 +1387,8 @@ export async function createMessage(): Promise<Message> {const dbClient = getDbClient();const db = dbClient.drizzle;- const guarded = opts !== undefined && Object.prototype.hasOwnProperty.call(opts, 'expectedClearBoundaryMs');+ const guarded =+ opts !== undefined && Object.prototype.hasOwnProperty.call(opts, 'expectedClearBoundaryMs');const expected = guarded ? opts?.expectedClearBoundaryMs : undefined;if (guarded &&@@ -1337,7 +1415,7 @@ export async function createMessage(const visibleCreatedAt =guarded && expected !== null && expected !== undefined? Math.max(body.createdAt ?? now, expected + 1)- : body.createdAt ?? now;+ : (body.createdAt ?? now);const insertRow = messageCreateToRow(id, sessionId, body, visibleCreatedAt);try {if (guarded) {@@ -1769,8 +1847,7 @@ export async function readPriorUserRoundCost(if (isEstimate) estimatedCurrencies.add(segment.currency);}const money = addCompatibleRegionalMoney(values);- const hasEstimatedValue =- money !== null && estimatedCurrencies.has(money.currency);+ const hasEstimatedValue = money !== null && estimatedCurrencies.has(money.currency);return {money,costUsd: money?.currency === 'USD' ? money.amount : 0,@@ -2126,6 +2203,7 @@ export async function listMessagesForAgentHandoff(content: unknown;createdAt: number;agentMeta: Record<string, unknown> | null;+ toolUseId: string | null;}>> {const db = getDbClient().drizzle;@@ -2151,6 +2229,7 @@ export async function listMessagesForAgentHandoff(content: messages.content,createdAt: messages.createdAt,agentMeta: messages.agentMeta,+ toolUseId: messages.toolUseId,}).from(messages).where(@@ -2159,12 +2238,83 @@ export async function listMessagesForAgentHandoff(.orderBy(desc(messages.createdAt), desc(messageRowid)).limit(limit);rows.reverse();- return rows.map((r) => {+ return rows+ .map((r) => {+ let content: unknown = r.content;+ try {+ content = JSON.parse(r.content);+ } catch {+ // 与 messageToCamel 同口径:非法 JSON 保留原字符串+ }+ let agentMeta: Record<string, unknown> | null = null;+ if (r.agentMeta) {+ try {+ const parsed: unknown = JSON.parse(r.agentMeta);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ agentMeta = parsed as Record<string, unknown>;+ }+ } catch {+ // 非法 JSON 视为无 meta+ }+ }+ if (agentMeta && typeof agentMeta.contextRebuild === 'object' && agentMeta.contextRebuild) {+ return null;+ }+ return {+ clientId: r.clientId,+ role: r.role,+ content,+ createdAt: r.createdAt,+ agentMeta,+ toolUseId: r.toolUseId ?? null,+ };+ })+ .filter((row): row is NonNullable<typeof row> => row !== null);+}++/** 换窗身份用:不受 handoff 400 行窗口限制,找最近一条非 rewind 的 user。 */+export async function findLatestUserMessageForRebuild(sessionId: string): Promise<{+ clientId: string;+ role: string;+ content: unknown;+ createdAt: number;+ agentMeta: Record<string, unknown> | null;+ toolUseId: string | null;+} | null> {+ const db = getDbClient().drizzle;+ const [sessRow] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const clearedAt = sessRow?.clearedAt ?? null;+ const afterClear = clearedAt === null ? undefined : gt(messages.createdAt, clearedAt);+ const rows = await db+ .select({+ clientId: messages.clientId,+ role: messages.role,+ content: messages.content,+ createdAt: messages.createdAt,+ agentMeta: messages.agentMeta,+ toolUseId: messages.toolUseId,+ })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'user'),+ isNull(messages.rewindAt),+ afterClear,+ ),+ )+ .orderBy(desc(messages.createdAt), desc(messageRowid))+ .limit(30);+ for (const r of rows) {let content: unknown = r.content;try {content = JSON.parse(r.content);} catch {- // 与 messageToCamel 同口径:非法 JSON 保留原字符串+ // 与 messageToCamel 同口径}let agentMeta: Record<string, unknown> | null = null;if (r.agentMeta) {@@ -2177,8 +2327,25 @@ export async function listMessagesForAgentHandoff(// 非法 JSON 视为无 meta}}- return { clientId: r.clientId, role: r.role, content, createdAt: r.createdAt, agentMeta };- });+ const text =+ typeof content === 'string'+ ? content+ : content && typeof content === 'object' && !Array.isArray(content)+ ? typeof (content as { text?: unknown }).text === 'string'+ ? (content as { text: string }).text+ : ''+ : '';+ if (isSyntheticTriggerText(text)) continue;+ return {+ clientId: r.clientId,+ role: r.role,+ content,+ createdAt: r.createdAt,+ agentMeta,+ toolUseId: r.toolUseId ?? null,+ };+ }+ return null;}/** Phase 2:目标引擎的停泊原生会话(由最近一次"它离场"的边界行派生)。 */diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 559f11d11e..9c6c6eed73 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -383,6 +383,7 @@ export async function applyAgentSwitchToSessionRow(/** 目标引擎下的 effort / fastMode(意图登记时 renderer 按目标目录解析,apply 一并落库)。 */effort?: string;fastMode?: boolean;+ contextWindow?: number | null;},): Promise<void> {const ownerScope = captureOwnerScope();@@ -401,6 +402,9 @@ export async function applyAgentSwitchToSessionRow(setObj.effort = patch.effort as (typeof sessions.$inferInsert)['effort'];}if (patch.fastMode !== undefined) setObj.fastMode = patch.fastMode;+ if (typeof patch.contextWindow === 'number' && patch.contextWindow > 0) {+ setObj.contextWindow = Math.floor(patch.contextWindow);+ }await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));if (!isOwnerScopeCurrent(ownerScope)) return;broadcastSessionPatched(@@ -412,6 +416,9 @@ export async function applyAgentSwitchToSessionRow(...(patch.providerId !== undefined ? { providerId: patch.providerId } : {}),...(patch.effort !== undefined ? { effort: patch.effort } : {}),...(patch.fastMode !== undefined ? { fastMode: patch.fastMode } : {}),+ ...(typeof patch.contextWindow === 'number' && patch.contextWindow > 0+ ? { contextWindow: Math.floor(patch.contextWindow) }+ : {}),},ownerScope,);diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 7d123f16a8..7e84e908d4 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -77,6 +77,8 @@ export function tx(db: Database.Database, args: unknown): unknown {return sessionsSetStatus(db, txArgs);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(db, txArgs);+ case 'context.rebuild':+ return contextRebuild(db, txArgs);case 'message.delete':return messageDelete(db, txArgs);case 'im.deleteBindings':@@ -217,6 +219,39 @@ function sessionAgentSwitchFallback(db: Database.Database, args: unknown): voidtransaction();}+/** 同一任务换干净原生会话:清 sdk_session_id + 追加隐藏 context_rebuild,不改可见消息。 */+function contextRebuild(db: Database.Database, args: unknown): void {+ const payload = asRecord(args, 'context.rebuild args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const markerId = expectString(payload.markerId, 'markerId');+ const markerClientId = expectString(payload.markerClientId, 'markerClientId');+ const markerContent = expectString(payload.markerContent, 'markerContent');+ const markerCreatedAt = expectNumber(payload.markerCreatedAt, 'markerCreatedAt');+ const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ const expectedClearedAt =+ payload.expectedClearedAt === undefined || payload.expectedClearedAt === null+ ? null+ : expectNumber(payload.expectedClearedAt, 'expectedClearedAt');+ const transaction = db.transaction(() => {+ const sessionResult = db+ .prepare(+ 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ? WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',+ )+ .run(updatedAt, sessionId, expectedClearedAt);+ if (sessionResult.changes !== 1) {+ throw Object.assign(new Error(`Session missing or clear-boundary changed: ${sessionId}`), {+ code: 'PRECONDITION_FAILED',+ });+ }+ // 只追加新边界。删掉更早的 context_rebuild 会让 fork 在「A 重建 → 切 B → B 再重建」+ // 后误把 A 重建前的消息接到 A 重建后的 SDK session。+ db.prepare(+ "INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, 'context_rebuild', ?, ?, ?)",+ ).run(markerId, markerClientId, sessionId, markerContent, markerCreatedAt, markerCreatedAt);+ });+ transaction();+}+/** 一轮消息内容清除 + 原生上下文失效 + 隐藏重建标记,三者同成同败。 */function messageDelete(db: Database.Database,diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.tsindex 3db271a12a..ba1911eb32 100644--- a/apps/desktop/src/main/maker-host/runtime-configs.ts+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts@@ -28,6 +28,10 @@ import { readMemorySettings } from './memory-settings-store.js';import { readSubagentModelSettings } from './subagent-model-settings-store.js';import { shouldKeepSubagentOverrideForParent } from './subagent-override-route.js';import { toolchainThreadCapEnv } from './toolchain-thread-cap.js';+import {+ assessModelSwitchContext,+ shouldHandoffAfterContextAssessment,+} from '../../shared/modelSwitchAssessment.js';// Claude / Codex 的 host system prompt:产品身份 → Skill 来源优先级 → agent 专属段。// Skill 优先级不放 host-system-prompt.md,避免把 #1645 的 Claude/Codex 行为扩到 Pi。@@ -203,6 +207,18 @@ export function buildDesktopClaudeRuntimeConfig(endpointFn: () => string): Agentenumerable: true,configurable: false,});+ Object.defineProperty(config, 'shouldHandoffAfterContextAssessment', {+ value: (contextTokens: number, contextWindow: number) =>+ shouldHandoffAfterContextAssessment(+ assessModelSwitchContext({+ contextTokens,+ targetContextWindow: contextWindow,+ autoCompactThresholdPct: readCompactionPct(),+ }),+ ),+ enumerable: true,+ configurable: false,+ });Object.defineProperty(config, 'subagentModel', {// 无路由上下文的兜底口径(subagentModelForRoute 缺席的消费方用):目录里该模型// 的所有拷贝都被停用才丢弃覆写。diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 8b44a10fe6..d280071b49 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -276,6 +276,9 @@ function createHarness(opts?: {const onRejectedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['onRejectedUserTurn']>>(() => {},);+ const persistTerminalSendError = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['persistTerminalSendError']>+ >(() => {});const supersedeRetriedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['supersedeRetriedUserTurn']>>(async () => []);@@ -289,6 +292,7 @@ function createHarness(opts?: {previewQueuedUserTurn,onDiscardedQueuedMessage,onRejectedUserTurn,+ persistTerminalSendError,supersedeRetriedUserTurn,isTurnRunning: () => running,isLiveTurnRunning: () => {@@ -368,6 +372,7 @@ function createHarness(opts?: {previewQueuedUserTurn,onDiscardedQueuedMessage,onRejectedUserTurn,+ persistTerminalSendError,supersedeRetriedUserTurn,setRunning(value: boolean) {running = value;@@ -1797,6 +1802,25 @@ describe('AgentInputCoordinator send transaction', () => {);});+ it('persists the agent-facing wire payload for mention messages', async () => {+ const h = createHarness();+ const sid = 'persist-wire-mentions';+ const item = makeItem('q-1', 'look at this', {+ mentions: [{ type: 'file', name: 'README.md', path: '/repo/README.md' }],+ });+ h.coordinator.enqueue(sid, item);+ await flush();+ expect(h.sendToAgent.mock.calls[0]?.[3]?.persistUserMessage?.agentFacingWireContent).toEqual(+ h.sendToAgent.mock.calls[0]?.[1],+ );+ const wire = h.sendToAgent.mock.calls[0]?.[1] as { content?: unknown };+ expect(wire.content).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: 'mention', path: '/repo/README.md' }),+ ]),+ );+ });+it('dispatches silent compact without persisting a user bubble', async () => {const h = createHarness();const sid = 'compact-silent';@@ -3836,6 +3860,12 @@ describe('AgentInputCoordinator send transaction', () => {expect.objectContaining(first),'failed',);+ expect(h.persistTerminalSendError).toHaveBeenCalledWith(sid, 'turn/start failed');++ h.coordinator.retryLastError(sid);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(latestProjection(h.projections).error).toBeNull();});it('dispatches new text after a persisted Pi image capability rejection', async () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.tsindex f77b6447ec..026472b154 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts@@ -194,7 +194,7 @@ describe('buildForkOriginHandoff', () => {const text = buildForkOriginHandoff('sess-parent-2');expect(text).not.toContain('search_chat_history');expect(text).not.toContain('get_chat_history');- expect(text).not.toContain('== Work state');+ expect(text).not.toContain('== Work ledger');expect(text.split('\n').filter((line) => line.trim().length > 0)).toHaveLength(3);});});@@ -548,7 +548,7 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>],opts,);- expect(text).toContain('== Work state (auto-extracted) ==');+ expect(text).toContain('== Work ledger (auto-extracted) ==');expect(text).toContain('- /repo/a.ts');expect(text).toContain('- /repo/b.ts');expect(text).toContain('- /repo/c.ts');@@ -573,7 +573,32 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>it('无工具活动时不渲染工作状态区', () => {const text = buildHandoffText([msg('user', '你好'), msg('assistant', '你好!')], opts);- expect(text).not.toContain('== Work state');+ expect(text).not.toContain('== Work ledger');+ });++ it('把命令与 tool_result 成败收进 ledger,不把整段 stdout 写进去', () => {+ const text = buildHandoffText(+ [+ msg('user', '跑测试'),+ {+ role: 'tool_use',+ content: { toolName: 'Bash', input: { command: 'pnpm test:unit' } },+ createdAt: 0,+ toolUseId: 't1',+ },+ {+ role: 'tool_result',+ content: `${'FAIL src/foo.test.ts\n'.repeat(40)}exit code 1`,+ createdAt: 1,+ toolUseId: 't1',+ },+ ],+ opts,+ );+ 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');});it('framing 包含「先核对工作区、以工作区为准」纪律', () => {@@ -593,6 +618,9 @@ describe('buildHandoffText 早期原文检索指引', () => {expect(text).toContain('search_chat_history');expect(text).toContain('get_chat_history');expect(text).toContain('"session_ids":["sess-abc"]');+ expect(text).toContain('"limit":10');+ expect(text).toContain('"limit":20');+ expect(text).toContain('Never request the default 200-row page');// 指引在结束标记之前expect(text.indexOf('Retrieving earlier verbatim history')).toBeLessThan(text.indexOf('End of handoff note'),@@ -712,6 +740,9 @@ describe('buildHandoffText 超限收缩保住首尾', () => {sessionId: 'sess-cap',});expect(text.length).toBe(16_000); // 确实顶到上限 = 确实走了兜底分支+ expect(text).toContain('"session_ids":["sess-cap"]');+ expect(text).toContain('"limit":10');+ expect(text).toContain('"limit":20');expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows ==")).toBe(true);});@@ -728,6 +759,22 @@ describe('buildHandoffText 超限收缩保住首尾', () => {.toBe(true);});+ it('context-overflow 走隐藏重建 framing,不用可见的 agent-switch 口径', () => {+ const text = buildHandoffText([msg('user', '继续改'), msg('assistant', '好')], {+ fromLabel: 'Pi',+ toLabel: 'Pi',+ sessionId: 'sess-overflow',+ reason: 'context-overflow',+ });+ expect(text).toContain("exceeded the model's context window");+ expect(text).toContain('[Session context rebuild · internal context]');+ expect(text).not.toContain('from here on you (Pi) continue it');+ expect(text).toContain('"limit":10');+ expect(text.trimEnd().endsWith("== End of rebuild note; the user's new message follows ==")).toBe(+ true,+ );+ });+it('单轮 100 条 tool_use 折叠中部,且硬上限/检索段/结束标记全部存活', () => {const messages: HandoffSourceMessage[] = [msg('user', '执行大量工具')];for (let i = 0; i < 100; i++) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.tsnew file mode 100644index 0000000000..753966d408--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts@@ -0,0 +1,687 @@+import { describe, expect, it, vi } from 'vitest';++import {+ createContextOverflowRollover,+ effectivePiContextWindow,+ findLatestRebuildableError,+ lookupVerifiedContextWindow,+ isContextOverflowErrorData,+ isPiPromptRpcTimeoutError,+ persistedUserContentToWireMessage,+ planContextOverflowRollover,+ shouldRebuildForContextPressure,+ shouldRebuildPiNativeSession,+ type OverflowSourceMessage,+} from '../contextOverflowRollover';++function msg(+ role: string,+ content: unknown,+ clientId: string,+ createdAt = 0,+): OverflowSourceMessage {+ return { role, content, clientId, createdAt };+}++describe('isContextOverflowErrorData', () => {+ it('accepts the stable reason and the xAI prompt-length phrasing', () => {+ expect(isContextOverflowErrorData({ reason: 'context-overflow', message: 'nope' })).toBe(true);+ expect(+ isContextOverflowErrorData({+ message:+ 'API Error: 400 litellm.BadRequestError: XaiException - {"code":"invalid-argument","error":"This model\'s maximum prompt length is 500000 but the request contains 637815 tokens."}',+ }),+ ).toBe(true);+ });++ it('rejects generic invalid-argument and other 4xx families', () => {+ expect(+ isContextOverflowErrorData({+ message: '{"code":"invalid-argument","error":"unsupported field: foo"}',+ }),+ ).toBe(false);+ expect(+ isContextOverflowErrorData({ message: 'Rate limit exceeded: too many tokens per minute' }),+ ).toBe(false);+ });+});++describe('shouldRebuildPiNativeSession', () => {+ it('treats a PI prompt RPC timeout as an unhealthy native session', () => {+ expect(isPiPromptRpcTimeoutError({ message: 'pi rpc timeout after 30000ms: prompt' })).toBe(+ true,+ );+ expect(shouldRebuildPiNativeSession({ message: 'pi rpc timeout after 30000ms: prompt' })).toBe(+ true,+ );+ });++ it('treats Grok 4 remaining-window pressure as a rebuild even if the DB window is inflated', () => {+ expect(effectivePiContextWindow('x-ai/grok-4.6', 1_050_000)).toBe(500_000);+ expect(effectivePiContextWindow('x-ai/grok-4.6', 1_050_000, 500_000)).toBe(500_000);+ expect(+ lookupVerifiedContextWindow(+ (_agentKind, id) => (id === 'grok-4.6' ? 500_000 : null),+ 'x-ai/grok-4.6',+ ),+ ).toBe(500_000);+ expect(shouldRebuildForContextPressure(553_582, 1_050_000)).toBe(false);+ expect(+ shouldRebuildForContextPressure(+ 553_582,+ effectivePiContextWindow('x-ai/grok-4.6', 1_050_000),+ ),+ ).toBe(true);+ expect(shouldRebuildForContextPressure(400_000, 500_000)).toBe(false);+ expect(shouldRebuildForContextPressure(400_000, 500_000, 75)).toBe(true);+ expect(shouldRebuildForContextPressure(450_000, 500_000)).toBe(true);+ });++ it('resolves a verified window with the session agent and explicit provider', () => {+ const resolve = vi.fn((agentKind: string, modelId: string, providerId: string | null) =>+ agentKind === 'codex' && modelId === 'gpt-5.6' && providerId === 'xd' ? 372_000 : null,+ );++ expect(lookupVerifiedContextWindow(resolve, 'gpt-5.6', 'xd', 'codex')).toBe(372_000);+ expect(resolve).toHaveBeenCalledWith('codex', 'gpt-5.6', 'xd');+ expect(resolve).not.toHaveBeenCalledWith('codex', 'gpt-5.6', 'xai');+ });++ it('does not borrow the xAI route when the session provider is unresolved', () => {+ const resolve = vi.fn((_agentKind: string, _modelId: string, providerId: string | null) =>+ providerId === 'xai' ? 500_000 : null,+ );++ expect(lookupVerifiedContextWindow(resolve, 'grok-4.6')).toBeNull();+ expect(resolve).toHaveBeenCalledWith('pi', 'grok-4.6', null);+ expect(resolve).not.toHaveBeenCalledWith('pi', 'grok-4.6', 'xai');+ });++ it('does not rebuild on other PI RPC timeouts', () => {+ expect(+ shouldRebuildPiNativeSession({ message: 'pi rpc timeout after 30000ms: set_model' }),+ ).toBe(false);+ });++ it('finds a trailing prompt-timeout error as the reason to skip resume', () => {+ expect(+ findLatestRebuildableError([+ msg('user', '还有建议吗', 'u1'),+ msg('error', { message: 'pi rpc timeout after 30000ms: prompt' }, 'e1'),+ ]),+ ).toEqual({ message: 'pi rpc timeout after 30000ms: prompt' });+ expect(+ findLatestRebuildableError([+ msg('user', '还有建议吗', 'u1'),+ msg('assistant', '这是回答', 'a1'),+ ]),+ ).toBeNull();+ expect(+ findLatestRebuildableError(+ [+ msg('user', '继续', 'u1'),+ msg('error', { message: 'pi rpc timeout after 30000ms: prompt' }, 'e1'),+ ],+ false,+ ),+ ).toBeNull();+ });+});++describe('planContextOverflowRollover', () => {+ it('cuts handoff before the failed user message and keeps that row for wire replay', () => {+ const plan = planContextOverflowRollover([+ msg('user', '先做 A', 'u1', 1),+ msg('assistant', '做完 A', 'a1', 2),+ msg('user', '再做 B', 'u2', 3),+ ]);+ expect(plan).toMatchObject({+ action: 'rebuild',+ sourceUserClientId: 'u2',+ sourceUserContent: '再做 B',+ });+ if (plan.action !== 'rebuild') throw new Error('expected rebuild');+ expect(plan.handoffMessages.map((item) => item.clientId)).toEqual(['u1', 'a1']);+ });++ it('stops when the overflowing turn already produced assistant text or tools', () => {+ expect(+ planContextOverflowRollover([+ msg('user', '改文件', 'u1'),+ msg('tool_use', { toolName: 'Edit', input: { file_path: '/repo/a.ts' } }, 't1'),+ ]).action,+ ).toBe('stop');+ expect(+ planContextOverflowRollover([msg('user', '继续', 'u1'), msg('assistant', '先说一句', 'a1')]),+ ).toMatchObject({ action: 'stop', reason: 'has-side-effects' });+ expect(+ planContextOverflowRollover([+ msg('user', '问你一个问题', 'u1'),+ msg('ask_user', { prompt: '选哪个?' }, 'q1'),+ ]),+ ).toMatchObject({ action: 'stop', reason: 'has-side-effects' });+ });++ it('does not treat a later error card as side effects', () => {+ const plan = planContextOverflowRollover([+ msg('user', '继续', 'u1'),+ msg('error', 'context overflow', 'e1'),+ ]);+ expect(plan.action).toBe('rebuild');+ });++ it('refuses a second rollover of the same user message', () => {+ expect(planContextOverflowRollover([msg('user', '继续', 'u1')], 'u1')).toMatchObject({+ action: 'stop',+ reason: 'already-rolled',+ });+ });+});++describe('createContextOverflowRollover', () => {+ function makeDeps(source: OverflowSourceMessage[]) {+ return {+ getSessionRow: vi.fn(async () => ({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null as string | null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 0,+ contextWindow: 200_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ })),+ listMessages: vi.fn(async () => source),+ findLatestUser: vi.fn(async (): Promise<OverflowSourceMessage | null> => null),+ findLatestRebuildMeta: vi.fn(async () => null),+ getLiveSession: vi.fn(+ (): {+ isTurnRunning(): boolean;+ getUsageSnapshot?: () => { contextTokens: number; contextWindow: number };+ } => ({ isTurnRunning: () => false }),+ ),+ closeSession: vi.fn(async () => undefined),+ getAutoCompactThresholdPct: undefined as (() => number | undefined) | undefined,+ drainPersistQueue: vi.fn(async () => undefined),+ commitRebuild: vi.fn(async () => undefined),+ setPendingHandoff: vi.fn(),+ readPendingHandoffGeneration: vi.fn(() => 3),+ replayUserMessage: vi.fn(async () => ({ accepted: true })),+ onRebuilt: vi.fn(),+ withCloseSuppressed: async <T>(_sessionId: string, fn: () => Promise<T>) => fn(),+ log: { info: vi.fn(), warn: vi.fn() },+ };+ }++ it('rebuilds once, injects handoff, and wire-replays the same user content', async () => {+ const deps = makeDeps([+ msg('user', '先做 A', 'u1', 1),+ msg('assistant', '做完 A', 'a1', 2),+ msg('user', '再做 B', 'u2', 3),+ ]);+ const rollover = createContextOverflowRollover(deps);+ expect(rollover.claim('s1')).toBe('claimed');+ expect(rollover.claim('s1')).toBe('in-flight');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(true);+ expect(deps.closeSession).toHaveBeenCalledWith('s1');+ expect(deps.commitRebuild).toHaveBeenCalledWith(+ 's1',+ expect.stringContaining("exceeded the model's context window"),+ expect.objectContaining({+ reason: 'context-overflow',+ sourceUserClientId: 'u2',+ sourceAgentKind: 'pi',+ sourceModel: 'x-ai/grok-4.6',+ sourceProviderId: 'xai',+ expectedClearedAt: null,+ }),+ );+ expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', expect.any(String), 3);+ expect(deps.setPendingHandoff.mock.calls[0]?.[1]).toContain('先做 A');+ expect(deps.setPendingHandoff.mock.calls[0]?.[1]).not.toContain('再做 B');+ expect(deps.replayUserMessage).toHaveBeenCalledWith('s1', '再做 B');+ expect(deps.onRebuilt).toHaveBeenCalledWith('s1');+ expect(deps.replayUserMessage.mock.invocationCallOrder[0]).toBeLessThan(+ deps.onRebuilt.mock.invocationCallOrder[0],+ );+ });++ it('keeps coordinator recovery when replay is rejected', async () => {+ const deps = makeDeps([msg('user', '再做 B', 'u2')]);+ deps.replayUserMessage.mockResolvedValue({ accepted: false });+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(false);+ expect(deps.commitRebuild).toHaveBeenCalled();+ expect(deps.onRebuilt).not.toHaveBeenCalled();+ });++ it('rebuilds scheduler/IM turns without generic replay so the owner retries', async () => {+ const deps = makeDeps([+ {+ ...msg('user', '心跳任务', 'u-sched'),+ agentMeta: { origin: { kind: 'scheduler', scheduleId: 'sch-1', scheduleName: 'PR 心跳' } },+ },+ ]);+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(true);+ expect(deps.commitRebuild).toHaveBeenCalled();+ expect(deps.setPendingHandoff).toHaveBeenCalled();+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ expect(deps.onRebuilt).not.toHaveBeenCalled();+ });++ it('marks external-origin turns as skipGenericReplay in the plan', () => {+ const plan = planContextOverflowRollover([+ {+ ...msg('user', 'from im', 'u-im'),+ agentMeta: { origin: { kind: 'im', channel: 'feishu' } },+ },+ ]);+ expect(plan).toMatchObject({ action: 'rebuild', skipGenericReplay: true });+ });++ it('treats any origin.kind as an external owner, including orca', () => {+ expect(+ planContextOverflowRollover([+ {+ ...msg('user', 'from orca', 'u-orca'),+ agentMeta: { origin: { kind: 'orca', senderLabel: 'Lead' } },+ },+ ]),+ ).toMatchObject({ action: 'rebuild', skipGenericReplay: true });+ expect(+ planContextOverflowRollover([msg('user', 'from cindy chat', 'u-user')]),+ ).toMatchObject({ action: 'rebuild', skipGenericReplay: false });+ });++ it('rebuilds orca turns without generic replay so the owner retries', async () => {+ const deps = makeDeps([+ {+ ...msg('user', '派给 worker', 'u-orca'),+ agentMeta: { origin: { kind: 'orca', senderLabel: 'Lead', displayText: '派给 worker' } },+ },+ ]);+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(true);+ expect(deps.commitRebuild).toHaveBeenCalled();+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ expect(deps.onRebuilt).not.toHaveBeenCalled();+ });++ it('does not replay when the failed turn already had tool side effects', async () => {+ const deps = makeDeps([+ msg('user', '改文件', 'u1'),+ msg('tool_use', { toolName: 'Edit', input: { file_path: '/repo/a.ts' } }, 't1'),+ ]);+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(false);+ expect(deps.commitRebuild).not.toHaveBeenCalled();+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ });++ it('rebuilds before send when Grok context is already over the real window', async () => {+ const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 553_582,+ contextWindow: 1_050_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ });+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ expect(deps.commitRebuild).toHaveBeenCalled();+ expect(deps.onRebuilt).toHaveBeenCalledWith('s1');+ });++ it('uses the host compact threshold when deciding pre-send pressure rebuild', async () => {+ const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 400_000,+ contextWindow: 500_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ });+ deps.getAutoCompactThresholdPct = vi.fn(() => 75);+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(deps.commitRebuild).toHaveBeenCalled();+ });++ it('uses the same pressure guard for Claude Code and Codex before send', async () => {+ for (const agentKind of ['cc', 'codex'] as const) {+ const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind,+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: `/tmp/dead-${agentKind}`,+ contextTokens: 400_000,+ contextWindow: 500_000,+ model: 'model',+ providerId: 'xd',+ });+ deps.getAutoCompactThresholdPct = vi.fn(() => 75);+ const rollover = createContextOverflowRollover(deps);++ await expect(rollover.prepareUnhealthySession(`session-${agentKind}`)).resolves.toBe(true);+ expect(deps.commitRebuild).toHaveBeenCalled();+ deps.commitRebuild.mockClear();+ }+ });++ it('fails closed when a pre-send rebuild cannot commit', async () => {+ const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'codex',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: 'dead-thread',+ contextTokens: 400_000,+ contextWindow: 500_000,+ model: 'gpt-5.6',+ providerId: 'xd',+ });+ deps.getAutoCompactThresholdPct = vi.fn(() => 75);+ deps.commitRebuild.mockRejectedValue(new Error('db unavailable'));+ const rollover = createContextOverflowRollover(deps);++ await expect(rollover.prepareUnhealthySession('s1')).rejects.toThrow('db unavailable');+ });++ it('drains persist queue before reading messages on prepare', async () => {+ const order: string[] = [];+ const deps = makeDeps([+ msg('user', '还有建议吗', 'u1'),+ msg('error', { message: 'pi rpc timeout after 30000ms: prompt' }, 'e1'),+ ]);+ deps.drainPersistQueue.mockImplementation(async () => {+ order.push('drain');+ });+ deps.listMessages.mockImplementation(async () => {+ order.push('list');+ return [+ msg('user', '还有建议吗', 'u1'),+ msg('error', { message: 'pi rpc timeout after 30000ms: prompt' }, 'e1'),+ ];+ });+ const rollover = createContextOverflowRollover(deps);+ await rollover.prepareUnhealthySession('s1');+ expect(order[0]).toBe('drain');+ expect(order).toContain('list');+ expect(order.indexOf('drain')).toBeLessThan(order.indexOf('list'));+ });++ it('rebuilds a timed-out PI session before send without replaying', async () => {+ const deps = makeDeps([+ msg('user', '还有建议吗', 'u1'),+ msg('error', { message: 'pi rpc timeout after 30000ms: prompt' }, 'e1'),+ ]);+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(deps.closeSession).toHaveBeenCalledWith('s1');+ expect(deps.commitRebuild).toHaveBeenCalled();+ expect(deps.setPendingHandoff).toHaveBeenCalled();+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ expect(deps.setPendingHandoff.mock.calls[0]?.[1]).not.toContain('还有建议吗');+ expect(deps.setPendingHandoff.mock.calls[0]?.[1]).toContain('stopped responding to prompts');+ expect(deps.commitRebuild).toHaveBeenCalledWith(+ 's1',+ expect.any(String),+ expect.objectContaining({ reason: 'pi-prompt-timeout' }),+ );+ });++ it('omits a still-pending last user from prepare handoff', async () => {+ const deps = makeDeps([+ msg('user', '先做 A', 'u1'),+ msg('assistant', '好', 'a1'),+ msg('user', 'IM 待发', 'u-pending'),+ ]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 400_000,+ contextWindow: 500_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ });+ deps.getAutoCompactThresholdPct = vi.fn(() => 75);+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ const handoff = String(deps.setPendingHandoff.mock.calls[0]?.[1] ?? '');+ expect(handoff).toContain('先做 A');+ expect(handoff).not.toContain('IM 待发');+ });++ it('keeps a completed last user in prepare handoff', async () => {+ const deps = makeDeps([+ msg('user', '先做 A', 'u1'),+ msg('assistant', '已完成', 'a1'),+ ]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 400_000,+ contextWindow: 500_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ });+ deps.getAutoCompactThresholdPct = vi.fn(() => 75);+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(String(deps.setPendingHandoff.mock.calls[0]?.[1] ?? '')).toContain('先做 A');+ });++ it('prefers live usage over a stale DB context snapshot', async () => {+ const deps = makeDeps([msg('user', '先做 A', 'u1'), msg('assistant', '好', 'a1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 1_000,+ contextWindow: 500_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ });+ deps.getLiveSession.mockReturnValue({+ isTurnRunning: () => false,+ getUsageSnapshot: () => ({ contextTokens: 450_000, contextWindow: 500_000 }),+ });+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(deps.commitRebuild).toHaveBeenCalled();+ });++ it('finds last user outside the bounded handoff window', async () => {+ const deps = makeDeps([+ msg('tool_use', { toolName: 'Edit' }, 't1'),+ msg('tool_result', { output: 'ok' }, 'tr1'),+ ]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'pi',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead.jsonl',+ contextTokens: 450_000,+ contextWindow: 500_000,+ model: 'x-ai/grok-4.6',+ providerId: 'xai',+ });+ deps.findLatestUser.mockResolvedValue(msg('user', '先做 A', 'u-old'));+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(deps.commitRebuild).toHaveBeenCalledWith(+ 's1',+ expect.any(String),+ expect.objectContaining({ sourceUserClientId: 'u-old' }),+ );+ });++ it('does not auto-replay a prompt RPC timeout as context-overflow', async () => {+ const deps = makeDeps([+ msg('user', '还有建议吗', 'u1'),+ msg('error', { message: 'pi rpc timeout after 30000ms: prompt' }, 'e1'),+ ]);+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { message: 'pi rpc timeout after 30000ms: prompt' }),+ ).resolves.toBe(false);+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ });++ it('treats an unaccepted replay as recovery failure', async () => {+ const deps = makeDeps([msg('user', '再做 B', 'u2')]);+ deps.replayUserMessage.mockResolvedValue({ accepted: false });+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(false);+ });++ it('rolls over a local Claude Code session on explicit overflow', async () => {+ const deps = makeDeps([msg('user', '继续', 'u1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'cc',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead-claude.jsonl',+ contextTokens: 0,+ contextWindow: 0,+ model: '',+ providerId: '',+ });+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(true);+ expect(deps.closeSession).toHaveBeenCalledWith('s1');+ });++ it('rolls over a local Codex session on explicit overflow', async () => {+ const deps = makeDeps([msg('user', '继续', 'u1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'codex',+ remoteHostId: null,+ clearedAt: null,+ sdkSessionId: '/tmp/dead-codex-thread',+ contextTokens: 0,+ contextWindow: 0,+ model: '',+ providerId: '',+ });+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');+ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(true);+ expect(deps.closeSession).toHaveBeenCalledWith('s1');+ });++ it('keeps remote sessions out of automatic rollover', async () => {+ const deps = makeDeps([msg('user', '继续', 'u1')]);+ deps.getSessionRow.mockResolvedValue({+ status: 'active',+ agentKind: 'codex',+ remoteHostId: 'remote-1',+ clearedAt: null,+ sdkSessionId: 'thread-1',+ contextTokens: 500_000,+ contextWindow: 500_000,+ model: 'gpt-5.6',+ providerId: 'xd',+ });+ const rollover = createContextOverflowRollover(deps);+ rollover.claim('s1');++ await expect(+ rollover.tryRecover('s1', { reason: 'context-overflow', message: 'prompt too long' }),+ ).resolves.toBe(false);+ expect(deps.closeSession).not.toHaveBeenCalled();+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(deps.commitRebuild).not.toHaveBeenCalled();+ });+});++describe('persistedUserContentToWireMessage', () => {+ it('replays the retained agent-facing payload without projecting it to display text', () => {+ const wirePayload = {+ type: 'user' as const,+ content: [+ { type: 'text', text: '原始引用语义' },+ { type: 'text', text: 'SESSION_REFERENCE_DATA_V1\nquoted context' },+ ],+ };+ expect(+ persistedUserContentToWireMessage({+ text: '显示给用户的正文',+ agentFacingWireContent: wirePayload,+ }),+ ).toEqual(wirePayload);+ });++ it('projects structured references for legacy persisted messages', () => {+ const href = 'cindy://project/%2Frepos%2Fcindy';+ const text = `请处理 ${href}`;+ expect(+ persistedUserContentToWireMessage({+ text,+ agentReferences: [+ {+ kind: 'project',+ start: text.indexOf(href),+ end: text.indexOf(href) + href.length,+ href,+ name: 'src',+ workingDir: '/repo/src',+ },+ ],+ images: [],+ files: [],+ }),+ ).toBe(+ '请处理 [Referenced project]\nName: src\nWorking directory: /repos/cindy\n[/Referenced project]',+ );+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 38265ffef8..4ed41cc0c1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -1814,4 +1814,36 @@ describe('session-agent-switch handoff injection', () => {// 5. accepted 之后才消费交接(未派发则保留下次重试)。expect(consumePendingHandoff).toHaveBeenCalledWith('session-1');});++ it('overflow prepare 在 getSession 之前;peek 不再关掉发送目标', async () => {+ const callOrder: string[] = [];+ let unhealthy = true;+ const fresh = createSession();+ const { deps } = createDeps({+ prepareUnhealthySession: vi.fn(async () => {+ callOrder.push('prepare');+ unhealthy = false;+ }),+ getSession: vi.fn(() => {+ callOrder.push('getSession');+ return unhealthy ? createSession({ getStatus: () => 'closed' as const }) : fresh;+ }),+ peekPendingHandoff: vi.fn(async () => {+ callOrder.push('peek');+ return 'OVERFLOW-HANDOFF';+ }),+ });+ const transaction = createMakerSendTransaction(deps);+ await transaction.sendToAgentAccepted('session-1', { type: 'user', content: '继续' }, {+ agentKind: 'codex',+ workingDir: '/tmp/w',+ });++ expect(callOrder.indexOf('prepare')).toBeGreaterThanOrEqual(0);+ expect(callOrder.indexOf('prepare')).toBeLessThan(callOrder.indexOf('getSession'));+ expect(callOrder.indexOf('getSession')).toBeLessThan(callOrder.indexOf('peek'));+ expect(fresh.send).toHaveBeenCalledTimes(1);+ const sent = vi.mocked(fresh.send).mock.calls[0]?.[0] as { content: string };+ expect(sent.content).toContain('OVERFLOW-HANDOFF');+ });});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.tsindex c71801aab1..b48f2a6577 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts@@ -141,6 +141,9 @@ describe('Orca lead/worker dispatcher', () => {clientId: 'client-1',role: 'user',content: '{"orcaSource":"lead","content":"Implement feature"}',+ agentMeta: {+ origin: { kind: 'orca', senderLabel: 'Lead', displayText: 'Implement feature' },+ },});expect(h.liveSession.send).toHaveBeenCalledWith({diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 09e4b4f254..14e9804870 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -209,6 +209,8 @@ export interface AgentInputSendOpts {persistUserMessage?: {clientId: string;content: string;+ /** Overflow 重放用的 agent-facing wire payload(mention / 标注附件等)。 */+ agentFacingWireContent?: unknown;sdkSessionId?: string;delivery: AgentInputDelivery;expectedClearBoundaryMs?: number | null;@@ -427,6 +429,13 @@ export interface AgentInputCoordinatorDeps {*//** Technical or policy rejection before vendor dispatch. */onRejectedUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;+ /**+ * 用户消息已落库、但 vendor 派发失败时补一条可重试的 error 行。+ * 没有这条,聊天里只剩用户气泡、没有红条,重试入口也不稳定。+ */+ persistTerminalSendError?: (sessionId: string, message: string) => void;+ /** 已落库但 vendor reject:宿主可关掉卡住的原生会话,等用户重试再换窗。 */+ onPersistedSendRejected?: (sessionId: string, message: string) => void;onAcceptedQueuedMessage?: (sessionId: string,item: AgentInputQueuedMessage,@@ -1862,11 +1871,7 @@ export class AgentInputCoordinator {// marker 已置位,筛查期间并发 steer / drain 被挡;stop / clearSession 竞态// 由筛查后的 marker 复查兜底。if (!item.bypassGhostHooks && this.deps.screenUserMessage) {- const verdict = await this.deps.screenUserMessage(- sessionId,- getAgentFacingText(item),- item,- );+ const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(item), item);const cur = this.getState(sessionId);const ownsCurrentRequest = this.isCurrentSteerRequest(cur,@@ -1874,10 +1879,7 @@ export class AgentInputCoordinator {steerGeneration,steerRequestToken,);- if (- !ownsCurrentRequest ||- !matchesExpectedTurn()- ) {+ if (!ownsCurrentRequest || !matchesExpectedTurn()) {// stop/close/clearSession 赢在筛查期间:steer 事务已被取消,静默放弃。if (ownsCurrentRequest &&@@ -2207,14 +2209,7 @@ export class AgentInputCoordinator {const persisted = await this.persistAcceptedUserMessage(sessionId, accepted.activeTurn);const settled = this.getState(sessionId);let releasedSteerMarker = false;- if (- this.isCurrentSteerRequest(- settled,- item.clientId,- steerGeneration,- steerRequestToken,- )- ) {+ if (this.isCurrentSteerRequest(settled, item.clientId, steerGeneration, steerRequestToken)) {releasedSteerMarker = this.clearSteeringMarker(settled, item.clientId, {generation: steerGeneration,token: steerRequestToken,@@ -3356,16 +3351,29 @@ export class AgentInputCoordinator {if (typeof projected.text === 'string' && projected.text.includes(RECOVERY_CHECKPOINT_MARKER)) {projected.text = projected.text.slice(0, projected.text.indexOf(RECOVERY_CHECKPOINT_MARKER));}- if (typeof projected.persistedContent === 'string' && projected.persistedContent.includes(RECOVERY_CHECKPOINT_MARKER)) {- projected.persistedContent = projected.persistedContent.slice(0, projected.persistedContent.indexOf(RECOVERY_CHECKPOINT_MARKER));+ if (+ typeof projected.persistedContent === 'string' &&+ projected.persistedContent.includes(RECOVERY_CHECKPOINT_MARKER)+ ) {+ projected.persistedContent = projected.persistedContent.slice(+ 0,+ projected.persistedContent.indexOf(RECOVERY_CHECKPOINT_MARKER),+ );}// chatMessage.content is the outbound payload sent to remote controllers// (device-link); it must mirror the same strip so the checkpoint marker// never leaks past transport boundaries.- if (projected.chatMessage && typeof projected.chatMessage.content === 'string' && projected.chatMessage.content.includes(RECOVERY_CHECKPOINT_MARKER)) {+ if (+ projected.chatMessage &&+ typeof projected.chatMessage.content === 'string' &&+ projected.chatMessage.content.includes(RECOVERY_CHECKPOINT_MARKER)+ ) {projected.chatMessage = {...projected.chatMessage,- content: projected.chatMessage.content.slice(0, projected.chatMessage.content.indexOf(RECOVERY_CHECKPOINT_MARKER)),+ content: projected.chatMessage.content.slice(+ 0,+ projected.chatMessage.content.indexOf(RECOVERY_CHECKPOINT_MARKER),+ ),};}return projected;@@ -3675,84 +3683,81 @@ export class AgentInputCoordinator {head.persistedContent,referenceContexts,);- const result = await this.deps.sendToAgent(- sessionId,- buildMakerUserMessage(head, referenceContexts),- head.createOpts,- {- messageUuid: active.messageUuid,- userName: head.userName,- throwOnStartFailure: true,- ...(head.autoResume && typeof head.autoResumeInfo?.sessionTotal === 'number'- ? { turnAttemptToken: head.autoResumeInfo.sessionTotal }- : {}),- signal: this.getInputAbortSignal(sessionId, active.generation),+ const makerUserMessage = buildMakerUserMessage(head, referenceContexts);+ const result = await this.deps.sendToAgent(sessionId, makerUserMessage, head.createOpts, {+ messageUuid: active.messageUuid,+ userName: head.userName,+ throwOnStartFailure: true,+ ...(head.autoResume && typeof head.autoResumeInfo?.sessionTotal === 'number'+ ? { turnAttemptToken: head.autoResumeInfo.sessionTotal }+ : {}),+ signal: this.getInputAbortSignal(sessionId, active.generation),+ expectedClearBoundaryMs: active.clearBoundaryMs,+ expectedInputGeneration: active.generation,+ ...(head.origin?.kind === 'scheduler' ? { origin: head.origin } : {}),+ // 手机来源透传到 send 事务:drain 已脱离入队时的 async context。+ ...(head.fromMobileClient ? { fromMobileClient: true } : {}),+ persistUserMessage: {+ clientId: head.clientId,+ content: head.persistedContent,+ agentFacingWireContent: makerUserMessage,+ sdkSessionId,+ delivery: active.delivery,expectedClearBoundaryMs: active.clearBoundaryMs,expectedInputGeneration: active.generation,- ...(head.origin?.kind === 'scheduler' ? { origin: head.origin } : {}),- // 手机来源透传到 send 事务:drain 已脱离入队时的 async context。- ...(head.fromMobileClient ? { fromMobileClient: true } : {}),- persistUserMessage: {- clientId: head.clientId,- content: head.persistedContent,- sdkSessionId,- delivery: active.delivery,- expectedClearBoundaryMs: active.clearBoundaryMs,- expectedInputGeneration: active.generation,- // 自动续跑标记必须一路透到落库:renderer 靠 agentMeta.autoResume 隐藏气泡,- // host 靠它跳过额度充值(见 AgentInputQueuedMessage.autoResume)。- ...(head.autoResume ? { autoResume: true } : {}),- ...(head.autoResumeInfo ? { autoResumeInfo: head.autoResumeInfo } : {}),- ...(head.recoveryCheckpoint ? { recoveryCheckpoint: head.recoveryCheckpoint } : {}),- ...(head.origin ? { origin: head.origin } : {}),- shouldBroadcast: () => this.isTurnGenerationCurrent(sessionId, active),- onPersisting: () => {- this.notifyUserMessagePersisting(sessionId, head);- if (this.isTurnGenerationCurrent(sessionId, active)) {- active.persisting = true;- }- },- onPersisted: async () => {- // The DB row already owns any staged attachment references. This- // callback intentionally runs before generation checks: a clear- // or Stop may win the pre-vendor race after persistence, but it- // must not delete media that the durable row now references.- this.notifyUserMessagePersisted(sessionId, head);- if (this.isTurnGenerationCurrent(sessionId, active)) {- active.persisted = true;- active.persisting = false;- active.dispatchLifecycle = 'awaiting-dispatch-hooks';- this.notifyUserMessageQueryable(sessionId, head);- // 跨过 DB 持久化边界即刻收窄快照:此后崩溃属 interrupted-turn- // 辖区,若等到下一次 emit(turn done)才写,长 turn 内崩溃会把- // 已送达的消息二次恢复(issue #761)。- this.maybePersistQueueSnapshot(sessionId);- }- await this.deps.beforeDispatchUserTurn?.(sessionId, head);- if (!this.isActiveTurnCurrent(sessionId, active)) {- throw new Error(- '[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',- );- }- // host 把排队 orca 消息的 accepted 副作用挂在这个 hook 上(置 running /- // autoBridgePending), 必须 await 完才能放行 vendor turn —— fire-and-forget- // 会让快 worker 在状态可见前结束 turn, 桥接被 turn-end handler 误跳过。- await this.deps.onAcceptedQueuedMessage?.(sessionId, head);- if (!this.isActiveTurnCurrent(sessionId, active)) {- throw new Error(- '[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',- );- }- active.dispatchLifecycle = 'sending';- },- onPersistFailed: () => {- this.notifyUserMessagePersistenceFailed(sessionId, head, {- retainForRetry: true,- });- },+ // 自动续跑标记必须一路透到落库:renderer 靠 agentMeta.autoResume 隐藏气泡,+ // host 靠它跳过额度充值(见 AgentInputQueuedMessage.autoResume)。+ ...(head.autoResume ? { autoResume: true } : {}),+ ...(head.autoResumeInfo ? { autoResumeInfo: head.autoResumeInfo } : {}),+ ...(head.recoveryCheckpoint ? { recoveryCheckpoint: head.recoveryCheckpoint } : {}),+ ...(head.origin ? { origin: head.origin } : {}),+ shouldBroadcast: () => this.isTurnGenerationCurrent(sessionId, active),+ onPersisting: () => {+ this.notifyUserMessagePersisting(sessionId, head);+ if (this.isTurnGenerationCurrent(sessionId, active)) {+ active.persisting = true;+ }+ },+ onPersisted: async () => {+ // The DB row already owns any staged attachment references. This+ // callback intentionally runs before generation checks: a clear+ // or Stop may win the pre-vendor race after persistence, but it+ // must not delete media that the durable row now references.+ this.notifyUserMessagePersisted(sessionId, head);+ if (this.isTurnGenerationCurrent(sessionId, active)) {+ active.persisted = true;+ active.persisting = false;+ active.dispatchLifecycle = 'awaiting-dispatch-hooks';+ this.notifyUserMessageQueryable(sessionId, head);+ // 跨过 DB 持久化边界即刻收窄快照:此后崩溃属 interrupted-turn+ // 辖区,若等到下一次 emit(turn done)才写,长 turn 内崩溃会把+ // 已送达的消息二次恢复(issue #761)。+ this.maybePersistQueueSnapshot(sessionId);+ }+ await this.deps.beforeDispatchUserTurn?.(sessionId, head);+ if (!this.isActiveTurnCurrent(sessionId, active)) {+ throw new Error(+ '[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',+ );+ }+ // host 把排队 orca 消息的 accepted 副作用挂在这个 hook 上(置 running /+ // autoBridgePending), 必须 await 完才能放行 vendor turn —— fire-and-forget+ // 会让快 worker 在状态可见前结束 turn, 桥接被 turn-end handler 误跳过。+ await this.deps.onAcceptedQueuedMessage?.(sessionId, head);+ if (!this.isActiveTurnCurrent(sessionId, active)) {+ throw new Error(+ '[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',+ );+ }+ active.dispatchLifecycle = 'sending';+ },+ onPersistFailed: () => {+ this.notifyUserMessagePersistenceFailed(sessionId, head, {+ retainForRetry: true,+ });},},- );+ });if (this.discardOnStaleActiveTurn(sessionId, active, isSendDispatched(result))) return;active.persisting = false;if (!isSendDispatched(result)) {@@ -3847,24 +3852,16 @@ export class AgentInputCoordinator {}latest.error = errorMessage(err);latest.stickyError = null;- const piImageCapabilityRejected = isPiImageInputUnsupportedError(err);// 同 handleSendNotDispatched:调度来源的 prompt 不留可被人手动 Retry 的 recovery// (review #944 第九轮 P1;判据内建在 setActiveTurnRecovery)。const schedulerOrigin = this.setActiveTurnRecovery(latest, head) === 'dropped-scheduler';- if (schedulerOrigin) {- // 摘掉 recovery 就**必须**一并放掉 activeTurn。isDispatchBoundaryBusy 只要- // activeTurn 非空就判忙,而这条 active-turn recovery 原本是唯一能清掉它的入口- // (用户 Retry / clearError)—— 现在没有了,不主动清就等于把会话永久钉在"有活跃- // turn":之后所有用户与调度消息全部积压到 coordinator 被重置- // (review #944 第十轮 P1)。- latest.activeTurn = null;- } else if (piImageCapabilityRejected) {- // Pi 图片能力拒绝发生在 vendor RPC 之前,不会再有 terminal event 来释放 activeTurn;- // 已持久化的用户行仍保留 active-turn recovery,供用户切换到视觉模型后重试。- latest.activeTurn = null;- }+ // 已落库的派发失败必须立刻放开边界。否则 coordinator 会一直占着 activeTurn,+ // 下一轮被 dispatch-boundary-busy 挡住,界面上只剩用户气泡、没有红条、也不能重试。+ latest.activeTurn = null;this.notifyRejectedUserTurn(sessionId, head);this.notifyUndispatchedUserTurn(sessionId, head, 'failed');+ this.persistTerminalSendError(sessionId, latest.error);+ this.notifyPersistedSendRejected(sessionId, latest.error);this.emit(sessionId);// 派发边界刚刚放开,队里可能还压着别的消息 —— 用户那条路靠 clearError 顺带唤醒,// scheduler 这条没有人点,必须自己唤一次。@@ -3967,6 +3964,10 @@ export class AgentInputCoordinator {...logFields,},);+ if (!cancelledByUserBoundary) {+ this.persistTerminalSendError(sessionId, message);+ this.notifyPersistedSendRejected(sessionId, message);+ }this.emit(sessionId);// activeTurn 上面已置空,但队里可能还压着别的消息 —— 用户那条路靠 clearError 顺带// 唤醒,scheduler 这条没有 recovery、没有人点,必须自己唤一次(review #944 第十轮 P1)。@@ -5113,6 +5114,29 @@ export class AgentInputCoordinator {}}+ private persistTerminalSendError(sessionId: string, message: string): void {+ if (!message.trim()) return;+ try {+ this.deps.persistTerminalSendError?.(sessionId, message);+ } catch (err) {+ log.warn('persistTerminalSendError failed', {+ sessionId,+ error: errorMessage(err),+ });+ }+ }++ private notifyPersistedSendRejected(sessionId: string, message: string): void {+ try {+ this.deps.onPersistedSendRejected?.(sessionId, message);+ } catch (err) {+ log.warn('onPersistedSendRejected failed', {+ sessionId,+ error: errorMessage(err),+ });+ }+ }+private isTurnGenerationCurrent(sessionId: string, active: ActiveTurn): boolean {return this.getState(sessionId).generation === active.generation;}diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.tsindex f2c08caebd..dd84eb76b2 100644--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts@@ -21,6 +21,8 @@ export interface HandoffSourceMessage {role: string;content: unknown;createdAt: number; // unix ms+ /** 生产 tool_result 的关联列;content 经常是纯字符串,不能靠信封里的 toolUseId。 */+ toolUseId?: string | null;}export interface BuildHandoffOptions {@@ -50,9 +52,10 @@ export interface BuildHandoffOptions {workStateMessages?: HandoffSourceMessage[];/*** 交接触发原因。message-deletion 表示同一引擎因本地消息被删除而重建原生- * 上下文;framing 会要求只采用删除后的有效历史,且不向用户暴露内部重建。+ * 上下文;context-overflow 表示同一引擎因窗口超限而换干净原生会话;+ * pi-prompt-timeout 表示原生会话对 prompt 无响应后用户重试换窗。*/- reason?: 'agent-switch' | 'message-deletion';+ reason?: 'agent-switch' | 'message-deletion' | 'context-overflow' | 'pi-prompt-timeout';}/** 最近多少个用户轮次进入逐字区(其余进单行提要区)。 */@@ -196,35 +199,115 @@ interface Turn {*/interface WorkState {changedFiles: string[];- commands: string[];+ commands: Array<{ command: string; outcome?: string }>;+ failedPaths: string[];+}++function commandTextOf(input: Record<string, unknown>): string {+ const raw = input.command;+ if (typeof raw === 'string') return raw;+ if (Array.isArray(raw)) return raw.filter((x) => typeof x === 'string').join(' ');+ return '';+}++function toolUseIdOf(message: HandoffSourceMessage, content?: Record<string, unknown>): string {+ if (typeof message.toolUseId === 'string' && message.toolUseId) return message.toolUseId;+ if (!content) return '';+ return typeof content.toolUseId === 'string'+ ? content.toolUseId+ : typeof content.id === 'string'+ ? content.id+ : '';+}++function extractFailedPathHints(text: string): string[] {+ const hints: string[] = [];+ for (const line of text.split('\n')) {+ const match = line.match(/\bFAIL\s+(\S+)/) ?? line.match(/(\S+\.(?:test|spec)\.\w+)/);+ if (!match?.[1]) continue;+ hints.push(truncate(match[1], 80));+ if (hints.length >= 3) break;+ }+ return hints;+}++function extractCommandOutcome(content: Record<string, unknown>): string | undefined {+ if (content.isError === true) return 'failed';+ if (typeof content.exitCode === 'number' && Number.isFinite(content.exitCode)) {+ return `exit ${content.exitCode}`;+ }+ const text = extractPlainText(content.fullText ?? content.output ?? content.content ?? content);+ const exitMatch = text.match(/exit(?:ed)?(?:\s+code)?[:\s]+(-?\d+)/i);+ if (exitMatch) return `exit ${exitMatch[1]}`;+ if (/\b(tests? failed|failing tests|assertionerror)\b/i.test(text)) return 'tests failed';+ if (content.isError === false) return 'ok';+ return undefined;+}++function isFailedOutcome(outcome: string | undefined): boolean {+ if (!outcome) return false;+ if (outcome === 'ok' || outcome === 'exit 0') return false;+ return true;}function extractWorkState(messages: HandoffSourceMessage[]): WorkState {const files = new Set<string>();- const commands: string[] = [];+ const commands: Array<{ command: string; outcome?: string }> = [];+ const commandByToolUseId = new Map<string, number>();+ const failedPaths: string[] = [];for (const msg of messages) {- if (msg.role !== 'tool_use' || !msg.content || typeof msg.content !== 'object') continue;- const c = msg.content as Record<string, unknown>;- const name = typeof c.toolName === 'string' ? c.toolName : '';- const input = (c.input && typeof c.input === 'object' ? c.input : {}) as Record<string, unknown>;- if (FILE_EDIT_TOOL_NAMES.has(name)) {- for (const key of ['file_path', 'path', 'notebook_path']) {- const v = input[key];- if (typeof v === 'string' && v) files.add(v);+ const objectContent =+ msg.content && typeof msg.content === 'object' && !Array.isArray(msg.content)+ ? (msg.content as Record<string, unknown>)+ : undefined;+ if (msg.role === 'tool_use') {+ if (!objectContent) continue;+ const name = typeof objectContent.toolName === 'string' ? objectContent.toolName : '';+ const input = (+ objectContent.input && typeof objectContent.input === 'object'+ ? objectContent.input+ : {}+ ) as Record<string, unknown>;+ if (FILE_EDIT_TOOL_NAMES.has(name)) {+ for (const key of ['file_path', 'path', 'notebook_path']) {+ const v = input[key];+ if (typeof v === 'string' && v) files.add(v);+ }+ } else if (COMMAND_TOOL_NAMES.has(name)) {+ const cmd = commandTextOf(input);+ if (!cmd) continue;+ const entry = { command: truncate(oneLine(cmd), COMMAND_LINE_CAP) };+ const index = commands.push(entry) - 1;+ const toolUseId = toolUseIdOf(msg, objectContent);+ if (toolUseId) commandByToolUseId.set(toolUseId, index);}- } else if (COMMAND_TOOL_NAMES.has(name)) {- const raw = input.command;- const cmd = typeof raw === 'string'- ? raw- : Array.isArray(raw)- ? raw.filter((x) => typeof x === 'string').join(' ')- : '';- if (cmd) commands.push(truncate(oneLine(cmd), COMMAND_LINE_CAP));+ continue;+ }+ if (msg.role !== 'tool_result') continue;+ const toolUseId = toolUseIdOf(msg, objectContent);+ const index = toolUseId ? commandByToolUseId.get(toolUseId) : undefined;+ if (index === undefined) continue;+ const outcomeSource =+ objectContent ??+ (typeof msg.content === 'string' ? { fullText: msg.content } : undefined);+ if (!outcomeSource) continue;+ const outcome = extractCommandOutcome(outcomeSource);+ if (!outcome) continue;+ commands[index] = { ...commands[index]!, outcome };+ if (isFailedOutcome(outcome)) {+ const rawText =+ typeof msg.content === 'string'+ ? msg.content+ : extractPlainText(outcomeSource.fullText ?? outcomeSource.output ?? outcomeSource);+ const hints = extractFailedPathHints(rawText);+ if (hints.length > 0) failedPaths.push(...hints);+ else failedPaths.push(`${commands[index]!.command} → ${outcome}`);}}return {changedFiles: [...files].slice(-CHANGED_FILES_CAP),commands: commands.slice(-COMMANDS_CAP),+ failedPaths: failedPaths.slice(-COMMANDS_CAP),};}@@ -329,7 +412,11 @@ const FORK_TERMINATOR = "== End of fork note; the user's new message follows =="/** 结束标记——交接正文与"用户的新消息"之间唯一的分隔,任何情况下都要留住。 */function handoffTerminator(opts: BuildHandoffOptions): string {- return opts.reason === 'message-deletion' ? REBUILD_TERMINATOR : HANDOFF_TERMINATOR;+ return opts.reason === 'message-deletion' ||+ opts.reason === 'context-overflow' ||+ opts.reason === 'pi-prompt-timeout'+ ? REBUILD_TERMINATOR+ : HANDOFF_TERMINATOR;}/**@@ -371,13 +458,33 @@ function splitTrailingTerminator(text: string): [body: string, tail: string] {* 内部历史的显式分隔——工具密集的长历史(逐字区已收缩到 1 轮仍超限)真会走到这里,* 英文 framing 比原中文长,触达上限更容易。*/+const RETRIEVAL_SECTION_HEADING = '== Retrieving earlier verbatim history';++function splitMandatoryHandoffTail(text: string, opts: BuildHandoffOptions): {+ body: string;+ tail: string;+} {+ const retrievalAt = text.lastIndexOf(RETRIEVAL_SECTION_HEADING);+ if (retrievalAt >= 0) {+ return {+ body: text.slice(0, retrievalAt).trimEnd(),+ tail: text.slice(retrievalAt),+ };+ }+ const [body, terminatorTail] = splitTrailingTerminator(text);+ return {+ body: body.trimEnd(),+ tail: terminatorTail || `${handoffTerminator(opts)}`,+ };+}+function capPreservingTerminator(text: string, opts: BuildHandoffOptions): string {if (text.length <= HANDOFF_HARD_CAP) return text;- const terminator = handoffTerminator(opts);+ const { body, tail } = splitMandatoryHandoffTail(text, opts);const separator = '\n\n';- const room = HANDOFF_HARD_CAP - terminator.length - separator.length;- if (room <= 0) return terminator.slice(0, HANDOFF_HARD_CAP);- return `${text.slice(0, room)}${separator}${terminator}`;+ 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}`;}function assembleHandoffText(@@ -390,16 +497,30 @@ function assembleHandoffText(const earlier = turns.slice(0, -recentCount);const sections: string[] = [];- if (opts.reason === 'message-deletion') {+ if (+ opts.reason === 'message-deletion' ||+ opts.reason === 'context-overflow' ||+ opts.reason === 'pi-prompt-timeout'+ ) {+ const rebuildCause =+ opts.reason === 'context-overflow'+ ? `The previous native agent session exceeded the model's context window, so Cindy started a fresh native session in the same task. ` ++ `Below is the valid conversation history before the overflowing turn; treat only these records as the prior conversation, ` ++ `and do not try to recover, cite, or infer messages that are not listed. `+ : opts.reason === 'pi-prompt-timeout'+ ? `The previous native agent session stopped responding to prompts, so Cindy started a fresh native session in the same task. ` ++ `Below is the valid conversation history before the unresponsive turn; treat only these records as the prior conversation, ` ++ `and do not try to recover, cite, or infer messages that are not listed. `+ : `The user edited this conversation's local record, which invalidated the current native session context. ` ++ `Below is the valid conversation history after that edit; treat only these records as the prior conversation, ` ++ `and do not try to recover, cite, or infer messages that are not listed. `;sections.push(`[Session context rebuild · internal context]\n` +- `The user edited this conversation's local record, which invalidated the current native session context. ` +- `Below is the valid conversation history after that edit; treat only these records as the prior conversation, ` +- `and do not try to recover, cite, or infer messages that are not listed. ` ++ rebuildCause +`Continue naturally in the first person, and do not mention this rebuild note to the user. ` +`Before making any change, check the actual workspace state (e.g. git status / git diff / reading the relevant files): ` +`when the record conflicts with the workspace, the workspace always wins; ` +- `when you are unsure about an earlier detail, read the real files and code to confirm rather than guessing from the summary.`,+ `when you are unsure about an earlier detail, read the real files and code to confirm rather than guessing from the index or a guess.`,);} else if (opts.mode === 'delta') {// 归位续接:目标引擎 resume 了自己的停泊原生会话,已持有离场前的完整记忆。@@ -432,17 +553,23 @@ function assembleHandoffText(// 动过哪些文件、跑过哪些命令,避免重复劳动或誤判"还没做过"。// delta 模式按 workStateMessages(全量历史)提取,见 BuildHandoffOptions 注释。const work = extractWorkState(opts.workStateMessages ?? messages);- if (work.changedFiles.length > 0 || work.commands.length > 0) {+ if (work.changedFiles.length > 0 || work.commands.length > 0 || work.failedPaths.length > 0) {const lines: string[] = [];if (work.changedFiles.length > 0) {lines.push('Files changed:');for (const f of work.changedFiles) lines.push(`- ${f}`);}if (work.commands.length > 0) {- lines.push('Commands run (most recent):');- for (const cmd of work.commands) lines.push(`- ${cmd}`);+ lines.push('Commands (most recent):');+ for (const cmd of work.commands) {+ lines.push(cmd.outcome ? `- ${cmd.command} → ${cmd.outcome}` : `- ${cmd.command}`);+ }+ }+ if (work.failedPaths.length > 0) {+ lines.push('Failed attempts:');+ for (const path of work.failedPaths) lines.push(`- ${path}`);}- sections.push(`== Work state (auto-extracted) ==\n${lines.join('\n')}`);+ sections.push(`== Work ledger (auto-extracted) ==\n${lines.join('\n')}`);}if (earlier.length > 0) {@@ -469,7 +596,7 @@ function assembleHandoffText(sections.push(opts.mode === 'delta'? `== Earlier progress while you were away ==\n${digest}`- : `== Earlier conversation digest ==\n${digest}`,+ : `== Earlier conversation index (hints only, not a verified summary) ==\n${digest}`,);}@@ -498,11 +625,11 @@ function assembleHandoffText(sections.push(`== Retrieving earlier verbatim history (use when needed) ==\n` +`Session id: ${opts.sessionId}\n` +- `Earlier conversation text beyond the digest above can be retrieved at any time (tools live under cindy_helper's history category):\n` +- `- By content: search_chat_history, args {"query":"<keywords>","session_ids":["${opts.sessionId}"]}\n` +- `- By time/role: get_chat_history, args {"session_ids":["${opts.sessionId}"],"roles":["user","assistant"]} (page through with nextCursor when hasMore)\n` +- `When the user asks about a detail that is not in the context above, retrieve the original text before answering instead of guessing from the digest; ` +- `when retrieved history conflicts with the current workspace, the workspace wins. Use this only when needed, not on every turn.`,+ `The index above is only a hint. Retrieve earlier verbatim text only when needed (tools live under cindy_helper's history category):\n` ++ `1. First: search_chat_history, args {"query":"<keywords>","session_ids":["${opts.sessionId}"],"limit":10}\n` ++ `2. Only if that is not enough: get_chat_history, args {"session_ids":["${opts.sessionId}"],"roles":["user","assistant"],"limit":20}\n` ++ `Page with nextCursor only when hasMore is true and the needed detail is still missing. Never request the default 200-row page and never dump the full history.\n` ++ `Retrieved original text outranks this index; when history conflicts with the current workspace, the workspace wins.`,);}diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.tsnew file mode 100644index 0000000000..7a61ab8eca--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts@@ -0,0 +1,567 @@+/**+ * 同一任务里因上下文超限而隐藏重建原生 Agent 会话。+ *+ * 抄 messageDeleteHandler 的 same-engine context_rebuild,不抄可见 agent_switch。+ * 规划函数是纯的,host 只负责关 live handle、落库、注入交接、wire 重放失败那条 user 消息。+ */++import { CONTEXT_OVERFLOW_REASON, isContextOverflowErrorMessage } from '@cindy/maker-core';+import {+ projectAgentFacingText,+ readAgentInputReferences,+} from '@cindy/maker-shared/agent-input-projection';++import {+ assessModelSwitchContext,+ shouldHandoffAfterContextAssessment,+} from '../../shared/modelSwitchAssessment';+import { buildHandoffText, extractPlainText, type HandoffSourceMessage } from './agentHandoff.js';++const SYNTHETIC_TRIGGER_PREFIX = '[UI_ACTION_TRIGGER]';++export interface OverflowSourceMessage extends HandoffSourceMessage {+ clientId: string;+ agentMeta?: Record<string, unknown> | null;+}++export type OverflowRolloverStopReason = 'no-user' | 'has-side-effects' | 'already-rolled';++export type OverflowRolloverPlan =+ | {+ action: 'rebuild';+ sourceUserClientId: string;+ sourceUserContent: unknown;+ sourceUserAgentFacingWireContent?: unknown;+ skipGenericReplay: boolean;+ handoffMessages: OverflowSourceMessage[];+ }+ | { action: 'stop'; reason: OverflowRolloverStopReason };++export function isContextOverflowErrorData(data: unknown): boolean {+ if (!data || typeof data !== 'object') return false;+ const rec = data as { reason?: unknown; message?: unknown; sdkError?: unknown };+ if (rec.reason === CONTEXT_OVERFLOW_REASON) return true;+ return [rec.message, rec.sdkError].some(+ (value) => typeof value === 'string' && isContextOverflowErrorMessage(value),+ );+}++const PI_PROMPT_RPC_TIMEOUT_RE = /pi rpc timeout after \d+ms: prompt\b/i;++export function isPiPromptRpcTimeoutError(data: unknown): boolean {+ if (!data || typeof data !== 'object') return false;+ const rec = data as { message?: unknown; sdkError?: unknown };+ return [rec.message, rec.sdkError].some(+ (value) => typeof value === 'string' && PI_PROMPT_RPC_TIMEOUT_RE.test(value),+ );+}++/** PI 原生会话已经无法继续:超限,或 prompt RPC 超时(巨大 jsonl resume 卡死)。 */+export function shouldRebuildPiNativeSession(data: unknown): boolean {+ return isContextOverflowErrorData(data) || isPiPromptRpcTimeoutError(data);+}++const GROK_4_CONTEXT_CAP = 500_000;++export function effectiveContextWindow(+ model: string | null | undefined,+ reportedWindow: number,+ verifiedWindow?: number | null,+): number {+ if (typeof verifiedWindow === 'number' && verifiedWindow > 0) return verifiedWindow;+ const reported = Number.isFinite(reportedWindow) && reportedWindow > 0 ? reportedWindow : 0;+ if (typeof model === 'string' && /grok-4/i.test(model)) {+ return reported > 0 ? Math.min(reported, GROK_4_CONTEXT_CAP) : GROK_4_CONTEXT_CAP;+ }+ return reported;+}++/** @deprecated Kept for callers/tests that still use the old PI-specific name. */+export const effectivePiContextWindow = effectiveContextWindow;++export function lookupVerifiedContextWindow(+ resolve:+ ((agentKind: string, modelId: string, providerId: string | null) => number | null) | undefined,+ model: string | null | undefined,+ providerId?: string | null,+ agentKind?: string,+): number | null {+ if (!resolve || !model) return null;+ const ids = [model];+ const slash = model.lastIndexOf('/');+ if (slash >= 0) ids.push(model.slice(slash + 1));+ if (model.startsWith('x-ai/')) ids.push(`xai/${model.slice(5)}`);+ // A missing provider is an unresolved route, not permission to borrow the+ // xAI catalog entry. The Grok model-level cap below remains the only generic+ // fallback; directory lookup must stay scoped to this session's provider.+ const providerIds = [providerId ?? null];+ for (const id of [...new Set(ids)]) {+ const callResolve = (pid: string | null): number | null => resolve(agentKind ?? 'pi', id, pid);+ const hit = providerIds+ .map(callResolve)+ .find((value) => typeof value === 'number' && value > 0);+ if (typeof hit === 'number' && hit > 0) return hit;+ }+ return null;+}++export function shouldRebuildForContextPressure(+ tokens: number,+ window: number,+ autoCompactThresholdPct?: number,+): boolean {+ return shouldHandoffAfterContextAssessment(+ assessModelSwitchContext({+ contextTokens: tokens,+ targetContextWindow: window,+ autoCompactThresholdPct,+ }),+ );+}++function isSyntheticUser(message: OverflowSourceMessage): boolean {+ if (message.role !== 'user') return false;+ return extractPlainText(message.content).startsWith(SYNTHETIC_TRIGGER_PREFIX);+}++function hasTurnSideEffects(messagesAfterUser: OverflowSourceMessage[]): boolean {+ return messagesAfterUser.some((message) => message.role !== 'error');+}++export type OverflowReplayWireMessage =+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> };++function isOverflowReplayWireMessage(value: unknown): value is OverflowReplayWireMessage {+ if (typeof value === 'string') return true;+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const record = value as Record<string, unknown>;+ return (+ record.type === 'user' && (typeof record.content === 'string' || Array.isArray(record.content))+ );+}++export function persistedUserContentToWireMessage(content: unknown): OverflowReplayWireMessage {+ if (typeof content === 'string') {+ const trimmed = content.trim();+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {+ try {+ return persistedUserContentToWireMessage(JSON.parse(content));+ } catch {+ return content;+ }+ }+ return content;+ }+ if (Array.isArray(content)) {+ return { type: 'user', content: content as Array<{ type: string; [k: string]: unknown }> };+ }+ if (!content || typeof content !== 'object') return '';+ const rec = content as Record<string, unknown>;+ if (isOverflowReplayWireMessage(rec.agentFacingWireContent)) {+ return rec.agentFacingWireContent;+ }+ if (rec.type === 'user') {+ if (typeof rec.content === 'string' || Array.isArray(rec.content)) {+ return rec as OverflowReplayWireMessage;+ }+ }+ const text = typeof rec.text === 'string' ? rec.text : '';+ const agentReferences = readAgentInputReferences(rec.agentReferences, text);+ const projectedText = projectAgentFacingText({+ text,+ quotesEncoded: rec.quotesEncoded === true,+ agentReferences,+ });+ const images = Array.isArray(rec.images) ? rec.images : [];+ const files = Array.isArray(rec.files) ? rec.files : [];+ if (images.length === 0 && files.length === 0) return projectedText;+ const blocks: Array<{ type: string; [k: string]: unknown }> = [];+ if (projectedText) blocks.push({ type: 'text', text: projectedText });+ for (const image of images) {+ if (!image || typeof image !== 'object') continue;+ const item = image as Record<string, unknown>;+ const path =+ typeof item.url === 'string' ? item.url : typeof item.path === 'string' ? item.path : '';+ if (path) blocks.push({ type: 'image', path });+ }+ for (const file of files) {+ if (!file || typeof file !== 'object') continue;+ const item = file as Record<string, unknown>;+ const path = typeof item.path === 'string' ? item.path : '';+ if (path) blocks.push({ type: 'file', path });+ }+ return { type: 'user', content: blocks.length > 0 ? blocks : projectedText };+}++export function planContextOverflowRollover(+ messages: OverflowSourceMessage[],+ alreadyRolledUserClientId?: string | null,+): OverflowRolloverPlan {+ let lastUserIndex = -1;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i];+ if (message && message.role === 'user' && !isSyntheticUser(message)) {+ lastUserIndex = i;+ break;+ }+ }+ if (lastUserIndex < 0) return { action: 'stop', reason: 'no-user' };+ const sourceUser = messages[lastUserIndex]!;+ if (alreadyRolledUserClientId && alreadyRolledUserClientId === sourceUser.clientId) {+ return { action: 'stop', reason: 'already-rolled' };+ }+ if (hasTurnSideEffects(messages.slice(lastUserIndex + 1))) {+ return { action: 'stop', reason: 'has-side-effects' };+ }+ return {+ action: 'rebuild',+ sourceUserClientId: sourceUser.clientId,+ sourceUserContent: sourceUser.content,+ ...(sourceUser.agentMeta?.agentFacingWireContent !== undefined+ ? { sourceUserAgentFacingWireContent: sourceUser.agentMeta.agentFacingWireContent }+ : {}),+ skipGenericReplay: isExternalDispatchOwner(sourceUser.agentMeta),+ handoffMessages: messages.slice(0, lastUserIndex),+ };+}++function isExternalDispatchOwner(agentMeta: Record<string, unknown> | null | undefined): boolean {+ if (!agentMeta) return false;+ if (agentMeta.hookSource) return true;+ const origin = agentMeta.origin;+ if (!origin || typeof origin !== 'object' || Array.isArray(origin)) return false;+ const kind = (origin as { kind?: unknown }).kind;+ // 有 origin.kind 就是外部派单方(scheduler / IM / goal / orca / …)。+ // 不要再列白名单:漏一个 kind 就会走 generic replay 冒充 Cindy 对话。+ return typeof kind === 'string' && kind.length > 0;+}++function normalizeOverflowDbAgentKind(value: string): 'cc' | 'codex' | 'pi' {+ if (value === 'codex' || value === 'pi') return value;+ return 'cc';+}++export function engineLabelForOverflow(agentKind: string): string {+ if (agentKind === 'codex') return 'Codex';+ if (agentKind === 'pi') return 'Pi';+ return 'Claude Code';+}++export function errorContentToData(content: unknown): unknown {+ if (typeof content === 'string') {+ const trimmed = content.trim();+ if (trimmed.startsWith('{')) {+ try {+ return JSON.parse(trimmed);+ } catch {+ return { message: content };+ }+ }+ return { message: content };+ }+ return content;+}++/** 最近一条终态若是超限,或(PI 专属)prompt 超时,则原生会话已死,发送前不要再 resume。 */+export function findLatestRebuildableError(+ messages: OverflowSourceMessage[],+ allowPiPromptTimeout = true,+): unknown | null {+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i];+ if (!message) continue;+ if (message.role === 'error') {+ const data = errorContentToData(message.content);+ if (isContextOverflowErrorData(data)) return data;+ if (allowPiPromptTimeout && isPiPromptRpcTimeoutError(data)) return data;+ return null;+ }+ if (message.role === 'assistant' && extractPlainText(message.content).trim().length > 0) {+ return null;+ }+ }+ return null;+}++export interface ContextOverflowRolloverDeps {+ getSessionRow(sessionId: string): Promise<{+ status: string;+ agentKind: string;+ remoteHostId: string | null;+ clearedAt: number | null;+ sdkSessionId?: string | null;+ contextTokens?: number | null;+ contextWindow?: number | null;+ model?: string | null;+ providerId?: string | null;+ } | null>;+ resolveVerifiedWindow?(+ agentKind: string,+ modelId: string,+ providerId: string | null,+ ): number | null;+ getAutoCompactThresholdPct?(): number | undefined;+ listMessages(sessionId: string): Promise<OverflowSourceMessage[]>;+ /** 不受 handoff 窗口限制的最近 user,避免工具密集 turn 把身份扫丢。 */+ findLatestUser?(sessionId: string): Promise<OverflowSourceMessage | null>;+ findLatestRebuildMeta(+ sessionId: string,+ ): Promise<{ reason?: string; sourceUserClientId?: string | null } | null>;+ getLiveSession(sessionId: string): {+ isTurnRunning(): boolean;+ getUsageSnapshot?(): { contextTokens: number; contextWindow: number };+ } | null | undefined;+ closeSession(sessionId: string): Promise<void>;+ drainPersistQueue(): Promise<void>;+ commitRebuild(+ sessionId: string,+ handoff: string,+ meta: {+ reason: 'context-overflow' | 'pi-prompt-timeout';+ sourceUserClientId: string | null;+ sourceAgentKind?: 'cc' | 'codex' | 'pi';+ sourceModel?: string | null;+ sourceProviderId?: string | null;+ expectedClearedAt?: number | null;+ },+ ): Promise<void>;+ setPendingHandoff(sessionId: string, handoff: string, expectedGeneration?: number): void;+ readPendingHandoffGeneration?(sessionId: string): number;+ replayUserMessage(+ sessionId: string,+ content: unknown,+ agentFacingWireContent?: unknown,+ ): Promise<{ accepted: boolean }>;+ onRebuilt?(sessionId: string): void;+ withSessionLock?<T>(sessionId: string, fn: () => Promise<T>): Promise<T>;+ withCloseSuppressed<T>(sessionId: string, fn: () => Promise<T>): Promise<T>;+ log: {+ info(message: string, fields?: Record<string, unknown>): void;+ warn(message: string, fields?: Record<string, unknown>): void;+ };+}++export type OverflowClaimResult = 'claimed' | 'in-flight' | 'idle';++export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps): {+ claim(sessionId: string): OverflowClaimResult;+ tryRecover(sessionId: string, errorData: unknown): Promise<boolean>;+ prepareUnhealthySession(sessionId: string): Promise<boolean>;+} {+ const inFlight = new Set<string>();++ const runRecover = async (sessionId: string, errorData: unknown): Promise<boolean> => {+ if (!isContextOverflowErrorData(errorData)) return false;+ await deps.drainPersistQueue();+ const sessionRow = await deps.getSessionRow(sessionId);+ if (!sessionRow || sessionRow.status === 'deleted') return false;+ if (sessionRow.remoteHostId) return false;++ return deps.withCloseSuppressed(sessionId, async () => {+ const live = deps.getLiveSession(sessionId);+ if (live?.isTurnRunning()) {+ deps.log.warn('context overflow rollover skipped: turn still running', { sessionId });+ return false;+ }+ const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);+ const [source, rebuildMeta] = await Promise.all([+ deps.listMessages(sessionId),+ deps.findLatestRebuildMeta(sessionId),+ ]);+ const alreadyRolled =+ rebuildMeta?.reason === 'context-overflow' ? rebuildMeta.sourceUserClientId : null;+ const plan = planContextOverflowRollover(source, alreadyRolled);+ if (plan.action === 'stop') {+ deps.log.info('context overflow rollover stopped', {+ sessionId,+ reason: plan.reason,+ });+ return false;+ }++ if (live) await deps.closeSession(sessionId);+ const label = engineLabelForOverflow(sessionRow.agentKind);+ const handoff = buildHandoffText(plan.handoffMessages, {+ fromLabel: label,+ toLabel: label,+ sessionId,+ reason: 'context-overflow',+ });+ await deps.commitRebuild(sessionId, handoff, {+ reason: 'context-overflow',+ sourceUserClientId: plan.sourceUserClientId,+ sourceAgentKind: normalizeOverflowDbAgentKind(sessionRow.agentKind),+ sourceModel: sessionRow.model ?? null,+ sourceProviderId: sessionRow.providerId ?? null,+ expectedClearedAt: sessionRow.clearedAt,+ });+ deps.setPendingHandoff(sessionId, handoff, handoffGeneration);+ if (plan.skipGenericReplay) {+ deps.log.info('overflow rebuilt; external owner must retry send', {+ sessionId,+ sourceUserClientId: plan.sourceUserClientId,+ });+ return true;+ }+ const replay =+ plan.sourceUserAgentFacingWireContent !== undefined+ ? await deps.replayUserMessage(+ sessionId,+ plan.sourceUserContent,+ plan.sourceUserAgentFacingWireContent,+ )+ : await deps.replayUserMessage(sessionId, plan.sourceUserContent);+ if (!replay.accepted) {+ deps.log.warn('context overflow rollover replay was not accepted', {+ sessionId,+ sourceUserClientId: plan.sourceUserClientId,+ });+ return false;+ }+ // 重放被接受后再清 recovery:失败时要保留 Retry,不能先 clearError。+ deps.onRebuilt?.(sessionId);+ deps.log.info('context overflow rollover replayed user message', {+ sessionId,+ sourceUserClientId: plan.sourceUserClientId,+ });+ return true;+ });+ };++ const runPrepare = async (sessionId: string): Promise<boolean> => {+ await deps.drainPersistQueue();+ const sessionRow = await deps.getSessionRow(sessionId);+ if (!sessionRow || sessionRow.status === 'deleted') return false;+ if (sessionRow.remoteHostId) return false;+ if (!sessionRow.sdkSessionId) return false;+ const live = deps.getLiveSession(sessionId);+ if (live?.isTurnRunning()) return false;+ const source = await deps.listMessages(sessionId);+ const lastError = findLatestRebuildableError(source, sessionRow.agentKind === 'pi');+ const liveUsage = live?.getUsageSnapshot?.();+ const hasLiveTokens =+ liveUsage !== undefined &&+ Number.isFinite(liveUsage.contextTokens) &&+ liveUsage.contextTokens >= 0;+ const tokens = hasLiveTokens+ ? liveUsage.contextTokens+ : typeof sessionRow.contextTokens === 'number'+ ? sessionRow.contextTokens+ : 0;+ const reportedWindow =+ hasLiveTokens && liveUsage.contextWindow > 0+ ? liveUsage.contextWindow+ : typeof sessionRow.contextWindow === 'number'+ ? sessionRow.contextWindow+ : 0;+ const verified = lookupVerifiedContextWindow(+ deps.resolveVerifiedWindow,+ sessionRow.model,+ sessionRow.providerId,+ sessionRow.agentKind,+ );+ const window = effectiveContextWindow(sessionRow.model, reportedWindow, verified);+ const pressure = shouldRebuildForContextPressure(+ tokens,+ window,+ deps.getAutoCompactThresholdPct?.(),+ );+ if (!lastError && !pressure) return false;+ let lastUser: OverflowSourceMessage | undefined;+ let lastUserIndex = -1;+ for (let i = source.length - 1; i >= 0; i -= 1) {+ const message = source[i];+ if (message && message.role === 'user' && !isSyntheticUser(message)) {+ lastUser = message;+ lastUserIndex = i;+ break;+ }+ }+ if (!lastUser) {+ lastUser = (await deps.findLatestUser?.(sessionId)) ?? undefined;+ lastUserIndex = -1;+ }+ if (!lastUser) return false;+ const rebuildReason = isPiPromptRpcTimeoutError(lastError)+ ? 'pi-prompt-timeout'+ : 'context-overflow';+ // 待发出/失败的 user 还会由本次 send 或 Retry 再 wire 一次,交接里不能带。+ // 已完成的最后一轮(后面有非 error)要留在交接里。+ // lastUser 若不在 handoff 窗口里(index < 0),窗口全是其后的 tool/assistant,算已完成。+ const pendingOutbound =+ lastUserIndex >= 0 &&+ source.slice(lastUserIndex + 1).every((message) => message.role === 'error');+ const handoffMessages = (+ pendingOutbound && lastUserIndex >= 0 ? source.slice(0, lastUserIndex) : source+ ).filter((message) => message.role !== 'error');+ const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);+ // 关掉当前 live handle。调用方必须在解析发送目标之前调用 prepare,+ // 再 getSession / createSession;peek 之后对旧对象 send 会打到已关闭实例。+ if (live) await deps.closeSession(sessionId);+ const label = engineLabelForOverflow(sessionRow.agentKind);+ const handoff = buildHandoffText(handoffMessages, {+ fromLabel: label,+ toLabel: label,+ sessionId,+ reason: rebuildReason,+ });+ await deps.commitRebuild(sessionId, handoff, {+ reason: rebuildReason,+ sourceUserClientId: lastUser.clientId,+ sourceAgentKind: normalizeOverflowDbAgentKind(sessionRow.agentKind),+ sourceModel: sessionRow.model ?? null,+ sourceProviderId: sessionRow.providerId ?? null,+ expectedClearedAt: sessionRow.clearedAt,+ });+ deps.setPendingHandoff(sessionId, handoff, handoffGeneration);+ deps.onRebuilt?.(sessionId);+ deps.log.info('unhealthy native session rebuilt before send; skip compact/resume', {+ sessionId,+ sourceUserClientId: lastUser.clientId,+ });+ return true;+ };++ return {+ claim(sessionId: string): OverflowClaimResult {+ if (inFlight.has(sessionId)) return 'in-flight';+ inFlight.add(sessionId);+ return 'claimed';+ },++ async tryRecover(sessionId: string, errorData: unknown): Promise<boolean> {+ try {+ if (deps.withSessionLock) {+ return await deps.withSessionLock(sessionId, () => runRecover(sessionId, errorData));+ }+ return await runRecover(sessionId, errorData);+ } catch (error) {+ deps.log.warn('context overflow rollover failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ } finally {+ inFlight.delete(sessionId);+ }+ },++ async prepareUnhealthySession(sessionId: string): Promise<boolean> {+ if (inFlight.has(sessionId)) return false;+ inFlight.add(sessionId);+ try {+ return await deps.withCloseSuppressed(sessionId, () => runPrepare(sessionId));+ } catch (error) {+ deps.log.warn('unhealthy native session prepare failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ // A failed pre-send rebuild must not fall through to the caller's+ // stale resume/fork/thread options. Let the send boundary fail closed.+ throw error;+ } finally {+ inFlight.delete(sessionId);+ }+ },+ };+}diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex f4d5bdd48d..e84c21dd1d 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -5,9 +5,7 @@ import {type SessionSendResult,type UserMessage,} from '@cindy/maker-core';-import {- CODEX_RESUME_NOT_READY_WIRE_MESSAGE,-} from '@cindy/maker-shared/agent-input-projection';+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';import {createHostSendFailure,@@ -64,6 +62,7 @@ type MakerSendOptions = {persistUserMessage?: {clientId?: unknown;content?: unknown;+ agentFacingWireContent?: unknown;sdkSessionId?: unknown;delivery?: unknown;shouldBroadcast?: unknown;@@ -214,6 +213,11 @@ export interface MakerSendTransactionDeps {* 保留意图本次不动。undefined = 不启用(测试最小 harness)。*/applyPendingAgentSwitch?(sessionId: string): Promise<void>;+ /**+ * 发送前换窗:必须在 getSession 之前。prepare 会关掉不健康的 live handle,+ * 随后本事务按空 session 走 lazy-create,避免 peek 之后对已关闭对象 send。+ */+ prepareUnhealthySession?(sessionId: string): Promise<boolean | void>;/*** session-agent-switch:pending 交接读取(agentHandoff 注册表)。命中时把交接* 文本前置进 wire payload(不影响 persistUserMessage 落库显示内容),并在@@ -261,6 +265,7 @@ type ResolveSessionResult =function readPersistUserMessageOption(sendOpts: MakerSendOptions): {clientId: string;content: unknown;+ agentFacingWireContent?: IpcUserMessage;sdkSessionId?: string;delivery?: 'turn' | 'steer';autoResume?: boolean;@@ -279,6 +284,9 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {return {clientId: persist.clientId,content: persist.content,+ ...(persist.agentFacingWireContent && typeof persist.agentFacingWireContent === 'object'+ ? { agentFacingWireContent: persist.agentFacingWireContent as IpcUserMessage }+ : {}),...(typeof persist.sdkSessionId === 'string' ? { sdkSessionId: persist.sdkSessionId } : {}),...(persist.autoResume === true ? { autoResume: true as const } : {}),...(persist.autoResumeInfo && typeof persist.autoResumeInfo === 'object'@@ -596,6 +604,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make// 去时才切」)。必须在 getSession 之前——apply 会 close 旧引擎的 live session,// 让下方走 lazy-create 按 DB 新值 spawn 新引擎。await deps.applyPendingAgentSwitch?.(sessionId);+ await deps.prepareUnhealthySession?.(sessionId);let sess = deps.getSession(sessionId);// Maker keeps a failed Session registered until its real handle cleanup// succeeds. It is not a reusable send target: route it through the@@ -803,9 +812,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make})();const startsWithSlashCommand =reconcileSlashRanges !== undefined- ? reconcileSlashRanges.some(- (range) => (range as { start?: unknown } | null)?.start === 0,- )+ ? reconcileSlashRanges.some((range) => (range as { start?: unknown } | null)?.start === 0): reconcilePersistText.startsWith('/');const isOrdinaryUserTurn =soForReconcile.origin === undefined &&@@ -829,8 +836,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make// 两个来源:直连 maker:send 走 async context(deps 注入);排队 / 插入路径走// coordinator 从队列项透传的 so.fromMobileClient(drain 时 context 已结束)。const mobileClientNote =- (deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true)- && shouldPrependMobileClientPromptNote(normalized, sess.agentKind)+ (deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true) &&+ shouldPrependMobileClientPromptNote(normalized, sess.agentKind)? buildMobileClientPromptNote(): null;const outgoing = mobileClientNote@@ -1008,10 +1015,14 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make...(persistUserMessage.recoveryCheckpoint? { recoveryCheckpoint: persistUserMessage.recoveryCheckpoint }: {}),- ...(persistUserMessage.origin ? { origin: persistUserMessage.origin } : {}),- // scheduler 排队消息:与 runner 直发路径落库的 agentMeta.origin- // 对齐,renderer 据此渲染"由自动化任务发送"标签。- ...(so.origin ? { origin: so.origin } : {}),+ ...(persistUserMessage.agentFacingWireContent+ ? { agentFacingWireContent: persistUserMessage.agentFacingWireContent }+ : {}),+ // 队列来源写入 agentMeta,不发给 maker-core。Orca 只在 persist+ // 上;scheduler 直发可能只在 sendOpts.origin 上。+ ...((persistUserMessage.origin ?? so.origin)+ ? { origin: persistUserMessage.origin ?? so.origin }+ : {}),},},persistUserMessage.shouldBroadcast ||diff --git a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.tsindex 440efb7edf..4081cef3e2 100644--- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts+++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts@@ -145,7 +145,12 @@ export interface OrcaInterAgentDispatcherDeps<TSessionMeta> {) => Promise<OrcaInterAgentSendToSessionInternalResult>;createDbMessage: (sessionId: string,- message: { clientId: string; role: 'user'; content: string },+ message: {+ clientId: string;+ role: 'user';+ content: string;+ agentMeta?: Record<string, unknown>;+ },) => Promise<unknown>;beginDirectTurnChangeSet: (sessionId: string, clientId: string) => Promise<void>;abortDirectTurnChangeSet: (sessionId: string) => void;@@ -346,6 +351,7 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(try {const live = deps.getLiveSession(params.targetSessionId);if (live) {+ const senderLabel = await resolveSenderLabel();const result = await sendPersistedUserMessageToSession(deps, {session: live,dbContent: persistedContent,@@ -353,6 +359,11 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(clientId,source: params.meta.source,context: params.meta.context,+ origin: {+ kind: 'orca',+ senderLabel,+ displayText: params.rawContent,+ },onAccepted: runAccepted,});if (result.dispatched) {@@ -426,10 +437,11 @@ async function sendPersistedUserMessageToSession<TSessionMeta>(clientId?: string;source: string;context: string;+ origin?: AgentInputQueuedMessage['origin'];onAccepted?: () => void | Promise<void>;},): Promise<CollabDirectDispatchResult> {- const { session, dbContent, agentMessage, clientId = deps.createId(), source, context, onAccepted } = params;+ const { session, dbContent, agentMessage, clientId = deps.createId(), source, context, origin, onAccepted } = params;let turnChangeSetStarted = false;const result = await resolveCollabDispatchResult(() => session.send(agentMessage, {@@ -441,6 +453,7 @@ async function sendPersistedUserMessageToSession<TSessionMeta>(clientId,role: 'user',content: dbContent,+ ...(origin ? { agentMeta: { origin } } : {}),});await deps.beginDirectTurnChangeSet(session.id, clientId);turnChangeSetStarted = true;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 146d0a371c..49a91bc82e 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -166,10 +166,7 @@ import {import * as imageCacheStore from '../imageCacheStore.js';import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';import { materializeGeneratedImage } from '../cindy-media/generatedMedia.js';-import {- getDbClient,- isDbClientNotReadyError,-} from '../localDb/client/current.js';+import { getDbClient, isDbClientNotReadyError } from '../localDb/client/current.js';import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';import {awaitAgentInputQueueSnapshotPersistence,@@ -189,12 +186,15 @@ import {broadcastMessageRow,broadcastMessageAgentMetaUpdate,broadcastMessageDeleted,+ commitContextRebuild,commitMessageDeletion,createMessage as createDbMessage,+ findLatestContextRebuildMeta,rewindPersistedUserMessageAfterClear,findParkedEngineSession,getMessageDeletionTarget,listMessagesForAgentHandoff,+ findLatestUserMessageForRebuild,patchMessageAgentMeta,supersedeRetriedUserTurn,updateMessageContent,@@ -699,6 +699,14 @@ import {prependHandoffToUserMessage,type HandoffWireMessage,} from './agentHandoff.js';+import {+ createContextOverflowRollover,+ isContextOverflowErrorData,+ isPiPromptRpcTimeoutError,+ lookupVerifiedContextWindow,+ persistedUserContentToWireMessage,+ shouldRebuildPiNativeSession,+} from './contextOverflowRollover.js';import { hydrateQueuedAgentReferences } from './agentInputReferences.js';import { agentHandoffPending } from './agentHandoffPendingSingleton.js';import { clearSealedCodexPlanState, readCodexPlanState } from '../localDb/codexPlanState.js';@@ -735,6 +743,8 @@ import {setSessionProvider,} from '../maker-host/session-provider-store.js';import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';+import { readCompactionPct } from '../maker-host/compaction-settings-store.js';+import { resolveVerifiedContextWindow } from '../maker-host/catalog-to-descriptors.js';import { refreshXaiMediaModels } from '../maker-host/model-discovery/xai-media.js';import { testProviderConnection } from '../maker-host/provider-diagnostics.js';import { fetchProviderModels } from '../maker-host/provider-model-fetch.js';@@ -1517,11 +1527,15 @@ type SendToSessionInternalResult =/** 暴露给 xdt-helper MCP provider 的协同控制面,必须复用 IPC 同源业务路径。 */interface OrcaCollabService {- listSessionQueue: (sessionId: string) => Promise<+ listSessionQueue: (+ sessionId: string,+ ) => Promise<| { ok: true; messages: SessionQueueInspectionEntry[] }| { ok: false; errorCode: 'NOT_FOUND' | 'HOST_NOT_READY' | 'INTERNAL'; message: string }>;- listSessionQueuedCounts: (sessionIds: string[]) => Promise<+ listSessionQueuedCounts: (+ sessionIds: string[],+ ) => Promise<| { ok: true; counts: Record<string, number> }| { ok: false; errorCode: 'HOST_NOT_READY' | 'INTERNAL'; message: string }>;@@ -2615,6 +2629,16 @@ export async function withSendToSessionLock<T>(}let agentInputCoordinatorHolder: AgentInputCoordinator | null = null;+let contextOverflowRolloverHolder: ReturnType<typeof createContextOverflowRollover> | null = null;+const overflowSuppressedBroadcasts = new Map<+ string,+ {+ sessionId: string;+ event: AgentEvent;+ persistId?: string;+ resolvedContent?: unknown;+ }+>();function getWiredSessionCloseReason(session: WiredSession) {return getMakerIfReady()?.getSessionCloseReason(session) ?? 'unexpected';@@ -2832,6 +2856,11 @@ export async function acquirePendingAgentSwitchForDirectSend(return pendingAgentSwitchApplyHolder?.(sessionId, signal) ?? (() => {});}+/** 直发路径在 createSession / 重读 live session 之前关掉不健康原生会话。 */+export async function prepareUnhealthySessionForSend(sessionId: string): Promise<void> {+ await contextOverflowRolloverHolder?.prepareUnhealthySession(sessionId);+}+/** Later successful model/provider picks supersede an earlier cross-engine intent. */export function cancelPendingAgentSwitchForSession(sessionId: string): void {cancelPendingAgentSwitchHolder?.(sessionId);@@ -4148,13 +4177,27 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 先 broadcast 保 UI 实时性,再 flush(flush 只入队、不阻塞)。// Keep the raw event for main-side coordination/persistence, but only// cross renderer/device-link boundaries with the redacted copy.- broadcastToAllWindows(MAKER_PUSH.EVENT, {- sessionId: session.id,- event: broadcastEvent,- persistId,- resolvedContent,- });- handleAgentIslandEventAfterBroadcast(session, broadcastEvent);+ const suppressOverflowBroadcast =+ !session.remoteHostId &&+ event.type === 'error' &&+ isTerminalTurnErrorEvent(event) &&+ isContextOverflowErrorData(event.data);+ if (suppressOverflowBroadcast) {+ overflowSuppressedBroadcasts.set(session.id, {+ sessionId: session.id,+ event: broadcastEvent,+ persistId,+ resolvedContent,+ });+ } else {+ broadcastToAllWindows(MAKER_PUSH.EVENT, {+ sessionId: session.id,+ event: broadcastEvent,+ persistId,+ resolvedContent,+ });+ handleAgentIslandEventAfterBroadcast(session, broadcastEvent);+ }if (shouldMarkTurnTerminalIdleAfterBroadcast) {sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(session.id);// #9 idle 兜底:正常 done、终止型 error(含 abort)统一在 tracker 已置 idle 后@@ -4261,7 +4304,54 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidevent.type === 'error' &&(agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true ||agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true);- if (+ const overflowClaim =+ event.type === 'error' &&+ !session.remoteHostId &&+ isTerminalTurnErrorEvent(event) &&+ !isPlannedUpgradeClose &&+ !isRemoteAuthRetry &&+ !autoResumeSuppressesPersist &&+ isContextOverflowErrorData(attributedEvent.data)+ ? (contextOverflowRolloverHolder?.claim(session.id) ?? 'idle')+ : 'idle';+ if (overflowClaim === 'claimed') {+ const overflowErrorData = attributedEvent.data;+ const surfaceOverflowFailure = (): void => {+ const stashed = overflowSuppressedBroadcasts.get(session.id);+ overflowSuppressedBroadcasts.delete(session.id);+ if (stashed) {+ broadcastToAllWindows(MAKER_PUSH.EVENT, stashed);+ handleAgentIslandEventAfterBroadcast(session, stashed.event);+ }+ onTurnErrorEvent(+ session.id,+ overflowErrorData as {+ message?: unknown;+ reason?: unknown;+ sdkError?: unknown;+ } | null,+ eventAgentMeta,+ );+ };+ void contextOverflowRolloverHolder+ ?.tryRecover(session.id, overflowErrorData)+ .then((recovered) => {+ if (recovered) {+ overflowSuppressedBroadcasts.delete(session.id);+ return;+ }+ surfaceOverflowFailure();+ })+ .catch((error) => {+ log.warn('context overflow rollover rejected', {+ sessionId: session.id,+ error: error instanceof Error ? error.message : String(error),+ });+ surfaceOverflowFailure();+ });+ } else if (overflowClaim === 'in-flight') {+ // 同一 turn 的重复终态 error:继续压住,避免污染历史。+ } else if (event.type === 'error' &&!isPlannedUpgradeClose &&!isRemoteAuthRetry &&@@ -4402,10 +4492,22 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void}}if (pendingContextSnapshot) {+ const verifiedWindow = lookupVerifiedContextWindow(+ (agentKind, modelId, providerId) =>+ resolveVerifiedContextWindow(+ getActiveCatalog(),+ dbToMakerAgentKind(agentKind),+ providerId,+ modelId,+ ),+ session.model,+ getSessionProvider(session.id),+ session.agentKind,+ );recordSessionContextSnapshot(session.id,pendingContextSnapshot.contextTokens,- pendingContextSnapshot.contextWindow,+ verifiedWindow ?? pendingContextSnapshot.contextWindow,);}if (pendingCodexAccountUsageSnapshot) {@@ -5349,23 +5451,21 @@ let disposePiPackagesChangedBroadcast: (() => void) | null = null;* soon as the Renderer selects an owner, before the splash-gated Maker IPC bundle is available.*/export function registerModelVisibilitySyncIpc(): void {- ipcMain.handle(MAKER_INVOKE.MODEL_VISIBILITY_SYNC, async (- event,- dataOwnerId: unknown,- ownerGeneration: unknown,- map: unknown,- ) => {- assertTrustedAppRendererEvent(event);- syncModelVisibilityMirrorForOwner(- map,- { dataOwnerId, ownerGeneration },- getActiveDataOwnerPushStamp(),- isAppSessionBoundaryPending(),- () => {- broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});- },- );- });+ ipcMain.handle(+ MAKER_INVOKE.MODEL_VISIBILITY_SYNC,+ async (event, dataOwnerId: unknown, ownerGeneration: unknown, map: unknown) => {+ assertTrustedAppRendererEvent(event);+ syncModelVisibilityMirrorForOwner(+ map,+ { dataOwnerId, ownerGeneration },+ getActiveDataOwnerPushStamp(),+ isAppSessionBoundaryPending(),+ () => {+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});+ },+ );+ },+ );}export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): void {@@ -6165,81 +6265,89 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await getDesktopCommandRegistry().execute(name, c);});- ipcMain.handle(MAKER_INVOKE.LIST_AGENT_COMMANDS, async (event, agentKind: unknown, rawParams?: unknown) => {- assertAgentCommandListIpcCaller(event, {- isDeviceLinkInvoke,- assertTrustedSender: (sourceEvent) =>- assertTrustedAppRendererEvent(- sourceEvent as Parameters<typeof assertTrustedAppRendererEvent>[0],- ),- });- try {- const kind = requireAgentKind(agentKind);- const params = rawParams === undefined ? {} : requireObject(rawParams);- if (params.sessionId !== undefined && typeof params.sessionId !== 'string') {- throwIpcError('INVALID_PARAMS', 'sessionId must be a string');- }- if (- params.allowManagedPiPackagePreview !== undefined- && typeof params.allowManagedPiPackagePreview !== 'boolean'- ) {- throwIpcError('INVALID_PARAMS', 'allowManagedPiPackagePreview must be a boolean');- }- const sessionId = typeof params.sessionId === 'string' && params.sessionId.trim()- ? params.sessionId.trim()- : undefined;- const sessionMeta = sessionId ? await maker.getSessionMeta(sessionId) : null;- const builtins = maker.listAgentCommands(kind);- const mayListPackageCommands = shouldListPiPackageCommands(- kind,- sessionId !== undefined,- sessionMeta,- params.allowManagedPiPackagePreview !== false,- );- let packageCommands: Array<{ name: string; description: string }> = [];- let runtimeStatus: import('../../shared/piPackages.js').PiPackageCommandRuntimeStatus | undefined;- if (mayListPackageCommands && sessionId) {- const manifest = maker.getSessionRuntimeCapabilities(sessionId);- runtimeStatus = manifest?.status === 'loaded'- ? 'loaded'- : manifest?.status === 'failed'- ? 'failed'- : manifest?.status === 'unknown'- ? 'unknown'- : 'pending';- const managedNames = new Set(manifest?.managedPackageCommandNames ?? []);- if (manifest?.status === 'loaded') {- packageCommands = manifest.commands.flatMap((command) => (- managedNames.has(command.name) && !command.name.startsWith('skill:')- ? [{- name: command.name,- description: command.description ?? `Pi extension command: ${command.name}`,- }]- : []- ));- } else if (!manifest) {- // An empty local Pi task may have a persisted session row before its- // process starts. Keep inspected Prompt templates visible; send waits- // for this task's get_commands catalog before allowing execution.+ ipcMain.handle(+ MAKER_INVOKE.LIST_AGENT_COMMANDS,+ async (event, agentKind: unknown, rawParams?: unknown) => {+ assertAgentCommandListIpcCaller(event, {+ isDeviceLinkInvoke,+ assertTrustedSender: (sourceEvent) =>+ assertTrustedAppRendererEvent(+ sourceEvent as Parameters<typeof assertTrustedAppRendererEvent>[0],+ ),+ });+ try {+ const kind = requireAgentKind(agentKind);+ const params = rawParams === undefined ? {} : requireObject(rawParams);+ if (params.sessionId !== undefined && typeof params.sessionId !== 'string') {+ throwIpcError('INVALID_PARAMS', 'sessionId must be a string');+ }+ if (+ params.allowManagedPiPackagePreview !== undefined &&+ typeof params.allowManagedPiPackagePreview !== 'boolean'+ ) {+ throwIpcError('INVALID_PARAMS', 'allowManagedPiPackagePreview must be a boolean');+ }+ const sessionId =+ typeof params.sessionId === 'string' && params.sessionId.trim()+ ? params.sessionId.trim()+ : undefined;+ const sessionMeta = sessionId ? await maker.getSessionMeta(sessionId) : null;+ const builtins = maker.listAgentCommands(kind);+ const mayListPackageCommands = shouldListPiPackageCommands(+ kind,+ sessionId !== undefined,+ sessionMeta,+ params.allowManagedPiPackagePreview !== false,+ );+ let packageCommands: Array<{ name: string; description: string }> = [];+ let runtimeStatus:+ import('../../shared/piPackages.js').PiPackageCommandRuntimeStatus | undefined;+ if (mayListPackageCommands && sessionId) {+ const manifest = maker.getSessionRuntimeCapabilities(sessionId);+ runtimeStatus =+ manifest?.status === 'loaded'+ ? 'loaded'+ : manifest?.status === 'failed'+ ? 'failed'+ : manifest?.status === 'unknown'+ ? 'unknown'+ : 'pending';+ const managedNames = new Set(manifest?.managedPackageCommandNames ?? []);+ if (manifest?.status === 'loaded') {+ packageCommands = manifest.commands.flatMap((command) =>+ managedNames.has(command.name) && !command.name.startsWith('skill:')+ ? [+ {+ name: command.name,+ description: command.description ?? `Pi extension command: ${command.name}`,+ },+ ]+ : [],+ );+ } else if (!manifest) {+ // An empty local Pi task may have a persisted session row before its+ // process starts. Keep inspected Prompt templates visible; send waits+ // for this task's get_commands catalog before allowing execution.+ packageCommands = await listManagedPiPromptCommands();+ }+ } else if (mayListPackageCommands) {+ // Before a task exists, only prompt templates are statically knowable.+ // Extension commands appear after that exact Pi runtime confirms them.packageCommands = await listManagedPiPromptCommands();}- } else if (mayListPackageCommands) {- // Before a task exists, only prompt templates are statically knowable.- // Extension commands appear after that exact Pi runtime confirms them.- packageCommands = await listManagedPiPromptCommands();+ const commands = mergePiPackageCommands(kind, builtins, packageCommands);+ return { success: true, commands, ...(runtimeStatus ? { runtimeStatus } : {}) };+ } catch (err) {+ return toAgentCommandListFailure(err, {+ reportError: (error) => {+ log.warn('Agent command list failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ },+ });}- const commands = mergePiPackageCommands(kind, builtins, packageCommands);- return { success: true, commands, ...(runtimeStatus ? { runtimeStatus } : {}) };- } catch (err) {- return toAgentCommandListFailure(err, {- reportError: (error) => {- log.warn('Agent command list failed', {- error: error instanceof Error ? error.message : String(error),- });- },- });- }- });+ },+ );ipcMain.handle(MAKER_INVOKE.LIST_AGENT_SKILLS,@@ -6319,72 +6427,80 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)source: payload.source,...(typeof payload.enabled === 'boolean' ? { enabled: payload.enabled } : {}),};- return runPiPackageMutationIpcBoundary(async () => {- if (!piPackageMutationNeedsGrant(request)) return mutatePiPackage(request);+ return runPiPackageMutationIpcBoundary(+ async () => {+ if (!piPackageMutationNeedsGrant(request)) return mutatePiPackage(request);- const enableIdentity = request.action === 'set-enabled' && request.enabled === true- ? await capturePiPackageEnableIdentity(request.source)- : undefined;- const grantBinding = enableIdentity- ? { expectedPackageFingerprint: enableIdentity.expectedPackageFingerprint }- : undefined;+ const enableIdentity =+ request.action === 'set-enabled' && request.enabled === true+ ? await capturePiPackageEnableIdentity(request.source)+ : undefined;+ const grantBinding = enableIdentity+ ? { expectedPackageFingerprint: enableIdentity.expectedPackageFingerprint }+ : undefined;- const source = escapePiPackageNativeDialogText(request.source);- const copy =- request.action === 'set-enabled'- ? {- title: t('settings.piPackages.extensionApprovalTitle'),- message: enableIdentity?.displayLabel ?? '',- detail: t('settings.piPackages.extensionApprovalDescription'),- confirm: t('settings.piPackages.approveAndEnable'),- }- : request.action === 'remove'+ const source = escapePiPackageNativeDialogText(request.source);+ const copy =+ request.action === 'set-enabled'? {- title: t('settings.piPackages.uninstallTitle'),- message: t('settings.piPackages.uninstallTitle'),- detail: t('settings.piPackages.uninstallDescription').replace('{{name}}', source),- confirm: t('settings.piPackages.confirmUninstall'),+ title: t('settings.piPackages.extensionApprovalTitle'),+ message: enableIdentity?.displayLabel ?? '',+ detail: t('settings.piPackages.extensionApprovalDescription'),+ confirm: t('settings.piPackages.approveAndEnable'),}- : request.action === 'update'+ : request.action === 'remove'? {- title: t('settings.piPackages.updateConfirmTitle'),- message: t('settings.piPackages.updateConfirmTitle'),- detail: t('settings.piPackages.updateConfirmDescription').replace(- '{{source}}',- source,- ),- confirm: t('settings.piPackages.confirmUpdate'),+ title: t('settings.piPackages.uninstallTitle'),+ message: t('settings.piPackages.uninstallTitle'),+ detail: t('settings.piPackages.uninstallDescription').replace('{{name}}', source),+ confirm: t('settings.piPackages.confirmUninstall'),}- : {- title: t('settings.piPackages.confirmTitle'),- message: t('settings.piPackages.confirmTitle'),- detail: t('settings.piPackages.confirmDescription').replace('{{source}}', source),- confirm: t('settings.piPackages.confirmInstall'),- };- const owner = BrowserWindow.fromWebContents(event.sender);- const options = {- type: 'warning' as const,- title: copy.title,- message: copy.message,- detail: copy.detail,- buttons: [copy.confirm, t('settings.piPackages.cancel')],- defaultId: 1,- cancelId: 1,- noLink: true,- };- const decision = owner- ? await dialog.showMessageBox(owner, options)- : await dialog.showMessageBox(options);- if (decision.response !== 0) {- throwIpcError('MUTATION_CANCELLED', 'Pi extension mutation cancelled');- }- return mutatePiPackage(request, issuePiPackageMutationGrant(request, grantBinding));- }, t('settings.piPackages.operationFailed'), (error) => {- log.warn('Pi extension mutation failed', {- action: request.action,- message: error instanceof Error ? error.message : String(error),- });- });+ : request.action === 'update'+ ? {+ title: t('settings.piPackages.updateConfirmTitle'),+ message: t('settings.piPackages.updateConfirmTitle'),+ detail: t('settings.piPackages.updateConfirmDescription').replace(+ '{{source}}',+ source,+ ),+ confirm: t('settings.piPackages.confirmUpdate'),+ }+ : {+ title: t('settings.piPackages.confirmTitle'),+ message: t('settings.piPackages.confirmTitle'),+ detail: t('settings.piPackages.confirmDescription').replace(+ '{{source}}',+ source,+ ),+ confirm: t('settings.piPackages.confirmInstall'),+ };+ const owner = BrowserWindow.fromWebContents(event.sender);+ const options = {+ type: 'warning' as const,+ title: copy.title,+ message: copy.message,+ detail: copy.detail,+ buttons: [copy.confirm, t('settings.piPackages.cancel')],+ defaultId: 1,+ cancelId: 1,+ noLink: true,+ };+ const decision = owner+ ? await dialog.showMessageBox(owner, options)+ : await dialog.showMessageBox(options);+ if (decision.response !== 0) {+ throwIpcError('MUTATION_CANCELLED', 'Pi extension mutation cancelled');+ }+ return mutatePiPackage(request, issuePiPackageMutationGrant(request, grantBinding));+ },+ t('settings.piPackages.operationFailed'),+ (error) => {+ log.warn('Pi extension mutation failed', {+ action: request.action,+ message: error instanceof Error ? error.message : String(error),+ });+ },+ );});ipcMain.handle(@@ -6847,11 +6963,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)o.providerId = reroute;}} else if (shouldApplyExclusiveProviderRerouteLive(o.providerId)) {- const pin = await pinExclusiveSessionProvider(- o.agentKind,- o.model,- o.providerId ?? null,- );+ const pin = await pinExclusiveSessionProvider(o.agentKind, o.model, o.providerId ?? null);if (pin) o.providerId = pin;}}@@ -7994,11 +8106,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 解释它)。lazy-create 时刻 DB 行是唯一真源,执行字段无条件对齐。co.model = row.model ?? undefined;co.resumeSessionId = row.sdkSessionId ?? undefined;+ if (!row.sdkSessionId && co.vendorOptions) {+ // context.rebuild clears the DB sdk_session_id. Queued createOpts may+ // still carry vendor-specific resume/fork anchors from before the close;+ // strip every native continuation hint so CC/Codex bootstrap fresh too.+ const freshVendorOptions = { ...co.vendorOptions };+ for (const key of ['resumeSessionAt', 'forkSession', 'threadId', 'tailTurnsToDrop']) {+ delete freshVendorOptions[key];+ }+ co.vendorOptions =+ Object.keys(freshVendorOptions).length > 0 ? freshVendorOptions : undefined;+ }co.providerId = row.providerId;co.effort = (row.effort ?? undefined) as CreateOpts['effort'];co.fastMode = !!row.fastMode;- } catch {- // 校正读库失败按原 opts 继续(与切换功能上线前行为一致)。+ } catch (error) {+ // context.rebuild clears sdk_session_id before the next bootstrap. If the+ // DB truth cannot be read, continuing with caller-supplied opts could+ // resurrect the dead native resume/fork/thread; fail closed instead.+ log.warn('lazy-create: DB reconciliation failed; refusing stale native bootstrap', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;}}@@ -8031,7 +8161,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)listMessagesForAgentHandoff(sessionId, 400, after),findParkedEngineSession: (sessionId, targetDbKind) =>findParkedEngineSession(sessionId, targetDbKind),- applyAgentSwitchToDb: applyAgentSwitchToSessionRow,+ applyAgentSwitchToDb: async (sessionId, patch) => {+ const verifiedWindow = lookupVerifiedContextWindow(+ (agentKind, modelId, pid) =>+ resolveVerifiedContextWindow(+ getActiveCatalog(),+ dbToMakerAgentKind(agentKind || patch.agentKind),+ pid,+ modelId,+ ),+ patch.model,+ patch.providerId ?? null,+ dbToMakerAgentKind(patch.agentKind),+ );+ await applyAgentSwitchToSessionRow(sessionId, {+ ...patch,+ ...(verifiedWindow ? { contextWindow: verifiedWindow } : {}),+ });+ },setSessionProvider,supersedePendingCredentialSwitch: clearPendingCredentialSwitchForSession,insertBoundaryMessage: async (sessionId, content) => {@@ -8155,6 +8302,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)bootstrapAfterSwitch: true,signal,});+ await contextOverflowRolloverHolder?.prepareUnhealthySession(sessionId);return release;} catch (err) {release();@@ -8566,6 +8714,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)clientId,role: 'user',content: persistedContent ?? message,+ ...(queuedOrigin ? { agentMeta: { origin: queuedOrigin } as AgentMeta } : {}),});// F4: send_to_session 的 create 分支也建了一条用户可见新会话(有 title + 落了 user// 消息),同属"新建会话需同步所有窗侧栏"的 purpose。广播跟 user row 持久化@@ -8719,10 +8868,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)clientId,role: 'user',content: persistedContent ?? message,+ ...(queuedOrigin ? { agentMeta: { origin: queuedOrigin } as AgentMeta } : {}),});await runAcceptedCallback(onAccepted, targetSessionId, clientId);};+ await contextOverflowRolloverHolder?.prepareUnhealthySession(targetSessionId);let live = maker.getSession(targetSessionId);if (live) {if (live.isTurnRunning?.()) {@@ -10161,8 +10312,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)idleReleaseWatcher.start();const sessionControlService = createSessionControlService({- sessionExists: async (sessionId) =>- (await maker.getSessionMeta(sessionId)) !== null,+ sessionExists: async (sessionId) => (await maker.getSessionMeta(sessionId)) !== null,getLiveSession: (sessionId) => maker.getSession(sessionId) ?? null,getSessionActivitySnapshot: readCanonicalSessionActivity,assertExternalInputAllowed: assertReviewExternalInputAllowed,@@ -10228,7 +10378,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}await inputCoordinator.ensureQueueRestored(sessionId);if (!inputCoordinator.isQueueRestored(sessionId)) {- return { ok: false, errorCode: 'INTERNAL', message: `queue restore incomplete for ${sessionId}` };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: `queue restore incomplete for ${sessionId}`,+ };}return {ok: true,@@ -10246,8 +10400,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)listSessionQueuedCounts: async (sessionIds) => {try {const counts = await resolveSessionQueueCounts(sessionIds, {- getLiveQueue: (sessionId) =>- inputCoordinator.getQueueInspectionIfRestored(sessionId),+ getLiveQueue: (sessionId) => inputCoordinator.getQueueInspectionIfRestored(sessionId),loadPersistedCounts: loadAgentInputQueueSnapshotCounts,});return { ok: true, counts };@@ -10489,12 +10642,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)try {const agents: AgentKind[] = agent ? [agent] : ['codex', 'claude-code', 'pi'];const providerRouting = await getProviderRoutingContext();- const result: Record<string, Array<{- id: string;- label: string;- providers: Array<{ id: string; name: string }>;- defaultProviderId: string | null;- }>> = {};+ const result: Record<+ string,+ Array<{+ id: string;+ label: string;+ providers: Array<{ id: string; name: string }>;+ defaultProviderId: string | null;+ }>+ > = {};for (const a of agents) {const caps = maker.getCapabilities(a);// key 必须区分 pi,否则 pi 模型会被塞进 claude_code 键与 CC 模型混淆。@@ -10718,6 +10874,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)isMobileClientInvoke: () => isMobileControllerInvoke(),applyPendingAgentSwitch: (sessionId) =>applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId),+ prepareUnhealthySession: (sessionId) =>+ contextOverflowRolloverHolder?.prepareUnhealthySession(sessionId) ?? Promise.resolve(false),log,});@@ -10725,8 +10883,121 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const [sessionId] = args;if (typeof sessionId !== 'string') return await sendToAgentAcceptedUnlocked(...args);await assertReviewExternalInputAllowed(sessionId);- return await withSendToSessionLock(sessionId, () => sendToAgentAcceptedUnlocked(...args));+ return await withSendToSessionLock(sessionId, async () => {+ return sendToAgentAcceptedUnlocked(...args);+ });};+ contextOverflowRolloverHolder = createContextOverflowRollover({+ getSessionRow: async (sessionId) => {+ const [row] = await getDbClient()+ .drizzle.select({+ status: sessions.status,+ agentKind: sessions.agentKind,+ remoteHostId: sessions.remoteHostId,+ clearedAt: sessions.clearedAt,+ sdkSessionId: sessions.sdkSessionId,+ contextTokens: sessions.contextTokens,+ contextWindow: sessions.contextWindow,+ model: sessions.model,+ providerId: sessions.providerId,+ })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ return row ?? null;+ },+ getAutoCompactThresholdPct: () => readCompactionPct(),+ resolveVerifiedWindow: (agentKind, modelId, providerId) => {+ const catalog = getActiveCatalog();+ const makerAgentKind = dbToMakerAgentKind(agentKind);+ return resolveVerifiedContextWindow(catalog, makerAgentKind, providerId, modelId);+ },+ listMessages: (sessionId) => listMessagesForAgentHandoff(sessionId, 400),+ findLatestUser: findLatestUserMessageForRebuild,+ findLatestRebuildMeta: findLatestContextRebuildMeta,+ getLiveSession: (sessionId) => maker.getSession(sessionId),+ closeSession: (sessionId) => maker.closeSession(sessionId),+ drainPersistQueue,+ commitRebuild: async (sessionId, handoff, meta) => {+ const { updatedAt } = await commitContextRebuild(sessionId, handoff, meta);+ const [sessionKindRow] = await getDbClient()+ .drizzle.select({ agentKind: sessions.agentKind })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const cardAgentKind =+ sessionKindRow?.agentKind === 'codex'+ ? 'codex'+ : sessionKindRow?.agentKind === 'pi'+ ? 'pi'+ : 'cc';+ broadcastSessionPatched(sessionId, {+ sdkSessionId: null,+ updatedAt: new Date(updatedAt).toISOString(),+ });+ await createDbMessage(sessionId, {+ clientId: `context-rebuild-card:${createId()}`,+ role: 'assistant',+ content: '',+ agentKind: cardAgentKind,+ agentMeta: {+ contextRebuild: {+ reason: meta.reason,+ handoff,+ },+ } as AgentMeta,+ });+ },+ setPendingHandoff: (sessionId, handoff, expectedGeneration) =>+ agentHandoffPending.set(sessionId, handoff, expectedGeneration),+ readPendingHandoffGeneration: (sessionId) => agentHandoffPending.readGeneration(sessionId),+ onRebuilt: (sessionId) => {+ // overflow 终态已先走 coordinator onTurnEvent('error'),会留下 active-turn+ // recovery 和错误横幅。重放绕开 coordinator,随后的 done 会被 recovery 吃掉。+ agentInputCoordinatorHolder?.clearError(sessionId);+ },+ replayUserMessage: async (sessionId, content, agentFacingWireContent) => {+ const [row] = await getDbClient()+ .drizzle.select()+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!row?.workingDir) return { accepted: false };+ const createOpts = buildCreateOptsWithStderr({+ id: sessionId,+ agentKind: dbToMakerAgentKind(row.agentKind),+ workingDir: row.workingDir,+ model: row.model ?? undefined,+ providerId: row.providerId,+ effort: (row.effort ?? undefined) as CreateOpts['effort'],+ fastMode: !!row.fastMode,+ permissionMode: (row.permissionMode ?? 'ask') as CreateOpts['permissionMode'],+ planMode: !!row.planModeEnabled,+ title: row.title ?? undefined,+ remoteHostId: row.remoteHostId ?? undefined,+ });+ if (createOpts.extraDirs === undefined) {+ try {+ const extraDirs = await readSessionExtraDirsFromDb(sessionId);+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;+ } catch (err) {+ log.warn('overflow replay: read extra_dirs from DB failed (non-fatal)', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ }+ const result = await sendToAgentAcceptedUnlocked(+ sessionId,+ persistedUserContentToWireMessage(agentFacingWireContent ?? content),+ createOpts,+ );+ return { accepted: result.accepted === true };+ },+ withSessionLock: withSendToSessionLock,+ withCloseSuppressed: withRehydrateCloseSuppressed,+ log,+ });/*** Same-turn steer contract: resolved STEER means maker-core accepted the* inserted message into the active turn (Claude: streaming input push;@@ -11701,6 +11972,26 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (item.autoResume) return;autoResumeBookkeeping.surfaceSuppressedErrorForRetry(sessionId, item.clientId);},+ persistTerminalSendError: (sessionId, message) => {+ onTurnErrorEvent(+ sessionId,+ {+ message,+ ...(isPiPromptRpcTimeoutError({ message }) ? { reason: 'pi-prompt-timeout' } : {}),+ },+ null,+ );+ },+ onPersistedSendRejected: (sessionId, message) => {+ if (!isPiPromptRpcTimeoutError({ message })) return;+ // 第一次 timeout:只关掉卡住的原生进程,不自动 replay。用户重试时再 hidden rebuild。+ void maker.closeSession(sessionId).catch((error) => {+ log.warn('failed to close unhealthy PI session after prompt timeout', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ },// 队列项未派发即被丢弃(stop/remove/clearSession) → 释放暂存的 accepted 副作用, 防回调表泄漏。onDiscardedQueuedMessage: (sessionId, item) => {rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'discarded');@@ -11928,6 +12219,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (route.model) patch.model = route.model;if (route.effort) patch.effort = route.effort;if (route.fastMode !== undefined) patch.fastMode = route.fastMode;+ const agentKind = getSessionDbAgentKind(sessionId);+ if (route.model && agentKind) {+ const verifiedWindow = lookupVerifiedContextWindow(+ (resolvedAgentKind, modelId, pid) =>+ resolveVerifiedContextWindow(+ getActiveCatalog(),+ dbToMakerAgentKind(resolvedAgentKind || agentKind),+ pid,+ modelId,+ ),+ route.model,+ route.providerId ?? null,+ dbToMakerAgentKind(agentKind),+ );+ if (verifiedWindow) patch.contextWindow = verifiedWindow;+ }await getDbClient().drizzle.update(sessions).set(patch).where(eq(sessions.id, sessionId));broadcastSessionPatched(sessionId, patch);},@@ -13499,6 +13806,35 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)markRemoteSettingPersistedInsideHandler(response);}}+ if (!response.deferred) {+ const currentAgentKind =+ maker.getSession(sessionId)?.agentKind ??+ dbToMakerAgentKind(getSessionDbAgentKind(sessionId));+ const verifiedWindow = lookupVerifiedContextWindow(+ (agentKind, modelId, pid) =>+ resolveVerifiedContextWindow(+ getActiveCatalog(),+ dbToMakerAgentKind(agentKind),+ pid,+ modelId,+ ),+ model,+ typeof effectiveProviderId === 'string' ? effectiveProviderId : null,+ currentAgentKind,+ );+ if (verifiedWindow) {+ const [usage] = await getDbClient()+ .drizzle.select({ contextTokens: sessions.contextTokens })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ await recordSessionContextSnapshot(+ sessionId,+ usage?.contextTokens ?? 0,+ verifiedWindow,+ );+ }+ }return response;} catch (err) {if (err instanceof CredentialModeSwitchBusyError) {@@ -14219,18 +14555,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)registerAndroidAutomationHandlers(createElectronIpcHandlerRegistry());// ── iOS Simulator pane / Agent discovery ────────────────────────────────- registerIOSSimulatorHandlers(- createElectronIpcHandlerRegistry(),- {- getPluginAccess: getIOSSimulatorPluginAccessDecision,- getSessionContext: async (sessionId) => {- const liveSession = maker.getSession(sessionId);- if (liveSession) return { workingDir: liveSession.workDir };- const snapshot = await getSessionRowSnapshotStrict(sessionId);- return snapshot ? { workingDir: snapshot.workingDir } : null;- },+ registerIOSSimulatorHandlers(createElectronIpcHandlerRegistry(), {+ getPluginAccess: getIOSSimulatorPluginAccessDecision,+ getSessionContext: async (sessionId) => {+ const liveSession = maker.getSession(sessionId);+ if (liveSession) return { workingDir: liveSession.workDir };+ const snapshot = await getSessionRowSnapshotStrict(sessionId);+ return snapshot ? { workingDir: snapshot.workingDir } : null;},- );+ });// ── Browser automation (Settings →「电脑使用」) ───────────────────────────// Probe local browser detection. Drives the detection status + downloaddiff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.tsindex 4e8d695d02..799783a352 100644--- a/apps/desktop/src/main/maker-orchestration/fork.ts+++ b/apps/desktop/src/main/maker-orchestration/fork.ts@@ -16,10 +16,12 @@ import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-iimport { getDbClient } from '../localDb/client/current';import { sessions, messages } from '../localDb/schema';import { sessionToCamel } from '../localDb/mapper';+import { commitContextRebuild, createMessage } from '../localDb/ipc/messages.js';import { getMaker } from '../maker-host/index.js';import { createBusinessSessionId } from '../sessionIds.js';import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../shared/agentKindConversion.js';-import type { Session } from '../../renderer/lib/ccAgent.types';+import type { AgentMeta, Session } from '../../renderer/lib/ccAgent.types';+import { buildHandoffText, type HandoffSourceMessage } from '../maker-ipc/agentHandoff.js';import {type ClaudeTranscriptAnchorIndex,loadClaudeTranscriptAnchorIndex,@@ -53,9 +55,7 @@ function codexForkFailureDetail(err: unknown): string {}function normalizePositiveInt(value: unknown): number {- return typeof value === 'number' && Number.isFinite(value) && value > 0- ? Math.floor(value)- : 0;+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;}const messageRowid = sql<number>`rowid`;@@ -69,11 +69,14 @@ interface MessagePosition {interface ForkNativeSource {agentKind: DbAgentKind;- sdkSessionId: string;+ sdkSessionId: string | null;model: string;providerId: string | null;/** 目标所在原生 session 离场的位置;copy 不能把这条未来边界带进子会话。 */nextSwitch: MessagePosition | null;+ /** false = 原生会话已因同引擎换窗失效,只复制可见历史,首次发送走交接。 */+ reuseVendorSession: boolean;+ rebuildReason?: 'context-overflow' | 'pi-prompt-timeout';}interface ForkTimelineMessage {@@ -96,20 +99,123 @@ interface ParsedAgentSwitchBoundary {handoff?: string;}+function parseJsonContent(content: string): unknown {+ try {+ return JSON.parse(content) as unknown;+ } catch {+ return content;+ }+}++async function seedForkHandoffAfterSameEngineRebuild(opts: {+ sessionId: string;+ rows: ForkTimelineMessage[];+ agentKind: DbAgentKind;+ model: string;+ providerId: string | null;+ reason: 'context-overflow' | 'pi-prompt-timeout';+}): Promise<void> {+ const handoffMessages: HandoffSourceMessage[] = opts.rows+ .filter(+ (row) =>+ row.role !== 'error' && row.role !== 'context_rebuild' && row.role !== 'agent_switch',+ )+ .map((row) => ({+ role: row.role,+ content: parseJsonContent(row.content),+ createdAt: row.createdAt,+ toolUseId: row.toolUseId,+ }));+ const lastUser = [...opts.rows].reverse().find((row) => row.role === 'user');+ const label =+ opts.agentKind === 'codex' ? 'Codex' : opts.agentKind === 'pi' ? 'Pi' : 'Claude Code';+ const handoff = buildHandoffText(handoffMessages, {+ fromLabel: label,+ toLabel: label,+ sessionId: opts.sessionId,+ reason: opts.reason,+ });+ await commitContextRebuild(opts.sessionId, handoff, {+ reason: opts.reason,+ sourceUserClientId: lastUser?.clientId ?? null,+ sourceAgentKind: opts.agentKind,+ sourceModel: opts.model,+ sourceProviderId: opts.providerId,+ });+ await createMessage(opts.sessionId, {+ clientId: `context-rebuild-card:${createId()}`,+ role: 'assistant',+ content: '',+ agentKind: opts.agentKind === 'cc' ? 'cc' : opts.agentKind,+ agentMeta: {+ contextRebuild: {+ reason: opts.reason,+ handoff,+ },+ } as AgentMeta,+ });+}++interface ParsedContextRebuildBoundary {+ reason: 'context-overflow' | 'pi-prompt-timeout';+ sourceAgentKind?: DbAgentKind;+ sourceModel?: string | null;+ sourceProviderId?: string | null;+}++function parseContextRebuildBoundary(content: string): ParsedContextRebuildBoundary | null {+ try {+ const parsed = JSON.parse(content) as Record<string, unknown>;+ if (parsed.reason !== 'context-overflow' && parsed.reason !== 'pi-prompt-timeout') {+ return null;+ }+ return {+ reason: parsed.reason,+ ...(parsed.sourceAgentKind === 'cc' ||+ parsed.sourceAgentKind === 'codex' ||+ parsed.sourceAgentKind === 'pi'+ ? { sourceAgentKind: parsed.sourceAgentKind }+ : {}),+ ...(typeof parsed.sourceModel === 'string' ? { sourceModel: parsed.sourceModel } : {}),+ ...(Object.hasOwn(parsed, 'sourceProviderId')+ ? {+ sourceProviderId:+ typeof parsed.sourceProviderId === 'string' ? parsed.sourceProviderId : null,+ }+ : {}),+ };+ } catch {+ return null;+ }+}++function parseContextRebuildReason(+ content: string,+): 'context-overflow' | 'pi-prompt-timeout' | null {+ return parseContextRebuildBoundary(content)?.reason ?? null;+}+function parseAgentSwitchBoundary(content: string): ParsedAgentSwitchBoundary | null {try {const parsed = JSON.parse(content) as Record<string, unknown>;- if (parsed.fromAgentKind !== 'cc' && parsed.fromAgentKind !== 'codex' && parsed.fromAgentKind !== 'pi') return null;- const toAgentKind = parsed.toAgentKind === 'cc' || parsed.toAgentKind === 'codex' || parsed.toAgentKind === 'pi'- ? parsed.toAgentKind- : undefined;+ if (+ parsed.fromAgentKind !== 'cc' &&+ parsed.fromAgentKind !== 'codex' &&+ parsed.fromAgentKind !== 'pi'+ )+ return null;+ const toAgentKind =+ parsed.toAgentKind === 'cc' || parsed.toAgentKind === 'codex' || parsed.toAgentKind === 'pi'+ ? parsed.toAgentKind+ : undefined;return {fromAgentKind: parsed.fromAgentKind,toAgentKind,fromModel: typeof parsed.fromModel === 'string' ? parsed.fromModel : null,- fromSdkSessionId: typeof parsed.fromSdkSessionId === 'string' && parsed.fromSdkSessionId- ? parsed.fromSdkSessionId- : null,+ fromSdkSessionId:+ typeof parsed.fromSdkSessionId === 'string' && parsed.fromSdkSessionId+ ? parsed.fromSdkSessionId+ : null,handoff: typeof parsed.handoff === 'string' && parsed.handoff ? parsed.handoff : undefined,};} catch {@@ -148,8 +254,13 @@ async function resolveForkNativeSource(}const client = getDbClient();const positionParams = [sourceSessionId, target.createdAt, target.createdAt, target.rowid];- const invalidated = await client.queryOne<{ id: string }>(- `SELECT id FROM messages+ const invalidated = await client.queryOne<{+ id: string;+ content: string;+ created_at: number;+ rowid: number;+ }>(+ `SELECT id, content, created_at, rowid FROM messagesWHERE session_id = ?AND role = 'context_rebuild'AND (created_at > ? OR (created_at = ? AND rowid > ?))@@ -157,7 +268,9 @@ async function resolveForkNativeSource(LIMIT 1`,positionParams,);- if (invalidated) {+ const rebuildBoundary = invalidated ? parseContextRebuildBoundary(invalidated.content) : null;+ const rebuildReason = rebuildBoundary?.reason ?? null;+ if (invalidated && !rebuildBoundary) {throw forkError('UNSUPPORTED_HISTORY', '目标消息对应的历史引擎会话已因上下文重建失效');}const nextSwitch = await client.queryOne<{@@ -174,31 +287,67 @@ async function resolveForkNativeSource(LIMIT 1`,positionParams,);- if (!nextSwitch) {- if (!source.sdkSessionId) {- throw forkError('SOURCE_NEVER_RAN', '原会话尚未运行,无法 fork');+ if (+ nextSwitch &&+ (!invalidated ||+ isBefore(+ { createdAt: nextSwitch.created_at, rowid: nextSwitch.rowid },+ { createdAt: invalidated.created_at, rowid: invalidated.rowid },+ ))+ ) {+ const parsed = parseAgentSwitchBoundary(nextSwitch.content);+ if (!parsed?.fromSdkSessionId) {+ throw forkError('UNSUPPORTED_HISTORY', '目标消息对应的历史引擎会话不可用');}- const agentKind: DbAgentKind = normalizeDbAgentKind(source.agentKind);return {- agentKind,- sdkSessionId: source.sdkSessionId,+ agentKind: parsed.fromAgentKind,+ sdkSessionId: parsed.fromSdkSessionId,+ model: parsed.fromModel ?? source.model,+ providerId: parsed.fromAgentKind === source.agentKind ? source.providerId : null,+ nextSwitch: { createdAt: nextSwitch.created_at, rowid: nextSwitch.rowid },+ reuseVendorSession: true,+ };+ }+ if (rebuildReason) {+ if (rebuildBoundary?.sourceAgentKind) {+ return {+ agentKind: rebuildBoundary.sourceAgentKind,+ sdkSessionId: null,+ model: rebuildBoundary.sourceModel ?? source.model,+ providerId: Object.hasOwn(rebuildBoundary, 'sourceProviderId')+ ? (rebuildBoundary.sourceProviderId ?? null)+ : source.providerId,+ nextSwitch: null,+ reuseVendorSession: false,+ rebuildReason,+ };+ }+ // Legacy rebuild markers predate the source engine metadata. They are safe+ // only while the session stayed on the same engine after rebuilding; if a+ // later switch exists, fail closed instead of forking with the current engine.+ if (nextSwitch) {+ throw forkError('UNSUPPORTED_HISTORY', '无法确认目标消息对应的历史引擎');+ }+ return {+ agentKind: normalizeDbAgentKind(source.agentKind),+ sdkSessionId: null,model: source.model,providerId: source.providerId,nextSwitch: null,+ reuseVendorSession: false,+ rebuildReason,};}- const parsed = parseAgentSwitchBoundary(nextSwitch.content);- if (!parsed?.fromSdkSessionId) {- throw forkError('UNSUPPORTED_HISTORY', '目标消息对应的历史引擎会话不可用');+ if (!source.sdkSessionId) {+ throw forkError('SOURCE_NEVER_RAN', '原会话尚未运行,无法 fork');}return {- agentKind: parsed.fromAgentKind,- sdkSessionId: parsed.fromSdkSessionId,- model: parsed.fromModel ?? source.model,- // 边界没有保存历史 provider;只有仍处于同一 agent 时才继承当前凭证形态,- // 否则跟随目标 agent 默认 provider,不能把另一家引擎的 providerId 带过去。- providerId: parsed.fromAgentKind === source.agentKind ? source.providerId : null,- nextSwitch: { createdAt: nextSwitch.created_at, rowid: nextSwitch.rowid },+ agentKind: normalizeDbAgentKind(source.agentKind),+ sdkSessionId: source.sdkSessionId,+ model: source.model,+ providerId: source.providerId,+ nextSwitch: null,+ reuseVendorSession: true,};}@@ -263,12 +412,14 @@ async function countCodexTailTurns(sourceClearedAt: number | null,boundary: MessagePosition,): Promise<number> {- const rowPredicate = boundary.rowid === null- ? 'created_at >= ?'- : '(created_at > ? OR (created_at = ? AND rowid >= ?))';- const rowParams = boundary.rowid === null- ? [boundary.createdAt]- : [boundary.createdAt, boundary.createdAt, boundary.rowid];+ const rowPredicate =+ boundary.rowid === null+ ? 'created_at >= ?'+ : '(created_at > ? OR (created_at = ? AND rowid >= ?))';+ const rowParams =+ boundary.rowid === null+ ? [boundary.createdAt]+ : [boundary.createdAt, boundary.createdAt, boundary.rowid];const rows = await getDbClient().query<{role: string;content: string;@@ -356,8 +507,9 @@ function collectLegacyClaudeTranscriptParentUuids(// Imported Claude rows may use a synthetic per-content-block UUID. The// assistant request id is the stable bridge back to the real transcript// entry in that case; keep the database UUID as the migration key below.- const entry = index.byUuid.get(meta.uuid)- ?? (meta.requestId ? index.assistantByRequestId.get(meta.requestId) : undefined);+ const entry =+ index.byUuid.get(meta.uuid) ??+ (meta.requestId ? index.assistantByRequestId.get(meta.requestId) : undefined);if (!entry) continue;// Top-level assistants and every non-assistant transcript record use// parentUuid as the legacy transcript edge. A legacy subagent assistant@@ -387,8 +539,9 @@ function collectClaudeToolParentUuids(for (const row of rows) {const meta = parseClaudeAgentMeta(row.agentMeta);if (!meta.parentUuid) continue;- const entry = (meta.uuid ? index.byUuid.get(meta.uuid) : undefined)- ?? (meta.requestId ? index.assistantByRequestId.get(meta.requestId) : undefined);+ const entry =+ (meta.uuid ? index.byUuid.get(meta.uuid) : undefined) ??+ (meta.requestId ? index.assistantByRequestId.get(meta.requestId) : undefined);if (entry?.toolParentUuid === meta.parentUuid) uuids.add(meta.parentUuid);}return [...uuids];@@ -447,9 +600,7 @@ export async function forkSessionAtMessage(rowid: messageRowid,}).from(messages)- .where(- and(eq(messages.sessionId, sourceSessionId), eq(messages.clientId, messageClientId)),- )+ .where(and(eq(messages.sessionId, sourceSessionId), eq(messages.clientId, messageClientId))).limit(1);if (!target) {throw forkError('MESSAGE_NOT_FOUND', `Message ${messageClientId} 不存在于 ${sourceSessionId}`);@@ -538,7 +689,7 @@ export async function forkSessionAtMessage(target.role,forkSource.agentKind,);- if (!usesTailTurnFork) {+ if (!usesTailTurnFork && forkSource.sdkSessionId) {claudeAnchorIndex = await loadClaudeTranscriptAnchorIndex({sdkSessionId: forkSource.sdkSessionId,workingDir: source.workingDir,@@ -551,12 +702,9 @@ export async function forkSessionAtMessage(// 切换后的首条 user 自身不进子分支。fresh Claude session 在它之前没有可 fork// 的 assistant 锚点,此时创建未绑定的新会话,并把复制边界恢复为 pending handoff。if (!assistantUuid && !resetHandoffBoundaryClientId) {- throw forkError(- 'NO_PRIOR_ASSISTANT',- '请在 AI 回复之后的提问上 fork',- );+ throw forkError('NO_PRIOR_ASSISTANT', '请在 AI 回复之后的提问上 fork');}- } else {+ } else if (forkSource.reuseVendorSession && forkSource.sdkSessionId) {tailTurnsToDrop = await countCodexTailTurns(sourceSessionId,source.sdkSessionId,@@ -572,29 +720,32 @@ export async function forkSessionAtMessage(let newSdkSessionId: string | null = null;let uuidMap = new Map<string, string>();let initialContextTokens: number | undefined;- if (usesTailTurnFork || assistantUuid) {+ if (+ forkSource.reuseVendorSession &&+ forkSource.sdkSessionId &&+ (usesTailTurnFork || assistantUuid)+ ) {const agentKind = dbToMakerAgentKind(forkSource.agentKind);- const forkResult = await getMaker().forkSdkSession(agentKind, {- sourceSdkSessionId: forkSource.sdkSessionId,- ...(isCodex ? { model: forkSource.model, providerId: forkSource.providerId } : {}),- upToMessageId: assistantUuid,- ...(tailTurnsToDrop !== undefined ? { tailTurnsToDrop } : {}),- title: newTitle,- workingDir: source.workingDir ?? undefined,- // Pi 的 fork 守卫判定源 session 是否远端(用 DB 的 remoteHostId, 不用- // agent 实例字段 —— R4 竞态 #1)。- remoteHostId: source.remoteHostId ?? null,- }).catch((err: unknown) => {- // 这里刻意用 isCodex(非 usesTailTurnFork):CODEX_FORK_STATE_UNAVAILABLE 是 codex 专属- // 错误码 + 文案,只有真 codex 失败才包装。pi 与 cc 一样裸抛原始错误(不会拿到指名道姓- // 错对象的 "Codex 状态不可用" 提示)。改成 usesTailTurnFork 会让 pi 误报成 codex 错误。- if (!isCodex) throw err;- const detail = codexForkFailureDetail(err);- throw forkError(- 'CODEX_FORK_STATE_UNAVAILABLE',- detail,- );- });+ const forkResult = await getMaker()+ .forkSdkSession(agentKind, {+ sourceSdkSessionId: forkSource.sdkSessionId,+ ...(isCodex ? { model: forkSource.model, providerId: forkSource.providerId } : {}),+ upToMessageId: assistantUuid,+ ...(tailTurnsToDrop !== undefined ? { tailTurnsToDrop } : {}),+ title: newTitle,+ workingDir: source.workingDir ?? undefined,+ // Pi 的 fork 守卫判定源 session 是否远端(用 DB 的 remoteHostId, 不用+ // agent 实例字段 —— R4 竞态 #1)。+ remoteHostId: source.remoteHostId ?? null,+ })+ .catch((err: unknown) => {+ // 这里刻意用 isCodex(非 usesTailTurnFork):CODEX_FORK_STATE_UNAVAILABLE 是 codex 专属+ // 错误码 + 文案,只有真 codex 失败才包装。pi 与 cc 一样裸抛原始错误(不会拿到指名道姓+ // 错对象的 "Codex 状态不可用" 提示)。改成 usesTailTurnFork 会让 pi 误报成 codex 错误。+ if (!isCodex) throw err;+ const detail = codexForkFailureDetail(err);+ throw forkError('CODEX_FORK_STATE_UNAVAILABLE', detail);+ });({ newSdkSessionId, uuidMap, initialContextTokens } = forkResult);}const forkContextTokens = normalizePositiveInt(initialContextTokens);@@ -617,49 +768,49 @@ export async function forkSessionAtMessage(? []: collectClaudeToolParentUuids(sourceMessages, claudeAnchorIndex);try {- await getDbClient().tx('fork.session', {- sourceSessionId,- sourceClearedAt: source.clearedAt,- targetCreatedAt: copyBoundary.createdAt,- targetRowid: copyBoundary.rowid,- newSession: {- id: newSessionId,- title: newTitle,- workingDir: source.workingDir,- model: forkSource.model,- // 同一 agent 的 fork 继承 providerId,避免凭证形态漂移;历史跨 agent 片段- // 没有可靠的 provider 快照,使用 null 跟随目标 agent 的默认 provider。- providerId: forkSource.providerId,- effort: source.effort,- permissionMode: source.permissionMode,- status: 'active',- sdkSessionId: newSdkSessionId,- totalTokenUsage: 0,- totalCostUsd: 0,- contextTokens: forkContextTokens,- contextWindow: forkContextWindow,- fastMode: forkSource.agentKind === source.agentKind ? source.fastMode : false,- clearedAt: null,- pinnedAt: null,- userSendAt: now,- agentKind: forkSource.agentKind,- workspaceKind: source.workspaceKind,- // 轮 26 HIGH-1:远端会话 fork 必须继承 remoteHostId —— 缺失会落成- // NULL, 子会话被下游当成本地会话处理(本地 transport/MCP 全错)。- remoteHostId: source.remoteHostId ?? null,- codexHistoryHasProductPrompt: source.codexHistoryHasProductPrompt,- parentSessionId: source.id,- forkedAtMessageId: messageClientId,- createdAt: now,- updatedAt: now,- },- uuidMap: Array.from(txUuidMap.entries()),- ...(legacyTranscriptParentUuids.length > 0 ? { legacyTranscriptParentUuids } : {}),- ...(toolParentUuids.length > 0 ? { toolParentUuids } : {}),- detachAgentSwitchSessions: true,- resetHandoffBoundaryClientId,- newMessageIds,- });+ await getDbClient().tx('fork.session', {+ sourceSessionId,+ sourceClearedAt: source.clearedAt,+ targetCreatedAt: copyBoundary.createdAt,+ targetRowid: copyBoundary.rowid,+ newSession: {+ id: newSessionId,+ title: newTitle,+ workingDir: source.workingDir,+ model: forkSource.model,+ // 同一 agent 的 fork 继承 providerId,避免凭证形态漂移;历史跨 agent 片段+ // 没有可靠的 provider 快照,使用 null 跟随目标 agent 的默认 provider。+ providerId: forkSource.providerId,+ effort: source.effort,+ permissionMode: source.permissionMode,+ status: 'active',+ sdkSessionId: newSdkSessionId,+ totalTokenUsage: 0,+ totalCostUsd: 0,+ contextTokens: forkContextTokens,+ contextWindow: forkContextWindow,+ fastMode: forkSource.agentKind === source.agentKind ? source.fastMode : false,+ clearedAt: null,+ pinnedAt: null,+ userSendAt: now,+ agentKind: forkSource.agentKind,+ workspaceKind: source.workspaceKind,+ // 轮 26 HIGH-1:远端会话 fork 必须继承 remoteHostId —— 缺失会落成+ // NULL, 子会话被下游当成本地会话处理(本地 transport/MCP 全错)。+ remoteHostId: source.remoteHostId ?? null,+ codexHistoryHasProductPrompt: source.codexHistoryHasProductPrompt,+ parentSessionId: source.id,+ forkedAtMessageId: messageClientId,+ createdAt: now,+ updatedAt: now,+ },+ uuidMap: Array.from(txUuidMap.entries()),+ ...(legacyTranscriptParentUuids.length > 0 ? { legacyTranscriptParentUuids } : {}),+ ...(toolParentUuids.length > 0 ? { toolParentUuids } : {}),+ detachAgentSwitchSessions: true,+ resetHandoffBoundaryClientId,+ newMessageIds,+ });} catch (err) {// 轮 40-w4-t13 HIGH:SDK 侧已创建新 session file(forkSdkSession), DB 事务// 失败时该文件成孤儿 —— 调用方收到失败, 但孤儿累积不可达。至少记录@@ -678,6 +829,16 @@ export async function forkSessionAtMessage(if (!row) {throw new Error('Fork session 创建后查询失败');}+ if (!forkSource.reuseVendorSession && forkSource.rebuildReason) {+ await seedForkHandoffAfterSameEngineRebuild({+ sessionId: newSessionId,+ rows: sourceMessages,+ agentKind: forkSource.agentKind,+ model: forkSource.model,+ providerId: forkSource.providerId,+ reason: forkSource.rebuildReason,+ });+ }return sessionToCamel({ ...row, messageCount: sourceMessages.length });}@@ -700,7 +861,10 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis// 远端 Codex 会话的 rollout 在远端机器上,本地 forkSdkSession 走本地 host 找不到,// 会失败或建出指向远端 workdir 的本地会话。本期不支持 → 显式拒绝(UI 也已隐藏入口)。if (source.remoteHostId) {- throw forkError('REMOTE_NOT_SUPPORTED', '远端 Codex 会话暂不支持剥离 fork(rollout 在远端,本地无法剥离)');+ throw forkError(+ 'REMOTE_NOT_SUPPORTED',+ '远端 Codex 会话暂不支持剥离 fork(rollout 在远端,本地无法剥离)',+ );}if (!source.sdkSessionId) {throw forkError('SOURCE_NEVER_RAN', '原会话尚未运行,无法 fork');@@ -709,11 +873,13 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promisconst sourceMessages = await db.select().from(messages)- .where(and(- eq(messages.sessionId, sourceSessionId),- source.clearedAt === null ? undefined : gt(messages.createdAt, source.clearedAt),- isNull(messages.rewindAt),- ))+ .where(+ and(+ eq(messages.sessionId, sourceSessionId),+ source.clearedAt === null ? undefined : gt(messages.createdAt, source.clearedAt),+ isNull(messages.rewindAt),+ ),+ ).orderBy(asc(messages.createdAt), asc(messageRowid));const maxCreatedAt = sourceMessages.reduce((max, message) => Math.max(max, Number(message.createdAt ?? 0)),@@ -730,24 +896,23 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promisconst newTitle = source.title.startsWith('[Fork·已剥离]')? source.title: `[Fork·已剥离] ${source.title}`;- const { newSdkSessionId, uuidMap } = await getMaker().forkSdkSession('codex', {- sourceSdkSessionId: source.sdkSessionId,- model: source.model,- providerId: source.providerId,- upToMessageId: undefined,- title: newTitle,- workingDir: source.workingDir ?? undefined,- stripEncryptedReasoning: true,- // 轮 26:与 forkSessionAtMessage 对齐 —— 源必为本地(上方已拒远端), 显式- // 传 null 保持 forkSdkSession 参数形态一致。- remoteHostId: source.remoteHostId ?? null,- }).catch((err: unknown) => {- const detail = codexForkFailureDetail(err);- throw forkError(- 'CODEX_FORK_STATE_UNAVAILABLE',- detail,- );- });+ const { newSdkSessionId, uuidMap } = await getMaker()+ .forkSdkSession('codex', {+ sourceSdkSessionId: source.sdkSessionId,+ model: source.model,+ providerId: source.providerId,+ upToMessageId: undefined,+ title: newTitle,+ workingDir: source.workingDir ?? undefined,+ stripEncryptedReasoning: true,+ // 轮 26:与 forkSessionAtMessage 对齐 —— 源必为本地(上方已拒远端), 显式+ // 传 null 保持 forkSdkSession 参数形态一致。+ remoteHostId: source.remoteHostId ?? null,+ })+ .catch((err: unknown) => {+ const detail = codexForkFailureDetail(err);+ throw forkError('CODEX_FORK_STATE_UNAVAILABLE', detail);+ });const now = Date.now();const newSessionId = createBusinessSessionId();diff --git a/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsxindex be4f0a7f15..c9f5cb1306 100644--- a/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx+++ b/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx@@ -74,6 +74,23 @@ describe('ErrorBanner Codex xAI auth classification', () => {});});+describe('ErrorBanner context-overflow retry', () => {+ it('keeps Retry when automatic rollover failed and recovery is still available', () => {+ const onRetry = vi.fn();+ render(+ createElement(ErrorBanner, {+ error: "This model's maximum prompt length is 500000",+ errorReason: 'context-overflow',+ retryText: 'retry-token',+ onRetry,+ }),+ );+ const retry = screen.getByTitle('chat.errorBanner.retryTitle');+ fireEvent.click(retry);+ expect(onRetry).toHaveBeenCalledWith('retry-token');+ });+});+describe('ErrorBanner network retry guidance', () => {it('shows Codex reconnect progress while the turn keeps running', () => {render(createElement(ErrorBanner, {diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.tsindex 6733e1e56a..228e47d372 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts@@ -155,3 +155,38 @@ describe('agent switch 历史投影', () => {expect(card?.systemCardData).toMatchObject({ resumed: true });});});++describe('context rebuild 历史投影', () => {+ it('把可见交接行投影成可展开的 context-rebuild 卡', async () => {+ const id = sid('context-rebuild-card');+ transportMocks.listMessages.mockResolvedValueOnce([+ {+ id: 'row-rebuild',+ clientId: 'context-rebuild-card:1',+ sessionId: id,+ role: 'assistant',+ content: '',+ agentMeta: {+ contextRebuild: {+ reason: 'pi-prompt-timeout',+ handoff: 'stopped responding to prompts',+ },+ },+ createdAt: Date.now(),+ },+ ] as never);++ makerChatStore.ensureInitialMessages(id);+ await vi.waitFor(() => {+ expect(makerChatStore.getSnapshot(id).historyLoaded).toBe(true);+ });++ const card = makerChatStore+ .getSnapshot(id)+ .messages.find((message) => message.systemCardType === 'context-rebuild');+ expect(card?.systemCardData).toMatchObject({+ reason: 'pi-prompt-timeout',+ handoff: 'stopped responding to prompts',+ });+ });+});diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsxindex 905695ffbe..3499d65e42 100644--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx@@ -52,7 +52,8 @@ interface SystemCardProps {| 'review'| 'auto-resume'| 'auto-resume-pending'- | 'agent-switch';+ | 'agent-switch'+ | 'context-rebuild';data?: Record<string, unknown>;/*** 这条自愈记录此刻是否真的在飞(会话有在跑的 turn,且它就是那个 turn 的发起者)。@@ -1133,6 +1134,68 @@ function AgentSwitchCard({ data }: { data?: Record<string, unknown> }) {);}+function ContextRebuildCard({ data }: { data?: Record<string, unknown> }) {+ const { t } = useTranslation();+ const [expanded, setExpanded] = useState(false);+ const handoff = typeof data?.handoff === 'string' ? data.handoff : '';+ const reason = data?.reason === 'pi-prompt-timeout' ? 'timeout' : 'overflow';+ const label = t(+ reason === 'timeout'+ ? 'chat.systemCard.contextRebuild.labelTimeout'+ : 'chat.systemCard.contextRebuild.labelOverflow',+ );++ return (+ <div className="w-full select-none py-2" role="separator" aria-label={label}>+ <div className="flex w-full items-center gap-3">+ <div className="h-px flex-1 bg-[var(--msg-tool-card-border)]" />+ <button+ type="button"+ onClick={() => handoff && setExpanded((v) => !v)}+ className={cn(+ 'flex min-w-0 items-center gap-1.5 rounded-full border border-[var(--msg-tool-card-border)]',+ 'bg-background/50 px-2.5 py-1 text-11 text-muted-foreground',+ handoff && 'cursor-pointer hover:bg-[var(--msg-tool-card-bg)]',+ )}+ aria-expanded={expanded}+ title={handoff ? t('chat.systemCard.contextRebuild.toggleHint') : undefined}+ >+ <RefreshCw size={12} className="shrink-0" />+ <span>{label}</span>+ {handoff && (+ <ChevronRight+ size={12}+ className={cn('shrink-0 transition-transform', expanded && 'rotate-90')}+ />+ )}+ </button>+ <div className="h-px flex-1 bg-[var(--msg-tool-card-border)]" />+ </div>+ <Collapse open={expanded && !!handoff}>+ {handoff ? (+ <div+ className={cn(+ 'mx-auto mt-2 max-w-full rounded-[10px] border border-[var(--msg-tool-card-border)]',+ 'bg-[var(--msg-tool-card-bg)] px-4 py-3 select-text',+ )}+ >+ <div className="mb-1.5 text-11 font-medium text-muted-foreground">+ {t(+ isEnglishSourceHandoff(handoff)+ ? 'chat.systemCard.contextRebuild.handoffTitleEnglishSource'+ : 'chat.systemCard.contextRebuild.handoffTitle',+ )}+ </div>+ <pre className="max-h-64 overflow-y-auto whitespace-pre-wrap break-words font-mono text-12 leading-[1.55] text-[var(--msg-tool-text)]">+ {handoff}+ </pre>+ </div>+ ) : null}+ </Collapse>+ </div>+ );+}+const REVIEW_FAILURE_I18N_KEY: Record<ReviewFailureCode, string> = {'no-visible-result': 'chat.systemCard.review.noResult','reviewer-closed': 'chat.systemCard.review.failure.reviewerClosed',@@ -1240,6 +1303,8 @@ export function SystemCard({return <AutoResumeActionRow state="live" info={readAutoResumeInfo(data)} />;case 'agent-switch':return <AgentSwitchCard data={data} />;+ case 'context-rebuild':+ return <ContextRebuildCard data={data} />;case 'learn':return <LearnStatusCard data={data} contextSessionId={sessionId} />;case 'review':diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.tsindex 579e19e892..90a3ba6bdf 100644--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts@@ -28,6 +28,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {'logic.errors.codexCompactionNotConvergingModelSwitch',session_event_loop_crashed: 'logic.errors.turnFailed',turn_no_event_timeout: 'logic.errors.turnNoEventTimeout',+ 'context-overflow': 'chat.errorBanner.contextOverflow',[UPSTREAM_OVERLOAD_REASON]: 'chat.errorBanner.overloadBusyNoRetry',[CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON]: 'chat.errorBanner.claudeGatewayOpusPlanMismatch',[CLAUDE_SUBSCRIPTION_OPUS_PLAN_MISMATCH_REASON]:diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 922fa4d31f..d6eff82946 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -5986,9 +5986,8 @@ export function ChatInput({/*** 切模型前的上下文容量护栏(大窗口 → 小窗口场景)。- * 为什么必须在**切换前**拦: `/compact` 自救本身是一次 LLM 调用, 要把全量历史喂给- * "当前模型" —— 切到小窗口模型之后连压缩请求都可能超限, 只有还没切走的大窗口模型- * 能读完整历史。分级语义见 shared/modelSwitchAssessment.ts。+ * 分级语义见 shared/modelSwitchAssessment.ts。overflow 确认后由 host 交接换窗,+ * 不要再建议用户先 /compact —— 小窗口模型压整段历史同样会失败。* 返回 false = 用户取消, 调用方直接放弃本次切换(无任何副作用)。* fail-open: 占用未知(0)/ 目标窗口未知 / 阈值读取失败都不拦。*/@@ -6032,12 +6031,17 @@ export function ChatInput({// 期望用户先取消回去压缩(点上下文圆环)或新开会话, "仍然切换"是次选。return confirmDialog({title: t('newChat.chatInput.modelSwitchContextGuard.title'),- description: t('newChat.chatInput.modelSwitchContextGuard.overflowDescription', vars),+ description: t(+ remoteHostId+ ? 'newChat.chatInput.modelSwitchContextGuard.overflowDescriptionRemote'+ : 'newChat.chatInput.modelSwitchContextGuard.overflowDescription',+ vars,+ ),confirmText: t('newChat.chatInput.modelSwitchContextGuard.confirmSwitch'),cancelText: t('newChat.chatInput.modelSwitchContextGuard.cancelSwitch'),});},- [sessionId, confirmDialog, t],+ [sessionId, remoteHostId, confirmDialog, t],);// session-agent-switch 意图制:选中「只属于另一家引擎」的模型 → 只向 main 登记diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f1cb168464..462894ad40 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6603,11 +6603,12 @@"effortRuntimeDirty": "Reasoning effort is still updating. Wait a moment, then send again.","credentialSwitchApplied": "Model provider switch is now in effect.","modelSwitchContextGuard": {- "title": "Target model has a smaller context window",- "warnToast": "This session uses {{used}} of context — about {{pct}}% of the target model's {{total}} window after switching",- "overflowDescription": "This session uses {{used}} of context, exceeding the target model's {{total}} window (about {{pct}}%). After switching, replies and even compaction may fail. Compact the session first (click the context ring) or start a new session for this model. Switch anyway?",- "confirmSwitch": "Switch model anyway",- "cancelSwitch": "Cancel switch"+ "title": "This model can't fit the current conversation",+ "warnToast": "This conversation already uses {{used}} — about {{pct}}% of the new model's {{total}} capacity",+ "overflowDescription": "This conversation already uses {{used}}, more than the new model can hold ({{total}}, about {{pct}}%). If you switch, Cindy will make a short summary and continue. Your chat history stays; it just won't all be passed through verbatim.",+ "overflowDescriptionRemote": "This conversation already uses {{used}}, more than the new model can hold ({{total}}, about {{pct}}%). On a remote session Cindy cannot rebuild a fresh agent context, so the next request may still fail. You can switch anyway, or keep this model.",+ "confirmSwitch": "Switch and continue",+ "cancelSwitch": "Keep this model"},"agentSwitch": {"engineNotReady": "Engine switched, but the new engine failed to start; it will retry when you send a message",@@ -6987,7 +6988,8 @@"silentStopContinueTitle": "Continue the current task","piTransportClosed": "Remote Pi connection interrupted (SSH channel closed). The remote task is still running — reconnect to continue.","piManagerUnavailable": "Remote Pi manager is not ready. Retry shortly; if it keeps failing, reinstall Pi under Settings → Remote Machines.",- "piBundledNodeMissing": "The remote host is missing its runtime (Node.js). Expand the host under Settings → Remote Machines and click Install on Claude Code or Codex first (they bundle Node.js), then start a Pi task."+ "piBundledNodeMissing": "The remote host is missing its runtime (Node.js). Expand the host under Settings → Remote Machines and click Install on Claude Code or Codex first (they bundle Node.js), then start a Pi task.",+ "contextOverflow": "This message itself exceeds the model's context window, so Cindy cannot continue it in a fresh agent session. Shorten the input or remove a large attachment, then try again."},"backgroundActivity": {"status": "Background subtasks running, still consuming model usage…",@@ -7318,6 +7320,13 @@"handoffTitleEnglishSource": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)","resumedBadge": "session resumed"},+ "contextRebuild": {+ "labelOverflow": "Context reorganized, continuing",+ "labelTimeout": "Last turn didn't respond; context reorganized to continue",+ "toggleHint": "View handoff context",+ "handoffTitle": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)",+ "handoffTitleEnglishSource": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)"+ },"review": {"running": "Reviewing current work","completed": "Review complete",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a9e203a67e..04e3e518af 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6601,11 +6601,12 @@"effortRuntimeDirty": "推論強度を更新しています。少し待ってからもう一度送信してください。","credentialSwitchApplied": "モデルプロバイダーの切り替えが有効になりました。","modelSwitchContextGuard": {- "title": "切替先モデルのコンテキストウィンドウが小さいです",- "warnToast": "このセッションは {{used}} のコンテキストを使用中です。切替後は切替先モデルのウィンドウ({{total}})の約 {{pct}}% を占めます",- "overflowDescription": "このセッションは {{used}} のコンテキストを使用中で、切替先モデルのウィンドウ({{total}}、約 {{pct}}%)を超えています。切替後は応答も圧縮も失敗する可能性があります。先にコンテキストリングをクリックしてセッションを圧縮するか、新しいセッションでこのモデルを使用してください。それでも切り替えますか?",- "confirmSwitch": "モデルを切り替える",- "cancelSwitch": "切替をキャンセル"+ "title": "このモデルには今の会話が収まりません",+ "warnToast": "この会話はすでに {{used}} 使っています。切替後は新しいモデルの容量({{total}})の約 {{pct}}% になります",+ "overflowDescription": "この会話はすでに {{used}} 使っており、新しいモデルが扱える {{total}}(約 {{pct}}%)を超えています。切り替えると、Cindy が要約してから続けます。チャット履歴は残りますが、全文をそのままは渡しません。",+ "overflowDescriptionRemote": "この会話はすでに {{used}} 使っており、新しいモデルが扱える {{total}}(約 {{pct}}%)を超えています。リモートのタスクでは自動的に新しいエージェント文脈へ引き継げないため、次の送信が失敗する可能性があります。このまま切り替えるか、今のモデルのままにしてください。",+ "confirmSwitch": "切り替えて続ける",+ "cancelSwitch": "今は切り替えない"},"agentSwitch": {"engineNotReady": "エンジンは切り替わりましたが、新しいエンジンの起動に失敗しました。メッセージ送信時に自動的に再試行されます",@@ -6984,7 +6985,8 @@"silentStopContinueTitle": "現在のタスクを続行","piTransportClosed": "リモート Pi の接続が切断されました(SSH チャンネルが閉じました)。リモートのタスクは実行中のままです。再接続すると続行できます。","piManagerUnavailable": "リモート Pi マネージャーが準備できていません。しばらくして再試行してください。失敗が続く場合は「設定 → リモートマシン」で Pi を再インストールしてください。",- "piBundledNodeMissing": "リモートホストに実行環境(Node.js)がありません。「設定 → リモートマシン」でホストを展開し、まず Claude Code または Codex の「インストール」をクリックしてください(Node.js もインストールされます)。その後 Pi タスクを開始してください。"+ "piBundledNodeMissing": "リモートホストに実行環境(Node.js)がありません。「設定 → リモートマシン」でホストを展開し、まず Claude Code または Codex の「インストール」をクリックしてください(Node.js もインストールされます)。その後 Pi タスクを開始してください。",+ "contextOverflow": "このメッセージ自体がモデルのコンテキスト上限を超えているため、同じセッション内で自動的に新しいエージェントセッションへ引き継げません。入力を短くするか大きな添付を外してから再試行してください。"},"backgroundActivity": {"status": "バックグラウンドのサブタスクが実行中、モデル使用量を消費しています…",@@ -7315,6 +7317,13 @@"handoffTitleEnglishSource": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)","resumedBadge": "セッション再開"},+ "contextRebuild": {+ "labelOverflow": "コンテキストを整理して続行しました",+ "labelTimeout": "直前の応答がなかったため、整理して続行しました",+ "toggleHint": "引き継ぎ内容を表示",+ "handoffTitle": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",+ "handoffTitleEnglishSource": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)"+ },"review": {"running": "現在の成果をレビュー中","completed": "レビュー完了",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 8df1971aa1..a829df0f5f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6601,11 +6601,12 @@"effortRuntimeDirty": "추론 강도를 업데이트하고 있습니다. 잠시 후 다시 전송해 주세요.","credentialSwitchApplied": "모델 제공자 전환이 적용되었습니다.","modelSwitchContextGuard": {- "title": "대상 모델의 컨텍스트 창이 더 작습니다",- "warnToast": "이 세션은 {{used}}의 컨텍스트를 사용 중입니다. 전환 후 대상 모델 창({{total}})의 약 {{pct}}%를 차지합니다",- "overflowDescription": "이 세션은 {{used}}의 컨텍스트를 사용 중이며, 대상 모델 창({{total}}, 약 {{pct}}%)을 초과합니다. 전환 후에는 응답과 압축이 모두 실패할 수 있습니다. 먼저 컨텍스트 링을 클릭해 세션을 압축하거나 새 세션에서 이 모델을 사용하세요. 그래도 전환하시겠습니까?",- "confirmSwitch": "모델 전환 진행",- "cancelSwitch": "전환 취소"+ "title": "이 모델에는 지금 대화를 다 넣을 수 없습니다",+ "warnToast": "이 대화는 이미 {{used}}를 사용 중입니다. 바꾸면 새 모델 용량({{total}})의 약 {{pct}}%가 됩니다",+ "overflowDescription": "이 대화는 이미 {{used}}를 사용 중이며, 새 모델이 담을 수 있는 {{total}}(약 {{pct}}%)를 넘습니다. 바꾸면 Cindy가 요약을 만든 뒤 이어서 진행합니다. 채팅 기록은 그대로 있고, 전체를 그대로 넘기지는 않습니다.",+ "overflowDescriptionRemote": "이 대화는 이미 {{used}}를 사용 중이며, 새 모델이 담을 수 있는 {{total}}(약 {{pct}}%)를 넘습니다. 원격 작업에서는 자동으로 새 에이전트 문맥을 이어갈 수 없어 다음 요청이 실패할 수 있습니다. 그대로 바꾸거나 현재 모델을 유지하세요.",+ "confirmSwitch": "바꾸고 계속하기",+ "cancelSwitch": "지금은 바꾸지 않기"},"agentSwitch": {"engineNotReady": "엔진이 전환되었지만 새 엔진 시작에 실패했습니다. 메시지를 보낼 때 자동으로 재시도됩니다",@@ -6984,7 +6985,8 @@"silentStopContinueTitle": "현재 작업 계속","piTransportClosed": "원격 Pi 연결이 끊어졌습니다(SSH 채널 닫힘). 원격 작업은 계속 실행 중입니다. 다시 연결하면 계속할 수 있습니다.","piManagerUnavailable": "원격 Pi 관리자가 준비되지 않았습니다. 잠시 후 다시 시도하세요. 계속 실패하면 「설정 → 원격 머신」에서 Pi를 다시 설치하세요.",- "piBundledNodeMissing": "원격 호스트에 런타임(Node.js)이 없습니다. 「설정 → 원격 머신」에서 호스트를 펼쳐 먼저 Claude Code 또는 Codex의 「설치」를 클릭하세요(Node.js가 함께 설치됨). 그런 다음 Pi 작업을 시작하세요."+ "piBundledNodeMissing": "원격 호스트에 런타임(Node.js)이 없습니다. 「설정 → 원격 머신」에서 호스트를 펼쳐 먼저 Claude Code 또는 Codex의 「설치」를 클릭하세요(Node.js가 함께 설치됨). 그런 다음 Pi 작업을 시작하세요.",+ "contextOverflow": "이 메시지 자체가 모델 컨텍스트 한도를 초과해서, 같은 세션에서 새 에이전트 세션으로 자동 이어갈 수 없습니다. 입력을 줄이거나 큰 첨부파일을 제거한 뒤 다시 시도하세요."},"backgroundActivity": {"status": "백그라운드 하위 작업 실행 중, 모델 사용량을 소비하고 있습니다…",@@ -7315,6 +7317,13 @@"handoffTitleEnglishSource": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)","resumedBadge": "세션 재개됨"},+ "contextRebuild": {+ "labelOverflow": "컨텍스트를 정리하고 계속합니다",+ "labelTimeout": "직전 응답이 없어 정리한 뒤 계속합니다",+ "toggleHint": "인계 내용 보기",+ "handoffTitle": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",+ "handoffTitleEnglishSource": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)"+ },"review": {"running": "현재 결과물을 검토하는 중","completed": "검토 완료",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 49d9adf01c..c282f24e35 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6601,11 +6601,12 @@"effortRuntimeDirty": "推理强度还在更新,稍等一下再发送","credentialSwitchApplied": "模型来源切换已生效。","modelSwitchContextGuard": {- "title": "目标模型的上下文窗口较小",- "warnToast": "当前任务已使用 {{used}} 上下文,切换后约占目标模型窗口({{total}})的 {{pct}}%",- "overflowDescription": "当前任务已使用 {{used}} 上下文,超出目标模型窗口({{total}},约 {{pct}}%)。切换后回复和压缩都可能失败,建议先点击上下文圆环压缩对话,或新建任务使用该模型。仍要切换吗?",- "confirmSwitch": "仍然切换模型",- "cancelSwitch": "取消切换"+ "title": "这个模型装不下当前对话",+ "warnToast": "这段对话已经用了 {{used}},换过去大约会占新模型容量({{total}})的 {{pct}}%",+ "overflowDescription": "这段对话已经用了 {{used}},超过新模型能放下的 {{total}}(约 {{pct}}%)。换过去后,Cindy 会先整理一份摘要再继续;对话记录还在,只是不会整段原样带给新模型。",+ "overflowDescriptionRemote": "这段对话已经用了 {{used}},超过新模型能放下的 {{total}}(约 {{pct}}%)。远程任务不会自动换窗,下一次发送仍可能失败。可以仍然切换,或留在当前模型。",+ "confirmSwitch": "切换并继续",+ "cancelSwitch": "先不换"},"agentSwitch": {"engineNotReady": "引擎已切换,但新引擎启动失败;发送消息时会自动重试",@@ -6984,7 +6985,8 @@"silentStopContinueTitle": "继续当前任务","piTransportClosed": "远端 Pi 连接已中断(SSH 通道关闭)。远端任务仍在运行,重新连接后可以继续。","piManagerUnavailable": "远端 Pi 管理器未就绪,请稍后重试;若持续失败请到「设置 → 远端机器」重新安装 Pi。",- "piBundledNodeMissing": "远端缺少运行环境(Node.js)。请到「设置 → 远端机器」展开该主机,先在 Claude Code 或 Codex 行点击「安装」(会附带 Node.js),再创建 Pi 任务。"+ "piBundledNodeMissing": "远端缺少运行环境(Node.js)。请到「设置 → 远端机器」展开该主机,先在 Claude Code 或 Codex 行点击「安装」(会附带 Node.js),再创建 Pi 任务。",+ "contextOverflow": "这条消息本身已经超过模型上下文上限,没法在当前 Agent 里自动换窗继续。请缩短输入或去掉超大附件后再试。"},"backgroundActivity": {"status": "后台子任务运行中,模型用量仍在消耗…",@@ -7315,6 +7317,13 @@"handoffTitleEnglishSource": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)","resumedBadge": "已续接原任务"},+ "contextRebuild": {+ "labelOverflow": "已整理上下文并继续",+ "labelTimeout": "上一轮没有响应,已整理后继续",+ "toggleHint": "查看交接内容",+ "handoffTitle": "交接内容——整理后发送给后续对话的上下文摘要(不计入对话记录,仅在此展示)",+ "handoffTitleEnglishSource": "交接内容——整理后发送给后续对话的上下文摘要,原文为英文(不计入对话记录,仅在此展示)"+ },"review": {"running": "正在审查当前成果","completed": "审查完成",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex bd303ba912..b4a9ea2483 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6601,11 +6601,12 @@"effortRuntimeDirty": "推理強度還在更新,稍等一下再傳送","credentialSwitchApplied": "模型來源切換已生效。","modelSwitchContextGuard": {- "title": "目標模型的上下文視窗較小",- "warnToast": "當前任務已使用 {{used}} 上下文,切換後約佔目標模型視窗({{total}})的 {{pct}}%",- "overflowDescription": "當前任務已使用 {{used}} 上下文,超出目標模型視窗({{total}},約 {{pct}}%)。切換後回覆和壓縮都可能失敗,建議先點選上下文圓環壓縮對話,或新建任務使用該模型。仍要切換嗎?",- "confirmSwitch": "仍然切換模型",- "cancelSwitch": "取消切換"+ "title": "這個模型裝不下目前的對話",+ "warnToast": "這段對話已經用了 {{used}},換過去大約會佔新模型容量({{total}})的 {{pct}}%",+ "overflowDescription": "這段對話已經用了 {{used}},超過新模型能放下的 {{total}}(約 {{pct}}%)。換過去後,Cindy 會先整理一份摘要再繼續;對話記錄還在,只是不會整段原樣帶給新模型。",+ "overflowDescriptionRemote": "這段對話已經用了 {{used}},超過新模型能放下的 {{total}}(約 {{pct}}%)。遠端任務不會自動換窗,下一次傳送仍可能失敗。可以仍然切換,或留在目前模型。",+ "confirmSwitch": "切換並繼續",+ "cancelSwitch": "先不換"},"agentSwitch": {"engineNotReady": "引擎已切換,但新引擎啟動失敗;傳送訊息時會自動重試",@@ -6983,7 +6984,8 @@"silentStopContinueTitle": "繼續當前任務","piTransportClosed": "遠端 Pi 連線已中斷(SSH 通道關閉)。遠端任務仍在執行,重新連線後可以繼續。","piManagerUnavailable": "遠端 Pi 管理器未就緒,請稍後重試;若持續失敗請到「設定 → 遠端機器」重新安裝 Pi。",- "piBundledNodeMissing": "遠端缺少執行環境(Node.js)。請到「設定 → 遠端機器」展開該主機,先在 Claude Code 或 Codex 列點擊「安裝」(會附帶 Node.js),再建立 Pi 任務。"+ "piBundledNodeMissing": "遠端缺少執行環境(Node.js)。請到「設定 → 遠端機器」展開該主機,先在 Claude Code 或 Codex 列點擊「安裝」(會附帶 Node.js),再建立 Pi 任務。",+ "contextOverflow": "這則訊息本身已超過模型上下文上限,無法在目前 Agent 中自動換窗繼續。請縮短輸入或去掉過大附件後再試。"},"backgroundActivity": {"status": "後臺子任務執行中,模型用量仍在消耗…",@@ -7314,6 +7316,13 @@"handoffTitleEnglishSource": "交接內容——切換時傳送給新引擎的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)","resumedBadge": "已續接原任務"},+ "contextRebuild": {+ "labelOverflow": "已整理上下文並繼續",+ "labelTimeout": "上一輪沒有回應,已整理後繼續",+ "toggleHint": "檢視交接內容",+ "handoffTitle": "交接內容——整理後傳送給後續對話的上下文摘要(不計入對話記錄,僅在此展示)",+ "handoffTitleEnglishSource": "交接內容——整理後傳送給後續對話的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)"+ },"review": {"running": "正在審查當前成果","completed": "審查完成",diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex a73278446d..c66e628870 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -479,7 +479,8 @@ export interface ChatMessage {* 派生、重开会话仍在;这条只活在退避那几秒,补发一发出就撤掉。*/| 'auto-resume-pending'- | 'agent-switch';+ | 'agent-switch'+ | 'context-rebuild';systemCardData?: Record<string, unknown>;/** FP-3: plan_review message fields */planReviewStatus?: 'pending' | 'approved' | 'revised' | 'expired' | 'cancelled';@@ -15449,6 +15450,25 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {...(c.dismissed === true ? { errorDismissed: true } : {}),};}+ // 同一引擎换干净原生会话:可见交接记录,展开看发给新窗口的摘要。+ const contextRebuild =+ m.role === 'assistant' && m.agentMeta && typeof m.agentMeta === 'object'+ ? (m.agentMeta as { contextRebuild?: unknown }).contextRebuild+ : undefined;+ if (contextRebuild && typeof contextRebuild === 'object') {+ const c = contextRebuild as Record<string, unknown>;+ return {+ clientId: m.clientId,+ role: 'assistant' as const,+ content: '',+ isStreaming: false,+ systemCardType: 'context-rebuild' as const,+ systemCardData: {+ reason: typeof c.reason === 'string' ? c.reason : 'context-overflow',+ handoff: typeof c.handoff === 'string' ? c.handoff : '',+ },+ };+ }// session-agent-switch:引擎切换边界行 → 'agent-switch' system card(与// compact 分隔同视觉语言)。role 投影成 'assistant' 走 SystemCard 渲染管线// (工作组分组守卫天然排除 systemCardType 消息,无需改 MessageStream);diff --git a/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts b/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.tsindex 487c02942a..6595cc6651 100644--- a/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts+++ b/apps/desktop/src/shared/__tests__/modelSwitchAssessment.test.ts@@ -1,6 +1,9 @@import { describe, expect, it } from 'vitest';-import { assessModelSwitchContext } from '../modelSwitchAssessment';+import {+ assessModelSwitchContext,+ shouldHandoffAfterContextAssessment,+} from '../modelSwitchAssessment';describe('assessModelSwitchContext', () => {it('fail-open: unknown context tokens → ok', () => {@@ -96,4 +99,24 @@ describe('assessModelSwitchContext', () => {assessModelSwitchContext({ contextTokens: 190_000, targetContextWindow: 1_000_000 }),).toEqual({ level: 'ok', projectedPct: 19 });});++ it('handoffs on danger/overflow, not on warn',+ () => {+ expect(+ shouldHandoffAfterContextAssessment(+ assessModelSwitchContext({ contextTokens: 150_000, targetContextWindow: 200_000 }),+ ),+ ).toBe(false);+ expect(+ shouldHandoffAfterContextAssessment(+ assessModelSwitchContext({ contextTokens: 180_000, targetContextWindow: 200_000 }),+ ),+ ).toBe(true);+ expect(+ shouldHandoffAfterContextAssessment(+ assessModelSwitchContext({ contextTokens: 200_000, targetContextWindow: 200_000 }),+ ),+ ).toBe(true);+ },+ );});diff --git a/apps/desktop/src/shared/modelSwitchAssessment.ts b/apps/desktop/src/shared/modelSwitchAssessment.tsindex f5c6f3ebd3..6e516047c8 100644--- a/apps/desktop/src/shared/modelSwitchAssessment.ts+++ b/apps/desktop/src/shared/modelSwitchAssessment.ts@@ -9,10 +9,10 @@* - ok : 占用 < 70% —— 直接切* - warn : 70% ≤ 占用 < 自动压缩阈值 —— 允许切, 轻提示* - danger : 自动压缩阈值 ≤ 占用 < 100% —— 允许切, 轻提示(切过去会立即触发自动压缩)- * - overflow : 占用 ≥ 100% —— 弹确认并建议先压缩 / 新开会话+ * - overflow : 占用 ≥ 100% —— 弹确认;确认后由 host 交接换窗,而不是用新模型压缩** danger 档阈值取用户当前的 auto-compact 触发百分比(设置页 50-95%), 语义统一为- * "切过去就会立刻触发你设置的压缩线"; 读不到 / 非法时回退 90。+ * "切过去就会立刻顶到压缩线"; 读不到 / 非法时回退 90。此时同样走交接,不再先 compact。** fail-open 原则: 目标窗口未知(目录查不到)或当前占用未知(=0, 新会话 / 状态未回流)* 时一律放行 —— 预检是护栏不是闸门, 缺数据时不能挡住用户操作。@@ -75,3 +75,10 @@ export function assessModelSwitchContext(if (ratio >= WARN_RATIO) return { level: 'warn', projectedPct };return { level: 'ok', projectedPct };}++/** danger/overflow = 新窗口装不下当前用量,应交接而不是 compact。 */+export function shouldHandoffAfterContextAssessment(+ assessment: ModelSwitchContextAssessment,+): boolean {+ return assessment.level === 'danger' || assessment.level === 'overflow';+}diff --git a/apps/desktop/src/shared/providerErrors.ts b/apps/desktop/src/shared/providerErrors.tsindex c46b6d1326..65de6b896e 100644--- a/apps/desktop/src/shared/providerErrors.ts+++ b/apps/desktop/src/shared/providerErrors.ts@@ -82,7 +82,7 @@ const MODEL_NOT_FOUND_RE =/model[^\n]{0,80}(not.{0,4}(found|exist)|does not exist|invalid|unknown|unsupported)|model_not_found|invalid model/i;/** 上下文超长:Anthropic "prompt is too long"、OpenAI "maximum context length"、通用 token limit 措辞。 */const CONTEXT_TOO_LONG_RE =- /prompt is too long|maximum context length|context.{0,20}(length|window).{0,40}(exceed|too)|too many tokens|input length.{0,20}exceed|context_length_exceeded/i;+ /prompt is too long|maximum (?:context|prompt) length|context.{0,20}(length|window).{0,40}(exceed|too)|context_length_exceeded/i;/** wire 兼容性:端点不认识请求里的字段 / 参数(典型:litellm/Azure 对 Anthropic-only 字段报错)。 */const WIRE_RE =/(unknown|unexpected|unsupported|extra|unrecognized).{0,16}(field|parameter|argument|inputs?|property|request param)|extra inputs are not permitted|invalid_request_error[^\n]{0,120}(field|param)/i;diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex e44a9c7d1b..0da946f83b 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -11,6 +11,17 @@ Agent 会话的事件流与 prompt 组装中枢,这里的改动会在用户无[`electron-security-and-process-boundaries.md`](electron-security-and-process-boundaries.md),Orca 多 Agent 协同另见 [`orca-team-architecture.md`](orca-team-architecture.md)。+## 上下文已满时的引擎边界++本地 Claude Code、Codex、PI 在同一 Cindy 任务内,按 host 的+`assessModelSwitchContext` 评估判断当前模型已经满(`danger` 或 `overflow`)时,走+`host-controlled rollover + model-controlled bounded retrieval`:host 关闭旧原生窗口、写交接并+在下一次发送前 fresh bootstrap,不先让引擎自动压缩。明确 `context-overflow` 且本轮没有助手输出或+工具副作用时,host 才会对失败的 user 消息做一次 wire-only replay;有副作用或分类不确定时必须+fail closed。PI 的 `pi-prompt-timeout` 是唯一保留的 timeout 交接入口;Claude Code/Codex 的普通+timeout 不得触发自动换窗或 replay。Codex 当前没有与 Claude `AutoCompactController` 对等的 host+自动 `/compact` 注入路径;未来若增加,仍须遵守同一评估和交接边界。手动压缩入口不受此规则影响。+> **适用范围与增量原则**:Agent 能力归属(下节 1)与代码优先确定性(下节 2)按增量> 适用——约束新增和正在修改的代码,不要求为统一形式专项重构存量。但**核心指标不变量> (下节 3)与 system prompt 改动门禁(下节 4)对所有触及相关路径的改动都生效,不分diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 95e4f9e899..614ecf96e9 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -54,7 +54,7 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi## 2. 配置面:Cindy 显式设置 vs 放任 pi 默认Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、启动时 RPC-`set_auto_compaction{enabled:true}` / `set_thinking_level`。env:`CINDY_PI_API_KEY`、+`set_auto_compaction{enabled:false}` / `set_thinking_level`。接近窗口上限时由 host 交接换窗,不再先让 PI 自动压缩。env:`CINDY_PI_API_KEY`、`CINDY_PI_SESSION_ID`、`PI_CODING_AGENT_DIR`、`CINDY_PI_PERMISSION_FILE`、`CINDY_PI_MCP_BRIDGE`、外部 MCP 专用动态 env、`PI_OFFLINE=1`(关启动期联网)、`NO_PROXY` 兜底 loopback(防全局代理打穿本地 proxy 与 MCP bridge)。@@ -180,10 +180,8 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、每个真实模型(chatgpt/、xai/、glm、deepseek、kimi…)仍建议在 release candidate 上anthropic-compat 下至少跑一轮**带工具调用**的回合,逐个确认 thinking 格式 / toolstreaming / redacted thinking 正确;这是额度/账号发布 smoke,不再是功能缺口。-- [x] **compaction**:启动显式开启原生 auto-compaction;host 另按与 Claude Code 共用的- 百分比阈值在 turn 结束或 setModel 窗口变化后调 compact RPC(默认 75%),原生- `window - reserve` 仍作顶满抢救。手动 compact、boundary/usage 翻译、compaction- digest 写入与缓存命中均有测试。长上下文压力仍属于 RC soak。+- [x] **compaction**:启动显式关闭 auto-compaction;接近/超过目标窗口由 host 交接换窗。+ 手动 compact、boundary/usage 翻译、compaction digest 写入与缓存命中仍有测试。- [x] **无人值守**:scheduler 对 `agentKind=pi` 使用 Pi 默认模型与`bypassPermissions` 的契约测试已补;Pi bridge 的 auto allow/deny 也用真二进制覆盖。- [x] **resume 边界**:已用 Pi v0.82.1 真二进制创建 JSONL,再由 v0.83.0 恢复;diff --git a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.tsindex 12a5d1efa5..f607eedf46 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts@@ -67,11 +67,13 @@ const TEST_MODELS: ModelDescriptor[] = [},];-function createNoopLogger(): Logger {+function createNoopLogger(onInfo?: (message: string) => void): Logger {const logger: Logger = {trace() {},debug() {},- info() {},+ info(message: string) {+ onInfo?.(message);+ },warn() {},error() {},fatal() {},@@ -82,7 +84,10 @@ function createNoopLogger(): Logger {return logger;}-function createDeps(runtimeConfig: AgentDeps['runtimeConfig'] = {}): AgentDeps {+function createDeps(+ runtimeConfig: AgentDeps['runtimeConfig'] = {},+ onInfo?: (message: string) => void,+): AgentDeps {const auth: AuthAdapter = {async getState() {return { authenticated: true };@@ -100,7 +105,7 @@ function createDeps(runtimeConfig: AgentDeps['runtimeConfig'] = {}): AgentDeps {auth,runtimeConfig,binaryPath: process.execPath,- logger: createNoopLogger(),+ logger: createNoopLogger(onInfo),};}@@ -175,6 +180,7 @@ function createFakeQuery(stream = createControlledStream()) {setModel: vi.fn(async () => assertWritable()),applyFlagSettings: vi.fn(async () => assertWritable()),interrupt: vi.fn(async () => {}),+ send: vi.fn(async () => {}),close: vi.fn(() => {closed = true;}),@@ -194,7 +200,12 @@ async function makeTempDir(): Promise<string> {}async function startRewindableSession(- options: { autoCompactThresholdPct?: number; idleTimeoutMs?: number } = {},+ options: {+ autoCompactThresholdPct?: number;+ idleTimeoutMs?: number;+ remoteHostId?: string;+ shouldHandoffAfterContextAssessment?: (tokens: number, window: number) => boolean;+ } = {},) {const configDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;@@ -204,19 +215,33 @@ async function startRewindableSession(const firstQuery = createFakeQuery();sdkMock.query.mockReturnValue(firstQuery);+ const remoteCcQueryFactory = options.remoteHostId+ ? (async () => firstQuery as never)+ : undefined;+ const infoCalls: string[] = [];const agent = new ClaudeCodeAgent({- ...createDeps({ autoCompactThresholdPct: options.autoCompactThresholdPct }),+ ...createDeps(+ {+ autoCompactThresholdPct: options.autoCompactThresholdPct,+ shouldHandoffAfterContextAssessment: options.shouldHandoffAfterContextAssessment,+ },+ (message) => {+ infoCalls.push(message);+ },+ ),capabilityAdditions: { availableModels: TEST_MODELS },+ ...(remoteCcQueryFactory ? { remoteCcQueryFactory } : {}),});const handle = await agent.startSession({sessionId: 'session-rewind',model: 'claude-opus-4-6',workingDir,permissionMode: 'acceptEdits',+ ...(options.remoteHostId ? { remoteHostId: options.remoteHostId } : {}),});- return { agent, handle, firstQuery };+ return { agent, handle, firstQuery, infoCalls };}afterEach(async () => {@@ -660,6 +685,77 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {await handle.close();});+ it('skips idle auto-compact on local sessions when host will rebuild context', async () => {+ const shouldHandoff = vi.fn(() => true);+ const { handle, firstQuery, infoCalls } = await startRewindableSession({+ autoCompactThresholdPct: 50,+ shouldHandoffAfterContextAssessment: shouldHandoff,+ });+ void (async () => {+ try {+ for await (const _event of handle.events()) {+ /* drain */+ }+ } catch {+ /* ignore */+ }+ })();++ await handle.send({ type: 'user', content: 'hi' });+ firstQuery.stream.emit({+ type: 'result',+ stop_reason: 'end_turn',+ total_cost_usd: 0,+ usage: { input_tokens: 400_000, output_tokens: 20 },+ });+ await vi.waitFor(() => {+ expect(handle.isTurnRunning?.()).toBe(false);+ });++ await handle.setModel?.('claude-sonnet-5');+ expect(handle.getUsageSnapshot().contextWindow).toBe(500_000);+ expect(shouldHandoff).toHaveBeenCalled();+ expect(infoCalls.filter((message) => message === 'auto-compact triggered')).toEqual([]);++ await handle.close();+ });++ it('keeps idle auto-compact on remote sessions because overflow rollover is local-only', async () => {+ const { handle, firstQuery, infoCalls } = await startRewindableSession({+ autoCompactThresholdPct: 50,+ remoteHostId: 'remote-1',+ shouldHandoffAfterContextAssessment: () => true,+ });+ void (async () => {+ try {+ for await (const _event of handle.events()) {+ /* drain */+ }+ } catch {+ /* ignore */+ }+ })();++ await handle.send({ type: 'user', content: 'hi' });+ firstQuery.stream.emit({+ type: 'result',+ stop_reason: 'end_turn',+ total_cost_usd: 0,+ usage: { input_tokens: 400_000, output_tokens: 20 },+ });+ await vi.waitFor(() => {+ expect(handle.isTurnRunning?.()).toBe(false);+ });++ await handle.setModel?.('claude-sonnet-5');+ expect(handle.getUsageSnapshot().contextWindow).toBe(500_000);+ expect(infoCalls.filter((message) => message === 'auto-compact triggered')).toEqual([+ 'auto-compact triggered',+ ]);++ await handle.close();+ });+it('rebuild replays auto-compact when a large→small window switch crossed the threshold during rewind', async () => {const { handle, firstQuery } = await startRewindableSession({ autoCompactThresholdPct: 50 });const eventIterator = handle.events()[Symbol.asyncIterator]();diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 2992a4a29e..53e6d4ef3d 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -1266,6 +1266,13 @@ export class ClaudeCodeAgent extends BaseAgent {workdir: opts.workingDir,agentKind: 'claude-code',getThresholdPct: getAutoCompactThresholdPct,+ // 远端没有 overflow rollover;关掉 /compact 会让会话只能硬超限。+ ...(opts.remoteHostId+ ? {}+ : {+ shouldHandoffAfterContextAssessment:+ this.deps.runtimeConfig.shouldHandoffAfterContextAssessment,+ }),});// opts.makerMemoryEnabled 优先 (per-session, renderer 透传); fallback 到 runtimeConfig// (host 静态配置, 一般 undefined)。manager 没注入视为禁用。diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-host-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-host-auto-compact.test.tsindex 7d16d1c3f1..bca47e0fb9 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-host-auto-compact.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-host-auto-compact.test.ts@@ -89,7 +89,10 @@ describe('PiAgent host auto-compact', () => {rmSync(cwd, { recursive: true, force: true });});- function buildDeps(threshold: number | undefined): AgentDeps {+ function buildDeps(+ threshold: number | undefined,+ extra?: { shouldHandoff?: (tokens: number, window: number) => boolean },+ ): AgentDeps {return {auth: {getState: async () => ({ authenticated: true, identity: 't', authSource: 'api-key' as const }),@@ -100,6 +103,9 @@ describe('PiAgent host auto-compact', () => {runtimeConfig: {endpoint: 'http://127.0.0.1:9',...(threshold === undefined ? {} : { autoCompactThresholdPct: threshold }),+ ...(extra?.shouldHandoff+ ? { shouldHandoffAfterContextAssessment: extra.shouldHandoff }+ : {}),},binaryPath: path.join(agentHome, 'pi'),logger: noopLogger,@@ -114,8 +120,11 @@ describe('PiAgent host auto-compact', () => {};}- async function start(threshold: number | undefined): Promise<AgentSessionHandle> {- return new PiAgent(buildDeps(threshold)).startSession({+ async function start(+ threshold: number | undefined,+ extra?: { shouldHandoff?: (tokens: number, window: number) => boolean },+ ): Promise<AgentSessionHandle> {+ return new PiAgent(buildDeps(threshold, extra)).startSession({sessionId: 's1',workingDir: cwd,model: 'm',@@ -154,6 +163,24 @@ describe('PiAgent host auto-compact', () => {await handle.close();});+ it('does not compact after agent_settled when host assessment requires rollover', async () => {+ const handle = await start(75, { shouldHandoff: () => true });+ settleWithUsage(160_000);+ await Promise.resolve();+ expect(knobs.compactCalls).toEqual([]);+ await handle.close();+ });++ it('does not compact after setModel when host assessment requires rollover', async () => {+ const handle = await start(75, { shouldHandoff: () => true });+ // 80k / 200k = 40% — 旧窗口未达阈值;切到 100k 后是 80%。+ settleWithUsage(80_000);+ await handle.setModel!('n');+ await Promise.resolve();+ expect(knobs.compactCalls).toEqual([]);+ await handle.close();+ });+it('counts cache tokens toward occupancy', async () => {const handle = await start(75);settleWithUsage(1_000, 159_000);diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex dc52c5b026..67f129602c 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -433,6 +433,69 @@ describe('pi translator', () => {expect(terminalErrors[0]?.data).toMatchObject({ message: 'final provider error' });});+ it('tags a terminal xAI prompt-length error as context-overflow', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ const overflow =+ 'API Error: 400 litellm.BadRequestError: XaiException - {"code":"invalid-argument","error":"This model\'s maximum prompt length is 500000 but the request contains 637815 tokens."}';++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(+ ev({+ type: 'message_end',+ message: {+ role: 'assistant',+ content: [],+ stopReason: 'error',+ errorMessage: overflow,+ },+ }),+ queue,+ ctx,+ );+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);++ const terminalErrors = events.filter(+ (event) =>+ event.type === 'error' &&+ (event.data as { isTerminal?: boolean }).isTerminal === true,+ );+ expect(terminalErrors).toHaveLength(1);+ expect(terminalErrors[0]?.data).toMatchObject({+ isTerminal: true,+ reason: 'context-overflow',+ });+ });++ it('does not tag a generic invalid-argument as context-overflow', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(+ ev({+ type: 'message_end',+ message: {+ role: 'assistant',+ content: [],+ stopReason: 'error',+ errorMessage: '{"code":"invalid-argument","error":"unsupported field: foo"}',+ },+ }),+ queue,+ ctx,+ );+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);++ const terminalErrors = events.filter(+ (event) =>+ event.type === 'error' &&+ (event.data as { isTerminal?: boolean }).isTerminal === true,+ );+ expect(terminalErrors).toHaveLength(1);+ expect((terminalErrors[0]?.data as { reason?: string }).reason).toBeUndefined();+ });+it('preserves a 64KB ghost_manual envelope only as tool_result data', () => {const { content, wire } = makeGhostManual64KiBFixture();expect(Buffer.byteLength(wire, 'utf8')).toBeGreaterThan(64 * 1024);diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex b8682a1e9c..017c46b98c 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -2280,6 +2280,13 @@ export class PiAgent extends BaseAgent {workdir: opts.workingDir,agentKind: 'pi',getThresholdPct: getAutoCompactThresholdPct,+ // 远端没有 overflow rollover,必须保留 host compact。+ ...(opts.remoteHostId+ ? {}+ : {+ shouldHandoffAfterContextAssessment:+ this.deps.runtimeConfig.shouldHandoffAfterContextAssessment,+ }),});// compact / 所有 prompt(/plan、分支切换、用户发送) / set_model / set_thinking_level// 共用一条双向串行链。只等 compact 再发控制 RPC 是单向的。@@ -2949,13 +2956,10 @@ export class PiAgent extends BaseAgent {}}- // 显式保证 auto-compaction 开 —— 这是"pi 保持轻上下文"的不变量:上下文接近满时- // pi 自动压缩(与 CC/Codex 一致)。pi 默认即开,这里显式化并兜底(幂等,失败不致命)。+ // 上下文接近满时由 host 换干净原生会话(handoff),不再让 PI 先自动压缩。+ // 自动压缩在大窗口上往往先卡住/超时,用户看不到交接。失败不致命。{- const resp = await proc.request({- type: 'set_auto_compaction',- enabled: true,- });+ const resp = await proc.request({ type: 'set_auto_compaction', enabled: false });if (!resp.success) {this.deps.logger.warn('pi set_auto_compaction failed (non-fatal)', {error: resp.error,diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 99fe55d87e..7ba4440d48 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -34,6 +34,10 @@ import {formatOverloadRetryMessage,parseOverloadError,} from '../shared/overload-error.js';+import {+ CONTEXT_OVERFLOW_REASON,+ isContextOverflowErrorMessage,+} from '../shared/context-overflow-error.js';import type { PiRpcEvent } from './rpc-client.js';import { parsePiSubagentProgress, type PiSubagentUsage } from './subagent-progress.js';@@ -63,6 +67,7 @@ interface PiPendingAssistantError {sdkError: string;errorStatus?: 401 | 429 | 529;usageLimit?: true;+ reason?: typeof CONTEXT_OVERFLOW_REASON;}interface PiThinkingBlock {@@ -339,6 +344,9 @@ function piAssistantErrorOf(rawError: string): PiPendingAssistantError {sdkError: redactedError,...(signals.errorStatus !== undefined ? { errorStatus: signals.errorStatus } : {}),...(signals.usageLimit ? { usageLimit: true } : {}),+ ...(isContextOverflowErrorMessage(redactedError)+ ? { reason: CONTEXT_OVERFLOW_REASON }+ : {}),};}diff --git a/packages/maker-core/src/agents/shared/auto-compact-controller.test.ts b/packages/maker-core/src/agents/shared/auto-compact-controller.test.tsindex 5d9d6343c1..5485b8921c 100644--- a/packages/maker-core/src/agents/shared/auto-compact-controller.test.ts+++ b/packages/maker-core/src/agents/shared/auto-compact-controller.test.ts@@ -13,12 +13,16 @@ const noopLogger: Logger = {child: () => noopLogger,};-function makeController(getThresholdPct: () => number | undefined): AutoCompactController {+function makeController(+ getThresholdPct: () => number | undefined,+ shouldHandoffAfterContextAssessment?: (tokens: number, window: number) => boolean,+): AutoCompactController {return new AutoCompactController({logger: noopLogger,workdir: '/tmp/project',agentKind: 'claude-code',getThresholdPct,+ shouldHandoffAfterContextAssessment,});}@@ -133,4 +137,12 @@ describe('AutoCompactController', () => {threshold = 75;expect(controller.shouldCompactNow()).toBe(true);});++ it('skips auto-compact when the host assessment requires rollover', () => {+ const controller = makeController(() => 75, (tokens, window) => tokens >= window * 0.75);++ controller.onUsageUpdate(150, 200);++ expect(controller.shouldCompactNow()).toBe(false);+ });});diff --git a/packages/maker-core/src/agents/shared/auto-compact-controller.ts b/packages/maker-core/src/agents/shared/auto-compact-controller.tsindex 0ed4c460ac..4165e29043 100644--- a/packages/maker-core/src/agents/shared/auto-compact-controller.ts+++ b/packages/maker-core/src/agents/shared/auto-compact-controller.ts@@ -17,6 +17,14 @@ export interface AutoCompactControllerDeps {agentKind: string;/** 返回当前自动压缩阈值百分比。undefined 表示关闭 host 侧自动压缩。 */getThresholdPct: () => number | undefined;+ /**+ * Host-owned context assessment. danger/overflow sessions are rebuilt by+ * the host on the next send, so the controller must not inject `/compact`.+ */+ shouldHandoffAfterContextAssessment?: (+ contextTokens: number,+ contextWindow: number,+ ) => boolean;}/**@@ -48,6 +56,20 @@ export class AutoCompactController {shouldCompactNow(): boolean {const thresholdPct = this.normalizeThreshold(this.deps.getThresholdPct());if (thresholdPct === undefined || this.latest === null || this.fired) return false;+ if (+ this.deps.shouldHandoffAfterContextAssessment?.(+ this.latest.contextTokens,+ this.latest.contextWindow,+ ) === true+ ) {+ this.deps.logger.debug('auto-compact skipped: host will rebuild context', {+ contextTokens: this.latest.contextTokens,+ contextWindow: this.latest.contextWindow,+ workdir: this.deps.workdir,+ agentKind: this.deps.agentKind,+ });+ return false;+ }if (this.latest.ratio < thresholdPct / 100) return false;this.fired = true;this.deps.logger.debug('auto-compact threshold crossed', {diff --git a/packages/maker-core/src/agents/shared/context-overflow-error.test.ts b/packages/maker-core/src/agents/shared/context-overflow-error.test.tsindex 111241fa08..591dfa4fb4 100644--- a/packages/maker-core/src/agents/shared/context-overflow-error.test.ts+++ b/packages/maker-core/src/agents/shared/context-overflow-error.test.ts@@ -33,6 +33,11 @@ describe('isContextOverflowErrorMessage', () => {),).toBe(true);expect(isContextOverflowErrorMessage('{"code": "context_length_exceeded"}')).toBe(true);+ expect(+ isContextOverflowErrorMessage(+ 'API Error: 400 litellm.BadRequestError: XaiException - {"code":"invalid-argument","error":"This model\'s maximum prompt length is 500000 but the request contains 637815 tokens."}',+ ),+ ).toBe(true);});it('does NOT confuse rate, output, or tool argument limits with context overflow', () => {diff --git a/packages/maker-core/src/agents/shared/context-overflow-error.ts b/packages/maker-core/src/agents/shared/context-overflow-error.tsindex 8decf25057..bffe34cdf3 100644--- a/packages/maker-core/src/agents/shared/context-overflow-error.ts+++ b/packages/maker-core/src/agents/shared/context-overflow-error.ts@@ -10,6 +10,7 @@* 已知措辞形态(pattern 逐条对应,只认错误文本形态、与 provider 无关):* - Anthropic: `prompt is too long: 250000 tokens > 200000 maximum`* - OpenAI: `This model's maximum context length is 128000 tokens...`+ * - xAI / litellm: `This model's maximum prompt length is 500000 but the request contains 637815 tokens.`* - litellm / Azure: `{"code": "context_length_exceeded"}` /* `Your input exceeds the context window of this model.`(#1429 实踩)*@@ -56,7 +57,7 @@ export const CONTEXT_OVERFLOW_REASON = 'context-overflow';* 误伤面与既有 overload / network pattern 同级。*/const CONTEXT_OVERFLOW_RE =- /prompt is too long|maximum context length|context.{0,20}(length|window).{0,40}(exceed|too)|(input|request|message).{0,20}exceeds?.{0,40}context.{0,20}(length|window)|context_length_exceeded/i;+ /prompt is too long|maximum (?:context|prompt) length|context.{0,20}(length|window).{0,40}(exceed|too)|(input|request|message).{0,20}exceeds?.{0,40}context.{0,20}(length|window)|context_length_exceeded/i;/** 是否是上下文超限类错误。命中 = 不可原样重试,恢复动作是压缩上下文或新开会话。 */export function isContextOverflowErrorMessage(message: string): boolean {diff --git a/packages/maker-core/src/interfaces/runtime-config.ts b/packages/maker-core/src/interfaces/runtime-config.tsindex 3557328755..4da1482723 100644--- a/packages/maker-core/src/interfaces/runtime-config.ts+++ b/packages/maker-core/src/interfaces/runtime-config.ts@@ -103,6 +103,16 @@ export interface AgentRuntimeConfig {*/autoCompactThresholdPct?: number;+ /**+ * Host-owned context switch assessment. When true, skip host auto-compact+ * because the host will rebuild the native session before the next send.+ * Do not install this on sessions the host cannot rebuild (remoteHostId).+ */+ shouldHandoffAfterContextAssessment?: (+ contextTokens: number,+ contextWindow: number,+ ) => boolean;+/*** Host-managed executable directories to prepend to agent subprocess PATH.*