Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(ui): stream pacing for bursts, a bottom-follow glide that ends, copy feedback and mascot polish (#8260)
Milind Soni63bb251af7ab
diff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsxindex 479b65bba6..7fff77da08 100644--- a/src/components/Avatar.tsx+++ b/src/components/Avatar.tsx@@ -74,6 +74,7 @@ export type MausAvatarProps = {motionKey?: number;turn?: number;gaze?: { x?: number; y?: number };+ glance?: { x?: number; y?: number };spring?: number;eyeScale?: number;showMouth?: boolean;@@ -146,6 +147,7 @@ function GradientAvatarComponent(motionKey = 0,turn,gaze,+ glance,spring,eyeScale,showMouth,@@ -200,6 +202,7 @@ function GradientAvatarComponent(title={label ?? null}lookAround={lookAround ?? (forward ? 0 : 1)}gaze={gaze}+ glance={glance}turn={turn}spring={spring}eyeScale={eyeScale}diff --git a/src/components/ChatHeadPill.tsx b/src/components/ChatHeadPill.tsxindex cbaf72380b..ddfa59b693 100644--- a/src/components/ChatHeadPill.tsx+++ b/src/components/ChatHeadPill.tsx@@ -6,6 +6,7 @@ import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import type { Bot } from "@/state/store"; import { useStoreSelector } from "@/state/store-select";import { awayFromMainThread } from "@/state/thread-navigation";+import { useComposerFocused } from "@/lib/composer-focus";import { BotAvatar } from "./Avatar";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";import { sidebarBotActivityTasks } from "./SidebarBotActivity";@@ -17,6 +18,7 @@ import { ThreadSwitcherPill } from "./ThreadSwitcherPill";/** The factory title a new conversation starts with. */const UNTITLED = "New thread";const CHEVRON_MOTION = "duration-[140ms] ease-[cubic-bezier(.22,1,.36,1)]";+const COMPOSER_GLANCE = { x: 0, y: 0.36 } as const;export type ChatHeadPrivacy = { kind: "private" } | { kind: "ownHelper" } | { kind: "shared"; team: string; onlyPeopleAdded?: boolean; sharedWith?: string } | null;@@ -43,6 +45,8 @@ export function ChatHeadPill({ bot, avatar, privacy, onToggle, switcher = falseonToggle: () => void;}) {const open = useStoreSelector((state) => state.settingsOpen), pendingQueued = useStoreSelector((state) => state.pendingQueued);+ const composerFocused = useComposerFocused(bot.threadId);+ const glance = composerFocused && !bot.busy ? COMPOSER_GLANCE : undefined;const elsewhere = sidebarBotActivityTasks(bot, pendingQueued).filter((task) => task.threadId !== bot.threadId).length;const privacyLabel = privacyLabelOf(privacy);const PrivacyIcon = privacy ? PRIVACY_ICONS[privacy.kind] : Users;@@ -54,7 +58,7 @@ export function ChatHeadPill({ bot, avatar, privacy, onToggle, switcher = falseconst tabs = useMemo(() => (switcher ? threadTabs(bot) : []), [switcher, bot.id, bot.threadId, bot.switchingTo, bot.mainThreadId, bot.tasks, bot.busy]);if (showsTabs(tabs)) {const head = <>- <BotAvatar bot={bot} size={28} {...avatar} />+ <BotAvatar bot={bot} size={28} {...avatar} glance={glance} /><span dir="auto" className="min-w-0 truncate text-[14px] font-medium leading-5">{bot.name}</span>{privacyLabel && <span data-chathead-privacy={privacy?.kind} title={privacyLabel} className="flex shrink-0 text-ink-tertiary"><PrivacyIcon size={13} aria-hidden="true" /><span className="sr-only">{privacyLabel}</span></span>}{elsewhere > 0 && <span role="img" data-chathead-elsewhere aria-label={t("task.otherActivity", { count: elsewhere })} className="size-1.5 shrink-0 rounded-full bg-accent" />}@@ -73,7 +77,7 @@ export function ChatHeadPill({ bot, avatar, privacy, onToggle, switcher = falsearia-controls={open ? BOT_PANEL_ID : undefined}className={cn("group flex min-w-0 max-w-full items-center gap-2 rounded-full py-[5.5px] pl-[5.5px] pr-[13.5px] text-ink", ELEVATED_FLOAT, ELEVATED_HOVER)}>- <BotAvatar bot={bot} size={28} {...avatar} />+ <BotAvatar bot={bot} size={28} {...avatar} glance={glance} /><span dir="auto" className="min-w-0 truncate text-[14px] font-medium leading-5">{bot.name}</span>{conversation && (<>diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsxindex 4c63ac665c..30dff9b676 100644--- a/src/components/ChatMarkdown.tsx+++ b/src/components/ChatMarkdown.tsx@@ -4,7 +4,7 @@ import Markdown, { defaultUrlTransform, type Components, type ExtraProps, type Oimport remarkGfm from "remark-gfm";import remarkMath from "remark-math";import { fromMarkdown, type Options as MarkdownParseOptions } from "mdast-util-from-markdown";-import { Check, Copy, Download, Eye, FolderOpen, LoaderCircle, RotateCcw, WrapText, X } from "lucide-react";+import { Check, Download, Eye, FolderOpen, LoaderCircle, RotateCcw, WrapText } from "lucide-react"; import { CopyFeedbackIcon } from "./CopyFeedbackIcon";import { useCopyFeedback } from "@/lib/copy-text";import { t } from "@/lib/i18n";import { cn } from "@/lib/cn";@@ -336,17 +336,17 @@ export function MermaidDiagram({ code }: MermaidDiagramProps) {>{copied === "failed" ? (<>- <X size={12} className="text-danger" aria-hidden="true" />+ <CopyFeedbackIcon state="failed" size={12} /><span className="text-danger font-medium hidden sm:inline">{t("common.copyFailed")}</span></>) : copied === "copied" ? (<>- <Check size={12} className="text-success" aria-hidden="true" />+ <CopyFeedbackIcon state="copied" size={12} /><span className="text-success font-medium hidden sm:inline">{t("chat.code.copiedShort")}</span></>) : (<>- <Copy size={12} aria-hidden="true" />+ <CopyFeedbackIcon state="idle" size={12} /><span className="hidden sm:inline">{t("common.copy")}</span></>)}diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsxindex ae03b2b79a..05a932eeff 100644--- a/src/components/CodeBlock.tsx+++ b/src/components/CodeBlock.tsx@@ -1,7 +1,8 @@// Security: Shiki's output is generator-escaped; nothing else reaches the DOM as HTML.import { useEffect, useMemo, useRef, useState } from "react";import type { HighlighterCore } from "shiki/core";-import { Check, Copy, Download, MoreHorizontal, WrapText, X } from "lucide-react";+import { Download, MoreHorizontal, WrapText } from "lucide-react";+import { CopyFeedbackIcon } from "./CopyFeedbackIcon";import { cn } from "@/lib/cn";import { useCopyFeedback } from "@/lib/copy-text";@@ -186,9 +187,7 @@ export function CodePlate({ copied, onCopy, copyLabel, items }: {<button type="button" onClick={onCopy} className={PLATE_BUTTON}title={copied === "copied" ? t("code.copiedTitle") : copied === "failed" ? t("common.copyFailed") : copyLabel}aria-label={copied === "copied" ? t("code.copiedTitle") : copied === "failed" ? t("common.copyFailed") : copyLabel}>- {copied === "failed" ? <X size={16} className="text-danger" aria-hidden="true" />- : copied === "copied" ? <Check size={16} className="text-success" aria-hidden="true" />- : <Copy size={16} aria-hidden="true" />}+ <CopyFeedbackIcon state={copied} size={16} /></button>{copied !== "idle" && <span role="status" className="sr-only">{copied === "failed" ? t("common.copyFailed") : t("code.copiedTitle")}</span>}<SidebarPopoverMenu items={items} ariaLabel={t("chat.more")} placement="above" align="end" triggerTitle={t("chat.more")}@@ -317,9 +316,7 @@ export function CodeBlock({ code, lang, initialWrap = false, open = false }: Codtitle={copied === "copied" ? t("code.copiedTitle") : copied === "failed" ? t("common.copyFailed") : t("code.copyTitle")}aria-label={copied === "copied" ? t("code.copiedAria") : copied === "failed" ? t("common.copyFailed") : t("code.copyAria")}>- {copied === "failed" ? <X size={12} className="text-danger" aria-hidden="true" />- : copied === "copied" ? <Check size={12} className="text-success" aria-hidden="true" />- : <Copy size={12} aria-hidden="true" />}+ <CopyFeedbackIcon state={copied} size={12} /><span aria-hidden="true" className="hidden max-sm:inline touch:inline">{t("code.copy")}</span><span role="status" className={`max-sm:sr-only touch:sr-only ${copied === "failed" ? "text-danger font-medium" : copied === "copied" ? "text-success font-medium" : ""}`}>{copied === "failed" ? t("common.copyFailed") : copied === "copied" ? t("code.copied") : t("code.copy")}diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex f9fd53eb3d..f50affb33c 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -7,7 +7,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type SetStateActionimport { Mic, Square } from "lucide-react";import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";import { visibleMessages, currentTaskBot, type Action, type Bot, type Group, type InstanceInfo, type Message } from "@/state/store";-import { cn } from "@/lib/cn";+import { cn } from "@/lib/cn"; import { useComposerFocusHandlers } from "@/lib/composer-focus"; import { tapHaptic } from "@/lib/haptics";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";import { useMenuMotion } from "./MenuMotion";import { ELEVATED_CARD, ELEVATED_COMPOSER, ELEVATED_FLOAT } from "./elevated";@@ -239,7 +239,7 @@ export function Composer({branchLeafId: group ? undefined : bot?.activeLeafId ?? undefined, draftId, text, editText, stopDictation });const micShown = !locked && !busy && micReady;const [caret, setCaret] = useState(0);- const shellRef = useRef<HTMLDivElement>(null);+ const shellRef = useRef<HTMLDivElement>(null); const composerFocus = useComposerFocusHandlers(threadId);const tall = useTallPill(shellRef, simpleDock);const multiline = simpleDock && (tall || text.includes("\n"));const [highlight, setHighlight] = useState(0);@@ -824,7 +824,7 @@ export function Composer({)}<MentionTextareawrapperClassName={stacked ? "basis-full" : undefined} ghost={suggestion.text ? <SuggestedReplyGhost text={suggestion.text} onUse={suggestion.accept} /> : undefined}- inputRef={inputRef}+ inputRef={inputRef} {...composerFocus}peers={[...(group ? [...(members ?? []), ...(group.dm ? [] : departmentChoices(members ?? []))] : bots.filter((member) => member.id !== bot?.id)), ...teammates.peers]}everyone={Boolean(group && !group.dm)}dir="auto"@@ -943,7 +943,7 @@ export function Composer({<div data-composer-actions style={composerOrderStyle(composerLayout.order)} className={cn("flex items-center", simpleDock ? "gap-2" : "gap-1", stacked && "ms-auto")}>{(simpleDock ? stoppable : busy && mayStop) && !locked && (<button- onClick={interruptTurn} data-composer-end="stop"+ onClick={() => { tapHaptic(); interruptTurn(); }} data-composer-end="stop"aria-label={t("chat.stopTurn")}data-composer-stop={simpleDock ? (stopInSlot ? "slot" : "beside") : undefined}className={cn(diff --git a/src/components/ComposerSendButton.tsx b/src/components/ComposerSendButton.tsxindex 024789907f..e36ee7e289 100644--- a/src/components/ComposerSendButton.tsx+++ b/src/components/ComposerSendButton.tsx@@ -3,6 +3,7 @@ import { ArrowUp, ChevronUp, Clock, CornerDownRight, RotateCcw } from "lucide-reimport type { FollowUp } from "../../shared/follow-up";import { cn } from "@/lib/cn";+import { tapHaptic } from "@/lib/haptics";import { t } from "@/lib/i18n";import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";@@ -33,7 +34,7 @@ export function ComposerSendButton({ compact, waits, label, title, look, disableconst alternate = menu?.choices[1] !== "restart" ? menu?.choices[1] : undefined;const button = (<button- onClick={(event) => onSend(event.metaKey || event.ctrlKey)} data-composer-send=""+ onClick={(event) => { tapHaptic(); onSend(event.metaKey || event.ctrlKey); }} data-composer-send=""disabled={disabled}aria-label={label}title={menu && alternate ? t("composer.followUp.buttonTitle", { title, key: menu.alternateKey, alternate: t(`composer.followUp.${alternate}`) }) : title}diff --git a/src/components/CopyFeedbackIcon.tsx b/src/components/CopyFeedbackIcon.tsxnew file mode 100644index 0000000000..0fab6b7b77--- /dev/null+++ b/src/components/CopyFeedbackIcon.tsx@@ -0,0 +1,14 @@+import { Check, Copy, X } from "lucide-react";+import { cn } from "@/lib/cn";+import type { CopyFeedback } from "@/lib/copy-text";++/** Copy, Check or X in one slot; only the feedback icons play in. */+export function CopyFeedbackIcon({ state, size = 14, strokeWidth, className }: { state: CopyFeedback; size?: number; strokeWidth?: number; className?: string }) {+ if (state === "failed") {+ return <X key="failed" size={size} strokeWidth={strokeWidth} className={cn("animate-icon-morph text-danger", className)} aria-hidden="true" />;+ }+ if (state === "copied") {+ return <Check key="copied" size={size} strokeWidth={strokeWidth} className={cn("check-in text-success", className)} aria-hidden="true" />;+ }+ return <Copy key="idle" size={size} strokeWidth={strokeWidth} className={className} aria-hidden="true" />;+}diff --git a/src/components/CursorAvatar.tsx b/src/components/CursorAvatar.tsxindex df4a138c3e..e3de417622 100644--- a/src/components/CursorAvatar.tsx+++ b/src/components/CursorAvatar.tsx@@ -17,7 +17,7 @@ import {} from "./cursor-face-data"import {BLEND_OMEGA, COMPACT_MASCOT_PX, FRAME_SLACK_MS, GLYPH_EASE_MS, HOVER_BLINK_MS, MOTION, PoseBlend, REST_POSE, VIEW_SPAN, blinkOpenness, bodyPose,- bodyTransform, faceTravelUnits, frameFloorMs, loopSeed, morphUnitsPerMs, nextFrameAt, nextMascotFrame, poseTransform, restPose, type BodyMotion,+ bodyTransform, faceTravelUnits, frameFloorMs, loopSeed, morphUnitsPerMs, nextFrameAt, nextMascotFrame, poseTransform, restPose, specularTransform, type BodyMotion,} from "./mascot-motion"import { mascotClock, put, usePrefersReducedMotion, type MascotTicket } from "./mascot-clock"@@ -504,7 +504,7 @@ export interface CursorAvatarProps {state?: CursorStateexpression?: numbersize?: number | string- gaze?: { x?: number; y?: number }+ gaze?: { x?: number; y?: number }; glance?: { x?: number; y?: number }turn?: numberlookAround?: numberflip?: boolean@@ -555,7 +555,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProstate = 'idle',expression,size = 160,- gaze,+ gaze, glance,turn = 0,lookAround = 0.5,flip = false,@@ -585,7 +585,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst eye0 = useRef<SVGPathElement | null>(null)const eye1 = useRef<SVGPathElement | null>(null)const mouth = useRef<SVGPathElement | null>(null)- const faceShift = useRef<SVGGElement | null>(null)+ const faceShift = useRef<SVGGElement | null>(null), gradRef = useRef<SVGLinearGradientElement | null>(null)const bodyGroup = useRef<SVGGElement | null>(null)const bodyContent = useRef<SVGGElement | null>(null)const trailLayer = useRef<SVGGElement | null>(null)@@ -599,23 +599,8 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst paint = `url(#${uid}-grad)`const sizePx = typeof size === 'number' ? size : 160const props = {- state,- expression,- gaze,- turn,- flip,- spring,- eyeScale,- resting,- reduced,- lookAround,- motionStrength,- effects,- glyphs,- autoBlink,- paint,- sizePx,- compact: sizePx <= COMPACT_MASCOT_PX,+ state, expression, gaze, glance, turn, flip, spring, eyeScale, resting, reduced, lookAround,+ motionStrength, effects, glyphs, autoBlink, paint, sizePx, compact: sizePx <= COMPACT_MASCOT_PX,}const engine = useRef({@@ -712,10 +697,14 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProreturn () => clearTimeout(timer)}, [state, autoExpression, expression, resting, reduced])+ useEffect(() => { engine.current.faceStale = true; wake() }, [state, expression, gaze?.x, gaze?.y, turn, eyeScale, lookAround, resting, reduced, motionStrength, effects, glyphs, paint, showMouth, size, autoBlink])useEffect(() => {- engine.current.faceStale = true- wake()- }, [state, expression, gaze?.x, gaze?.y, turn, eyeScale, lookAround, resting, reduced, motionStrength, effects, glyphs, paint, showMouth, size, autoBlink])+ const e = engine.current+ if (e.hovered) return+ const nx = !reduced && glance ? clamp(glance.x ?? 0, -1, 1) : 0, ny = !reduced && glance ? clamp(glance.y ?? 0, -1, 1) : 0+ if (nx === e.lookTarget[0] && ny === e.lookTarget[1]) return+ e.lookTarget = [nx, ny]; wake()+ }, [glance?.x, glance?.y, reduced])useEffect(() => {const el = svg.current@@ -730,8 +719,9 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProdoc.removeEventListener('pointermove', follow)doc.documentElement.removeEventListener('pointerleave', stop)const e = engine.current+ const g = e.props.glancee.hovered = false- e.lookTarget = [0, 0]+ e.lookTarget = !e.props.reduced && g ? [clamp(g.x ?? 0, -1, 1), clamp(g.y ?? 0, -1, 1)] : [0, 0]wake()}const follow = (event: PointerEvent) => {@@ -859,6 +849,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProconst fy = e.look[1] * GAZE_TRAVEL.yput(faceShift.current, 'transform', Math.abs(fx) < 0.005 && Math.abs(fy) < 0.005 ? null : `translate(${fx.toFixed(2)} ${fy.toFixed(2)})`)}+ if (gradRef.current) put(gradRef.current, 'gradientTransform', specularTransform(e.look[0], e.look[1], pose.fx))}const drawEffects = (e: typeof engine.current, now: number, showEffects: boolean, showGlyphs: boolean) => {@@ -1007,7 +998,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarProaria-hidden={label ? undefined : true}><defs>- <linearGradient id={`${uid}-grad`} x1="1" y1="0" x2="0" y2="1">+ <linearGradient ref={gradRef} id={`${uid}-grad`} x1="1" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={gradient[0]} /><stop offset="55%" stopColor={gradient[1]} /><stop offset="100%" stopColor={gradient[2]} />diff --git a/src/components/MessageActions.tsx b/src/components/MessageActions.tsxindex 40e6ba2038..6dfb3fcb28 100644--- a/src/components/MessageActions.tsx+++ b/src/components/MessageActions.tsx@@ -1,5 +1,6 @@import { Children, createContext, use, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";-import { Check, Copy, Ellipsis, Reply, X } from "lucide-react";+import { Ellipsis, Reply } from "lucide-react";+import { CopyFeedbackIcon } from "./CopyFeedbackIcon";import { popoverClosesOnKey, usePopoverDismiss } from "@/hooks/use-popover-dismiss";import { cn } from "@/lib/cn";import { useCopyFeedback } from "@/lib/copy-text";@@ -326,7 +327,7 @@ export function CopyButton({ text, className }: { text: string; className?: striclassName,)}>- {state === "copied" ? <Check {...ACTION_ICON} className="text-success" /> : state === "failed" ? <X {...ACTION_ICON} className="text-danger" /> : <Copy {...ACTION_ICON} />}+ <CopyFeedbackIcon state={state} {...ACTION_ICON} /></button>);}diff --git a/src/components/TurnNarrationRun.tsx b/src/components/TurnNarrationRun.tsxindex c87b3516a6..f8d0beffd9 100644--- a/src/components/TurnNarrationRun.tsx+++ b/src/components/TurnNarrationRun.tsx@@ -33,7 +33,7 @@ export const TurnNarrationRun = memo(function TurnNarrationRun({ label, title, f><Check size={13} className="text-success" /><span>{label}</span>- <ChevronRight size={13} className={open ? "rotate-90" : undefined} />+ <ChevronRight size={13} className={open ? "chevron-turn rotate-90" : "chevron-turn"} /></button></div>{open && (steps ? steps.map(step) : children)}diff --git a/src/components/mascot-motion.ts b/src/components/mascot-motion.tsindex 533186da05..472530f634 100644--- a/src/components/mascot-motion.ts+++ b/src/components/mascot-motion.ts@@ -406,3 +406,11 @@ export function faceTravelUnits(from.mouth.forEach((value, i) => { travel = Math.max(travel, Math.abs(to.mouth[i] - value)); });return travel + Math.hypot(to.gaze[0] - from.gaze[0], to.gaze[1] - from.gaze[1]);}++/** Subtle counter-shifted gradient highlight so the mascot's lighting rolls smoothly with gaze and lean. */+export function specularTransform(lookX: number, lookY: number, poseFx: number): string | null {+ const dx = -(lookX * 0.14 + poseFx * 0.008);+ const dy = -(lookY * 0.14);+ if (Math.abs(dx) < 0.003 && Math.abs(dy) < 0.003) return null;+ return `translate(${dx.toFixed(3)} ${dy.toFixed(3)})`;+}diff --git a/src/components/smooth-micro-transitions.dom.test.ts b/src/components/smooth-micro-transitions.dom.test.tsnew file mode 100644index 0000000000..4ad4a5832a--- /dev/null+++ b/src/components/smooth-micro-transitions.dom.test.ts@@ -0,0 +1,66 @@+// @vitest-environment happy-dom+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { createElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it } from "vitest";+import { TurnNarrationRun } from "./TurnNarrationRun";+import { CopyFeedbackIcon } from "./CopyFeedbackIcon";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(() => {+ document.body.innerHTML = "";+});++function mount() {+ const host = document.createElement("div");+ document.body.appendChild(host);+ return { host, root: createRoot(host) };+}++describe("smooth micro-transitions", () => {+ it("draws the resting copy icon still, so code blocks and messages mount without motion", () => {+ const { host, root } = mount();+ act(() => root.render(createElement(CopyFeedbackIcon, { state: "idle", size: 17, strokeWidth: 1.5 })));+ const icon = host.querySelector("svg")!;+ expect(icon.getAttribute("class")).not.toMatch(/animate|check-in/);+ expect(icon.getAttribute("stroke-width")).toBe("1.5");++ act(() => root.render(createElement(CopyFeedbackIcon, { state: "copied", size: 17, strokeWidth: 1.5 })));+ expect(host.querySelector(".check-in")).not.toBeNull();++ act(() => root.render(createElement(CopyFeedbackIcon, { state: "failed", size: 17, strokeWidth: 1.5 })));+ expect(host.querySelector(".check-in")).toBeNull();+ expect(host.querySelector(".animate-icon-morph")).not.toBeNull();+ act(() => root.unmount());+ });++ it("turns the narration chevron and shows the steps at once, with no animated panel", () => {+ const { host, root } = mount();+ act(() => root.render(createElement(TurnNarrationRun, { label: "2 steps", children: createElement("div", { "data-testid": "step" }, "Read file") } as never)));+ const toggle = host.querySelector("button")!;+ expect(host.querySelector("svg.chevron-turn")).not.toBeNull();+ expect(host.querySelector('[data-testid="step"]')).toBeNull();++ act(() => toggle.click());+ expect(host.querySelector('[data-testid="step"]')).not.toBeNull();+ expect(host.querySelector("svg.chevron-turn")?.getAttribute("class")).toContain("rotate-90");++ act(() => toggle.click());+ expect(host.querySelector('[data-testid="step"]'), "closing is instant").toBeNull();+ act(() => root.unmount());+ });++ it("switches every new animation off under both reduced-motion settings", () => {+ const css = readFileSync(join(process.cwd(), "src", "styles.css"), "utf8");+ const media = css.slice(css.indexOf("@media (prefers-reduced-motion: reduce) {\n .turn-now-card"));+ const block = media.slice(0, media.indexOf("\n}\n"));+ const flagged = media.slice(0, media.indexOf("animation: none !important;"));+ for (const name of ["animate-icon-morph", "chevron-turn", "turn-phrase-in"]) {+ expect(block, `${name} under prefers-reduced-motion`).toContain(`.${name}`);+ expect(flagged, `${name} under data-reduced-motion`).toContain(`:root[data-reduced-motion="true"] .${name}`);+ }+ });+});diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.tsindex 7efd678cc4..fa8e1def0e 100644--- a/src/hooks/use-transcript-viewport.test.ts+++ b/src/hooks/use-transcript-viewport.test.ts@@ -879,8 +879,24 @@ describe("following a reply and coming back to a conversation", () => {expect(scroller.calls.at(-1)).toEqual({ top: scroller.scrollHeight });noteLiveReplyEvent({ eventId: "d1", provider: "claudeAgent", threadId: "thread", createdAt: "", turnId: "t", type: "content.delta", streamKind: "assistant_text", delta: "Streaming words " } as RuntimeEvent);+ const from = scroller.scrollTop;grow();- expect(scroller.calls.at(-1)).toEqual({ top: scroller.scrollHeight, behavior: "smooth" });+ expect(scroller.scrollTop, "the glide starts on the next frame").toBe(from);+ const seen: number[] = [];+ const start = performance.now();+ for (let frame = 1; frame <= 60 && frames.length; frame++) {+ const queued = frames;+ frames = [];+ for (const run of queued) run(start + frame * 16);+ seen.push(scroller.scrollTop);+ view.current.scrollHandlers.onScroll();+ }+ for (const run of frames.splice(0)) run(start + 61 * 16);+ expect(frames, "the glide stops once it arrives").toEqual([]);+ expect(seen.indexOf(scroller.bottom), "it took several frames").toBeGreaterThan(3);+ expect(seen, "only ever down").toEqual([...seen].sort((a, b) => a - b));+ expect(scroller.scrollTop).toBe(scroller.bottom);+ expect(view.current.following, "its own scroll events do not let go of the end").toBe(true);readUpTo(view, 100);const calls = scroller.calls.length;@@ -890,6 +906,32 @@ describe("following a reply and coming back to a conversation", () => {expect(scroller.scrollTop).toBe(100);});+ const takeovers: Array<[string, (view: ReturnType<typeof mount>) => void]> = [+ ["a wheel or trackpad flick up", (view) => view.current.scrollHandlers.onWheel({ deltaY: -4 } as never)],+ ["a scroll key", () => press("PageUp")],+ ["a grab of the scrollbar", (view) => view.current.scrollHandlers.onPointerDown({ target: scroller, nativeEvent: { offsetX: 404 } } as never)],+ ["a finger dragging down", (view) => {+ view.current.scrollHandlers.onTouchStart({ touches: [{ clientY: 100 }] } as never);+ view.current.scrollHandlers.onTouchMove({ touches: [{ clientY: 110 }] } as never);+ }],+ ];+ for (const [input, takeOver] of takeovers) {+ it(`stops gliding after a streaming reply on the instant of ${input}`, () => {+ const view = mount({ messages: rows(20) });+ noteLiveReplyEvent({ eventId: "d1", provider: "claudeAgent", threadId: "thread", createdAt: "", turnId: "t", type: "content.delta", streamKind: "assistant_text", delta: "Streaming words " } as RuntimeEvent);+ scroller.extra += 120;+ for (const callback of resized) callback();+ const start = performance.now();+ for (const run of frames.splice(0)) run(start + 16);+ const at = scroller.scrollTop;+ expect(at, "the glide had begun").toBeGreaterThan(scroller.bottom - 120);+ view.act(() => takeOver(view));+ for (let frame = 2; frame < 30; frame++) for (const run of frames.splice(0)) run(start + frame * 16);+ expect(view.current.following).toBe(false);+ expect(scroller.scrollTop, "no write after the reader took over").toBe(at);+ });+ }+it("offers Jump to latest only a moment after the reader leaves the end, and hides it at once on return", () => {vi.useFakeTimers();try {diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.tsindex 4ef4fa61d4..c089696331 100644--- a/src/hooks/use-transcript-viewport.ts+++ b/src/hooks/use-transcript-viewport.ts@@ -11,7 +11,7 @@ import {type TouchEvent,type WheelEvent,} from "react";-import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, useBottomFollowResize } from "@/lib/bottom-follow";+import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, haltBottomChase, useBottomFollowResize } from "@/lib/bottom-follow";import { afterPaint } from "@/lib/after-paint";import { useFocusMessage } from "@/lib/focus-message";import { settleNearScreen } from "@/lib/on-screen";@@ -264,9 +264,9 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({followNow.current = { key: followNow.current.key, follow: after };followRef.current = after.mode === "following";const el = scrollRef.current;- if (el && before.mode === "following" && after.mode === "released" && smoothFollow()) {- // A smooth follow scroll keeps running after the reader takes over; an instant scroll to where it is halts it.- el.scrollTo({ top: el.scrollTop });+ if (el && before.mode === "following" && after.mode === "released") {+ haltBottomChase(el);+ if (smoothFollow()) el.scrollTo({ top: el.scrollTop });}if (after.mode === "following") rememberTranscriptPosition(followNow.current.key, { atEnd: true });setFollowShown(after);@@ -345,6 +345,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({const el = scrollRef.current;if (!el) return;if (!followRef.current) return noteLeftEnd();+ haltBottomChase(el);el.scrollTo({ top: el.scrollHeight });lastTop.current = el.scrollTop;// eslint-disable-next-line react-hooks/exhaustive-deps -- pinOn is the caller's dependency listdiff --git a/src/lib/bottom-follow.test.ts b/src/lib/bottom-follow.test.tsindex f68f9a14ec..a928b94e68 100644--- a/src/lib/bottom-follow.test.ts+++ b/src/lib/bottom-follow.test.ts@@ -1,6 +1,61 @@-import { describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { followBottomGrowth } from "./bottom-follow";+import { followBottomGrowth, haltBottomChase } from "./bottom-follow";++let now = 1_000;+let pending = new Map<number, FrameRequestCallback>();+let nextId = 1;++beforeEach(() => {+ now = 1_000;+ pending = new Map();+ nextId = 1;+ vi.spyOn(performance, "now").mockImplementation(() => now);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ pending.set(nextId, callback);+ return nextId++;+ });+ vi.stubGlobal("cancelAnimationFrame", (id: number) => void pending.delete(id));+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function frame(ms: number) {+ now += ms;+ const batch = [...pending.values()];+ pending.clear();+ for (const callback of batch) callback(now);+}++/** A scroller that snaps every scrollTop write the way a browser does, and clamps it to its end. */+function scrollerWith(snap: (top: number) => number, { scrollHeight = 1_100, clientHeight = 500, scrollTop = 500 } = {}) {+ let top = scrollTop;+ const scroller = {+ scrollHeight,+ clientHeight,+ calls: [] as ScrollToOptions[],+ get scrollTop() {+ return top;+ },+ set scrollTop(value: number) {+ top = Math.max(0, Math.min(snap(value), scroller.scrollHeight - scroller.clientHeight));+ },+ scrollTo(options: ScrollToOptions = {}) {+ scroller.calls.push(options);+ if (typeof options.top === "number") scroller.scrollTop = options.top;+ },+ };+ return scroller;+}++const SNAPS = {+ "whole pixels": Math.round,+ "half pixels": (value: number) => Math.round(value * 2) / 2,+ "whole pixels, rounded down": Math.floor,+};describe("followBottomGrowth", () => {it("scrolls resized content to its new bottom while following", () => {@@ -14,7 +69,7 @@ describe("followBottomGrowth", () => {expect(calls).toEqual([{ top: 1_240 }]);});- it("glides to the bottom while a reply streams in", () => {+ it("falls back to a smooth scroll where the scroller has no layout to read", () => {const calls: ScrollToOptions[] = [];const scroller = {scrollHeight: 1_240,@@ -35,4 +90,117 @@ describe("followBottomGrowth", () => {expect(followBottomGrowth(scroller, false)).toBe(false);expect(calls).toEqual([]);});++ for (const [name, snap] of Object.entries(SNAPS)) {+ for (const [hz, ms] of [[60, 1000 / 60], [120, 1000 / 120]] as const) {+ for (const dpr of [1, 2]) {+ it(`glides all the way to the end on a scroller that snaps to ${name}, at ${hz} Hz and ${dpr}x, then stops asking for frames`, () => {+ vi.stubGlobal("window", { devicePixelRatio: dpr });+ const scroller = scrollerWith(snap);+ scroller.scrollHeight += 37;+ followBottomGrowth(scroller, true, true);+ const tops: number[] = [];+ for (let i = 0; i < 400 && pending.size; i++) {+ frame(ms);+ tops.push(scroller.scrollTop);+ }+ expect(pending.size, "no frame left asked for").toBe(0);+ expect(scroller.scrollTop).toBe(637);+ expect(tops.length, "a glide, not a jump").toBeGreaterThan(hz === 60 ? 4 : 8);+ expect(tops.length, "and not a long one").toBeLessThan(hz === 60 ? 40 : 80);+ expect(tops, "only ever down").toEqual([...tops].sort((a, b) => a - b));+ });+ }+ }+ }++ it("takes growth during a glide into the same glide", () => {+ const scroller = scrollerWith(Math.round);+ scroller.scrollHeight += 40;+ followBottomGrowth(scroller, true, true);+ frame(16);+ expect(scroller.scrollTop).toBeGreaterThan(500);+ scroller.scrollHeight += 40;+ followBottomGrowth(scroller, true, true);+ expect(pending.size, "one glide").toBe(1);+ for (let i = 0; i < 400 && pending.size; i++) frame(16);+ expect(pending.size).toBe(0);+ expect(scroller.scrollTop).toBe(680);+ });++ it("glides without a jump for as long as the stream grows, and ends after it ends", () => {+ const scroller = scrollerWith((value) => Math.round(value * 2) / 2, { clientHeight: 5_000, scrollHeight: 5_500 });+ for (let i = 0; i < 400; i++) {+ scroller.scrollHeight += 6;+ followBottomGrowth(scroller, true, true);+ frame(1000 / 120);+ }+ expect(scroller.calls, "never landed by a jump while growing").toEqual([]);+ for (let i = 0; i < 200 && pending.size; i++) frame(1000 / 60);+ expect(pending.size).toBe(0);+ expect(scroller.scrollTop).toBe(scroller.scrollHeight - scroller.clientHeight);+ });++ it("lands at once on a jump bigger than most of the view, with no glide", () => {+ const scroller = scrollerWith(Math.round);+ scroller.scrollHeight += 2_000;+ followBottomGrowth(scroller, true, true);+ expect(scroller.calls).toEqual([{ top: 3_100 }]);+ expect(scroller.scrollTop).toBe(2_600);+ expect(pending.size).toBe(0);+ });++ it("lands at once when a jump arrives during a glide", () => {+ const scroller = scrollerWith(Math.round);+ scroller.scrollHeight += 40;+ followBottomGrowth(scroller, true, true);+ frame(16);+ scroller.scrollHeight += 2_000;+ followBottomGrowth(scroller, true, true);+ expect(pending.size).toBe(0);+ expect(scroller.scrollTop).toBe(scroller.scrollHeight - scroller.clientHeight);+ });++ it("ends on the frame a write does not move the scroller, at the end", () => {+ const scroller = scrollerWith(() => 500);+ scroller.scrollHeight += 40;+ followBottomGrowth(scroller, true, true);+ frame(16);+ expect(pending.size).toBe(0);+ expect(scroller.calls).toEqual([{ top: 1_140 }]);+ });++ for (const [who, move] of [["the reader scrolls up", -20], ["something else scrolls it down", 15]] as const) {+ it(`lets go at once when ${who}, and never writes again`, () => {+ const scroller = scrollerWith(Math.round, { scrollHeight: 1_200 });+ scroller.scrollHeight += 40;+ followBottomGrowth(scroller, true, true);+ frame(16);+ const theirs = scroller.scrollTop + move;+ scroller.scrollTop = theirs;+ frame(16);+ expect(scroller.scrollTop).toBe(theirs);+ expect(pending.size).toBe(0);+ expect(scroller.calls).toEqual([]);+ });+ }++ it("stops a glide when halted, and when growth arrives while not following", () => {+ const scroller = scrollerWith(Math.round);+ scroller.scrollHeight += 40;+ followBottomGrowth(scroller, true, true);+ haltBottomChase(scroller);+ expect(pending.size).toBe(0);+ followBottomGrowth(scroller, true, true);+ expect(followBottomGrowth(scroller, false, true)).toBe(false);+ expect(pending.size).toBe(0);+ expect(scroller.scrollTop).toBe(500);+ });++ it("asks for nothing when already at the end", () => {+ const scroller = scrollerWith(Math.round, { scrollHeight: 1_000 });+ followBottomGrowth(scroller, true, true);+ expect(pending.size).toBe(0);+ expect(scroller.calls).toEqual([]);+ });});diff --git a/src/lib/bottom-follow.ts b/src/lib/bottom-follow.tsindex 3749d186d6..49cb895e91 100644--- a/src/lib/bottom-follow.ts+++ b/src/lib/bottom-follow.ts@@ -4,12 +4,98 @@ export const BOTTOM_FOLLOW_THRESHOLD = 4;interface BottomFollowScroller {scrollHeight: number;+ scrollTop?: number;+ clientHeight?: number;scrollTo(options?: ScrollToOptions): void;}+type ChaseScroller = BottomFollowScroller & { scrollTop: number; clientHeight: number };+interface Chase {+ raf: number;+ /** Where the chase has got to, unrounded: a scroller that snaps scrollTop to device pixels would stall a chase that read it back. */+ pos: number;+ /** scrollTop as last read after the chase's own write; anything else moving it ends the chase. */+ seen: number;+ lastTime: number;+ frames: number;+}++const chases = new WeakMap<BottomFollowScroller, Chase>();+/** Per second: about half the gap closes in a 16 ms frame. */+const CHASE_RATE = 40;+/** A chase that has not arrived this many frames after the last growth (two seconds at 60 Hz) lands at once. */+const MAX_CHASE_FRAMES = 120;+/** Growth past this share of the view lands at once instead of a long glide. */+const SNAP_SHARE = 0.75;++const devicePixel = () => 1 / (typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1);+const bottomOf = (scroller: ChaseScroller) => Math.max(0, scroller.scrollHeight - scroller.clientHeight);++/** Ends `scroller`'s glide toward the bottom at once, where it is (the reader took over, or the view jumped). */+export function haltBottomChase(scroller: BottomFollowScroller | null | undefined): void {+ const active = scroller && chases.get(scroller);+ if (!active) return;+ cancelAnimationFrame(active.raf);+ chases.delete(scroller);+}++function canChase(scroller: BottomFollowScroller): scroller is ChaseScroller {+ return typeof requestAnimationFrame === "function" && typeof scroller.scrollTop === "number" && typeof scroller.clientHeight === "number" && scroller.clientHeight > 0;+}++function land(scroller: BottomFollowScroller): void {+ haltBottomChase(scroller);+ scroller.scrollTo({ top: scroller.scrollHeight });+}++function step(scroller: ChaseScroller, chase: Chase, now: number): void {+ const top = scroller.scrollTop;+ if (Math.abs(top - chase.seen) > 1) {+ chases.delete(scroller);+ return;+ }+ const target = bottomOf(scroller);+ const remaining = target - chase.pos;+ const pixel = devicePixel();+ if (remaining <= pixel / 2 || chase.frames >= MAX_CHASE_FRAMES || remaining > scroller.clientHeight * SNAP_SHARE) return land(scroller);+ const dt = Math.min(Math.max(now - chase.lastTime, 4), 64) / 1000;+ chase.lastTime = now;+ chase.frames += 1;+ chase.pos = Math.min(target, chase.pos + Math.max(remaining * (1 - Math.exp(-CHASE_RATE * dt)), pixel));+ scroller.scrollTop = chase.pos;+ const after = scroller.scrollTop;+ if (after === top || chase.pos >= target) return land(scroller);+ chase.seen = after;+ chase.raf = requestAnimationFrame((time) => step(scroller, chase, time));+}++/** Keeps a following transcript at its end as it grows: at once, or, with `smooth` (a reply streaming in), by a glide+ * that closes most of the gap each frame and stops when it arrives, when the scroller stops moving, or when anything+ * else moves it. Returns whether it followed. */export function followBottomGrowth(scroller: BottomFollowScroller, following: boolean, smooth = false): boolean {- if (!following) return false;- scroller.scrollTo(smooth ? { top: scroller.scrollHeight, behavior: "smooth" } : { top: scroller.scrollHeight });+ if (!following) {+ haltBottomChase(scroller);+ return false;+ }+ if (!smooth) {+ land(scroller);+ return true;+ }+ if (!canChase(scroller)) {+ scroller.scrollTo({ top: scroller.scrollHeight, behavior: "smooth" });+ return true;+ }+ const active = chases.get(scroller);+ const gap = bottomOf(scroller) - (active?.pos ?? scroller.scrollTop);+ if (gap > scroller.clientHeight * SNAP_SHARE) {+ land(scroller);+ return true;+ }+ if (active) active.frames = 0;+ if (gap <= devicePixel() / 2 || active) return true;+ const chase: Chase = { raf: 0, pos: scroller.scrollTop, seen: scroller.scrollTop, lastTime: performance.now(), frames: 0 };+ chases.set(scroller, chase);+ chase.raf = requestAnimationFrame((time) => step(scroller, chase, time));return true;}@@ -27,6 +113,9 @@ export function useBottomFollowResize(const observer = new ResizeObserver(onResize);observer.observe(transcript);- return () => observer.disconnect();+ return () => {+ haltBottomChase(scroller);+ observer.disconnect();+ };}, [observeKey, onResize, scrollRef, transcriptRef]);}diff --git a/src/lib/composer-focus.test.ts b/src/lib/composer-focus.test.tsnew file mode 100644index 0000000000..00e9f18d66--- /dev/null+++ b/src/lib/composer-focus.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { specularTransform } from "@/components/mascot-motion";+import { setComposerFocused } from "./composer-focus";++describe("specularTransform", () => {+ it("returns null at rest so resting mascots write zero gradient attributes", () => {+ expect(specularTransform(0, 0, 0)).toBeNull();+ expect(specularTransform(0.001, 0.001, 0)).toBeNull();+ });++ it("counter-shifts the gradient highlight when gazing or leaning", () => {+ expect(specularTransform(1, 0, 0)).toBe("translate(-0.140 0.000)");+ expect(specularTransform(0, 0.5, 0)).toBe("translate(0.000 -0.070)");+ expect(specularTransform(-0.5, -0.5, 0)).toBe("translate(0.070 0.070)");+ });+});++describe("composer-focus", () => {+ it("handles missing thread ids safely", () => {+ expect(() => setComposerFocused(null, true)).not.toThrow();+ expect(() => setComposerFocused(undefined, false)).not.toThrow();+ });+});diff --git a/src/lib/composer-focus.ts b/src/lib/composer-focus.tsnew file mode 100644index 0000000000..146967f75e--- /dev/null+++ b/src/lib/composer-focus.ts@@ -0,0 +1,46 @@+import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";++const focusedThreads = new Set<string>();+const listeners = new Map<string, Set<() => void>>();++function notify(threadId: string): void {+ const set = listeners.get(threadId);+ if (!set) return;+ for (const fn of Array.from(set)) fn();+}++/** Tracks whether the composer for `threadId` currently has keyboard focus (used for subtle mascot glance). */+export function setComposerFocused(threadId: string | null | undefined, focused: boolean): void {+ if (!threadId) return;+ const had = focusedThreads.has(threadId);+ if (had === focused) return;+ if (focused) focusedThreads.add(threadId);+ else focusedThreads.delete(threadId);+ notify(threadId);+}++/** Focus/blur handlers for a thread's composer input, clearing focus on thread switch or unmount. */+export function useComposerFocusHandlers(threadId: string | null | undefined): { onFocus: () => void; onBlur: () => void } {+ useEffect(() => () => setComposerFocused(threadId, false), [threadId]);+ return useMemo(+ () => ({+ onFocus: () => setComposerFocused(threadId, true),+ onBlur: () => setComposerFocused(threadId, false),+ }),+ [threadId],+ );+}++export function useComposerFocused(threadId: string | null | undefined): boolean {+ const subscribe = useCallback((listener: () => void) => {+ if (!threadId) return () => {};+ let set = listeners.get(threadId);+ if (!set) listeners.set(threadId, (set = new Set()));+ set.add(listener);+ return () => {+ set.delete(listener);+ if (set.size === 0) listeners.delete(threadId);+ };+ }, [threadId]);+ return useSyncExternalStore(subscribe, () => Boolean(threadId && focusedThreads.has(threadId)), () => false);+}diff --git a/src/lib/copy-text.ts b/src/lib/copy-text.tsindex c57191c720..9a09cf1d75 100644--- a/src/lib/copy-text.ts+++ b/src/lib/copy-text.ts@@ -1,4 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";+import { tapHaptic } from "./haptics";export type CopyResult = "copied" | "empty" | "failed";export type CopyFeedback = "idle" | "copied" | "failed";@@ -126,6 +127,7 @@ export function createCopyFeedback({}if (disposed || result === "empty") return result;clear();+ if (result === "copied") tapHaptic();onChange(result === "copied" ? "copied" : "failed");timer = setTimer(() => {timer = undefined;diff --git a/src/lib/haptics.ts b/src/lib/haptics.tsnew file mode 100644index 0000000000..5ef0c68481--- /dev/null+++ b/src/lib/haptics.ts@@ -0,0 +1,12 @@+import { reducedMotion } from "@/components/MenuMotion";++/** Subtle tactile pulse on supported touch devices (silent no-op on desktop or under reduced motion). */+export function tapHaptic(durationMs = 6): void {+ if (reducedMotion()) return;+ if (typeof navigator === "undefined" || typeof navigator.vibrate !== "function") return;+ try {+ navigator.vibrate(durationMs);+ } catch {+ // Ignore browsers that block vibration outside trusted touch gestures.+ }+}diff --git a/src/lib/stream-pacer.test.ts b/src/lib/stream-pacer.test.tsnew file mode 100644index 0000000000..bb4393d32b--- /dev/null+++ b/src/lib/stream-pacer.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { nextPacedLength, wordBoundary } from "./stream-pacer";++const drain = (text: string, dt = 16) => {+ const goal = wordBoundary(text, false);+ const cuts: number[] = [];+ for (let shown = 0; shown < goal && cuts.length < 500;) cuts.push((shown = nextPacedLength(shown, text, goal, dt)));+ return cuts;+};++describe("nextPacedLength", () => {+ it("drains a burst over frames, stopping only just after a space", () => {+ const text = "Here is a smooth streaming sentence with several words arriving in one chunk. ".repeat(4);+ const cuts = drain(text);+ expect(cuts.length).toBeGreaterThan(1);+ expect(cuts.at(-1)).toBe(text.length);+ for (const cut of cuts) expect(text[cut - 1]).toMatch(/[ \n]/);+ });++ it("closes a large burst in a handful of frames", () => {+ const cuts = drain("word ".repeat(400));+ expect(cuts.length).toBeLessThan(35);+ });++ it("shows everything up to the goal when no space lies ahead", () => {+ const text = `See [the docs](https://example.com/${"a".repeat(200)}) `;+ expect(nextPacedLength(4, text, text.length, 16)).toBe(text.length);+ });++ it("never cuts before a mark or joiner that belongs to the character before it", () => {+ const text = `ab ́cd ${"x".repeat(40)} `;+ const cut = nextPacedLength(0, text, text.length, 4);+ expect(cut === text.length || !/^[́]/.test(text.slice(cut))).toBe(true);+ });++ it("stays put when already caught up", () => {+ expect(nextPacedLength(10, "hello test ", 10, 16)).toBe(10);+ });+});++describe("wordBoundary", () => {+ it("cuts just after the last space or line break while streaming, and nowhere once done", () => {+ expect(wordBoundary("one two thr", false)).toBe(8);+ expect(wordBoundary("one\ntwo", false)).toBe(4);+ expect(wordBoundary("unbroken", false)).toBe(0);+ expect(wordBoundary("one two thr", true)).toBe(11);+ });+});diff --git a/src/lib/stream-pacer.ts b/src/lib/stream-pacer.tsnew file mode 100644index 0000000000..3e75e018df--- /dev/null+++ b/src/lib/stream-pacer.ts@@ -0,0 +1,34 @@+/** A single delta that adds more than this many characters is a burst worth spreading over frames; anything smaller is+ * drawn as it arrives, with no frame of its own. */+export const PACE_BURST_CHARS = 96;+/** A burst's backlog closes with this time constant, but never slower than MIN_CHARS_PER_SEC. */+const CATCHUP_MS = 90;+const MIN_CHARS_PER_SEC = 140;+/** A frame this long after the last one means the page was in the background: what is waiting shows at once. */+export const PACE_STALE_FRAME_MS = 250;++const SPACE = /[ \n]/;+/** Characters that belong to the one before them, so a cut must never fall just before one. */+const JOINS_PREVIOUS = /^(?:\p{M}|\u200d)/u;++/** Where the words that streamed so far may be cut: just after their last space or line break (all of it once done). */+export function wordBoundary(text: string, done: boolean): number {+ return done ? text.length : Math.max(text.lastIndexOf(" "), text.lastIndexOf("\n")) + 1;+}++/** The first cut at or after `from` that falls just after a space and before a new character, else `goal`. */+function cutFrom(text: string, from: number, goal: number): number {+ for (let at = Math.max(1, from); at < goal; at++) {+ if (SPACE.test(text[at - 1]!) && !JOINS_PREVIOUS.test(text.slice(at, at + 1))) return at;+ }+ return goal;+}++/** How much of `text` to show after a frame of `dtMs`, moving from `shown` toward `goal` (a cut `wordBoundary` gave).+ * It only ever stops just after a space, so a word, a link or an emoji is never split; with no space ahead it shows all. */+export function nextPacedLength(shown: number, text: string, goal: number, dtMs: number): number {+ if (shown >= goal) return goal;+ const dt = Math.min(Math.max(dtMs, 4), 64);+ const step = Math.max(Math.ceil(((goal - shown) * dt) / CATCHUP_MS), Math.ceil((MIN_CHARS_PER_SEC * dt) / 1000));+ return shown + step >= goal ? goal : cutFrom(text, shown + step, goal);+}diff --git a/src/state/live-reply-pacing.dom.test.ts b/src/state/live-reply-pacing.dom.test.tsnew file mode 100644index 0000000000..1d81e15b8e--- /dev/null+++ b/src/state/live-reply-pacing.dom.test.ts@@ -0,0 +1,225 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { RuntimeEvent } from "../../shared/runtime-events";+import { noteLiveReplyEvent, resetLiveReplies, stopLiveReply, useLiveRow } from "./live-reply";+import type { Message } from "@/state/store";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let seq = 0;+let frames = new Map<number, FrameRequestCallback>();+let nextFrame = 1;+let clock = 0;+let renders: Record<string, string[]> = {};+let roots: Root[] = [];++beforeEach(() => {+ frames = new Map();+ nextFrame = 1;+ clock = 0;+ renders = {};+ vi.spyOn(performance, "now").mockImplementation(() => clock);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ frames.set(nextFrame, callback);+ return nextFrame++;+ });+ vi.stubGlobal("cancelAnimationFrame", (id: number) => void frames.delete(id));+});++afterEach(() => {+ for (const root of roots) act(() => root.unmount());+ roots = [];+ resetLiveReplies();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+});++const delta = (text: string, item = "i1", threadId = "t") => act(() => noteLiveReplyEvent({+ eventId: `e${++seq}`, provider: "claudeAgent", threadId, createdAt: "", turnId: "turn", itemId: item,+ type: "content.delta", streamKind: "assistant_text", delta: text,+} as RuntimeEvent));+const complete = (text: string, item = "i1", threadId = "t") => act(() => noteLiveReplyEvent({+ eventId: `e${++seq}`, provider: "claudeAgent", threadId, createdAt: "", turnId: "turn", itemId: item,+ type: "item.completed", itemType: "assistant_text", text,+} as RuntimeEvent));+const frame = (ms = 1000 / 60) => act(() => {+ clock += ms;+ const batch = [...frames.values()];+ frames.clear();+ for (const callback of batch) callback(clock);+});+const drain = () => {+ for (let i = 0; i < 300 && frames.size; i++) frame();+};++function Row({ id, threadId, label }: { id: string; threadId: string; label: string }) {+ const message = useLiveRow(threadId, { id, role: "bot", kind: "text", text: "", at: 0 } as Message);+ (renders[label] ??= []).push(message.text ?? "");+ return null;+}+function mountRows(rows: Array<{ id: string; threadId?: string; label: string }>) {+ const host = document.createElement("div");+ document.body.appendChild(host);+ const root = createRoot(host);+ roots.push(root);+ const draw = () => act(() => root.render(rows.map((row) => createElement(Row, { key: row.label, threadId: "t", ...row }))));+ draw();+ return { root, draw };+}+const live = (item = "i1") => `live:${item}`;+const last = (label: string) => renders[label]!.at(-1)!;+const loneSurrogate = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;+const words = (count: number, from = 0) => Array.from({ length: count }, (_, i) => `word${from + i} `).join("");++describe("a live row drawing a streamed reply", () => {+ it("draws steady deltas as they come: one render each, and no frames of its own", () => {+ delta("Hello ");+ mountRows([{ id: live(), label: "live" }, { id: "m1", label: "settled" }]);+ const before = renders.live!.length;+ for (let i = 0; i < 120; i++) delta(`w${i} `);+ expect(renders.live!.length - before).toBe(120);+ expect(frames.size).toBe(0);+ expect(renders.settled!.length, "a settled row never draws again").toBe(1);+ });++ it("spreads a burst over frames on word boundaries, then goes back to one render per delta", () => {+ delta("Start ");+ mountRows([{ id: live(), label: "live" }, { id: "m1", label: "settled" }]);+ const burst = words(80);+ delta(burst);+ const full = `Start ${burst}`;+ expect(last("live").length, "part of the burst shows at once").toBeGreaterThan("Start ".length);+ expect(last("live").length).toBeLessThan(full.length);+ const during = renders.live!.length;+ drain();+ expect(last("live")).toBe(full);+ const shown = renders.live!.slice(during - 1);+ for (const text of shown) {+ expect(full.startsWith(text)).toBe(true);+ expect(text).toMatch(/\s$/);+ }+ expect(shown.length, "a few frames, not one per character").toBeLessThan(40);++ const settledBefore = renders.settled!.length;+ const afterBurst = renders.live!.length;+ for (let i = 0; i < 50; i++) delta(`s${i} `);+ expect(renders.live!.length - afterBurst, "drained: renders equal deltas").toBe(50);+ expect(frames.size).toBe(0);+ expect(renders.settled!.length).toBe(settledBefore);+ });++ it("asks for at most one frame at a time, however many rows are catching up", () => {+ delta("A ", "i1");+ delta("B ", "i2", "u");+ mountRows([{ id: live("i1"), label: "one" }, { id: live("i2"), threadId: "u", label: "two" }]);+ delta(words(60), "i1");+ delta(words(60), "i2", "u");+ expect(frames.size).toBe(1);+ frame();+ expect(frames.size).toBe(1);+ const oneAt = renders.one!.length, twoAt = renders.two!.length;+ frame();+ expect(renders.one!.length - oneAt).toBeLessThanOrEqual(2);+ expect(renders.two!.length - twoAt).toBeLessThanOrEqual(2);+ drain();+ expect(last("one")).toBe(`A ${words(60)}`);+ expect(last("two")).toBe(`B ${words(60)}`);+ });++ it("never splits a long token: with no space ahead it shows the whole of it", () => {+ delta("See ");+ mountRows([{ id: live(), label: "live" }]);+ const link = `[the docs](https://example.com/${"a".repeat(300)}) `;+ delta(`${link}and more `);+ drain();+ for (const text of renders.live!) {+ expect(text.includes("[the docs](") && !text.includes(link), `cut inside the link: ${text.slice(0, 40)}`).toBe(false);+ }+ expect(last("live")).toBe(`See ${link}and more `);+ });++ it("never splits an emoji or a joined sequence", () => {+ delta("Go ");+ mountRows([{ id: live(), label: "live" }]);+ const family = "\u{1F468}\u{1F469}\u{1F467}";+ const run = `${"\u{1F600}".repeat(60)} ${family.repeat(20)} ${"é".repeat(50)} ${"\u{1F44D}\u{1F3FD}".repeat(40)} `;+ delta(run);+ drain();+ for (const text of renders.live!) {+ expect(loneSurrogate.test(text)).toBe(false);+ expect(text === "Go " || text.endsWith(" ")).toBe(true);+ }+ expect(last("live")).toBe(`Go ${run}`);+ });++ it("shows everything at once when the reply ends mid-burst", () => {+ delta("Start ");+ mountRows([{ id: live(), label: "live" }]);+ delta(words(80));+ frame();+ complete(`Start ${words(80)}done`);+ expect(last("live")).toBe(`Start ${words(80)}done`);+ frame();+ expect(frames.size).toBe(0);+ });++ it("shows everything at once on Stop", () => {+ delta("Start ");+ mountRows([{ id: live(), label: "live" }]);+ delta(words(80));+ act(() => stopLiveReply("t"));+ expect(last("live")).toBe(`Start ${words(80)}`);+ frame();+ expect(frames.size).toBe(0);+ });++ it("stops asking for frames once its row is gone", () => {+ delta("Start ");+ const { root } = mountRows([{ id: live(), label: "live" }]);+ delta(words(80));+ act(() => root.unmount());+ roots = [];+ frame();+ expect(frames.size).toBe(0);+ });++ it("shows everything at once when the page is hidden, and paces nothing while hidden", () => {+ delta("Start ");+ mountRows([{ id: live(), label: "live" }]);+ delta(words(80));+ Object.defineProperty(document, "hidden", { configurable: true, get: () => true });+ frame();+ expect(last("live")).toBe(`Start ${words(80)}`);+ expect(frames.size).toBe(0);+ delta(words(80, 80));+ expect(last("live")).toBe(`Start ${words(160)}`);+ expect(frames.size).toBe(0);+ delete (document as { hidden?: boolean }).hidden;+ });++ it("shows what waited at once after a long gap between frames (a window in the background)", () => {+ delta("Start ");+ mountRows([{ id: live(), label: "live" }]);+ delta(words(80));+ frame(1_000);+ expect(last("live")).toBe(`Start ${words(80)}`);+ expect(frames.size).toBe(0);+ });++ it("paces nothing under reduced motion", () => {+ document.documentElement.dataset.reducedMotion = "true";+ try {+ delta("Start ");+ mountRows([{ id: live(), label: "live" }]);+ delta(words(80));+ expect(last("live")).toBe(`Start ${words(80)}`);+ expect(frames.size).toBe(0);+ } finally {+ delete document.documentElement.dataset.reducedMotion;+ }+ });+});diff --git a/src/state/live-reply.ts b/src/state/live-reply.tsindex 4de7e59945..67a5e7e8ab 100644--- a/src/state/live-reply.ts+++ b/src/state/live-reply.ts@@ -8,6 +8,8 @@ import type { RuntimeEvent } from "../../shared/runtime-events";import { isClientCancellation } from "../../shared/client-cancel";import { redactSecretsInText } from "../../shared/redact";import { isPureLeakedSystemHarnessMessage } from "../../shared/system-message-guard";+import { nextPacedLength, PACE_BURST_CHARS, PACE_STALE_FRAME_MS, wordBoundary } from "@/lib/stream-pacer";+import { reducedMotion } from "@/components/MenuMotion";import type { Message } from "@/state/store";export interface LiveReplyItem {@@ -59,9 +61,102 @@ function put(threadId: string, next: ThreadReplies): void {if (next.items.length || next.skipping) threads.set(threadId, next);if (threads.size > MAX_THREADS) threads.delete(threads.keys().next().value!);if ((current?.items ?? EMPTY) === next.items) return;+ pace(threadId, current?.items ?? EMPTY, next.items);+ notify(threadId);+}++function notify(threadId: string): void {for (const listener of Array.from(listeners.get(threadId) ?? [])) listener();}+// A burst (one delta of many words) is drawn over a few frames instead of at once; steady deltas are drawn as they+// come. Kept here, beside the items, so only rows that show a live reply see it and a settled row pays nothing.+/** Per thread, per item key: how much of the item's text is drawn while it catches up with a burst. */+const pacing = new Map<string, Map<string, number>>();+const pacedViews = new Map<string, { items: readonly LiveReplyItem[]; version: number; view: readonly LiveReplyItem[] }>();+let paceVersion = 0;+let paceFrame = 0;+let paceAt = 0;++const canPace = () => typeof requestAnimationFrame === "function" && typeof document !== "undefined" && !document.hidden && !reducedMotion();++function pace(threadId: string, before: readonly LiveReplyItem[], after: readonly LiveReplyItem[]): void {+ const held = pacing.get(threadId);+ let able: boolean | undefined;+ for (const item of after) {+ const goal = wordBoundary(item.text, item.done);+ const shown = held?.get(item.key);+ if (item.done || item.savedAs !== undefined) {+ held?.delete(item.key);+ } else if (shown !== undefined) {+ if (shown >= goal || !(able ??= canPace())) held!.delete(item.key);+ } else {+ const previous = before.find((one) => one.key === item.key);+ const from = previous ? wordBoundary(previous.text, previous.done) : 0;+ if (goal - from <= PACE_BURST_CHARS || !(able ??= canPace())) continue;+ const first = nextPacedLength(from, item.text, goal, 1000 / 60);+ if (first >= goal) continue;+ const map = held ?? new Map<string, number>();+ map.set(item.key, first);+ pacing.set(threadId, map);+ }+ }+ for (const key of held?.keys() ?? []) if (!after.some((item) => item.key === key)) held!.delete(key);+ if (held && !held.size) pacing.delete(threadId);+ paceVersion += 1;+ if (pacing.size && !paceFrame) {+ paceAt = performance.now();+ paceFrame = requestAnimationFrame(paceTick);+ }+}++function paceTick(now: number): void {+ paceFrame = 0;+ const dt = now - paceAt;+ paceAt = now;+ const flush = dt > PACE_STALE_FRAME_MS || !canPace();+ for (const [threadId, held] of Array.from(pacing)) {+ const items = threads.get(threadId)?.items ?? EMPTY;+ const watched = Boolean(listeners.get(threadId)?.size);+ for (const [key, shown] of Array.from(held)) {+ const item = items.find((one) => one.key === key);+ const goal = item ? wordBoundary(item.text, item.done) : 0;+ const next = item && watched && !flush ? nextPacedLength(shown, item.text, goal, dt) : goal;+ if (next >= goal) held.delete(key);+ else held.set(key, next);+ }+ if (!held.size) pacing.delete(threadId);+ paceVersion += 1;+ if (watched) notify(threadId);+ }+ if (pacing.size) paceFrame = requestAnimationFrame(paceTick);+}++function stopPacing(): void {+ if (paceFrame) cancelAnimationFrame(paceFrame);+ paceFrame = 0;+ pacing.clear();+ pacedViews.clear();+}++/** The thread's items as its live rows draw them: the same array as `liveReplies` unless a burst is being drawn. */+function pacedReplies(threadId: string): readonly LiveReplyItem[] {+ const items = liveReplies(threadId);+ const held = pacing.get(threadId);+ if (!held) {+ pacedViews.delete(threadId);+ return items;+ }+ const cached = pacedViews.get(threadId);+ if (cached?.items === items && cached.version === paceVersion) return cached.view;+ const view = items.map((item) => {+ const shown = held.get(item.key);+ return shown === undefined ? item : { ...item, text: item.text.slice(0, shown) };+ });+ pacedViews.set(threadId, { items, version: paceVersion, view });+ return view;+}+function firstSeen(eventId: string): boolean {if (seenEvents.has(eventId)) return false;seenEvents.add(eventId);@@ -142,6 +237,10 @@ export function noteLiveReplyMessage(threadId: string, message: (Pick<Message, "* Stop cut short completes the item and its saved message takes its place; otherwise the turn's end removes it. */export function stopLiveReply(threadId: string): void {put(threadId, { items: threads.get(threadId)?.items ?? EMPTY, skipping: true });+ if (pacing.delete(threadId)) {+ paceVersion += 1;+ notify(threadId);+ }}/** The live stream restarted without the frames it missed: no thread's open item can be completed from here. */@@ -180,8 +279,7 @@ export function isLiveReply(message: Pick<Message, "id">): boolean {/** What a streaming item shows. The last word waits for the space after it, so a secret is masked whole or not shown. */export function liveReplyText(item: Pick<LiveReplyItem, "text" | "done">): string {- const end = item.done ? item.text.length : Math.max(item.text.lastIndexOf(" "), item.text.lastIndexOf("\n")) + 1;- const text = item.text.slice(0, end);+ const text = item.text.slice(0, wordBoundary(item.text, item.done));return isClientCancellation(text) ? "" : redactSecretsInText(text);}@@ -210,7 +308,7 @@ const noSubscription = () => () => {};export function useLiveRow(threadId: string, row: Message): Message {const live = isLiveReply(row);const subscribeLive = useCallback((listener: () => void) => subscribe(threadId, listener), [threadId]);- const items = useSyncExternalStore(live ? subscribeLive : noSubscription, () => live ? liveReplies(threadId) : EMPTY, () => EMPTY);+ const items = useSyncExternalStore(live ? subscribeLive : noSubscription, () => live ? pacedReplies(threadId) : EMPTY, () => EMPTY);const item = live ? items.find((one) => `${LIVE_ID}${one.key}` === row.id) : undefined;return (item && liveRowOf(item, () => row.from)) || row;}@@ -361,6 +459,7 @@ export function useLiveTranscriptLayout(threadId: string, windowed: Message[], t/** Tests only. */export function resetLiveReplies(): void {+ stopPacing();threads.clear();seenEvents.clear();streamed.clear();diff --git a/src/styles.css b/src/styles.cssindex 94157a6749..271959bbe4 100644--- a/src/styles.css+++ b/src/styles.css@@ -2623,6 +2623,12 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clofrom { opacity: 0; }}.turn-phrase-in { animation: turn-phrase-in 0.32s ease-out both; }+@keyframes icon-morph-in {+ from { opacity: 0; transform: scale(0.84); }+ to { opacity: 1; transform: none; }+}+.animate-icon-morph { animation: icon-morph-in 140ms cubic-bezier(0.22, 1, 0.36, 1) both; }+.chevron-turn { transition: rotate 150ms cubic-bezier(0.22, 1, 0.36, 1), transform 150ms cubic-bezier(0.22, 1, 0.36, 1); }.turn-now-toggle {display: flex;min-width: 0;@@ -2666,7 +2672,8 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo.animate-caret, .animate-msg-in, .animate-pop-in, .animate-pop-out, .animate-menu-in { animation: none; }.animate-status-pulse { animation: none; opacity: 0.6; }.thinking-sheen { display: none; }- .turn-phrase-in { animation: none; }+ .turn-phrase-in, .animate-icon-morph { animation: none; }+ .chevron-turn { transition: none; }.turn-mascot-in, .turn-mascot-out, .turn-answer { animation: none; }.reply-bubble-in { animation: none; }.animate-rise, .animate-spot-in { animation: none; }@@ -2688,6 +2695,9 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo:root[data-reduced-motion="true"] .step-open,:root[data-reduced-motion="true"] .check-in,:root[data-reduced-motion="true"] .progress-fill,+:root[data-reduced-motion="true"] .turn-phrase-in,+:root[data-reduced-motion="true"] .animate-icon-morph,+:root[data-reduced-motion="true"] .chevron-turn,:root[data-reduced-motion="true"] .welcome-screen * {animation: none !important;transition: none !important;