Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat: saved rows hold still while a reply streams (#6560)
Milind Soni9d101a632dc3
diff --git a/src/components/ChatView.rows-hold-still.test.ts b/src/components/ChatView.rows-hold-still.test.tsnew file mode 100644index 0000000000..bfae294c79--- /dev/null+++ b/src/components/ChatView.rows-hold-still.test.ts@@ -0,0 +1,159 @@+// @vitest-environment happy-dom+// The real provider and live stream, a long chat on screen: a reply streaming in, or another bot at work, draws no saved row again.+import { countBy, renderMark, renderedSince } from "@/testing/render-counts";+import { 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() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true, 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 DAY = 86_400_000;+const start = Date.UTC(2026, 10, 1, 9);+/** Sixty rows over a few days: asks, answers with a link, folded tool steps and work summaries. */+function transcript(): Message[] {+ const rows: Message[] = [];+ for (let turn = 0; turn < 10; turn++) {+ const at = start + turn * DAY / 3, turnId = `turn-${turn}`;+ rows.push({ id: `ask-${turn}`, role: "user", kind: "text", at, text: `Question ${turn}` });+ rows.push({ id: `note-${turn}`, role: "bot", kind: "text", at: at + 1_000, text: `Looking into ${turn}.`, turnId });+ rows.push({ id: `step-${turn}a`, role: "bot", kind: "activity", at: at + 2_000, tool: { name: "Bash", ok: true }, turnId });+ rows.push({ id: `step-${turn}b`, role: "bot", kind: "activity", at: at + 3_000, tool: { name: "Read", ok: true }, turnId });+ rows.push({ id: `answer-${turn}`, role: "bot", kind: "text", at: at + 9_000, text: `Answer ${turn}, see https://example.com/${turn}.`, turnId, turnTerminal: true });+ rows.push({ id: `digest-${turn}`, role: "bot", kind: "digest", at: at + 9_500, text: "", digest: {+ turnId, botId: "b", threadId: "b-thread", at: at + 9_500, durationMs: 9_000, tools: [{ name: "Bash", count: 1, failed: 0 }, { name: "Read", count: 1, failed: 0 }],+ memory: [], reply: "", hookCoverage: "preview",+ } } as Message);+ }+ 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 === "b"));+ return bot ? createElement(ChatView, { bot }) : null;+}++let root: Root;+let cursor = 0;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 6; i++) await task(); };+const stream = () => FixtureEventSource.opened[0]!;+const send = async (frame: object) => { stream().send(frame, `run:${++cursor}`); await settle(); };+const runtime = (threadId: string, event: object) => send({ kind: "runtime", event: {+ eventId: `e${++cursor}`, provider: "codex", threadId, turnId: "live-turn", createdAt: "2026-11-18T00:00:00.000Z", ...event,+} });+const say = (threadId: string, delta: string) => runtime(threadId, { type: "content.delta", streamKind: "assistant_text", delta, itemId: "live-item" });+const liveRow = () => document.querySelector('[data-mid^="live:"]');+let mounted = new Map<string, number>();++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?")+ ? json({ bots: [{ ...announced("a", "Ada"), messages: [] }, { ...announced("b", "Bea"), messages: transcript() }], groups: [] })+ : json(answers[path.replace(/\?.*$/, "")] ?? {}));+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ const mark = renderMark();+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Shown), createElement(Shell))));+ await settle();+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "select", id: "b" }));+ await settle();+ mounted = countBy(renderedSince(mark), (entry) => entry.component);+});+afterAll(() => {+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});++describe("a long chat on screen", () => {+ it("draws every kind of row these checks watch", () => {+ expect(document.querySelectorAll("[data-mid]").length).toBeGreaterThan(30);+ for (const component of ["Bubble", "DigestChip", "TurnNarrationRun", "PublishedSiteCards", "DaySeparator", "ForkLinks"]) {+ expect(mounted.get(component) ?? 0, component).toBeGreaterThan(0);+ }+ });++ it("draws no saved row again while a reply streams in", async () => {+ await send({ kind: "bot", bot: { ...announced("b", "Bea"), busy: true, activity: "working" } });+ await runtime("b-thread", { type: "turn.started" });+ await say("b-thread", "Streaming ");+ expect(liveRow()?.textContent).toContain("Streaming");+ const mark = renderMark();+ for (let word = 0; word < 20; word++) await say("b-thread", `word${word} `);+ expect(liveRow()?.textContent).toContain("word19");+ const list = renderedSince(mark).filter((entry) => entry.component === "MessagesList" || (entry.row !== null && !entry.row.startsWith("live:")));+ expect(countBy(list, (entry) => entry.component), "neither the list nor a saved row draws again").toEqual(new Map());+ expect(renderedSince(mark).length, "the streaming row itself").toBeGreaterThan(0);+ });++ it("draws only the streamed row and the saved reply that takes its place", async () => {+ const mark = renderMark();+ await runtime("b-thread", { type: "item.completed", itemType: "assistant_text", itemId: "live-item", text: "Streaming done." });+ await send({ kind: "message", threadId: "b-thread", message: {+ id: "b-saved", itemId: "live-item", at: Date.now(), role: "bot", kind: "text", text: "Streaming done.", turnId: "live-turn", turnTerminal: true,+ } });+ expect(liveRow()).toBeNull();+ expect(document.querySelector('[data-mid="b-saved"]')?.textContent).toContain("Streaming done.");+ const rows = new Set(renderedSince(mark).flatMap((entry) => entry.row === null ? [] : [entry.row]));+ expect(rows).toEqual(new Set(["live:live-item", "b-saved"]));+ expect(renderedSince(mark).filter((entry) => entry.component === "TurnNarrationRun"), "a folded turn above").toEqual([]);+ });++ it("draws no row again while another bot works", async () => {+ const mark = renderMark();+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: true, activity: "working" } });+ await runtime("a-thread", { type: "turn.started" });+ for (let word = 0; word < 5; word++) await say("a-thread", `other${word} `);+ await send({ kind: "message", threadId: "a-thread", message: { id: "a1", at: start, role: "bot", kind: "text", text: "Done." } });+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: false, activity: "idle", tasks: [+ ...announced("a", "Ada").tasks!, { threadId: "a-fork", title: "Fork", createdAt: 2, approvalMode: "ask", origin: { threadId: "a-thread", messageId: "a1" } },+ ] } });+ flushSync(() => dispatch({ type: "connected", value: false }));+ flushSync(() => dispatch({ type: "connected", value: true }));+ await settle();+ expect(countBy(renderedSince(mark).filter((entry) => entry.row !== null), (entry) => entry.component)).toEqual(new Map());+ });+});diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 45f8ecb00e..7b9eb62495 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -58,7 +58,7 @@ import { normalizeState, stateForBot } from "@/lib/mascot";import { peerLine, peerPreview, peerRequest, type PeerLine } from "@/lib/peer-message"; import { PEER_HOW, PeerCompactRow, PeerMessagesContext, PeerOpenedActions } from "./PeerExchange";import { showWorkingDots } from "@/lib/turn-tail";import { lastNonReceipt } from "@/lib/receipts";-import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, streamedReply, useHasLiveReply, useLiveTranscript } from "@/state/live-reply"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";+import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, streamedReply, useHasLiveReply, useLiveRow, useLiveTranscriptLayout } from "@/state/live-reply"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";import { ChatMarkdown } from "./ChatMarkdown";import { LiveToolsContext, useLiveToolIds } from "@/hooks/use-live-tool-ids";import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";@@ -289,7 +289,7 @@ export function FailedTurnRow({ tool, engine, onRetry, botId, threadId, messageAexport { MessageBoundary };const Bubble = memo(function Bubble({- message,+ message: row,emerging = false,eagerAttachments = false,joinAbove = false,@@ -324,6 +324,7 @@ const Bubble = memo(function Bubble({onReply: (message: Message) => void;}) {const { botId, threadId, botName, voiceId, tts, localVoice, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer, phone } = useChatRows(), busy = use(ChatBusyContext);+ const message = useLiveRow(threadId, row);const forkAction = !phone && message.kind === "text" && !message.id.startsWith("optimistic-")? [forkMessageItem({ kind: "bot", ownerId: botId, threadId, messageId: message.id }, dispatch, busy)] : [];const remoteClient = window.ogb?.remoteClient?.active === true;@@ -663,7 +664,7 @@ const MessagesList = memo(function MessagesList({onReply: (message: Message) => void;}) {const { botId, threadId, botName, botColor, bots, hasMore, focus, showToolCalls, locale, dispatch, canReact, simple = false } = useChatRows(), busy = use(ChatBusyContext);- const messages = useLiveTranscript(threadId, saved, transcript);+ const messages = useLiveTranscriptLayout(threadId, saved, transcript);// 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]);const newestMessageId = messages.at(-1)?.id;@@ -675,8 +676,8 @@ const MessagesList = memo(function MessagesList({const unreadIds = useMemo(() => unreadMessageIds(messages, unreadDividerId), [messages, unreadDividerId]);let dividerPlaced = false;const layout = useMemo(() => simple ? simpleRowLayout(items, { botId, showToolCalls, unreadIds }) : null, [simple, items, unreadIds, showToolCalls, botId]);- const joins = layout?.joins;const durations = useMemo(() => simple ? turnDurations(messages) : null, [messages, simple]);+ const stepChip = useCallback((step: Message) => <div key={step.id} className="contents" data-mid={step.id}><ActivityChip message={step} place={place} /></div>, [place]);const dividerAbove = (rows: readonly Message[]) => {if (!unreadIds || dividerPlaced || !rows.some((row) => unreadIds.has(row.id))) return null;dividerPlaced = true;@@ -693,14 +694,13 @@ const MessagesList = memo(function MessagesList({if (item.kind === "turn" || item.kind === "run") {if (!showToolCalls) return divider && <div key={item.id} className="contents">{divider}</div>;const forceOpen = item.messages.some((step) => step.id === focusedId);- const steps = item.messages.map((step) => <div key={step.id} className="contents" data-mid={step.id}><ActivityChip message={step} place={place} /></div>);return (<div key={item.id} className="contents">{newDay && <DaySeparator at={first.at} today={today} simple={simple} />}{divider}{item.kind === "turn"- ? <TurnNarrationRun label={item.label} title={t("chat.run.showSteps")} forceOpen={forceOpen}>{steps}</TurnNarrationRun>- : <ActivityRun messages={item.messages} forceOpen={forceOpen}>{steps}</ActivityRun>}+ ? <TurnNarrationRun label={item.label} title={t("chat.run.showSteps")} forceOpen={forceOpen} steps={item.messages} step={stepChip} />+ : <ActivityRun messages={item.messages} forceOpen={forceOpen}>{item.messages.map(stepChip)}</ActivityRun>}</div>);}@@ -762,8 +762,8 @@ const MessagesList = memo(function MessagesList({message={m}emerging={m.id === emergingId}eagerAttachments={m.id === newestMessageId || m.id === newestUserMessageId}- joinAbove={joins?.[i]?.above}- joinBelow={joins?.[i]?.below}+ joinAbove={layout?.joins[i]?.above}+ joinBelow={layout?.joins[i]?.below}workedFor={durations?.get(m.id)}editing={editingId === m.id}pinned={m.id === pinnedMessageId}diff --git a/src/components/DaySeparator.tsx b/src/components/DaySeparator.tsxindex 2ef3511f82..750a1896a0 100644--- a/src/components/DaySeparator.tsx+++ b/src/components/DaySeparator.tsx@@ -1,12 +1,13 @@// The day and time line between a conversation's days (ChatView.tsx).import { cn } from "@/lib/cn";+import { memoInLocale } from "@/lib/locale-memo";import { dayLabel } from "@/lib/transcript-derivations";import { formatTime } from "@/state/store";-export function DaySeparator({ at, today, simple = false }: { at: number; today: number; simple?: boolean }) {+export const DaySeparator = memoInLocale(function DaySeparator({ at, today, simple = false }: { at: number; today: number; simple?: boolean }) {return (<div className={cn("text-center text-[13px] text-ink-secondary", simple ? "pt-5 pb-1 leading-[18px]" : "py-3")}>{dayLabel(at, today)} {formatTime(at)}</div>);-}+});diff --git a/src/components/DigestChip.tsx b/src/components/DigestChip.tsxindex 952580f99e..b40631e46a 100644--- a/src/components/DigestChip.tsx+++ b/src/components/DigestChip.tsx@@ -2,6 +2,7 @@ import { useState } from "react";import { ClipboardList } from "lucide-react";import { t } from "@/lib/i18n";+import { memoInLocale } from "@/lib/locale-memo";import type { LocaleKey } from "@/locales";import { formatDuration } from "@/lib/usage-trace";import type { Message } from "@/state/store";@@ -16,7 +17,7 @@ const WORK_KEY: Record<"noFiles" | "oneFile" | "files", Record<"oneTool" | "tool};const one = (count: number | string) => String(count) === "1";-export function DigestChip({ message }: { message: Message }) {+export const DigestChip = memoInLocale(function DigestChip({ message }: { message: Message }) {const [tracing, setTracing] = useState(false);const digest = message.digest;if (!digest) return null;@@ -43,7 +44,7 @@ export function DigestChip({ message }: { message: Message }) {{tracing && <TraceDialog id={traceRootId(digest.threadId, digest.turnId)} at={digest.at} onClose={() => setTracing(false)} />}</div>);-}+});const COMPACTION_CHIP = "max-w-[600px] rounded-xl border border-hairline/40 bg-panel px-3 py-2 text-[12px] text-ink-secondary";diff --git a/src/components/ForkMessage.tsx b/src/components/ForkMessage.tsxindex 1e522614bd..8b5db532d9 100644--- a/src/components/ForkMessage.tsx+++ b/src/components/ForkMessage.tsx@@ -2,7 +2,8 @@ import { GitFork } from "lucide-react";import type { Dispatch } from "react";import { ACTION_ICON, type MessageMenuItem } from "./MessageActions";import { t } from "@/lib/i18n";-import { useStore, type Action } from "@/state/store";+import type { Action, AppState } from "@/state/store";+import { sameItems, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Owner = { kind: "bot" | "group"; ownerId: string; threadId: string; messageId: string };@@ -16,12 +17,18 @@ export function forkMessageItem(owner: Owner, dispatch: Dispatch<Action>, disabl};}-export function ForkLinks(owner: Owner & { phone: boolean }) {- const { state, dispatch } = useStore();+const NO_FORKS: never[] = [];++function forksOf(state: AppState, owner: Owner) {const tasks = owner.kind === "bot"? state.bots?.find((bot) => bot.id === owner.ownerId)?.tasks: state.groups?.find((group) => group.id === owner.ownerId)?.tasks;- const forks = tasks?.filter((task) => task.origin?.threadId === owner.threadId && task.origin.messageId === owner.messageId) ?? [];+ return tasks?.filter((task) => task.origin?.threadId === owner.threadId && task.origin.messageId === owner.messageId) ?? NO_FORKS;+}++export function ForkLinks(owner: Owner & { phone: boolean }) {+ const dispatch = useStoreDispatch();+ const forks = useStoreSelector((state) => forksOf(state, owner), sameItems);if (owner.phone || !forks.length) return null;return (<div className="mt-1 flex flex-wrap gap-1" data-testid="fork-links">diff --git a/src/components/TurnNarrationRun.tsx b/src/components/TurnNarrationRun.tsxindex 84a0e5f2f0..c87b3516a6 100644--- a/src/components/TurnNarrationRun.tsx+++ b/src/components/TurnNarrationRun.tsx@@ -1,19 +1,21 @@// Providers such as Grok narrate before tools.-import { useEffect, useState } from "react";+import { memo, useEffect, useState, type ReactNode } from "react";import { Check, ChevronRight } from "lucide-react";import { t } from "@/lib/i18n";+import type { Message } from "@/state/store";+import { sameItems } from "@/state/store-select";-export function TurnNarrationRun({- label,- title,- forceOpen = false,- children,-}: {+type Props = {label: string;title?: string;forceOpen?: boolean;- children: React.ReactNode;-}) {+} & ({ children: ReactNode; steps?: never; step?: never } | { steps: readonly Message[]; step: (message: Message) => ReactNode; children?: never });++const sameProps = (a: Props, b: Props) =>+ a.label === b.label && a.title === b.title && a.forceOpen === b.forceOpen && a.children === b.children && a.step === b.step &&+ (a.steps === b.steps || (a.steps !== undefined && b.steps !== undefined && sameItems(a.steps, b.steps)));++export const TurnNarrationRun = memo(function TurnNarrationRun({ label, title, forceOpen = false, children, steps, step }: Props) {const [open, setOpen] = useState(forceOpen);useEffect(() => {if (forceOpen) setOpen(true);@@ -34,7 +36,7 @@ export function TurnNarrationRun({<ChevronRight size={13} className={open ? "rotate-90" : undefined} /></button></div>- {open && children}+ {open && (steps ? steps.map(step) : children)}</div>);-}+}, sameProps);diff --git a/src/components/published-apps/PublishedSiteCards.tsx b/src/components/published-apps/PublishedSiteCards.tsxindex e7f381c61c..9f20e5a243 100644--- a/src/components/published-apps/PublishedSiteCards.tsx+++ b/src/components/published-apps/PublishedSiteCards.tsx@@ -4,6 +4,7 @@ import { ArrowUpRight, Eye } from "lucide-react";import { openExternalLink } from "@/lib/app-links";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";+import { memoInLocale } from "@/lib/locale-memo";import { askAboutSite, useKnownPublishedApps } from "@/lib/own-published-apps";import { showAppBesideChat } from "@/lib/page-open";import { publishedSiteLinks, type SiteCardLink } from "@/lib/published-site-links";@@ -16,14 +17,17 @@ import { SiteThumb } from "./SiteThumb";/** Which shown message links each site, so only the newest of them draws it. */const claims = new Map<string, Map<string, number>>();const claimListeners = new Set<() => void>();-let claimsVersion = 0;function changeClaims(change: () => void): void {change();- claimsVersion += 1;for (const listener of claimListeners) listener();}+function subscribeClaims(listener: () => void): () => void {+ claimListeners.add(listener);+ return () => { claimListeners.delete(listener); };+}+function newestClaim(appId: string): string | undefined {let best: [string, number] | undefined;for (const [messageId, at] of claims.get(appId) ?? []) {@@ -40,15 +44,16 @@ function useNewestFor(links: readonly SiteCardLink[], messageId: string, at: numchangeClaims(() => { for (const id of ids) { if (!claims.has(id)) claims.set(id, new Map()); claims.get(id)!.set(messageId, at); } });return () => changeClaims(() => { for (const id of ids) { claims.get(id)?.delete(messageId); if (claims.get(id)?.size === 0) claims.delete(id); } });}, [sites, messageId, at]);- useSyncExternalStore((listener) => { claimListeners.add(listener); return () => { claimListeners.delete(listener); }; }, () => claimsVersion, () => claimsVersion);- return links.filter((link) => newestClaim(link.appId) === messageId);+ const newest = () => links.filter((link) => newestClaim(link.appId) === messageId).map((link) => link.appId).join("\n");+ const shown = useSyncExternalStore(subscribeClaims, newest, newest);+ return useMemo(() => links.filter((link) => shown.split("\n").includes(link.appId)), [links, shown]);}/** One card under a bot's reply for each of the viewer's own published sites it links to (their Published apps list),* on the newest reply that links it: the site drawn small, its name and address, Open (the preview beside the chat,* full screen on a phone) and Open in browser. Any other site stays a plain link. Nothing while the reply streams, and* nothing on a published page's or a template's own card. */-export function PublishedSiteCards({ message }: { message: Message }) {+export const PublishedSiteCards = memoInLocale(function PublishedSiteCards({ message }: { message: Message }) {const apps = useKnownPublishedApps();const done = message.role === "bot" && message.kind === "text" && !message.publishedPage && !message.template && !isLiveReply(message);const text = done ? message.text ?? "" : "";@@ -62,7 +67,7 @@ export function PublishedSiteCards({ message }: { message: Message }) {{shown.map((link) => <PublishedSiteCard key={link.appId} link={link} />)}</div>);-}+});function PublishedSiteCard({ link }: { link: SiteCardLink }) {const store = useOptionalStoreRef();diff --git a/src/lib/locale-memo.test.ts b/src/lib/locale-memo.test.tsnew file mode 100644index 0000000000..ea73fbeda4--- /dev/null+++ b/src/lib/locale-memo.test.ts@@ -0,0 +1,40 @@+// @vitest-environment happy-dom+import { createElement, useState } from "react";+import { flushSync } from "react-dom";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it } from "vitest";+import { setLocale, t } from "@/lib/i18n";+import { memoInLocale } from "./locale-memo";++afterEach(() => { setLocale("en"); });++describe("memoInLocale", () => {+ it("holds for the same props and draws again for new props or a new language", () => {+ let drawn = 0;+ const Label = memoInLocale(function Label({ id }: { id: string }) {+ drawn += 1;+ return createElement("span", null, `${t("trace.view")} ${id}`);+ });+ let redraw!: (id: string) => void;+ function Parent() {+ const [id, setId] = useState("a");+ const [, setTick] = useState(0);+ redraw = (next) => { setId(next); setTick((tick) => tick + 1); };+ return createElement(Label, { id });+ }+ const host = document.createElement("div");+ const root = createRoot(host);+ flushSync(() => root.render(createElement(Parent)));+ expect([drawn, host.textContent]).toEqual([1, "View trace a"]);+ flushSync(() => redraw("a"));+ expect(drawn, "same props, same language").toBe(1);+ flushSync(() => redraw("b"));+ expect([drawn, host.textContent]).toEqual([2, "View trace b"]);+ setLocale("de");+ flushSync(() => redraw("b"));+ expect(drawn).toBe(3);+ expect(host.textContent).toBe(`${t("trace.view")} b`);+ expect(host.textContent).not.toBe("View trace b");+ flushSync(() => root.unmount());+ });+});diff --git a/src/lib/locale-memo.ts b/src/lib/locale-memo.tsnew file mode 100644index 0000000000..4f41e2cf12--- /dev/null+++ b/src/lib/locale-memo.ts@@ -0,0 +1,17 @@+import { memo, type ReactNode } from "react";+import { activeLocale } from "@/lib/i18n";++const drawnIn = new WeakMap<object, string>();++/** `memo` for a component that reads `t()` or formats dates: it draws again when a prop changes or the language does,+ * which React cannot see. */+export function memoInLocale<P extends object>(component: (props: P) => ReactNode) {+ const Drawn = (props: P) => {+ drawnIn.set(props, activeLocale());+ return component(props);+ };+ Drawn.displayName = component.name;+ return memo(Drawn, (before, after) =>+ drawnIn.get(before) === activeLocale() && Object.keys(after).length === Object.keys(before).length &&+ (Object.keys(after) as (keyof P)[]).every((key) => Object.is(before[key], after[key])));+}diff --git a/src/state/live-reply.ts b/src/state/live-reply.tsindex 50d7943e86..7aa139bc89 100644--- a/src/state/live-reply.ts+++ b/src/state/live-reply.ts@@ -2,11 +2,12 @@// under and held outside the app reducer, so a delta re-renders only the transcript that shows that thread. A streamed// item stays drawn until the transcript holds the message saved under the same id, so the saved bubble replaces it in// the same commit.-import { createContext, useEffect, useMemo, useSyncExternalStore } from "react";+import { createContext, useCallback, useEffect, useMemo, useSyncExternalStore } from "react";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 type { Message } from "@/state/store";export interface LiveReplyItem {@@ -48,6 +49,7 @@ const streamed = new Set<string>();* turn boundary, since any item open across the gap lost its start. */let gapped = false;const boundarySinceGap = new Set<string>();+const shapes = new Map<string, { items: readonly LiveReplyItem[]; shapes: readonly LiveRowShape[] }>();function put(threadId: string, next: ThreadReplies): void {const current = threads.get(threadId);@@ -183,6 +185,13 @@ export function liveReplyText(item: Pick<LiveReplyItem, "text" | "done">): strinreturn isClientCancellation(text) ? "" : redactSecretsInText(text);}+const shownTexts = new WeakMap<LiveReplyItem, string>();+function shownText(item: LiveReplyItem): string {+ let text = shownTexts.get(item);+ if (text === undefined) shownTexts.set(item, (text = liveReplyText(item)));+ return text;+}+function subscribe(threadId: string | null | undefined, listener: () => void): () => void {if (!threadId) return () => {};let set = listeners.get(threadId);@@ -202,6 +211,17 @@ export function useLiveReplies(threadId: string | null | undefined): readonly Li);}+const noSubscription = () => () => {};++/** `row` as drawn now: a live row's words so far, from its thread's stream; any other row as it is, subscribing to nothing. */+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 item = live ? items.find((one) => `${LIVE_ID}${one.key}` === row.id) : undefined;+ return (item && liveRowOf(item)) || row;+}+export function useHasLiveReply(threadId: string | null | undefined): boolean {return useSyncExternalStore((listener) => subscribe(threadId, listener),@@ -226,9 +246,11 @@ export function roomLiveSpeaker(members: readonly RoomMember[], speakingNow?: st};}-/** The transcript rows the live items draw, after `transcript`'s own: an item whose saved message `transcript` holds- * draws nothing, so the two never show together. */-export function liveReplyRows(items: readonly LiveReplyItem[], transcript: readonly (Pick<Message, "id"> & { itemId?: string })[], speaker?: LiveSpeaker): { rows: Message[]; settled: string[] } {+type Drawable = Pick<LiveReplyItem, "key" | "itemId" | "savedAs">;++/** The rows `entries` draw after `transcript`'s own: an entry whose saved message `transcript` holds draws nothing, so+ * the two never show together. */+function drawnAfter<T extends Drawable>(entries: readonly T[], transcript: readonly (Pick<Message, "id"> & { itemId?: string })[], row: (entry: T) => Message | null): { rows: Message[]; settled: string[] } {const rows: Message[] = [];const settled: string[] = [];const ids = new Set<string>(), itemIds = new Set<string>();@@ -236,34 +258,111 @@ export function liveReplyRows(items: readonly LiveReplyItem[], transcript: readoids.add(message.id);if (message.itemId !== undefined) itemIds.add(message.itemId);}- for (const item of items) {- if ((item.itemId !== undefined && itemIds.has(item.itemId)) || (item.savedAs !== undefined && ids.has(item.savedAs))) {- settled.push(item.key);+ for (const entry of entries) {+ if ((entry.itemId !== undefined && itemIds.has(entry.itemId)) || (entry.savedAs !== undefined && ids.has(entry.savedAs))) {+ settled.push(entry.key);continue;}- const text = liveReplyText(item);- if (!text.trim()) continue;- const from = speaker?.(item.botId);- let row = rowCache.get(item);- if (!row || row.text !== text || !sameSpeaker(row.message.from, from)) {- row = { text, message: { id: `${LIVE_ID}${item.key}`, role: "bot", kind: "text", text, at: item.at, ...(item.turnId ? { turnId: item.turnId } : {}), ...(from ? { from } : {}) } as Message };- rowCache.set(item, row);- }- rows.push(row.message);+ const drawn = row(entry);+ if (drawn) rows.push(drawn);}return { rows, settled };}-/** The rows a transcript window draws: `windowed` (a slice of the whole `transcript`), then the live items. An item is- * matched against the whole transcript, so one saved outside the window is not drawn again; and live rows follow the- * newest message, so a window that stops short of it (scrolled back, or opened at a found or pinned message) draws none. */-export function withLiveRows(items: readonly LiveReplyItem[], windowed: Message[], transcript: readonly Message[], speaker?: LiveSpeaker): { rows: Message[]; settled: string[] } {- if (!items.length) return { rows: windowed, settled: [] };- const drawn = liveReplyRows(items, transcript, speaker);+function liveRowOf(item: LiveReplyItem, speaker?: LiveSpeaker): Message | null {+ const text = shownText(item);+ if (!text.trim()) return null;+ const from = speaker?.(item.botId);+ let row = rowCache.get(item);+ if (!row || row.text !== text || !sameSpeaker(row.message.from, from)) {+ row = { text, message: { id: `${LIVE_ID}${item.key}`, role: "bot", kind: "text", text, at: item.at, ...(item.turnId ? { turnId: item.turnId } : {}), ...(from ? { from } : {}) } as Message };+ rowCache.set(item, row);+ }+ return row.message;+}++/** The transcript rows the live items draw, after `transcript`'s own. */+export function liveReplyRows(items: readonly LiveReplyItem[], transcript: readonly (Pick<Message, "id"> & { itemId?: string })[], speaker?: LiveSpeaker): { rows: Message[]; settled: string[] } {+ return drawnAfter(items, transcript, (item) => liveRowOf(item, speaker));+}++/** `windowed` (a slice of the whole `transcript`) with `drawn` after it. An item is matched against the whole transcript,+ * so one saved outside the window is not drawn again; and live rows follow the newest message, so a window that stops+ * short of it (scrolled back, or opened at a found or pinned message) draws none. */+function windowWith(drawn: { rows: Message[]; settled: string[] }, windowed: Message[], transcript: readonly Message[]): { rows: Message[]; settled: string[] } {const atEnd = windowed.at(-1)?.id === transcript.at(-1)?.id;return { rows: atEnd && drawn.rows.length ? [...windowed, ...drawn.rows] : windowed, settled: drawn.settled };}+/** The rows a transcript window draws: `windowed`, then the live items. */+export function withLiveRows(items: readonly LiveReplyItem[], windowed: Message[], transcript: readonly Message[], speaker?: LiveSpeaker): { rows: Message[]; settled: string[] } {+ if (!items.length) return { rows: windowed, settled: [] };+ return windowWith(liveReplyRows(items, transcript, speaker), windowed, transcript);+}++/** A live item as the transcript's layout sees it: everything but its words, which change nothing there except whether+ * the row shows at all and whether it is only a leaked harness message, which a transcript hides. */+interface LiveRowShape extends Drawable {+ turnId?: string;+ at: number;+ shown: boolean;+ /** The words when they are only a leaked harness message, else "". */+ harness: string;+}++const NO_SHAPES: readonly LiveRowShape[] = [];+const sameShape = (a: LiveRowShape, b: LiveRowShape) =>+ a.key === b.key && a.itemId === b.itemId && a.savedAs === b.savedAs && a.turnId === b.turnId && a.at === b.at && a.shown === b.shown && a.harness === b.harness;++function shapeOf(item: LiveReplyItem): LiveRowShape {+ const text = shownText(item);+ return { key: item.key, itemId: item.itemId, savedAs: item.savedAs, turnId: item.turnId, at: item.at, shown: text.trim() !== "", harness: isPureLeakedSystemHarnessMessage(text) ? text : "" };+}++/** The thread's live rows as shapes, the same array for as long as no shape changes: a new word keeps it. */+function liveRowShapes(threadId: string): readonly LiveRowShape[] {+ const items = liveReplies(threadId);+ const cached = shapes.get(threadId);+ if (cached?.items === items) return cached.shapes;+ if (!items.length) {+ shapes.delete(threadId);+ return NO_SHAPES;+ }+ const previous = cached?.shapes ?? NO_SHAPES;+ let changed = items.length !== previous.length;+ const next = items.map((item, at) => {+ const shape = shapeOf(item), before = previous[at];+ if (before && sameShape(before, shape)) return before;+ changed = true;+ return shape;+ });+ shapes.delete(threadId);+ shapes.set(threadId, { items, shapes: changed ? next : previous });+ if (shapes.size > MAX_THREADS) shapes.delete(shapes.keys().next().value!);+ return changed ? next : previous;+}++const standIns = new WeakMap<LiveRowShape, Message>();+function standInFor(shape: LiveRowShape): Message | null {+ if (!shape.shown) return null;+ let row = standIns.get(shape);+ if (!row) standIns.set(shape, (row = { id: `${LIVE_ID}${shape.key}`, role: "bot", kind: "text", text: shape.harness, at: shape.at, ...(shape.turnId ? { turnId: shape.turnId } : {}) } as Message));+ return row;+}++/** `useLiveTranscript` for a list that must not draw again for each word: each live row is a stand-in without its words,+ * which change only when a live row starts, settles or ends; the row's Bubble draws the words with `useLiveRow`. */+export function useLiveTranscriptLayout(threadId: string, windowed: Message[], transcript: readonly Message[]): Message[] {+ const subscribeThread = useCallback((listener: () => void) => subscribe(threadId, listener), [threadId]);+ const shown = useSyncExternalStore(subscribeThread, () => liveRowShapes(threadId), () => NO_SHAPES);+ const live = useMemo(+ () => shown.length ? windowWith(drawnAfter(shown, transcript, standInFor), windowed, transcript) : { rows: windowed, settled: [] },+ [shown, windowed, transcript],+ );+ useEffect(() => settleLiveReplies(threadId, live.settled), [threadId, live.settled]);+ return live.rows;+}+/** The `windowed` rows of `transcript` with the thread's streaming reply after them; in a room, each live row names its* speaker from `members`. */export function useLiveTranscript(threadId: string, windowed: Message[], transcript: readonly Message[], members?: readonly RoomMember[], speakingNow?: string | null): Message[] {@@ -281,4 +380,5 @@ export function resetLiveReplies(): void {streamed.clear();gapped = false;boundarySinceGap.clear();+ shapes.clear();}diff --git a/src/testing/render-counts.ts b/src/testing/render-counts.tsnew file mode 100644index 0000000000..c5250a17b5--- /dev/null+++ b/src/testing/render-counts.ts@@ -0,0 +1,75 @@+// Counts the components each React commit renders, by name and by the transcript row (the nearest `data-mid` above+// them), through the hook React's developer tools attach to. React reads the hook once, when react-dom loads: import+// this module before anything that loads react-dom.+interface Fiber {+ tag: number;+ type: unknown;+ flags: number;+ alternate: Fiber | null;+ child: Fiber | null;+ sibling: Fiber | null;+ memoizedProps: Record<string, unknown> | null;+}++export interface Rendered {+ component: string;+ row: string | null;+}++const FUNCTION = 0, CLASS = 1, HOST = 5, FORWARD_REF = 11, MEMO = 14, SIMPLE_MEMO = 15;+const PERFORMED_WORK = 1;+const COMPONENTS = new Set([FUNCTION, CLASS, FORWARD_REF, MEMO, SIMPLE_MEMO]);++const rendered: Rendered[] = [];++/** The component's own name: the module transform renames a memo's inner function, `Bubble` to `Bubble2`. */+function nameOf(fiber: Fiber): string {+ const type = fiber.type as { displayName?: string; name?: string; render?: { name?: string }; type?: { name?: string } } | null;+ return (type?.displayName || type?.name || type?.render?.name || type?.type?.name || "anonymous").replace(/(?<=\D)\d+$/, "");+}++/** A subtree React skipped keeps the very child it had, and its fibers still carry the flags of the commit that last drew them. */+function walk(first: Fiber, row: string | null): void {+ for (let fiber: Fiber | null = first; fiber; fiber = fiber.sibling) {+ const mounted = fiber.alternate === null;+ const mid = fiber.tag === HOST ? fiber.memoizedProps?.["data-mid"] : undefined;+ const here = typeof mid === "string" ? mid : row;+ if (COMPONENTS.has(fiber.tag) && (mounted || (fiber.flags & PERFORMED_WORK) !== 0)) rendered.push({ component: nameOf(fiber), row: here });+ if (fiber.child && (mounted || fiber.child !== fiber.alternate!.child)) walk(fiber.child, here);+ }+}++const target = globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: unknown };+if (target.__REACT_DEVTOOLS_GLOBAL_HOOK__) throw new Error("render-counts: another developer-tools hook is installed");+const renderers = new Map<number, unknown>();+target.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {+ supportsFiber: true,+ renderers,+ inject(renderer: unknown) {+ renderers.set(renderers.size + 1, renderer);+ return renderers.size;+ },+ onScheduleFiberRoot() {},+ onCommitFiberRoot(_id: number, root: { current: Fiber }) {+ walk(root.current, null);+ },+ onCommitFiberUnmount() {},+ onPostCommitFiberRoot() {},+ setStrictMode() {},+ checkDCE() {},+};++/** Where the count stands now; pass it to `renderedSince`. */+export function renderMark(): number {+ return rendered.length;+}++export function renderedSince(mark: number): readonly Rendered[] {+ return rendered.slice(mark);+}++export function countBy<K extends string | null>(list: readonly Rendered[], key: (entry: Rendered) => K): Map<K, number> {+ const counts = new Map<K, number>();+ for (const entry of list) counts.set(key(entry), (counts.get(key(entry)) ?? 0) + 1);+ return counts;+}