Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): recover companion context before native compaction stalls (#5877)
Chris Zhang73d99b603e39
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.tsindex 26eb0f0c54..2b3f934d5e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import {CODEX_HISTORY_CONTINUE_MESSAGE,+ canContinueContextRecovery,createContextOverflowRollover,effectiveContextWindow,effectivePiContextWindow,@@ -311,6 +312,7 @@ describe('createContextOverflowRollover', () => {async (): Promise<{status: string;source?: string;+ botRole?: string | null;agentKind: string;remoteHostId: string | null;clearedAt: number | null;@@ -339,6 +341,7 @@ describe('createContextOverflowRollover', () => {getLiveSession: vi.fn((): {isTurnRunning(): boolean;+ listBackgroundTasks?(): ReadonlyArray<unknown>;getUsageSnapshot?: () => {contextTokens: number;contextWindow: number;@@ -361,6 +364,131 @@ describe('createContextOverflowRollover', () => {};}+ it.each(['cc', 'codex', 'pi'])('checkpoints a pressured %s companion before send, retaining outcomes without replay', async (agentKind) => {+ const deps = makeDeps([+ msg('user', 'Keep the game keyboard accessible', 'u1'),+ { ...msg('tool_use', { toolName: 'Write', input: { file_path: '/game/index.html' } }, 't1'), toolUseId: 'write-1' },+ { ...msg('tool_result', { fullText: 'Saved index.html; keyboard test passed' }, 'r1'), toolUseId: 'write-1' },+ msg('assistant', 'Keyboard controls are ready. Next: add touch controls.', 'a1'),+ ]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), agentKind, source: 'bot', botRole: 'canonical', contextTokens: 180_000 });+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);+ const handoff = deps.setPendingHandoff.mock.calls[0]![1] as string;+ expect(handoff).toContain('Keep the game keyboard accessible');+ expect(handoff).toContain('Saved index.html; keyboard test passed');+ expect(handoff).toContain('Next: add touch controls');+ expect(handoff.length).toBeLessThanOrEqual(16_000);+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ // Persisted reset prevents another checkpoint after a cold restart.+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), sdkSessionId: null, contextTokens: 0 });+ await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(deps.commitRebuild).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['desktop', null, 180_000], ['bot', 'delegation', 180_000], ['bot', 'group', 180_000],+ ['bot', null, 180_000], ['bot', 'canonical', 179_999], ['bot', 'canonical', 0],+ ] as const)('leaves healthy/non-canonical contexts alone: %s %s %s', async (source, botRole, contextTokens) => {+ const deps = makeDeps([msg('user', 'hello', 'u1'), msg('assistant', 'hello', 'a1')]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source, botRole, contextTokens });+ await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(deps.closeSession).not.toHaveBeenCalled();+ });++ it.each([+ ['Error running remote compact task: summarization produced empty response', true],+ ['Error running remote compact task: invalid_request_error', true],+ ['Error during compaction: invalid-argument', true],+ ['Error running remote compact task: connection timed out', false],+ ['Error running remote compact task: HTTP 401 unauthorized', false],+ ['Error running remote compact task: HTTP 429 usage limit exceeded', false],+ ['summarization produced empty response', false],+ ['invalid_request_error', false],+ ])('new companion input handles only proven compact failures: %s', async (message, expected) => {+ const deps = makeDeps([msg('user', 'save the game', 'u1'), msg('assistant', 'Saved', 'a1'), msg('error', { message }, 'e1')]);+ const row = { ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', agentKind: 'codex' };+ deps.getSessionRow.mockResolvedValue(row);+ await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(expected);+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ // The new policy is scoped to companions, not all ordinary/manual compaction.+ deps.getSessionRow.mockResolvedValue({ ...row, source: 'desktop', botRole: null });+ await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);+ });++ it.each(['healthy', 'unknown', 'oversized'] as const)('checks companion image bytes before an error: %s', async (health) => {+ const deps = makeDeps([msg('user', 'continue the game', 'u1'), msg('assistant', 'ready', 'a1')]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', agentKind: 'codex' });+ const classifyCodexHistory = vi.fn(async () => health);+ await expect(createContextOverflowRollover({ ...deps, classifyCodexHistory }).prepareUnhealthySession('s1')).resolves.toBe(health === 'oversized');+ expect(classifyCodexHistory).toHaveBeenCalledOnce();+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ });++ it('continues a direct companion image failure once without replaying a completed tool', async () => {+ const deps = makeDeps([+ msg('user', 'save the game and then test it', 'u1'),+ { ...msg('tool_result', { fullText: 'Game saved successfully' }, 'r1'), toolUseId: 'write-1' },+ ]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', agentKind: 'codex' });+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(true);+ expect(deps.replayUserMessage).toHaveBeenCalledWith('s1', CODEX_HISTORY_CONTINUE_MESSAGE, undefined,+ expect.objectContaining({ continueFromHistory: true, sourceUserClientId: 'u1' }));+ expect(deps.setPendingHandoff.mock.calls[0]![1]).toContain('Game saved successfully');+ await expect(rollover.tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(false);+ expect(deps.replayUserMessage).toHaveBeenCalledTimes(1);+ });++ it.each(['group', 'delegation', null])('does not take over noncanonical Bot recovery: %s', async (botRole) => {+ const deps = makeDeps([msg('user', 'continue', 'u1')]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole, agentKind: 'codex' });+ expect(canContinueContextRecovery(await deps.getSessionRow())).toBe(false);+ await expect(createContextOverflowRollover(deps).tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(false);+ expect(deps.closeSession).not.toHaveBeenCalled();+ });++ it('keeps a companion external-dispatch turn with its original owner', async () => {+ const deps = makeDeps([{ ...msg('user', 'scheduled work', 'u1'), agentMeta: { origin: { kind: 'scheduler' } } }]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', agentKind: 'codex' });+ await expect(createContextOverflowRollover(deps).tryRecover('s1', { reason: 'codex_history_oversized' })).resolves.toBe(false);+ expect(deps.closeSession).not.toHaveBeenCalled();+ });++ it('does not checkpoint while native background execution is still active', async () => {+ const deps = makeDeps([msg('user', 'continue', 'u1')]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 190_000 });+ deps.getLiveSession.mockReturnValue({ isTurnRunning: () => false, listBackgroundTasks: () => [{ id: 'active' }] });+ await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(deps.closeSession).not.toHaveBeenCalled();+ });++ it.each(['history', 'close'])('stopping companion preparation during %s forbids a late rebuild', async (stage) => {+ const deps = makeDeps([msg('user', 'continue', 'u1')]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 190_000 });+ const rollover = createContextOverflowRollover(deps);+ if (stage === 'history') deps.listMessages.mockImplementation(async () => { rollover.cancelRecovery('s1'); return [msg('user', 'continue', 'u1')]; });+ else deps.closeSession.mockImplementation(async () => { rollover.cancelRecovery('s1'); });+ await expect(rollover.prepareUnhealthySession('s1')).rejects.toThrow();+ expect(deps.commitRebuild).not.toHaveBeenCalled();+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ if (stage === 'history') expect(deps.closeSession).not.toHaveBeenCalled();+ });++ it('manual restart retains tool outcomes and strips image bodies even after a partial reply', async () => {+ const deps = makeDeps([+ msg('user', 'create the game', 'u1'),+ { ...msg('tool_result', { content: [{ type: 'text', text: 'Build completed; preview ready' }, { type: 'image', data: 'IMAGE_BYTES' }] }, 'r1'), toolUseId: 'build-1' },+ msg('assistant', 'Checking the preview next', 'a1'),+ ]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical' });+ await createContextOverflowRollover(deps).prepareNativeSessionRecovery('s1', null, vi.fn());+ const handoff = deps.setPendingHandoff.mock.calls[0]![1];+ expect(handoff).toContain('Build completed; preview ready');+ expect(handoff).not.toContain('IMAGE_BYTES');+ expect(deps.replayUserMessage).not.toHaveBeenCalled();+ });+it.each(['cc', 'codex', 'pi'] as const)('explicit Bot restart replaces a running %s context without replay', async (agentKind) => {const deps = makeDeps([msg('user', 'keep my request', 'u1', 1)]);deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', agentKind });@@ -1250,6 +1378,7 @@ describe('createContextOverflowRollover', () => {'s1',expect.any(String),expect.objectContaining({ reason: 'pi-prompt-timeout' }),+ expect.any(AbortSignal),);});@@ -1343,6 +1472,7 @@ describe('createContextOverflowRollover', () => {'s1',expect.any(String),expect.objectContaining({ sourceUserClientId: 'u-old' }),+ expect.any(AbortSignal),);});@@ -1676,7 +1806,7 @@ describe('createContextOverflowRollover', () => {const rollover = createContextOverflowRollover(deps);await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);expect(deps.commitRebuild).toHaveBeenCalledWith('s1', expect.stringContaining('Saved revision 42'),- expect.objectContaining({ sourceUserClientId: 'u1' }));+ expect.objectContaining({ sourceUserClientId: 'u1' }), expect.any(AbortSignal));expect(deps.replayUserMessage).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts b/apps/desktop/src/main/maker-ipc/cindyContextCompression.tsindex 96e70540cd..c3b222a2e4 100644--- a/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts+++ b/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts@@ -21,8 +21,8 @@ export type CompressionBudgetState = 'ok' | 'violated' | 'unknown';/*** tokens='violated' 只允许这些证据(普通 timeout / 网络 / 鉴权不算):* - 终态 context-overflow(含 PI prompt RPC 超时)- * - 本机占用 ≥ 100%- * - 官方 compact 确定性失败(needsRollover:空摘要、compact 路径 invalid-request)+ * - 本机占用 ≥ 100%(伙伴主对话的发送边界提前至 90%)+ * - 官方 compact 确定性失败(needsRollover,或伙伴已记录的压缩空摘要/invalid-request)** bytes='violated':Codex 活尾巴可剥超大内联图(>8MB 且可剥 ≥ 一半且剥完 ≤8MB),* 或 Pi 的真实 413 经一次原生压缩仍无法恢复。diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.tsindex 11444386e0..098c5d4d9b 100644--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts@@ -10,6 +10,7 @@ import {CONTEXT_OVERFLOW_REASON,PI_REQUEST_BODY_RECOVERY_EXHAUSTED,isContextOverflowErrorMessage,+ isDeterministicHostCompactFailure,isRemoteCompactEncryptedContentError,} from '@cindy/maker-core';import {@@ -37,6 +38,7 @@ import { isPiPromptRpcTimeoutError } from '../../shared/inputError.js';export { isPiPromptRpcTimeoutError } from '../../shared/inputError.js';const SYNTHETIC_TRIGGER_PREFIX = '[UI_ACTION_TRIGGER]';+const BOT_CONTEXT_CHECKPOINT_RATIO = 0.9;export const CODEX_HISTORY_CONTINUE_MESSAGE ='Continue the unfinished task from the retained history. Do not repeat completed actions. ' +@@ -81,6 +83,19 @@ export function isOversizedHistoryErrorData(data: unknown): boolean {return (data as { reason?: unknown }).reason === CODEX_HISTORY_OVERSIZED_REASON;}+/** A new companion input may retire an explicitly rejected compact operation.+ * Bare empty responses, transport failures and ordinary generation errors are+ * not proof of a broken compact context. Reuse the native failure classifier.+ */+function isCompanionCompactFailure(data: unknown): boolean {+ if (!data || typeof data !== 'object') return false;+ const record = data as { message?: unknown; sdkError?: unknown };+ return [record.message, record.sdkError].some(value =>+ typeof value === 'string'+ && /error during compaction|pi compact failed|error running remote compact task/i.test(value)+ && isDeterministicHostCompactFailure(value.replace(/error running remote compact task/ig, 'Error during compaction')));+}+export interface NativeSessionRecoveryTarget {model: string;providerId: string | null;@@ -342,6 +357,7 @@ export function errorContentToData(content: unknown): unknown {export function findLatestRebuildableError(messages: OverflowSourceMessage[],allowPiPromptTimeout = true,+ allowCompanionCompactFailure = false,): unknown | null {for (let i = messages.length - 1; i >= 0; i -= 1) {const message = messages[i];@@ -352,6 +368,7 @@ export function findLatestRebuildableError(if (allowPiPromptTimeout && isPiPromptRpcTimeoutError(data)) return data;if (allowPiPromptTimeout && isPiRequestBodyRecoveryExhausted(data)) return data;if (isOversizedHistoryErrorData(data)) return data;+ if (allowCompanionCompactFailure && isCompanionCompactFailure(data)) return data;return null;}if (message.role === 'assistant' && extractPlainText(message.content).trim().length > 0) {@@ -365,6 +382,8 @@ export interface ContextOverflowRolloverDeps {getSessionRow(sessionId: string): Promise<{status: string;source?: string | null;+ /** Resolved from the active, unarchived Bot link and Profile, never from UI hints. */+ botRole?: string | null;agentKind: string;remoteHostId: string | null;clearedAt: number | null;@@ -391,6 +410,7 @@ export interface ContextOverflowRolloverDeps {): Promise<{ reason?: string; sourceUserClientId?: string | null } | null>;getLiveSession(sessionId: string): {isTurnRunning(): boolean;+ listBackgroundTasks?(): ReadonlyArray<unknown>;getUsageSnapshot?(): { contextTokens: number; contextWindow: number; needsRollover?: boolean };} | null | undefined;rehydrateColdPiRuntimeForWindowVerification?(sessionId: string): Promise<void>;@@ -436,6 +456,15 @@ export interface ContextOverflowRolloverDeps {};}+/** Only the companion's direct chat shares Desktop's automatic continuation owner. */+export function isCanonicalBotContext(row: { source?: string | null; botRole?: string | null }): boolean {+ return row.source === 'bot' && row.botRole === 'canonical';+}++export function canContinueContextRecovery(row: { source?: string | null; botRole?: string | null }): boolean {+ return row.source === 'desktop' || isCanonicalBotContext(row);+}+export type OverflowClaimResult = 'claimed' | 'in-flight' | 'idle';export type ModelWindowSwitchPreparationResult =@@ -519,11 +548,11 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)if (!sessionRow || sessionRow.status === 'deleted') return false;// SSH only. device-link 会话落在被控桌面本地库,没有 remoteHostId,必须继续换窗。if (sessionRow.remoteHostId) return false;- if (oversized && (sessionRow.source !== 'desktop' || sessionRow.agentKind !== 'codex')) return false;+ if (oversized && (!canContinueContextRecovery(sessionRow) || sessionRow.agentKind !== 'codex')) return false;return deps.withCloseSuppressed(sessionId, async () => {const live = deps.getLiveSession(sessionId);- if (live?.isTurnRunning()) {+ if (live?.isTurnRunning() || (live?.listBackgroundTasks?.().length ?? 0) > 0) {deps.log.warn('context overflow rollover skipped: turn still running', { sessionId });return false;}@@ -577,7 +606,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)toLabel: label,sessionId,reason: oversized ? 'native-session-recovery' : 'context-overflow',- includeToolResults: oversized,+ includeToolResults: oversized || isCanonicalBotContext(sessionRow),});await deps.commitRebuild(sessionId, handoff, {reason: 'context-overflow',@@ -789,7 +818,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)return 'rebuilt';};- const runPrepare = async (sessionId: string): Promise<boolean> => {+ const runPrepare = async (sessionId: string, signal: AbortSignal): Promise<boolean> => {await deps.drainPersistQueue();const sessionRow = await deps.getSessionRow(sessionId);if (!sessionRow || sessionRow.status === 'deleted') return false;@@ -797,9 +826,10 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)if (sessionRow.remoteHostId) return false;if (!sessionRow.sdkSessionId) return false;const live = deps.getLiveSession(sessionId);- if (live?.isTurnRunning()) return false;+ if (live?.isTurnRunning() || (live?.listBackgroundTasks?.().length ?? 0) > 0) return false;+ const companion = isCanonicalBotContext(sessionRow);const source = await deps.listMessages(sessionId);- const lastError = findLatestRebuildableError(source, sessionRow.agentKind === 'pi');+ const lastError = findLatestRebuildableError(source, sessionRow.agentKind === 'pi', companion);const liveUsage = live?.getUsageSnapshot?.();const hasLiveTokens =liveUsage !== undefined &&@@ -823,21 +853,24 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)sessionRow.agentKind,);const window = effectiveContextWindow(sessionRow.model, reportedWindow, verified);- const pressure = shouldRebuildForContextPressure(usedTokens, window);+ // At a send boundary, checkpoint a pressured companion before the next turn+ // enters native compaction. Native compaction remains enabled within a turn.+ const pressure = shouldRebuildForContextPressure(usedTokens, companion ? window * BOT_CONTEXT_CHECKPOINT_RATIO : window);const compactFailed = liveUsage?.needsRollover === true;const piByteRecoveryFailed = sessionRow.agentKind === 'pi' && isPiRequestBodyRecoveryExhausted(lastError);const tokenViolated =isContextOverflowErrorData(lastError) ||isPiPromptRpcTimeoutError(lastError) ||pressure ||- compactFailed;+ compactFailed ||+ (companion && isCompanionCompactFailure(lastError));const oversized = isOversizedHistoryErrorData(lastError);- const historyHealth = oversized && sessionRow.agentKind === 'codex'+ const historyHealth = (oversized || companion) && sessionRow.agentKind === 'codex'? await deps.classifyCodexHistory?.(sessionRow.sdkSessionId): undefined;const action = decideCindyCompression({local: true,- bytes: piByteRecoveryFailed || (oversized && historyHealth !== 'healthy') ? 'violated' : 'unknown',+ bytes: piByteRecoveryFailed || historyHealth === 'oversized' || (oversized && historyHealth !== 'healthy') ? 'violated' : 'unknown',tokens: tokenViolated ? 'violated' : 'unknown',});if (action !== 'rebuild') return false;@@ -871,14 +904,16 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);// 关掉当前 live handle。调用方必须在解析发送目标之前调用 prepare,// 再 getSession / createSession;peek 之后对旧对象 send 会打到已关闭实例。+ signal.throwIfAborted();if (live) await deps.closeSession(sessionId);+ signal.throwIfAborted();const label = engineLabelForOverflow(sessionRow.agentKind);const handoff = buildHandoffText(handoffMessages, {fromLabel: label,toLabel: label,sessionId,- reason: isOversizedHistoryErrorData(lastError) ? 'native-session-recovery' : rebuildReason,- includeToolResults: isOversizedHistoryErrorData(lastError),+ reason: companion || isOversizedHistoryErrorData(lastError) ? 'native-session-recovery' : rebuildReason,+ includeToolResults: companion || isOversizedHistoryErrorData(lastError),});await deps.commitRebuild(sessionId, handoff, {reason: rebuildReason,@@ -887,7 +922,8 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)sourceModel: sessionRow.model ?? null,sourceProviderId: sessionRow.providerId ?? null,expectedClearedAt: sessionRow.clearedAt,- });+ }, signal);+ signal.throwIfAborted();deps.setPendingHandoff(sessionId, handoff, handoffGeneration);deps.onRebuilt?.(sessionId);deps.log.info('unhealthy native session rebuilt before send; skip compact/resume', {@@ -934,6 +970,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)toLabel: engineLabelForOverflow(row.agentKind),sessionId,reason: 'native-session-recovery',+ includeToolResults: !target || isCanonicalBotContext(row),});// Durable handoff, SDK reset and complete target route succeed or fail together.// No user turn or tool call is replayed by this control-plane operation.@@ -996,9 +1033,10 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)async prepareUnhealthySession(sessionId: string): Promise<boolean> {if (inFlight.has(sessionId)) return false;- inFlight.set(sessionId, undefined);+ const controller = new AbortController();+ inFlight.set(sessionId, controller);try {- return await deps.withCloseSuppressed(sessionId, () => runPrepare(sessionId));+ return await deps.withCloseSuppressed(sessionId, () => runPrepare(sessionId, controller.signal));} catch (error) {deps.log.warn('unhealthy native session prepare failed', {sessionId,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 65897ab204..10bf2b323b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -975,6 +975,7 @@ import { sanitizeSourceName } from '@cindy/maker-shared/message-source';import { UI_ACTION_TRIGGER_PREFIX } from '@cindy/maker-shared/synthetic-trigger';import {createContextOverflowRollover,+ canContinueContextRecovery,hasModelWindowContextToProtect,isContextOverflowErrorData,isOversizedHistoryErrorData,@@ -15935,29 +15936,43 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): withCindyMakeProjectUse(app.getPath('userData'), botInput?.workingDir, () => sendToAgentAcceptedUnlocked(...args));});};+ // Shared by pre-send pressure checks and the final automatic-continuation gate.+ // A stale/archived link must not turn a delegated or deleted companion into a direct chat.+ const readContextRecoverySession = async (sessionId: string) => {+ const [row] = await getDbClient()+ .drizzle.select({+ status: sessions.status,+ source: sessions.source,+ botRole: botSessionLinks.role,+ botLinkArchivedAt: botSessionLinks.archivedAt,+ botStatus: botProfiles.status,+ botHiddenAt: botProfiles.hiddenAt,+ agentKind: sessions.agentKind,+ remoteHostId: sessions.remoteHostId,+ clearedAt: sessions.clearedAt,+ sdkSessionId: sessions.sdkSessionId,+ contextTokens: sessions.contextTokens,+ contextWindow: sessions.contextWindow,+ model: sessions.model,+ providerId: sessions.providerId,+ workingDir: sessions.workingDir,+ })+ .from(sessions)+ .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))+ .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!row) return null;+ return {+ ...row,+ botRole: row.botStatus === 'active' && !row.botHiddenAt && row.botLinkArchivedAt === null+ ? row.botRole : null,+ };+ };contextOverflowRolloverHolder = createContextOverflowRollover({hasExternalRecoveryOwner: (sessionId) =>isHeadlessGhostSetupTurn(sessionId) || !!bindingStore.findByTarget(sessionId),- getSessionRow: async (sessionId) => {- const [row] = await getDbClient()- .drizzle.select({- status: sessions.status,- source: sessions.source,- agentKind: sessions.agentKind,- remoteHostId: sessions.remoteHostId,- clearedAt: sessions.clearedAt,- sdkSessionId: sessions.sdkSessionId,- contextTokens: sessions.contextTokens,- contextWindow: sessions.contextWindow,- model: sessions.model,- providerId: sessions.providerId,- workingDir: sessions.workingDir,- })- .from(sessions)- .where(eq(sessions.id, sessionId))- .limit(1);- return row ?? null;- },+ getSessionRow: readContextRecoverySession,classifyCodexHistory: async (threadId) => {const ownerScope = captureDataOwnerBroadcastScope();const dbSnapshot = getCurrentDbClientSnapshot();@@ -16132,9 +16147,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)content: recovery.sourceUserContent,}): undefined;- if (recovery?.continueFromHistory &&- (row.source !== 'desktop' || isHeadlessGhostSetupTurn(sessionId) || bindingStore.findByTarget(sessionId))) {- return { accepted: false };+ if (recovery?.continueFromHistory) {+ const current = await readContextRecoverySession(sessionId);+ if (!current || !canContinueContextRecovery(current) || current.status !== 'active'+ || isHeadlessGhostSetupTurn(sessionId) || bindingStore.findByTarget(sessionId)) {+ return { accepted: false };+ }}const sendReplay = () => sendToAgentAcceptedUnlocked(sessionId,diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 18391d1abd..2fc6478c88 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -111,10 +111,15 @@ Cindy 保底压缩是**一套**交接重建流程。装得进当前约束就不(可剥的超大内联图)或 token 预算破了,都直接交接重建。Codex 索引历史归原生运行时所有,不再先尝试改写历史/剥图。决定函数见 `cindyContextCompression.ts`。字节预算目前只有 Codex 能测量。工具输出不另开一档:图片恢复的交接保留受长度限制、-带调用关联的文本结果摘要,省略图片数据;其他交接继续沿用原有结果省略规则。+带调用关联的文本结果摘要,省略图片数据;伙伴主对话及显式重启也保留这些结果,其他交接沿用原规则。可剥图不足一半的混合大尾巴有意不救。打开会话不触发;只在终态错误或下次发送时由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援摘要不得依赖额外模型调用。-Codex 图片历史重建后,普通用户任务可在同一任务内自动续接未完成工作。交接包含原请求+伙伴 canonical 主对话在发送边界达到已知窗口的 90%,或本地 Codex 图片活尾巴实测超限时,+复用同一持久交接提前重建;保留有界工具结果、按输入取消恢复,后台原生工作未结束时不换窗。+权限依据为有效 Bot link 与 active Profile;其它任务保留原来的满窗门槛。+伙伴下一次发送也识别已记录、明确来自压缩的空摘要/invalid-request 错误;不扩大原生 latch+规则,不把普通空回复、网络、鉴权或额度错误当作压缩损坏。+Codex 图片历史重建后,普通用户任务和伙伴主对话可在同一任务内自动续接未完成工作。交接包含原请求和本轮已有进展,新原生线程只接收隐藏的继续指令,不重放原用户请求或已完成的工具操作。结果不明确时先核实当前状态,不盲目重试;旧原生执行句柄不能跨线程恢复。每条用户输入最多自动恢复一次,沿用重建记录与输入身份去重;已有助手/工具消息只禁止diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex ca19476b51..3e349caf22 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -58,10 +58,20 @@ Cindy Session,以父任务关系回到发起伙伴,但不冒充该伙伴或### 3.2 模型上下文压力-上下文接近上限时,优先使用 Harness 原生压缩;原生压缩确定性失败时走现有宿主重建流程:-生成受控交接、关闭原生句柄、在**同一条产品任务**里重建模型上下文,并且只在最新用户输入-尚未产生 assistant / tool 副作用时自动重放。不得靠提示词要求模型自行猜测何时压缩,也不得-为了重试重复执行可能有外部副作用的工具。+伙伴主对话在下一次发送的安全边界主动检查上下文:已知 token 占用达到窗口的 90%,+或 Codex 本地历史确认存在超大内联图片时,先用已有持久交接重建模型工作上下文。+交接保存近期需求、回复、改动和有界工具结果,省略图片正文;不额外调用模型生成摘要,+不等待旧 Harness 压缩成功。原生压缩仍在单轮内部正常工作,健康主对话不换窗。已持久记录的压缩空摘要/invalid-request 失败,也在下一次发送时+由宿主重建;普通网络、鉴权、额度错误不据此换窗。++Codex 图片历史在运行中确定失败时,伙伴主对话与普通桌面任务共用一次隐藏续接:+保留原请求与已记录进展,不重放原请求或已完成工具;结果不明先核实。每条输入最多自动+续接一次,停止、新输入接管和排队输入仍能取消恢复。群分工、委派、IM 和自动化输入的+续接仍由原分发者负责,不能被主对话恢复抢占。普通上下文溢出仍只在本轮没有 assistant /+tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭句柄。++自动恢复无法完成时保留错误与既有继续/重试入口;「重启伙伴」无需旧模型参与,保留+同一条时间线、记忆与文件,并携带工具结果重新建立上下文。重启不自动重放请求。完整聊天记录与模型工作上下文必须分离:压缩可以丢弃模型不再需要的旧 tool result 和中间过程,但用户时间线、搜索索引和审计记录仍按既有持久化策略保留。完整消息继续写入 SQLite,界面与