Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Settings, calendar, bot settings, palette and Inbox stop redrawing on other bots' turns; config frames keep the place fields (#6779)
Milind Sonid3f2397dcd83
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5ea56e2c69..1ec0bb0770 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -115,7 +115,7 @@ jobs:- name: Source guards# The tests that only read the source: seconds here, and they stay in the shards. On Nov 3-4 2026 one of them was# red on main for 11 hours, and each PR heard about it after about 70 minutes, once its shards had found a runner.- run: pnpm exec vitest run src/locales/ scripts/testing/file-size-ratchet.test.ts scripts/testing/index-route-ratchet.test.ts scripts/testing/tighten-ratchets.test.ts scripts/testing/comment-history.test.ts scripts/testing/lazy-server-modules.test.ts scripts/testing/duration-sequencer.test.ts scripts/testing/host-e2e.test.ts scripts/testing/ci-retry-list.test.ts src/lib/copy-text.guard.test.ts src/components/Select.guard.test.ts --reporter=default --reporter=github-actions+ run: pnpm exec vitest run src/locales/ scripts/testing/file-size-ratchet.test.ts scripts/testing/index-route-ratchet.test.ts scripts/testing/store-read-ratchet.test.ts scripts/testing/tighten-ratchets.test.ts scripts/testing/comment-history.test.ts scripts/testing/lazy-server-modules.test.ts scripts/testing/duration-sequencer.test.ts scripts/testing/host-e2e.test.ts scripts/testing/ci-retry-list.test.ts src/lib/copy-text.guard.test.ts src/components/Select.guard.test.ts --reporter=default --reporter=github-actions# The rest runs only on a Boat VM, where ci-scope moved the Linux jobs' work into this job.- name: Remove what Boat installs and GitHub's runners lackif: steps.scope.outputs.linux_lanesdiff --git a/scripts/testing/store-read-ratchet.test.ts b/scripts/testing/store-read-ratchet.test.tsnew file mode 100644index 0000000000..2b22325c72--- /dev/null+++ b/scripts/testing/store-read-ratchet.test.ts@@ -0,0 +1,224 @@+// Each source file's calls to useStore(), the whole-store read: a component that calls it draws again on every store+// change, another bot's message included, whatever it shows. Read what a component draws with useStoreSelector+// (src/state/store-select.ts) instead. A count may only go down: a PR that adds a call fails here. One that removes calls+// passes and is told which numbers to lower; scripts/tighten-ratchets.mjs lowers any left at each release.+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";+import { storeReadsIn } from "../tighten-ratchets.mjs";++const ROOT = new URL("../../", import.meta.url);++const READS: Record<string, number> = {+ "src/App.tsx": 1,+ "src/components/ActivityPanel.tsx": 1,+ "src/components/AppGrantPrompt.tsx": 1,+ "src/components/AppNotices.tsx": 1,+ "src/components/ArchivedBotsPanel.tsx": 1,+ "src/components/AwakeBotsPicker.tsx": 2,+ "src/components/BotLimitPopup.tsx": 2,+ "src/components/BotMenuDelete.tsx": 1,+ "src/components/BotProjects.tsx": 2,+ "src/components/BrowserPanel.tsx": 2,+ "src/components/BrowserProfilesManager.tsx": 1,+ "src/components/BurstCard.tsx": 1,+ "src/components/CallView.tsx": 4,+ "src/components/CanvasComputers.tsx": 1,+ "src/components/CardHint.tsx": 1,+ "src/components/ChatEmptyState.tsx": 1,+ "src/components/ChatFindBar.tsx": 1,+ "src/components/ClaudeCodeSwitches.tsx": 2,+ "src/components/ClaudeSignIn.tsx": 1,+ "src/components/ClaudeUpdatePrompt.tsx": 1,+ "src/components/CloudAddDialog.tsx": 1,+ "src/components/CloudEngineSignIn.tsx": 2,+ "src/components/CloudHowTo.tsx": 1,+ "src/components/CloudIntent.tsx": 1,+ "src/components/CloudRoomCard.tsx": 2,+ "src/components/CloudSetup.tsx": 2,+ "src/components/CloudTimeZone.tsx": 1,+ "src/components/CloudUsageMeter.tsx": 2,+ "src/components/CommandAllowlistDialog.tsx": 1,+ "src/components/CompanyModels.tsx": 1,+ "src/components/ComposerPlusMenu.tsx": 1,+ "src/components/ComputerFilesPane.tsx": 1,+ "src/components/ComputerPanel.tsx": 1,+ "src/components/ComputerSharingSettings.tsx": 1,+ "src/components/ConnectedWorkspacesSettings.tsx": 1,+ "src/components/ConversationTurnLimit.tsx": 1,+ "src/components/DataResultChip.tsx": 1,+ "src/components/DeviceSignIn.tsx": 1,+ "src/components/EngineAccounts.tsx": 3,+ "src/components/EngineAppCopy.tsx": 1,+ "src/components/EngineBrowserSignIn.tsx": 1,+ "src/components/EngineSetup.tsx": 5,+ "src/components/EngineUsage.tsx": 3,+ "src/components/FilePreviewPanel.tsx": 1,+ "src/components/FilesView.tsx": 2,+ "src/components/FirstReplyRescueRow.tsx": 1,+ "src/components/ForkPanel.tsx": 1,+ "src/components/FrameBarPinnedPages.tsx": 1,+ "src/components/GoalRunCard.tsx": 1,+ "src/components/GrokMoveDialog.tsx": 1,+ "src/components/GroupCallView.tsx": 1,+ "src/components/GroupView.tsx": 2,+ "src/components/HelperIntro.tsx": 1,+ "src/components/HelperKeySuggestion.tsx": 1,+ "src/components/HelperSetup.tsx": 3,+ "src/components/HomeLine.tsx": 1,+ "src/components/ImportDialog.tsx": 1,+ "src/components/ImportSettings.tsx": 1,+ "src/components/InboxLine.tsx": 3,+ "src/components/InspectorPanel.tsx": 1,+ "src/components/LiveCallBar.tsx": 1,+ "src/components/LiveCallHost.tsx": 1,+ "src/components/LiveCallPill.tsx": 1,+ "src/components/LiveCallSettings.tsx": 1,+ "src/components/LiveKeyNeeded.tsx": 1,+ "src/components/LiveKeySetup.tsx": 1,+ "src/components/LiveProviderSettings.tsx": 1,+ "src/components/LocalComputerSection.tsx": 1,+ "src/components/LocalVmWorkspace.tsx": 1,+ "src/components/ManageMembersPanel.tsx": 1,+ "src/components/MapComposer.tsx": 1,+ "src/components/MausBotWelcome.tsx": 3,+ "src/components/McpServersPanel.tsx": 1,+ "src/components/MemberApps.tsx": 1,+ "src/components/NewBotDialog.tsx": 2,+ "src/components/NewTaskFolderDialog.tsx": 1,+ "src/components/NoEngines.tsx": 1,+ "src/components/NotificationsPanel.tsx": 3,+ "src/components/OllamaServer.tsx": 1,+ "src/components/OpenAiCompatServers.tsx": 5,+ "src/components/OpenFilesButton.tsx": 1,+ "src/components/OptionCard.tsx": 1,+ "src/components/PendingApproval.tsx": 1,+ "src/components/PhoneDevicesSection.tsx": 1,+ "src/components/PhonesList.tsx": 1,+ "src/components/PlaceTint.tsx": 1,+ "src/components/PostizCard.tsx": 1,+ "src/components/ProIntroduction.tsx": 3,+ "src/components/PublishedPageCard.tsx": 1,+ "src/components/QuestionCard.tsx": 2,+ "src/components/ReadyBotGallery.tsx": 1,+ "src/components/RemoteAgentSettingsPanel.tsx": 1,+ "src/components/RoomBulletin.tsx": 1,+ "src/components/RoomChiefAbsent.tsx": 1,+ "src/components/RoomHeader.tsx": 2,+ "src/components/RoomHoldsBanner.tsx": 1,+ "src/components/RoomMoreMenu.tsx": 1,+ "src/components/RoomQueueList.tsx": 1,+ "src/components/RoutineCalendarPage.tsx": 3,+ "src/components/RoutineRunCard.tsx": 2,+ "src/components/RoutineScheduleNote.tsx": 1,+ "src/components/SavedStepsRow.tsx": 1,+ "src/components/SearchResults.tsx": 1,+ "src/components/SecretRequestCard.tsx": 1,+ "src/components/SetupOffer.tsx": 1,+ "src/components/SidebarBotMenu.tsx": 1,+ "src/components/SidebarConnectApps.tsx": 2,+ "src/components/SidebarFooter.tsx": 3,+ "src/components/SidebarFooterNav.tsx": 3,+ "src/components/SidebarGroupThreadList.tsx": 1,+ "src/components/SidebarInboxRow.tsx": 1,+ "src/components/SidebarNewChatPanel.tsx": 1,+ "src/components/SidebarNewRoomPanel.tsx": 1,+ "src/components/SidebarPeople.tsx": 1,+ "src/components/SidebarPhoneBar.tsx": 1,+ "src/components/SidebarProfileMenu.tsx": 1,+ "src/components/SidebarSectionPicker.tsx": 1,+ "src/components/SidebarTeamMenu.tsx": 2,+ "src/components/SidebarTiles.tsx": 1,+ "src/components/SignInRequestCard.tsx": 1,+ "src/components/SimpleHelperIntro.tsx": 1,+ "src/components/SkillsSection.tsx": 1,+ "src/components/SoulField.tsx": 1,+ "src/components/StatusActivityRow.tsx": 1,+ "src/components/TailnetComputers.tsx": 2,+ "src/components/TaskPicker.tsx": 3,+ "src/components/TeamCanvas.tsx": 2,+ "src/components/TeamDialog.tsx": 1,+ "src/components/TeamLibraryPanel.tsx": 1,+ "src/components/TeamMapPage.tsx": 2,+ "src/components/TeamOwner.tsx": 3,+ "src/components/TeamSettingsDialog.tsx": 1,+ "src/components/TeamSideSwitch.tsx": 2,+ "src/components/TeamWelcome.tsx": 1,+ "src/components/TemplateCard.tsx": 4,+ "src/components/ThreadChip.tsx": 1,+ "src/components/ThreadRefs.tsx": 1,+ "src/components/TrialCreditNotice.tsx": 1,+ "src/components/TriggerCard.tsx": 1,+ "src/components/UsageCaps.tsx": 1,+ "src/components/UsageSection.tsx": 4,+ "src/components/VoiceEveryReplySetting.tsx": 1,+ "src/components/VoiceHearingSetting.tsx": 1,+ "src/components/VoiceSettings.tsx": 1,+ "src/components/VoiceSetupDialog.tsx": 1,+ "src/components/WatchScreenButton.tsx": 1,+ "src/components/WebPanelPage.tsx": 2,+ "src/components/WebhookTrigger.tsx": 1,+ "src/components/WindowFrameBar.tsx": 1,+ "src/components/WindowPlaceTitle.tsx": 1,+ "src/components/WorkspacesSection.tsx": 1,+ "src/components/XCard.tsx": 1,+ "src/components/announcements/AnnouncementsPage.tsx": 2,+ "src/components/announcements/use-announcements.ts": 1,+ "src/components/app/AppFrame.tsx": 1,+ "src/components/app/AppMessage.tsx": 2,+ "src/components/app/PageTools.tsx": 1,+ "src/components/bot-panel/use-memory-doc.ts": 1,+ "src/components/browser/PasskeyNotice.tsx": 1,+ "src/components/cloud-welcome/CloudWelcome.tsx": 1,+ "src/components/cloud-welcome/WelcomeKeeper.tsx": 1,+ "src/components/cloud-welcome/WelcomeSteps.tsx": 1,+ "src/components/cloud-welcome/parts.tsx": 1,+ "src/components/conversation-share/ConversationShareDialogs.tsx": 1,+ "src/components/data/DataPanel.tsx": 1,+ "src/components/data/InlineDataChart.tsx": 1,+ "src/components/keys/KeyPanels.tsx": 4,+ "src/components/keys/KeyRow.tsx": 2,+ "src/components/keys/KeysLink.tsx": 1,+ "src/components/onboarding/ChiefIntro.tsx": 1,+ "src/components/onboarding/ConnectAi.tsx": 1,+ "src/components/onboarding/FirstConversationTour.tsx": 1,+ "src/components/onboarding/GuidedTour.tsx": 1,+ "src/components/onboarding/MeetScreen.tsx": 1,+ "src/components/onboarding/SignInPill.tsx": 1,+ "src/components/onboarding/WelcomeFlow.tsx": 1,+ "src/components/onboarding/WelcomeGate.tsx": 1,+ "src/components/published-apps/AppPreviewPanel.tsx": 1,+ "src/components/published-apps/PublishedAppsPage.tsx": 1,+ "src/components/remote-desktop-panel.tsx": 1,+ "src/components/room-panel/ResponderPage.tsx": 1,+ "src/components/room-panel/RoomPanel.tsx": 1,+ "src/components/team-files/TeamFilesPage.tsx": 1,+ "src/components/usage/TraceWaterfall.tsx": 2,+ "src/components/usage/UsageInsights.tsx": 1,+ "src/components/widget/WidgetMessage.tsx": 1,+ "src/hooks/use-read-shown-chat.ts": 1,+ "src/hooks/use-usage-snapshot.ts": 1,+ "src/lib/app-load.ts": 1,+ "src/lib/connect-ai-events.ts": 1,+ "src/state/store-ref.ts": 1,+ "src/state/store-select.ts": 1,+};++function sourceFiles(): string[] {+ const out = execFileSync("git", ["ls-files", "src"], { cwd: ROOT, encoding: "utf8" });+ return out.split("\n").filter((file) => /\.(ts|tsx)$/.test(file) && !file.includes(".test.") && !file.includes("/testing/"));+}++describe("whole-store reads", () => {+ it("no file calls useStore() more often than written here", () => {+ const grown: string[] = [], shrunk: string[] = [];+ for (const file of sourceFiles()) {+ const calls = storeReadsIn(readFileSync(new URL(file, ROOT), "utf8"));+ const written = READS[file] ?? 0;+ if (calls > written) grown.push(`${file} calls useStore() ${calls} times, ${written ? `more than ${written}` : "and is not listed"}: select what it draws with useStoreSelector`);+ else if (calls < written) shrunk.push(`${file}: ${written} → ${calls}`);+ }+ if (shrunk.length) console.info(`Fewer useStore() calls than written in scripts/testing/store-read-ratchet.test.ts; lower these numbers (or run node scripts/tighten-ratchets.mjs):\n${shrunk.join("\n")}`);+ expect(grown, "See src/state/store-select.ts").toEqual([]);+ });+});diff --git a/scripts/testing/tighten-ratchets.test.ts b/scripts/testing/tighten-ratchets.test.tsindex 2fd99661ee..5552eb7df0 100644--- a/scripts/testing/tighten-ratchets.test.ts+++ b/scripts/testing/tighten-ratchets.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { tightenRoutes, tightenSizes } from "../tighten-ratchets.mjs";+import { storeReadsIn, tightenRoutes, tightenSizes, tightenStoreReads } from "../tighten-ratchets.mjs";const SIZES = `const LINES: Record<string, number> = {"server/index.ts": 16200,@@ -34,4 +34,25 @@ describe("tighten-ratchets", () => {expect(text).toContain(` // a comment stays\n 'path === "/': 90,\n "path.match(": 26,`);expect(changes).toEqual(['path === "/: 92 → 90']);});++ it("counts useStore() calls but not its definition, and lowers or drops a file's number, never raising one", () => {+ expect(storeReadsIn("export function useStore() {}\nconst a = useStore();\nconst b = useStore().state;\nuseStoreRef();")).toBe(2);+ expect(storeReadsIn("// useStore() in a comment\n/* and useStore() here */\nconst url = \"https://x\"; const a = useStore();")).toBe(1);+ expect(storeReadsIn("import { useStore as readStore } from \"./store\";\nconst a = readStore();\nconst b = readStore().state;")).toBe(2);+ const reads = `const READS: Record<string, number> = {+ "src/a.tsx": 3,+ "src/b.tsx": 2,+ "src/c.tsx": 1,+ "src/gone.tsx": 1,+};+`;+ const now: Record<string, number | null> = { "src/a.tsx": 1, "src/b.tsx": 4, "src/c.tsx": 0, "src/gone.tsx": null };+ const { text, changes } = tightenStoreReads(reads, (file: string) => now[file] ?? null);+ expect(text).toBe(`const READS: Record<string, number> = {+ "src/a.tsx": 1,+ "src/b.tsx": 2,+};+`);+ expect(changes).toEqual(["src/a.tsx: 3 → 1", "src/c.tsx: removed (no calls)", "src/gone.tsx: removed (gone)"]);+ });});diff --git a/scripts/tighten-ratchets.mjs b/scripts/tighten-ratchets.mjsindex 157c53b03a..ffe19d83a5 100644--- a/scripts/tighten-ratchets.mjs+++ b/scripts/tighten-ratchets.mjs@@ -1,4 +1,4 @@-// Lowers the numbers in the two ratchet tests to what the tree has now, so a pull request that shrinks a file never+// Lowers the numbers in the ratchet tests to what the tree has now, so a pull request that shrinks a file never// edits those lines. prepare-release.yml runs it on each release.import { existsSync, readFileSync, writeFileSync } from "node:fs";import { fileURLToPath } from "node:url";@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";const ROOT = new URL("../", import.meta.url);const SIZES = "scripts/testing/file-size-ratchet.test.ts";const ROUTES = "scripts/testing/index-route-ratchet.test.ts";+const STORE_READS = "scripts/testing/store-read-ratchet.test.ts";const LISTED_FROM = 1000;/** The lines between `const <name> ... = {` and its closing `};`. */@@ -50,14 +51,42 @@ export function tightenRoutes(text, timesOf) {return { text: text.slice(0, open) + lines.join("\n") + text.slice(close), changes };}+/** How many times a source file calls useStore(), under its own name or one it is imported as, its definition and+ * comments aside. */+export function storeReadsIn(source) {+ const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");+ const names = ["useStore", ...[...code.matchAll(/\buseStore as (\w+)/g)].map((match) => match[1])];+ return names.reduce((sum, name) => sum + (code.match(new RegExp(`(?<!function )\\b${name}\\(\\)`, "g"))?.length ?? 0), 0);+}++/** Each file keeps the lower of its number and its calls now; a file gone or with none left leaves the list. */+export function tightenStoreReads(text, readsOf) {+ const { open, close } = block(text, "READS");+ const changes = [];+ const lines = text.slice(open, close).split("\n").flatMap((line) => {+ const entry = /^(\s*)"([^"]+)": (\d+),$/.exec(line);+ if (!entry) return [line];+ const [, indent, file, written] = entry;+ const now = readsOf(file);+ if (!now) { changes.push(`${file}: removed (${now === null ? "gone" : "no calls"})`); return []; }+ if (now >= Number(written)) return [line];+ changes.push(`${file}: ${written} → ${now}`);+ return [`${indent}"${file}": ${now},`];+ });+ return { text: text.slice(0, open) + lines.join("\n") + text.slice(close), changes };+}+if (process.argv[1] === fileURLToPath(import.meta.url)) {const path = (file) => new URL(file, ROOT);const linesOf = (file) => existsSync(path(file)) ? readFileSync(path(file), "utf8").split("\n").length - 1 : null;const index = readFileSync(path("server/index.ts"), "utf8");const sizes = tightenSizes(readFileSync(path(SIZES), "utf8"), linesOf);const routes = tightenRoutes(readFileSync(path(ROUTES), "utf8"), (needle) => index.split(needle).length - 1);+ const reads = tightenStoreReads(readFileSync(path(STORE_READS), "utf8"), (file) => existsSync(path(file)) ? storeReadsIn(readFileSync(path(file), "utf8")) : null);if (sizes.changes.length) writeFileSync(path(SIZES), sizes.text);if (routes.changes.length) writeFileSync(path(ROUTES), routes.text);- for (const change of [...sizes.changes, ...routes.changes]) console.log(change);- if (!sizes.changes.length && !routes.changes.length) console.log("ratchets already tight");+ if (reads.changes.length) writeFileSync(path(STORE_READS), reads.text);+ const changes = [...sizes.changes, ...routes.changes, ...reads.changes];+ for (const change of changes) console.log(change);+ if (!changes.length) console.log("ratchets already tight");}diff --git a/src/components/AboutMeSettings.tsx b/src/components/AboutMeSettings.tsxindex 9613f4fc73..144eff9404 100644--- a/src/components/AboutMeSettings.tsx+++ b/src/components/AboutMeSettings.tsx@@ -1,14 +1,15 @@import { FIELD_EDGE } from "./SettingsPrimitives";import { useEffect, useState, useSyncExternalStore } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { saveTeamProfile } from "@/lib/own-profile";import { createAboutMeDraft } from "./about-me-draft";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const drafts = new WeakMap<object, { controller: ReturnType<typeof createAboutMeDraft>; team: { current: boolean } }>();export function AboutMeSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const confirmed = state.config?.profile?.aboutMe ?? "";const team = Boolean(state.config?.team);let draft = drafts.get(dispatch);diff --git a/src/components/AppSettingsRows.tsx b/src/components/AppSettingsRows.tsxindex 720e0d194c..38e269306e 100644--- a/src/components/AppSettingsRows.tsx+++ b/src/components/AppSettingsRows.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { builtInBrowserEnabled, showToolCallsEnabled, skillAuthoringEnabled } from "@/lib/feature-flags";import { localeChoices } from "@/locales";import { activeLocale, activePackComplete, t } from "@/lib/i18n";@@ -23,6 +23,7 @@ import { parseSendKey, SEND_KEYS, sendKeyLabel, setSendKey, useSendKey } from "@import { alternateSendLabel, parseFollowUpDefault, setFollowUpDefault, useFollowUpDefault } from "@/lib/follow-up";import { effectiveLanguage, setLanguageChoice, useLanguageChoice } from "@/lib/language-preference";import { Select } from "./Select";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function UpdatesRow({ title = t("settings.updates.title") }: { title?: string }) {const s = useUpdaterState();@@ -83,7 +84,7 @@ export function UpdatesRow({ title = t("settings.updates.title") }: { title?: st}function useNewBotEffort() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const current = state.config?.newBots?.effort ?? "";const [saving, setSaving] = useState(false);const [error, setError] = useState("");@@ -155,7 +156,7 @@ export function NewBotDefaultsRow({ onEdit }: { onEdit: () => void }) {}function ReplayAppTourButton({ label = t("settings.welcome.appTour") }: { label?: string }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const [saving, setSaving] = useState(false);const [failed, setFailed] = useState(false);return (@@ -191,7 +192,7 @@ function ReplayAppTourButton({ label = t("settings.welcome.appTour") }: { label?/** The two tours, one row each, each with its one Replay. */export function ReplayTourRow() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();// A team member's app has no tours of its own to replay.if (state.config?.team) return null;return <>@@ -205,7 +206,7 @@ export function ReplayTourRow() {}export function LanguageRow({ simple = false }: { simple?: boolean }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const current = effectiveLanguage(useLanguageChoice(), state.config?.language);return (@@ -345,7 +346,7 @@ export function UniversalPinsRow() {}export function ToolCallsRow() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const enabled = showToolCallsEnabled(state.config);const [saving, setSaving] = useState(false);const [error, setError] = useState("");@@ -385,7 +386,7 @@ export function ToolCallsRow() {}export function ExperimentalFeaturesRow() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const skillAuthoring = skillAuthoringEnabled(state.config);const [saving, setSaving] = useState(false);const [error, setError] = useState("");@@ -428,7 +429,7 @@ export function ExperimentalFeaturesRow() {}export function BrowserProfilesRow() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const profiles = state.config?.browserProfiles ?? [];if (!builtInBrowserEnabled(state.config) && profiles.length === 0) return null;// The manager draws its own section, with Add as the section's action.diff --git a/src/components/AutomaticRecoverySettings.tsx b/src/components/AutomaticRecoverySettings.tsxindex 1923374d1b..704ef83ff7 100644--- a/src/components/AutomaticRecoverySettings.tsx+++ b/src/components/AutomaticRecoverySettings.tsx@@ -1,8 +1,9 @@import { useRef, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { LearnMore, SettingRow, SettingsRows, Switch } from "./SettingsPrimitives";import { Select } from "./Select";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Recovery = NonNullable<ConfigStatus["automaticRecovery"]>;@@ -10,7 +11,7 @@ type Recovery = NonNullable<ConfigStatus["automaticRecovery"]>;* soon as a model is chosen; until then the model row says what is missing. The provider and model rows show only while* the switch is on. */export function AutomaticRecoverySettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, instances: s.instances }), sameFields), dispatch = useStoreDispatch();const [draft, setDraft] = useState<Recovery | null>(null);const [saving, setSaving] = useState(false);const [error, setError] = useState("");diff --git a/src/components/AvatarImageGenerator.tsx b/src/components/AvatarImageGenerator.tsxindex 47fc88f28d..6ce3fe0af8 100644--- a/src/components/AvatarImageGenerator.tsx+++ b/src/components/AvatarImageGenerator.tsx@@ -1,8 +1,8 @@import { useState } from "react";import { Loader2, Sparkles } from "lucide-react";-import { useStore } from "@/state/store";import { t } from "@/lib/i18n";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const INPUT_CLASS = "w-full min-w-0 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none disabled:opacity-50";const PROVIDER_LABEL = { openai: "OpenAI", xai: "Grok (xAI)", gemini: "Gemini", openrouter: "OpenRouter", higgsfield: "Higgsfield", custom: "Custom" } as const;@@ -18,7 +18,7 @@ export function AvatarImageGenerator({generating: boolean;onGenerate: (direction: string) => Promise<void>;}) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const imageGen = state.config?.imageGen;const [direction, setDirection] = useState("");const busy = disabled || generating;diff --git a/src/components/AwayEmailsSetting.tsx b/src/components/AwayEmailsSetting.tsxindex daa10780cc..5edf284db5 100644--- a/src/components/AwayEmailsSetting.tsx+++ b/src/components/AwayEmailsSetting.tsx@@ -1,12 +1,13 @@import { useEffect, useId, useState } from "react";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { t } from "@/lib/i18n";import { Switch } from "./SettingsPrimitives";/** Settings → General on a Team Cloud (a row of Account, or in Profile): the person's own "Email me when I'm away"* (GET/PUT /api/me/away-emails). Nothing off a team. */export function AwayEmailsSetting({ row = false }: { row?: boolean }) {- const team = Boolean(useStore().state.config?.team);+ const team = useStoreSelector((state) => Boolean(state.config?.team));const [on, setOn] = useState<boolean | null>(null);const [failed, setFailed] = useState(false);const label = useId();diff --git a/src/components/BotSettingsDialog.tsx b/src/components/BotSettingsDialog.tsxindex a526dccf3a..dd9865808b 100644--- a/src/components/BotSettingsDialog.tsx+++ b/src/components/BotSettingsDialog.tsx@@ -1,7 +1,7 @@-import { useEffect, useRef, useState } from "react";+import { useEffect, useRef, useState, type ComponentProps } from "react";import { ChevronDown, Search, X } from "lucide-react";-import { useStore, type Bot, type BotSettingsSection } from "@/state/store";+import { type Bot, type BotSettingsSection } from "@/state/store";import { cn } from "@/lib/cn";import { useCaptionChrome } from "./DesktopCapabilities";import { BOT_SECTIONS, appSearchPhase, searchEmptyText, sectionLabel, sectionMatches } from "./bot-settings/sections";@@ -31,15 +31,22 @@ import { BOT_PANEL_ID, sidePanelCls } from "./bot-panel/side-panel";import { HistoryRollbackDialog, useBotHistory, useBotOverview } from "./bot-settings/useBotOverview";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { ShareBotButton, useTeamName } from "./bot-access/ShareBotButton";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";/** Where the Library's memory, skills and folder rows lead in Advanced settings. */const LIBRARY_LINKS: Partial<Record<SimplePageId, BotSettingsSection>> = { memory: "memory", skills: "skills", folder: "access" };+/** The avatar moves with every turn of the bot, so only this section follows its motion. */+function MovingIdentitySection(props: Omit<ComponentProps<typeof IdentitySection>, "mascotMotion">) {+ const mascotMotion = useStoreSelector((state) => state.mascotMotion?.botId === props.bot.id ? state.mascotMotion : null);+ return <IdentitySection {...props} mascotMotion={mascotMotion} />;+}+export function BotSettingsDialog({ bot, overlay = false }: {bot: Bot;overlay?: boolean;}) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ botSettingsExpandAccordion: s.botSettingsExpandAccordion, botSettingsExpandRemembered: s.botSettingsExpandRemembered, botSettingsSection: s.botSettingsSection, routineRuns: s.routineRuns }), sameFields), dispatch = useStoreDispatch();const section = state.botSettingsSection;const derived = useBotSettingsDerived(bot);const dialogRef = useRef<HTMLElement | null>(null);@@ -118,11 +125,10 @@ export function BotSettingsDialog({ bot, overlay = false }: {);case "identity":return (- <IdentitySection+ <MovingIdentitySectionbot={bot}patch={derived.patch}activeState={derived.activeState}- mascotMotion={derived.mascotMotion}/>);case "soul":diff --git a/src/components/BrowserSettingsRows.tsx b/src/components/BrowserSettingsRows.tsxindex 3ad23c872a..6ca7dd3ee9 100644--- a/src/components/BrowserSettingsRows.tsx+++ b/src/components/BrowserSettingsRows.tsx@@ -4,12 +4,13 @@ import { productName } from "@/lib/brand";import { browserAvailable, browserUnavailableReason, builtInBrowserEnabled } from "@/lib/feature-flags";import { t } from "@/lib/i18n";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { MoreText, SettingRow, Switch } from "./SettingsPrimitives";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";/** Saves one config change through PATCH /api/config, one at a time, and shows the server's answer or its error. */export function useConfigSave() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [saving, setSaving] = useState(false);const [error, setError] = useState("");const save = async (patch: Record<string, unknown>) => {@@ -32,7 +33,7 @@ export function useConfigSave() {}export function BuiltInBrowserRow() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const browser = builtInBrowserEnabled(state.config);const desktopBrowser = browserAvailable(state.config);const browserInstallable = state.config?.browserEngine?.installable === true;@@ -72,7 +73,7 @@ export function BuiltInBrowserRow() {/** Self-hosted servers only, for the owner: browserEngine.egress.localNetwork lets bots' browsers open this server's* own sites and its local network. OpenMausBot's own ports, cloud metadata and link-local addresses stay closed. */export function ServerSitesRow() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const owner = useOwnerOrAdmin();const on = state.config?.browserEngine?.serverSites;const { saving, error, save } = useConfigSave();@@ -97,7 +98,7 @@ export function ServerSitesRow() {/** Owner-only unauthenticated SOCKS5 upstream for public destinations. The endpoint is write-only in the UI. */export function BrowserProxyRow() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const owner = useOwnerOrAdmin();const canEditProxy = state.config?.team ? state.config.browserEngine?.proxyEditable === true : owner === true;const configured = state.config?.browserEngine?.proxyConfigured === true;@@ -133,7 +134,7 @@ export function BrowserProxyRow() {/** browserEngine.engine: the bots' browsers run on OpenMausBot's own Chrome driver instead of agent-browser. */export function NewBrowserSettings() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const on = state.config?.browserEngine?.engine === "chrome";const { saving, error, save } = useConfigSave();diff --git a/src/components/CacheKeepWarmSettings.tsx b/src/components/CacheKeepWarmSettings.tsxindex 41b7a3d03e..b6111751ac 100644--- a/src/components/CacheKeepWarmSettings.tsx+++ b/src/components/CacheKeepWarmSettings.tsx@@ -1,9 +1,10 @@import { useRef, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { SettingRow, Switch } from "./SettingsPrimitives";import { productName } from "@/lib/brand";import { Select } from "./Select";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";type KeepWarm = NonNullable<ConfigStatus["cacheKeepWarm"]>;@@ -11,7 +12,7 @@ type KeepWarm = NonNullable<ConfigStatus["cacheKeepWarm"]>;export const KEEP_WARM_WINDOWS = [60, 120, 180, 360, 720] as const;export function CacheKeepWarmSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const [saving, setSaving] = useState(false);const [error, setError] = useState("");const inFlight = useRef(false);diff --git a/src/components/ChatMoreMenu.tsx b/src/components/ChatMoreMenu.tsxindex a4abb4e641..379276a6cd 100644--- a/src/components/ChatMoreMenu.tsx+++ b/src/components/ChatMoreMenu.tsx@@ -1,6 +1,6 @@import { useMemo, useState, type JSX } from "react";import { Bug, Copy, Cpu, Download, Gauge, LayoutTemplate, ListChecks, MessagesSquare, Monitor, MoreHorizontal, RotateCcw, Search, Share, SquarePen, UserPlus, UserRound, Users } from "lucide-react";-import { currentTaskBot, openBotThread, useStore, visibleMessages, type Bot } from "@/state/store";+import { currentTaskBot, openBotThread, visibleMessages, type Bot } from "@/state/store";import { useAdvancedMode } from "@/lib/interface-mode";import { useShowThreads } from "@/lib/thread-preferences";import { requestChatFind, useChatFindOpen } from "@/lib/chat-find";@@ -27,13 +27,14 @@ import { tasksOfSide } from "@/state/team-side";import { openConversationDialog, shareChoices } from "./conversation-share/conversation-share";import { askBot } from "@/lib/template-share";import { TEMPLATE_SHARE_MESSAGE } from "../../shared/share-card";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";/** One item list for the chat's ⋯ menu wherever it sits; it lists the threads whenever the sidebar hides them. The* Simple bot panel draws the same items as rows, and its Share button holds the two that export. */export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: SidebarMenuItem[]; on: boolean } {const bot = useMemo(() => currentTaskBot(profile), [profile]);const messages = useMemo(() => visibleMessages(bot), [bot]);- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ activityOpen: s.activityOpen, computerOpen: s.computerOpen, inspectorOpen: s.inspectorOpen, instances: s.instances }), sameFields), dispatch = useStoreDispatch();const advanced = useAdvancedMode();const showThreads = useShowThreads();const findOpen = useChatFindOpen(bot.threadId);diff --git a/src/components/ClaudeBedrock.tsx b/src/components/ClaudeBedrock.tsxindex e43ac0adb1..912b1914a0 100644--- a/src/components/ClaudeBedrock.tsx+++ b/src/components/ClaudeBedrock.tsx@@ -1,12 +1,13 @@import { useState } from "react";import { Loader2, Plus, Trash2 } from "lucide-react";-import { api, useStore, type InstanceInfo } from "@/state/store";+import { api, type InstanceInfo } from "@/state/store";import { t } from "@/lib/i18n";import { cn } from "@/lib/cn";import { ConfirmDialog } from "./ConfirmDialog";import { KEY_FIELD } from "./keys/KeyRow";import { PresetProviderMark } from "./ProviderIcons";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const INPUT = cn(KEY_FIELD, "font-sans");const TIER_PLACEHOLDER = {@@ -53,7 +54,7 @@ const TIER_LABEL: Record<Tier, "claudeBedrock.opus" | "claudeBedrock.sonnet" | "};function BedrockForm({ instance, onDone }: { instance?: InstanceInfo; onDone: () => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [draft, setDraft] = useState<Draft>(instance ? draftOf(instance) : EMPTY);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);@@ -133,13 +134,13 @@ function BedrockForm({ instance, onDone }: { instance?: InstanceInfo; onDone: ()}function BedrockRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: () => void }) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch();const [confirming, setConfirming] = useState(false);const [removing, setRemoving] = useState(false);const [error, setError] = useState<string | null>(null);- const usedBy = state.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId+ const usedBy = useStoreSelector((s) => s.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId|| bot.fallback?.some((candidate) => candidate.instanceId === instance.instanceId)- || bot.tasks?.some((task) => task.modelSelection?.instanceId === instance.instanceId)).length;+ || bot.tasks?.some((task) => task.modelSelection?.instanceId === instance.instanceId)).length);const bedrock = instance.claudeBedrock;const remove = async () => {setConfirming(false);@@ -181,7 +182,7 @@ function BedrockRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: () =}export function ClaudeBedrockEndpoints() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const instances = state.instances.filter((instance) => instance.claudeBedrock);const [open, setOpen] = useState<string | null>(null);return (diff --git a/src/components/ClaudeEndpoints.tsx b/src/components/ClaudeEndpoints.tsxindex c1616c5f78..8e87a23d5d 100644--- a/src/components/ClaudeEndpoints.tsx+++ b/src/components/ClaudeEndpoints.tsx@@ -1,11 +1,12 @@import { useState } from "react";import { Loader2, Plus, Trash2 } from "lucide-react";-import { api, useStore, type InstanceInfo } from "@/state/store";+import { api, type InstanceInfo } from "@/state/store";import { t } from "@/lib/i18n";import { cn } from "@/lib/cn";import { ConfirmDialog } from "./ConfirmDialog";import { KEY_FIELD } from "./keys/KeyRow";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Engine = "claude" | "codex";// Placeholders only: an Anthropic key already has its own engine in Settings → Keys. An empty Codex URL means OpenAI.@@ -28,7 +29,7 @@ const draftOf = (instance: InstanceInfo): Draft => ({});function EndpointForm({ instance, engine, onDone }: { instance?: InstanceInfo; engine: Engine; onDone: () => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const official = OFFICIAL[engine];const [draft, setDraft] = useState<Draft>(instance ? draftOf(instance) : EMPTY);const [saving, setSaving] = useState(false);@@ -99,13 +100,13 @@ function EndpointForm({ instance, engine, onDone }: { instance?: InstanceInfo; e}function EndpointRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: () => void }) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch();const [confirming, setConfirming] = useState(false);const [removing, setRemoving] = useState(false);const [error, setError] = useState<string | null>(null);- const usedBy = state.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId+ const usedBy = useStoreSelector((s) => s.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId|| bot.fallback?.some((candidate) => candidate.instanceId === instance.instanceId)- || bot.tasks?.some((task) => task.modelSelection?.instanceId === instance.instanceId)).length;+ || bot.tasks?.some((task) => task.modelSelection?.instanceId === instance.instanceId)).length);const endpoint = instance.claudeEndpoint ?? instance.codexEndpoint;const remove = async () => {setConfirming(false);@@ -146,7 +147,7 @@ function EndpointRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: ()}function AgentEndpoints({ engine }: { engine: Engine }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const endpoints = state.instances.filter((instance) => engine === "claude" ? instance.claudeEndpoint : instance.codexEndpoint);const [open, setOpen] = useState<string | null>(null);return (diff --git a/src/components/CloudBackendPicker.tsx b/src/components/CloudBackendPicker.tsxindex 4484a7423a..2c3bac64ba 100644--- a/src/components/CloudBackendPicker.tsx+++ b/src/components/CloudBackendPicker.tsx@@ -1,7 +1,7 @@import type { CloudBackend } from "../../shared/wire";import { cn } from "@/lib/cn";-import { useStore } from "@/state/store";import { t } from "@/lib/i18n";+import { sameFields, useStoreSelector } from "@/state/store-select";export function CloudBackendPicker({value,@@ -12,7 +12,7 @@ export function CloudBackendPicker({compact?: boolean;onChange: (backend: CloudBackend) => void;}) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);if (state.config?.cloudHome) return null;return (<div className="mt-3 rounded-lg bg-inset p-3">diff --git a/src/components/CommandPalette.tsx b/src/components/CommandPalette.tsxindex 5480d0b738..76bb4f33c7 100644--- a/src/components/CommandPalette.tsx+++ b/src/components/CommandPalette.tsx@@ -1,8 +1,11 @@import { t } from "@/lib/i18n";-import { useEffect, useRef, useState } from "react";+import { memo, useEffect, useRef, useState } from "react";import { MessageSquare, Search, Users } from "lucide-react";import { BotAvatar } from "./Avatar";-import { api, openBot, useStore, type Bot, type Group } from "@/state/store";+import { api, openBot } from "@/state/store";+import { useBotsApartFromTurns, useGroupsApartFromTurns, type BotApartFromTurns, type GroupApartFromTurns } from "@/state/apart-from-turns";+import { useStoreRef } from "@/state/store-ref";+import { useActiveLocale } from "@/lib/use-active-locale";import { rankByName } from "@/lib/palette-rank";import { useShowThreads } from "@/lib/thread-preferences";import { cn } from "@/lib/cn";@@ -11,8 +14,8 @@ import { landOnSearchHit } from "@/lib/focus-message";import { imeComposing } from "@/lib/send-key";type PaletteEntry =- | { kind: "bot"; bot: Bot }- | { kind: "room"; group: Group }+ | { kind: "bot"; bot: BotApartFromTurns }+ | { kind: "room"; group: GroupApartFromTurns }| { kind: "message"; hit: SearchHit };const OPEN_EVENT = "omb:open-command-palette";@@ -21,8 +24,9 @@ export function openCommandPalette() {window.dispatchEvent(new Event(OPEN_EVENT));}-export function CommandPalette({ onOpenChange }: { onOpenChange?: (open: boolean) => void }) {- const { state, dispatch } = useStore();+export const CommandPalette = memo(function CommandPalette({ onOpenChange }: { onOpenChange?: (open: boolean) => void }) {+ const store = useStoreRef(), dispatch = store.dispatch, allBots = useBotsApartFromTurns(), groups = useGroupsApartFromTurns();+ useActiveLocale();const showThreads = useShowThreads();const [open, setOpen] = useState(false);const [query, setQuery] = useState("");@@ -85,8 +89,8 @@ export function CommandPalette({ onOpenChange }: { onOpenChange?: (open: booleanif (!open) return null;- const bots = rankByName(state.bots.filter((b) => !b.hidden), q);- const rooms = rankByName(state.groups, q);+ const bots = rankByName(allBots.filter((b) => !b.hidden), q);+ const rooms = rankByName(groups, q);const entries: PaletteEntry[] = [...bots.map((bot): PaletteEntry => ({ kind: "bot", bot })),...rooms.map((group): PaletteEntry => ({ kind: "room", group })),@@ -98,12 +102,13 @@ export function CommandPalette({ onOpenChange }: { onOpenChange?: (open: booleanif (entry.kind === "message") {const hit = entry.hit;try {- await landOnSearchHit(hit, state, dispatch, showThreads);+ await landOnSearchHit(hit, store.state(), dispatch, showThreads);} catch (error) {dispatch({ type: "error", message: error instanceof Error ? error.message : String(error) });}} else if (entry.kind === "bot") {- openBot(dispatch, entry.bot, showThreads);+ const bot = store.state().bots.find((candidate) => candidate.id === entry.bot.id);+ if (bot) openBot(dispatch, bot, showThreads);} else {dispatch({ type: "select", id: entry.group.id });}@@ -247,4 +252,4 @@ export function CommandPalette({ onOpenChange }: { onOpenChange?: (open: boolean</div></div>);-}+});diff --git a/src/components/ContextWarning.tsx b/src/components/ContextWarning.tsxindex bba888c9e1..bdfed29b27 100644--- a/src/components/ContextWarning.tsx+++ b/src/components/ContextWarning.tsx@@ -5,14 +5,15 @@ import { cn } from "@/lib/cn";import { CONTEXT_WARNING_PERCENT, roomContextWarnings, threadContextWarning } from "@/lib/context-warning";import { t } from "@/lib/i18n";import { formatTokens } from "@/lib/usage";-import { api, useStore, type Bot, type Group, type Message } from "@/state/store";+import { api, type Bot, type Group, type Message } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";const pill = "flex items-center gap-1.5 rounded-full border border-warning/40 bg-warning/10 px-2.5 py-1 text-[13px] text-ink";const calmPill = "flex items-center gap-1.5 rounded-full border border-hairline/40 bg-raised/50 px-2.5 py-1 text-[13px] text-ink-secondary";const action = "rounded-full px-1.5 font-medium text-accent hover:underline disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline";export function useContextAction() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [pending, setPending] = useState(false);const run = (path: string, body: unknown) => {if (pending) return;diff --git a/src/components/CopilotModelPicker.test.ts b/src/components/CopilotModelPicker.test.tsindex 14b92d0785..1fdb0ba7b3 100644--- a/src/components/CopilotModelPicker.test.ts+++ b/src/components/CopilotModelPicker.test.ts@@ -16,6 +16,7 @@ const fixture = vi.hoisted(() => {return { instances: [] as InstanceInfo[], modelVariantSessions: {} as AppState["modelVariantSessions"], dispatch: vi.fn(),values: [] as unknown[], index: 0, own: 0 };});+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("react", async (original) => ({...await original<typeof import("react")>(),useState: (initial: unknown) => {diff --git a/src/components/CustomAcpModelPicker.test.ts b/src/components/CustomAcpModelPicker.test.tsindex 09c5f23c2b..b69858ecf0 100644--- a/src/components/CustomAcpModelPicker.test.ts+++ b/src/components/CustomAcpModelPicker.test.ts@@ -15,6 +15,7 @@ const fixture = vi.hoisted(() => {return { instances: [] as InstanceInfo[], modelVariantSessions: {} as AppState["modelVariantSessions"], dispatch: vi.fn(),values: [] as unknown[], index: 0, own: 0, advanced: false };});+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("react", async (original) => ({...await original<typeof import("react")>(),useState: (initial: unknown) => {diff --git a/src/components/DecisionModelSettings.tsx b/src/components/DecisionModelSettings.tsxindex 9dc77251ef..71871913de 100644--- a/src/components/DecisionModelSettings.tsx+++ b/src/components/DecisionModelSettings.tsx@@ -1,6 +1,6 @@// Security: the key is write-only; the server reports configured-or-not, never the value.import { useEffect, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";@@ -8,6 +8,7 @@ import { LearnMore, SETTINGS_INPUT, SettingRow, SettingsField, SettingsFormFoot,import { Select } from "./Select";import { WorkersAiKeyCard } from "./WorkersAiKeyCard";import { openKeySettings } from "./keys/key-focus";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";type CustomApi = "systemone" | "decisions" | "chat";const customApiOf = (api: string | undefined): CustomApi => (api === "decisions" || api === "chat" ? api : "systemone");@@ -152,7 +153,7 @@ function SavedText({ saved, onSave, disabled, label, placeholder, testId }: {}export function DecisionModelSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const decider = state.config?.decider;const provider = asProvider(decider?.chosen ?? decider?.provider);const openrouter = provider === "openrouter";diff --git a/src/components/DefaultBotControls.tsx b/src/components/DefaultBotControls.tsxindex 709d8ee500..14251b0ee4 100644--- a/src/components/DefaultBotControls.tsx+++ b/src/components/DefaultBotControls.tsx@@ -3,9 +3,11 @@ import { EyeOff, UserMinus } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { DEFAULT_BOT_NAME, myDefaultBot, useViewerEmail } from "@/lib/default-bot";-import { useStore, type Action, type Bot } from "@/state/store";+import { type Action, type Bot } from "@/state/store";import { Card, NavRow } from "./bot-panel/rows";import { SettingRow, Switch } from "./SettingsPrimitives";+import { useStoreDispatch } from "@/state/store-select";+import { useBotApartFromTurns } from "@/state/apart-from-turns";/** Hiding MausBot is the Settings switch turned off: one place says whether it is in the sidebar. */export function showDefaultBot(dispatch: (action: Action) => void, bot: Pick<Bot, "id" | "name">, shown: boolean): void {@@ -14,7 +16,7 @@ export function showDefaultBot(dispatch: (action: Action) => void, bot: Pick<Bot}export function HideDefaultBotItem({ bot, onDone, className = "flex w-full items-center gap-3 px-3.5 py-2 text-left text-[14px]" }: { bot: Bot; onDone: () => void; className?: string }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return (<buttontype="button"@@ -32,7 +34,7 @@ export function HideDefaultBotItem({ bot, onDone, className = "flex w-full items/** Demotes the default bot to a regular bot: the mark is cleared server-side, so it can then be archived or deleted. */export function DemoteDefaultBotItem({ bot, onDone, className = "flex w-full items-center gap-3 px-3.5 py-2 text-left text-[14px]" }: { bot: Bot; onDone: () => void; className?: string }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return (<buttontype="button"@@ -53,8 +55,8 @@ export function DemoteDefaultBotItem({ bot, onDone, className = "flex w-full ite/** Settings → General: whether the viewer's own MausBot has a row in the sidebar. */export function DefaultBotSidebarRow({ simple = false }: { simple?: boolean }) {- const { state, dispatch } = useStore();- const bot = myDefaultBot(state.bots, useViewerEmail());+ const viewer = useViewerEmail(), dispatch = useStoreDispatch();+ const bot = useBotApartFromTurns((bots) => myDefaultBot(bots, viewer));if (!bot) return null;const shown = !bot.sidebarHidden;return (@@ -71,7 +73,7 @@ export function DefaultBotSidebarRow({ simple = false }: { simple?: boolean }) {/** Bot settings: MausBot is never deleted, only taken off the sidebar. */export function DefaultBotHideRow({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();if (!bot.defaultBot || bot.sidebarHidden) return null;return (<Card anchor="default-bot">diff --git a/src/components/DisplayNameSetting.tsx b/src/components/DisplayNameSetting.tsxindex cdb943b475..c5a0369b30 100644--- a/src/components/DisplayNameSetting.tsx+++ b/src/components/DisplayNameSetting.tsx@@ -1,5 +1,6 @@import { useEffect, useId, useState } from "react";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { t } from "@/lib/i18n";import { SETTINGS_INPUT } from "./SettingsPrimitives";@@ -8,7 +9,7 @@ interface OwnName { displayName: string; shownAs: string }/** Settings → Bots → About you on a self-hosted server: the name a signed-in person goes by there (GET/PUT /api/me).* Nothing on a team, or on the owner's own computer, which goes by the profile's name. */export function DisplayNameSetting() {- const team = Boolean(useStore().state.config?.team);+ const team = useStoreSelector((state) => Boolean(state.config?.team));const [own, setOwn] = useState<OwnName | null>(null);const [draft, setDraft] = useState("");const [failed, setFailed] = useState(false);diff --git a/src/components/EngineLibrary.tsx b/src/components/EngineLibrary.tsxindex 61b78ea430..b3c9571d49 100644--- a/src/components/EngineLibrary.tsx+++ b/src/components/EngineLibrary.tsx@@ -2,10 +2,11 @@ import { useContext, useState, type ReactNode } from "react";import { SettingsLook } from "./SettingsPrimitives";import { useUpdatedOnce } from "@/hooks/use-updated-once";import { ArrowUpRight, Check, ChevronDown, RefreshCw } from "lucide-react";-import { useStore, type InstanceInfo } from "@/state/store";+import { type InstanceInfo } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { InstanceProviderMark } from "./ProviderIcons";+import { useStoreActions } from "@/state/store-select";export function engineReady(instance: InstanceInfo): boolean {if (instance.driverKind === "clineAgent") {@@ -101,7 +102,7 @@ export function EngineSections({ instances, renderEngine, isReady = engineReady}export function RefreshEngines() {- const { refreshInstances } = useStore();+ const { refreshInstances } = useStoreActions();const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);const [checked, setChecked] = useState(false);diff --git a/src/components/EnginesSettings.tsx b/src/components/EnginesSettings.tsxindex d9e02162ce..b7d3697442 100644--- a/src/components/EnginesSettings.tsx+++ b/src/components/EnginesSettings.tsx@@ -1,7 +1,7 @@import { useEffect, useRef, useState, type ReactNode } from "react";import { Check, Loader2, RefreshCw, TriangleAlert } from "lucide-react";-import { api, useStore, type InstanceInfo } from "@/state/store";+import { api, type InstanceInfo } from "@/state/store";import { useShowInstances } from "@/state/use-show-instances";import { EngineCard, EngineSections, RefreshEngines, engineReady } from "./EngineLibrary";import { cn } from "@/lib/cn";@@ -26,6 +26,7 @@ import { InstanceProviderMark } from "./ProviderIcons";import { GEMINI_PRESET, GeminiServer, hasGeminiServer } from "./OpenAiCompatServers";import { HiddenEngines, HiddenProviderRows, useHiddenProviders } from "./HiddenProviders";import { AdminOnly } from "./AdminOnly";+import { sameFields, useStoreActions, useStoreSelector } from "@/state/store-select";export { HiddenEngines };@@ -195,7 +196,7 @@ function CustomPicker({ instance, cliDefault, onClose, onSaved }: {/** The executable behind an engine: its path, Claude's self-update, and a reset to the default. */function EngineAdvanced({ instance }: { instance: InstanceInfo }) {- const { refreshInstances } = useStore();+ const { refreshInstances } = useStoreActions();const showInstances = useShowInstances();const [open, setOpen] = useState(false);const cliMotion = useMenuMotion(open);@@ -336,13 +337,12 @@ function EngineAdvanced({ instance }: { instance: InstanceInfo }) {/** Remove drops an added Antigravity account or an added server; Sign out forgets a signed-in account's sign-in (Antigravity's* Google one, or a CLI's own login such as Kimi's) and never hides the provider, which stays listed with Set up. */function EngineAccountAction({ instance, action, cli = false, removeBody = "accounts.removeBodyAntigravity" }: { instance: InstanceInfo; action: "remove" | "signOut"; cli?: boolean; removeBody?: LocaleKey }) {- const { state } = useStore();const showInstances = useShowInstances();const [confirming, setConfirming] = useState(false);const [running, setRunning] = useState(false);const [error, setError] = useState<string | null>(null);const remove = action === "remove";- const usedBy = remove ? state.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId).length : 0;+ const usedBy = useStoreSelector((s) => remove ? s.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId).length : 0);const label = t(remove ? "accounts.remove" : "accounts.signOut");const run = async () => {setConfirming(false);@@ -375,7 +375,7 @@ function EngineAccountAction({ instance, action, cli = false, removeBody = "acco}function AntigravityAddAccount({ source }: { source: InstanceInfo }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const [addedId, setAddedId] = useState<string | null>(null);const added = addedId ? state.instances.find((instance) => instance.instanceId === addedId && instance.snapshot.authenticated !== true) : undefined;return <>@@ -542,7 +542,7 @@ function groupedAccounts(listed: InstanceInfo[]) {/** The chat's AI sign-in card: Simple Providers with only the accounts a person signs in to (Claude, ChatGPT or Codex,* Antigravity), for an owner or admin. */export function AiSignInSettings() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const { groups, groupOf, rows } = groupedAccounts(state.instances.filter((instance) => accountGroupOf(instance) !== null || (instance.driverKind === "antigravityAgent" && !instance.readOnly)));const isReady = (instance: InstanceInfo) => { const group = groupOf(instance); return group ? accountsReady(groups.get(group)!) : engineReady(instance); };const renderEngine = (instance: InstanceInfo, bare = false) => {@@ -555,7 +555,7 @@ export function AiSignInSettings() {}export function EnginesSettings({ simple = false, more }: { simple?: boolean; more?: { id: string; open: boolean; onToggle: () => void } }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);// Leaving Settings ends the "now uses the copy OpenMausBot installed" lines.useEffect(() => forgetAppCopySwitches, []);const listed = state.instances.filter((i) => i.readOnly || i.cli !== undefined || i.cliDefault !== undefined || i.snapshot.state === "unavailable" || isApiKeyEngine(i) || i.claudeEndpoint !== undefined || i.claudeBedrock !== undefined || i.codexEndpoint !== undefined);diff --git a/src/components/EveryBotRules.tsx b/src/components/EveryBotRules.tsxindex e1f2a56ac8..e3e4c8c544 100644--- a/src/components/EveryBotRules.tsx+++ b/src/components/EveryBotRules.tsx@@ -1,13 +1,14 @@import { FIELD_EDGE } from "./SettingsPrimitives";import { useEffect, useSyncExternalStore } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { createAboutMeDraft } from "./about-me-draft";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const drafts = new WeakMap<object, ReturnType<typeof createAboutMeDraft>>();export function EveryBotRules() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const confirmed = state.config?.everyBotRules;let controller = drafts.get(dispatch);if (!controller) {diff --git a/src/components/HiddenProviders.tsx b/src/components/HiddenProviders.tsxindex 5d5d14fad1..f076555a13 100644--- a/src/components/HiddenProviders.tsx+++ b/src/components/HiddenProviders.tsx@@ -1,10 +1,11 @@import { useEffect, useMemo, useState } from "react";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";import { useShowInstances } from "@/state/use-show-instances";import { t } from "@/lib/i18n";import { InstanceProviderMark } from "./ProviderIcons";import { SettingsMark } from "./SettingsPrimitives";+import { sameFields, useStoreSelector } from "@/state/store-select";/** A provider someone hid: the server leaves it out of /api/instances and every model list (withInstanceConfig), so* these lists are the only way back to it. */@@ -12,7 +13,7 @@ export interface HiddenProvider { instanceId: string; driverKind?: string; displ/** GET /api/instances/hidden, read again whenever the instance list changes (a Hide or an Unhide refreshes it). */export function useHiddenProviders(): HiddenProvider[] {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const [hidden, setHidden] = useState<HiddenProvider[]>([]);useEffect(() => {let alive = true;diff --git a/src/components/ImageGenerationSettings.tsx b/src/components/ImageGenerationSettings.tsxindex fd606c6085..c92000807d 100644--- a/src/components/ImageGenerationSettings.tsx+++ b/src/components/ImageGenerationSettings.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";@@ -9,6 +9,7 @@ import { saveCredential } from "./keys/key-save";import { LearnMore, SETTINGS_INLINE_INPUT, SETTINGS_INPUT, SettingRow, SettingsField, SettingsGroup, SettingsRows, StatusDot } from "./SettingsPrimitives";import { Select } from "./Select";import { productName } from "@/lib/brand";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const PROVIDER_LABEL: Record<ImageProvider, string> = {openai: "OpenAI", xai: "Grok (xAI)", gemini: "Gemini", openrouter: "OpenRouter", higgsfield: "Higgsfield", custom: "Custom",@@ -58,7 +59,7 @@ function keyConfigured(status: ImageGenStatus | undefined, provider: ImageProvid}export function ImageGenerationSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const status = state.config?.imageGen;const primary = status?.primary ?? { provider: status?.provider ?? "openai", model: status?.model ?? IMAGE_DEFAULT_MODELS.openai, configured: status?.configured === true };const fallback = status?.fallback ?? null;@@ -260,7 +261,7 @@ function ModelRow({ slot, slotLabel, provider, model, openrouterModels, disabled}function HiggsfieldCard({ connected }: { connected: boolean }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return (<SettingsGroup label={PROVIDER_LABEL.higgsfield} block="images-higgsfield"><SettingsRows>@@ -282,7 +283,7 @@ function HiggsfieldCard({ connected }: { connected: boolean }) {}function ProviderKeyCard({ provider, status }: { provider: ImageProvider; status: ImageGenStatus | undefined }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [value, setValue] = useState("");const [url, setUrl] = useState<string | null>(null);const [saving, setSaving] = useState(false);diff --git a/src/components/McpCallTimeoutSettings.tsx b/src/components/McpCallTimeoutSettings.tsxindex aeba9124fc..c503a43322 100644--- a/src/components/McpCallTimeoutSettings.tsx+++ b/src/components/McpCallTimeoutSettings.tsx@@ -8,11 +8,12 @@ import {mcpCallTimeoutMinutes,parseMcpCallTimeoutMinutes,} from "@/lib/mcp-call-timeout";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function McpCallTimeoutSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const confirmedMinutes = mcpCallTimeoutMinutes(state.config);const [value, setValue] = useState(String(confirmedMinutes));const [dirty, setDirty] = useState(false);diff --git a/src/components/ModelPicker.simple.test.ts b/src/components/ModelPicker.simple.test.tsindex 455ee814a8..b9c9abc41e 100644--- a/src/components/ModelPicker.simple.test.ts+++ b/src/components/ModelPicker.simple.test.ts@@ -27,6 +27,7 @@ const fixture = vi.hoisted(() => {refreshInstances: (() => Promise.resolve()) as () => Promise<void>,};});+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("react", async (original) => ({...await original<typeof import("react")>(),useState: (initial: unknown) => {diff --git a/src/components/ModelPicker.test.ts b/src/components/ModelPicker.test.tsindex 8586c77315..03ca11b09f 100644--- a/src/components/ModelPicker.test.ts+++ b/src/components/ModelPicker.test.ts@@ -13,6 +13,7 @@ const fixture = vi.hoisted(() => {vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => {} });return { instances: [] as InstanceInfo[], modelVariantSessions: {} as AppState["modelVariantSessions"], dispatch: vi.fn() };});+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => ({...(await importOriginal<typeof import("@/state/store")>()),useStore: () => ({diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex 7689ff5ff2..ab9c082840 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -3,7 +3,7 @@ import { modelLabel, modelProvider } from "@/lib/model-label";import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";import { createPortal } from "react-dom";import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, KeyRound, Loader2, RefreshCw, X } from "lucide-react";-import { useStore, currentTaskBot, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store"; import { sameFields, useStoreActions, useStoreSelector } from "@/state/store-select";+import { currentTaskBot, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store"; import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select";import type { EffortLevel } from "../../shared/wire";import { filterCustomModels, partitionCustomModels, suggestedModels } from "@/lib/custom-models";import { configuredModelInstances, isClaudeAccount, isCustomOnly, modelsAwaitEngine, SIGN_IN_FAMILY_LABEL, signInFamily } from "@/lib/engine-rail";@@ -66,7 +66,7 @@ export function EffortRow({label?: ReactNode;compact?: boolean;}) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields), dispatch = useStoreDispatch();const selection = bot.modelSelection;const instance = state.instances.find((candidate) => candidate.instanceId === selection.instanceId);if (instance?.capabilities?.modelVariants) {@@ -127,7 +127,7 @@ export function ModelVariantRow({ bot, threadId, updateBotDefault, className, lawide?: boolean;quiet?: boolean;}) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances, modelVariantSessions: s.modelVariantSessions }), sameFields), dispatch = useStoreDispatch();const selection = bot.modelSelection;const choices = variantChoices(state, selection, threadId ?? bot.threadId);if (!choices) return null;diff --git a/src/components/PlaceChip.tsx b/src/components/PlaceChip.tsxindex a07f1734c7..90d67f1881 100644--- a/src/components/PlaceChip.tsx+++ b/src/components/PlaceChip.tsx@@ -7,16 +7,17 @@ import { t } from "@/lib/i18n";import { instanceSupportsLocalComputer, localComputerDisabledReason, localComputerSelectable, pageOnRemoteServer } from "@/lib/local-computer";import { effectivePlace, personPin, PLACES, placeLabelKey, placeOffered, type Place } from "@/lib/place";import { placeBlocked, placeFacts, placeHasIssue, placeViewFor, usePlaceSeat } from "@/lib/place-view";-import { useStore, type Bot, type Task } from "@/state/store";+import { type Bot, type Task } from "@/state/store";import type { PlaceView } from "../../shared/place-view";import { useDesktopCapabilities } from "./DesktopCapabilities";import { PlaceIcon } from "./PlaceIcon";import type { SidebarMenuItem } from "./SidebarPopoverMenu";+import { sameFields, useStoreSelector } from "@/state/store-select";export type PlaceAvailability = Record<Place, boolean>;export function usePlaceViews(bot: Bot): Record<Place, { view: PlaceView; reachable: boolean; policy: boolean; listed: boolean }> {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, instances: s.instances }), sameFields);const { capabilities } = useDesktopCapabilities();const seat = usePlaceSeat(state.config, capabilities);const backend = bot.cloudBackend === "vps" ? "vps" : "box";diff --git a/src/components/PlaceLookCard.tsx b/src/components/PlaceLookCard.tsxindex cd92b8d2fa..005507c7e5 100644--- a/src/components/PlaceLookCard.tsx+++ b/src/components/PlaceLookCard.tsx@@ -4,11 +4,11 @@ import type { PlaceColorOutcome } from "../../electron/place-look.mjs";import { t } from "@/lib/i18n";import { choosePlaceColor, usePlaceLook } from "@/lib/place-look";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { useStore } from "@/state/store";import { PlacePicture } from "./PlacePicture";import { SettingRow, SettingsRows } from "./SettingsPrimitives";import { SwatchRadios } from "./SwatchRadios";import { useSettingsPlace } from "./settings/settings-place";+import { sameFields, useStoreSelector } from "@/state/store-select";/** The sidebar's look, as two rows of Settings: its colour, in the six swatches the rail's circles use, and its picture,* kept on the place's own server for everyone there. Both start plain. This computer's colour is the app's own; a@@ -18,7 +18,7 @@ export function PlaceLookRows() {const look = usePlaceLook();// The place's name from the one source Settings, the rail and the title bar share: never the raw entry's "This Mac".const place = useSettingsPlace();- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const admin = useOwnerOrAdmin() === true;const computer = window.ogb?.app?.ownPage === true;const [pending, setPending] = useState<CloudSwatch | null>(null);diff --git a/src/components/ProfileSettings.tsx b/src/components/ProfileSettings.tsxindex cd7f80b66c..62bba6fa5b 100644--- a/src/components/ProfileSettings.tsx+++ b/src/components/ProfileSettings.tsx@@ -1,5 +1,5 @@import { useEffect, useId, useRef, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { avatarMarks } from "@/lib/avatar-marks";import { saveTeamProfile } from "@/lib/own-profile";@@ -11,6 +11,7 @@ import { EveryBotRules } from "./EveryBotRules";import { SETTINGS_INPUT, SettingsField } from "./SettingsPrimitives";import { profileInitials } from "./SidebarProfileMenu";import { User } from "lucide-react";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const PHOTO_MIN_SIDE = 64;const PHOTO_MAX_SIDE = 8192;@@ -65,7 +66,7 @@ function croppedPhoto(file: File, zoom: number): Promise<File> {/** The person's own picture beside their name in the sidebar. Kept in the app's attachment store; "" removes it. */function ProfilePhoto({ initials }: { initials: string }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const avatarUrl = state.config?.profile?.avatarUrl ?? "";const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -154,7 +155,7 @@ function ProfilePhoto({ initials }: { initials: string }) {}export function ProfileFields() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const [name, setName] = useState(state.config?.profile?.name ?? "");const [email, setEmail] = useState(state.config?.profile?.email ?? "");useEffect(() => {@@ -219,7 +220,7 @@ function ProfileAvatar({ profile }: { profile?: { name?: string; email?: string;}export function ProfileSummaryRow() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const [editing, setEditing] = useState(false);const profile = state.config?.profile;const name = profile?.name?.trim() ?? "";diff --git a/src/components/RoomTurnTimeoutSettings.tsx b/src/components/RoomTurnTimeoutSettings.tsxindex e27935c4dc..dd84311649 100644--- a/src/components/RoomTurnTimeoutSettings.tsx+++ b/src/components/RoomTurnTimeoutSettings.tsx@@ -7,11 +7,12 @@ import {MIN_ROOM_TURN_TIMEOUT_MINUTES,parseRoomTurnTimeoutMinutes,} from "@/lib/room-turn-timeout";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function RoomTurnTimeoutSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const confirmedMinutes = state.config?.rooms.turnTimeoutMinutes ?? 5;const [value, setValue] = useState(String(confirmedMinutes));const [dirty, setDirty] = useState(false);diff --git a/src/components/RoutineCalendarPage.tsx b/src/components/RoutineCalendarPage.tsxindex e92e284c3c..c130566439 100644--- a/src/components/RoutineCalendarPage.tsx+++ b/src/components/RoutineCalendarPage.tsx@@ -1,13 +1,5 @@import { boatCapableEngine } from "@/lib/remote-desktop";-import {- useEffect,- useLayoutEffect,- useRef,- useState,- type DragEvent as ReactDragEvent,- type PointerEvent as ReactPointerEvent,- type ReactNode,-} from "react";+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";import {CheckCircle2,ChevronRight,@@ -55,19 +47,16 @@ import {addDays,atLocalTime,CALENDAR_SLOT_MINUTES,- formatGmtOffset,fromLocalDateAndTime,intervalAnchorForSave,nextIntervalForSave,- packCalendarCollisions,- slotAt,startOfDay,toLocalDateInput,toLocalTimeInput,type CallOccurrence,type RoutineCalendarItem,} from "@/lib/routine-calendar";-import { limitResetWhen, type ResetMarker } from "@/lib/limit-resets";+import { limitResetWhen } from "@/lib/limit-resets";import { LimitResetFields, type LimitResetChoice } from "./routines/LimitResetFields";import { DAY_NAMES, dayName, durationLabel, niceDate, niceTime, scheduleLabel } from "@/lib/schedule-label";import { Select } from "./Select";@@ -83,14 +72,15 @@ import {type RoutineTarget,} from "@/lib/routines"; import { ROUTINE_GOAL_RUN_LIMIT_MINUTES, ROUTINE_RUN_LIMIT_MAX_MINUTES, ROUTINE_RUN_LIMIT_MINUTES } from "@/lib/routines";import { api, openBotThread, openThread, useStore, type Bot, type Group } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";import { RoutineScheduleNote } from "./RoutineScheduleNote";-import { CalendarEventCard, HOUR_HEIGHT, statusState } from "./routines/CalendarEventCard";+import { statusState } from "./routines/CalendarEventCard";+export { CalendarGrid } from "./routines/CalendarGrid";const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];const WEEKDAYS = [1, 2, 3, 4, 5];const INTERVAL_PRESETS = [5, 10, 15, 30, 60];const EVENT_DURATION_OPTIONS = Array.from({ length: 240 / CALENDAR_SLOT_MINUTES }, (_, index) => (index + 1) * CALENDAR_SLOT_MINUTES), RUN_LIMIT_OPTIONS = [...EVENT_DURATION_OPTIONS, 300, 360, 480, 720, ROUTINE_RUN_LIMIT_MAX_MINUTES];-import { BOT_DRAG_TYPE, EVENT_DRAG_TYPE, LimitResetMarker, type ResetDrop } from "./routines/LimitResetMarkers";export type EventKind = "routine" | "call";export type RoutinesLayout = "day" | "week" | "list";@@ -1159,133 +1149,6 @@ export function QuickComposer({);}-export function CalendarGrid({- anchor,- days,- items,- bots,- groups,- selectedId,- onOpen,- onCreate,- onMove,- onResize,- markers = [],- onDropOnReset,-}: {- anchor: number;- days: number;- items: CalendarEventItem[];- markers?: ResetMarker[];- onDropOnReset?: (drop: ResetDrop, marker: ResetMarker) => void;- bots: Bot[];- groups: Group[];- selectedId?: string;- onOpen: (item: CalendarEventItem) => void;- onCreate: (seed: EventSeed) => void;- onMove: (item: { kind: EventKind; id: string; at: number }, nextAt: number) => void;- onResize: (item: CalendarEventItem, duration: number) => void;-}) {- const scrollRef = useRef<HTMLDivElement>(null);- const [selection, setSelection] = useState<{ day: number; start: number; end: number } | null>(null);- const [dragPreview, setDragPreview] = useState<{ day: number; at: number } | null>(null);- const today = startOfDay(Date.now());- const starts = Array.from({ length: days }, (_, index) => addDays(anchor, index));- const minDayWidth = days === 7 ? 64 : days === 3 ? 180 : 280;- const gridTemplateColumns = `64px repeat(${days}, minmax(${minDayWidth}px, 1fr))`;- const minWidth = 64 + days * minDayWidth;-- useEffect(() => {- const viewport = scrollRef.current;- if (!viewport) return;- const now = new Date();- const hour = starts.includes(today) ? Math.max(0, now.getHours() - 2) : 7;- viewport.scrollTo({ top: hour * HOUR_HEIGHT });- }, [days]);-- const beginSelection = (event: ReactPointerEvent<HTMLDivElement>, day: number) => {- if (event.button !== 0 || (event.target as HTMLElement).closest("[data-event-card]")) return;- const rect = event.currentTarget.getBoundingClientRect();- const start = slotAt(day, event.clientY, rect.top, HOUR_HEIGHT);- let end = start + 30 * 60_000;- setSelection({ day, start, end });- const move = (pointer: PointerEvent) => {- const current = slotAt(day, pointer.clientY, rect.top, HOUR_HEIGHT);- end = Math.max(start + CALENDAR_SLOT_MINUTES * 60_000, current + CALENDAR_SLOT_MINUTES * 60_000);- setSelection({ day, start, end });- };- const up = (pointer: PointerEvent) => {- document.removeEventListener("pointermove", move);- document.removeEventListener("pointerup", up);- setSelection(null);- onCreate({ kind: "routine", at: start, durationMinutes: Math.max(CALENDAR_SLOT_MINUTES, Math.round((end - start) / 60_000)), botIds: [], anchor: { x: pointer.clientX, y: pointer.clientY } });- };- document.addEventListener("pointermove", move);- document.addEventListener("pointerup", up, { once: true });- };-- const drop = (event: ReactDragEvent<HTMLDivElement>, day: number) => {- event.preventDefault();- setDragPreview(null);- const rect = event.currentTarget.getBoundingClientRect();- const at = slotAt(day, event.clientY, rect.top, HOUR_HEIGHT);- const botId = event.dataTransfer.getData(BOT_DRAG_TYPE);- if (botId) return onCreate({ kind: "routine", at, durationMinutes: 30, botIds: [botId], anchor: { x: event.clientX, y: event.clientY } });- const raw = event.dataTransfer.getData(EVENT_DRAG_TYPE);- if (!raw) return;- try {- const item = JSON.parse(raw) as { kind: EventKind; id: string; at: number };- onMove(item, at);- } catch {- }- };-- const previewDrop = (event: ReactDragEvent<HTMLDivElement>, day: number) => {- if (!event.dataTransfer.types.includes(BOT_DRAG_TYPE) && !event.dataTransfer.types.includes(EVENT_DRAG_TYPE)) return;- event.preventDefault();- event.dataTransfer.dropEffect = event.dataTransfer.types.includes(EVENT_DRAG_TYPE) ? "move" : "copy";- const rect = event.currentTarget.getBoundingClientRect();- const at = slotAt(day, event.clientY, rect.top, HOUR_HEIGHT);- setDragPreview((current) => current?.day === day && current.at === at ? current : { day, at });- };-- return (- <div ref={scrollRef} className="min-h-0 flex-1 overflow-auto border-l border-t border-hairline/40 bg-app">- <div className="sticky top-0 z-30 grid bg-app/95 backdrop-blur" style={{ gridTemplateColumns, minWidth }}>- <div className="border-b border-r border-hairline/40 px-2 py-3 text-center text-[9px] uppercase tracking-wider text-ink-secondary">{formatGmtOffset(-new Date(anchor).getTimezoneOffset())}</div>- {starts.map((start) => {- const date = new Date(start);- const isToday = start === today;- return <div key={start} role="columnheader" className={cn("border-b border-r border-hairline/40 px-2 py-2 text-center last:border-r-0", isToday && "bg-accent/[0.035]")}><div className={cn("text-[10px] font-medium uppercase tracking-[0.14em]", isToday ? "text-accent" : "text-ink-secondary")}>{dayName(date.getDay())}</div><div className={cn("mx-auto mt-1 flex size-8 items-center justify-center rounded-full text-[15px] font-medium", isToday ? "bg-accent text-accent-ink" : "text-ink")}>{date.getDate()}</div></div>;- })}- </div>- <div role="grid" aria-label={t("routines.calendar.label")} onDragEnd={() => setDragPreview(null)} className="relative grid" style={{ height: HOUR_HEIGHT * 24, gridTemplateColumns, minWidth }}>- <div className="relative border-r border-hairline/40">- {Array.from({ length: 24 }, (_, hour) => <div key={hour} className="absolute right-2 -translate-y-1/2 text-[10px] tabular-nums text-ink-tertiary" style={{ top: hour * HOUR_HEIGHT }}>{hour === 0 ? "" : new Date(2000, 0, 1, hour).toLocaleTimeString(intlLocale(), { hour: "numeric" })}</div>)}- </div>- {starts.map((start) => {- const now = new Date();- const nowTop = ((now.getHours() * 60 + now.getMinutes()) / 60) * HOUR_HEIGHT;- const dayItems = items.filter((item) => startOfDay(item.at) === start);- const collisionLayouts = packCalendarCollisions(dayItems);- const selected = selection?.day === start ? selection : null;- const preview = dragPreview?.day === start ? dragPreview : null;- return (- <div key={start} role="gridcell" aria-label={t("routines.calendar.day", { date: niceDate(start) })} onPointerDown={(event) => beginSelection(event, start)} onDragOver={(event) => previewDrop(event, start)} onDragLeave={(event) => { if (!(event.relatedTarget instanceof Node) || !event.currentTarget.contains(event.relatedTarget)) setDragPreview(null); }} onDrop={(event) => drop(event, start)} className={cn("relative border-r border-hairline/40 last:border-r-0", start === today && "bg-accent/[0.025]")}>- {Array.from({ length: 48 }, (_, half) => <div key={half} className={cn("pointer-events-none absolute inset-x-0 border-t", half % 2 === 0 ? "border-hairline/30" : "border-hairline/10")} style={{ top: (half / 2) * HOUR_HEIGHT }} />)}- {start === today && <div className="pointer-events-none absolute inset-x-0 z-20 flex items-center" style={{ top: nowTop }}><span className="-ml-1 size-2 rounded-full bg-danger" /><span className="h-px flex-1 bg-danger/80" /></div>}- {selected && <div className="pointer-events-none absolute inset-x-1 z-10 rounded-md border border-accent/70 bg-accent/20" style={{ top: ((new Date(selected.start).getHours() * 60 + new Date(selected.start).getMinutes()) / 60) * HOUR_HEIGHT, height: Math.max(16, ((selected.end - selected.start) / 3_600_000) * HOUR_HEIGHT) }} />}- {preview && <div className="pointer-events-none absolute inset-x-1 z-20 rounded-md border border-accent/80 bg-accent/25 shadow-sm" style={{ top: ((new Date(preview.at).getHours() * 60 + new Date(preview.at).getMinutes()) / 60) * HOUR_HEIGHT, height: HOUR_HEIGHT / 2 }}><div className="px-2 py-1 text-[10px] font-medium text-accent">{niceTime(preview.at)}</div></div>}- {markers.filter((marker) => startOfDay(marker.at) === start).map((marker) => <LimitResetMarker key={marker.engine} marker={marker} hourHeight={HOUR_HEIGHT} onDrop={onDropOnReset && ((drop) => onDropOnReset(drop, marker))} />)}- {dayItems.map((item) => <CalendarEventCard key={item.id} item={item} bots={bots} groups={groups} compact={days === 7} layout={collisionLayouts.get(item.id) ?? { column: 0, columns: 1 }} selected={item.id === selectedId} onOpen={() => onOpen(item)} onResize={(minutes) => onResize(item, minutes)} />)}- </div>- );- })}- </div>- </div>- );-}-export function EventDetails({item,bots,@@ -1564,7 +1427,7 @@ export function PausedList({onEdit: (routine: Routine) => void;onOpenRoom: (id: string) => void;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const dialogRef = useRef<HTMLDivElement>(null);useModalDialog(dialogRef, onClose);return (diff --git a/src/components/ServerUpdateRow.tsx b/src/components/ServerUpdateRow.tsxindex 942fc7f1ef..f3c1253966 100644--- a/src/components/ServerUpdateRow.tsx+++ b/src/components/ServerUpdateRow.tsx@@ -5,10 +5,11 @@ import { openExternalLink } from "@/lib/app-links";import { t } from "@/lib/i18n";import { serverUpdateConfirmBody, serverUpdateView, type ServerUpdateCheck, type ServerUpdateStatus, type ServerUpdateView } from "@/lib/server-update";import { ApiError } from "@/state/api";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";import type { AppUpdateAnswer } from "@/types/ogb";import { ConfirmDialog } from "./ConfirmDialog";import { SettingRow } from "./SettingsPrimitives";+import { sameFields, useStoreSelector } from "@/state/store-select";const STATUS = "/api/updates/server";const POLL_MS = 4_000;@@ -24,7 +25,7 @@ const settled = (status: ServerUpdateStatus | null) => status?.run?.outcome !==/** The check every session may read, the admin's button state, and the press. While the server restarts the page's* connection drops; the store's own reconnect brings it back (`state.connected`), and only then is the server asked again. */export function useServerUpdate() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ connected: s.connected }), sameFields);const connected = state.connected !== false;const [check, setCheck] = useState<ServerUpdateCheck | null>(null);const [status, setStatus] = useState<ServerUpdateStatus | null>(null);diff --git a/src/components/ShareLearnedSkillsSettings.tsx b/src/components/ShareLearnedSkillsSettings.tsxindex bf4106329b..b3232ef94a 100644--- a/src/components/ShareLearnedSkillsSettings.tsx+++ b/src/components/ShareLearnedSkillsSettings.tsx@@ -2,9 +2,10 @@ import { useState } from "react";import { shareLearnedSkillsMode, skillAuthoringEnabled, skillsLibraryEnabled } from "@/lib/feature-flags";import { t } from "@/lib/i18n";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { SkillReviewSettings } from "./SkillReviewSettings";import { MoreText, Segmented, SettingRow } from "./SettingsPrimitives";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const MODES = [{ value: "off", label: "settings.experimental.shareSkillsOff" },@@ -13,7 +14,7 @@ const MODES = [] as const;export function ShareLearnedSkillsSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const [saving, setSaving] = useState(false);const [error, setError] = useState("");if (!skillsLibraryEnabled(state.config)) return null;diff --git a/src/components/SkillReviewSettings.tsx b/src/components/SkillReviewSettings.tsxindex d148144c28..92546431f0 100644--- a/src/components/SkillReviewSettings.tsx+++ b/src/components/SkillReviewSettings.tsx@@ -9,16 +9,17 @@ import {skillReviewSteps,skillReviewUnavailableEngines,} from "@/lib/feature-flags";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { MoreText, SETTINGS_INLINE_INPUT, SettingRow, Switch } from "./SettingsPrimitives";+import { sameFields, sameItems, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function SkillReviewSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const authoring = skillAuthoringEnabled(state.config);const enabled = skillReviewEnabled(state.config);const confirmedSteps = skillReviewSteps(state.config);- const unavailable = skillReviewUnavailableEngines(state.bots, state.instances);+ const unavailable = useStoreSelector((s) => skillReviewUnavailableEngines(s.bots, s.instances), sameItems);const [value, setValue] = useState(String(confirmedSteps));const [dirty, setDirty] = useState(false);const [saving, setSaving] = useState(false);diff --git a/src/components/SkillsSection.behavior.test.ts b/src/components/SkillsSection.behavior.test.tsindex 42e8d5c46c..5ed834c111 100644--- a/src/components/SkillsSection.behavior.test.ts+++ b/src/components/SkillsSection.behavior.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { SkillsLibrarySkillWire } from "../../shared/wire";const fixture = vi.hoisted(() => ({ values: [] as unknown[], index: 0, modal: vi.fn(), request: vi.fn() }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("react", async (original) => ({...await original<typeof import("react")>(),useState: (initial: unknown) => {diff --git a/src/components/TeamSideSwitch.tsx b/src/components/TeamSideSwitch.tsxindex 481a2e7d8e..857ed203e8 100644--- a/src/components/TeamSideSwitch.tsx+++ b/src/components/TeamSideSwitch.tsx@@ -7,6 +7,7 @@ import { t } from "@/lib/i18n";import { useShowThreads } from "@/lib/thread-preferences";import { openBot, useStore, type AppState, type Bot, type Group } from "@/state/store";import { listedSide, setTeamSide, showTeamSide, sideOfThread, teamSide, teamSideView, useTeamSide, type TeamSide } from "@/state/team-side";+import { useStoreSelector } from "@/state/store-select";import { markTeamPrivateChatsLineSaid, sharedChatAudience } from "./TeamPrivateChatsLine";const SIDES = [{ side: "me", label: "teamSide.me", Icon: Lock }, { side: "team", label: "teamSide.team", Icon: Users }] as const;@@ -32,9 +33,9 @@ export function useTeamSideLists(state: Pick<AppState, "bots" | "groups" | "conf/** The side the conversation a bot has on screen is listed on, on a team's Cloud; null anywhere else. */export function useConversationSide(bot: Bot): TeamSide | null {- const { state } = useStore();+ const onTeam = useStoreSelector((state) => Boolean(state.config?.team));const { team } = useTeamSide();- return state.config?.team && team ? listedSide(bot, bot.threadId) : null;+ return onTeam && team ? listedSide(bot, bot.threadId) : null;}function hintDue(teamId: string): boolean {diff --git a/src/components/ThreadCleanupSettings.tsx b/src/components/ThreadCleanupSettings.tsxindex 269060f6a6..a2c32ec380 100644--- a/src/components/ThreadCleanupSettings.tsx+++ b/src/components/ThreadCleanupSettings.tsx@@ -1,8 +1,9 @@import { useEffect, useRef, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { SETTINGS_INLINE_INPUT, SettingRow, SettingsGroup, SettingsRows, Switch } from "./SettingsPrimitives";import { cn } from "@/lib/cn";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";/** Server bounds from server/config.ts, mirrored to reject out-of-range input before the round trip. */const MIN_RETENTION_DAYS = 1;@@ -35,7 +36,7 @@ function mibText(bytes: number): string {type Knob = "retention" | "cap";export function ThreadCleanupSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const confirmedRetentionDays = state.config?.threads?.eventLogRetentionDays ?? null;const confirmedCapBytes = state.config?.threads?.eventLogMaxBytes ?? null;const [retentionDraft, setRetentionDraft] = useState<string | null>(null);diff --git a/src/components/ThreadConcurrencySettings.tsx b/src/components/ThreadConcurrencySettings.tsxindex 31ec0dbff8..4580e89686 100644--- a/src/components/ThreadConcurrencySettings.tsx+++ b/src/components/ThreadConcurrencySettings.tsx@@ -1,11 +1,12 @@import { useRef, useState } from "react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { t } from "@/lib/i18n";import { SettingRow } from "./SettingsPrimitives";import { Select } from "./Select";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function ThreadConcurrencySettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const confirmed = state.config?.threads?.maxConcurrentPerBot ?? 3;const oneThreadPerBot = state.config?.cloudStarter === true;const [pending, setPending] = useState<number | null>(null);diff --git a/src/components/ThreadModelsLine.tsx b/src/components/ThreadModelsLine.tsxindex cbefbeb27d..1095294b9a 100644--- a/src/components/ThreadModelsLine.tsx+++ b/src/components/ThreadModelsLine.tsx@@ -3,10 +3,11 @@ import { useRef, useState } from "react";import { threadsOnOwnModel } from "../../shared/thread-model";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";export function ThreadModelsLine({ bot, className }: { bot: Bot; className?: string }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [busy, setBusy] = useState(0);const latestRequest = useRef(0);const count = threadsOnOwnModel(bot.modelSelection, bot.tasks ?? []).length;diff --git a/src/components/TriggerCard.tsx b/src/components/TriggerCard.tsxindex 5695c2cfed..af5ef36503 100644--- a/src/components/TriggerCard.tsx+++ b/src/components/TriggerCard.tsx@@ -9,6 +9,7 @@ import { saveWebhookCredential, webhookCredentialStore } from "@/lib/webhook-creimport { api, ApiError, useStore, type OptionCardData } from "@/state/store";import { appWaitingLine } from "@/lib/app-automations";import { useAppTriggers } from "@/lib/app-triggers";+import { useMinuteTick } from "@/lib/minute-tick";import { useAllAutomationActions } from "./automations/app-actions";// The editors live with the Automations page; a chat only loads one when Edit is pressed.@@ -22,6 +23,7 @@ const ACTION = "rounded-md px-1.5 py-0.5 font-medium hover:bg-inset focus-visiblexport function TriggerCard({ card, threadId }: { card: OptionCardData; threadId?: string }) {const { state, dispatch } = useStore();const actions = useAllAutomationActions();+ useMinuteTick();const appTriggers = useAppTriggers();const [editing, setEditing] = useState(false);const [undoing, setUndoing] = useState(false);diff --git a/src/components/TriggersPage.tsx b/src/components/TriggersPage.tsxindex 23965f6f03..f29e389983 100644--- a/src/components/TriggersPage.tsx+++ b/src/components/TriggersPage.tsx@@ -7,8 +7,11 @@ import { t } from "@/lib/i18n";import { isRoutineProblemRun } from "@/lib/routines";import { saveWebhookCredential, webhookCredentialStore } from "@/lib/webhook-credentials";import { botInDepartment, filterableDepartments, GENERAL_DEPARTMENT } from "@/lib/department-filter";-import { useStore } from "@/state/store";+import { type Bot } from "@/state/store";+import { useBotsApartFromTurns } from "@/state/apart-from-turns";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useAppTriggers } from "@/lib/app-triggers";+import { useMinuteTick } from "@/lib/minute-tick";import { AppEventEditor } from "./automations/AppEventEditor";import { useAllAutomationActions } from "./automations/app-actions";import { AutomationPanel } from "./automations/AutomationPanel";@@ -25,11 +28,16 @@ import { schedulableBots, useTeamPeople } from "@/state/team-people";/** The bot filter earns its place only on a long list shared by several bots. */const FILTER_FROM = 9;+const NO_BOTS: Bot[] = [];/** Automations: every schedule and every "when another app sends something", each as one plain sentence. */export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpenRoom: (id: string) => void }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({+ routinesFocus: s.routinesFocus, routines: s.routines, webhooks: s.webhooks, routineRuns: s.routineRuns, sections: s.sections,+ routinesUnreadable: s.config?.routinesUnreadable, routinesLoadState: s.routinesLoadState, hydrated: s.hydrated,+ }), sameFields), bots = useBotsApartFromTurns(), dispatch = useStoreDispatch();const actions = useAllAutomationActions();+ useMinuteTick();const appTriggers = useAppTriggers();const backButtonRef = useRef<HTMLButtonElement>(null);const focus = state.routinesFocus;@@ -40,9 +48,11 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpeconst [newText, setNewText] = useState<string | null>(null);const [editing, setEditing] = useState<{ kind: SetUpKind; id?: string; botId?: string } | null>(null);const routinesOnly = window.ogb?.remoteClient?.active === true;- const visibleBots = state.bots.filter((bot) => !bot.hidden);+ const visibleBots = bots.filter((bot) => !bot.hidden);+ // An editor reads each bot's threads, so while one is open the page follows every change to the bots.+ const editorBots = useStoreSelector((s) => editing ? s.bots : NO_BOTS).filter((bot) => !bot.hidden);const team = useTeamPeople();- const botName = (botId: string) => state.bots.find((bot) => bot.id === botId)?.name ?? t("routines.unavailableBot");+ const botName = (botId: string) => bots.find((bot) => bot.id === botId)?.name ?? t("routines.unavailableBot");useEffect(() => {setBotFilter(focus?.botId ?? "all");@@ -51,9 +61,9 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe}, [focus]);useEffect(() => { backButtonRef.current?.focus({ preventScroll: true }); }, []);- const all = useMemo(() => automationsFrom({ routines: state.routines, webhooks: routinesOnly ? [] : state.webhooks, appTriggers: appTriggers.triggers, runs: state.routineRuns, bots: state.bots }),- [state.routines, state.webhooks, appTriggers.triggers, state.routineRuns, state.bots, routinesOnly]);- const departments = filterableDepartments(state.bots, [...new Set([...(state.sections ?? []), ...state.bots.flatMap((bot) => bot.section ? [bot.section] : [])])]);+ const all = useMemo(() => automationsFrom({ routines: state.routines, webhooks: routinesOnly ? [] : state.webhooks, appTriggers: appTriggers.triggers, runs: state.routineRuns, bots }),+ [state.routines, state.webhooks, appTriggers.triggers, state.routineRuns, bots, routinesOnly]);+ const departments = filterableDepartments(bots, [...new Set([...(state.sections ?? []), ...bots.flatMap((bot) => bot.section ? [bot.section] : [])])]);const showDepartments = departments.names.length + (departments.hasGeneral ? 1 : 0) > 1;const activeDepartment = department === "all" || (department === GENERAL_DEPARTMENT ? departments.hasGeneral : departments.names.includes(department)) ? department : "all";useEffect(() => {@@ -61,7 +71,7 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpesetDepartment("all");setBotFilter("all");}, [activeDepartment, department]);- const inDepartment = (botId: string) => botInDepartment(state.bots.find((bot) => bot.id === botId), activeDepartment);+ const inDepartment = (botId: string) => botInDepartment(bots.find((bot) => bot.id === botId), activeDepartment);const departmentBots = visibleBots.filter((bot) => botInDepartment(bot, activeDepartment));const showFilter = all.length >= FILTER_FROM && new Set(all.map((automation) => automation.botId)).size > 1;const listed = orderAutomations(all.filter((automation) => inDepartment(automation.botId) && (!showFilter || botFilter === "all" || automation.botId === botFilter)));@@ -107,8 +117,8 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe<div className="min-h-0 flex-1 overflow-y-auto"><div className="mx-auto w-full max-w-3xl p-4 sm:p-6"><LimitWarnings botFilter={showFilter ? botFilter : "all"} />- {state.config?.routinesUnreadable && <div role="alert" className="mb-4 rounded-lg bg-danger/10 p-3 text-[12px] leading-relaxed text-danger" data-routines-unreadable="">{t("routines.unreadable")}</div>}- {all.length === 0 && !state.config?.routinesUnreadable && state.routinesLoadState !== "loading" && state.hydrated ? (+ {state.routinesUnreadable && <div role="alert" className="mb-4 rounded-lg bg-danger/10 p-3 text-[12px] leading-relaxed text-danger" data-routines-unreadable="">{t("routines.unreadable")}</div>}+ {all.length === 0 && !state.routinesUnreadable && state.routinesLoadState !== "loading" && state.hydrated ? (<section aria-label={t("automations.empty.title")} className="px-6 py-16 text-center"><div className="mx-auto mb-4 flex size-12 items-center justify-center rounded-2xl bg-accent/10 text-accent"><Zap size={22} /></div><h2 className="text-[17px] font-semibold text-ink">{t("automations.empty.title")}</h2>@@ -159,11 +169,11 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe{newText !== null && (<NewAutomation initialText={newText} onClose={() => setNewText(null)} onSetUpYourself={(kind, botId) => { setNewText(null); setEditing({ kind, botId }); }} />)}- {editing?.kind === "schedule" && (editRoutine || !editing.id) && <RoutineEditor routine={editRoutine} bots={schedulableBots(visibleBots, team, editRoutine?.botId)} initialBotId={editing.botId} plain onClose={() => setEditing(null)} />}+ {editing?.kind === "schedule" && (editRoutine || !editing.id) && <RoutineEditor routine={editRoutine} bots={schedulableBots(editorBots, team, editRoutine?.botId)} initialBotId={editing.botId} plain onClose={() => setEditing(null)} />}{editing?.kind === "webhook" && (editWebhook || !editing.id) && (- <WebhookEditor webhook={editWebhook} bots={visibleBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onCredential={(credential, id) => { saveWebhookCredential(webhookCredentialStore(), id, credential); setOpenId(id); }} />+ <WebhookEditor webhook={editWebhook} bots={editorBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onCredential={(credential, id) => { saveWebhookCredential(webhookCredentialStore(), id, credential); setOpenId(id); }} />)}- {editing?.kind === "app" && (editApp || !editing.id) && <AppEventEditor trigger={editApp} bots={visibleBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onSaved={(trigger) => setOpenId(trigger.id)} />}+ {editing?.kind === "app" && (editApp || !editing.id) && <AppEventEditor trigger={editApp} bots={editorBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onSaved={(trigger) => setOpenId(trigger.id)} />}</ToolPage>);}diff --git a/src/components/UsageBudget.tsx b/src/components/UsageBudget.tsxindex f95b70c0a5..6c3c5062ce 100644--- a/src/components/UsageBudget.tsx+++ b/src/components/UsageBudget.tsx@@ -1,10 +1,11 @@import { useEffect, useState } from "react";import { Loader2, Plus, Trash2 } from "lucide-react";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { formatUsd } from "@/lib/usage";import { Card } from "./SettingsPrimitives";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export interface BudgetState {month: string;@@ -32,7 +33,7 @@ export function budgetTone(state: BudgetState | null): "quiet" | "warning" | "da}export function BudgetCard({ budget }: { budget: BudgetState | null }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const saved = state.config?.budgets ?? {};const [monthly, setMonthly] = useState(saved.monthlyUsd === undefined ? "" : String(saved.monthlyUsd));const [warnAt, setWarnAt] = useState(saved.warnAtPercent === undefined ? "80" : String(saved.warnAtPercent));@@ -111,7 +112,7 @@ function rowsFrom(prices: Record<string, ModelPrice> | undefined): PriceRow[] {}export function PricesCard() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const saved = state.config?.billing;const [currency, setCurrency] = useState(saved?.currency ?? "USD");const [rows, setRows] = useState<PriceRow[]>(rowsFrom(saved?.prices));@@ -193,7 +194,7 @@ export function PricesCard() {}export function UsageBudgetCards({ budget }: { budget: BudgetState | null }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const budgets = entitledTo(state.config, "budgets");const billing = entitledTo(state.config, "billing");if (!budgets && !billing) return null;diff --git a/src/components/UsbPhoneTakeoverSettings.tsx b/src/components/UsbPhoneTakeoverSettings.tsxindex 9ee6d10a00..bea933c0c7 100644--- a/src/components/UsbPhoneTakeoverSettings.tsx+++ b/src/components/UsbPhoneTakeoverSettings.tsx@@ -1,12 +1,12 @@import { usbPhoneTakeoverEnabled } from "@/lib/feature-flags";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";import { useConfigSave } from "./BrowserSettingsRows";import { MoreText, SettingRow, Switch } from "./SettingsPrimitives";+import { sameFields, useStoreSelector } from "@/state/store-select";/** features.usbPhoneTakeover. Shown only where the server reports the flag: one with no USB port leaves it out. */export function UsbPhoneTakeoverSettings() {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const on = usbPhoneTakeoverEnabled(state.config);const { saving, error, save } = useConfigSave();if (state.config?.features?.usbPhoneTakeover === undefined) return null;diff --git a/src/components/VaultSettings.tsx b/src/components/VaultSettings.tsxindex e0c8b9d4d6..2c5bc6d444 100644--- a/src/components/VaultSettings.tsx+++ b/src/components/VaultSettings.tsx@@ -9,13 +9,14 @@ import { addLogin, changeLogin, connectOnePassword, deleteLogin, disconnectOnePaimport { relativeTime } from "@/lib/memory";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { deleteSecret, listVault } from "@/lib/vault";-import { useStore } from "@/state/store";import { Segmented } from "./bot-panel/rows";import { LoginBotPicker, LoginForm } from "./LoginForm";import { Card, LearnMore, SETTINGS_INPUT, SettingsEmptyRow, SettingsField, SettingsGroup, SettingsLinkRow, SettingsRows } from "./SettingsPrimitives";import { SettingsDialog } from "./settings/SettingsDialog";import { EnvImportForm, SecretForm } from "./VaultSecretForms";import { BitwardenConnection } from "./BitwardenConnection";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useBotsApartFromTurns } from "@/state/apart-from-turns";// Security: a row never shows a password or a secret, which no route returns. A saved value can only be replaced.@@ -47,10 +48,10 @@ function rowsOf(logins: LoginSummary[], secrets: Array<VaultSecret | LinkedSecre}export function VaultSettings() {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), allBots = useBotsApartFromTurns(), dispatch = useStoreDispatch();const ownerOrAdmin = useOwnerOrAdmin();const member = ownerOrAdmin === false && Boolean(state.config?.team);- const bots = state.bots.map((bot) => ({ id: bot.id, name: bot.name }));+ const bots = allBots.map((bot) => ({ id: bot.id, name: bot.name }));const [logins, setLogins] = useState<LoginSummary[] | null>(null);const [secrets, setSecrets] = useState<Array<VaultSecret | LinkedSecret>>([]);const [onePassword, setOnePassword] = useState<OnePasswordStatus>({ connected: false });@@ -164,9 +165,9 @@ export function VaultSettings() {<div className="mt-0.5 text-[12px] leading-snug text-ink-tertiary">{[t(SOURCE_KEYS[login.source]), whoLine(login.bots, login.onePassword), used(login.lastUsedAt)].join(" · ")}</div>- {loginHeldBackFor(login, state.bots).length > 0 && (+ {loginHeldBackFor(login, allBots).length > 0 && (<div className="mt-0.5 text-[12px] leading-snug text-warning" data-login-held-back>- {t("settings.logins.sharedBrowser", { bots: botNames(loginHeldBackFor(login, state.bots)) })}+ {t("settings.logins.sharedBrowser", { bots: botNames(loginHeldBackFor(login, allBots)) })}</div>)}</div>diff --git a/src/components/WorkersAiKeyCard.tsx b/src/components/WorkersAiKeyCard.tsxindex bf9af8813a..19107adc92 100644--- a/src/components/WorkersAiKeyCard.tsx+++ b/src/components/WorkersAiKeyCard.tsx@@ -3,8 +3,9 @@import { useState } from "react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";import { SETTINGS_INPUT, SettingsField, SettingsFormFoot, SettingsGroup, SettingsRows, StatusDot } from "./SettingsPrimitives";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const TOKEN_URL = "https://dash.cloudflare.com/profile/api-tokens";const ACCOUNT_ID = /^[0-9a-f]{32}$/i;@@ -12,7 +13,7 @@ const ACCOUNT_ID = /^[0-9a-f]{32}$/i;type TestResult = { ok: true; latencyMs: number; extraction?: { ok: boolean } } | { ok: false; reason: string; status?: number; extraction?: { ok: boolean } };export function WorkersAiKeyCard({ failureText }: { failureText: (result: { reason: string; status?: number }) => string }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const helpers = state.config?.helpers;const saved = helpers?.own.workersAi === true;const savedAccount = helpers?.workersAiAccountId ?? "";diff --git a/src/components/automations/AppEventEditor.tsx b/src/components/automations/AppEventEditor.tsxindex e1b4dc9e4c..d3319b0657 100644--- a/src/components/automations/AppEventEditor.tsx+++ b/src/components/automations/AppEventEditor.tsx@@ -8,15 +8,16 @@ import { useModalDialog } from "@/hooks/use-modal-dialog";import { appTriggerApi, type AppEventCatalog, type AppTrigger, type AppTriggerFilter } from "@/lib/app-triggers";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { Select } from "../Select";import { suggestedName } from "../WebhookTrigger";+import { useStoreDispatch } from "@/state/store-select";const FIELD = "w-full rounded-xl border border-hairline/60 bg-panel px-3.5 py-2.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent/70";const LABEL = "mb-1.5 block text-[12px] font-medium text-ink-secondary";export function AppEventEditor({ trigger, bots, initialBotId, onClose, onSaved }: { trigger?: AppTrigger; bots: Bot[]; initialBotId?: string; onClose: () => void; onSaved?: (trigger: AppTrigger) => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [botId, setBotId] = useState(trigger?.botId ?? (initialBotId && bots.some((bot) => bot.id === initialBotId) ? initialBotId : bots[0]?.id) ?? "");const [catalog, setCatalog] = useState<AppEventCatalog | null>(null);const [app, setApp] = useState(trigger?.app ?? "");diff --git a/src/components/automations/AutomationPanel.tsx b/src/components/automations/AutomationPanel.tsxindex fa17ac0977..50bcc2e213 100644--- a/src/components/automations/AutomationPanel.tsx+++ b/src/components/automations/AutomationPanel.tsx@@ -7,10 +7,11 @@ import { copyText } from "@/lib/copy-text";import { t } from "@/lib/i18n";import { isRoutineProblemRun } from "@/lib/routines";import { loadWebhookCredentials, webhookCredentialStore } from "@/lib/webhook-credentials";-import { useStore } from "@/state/store";import { AppEventsSection } from "./AppEventsSection";import { useAllAutomationActions } from "./app-actions";import { FixButton, StatusMark } from "./parts";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useMinuteTick } from "@/lib/minute-tick";const RECENT = 5;const BUTTON = "flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-[13px] font-medium disabled:opacity-50";@@ -23,7 +24,8 @@ export function AutomationPanel({ automation, sentence, onClose, onEdit, onDeletonEdit: () => void;onDeleted: () => void;}) {- const { state, dispatch } = useStore();+ useMinuteTick();+ const state = useStoreSelector((s) => ({ bots: s.bots, config: s.config, webhookAttempts: s.webhookAttempts, webhookIngress: s.webhookIngress, webhooks: s.webhooks }), sameFields), dispatch = useStoreDispatch();const [unseenRunIds] = useState(() => new Set(automation.runs.filter((run) => isRoutineProblemRun(run) && !run.seenAt).map((run) => run.id)));const visibleRuns = automation.runs.filter((run, index) => index < RECENT || unseenRunIds.has(run.id) || (isRoutineProblemRun(run) && !run.seenAt));useEffect(() => {diff --git a/src/components/automations/AutomationsCalendar.tsx b/src/components/automations/AutomationsCalendar.tsxindex 7b252eab56..0468b58cc1 100644--- a/src/components/automations/AutomationsCalendar.tsx+++ b/src/components/automations/AutomationsCalendar.tsx@@ -5,17 +5,21 @@ import { CalendarSidebar } from "@/components/routines/CalendarSidebar";import type { CalendarCall } from "@/lib/calendar-calls";import { cn } from "@/lib/cn";import { botInDepartment } from "@/lib/department-filter";-import { t } from "@/lib/i18n";+import { activeLocale, t } from "@/lib/i18n";import { addDays, calendarRangeLabel, projectCalls, projectedRoutineItems, scheduleAt, startOfDay, startOfWeek } from "@/lib/routine-calendar";import { resetMarkers, useEngineLimits, type ResetMarker } from "@/lib/limit-resets";import { automationsFrom, automationStatus } from "@/lib/automations";import type { RoutineRun } from "@/lib/routines";-import { api, useStore } from "@/state/store";+import { api, type Bot } from "@/state/store";+import { useBotsApartFromTurns, useGroupsApartFromTurns } from "@/state/apart-from-turns";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useRoutineRunsFrom } from "@/state/older-routine-runs";import { schedulableBots, useTeamPeople } from "@/state/team-people";import { CalendarGrid, EventDetails, EventEditor, QuickComposer, type CalendarEventItem, type EventKind, type EventSeed } from "../RoutineCalendarPage";import type { ResetDrop } from "../routines/LimitResetMarkers";+const NO_BOTS: Bot[] = [];+/** The schedules (and scheduled calls) on a week or day grid. An automation opens the same panel as the list; a call* keeps its own details. */export function AutomationsCalendar({ botFilter, department = "all", selectedAutomationId, onOpenAutomation, onOpenRoom }: {@@ -25,7 +29,8 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAutonOpenAutomation: (id: string) => void;onOpenRoom: (id: string) => void;}) {- const { state, dispatch } = useStore();+ const routines = useStoreSelector((state) => state.routines), routineRuns = useStoreSelector((state) => state.routineRuns);+ const bots = useBotsApartFromTurns(), groups = useGroupsApartFromTurns(), dispatch = useStoreDispatch();const routinesOnly = window.ogb?.remoteClient?.active === true;const [days, setDays] = useState<1 | 7>(() => (window.innerWidth < 640 ? 1 : 7));const [anchor, setAnchor] = useState(() => startOfDay(Date.now()));@@ -34,8 +39,10 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAutconst [editor, setEditor] = useState<EventSeed | null>(null);const [selected, setSelected] = useState<CalendarEventItem | null>(null);const [error, setError] = useState("");- const visibleBots = state.bots.filter((bot) => !bot.hidden);- const routineBots = schedulableBots(visibleBots, useTeamPeople(), editor?.botIds[0]);+ const visibleBots = useMemo(() => bots.filter((bot) => !bot.hidden), [bots]);+ // The details and the editors read each bot's threads, so while one is open the calendar follows every change to the bots.+ const liveBots = useStoreSelector((state) => selected || quick || editor ? state.bots : NO_BOTS);+ const routineBots = schedulableBots(liveBots.filter((bot) => !bot.hidden), useTeamPeople(), editor?.botIds[0]);const rangeStart = days === 7 ? startOfWeek(anchor) : startOfDay(anchor);const rangeEnd = addDays(rangeStart, days);useRoutineRunsFrom(rangeStart);@@ -48,20 +55,20 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAutuseEffect(() => { if (!routinesOnly) void loadCalls(); }, [loadCalls, routinesOnly]);const items = useMemo<CalendarEventItem[]>(() => {- const botIds = new Set(state.bots.map((bot) => bot.id));- const routines = state.routines.filter((routine) => botIds.has(routine.botId));- const needsYou = new Set(automationsFrom({ routines, webhooks: [], runs: state.routineRuns }).filter((automation) => automationStatus(automation).state === "needs-you").map((automation) => automation.id));- const routineItems = projectedRoutineItems(routines, state.routineRuns.filter((run) => botIds.has(run.botId)), rangeStart, rangeEnd)+ const botIds = new Set(bots.map((bot) => bot.id));+ const owned = routines.filter((routine) => botIds.has(routine.botId));+ const needsYou = new Set(automationsFrom({ routines: owned, webhooks: [], runs: routineRuns }).filter((automation) => automationStatus(automation).state === "needs-you").map((automation) => automation.id));+ const routineItems = projectedRoutineItems(owned, routineRuns.filter((run) => botIds.has(run.botId)), rangeStart, rangeEnd).map((item) => ({ ...item, kind: "routine" as const, needsYou: Boolean(item.routine && !item.run && needsYou.has(item.routine.id)) }));const callItems = projectCalls(calls, rangeStart, rangeEnd).map((item) => ({ ...item, kind: "call" as const }));- const botOf = (id: string | undefined) => state.bots.find((bot) => bot.id === id);+ const botOf = (id: string | undefined) => bots.find((bot) => bot.id === id);return [...routineItems, ...callItems].filter((item) => item.kind === "call"? item.call.botIds.some((id) => botInDepartment(botOf(id), department)): botInDepartment(botOf(item.routine?.botId ?? item.run?.botId), department)).filter((item) => botFilter === "all" || (item.kind === "call" ? item.call.botIds.includes(botFilter) : (item.routine?.botId ?? item.run?.botId) === botFilter)).sort((left, right) => left.at - right.at);- }, [state.routines, state.routineRuns, state.bots, calls, rangeStart, rangeEnd, botFilter, department]);+ }, [routines, routineRuns, bots, calls, rangeStart, rangeEnd, botFilter, department]);const liveSelected = selected?.kind === "call"? (() => { const call = calls.find((candidate) => candidate.id === selected.call.id); return call ? { ...selected, call } : null; })()@@ -79,7 +86,7 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAutif (nextAt === dragged.at) return;try {if (dragged.kind === "routine") {- const routine = state.routines.find((candidate) => candidate.id === dragged.id);+ const routine = routines.find((candidate) => candidate.id === dragged.id);if (!routine) return;if (routine.schedule.type === "cron") throw new Error(t("automations.calendar.cronMove"));if (routine.schedule.type !== "once" && !window.confirm(t("automations.calendar.moveSeries"))) return;@@ -130,6 +137,7 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAutsetEditor({ kind: "call", at: liveSelected.at, durationMinutes: liveSelected.call.durationMinutes, botIds: liveSelected.call.botIds, call: liveSelected.call });setSelected(null);};+ const selectDate = useCallback((at: number) => setAnchor(startOfDay(at)), []);const segment = (active: boolean) => cn("rounded-md px-3 py-1 text-[12px] font-medium", active ? "bg-raised text-ink shadow-sm" : "text-ink-secondary hover:text-ink");return (@@ -146,15 +154,15 @@ export function AutomationsCalendar({ botFilter, department = "all", selectedAut{error && <button type="button" onClick={() => setError("")} className="w-full text-left text-[12px] text-danger">{error}</button>}</div><div className="relative flex min-h-0 flex-1">- {!liveSelected && <div className="hidden shrink-0 @min-[1040px]/routines:block"><CalendarSidebar bots={visibleBots} anchor={anchor} onSelectDate={(at) => setAnchor(startOfDay(at))} /></div>}- <CalendarGrid anchor={rangeStart} days={days} items={items} bots={state.bots} groups={state.groups} selectedId={selectedId}+ {!liveSelected && <div className="hidden shrink-0 @min-[1040px]/routines:block"><CalendarSidebar bots={visibleBots} anchor={anchor} onSelectDate={selectDate} locale={activeLocale()} /></div>}+ <CalendarGrid anchor={rangeStart} days={days} items={items} bots={bots} groups={groups} selectedId={selectedId}onOpen={openItem}onCreate={(seed) => { setSelected(null); setQuick(seed); }}onMove={(item, at) => void moveEvent(item, at)} onResize={(item, duration) => void resizeEvent(item, duration)}markers={markers} onDropOnReset={(drop, marker) => void dropOnReset(drop, marker)} />{liveSelected && (<div className="absolute inset-y-0 right-0 z-30 flex shadow-2xl @min-[760px]/routines:static @min-[760px]/routines:shadow-none">- <EventDetails key={`${liveSelected.kind}:${liveSelected.id}`} item={liveSelected} bots={state.bots} onClose={() => setSelected(null)} onEdit={editSelected} onOpenRun={openRun}+ <EventDetails key={`${liveSelected.kind}:${liveSelected.id}`} item={liveSelected} bots={liveBots} onClose={() => setSelected(null)} onEdit={editSelected} onOpenRun={openRun}onCallChanged={(id) => { if (id) setCalls((current) => current.filter((call) => call.id !== id)); else void loadCalls(); }} onOpenRoom={onOpenRoom} /></div>)}diff --git a/src/components/automations/LimitWarnings.tsx b/src/components/automations/LimitWarnings.tsxindex bc2d76b9b4..f30692e0fa 100644--- a/src/components/automations/LimitWarnings.tsx+++ b/src/components/automations/LimitWarnings.tsx@@ -4,19 +4,21 @@ import { Hourglass } from "lucide-react";import { t } from "@/lib/i18n";import { dueBeforeReset, limitLine, nearLimitEngines, useEngineLimits, type EngineLimit } from "@/lib/limit-resets";import type { Routine } from "@/lib/routines";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useBotsApartFromTurns } from "@/state/apart-from-turns";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";/** Each engine near its limit, with the automations due before it resets and one button that moves just their next* run to after the reset. */export function LimitWarnings({ botFilter = "all" }: { botFilter?: string }) {- const { state, dispatch } = useStore();+ const allRoutines = useStoreSelector((state) => state.routines), bots = useBotsApartFromTurns(), dispatch = useStoreDispatch();const engines = nearLimitEngines(useEngineLimits());const [busy, setBusy] = useState<string | null>(null);const [moved, setMoved] = useState<string | null>(null);const [error, setError] = useState("");if (!engines.length) return null;- const botEngine = (botId: string) => state.bots.find((bot) => bot.id === botId)?.modelSelection?.instanceId;- const routines = state.routines.filter((routine) => botFilter === "all" || routine.botId === botFilter);+ const botEngine = (botId: string) => bots.find((bot) => bot.id === botId)?.modelSelection?.instanceId;+ const routines = allRoutines.filter((routine) => botFilter === "all" || routine.botId === botFilter);const move = async (limit: EngineLimit, due: Routine[]) => {setBusy(limit.engine);setError("");diff --git a/src/components/automations/NewAutomation.tsx b/src/components/automations/NewAutomation.tsxindex 35d9d87788..722b1bd5de 100644--- a/src/components/automations/NewAutomation.tsx+++ b/src/components/automations/NewAutomation.tsx@@ -5,8 +5,9 @@ import { useModalDialog } from "@/hooks/use-modal-dialog";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { imeComposing } from "@/lib/send-key";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { Select } from "../Select";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export type SetUpKind = "schedule" | "webhook" | "app";@@ -25,7 +26,7 @@ export function NewAutomation({ initialText = "", onClose, onSetUpYourself }: {/** The bot this box would have asked, so the editor starts with it chosen. */onSetUpYourself: (kind: SetUpKind, botId: string) => void;}) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ bots: s.bots, selectedId: s.selectedId }), sameFields), dispatch = useStoreDispatch();const bots = state.bots.filter((bot) => !bot.hidden);const [text, setText] = useState(initialText);const [botId, setBotId] = useState(() => defaultBot(bots, state.selectedId)?.id ?? "");diff --git a/src/components/automations/actions.ts b/src/components/automations/actions.tsindex 8ae0869fe6..afcd3b2fab 100644--- a/src/components/automations/actions.ts+++ b/src/components/automations/actions.ts@@ -8,10 +8,11 @@ import type { RoutineRun } from "@/lib/routines";import { useShowThreads } from "@/lib/thread-preferences";import { loadWebhookCredentials, removeWebhookCredential, saveWebhookCredential, webhookCredentialStore } from "@/lib/webhook-credentials";import type { WebhookCredential } from "@/lib/webhooks";-import { api, openBotThread, useStore } from "@/state/store";+import { api, openBotThread } from "@/state/store";+import { useStoreRef } from "@/state/store-ref";export function useAutomationActions() {- const { state, dispatch } = useStore();+ const store = useStoreRef(), dispatch = store.dispatch;const showThreads = useShowThreads();const [busy, setBusy] = useState<string | null>(null);const [error, setError] = useState("");@@ -79,7 +80,7 @@ export function useAutomationActions() {});const openRun = (automation: Automation, run: RoutineRun | undefined) => {- const bot = state.bots.find((candidate) => candidate.id === automation.botId);+ const bot = store.state().bots.find((candidate) => candidate.id === automation.botId);if (bot && run?.threadId) openBotThread(dispatch, bot, run.threadId, showThreads);};diff --git a/src/components/automations/parts.tsx b/src/components/automations/parts.tsxindex cfecd05da3..c9d90e9060 100644--- a/src/components/automations/parts.tsx+++ b/src/components/automations/parts.tsx@@ -3,8 +3,8 @@ import { Check, TriangleAlert } from "lucide-react";import { AUTOMATION_FIX_LABEL, runAwaitingAnswer, type Automation, type AutomationStatus } from "@/lib/automations";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";import type { useAllAutomationActions } from "./app-actions";+import { useStoreDispatch } from "@/state/store-select";/** A coloured dot for Working and Paused; a warning sign for Needs you; a quiet check for Done. */export function StatusMark({ status, className }: { status: AutomationStatus; className?: string }) {@@ -21,7 +21,7 @@ export function FixButton({ automation, status, actions, onEdit, className }: {onEdit: () => void;className?: string;}) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();if (status.state !== "needs-you" || !status.fix) return null;const fix = status.fix;const waiting = fix === "answer" ? runAwaitingAnswer(automation.runs) : undefined;diff --git a/src/components/avatar-editing.tsx b/src/components/avatar-editing.tsxindex ff1a3b9dac..30f9713324 100644--- a/src/components/avatar-editing.tsx+++ b/src/components/avatar-editing.tsx@@ -1,6 +1,6 @@import { useRef, useState, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { imageAttachmentFromFile } from "@/lib/composer-attachments";import { useOrganizationBranding } from "@/lib/use-organization-branding";import { t } from "@/lib/i18n";@@ -15,6 +15,7 @@ import {} from "../../shared/bot-avatar";import { BotAvatar } from "./Avatar";import { useBotEditor } from "./bot-settings/BotEditorContext";+import { useStoreActions } from "@/state/store-select";export type AvatarPatch = Partial<Pick<Bot, "avatarCrop" | "avatarUrl" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor">@@ -131,7 +132,7 @@ export function OrganizationAvatarIcons({ busy, onUpload }: { busy: boolean; onU}export function useAvatarImage(bot: Bot, onPatch: (patch: AvatarPatch) => void) {- const { flushBotPatches } = useStore();+ const { flushBotPatches } = useStoreActions();const { request: api, uploadAvatar } = useBotEditor();const fileRef = useRef<HTMLInputElement>(null);const [uploading, setUploading] = useState(false);diff --git a/src/components/background-turn.render-count.test.ts b/src/components/background-turn.render-count.test.tsnew file mode 100644index 0000000000..734c5ab67e--- /dev/null+++ b/src/components/background-turn.render-count.test.ts@@ -0,0 +1,176 @@+// @vitest-environment happy-dom+// The real provider and live stream, with Settings, the routines calendar, a bot's settings, the command palette or the+// Inbox open behind a parent that reads the whole store as App does: another bot's turn draws none of them.+import { renderMark, renderedSince } from "@/testing/render-counts";+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { Action, AppSettingsSection, BotAnnouncement, BotSettingsSection, InstanceInfo } from "@/state/store";++const mode = vi.hoisted(() => ({ advanced: true }));+vi.mock("@/lib/interface-mode", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/interface-mode")>(), useAdvancedMode: () => mode.advanced }));+vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn(), analyticsEnabled: () => false, setAnalyticsEnabled: vi.fn() }));+// What shows the time draws again as a minute turns; these counts are of store changes alone.+vi.mock("@/lib/minute-tick", () => ({ useMinuteTick: () => 0 }));+vi.mock("@/lib/cloud-guest", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useCanWriteIn: () => true, useReactor: () => "user" }));++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const announced = (i: number, extra: Partial<BotAnnouncement> = {}): BotAnnouncement => ({+ id: `b${i}`, threadId: `b${i}-thread`, name: `Bot ${i}`, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "test", model: "m" }, section: i % 3 === 0 ? "Sales" : undefined,+ tasks: [{ threadId: `b${i}-thread`, title: "Chat", createdAt: 1, approvalMode: "ask" }], ...extra,+} as BotAnnouncement);+const at = Date.UTC(2026, 10, 18, 9);+const routines = Array.from({ length: 12 }, (_, i) => ({+ id: `r${i}`, name: `Routine ${i}`, prompt: "Do it.", target: "bot", botId: `b${i % 12}`, runOn: "maus", enabled: true,+ schedule: { type: "daily", time: `${String(8 + (i % 10)).padStart(2, "0")}:00`, weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30,+ nextRunAt: at + 3_600_000, createdAt: 0, updatedAt: 0,+}));+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const answers: Record<string, unknown> = {+ "/api/instances": { instances: [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" }, models: { default: "m", options: [{ id: "m", label: "Model" }] } } as unknown as InstanceInfo] },+ "/api/config": {+ anthropic: { configured: true }, composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" },+ rooms: { turnTimeoutMinutes: 10 }, mcp: { callTimeoutMinutes: 5 }, threads: { maxConcurrentPerBot: 3 }, localVm: { mode: "shared", maxInstances: 1 },+ profile: { name: "Ada", email: "[email protected]", aboutMe: "" }, features: {}, edition: { edition: "community", features: [] }, browserProfiles: [],+ budgets: {}, billing: { currency: "USD", prices: {} }, pausedBots: [], heldBots: [], newBots: {},+ },+ "/api/routines": { routines, runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] },+ "/api/profile/learned": { learned: [] },+ "/api/themes": { themes: [] },+ "/api/themes/history": { items: [] },+};+const missing = () => Promise.resolve(new Response(JSON.stringify({ error: "not in this fixture" }), { status: 404 }));++const { StoreProvider, useStore } = await import("@/state/store");+const { SettingsModal, TriggersPage, BotSettingsDialog } = await import("./lazy-screens");+await Promise.all([SettingsModal.preload(), TriggersPage.preload(), BotSettingsDialog.preload()]);+const { CommandPalette, openCommandPalette } = await import("./CommandPalette");+const { InboxPanel } = await import("./inbox/InboxPanel");+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false;++type Surface = "settings" | "calendar" | "bot-settings" | "palette" | "inbox" | "none";+let surface: Surface = "none";+let dispatch!: (action: Action) => void;+const onBack = () => {}, onOpenRoom = () => {}, onOpenChange = () => {};+function App() {+ const { state, dispatch: storeDispatch } = useStore();+ dispatch = storeDispatch;+ const bot = state.bots.find((candidate) => candidate.id === state.selectedId);+ if (surface === "settings") return createElement(SettingsModal);+ if (surface === "calendar") return createElement(TriggersPage, { onBack, onOpenRoom });+ if (surface === "bot-settings") return bot ? createElement(BotSettingsDialog, { key: bot.id, bot, overlay: false }) : null;+ if (surface === "palette") return createElement(CommandPalette, { onOpenChange });+ if (surface === "inbox") return createElement(InboxPanel);+ return null;+}++let root: Root;+let cursor = 0;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 30; i++) await task(); };+const send = async (frame: object) => { FixtureEventSource.opened[0]!.send(frame, `run:${++cursor}`); await settle(); };+const background = (busy: boolean) => send({ kind: "bot", bot: announced(7, busy ? { busy: true, activity: "working" } : { busy: false, activity: "idle" }) });++async function show(next: Surface, setUp: () => void = () => {}) {+ surface = next;+ flushSync(setUp);+ flushSync(() => dispatch({ type: "connected", value: false }));+ flushSync(() => dispatch({ type: "connected", value: true }));+ await settle();+ // The selected bot's own motion ends with the first move of another bot: that one draw is not what is counted here.+ await background(false);+}++/** The components drawn while another bot works: it goes busy, its turn adds and patches a message, it goes idle. */+async function drawnByAnotherBotsTurn(): Promise<string[]> {+ const mark = renderMark();+ await background(true);+ await send({ kind: "message", threadId: "b7-thread", message: { id: `m${cursor}`, at: at + cursor, role: "bot", kind: "activity", tool: { name: "Bash" } } });+ await send({ kind: "message.patch", threadId: "b7-thread", message: { id: `m${cursor - 1}`, at: at + cursor, role: "bot", kind: "activity", tool: { name: "Bash", ok: true } } });+ await background(false);+ return renderedSince(mark).map((entry) => entry.component).filter((name) => name !== "App" && name !== "StoreProvider");+}++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (input: string) => {+ const path = String(input).replace(/\?.*$/, "");+ if (path === "/api/bots") return json({ bots: Array.from({ length: 12 }, (_, i) => ({ ...announced(i), messages: [] })), groups: [] });+ if (path in answers) return json(answers[path]);+ return /^\/api\/bots\/[^/]+\/overview$/.test(path) ? missing() : json({});+ });+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(App))));+ await settle();+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "select", id: "b0" }));+ await settle();+});+afterAll(() => {+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});+beforeEach(async () => { await show("none"); });++describe("another bot's turn", () => {+ for (const advanced of [true, false]) for (const section of ["overview", "ai", "bots", "general"] as AppSettingsSection[]) {+ it(`draws nothing in Settings → ${section}${advanced ? "" : " (Simple)"}`, async () => {+ mode.advanced = advanced;+ await show("settings", () => dispatch({ type: "toggleAppSettings", open: true, section }));+ expect(document.querySelector("[data-settings-page-body]")).not.toBeNull();+ expect(await drawnByAnotherBotsTurn()).toEqual([]);+ flushSync(() => dispatch({ type: "toggleAppSettings", open: false }));+ });+ }++ it("draws nothing on the routines calendar, its cards included", async () => {+ mode.advanced = true;+ await show("calendar", () => dispatch({ type: "showRoutines", view: "calendar" }));+ expect(document.querySelectorAll("[data-event-card]").length).toBeGreaterThan(0);+ expect(await drawnByAnotherBotsTurn()).toEqual([]);+ });++ for (const advanced of [true, false]) for (const section of ["overview", "model", "permissions", "access"] as BotSettingsSection[]) {+ it(`draws nothing in the selected bot's settings → ${section}${advanced ? "" : " (Simple)"}`, async () => {+ mode.advanced = advanced;+ await show("bot-settings", () => dispatch({ type: "toggleSettings", open: true, section }));+ expect(await drawnByAnotherBotsTurn()).toEqual([]);+ flushSync(() => dispatch({ type: "toggleSettings", open: false }));+ });+ }++ it("draws nothing in the command palette, closed or open", async () => {+ await show("palette");+ expect(await drawnByAnotherBotsTurn()).toEqual([]);+ flushSync(() => openCommandPalette());+ await settle();+ expect(document.querySelectorAll('[role="dialog"] button').length).toBeGreaterThan(0);+ expect(await drawnByAnotherBotsTurn()).toEqual([]);+ });++ it("draws nothing in the Inbox for a patched message that moves no conversation", async () => {+ await show("inbox");+ const mark = renderMark();+ await send({ kind: "message.patch", threadId: "b7-thread", message: { id: "never-added", at, role: "bot", kind: "activity", tool: { name: "Bash", ok: true } } });+ expect(renderedSince(mark).map((entry) => entry.component).filter((name) => name !== "App" && name !== "StoreProvider")).toEqual([]);+ });+});diff --git a/src/components/bot-access/AccessOverview.tsx b/src/components/bot-access/AccessOverview.tsxindex d277abd7e2..68a62b1467 100644--- a/src/components/bot-access/AccessOverview.tsx+++ b/src/components/bot-access/AccessOverview.tsx@@ -5,7 +5,7 @@ import { sharedLevel, type BotAccess } from "../../../shared/bot-access";import { botOwner } from "../../../shared/bot-owner";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { ownerOf, useTeamPeople, type TeamPeople, type TeamPerson } from "@/state/team-people";import { BotAvatar } from "../Avatar";import { PersonFace } from "../TeamOwner";@@ -13,6 +13,7 @@ import { accessOfBot, saveAccess, withPerson } from "./access";import { UndoToast, useTeamName } from "./ShareBotButton";import { ShareBotDialog } from "./ShareBotDialog";import { PeopleStack } from "./PeopleStack";+import { useStoreSelector } from "@/state/store-select";type Change = { botId: string; before: BotAccess; after: BotAccess; text: string };type Listing = "bot" | "person";@@ -36,7 +37,7 @@ const includes = (wanted: string, ...parts: Array<string | undefined>): boolean/** Settings → Bot access on a team, for its admins: the team's bots, or its people, each opening what can change there.* A person's stored level stays as it is; the page shows who is added and lets them be removed. */export function AccessOverview() {- const { state } = useStore();+ const allBots = useStoreSelector((s) => s.bots);const team = useTeamPeople();const teamName = useTeamName();const rootRef = useRef<HTMLDivElement | null>(null);@@ -55,7 +56,7 @@ export function AccessOverview() {}, [personEmail]);if (!team || !teamName) return null;const members = team.people.filter((person) => person.role === "member").sort((a, b) => a.name.localeCompare(b.name));- const bots = sharedBots(state.bots);+ const bots = sharedBots(allBots);const sharing = sharingId ? bots.find((bot) => bot.id === sharingId) : undefined;const person = personEmail ? members.find((member) => member.email === personEmail) : undefined;const wanted = query.trim().toLowerCase();diff --git a/src/components/bot-access/ShareBotButton.tsx b/src/components/bot-access/ShareBotButton.tsxindex a4b6303d2a..c758f37a75 100644--- a/src/components/bot-access/ShareBotButton.tsx+++ b/src/components/bot-access/ShareBotButton.tsx@@ -3,7 +3,7 @@ import { createPortal } from "react-dom";import { Share } from "lucide-react";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store"; import { sameFields, useStoreSelector } from "@/state/store-select";import { saveAccess } from "./access";import { ShareBotDialog } from "../lazy-screens";import type { AccessChange } from "./ShareBotDialog";@@ -12,7 +12,7 @@ const TOAST_MS = 6_000;/** The team's name, or null anywhere but a team. */export function useTeamName(): string | null {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const team = (state.config as { team?: { name?: unknown } } | null | undefined)?.team;return typeof team?.name === "string" && team.name ? team.name : null;}diff --git a/src/components/bot-access/ShareBotDialog.tsx b/src/components/bot-access/ShareBotDialog.tsxindex c1c4aa3dc3..e99b6f1fb5 100644--- a/src/components/bot-access/ShareBotDialog.tsx+++ b/src/components/bot-access/ShareBotDialog.tsx@@ -6,11 +6,12 @@ import type { BotAccess, BotAccessLevel, GrantedLevel } from "../../../shared/boimport { botOwner } from "../../../shared/bot-owner";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { mayChangeOwner, ownerChanged, ownerOf, useTeamPeople, type TeamPeople, type TeamPerson } from "@/state/team-people";import { MENU_SHEET } from "../menu-recipe";import { accessOfBot, addablePeople, canShare, levelWhenAdded, nameOf, personOf, saveAccess, saveOwner, withPerson } from "./access";import { choiceItem, EntryFace, PersonMenu, QuietMenu } from "./ShareControls";+import { useStoreDispatch } from "@/state/store-select";export interface AccessChange { before: BotAccess; after: BotAccess; text: string }@@ -25,7 +26,7 @@ export function ShareBotDialog({ bot, teamName, onClose, onChanged, headerMenu }headerMenu?: ReactNode;}) {const team = useTeamPeople();- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const dialogRef = useRef<HTMLDivElement | null>(null);const [error, setError] = useState("");const [busy, setBusy] = useState(false);diff --git a/src/components/bot-panel/AdvancedSettingsRow.tsx b/src/components/bot-panel/AdvancedSettingsRow.tsxindex 6990330a55..1c305aed75 100644--- a/src/components/bot-panel/AdvancedSettingsRow.tsx+++ b/src/components/bot-panel/AdvancedSettingsRow.tsx@@ -3,12 +3,12 @@ import { SlidersHorizontal } from "lucide-react";import { t } from "@/lib/i18n";import { setAdvancedMode } from "@/lib/interface-mode";import { SIMPLE_ONLY } from "@/lib/simple-only";-import { useStore } from "@/state/store";import { Card, NavRow } from "./rows";+import { useStoreDispatch } from "@/state/store-select";/** Simple mode leaves out Sending on your behalf and per-app Access; this row says they exist and opens them in Advanced mode. */export function AdvancedSettingsRow() {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();if (SIMPLE_ONLY) return null;const open = () => {setAdvancedMode(true);diff --git a/src/components/bot-panel/AvatarEditorCard.tsx b/src/components/bot-panel/AvatarEditorCard.tsxindex 7fdc57d0c4..a971612ed2 100644--- a/src/components/bot-panel/AvatarEditorCard.tsx+++ b/src/components/bot-panel/AvatarEditorCard.tsx@@ -6,7 +6,7 @@ import { t } from "@/lib/i18n";import { bodyName, colorName, festivalName } from "@/lib/mascot-names";import type { LocaleKey } from "@/locales";import { colorSwatch, MAUS_COLOR_LABEL, MAUS_COLOR_NAMES, PICKABLE_STATES, type MausState } from "@/lib/mascot";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { mayRename, useTeamPeople } from "@/state/team-people";import { MASCOT_BODY_IDS } from "../../../shared/mascot-bodies";import { FESTIVAL_IDS, FESTIVALS, isCarvedBody, type BotBodyId } from "../../../shared/bot-body";@@ -16,6 +16,8 @@ import { AvatarImageGenerator } from "../AvatarImageGenerator";import { AvatarFraming, OrganizationAvatarIcons, RESET_MASCOT_PATCH, useAvatarImage, type AvatarPatch } from "../avatar-editing";import { Segmented } from "./rows";import { MascotFaceColorPicker } from "../MascotFaceColorPicker";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useBotsApartFromTurns } from "@/state/apart-from-turns";export type AvatarEditorTab = "bot" | "generate" | "upload";@@ -67,9 +69,9 @@ export function AvatarEditorCard({ bot, activeState, onPatch, onClose }: {}, []);const pickMascot = (patch: AvatarPatch) => onPatch(crop === "mascot" ? patch : { ...patch, avatarCrop: "mascot" });const body = bot.mascotBody ?? "cursor";- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), bots = useBotsApartFromTurns(), dispatch = useStoreDispatch();const team = useTeamPeople();- const othersToMatch = state.bots.filter((other) => other.id !== bot.id && (other.mascotBody ?? "cursor") !== body+ const othersToMatch = bots.filter((other) => other.id !== bot.id && (other.mascotBody ?? "cursor") !== body&& (team ? mayRename(other, team) : !state.config?.team));const festival = useFestivalDress();const costume = wornBody(bot.mascotBody, bot.color, festival);diff --git a/src/components/bot-panel/BackupAis.tsx b/src/components/bot-panel/BackupAis.tsxindex 9ad2ceb52c..eb90515363 100644--- a/src/components/bot-panel/BackupAis.tsx+++ b/src/components/bot-panel/BackupAis.tsx@@ -10,13 +10,14 @@ import { pickerPlacement, type PickerPlacement } from "@/lib/picker-placement";import { shortModelLabel } from "@/lib/model-friendly";import { modelName, providerName, simpleModelMenu } from "@/lib/simple-model-menu";import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";-import { useStore, type Bot, type InstanceInfo } from "@/state/store";+import { type Bot, type InstanceInfo } from "@/state/store";import { useMenuMotion } from "../MenuMotion";import { modelMenuKey, modelMenuPointerMove } from "../model-menu-keys";import { SIMPLE_POPOVER_WIDTH } from "../ModelPicker";import { InstanceProviderMark } from "../ProviderIcons";import { SimpleModelMenu } from "../SimpleModelMenu";import { buttonCls, Card, ColRow, RowIcon, RowText, TrashButton } from "./rows";+import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Backup = NonNullable<Bot["fallback"]>[number];@@ -40,7 +41,7 @@ function BackupChooser({ bot, current, exclude, onPick, label, title, buttonRef,children: ReactNode;"data-panel-action"?: string;}) {- const { state, dispatch, refreshInstances, refreshModels } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields), dispatch = useStoreDispatch(), { refreshInstances, refreshModels } = useStoreActions();const [open, setOpen] = useState(false);const [query, setQuery] = useState("");const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());@@ -216,7 +217,7 @@ function BackupChooser({ bot, current, exclude, onPick, label, title, buttonRef,}export function BackupAis({ bot, onChange }: { bot: Bot; onChange: (fallback: Backup[]) => void }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const chain = bot.fallback ?? [];const addRef = useRef<HTMLButtonElement>(null);const others = (except: number | null) => new Set([bot.modelSelection, ...chain.filter((_, index) => index !== except)]diff --git a/src/components/bot-panel/ComputerTab.tsx b/src/components/bot-panel/ComputerTab.tsxindex 7b2b89f722..0e7443d623 100644--- a/src/components/bot-panel/ComputerTab.tsx+++ b/src/components/bot-panel/ComputerTab.tsx@@ -6,7 +6,7 @@ import { t } from "@/lib/i18n";import type { Place } from "@/lib/place";import { placeHasIssue, worksOnSimpleLabel } from "@/lib/place-view";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import { BotAvatar } from "../Avatar";import { useDesktopCapabilities } from "../DesktopCapabilities";import { LocalComputerAutoWarning } from "../LocalComputerAutoWarning";@@ -16,6 +16,7 @@ import { CloudPreference } from "../bot-settings/AccessSection";import type { BotPatch, useBotSettingsDerived } from "../bot-settings/useBotSettingsDerived";import type { SimplePageId } from "./page-registry";import { Card, NavRow, RadioRow } from "./rows";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Derived = ReturnType<typeof useBotSettingsDerived>;type PlaceChoice = "auto" | Place | "off";@@ -30,7 +31,7 @@ interface PlaceOption {const OFF_LABEL = () => t("place.off");export function useOpenComputer(bot: Pick<Bot, "id">) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();return (view: ComputerPanelView = "computer") => {writeComputerPanelView(bot.id, view);dispatch({ type: "toggleSettings", open: false });@@ -53,7 +54,7 @@ function useSignedInCount(bot: Pick<Bot, "id">, enabled: boolean): number | null}function usePlaceChoices(bot: Bot) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const { capabilities } = useDesktopCapabilities();const platform = capabilities.host?.platform ?? "other";const placeViews = usePlaceViews(bot);@@ -82,7 +83,7 @@ function usePlaceChoices(bot: Bot) {}export function WherePage({ bot, derived }: { bot: Bot; derived: Derived }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { options, current, usingNow } = usePlaceChoices(bot);const [localAutoWarning, setLocalAutoWarning] = useState<{ botId: string; patch: BotPatch } | null>(null);const { patch, approvalMode } = derived;diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsxindex d58bc6f203..c707e97789 100644--- a/src/components/bot-panel/Conversations.tsx+++ b/src/components/bot-panel/Conversations.tsx@@ -4,13 +4,14 @@ import { ChevronDown, ChevronUp, Search, SquarePen } from "lucide-react";import { cn } from "@/lib/cn";import { activeLocale, t } from "@/lib/i18n";import { SIDEBAR_INLINE, useMediaQuery } from "@/lib/use-media-query";-import { api, currentTaskBot, openBotThread, useStore, visibleMessages, type Bot, type Message } from "@/state/store";+import { api, currentTaskBot, openBotThread, visibleMessages, type Bot, type Message } from "@/state/store";import { lastLine } from "../sidebar-preview";import { isArchived, orderedThreadList, SidebarThreadRow, stampClock, threadRecency, threadRowActions, useRelativeNow } from "../SidebarThreadRow";import { filterTasks } from "../TaskPicker";import { useConversationSide } from "../TeamSideSwitch";import { tasksOfSide } from "@/state/team-side";import { CardLabel, panelActionCls } from "./rows";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export const CONVERSATIONS_SHOWN = 3;const PANEL_ROW_LOOK = "[&_.font-semibold]:font-medium [&_time]:text-[12px] [&_time]:text-ink-tertiary [&_span.bg-accent]:size-2";@@ -55,7 +56,7 @@ export function forgetConversationLines(): void {}export function BotConversations({ bot }: { bot: Bot }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances, pendingQueued: s.pendingQueued }), sameFields), dispatch = useStoreDispatch();const now = useRelativeNow();const phone = !useMediaQuery(SIDEBAR_INLINE, true);const [query, setQuery] = useState("");diff --git a/src/components/bot-panel/DetailsTab.tsx b/src/components/bot-panel/DetailsTab.tsxindex 8977d5d509..73b86fe465 100644--- a/src/components/bot-panel/DetailsTab.tsx+++ b/src/components/bot-panel/DetailsTab.tsx@@ -2,7 +2,7 @@ import { Calendar, CalendarPlus, ChevronRight, Sparkles } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { currentTaskBot, useStore, type Bot } from "@/state/store";+import { currentTaskBot, type Bot } from "@/state/store";import { useChatMoreItems } from "../ChatMoreMenu";import { EffortRow, ModelPicker } from "../ModelPicker";import type { SidebarMenuItem } from "../SidebarPopoverMenu";@@ -11,6 +11,7 @@ import { BotConversations } from "./Conversations";import type { SimplePageId } from "./page-registry";import { TryAsking } from "./TryAsking";import { Card, CardLabel, LabelAction, panelActionCls, NavRow, RowIcon, rowCls, RowText } from "./rows";+import { useStoreDispatch } from "@/state/store-select";type Derived = ReturnType<typeof useBotSettingsDerived>;@@ -46,7 +47,7 @@ export function DetailsTab({ bot, derived, onOpen }: {onOpen: (page: SimplePageId) => void;}) {const { items } = useChatMoreItems(bot);- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const thread = currentTaskBot(bot);const routinesOn = derived.botRoutines.filter((routine) => routine.enabled).length;const conversationItems = CONVERSATION_ITEMS.flatMap((key) => items.filter((item) => item.key === key));diff --git a/src/components/bot-panel/HeavyBotRow.tsx b/src/components/bot-panel/HeavyBotRow.tsxindex ffb08a1763..e4097f8dbd 100644--- a/src/components/bot-panel/HeavyBotRow.tsx+++ b/src/components/bot-panel/HeavyBotRow.tsx@@ -3,11 +3,12 @@ import { Gauge } from "lucide-react";import { t } from "@/lib/i18n";import { tidyMemoryNow } from "@/lib/memory";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import { buttonCls, Card, RowIcon, rowCls, RowText } from "./rows";+import { useStoreDispatch } from "@/state/store-select";export function HeavyBotRow({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [heavy, setHeavy] = useState(false);const [tidying, setTidying] = useState(false);const [checked, setChecked] = useState(0);diff --git a/src/components/bot-panel/LibraryTab.tsx b/src/components/bot-panel/LibraryTab.tsxindex e8153e586b..9b9ef15748 100644--- a/src/components/bot-panel/LibraryTab.tsx+++ b/src/components/bot-panel/LibraryTab.tsx@@ -5,7 +5,7 @@ import { t } from "@/lib/i18n";import { usePageOpener } from "@/lib/page-open";import { shortPath } from "@/lib/short-path";import { SIDEBAR_INLINE, useMediaQuery } from "@/lib/use-media-query";-import { useStore, visibleMessages, type Bot, type Message } from "@/state/store";+import { visibleMessages, type Bot, type Message } from "@/state/store";import { AttachedFileChip } from "../AttachmentPreview";import { recentChangedFiles, sharedFileReferences } from "../ComputerFilesPane";import { useDesktopCapabilities } from "../DesktopCapabilities";@@ -14,6 +14,7 @@ import type { SimplePageId } from "./page-registry";import { Card, CardLabel, NavRow } from "./rows";import { panelMemoryNotes } from "./memory-notes";import { useMemoryDoc } from "./use-memory-doc";+import { useStoreDispatch } from "@/state/store-select";export interface LibraryItems {pages: Array<{ messageId: string; title: string; url: string }>;@@ -50,7 +51,7 @@ export function libraryItems(bot: Bot, messages: readonly Message[] = visibleMesconst fileName = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);export function LibraryTab({ bot, onOpen }: { bot: Bot; onOpen: (page: SimplePageId) => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { capabilities } = useDesktopCapabilities();const openPage = usePageOpener();const phone = !useMediaQuery(SIDEBAR_INLINE, true);diff --git a/src/components/bot-panel/MemoryUpkeepCards.tsx b/src/components/bot-panel/MemoryUpkeepCards.tsxindex 3204562bbf..9eae0e70e4 100644--- a/src/components/bot-panel/MemoryUpkeepCards.tsx+++ b/src/components/bot-panel/MemoryUpkeepCards.tsx@@ -2,14 +2,15 @@ import { useCallback, useEffect, useState } from "react";import { t } from "@/lib/i18n";import { fetchMemoryJournal, fetchMemoryOverview, markMemoryReviewed, revertMemoryChange, type LendingReview, type MemoryJournalRow } from "@/lib/memory";-import { ApiError, useStore, type Bot } from "@/state/store";+import { ApiError, type Bot } from "@/state/store";import { LendingReviewNotice, MemoryJournalList } from "../bot-settings/MemorySection";import { Card, SwitchRow } from "./rows";+import { useStoreDispatch } from "@/state/store-select";const SHOWN = 5;export function MemoryUpkeepCards({ bot, onChanged }: { bot: Bot; onChanged: () => Promise<void> }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [rows, setRows] = useState<MemoryJournalRow[]>([]);const [review, setReview] = useState<{ value: LendingReview; stale: boolean } | null>(null);const [busy, setBusy] = useState<string | null>(null);diff --git a/src/components/bot-panel/SettingsPage.tsx b/src/components/bot-panel/SettingsPage.tsxindex 4d45dd6819..14ac4b2b7f 100644--- a/src/components/bot-panel/SettingsPage.tsx+++ b/src/components/bot-panel/SettingsPage.tsx@@ -10,7 +10,7 @@ import { callCapabilityHelp } from "@/lib/call-capability";import { listensHere, missingListenKey, speechBridge } from "@/lib/speech";import { requestNotificationPermission } from "@/lib/notify";import { firstSentence } from "@/lib/soul";-import { currentTaskBot, useStore, type Bot } from "@/state/store";+import { currentTaskBot, type Bot } from "@/state/store";import type { ApprovalMode } from "../../../shared/approval-mode";import { BOT_PROFILE_LIMITS } from "../../../shared/bot-profile";import { REPLY_STYLES, type ReplyStyle } from "../../../shared/reply-style";@@ -32,6 +32,7 @@ import { HeavyBotRow } from "./HeavyBotRow";import { SoulChanges } from "./SoulChanges";import type { SimplePageId } from "./page-registry";import { buttonCls, Card, ColRow, NavRow, RowIcon, rowCls, RowText, Segmented, SwitchRow, TrashButton, type SegmentOption } from "./rows";+import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Derived = ReturnType<typeof useBotSettingsDerived>;@@ -42,7 +43,7 @@ export function SettingsPage({ bot, derived, onOpen, editingInstructions = falseeditingInstructions?: boolean;onEditInstructions?: (open: boolean) => void;}) {- const { state, dispatch, flushBotPatches } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch(), { flushBotPatches } = useStoreActions();const { capabilities, ready } = useDesktopCapabilities();const apps = useBotApps(bot);const { servers: allServers } = useMcpServers();diff --git a/src/components/bot-panel/SoulChanges.tsx b/src/components/bot-panel/SoulChanges.tsxindex 8e7a021646..4a58e314a4 100644--- a/src/components/bot-panel/SoulChanges.tsx+++ b/src/components/bot-panel/SoulChanges.tsx@@ -2,13 +2,14 @@ import { useCallback, useEffect, useState } from "react";import { t } from "@/lib/i18n";import { fetchSoulChanges, undoSoulChange, type MemoryJournalRow } from "@/lib/memory";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { MemoryJournalList } from "../bot-settings/MemorySection";+import { useStoreActions, useStoreDispatch } from "@/state/store-select";const SHOWN = 5;export function SoulChanges({ bot }: { bot: Bot }) {- const { dispatch, flushBotPatches } = useStore();+ const dispatch = useStoreDispatch(), { flushBotPatches } = useStoreActions();const [rows, setRows] = useState<MemoryJournalRow[]>([]);const [reverting, setReverting] = useState<string | null>(null);const load = useCallback(() => fetchSoulChanges(bot.id).then((list) => setRows(list.rows.slice(0, SHOWN)), () => {}), [bot.id]);diff --git a/src/components/bot-panel/TryAsking.tsx b/src/components/bot-panel/TryAsking.tsxindex 4cae11b966..3cfe196bc8 100644--- a/src/components/bot-panel/TryAsking.tsx+++ b/src/components/bot-panel/TryAsking.tsx@@ -1,12 +1,13 @@import { t } from "@/lib/i18n";import { useAdvancedMode } from "@/lib/interface-mode";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { HELPER_ASK_KEYS } from "../HelperIntro";import { Card } from "./rows";+import { useStoreDispatch } from "@/state/store-select";/** MausBot's example asks, in its panel (Simple mode): a tap sends one in the open conversation. */export function TryAsking({ bot }: { bot: Bot }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const advanced = useAdvancedMode();if (advanced || !bot.defaultBot) return null;return (diff --git a/src/components/bot-panel/bot-actions.ts b/src/components/bot-panel/bot-actions.tsindex e9dd8e7285..3d628c2932 100644--- a/src/components/bot-panel/bot-actions.ts+++ b/src/components/bot-panel/bot-actions.ts@@ -4,13 +4,15 @@ import { t } from "@/lib/i18n";import { useCopyFeedback } from "@/lib/copy-text";import { botUnreadThreadIds, markBotRead } from "@/lib/folder-read";import { useShowThreads } from "@/lib/thread-preferences";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import { announceArchiveNotice, archiveBotWithNotice } from "../bot-archive";import { moveBotsToSection } from "../bot-sections";import { currentArchivableBot, type BotConfirmKind } from "../Sidebar";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useStoreRef } from "@/state/store-ref";export function useBotActions(bot: Bot) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ deletingBots: s.deletingBots }), sameFields), store = useStoreRef(), dispatch = useStoreDispatch();const showThreads = useShowThreads();const [confirm, setConfirm] = useState<BotConfirmKind | null>(null);const [reading, setReading] = useState(false);@@ -18,7 +20,7 @@ export function useBotActions(bot: Bot) {const readInFlight = useRef(false);const copy = useCopyFeedback(bot.threadId);- const visibleBotCount = state.bots.filter((candidate) => !candidate.hidden).length;+ const visibleBotCount = useStoreSelector((s) => s.bots.filter((candidate) => !candidate.hidden).length);const archiveHint = bot.chiefOfStaff? t("sidebar.bot.archiveBlockedChief"): visibleBotCount <= 1@@ -46,11 +48,12 @@ export function useBotActions(bot: Bot) {// The sidebar's own archive path: its corner notice says "Archived" with Undo, or why it failed.const archive = async () => {- const current = currentArchivableBot(state.bots, bot.id);+ const { bots, selectedId } = store.state();+ const current = currentArchivableBot(bots, bot.id);if (!current) return;await archiveBotWithNotice(current, {- bots: state.bots,- selectedId: state.selectedId,+ bots,+ selectedId,dispatch,showThreads,notify: (notice) => {@@ -61,7 +64,7 @@ export function useBotActions(bot: Bot) {};const requestArchive = () => {- if (currentArchivableBot(state.bots, bot.id)) setConfirm("archive");+ if (currentArchivableBot(store.state().bots, bot.id)) setConfirm("archive");};const confirmed = () => {diff --git a/src/components/bot-panel/browser-logins.tsx b/src/components/bot-panel/browser-logins.tsxindex 0e8c04e93c..ad3beca957 100644--- a/src/components/bot-panel/browser-logins.tsx+++ b/src/components/bot-panel/browser-logins.tsx@@ -2,24 +2,25 @@ import { Plus } from "lucide-react";import { t } from "@/lib/i18n";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { SignedInSites } from "../SignedInSites";import { Card, ColRow, LinkRow, NoteRow } from "./rows";+import { sameFields, sameItems, useStoreSelector } from "@/state/store-select";export function BrowserLogins({ bot, browserEnabled, onOpenBrowser }: {bot: Bot;browserEnabled: boolean;onOpenBrowser: () => void;}) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const ownerOrAdmin = useOwnerOrAdmin();const profileId = bot.browserProfile ?? "";const profile = (state.config?.browserProfiles ?? []).find((candidate) => candidate.id === profileId);const temporary = profileId === "guest";const ownChrome = profile?.browser === "chrome" && state.config?.browserEngine?.myChrome === true;- const sharedBy = profileId && !temporary- ? state.bots.filter((candidate) => candidate.browserProfile === profileId).map((candidate) => candidate.name)- : [bot.name];+ const sharedBy = useStoreSelector((s) => profileId && !temporary+ ? s.bots.filter((candidate) => candidate.browserProfile === profileId).map((candidate) => candidate.name)+ : [bot.name], sameItems);return (<Card anchor="logins">diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsxindex 732a232837..d22fe5e5c0 100644--- a/src/components/bot-panel/pages.tsx+++ b/src/components/bot-panel/pages.tsx@@ -14,7 +14,7 @@ import type { Routine } from "@/lib/routines";import type { SkillImportSummary } from "../../../shared/skill-import";import { shortPath } from "@/lib/short-path";import { skillImportLines } from "@/lib/skill-import";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { useDesktopCapabilities } from "../DesktopCapabilities";import { connectAppFromBot } from "../AppGrantPrompt";import { ServiceIcon } from "../ServiceIcon";@@ -38,6 +38,7 @@ import { BotSwitch, buttonCls, Card, ColRow, ItemRow, LinkRow, NoteRow, RadioRowimport { MemoryUpkeepCards } from "./MemoryUpkeepCards";import { useMemoryDoc } from "./use-memory-doc";import { useTeamMemoryEntries } from "../conversation-share/conversation-share";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";type Derived = ReturnType<typeof useBotSettingsDerived>;@@ -55,7 +56,7 @@ function errorText(error: unknown, fallback: string): string {}export function AppsPage({ bot, derived }: PageContext) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const apps = useBotApps(bot);const { servers: allServers, error: mcpError } = useMcpServers();const { patch, canUseConnectedApps } = derived;@@ -135,7 +136,7 @@ export function AppsPage({ bot, derived }: PageContext) {}export function RoutinesPage({ bot, derived }: PageContext) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, routineRuns: s.routineRuns, routinesLoadState: s.routinesLoadState }), sameFields), dispatch = useStoreDispatch();// Arriving with no routines means the person asked to add one, so the editor opens straight away.const [editing, setEditing] = useState<Routine | "new" | null>(() => derived.botRoutines.length === 0 ? "new" : null);return (@@ -413,7 +414,7 @@ function MemoryFullWindow({ label, onClose, children }: { label: string; onCloseexport function SkillsPage({ bot }: PageContext) {const { request: api } = useBotEditor();- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const skills = useManagedSkills(bot);const [source, setSource] = useState("");const [importing, setImporting] = useState(false);diff --git a/src/components/bot-settings/AccessSection.test.ts b/src/components/bot-settings/AccessSection.test.tsindex 0ee62aa626..6255c7d34a 100644--- a/src/components/bot-settings/AccessSection.test.ts+++ b/src/components/bot-settings/AccessSection.test.ts@@ -15,6 +15,7 @@ const fixture = vi.hoisted(() => ({capabilities: { host: { homeDir: undefined } as { homeDir: undefined; platform?: string }, localComputer: { available: false, reasonCode: "unsupported" } },apps: { phase: "loading", apps: [], connectedSlugs: [] } as import("./useBotApps").BotApps,}));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: { ...original.initialState, config: fixture.config ?? original.initialState.config, instances: fixture.instances as typeof original.initialState.instances }, dispatch: fixture.dispatch }) };diff --git a/src/components/bot-settings/AccessSection.tsx b/src/components/bot-settings/AccessSection.tsxindex aac6691df0..89faf95c4b 100644--- a/src/components/bot-settings/AccessSection.tsx+++ b/src/components/bot-settings/AccessSection.tsx@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";import { browserUnavailableReason } from "@/lib/feature-flags";import { ChevronDown, ChevronRight, FolderOpen, Plus } from "lucide-react";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import { useBotEditor } from "./BotEditorContext";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -39,6 +39,7 @@ import { KeysLink } from "../keys/KeysLink";import type { ConnectorScope, ConnectorScopes } from "../../../shared/connector-scopes";import type { ConnectorAccount } from "@/lib/connector-status";import type { useBotSettingsDerived } from "./useBotSettingsDerived";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";/*** Claude keeps sessions per project folder, so the server pins each task's folder on its first turn. PATCHed directly,@@ -132,7 +133,7 @@ export function WorkingFolder({ bot }: { bot: Bot }) {* bot.*/export function McpServersCard({ bot, patch }: { bot: Bot; patch: (patch: { mcpServers: string[] | null }) => void }) {- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const { servers: all, error, refresh } = useMcpServers();const servers = all ? mcpServersOfBot(all, bot.id) : null;const mounted = new Set((servers ? mcpServersForBot(servers, bot.mcpServers, bot.id) : []).map((server) => server.name));@@ -481,7 +482,7 @@ function ConnectorToolsGrants({/** Research through treg (the X tools and the general research tools): on for every bot whenever this server holds a* treg key or a Cloud plan's research credential, and switchable off per bot. */function ResearchCard({ bot, patch }: { bot: Bot; patch: (patch: { xResearch: boolean }) => void }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const connecting = xResearchAction(useCloudPlan()?.view ?? null) === "connecting" && state.config?.xResearch?.unavailable !== true;const ownKey = state.config?.treg?.configured === true, included = state.config?.xResearch?.included === true;const available = ownKey || included;@@ -563,7 +564,7 @@ export function cloudPreferenceShown(bot: Pick<Bot, "computer">, config: { cloud*/export function VpsAliasField({ bot }: { bot: Bot }) {const { request: api } = useBotEditor();- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const defaultAlias = state.config?.vps?.sshAlias ?? "";const [draft, setDraft] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);@@ -622,7 +623,7 @@ export function VpsAliasField({ bot }: { bot: Bot }) {}export function CloudPreference({ bot, patch }: { bot: Bot; patch: ReturnType<typeof useBotSettingsDerived>["patch"] }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const { draft } = useBotEditor();if (!cloudPreferenceShown(bot, state.config)) return null;return (@@ -659,7 +660,7 @@ export function CloudPreference({ bot, patch }: { bot: Bot; patch: ReturnType<ty}function DraftWorksOn({ bot, patch, seat }: { bot: Bot; patch: ReturnType<typeof useBotSettingsDerived>["patch"]; seat: PlaceSeat }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, instances: s.instances }), sameFields);const { capabilities } = useDesktopCapabilities();const providerSupportsLocal = instanceSupportsLocalComputer(state.instances, bot);const localReason = localComputerDisabledReason({ capabilities, providerSupportsLocal });@@ -701,7 +702,7 @@ export function AccessSection({parts?: readonly AccessPart[];}) {const { draft } = useBotEditor();- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, instances: s.instances, webhooks: s.webhooks }), sameFields), dispatch = useStoreDispatch();const {patch,canUseConnectedApps,diff --git a/src/components/bot-settings/BotApiCard.tsx b/src/components/bot-settings/BotApiCard.tsxindex 800b78486a..40d718e0e9 100644--- a/src/components/bot-settings/BotApiCard.tsx+++ b/src/components/bot-settings/BotApiCard.tsx@@ -5,10 +5,12 @@ import { cn } from "@/lib/cn";import { copyText } from "@/lib/copy-text";import { t } from "@/lib/i18n";import { relativeTime } from "@/lib/memory";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import { BOT_API_KEY_PLACEHOLDER, BOT_API_UPGRADE, botApiCurl } from "../../../shared/bot-api";import { NoteLine, useCloudUsage, useUpgrade } from "../CloudUsageMeter";import { Switch } from "../SettingsPrimitives";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useMinuteTick } from "@/lib/minute-tick";export interface BotApiCall {id: string;@@ -89,12 +91,13 @@ function BotApiStarter({ className }: { className?: string }) {/** The Bot API, the same in the bot panel and in Bot settings: a switch, the key once, the command to paste. */export function BotApiCard(props: { bot: Bot; webhooksLink?: boolean; className?: string }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);return state.config?.cloudStarter === true ? <BotApiStarter className={props.className} /> : <BotApiSection {...props} />;}function BotApiSection({ bot, webhooksLink = false, className }: { bot: Bot; webhooksLink?: boolean; className?: string }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ webhooks: s.webhooks }), sameFields), dispatch = useStoreDispatch();+ useMinuteTick();const [view, setView] = useState<BotApiView | null>(null);const [freshKey, setFreshKey] = useState<string | null>(null);const [confirmingNewKey, setConfirmingNewKey] = useState(false);diff --git a/src/components/bot-settings/IdentitySection.tsx b/src/components/bot-settings/IdentitySection.tsxindex afb1ed574e..719dac80b2 100644--- a/src/components/bot-settings/IdentitySection.tsx+++ b/src/components/bot-settings/IdentitySection.tsx@@ -2,7 +2,7 @@ import { useState } from "react";import { DefaultBotHideRow } from "../DefaultBotControls";import { BookOpen } from "lucide-react";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import type { MausMotion, MausState } from "@/lib/mascot";import { cn } from "@/lib/cn";import { BOT_PROFILE_LIMITS } from "../../../shared/bot-profile";@@ -15,6 +15,7 @@ import { PackageProvenance } from "./PackageProvenance";import { ProposalStatus } from "./ProposalStatus";import { randomBotName } from "@/lib/random-bot-name";import { intlLocale, t } from "@/lib/i18n";+import { useStoreRef } from "@/state/store-ref";export type IdentityPart = "avatar" | "provenance" | "name" | "title" | "blurb";@@ -35,7 +36,7 @@ export function IdentitySection({}) {const [instructionsOpen, setInstructionsOpen] = useState(false);const { draft } = useBotEditor();- const { state } = useStore();+ const store = useStoreRef();const shows = (part: IdentityPart) => !parts || parts.includes(part);return (@@ -51,7 +52,7 @@ export function IdentitySection({key={kind}type="button"className="rounded-md px-2 py-1 text-xs text-ink-secondary hover:bg-control hover:text-ink"- onClick={() => patch({ name: randomBotName(kind, bot.name, state.bots.map(existing => existing.name)) })}+ onClick={() => patch({ name: randomBotName(kind, bot.name, store.state().bots.map(existing => existing.name)) })}>{t(kind === "female" ? "newBot.randomFemaleName" : "newBot.randomMaleName")}</button>)}</div>}</div>diff --git a/src/components/bot-settings/MemorySection.tsx b/src/components/bot-settings/MemorySection.tsxindex 0c539be5f6..ffd6db46b4 100644--- a/src/components/bot-settings/MemorySection.tsx+++ b/src/components/bot-settings/MemorySection.tsx@@ -34,10 +34,12 @@ import { localizedRelativeTime } from "@/lib/relative-time";import { shortPath } from "@/lib/short-path";import { activeLocale, t } from "@/lib/i18n";import { roomMemoryCaptureEnabled } from "@/lib/feature-flags";-import { api, ApiError, useStore, type Bot, type ConfigStatus } from "@/state/store";+import { api, ApiError, type Bot, type ConfigStatus } from "@/state/store";import { Switch } from "../SettingsPrimitives";import { useDesktopCapabilities } from "../DesktopCapabilities";import { inputCls } from "./field";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useMinuteTick } from "@/lib/minute-tick";const buttonCls = "rounded-lg bg-control px-3 py-1.5 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50";const quietButtonCls = "rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50";@@ -123,7 +125,7 @@ export function MemorySection({ bot, active = true, onToggle }: { bot: Bot; acticonst [lendingReview, setLendingReview] = useState<LendingReview | null>(null);const [lendingReviewStale, setLendingReviewStale] = useState(false);const [reviewing, setReviewing] = useState(false);- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const learnFromRooms = roomMemoryCaptureEnabled(state.config);const [roomsSaving, setRoomsSaving] = useState(false);const [roomsError, setRoomsError] = useState("");@@ -673,6 +675,7 @@ export function MemoryJournalList({onRevert: (row: MemoryJournalRow) => void;now?: number;}) {+ useMinuteTick();if (!rows) return <div className="text-[13px] text-ink-secondary">{t("memory.loading")}</div>;if (rows.length === 0) return <div className="text-[13px] text-ink-secondary">{t("memory.noChanges")}</div>;return (diff --git a/src/components/bot-settings/ModelSection.test.ts b/src/components/bot-settings/ModelSection.test.tsindex a19fb885ff..b4d3bd427a 100644--- a/src/components/bot-settings/ModelSection.test.ts+++ b/src/components/bot-settings/ModelSection.test.ts@@ -6,6 +6,7 @@ import type { Bot, InstanceInfo } from "@/state/store";const instances = vi.hoisted(() => [] as InstanceInfo[]);const recovery = vi.hoisted(() => ({ enabled: true }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: { ...original.initialState, instances, config: { automaticRecovery: recovery } }, dispatch: vi.fn() }) };diff --git a/src/components/bot-settings/ModelSection.tsx b/src/components/bot-settings/ModelSection.tsxindex 8b17c45b1d..446f8ae107 100644--- a/src/components/bot-settings/ModelSection.tsx+++ b/src/components/bot-settings/ModelSection.tsx@@ -1,16 +1,17 @@import { EffortRow, ModelPicker } from "../ModelPicker";import { X } from "lucide-react";import { cn } from "@/lib/cn";-import { useStore, type Bot, type InstanceInfo } from "@/state/store";+import { type Bot, type InstanceInfo } from "@/state/store";import { useBotEditor } from "./BotEditorContext";import { ProposalStatus } from "./ProposalStatus";import { ThreadModelsLine } from "../ThreadModelsLine";import { t } from "@/lib/i18n";import { Select } from "../Select";import { backupNote } from "@/lib/engine-rail";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function ModelSection({ bot }: { bot: Bot }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, instances: s.instances }), sameFields), dispatch = useStoreDispatch();const { draft } = useBotEditor();const modelVariants = state.instances.find((instance) => instance.instanceId === bot.modelSelection.instanceId)?.capabilities?.modelVariants;return (@@ -73,7 +74,7 @@ function KeepWarmRow({ bot, workspaceOn, onChange }: { bot: Bot; workspaceOn: bo}export function FallbackChain({ bot, onChange }: { bot: Bot; onChange: (fallback: Bot["fallback"]) => void }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields);const chain = bot.fallback ?? [];// Backups may share an account with the main AI or each other, never a model.const taken = (instanceId: string, model: string, except?: number) =>diff --git a/src/components/bot-settings/PermissionsSection.tsx b/src/components/bot-settings/PermissionsSection.tsxindex 9a11efd98f..f9360910fa 100644--- a/src/components/bot-settings/PermissionsSection.tsx+++ b/src/components/bot-settings/PermissionsSection.tsx@@ -6,7 +6,7 @@ import { Crown } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { threadApprovalModes, useStore, type Bot } from "@/state/store";+import { threadApprovalModes, type Bot } from "@/state/store";import type { ApprovalMode } from "../../../shared/approval-mode";import { effectiveOutboundPolicy, type OutboundPolicy } from "../../../shared/outbound";import { ApprovalModeSelector } from "../ApprovalModeSelector";@@ -17,6 +17,7 @@ import { ManagedTeamsSettings } from "./ManagedTeamsSettings";import { ProposalStatus } from "./ProposalStatus";import type { useBotSettingsDerived } from "./useBotSettingsDerived";import { useBotEditor } from "./BotEditorContext";+import { sameItems, useStoreDispatch, useStoreSelector } from "@/state/store-select";export type PermissionsPart = "chief" | "approval" | "outbound";@@ -31,7 +32,7 @@ export function PermissionsSection({}) {const { patch, engine, canCoordinate, approvalMode, trustedModesAvailable, sectionName, currentChief } = derived;const team = useTeamPeople();- const { state, dispatch } = useStore();+ const teams = useStoreSelector((s) => ["", ...(s.sections ?? []), ...[...s.bots, ...s.groups].map(member => member.section?.trim() || "")], sameItems), dispatch = useStoreDispatch();const ownerOrAdmin = useOwnerOrAdmin();const { draft } = useBotEditor();const displaySectionName = sectionName === "General" ? t("botAccess.teams.general") : sectionName;@@ -102,7 +103,7 @@ export function PermissionsSection({{bot.chiefOfStaff && <ManagedTeamsSettingskey={bot.id + JSON.stringify(bot.managedSections ?? [])}name={bot.name} ownTeam={bot.section?.trim() || ""}- teams={["", ...(state.sections ?? []), ...[...state.bots, ...state.groups].map(member => member.section?.trim() || "")]}+ teams={teams}allowed={bot.managedSections ?? []}onSave={managedSections => patch({ managedSections, acknowledgePeerScope: true })}/>}diff --git a/src/components/bot-settings/ProposalStatus.test.ts b/src/components/bot-settings/ProposalStatus.test.tsindex ca595ec2c0..6915e0da22 100644--- a/src/components/bot-settings/ProposalStatus.test.ts+++ b/src/components/bot-settings/ProposalStatus.test.ts@@ -6,6 +6,7 @@ import { StoreProvider, api, type Bot } from "@/state/store";import { BotEditorContext } from "./BotEditorContext";const fixture = vi.hoisted(() => ({ bots: [] as Bot[] }));+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: { ...original.initialState, bots: fixture.bots }, dispatch: vi.fn() }) };diff --git a/src/components/bot-settings/ProposalStatus.tsx b/src/components/bot-settings/ProposalStatus.tsxindex 5652c23821..9d057ef621 100644--- a/src/components/bot-settings/ProposalStatus.tsx+++ b/src/components/bot-settings/ProposalStatus.tsx@@ -1,6 +1,7 @@import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { useBotEditor } from "./BotEditorContext";+import { useStoreSelector } from "@/state/store-select";const sectionKey = (section?: string | null) => (section ?? "").trim();@@ -17,8 +18,8 @@ function chiefCovers(bot: Bot, bots: ReadonlyArray<Bot>): boolean {export function ProposalStatus({ bot, kind }: { bot: Bot; kind: "chief" | "owner" }) {const { draft } = useBotEditor();- const { state } = useStore();- if (draft || !chiefCovers(bot, state.bots)) return null;+ const covered = useStoreSelector((s) => chiefCovers(bot, s.bots));+ if (draft || !covered) return null;return (<div className="mt-1 text-[12px] leading-snug text-ink-secondary">{t(kind === "chief" ? "botSettings.proposal.chief" : "botSettings.proposal.owner")}diff --git a/src/components/bot-settings/RoutinesSection.tsx b/src/components/bot-settings/RoutinesSection.tsxindex 5075651abc..d723a36400 100644--- a/src/components/bot-settings/RoutinesSection.tsx+++ b/src/components/bot-settings/RoutinesSection.tsx@@ -1,13 +1,14 @@import { CalendarClock, ChevronRight, FileText, Plus } from "lucide-react";import { useState } from "react";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import type { Routine, RoutineRun, RoutineRunOn } from "@/lib/routines";import { t } from "@/lib/i18n";import { RoutineEditor } from "../RoutinesPage";import { RoutineList } from "../routines/RoutineList";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function RoutinesSection({ bot, routines, runs, defaultRunOn }: { bot: Bot; routines: Routine[]; runs: RoutineRun[]; defaultRunOn?: RoutineRunOn }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, routinesLoadState: s.routinesLoadState }), sameFields), dispatch = useStoreDispatch();const [editing, setEditing] = useState<Routine | "new" | null>(null);return <div className="flex flex-col gap-4"><div className="rounded-xl bg-card p-4">diff --git a/src/components/bot-settings/SkillsSection.tsx b/src/components/bot-settings/SkillsSection.tsxindex b53a106f6e..8589ff06f6 100644--- a/src/components/bot-settings/SkillsSection.tsx+++ b/src/components/bot-settings/SkillsSection.tsx@@ -4,7 +4,7 @@ import { skillImportLines } from "@/lib/skill-import";import type { SkillImportSummary } from "../../../shared/skill-import";import { useEffect, useRef, useState } from "react";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { useBotEditor } from "./BotEditorContext";import { skillAuthoringEnabled, skillsLibraryEnabled } from "@/lib/feature-flags";import { Switch } from "../SettingsPrimitives";@@ -12,6 +12,7 @@ import { inputCls } from "./field";import { OrgSkillsCard } from "./OrgSkillsCard";import { WriteCommandCard } from "./WriteCommandCard";import { Select } from "../Select";+import { sameFields, useStoreSelector } from "@/state/store-select";export interface ManagedSkill {name: string;@@ -287,7 +288,7 @@ export function SkillReviewDialog({export function SkillsSection({ bot }: { bot: Bot }) {const { request: api } = useBotEditor();- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const featureEnabled = skillAuthoringEnabled(state.config);const libraryOn = skillsLibraryEnabled(state.config);const {diff --git a/src/components/bot-settings/ToolGroupsCard.tsx b/src/components/bot-settings/ToolGroupsCard.tsxindex 1b37caaccc..cc488a696e 100644--- a/src/components/bot-settings/ToolGroupsCard.tsx+++ b/src/components/bot-settings/ToolGroupsCard.tsx@@ -1,8 +1,9 @@import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { TOOL_GROUP_TOKENS, TOOL_GROUPS, type ToolGroup } from "../../../shared/tool-groups";import { Switch } from "../SettingsPrimitives";+import { sameFields, useStoreSelector } from "@/state/store-select";const GROUP_WORDS: Record<ToolGroup, [LocaleKey, LocaleKey]> = {meetings: ["botAccess.toolGroups.meetings", "botAccess.toolGroups.meetingsHint"],@@ -18,7 +19,7 @@ export function shownToolGroups(available: readonly ToolGroup[] | undefined, off}export function ToolGroupsCard({ bot, patch }: { bot: Bot; patch: (patch: { toolsOff: ToolGroup[] }) => void }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const off = bot.toolsOff ?? [];const groups = shownToolGroups(state.config?.toolGroups, off);if (groups.length === 0) return null;diff --git a/src/components/bot-settings/UsageSection.tsx b/src/components/bot-settings/UsageSection.tsxindex 1ebd1ffbd8..33423d3dd2 100644--- a/src/components/bot-settings/UsageSection.tsx+++ b/src/components/bot-settings/UsageSection.tsx@@ -1,11 +1,12 @@import { ChevronRight } from "lucide-react";import { cn } from "@/lib/cn";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { t } from "@/lib/i18n";import { botUsage, costCaption, formatTokens, formatUsd, hasFiniteCost, headlineTokens, tokensColumnLabel, usageDetail } from "@/lib/usage";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";export function UsageSection({ bot, bare = false }: { bot: Bot; bare?: boolean }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ instances: s.instances }), sameFields), dispatch = useStoreDispatch();const usage = botUsage(bot);const instance = state.instances.find((i) => i.instanceId === bot.modelSelection.instanceId);diff --git a/src/components/bot-settings/VisibilitySection.tsx b/src/components/bot-settings/VisibilitySection.tsxindex 095e192a5a..4f331f07ea 100644--- a/src/components/bot-settings/VisibilitySection.tsx+++ b/src/components/bot-settings/VisibilitySection.tsx@@ -1,12 +1,14 @@import { useEffect, useState } from "react";import { Check, Loader2 } from "lucide-react";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";+import { sameJson } from "@/state/same-json";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import type { BotVisibility } from "../../../shared/wire";import { useTeamName } from "../bot-access/ShareBotButton";+import { sameFields, useStoreSelector } from "@/state/store-select";export type VisibilityMode = "everyone" | "admins" | "people";@@ -50,7 +52,7 @@ const OPTIONS: Array<{ mode: VisibilityMode; key: "botSettings.visibility.everyo];export function useChoosesVisibility(): boolean {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const ownerOrAdmin = useOwnerOrAdmin();const teamName = useTeamName();return !window.ogb && ownerOrAdmin === true && Boolean(state.config) && !teamName;@@ -62,8 +64,7 @@ export function visibilityLabel(visibility: BotVisibility | undefined): string {}export function VisibilitySection({ bot }: { bot: Bot }) {- const { state } = useStore();- const mixed = mixedRooms(bot, state.groups, state.bots);+ const mixed = useStoreSelector((s) => mixedRooms(bot, s.groups, s.bots), sameJson);const saved = formFromVisibility(bot.visibility);const [mode, setMode] = useState<VisibilityMode>(saved.mode);const [people, setPeople] = useState(saved.people);diff --git a/src/components/bot-settings/VoiceSection.tsx b/src/components/bot-settings/VoiceSection.tsxindex a95693f334..fb49bfbba5 100644--- a/src/components/bot-settings/VoiceSection.tsx+++ b/src/components/bot-settings/VoiceSection.tsx@@ -1,11 +1,12 @@import { requestNotificationPermission } from "@/lib/notify";import { t } from "@/lib/i18n";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { BotLiveVoiceSelect } from "../BotLiveVoiceSelect";import { Switch } from "../SettingsPrimitives";import { VoiceSettings } from "../VoiceSettings";import type { useBotSettingsDerived } from "./useBotSettingsDerived";import { useBotEditor } from "./BotEditorContext";+import { sameFields, useStoreSelector } from "@/state/store-select";export function VoiceSection({bot,@@ -16,7 +17,7 @@ export function VoiceSection({}) {const { patch } = derived;const { draft } = useBotEditor();- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const live = state.config?.live;// Fish Audio and ElevenLabs calls speak in their agent's own voice, so only the other providers have a voice to pick.// A bot being created has no call voice yet: new-bot defaults don't keep one.diff --git a/src/components/bot-settings/useBotOverview.tsx b/src/components/bot-settings/useBotOverview.tsxindex 55f2a66590..2a6dfb3da9 100644--- a/src/components/bot-settings/useBotOverview.tsx+++ b/src/components/bot-settings/useBotOverview.tsx@@ -1,11 +1,12 @@import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";-import { api, useStore, type Bot } from "@/state/store";+import { api, type Bot } from "@/state/store";import type { BotOverview } from "@/lib/bot-overview-types";import { ConfirmDialog } from "../ConfirmDialog";import type { HistoryRow } from "./HistorySection";import type { PromptPreviewData } from "./PromptPreview";import { t } from "@/lib/i18n";+import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select";/*** Reads the bot's overview and prompt preview while `want` asks for them. By default every change to the bot's facts@@ -14,7 +15,7 @@ import { t } from "@/lib/i18n";* there would save, record a history row and read once per keystroke.*/export function useBotOverview(bot: Bot, want: { overview: boolean; prompt: boolean; followEdits?: boolean }) {- const { state, flushBotPatches } = useStore();+ const state = useStoreSelector((s) => ({ routines: s.routines, webhooks: s.webhooks }), sameFields), { flushBotPatches } = useStoreActions();const [overview, setOverview] = useState<BotOverview | null>(null);const [overviewError, setOverviewError] = useState(false);const [prompt, setPrompt] = useState<PromptPreviewData | null>(null);@@ -104,7 +105,7 @@ export function useBotOverview(bot: Bot, want: { overview: boolean; prompt: bool}export function useBotHistory(bot: Bot, active: boolean) {- const { dispatch, flushBotPatches } = useStore();+ const dispatch = useStoreDispatch(), { flushBotPatches } = useStoreActions();const [rows, setRows] = useState<HistoryRow[] | null>(null);const [error, setError] = useState(false);const [revision, setRevision] = useState<string | null>(null);diff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex 53160c720e..492956fffb 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -1,9 +1,11 @@import { useDesktopCapabilities } from "../DesktopCapabilities";import { browserAvailable, builtInBrowserEnabled } from "@/lib/feature-flags";import { stateForBot } from "@/lib/mascot";-import { useStore, type Bot } from "@/state/store";+import { type Bot } from "@/state/store";import { approvalModeFor } from "../../../shared/approval-mode";import { connectorGrantsState, type ConnectorGrantsState } from "@/lib/connector-grants";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useBotApartFromTurns } from "@/state/apart-from-turns";export type BotPatch = Partial<Pick<@@ -56,11 +58,15 @@ export type BotPatch = Partial<};export function useBotSettingsDerived(bot: Bot) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config, instances: s.instances, routines: s.routines }), sameFields), dispatch = useStoreDispatch();+ const currentChief = useBotApartFromTurns((bots) => bots.find(+ (candidate) =>+ candidate.chiefOfStaff &&+ (candidate.section?.trim() || "") === (bot.section?.trim() || ""),+ ));const { capabilities } = useDesktopCapabilities();const patch = (p: BotPatch) => dispatch({ type: "updateBot", botId: bot.id, patch: p });const activeState = stateForBot(bot);- const mascotMotion = state.mascotMotion?.botId === bot.id ? state.mascotMotion : null;const engine = state.instances.find((instance) => instance.instanceId === bot.modelSelection.instanceId);const approvalMode = approvalModeFor(bot);const trustedModesAvailable = Boolean(window.ogb?.approvals && capabilities.host.packaged);@@ -77,11 +83,6 @@ export function useBotSettingsDerived(bot: Bot) {const browserAllowed = bot.browser !== false;const browserEnabled = browserFeature && browserAllowed;const sectionName = bot.section?.trim() || "General";- const currentChief = state.bots.find(- (candidate) =>- candidate.chiefOfStaff &&- (candidate.section?.trim() || "") === (bot.section?.trim() || ""),- );const botRoutines = state.routines.filter((routine) => routine.botId === bot.id);const activeBotRoutines = botRoutines.filter((routine) => routine.enabled).length;@@ -106,6 +107,5 @@ export function useBotSettingsDerived(bot: Bot) {botRoutines,activeBotRoutines,activeState,- mascotMotion,};}diff --git a/src/components/inbox/FinishedThreads.tsx b/src/components/inbox/FinishedThreads.tsxindex 7b26d4b2ed..8a496cb86e 100644--- a/src/components/inbox/FinishedThreads.tsx+++ b/src/components/inbox/FinishedThreads.tsx@@ -54,21 +54,15 @@ export function finishedThreads(bots: readonly Bot[], groups: readonly Group[] =return found.sort((a, b) => b.at - a.at).slice(0, limit).map(({ at: _at, ...row }) => row);}-export function FinishedThreads({ bots, groups, queued, readThreads, exclude, now, current, onOpen }: {- bots: readonly Bot[];- groups: readonly Group[];- queued: Record<string, unknown[]>;- /** Conversations the person has already read in the Inbox, even if the chat itself was never opened. */- readThreads?: ReadonlySet<string>;- /** Conversations the pinned section at the top already shows: this list leaves them out. */- exclude?: ReadonlySet<string>;+export function FinishedThreads({ rows, now, current, onOpen }: {+ /** From finishedThreads: the read conversations, without the ones the pinned section at the top already shows. */+ rows: readonly FinishedThread[];/** The clock the row's last-activity label is relative to. */now: number;/** The conversation the chat window has open, marked like a selected sidebar row. */current?: OpenThread;onOpen(row: FinishedThread): void;}) {- const rows = finishedThreads(bots, groups, queued, FINISHED_LIMIT, readThreads, exclude);if (!rows.length) return null;return (<section data-inbox-finished aria-label={t("inbox.settled.title")} className="border-t border-hairline/40 px-1.5 py-1.5">diff --git a/src/components/inbox/InboxActive.tsx b/src/components/inbox/InboxActive.tsxindex f3e0ad43e6..4b7ddf7313 100644--- a/src/components/inbox/InboxActive.tsx+++ b/src/components/inbox/InboxActive.tsx@@ -3,7 +3,9 @@import { Pin, PinOff } from "lucide-react";import type { InboxView } from "../../../shared/inbox";import { t } from "@/lib/i18n";-import { useStore, type AppState } from "@/state/store";+import { type AppState } from "@/state/store";+import { sameJson } from "@/state/same-json";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useTeamPeople } from "@/state/team-people";import { AttentionThreadRows, attentionJumpAction, crossBotAttentionThreads, type AttentionThread, type OpenThread } from "../SidebarBotActivity";import { NeedsYouLine } from "../TeamOwner";@@ -62,10 +64,10 @@ export function InboxActive({ view, current, exclude }: {/** Conversations the pinned section at the top already shows: these lists leave them out so none appears twice. */exclude?: ReadonlySet<string>;}) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch();const team = useTeamPeople();const pinned = useAttentionPinned();- const entries = inboxAttentionEntries(state, view).filter((entry) => !exclude?.has(entry.task.threadId));+ const entries = useStoreSelector((state) => inboxAttentionEntries(state, view).filter((entry) => !exclude?.has(entry.task.threadId)), sameJson);const fixes = inboxFixes(team?.needsYou, view);return (<>diff --git a/src/components/inbox/InboxCard.tsx b/src/components/inbox/InboxCard.tsxindex 64c6a7f908..2e32ff6d7c 100644--- a/src/components/inbox/InboxCard.tsx+++ b/src/components/inbox/InboxCard.tsx@@ -15,7 +15,7 @@ import { InboxRowItem } from "./InboxRow";import { asMessage } from "./inbox-answer";import { askOf, CARD_ROWS, choiceResponse, choicesOf, rowsIn, tabCounts } from "./inbox-view";import { accessRequestWords } from "../bot-access/access-card";-import { useInboxActions } from "./use-inbox-actions";+import { useInboxActions, useInboxAsker } from "./use-inbox-actions";/** Most choices a question shows as buttons on the card; one with more opens in the inbox. */const CARD_CHOICES = 3;@@ -28,7 +28,7 @@ export function InboxCardSlot({ threadId, messageId }: { threadId: string; messa}function Answers({ row, view }: { row: InboxRow; view: InboxView }) {- const { answer, askerOf } = useInboxActions(view);+ const { answer } = useInboxActions(view), asker = useInboxAsker(row);const [sending, setSending] = useState<string | null>(null);const [failed, setFailed] = useState(false);const ask = askOf(row);@@ -38,7 +38,7 @@ function Answers({ row, view }: { row: InboxRow; view: InboxView }) {const pending = view.threadId ? pendingApprovals([asMessage(row)])[0] : undefined;return pending ? (<div className="flex flex-wrap items-center justify-end gap-2">- <PendingApprovalActions part="primary" tag="inbox" pending={pending} threadId={view.threadId!} bot={askerOf(row)} onCancelTurn={() => {}} />+ <PendingApprovalActions part="primary" tag="inbox" pending={pending} threadId={view.threadId!} bot={asker} onCancelTurn={() => {}} /></div>) : null;}diff --git a/src/components/inbox/InboxPanel.tsx b/src/components/inbox/InboxPanel.tsxindex c323078c40..1b24a19942 100644--- a/src/components/inbox/InboxPanel.tsx+++ b/src/components/inbox/InboxPanel.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState, type KeyboardEvent } from "react";+import { memo, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";import { createPortal } from "react-dom";import { Check, Inbox, Maximize2, Minimize2, Search, X } from "lucide-react";import type { InboxRow } from "../../../shared/inbox";@@ -7,12 +7,14 @@ import { useAdvancedMode } from "@/lib/interface-mode";import { t } from "@/lib/i18n";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";import { closeInbox, markAllInboxRead, readInboxLine, readInboxRow, useInboxMarkingAll, useInboxPanel, useInboxView, widenInbox } from "@/state/inbox";-import { useStore } from "@/state/store";+import { sameJson } from "@/state/same-json";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { useActiveLocale } from "@/lib/use-active-locale";import { InboxActive, inboxAttentionEntries, inboxOpenThread, readNewsThreads, unreadConversations } from "./InboxActive";import { attentionJumpAction, attentionUnpinAction } from "../SidebarBotActivity";import { InboxReading } from "./InboxReading";import { InboxRowItem } from "./InboxRow";-import { FinishedThreads } from "./FinishedThreads";+import { FinishedThreads, finishedThreads } from "./FinishedThreads";import { PinnedThreads, pinnedThreadRows } from "./PinnedThreads";import { matchesSearch, nextAfter } from "./inbox-answer";import { listedRows, rowsIn, waitingCount } from "./inbox-view";@@ -20,9 +22,10 @@ import { useInboxActions } from "./use-inbox-actions";import { roundButtonCls } from "../bot-panel/rows";-export function InboxPanel() {+export const InboxPanel = memo(function InboxPanel() {const view = useInboxView();- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch();+ useActiveLocale();const panel = useInboxPanel();const markingAll = useInboxMarkingAll();const phone = useMediaQuery(PHONE_LAYOUT);@@ -74,9 +77,12 @@ export function InboxPanel() {const row = rows[at + by];if (row) open(row);};- const pinnedThreads = new Set(pinnedThreadRows(state.bots, state.groups, state.pendingQueued).map((row) => row.task.threadId));- const count = waitingCount(view) + unreadConversations(inboxAttentionEntries(state, view), view);- const openThread = inboxOpenThread(state);+ const pinnedRows = useStoreSelector((state) => pinnedThreadRows(state.bots, state.groups, state.pendingQueued), sameJson);+ const pinnedThreads = useMemo(() => new Set(pinnedRows.map((row) => row.task.threadId)), [pinnedRows]);+ const finishedRows = useStoreSelector((state) => finishedThreads(state.bots, state.groups, state.pendingQueued, undefined, readNewsThreads(view), pinnedThreads), sameJson);+ const unread = useStoreSelector((state) => unreadConversations(inboxAttentionEntries(state, view), view));+ const count = waitingCount(view) + unread;+ const openThread = useStoreSelector((state) => inboxOpenThread(state), sameJson);const body = (<><div className="flex h-[50px] shrink-0 items-start gap-2.5 px-[13px] pt-[13px]">@@ -108,7 +114,7 @@ export function InboxPanel() {<><div className="min-h-0 flex-1 overflow-y-auto">{/* The conversations each bot and room pinned, at the top of the list. */}- {!query.trim() && <PinnedThreads bots={state.bots} groups={state.groups} queued={state.pendingQueued} now={now} current={openThread} onOpen={(row) => dispatch(attentionJumpAction(row))} onUnpin={(row) => dispatch(attentionUnpinAction(row))} />}+ {!query.trim() && <PinnedThreads rows={pinnedRows} now={now} current={openThread} onOpen={(row) => dispatch(attentionJumpAction(row))} onUnpin={(row) => dispatch(attentionUnpinAction(row))} />}{listed.length > 0 && <label className="mx-[13px] my-2.5 flex h-8 items-center gap-2 rounded-lg bg-ink/[0.045] px-2.5 ring-[0.5px] ring-ink/[0.12] focus-within:ring-ink/30"><Search size={14} aria-hidden="true" className="shrink-0 text-ink-tertiary" /><input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("inbox.search")} aria-label={t("inbox.search")}@@ -129,7 +135,7 @@ export function InboxPanel() {</div>{!query.trim() && <InboxActive view={view} current={openThread} exclude={pinnedThreads} />}{/* The finished, already-read conversations. */}- {!query.trim() && <FinishedThreads bots={state.bots} groups={state.groups} queued={state.pendingQueued} readThreads={readNewsThreads(view)} exclude={pinnedThreads} now={now} current={openThread} onOpen={(row) => dispatch(attentionJumpAction(row))} />}+ {!query.trim() && <FinishedThreads rows={finishedRows} now={now} current={openThread} onOpen={(row) => dispatch(attentionJumpAction(row))} />}{done.length > 0 && (<section data-inbox-done className="px-1.5 pb-1.5"><button type="button" data-inbox-done-toggle aria-expanded={showDone} onClick={() => setShowDone(!showDone)}@@ -166,4 +172,4 @@ export function InboxPanel() {{body}</aside>);-}+});diff --git a/src/components/inbox/InboxReading.tsx b/src/components/inbox/InboxReading.tsxindex 95c5a96429..6c8613eb2a 100644--- a/src/components/inbox/InboxReading.tsx+++ b/src/components/inbox/InboxReading.tsx@@ -11,7 +11,7 @@ import { InboxAnswer } from "./InboxAnswer";import { answerKindOf, headlineOf, singleQuestion } from "./inbox-answer";import { askOf, closeResponse, senderLabel, textOf } from "./inbox-view";import { useAskContext } from "./use-ask-context";-import { useInboxActions } from "./use-inbox-actions";+import { useInboxActions, useInboxAsker } from "./use-inbox-actions";const NAV_BUTTON = "flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink disabled:pointer-events-none disabled:opacity-35 pointer-coarse:size-9";@@ -43,8 +43,8 @@ export function InboxReading({ view, row, now, position, onStep }: {position: { index: number; count: number } | null;onStep(by: -1 | 1): void;}) {- const { answer, openInChat, run, askerOf } = useInboxActions(view);- const asker = askerOf(row);+ const { answer, openInChat, run } = useInboxActions(view);+ const asker = useInboxAsker(row);const context = useAskContext(row);const kind = answerKindOf(row);const headline = headlineOf(row);diff --git a/src/components/inbox/PinnedThreads.tsx b/src/components/inbox/PinnedThreads.tsxindex f1a8289b21..a9e6a4db99 100644--- a/src/components/inbox/PinnedThreads.tsx+++ b/src/components/inbox/PinnedThreads.tsx@@ -18,10 +18,8 @@ export function pinnedThreadRows(bots: readonly Bot[], groups: readonly Group[],.sort((a, b) => threadRecency(b.task) - threadRecency(a.task));}-export function PinnedThreads({ bots, groups, queued, now, current, onOpen, onUnpin }: {- bots: readonly Bot[];- groups: readonly Group[];- queued: Record<string, unknown[]>;+export function PinnedThreads({ rows, now, current, onOpen, onUnpin }: {+ rows: readonly AttentionThread[];/** The clock each row's last-activity label is relative to. */now: number;/** The conversation the chat window has open, marked like a selected sidebar row. */@@ -29,7 +27,6 @@ export function PinnedThreads({ bots, groups, queued, now, current, onOpen, onUnonOpen(row: AttentionThread): void;onUnpin(row: AttentionThread): void;}) {- const rows = pinnedThreadRows(bots, groups, queued);if (!rows.length) return null;return (<section data-inbox-pinned aria-label={t("sidebar.pinnedThreads.title")} className="border-b border-hairline/40 px-1.5 py-1.5">diff --git a/src/components/inbox/finished.dom.test.ts b/src/components/inbox/finished.dom.test.tsindex 441456bc4e..5cd8eb015f 100644--- a/src/components/inbox/finished.dom.test.ts+++ b/src/components/inbox/finished.dom.test.ts@@ -5,7 +5,7 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Bot, Group, Task } from "@/state/store";import { t } from "@/lib/i18n";-import { FinishedThreads } from "./FinishedThreads";+import { FinishedThreads, finishedThreads } from "./FinishedThreads";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -15,7 +15,7 @@ const bot = (id: string, tasks: Task[]): Bot => ({ id, name: id, tasks } as unknlet root: Root;const mount = (bots: Bot[], groups: Group[] = [], current?: { kind: "bot"; botId: string; threadId: string }) => act(async () => {- root.render(createElement(FinishedThreads, { bots, groups, queued: {}, now: NOW, current, onOpen: vi.fn() }));+ root.render(createElement(FinishedThreads, { rows: finishedThreads(bots, groups, {}), now: NOW, current, onOpen: vi.fn() }));});beforeEach(() => {diff --git a/src/components/inbox/pinned.dom.test.ts b/src/components/inbox/pinned.dom.test.tsindex 35a4ea48eb..e11acf24a2 100644--- a/src/components/inbox/pinned.dom.test.ts+++ b/src/components/inbox/pinned.dom.test.ts@@ -20,7 +20,7 @@ let root: Root;const onOpen = vi.fn();const onUnpin = vi.fn();const mount = (bots: Bot[], groups: Group[] = [], current?: { kind: "bot"; botId: string; threadId: string }) => act(async () => {- root.render(createElement(PinnedThreads, { bots, groups, queued: {}, now: NOW, current, onOpen, onUnpin }));+ root.render(createElement(PinnedThreads, { rows: pinnedThreadRows(bots, groups, {}), now: NOW, current, onOpen, onUnpin }));});const rowTitles = () => [...document.querySelectorAll<HTMLElement>("[data-pinned-row]")].map((row) => row.querySelector("[data-pinned-title]")?.textContent);diff --git a/src/components/inbox/use-inbox-actions.ts b/src/components/inbox/use-inbox-actions.tsindex 31b927b400..172c9d3792 100644--- a/src/components/inbox/use-inbox-actions.ts+++ b/src/components/inbox/use-inbox-actions.ts@@ -2,7 +2,9 @@ import { useCallback } from "react";import type { InboxRow, InboxView } from "../../../shared/inbox";import { useShowThreads } from "@/lib/thread-preferences";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";-import { openThread, useStore } from "@/state/store";+import { openThread } from "@/state/store";+import { useStoreRef } from "@/state/store-ref";+import { useStoreSelector } from "@/state/store-select";import { closeInbox, doneInboxRow, openInbox, readInboxRow, refreshInbox } from "@/state/inbox";import type { CardResponse } from "@/lib/card-answer";import { answerThread, closeResponse, type QuickAction } from "./inbox-view";@@ -10,7 +12,7 @@ import { answerThread, closeResponse, type QuickAction } from "./inbox-view";/** What a row's buttons do. An ask is answered through its copy's card here, which answers the card where it was asked,* as its buttons in the chat do; a line of news is done, or opened where it came from. */export function useInboxActions(view: InboxView | null) {- const { state, dispatch } = useStore();+ const store = useStoreRef(), dispatch = store.dispatch;const showThreads = useShowThreads();const phone = useMediaQuery(PHONE_LAYOUT);@@ -27,11 +29,11 @@ export function useInboxActions(view: InboxView | null) {const target = row.origin ? { botId: row.origin.botId, threadId: row.origin.threadId, messageId: row.origin.messageId }: view?.threadId && view.botId ? { botId: view.botId, threadId: view.threadId, messageId: row.id } : null;if (!target) return;- openThread(dispatch, { botId: target.botId, threadId: target.threadId }, state, showThreads);+ openThread(dispatch, { botId: target.botId, threadId: target.threadId }, store.state(), showThreads);if (target.messageId) dispatch({ type: "focusMessage", threadId: target.threadId, messageId: target.messageId });// The conversation is in the main window; on a phone the inbox is a sheet over it.if (phone) closeInbox();- }, [view, state, dispatch, showThreads, phone]);+ }, [view, store, dispatch, showThreads, phone]);const run = useCallback((row: InboxRow, action: QuickAction) => {if (action === "allow" || action === "deny") answer(row, { behavior: action });@@ -41,9 +43,10 @@ export function useInboxActions(view: InboxView | null) {else { readInboxRow(row); openInbox({ reading: row.id }); }}, [answer, openInChat]);- /** The bot a line is from: its face leads the line's card and its colour is on the card's answer. None for a teammate's line. */- const askerOf = (row: InboxRow) => (row.from.botId ? state.bots.find((bot) => bot.id === row.from.botId) : undefined);- const colorOf = (row: InboxRow) => askerOf(row)?.color;+ return { run, answer, openInChat };+}- return { run, answer, openInChat, colorOf, askerOf };+/** The bot a line is from: its face leads the line's card and its colour is on the card's answer. None for a teammate's line. */+export function useInboxAsker(row: InboxRow) {+ return useStoreSelector((state) => (row.from.botId ? state.bots.find((bot) => bot.id === row.from.botId) : undefined));}diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsxindex 9f942d86b4..23e2c27f2d 100644--- a/src/components/keys/KeysPage.tsx+++ b/src/components/keys/KeysPage.tsx@@ -1,7 +1,7 @@import { SettingsFoldRow, SettingsRows } from "../SettingsPrimitives";import { useEffect, useId, useRef, useState, type ReactNode } from "react";import { ChevronRight, Search } from "lucide-react";-import { useStore, type ConfigStatus } from "@/state/store";+import { type ConfigStatus } from "@/state/store";import { cn } from "@/lib/cn";import { scrollParent, scrollWithin } from "@/lib/scroll-within";import { t } from "@/lib/i18n";@@ -15,6 +15,7 @@ import { KEY_CATALOG, KEY_SECTIONS, keyHidden, keyMatches, savedState, type KeyEimport { finishKeyFocus, useKeyFocus, type KeyFocusRequest } from "./key-focus";import { AnthropicEveryClaudeBot, OpenAiCompatUrl, OpenCodeProviderKeys, VpsConnection } from "./KeyPanels";import { KEY_CONTENT, KEY_ROW, KeyRow, MaskedKey, RowHeading, type KeyStatus } from "./KeyRow";+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";const CARD = "rounded-xl bg-card in-data-[settings-look=simple]:rounded-[12px] in-data-[settings-look=simple]:border-[0.5px] in-data-[settings-look=simple]:border-(--settings-edge) in-data-[settings-look=simple]:bg-menu";const HIGHLIGHT_MS = 1600;@@ -40,7 +41,7 @@ function connected(entry: KeyEntry, config: ConfigStatus | null | undefined): bo}function PanelRow({ entry, visible }: { entry: KeyEntry; visible: boolean }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const titleId = useId();const saved = savedState(entry, state.config);const status: KeyStatus = saved.configured ? { tone: "ok", text: t("keys.connected") } : null;@@ -53,7 +54,7 @@ function PanelRow({ entry, visible }: { entry: KeyEntry; visible: boolean }) {}function ElsewhereRow({ entry }: { entry: KeyEntry }) {- const { state, dispatch } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const titleId = useId();const opens = entry.opens;const saved = savedState(entry, state.config);@@ -84,7 +85,7 @@ export function KeyCatalogRow({ entry, visible }: { entry: KeyEntry; visible: bo}function KeySection({ id, rows, open, onToggle }: { id: KeySectionId; rows: KeyEntry[]; open: boolean; onToggle: () => void }) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const section = KEY_SECTIONS.find((candidate) => candidate.id === id)!;const headId = useId();const bodyId = useId();@@ -129,7 +130,7 @@ function landOn(page: HTMLElement | null, request: KeyFocusRequest, section: Key/** `bare`: inside AI's Other services, every section is a fold row in one card; `exclude`: sections listed elsewhere* (AI providers are AI's own Providers list), unless a search or a link asks for a key in one. */export function KeysPage({ bare = false, exclude = [] }: { bare?: boolean; exclude?: KeySectionId[] } = {}) {- const { state } = useStore();+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);const [query, setQuery] = useState("");const [open, setOpen] = useState<ReadonlySet<KeySectionId>>(() => new Set(KEY_SECTIONS.filter((section) => section.id === "ai" || KEY_CATALOG.some((entry) => entry.section === section.id && connected(entry, state.config)))diff --git a/src/components/language-switch.render.test.ts b/src/components/language-switch.render.test.tsnew file mode 100644index 0000000000..bc145480a7--- /dev/null+++ b/src/components/language-switch.render.test.ts@@ -0,0 +1,171 @@+// @vitest-environment happy-dom+// The real provider and live stream behind a parent that switches the page's language as App does: Settings, the+// routines calendar, a bot's settings, the command palette and the Inbox draw again in the new language, though App's+// redraws pass them by.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { Action, BotAnnouncement, InstanceInfo } from "@/state/store";++const mode = vi.hoisted(() => ({ advanced: true }));+vi.mock("@/lib/interface-mode", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/interface-mode")>(), useAdvancedMode: () => mode.advanced }));+vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn(), analyticsEnabled: () => false, setAnalyticsEnabled: vi.fn() }));+vi.mock("@/lib/cloud-guest", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useCanWriteIn: () => true, useReactor: () => "user" }));++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const announced = (i: number, extra: Partial<BotAnnouncement> = {}): BotAnnouncement => ({+ id: `b${i}`, threadId: `b${i}-thread`, name: `Bot ${i}`, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "test", model: "m" }, section: i % 3 === 0 ? "Sales" : undefined,+ tasks: [{ threadId: `b${i}-thread`, title: "Chat", createdAt: 1, approvalMode: "ask" }], ...extra,+} as BotAnnouncement);+const at = Date.UTC(2026, 10, 18, 9);+const routines = Array.from({ length: 12 }, (_, i) => ({+ id: `r${i}`, name: `Routine ${i}`, prompt: "Do it.", target: "bot", botId: `b${i % 12}`, runOn: "maus", enabled: true,+ schedule: { type: "daily", time: `${String(8 + (i % 10)).padStart(2, "0")}:00`, weekdays: [0, 1, 2, 3, 4, 5, 6] }, durationMinutes: 30,+ nextRunAt: at + 3_600_000, createdAt: 0, updatedAt: 0,+}));+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const answers: Record<string, unknown> = {+ "/api/instances": { instances: [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" }, models: { default: "m", options: [{ id: "m", label: "Model" }] } } as unknown as InstanceInfo] },+ "/api/config": {+ anthropic: { configured: true }, composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" },+ rooms: { turnTimeoutMinutes: 10 }, mcp: { callTimeoutMinutes: 5 }, threads: { maxConcurrentPerBot: 3 }, localVm: { mode: "shared", maxInstances: 1 },+ profile: { name: "Ada", email: "[email protected]", aboutMe: "" }, features: {}, edition: { edition: "community", features: [] }, browserProfiles: [],+ budgets: {}, billing: { currency: "USD", prices: {} }, pausedBots: [], heldBots: [], newBots: {},+ },+ "/api/routines": { routines, runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] },+ "/api/profile/learned": { learned: [] },+ "/api/themes": { themes: [] },+ "/api/themes/history": { items: [] },+};+const missing = () => Promise.resolve(new Response(JSON.stringify({ error: "not in this fixture" }), { status: 404 }));++const { StoreProvider, useStore } = await import("@/state/store");+const { effectiveLanguage, useLanguageChoice, usePageLanguage, setLanguageChoice } = await import("@/lib/language-preference");+const { activeLocale, t } = await import("@/lib/i18n");+const { SettingsModal, TriggersPage, BotSettingsDialog } = await import("./lazy-screens");+await Promise.all([SettingsModal.preload(), TriggersPage.preload(), BotSettingsDialog.preload()]);+const { CommandPalette, openCommandPalette } = await import("./CommandPalette");+const { InboxPanel } = await import("./inbox/InboxPanel");+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false;++let surface: "settings" | "calendar" | "bot-settings" | "palette" | "inbox" | "none" = "none";+let dispatch!: (action: Action) => void;+const onBack = () => {}, onOpenRoom = () => {}, onOpenChange = () => {};+function App() {+ const { state, dispatch: storeDispatch } = useStore();+ dispatch = storeDispatch;+ usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language), true);+ const bot = state.bots.find((candidate) => candidate.id === state.selectedId);+ if (surface === "settings") return createElement(SettingsModal);+ if (surface === "calendar") return createElement(TriggersPage, { onBack, onOpenRoom });+ if (surface === "bot-settings") return bot ? createElement(BotSettingsDialog, { key: bot.id, bot, overlay: false }) : null;+ if (surface === "palette") return createElement(CommandPalette, { onOpenChange });+ if (surface === "inbox") return createElement(InboxPanel);+ return null;+}+let root: Root;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 60; i++) await task(); };+/** Brazilian Portuguese has every English string, so each surface's text changes. */+const speak = async (language: "en" | "pt-br") => {+ setLanguageChoice(language);+ await vi.waitFor(() => expect(activeLocale()).toBe(language));+ await settle();+};++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (input: string) => {+ const path = String(input).replace(/\?.*$/, "");+ if (path === "/api/bots") return json({ bots: Array.from({ length: 12 }, (_, i) => ({ ...announced(i), messages: [] })), groups: [] });+ if (path in answers) return json(answers[path]);+ return /^\/api\/bots\/[^/]+\/overview$/.test(path) ? missing() : json({});+ });+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(App))));+ await settle();+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "select", id: "b0" }));+ await settle();+});+afterAll(async () => {+ await speak("en");+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});++const text = () => document.body.textContent ?? "";+async function open(next: typeof surface, action?: Action) {+ await speak("en");+ surface = next;+ flushSync(() => dispatch(action ?? { type: "connected", value: true }));+ await settle();+}++describe("a language switch", () => {+ it("draws the Inbox again in the new language", async () => {+ await open("inbox");+ expect(text()).toContain("Inbox");+ await speak("pt-br");+ expect(text()).toContain(t("inbox.panel.title"));+ });++ it("draws Settings again in the new language", async () => {+ await open("settings", { type: "toggleAppSettings", open: true, section: "general" });+ expect(text()).toContain("Settings");+ await speak("pt-br");+ expect(text()).toContain(t("settings.title"));+ flushSync(() => dispatch({ type: "toggleAppSettings", open: false }));+ });++ it("draws the routines calendar again in the new language, its sidebar and cards included", async () => {+ await open("calendar", { type: "showRoutines", view: "calendar" });+ const cards = () => [...document.querySelectorAll("[data-event-card]")].map((card) => card.getAttribute("aria-label"));+ const before = cards();+ expect(before.length).toBeGreaterThan(0);+ await speak("pt-br");+ expect(text()).toContain(t("routines.today"));+ expect(text()).toContain(t("routines.sidebar.myBots"));+ expect(cards()).not.toEqual(before);+ surface = "none";+ });++ it("draws a bot's settings again in the new language", async () => {+ mode.advanced = true;+ await open("bot-settings", { type: "toggleSettings", open: true, section: "overview" });+ expect(text()).toContain("Overview");+ await speak("pt-br");+ expect(text()).toContain(t("botSettings.sections.overview"));+ flushSync(() => dispatch({ type: "toggleSettings", open: false }));+ });++ it("draws the open command palette again in the new language", async () => {+ await open("palette");+ flushSync(() => openCommandPalette());+ await settle();+ const field = () => document.querySelector<HTMLInputElement>('[role="dialog"] input')?.placeholder;+ const before = field();+ await speak("pt-br");+ expect(field()).toBe(t("commandPalette.searchPlaceholder"));+ expect(field()).not.toBe(before);+ });+});diff --git a/src/components/lazy-screens.test.ts b/src/components/lazy-screens.test.tsindex 3bf40c3cfc..da04ddc266 100644--- a/src/components/lazy-screens.test.ts+++ b/src/components/lazy-screens.test.ts@@ -9,8 +9,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";const screens = await import("./lazy-screens");const { lazyScreen, preloadScreens } = screens;+/** A screen is a function, or a memo object when it draws from its props alone. */+const isScreen = (value: unknown): value is ReturnType<typeof lazyScreen> =>+ (typeof value === "function" || (typeof value === "object" && value !== null)) && "preload" in value;const stubPreloads = () => Object.values(screens)- .filter((value): value is ReturnType<typeof lazyScreen> => typeof value === "function" && "preload" in value)+ .filter(isScreen).map((screen) => vi.spyOn(screen, "preload").mockResolvedValue(() => null));let root: Root | null = null;@@ -201,7 +204,7 @@ describe("preloadScreens", () => {for (const preload of preloads) expect(preload).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(60_000);const rarelyOpened = [screens.CloudAddDialog, screens.GrokMoveDialog, screens.PhoneAppDialog, screens.ShareDepartmentDialog, screens.ImportDialog, screens.TeamLibraryPanel, screens.TeamFilesPage, screens.AnnouncementsPage];- const stubbed = Object.values(screens).filter((value): value is ReturnType<typeof lazyScreen> => typeof value === "function" && "preload" in value);+ const stubbed = Object.values(screens).filter(isScreen);for (const screen of stubbed) expect(screen.preload).toHaveBeenCalledTimes(rarelyOpened.includes(screen as never) ? 0 : 1);expect(preloads.length).toBe(stubbed.length);});diff --git a/src/components/lazy-screens.tsx b/src/components/lazy-screens.tsxindex 2ac8711591..68f5779cbf 100644--- a/src/components/lazy-screens.tsx+++ b/src/components/lazy-screens.tsx@@ -1,4 +1,5 @@-import { useEffect, useState, type ComponentType, type ReactNode } from "react";+import { createElement, memo, useEffect, useState, type ComponentType, type MemoExoticComponent, type ReactNode } from "react";+import { useActiveLocale } from "@/lib/use-active-locale";import { createPortal } from "react-dom";import { t } from "@/lib/i18n";@@ -6,13 +7,13 @@ import { t } from "@/lib/i18n";// up to 300 ms) and rethrows a failed import on every render. Chromium keeps a failed import() in its module map and// rejects every later import of it without refetching.-export type LazyScreen<P> = ((props: P) => ReactNode) & {+export type LazyScreen<P> = (((props: P) => ReactNode) | MemoExoticComponent<(props: P) => ReactNode>) & {preload: () => Promise<ComponentType<P>>;};export function lazyScreen<Props>(name: string,- load: () => Promise<(props: Props) => ReactNode>,+ load: () => Promise<((props: Props) => ReactNode) | MemoExoticComponent<(props: Props) => ReactNode>>,): LazyScreen<NonNullable<Props>> {type P = NonNullable<Props>;let ready: ComponentType<P> | undefined;@@ -45,6 +46,16 @@ export function lazyScreen<Props>(return Object.assign(Screen, { preload });}+/** For a screen drawn only from its props, its own store selections and the page's language: App drawing again passes+ * it by. */+function pureScreen<Props>(screen: LazyScreen<Props>): LazyScreen<Props> {+ function PureScreen(props: Props) {+ useActiveLocale();+ return createElement(screen as ComponentType<Props & object>, props as Props & object);+ }+ return Object.assign(memo(PureScreen), { preload: screen.preload }) as LazyScreen<Props>;+}+function ScreenUnavailable() {return createPortal(<div@@ -66,7 +77,7 @@ function ScreenUnavailable() {}export const ActivityPanel = lazyScreen("ActivityPanel", async () => (await import("./ActivityPanel")).ActivityPanel);-export const BotSettingsDialog = lazyScreen("BotSettingsDialog", async () => (await import("./BotSettingsDialog")).BotSettingsDialog);+export const BotSettingsDialog = pureScreen(lazyScreen("BotSettingsDialog", async () => (await import("./BotSettingsDialog")).BotSettingsDialog));export const ComputerPanel = lazyScreen("ComputerPanel", async () => (await import("./ComputerPanel")).ComputerPanel);export const FilesView = lazyScreen("FilesView", async () => (await import("./FilesView")).FilesView);export const InspectorPanel = lazyScreen("InspectorPanel", async () => (await import("./InspectorPanel")).InspectorPanel);@@ -77,8 +88,8 @@ export const PluginsPanel = lazyScreen("PluginsPanel", async () => (await importexport const RemoteAgentSettingsPanel = lazyScreen("RemoteAgentSettingsPanel", async () => (await import("./RemoteAgentSettingsPanel")).RemoteAgentSettingsPanel);export const RoomPanel = lazyScreen("RoomPanel", async () => (await import("./room-panel/RoomPanel")).RoomPanel);export const RemoteDesktopPanel = lazyScreen("RemoteDesktopPanel", async () => (await import("./remote-desktop-panel")).RemoteDesktopPanel);-export const TriggersPage = lazyScreen("TriggersPage", async () => (await import("./TriggersPage")).TriggersPage);-export const SettingsModal = lazyScreen("SettingsModal", async () => (await import("./SettingsModal")).SettingsModal);+export const TriggersPage = pureScreen(lazyScreen("TriggersPage", async () => (await import("./TriggersPage")).TriggersPage));+export const SettingsModal = pureScreen(lazyScreen("SettingsModal", async () => (await import("./SettingsModal")).SettingsModal));export const TeamMapPage = lazyScreen("TeamMapPage", async () => (await import("./TeamMapPage")).TeamMapPage);export const PublishedAppsPage = lazyScreen("PublishedAppsPage", async () => (await import("./published-apps/PublishedAppsPage")).PublishedAppsPage);export const AnnouncementsPage = lazyScreen("AnnouncementsPage", async () => (await import("./announcements/AnnouncementsPage")).AnnouncementsPage);diff --git a/src/components/routines/CalendarEventCard.tsx b/src/components/routines/CalendarEventCard.tsxindex 3c032bfd50..7d8e6081ba 100644--- a/src/components/routines/CalendarEventCard.tsx+++ b/src/components/routines/CalendarEventCard.tsx@@ -1,4 +1,4 @@-import { useEffect, useState, type PointerEvent as ReactPointerEvent } from "react";+import { memo, useEffect, useState, type PointerEvent as ReactPointerEvent } from "react";import { Video } from "lucide-react";import { BotAvatar } from "@/components/Avatar";@@ -9,7 +9,7 @@ import { CALENDAR_SLOT_MINUTES } from "@/lib/routine-calendar";import { partlyDone, routineHeldNote, routineRunLabel } from "@/lib/routine-display";import type { RoutineRunStatus } from "@/lib/routines";import { intervalLabel, niceTime } from "@/lib/schedule-label";-import type { Bot, Group } from "@/state/store";+import type { BotApartFromTurns, GroupApartFromTurns } from "@/state/apart-from-turns";import type { CalendarEventItem } from "../RoutineCalendarPage";import { EVENT_DRAG_TYPE } from "./LimitResetMarkers";@@ -31,7 +31,7 @@ export function cardLayout(height: number): "roomy" | "compact" | "tiny" {return height >= 22 ? "compact" : "tiny";}-export function CalendarEventCard({+export const CalendarEventCard = memo(function CalendarEventCard({item,bots,groups,@@ -42,13 +42,15 @@ export function CalendarEventCard({onResize,}: {item: CalendarEventItem;- bots: Bot[];- groups: Group[];+ bots: readonly BotApartFromTurns[];+ groups: readonly GroupApartFromTurns[];compact: boolean;layout: { column: number; columns: number };selected?: boolean;- onOpen: () => void;- onResize: (minutes: number) => void;+ onOpen: (item: CalendarEventItem) => void;+ onResize: (item: CalendarEventItem, minutes: number) => void;+ /** Drawn again in a new language. */+ locale?: string;}) {const isCall = item.kind === "call";const routine = item.kind === "routine" ? item.routine : null;@@ -94,7 +96,7 @@ export function CalendarEventCard({setPreviewDuration(item.durationMinutes);return;}- onResize(next);+ onResize(item, next);};document.addEventListener("pointermove", move);document.addEventListener("pointerup", up, { once: true });@@ -117,7 +119,7 @@ export function CalendarEventCard({event.dataTransfer.effectAllowed = "move";event.dataTransfer.setData(EVENT_DRAG_TYPE, JSON.stringify({ kind: item.kind, id: isCall ? item.call.id : routine!.id, at: item.at }));}}- onClick={(event) => { event.stopPropagation(); onOpen(); }}+ onClick={(event) => { event.stopPropagation(); onOpen(item); }}aria-pressed={selected}aria-label={`${name}, ${niceTime(item.at)}${paused ? `, ${t("routines.pausedSchedule")}` : statusLabel ? `, ${statusLabel}` : ""}`}className={cn(@@ -161,4 +163,4 @@ export function CalendarEventCard({{isCall && <div onPointerDown={beginResize} className="absolute inset-x-1 bottom-0 h-1.5 cursor-ns-resize rounded-full opacity-0 transition group-hover:opacity-100" aria-label={t("routines.event.resize")}><div className="mx-auto mt-0.5 h-0.5 w-5 rounded-full bg-current opacity-50" /></div>}</button>);-}+});diff --git a/src/components/routines/CalendarGrid.tsx b/src/components/routines/CalendarGrid.tsxnew file mode 100644index 0000000000..8f82be96eb--- /dev/null+++ b/src/components/routines/CalendarGrid.tsx@@ -0,0 +1,147 @@+import { useEffect, useMemo, useRef, useState, type DragEvent as ReactDragEvent, type PointerEvent as ReactPointerEvent } from "react";++import { useStableCallback } from "@/hooks/use-stable-callback";+import { useMinuteTick } from "@/lib/minute-tick";+import { cn } from "@/lib/cn";+import { activeLocale, intlLocale, t } from "@/lib/i18n";+import type { ResetMarker } from "@/lib/limit-resets";+import { addDays, CALENDAR_SLOT_MINUTES, formatGmtOffset, packCalendarCollisions, slotAt, startOfDay } from "@/lib/routine-calendar";+import { dayName, niceDate, niceTime } from "@/lib/schedule-label";+import type { BotApartFromTurns, GroupApartFromTurns } from "@/state/apart-from-turns";+import type { CalendarEventItem, EventKind, EventSeed } from "../RoutineCalendarPage";+import { CalendarEventCard, HOUR_HEIGHT } from "./CalendarEventCard";+import { BOT_DRAG_TYPE, EVENT_DRAG_TYPE, LimitResetMarker, type ResetDrop } from "./LimitResetMarkers";++const ONE_COLUMN = { column: 0, columns: 1 };++export function CalendarGrid({+ anchor,+ days,+ items,+ bots,+ groups,+ selectedId,+ onOpen,+ onCreate,+ onMove,+ onResize,+ markers = [],+ onDropOnReset,+}: {+ anchor: number;+ days: number;+ items: CalendarEventItem[];+ markers?: ResetMarker[];+ onDropOnReset?: (drop: ResetDrop, marker: ResetMarker) => void;+ bots: readonly BotApartFromTurns[];+ groups: readonly GroupApartFromTurns[];+ selectedId?: string;+ onOpen: (item: CalendarEventItem) => void;+ onCreate: (seed: EventSeed) => void;+ onMove: (item: { kind: EventKind; id: string; at: number }, nextAt: number) => void;+ onResize: (item: CalendarEventItem, duration: number) => void;+}) {+ const scrollRef = useRef<HTMLDivElement>(null);+ const openItem = useStableCallback(onOpen), resizeItem = useStableCallback(onResize);+ const byDay = useMemo(() => new Map(Array.from({ length: days }, (_, index) => {+ const start = addDays(anchor, index), dayItems = items.filter((item) => startOfDay(item.at) === start);+ return [start, { dayItems, layouts: packCalendarCollisions(dayItems) }];+ })), [anchor, days, items]);+ const [selection, setSelection] = useState<{ day: number; start: number; end: number } | null>(null);+ const [dragPreview, setDragPreview] = useState<{ day: number; at: number } | null>(null);+ useMinuteTick();+ const today = startOfDay(Date.now());+ const starts = Array.from({ length: days }, (_, index) => addDays(anchor, index));+ const minDayWidth = days === 7 ? 64 : days === 3 ? 180 : 280;+ const gridTemplateColumns = `64px repeat(${days}, minmax(${minDayWidth}px, 1fr))`;+ const minWidth = 64 + days * minDayWidth;++ useEffect(() => {+ const viewport = scrollRef.current;+ if (!viewport) return;+ const now = new Date();+ const hour = starts.includes(today) ? Math.max(0, now.getHours() - 2) : 7;+ viewport.scrollTo({ top: hour * HOUR_HEIGHT });+ }, [days]);++ const beginSelection = (event: ReactPointerEvent<HTMLDivElement>, day: number) => {+ if (event.button !== 0 || (event.target as HTMLElement).closest("[data-event-card]")) return;+ const rect = event.currentTarget.getBoundingClientRect();+ const start = slotAt(day, event.clientY, rect.top, HOUR_HEIGHT);+ let end = start + 30 * 60_000;+ setSelection({ day, start, end });+ const move = (pointer: PointerEvent) => {+ const current = slotAt(day, pointer.clientY, rect.top, HOUR_HEIGHT);+ end = Math.max(start + CALENDAR_SLOT_MINUTES * 60_000, current + CALENDAR_SLOT_MINUTES * 60_000);+ setSelection({ day, start, end });+ };+ const up = (pointer: PointerEvent) => {+ document.removeEventListener("pointermove", move);+ document.removeEventListener("pointerup", up);+ setSelection(null);+ onCreate({ kind: "routine", at: start, durationMinutes: Math.max(CALENDAR_SLOT_MINUTES, Math.round((end - start) / 60_000)), botIds: [], anchor: { x: pointer.clientX, y: pointer.clientY } });+ };+ document.addEventListener("pointermove", move);+ document.addEventListener("pointerup", up, { once: true });+ };++ const drop = (event: ReactDragEvent<HTMLDivElement>, day: number) => {+ event.preventDefault();+ setDragPreview(null);+ const rect = event.currentTarget.getBoundingClientRect();+ const at = slotAt(day, event.clientY, rect.top, HOUR_HEIGHT);+ const botId = event.dataTransfer.getData(BOT_DRAG_TYPE);+ if (botId) return onCreate({ kind: "routine", at, durationMinutes: 30, botIds: [botId], anchor: { x: event.clientX, y: event.clientY } });+ const raw = event.dataTransfer.getData(EVENT_DRAG_TYPE);+ if (!raw) return;+ try {+ const item = JSON.parse(raw) as { kind: EventKind; id: string; at: number };+ onMove(item, at);+ } catch {+ }+ };++ const previewDrop = (event: ReactDragEvent<HTMLDivElement>, day: number) => {+ if (!event.dataTransfer.types.includes(BOT_DRAG_TYPE) && !event.dataTransfer.types.includes(EVENT_DRAG_TYPE)) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = event.dataTransfer.types.includes(EVENT_DRAG_TYPE) ? "move" : "copy";+ const rect = event.currentTarget.getBoundingClientRect();+ const at = slotAt(day, event.clientY, rect.top, HOUR_HEIGHT);+ setDragPreview((current) => current?.day === day && current.at === at ? current : { day, at });+ };++ return (+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-auto border-l border-t border-hairline/40 bg-app">+ <div className="sticky top-0 z-30 grid bg-app/95 backdrop-blur" style={{ gridTemplateColumns, minWidth }}>+ <div className="border-b border-r border-hairline/40 px-2 py-3 text-center text-[9px] uppercase tracking-wider text-ink-secondary">{formatGmtOffset(-new Date(anchor).getTimezoneOffset())}</div>+ {starts.map((start) => {+ const date = new Date(start);+ const isToday = start === today;+ return <div key={start} role="columnheader" className={cn("border-b border-r border-hairline/40 px-2 py-2 text-center last:border-r-0", isToday && "bg-accent/[0.035]")}><div className={cn("text-[10px] font-medium uppercase tracking-[0.14em]", isToday ? "text-accent" : "text-ink-secondary")}>{dayName(date.getDay())}</div><div className={cn("mx-auto mt-1 flex size-8 items-center justify-center rounded-full text-[15px] font-medium", isToday ? "bg-accent text-accent-ink" : "text-ink")}>{date.getDate()}</div></div>;+ })}+ </div>+ <div role="grid" aria-label={t("routines.calendar.label")} onDragEnd={() => setDragPreview(null)} className="relative grid" style={{ height: HOUR_HEIGHT * 24, gridTemplateColumns, minWidth }}>+ <div className="relative border-r border-hairline/40">+ {Array.from({ length: 24 }, (_, hour) => <div key={hour} className="absolute right-2 -translate-y-1/2 text-[10px] tabular-nums text-ink-tertiary" style={{ top: hour * HOUR_HEIGHT }}>{hour === 0 ? "" : new Date(2000, 0, 1, hour).toLocaleTimeString(intlLocale(), { hour: "numeric" })}</div>)}+ </div>+ {starts.map((start) => {+ const now = new Date();+ const nowTop = ((now.getHours() * 60 + now.getMinutes()) / 60) * HOUR_HEIGHT;+ const { dayItems, layouts: collisionLayouts } = byDay.get(start)!;+ const selected = selection?.day === start ? selection : null;+ const preview = dragPreview?.day === start ? dragPreview : null;+ return (+ <div key={start} role="gridcell" aria-label={t("routines.calendar.day", { date: niceDate(start) })} onPointerDown={(event) => beginSelection(event, start)} onDragOver={(event) => previewDrop(event, start)} onDragLeave={(event) => { if (!(event.relatedTarget instanceof Node) || !event.currentTarget.contains(event.relatedTarget)) setDragPreview(null); }} onDrop={(event) => drop(event, start)} className={cn("relative border-r border-hairline/40 last:border-r-0", start === today && "bg-accent/[0.025]")}>+ {Array.from({ length: 48 }, (_, half) => <div key={half} className={cn("pointer-events-none absolute inset-x-0 border-t", half % 2 === 0 ? "border-hairline/30" : "border-hairline/10")} style={{ top: (half / 2) * HOUR_HEIGHT }} />)}+ {start === today && <div className="pointer-events-none absolute inset-x-0 z-20 flex items-center" style={{ top: nowTop }}><span className="-ml-1 size-2 rounded-full bg-danger" /><span className="h-px flex-1 bg-danger/80" /></div>}+ {selected && <div className="pointer-events-none absolute inset-x-1 z-10 rounded-md border border-accent/70 bg-accent/20" style={{ top: ((new Date(selected.start).getHours() * 60 + new Date(selected.start).getMinutes()) / 60) * HOUR_HEIGHT, height: Math.max(16, ((selected.end - selected.start) / 3_600_000) * HOUR_HEIGHT) }} />}+ {preview && <div className="pointer-events-none absolute inset-x-1 z-20 rounded-md border border-accent/80 bg-accent/25 shadow-sm" style={{ top: ((new Date(preview.at).getHours() * 60 + new Date(preview.at).getMinutes()) / 60) * HOUR_HEIGHT, height: HOUR_HEIGHT / 2 }}><div className="px-2 py-1 text-[10px] font-medium text-accent">{niceTime(preview.at)}</div></div>}+ {markers.filter((marker) => startOfDay(marker.at) === start).map((marker) => <LimitResetMarker key={marker.engine} marker={marker} hourHeight={HOUR_HEIGHT} onDrop={onDropOnReset && ((drop) => onDropOnReset(drop, marker))} />)}+ {dayItems.map((item) => <CalendarEventCard key={item.id} item={item} bots={bots} groups={groups} compact={days === 7} layout={collisionLayouts.get(item.id) ?? ONE_COLUMN} selected={item.id === selectedId} onOpen={openItem} onResize={resizeItem} locale={activeLocale()} />)}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/src/components/routines/CalendarSidebar.tsx b/src/components/routines/CalendarSidebar.tsxindex 5cc053400e..8214784347 100644--- a/src/components/routines/CalendarSidebar.tsx+++ b/src/components/routines/CalendarSidebar.tsx@@ -1,19 +1,21 @@-import { useMemo, useState, type DragEvent } from "react";+import { memo, useMemo, useState, type DragEvent } from "react";import { GripVertical, Search, UsersRound } from "lucide-react";import { BotAvatar } from "@/components/Avatar";-import type { Bot } from "@/state/store";+import type { BotApartFromTurns } from "@/state/apart-from-turns";import { MiniMonth } from "./MiniMonth";import { t } from "@/lib/i18n";export const BOT_CALENDAR_DRAG_TYPE = "application/x-openmaus-bot";export interface CalendarSidebarProps {- bots: Bot[];+ bots: readonly BotApartFromTurns[];anchor: number;onSelectDate: (at: number) => void;+ /** Drawn again in a new language. */+ locale?: string;}-export function CalendarSidebar({ bots, anchor, onSelectDate }: CalendarSidebarProps) {+export const CalendarSidebar = memo(function CalendarSidebar({ bots, anchor, onSelectDate }: CalendarSidebarProps) {const [query, setQuery] = useState("");const filteredBots = useMemo(() => {const normalized = query.trim().toLocaleLowerCase();@@ -23,7 +25,7 @@ export function CalendarSidebar({ bots, anchor, onSelectDate }: CalendarSidebarP);}, [bots, query]);- const beginBotDrag = (event: DragEvent<HTMLDivElement>, bot: Bot) => {+ const beginBotDrag = (event: DragEvent<HTMLDivElement>, bot: BotApartFromTurns) => {event.dataTransfer.effectAllowed = "copy";event.dataTransfer.setData(BOT_CALENDAR_DRAG_TYPE, bot.id);event.dataTransfer.setData("text/plain", bot.id);@@ -107,4 +109,4 @@ export function CalendarSidebar({ bots, anchor, onSelectDate }: CalendarSidebarP</section></aside>);-}+});diff --git a/src/components/settings/DesktopKinds.tsx b/src/components/settings/DesktopKinds.tsxindex 10943420b3..f569b428a9 100644--- a/src/components/settings/DesktopKinds.tsx+++ b/src/components/settings/DesktopKinds.tsx@@ -3,7 +3,7 @@ import { Cloud, Laptop, Server } from "lucide-react";import { t } from "@/lib/i18n";import { productName } from "@/lib/brand";import { computerInventoryRequest } from "@/lib/computer-requests";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { LocalComputerSection } from "../LocalComputerSection";import { SettingRow, SettingsGroup, SettingsLinkRow, SettingsMark, SettingsRows, StatusDot } from "../SettingsPrimitives";import { useAccountSummary } from "./account-summary";@@ -60,8 +60,7 @@ function PrivateSetup({ status, onCheck, onClose }: { status: PrivateStatus; onC/** Desktops: what each kind is, its state first, and one Set up. */export function DesktopKinds() {const { ctx, place, go } = useSettingsShell();- const { state } = useStore();- const cloudHome = state.config?.cloudHome === true;+ const cloudHome = useStoreSelector((state) => state.config?.cloudHome === true);const [local, setLocal] = useState<PrivateStatus>(null);const [cloud, setCloud] = useState<{ configured: boolean; available: boolean } | null>(null);const [vps, setVps] = useState<{ configured: boolean; available: boolean } | null>(null);diff --git a/src/components/settings/SettingsNav.tsx b/src/components/settings/SettingsNav.tsxindex 957663c48e..69f5c636b7 100644--- a/src/components/settings/SettingsNav.tsx+++ b/src/components/settings/SettingsNav.tsx@@ -7,7 +7,7 @@ import { t } from "@/lib/i18n";import { productName } from "@/lib/brand";import { setAdvancedMode, useAdvancedMode } from "@/lib/interface-mode";import { SIMPLE_ONLY } from "@/lib/simple-only";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { InitialsAvatar } from "../Avatar";import { PlaceMark } from "../PlacesRail";import { profileInitials } from "../SidebarProfileMenu";@@ -56,11 +56,10 @@ export function YouAvatar({ size }: { size: number }) {/** The place's one status line under its name: bots on This computer, power on a Cloud. */export function usePlaceSubLine(place: SettingsPlace): string {- const { state } = useStore();+ const count = useStoreSelector((state) => (place.kind === "computer" ? state.bots.length : 0));const update = useUpdaterState();if (update?.status === "downloaded" && place.kind === "computer") return t("sidebar.update.readyShort");if (place.kind === "computer") {- const count = state.bots.length;return count === 0 ? t("settings.place.botsNone") : count === 1 ? t("settings.place.botsOne") : t("settings.place.botsMany", { count });}return place.kind === "server" ? t("settings.place.running") : t("settings.place.alwaysOn");diff --git a/src/components/settings/SettingsWindow.tsx b/src/components/settings/SettingsWindow.tsxindex c66c85c776..18a2546d82 100644--- a/src/components/settings/SettingsWindow.tsx+++ b/src/components/settings/SettingsWindow.tsx@@ -6,7 +6,8 @@ import { glassPopupFrameStyle, glassPopupTopInset, GLASS_POPUP_GUTTER } from "@/import { scrollWithin } from "@/lib/scroll-within";import { useMediaQuery } from "@/lib/use-media-query";import { setAdvancedMode } from "@/lib/interface-mode";-import { api, useStore, type ConfigStatus } from "@/state/store";+import { api, type ConfigStatus } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useIsTopLayer } from "../Layer";import { LicenseExpiryBanner } from "../LicenseExpiryBanner";import { shortcutLabel } from "../ShortcutHint";@@ -50,20 +51,21 @@ export function revealAnchor(scroller: HTMLElement | null, anchor: string | nullexport function SettingsWindow() {const isTop = useIsTopLayer();- const { state, dispatch } = useStore();+ const section = useStoreSelector((state) => state.appSettingsSection), config = useStoreSelector((state) => state.config);+ const unreachable = useStoreSelector((state) => Boolean(state.error)), dispatch = useStoreDispatch();const ctx = useSettingsContext();const place = useSettingsPlace();const narrow = useMediaQuery(NARROW, false);- const target = resolveSettingsTarget(state.appSettingsSection, ctx);+ const target = resolveSettingsTarget(section, ctx);const [anchor, setAnchor] = useState<string | null>(target.anchor ?? null);- const [narrowPage, setNarrowPage] = useState(state.appSettingsSection !== "overview");+ const [narrowPage, setNarrowPage] = useState(section !== "overview");const [query, setQuery] = useState("");const pages = visiblePages(ctx);const page = pageById(target.page);const dialogRef = useRef<HTMLDivElement>(null);const scrollRef = useRef<HTMLDivElement>(null);- useEffect(() => { setAnchor(target.anchor ?? null); setNarrowPage((open) => open || state.appSettingsSection !== "overview"); }, [state.appSettingsSection, target.anchor]);+ useEffect(() => { setAnchor(target.anchor ?? null); setNarrowPage((open) => open || section !== "overview"); }, [section, target.anchor]);useEffect(() => {const frame = window.requestAnimationFrame(() => {if (anchor) revealAnchor(scrollRef.current, anchor);@@ -79,7 +81,7 @@ export function SettingsWindow() {const hits = useMemo(() => searchSettings(query, ctx, (entry) => hitLabel({ entry, elsewhere: false, score: 0 }, place, ctx.desktop),(candidate) => pageLabel(candidate, place, ctx.desktop)), [query, ctx, place]);- const keyHits = useMemo(() => (ctx.client || !query.trim() ? [] : KEY_CATALOG.filter((entry) => !keyHidden(entry.id, state.config) && keyMatches(entry, query.trim().toLowerCase(), state.config)).slice(0, 8)), [ctx.client, query, state.config]);+ const keyHits = useMemo(() => (ctx.client || !query.trim() ? [] : KEY_CATALOG.filter((entry) => !keyHidden(entry.id, config) && keyMatches(entry, query.trim().toLowerCase(), config)).slice(0, 8)), [ctx.client, query, config]);const openKey = (entry: KeyEntry) => { setQuery(""); setNarrowPage(true); dispatch(entry.uses ? openKeySettings(entry.uses, entry.id) : openKeySettings(entry.id)); };const computer = useSwitchToComputer();const close = () => dispatch({ type: "toggleAppSettings", open: false });@@ -190,9 +192,9 @@ export function SettingsWindow() {<div className={cn("flex max-w-[640px] flex-col", narrow && "max-w-none")}><SettingsPageHeader page={page} ctx={ctx} place={place} narrow={narrow} missing={missing} /><div key={target.page} data-settings-page-body={target.page} className={cn("flex flex-col gap-6", narrow && "px-4")}>- <LicenseExpiryBanner config={state.config} />- {page.owner === "place" && state.config === null- ? state.error ? <SettingsUnreachable place={place.name} onRetry={() => void api<ConfigStatus>("/api/config").then((config) => dispatch({ type: "configStatus", config })).catch(() => {})} />+ <LicenseExpiryBanner config={config} />+ {page.owner === "place" && config === null+ ? unreachable ? <SettingsUnreachable place={place.name} onRetry={() => void api<ConfigStatus>("/api/config").then((config) => dispatch({ type: "configStatus", config })).catch(() => {})} />: <><SettingsSkeletonCard place={place.name} /><SettingsSkeletonCard place={place.name} /></>: <SettingsPageBody page={target.page} />}</div>diff --git a/src/components/settings/account-summary.ts b/src/components/settings/account-summary.tsindex 98be88f101..6c8a00a07f 100644--- a/src/components/settings/account-summary.ts+++ b/src/components/settings/account-summary.ts@@ -4,7 +4,7 @@ import { cloudPlanLabel, cloudPlanView } from "@/lib/cloud-plan";import { t } from "@/lib/i18n";import { profileForSession, type SessionState } from "@/lib/session";import { readSharedSessionState } from "@/lib/shared-session";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";export interface AccountSummary {/** read from the account bridge, the plan bridge or the server session; null until it answers */@@ -53,14 +53,14 @@ export function useAccountSummary(): AccountSummary {/** The name and photo the chrome shows for you, and the server session they came from. */export function useYou(): { profile: { name?: string; email?: string; avatarUrl?: string } | undefined; session: SessionState | null } {- const { state } = useStore();+ const profile = useStoreSelector((state) => state.config?.profile);const [session, setSession] = useState<SessionState | null>(null);useEffect(() => {let alive = true;void readSharedSessionState().then((next) => { if (alive) setSession(next); });return () => { alive = false; };}, []);- return { profile: profileForSession(state.config?.profile, session), session };+ return { profile: profileForSession(profile, session), session };}/** "Pro · [email protected]", "Not signed in"; in a browser, "Signed in to My Cloud". */diff --git a/src/components/settings/pages/AccountPages.tsx b/src/components/settings/pages/AccountPages.tsxindex fef619516b..6f9e05e995 100644--- a/src/components/settings/pages/AccountPages.tsx+++ b/src/components/settings/pages/AccountPages.tsx@@ -2,7 +2,8 @@ import { ArrowUpRight } from "lucide-react";import { t } from "@/lib/i18n";import { CLOUD_PLAN_URL } from "@/lib/app-links";import { productName } from "@/lib/brand";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useState } from "react";import { InertRow, useSwitchToComputer } from "../inert";import { PlaceBadge, YouAvatar } from "../SettingsNav";@@ -21,7 +22,7 @@ import { profileLabel } from "../../SidebarProfileMenu";export function AccountPage() {const { ctx, place, go } = useSettingsShell();- const { state, dispatch } = useStore();+ const linkRequest = useStoreSelector((state) => state.appSettingsCloudLink), dispatch = useStoreDispatch();const { profile, session } = useYou();const summary = useAccountSummary();const computer = useSwitchToComputer();@@ -43,7 +44,7 @@ export function AccountPage() {: <SettingsLinkRow title={t("settings.account.nameRow")} badge={<PlaceBadge place={place} size={14} />} value={profileLabel(profile)} onClick={() => go("bots", "about-you")} data={{ "data-account-name-row": "" }} />}</SettingsRows></SettingsGroup>- {bridge && <CloudAccountSettings part="account" advanced={ctx.advanced} linkRequest={state.appSettingsCloudLink} avatar={<YouAvatar size={32} />}+ {bridge && <CloudAccountSettings part="account" advanced={ctx.advanced} linkRequest={linkRequest} avatar={<YouAvatar size={32} />}onSignIn={() => dispatch({ type: "openCloudAdd", source: "app_settings", signIn: true })} />}{elsewhere && (<SettingsGroup label={t("settings.account.mausbot", { app: productName() })} block="mausbot-account">@@ -90,7 +91,7 @@ export function AccountPage() {export function PlanPage() {const { ctx, place } = useSettingsShell();- const { state, dispatch } = useStore();+ const linkRequest = useStoreSelector((state) => state.appSettingsCloudLink), teamHome = useStoreSelector((state) => state.config?.team), dispatch = useStoreDispatch();const { usage, upgrade, dialog } = useCloudUsageSettings();if (!ctx.desktop) {return (@@ -104,7 +105,7 @@ export function PlanPage() {);}return <>- <CloudAccountSettings part="plan" advanced={ctx.advanced} cloudHome={ctx.cloud} teamHome={state.config?.team} linkRequest={state.appSettingsCloudLink}+ <CloudAccountSettings part="plan" advanced={ctx.advanced} cloudHome={ctx.cloud} teamHome={teamHome} linkRequest={linkRequest}usage={usage} upgrade={upgrade}// A Cloud's own cost stays off its paid plan's card (§1.3: it must never read as a second bill).extra={!ctx.advanced && !ctx.client && !(ctx.team && !ctx.admin) && (place.kind === "computer" || place.kind === "server") ? <SpentRow place={place.name} /> : undefined}diff --git a/src/components/settings/pages/AppPages.tsx b/src/components/settings/pages/AppPages.tsxindex e91923d4f7..66236555b8 100644--- a/src/components/settings/pages/AppPages.tsx+++ b/src/components/settings/pages/AppPages.tsx@@ -3,7 +3,7 @@ import { Plus } from "lucide-react";import { productName } from "@/lib/brand";import { FEEDBACK_URL, HELP_CENTER_URL, desktopAppVersion, openExternalLink } from "@/lib/app-links";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";+import { useStoreDispatch } from "@/state/store-select";import { AboutDialog } from "../../AboutDialog";import { AnalyticsRow } from "../../AnalyticsRow";import { ChatWidthRow, FontRow, SidebarToolsLayoutRow } from "../../AppearanceSelectRows";@@ -36,7 +36,7 @@ const elsewhere = (bridge: unknown, ctx: { desktop: boolean; here: boolean; homeexport function AppPage() {const { ctx } = useSettingsShell();- const { dispatch } = useStore();+ const dispatch = useStoreDispatch();const [about, setAbout] = useState(false);const desk = ctx.desktop && !ctx.client;const computer = useSwitchToComputer();diff --git a/src/components/settings/pages/PhonePage.tsx b/src/components/settings/pages/PhonePage.tsxindex 585019b936..ce4f684346 100644--- a/src/components/settings/pages/PhonePage.tsx+++ b/src/components/settings/pages/PhonePage.tsx@@ -1,7 +1,7 @@import { useState } from "react";import { ArrowUpRight } from "lucide-react";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { PhoneDevicesSection } from "../../PhoneDevicesSection";import { PlaceMark } from "../../PlacesRail";import { PlaceBadge } from "../SettingsNav";@@ -62,13 +62,12 @@ function OtherPlaces() {export function PhonePage() {const { ctx, place } = useSettingsShell();- const { state } = useStore();- const focus = state.appSettingsPhonePairing;+ const focus = useStoreSelector((state) => state.appSettingsPhonePairing), config = useStoreSelector((state) => state.config);return <>{ctx.here- ? <PhoneDevicesSection profileEmail={state.config?.profile?.email} focusRequest={focus} simple={!ctx.advanced} placeName={place.name} top={<PairWithCloud />} />- : <ServerPairingCard cloudHome={ctx.cloud} focusRequest={focus} team={state.config?.team?.name} placeName={place.name} simple={!ctx.advanced}- teamPhoneBlocked={state.config?.managedPolicy?.remoteAccess === false ? t("policy.teamRemoteBlocked", { organization: state.config.managedPolicy.organizationName }) : null} />}+ ? <PhoneDevicesSection profileEmail={config?.profile?.email} focusRequest={focus} simple={!ctx.advanced} placeName={place.name} top={<PairWithCloud />} />+ : <ServerPairingCard cloudHome={ctx.cloud} focusRequest={focus} team={config?.team?.name} placeName={place.name} simple={!ctx.advanced}+ teamPhoneBlocked={config?.managedPolicy?.remoteAccess === false ? t("policy.teamRemoteBlocked", { organization: config.managedPolicy.organizationName }) : null} />}<OtherPlaces /></>;}diff --git a/src/components/settings/pages/PlacePages.tsx b/src/components/settings/pages/PlacePages.tsxindex 9004e4d86e..c2236a7a42 100644--- a/src/components/settings/pages/PlacePages.tsx+++ b/src/components/settings/pages/PlacePages.tsx@@ -3,7 +3,7 @@ import { X } from "lucide-react";import { t } from "@/lib/i18n";import { productName } from "@/lib/brand";import { skillsLibraryEnabled } from "@/lib/feature-flags";-import { useStore } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { useTeamPeople } from "@/state/team-people";import { AdminOnly } from "../../AdminOnly";import { AutomaticRecoverySettings } from "../../AutomaticRecoverySettings";@@ -66,14 +66,13 @@ function useGroupedNote(): [boolean, () => void] {export function OverviewPage() {const { ctx, place, go } = useSettingsShell();- const { state, dispatch } = useStore();+ const team = useStoreSelector((state) => state.config?.team), dispatch = useStoreDispatch();+ const engines = useStoreSelector((state) => state.instances.filter((instance) => instance.snapshot.state === "available").length);const [note, dismiss] = useGroupedNote();const phone = usePhonePlaceState(!ctx.client);- const team = state.config?.team;const teamOwner = useTeamPeople()?.me?.role === "owner";const phoneValue = phone.kind === "paired" || phone.kind === "attention" ? t("settings.glance.phonePaired", { count: phone.count }): phone.kind === "none" ? t("settings.glance.notSetUp") : undefined;- const engines = state.instances.filter((instance) => instance.snapshot.state === "available").length;const apps = useConnectedAppCount();return <>{note && (@@ -151,8 +150,8 @@ export function AiPage() {export function BotsPage() {const { ctx } = useSettingsShell();- const { state } = useStore();- const paused = (state.config?.pausedBots?.length ?? 0) > 0;+ const config = useStoreSelector((state) => state.config);+ const paused = (config?.pausedBots?.length ?? 0) > 0;return <>{paused && <SettingsGroup block="awake"><SettingsRows><SettingRow title={t("settings.bots.awakeTitle")} subtitle={t("settings.bots.awakeLine")}><PausedBotsButton /></SettingRow></SettingsRows></SettingsGroup>}<SettingsGroup label={t("settings.bots.aboutYou")} block="about-you"@@ -173,7 +172,7 @@ export function BotsPage() {<div data-settings-block="keep-warm" className="contents"><CacheKeepWarmSettings /></div></SettingsRows></SettingsGroup></AdvancedSection>}- {skillsLibraryEnabled(state.config) && <div data-settings-block="skills"><SkillsSection /></div>}+ {skillsLibraryEnabled(config) && <div data-settings-block="skills"><SkillsSection /></div>}<AdvancedSection anchor="early"><div data-settings-block="early"><ExperimentalFeaturesRow /></div></AdvancedSection></>;}diff --git a/src/components/settings/phone-status.ts b/src/components/settings/phone-status.tsindex cf461571a7..2af618a98e 100644--- a/src/components/settings/phone-status.ts+++ b/src/components/settings/phone-status.ts@@ -1,5 +1,6 @@import { useEffect, useState } from "react";-import { api, useStore } from "@/state/store";+import { api } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { companionBridge } from "@/lib/companion-bridge";import { readMembership } from "@/lib/membership";import { isOwnerOrAdmin } from "@/lib/session";@@ -35,11 +36,10 @@ function serverPhoneState(): Promise<PhonePlaceState> {/** Phones paired with the place on screen, as the outer menu and the nav say it in a few words. */export function usePhonePlaceState(enabled = true): PhonePlaceState {- const { state } = useStore();+ const policy = useStoreSelector((state) => state.config?.managedPolicy);const here = companionBridge() !== null && window.ogb?.remoteClient?.active !== true;const local = useSidebarPhoneStatus();const [server, setServer] = useState<PhonePlaceState>({ kind: "checking" });- const policy = state.config?.managedPolicy;useEffect(() => {if (here || !enabled) return;let alive = true;diff --git a/src/components/settings/settings-context.ts b/src/components/settings/settings-context.tsindex c6912e6bdf..68fc4f5c20 100644--- a/src/components/settings/settings-context.ts+++ b/src/components/settings/settings-context.ts@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { appVersion } from "@/lib/app-links";import { pageIsThisComputer } from "@/lib/companion-bridge";import { skillsLibraryEnabled } from "@/lib/feature-flags";@@ -7,37 +7,31 @@ export { useSettingsPlace, type PlaceKind, type SettingsPlace } from "./settingsimport { useAdvancedMode } from "@/lib/interface-mode";import { railShown, usePlaces, type RailPlace } from "@/lib/places";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { workspacesAvailable } from "../WorkspacesSection";import type { SettingsContext } from "./settings-index";export function useSettingsContext(): SettingsContext {- const { state } = useStore();+ const config = useStoreSelector((state) => state.config);const advanced = useAdvancedMode();const admin = useOwnerOrAdmin() === true;const places = usePlaces();const known = useKnownPlaceCount();const ogb = typeof window === "undefined" ? undefined : window.ogb;const client = ogb?.remoteClient?.active === true;- const cloud = state.config?.cloudHome === true;- const team = Boolean(state.config?.team);+ const cloud = config?.cloudHome === true;+ const team = Boolean(config?.team);const desktop = Boolean(ogb);- return {- desktop,- here: pageIsThisComputer(),- home: pageIsThisComputer() || Boolean(ogb?.home),- cloud,- team,- client,- admin,- places: known > 1 || (!ogb?.environments && railShown(places)),- plan: desktop ? Boolean(ogb?.cloudAccount || (ogb?.cloudPlan && cloud)) : cloud && !team && admin,- organization: Boolean(ogb?.organization) && !client,- environments: Boolean(ogb?.environments),- installations: workspacesAvailable(state.config),- skills: skillsLibraryEnabled(state.config),- advanced,- };+ const here = pageIsThisComputer();+ const home = here || Boolean(ogb?.home);+ const placesShown = known > 1 || (!ogb?.environments && railShown(places));+ const plan = desktop ? Boolean(ogb?.cloudAccount || (ogb?.cloudPlan && cloud)) : cloud && !team && admin;+ const organization = Boolean(ogb?.organization) && !client;+ const environments = Boolean(ogb?.environments);+ const installations = workspacesAvailable(config);+ const skills = skillsLibraryEnabled(config);+ return useMemo(() => ({ desktop, here, home, cloud, team, client, admin, places: placesShown, plan, organization, environments, installations, skills, advanced }),+ [desktop, here, home, cloud, team, client, admin, placesShown, plan, organization, environments, installations, skills, advanced]);}/** How many places this app knows (a hidden rail's included), from main's environments list. */diff --git a/src/components/settings/settings-place.ts b/src/components/settings/settings-place.tsindex dd21393657..a050381c29 100644--- a/src/components/settings/settings-place.ts+++ b/src/components/settings/settings-place.ts@@ -1,6 +1,6 @@import { pageIsThisComputer } from "@/lib/companion-bridge";import { t } from "@/lib/i18n";-import { useStore } from "@/state/store";+import { useStoreSelector } from "@/state/store-select";import { useWindowPlace, windowPlaceName } from "../WindowPlaceTitle";export type PlaceKind = "computer" | "cloud" | "team" | "server";@@ -15,14 +15,14 @@ export interface SettingsPlace {/** The place on screen as Settings names it: the same name as the rail and the title bar, This computer by default. */export function useSettingsPlace(): SettingsPlace {- const { state } = useStore();+ const config = useStoreSelector((state) => state.config);const place = useWindowPlace();- const team = state.config?.team?.name;+ const team = config?.team?.name;if (pageIsThisComputer()) {const name = place ? windowPlaceName(place, undefined) : t("rail.thisComputer");return { name, kind: "computer", color: place?.color ?? null, named: Boolean(place?.profileName) };}- if (state.config?.cloudHome) {+ if (config?.cloudHome) {const name = place ? windowPlaceName(place, team) : team || t("cloudSetup.myCloud");return { name, kind: team ? "team" : "cloud", color: place?.color ?? null, named: true };}diff --git a/src/hooks/use-stable-callback.ts b/src/hooks/use-stable-callback.tsnew file mode 100644index 0000000000..e17c600fc4--- /dev/null+++ b/src/hooks/use-stable-callback.ts@@ -0,0 +1,9 @@+import { useCallback, useInsertionEffect, useRef } from "react";++/** One function for the component's whole life that calls the newest `callback`: a handler handed to a memoised child+ * that does not draw it again each time this component draws. Call it from events, never while rendering. */+export function useStableCallback<Args extends unknown[], Result>(callback: (...args: Args) => Result): (...args: Args) => Result {+ const latest = useRef(callback);+ useInsertionEffect(() => { latest.current = callback; });+ return useCallback((...args: Args) => latest.current(...args), []);+}diff --git a/src/lib/config-status-frame.ts b/src/lib/config-status-frame.tsindex 6ddc797d4e..a5d88e9f5b 100644--- a/src/lib/config-status-frame.ts+++ b/src/lib/config-status-frame.ts@@ -1,13 +1,26 @@import type { ConfigStatus } from "@/state/config-status";-// A section left out here is wiped from state.config whenever a config frame lands.+// A setting left out here is wiped from state.config whenever a config frame lands.export type ConfigStatusFrame = Pick<ConfigStatus,"awakeLimit" | "pausedBots" | "pausedByPerson" | "heldBots" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "xResearch" | "treg" | "postiz" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "everyBotRules" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team" | "workspaceBanner" | "toolGroups">;-export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus {+/** What the server says about the place itself. Its frames carry them as GET /api/config does, one left out meaning+ * unset (planTurns off Starter, routinesUnreadable once the routines read again); a frame with none of them (an older+ * server's) says nothing about them. */+const PLACE_FIELDS = ["computerName", "newBots", "signIn", "membership", "cloudStarter", "waitingForRoom", "planTurns", "decisions", "safetyFloor", "routinesUnreadable", "botLimit"];++function placeFields(frame: object, held: ConfigStatus | null | undefined): Partial<ConfigStatus> {+ const carried = PLACE_FIELDS.some((field) => field in frame);+ const source = (carried ? frame : held ?? {}) as Record<string, unknown>;+ return Object.fromEntries(PLACE_FIELDS.flatMap((field) => source[field] === undefined ? [] : [[field, source[field]]]));+}++/** `held`: the config the store holds now, which keeps the place fields a frame without them says nothing about. */+export function configStatusFromFrame(frame: ConfigStatusFrame, held?: ConfigStatus | null): ConfigStatus {return {+ ...placeFields(frame, held),xai: frame.xai,mistral: frame.mistral,cerebras: frame.cerebras,diff --git a/src/lib/department-filter.ts b/src/lib/department-filter.tsindex 3f21601d69..0b105ff595 100644--- a/src/lib/department-filter.ts+++ b/src/lib/department-filter.ts@@ -2,7 +2,7 @@ import type { Bot } from "@/state/store";export const GENERAL_DEPARTMENT = "\u0000general";-export function filterableDepartments(bots: readonly Bot[], order: readonly string[]): { names: string[]; hasGeneral: boolean } {+export function filterableDepartments(bots: readonly Pick<Bot, "hidden" | "section">[], order: readonly string[]): { names: string[]; hasGeneral: boolean } {const visible = bots.filter((bot) => !bot.hidden);const used = new Set(visible.map((bot) => bot.section).filter((name): name is string => Boolean(name)));return { names: order.filter((name) => used.has(name)), hasGeneral: visible.some((bot) => !bot.section) };diff --git a/src/lib/i18n.ts b/src/lib/i18n.tsindex fca6705107..2402ed8355 100644--- a/src/lib/i18n.ts+++ b/src/lib/i18n.ts@@ -35,8 +35,10 @@ export async function loadLocale(tag: string | undefined): Promise<string> {}function show(resolved: string): string {+ const changed = resolved !== active || (locales[resolved] ?? en) !== activePack;activePack = locales[resolved] ?? en;active = resolved;+ if (changed) for (const listener of localeListeners) listener();// Screen readers choose pronunciation from <html lang>, and index.html ships "en".const root = typeof document === "undefined" ? undefined : document?.documentElement;if (root) {@@ -64,6 +66,14 @@ export function activeLocale(): string {return active;}+const localeListeners = new Set<() => void>();++/** Calls `listener` each time the page shows another language; for useActiveLocale. */+export function subscribeLocale(listener: () => void): () => void {+ localeListeners.add(listener);+ return () => { localeListeners.delete(listener); };+}+export function intlLocale(system: string | undefined = globalThis.navigator?.language): string {const tag = documentLanguage(active);if (tag.includes("-") || !system) return tag;diff --git a/src/lib/minute-tick.test.ts b/src/lib/minute-tick.test.tsnew file mode 100644index 0000000000..99ee29871b--- /dev/null+++ b/src/lib/minute-tick.test.ts@@ -0,0 +1,60 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useMinuteTick } from "./minute-tick";++const { CalendarGrid } = await import("@/components/routines/CalendarGrid");++let root: Root | null = null;+const mount = (element: ReturnType<typeof createElement>) => {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root!.render(element));+ return container;+};+const advance = (ms: number) => flushSync(() => { vi.advanceTimersByTime(ms); });++beforeEach(() => { vi.useFakeTimers({ now: new Date(2026, 10, 20, 23, 58, 30) }); });+afterEach(() => {+ flushSync(() => root?.unmount());+ root = null;+ vi.useRealTimers();+});++describe("the minute tick", () => {+ it("draws its readers once as each minute turns, on one timer, and keeps no timer once none reads it", () => {+ const drawn: number[] = [];+ function Clock() { drawn.push(useMinuteTick()); return null; }+ function Two() { return [createElement(Clock, { key: "a" }), createElement(Clock, { key: "b" })]; }+ mount(createElement(Two));+ expect(drawn).toEqual([new Date(2026, 10, 20, 23, 58).getTime(), new Date(2026, 10, 20, 23, 58).getTime()]);+ expect(vi.getTimerCount()).toBe(1);+ advance(29_000);+ expect(drawn).toHaveLength(2);+ advance(1_001);+ expect(drawn.slice(2)).toEqual([new Date(2026, 10, 20, 23, 59).getTime(), new Date(2026, 10, 20, 23, 59).getTime()]);+ advance(59_000);+ expect(drawn).toHaveLength(4);+ advance(1_000);+ expect(drawn).toHaveLength(6);+ flushSync(() => root!.unmount());+ root = null;+ expect(vi.getTimerCount()).toBe(0);+ });++ it("moves the calendar's today and its now line across midnight with nothing else changing", () => {+ const day = new Date(2026, 10, 20).getTime(), next = new Date(2026, 10, 21).getTime();+ const container = mount(createElement(CalendarGrid, {+ anchor: day, days: 2, items: [], bots: [], groups: [], onOpen: vi.fn(), onCreate: vi.fn(), onMove: vi.fn(), onResize: vi.fn(),+ }));+ const today = () => [...container.querySelectorAll('[role="columnheader"]')].findIndex((header) => header.className.includes("bg-accent"));+ const nowLine = () => [...container.querySelectorAll('[role="gridcell"]')].findIndex((cell) => cell.querySelector(".bg-danger") !== null);+ expect([today(), nowLine()]).toEqual([0, 0]);+ advance(91_000);+ expect(Date.now()).toBeGreaterThanOrEqual(next);+ expect([today(), nowLine()]).toEqual([1, 1]);+ });+});diff --git a/src/lib/minute-tick.ts b/src/lib/minute-tick.tsnew file mode 100644index 0000000000..d9d06c3ed8--- /dev/null+++ b/src/lib/minute-tick.ts@@ -0,0 +1,45 @@+import { useSyncExternalStore } from "react";++const MINUTE_MS = 60_000;+const listeners = new Set<() => void>();+let minute = 0;+let timer: ReturnType<typeof setTimeout> | null = null;++function currentMinute(): number {+ return Math.floor(Date.now() / MINUTE_MS) * MINUTE_MS;+}++/** One timer for every reader, set for the start of the next minute, and only while something reads it. */+function schedule(): void {+ timer = setTimeout(() => {+ minute = currentMinute();+ for (const listener of listeners) listener();+ schedule();+ }, minute + MINUTE_MS - Date.now() + 1);+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ if (timer === null) {+ minute = currentMinute();+ schedule();+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0 && timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ };+}++/** With no reader the timer is off, so the minute is read from the clock. */+function snapshot(): number {+ return timer === null ? currentMinute() : minute;+}++/** The current minute's start: a component showing the time or a time relative to now draws again as each minute turns,+ * whatever else changes. */+export function useMinuteTick(): number {+ return useSyncExternalStore(subscribe, snapshot, snapshot);+}diff --git a/src/lib/use-active-locale.ts b/src/lib/use-active-locale.tsnew file mode 100644index 0000000000..4ca256b8f6--- /dev/null+++ b/src/lib/use-active-locale.ts@@ -0,0 +1,7 @@+import { useSyncExternalStore } from "react";+import { activeLocale, subscribeLocale } from "./i18n";++/** The language t() shows: a memoised component that reads it draws again in a new language, as App does. */+export function useActiveLocale(): string {+ return useSyncExternalStore(subscribeLocale, activeLocale, activeLocale);+}diff --git a/src/state/apart-from-turns.test.ts b/src/state/apart-from-turns.test.tsnew file mode 100644index 0000000000..7f8b3b3eef--- /dev/null+++ b/src/state/apart-from-turns.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { sameBotApartFromTurns, sameBotsApartFromTurns, sameGroupsApartFromTurns } from "./apart-from-turns";+import { initialState, reducer, type Bot, type Group, type Message } from "./store";++const bot = (id: string, patch: Partial<Bot> = {}): Bot => ({+ id, threadId: `${id}-thread`, name: id, title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "test", model: "m" }, messages: [], tasks: [{ threadId: `${id}-thread`, title: "Chat", createdAt: 1 }], ...patch,+} as Bot);+const room = (patch: Partial<Group> = {}): Group => ({+ id: "room", threadId: "room-thread", name: "Planning", memberIds: ["a"], defaultResponder: { kind: "member", botId: "a" },+ bulletin: "", unread: false, createdAt: 1, messages: [], ...patch,+} as Group);++describe("a bot list kept across turns", () => {+ it("is the same through a turn: a message, busy, unread and the thread stamps", () => {+ const before = { ...initialState, bots: [bot("a"), bot("b")] };+ const message = { id: "m1", role: "bot", kind: "text", text: "hi", at: 5 } as Message;+ const added = reducer(before, { type: "messageAdded", threadId: "b-thread", message });+ const busy = reducer(added, { type: "botPatched", bot: { ...bot("b"), busy: true, activity: "working", unread: true, tasks: [{ threadId: "b-thread", title: "Chat", createdAt: 1, updatedAt: 5 }] } });+ expect(busy.bots).not.toBe(before.bots);+ expect(sameBotsApartFromTurns(before.bots, added.bots)).toBe(true);+ expect(sameBotsApartFromTurns(before.bots, busy.bots)).toBe(true);+ });++ it("differs when anything a reader draws changes, even in a new object of the same shape", () => {+ const bots = [bot("a"), bot("b")];+ expect(sameBotsApartFromTurns(bots, [bot("a"), bot("b")])).toBe(true);+ expect(sameBotsApartFromTurns(bots, [bot("a"), bot("b", { name: "Bea" })])).toBe(false);+ expect(sameBotsApartFromTurns(bots, [bot("a"), bot("b", { modelSelection: { instanceId: "test", model: "n" } })])).toBe(false);+ expect(sameBotsApartFromTurns(bots, [bot("a"), bot("b", { section: "Sales" })])).toBe(false);+ expect(sameBotsApartFromTurns(bots, [bot("b"), bot("a")]), "order").toBe(false);+ expect(sameBotsApartFromTurns(bots, [bot("a")]), "a bot gone").toBe(false);+ });++ it("compares one bot the same way, and an absent one only with an absent one", () => {+ expect(sameBotApartFromTurns(bot("a"), bot("a", { busy: true, messages: [{ id: "x" } as Message] }))).toBe(true);+ expect(sameBotApartFromTurns(bot("a"), bot("a", { color: "blue" }))).toBe(false);+ expect(sameBotApartFromTurns(undefined, undefined)).toBe(true);+ expect(sameBotApartFromTurns(bot("a"), undefined)).toBe(false);+ });++ it("keeps a room list through a room's turn, not through a rename", () => {+ expect(sameGroupsApartFromTurns([room()], [room({ messages: [{ id: "x" } as Message], unread: true, busyBotId: "a", working: true })])).toBe(true);+ expect(sameGroupsApartFromTurns([room()], [room({ name: "Review" })])).toBe(false);+ });+});diff --git a/src/state/apart-from-turns.ts b/src/state/apart-from-turns.tsnew file mode 100644index 0000000000..9c41cfd368--- /dev/null+++ b/src/state/apart-from-turns.ts@@ -0,0 +1,55 @@+import type { Bot, Group } from "./store";+import { sameJson } from "./same-json";+import { useStoreSelector } from "./store-select";++const BOT_TURN_FIELDS = [+ "messages", "activeLeafId", "hasMore", "awaitingThreadSnapshot", "switchingTo",+ "busy", "activity", "turnStartedAt", "waitingForTeammates", "unread", "tasks",+] as const satisfies readonly (keyof Bot)[];+const GROUP_TURN_FIELDS = [+ "messages", "hasMore", "unread", "lastReadMessageId", "busyBotId", "working", "turnStartedAt", "tasks", "usage", "queue", "holds", "heldMessages",+] as const satisfies readonly (keyof Group)[];++/** A bot as a reader sees it that never shows its conversation, threads, busy or unread state. */+export type BotApartFromTurns = Omit<Bot, (typeof BOT_TURN_FIELDS)[number]>;+export type GroupApartFromTurns = Omit<Group, (typeof GROUP_TURN_FIELDS)[number]>;++const botTurnFields: ReadonlySet<string> = new Set(BOT_TURN_FIELDS);+const groupTurnFields: ReadonlySet<string> = new Set(GROUP_TURN_FIELDS);++function sameApartFrom(a: object, b: object, skip: ReadonlySet<string>): boolean {+ const left = a as Record<string, unknown>, right = b as Record<string, unknown>;+ for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) {+ if (!skip.has(key) && !sameJson(left[key], right[key])) return false;+ }+ return true;+}++function sameListApartFrom<T extends object>(a: readonly T[], b: readonly T[], skip: ReadonlySet<string>): boolean {+ return a === b || (a.length === b.length && a.every((item, index) => item === b[index] || sameApartFrom(item, b[index]!, skip)));+}++export function sameBotsApartFromTurns(a: readonly Bot[], b: readonly Bot[]): boolean {+ return sameListApartFrom(a, b, botTurnFields);+}++export function sameBotApartFromTurns(a: Bot | undefined, b: Bot | undefined): boolean {+ return a === b || (a !== undefined && b !== undefined && sameApartFrom(a, b, botTurnFields));+}++export function sameGroupsApartFromTurns(a: readonly Group[], b: readonly Group[]): boolean {+ return sameListApartFrom(a, b, groupTurnFields);+}++/** The bot list kept across turns: a turn changes nothing these readers draw, so it draws them nothing. */+export function useBotsApartFromTurns(): readonly BotApartFromTurns[] {+ return useStoreSelector((state) => state.bots, sameBotsApartFromTurns);+}++export function useGroupsApartFromTurns(): readonly GroupApartFromTurns[] {+ return useStoreSelector((state) => state.groups, sameGroupsApartFromTurns);+}++export function useBotApartFromTurns(pick: (bots: readonly Bot[]) => Bot | undefined): BotApartFromTurns | undefined {+ return useStoreSelector((state) => pick(state.bots), sameBotApartFromTurns);+}diff --git a/src/state/config-change-count.test.ts b/src/state/config-change-count.test.tsindex 67b13a8474..656193456d 100644--- a/src/state/config-change-count.test.ts+++ b/src/state/config-change-count.test.ts@@ -17,8 +17,8 @@ class FixtureEventSource {send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }}-/** What a config frame carries into the store. */-const framed = (savedSteps: boolean) => ({+/** What the server says about each setting. */+const settingsOf = (savedSteps: boolean) => ({xai: { configured: false }, anthropic: { configured: true, everyClaudeBot: true }, openai: { configured: false },composio: { configured: false, mode: "hosted" }, box: { configured: false }, vps: { configured: false, sshAlias: "" },rooms: { turnTimeoutMinutes: 10 }, mcp: { callTimeoutMinutes: 5 }, threads: { maxConcurrentPerBot: 3 },@@ -29,9 +29,9 @@ const framed = (savedSteps: boolean) => ({edition: { edition: "community", features: [] }, browserProfiles: [{ id: "work", name: "Work" }],budgets: {}, billing: { currency: "USD", prices: {} }, pausedBots: [], heldBots: [],});-/** What GET and PATCH /api/config answer: the same, and the sections a frame leaves out. */+/** What GET and PATCH /api/config answer and a config frame carries: the settings and what it says about the place. */const answered = (savedSteps: boolean) => ({- ...framed(savedSteps), computerName: "Studio", newBots: {}, signIn: { admins: [], members: [] },+ ...settingsOf(savedSteps), computerName: "Studio", newBots: {}, signIn: { admins: [], members: [] },membership: { authority: "local", pairingCodes: true }, decisions: { retentionDays: 30 }, safetyFloor: { enabled: true },});const INSTANCES = [{ instanceId: "codex", driverKind: "codex", displayName: "Codex", enabled: true, snapshot: { state: "available", authenticated: true, models: [{ id: "m", name: "M" }] } }];@@ -113,32 +113,37 @@ describe("a switched setting reaches the store's readers", () => {expect(seen).toBe(held);});- it("draws once for the frame and once for the answer, and not again for the same engine list", async () => {+ it("draws once for a switch: the frame, then nothing for the answer that says the same, nor for the same engine list", async () => {config = answered(true);- const counted = await flip(framed(true), answered(true));+ const counted = await flip(answered(true), answered(true));expect(seen.config).toEqual(answered(true));- expect(counted).toBe(2);+ expect(counted).toBe(1);});- it("draws once for a frame that repeats the answer, as it drops the sections a frame leaves out", async () => {- const before = renders, reads = instanceReads;- configFrame(framed(true));+ it("draws nothing for a frame from an older server that leaves out what it says about the place", async () => {+ const before = renders, held = seen, reads = instanceReads;+ configFrame(settingsOf(true));await paint();expect(instanceReads).toBe(reads + 1);- expect(seen.config).toEqual(framed(true));- expect(renders - before).toBe(1);+ expect(seen.config).toEqual(answered(true));+ expect(renders - before).toBe(0);+ expect(seen).toBe(held);});- it("draws once when the answer says no more than the frame did", async () => {- config = framed(false);- const counted = await flip(framed(false), framed(false));+ it("draws once when the answer comes before the frame", async () => {+ config = answered(false);+ const before = renders;+ flushSync(() => dispatch({ type: "configStatus", config: structuredClone(answered(false)) as unknown as ConfigStatus }));+ await paint();+ configFrame(answered(false));+ await paint();expect(seen.config?.features?.savedSteps).toBe(false);- expect(counted).toBe(1);+ expect(renders - before).toBe(1);});it("draws nothing for a config frame that repeats the last one, nor for the engine list read after it", async () => {const before = renders, held = seen, reads = instanceReads;- configFrame(framed(false));+ configFrame(answered(false));await paint();expect(instanceReads).toBe(reads + 1);expect(renders - before).toBe(0);@@ -148,7 +153,7 @@ describe("a switched setting reaches the store's readers", () => {it("still takes a changed engine list", async () => {const before = renders;INSTANCES[0]!.snapshot.models.push({ id: "n", name: "N" });- configFrame(framed(false));+ configFrame(answered(false));await paint();expect(seen.instances).toEqual(INSTANCES);expect(renders - before).toBe(1);diff --git a/src/state/config-frame-fields.test.ts b/src/state/config-frame-fields.test.tsnew file mode 100644index 0000000000..7489665e61--- /dev/null+++ b/src/state/config-frame-fields.test.ts@@ -0,0 +1,122 @@+// @vitest-environment happy-dom+// The real provider and its live stream: a config frame leaves the store holding what the server last said about each+// setting, whichever of GET, a PATCH answer or the frame said it.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { Action, AppState, ConfigStatus } from "./store";++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }+}++const settings = {+ xai: { configured: false }, anthropic: { configured: true }, composio: { configured: false }, box: { configured: false },+ vps: { configured: false, sshAlias: "" }, rooms: { turnTimeoutMinutes: 10 }, mcp: { callTimeoutMinutes: 5 }, threads: { maxConcurrentPerBot: 1 },+ localVm: { mode: "shared", maxInstances: 1 }, profile: { name: "Ada", email: "[email protected]", aboutMe: "" }, language: "",+ features: { showToolCalls: false }, edition: { edition: "community", features: [] }, browserProfiles: [], budgets: {},+ billing: { currency: "USD", prices: {} }, pausedBots: [], heldBots: [],+};+/** What the server says about the place itself; GET /api/config, a PATCH answer and a config frame all carry it. */+const place = {+ computerName: "Studio", newBots: { effort: "high" }, signIn: { admins: ["[email protected]"], members: [] },+ membership: { authority: "local", pairingCodes: true }, cloudStarter: true, waitingForRoom: true,+ planTurns: { running: 1, waiting: 2, refusedAt: 5, refused: "tasks" }, decisions: { retentionDays: 30 }, safetyFloor: { enabled: true },+ routinesUnreadable: true, botLimit: 3,+};+const FIELDS = Object.keys(place) as Array<keyof typeof place>;++const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));+const { StoreProvider, useStore } = await import("./store");++let seen!: AppState;+let dispatch!: (action: Action) => void;+function Probe() {+ ({ state: seen, dispatch } = useStore());+ return null;+}+let root: Root;+let cursor = 0;+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 10; i++) await task(); };+const paints: FrameRequestCallback[] = [];+const paint = async () => {+ for (const callback of paints.splice(0)) callback(performance.now());+ await settle();+};+const configFrame = async (body: object) => {+ FixtureEventSource.opened[0]!.send({ kind: "config", ...body, seq: ++cursor }, `run:${cursor}`);+ await paint();+};+const held = () => Object.fromEntries(FIELDS.map((field) => [field, (seen.config as Record<string, unknown> | null)?.[field]]));++beforeAll(async () => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => paints.push(callback));+ vi.stubGlobal("cancelAnimationFrame", () => {});+ vi.stubGlobal("fetch", (input: string) => {+ const path = String(input).replace(/\?.*$/, "");+ if (path === "/api/config") return json({ ...settings, ...place });+ if (path === "/api/bots") return json({ bots: [], groups: [] });+ if (path === "/api/routines") return json({ routines: [], runs: [] });+ if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });+ return json({});+ });+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ await settle();+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ await paint();+});+afterAll(() => {+ root.unmount();+ vi.unstubAllGlobals();+});++describe("a config frame", () => {+ it("starts from what GET /api/config answered", () => {+ expect(held()).toEqual(place);+ });++ it("keeps each of them when the frame says the same, as the server's frames do", async () => {+ await configFrame({ ...settings, ...place });+ expect(held()).toEqual(place);+ });++ it("takes a new value the frame carries", async () => {+ await configFrame({ ...settings, ...place, computerName: "Desk", waitingForRoom: false, newBots: {} });+ expect(held()).toEqual({ ...place, computerName: "Desk", waitingForRoom: false, newBots: {} });+ });++ it("keeps what the last answer said when a frame carries none of them, as an older server's do", async () => {+ flushSync(() => dispatch({ type: "configStatus", config: { ...settings, ...place } as unknown as ConfigStatus }));+ await configFrame(settings);+ expect(held()).toEqual(place);+ });++ it("drops the routines alert once a frame no longer carries it, as GET would", async () => {+ flushSync(() => dispatch({ type: "configStatus", config: { ...settings, ...place } as unknown as ConfigStatus }));+ const { routinesUnreadable: _unreadable, ...readable } = place;+ await configFrame({ ...settings, ...readable });+ expect(seen.config?.routinesUnreadable).toBeUndefined();+ expect(seen.config?.botLimit).toBe(3);+ });++ it("drops the Starter turns once a frame no longer carries them, as GET would", async () => {+ flushSync(() => dispatch({ type: "configStatus", config: { ...settings, ...place } as unknown as ConfigStatus }));+ const { planTurns: _planTurns, ...offStarter } = place;+ await configFrame({ ...settings, ...offStarter, cloudStarter: false });+ expect(seen.config?.planTurns).toBeUndefined();+ expect(seen.config?.cloudStarter).toBe(false);+ });+});diff --git a/src/state/store.tsx b/src/state/store.tsxindex 90efe8b7b5..6c23f55042 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -3184,7 +3184,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {case "config": forgetSharedSession();rawDispatch({type: "configStatus",- config: configStatusFromFrame(frame as unknown as ConfigStatusFrame),+ config: configStatusFromFrame(frame as unknown as ConfigStatusFrame, store.getState().config),});{const instances = partByKey.get("instances");diff --git a/src/state/use-show-instances.ts b/src/state/use-show-instances.tsindex 650e2f63f0..5feacba189 100644--- a/src/state/use-show-instances.ts+++ b/src/state/use-show-instances.ts@@ -1,9 +1,10 @@import { useCallback } from "react";-import { useStore, type InstanceInfo } from "./store";+import type { InstanceInfo } from "./store";+import { useStoreActions, useStoreDispatch } from "./store-select";export function useShowInstances() {- const { dispatch, refreshInstances } = useStore();+ const dispatch = useStoreDispatch(), { refreshInstances } = useStoreActions();return useCallback(async (answer: unknown) => {const instances = (answer as { instances?: unknown } | undefined)?.instances;if (Array.isArray(instances)) dispatch({ type: "instances", instances: instances as InstanceInfo[] });