Skip to content

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

Chat: a bot switch draws its newest rows first and mounts no hover-only part (#6623)

Milind Soni96acdd4bcd14
diff --git a/src/components/ChatView.rows-hold-still.test.ts b/src/components/ChatView.rows-hold-still.test.ts
index af3e1fe2ba..f664155fbc 100644
--- a/src/components/ChatView.rows-hold-still.test.ts
+++ b/src/components/ChatView.rows-hold-still.test.ts
@@ -111,7 +111,7 @@ afterAll(() => {
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"]) {
+ for (const component of ["Bubble", "DigestChip", "TurnNarrationRun", "PublishedSiteCards", "DaySeparator"]) {
expect(mounted.get(component) ?? 0, component).toBeGreaterThan(0);
}
});
diff --git a/src/components/ChatView.switch.test.ts b/src/components/ChatView.switch.test.ts
new file mode 100644
index 0000000000..4855fbb9ca
--- /dev/null
+++ b/src/components/ChatView.switch.test.ts
@@ -0,0 +1,187 @@
+// @vitest-environment happy-dom
+// The real provider, two long chats: switching between them draws the newest rows first and mounts no hover-only part.
+import { commitMark, commitsSince, 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 { MESSAGE_ROW } from "./MessageActions";
+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", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useReactor: () => "user" }));
+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true, 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" },
+ { threadId: `${id}-fork`, title: "Fork", createdAt: 2, approvalMode: "ask", origin: { threadId: `${id}-thread`, messageId: `${id}-answer-22` } }],
+});
+
+const start = Date.UTC(2026, 10, 1, 9);
+/** 120 rows: asks, answers with a link and a list, folded tool steps and work summaries. */
+function transcript(bot: string): Message[] {
+ const rows: Message[] = [];
+ for (let turn = 0; rows.length < 120; turn++) {
+ const at = start + turn * 600_000, turnId = `${bot}-turn-${turn}`;
+ rows.push({ id: `${bot}-ask-${turn}`, role: "user", kind: "text", at, text: `Question ${turn}: what is slow?` });
+ rows.push({ id: `${bot}-step-${turn}a`, role: "bot", kind: "activity", at: at + 2_000, tool: { name: "Bash", ok: true }, turnId });
+ rows.push({ id: `${bot}-step-${turn}b`, role: "bot", kind: "activity", at: at + 3_000, tool: { name: "Read", ok: true }, turnId });
+ rows.push({ id: `${bot}-answer-${turn}`, role: "bot", kind: "text", at: at + 9_000, turnId, turnTerminal: true,
+ text: `## Step ${turn}\n\nThe **merge** re-sorts on every call; see [the notes](https://example.com/${bot}/${turn}).\n\n- first point\n- second point` });
+ rows.push({ id: `${bot}-digest-${turn}`, role: "bot", kind: "digest", at: at + 9_500, text: "", digest: {
+ turnId, botId: bot, threadId: `${bot}-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 === 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(); } };
+const stream = () => FixtureEventSource.opened[0]!;
+const rows = () => document.querySelectorAll('[role="log"] [data-mid]');
+
+/** No layout here: the scroller reads as a 900px view over rows 120px tall each. */
+function layout() {
+ const scroller = (el: Element) => el.classList.contains("glass-scroller");
+ Object.defineProperty(HTMLElement.prototype, "clientHeight", { configurable: true, get() { return scroller(this) ? 900 : 0; } });
+ Object.defineProperty(HTMLElement.prototype, "scrollHeight", { configurable: true, get() { return scroller(this) ? 120 * this.querySelectorAll("[data-mid]").length : 0; } });
+}
+
+/** A click on a bot in the sidebar: what its commit draws, then everything until the chat is quiet again. */
+async function switchTo(id: string) {
+ const mark = renderMark(), commits = commitMark();
+ flushSync(() => dispatch({ type: "select", id }));
+ const first = { mounted: renderedSince(mark).filter((entry) => entry.mounted).length, rows: rows().length, ids: [...rows()].map((row) => row.getAttribute("data-mid")) };
+ await frames();
+ const mounted = renderedSince(mark).filter((entry) => entry.mounted);
+ const again = renderedSince(mark).filter((entry) => !entry.mounted && entry.row !== null);
+ const chat = renderedSince(mark).filter((entry) => entry.component === "ChatView").length;
+ return { first, mounted: mounted.length, again, chat, commits: commitsSince(commits), byName: countBy(mounted, (entry) => entry.component) };
+}
+
+const HOVER_ONLY = ["ReplyAction", "CopyButton", "ReactAction", "SpeakButton", "SmilePlus", "Reply", "Copy", "ReactionChips", "AttachmentGallery"];
+const row = (id: string) => document.querySelector<HTMLElement>(`[data-mid="${id}"] [${MESSAGE_ROW}]`)!;
+const tray = (id: string) => row(id).querySelector<HTMLElement>('[data-testid="message-actions"]')!;
+const more = (id: string) => tray(id).querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!;
+
+beforeAll(async () => {
+ layout();
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?")
+ ? json({ bots: [{ ...announced("a", "Ada"), messages: transcript("a") }, { ...announced("b", "Bea"), messages: transcript("b") }], groups: [] })
+ : 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();
+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });
+ await settle();
+ flushSync(() => dispatch({ type: "select", id: "a" }));
+ await frames();
+ await switchTo("b");
+ await switchTo("a");
+});
+afterAll(() => {
+ flushSync(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+describe("switching between two long chats", () => {
+ it("draws the newest rows in the click's commit and the rest of the window after it", async () => {
+ const { first, mounted, again, chat, commits } = await switchTo("b");
+ expect(first.ids.at(-1)).toBe("b-digest-23");
+ expect(first.rows).toBeGreaterThan(5);
+ expect(first.rows).toBeLessThanOrEqual(14);
+ expect(first.mounted, "components mounted before the first paint").toBeLessThanOrEqual(200);
+ expect(rows().length).toBe(72);
+ expect(rows()[0]!.getAttribute("data-mid")).toBe("b-ask-0");
+ expect(mounted, "components mounted in all").toBeLessThanOrEqual(850);
+ expect(countBy(again, (entry) => entry.component), "a row drawn twice").toEqual(new Map());
+ expect(chat, "the chat drawn for the click and once for the rows above").toBe(2);
+ expect(commits).toBeLessThanOrEqual(5);
+ });
+
+ it("mounts no part that only a hover, focus or right-click shows", async () => {
+ const { byName } = await switchTo("a");
+ for (const name of HOVER_ONLY) expect(byName.get(name) ?? 0, name).toBe(0);
+ expect(byName.get("MessageActions")).toBe(48);
+ expect(byName.get("ForkLinks"), "only the message a conversation was forked from").toBe(1);
+ expect(document.querySelector('[data-mid="a-answer-22"] [data-testid="fork-links"]')?.textContent).toContain("Fork");
+ expect(document.querySelectorAll('[data-testid="message-actions"] button[aria-label="Copy message"]')).toHaveLength(0);
+ });
+
+ it("mounts a message's buttons when the pointer comes over it", async () => {
+ flushSync(() => row("a-answer-23").dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" })));
+ expect(tray("a-answer-23").dataset.shown).toBe("true");
+ expect([...tray("a-answer-23").querySelectorAll("button")].map((button) => button.getAttribute("aria-label")))
+ .toEqual(["Reply to message", "Add reaction", "Copy message", "Message actions"]);
+ expect(tray("a-answer-22").querySelectorAll("button")).toHaveLength(1);
+ });
+
+ it("hands Tab from above to the first button and Shift+Tab from below to the last", async () => {
+ const composer = document.querySelector<HTMLTextAreaElement>("textarea")!;
+ const above = row("a-ask-21").querySelector<HTMLElement>("button, a")!;
+ above.focus();
+ flushSync(() => more("a-answer-21").focus());
+ expect(document.activeElement?.getAttribute("aria-label")).toBe("Reply to message");
+ composer.focus();
+ flushSync(() => more("a-answer-20").focus());
+ expect(document.activeElement).toBe(more("a-answer-20"));
+ expect(tray("a-answer-20").querySelectorAll("button")).toHaveLength(4);
+ });
+
+ it("opens the menu on a right-click before any hover", async () => {
+ const bubble = row("a-answer-19").querySelector("[data-chat-bubble] p")!;
+ flushSync(() => bubble.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 40, clientY: 20 })));
+ expect([...document.querySelectorAll("[role=menuitem]")].map((item) => item.textContent)).toEqual(expect.arrayContaining(["Reply", "Copy message"]));
+ flushSync(() => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));
+ });
+
+ it("draws the whole window at once for a jump to an older message", async () => {
+ flushSync(() => dispatch({ type: "focusMessage", threadId: "b-thread", messageId: "b-answer-3" }));
+ const { first } = await switchTo("b");
+ expect(first.ids).toContain("b-answer-3");
+ });
+});
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 7b9eb62495..eb45252137 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -8,7 +8,7 @@ import { WorkingDots } from "@/components/WorkingIndicator";
import { ChatBusyContext, CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction } from "@/components/MessageActions";
import { ReactAction, ReactionChips } from "@/components/Reactions";
import { replyAndCopy, useBotMessageMenu, userMessageMenu } from "@/components/message-menu";
-import { forkMessageItem, ForkLinks } from "@/components/ForkMessage";
+import { forkMessageItem, ForkLinks, useForkedMessages } from "@/components/ForkMessage";
import { savesToTeamMemory, TEAM_MEMORY_ITEM, TeamMemorySavesContext } from "@/components/conversation-share/conversation-share";
import { useSpeech } from "@/lib/tts/useSpeech";
import { localSystemVoiceActive } from "@/lib/local-voice";
@@ -54,8 +54,8 @@ import { THIS_COMPUTER_NOT_READY } from "../../shared/your-computer";
import { BotAvatar } from "./Avatar";
import { TurnPresence } from "./TurnPresence";
import { showToolCallsEnabled, skillAuthoringEnabled } from "@/lib/feature-flags";
-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 { stateForBot } from "@/lib/mascot";
+import { peerLine, peerPreview, peerRequest } from "@/lib/peer-message"; import { PeerCompactRow, PeerLabel, 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, useLiveRow, useLiveTranscriptLayout } from "@/state/live-reply"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";
@@ -304,8 +304,11 @@ const Bubble = memo(function Bubble({
onRegenerate,
replyTarget,
onReply,
+ forked = false,
}: {
message: Message;
+ /** A conversation was forked from this message. */
+ forked?: boolean;
emerging?: boolean;
eagerAttachments?: boolean;
/** Simple mode: this bubble meets the one above (or below) in its sender's group. */
@@ -400,7 +403,7 @@ const Bubble = memo(function Bubble({
// A long request from another bot is one line until opened.
const peerLong = peer ? peerPreview(text) : null;
- if (peer && peerLong && !expanded && (!focusedSearch || folded)) return <div {...{ [MESSAGE_ROW]: "" }} className="group flex w-full flex-col items-start"><PeerLabel peer={peer} /><PeerCompactRow preview={peerLong} onOpen={() => setExpanded(true)} /></div>;
+ if (peer && peerLong && !expanded && (!focusedSearch || folded)) return <div {...{ [MESSAGE_ROW]: "" }} className="group flex w-full flex-col items-start"><PeerLabel peer={peer} bots={bots} /><PeerCompactRow preview={peerLong} onOpen={() => setExpanded(true)} /></div>;
const forks = user && versions ? versions : [message];
const versionIndex = forks.findIndex((v) => v.id === message.id);
const switchTo = (v: Message | undefined) => {
@@ -420,7 +423,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)}>
- {message.relay ? <RelayLabel message={message} /> : peer && <PeerLabel peer={peer} />}
+ {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")}>
{user && (
@@ -489,7 +492,7 @@ const Bubble = memo(function Bubble({
</div>
) : user ? (
<>
- {attachments && <AttachmentGallery images={attachments.images} files={attachments.files} message={{ threadId, messageId: message.id }} eager={eagerAttachments} className={!visibleText ? "mb-0" : undefined} />}
+ {attachments && attachments.images.length + attachments.files.length > 0 && <AttachmentGallery images={attachments.images} files={attachments.files} message={{ threadId, messageId: message.id }} eager={eagerAttachments} className={!visibleText ? "mb-0" : undefined} />}
{visibleText && (
<div
className={cn("chat-text", collapsible && "max-h-40 overflow-hidden [mask-image:linear-gradient(to_bottom,black_60%,transparent)]")}
@@ -536,7 +539,7 @@ const Bubble = memo(function Bubble({
))}
</div>
)}
- {!group && <AttachmentGallery images={generatedPaths} files={linkedFiles} originals={attached.originals} message={{ threadId, messageId: message.id }} className={text ? undefined : "mb-0"} eager={eagerAttachments} />}
+ {!group && generatedPaths.length + linkedFiles.length > 0 && <AttachmentGallery images={generatedPaths} files={linkedFiles} originals={attached.originals} message={{ threadId, messageId: message.id }} className={text ? undefined : "mb-0"} eager={eagerAttachments} />}
{split ? (
<ConversationalReply simple={simple} join={join} segments={reply.segments} firstNew={reply.firstNew} citation={{ messageId: message.id, botId, threadId }}
renderSegment={(segment) => <ChatMarkdown text={segment} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} originals={group?.originals} />} />
@@ -548,7 +551,7 @@ const Bubble = memo(function Bubble({
) : text ? (
<div data-citation-source={message.id} data-citation-owner-type="bot" data-citation-owner={botId} data-citation-thread={threadId}><ChatMarkdown text={text} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} originals={group?.originals} /></div>
) : null}
- {group && <AttachmentGallery images={group.images} files={group.files} originals={group.originals} message={{ threadId, messageId: message.id }} eager={eagerAttachments} beneath />}
+ {group && group.images.length + group.files.length > 0 && <AttachmentGallery images={group.images} files={group.files} originals={group.originals} message={{ threadId, messageId: message.id }} eager={eagerAttachments} beneath />}
</MessageBoundary>
)}
</div>
@@ -562,9 +565,9 @@ const Bubble = memo(function Bubble({
{formatTime(message.at)}
</span>
</div>
- <ReactionChips threadId={threadId} message={message} bots={bots} align={user ? "end" : "start"} canReact={canReact} />
+ {Boolean(message.reactions?.length) && <ReactionChips threadId={threadId} message={message} bots={bots} align={user ? "end" : "start"} canReact={canReact} />}
{peer && expanded && peerLong && <PeerOpenedActions peer={peer} bots={bots} botId={botId} botName={botName} onFold={() => { setExpanded(false); setFolded(true); }} />}
- <ForkLinks kind="bot" ownerId={botId} threadId={threadId} messageId={message.id} phone={phone} />
+ {forked && <ForkLinks kind="bot" ownerId={botId} threadId={threadId} messageId={message.id} phone={phone} />}
{forks.length > 1 && (
<div className="mt-1 flex items-center gap-0.5 pr-1 text-[12px] text-ink-secondary">
<button
@@ -592,27 +595,6 @@ const Bubble = memo(function Bubble({
);
});
-function PeerLabel({ peer }: { peer: PeerLine }) {
- const { bots } = useChatRows();
- const author =
- bots.find((b) => b.id === peer.botId) ?? bots.find((b) => b.name === peer.name);
- const how = t(PEER_HOW[peer.delivery]);
- return (
- <div className="mb-1 flex items-center gap-1.5 pl-0.5" data-testid="peer-label">
- <BotAvatar
- bot={author ?? { name: peer.name, color: "blue" }}
- state={normalizeState(author?.mascotExpression) ?? "happy"}
- size={20}
- motion="none"
- motionKey={0}
- animated={false}
- />
- <span className={cn("text-[13px] font-semibold", author ? "bot-identity" : "text-ink-secondary")} data-bot-color={author?.color}>{peer.name}</span>
- <span className="text-[12px] text-ink-tertiary">· {how}</span>
- </div>
- );
-}
-
const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { message: Message; place?: EffectivePlace }) {
const { bots, dispatch, threadId } = useChatRows(), liveTools = use(LiveToolsContext);
const tool = message.tool;
@@ -625,7 +607,7 @@ const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { m
const RoomHandoffChip = ({ message, comm, bots, dispatch, threadId }: { message: Message; comm: NonNullable<Message["comm"]>; bots: readonly Bot[]; dispatch: Dispatch<Action>; threadId: string }) => { const store = useStoreRef(); return <HandoffChip message={message} bots={bots} threadId={threadId} title={t("chat.openConversationWith", { name: comm.withName })} onClick={() => openRoomThread(dispatch, comm, store.state().groups)} />; };
const MessagesList = memo(function MessagesList({
- messages: saved,
+ messages: saved, drawFrom,
transcript,
lookups,
place,
@@ -645,6 +627,8 @@ const MessagesList = memo(function MessagesList({
onReply,
}: {
messages: Message[];
+ /** The oldest row this commit draws; the rows above it keep their places for the next. */
+ drawFrom?: string;
transcript: Message[];
lookups: TranscriptLookups;
place: EffectivePlace;
@@ -664,9 +648,10 @@ 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 = useLiveTranscriptLayout(threadId, saved, transcript);
+ const messages = useLiveTranscriptLayout(threadId, saved, transcript), forked = useForkedMessages("bot", botId, threadId);
// 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 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;
let newestUserMessageId: string | undefined;
for (let i = messages.length - 1; i >= 0 && !newestUserMessageId; i--) {
@@ -691,6 +676,7 @@ const MessagesList = memo(function MessagesList({
const first = item.kind === "message" ? item.message : item.messages[0];
const newDay = needsStamp(prev, first, simple);
const divider = dividerAbove(item.kind === "message" ? [item.message] : item.messages);
+ if (i < drawnFrom) return null;
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);
@@ -773,7 +759,7 @@ const MessagesList = memo(function MessagesList({
onSubmitEdit={onSubmitEdit}
onRegenerate={m.id === lastBotTextId && !m.automation && canRetryLast ? onRegenerate : undefined}
replyTarget={lookups.replyTarget(m)}
- onReply={onReply}
+ onReply={onReply} forked={forked.has(m.id)}
/>
);
}
@@ -785,7 +771,7 @@ const MessagesList = memo(function MessagesList({
{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} />}
- {isLiveReply(m) ? <StreamingReplyContext value>{row}</StreamingReplyContext> : row}<PublishedSiteCards message={m} />{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}{m.savedSteps && <SavedStepsChip botId={botId} message={m} />}
+ {isLiveReply(m) ? <StreamingReplyContext value>{row}</StreamingReplyContext> : row}{m.role === "bot" && m.kind === "text" && <PublishedSiteCards message={m} />}{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}{m.savedSteps && <SavedStepsChip botId={botId} message={m} />}
</div>
);
})}
@@ -809,7 +795,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
const phone = useMediaQuery(PHONE_LAYOUT);
const phoneMenu = phone && !remoteClient;
const simpleHead = !advanced && !remoteClient;
- const canWrite = useCanWriteIn(bot.threadId, bot.yourAccess);
+ const canWrite = useCanWriteIn(bot.threadId, bot.yourAccess), mayWrite = canWrite !== false;
const computerStarting = computerStartLine(state.computerStart, bot.name); useScreensWhile(Boolean(computerStarting));
const mascotMotion = state.mascotMotion;
@@ -844,7 +830,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
topSentinelRef,
transcriptKey,
following, showJumpToLatest,
- windowedMessages,
+ windowedMessages, drawFrom,
hiddenCount,
laterCount,
olderPending,
@@ -885,8 +871,8 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
const reactor = useReactor();
const speakerViewer = 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, 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, phone }),
- [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, phone],
+ () => ({ 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: mayWrite, openedAt, speakerViewer, phone }),
+ [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, mayWrite, openedAt, speakerViewer, phone],
);
const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && (currentTask?.private === true || (ownChatStarted(bot.threadId) && !currentTask?.shared)), ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;
@@ -967,9 +953,9 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
}, [lastUserMessage, bot.busy, bot.id, bot.threadId, dispatch]);
const currentLink = profile.tasks?.find((task) => task.threadId === bot.threadId)?.link;
- const threadLink = useMemo(() => canWrite !== false
+ const threadLink = useMemo(() => mayWrite
? { link: currentLink, assign: (link: string | null) => dispatch({ type: "updateTask", botId: bot.id, threadId: bot.threadId, patch: { link } }) }
- : null, [canWrite, currentLink, bot.id, bot.threadId, dispatch]);
+ : null, [mayWrite, currentLink, bot.id, bot.threadId, dispatch]);
const routineRun = useThreadRoutineRun(bot.id, bot.threadId);
// A run inside its own results conversation (a wait finishing in this chat) is no execution thread: no banner.
@@ -1156,7 +1142,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal
{windowedMessages.length === 0 && !bot.busy && <EmptyChat bot={bot} />}
<ChatRowsContext.Provider value={rows}><TeamMemorySavesContext value={savesToTeamMemory(bot, Boolean(team))}><LiveToolsContext value={liveTools}><ChatBusyContext value={busy}><PagePaneContext value={pagePane}>
<MessagesList
- messages={windowedMessages}
+ messages={windowedMessages} drawFrom={drawFrom}
transcript={messages}
lookups={lookups}
place={place}
diff --git a/src/components/ForkMessage.tsx b/src/components/ForkMessage.tsx
index 8b5db532d9..977e50e330 100644
--- a/src/components/ForkMessage.tsx
+++ b/src/components/ForkMessage.tsx
@@ -1,5 +1,5 @@
import { GitFork } from "lucide-react";
-import type { Dispatch } from "react";
+import { useMemo, type Dispatch } from "react";
import { ACTION_ICON, type MessageMenuItem } from "./MessageActions";
import { t } from "@/lib/i18n";
import type { Action, AppState } from "@/state/store";
@@ -19,11 +19,18 @@ export function forkMessageItem(owner: Owner, dispatch: Dispatch<Action>, disabl
const NO_FORKS: never[] = [];
-function forksOf(state: AppState, owner: Owner) {
+/** A null message: forks from any message of the thread. */
+function forksOf(state: AppState, owner: Omit<Owner, "messageId"> & { messageId: string | null }) {
const tasks = owner.kind === "bot"
? state.bots?.find((bot) => bot.id === owner.ownerId)?.tasks
: state.groups?.find((group) => group.id === owner.ownerId)?.tasks;
- return tasks?.filter((task) => task.origin?.threadId === owner.threadId && task.origin.messageId === owner.messageId) ?? NO_FORKS;
+ return tasks?.filter((task) => task.origin?.threadId === owner.threadId && (owner.messageId === null || task.origin.messageId === owner.messageId)) ?? NO_FORKS;
+}
+
+/** The messages of a thread that conversations were forked from: one read for the whole transcript. */
+export function useForkedMessages(kind: Owner["kind"], ownerId: string, threadId: string): ReadonlySet<string> {
+ const ids = useStoreSelector((state) => forksOf(state, { kind, ownerId, threadId, messageId: null }).map((task) => task.origin!.messageId), sameItems);
+ return useMemo(() => new Set(ids), [ids]);
}
export function ForkLinks(owner: Owner & { phone: boolean }) {
diff --git a/src/components/GroupView.message-actions.test.ts b/src/components/GroupView.message-actions.test.ts
index 6b24b3e0cb..3068462af2 100644
--- a/src/components/GroupView.message-actions.test.ts
+++ b/src/components/GroupView.message-actions.test.ts
@@ -2,7 +2,6 @@
import { createElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
-import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Bot, Group, Message } from "@/state/store";
@@ -23,6 +22,7 @@ vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => fixture.canWrite, useReactor: () => "user" }));
const { Transcript } = await import("./GroupView");
+const { MESSAGE_ROW } = await import("./MessageActions");
const { MessageBoundary } = await import("./ChatView");
const lead = { id: "lead", name: "Lead", color: "blue", voice: "verse" } as Bot;
@@ -37,11 +37,17 @@ const text = (id: string, role: "user" | "bot", body: string): Message => ({
...(role === "bot" ? { from: { botId: "lead", name: "Lead", color: "blue" as const } } : {}),
});
+/** The room as drawn with the pointer over each message, which is when a message's own buttons mount. */
const markup = (messages: Message[]) => {
- const group = { ...room, messages };
- return renderToStaticMarkup(createElement(Transcript, {
- group, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
- }));
+ vi.unstubAllGlobals();
+ flushSync(() => root.render(createElement(Transcript, {
+ group: { ...room, messages }, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
+ })));
+ hover();
+ return host.innerHTML;
+};
+const hover = () => {
+ for (const row of host.querySelectorAll(`[${MESSAGE_ROW}]`)) flushSync(() => row.dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" })));
};
function Boom(): ReactNode {
@@ -95,6 +101,7 @@ describe("room message actions", () => {
flushSync(() => root.render(createElement(Transcript, {
group: { ...room, messages }, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
})));
+ hover();
flushSync(() => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!.click());
const items = [...host.querySelectorAll<HTMLButtonElement>("[role=menuitem]")];
expect(items.map((item) => item.textContent)).toEqual(expect.arrayContaining(["Read this aloud", "Show raw markdown", "Pin message", "Copy message ID"]));
@@ -111,6 +118,7 @@ describe("room message actions", () => {
flushSync(() => root.render(createElement(Transcript, {
group: { ...room, messages }, members: [lead], locale: "en", messages, transcript: messages, onReply: () => {},
})));
+ hover();
const bar = host.querySelector('[data-testid="message-actions"]')!;
const button = bar.querySelector<HTMLButtonElement>('button[aria-label="Read this aloud"]');
expect(button?.disabled).toBe(false);
diff --git a/src/components/MessageActions.test.ts b/src/components/MessageActions.test.ts
index 08d1d9d948..660009ad80 100644
--- a/src/components/MessageActions.test.ts
+++ b/src/components/MessageActions.test.ts
@@ -20,15 +20,22 @@ const render = (props: Partial<Omit<Props, "children">> = {}) =>
);
describe("MessageActions", () => {
- it("shows only reply and copy, hidden until the message is hovered or focused", () => {
+ it("keeps reply and copy out until the message is hovered or focused, holding their room", () => {
const html = render({ menu: [pin] });
- expect(html).toContain(">reply<");
- expect(html).toContain(">copy<");
+ expect(html).not.toContain(">reply<");
+ expect(html).not.toContain(">copy<");
+ expect(html.match(/<span aria-hidden="true" class="size-7 shrink-0"><\/span>/g)).toHaveLength(2);
expect(html).toContain("opacity-0");
expect(html).toContain("pointer-events-none");
expect(html).not.toContain('data-shown="true"');
});
+ it("draws reply and copy at once with no more menu to reach them through", () => {
+ const html = render();
+ expect(html).toContain(">reply<");
+ expect(html).toContain(">copy<");
+ });
+
it("moves the rest behind a closed more menu", () => {
const html = render({ menu: [pin] });
expect(html).toContain('aria-label="Message actions"');
@@ -42,8 +49,9 @@ describe("MessageActions", () => {
});
it("stays out while a control must remain reachable", () => {
- const html = render({ forceOpen: true });
+ const html = render({ forceOpen: true, menu: [pin] });
expect(html).toContain('data-shown="true"');
+ expect(html).toContain(">reply<");
expect(html).not.toContain("opacity-0");
});
diff --git a/src/components/MessageActions.tsx b/src/components/MessageActions.tsx
index ed367957e4..9328abb9d2 100644
--- a/src/components/MessageActions.tsx
+++ b/src/components/MessageActions.tsx
@@ -1,4 +1,4 @@
-import { createContext, use, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
+import { Children, createContext, use, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Check, Copy, Ellipsis, Reply, X } from "lucide-react";
import { popoverClosesOnKey, usePopoverDismiss } from "@/hooks/use-popover-dismiss";
import { cn } from "@/lib/cn";
@@ -76,6 +76,13 @@ export function MessageActions({
const mirrored = side === "user";
const streaming = use(StreamingReplyContext);
const shown = !streaming && (forceOpen || menuOpen || hovered || keyboardFocus || tapped);
+ // The buttons mount on the row's first hover, focus, tap or right-click; until then the "more" button is the way in.
+ const [armed, setArmed] = useState(false);
+ if (!armed && (shown || forceOpen)) setArmed(true);
+ const drawn = armed || items.length === 0;
+ const armedRef = useRef(drawn);
+ armedRef.current = drawn;
+ const handOff = useRef(false);
const canPointRef = useRef(false);
canPointRef.current = !streaming && items.length + contextItems.length > 0;
@@ -86,7 +93,15 @@ export function MessageActions({
let press: { x: number; y: number; at: number; timer: ReturnType<typeof setTimeout> } | null = null;
const enter = (event: PointerEvent) => { if (event.pointerType !== "touch") setHovered(true); };
const leave = (event: PointerEvent) => { if (event.pointerType !== "touch") setHovered(false); };
- const focusIn = (event: FocusEvent) => setKeyboardFocus(focusVisible(event.target));
+ const focusIn = (event: FocusEvent) => {
+ if (!armedRef.current) {
+ // Tab from above lands on "more" before the buttons ahead of it exist: focus goes on to the first of them.
+ const from = event.relatedTarget;
+ handOff.current = event.target === moreRef.current && !(from instanceof Node && rootRef.current && rootRef.current.compareDocumentPosition(from) & Node.DOCUMENT_POSITION_FOLLOWING);
+ setArmed(true);
+ }
+ setKeyboardFocus(focusVisible(event.target));
+ };
const focusOut = (event: FocusEvent) => {
if (event.relatedTarget instanceof Node && row.contains(event.relatedTarget)) return;
setKeyboardFocus(false);
@@ -151,6 +166,12 @@ export function MessageActions({
};
}, []);
+ useLayoutEffect(() => {
+ if (!drawn || !handOff.current) return;
+ handOff.current = false;
+ rootRef.current?.querySelector<HTMLElement>("button:not(:disabled)")?.focus();
+ }, [drawn]);
+
usePopoverDismiss(tapped && !menuOpen, rowRef, () => setTapped(false));
usePopoverDismiss(menuOpen, rootRef, () => {
setMenuOpen(false);
@@ -210,7 +231,7 @@ export function MessageActions({
(document.activeElement as HTMLElement | null)?.blur();
}}
>
- {children}
+ {drawn ? children : Children.toArray(children).map((_, index) => <span key={index} aria-hidden="true" className="size-7 shrink-0" />)}
{items.length > 0 && (
<button
ref={moreRef}
@@ -226,7 +247,7 @@ export function MessageActions({
aria-controls={menuOpen ? menuId : undefined}
className={cn(messageActionClass, menuOpen && "bg-ink/10 text-ink")}
>
- <Ellipsis {...ACTION_ICON} aria-hidden="true" />
+ {drawn && <Ellipsis {...ACTION_ICON} aria-hidden="true" />}
</button>
)}
{menuOpen && (
diff --git a/src/components/PeerExchange.tsx b/src/components/PeerExchange.tsx
index eab02ac7c9..c7ac08f0e2 100644
--- a/src/components/PeerExchange.tsx
+++ b/src/components/PeerExchange.tsx
@@ -127,3 +127,22 @@ export function PeerExchangeView({ lines, peerName, peerBot, botName, self, onCl
</div>
);
}
+
+export function PeerLabel({ peer, bots }: { peer: PeerLine; bots: readonly Bot[] }) {
+ const author = authorOf(bots, peer);
+ const how = t(PEER_HOW[peer.delivery]);
+ return (
+ <div className="mb-1 flex items-center gap-1.5 pl-0.5" data-testid="peer-label">
+ <BotAvatar
+ bot={author ?? { name: peer.name, color: "blue" }}
+ state={normalizeState(author?.mascotExpression) ?? "happy"}
+ size={20}
+ motion="none"
+ motionKey={0}
+ animated={false}
+ />
+ <span className={cn("text-[13px] font-semibold", author ? "bot-identity" : "text-ink-secondary")} data-bot-color={author?.color}>{peer.name}</span>
+ <span className="text-[12px] text-ink-tertiary">· {how}</span>
+ </div>
+ );
+}
diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.ts
index 7846cd400d..50bc85c7ca 100644
--- a/src/hooks/use-transcript-viewport.test.ts
+++ b/src/hooks/use-transcript-viewport.test.ts
@@ -182,7 +182,9 @@ beforeEach(() => {
addEventListener: (_: string, listener: (event: Partial<KeyboardEvent>) => void) => keyListeners.add(listener),
removeEventListener: (_: string, listener: (event: Partial<KeyboardEvent>) => void) => keyListeners.delete(listener),
});
- vi.stubGlobal("requestAnimationFrame", (frame: FrameRequestCallback) => frames.push(frame));
+ const requested: FrameRequestCallback[] = [];
+ vi.stubGlobal("requestAnimationFrame", (frame: FrameRequestCallback) => { frames.push(frame); return requested.push(frame); });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { frames = frames.filter((frame) => frame !== requested[id - 1]); });
vi.stubGlobal("ResizeObserver", class {
constructor(callback: () => void) {
observers++;
diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.ts
index 2eea5b375d..8ef8c91671 100644
--- a/src/hooks/use-transcript-viewport.ts
+++ b/src/hooks/use-transcript-viewport.ts
@@ -1,4 +1,5 @@
import {
+ startTransition,
useCallback,
useEffect,
useLayoutEffect,
@@ -16,6 +17,7 @@ import {
TRANSCRIPT_WINDOW_MAX,
TRANSCRIPT_WINDOW_SIZE,
capWindowEnd,
+ firstFrameRow,
focusWindowRange,
followWindowStart,
resolveTranscriptWindow,
@@ -162,6 +164,50 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const range = resolveTranscriptWindow(messages, transcriptWindow.start, TRANSCRIPT_WINDOW_SIZE, transcriptWindow.end);
return { ...range, visible: withRestingCard(messages, range.visible, range.startIndex, rests) };
}, [messages, transcriptWindow.start, transcriptWindow.end, rests]);
+ // A switch that opens at the end draws the newest rows first; the rows above them follow after that frame is painted.
+ const [firstFrame, setFirstFrame] = useState<{ key: string; from: string } | null>(null);
+ if (switched) {
+ const jumping = Boolean(focusMessage && !focusMessage.consumed && focusMessage.threadId === threadId);
+ const from = current.restore || jumping ? undefined : firstFrameRow(resolveTranscriptWindow(messages, next.start, TRANSCRIPT_WINDOW_SIZE, next.end).visible);
+ if (firstFrame?.key !== transcriptKey || firstFrame.from !== from) setFirstFrame(from ? { key: transcriptKey, from } : null);
+ }
+ const drawFrom = firstFrame?.key === transcriptKey ? firstFrame.from : undefined;
+ const drawFromRef = useRef(drawFrom);
+ drawFromRef.current = drawFrom;
+ const filling = useRef<{ key: string; height: number } | null>(null);
+ const fillNow = useCallback(() => {
+ filling.current = { key: followNow.current.key, height: scrollRef.current?.scrollHeight ?? 0 };
+ setFirstFrame(null);
+ }, []);
+ useLayoutEffect(() => {
+ const el = scrollRef.current, filled = filling.current;
+ if (!el) return;
+ if (drawFrom) {
+ // Newest rows that do not fill the view would show an empty top for a frame: the rest comes before this paint.
+ if (el.scrollHeight <= el.clientHeight) fillNow();
+ return;
+ }
+ filling.current = null;
+ if (filled?.key !== transcriptKey) return;
+ el.scrollTop = followRef.current ? el.scrollHeight : el.scrollTop + el.scrollHeight - filled.height;
+ lastTop.current = el.scrollTop;
+ }, [drawFrom, fillNow, transcriptKey]);
+ useEffect(() => {
+ if (!drawFrom) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const fill = () => {
+ clearTimeout(timer);
+ cancelAnimationFrame(frame);
+ timer = setTimeout(() => startTransition(fillNow), 0);
+ };
+ // A frame callback runs just before the paint; the task it queues runs after it. A hidden window gets no frames.
+ const frame = requestAnimationFrame(fill);
+ timer = setTimeout(fill, 100);
+ return () => {
+ cancelAnimationFrame(frame);
+ clearTimeout(timer);
+ };
+ }, [drawFrom, fillNow]);
const windowRef = useRef(transcriptWindow);
windowRef.current = transcriptWindow;
restingCardId.current = windowedMessages[0] && windowedMessages[0] !== messages[startIndex] ? windowedMessages[0].id : undefined;
@@ -257,6 +303,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const range = focusWindowRange(messages.length, targetIndex);
followEvent({ type: "navigated" });
followEvent({ type: "leftEnd" });
+ if (drawFromRef.current) setFirstFrame(null);
setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, start: range.start, end: range.end });
}, [threadId, messages, followEvent, focusMessage, transcriptKey]);
useFocusMessage(threadId, messages.length > 0, scrollRef);
@@ -326,7 +373,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
});
const triggerAutoEarlier = useCallback(() => {
- if (expandingRef.current) return;
+ if (expandingRef.current || drawFromRef.current) return;
if (hiddenCount > 0) {
expandingRef.current = true;
setBottomFollow(false);
@@ -338,7 +385,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}
}, [hiddenCount, startIndex, laterCount, endIndex, messages.length, hasMore, olderPending, threadId, dispatch, transcriptKey]);
const triggerAutoLater = () => {
- if (expandingRef.current || laterCount === 0) return;
+ if (expandingRef.current || drawFromRef.current || laterCount === 0) return;
expandingRef.current = true;
stepWindow(windowLater);
};
@@ -458,6 +505,8 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
/** The reader left the end a moment ago and has not come back: offer the way down. */
showJumpToLatest: wantsJump && jumpShown,
windowedMessages,
+ /** While a switch draws its first frame: the oldest row drawn. */
+ drawFrom,
hiddenCount,
laterCount,
olderPending,
diff --git a/src/lib/cloud-guest.ts b/src/lib/cloud-guest.ts
index 2a7bf39807..8055674252 100644
--- a/src/lib/cloud-guest.ts
+++ b/src/lib/cloud-guest.ts
@@ -13,19 +13,25 @@ export function canWriteIn(state: SessionState | null, threadId: string): boolea
return state.openedThreads?.includes(threadId) === true;
}
-/** False too for a team bot this person can only view. */
+const writable = new Map<string, boolean>();
+const writableListeners = new Set<() => void>();
+function subscribeWritable(listener: () => void): () => void {
+ writableListeners.add(listener);
+ return () => writableListeners.delete(listener);
+}
+
+/** False too for a team bot this person can only view. Null until known; a conversation opened before shows what was
+ * learned then while it is read again. */
export function useCanWriteIn(threadId: string, level?: string): boolean | null {
- const [allowed, setAllowed] = useState<boolean | null>(null);
+ const allowed = useSyncExternalStore(subscribeWritable, () => writable.get(threadId) ?? null, () => null);
useEffect(() => {
- let alive = true;
- setAllowed(null);
void read().then(async (state) => {
const known = canWriteIn(state, threadId) ? state : await read(true);
- if (alive) setAllowed(canWriteIn(known, threadId));
+ const value = canWriteIn(known, threadId);
+ if (writable.get(threadId) === value) return;
+ writable.set(threadId, value);
+ for (const listener of writableListeners) listener();
});
- return () => {
- alive = false;
- };
}, [threadId]);
return level === "view" ? false : allowed;
}
diff --git a/src/lib/drafts.ts b/src/lib/drafts.ts
index 8210469b29..0da105fbe1 100644
--- a/src/lib/drafts.ts
+++ b/src/lib/drafts.ts
@@ -218,7 +218,8 @@ export function useReplyDraft<T extends { id: string }>(
useEffect(() => {
setReplyState((current) => {
if (current.threadId === threadId && current.message) return current;
- return { threadId, message: resolveReplyMessage(threadId, messages) };
+ const message = resolveReplyMessage(threadId, messages);
+ return message || current.message ? { threadId, message } : current;
});
}, [messages, threadId]);
diff --git a/src/lib/transcript-window.ts b/src/lib/transcript-window.ts
index 304927ba8f..c4d98a4672 100644
--- a/src/lib/transcript-window.ts
+++ b/src/lib/transcript-window.ts
@@ -19,6 +19,14 @@ export function tailWindowStart(total: number, size: number = TRANSCRIPT_WINDOW_
return Math.max(0, total - size);
}
+/** The newest rows a switch draws in its first frame; the rest of the window follows once that frame is on screen. */
+export const FIRST_FRAME_ROWS = 20;
+
+/** The first row a switch draws, when the window holds more than the first frame does. */
+export function firstFrameRow<T extends { id: string }>(visible: readonly T[]): string | undefined {
+ return visible.length > FIRST_FRAME_ROWS ? visible[visible.length - FIRST_FRAME_ROWS]!.id : undefined;
+}
+
export function followWindowStart(messages: readonly { role?: string }[], start: number): number {
const tail = tailWindowStart(messages.length);
const oldest = Math.max(start, tail - TRANSCRIPT_WINDOW_SIZE);
diff --git a/src/testing/render-counts.ts b/src/testing/render-counts.ts
index c5250a17b5..08fa3a09bc 100644
--- a/src/testing/render-counts.ts
+++ b/src/testing/render-counts.ts
@@ -14,6 +14,10 @@ interface Fiber {
export interface Rendered {
component: string;
row: string | null;
+ /** Drawn for the first time: a component React created in this commit. */
+ mounted: boolean;
+ /** Which commit drew it, counted from the first. */
+ commit: number;
}
const FUNCTION = 0, CLASS = 1, HOST = 5, FORWARD_REF = 11, MEMO = 14, SIMPLE_MEMO = 15;
@@ -21,6 +25,7 @@ const PERFORMED_WORK = 1;
const COMPONENTS = new Set([FUNCTION, CLASS, FORWARD_REF, MEMO, SIMPLE_MEMO]);
const rendered: Rendered[] = [];
+let commits = 0;
/** The component's own name: the module transform renames a memo's inner function, `Bubble` to `Bubble2`. */
function nameOf(fiber: Fiber): string {
@@ -34,7 +39,7 @@ function walk(first: Fiber, row: string | null): void {
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 (COMPONENTS.has(fiber.tag) && (mounted || (fiber.flags & PERFORMED_WORK) !== 0)) rendered.push({ component: nameOf(fiber), row: here, mounted, commit: commits });
if (fiber.child && (mounted || fiber.child !== fiber.alternate!.child)) walk(fiber.child, here);
}
}
@@ -51,6 +56,7 @@ target.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
},
onScheduleFiberRoot() {},
onCommitFiberRoot(_id: number, root: { current: Fiber }) {
+ commits++;
walk(root.current, null);
},
onCommitFiberUnmount() {},
@@ -68,6 +74,15 @@ export function renderedSince(mark: number): readonly Rendered[] {
return rendered.slice(mark);
}
+/** Where the commit count stands now; pass it to `commitsSince`. */
+export function commitMark(): number {
+ return commits;
+}
+
+export function commitsSince(mark: number): number {
+ return commits - 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);