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): 滚回底部后恢复流式贴底跟随 (#3251)

Dash89ae2d856b8d
diff --git a/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts b/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts
index ade02861ef..150e3a7a4a 100644
--- a/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts
+++ b/apps/desktop/src/renderer/__tests__/autoFollowIntent.test.ts
@@ -27,8 +27,13 @@ import {
resolveRenderPinDecision,
resolveSendWindowHandoff,
selectTailUserMessageId,
+ isVerticalScrollbarPress,
+ shouldRepinOnDownIntent,
+ shouldRepinOnWheel,
+ shouldUnpinOnScrollbarDrag,
shouldUnpinOnUpIntent,
shouldUnpinOnWheel,
+ REPIN_AT_BOTTOM_PX,
UNPIN_MIN_SCROLLABLE_PX,
} from '../components/chat/autoFollowIntent';
@@ -79,6 +84,107 @@ describe('shouldUnpinOnWheel', () => {
});
});
+describe('shouldRepinOnWheel', () => {
+ it('向下滚动且已贴死底部 → 恢复', () => {
+ expect(shouldRepinOnWheel({ deltaX: 0, deltaY: 40, distanceFromBottom: 0 })).toBe(true);
+ expect(
+ shouldRepinOnWheel({ deltaX: 0, deltaY: 1, distanceFromBottom: REPIN_AT_BOTTOM_PX }),
+ ).toBe(true);
+ });
+
+ it('向上滚动 → 不恢复', () => {
+ expect(shouldRepinOnWheel({ deltaX: 0, deltaY: -40, distanceFromBottom: 0 })).toBe(false);
+ });
+
+ it('距底超过贴死阈值(刚上滚一格的残留)→ 不恢复,防回弹翻回', () => {
+ expect(shouldRepinOnWheel({ deltaX: 0, deltaY: 40, distanceFromBottom: 40 })).toBe(false);
+ expect(
+ shouldRepinOnWheel({ deltaX: 0, deltaY: 40, distanceFromBottom: REPIN_AT_BOTTOM_PX + 1 }),
+ ).toBe(false);
+ });
+
+ it('水平为主轴的触控板平移 → 不恢复', () => {
+ expect(shouldRepinOnWheel({ deltaX: 60, deltaY: 3, distanceFromBottom: 0 })).toBe(false);
+ });
+});
+
+describe('shouldRepinOnDownIntent', () => {
+ it('已贴死底部 → 恢复(方向由 caller 保证)', () => {
+ expect(shouldRepinOnDownIntent({ distanceFromBottom: 0 })).toBe(true);
+ expect(shouldRepinOnDownIntent({ distanceFromBottom: REPIN_AT_BOTTOM_PX })).toBe(true);
+ });
+
+ it('距底超过贴死阈值 → 不恢复', () => {
+ expect(shouldRepinOnDownIntent({ distanceFromBottom: REPIN_AT_BOTTOM_PX + 1 })).toBe(false);
+ });
+});
+
+describe('shouldUnpinOnScrollbarDrag', () => {
+ it('指针按下且上移过死区 → 解除', () => {
+ expect(
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: true,
+ scrollDelta: -2,
+ directionDeadZonePx: 1,
+ }),
+ ).toBe(true);
+ });
+
+ it('只按下未移动 / 下移 → 不解除(点滑块不该掐死跟随)', () => {
+ expect(
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: true,
+ scrollDelta: 0,
+ directionDeadZonePx: 1,
+ }),
+ ).toBe(false);
+ expect(
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: true,
+ scrollDelta: 40,
+ directionDeadZonePx: 1,
+ }),
+ ).toBe(false);
+ expect(
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: true,
+ scrollDelta: -1,
+ directionDeadZonePx: 1,
+ }),
+ ).toBe(false);
+ });
+
+ it('指针未按下 → 不解除', () => {
+ expect(
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: false,
+ scrollDelta: -40,
+ directionDeadZonePx: 1,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('isVerticalScrollbarPress', () => {
+ it('点在容器自身且 offsetX 落在滚动条槽 → 进入拖拽', () => {
+ expect(isVerticalScrollbarPress({ targetIsRoot: true, offsetX: 800, clientWidth: 784 })).toBe(
+ true,
+ );
+ expect(isVerticalScrollbarPress({ targetIsRoot: true, offsetX: 784, clientWidth: 784 })).toBe(
+ true,
+ );
+ });
+
+ it('点在正文后代 / 容器内容区 → 不进入拖拽', () => {
+ expect(isVerticalScrollbarPress({ targetIsRoot: false, offsetX: 800, clientWidth: 784 })).toBe(
+ false,
+ );
+ expect(isVerticalScrollbarPress({ targetIsRoot: true, offsetX: 400, clientWidth: 784 })).toBe(
+ false,
+ );
+ });
+});
+
describe('shouldUnpinOnUpIntent', () => {
it('容器可滚 → 解除(方向语义由 caller 的事件分支保证)', () => {
expect(shouldUnpinOnUpIntent(SCROLLABLE)).toBe(true);
@@ -190,6 +296,36 @@ describe('resolveNearBottomOnScroll', () => {
).toBe(false);
});
+ it('已贴死底部 + 已解除 + 非上滚(含 delta≈0)→ 恢复跟随', () => {
+ expect(
+ resolveNearBottomOnScroll({
+ ...BASE,
+ wasNearBottom: false,
+ distanceFromBottom: 0,
+ scrollDelta: 0,
+ }),
+ ).toBe(true);
+ expect(
+ resolveNearBottomOnScroll({
+ ...BASE,
+ wasNearBottom: false,
+ distanceFromBottom: REPIN_AT_BOTTOM_PX,
+ scrollDelta: 0,
+ }),
+ ).toBe(true);
+ });
+
+ it('已贴死底部 + 已解除 + 上滚 → 保持解除(1px 上滚解除后的 scroll 不得翻回)', () => {
+ expect(
+ resolveNearBottomOnScroll({
+ ...BASE,
+ wasNearBottom: false,
+ distanceFromBottom: 0,
+ scrollDelta: -1,
+ }),
+ ).toBe(false);
+ });
+
it('阈值带内 + 已解除 + 明确向下 → 恢复跟随', () => {
expect(
resolveNearBottomOnScroll({
@@ -212,72 +348,85 @@ describe('resolveNearBottomOnScroll', () => {
describe('resolveRenderPinDecision', () => {
it('explicit tail send takes ownership from a restored history anchor', () => {
- expect(resolveRenderPinDecision({
- restoring: true,
- newUserSend: true,
- sentFromThisRenderer: true,
- nearBottom: false,
- })).toEqual({ clearRestoring: true, pinToBottom: true });
+ expect(
+ resolveRenderPinDecision({
+ restoring: true,
+ newUserSend: true,
+ sentFromThisRenderer: true,
+ nearBottom: false,
+ }),
+ ).toEqual({ clearRestoring: true, pinToBottom: true });
});
it('restored history remains anchored until an explicit user send', () => {
- expect(resolveRenderPinDecision({
- restoring: true,
- newUserSend: false,
- sentFromThisRenderer: false,
- nearBottom: false,
- })).toEqual({ clearRestoring: false, pinToBottom: false });
+ expect(
+ resolveRenderPinDecision({
+ restoring: true,
+ newUserSend: false,
+ sentFromThisRenderer: false,
+ nearBottom: false,
+ }),
+ ).toEqual({ clearRestoring: false, pinToBottom: false });
});
it('keeps ordinary near-bottom auto-follow behavior', () => {
- 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 });
+ 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 });
+ 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 });
+ 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 });
+ expect(
+ resolveRenderPinDecision({
+ restoring: true,
+ newUserSend: true,
+ sentFromThisRenderer: false,
+ nearBottom: false,
+ }),
+ ).toEqual({ clearRestoring: false, pinToBottom: false });
});
});
describe('selectTailUserMessageId', () => {
type Item = { type: 'message'; id: string; role: 'user' | 'assistant' };
- const userMessageId = (item: Item | undefined) =>
- item?.role === 'user' ? item.id : null;
+ 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' };
@@ -330,17 +479,13 @@ describe('selectTailUserMessageId', () => {
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),
+ 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,
+ findLastMatching([{ id: 'a' }, { id: 'b' }], (item) => (item.id === 'b' ? item : null))?.id,
).toBe('b');
});
});
@@ -633,10 +778,7 @@ describe('resolveLastUserMessageObservation', () => {
describe('MessageStream send-window handoff wiring', () => {
it('clears any anchored window on a local send and only defers pin for stale slices', () => {
- const source = readFileSync(
- resolve(__dirname, '../components/chat/MessageStream.tsx'),
- 'utf8',
- );
+ const source = readFileSync(resolve(__dirname, '../components/chat/MessageStream.tsx'), 'utf8');
expect(source).toContain('resolveSendWindowHandoff({');
expect(source).toContain('if (windowHandoff.clearWindowAnchor)');
expect(source).toContain('if (decision.pinToBottom && !windowHandoff.deferPinToNextRender)');
diff --git a/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts b/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts
index d8f990b07e..dff7853bac 100644
--- a/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts
+++ b/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts
@@ -368,16 +368,35 @@ describe('MessageStream focus cancellation wiring', () => {
expect(collapseObserver).toContain('refreshHiddenChildViewportAnchor()');
});
+ it('clears the historical window anchor when wheel or touch restores follow', () => {
+ const pin = sourceBetween(
+ 'const pinAutoFollowForUserDownIntent = useCallback(() => {',
+ 'const scrollbarDragStartTopRef',
+ );
+ expect(pin).toContain('if (!windowCoversEndRef.current) return');
+ expect(pin).toContain('setUnreadCount(0)');
+ expect(pin).toContain('setFirstVisibleItemKey(null)');
+ });
+
it('cancels chip jumps on scrollbar mousedown as well as wheel and touch', () => {
const takeover = sourceBetween(
'const onWheel = (event: WheelEvent) => {',
- '}, [clearChipJumpSuppression, triggerUserIntentFill, unpinAutoFollowForUserUpIntent]);',
+ '}, [\n clearChipJumpSuppression,\n endScrollbarDrag,\n pinAutoFollowForUserDownIntent,\n triggerUserIntentFill,\n unpinAutoFollowForUserUpIntent,\n ]);',
);
expect(takeover).toContain('clearChipJumpSuppression();');
expect(takeover).toContain("root.addEventListener('mousedown', onMouseDown)");
+ expect(takeover).toContain("window.addEventListener('mousemove', onMouseMove)");
+ expect(takeover).toContain('isVerticalScrollbarPress({');
+ expect(takeover).toContain('shouldUnpinOnScrollbarDrag({');
+ expect(takeover).toContain('endScrollbarDrag()');
+ expect(takeover).toContain("window.addEventListener('pointercancel', onPointerCancel)");
+ expect(takeover).toContain("window.addEventListener('blur', onWindowBlur)");
+ expect(takeover).toContain("document.addEventListener('visibilitychange', onVisibilityChange)");
+ expect(takeover).toContain('shouldRepinOnWheel({');
+ expect(takeover).toContain('pinAutoFollowForUserDownIntent()');
});
- it('uses message-level neighbors only when the deleted child\'s render item survives', () => {
+ it("uses message-level neighbors only when the deleted child's render item survives", () => {
const compensation = sourceBetween(
'// ── 删除靠前 message 后的视口保位(#2289)──',
'// ── post-load auto-expand ──',
@@ -390,9 +409,7 @@ describe('MessageStream focus cancellation wiring', () => {
expect(compensation).toContain('resolveDeleteCompensationLanding(');
expect(compensation).toContain('queryVisibleAggregateContainer(root, survivorMessageId)');
expect(compensation).toContain('toRenderItemViewportSnapshot(');
- expect(compensation).not.toContain(
- 'if (anchor.messageClientId && snapshotMessageGone) {',
- );
+ expect(compensation).not.toContain('if (anchor.messageClientId && snapshotMessageGone) {');
});
it('finishes an older chip or rail navigation before starting a jump to bottom', () => {
@@ -417,8 +434,9 @@ describe('MessageStream focus cancellation wiring', () => {
'const settleChipJump = useCallback(',
);
expect(takeover).toContain(
- 'deferredDeleteCompensationRef.current ||\n chipJumpGenerationRef.current !== null ||\n focusJumpRef.current ||\n programmaticScrollRef.current',
+ 'deferredDeleteCompensationRef.current ||\n chipJumpGenerationRef.current !== null ||\n focusJumpRef.current',
);
+ expect(takeover).not.toContain('focusJumpRef.current ||\n programmaticScrollRef.current');
expect(takeover).toContain('unpinAutoFollowForUserUpIntent()');
expect(takeover).toContain('if (focusJumpRef.current)');
expect(takeover).toContain('cancelFocusJump()');
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 08bd26a128..60515be527 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -219,6 +219,25 @@ function hasNestedScrollableAncestorThatCanScrollUp(
return false;
}
+function hasNestedScrollableAncestorThatCanScrollDown(
+ root: HTMLElement,
+ target: EventTarget | null,
+): boolean {
+ let el = eventTargetElement(target);
+ while (el && el !== root) {
+ if (!root.contains(el)) return false;
+ const overflowY = window.getComputedStyle(el).overflowY;
+ const maxScroll = el.scrollHeight - el.clientHeight;
+ const canScroll =
+ (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') &&
+ maxScroll > SCROLL_DIRECTION_DEAD_ZONE_PX &&
+ el.scrollTop < maxScroll - SCROLL_DIRECTION_DEAD_ZONE_PX;
+ if (canScroll) return true;
+ el = el.parentElement;
+ }
+ return false;
+}
+
import { UserMessage } from './UserMessage';
import { AssistantMessage } from './AssistantMessage';
import { AskUserQuestionBubble } from './AskUserQuestionBubble';
@@ -298,6 +317,11 @@ import {
readFollowLatestRequestKey,
shouldBumpSendFollowCancelOnScroll,
subscribeFollowLatestRequests,
+ REPIN_AT_BOTTOM_PX,
+ isVerticalScrollbarPress,
+ shouldRepinOnDownIntent,
+ shouldRepinOnWheel,
+ shouldUnpinOnScrollbarDrag,
shouldUnpinOnUpIntent,
shouldUnpinOnWheel,
} from './autoFollowIntent';
@@ -1493,12 +1517,14 @@ export function buildRenderItems(
// 不把后续计划事件带进来,避免改变「正在复核哪张 insertion」的语义。
const validationMessages = [
...prefix,
- ...messages.slice(index + 1).filter(
- (message) =>
- message.role === 'tool_result' &&
- typeof message.toolUseId === 'string' &&
- prefixPlanToolUseIds.has(message.toolUseId),
- ),
+ ...messages
+ .slice(index + 1)
+ .filter(
+ (message) =>
+ message.role === 'tool_result' &&
+ typeof message.toolUseId === 'string' &&
+ prefixPlanToolUseIds.has(message.toolUseId),
+ ),
];
const stateAtInsertion = getLatestMessageTodoState(validationMessages, {
taskHistoryMayBeIncomplete: true,
@@ -3917,6 +3943,21 @@ export function MessageStream({
if (firstVisibleItemKey !== null && wasCovering && !windowCoversEnd) {
isNearBottomRef.current = false;
setIsNearBottom(false);
+ return;
+ }
+ // 锚定窗向下扩到真正盖住尾部,且用户已经贴在当前窗口底 → 切回默认尾窗并
+ // 恢复跟随。扩窗发生在本次 scroll 之后,同一帧的 handleScroll 还看不到
+ // windowCoversEnd=true,没有下一次滚动时会永远停在「已到底、但不跟」。
+ if (!wasCovering && windowCoversEnd && firstVisibleItemKey !== null) {
+ const el = scrollRef.current;
+ if (!el) return;
+ const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
+ if (distanceFromBottom <= REPIN_AT_BOTTOM_PX) {
+ isNearBottomRef.current = true;
+ setIsNearBottom(true);
+ setUnreadCount(0);
+ setFirstVisibleItemKey(null);
+ }
}
}, [firstVisibleItemKey, windowCoversEnd]);
@@ -4159,6 +4200,31 @@ export function MessageStream({
setIsNearBottom(false);
}, [sessionId]);
+ // 与 unpin 对称:用户已经贴死底部时的向下意图恢复跟随。不经过 scroll 事件 —
+ // 贴死底部后再往下滚通常不再改变 scrollTop。历史切片的底不是会话尾,不能从
+ // 那里开始跟随(与 resolveEffectiveNearBottom 同口径)。覆盖末尾的锚定窗也要
+ // 一并清掉,否则下一条 token 会 uncover 再 unpin。
+ const pinAutoFollowForUserDownIntent = useCallback(() => {
+ if (!windowCoversEndRef.current) return;
+ if (isNearBottomRef.current) return;
+ isNearBottomRef.current = true;
+ setIsNearBottom(true);
+ setUnreadCount(0);
+ setFirstVisibleItemKey(null);
+ }, []);
+
+ // 滚动条拖拽:只记按下时的 scrollTop。单纯 mousedown 不解除;上移过死区才 unpin。
+ // 按下期间停掉流式 pin,避免 programmatic 窗口把拖拽 scroll 吞掉后再钉回。
+ const scrollbarDragStartTopRef = useRef<number | null>(null);
+ const pinToBottomRef = useRef<() => void>(() => {});
+ // 拖拽态必须有界结束:mouseup / blur / pointercancel / 页签隐藏都走这里。
+ // Alt-Tab 后在别处松手收不到 mouseup,不清理则 pinToBottom 会永久提前返回。
+ const endScrollbarDrag = useCallback(() => {
+ if (scrollbarDragStartTopRef.current == null) return;
+ scrollbarDragStartTopRef.current = null;
+ if (isNearBottomRef.current) pinToBottomRef.current();
+ }, []);
+
// ── jump-to-bottom chip ──
// 用户向下滚动且未到底时显示扁平的"跳到底部" chip,2s 内无滚动自动隐藏。
// 与 NewMessageIndicator 互斥(它有未读时优先)。state 用 setter 直接控制,
@@ -4217,14 +4283,14 @@ export function MessageStream({
);
// wheel/touch/键盘接管:结束当前 smooth,但让期间延期的删除补偿重放。
const clearChipJumpSuppression = useCallback(() => {
- // 跳底会乐观置位贴底。接管后若仍贴底:流式 ResizeObserver 会 pinToBottom 拽回
- // 视口,延期删除重放也会被补偿 effect 直接跳过。有进行中的 chip / focus /
- // 跳底 generation 时一律解除,不只在已有延期删除时。
+ // 只在打断真正的导航跳转(chip / focus / 延期删除补偿)时解除跟随。
+ // 流式 pinToBottom 也会打开 programmaticScrollRef,把它算进接管条件会让
+ // 生成期间任意滚轮或点滚动条都把跟随掐死;人已经在底部时再也产生不了
+ // 向下 scroll,跟随就恢复不了。想离开底部走 wheel / 触控 / 键盘的上滚意图。
if (
deferredDeleteCompensationRef.current ||
chipJumpGenerationRef.current !== null ||
- focusJumpRef.current ||
- programmaticScrollRef.current
+ focusJumpRef.current
) {
unpinAutoFollowForUserUpIntent();
}
@@ -4390,6 +4456,20 @@ export function MessageStream({
unpinAutoFollowForUserUpIntent();
}
triggerUserIntentFill();
+ return;
+ }
+ if (event.deltaY > 0) {
+ if (hasNestedScrollableAncestorThatCanScrollDown(root, event.target)) return;
+ const distanceFromBottom = root.scrollHeight - root.scrollTop - root.clientHeight;
+ if (
+ shouldRepinOnWheel({
+ deltaX: event.deltaX,
+ deltaY: event.deltaY,
+ distanceFromBottom,
+ })
+ ) {
+ pinAutoFollowForUserDownIntent();
+ }
}
};
const onTouchStart = (event: TouchEvent) => {
@@ -4412,13 +4492,57 @@ export function MessageStream({
unpinAutoFollowForUserUpIntent();
}
triggerUserIntentFill();
+ return;
+ }
+ if (startY - currentY > TOUCH_HISTORY_INTENT_THRESHOLD_PX) {
+ userHistoryTouchStartYRef.current = currentY;
+ if (hasNestedScrollableAncestorThatCanScrollDown(root, event.target)) return;
+ const distanceFromBottom = root.scrollHeight - root.scrollTop - root.clientHeight;
+ if (shouldRepinOnDownIntent({ distanceFromBottom })) {
+ pinAutoFollowForUserDownIntent();
+ }
}
};
const onTouchEnd = () => {
userHistoryTouchStartYRef.current = null;
};
- const onMouseDown = () => {
+ const onMouseDown = (event: MouseEvent) => {
clearChipJumpSuppression();
+ if (
+ isVerticalScrollbarPress({
+ targetIsRoot: event.target === root,
+ offsetX: event.offsetX,
+ clientWidth: root.clientWidth,
+ })
+ ) {
+ scrollbarDragStartTopRef.current = root.scrollTop;
+ }
+ };
+ const onMouseMove = () => {
+ const startTop = scrollbarDragStartTopRef.current;
+ if (startTop == null) return;
+ if (
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: true,
+ scrollDelta: root.scrollTop - startTop,
+ directionDeadZonePx: SCROLL_DIRECTION_DEAD_ZONE_PX,
+ }) &&
+ shouldUnpinOnUpIntent({ scrollHeight: root.scrollHeight, clientHeight: root.clientHeight })
+ ) {
+ unpinAutoFollowForUserUpIntent();
+ }
+ };
+ const onMouseUp = () => {
+ endScrollbarDrag();
+ };
+ const onPointerCancel = () => {
+ endScrollbarDrag();
+ };
+ const onWindowBlur = () => {
+ endScrollbarDrag();
+ };
+ const onVisibilityChange = () => {
+ if (document.hidden) endScrollbarDrag();
};
root.addEventListener('wheel', onWheel, { passive: true });
root.addEventListener('touchstart', onTouchStart, { passive: true });
@@ -4426,6 +4550,11 @@ export function MessageStream({
root.addEventListener('touchend', onTouchEnd, { passive: true });
root.addEventListener('touchcancel', onTouchEnd, { passive: true });
root.addEventListener('mousedown', onMouseDown);
+ window.addEventListener('mousemove', onMouseMove);
+ window.addEventListener('mouseup', onMouseUp);
+ window.addEventListener('pointercancel', onPointerCancel);
+ window.addEventListener('blur', onWindowBlur);
+ document.addEventListener('visibilitychange', onVisibilityChange);
return () => {
root.removeEventListener('wheel', onWheel);
root.removeEventListener('touchstart', onTouchStart);
@@ -4433,8 +4562,19 @@ export function MessageStream({
root.removeEventListener('touchend', onTouchEnd);
root.removeEventListener('touchcancel', onTouchEnd);
root.removeEventListener('mousedown', onMouseDown);
+ window.removeEventListener('mousemove', onMouseMove);
+ window.removeEventListener('mouseup', onMouseUp);
+ window.removeEventListener('pointercancel', onPointerCancel);
+ window.removeEventListener('blur', onWindowBlur);
+ document.removeEventListener('visibilitychange', onVisibilityChange);
};
- }, [clearChipJumpSuppression, triggerUserIntentFill, unpinAutoFollowForUserUpIntent]);
+ }, [
+ clearChipJumpSuppression,
+ endScrollbarDrag,
+ pinAutoFollowForUserDownIntent,
+ triggerUserIntentFill,
+ unpinAutoFollowForUserUpIntent,
+ ]);
useEffect(() => {
const onHistoryNavigationKey = (event: KeyboardEvent) => {
if (!ownsHardwareScrollActions) return;
@@ -4466,6 +4606,8 @@ export function MessageStream({
const pinToBottom = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
+ // 滚动条拖拽中不要钉回,否则滑块上移会被下一帧 pin 吃掉。
+ if (scrollbarDragStartTopRef.current != null) return;
const generation = beginProgrammaticScroll();
suppressScrollbarActivation(el);
el.scrollTop = el.scrollHeight;
@@ -4478,6 +4620,7 @@ export function MessageStream({
}
});
}, [beginProgrammaticScroll, finishProgrammaticScroll, refreshViewportAnchor]);
+ pinToBottomRef.current = pinToBottom;
// 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
@@ -5091,7 +5234,8 @@ export function MessageStream({
const distanceFromBottom = el.scrollHeight - currentScrollTop - el.clientHeight;
const threshold = 100;
- if (!programmaticScrollRef.current) {
+ const draggingScrollbar = scrollbarDragStartTopRef.current != null;
+ if (!programmaticScrollRef.current || draggingScrollbar) {
// 用户手动滚动 = 接管浏览,退出「还原中」,后续恢复正常 auto-follow 判定。
restoringRef.current = false;
// 持续保存浏览位置(rAF 节流,DOM 必然存活),内含删除前快照刷新——纯滚动后
@@ -5106,6 +5250,18 @@ export function MessageStream({
// 覆盖,这里读的还是上一次值)。跟随态迁移与 jump-down chip 共用。
// programmatic scroll 不进本分支 — auto-follow 自己滚不该参与判定。
const delta = currentScrollTop - prevScrollTopRef.current;
+ // 滚动条上拖:前 100px 内 resolveNearBottomOnScroll 会保持跟随。流式 pin
+ // 下一帧又钉回,必须在这里按拖拽上移立即解除。
+ if (
+ shouldUnpinOnScrollbarDrag({
+ pointerDown: draggingScrollbar,
+ scrollDelta: delta,
+ directionDeadZonePx: SCROLL_DIRECTION_DEAD_ZONE_PX,
+ }) &&
+ shouldUnpinOnUpIntent({ scrollHeight: el.scrollHeight, clientHeight: el.clientHeight })
+ ) {
+ unpinAutoFollowForUserUpIntent();
+ }
// F2: 跟随态迁移(规则见 resolveNearBottomOnScroll 注释)。恢复跟随要求
// 明确向下滚 — 意图解除(wheel 上滚)后紧跟着的上滚 scroll 事件距底仍
@@ -5251,6 +5407,7 @@ export function MessageStream({
setFirstVisibleItemKey,
setAnchoredForwardItems,
sessionId,
+ unpinAutoFollowForUserUpIntent,
]);
// 渲染窗口下移到 render-item 轴后,U2 "末尾窗口全是 orphan tool_result"
diff --git a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts b/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts
index 778dcb9ed1..c85007f2b5 100644
--- a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts
+++ b/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts
@@ -15,9 +15,12 @@
* - **解除**:看用户输入意图,不看距离。wheel 上滚 / 触摸下拉 / PageUp 等
* 只有用户能产生(程序化 scrollTop 赋值不发 wheel 事件),没有上述竞态,
* 滚一行(哪怕一像素)立即解除,确定性响应。
- * - **恢复**:保留距离判定(距底 < threshold),但要求 scroll 事件方向向下 —
- * 否则解除跟随后紧跟着到达的那个用户上滚 scroll 事件(距底仍 < threshold)
- * 会把刚解除的跟随立刻翻回去,修复失效。
+ * - **恢复**:两条互补信号,都不能只看「距底 < 100」:
+ * 1. scroll 事件:距底 < threshold 且方向明确向下(防解除后紧跟的上滚
+ * scroll 把跟随立刻翻回去);
+ * 2. 用户已经贴死底部(距底 ≤ REPIN_AT_BOTTOM_PX)时的向下意图
+ * (wheel / 触控上滑)。人已经在最底时继续往下滚往往不再产生
+ * scroll 事件,只靠 1 会表现为「滚到最后了,新生成却不跟」。
*
* 抽成纯函数为了单测覆盖 + 与 React 副作用解耦,pattern 同
* scrollAnchoringDetect / viewportFillDetect。
@@ -33,6 +36,13 @@
*/
export const UNPIN_MIN_SCROLLABLE_PX = 1;
+/**
+ * 「已经贴死底部」的距离(px)。比 100px 近底阈值小一档:
+ * 典型一格滚轮约 40px,停在这里说明人就在视口底,不是刚上滚一格后的残留。
+ * 用于 wheel / 触控的恢复意图,以及 scroll 事件在 delta≈0 时的落地恢复。
+ */
+export const REPIN_AT_BOTTOM_PX = 8;
+
export interface WheelUnpinArgs {
/** wheel 事件的 deltaX(水平分量,用于主轴判定) */
deltaX: number;
@@ -84,6 +94,96 @@ export function shouldUnpinOnUpIntent({ scrollHeight, clientHeight }: UpIntentUn
return scrollHeight - clientHeight > UNPIN_MIN_SCROLLABLE_PX;
}
+export interface ScrollbarDragUnpinArgs {
+ /** 指针仍按在滚动容器上(滚动条拖拽中)。 */
+ pointerDown: boolean;
+ /** 相对按下时的 scrollTop 增量(负 = 向上)。 */
+ scrollDelta: number;
+ /** 方向判断死区(px)。 */
+ directionDeadZonePx: number;
+}
+
+/**
+ * 滚动条拖拽是否构成「用户想向上离开尾部」。
+ *
+ * 只认按下后的实际上移,不认单纯 mousedown:生成期间点一下滑块不该掐死跟随。
+ * 流式 pin 会把 programmatic scroll 窗口几乎一直打开,handleScroll 的普通
+ * 用户分支看不见这次拖拽,必须用按下态 + scrollTop 上移单独判定。
+ */
+export function shouldUnpinOnScrollbarDrag({
+ pointerDown,
+ scrollDelta,
+ directionDeadZonePx,
+}: ScrollbarDragUnpinArgs): boolean {
+ return pointerDown && scrollDelta < -directionDeadZonePx;
+}
+
+export interface VerticalScrollbarPressArgs {
+ /** mousedown 的 target 是否就是滚动容器本身。 */
+ targetIsRoot: boolean;
+ /** 相对滚动容器的 offsetX。 */
+ offsetX: number;
+ /** 滚动容器 clientWidth(不含纵向滚动条)。 */
+ clientWidth: number;
+}
+
+/**
+ * 这次 mousedown 是否落在纵向滚动条上。
+ *
+ * 滚动条生命周期不变量:
+ * - 进入拖拽:只有点到滑块/槽(target === 容器且 offsetX ≥ clientWidth);
+ * 正文、链接、按钮上的按下不能进拖拽态,否则长按选字会停 pin、松手又被钉回;
+ * - 拖拽中:抑制 pin,scrollTop 上移过死区才 unpin;
+ * - 松开:若仍在跟随,补一次 pin(按住期间最后一批 token 可能已经 settle)。
+ */
+export function isVerticalScrollbarPress({
+ targetIsRoot,
+ offsetX,
+ clientWidth,
+}: VerticalScrollbarPressArgs): boolean {
+ return targetIsRoot && offsetX >= clientWidth;
+}
+
+export interface WheelRepinArgs {
+ /** wheel 事件的 deltaX(水平分量,用于主轴判定) */
+ deltaX: number;
+ /** wheel 事件的 deltaY(正 = 向下) */
+ deltaY: number;
+ /** 当前距底距离(scrollHeight - scrollTop - clientHeight) */
+ distanceFromBottom: number;
+}
+
+/**
+ * wheel 事件是否构成「用户已在底部、应恢复 auto-follow」。
+ *
+ * 与 shouldUnpinOnWheel 对称:看意图不看「能不能再滚」。人已经贴死底部时
+ * 继续往下滚通常不再改变 scrollTop,handleScroll 收不到向下 delta,必须
+ * 在 wheel 层恢复。距底必须 ≤ REPIN_AT_BOTTOM_PX,避免刚上滚一格(约 40px)
+ * 后的回弹/惯性把跟随立刻翻回去。
+ */
+export function shouldRepinOnWheel({
+ deltaX,
+ deltaY,
+ distanceFromBottom,
+}: WheelRepinArgs): boolean {
+ if (deltaY <= 0) return false;
+ if (Math.abs(deltaY) < Math.abs(deltaX)) return false;
+ return distanceFromBottom <= REPIN_AT_BOTTOM_PX;
+}
+
+export interface DownIntentRepinArgs {
+ /** 当前距底距离(scrollHeight - scrollTop - clientHeight) */
+ distanceFromBottom: number;
+}
+
+/**
+ * 非 wheel 的向下意图(触摸上滑已过阈值)是否应恢复 auto-follow。
+ * 方向语义由 caller 的事件分支保证,这里只判「已经贴死底部」。
+ */
+export function shouldRepinOnDownIntent({ distanceFromBottom }: DownIntentRepinArgs): boolean {
+ return distanceFromBottom <= REPIN_AT_BOTTOM_PX;
+}
+
export interface SelectTailUserMessageArgs<T extends { type: string }> {
/** 当前有界窗口是否覆盖完整 render-item 尾部。 */
windowCoversEnd: boolean;
@@ -96,10 +196,7 @@ export interface SelectTailUserMessageArgs<T extends { type: string }> {
}
/** 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 {
+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;
@@ -294,6 +391,11 @@ export interface ResolveNearBottomArgs {
thresholdPx: number;
/** 方向判断死区(px),增量绝对值不超过它不算方向 */
directionDeadZonePx: number;
+ /**
+ * 「已经贴死底部」的距离(px)。已解除且距底不超过它、且不是上滚时恢复跟随。
+ * 人滚到最底后最后一次 scroll 常为 delta≈0,只靠向下方向会永远恢复不了。
+ */
+ atBottomPx?: number;
}
/**
@@ -309,6 +411,9 @@ export interface ResolveNearBottomArgs {
* - 距底 < threshold 且原本没在跟 → 只有明确向下(delta > 死区)才恢复
* 跟随。**不能只看距离**:意图解除后紧跟着到达的用户上滚 scroll 事件距底
* 仍 < threshold,若无方向守卫会把刚解除的跟随立刻翻回去(修复的核心)。
+ * - 已贴死底部(距底 ≤ atBottomPx)且不是上滚(delta ≥ 0)→ 恢复。人已经在
+ * 最底时最后一次 scroll 常为 delta≈0;1px 上滚解除后的 scroll 带负 delta,
+ * 不会误恢复。
*/
export function resolveNearBottomOnScroll({
wasNearBottom,
@@ -316,12 +421,14 @@ export function resolveNearBottomOnScroll({
scrollDelta,
thresholdPx,
directionDeadZonePx,
+ atBottomPx = REPIN_AT_BOTTOM_PX,
}: ResolveNearBottomArgs): boolean {
if (distanceFromBottom >= thresholdPx) {
if (!wasNearBottom) return false;
return scrollDelta >= -directionDeadZonePx;
}
if (wasNearBottom) return true;
+ if (distanceFromBottom <= atBottomPx && scrollDelta >= 0) return true;
return scrollDelta > directionDeadZonePx;
}
@@ -365,22 +472,15 @@ export function shouldApplyFollowLatestRequest(
const sendFollowCancelGenerations = new Map<string, number>();
-export function readSendFollowCancelGeneration(
- sessionId: string | null | undefined,
-): 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 {
+export function bumpSendFollowCancelGeneration(sessionId: string | null | undefined): void {
if (!sessionId) return;
- sendFollowCancelGenerations.set(
- sessionId,
- (sendFollowCancelGenerations.get(sessionId) ?? 0) + 1,
- );
+ sendFollowCancelGenerations.set(sessionId, (sendFollowCancelGenerations.get(sessionId) ?? 0) + 1);
}
export function shouldBumpSendFollowCancelOnScroll({
@@ -423,9 +523,7 @@ export function subscribeFollowLatestRequests(onStoreChange: () => void): () =>
};
}
-export function readFollowLatestRequestKey(
- sessionId: string | null | undefined,
-): number {
+export function readFollowLatestRequestKey(sessionId: string | null | undefined): number {
if (!sessionId) return 0;
return followLatestRequests.get(sessionId) ?? 0;
}
@@ -451,10 +549,7 @@ export function tryRequestFollowLatest({
return false;
}
if (!sourceSessionId) return false;
- followLatestRequests.set(
- sourceSessionId,
- (followLatestRequests.get(sourceSessionId) ?? 0) + 1,
- );
+ followLatestRequests.set(sourceSessionId, (followLatestRequests.get(sourceSessionId) ?? 0) + 1);
for (const listener of followLatestListeners) listener();
return true;
}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx
index f47a45626e..e97a8b7cf7 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx
@@ -64,7 +64,8 @@ vi.mock('@/lib/makerTransport', () => ({
// useSessionEstimatedValue 的历史初值入口:本套测试全部按本机会话走,直接委托给
// 下方 messageService mock(既有用例继续用它驱动/断言调用次数)。
estimatedSessionValueFor: vi.fn(async (sessionId: string) =>
- (await import('@/lib/messageService')).estimatedSessionValue(sessionId)),
+ (await import('@/lib/messageService')).estimatedSessionValue(sessionId),
+ ),
}));
vi.mock('@/lib/messageService', () => ({
@@ -114,7 +115,10 @@ vi.mock('@/lib/composerDraftStore', () => ({
import { useCCAgentChat } from '@/hooks/useCCAgentChat';
import { useSessionEstimatedValue } from '@/hooks/useSessionEstimatedValue';
-import { ChatDisplaySnapshotProvider, type ChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotContext';
+import {
+ ChatDisplaySnapshotProvider,
+ type ChatDisplaySnapshot,
+} from '@/components/chat/ChatDisplaySnapshotContext';
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import * as messageService from '@/lib/messageService';
import { buildTurnUsageDetails } from '../../../shared/turnUsageDetails';
@@ -176,7 +180,9 @@ function assistantCostMessage(clientId: string, costUsd: number): ChatMessage {
function displaySnapshot(
sessionId: string,
messages: ChatMessage[],
- options: Partial<Pick<ChatDisplaySnapshot, 'chatRealtime' | 'historyLoaded' | 'hasMoreMessages'>> = {},
+ options: Partial<
+ Pick<ChatDisplaySnapshot, 'chatRealtime' | 'historyLoaded' | 'hasMoreMessages'>
+ > = {},
): ChatDisplaySnapshot {
return {
sessionId,
@@ -192,7 +198,10 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
let turnCostListener: TurnCostListener | null = null;
beforeEach(() => {
- vi.mocked(messageService.estimatedSessionValue).mockResolvedValue({ totalValueUsd: 0, entries: [] });
+ vi.mocked(messageService.estimatedSessionValue).mockResolvedValue({
+ totalValueUsd: 0,
+ entries: [],
+ });
});
afterEach(() => {
@@ -213,8 +222,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
const loadOlder = vi.spyOn(makerChatStore, 'loadOlderMessages');
const { result, rerender } = renderHook(
- ({ live }: { live: boolean }) =>
- useCCAgentChat(sessionId, undefined, { chatRealtime: live }),
+ ({ live }: { live: boolean }) => useCCAgentChat(sessionId, undefined, { chatRealtime: live }),
{ initialProps: { live: true } },
);
@@ -267,17 +275,21 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
expect(sessionViewSource).toContain('key={sessionId}');
expect(messageStreamSource).toContain('if (isNearBottomRef.current) {');
expect(messageStreamSource).toContain('pinToBottom();');
- expect(messageStreamSource).toContain('if (!programmaticScrollRef.current) {');
+ expect(messageStreamSource).toContain(
+ 'if (!programmaticScrollRef.current || draggingScrollbar) {',
+ );
});
it('keeps session value consumers on the frozen display snapshot while hidden', async () => {
const sessionId = sid('hidden-consumers');
sessionIds.push(sessionId);
- (window as unknown as {
- electronAPI: {
- onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
- };
- }).electronAPI = {
+ (
+ window as unknown as {
+ electronAPI: {
+ onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
+ };
+ }
+ ).electronAPI = {
onUsageMessageTurnCost: (cb: TurnCostListener) => {
turnCostListener = cb;
return () => {
@@ -286,7 +298,9 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
},
};
const renderCounts = { estimated: 0 };
- const initialSnapshot = displaySnapshot(sessionId, [assistantCostMessage('visible-cost', 1.23)]);
+ const initialSnapshot = displaySnapshot(sessionId, [
+ assistantCostMessage('visible-cost', 1.23),
+ ]);
const latestSnapshot = displaySnapshot(sessionId, [
assistantCostMessage('visible-cost', 1.23),
assistantCostMessage('restored-cost', 4.56),
@@ -295,7 +309,9 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
function EstimatedValueProbe() {
renderCounts.estimated += 1;
const value = useSessionEstimatedValue(sessionId, true);
- return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;
+ return (
+ <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>
+ );
}
function TestTree({ snapshot }: { snapshot: ChatDisplaySnapshot }) {
@@ -332,11 +348,13 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
it('keeps direct turn-cost events live when a realtime display provider is present', async () => {
const sessionId = sid('visible-provider');
sessionIds.push(sessionId);
- (window as unknown as {
- electronAPI: {
- onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
- };
- }).electronAPI = {
+ (
+ window as unknown as {
+ electronAPI: {
+ onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
+ };
+ }
+ ).electronAPI = {
onUsageMessageTurnCost: (cb: TurnCostListener) => {
turnCostListener = cb;
return () => {
@@ -344,11 +362,16 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
};
},
};
- vi.mocked(messageService.estimatedSessionValue).mockResolvedValue({ totalValueUsd: 0, entries: [] });
+ vi.mocked(messageService.estimatedSessionValue).mockResolvedValue({
+ totalValueUsd: 0,
+ entries: [],
+ });
function EstimatedValueProbe() {
const value = useSessionEstimatedValue(sessionId, true);
- return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;
+ return (
+ <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>
+ );
}
render(
@@ -382,11 +405,13 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
it('pauses direct turn-cost events while frozen and refreshes once when realtime resumes', async () => {
const sessionId = sid('frozen-provider');
sessionIds.push(sessionId);
- (window as unknown as {
- electronAPI: {
- onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
- };
- }).electronAPI = {
+ (
+ window as unknown as {
+ electronAPI: {
+ onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
+ };
+ }
+ ).electronAPI = {
onUsageMessageTurnCost: (cb: TurnCostListener) => {
turnCostListener = cb;
return () => {
@@ -395,21 +420,24 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
},
};
const renderCounts = { estimated: 0 };
- vi.mocked(messageService.estimatedSessionValue)
- .mockResolvedValueOnce({
- totalValueMoney: usdEstimate(4.56),
- totalValueUsd: 4.56,
- entries: [{
+ vi.mocked(messageService.estimatedSessionValue).mockResolvedValueOnce({
+ totalValueMoney: usdEstimate(4.56),
+ totalValueUsd: 4.56,
+ entries: [
+ {
clientId: 'hidden-cost',
money: usdEstimate(4.56),
costUsd: 4.56,
- }],
- });
+ },
+ ],
+ });
function EstimatedValueProbe({ sessionId: currentSessionId }: { sessionId: string }) {
renderCounts.estimated += 1;
const value = useSessionEstimatedValue(currentSessionId, true);
- return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;
+ return (
+ <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>
+ );
}
const { rerender } = render(
@@ -473,16 +501,19 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
const nextSessionId = sid('next-provider');
sessionIds.push(clearedSessionId, staleSessionId, nextSessionId);
const pendingQueries = new Map<string, (value: EstimatedValueSnapshot) => void>();
- vi.mocked(messageService.estimatedSessionValue).mockImplementation((sessionId: string) =>
- new Promise((resolveQuery) => {
- pendingQueries.set(sessionId, resolveQuery);
- }),
+ vi.mocked(messageService.estimatedSessionValue).mockImplementation(
+ (sessionId: string) =>
+ new Promise((resolveQuery) => {
+ pendingQueries.set(sessionId, resolveQuery);
+ }),
);
- (window as unknown as {
- electronAPI: {
- onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
- };
- }).electronAPI = {
+ (
+ window as unknown as {
+ electronAPI: {
+ onUsageMessageTurnCost: (cb: TurnCostListener) => () => void;
+ };
+ }
+ ).electronAPI = {
onUsageMessageTurnCost: (cb: TurnCostListener) => {
turnCostListener = cb;
return () => {
@@ -493,7 +524,9 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
function EstimatedValueProbe({ sessionId: currentSessionId }: { sessionId: string }) {
const value = useSessionEstimatedValue(currentSessionId, true);
- return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;
+ return (
+ <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>
+ );
}
const { rerender } = render(
@@ -548,11 +581,13 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
pendingQueries.get(staleSessionId)?.({
totalValueMoney: usdEstimate(7.77),
totalValueUsd: 7.77,
- entries: [{
- clientId: 'stale-entry',
- money: usdEstimate(7.77),
- costUsd: 7.77,
- }],
+ entries: [
+ {
+ clientId: 'stale-entry',
+ money: usdEstimate(7.77),
+ costUsd: 7.77,
+ },
+ ],
});
});
expect(screen.getByTestId('estimated-value').textContent).toBe('');
@@ -561,11 +596,13 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
pendingQueries.get(nextSessionId)?.({
totalValueMoney: usdEstimate(3.21),
totalValueUsd: 3.21,
- entries: [{
- clientId: 'next-entry',
- money: usdEstimate(3.21),
- costUsd: 3.21,
- }],
+ entries: [
+ {
+ clientId: 'next-entry',
+ money: usdEstimate(3.21),
+ costUsd: 3.21,
+ },
+ ],
});
});