Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat: a streaming answer no longer redraws every message and the tab strip
luishron123f92b82045505
diff --git a/src/components/ChatView.rows-hold-still.test.ts b/src/components/ChatView.rows-hold-still.test.tsindex f664155fbc..6351be2c13 100644--- a/src/components/ChatView.rows-hold-still.test.ts+++ b/src/components/ChatView.rows-hold-still.test.ts@@ -131,6 +131,15 @@ describe("a long chat on screen", () => {expect(countBy(renderedSince(mark).filter((entry) => entry.row !== null), (entry) => entry.component)).toEqual(new Map());});+ it("draws no saved row again when its own turn starts and ends", async () => {+ const mark = renderMark();+ await send({ kind: "bot", bot: { ...announced("b", "Bea"), busy: true, activity: "working" } });+ await send({ kind: "bot", bot: { ...announced("b", "Bea"), busy: false, activity: "idle" } });+ expect(document.querySelectorAll("[data-mid]").length).toBeGreaterThan(30);+ const redrawn = new Set(renderedSince(mark).flatMap((entry) => entry.component === "Bubble" && entry.row ? [entry.row] : []));+ expect(redrawn, "only the answer Regenerate is offered on").toEqual(new Set(["answer-9"]));+ });+it("draws no saved row again while a reply streams in", async () => {await send({ kind: "bot", bot: { ...announced("b", "Bea"), busy: true, activity: "working" } });await runtime("b-thread", { type: "turn.started" });diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex fa668b8e97..c1242a1ab2 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -259,6 +259,34 @@ export function FailedTurnRow({ tool, engine, onRetry, botId, threadId, messageAexport { MessageBoundary };+function VersionSwitch({ versions, index, onSwitch }: { versions: readonly Message[]; index: number; onSwitch: (version: Message) => void }) {+ const busy = use(ChatBusyContext);+ const go = (version: Message | undefined) => { if (version && !busy) onSwitch(version); };+ return (+ <div className="mt-1 flex items-center gap-0.5 pr-1 text-[12px] text-ink-secondary">+ <button+ onClick={() => go(versions[index - 1])}+ disabled={index <= 0 || busy}+ className="rounded p-0.5 hover:bg-raised hover:text-ink disabled:opacity-30 disabled:hover:bg-transparent"+ title={t("chat.previousVersion")}+ >+ <ChevronLeft size={14} />+ </button>+ <span className="tabular-nums">+ {index + 1}/{versions.length}+ </span>+ <button+ onClick={() => go(versions[index + 1])}+ disabled={index >= versions.length - 1 || busy}+ className="rounded p-0.5 hover:bg-raised hover:text-ink disabled:opacity-30 disabled:hover:bg-transparent"+ title={t("chat.nextVersion")}+ >+ <ChevronRight size={14} />+ </button>+ </div>+ );+}+const Bubble = memo(function Bubble({message: row,emerging = false,@@ -297,10 +325,10 @@ const Bubble = memo(function Bubble({replyTarget?: Message;onReply: (message: Message) => void;}) {- const { botId, threadId, botName, voiceId, tts, localVoice, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer, phone } = useChatRows(), busy = use(ChatBusyContext);+ const { botId, threadId, botName, voiceId, tts, localVoice, bots, mentionPeers, mentionPerson, focus, dispatch, onBranch, bubbleStyle, conversational, simple, canReact, openedAt, speakerViewer, phone } = useChatRows();const message = useLiveRow(threadId, row);const forkAction = !phone && message.kind === "text" && !message.id.startsWith("optimistic-")- ? [forkMessageItem({ kind: "bot", ownerId: botId, threadId, messageId: message.id }, dispatch, busy)] : [];+ ? [{ ...forkMessageItem({ kind: "bot", ownerId: botId, threadId, messageId: message.id }, dispatch, false), disabledWhileBusy: true }] : [];const remoteClient = window.ogb?.remoteClient?.active === true;const peer = peerLine(message) ?? peerRequest(message, botId);const user = message.role === "user" && !peer;@@ -323,7 +351,7 @@ const Bubble = memo(function Bubble({canSpeak: message.kind === "text" && !peer,viewRaw,onToggleRaw: () => setViewRaw((raw) => !raw),- onRegenerate: !busy ? onRegenerate : undefined,+ onRegenerate,pin: remoteClient ? undefined : {pinned,onToggle: () => dispatch({ type: "updateTask", botId, threadId, patch: { pinnedMessageId: pinned ? "" : message.id } }),@@ -377,8 +405,8 @@ const Bubble = memo(function Bubble({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) => {- if (v && !busy && !v.id.startsWith("optimistic-")) dispatch({ type: "switchBranch", botId, threadId, messageId: v.id });+ const switchTo = (v: Message) => {+ if (!v.id.startsWith("optimistic-")) dispatch({ type: "switchBranch", botId, threadId, messageId: v.id });};const togglePin = () =>dispatch({ type: "updateTask", botId, threadId, patch: { pinnedMessageId: pinned ? "" : message.id } });@@ -539,29 +567,7 @@ const Bubble = memo(function Bubble({{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); }} />}{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- onClick={() => switchTo(forks[versionIndex - 1])}- disabled={versionIndex <= 0 || busy}- className="rounded p-0.5 hover:bg-raised hover:text-ink disabled:opacity-30 disabled:hover:bg-transparent"- title={t("chat.previousVersion")}- >- <ChevronLeft size={14} />- </button>- <span className="tabular-nums">- {versionIndex + 1}/{forks.length}- </span>- <button- onClick={() => switchTo(forks[versionIndex + 1])}- disabled={versionIndex >= forks.length - 1 || busy}- className="rounded p-0.5 hover:bg-raised hover:text-ink disabled:opacity-30 disabled:hover:bg-transparent"- title={t("chat.nextVersion")}- >- <ChevronRight size={14} />- </button>- </div>- )}+ {forks.length > 1 && <VersionSwitch versions={forks} index={versionIndex} onSwitch={switchTo} />}</div>);});diff --git a/src/components/HeaderThreadTabs.renders.dom.test.ts b/src/components/HeaderThreadTabs.renders.dom.test.tsnew file mode 100644index 0000000000..d8ac337fd0--- /dev/null+++ b/src/components/HeaderThreadTabs.renders.dom.test.ts@@ -0,0 +1,47 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { Bot, Task } from "@/state/store";++const drawn = vi.hoisted(() => ({ avatars: 0 }));+vi.mock("@/lib/use-feature", () => ({ useFeature: (name: string) => name === "threadTabs" }));+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => vi.fn(), useStoreSelector: () => undefined }));+vi.mock("./Avatar", () => ({ BotAvatar: () => { drawn.avatars++; return null; } }));++import { HeaderThreadTabs } from "./HeaderThreadTabs";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const task = (threadId: string, title: string, at: number, extra: Partial<Task> = {}): Task => ({ threadId, title, createdAt: at, lastThreadOrderAt: at, ...extra });+const tasks = () => Array.from({ length: 60 }, (_, i) => task(`t${i}`, `Thread ${i}`, 100 - i, i === 0 ? { busy: true } : {}));+const kiwi = (extra: Partial<Bot> = {}): Bot =>+ ({ id: "kiwi", name: "Kiwi", color: "green", threadId: "t0", mainThreadId: "t0", busy: true, tasks: tasks(), messages: [], ...extra } as unknown as Bot);++let root: Root | null = null;+afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; drawn.avatars = 0; });++const draw = (bot: Bot) => act(() => root!.render(createElement(HeaderThreadTabs, { bot })));+const selected = () => document.querySelector('[role="tab"][aria-selected="true"]')?.getAttribute("data-tab-id");++describe("thread tab strip while a reply streams", () => {+ it("does not draw its 60 tabs again for a bot update that changes none of them", () => {+ root = createRoot(document.body.appendChild(document.createElement("div")));+ draw(kiwi());+ const first = drawn.avatars;+ expect(document.querySelectorAll('[role="tab"]')).toHaveLength(60);++ draw(kiwi({ messages: [{ id: "m1" } as Bot["messages"][number]], turnStartedAt: 5, activity: "working" } as Partial<Bot>));+ draw(kiwi({ tasks: tasks().map((one) => ({ ...one, lastActivityAt: 9 })) } as Partial<Bot>));+ expect(drawn.avatars).toBe(first);++ draw(kiwi({ tasks: tasks().map((one) => (one.threadId === "t3" ? { ...one, title: "Renamed" } : one)) }));+ expect(drawn.avatars).toBe(first + 1);+ expect(document.querySelector('[data-tab-id="t3"]')?.textContent).toContain("Renamed");++ draw(kiwi({ threadId: "t5" }));+ expect(selected()).toBe("t5");+ draw(kiwi({ threadId: "t5", name: "Kiwi Two" }));+ expect(document.querySelector("[data-thread-tabs-bot]")?.textContent).toBe("Kiwi Two");+ });+});diff --git a/src/components/HeaderThreadTabs.tsx b/src/components/HeaderThreadTabs.tsxindex 8e27fa1dfc..73486ac105 100644--- a/src/components/HeaderThreadTabs.tsx+++ b/src/components/HeaderThreadTabs.tsx@@ -1,7 +1,8 @@-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type WheelEvent as ReactWheelEvent } from "react";+import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type WheelEvent as ReactWheelEvent } from "react";import { Pin, Plus, X } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";+import { sameDrawnBot } from "@/lib/drawn-bots";import { nextRename } from "@/lib/rename";import { localizedTaskTitle } from "@/lib/task-title";import { useFeature } from "@/lib/use-feature";@@ -9,7 +10,7 @@ import type { Bot } from "@/state/store";import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { BotAvatar } from "./Avatar";import { reducedMotion } from "./MenuMotion";-import { botShowsTabs, neighbourOf, openTabId, showsTabs, threadTabs, type ThreadTab } from "./thread-tabs";+import { botShowsTabs, neighbourOf, openTabId, sameTabs, showsTabs, threadTabs, type ThreadTab } from "./thread-tabs";import { useSlidingIndicator, useTabMotion } from "./thread-tab-motion";import { UndoToast, useUndoToast } from "./UndoToast";@@ -32,9 +33,9 @@ export function useBotHasThreads(botId: string): boolean {/** A bot's threads as tabs in the chat header, once Thread tabs is on and the bot has two threads or more. */export function HeaderThreadTabs({ bot }: { bot: Bot }) {const on = useFeature("threadTabs");- const tabs = useMemo(() => threadTabs(bot), [bot.id, bot.threadId, bot.switchingTo, bot.mainThreadId, bot.tasks, bot.busy]);+ const tabs = threadTabs(bot);if (!on || !showsTabs(tabs)) return null;- return <Strip bot={bot} tabs={tabs} />;+ return <Strip bot={bot} tabs={tabs} active={openTabId(bot)} />;}/** The mask that fades a sideways-scrolling row's edges where more of it is hidden, none when it all fits. */@@ -48,13 +49,17 @@ export function edgeFade(element: HTMLElement, fade = FADE): string | undefinedreturn `linear-gradient(to right, ${left}, ${right})`;}-function Strip({ bot, tabs }: { bot: Bot; tabs: ThreadTab[] }) {+type StripProps = { bot: Bot; tabs: ThreadTab[]; active: string };++const sameStrip = (a: StripProps, b: StripProps) => a.active === b.active && sameTabs(a.tabs, b.tabs)+ && a.bot.id === b.bot.id && a.bot.yourAccess === b.bot.yourAccess && sameDrawnBot(a.bot, b.bot);++const Strip = memo(function Strip({ bot, tabs, active }: StripProps) {const dispatch = useStoreDispatch();const panelOpen = useStoreSelector((state) => state.settingsOpen);const panelBeside = useStoreSelector((state) => state.settingsOpen || state.computerOpen || state.inspectorOpen);const scroller = useRef<HTMLDivElement>(null);const { shown, entering } = useTabMotion(tabs, scroller);- const active = openTabId(bot);const indicator = useSlidingIndicator(scroller, active);const [renaming, setRenaming] = useState<string | null>(null);const [draft, setDraft] = useState("");@@ -202,4 +207,4 @@ function Strip({ bot, tabs }: { bot: Bot; tabs: ThreadTab[] }) {<UndoToast toast={toast} onDone={() => setToast(null)} /></div>);-}+}, sameStrip);diff --git a/src/components/MessageActions.tsx b/src/components/MessageActions.tsxindex 9328abb9d2..f98baeb7ad 100644--- a/src/components/MessageActions.tsx+++ b/src/components/MessageActions.tsx@@ -21,6 +21,8 @@ export type MessageMenuItem = {disabled?: boolean;/** Offered only while the chat's turn is not running. */idleOnly?: boolean;+ /** Greyed out while the chat's turn is running. */+ disabledWhileBusy?: boolean;};/** Whether the chat's turn is running, apart from the row values every message reads: a turn starting or ending@@ -66,8 +68,8 @@ export function MessageActions({const [pointAt, setPointAt] = useState<{ x: number; y: number; clientX: number; clientY: number } | null>(null);const offered = pointAt ? [...contextItems, ...items] : items;// use() may run conditionally: a closed menu has no reason to follow the turn.- const busy = menuOpen && offered.some((item) => item.idleOnly) ? use(ChatBusyContext) : false;- const menu = busy ? offered.filter((item) => !item.idleOnly) : offered;+ const busy = menuOpen && offered.some((item) => item.idleOnly || item.disabledWhileBusy) ? use(ChatBusyContext) : false;+ const menu = busy ? offered.filter((item) => !item.idleOnly).map((item) => (item.disabledWhileBusy ? { ...item, disabled: true } : item)) : offered;const [hovered, setHovered] = useState(false);const [keyboardFocus, setKeyboardFocus] = useState(false);const [tapped, setTapped] = useState(false);diff --git a/src/components/message-menu.tsx b/src/components/message-menu.tsxindex 95b9e26425..764674f8a1 100644--- a/src/components/message-menu.tsx+++ b/src/components/message-menu.tsx@@ -99,7 +99,7 @@ export function useBotMessageMenu({onSelect: onToggleRaw,});}- if (onRegenerate) items.push({ key: "regenerate", icon: <RefreshCw {...ACTION_ICON} />, label: t("chat.regenerate"), onSelect: onRegenerate });+ if (onRegenerate) items.push({ key: "regenerate", icon: <RefreshCw {...ACTION_ICON} />, label: t("chat.regenerate"), onSelect: onRegenerate, idleOnly: true });items.push(...teamMemory, ...pinItem(pin), idItem(messageId));return items;}diff --git a/src/components/thread-tabs.ts b/src/components/thread-tabs.tsindex 0f7219dabe..ec008259e2 100644--- a/src/components/thread-tabs.ts+++ b/src/components/thread-tabs.ts@@ -48,6 +48,14 @@ export function threadTabs(bot: TabsBot): ThreadTab[] {return tabs;}+const sameTab = (a: ThreadTab, b: ThreadTab) => a.threadId === b.threadId && a.title === b.title && a.pinned === b.pinned+ && a.working === b.working && a.draft === b.draft && a.closable === b.closable && a.renamable === b.renamable;++/** Whether two strips draw the same tabs in the same order. */+export function sameTabs(a: readonly ThreadTab[], b: readonly ThreadTab[]): boolean {+ return a === b || (a.length === b.length && a.every((tab, i) => sameTab(tab, b[i]!)));+}+/** The strip shows for a bot with two threads or more, its blank New thread chat counted. */export const showsTabs = (tabs: readonly ThreadTab[]): boolean => tabs.length > 1;diff --git a/src/lib/drawn-bots.ts b/src/lib/drawn-bots.tsindex 45dc68da26..15817b04c8 100644--- a/src/lib/drawn-bots.ts+++ b/src/lib/drawn-bots.ts@@ -6,8 +6,13 @@ const drawn = (bot: Bot) => [bot.mascotFaceColor, bot.mascotBodyColor, bot.mascotMaterial, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY,].join("\u0001");+/** Whether two versions of a bot look the same wherever it is drawn by name and avatar. */+export function sameDrawnBot(a: Bot, b: Bot): boolean {+ return a === b || drawn(a) === drawn(b);+}+/** For a reader that draws other bots only by name, look and whether they are shown: a turn changing none of that* keeps the earlier list, so the reader does not render again. */export function sameDrawnBots(a: readonly Bot[], b: readonly Bot[]): boolean {- return a.length === b.length && a.every((bot, i) => bot === b[i] || drawn(bot) === drawn(b[i]!));+ return a.length === b.length && a.every((bot, i) => sameDrawnBot(bot, b[i]!));}