Skip to content

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

Rooms: saved rows hold still while members stream (#6675)

Milind Soni51d24a81fae3
diff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsx
index 33fce70ff7..d4849c5937 100644
--- a/src/components/Avatar.tsx
+++ b/src/components/Avatar.tsx
@@ -66,13 +66,16 @@ const gradientFor = (color: MausColor): [string, string, string] => {
return [mix(fill, "#ffffff", 0.55), fill, mix(fill, "#000000", 0.42)];
};
+const roomGradients = new Map<MausColor, [string, string, string]>();
+
+/** One array per colour, so a memoised mascot drawn with it does not draw again. */
export function roomAvatarGradient(color: MausColor): [string, string, string] {
- const fill = `var(--identity-${color})`;
- return [
- `color-mix(in srgb, ${fill} 82%, #ffffff)`,
- fill,
- `color-mix(in srgb, ${fill} 82%, #000000)`,
- ];
+ let gradient = roomGradients.get(color);
+ if (!gradient) {
+ const fill = `var(--identity-${color})`;
+ roomGradients.set(color, (gradient = [`color-mix(in srgb, ${fill} 82%, #ffffff)`, fill, `color-mix(in srgb, ${fill} 82%, #000000)`]));
+ }
+ return gradient;
}
export type MausAvatarHandle = CursorAvatarHandle;
diff --git a/src/components/CursorAvatar.clock.test.ts b/src/components/CursorAvatar.clock.test.ts
index 5affddd533..a8571c1257 100644
--- a/src/components/CursorAvatar.clock.test.ts
+++ b/src/components/CursorAvatar.clock.test.ts
@@ -107,6 +107,21 @@ describe("CursorAvatar on the shared clock", () => {
expect(mascotClock().pending()).toBe(0);
});
+ it("keeps its body when drawn again with a new look", () => {
+ render([{ state: "idle", animated: false, size: 20, gradient: ["#111111", "#222222", "#333333"] }]);
+ run(100);
+ const watcher = new MutationObserver(() => {});
+ watcher.observe(host, { childList: true, subtree: true });
+ for (let turn = 1; turn <= 5; turn++) {
+ render([{ state: "idle", animated: false, size: 20, turn, gradient: ["#111111", "#222222", "#333333"] }]);
+ run(100);
+ }
+ const replaced = watcher.takeRecords();
+ watcher.disconnect();
+ expect(host.querySelector("clipPath")!.childElementCount).toBeGreaterThan(0);
+ expect(replaced).toEqual([]);
+ });
+
it("lets a small idle mascot settle to no frames, and wakes it for a blink", () => {
const ref = createRef<MausAvatarHandle>();
render([{ state: "idle", size: 24, ref }]);
diff --git a/src/components/CursorAvatar.tsx b/src/components/CursorAvatar.tsx
index 9c829b3bcf..acf76e6fcc 100644
--- a/src/components/CursorAvatar.tsx
+++ b/src/components/CursorAvatar.tsx
@@ -1239,7 +1239,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro
const dimension = typeof size === 'number' ? `${size}px` : size
const label = title === undefined ? mascotLabel(silhouette.name) : title
- const body = silhouette.body.replace(/\{\{GRADIENT\}\}/g, `url(#${uid}-grad)`)
+ const body = useMemo(() => ({ __html: silhouette.body.replace(/\{\{GRADIENT\}\}/g, `url(#${uid}-grad)`) }), [silhouette.body, uid]), clip = useMemo(() => ({ __html: silhouette.clip }), [silhouette.clip])
const cutFace = !eyeColor && !picture
const ink = cutFace ? 'black' : eyeColor
const face = (
@@ -1273,7 +1273,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro
<clipPath
id={`${uid}-clip`}
transform={silhouette.fit || undefined}
- dangerouslySetInnerHTML={{ __html: silhouette.clip }}
+ dangerouslySetInnerHTML={clip}
/>
{cutFace && <mask id={`${uid}-face`} maskUnits="userSpaceOnUse" x={-VIEW_SPAN} y={-VIEW_SPAN} width={VIEW_SPAN * 3} height={VIEW_SPAN * 3}>
<rect x={-VIEW_SPAN} y={-VIEW_SPAN} width={VIEW_SPAN * 3} height={VIEW_SPAN * 3} fill="white" />{face}</mask>}
@@ -1283,7 +1283,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro
<g ref={bodyGroup}>
<g ref={bodyContent}>
{picture ? <image href={picture} x="-15" y="-15" width={VIEW_SPAN} height={VIEW_SPAN} preserveAspectRatio="none" /> : <g mask={cutFace ? `url(#${uid}-face)` : undefined}>
- <g transform={silhouette.fit || undefined} dangerouslySetInnerHTML={{ __html: body }} />
+ <g transform={silhouette.fit || undefined} dangerouslySetInnerHTML={body} />
</g>}
{!cutFace && face}
</g>
diff --git a/src/components/GroupView.render-count.test.ts b/src/components/GroupView.render-count.test.ts
index fa56f6adf2..0cd6322128 100644
--- a/src/components/GroupView.render-count.test.ts
+++ b/src/components/GroupView.render-count.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment happy-dom
// The real provider and live stream with a room of 120 messages on screen: a streamed delta draws only the bubble it
// grows, and a store change the bubbles do not show draws none.
+import { renderMark, renderedSince } from "@/testing/render-counts";
import { createElement } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
@@ -112,15 +113,53 @@ describe("a room on screen", () => {
expect(renders.bubbles).toBeGreaterThanOrEqual(120);
});
+ it("touches no saved row while members take turns streaming, changing status and handing over", async () => {
+ // The window moves down as rows arrive, and its new first row takes the day's stamp.
+ const savedRows = [...document.querySelectorAll("[data-mid]")].slice(8);
+ let touched = 0;
+ const count = (records: MutationRecord[]) => {
+ for (const record of records) if (savedRows.some((row) => row.contains(record.target))) touched += record.addedNodes.length + record.removedNodes.length;
+ };
+ const watcher = new MutationObserver(count);
+ watcher.observe(document.querySelector('[role="log"]')!, { childList: true, subtree: true });
+ const runtime = (event: object) => send({ kind: "runtime", event: { provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), ...event } });
+ let listOnWords = 0;
+ const savedIds = new Set(savedRows.map((row) => row.getAttribute("data-mid"))), turns = renderMark();
+ for (const [botId, name, other] of [["a", "Ada", "Bea"], ["b", "Bea", "Ada"]] as const) {
+ const turnId = `turn-${botId}`, itemId = `item-${botId}`;
+ await runtime({ eventId: `start-${botId}`, turnId, type: "turn.started", botId });
+ for (let i = 0; i < 6; i++) {
+ const mark = renderMark();
+ await runtime({ eventId: `${botId}${i}`, turnId, itemId, type: "content.delta", streamKind: "assistant_text", delta: `${name} asks @${other} word${i} `, botId });
+ if (i > 0) listOnWords += renderedSince(mark).filter((entry) => entry.component === "Transcript").length;
+ await send({ kind: "bot", bot: { ...announced(botId, name), busy: true, activity: i % 2 ? "working" : "thinking" } });
+ }
+ expect(document.querySelector(`[data-mid="live:${itemId}"]`)?.textContent, "the streaming row names whom it asks").toContain(other);
+ await runtime({ eventId: `done-${botId}`, turnId, itemId, type: "item.completed", itemType: "assistant_text", text: `${name} is done`, botId });
+ await send({ kind: "message", threadId: "room-thread", message: { id: `said-${botId}`, itemId, turnId, at: at + 200 + ++cursor, role: "bot", kind: "text", text: `${name} is done`, from: { botId, name, color: "green" } } });
+ await runtime({ eventId: `end-${botId}`, turnId, type: "turn.completed", botId });
+ await send({ kind: "bot", bot: { ...announced(botId, name), busy: false } });
+ expect(document.querySelector(`[data-mid="said-${botId}"]`)?.textContent).toContain(`${name} is done`);
+ }
+ count(watcher.takeRecords());
+ watcher.disconnect();
+ expect(document.querySelectorAll('[data-mid^="live:"]')).toHaveLength(0);
+ expect(listOnWords, "the room's list drawn for a word").toBe(0);
+ expect(renderedSince(turns).filter((entry) => savedIds.has(entry.row) && /Avatar|ClusterLabel/.test(entry.component)), "saved rows' speakers").toEqual([]);
+ expect(touched, "nodes replaced inside saved rows").toBe(0);
+ });
+
it("draws only the streaming bubble for each delta", async () => {
flushSync(() => noteLiveReplyEvent({ eventId: "ts", provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), turnId: "t1", type: "turn.started" } as RuntimeEvent));
delta("Starting ");
await settle();
expect(document.querySelector('[data-mid^="live:"]')?.textContent).toContain("Starting");
- const before = renders.bubbles;
+ const before = renders.bubbles, mark = renderMark();
for (let i = 0; i < 20; i++) delta(`word${i} `);
await settle();
expect(renders.bubbles - before).toBe(20);
+ expect(renderedSince(mark).filter((entry) => entry.component === "Transcript"), "the room's list").toEqual([]);
+ expect(renderedSince(mark).filter((entry) => entry.row !== null && !entry.row.startsWith("live:")), "saved rows").toEqual([]);
expect(document.querySelector('[data-mid^="live:"]')?.textContent).toContain("word19");
});
@@ -164,14 +203,15 @@ describe("a room on screen", () => {
expect(renders.chips).toBe(chips);
});
- it("draws every bubble and tool chip again in a new language", async () => {
- const before = renders.bubbles, chips = renders.chips;
+ it("draws every bubble, tool chip and speaker line again in a new language", async () => {
+ const before = renders.bubbles, chips = renders.chips, mark = renderMark();
setLocale("de");
try {
flushSync(() => dispatch({ type: "connected", value: false }));
await settle();
expect(renders.bubbles - before).toBeGreaterThanOrEqual(120);
expect(renders.chips).toBeGreaterThan(chips);
+ expect(renderedSince(mark).filter((entry) => entry.component === "ClusterLabel").length, "speaker lines").toBeGreaterThan(20);
} finally {
setLocale("en");
flushSync(() => dispatch({ type: "connected", value: true }));
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index a2aee39b88..94ad978896 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -65,7 +65,7 @@ import { roomNeedsSetup, setupResponderMode, type RoomResponderMode } from "@/li
import { useComposerDockPad } from "@/lib/composer-dock";
import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";
import { awaitedMemberId, showWorkingDots } from "@/lib/turn-tail";
-import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, useLiveTranscript } from "@/state/live-reply";
+import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, roomLiveSpeaker, StreamingReplyContext, useLiveRow, useLiveTranscriptLayout } from "@/state/live-reply";
import { useTranscriptViewport } from "@/hooks/use-transcript-viewport"; import { staysInView } from "../../shared/person-wait";
import { useUnreadDivider } from "@/hooks/use-unread-divider";
import { unreadMessageIds } from "@/lib/unread-divider";
@@ -114,6 +114,12 @@ export const RoomToolChip = memo(function RoomToolChip({ message, roomId, thread
);
});
+/** A text message's speaker; one still streaming names whom it @-mentions as its words arrive. */
+function TextSpeakerLabel({ threadId, message, bot, members, transcript, teammates, locale }: { threadId: string; message: Message; bot?: Bot; members: Bot[]; transcript: Message[]; teammates: Parameters<typeof roomAddressees>[3]; locale: string }) {
+ const m = useLiveRow(threadId, message);
+ return m.from ? <ClusterLabel bot={bot} name={m.from.name} color={m.from.color} to={roomAddressees(m, members, transcript, teammates)} locale={locale} /> : null;
+}
+
export const Transcript = memo(function Transcript({
group,
members,
@@ -140,7 +146,8 @@ export const Transcript = memo(function Transcript({
const showThreads = useShowThreads();
const showToolCalls = showToolCallsEnabled(config);
const canReact = useCanReact(group.threadId); const teammatePeers = useTeammates().peers;
- const memberOf = (id?: string) => members.find((b) => b.id === id); const messages = useLiveTranscript(group.threadId, saved, transcript, members, roomThreadSpeakerId(group, group.threadId));
+ const memberOf = (id?: string) => members.find((b) => b.id === id), speakingNow = roomThreadSpeakerId(group, group.threadId);
+ const messages = useLiveTranscriptLayout(group.threadId, saved, transcript, useMemo(() => roomLiveSpeaker(members, speakingNow), [members, speakingNow]));
const folds = useMemo(() => roomTurnFolds(messages), [messages, locale]);
const items = useMemo(() => groupActivityRuns(messages.filter(message =>
!folds.hiddenIds.has(message.id) &&
@@ -208,7 +215,7 @@ export const Transcript = memo(function Transcript({
)}
{divider}
{first.from && cluster && (
- <ClusterLabel bot={memberOf(first.from.botId)} name={first.from.name} color={first.from.color} />
+ <ClusterLabel bot={memberOf(first.from.botId)} name={first.from.name} color={first.from.color} locale={locale} />
)}
<ActivityRun messages={item.messages} forceOpen={item.messages.some((step) => step.id === focusedId)}>
{item.messages.map((step) => (
@@ -279,7 +286,7 @@ export const Transcript = memo(function Transcript({
<CompactionChip message={m} />
) : m.kind === "digest" ? (
showToolCalls ? <DigestChip message={m} /> : null
- ) : (m.kind === "app" || m.kind === "widget") && m.from ? <RoomRichRow message={m} from={m.from} threadId={group.threadId} /> : m.template ? <TemplateChatCard message={m} /> : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length) ? (
+ ) : (m.kind === "app" || m.kind === "widget") && m.from ? <RoomRichRow message={m} from={m.from} threadId={group.threadId} /> : m.template ? <TemplateChatCard message={m} /> : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length || isLiveReply(m)) ? (
!user && isPureLeakedSystemHarnessMessage(m.text) && !m.attachments?.length ? null : (
textRow(m, m.id === emergingId, m.id === newestMessageId || m.id === newestUserMessageId)
)
@@ -294,11 +301,10 @@ export const Transcript = memo(function Transcript({
</div>
)}
{divider}
- {m.from && (
- (m.kind === "text" && botTextShowsSpeaker(items, i))
- || (!user && m.kind !== "text" && newCluster && !(m.kind === "activity" && m.comm) && !laterTextOwns(items, i, m.from.botId, m.at))
- ) && (
- <ClusterLabel bot={memberOf(m.from.botId)} name={m.from.name} color={m.from.color} to={m.kind === "text" ? roomAddressees(m, members, transcript, teammatePeers) : undefined} />
+ {m.from && m.kind === "text" && botTextShowsSpeaker(items, i) ? (
+ <TextSpeakerLabel threadId={group.threadId} message={m} bot={memberOf(m.from.botId)} members={members} transcript={transcript} teammates={teammatePeers} locale={locale} />
+ ) : m.from && !user && m.kind !== "text" && newCluster && !(m.kind === "activity" && m.comm) && !laterTextOwns(items, i, m.from.botId, m.at) && (
+ <ClusterLabel bot={memberOf(m.from.botId)} name={m.from.name} color={m.from.color} locale={locale} />
)}
{fold && (
<TurnNarrationRun
diff --git a/src/components/RoomClusterLabel.tsx b/src/components/RoomClusterLabel.tsx
index 42654582bd..6848eacff2 100644
--- a/src/components/RoomClusterLabel.tsx
+++ b/src/components/RoomClusterLabel.tsx
@@ -1,7 +1,8 @@
-import { Fragment } from "react";
+import { Fragment, memo } from "react";
import { BotAvatar } from "./Avatar";
import { cn } from "@/lib/cn";
+import { sameDrawnBots } from "@/lib/drawn-bots";
import { MAUS_COLOR_NAMES, normalizeState, type MausColor } from "@/lib/mascot";
import type { RoomAddressee } from "@/lib/room-addressees";
import type { Bot } from "@/state/store";
@@ -20,7 +21,25 @@ function Name({ name, color }: { name: string; color?: string }) {
);
}
-export function ClusterLabel({ bot, name, color, to = [] }: { bot?: Bot; name: string; color: string; to?: readonly RoomAddressee[] }) {
+interface ClusterLabelProps {
+ bot?: Bot;
+ name: string;
+ color: string;
+ to?: readonly RoomAddressee[];
+ /** Drawn again in a new language. */
+ locale?: string;
+}
+
+const sameAddressees = (a: readonly RoomAddressee[] = [], b: readonly RoomAddressee[] = []) =>
+ a.length === b.length && a.every((one, i) => one.key === b[i]!.key && one.name === b[i]!.name && one.color === b[i]!.color);
+
+/** Drawn again only when what it shows changes: a bot's status, words or turn leave it as it is. */
+function sameLabel(a: ClusterLabelProps, b: ClusterLabelProps): boolean {
+ return a.name === b.name && a.color === b.color && a.locale === b.locale && sameAddressees(a.to, b.to)
+ && (a.bot === b.bot || (a.bot !== undefined && b.bot !== undefined && sameDrawnBots([a.bot], [b.bot])));
+}
+
+export const ClusterLabel = memo(function ClusterLabel({ bot, name, color, to = [] }: ClusterLabelProps) {
return (
<div className="mt-1.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 pl-0.5">
<BotAvatar
@@ -46,4 +65,4 @@ export function ClusterLabel({ bot, name, color, to = [] }: { bot?: Bot; name: s
)}
</div>
);
-}
+}, sameLabel);
diff --git a/src/components/RoomTextMessage.tsx b/src/components/RoomTextMessage.tsx
index 566ab96891..ccae3aac55 100644
--- a/src/components/RoomTextMessage.tsx
+++ b/src/components/RoomTextMessage.tsx
@@ -13,7 +13,7 @@ import { cn } from "@/lib/cn";
import { formatTime, type Bot, type Message } from "@/state/store";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { useStoreRef } from "@/state/store-ref";
-import { isLiveReply, streamedReply } from "@/state/live-reply";
+import { isLiveReply, streamedReply, useLiveRow } from "@/state/live-reply";
import { useTeammates } from "@/state/team-people";
import { stripLeakedSystemHarnessMessages } from "../../shared/system-message-guard.ts";
import { ThreadRefText } from "./ThreadRefs";
@@ -66,14 +66,15 @@ function sameRow(previous: RoomTextMessageProps, next: RoomTextMessageProps): bo
return keys.length === Object.keys(previous).length && keys.every((key) => key === "members" ? sameMembers(previous.members, next.members) : Object.is(previous[key], next[key]));
}
-/** One text message in a room: drawn again only when its own props or the store slices it shows change. */
+/** One text message in a room: drawn again only when its own props or the store slices it shows change, or, while it
+ * streams, its words. */
export const RoomTextMessage = memo(function RoomTextMessage({
groupId,
threadId,
dm,
pinned,
working,
- message: m,
+ message: row,
members,
replyTarget,
emerging,
@@ -83,6 +84,7 @@ export const RoomTextMessage = memo(function RoomTextMessage({
phone,
localVoice,
}: RoomTextMessageProps) {
+ const m = useLiveRow(threadId, row);
const dispatch = useStoreDispatch(), store = useStoreRef();
const focusNonce = useStoreSelector((state) => {
const focus = state.focusMessage;
diff --git a/src/lib/room-speaker.ts b/src/lib/room-speaker.ts
index d95b924d40..9dbc458141 100644
--- a/src/lib/room-speaker.ts
+++ b/src/lib/room-speaker.ts
@@ -1,8 +1,9 @@
import type { ActivityTranscriptItem } from "./activity-runs";
import { localDay } from "./transcript-derivations";
+import { isLiveReply } from "@/state/live-reply";
-function isBotText(message: { role: string; kind: string; text?: string; attachments?: readonly unknown[]; from?: { botId: string } }): message is { role: "bot"; kind: "text"; text?: string; attachments?: readonly unknown[]; from: { botId: string }; at: number } {
- return message.role === "bot" && message.kind === "text" && Boolean(message.from?.botId) && Boolean(message.text?.trim() || message.attachments?.length);
+function isBotText(message: { id: string; role: string; kind: string; text?: string; attachments?: readonly unknown[]; from?: { botId: string } }): message is { id: string; role: "bot"; kind: "text"; text?: string; attachments?: readonly unknown[]; from: { botId: string }; at: number } {
+ return message.role === "bot" && message.kind === "text" && Boolean(message.from?.botId) && Boolean(message.text?.trim() || message.attachments?.length || isLiveReply(message));
}
function laterTextOwns(items: readonly ActivityTranscriptItem[], index: number, botId: string, at: number): boolean {
diff --git a/src/state/live-reply.ts b/src/state/live-reply.ts
index 7aa139bc89..4de7e59945 100644
--- a/src/state/live-reply.ts
+++ b/src/state/live-reply.ts
@@ -203,23 +203,16 @@ function subscribe(threadId: string | null | undefined, listener: () => void): (
};
}
-export function useLiveReplies(threadId: string | null | undefined): readonly LiveReplyItem[] {
- return useSyncExternalStore(
- (listener) => subscribe(threadId, listener),
- () => liveReplies(threadId),
- () => EMPTY,
- );
-}
-
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. */
+/** `row` as drawn now: a live row's words so far, from its thread's stream, said by the speaker its stand-in names; 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;
+ return (item && liveRowOf(item, () => row.from)) || row;
}
export function useHasLiveReply(threadId: string | null | undefined): boolean {
@@ -304,6 +297,7 @@ export function withLiveRows(items: readonly LiveReplyItem[], windowed: Message[
* the row shows at all and whether it is only a leaked harness message, which a transcript hides. */
interface LiveRowShape extends Drawable {
turnId?: string;
+ botId?: string;
at: number;
shown: boolean;
/** The words when they are only a leaked harness message, else "". */
@@ -312,11 +306,11 @@ interface LiveRowShape extends Drawable {
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;
+ a.key === b.key && a.itemId === b.itemId && a.savedAs === b.savedAs && a.turnId === b.turnId && a.botId === b.botId && 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 : "" };
+ return { key: item.key, itemId: item.itemId, savedAs: item.savedAs, turnId: item.turnId, botId: item.botId, 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. */
@@ -343,36 +337,28 @@ function liveRowShapes(threadId: string): readonly LiveRowShape[] {
}
const standIns = new WeakMap<LiveRowShape, Message>();
-function standInFor(shape: LiveRowShape): Message | null {
+function standInFor(shape: LiveRowShape, speaker?: LiveSpeaker): Message | null {
if (!shape.shown) return null;
+ const from = speaker?.(shape.botId);
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));
+ if (!row || !sameSpeaker(row.from, from)) standIns.set(shape, (row = { id: `${LIVE_ID}${shape.key}`, role: "bot", kind: "text", text: shape.harness, at: shape.at, ...(shape.turnId ? { turnId: shape.turnId } : {}), ...(from ? { from } : {}) } 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[] {
+/** The `windowed` rows of `transcript` with the thread's live rows after them, 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`. In a room, `speaker` names each live row's member. */
+export function useLiveTranscriptLayout(threadId: string, windowed: Message[], transcript: readonly Message[], speaker?: LiveSpeaker): 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],
+ () => shown.length ? windowWith(drawnAfter(shown, transcript, (shape) => standInFor(shape, speaker)), windowed, transcript) : { rows: windowed, settled: [] },
+ [shown, windowed, transcript, speaker],
);
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[] {
- const items = useLiveReplies(threadId);
- const speaker = useMemo(() => members && roomLiveSpeaker(members, speakingNow), [members, speakingNow]);
- const live = useMemo(() => withLiveRows(items, windowed, transcript, speaker), [items, windowed, transcript, speaker]);
- useEffect(() => settleLiveReplies(threadId, live.settled), [threadId, live.settled]);
- return live.rows;
-}
-
/** Tests only. */
export function resetLiveReplies(): void {
threads.clear();