Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): 收尾压缩与假忙队列不再卡住产品 turn (#3103)
Dash6a8ec9b9e3c6
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 7d81b97376..6b39ee0815 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -186,6 +186,19 @@ describe('maker:event hot path ordering', () => {expect(coordinatorSource).toContain("return reconcileSessionTurnIdle(sessionId, 'authoritative-idle');",);+ expect(coordinatorSource).toContain('isLiveTurnRunning: (sessionId) =>');+ expect(coordinatorSource).toContain('if (!sess) return undefined;');+ });++ it('does not latch product-turn bookkeeping on background status events', () => {+ const statusStart = source.indexOf('if (event.type === \'status\') {');+ const statusEnd = source.indexOf("if (event.type === 'done')", statusStart);+ const statusSource = source.slice(statusStart, statusEnd);+ expect(statusStart).toBeGreaterThanOrEqual(0);+ expect(statusEnd).toBeGreaterThan(statusStart);+ expect(statusSource).toContain("data.isRunning === true && event.turnScope !== 'background'");+ expect(statusSource).toContain("event.turnScope !== 'background'");+ expect(statusSource).toContain('sessionTurnActivityTracker.setSessionInTurn(session.id, data.isRunning)');});it('persists a terminal Codex plan before clearing its turn-owned lookup maps', () => {diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.tsindex 9f6c0d1838..cf4338f9a3 100644--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts@@ -128,6 +128,38 @@ describe('Agent Island display state', () => {expect(buildAgentIslandDisplayState(state, 1_201).sessions[0]?.phase).toBe('completed');});+ it('does not start or complete a product turn from background compact status', () => {+ const state = createAgentIslandState();+ const meta = { sessionId: 'idle-compact', title: 'Idle compact', agentKind: 'pi' as const };++ applyAgentIslandEvent(+ state,+ meta,+ {+ type: 'status',+ source: 'pi',+ turnScope: 'background',+ data: { isRunning: true, status: 'Compacting context…' },+ },+ 1_000,+ );+ const display = buildAgentIslandDisplayState(state, 1_001);+ expect(display.sessions).toHaveLength(0);++ applyAgentIslandEvent(+ state,+ meta,+ {+ type: 'status',+ source: 'pi',+ turnScope: 'background',+ data: { isRunning: false, status: 'Done' },+ },+ 1_100,+ );+ expect(buildAgentIslandDisplayState(state, 1_101).sessions).toHaveLength(0);+ });+it('keeps the notch visible even when there are no active sessions', () => {const state = createAgentIslandState();diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 01a12a4659..ecc0e303a6 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -2619,7 +2619,7 @@ function getAgentIslandSoundEventForTransition(}function isCompletionDoneEvent(event: AgentEvent): boolean {- return isProductTurnCompletionTailEvent(event);+ return event.turnScope !== 'background' && isProductTurnCompletionTailEvent(event);}function isCancelledTerminalEvent(event: AgentEvent): boolean {@@ -2630,7 +2630,7 @@ function isCancelledTerminalEvent(event: AgentEvent): boolean {}function isRunningStatusEvent(event: AgentEvent): boolean {- if (event.type !== 'status') return false;+ if (event.type !== 'status' || event.turnScope === 'background') return false;const data = event.data as { isRunning?: unknown } | undefined;return data?.isRunning === true;}diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.tsindex f0d24d45e0..456d88a88a 100644--- a/apps/desktop/src/main/agent-island/state.ts+++ b/apps/desktop/src/main/agent-island/state.ts@@ -533,6 +533,13 @@ export function applyAgentIslandEvent(const data = asRecord(event.data);const isRunning = data?.isRunning;const status = typeof data?.status === 'string' ? data.status : null;+ if (event.turnScope === 'background') {+ if (status && !session.currentToolUseId && !session.toolDetailUntil) {+ session.detail = status;+ session.detailSource = 'status';+ }+ return true;+ }if (isRunning === true) {markSessionRunning(state, session, now);if (session.pendingInteractionIds.size === 0) {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 75596d9644..eb89a4fb9b 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@@ -170,6 +170,7 @@ function createHarness(opts?: {getRecoveryContextSnapshot?: (sessionId: string, userClientId: string) => Promise<RecoveryContextSnapshot>;}) {let running = false;+ let liveRunningOverride: boolean | null | 'unknown' = null;let turnGeneration = 0;let turnSessionIdentity: object = {};let pendingInteraction = false;@@ -286,6 +287,10 @@ function createHarness(opts?: {onRejectedUserTurn,supersedeRetriedUserTurn,isTurnRunning: () => running,+ isLiveTurnRunning: () => {+ if (liveRunningOverride === 'unknown') return undefined;+ return liveRunningOverride === null ? running : liveRunningOverride;+ },getTurnGeneration: () => turnGeneration,getTurnSessionIdentity: () => turnSessionIdentity,reconcileTurnIdle,@@ -362,6 +367,9 @@ function createHarness(opts?: {setRunning(value: boolean) {running = value;},+ setLiveRunning(value: boolean | null | 'unknown') {+ liveRunningOverride = value;+ },setTurnGeneration(value: number) {turnGeneration = value;},@@ -5942,6 +5950,161 @@ describe('AgentInputCoordinator steer transaction', () => {expect(mocks.touchUserSendInDb).toHaveBeenCalledWith(sid, undefined);});+ it('reconciles a stale tracker on drain and releases the queued head without Stop/steer', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-stale-tracker';+ const first = makeItem('q-1', 'queued-after-idle');++ h.setRunning(true);+ h.setLiveRunning(false);+ h.reconcileTurnIdle.mockImplementation(() => {+ h.setRunning(false);+ h.setLiveRunning(false);+ return true;+ });++ h.coordinator.enqueue(sid, first);+ await flush();+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(250);+ await flush();++ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not treat a second immediate drain as confirmation of a lost terminal', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-stale-tracker-grace';+ h.setRunning(true);+ h.setLiveRunning(false);+ h.reconcileTurnIdle.mockImplementation(() => {+ h.setRunning(false);+ h.setLiveRunning(false);+ return true;+ });++ h.coordinator.enqueue(sid, makeItem('q-1', 'queued-after-idle'));+ await flush();+ h.coordinator.enqueue(sid, makeItem('q-2', 'second-drain'));+ await flush();++ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(249);+ await flush();+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(1);+ await flush();+ expect(h.reconcileTurnIdle).toHaveBeenCalledWith(sid);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not reconcile a dispatched turn that has not started yet', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-dispatched-not-started';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'queued-before-agent-start');++ h.coordinator.enqueue(sid, first);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setLiveRunning(false);+ h.setRunning(true);+ h.coordinator.enqueue(sid, second);+ await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();++ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not synthesize done when the real terminal arrives during the live-idle grace', async () => {+ vi.useFakeTimers();+ try {+ const h = createHarness();+ const sid = 'drain-stale-real-done';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'queued-after-idle');++ h.coordinator.enqueue(sid, first);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setLiveRunning(false);+ h.setRunning(true);+ h.coordinator.enqueue(sid, second);+ await flush();+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);++ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'done');+ await flush();++ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'queued-after-idle',+ });++ await vi.advanceTimersByTimeAsync(250);+ await flush();+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not reconcile while the live turn is still running', async () => {+ const h = createHarness();+ const sid = 'drain-live-busy';+ h.setRunning(true);+ h.reconcileTurnIdle.mockReturnValue(false);+ h.coordinator.enqueue(sid, makeItem('q-1', 'wait'));+ await flush();+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).not.toHaveBeenCalled();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-1']);+ });++ it('does not reconcile when the live Session probe is unavailable', async () => {+ const h = createHarness();+ const sid = 'drain-live-unknown';+ h.setRunning(true);+ h.setLiveRunning('unknown');+ h.coordinator.enqueue(sid, makeItem('q-1', 'wait'));+ await flush();+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ expect(h.sendToAgent).not.toHaveBeenCalled();+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-1']);+ });+it('recovers from a zombie turn: NO_ACTIVE_TURN reconciles stale busy state and dispatches the fallback', async () => {// 场景: q-1 已派发但 turn 异常死亡 (done 事件丢失) —— coordinator 的// activeTurn 和 host busy tracker 双双 stale。修复前: 插话 → fallback →diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex cc2b06bbae..0df384880f 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -266,13 +266,16 @@ export interface AgentInputCoordinatorDeps {) => Promise<void>;abortSession: (sessionId: string) => Promise<void>;isTurnRunning: (sessionId: string) => boolean;+ /** Live Session only — must not OR the desktop tracker. undefined = probe unavailable. */+ isLiveTurnRunning?: (sessionId: string) => boolean | undefined;/** maker-core turn 代号;steer 跨 await 后据此验证仍属于开始时的同一 vendor turn。 */getTurnGeneration?: (sessionId: string) => number | null;/** maker-core Session object identity; control-plane steer uses it to reject session reuse. */getTurnSessionIdentity?: (sessionId: string) => object | null;/**- * Reconcile the host's live session/tracker view after an abort or a- * maker-core NO_ACTIVE_TURN. The event-driven tracker can stay stale when a+ * Reconcile the host's live session/tracker view after an abort, a+ * maker-core NO_ACTIVE_TURN, or a drain blocked on a stale tracker while the+ * live Session is idle. The event-driven tracker can stay stale when a* turn dies without a terminal event, leaving the queue behind a false busy* boundary. Returns true only when it actually cleared that stale boundary;* a normal status=closed cleanup returning false must not make Codex release@@ -614,6 +617,12 @@ interface SessionInputState {sessionRunningRetryDelayMs: number | null;/** 保护新 generation 的 timer 不被旧 generation 的迟到 callback 清掉。 */sessionRunningRetryToken: symbol | null;+ /**+ * First time we saw live-idle + tracker-busy while queued work was blocked.+ * Terminal events may still be in Session's AsyncQueue after the handle+ * flips idle; reconcile only after SESSION_RUNNING_RETRY_DELAY_MS.+ */+ staleLiveIdleSinceMs: number | null;/*** 发送撞上 CREDENTIAL_SWITCH_BUSY 后的可见等待态:队首保留,挡路会话 turn 结束* (onExternalTurnSettled)或兜底定时器触发自动重发。clientId 绑定等待中的那条@@ -677,6 +686,7 @@ function createInitialInputState(sessionRunningRetryOwnerKey: null,sessionRunningRetryDelayMs: null,sessionRunningRetryToken: null,+ staleLiveIdleSinceMs: null,credentialSwitchWait: null,credentialSwitchRetryTimer: null,credentialSwitchRetryGeneration: null,@@ -2940,6 +2950,7 @@ export class AgentInputCoordinator {): void {const state = this.getState(sessionId);const active = state.activeTurn;+ state.staleLiveIdleSinceMs = null;this.clearAbortReconcileRetry(state);state.queueAbortPending = false;state.abortBoundaryToken = null;@@ -3385,6 +3396,56 @@ export class AgentInputCoordinator {);}+ /**+ * Live Session idle + host tracker still busy is an invariant break.+ * Reconcile the tracker so queued input can drain without a user Stop / steer.+ * Do not call this while a send is in flight, an activeTurn still owns the+ * generation, a permission card is up, or abort/steer already owns the boundary.+ * Dispatched-but-not-started turns (Pi may accept a prompt before agent_start)+ * must wait for real lifecycle events — do not synthesize done.+ */+ private tryReconcileStaleDispatchBoundary(+ sessionId: string,+ state: SessionInputState,+ ): boolean {+ if (+ state.abortBoundaryToken ||+ state.queueAbortPending ||+ state.queueInteractionLocks.length > 0 ||+ state.steeringQueueClientIds.length > 0 ||+ state.pendingExternalTerminalDone ||+ this.deps.hasPendingInteraction(sessionId) ||+ state.activeTurn !== null+ ) {+ state.staleLiveIdleSinceMs = null;+ return false;+ }+ // Missing live probe fail-closed: do not steal abort/live-turn reconcile.+ if (this.deps.isLiveTurnRunning?.(sessionId) !== false) {+ state.staleLiveIdleSinceMs = null;+ return false;+ }++ if (!this.deps.isTurnRunning(sessionId)) {+ state.staleLiveIdleSinceMs = null;+ return false;+ }++ // Handle may already be idle while status/done is still queued in Session.+ // Extra drains in this window must not confirm; wait the existing 250ms retry.+ if (state.staleLiveIdleSinceMs == null) {+ state.staleLiveIdleSinceMs = Date.now();+ }+ if (Date.now() - state.staleLiveIdleSinceMs < SESSION_RUNNING_RETRY_DELAY_MS) {+ return false;+ }++ const reconciled = this.deps.reconcileTurnIdle?.(sessionId) === true;+ if (!reconciled) return false;+ state.staleLiveIdleSinceMs = null;+ return true;+ }+private isTurnSteerable(sessionId: string, state: SessionInputState): boolean {return state.activeTurn !== null || this.deps.isTurnRunning(sessionId);}@@ -3467,12 +3528,29 @@ export class AgentInputCoordinator {const state = this.getState(sessionId);const compact = this.getDrainableCompact(sessionId, state);if (compact) {+ state.staleLiveIdleSinceMs = null;state.pendingCompacts = state.pendingCompacts.slice(1);await this.dispatchCompact(sessionId, compact, reason);return;}const head = this.getDrainableHead(sessionId, state);if (!head) {+ const hasRunnableWork =+ state.pendingQueue.length > 0 ||+ state.pendingCompacts.some((item) => item.waitForClientIds.length === 0);+ if (+ hasRunnableWork &&+ this.isDispatchBoundaryBusy(sessionId, state) &&+ this.tryReconcileStaleDispatchBoundary(sessionId, state)+ ) {+ this.scheduleDrain(sessionId, 'reconcile-stale-idle');+ return;+ }+ if (hasRunnableWork && state.staleLiveIdleSinceMs != null) {+ this.scheduleSessionRunningRetry(sessionId, 'stale-live-idle-confirm');+ } else if (!hasRunnableWork) {+ state.staleLiveIdleSinceMs = null;+ }// #2506 结果级诊断:排队输入被 gate 挡住时留痕(此前零日志,gate-clear// 到成功 drain 之间的静默滞留无从定位)。只记 id / 布尔 / 枚举,不记正文;// 空队列的例行 drain 不记,避免每次 turn-done 都产生噪音。@@ -3502,6 +3580,7 @@ export class AgentInputCoordinator {this.scheduleExternalTurnRetryIfNeeded(sessionId, state, `drain-blocked:${reason}`);return;}+ state.staleLiveIdleSinceMs = null;state.pendingQueue = state.pendingQueue.slice(1);this.removePendingCompactWaitClientId(state, head.clientId);if (!state.stickyError) {@@ -4100,6 +4179,10 @@ export class AgentInputCoordinator {if (latest.generation !== generation) return;if (latest.pendingQueue.length === 0 && latest.pendingCompacts.length === 0) return;if (this.isDispatchBoundaryBusy(sessionId, latest)) {+ if (this.tryReconcileStaleDispatchBoundary(sessionId, latest)) {+ this.scheduleDrain(sessionId, 'session-running-retry-reconciled');+ return;+ }this.scheduleSessionRunningRetry(sessionId, reason);return;}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 68b0a4b5c6..70bc287e80 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -3847,7 +3847,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidcontextTokens?: number;contextWindow?: number;};- if (data.isRunning === true) {+ // Idle compact / late background work may still send isRunning for UI+ // copy. It must not latch the product turn tracker or idle bookkeeping.+ if (data.isRunning === true && event.turnScope !== 'background') {// replacement 已进入 vendor 后,running 是新 attempt 的权威起点。不要依赖// sendToAgent 返回后的 onDispatched 回调:provider 可同步发事件并先清 activeTurn。autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);@@ -3891,7 +3893,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void) {turnModelPromiseBySession.set(session.id, readSessionModelForUsage(session.id));}- } else if (data.isRunning === false && !isContinuationBoundary) {+ } else if (+ data.isRunning === false &&+ !isContinuationBoundary &&+ event.turnScope !== 'background'+ ) {shouldMarkTurnStatusIdleAfterBroadcast = true;}if (@@ -11547,6 +11553,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const sess = getStableSessionForTurnBoundary(sessionId);return isSessionTurnDispatchBoundaryBusy(sessionTurnActivityTracker, sessionId, sess);},+ isLiveTurnRunning: (sessionId) => {+ try {+ const sess = getStableSessionForTurnBoundary(sessionId);+ if (!sess) return undefined;+ return sess.isTurnRunning();+ } catch {+ return undefined;+ }+ },getTurnGeneration: (sessionId) =>getStableSessionForTurnBoundary(sessionId)?.getTurnGeneration() ?? null,getTurnSessionIdentity: (sessionId) => getStableSessionForTurnBoundary(sessionId) ?? null,diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreCompactBoundary.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreCompactBoundary.test.tsindex 2bd2c00f67..029a089a7a 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreCompactBoundary.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreCompactBoundary.test.ts@@ -81,4 +81,31 @@ describe('handleStreamEvent compact boundary identity', () => {expect(afterSecond.streamingClientId).toBeNull();expect(afterSecond.messages.at(-1)?.clientId).toBe('compact:boundary-2');});++ it('does not finish a live turn when a background compact_boundary arrives', () => {+ const streaming = {+ ...EMPTY_SESSION_STATE,+ messages: [+ {+ clientId: 'live-after-idle-compact',+ role: 'assistant' as const,+ content: '正在回答',+ isStreaming: true,+ },+ ],+ streamingClientId: 'live-after-idle-compact',+ isStreaming: true,+ };+ const afterBackground = handleStreamEvent(streaming, {+ ...compactEvent('idle-compact'),+ turnScope: 'background',+ });++ expect(afterBackground.streamingClientId).toBe('live-after-idle-compact');+ expect(afterBackground.isStreaming).toBe(true);+ expect(+ afterBackground.messages.find((message) => message.clientId === 'live-after-idle-compact'),+ ).toMatchObject({ isStreaming: true });+ expect(afterBackground.messages.at(-1)?.systemCardType).toBe('compact');+ });});diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex e96dbc9a58..0b5b47bdee 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -2116,6 +2116,59 @@ describe('makerChatStore text delta batching', () => {expect(snap.messages.some((m) => m.role === 'user' && m.content === 'next')).toBe(false);});+ it('does not flip product isRunning for background compact status', () => {+ emitStatus({ status: 'Done', isRunning: false });+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(false);++ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'status',+ source: 'pi',+ turnScope: 'background',+ data: {+ status: 'Compacting context…',+ isRunning: true,+ tokenUsage: 0,+ contextTokens: 415010,+ contextWindow: 500000,+ },+ },+ });++ const snap = makerChatStore.getSnapshot(SESSION_ID);+ expect(snap.agentStatus.isRunning).toBe(false);+ expect(snap.agentStatus.status).toBe('Compacting context…');+ expect(snap.agentStatus.contextTokens).toBe(415010);+ expect(snap.agentStatus.contextWindow).toBe(500000);+ });++ it('does not paint a live turn as Done when a late background compact status arrives', () => {+ emitStatus({ status: 'Thinking…', isRunning: true });+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(true);++ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'status',+ source: 'pi',+ turnScope: 'background',+ data: {+ status: 'Done',+ isRunning: false,+ tokenUsage: 0,+ contextTokens: 20000,+ contextWindow: 500000,+ },+ },+ });++ const snap = makerChatStore.getSnapshot(SESSION_ID);+ expect(snap.agentStatus.isRunning).toBe(true);+ expect(snap.agentStatus.status).toBe('Thinking…');+ expect(snap.agentStatus.contextTokens).toBe(20000);+ });+// 本地 only 迁移后,网关 key 无服务器副本,401 不再触发"从服务器重拉 key"。// 原先验证 refreshApiKeyFromServer 调用次数的两个用例(terminal → 重拉、recoverable// → 不重拉)随该行为一并移除。非 remote 会话的 401 直接把 error 浮现给用户。diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 94edffc955..c607e98300 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -5748,11 +5748,14 @@ export function handleStreamEvent(if (boundaryId && state.messages.some((message) => message.clientId === clientId)) {return state;}- const finalized = finalizeStreamingInState(state);+ // Background compact belongs to the previous idle cycle. Finalizing here+ // would seal a product turn that started after compaction_start.+ const nextState =+ event.turnScope === 'background' ? state : finalizeStreamingInState(state);return {- ...finalized,+ ...nextState,messages: [- ...finalized.messages,+ ...nextState.messages,{clientId,role: 'assistant' as const,@@ -5942,6 +5945,39 @@ function mergeLiveGenerationStatus(return merged;}+/** Idle compact / late background status may refresh copy and context tokens without flipping the product turn. */+function applyBackgroundStatus(+ state: SessionChatState,+ data: Record<string, unknown>,+): SessionChatState {+ const rawStatus = typeof data.status === 'string' ? data.status.trim() : '';+ // A late idle-compact Done must not paint the product turn as finished.+ const status =+ !rawStatus || (rawStatus === 'Done' && state.agentStatus.isRunning)+ ? state.agentStatus.status+ : rawStatus;+ let contextTokens = state.agentStatus.contextTokens;+ let contextWindow = state.agentStatus.contextWindow;+ if (+ typeof data.contextWindow === 'number' &&+ data.contextWindow > 0 &&+ typeof data.contextTokens === 'number' &&+ data.contextTokens >= 0+ ) {+ contextTokens = data.contextTokens;+ contextWindow = data.contextWindow;+ }+ return {+ ...state,+ agentStatus: {+ ...state.agentStatus,+ status,+ contextTokens,+ contextWindow,+ },+ };+}+function handleStatusUpdate(state: SessionChatState,update: CCAgentStatusUpdate,@@ -6103,6 +6139,7 @@ type MakerEventPayload = {source?: 'claude-code' | 'codex' | 'pi' | 'vision-bridge';agentMeta?: Record<string, unknown>;turnContinuationId?: number;+ turnScope?: 'turn' | 'background';};persistId?: string;resolvedContent?: string;@@ -6286,6 +6323,7 @@ function dispatchStreamEventPayload(...(event.turnContinuationId !== undefined? { turnContinuationId: event.turnContinuationId }: {}),+ ...(event.turnScope !== undefined ? { turnScope: event.turnScope } : {}),persistId,resolvedContent,} as CCAgentStreamEvent;@@ -6666,9 +6704,14 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {// 持久化 (totalCostUsd / contextTokens / contextWindow → sessions 表) 已搬到 main 端的// sessionSpendBroadcaster, renderer 只更新 in-memory agentStatus, 不再 IPC 写库 (避免多 window 竞写)。if (event.type === 'status') {+ const data = event.data as Record<string, unknown>;+ if (event.turnScope === 'background') {+ setState(sessionId, (s) => applyBackgroundStatus(s, data));+ return;+ }const update = {sessionId,- ...(event.data as Record<string, unknown>),+ ...data,...(event.turnContinuationId !== undefined? { turnContinuationId: event.turnContinuationId }: {}),diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fa835e8688..1b8432518c 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -704,6 +704,8 @@ interface CCAgentStreamEvent {agentMeta?: import('@/lib/ccAgent.types').AgentMeta;/** Host-owned SDK boundary claim; claimed done/status events are not product completion. */turnContinuationId?: number;+ /** Idle/host compact is not a product turn; must not finalize live streaming. */+ turnScope?: 'turn' | 'background';/*** F1-a: 由 main 端 messagePersistBroadcaster 为这条消息分配的稳定 persistId,* 经 maker:event payload 透传。renderer 用它当在途气泡 clientId(不再自造随机),diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 9713be2cdd..996df7ef54 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -1384,6 +1384,61 @@ describe('remoteSessionStore', () => {}});+ it('does not finish a live turn when a background compact_boundary arrives', () => {+ remoteSessionStore.setMessages('s1', [{+ ...messageAt('live-after-idle-compact', 's1', '2026-01-01T00:00:01.000Z'),+ content: { text: '正在回答', isStreaming: true, streaming: true },+ agentMeta: { isStreaming: true, streaming: true },+ }]);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'compact_boundary',+ turnScope: 'background',+ data: { boundaryId: 'idle-compact', trigger: 'auto' },+ });++ const stored = remoteSessionStore.getMessages('s1');+ expect(stored.find((item) => item.id === 'live-after-idle-compact')).toMatchObject({+ agentMeta: { isStreaming: true, streaming: true },+ content: { text: '正在回答', isStreaming: true, streaming: true },+ });+ expect(stored.at(-1)).toMatchObject({+ id: 'mobile-system-compact:idle-compact',+ systemCardType: 'compact',+ });+ });++ it('does not flip product isRunning for background compact status', () => {+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true, status: 'Thinking…', tokenUsage: 80 },+ });+ expect(remoteSessionStore.getSessionRunStatus('s1').isRunning).toBe(true);+ expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(true);++ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ turnScope: 'background',+ data: { isRunning: true, status: 'Compacting context…' },+ });+ expect(remoteSessionStore.getSessionRunStatus('s1')).toMatchObject({+ isRunning: true,+ status: 'Compacting context…',+ tokenUsage: 80,+ });+ expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(true);++ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ turnScope: 'background',+ data: { isRunning: false, status: 'Done' },+ });+ expect(remoteSessionStore.getSessionRunStatus('s1')).toMatchObject({+ isRunning: true,+ status: 'Compacting context…',+ });+ expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(true);+ });+it('increments message version when searchable message windows change', () => {const initialVersion = remoteSessionStore.getMessageVersion();remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex a76661dfd1..5fa4c0d3fc 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -3091,14 +3091,18 @@ export const remoteSessionStore = {if (textFlushed || reconnectCleared) emit();return;}- // The compact boundary itself preserves the historical `streaming: false` marker- // on the rows (the renderer uses it for compact boundaries), so do not use the- // generic finalizer here. Only retire the live-row identity after de-duplication.- streamingAssistantClientIds.delete(sessionId);- const finalized = existing.map(finishMessageStreamingAtCompactBoundary);+ const backgroundCompact = readString(event, 'turnScope') === 'background';+ // Background compact belongs to the previous idle cycle. Finalizing here+ // would seal a product turn that started after compaction_start.+ if (!backgroundCompact) {+ streamingAssistantClientIds.delete(sessionId);+ }+ const nextMessages = backgroundCompact+ ? existing+ : existing.map(finishMessageStreamingAtCompactBoundary);const createdAt = new Date().toISOString();messages.set(sessionId, normalizeMessages([- ...finalized,+ ...nextMessages,{id: clientId,clientId,@@ -3119,6 +3123,16 @@ export const remoteSessionStore = {if (type === 'status') {const data = isRecord(event.data) ? event.data : null;const current = readSessionRunStatus(sessionId);+ if (readString(event, 'turnScope') === 'background') {+ const rawStatus = readString(data, 'status') ?? '';+ const status =+ !rawStatus || (rawStatus === 'Done' && current.isRunning)+ ? current.status+ : rawStatus;+ const changed = writeSessionRunStatus(sessionId, { ...current, status });+ if (changed || textFlushed || reconnectCleared) emit();+ return;+ }const isRunning = typeof data?.isRunning === 'boolean' ? data.isRunning : current.isRunning;if (!isRunning && isTurnContinuationBoundaryEvent(event)) {// A claimed status(false) closes only the provider SDK segment. Keep thediff --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 c5d145e6e3..dc52c5b026 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@@ -505,6 +505,7 @@ describe('pi translator', () => {(e) => e.type === 'status' && (e.data as { isRunning?: boolean }).isRunning === true,);expect(startStatus).toBeDefined();+ expect(startStatus?.turnScope).toBe('background');translatePiEvent(ev({ type: 'compaction_end', reason: 'manual', result: { tokensBefore: 100, estimatedTokensAfter: 20 } }),@@ -520,6 +521,78 @@ describe('pi translator', () => {const endData = endStatus!.data as { status: string; contextTokens?: number };expect(endData.status).toBe('Done');expect(endData.contextTokens).toBe(20);+ expect(endStatus?.turnScope).toBe('background');+ });++ it('marks idle/host auto-compact status as background so it cannot latch a product turn', () => {+ const ctx = createPiTranslateContext(noopLogger);+ ctx.isStreaming = false;+ ctx.hostAutoCompactInFlight = true;+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'compaction_start' }), queue, ctx);+ const start = events.find((e) => e.type === 'status');+ expect(start).toMatchObject({+ turnScope: 'background',+ data: expect.objectContaining({ isRunning: true, status: 'Compacting context…' }),+ });+ });++ it('does not mark in-turn compaction_start as background', () => {+ const ctx = createPiTranslateContext(noopLogger);+ ctx.isStreaming = true;+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'compaction_start' }), queue, ctx);+ const start = events.find((e) => e.type === 'status');+ expect(start).toBeDefined();+ expect(start?.turnScope).toBeUndefined();+ });++ it('keeps idle compact_boundary background after a new turn starts mid-compact', () => {+ const ctx = createPiTranslateContext(noopLogger);+ ctx.isStreaming = false;+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'compaction_start', reason: 'threshold' }), queue, ctx);+ expect(events.find((e) => e.type === 'status')?.turnScope).toBe('background');++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ expect(ctx.isStreaming).toBe(true);++ translatePiEvent(+ ev({+ type: 'compaction_end',+ reason: 'threshold',+ result: { tokensBefore: 150000, estimatedTokensAfter: 32000 },+ }),+ queue,+ ctx,+ );+ const boundary = events.find((e) => e.type === 'compact_boundary');+ expect(boundary?.turnScope).toBe('background');+ expect(+ events.filter(+ (e) => e.type === 'status' && (e.data as { status?: string }).status === 'Done',+ ),+ ).toHaveLength(0);+ });++ it('does not relabel an in-turn compact_boundary as background if streaming later stops', () => {+ const ctx = createPiTranslateContext(noopLogger);+ ctx.isStreaming = true;+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'compaction_start', reason: 'threshold' }), queue, ctx);+ ctx.isStreaming = false;+ translatePiEvent(+ ev({+ type: 'compaction_end',+ reason: 'threshold',+ result: { tokensBefore: 150000, estimatedTokensAfter: 32000 },+ }),+ queue,+ ctx,+ );+ const boundary = events.find((e) => e.type === 'compact_boundary');+ expect(boundary).toBeDefined();+ expect(boundary?.turnScope).toBeUndefined();});it('#1933 review:auto compaction 在活跃 turn 内不补发 status(false)(不得误收口 turn)', () => {diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 400ddee89c..99fe55d87e 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -134,6 +134,12 @@ export interface PiTranslateContext {subagentToolCalls: Map<string, AgentTaskUpdateEventData>;/** Host 百分比闸发起的 compact RPC 在途;Pi 仍会报 reason=manual。 */hostAutoCompactInFlight: boolean;+ /**+ * compaction_start 锁存的 turnScope。end/boundary 必须复用,不能按结束时的+ * isStreaming 重判——idle compact 期间用户开了新 turn 时,重判会把后台边界+ * 当成前台事件,截断正在流式的 assistant。+ */+ compactTurnScope: 'background' | 'turn' | null;}export function createPiTranslateContext(logger: Logger): PiTranslateContext {@@ -163,6 +169,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {subagentToolCalls: new Map(),pendingAssistantError: null,hostAutoCompactInFlight: false,+ compactTurnScope: null,};}@@ -181,6 +188,7 @@ export function disposePiTranslateContext(ctx: PiTranslateContext): void {stopPiGenerationHeartbeat(ctx);ctx.isStreaming = false;ctx.pendingAssistantError = null;+ ctx.compactTurnScope = null;ctx.subagentToolCalls.clear();}@@ -227,14 +235,39 @@ function pushStatus(ctx: PiTranslateContext,text: string,isRunning: boolean,+ extras?: Pick<AgentEvent, 'turnScope'>,): void {queue.push({type: 'status',data: { status: text, ...usageSnapshotOf(ctx), isRunning },source: 'pi',+ ...(extras?.turnScope ? { turnScope: extras.turnScope } : {}),});}+/** Idle compact is not a product turn; mark it background so host/UI do not latch busy. */+function idleCompactScope(ctx: PiTranslateContext): Pick<AgentEvent, 'turnScope'> | undefined {+ return ctx.isStreaming ? undefined : { turnScope: 'background' };+}++function latchCompactTurnScope(+ ctx: PiTranslateContext,+): Pick<AgentEvent, 'turnScope'> | undefined {+ const scope = idleCompactScope(ctx);+ ctx.compactTurnScope = scope?.turnScope === 'background' ? 'background' : 'turn';+ return scope;+}++function takeCompactTurnScope(+ ctx: PiTranslateContext,+): Pick<AgentEvent, 'turnScope'> | undefined {+ const latched = ctx.compactTurnScope;+ ctx.compactTurnScope = null;+ if (latched === 'background') return { turnScope: 'background' };+ if (latched === 'turn') return undefined;+ return idleCompactScope(ctx);+}+function applyUsage(ctx: PiTranslateContext, usage: PiUsage | undefined): void {if (!usage) return;const input = usage.input ?? 0;@@ -697,15 +730,19 @@ export function translatePiEvent(}case 'compaction_start': {- pushStatus(queue, ctx, 'Compacting context…', true);+ // Host auto-compact 发在 agent_settled 之后(isStreaming=false)。若这里+ // 无条件 isRunning=true 而不标 background,desktop tracker 会当成新一轮产品 turn。+ // 在 start 锁存 scope:end 时 isStreaming 可能已因新 turn 变 true。+ pushStatus(queue, ctx, 'Compacting context…', true, latchCompactTurnScope(ctx));return;}case 'compaction_end': {+ const compactScope = takeCompactTurnScope(ctx);if (isFailedOrAbortedPiCompaction(event)) {// 失败/取消不是压缩边界。手动压缩仍要收口 Compacting 状态,避免圆环卡 running。if (event.reason === 'manual' && !ctx.isStreaming) {- pushStatus(queue, ctx, 'Done', false);+ pushStatus(queue, ctx, 'Done', false, compactScope);}return;}@@ -718,6 +755,7 @@ export function translatePiEvent(postTokens: result?.estimatedTokensAfter,},source: 'pi',+ ...compactScope,});if (result && typeof result.estimatedTokensAfter === 'number') {ctx.contextTokens = result.estimatedTokensAfter;@@ -726,8 +764,9 @@ export function translatePiEvent(// 若不收口,renderer 圆环会永久卡 running、新 contextTokens 也送不回去。// 仅 manual 收口:auto 压缩发生在活跃 turn 内(turn 结束经 agent_settled 自然收口),// 且若压缩期间用户已开始新 turn(ctx.isStreaming)也不能收口,否则会误杀新 turn。+ // idle compact 的 status 带 turnScope=background,产品 turn 位不再闪。if (event.reason === 'manual' && !ctx.isStreaming) {- pushStatus(queue, ctx, 'Done', false);+ pushStatus(queue, ctx, 'Done', false, compactScope);}return;}diff --git a/packages/maker-shared/src/__tests__/turnContinuation.test.ts b/packages/maker-shared/src/__tests__/turnContinuation.test.tsindex 39914e133b..2c10a18924 100644--- a/packages/maker-shared/src/__tests__/turnContinuation.test.ts+++ b/packages/maker-shared/src/__tests__/turnContinuation.test.ts@@ -47,5 +47,13 @@ describe('turn continuation predicates', () => {expect(isProductTurnCompletionTailEvent({ type: 'status', data: { status: 'Working', isRunning: false } })).toBe(false);expect(isProductTurnCompletionTailEvent({ type: 'status', data: { status: 'Done', isRunning: true } })).toBe(false);expect(isProductTurnCompletionTailEvent({ type: 'status', data: null })).toBe(false);+ expect(+ isProductTurnCompletionTailEvent({+ type: 'status',+ turnScope: 'background',+ data: { status: 'Done', isRunning: false },+ }),+ ).toBe(false);+ expect(isProductTurnCompletionTailEvent({ type: 'done', turnScope: 'background' })).toBe(false);});});diff --git a/packages/maker-shared/src/turnContinuation.ts b/packages/maker-shared/src/turnContinuation.tsindex 99a4070669..cfd6bb597c 100644--- a/packages/maker-shared/src/turnContinuation.ts+++ b/packages/maker-shared/src/turnContinuation.ts@@ -12,6 +12,7 @@ export interface TurnContinuationEventLike {type?: unknown;data?: unknown;turnContinuationId?: unknown;+ turnScope?: unknown;}export function isTurnContinuationBoundaryEvent(@@ -34,6 +35,7 @@ export function isProductTurnCompletionTailEvent(event: TurnContinuationEventLike | null | undefined,): boolean {if (!event || isTurnContinuationBoundaryEvent(event)) return false;+ if (event.turnScope === 'background') return false;if (event.type === 'done') return true;if (event.type !== 'status' || !isRecord(event.data)) return false;return event.data.isRunning === false && event.data.status === 'Done';