Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Stop re-rendering every message row when a store value changes (#4166)

Milind Soni6bb11b81d347
diff --git a/scripts/bench-desktop.ts b/scripts/bench-desktop.ts
index 3fc1346444..33786f4317 100644
--- a/scripts/bench-desktop.ts
+++ b/scripts/bench-desktop.ts
@@ -348,7 +348,7 @@ async function pageLoad(page: Page, url: string, timeoutMs = 60_000) {
}
async function benchSnapshot(page: Page) {
- return page.evaluate<{ commits: number; commitMs: number; probeMs: number; renderedTotal: number; maxRendered: number; renders: Record<string, number>; selfMs: Record<string, number>; mounts: Record<string, number>; timerFires: Record<string, number>; sse: { frames: number; bytes: number; kinds: Record<string, { n: number; bytes: number }> }; longTasks: Array<[number, number]>; liveIntervals: string[] }>(
+ return page.evaluate<{ commits: number; commitMs: number; probeMs: number; renderedTotal: number; maxRendered: number; renders: Record<string, number>; selfMs: Record<string, number>; mounts: Record<string, number>; why: Record<string, Record<string, number>>; timerFires: Record<string, number>; sse: { frames: number; bytes: number; kinds: Record<string, { n: number; bytes: number }> }; longTasks: Array<[number, number]>; liveIntervals: string[] }>(
"(() => { const b = window.__bench; return { ...b, liveIntervals: [...b.liveIntervals.values()], reset: undefined }; })()");
}
@@ -465,7 +465,7 @@ async function streamTurn(chrome: Chrome, page: Page, fixture: Fixture, botId: s
reactCommits: snapshot.commits, commitsPerSec: round(snapshot.commits / seconds),
renderMsTotal: Math.round(snapshot.commitMs),
componentsRenderedPerCommit: round(snapshot.renderedTotal / Math.max(1, snapshot.commits)), maxComponentsInOneCommit: snapshot.maxRendered,
- topRendered: Object.fromEntries(top.map(([name, count]) => [name, { renders: count, perCommit: round(count / Math.max(1, snapshot.commits), 2), selfMs: Math.round(snapshot.selfMs[name] ?? 0) }])),
+ topRendered: Object.fromEntries(top.map(([name, count]) => [name, { renders: count, perCommit: round(count / Math.max(1, snapshot.commits), 2), selfMs: Math.round(snapshot.selfMs[name] ?? 0), why: snapshot.why[name] }])),
groups: componentGroups(snapshot.renders, snapshot.selfMs),
mounts: Object.values(snapshot.mounts).reduce((sum, n) => sum + n, 0),
animationsMidTurn,
diff --git a/scripts/testing/bench-desktop-page.ts b/scripts/testing/bench-desktop-page.ts
index c8f9fa2b93..fcea6441c6 100644
--- a/scripts/testing/bench-desktop-page.ts
+++ b/scripts/testing/bench-desktop-page.ts
@@ -56,12 +56,13 @@ function probe(options: ProbeOptions): void {
const bench = {
marks: {} as Record<string, number>, commits: 0, commitMs: 0, probeMs: 0, renderedTotal: 0, maxRendered: 0,
renders: {} as Record<string, number>, selfMs: {} as Record<string, number>, mounts: {} as Record<string, number>,
+ why: {} as Record<string, Record<string, number>>,
timerFires: {} as Record<string, number>, liveIntervals: new Map<number, string>(),
sse: { frames: 0, bytes: 0, kinds: {} as Record<string, { n: number; bytes: number }> },
longTasks: [] as Array<[number, number]>,
reset() {
bench.commits = 0; bench.commitMs = 0; bench.probeMs = 0; bench.renderedTotal = 0; bench.maxRendered = 0;
- bench.renders = {}; bench.selfMs = {}; bench.mounts = {}; bench.timerFires = {}; bench.longTasks = [];
+ bench.renders = {}; bench.selfMs = {}; bench.mounts = {}; bench.why = {}; bench.timerFires = {}; bench.longTasks = [];
bench.sse = { frames: 0, bytes: 0, kinds: {} };
},
};
@@ -116,7 +117,7 @@ function probe(options: ProbeOptions): void {
} as typeof EventSource;
}
- interface Fiber { tag: number; type: { displayName?: string; name?: string; render?: { displayName?: string; name?: string } } | null; alternate: Fiber | null; child: Fiber | null; sibling: Fiber | null; flags: number; actualDuration?: number }
+ interface Fiber { tag: number; type: { displayName?: string; name?: string; render?: { displayName?: string; name?: string } } | null; alternate: Fiber | null; child: Fiber | null; sibling: Fiber | null; flags: number; actualDuration?: number; memoizedProps?: Record<string, unknown> | null }
const COMPOSITE = new Set([0, 1, 11, 15]);
const nameOf = (fiber: Fiber) => {
const type = fiber.type;
@@ -143,6 +144,14 @@ function probe(options: ProbeOptions): void {
if (mounted || fiber.flags & 1) {
const counts = mounted ? bench.mounts : bench.renders;
counts[name] = (counts[name] ?? 0) + 1;
+ if (previous) {
+ // Why a component rendered again: the props that changed, a parent's new props object with equal values,
+ // or the same props (its own state, a context or a store it reads).
+ const before = previous.memoizedProps ?? {}, after = fiber.memoizedProps ?? {};
+ const changed = before === after ? ["self"] : Object.keys(after).filter((key) => after[key] !== before[key]).map((key) => `prop:${key}`);
+ const reasons = bench.why[name] ?? (bench.why[name] = {});
+ for (const reason of changed.length ? changed : [before === after ? "self" : "parent"]) reasons[reason] = (reasons[reason] ?? 0) + 1;
+ }
rendered += 1;
if (typeof fiber.actualDuration === "number") {
let self = fiber.actualDuration;
diff --git a/src/components/ChatMarkdown.renderers.test.ts b/src/components/ChatMarkdown.renderers.test.ts
index cb1ae3ea8c..f812fb6779 100644
--- a/src/components/ChatMarkdown.renderers.test.ts
+++ b/src/components/ChatMarkdown.renderers.test.ts
@@ -60,6 +60,9 @@ describe("ChatMarkdown element renderers", () => {
markdownProps(before, "No thread links here: `code`, **bold** and a [site](https://example.test).");
expect(threadListReads()).toBe(0);
+ markdownProps(before, "## A heading\n\nStill # no thread link.");
+ expect(threadListReads()).toBe(0);
+
markdownProps(before, "Tracked in #QA PR 245.");
expect(threadListReads()).toBe(1);
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index 5ce193cb38..f72e7c6f7f 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -712,7 +712,8 @@ const MARKDOWN_COMPONENTS: Components = {
},
};
-const MAY_LINK_THREAD = /#|openmausbot/i;
+// A thread link is "#" directly before a title, or an app link. A heading's "## " never reaches the plugin as text.
+const MAY_LINK_THREAD = /#[^\s#]|openmausbot/i;
const NO_THREAD_REFS: ThreadRefsValue = { threads: [] };
function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS, everyone = false, mentionPerson, delivered }: {
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 744335d365..5016d31c9e 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -1,11 +1,11 @@
-import { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type Dispatch } from "react";
+import { createContext, memo, use, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type Dispatch } from "react";
import { useAdvancedMode } from "@/lib/interface-mode";
import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";
import { ThreadLinkContext } from "@/components/ThreadLinkMenu";
import { useShowThreads } from "@/lib/thread-preferences";
import { AlertTriangle, ChevronLeft, ChevronRight, Copy, Monitor, RefreshCw, Reply, Square, Webhook } from "lucide-react";
import { WorkingDots } from "@/components/WorkingIndicator";
-import { ACTION_ICON, CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction, type MessageMenuItem } from "@/components/MessageActions";
+import { ACTION_ICON, ChatBusyContext, CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction, type MessageMenuItem } from "@/components/MessageActions";
import { copyText } from "@/lib/copy-text";
import { ReactAction, ReactionChips } from "@/components/Reactions";
import { useBotMessageMenu, userMessageMenu } from "@/components/message-menu";
@@ -59,7 +59,7 @@ import { showWorkingDots } from "@/lib/turn-tail";
import { lastNonReceipt } from "@/lib/receipts";
import { useTurnLive } from "@/state/turn-status"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";
import { ChatMarkdown } from "./ChatMarkdown";
-import { liveToolIds } from "@/lib/tool-liveness";
+import { LiveToolsContext, useLiveToolIds } from "@/hooks/use-live-tool-ids";
import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";
import { RawMarkdownView, RawToggleAction } from "./RawMarkdownToggle";
import { ThreadChip } from "./ThreadChip";
@@ -140,7 +140,7 @@ const USER_COLLAPSE_LINES = 8;
interface ChatRows {
botId: string; threadId: string; botName: string; botColor: Bot["color"]; voiceId?: string;
- tts: ConfigStatus["tts"]; localVoice: boolean; busy: boolean; liveTools: ReadonlySet<string>;
+ tts: ConfigStatus["tts"]; localVoice: boolean;
hasMore: boolean; bots: readonly Bot[];
mentionPeers: readonly MentionPeer[]; mentionPerson: { profileName?: string };
/** On a Team Cloud, the viewer's person key: another person's line carries their name. */
@@ -346,7 +346,7 @@ const Bubble = memo(function Bubble({
replyTarget?: Message;
onReply: (message: Message) => void;
}) {
- const { botId, threadId, botName, voiceId, tts, localVoice, busy, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer } = useChatRows();
+ const { botId, threadId, botName, voiceId, tts, localVoice, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer } = useChatRows(), busy = onRegenerate || versions ? use(ChatBusyContext) : false;
const remoteClient = window.ogb?.remoteClient?.active === true;
const peer = peerLine(message) ?? peerRequest(message, botId);
const user = message.role === "user" && !peer;
@@ -446,7 +446,7 @@ const Bubble = memo(function Bubble({
...(simple ? replyAndCopy(() => onReply(message), visibleText) : []),
...userMessageMenu({
messageId: message.id,
- onEdit: !speaker && message.kind === "text" && !webhookView && !hasAttachments && !busy && !message.id.startsWith("optimistic-")
+ onEdit: !speaker && message.kind === "text" && !webhookView && !hasAttachments && !message.id.startsWith("optimistic-")
? () => onStartEdit(message.id) : undefined,
pin: remoteClient ? undefined : { pinned, onToggle: togglePin },
}),
@@ -634,7 +634,7 @@ function PeerLabel({ peer }: { peer: PeerLine }) {
}
const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { message: Message; place?: EffectivePlace }) {
- const { bots, dispatch, liveTools, threadId } = useChatRows();
+ const { bots, dispatch, threadId } = useChatRows(), liveTools = use(LiveToolsContext);
const tool = message.tool;
if (!tool) return null;
if (message.threadRef) return <ThreadChip message={message} />; if (message.relay) return <TeammateChip message={message} />;
@@ -685,7 +685,7 @@ const MessagesList = memo(function MessagesList({
onRegenerate: () => void;
onReply: (message: Message) => void;
}) {
- const { botId, threadId, botName, botColor, bots, busy, hasMore, focus, showToolCalls, locale, simple = false } = useChatRows();
+ const { botId, threadId, botName, botColor, bots, hasMore, focus, showToolCalls, locale, simple = false } = useChatRows(), busy = use(ChatBusyContext);
// 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;
@@ -855,7 +855,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {
const { messages: allMessages, activeLeafId } = bot;
const messages = useMemo(() => visibleMessages({ messages: allMessages, activeLeafId }), [allMessages, activeLeafId]);
const lookups = useMemo(() => transcriptLookups(allMessages, messages), [allMessages, messages]);
- const liveTools = useMemo(() => liveToolIds(messages, bot), [messages, bot.busy, bot.turnStartedAt]);
+ const liveTools = useLiveToolIds(messages, bot);
const recordedRun = useMemo(() => runSteps(messages, liveTools), [messages, liveTools]);
const recordedRunCounts = runSummary(recordedRun);
const engineSupportsAgents = Boolean(
@@ -915,8 +915,8 @@ export function ChatView({ bot: profile }: { bot: Bot }) {
const reactor = useReactor();
const speakerViewer = state.config?.team && reactor !== "user" ? reactor : null;
const rows = useMemo<ChatRows>(
- () => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, busy, liveTools, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: canWrite !== false, openedAt, speakerViewer }),
- [bot.id, bot.threadId, bot.name, bot.color, bot.voice, tts, localVoice, busy, liveTools, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, canWrite, openedAt, speakerViewer],
+ () => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: canWrite !== false, openedAt, speakerViewer }),
+ [bot.id, bot.threadId, bot.name, bot.color, bot.voice, tts, localVoice, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, canWrite, openedAt, speakerViewer],
);
const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && currentTask?.private === true, ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;
@@ -1188,7 +1188,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {
<div ref={topSentinelRef} className="h-2 w-full pointer-events-none" aria-hidden="true" />
) : null}
{windowedMessages.length === 0 && !bot.busy && <EmptyChat bot={bot} />}
- <ChatRowsContext.Provider value={rows}>
+ <ChatRowsContext.Provider value={rows}><LiveToolsContext value={liveTools}><ChatBusyContext value={busy}>
<MessagesList
messages={windowedMessages}
transcript={messages}
@@ -1209,7 +1209,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {
onRegenerate={regenerate}
onReply={selectReply}
/>
- </ChatRowsContext.Provider>
+ </ChatBusyContext></LiveToolsContext></ChatRowsContext.Provider>
{stopNoticeDue(messages, stoppedAt, busy) && <CancelledTurnRow name={PERSON_STOPPED_TURN_NAME} />}
{laterCount > 0 && (
<div className="flex justify-center">
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index 15b4af5283..13036fec3d 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -71,7 +71,7 @@ import { TurnNarrationRun } from "./TurnNarrationRun";
import { ActivityRun } from "./ActivityRun";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
-import { liveToolIds } from "@/lib/tool-liveness";
+import { useLiveToolIds } from "@/hooks/use-live-tool-ids";
import { roomNeedsSetup } from "@/lib/room-setup";
import { useComposerDockPad } from "@/lib/composer-dock";
import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";
@@ -355,7 +355,7 @@ export const Transcript = memo(function Transcript({
const newest = transcript[retryableIndex];
return newest && isCancelledTranscriptRow(newest) ? roomRetryRequest(transcript, retryableIndex) : null;
}, [transcript, retryableIndex]);
- const liveTools = useMemo(() => liveToolIds(transcript, { busy: roomBusy, turnStartedAt: group.turnStartedAt }), [transcript, roomBusy, group.turnStartedAt]);
+ const liveTools = useLiveToolIds(transcript, { busy: roomBusy, turnStartedAt: group.turnStartedAt });
const retryRoom = useCallback(() => {
if (!retryRequest || roomBusy) return;
dispatch({
diff --git a/src/components/MessageActions.idle.dom.test.ts b/src/components/MessageActions.idle.dom.test.ts
new file mode 100644
index 0000000000..93c255e305
--- /dev/null
+++ b/src/components/MessageActions.idle.dom.test.ts
@@ -0,0 +1,36 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ChatBusyContext, MessageActions, type MessageMenuItem } from "./MessageActions";
+
+const items: MessageMenuItem[] = [
+ { key: "edit", icon: null, label: "Edit", onSelect() {}, idleOnly: true },
+ { key: "id", icon: null, label: "Copy id", onSelect() {} },
+];
+
+describe("a chat message's menu while a turn runs", () => {
+ let root: Root, host: HTMLElement;
+ const draw = (busy: boolean) => flushSync(() => root.render(createElement(ChatBusyContext, { value: busy }, createElement(MessageActions, { side: "user", menu: items }))));
+ const offered = () => [...host.querySelectorAll("[role=menuitem]")].map((item) => item.textContent);
+ beforeEach(() => {
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ });
+ afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+ });
+
+ it("leaves out what only works between turns, and offers it again when the turn ends", () => {
+ draw(true);
+ flushSync(() => host.querySelector<HTMLButtonElement>("button[aria-haspopup=menu]")!.click());
+ expect(offered()).toEqual(["Copy id"]);
+ draw(false);
+ expect(offered()).toEqual(["Edit", "Copy id"]);
+ draw(true);
+ expect(offered()).toEqual(["Copy id"]);
+ });
+});
diff --git a/src/components/MessageActions.tsx b/src/components/MessageActions.tsx
index 45cd8e12c0..0ceb20b10c 100644
--- a/src/components/MessageActions.tsx
+++ b/src/components/MessageActions.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
+import { createContext, use, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Check, Copy, Ellipsis, Reply, X } from "lucide-react";
import { popoverClosesOnKey, usePopoverDismiss } from "@/hooks/use-popover-dismiss";
import { cn } from "@/lib/cn";
@@ -18,8 +18,14 @@ export type MessageMenuItem = {
onSelect: () => void;
title?: string;
disabled?: boolean;
+ /** Offered only while the chat's turn is not running. */
+ idleOnly?: boolean;
};
+/** Whether the chat's turn is running, apart from the row values every message reads: a turn starting or ending
+ * re-renders only the few rows that show it, not every message. */
+export const ChatBusyContext = createContext(false);
+
export const MESSAGE_ROW = "data-message-row";
const INTERACTIVE = "a, button, input, textarea, select, summary, label, [role=button], [contenteditable=true]";
@@ -37,7 +43,7 @@ export function MessageActions({
side,
forceOpen = false,
className,
- menu = [],
+ menu: items = [],
children,
}: {
side: "user" | "bot";
@@ -51,10 +57,13 @@ export function MessageActions({
const moreRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const menuId = useId();
+ const [menuOpen, setMenuOpen] = useState(false);
+ // use() may run conditionally: a closed menu has no reason to follow the turn.
+ const busy = menuOpen && items.some((item) => item.idleOnly) ? use(ChatBusyContext) : false;
+ const menu = busy ? items.filter((item) => !item.idleOnly) : items;
const [hovered, setHovered] = useState(false);
const [keyboardFocus, setKeyboardFocus] = useState(false);
const [tapped, setTapped] = useState(false);
- const [menuOpen, setMenuOpen] = useState(false);
const [menuAbove, setMenuAbove] = useState(false);
const [menuFlipped, setMenuFlipped] = useState(false);
const mirrored = side === "user";
diff --git a/src/components/Reactions.tsx b/src/components/Reactions.tsx
index e64ad760f2..847c48079f 100644
--- a/src/components/Reactions.tsx
+++ b/src/components/Reactions.tsx
@@ -7,7 +7,8 @@ import { useCanWriteIn, useReactor } from "@/lib/cloud-guest";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
-import { api, useStore, type Bot, type Message } from "@/state/store";
+import { api, type Bot, type Message } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
const LABEL: Record<Reaction, LocaleKey> = {
"👍": "chat.reaction.yes",
@@ -33,7 +34,7 @@ const newestTap = new Map<string, number>();
let taps = 0;
function useReaction(threadId: string, message: Message) {
- const { dispatch } = useStore();
+ const { dispatch } = useStoreRef();
const me = useReactor();
const latest = useRef(message);
useLayoutEffect(() => { latest.current = message; });
diff --git a/src/components/ThreadRefs.tsx b/src/components/ThreadRefs.tsx
index a01141ef63..426c8624cf 100644
--- a/src/components/ThreadRefs.tsx
+++ b/src/components/ThreadRefs.tsx
@@ -3,6 +3,7 @@ import type { MentionPeer } from "@/lib/mentions";
import { createContext, Fragment, useContext, useMemo, useRef, type ReactNode } from "react";
import { botOpensTo, openBot, openThread, useStore, type Action, type AppState, type Bot, type Group, type ThreadTarget } from "@/state/store";
import { useShowThreads } from "@/lib/thread-preferences";
+import { useStoreRef } from "@/state/store-ref";
import { t } from "@/lib/i18n";
import { parseBotRefUrl, parseThreadRefUrl, resolveThreadRefAddress, splitThreadRefsForDisplay, type ThreadRefCandidate } from "@/lib/thread-refs";
@@ -57,13 +58,13 @@ export interface ThreadLinkTarget extends ThreadTarget {
}
export function ThreadLink({ target, ambiguous, children }: { target: ThreadLinkTarget; ambiguous: boolean; children?: ReactNode }) {
- const { state, dispatch } = useStore();
+ const store = useStoreRef();
const showThreads = useShowThreads();
return (
<button
type="button"
data-thread-link={target.threadId}
- onClick={() => openThread(dispatch, target, state, showThreads)}
+ onClick={() => openThread(store.dispatch, target, store.state(), showThreads)}
title={ambiguous ? t("chat.openThreadOn", { title: target.title, name: target.botName }) : t("chat.openThread", { title: target.title })}
className="inline break-words text-start text-accent underline decoration-accent/40 hover:decoration-accent"
>
diff --git a/src/components/message-menu.tsx b/src/components/message-menu.tsx
index eeb5caccb0..c65facc95b 100644
--- a/src/components/message-menu.tsx
+++ b/src/components/message-menu.tsx
@@ -84,7 +84,7 @@ export function useBotMessageMenu({
export function userMessageMenu({ messageId, onEdit, pin }: { messageId: string; onEdit?: () => void; pin?: PinAction }): MessageMenuItem[] {
return [
- ...(onEdit ? [{ key: "edit", icon: <Pencil {...ACTION_ICON} />, label: t("chat.editMessage"), onSelect: onEdit }] : []),
+ ...(onEdit ? [{ key: "edit", icon: <Pencil {...ACTION_ICON} />, label: t("chat.editMessage"), onSelect: onEdit, idleOnly: true }] : []),
...pinItem(pin),
idItem(messageId),
];
diff --git a/src/hooks/use-live-tool-ids.test.ts b/src/hooks/use-live-tool-ids.test.ts
new file mode 100644
index 0000000000..57207b8914
--- /dev/null
+++ b/src/hooks/use-live-tool-ids.test.ts
@@ -0,0 +1,30 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it } from "vitest";
+import type { ToolRunMessage } from "@/lib/tool-liveness";
+import { useLiveToolIds } from "./use-live-tool-ids";
+
+const tool = (id: string, at: number, done = false): ToolRunMessage => ({ id, at, role: "bot", kind: "activity", turnId: "t1", ...(done ? { turnCompletedAt: at } : {}) });
+const text = (id: string, at: number): ToolRunMessage => ({ id, at, role: "bot", kind: "text", turnId: "t1" });
+
+describe("useLiveToolIds", () => {
+ it("keeps the same set while the same calls run, and a new one when they change", () => {
+ const seen: Array<ReadonlySet<string>> = [];
+ function Probe({ messages, busy }: { messages: ToolRunMessage[]; busy: boolean }) {
+ seen.push(useLiveToolIds(messages, { busy, turnStartedAt: 1 }));
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ const draw = (messages: ToolRunMessage[], busy = true) => flushSync(() => root.render(createElement(Probe, { messages, busy })));
+ draw([tool("a", 2)]);
+ draw([tool("a", 2), text("x", 3)]);
+ expect(seen[1]).toBe(seen[0]);
+ draw([tool("a", 2), text("x", 3), tool("b", 4)]);
+ expect([...seen[2]!]).toEqual(["a", "b"]);
+ draw([tool("a", 2), text("x", 3), tool("b", 4)], false);
+ expect(seen[3]!.size).toBe(0);
+ root.unmount();
+ });
+});
diff --git a/src/hooks/use-live-tool-ids.ts b/src/hooks/use-live-tool-ids.ts
new file mode 100644
index 0000000000..25f6062adf
--- /dev/null
+++ b/src/hooks/use-live-tool-ids.ts
@@ -0,0 +1,20 @@
+import { createContext, useMemo, useRef } from "react";
+import { liveToolIds, type LiveToolRun, type ToolRunMessage } from "@/lib/tool-liveness";
+
+/** The running tool calls, apart from the chat's other row values: only tool rows read them, so a call starting or
+ * finishing re-renders those rows and not every message bubble. */
+export const LiveToolsContext = createContext<ReadonlySet<string>>(new Set());
+
+const sameIds = (a: ReadonlySet<string>, b: ReadonlySet<string>) => a.size === b.size && [...a].every((id) => b.has(id));
+
+/** The tool calls still running in this turn. Every new row of a busy turn recomputes them, but the set keeps its
+ * identity while the same calls run, so the tool rows reading it render again only when a call starts or ends. */
+export function useLiveToolIds(messages: readonly ToolRunMessage[], run: LiveToolRun): ReadonlySet<string> {
+ const previous = useRef<ReadonlySet<string> | null>(null);
+ const { busy, turnStartedAt } = run;
+ return useMemo(() => {
+ const next = liveToolIds(messages, { busy, turnStartedAt });
+ if (previous.current && sameIds(previous.current, next)) return previous.current;
+ return (previous.current = next);
+ }, [messages, busy, turnStartedAt]);
+}
diff --git a/src/lib/format-time.ts b/src/lib/format-time.ts
new file mode 100644
index 0000000000..0b02f8ee65
--- /dev/null
+++ b/src/lib/format-time.ts
@@ -0,0 +1,7 @@
+const TIME_FORMAT = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" });
+
+export function formatTime(at: number) {
+ const date = new Date(at);
+ // toLocaleTimeString's output, where Intl.DateTimeFormat.format would throw
+ return Number.isNaN(date.getTime()) ? "Invalid Date" : TIME_FORMAT.format(date);
+}
diff --git a/src/lib/page-open.ts b/src/lib/page-open.ts
index 23ad41d81c..dfb765d49d 100644
--- a/src/lib/page-open.ts
+++ b/src/lib/page-open.ts
@@ -1,6 +1,7 @@
-import { useCallback, useContext, useEffect, useRef, type MouseEvent } from "react";
+import { useCallback, useEffect, useRef, type MouseEvent } from "react";
import { PAGE_ID } from "../../shared/published-page";
-import { StoreContext, type Bot } from "@/state/store";
+import type { Bot } from "@/state/store";
+import { useOptionalStoreRef } from "@/state/store-ref";
import { openExternalLink } from "./app-links";
import { browserAvailable, builtInBrowserEnabled, type FeatureFlagConfig } from "./feature-flags";
@@ -71,11 +72,11 @@ export function usePanelPage(botId: string, open: (page: PanelPage) => void): vo
* anything else outside the chat. It never sends a message, starts a turn or opens a chat. */
export function usePageOpener(): (url: string) => void {
// Outside the app's store (a message drawn on its own) there is no panel: the page opens outside the chat.
- const store = useContext(StoreContext);
+ const store = useOptionalStoreRef();
const latest = useRef(store);
latest.current = store;
return useCallback((url: string) => {
- const app = latest.current, state = app?.state;
+ const app = latest.current, state = app?.state();
const botId = app && state ? pagePanelBot(url, { selectedId: state.selectedId, bots: state.bots ?? [], groups: state.groups ?? [], config: state.config, desktop: window.ogb }) : null;
if (!app || !botId) { void openExternalLink(url).catch(() => {}); return; }
requestPanelPage(botId, url);
diff --git a/src/state/snapshot-navigation.ts b/src/state/snapshot-navigation.ts
index 2851c8a645..3846c6a033 100644
--- a/src/state/snapshot-navigation.ts
+++ b/src/state/snapshot-navigation.ts
@@ -1,8 +1,14 @@
import type { Bot, Group, Message } from "./store";
+// One branch per transcript array and leaf: every sidebar row, the composer and the chat ask for it on each store
+// change, and an unchanged transcript keeps the same array (so memos keyed on it hold).
+const branches = new WeakMap<readonly Message[], { leafId: string; path: Message[] }>();
+
export function visibleMessages(bot: Pick<Bot, "messages" | "activeLeafId">): Message[] {
const leafId = bot.activeLeafId;
if (!leafId) return bot.messages;
+ const cached = branches.get(bot.messages);
+ if (cached?.leafId === leafId) return cached.path;
const byId = new Map(bot.messages.map((m) => [m.id, m]));
if (!byId.has(leafId)) return bot.messages;
const path: Message[] = [];
@@ -11,7 +17,9 @@ export function visibleMessages(bot: Pick<Bot, "messages" | "activeLeafId">): Me
path.push(cur);
cur = cur.parentId ? byId.get(cur.parentId) : undefined;
}
- return path.reverse();
+ path.reverse();
+ branches.set(bot.messages, { leafId, path });
+ return path;
}
export function navigatedSince(
diff --git a/src/state/store-ref-context.ts b/src/state/store-ref-context.ts
new file mode 100644
index 0000000000..a15c84d1bc
--- /dev/null
+++ b/src/state/store-ref-context.ts
@@ -0,0 +1,11 @@
+import { createContext, type Dispatch } from "react";
+import type { Action, AppState } from "./store";
+
+/** The app store's dispatch and a reader of its newest state: this value never changes. Read it with useStoreRef. */
+export interface StoreRef {
+ dispatch: Dispatch<Action>;
+ /** The newest state, for an event handler; never read while rendering. */
+ state(): AppState;
+}
+
+export const StoreRefContext = createContext<StoreRef | null>(null);
diff --git a/src/state/store-ref.test.ts b/src/state/store-ref.test.ts
new file mode 100644
index 0000000000..745b0d0285
--- /dev/null
+++ b/src/state/store-ref.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment happy-dom
+import { createElement, type ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { BotEditorStore, StoreProvider, useStore } from "./store";
+import { useStoreRef } from "./store-ref";
+import type { StoreRef } from "./store-ref-context";
+
+class FixtureEventSource {
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onmessage: ((event: { data: string }) => void) | null = null;
+ close() {}
+}
+
+let store!: ReturnType<typeof useStore>;
+let ref: StoreRef | null = null;
+let storeRenders = 0, refRenders = 0;
+function StoreReader() { store = useStore(); storeRenders++; return null; }
+function RefReader() { ref = useStoreRef(); refRenders++; return null; }
+let root: Root;
+
+beforeEach(() => {
+ storeRenders = 0;
+ refRenders = 0;
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", async () => new Response(JSON.stringify({ bots: [], groups: [], instances: [] })));
+ root = createRoot(document.createElement("div"));
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+const mount = (children: ReactNode) => flushSync(() => root.render(createElement(StoreProvider, null, createElement(StoreReader), children)));
+
+describe("store ref", () => {
+ it("reads the newest state without rendering again on a change", () => {
+ mount(createElement(RefReader));
+ const rendered = refRenders, first = ref;
+ flushSync(() => store.dispatch({ type: "error", message: "Something broke" }));
+ expect(storeRenders).toBeGreaterThan(1);
+ expect(refRenders).toBe(rendered);
+ expect(ref).toBe(first);
+ expect(ref?.state().error).toBe("Something broke");
+ });
+
+ it("follows a bot editor's own store inside it", () => {
+ mount(null);
+ const scoped = { ...store, state: { ...store.state, error: "scoped" }, dispatch: vi.fn() };
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(StoreReader),
+ createElement(BotEditorStore, { value: scoped, children: createElement(RefReader) }))));
+ expect(ref?.state().error).toBe("scoped");
+ ref?.dispatch({ type: "error", message: null });
+ expect(scoped.dispatch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/state/store-ref.ts b/src/state/store-ref.ts
new file mode 100644
index 0000000000..182c9b25e7
--- /dev/null
+++ b/src/state/store-ref.ts
@@ -0,0 +1,21 @@
+// For a component that only uses the store from an event handler (react to a message, open a link or a page): it does
+// not render again on every state change as a useStore() reader does.
+import { use, useContext } from "react";
+import { StoreContext, useStore as readStore } from "./store";
+import { StoreRefContext, type StoreRef } from "./store-ref-context";
+
+const scopedRef = ({ dispatch, state }: Pick<ReturnType<typeof readStore>, "dispatch" | "state">): StoreRef => ({ dispatch, state: () => state });
+
+/** Inside a scoped store (a bot editor's) this is that store's, followed like useStore(). Throws outside any store.
+ * readStore only reads a context, and a component stays on one side of this branch, so calling it here is safe. */
+export function useStoreRef(): StoreRef {
+ return useContext(StoreRefContext) ?? scopedRef(readStore());
+}
+
+/** The same for what may be drawn outside any store: null there. */
+export function useOptionalStoreRef(): StoreRef | null {
+ const ref = useContext(StoreRefContext);
+ if (ref) return ref;
+ const scoped = use(StoreContext);
+ return scoped && scopedRef(scoped);
+}
diff --git a/src/state/store.test.ts b/src/state/store.test.ts
index 6189cbe53d..cd926410db 100644
--- a/src/state/store.test.ts
+++ b/src/state/store.test.ts
@@ -1334,6 +1334,14 @@ describe("optimistic sent messages", () => {
expect(visibleMessages(restored.bots[0]!).map((message) => message.text)).toEqual(["Ready", "first try", "old answer"]);
expect(restored.bots[0]?.messages).toEqual([root, question, answer]);
});
+
+ it("hands back the same branch for the same transcript and leaf", () => {
+ const shown = conversation().bots[0]!;
+ const branch = visibleMessages(shown);
+ expect(visibleMessages({ messages: shown.messages, activeLeafId: answer.id })).toBe(branch);
+ expect(visibleMessages({ messages: shown.messages, activeLeafId: question.id }).map((message) => message.id)).toEqual([root.id, question.id]);
+ expect(visibleMessages({ messages: [...shown.messages], activeLeafId: answer.id })).not.toBe(branch);
+ });
});
it("uses the same immediate reconciliation for a channel", () => {
diff --git a/src/state/store.tsx b/src/state/store.tsx
index bab86b3e97..a72c430285 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -37,6 +37,7 @@ import { approvalModeFor, type ApprovalMode } from "../../shared/approval-mode";
import { desktopCapabilitiesNow } from "@/lib/desktop";
import { sameModelSelection } from "../../shared/thread-model";
import type { BotBodyId } from "../../shared/bot-body";
+import { StoreRefContext } from "./store-ref-context";
import type { QuestionRequestCardData } from "../../shared/ask-question";
import type { ProfileRequestCardData } from "../../shared/profile-request";
import type { ModelRequestCardData } from "../../shared/model-request";
@@ -3342,7 +3343,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {
() => ({ state, dispatch, flushBotPatches, refreshInstances, refreshModels }),
[state, dispatch, flushBotPatches, refreshInstances, refreshModels],
);
- return <StoreContext.Provider value={value}>{children}</StoreContext.Provider>;
+ const ref = useMemo(() => ({ dispatch, state: () => stateRef.current }), [dispatch]);
+ return <StoreRefContext value={ref}><StoreContext.Provider value={value}>{children}</StoreContext.Provider></StoreRefContext>;
}
export function useStore() {
@@ -3352,13 +3354,7 @@ export function useStore() {
}
export function BotEditorStore({ value, children }: { value: ReturnType<typeof useStore>; children: ReactNode }) {
- return <StoreContext.Provider value={value}>{children}</StoreContext.Provider>;
+ return <StoreRefContext value={null}><StoreContext.Provider value={value}>{children}</StoreContext.Provider></StoreRefContext>;
}
-const TIME_FORMAT = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" });
-
-export function formatTime(at: number) {
- const date = new Date(at);
- // toLocaleTimeString's output, where Intl.DateTimeFormat.format would throw
- return Number.isNaN(date.getTime()) ? "Invalid Date" : TIME_FORMAT.format(date);
-}
+export { formatTime } from "@/lib/format-time";