Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 「N 条新消息」按回复计数,同一回合的中间正文只算一条
Dash4214bc0c3467
diff --git a/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts b/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.tsindex d62e14e551..edc25edc2b 100644--- a/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts+++ b/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts@@ -418,7 +418,7 @@ describe('MessageStream focus cancellation wiring', () => {'const scrollbarDragStartTopRef',);expect(pin).toContain('if (!windowCoversEndRef.current) return');- expect(pin).toContain('setUnreadCount(0)');+ expect(pin).toContain('setUnreadKeys(NO_UNREAD_KEYS)');expect(pin).toContain('setFirstVisibleItemKey(null)');});diff --git a/apps/desktop/src/renderer/__tests__/focusScrollWindow.test.ts b/apps/desktop/src/renderer/__tests__/focusScrollWindow.test.tsindex da41a3e1d0..2b54f5725c 100644--- a/apps/desktop/src/renderer/__tests__/focusScrollWindow.test.ts+++ b/apps/desktop/src/renderer/__tests__/focusScrollWindow.test.ts@@ -56,7 +56,7 @@ it.each([false, true])('only repins a window extended to the tail outside prografirstVisibleItemKey: 'search-window', isNearBottomRef: { current: false },programmaticScrollRef: { current: navigating }, restoringRef: { current: false },scrollRef: { current: { scrollHeight: 600, scrollTop: 0, clientHeight: 600 } },- setIsNearBottom: vi.fn(), setUnreadCount: vi.fn(), setFirstVisibleItemKey: vi.fn(),+ setIsNearBottom: vi.fn(), setUnreadKeys: vi.fn(), NO_UNREAD_KEYS: new Set(), setFirstVisibleItemKey: vi.fn(),resolveWindowCoverageLossAction, REPIN_AT_BOTTOM_PX,};new Function(...Object.keys(bindings), code)(...Object.values(bindings))();diff --git a/apps/desktop/src/renderer/__tests__/jumpToLatestLayout.test.tsx b/apps/desktop/src/renderer/__tests__/jumpToLatestLayout.test.tsxindex 02dc0aa913..9c0e046057 100644--- a/apps/desktop/src/renderer/__tests__/jumpToLatestLayout.test.tsx+++ b/apps/desktop/src/renderer/__tests__/jumpToLatestLayout.test.tsx@@ -35,7 +35,7 @@ it('measures the latest window after its React commit when jumping out of historuseCallback: (callback: () => void) => callback, flushSync, scrollRef,restoringRef: { current: false }, cancelFocusJump: vi.fn(),chipJumpGenerationRef: { current: null }, finishChipJump: vi.fn(),- setUnreadCount: vi.fn(), setIsNearBottom: vi.fn(), isNearBottomRef: { current: false },+ setUnreadKeys: vi.fn(), NO_UNREAD_KEYS: new Set(), setIsNearBottom: vi.fn(), isNearBottomRef: { current: false },beginProgrammaticScroll: () => 1, setFirstVisibleItemKey,syncMessageViewport: vi.fn(),finishProgrammaticScroll: () => false, refreshViewportAnchor: vi.fn(), CHIP_JUMP_SAFETY_MS: 1000,diff --git a/apps/desktop/src/renderer/__tests__/tailWindowScrollLayout.test.ts b/apps/desktop/src/renderer/__tests__/tailWindowScrollLayout.test.tsindex 7b99a9f32d..745c0983ea 100644--- a/apps/desktop/src/renderer/__tests__/tailWindowScrollLayout.test.ts+++ b/apps/desktop/src/renderer/__tests__/tailWindowScrollLayout.test.ts@@ -22,17 +22,19 @@ const code = ts.transpileModule(`return (${initializer.arguments[0].getText(sourcompilerOptions: { target: ts.ScriptTarget.ES2022 },}).outputText;+const NO_UNREAD_KEYS: ReadonlySet<string> = new Set();+function fixture(following: boolean, delta: number, distance = 0, coversEnd = true) {const setFirstVisibleItemKey = vi.fn();const setAnchoredForwardItems = vi.fn();- const setUnreadCount = vi.fn();+ const setUnreadKeys = vi.fn();const onLoadMore = vi.fn();const expandWindow = vi.fn();const isNearBottomRef = { current: following };const bindings = {scrollRef: { current: { scrollTop: 10_000, scrollHeight: 10_600 + distance, clientHeight: 600 } },prevScrollTopRef: { current: 10_000 - delta },- isNearBottomRef, setIsNearBottom: vi.fn(), setUnreadCount,+ isNearBottomRef, setIsNearBottom: vi.fn(), setUnreadKeys, NO_UNREAD_KEYS,restoringRef: { current: false }, scrollbarDragStartTopRef: { current: null },programmaticScrollRef: { current: false }, isLoadingMore: false,prevScrollHeightRef: { current: 0 }, saveRafRef: { current: 1 },@@ -47,7 +49,7 @@ function fixture(following: boolean, delta: number, distance = 0, coversEnd = trbumpSendFollowCancelGeneration: vi.fn(), sessionId: 'restored-tail',};const scroll = new Function(...Object.keys(bindings), code)(...Object.values(bindings)) as () => void;- return { scroll, isNearBottomRef, setFirstVisibleItemKey, setAnchoredForwardItems, setUnreadCount, onLoadMore, expandWindow };+ return { scroll, isNearBottomRef, setFirstVisibleItemKey, setAnchoredForwardItems, setUnreadKeys, onLoadMore, expandWindow };}describe('tail window during layout scrolls', () => {@@ -65,7 +67,7 @@ describe('tail window during layout scrolls', () => {state.scroll();expect(state.isNearBottomRef.current).toBe(true);expect(state.setFirstVisibleItemKey).toHaveBeenCalledExactlyOnceWith(null);- expect(state.setUnreadCount).toHaveBeenCalledExactlyOnceWith(0);+ expect(state.setUnreadKeys).toHaveBeenCalledExactlyOnceWith(NO_UNREAD_KEYS);});it('does not shrink history when scrolling up close to the tail', () => {const state = fixture(false, -40, 40);diff --git a/apps/desktop/src/renderer/__tests__/unreadCount.test.ts b/apps/desktop/src/renderer/__tests__/unreadCount.test.tsindex a60c8dd13d..c91b5e834c 100644--- a/apps/desktop/src/renderer/__tests__/unreadCount.test.ts+++ b/apps/desktop/src/renderer/__tests__/unreadCount.test.ts@@ -6,11 +6,38 @@*/import { describe, expect, it } from 'vitest';-import { countUnreadAdded } from '../components/chat/unreadCount';+import { collectUnreadKeys } from '../components/chat/unreadCount';const msg = (clientId: string, role: string) => ({ clientId, role });+const countUnreadAdded = (args: Parameters<typeof collectUnreadKeys>[0]) =>+ collectUnreadKeys(args).length;describe('countUnreadAdded', () => {+ // 一次回复执行中会写出几十段中间正文,最终折进同一段工作过程;逐条计数曾把+ // 一次回复报成「59 条新消息」。同一回合跨多次 diff 返回同一个键,由调用方去重。+ it('同一回合的多段 assistant 输出只算一条,steer 不开启新回合', () => {+ const first = [msg('u1', 'user'), msg('a1', 'assistant'), msg('a2', 'assistant')];+ expect(+ collectUnreadKeys({ prevIds: new Set(['u1']), messages: first, nearBottom: false }),+ ).toEqual(['turn:u1']);+ const second = [+ ...first,+ { clientId: 's1', role: 'user', delivery: 'steer' },+ msg('a3', 'assistant'),+ msg('q1', 'ask_user'),+ msg('u2', 'user'),+ msg('a4', 'assistant'),+ ];+ expect(+ collectUnreadKeys({+ prevIds: new Set(first.map((m) => m.clientId)),+ messages: second,+ nearBottom: false,+ isLocalUserSend: () => true,+ }),+ ).toEqual(['turn:u1', 'q1', 'turn:u2']);+ });+it('assistant / ask_user / plan_review 在离底时计数', () => {expect(countUnreadAdded({@@ -146,9 +173,20 @@ describe('countUnreadAdded', () => {});it('counts new result receipts in history, but not replayed receipts or paginated old cards', () => {- const messages = [{ clientId: 'older-result', role: 'assistant' }, { clientId: 'anchor', role: 'assistant' },- { clientId: 'user-input', role: 'user' }, { clientId: 'result-1', role: 'assistant' },- { clientId: 'hidden-wake', role: 'user', isSyntheticTrigger: true }, { clientId: 'result-2', role: 'assistant' }];+ const messages = [+ { clientId: 'older-result', role: 'assistant' },+ { clientId: 'anchor', role: 'assistant' },+ { clientId: 'user-input', role: 'user' },+ { clientId: 'result-1', role: 'assistant' },+ { clientId: 'hidden-wake', role: 'user', isSyntheticTrigger: true },+ { clientId: 'result-2', role: 'assistant' },+ ];expect(countUnreadAdded({ prevIds: new Set(['anchor']), messages, nearBottom: false })).toBe(2);- expect(countUnreadAdded({ prevIds: new Set(messages.map(message => message.clientId)), messages, nearBottom: false })).toBe(0);+ expect(+ countUnreadAdded({+ prevIds: new Set(messages.map((message) => message.clientId)),+ messages,+ nearBottom: false,+ }),+ ).toBe(0);});diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 01000d69e9..8e0f01a791 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -411,7 +411,9 @@ import {shouldUnpinOnWheel,isUpwardWheelIntent,} from './autoFollowIntent';-import { countUnreadAdded } from './unreadCount';+import { collectUnreadKeys } from './unreadCount';++const NO_UNREAD_KEYS: ReadonlySet<string> = new Set();import {collectBotMessageTimeGroups,findFirstUnreadBotReplyClientId,@@ -4014,7 +4016,7 @@ export function MessageStream({if (coverageLossAction === 'handoff-to-tail') {isNearBottomRef.current = true;setIsNearBottom(true);- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);setFirstVisibleItemKey(null);return;}@@ -4036,7 +4038,7 @@ export function MessageStream({if (distanceFromBottom <= REPIN_AT_BOTTOM_PX) {isNearBottomRef.current = true;setIsNearBottom(true);- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);setFirstVisibleItemKey(null);}}@@ -4427,12 +4429,13 @@ export function MessageStream({// ── F2 / new-message-indicator ──// `isNearBottomRef` 驱动 auto-follow 判定;`isNearBottom` state 只驱动按钮// 显隐(两者同步更新,任何路径都不允许只更新其中一个)。- // `unreadCount` 在"已离底 + 新 assistant/ask_user/plan_review 消息到达"时递增,- // 点击按钮 / 自动回底 / 切换会话 → 归零。+ // `unreadCount` = 离底期间累计的未读键数(同一回合的回复只算一条,见+ // unreadCount.ts),点击按钮 / 自动回底 / 切换会话 → 归零。// Restored history starts unfollowed. Initialize the indicator from the same// snapshot as the scroll gate: later input may correctly leave false unchanged.const [isNearBottom, setIsNearBottom] = useState<boolean>(() => isNearBottomRef.current);- const [unreadCount, setUnreadCount] = useState<number>(0);+ const [unreadKeys, setUnreadKeys] = useState<ReadonlySet<string>>(NO_UNREAD_KEYS);+ const unreadCount = unreadKeys.size;// Only the rendered tail of a canonical Bot chat acknowledges replies. History// navigation, background windows and streaming work never move its read position.useEffect(() => {@@ -4485,7 +4488,7 @@ export function MessageStream({if (isNearBottomRef.current) return;isNearBottomRef.current = true;setIsNearBottom(true);- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);setFirstVisibleItemKey(null);}, []);@@ -4970,7 +4973,7 @@ export function MessageStream({restoringRef.current = false;isNearBottomRef.current = true;setIsNearBottom(true);- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);pinToBottom(true);}, [cancelFocusJump, finishChipJump, followLatestRequestKey, pinToBottom]);@@ -4989,7 +4992,7 @@ export function MessageStream({if (chipJumpGeneration !== null) {finishChipJump(chipJumpGeneration, { consumeDeferredDelete: true });}- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);setIsNearBottom(true);isNearBottomRef.current = true;const generation = beginProgrammaticScroll();@@ -5088,22 +5091,25 @@ export function MessageStream({syncMessageViewport,]);- // F2: messages diff → 按角色累计 unreadCount- // - 计数规则抽成纯函数 countUnreadAdded(见 unreadCount.ts):新 clientId 才计、- // 贴底不计、assistant/ask_user/plan_review 计;#2194 起非本端发送的 user 也计。+ // F2: messages diff → 累计未读键+ // - 计数规则抽成纯函数 collectUnreadKeys(见 unreadCount.ts):新 clientId 才计、+ // 贴底不计、同一回合的回复只算一条;#2194 起非本端发送的 user 也计。useEffect(() => {const prev = prevMessageIdsRef.current;const currentIds = new Set<string>();for (const m of messages) currentIds.add(m.clientId);- const addedVisible = countUnreadAdded({+ const addedKeys = collectUnreadKeys({prevIds: prev,messages,nearBottom: isNearBottomRef.current,isLocalUserSend,});- if (addedVisible > 0) {- setUnreadCount((c) => c + addedVisible);+ if (addedKeys.length > 0) {+ setUnreadKeys((keys) => {+ if (addedKeys.every((key) => keys.has(key))) return keys;+ return new Set([...keys, ...addedKeys]);+ });}prevMessageIdsRef.current = currentIds;}, [messages, isLocalUserSend]);@@ -5174,7 +5180,7 @@ export function MessageStream({setFirstVisibleItemKey(null);isNearBottomRef.current = true;setIsNearBottom(true);- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);}if (userMessageObservation.isNewUserSend && lastUserMsg) {@@ -5766,7 +5772,7 @@ export function MessageStream({isNearBottomRef.current = effectiveNearBottom;setIsNearBottom(effectiveNearBottom);if (effectiveNearBottom) {- setUnreadCount(0);+ setUnreadKeys(NO_UNREAD_KEYS);// Only shrink history when the reader resumes following the tail.// Ctrl+F / Ctrl+A mount offscreen text and change scroll geometry at// an already-followed tail; those scroll events must preserve thediff --git a/apps/desktop/src/renderer/components/chat/unreadCount.ts b/apps/desktop/src/renderer/components/chat/unreadCount.tsindex 23c35e7ee5..4969d6da6d 100644--- a/apps/desktop/src/renderer/components/chat/unreadCount.ts+++ b/apps/desktop/src/renderer/components/chat/unreadCount.ts@@ -2,9 +2,14 @@* unreadCount — 「N 条新消息」未读计数纯函数。* ---------------------------------------------------------------------------* MessageStream 的消息 diff 计数抽成纯函数(pattern 同 autoFollowIntent /- * scrollAnchoringDetect),规则:+ * scrollAnchoringDetect)。返回本轮新增的**未读键**,调用方按键去重累加,+ * 未读数 = 键的数量。规则:*- * - 只累计**新出现**的 clientId;流式 token 追加(同 id 内容变化)不计数。+ * - 按用户看到的「一条消息」计数:同一回合(两条非 steer user 消息之间)的+ * assistant 输出共用一个键——执行中的中间正文、空占位行最终都折进同一段+ * 工作过程,逐条计数会让一次回复报出几十条新消息。ask_user / plan_review+ * 卡片各自独立计数。+ * - 只看**新出现**的 clientId;流式 token 追加(同 id 内容变化)不计数。* - 视口在底部时不累计——auto-follow 已经把它送进视野。* - 只数**尾部追加**:分页 loadOlderMessages prepend 的历史行同样不在* prevIds 里,按纯 clientId 差分会把视口上方的旧消息误计成「新消息」@@ -12,7 +17,6 @@* 它之后的行;一条已见消息都找不到(窗口整体重置)则本轮不计。* prevIds 为空(首渲染)保持既有行为:assistant 等角色全部按新内容计,* 但 user 行仍不计(见下一条的基线要求)。- * - assistant / ask_user / plan_review 在离底时计数。* - user 消息默认不计数(本端发送会强制回底,用户必然看见);但 #2194 之后* 外部入口(IM / 手机端 / 定时任务)注入的 user 消息不再抢视口,若不计数* 就会在屏幕外无声无息——调用方传入 isLocalUserSend 时,**非本端发送**的@@ -21,7 +25,8 @@* diff 的 prevIds 为空,内存态登记在重载后对该批历史 user 行一律返回* false,若计入会把整批历史误报成「新消息」(Codex review P2,第五轮)。* - 合成指令行(isSyntheticTrigger,如手动「继续」/ Mivo 触发指令)渲染 null,- * 永远不可见,不计数——否则留下点对不掉的幻影未读(Codex review P1)。+ * 永远不可见,不计数——否则留下点对不掉的幻影未读(Codex review P1)。它仍是+ * 回合边界:定时唤醒后的结果是一条新回复。*/export interface UnreadCountMessage {@@ -29,9 +34,11 @@ export interface UnreadCountMessage {role: string;/** 合成指令行(MessageStream 渲染 null);缺省视为普通可见消息 */isSyntheticTrigger?: boolean;+ /** 'steer' 的 user 消息插进当前回合,不开启新回合 */+ delivery?: string;}-export interface CountUnreadAddedArgs {+export interface CollectUnreadKeysArgs {/** 上一轮已见的 clientId 集合 */prevIds: ReadonlySet<string>;/** 本轮完整消息列表(按渲染顺序) */@@ -42,14 +49,18 @@ export interface CountUnreadAddedArgs {isLocalUserSend?: (clientId: string) => boolean;}-export function countUnreadAdded({+function isTurnBoundary(m: UnreadCountMessage): boolean {+ return m.role === 'user' && m.delivery !== 'steer';+}++export function collectUnreadKeys({prevIds,messages,nearBottom,isLocalUserSend,-}: CountUnreadAddedArgs): number {- if (nearBottom) return 0;- let candidates: readonly UnreadCountMessage[] = messages;+}: CollectUnreadKeysArgs): string[] {+ if (nearBottom) return [];+ let start = 0;if (prevIds.size > 0) {// 只数尾部追加:分页 prepend 的历史行不在 prevIds 里,纯差分会误计。let lastSeenIdx = -1;@@ -60,20 +71,29 @@ export function countUnreadAdded({}}// 一条已见消息都找不到 = 窗口整体重置(rewind / 重载),不做未读猜测。- if (lastSeenIdx === -1) return 0;- candidates = messages.slice(lastSeenIdx + 1);+ if (lastSeenIdx === -1) return [];+ start = lastSeenIdx + 1;}- let added = 0;- for (const m of candidates) {+ let turnKey = 'turn:';+ for (let i = start - 1; i >= 0; i--) {+ if (isTurnBoundary(messages[i])) {+ turnKey = `turn:${messages[i].clientId}`;+ break;+ }+ }+ const keys = new Set<string>();+ for (let i = start; i < messages.length; i++) {+ const m = messages[i];+ if (isTurnBoundary(m)) turnKey = `turn:${m.clientId}`;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;+ if (m.role === 'assistant') {+ keys.add(turnKey);+ } else if (m.role === 'ask_user' || m.role === 'plan_review') {+ keys.add(m.clientId);+ } else if (m.role === 'user' && prevIds.size > 0 && isLocalUserSend?.(m.clientId) === false) {+ keys.add(m.clientId);}}- return added;+ return [...keys];}