Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Smoother while bots work: one commit per paint, selector subscriptions, one-bot reconcile (#5485)
Milind Sonib692f4709cc8
diff --git a/server/request-auth.ts b/server/request-auth.tsindex e3b0ad4e8f..38648ff112 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -331,6 +331,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET"], path: /^\/api\/events$/ },// reads that carry no secrets{ methods: ["GET"], path: /^\/api\/bots$/ },+ { methods: ["GET"], path: /^\/api\/bots\/[\w-]+$/ },{ methods: ["GET"], path: /^\/api\/team-map$/ },// a link into the organisation's Admin: identifiers only, and Admin authorizes its own visitor{ methods: ["GET"], path: /^\/api\/bots\/[\w-]+\/slack-management$/ },diff --git a/server/routes/threads-one-bot.test.ts b/server/routes/threads-one-bot.test.tsnew file mode 100644index 0000000000..8bee7411d6--- /dev/null+++ b/server/routes/threads-one-bot.test.ts@@ -0,0 +1,78 @@+import { rmSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { NO_SUCH_BOT } from "../../shared/bot-read.ts";+import { DATA_DIR } from "../config.ts";+import type { ModelSelection } from "../contracts.ts";+import { json, readBody } from "../harness/http.ts";+import type { RequestAuth } from "../request-auth.ts";+import { CLIENT_ALLOW } from "../request-auth.ts";+import { Store, type BotRecord } from "../store.ts";+import { dispatchRoutes } from "./table.ts";+import { createThreadRoutes, type ThreadRouteDeps } from "./threads.ts";++type Body = { bot: { messages: Array<{ text: string }>; tasks: unknown[] }; bots: Array<{ id: string }>; error?: string };+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };+const servers: Server[] = [];++beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++async function serve(store: Store, hidden: string): Promise<string> {+ const deps = {+ store, viewerFor: () => ({}),+ visibleTo: () => ({ everything: true, bot: (id: string) => id !== hidden, group: () => true, thread: () => true, sections: () => [] }),+ workspaceAccess: () => null, desktopMutationToken: () => undefined, companionMutationToken: () => undefined, cliOwnerToken: () => undefined,+ groupUsageReader: { refresh: () => {} },+ pageSize: (raw: string | null) => raw === null ? undefined : /^\d+$/.test(raw) ? Number(raw) : null,+ messagePage: (threadId: string, limit = 200) => ({ messages: store.messagesFor(threadId).slice(-limit), hasMore: false, activeLeafId: null }),+ wireBot: (bot: BotRecord) => ({ id: bot.id, threadId: bot.threadId, name: bot.name }),+ publicBotQueuedMessages: () => ({}),+ publicGroupState: () => ({}),+ botComputerControlSnapshot: () => ({ held: false, helpReason: null }),+ } as unknown as ThreadRouteDeps;+ const routes = [createThreadRoutes(deps)];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });+ if (!handled) json(res, 404, { from: "inline routes" });+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+}++describe("GET /api/bots/:id", () => {+ it("answers one bot as the list does, with only its own newest messages", async () => {+ const store = new Store(() => sonnet);+ const scout = store.createBot({ name: "Scout" }, { seedMessages: false });+ const other = store.createBot({ name: "Other" }, { seedMessages: false });+ const hidden = store.createBot({ name: "Hidden" }, { seedMessages: false });+ for (const text of ["one", "two", "three"]) store.appendMessage(scout.threadId, { role: "user", kind: "text", text });+ store.appendMessage(other.threadId, { role: "user", kind: "text", text: "elsewhere" });+ const base = await serve(store, hidden.id);+ const get = async (path: string) => { const res = await fetch(`${base}${path}`); return { status: res.status, body: await res.json() as Body }; };++ const one = await get(`/api/bots/${scout.id}?messages=2`);+ const list = await get(`/api/bots?messages=2`);+ expect(one.status).toBe(200);+ expect(one.body).toEqual({ bot: list.body.bots.find((bot) => bot.id === scout.id) });+ expect(one.body.bot.messages.map((message) => message.text)).toEqual(["two", "three"]);+ expect(one.body.bot.tasks).toEqual([]);++ expect(await get(`/api/bots/${hidden.id}`)).toEqual({ status: 404, body: { error: NO_SUCH_BOT } });+ expect(await get("/api/bots/no-such-bot")).toEqual({ status: 404, body: { error: NO_SUCH_BOT } });+ expect((await get(`/api/bots/${scout.id}?messages=-1`)).status).toBe(400);+ });++ it("is a read a client session may make, like the list", () => {+ const allowed = (path: string) => CLIENT_ALLOW.some((rule) => rule.methods.includes("GET") && rule.path.test(path));+ expect(allowed("/api/bots")).toBe(true);+ expect(allowed("/api/bots/bot-1")).toBe(true);+ });+});diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex a142379ad5..ef07d8d740 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -2,6 +2,7 @@ import { userError } from "../user-errors.ts";import { basename, join } from "node:path";import type { WireBot, WireGroup } from "../../shared/wire.ts";+import { NO_SUCH_BOT } from "../../shared/bot-read.ts";import {ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,parseAudioRange, readAttachment, saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,@@ -78,6 +79,13 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {pageSize, messagePage, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo,} = deps;+ // tasks stays explicit: clients expect [] where wireBot() would omit the key.+ const shownBot = (bot: BotRecord, visible: VisibleSet, limit: number | undefined) => {+ const wired = wireBot(bot);+ // Narrowed first: on a Team Cloud the selected conversation may be someone else's, and its words never go out.+ const shown = memberBot({ ...wired, tasks: wired.tasks ?? [] }, visible);+ return { ...shown, ...(typeof shown.threadId === "string" ? messagePage(shown.threadId, limit) : { messages: [], hasMore: false, activeLeafId: null }) };+ };const jobs = createJobRoutes({ store, coordinator: deps.coordinator, groupThreadIsWorking: deps.groupThreadIsWorking, viewerFor, visibleTo, sessions });const handle = async ({ req, res, url, path, method, auth, json, readBody }: RouteContext): Promise<unknown> => {let m: RegExpMatchArray | null = null;@@ -92,16 +100,10 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {try { groupUsageReader.refresh(); } catch { }const limit = pageSize(url.searchParams.get("messages"));if (limit === null) return json(res, 400, { error: "messages must be a non-negative whole number" });- // tasks stays explicit: clients expect [] where wireBot() would omit the key.const shownBots = (deps.botOrderFor?.(auth, store.bots) ?? store.bots).filter((bot) => visible.bot(bot.id));const queued = publicBotQueuedMessages();return json(res, 200, {- bots: shownBots.map((bot) => {- const wired = wireBot(bot);- // Narrowed first: on a Team Cloud the selected conversation may be someone else's, and its words never go out.- const shown = memberBot({ ...wired, tasks: wired.tasks ?? [] }, visible);- return { ...shown, ...(typeof shown.threadId === "string" ? messagePage(shown.threadId, limit) : { messages: [], hasMore: false, activeLeafId: null }) };- }),+ bots: shownBots.map((bot) => shownBot(bot, visible, limit)),botQueuedMessages: visible.everything ? queued : Object.fromEntries(Object.entries(queued).filter(([threadId]) => visible.thread(threadId))),sections: visible.sections(store.sections),groups: store.groups.filter((g) => visible.group(g.id)).map((g) => {@@ -120,6 +122,15 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {});}+ m = path.match(/^\/api\/bots\/([\w-]+)$/);+ if (m && method === "GET") {+ const bot = store.bot(m[1]);+ if (!bot || !visible.bot(bot.id)) return json(res, 404, { error: NO_SUCH_BOT });+ const limit = pageSize(url.searchParams.get("messages"));+ if (limit === null) return json(res, 400, { error: "messages must be a non-negative whole number" });+ return json(res, 200, { bot: shownBot(bot, visible, limit) });+ }+m = path.match(/^\/api\/threads\/([\w-]+)\/messages$/);if (m && method === "GET") {const threadId = m[1];diff --git a/shared/bot-read.ts b/shared/bot-read.tsnew file mode 100644index 0000000000..b179930664--- /dev/null+++ b/shared/bot-read.ts@@ -0,0 +1,3 @@+/** The error of `GET /api/bots/:id` (404) when the bot does not exist or the caller may not see it. A 404 without it+ * comes from a server that has no one-bot read. */+export const NO_SUCH_BOT = "no such bot";diff --git a/src/App.tsx b/src/App.tsxindex 67de49f3bb..1ff0b5c02e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -148,6 +148,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {cloudAddOpened.current ||= Boolean(state.cloudAdd);const [localVmWorkspaceBotId, setLocalVmWorkspaceBotId] = useState<string | null>(null);const menuButtonRef = useRef<HTMLButtonElement>(null);+ const closeDrawer = useCallback(() => { setDrawerOpen(false); menuButtonRef.current?.focus(); }, []);const previousViewRef = useRef(state.activeView);const calendarOriginRef = useRef<"chat" | "team-map" | "web-panel">("chat");const loading = loadingLine({ connected: state.connected, hydrated: state.hydrated === true, developer: import.meta.env.DEV });@@ -368,10 +369,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {{!calendarFocus && <SidebarcollapseToIcons={collapseSidebar}open={drawerOpen}- onClose={() => {- setDrawerOpen(false);- menuButtonRef.current?.focus();- }}+ onClose={closeDrawer}/>}{state.activeView === "team-map" ? (<TeamMapPage />diff --git a/src/components/ChatHeadPill.tsx b/src/components/ChatHeadPill.tsxindex 2973678ca2..425286aa9c 100644--- a/src/components/ChatHeadPill.tsx+++ b/src/components/ChatHeadPill.tsx@@ -4,7 +4,7 @@ import type { ComponentProps } from "react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import type { Bot } from "@/state/store"; import { useStoreSelector } from "@/state/store-select";import { awayFromMainThread } from "@/state/thread-navigation";import { BotAvatar } from "./Avatar";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";@@ -38,9 +38,8 @@ export function ChatHeadPill({ bot, avatar, privacy, onToggle }: {privacy: ChatHeadPrivacy;onToggle: () => void;}) {- const { state } = useStore();- const open = state.settingsOpen;- const elsewhere = sidebarBotActivityTasks(bot, state.pendingQueued).filter((task) => task.threadId !== bot.threadId).length;+ const open = useStoreSelector((state) => state.settingsOpen), pendingQueued = useStoreSelector((state) => state.pendingQueued);+ const elsewhere = sidebarBotActivityTasks(bot, pendingQueued).filter((task) => task.threadId !== bot.threadId).length;const privacyLabel = privacyLabelOf(privacy);const PrivacyIcon = privacy ? PRIVACY_ICONS[privacy.kind] : Users;const title = bot.tasks?.find((task) => task.threadId === bot.threadId)?.title;diff --git a/src/components/ChatView.render-count.test.ts b/src/components/ChatView.render-count.test.tsnew file mode 100644index 0000000000..16dfd3da8f--- /dev/null+++ b/src/components/ChatView.render-count.test.ts@@ -0,0 +1,137 @@+// @vitest-environment happy-dom+// The real provider and live stream with two bots, B's chat on screen: frames about A must not draw B's chat again.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { ServerFrame } from "../../shared/wire";+import type { Action, BotAnnouncement, InstanceInfo, Message } from "@/state/store";++const renders = vi.hoisted(() => ({ chat: 0, composer: 0, header: 0 }));+vi.mock("@/lib/drafts", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/lib/drafts")>();+ return {+ ...original,+ useReplyDraft: (...args: Parameters<typeof original.useReplyDraft>) => { renders.chat++; return original.useReplyDraft(...args); },+ useComposerDraft: (...args: Parameters<typeof original.useComposerDraft>) => { renders.composer++; return original.useComposerDraft(...args); },+ };+});+vi.mock("./SidebarBotActivity", async (importOriginal) => {+ const original = await importOriginal<typeof import("./SidebarBotActivity")>();+ return { ...original, sidebarBotActivityTasks: (...args: Parameters<typeof original.sidebarBotActivityTasks>) => { renders.header++; return original.sidebarBotActivityTasks(...args); } };+});+vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true, useReactor: () => "user" }));+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancedMode: vi.fn() }));++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const announced = (id: string, name: string): BotAnnouncement => ({+ id, threadId: `${id}-thread`, name, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "test", model: "m" },+ tasks: [{ threadId: `${id}-thread`, title: "Chat", createdAt: 1, approvalMode: "ask" }],+});+const 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": {},+ "/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!: (action: Action) => void;+function Shown() {+ dispatch = useStore().dispatch;+ return null;+}+function Shell() {+ const bot = useStoreSelector((state) => state.bots.find((candidate) => candidate.id === "b"));+ return bot ? createElement(ChatView, { bot }) : null;+}++let root: Root;+let cursor = 0;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 6; i++) await task(); };+const stream = () => FixtureEventSource.opened[0]!;+const send = async (frame: object) => { stream().send(frame, `run:${++cursor}`); await settle(); };+const reply = (threadId: string, id: string): ServerFrame => ({ kind: "message", threadId, message: { id, at: ++cursor, role: "bot", kind: "text", text: id } as Message } as ServerFrame);+const counts = () => ({ ...renders });++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?")+ ? json({ bots: [announced("a", "Ada"), announced("b", "Bea")].map((bot) => ({ ...bot, messages: [] })), 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: "b" }));+ await settle();+});+afterAll(() => {+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});++describe("a chat on screen", () => {+ it("is drawn", () => {+ expect(document.querySelector('[data-chathead-pill]')).not.toBeNull();+ expect(renders.chat).toBeGreaterThan(0);+ expect(renders.composer).toBeGreaterThan(0);+ expect(renders.header).toBeGreaterThan(0);+ });++ it("does not draw again, nor its composer or header, for another bot's turn", async () => {+ // The header's mascot motion is one for the whole app: A's first frame takes it from B, a change B does show.+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: true, activity: "working" } });+ const before = counts();+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: true, activity: "working", description: "Still working" } });+ await send(reply("a-thread", "a1"));+ await send({ kind: "message.patch", threadId: "a-thread", message: { id: "a1", at: 1, role: "bot", kind: "text", text: "a1, longer" } });+ await send({ kind: "runtime", event: { type: "turn.started", eventId: "e1", provider: "codex", threadId: "a-thread", turnId: "t1", createdAt: "2026-11-11T00:00:00.000Z" } });+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: false, activity: "idle" } });+ expect(counts()).toEqual(before);+ });++ it("does not draw again for a store change it does not show", async () => {+ const before = counts();+ flushSync(() => dispatch({ type: "connected", value: false }));+ flushSync(() => dispatch({ type: "connected", value: true }));+ await settle();+ expect(counts()).toEqual(before);+ });++ it("draws its composer again when another bot's title changes, which the @-mention menu shows", async () => {+ const before = counts();+ await send({ kind: "bot", bot: { ...announced("a", "Ada"), busy: false, activity: "idle", title: "Researcher" } });+ expect(renders.composer).toBeGreaterThan(before.composer);+ });++ it("draws again for its own bot's reply", async () => {+ const before = counts();+ await send(reply("b-thread", "b1"));+ expect(renders.chat).toBeGreaterThan(before.chat);+ expect(document.querySelector('[data-mid="b1"]')).not.toBeNull();+ });+});diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 84e6279a5d..653308d849 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -17,7 +17,6 @@ import { useCaptionChrome, useDesktopCapabilities } from "@/components/DesktopCaimport {api,currentTaskBot,- useStore,formatTime,openRoomThread,openThread,@@ -92,7 +91,7 @@ import { AttachmentGallery, collectMessageFiles, replyAttachmentGroup, splitMessimport { ScreenFrame } from "./ScreenFrame";import { CompactionChip, DigestChip } from "./DigestChip";import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";-import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref";+import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { sameDrawnBots } from "@/lib/drawn-bots";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";import { ModelPicker } from "./ModelPicker";import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats";@@ -165,16 +164,6 @@ function useChatRows(): ChatRows {return rows;}-const drawnBot = (bot: Bot) =>- [bot.id, bot.name, bot.hidden, bot.color, bot.mascotBody, bot.mascotExpression, bot.mascotFaceColor, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY].join("\u0001");--function useDrawnBots(bots: readonly Bot[]): readonly Bot[] {- const signature = bots.map(drawnBot).join("\u0002");- const cache = useRef({ signature, bots });- if (cache.current.signature !== signature) cache.current = { signature, bots };- return cache.current.bots;-}-export function ErrorRow({message,headline: plainHeadline,@@ -254,11 +243,11 @@ function PlaceFailedRow({ place, botId, threadId, onRetry }: {threadId?: string;onRetry?: () => void;}) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch(), config = useStoreSelector((state) => state.config);const { capabilities } = useDesktopCapabilities();- const seat = usePlaceSeat(state.config, capabilities);- const bot = state.bots.find((candidate) => candidate.id === botId);- const view = placeRowViewFor(place, seat, worksOnSimpleLabel(bot?.computer, capabilities.host.platform));+ const seat = usePlaceSeat(config, capabilities);+ const computer = useStoreSelector((state) => state.bots.find((candidate) => candidate.id === botId)?.computer);+ const view = placeRowViewFor(place, seat, worksOnSimpleLabel(computer, capabilities.host.platform));const id = view.action?.id;const onClick = !id ? undefined: id === "try-again" ? onRetry@@ -268,7 +257,7 @@ function PlaceFailedRow({ place, botId, threadId, onRetry }: {const TRIAL_CREDIT_LINE: Record<"paused" | "too_low", LocaleKey> = { paused: "engines.trialCreditPaused", too_low: "engines.trialCreditTooLow" };function TrialCreditFailedRow({ kind, onRetry }: { kind: TrialCreditRefusal; onRetry?: () => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();if (kind === "used_up" || kind === "ended") return <TrialCreditNotice kind={kind} />;if (kind === "paused") return <ErrorRow message={t(TRIAL_CREDIT_LINE[kind])} onRetry={onRetry} />;return <ErrorRow message={t(TRIAL_CREDIT_LINE[kind])} action={{ label: t("chat.error.connectOwnAi"), onClick: () => dispatch({ type: "toggleAppSettings", open: true, section: "engines" }) }} />;@@ -810,9 +799,9 @@ const MessagesList = memo(function MessagesList({const CHATHEAD_PILL = `flex min-w-0 items-center gap-2 rounded-full py-0.5 pl-1.5 text-ink ${ELEVATED_FLOAT}`;-export function ChatView({ bot: profile }: { bot: Bot }) {+export const ChatView = memo(function ChatView({ bot: profile }: { bot: Bot }) {const bot = useMemo(() => currentTaskBot(profile), [profile]);- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ computerStart: s.computerStarts[profile.id], mascotMotion: s.mascotMotion?.botId === profile.id ? s.mascotMotion : null, instances: s.instances, config: s.config, focusMessage: s.focusMessage, settingsOpen: s.settingsOpen, computerOpen: s.computerOpen, error: s.error, notice: s.notice }), sameFields), dispatch = useStoreDispatch(), store = useStoreRef();const showThreads = useShowThreads();const remoteClient = window.ogb?.remoteClient?.active === true;const { dragProps: headerDragProps, noDragStyle: headerNoDragStyle } = useCaptionChrome();@@ -826,8 +815,8 @@ export function ChatView({ bot: profile }: { bot: Bot }) {const simpleHead = !advanced && !remoteClient;const canWrite = useCanWriteIn(bot.threadId, bot.yourAccess);- const computerStarting = computerStartLine(state.computerStarts[bot.id], bot.name); useScreensWhile(Boolean(computerStarting));- const mascotMotion = state.mascotMotion?.botId === bot.id ? state.mascotMotion : null;+ const computerStarting = computerStartLine(state.computerStart, bot.name); useScreensWhile(Boolean(computerStarting));+ const mascotMotion = state.mascotMotion;const [findOpen, setFindOpen] = useState(false);const { replyTo, selectReply, clearReply, consumeReply, restoreReply } = useReplyDraft(bot.threadId,@@ -889,7 +878,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {);const unreadDivider = useUnreadDivider({ threadId: bot.threadId, messages, following });- const bots = useDrawnBots(state.bots);+ const bots = useStoreSelector((s) => s.bots, sameDrawnBots);const teammates = useTeammates(); const mentionPeers = useMemo(() => [...bots.filter((peer) => peer.id !== bot.id), ...teammates.peers], [bots, bot.id, teammates]);const focus = state.focusMessage?.threadId === bot.threadId ? state.focusMessage : null;const showToolCalls = showToolCallsEnabled(state.config);@@ -1000,7 +989,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {// A run inside its own results conversation (a wait finishing in this chat) is no execution thread: no banner.const routineExecution = routineRun && (routineRun.resultsThreadId ?? routineRun.sourceThreadId) !== bot.threadId ? routineRun : undefined;const resultsThreadId = routineExecution?.resultsThreadId ?? routineExecution?.sourceThreadId;- const canOpenResults = resultsThreadId && [...state.bots, ...state.groups].some((owner) => owner.threadId === resultsThreadId || owner.tasks?.some((task) => task.threadId === resultsThreadId));+ const canOpenResults = useStoreSelector((s) => Boolean(resultsThreadId) && [...s.bots, ...s.groups].some((owner) => owner.threadId === resultsThreadId || owner.tasks?.some((task) => task.threadId === resultsThreadId)));return (<ThreadLinkContext value={threadLink}>@@ -1113,7 +1102,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {{phone && <UsageAlert engine={bot.modelSelection?.instanceId} />}{/* The model and the bot's computer stay in view in both modes; Simple mode moves only ⋯ into the bot panel. */}{!phone && <ModelPicker key={bot.threadId} bot={bot} threadId={bot.threadId} />}- <LiveCallChip currentBotId={bot.id} onOpen={(botId, threadId) => openThread(dispatch, { botId, threadId }, state, showThreads)} />{!phoneMenu && <WatchScreenButton botId={bot.id} messages={messages} liveTools={liveTools} place={place} />}+ <LiveCallChip currentBotId={bot.id} onOpen={(botId, threadId) => openThread(dispatch, { botId, threadId }, store.state(), showThreads)} />{!phoneMenu && <WatchScreenButton botId={bot.id} messages={messages} liveTools={liveTools} place={place} />}{!phoneMenu && <buttondata-tour="computer"onClick={(event) => { if (!state.computerOpen) rememberComputerPanelOpen({ botId: bot.id, opener: event.currentTarget, tabs: event.detail === 0 }); dispatch({ type: "toggleComputer" }); }}@@ -1134,7 +1123,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {{(advanced || remoteClient) && <BotActivityPicker bot={bot} />}{privateChat && team && <TeamPrivateFirstLine key={team.id} team={team} />}{routineExecution && <div className="mx-5 mb-2 flex flex-wrap items-center gap-2 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[12px] text-ink-secondary"><span className="min-w-0 flex-1 truncate">{t("routines.executionDetails", { name: routineExecution.routineName })}</span>- {canOpenResults && resultsThreadId && <button type="button" onClick={() => openThread(dispatch, { botId: bot.id, threadId: resultsThreadId }, state, showThreads)} className="rounded px-2 py-1 text-accent hover:bg-raised">{t("routines.results.back")}</button>}+ {canOpenResults && resultsThreadId && <button type="button" onClick={() => openThread(dispatch, { botId: bot.id, threadId: resultsThreadId }, store.state(), showThreads)} className="rounded px-2 py-1 text-accent hover:bg-raised">{t("routines.results.back")}</button>}<button type="button" onClick={() => dispatch({ type: "showRoutines", section: "logs", routineId: routineExecution.routineId, botId: bot.id })} className="rounded px-2 py-1 hover:bg-raised hover:text-ink">{t("routines.logs")}</button></div>}{findOpen && <ChatFindBar threadId={bot.threadId} onClose={() => setFindOpen(false)} />}@@ -1303,4 +1292,4 @@ export function ChatView({ bot: profile }: { bot: Bot }) {</main></ThreadLinkContext>);-}+});diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex e776a6ef72..fba649d23f 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -3,7 +3,8 @@ import { TeamAudienceLabel } from "./TeamSideSwitch";import { useComposerDictation } from "@/lib/use-composer-dictation";import { useCallback, useEffect, useMemo, useRef, useState, type SetStateAction } from "react";import { Mic, Paperclip, Square, X } from "lucide-react";-import { useStore, visibleMessages, currentTaskBot, type Bot, type Group, type InstanceInfo, type Message } from "@/state/store";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";+import { visibleMessages, currentTaskBot, type Bot, type Group, type InstanceInfo, type Message } from "@/state/store";import { cn } from "@/lib/cn";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";import { useMenuMotion } from "./MenuMotion";@@ -127,7 +128,7 @@ export function Composer({}) {const bot = profile ? currentTaskBot(profile) : undefined;const locked = setupLocked || Boolean(bot?.awaitingThreadSnapshot);- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances, config: s.config, queued: s.pendingQueued[group?.threadId ?? bot?.threadId ?? ""] }), sameFields), dispatch = useStoreDispatch(), store = useStoreRef(), bots = useStoreSelector((s) => s.bots, sameDrawnBots);const { threads, currentBotId } = useThreadRefs();const advanced = useAdvancedMode();// On a phone the composer is a dock: a round + (attach and every other tool), then one pill with the field, the mic and the voice button.@@ -153,10 +154,10 @@ export function Composer({const approval = approvals[0];// A Turn on card can wait while the person walks to their computer: they can still write meanwhile.const blocking = Boolean(approval && !approval.message.card?.computerAsk);- const approvalBot = group+ const asker = useStoreSelector((s) => s.bots.find((one) => one.id === approval?.message.inbox?.from.botId)), approvalBot = group? members?.find((member) => member.id === approval?.message.from?.botId) ??members?.find((member) => member.id === groupBusyBotId)- : state.bots.find((one) => one.id === approval?.message.inbox?.from.botId) ?? bot;+ : asker ?? bot;const busyName = group? (members?.find((b) => b.id === groupBusyBotId)?.name ??(groupWorking ? t("composer.busy.team") : t("composer.busy.aBot")))@@ -334,11 +335,11 @@ export function Composer({...(!group.dm ? [{ id: "__everyone__", name: "everyone" }] : []),...(members ?? []).map((member) => ({ id: member.id, name: member.name, bot: member })),]- : state.bots+ : bots.filter((member) => member.id !== bot?.id && !member.hidden && !hiddenFromSidebar(member, viewer)).map((member) => ({ id: member.id, name: member.name, bot: member }));return mentionChoicesForQuery([...pool, ...teammateChoices(teammates.people), DEVS_CHOICE], mention.query);- }, [mention, dismissedAt, state.bots, bot?.id, group, members, teammates, viewer]);+ }, [mention, dismissedAt, bots, bot?.id, group, members, teammates, viewer]);const mentionEveryoneCount = (members ?? []).filter((member) => !member.hidden).length;const mentionPickerOpen = candidates.length > 0;const commandMotion = useMenuMotion(commandPickerOpen);@@ -406,7 +407,7 @@ export function Composer({};const sharedChat = Boolean(state.config?.team && !group && profile?.tasks?.some((task) => task.threadId === threadId && !task.private));- const queuedMessages = sharedChat ? [] : state.pendingQueued[threadId] ?? [];+ const queuedMessages = sharedChat ? [] : state.queued ?? [];const pendingCount = queuedMessages.length;const canSteerQueued = composerCanSteerQueuedMessages(busy,@@ -558,7 +559,7 @@ export function Composer({if (!composed) return;stopDictation();const body = restoredRequestText(draftId) ?? composed;- const dataContext = dataContextFor(body, state.computerOpen ? state.dataView : null, !group && bot ? { botId: bot.id, threadId } : undefined);+ const dataContext = dataContextFor(body, store.state().computerOpen ? store.state().dataView : null, !group && bot ? { botId: bot.id, threadId } : undefined);const sentDraft: ComposerDraftSnapshot = {draftId,revision: draftRevision(draftId),@@ -830,7 +831,7 @@ export function Composer({<MentionTextareawrapperClassName={singleRow || simpleDock ? undefined : cn("@max-[30rem]/composer:order-first @max-[30rem]/composer:basis-full", stacked && "order-first basis-full")}inputRef={inputRef}- peers={[...(group ? members ?? [] : state.bots.filter((member) => member.id !== bot?.id)), ...teammates.peers]}+ peers={[...(group ? members ?? [] : bots.filter((member) => member.id !== bot?.id)), ...teammates.peers]}everyone={Boolean(group && !group.dm)}dir="auto"rows={1}diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex 4180b3edee..adf00468c1 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -3,7 +3,7 @@ import { modelLabel, modelProvider } from "@/lib/model-label";import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";import { createPortal } from "react-dom";import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, KeyRound, Loader2, RefreshCw, X } from "lucide-react";-import { useStore, currentTaskBot, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store";+import { useStore, currentTaskBot, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store"; import { sameFields, useStoreActions, useStoreSelector } from "@/state/store-select";import type { EffortLevel } from "../../shared/wire";import { filterCustomModels, partitionCustomModels, suggestedModels } from "@/lib/custom-models";import { configuredModelInstances, isClaudeAccount, isCustomOnly, modelsAwaitEngine, SIGN_IN_FAMILY_LABEL, signInFamily } from "@/lib/engine-rail";@@ -215,7 +215,7 @@ export function ModelPicker({label?: ReactNode;size?: "sm" | "md";}) {- const { state, dispatch: storeDispatch, refreshInstances, refreshModels: refreshInstanceModels } = useStore();+ const { dispatch: storeDispatch, refreshInstances, refreshModels: refreshInstanceModels } = useStoreActions(), state = useStoreSelector((s) => ({ instances: s.instances, modelVariantSessions: s.modelVariantSessions, profile: s.bots.find((candidate) => candidate.id === shown.id) }), sameFields);const [open, setOpen] = useState(false);const { bot, dispatch } = useAiSwitch({ bot: shown, threadId, contained, dispatch: storeDispatch, setOpen: (next) => (next ? openMenu() : setOpen(false)) });const locked = lockedWhileBusy(state, bot, contained, threadId);@@ -436,7 +436,7 @@ export function ModelPicker({setFullView(false);};- const profile = state.bots.find((candidate) => candidate.id === bot.id) ?? bot;+ const profile = (state.profile?.id === bot.id ? state.profile : undefined) ?? bot;const follows = threadId ? profile.tasks?.find((task) => task.threadId === threadId)?.followsBotModel : undefined;const botModelInstance = state.instances.find((instance) => instance.instanceId === profile.modelSelection.instanceId);const botModelName = botModelInstance ? `${engineDisplayName(botModelInstance)} · ${modelLabel(botModelInstance, profile.modelSelection.model)}${variantSuffix(botModelInstance, profile.modelSelection.model, profile.modelSelection.variant)}` : profile.modelSelection.model;diff --git a/src/components/NowCard.tsx b/src/components/NowCard.tsxindex 602620a399..ea65ee4d3c 100644--- a/src/components/NowCard.tsx+++ b/src/components/NowCard.tsx@@ -1,6 +1,7 @@import { useMemo } from "react";import type { LocaleKey } from "@/locales";-import { useStore, type Bot, type Message } from "@/state/store";+import type { Bot, Message } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";import type { TurnLive } from "@/state/turn-status";import { cn } from "@/lib/cn";import { focusActivityRun } from "@/lib/activity-focus";@@ -44,7 +45,7 @@ export function NowCard({ steps, tail, onOpenActivity }: { steps: readonly NowSt/** Everything the working line of a bot's chat shows: what is happening now, in each mode's words, how a long step is* doing, and the card it unfolds. */export function useTurnNow(bot: Pick<Bot, "id" | "name" | "threadId">, messages: readonly Message[], lastMessage: Message | undefined, live: TurnLive, advanced: boolean) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const status = live.status;const exact = turnNowPhrases(status, lastMessage);const shown = advanced ? exact : friendlyNowPhrases(status, lastMessage);diff --git a/src/components/RoutineResultsNavigation.test.ts b/src/components/RoutineResultsNavigation.test.tsindex 4ccaa9a8a7..424e2b8aba 100644--- a/src/components/RoutineResultsNavigation.test.ts+++ b/src/components/RoutineResultsNavigation.test.ts@@ -24,6 +24,7 @@ vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));const { initialState } = await import("@/state/store");const { EventDetails } = await import("./RoutineCalendarPage");const { ChatView } = await import("./ChatView");+const drawChatView = (ChatView as unknown as { type: (props: import("react").ComponentProps<typeof ChatView>) => import("react").ReactNode }).type;const bot: Bot = {id: "runner", threadId: "execution", name: "Runner", title: "", description: "", color: "green",@@ -134,7 +135,7 @@ describe("routine results navigation", () => {it("returns from an execution chat to its group-owned source task", () => {fixture.state!.routineRuns = [{ ...run, sourceThreadId: "original-room-source" }];- const buttons = buttonsFrom(() => ChatView({ bot }));+ const buttons = buttonsFrom(() => drawChatView({ bot }));expect(buttons.has("Back to results")).toBe(true);buttons.get("Back to results")!.onClick!();expect(fixture.dispatch.mock.calls).toEqual([@@ -164,12 +165,12 @@ describe("routine results navigation", () => {it("omits Back to results when the execution's recorded destination was deleted", () => {fixture.state!.routineRuns = [{ ...run, resultsThreadId: "deleted-destination" }];- expect(buttonsFrom(() => ChatView({ bot })).has("Back to results")).toBe(false);+ expect(buttonsFrom(() => drawChatView({ bot })).has("Back to results")).toBe(false);});it("shows no run banner when the run worked inside the conversation its results go to", () => {fixture.state!.routineRuns = [{ ...run, resultsThreadId: "execution", sourceThreadId: "execution" }];- const buttons = buttonsFrom(() => ChatView({ bot }));+ const buttons = buttonsFrom(() => drawChatView({ bot }));expect(buttons.has("Back to results")).toBe(false);expect(buttons.has("Run logs")).toBe(false);});diff --git a/src/components/SharedQueueLine.tsx b/src/components/SharedQueueLine.tsxindex d22ec64afa..dcbfb83c26 100644--- a/src/components/SharedQueueLine.tsx+++ b/src/components/SharedQueueLine.tsx@@ -7,7 +7,8 @@ import { useReactor } from "@/lib/cloud-guest";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import type { Bot } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";type Waiting = { queueId: string; text: string; sender?: ResolvedSender };@@ -75,14 +76,14 @@ export function SharedQueueLine({ waiting, viewer, onRemove, className }: {/** In a Team Cloud conversation several people write in: the working line's lead, the quiet line under it, and whether* the viewer may act on a request someone made. */export function useSharedRun(bot: Bot, advanced: boolean): { label?: string; line: ReactNode; mayAct: (asker: ResolvedSender | undefined) => boolean } {- const { state, dispatch } = useStore();+ const team = useStoreSelector((state) => Boolean(state.config?.team)), waiting = useStoreSelector((state) => state.pendingQueued[bot.threadId]), dispatch = useStoreDispatch();const viewer = useReactor();const mayAct = useMayAct();- const task = state.config?.team ? bot.tasks?.find((one) => one.threadId === bot.threadId && !one.private) : undefined;+ const task = team ? bot.tasks?.find((one) => one.threadId === bot.threadId && !one.private) : undefined;if (!task) return { line: null, mayAct: () => true };return {label: workingForLabel(task.askedBy, viewer),- line: <SharedQueueLine waiting={state.pendingQueued[bot.threadId] ?? []} viewer={viewer} className={advanced ? "ps-11" : "ps-12"}+ line: <SharedQueueLine waiting={waiting ?? []} viewer={viewer} className={advanced ? "ps-11" : "ps-12"}onRemove={(queueId) => dispatch({ type: "cancelQueued", botId: bot.id, threadId: bot.threadId, queueId })} />,mayAct,};diff --git a/src/components/Sidebar.departments.test.ts b/src/components/Sidebar.departments.test.tsindex 0cf4b600f4..61b9d79bfd 100644--- a/src/components/Sidebar.departments.test.ts+++ b/src/components/Sidebar.departments.test.ts@@ -38,6 +38,7 @@ vi.mock("./DesktopCapabilities", async () => {vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.advanced }));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => fixture.advanced, setAdvancedMode: () => {} }));vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) };@@ -48,6 +49,7 @@ import { BOTS_SECTION_ID, CHANNELS_SECTION_ID, userSectionId } from "@/lib/sidebimport { SIDEBAR_DENSITY_KEY } from "@/lib/sidebar-preferences";import { PHONE_LAYOUT } from "@/lib/use-media-query";import { BotContextMenu, BotListItem, Sidebar, TeamMenuItems } from "./Sidebar";+const drawSidebar = (Sidebar as unknown as { type: (props: import("react").ComponentProps<typeof Sidebar>) => import("react").ReactNode }).type;import { NEW_DEPARTMENT } from "./SidebarBotDrag";import { SidebarSectionHeader } from "./SidebarSectionHeader";import { ConfirmDialog } from "./ConfirmDialog";@@ -73,7 +75,7 @@ function nodes(value: ReactNode): ReactElement<Props>[] {}function render() {fixture.index = 0;- const root = Sidebar({ open: false, onClose: () => {} }) as ReactElement<Props>;+ const root = drawSidebar({ open: false, onClose: () => {} }) as ReactElement<Props>;return [root, ...nodes(root.props.children)];}const rows = () => render().filter((node) => node.type === BotListItem).map((node) => node.props as unknown as RowProps);diff --git a/src/components/Sidebar.header-menus.test.ts b/src/components/Sidebar.header-menus.test.tsindex fe38505070..a32f88f7e3 100644--- a/src/components/Sidebar.header-menus.test.ts+++ b/src/components/Sidebar.header-menus.test.ts@@ -33,12 +33,14 @@ vi.mock("./DesktopCapabilities", async () => {});vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true, setAdvancedMode: () => {} }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: original.initialState, dispatch: vi.fn() }) };});import { Sidebar } from "./Sidebar";+const drawSidebar = (Sidebar as unknown as { type: (props: import("react").ComponentProps<typeof Sidebar>) => import("react").ReactNode }).type;import { SidebarNewChatPanel } from "./SidebarNewChatPanel";type Props = { children?: ReactNode; className?: string; onClick?: () => void; [key: string]: unknown };@@ -51,7 +53,7 @@ function nodes(value: ReactNode): ReactElement<Props>[] {function render() {fixture.index = 0;fixture.effects = [];- return nodes(Sidebar({ open: false, onClose: () => {} }));+ return nodes(drawSidebar({ open: false, onClose: () => {} }));}const trigger = (label: string) => render().find((node) => node.type === "button" && node.props["aria-label"] === label)!;diff --git a/src/components/Sidebar.open-bot.test.ts b/src/components/Sidebar.open-bot.test.tsindex 1fe0810b5b..d1b162cfbd 100644--- a/src/components/Sidebar.open-bot.test.ts+++ b/src/components/Sidebar.open-bot.test.ts@@ -1,4 +1,4 @@-import { Children, isValidElement, type EffectCallback, type ReactElement, type ReactNode } from "react";+import { Children, isValidElement, type ComponentProps, type EffectCallback, type ReactElement, type ReactNode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { AppState, Bot } from "@/state/store";@@ -36,6 +36,7 @@ vi.mock("./DesktopCapabilities", async () => {});vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.showThreads }));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true, setAdvancedMode: () => {} }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, api: fixture.api, useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) };@@ -44,6 +45,7 @@ vi.mock("@/state/store", async (importOriginal) => {import { initialState } from "@/state/store";import { ConfirmDialog } from "./ConfirmDialog";import { ArchivedBotsPanel, BotContextMenu, Sidebar } from "./Sidebar";+const drawSidebar = (Sidebar as unknown as { type: (props: ComponentProps<typeof Sidebar>) => ReactNode }).type;const left = (id: string, extra: Partial<Bot> = {}): Bot => ({id, threadId: `${id}-left`, mainThreadId: `${id}-main`, name: id, title: "", description: "", notifications: true,@@ -101,7 +103,7 @@ describe.each([false, true])("with threads shown: %s", (shown) => {it("opens the next bot after archiving the one on screen, and the archived one again on Undo", async () => {fixture.state = { ...initialState, bots: [left("scout"), left("atlas")], selectedId: "scout", activeView: "chat" };fixture.api.mockImplementation(async (_path: string, init: RequestInit) => ({ bot: { ...left("scout"), ...JSON.parse(String(init.body)) } }));- const sidebar = () => render(() => Sidebar({ open: false, onClose: () => {} }));+ const sidebar = () => render(() => drawSidebar({ open: false, onClose: () => {} }));sidebar().find((node) => node.type === BotContextMenu)!.props.onArchive!(fixture.state.bots[0]!);sidebar().find((node) => node.type === ConfirmDialog && node.props.open)!.props.onConfirm!();await flush();diff --git a/src/components/Sidebar.plus-menu.test.ts b/src/components/Sidebar.plus-menu.test.tsindex e9821467b4..a3fe4019de 100644--- a/src/components/Sidebar.plus-menu.test.ts+++ b/src/components/Sidebar.plus-menu.test.ts@@ -34,12 +34,14 @@ vi.mock("./DesktopCapabilities", async () => {});vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancedMode: () => {} }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: original.initialState, dispatch: vi.fn() }) };});import { Sidebar } from "./Sidebar";+const drawSidebar = (Sidebar as unknown as { type: (props: import("react").ComponentProps<typeof Sidebar>) => import("react").ReactNode }).type;type Props = { children?: ReactNode; onClick?: () => void; role?: string; [key: string]: unknown };function nodes(value: ReactNode): ReactElement<Props>[] {@@ -56,7 +58,7 @@ function words(value: ReactNode): string {}function render() {fixture.index = 0;- return nodes(Sidebar({ open: true, onClose: () => {} }));+ return nodes(drawSidebar({ open: true, onClose: () => {} }));}function plusMenu(admin: boolean | null) {fixture.values = [];diff --git a/src/components/Sidebar.simple-layout.test.ts b/src/components/Sidebar.simple-layout.test.tsindex bbe871d204..cb20af90cf 100644--- a/src/components/Sidebar.simple-layout.test.ts+++ b/src/components/Sidebar.simple-layout.test.ts@@ -37,6 +37,7 @@ vi.mock("./DesktopCapabilities", async () => {});vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.advanced }));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => fixture.advanced, setAdvancedMode: () => {} }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) };@@ -46,6 +47,7 @@ import { initialState } from "@/state/store";import { BOTS_SECTION_ID, CHANNELS_SECTION_ID, PINNED_SECTION_ID, userSectionId } from "@/lib/sidebar-layout";import { SIDEBAR_COLLAPSED_SECTIONS_KEY, SIDEBAR_DENSITY_KEY, SIDEBAR_SECTION_ORDER_KEY, SIDEBAR_WIDTH_KEY, SIMPLE_SIDEBAR_SECTION_ORDER_KEY, SIMPLE_SIDEBAR_WIDTH_KEY, setSidebarDensity } from "@/lib/sidebar-preferences";import { Sidebar, TeamMenuItems } from "./Sidebar";+const drawSidebar = (Sidebar as unknown as { type: (props: import("react").ComponentProps<typeof Sidebar>) => import("react").ReactNode }).type;import { PinnedBotRoster } from "./PinnedCircleThreads";import { SidebarFooter } from "./SidebarFooter";import { SidebarResizeHandle } from "./SidebarResizeHandle";@@ -74,7 +76,7 @@ function nodes(value: ReactNode): ReactElement<Props>[] {function render(collapseToIcons = false) {fixture.index = 0;fixture.effects = [];- const root = Sidebar({ open: false, onClose: () => {}, collapseToIcons }) as ReactElement<Props>;+ const root = drawSidebar({ open: false, onClose: () => {}, collapseToIcons }) as ReactElement<Props>;return { root, tree: [root, ...nodes(root.props.children)] };}const sectionOrder = (tree: ReactElement<Props>[]) => tree.map((node) => node.props["data-sidebar-section-id"]).filter(Boolean);diff --git a/src/components/Sidebar.simple-mode.test.ts b/src/components/Sidebar.simple-mode.test.tsindex 7ae1656369..ef2202591e 100644--- a/src/components/Sidebar.simple-mode.test.ts+++ b/src/components/Sidebar.simple-mode.test.ts@@ -1,4 +1,4 @@-import { Children, createElement, isValidElement, type KeyboardEvent, type MemoExoticComponent, type MouseEvent, type ReactElement, type ReactNode } from "react";+import { Children, createElement, isValidElement, type ComponentProps, type KeyboardEvent, type MemoExoticComponent, type MouseEvent, type ReactElement, type ReactNode } from "react";import { renderToStaticMarkup } from "react-dom/server";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { initialState, type AppState, type Bot, type Group } from "@/state/store";@@ -298,7 +298,7 @@ describe("bot-first sidebar", () => {fixture.advanced = advanced;const group: Group = { id: "room", threadId: "room-thread", name: "Launch", memberIds: [bot.id], messages: [], defaultResponder: { kind: "mentions" }, bulletin: "", unread: false, createdAt: 1 };let tree: ReactNode;- function Capture() { tree = GroupListItem({ group, density, onMenu: vi.fn() }); return tree; }+ function Capture() { tree = (GroupListItem as unknown as { type: (props: ComponentProps<typeof GroupListItem>) => ReactElement }).type({ group, density, onMenu: vi.fn() }); return tree; }const markup = renderToStaticMarkup(createElement(Capture));const row = findElement(tree, "data-sidebar-group-row", group.id)!;expect(String(row.props.className).split(" ")).toEqual(expect.arrayContaining([...spacing]));diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex a765f8edb8..41271971e2 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -2,7 +2,8 @@ import { OrganizationIdentity } from "./OrganizationIdentity";import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";import { createPortal } from "react-dom";import { Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderPlus, LayoutTemplate, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, Plus, Search, SquarePen, TextQuote, Trash2, Users, X } from "lucide-react";-import { api, useStore, formatTime, visibleMessages, currentTaskBot, botOpensTo, openBot, openThread, type Action, type AppState, type Bot, type BotProject, type Group, type InstanceInfo, type Message } from "@/state/store";+import { sidebarState } from "./sidebar-state"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";+import { api, formatTime, visibleMessages, currentTaskBot, botOpensTo, openBot, openThread, type Action, type AppState, type Bot, type BotProject, type Group, type InstanceInfo, type Message } from "@/state/store";import { approvalModeFor } from "../../shared/approval-mode";import { liveActivityLabel, sidebarMessage } from "@/lib/live-activity";import { SidebarWorkingStep } from "./SidebarWorkingStep";@@ -136,7 +137,7 @@ export function openBotContextMenu(onMenu: (menu: MenuState) => void, botId: stronMenu({ botId, x: event.clientX, y: event.clientY });}-export function GroupListItem({+export const GroupListItem = memo(function GroupListItem({group,density,query = "",@@ -147,9 +148,9 @@ export function GroupListItem({query?: string;onMenu: (menu: { groupId: string; x: number; y: number }) => void;}) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch(), bots = useStoreSelector((s) => s.bots, sameDrawnBots), instances = useStoreSelector((s) => s.instances);const advanced = useAdvancedMode();- const selected = state.activeView === "chat" && state.selectedId === group.id;+ const selected = useStoreSelector((s) => s.activeView === "chat" && s.selectedId === group.id);const [threadsOpen, setThreadsOpen] = useSearchDisclosure(`group:${group.id}`, query ?? "", searchMatchesThreads(query ?? "", group.tasks), selected);const wasSelected = useRef(selected);useEffect(() => {@@ -162,7 +163,7 @@ export function GroupListItem({const railTile = !advanced && density === "icons";const roomBusy = Boolean(group.busyBotId) || Boolean(group.working);const members = group.memberIds- .map((id) => state.bots.find((b) => b.id === id))+ .map((id) => bots.find((b) => b.id === id)).filter((b): b is Bot => Boolean(b));const last = group.messages.at(-1);return (@@ -201,7 +202,7 @@ export function GroupListItem({{simpleRow && !expanded && group.unread && <RowDot />}</div>{!expanded && <div className="flex items-center justify-between gap-2">- <span className={cn("truncate text-ink-secondary", simpleRow ? "text-[13px] leading-[18px]" : "text-[11px]")}>{group.description || groupPreview(group, state.bots, state.instances, advanced)}</span>+ <span className={cn("truncate text-ink-secondary", simpleRow ? "text-[13px] leading-[18px]" : "text-[11px]")}>{group.description || groupPreview(group, bots, instances, advanced)}</span>{!simpleRow && group.unread && <span className="size-2 shrink-0 rounded-full bg-accent" />}</div>}{simpleRow && <RowStatusText unread={group.unread} />}@@ -221,7 +222,7 @@ export function GroupListItem({{expanded && <GroupThreadList group={group} selected={selected} query={group.name.toLowerCase().includes(query.toLowerCase()) ? "" : query} />}</>);-}+});function RoomContextMenu({menu,@@ -236,9 +237,9 @@ function RoomContextMenu({}) {const motion = useHeldMenuMotion(menu);const shown = motion.value;- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch(), store = useStoreRef();const remoteClient = window.ogb?.remoteClient?.active === true;- const group = shown ? state.groups.find((g) => g.id === shown.groupId) : undefined;+ const group = useStoreSelector((s) => shown ? s.groups.find((g) => g.id === shown.groupId) : undefined);const [renaming, setRenaming] = useState(false);const [describing, setDescribing] = useState(false);const [draft, setDraft] = useState(group?.name ?? "");@@ -246,8 +247,8 @@ function RoomContextMenu({useEffect(() => {if (!menu) return;- setDraft(state.groups.find((g) => g.id === menu.groupId)?.name ?? "");- setDescriptionDraft(state.groups.find((g) => g.id === menu.groupId)?.description ?? "");+ const named = store.state().groups.find((g) => g.id === menu.groupId);+ setDraft(named?.name ?? ""); setDescriptionDraft(named?.description ?? "");setRenaming(false);setDescribing(false);}, [menu]);@@ -664,8 +665,8 @@ export interface BotRowProps {botDragging?: boolean;}-export function botRowProps(- state: AppState,+export function botRowProps<State extends Pick<AppState, "activeView" | "selectedId" | "revealThread" | "deletingBots" | "mascotMotion" | "pendingQueued" | "instances" | "liveCall" | "config">>(+ state: State,dispatch: Dispatch<Action>,bot: Bot,layout: Pick<BotRowProps, "density" | "query" | "onMenu" | "renameRequest" | "botDrag" | "botDrop" | "botDragging">,@@ -919,12 +920,12 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {);});-export function Sidebar({ open, onClose, collapseToIcons = false }: {+export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons = false }: {open: boolean;onClose: () => void;collapseToIcons?: boolean;}) {- const { state, dispatch } = useStore();+ const state = useStoreSelector(sidebarState, sameFields), dispatch = useStoreDispatch();const now = useRelativeNow();const cloudOwner = useCloudOwner(state.config?.cloudHome === true);const endHowTo = useCallback(() => endCloudHowTo(dispatch), [dispatch]);@@ -1683,4 +1684,4 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {)}</aside>);-}+});diff --git a/src/components/sidebar-state.ts b/src/components/sidebar-state.tsnew file mode 100644index 0000000000..613a7b858d--- /dev/null+++ b/src/components/sidebar-state.ts@@ -0,0 +1,8 @@+import type { AppState } from "@/state/store";++/** What the sidebar list draws: a change anywhere else in the store leaves it alone. */+export const sidebarState = (s: AppState) => ({+ bots: s.bots, groups: s.groups, sections: s.sections, pendingQueued: s.pendingQueued, instances: s.instances, config: s.config, selectedId: s.selectedId,+ activeView: s.activeView, computerOpen: s.computerOpen, inspectorOpen: s.inspectorOpen, deletingBots: s.deletingBots, revealThread: s.revealThread,+ liveCall: s.liveCall, cloudHowTo: s.cloudHowTo, mascotMotion: s.activeView === "chat" && s.mascotMotion?.botId === s.selectedId ? s.mascotMotion : null,+});diff --git a/src/components/thread-approval.tsx b/src/components/thread-approval.tsxindex ad8118db3b..40772de1e2 100644--- a/src/components/thread-approval.tsx+++ b/src/components/thread-approval.tsx@@ -1,7 +1,8 @@import { useState, type ComponentProps, type ReactNode } from "react";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { useStore, type Bot } from "@/state/store";+import type { Bot } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { approvalModeFor, type ApprovalMode } from "../../shared/approval-mode";import type { ApprovalModeSelector } from "./ApprovalModeSelector";import { CommandAllowlistDialog } from "./CommandAllowlistDialog";@@ -13,13 +14,13 @@ export type ApprovalChoice = ComponentProps<typeof ApprovalModeSelector>;/** One conversation's approval level as every control offers it (the composer and the bot panel), with the dialogs a* choice can open: the warning before Auto on this computer, and the command allowlist. A remote client gets none. */export function useThreadApproval(bot: Bot | undefined): { choice: ApprovalChoice | undefined; dialogs: ReactNode } {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch(), instances = useStoreSelector((state) => state.instances);const { capabilities } = useDesktopCapabilities();const ownerOrAdmin = useOwnerOrAdmin();const remoteClient = window.ogb?.remoteClient?.active === true;const [warning, setWarning] = useState<{ botId: string; threadId: string } | null>(null);const [allowlist, setAllowlist] = useState<{ botId: string; botName: string; threadId: string } | null>(null);- const engine = bot ? state.instances.find((instance) => instance.instanceId === bot.modelSelection.instanceId) : undefined;+ const engine = bot ? instances.find((instance) => instance.instanceId === bot.modelSelection.instanceId) : undefined;const trusted = Boolean(!remoteClient && window.ogb?.approvals && capabilities.host.packaged);const onSelect = (mode: ApprovalMode) => {if (!bot || mode === approvalModeFor(bot)) return;diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.tsindex 6155f5f1a0..ba65f984b8 100644--- a/src/hooks/use-transcript-viewport.test.ts+++ b/src/hooks/use-transcript-viewport.test.ts@@ -77,6 +77,7 @@ const store = vi.hoisted(() => ({},dispatch: (() => {}) as (action: unknown) => void,}));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", () => ({ useStore: () => store }));// Scrolling a hit into view needs the real DOM; this suite checks the window around it.vi.mock("@/lib/focus-message", () => ({ useFocusMessage: () => {} }));diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.tsindex ce5f2e8adc..dd6b1bb6ee 100644--- a/src/hooks/use-transcript-viewport.ts+++ b/src/hooks/use-transcript-viewport.ts@@ -21,7 +21,7 @@ import {tailWindowStart,} from "@/lib/transcript-window";import { reducedMotion } from "@/lib/onboarding";-import { useStore } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";export const AUTO_EXPAND_TOP_THRESHOLD = 250;@@ -42,7 +42,9 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({transcriptShown?: boolean;hasMore?: boolean;}) {- const { state, dispatch } = useStore();+ const focusMessage = useStoreSelector((state) => state.focusMessage);+ const olderPending = useStoreSelector((state) => Boolean(state.loadingOlder[threadId]));+ const dispatch = useStoreDispatch();const scrollRef = useRef<HTMLDivElement>(null);const transcriptRef = useRef<HTMLDivElement>(null);const topSentinelRef = useRef<HTMLDivElement>(null);@@ -94,7 +96,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({const appliedFocus = useRef<number | null>(null);useEffect(() => {- const focus = state.focusMessage;+ const focus = focusMessage;if (!focus || focus.consumed || focus.threadId !== threadId || appliedFocus.current === focus.nonce) return;const targetIndex = messages.findIndex((message) => message.id === focus.messageId);if (targetIndex < 0) return;@@ -102,7 +104,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({const range = focusWindowRange(messages.length, targetIndex);setBottomFollow(false);setTranscriptWindow({ key: transcriptKey, start: range.start, end: range.end });- }, [threadId, messages, setBottomFollow, state.focusMessage, transcriptKey]);+ }, [threadId, messages, setBottomFollow, focusMessage, transcriptKey]);useFocusMessage(threadId, messages.length > 0);// `follow` is omitted on purpose: re-arming only arms future content and never scrolls.@@ -150,7 +152,6 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({const nextEnd = Math.min(messages.length, endIndex + TRANSCRIPT_WINDOW_SIZE);setTranscriptWindow((w) => ({ ...w, end: nextEnd >= messages.length ? null : nextEnd }));};- const olderPending = Boolean(state.loadingOlder[threadId]);const loadOlder = () => {holdRowForPrepend();dispatch({ type: "loadOlderMessages", threadId });diff --git a/src/hooks/use-unread-divider.ts b/src/hooks/use-unread-divider.tsindex 86f0929a6a..2f1c61df60 100644--- a/src/hooks/use-unread-divider.ts+++ b/src/hooks/use-unread-divider.ts@@ -1,15 +1,15 @@import { useEffect, useMemo, useRef, useState } from "react";import { peerLine } from "@/lib/peer-message";import { UNREAD_DIVIDER_FADE_MS, UNREAD_DIVIDER_LINGER_MS } from "@/lib/unread-divider";-import { useStore, type Message } from "@/state/store";+import type { Message } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";export function useUnreadDivider({ threadId, messages, following }: {threadId: string;messages: readonly Message[];following: boolean;}): { messageId: string | null; fading: boolean } {- const { state, dispatch } = useStore();- const divider = state.unreadDivider;+ const divider = useStoreSelector((state) => state.unreadDivider), dispatch = useStoreDispatch();const messageId = divider && divider.threadId === threadId ? divider.messageId : null;const newestOwnId = useMemo(() => {for (let i = messages.length - 1; i >= 0; i--) {diff --git a/src/lib/drawn-bots.test.ts b/src/lib/drawn-bots.test.tsnew file mode 100644index 0000000000..4a4d70b57d--- /dev/null+++ b/src/lib/drawn-bots.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import type { Bot } from "@/state/store";+import { sameDrawnBots } from "./drawn-bots";++const bot = (fields: Partial<Bot> = {}): Bot => ({+ id: "bot", threadId: "thread", name: "Fixture", title: "Writer", description: "", notifications: true,+ unread: false, color: "green", messages: [], ...fields,+} as Bot);++describe("sameDrawnBots", () => {+ it("keeps the list when only what readers do not draw changed", () => {+ expect(sameDrawnBots([bot()], [bot({ unread: true, messages: [{ id: "m" } as Bot["messages"][number]] })])).toBe(true);+ });++ it("draws again when the name or look changed", () => {+ expect(sameDrawnBots([bot()], [bot({ name: "Renamed" })])).toBe(false);+ expect(sameDrawnBots([bot()], [bot({ color: "blue" })])).toBe(false);+ });++ it("draws again when the title or chief-of-staff mark changed, which the @-mention menu shows", () => {+ expect(sameDrawnBots([bot()], [bot({ title: "Editor" })])).toBe(false);+ expect(sameDrawnBots([bot({ title: "" })], [bot({ title: "", chiefOfStaff: true })])).toBe(false);+ });++ it("draws again when a bot was added or removed", () => {+ expect(sameDrawnBots([bot()], [bot(), bot({ id: "other" })])).toBe(false);+ });+});diff --git a/src/lib/drawn-bots.ts b/src/lib/drawn-bots.tsnew file mode 100644index 0000000000..2d17e6eeaa--- /dev/null+++ b/src/lib/drawn-bots.ts@@ -0,0 +1,13 @@+import type { Bot } from "@/state/store";++const drawn = (bot: Bot) => [+ // title and chiefOfStaff: the @-mention menu describes each bot by them.+ bot.id, bot.name, bot.title, bot.chiefOfStaff, bot.hidden, bot.sidebarHidden, JSON.stringify(bot.defaultBot ?? null), bot.color, bot.mascotBody, bot.mascotExpression,+ bot.mascotFaceColor, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY,+].join("\u0001");++/** 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]!));+}diff --git a/src/lib/focus-message.test.ts b/src/lib/focus-message.test.tsindex 44d1d2726e..b97baf630d 100644--- a/src/lib/focus-message.test.ts+++ b/src/lib/focus-message.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const fixture = vi.hoisted(() => ({ effect: null as EffectCallback | null, text: "", dispatch: vi.fn() }));vi.mock("react", () => ({ useEffect: (effect: EffectCallback) => { fixture.effect = effect; } }));+vi.mock("@/state/store-select", async () => (await import("@/testing/plain-store-select")).plainStoreSelect());vi.mock("@/state/store", () => ({api: vi.fn(),useStore: () => ({ state: { focusMessage: { threadId: "thread", messageId: "message", matchText: fixture.text, nonce: 1, consumed: false } }, dispatch: fixture.dispatch }),diff --git a/src/lib/focus-message.ts b/src/lib/focus-message.tsindex 1dcb50f1dc..58d35a029b 100644--- a/src/lib/focus-message.ts+++ b/src/lib/focus-message.ts@@ -1,6 +1,7 @@// Rows are `display: contents` wrappers with no box, so their last child is what gets scrolled and highlighted.import { useEffect } from "react";-import { api, MESSAGE_PAGE_SIZE, useStore, type Action, type AppState, type Message } from "@/state/store";+import { api, MESSAGE_PAGE_SIZE, type Action, type AppState, type Message } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import type { SearchHit } from "@/lib/search-hit";import { t } from "@/lib/i18n";@@ -100,8 +101,7 @@ function matchRange(root: HTMLElement, text: string): Range | null {}export function useFocusMessage(threadId: string, ready: boolean) {- const { state, dispatch } = useStore();- const focus = state.focusMessage;+ const focus = useStoreSelector((state) => state.focusMessage), dispatch = useStoreDispatch();useEffect(() => {if (!focus || focus.consumed || focus.threadId !== threadId || !ready) return;let tries = 0;diff --git a/src/lib/use-composer-dictation.ts b/src/lib/use-composer-dictation.tsindex 3601b698e5..1320daaf5b 100644--- a/src/lib/use-composer-dictation.ts+++ b/src/lib/use-composer-dictation.ts@@ -1,7 +1,7 @@import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";import { useDesktopCapabilities } from "@/components/DesktopCapabilities";import { withOpenSettings } from "@/components/OpenSystemSettings";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { t } from "./i18n";import { fishSpeech } from "./fish-speech";import { listensHere, speechBridge } from "./speech";@@ -12,7 +12,7 @@ export function useComposerDictation({ draftId, text, onText }: {onText: (text: string) => void;}) {const { capabilities } = useDesktopCapabilities();- const ready = listensHere(capabilities, useStore().state.config);+ const ready = listensHere(capabilities, useStoreSelector((state) => state.config));const [recording, setRecording] = useState(false);const [speechError, setSpeechError] = useState<ReactNode>(null);const draft = useRef({ id: draftId, text });diff --git a/src/state/app-store.test.ts b/src/state/app-store.test.tsnew file mode 100644index 0000000000..839538865f--- /dev/null+++ b/src/state/app-store.test.ts@@ -0,0 +1,146 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { createAppStore, nextPaint, type FrameSchedule } from "./app-store";++type Action = { type: "frame" | "action"; id: string };++function fixture() {+ const scheduled: Array<() => void> = [];+ const schedule: FrameSchedule = (flush) => {+ scheduled.push(flush);+ return () => { scheduled.splice(scheduled.indexOf(flush), 1); };+ };+ const store = createAppStore<string[], Action, string>((state, action) => [...state, `${action.type}:${action.id}`], [], schedule);+ const notified = vi.fn();+ store.subscribe(notified);+ const handled: string[] = [];+ const stop = store.handleFrames((frame) => {+ handled.push(frame);+ store.dispatch({ type: "frame", id: frame });+ });+ const paint = () => { for (const flush of scheduled.splice(0)) flush(); };+ return { store, notified, handled, stop, paint, scheduled };+}++afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++describe("live frames reach the store once per paint", () => {+ it("applies every queued frame in arrival order at the next paint, as one change", () => {+ const { store, notified, paint, scheduled } = fixture();+ store.enqueueFrame("a");+ store.enqueueFrame("b");+ store.enqueueFrame("c");+ expect(store.getState()).toEqual([]);+ expect(scheduled).toHaveLength(1);+ paint();+ expect(store.getState()).toEqual(["frame:a", "frame:b", "frame:c"]);+ expect(notified).toHaveBeenCalledTimes(1);+ });++ it("applies queued frames before an action that arrives after them", () => {+ const { store, notified, scheduled } = fixture();+ store.enqueueFrame("a");+ store.enqueueFrame("b");+ store.dispatch({ type: "action", id: "1" });+ expect(store.getState()).toEqual(["frame:a", "frame:b", "action:1"]);+ expect(scheduled, "the paint it waited for is cancelled").toHaveLength(0);+ expect(notified).toHaveBeenCalledTimes(2);+ });++ it("flushes on demand, so a reader sees every frame that came before it", () => {+ const { store, paint } = fixture();+ store.enqueueFrame("a");+ store.flushFrames();+ expect(store.getState()).toEqual(["frame:a"]);+ paint();+ expect(store.getState()).toEqual(["frame:a"]);+ });++ it("applies an urgent frame now, after the frames queued before it", () => {+ const { store, notified, scheduled } = fixture();+ store.enqueueFrame("a");+ store.enqueueFrame("call", true);+ expect(store.getState()).toEqual(["frame:a", "frame:call"]);+ expect(scheduled).toHaveLength(0);+ expect(notified).toHaveBeenCalledTimes(1);+ });++ it("keeps applying the frames after one that throws", async () => {+ const thrown: unknown[] = [];+ const store = createAppStore<string[], string, string>((state, action) => [...state, action], [], (flush) => { flush(); return () => {}; });+ store.handleFrames((frame) => {+ if (frame === "bad") throw new Error("bad frame");+ store.dispatch(frame);+ });+ const onError = (error: unknown) => { thrown.push(error); };+ process.on("uncaughtException", onError);+ try {+ store.enqueueFrame("bad");+ store.enqueueFrame("good");+ await new Promise((resolve) => setTimeout(resolve, 0));+ } finally {+ process.off("uncaughtException", onError);+ }+ expect(store.getState()).toEqual(["good"]);+ expect(thrown).toEqual([new Error("bad frame")]);+ });++ it("does not tell subscribers about a frame that changed nothing", () => {+ const store = createAppStore<number, number, number>((state, action) => Math.max(state, action), 5, (flush) => { flush(); return () => {}; });+ const notified = vi.fn();+ store.subscribe(notified);+ store.handleFrames((frame) => store.dispatch(frame));+ store.enqueueFrame(3);+ expect(notified).not.toHaveBeenCalled();+ store.enqueueFrame(7);+ expect(notified).toHaveBeenCalledTimes(1);+ });++ it("drops the queue once its handler stops", () => {+ const { store, stop, paint, scheduled } = fixture();+ store.enqueueFrame("a");+ stop();+ expect(scheduled).toHaveLength(0);+ paint();+ store.dispatch({ type: "action", id: "1" });+ expect(store.getState()).toEqual(["action:1"]);+ });+});++describe("the next paint", () => {+ it("is the next animation frame while the window shows", () => {+ vi.useFakeTimers();+ let frame: FrameRequestCallback | undefined;+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frame = callback; return 1; });+ vi.stubGlobal("cancelAnimationFrame", () => { frame = undefined; });+ const flush = vi.fn();+ nextPaint(flush);+ frame!(0);+ expect(flush).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(1_000);+ expect(flush, "the fallback timer is cleared").toHaveBeenCalledTimes(1);+ });++ it("falls back to a timer when no animation frame comes, as in a hidden window", () => {+ vi.useFakeTimers();+ const cancelled = vi.fn();+ vi.stubGlobal("requestAnimationFrame", () => 7);+ vi.stubGlobal("cancelAnimationFrame", cancelled);+ const flush = vi.fn();+ nextPaint(flush);+ vi.advanceTimersByTime(99);+ expect(flush).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(flush).toHaveBeenCalledTimes(1);+ expect(cancelled).toHaveBeenCalledWith(7);+ });++ it("can be cancelled", () => {+ vi.useFakeTimers();+ vi.stubGlobal("requestAnimationFrame", () => 1);+ vi.stubGlobal("cancelAnimationFrame", () => {});+ const flush = vi.fn();+ nextPaint(flush)();+ vi.advanceTimersByTime(1_000);+ expect(flush).not.toHaveBeenCalled();+ });+});diff --git a/src/state/app-store.ts b/src/state/app-store.tsnew file mode 100644index 0000000000..4d4a435782--- /dev/null+++ b/src/state/app-store.ts@@ -0,0 +1,118 @@+import { flushSync } from "react-dom";++/** Runs `flush` once, at the next animation frame or after `fallbackMs` when no frame comes (a hidden window). */+export type FrameSchedule = (flush: () => void) => () => void;++/** Chromium pauses animation frames in a hidden window; the timer still runs there, throttled. */+const HIDDEN_WINDOW_FALLBACK_MS = 100;++export const nextPaint: FrameSchedule = (flush) => {+ let frame: number | null = null;+ const timer = setTimeout(run, HIDDEN_WINDOW_FALLBACK_MS);+ if (typeof requestAnimationFrame === "function") frame = requestAnimationFrame(run);+ function cancel() {+ clearTimeout(timer);+ if (frame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame);+ }+ function run() {+ cancel();+ flush();+ }+ return cancel;+};++export interface AppStore<State, Action, Frame> {+ getState(): State;+ /** Applies every queued frame first, so actions and frames reach the reducer in the order they arrived. */+ dispatch(action: Action): void;+ subscribe(listener: () => void): () => void;+ /** Queues a live frame for the next paint. An urgent frame is applied and rendered now, after every frame queued+ * before it. */+ enqueueFrame(frame: Frame, urgent?: boolean): void;+ /** Applies the queued frames now, in order, as one change to subscribers. */+ flushFrames(): void;+ /** Sets what applies a frame; the returned stop drops the queue. */+ handleFrames(handler: (frame: Frame) => void): () => void;+}++export function createAppStore<State, Action, Frame>(+ reducer: (state: State, action: Action) => State,+ initial: State,+ schedule: FrameSchedule = nextPaint,+): AppStore<State, Action, Frame> {+ let state = initial;+ const listeners = new Set<() => void>();+ let held = 0;+ let changedWhileHeld = false;+ let queue: Frame[] = [];+ let handler: ((frame: Frame) => void) | null = null;+ let cancelScheduled: (() => void) | null = null;++ const notify = () => {+ if (held > 0) {+ changedWhileHeld = true;+ return;+ }+ for (const listener of listeners) listener();+ };+ const flushFrames = () => {+ cancelScheduled?.();+ cancelScheduled = null;+ const apply = handler;+ if (!apply || queue.length === 0) return;+ const frames = queue;+ queue = [];+ held++;+ try {+ for (const frame of frames) {+ try {+ apply(frame);+ } catch (error) {+ // One bad frame must not drop the frames after it, as it could not when each frame had its own task.+ queueMicrotask(() => { throw error; });+ }+ }+ } finally {+ held--;+ if (held === 0 && changedWhileHeld) {+ changedWhileHeld = false;+ notify();+ }+ }+ };++ return {+ getState: () => state,+ dispatch(action) {+ flushFrames();+ const next = reducer(state, action);+ if (Object.is(next, state)) return;+ state = next;+ notify();+ },+ subscribe(listener) {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+ },+ enqueueFrame(frame, urgent = false) {+ queue.push(frame);+ if (urgent) flushSync(flushFrames);+ else if (!cancelScheduled) {+ let ran = false;+ const cancel = schedule(() => { ran = true; flushFrames(); });+ if (!ran) cancelScheduled = cancel;+ }+ },+ flushFrames,+ handleFrames(next) {+ handler = next;+ return () => {+ if (handler !== next) return;+ handler = null;+ queue = [];+ cancelScheduled?.();+ cancelScheduled = null;+ };+ },+ };+}diff --git a/src/state/bot-read.test.ts b/src/state/bot-read.test.tsnew file mode 100644index 0000000000..54dca7df72--- /dev/null+++ b/src/state/bot-read.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it, vi } from "vitest";+import { NO_SUCH_BOT } from "../../shared/bot-read";+import { ApiError } from "./api";+import { readOneBot } from "./bot-read";+import type { BotAnnouncement } from "./store";++const bot = (id: string) => ({ id, threadId: `${id}-thread`, name: id }) as BotAnnouncement;++describe("reading one bot to reconcile it", () => {+ it("asks for that bot alone", async () => {+ const read = vi.fn(async (_path: string) => ({ bot: bot("scout") }) as never);+ expect(await readOneBot("scout", 200, undefined, read)).toEqual(bot("scout"));+ expect(read.mock.calls.map(([path]) => path)).toEqual(["/api/bots/scout?messages=200"]);+ });++ it("answers null for a bot the server no longer has, without reading every bot", async () => {+ const read = vi.fn(async () => { throw new ApiError(NO_SUCH_BOT, 404, { error: NO_SUCH_BOT }); });+ expect(await readOneBot("gone", 200, undefined, read)).toBeNull();+ expect(read).toHaveBeenCalledTimes(1);+ });++ it("reads the list from a server without the one-bot read", async () => {+ const read = vi.fn(async (path: string) => {+ if (path.startsWith("/api/bots/")) throw new ApiError("not found", 404, { error: "not found" });+ return { bots: [bot("other"), bot("scout")] } as never;+ });+ expect(await readOneBot("scout", 200, undefined, read)).toEqual(bot("scout"));+ expect(read.mock.calls.map(([path]) => path)).toEqual(["/api/bots/scout?messages=200", "/api/bots?messages=200"]);+ });++ it("passes any other failure on", async () => {+ const read = vi.fn(async () => { throw new ApiError("offline", 503); });+ await expect(readOneBot("scout", 200, undefined, read)).rejects.toThrow("offline");+ expect(read).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/state/bot-read.ts b/src/state/bot-read.tsnew file mode 100644index 0000000000..92bc498f70--- /dev/null+++ b/src/state/bot-read.ts@@ -0,0 +1,18 @@+import { api, ApiError } from "./api";+import type { BotAnnouncement } from "./store";+import { NO_SUCH_BOT } from "../../shared/bot-read";++type Read = <T>(path: string, init?: { signal?: AbortSignal }) => Promise<T>;++/** One bot as the server holds it, with its newest `messages` in the shown conversation; null when it is gone. */+export async function readOneBot(botId: string, messages: number, signal?: AbortSignal, read: Read = api): Promise<BotAnnouncement | null> {+ try {+ const { bot } = await read<{ bot?: BotAnnouncement }>(`/api/bots/${encodeURIComponent(botId)}?messages=${messages}`, { signal });+ return bot ?? null;+ } catch (error) {+ if (!(error instanceof ApiError) || error.status !== 404) throw error;+ if (error.body?.error === NO_SUCH_BOT) return null;+ }+ const { bots } = await read<{ bots: BotAnnouncement[] }>(`/api/bots?messages=${messages}`, { signal });+ return bots.find((candidate) => candidate.id === botId) ?? null;+}diff --git a/src/state/frame-batching.test.ts b/src/state/frame-batching.test.tsnew file mode 100644index 0000000000..80da8553aa--- /dev/null+++ b/src/state/frame-batching.test.ts@@ -0,0 +1,113 @@+// @vitest-environment happy-dom+// The real provider and its live stream; animation frames run only when a test paints.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { LiveCallState, ServerFrame } from "../../shared/wire";+import type { Action, AppState, BotAnnouncement, Message } from "./store";++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 bot: BotAnnouncement = {+ id: "bot", threadId: "thread", name: "Fixture", title: "", description: "",+ notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "fake", model: "m" },+ tasks: [{ threadId: "thread", title: "Thread", createdAt: 1, approvalMode: "ask" }],+};+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const answers: Record<string, unknown> = {+ "/api/instances": { instances: [] },+ "/api/config": {},+ "/api/routines": { routines: [], runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] },+};++const paints: FrameRequestCallback[] = [];+let painting = false;+const { StoreProvider, useStore } = await import("./store");++let renders = 0;+let seen!: AppState;+let dispatch!: (action: Action) => void;+function Probe() {+ ({ state: seen, dispatch } = useStore());+ renders++;+ return null;+}+let root: Root;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 5; i++) await task(); };+const paint = async () => {+ painting = true;+ for (const callback of paints.splice(0)) callback(performance.now());+ painting = false;+ await settle();+};+const stream = () => FixtureEventSource.opened[0]!;+let cursor = 0;+const message = (id: string): Message => ({ id, at: cursor, role: "bot", kind: "text", text: id } as Message);+const frame = (id: string): ServerFrame => ({ kind: "message", threadId: "thread", message: message(id) } as ServerFrame);+const ids = () => seen.bots.find((candidate) => candidate.id === "bot")!.messages.map((one) => one.id);++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => paints.push(callback));+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { if (!painting) paints.splice(id - 1, 1, () => {}); });+ vi.stubGlobal("fetch", (path: string) => path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? {}));+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ await settle();+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ await paint();+});+afterAll(() => {+ root.unmount();+ vi.unstubAllGlobals();+});+beforeEach(async () => {+ await paint();+});++describe("live frames reach the screen once per paint", () => {+ it("draws a burst of frames that arrived in separate tasks in one render, in arrival order", async () => {+ const before = renders;+ const start = ids().length;+ for (let i = 0; i < 10; i++) {+ stream().send(frame(`burst-${i}`), `run:${++cursor}`);+ await task();+ }+ expect(renders, "nothing renders before the paint").toBe(before);+ await paint();+ expect(renders).toBe(before + 1);+ expect(ids().slice(start)).toEqual(Array.from({ length: 10 }, (_, i) => `burst-${i}`));+ });++ it("applies frames that arrived before an action ahead of it", async () => {+ const start = ids().length;+ stream().send(frame("from-stream"), `run:${++cursor}`);+ await task();+ flushSync(() => dispatch({ type: "messageAdded", threadId: "thread", message: message("from-action") }));+ expect(ids().slice(start)).toEqual(["from-stream", "from-action"]);+ });++ it("draws a live call at once, with every frame queued before it", () => {+ const start = ids().length;+ const call = { callId: "c1", botId: "bot", threadId: "thread", client: "desktop", voice: "vo", startedAt: 1, status: "live" } as LiveCallState;+ stream().send(frame("before-call"), `run:${++cursor}`);+ stream().send({ kind: "live.call", botId: "bot", threadId: "thread", call }, `run:${++cursor}`);+ expect(seen.liveCall).toEqual(call);+ expect(ids().slice(start)).toEqual(["before-call"]);+ });+});diff --git a/src/state/older-routine-runs.ts b/src/state/older-routine-runs.tsindex 6f77051664..99a17868f7 100644--- a/src/state/older-routine-runs.ts+++ b/src/state/older-routine-runs.ts@@ -1,12 +1,12 @@import { useEffect } from "react";import type { RoutineRun } from "@/lib/routines";-import { api, useStore } from "./store";+import { api } from "./store";+import { useStoreDispatch, useStoreSelector } from "./store-select";/** Loads the runs scheduled from `start` up to where the app's window begins, once a view shows dates before it. */export function useRoutineRunsFrom(start: number): void {- const { state, dispatch } = useStore();- const since = state.routineRunsSince;+ const since = useStoreSelector((state) => state.routineRunsSince), dispatch = useStoreDispatch();useEffect(() => {if (since === null || start >= since) return;let live = true;@@ -19,10 +19,10 @@ export function useRoutineRunsFrom(start: number): void {/** The run that worked in this conversation; one older than the app's window is loaded when the thread is a run's. */export function useThreadRoutineRun(botId: string, threadId: string): RoutineRun | undefined {- const { state, dispatch } = useStore();- const run = state.routineRuns.find((candidate) => candidate.target === "bot" && candidate.botId === botId && candidate.threadId === threadId);- const marked = state.bots.find((bot) => bot.id === botId)?.tasks?.some((task) => task.threadId === threadId && task.routineRunId);- const missing = !run && Boolean(marked) && state.routineRunsSince !== null;+ const dispatch = useStoreDispatch();+ const run = useStoreSelector((state) => state.routineRuns.find((candidate) => candidate.target === "bot" && candidate.botId === botId && candidate.threadId === threadId));+ const missing = useStoreSelector((state) => !run && state.routineRunsSince !== null &&+ Boolean(state.bots.find((bot) => bot.id === botId)?.tasks?.some((task) => task.threadId === threadId && task.routineRunId)));useEffect(() => {if (!missing) return;let live = true;diff --git a/src/state/read-in-flight.test.ts b/src/state/read-in-flight.test.tsnew file mode 100644index 0000000000..e30e9b8aee--- /dev/null+++ b/src/state/read-in-flight.test.ts@@ -0,0 +1,129 @@+// @vitest-environment happy-dom+// A chat watched to the end ends read on the server too: unread frames that arrive while a read is in flight ask for+// exactly one more read once it finishes.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { ServerFrame } from "../../shared/wire";+import type { Action, AppState, BotAnnouncement } from "./store";++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 bot: BotAnnouncement = {+ id: "bot", threadId: "thread", name: "Fixture", title: "", description: "",+ notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "fake", model: "m" },+ tasks: [{ threadId: "thread", title: "Thread", createdAt: 1, approvalMode: "ask" }],+};+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const answers: Record<string, unknown> = {+ "/api/instances": { instances: [] },+ "/api/config": {},+ "/api/routines": { routines: [], runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] },+};+const reads: Array<{ body: unknown; answer: () => void; fail: () => void }> = [];++const { StoreProvider, useStore } = await import("./store");++let seen!: AppState;+let dispatch!: (action: Action) => void;+function Probe() {+ ({ state: seen, dispatch } = useStore());+ return null;+}+let root: Root;+let cursor = 0;+const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0)); };+const stream = () => FixtureEventSource.opened.at(-1)!;+const unreadFrame = (): ServerFrame => ({+ kind: "bot",+ bot: { ...bot, unread: true, tasks: [{ ...bot.tasks![0]!, unread: true }] },+} as ServerFrame);+// Each frame is applied before the next arrives, as when they come in separate paints.+const sendUnread = () => {+ stream().send(unreadFrame(), `run:${++cursor}`);+ flushSync(() => dispatch({ type: "connected", value: true }));+};++beforeAll(async () => {+ vi.spyOn(document, "hasFocus").mockImplementation(() => true);+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {+ if (path === "/api/bots/bot/read") {+ return new Promise<Response>((resolve, reject) => {+ reads.push({ body: JSON.parse(String(init?.body)), answer: () => resolve(new Response("{}")), fail: () => reject(new Error("offline")) });+ });+ }+ return path.startsWith("/api/bots?") ? json({ bots: [bot], groups: [] }) : json(answers[path.replace(/\?since=[^&]*$/, "")] ?? { ok: true });+ });+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ await settle();+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "select", id: "bot" }));+ await settle();+});+afterAll(() => {+ root.unmount();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("marking the shown chat read while a read is in flight", () => {+ it("sends one more read after the first finishes, however many unread frames came meanwhile", async () => {+ expect(seen.selectedId).toBe("bot");+ expect(seen.activeView).toBe("chat");++ sendUnread();+ expect(reads.map((read) => read.body)).toEqual([{ threadId: "thread" }]);++ sendUnread();+ sendUnread();+ await settle();+ expect(reads, "nothing more is sent while the first read is open").toHaveLength(1);+ expect(seen.bots[0]!.tasks![0]!.unread, "the screen shows the chat read").toBeFalsy();++ reads[0]!.answer();+ await settle();+ expect(reads.map((read) => read.body)).toEqual([{ threadId: "thread" }, { threadId: "thread" }]);++ reads[1]!.answer();+ await settle();+ expect(reads, "one follow-up, not one per frame").toHaveLength(2);+ });++ it("sends the follow-up after a read that failed, too", async () => {+ const start = reads.length;+ sendUnread();+ sendUnread();+ expect(reads).toHaveLength(start + 1);+ reads[start]!.fail();+ await settle();+ expect(reads).toHaveLength(start + 2);+ reads[start + 1]!.answer();+ await settle();+ expect(reads).toHaveLength(start + 2);+ });++ it("sends no follow-up when no unread frame came while the read was open", async () => {+ const start = reads.length;+ sendUnread();+ expect(reads).toHaveLength(start + 1);+ reads[start]!.answer();+ await settle();+ expect(reads).toHaveLength(start + 1);+ });+});diff --git a/src/state/stop-turn-store.test.ts b/src/state/stop-turn-store.test.tsindex f98f5ae8b2..1d43437ea3 100644--- a/src/state/stop-turn-store.test.ts+++ b/src/state/stop-turn-store.test.ts@@ -86,4 +86,21 @@ describe("Stop in the store", () => {await settle();expect(stops().at(-1)).toEqual({ threadId: "thread" });});++ it("does not bring back a turn whose frame was still waiting for a paint when the stream restarted", async () => {+ now += 5_000;+ // Sent together: the turn's frame is queued for the next paint when the restart arrives.+ stream().send({ kind: "runtime", event: { eventId: "e2", provider: "fake", threadId: "thread", turnId: "turn-2", createdAt: "", type: "turn.started" } } satisfies ServerFrame, `run:${++cursor}`);+ stream().send({ kind: "hello", resumed: false, cursor: "run:90" });+ await settle();+ dispatch({ type: "interrupt", botId: "bot", threadId: "thread" });+ await settle();+ expect(stops().at(-1)).toEqual({ threadId: "thread" });++ now += 5_000;+ await send({ kind: "runtime", event: { eventId: "e3", provider: "fake", threadId: "thread", turnId: "turn-3", createdAt: "", type: "turn.started" } } satisfies ServerFrame);+ dispatch({ type: "interrupt", botId: "bot", threadId: "thread" });+ await settle();+ expect(stops().at(-1)).toEqual({ threadId: "thread", turnId: "turn-3" });+ });});diff --git a/src/state/store-context.ts b/src/state/store-context.tsnew file mode 100644index 0000000000..652b51ee49--- /dev/null+++ b/src/state/store-context.ts@@ -0,0 +1,23 @@+import { createContext, type Dispatch } from "react";+import type { Action, AppState, BotAnnouncement } from "./store";++export interface StoreActions {+ dispatch: Dispatch<Action>;+ flushBotPatches: (botId: string) => Promise<BotAnnouncement | null>;+ refreshInstances: (options?: { reportErrors?: boolean; cached?: boolean }) => Promise<void>;+ refreshModels: (instanceId: string) => Promise<void>;+}++export interface StoreValue extends StoreActions {+ state: AppState;+}++/** The app store for useSyncExternalStore: the value never changes, `getState` is the newest state. */+export interface StoreSource extends StoreActions {+ getState(): AppState;+ subscribe(listener: () => void): () => void;+}++export const StoreContext = createContext<StoreValue | null>(null);++export const StoreSourceContext = createContext<StoreSource | null>(null);diff --git a/src/state/store-select.test.ts b/src/state/store-select.test.tsnew file mode 100644index 0000000000..7e121a4be3--- /dev/null+++ b/src/state/store-select.test.ts@@ -0,0 +1,131 @@+// @vitest-environment happy-dom+import { createElement, type ReactNode } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { createAppStore } from "./app-store";+import { initialState, reducer, type Action, type AppState, type Bot } from "./store";+import { StoreContext, StoreSourceContext, type StoreSource, type StoreValue } from "./store-context";+import { sameFields, sameItems, useStoreActions, useStoreSelector } from "./store-select";++const bot = (id: string, name = id): Bot => ({+ id, threadId: `${id}-thread`, name, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "fake", model: "m" }, messages: [],+} as unknown as Bot);++function storeWith(state: Partial<AppState>) {+ const store = createAppStore<AppState, Action, never>(reducer, { ...initialState, ...state }, (flush) => { flush(); return () => {}; });+ const source: StoreSource = {+ getState: store.getState, subscribe: store.subscribe, dispatch: store.dispatch,+ flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),+ };+ return { store, source };+}++let root: Root | null = null;+function mount(source: StoreSource, child: ReactNode) {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root!.render(createElement(StoreSourceContext, { value: source }, child)));+}+const act = (fn: () => void) => flushSync(fn);+afterEach(() => { flushSync(() => root?.unmount()); root = null; });++describe("useStoreSelector", () => {+ it("renders again only when its slice changes", () => {+ const { store, source } = storeWith({ bots: [bot("a"), bot("b")], connected: true });+ const names: string[] = [];+ function Name({ id }: { id: string }) {+ names.push(useStoreSelector((state) => state.bots.find((candidate) => candidate.id === id)?.name ?? ""));+ return null;+ }+ mount(source, createElement(Name, { id: "b" }));+ expect(names).toEqual(["b"]);+ act(() => store.dispatch({ type: "botPatched", bot: { ...bot("a"), name: "renamed a" } }));+ act(() => store.dispatch({ type: "connected", value: false }));+ expect(names, "a change to another bot or another field draws nothing").toEqual(["b"]);+ act(() => store.dispatch({ type: "botPatched", bot: { ...bot("b"), name: "renamed b" } }));+ expect(names).toEqual(["b", "renamed b"]);+ });++ it("keeps the earlier value while `equal` says it is the same", () => {+ const { store, source } = storeWith({ bots: [bot("a"), bot("b")] });+ const seen: Array<readonly string[]> = [];+ function Ids() {+ seen.push(useStoreSelector((state) => state.bots.map((candidate) => candidate.id), sameItems));+ return null;+ }+ mount(source, createElement(Ids));+ act(() => store.dispatch({ type: "botPatched", bot: { ...bot("a"), name: "renamed" } }));+ expect(seen).toHaveLength(1);+ act(() => store.dispatch({ type: "botsOrdered", botIds: ["b", "a"] }));+ expect(seen.map((ids) => [...ids])).toEqual([["a", "b"], ["b", "a"]]);+ });++ it("without `equal`, a new object each read is a change", () => {+ const { store, source } = storeWith({ bots: [bot("a")] });+ let renders = 0;+ function Ids() {+ useStoreSelector((state) => state.bots.map((candidate) => candidate.id));+ renders++;+ return null;+ }+ mount(source, createElement(Ids));+ act(() => store.dispatch({ type: "connected", value: !store.getState().connected }));+ expect(renders).toBe(2);+ });++ it("reads anew when its selector names another slice", () => {+ const { source } = storeWith({ bots: [bot("a", "Ada"), bot("b", "Bea")] });+ const names: string[] = [];+ function Name({ id }: { id: string }) {+ names.push(useStoreSelector((state) => state.bots.find((candidate) => candidate.id === id)!.name));+ return null;+ }+ mount(source, createElement(Name, { id: "a" }));+ flushSync(() => root!.render(createElement(StoreSourceContext, { value: source }, createElement(Name, { id: "b" }))));+ expect(names).toEqual(["Ada", "Bea"]);+ });++ it("compares a record of slices field by field", () => {+ expect(sameFields({ a: 1, b: "x" }, { a: 1, b: "x" })).toBe(true);+ expect(sameFields({ a: 1, b: "x" }, { a: 1, b: "y" })).toBe(false);+ expect(sameFields({ a: 1 } as Record<string, number>, { a: 1, b: 2 })).toBe(false);+ expect(sameItems([1, 2], [1, 2])).toBe(true);+ expect(sameItems([1, 2], [2, 1])).toBe(false);+ expect(sameItems([1], [1, 2])).toBe(false);+ });++ it("follows a store given as a plain value, as a preview or a bot editor gives it", () => {+ const value = (connected: boolean): StoreValue => ({+ state: { ...initialState, connected }, dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),+ });+ const seen: boolean[] = [];+ function Connected() {+ seen.push(useStoreSelector((state) => state.connected));+ return null;+ }+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root!.render(createElement(StoreContext.Provider, { value: value(false) }, createElement(Connected))));+ flushSync(() => root!.render(createElement(StoreContext.Provider, { value: value(true) }, createElement(Connected))));+ expect(seen).toEqual([false, true]);+ });+});++describe("useStoreActions", () => {+ it("never renders again for a state change", () => {+ const { store, source } = storeWith({});+ let renders = 0;+ function Actions() {+ useStoreActions();+ renders++;+ return null;+ }+ mount(source, createElement(Actions));+ act(() => store.dispatch({ type: "connected", value: !store.getState().connected }));+ expect(renders).toBe(1);+ });+});diff --git a/src/state/store-select.ts b/src/state/store-select.tsnew file mode 100644index 0000000000..88357ce3d3--- /dev/null+++ b/src/state/store-select.ts@@ -0,0 +1,64 @@+import { useContext, useMemo, useSyncExternalStore } from "react";+import { useStore, type AppState } from "./store";+import { StoreSourceContext, type StoreActions, type StoreSource, type StoreValue } from "./store-context";++const scopedSources = new WeakMap<StoreValue, StoreSource>();+const noSubscription = () => () => {};++/** A store given as a plain value (a bot editor's, a preview's) changes by being given again, so it needs no+ * subscription: its reader is already a context reader of that value. */+function scopedSource(value: StoreValue): StoreSource {+ let source = scopedSources.get(value);+ if (!source) {+ source = { ...value, getState: () => value.state, subscribe: noSubscription };+ scopedSources.set(value, source);+ }+ return source;+}++/** useStore only reads a context, and a component stays on one side of this branch, so calling it here is safe. */+function useStoreSource(): StoreSource {+ return useContext(StoreSourceContext) ?? scopedSource(useStore());+}++interface Selection<T> {+ state: AppState;+ selector: (state: AppState) => T;+ value: T;+}++/** Renders again only when the selected value changes under `equal`. A selector may be a new closure each render. */+export function useStoreSelector<T>(selector: (state: AppState) => T, equal: (a: T, b: T) => boolean = Object.is): T {+ const source = useStoreSource();+ const last = useMemo<{ current?: Selection<T> }>(() => ({}), []);+ const read = () => {+ const state = source.getState();+ const previous = last.current;+ if (previous && previous.state === state && previous.selector === selector) return previous.value;+ const value = selector(state);+ const kept = previous && equal(previous.value, value) ? previous.value : value;+ last.current = { state, selector, value: kept };+ return kept;+ };+ return useSyncExternalStore(source.subscribe, read, read);+}++/** The store's actions without its state: never renders again on a state change. */+export function useStoreActions(): StoreActions {+ return useStoreSource();+}++export function useStoreDispatch(): StoreActions["dispatch"] {+ return useStoreSource().dispatch;+}++/** For a selector that builds an array: equal when every item is the same object. */+export function sameItems<T>(a: readonly T[], b: readonly T[]): boolean {+ return a.length === b.length && a.every((item, index) => Object.is(item, b[index]));+}++/** For a selector that builds a record of slices: equal when every field is the same value. */+export function sameFields<T extends object>(a: T, b: T): boolean {+ const keys = Object.keys(a) as (keyof T)[];+ return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]));+}diff --git a/src/state/store.tsx b/src/state/store.tsxindex 10ac313636..c542ec6242 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -1,15 +1,7 @@import { cloudAsleep, onCloudPower } from "../lib/cloud-power";import { api, ApiError, retryRequest, snapshotArrays } from "./api";-import {- createContext,- useCallback,- useContext,- useEffect,- useMemo,- useReducer,- useRef,- type ReactNode,-} from "react";+import { use, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";+import { createAppStore } from "./app-store"; import { readOneBot } from "./bot-read"; import { StoreContext, StoreSourceContext } from "./store-context";import { flushSync } from "react-dom";import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, ResolvedSender, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire"; import type { InstanceEndpointInfo } from "../../shared/claude-endpoint";import { movesThreadToTop } from "../../shared/wire"; import type { DefaultBotFields } from "../../shared/default-bot";@@ -2074,13 +2066,7 @@ export function runtimeFrameAction(event: RuntimeEvent): Action | null {: null;}-export const StoreContext = createContext<{- state: AppState;- dispatch: React.Dispatch<Action>;- flushBotPatches: (botId: string) => Promise<BotAnnouncement | null>;- refreshInstances: (options?: { reportErrors?: boolean; cached?: boolean }) => Promise<void>;- refreshModels: (instanceId: string) => Promise<void>;-} | null>(null);+export { StoreContext } from "./store-context";function restoreBotSettingsSection(state: AppState): AppState {const section = readLastBotSection();@@ -2093,7 +2079,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {...bot,tasks: bot.tasks?.map((task) => ({ ...task, ...taskPatchFields(taskWrites.get(task.threadId)?.patch ?? {}) })),});- const [state, rawDispatch] = useReducer(reducer, initialState, (initial) => withRememberedTrayPin(restoreBotSettingsSection(initial)));+ const [store] = useState(() => createAppStore<AppState, Action, ServerFrame>(reducer, withRememberedTrayPin(restoreBotSettingsSection(initialState))));+ const rawDispatch = store.dispatch, state = useSyncExternalStore(store.subscribe, store.getState, store.getState);const stateRef = useRef(state), selectionRevision = useRef(0);stateRef.current = state;const showThreads = useShowThreads();@@ -2114,10 +2101,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {createBotPatchQueue({send: (botId, patch, signal, currentBot, leaving) =>persistBotUpdate(botId, patch, signal, api, desktopApprovalBridge(), currentBot, leaving),- reconcile: async (botId, signal) => {- const result: { bots: BotAnnouncement[] } = await api(`/api/bots?messages=${MESSAGE_PAGE_SIZE}`, { signal });- return result.bots.find((candidate) => candidate.id === botId) ?? null;- },+ reconcile: (botId, signal) => readOneBot(botId, MESSAGE_PAGE_SIZE, signal),onAuthoritative: (bot, optimisticOverlay) => {rawDispatch({ type: "botPatched", bot: withTaskWrites({ ...bot, ...optimisticOverlay }) });},@@ -2211,8 +2195,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {// Keep blocking sends while reconciliation fails (it is asked again) or a newer write owns this lane.if (taskWrites.get(threadId) === pending) {pending.patch = {};- retryRequest(() => taskWrites.get(threadId) === pending, () => api(`/api/bots?messages=${MESSAGE_PAGE_SIZE}`).then(({ bots }) => {- const bot = taskWrites.get(threadId) === pending ? bots.find((candidate: Bot) => candidate.id === botId) : undefined;+ retryRequest(() => taskWrites.get(threadId) === pending, () => readOneBot(botId, MESSAGE_PAGE_SIZE).then((read) => {+ const bot = taskWrites.get(threadId) === pending ? read : null;if (bot) {rawDispatch({ type: "botPatched", bot: withTaskWrites(bot) });taskWrites.delete(threadId);@@ -2240,7 +2224,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {};const wrapped: React.Dispatch<Action> = (action) => {- if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps"].includes(action.type)) selectionRevision.current++;+ store.flushFrames(); if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps"].includes(action.type)) selectionRevision.current++;// Pin before any await or optimistic state change.action = pinBotThreadAction(action, stateRef.current.bots);if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };@@ -3081,7 +3065,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {} while (alive && rehydrateRequested);if (!alive || !loaded) return false;hydrated = true;- for (const frame of pendingFrames.splice(0)) handleFrame(frame);+ for (const frame of pendingFrames.splice(0)) store.enqueueFrame(frame);+ store.flushFrames();return true;})().finally(() => {hydrationPromise = null;@@ -3090,6 +3075,16 @@ export function StoreProvider({ children }: { children: ReactNode }) {};const hydrationFallback = setTimeout(hydrate, 1_000);+ // One read per conversation at a time; an unread frame meanwhile asks for exactly one more once it finishes.+ const readsInFlight = new Map<string, boolean>();+ const sendRead = (botId: string, threadId: string | undefined, key: string): void => {+ readsInFlight.set(key, false);+ void fetch(`/api/bots/${botId}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId }) }).catch(() => {}).finally(() => {+ const again = readsInFlight.get(key); readsInFlight.delete(key);+ if (again && alive) sendRead(botId, threadId, key);+ });+ };+ const stopFrames = store.handleFrames((frame) => { handleFrame(frame); stateRef.current = store.getState(); });handleFrame = (frame) => {if (frame.kind === "config") bumpPeripheralVersion("config", "instances");else if (frame.kind === "routine" || frame.kind === "routine.deleted" || frame.kind === "routine.run") {@@ -3141,7 +3136,9 @@ export function StoreProvider({ children }: { children: ReactNode }) {(selectedTask?.unread || (!bot.tasks && bot.unread))) {if (selectedTask) selectedTask.unread = false;bot.unread = botShowsUnread(bot);- fetch(`/api/bots/${bot.id}/read`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ threadId: shown }) }).catch(() => {});+ const read = `${bot.id}:${shown}`;+ if (readsInFlight.has(read)) readsInFlight.set(read, true);+ else sendRead(bot.id, shown, read);}rawDispatch({type: "botPatched",@@ -3253,6 +3250,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {onOpen: () => rawDispatch({ type: "connected", value: true }),onError: () => rawDispatch({ type: "connected", value: false }),onSnapshotRequired: () => {+ store.flushFrames(); // the old stream's waiting frames go first, so forgetLiveTurns() below has the last wordclearTimeout(hydrationFallback);publishMissedFrames();// Frames buffered before a non-resumable stream belong to an abandoned generation, and so do the turns they named.@@ -3262,8 +3260,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {},onFrame: (frame) => {publishLiveFrame(frame as ServerFrame);- if (hydrated) handleFrame(frame as ServerFrame);- else pendingFrames.push(withoutScreenPixels(frame as ServerFrame));+ const queued = withoutScreenPixels(frame as ServerFrame); // the store reads only a screen frame's botId+ if (hydrated) store.enqueueFrame(queued, frame.kind === "live.call"); else pendingFrames.push(queued);},});return () => {@@ -3272,7 +3270,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {for (const refresh of peripheralRefresh.values()) {if (refresh.timer) clearTimeout(refresh.timer);}- stopLive();+ stopLive(); stopFrames();};}, []);@@ -3320,16 +3318,16 @@ export function StoreProvider({ children }: { children: ReactNode }) {() => ({ state, dispatch, flushBotPatches, refreshInstances, refreshModels }),[state, dispatch, flushBotPatches, refreshInstances, refreshModels],);- const ref = useMemo(() => ({ dispatch, state: () => stateRef.current }), [dispatch]);- return <StoreRefContext value={ref}><StoreContext.Provider value={value}>{children}</StoreContext.Provider></StoreRefContext>;+ const ref = useMemo(() => ({ dispatch, state: () => stateRef.current }), [dispatch]), source = useMemo(() => ({ getState: store.getState, subscribe: store.subscribe, dispatch, flushBotPatches, refreshInstances, refreshModels }), [store, dispatch, flushBotPatches, refreshInstances, refreshModels]);+ return <StoreRefContext value={ref}><StoreSourceContext value={source}><StoreContext.Provider value={value}>{children}</StoreContext.Provider></StoreSourceContext></StoreRefContext>;}export function useStore() {- const ctx = useContext(StoreContext);+ const ctx = use(StoreContext);if (!ctx) throw new Error("useStore outside provider");return ctx;}export function BotEditorStore({ value, children }: { value: ReturnType<typeof useStore>; children: ReactNode }) {- return <StoreRefContext value={null}><StoreContext.Provider value={value}>{children}</StoreContext.Provider></StoreRefContext>;+ return <StoreRefContext value={null}><StoreSourceContext value={null}><StoreContext.Provider value={value}>{children}</StoreContext.Provider></StoreSourceContext></StoreRefContext>;}diff --git a/src/state/task-write-recovery.test.ts b/src/state/task-write-recovery.test.tsindex 49e4094107..c226c4a7f6 100644--- a/src/state/task-write-recovery.test.ts+++ b/src/state/task-write-recovery.test.ts@@ -3,7 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { afterEach, describe, expect, it, vi } from "vitest";import { initialState, MESSAGE_PAGE_SIZE, StoreProvider, useStore, type Action, type BotAnnouncement } from "./store";-const SNAPSHOT = `/api/bots?messages=${MESSAGE_PAGE_SIZE}`;+const SNAPSHOT = `/api/bots/bot?messages=${MESSAGE_PAGE_SIZE}`;const bot: BotAnnouncement = {id: "bot", threadId: "thread", name: "Fixture", title: "", description: "",@@ -76,7 +76,7 @@ describe("thread setting save recovery", () => {controls.send();await flush();expect(requests.mock.calls.some(([path]) => path === "/api/bots/bot")).toBe(true);- reconciled.resolve(response({ bots: [bot] }));+ reconciled.resolve(response({ bot }));await flush();profileSave.resolve(response({ bot }));await flush();@@ -98,7 +98,7 @@ describe("thread setting save recovery", () => {controls.send();await flush();expect(requests.mock.calls.map(([path]) => path)).toEqual(["/api/bots/bot/tasks/thread", SNAPSHOT]);- reconcile.resolve(response({ bots: [bot] }));+ reconcile.resolve(response({ bot }));await flush();expect(requests).toHaveBeenCalledTimes(2);controls.send();@@ -108,7 +108,7 @@ describe("thread setting save recovery", () => {it.each(["unreachable", "missing bot"])("stays blocked when reconciliation is %s", async (failure) => {const requests = vi.fn<typeof fetch>(async (path) => path === SNAPSHOT- ? response({ bots: [], error: "Offline" }, failure === "unreachable" ? 503 : 200)+ ? response(failure === "unreachable" ? { error: "Offline" } : {}, failure === "unreachable" ? 503 : 200): response({ error: "Save failed" }, 500));const controls = mount(requests);controls.update();@@ -121,7 +121,7 @@ describe("thread setting save recovery", () => {it("asks again after a failed reconciliation, and permits a send once the server answers", async () => {let reachable = false;const requests = vi.fn<typeof fetch>(async (path) => {- if (path === SNAPSHOT) return reachable ? response({ bots: [bot] }) : response({ error: "Offline" }, 503);+ if (path === SNAPSHOT) return reachable ? response({ bot }) : response({ error: "Offline" }, 503);if (path === "/api/bots/bot/tasks/thread") return response({ error: "Save failed" }, 500);return response({});});@@ -157,7 +157,7 @@ describe("thread setting save recovery", () => {await flush();controls.update();await flush();- reconcile.resolve(response({ bots: [bot] }));+ reconcile.resolve(response({ bot }));await flush();controls.send();await flush();diff --git a/src/testing/plain-store-select.ts b/src/testing/plain-store-select.tsnew file mode 100644index 0000000000..2e64347415--- /dev/null+++ b/src/testing/plain-store-select.ts@@ -0,0 +1,12 @@+// For a test that calls a component as a plain function and mocks useStore(): the selector hooks read that mock.+import { useStore, type AppState } from "@/state/store";+import type * as StoreSelect from "@/state/store-select";++export function plainStoreSelect(original?: typeof StoreSelect): typeof StoreSelect {+ return {+ ...original!,+ useStoreSelector: <T,>(selector: (state: AppState) => T) => selector(useStore().state),+ useStoreDispatch: () => useStore().dispatch,+ useStoreActions: () => useStore(),+ };+}