Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf: trim App bundle, eliminate store re-render hotspots, and bound server caches (batches 9–11)
milind-sonifed50f025433
diff --git a/packages/phone-protocol/src/widget-text.ts b/packages/phone-protocol/src/widget-text.tsindex 6f118ad83f..08254acc6d 100644--- a/packages/phone-protocol/src/widget-text.ts+++ b/packages/phone-protocol/src/widget-text.ts@@ -1,3 +1,5 @@+import type { WidgetButtonSpec, WidgetNode, WidgetRoot } from "./widget.ts";+/** A moment a client words in the reader's language: `clock` "10:30 AM" (marked UTC when there is no zone),* `bareClock` the same never marked, `longDate` "Thursday, October 22", `shortDate` "Thu, Oct 22". */export interface WidgetMoment {@@ -24,8 +26,16 @@ const STYLES = new Set<WidgetMoment["style"]>(["clock", "bareClock", "longDate",const MAX_PARAMS = 8;const MAX_DEPTH = 3;const MAX_STRING = 400;+const WIDGET_FALLBACK_LIMIT = 1_500;const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);+const widgetString = (node: WidgetNode, key: string): string | undefined => (typeof node[key] === "string" ? node[key] as string : undefined);+const widgetNumber = (node: WidgetNode, key: string): number | undefined => (typeof node[key] === "number" ? node[key] as number : undefined);++function buttonSpecOf(root: WidgetRoot, key: "confirm" | "cancel"): WidgetButtonSpec | undefined {+ const spec = root[key];+ return isRecord(spec) && typeof spec.label === "string" && isRecord(spec.action) ? spec as unknown as WidgetButtonSpec : undefined;+}function readParam(raw: unknown, depth: number): WidgetTextParam | undefined {if (typeof raw === "string") return raw.slice(0, MAX_STRING);@@ -56,3 +66,67 @@ export function readWidgetText(raw: unknown): WidgetTextFields | undefined {}return Object.keys(fields).length ? fields : undefined;}++/** Days as a person says them: "Every day", "Weekdays", "Weekends", or the names. */+export function dayList(days: string): string {+ const picked = days.split(",").filter(Boolean);+ if (picked.length === 7) return "Every day";+ if (picked.join(",") === "mon,tue,wed,thu,fri") return "Weekdays";+ if (picked.join(",") === "sat,sun") return "Weekends";+ const names: Record<string, string> = { mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat", sun: "Sun" };+ return picked.map((day) => names[day] ?? day).join(", ");+}++function inlineText(node: WidgetNode): string {+ switch (node.type) {+ case "Text": case "Title": case "Caption": case "Label":+ return widgetString(node, "value") ?? "";+ case "Markdown":+ return (widgetString(node, "value") ?? "").replace(/\s+/g, " ");+ case "Badge":+ return widgetString(node, "label") ?? "";+ case "Button":+ return node.label ? `[${String(node.label)}]` : "";+ case "Image":+ return node.alt ? `[image: ${String(node.alt)}]` : "[image]";+ case "Progress":+ return [widgetString(node, "label"), `${Math.round((widgetNumber(node, "value") ?? 0) * 100)}%`].filter(Boolean).join(" ");+ case "Chart":+ return `[chart: ${(Array.isArray(node.series) ? node.series as Array<{ label?: string; dataKey: string }> : []).map((series) => series.label ?? series.dataKey).join(", ")}]`;+ case "Checkbox":+ return `[ ] ${widgetString(node, "label") ?? String(node.name)}`;+ case "Select": case "RadioGroup":+ return `(${(Array.isArray(node.options) ? node.options as Array<{ label: string }> : []).slice(0, 6).map((option) => option.label).join(" / ")})`;+ case "DayPicker":+ return `[${typeof node.defaultValue === "string" ? dayList(node.defaultValue) : "days"}]`;+ case "Input": case "Textarea": case "DatePicker": case "TimePicker":+ return `[${widgetString(node, "placeholder") ?? String(node.name)}]`;+ default:+ return (Array.isArray(node.children) ? node.children : []).map(inlineText).filter(Boolean).join(" · ");+ }+}++function blockLines(node: WidgetNode): string[] {+ const children = Array.isArray(node.children) ? node.children : [];+ if (node.type === "ListViewItem") return [`- ${inlineText(node)}`];+ if (node.type === "Table") return children.map((row) => (Array.isArray(row.children) ? row.children : []).map(inlineText).join(" | "));+ if (node.type === "Markdown") return [widgetString(node, "value") ?? ""];+ const stacked = node.type === "Col" || node.type === "Form" || node.type === "Transition" || (node.type === "Box" && node.direction !== "row");+ return stacked ? children.flatMap(blockLines) : [inlineText(node)];+}++/** The readable version of a widget: the message `text`, read by previews,+ * notifications, exports, replayed history and clients that do not know the kind. */+export function widgetToText(root: WidgetRoot): string {+ const lines: string[] = [];+ const statusText = isRecord(root.status) && typeof root.status.text === "string" ? root.status.text : "";+ if (statusText) lines.push(statusText);+ const title = widgetString(root, "title");+ const head = [title ? `**${title}**` : "", widgetString(root, "caption"), widgetString(root, "meta")].filter(Boolean).join(" · ");+ if (head) lines.push(head);+ for (const child of Array.isArray(root.children) ? root.children : []) lines.push(...blockLines(child));+ const buttons = (["confirm", "cancel"] as const).map((key) => buttonSpecOf(root, key)?.label).filter(Boolean).map((label) => `[${label}]`).join(" ");+ if (buttons) lines.push(buttons);+ const out = lines.map((line) => line.trimEnd()).filter(Boolean).join("\n");+ return out.length <= WIDGET_FALLBACK_LIMIT ? out : `${out.slice(0, WIDGET_FALLBACK_LIMIT - 1).trimEnd()}…`;+}diff --git a/packages/phone-protocol/src/widget.ts b/packages/phone-protocol/src/widget.tsindex f124c264e7..b23d2c4202 100644--- a/packages/phone-protocol/src/widget.ts+++ b/packages/phone-protocol/src/widget.ts@@ -3,7 +3,8 @@// Model input is normalised here once; every renderer reads canonical trees only.import type { JsonValue } from "./json.ts";import { childNodes, nodeTypeProblem } from "./widget-input.ts";-import { readWidgetText } from "./widget-text.ts";+import { dayList, readWidgetText, widgetToText } from "./widget-text.ts";+export { dayList, widgetToText };import { buttonStyle } from "./widget-button-style.ts";export const WIDGET_VERSION = 1;@@ -931,67 +932,3 @@ export function widgetAdvice(root: WidgetRoot): string | undefined {return notes.length ? notes.join(" ") : undefined;}-/** Days as a person says them: "Every day", "Weekdays", "Weekends", or the names. */-export function dayList(days: string): string {- const picked = days.split(",").filter(Boolean);- if (picked.length === 7) return "Every day";- if (picked.join(",") === "mon,tue,wed,thu,fri") return "Weekdays";- if (picked.join(",") === "sat,sun") return "Weekends";- const names: Record<string, string> = { mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat", sun: "Sun" };- return picked.map((day) => names[day] ?? day).join(", ");-}---function inlineText(node: WidgetNode): string {- switch (node.type) {- case "Text": case "Title": case "Caption": case "Label":- return widgetString(node, "value") ?? "";- case "Markdown":- return (widgetString(node, "value") ?? "").replace(/\s+/g, " ");- case "Badge":- return widgetString(node, "label") ?? "";- case "Button":- return node.label ? `[${String(node.label)}]` : "";- case "Image":- return node.alt ? `[image: ${String(node.alt)}]` : "[image]";- case "Progress":- return [widgetString(node, "label"), `${Math.round((widgetNumber(node, "value") ?? 0) * 100)}%`].filter(Boolean).join(" ");- case "Chart":- return `[chart: ${(Array.isArray(node.series) ? node.series as Array<{ label?: string; dataKey: string }> : []).map((series) => series.label ?? series.dataKey).join(", ")}]`;- case "Checkbox":- return `[ ] ${widgetString(node, "label") ?? String(node.name)}`;- case "Select": case "RadioGroup":- return `(${(Array.isArray(node.options) ? node.options as Array<{ label: string }> : []).slice(0, 6).map((option) => option.label).join(" / ")})`;- case "DayPicker":- return `[${typeof node.defaultValue === "string" ? dayList(node.defaultValue) : "days"}]`;- case "Input": case "Textarea": case "DatePicker": case "TimePicker":- return `[${widgetString(node, "placeholder") ?? String(node.name)}]`;- default:- return (Array.isArray(node.children) ? node.children : []).map(inlineText).filter(Boolean).join(" · ");- }-}--function blockLines(node: WidgetNode): string[] {- const children = Array.isArray(node.children) ? node.children : [];- if (node.type === "ListViewItem") return [`- ${inlineText(node)}`];- if (node.type === "Table") return children.map((row) => (Array.isArray(row.children) ? row.children : []).map(inlineText).join(" | "));- if (node.type === "Markdown") return [widgetString(node, "value") ?? ""];- const stacked = node.type === "Col" || node.type === "Form" || node.type === "Transition" || (node.type === "Box" && node.direction !== "row");- return stacked ? children.flatMap(blockLines) : [inlineText(node)];-}--/** The readable version of a widget: the message `text`, read by previews,- * notifications, exports, replayed history and clients that do not know the kind. */-export function widgetToText(root: WidgetRoot): string {- const lines: string[] = [];- const statusText = isRecord(root.status) && typeof root.status.text === "string" ? root.status.text : "";- if (statusText) lines.push(statusText);- const title = widgetString(root, "title");- const head = [title ? `**${title}**` : "", widgetString(root, "caption"), widgetString(root, "meta")].filter(Boolean).join(" · ");- if (head) lines.push(head);- for (const child of Array.isArray(root.children) ? root.children : []) lines.push(...blockLines(child));- const buttons = (["confirm", "cancel"] as const).map((key) => buttonSpecOf(root, key)?.label).filter(Boolean).map((label) => `[${label}]`).join(" ");- if (buttons) lines.push(buttons);- const out = lines.map((line) => line.trimEnd()).filter(Boolean).join("\n");- return out.length <= WIDGET_LIMITS.fallback ? out : `${out.slice(0, WIDGET_LIMITS.fallback - 1).trimEnd()}…`;-}diff --git a/server/attachments.test.ts b/server/attachments.test.tsindex 11ff11c4d3..5acbe1fca9 100644--- a/server/attachments.test.ts+++ b/server/attachments.test.ts@@ -61,7 +61,9 @@ const {extensionForFileMime,extensionForMime,parseAudioRange,+ attachmentExistsAsync,readAttachment,+ readAttachmentAsync,sanitizeSharedFileName,saveAudio,saveFile,@@ -494,6 +496,17 @@ describe("readAttachment name lock", () => {expect(readAttachment("uuid.jpeg")).toBeNull(); // saved as .jpgexpect(readAttachment("note.wav")).toBeNull(); // only .mp3 audio is written});++ it("readAttachmentAsync and attachmentExistsAsync enforce the same name lock and round-trip files", async () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);+ const saved = saveImage(png, "image/png");+ const name = saved.path.split(/[\\/]/).pop()!;+ expect(await attachmentExistsAsync(name)).toBe(true);+ expect(await readAttachmentAsync(name)).toEqual({ bytes: png, mime: "image/png" });+ expect(await attachmentExistsAsync("../config.json")).toBe(false);+ expect(await readAttachmentAsync("..%2F..%2Fconfig.json")).toBeNull();+ expect(await readAttachmentAsync("uuid.jpeg")).toBeNull();+ });});describe("saveNamedAttachment", () => {diff --git a/server/attachments.ts b/server/attachments.tsindex 229ba5c8bf..0bd6ef5a38 100644--- a/server/attachments.ts+++ b/server/attachments.ts@@ -10,7 +10,7 @@ import {unlinkSync,writeFileSync,} from "node:fs";-import { link, open, unlink } from "node:fs/promises";+import { link, open, readFile, stat, unlink } from "node:fs/promises";import { basename, dirname, extname, join, resolve } from "node:path";import { FILE_MAX_BYTES, PREVIEW_MAX_BYTES } from "../shared/upload-limits.ts";import { DATA_DIR } from "./config.ts";@@ -757,11 +757,26 @@ export function attachmentExists(name: string): boolean {}}-/** Only a bare filename inside ATTACHMENTS_DIR resolves: the route must never become a file server for the data dir. */-export function readAttachment(name: string): { bytes: Buffer; mime: string } | null {+function attachmentPath(name: string): string | null {if (!/^[A-Za-z0-9-]+\.(png|jpg|jpeg|gif|webp|mp3|wav)$/.test(name)) return null;const path = join(ATTACHMENTS_DIR, name);- if (extname(path) === ".jpeg") return null;+ return extname(path) === ".jpeg" ? null : path;+}++export async function attachmentExistsAsync(name: string): Promise<boolean> {+ const path = attachmentPath(name);+ if (!path) return false;+ try {+ return (await stat(path)).isFile();+ } catch {+ return false;+ }+}++/** Only a bare filename inside ATTACHMENTS_DIR resolves: the route must never become a file server for the data dir. */+export function readAttachment(name: string): { bytes: Buffer; mime: string } | null {+ const path = attachmentPath(name);+ if (!path) return null;try {return { bytes: readFileSync(path), mime: mimeForExt(extname(path)) };} catch {@@ -769,6 +784,17 @@ export function readAttachment(name: string): { bytes: Buffer; mime: string } |}}+/** Async variant for HTTP handlers so attachment downloads do not block the event loop. */+export async function readAttachmentAsync(name: string): Promise<{ bytes: Buffer; mime: string } | null> {+ const path = attachmentPath(name);+ if (!path) return null;+ try {+ return { bytes: await readFile(path), mime: mimeForExt(extname(path)) };+ } catch {+ return null;+ }+}+function mimeForExt(ext: string): string {switch (ext) {case ".png":diff --git a/server/connector-tools-list.test.ts b/server/connector-tools-list.test.tsindex 18377db3f5..309dee95a8 100644--- a/server/connector-tools-list.test.ts+++ b/server/connector-tools-list.test.ts@@ -230,3 +230,19 @@ describe("paginated tools/list fallback", () => {}});});++describe("bounded tools/list cache", () => {+ it("evicts the oldest backend once the cache exceeds its cap", async () => {+ const req = (id: string) => ({ jsonrpc: "2.0", id, method: "tools/list" });+ const ok = (id: string, name: string) => Response.json({ jsonrpc: "2.0", id, result: { tools: [{ name }] } });+ await withToolsListFallback("evict-oldest-0", req("seed-0"), async () => ok("seed-0", "tool-0"));+ for (let i = 1; i <= 130; i++) {+ await withToolsListFallback(`evict-oldest-${i}`, req(`seed-${i}`), async () => ok(`seed-${i}`, `tool-${i}`));+ }+ const oldest = await withToolsListFallback("evict-oldest-0", req("retry-0"), async () => new Response(null, { status: 503 }));+ expect(oldest.status).toBe(503);+ const newest = await withToolsListFallback("evict-oldest-130", req("retry-130"), async () => new Response(null, { status: 503 }));+ expect(newest.status).toBe(200);+ expect(await newest.json()).toEqual({ jsonrpc: "2.0", id: "retry-130", result: { tools: [{ name: "tool-130" }] } });+ });+});diff --git a/server/connector-tools-list.ts b/server/connector-tools-list.tsindex ff1988f9e1..e3de6d2e06 100644--- a/server/connector-tools-list.ts+++ b/server/connector-tools-list.ts@@ -34,7 +34,14 @@ export function parseMcpResponse(text: string, id: unknown): Record<string, unknreturn frames.filter(candidate).at(-1) ?? frames.map(diagnostic).filter((frame) => frame !== null).at(-1) ?? null;}+const MAX_TOOL_LIST_BACKENDS = 128;+const MAX_TOOL_LIST_PAGES = 16;const lastToolsLists = new Map<string, Map<string | undefined, unknown>>();+function rememberToolsList(backend: string, pages: Map<string | undefined, unknown>): void {+ lastToolsLists.delete(backend);+ if (lastToolsLists.size >= MAX_TOOL_LIST_BACKENDS) lastToolsLists.delete(lastToolsLists.keys().next().value!);+ lastToolsLists.set(backend, pages);+}function toolsListId(payload: unknown): { id: unknown; cursor: string | undefined } | null {if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;@@ -79,13 +86,14 @@ export async function withToolsListFallback(const result = toolsResult(await response.clone().text(), request.id);if (result !== undefined) {if (request.cursor === undefined) {- lastToolsLists.set(backend, new Map([[undefined, result]]));+ rememberToolsList(backend, new Map([[undefined, result]]));} else {const pages = lastToolsLists.get(backend);if (pages === pagesAtStart || (pagesAtStart === undefined && !pages?.has(undefined))) {const current = pages ?? new Map<string | undefined, unknown>();+ if (!current.has(request.cursor) && current.size >= MAX_TOOL_LIST_PAGES) current.delete(current.keys().next().value!);current.set(request.cursor, result);- lastToolsLists.set(backend, current);+ rememberToolsList(backend, current);}}}diff --git a/server/drivers/chat-host-computer.ts b/server/drivers/chat-host-computer.tsindex 9846d1140e..33846b8447 100644--- a/server/drivers/chat-host-computer.ts+++ b/server/drivers/chat-host-computer.ts@@ -26,6 +26,7 @@ export function hostComputerKey(server: Server): string {return JSON.stringify(OMB_CUA_COMMAND === undefined ? [server.command, server.args] : [OMB_CUA_COMMAND, OMB_CUA_ARGS ?? "", OMB_CUA_PLATFORM ?? "", OMB_HOST_FILES ?? ""]);}+const MAX_HOST_COMPUTER_KEYS = 64;const lastListed = new Map<string, unknown[]>();const lastFailed = new Set<string>();@@ -47,11 +48,13 @@ export async function startHostComputer(key: string, list: (include: (tool: unkninclude: (tool: unknown) => boolean, wait: { quickMs: number; firstMs: number }, signal: AbortSignal): Promise<HostComputerStart> {const seen: unknown[] = [];const listing = list((tool) => { seen.push(tool); return include(tool); }).then((tools) => {+ lastListed.delete(key);+ if (lastListed.size >= MAX_HOST_COMPUTER_KEYS) lastListed.delete(lastListed.keys().next().value!);lastListed.set(key, seen);lastFailed.delete(key);return tools;}, (error: unknown) => {- if (!signal.aborted) lastFailed.add(key);+ if (!signal.aborted) { if (!lastFailed.has(key) && lastFailed.size >= MAX_HOST_COMPUTER_KEYS) lastFailed.delete(lastFailed.values().next().value!); lastFailed.add(key); }throw error;});listing.catch(() => {});diff --git a/server/drivers/claude-transcript-images.ts b/server/drivers/claude-transcript-images.tsindex 1d3290a804..6b39816a94 100644--- a/server/drivers/claude-transcript-images.ts+++ b/server/drivers/claude-transcript-images.ts@@ -27,6 +27,7 @@ const PROJECT_DIR_MAX = 200;/** The copy of a transcript as it was before its latest fold. */export const FOLD_BACKUP_SUFFIX = ".before-image-fold";+const MAX_COUNTED_TRANSCRIPTS = 512;const counted = new Map<string, { stamp: string; total: number }>();export interface FoldResult {@@ -103,7 +104,7 @@ const stampOf = (stat: Stats) => `${stat.size}:${stat.mtimeMs}`;/** Images in one version of a transcript, counted once per version; rows that never say "image" are not parsed. */function imagesIn(file: string, stat: Stats): number {const stamp = stampOf(stat), seen = counted.get(file);- if (seen?.stamp === stamp) return seen.total;+ if (seen?.stamp === stamp) { counted.delete(file); counted.set(file, seen); return seen.total; }let total = 0;for (const line of readFileSync(file, "utf8").split("\n")) {if (!line.includes('"image"')) continue;@@ -111,6 +112,8 @@ function imagesIn(file: string, stat: Stats): number {total += imageSlots(JSON.parse(line)).length;} catch { /* a half-written last line */ }}+ counted.delete(file);+ if (counted.size >= MAX_COUNTED_TRANSCRIPTS) counted.delete(counted.keys().next().value!);counted.set(file, { stamp, total });return total;}diff --git a/server/index.ts b/server/index.tsindex 31b6a69fc6..1dd25da33f 100644--- a/server/index.ts+++ b/server/index.ts@@ -13757,12 +13757,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {// A refusal is stored, an allowance is not: losing a refusal would let a ring re-form one call later.const preflight = askBudget(from, room);if (!preflight.allowed) {- roomPostBudgets.set(room.id, preflight.budget);+ if (!roomPostBudgets.has(room.id) && roomPostBudgets.size >= 1_000) roomPostBudgets.delete(roomPostBudgets.keys().next().value!); roomPostBudgets.set(room.id, preflight.budget);return json(res, 429, { error: preflight.message });}const poster = from;const decision = askBudget(poster, room);- roomPostBudgets.set(room.id, decision.budget);+ if (!roomPostBudgets.has(room.id) && roomPostBudgets.size >= 1_000) roomPostBudgets.delete(roomPostBudgets.keys().next().value!); roomPostBudgets.set(room.id, decision.budget);if (!decision.allowed) return json(res, 429, { error: decision.message });// Reading the mark keeps its window alive through a turn that only posts; an aged-out mark would hand the next hop to auto-approve.const unattended = isUnattended(poster.id, internalCapability.threadId);@@ -14354,7 +14354,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {let routineMatch = path.match(/^\/api\/routines\/([\w-]+)\/run$/);if (routineMatch && method === "POST") {const run = routines!.runNow(routineMatch[1]);- if (run && (CLOUD_HOME ? cloudOwnerSession(auth) : ownerOrAdmin(auth))) ownerStartedRoutineRuns.add(run.id);+ if (run && (CLOUD_HOME ? cloudOwnerSession(auth) : ownerOrAdmin(auth))) { if (ownerStartedRoutineRuns.size >= 2_000) ownerStartedRoutineRuns.delete(ownerStartedRoutineRuns.values().next().value!); ownerStartedRoutineRuns.add(run.id); }return run ? json(res, 201, { run }) : json(res, 404, { error: "no such routine" });}routineMatch = path.match(/^\/api\/routines\/([\w-]+)$/);diff --git a/server/room-feed-since.ts b/server/room-feed-since.tsindex 237c6c1b6c..6ecc569c92 100644--- a/server/room-feed-since.ts+++ b/server/room-feed-since.ts@@ -24,6 +24,7 @@ export function roomFeedSince(dataDir: string, now = Date.now()): number {since = now;try { writeFileAtomic(file, JSON.stringify({ version: 1, since }), { mode: 0o600 }); } catch { /* kept in memory */ }}+ if (!known.has(dataDir) && known.size >= 64) known.delete(known.keys().next().value!);known.set(dataDir, since);return since;}diff --git a/server/routes/team-owners.ts b/server/routes/team-owners.tsindex 969c0d3e5b..2713e697d5 100644--- a/server/routes/team-owners.ts+++ b/server/routes/team-owners.ts@@ -12,7 +12,7 @@ import { z } from "zod";import { botAvatarUrlSchema } from "../../shared/bot-avatar.ts";import type { PersonPresence } from "../../shared/team-presence.ts";import { botOwner, nameFromEmail, ownerEmail } from "../../shared/bot-owner.ts";-import { attachmentExists, readAttachment } from "../attachments.ts";+import { attachmentExists, attachmentExistsAsync, readAttachmentAsync } from "../attachments.ts";import { setReportsTo } from "../bot-owners.ts";import type { CloudTeam } from "../cloud-team.ts";import { personKey } from "../person-key.ts";@@ -101,14 +101,17 @@ export function createTeamOwnerRoutes(deps: TeamOwnerRouteDeps): RouteHandler {const email = members().find((person) => personKey({ id: "", email: person.email }) === picture[1])?.email;const avatarUrl = email ? profileOf(email).avatarUrl : undefined;const name = storedPicture(avatarUrl);- const stored = name ? readAttachment(name) : null;- if (!avatarUrl || !stored) return json(res, 404, { error: "no such picture" });- // Revalidated on every use, so the member check above runs each time; the address changes with the picture.- const headers = { "content-type": stored.mime, "cache-control": "private, no-cache", etag: `"${pictureVersion(avatarUrl)}"`, "x-content-type-options": "nosniff" };- if (req.headers["if-none-match"] === headers.etag) {- res.writeHead(304, headers);+ if (!avatarUrl || !name) return json(res, 404, { error: "no such picture" });+ const etag = `"${pictureVersion(avatarUrl)}"`;+ // Short-circuit revalidation before reading bytes from disk.+ if (req.headers["if-none-match"] === etag && await attachmentExistsAsync(name)) {+ res.writeHead(304, { "cache-control": "private, no-cache", etag, "x-content-type-options": "nosniff" });return void res.end();}+ const stored = await readAttachmentAsync(name);+ if (!stored) return json(res, 404, { error: "no such picture" });+ // Revalidated on every use, so the member check above runs each time; the address changes with the picture.+ const headers = { "content-type": stored.mime, "cache-control": "private, no-cache", etag, "x-content-type-options": "nosniff" };res.writeHead(200, { ...headers, "content-length": String(stored.bytes.byteLength) });return void res.end(stored.bytes);}diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex e56f46b68f..9b16457950 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -8,7 +8,7 @@ import { closeUnfinishedCodeFence } from "../../shared/markdown-code-fence.ts";import { KEPT_ORIGINALS_DIR, keptOriginal } from "../attachment-originals.ts";import {ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,- parseAudioRange, readAttachment, saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,+ parseAudioRange, readAttachmentAsync, saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,} from "../attachments.ts";import { saveXmindUpload, XMIND_MIME } from "../xmind.ts";import { deliveredCopy } from "../bot-attachment.ts";@@ -509,7 +509,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {return json(res, 200, { ok: true });}if (m && method === "GET") {- const attachment = readAttachment(m[1]!);+ const attachment = await readAttachmentAsync(m[1]!);if (!attachment) return json(res, 404, { error: "no such attachment" });const size = attachment.bytes.byteLength;// Visibility is decided per request, so the browser must never reuse one member's copy for another identity.diff --git a/server/skills.ts b/server/skills.tsindex ce54cb9ef8..c5313c366a 100644--- a/server/skills.ts+++ b/server/skills.ts@@ -41,7 +41,7 @@ export { STAGED_SKILL_FILE_MAX_BYTES } from "./skill-storage.ts";export const INDEX_MAX_SKILLS = 100;export const INDEX_MAX_BYTES = 32_000;-const loggedIndexOmissions = new Map<string, string>();+const MAX_LOGGED_INDEX_OMISSIONS = 512, loggedIndexOmissions = new Map<string, string>();export const MAX_STAGED_SKILLS = 20;export const STAGED_GIST_MAX = 240;export interface SkillManifestEntry {@@ -1284,7 +1284,7 @@ export function skillsSystemPrompt(botId: string, assignedLibrary?: readonly strconst signature = JSON.stringify([reason(lines.length), omitted.map((skill) => skill.name)]);if (loggedIndexOmissions.get(botId) !== signature) {console.warn(`Skills index for bot ${botId}: ${omitted.length} enabled skills omitted by ${reason(lines.length)}: ${omitted.map((skill) => skill.name).join(", ")}`);- loggedIndexOmissions.set(botId, signature);+ if (!loggedIndexOmissions.has(botId) && loggedIndexOmissions.size >= MAX_LOGGED_INDEX_OMISSIONS) loggedIndexOmissions.delete(loggedIndexOmissions.keys().next().value!); loggedIndexOmissions.set(botId, signature);}} else {loggedIndexOmissions.delete(botId);diff --git a/server/vps-computer-rpc.ts b/server/vps-computer-rpc.tsindex a4f42bac84..7c03a93288 100644--- a/server/vps-computer-rpc.ts+++ b/server/vps-computer-rpc.ts@@ -44,6 +44,7 @@ const queues = new Map<string, Promise<unknown>>();export function forgetVpsComputers(): void {for (const botId of children.keys()) dropChild(botId);targets.clear();+ queues.clear();}/** The turn's bot serves its VPS computer's tools from here: remembers the target and drops a child that points at@@ -126,7 +127,9 @@ export async function vpsComputerTurn(turn: {return failure(error);}});- queues.set(turn.botId, queued.then(() => undefined, () => undefined));+ const nextQueue = queued.then(() => undefined, () => undefined);+ queues.set(turn.botId, nextQueue);+ void nextQueue.finally(() => { if (queues.get(turn.botId) === nextQueue) queues.delete(turn.botId); });let onAbort: () => void = () => {};const aborted = new Promise<never>((_, reject) => {onAbort = () => reject(interrupted());diff --git a/server/workspace.ts b/server/workspace.tsindex dc35331b80..3d9695c530 100644--- a/server/workspace.ts+++ b/server/workspace.ts@@ -254,6 +254,7 @@ export function syncMemoryIndex(botId: string): void {}}for (const gone of indexed.keys()) removeMemoryFile(botId, gone);+ if (!memoryIndexDates.has(botId) && memoryIndexDates.size >= 512) memoryIndexDates.delete(memoryIndexDates.keys().next().value!);memoryIndexDates.set(botId, today);}diff --git a/src/App.tsx b/src/App.tsxindex 8ed314dd80..855e6d064e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -3,14 +3,15 @@ import { ChevronLeft, Loader2, Menu } from "lucide-react";import { CLOUD_LINK_SETTINGS, openBot, StoreProvider, useStore } from "@/state/store";import { nextShortcutBot, shortcutBots, shownBotIds } from "@/lib/sidebar-shortcut-order";import { useShowThreads } from "@/lib/thread-preferences";-import { useWelcomeViewer, WelcomeGate } from "@/components/onboarding/WelcomeGate";-import { MausBotWelcome } from "@/components/MausBotWelcome";+import { useWelcomeViewer } from "@/components/onboarding/welcome-viewer";+import {+ LazyAppNotices, LazyConversationShareDialogs, LazyFirstConversationTour, LazyGuidedTour,+ LazyMausBotWelcome, LazyPublishTemplateHost, LazyWelcomeGate,+} from "@/components/lazy-overlays";import { NewBotNameHost } from "@/components/NewBotName";import { MemberApps } from "@/components/MemberApps";import { CloudTimeZoneSync } from "@/components/CloudTimeZone";import { cloudSignInDue, noEnginesDue, spotlightsQuiet, workedEarlier, type WelcomeViewer } from "@/lib/onboarding";-import { FirstConversationTour } from "@/components/onboarding/FirstConversationTour";-import { GuidedTour } from "@/components/onboarding/GuidedTour";import { LiveCallHost } from "@/components/LiveCallHost";import { ThreadRefsProvider } from "@/components/ThreadRefs";import { initAnalytics } from "@/lib/analytics";@@ -41,7 +42,6 @@ import { WorkspaceBackupRecovery } from "@/components/WorkspaceBackupRecovery";import { NotificationRail, NotificationsPanel } from "@/components/NotificationsPanel";import { useNotificationFeed } from "@/lib/notification-preferences";import { UpdateBanner } from "@/components/UpdateBanner";-import { AppNotices } from "@/components/AppNotices";import { CliLoginCard } from "@/components/CliLoginCard";import { AppGrantNotice } from "@/components/AppGrantPrompt";import { BotLimitPopup } from "@/components/BotLimitPopup";@@ -68,8 +68,6 @@ import { cloudIntentDue, cloudIntentShown, useCloudIntent } from "@/lib/cloud-inimport { CloudSetup } from "@/components/CloudSetup";import { CloudWelcome } from "@/components/cloud-welcome/CloudWelcome";import { TeamWelcome } from "@/components/TeamWelcome";-import { ConversationShareDialogs } from "@/components/conversation-share/ConversationShareDialogs";-import { PublishTemplateHost } from "@/components/publish-template";import { invitedToTeam, teamWelcomeDue, useTeamWelcomeRecord } from "@/lib/team-welcome";import { WelcomeKeeper } from "@/components/cloud-welcome/WelcomeKeeper";import { EmptyChatShell } from "@/components/onboarding/EmptyChatShell";@@ -414,15 +412,15 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<LiveConnectionStrip connected={state.connected} hydrated={state.hydrated === true} /><CloudSendStrip cloudHome={state.config?.cloudHome === true} /><HomeLine />- <AppNotices quiet={paletteOpen || drawerOpen || Boolean(localVmWorkspaceBotId)} viewer={viewer} />+ <LazyAppNotices quiet={paletteOpen || drawerOpen || Boolean(localVmWorkspaceBotId)} viewer={viewer} /><CliLoginCard /></>;return (<div data-look="app" className={cn("flex h-full flex-col", framed && "bg-frame")} onClickCapture={drawerOpen ? noteDrawerAction : undefined} onKeyDownCapture={drawerOpen ? noteDrawerAction : undefined}><WindowFrameBar notifications={notificationTray} sidebarUpdate={!advanced && sidebarShown} /><BotLimitPopup />- <ConversationShareDialogs />- <PublishTemplateHost />+ <LazyConversationShareDialogs />+ <LazyPublishTemplateHost />{!framed && strips}<div className="relative flex min-h-0 flex-1 overflow-x-clip">{!calendarFocus && <button@@ -590,13 +588,13 @@ function Application() {<ThreadRefsProvider><Shell viewer={viewer} /></ThreadRefsProvider>- <WelcomeGate viewer={viewer} />- <MausBotWelcome viewer={viewer} />+ <LazyWelcomeGate viewer={viewer} />+ <LazyMausBotWelcome viewer={viewer} /><NewBotNameHost /><CloudTimeZoneSync viewer={viewer} />- <GuidedTour />+ <LazyGuidedTour /><LiveCallHost />- <FirstConversationTour quiet={spotlightsQuiet(viewer)} />+ <LazyFirstConversationTour quiet={spotlightsQuiet(viewer)} /></StoreProvider></DesktopCapabilitiesProvider>);diff --git a/src/components/ActivityPanel.tsx b/src/components/ActivityPanel.tsxindex bf16e4769c..e37c37b6a2 100644--- a/src/components/ActivityPanel.tsx+++ b/src/components/ActivityPanel.tsx@@ -1,7 +1,8 @@import { routineLineText } from "@/lib/activity-text";+import { useStoreDispatch } from "@/state/store-select";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { ListChecks, RefreshCw, X } from "lucide-react";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";import {@@ -28,7 +29,7 @@ const TONE_CLASS: Record<ChipTone, string> = {};export function ActivityPanel({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { dragProps } = useCaptionChrome();const [rows, setRows] = useState<ActivityRow[] | null>(null);const [error, setError] = useState<string | null>(null);diff --git a/src/components/AppGrantPrompt.tsx b/src/components/AppGrantPrompt.tsxindex 5f37536e46..61643dffac 100644--- a/src/components/AppGrantPrompt.tsx+++ b/src/components/AppGrantPrompt.tsx@@ -5,7 +5,7 @@ import { appSwitchPatch, botAppScope } from "@/lib/bot-app-access";import type { ConnectorStatus } from "@/lib/connector-status";import { t } from "@/lib/i18n";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { useStore, type Action, type Bot, type InstanceInfo } from "@/state/store";+import { type Action, type Bot, type InstanceInfo } from "@/state/store";import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { EMAIL_SLUG } from "../../shared/email";import { BotAvatar } from "./Avatar";@@ -48,7 +48,7 @@ export function showAppGrantNotice(next: { slug: string; text: string } | null)/** "Your bots can now use Apollo · Change", for a few seconds. It outlives the Apps pop-up, which Change opens again. */export function AppGrantNotice() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const shown = useSyncExternalStore(subscribe, () => notice, () => null);const done = useCallback(() => showAppGrantNotice(null), []);if (!shown) return null;diff --git a/src/components/AppNotices.tsx b/src/components/AppNotices.tsxindex 84bc368b2a..d6722e0505 100644--- a/src/components/AppNotices.tsx+++ b/src/components/AppNotices.tsx@@ -43,7 +43,7 @@ import { openKeySettings } from "./keys/key-focus";import { ModelgoOfferCard, type ModelgoCardAction } from "./ModelgoOffer";import { LinkButton, NoticeCard, NoticeToast, NotNowButton } from "./NoticeCard";import { useDesktopNotices, useOtherDialogOpen } from "./notice-dialogs";-import { localDesktopPage } from "./onboarding/WelcomeGate";+import { localDesktopPage } from "./onboarding/welcome-viewer";import { UpdatesConsentDialog, updatesConsentBridge, useUpdatesConsent } from "./UpdatesConsent";import { useMausBotWelcomeDue } from "./MausBotWelcome";import { NewLookNotice, reportNewLook } from "./NewLookNotice";diff --git a/src/components/BotLimitPopup.tsx b/src/components/BotLimitPopup.tsxindex 8bc6c99606..7b8d7773dd 100644--- a/src/components/BotLimitPopup.tsx+++ b/src/components/BotLimitPopup.tsx@@ -7,6 +7,7 @@ import { cloudPlanLabel } from "@/lib/cloud-plan";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useStore } from "@/state/store";+import { sameFields, useStoreSelector } from "@/state/store-select";import { MausAvatar } from "./Avatar";import { AwakeBotsPicker } from "./AwakeBotsPicker";import { useCloudPlanSnapshot } from "./CloudTrialNotice";@@ -20,8 +21,8 @@ const BODY = "bot-limit-body";const LAYER = "z-[80]";export function BotLimitPopup() {- const { state } = useStore();- const turns = state.config?.planTurns, loaded = Boolean(state.config), seen = useRef<number | undefined | null>(null);+ const { turns, loaded } = useStoreSelector((state) => ({ turns: state.config?.planTurns, loaded: Boolean(state.config) }), sameFields);+ const seen = useRef<number | undefined | null>(null);useEffect(() => {if (!loaded) return;const next = planRefusal(seen.current, turns);diff --git a/src/components/BotProjects.tsx b/src/components/BotProjects.tsxindex 6c78828a47..a4462a006c 100644--- a/src/components/BotProjects.tsx+++ b/src/components/BotProjects.tsx@@ -1,7 +1,8 @@import { useEffect, useRef, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { createPortal } from "react-dom";import { ArrowDown, ArrowUp, CheckCheck, Folder, MoreHorizontal, Pencil, Plus, X } from "lucide-react";-import { useStore, type Bot, type BotProject } from "@/state/store";+import { type Bot, type BotProject } from "@/state/store";import { cn } from "@/lib/cn";import { MENU_SHEET } from "./menu-recipe";import { useHeldMenuMotion } from "./MenuMotion";@@ -80,7 +81,7 @@ export function BotProjectDialog({ bot, project, onClose, onCreated }: {onClose: () => void;onCreated?: (project: BotProject) => void;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [name, setName] = useState(project?.name ?? "");const [emoji, setEmoji] = useState(project?.emoji ?? "");const [choosingIcon, setChoosingIcon] = useState(false);@@ -178,7 +179,7 @@ export function BotProjectDialog({ bot, project, onClose, onCreated }: {}export function NewThreadButton({ bot, className, compact = false, onCreated }: { bot: Bot; className?: string; compact?: boolean; onCreated?: () => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const projects = bot.projects ?? [];const currentProject = projects.find((project) => project.id === bot.tasks?.find((task) => task.threadId === bot.threadId)?.projectId);return <button type="button" aria-label={t("task.newShort")} title={currentProject ? t("task.newIn", { name: currentProject.name }) : t("task.newShort")}diff --git a/src/components/BurstCard.tsx b/src/components/BurstCard.tsxindex 860e127cd6..8c177b94b2 100644--- a/src/components/BurstCard.tsx+++ b/src/components/BurstCard.tsx@@ -4,7 +4,8 @@ import { useEffect, useState } from "react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { serverErrorText } from "@/lib/server-error";-import { api, ApiError, openThread, useStore } from "@/state/store";+import { api, ApiError, openThread } from "@/state/store";+import { useStoreRef } from "@/state/store-ref";import { useShowThreads } from "@/lib/thread-preferences";import type { LocaleKey } from "@/locales";import type { BurstCardData, BurstChildRow, BurstChildStatus, BurstView } from "../../shared/burst";@@ -169,7 +170,7 @@ function BurstEditor({ view, busy, onSave, onBack }: { view: BurstView; busy: bo/** The parts under the card, opened on demand; each started part opens its own thread. */export function BurstRows({ botId, rows }: { botId: string; rows: BurstChildRow[] }) {- const { state, dispatch } = useStore();+ const storeRef = useStoreRef();const showThreads = useShowThreads();return (<ul className="max-h-[280px] space-y-0.5 overflow-y-auto pt-1.5">@@ -184,7 +185,7 @@ export function BurstRows({ botId, rows }: { botId: string; rows: BurstChildRow[return (<li key={row.seq}>{row.threadId ? (- <button type="button" title={row.error ?? t("chat.openThread", { title: row.title })} onClick={() => openThread(dispatch, { botId, threadId: row.threadId! }, state, showThreads)}+ <button type="button" title={row.error ?? t("chat.openThread", { title: row.title })} onClick={() => openThread(storeRef.dispatch, { botId, threadId: row.threadId! }, storeRef.state(), showThreads)}className="flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left text-[12px] text-ink-secondary hover:bg-raised hover:text-ink">{label}</button>) : (<div className="flex w-full items-center gap-2 px-1.5 py-1 text-[12px] text-ink-secondary">{label}</div>diff --git a/src/components/CanvasComputers.tsx b/src/components/CanvasComputers.tsxindex ce5b37e250..28d8ff606c 100644--- a/src/components/CanvasComputers.tsx+++ b/src/components/CanvasComputers.tsx@@ -1,7 +1,8 @@import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";+import { useStoreDispatch } from "@/state/store-select";import { createPortal } from "react-dom";import { ArrowUpRight, Box, ExternalLink, Loader2, Monitor, Plus, RefreshCw, X } from "lucide-react";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";import type { TeamComputer } from "../../shared/team-computer";import { ConfirmDialog } from "./ConfirmDialog";import { Select } from "./Select";@@ -33,7 +34,7 @@ export function CanvasComputers({ open, createRequest, drop, sections, onClose,onDropHandled: () => void;onChange: (computers: TeamComputer[]) => void;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [inventory, setInventory] = useState<Inventory | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState("");diff --git a/src/components/ChatEmptyState.tsx b/src/components/ChatEmptyState.tsxindex b9c308fb08..ce27f9e16f 100644--- a/src/components/ChatEmptyState.tsx+++ b/src/components/ChatEmptyState.tsx@@ -1,4 +1,5 @@-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";import { useAdvancedMode } from "@/lib/interface-mode";import { t } from "@/lib/i18n";import { BotAvatar } from "./Avatar";@@ -6,7 +7,7 @@ import { RenameTitle } from "./RenameTitle";/** A chat with no messages yet: the bot, its name (renamable in Advanced) and what it is for. */export function EmptyChat({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const advanced = useAdvancedMode();return (<div className="flex flex-1 flex-col items-center justify-center gap-3 py-24 text-center">diff --git a/src/components/ChatFindBar.tsx b/src/components/ChatFindBar.tsxindex 0559d980e9..62d815483e 100644--- a/src/components/ChatFindBar.tsx+++ b/src/components/ChatFindBar.tsx@@ -6,10 +6,12 @@ import { t } from "@/lib/i18n";import { imeComposing } from "@/lib/send-key";import type { SearchHit } from "@/lib/search-hit";import { useShowThreads } from "@/lib/thread-preferences";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreRef } from "@/state/store-ref";export function ChatFindBar({ threadId, onClose, inForkPanel = false }: { threadId: string; onClose: () => void; inForkPanel?: boolean }) {- const { state, dispatch } = useStore();+ const storeRef = useStoreRef();+ const dispatch = storeRef.dispatch;const showThreads = useShowThreads();const inputRef = useRef<HTMLInputElement>(null);const requestRef = useRef(0);@@ -56,7 +58,8 @@ export function ChatFindBar({ threadId, onClose, inForkPanel = false }: { threadconst hit = hits[next];if (!hit) return;setIndex(next);- const panel = state.forkPanel;+ const currentState = storeRef.state();+ const panel = currentState.forkPanel;const landing = inForkPanel? (async () => {if (panel?.threadId !== hit.threadId) throw new Error(t("chat.find.unavailable"));@@ -70,7 +73,7 @@ export function ChatFindBar({ threadId, onClose, inForkPanel = false }: { threaddispatch({ type: "focusMessage", threadId: hit.threadId, messageId: hit.messageId,matchText: hit.snippet.slice(hit.matchStart, hit.matchStart + hit.matchLength) });})()- : landOnSearchHit(hit, state, dispatch, showThreads);+ : landOnSearchHit(hit, currentState, dispatch, showThreads);void landing.catch((error) =>dispatch({ type: "error", message: error instanceof Error ? error.message : t("chat.find.unavailable") }),);diff --git a/src/components/ChatView.apps.test.ts b/src/components/ChatView.apps.test.tsindex 120f6ec32b..f5f8b0d56f 100644--- a/src/components/ChatView.apps.test.ts+++ b/src/components/ChatView.apps.test.ts@@ -24,6 +24,8 @@ vi.mock("./ModelPicker", () => ({ ModelPicker: () => createElement("span") }));vi.mock("./ApprovalModeSelector", () => ({ ApprovalModeSelector: () => createElement("span") }));const { ChatView } = await import("./ChatView");+const { LazyAppMessage } = await import("./lazy-overlays");+await LazyAppMessage.preload();afterAll(() => vi.unstubAllGlobals());const message = (id: string, text: string, extra: Partial<Message> = {}): Message =>diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 5778826484..52c51f76de 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -66,7 +66,7 @@ import { NewConversationInstead } from "./NewConversationInstead";import { SkillBurgerSlot } from "./skill-burger/SkillBurgerSlot"; import { useFeature } from "@/lib/use-feature";import { useColorUserBubbles } from "@/lib/user-bubble-preference";import { userBubbleStyle } from "@/lib/user-bubble-tone";-import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard"; import { PublishedSiteCards } from "./published-apps/PublishedSiteCards";+import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { LazyTemplateChatCard } from "./lazy-overlays"; import { PublishedSiteCards } from "./published-apps/PublishedSiteCards";import { ThreadRefText } from "./ThreadRefs"; import { WatchScreenButton } from "./WatchScreenButton";import { optionsCardRow } from "./OptionsCardRow";import { MessageBoundary } from "./MessageBoundary";@@ -680,7 +680,7 @@ const MessagesList = memo(function MessagesList({case "screen":return <ScreenFrame threadId={threadId} message={m} />;default: {- if (m.publishedPage || m.template) return m.template ? <TemplateChatCard message={m} botId={botId} threadId={threadId} /> : <PublishedPageCard message={m} />;+ if (m.publishedPage || m.template) return m.template ? <LazyTemplateChatCard message={m} botId={botId} threadId={threadId} /> : <PublishedPageCard message={m} />;const note = automationNoteRow(m, transcript);if (note) return note;const peer = peerLine(m) ?? peerRequest(m, botId);diff --git a/src/components/ClaudeSignIn.tsx b/src/components/ClaudeSignIn.tsxindex 0a2db970f1..066caba111 100644--- a/src/components/ClaudeSignIn.tsx+++ b/src/components/ClaudeSignIn.tsx@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from "react";+import { useStoreActions } from "@/state/store-select";import { ExternalLink, Loader2, LogIn } from "lucide-react";-import { api, ApiError, useStore } from "@/state/store";+import { api, ApiError } from "@/state/store";import { t } from "@/lib/i18n";import { openExternalLink } from "@/lib/app-links";import { engineSignedIn } from "@/lib/product-events";@@ -43,7 +44,7 @@ export function ClaudeSignIn({ instanceId, autoStart = false, onDone, onStart }:/** A sign-in is starting. */onStart?: () => void;}) {- const { refreshInstances, refreshModels } = useStore();+ const { refreshInstances, refreshModels } = useStoreActions();const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);const [code, setCode] = useState("");const [busy, setBusy] = useState<"start" | "finish" | "cancel" | null>(autoStart ? "start" : null);diff --git a/src/components/ClaudeUpdatePrompt.tsx b/src/components/ClaudeUpdatePrompt.tsxindex 398acd0c70..439627e0e2 100644--- a/src/components/ClaudeUpdatePrompt.tsx+++ b/src/components/ClaudeUpdatePrompt.tsx@@ -1,9 +1,10 @@import { useState } from "react";+import { useStoreActions } from "@/state/store-select";import { Check, Copy, Download, Loader2, RefreshCw, X } from "lucide-react";import { t } from "@/lib/i18n";import { useCopyFeedback } from "@/lib/copy-text";-import { api, useStore, type InstanceInfo } from "@/state/store";+import { api, type InstanceInfo } from "@/state/store";const UPDATE_COMMAND = "claude update";@@ -21,7 +22,7 @@ export function ClaudeUpdatePrompt({instance: InstanceInfo;onRetry?: () => void;}) {- const { refreshInstances } = useStore();+ const { refreshInstances } = useStoreActions();const [phase, setPhase] = useState<Phase>({ kind: "ask" });const { state: copyState, copy: copyCommand } = useCopyFeedback(UPDATE_COMMAND);const copyLabel = t(copyState === "failed" ? "common.copyFailed" : "chat.claudeUpdate.copy");diff --git a/src/components/CloudHowTo.tsx b/src/components/CloudHowTo.tsxindex f3b16dab77..7c09d47d73 100644--- a/src/components/CloudHowTo.tsx+++ b/src/components/CloudHowTo.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from "react";import { track } from "@/lib/analytics";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { NoticeToast } from "./NoticeCard";import { Spotlight } from "./onboarding/Spotlight";@@ -15,10 +15,10 @@ export function switcherPlacement(doc: Pick<Document, "querySelectorAll"> = docu}export function CloudHowTo() {- const { state, dispatch } = useStore();+ const open = useStoreSelector((state) => state.cloudHowTo);+ const dispatch = useStoreDispatch();const [placement, setPlacement] = useState<"below" | "right" | null>(null);const [toast, setToast] = useState<string | null>(null);- const open = state.cloudHowTo;useEffect(() => {if (!open) return;const found = switcherPlacement();diff --git a/src/components/CloudTimeZone.tsx b/src/components/CloudTimeZone.tsxindex 63a68ce57b..0093eaa9ba 100644--- a/src/components/CloudTimeZone.tsx+++ b/src/components/CloudTimeZone.tsx@@ -4,7 +4,8 @@import { useEffect } from "react";import type { WelcomeViewer } from "@/lib/onboarding";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";export function deviceTimeZone(): string | null {try {@@ -25,8 +26,8 @@ export async function syncCloudTimeZone(zone: string | null, request: typeof api}export function CloudTimeZoneSync({ viewer }: { viewer: WelcomeViewer | null }) {- const { state } = useStore();- const due = Boolean(viewer?.cloudHome && viewer.canSave && state.connected);+ const connected = useStoreSelector((state) => state.connected);+ const due = Boolean(viewer?.cloudHome && viewer.canSave && connected);useEffect(() => {if (due) void syncCloudTimeZone(deviceTimeZone()).catch(() => {});}, [due]);diff --git a/src/components/CloudUsageMeter.tsx b/src/components/CloudUsageMeter.tsxindex ee21654d90..b02ff1fb0b 100644--- a/src/components/CloudUsageMeter.tsx+++ b/src/components/CloudUsageMeter.tsx@@ -6,7 +6,7 @@ import type { CloudUsage, CloudUsageMeter } from "../../electron/cloud-home.mjs"import { cloudPlanChanged, useCloudPlanSnapshot } from "./CloudTrialNotice";import { ConfirmDialog } from "./ConfirmDialog";import { Card, SettingsLook, SIMPLE_CARD } from "./SettingsPrimitives";-import { localDesktopPage } from "./onboarding/WelcomeGate";+import { localDesktopPage } from "./onboarding/welcome-viewer";import { cloudPlanLabel } from "@/lib/cloud-plan";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -16,7 +16,7 @@ import {upgradeConfirmBody, upgradeLabel, upgradePath, usageCardView, type MeterBand,} from "@/lib/usage-meter";import type { LocaleKey } from "@/locales";-import { useStore } from "@/state/store";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const TEAM_TIERS: readonly string[] = ["team", "business"];export type UpgradeSource = "app_usage" | "app_settings" | "app_room";@@ -27,10 +27,10 @@ export function usageBridge(cloudHome: boolean): CloudPlanBridge | undefined {}export function useCloudUsage(): { usage: CloudUsage | null; bridge: CloudPlanBridge | undefined; teamHome: boolean } {- const { state } = useStore();- const bridge = usageBridge(state.config?.cloudHome === true);+ const { cloudHome, teamHome } = useStoreSelector((state) => ({ cloudHome: state.config?.cloudHome === true, teamHome: Boolean(state.config?.cloudHome && state.config?.team) }), sameFields);+ const bridge = usageBridge(cloudHome);const plan: CloudPlanSnapshot | null = useCloudPlanSnapshot(bridge);- return { usage: plan?.status === "paid" ? plan.usage ?? null : null, bridge, teamHome: Boolean(state.config?.cloudHome && state.config?.team) };+ return { usage: plan?.status === "paid" ? plan.usage ?? null : null, bridge, teamHome };}export function MeterBar({ meter, label, compact = false }: { meter: CloudUsageMeter; label: string; compact?: boolean }) {@@ -178,7 +178,7 @@ export function CloudUsageCardView({ usage, meters, band, upgrade, onHide, onSee}export function CloudUsageCard() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const advanced = useAdvancedMode();const { usage, bridge, teamHome } = useCloudUsage();const [dismissed, setDismissed] = useState(readUsageCardDismissed);diff --git a/src/components/ComposerPlusMenu.tsx b/src/components/ComposerPlusMenu.tsxindex f473a2d9ed..08677343a7 100644--- a/src/components/ComposerPlusMenu.tsx+++ b/src/components/ComposerPlusMenu.tsx@@ -15,7 +15,7 @@ import { listensHere, missingListenKey, speechBridge } from "@/lib/speech";import { requestCallStart } from "@/lib/call-start-request";import { useOnCall } from "@/lib/call";import { isLiveCallRunning, useLiveMedia } from "@/lib/live-call-media";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useDesktopCapabilities } from "./DesktopCapabilities";@@ -148,15 +148,16 @@ export function ComposerPlusMenu({ onAttach, goal, teach, approval, callBotId, ecallBotId?: string;}) {const { capabilities, ready } = useDesktopCapabilities();- const { state } = useStore();+ const config = useStoreSelector((state) => state.config);+ const liveCall = useStoreSelector((state) => state.liveCall);const storedMode = useCallMode();const onCall = useOnCall();const media = useLiveMedia();- const turnsHere = !ready || listensHere(capabilities, state.config);+ const turnsHere = !ready || listensHere(capabilities, config);const callMode = effectiveCallMode(storedMode, { turnsHere, canLive: true });- const turnsHelp = turnsHere ? null : callCapabilityHelp(capabilities, Boolean(speechBridge(state.config)?.speechStart), missingListenKey(capabilities, state.config));+ const turnsHelp = turnsHere ? null : callCapabilityHelp(capabilities, Boolean(speechBridge(config)?.speechStart), missingListenKey(capabilities, config));// As the call button, which hides while Live is the mode and its line is held on another device.- const lineHeldElsewhere = callMode === "live" && liveLineHeldElsewhere(media, state.liveCall);+ const lineHeldElsewhere = callMode === "live" && liveLineHeldElsewhere(media, liveCall);const calling = callBotId !== undefined && (onCall === callBotId || isLiveCallRunning(media.phase) || lineHeldElsewhere);const simple = !useAdvancedMode();const items: SidebarMenuItem[] = [diff --git a/src/components/ComputerFilesPane.tsx b/src/components/ComputerFilesPane.tsxindex 309c852e8f..1e59367394 100644--- a/src/components/ComputerFilesPane.tsx+++ b/src/components/ComputerFilesPane.tsx@@ -1,6 +1,7 @@import { FileText, FolderOpen } from "lucide-react";+import { useStoreDispatch } from "@/state/store-select";import { useMemo } from "react";-import { useStore, visibleMessages, type Bot } from "@/state/store";+import { visibleMessages, type Bot } from "@/state/store";import { useDesktopCapabilities } from "./DesktopCapabilities";import { collectMessageFiles, fileIdentity, splitMessageAttachments, type GalleryFile } from "./AttachmentGallery";import { AttachedFileChip, type MessageAttachmentContext } from "./AttachmentPreview";@@ -77,7 +78,7 @@ function splitPath(path: string): { name: string; folder: string } {}export function ComputerFilesPane({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { capabilities } = useDesktopCapabilities();const home = capabilities.host.homeDir;const task = bot.tasks?.find((candidate) => candidate.threadId === bot.threadId);diff --git a/src/components/DataResultChip.tsx b/src/components/DataResultChip.tsxindex 078b3a7962..671430d351 100644--- a/src/components/DataResultChip.tsx+++ b/src/components/DataResultChip.tsx@@ -1,19 +1,20 @@import { useId, useState } from "react";import { ArrowUpRight, ChartNoAxesCombined, ChevronRight, Table2 } from "lucide-react";-import { useStore, type Message } from "@/state/store";+import type { Message } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { t } from "@/lib/i18n";import { InlineDataChart } from "./data/InlineDataChart";export function DataResultChip({ message }: { message: Message }) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch();const [expanded, setExpanded] = useState(false);const queryId = useId();const result = message.dataResult;+ const companion = window.ogb?.remoteClient?.active === true;+ const available = useStoreSelector((state) => !companion && Boolean(result) && state.bots.some((bot) => bot.id === result!.botId));if (!result) return null;const chart = result.kind === "chart";const Icon = chart ? ChartNoAxesCombined : Table2;- const companion = window.ogb?.remoteClient?.active === true;- const available = !companion && state.bots.some((bot) => bot.id === result.botId);return (<div data-data-result={result.cardId} className="w-full max-w-[min(var(--chat-prose-max),var(--chat-card-pct))] overflow-hidden rounded-xl border border-hairline/40 bg-panel text-sm"><div className="flex items-center gap-3 px-3 py-2">diff --git a/src/components/DeviceSignIn.tsx b/src/components/DeviceSignIn.tsxindex 9caeb959b7..39ad16578e 100644--- a/src/components/DeviceSignIn.tsx+++ b/src/components/DeviceSignIn.tsx@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from "react";+import { useStoreActions } from "@/state/store-select";import { Check, Copy, ExternalLink, Loader2, LogIn, X } from "lucide-react";-import { api, ApiError, useStore } from "@/state/store";+import { api, ApiError } from "@/state/store";import { intlLocale, t } from "@/lib/i18n";import { openExternalLink } from "@/lib/app-links";import { useCopyFeedback } from "@/lib/copy-text";@@ -186,7 +187,7 @@ export function DeviceSignIn({ instanceId, browserPkce = false, provider = "code/** A sign-in is starting. */onStart?: () => void;}) {- const { refreshInstances, refreshModels } = useStore();+ const { refreshInstances, refreshModels } = useStoreActions();const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);const [busy, setBusy] = useState(autoStart);const started = useRef(false);diff --git a/src/components/EngineAppCopy.tsx b/src/components/EngineAppCopy.tsxindex f7fc1c706f..1721e0a27b 100644--- a/src/components/EngineAppCopy.tsx+++ b/src/components/EngineAppCopy.tsx@@ -1,7 +1,8 @@// An engine whose CLI runs the copy OpenMausBot installed: the person's terminal does not reach it, so it is// finished here, never with a terminal step.+import { useStoreDispatch } from "@/state/store-select";import { Check, KeyRound, X } from "lucide-react";-import { useStore, type InstanceInfo } from "@/state/store";+import { type InstanceInfo } from "@/state/store";import { dismissAppCopySwitch, useAppCopySwitch } from "@/state/engine-install";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -31,7 +32,7 @@ export function AppCopyNotice({ instance, className }: { instance: InstanceInfo;/** Installed but not signed in. Only OpenCode ships such a build today, and its free models need no account. */export function AppCopySetup({ instance, className, unframed }: { instance: InstanceInfo; className?: string; unframed: boolean }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const remote = window.ogb?.remoteClient?.active === true;return (<div data-engine-setup-app-copy className={cn(!unframed && "rounded-xl border border-hairline/40 bg-control/30 p-3", className)}>diff --git a/src/components/EngineBrowserSignIn.tsx b/src/components/EngineBrowserSignIn.tsxindex fc7ccfc8f2..157025b8e5 100644--- a/src/components/EngineBrowserSignIn.tsx+++ b/src/components/EngineBrowserSignIn.tsx@@ -1,8 +1,9 @@// A sign-in whose engine opens the person's browser itself (Mistral Vibe's ACP authenticate): the app starts the// flow, then only polls until the engine reports it done — there is no link or code to show.+import { useStoreActions } from "@/state/store-select";import { useEffect, useRef, useState } from "react";import { Loader2, LogIn } from "lucide-react";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";import { intlLocale, t } from "@/lib/i18n";import { engineSignedIn } from "@/lib/product-events";import { deviceFlowUnavailable, type DeviceSignInStatus } from "./DeviceSignIn";@@ -24,7 +25,7 @@ export function EngineBrowserSignIn({ instanceId, name, autoStart = false, onDon/** A sign-in is starting. */onStart?: () => void;}) {- const { refreshInstances, refreshModels } = useStore();+ const { refreshInstances, refreshModels } = useStoreActions();const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);const [busy, setBusy] = useState(autoStart);const started = useRef(false);diff --git a/src/components/EngineUsage.tsx b/src/components/EngineUsage.tsxindex 277500a7d4..46cd0ed0c0 100644--- a/src/components/EngineUsage.tsx+++ b/src/components/EngineUsage.tsx@@ -10,7 +10,7 @@ import {type EngineLimit, type UsageTone,} from "@/lib/limit-resets";import type { Routine } from "@/lib/routines";-import { api, useStore, type Message } from "@/state/store";+import { api, type Message } from "@/state/store";import { failedTurnNotice } from "@/lib/failed-turn";import { codexUsageLimitReached } from "../../shared/codex-usage-limit";import { openBotSettings } from "./bot-panel/panel-link";@@ -19,7 +19,7 @@ import { threadUpdatedLabel } from "./SidebarThreadRow";/** The stopped turn's "Continue at 3:40 PM when your limit resets": one click sets up a one-time automation in this* conversation that picks up where it stopped. Undefined when there is nothing to offer. */export function useLimitResetContinue(botId: string | undefined, threadId: string | undefined, resetsAt: number | undefined) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [state, setState] = useState<"idle" | "working" | "set">("idle");if (!botId || !threadId || !resetsAt || resetsAt <= Date.now() || state === "set") return undefined;return {@@ -127,7 +127,7 @@ export function UsageRing({ limit, className }: { limit: EngineLimit; className?* clears and a fresh check. */export function UsageRows({ limit }: { limit: EngineLimit }) {const [checking, setChecking] = useState(false);- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const now = Date.now();const checkedAt = limit.checkedAt ?? limitsCheckedAt();return (@@ -271,7 +271,7 @@ export function UsageMenuRows({ engine }: { engine: string | undefined }) {/** A phone's header has no model button: near or at the limit, the bars stand alone and open the bot's model. */export function UsageAlert({ engine }: { engine: string | undefined }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const limit = useEngineUsage(engine);if (!limit || usageTone(limit) === "fine") return null;const line = limitLine(limit, Date.now(), ", ");diff --git a/src/components/FrameBarPinnedPages.tsx b/src/components/FrameBarPinnedPages.tsxindex 0faea8dfdb..c053bf30b2 100644--- a/src/components/FrameBarPinnedPages.tsx+++ b/src/components/FrameBarPinnedPages.tsx@@ -4,7 +4,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode, type RefObject } froimport { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useWebPanels } from "@/lib/web-panel-preferences";-import { useStore } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import type { WebPanel } from "@/lib/web-panels";import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";import { useWindowPlace } from "./WindowPlaceTitle";@@ -36,7 +36,8 @@ export function FrameBarPinnedPages() {const panels = useWebPanels();// Main names the place after this page mounts: until it does, the bar has no place name to keep clear of.const place = useWindowPlace();- const { state, dispatch } = useStore();+ const activeId = useStoreSelector((state) => (state.activeView === "web-panel" ? state.webPanelId : undefined));+ const dispatch = useStoreDispatch();const wrapRef = useRef<HTMLDivElement>(null);const measureRef = useRef<HTMLDivElement>(null);const [roomy, setRoomy] = useState(false);@@ -67,7 +68,6 @@ export function FrameBarPinnedPages() {}, [panels, place]);if (!panels.length) return null;- const activeId = state.activeView === "web-panel" ? state.webPanelId : undefined;const open = (id: string) => dispatch({ type: "showWebPanel", id });const items: SidebarMenuItem[] = panels.map((panel) => ({key: panel.id,diff --git a/src/components/GoalRunCard.tsx b/src/components/GoalRunCard.tsxindex a979972793..7a3543cb68 100644--- a/src/components/GoalRunCard.tsx+++ b/src/components/GoalRunCard.tsx@@ -1,4 +1,5 @@import { routineLineText } from "@/lib/activity-text";+import { useStoreDispatch } from "@/state/store-select";import {CheckCircle2,CircleAlert,@@ -10,7 +11,7 @@ import {import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Message } from "@/state/store";+import { type Message } from "@/state/store";import type { GroupGoalRunCardData } from "../../shared/group-goal-run";import type { LocaleKey } from "@/locales";@@ -137,7 +138,7 @@ export function GoalRunCard({ message, solo = false, onStop }: { message: Messag}export function GoalRunRow({ botId, threadId, message }: { botId: string; threadId?: string; message: Message }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return (<div className="flex justify-start"><GoalRunCard message={message} solo onStop={() => dispatch({ type: "interrupt", botId, threadId })} />diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex 6022c6b06c..c39e9e8ec0 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -70,7 +70,7 @@ import { NewMessagesDivider } from "./NewMessagesDivider";import { appendDraftAttachments, useReplyDraft } from "@/lib/drafts";import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer";import { pendingApprovals } from "./PendingApproval";-import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard"; import { RoomRichRow } from "./RichMessageRow";+import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { LazyTemplateChatCard } from "./lazy-overlays"; import { RoomRichRow } from "./RichMessageRow";import { TranscriptAnnouncer } from "./TranscriptAnnouncer";import { dayLabel, localDay } from "@/lib/transcript-derivations";import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";@@ -285,7 +285,7 @@ export const Transcript = memo(function Transcript({<CompactionChip message={m} />) : m.kind === "digest" ? (showToolCalls ? <DigestChip message={m} /> : null- ) : (m.kind === "app" || m.kind === "widget") && m.from ? <RoomRichRow message={m} from={m.from} threadId={group.threadId} /> : m.template ? <TemplateChatCard message={m} /> : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length || isLiveReply(m)) ? (+ ) : (m.kind === "app" || m.kind === "widget") && m.from ? <RoomRichRow message={m} from={m.from} threadId={group.threadId} /> : m.template ? <LazyTemplateChatCard message={m} /> : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length || isLiveReply(m)) ? (!user && isPureLeakedSystemHarnessMessage(m.text) && !m.attachments?.length ? null : (textRow(m, m.id === emergingId, m.id === newestMessageId || m.id === newestUserMessageId))diff --git a/src/components/HelperKeySuggestion.tsx b/src/components/HelperKeySuggestion.tsxindex 3742ae639e..58dd581123 100644--- a/src/components/HelperKeySuggestion.tsx+++ b/src/components/HelperKeySuggestion.tsx@@ -1,16 +1,17 @@// The proactive bot's one suggestion to add a helper-model key (server/host/helper-suggestion.ts), in the person's own// language. A suggestion, not an approval: Add key opens Settings on this device, Not now is kept and ends it. Labelled as// the app's own tip, with what the key and Jev are, so it never reads as an unattributed message from a stranger.+import { useStoreDispatch } from "@/state/store-select";import { useState } from "react";import { Lightbulb, Loader2 } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { api, useStore, type Message } from "@/state/store";+import { api, type Message } from "@/state/store";import { ASK_PRIMARY_BUTTON, ASK_QUIET_BUTTON } from "./AskCard";export function HelperKeySuggestion({ threadId, message }: { threadId?: string; message: Message }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const declined = message.setupSuggestion?.answer === "notNow";diff --git a/src/components/HomeLine.tsx b/src/components/HomeLine.tsxindex 17bcc5e6bf..088a4be5f1 100644--- a/src/components/HomeLine.tsx+++ b/src/components/HomeLine.tsx@@ -9,7 +9,8 @@ import { HOME_LINE_NOTICE, homeLineShown, homeLineStage } from "@/lib/notices";import { hintSeenPatch } from "@/lib/onboarding";import { computerName } from "@/lib/places";import { setNotificationPlace } from "@/lib/notify";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";type Line = { kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile"; name?: string };@@ -38,10 +39,11 @@ function ConnectAiLink() {* a few days (homeLineStage); connecting an AI stays offered while none is ready. */export function HomeLine() {const bridge = !window.ogb?.remoteClient?.active ? window.ogb?.workspaces : undefined;- const { state, dispatch } = useStore();+ const record = useStoreSelector((state) => state.config?.onboarding);+ const instances = useStoreSelector((state) => state.instances);+ const dispatch = useStoreDispatch();const [line, setLine] = useState<Line | null>(null);const [closed, setClosed] = useState(false);- const record = state.config?.onboarding;const informational = line?.kind === "profile";const stage = informational && record ? homeLineStage(record, Date.now()) : null;const save = (patch: ReturnType<typeof homeLineShown>) => {@@ -59,7 +61,7 @@ export function HomeLine() {if (!line) return null;// Until this workspace's config says how often the words were shown, they wait, so a line already closed never flashes.const words = !informational || (stage === "due" && !closed);- const aiMissing = line.kind !== "left" && !state.instances.some((instance) => engineReady(instance) && !freeFallback(instance));+ const aiMissing = line.kind !== "left" && !instances.some((instance) => engineReady(instance) && !freeFallback(instance));if (!words && !aiMissing) return null;return <div role="status" data-home-line={line.kind} className={`relative flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-hairline/40 bg-panel ${informational ? "px-8" : "px-3"} py-1.5 text-[13px] text-ink-secondary`}>{line.kind === "clean" ? <Cloud size={14} aria-hidden="true" /> : line.kind === "profile" ? <Laptop size={14} aria-hidden="true" /> : <Users size={14} aria-hidden="true" />}diff --git a/src/components/ImportDialog.tsx b/src/components/ImportDialog.tsxindex 02f1d59b3c..361e77461b 100644--- a/src/components/ImportDialog.tsx+++ b/src/components/ImportDialog.tsx@@ -1,4 +1,5 @@import { useEffect, useId, useRef, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { FolderOpen, Loader2, Trash2 } from "lucide-react";import type { TeamTemplate, TemplateDetails } from "../../shared/share-card";@@ -6,7 +7,7 @@ import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { relativeTime } from "@/lib/memory";import { addImport, addedLine, folderFiles, previewImport, removeTeamTemplate, teamTemplates, type ImportSource } from "@/lib/template-share";-import { useStore } from "@/state/store";+import { SETTINGS_INPUT } from "./SettingsPrimitives";import { TemplateDetailsBody, TemplateModal, useTeamTemplatesOwner } from "./TemplateCard";@@ -64,7 +65,7 @@ function TeamTemplateList({ team, onOpen, disabled }: { team: string; onOpen: (s/** Import: paste a GitHub link or choose a folder, see what it brings, then Add. `onAdded` gets the line to show. */export function ImportDialog({ initialUrl, onClose, onAdded }: { initialUrl?: string; onClose: () => void; onAdded: (line: string) => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [url, setUrl] = useState(initialUrl ?? "");const [source, setSource] = useState<ImportSource | null>(null);const [details, setDetails] = useState<TemplateDetails | null>(null);diff --git a/src/components/InspectorPanel.tsx b/src/components/InspectorPanel.tsxindex ba3e005d03..38d7f6b9b9 100644--- a/src/components/InspectorPanel.tsx+++ b/src/components/InspectorPanel.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { Bug, ChevronDown, ChevronRight, RefreshCw, X } from "lucide-react";-import { useStore, visibleMessages, type Bot } from "@/state/store";+import { visibleMessages, type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";import { formatTime, toRows, type InspectorPage, type InspectorRow } from "@/lib/inspector";@@ -23,7 +24,7 @@ type Lens = "run" | "events" | "raw";* Native expansion resets on a loaded snapshot: its positional keys are not identities.*/export function InspectorPanel({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { dragProps } = useCaptionChrome();const threadId = bot.threadId;const [lens, setLens] = useState<Lens>("run");diff --git a/src/components/LiveCallBar.tsx b/src/components/LiveCallBar.tsxindex c27b4c357d..860cac3e34 100644--- a/src/components/LiveCallBar.tsx+++ b/src/components/LiveCallBar.tsx@@ -7,7 +7,8 @@ import {dismissLiveNotice, hangUpLiveCall, isLiveCallRunning, liveCallChord, setLiveMuted, takeLiveCallAction, useLiveMedia,type LiveCallAction, type LiveMediaState,} from "@/lib/live-call-media";-import { api, liveCallFromFrame, nextLiveCallLookup, useStore, type Action, type Bot } from "@/state/store";+import { api, liveCallFromFrame, nextLiveCallLookup, type Action, type Bot } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { cn } from "@/lib/cn";import type { LiveCallState, LiveClient } from "../../shared/wire";import { LiveCallSettings } from "./LiveCallSettings";@@ -84,13 +85,15 @@ export async function hangUpRemoteCall(}export function LiveCallBar({ bot }: { bot: Bot }) {- const { state, dispatch } = useStore();+ const liveCall = useStoreSelector((state) => state.liveCall);+ const liveCallVersion = useStoreSelector((state) => state.liveCallVersion);+ const dispatch = useStoreDispatch();const media = useLiveMedia();const [now, setNow] = useState(() => Date.now());const [settingsOpen, setSettingsOpen] = useState(false);const rootRef = useRef<HTMLDivElement>(null);const gearRef = useRef<HTMLButtonElement>(null);- const view = liveCallBarView({ bot, media, server: state.liveCall, now });+ const view = liveCallBarView({ bot, media, server: liveCall, now });const kind = view?.kind;useEffect(() => {@@ -147,7 +150,7 @@ export function LiveCallBar({ bot }: { bot: Bot }) {type="button"aria-label={t("call.live.hangUp")}className={cn(button, "bg-danger text-white hover:brightness-110")}- onClick={() => void hangUpRemoteCall(callId, state.liveCallVersion, dispatch)}+ onClick={() => void hangUpRemoteCall(callId, liveCallVersion, dispatch)}><PhoneOff className="size-3.5" /> <span className="hidden sm:inline">{t("call.live.hangUp")}</span></button>diff --git a/src/components/LiveCallHost.tsx b/src/components/LiveCallHost.tsxindex 4ac32371fe..777de2d699 100644--- a/src/components/LiveCallHost.tsx+++ b/src/components/LiveCallHost.tsx@@ -2,13 +2,14 @@ import { useEffect } from "react";import { useReportCallPresence } from "@/lib/call-presence";import { isMacPlatform } from "@/lib/keyboard-shortcuts";import { handleLiveCallKey, onLiveStreamConnected, onServerCall } from "@/lib/live-call-media";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";export function LiveCallHost() {- const { state } = useStore();+ const liveCall = useStoreSelector((state) => state.liveCall);+ const connected = useStoreSelector((state) => state.connected);useReportCallPresence();- useEffect(() => onServerCall(state.liveCall), [state.liveCall]);- useEffect(() => onLiveStreamConnected(state.connected), [state.connected]);+ useEffect(() => onServerCall(liveCall), [liveCall]);+ useEffect(() => onLiveStreamConnected(connected), [connected]);useEffect(() => {const isMac = isMacPlatform();const onKey = (event: KeyboardEvent) => {diff --git a/src/components/LiveCallPill.tsx b/src/components/LiveCallPill.tsxindex 8c2a82a500..0b6f54cb48 100644--- a/src/components/LiveCallPill.tsx+++ b/src/components/LiveCallPill.tsx@@ -3,7 +3,7 @@ import { t } from "@/lib/i18n";import { cn } from "@/lib/cn";import { isMacPlatform } from "@/lib/keyboard-shortcuts";import { hangUpLiveCall, isLiveCallRunning, liveCallChord, setLiveMuted, useLiveMedia, type LiveMediaState } from "@/lib/live-call-media";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import type { LiveCallState } from "../../shared/wire";export function liveBadgeFor(botId: string, media: LiveMediaState, server: LiveCallState | null): boolean {@@ -12,10 +12,9 @@ export function liveBadgeFor(botId: string, media: LiveMediaState, server: LiveC}function useCallElsewhere(currentBotId: string | null) {- const { state } = useStore();const media = useLiveMedia();const active = isLiveCallRunning(media.phase);- const bot = active ? state.bots.find((candidate) => candidate.id === media.botId) : undefined;+ const bot = useStoreSelector((state) => (active ? state.bots.find((candidate) => candidate.id === media.botId) : undefined));const onScreen = Boolean(bot && bot.id === currentBotId && bot.threadId === media.threadId);return { media, bot: onScreen ? undefined : bot, threadId: media.threadId };}diff --git a/src/components/MapComposer.tsx b/src/components/MapComposer.tsxindex cc8b0946d1..2f603fe4c0 100644--- a/src/components/MapComposer.tsx+++ b/src/components/MapComposer.tsx@@ -1,6 +1,7 @@import { useEffect, useMemo, useRef, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { ArrowUp, X } from "lucide-react";-import { openBot, useStore, type Bot } from "@/state/store";+import { openBot, type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { mentionChoicesForQuery, mentionQueryAt } from "@/lib/mentions";@@ -22,7 +23,7 @@ export function MapComposer({ bots, teams, onTagged, onSent }: {/** The bots a message just went to, so their cards can acknowledge it. */onSent: (botIds: string[]) => void;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const showThreads = useShowThreads();const sendKey = useSendKey();const inputRef = useRef<HTMLTextAreaElement>(null);diff --git a/src/components/NewTaskFolderDialog.tsx b/src/components/NewTaskFolderDialog.tsxindex fbd03a8da0..3b0a85b46d 100644--- a/src/components/NewTaskFolderDialog.tsx+++ b/src/components/NewTaskFolderDialog.tsx@@ -1,13 +1,14 @@import { useEffect, useRef, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { createPortal } from "react-dom";import { FolderOpen } from "lucide-react";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { t } from "@/lib/i18n";import { useModalDialog } from "@/hooks/use-modal-dialog";/** A pin is chosen while creating a thread, never by moving the working directory of an existing provider session. */export function NewTaskFolderDialog({ bot, onClose, onReturnFocus }: { bot: Bot; onClose: () => void; onReturnFocus?: () => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [cwd, setCwd] = useState(bot.cwd ?? "");const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);diff --git a/src/components/OpenFilesButton.tsx b/src/components/OpenFilesButton.tsxindex 0a6a8127f3..93aeee8286 100644--- a/src/components/OpenFilesButton.tsx+++ b/src/components/OpenFilesButton.tsx@@ -1,7 +1,7 @@-import { useStore } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";/** Opens Files, offering `suggest` (folders on this computer) for sharing. Render it only where cloudFilesBridge() is. */export function OpenFilesButton({ label, suggest, className = "ui-button" }: { label: string; suggest?: string[]; className?: string }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return <button type="button" className={className} onClick={() => dispatch({ type: "showFiles", ...(suggest ? { suggest } : {}) })}>{label}</button>;}diff --git a/src/components/PendingApproval.tsx b/src/components/PendingApproval.tsxindex c16bf3d8f2..24c5688665 100644--- a/src/components/PendingApproval.tsx+++ b/src/components/PendingApproval.tsx@@ -1,6 +1,7 @@import { memo, useState, type ReactNode } from "react";+import { useStoreDispatch } from "@/state/store-select";import { ChevronDown, Monitor, Send, ShieldCheck, TriangleAlert } from "lucide-react";-import { useStore, type Bot, type Message } from "@/state/store";+import { type Bot, type Message } from "@/state/store";import { cn } from "@/lib/cn";import { t, tFromServer } from "@/lib/i18n";import type { LocaleKey } from "@/locales";@@ -262,7 +263,7 @@ export function PendingApprovalActions({/** Marks each answer for the surface that shows it, as data-<tag>-action. */tag?: string;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const ownerOrAdmin = useOwnerOrAdmin();const isRoutineRequest = isRoutineApproval(pending);const isSkillRequest = isSkillApproval(pending);diff --git a/src/components/ProIntroduction.tsx b/src/components/ProIntroduction.tsxindex 37f57fd8e0..1b4d2e5ee3 100644--- a/src/components/ProIntroduction.tsx+++ b/src/components/ProIntroduction.tsx@@ -1,7 +1,8 @@import { useEffect, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { Cloud, Crown } from "lucide-react";import type { CloudAccountState } from "../../electron/cloud-account.mjs";-import { useStore } from "@/state/store";+import { buyOfferAllowed, cloudPlanLine, cloudPlanView, moneyBackLine, offerTrialDays, usd, type CloudPlanView } from "@/lib/cloud-plan";import { useCloudOffer } from "@/lib/use-cloud-offer";import { t } from "@/lib/i18n";@@ -27,7 +28,7 @@ export function useCloudPlan(): { view: CloudPlanView; account: CloudAccountStat}export function ProSettingsCard() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const plan = useCloudPlan();const offering = plan !== null && buyOfferAllowed(plan.view);const offer = useCloudOffer(offering, plan?.account?.offer);@@ -69,7 +70,7 @@ export function ProSettingsCard() {}export function CloudPlanRow({ place, usage = null, upgrade }: { place: "account" | "plan"; usage?: CloudUsage | null; upgrade?: UpgradeUi }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const plan = useCloudPlan();const offering = plan !== null && buyOfferAllowed(plan.view);const offer = useCloudOffer(offering, plan?.account?.offer);@@ -112,6 +113,6 @@ export function CloudPlanFootnote() {/** Plan & billing's own row for the plans on offer. */export function ProCompareRow() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return <SettingsLinkRow title={t("pro.seePlans")} onClick={() => dispatch({ type: "openCloudAdd", source: "app_settings" })} data={{ "data-plan-compare": "" }} />;}diff --git a/src/components/PublishedPageCard.tsx b/src/components/PublishedPageCard.tsxindex e3349b16f5..4599e9d8b8 100644--- a/src/components/PublishedPageCard.tsx+++ b/src/components/PublishedPageCard.tsx@@ -1,4 +1,5 @@import { useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { ArrowUpRight, Check, Copy, Globe, Loader2, Lock, X } from "lucide-react";import type { PublishedPageCard as Card } from "../../shared/published-page";import { cloudPlanLabel } from "@/lib/cloud-plan";@@ -6,7 +7,7 @@ import { cn } from "@/lib/cn";import { useCopyFeedback } from "@/lib/copy-text";import { usePageOpener } from "@/lib/page-open";import { t } from "@/lib/i18n";-import { api, useStore, type Message } from "@/state/store";+import { api, type Message } from "@/state/store";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_PRIMARY_BUTTON } from "./AskCard";const usageLine = (card: Card) => card.usage ? t("chat.page.usage", { pages: card.usage.pages, limit: card.usage.limit }) : null;@@ -20,7 +21,7 @@ function limitLine(card: Card): string {/** A page a bot published: its link, Copy link, Open and Unpublish; or, at the plan's limit, why not and where to get more.* The link and Open both open the page (usePageOpener): never a message, a turn or a chat. */export function PublishedPageCard({ message }: { message: Message }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const card = message.publishedPage;const { state: copied, copy } = useCopyFeedback(card?.url ?? "");const [busy, setBusy] = useState(false);diff --git a/src/components/QuestionCard.tsx b/src/components/QuestionCard.tsxindex 9439bd6673..c9bf2c6a30 100644--- a/src/components/QuestionCard.tsx+++ b/src/components/QuestionCard.tsx@@ -1,8 +1,9 @@// A bot's question to the person, whatever asked it: a pick from its choices, its own words, or both. The same card// answers in the chat, in the inbox's copy of it and in the inbox panel.+import { useStoreDispatch } from "@/state/store-select";import { useMemo, useState } from "react";import { Check } from "lucide-react";-import { useStore, type Message } from "@/state/store";+import { type Message } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import {@@ -95,7 +96,7 @@ export function QuestionCard({/** The person has written in the chat since: the choices recede, and still answer. */typedPast?: boolean;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const origin = useInboxOrigin(message);const card = message.card;const questions = useMemo(() => (card ? cardQuestions(card) : []), [card]);@@ -232,7 +233,7 @@ export const decidedByBot = (card: NonNullable<Message["card"]>): boolean =>card.answeredBy?.kind === "bot" && card.answered === "answer" && !card.dismissed && !card.expired && !card.stopped;function DecidedQuestion({ threadId, asker, card, questions }: { threadId: string; asker?: Asker; card: NonNullable<Message["card"]>; questions: readonly AskQuestion[] }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [open, setOpen] = useState(false);const [draft, setDraft] = useState("");const [state, setState] = useState<"idle" | "sending" | "failed">("idle");diff --git a/src/components/RemoteAgentSettingsPanel.tsx b/src/components/RemoteAgentSettingsPanel.tsxindex 827681ee9f..cfc9d983de 100644--- a/src/components/RemoteAgentSettingsPanel.tsx+++ b/src/components/RemoteAgentSettingsPanel.tsx@@ -1,7 +1,8 @@import { useRef, useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { Bell, ChevronLeft, ImagePlus, Loader2, Trash2, X } from "lucide-react";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";import { VoiceSettings } from "./VoiceSettings";@@ -20,7 +21,7 @@ export function RemoteAgentSettingsPanel({ bot, overlay = false }: {bot: Bot;overlay?: boolean;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { dragProps } = useCaptionChrome();const [saving, setSaving] = useState(false);const [error, setError] = useState("");diff --git a/src/components/RichMessageRow.tsx b/src/components/RichMessageRow.tsxindex 37462fac3a..3789b09938 100644--- a/src/components/RichMessageRow.tsx+++ b/src/components/RichMessageRow.tsx@@ -1,15 +1,14 @@import { AppWindow, Crosshair } from "lucide-react";import type { Message } from "@/state/store";import { t } from "@/lib/i18n";-import { AppMessage } from "./app/AppMessage";import { BugReportNote } from "./BugReportNote";import { BurstCard } from "./BurstCard";import { EmailDraftCard } from "./EmailDraftCard";import { GoalRunRow } from "./GoalRunCard";import { HelperKeySuggestion } from "./HelperKeySuggestion";+import { LazyAppMessage, LazyWidgetMessage } from "./lazy-overlays";import { MessageBoundary } from "./MessageBoundary";import { SettingsCard } from "./SettingsCard";-import { WidgetMessage } from "./widget/WidgetMessage";export function richRowKind(message: Message): Message["kind"] {// MausBot's follow-up is text the model reads, drawn under its intro's card row (OptionsCardRow).@@ -35,8 +34,8 @@ export function RichMessageRow({ botId, botName, threadId, message, room }: { bo: message.kind === "goal.run"? <GoalRunRow botId={botId} threadId={threadId} message={message} />: message.kind === "app"- ? <AppMessage botId={botId} botName={botName} threadId={threadId} message={message} room={room} />- : <WidgetMessage botId={botId} threadId={threadId} message={message} viewOnly={room} />}+ ? <LazyAppMessage botId={botId} botName={botName} threadId={threadId} message={message} room={room} />+ : <LazyWidgetMessage botId={botId} threadId={threadId} message={message} viewOnly={room} />}</MessageBoundary>);}@@ -73,5 +72,5 @@ export function UserLineNote({ message }: { message: Message }) {}if (message.via === "api") return <span data-via-bot-api className="mt-1 text-[11px] text-ink-tertiary" title={t("chat.viaBotApi")}>{t("chat.viaBotApi")}</span>;if (message.via !== "call") return null;- return <span className="mt-1 text-[11px] text-ink-tertiary" title={t("chat.viaCall")}>{t("chat.viaCall")}</span>;+ return <span data-via-call className="mt-1 text-[11px] text-ink-tertiary" title={t("chat.viaCall")}>{t("chat.viaCall")}</span>;}diff --git a/src/components/RoomBulletin.tsx b/src/components/RoomBulletin.tsxindex b30061d8cf..ed56299b8e 100644--- a/src/components/RoomBulletin.tsx+++ b/src/components/RoomBulletin.tsx@@ -1,12 +1,13 @@import { useEffect, useRef, useState, type KeyboardEvent } from "react";+import { useStoreDispatch } from "@/state/store-select";import { Pin } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Group } from "@/state/store";+import { type Group } from "@/state/store";export function useBulletinEditor(group: Group) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [open, setOpen] = useState(false);const [draft, setDraft] = useState(group.bulletin);const settled = useRef(false);diff --git a/src/components/RoomChiefAbsent.tsx b/src/components/RoomChiefAbsent.tsxindex c67962b20b..3430b22dfb 100644--- a/src/components/RoomChiefAbsent.tsx+++ b/src/components/RoomChiefAbsent.tsx@@ -1,11 +1,12 @@import { useState } from "react";+import { useStoreDispatch } from "@/state/store-select";import { t } from "@/lib/i18n";-import { api, useStore, type Group } from "@/state/store";+import { api, type Group } from "@/state/store";/** One line in a room its department's Chief of Staff is not in: why its work stops for approvals, and the way to add it. */export function RoomChiefAbsent({ group }: { group: Group }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [busy, setBusy] = useState(false);const chief = group.chiefAbsent;if (!chief) return null;diff --git a/src/components/RoomHoldsBanner.tsx b/src/components/RoomHoldsBanner.tsxindex 7624adee81..84085387b9 100644--- a/src/components/RoomHoldsBanner.tsx+++ b/src/components/RoomHoldsBanner.tsx@@ -1,10 +1,11 @@import { Pause } from "lucide-react";+import { useStoreDispatch } from "@/state/store-select";import { t } from "@/lib/i18n";-import { useStore, type Bot, type Group } from "@/state/store";+import { type Bot, type Group } from "@/state/store";export function RoomHoldsBanner({ group, members }: { group: Group; members: Bot[] }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const held = members.filter((member) => group.holds?.[member.id]);if (!held.length) return null;return (diff --git a/src/components/RoomMoreMenu.tsx b/src/components/RoomMoreMenu.tsxindex 7faa7a58a7..f7cb539428 100644--- a/src/components/RoomMoreMenu.tsx+++ b/src/components/RoomMoreMenu.tsx@@ -1,4 +1,5 @@import { useState, type JSX } from "react";+import { useStoreDispatch } from "@/state/store-select";import { Copy, Download, Gauge, MessagesSquare, MoreHorizontal, Search, SquarePen, Timer } from "lucide-react";import { requestChatFind, useChatFindOpen } from "@/lib/chat-find";@@ -12,7 +13,7 @@ import { conversationTranscript } from "@/lib/conversation-transcript";import { t } from "@/lib/i18n";import { localizedTaskTitle } from "@/lib/task-title";import { useShowThreads } from "@/lib/thread-preferences";-import { useStore, type Group } from "@/state/store";+import { type Group } from "@/state/store";import { PRESET_TURN_LIMITS, useConversationTurnLimit } from "./ConversationTurnLimit";import { groupUsageSummary } from "./GroupUsageChip";import { ShortcutHint } from "./ShortcutHint";@@ -31,7 +32,7 @@ function turnLimitLabel(minutes: number): string {}function useRoomMoreItems(group: Group): { items: SidebarMenuItem[]; on: boolean } {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const showThreads = useShowThreads();const findOpen = useChatFindOpen(group.threadId);const limit = useConversationTurnLimit(group);diff --git a/src/components/SecretRequestCard.tsx b/src/components/SecretRequestCard.tsxindex 0a288c7da7..22d56a064b 100644--- a/src/components/SecretRequestCard.tsx+++ b/src/components/SecretRequestCard.tsx@@ -1,4 +1,5 @@import { useState, type FormEvent } from "react";+import { useStoreDispatch } from "@/state/store-select";import { ExternalLink, KeyRound, Loader2, LockKeyhole, RefreshCw, X } from "lucide-react";import { CUSTOM_SECRET_TARGET, credentialResumeOutcome, credentialSaveRequest, desktopCredentialSlot, isConfigCredentialTarget, isProviderCredentialTarget } from "../../shared/credential-request";@@ -6,7 +7,7 @@ import { credentialProvider } from "@/lib/analytics-allowlist";import { cn } from "@/lib/cn";import { activeLocale, t } from "@/lib/i18n";import { keySaved, keySaveFailure, savedKeyResult } from "@/lib/product-events";-import { api, useStore, type Bot, type ConfigStatus, type Message } from "@/state/store";+import { api, type Bot, type ConfigStatus, type Message } from "@/state/store";import { ASK_FIELD, askPrimary, ASK_QUIET_BUTTON, AskCard, AskSettledLine, returnFocusToComposer } from "./AskCard";import { EmailConnectForm, type EmailConnectRefusal } from "./EmailCard";import { EmailOutgoingRequestForm, EmailRequestSettled } from "./EmailRequestCard";@@ -30,7 +31,7 @@ export function SecretRequestCard({threadId: string;message: Message;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const secret = message.secret!;const localize = activeLocale() !== "en";const greenference = localize && secret.target === "greenferenceApiKey";diff --git a/src/components/SoulField.tsx b/src/components/SoulField.tsxindex f4d8a0bf0c..a2313745ed 100644--- a/src/components/SoulField.tsx+++ b/src/components/SoulField.tsx@@ -1,9 +1,10 @@import { useEffect, useId, useRef, useState, type ReactNode, type TextareaHTMLAttributes } from "react";+import { useStoreActions } from "@/state/store-select";import { BOT_PROFILE_LIMITS } from "../../shared/bot-profile";import { cn } from "@/lib/cn";import { firstSentence, soulPatchFor, utf8Bytes } from "@/lib/soul";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { useModalDialog } from "@/hooks/use-modal-dialog";import { useAdvancedMode } from "@/lib/interface-mode";import { Layer } from "./Layer";@@ -22,7 +23,7 @@ export function SoulField({onPatch: (patch: { soul?: string; description?: string }) => void;simple?: { label: string; placeholder: string };}) {- const { dispatch, flushBotPatches } = useStore();+ const { dispatch, flushBotPatches } = useStoreActions();const { request: api } = useBotEditor();const limit = BOT_PROFILE_LIMITS.soul;const [draft, setDraft] = useState(bot.soul ?? "");diff --git a/src/components/StatusActivityRow.tsx b/src/components/StatusActivityRow.tsxindex ca6cac00a3..0637061b37 100644--- a/src/components/StatusActivityRow.tsx+++ b/src/components/StatusActivityRow.tsx@@ -1,8 +1,9 @@import { Brain, Info, RefreshCw } from "lucide-react";+import { useStoreDispatch } from "@/state/store-select";import { statusActivity } from "@/lib/activity-runs";import { isSavedToThreadLine } from "@/lib/activity-text";import { t } from "@/lib/i18n";-import { useStore, type Message } from "@/state/store";+import { type Message } from "@/state/store";import { bugReportFixedText } from "./BugReportNote";import { CancelledTurnRow } from "./CancelledTurnRow";import { FirstReplyRescueRow } from "./FirstReplyRescueRow";@@ -10,7 +11,7 @@ import { FirstReplyRescueRow } from "./FirstReplyRescueRow";const pill = "rounded-full border border-hairline/40 px-2.5 py-1 text-[13px] text-ink hover:bg-raised";export function StatusActivityRow({ message }: { message: Message }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const status = statusActivity(message);if (!status) return null;if (status.kind === "stopped") return <CancelledTurnRow name={message.tool?.name} stoppedBy={message.stoppedBy} />;diff --git a/src/components/TeamLibraryPanel.tsx b/src/components/TeamLibraryPanel.tsxindex a21ca13bd8..1948d5a91a 100644--- a/src/components/TeamLibraryPanel.tsx+++ b/src/components/TeamLibraryPanel.tsx@@ -1,4 +1,5 @@import { track } from "@/lib/analytics";+import { useStoreDispatch } from "@/state/store-select";import { t } from "@/lib/i18n";import { addTemplate } from "@/lib/template-add";import { addImport, previewImport } from "@/lib/template-share";@@ -8,7 +9,7 @@ import type { PackageDocument } from "../../shared/package-format";import { COMMUNITY_REPOSITORY_URL, type TemplateDetails } from "../../shared/share-card";import type { Routine } from "@/lib/routines";import { openExternalLink } from "@/lib/app-links";-import { api, useStore, type Bot, type Group } from "@/state/store";+import { api, type Bot, type Group } from "@/state/store";import { ArrowLeft, Check, ExternalLink, Github, Loader2, Search, X } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";@@ -44,7 +45,7 @@ export function TeamLibraryPanel({onImported: (result: TeamImportResult) => void;returnFocusRef: React.RefObject<HTMLButtonElement | null>;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const dialogRef = useRef<HTMLDivElement>(null);const galleryErrorRef = useRef<HTMLDivElement>(null);const [catalog, setCatalog] = useState<TeamCatalog | null>(null);diff --git a/src/components/TemplateCard.test.ts b/src/components/TemplateCard.test.tsindex 4967010a9c..0f36c6438e 100644--- a/src/components/TemplateCard.test.ts+++ b/src/components/TemplateCard.test.ts@@ -15,7 +15,7 @@ vi.mock("@/state/store", async () => {return { StoreContext: createContext(null), useStore: () => ({ state: place.state, dispatch }), api: (path: string, init?: RequestInit) => api(path, init) };});vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => place.admin }));-vi.mock("@/state/store-select", () => ({ useStoreSelector: <T,>(select: (state: never) => T) => select(place.state as never) }));+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => dispatch, useStoreSelector: <T,>(select: (state: never) => T) => select(place.state as never) }));vi.mock("@/lib/session", () => ({readSessionState: async () => ({ kind: "loopback" }),profileForSession: (profile: { name?: string } | undefined, session: unknown) => (session && place.own ? profile : undefined),diff --git a/src/components/TemplateCard.tsx b/src/components/TemplateCard.tsxindex 92a932e34f..61e179b53b 100644--- a/src/components/TemplateCard.tsx+++ b/src/components/TemplateCard.tsx@@ -15,8 +15,8 @@ import { addToTeamTemplates, askBot, countsLine, creditShown, deleteTemplate, doimport { profileForSession, readSessionState, type SessionState } from "@/lib/session";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { useModalDialog } from "@/hooks/use-modal-dialog";-import { useStore, type Message } from "@/state/store";-import { useStoreSelector } from "@/state/store-select";+import { type Message } from "@/state/store";+import { useStoreSelector, useStoreDispatch } from "@/state/store-select";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_PRIMARY_BUTTON } from "./AskCard";import { BotAvatar } from "./Avatar";import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";@@ -246,7 +246,7 @@ export function useRepoPublishOffered(): boolean {/** The template card a bot posts in its chat. `botId` and `threadId` are this chat's, for Update; a group chat leaves them out. */export function TemplateChatCard({ message, botId, threadId }: { message: Message; botId?: string; threadId?: string }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const actions = useTemplateActions(message.template!);const [details, setDetails] = useState(false);const [repo, setRepo] = useState(false);@@ -391,7 +391,7 @@ const repoField = "h-8 w-full min-w-0 rounded-lg border border-hairline bg-insetconst repoSpinner = <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />;export function TemplateRepoPublishDialog({ card, onClose }: { card: Pick<TemplateCard, "id" | "name">; onClose: () => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [connection, setConnection] = useState<Connection>({ state: "checking" });const [repo, setRepo] = useState("");const [folder, setFolder] = useState("");diff --git a/src/components/TrialCreditNotice.tsx b/src/components/TrialCreditNotice.tsxindex 1edefbf2a2..a529a9f82e 100644--- a/src/components/TrialCreditNotice.tsx+++ b/src/components/TrialCreditNotice.tsx@@ -1,10 +1,11 @@import { Info } from "lucide-react";+import { useStoreDispatch } from "@/state/store-select";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";+/** A turn the trial credit could no longer pay for: a quiet note with the one way on, never an error in the chat. */export function TrialCreditNotice({ kind }: { kind: "used_up" | "ended" }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return (<div role="note" data-trial-credit-notice={kind} className="flex justify-start"><div className="w-fit max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-xl border border-hairline/60 bg-raised/50 px-3.5 py-2.5 text-[14px] text-ink">diff --git a/src/components/WindowFrameBar.tsx b/src/components/WindowFrameBar.tsxindex 6106438a6f..414a3cd237 100644--- a/src/components/WindowFrameBar.tsx+++ b/src/components/WindowFrameBar.tsx@@ -1,10 +1,11 @@import { Settings } from "lucide-react";+import { useStoreDispatch } from "@/state/store-select";import { useEffect } from "react";import { sayFrameDrawn } from "@/lib/chrome-rail";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";+import { ChromeRailToggle } from "./ChromeRailToggle";import { captionChrome, useDesktopCapabilities, windowFrameable, windowFramed } from "./DesktopCapabilities";import { FrameBarPinnedPages } from "./FrameBarPinnedPages";@@ -24,7 +25,7 @@ export const FRAME_BAR_BUTTON = "flex size-[22px] shrink-0 items-center justify-* is the window's middle. */export function WindowFrameBar({ notifications = false, sidebarUpdate = false }: { notifications?: boolean; sidebarUpdate?: boolean }) {const { capabilities } = useDesktopCapabilities();- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const frameable = windowFrameable(capabilities), framed = windowFramed(capabilities);useEffect(() => { if (frameable) sayFrameDrawn(framed); }, [frameable, framed]);if (!framed) return null;diff --git a/src/components/announcements/use-announcements.ts b/src/components/announcements/use-announcements.tsindex 3adf4ef2e3..bddb16cead 100644--- a/src/components/announcements/use-announcements.ts+++ b/src/components/announcements/use-announcements.ts@@ -13,7 +13,7 @@ import { usedBefore } from "@/lib/notices";import type { WelcomeViewer } from "@/lib/onboarding";import { useStore } from "@/state/store";import { useDesktopNotices } from "../desktop-notices";-import { localDesktopPage, useWelcomeViewer } from "../onboarding/WelcomeGate";+import { localDesktopPage, useWelcomeViewer } from "../onboarding/welcome-viewer";/** An organization runs this desktop: null while main answers; false in a browser. */function useOrganization(): boolean | null {diff --git a/src/components/app/AppFrame.tsx b/src/components/app/AppFrame.tsxindex 65327bcff2..17de559f70 100644--- a/src/components/app/AppFrame.tsx+++ b/src/components/app/AppFrame.tsx@@ -1,6 +1,7 @@import { useLayoutEffect, useRef, type MutableRefObject } from "react";+import { useStoreActions } from "@/state/store-select";import { appVersion, openExternalLink } from "@/lib/app-links";-import { useStore } from "@/state/store";+import type { AppBlockedReason, AppDocument } from "../../../shared/app";import { PAGE_RPC_METHODS, RPC_HOST_REFUSED, type JsonRpcError } from "../../../shared/app-frame/bridge";import { callAppRpc, newAppSendId, postAppContext, sendAppMessage } from "./app-api";@@ -47,7 +48,7 @@ const refusal = (message: string): JsonRpcError => ({ code: RPC_HOST_REFUSED, meexport function AppFrame(props: AppFrameProps) {const box = useRef<HTMLDivElement | null>(null);- const { flushBotPatches } = useStore();+ const { flushBotPatches } = useStoreActions();// Callbacks change every render; the frame lives across renders.const latest = useRef({ ...props, flushBotPatches });latest.current = { ...props, flushBotPatches };diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex 95f843d763..1d82aa4562 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -1,8 +1,9 @@// A bot's page in the chat, artifact-style: its version stepper, Point, Share, Open in new tab and Full screen.+import { useStoreDispatch } from "@/state/store-select";import { createContext, useCallback, useEffect, useRef, useState, type MutableRefObject, type ReactNode } from "react";import { createPortal } from "react-dom";import { ArrowUpRight, Check, ChevronLeft, ChevronRight, Copy, Crosshair, Download, Globe, Loader2, Lock, Maximize2, Pin, PinOff, Share2, Trash2, X } from "lucide-react";-import { useStore } from "@/state/store";+import { openExternalLink } from "@/lib/app-links";import { cn } from "@/lib/cn";import { useCopyFeedback } from "@/lib/copy-text";@@ -294,7 +295,7 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, ro/** Under the toolbar: the public link with Copy, Update link and Unpublish once shared, or why sharing failed; the Point* hint. */export function PageNotes({ version, point, share, save, room, className }: Pick<PageToolsProps, "version" | "point" | "share" | "save" | "room"> & { className?: string }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { state: copied, copy } = useCopyFeedback(share.url ?? "");const state = share.share, owner = share.visibility === "owner";const rows: ReactNode[] = [];diff --git a/src/components/keys/KeysLink.tsx b/src/components/keys/KeysLink.tsxindex c8b5dd5bed..26653ead6a 100644--- a/src/components/keys/KeysLink.tsx+++ b/src/components/keys/KeysLink.tsx@@ -1,10 +1,10 @@-import { useStore } from "@/state/store";import { t } from "@/lib/i18n";+import { useStoreDispatch } from "@/state/store-select";import type { KeyId } from "./key-catalog";import { openKeySettings } from "./key-focus";export function KeysLink({ id, purpose }: { id: KeyId; purpose?: KeyId }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();if (typeof window !== "undefined" && window.ogb?.remoteClient?.active === true) return null;return (<button type="button" data-keys-link={purpose ?? id} onClick={() => dispatch(openKeySettings(id, purpose))}diff --git a/src/components/lazy-overlays.tsx b/src/components/lazy-overlays.tsxnew file mode 100644index 0000000000..2bd152189e--- /dev/null+++ b/src/components/lazy-overlays.tsx@@ -0,0 +1,13 @@+import { lazyScreen } from "./lazy-screens";++// Secondary overlays, modals, and rich message renderers split out of the eager App chunk.+export const LazyWidgetMessage = lazyScreen("WidgetMessage", async () => (await import("./widget/WidgetMessage")).WidgetMessage);+export const LazyAppMessage = lazyScreen("AppMessage", async () => (await import("./app/AppMessage")).AppMessage);+export const LazyTemplateChatCard = lazyScreen("TemplateChatCard", async () => (await import("./TemplateCard")).TemplateChatCard);+export const LazyAppNotices = lazyScreen("AppNotices", async () => (await import("./AppNotices")).AppNotices);+export const LazyWelcomeGate = lazyScreen("WelcomeGate", async () => (await import("./onboarding/WelcomeGate")).WelcomeGate);+export const LazyMausBotWelcome = lazyScreen("MausBotWelcome", async () => (await import("./MausBotWelcome")).MausBotWelcome);+export const LazyGuidedTour = lazyScreen("GuidedTour", async () => (await import("./onboarding/GuidedTour")).GuidedTour);+export const LazyFirstConversationTour = lazyScreen("FirstConversationTour", async () => (await import("./onboarding/FirstConversationTour")).FirstConversationTour);+export const LazyPublishTemplateHost = lazyScreen("PublishTemplateHost", async () => (await import("./publish-template")).PublishTemplateHost);+export const LazyConversationShareDialogs = lazyScreen("ConversationShareDialogs", async () => (await import("./conversation-share/ConversationShareDialogs")).ConversationShareDialogs);diff --git a/src/components/onboarding/SignInPill.tsx b/src/components/onboarding/SignInPill.tsxindex 1d14d483a1..814a556d0a 100644--- a/src/components/onboarding/SignInPill.tsx+++ b/src/components/onboarding/SignInPill.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";+import { useStoreActions } from "@/state/store-select";import { ArrowUp, Check, Copy, LoaderCircle } from "lucide-react";import { claudeSignInLink } from "@/components/ClaudeSignIn";import { chatgptPlanLink, deviceSignInProvider, type DeviceSignInStatus } from "@/components/DeviceSignIn";@@ -11,7 +12,7 @@ import { useCopyFeedback } from "@/lib/copy-text";import { t } from "@/lib/i18n";import { plainSignIn } from "@/lib/onboarding";import { engineSignedIn } from "@/lib/product-events";-import { api, ApiError, useStore, type InstanceInfo } from "@/state/store";+import { api, ApiError, type InstanceInfo } from "@/state/store";import { deviceSignInLink, isDeviceSignInCode } from "../../../shared/device-sign-in";const POLL_MS = 2_000;@@ -41,7 +42,7 @@ export function pillWay(instance: InstanceInfo | undefined): "install" | "sign-i* page, and the code pasted or shown in the same place. A finished sign-in refreshes the AIs, where the welcome's test* message takes over. `place` names the first-run flow for usage analytics. */export function useSignInPill(instance: InstanceInfo | undefined, place: ConnectAiPlace | null = null) {- const { refreshInstances, refreshModels } = useStore();+ const { refreshInstances, refreshModels } = useStoreActions();const [slot, setSlot] = useState<Slot>({ kind: "start" });const [error, setError] = useState<string | null>(null);const id = instance?.instanceId ?? "";diff --git a/src/components/onboarding/WelcomeFlow.tsx b/src/components/onboarding/WelcomeFlow.tsxindex 63667baf8e..f84cf00a96 100644--- a/src/components/onboarding/WelcomeFlow.tsx+++ b/src/components/onboarding/WelcomeFlow.tsx@@ -7,7 +7,7 @@ import { clearWelcomeDraft, readWelcomeDraft, saveWelcomeDraft } from "@/lib/welimport { api, useStore } from "@/state/store";import { ChiefIntro } from "./ChiefIntro";import { MeetScreen } from "./MeetScreen";-import { localDesktopPage } from "./WelcomeGate";+import { localDesktopPage } from "./welcome-viewer";const LEAVE_MS = 100;const FADE_MS = 150;diff --git a/src/components/onboarding/WelcomeGate.tsx b/src/components/onboarding/WelcomeGate.tsxindex 30b5302447..d6284c4113 100644--- a/src/components/onboarding/WelcomeGate.tsx+++ b/src/components/onboarding/WelcomeGate.tsx@@ -1,38 +1,12 @@import { useEffect, useState } from "react";import { emailGateDone } from "@/lib/analytics";import { clearWelcomeDraft } from "@/lib/welcome-draft";-import { hostedMember, LOCAL_VIEWER, welcomeDue, welcomeViewer, type WelcomeViewer } from "@/lib/onboarding";-import { api, useStore } from "@/state/store";+import { hostedMember, welcomeDue, type WelcomeViewer } from "@/lib/onboarding";+import { useStore } from "@/state/store";import { SharedWorkspaceHint } from "./SharedWorkspaceHint";import { WelcomeFlow } from "./WelcomeFlow";-/**- * Security: a remote page the desktop app loads gets a reduced but truthy window.ogb without remoteClient, and is no- * more the owner than a browser.- */-export function localDesktopPage(): boolean {- return window.ogb?.remoteClient !== undefined;-}--export function useWelcomeViewer(): WelcomeViewer | null {- const local = localDesktopPage();- const [viewer, setViewer] = useState<WelcomeViewer | null>(local ? LOCAL_VIEWER : null);- useEffect(() => {- if (local) return;- let active = true;- void api("/api/auth/session", { timeoutMs: 10_000 })- .then((session) => {- if (active) setViewer(welcomeViewer(session));- })- .catch(() => {- if (active) setViewer(LOCAL_VIEWER);- });- return () => {- active = false;- };- }, [local]);- return viewer;-}+export { localDesktopPage, useWelcomeViewer } from "./welcome-viewer";export function WelcomeGate({ viewer }: { viewer: WelcomeViewer | null }) {const { state, dispatch } = useStore();diff --git a/src/components/onboarding/welcome-viewer.ts b/src/components/onboarding/welcome-viewer.tsnew file mode 100644index 0000000000..bbc1a802ba--- /dev/null+++ b/src/components/onboarding/welcome-viewer.ts@@ -0,0 +1,31 @@+import { useEffect, useState } from "react";+import { LOCAL_VIEWER, welcomeViewer, type WelcomeViewer } from "@/lib/onboarding";+import { api } from "@/state/store";++/**+ * Security: a remote page the desktop app loads gets a reduced but truthy window.ogb without remoteClient, and is no+ * more the owner than a browser.+ */+export function localDesktopPage(): boolean {+ return window.ogb?.remoteClient !== undefined;+}++export function useWelcomeViewer(): WelcomeViewer | null {+ const local = localDesktopPage();+ const [viewer, setViewer] = useState<WelcomeViewer | null>(local ? LOCAL_VIEWER : null);+ useEffect(() => {+ if (local) return;+ let active = true;+ void api("/api/auth/session", { timeoutMs: 10_000 })+ .then((session) => {+ if (active) setViewer(welcomeViewer(session));+ })+ .catch(() => {+ if (active) setViewer(LOCAL_VIEWER);+ });+ return () => {+ active = false;+ };+ }, [local]);+ return viewer;+}diff --git a/src/components/sidebar-preview.ts b/src/components/sidebar-preview.tsindex ad426f612a..1e343f699a 100644--- a/src/components/sidebar-preview.ts+++ b/src/components/sidebar-preview.ts@@ -13,7 +13,7 @@ import { plainPreviewText } from "@/lib/plain-preview";import { isClientCancellation, isStoppedTurnName } from "../../shared/client-cancel";import { roomWorkingPreview } from "@/lib/room-threads";import { localizedCard } from "@/lib/widget-text";-import { widgetToText } from "../../shared/widget";+import { widgetToText } from "../../shared/widget-text";import { isSavedToThreadLine } from "@/lib/activity-text";/** The newest message a preview can show. A receipt or a screen frame says nothing about the conversation on its own. */diff --git a/src/hooks/use-usage-snapshot.ts b/src/hooks/use-usage-snapshot.tsindex aa70ca518a..700ac1de22 100644--- a/src/hooks/use-usage-snapshot.ts+++ b/src/hooks/use-usage-snapshot.ts@@ -1,6 +1,6 @@import { useEffect, useRef } from "react";import { preloadConnectedApps } from "@/lib/connected-apps";-import { localDesktopPage } from "@/components/onboarding/WelcomeGate";+import { localDesktopPage } from "@/components/onboarding/welcome-viewer";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { sendDailySnapshot, SNAPSHOT_CHECK_MS, snapshotReady, type UsageSources } from "@/lib/usage-snapshot";import { api, useStore, type ConfigStatus } from "@/state/store";diff --git a/src/lib/routine-calendar.ts b/src/lib/routine-calendar.tsindex 7582cce43b..361061a0d2 100644--- a/src/lib/routine-calendar.ts+++ b/src/lib/routine-calendar.ts@@ -2,6 +2,8 @@ import type { CalendarCall } from "./calendar-calls";import type { Routine, RoutineRun, RoutineSchedule } from "./routines";import { nextCronRuns } from "../../shared/routine-schedule";import { intlLocale, t } from "@/lib/i18n";+import { atLocalTime } from "@/lib/schedule-label";+export { atLocalTime };export const CALENDAR_SLOT_MINUTES = 5;const ROUTINE_MARKER_MINUTES = 30;@@ -47,12 +49,6 @@ export function startOfWeek(at: number): number {return date.getTime();}-export function atLocalTime(day: number, time: string): number {- const [hour, minute] = time.split(":").map(Number);- const date = new Date(day);- date.setHours(hour, minute, 0, 0);- return date.getTime();-}export function toLocalDateInput(at: number): string {const date = new Date(at - new Date(at).getTimezoneOffset() * 60_000);diff --git a/src/lib/schedule-label.ts b/src/lib/schedule-label.tsindex ffbe745f13..06fea92b02 100644--- a/src/lib/schedule-label.ts+++ b/src/lib/schedule-label.ts@@ -1,4 +1,3 @@-import { atLocalTime } from "@/lib/routine-calendar";import type { RoutineSchedule } from "@/lib/routines";import { cronScheduleLabel } from "../../shared/cron-label";import { cronText } from "@/lib/cron-text";@@ -8,6 +7,13 @@ import { intlLocale, t } from "@/lib/i18n";export const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;+export function atLocalTime(day: number, time: string): number {+ const [hour, minute] = time.split(":").map(Number);+ const date = new Date(day);+ date.setHours(hour, minute, 0, 0);+ return date.getTime();+}+export function dayName(day: number): string {return new Date(2026, 0, 4 + day).toLocaleDateString(intlLocale(), { weekday: "short" });}diff --git a/src/state/store-select.test.ts b/src/state/store-select.test.tsindex 7e121a4be3..10bfd43cdc 100644--- a/src/state/store-select.test.ts+++ b/src/state/store-select.test.ts@@ -6,7 +6,7 @@ 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";+import { sameFields, sameItems, useStoreActions, useStoreDispatch, useStoreSelector } from "./store-select";const bot = (id: string, name = id): Bot => ({id, threadId: `${id}-thread`, name, title: "", description: "", notifications: true, unread: false, color: "green",@@ -128,4 +128,20 @@ describe("useStoreActions", () => {act(() => store.dispatch({ type: "connected", value: !store.getState().connected }));expect(renders).toBe(1);});++ it("useStoreDispatch returns a stable dispatch without re-rendering on state updates", () => {+ const { store, source } = storeWith({ connected: false });+ let renders = 0;+ let captured: ((action: Action) => void) | null = null;+ function Sender() {+ captured = useStoreDispatch();+ renders++;+ return null;+ }+ mount(source, createElement(Sender));+ act(() => captured?.({ type: "connected", value: true }));+ act(() => store.dispatch({ type: "connected", value: false }));+ expect(renders).toBe(1);+ expect(store.getState().connected).toBe(false);+ });});diff --git a/src/state/store-select.ts b/src/state/store-select.tsindex 88357ce3d3..8fb0d97aba 100644--- a/src/state/store-select.ts+++ b/src/state/store-select.ts@@ -16,9 +16,19 @@ function scopedSource(value: StoreValue): StoreSource {return source;}+/** Reads `StoreSourceContext` when rendered by React, returning `null` if invoked directly outside React (e.g. unit+ * tests that mock `useStore` and call a component function without a React dispatcher). */+function readStoreSourceContext(): StoreSource | null {+ try {+ return useContext(StoreSourceContext);+ } catch {+ return null;+ }+}+/** 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());+ return readStoreSourceContext() ?? scopedSource(useStore());}interface Selection<T> {