Skip to content

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

perf batches 12-14: lazyScreen for the new chunks, statement cache guard, settle outside-lineage hand-offs

milind-soni665f06f63fae
diff --git a/server/message-db.test.ts b/server/message-db.test.ts
index 09b0313457..cacca9648c 100644
--- a/server/message-db.test.ts
+++ b/server/message-db.test.ts
@@ -23,6 +23,7 @@ import { closeMessageDb,
latestSaidByBot,
markNotificationLogRead,
prepared,
+ readMessage,
readMessageText,
recentMessages,
recentNotificationLog,
@@ -721,4 +722,37 @@ describe("SQLite cache and prepared statement reuse", () => {
closeMessageDb();
expect(prepared("SELECT 1 AS n") === first).toBe(false);
});
+
+ it("reads and writes through its cached statements again after the database is closed and reopened", () => {
+ insertMessage("t-cache", msg("m1", "before close"));
+ expect(readMessage("t-cache", "m1")?.text).toBe("before close");
+ const cached = prepared("SELECT json FROM messages WHERE thread_id = ? AND id = ?");
+ closeMessageDb();
+ // The closed database's statement is finalized with it, and none of the cached functions reach for it.
+ expect(() => cached.get("t-cache", "m1")).toThrow();
+ expect(readMessage("t-cache", "m1")?.text).toBe("before close");
+ insertMessage("t-cache", msg("m2", "after reopen"));
+ updateMessage("t-cache", msg("m2", "after reopen, edited"));
+ expect(readMessage("t-cache", "m2")?.text).toBe("after reopen, edited");
+ expect(prepared("SELECT json FROM messages WHERE thread_id = ? AND id = ?") === cached).toBe(false);
+ });
+
+ // Windows will not delete a file SQLite holds open.
+ it.skipIf(process.platform === "win32")("prepares afresh on the new database when db() opens again because its file went", () => {
+ const now = Date.now();
+ const clock = vi.spyOn(Date, "now").mockReturnValue(now);
+ try {
+ insertMessage("t-moved", msg("m1", "on the old file"));
+ const cached = prepared("SELECT json FROM messages WHERE thread_id = ? AND id = ?");
+ expect(readMessage("t-moved", "m1")).not.toBeNull();
+ for (const suffix of ["", "-wal", "-shm"]) rmSync(join(DATA_DIR, `messages.db${suffix}`), { force: true });
+ clock.mockReturnValue(now + 1_000);
+ expect(readMessage("t-moved", "m1")).toBeNull();
+ expect(prepared("SELECT json FROM messages WHERE thread_id = ? AND id = ?") === cached).toBe(false);
+ insertMessage("t-moved", msg("m2", "on the new file"));
+ expect(readMessage("t-moved", "m2")?.text).toBe("on the new file");
+ } finally {
+ clock.mockRestore();
+ }
+ });
});
diff --git a/server/message-db.ts b/server/message-db.ts
index 6656139104..9368ebcbb7 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -159,8 +159,10 @@ function db(): DatabaseSync {
return handle;
}
-/** One prepared statement per SQL text for the life of the open database. */
+/** One prepared statement per SQL text for the life of the open database. A connection db() has since replaced (its file
+ * went, or the data folder moved) prepares its own, uncached: a cached one would run on the other database. */
function preparedOn(database: DatabaseSync, sql: string): StatementSync {
+ if (database !== handle) return database.prepare(sql);
let statement = statements.get(sql);
if (!statement) statements.set(sql, statement = database.prepare(sql));
return statement;
diff --git a/server/outside-lineage.e2e.test.ts b/server/outside-lineage.e2e.test.ts
index dd94ae24ad..2dc6960d68 100644
--- a/server/outside-lineage.e2e.test.ts
+++ b/server/outside-lineage.e2e.test.ts
@@ -30,7 +30,11 @@ async function until<V>(what: string, fn: () => Promise<V> | V, ms = hostTimeout
}
}
const said = (marker: string, where: "prompt" | "systemPrompt" = "prompt") => { const turn = read(); return turn && JSON.stringify(turn[where] ?? "").includes(marker) ? turn : null; };
-const turnWith = (marker: string, where: "prompt" | "systemPrompt" = "prompt") => until(`a turn with ${marker}`, () => said(marker, where));
+// A timeout names the turn the dump last held, so a turn that came in over this one can be told from one that never started.
+const turnWith = (marker: string, where: "prompt" | "systemPrompt" = "prompt") => until(`a turn with ${marker}`, () => said(marker, where)).catch((error: Error) => {
+ const last = read();
+ throw new Error(`${error.message}; the dump last held ${last ? `pid ${last.pid}: ...${JSON.stringify(last.prompt ?? "").slice(-300)}` : "nothing"}`);
+});
const confined = (turn: { argv: string[] }) => turn.argv.includes("--restricted");
const skillNamed = (name: string) => ({ name, description: "Write the digest.", source: "local:test", enabled: true, text: `---\nname: ${name}\ndescription: Write the digest.\n---\n\nWrite the digest.\n` });
const atFull = (turn: { argv: string[] }) => turn.argv[turn.argv.indexOf("--permission-mode") + 1] === "bypassPermissions";
@@ -313,6 +317,10 @@ describe("a Team Cloud", () => {
const named = await internal(chief.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "line-as-answer", answers: handed.body.receipts[0].requestId });
expect(named.body.receipts[0].outcome).toBe("failed");
expect(JSON.stringify(await linesOf(work))).not.toContain("line-as-answer");
+ // This hand-off answers back: once Fold mate stops, the report on it starts Fold chief's next turn a hand-off tick
+ // later, past finish's idle check on a slow runner, and that turn's dump would replace the next test's.
+ writeFileSync(release, "");
+ await turnWith(`report on assignment ${handed.body.receipts[0].requestId}`);
await finish(chief.id, mate.id);
}, hostTimeout(120_000));
@@ -600,6 +608,7 @@ describe("a personal Cloud someone else has used", () => {
expect(JSON.stringify((await cloud("GET", `/api/threads/${work}/messages`)).body.messages)).not.toContain("line-for-owner-work");
writeFileSync(release, "");
+ await turnWith(`report on assignment ${handed.body.receipts[0].requestId}`);
await sleep(2_000);
rmSync(release, { force: true });
rmSync(dump, { force: true });
diff --git a/src/components/GroupCallView.tsx b/src/components/GroupCallView.tsx
index 1cc8a92736..203f11ed41 100644
--- a/src/components/GroupCallView.tsx
+++ b/src/components/GroupCallView.tsx
@@ -1,4 +1,3 @@
-import { lazy, Suspense } from "react";
import { useOnCall } from "@/lib/call";
import { track } from "@/lib/analytics";
import type { Bot, Group } from "@/state/store";
@@ -6,7 +5,7 @@ import { CallTargetButton, type CallButtonPlacement } from "./CallView";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useDesktopCapabilities } from "./DesktopCapabilities";
-const GroupCall = lazy(() => import("./GroupCallBody"));
+import { GroupCall } from "./lazy-views";
/** `fill` (Simple composer): a round button in that colour, with its glyph in `ink`. */
export function GroupCallButton({ group, members, placement, fill, ink }: { group: Group; members: Bot[]; placement?: CallButtonPlacement; fill?: string; ink?: string }) {
@@ -37,9 +36,5 @@ export function RoomHeaderCallButton({ group, members }: { group: Group; members
export function GroupCallOverlay({ group, members }: { group: Group; members: Bot[] }) {
const active = useOnCall() === group.id;
if (!active) return null;
- return (
- <Suspense fallback={null}>
- <GroupCall group={group} members={members} />
- </Suspense>
- );
+ return <GroupCall group={group} members={members} />;
}
diff --git a/src/components/GroupView.auto.test.ts b/src/components/GroupView.auto.test.ts
index 6035350434..d27f16f4c6 100644
--- a/src/components/GroupView.auto.test.ts
+++ b/src/components/GroupView.auto.test.ts
@@ -9,6 +9,12 @@ vi.mock("@/state/store", async (original) => ({
...await original<typeof import("@/state/store")>(),
useStore: () => ({ state: { config: fixture.config }, dispatch: fixture.dispatch }),
}));
+// The selector reads the same fixture, so a component can still be called as a plain function below.
+vi.mock("@/state/store-select", async (original) => ({
+ ...await original<typeof import("@/state/store-select")>(),
+ useStoreSelector: <T,>(select: (state: { config: ConfigStatus | null }) => T) => select({ config: fixture.config }),
+ useStoreDispatch: () => fixture.dispatch,
+}));
vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({}) }));
import { Transcript } from "./GroupView";
diff --git a/src/components/SearchResults.tsx b/src/components/SearchResults.tsx
index 7a519c7989..211173aed4 100644
--- a/src/components/SearchResults.tsx
+++ b/src/components/SearchResults.tsx
@@ -5,12 +5,11 @@ import { useStoreRef } from "@/state/store-ref";
import { useStoreSelector } from "@/state/store-select";
import { BotAvatar } from "./Avatar";
import { cn } from "@/lib/cn";
-import type { SearchHit } from "@/lib/search-hit";
+import { MIN_QUERY, type SearchHit } from "@/lib/search-hit";
import { landOnSearchHit } from "@/lib/focus-message";
import { useShowThreads } from "@/lib/thread-preferences";
import { t } from "@/lib/i18n";
-export const MIN_QUERY = 2;
const DEBOUNCE_MS = 250;
export function SearchResults({ query, onLanded }: { query: string; onLanded: () => void }) {
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index e921bf4290..1c1494bb10 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -1,5 +1,5 @@
import { OrganizationIdentity } from "./OrganizationIdentity";
-import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";
import { createPortal } from "react-dom";
import { Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderInput, FolderPlus, LayoutTemplate, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, Plus, Search, SquarePen, TextQuote, Trash2, Users, X } from "lucide-react";
import { botPendingQueued, botRoutineRuns, sameBotRowProps, sidebarState } from "./sidebar-state"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";
@@ -28,7 +28,7 @@ import { RoomMark, StackedMauses } from "./StackedMauses";
import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";
import { nextRename } from "@/lib/rename";
import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";
-const MIN_QUERY = 2; const SearchResults = lazy(() => import("./SearchResults").then((m) => ({ default: m.SearchResults })));
+import { MIN_QUERY } from "@/lib/search-hit";
import { ImportDialog, ShareTemplateDialog, TeamDialog, TeamLibraryPanel, TeamSettingsDialog } from "./lazy-screens";
import { SidebarNewChatPanel } from "./SidebarNewChatPanel";
import { openCommandPalette } from "./CommandPalette";
@@ -104,7 +104,7 @@ import { myDefaultBot, useViewerEmail, useWelcomingBot } from "@/lib/default-bot
import { PinnedBotRoster, PinnedCircleThreadSection } from "./PinnedCircleThreads";
import { archiveBotWithNotice, onArchiveNotice, type ArchiveNotice } from "./bot-archive";
import { ArchivedBotsPanel, botConfirmProps, type BotConfirmKind } from "./ArchivedBotsPanel"; import { MovedBotRows } from "./MoveToTeam"; import { MovedToMyCloudRow } from "./MoveToMyCloud";
-const NewRoomPanel = lazy(() => import("./SidebarNewRoomPanel").then((m) => ({ default: m.NewRoomPanel })));
+import { NewRoomPanel, SearchResults } from "./lazy-views";
import { SectionPicker } from "./SidebarSectionPicker";
export { PinnedBotCircle, PinnedCircleThreadPanel, PinnedCircleThreadSection } from "./PinnedCircleThreads";
@@ -1454,7 +1454,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
</div>
);
})}
- <OtherPlaceLine query={query} icons={density === "icons"} /><PlacedBotMenuHost /><MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} />{query.trim().length >= MIN_QUERY && <Suspense fallback={null}><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} /></Suspense>}
+ <OtherPlaceLine query={query} icons={density === "icons"} /><PlacedBotMenuHost /><MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} />{query.trim().length >= MIN_QUERY && <SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} />}
{showPinnedCircleThreads && (
<PinnedCircleThreadSection
bots={pinnedBots}
@@ -1581,7 +1581,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
dispatch({ type: "patchGroup", groupId: roomSectionPicker.groupId, patch: { section } });
}}
/>
- {newRoom && <Suspense fallback={null}><NewRoomPanel onClose={() => setNewRoom(false)} /></Suspense>}
+ {newRoom && <NewRoomPanel onClose={() => setNewRoom(false)} />}
{/* Portaled: below md the sidebar's translate makes it the containing block for fixed children. */}
{newChatOpen && createPortal(
<SidebarNewChatPanel
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index d26ae83211..104a803960 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -1,4 +1,4 @@
-import { lazy, Suspense, useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import {
ArrowUpRight,
Archive,
@@ -35,8 +35,7 @@ import { usePhonePlaceState, type PhonePlaceState } from "./settings/phone-statu
import { useSettingsPlace } from "./settings/settings-place";
import { AccountMoveStatus, useAccountMove, type AccountMoveKind } from "./AccountMove";
import { InitialsAvatar } from "./Avatar";
-const SignOutConfirm = lazy(() => import("./settings/SignOutConfirm").then((m) => ({ default: m.SignOutConfirm })));
-const AboutDialog = lazy(() => import("./AboutDialog").then((m) => ({ default: m.AboutDialog })));
+import { AboutDialog, SignOutConfirm } from "./lazy-views";
import { CloudTile } from "./cloud-buy/parts";
import { usageBridge } from "./CloudUsageMeter";
import { useCloudPlanSnapshot } from "./CloudTrialNotice";
@@ -710,12 +709,12 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
</span>
)}
/>
- {aboutOpen && <Suspense fallback={null}><AboutDialog open onClose={() => setAboutOpen(false)} /></Suspense>}
- {signingOut && <Suspense fallback={null}><SignOutConfirm browser={signingOut === "browser"} here={signingOut === "browser" ? place.name : t("rail.thisComputer")}
+ {aboutOpen && <AboutDialog open onClose={() => setAboutOpen(false)} />}
+ {signingOut && <SignOutConfirm browser={signingOut === "browser"} here={signingOut === "browser" ? place.name : t("rail.thisComputer")}
cloud={signingOut === "desktop" && summary.plan ? t("cloudSetup.myCloud") : null} onClose={() => setSigningOut(null)}
onConfirm={() => signingOut === "browser"
? api("/api/auth/logout", { method: "POST" }).finally(() => location.reload())
- : window.ogb?.cloudAccount?.signOut()} /></Suspense>}
+ : window.ogb?.cloudAccount?.signOut()} />}
{accounts.sheet && <AccountsSheet adding={accounts.sheet.email} note={accounts.sheet.note} onClose={accounts.closeSheet} />}
</>
);
diff --git a/src/components/ThreadRefs.dom.test.ts b/src/components/ThreadRefs.dom.test.ts
new file mode 100644
index 0000000000..ab653cfddf
--- /dev/null
+++ b/src/components/ThreadRefs.dom.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment happy-dom
+// ThreadRefsProvider selects its threads by their signature: what a #Title link reads must follow every change to a
+// title, a name or the open bot, and nothing else may hand the message rows a new value.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createAppStore } from "@/state/app-store";
+import { initialState, reducer, type Action, type AppState, type Bot, type Group } from "@/state/store";
+import { StoreSourceContext, type StoreSource } from "@/state/store-context";
+import { ThreadRefsProvider, useThreadRefs, type ThreadRefsValue } from "./ThreadRefs";
+
+const bot = (id: string, name: string, tasks: Bot["tasks"]): Bot => ({
+ id, threadId: tasks?.[0]?.threadId ?? id, name, title: "", description: "", notifications: true,
+ color: "green", unread: false, messages: [], modelSelection: { instanceId: "fake", model: "test" }, tasks,
+});
+const scout = bot("scout", "Scout", [{ threadId: "scout-main", title: "Main", createdAt: 1 }, { threadId: "qa", title: "QA PR 245", createdAt: 2 }]);
+const ada = bot("ada", "Ada", [{ threadId: "ada-main", title: "Main", createdAt: 3 }]);
+const room: Group = {
+ id: "standup", threadId: "standup-1", name: "Standup", memberIds: ["scout"], defaultResponder: { kind: "everyone" },
+ bulletin: "", unread: false, createdAt: 1, messages: [], tasks: [{ threadId: "standup-1", title: "Monday plan", createdAt: 4 }],
+};
+
+let root: Root | null = null;
+afterEach(() => { flushSync(() => root?.unmount()); root = null; });
+
+function mounted() {
+ const store = createAppStore<AppState, Action, never>(reducer, { ...initialState, bots: [scout, ada], groups: [room], selectedId: "scout" },
+ (flush) => { flush(); return () => {}; });
+ const source: StoreSource = { getState: store.getState, subscribe: store.subscribe, dispatch: store.dispatch,
+ flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() };
+ const seen: ThreadRefsValue[] = [];
+ function Reader() {
+ seen.push(useThreadRefs());
+ return null;
+ }
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root!.render(createElement(StoreSourceContext, { value: source }, createElement(ThreadRefsProvider, null, createElement(Reader)))));
+ const latest = () => seen.at(-1)!;
+ const titles = () => latest().threads.map((ref) => `${ref.botName}: ${ref.title}`);
+ return { store, seen, latest, titles, act: (action: Action) => flushSync(() => store.dispatch(action)) };
+}
+
+describe("ThreadRefsProvider", () => {
+ it("follows a renamed thread, a renamed bot or room, a new thread and the open bot", () => {
+ const view = mounted();
+ expect(view.titles()).toEqual(["Scout: Main", "Scout: QA PR 245", "Ada: Main", "Standup: Monday plan"]);
+ expect(view.latest().currentBotId).toBe("scout");
+
+ view.act({ type: "botPatched", bot: { ...scout, tasks: [scout.tasks![0]!, { threadId: "qa", title: "QA PR 246", createdAt: 2 }] } });
+ expect(view.titles()).toContain("Scout: QA PR 246");
+
+ view.act({ type: "botPatched", bot: { ...ada, name: "Ada Lovelace" } });
+ expect(view.titles()).toContain("Ada Lovelace: Main");
+
+ view.act({ type: "botPatched", bot: { ...ada, name: "Ada Lovelace", tasks: [...ada.tasks!, { threadId: "ada-new", title: "Fresh", createdAt: 9 }] } });
+ expect(view.titles()).toContain("Ada Lovelace: Fresh");
+
+ view.act({ type: "groupPatched", group: { ...room, name: "Daily", tasks: [{ threadId: "standup-1", title: "Tuesday plan", createdAt: 4 }] } });
+ expect(view.titles()).toContain("Daily: Tuesday plan");
+
+ view.act({ type: "select", id: "ada" });
+ expect(view.latest().currentBotId).toBe("ada");
+ });
+
+ it("hands the rows the same value for a change no link reads", () => {
+ const view = mounted();
+ const before = view.latest();
+ const renders = view.seen.length;
+ view.act({ type: "botPatched", bot: { ...scout, unread: true, newThreadModel: { instanceId: "fake", model: "other" } } });
+ view.act({ type: "connected", value: false });
+ expect(view.seen.length).toBe(renders);
+ expect(view.latest()).toBe(before);
+ });
+});
diff --git a/src/components/lazy-views.tsx b/src/components/lazy-views.tsx
index 3737523e51..89deee2509 100644
--- a/src/components/lazy-views.tsx
+++ b/src/components/lazy-views.tsx
@@ -13,3 +13,9 @@ export const NoEngines = lazyScreen("NoEngines", async () => (await import("./No
export const MemberApps = lazyScreen("MemberApps", async () => (await import("./MemberApps")).MemberApps);
export const SkillBurgerSlot = lazyScreen("SkillBurgerSlot", async () => (await import("./skill-burger/SkillBurgerSlot")).SkillBurgerSlot);
export const SiteFrame = lazyScreen("SiteFrame", async () => (await import("./published-apps/SiteFrame")).SiteFrame);
+// Drawn only once someone opens them: a call with a room, a sidebar search, a new room, About and Sign out.
+export const GroupCall = lazyScreen("GroupCall", async () => (await import("./GroupCallBody")).default);
+export const SearchResults = lazyScreen("SearchResults", async () => (await import("./SearchResults")).SearchResults);
+export const NewRoomPanel = lazyScreen("NewRoomPanel", async () => (await import("./SidebarNewRoomPanel")).NewRoomPanel);
+export const AboutDialog = lazyScreen("AboutDialog", async () => (await import("./AboutDialog")).AboutDialog);
+export const SignOutConfirm = lazyScreen("SignOutConfirm", async () => (await import("./settings/SignOutConfirm")).SignOutConfirm);
diff --git a/src/lib/search-hit.ts b/src/lib/search-hit.ts
index 338ca10463..681ded5a25 100644
--- a/src/lib/search-hit.ts
+++ b/src/lib/search-hit.ts
@@ -1,3 +1,6 @@
+/** The shortest query the sidebar searches messages for. */
+export const MIN_QUERY = 2;
+
export interface SearchHit {
botId?: string;
groupId?: string;