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): 外部入口注入的 user 消息不再强制滚动聊天到底部 (#2194) (#2215)

KingSystemHaiGoec806396f49c
diff --git a/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts b/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts
index 34fc4be7cf..6bc76ebed4 100644
--- a/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts
+++ b/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts
@@ -174,6 +174,7 @@ describe('resolveRenderPinDecision', () => {
expect(resolveRenderPinDecision({
restoring: true,
newUserSend: true,
+ sentFromThisRenderer: true,
nearBottom: false,
})).toEqual({ clearRestoring: true, pinToBottom: true });
});
@@ -182,6 +183,7 @@ describe('resolveRenderPinDecision', () => {
expect(resolveRenderPinDecision({
restoring: true,
newUserSend: false,
+ sentFromThisRenderer: false,
nearBottom: false,
})).toEqual({ clearRestoring: false, pinToBottom: false });
});
@@ -190,11 +192,42 @@ describe('resolveRenderPinDecision', () => {
expect(resolveRenderPinDecision({
restoring: false,
newUserSend: false,
+ sentFromThisRenderer: false,
nearBottom: true,
})).toEqual({ clearRestoring: false, pinToBottom: true });
expect(resolveRenderPinDecision({
restoring: false,
newUserSend: false,
+ sentFromThisRenderer: false,
+ nearBottom: false,
+ })).toEqual({ clearRestoring: false, pinToBottom: false });
+ });
+
+ // #2194: IM 渠道 / 手机端 / 定时任务注入的 user 消息没有本端发送意图,
+ // 不应夺走视口——按普通新内容处理(贴底才跟随)。
+ it('externally injected user message does not steal a scrolled-up viewport', () => {
+ expect(resolveRenderPinDecision({
+ restoring: false,
+ newUserSend: true,
+ sentFromThisRenderer: false,
+ nearBottom: false,
+ })).toEqual({ clearRestoring: false, pinToBottom: false });
+ });
+
+ it('externally injected user message still follows while near the bottom', () => {
+ expect(resolveRenderPinDecision({
+ restoring: false,
+ newUserSend: true,
+ sentFromThisRenderer: false,
+ nearBottom: true,
+ })).toEqual({ clearRestoring: false, pinToBottom: true });
+ });
+
+ it('externally injected user message does not take ownership from a restored anchor', () => {
+ expect(resolveRenderPinDecision({
+ restoring: true,
+ newUserSend: true,
+ sentFromThisRenderer: false,
nearBottom: false,
})).toEqual({ clearRestoring: false, pinToBottom: false });
});
diff --git a/apps/desktop/src/renderer/__tests__/localSentUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/localSentUserMessage.test.ts
new file mode 100644
index 0000000000..4904d39249
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/localSentUserMessage.test.ts
@@ -0,0 +1,882 @@
+/**
+ * localSentUserMessage.test.ts
+ * ---------------------------------------------------------------------------
+ * #2194: MessageStream 的「末尾新 user 消息强制回底」只应响应本端 composer
+ * 发出的消息。makerChatStore 在 sendMessageCore / steerMessageCore 登记本端
+ * 发送的 clientId,外部入口(IM 渠道 / 手机端 device-link / 定时任务)注入
+ * 的 user 消息不在集合中,按普通新内容处理。
+ *
+ * 这里锁定 store 侧契约:本端发送可查到、未知(外部注入)clientId 查不到、
+ * purge 后标记随会话清除。
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type {
+ AgentInputProjection,
+ AgentInputQueuedMessage,
+} from '../../shared/agentInputQueue';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { __resetStickySessionOriginForTest } from '@/features/device-link/stickySessionOrigin';
+
+vi.mock('@/lib/messageService', () => ({
+ list: vi.fn(async () => ({ items: [], hasMore: false, oldestId: null })),
+ create: vi.fn(async () => ({}) as unknown),
+ updateContent: vi.fn(async () => ({}) as unknown),
+}));
+
+vi.mock('@/lib/sessionService', () => ({
+ touchUserSend: vi.fn(async () => {}),
+ update: vi.fn(async () => ({})),
+ get: vi.fn(async () => null),
+}));
+
+vi.mock('@/lib/sessionsBus', () => ({
+ emitPatch: vi.fn(),
+}));
+
+vi.mock('@/lib/userPromptStore', () => ({
+ getUserPrompt: () => 'test user prompt',
+}));
+
+vi.mock('@/lib/memorySettingsStore', () => ({
+ getMakerMemoryEnabled: () => true,
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+vi.mock('@/lib/imageRef', () => ({
+ parseUserContent: vi.fn((c: string) => ({ text: c, images: [], files: [] })),
+ stringifyUserContent: vi.fn((text: string, images = [], files = []) =>
+ JSON.stringify({ text, images, files }),
+ ),
+}));
+
+vi.mock('@/lib/composerDraftStore', () => ({
+ saveDraft: vi.fn(),
+ setRemoteOptimisticAttachmentUrls: vi.fn(),
+ plainTextToTiptapDoc: (s: string) => ({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],
+ }),
+}));
+
+import { makerChatStore } from '@/lib/makerChatStore';
+import * as sessionService from '@/lib/sessionService';
+
+const MODEL = 'claude-opus-4-7';
+const EFFORT = 'medium';
+const PERM = 'default';
+const WD = 'C:\\workspace';
+
+function projection(
+ sessionId: string,
+ patch: Partial<AgentInputProjection> = {},
+): AgentInputProjection {
+ return {
+ sessionId,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ credentialSwitchWait: null,
+ ...patch,
+ };
+}
+
+function queuedItem(
+ clientId: string,
+ text: string,
+ opts?: {
+ supersedesUserClientId?: string;
+ originalSyntheticTrigger?: 'continue';
+ autoResume?: boolean;
+ },
+): AgentInputQueuedMessage {
+ return {
+ clientId,
+ text,
+ persistedContent: JSON.stringify({ text, images: [], files: [] }),
+ model: MODEL,
+ effort: EFFORT,
+ permissionMode: PERM,
+ workingDir: WD,
+ ...(opts?.supersedesUserClientId && {
+ supersedesUserClientId: opts.supersedesUserClientId,
+ }),
+ ...(opts?.originalSyntheticTrigger && {
+ originalSyntheticTrigger: opts.originalSyntheticTrigger,
+ }),
+ ...(opts?.autoResume ? { autoResume: true } : {}),
+ chatMessage: {
+ clientId,
+ role: 'user',
+ content: text,
+ isStreaming: false,
+ createdAt: '2026-06-07T00:00:00.000Z',
+ },
+ createOpts: {
+ agentKind: 'claude-code',
+ workingDir: WD,
+ model: MODEL,
+ effort: EFFORT,
+ permissionMode: PERM,
+ userPrompt: 'test user prompt',
+ makerMemoryEnabled: true,
+ displayReasoning: 'summarized',
+ },
+ };
+}
+
+const enqueue = vi.fn((sessionId: string, item: AgentInputQueuedMessage) =>
+ Promise.resolve(projection(sessionId, { pendingQueue: [item] })),
+);
+
+const retryLastError = vi.fn((sessionId: string) => Promise.resolve(projection(sessionId)));
+
+const resume = vi.fn((sessionId: string) => Promise.resolve(projection(sessionId)));
+
+const steer = vi.fn((_sessionId: string, _item: AgentInputQueuedMessage) =>
+ Promise.resolve(true),
+);
+
+let projectionHandler: ((projection: AgentInputProjection) => void) | null = null;
+
+const onInputProjection = vi.fn((cb: (projection: AgentInputProjection) => void) => {
+ projectionHandler = cb;
+ return vi.fn();
+});
+
+function installElectronBridge(): void {
+ projectionHandler = null;
+ const w = globalThis as unknown as { window?: Record<string, unknown> };
+ if (!w.window) w.window = {};
+ w.window.electronAPI = {
+ maker: {
+ input: { enqueue, retryLastError, resume, steer },
+ onInputProjection,
+ onEvent: vi.fn(() => vi.fn()),
+ onStatusChanged: vi.fn(() => vi.fn()),
+ onInteractionRequest: vi.fn(() => vi.fn()),
+ onInteractionDismissed: vi.fn(() => vi.fn()),
+ send: vi.fn(async () => {}),
+ steer: vi.fn(async () => {}),
+ generateTitle: vi.fn(async () => ({ title: 't' })),
+ abortSession: vi.fn(async () => {}),
+ closeSession: vi.fn(async () => {}),
+ listActive: vi.fn(async () => []),
+ },
+ localDb: {
+ messages: {
+ onCreated: vi.fn(() => vi.fn()),
+ },
+ },
+ deviceLink: { invoke: vi.fn().mockResolvedValue(undefined) },
+ };
+}
+
+const flushPromises = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ remoteProjectsStore.clear();
+ __resetStickySessionOriginForTest();
+ makerChatStore.__teardownGlobalListeners();
+ installElectronBridge();
+});
+
+afterEach(() => {
+ makerChatStore.__teardownGlobalListeners();
+ remoteProjectsStore.clear();
+ __resetStickySessionOriginForTest();
+});
+
+describe('isLocalSentUserMessage (#2194)', () => {
+ it('本端 sendMessage 发出的 user 消息登记为本端发送', async () => {
+ const sid = `local-${Math.random().toString(36).slice(2, 8)}`;
+
+ makerChatStore.sendMessage(sid, 'hello', MODEL, EFFORT, PERM, WD);
+ await flushPromises();
+
+ expect(enqueue).toHaveBeenCalledTimes(1);
+ const item = enqueue.mock.calls[0][1];
+ expect(makerChatStore.isLocalSentUserMessage(sid, item.clientId)).toBe(true);
+ });
+
+ it('外部入口注入的 user 消息(未知 clientId)不算本端发送', () => {
+ const sid = `external-${Math.random().toString(36).slice(2, 8)}`;
+
+ // IM / 手机端 / 定时任务注入的消息不经 sendMessageCore,clientId 不在集合中。
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'injected-from-im')).toBe(false);
+ });
+
+ it('purgeSession 后本端发送标记随会话清除', async () => {
+ const sid = `purge-${Math.random().toString(36).slice(2, 8)}`;
+
+ makerChatStore.sendMessage(sid, 'bye', MODEL, EFFORT, PERM, WD);
+ await flushPromises();
+ const item = enqueue.mock.calls[0][1];
+ expect(makerChatStore.isLocalSentUserMessage(sid, item.clientId)).toBe(true);
+
+ makerChatStore.purgeSession(sid);
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, item.clientId)).toBe(false);
+ });
+
+ // review P1(第三轮): 人工 Retry 的零产出克隆项自带 supersedesUserClientId
+ // (仅 manual 非 auto 设置),renderer 按字段直接辨认——不猜队首差分,
+ // 异步窗口内混入的外部入队不会被误认。
+ it('人工 Retry 的克隆项(带 supersedesUserClientId)按本端发送登记', async () => {
+ const sid = `retry-${Math.random().toString(36).slice(2, 8)}`;
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [queuedItem('retry-clone', 'failed text', { supersedesUserClientId: 'orig-user' })],
+ }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+ expect(retryLastError).toHaveBeenCalledTimes(1);
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'retry-clone')).toBe(true);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'injected-from-im')).toBe(false);
+ });
+
+ it('Retry 回执里的外部入队项(无 supersedesUserClientId)不被误认', async () => {
+ const sid = `retry-race-${Math.random().toString(36).slice(2, 8)}`;
+ // Greptile P1 场景:retry 未生成新项,异步窗口内外部消息入队到队首。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('external-enqueue', 'from im')] }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'external-enqueue')).toBe(false);
+ });
+
+ it('Retry 未生成新项(superseded / no-op)时不做标记', async () => {
+ const sid = `retry-noop-${Math.random().toString(36).slice(2, 8)}`;
+
+ // 默认 mock 返回空 pendingQueue——无克隆项,等价 superseded / no-op。
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'anything')).toBe(false);
+ });
+
+ // review P1(第四轮,Greptile): main 的 drain 可能在 retry 回执 apply 之后、
+ // renderer 登记之前抢先消费克隆并推送新投影覆盖 state.pendingQueue——登记
+ // 必须读回执自带的投影快照(main 在 scheduleDrain 前同步生成),不能扫
+ // 当前 state,否则克隆漏记、重试气泡被按外部消息处理。
+ it('drain 抢先消费克隆并覆盖 state 时,仍按回执快照登记克隆', async () => {
+ const sid = `retry-drain-${Math.random().toString(36).slice(2, 8)}`;
+
+ makerChatStore.initGlobalListeners();
+ expect(projectionHandler).toBeTypeOf('function');
+
+ let resolveRetry!: (p: AgentInputProjection) => void;
+ retryLastError.mockImplementationOnce(
+ () => new Promise<AgentInputProjection>((res) => (resolveRetry = res)),
+ );
+
+ const p = makerChatStore.retryLastError(sid);
+ resolveRetry(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('retry-clone', 'failed text', { supersedesUserClientId: 'orig-user' }),
+ ],
+ }),
+ );
+ // 让回执 apply 先跑一拍,再模拟 drain 推送:克隆已被消费,队列空了。
+ await Promise.resolve();
+ projectionHandler!(projection(sid, { pendingQueue: [] }));
+ await p;
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'retry-clone')).toBe(true);
+ });
+
+ // Copilot review nit:重复登记同一 clientId 时,旧实现会先无谓逐出最旧 id,
+ // 容量掉到 CAP-1、误丢更早的本端发送记录。已存在应直接返回。
+ it('重复登记同一 clientId 不会逐出最旧记录(容量守卫)', async () => {
+ const sid = `retry-cap-${Math.random().toString(36).slice(2, 8)}`;
+ // LOCAL_SENT_IDS_CAP = 200(makerChatStore.ts),借 retry 回执填满。
+ for (let i = 0; i < 200; i++) {
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [queuedItem(`clone-${i}`, 't', { supersedesUserClientId: 'orig' })],
+ }),
+ );
+ await makerChatStore.retryLastError(sid);
+ }
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'clone-0')).toBe(true);
+
+ // 重复登记 clone-5:不应逐出 clone-0。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [queuedItem('clone-5', 't', { supersedesUserClientId: 'orig' })],
+ }),
+ );
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'clone-0')).toBe(true);
+
+ // 真正的新 id 仍按 LRU 逐出最旧记录。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [queuedItem('clone-new', 't', { supersedesUserClientId: 'orig' })],
+ }),
+ );
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'clone-0')).toBe(false);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'clone-new')).toBe(true);
+ });
+
+ // Copilot review nit:retry 回执到达前会话已被 purge 时,登记会把
+ // localSentUserMessageIds 条目重新创建出来——泄漏,且同 id 会话重建后
+ // 旧标记会复活。settle 时会话不存在则直接不登记。
+ it('retry 回执到达前会话已 purge 时不登记,会话重建后旧标记不复活', async () => {
+ const sid = `retry-purge-${Math.random().toString(36).slice(2, 8)}`;
+
+ let resolveRetry!: (p: AgentInputProjection) => void;
+ retryLastError.mockImplementationOnce(
+ () => new Promise<AgentInputProjection>((res) => (resolveRetry = res)),
+ );
+
+ const p = makerChatStore.retryLastError(sid);
+ makerChatStore.purgeSession(sid);
+ resolveRetry(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('retry-clone', 'failed text', { supersedesUserClientId: 'orig-user' }),
+ ],
+ }),
+ );
+ await p;
+ await flushPromises();
+
+ // 会话重建(一次新发送)后,purge 前那次 retry 的克隆标记不得复活。
+ makerChatStore.sendMessage(sid, 'again', MODEL, EFFORT, PERM, WD);
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'retry-clone')).toBe(false);
+ });
+
+ // Codex review P1(第八轮): 本地 UI 触发器(silent-stop「继续」/ 中断横幅
+ // 「继续任务」/ Mivo 触发)是本端点击意图——合成行虽不渲染气泡,但点击后
+ // 用户要看到续跑产出,必须按本端发送登记以触发强制回底。
+ it('本地 UI 触发器(sendUiTrigger)的合成行登记为本端意图', async () => {
+ const sid = `uitrigger-${Math.random().toString(36).slice(2, 8)}`;
+ vi.mocked(sessionService.get).mockResolvedValueOnce({
+ agentKind: 'claude-code',
+ sdkSessionId: null,
+ fastMode: false,
+ workingDir: WD,
+ model: MODEL,
+ effort: EFFORT,
+ permissionMode: PERM,
+ } as unknown as Awaited<ReturnType<typeof sessionService.get>>);
+
+ await makerChatStore.sendUiTrigger(sid, '[UI_ACTION_TRIGGER] test');
+ await flushPromises();
+
+ expect(enqueue).toHaveBeenCalledTimes(1);
+ const item = enqueue.mock.calls[0][1];
+ expect(makerChatStore.isLocalSentUserMessage(sid, item.clientId)).toBe(true);
+ // 外部注入的 clientId 不受影响。
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'injected-from-im')).toBe(false);
+ });
+
+ // Codex review P2(第九轮): queue-head(派发前失败)的人工 Retry 由 main
+ // 原样重发既有队首项——无新 clientId、无 supersedesUserClientId。renderer
+ // 以点击时刻镜像的 inputRecovery(projection 线上自带字段)取权威 clientId,
+ // 回执确认生效(error / recovery 清空)后登记;重载后内存标记丢失时续跑
+ // 落库的新行仍能识别为本端意图。
+ it('queue-head 人工 Retry 在回执确认生效后登记队首为本端意图', async () => {
+ const sid = `retry-qh-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ // 建立 queue-head 失败镜像:队首项 + error + recovery。
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('head-1', 'stuck head')],
+ error: 'dispatch failed',
+ recovery: { kind: 'queue-head', clientId: 'head-1' },
+ }),
+ );
+ // 人工 Retry 生效:error / recovery 清空,队首原样保留(无克隆项)。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('head-1', 'stuck head')] }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'head-1')).toBe(true);
+ });
+
+ it('queue-head Retry 被 superseded(回执 recovery 未清)时不登记队首', async () => {
+ const sid = `retry-qh-super-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('head-2', 'stuck head')],
+ error: 'dispatch failed',
+ recovery: { kind: 'queue-head', clientId: 'head-2' },
+ }),
+ );
+ // superseded:main 未处理本次 retry,error / recovery 原样保留。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [queuedItem('head-2', 'stuck head')],
+ error: 'dispatch failed',
+ recovery: { kind: 'queue-head', clientId: 'head-2' },
+ }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'head-2')).toBe(false);
+ });
+
+ it('active-turn 失败时不误标无关队首', async () => {
+ const sid = `retry-at-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ // active-turn 失败 + 队首是无关的外部入队消息。
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('head-ext', 'from im')],
+ error: 'turn failed',
+ recovery: { kind: 'active-turn', item: queuedItem('failed-turn', 'original') },
+ }),
+ );
+ // 有产出续跑分支:回执 error / recovery 清空,队首换成隐藏续跑指令。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('continue-item', 'continue')] }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'head-ext')).toBe(false);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-item')).toBe(false);
+ });
+
+ // Greptile review P1(第十轮): 并发 drain 抢在 Retry 回执前消费并派发
+ // queue-head(recovery 随之清空)时,本次 Retry 实为 superseded——仅凭
+ // error / recovery 为空会误登记。真正的 queue-head 重试项在回执快照里
+ // 仍在队列(main 同步 getProjection 先于 drain),不在队列即不登记。
+ it('queue-head 被并发 drain 抢先消费(回执队列已无该项)时不登记', async () => {
+ const sid = `retry-qh-drain-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('head-3', 'stuck head')],
+ error: 'dispatch failed',
+ recovery: { kind: 'queue-head', clientId: 'head-3' },
+ }),
+ );
+ // 并发 drain 已消费并派发 head-3:回执 error / recovery 为空,但队列空了。
+ retryLastError.mockResolvedValueOnce(projection(sid, { pendingQueue: [] }));
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'head-3')).toBe(false);
+ });
+
+ // Codex review P1(第十轮): 有产出人工 Retry 的隐藏续跑指令由 main 生成
+ // (originalSyntheticTrigger='continue' 且非 autoResume),合成行渲染 null,
+ // 不登记则续跑产出在屏幕外开始。auto 自动续跑不标记。
+ it('有产出人工 Retry 的隐藏续跑指令登记为本端意图,auto 续跑不登记', async () => {
+ const sid = `retry-cont-${Math.random().toString(36).slice(2, 8)}`;
+
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('continue-manual', 'continue', { originalSyntheticTrigger: 'continue' }),
+ ],
+ }),
+ );
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-manual')).toBe(true);
+
+ const sid2 = `retry-cont-auto-${Math.random().toString(36).slice(2, 8)}`;
+ retryLastError.mockResolvedValueOnce(
+ projection(sid2, {
+ pendingQueue: [
+ queuedItem('continue-auto', 'continue', {
+ originalSyntheticTrigger: 'continue',
+ autoResume: true,
+ }),
+ ],
+ }),
+ );
+ await makerChatStore.retryLastError(sid2);
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid2, 'continue-auto')).toBe(false);
+ });
+
+ // Codex review P2(第十一轮): 暂停队列的「继续」与队列项 steer 也是本端
+ // 点击意图——队列可能来自上一次 renderer 生命周期或外部入口,发送侧登记
+ // 不到,动作触发时按点击归属补上。
+ it('暂停队列「继续」(resumeQueue)生效后登记队首为本端意图', async () => {
+ const sid = `resume-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, { pendingQueue: [queuedItem('q1', 'queued')], queuePaused: true }),
+ );
+ resume.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('q1', 'queued')], queuePaused: false }),
+ );
+
+ makerChatStore.resumeQueue(sid);
+ await flushPromises();
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q1')).toBe(true);
+ });
+
+ it('resume 未生效(回执仍 paused)时不登记', async () => {
+ const sid = `resume-noop-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, { pendingQueue: [queuedItem('q2', 'queued')], queuePaused: true }),
+ );
+ // 默认 mock 返回 queuePaused: false——这里显式保持 paused,模拟未生效。
+ resume.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('q2', 'queued')], queuePaused: true }),
+ );
+
+ // 预登记后回执确认未生效需回滚——回执回调链不止 3 个 tick,多刷几轮。
+ makerChatStore.resumeQueue(sid);
+ await flushPromises();
+ await flushPromises();
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q2')).toBe(false);
+ });
+
+ it('队列项 steer 成功后登记为本端意图,失败不登记', async () => {
+ const sid = `steer-q-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('q3', 'queued'), queuedItem('q4', 'queued too')],
+ }),
+ );
+
+ steer.mockResolvedValueOnce(true);
+ await makerChatStore.steerQueuedMessage(sid, 'q3');
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q3')).toBe(true);
+
+ steer.mockResolvedValueOnce(false);
+ await makerChatStore.steerQueuedMessage(sid, 'q4');
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q4')).toBe(false);
+ });
+
+ // Greptile review P1(第十二轮): 回执队列里点击前就存在的外部项(例如被
+ // main 按文本标记 originalSyntheticTrigger='continue' 的外部入队项)不属于
+ // 本次点击的产物——只登记点击后**新出现**的项。
+ it('Retry 回执里点击前就存在的外部 continue 项不被误认', async () => {
+ const sid = `retry-ext-cont-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('ext-continue', 'external continue', { originalSyntheticTrigger: 'continue' }),
+ ],
+ error: 'turn failed',
+ }),
+ );
+ // 回执:点击前的外部 continue 项仍在 + 本次 retry 的新克隆项。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('retry-clone-2', 'failed text', { supersedesUserClientId: 'orig' }),
+ queuedItem('ext-continue', 'external continue', { originalSyntheticTrigger: 'continue' }),
+ ],
+ }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'ext-continue')).toBe(false);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'retry-clone-2')).toBe(true);
+ });
+
+ // Greptile review P1(第十三轮): 点击后、回执前由外部入口并发入队的
+ // continue 项不在点击快照里(通过「新出现」校验),但 main 的
+ // performRetryLastError 把本次续跑指令 unshift 到队首且回执同步生成——
+ // 只登记回执队首的 continue 项,队尾的外部并发项不得误认。
+ it('Retry 回执里点击后并发入队的外部 continue 项(非队首)不被误认', async () => {
+ const sid = `retry-ext-race-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(projection(sid, { pendingQueue: [], error: 'turn failed' }));
+ // 回执:队首是 main 为本次点击生成的续跑指令,队尾是点击后并发入队的外部
+ // continue 项(同为新出现的 continue 项,只能靠队首位置区分)。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('continue-manual-2', 'continue', { originalSyntheticTrigger: 'continue' }),
+ queuedItem('ext-continue-race', 'external continue', {
+ originalSyntheticTrigger: 'continue',
+ }),
+ ],
+ }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-manual-2')).toBe(true);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'ext-continue-race')).toBe(false);
+ });
+
+ // Codex review P2(第十三轮): main 的 resume 在返回 projection 前就会 emit
+ // 并 scheduleDrain,队首行可能抢在回执回调前落库——resumeQueue 必须在 IPC
+ // 前同步预登记;回执确认未生效或 IPC 失败时回滚。
+ it('resumeQueue 在 IPC 回执前同步预登记队首,生效后保留', async () => {
+ const sid = `resume-pre-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, { pendingQueue: [queuedItem('q5', 'queued')], queuePaused: true }),
+ );
+ resume.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('q5', 'queued')], queuePaused: false }),
+ );
+
+ makerChatStore.resumeQueue(sid);
+ // 回执未到,登记已同步生效(main 的 drain / 落库可能抢在回执前)。
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q5')).toBe(true);
+
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q5')).toBe(true);
+ });
+
+ it('resume IPC 失败时回滚预登记', async () => {
+ const sid = `resume-rollback-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, { pendingQueue: [queuedItem('q6', 'queued')], queuePaused: true }),
+ );
+ resume.mockRejectedValueOnce(new Error('ipc down'));
+
+ makerChatStore.resumeQueue(sid);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q6')).toBe(true);
+
+ // IPC 拒绝 → 回滚。回执回调链不止 3 个 tick,多刷几轮。
+ await flushPromises();
+ await flushPromises();
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'q6')).toBe(false);
+ });
+
+ // Greptile review P1(第十四轮): retry 被 supersede / no-op 时回执里没有
+ // 本次点击的产物——此时并发出现在回执队首的外部 continue 项(如外部入口的
+ // steer-fallback 把新项抬到队首)不得误认。生效(resumed)的回执
+ // error / recovery 必然双空(main 在 unshift 前同步清掉),据此门控。
+ it('Retry 被 supersede(回执 recovery 保留)时队首的外部 continue 项不被误认', async () => {
+ const sid = `retry-super-head-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [],
+ error: 'turn failed',
+ recovery: { kind: 'active-turn', item: queuedItem('failed-turn-x', 'original') },
+ }),
+ );
+ // superseded:main 未处理本次 retry,error / recovery 原样保留;并发窗口里
+ // 外部入口的新 continue 项出现在回执队首。
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('ext-head-continue', 'external continue', {
+ originalSyntheticTrigger: 'continue',
+ }),
+ ],
+ error: 'turn failed',
+ recovery: { kind: 'active-turn', item: queuedItem('failed-turn-x', 'original') },
+ }),
+ );
+
+ await makerChatStore.retryLastError(sid);
+ await flushPromises();
+
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'ext-head-continue')).toBe(false);
+ });
+
+ // Codex review P2(第十四轮): queue-head 重试的 clientId 点击时刻已知,而
+ // main 的 scheduleDrain 经 queueMicrotask 在返回 projection 前就会跑——重发
+ // 的队首行可能抢在回执回调前落库,必须 IPC 前预登记;IPC 失败时回滚。
+ it('queue-head Retry 在 IPC 回执前同步预登记,生效后保留', async () => {
+ const sid = `retry-qh-pre-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('qh-1', 'stuck head')],
+ error: 'dispatch failed',
+ recovery: { kind: 'queue-head', clientId: 'qh-1' },
+ }),
+ );
+ retryLastError.mockResolvedValueOnce(
+ projection(sid, { pendingQueue: [queuedItem('qh-1', 'stuck head')] }),
+ );
+
+ const p = makerChatStore.retryLastError(sid);
+ // 回执未到,预登记已同步生效。
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'qh-1')).toBe(true);
+
+ await p;
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'qh-1')).toBe(true);
+ });
+
+ it('queue-head Retry IPC 失败时回滚预登记', async () => {
+ const sid = `retry-qh-rej-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [queuedItem('qh-2', 'stuck head')],
+ error: 'dispatch failed',
+ recovery: { kind: 'queue-head', clientId: 'qh-2' },
+ }),
+ );
+ retryLastError.mockRejectedValueOnce(new Error('ipc down'));
+
+ const p = makerChatStore.retryLastError(sid);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'qh-2')).toBe(true);
+
+ await expect(p).rejects.toThrow('ipc down');
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'qh-2')).toBe(false);
+ });
+
+ // Codex review P1(第十五轮): active-turn 人工 Retry 的产物由 main 在返回
+ // projection 前 scheduleDrain(queueMicrotask)落库,可能抢在 IPC 回执前经
+ // onCreated 到达 MessageStream。main 的 emit 先于 drain——凭点击时的一次性
+ // 意图在投影事件里同步认领,不等回执。
+ it('active-turn Retry 产物在 IPC 回执前经投影事件同步认领', async () => {
+ const sid = `retry-intent-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [],
+ error: 'turn failed',
+ recovery: { kind: 'active-turn', item: queuedItem('failed-turn-y', 'original') },
+ }),
+ );
+ let resolveRetry!: (p: AgentInputProjection) => void;
+ retryLastError.mockImplementationOnce(
+ () => new Promise<AgentInputProjection>((res) => (resolveRetry = res)),
+ );
+
+ const p = makerChatStore.retryLastError(sid);
+ // main 的 emit 先于 scheduleDrain:生效投影(error/recovery 清空、队首是
+ // 本次续跑指令)在回执 settle 前到达,凭一次性意图同步认领。
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('continue-fast', 'continue', { originalSyntheticTrigger: 'continue' }),
+ ],
+ }),
+ );
+ // 回执尚未 settle,登记已生效。
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-fast')).toBe(true);
+
+ resolveRetry(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('continue-fast', 'continue', { originalSyntheticTrigger: 'continue' }),
+ ],
+ }),
+ );
+ await p;
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-fast')).toBe(true);
+ });
+
+ it('Retry 意图不被未生效投影(error 仍在)误消费', async () => {
+ const sid = `retry-intent-gate-${Math.random().toString(36).slice(2, 8)}`;
+ makerChatStore.initGlobalListeners();
+
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [],
+ error: 'turn failed',
+ recovery: { kind: 'active-turn', item: queuedItem('failed-turn-z', 'original') },
+ }),
+ );
+ let resolveRetry!: (p: AgentInputProjection) => void;
+ retryLastError.mockImplementationOnce(
+ () => new Promise<AgentInputProjection>((res) => (resolveRetry = res)),
+ );
+
+ const p = makerChatStore.retryLastError(sid);
+ // 未生效投影:error / recovery 仍在——队首的外部 continue 项不认领,意图保留。
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('ext-cont-pending', 'external', { originalSyntheticTrigger: 'continue' }),
+ ],
+ error: 'turn failed',
+ recovery: { kind: 'active-turn', item: queuedItem('failed-turn-z', 'original') },
+ }),
+ );
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'ext-cont-pending')).toBe(false);
+
+ // 生效投影到达:认领本次产物,外部项仍不认。
+ projectionHandler!(
+ projection(sid, {
+ pendingQueue: [
+ queuedItem('continue-real', 'continue', { originalSyntheticTrigger: 'continue' }),
+ queuedItem('ext-cont-pending', 'external', { originalSyntheticTrigger: 'continue' }),
+ ],
+ }),
+ );
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-real')).toBe(true);
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'ext-cont-pending')).toBe(false);
+
+ resolveRetry(projection(sid, { pendingQueue: [] }));
+ await p;
+ await flushPromises();
+ expect(makerChatStore.isLocalSentUserMessage(sid, 'continue-real')).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
index c4b5541e37..0e31d7bc6c 100644
--- a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts
@@ -73,6 +73,7 @@ const state = (overrides: Partial<SessionChatState> = {}): SessionChatState => (
agentStatus: agentStatus(false),
error: null,
recoverableError: null,
+ inputRecovery: null,
activeTurnRetryText: null,
errorRetryText: null,
credentialSwitchWait: null,
diff --git a/apps/desktop/src/renderer/__tests__/unreadCount.test.ts b/apps/desktop/src/renderer/__tests__/unreadCount.test.ts
new file mode 100644
index 0000000000..79d95c4950
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/unreadCount.test.ts
@@ -0,0 +1,146 @@
+/**
+ * unreadCount 单测 — 「N 条新消息」未读计数纯函数。
+ *
+ * #2194 之后外部入口注入的 user 消息不再抢视口,必须计入未读,否则离底
+ * 阅读时新到内容在屏幕外无声无息(Codex review P2)。
+ */
+import { describe, expect, it } from 'vitest';
+
+import { countUnreadAdded } from '../components/chat/unreadCount';
+
+const msg = (clientId: string, role: string) => ({ clientId, role });
+
+describe('countUnreadAdded', () => {
+ it('assistant / ask_user / plan_review 在离底时计数', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(),
+ messages: [msg('a1', 'assistant'), msg('a2', 'ask_user'), msg('a3', 'plan_review')],
+ nearBottom: false,
+ }),
+ ).toBe(3);
+ });
+
+ it('已见 clientId(流式 token 追加)不重复计数', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(['a1']),
+ messages: [msg('a1', 'assistant'), msg('a2', 'assistant')],
+ nearBottom: false,
+ }),
+ ).toBe(1);
+ });
+
+ it('贴底时不计数(auto-follow 接管)', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(),
+ messages: [msg('a1', 'assistant'), msg('u1', 'user')],
+ nearBottom: true,
+ isLocalUserSend: () => false,
+ }),
+ ).toBe(0);
+ });
+
+ it('tool_use / tool_result 不计数', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(),
+ messages: [msg('t1', 'tool_use'), msg('t2', 'tool_result')],
+ nearBottom: false,
+ }),
+ ).toBe(0);
+ });
+
+ // #2194 / Codex P2:外部注入的 user 消息不再抢视口 → 计入未读;
+ // 本端发送(会强制回底)不计。该规则需要基线(prevIds 非空)才生效。
+ it('非本端发送的 user 消息计数,本端发送不计', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(['seen']),
+ messages: [msg('seen', 'assistant'), msg('ext', 'user'), msg('local', 'user')],
+ nearBottom: false,
+ isLocalUserSend: (id) => id === 'local',
+ }),
+ ).toBe(1);
+ });
+
+ // Codex P2(第六轮):会话重开 / 还原离底时首轮 diff 的 prevIds 为空,
+ // 内存态登记对整批历史 user 行一律返回 false——计入会把历史误报成新消息。
+ it('prevIds 为空(首渲染基线未建立)时 user 行不计数,assistant 行保持既有行为', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(),
+ messages: [msg('u1', 'user'), msg('u2', 'user'), msg('a1', 'assistant')],
+ nearBottom: false,
+ isLocalUserSend: () => false,
+ }),
+ ).toBe(1);
+ });
+
+ it('isLocalUserSend 缺省时 user 不计数(既有行为)', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(),
+ messages: [msg('u1', 'user')],
+ nearBottom: false,
+ }),
+ ).toBe(0);
+ });
+
+ // Codex P1(第四轮):合成指令行(手动「继续」/ Mivo 触发指令)渲染 null,
+ // sendUiTrigger 也不登记本端发送——若计数会留下点对不掉的幻影未读。
+ it('合成指令行(isSyntheticTrigger)不计数', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(['seen']),
+ messages: [
+ msg('seen', 'assistant'),
+ { clientId: 'syn', role: 'user', isSyntheticTrigger: true },
+ msg('ext', 'user'),
+ ],
+ nearBottom: false,
+ isLocalUserSend: () => false,
+ }),
+ ).toBe(1);
+ });
+
+ // Codex P2(第五轮):分页 loadOlderMessages prepend 的历史行不在 prevIds
+ // 里,纯 clientId 差分会把视口上方的旧消息误计成「新消息」。
+ it('分页 prepend 的历史行不计数,只有尾部追加才计', () => {
+ // prevIds 非空:以最后一条已见消息为界。
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(['m3', 'm4']),
+ messages: [
+ msg('h1', 'assistant'),
+ msg('h2', 'user'),
+ msg('m3', 'assistant'),
+ msg('m4', 'user'),
+ ],
+ nearBottom: false,
+ isLocalUserSend: () => false,
+ }),
+ ).toBe(0);
+
+ // 同一帧里既有 prepend 又有尾部追加:只数尾部。
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(['m3']),
+ messages: [msg('h1', 'assistant'), msg('m3', 'assistant'), msg('new', 'assistant')],
+ nearBottom: false,
+ }),
+ ).toBe(1);
+ });
+
+ it('prevIds 里的消息一条都不在列表中(窗口整体重置)时不计数', () => {
+ expect(
+ countUnreadAdded({
+ prevIds: new Set(['gone1', 'gone2']),
+ messages: [msg('a1', 'assistant'), msg('u1', 'user')],
+ nearBottom: false,
+ isLocalUserSend: () => false,
+ }),
+ ).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 29d8e4e559..2189732c26 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -220,6 +220,7 @@ import {
shouldUnpinOnUpIntent,
shouldUnpinOnWheel,
} from './autoFollowIntent';
+import { countUnreadAdded } from './unreadCount';
import { useNavigationKeyListener } from './useNavigationKeyListener';
import { suppressScrollbarActivation } from '@/lib/scrollbarAutoHide';
import { collectAssistantTurnUsageDetails } from '@/lib/userTurnUsage';
@@ -278,6 +279,15 @@ interface MessageStreamProps {
} | null;
/** Opens the parent conversation and focuses the original fork point. */
onOpenForkOrigin?: () => void;
+ /**
+ * #2194: whether a user message (by clientId) was sent from this renderer's
+ * composer. Only such messages force-pin the viewport to the tail; user
+ * messages injected by other entries (IM channels, a mobile client driving
+ * the session, scheduler runs) follow the ordinary near-bottom rule.
+ * Optional — consumers that cannot tell (tests, storybook) keep the legacy
+ * behavior of treating every new tail user message as a local send.
+ */
+ isLocalUserSend?: (clientId: string) => boolean;
}
// ---------------------------------------------------------------------------
@@ -2526,6 +2536,7 @@ export function MessageStream({
focusMessageRequestId,
forkOrigin,
onOpenForkOrigin,
+ isLocalUserSend,
}: MessageStreamProps) {
// 右上角 chip 栈插槽 —— PrevMessageJumpChip 通过 portal 挂到这里,
// 与 DiffPanelToggle 在同一栈中各占一行。Provider 不存在时返回 null,
@@ -3543,28 +3554,24 @@ export function MessageStream({
}, []);
// F2: messages diff → 按角色累计 unreadCount
- // - 用 Set 做 O(n) diff,流式 token 追加(同一 clientId 的 content 变化)不计数
- // - 只在 isNearBottomRef.current === false 时累计;底部时 auto-follow 接手
- // - 角色过滤:user / tool_use / tool_result 跳过;assistant / ask_user / plan_review 计数
+ // - 计数规则抽成纯函数 countUnreadAdded(见 unreadCount.ts):新 clientId 才计、
+ // 贴底不计、assistant/ask_user/plan_review 计;#2194 起非本端发送的 user 也计。
useEffect(() => {
const prev = prevMessageIdsRef.current;
const currentIds = new Set<string>();
- let addedVisible = 0;
-
- for (const m of messages) {
- currentIds.add(m.clientId);
- if (prev.has(m.clientId)) continue;
- // 新出现的 clientId:按角色过滤
- if (m.role === 'assistant' || m.role === 'ask_user' || m.role === 'plan_review') {
- if (!isNearBottomRef.current) addedVisible += 1;
- }
- }
+ for (const m of messages) currentIds.add(m.clientId);
+ const addedVisible = countUnreadAdded({
+ prevIds: prev,
+ messages,
+ nearBottom: isNearBottomRef.current,
+ isLocalUserSend,
+ });
if (addedVisible > 0) {
setUnreadCount((c) => c + addedVisible);
}
prevMessageIdsRef.current = currentIds;
- }, [messages]);
+ }, [messages, isLocalUserSend]);
// ── Synchronous pin-to-bottom on every relevant change. ──
// useLayoutEffect fires before paint, so a new message / bottomPadding change
@@ -3631,6 +3638,14 @@ export function MessageStream({
const decision = resolveRenderPinDecision({
restoring: restoringRef.current,
newUserSend: userMessageObservation.isNewUserSend,
+ // #2194: 未提供回调时按既有语义视为本端发送(测试 / 其它消费方不变);
+ // 提供了回调就严格以其返回值为准——实现方误返回 undefined(如被 as any
+ // 绕过)时按外部注入处理,不用 ?? true 掩盖(Copilot review nit)。
+ sentFromThisRenderer: lastUserMsg
+ ? isLocalUserSend
+ ? isLocalUserSend(lastUserMsg.clientId) === true
+ : true
+ : false,
nearBottom: isNearBottomRef.current,
});
diff --git a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts b/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts
index dd7c26a319..4ae1697efa 100644
--- a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts
+++ b/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts
@@ -117,6 +117,14 @@ export interface ResolveRenderPinArgs {
restoring: boolean;
/** The current render introduced a new user message at the tail. */
newUserSend: boolean;
+ /**
+ * The tail user message was sent from this renderer's composer (local send,
+ * edit-resend, or a device-link send initiated on this desktop). User
+ * messages injected by other entries (IM channels, a mobile client driving
+ * the session remotely, scheduler runs) arrive over IPC with no local
+ * composer intent and must not steal the viewport (#2194).
+ */
+ sentFromThisRenderer: boolean;
/** Auto-follow was active before this render. */
nearBottom: boolean;
}
@@ -169,14 +177,20 @@ export function resolveLastUserMessageObservation({
/**
* Resolve the render-time priority between a saved history anchor and auto-follow.
* Reopening a session must preserve a real reading position, but a user message
- * sent during that mounted session is an explicit request to resume at the tail.
+ * sent from this renderer during that mounted session is an explicit request to
+ * resume at the tail. A user message injected by another entry (IM channel,
+ * mobile client, scheduler) carries no such intent: it follows the ordinary
+ * rule — pin only while the user is still near the bottom.
*/
export function resolveRenderPinDecision({
restoring,
newUserSend,
nearBottom,
+ sentFromThisRenderer,
}: ResolveRenderPinArgs): ResolveRenderPinDecision {
- if (newUserSend) return { clearRestoring: restoring, pinToBottom: true };
+ if (newUserSend && sentFromThisRenderer) {
+ return { clearRestoring: restoring, pinToBottom: true };
+ }
if (restoring) return { clearRestoring: false, pinToBottom: false };
return { clearRestoring: false, pinToBottom: nearBottom };
}
diff --git a/apps/desktop/src/renderer/components/chat/unreadCount.ts b/apps/desktop/src/renderer/components/chat/unreadCount.ts
new file mode 100644
index 0000000000..23c35e7ee5
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/unreadCount.ts
@@ -0,0 +1,79 @@
+/**
+ * unreadCount — 「N 条新消息」未读计数纯函数。
+ * ---------------------------------------------------------------------------
+ * MessageStream 的消息 diff 计数抽成纯函数(pattern 同 autoFollowIntent /
+ * scrollAnchoringDetect),规则:
+ *
+ * - 只累计**新出现**的 clientId;流式 token 追加(同 id 内容变化)不计数。
+ * - 视口在底部时不累计——auto-follow 已经把它送进视野。
+ * - 只数**尾部追加**:分页 loadOlderMessages prepend 的历史行同样不在
+ * prevIds 里,按纯 clientId 差分会把视口上方的旧消息误计成「新消息」
+ * (Codex review P2)。prevIds 非空时以「最后一条已见消息」为界,只数
+ * 它之后的行;一条已见消息都找不到(窗口整体重置)则本轮不计。
+ * prevIds 为空(首渲染)保持既有行为:assistant 等角色全部按新内容计,
+ * 但 user 行仍不计(见下一条的基线要求)。
+ * - assistant / ask_user / plan_review 在离底时计数。
+ * - user 消息默认不计数(本端发送会强制回底,用户必然看见);但 #2194 之后
+ * 外部入口(IM / 手机端 / 定时任务)注入的 user 消息不再抢视口,若不计数
+ * 就会在屏幕外无声无息——调用方传入 isLocalUserSend 时,**非本端发送**的
+ * user 消息计入未读(Codex review P2)。isLocalUserSend 缺省保持既有行为。
+ * 该规则只在 prevIds 非空(已有基线)时生效:会话重开 / 还原离底时首轮
+ * diff 的 prevIds 为空,内存态登记在重载后对该批历史 user 行一律返回
+ * false,若计入会把整批历史误报成「新消息」(Codex review P2,第五轮)。
+ * - 合成指令行(isSyntheticTrigger,如手动「继续」/ Mivo 触发指令)渲染 null,
+ * 永远不可见,不计数——否则留下点对不掉的幻影未读(Codex review P1)。
+ */
+
+export interface UnreadCountMessage {
+ clientId: string;
+ role: string;
+ /** 合成指令行(MessageStream 渲染 null);缺省视为普通可见消息 */
+ isSyntheticTrigger?: boolean;
+}
+
+export interface CountUnreadAddedArgs {
+ /** 上一轮已见的 clientId 集合 */
+ prevIds: ReadonlySet<string>;
+ /** 本轮完整消息列表(按渲染顺序) */
+ messages: readonly UnreadCountMessage[];
+ /** 视口是否贴底(auto-follow 接管,不累计) */
+ nearBottom: boolean;
+ /** #2194: 判定 user 消息是否本端发送;缺省时 user 一律不计数(既有行为) */
+ isLocalUserSend?: (clientId: string) => boolean;
+}
+
+export function countUnreadAdded({
+ prevIds,
+ messages,
+ nearBottom,
+ isLocalUserSend,
+}: CountUnreadAddedArgs): number {
+ if (nearBottom) return 0;
+ let candidates: readonly UnreadCountMessage[] = messages;
+ if (prevIds.size > 0) {
+ // 只数尾部追加:分页 prepend 的历史行不在 prevIds 里,纯差分会误计。
+ let lastSeenIdx = -1;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (prevIds.has(messages[i].clientId)) {
+ lastSeenIdx = i;
+ break;
+ }
+ }
+ // 一条已见消息都找不到 = 窗口整体重置(rewind / 重载),不做未读猜测。
+ if (lastSeenIdx === -1) return 0;
+ candidates = messages.slice(lastSeenIdx + 1);
+ }
+ let added = 0;
+ for (const m of candidates) {
+ if (prevIds.has(m.clientId)) continue;
+ if (m.isSyntheticTrigger) continue;
+ if (m.role === 'assistant' || m.role === 'ask_user' || m.role === 'plan_review') {
+ added += 1;
+ continue;
+ }
+ if (m.role === 'user' && prevIds.size > 0 && isLocalUserSend?.(m.clientId) === false) {
+ added += 1;
+ }
+ }
+ return added;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 50a430ce73..48c3575fe6 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1207,6 +1207,18 @@ export function CCAgentSessionView({
});
}, [handoffFrom?.dispatcherSessionId, navigate, ownsWindowRoute, sessionId]);
+ // #2194: 只有本端 composer 发出的 user 消息才强制回底;IM / 手机端 /
+ // 定时任务注入的按普通新内容处理(贴底才跟随)。useCallback 稳定引用——
+ // MessageStream 的未读 diff effect 依赖它,内联箭头会让父组件每次
+ // re-render 都重跑一遍 O(n) diff(Copilot review nit)。sessionId 不可用
+ // 的极短窗口按**非本端发送**处理:该窗口内本端发送会被 guard 早返、根本
+ // 发不出去,能到达的 user 消息必然来自外部(Copilot review nit)。
+ const isLocalUserSend = useCallback(
+ (clientId: string) =>
+ sessionId ? makerChatStore.isLocalSentUserMessage(sessionId, clientId) : false,
+ [sessionId],
+ );
+
const handleOpenForkOrigin = useCallback(() => {
if (!canNavigateSession) {
log.info('fork origin navigation ignored by embedded sidebar view', { sessionId });
@@ -3693,6 +3705,7 @@ export function CCAgentSessionView({
focusMessageRequestId={focusedMessageTarget?.requestId ?? 0}
forkOrigin={forkOrigin}
onOpenForkOrigin={handleOpenForkOrigin}
+ isLocalUserSend={isLocalUserSend}
/>
);
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 4456ce4b88..ee25399fe9 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -58,6 +58,7 @@ import type {
AgentInputCreateOpts,
AgentInputProjection,
AgentInputQueuedMessage,
+ AgentInputRecovery,
AgentInputSessionRef,
AgentInputReference,
} from '../../shared/agentInputQueue';
@@ -2281,6 +2282,13 @@ export interface SessionChatState {
*/
errorReason?: string | null;
recoverableError: string | null;
+ /**
+ * 输入投影自带的 recovery 镜像(main 的 retry 权威状态)。renderer 侧人工
+ * Retry 登记本端意图时用它区分 queue-head(原样重发既有队首项)与
+ * active-turn(克隆 / 续跑指令)——projection 线上本就有该字段,仅镜像,
+ * 不改协议。
+ */
+ inputRecovery: AgentInputRecovery;
/**
* 当前已派发 turn 的 retry 候选文本。
*
@@ -2572,6 +2580,7 @@ function createInitialState(): SessionChatState {
usageLimitRecovery: null,
errorReason: null,
recoverableError: null,
+ inputRecovery: null,
activeTurnRetryText: null,
errorRetryText: null,
credentialSwitchWait: null,
@@ -2639,6 +2648,7 @@ export const EMPTY_SESSION_STATE: SessionChatState = Object.freeze({
usageLimitRecovery: null,
errorReason: null,
recoverableError: null,
+ inputRecovery: null,
activeTurnRetryText: null,
errorRetryText: null,
credentialSwitchWait: null,
@@ -2691,6 +2701,99 @@ const sessions = new Map<string, SessionChatState>();
const listeners = new Map<string, Set<() => void>>();
const lightSnapshotCache = new Map<string, SessionChatLightState>();
+/**
+ * #2194: clientIds of user messages sent from THIS renderer's composer.
+ * sendMessageCore / steerMessageCore are the choke points every local send
+ * (composer send, edit-resend, steer, device-link send initiated on this
+ * desktop) passes through, so those local user messages are recorded there.
+ * Further paths register separately: local UI triggers (silent-stop Continue /
+ * app-exit Continue / Mivo) in sendUiTriggerCore; a manual Retry in
+ * retryLastError (clone via the receipt's supersedesUserClientId, hidden
+ * continue via originalSyntheticTrigger, queue-head redispatch via the
+ * mirrored inputRecovery captured at click time); and queue actions that
+ * dispatch a restored/externally-queued row (resumeQueue, steerQueuedMessage)
+ * at click time.
+ * MessageStream uses this to tell an explicit local send — which force-pins
+ * the viewport to the tail — apart from user messages injected by other
+ * entries (IM channels, a mobile client driving the session remotely,
+ * scheduler runs), which must not steal the reading position. Memory-only
+ * by design: the force-pin only matters at send time; after a renderer
+ * restart the restore path owns the viewport anchor.
+ */
+const localSentUserMessageIds = new Map<string, Set<string>>();
+/** Generous per-session cap — the lookup only matters right after sending. */
+const LOCAL_SENT_IDS_CAP = 200;
+
+function markLocalSentUserMessage(sessionId: string, clientId: string): void {
+ let ids = localSentUserMessageIds.get(sessionId);
+ if (!ids) {
+ ids = new Set();
+ localSentUserMessageIds.set(sessionId, ids);
+ }
+ // 已存在时直接返回:重复登记不该无谓逐出最旧 id(容量会掉到 CAP-1,
+ // Copilot review nit)。
+ if (ids.has(clientId)) return;
+ if (ids.size >= LOCAL_SENT_IDS_CAP) {
+ const oldest = ids.values().next().value;
+ if (oldest !== undefined) ids.delete(oldest);
+ }
+ ids.add(clientId);
+}
+
+/**
+ * Roll back a speculative mark (e.g. queued steer marked before the IPC when
+ * main persists before resolving). Never recreates a purged session's entry.
+ */
+function unmarkLocalSentUserMessage(sessionId: string, clientId: string): void {
+ localSentUserMessageIds.get(sessionId)?.delete(clientId);
+}
+
+/** Whether the given user message was sent from this renderer's composer. */
+function isLocalSentUserMessage(sessionId: string, clientId: string): boolean {
+ return localSentUserMessageIds.get(sessionId)?.has(clientId) ?? false;
+}
+
+/**
+ * #2194: 人工 Retry(active-turn)的一次性本端意图。main 的
+ * performRetryLastError 在返回 projection 前就 emit 并 scheduleDrain
+ * (queueMicrotask),续跑 / 克隆行可能抢在 retry 的 IPC 回执前经
+ * localDb.messages.onCreated 落库、被 MessageStream 基线化为外部
+ * (Codex review P1)。但 main 的 emit 先于 scheduleDrain,投影事件必然
+ * 先于落库广播携带本次产物——点击时记下意图(含点击时刻的队列快照),
+ * applyInputProjection 时凭意图同步认领新 clientId,不等回执。
+ * 回执 settle 时无条件清意图(兜底清理)。
+ */
+const pendingLocalRetryIntents = new Map<string, { queueIds: Set<string> }>();
+
+/**
+ * 与 retryLastError 回执扫描同口径:retry 生效(resumed)时 main 在 unshift
+ * 前同步清掉 error / recovery,投影必然双空,且 unshift → emit 同步、队首
+ * 必然是本次产物;未生效的投影(含 superseded)里没有本次产物,意图继续
+ * pending 等生效投影或回执清理。点击后首个 error/recovery 双空的投影就是
+ * 本次生效投影(其它路径并发清 error 本身就让本次 retry superseded),
+ * 无论是否认领到产物都消费意图——一次性语义。
+ */
+function claimLocalRetryProductFromProjection(projection: AgentInputProjection): void {
+ const intent = pendingLocalRetryIntents.get(projection.sessionId);
+ if (!intent) return;
+ if (projection.error !== null || projection.recovery !== null) return;
+ pendingLocalRetryIntents.delete(projection.sessionId);
+ if (!sessions.has(projection.sessionId)) return;
+ const headClientId = projection.pendingQueue[0]?.clientId;
+ for (const item of projection.pendingQueue) {
+ if (intent.queueIds.has(item.clientId)) continue;
+ if (item.supersedesUserClientId) {
+ markLocalSentUserMessage(projection.sessionId, item.clientId);
+ } else if (
+ item.originalSyntheticTrigger === 'continue' &&
+ item.autoResume !== true &&
+ headClientId === item.clientId
+ ) {
+ markLocalSentUserMessage(projection.sessionId, item.clientId);
+ }
+ }
+}
+
/**
* F-SB-7: Global listeners — notified whenever ANY session's state changes.
* Used by Sidebar to track running status across all sessions without needing
@@ -3072,6 +3175,8 @@ function _purgeSession(sessionId: string): void {
bumpRendererClearGeneration(sessionId);
cancelRemoteOptimisticSendsForSessionPurge(sessionId);
sessions.delete(sessionId);
+ localSentUserMessageIds.delete(sessionId);
+ pendingLocalRetryIntents.delete(sessionId);
// 状态快照同步失效:该会话若有 running / pending / 待投递 transition 条目,
// 不能在缓存里残留(purge 不走 setState,需单独置位)。
_stopTransitions.delete(sessionId);
@@ -3519,6 +3624,9 @@ function applyInputProjection(
if (opts.supersedeQueries !== false) {
supersedeInputProjectionRequests(projection.sessionId);
}
+ // #2194: 人工 Retry 的一次性意图认领——必须在落库广播(onCreated)可能
+ // 到达之前完成登记,main 的 emit 先于 scheduleDrain,这里一定更早。
+ claimLocalRetryProductFromProjection(projection);
// wire 上「字段缺省」就是旧被控端的能力信号;新版没有续跑项时也会显式发 null。
// 必须在 `?? null` 归一化前按 own property 读取,不能让 undefined/null 混淆版本。
const continuationInFlightProjectionCapability: ContinuationInFlightProjectionCapability =
@@ -3703,6 +3811,9 @@ function applyInputProjection(
continuationInFlightClientId: projection.continuationInFlightClientId ?? null,
continuationTurnClientId: projectedContinuationTurnClientId,
continuationInFlightProjectionCapability,
+ // 线上字段镜像(旧被控端缺省回落 null),供人工 Retry 区分 queue-head /
+ // active-turn 归属(#2194 本端意图登记)。
+ inputRecovery: projection.recovery ?? null,
...(authRetryProjectionError ? { _authRetryPersistOnProjectionError: undefined } : {}),
};
});
@@ -10864,10 +10975,44 @@ function setQueueExpanded(sessionId: string, expanded: boolean): void {
function resumeQueue(sessionId: string): void {
if (!sessionId) return;
+ // #2194 (Codex review P2): 暂停队列的「继续」是本端点击意图——恢复后 drain
+ // 派发的队首项落库时会作为新尾部 user 行出现,不登记则门控误判为外部注入,
+ // 续跑在屏幕外开始(队列可能来自上一次 renderer 生命周期或外部入口)。
+ // 点击时刻快照队首。main 的 resume 在返回 projection 前就会 emit 并
+ // scheduleDrain,快的恢复队列上队首行可能抢在回执回调前落库、被基线化为
+ // 外部(Codex review P2):点击意图在点击时刻已确定,先登记,回执确认未
+ // 生效(仍 paused / 队首已不在队列)或 IPC 失败再回滚(会话已 purge 时
+ // 回滚为 no-op,不会复活条目)。
+ const preResumeState = sessions.get(sessionId);
+ const preResumeHeadClientId =
+ preResumeState?.queuePaused === true
+ ? (preResumeState.pendingQueue[0]?.clientId ?? null)
+ : null;
+ if (preResumeHeadClientId) {
+ markLocalSentUserMessage(sessionId, preResumeHeadClientId);
+ }
const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);
runAgentDispatchProjectionOperation(sessionId, (input) =>
boundaryOpts ? input.resume(sessionId, boundaryOpts) : input.resume(sessionId),
- ).catch((err) => log.warn('resumeQueue failed:', err));
+ )
+ .then(({ projection }) => {
+ if (
+ preResumeHeadClientId &&
+ !(
+ sessions.has(sessionId) &&
+ projection.queuePaused === false &&
+ projection.pendingQueue.some((item) => item.clientId === preResumeHeadClientId)
+ )
+ ) {
+ unmarkLocalSentUserMessage(sessionId, preResumeHeadClientId);
+ }
+ })
+ .catch((err) => {
+ if (preResumeHeadClientId) {
+ unmarkLocalSentUserMessage(sessionId, preResumeHeadClientId);
+ }
+ log.warn('resumeQueue failed:', err);
+ });
}
function setQueueInteractionLock(sessionId: string, lockId: string, locked: boolean): void {
@@ -11351,6 +11496,10 @@ async function sendMessageCore(
opts,
identity,
);
+ // #2194: 登记本端发送——MessageStream 的强 pin 只认这个集合,外部入口
+ // (IM / 手机端 / 定时任务)注入的 user 消息不抢视口。后续路径 return false
+ // (如 beforeEnqueue 回滚)会留下一个永不渲染的 id,无害。
+ markLocalSentUserMessage(sessionId, queued.clientId);
const deviceLinkRemote = remoteScopeAtStart !== null;
const remoteRecord = remoteScopeAtStart
@@ -11735,6 +11884,8 @@ async function steerMessageCore(
opts,
identity,
);
+ // #2194: 与 sendMessageCore 相同——本端 steer 也是明确的本地发送意图。
+ markLocalSentUserMessage(sessionId, queued.clientId);
const deviceLinkRemote = remoteScopeAtStart !== null;
const remoteDeviceId = remoteScopeAtStart?.deviceId;
const remoteRecord = remoteScopeAtStart
@@ -11971,17 +12122,24 @@ function steerQueuedMessage(sessionId: string, clientId: string): Promise<boolea
return withAgentSendDispatch(
sessionId,
() => Promise.resolve(false),
- () =>
- steerApi.input
+ () => {
+ // #2194 (Codex review P1): main 的 steer 在返回成功**之前**就
+ // persistAcceptedUserMessage,onCreated 推送可能抢在回执登记前把该行
+ // 基线化为外部消息——校验通过后、IPC 之前先登记,确定失败再回滚
+ // (unmark 不会复活已 purge 会话的条目)。
+ markLocalSentUserMessage(sessionId, clientId);
+ return steerApi.input
.steer(sessionId, queued, {
removeFromQueue: true,
...getRemoteInputClearBoundaryOpts(sessionId),
})
.then((ok) => {
+ if (!ok) unmarkLocalSentUserMessage(sessionId, clientId);
requestInputProjection(sessionId);
return ok;
})
.catch((err) => {
+ unmarkLocalSentUserMessage(sessionId, clientId);
// 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里
// (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。
const message = decodeRemoteErrorMessage(
@@ -11995,7 +12153,8 @@ function steerQueuedMessage(sessionId: string, clientId: string): Promise<boolea
errorRetryText: null,
}));
return false;
- }),
+ });
+ },
);
}
@@ -12177,10 +12336,106 @@ function retryLastError(sessionId: string): Promise<void> {
// renderer 不传文案、不做判定。
// retryLastError 在 main 内会先 await 历史查询再入队,必须从点击时刻起占住与
// Agent 切换共享的发送 token;否则后点的切换能越过这段查询,让重试改由新 Agent 执行。
+ // #2194 (review P1): 人工 Retry 是本地意图,但重试项由 main 在
+ // performRetryLastError 以**新 clientId** 生成,发送侧登记不到。权威归属:
+ // 人工 retry 的零产出克隆项自带 `supersedesUserClientId`(仅 manual 非 auto
+ // 路径设置,见 agent-input-coordinator.ts),直接按字段辨认——不猜队首差分
+ // (异步窗口内可能混入外部入队)、不做文本猜测(维护者口径,#2222)。
+ // 有产出分支的隐藏续跑指令由 main 显式清掉 supersedes 字段,但它同样是本次
+ // 点击的产物:按 `originalSyntheticTrigger === 'continue'` 且非 autoResume
+ // 辨认(auto 自动续跑不是用户动作,不标记;Codex review P1)。
+ // queue-head(派发前失败)分支 main 原样重发**既有队首项**——没有新
+ // clientId、没有 supersedesUserClientId。以点击时刻镜像的 inputRecovery
+ // (projection 线上自带字段)取权威 clientId;重载后内存标记丢失时,续跑
+ // 落库的新行仍能识别为本端意图(Codex review P2)。
+ const preRetryRecovery = sessions.get(sessionId)?.inputRecovery ?? null;
+ const preRetryQueueHeadClientId =
+ preRetryRecovery?.kind === 'queue-head' ? preRetryRecovery.clientId : null;
+ // 点击时刻的队列快照:回执里只登记**新出现**的项。点击前就在队列里的外部
+ // 入队项(例如被 main 按文本标记 originalSyntheticTrigger='continue' 的
+ // 外部项)不属于本次点击的产物,不能误认(Greptile review P1)。
+ const preRetryQueueIds = new Set(
+ (sessions.get(sessionId)?.pendingQueue ?? []).map((item) => item.clientId),
+ );
+ // active-turn 重试的产物 clientId 由 main 生成、点击时刻未知,而 main 的
+ // scheduleDrain(queueMicrotask)可能抢在 IPC 回执前把产物行落库——但
+ // main 的 emit 先于 scheduleDrain,投影事件更早。记下一次性意图(含点击
+ // 时刻队列快照),applyInputProjection 凭意图同步认领(Codex review P1);
+ // 回执 settle 时清理。queue-head 分支不产生新项,走下面的 id 预登记。
+ if (preRetryRecovery?.kind === 'active-turn') {
+ pendingLocalRetryIntents.set(sessionId, { queueIds: preRetryQueueIds });
+ }
+ // queue-head 重试的 clientId 点击时刻已知,但 main 的 scheduleDrain 经
+ // queueMicrotask 在返回 projection 前就会跑,重发的队首行可能抢在回执
+ // 回调前落库、被基线化为外部(Codex review P2):先预登记,回执确认未
+ // 生效或 IPC 失败再回滚(会话已 purge 时回滚为 no-op)。
+ if (preRetryQueueHeadClientId) {
+ markLocalSentUserMessage(sessionId, preRetryQueueHeadClientId);
+ }
const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);
return runAgentDispatchProjectionOperation(sessionId, (input) =>
boundaryOpts ? input.retryLastError(sessionId, boundaryOpts) : input.retryLastError(sessionId),
- ).then(() => undefined);
+ ).then(
+ ({ projection }) => {
+ // 一次性意图的兜底清理:正常路径下 applyInputProjection 已凭意图认领
+ // 并消费;未消费时(投影 stale 被丢 / 顺序异常)回执扫描仍是 fallback。
+ pendingLocalRetryIntents.delete(sessionId);
+ // 扫**回执自带的投影快照**而非当前 state:回执由 main 在 scheduleDrain 之前
+ // 同步生成(agent-input-coordinator.ts performRetryLastError 末尾),必然含
+ // 本次克隆;drain 可能抢在本回调前消费克隆并推送新投影覆盖 state
+ // (Greptile review P1),那时扫 state.pendingQueue 会漏记。
+ // 会话在 retry settle 前被 purge 时不登记——否则会把 localSentUserMessageIds
+ // 条目重新创建出来(泄漏 + 同 id 会话重建后旧标记复活,Copilot review nit)。
+ // purge 本身会清掉预登记,这里直接返回即可。
+ if (!sessions.has(sessionId)) return;
+ // 本次 retry 生效(outcome 'resumed')时 main 在 unshift 前同步清掉
+ // error / recovery,回执必然双空;superseded / no-op 时 recovery 原样
+ // 保留,回执里根本没有本次点击的产物——并发出现在队首的外部 continue
+ // 项不得误认(Greptile review P1)。
+ const retryTookEffect = projection.error === null && projection.recovery === null;
+ if (retryTookEffect) {
+ for (const item of projection.pendingQueue) {
+ if (preRetryQueueIds.has(item.clientId)) continue;
+ if (item.supersedesUserClientId) {
+ markLocalSentUserMessage(sessionId, item.clientId);
+ } else if (
+ item.originalSyntheticTrigger === 'continue' &&
+ item.autoResume !== true &&
+ projection.pendingQueue[0]?.clientId === item.clientId
+ ) {
+ // 有产出人工 retry 的隐藏续跑指令:合成行渲染 null,不登记则续跑产出
+ // 在屏幕外开始(Codex review P1)。auto 自动续跑不标记。
+ // 还须是回执队首:retry 生效时 main 把本次续跑指令 unshift 到队首,
+ // 且 unshift → getProjection 之间无 await(同步),队首必然是本次
+ // 产物;并发的外部入队项只会被压在下面(Greptile review P1)。
+ markLocalSentUserMessage(sessionId, item.clientId);
+ }
+ }
+ }
+ // queue-head 重试的预登记确认:仅当回执确认本次重试生效(error 清空且
+ // recovery 已清)且**队首项仍在回执队列**(被本次 retry 重新武装,main
+ // 同步 getProjection 先于 drain)才保留;若已被并发 drain 消费派发
+ // (不在队列)或本次 retry 实为 superseded / no-op,回滚预登记——留着
+ // 会让该外部行落库时误触发强制回底(Greptile review P1)。
+ if (
+ preRetryQueueHeadClientId &&
+ !(
+ retryTookEffect &&
+ projection.pendingQueue.some((item) => item.clientId === preRetryQueueHeadClientId)
+ )
+ ) {
+ unmarkLocalSentUserMessage(sessionId, preRetryQueueHeadClientId);
+ }
+ },
+ (err) => {
+ // IPC 失败:本次点击没有产生任何效果,清意图 + 回滚 queue-head 预登记。
+ pendingLocalRetryIntents.delete(sessionId);
+ if (preRetryQueueHeadClientId) {
+ unmarkLocalSentUserMessage(sessionId, preRetryQueueHeadClientId);
+ }
+ throw err;
+ },
+ );
}
/**
@@ -13400,6 +13655,12 @@ function sendUiTriggerCore(sessionId: string, prompt: string): Promise<void> {
// 远端 SSH 会话:重启后 lazy-create 缺它会把远端 workingDir 当本地路径。
...(session.remoteHostId ? { remoteHostId: session.remoteHostId } : {}),
};
+ // #2194 (Codex review P1): 本地 UI 触发器(silent-stop「继续」/ 中断横幅
+ // 「继续任务」/ Mivo 触发)是本端点击意图——合成行虽不渲染气泡,但点击后
+ // 用户要看到续跑产出,必须按本端发送登记以触发强制回底;未读计数对
+ // isSyntheticTrigger 行一律跳过,不会因此产生幻影未读。direct-send 兜底
+ // 分支的 clientId 由执行端生成,renderer 无从登记(行缺失的稀有路径)。
+ markLocalSentUserMessage(sessionId, queued.clientId);
const operation = beginInputProjectionOperation(sessionId, remoteDeviceId);
return operation.api.input
.enqueue(sessionId, queued, { sendAtMs: Date.now() })
@@ -13702,6 +13963,8 @@ export const makerChatStore = {
loadAroundMessage,
loadAroundMessageClientId,
sendMessage,
+ /** #2194: MessageStream 强 pin 门控——区分本端发送与外部注入的 user 消息。 */
+ isLocalSentUserMessage,
beginRemoteOptimisticComposerTransition,
cancelRemoteOptimisticSendsForDataOwnerBoundary,
// /goal 从首页新建的会话不经普通发送路径,自动起名漏触发 —— 暴露此动作让调用方用目标文案补起名。