Skip to content

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

First snapshot sends a tail of conversations not on screen; background conversations stay bounded (#6795)

Milind Sonifd8781a73141
diff --git a/packages/phone-protocol/src/responses.ts b/packages/phone-protocol/src/responses.ts
index cc877e1104..4dfe437fae 100644
--- a/packages/phone-protocol/src/responses.ts
+++ b/packages/phone-protocol/src/responses.ts
@@ -88,7 +88,9 @@ export interface WireComputerControl {
help?: ComputerHelpRef;
}
-/** GET /api/bots?messages=N: the fleet, each bot and room with the newest page of its selected conversation. */
+/** GET /api/bots?messages=N: the fleet, each bot and room with the newest page of its selected conversation. With
+ * `&tail=T&open=ID,…`, a bot not named in `open` carries only the newest T or more of those rows (`hasMore` true when
+ * rows were left out), reaching back to every line a client reads from a conversation it is not showing. */
export interface BotsResponse<Message = WireMessage> {
bots: Array<WireBot & WireMessagePage<Message>>;
botQueuedMessages: BotQueuedMessages;
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 49b051f1f0..6a76947017 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -212,6 +212,7 @@ export const SRC_OUTSIDE_RENDERER = [
"src/components/app/app-frame-host.ts",
"src/lib/citations.ts",
"src/lib/composer-attachments.ts",
+ "src/lib/peer-message.ts",
"src/lib/random-uuid.ts",
"src/lib/receipts.ts",
];
diff --git a/server/host/snapshot-tail.ts b/server/host/snapshot-tail.ts
new file mode 100644
index 0000000000..a6f54928ce
--- /dev/null
+++ b/server/host/snapshot-tail.ts
@@ -0,0 +1,59 @@
+import { peerLine } from "../../src/lib/peer-message.ts";
+import { isReceipt } from "../../src/lib/receipts.ts";
+import type { MessagePage } from "../routes/threads.ts";
+
+type Row = { id: string; role?: string; kind?: string; text?: string; tool?: unknown; parentId?: string | null };
+
+/** The branch a client draws, oldest first: the chain up from the active leaf, or every row when the leaf is not held. */
+function branchOf(rows: readonly Row[], leafId: string | null | undefined): readonly Row[] {
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ if (!leafId || !byId.has(leafId)) return rows;
+ const path: Row[] = [];
+ for (let row = byId.get(leafId); row; row = row.parentId ? byId.get(row.parentId) : undefined) path.push(row);
+ return path.reverse();
+}
+
+const isPerson = (row: Row) => row.role === "user" && !peerLine(row as Parameters<typeof peerLine>[0]);
+const notReceipt = (row: Row) => !isReceipt({ kind: row.kind ?? "" });
+const previewable = (row: Row) => notReceipt(row) && row.kind !== "screen";
+
+/**
+ * Where in `rows` each line lies that a client reads from a conversation it is not showing (-1 when `rows` has none):
+ * the sidebar preview's newest line and the line it quotes, the person's last line or the read cursor (the unread
+ * divider goes after the later of them), the newest person-role line and tool step, the newest non-receipt of the rows
+ * and of the branch (the sidebar mascot and its failed mark), the active leaf, and the end of every other branch (where
+ * another client switching branches moves the leaf).
+ */
+function readLines(rows: readonly Row[], leafId: string | null | undefined, cursorId: string | undefined): number[] {
+ const at = new Map(rows.map((row, index) => [row.id, index]));
+ const branch = branchOf(rows, leafId);
+ const newest = (from: readonly Row[], test: (row: Row) => boolean) => {
+ const row = from.findLast(test);
+ return row ? at.get(row.id)! : -1;
+ };
+ const onBranch = new Set(branch);
+ const parents = new Set(rows.map((row) => row.parentId));
+ const otherEnds = rows.flatMap((row, index) => onBranch.has(row) || parents.has(row.id) ? [] : [index]);
+ return [
+ newest(branch, previewable),
+ newest(branch, (row) => row.role === "user" || (previewable(row) && row.kind !== "activity")),
+ Math.max(newest(branch, isPerson), newest(branch, (row) => row.id === cursorId)),
+ newest(rows, (row) => row.role === "user"),
+ newest(rows, (row) => row.kind === "activity" && Boolean(row.tool)),
+ newest(rows, notReceipt),
+ newest(branch, notReceipt),
+ leafId ? at.get(leafId) ?? -1 : -1,
+ ...otherEnds,
+ ];
+}
+
+/**
+ * A conversation's newest rows for a client that is not showing it: at least `floor`, and back far enough that every
+ * line the client reads from it is the one it would read from the newest `limit` rows.
+ */
+export function heldTail<P extends MessagePage>(read: (limit: number) => P, floor: number, limit: number, cursorId?: string): P {
+ const page = read(limit);
+ let start = Math.max(0, page.messages.length - floor);
+ for (const index of readLines(page.messages as Row[], page.activeLeafId, cursorId)) if (index >= 0) start = Math.min(start, index);
+ return start === 0 ? page : { ...page, messages: page.messages.slice(start), hasMore: true };
+}
diff --git a/server/routes/threads-snapshot-tail.test.ts b/server/routes/threads-snapshot-tail.test.ts
new file mode 100644
index 0000000000..c07842008c
--- /dev/null
+++ b/server/routes/threads-snapshot-tail.test.ts
@@ -0,0 +1,109 @@
+import { rmSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { ModelSelection } from "../contracts.ts";
+import { json, readBody } from "../harness/http.ts";
+import { messagePages, pageSize } from "../host/message-pages.ts";
+import { closeMessageDb } from "../message-db.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { Store, type BotRecord } from "../store.ts";
+import { dispatchRoutes } from "./table.ts";
+import { createThreadRoutes, type ThreadRouteDeps } from "./threads.ts";
+
+type WireRow = { id: string; text?: string };
+type Listed = { id: string; threadId: string; messages: WireRow[]; hasMore: boolean; activeLeafId: string | null };
+type Body = { bots: Listed[]; groups: unknown[]; error?: string };
+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
+const servers: Server[] = [];
+
+beforeEach(() => {
+ closeMessageDb();
+ rmSync(DATA_DIR, { recursive: true, force: true });
+});
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
+});
+
+async function serve(store: Store): Promise<string> {
+ const deps = {
+ store, viewerFor: () => ({}),
+ visibleTo: () => ({ everything: true, bot: () => true, group: () => true, thread: () => true, sections: () => [] }),
+ workspaceAccess: () => null, desktopMutationToken: () => undefined, companionMutationToken: () => undefined, cliOwnerToken: () => undefined,
+ groupUsageReader: { refresh: () => {} },
+ pageSize, defaultPage: 50, ...messagePages(store),
+ wireBot: (bot: BotRecord) => ({ id: bot.id, threadId: bot.threadId, name: bot.name }),
+ publicBotQueuedMessages: () => ({}),
+ publicGroupState: () => ({}),
+ botComputerControlSnapshot: () => ({ held: false, helpReason: null }),
+ } as unknown as ThreadRouteDeps;
+ const routes = [createThreadRoutes(deps)];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;
+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ if (!handled) json(res, 404, { from: "inline routes" });
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+function fleet(bots: number, rows: number) {
+ const store = new Store(() => sonnet);
+ const made = Array.from({ length: bots }, (_, index) => store.createBot({ name: `Bot ${index}` }, { seedMessages: false }));
+ for (const bot of made) {
+ for (let index = 0; index < rows; index++) {
+ store.appendMessage(bot.threadId, index % 10 === 0 ? { role: "user", kind: "text", text: `ask ${index}` } : { role: "bot", kind: "text", text: `reply ${index}` });
+ }
+ }
+ return { store, made };
+}
+
+describe("GET /api/bots with a tail for the conversations not open", () => {
+ it("sends one page of the open bots and a tail of the rest, with nothing else changed", async () => {
+ const { store, made } = fleet(4, 260);
+ const base = await serve(store);
+ const get = async (query: string) => (await (await fetch(`${base}/api/bots?${query}`)).json()) as Body;
+ const whole = await get("messages=200");
+ const tailed = await get(`messages=200&tail=20&open=${made[1]!.id},${made[3]!.id}`);
+
+ const byId = (body: Body) => new Map(body.bots.map((bot) => [bot.id, bot]));
+ const [wholeBots, tailedBots] = [byId(whole), byId(tailed)];
+ for (const bot of made) {
+ const full = wholeBots.get(bot.id)!, sent = tailedBots.get(bot.id)!;
+ const { messages: _a, ...fullRest } = full, { messages: _b, ...sentRest } = sent;
+ expect(sentRest).toEqual(fullRest);
+ expect(full.messages).toHaveLength(200);
+ if (bot === made[1] || bot === made[3]) expect(sent.messages).toEqual(full.messages);
+ else {
+ expect(sent.messages).toEqual(full.messages.slice(-sent.messages.length));
+ expect(sent.messages.map((row) => row.text)).toContain("ask 250");
+ expect(sent.messages).toHaveLength(20);
+ expect(sent.hasMore).toBe(true);
+ }
+ }
+ expect(Object.keys(tailed).sort()).toEqual(Object.keys(whole).sort());
+ expect(JSON.stringify(tailed).length).toBeLessThan(JSON.stringify(whole).length * 0.6);
+ });
+
+ it("answers a client that sends no tail exactly as before", async () => {
+ const { store } = fleet(3, 120);
+ const base = await serve(store);
+ const get = async (query: string) => (await (await fetch(`${base}/api/bots?${query}`)).json()) as Body;
+ for (const query of ["messages=200", "messages=50", ""]) {
+ const answer = await get(query);
+ for (const bot of answer.bots) expect(bot.messages).toHaveLength(query === "messages=50" ? 50 : 120);
+ }
+ expect(await get("messages=200&tail=500")).toEqual(await get("messages=200"));
+ expect(await get("tail=20")).toEqual(await get(""));
+ });
+
+ it("refuses a tail that is not a whole number", async () => {
+ const base = await serve(fleet(1, 3).store);
+ const answer = await fetch(`${base}/api/bots?messages=200&tail=-1`);
+ expect(answer.status).toBe(400);
+ });
+});
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 5b8480faaf..d33cf4df64 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -25,6 +25,7 @@ import { resolveRequestAuth, type RequestAuth, type ResolveOptions } from "../re
import type { queuedSteerSnapshot } from "../steer-queue.ts";
import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { answerAsleep, backgroundWhileAsleep } from "../cloud-power.ts";
+import { heldTail } from "../host/snapshot-tail.ts";
import { createJobRoutes } from "./jobs.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
@@ -84,11 +85,14 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
} = deps;
const mediaLinks = new MessageMediaLinks();
// tasks stays explicit: clients expect [] where wireBot() would omit the key.
- const shownBot = (bot: BotRecord, visible: VisibleSet, limit: number | undefined) => {
+ const shownBot = (bot: BotRecord, visible: VisibleSet, limit: number | undefined, tail?: number) => {
const wired = wireBot(bot);
// Narrowed first: on a Team Cloud the selected conversation may be someone else's, and its words never go out.
const shown = memberBot({ ...wired, tasks: wired.tasks ?? [] }, visible);
- return { ...shown, ...(typeof shown.threadId === "string" ? messagePage(shown.threadId, limit) : { messages: [], hasMore: false, activeLeafId: null }) };
+ const threadId = shown.threadId;
+ if (typeof threadId !== "string") return { ...shown, messages: [], hasMore: false, activeLeafId: null };
+ const cursor = shown.tasks?.find((task) => task.threadId === threadId)?.lastReadMessageId;
+ return { ...shown, ...(tail !== undefined && limit !== undefined && tail < limit ? heldTail((size) => messagePage(threadId, size), tail, limit, cursor) : messagePage(threadId, limit)) };
};
const jobs = createJobRoutes({ store, coordinator: deps.coordinator, groupThreadIsWorking: deps.groupThreadIsWorking, viewerFor, visibleTo, sessions });
const handle = async ({ req, res, url, path, method, auth, json, readBody }: RouteContext): Promise<unknown> => {
@@ -105,10 +109,13 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
try { groupUsageReader.refresh(); } catch { }
const limit = pageSize(url.searchParams.get("messages"));
if (limit === null) return json(res, 400, { error: "messages must be a non-negative whole number" });
+ const tail = pageSize(url.searchParams.get("tail"));
+ if (tail === null) return json(res, 400, { error: "tail must be a non-negative whole number" });
+ const open = new Set(url.searchParams.get("open")?.split(",") ?? []);
const shownBots = (deps.botOrderFor?.(auth, store.bots) ?? store.bots).filter((bot) => visible.bot(bot.id));
const queued = publicBotQueuedMessages();
return json(res, 200, {
- bots: shownBots.map((bot) => shownBot(bot, visible, limit)),
+ bots: shownBots.map((bot) => shownBot(bot, visible, limit, open.has(bot.id) ? undefined : tail)),
botQueuedMessages: visible.everything ? queued : Object.fromEntries(Object.entries(queued).filter(([threadId]) => visible.thread(threadId))),
sections: visible.sections(store.sections),
groups: store.groups.filter((g) => visible.group(g.id)).map((g) => {
diff --git a/src/components/WebPanelPage.test.ts b/src/components/WebPanelPage.test.ts
index 2e87d8ebfd..dcc6204c9e 100644
--- a/src/components/WebPanelPage.test.ts
+++ b/src/components/WebPanelPage.test.ts
@@ -171,3 +171,19 @@ describe("a pinned web panel's page", () => {
expect(host.querySelector("[data-app-placeholder]")).not.toBeNull();
});
});
+
+describe("a pinned chat page whose row the app does not hold", () => {
+ it("fetches the page again when a frame replaces it", async () => {
+ const { noteAppPagePatch } = await import("@/state/held-tails");
+ fixture.panels = [{ id: "panel-1", name: "Sales", page: { botId: "b1", threadId: "t1", messageId: "m1" } }];
+ fixture.state = { webPanelId: "panel-1", bots: [{ id: "b1", threadId: "t1", messages: [{ id: "newer", kind: "text" }] }] };
+ fixture.fetchAppDocument.mockClear();
+ await act(async () => root.render(createElement(WebPanelPage)));
+ expect(fixture.fetchAppDocument).toHaveBeenCalledTimes(1);
+ await act(async () => noteAppPagePatch("t1", { id: "m1", app: { title: "Sales", source: "html", doc: "d1", rev: 2 } } as never));
+ expect(fixture.fetchAppDocument).toHaveBeenCalledTimes(2);
+ await act(async () => noteAppPagePatch("t1", { id: "m1", app: { title: "Sales", source: "html", doc: "d1", rev: 2 } } as never));
+ expect(fixture.fetchAppDocument).toHaveBeenCalledTimes(2);
+ fixture.state = { webPanelId: "panel-1" };
+ });
+});
diff --git a/src/components/WebPanelPage.tsx b/src/components/WebPanelPage.tsx
index f7e8abf9ee..92fabaf31b 100644
--- a/src/components/WebPanelPage.tsx
+++ b/src/components/WebPanelPage.tsx
@@ -13,6 +13,7 @@ import { setWebPanels, useWebPanels } from "@/lib/web-panel-preferences";
import { isAppOrigin, type PinnedChatPage, type WebPanel } from "@/lib/web-panels";
import { api } from "@/state/api";
import { useStore, type Bot } from "@/state/store";
+import { useAppPagePatch } from "@/state/held-tails";
import type { AppDocument } from "../../shared/app";
import { AppDocumentError, fetchAppDocument } from "./app/app-api";
import { AppFrame, type AppFrameHandle } from "./app/AppFrame";
@@ -111,7 +112,8 @@ function storedPageVersion(bots: readonly Bot[] | undefined, page: PinnedChatPag
function PinnedChatPageView({ panel, page, panels }: { panel: WebPanel; page: PinnedChatPage; panels: readonly WebPanel[] }) {
const { state, dispatch } = useStore();
// Only a new stored version means the page changed: while its chat is not loaded (switching threads) it stays put.
- const stored = storedPageVersion(state.bots, page);
+ const patched = useAppPagePatch(page.threadId, page.messageId);
+ const stored = storedPageVersion(state.bots, page) || patched;
const [version, setVersion] = useState(stored);
if (stored && stored !== version) setVersion(stored);
const [reloads, setReloads] = useState(0);
diff --git a/src/hooks/use-transcript-viewport.reopen.test.ts b/src/hooks/use-transcript-viewport.reopen.test.ts
new file mode 100644
index 0000000000..2a4a55299e
--- /dev/null
+++ b/src/hooks/use-transcript-viewport.reopen.test.ts
@@ -0,0 +1,326 @@
+// Runs against a small stand-in for React's hooks (no DOM), a scroller whose height is its mounted row count, and rows a
+// text selection can span.
+import type { DependencyList } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const react = vi.hoisted(() => {
+ type Committed = { deps?: DependencyList; cleanup?: void | (() => void) };
+ type Pending = { slot: number; layout: boolean; deps?: DependencyList; run: () => void | (() => void) };
+ const runtime = { slots: [] as unknown[], cursor: 0, dirty: false, pending: [] as Pending[] };
+ const same = (a?: DependencyList, b?: DependencyList) =>
+ Boolean(a && b && a.length === b.length && a.every((value, index) => Object.is(value, b[index])));
+ const effect = (layout: boolean) => (run: () => void | (() => void), deps?: DependencyList) => {
+ const slot = runtime.cursor++;
+ if (same((runtime.slots[slot] as Committed | undefined)?.deps, deps)) return;
+ runtime.pending.push({ slot, layout, deps, run });
+ };
+ const memo = <T,>(factory: () => T, deps: DependencyList): T => {
+ const slot = runtime.cursor++;
+ const held = runtime.slots[slot] as { value: T; deps: DependencyList } | undefined;
+ if (held && same(held.deps, deps)) return held.value;
+ const value = factory();
+ runtime.slots[slot] = { value, deps };
+ return value;
+ };
+ const hooks = {
+ useState<T>(initial: T | (() => T)) {
+ const slot = runtime.cursor++;
+ if (!runtime.slots[slot]) {
+ const cell = {
+ value: typeof initial === "function" ? (initial as () => T)() : initial,
+ set: (next: T | ((current: T) => T)) => {
+ const value = typeof next === "function" ? (next as (current: T) => T)(cell.value) : next;
+ if (Object.is(value, cell.value)) return;
+ cell.value = value;
+ runtime.dirty = true;
+ },
+ };
+ runtime.slots[slot] = cell;
+ }
+ const cell = runtime.slots[slot] as { value: T; set: (next: T | ((current: T) => T)) => void };
+ return [cell.value, cell.set] as const;
+ },
+ useRef<T>(initial: T) {
+ const slot = runtime.cursor++;
+ return (runtime.slots[slot] ??= { current: initial }) as { current: T };
+ },
+ useMemo: memo,
+ useCallback: <T,>(callback: T, deps: DependencyList) => memo(() => callback, deps),
+ useEffect: effect(false),
+ useLayoutEffect: effect(true),
+ };
+ /** A render-phase update re-renders before committing, as React does; layout effects run before passive ones. */
+ function render(draw: () => void, commit: () => void) {
+ for (let pass = 0; pass < 20; pass++) {
+ runtime.cursor = 0;
+ runtime.dirty = false;
+ runtime.pending = [];
+ draw();
+ if (runtime.dirty) continue;
+ commit();
+ const pending = [...runtime.pending.filter((e) => e.layout), ...runtime.pending.filter((e) => !e.layout)];
+ for (const { slot, deps, run } of pending) {
+ (runtime.slots[slot] as Committed | undefined)?.cleanup?.();
+ runtime.slots[slot] = { deps, cleanup: run() };
+ }
+ if (!runtime.dirty) return;
+ }
+ throw new Error("render did not settle");
+ }
+ return { runtime, hooks, render };
+});
+vi.mock("react", async (original) => ({ ...await original<typeof import("react")>(), ...react.hooks }));
+
+const store = vi.hoisted(() => ({
+ state: {
+ focusMessage: null as null | { threadId: string; messageId: string; nonce: number; consumed: boolean },
+ loadingOlder: {} as Record<string, true>,
+ },
+ dispatch: (() => {}) as (action: unknown) => void,
+}));
+vi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));
+vi.mock("@/state/store", () => ({ useStore: () => store }));
+// Scrolling a hit into view needs the real DOM; this suite checks the window around it.
+vi.mock("@/lib/focus-message", () => ({ useFocusMessage: () => {} }));
+
+import { useTranscriptViewport } from "./use-transcript-viewport";
+import { SELECTION_HOLD_MAX, TRANSCRIPT_WINDOW_MAX } from "@/lib/transcript-window";
+import { forgetTranscriptPositions } from "@/lib/transcript-follow";
+import { resetLiveReplies } from "@/state/live-reply";
+
+type Row = { id: string; role?: "user" | "bot" };
+const rows = (count: number, from = 0): Row[] => Array.from({ length: count }, (_, index) => ({ id: `m${from + index}` }));
+
+const ROW = 50;
+let heightOf = (_row: Row) => ROW;
+class Scroller {
+ rows = 0;
+ content = 0;
+ extra = 0;
+ scrollTop = 0;
+ clientHeight = 400;
+ clientWidth = 400;
+ calls: ScrollToOptions[] = [];
+ get scrollHeight() {
+ return this.content + this.extra;
+ }
+ get bottom() {
+ return Math.max(0, this.scrollHeight - this.clientHeight);
+ }
+ scrollTo(options: ScrollToOptions) {
+ this.calls.push(options);
+ this.scrollTop = Math.max(0, Math.min(options.top ?? this.scrollTop, this.bottom));
+ }
+ getBoundingClientRect() {
+ return { top: 0, bottom: this.clientHeight, height: this.clientHeight };
+ }
+}
+
+type FakeRow = { nodeType: 1; dataset: { mid: string }; parentElement: null; closest(): FakeRow; getBoundingClientRect(): { top: number; bottom: number; height: number } };
+const elements = new Map<string, FakeRow>();
+let drawn: readonly Row[] = [];
+const rowElement = (id: string): FakeRow => {
+ let element = elements.get(id);
+ if (!element) {
+ element = {
+ nodeType: 1, dataset: { mid: id }, parentElement: null, closest: () => element!,
+ getBoundingClientRect: () => {
+ const index = drawn.findIndex((row) => row.id === id);
+ const top = index * ROW - scroller.scrollTop;
+ return { top, bottom: top + ROW, height: ROW };
+ },
+ };
+ elements.set(id, element);
+ }
+ return element;
+};
+/** The person's text selection, from the start of one row to the start of another. */
+let selection: { from: string; to: string } | null = null;
+let selectionDropped = 0;
+const pageSelection = () => {
+ if (!selection) return { rangeCount: 0, isCollapsed: true };
+ const range = { startContainer: rowElement(selection.from), endContainer: rowElement(selection.to), startOffset: 0, endOffset: 0, intersectsNode: () => true };
+ return {
+ rangeCount: 1, isCollapsed: false, getRangeAt: () => range, anchorNode: range.startContainer, anchorOffset: 0,
+ focusNode: range.endContainer, focusOffset: 0, toString: () => "", removeAllRanges: () => { selectionDropped++; selection = null; },
+ };
+};
+const transcriptOf = (shown: readonly Row[]) => {
+ drawn = shown;
+ return {
+ querySelectorAll: () => shown.map((row) => rowElement(row.id)),
+ contains: (node: unknown) => shown.some((row) => elements.get(row.id) === node),
+ ownerDocument: { getSelection: pageSelection },
+ };
+};
+
+type Props = Parameters<typeof useTranscriptViewport<Row>>[0];
+let scroller: Scroller;
+let frames: FrameRequestCallback[];
+let keyListeners: Set<(event: Partial<KeyboardEvent>) => void>;
+let dispatched: unknown[];
+
+function mount(initial: Partial<Props> = {}) {
+ let props: Props = { ownerId: "bot", threadId: "thread", messages: rows(10), pinOn: [false], ...initial };
+ let result!: ReturnType<typeof useTranscriptViewport<Row>>;
+ const draw = () => {
+ result = useTranscriptViewport(props);
+ };
+ // React's commit before layout effects; a browser clamps scrollTop when content gets shorter.
+ const commit = () => {
+ result.scrollRef.current = scroller as unknown as HTMLDivElement;
+ result.transcriptRef.current = transcriptOf(result.windowedMessages) as unknown as HTMLDivElement;
+ scroller.rows = result.windowedMessages.length;
+ scroller.content = result.windowedMessages.reduce((sum, row) => sum + heightOf(row), 0);
+ scroller.scrollTop = Math.min(scroller.scrollTop, scroller.bottom);
+ };
+ const flushFrames = () => {
+ const queued = frames;
+ frames = [];
+ for (const frame of queued) frame(0);
+ };
+ react.render(draw, commit);
+ return {
+ get current() {
+ return result;
+ },
+ rerender(next: Partial<Props>) {
+ props = { ...props, ...next };
+ react.render(draw, commit);
+ },
+ act(handler: () => void) {
+ handler();
+ react.render(draw, commit);
+ flushFrames();
+ },
+ unmount,
+ };
+}
+
+/** Runs every committed effect's cleanup, as an unmount does. */
+function unmount() {
+ for (const slot of react.runtime.slots) {
+ const cleanup = (slot as { cleanup?: unknown } | undefined)?.cleanup;
+ if (typeof cleanup === "function") cleanup();
+ }
+ react.runtime.slots = [];
+}
+
+beforeEach(() => {
+ react.runtime.slots = [];
+ scroller = new Scroller();
+ heightOf = () => ROW;
+ frames = [];
+ keyListeners = new Set();
+ dispatched = [];
+ forgetTranscriptPositions();
+ resetLiveReplies();
+ store.state.focusMessage = null;
+ store.state.loadingOlder = {};
+ store.dispatch = (action) => dispatched.push(action);
+ vi.stubGlobal("window", {
+ addEventListener: (_: string, listener: (event: Partial<KeyboardEvent>) => void) => keyListeners.add(listener),
+ removeEventListener: (_: string, listener: (event: Partial<KeyboardEvent>) => void) => keyListeners.delete(listener),
+ });
+ const requested: FrameRequestCallback[] = [];
+ vi.stubGlobal("requestAnimationFrame", (frame: FrameRequestCallback) => { frames.push(frame); return requested.push(frame); });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { frames = frames.filter((frame) => frame !== requested[id - 1]); });
+ vi.stubGlobal("ResizeObserver", class {
+ observe() {}
+ disconnect() {}
+ });
+ vi.stubGlobal("IntersectionObserver", class {
+ constructor() {}
+ observe() {}
+ disconnect() {}
+ });
+ vi.stubGlobal("HTMLTextAreaElement", class {});
+ vi.stubGlobal("document", {});
+ elements.clear();
+ selection = null;
+ selectionDropped = 0;
+ vi.stubGlobal("HTMLInputElement", class {});
+ return () => {
+ unmount();
+ vi.unstubAllGlobals();
+ };
+});
+
+describe("a conversation held as a short tail, opened again", () => {
+ const topId = (view: ReturnType<typeof mount>) => view.current.windowedMessages[Math.floor(scroller.scrollTop / ROW)]!.id;
+ const scrollTo = (view: ReturnType<typeof mount>, top: number) => view.act(() => {
+ scroller.scrollTop = top;
+ view.current.scrollHandlers.onScroll();
+ });
+ /** Every drawn row is the conversation's own, in order, with none skipped. */
+ const contiguous = (view: ReturnType<typeof mount>, held: readonly Row[]) => {
+ const shown = view.current.windowedMessages.map((row) => row.id);
+ const from = held.findIndex((row) => row.id === shown[0]);
+ expect(from).toBeGreaterThanOrEqual(0);
+ expect(shown).toEqual(held.slice(from, from + shown.length).map((row) => row.id));
+ };
+ const drawnIds = (view: ReturnType<typeof mount>) => view.current.windowedMessages.map((row) => row.id);
+
+ /** Opens a tail of 20, takes the page before it, then reads up to the first row, paging the rest in when it runs out. */
+ function readToTheTop(selected: { from: string; to: string } | null) {
+ let held = rows(20, 380);
+ const view = mount({ messages: held, hasMore: true });
+ held = [...rows(200, 180), ...held];
+ view.rerender({ messages: held, hasMore: true });
+ expect(view.current.windowedMessages.at(-1)?.id).toBe("m399");
+ contiguous(view, held);
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ selection = selected;
+ const asked: unknown[] = [];
+ for (let steps = 0; view.current.windowedMessages[0]?.id !== "m0" && steps < 100; steps++) {
+ if (view.current.hiddenCount === 0) {
+ dispatched = [];
+ scrollTo(view, 900);
+ scrollTo(view, 100);
+ asked.push(...dispatched);
+ const reading = topId(view);
+ held = [...rows(180, 0), ...held];
+ view.rerender({ messages: held, hasMore: false });
+ expect(topId(view), "the row at the top stays the row at the top as the page lands").toBe(reading);
+ } else {
+ scrollTo(view, 900);
+ scroller.scrollTop = 100;
+ const reading = topId(view);
+ view.act(() => view.current.scrollHandlers.onScroll());
+ expect(topId(view), "the row at the top stays the row at the top").toBe(reading);
+ }
+ contiguous(view, held);
+ if (selected) expect(drawnIds(view), "the selected rows stay drawn").toEqual(expect.arrayContaining(["m380", "m383", "m385"]));
+ }
+ expect(asked, "past the rows held it asks the server instead of stepping into rows it does not have").toEqual([{ type: "loadOlderMessages", threadId: "thread" }]);
+ expect(view.current.windowedMessages[0]?.id).toBe("m0");
+ return view;
+ }
+
+ it("steps toward older rows over the page paged back in, keeping the selection and the row under the reader", () => {
+ const view = readToTheTop({ from: "m380", to: "m385" });
+ expect(view.current.windowedMessages.length).toBeLessThanOrEqual(SELECTION_HOLD_MAX);
+ expect(view.current.windowedMessages.length).toBeGreaterThan(TRANSCRIPT_WINDOW_MAX);
+ expect(selection, "the selection was never taken off the page").toEqual({ from: "m380", to: "m385" });
+ expect(selectionDropped).toBe(0);
+ });
+
+ it("lets those rows go when nothing is selected", () => {
+ const view = readToTheTop(null);
+ expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect(drawnIds(view)).not.toContain("m385");
+ });
+
+ it("draws only rows it holds while the page before the tail is on its way", () => {
+ const held = rows(20, 380);
+ const view = mount({ messages: held, hasMore: true });
+ selection = { from: "m385", to: "m390" };
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ dispatched = [];
+ scrollTo(view, 0);
+ expect(view.current.hiddenCount).toBe(0);
+ expect(dispatched).toEqual([{ type: "loadOlderMessages", threadId: "thread" }]);
+ expect(drawnIds(view)).toEqual(held.map((row) => row.id));
+ expect(selectionDropped).toBe(0);
+ });
+});
diff --git a/src/state/chat-snapshot.test.ts b/src/state/chat-snapshot.test.ts
new file mode 100644
index 0000000000..6483fb6e6c
--- /dev/null
+++ b/src/state/chat-snapshot.test.ts
@@ -0,0 +1,133 @@
+// @vitest-environment happy-dom
+import { createElement, type Dispatch } 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 { ApiError } from "./api";
+import { readChatSnapshot, SNAPSHOT_TAIL } from "./chat-snapshot";
+import type { Action, AppState, BotAnnouncement, Message } from "./store";
+
+const row = (thread: string, index: number): Message => ({ id: `${thread}-${index}`, at: index, role: index % 10 ? "bot" : "user", kind: "text", text: `${thread} ${index}`, parentId: index ? `${thread}-${index - 1}` : null } as Message);
+const thread = (id: string, count: number) => Array.from({ length: count }, (_, index) => row(id, index));
+const bot = (id: string, messages: Message[], hasMore: boolean): BotAnnouncement => ({
+ id, threadId: `${id}-t`, name: id, title: "", description: "", notifications: true, unread: false, color: "green",
+ modelSelection: { instanceId: "fake", model: "m" }, tasks: [{ threadId: `${id}-t`, title: "Thread", createdAt: 1 }],
+ messages, hasMore, activeLeafId: messages.at(-1)?.id ?? null,
+} as BotAnnouncement);
+const full = { a: thread("a-t", 400), b: thread("b-t", 400), c: thread("c-t", 400) };
+const tailOf = (id: keyof typeof full) => bot(id, full[id].slice(-SNAPSHOT_TAIL), true);
+const pageOf = (id: keyof typeof full) => bot(id, full[id].slice(-200), true);
+
+describe("reading the first snapshot", () => {
+ it("asks for one page of the conversation that may open and a tail of the rest", async () => {
+ const read = vi.fn(async (path: string) => path.startsWith("/api/bots?") ? { bots: [tailOf("a"), pageOf("b")], groups: [] } : {});
+ const snapshot = await readChatSnapshot(() => ({ selectedId: "" }), "b", read as never);
+ expect(read.mock.calls.map(([path]) => path)).toEqual([`/api/bots?messages=200&tail=${SNAPSHOT_TAIL}&open=b`]);
+ expect(snapshot.bots.map((sent) => sent.messages?.length)).toEqual([SNAPSHOT_TAIL, 200]);
+ });
+
+ it("fills the conversation it will open on before it is applied, whatever the server sent", async () => {
+ const read = vi.fn(async (path: string) => path.startsWith("/api/bots?") ? { bots: [tailOf("a"), tailOf("b")], groups: [] }
+ : { messages: full.a.slice(-200), hasMore: true, activeLeafId: "a-t-399" });
+ const snapshot = await readChatSnapshot(() => ({ selectedId: "" }), "gone", read as never);
+ expect(read.mock.calls.map(([path]) => path)).toEqual([`/api/bots?messages=200&tail=${SNAPSHOT_TAIL}&open=gone`, "/api/threads/a-t/messages?limit=200"]);
+ expect(snapshot.bots[0]!.messages).toEqual(full.a.slice(-200));
+ expect(snapshot.bots[1]!.messages).toHaveLength(SNAPSHOT_TAIL);
+ });
+
+ it("fills the conversation the person opened while the snapshot was on its way", async () => {
+ let selectedId = "a";
+ const read = vi.fn(async (path: string) => {
+ if (path.startsWith("/api/bots?")) { selectedId = "c"; return { bots: [pageOf("a"), tailOf("b"), tailOf("c")], groups: [] }; }
+ return { messages: full.c.slice(-200), hasMore: true, activeLeafId: "c-t-399" };
+ });
+ const snapshot = await readChatSnapshot(() => ({ selectedId }), undefined, read as never);
+ expect(read.mock.calls.at(-1)![0]).toBe("/api/threads/c-t/messages?limit=200");
+ expect(snapshot.bots[2]!.messages).toHaveLength(200);
+ });
+
+ it("asks once of a server that ignores tail", async () => {
+ const old = vi.fn(async () => ({ bots: [pageOf("a"), pageOf("b")], groups: [] }));
+ expect((await readChatSnapshot(() => ({ selectedId: "a" }), undefined, old as never)).bots[1]!.messages).toHaveLength(200);
+ expect(old).toHaveBeenCalledTimes(1);
+ });
+
+ it("applies the tail when the page cannot be read, to be paged back once the snapshot lands", async () => {
+ for (const error of [new ApiError("no such conversation", 404), new ApiError("unavailable", 503), new TypeError("offline")]) {
+ const failing = vi.fn(async (path: string) => {
+ if (path.startsWith("/api/bots?")) return { bots: [tailOf("a")], groups: [] };
+ throw error;
+ });
+ expect((await readChatSnapshot(() => ({ selectedId: "a" }), undefined, failing as never)).bots[0]!.messages).toHaveLength(SNAPSHOT_TAIL);
+ }
+ });
+});
+
+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 }); }
+}
+
+describe("the store with a tailed snapshot", () => {
+ const requests: string[] = [];
+ const json = (body: unknown, status = 200) => Promise.resolve(new Response(JSON.stringify(body), { status }));
+ let seen!: AppState;
+ let dispatch!: Dispatch<Action>;
+ let root: Root;
+ const settle = async () => { for (let i = 0; i < 8; i++) await new Promise((resolve) => setTimeout(resolve, 0)); };
+
+ beforeAll(async () => {
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", (path: string) => {
+ requests.push(path);
+ if (path.startsWith("/api/bots?")) return json({ bots: [pageOf("a"), tailOf("b")], groups: [] });
+ const older = /^\/api\/threads\/b-t\/messages\?limit=200&before=(.+)$/.exec(path);
+ if (older) {
+ const at = full.b.findIndex((message) => message.id === decodeURIComponent(older[1]!));
+ return json({ messages: full.b.slice(Math.max(0, at - 200), at), hasMore: at > 200 });
+ }
+ return json({});
+ });
+ const { StoreProvider, useStore } = await import("./store");
+ function Probe() {
+ ({ state: seen, dispatch } = useStore());
+ return null;
+ }
+ 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();
+ });
+ afterAll(() => {
+ root.unmount();
+ vi.unstubAllGlobals();
+ });
+
+ it("opens on a whole page, and pages a tailed conversation back in as soon as it opens", async () => {
+ expect(requests.find((path) => path.startsWith("/api/bots?"))).toContain(`tail=${SNAPSHOT_TAIL}`);
+ expect(seen.selectedId).toBe("a");
+ expect(seen.bots.find((held) => held.id === "a")!.messages).toHaveLength(200);
+ const before = seen.bots.find((held) => held.id === "b")!;
+ expect(before.messages).toHaveLength(SNAPSHOT_TAIL);
+
+ flushSync(() => dispatch({ type: "select", id: "b" }));
+ await vi.waitFor(() => expect(seen.bots.find((held) => held.id === "b")!.messages).toHaveLength(200 + SNAPSHOT_TAIL));
+ const after = seen.bots.find((held) => held.id === "b")!;
+ expect(after.messages).toEqual(full.b.slice(-(200 + SNAPSHOT_TAIL)));
+ expect(after.hasMore).toBe(true);
+ expect(requests.filter((path) => path.startsWith("/api/threads/b-t/messages"))).toHaveLength(1);
+
+ flushSync(() => dispatch({ type: "select", id: "a" }));
+ flushSync(() => dispatch({ type: "select", id: "b" }));
+ await settle();
+ expect(requests.filter((path) => path.startsWith("/api/threads/b-t/messages"))).toHaveLength(1);
+ });
+});
diff --git a/src/state/chat-snapshot.ts b/src/state/chat-snapshot.ts
new file mode 100644
index 0000000000..8c22527398
--- /dev/null
+++ b/src/state/chat-snapshot.ts
@@ -0,0 +1,38 @@
+import { api, snapshotArrays } from "./api";
+import { noteSnapshotTails } from "./held-tails";
+import { MESSAGE_PAGE_SIZE, shortHeld } from "./message-history";
+import { hydratedSelectedId } from "./snapshot-navigation";
+import type { Action, AppState, Bot, Group, Message } from "./store";
+
+/** The fewest rows the first snapshot carries of a conversation nobody has open; the server reaches back further when
+ * the sidebar, the unread divider or the team map reads an older line. */
+export const SNAPSHOT_TAIL = 20;
+
+type ThreadPage = { messages: Message[]; hasMore?: boolean; activeLeafId?: string | null };
+type Hydrate = Extract<Action, { type: "hydrate" }>;
+export type ChatSnapshot = { bots: Bot[]; groups?: Group[]; sections?: string[]; computerControl?: Hydrate["computerControl"]; botQueuedMessages?: Hydrate["botQueuedMessages"] };
+type Read = <T>(path: string) => Promise<T>;
+
+/**
+ * Every bot and room, with one page of the conversations that may open and a tail of the others. The conversation the
+ * snapshot will open on (or the one open by the time it lands) gets its whole page before it is applied; when that page
+ * cannot be read, the tail is applied and paged back once the snapshot lands.
+ */
+export async function readChatSnapshot(current: () => Pick<AppState, "selectedId">, resumeId: string | undefined, read: Read = api): Promise<ChatSnapshot> {
+ const open = [...new Set([current().selectedId, resumeId ?? ""].filter(Boolean))].map(encodeURIComponent).join(",");
+ const snapshot = snapshotArrays(await read<ChatSnapshot>(`/api/bots?messages=${MESSAGE_PAGE_SIZE}&tail=${SNAPSHOT_TAIL}${open ? `&open=${open}` : ""}`), "bots");
+ const filled = new Set<string>();
+ for (;;) {
+ const id = hydratedSelectedId(current().selectedId, snapshot.bots, snapshot.groups ?? [], resumeId);
+ const owner = snapshot.bots.find((bot) => bot.id === id);
+ if (!shortHeld(owner) || filled.has(owner.threadId)) break;
+ filled.add(owner.threadId);
+ const page = await read<ThreadPage>(`/api/threads/${encodeURIComponent(owner.threadId)}/messages?limit=${MESSAGE_PAGE_SIZE}`).catch(() => null);
+ if (!page) break;
+ snapshot.bots = snapshot.bots.map((bot) => bot.id === owner.id && bot.threadId === owner.threadId
+ ? { ...bot, messages: page.messages, hasMore: Boolean(page.hasMore), ...(page.activeLeafId !== undefined ? { activeLeafId: page.activeLeafId } : {}) }
+ : bot);
+ }
+ noteSnapshotTails(snapshot.bots.filter((bot) => shortHeld(bot)));
+ return snapshot;
+}
diff --git a/src/state/held-in-background.test.ts b/src/state/held-in-background.test.ts
new file mode 100644
index 0000000000..15e16e653e
--- /dev/null
+++ b/src/state/held-in-background.test.ts
@@ -0,0 +1,179 @@
+import { describe, expect, it } from "vitest";
+import { lastLine } from "@/components/sidebar-preview";
+import { botUnreadCount } from "@/lib/bot-unread";
+import { forgetTranscriptPositions, rememberTranscriptPosition } from "@/lib/transcript-follow";
+import { setWebPanels } from "@/lib/web-panel-preferences";
+import { createAppStore } from "./app-store";
+import { followHeldTails, noteSnapshotTails } from "./held-tails";
+import { HELD_AFTER_LEAVING, HELD_IN_BACKGROUND } from "./message-history";
+import { visibleMessages } from "./snapshot-navigation";
+import { initialState, reducer, type Action, type AppState, type Bot, type Message } from "./store";
+
+const row = (index: number, parentId: string | null): Message =>
+ ({ id: `w${index}`, at: index, parentId, role: index % 25 ? "bot" : "user", kind: index % 3 ? "activity" : "text", text: `line ${index}`,
+ ...(index % 3 ? { tool: { name: "Bash", ok: true, input: "{}" } } : {}) }) as Message;
+const worker = (count: number): Bot => {
+ const messages = Array.from({ length: count }, (_, index) => row(index, index ? `w${index - 1}` : null));
+ return { id: "worker", threadId: "work", name: "Worker", messages, hasMore: false, activeLeafId: messages.at(-1)?.id ?? null, unread: true,
+ tasks: [{ threadId: "work", title: "Work", createdAt: 1, unread: true }] } as unknown as Bot;
+};
+const reader = { id: "reader", threadId: "read", name: "Reader", messages: [], hasMore: false, tasks: [] } as unknown as Bot;
+const held = (state: AppState) => state.bots.find((bot) => bot.id === "worker")!;
+const land = (state: AppState, index: number) => {
+ const parentId = held(state).activeLeafId ?? null;
+ return reducer(state, { type: "messageAdded", threadId: "work", message: row(index, parentId) });
+};
+const looksLike = (bot: Bot) => ({ simple: lastLine(bot, visibleMessages(bot), [], false), advanced: lastLine(bot, visibleMessages(bot), [], true), unread: botUnreadCount(bot) });
+
+describe("a conversation nobody has on screen, as its rows keep landing", () => {
+ it("keeps only its newest rows past the cap, with the same preview and unread count", () => {
+ let state: AppState = { ...initialState, bots: [worker(HELD_IN_BACKGROUND), reader], selectedId: "reader", activeView: "chat" };
+ const before = looksLike(held(state));
+ state = land(state, HELD_IN_BACKGROUND);
+ expect(held(state).messages).toHaveLength(HELD_AFTER_LEAVING);
+ expect(held(state).messages.at(-1)!.id).toBe(`w${HELD_IN_BACKGROUND}`);
+ expect(held(state).hasMore).toBe(true);
+ const unchanged = { ...looksLike(held(state)) };
+ const grown = reducer({ ...initialState, bots: [worker(HELD_IN_BACKGROUND + 1), reader], selectedId: "reader", activeView: "chat" }, { type: "showChat" });
+ expect(unchanged).toEqual(looksLike(held(grown)));
+ expect(before.unread).toBe(unchanged.unread);
+ for (let index = HELD_IN_BACKGROUND + 1; index < HELD_IN_BACKGROUND * 3; index++) state = land(state, index);
+ expect(held(state).messages.length).toBeLessThanOrEqual(HELD_IN_BACKGROUND);
+ });
+
+ it("never trims the conversation on screen, nor the first bot the chat draws when the selection names no one", () => {
+ for (const selectedId of ["worker", "gone"]) {
+ let state: AppState = { ...initialState, bots: [worker(HELD_IN_BACKGROUND), reader], selectedId, activeView: "chat" };
+ for (let index = HELD_IN_BACKGROUND; index < HELD_IN_BACKGROUND + 50; index++) state = land(state, index);
+ expect(held(state).messages).toHaveLength(HELD_IN_BACKGROUND + 50);
+ }
+ });
+
+ it("never trims a conversation whose pinned page the web panel shows", () => {
+ setWebPanels([{ id: "panel-1", name: "Sales", page: { botId: "worker", threadId: "work", messageId: "w3" } }]);
+ let state: AppState = { ...initialState, bots: [worker(HELD_IN_BACKGROUND), reader], selectedId: "reader", activeView: "web-panel", webPanelId: "panel-1" };
+ state = land(state, HELD_IN_BACKGROUND);
+ expect(held(state).messages).toHaveLength(HELD_IN_BACKGROUND + 1);
+ setWebPanels([]);
+ });
+
+ it("keeps the row the reader left it at", () => {
+ const place = `w${HELD_IN_BACKGROUND - 450}`;
+ rememberTranscriptPosition("worker:work", { atEnd: false, rowId: place, offsetWithinRow: 0 });
+ let state: AppState = { ...initialState, bots: [worker(HELD_IN_BACKGROUND), reader], selectedId: "reader", activeView: "chat" };
+ state = land(state, HELD_IN_BACKGROUND);
+ expect(held(state).messages[0]!.id).toBe(place);
+ expect(held(state).messages.length).toBeLessThan(HELD_IN_BACKGROUND);
+ forgetTranscriptPositions();
+ });
+
+ it("pages back the rows it let go when it opens again, the same rows as before", () => {
+ const thread = worker(HELD_IN_BACKGROUND + 1).messages;
+ let state: AppState = { ...initialState, bots: [worker(HELD_IN_BACKGROUND), reader], selectedId: "reader", activeView: "chat" };
+ state = land(state, HELD_IN_BACKGROUND);
+ state = reducer(state, { type: "select", id: "worker" });
+ const first = held(state).messages[0]!.id;
+ const at = thread.findIndex((message) => message.id === first);
+ state = reducer(state, { type: "olderMessages", threadId: "work", generation: 0, before: first, messages: thread.slice(Math.max(0, at - 200), at), hasMore: at > 200 });
+ expect(held(state).messages).toEqual(thread.slice(-held(state).messages.length));
+ expect(held(state).messages.length).toBeGreaterThan(HELD_AFTER_LEAVING);
+ });
+});
+
+describe("a conversation the snapshot sent as a short tail", () => {
+ const tailed = (count: number, hasMore = true) => ({ ...worker(count), hasMore });
+ /** A store holding `state`, the tails the snapshot sent, and what the follower asks for. */
+ async function follow(state: AppState, tails: Bot[]) {
+ const store = createAppStore<AppState, Action, never>(reducer, state, () => () => {});
+ const asked: Action[] = [];
+ noteSnapshotTails(tails);
+ const stop = followHeldTails(store, (action) => asked.push(action));
+ await Promise.resolve();
+ return { store, asked, stop, settle: () => Promise.resolve() };
+ }
+
+ it("asks for the page before its tail however it becomes selected", async () => {
+ for (const select of [{ type: "select", id: "worker" }, { type: "toggleComputer", botId: "worker", open: true }, { type: "toggleSettings", botId: "worker", open: true }] as Action[]) {
+ const bot = tailed(20);
+ const { store, asked, stop, settle } = await follow({ ...initialState, bots: [reader, bot], selectedId: "reader", activeView: "team-map" }, [bot]);
+ expect(asked).toEqual([]);
+ store.dispatch(select);
+ await settle();
+ expect(asked, select.type).toEqual([{ type: "loadOlderMessages", threadId: "work" }]);
+ store.dispatch({ type: "loadOlderMessages", threadId: "work" });
+ store.dispatch({ type: "select", id: "reader" });
+ store.dispatch(select);
+ await settle();
+ expect(asked, "not again while its page is on the way").toHaveLength(1);
+ stop();
+ }
+ });
+
+ it("asks for it when the selection falls to it because the selected bot is gone", async () => {
+ const bot = tailed(20);
+ const { asked, stop } = await follow({ ...initialState, bots: [bot, reader], selectedId: "gone", activeView: "chat" }, [bot]);
+ expect(asked).toEqual([{ type: "loadOlderMessages", threadId: "work" }]);
+ stop();
+ });
+
+ it("asks for it when another client moves its branch, not when a new row lands", async () => {
+ const bot = tailed(20);
+ const { store, asked, stop, settle } = await follow({ ...initialState, bots: [reader, bot], selectedId: "reader", activeView: "chat" }, [bot]);
+ store.dispatch({ type: "messageAdded", threadId: "work", message: row(20, held(store.getState()).activeLeafId ?? null) });
+ await settle();
+ expect(asked).toEqual([]);
+ store.dispatch({ type: "threadActive", threadId: "work", activeLeafId: "elsewhere" });
+ await settle();
+ expect(asked).toEqual([{ type: "loadOlderMessages", threadId: "work" }]);
+ stop();
+ });
+
+ it("asks again after a failed page, at most once per opening, and stops once a page lands", async () => {
+ const bot = tailed(20);
+ const thread = worker(400).messages;
+ const { store, asked, stop, settle } = await follow({ ...initialState, bots: [reader, bot], selectedId: "reader", activeView: "chat" }, [bot]);
+ const fail = () => {
+ store.dispatch({ type: "loadOlderMessages", threadId: "work" });
+ store.dispatch({ type: "olderMessages", threadId: "work", generation: 0, before: "w0", messages: [], hasMore: true });
+ };
+ store.dispatch({ type: "select", id: "worker" });
+ await settle();
+ expect(asked).toHaveLength(1);
+ fail();
+ await settle();
+ expect(asked, "one more ask after a failed page").toHaveLength(2);
+ fail();
+ await settle();
+ expect(asked, "no loop").toHaveLength(2);
+
+ store.dispatch({ type: "select", id: "reader" });
+ store.dispatch({ type: "select", id: "worker" });
+ await settle();
+ expect(asked, "selected again: a fresh ask").toHaveLength(3);
+ store.dispatch({ type: "loadOlderMessages", threadId: "work" });
+ store.dispatch({ type: "olderMessages", threadId: "work", generation: 0, before: "w0", messages: thread.slice(0, 0), hasMore: true });
+ await settle();
+ expect(asked).toHaveLength(4);
+ const older = Array.from({ length: 200 }, (_, index) => ({ ...thread[0]!, id: `older-${index}` }));
+ store.dispatch({ type: "olderMessages", threadId: "work", generation: 0, before: "w0", messages: older, hasMore: true });
+ await settle();
+ expect(held(store.getState()).messages).toHaveLength(220);
+ store.dispatch({ type: "select", id: "reader" });
+ store.dispatch({ type: "select", id: "worker" });
+ await settle();
+ expect(asked, "landed: nothing more to ask").toHaveLength(4);
+ stop();
+ });
+
+ it("leaves alone a whole page, a whole short conversation, and a conversation switched to since", async () => {
+ for (const bot of [tailed(200), tailed(20, false)]) {
+ const { asked, stop } = await follow({ ...initialState, bots: [bot, reader], selectedId: "worker", activeView: "chat" }, [bot]);
+ expect(asked).toEqual([]);
+ stop();
+ }
+ const switched = { ...tailed(20), messages: worker(20).messages.map((message) => ({ ...message, id: `other-${message.id}` })) };
+ const { asked, stop } = await follow({ ...initialState, bots: [switched, reader], selectedId: "worker", activeView: "chat" }, [tailed(20)]);
+ expect(asked).toEqual([]);
+ stop();
+ });
+});
diff --git a/src/state/held-tails.ts b/src/state/held-tails.ts
new file mode 100644
index 0000000000..c660aeb69a
--- /dev/null
+++ b/src/state/held-tails.ts
@@ -0,0 +1,92 @@
+import { useCallback, useSyncExternalStore } from "react";
+import { selectedOwner, shortHeld } from "./message-history";
+import type { Action, AppState, Message } from "./store";
+
+/** The conversations the last snapshot sent as a short tail, by the first row it sent, until the page before the tail
+ * lands. */
+const tails = new Map<string, string>();
+
+export function noteSnapshotTails(owners: Iterable<{ threadId: string; messages: readonly { id: string }[] }>): void {
+ tails.clear();
+ for (const owner of owners) if (owner.messages[0]) tails.set(owner.threadId, owner.messages[0].id);
+}
+
+/** How often one opening of a tail asks for the page before it: the first ask, and one more after a failed or
+ * discarded answer. */
+const ASKS_PER_OPENING = 2;
+
+/**
+ * Asks for the page before a snapshot's tail once the conversation is selected however that happens (a click, the team
+ * map's computer, a bot's settings, a deletion moving the selection), or once its branch moves anywhere but onto a new
+ * newest row (another client switching branches), since the rest of that branch may lie before the tail. Every request
+ * goes through `loadOlderMessages`; selecting it again, or another branch move, starts a fresh round of asks.
+ */
+export function followHeldTails(store: { getState(): AppState; subscribe(listener: () => void): () => void }, dispatch: (action: Action) => void): () => void {
+ const leaves = new Map<string, string | null | undefined>();
+ const asks = new Map<string, number>();
+ const moved = new Set<string>();
+ const queued = new Set<string>();
+ let selectedThread: string | undefined;
+ const check = () => {
+ if (!tails.size) return;
+ const state = store.getState();
+ const selected = selectedOwner(state);
+ if (selected?.threadId !== selectedThread) {
+ selectedThread = selected?.threadId;
+ if (selectedThread) asks.delete(selectedThread);
+ }
+ for (const owner of [...state.bots, ...state.groups]) {
+ const threadId = owner.threadId, first = tails.get(threadId);
+ if (first === undefined) continue;
+ if (owner.messages[0]?.id !== first || !shortHeld(owner)) {
+ if (asks.has(threadId)) {
+ tails.delete(threadId);
+ asks.delete(threadId);
+ moved.delete(threadId);
+ }
+ continue;
+ }
+ const leaf = "activeLeafId" in owner ? owner.activeLeafId : undefined;
+ if (leaves.has(threadId) && leaves.get(threadId) !== leaf && leaf !== owner.messages.at(-1)?.id) {
+ moved.add(threadId);
+ asks.delete(threadId);
+ }
+ leaves.set(threadId, leaf);
+ const asked = asks.get(threadId) ?? 0;
+ if ((owner !== selected && !moved.has(threadId)) || state.loadingOlder[threadId] || queued.has(threadId) || asked >= ASKS_PER_OPENING) continue;
+ asks.set(threadId, asked + 1);
+ queued.add(threadId);
+ queueMicrotask(() => {
+ queued.delete(threadId);
+ dispatch({ type: "loadOlderMessages", threadId });
+ });
+ }
+ };
+ check();
+ return store.subscribe(check);
+}
+
+/** Each pinnable page's newest version as live frames carry it, whether or not its row is held. */
+const pageVersions = new Map<string, string>();
+const pageListeners = new Set<() => void>();
+const pageKey = (threadId: string, messageId: string) => `${threadId}:${messageId}`;
+
+export function noteAppPagePatch(threadId: string, message: Pick<Message, "id" | "app">): void {
+ if (!message.app) return;
+ const version = `${message.app.doc}:${message.app.rev ?? 0}`;
+ const key = pageKey(threadId, message.id);
+ if (pageVersions.get(key) === version) return;
+ pageVersions.delete(key);
+ pageVersions.set(key, version);
+ if (pageVersions.size > 100) pageVersions.delete(pageVersions.keys().next().value!);
+ for (const listener of pageListeners) listener();
+}
+
+/** The version the newest frame gave a page in a chat, "" before any frame named it. */
+export function useAppPagePatch(threadId: string, messageId: string): string {
+ const subscribe = useCallback((listener: () => void) => {
+ pageListeners.add(listener);
+ return () => { pageListeners.delete(listener); };
+ }, []);
+ return useSyncExternalStore(subscribe, () => pageVersions.get(pageKey(threadId, messageId)) ?? "", () => "");
+}
diff --git a/src/state/message-history.ts b/src/state/message-history.ts
index 177cd9b63a..b35f9fc36f 100644
--- a/src/state/message-history.ts
+++ b/src/state/message-history.ts
@@ -1,3 +1,5 @@
+import { readTranscriptPosition } from "@/lib/transcript-follow";
+import { latestWebPanels } from "@/lib/web-panel-preferences";
import { placeUnreadDivider } from "@/lib/unread-divider";
import { api } from "./api";
import { visibleMessages } from "./snapshot-navigation";
@@ -49,10 +51,17 @@ export function trimmedHeld<T extends HeldOwner>(owner: T, keepFromId?: string):
return from > 0 ? { ...owner, messages: owner.messages.slice(from), hasMore: true } : owner;
}
+/** The selected room or bot, or the first bot when the selection names neither: what the chat and its panels show. */
+export const selectedOwner = (state: Pick<AppState, "bots" | "groups" | "selectedId">) =>
+ state.groups.find((group) => group.id === state.selectedId) ?? state.bots.find((bot) => bot.id === state.selectedId) ?? state.bots[0];
+
+/** A conversation on screen: the one the chat draws, or the chat a pinned page in the web panel comes from. */
+const shownThread = (state: AppState, threadId: string) =>
+ (state.activeView === "chat" && selectedOwner(state)?.threadId === threadId) ||
+ (state.activeView === "web-panel" && latestWebPanels().find((panel) => panel.id === state.webPanelId)?.page?.threadId === threadId);
+
export function reduceTrimHeldMessages(state: AppState, { threadId, keepFromId }: TrimHeldMessages): AppState {
- const shown = state.activeView === "chat" &&
- [...state.bots, ...state.groups].some((owner) => owner.id === state.selectedId && owner.threadId === threadId);
- if (shown) return state;
+ if (shownThread(state, threadId)) return state;
let changed = false;
const trim = <T extends HeldOwner>(owner: T): T => {
if (owner.threadId !== threadId) return owner;
@@ -65,6 +74,40 @@ export function reduceTrimHeldMessages(state: AppState, { threadId, keepFromId }
return changed ? { ...state, bots, groups } : state;
}
+/** The most rows a conversation nobody has on screen gathers from live frames before it is trimmed again. */
+export const HELD_IN_BACKGROUND = HELD_FOR_PLACE + HELD_AFTER_LEAVING;
+
+/** After a row lands in a conversation nobody has on screen: past `HELD_IN_BACKGROUND` rows it is trimmed as when the
+ * reader left it, keeping the row the reader was at; when its pinned message or branch lies further back than that
+ * keeps, it holds what a fresh snapshot would, its newest page. */
+export function capHeldInBackground(state: AppState, action: Action): AppState {
+ if (action.type !== "messageAdded") return state;
+ const owner = [...state.bots, ...state.groups].find((candidate) => candidate.threadId === action.threadId);
+ if (!owner || owner.messages.length <= HELD_IN_BACKGROUND || shownThread(state, action.threadId)) return state;
+ const place = readTranscriptPosition(`${owner.id}:${owner.threadId}`);
+ const trimmed = reduceTrimHeldMessages(state, { type: "trimHeldMessages", threadId: action.threadId, keepFromId: place?.atEnd ? undefined : place?.rowId });
+ const page = <T extends HeldOwner>(held: T): T => held.threadId === action.threadId && held.messages.length > HELD_IN_BACKGROUND
+ ? { ...held, messages: held.messages.slice(-MESSAGE_PAGE_SIZE), hasMore: true } : held;
+ return { ...trimmed, bots: trimmed.bots.map(page), groups: trimmed.groups.map(page) };
+}
+
+/** Holds fewer rows than one page while the server has more: a snapshot's tail, or a conversation switched to. */
+export const shortHeld = <T extends { messages: Message[]; hasMore?: boolean }>(owner: T | undefined): owner is T =>
+ Boolean(owner?.hasMore) && owner!.messages.length < MESSAGE_PAGE_SIZE;
+
+/** A row from before a short tail, landing in a conversation nobody has on screen (a frame queued while the snapshot was
+ * read): appended, it would read as the newest row. The page before the tail brings it in order when the tail opens.
+ * Only a row that is older than the tail and continues a row the tail does not hold counts: a row continuing the held
+ * rows is new, whatever its time says. */
+export function olderThanHeld(state: AppState, action: Action): boolean {
+ if (action.type !== "messageAdded") return false;
+ const owner = [...state.bots, ...state.groups].find((candidate) => candidate.threadId === action.threadId);
+ const first = owner?.messages[0], parentId = action.message.parentId;
+ if (!shortHeld(owner) || first === undefined || action.message.at >= first.at || typeof parentId !== "string") return false;
+ if ("activeLeafId" in owner && owner.activeLeafId === parentId) return false;
+ return !shownThread(state, action.threadId) && !owner.messages.some((message) => message.id === action.message.id || message.id === parentId);
+}
+
export function loadOlderPage(action: LoadOlderMessages, current: AppState, inFlight: Set<string>,
dispatch: (action: Action) => void, showError: (error: unknown) => void): void {
if (inFlight.has(action.threadId)) return;
diff --git a/src/state/snapshot-navigation.ts b/src/state/snapshot-navigation.ts
index 3846c6a033..c98d5965e7 100644
--- a/src/state/snapshot-navigation.ts
+++ b/src/state/snapshot-navigation.ts
@@ -22,6 +22,14 @@ export function visibleMessages(bot: Pick<Bot, "messages" | "activeLeafId">): Me
return path;
}
+/** The conversation a snapshot opens on: the one already open when the snapshot still has it, else the one to resume,
+ * else the first bot. */
+export function hydratedSelectedId(selectedId: string, bots: readonly Pick<Bot, "id" | "hidden">[], groups: readonly Pick<Group, "id">[], resumeId: string | undefined): string {
+ const known = (id: string) => bots.some((b) => b.id === id) || groups.some((g) => g.id === id);
+ const resumed = resumeId && (bots.some((b) => b.id === resumeId && !b.hidden) || groups.some((g) => g.id === resumeId)) ? resumeId : "";
+ return selectedId && known(selectedId) ? selectedId : resumed || (bots[0]?.id ?? "");
+}
+
export function navigatedSince(
owner: Pick<Bot, "threadId" | "switchingTo"> | undefined,
since: Readonly<Record<string, number>> | undefined,
diff --git a/src/state/snapshot-tail.test.ts b/src/state/snapshot-tail.test.ts
new file mode 100644
index 0000000000..0cbc7e5543
--- /dev/null
+++ b/src/state/snapshot-tail.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import { heldTail } from "../../server/host/snapshot-tail.ts";
+import { lastLine } from "@/components/sidebar-preview";
+import { endedOnFailure, stateForBot } from "@/lib/mascot";
+import { lastNonReceipt } from "@/lib/receipts";
+import { unreadDividerFor } from "@/lib/unread-divider";
+import { SNAPSHOT_TAIL } from "./chat-snapshot";
+import { MESSAGE_PAGE_SIZE } from "./message-history";
+import { visibleMessages } from "./snapshot-navigation";
+import type { Bot, Message } from "./store";
+
+type Row = Message & { parentId: string | null };
+type Page = { messages: Row[]; hasMore: boolean; activeLeafId: string | null };
+
+/** A conversation of `count` rows from a seeded mix of the person, other bots, replies, tool steps, screens and
+ * receipts, with an edit now and then that starts a branch. */
+function conversation(seed: number, count: number, kinds: { person: number; tool: number }): { rows: Row[]; leaf: string | null } {
+ let state = seed;
+ const random = () => ((state = (state * 1_103_515_245 + 12_345) % 2 ** 31) / 2 ** 31);
+ const rows: Row[] = [];
+ let leaf: string | null = null;
+ for (let index = 0; index < count; index++) {
+ const id = `s${seed}-${index}`;
+ const roll = random();
+ const edit = rows.length > 4 && random() < 0.02;
+ const parentId = edit ? rows[rows.length - 3]!.parentId : leaf;
+ const base = { id, at: index, parentId };
+ const row: Row = roll < kinds.person ? { ...base, role: "user", kind: "text", text: `ask ${index}` }
+ : roll < kinds.person + 0.03 ? { ...base, role: "user", kind: "text", text: `[From @Scout (bot) · message · reply expected] help ${index}` }
+ : roll < kinds.person + 0.03 + kinds.tool ? { ...base, role: "bot", kind: "activity", tool: { name: "Bash", ok: random() > 0.1, input: "{}" } }
+ : roll < kinds.person + 0.08 + kinds.tool ? { ...base, role: "bot", kind: random() < 0.5 ? "screen" : "digest" }
+ : { ...base, role: "bot", kind: "text", text: `reply ${index}` };
+ rows.push(row as Row);
+ leaf = id;
+ }
+ if (seed % 7 === 0 && rows.length > 40) leaf = rows[rows.length - 30]!.id;
+ return { rows, leaf };
+}
+
+const pageOf = ({ rows, leaf }: { rows: Row[]; leaf: string | null }) => (limit: number): Page =>
+ ({ messages: rows.slice(-limit), hasMore: rows.length > limit, activeLeafId: leaf });
+
+/** Everything a client reads from a conversation it holds but does not show. */
+function reads(page: Page, cursor: string | undefined) {
+ const bot = { id: "b", name: "Scout", threadId: "t", messages: page.messages, activeLeafId: page.activeLeafId, hasMore: page.hasMore } as unknown as Bot;
+ const shown = visibleMessages(bot);
+ return {
+ simplePreview: lastLine(bot, shown, [], false),
+ advancedPreview: lastLine(bot, shown, [], true),
+ divider: unreadDividerFor("t", shown, cursor, page.hasMore)?.messageId ?? null,
+ mascot: lastNonReceipt(page.messages)?.id,
+ sidebarMascot: stateForBot({ ...bot, messages: shown }),
+ sidebarFailed: endedOnFailure(shown),
+ lastPersonRole: page.messages.findLast((message) => message.role === "user")?.id,
+ lastTool: page.messages.findLast((message) => message.kind === "activity" && message.tool)?.id,
+ };
+}
+
+describe("a snapshot's tail of a conversation nobody has open", () => {
+ const mixes = [{ person: 0.1, tool: 0.5 }, { person: 0.01, tool: 0.7 }, { person: 0, tool: 0.3 }, { person: 0.3, tool: 0 }, { person: 0.02, tool: 0 }];
+
+ it("reads the same preview, divider, mascot, team-map step and last person line as a whole page", () => {
+ let tailed = 0;
+ for (let seed = 1; seed <= 120; seed++) {
+ const mix = mixes[seed % mixes.length]!;
+ const thread = conversation(seed, 30 + ((seed * 37) % 400), mix);
+ const read = pageOf(thread);
+ const cursors = [undefined, thread.rows[Math.floor(thread.rows.length * 0.4)]!.id, thread.rows.at(-5)!.id];
+ for (const cursor of cursors) {
+ const tail = heldTail(read, SNAPSHOT_TAIL, MESSAGE_PAGE_SIZE, cursor);
+ const page = read(MESSAGE_PAGE_SIZE);
+ expect(page.messages.slice(-tail.messages.length)).toEqual(tail.messages);
+ expect(tail.messages.length).toBeGreaterThanOrEqual(Math.min(SNAPSHOT_TAIL, thread.rows.length));
+ expect(reads(tail, cursor), `seed ${seed}, cursor ${cursor}`).toEqual(reads(page, cursor));
+ if (tail.messages.length < page.messages.length) {
+ tailed++;
+ expect(tail.hasMore).toBe(true);
+ }
+ }
+ }
+ expect(tailed).toBeGreaterThan(100);
+ });
+
+ it("stops at the floor when the person spoke last, and reaches back past other bots' lines to the person's", () => {
+ const rows = Array.from({ length: 300 }, (_, index) => ({ id: `m${index}`, at: index, parentId: index ? `m${index - 1}` : null, role: "bot", kind: "activity", tool: { name: "Bash", ok: true, input: "{}" } })) as Row[];
+ rows[299] = { ...rows[299]!, role: "user", kind: "text", text: "next?", tool: undefined };
+ expect(heldTail(pageOf({ rows, leaf: "m299" }), 20, 200).messages).toHaveLength(20);
+
+ rows[299] = { ...rows[299]!, text: "[From @Scout (bot) · message · reply expected] hi" };
+ rows[250] = { ...rows[250]!, role: "user", kind: "text", text: "do it", tool: undefined };
+ rows[270] = { ...rows[270]!, role: "bot", kind: "text", text: "done", tool: undefined };
+ const tail = heldTail(pageOf({ rows, leaf: "m299" }), 20, 200);
+ expect(tail.messages[0]!.id).toBe("m250");
+ expect(tail.hasMore).toBe(true);
+ });
+
+ it("reaches back at most one page, and sends a conversation shorter than the floor whole", () => {
+ const rows = Array.from({ length: 500 }, (_, index) => ({ id: `m${index}`, at: index, parentId: index ? `m${index - 1}` : null, role: "bot", kind: "activity", tool: { name: "Bash", ok: true, input: "{}" } })) as Row[];
+ const withPerson = (at: number) => rows.map((row, index) => index === at ? { ...row, role: "user", kind: "text", text: "go", tool: undefined } as Row : row);
+ expect(heldTail(pageOf({ rows: withPerson(320), leaf: "m499" }), 20, 200).messages[0]!.id).toBe("m320");
+ expect(heldTail(pageOf({ rows: withPerson(150), leaf: "m499" }), 20, 200).messages).toHaveLength(20);
+ const short = rows.slice(0, 12);
+ expect(heldTail(pageOf({ rows: short, leaf: "m11" }), 20, 200)).toEqual({ messages: short, hasMore: false, activeLeafId: "m11" });
+ });
+});
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 6c23f55042..4a50b87f64 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -1,6 +1,8 @@
import { cloudAsleep, onCloudPower } from "../lib/cloud-power";
import { api, ApiError, retryRequest, snapshotArrays } from "./api";
-import { loadOlderPage, MESSAGE_PAGE_SIZE, reduceOlderMessages, reduceTrimHeldMessages } from "./message-history";
+import { capHeldInBackground, loadOlderPage, MESSAGE_PAGE_SIZE, olderThanHeld, reduceOlderMessages, reduceTrimHeldMessages } from "./message-history";
+import { readChatSnapshot } from "./chat-snapshot";
+import { followHeldTails, noteAppPagePatch } from "./held-tails";
export { MESSAGE_PAGE_SIZE } from "./message-history";
import { addForkOptimistic, reduceForkPanel, removeForkOptimistic, runForkEffect, type ForkPanelAction, type ForkPanelState } from "./fork-panel";
import { use, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
@@ -20,7 +22,7 @@ import type { EngineInstall } from "./engine-install";
import { optimisticMessageId, optimisticUserMessage, sendArrived, sendReconciled } from "./optimistic-send";
import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";
import { savedStateAction, type SavedOwner, type SavedSnapshot } from "./saved-state";
-import { keepBotNavigation, keepGroupNavigation, navigatedSince, visibleMessages } from "./snapshot-navigation";
+import { hydratedSelectedId, keepBotNavigation, keepGroupNavigation, navigatedSince, visibleMessages } from "./snapshot-navigation";
export { visibleMessages } from "./snapshot-navigation";
export { awayFromMainThread, botOpensTo, markedThread, openBot, openBotRow, openBotThread, openRoomThread, openThread, visibleNotificationThread, type ThreadTarget } from "./thread-navigation";
import type { TurnDigest } from "../../shared/digest";
@@ -855,7 +857,8 @@ function dismissOnboardingCard(state: AppState, botId: string): AppState {
export const CLOUD_LINK_SETTINGS = { type: "toggleAppSettings", open: true, section: "cloudAccount", cloudLink: true } as const satisfies Action;
-export function reducer(state: AppState, action: Action): AppState {
+export function reducer(state: AppState, action: Action): AppState { return olderThanHeld(state, action) ? state : capHeldInBackground(reduceApp(state, action), action); }
+function reduceApp(state: AppState, action: Action): AppState {
const [newChatState, newChatOnly] = reduceNewChat(state, action); if (newChatOnly) return newChatState; state = newChatState;
if (action.type === "optimisticMessageRemoved") state = removeForkOptimistic(state, action);
if (action.type === "messageAdded" || action.type === "messagePatched" || action.type === "threadActive" || action.type === "optimisticMessageRemoved") {
@@ -871,11 +874,7 @@ export function reducer(state: AppState, action: Action): AppState {
if (isNotificationFeedAction(action)) return { ...state, notifications: reduceNotificationFeed(state.notifications, action) };
switch (action.type) {
case "hydrate": {
- const known = (id: string) => action.bots.some((b) => b.id === id) || action.groups.some((g) => g.id === id);
- const resume = action.resumeId;
- const resumed =
- resume && (action.bots.some((b) => b.id === resume && !b.hidden) || action.groups.some((g) => g.id === resume)) ? resume : "";
- const selectedId = state.selectedId && known(state.selectedId) ? state.selectedId : resumed || (action.bots[0]?.id ?? "");
+ const selectedId = hydratedSelectedId(state.selectedId, action.bots, action.groups, action.resumeId);
const hydrated = {
...state,
bots: action.bots.map((sent) => {
@@ -2255,7 +2254,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
if (previousOpened !== opened && cur.notice?.threadId && opened && cur.notice.threadId !== opened) rawDispatch({ type: "notice", notice: null });
switch (action.type) {
case "loadOlderMessages": {
- loadOlderPage(action, stateRef.current, olderPagesInFlight, rawDispatch, showError);
+ loadOlderPage(action, store.getState(), olderPagesInFlight, rawDispatch, showError);
break;
}
case "notice":
@@ -2846,6 +2845,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
};
return wrapped;
}, [botPatchQueue]);
+ useEffect(() => followHeldTails(store, dispatch), [store, dispatch]);
const launched = useRef(false);
useEffect(() => {
@@ -2974,7 +2974,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
})
.catch(() => {});
const chat = () =>
- api(`/api/bots?messages=${MESSAGE_PAGE_SIZE}`).then((answer) => snapshotArrays(answer, "bots")).then(({ bots, groups, sections, computerControl, botQueuedMessages }) => {
+ readChatSnapshot(store.getState, readLastConversation() ?? undefined).then(({ bots, groups, sections, computerControl, botQueuedMessages }) => {
if (!alive) return;
rawDispatch({
type: "hydrate",
@@ -3082,6 +3082,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
case "message.patch":
rawDispatch({ type: "messagePatched", threadId: frame.threadId, message: frame.message as Message });
rawDispatch({ type: "forkPanelMessage", threadId: frame.threadId, message: frame.message as Message, patch: true });
+ noteAppPagePatch(frame.threadId, frame.message as Message);
break;
case "thread":
rawDispatch({ type: "threadActive", threadId: frame.threadId, activeLeafId: frame.activeLeafId });
diff --git a/src/state/tail-review.test.ts b/src/state/tail-review.test.ts
new file mode 100644
index 0000000000..1bbd17ed7e
--- /dev/null
+++ b/src/state/tail-review.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from "vitest";
+import { heldTail } from "../../server/host/snapshot-tail.ts";
+import { lastLine } from "@/components/sidebar-preview";
+import { stateForBot } from "@/lib/mascot";
+import { visibleMessages } from "@/state/snapshot-navigation";
+import { recentChangedFiles } from "@/components/ComputerFilesPane";
+import { createAppStore } from "@/state/app-store";
+import { followHeldTails, noteSnapshotTails } from "@/state/held-tails";
+import { HELD_IN_BACKGROUND } from "@/state/message-history";
+import { initialState, reducer, type Action, type AppState, type Bot, type Message } from "@/state/store";
+
+type Row = Message & { parentId: string | null };
+
+describe("review: heldTail", () => {
+ it("a thread with no active leaf (legacy rows) and no person line in the last 20 rows still gets a short tail", () => {
+ const rows: Row[] = Array.from({ length: 300 }, (_, i) => ({ id: `r${i}`, at: i, parentId: null, role: "bot", kind: "text", text: `t${i}` }) as Row);
+ const read = (limit: number) => ({ messages: rows.slice(-limit), hasMore: rows.length > limit, activeLeafId: null });
+ const tail = heldTail(read, 20, 200);
+ expect(tail.messages.length).toBeLessThanOrEqual(20);
+ });
+});
+
+describe("review: a branch switch from another client on a tailed conversation", () => {
+ // Original branch o0..o59 (o10 is a person line). The person edited o10 -> e0 (parent o9), and the bot answered e1..e39.
+ const original: Row[] = Array.from({ length: 60 }, (_, i) => ({ id: `o${i}`, at: i, parentId: i ? `o${i - 1}` : null,
+ role: i === 10 ? "user" : "bot", kind: "text", text: i === 59 ? "ORIGINAL BRANCH END" : `o${i}` }) as Row);
+ const edited: Row[] = Array.from({ length: 40 }, (_, i) => ({ id: `e${i}`, at: 100 + i, parentId: i ? `e${i - 1}` : "o9",
+ role: i === 0 ? "user" : "bot", kind: "text", text: i === 39 ? "EDITED BRANCH END" : `e${i}` }) as Row);
+ const all = [...original, ...edited];
+ const bot = (messages: Row[], hasMore: boolean): Bot => ({ id: "b", name: "Scout", threadId: "t", messages, hasMore, activeLeafId: "e39", tasks: [] }) as unknown as Bot;
+ const other = { id: "o", name: "Other", threadId: "ot", messages: [], hasMore: false, tasks: [] } as unknown as Bot;
+ const read = (limit: number) => ({ messages: all.slice(-limit), hasMore: all.length > limit, activeLeafId: "e39" });
+
+ it("shows the same sidebar line and mascot as a whole page after the phone switches back to the original branch", () => {
+ const tail = heldTail(read, 20, 200);
+ const page = read(200);
+ const look = (b: Bot) => ({ line: lastLine(b, visibleMessages(b), [], true), mascot: stateForBot({ ...b, messages: visibleMessages(b) }) });
+ const after = (b: Bot) => {
+ const state: AppState = { ...initialState, bots: [b, other], selectedId: "o", activeView: "chat" };
+ return reducer(state, { type: "threadActive", threadId: "t", activeLeafId: "o59" }).bots[0]!;
+ };
+ expect(tail.messages.length).toBeLessThan(page.messages.length);
+ expect(look(after(bot(page.messages, page.hasMore))).line).toBe("ORIGINAL BRANCH END");
+ expect(look(after(bot(tail.messages, true))).line).toBe("ORIGINAL BRANCH END");
+ });
+});
+
+describe("review: the background cap", () => {
+ const row = (i: number): Message => ({ id: `w${i}`, at: i, parentId: i ? `w${i - 1}` : null, role: "bot", kind: "text", text: `l${i}` }) as Message;
+ const reader = { id: "reader", threadId: "read", name: "Reader", messages: [], hasMore: false, tasks: [] } as unknown as Bot;
+ it("still holds when the conversation has a pinned message more than 600 rows back", () => {
+ const messages = Array.from({ length: HELD_IN_BACKGROUND }, (_, i) => row(i));
+ const worker = { id: "worker", threadId: "work", name: "Worker", messages, hasMore: false, activeLeafId: messages.at(-1)!.id, pinnedMessageId: "w5", tasks: [] } as unknown as Bot;
+ let state: AppState = { ...initialState, bots: [worker, reader], selectedId: "reader", activeView: "chat" };
+ for (let i = HELD_IN_BACKGROUND; i < HELD_IN_BACKGROUND + 500; i++) state = reducer(state, { type: "messageAdded", threadId: "work", message: row(i) });
+ expect(state.bots[0]!.messages.length).toBeLessThanOrEqual(HELD_IN_BACKGROUND);
+ });
+});
+
+describe("review: a queued frame older than the snapshot's tail", () => {
+ it("lands where it belongs, not after the newest row", () => {
+ const row = (i: number, kind = "activity"): Message => ({ id: `r${i}`, at: i, parentId: i ? `r${i - 1}` : null, role: i === 0 ? "user" : "bot", kind,
+ text: `r${i}`, ...(kind === "activity" ? { tool: { name: `step ${i}`, ok: true, input: "{}" } } : {}) }) as Message;
+ // The snapshot sent r11..r30; r5 was queued from the stream while it was read.
+ const tail = Array.from({ length: 20 }, (_, k) => row(11 + k));
+ const bot = { id: "b", threadId: "t", name: "B", messages: tail, hasMore: true, activeLeafId: "r30", tasks: [] } as unknown as Bot;
+ const other = { id: "o", threadId: "ot", name: "O", messages: [], hasMore: false, tasks: [] } as unknown as Bot;
+ let state: AppState = { ...initialState, bots: [bot, other], selectedId: "o", activeView: "chat" };
+ state = reducer(state, { type: "messageAdded", threadId: "t", message: row(5) });
+ const held = state.bots[0]!;
+ expect(held.messages.findLast((m) => m.kind === "activity" && m.tool)?.id).toBe("r30");
+ });
+});
+
+describe("review: the Computer panel's recently changed files on a tailed bot (opened from the Team map, no chat drawn)", () => {
+ it("lists the same files as a whole page once the bot is selected and the page before its tail lands", async () => {
+ const rows: Row[] = [];
+ let parent: string | null = null;
+ const push = (r: Partial<Row>) => { const id = `x${rows.length}`; rows.push({ id, at: rows.length, parentId: parent, ...r } as Row); parent = id; };
+ for (let turn = 0; turn < 3; turn++) {
+ push({ role: "user", kind: "text", text: `do ${turn}` });
+ for (let s = 0; s < 12; s++) push({ role: "bot", kind: "activity", tool: { name: "Edit", ok: true, input: "{}" } } as Partial<Row>);
+ push({ role: "bot", kind: "text", text: `done ${turn}` });
+ push({ role: "bot", kind: "digest", digest: { files: { added: [`file-${turn}.ts`], changed: [], deleted: [] } } } as unknown as Partial<Row>);
+ }
+ const read = (limit: number) => ({ messages: rows.slice(-limit), hasMore: rows.length > limit, activeLeafId: parent });
+ const asBot = (p: { messages: Row[]; activeLeafId: string | null; hasMore: boolean }) => ({ id: "b", threadId: "t", name: "B", messages: p.messages, activeLeafId: p.activeLeafId, hasMore: p.hasMore, tasks: [] }) as unknown as Bot;
+ const other = { id: "o", threadId: "ot", name: "O", messages: [], hasMore: false, tasks: [] } as unknown as Bot;
+ const tail = asBot(heldTail(read, 20, 200));
+ expect(tail.messages.length).toBeLessThan(rows.length);
+
+ const store = createAppStore<AppState, Action, never>(reducer, { ...initialState, bots: [other, tail], selectedId: "o", activeView: "team-map" }, () => () => {});
+ const asked: Action[] = [];
+ noteSnapshotTails([tail]);
+ const stop = followHeldTails(store, (action) => asked.push(action));
+ store.dispatch({ type: "toggleComputer", botId: "b", open: true });
+ await Promise.resolve();
+ expect(asked).toEqual([{ type: "loadOlderMessages", threadId: "t" }]);
+ const first = tail.messages[0]!.id;
+ const at = rows.findIndex((r) => r.id === first);
+ store.dispatch({ type: "olderMessages", threadId: "t", generation: 0, before: first, messages: rows.slice(Math.max(0, at - 200), at), hasMore: at > 200 });
+ const held = store.getState().bots.find((b) => b.id === "b")!;
+ expect(recentChangedFiles(held)).toEqual(recentChangedFiles(asBot({ ...read(200), activeLeafId: parent })));
+ stop();
+ });
+});
+
+describe("review: a genuinely new row whose server time is behind the tail's first row", () => {
+ const rows = Array.from({ length: 20 }, (_, k) => ({ id: `r${k}`, at: 1_000_000 + k, parentId: k ? `r${k - 1}` : "r-1", role: "bot", kind: "text", text: `r${k}` }) as Message);
+ const bot = { id: "b", threadId: "t", name: "B", messages: rows, hasMore: true, activeLeafId: "r19", tasks: [] } as unknown as Bot;
+ const other = { id: "o", threadId: "ot", name: "O", messages: [], hasMore: false, tasks: [] } as unknown as Bot;
+ const land = (message: Partial<Message>) => reducer({ ...initialState, bots: [bot, other], selectedId: "o", activeView: "chat" },
+ { type: "messageAdded", threadId: "t", message: { id: "new", at: 999_000, role: "bot", kind: "text", text: "NEW REPLY", ...message } as Message }).bots[0]!;
+
+ it("is kept (server clock stepped back a second)", () => {
+ expect(land({ parentId: "r19" }).messages.at(-1)?.id).toBe("new");
+ });
+
+ it("is kept when it continues any held row, or names no parent at all", () => {
+ expect(land({ parentId: "r7" }).messages.at(-1)?.id).toBe("new");
+ expect(land({ parentId: null }).messages.at(-1)?.id).toBe("new");
+ expect(land({}).messages.at(-1)?.id).toBe("new");
+ });
+});