Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 本端发送后强制跟随最新消息 (#3057)
Dashd568d5f3f681
diff --git a/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts b/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.tsindex 1899721414..ade02861ef 100644--- a/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts+++ b/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts@@ -11,7 +11,18 @@ import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import {+ collectKnownUserMessageIds,+ findLastMatching,+ findLastMatchingId,+ resolveEffectiveNearBottom,resolveLastUserMessageObservation,+ bumpSendFollowCancelGeneration,+ readSendFollowCancelGeneration,+ shouldApplyFollowLatestRequest,+ shouldBumpSendFollowCancelOnScroll,+ shouldCommitFollowLatestRequest,+ tryRequestFollowLatest,+ readFollowLatestRequestKey,resolveNearBottomOnScroll,resolveRenderPinDecision,resolveSendWindowHandoff,@@ -267,38 +278,243 @@ describe('selectTailUserMessageId', () => {type Item = { type: 'message'; id: string; role: 'user' | 'assistant' };const userMessageId = (item: Item | undefined) =>item?.role === 'user' ? item.id : null;+ const oldUser: Item = { type: 'message', id: 'old-user', role: 'user' };+ const newUser: Item = { type: 'message', id: 'new-user', role: 'user' };+ const assistant: Item = { type: 'message', id: 'assistant-tail', role: 'assistant' };it('uses the real tail when a bounded window does not cover the end', () => {expect(selectTailUserMessageId({windowCoversEnd: false,- visibleLastItem: { type: 'message', id: 'old-user', role: 'user' },- realLastItem: { type: 'message', id: 'new-user', role: 'user' },+ visibleItems: [oldUser],+ allItems: [oldUser, newUser],userMessageId,}),).toBe('new-user');});- it('ignores an older visible-tail user when the real tail is assistant', () => {+ it('walks back past a real assistant tail to the latest user send', () => {expect(selectTailUserMessageId({windowCoversEnd: false,- visibleLastItem: { type: 'message', id: 'old-user', role: 'user' },- realLastItem: { type: 'message', id: 'assistant-tail', role: 'assistant' },+ visibleItems: [oldUser],+ allItems: [oldUser, newUser, assistant],+ userMessageId,+ }),+ ).toBe('new-user');+ });++ it('ignores an older visible-tail user when the real tail has no later user', () => {+ expect(+ selectTailUserMessageId({+ windowCoversEnd: false,+ visibleItems: [oldUser],+ allItems: [assistant],userMessageId,}),).toBeNull();});- it('uses the visible tail when the window covers the end', () => {+ it('uses the latest visible user even when the covered tail is assistant', () => {expect(selectTailUserMessageId({windowCoversEnd: true,- visibleLastItem: { type: 'message', id: 'visible-user', role: 'user' },- realLastItem: { type: 'message', id: 'visible-user', role: 'user' },+ visibleItems: [oldUser, newUser, assistant],+ allItems: [oldUser, newUser, assistant],userMessageId,}),- ).toBe('visible-user');+ ).toBe('new-user');+ });+});++describe('findLastMatchingId', () => {+ it('returns the last matching id walking from the tail', () => {+ expect(+ findLastMatchingId(+ [{ id: 'a' }, { id: 'b' }, { id: 'c' }],+ (item) => (item.id === 'c' ? null : item.id),+ ),+ ).toBe('b');+ expect(findLastMatchingId([{ id: 'a' }], () => null)).toBeNull();+ expect(+ findLastMatching(+ [{ id: 'a' }, { id: 'b' }],+ (item) => (item.id === 'b' ? item : null),+ )?.id,+ ).toBe('b');+ });+});++describe('resolveEffectiveNearBottom', () => {+ it('uses the scroll-event decision when the window covers the end', () => {+ expect(+ resolveEffectiveNearBottom({+ windowCoversEnd: true,+ nowNearBottom: true,+ wasNearBottom: false,+ }),+ ).toBe(true);+ expect(+ resolveEffectiveNearBottom({+ windowCoversEnd: true,+ nowNearBottom: false,+ wasNearBottom: true,+ }),+ ).toBe(false);+ });++ it('does not start following at the bottom of a historical slice', () => {+ expect(+ resolveEffectiveNearBottom({+ windowCoversEnd: false,+ nowNearBottom: true,+ wasNearBottom: false,+ }),+ ).toBe(false);+ });++ it('keeps an explicit follow while the window has not yet switched back to the tail', () => {+ expect(+ resolveEffectiveNearBottom({+ windowCoversEnd: false,+ nowNearBottom: true,+ wasNearBottom: true,+ }),+ ).toBe(true);+ });++ it('still drops follow when the user scrolls away during a stale-slice handoff', () => {+ expect(+ resolveEffectiveNearBottom({+ windowCoversEnd: false,+ nowNearBottom: false,+ wasNearBottom: true,+ }),+ ).toBe(false);+ });+});++describe('shouldApplyFollowLatestRequest', () => {+ it('applies only when the completing send still belongs to the visible session', () => {+ expect(shouldApplyFollowLatestRequest('session-a', 'session-a')).toBe(true);+ expect(shouldApplyFollowLatestRequest('session-a', 'session-b')).toBe(false);+ });++ it('ignores a late send after the user left the source session', () => {+ expect(shouldApplyFollowLatestRequest('session-a', 'session-b')).toBe(false);+ expect(shouldApplyFollowLatestRequest(null, 'session-b')).toBe(false);+ expect(shouldApplyFollowLatestRequest('session-a', null)).toBe(false);+ expect(shouldApplyFollowLatestRequest(undefined, 'session-b')).toBe(false);+ });+});++describe('shouldCommitFollowLatestRequest', () => {+ it('commits only when the send still belongs to this session and the user did not scroll away', () => {+ expect(+ shouldCommitFollowLatestRequest({+ sourceSessionId: 'session-a',+ currentSessionId: 'session-a',+ startGeneration: 3,+ currentGeneration: 3,+ }),+ ).toBe(true);+ });++ it('drops a failed-send leftover after the user scrolled or switched sessions', () => {+ expect(+ shouldCommitFollowLatestRequest({+ sourceSessionId: 'session-a',+ currentSessionId: 'session-a',+ startGeneration: 3,+ currentGeneration: 4,+ }),+ ).toBe(false);+ expect(+ shouldCommitFollowLatestRequest({+ sourceSessionId: 'session-a',+ currentSessionId: 'session-b',+ startGeneration: 3,+ currentGeneration: 3,+ }),+ ).toBe(false);+ });+});++describe('send follow cancel generation', () => {+ it('isolates cancel generation per session so another pane cannot cancel this send', () => {+ const aStart = readSendFollowCancelGeneration('session-a');+ const bStart = readSendFollowCancelGeneration('session-b');+ bumpSendFollowCancelGeneration('session-b');+ expect(readSendFollowCancelGeneration('session-a')).toBe(aStart);+ expect(readSendFollowCancelGeneration('session-b')).toBe(bStart + 1);+ });++ it('bumps on scrollbar unpin and continued user up-scroll, not on content growth while following', () => {+ expect(+ shouldBumpSendFollowCancelOnScroll({+ wasNearBottom: true,+ effectiveNearBottom: false,+ scrollDelta: -40,+ directionDeadZonePx: 2,+ }),+ ).toBe(true);+ expect(+ shouldBumpSendFollowCancelOnScroll({+ wasNearBottom: false,+ effectiveNearBottom: false,+ scrollDelta: -40,+ directionDeadZonePx: 2,+ }),+ ).toBe(true);+ expect(+ shouldBumpSendFollowCancelOnScroll({+ wasNearBottom: true,+ effectiveNearBottom: true,+ scrollDelta: -1,+ directionDeadZonePx: 2,+ }),+ ).toBe(false);+ });+});++describe('tryRequestFollowLatest', () => {+ it('bumps only the source session when generation is unchanged', () => {+ const sessionA = `follow-a-${Date.now()}`;+ const sessionB = `follow-b-${Date.now()}`;+ const startA = readSendFollowCancelGeneration(sessionA);+ expect(+ tryRequestFollowLatest({+ sourceSessionId: sessionA,+ currentSessionId: sessionA,+ startGeneration: startA,+ }),+ ).toBe(true);+ expect(readFollowLatestRequestKey(sessionA)).toBe(1);+ expect(readFollowLatestRequestKey(sessionB)).toBe(0);+ bumpSendFollowCancelGeneration(sessionA);+ expect(+ tryRequestFollowLatest({+ sourceSessionId: sessionA,+ currentSessionId: sessionA,+ startGeneration: startA,+ }),+ ).toBe(false);+ expect(readFollowLatestRequestKey(sessionA)).toBe(1);+ });++ it('does not bump session A when the visible session is already B', () => {+ const sessionA = `follow-switch-a-${Date.now()}`;+ const sessionB = `follow-switch-b-${Date.now()}`;+ const startA = readSendFollowCancelGeneration(sessionA);+ expect(+ tryRequestFollowLatest({+ sourceSessionId: sessionA,+ currentSessionId: sessionB,+ startGeneration: startA,+ }),+ ).toBe(false);+ expect(readFollowLatestRequestKey(sessionA)).toBe(0);+ expect(readFollowLatestRequestKey(sessionB)).toBe(0);});});@@ -376,6 +592,43 @@ describe('resolveLastUserMessageObservation', () => {isNewUserSend: true,});});++ it('treats a rollback to a previously seen user tail as baseline, not a new send', () => {+ expect(+ resolveLastUserMessageObservation({+ restoring: false,+ tailUserMessageId: 'user-1',+ previousTailUserMessageId: 'user-2',+ knownUserMessageIds: new Set(['user-1', 'user-2']),+ }),+ ).toEqual({+ baselineUserMessageId: 'user-1',+ isNewUserSend: false,+ });+ });++ it('does not treat remount rewind to an older already-loaded user as a send', () => {+ const messages = [+ { role: 'user' as const, clientId: 'user-1' },+ { role: 'assistant' as const, clientId: 'a1' },+ { role: 'user' as const, clientId: 'user-2' },+ ];+ const known = collectKnownUserMessageIds(messages, (message) =>+ message.role === 'user' ? message.clientId : null,+ );+ expect(known).toEqual(new Set(['user-1', 'user-2']));+ expect(+ resolveLastUserMessageObservation({+ restoring: false,+ tailUserMessageId: 'user-1',+ previousTailUserMessageId: 'user-2',+ knownUserMessageIds: known,+ }),+ ).toEqual({+ baselineUserMessageId: 'user-1',+ isNewUserSend: false,+ });+ });});describe('MessageStream send-window handoff wiring', () => {@@ -388,5 +641,43 @@ describe('MessageStream send-window handoff wiring', () => {expect(source).toContain('if (windowHandoff.clearWindowAnchor)');expect(source).toContain('if (decision.pinToBottom && !windowHandoff.deferPinToNextRender)');expect(source).not.toContain('realTailUserSendOutsideWindow');+ expect(source).toContain('followLatestRequestKey');+ expect(source).toContain('subscribeFollowLatestRequests');+ expect(source).toContain('readFollowLatestRequestKey(sessionId)');+ expect(source).toContain('pinToBottom();');+ expect(source).toContain('bumpSendFollowCancelGeneration(sessionId)');+ expect(source).toContain('shouldBumpSendFollowCancelOnScroll({');+ expect(source).toContain('knownUserMessageIds: knownUserMessageIdsRef.current');+ expect(source).toContain('collectKnownUserMessageIds(messages,');+ expect(source).toContain('if (!ownsHardwareScrollActions) return;');+ expect(source).toContain(+ 'useNavigationKeyListener(clearChipJumpSuppression, ownsHardwareScrollActions)',+ );+ expect(source).toContain('newUserSend: false');+ expect(source).toContain('cancelFocusJump({ consumeDeferredDelete: true });');+ });++ it('session view commits follow-latest only after accept and unchanged scroll generation', () => {+ const source = readFileSync(+ resolve(__dirname, '../features/cc-agent/CCAgentSessionView.tsx'),+ 'utf8',+ );+ expect(source).toContain('tryRequestFollowLatest({');+ expect(source).toContain('requestFollowLatest(sessionId, followStartGeneration)');+ expect(source).toContain(+ 'const followStartGeneration = readSendFollowCancelGeneration(sessionId);',+ );+ });++ it('edit-resend and blocked resend request follow-latest through the same owner', () => {+ const source = readFileSync(+ resolve(__dirname, '../components/chat/UserMessageEditBox.tsx'),+ 'utf8',+ );+ expect(source).toContain('tryRequestFollowLatest({');+ expect(source).toContain(+ 'const followStartGeneration = readSendFollowCancelGeneration(sessionId);',+ );+ expect(source).toContain('if (accepted)');});});diff --git a/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.tsindex eeb0a1a75f..d5cf8661a2 100644--- a/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts+++ b/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts@@ -122,10 +122,12 @@ describe('commitEditAndResend', () => {it('happy path:rewindCommit → emitPatch → drop → send 顺序执行,send 用 session 行的设置', async () => {const { deps, calls } = makeDeps();- await commitEditAndResend(- { sessionId: SESSION_ID, clientId: CLIENT_ID, text: 'edited text', fallbackWorkingDir: '/repo-fallback' },- deps,- );+ await expect(+ commitEditAndResend(+ { sessionId: SESSION_ID, clientId: CLIENT_ID, text: 'edited text', fallbackWorkingDir: '/repo-fallback' },+ deps,+ ),+ ).resolves.toBe(true);expect(calls).toEqual(['rewindCommit', 'emitPatch', 'drop', 'send']);expect(deps.rewindCommit).toHaveBeenCalledWith(SESSION_ID, CLIENT_ID);@@ -346,10 +348,12 @@ describe('commitEditAndResend', () => {it('非 quoted 消息重发失败:兜底不注入 quotes(第 4 参 undefined)', async () => {const { deps } = makeDeps(fakeSession(), { dispatchResult: false });- await commitEditAndResend(- { sessionId: SESSION_ID, clientId: CLIENT_ID, text: '> manual md\n\nbody', fallbackWorkingDir: '/repo' },- deps,- );+ await expect(+ commitEditAndResend(+ { sessionId: SESSION_ID, clientId: CLIENT_ID, text: '> manual md\n\nbody', fallbackWorkingDir: '/repo' },+ deps,+ ),+ ).resolves.toBe(false);const args = (deps.saveDraftFallback as unknown as Mock).mock.calls[0];expect(args[1]).toEqual({ type: 'doc', text: '> manual md\n\nbody' });expect(args).toHaveLength(3);diff --git a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.tsindex 65b2eb077d..0c6f5e6293 100644--- a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts+++ b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts@@ -40,12 +40,16 @@ vi.mock('@/lib/sessionService', () => ({}));vi.mock('@/lib/editLastUserMessage', () => ({- commitEditAndResendWithRunningRetry: vi.fn(async () => {}),+ commitEditAndResendWithRunningRetry: vi.fn(async () => true),}));import { toast } from '@/lib/toast';import { rewindPreview } from '@/lib/sessionService';import { commitEditAndResendWithRunningRetry } from '@/lib/editLastUserMessage';+import {+ readFollowLatestRequestKey,+ bumpSendFollowCancelGeneration,+} from '../components/chat/autoFollowIntent';import { UserMessageEditBox } from '../components/chat/UserMessageEditBox';const commitMock = commitEditAndResendWithRunningRetry as unknown as ReturnType<typeof vi.fn>;@@ -97,6 +101,50 @@ describe('UserMessageEditBox — idle 发送', () => {expect(props.onRequestStop).not.toHaveBeenCalled();});+ it('编辑重发受理后请求跟底;入队失败或等待期间上翻则不跟底', async () => {+ const acceptedId = `edit-follow-ok-${Date.now()}`;+ commitMock.mockResolvedValueOnce(true);+ const accepted = renderBox({ sessionId: acceptedId });+ fireEvent.click(accepted.sendBtn);+ await waitFor(() => expect(accepted.props.onSent).toHaveBeenCalledTimes(1));+ expect(readFollowLatestRequestKey(acceptedId)).toBe(1);+ accepted.unmount();+ vi.clearAllMocks();++ const failedId = `edit-follow-fail-${Date.now()}`;+ commitMock.mockResolvedValueOnce(false);+ const failed = renderBox({ sessionId: failedId });+ fireEvent.click(failed.sendBtn);+ await waitFor(() => expect(failed.props.onSent).toHaveBeenCalledTimes(1));+ expect(readFollowLatestRequestKey(failedId)).toBe(0);+ failed.unmount();+ vi.clearAllMocks();++ const cancelledId = `edit-follow-cancel-${Date.now()}`;+ let release: (value: boolean) => void = () => {};+ commitMock.mockImplementationOnce(+ () => new Promise<boolean>((resolve) => { release = resolve; }),+ );+ const cancelled = renderBox({ sessionId: cancelledId });+ fireEvent.click(cancelled.sendBtn);+ await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));+ bumpSendFollowCancelGeneration(cancelledId);+ await act(async () => { release(true); });+ await waitFor(() => expect(cancelled.props.onSent).toHaveBeenCalledTimes(1));+ expect(readFollowLatestRequestKey(cancelledId)).toBe(0);+ });++ it('被拦消息重发成功后请求跟底', async () => {+ const sessionId = `blocked-follow-${Date.now()}`;+ const override = vi.fn(async () => {});+ const box = renderBox({ sessionId, onCommitOverride: override });+ fireEvent.click(box.sendBtn);+ await waitFor(() => expect(box.props.onSent).toHaveBeenCalledTimes(1));+ expect(override).toHaveBeenCalledTimes(1);+ expect(readFollowLatestRequestKey(sessionId)).toBe(1);+ });++it('引用编辑框隐藏 marker,未修改时仍提交保序原文,修改后只提交可见文本', async () => {const encoded = '> <!-- cindy-composer-quote -->\n> quoted\n\nreply';const visible = '> quoted\n\nreply';diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 680c264f12..ff60a5be23 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -280,11 +280,19 @@ import {NO_SCROLL_TOLERANCE_PX,} from './viewportFillDetect';import {+ bumpSendFollowCancelGeneration,+ collectKnownUserMessageIds,+ findLastMatching,+ findLastMatchingId,+ resolveEffectiveNearBottom,resolveNearBottomOnScroll,resolveLastUserMessageObservation,resolveRenderPinDecision,resolveSendWindowHandoff,selectTailUserMessageId,+ readFollowLatestRequestKey,+ shouldBumpSendFollowCancelOnScroll,+ subscribeFollowLatestRequests,shouldUnpinOnUpIntent,shouldUnpinOnWheel,} from './autoFollowIntent';@@ -2870,10 +2878,20 @@ export function MessageStream({const [deleteCompensationReplay, setDeleteCompensationReplay] = useState(0);/** clientId of the last user-role message we've already observed. Used to* detect a NEW user send → force pin regardless of prior scroll state. */- const lastUserMsg = messages[messages.length - 1];const lastUserMsgIdRef = useRef<string | null>(- lastUserMsg?.role === 'user' ? lastUserMsg.clientId : null,+ findLastMatchingId(messages, (message) => (message.role === 'user' ? message.clientId : null)),);+ const knownUserMessageIdsRef = useRef<Set<string>>(+ collectKnownUserMessageIds(messages, (message) =>+ message.role === 'user' ? message.clientId : null,+ ),+ );+ const followLatestRequestKey = useSyncExternalStore(+ subscribeFollowLatestRequests,+ () => readFollowLatestRequestKey(sessionId),+ () => 0,+ );+ const prevFollowLatestRequestKeyRef = useRef(followLatestRequestKey);// ── render-window state ──// null = 默认窗口(取末尾 RENDER_WINDOW_INITIAL_ITEMS 个 item);非 null = 锚定到@@ -3982,10 +4000,11 @@ export function MessageStream({// shouldUnpinOnUpIntent),本回调只负责翻转:ref 与 state 同步更新(F2 不// 变量);unreadCount 不动 — 它只在回底时清零。const unpinAutoFollowForUserUpIntent = useCallback(() => {+ bumpSendFollowCancelGeneration(sessionId);if (!isNearBottomRef.current) return;isNearBottomRef.current = false;setIsNearBottom(false);- }, []);+ }, [sessionId]);// ── jump-to-bottom chip ──// 用户向下滚动且未到底时显示扁平的"跳到底部" chip,2s 内无滚动自动隐藏。@@ -4258,6 +4277,7 @@ export function MessageStream({}, [clearChipJumpSuppression, triggerUserIntentFill, unpinAutoFollowForUserUpIntent]);useEffect(() => {const onHistoryNavigationKey = (event: KeyboardEvent) => {+ if (!ownsHardwareScrollActions) return;if (event.defaultPrevented) return;if (!HISTORY_NAVIGATION_KEYS.has(event.key)) return;if (isEditableKeyboardTarget(event.target)) return;@@ -4275,8 +4295,13 @@ export function MessageStream({return () => {window.removeEventListener('keydown', onHistoryNavigationKey);};- }, [clearChipJumpSuppression, triggerUserIntentFill, unpinAutoFollowForUserUpIntent]);- useNavigationKeyListener(clearChipJumpSuppression);+ }, [+ clearChipJumpSuppression,+ ownsHardwareScrollActions,+ triggerUserIntentFill,+ unpinAutoFollowForUserUpIntent,+ ]);+ useNavigationKeyListener(clearChipJumpSuppression, ownsHardwareScrollActions);const pinToBottom = useCallback(() => {const el = scrollRef.current;@@ -4294,6 +4319,27 @@ export function MessageStream({});}, [beginProgrammaticScroll, finishProgrammaticScroll, refreshViewportAnchor]);+ // Composer send is an explicit "show me the result" intent. Don't wait for+ // the tail render item to be a user message — assistant / tool cards often+ // land in the same commit and used to hide the send from pin detection.+ // This is the only force-follow path: inference must not pin, because an+ // optimistic row can appear after the user already scrolled away.+ useLayoutEffect(() => {+ if (prevFollowLatestRequestKeyRef.current === followLatestRequestKey) return;+ prevFollowLatestRequestKeyRef.current = followLatestRequestKey;+ cancelFocusJump({ consumeDeferredDelete: true });+ const chipJumpGeneration = chipJumpGenerationRef.current;+ if (chipJumpGeneration !== null) {+ finishChipJump(chipJumpGeneration, { consumeDeferredDelete: true });+ }+ setFirstVisibleItemKey(null);+ restoringRef.current = false;+ isNearBottomRef.current = true;+ setIsNearBottom(true);+ setUnreadCount(0);+ pinToBottom();+ }, [cancelFocusJump, finishChipJump, followLatestRequestKey, pinToBottom]);+// F3: 平滑滚到底的按钮回调。// - 乐观更新 unreadCount / isNearBottom / isNearBottomRef → 按钮同一 tick fade-out// - programmaticScrollRef 打开 → scroll handler 在动画期间不会误判为"用户上滚"@@ -4426,30 +4472,26 @@ export function MessageStream({// ResizeObserver below is a safety net for async height growth *after* paint// (markdown render finish, image/code-highlight completion).//- // Special case: when the user hits send, a fresh user-role message appears- // at the tail. We force auto-follow back on regardless of whether the user- // had scrolled up — committing a new turn is an explicit intent to see the- // result land.+ // Local send force-follow is only followLatestRequestKey. Inference here+ // must not pin or steal the window: attachment prep can insert the+ // optimistic row after the user already unpinned.// biome-ignore lint/correctness/useExhaustiveDependencies: bottomPadding 是触发型依赖;overlay 高度变化时即使 effect 内不读取它,也必须重新 pin 到底。useLayoutEffect(() => {- const visibleLastItem = visibleRenderItems[visibleRenderItems.length - 1];- const realLastItem = allRenderItems[allRenderItems.length - 1];const tailUserMessageId = selectTailUserMessageId({windowCoversEnd,- visibleLastItem,- realLastItem,+ visibleItems: visibleRenderItems,+ allItems: allRenderItems,userMessageId: (item) =>item?.type === 'message' && item.message.role === 'user' ? item.message.clientId : null,});const lastUserMsg =tailUserMessageId === null? null- : realLastItem?.type === 'message' && realLastItem.message.clientId === tailUserMessageId- ? realLastItem.message- : visibleLastItem?.type === 'message' &&- visibleLastItem.message.clientId === tailUserMessageId- ? visibleLastItem.message- : null;+ : findLastMatching(allRenderItems, (item) =>+ item.type === 'message' && item.message.clientId === tailUserMessageId+ ? item.message+ : null,+ );// #2194: 未提供回调时按既有语义视为本端发送(测试 / 其它消费方不变);// 提供了回调就严格以其返回值为准——实现方误返回 undefined(如被 as any@@ -4461,21 +4503,24 @@ export function MessageStream({: false;const userMessageObservation = resolveLastUserMessageObservation({restoring: restoringRef.current,- tailUserMessageId: lastUserMsg?.clientId ?? null,+ tailUserMessageId,previousTailUserMessageId: lastUserMsgIdRef.current,+ knownUserMessageIds: knownUserMessageIdsRef.current,});+ for (const id of collectKnownUserMessageIds(allRenderItems, (item) =>+ item.type === 'message' && item.message.role === 'user' ? item.message.clientId : null,+ )) {+ knownUserMessageIdsRef.current.add(id);+ }lastUserMsgIdRef.current = userMessageObservation.baselineUserMessageId;const decision = resolveRenderPinDecision({restoring: restoringRef.current,- newUserSend: userMessageObservation.isNewUserSend,+ newUserSend: false,sentFromThisRenderer,nearBottom: isNearBottomRef.current,});- // 本端发送必须离开锚定历史窗,回到默认尾窗。只清「未覆盖末尾」的锚会漏掉- // 「发送时窗口仍盖住末尾、随后 assistant/工具卡把尾部顶出窗口」——视口已经- // 钉到最新,下一轮新消息却不再跟随。const windowHandoff = resolveSendWindowHandoff({- isNewUserSend: userMessageObservation.isNewUserSend,+ isNewUserSend: false,sentFromThisRenderer,hasWindowAnchor: firstVisibleItemKey !== null,windowCoversEnd,@@ -4909,9 +4954,23 @@ export function MessageStream({thresholdPx: threshold,directionDeadZonePx: SCROLL_DIRECTION_DEAD_ZONE_PX,});- // render-window-bidirectional 要点 3: 窗口未覆盖末尾时强制判为非贴底。- // 否则 DOM 距底 <100px 会被误判成"贴底",auto-follow 拽回底部、jump-down chip 不出现。- const effectiveNearBottom = !windowCoversEnd ? false : nowNearBottom;+ // 历史切片滚到自己的底 ≠ 会话末尾,不能从这里开始跟随。已经在跟+ // (本端发送 / 跳底)时,窗口还没切回尾窗的迟到 scroll 不得把跟随掐死。+ const effectiveNearBottom = resolveEffectiveNearBottom({+ windowCoversEnd,+ nowNearBottom,+ wasNearBottom: isNearBottomRef.current,+ });+ if (+ shouldBumpSendFollowCancelOnScroll({+ wasNearBottom: isNearBottomRef.current,+ effectiveNearBottom,+ scrollDelta: delta,+ directionDeadZonePx: SCROLL_DIRECTION_DEAD_ZONE_PX,+ })+ ) {+ bumpSendFollowCancelGeneration(sessionId);+ }if (effectiveNearBottom !== isNearBottomRef.current) {isNearBottomRef.current = effectiveNearBottom;setIsNearBottom(effectiveNearBottom);@@ -5026,6 +5085,7 @@ export function MessageStream({allRenderItems.length,setFirstVisibleItemKey,setAnchoredForwardItems,+ sessionId,]);// 渲染窗口下移到 render-item 轴后,U2 "末尾窗口全是 orphan tool_result"diff --git a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsxindex a7c1631cc3..65888b948b 100644--- a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx@@ -42,6 +42,10 @@ import { ListComposerTextarea } from '@/components/new-chat/ListComposerTextareaimport { toast } from '@/lib/toast';import { ApiError } from '@/lib/httpClient';import { rewindPreview } from '@/lib/sessionService';+import {+ readSendFollowCancelGeneration,+ tryRequestFollowLatest,+} from '@/components/chat/autoFollowIntent';import { commitEditAndResendWithRunningRetry } from '@/lib/editLastUserMessage';import type { RewindDraftImage } from '@/lib/rewindDraftAttachments';import type { FileRef, PastedTextRange, SlashCommandRange } from '@/lib/imageRef';@@ -204,6 +208,8 @@ export function UserMessageEditBox({: submitTokenIsRuntimeAlias && originalHadConfirmedRange && rebuiltSlashRange? [rebuiltSlashRange]: undefined;+ const followStartGeneration = readSendFollowCancelGeneration(sessionId);+ let accepted = true;if (onCommitOverride) {// 被拦消息:普通重发(不 rewind)。失败抛错落入下方 catch 保留编辑态。await onCommitOverride({@@ -214,7 +220,7 @@ export function UserMessageEditBox({...(preservedSlashCommandRanges !== undefined ? { slashCommandRanges: preservedSlashCommandRanges } : {}),});} else {- await commitEditAndResendWithRunningRetry({+ accepted = await commitEditAndResendWithRunningRetry({sessionId,clientId: messageClientId,text: submitText,@@ -229,6 +235,16 @@ export function UserMessageEditBox({}// 先归零守卫再 onSent:onSent 让父组件立刻卸载本组件,晚于它的 setState// 在已卸载组件上是无效 no-op(bot review 指出的死代码顺序问题)。+ // 编辑框挂在 MessageStream(key=sessionId) 里,切走即卸载;跟底 store 按+ // session 隔离,这里 bump 不会钉到别的会话。CCAgentSessionView 会在+ // `/cc-agent/:id` 切换后存活,所以那边才比对 sessionIdRef.current。+ if (accepted) {+ tryRequestFollowLatest({+ sourceSessionId: sessionId,+ currentSessionId: sessionId,+ startGeneration: followStartGeneration,+ });+ }submittingRef.current = false;setSubmitting(false);onSent();diff --git a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts b/apps/desktop/src/renderer/components/chat/autoFollowIntent.tsindex 7216264677..778dcb9ed1 100644--- a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts+++ b/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts@@ -87,29 +87,50 @@ export function shouldUnpinOnUpIntent({ scrollHeight, clientHeight }: UpIntentUnexport interface SelectTailUserMessageArgs<T extends { type: string }> {/** 当前有界窗口是否覆盖完整 render-item 尾部。 */windowCoversEnd: boolean;- /** 当前 DOM 窗口最后一个 render item。 */- visibleLastItem: T | undefined;- /** 内存中完整 render-item 序列最后一个 item。 */- realLastItem: T | undefined;+ /** 当前 DOM 窗口的 render items。 */+ visibleItems: readonly T[];+ /** 内存中完整 render-item 序列。 */+ allItems: readonly T[];/** 从 render item 提取 user message id;非 user item 返回 null。 */userMessageId: (item: T | undefined) => string | null;}+/** Walk items from the tail and return the first matching value. */+export function findLastMatching<T, U>(+ items: readonly T[],+ pick: (item: T) => U | null,+): U | null {+ for (let i = items.length - 1; i >= 0; i--) {+ const value = pick(items[i]);+ if (value) return value;+ }+ return null;+}++/** Walk items from the tail and return the first matching id. */+export function findLastMatchingId<T>(+ items: readonly T[],+ pickId: (item: T) => string | null,+): string | null {+ return findLastMatching(items, pickId);+}+/*** 选择供「新用户发送」检测的尾消息。** bounded window 未覆盖会话末尾时,visible 尾只代表历史切片边界,可能刚好是* 一条旧 user message;拿它建基线会误判跳回底部或遮蔽真正的新发送。因此该态- * 必须无条件读取内存全量的真实尾部。窗口覆盖末尾时 visible 尾与真实尾同义,- * 保留 visible 路径避免纯扩窗造成额外观察变化。+ * 必须无条件读取内存全量的真实尾部。窗口覆盖末尾时从 visible 尾往回找最近+ * 一条 user——发送后同一帧 assistant / 工具卡已经接在后面时,只看最后一项+ * 会把本次发送漏掉,后续不再强制跟底。*/export function selectTailUserMessageId<T extends { type: string }>({windowCoversEnd,- visibleLastItem,- realLastItem,+ visibleItems,+ allItems,userMessageId,}: SelectTailUserMessageArgs<T>): string | null {- return userMessageId(windowCoversEnd ? visibleLastItem : realLastItem);+ return findLastMatchingId(windowCoversEnd ? visibleItems : allItems, userMessageId);}export interface ResolveRenderPinArgs {@@ -143,6 +164,11 @@ export interface ResolveLastUserMessageObservationArgs {tailUserMessageId: string | null;/** The last tail user message already observed by the mounted stream. */previousTailUserMessageId: string | null;+ /**+ * Every user message id already loaded on this mount. Receding the tail to+ * any of these (rollback, rewind, remount) is not a send.+ */+ knownUserMessageIds?: ReadonlySet<string>;}export interface ResolveLastUserMessageObservation {@@ -152,18 +178,37 @@ export interface ResolveLastUserMessageObservation {isNewUserSend: boolean;}+/** Collect every user message id currently present. */+export function collectKnownUserMessageIds<T>(+ items: readonly T[],+ userMessageId: (item: T) => string | null,+): Set<string> {+ const ids = new Set<string>();+ for (const item of items) {+ const id = userMessageId(item);+ if (id) ids.add(id);+ }+ return ids;+}+/**- * Distinguish restored history hydration from a user send at the tail.- *- * A restored stream can mount before its first history batch arrives. If that- * batch ends in a user message, it must establish the baseline rather than- * taking ownership from the restored viewport as a new send.+ * A tail-user change follows as a send only when that user id is new to this+ * mount. Rollback, rewind, remount, and history hydration re-expose ids that+ * were already loaded — those only move the baseline.*/export function resolveLastUserMessageObservation({restoring,tailUserMessageId,previousTailUserMessageId,+ knownUserMessageIds,}: ResolveLastUserMessageObservationArgs): ResolveLastUserMessageObservation {+ if (+ tailUserMessageId !== null &&+ tailUserMessageId !== previousTailUserMessageId &&+ knownUserMessageIds?.has(tailUserMessageId)+ ) {+ return { baselineUserMessageId: tailUserMessageId, isNewUserSend: false };+ }const baselineUserMessageId =restoring && previousTailUserMessageId === null && tailUserMessageId !== null? tailUserMessageId@@ -279,3 +324,137 @@ export function resolveNearBottomOnScroll({if (wasNearBottom) return true;return scrollDelta > directionDeadZonePx;}++export interface ResolveEffectiveNearBottomArgs {+ /** Current bounded window includes the real session tail. */+ windowCoversEnd: boolean;+ /** Distance/direction resolver result for this scroll event. */+ nowNearBottom: boolean;+ /** Follow state before this scroll event. */+ wasNearBottom: boolean;+}++/**+ * Combine slice coverage with the scroll-event follow decision.+ *+ * A historical slice scrolled to its own bottom is not the session tail, so+ * we must not *start* following there. An explicit follow (composer send /+ * jump-to-latest) already set wasNearBottom; a late scroll event while the+ * window has not yet switched back to the default tail must not cancel it.+ */+export function resolveEffectiveNearBottom({+ windowCoversEnd,+ nowNearBottom,+ wasNearBottom,+}: ResolveEffectiveNearBottomArgs): boolean {+ if (windowCoversEnd) return nowNearBottom;+ return wasNearBottom ? nowNearBottom : false;+}++/**+ * A composer send that started on session A must not pin session B after the+ * user switched routes. FadeSwitcher only remounts on the first path segment,+ * so CCAgentSessionView state survives `/cc-agent/:id` changes.+ */+export function shouldApplyFollowLatestRequest(+ sourceSessionId: string | null | undefined,+ currentSessionId: string | null | undefined,+): boolean {+ return Boolean(sourceSessionId && sourceSessionId === currentSessionId);+}++const sendFollowCancelGenerations = new Map<string, number>();++export function readSendFollowCancelGeneration(+ sessionId: string | null | undefined,+): number {+ if (!sessionId) return 0;+ return sendFollowCancelGenerations.get(sessionId) ?? 0;+}++/** User up-intent on this stream cancels a still-pending follow-latest. */+export function bumpSendFollowCancelGeneration(+ sessionId: string | null | undefined,+): void {+ if (!sessionId) return;+ sendFollowCancelGenerations.set(+ sessionId,+ (sendFollowCancelGenerations.get(sessionId) ?? 0) + 1,+ );+}++export function shouldBumpSendFollowCancelOnScroll({+ wasNearBottom,+ effectiveNearBottom,+ scrollDelta,+ directionDeadZonePx,+}: {+ wasNearBottom: boolean;+ effectiveNearBottom: boolean;+ scrollDelta: number;+ directionDeadZonePx: number;+}): boolean {+ if (wasNearBottom && !effectiveNearBottom) return true;+ return !effectiveNearBottom && scrollDelta < -directionDeadZonePx;+}++export function shouldCommitFollowLatestRequest({+ sourceSessionId,+ currentSessionId,+ startGeneration,+ currentGeneration,+}: {+ sourceSessionId: string | null | undefined;+ currentSessionId: string | null | undefined;+ startGeneration: number;+ currentGeneration: number;+}): boolean {+ if (!shouldApplyFollowLatestRequest(sourceSessionId, currentSessionId)) return false;+ return startGeneration === currentGeneration;+}++const followLatestListeners = new Set<() => void>();+const followLatestRequests = new Map<string, number>();++export function subscribeFollowLatestRequests(onStoreChange: () => void): () => void {+ followLatestListeners.add(onStoreChange);+ return () => {+ followLatestListeners.delete(onStoreChange);+ };+}++export function readFollowLatestRequestKey(+ sessionId: string | null | undefined,+): number {+ if (!sessionId) return 0;+ return followLatestRequests.get(sessionId) ?? 0;+}++/** Accepted local send from any entry (composer, edit-resend) requests follow. */+export function tryRequestFollowLatest({+ sourceSessionId,+ currentSessionId,+ startGeneration,+}: {+ sourceSessionId: string | null | undefined;+ currentSessionId: string | null | undefined;+ startGeneration: number;+}): boolean {+ if (+ !shouldCommitFollowLatestRequest({+ sourceSessionId,+ currentSessionId,+ startGeneration,+ currentGeneration: readSendFollowCancelGeneration(sourceSessionId),+ })+ ) {+ return false;+ }+ if (!sourceSessionId) return false;+ followLatestRequests.set(+ sourceSessionId,+ (followLatestRequests.get(sourceSessionId) ?? 0) + 1,+ );+ for (const listener of followLatestListeners) listener();+ return true;+}diff --git a/apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts b/apps/desktop/src/renderer/components/chat/useNavigationKeyListener.tsindex a515deb05d..2b41c0240a 100644--- a/apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts+++ b/apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts@@ -39,14 +39,19 @@ export function shouldHandleNavigationKey(key: string, target: EventTarget | nul/*** 监听 window keydown,任一 NAVIGATION_KEYS 触发时调用 onNavKey。- * onNavKey 用 ref 持有,避免每次 render 重新挂 listener。+ * onNavKey / enabled 用 ref 持有,避免每次 render 重新挂 listener。+ * SplitGroup 里每个 MessageStream 都会挂一份;enabled=false 时忽略,+ * 避免未获滚动主权的 pane 把别人的键盘当成自己的上翻意图。*/-export function useNavigationKeyListener(onNavKey: () => void): void {+export function useNavigationKeyListener(onNavKey: () => void, enabled = true): void {const cbRef = useRef(onNavKey);cbRef.current = onNavKey;+ const enabledRef = useRef(enabled);+ enabledRef.current = enabled;useEffect(() => {const handler = (e: KeyboardEvent) => {+ if (!enabledRef.current) return;if (shouldHandleNavigationKey(e.key, e.target)) {cbRef.current();}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex cb942eb33d..a62974805a 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -71,6 +71,10 @@ import { PlanViewerCard } from '@/components/new-chat/PlanViewerCard';import { PlanActionCard } from '@/components/new-chat/PlanActionCard';import { InteractionPromptHost } from '@/components/interaction-portal';import { MessageStream } from '@/components/chat/MessageStream';+import {+ readSendFollowCancelGeneration,+ tryRequestFollowLatest,+} from '@/components/chat/autoFollowIntent';import { measureComposerStackTopOffset } from '@/components/chat/messageStreamIndicatorPosition';import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';import {@@ -1272,6 +1276,18 @@ export function CCAgentSessionView({sessionId ? makerChatStore.isLocalSentUserMessage(sessionId, clientId) : false,[sessionId],);+ const sessionIdRef = useRef(sessionId);+ sessionIdRef.current = sessionId;+ const requestFollowLatest = useCallback(+ (sourceSessionId: string | null | undefined, startGeneration: number) => {+ tryRequestFollowLatest({+ sourceSessionId,+ currentSessionId: sessionIdRef.current,+ startGeneration,+ });+ },+ [],+ );const handleOpenForkOrigin = useCallback(() => {if (!canNavigateSession) {@@ -2806,6 +2822,7 @@ export function CCAgentSessionView({): undefined;const dispatch = pending.deliveryMode === 'steer' ? steerMessage : sendMessage;+ const followStartGeneration = readSendFollowCancelGeneration(sessionId);const accepted = await dispatch(slashDispatch.message,pending.model,@@ -2844,6 +2861,7 @@ export function CCAgentSessionView({);if (accepted) {pending.onDeferredAccepted?.();+ requestFollowLatest(sessionId, followStartGeneration);const resumedSessionId = sessionId;if (resumedSessionId) {void dispatchDeferredUiAssignment(resumedSessionId, undefined).catch((err) => {@@ -2867,6 +2885,7 @@ export function CCAgentSessionView({session?.agentKind,session?.orcaRole,sessionId,+ requestFollowLatest,sendMessage,steerMessage,],@@ -3120,6 +3139,7 @@ export function CCAgentSessionView({...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {}),};if (deliveryMode === 'steer') {+ const followStartGeneration = readSendFollowCancelGeneration(sessionId);const accepted = await steerMessage(message,model,@@ -3131,6 +3151,7 @@ export function CCAgentSessionView({sendOptions,);if (accepted && sessionId) {+ requestFollowLatest(sessionId, followStartGeneration);void dispatchDeferredUiAssignment(sessionId, undefined).catch((err) => {log.error('recover deferred Worker assignment after user message failed', err);toast.error(t('newChat.collaboration.assignmentFailed'));@@ -3138,6 +3159,7 @@ export function CCAgentSessionView({}return accepted;}+ const followStartGeneration = readSendFollowCancelGeneration(sessionId);const accepted = await sendMessage(message,model,@@ -3149,6 +3171,7 @@ export function CCAgentSessionView({sendOptions,);if (accepted && sessionId) {+ requestFollowLatest(sessionId, followStartGeneration);void dispatchDeferredUiAssignment(sessionId, undefined).catch((err) => {log.error('recover deferred Worker assignment after user message failed', err);toast.error(t('newChat.collaboration.assignmentFailed'));@@ -3167,6 +3190,7 @@ export function CCAgentSessionView({patchLocalSession,sendMessage,steerMessage,+ requestFollowLatest,navigate,session,sessionId,@@ -3639,6 +3663,7 @@ export function CCAgentSessionView({: undefined;// 必须 await:sendMessage 在设备离线 / 访问被撤销 / 远端 enqueue 拒绝时不抛错,// 而是 resolve false —— 不等它就丢副本,正文会从界面和磁盘上一起消失(codex P1)。+ const followStartGeneration = readSendFollowCancelGeneration(sessionId);const delivered = await deliverRecoverableHandoff(sessionId, () =>sendMessage(pendingText,@@ -3670,6 +3695,7 @@ export function CCAgentSessionView({),);if (delivered) {+ requestFollowLatest(sessionId, followStartGeneration);void dispatchDeferredUiAssignment(sessionId, deferredUiAssignment).catch((err) => {log.error('deferred Worker assignment after first message failed', err);toast.error(t('newChat.collaboration.assignmentFailed'));@@ -3685,6 +3711,7 @@ export function CCAgentSessionView({historyLoaded,maybeDispatchDesktopSlashCommand,restoreRecoverableHandoff,+ requestFollowLatest,sendMessage,session,sessionId,diff --git a/apps/desktop/src/renderer/lib/editLastUserMessage.ts b/apps/desktop/src/renderer/lib/editLastUserMessage.tsindex e1328f3f10..4591b10b0f 100644--- a/apps/desktop/src/renderer/lib/editLastUserMessage.ts+++ b/apps/desktop/src/renderer/lib/editLastUserMessage.ts@@ -195,7 +195,7 @@ export async function fetchLatestUserMessageClientIdViaDb(export async function commitEditAndResend(opts: CommitEditAndResendOptions,deps: CommitEditAndResendDeps = defaultDeps,-): Promise<void> {+): Promise<boolean> {const attachments = buildRewindDraftAttachments({images: opts.images,files: opts.files,@@ -267,7 +267,9 @@ export async function commitEditAndResend(? plainTextToTiptapDoc(opts.text): null;deps.saveDraftFallback(opts.sessionId, document, attachments);+ return false;}+ return true;}/** 重试节奏(编辑自动停止场景专用,见 commitEditAndResendWithRunningRetry)。 */@@ -305,14 +307,13 @@ export async function commitEditAndResendWithRunningRetry(opts: CommitEditAndResendOptions,deps: CommitEditAndResendDeps = defaultDeps,retry: RunningRetryOptions = {},-): Promise<void> {+): Promise<boolean> {const attempts = retry.attempts ?? RUNNING_RETRY_DEFAULTS.attempts;const delayMs = retry.delayMs ?? RUNNING_RETRY_DEFAULTS.delayMs;const sleep = retry.sleep ?? defaultSleep;for (let attempt = 0; ; attempt++) {try {- await commitEditAndResend(opts, deps);- return;+ return await commitEditAndResend(opts, deps);} catch (err) {const isRunning = err instanceof ApiError && err.code === 'SESSION_RUNNING';if (!isRunning || attempt >= attempts) throw err;