Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 续跑发出后仍显示「重新连接中 N/5」并继续转圈 (#1225)

Dash6666cd3be3ff
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.ts
index fc7404b90e..4f202e1fa2 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
@@ -153,6 +153,7 @@ function sessionRunningError(): Error & { code: string } {
function createHarness() {
let running = false;
+ let turnGeneration = 0;
let pendingInteraction = false;
let agentKind: 'claude-code' | 'codex' | null = 'claude-code';
const projections: AgentInputProjection[] = [];
@@ -224,6 +225,7 @@ function createHarness() {
onUserEnqueue,
supersedeRetriedUserTurn,
isTurnRunning: () => running,
+ getTurnGeneration: () => turnGeneration,
reconcileTurnIdle,
hasPendingInteraction: () => pendingInteraction,
getAgentKind: () => agentKind,
@@ -278,6 +280,9 @@ function createHarness() {
setRunning(value: boolean) {
running = value;
},
+ setTurnGeneration(value: number) {
+ turnGeneration = value;
+ },
setPendingInteraction(value: boolean) {
pendingInteraction = value;
},
@@ -5196,6 +5201,167 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()
expect(projection.continuationInFlightClientId).toBeNull();
});
+ it('preserves the continuation vendor-turn owner after an accepted steer', async () => {
+ const h = createHarness();
+ const sid = 'continue-owner-survives-steer';
+
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),
+ { resumeRestorePausedQueue: true },
+ );
+ await flush();
+
+ let projection = latestProjection(h.projections);
+ expect(projection.continuationInFlightClientId).toBe('q-continue');
+ expect(projection.continuationTurnClientId).toBe('q-continue');
+
+ await h.coordinator.steer(sid, makeItem('q-steer', 'additional context'));
+ await flush();
+
+ projection = latestProjection(h.projections);
+ expect(projection.continuationInFlightClientId).toBeNull();
+ expect(projection.continuationTurnClientId).toBe('q-continue');
+
+ h.coordinator.onTurnEvent(sid, 'done');
+ projection = latestProjection(h.projections);
+ expect(projection.continuationTurnClientId).toBeNull();
+ });
+
+ it('keeps the continuation owner when a terminal event races ahead of steer ack but host remains running', async () => {
+ const h = createHarness();
+ h.setAgentKind('codex');
+ const sid = 'continue-owner-terminal-before-steer-ack';
+ const steerGate = deferred<void>();
+ h.steerToAgent.mockImplementationOnce(() => steerGate.promise);
+
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),
+ { resumeRestorePausedQueue: true },
+ );
+ await flush();
+
+ const steerPromise = h.coordinator.steer(sid, makeItem('q-steer', 'additional context'));
+ await flush();
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+ expect(latestProjection(h.projections).continuationTurnClientId).toBeNull();
+
+ // maker-core 仍把注入接受进同一 vendor turn;host running 视图也仍为 true。
+ steerGate.resolve();
+ await expect(steerPromise).resolves.toBe(true);
+ await flush();
+
+ expect(latestProjection(h.projections).continuationTurnClientId).toBe('q-continue');
+ });
+
+ it('does not inherit a continuation owner when vendor turn generation is unavailable', async () => {
+ const h = createHarness();
+ h.setAgentKind('codex');
+ const sid = 'continue-owner-generation-unavailable';
+ const steerGate = deferred<void>();
+ h.steerToAgent.mockImplementationOnce(() => steerGate.promise);
+
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),
+ { resumeRestorePausedQueue: true },
+ );
+ await flush();
+
+ h.setTurnGeneration(null as never);
+ const steerPromise = h.coordinator.steer(sid, makeItem('q-steer', 'additional context'));
+ await flush();
+ steerGate.resolve();
+ await expect(steerPromise).resolves.toBe(true);
+ await flush();
+
+ expect(latestProjection(h.projections).continuationTurnClientId).toBeNull();
+ });
+
+ it('does not inherit a continuation owner when another vendor turn starts during steer ack', async () => {
+ const h = createHarness();
+ h.setAgentKind('codex');
+ h.setTurnGeneration(1);
+ const sid = 'continue-owner-new-vendor-turn-during-steer';
+ const steerGate = deferred<void>();
+ h.steerToAgent.mockImplementationOnce(() => steerGate.promise);
+
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),
+ { resumeRestorePausedQueue: true },
+ );
+ await flush();
+
+ const steerPromise = h.coordinator.steer(sid, makeItem('q-steer', 'additional context'));
+ await flush();
+ h.coordinator.onTurnEvent(sid, 'done');
+ h.setTurnGeneration(2);
+
+ steerGate.resolve();
+ await expect(steerPromise).resolves.toBe(true);
+ await flush();
+
+ expect(latestProjection(h.projections).continuationTurnClientId).toBeNull();
+ });
+
+ it('clears the continuation vendor-turn owner immediately when the user stops', async () => {
+ const h = createHarness();
+ h.setAgentKind('codex');
+ const sid = 'continue-owner-cleared-on-stop';
+
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),
+ { resumeRestorePausedQueue: true },
+ );
+ await flush();
+
+ expect(latestProjection(h.projections).continuationTurnClientId).toBe('q-continue');
+
+ h.coordinator.stop(sid);
+ await flush();
+
+ expect(latestProjection(h.projections).continuationTurnClientId).toBeNull();
+ });
+
+ it('keeps the continuation dispatch identity current when Stop wins during vendor send', async () => {
+ const h = createHarness();
+ h.setAgentKind('codex');
+ const sid = 'continue-owner-stop-during-vendor-send';
+ const sendStarted = deferred<void>();
+ const sendSettled = deferred<void>();
+
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ sendStarted.resolve();
+ await sendSettled.promise;
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ return sendSuccess();
+ });
+
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),
+ { resumeRestorePausedQueue: true },
+ );
+ await sendStarted.promise;
+
+ h.coordinator.stop(sid);
+ expect(latestProjection(h.projections).continuationTurnClientId).toBeNull();
+
+ sendSettled.resolve();
+ await flush();
+
+ expect(latestProjection(h.projections).continuationTurnClientId).toBeNull();
+ expect(h.onDispatchedUserTurn).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ clientId: 'q-continue' }),
+ expect.any(Number),
+ );
+ });
+
it('does not retain an in-flight continuation marker when the user cancels it in the queue', async () => {
const h = createHarness();
const sid = 'continue-cancelled-while-queued';
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 9a38f2a71f..e8e0d8c987 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -129,6 +129,8 @@ export interface AgentInputCoordinatorDeps {
) => Promise<void>;
abortSession: (sessionId: string) => Promise<void>;
isTurnRunning: (sessionId: string) => boolean;
+ /** maker-core turn 代号;steer 跨 await 后据此验证仍属于开始时的同一 vendor turn。 */
+ getTurnGeneration?: (sessionId: string) => number | 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
@@ -307,6 +309,8 @@ interface ActiveTurn {
sendStarted: boolean;
dispatchLifecycle: ActiveTurnDispatchLifecycle;
pendingTerminalEvent: ActiveTurnTerminalEvent | null;
+ /** 当前 vendor turn 由哪条 Continue 合成项发起;同轮 steer 会继承它。 */
+ continuationOwnerClientId: string | null;
controlKind?: 'compact';
}
@@ -1048,6 +1052,7 @@ export class AgentInputCoordinator {
sendStarted: false,
dispatchLifecycle: 'preparing',
pendingTerminalEvent: null,
+ continuationOwnerClientId: null,
controlKind: 'compact',
};
state.activeTurn = active;
@@ -1178,6 +1183,11 @@ export class AgentInputCoordinator {
const messageUuid = crypto.randomUUID();
const createdAt = new Date().toISOString();
const steerGeneration = state.generation;
+ // steer ack 期间原 turn 可能先收到 terminal 事件并清掉 activeTurn。owner 是本次
+ // 注入开始时就已确定的 vendor-turn 身份,必须在 await 前快照,不能等 ack 后再从
+ // 可能已经清空的 activeTurn 读取。
+ const steerContinuationOwnerClientId = state.activeTurn?.continuationOwnerClientId ?? null;
+ const steerVendorTurnGeneration = this.deps.getTurnGeneration?.(sessionId) ?? null;
this.clearErrorUnlessQueueHeadBlocked(state, item.clientId);
state.queuePaused = false;
if (!state.steeringQueueClientIds.includes(item.clientId)) {
@@ -1356,6 +1366,9 @@ export class AgentInputCoordinator {
accepted.stickyError = null;
accepted.recovery = null;
this.invalidateAbortBoundaryForNewTurn(accepted);
+ const sameVendorTurn =
+ steerVendorTurnGeneration !== null &&
+ this.deps.getTurnGeneration?.(sessionId) === steerVendorTurnGeneration;
accepted.activeTurn = {
item,
delivery: 'steer',
@@ -1367,6 +1380,12 @@ export class AgentInputCoordinator {
sendStarted: true,
dispatchLifecycle: 'dispatched',
pendingTerminalEvent: null,
+ continuationOwnerClientId:
+ item.originalSyntheticTrigger === 'continue'
+ ? item.clientId
+ : sameVendorTurn
+ ? steerContinuationOwnerClientId
+ : null,
};
this.emit(sessionId);
@@ -1440,6 +1459,12 @@ export class AgentInputCoordinator {
state.stickyError = null;
state.recovery = null;
this.cancelPreSendActiveTurn(sessionId, state, preserveQueue);
+ // 用户显式 Stop 立即结束续跑行的 vendor-turn 归属。已跨过 vendor dispatch
+ // 的 activeTurn 仍需保留到 abort/terminal 收口,以维持队列边界;这里只清 owner,
+ // 让本次 stop projection 不再把「重新连接中」误判为仍在飞。
+ if (state.activeTurn && state.activeTurn.continuationOwnerClientId !== null) {
+ state.activeTurn.continuationOwnerClientId = null;
+ }
const shouldPause = Boolean(preserveQueue && opts?.pauseQueue && state.pendingQueue.length > 0);
state.queuePaused = shouldPause;
// Stop 出来的暂停是用户显式意图,不许后续新输入静默放行(区别于崩溃恢复暂停)。
@@ -2174,6 +2199,7 @@ export class AgentInputCoordinator {
state.activeTurn?.item?.originalSyntheticTrigger === 'continue'
? state.activeTurn.item.clientId
: null,
+ continuationTurnClientId: state.activeTurn?.continuationOwnerClientId ?? null,
steeringQueueClientIds: [...state.steeringQueueClientIds],
queuePaused: state.queuePaused,
queueExpanded: state.queueExpanded,
@@ -2313,6 +2339,8 @@ export class AgentInputCoordinator {
sendStarted: false,
dispatchLifecycle: 'preparing',
pendingTerminalEvent: null,
+ continuationOwnerClientId:
+ head.originalSyntheticTrigger === 'continue' ? head.clientId : null,
};
state.activeTurn = active;
this.emit(sessionId);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 520c547b52..c96cdc6d58 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -7757,6 +7757,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const sess = getStableSessionForTurnBoundary(sessionId);
return isSessionTurnDispatchBoundaryBusy(sessionTurnActivityTracker, sessionId, sess);
},
+ getTurnGeneration: (sessionId) =>
+ getStableSessionForTurnBoundary(sessionId)?.getTurnGeneration() ?? null,
reconcileTurnIdle: (sessionId) => {
// steer 拿到 maker-core 权威 NO_ACTIVE_TURN、或 abort 已让 vendor 停止
// 但终态事件丢失时,都走同一条收口路径。
diff --git a/apps/desktop/src/renderer/__tests__/findLastUserInputClientId.test.ts b/apps/desktop/src/renderer/__tests__/findLastUserInputClientId.test.ts
new file mode 100644
index 0000000000..778772cfcd
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/findLastUserInputClientId.test.ts
@@ -0,0 +1,142 @@
+/**
+ * findLastUserInputClientId.test.ts
+ * ---------------------------------------------------------------------------
+ * 自愈重连行的「此刻是不是我在飞」判据。
+ *
+ * 与同目录 findLastUserMessageClientId.test.ts 是**刻意成对**的两份:那份服务于「编辑
+ * 最后一条消息」这个可见 affordance,必须跳过渲染成 null 的合成行;本份要回答「正在跑的
+ * 这个 turn 是不是自动续跑发起的」——合成行恰恰是那个 turn 的发起者,跳过就答不了。
+ * 两份对同一份消息列表给出不同答案是正确的,改动时不要"统一"它们。
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ findLastUserInputClientId,
+ findLastUserMessageClientId,
+ isAutoResumeRowInFlight,
+} from '../components/chat/MessageStream';
+import type { ChatMessage } from '@/lib/makerChatStore';
+
+const mk = (clientId: string, role: ChatMessage['role']): ChatMessage =>
+ ({ clientId, role, content: clientId, isStreaming: false }) as ChatMessage;
+const synthetic = (clientId: string): ChatMessage =>
+ ({ ...mk(clientId, 'user'), isSyntheticTrigger: true }) as ChatMessage;
+
+describe('findLastUserInputClientId', () => {
+ it('空列表 / 没有 user 行 → null', () => {
+ expect(findLastUserInputClientId([])).toBeNull();
+ expect(findLastUserInputClientId([mk('a1', 'assistant'), mk('t1', 'thinking')])).toBeNull();
+ });
+
+ it('**含**合成行:自动续跑指令是最后一条用户侧输入', () => {
+ const messages = [mk('u1', 'user'), mk('a1', 'assistant'), synthetic('resume1')];
+ expect(findLastUserInputClientId(messages)).toBe('resume1');
+ // 同一份列表,编辑入口那份刻意给出不同答案(它要的是可见的真实 user 行)。
+ expect(findLastUserMessageClientId(messages)).toBe('u1');
+ });
+
+ it('续跑之后只有 thinking / tool 行 → 仍是续跑那条(它还在飞)', () => {
+ const messages = [
+ mk('u1', 'user'),
+ mk('a1', 'assistant'),
+ synthetic('resume1'),
+ mk('th1', 'thinking'),
+ mk('t1', 'tool_use'),
+ mk('r1', 'tool_result'),
+ ];
+ expect(findLastUserInputClientId(messages)).toBe('resume1');
+ });
+
+ it('用户自己接手后 → 换成他那条,旧的重连行随之停转', () => {
+ // 这是"只看会话在跑"会出错的场景:正在跑的已经是用户那个 turn 了。
+ const messages = [synthetic('resume1'), mk('th1', 'thinking'), mk('u2', 'user')];
+ expect(findLastUserInputClientId(messages)).toBe('u2');
+ });
+
+ it('插话(steer)不夺走归属:自愈 turn 里插一句,重连行仍在飞', () => {
+ // steer 是同一个正在跑的 turn 内的追加输入,不是新 turn 的发起者。算进来的话正在跑的
+ // 重连行会提前停转、退回静态(codex P2 / greptile P1)。这一支还是兜底判据成立的关键:
+ // steer 被接受时 coordinator 会替换 activeTurn,首选判据(continuationInFlight)随之失效。
+ const steer = { ...mk('s1', 'user'), delivery: 'steer' } as ChatMessage;
+ const messages = [mk('u1', 'user'), synthetic('resume1'), steer];
+ expect(findLastUserInputClientId(messages)).toBe('resume1');
+ });
+
+ it('插话之后又来一条真实用户消息(delivery=turn)→ 正常交接', () => {
+ const steer = { ...mk('s1', 'user'), delivery: 'steer' } as ChatMessage;
+ const real = { ...mk('u2', 'user'), delivery: 'turn' } as ChatMessage;
+ const messages = [synthetic('resume1'), steer, real];
+ expect(findLastUserInputClientId(messages)).toBe('u2');
+ });
+
+ it('连续两次重连 → 取后一条', () => {
+ const messages = [synthetic('resume1'), synthetic('resume2')];
+ expect(findLastUserInputClientId(messages)).toBe('resume2');
+ });
+});
+
+describe('isAutoResumeRowInFlight', () => {
+ const base = {
+ isContinuationTurnOwner: false,
+ sessionRunning: true,
+ isLastUserInput: true,
+ projectionCapability: 'supported' as const,
+ };
+
+ it('main owner 精确匹配覆盖已进入运行态、正文尚未到达的窗口', () => {
+ expect(
+ isAutoResumeRowInFlight({
+ ...base,
+ isContinuationTurnOwner: true,
+ }),
+ ).toBe(true);
+ });
+
+ it('renderer done 终态同步清除 stale continuation owner', async () => {
+ const { EMPTY_SESSION_STATE, handleStreamEvent } = await import('@/lib/makerChatStore');
+ const next = handleStreamEvent(
+ {
+ ...EMPTY_SESSION_STATE,
+ continuationTurnClientId: 'resume-1',
+ isStreaming: true,
+ agentStatus: {
+ ...EMPTY_SESSION_STATE.agentStatus,
+ isRunning: true,
+ },
+ },
+ { sessionId: 's1', type: 'done', data: {} },
+ );
+
+ expect(next.continuationTurnClientId).toBeNull();
+ expect(next.agentStatus.isRunning).toBe(false);
+ });
+
+ it('新版 supported 未匹配 owner → 不把无关 Goal turn 误判成重连', () => {
+ expect(isAutoResumeRowInFlight(base)).toBe(false);
+ });
+
+ it('尚未收到投影的 unknown fail closed', () => {
+ expect(isAutoResumeRowInFlight({ ...base, projectionCapability: 'unknown' })).toBe(false);
+ });
+
+ it('旧被控端字段缺省时保留 running + last-input 兼容兜底', () => {
+ expect(isAutoResumeRowInFlight({ ...base, projectionCapability: 'legacy' })).toBe(true);
+ });
+
+ it('旧端兼容兜底仍要求会话在跑且该行是最后一条非 steer 输入', () => {
+ expect(
+ isAutoResumeRowInFlight({
+ ...base,
+ projectionCapability: 'legacy',
+ sessionRunning: false,
+ }),
+ ).toBe(false);
+ expect(
+ isAutoResumeRowInFlight({
+ ...base,
+ projectionCapability: 'legacy',
+ isLastUserInput: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
index 7422f310b6..4a6fdf5312 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
@@ -60,6 +60,11 @@ import * as messageService from '@/lib/messageService';
import type { Message } from '@/lib/ccAgent.types';
import { CONTINUE_AFTER_ERROR_PROMPT } from '../../shared/interruptedTurn.js';
+const inputStop = vi.fn(async () => projection({ queuePaused: false }));
+const inputGetProjection = vi.fn<() => Promise<unknown>>(async () =>
+ Promise.reject(new Error('n/a in test')),
+);
+
let inputProjectionCb: ((projection: unknown) => void) | null = null;
function makeElectronApiStub() {
@@ -77,7 +82,8 @@ function makeElectronApiStub() {
onInteractionRequest: fanOut(),
onInteractionDismissed: fanOut(),
input: {
- getProjection: vi.fn(async () => Promise.reject(new Error('n/a in test'))),
+ getProjection: inputGetProjection,
+ stop: inputStop,
},
},
localDb: { messages: { onCreated: fanOut() } },
@@ -101,6 +107,15 @@ function serverMessage(over: Partial<Message>): Message {
}
const flush = () => new Promise((r) => setTimeout(r, 0));
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
const SID = 'auto-resume-card-session';
const PENDING_CARD_ID = '__auto_resume_pending__';
const PENDING_INFO = {
@@ -121,6 +136,8 @@ function projection(over: Record<string, unknown> = {}) {
queueInteractionLocks: [],
queueEditLocks: [],
queueAbortPending: false,
+ continuationInFlightClientId: null,
+ continuationTurnClientId: null,
error: null,
recovery: null,
errorRetryText: null,
@@ -129,6 +146,12 @@ function projection(over: Record<string, unknown> = {}) {
};
}
+/** 旧被控端 wire 形状:字段完全不存在;不能用显式 undefined 伪装(own property 仍存在)。 */
+function legacyProjection(over: Record<string, unknown> = {}) {
+ const { continuationTurnClientId: _unsupported, ...legacy } = projection(over);
+ return legacy;
+}
+
describe('mapServerMessages auto-resume 分隔线', () => {
beforeEach(() => {
(globalThis as { window?: unknown }).window = { electronAPI: makeElectronApiStub() };
@@ -308,6 +331,98 @@ describe('applyInputProjection 自愈进行中提示', () => {
});
});
+// Main now owns the vendor-turn continuation identity; Renderer mirrors it without a sticky seen marker.
+describe('续跑边界投影能力与 vendor turn owner', () => {
+ beforeEach(() => {
+ (globalThis as { window?: unknown }).window = { electronAPI: makeElectronApiStub() };
+ makerChatStore.initGlobalListeners();
+ });
+
+ afterEach(() => {
+ makerChatStore.purgeSession(SID);
+ });
+
+ it('尚未收到投影时 capability=unknown,owner 为 null', () => {
+ const snap = makerChatStore.getSnapshot(SID);
+ expect(snap.continuationInFlightProjectionCapability).toBe('unknown');
+ expect(snap.continuationTurnClientId).toBeNull();
+ });
+
+ it('新版显式 null 与非空 owner 都标记 supported,并原样镜像', () => {
+ inputProjectionCb!(projection());
+ let snap = makerChatStore.getSnapshot(SID);
+ expect(snap.continuationInFlightProjectionCapability).toBe('supported');
+ expect(snap.continuationTurnClientId).toBeNull();
+
+ inputProjectionCb!(projection({ continuationTurnClientId: 'resume-1' }));
+ snap = makerChatStore.getSnapshot(SID);
+ expect(snap.continuationInFlightProjectionCapability).toBe('supported');
+ expect(snap.continuationTurnClientId).toBe('resume-1');
+ });
+
+ it('owner 变回 null 时同步清除,不保留跨 turn 记忆', () => {
+ inputProjectionCb!(projection({ continuationTurnClientId: 'resume-1' }));
+ inputProjectionCb!(projection({ continuationTurnClientId: null }));
+ const snap = makerChatStore.getSnapshot(SID);
+ expect(snap.continuationTurnClientId).toBeNull();
+ });
+
+ it('字段完全缺省(旧被控端)→ capability=legacy', () => {
+ inputProjectionCb!(legacyProjection());
+ const snap = makerChatStore.getSnapshot(SID);
+ expect(snap.continuationInFlightProjectionCapability).toBe('legacy');
+ expect(snap.continuationTurnClientId).toBeNull();
+ });
+
+ it('同一会话的被控端升级后,显式字段会从 legacy 前进到 supported', () => {
+ inputProjectionCb!(legacyProjection());
+ inputProjectionCb!(projection({ continuationTurnClientId: null }));
+ expect(makerChatStore.getSnapshot(SID).continuationInFlightProjectionCapability).toBe(
+ 'supported',
+ );
+ });
+
+ it('done 终态清 owner后,迟到旧 projection 不能重新点亮转圈', async () => {
+ const staleQuery = deferred<unknown>();
+ inputGetProjection.mockImplementationOnce(() => staleQuery.promise);
+
+ inputProjectionCb!(projection({ continuationTurnClientId: 'resume-1' }));
+ makerChatStore.ensureInitialMessages(SID);
+ makerChatStore.__applyStreamEventForTest(SID, {
+ sessionId: SID,
+ type: 'done',
+ data: {},
+ } as CCAgentStreamEvent);
+ expect(makerChatStore.getSnapshot(SID).continuationTurnClientId).toBeNull();
+
+ staleQuery.resolve(projection({ continuationTurnClientId: 'resume-stale' }));
+ await flush();
+ expect(makerChatStore.getSnapshot(SID).continuationTurnClientId).toBeNull();
+ });
+
+ it('Stop 立即清除续跑 owner,迟到旧 projection 不能重新点亮转圈', async () => {
+ const staleQuery = deferred<unknown>();
+ inputGetProjection.mockImplementationOnce(() => staleQuery.promise);
+
+ // 先用普通 projection 建立 owner,再发起悬挂查询;这样测试不会依靠查询之后的
+ // push 顺带推进 epoch,必须由 Stop 自己同步作废该查询。
+ inputProjectionCb!(projection({ continuationTurnClientId: 'resume-1' }));
+ makerChatStore.ensureInitialMessages(SID);
+ expect(makerChatStore.getSnapshot(SID).continuationTurnClientId).toBe('resume-1');
+
+ inputStop.mockResolvedValueOnce(projection({ queueExpanded: true }));
+ makerChatStore.stopSession(SID);
+ expect(makerChatStore.getSnapshot(SID).continuationTurnClientId).toBeNull();
+
+ staleQuery.resolve(projection({ continuationTurnClientId: 'resume-stale' }));
+ await flush();
+ const snapshot = makerChatStore.getSnapshot(SID);
+ expect(snapshot.continuationTurnClientId).toBeNull();
+ // Stop 自己的响应属于推进后的新 authority 代际,不能被一并误杀。
+ expect(snapshot.queueExpanded).toBe(true);
+ });
+});
+
describe('同一次中断事件的多次重连折叠成一行', () => {
beforeEach(() => {
(globalThis as { window?: unknown }).window = { electronAPI: makeElectronApiStub() };
diff --git a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
index 1cb18ff58e..0f3a494f75 100644
--- a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
@@ -76,6 +76,8 @@ const state = (overrides: Partial<SessionChatState> = {}): SessionChatState => (
errorRetryText: null,
credentialSwitchWait: null,
continuationInFlightClientId: null,
+ continuationTurnClientId: null,
+ continuationInFlightProjectionCapability: 'unknown',
isLoadingMore: false,
hasMoreMessages: false,
isFirstMessage: false,
diff --git a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
index 8e31abfa9d..156820c26b 100644
--- a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
+++ b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
@@ -28,6 +28,7 @@ import { makerChatStore } from '@/lib/makerChatStore';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
const DEVICE_ID = 'dev-A';
+const DEVICE_B_ID = 'dev-B';
let n = 0;
const sid = () => `reconcile-${n++}`;
type RemotePush = { deviceId: string; channel: string; payload: unknown };
@@ -62,6 +63,8 @@ let remoteList: Message[] = [];
let remoteListResolver: ((args: unknown[]) => Message[] | Promise<Message[]>) | null = null;
/** 被控端经隧道返回的 around 窗口(local-db:messages:around-client-id):搜索跳转用。 */
let remoteAround: Message[] = [];
+let remoteProjectionResult: Promise<unknown> | null = null;
+let remoteExpandedResult: Promise<unknown> | null = null;
const invoke = vi.fn(async (_deviceId: string, channel: string, _args: unknown[]) => {
if (channel === 'local-db:messages:list') return remoteListResolver?.(_args) ?? remoteList;
if (channel === 'local-db:messages:around-client-id') return remoteAround;
@@ -69,8 +72,13 @@ const invoke = vi.fn(async (_deviceId: string, channel: string, _args: unknown[]
return { agentKind: 'cc', remoteHostId: null, sdkSessionId: null, fastMode: false, contextTokens: 0, contextWindow: 0, totalCostUsd: 0 };
}
if (channel === 'maker:input:get-projection') {
+ if (remoteProjectionResult) return remoteProjectionResult;
return { sessionId: _args[0], pendingQueue: [], steeringQueueClientIds: [], queuePaused: false, queueExpanded: false, queueInteractionLocks: [], queueEditLocks: [], queueAbortPending: false, error: null, recovery: null, errorRetryText: null };
}
+ if (channel === 'maker:input:set-expanded') {
+ if (remoteExpandedResult) return remoteExpandedResult;
+ return { sessionId: _args[0], pendingQueue: [], steeringQueueClientIds: [], queuePaused: false, queueExpanded: Boolean(_args[1]), queueInteractionLocks: [], queueEditLocks: [], queueAbortPending: false, continuationTurnClientId: null, error: null, recovery: null, errorRetryText: null };
+ }
return null;
});
@@ -135,6 +143,8 @@ beforeEach(() => {
remoteList = [];
remoteListResolver = null;
remoteAround = [];
+ remoteProjectionResult = null;
+ remoteExpandedResult = null;
invoke.mockClear();
});
@@ -146,6 +156,292 @@ afterEach(() => {
});
describe('makerChatStore.reconcileRemoteMessages', () => {
+ it('丢弃来源漂移前设备发来的旧 input projection push', async () => {
+ const s = sid();
+ makerChatStore.initGlobalListeners();
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s }] as never);
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-a',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('owner-a');
+
+ remoteProjectsStore.setDeviceSessions(DEVICE_B_ID, 'Mac B', [{ id: s }] as never);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', []);
+ expect(remoteProjectsStore.getSessionDeviceId(s)).toBe(DEVICE_B_ID);
+
+ remotePush?.({
+ deviceId: DEVICE_B_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-b',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('owner-b');
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: null,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('owner-b');
+ });
+
+ it('丢弃 origin 漂移前旧设备返回的直接操作 projection', async () => {
+ const s = sid();
+ const oldOperation = deferred<unknown>();
+ remoteExpandedResult = oldOperation.promise;
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s }] as never);
+ makerChatStore.initGlobalListeners();
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-a',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+
+ makerChatStore.setQueueExpanded(s, true);
+ await flush();
+ expect(invoke).toHaveBeenCalledWith(
+ DEVICE_ID,
+ 'maker:input:set-expanded',
+ [s, true],
+ );
+
+ remoteProjectsStore.setDeviceSessions(DEVICE_B_ID, 'Mac B', [{ id: s }] as never);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', []);
+ remotePush?.({
+ deviceId: DEVICE_B_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-b',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+
+ oldOperation.resolve({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: true,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-a-stale',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ await flush();
+
+ const snapshot = makerChatStore.getSnapshot(s);
+ expect(snapshot.continuationTurnClientId).toBe('owner-b');
+ expect(snapshot.queueExpanded).toBe(false);
+ });
+
+ it('终态之后丢弃此前发出的同源直接操作 projection', async () => {
+ const s = sid();
+ const oldOperation = deferred<unknown>();
+ remoteExpandedResult = oldOperation.promise;
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s }] as never);
+ makerChatStore.initGlobalListeners();
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-live',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+ makerChatStore.setQueueExpanded(s, true);
+ await flush();
+
+ makerChatStore.__applyStreamEventForTest(s, {
+ sessionId: s,
+ type: 'done',
+ data: {},
+ } as CCAgentStreamEvent);
+ oldOperation.resolve({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: true,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-stale',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ await flush();
+
+ const snapshot = makerChatStore.getSnapshot(s);
+ expect(snapshot.continuationTurnClientId).toBeNull();
+ expect(snapshot.queueExpanded).toBe(false);
+ });
+
+ it('origin 切换后立即清除旧设备 owner 并退回 unknown', async () => {
+ const s = sid();
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s }] as never);
+ makerChatStore.initGlobalListeners();
+ // 避免 origin 变更自动触发的新来源查询立即返回 legacy 投影,覆盖待验证的
+ // 中间 fail-closed 状态;真实 B 投影到达后的升级已有独立用例覆盖。
+ remoteProjectionResult = new Promise(() => {});
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-a',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('owner-a');
+
+ remoteProjectsStore.setDeviceSessions(DEVICE_B_ID, 'Mac B', [{ id: s }] as never);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', []);
+ await flush();
+
+ const snapshot = makerChatStore.getSnapshot(s);
+ expect(snapshot.continuationTurnClientId).toBeNull();
+ expect(snapshot.continuationInFlightProjectionCapability).toBe('unknown');
+ });
+
+ it('同源权威 projection push 到达后丢弃已在途旧查询', async () => {
+ const s = sid();
+ const oldProjection = deferred<unknown>();
+ remoteProjectionResult = oldProjection.promise;
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s }] as never);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ makerChatStore.initGlobalListeners();
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:input:projection',
+ payload: {
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-new',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('owner-new');
+
+ oldProjection.resolve({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'owner-old',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ await flush();
+
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('owner-new');
+ });
+
it('remote stall watchdog only counts heavy session pushes, not lightweight activity', async () => {
const s = sid();
makerChatStore.initGlobalListeners();
diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts
index 65166b5c73..1cf255c982 100644
--- a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts
@@ -55,6 +55,7 @@ function dbMessage(sessionId: string, id: string, content: string): Message {
/** 被控端经隧道返回的真历史(deviceLink.invoke 的 local-db:messages:list 应命中)。 */
let remoteHistory: Message[] = [];
+let remoteProjectionOwner: string | null = null;
const invoke = vi.fn(async (_deviceId: string, channel: string, _args: unknown[]) => {
if (channel === 'local-db:messages:list') return remoteHistory;
if (channel === 'local-db:sessions:get') {
@@ -64,6 +65,7 @@ const invoke = vi.fn(async (_deviceId: string, channel: string, _args: unknown[]
return {
sessionId: _args[0], pendingQueue: [], steeringQueueClientIds: [], queuePaused: false,
queueExpanded: false, queueInteractionLocks: [], queueEditLocks: [], queueAbortPending: false,
+ ...(remoteProjectionOwner ? { continuationTurnClientId: remoteProjectionOwner } : {}),
error: null, recovery: null, errorRetryText: null,
};
}
@@ -99,6 +101,7 @@ function seedRemote(sessionId: string): void {
beforeEach(() => {
stubElectronApi();
remoteHistory = [];
+ remoteProjectionOwner = null;
invoke.mockClear();
});
@@ -173,4 +176,99 @@ describe('makerChatStore.reconcileOpenSessionOrigins (device-link 历史竞速)'
await flush();
expect(makerChatStore.getSnapshot(s).messages).toHaveLength(1);
});
+
+ it('purge 后丢弃此前发起的旧投影查询', async () => {
+ const s = sid();
+ let resolveLocalProjection!: (projection: unknown) => void;
+ const localProjection = new Promise((resolve) => {
+ resolveLocalProjection = resolve;
+ });
+ vi.stubGlobal('window', {
+ electronAPI: {
+ maker: {
+ input: {
+ getProjection: vi.fn().mockReturnValueOnce(localProjection),
+ },
+ },
+ deviceLink: { invoke },
+ },
+ });
+
+ makerChatStore.ensureInitialMessages(s);
+ makerChatStore.purgeSession(s);
+ resolveLocalProjection({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'stale-owner',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ await flush();
+
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBeNull();
+ });
+
+ it('来源漂移时丢弃旧投影查询,避免旧本机 null 覆盖远程续跑 owner', async () => {
+ const s = sid();
+ let resolveLocalProjection!: (projection: unknown) => void;
+ const localProjection = new Promise((resolve) => {
+ resolveLocalProjection = resolve;
+ });
+ const localGetProjection = vi
+ .fn()
+ .mockReturnValueOnce(localProjection)
+ .mockResolvedValue({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: null,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ vi.stubGlobal('window', {
+ electronAPI: {
+ maker: { input: { getProjection: localGetProjection } },
+ deviceLink: { invoke },
+ },
+ });
+
+ makerChatStore.ensureInitialMessages(s);
+ seedRemote(s);
+ remoteProjectionOwner = 'continue-owner';
+ makerChatStore.reconcileOpenSessionOrigins();
+ await flush();
+
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('continue-owner');
+
+ resolveLocalProjection({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: null,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ await flush();
+
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('continue-owner');
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts b/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts
index 9115619637..c20fc9090b 100644
--- a/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts
@@ -51,6 +51,7 @@ let n = 0;
const sid = () => `stall-${n++}`;
let onEvent: ((data: unknown) => void) | undefined;
+let onInputProjection: ((data: unknown) => void) | undefined;
let remoteList: Message[] = [];
const invoke = vi.fn(async (_deviceId: string, channel: string) => {
@@ -63,10 +64,14 @@ const invoke = vi.fn(async (_deviceId: string, channel: string) => {
function installBridge(): void {
onEvent = undefined;
+ onInputProjection = undefined;
vi.stubGlobal('window', {
electronAPI: {
maker: {
- onInputProjection: vi.fn(() => vi.fn()),
+ onInputProjection: vi.fn((cb: (data: unknown) => void) => {
+ onInputProjection = cb;
+ return vi.fn();
+ }),
input: { getProjection: vi.fn(async () => null) },
onEvent: (cb: (d: unknown) => void) => { onEvent = cb; return vi.fn(); },
onStatusChanged: vi.fn(() => vi.fn()),
@@ -136,6 +141,29 @@ describe('finalizeStuckRemoteTurn', () => {
expect(makerChatStore.getSnapshot(s)).toBe(after);
});
+ it('仅残留 continuation owner 时也清除,不被空闲早返漏掉', async () => {
+ const s = sid();
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s }] as never);
+ onInputProjection?.({
+ sessionId: s,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ continuationTurnClientId: 'resume-owner',
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ });
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBe('resume-owner');
+
+ makerChatStore.finalizeStuckRemoteTurn(s);
+ expect(makerChatStore.getSnapshot(s).continuationTurnClientId).toBeNull();
+ });
+
it('本机会话 → no-op(不收尾,isRunning 保持)', async () => {
const s = sid();
// 不注册进 remoteProjectsStore → 本机会话
diff --git a/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx b/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx
index 8d838cab04..507053db4a 100644
--- a/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/systemCardAutoResumeRow.test.tsx
@@ -72,6 +72,40 @@ describe('SystemCard auto-resume 行', () => {
expect(screen.queryByRole('separator')).toBeNull();
});
+ // 一次中断的"进行中"跨两种载体:退避那几秒是 ephemeral 行,续跑发出后交棒给落库的这一行。
+ // 交棒之后任务确实在跑(只是还没吐出第一个可见字符),此时必须继续显示成重连中 —— 否则用户
+ // 看到一个静止的「重新连接」不知道是不是还在跑(实测截图)。
+ it('未回填 + 正在飞 → 「重新连接中 N/5」,文案与退避那段连续', () => {
+ render(
+ <SystemCard
+ cardType="auto-resume"
+ data={{ error: 'API Error: Connection closed mid-response.', attempt: 1, maxAttempts: 5 }}
+ autoResumeInFlight
+ />,
+ );
+ expect(
+ screen.getByText('chat.systemCard.autoResumePending.labelWithProgress({"attempt":1,"total":5})'),
+ ).toBeTruthy();
+ expect(
+ screen.queryByText('chat.systemCard.autoResume.labelNeutral'),
+ '正在飞的时候不该显示中性静态文案',
+ ).toBeNull();
+ });
+
+ it('已回填时 inFlight 不参与:终态优先,仍定格 ✓ / ✗', () => {
+ render(
+ <SystemCard
+ cardType="auto-resume"
+ data={{ error: 'boom', attempt: 2, maxAttempts: 5, outcome: 'succeeded' }}
+ autoResumeInFlight
+ />,
+ );
+ expect(screen.getByText('chat.systemCard.autoResume.label')).toBeTruthy();
+ expect(
+ screen.queryByText('chat.systemCard.autoResumePending.labelWithProgress({"attempt":2,"total":5})'),
+ ).toBeNull();
+ });
+
it('带中断信息但 outcome 未回填 → 中性文案(落库记录永不显示"进行中",不变量 I6)', () => {
render(
<SystemCard cardType="auto-resume" data={{ error: 'socket hang up', attempt: 1, maxAttempts: 5 }} />,
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index b5757759f9..2de837ecb1 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -36,7 +36,11 @@ import {
isDeliveryProseText,
} from '@cindy/maker-shared/message-render';
-import type { AgentTaskUpdate, ChatMessage } from '@/hooks/useCCAgentChat';
+import type {
+ AgentTaskUpdate,
+ ChatMessage,
+ ContinuationInFlightProjectionCapability,
+} from '@/hooks/useCCAgentChat';
import { Spinner } from '@/components/ui/spinner';
import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';
import type { KnownLocalFileRef } from '@/lib/localPathResolver';
@@ -222,6 +226,10 @@ interface MessageStreamProps {
* state via useExpandedBlockMemory). The session-level "is streaming"
* state lives on each ChatMessage's own `isStreaming` field instead. */
isSessionStreaming?: boolean;
+ /** 当前 vendor turn 的续跑发起项 clientId;steer 顶替 activeTurn 后仍保持。 */
+ continuationTurnClientId?: string | null;
+ /** 旧被控端缺省该字段时才启用兼容兜底;unknown 在首个投影前 fail closed。 */
+ continuationInFlightProjectionCapability?: ContinuationInFlightProjectionCapability;
/** F-SYNC-2: callback to load older messages */
onLoadMore?: () => void;
isLoadingMore?: boolean;
@@ -553,6 +561,51 @@ export function findLastUserMessageClientId(messages: readonly ChatMessage[]): s
return null;
}
+/**
+ * 最后一条「用户侧输入」的 clientId —— **含**合成行(自动续跑指令本身)。
+ *
+ * 与上面的 `findLastUserMessageClientId` 的区别就在这里:那份服务于「编辑最后一条消息」
+ * 这个**可见** affordance,刻意跳过渲染成 null 的合成行;本份要回答的是「此刻正在跑的
+ * 这个 turn 是不是自动续跑发起的」——合成行恰恰是那个 turn 的发起者,跳过就答不了。
+ *
+ * 用途:自愈重连行判断自己是不是"仍在飞"。用户在续跑之后又自己发了消息时,最后一条用户
+ * 侧输入就换成他那条,旧的重连行随之停转(正在跑的已经是另一个 turn 了)。
+ */
+export function findLastUserInputClientId(messages: readonly ChatMessage[]): string | null {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ // **插话(`delivery === 'steer'`)不算新 turn 的发起者** —— 它是同一个正在跑的 turn 内
+ // 的追加输入。算进来的话,用户在自愈 turn 里插一句,正在跑的重连行会立刻被"夺走归属"、
+ // 提前停转退回静态(codex P2 / greptile P1)。本文件里其它 turn 边界判断(见上方
+ // `hasFollowingUserTurn` 等)也都显式排除 steer,此处保持一致。
+ //
+ // 首选判据直接使用 main 投影的 vendor-turn owner;旧被控端缺省 owner 字段时,
+ // 才由下面的兼容分支按最后一条非 steer 用户输入兜底。
+ if (messages[i].role === 'user' && messages[i].delivery !== 'steer') {
+ return messages[i].clientId;
+ }
+ }
+ return null;
+}
+
+/**
+ * 自愈落库行是否仍属于当前运行中的续跑 turn。
+ *
+ * 新端以 main 持有的 vendor-turn owner 做精确关联;只有 wire 上确实缺省 owner 字段的旧
+ * 被控端才恢复历史启发式。旧端无法区分自动续跑与不落 user 行的 Goal turn,这是协议信息
+ * 不足时的兼容降级,不能扩散到 supported / unknown 两种状态。
+ */
+export function isAutoResumeRowInFlight(args: {
+ isContinuationTurnOwner: boolean;
+ sessionRunning: boolean;
+ isLastUserInput: boolean;
+ projectionCapability: ContinuationInFlightProjectionCapability;
+}): boolean {
+ return (
+ args.isContinuationTurnOwner ||
+ (args.projectionCapability === 'legacy' && args.sessionRunning && args.isLastUserInput)
+ );
+}
+
export function shouldBlockAssistantFork(
isSessionStreaming: boolean,
message: ChatMessage,
@@ -1999,6 +2052,12 @@ function renderWorkGroupChild(
isSessionStreaming: boolean;
firstUserMessageClientId: string | null;
lastUserMessageClientId: string | null;
+ /** 含合成行的最后一条用户侧输入(自愈重连行判断"仍在飞"的兜底判据)。 */
+ lastUserInputClientId: string | null;
+ /** 当前 vendor turn 的续跑 owner clientId。 */
+ continuationTurnClientId: string | null;
+ /** 旧端缺省 owner 字段时才启用兼容兜底。 */
+ continuationInFlightProjectionCapability: ContinuationInFlightProjectionCapability;
localFileRefs: readonly KnownLocalFileRef[];
singleResultMap: Map<string, string>;
assistantsWithFollowingUserBoundary: ReadonlySet<string>;
@@ -2040,6 +2099,9 @@ function renderWorkGroupChild(
assistantIsTurnFinal={props.turnFinalAssistantClientIds.has(item.message.clientId)}
isFirstUserMessage={item.message.clientId === props.firstUserMessageClientId}
isLastUserMessage={item.message.clientId === props.lastUserMessageClientId}
+ isLastUserInput={item.message.clientId === props.lastUserInputClientId}
+ isContinuationTurnOwner={item.message.clientId === props.continuationTurnClientId}
+ continuationInFlightProjectionCapability={props.continuationInFlightProjectionCapability}
localFileRefs={props.localFileRefs}
/>
);
@@ -2139,6 +2201,8 @@ export function MessageStream({
messages,
taskUpdates,
isSessionStreaming = false,
+ continuationTurnClientId = null,
+ continuationInFlightProjectionCapability = 'unknown',
onLoadMore,
isLoadingMore,
hasMoreMessages,
@@ -3368,6 +3432,8 @@ export function MessageStream({
// + 重发,更早的消息会连带丢弃后续轮次,v1 不开放)。与 first 同理用全量
// messages 判定,不受窗口分页影响。
const lastUserMessageClientId = useMemo(() => findLastUserMessageClientId(messages), [messages]);
+ // 含合成行的"最后一条用户侧输入":自愈重连行据此判断自己是不是仍在飞(见 helper 注释)。
+ const lastUserInputClientId = useMemo(() => findLastUserInputClientId(messages), [messages]);
// error-tail-banner:尾部未忽略的 error 行由输入框上方红条独家承载,流内需要
// 知道"是不是最后一条"来跳过重复渲染。
@@ -3523,6 +3589,9 @@ export function MessageStream({
isSessionStreaming,
firstUserMessageClientId,
lastUserMessageClientId,
+ lastUserInputClientId,
+ continuationTurnClientId,
+ continuationInFlightProjectionCapability,
localFileRefs,
singleResultMap,
assistantsWithFollowingUserBoundary,
@@ -3642,6 +3711,11 @@ export function MessageStream({
assistantIsTurnFinal={turnFinalAssistantClientIds.has(msg.clientId)}
isFirstUserMessage={msg.clientId === firstUserMessageClientId}
isLastUserMessage={msg.clientId === lastUserMessageClientId}
+ isLastUserInput={msg.clientId === lastUserInputClientId}
+ isContinuationTurnOwner={msg.clientId === continuationTurnClientId}
+ continuationInFlightProjectionCapability={
+ continuationInFlightProjectionCapability
+ }
isLastMessage={msg.clientId === lastMessageClientId}
localFileRefs={localFileRefs}
/>
@@ -3713,6 +3787,9 @@ const MessageItem = memo(function MessageItem({
assistantIsTurnFinal,
isFirstUserMessage,
isLastUserMessage,
+ isLastUserInput,
+ isContinuationTurnOwner,
+ continuationInFlightProjectionCapability,
isLastMessage,
localFileRefs,
}: {
@@ -3745,6 +3822,16 @@ const MessageItem = memo(function MessageItem({
/** True iff this message is the last user message in the full list —
* edit-last-message: gates the Edit (pencil) entry in UserMessage. */
isLastUserMessage?: boolean;
+ /**
+ * True iff this message is the last **user-side input** in the full list, synthetic rows
+ * included(见 `findLastUserInputClientId`)。自愈重连行用它 + `sessionRunning` 判断
+ * 「此刻正在跑的 turn 是不是我发起的」,从而决定要不要显示成"重新连接中"。
+ */
+ isLastUserInput?: boolean;
+ /** 当前 vendor turn 的续跑 owner 是否就是这条消息。 */
+ isContinuationTurnOwner?: boolean;
+ /** 当前投影对精确续跑边界字段的支持状态;legacy 才允许启用旧端兼容兜底。 */
+ continuationInFlightProjectionCapability?: ContinuationInFlightProjectionCapability;
/** True iff this message is the last message in the full list —
* error-tail-banner: a trailing un-dismissed error row is rendered by the
* actionable banner above the composer instead of an inline card. */
@@ -3759,6 +3846,14 @@ const MessageItem = memo(function MessageItem({
cardType={message.systemCardType}
data={message.systemCardData}
sessionId={sessionId}
+ // 「这条自愈记录此刻真的在飞吗」:main 持有 vendor-turn owner,只有旧端缺省该字段时
+ // 才回落到兼容启发式;supported / unknown 不再依赖 Renderer 的 sticky memory。
+ autoResumeInFlight={isAutoResumeRowInFlight({
+ isContinuationTurnOwner: isContinuationTurnOwner === true,
+ sessionRunning: sessionRunning === true,
+ isLastUserInput: isLastUserInput === true,
+ projectionCapability: continuationInFlightProjectionCapability ?? 'unknown',
+ })}
/>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index 03795cbe17..215094a160 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -17,6 +17,11 @@ import { LearnStatusCard } from '@/features/learn/LearnStatusCard';
interface SystemCardProps {
cardType: 'help' | 'cost' | 'context' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'learn' | 'auto-resume' | 'auto-resume-pending' | 'agent-switch';
data?: Record<string, unknown>;
+ /**
+ * 这条自愈记录此刻是否真的在飞(会话有在跑的 turn,且它就是那个 turn 的发起者)。
+ * 由 MessageStream 注入,判据见那里的注释。只影响 `auto-resume` 卡。
+ */
+ autoResumeInFlight?: boolean;
/** 卡片所在消息流的 sessionId(MessageStream 注入)。learn 卡按它路由 / 判定
* 归属会话 —— 嵌入式视图(Orca split pane)里 URL 参数是 lead 而非本 pane,
* 不能用 useParams(Codex review #548)。 */
@@ -844,23 +849,36 @@ function AutoResumeSeparator() {
function AutoResumeActionRow({
state,
info,
+ inFlight,
}: {
/**
* `live` = 退避窗口里的 ephemeral 行(一定是"正在重连")。
- * `recorded` = 落库的那条续跑记录,结果看 `info.outcome`:
- * 缺省仍是"重新连接中"(已经发出去、还没等到产出),succeeded / failed 才定格。
+ * `recorded` = 落库的那条续跑记录,结果看 `info.outcome` 与 `inFlight`。
*/
state: 'live' | 'recorded';
info: AutoResumeCardInfo;
+ /**
+ * 落库记录**此刻是否真的在飞**:会话有在跑的 turn,且这条续跑指令就是那个 turn 的
+ * 发起者(判据在 MessageStream)。为真且结果还没回填时,这一行按"正在重连"呈现。
+ */
+ inFlight?: boolean;
}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const hasProgress = info.attempt !== undefined && info.maxAttempts !== undefined;
- // **只有 live 行才会转圈。** 落库记录一律静态:`outcome` 未回填只说明"结果还没回来"
- // (app 在回填前退出就永远回不来了),不代表此刻真的在重连 —— 会话重开后让一堆历史
- // 记录一直转圈是假的。未回填时用中性文案「重新连接」(无时态):它同时覆盖"续跑刚发出、
- // 还在等模型响应"那几秒和"结果永远不会来了"两种情形,两边读起来都成立。
- const live = state === 'live';
+ // **转圈的判据是"此刻真的有 turn 在跑",不是"是不是 ephemeral 行"。**
+ //
+ // 一次中断的进行中状态跨两种载体:退避那 3–20 秒是 ephemeral 行(state='live'),续跑
+ // 指令发出去之后交棒给落库的这一行 —— 那时任务确实在跑,只是还没吐出第一个可见字符。
+ // 早先把"落库行"一律做成静态,导致转圈在交棒那一刻断掉,用户看到一个静止的「重新连接」
+ // 却不知道是不是还在跑(实测截图)。
+ //
+ // 但也**不能**只看"结果未回填":app 在回填前退出的话 outcome 永远回不来,会话重开后
+ // 一堆历史记录会集体转圈,那是假的。所以由 `inFlight` 把两者分开:
+ // - 未回填 + 正在飞 → 「重新连接中 N/5」+ 转圈(与退避那段文案连续,不跳变)
+ // - 未回填 + 没在飞 → 静态 ⟳ +「重新连接」(中性、无时态,不骗人)
+ // - 已回填 → ✓ / ✗ 定格,`inFlight` 不参与(终态优先)
+ const live = state === 'live' || (inFlight === true && info.outcome === undefined);
const outcome = live ? undefined : info.outcome;
const label = live
? hasProgress
@@ -1081,7 +1099,7 @@ function AgentSwitchCard({ data }: { data?: Record<string, unknown> }) {
);
}
-export function SystemCard({ cardType, data, sessionId }: SystemCardProps) {
+export function SystemCard({ cardType, data, sessionId, autoResumeInFlight }: SystemCardProps) {
switch (cardType) {
case 'help':
return <HelpCard data={data} />;
@@ -1106,7 +1124,7 @@ export function SystemCard({ cardType, data, sessionId }: SystemCardProps) {
// 的「已自动继续」分隔条 —— 后者保持原形态原文案,不被重连三态改写(copilot review)。
const info = readAutoResumeInfo(data);
return hasInterruptionContext(info) ? (
- <AutoResumeActionRow state="recorded" info={info} />
+ <AutoResumeActionRow state="recorded" info={info} inFlight={autoResumeInFlight === true} />
) : (
<AutoResumeSeparator />
);
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index d9377d3734..d9535126a8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1195,6 +1195,8 @@ export function CCAgentSessionView({
errorRetryText,
credentialSwitchWait,
continuationInFlightClientId,
+ continuationTurnClientId,
+ continuationInFlightProjectionCapability,
loadOlderMessages,
isLoadingMore,
hasMoreMessages,
@@ -3019,6 +3021,8 @@ export function CCAgentSessionView({
messages={messages}
taskUpdates={taskUpdates}
isSessionStreaming={isStreaming}
+ continuationTurnClientId={continuationTurnClientId}
+ continuationInFlightProjectionCapability={continuationInFlightProjectionCapability}
onLoadMore={loadOlderMessages}
isLoadingMore={isLoadingMore}
hasMoreMessages={hasMoreMessages}
diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
index fb2e219bf0..03ee5b57a4 100644
--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
@@ -34,6 +34,7 @@ import {
type AskUserDraft,
type AskUserViewerState,
type ChatMessage,
+ type ContinuationInFlightProjectionCapability,
type PendingPermission,
type PendingAskUser,
type PendingPluginSetup,
@@ -64,6 +65,7 @@ export type {
AskUserDraft,
AskUserViewerState,
ChatMessage,
+ ContinuationInFlightProjectionCapability,
PendingPermission,
PendingAskUser,
PendingPlanReview,
@@ -184,6 +186,10 @@ interface UseCCAgentChatReturn {
credentialSwitchWait: { clientId?: string; blockedBySessionIds: string[] } | null;
/** 已离队、正在 coordinator dispatch/turn 边界内的 Continue clientId。 */
continuationInFlightClientId: string | null;
+ /** 当前 vendor turn 的续跑发起项 clientId,steer 后及 Renderer 重载仍保持。 */
+ continuationTurnClientId: string | null;
+ /** 续跑边界投影能力;legacy 时保留旧被控端的兼容兜底。 */
+ continuationInFlightProjectionCapability: ContinuationInFlightProjectionCapability;
/** F-SYNC-2: Load older messages (prepend to top) */
loadOlderMessages: () => void;
isLoadingMore: boolean;
@@ -833,6 +839,9 @@ export function useCCAgentChat(
errorRetryText: lightState.errorRetryText,
credentialSwitchWait: lightState.credentialSwitchWait,
continuationInFlightClientId: lightState.continuationInFlightClientId,
+ continuationTurnClientId: lightState.continuationTurnClientId,
+ continuationInFlightProjectionCapability:
+ lightState.continuationInFlightProjectionCapability,
loadOlderMessages,
isLoadingMore: lightState.isLoadingMore,
hasMoreMessages: lightState.hasMoreMessages,
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 945e38380a..3269e8357b 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -75,6 +75,7 @@ import {
aroundMessagesByClientIdFor,
dismissErrorMessageFor,
isRemoteSession,
+ type RoutableMaker,
} from '@/lib/makerTransport';
import {
remoteProjectsStore,
@@ -737,6 +738,8 @@ export interface AgentSwitchIntentRecord {
fastMode?: boolean;
}
+export type ContinuationInFlightProjectionCapability = 'unknown' | 'supported' | 'legacy';
+
export interface SessionChatState {
/**
* 该 session 用哪个 agent (Claude / Codex)。 sendMessage 据此走 maker.send 时
@@ -820,6 +823,18 @@ export interface SessionChatState {
* 保持熄灭,同时不影响用户取消仍在队列中的 Continue 后恢复横幅。
*/
continuationInFlightClientId: string | null;
+ /**
+ * 当前 vendor turn 的续跑发起项 clientId。它由 main 绑定在 ActiveTurn 上,steer 顶替
+ * activeTurn 后仍保持原值,因此 Renderer 重载 / 新窗口也能恢复归属。
+ */
+ continuationTurnClientId: string | null;
+ /**
+ * 当前 projection 是否支持 `continuationTurnClientId`:
+ * unknown = 尚未收到投影;supported = 字段显式存在(值可以是 null);
+ * legacy = 旧被控端完全缺省字段,只能回落到 running + 最后一条输入的兼容判据。
+ * 不能用 `?? null` 推断:新版显式 null 需要挡住无关 Goal turn,旧版缺省需要兼容。
+ */
+ continuationInFlightProjectionCapability: ContinuationInFlightProjectionCapability;
isLoadingMore: boolean;
hasMoreMessages: boolean;
/**
@@ -1015,6 +1030,8 @@ export type SessionChatLightState = Pick<
| 'errorRetryText'
| 'credentialSwitchWait'
| 'continuationInFlightClientId'
+ | 'continuationTurnClientId'
+ | 'continuationInFlightProjectionCapability'
| 'isLoadingMore'
| 'hasMoreMessages'
| 'isFirstMessage'
@@ -1066,6 +1083,8 @@ function createInitialState(): SessionChatState {
errorRetryText: null,
credentialSwitchWait: null,
continuationInFlightClientId: null,
+ continuationTurnClientId: null,
+ continuationInFlightProjectionCapability: 'unknown',
isLoadingMore: false,
hasMoreMessages: true,
historyWindowHasIsland: false,
@@ -1130,6 +1149,8 @@ export const EMPTY_SESSION_STATE: SessionChatState = Object.freeze({
errorRetryText: null,
credentialSwitchWait: null,
continuationInFlightClientId: null,
+ continuationTurnClientId: null,
+ continuationInFlightProjectionCapability: 'unknown',
isLoadingMore: false,
hasMoreMessages: false,
historyWindowHasIsland: false,
@@ -1271,6 +1292,7 @@ function _purgeSession(sessionId: string): void {
// 代际递增(bump 而非 delete,原因见 _messagesEpoch 注释):作废 in-flight 翻页,
// 避免其提交把旧窗口 merge 进 purge 后重建的空 slice。
bumpMessagesEpoch(sessionId);
+ invalidateInputProjectionRequests(sessionId);
sessions.delete(sessionId);
// 状态快照同步失效:该会话若有 running / pending / 待投递 transition 条目,
// 不能在缓存里残留(purge 不走 setState,需单独置位)。
@@ -1551,8 +1573,21 @@ function shallowEqualRecord(
const AUTO_RESUME_PENDING_CLIENT_ID = '__auto_resume_pending__';
-function applyInputProjection(projection: AgentInputProjection): void {
+function applyInputProjection(
+ projection: AgentInputProjection,
+ opts: { supersedeQueries?: boolean } = {},
+): void {
if (!projection.sessionId) return;
+ if (opts.supersedeQueries !== false) {
+ supersedeInputProjectionRequests(projection.sessionId);
+ }
+ // wire 上「字段缺省」就是旧被控端的能力信号;新版没有续跑项时也会显式发 null。
+ // 必须在 `?? null` 归一化前按 own property 读取,不能让 undefined/null 混淆版本。
+ const continuationInFlightProjectionCapability: ContinuationInFlightProjectionCapability =
+ Object.prototype.hasOwnProperty.call(projection, 'continuationTurnClientId')
+ ? 'supported'
+ : 'legacy';
+ const projectedContinuationTurnClientId = projection.continuationTurnClientId ?? null;
setState(projection.sessionId, (s) => {
// Only trigger if the retried message is still stuck in the pending queue:
// projection.error is queue-level (string | null, no clientId), so we correlate
@@ -1654,6 +1689,8 @@ function applyInputProjection(projection: AgentInputProjection): void {
errorRetryText: projection.errorRetryText,
credentialSwitchWait: projection.credentialSwitchWait ?? null,
continuationInFlightClientId: projection.continuationInFlightClientId ?? null,
+ continuationTurnClientId: projectedContinuationTurnClientId,
+ continuationInFlightProjectionCapability,
...(authRetryProjectionError ? { _authRetryPersistOnProjectionError: undefined } : {}),
};
});
@@ -1669,9 +1706,15 @@ function markSessionHasUserMessage(sessionId: string): void {
function requestInputProjection(sessionId: string): void {
if (!sessionId) return;
if (typeof window === 'undefined' || !window.electronAPI?.maker?.input?.getProjection) return;
- makerApiFor(sessionId)
- .input.getProjection(sessionId)
- .then(applyInputProjection)
+ const origin = remoteProjectsStore.getSessionDeviceId(sessionId);
+ const epoch = beginInputProjectionRequest(sessionId, origin);
+ const api = makerApiFor(sessionId);
+ api.input
+ .getProjection(sessionId)
+ .then((projection) => {
+ if (!isCurrentInputProjectionRequest(sessionId, origin, epoch)) return;
+ applyInputProjection(projection, { supersedeQueries: false });
+ })
.catch((err) => log.warn('get input projection failed:', err));
}
@@ -2588,6 +2631,7 @@ export function handleStreamEvent(
errorRetryText: finalized.error ? finalized.errorRetryText : null,
pendingPermission: null,
pendingAskUser: null,
+ continuationTurnClientId: null,
// F-AUQ-MIN-5: viewerState lives with pendingAskUser — when the
// pending question is gone, reset so the next one starts expanded.
askUserViewerState: 'expanded',
@@ -2691,6 +2735,7 @@ export function handleStreamEvent(
errorRetryText: derivedRetryText ?? preservedRetryText,
isStreaming: false,
activeTurnRetryText: null,
+ continuationTurnClientId: null,
queueAbortPending: false,
streamingText: '', // MEM-4: finalizeStreamingInState intentionally keeps streamingText for
// the 'done' path to consume — reset it explicitly on error so the
@@ -3080,6 +3125,7 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
!state.messages.some((m) => m.isStreaming) &&
!state.queueAbortPending &&
state.steeringQueueClientIds.length === 0 &&
+ state.continuationTurnClientId === null &&
!state.pendingTaskWake &&
stoppedTasks === state.taskUpdates
) {
@@ -3126,6 +3172,7 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
pendingGhostGrantConfirm: null,
queueAbortPending: false,
steeringQueueClientIds: [],
+ continuationTurnClientId: null,
// session 都关了,后台任务事件流已断:running 残留任务标 stopped、唤醒桥接
// 清零,否则 running 快照(折算了后台任务)会让 spinner 永久转下去。
taskUpdates: stoppedTasks,
@@ -3223,6 +3270,7 @@ function handleStatusUpdate(
startedAt,
},
activeTurnRetryText: isTurnComplete ? null : state.activeTurnRetryText,
+ continuationTurnClientId: update.isRunning ? state.continuationTurnClientId : null,
// 新 turn 真正启动(isRunning false→true)时清掉上一轮残留的终态 error:
// coordinator 路径的 send 经 projection error:null 清横幅,但 direct send
// (scheduler / send-to-session / goal 等不走 coordinator 的路径)不发
@@ -3313,17 +3361,17 @@ function dispatchStreamEventPayload(
resolvedContent?: string,
): void {
if (!event) return;
- setState(sessionId, (s) =>
- handleStreamEvent(s, {
- sessionId,
- type: event.type,
- data: event.data,
- source: event.source,
- agentMeta: event.agentMeta as import('./ccAgent.types').CcMeta | undefined,
- persistId,
- resolvedContent,
- } as CCAgentStreamEvent),
- );
+ const streamEvent = {
+ sessionId,
+ type: event.type,
+ data: event.data,
+ source: event.source,
+ agentMeta: event.agentMeta as import('./ccAgent.types').CcMeta | undefined,
+ persistId,
+ resolvedContent,
+ } as CCAgentStreamEvent;
+ supersedeInputProjectionOnTerminalEvent(sessionId, streamEvent);
+ setState(sessionId, (s) => handleStreamEvent(s, streamEvent));
}
function clearTextDeltaFlushTimer(): void {
@@ -3661,6 +3709,9 @@ function initGlobalListeners(): void {
sessionId,
...(event.data as Record<string, unknown>),
} as CCAgentStatusUpdate;
+ if (!update.skipTurnReset && !update.isRunning) {
+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
+ }
setState(sessionId, (s) => handleStatusUpdate(s, update));
return;
}
@@ -3771,13 +3822,13 @@ function initGlobalListeners(): void {
event.data as Record<string, unknown> | null,
event.agentMeta ?? null,
);
- setState(sessionId, (s) =>
- handleStreamEvent(s, {
- sessionId,
- type: 'error',
- data: event.data,
- } as CCAgentStreamEvent),
- );
+ const terminalErrorEvent = {
+ sessionId,
+ type: 'error',
+ data: event.data,
+ } as CCAgentStreamEvent;
+ supersedeInputProjectionOnTerminalEvent(sessionId, terminalErrorEvent);
+ setState(sessionId, (s) => handleStreamEvent(s, terminalErrorEvent));
} finally {
setState(sessionId, (s) => ({ ...s, _authRetryInFlight: false }));
}
@@ -3874,14 +3925,21 @@ function initGlobalListeners(): void {
const handleMakerStatusRaw = (raw: unknown) => {
const payload = raw as { sessionId?: string; status?: string } | null;
if (!payload?.sessionId || payload.status !== 'closed') return;
+ supersedeInputProjectionRequests(payload.sessionId, { supersedeOperations: true });
flushPendingTextDelta(payload.sessionId);
setState(payload.sessionId, forceFinalizeOnSessionClosed);
};
bindIpc(window.electronAPI.maker.onStatusChanged, handleMakerStatusRaw, 'maker-status-changed');
- const handleInputProjectionRaw = (raw: unknown) => {
+ const handleInputProjectionRaw = (raw: unknown, sourceDeviceId?: string) => {
const projection = raw as AgentInputProjection | null;
if (!projection?.sessionId) return;
+ if (
+ sourceDeviceId !== undefined &&
+ remoteProjectsStore.getSessionDeviceId(projection.sessionId) !== sourceDeviceId
+ ) {
+ return;
+ }
applyInputProjection(projection);
};
bindIpc(
@@ -4297,7 +4355,8 @@ function initGlobalListeners(): void {
handleMakerStatusRaw(push.payload);
break;
case 'maker:input:projection':
- handleInputProjectionRaw(push.payload);
+ if (!push.deviceId) break;
+ handleInputProjectionRaw(push.payload, push.deviceId);
break;
case 'maker:interaction-request':
handleInteractionRequestRaw(push.payload);
@@ -4753,6 +4812,8 @@ function selectLightState(state: SessionChatState): SessionChatLightState {
errorRetryText: state.errorRetryText,
credentialSwitchWait: state.credentialSwitchWait,
continuationInFlightClientId: state.continuationInFlightClientId,
+ continuationTurnClientId: state.continuationTurnClientId,
+ continuationInFlightProjectionCapability: state.continuationInFlightProjectionCapability,
isLoadingMore: state.isLoadingMore,
hasMoreMessages: state.hasMoreMessages,
isFirstMessage: state.isFirstMessage,
@@ -4791,7 +4852,11 @@ function lightStateEquals(a: SessionChatLightState, b: SessionChatLightState): b
a.errorRetryText === b.errorRetryText &&
a.credentialSwitchWait === b.credentialSwitchWait &&
a.continuationInFlightClientId === b.continuationInFlightClientId &&
+ a.continuationTurnClientId === b.continuationTurnClientId &&
+ a.continuationInFlightProjectionCapability ===
+ b.continuationInFlightProjectionCapability &&
a.isLoadingMore === b.isLoadingMore &&
+
a.hasMoreMessages === b.hasMoreMessages &&
a.isFirstMessage === b.isFirstMessage &&
a.historyLoaded === b.historyLoaded &&
@@ -5260,6 +5325,154 @@ const _historyFetchInFlight = new Set<string>();
*/
const _historyLoadOrigin = new Map<string, string | undefined>();
+/**
+ * input projection 请求的来源与代际守卫。
+ *
+ * projection 查询可能跨过 device-link origin 切换:启动时先按本机来源发起的请求,可能在
+ * 远程来源已经接管后才返回。若无守卫,旧本机 projection 会覆盖远程 projection(尤其把
+ * continuationTurnClientId 从非空写回 null),让仍在运行的续跑行停止转圈。
+ *
+ * origin 变化时 epoch 单调递增,因此即使来源经历 A→undefined→A 的 ABA 也不会重新放行
+ * 更早请求。查询按 origin + epoch 丢弃旧响应;直接操作按 origin + authority epoch 拒绝
+ * 来源漂移或终态前发出的响应。实时 push 另在接收点按 source device 校验。
+ */
+const _inputProjectionOrigin = new Map<string, string | undefined>();
+const _inputProjectionEpoch = new Map<string, number>();
+const _inputProjectionAuthorityEpoch = new Map<string, number>();
+let _nextInputProjectionEpoch = 0;
+
+function nextInputProjectionEpoch(): number {
+ _nextInputProjectionEpoch += 1;
+ return _nextInputProjectionEpoch;
+}
+
+function supersedeInputProjectionRequests(
+ sessionId: string,
+ opts: { supersedeOperations?: boolean } = {},
+): void {
+ const origin = remoteProjectsStore.getSessionDeviceId(sessionId);
+ _inputProjectionOrigin.set(sessionId, origin);
+ const epoch = nextInputProjectionEpoch();
+ _inputProjectionEpoch.set(sessionId, epoch);
+ if (opts.supersedeOperations) {
+ _inputProjectionAuthorityEpoch.set(sessionId, epoch);
+ }
+}
+
+function invalidateInputProjectionRequests(sessionId: string): void {
+ _inputProjectionOrigin.delete(sessionId);
+ _inputProjectionEpoch.delete(sessionId);
+ // authority 代际不能 delete:pre-purge 操作可能捕获 0,delete 后回落 0 会误放行,
+ // 并通过 setState 复活已 purge 的 session。保留单调墓碑,与 messagesEpoch 同理。
+ _inputProjectionAuthorityEpoch.set(sessionId, nextInputProjectionEpoch());
+}
+
+function beginInputProjectionRequest(sessionId: string, origin: string | undefined): number {
+ _inputProjectionOrigin.set(sessionId, origin);
+ const epoch = nextInputProjectionEpoch();
+ _inputProjectionEpoch.set(sessionId, epoch);
+ return epoch;
+}
+
+function noteInputProjectionOrigin(
+ sessionId: string,
+ origin: string | undefined,
+): { epoch: number; changed: boolean } {
+ const previous = _inputProjectionOrigin.get(sessionId);
+ if (!_inputProjectionOrigin.has(sessionId) || previous !== origin) {
+ _inputProjectionOrigin.set(sessionId, origin);
+ const epoch = nextInputProjectionEpoch();
+ _inputProjectionEpoch.set(sessionId, epoch);
+ _inputProjectionAuthorityEpoch.set(sessionId, epoch);
+ return { epoch, changed: true };
+ }
+ return { epoch: _inputProjectionEpoch.get(sessionId)!, changed: false };
+}
+
+function isCurrentInputProjectionOrigin(
+ sessionId: string,
+ origin: string | undefined,
+): boolean {
+ return remoteProjectsStore.getSessionDeviceId(sessionId) === origin;
+}
+
+function isCurrentInputProjectionRequest(
+ sessionId: string,
+ origin: string | undefined,
+ epoch: number,
+): boolean {
+ return (
+ isCurrentInputProjectionOrigin(sessionId, origin) &&
+ (_inputProjectionEpoch.get(sessionId) ?? 0) === epoch
+ );
+}
+
+interface InputProjectionOperation {
+ api: RoutableMaker;
+ origin: string | undefined;
+ epoch: number;
+}
+
+/**
+ * 捕获一次会返回 projection 的操作路由。`api` 与 origin 必须在同一时刻定格:
+ * origin 漂移后重新调用 makerApiFor 会把同一业务意图错发到另一台设备。
+ * authority epoch 只由终态 / 来源切换推进;普通 push 与同源并发操作仍按响应到达顺序落地。
+ */
+function beginInputProjectionOperation(sessionId: string): InputProjectionOperation {
+ const origin = remoteProjectsStore.getSessionDeviceId(sessionId);
+ return {
+ api: makerApiFor(sessionId),
+ origin,
+ epoch: _inputProjectionAuthorityEpoch.get(sessionId) ?? 0,
+ };
+}
+
+function applyInputProjectionOperationResponse(
+ sessionId: string,
+ operation: InputProjectionOperation,
+ projection: AgentInputProjection,
+): boolean {
+ if (
+ !isCurrentInputProjectionOrigin(sessionId, operation.origin) ||
+ (_inputProjectionAuthorityEpoch.get(sessionId) ?? 0) !== operation.epoch
+ ) {
+ return false;
+ }
+ // 直接操作响应会 supersede 早先的查询;apply 的默认路径负责推进查询 epoch。
+ applyInputProjection(projection);
+ return true;
+}
+
+/**
+ * Renderer 收到权威 turn 终态时,同时作废所有此前发出的 projection 查询。
+ * reducer 本身保持纯函数;调用方在 setState 前执行这条时序屏障。
+ */
+function supersedeInputProjectionOnTerminalEvent(
+ sessionId: string,
+ event: Pick<CCAgentStreamEvent, 'type' | 'data'>,
+): void {
+ if (event.type === 'done') {
+ if ((event.data as { silentStop?: boolean } | null | undefined)?.silentStop !== true) {
+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
+ }
+ return;
+ }
+ if (event.type === 'error' && isTerminalErrorData(event.data)) {
+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
+ }
+}
+
+function runInputProjectionOperation(
+ sessionId: string,
+ invoke: (input: RoutableMaker['input']) => Promise<AgentInputProjection>,
+): Promise<{ applied: boolean; projection: AgentInputProjection }> {
+ const operation = beginInputProjectionOperation(sessionId);
+ return invoke(operation.api.input).then((projection) => ({
+ applied: applyInputProjectionOperationResponse(sessionId, operation, projection),
+ projection,
+ }));
+}
+
/**
* 会话消息切片的代际号:整体重置切片的路径递增——reloadMessages(rewind / origin
* 漂移重载)、clearSessionAfterGuard(/clear)、_purgeSession(删除 / 归档 / LRU 驱逐)、
@@ -5813,6 +6026,19 @@ function dropMessagesFromClientId(sessionId: string, clientId: string): void {
function reconcileOpenSessionOrigins(): void {
for (const sessionId of sessions.keys()) {
const current = remoteProjectsStore.getSessionDeviceId(sessionId);
+ // 即使当前来源暂时为空也要推进 projection 代际:否则 A→断连→A 的 ABA 会让
+ // 最初按 A 发起的旧查询在来源恢复后重新通过检查,覆盖恢复后的权威投影。
+ const originChange = noteInputProjectionOrigin(sessionId, current);
+ if (originChange.changed) {
+ // 来源变更后旧设备的 owner / capability 都失效。在新来源 projection 回来前
+ // fail closed,不能让 B 的历史沿用 A 的精确 owner 或 legacy 兜底。
+ setState(sessionId, (state) => ({
+ ...state,
+ continuationInFlightClientId: null,
+ continuationTurnClientId: null,
+ continuationInFlightProjectionCapability: 'unknown',
+ }));
+ }
if (current === undefined) continue;
const loaded = _historyLoadOrigin.get(sessionId);
if (current === loaded) continue;
@@ -6139,6 +6365,9 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
*/
function finalizeStuckRemoteTurn(sessionId: string): void {
if (!isRemoteSession(sessionId)) return;
+ // 看门狗确认被控端已停止 = 权威终态;在清本地 owner 前先作废所有旧查询,
+ // 防止 stall 期间悬挂的 getProjection 随后把已死 turn 重新点亮。
+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
flushPendingTextDelta(sessionId); // 收尾前把残留增量落定,避免丢最后一截文本
setState(sessionId, forceFinalizeOnSessionClosed);
}
@@ -6952,42 +7181,36 @@ function touchSessionUserSend(sessionId: string, workingDir: string, wasFirst: b
*/
function setQueueExpanded(sessionId: string, expanded: boolean): void {
if (!sessionId) return;
- makerApiFor(sessionId)
- .input.setExpanded(sessionId, expanded)
- .then(applyInputProjection)
- .catch((err) => log.warn('setQueueExpanded failed:', err));
+ runInputProjectionOperation(sessionId, (input) =>
+ input.setExpanded(sessionId, expanded),
+ ).catch((err) => log.warn('setQueueExpanded failed:', err));
}
function resumeQueue(sessionId: string): void {
if (!sessionId) return;
- makerApiFor(sessionId)
- .input.resume(sessionId)
- .then(applyInputProjection)
+ runInputProjectionOperation(sessionId, (input) => input.resume(sessionId))
.catch((err) => log.warn('resumeQueue failed:', err));
}
function setQueueInteractionLock(sessionId: string, lockId: string, locked: boolean): void {
if (!sessionId || !lockId) return;
- makerApiFor(sessionId)
- .input.setInteractionLock(sessionId, lockId, locked)
- .then(applyInputProjection)
- .catch((err) => log.warn('setQueueInteractionLock failed:', err));
+ runInputProjectionOperation(sessionId, (input) =>
+ input.setInteractionLock(sessionId, lockId, locked),
+ ).catch((err) => log.warn('setQueueInteractionLock failed:', err));
}
function setQueueEditLock(sessionId: string, clientId: string, locked: boolean): void {
if (!sessionId || !clientId) return;
- makerApiFor(sessionId)
- .input.setEditLock(sessionId, clientId, locked)
- .then(applyInputProjection)
- .catch((err) => log.warn('setQueueEditLock failed:', err));
+ runInputProjectionOperation(sessionId, (input) =>
+ input.setEditLock(sessionId, clientId, locked),
+ ).catch((err) => log.warn('setQueueEditLock failed:', err));
}
function moveQueueItem(sessionId: string, clientId: string, targetIndex: number): void {
if (!sessionId || !clientId) return;
- makerApiFor(sessionId)
- .input.move(sessionId, clientId, targetIndex)
- .then(applyInputProjection)
- .catch((err) => log.warn('moveQueueItem failed:', err));
+ runInputProjectionOperation(sessionId, (input) =>
+ input.move(sessionId, clientId, targetIndex),
+ ).catch((err) => log.warn('moveQueueItem failed:', err));
}
/**
@@ -6999,9 +7222,7 @@ function moveQueueItem(sessionId: string, clientId: string, targetIndex: number)
*/
function removeFromQueue(sessionId: string, clientId: string): void {
if (!sessionId || !clientId) return;
- makerApiFor(sessionId)
- .input.remove(sessionId, clientId)
- .then(applyInputProjection)
+ runInputProjectionOperation(sessionId, (input) => input.remove(sessionId, clientId))
.catch((err) => log.warn('removeFromQueue failed:', err));
}
@@ -7017,15 +7238,14 @@ function updateQueueItem(sessionId: string, clientId: string, newText: string):
const trimmed = newText.trim();
if (!trimmed) return;
const queued = getOrCreateState(sessionId).pendingQueue.find((q) => q.clientId === clientId);
- makerApiFor(sessionId)
- .input.updateText(
+ runInputProjectionOperation(sessionId, (input) =>
+ input.updateText(
sessionId,
clientId,
newText,
extractSessionRefs(newText, queued?.sessionRefs),
- )
- .then(applyInputProjection)
- .catch((err) => log.warn('updateQueueItem failed:', err));
+ ),
+ ).catch((err) => log.warn('updateQueueItem failed:', err));
}
/**
@@ -7347,8 +7567,9 @@ async function sendMessageCore(
);
}
- return makerApiFor(sessionId)
- .input.enqueue(sessionId, queued, { sendAtMs: Date.now() })
+ const operation = beginInputProjectionOperation(sessionId);
+ return operation.api.input
+ .enqueue(sessionId, queued, { sendAtMs: Date.now() })
.then((projection) => {
if (opts?.authRetryPersistOnProjectionError) {
setState(sessionId, (s) => ({
@@ -7359,8 +7580,10 @@ async function sendMessageCore(
},
}));
}
- applyInputProjection(projection);
- markSessionHasUserMessage(sessionId);
+ const applied = applyInputProjectionOperationResponse(sessionId, operation, projection);
+ if (applied) markSessionHasUserMessage(sessionId);
+ // RPC 已在发起时的设备上成功受理;origin 期间漂移只意味着旧 projection
+ // 不能写进当前镜像,不应向 composer 谎报发送失败并诱导用户重复发送。
return true;
})
.catch((err) => {
@@ -7407,12 +7630,11 @@ function compactSession(
// /compact 是控制 turn(上下文压缩), 与 sendUiTrigger 同口径: 显式普通执行,
// 不进计划模式、不消耗用户的一次性勾选(false 语义见 SendOptions.planMode)。
createOpts.planMode = false;
- return makerApiFor(sessionId)
- .input.compact(sessionId, createOpts, { userName: currentUserName })
- .then((projection) => {
- applyInputProjection(projection);
- return projection.error === null;
- })
+ return runInputProjectionOperation(sessionId, (input) =>
+ input.compact(sessionId, createOpts, { userName: currentUserName }),
+ )
+ // RPC 已执行成功时保留既有返回语义;origin 漂移只丢控制端镜像回写。
+ .then(({ projection }) => projection.error === null)
.catch((err) => {
const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));
setState(sessionId, (s) => ({
@@ -7540,8 +7762,11 @@ function steerMessageCore(
// 由队列行接管显示,这里必须返回 true 让 composer 清空草稿,否则用户面前
// 同时存在暂停行 + 草稿,再次发送会双份消费(review #939 第五轮)。
try {
- const latest = await makerApiFor(sessionId).input.getProjection(sessionId);
- applyInputProjection(latest);
+ const operation = beginInputProjectionOperation(sessionId);
+ const latest = await operation.api.input.getProjection(sessionId);
+ if (!applyInputProjectionOperationResponse(sessionId, operation, latest)) {
+ return false;
+ }
if (latest.pendingQueue.some((q) => q.clientId === queued.clientId)) {
// 物化进队列 = 这条输入已被主端接管、日后会派发,与受理同等 —— 起名也要
// 跟上,否则纯附件/fork 之后的第一句话恰好在这条不确定路径上不改名
@@ -7711,9 +7936,21 @@ function stopSession(
): void {
if (!sessionId) return;
flushPendingTextDelta(sessionId);
- makerApiFor(sessionId)
- .input.stop(sessionId, opts)
- .then(applyInputProjection)
+ const api = makerApiFor(sessionId);
+ // Stop 的乐观终态必须立即作废此前同源查询与旧操作;不能等响应回来,
+ // 否则旧结果会在 abort 往返期间把刚清掉的 owner 重新写回。先推进再捕获,
+ // 让 Stop 自己的权威响应仍属于新代际。
+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
+ const operation: InputProjectionOperation = {
+ api,
+ origin: remoteProjectsStore.getSessionDeviceId(sessionId),
+ epoch: _inputProjectionAuthorityEpoch.get(sessionId) ?? 0,
+ };
+ operation.api.input
+ .stop(sessionId, opts)
+ .then((projection) => {
+ applyInputProjectionOperationResponse(sessionId, operation, projection);
+ })
.catch((err) => log.warn('maker.input.stop failed:', err));
setState(sessionId, (s) => {
const id = s.streamingClientId;
@@ -7739,6 +7976,7 @@ function stopSession(
activeTurnRetryText: null,
errorRetryText: null,
pendingPermission: null,
+ continuationTurnClientId: null,
pendingAskUser: null,
// F-AUQ-MIN-5: Stop session — pending question is gone, reset viewer.
askUserViewerState: 'expanded',
@@ -7815,9 +8053,7 @@ function popQueueTail(sessionId: string): boolean {
*/
function clearError(sessionId: string): void {
if (!sessionId) return;
- makerApiFor(sessionId)
- .input.clearError(sessionId)
- .then(applyInputProjection)
+ runInputProjectionOperation(sessionId, (input) => input.clearError(sessionId))
.catch((err) => log.warn('clearError failed:', err));
setState(sessionId, (s) => {
if (
@@ -7844,11 +8080,8 @@ function retryLastError(sessionId: string): Promise<void> {
// 续跑语义在 main:coordinator 判定失败 turn 已有 assistant 产出时,用共享英文
// 常量 CONTINUE_AFTER_ERROR_PROMPT 替代重发原文(shared/interruptedTurn.ts),
// renderer 不传文案、不做判定。
- return makerApiFor(sessionId)
- .input.retryLastError(sessionId)
- .then((projection) => {
- applyInputProjection(projection);
- });
+ return runInputProjectionOperation(sessionId, (input) => input.retryLastError(sessionId))
+ .then(() => undefined);
}
/**
@@ -7944,10 +8177,10 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Pro
| { kind: 'projection'; projection: AgentInputProjection }
| { kind: 'error'; err: unknown }
| { kind: 'timeout' };
+ const clearOperation = beginInputProjectionOperation(sessionId);
try {
guardResult = await Promise.race([
- makerApiFor(sessionId)
- .input.clearSession(sessionId, clearedAt)
+ clearOperation.api.input.clearSession(sessionId, clearedAt)
.then(
(projection) => ({ kind: 'projection' as const, projection }),
(err) => ({ kind: 'error' as const, err }),
@@ -7965,7 +8198,7 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Pro
if (guardTimeoutId) clearTimeout(guardTimeoutId);
}
if (guardResult.kind === 'projection') {
- applyInputProjection(guardResult.projection);
+ applyInputProjectionOperationResponse(sessionId, clearOperation, guardResult.projection);
} else if (guardResult.kind === 'error') {
const err = guardResult.err;
log.warn('maker.input.clearSession failed:', err);
@@ -8986,10 +9219,11 @@ function sendUiTrigger(sessionId: string, prompt: string): Promise<void> {
// 远端 SSH 会话:重启后 lazy-create 缺它会把远端 workingDir 当本地路径。
...(session.remoteHostId ? { remoteHostId: session.remoteHostId } : {}),
};
- return makerApiFor(sessionId)
- .input.enqueue(sessionId, queued, { sendAtMs: Date.now() })
+ const operation = beginInputProjectionOperation(sessionId);
+ return operation.api.input
+ .enqueue(sessionId, queued, { sendAtMs: Date.now() })
.then((projection) => {
- applyInputProjection(projection);
+ applyInputProjectionOperationResponse(sessionId, operation, projection);
});
})
.catch((err) => {
@@ -9310,11 +9544,17 @@ export const makerChatStore = {
autoNameAttempts.clear();
},
/** Exposed for tests only: 把 stream event 打进真实 store(驱动 getRunningSnapshot 等)。 */
- __applyStreamEventForTest: (sessionId: string, event: CCAgentStreamEvent): void =>
- setState(sessionId, (s) => handleStreamEvent(s, event)),
+ __applyStreamEventForTest: (sessionId: string, event: CCAgentStreamEvent): void => {
+ supersedeInputProjectionOnTerminalEvent(sessionId, event);
+ setState(sessionId, (s) => handleStreamEvent(s, event));
+ },
/** Exposed for tests only: 把 status update 打进真实 store。 */
- __applyStatusUpdateForTest: (sessionId: string, update: CCAgentStatusUpdate): void =>
- setState(sessionId, (s) => handleStatusUpdate(s, update)),
+ __applyStatusUpdateForTest: (sessionId: string, update: CCAgentStatusUpdate): void => {
+ if (!update.skipTurnReset && !update.isRunning) {
+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
+ }
+ setState(sessionId, (s) => handleStatusUpdate(s, update));
+ },
/** Exposed for tests only. */
__hydratePersistedMessageForTest: hydratePersistedMessage,
/** Exposed for tests only. */
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 131d55b557..fe7e04546b 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -254,6 +254,12 @@ export interface AgentInputProjection {
* 派发」;旧被控端可能缺省该字段,消费方必须回落为 null。
*/
continuationInFlightClientId?: string | null;
+ /**
+ * 当前 vendor turn 的续跑发起项 clientId。与上面的 dispatch 边界字段不同:同轮
+ * steer 顶替 activeTurn 后,本字段仍保持原续跑项归属,供 Renderer 重载后恢复
+ * 「仍在运行」呈现。旧被控端可能缺省,消费方必须按旧端兼容策略处理。
+ */
+ continuationTurnClientId?: string | null;
steeringQueueClientIds: string[];
queuePaused: boolean;
queueExpanded: boolean;
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 7ac6875acb..ab2c6a3a32 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -338,6 +338,11 @@ export class Session {
// ── 公开 API ─────────────────────────────────────────────────────────────
+ /** 当前/最近一次已建立 reservation 的 turn 代号;只用于跨 await 识别是否仍是同一轮。 */
+ getTurnGeneration(): number {
+ return this.turnGeneration;
+ }
+
async send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult> {
const msg: UserMessage = typeof message === 'string'
? { type: 'user', content: message }