Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat: a switch settles in one frame, and a send draws one bubble that does not jump (#8268)
Milind Soni5b4db98d91bc
diff --git a/src/App.tsx b/src/App.tsxindex e73a5dea75..e8b8d3b97e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -77,6 +77,7 @@ import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { useConnectLink } from "@/lib/use-connect-link";import { isSettingsPage } from "@/components/settings/settings-pages";import { useBotListDrawer } from "@/hooks/use-bot-list-drawer";+import { useSwitchHold } from "@/hooks/use-switch-hold";import { usePhoneBack } from "@/hooks/use-phone-back";import { useRememberedSidePanel } from "@/hooks/use-remembered-side-panel";import { closeSidePanels } from "@/lib/page-open";@@ -181,6 +182,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const chiefStep = useChiefStepOpen();const bot = group || chiefStep ? undefined : (state.bots.find((b) => b.id === state.selectedId) ?? state.bots[0]);const chatBot = useMemo(() => bot && newChatBot(bot, state.newChat), [bot, state.newChat]);+ // A switch to a conversation still being read keeps the chat on screen until it lands (hooks/use-switch-hold).+ const shownChat = useSwitchHold(state.activeView === "chat" ? chatBot : undefined, (id) => state.bots.find((held) => held.id === id)) ?? chatBot;const { open: drawerOpen, show: openDrawer, hide: hideDrawer, noteAction: noteDrawerAction, back: drawerBack, backSteps: drawerBackSteps } = useBotListDrawer({ selectedId: state.selectedId, botThread: chatBot?.threadId, groupThread: group?.threadId,view: state.activeView, pluginsOpen: state.pluginsOpen, settingsOpen: state.settingsOpen });const closeDrawer = useCallback(() => { hideDrawer(); menuButtonRef.current?.focus(); }, [hideDrawer]);@@ -487,7 +490,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {) : group ? (<GroupView key={group.id} group={group} />) : bot ? (- <HandoffExchangeHost bot={chatBot ?? bot}><ChatView bot={chatBot ?? bot} /></HandoffExchangeHost>+ <HandoffExchangeHost bot={shownChat ?? bot}><ChatView bot={shownChat ?? bot} /></HandoffExchangeHost>) : noEngines ? (<NoEngines />) : (diff --git a/src/components/ChatView.switch-feel.test.ts b/src/components/ChatView.switch-feel.test.tsnew file mode 100644index 0000000000..50d73e558e--- /dev/null+++ b/src/components/ChatView.switch-feel.test.ts@@ -0,0 +1,154 @@+// @vitest-environment happy-dom+// The real provider and two chats the app holds: a switch draws them at their end with no entrance replayed, and a send+// is one row from Enter to the server's copy, its status line drawn with it.+import { act, createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { BotAnnouncement, InstanceInfo, Message } from "@/state/store";++vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+const painted = vi.hoisted(() => [] as (() => void)[]);+vi.mock("@/lib/after-paint", () => ({ afterPaint: (callback: () => void) => {+ painted.push(callback);+ return () => {+ const at = painted.indexOf(callback);+ if (at >= 0) painted.splice(at, 1);+ };+} }));+vi.mock("@/lib/cloud-guest", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useReactor: () => "user" }));+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancedMode: vi.fn() }));++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const announced = (id: string, name: string): BotAnnouncement => ({+ id, threadId: `${id}-thread`, name, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "test", model: "m" }, tasks: [{ threadId: `${id}-thread`, title: "Chat", createdAt: 1, approvalMode: "ask" }],+});+const start = Date.UTC(2026, 10, 1, 9);+function transcript(bot: string): Message[] {+ const rows: Message[] = [];+ for (let turn = 0; turn < 12; turn++) {+ const at = start + turn * 600_000;+ rows.push({ id: `${bot}-ask-${turn}`, role: "user", kind: "text", at, text: `Question ${turn}`, sendId: `${bot}-send-${turn}` });+ rows.push({ id: `${bot}-answer-${turn}`, role: "bot", kind: "text", at: at + 9_000, turnTerminal: true, text: `Answer ${turn}` });+ }+ return rows;+}+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const answers: Record<string, unknown> = {+ "/api/instances": { instances: [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" }, models: { options: [{ id: "m", label: "Model" }] } } as unknown as InstanceInfo] },+ "/api/config": { features: { showToolCalls: true } },+ "/api/routines": { routines: [], runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] },+};++const { StoreProvider, useStore } = await import("@/state/store");+const { useStoreSelector } = await import("@/state/store-select");+const { ChatView } = await import("./ChatView");++let dispatch!: ReturnType<typeof useStore>["dispatch"];+function Shown() {+ dispatch = useStore().dispatch;+ return null;+}+function Shell() {+ const bot = useStoreSelector((state) => state.bots.find((candidate) => candidate.id === state.selectedId));+ return bot ? createElement(ChatView, { bot }) : null;+}++let root: Root;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 6; i++) await task(); };+const frames = async () => { for (let i = 0; i < 4; i++) { await new Promise((resolve) => requestAnimationFrame(resolve)); await settle(); } };+async function paint() {+ const flag = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };+ flag.IS_REACT_ACT_ENVIRONMENT = true;+ try {+ await act(async () => { for (const run of painted.splice(0)) run(); });+ } finally {+ flag.IS_REACT_ACT_ENVIRONMENT = false;+ }+}+let answerSend: (body: unknown) => void = () => {};+const scroller = () => document.querySelector<HTMLElement>(".glass-scroller")!;+const bubbles = () => [...document.querySelectorAll<HTMLElement>('[role="log"] [data-look="message-user"]')];+const bubbleOf = (id: string) => document.querySelector<HTMLElement>(`[data-mid="${id}"] [data-look="message-user"]`);++beforeAll(async () => {+ const isScroller = (el: Element) => el.classList.contains("glass-scroller");+ Object.defineProperty(HTMLElement.prototype, "clientHeight", { configurable: true, get() { return isScroller(this) ? 900 : 0; } });+ Object.defineProperty(HTMLElement.prototype, "scrollHeight", { configurable: true, get() { return isScroller(this) ? 120 * this.querySelectorAll("[data-mid]").length : 0; } });+ vi.stubGlobal("EventSource", FixtureEventSource);+ // A send's POST is answered when the test says, as the server's reply lands before its live frames.+ vi.stubGlobal("fetch", (path: string, init?: RequestInit) => path.startsWith("/api/bots?")+ ? json({ bots: [{ ...announced("a", "Ada"), messages: transcript("a") }, { ...announced("b", "Bea"), messages: transcript("b") }], groups: [] })+ : init?.method === "POST" && path.endsWith("/messages") ? new Promise<Response>((done) => { answerSend = (body) => done(new Response(JSON.stringify(body), { status: 202 })); })+ : json(answers[path.replace(/\?.*$/, "")] ?? {}));+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Shown), createElement(Shell))));+ await settle();+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "select", id: "a" }));+ await paint();+ await frames();+});+afterAll(() => {+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});++describe("a switch to a chat the app holds", () => {+ it("draws it at its end, with the person's messages already in place, in the click's commit", async () => {+ flushSync(() => dispatch({ type: "select", id: "b" }));+ expect(bubbles().length).toBeGreaterThan(0);+ expect(bubbleOf("b-ask-11")).not.toBeNull();+ expect(scroller().scrollTop, "at the end before the paint").toBe(scroller().scrollHeight);+ for (const bubble of bubbles()) expect(bubble.className, bubble.closest("[data-mid]")?.getAttribute("data-mid") ?? "").not.toContain("animate-msg-in");+ await paint();+ await frames();+ for (const bubble of bubbles()) expect(bubble.className).not.toContain("animate-msg-in");+ });+});++describe("a send", () => {+ it("is one row from Enter to the server's copy, entering once, with its status line from the start", async () => {+ flushSync(() => dispatch({ type: "send", botId: "b", threadId: "b-thread", text: "One more thing", sendId: "feel-1" }));+ const sent = bubbleOf("optimistic-feel-1");+ expect(sent).not.toBeNull();+ expect(sent!.className).toContain("animate-msg-in");+ const presence = () => document.querySelector('[role="log"] .turn-presence');+ expect(presence(), "the status line arrives with the bubble").not.toBeNull();+ // The send's reply carries the server's copy before any live frame says the bot is busy.+ const copy = { id: "server-feel-1", role: "user", kind: "text", at: Date.now(), text: "One more thing", sendId: "feel-1", parentId: "b-answer-11" };+ await settle();+ answerSend({ ok: true, threadId: "b-thread", message: copy });+ await frames();+ expect(bubbleOf("optimistic-feel-1")).toBeNull();+ expect(bubbleOf("server-feel-1"), "the same element, not a new row replaying its entrance").toBe(sent);+ expect(presence(), "the status line holds until the bot is busy").not.toBeNull();+ expect(document.querySelector('[role="log"] .turn-mascot-out'), "and does not start to leave").toBeNull();+ expect(document.querySelector('[role="log"] [data-turn-status]')).not.toBeNull();+ FixtureEventSource.opened[0]!.send({ kind: "bot", bot: { ...announced("b", "Bea"), busy: true, activity: "working", turnStartedAt: Date.now() } });+ FixtureEventSource.opened[0]!.send({ kind: "message", threadId: "b-thread", message: copy });+ await frames();+ expect(bubbleOf("server-feel-1")).toBe(sent);+ expect(document.querySelector('[role="log"] .turn-mascot-out')).toBeNull();+ expect(presence()).not.toBeNull();+ });+});diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 712793704b..f80452e09a 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -115,7 +115,7 @@ import { splitTranscriptAttachments } from "@/lib/composer-attachments";import { useComposerDockPad } from "@/lib/composer-dock";import { ChatBackdrop, GlassBar, GlassScrollFrame } from "./GlassScrollFrame";import { PagePaneContext } from "./app/PageTools";-import { useTranscriptViewport } from "@/hooks/use-transcript-viewport"; import { staysInView } from "../../shared/person-wait";+import { useTranscriptViewport } from "@/hooks/use-transcript-viewport"; import { useAwaitingTurn } from "@/hooks/use-awaiting-turn"; import { staysInView } from "../../shared/person-wait";import { useUnreadDivider } from "@/hooks/use-unread-divider"; import { useTabsFrameOnRoot } from "@/hooks/use-tabs-frame-on-root";import { NewMessagesDivider } from "./NewMessagesDivider";import { unreadMessageIds } from "@/lib/unread-divider"; import { UnreadContextOverlay } from "./UnreadContextOverlay";@@ -128,7 +128,7 @@ import { highlightCitationSource } from "@/lib/citations-dom";import { useCanWriteIn, useReactor } from "@/lib/cloud-guest";import { formattedReplyWidth, isFormattedReply, splitReplyBlocks } from "@/lib/formatted-reply";import { otherSpeaker } from "@/lib/own-profile"; import { useSharedRun } from "./SharedQueueLine";-import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer";+import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer"; import { transcriptRowKeys } from "@/lib/transcript-row-keys";import { pendingApprovals } from "./PendingApproval";import { TranscriptAnnouncer } from "./TranscriptAnnouncer";import { JumpToLatestButton } from "./JumpToLatestButton";@@ -307,7 +307,8 @@ const Bubble = memo(function Bubble({const user = message.role === "user" && !peer;const speaker = user ? otherSpeaker(message, speakerViewer ?? null) : null;const ownBubbleStyle = speaker ? undefined : bubbleStyle;- const [expanded, setExpanded] = useState(false), [folded, setFolded] = useState(false);+ // Only a message that arrives while the chat is open plays the entrance; decided once, so the server's copy of a send cannot replay it.+ const [expanded, setExpanded] = useState(false), [folded, setFolded] = useState(false), [entering] = useState(() => message.at >= openedAt);const focusedHere = focus?.messageId === message.id, focusedSearch = focusedHere && Boolean(focus.matchText);const [viewRaw, setViewRaw] = useState(false);const speech = useSpeech();@@ -394,7 +395,7 @@ const Bubble = memo(function Bubble({);return (- <div {...{ [MESSAGE_ROW]: "" }} data-look={user ? "message-user" : "message-bot"} className={cn("group flex w-full flex-col", user ? "animate-msg-in items-end" : "items-start", simple && join?.above && SIMPLE_STACKED)}>+ <div {...{ [MESSAGE_ROW]: "" }} data-look={user ? "message-user" : "message-bot"} className={cn("group flex w-full flex-col", user ? cn(entering && "animate-msg-in", "items-end") : "items-start", simple && join?.above && SIMPLE_STACKED)}>{message.relay ? <RelayLabel message={message} /> : peer && <PeerLabel peer={peer} bots={bots} />}{speaker && <div className="mb-0.5 px-1 text-right text-[13px] [overflow-wrap:anywhere] font-semibold text-ink-secondary">{speaker}</div>}<div className={cn("flex w-full items-center gap-1.5", user ? "justify-end" : "justify-start")}>@@ -593,7 +594,7 @@ const MessagesList = memo(function MessagesList({// A finished turn keeps the bot's progress lines and folds only its tool steps under "Worked for", in both modes.const items = useMemo(() => groupTranscript(messages), [messages, locale]), earlier = useMemo(() => earlierAnswers(messages), [messages]);const drawnFrom = useMemo(() => drawFrom ? Math.max(0, items.findIndex((item) => item.kind === "message" ? item.message.id === drawFrom : item.messages.some((row) => row.id === drawFrom))) : 0, [items, drawFrom]);- const newestMessageId = messages.at(-1)?.id;+ const newestMessageId = messages.at(-1)?.id, rowKeys = useMemo(() => transcriptRowKeys(messages), [messages]);let newestUserMessageId: string | undefined;for (let i = messages.length - 1; i >= 0 && !newestUserMessageId; i--) {if (messages[i]!.role === "user") newestUserMessageId = messages[i]!.id;@@ -708,9 +709,9 @@ const MessagesList = memo(function MessagesList({}}})();- if (!row) return divider && <div key={m.id} className="contents">{divider}</div>;+ if (!row) return divider && <div key={rowKeys.get(m.id) ?? m.id} className="contents">{divider}</div>;return (- <div key={m.id} className="contents" data-mid={m.id} data-tuck={layout?.tucks[i] ? "" : undefined}>+ <div key={rowKeys.get(m.id) ?? m.id} className="contents" data-mid={m.id} data-tuck={layout?.tucks[i] ? "" : undefined}>{newDay && <DaySeparator at={m.at} today={today} simple={simple} />}{divider}{m.automation && <AutomationCaption message={m} line={m.automation} botId={botId} />}{m.inbox && <InboxCaption message={m} />}@@ -798,8 +799,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal// A beat the store still holds after it played is no beat: the face neither keeps moving nor replays it when a turn starts.const headerBeat = useMotionBeat(mascotMotion?.kind, mascotMotion?.nonce ?? 0), headerMotion = (headerBeat && mascotMotion?.kind) || "none";const headerAnimated = headerBeat || busy;- const branch = useRef(messages);- branch.current = messages;+ const branch = useRef(messages); branch.current = messages;const onBranch = useCallback((messageId: string) => branch.current.some((m) => m.id === messageId), []);const colorMine = useColorUserBubbles();// Simple mode draws your bubble in one flat tone of the bot's colour.@@ -833,10 +833,10 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal}, [lastTypedMessage]);const lastMessage = lastNonReceipt(messages);- const live = useTurnLive(bot.threadId), now = useTurnNow(bot, messages, lastMessage, live, advanced);+ const live = useTurnLive(bot.threadId), now = useTurnNow(bot, messages, lastMessage, live, advanced), awaiting = useAwaitingTurn(bot.threadId, lastMessage, Boolean(bot.busy));const toolInFlight = (lastMessage?.kind === "activity" && lastMessage.tool?.ok === undefined) || Boolean(live.status && live.status.activity !== "thinking" && live.status.activity !== "reply");- // The mascot and its status line stay for the whole turn; only its end hides them, never a timer.- const waiting = Boolean(bot.busy && bot.activity !== "waiting-on-you" && showWorkingDots(bot.busy, lastMessage, undefined, live.ended));+ // The mascot and its status line show from the send and stay for the whole turn; only its end hides them, never a timer.+ const waiting = bot.busy ? bot.activity !== "waiting-on-you" && showWorkingDots(bot.busy, lastMessage, undefined, live.ended) : awaiting;const wasWaiting = useRef(false);const [popping, setPopping] = useState<string | null>(null);const poppingTimer = useRef<ReturnType<typeof setTimeout> | null>(null);diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsxindex 60ac6bef8d..ae03b2b79a 100644--- a/src/components/CodeBlock.tsx+++ b/src/components/CodeBlock.tsx@@ -203,11 +203,15 @@ export function CodeBlock({ code, lang, initialWrap = false, open = false }: Codconst frame = useRef<HTMLDivElement>(null);// A long chat can hold dozens of blocks: coloured ones are thousands of spans to style and lay out on every switch,// so a block is coloured only once it comes near the screen.- const near = useNearScreen(frame);const highlightable = !open && code.length <= HIGHLIGHT_MAX_CHARS;- const [html, setHtml] = useState<string | null>(() => highlightable && near ? highlightCache.get(highlightKey(lang, code)) ?? null : null);+ const key = useMemo(() => highlightable ? highlightKey(lang, code) : null, [highlightable, lang, code]);+ // A colouring already made (a chat opened again) is drawn in the frame the block first appears in, read here in render.+ const cached = key === null ? undefined : highlightCache.get(key);+ const near = useNearScreen(frame, cached !== undefined);+ const [html, setHtml] = useState<string | null>(null);+ const shown = !highlightable || !near ? null : cached ?? html;// React compares dangerouslySetInnerHTML by identity: a fresh object each render rebuilds the highlighted DOM.- const markup = useMemo(() => (html ? { __html: html } : null), [html]);+ const markup = useMemo(() => (shown ? { __html: shown } : null), [shown]);const { state: copied, copy } = useCopyFeedback(code);const [wrapLines, setWrapLines] = useState(initialWrap);useEffect(() => {@@ -215,11 +219,11 @@ export function CodeBlock({ code, lang, initialWrap = false, open = false }: Cod}, [initialWrap]);useEffect(() => {- if (!highlightable) return setHtml(null);+ if (key === null) return setHtml(null);if (!near) return;- const key = highlightKey(lang, code);- const cached = highlightCache.get(key);- if (cached) return setHtml(cached);+ // Held in state too, so a colouring the cache later lets go of stays drawn.+ const ready = highlightCache.get(key);+ if (ready) return setHtml(ready);let alive = true;highlightFence(code, lang || "text").then((out) => {@@ -232,7 +236,7 @@ export function CodeBlock({ code, lang, initialWrap = false, open = false }: Codreturn () => {alive = false;};- }, [code, lang, highlightable, near]);+ }, [code, lang, key, near]);const download = () => {const filename = getSnippetFileName(lang);diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex c39e9e8ec0..ee7db89367 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -82,6 +82,7 @@ import { RoomBulletin } from "./RoomBulletin";import { RoomHeader } from "./RoomHeader";import { useChatFindRequests, useChatFindShortcut } from "@/lib/chat-find";import { simpleRoomHeader } from "@/lib/room-panel";+import { transcriptRowKeys } from "@/lib/transcript-row-keys";export const RoomToolChip = memo(function RoomToolChip({ message, roomId, threadId, live = false }: { message: Message; roomId?: string; threadId?: string; live?: boolean; /** Drawn again in a new language. */ locale?: string }) {const bots = useStoreSelector((s) => s.bots), instances = useStoreSelector((s) => s.instances), dispatch = useStoreDispatch(), store = useStoreRef();@@ -188,6 +189,8 @@ export const Transcript = memo(function Transcript({emerging={emerging} eager={eager} onReply={onReply} canReact={canReact} phone={phone} locale={locale} localVoice={localVoice} />);const unreadIds = useMemo(() => unreadMessageIds(messages, unreadDividerId), [messages, unreadDividerId]);+ // A send keeps one row from its optimistic stand-in to the server's copy (lib/transcript-row-keys).+ const rowKeys = useMemo(() => transcriptRowKeys(messages), [messages]);let dividerPlaced = false;const dividerAbove = (rows: readonly Message[]) => {if (!unreadIds || dividerPlaced || !rows.some((row) => unreadIds.has(row.id))) return null;@@ -290,10 +293,10 @@ export const Transcript = memo(function Transcript({textRow(m, m.id === emergingId, m.id === newestMessageId || m.id === newestUserMessageId))) : null;- if (!row) return divider && <div key={m.id} className="contents">{divider}</div>;+ if (!row) return divider && <div key={rowKeys.get(m.id) ?? m.id} className="contents">{divider}</div>;const fold = folds.byTerminalId.get(m.id);return (- <div key={m.id} className="contents" data-mid={m.id}>+ <div key={rowKeys.get(m.id) ?? m.id} className="contents" data-mid={m.id}>{newDay && (<div className="py-3 text-center text-[13px] text-ink-secondary">{dayLabel(m.at)} {formatTime(m.at)}diff --git a/src/components/TurnPresence.test.ts b/src/components/TurnPresence.test.tsindex 39120f6912..1b211b134e 100644--- a/src/components/TurnPresence.test.ts+++ b/src/components/TurnPresence.test.ts@@ -1,5 +1,5 @@// @vitest-environment happy-dom-import { act, createElement } from "react";+import { act, createElement, useLayoutEffect } from "react";import { createRoot, type Root } from "react-dom/client";import { renderToStaticMarkup } from "react-dom/server";import { readFileSync } from "node:fs";@@ -219,3 +219,23 @@ describe("thinking shimmer box", () => {expect(phrase.querySelector(".thinking-sheen")?.getAttribute("aria-hidden")).toBe("true");});});++describe("TurnPresence arriving", () => {+ it("is drawn in the commit that makes it visible, entering, not a frame later", () => {+ const atCommit: boolean[] = [];+ function Probe({ visible }: { visible: boolean }) {+ useLayoutEffect(() => { atCommit.push(Boolean(host.querySelector(".turn-presence .turn-mascot-in"))); });+ return createElement(TurnPresence, { avatar: null, visible, seed, since: null });+ }+ act(() => root.render(createElement(Probe, { visible: false })));+ act(() => root.render(createElement(Probe, { visible: true })));+ expect(atCommit.slice(0, 2)).toEqual([false, true]);+ // Back after it left: it enters again rather than drawing the way out it last played.+ act(() => root.render(createElement(Probe, { visible: false })));+ act(() => void vi.advanceTimersByTime(400));+ atCommit.length = 0;+ act(() => root.render(createElement(Probe, { visible: true })));+ expect(atCommit[0]).toBe(true);+ expect(host.querySelector(".turn-mascot-out")).toBeNull();+ });+});diff --git a/src/components/TurnPresence.tsx b/src/components/TurnPresence.tsxindex d20667e057..b454c373d2 100644--- a/src/components/TurnPresence.tsx+++ b/src/components/TurnPresence.tsx@@ -145,7 +145,9 @@ export function TurnPresence({return () => clearTimeout(timer);}, [visible, answering, mounted]);- const showWorking = presencePhase === "think";+ // Until the effect below has run, a presence becoming visible enters as a fresh one would, whatever it last left.+ const phaseNow = !mounted && visible ? (answering ? "answer" : "think") : presencePhase;+ const showWorking = phaseNow === "think";const expandable = Boolean(card) && showWorking;useEffect(() => {if (!expandable) setOpen(false);@@ -165,8 +167,10 @@ export function TurnPresence({}, [open]);const lead = label ?? t("chat.activity.working");const now = phrases && phrases.length > 0 ? phrases : null;- const { current, previous } = useRotatingPhrase(now ?? NOTHING, phase ?? now?.[0] ?? "", seed, mounted && showWorking && now !== null);- if (!mounted) return null;+ // Shown in the commit that makes it visible, not a frame later: the rows above it take their places once.+ const shown = mounted || visible;+ const { current, previous } = useRotatingPhrase(now ?? NOTHING, phase ?? now?.[0] ?? "", seed, shown && showWorking && now !== null);+ if (!shown) return null;const status = showWorking && simple ? (<span id={statusId} className="flex min-w-0 items-baseline gap-x-1.5 text-[14px] leading-[22px] text-ink-tertiary" data-turn-status><span className="turn-phrase turn-phrase-quiet relative grid min-w-0" title={hover} data-turn-now={now ? "" : undefined}>@@ -216,8 +220,8 @@ export function TurnPresence({title={simple && showWorking ? [lead, since !== null ? formatElapsed(Date.now() - since) : null, detail ?? (now ? current : null), size].filter(Boolean).join(" · ") : undefined}className={cn(simple ? "flex h-9 min-w-0 max-w-full items-center gap-2 ps-2" : "flex min-w-0 max-w-full items-center gap-2",- presencePhase === "think" && "turn-mascot-in",- presencePhase === "out" && "turn-mascot-out",+ phaseNow === "think" && "turn-mascot-in",+ phaseNow === "out" && "turn-mascot-out",)}>{avatar}diff --git a/src/hooks/use-awaiting-turn.test.ts b/src/hooks/use-awaiting-turn.test.tsnew file mode 100644index 0000000000..58105e9377--- /dev/null+++ b/src/hooks/use-awaiting-turn.test.ts@@ -0,0 +1,60 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { optimisticUserMessage } from "@/state/optimistic-send";+import type { Message } from "@/state/store";+import { useAwaitingTurn } from "./use-awaiting-turn";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const seen: boolean[] = [];+function Probe({ threadId, last, busy }: { threadId: string; last: Message | undefined; busy: boolean }) {+ seen.push(useAwaitingTurn(threadId, last, busy));+ return null;+}+let root: Root;+const show = (last: Message | undefined, busy = false, threadId = "t") => act(() => root.render(createElement(Probe, { threadId, last, busy })));+const now = () => seen.at(-1);+const sent = optimisticUserMessage("hi", "s1");+const copy: Message = { ...sent, id: "server-1" };+const reply: Message = { id: "r1", role: "bot", kind: "text", at: 2, text: "ok" };++beforeEach(() => {+ seen.length = 0;+ root = createRoot(document.createElement("div"));+});+afterEach(() => act(() => root.unmount()));++describe("useAwaitingTurn", () => {+ it("waits from the send through its server copy until the bot is seen busy, then never again for that send", () => {+ show(sent);+ expect(now()).toBe(true);+ show(copy);+ expect(now(), "the reply's copy lands before the busy frame").toBe(true);+ show(copy, true);+ expect(now()).toBe(false);+ show(copy, false);+ expect(now(), "a turn that ended with no row after the send").toBe(false);+ });++ it("ends when a row follows the send, the send is taken back, or another conversation opens", () => {+ show(sent);+ show(reply);+ expect(now()).toBe(false);+ show(copy);+ expect(now()).toBe(false);+ show(sent);+ show(undefined);+ expect(now()).toBe(false);+ show(sent);+ show(copy, false, "other");+ expect(now()).toBe(false);+ });++ it("never waits for an old message of the person's that it did not see sent", () => {+ show(copy);+ expect(now()).toBe(false);+ });+});diff --git a/src/hooks/use-awaiting-turn.ts b/src/hooks/use-awaiting-turn.tsnew file mode 100644index 0000000000..f5bc834feb--- /dev/null+++ b/src/hooks/use-awaiting-turn.ts@@ -0,0 +1,21 @@+import { useLayoutEffect, useRef } from "react";+import { awaitingTurn } from "@/lib/turn-tail";+import type { Message } from "@/state/store";++/**+ * Whether the person's send is waiting for the turn it starts: from Enter until the bot is first seen busy, so the+ * status line shows with the bubble and stays through the gap between the send's reply (which carries the server's copy+ * and lands first) and the live frame that says the bot is busy. A send the server takes back, or any row after it,+ * ends the wait; so does seeing the bot busy, after which `busy` alone says whether the turn runs.+ */+export function useAwaitingTurn(threadId: string, lastMessage: Message | undefined, busy: boolean): boolean {+ const sent = useRef<{ threadId: string; sendId: string } | null>(null);+ const optimistic = awaitingTurn(lastMessage);+ const sendId = lastMessage?.role === "user" ? lastMessage.sendId : undefined;+ const waiting = optimistic || (!busy && sendId !== undefined && sent.current?.threadId === threadId && sent.current.sendId === sendId);+ useLayoutEffect(() => {+ if (optimistic && sendId) sent.current = { threadId, sendId };+ else if (busy || !sendId || sent.current?.threadId !== threadId || sent.current.sendId !== sendId) sent.current = null;+ }, [optimistic, sendId, busy, threadId]);+ return waiting && !busy;+}diff --git a/src/hooks/use-switch-hold.test.ts b/src/hooks/use-switch-hold.test.tsnew file mode 100644index 0000000000..0d4a8fcc7f--- /dev/null+++ b/src/hooks/use-switch-hold.test.ts@@ -0,0 +1,70 @@+// @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 { SWITCH_HOLD_MS, useSwitchHold } from "./use-switch-hold";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++type Chat = { id: string; threadId: string; switchingTo?: string };+let bots: Chat[] = [];+const drawn: string[] = [];+function Pane({ selected }: { selected: Chat | undefined }) {+ const shown = useSwitchHold(selected, (id) => bots.find((bot) => bot.id === id));+ drawn.push(shown ? `${shown.id}:${shown.threadId}` : "none");+ return null;+}++let root: Root;+const show = (selected: Chat | undefined) => act(() => root.render(createElement(Pane, { selected })));+const last = () => drawn.at(-1);++beforeEach(() => {+ vi.useFakeTimers();+ drawn.length = 0;+ bots = [{ id: "a", threadId: "a-1" }, { id: "b", threadId: "b-1" }];+ root = createRoot(document.createElement("div"));+});+afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});++describe("useSwitchHold", () => {+ it("keeps the chat on screen while another bot's conversation is read, then draws the one asked for", () => {+ show(bots[0]);+ show({ ...bots[1]!, switchingTo: "b-2" });+ expect(drawn).toEqual(["a:a-1", "a:a-1"]);+ // The held chat is read live.+ bots[0] = { ...bots[0]!, threadId: "a-1" };+ show({ id: "b", threadId: "b-2" });+ expect(last()).toBe("b:b-2");+ expect(drawn).not.toContain("b:b-1");+ });++ it("holds no longer than its limit, then draws the selected bot as it is", () => {+ show(bots[0]);+ show({ ...bots[1]!, switchingTo: "b-2" });+ act(() => void vi.advanceTimersByTime(SWITCH_HOLD_MS - 1));+ expect(last()).toBe("a:a-1");+ act(() => void vi.advanceTimersByTime(1));+ expect(last()).toBe("b:b-1");+ show({ id: "b", threadId: "b-2" });+ expect(last()).toBe("b:b-2");+ // The next switch to that conversation holds again.+ show(bots[0]);+ show({ ...bots[1]!, switchingTo: "b-2" });+ expect(last()).toBe("a:a-1");+ });++ it("holds nothing for a switch within the chat on screen, a switch already held, or a first draw", () => {+ show({ ...bots[0]!, switchingTo: "a-2" });+ expect(last()).toBe("a:a-1");+ show(undefined);+ show({ ...bots[1]!, switchingTo: "b-2" });+ expect(last()).toBe("b:b-1");+ show({ ...bots[0]!, switchingTo: "a-1" });+ expect(last()).toBe("a:a-1");+ });+});diff --git a/src/hooks/use-switch-hold.ts b/src/hooks/use-switch-hold.tsnew file mode 100644index 0000000000..ba91b3b1d4--- /dev/null+++ b/src/hooks/use-switch-hold.ts@@ -0,0 +1,39 @@+import { useEffect, useLayoutEffect, useRef, useState } from "react";++/** The longest a chat switch keeps the chat it left on screen while the one it opens is read. */+export const SWITCH_HOLD_MS = 150;++interface Switchable {+ id: string;+ threadId: string;+ switchingTo?: string;+}++/**+ * The chat to draw. Opening another bot's conversation the app does not hold yet (its row marked for an unread reply,+ * or one of its threads) selects the bot at once but has its messages only when the server answers; drawing the bot+ * meanwhile paints its last conversation for a frame or more, then the one asked for. So the chat that was on screen+ * stays until the answer lands, up to `SWITCH_HOLD_MS`, then the selected bot as it is. `find` reads the held chat live,+ * so it keeps updating while held.+ */+export function useSwitchHold<T extends Switchable>(selected: T | undefined, find: (id: string) => T | undefined): T | undefined {+ const drawn = useRef<string | undefined>(undefined);+ const [expired, setExpired] = useState<string | null>(null);+ const waitingFor = selected?.switchingTo !== undefined && selected.switchingTo !== selected.threadId+ ? `${selected.id}:${selected.switchingTo}` : null;+ const from = waitingFor !== null && expired !== waitingFor && drawn.current !== undefined && drawn.current !== selected!.id+ ? find(drawn.current) : undefined;+ const shown = from ?? selected;+ const holding = from !== undefined;+ useLayoutEffect(() => {+ drawn.current = shown?.id;+ });+ useEffect(() => {+ // A switch that landed lets the next one to the same conversation hold again.+ if (waitingFor === null) return setExpired(null);+ if (!holding) return;+ const timer = setTimeout(() => setExpired(waitingFor), SWITCH_HOLD_MS);+ return () => clearTimeout(timer);+ }, [holding, waitingFor]);+ return shown;+}diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.tsindex fe1164443b..4ef4fa61d4 100644--- a/src/hooks/use-transcript-viewport.ts+++ b/src/hooks/use-transcript-viewport.ts@@ -14,6 +14,7 @@ import {import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, useBottomFollowResize } from "@/lib/bottom-follow";import { afterPaint } from "@/lib/after-paint";import { useFocusMessage } from "@/lib/focus-message";+import { settleNearScreen } from "@/lib/on-screen";import {TRANSCRIPT_WINDOW_MAX,TRANSCRIPT_WINDOW_SIZE,@@ -384,6 +385,9 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({if (!aside || !list) return;if (aside.key !== transcriptKey || restoreSelection(list, aside.selection) !== "waiting") setAside.current = null;});+ // Last of the layout effects, with the scroll position final: code blocks with a colouring ready learn they are on+ // screen before this paint (lib/on-screen), so a chat opened again shows its code coloured in its first frame.+ useLayoutEffect(() => settleNearScreen());useEffect(() => {const pressed = () => {setAside.current = null;diff --git a/src/lib/on-screen.test.ts b/src/lib/on-screen.test.tsindex 0dfda0954c..93bf931c1a 100644--- a/src/lib/on-screen.test.ts+++ b/src/lib/on-screen.test.ts@@ -1,9 +1,9 @@// @vitest-environment happy-dom-import { act, createElement, useRef } from "react";+import { act, createElement, useLayoutEffect, useRef } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useNearScreen } from "./on-screen";+import { settleNearScreen, useNearScreen } from "./on-screen";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -62,3 +62,44 @@ describe("useNearScreen", () => {expect(near()).toBe("true");});});++/** A scroller as the chat's: it puts its scroll position in place, then answers what asked before the paint. */+function Scroller({ top, seen }: { top: number; seen: string[] }) {+ return createElement(Settles, null, createElement(Asking, { top, seen }));+}+function Settles({ children }: { children: unknown }) {+ useLayoutEffect(() => settleNearScreen());+ return createElement("div", null, children as never);+}+function Asking({ top, seen }: { top: number; seen: string[] }) {+ const ref = useRef<HTMLDivElement>(null);+ const near = useNearScreen(ref, true);+ // What each commit would paint.+ useLayoutEffect(() => { seen.push(String(near)); });+ return createElement("div", { ref, "data-near": String(near), "data-top": top });+}++describe("settleNearScreen", () => {+ beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {+ const top = Number(this.dataset.top ?? 0);+ return { top, bottom: top + 100, left: 0, right: 300, width: 300, height: 100, x: 0, y: top, toJSON() {} } as DOMRect;+ });+ });+ afterEach(() => vi.restoreAllMocks());++ it("tells a block that asked before paint that it is near in the commit that mounted it, with no observer report", () => {+ const seen: string[] = [];+ act(() => root.render(createElement(Scroller, { top: 200, seen })));+ // The commit that mounted it was answered before its paint: the next commit (still before the paint) draws it near.+ expect(seen).toEqual(["false", "true"]);+ expect(host.querySelector<HTMLElement>("[data-near]")!.dataset.near).toBe("true");+ });++ it("leaves a block far below the screen to the observer", () => {+ const seen: string[] = [];+ act(() => root.render(createElement(Scroller, { top: innerHeight + 2_000, seen })));+ expect(seen).toEqual(["false"]);+ expect([...FakeObserver.last!.watched]).toHaveLength(1);+ });+});diff --git a/src/lib/on-screen.ts b/src/lib/on-screen.tsindex c8478064a0..0d80575455 100644--- a/src/lib/on-screen.ts+++ b/src/lib/on-screen.ts@@ -1,4 +1,4 @@-import { useEffect, useState, type RefObject } from "react";+import { useEffect, useLayoutEffect, useState, type RefObject } from "react";// One observer per margin, each with its own elements, so an element can be watched at two margins at once.const observers = new Map<number, { observer: IntersectionObserver; watchers: Map<Element, (onScreen: boolean) => void> }>();@@ -40,9 +40,51 @@ export function useOnScreen(ref: RefObject<Element | null>): boolean {const NEAR_SCREEN_MARGIN = 800;-/** Stays true once the element has come near the screen; true at once where the browser has no IntersectionObserver. */-export function useNearScreen(ref: RefObject<Element | null>): boolean {+/** Elements waiting to be told, before the paint, whether they mount near the screen (see `settleNearScreen`). */+const askedBeforePaint = new Map<Element, () => void>();++/** Whether `element` is within `margin` of the screen now, clipped by the boxes it scrolls in, as the observer counts. */+function nearScreenNow(element: Element, margin: number): boolean {+ const box = element.getBoundingClientRect();+ if (box.width === 0 && box.height === 0) return false;+ let top = -margin, bottom = window.innerHeight + margin;+ for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) {+ const overflow = getComputedStyle(parent).overflowY;+ if (overflow !== "auto" && overflow !== "scroll") continue;+ const frame = parent.getBoundingClientRect();+ top = Math.max(top, frame.top - margin);+ bottom = Math.min(bottom, frame.bottom + margin);+ }+ return box.bottom >= top && box.top <= bottom;+}++/**+ * Answers, in the commit that mounted them, the elements that asked before paint whether they are near the screen.+ * Called by a scroller from a layout effect once it has put its scroll position in place, so a block drawn in a chat's+ * first frame is coloured in that frame instead of one frame later, when the observer would report.+ */+export function settleNearScreen(): void {+ if (askedBeforePaint.size === 0) return;+ const asked = [...askedBeforePaint];+ askedBeforePaint.clear();+ for (const [element, near] of asked) if (nearScreenNow(element, NEAR_SCREEN_MARGIN)) near();+}++/**+ * Stays true once the element has come near the screen; true at once where the browser has no IntersectionObserver.+ * `beforePaint`: the element has something ready to draw once near (a cached colouring), so it also asks the scroller+ * that mounts it (`settleNearScreen`) before the first paint.+ */+export function useNearScreen(ref: RefObject<Element | null>, beforePaint = false): boolean {const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");+ useLayoutEffect(() => {+ const element = ref.current;+ if (near || !beforePaint || !element) return;+ askedBeforePaint.set(element, () => setNear(true));+ return () => {+ askedBeforePaint.delete(element);+ };+ }, [ref, near, beforePaint]);useEffect(() => {const element = ref.current;if (near || !element) return;diff --git a/src/lib/transcript-row-keys.test.ts b/src/lib/transcript-row-keys.test.tsnew file mode 100644index 0000000000..ba0427c2c2--- /dev/null+++ b/src/lib/transcript-row-keys.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest";++import { optimisticMessageId } from "@/state/optimistic-send";+import { transcriptRowKeys } from "./transcript-row-keys";++describe("transcriptRowKeys", () => {+ it("keys a send's optimistic stand-in and the server's copy alike", () => {+ const sent = transcriptRowKeys([{ id: "a" }, { id: optimisticMessageId("s1"), sendId: "s1" }]);+ const echoed = transcriptRowKeys([{ id: "a" }, { id: "server-1", sendId: "s1" }]);+ expect(sent.get(optimisticMessageId("s1"))).toBe("send:s1");+ expect(echoed.get("server-1")).toBe("send:s1");+ expect(sent.has("a")).toBe(false);+ });++ it("gives no shared key to rows that carry the same sendId", () => {+ const keys = transcriptRowKeys([{ id: "x", sendId: "s1" }, { id: "y", sendId: "s1" }, { id: "z", sendId: "s2" }]);+ expect(keys.has("x")).toBe(false);+ expect(keys.has("y")).toBe(false);+ expect(keys.get("z")).toBe("send:s2");+ });+});diff --git a/src/lib/transcript-row-keys.ts b/src/lib/transcript-row-keys.tsnew file mode 100644index 0000000000..815ade67c2--- /dev/null+++ b/src/lib/transcript-row-keys.ts@@ -0,0 +1,15 @@+/**+ * React keys for a transcript's rows. A sent message is keyed by its sendId, which its optimistic stand-in and the+ * server's copy share, so the copy replaces the stand-in in place: one row from Enter to the echo, its entrance played+ * once. A sendId more than one row carries keys none of them, and those rows keep their ids.+ */+export function transcriptRowKeys(messages: readonly { id: string; sendId?: string }[]): ReadonlyMap<string, string> {+ const owners = new Map<string, string | null>();+ for (const message of messages) {+ if (!message.sendId) continue;+ owners.set(message.sendId, owners.has(message.sendId) ? null : message.id);+ }+ const keys = new Map<string, string>();+ for (const [sendId, id] of owners) if (id !== null) keys.set(id, `send:${sendId}`);+ return keys;+}diff --git a/src/lib/turn-tail.test.ts b/src/lib/turn-tail.test.tsindex 997fb49e2c..57ad85da06 100644--- a/src/lib/turn-tail.test.ts+++ b/src/lib/turn-tail.test.ts@@ -1,7 +1,8 @@import { describe, expect, it } from "vitest";import type { Message } from "@/state/store";-import { awaitedMemberId, showWorkingDots } from "./turn-tail";+import { awaitedMemberId, awaitingTurn, showWorkingDots } from "./turn-tail";+import { optimisticUserMessage } from "@/state/optimistic-send";const msg = (m: Partial<Message>): Message => ({ id: "m1", role: "bot", kind: "text", at: 1, ...m });@@ -66,3 +67,14 @@ describe("awaitedMemberId", () => {expect(awaitedMemberId(true, null, undefined)).toBeUndefined();});});++describe("awaitingTurn", () => {+ it("is the person's send until the server's copy of it lands", () => {+ const sent = optimisticUserMessage("hi", "s1");+ expect(awaitingTurn(sent)).toBe(true);+ expect(awaitingTurn({ ...sent, id: "server-1" })).toBe(false);+ expect(awaitingTurn(msg({ role: "user" }))).toBe(false);+ expect(awaitingTurn(msg({}))).toBe(false);+ expect(awaitingTurn(undefined)).toBe(false);+ });+});diff --git a/src/lib/turn-tail.ts b/src/lib/turn-tail.tsindex a4d0df82dd..8c4e769024 100644--- a/src/lib/turn-tail.ts+++ b/src/lib/turn-tail.ts@@ -1,3 +1,4 @@+import { optimisticMessageId } from "@/state/optimistic-send";import type { Message } from "@/state/store";/** Whether the mascot and its status line show under the transcript. They stay for the whole turn: a bot's text in the@@ -18,6 +19,12 @@ export function showWorkingDots(return !turnEnded;}+/** Whether the newest row is the person's send the server has not yet taken: its optimistic stand-in. A send it refuses+ * is taken back. (hooks/use-awaiting-turn carries the wait on to the frame that says the bot is busy.) */+export function awaitingTurn(lastMessage: Message | undefined): boolean {+ return lastMessage?.role === "user" && lastMessage.sendId !== undefined && lastMessage.id === optimisticMessageId(lastMessage.sendId);+}+export function awaitedMemberId(working: boolean | undefined,speakerBotId: string | null | undefined,