Skip to content

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

perf: snapshot live activity for thread list pages

vincent3f6b5a681270
diff --git a/server/coordinator.ts b/server/coordinator.ts
index 5425be54cd..7407b644c8 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -194,6 +194,10 @@ export interface Coordinator {
* finished before that time. Reads only that thread's rows. */
inThread(threadId: string, filter?: { open?: boolean; since?: number }): HandoffView[];
active(): HandoffView[];
+ /** Live thread facts for a list page, including the first queued handoff per bot and thread. */
+ threadActivity(threads: ReadonlyMap<string, ReadonlySet<string>>): {
+ awaitingAnswer: Set<string>; activeDirect: Set<string>; queued: Map<string, Map<string, HandoffView>>;
+ };
children(id: string): HandoffView[];
/** A generation with no root is refused; throws an Error whose message is the typed refusal shown to the model. */
enqueue(source: RoomAddress, generation: string, parentId: string | undefined, target: RoomAddress, text: string,
diff --git a/server/routes/internal-threads.test.ts b/server/routes/internal-threads.test.ts
index e34b2011e2..1dbd1058ef 100644
--- a/server/routes/internal-threads.test.ts
+++ b/server/routes/internal-threads.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import type { HandoffView } from "../coordinator.ts";
+import type { CoordinatorHost, HandoffView } from "../coordinator.ts";
+import { RuntimeCoordinator } from "../runtime-coordinator.ts";
+import * as runtimeStores from "../runtime/store.ts";
+import type { Assignment } from "../runtime/types.ts";
import type { BotRecord, TaskRecord } from "../store.ts";
import { createInternalThreadRoutes } from "./internal-threads.ts";
@@ -21,7 +24,8 @@ const tasks: Record<string, TaskRecord[]> = {
async function listThreads(from: BotRecord) {
const route = createInternalThreadRoutes({
store: { bot: (id: string) => [lead, ops].find((bot) => bot.id === id), bots: [lead, ops], tasks: (id: string) => tasks[id] ?? [] } as never,
- coordinator: { awaitingAnswer: () => false, parkedDirect: () => undefined, activeDirect: (threadId: string) => threadId === "t-ops-new" ? handoff : undefined, active: () => [handoff] } as never,
+ coordinator: { awaitingAnswer: () => false, activeDirect: () => false,
+ threadActivity: () => ({ awaitingAnswer: new Set(), activeDirect: new Set(["t-ops-new"]), queued: new Map([["t-ops-new", new Map([[ops.id, handoff]])]]) }) },
from, fromThreadId: "t-own", ownsThread: () => true, shown: () => true, mainThreadTasks: () => [],
threadBusy: (_bot, threadId) => threadId === "t-ops-busy", queuedThreadPosition: () => null,
queuedReason: (node, showTitle) => `${node.id} waits${showTitle ? " (titles)" : ""}`,
@@ -54,16 +58,16 @@ describe("list_threads on a queued handoff", () => {
});
describe("list_threads past the first 100", () => {
- async function page(query: string) {
- const many = Array.from({ length: 130 }, (_, index) => task(`t-${index}`, `Event ${index}`, undefined));
- many.forEach((row, index) => { row.createdAt = index; });
+ async function page(query: string, busy: (threadId: string) => boolean = () => false) {
+ const many = Array.from({ length: 130 }, (_, index) => ({ ...task(`t-${index}`, `Event ${index}`), createdAt: index }));
const route = createInternalThreadRoutes({
store: { bot: () => undefined, bots: [lead], tasks: (id: string) => id === lead.id ? many : [] } as never,
- coordinator: { awaitingAnswer: () => false, parkedDirect: () => undefined, activeDirect: () => undefined, active: () => [] } as never,
+ coordinator: { awaitingAnswer: () => false, activeDirect: () => false,
+ threadActivity: () => ({ awaitingAnswer: new Set(), activeDirect: new Set(), queued: new Map() }) },
from: lead, fromThreadId: "t-own", ownsThread: () => true, shown: () => true, mainThreadTasks: () => [],
- threadBusy: () => false, queuedThreadPosition: () => null, queuedReason: () => "", readBody: async () => ({}),
+ threadBusy: (_botId, threadId) => busy(threadId), queuedThreadPosition: () => null, queuedReason: () => "", readBody: async () => ({}),
});
- let body: { threads: Array<{ threadId: string }>; total: number; page: number; pageSize: number } | undefined;
+ let body: { threads: Array<{ threadId: string; state: string }>; total: number; page: number; pageSize: number } | undefined;
await route({ res: {}, url: new URL(`http://x/api/internal/threads${query}`), path: "/api/internal/threads", method: "GET",
json: (_res: unknown, _status: number, value: never) => { body = value; } } as never);
return body!;
@@ -79,6 +83,101 @@ describe("list_threads past the first 100", () => {
expect(second.threads.map((thread) => thread.threadId)).toEqual(Array.from({ length: 30 }, (_, index) => `t-${29 - index}`));
expect((await page("?page=0")).page).toBe(1);
});
+
+ it("only looks up live state for threads returned by the requested page", async () => {
+ const lookedUp = new Set<string>();
+ const second = await page("?page=2", (threadId) => {
+ lookedUp.add(threadId);
+ return threadId === "t-29";
+ });
+
+ expect(second.threads[0]).toMatchObject({ threadId: "t-29", state: "running" });
+ expect(lookedUp).toEqual(new Set(Array.from({ length: 30 }, (_, index) => `t-${index}`)));
+ });
+});
+
+describe("list_threads with the real runtime store", () => {
+ it("reads the live assignments once for a full page without changing their states or queue details", async () => {
+ const stores: runtimeStores.RuntimeStore[] = [];
+ const open = runtimeStores.openRuntimeStore;
+ const factory = vi.spyOn(runtimeStores, "openRuntimeStore").mockImplementation((path) => {
+ const store = open(path);
+ stores.push(store);
+ return store;
+ });
+ const host: CoordinatorHost = {
+ validate: () => undefined, busy: () => false, run: async () => ({ ok: true, text: "" }),
+ report: () => {}, changed: () => {}, names: () => ({ requester: "Lead", assignee: "Lead" }),
+ park: () => {}, levelOf: () => ({ level: "ask" }), chiefOf: () => false,
+ };
+ const coordinator = new RuntimeCoordinator({ dataDir: ":memory:", host });
+ factory.mockRestore();
+ try {
+ coordinator.active();
+ const runtime = stores[0];
+ if (!runtime) throw new Error("runtime store was not opened");
+ const insert = (id: string, threadId: string, patch: Partial<Assignment> = {}) => {
+ const row: Assignment = {
+ id, rootId: id, depth: 0, origin: { kind: "person", source: "chat" }, requester: { kind: "person" },
+ assignee: { botId: lead.id, destination: { kind: "standing_thread", threadId } },
+ mode: "work", reply: "resume", brief: "", status: "queued", level: "ask", levelSource: "own",
+ executions: 0, restarts: 0, createdAt: 10, lastActivityAt: 10, result: "", rework: false, version: 1, ...patch,
+ };
+ runtime.insert(row, { kind: "enqueued", at: 10 });
+ };
+ const many = Array.from({ length: 100 }, (_, index) => ({ ...task(`t-${index}`, `Event ${index}`), createdAt: index }));
+ many[96] = { ...many[96], activity: "waiting-on-you", closedBy: { botId: lead.id, name: lead.name, at: 2 } };
+ many[92] = { ...many[92], activity: "waiting-on-you", closedBy: { botId: lead.id, name: lead.name, at: 2 } };
+ insert("finished-parent", "t-95", { status: "completed", assignee: { botId: lead.id, destination: { kind: "room_thread", threadId: "t-95", groupId: "" } } });
+ insert("empty-group-first", "t-95", { parentId: "finished-parent", createdAt: 1, assignee: { botId: lead.id, destination: { kind: "room_thread", threadId: "t-95", groupId: "" } } });
+ insert("empty-group-only", "t-94", { assignee: { botId: lead.id, destination: { kind: "room_thread", threadId: "t-94", groupId: "" } } });
+ for (let i = 0; i < 100; i++) if (![92, 94, 96, 97, 98].includes(i)) insert(`queued-${i}`, `t-${i}`);
+ insert("first-queued", "t-90", { createdAt: 1 });
+ insert("wrong-bot-queued", "t-peer", { createdAt: 0 });
+ insert("peer-first", "t-peer", { createdAt: 1, assignee: { botId: ops.id, destination: { kind: "standing_thread", threadId: "t-peer" } } });
+ insert("peer-later", "t-peer", { createdAt: 2, assignee: { botId: ops.id, destination: { kind: "standing_thread", threadId: "t-peer" } } });
+ const peer = task("t-peer", "Peer", { botId: lead.id, name: lead.name, at: 100 });
+ insert("group-parked", "t-99", { status: "needs_input", assignee: { botId: lead.id, destination: { kind: "room_thread", threadId: "t-99", groupId: "g" } } });
+ insert("waiting-for-child", "t-98", { status: "waiting", question: "stale question" });
+ insert("direct-parked", "t-96", { status: "needs_input" });
+ insert("source", "t-97", { status: "running", executions: 1, createdAt: 1 });
+ const route = createInternalThreadRoutes({
+ store: { bot: () => undefined, bots: [lead, ops], tasks: (id: string) => id === lead.id ? many : [peer] } as never,
+ coordinator, from: lead, fromThreadId: "t-own", ownsThread: () => true, shown: () => true, mainThreadTasks: () => [],
+ threadBusy: (_botId, threadId) => threadId === "t-99" || threadId === "t-98",
+ queuedThreadPosition: () => null, queuedReason: (node, showTitle) => `${node.id}:${node.kind}:${showTitle ? "own" : "peer"}`, readBody: async () => ({}),
+ });
+ const all = vi.spyOn(runtime, "all");
+ try {
+ let body: { threads: Array<Record<string, unknown>>; total: number; page: number } | undefined;
+ await route({ res: {}, url: new URL("http://x/api/internal/threads"), path: "/api/internal/threads", method: "GET",
+ json: (_res: unknown, _status: number, value: never) => { body = value; } } as never);
+ expect(body).toMatchObject({ total: 101, page: 1 });
+ const rows = body?.threads ?? [];
+ expect(rows).toHaveLength(100);
+ expect(rows.find(row => row.threadId === "t-99")).toMatchObject({ state: "waiting-on-you" });
+ expect(rows.find(row => row.threadId === "t-98")).toMatchObject({ state: "running" });
+ expect(rows.find(row => row.threadId === "t-96")).toMatchObject({ state: "waiting-on-you" });
+ expect(rows.find(row => row.threadId === "t-92")).toMatchObject({ state: "closed" });
+ expect(rows.find(row => row.threadId === "t-94")).toMatchObject({ state: "idle" });
+ expect(rows.find(row => row.threadId === "t-97")).toMatchObject({ state: "queued", delegationId: undefined });
+ expect(rows.find(row => row.threadId === "t-95")).toMatchObject({ state: "queued", delegationId: "empty-group-first", waiting: "empty-group-first:assignment:own" });
+ expect(rows.find(row => row.threadId === "t-90")).toMatchObject({ state: "queued", delegationId: "first-queued", waiting: "first-queued:work:own" });
+ expect(rows.find(row => row.threadId === "t-peer")).toMatchObject({ botId: ops.id, own: false, state: "queued", delegationId: "peer-first", waiting: "peer-first:work:peer" });
+ const liveReads = all.mock.calls.filter(([filter]) => filter?.nonTerminal === true);
+ expect(liveReads).toHaveLength(1);
+ all.mockClear();
+ await route({ res: {}, url: new URL("http://x/api/internal/threads?page=3"), path: "/api/internal/threads", method: "GET",
+ json: (_res: unknown, _status: number, value: never) => { body = value; } } as never);
+ expect(body).toMatchObject({ threads: [], total: 101, page: 3 });
+ expect(all.mock.calls.filter(([filter]) => filter?.nonTerminal === true)).toHaveLength(0);
+ } finally {
+ all.mockRestore();
+ }
+ } finally {
+ coordinator.close();
+ }
+ });
});
describe("rename_thread on the conversation the turn speaks in", () => {
diff --git a/server/routes/internal-threads.ts b/server/routes/internal-threads.ts
index b7731a94dd..46f3ab06e0 100644
--- a/server/routes/internal-threads.ts
+++ b/server/routes/internal-threads.ts
@@ -25,7 +25,7 @@ interface ThreadRow {
/** Only dispatch inside the internal capability gate: `from` and `fromThreadId` come from the caller's capability. */
export function createInternalThreadRoutes(deps: {
store: Pick<Store, "bot" | "bots" | "tasks" | "taskByThread" | "appendMessage" | "patchTask" | "setTaskClosedBy" | "renameTask" | "patchBot" | "groupByThread" | "groupTaskByThread">;
- coordinator: Pick<Coordinator, "awaitingAnswer" | "parkedDirect" | "activeDirect" | "active">;
+ coordinator: Pick<Coordinator, "threadActivity" | "awaitingAnswer" | "activeDirect">;
from: BotRecord;
fromThreadId: string;
ownsThread(botId: string, threadId: string): boolean;
@@ -47,30 +47,9 @@ export function createInternalThreadRoutes(deps: {
if (!deps.ownsThread(from.id, fromThreadId)) {
return json(res, 403, { error: "source conversation does not belong to sender" });
}
- const rows: ThreadRow[] = [];
- const stateOf = (bot: BotRecord, task: TaskRecord) => {
- if ((!task.closedBy && task.activity === "waiting-on-you") || coordinator.awaitingAnswer(task.threadId)) return "waiting-on-you" as const;
- if (deps.threadBusy(bot.id, task.threadId)) return "running" as const;
- if (coordinator.parkedDirect(task.threadId)) return "waiting-on-you" as const;
- if (deps.queuedThreadPosition(bot.id, task.threadId) !== null) return "queued" as const;
- if (coordinator.activeDirect(task.threadId)) return "queued" as const;
- if (task.closedBy) return "closed" as const;
- return "idle" as const;
- };
- // A queued handoff says why it waits and which handoff it is, so a bot can tell the person and match a report.
- const queued = (bot: BotRecord, task: TaskRecord, state: ThreadState): Pick<ThreadRow, "waiting" | "delegationId"> => {
- const node = state === "queued" ? coordinator.active().find((n) => n.threadId === task.threadId && n.botId === bot.id && !n.groupId && n.status === "queued") : undefined;
- return node ? { waiting: deps.queuedReason(node, bot.id === from.id ? deps.shown : undefined), delegationId: node.id } : {};
- };
+ const visible: { bot: BotRecord; task: TaskRecord; openedAt: number; openedBy?: string }[] = [];
for (const task of store.tasks(from.id)) {
- if (!deps.shown(task.threadId)) continue;
- const state = stateOf(from, task);
- rows.push({
- threadId: task.threadId, botId: from.id, botName: from.name, title: task.title,
- state, unread: task.unread === true, openedAt: task.openedBy?.at ?? task.createdAt,
- delegationId: task.openedBy?.delegationId, own: true, ...queued(from, task, state),
- ...(task.archivedAt !== undefined ? { archived: true as const } : {}),
- });
+ if (deps.shown(task.threadId)) visible.push({ bot: from, task, openedAt: task.openedBy?.at ?? task.createdAt });
}
for (const peer of reachablePeers(store.bots, from)) {
for (const task of store.tasks(peer.id)) {
@@ -78,20 +57,36 @@ export function createInternalThreadRoutes(deps: {
if (!opener || !deps.shown(task.threadId)) continue;
const mine = opener.botId === from.id;
if (!mine && !chiefTidies(from, task, store.bot(opener.botId), peer)) continue;
- const state = stateOf(peer, task);
- rows.push({
- threadId: task.threadId, botId: peer.id, botName: peer.name, title: task.title,
- state, unread: task.unread === true, openedAt: opener.at,
- delegationId: opener.delegationId, own: false, ...queued(peer, task, state),
- ...(mine ? {} : { openedBy: opener.name }), ...(task.archivedAt !== undefined ? { archived: true as const } : {}),
- });
+ visible.push({ bot: peer, task, openedAt: opener.at, ...(mine ? {} : { openedBy: opener.name }) });
}
}
- rows.sort((a, b) => b.openedAt - a.openedAt);
+ visible.sort((a, b) => b.openedAt - a.openedAt);
const asked = Number(url.searchParams.get("page"));
const page = Number.isSafeInteger(asked) && asked > 0 ? asked : 1;
const start = (page - 1) * THREADS_PAGE;
- return json(res, 200, { threads: rows.slice(start, start + THREADS_PAGE), total: rows.length, page, pageSize: THREADS_PAGE });
+ const selected = visible.slice(start, start + THREADS_PAGE);
+ if (selected.length === 0) return json(res, 200, { threads: [], total: visible.length, page, pageSize: THREADS_PAGE });
+ const pageThreads = new Map<string, Set<string>>();
+ for (const { bot, task } of selected) {
+ let bots = pageThreads.get(task.threadId);
+ if (!bots) { bots = new Set(); pageThreads.set(task.threadId, bots); }
+ bots.add(bot.id);
+ }
+ const activity = coordinator.threadActivity(pageThreads);
+ const threads = selected.map(({ bot, task, openedAt, openedBy }): ThreadRow => {
+ const state: ThreadState = (!task.closedBy && task.activity === "waiting-on-you") || activity.awaitingAnswer.has(task.threadId) ? "waiting-on-you"
+ : deps.threadBusy(bot.id, task.threadId) ? "running"
+ : deps.queuedThreadPosition(bot.id, task.threadId) !== null || activity.activeDirect.has(task.threadId) ? "queued"
+ : task.closedBy ? "closed" : "idle";
+ const node = state === "queued" ? activity.queued.get(task.threadId)?.get(bot.id) : undefined;
+ return {
+ threadId: task.threadId, botId: bot.id, botName: bot.name, title: task.title,
+ state, unread: task.unread === true, openedAt, delegationId: task.openedBy?.delegationId,
+ own: bot.id === from.id, ...(node ? { waiting: deps.queuedReason(node, bot.id === from.id ? deps.shown : undefined), delegationId: node.id } : {}),
+ ...(openedBy !== undefined ? { openedBy } : {}), ...(task.archivedAt !== undefined ? { archived: true } : {}),
+ };
+ });
+ return json(res, 200, { threads, total: visible.length, page, pageSize: THREADS_PAGE });
}
// rename_thread names only the conversation the turn speaks in. A room's thread is the room's, and an automation's
// chat keeps the name its runs find it by.
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index 80477147aa..41fdeb5602 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -253,6 +253,27 @@ export class RuntimeCoordinator implements Coordinator {
return this.live().map(row => this.project(row));
}
+ threadActivity(threads: ReadonlyMap<string, ReadonlySet<string>>): {
+ awaitingAnswer: Set<string>; activeDirect: Set<string>; queued: Map<string, Map<string, HandoffView>>;
+ } {
+ this.ready();
+ const awaitingAnswer = new Set<string>();
+ const activeDirect = new Set<string>();
+ const queued = new Map<string, Map<string, HandoffView>>();
+ for (const row of this.live()) {
+ const { threadId, groupId } = row.assignee.destination;
+ const bots = threads.get(threadId);
+ if (!bots) continue;
+ if (row.status === "needs_input") awaitingAnswer.add(threadId);
+ if (groupId === undefined) activeDirect.add(threadId);
+ if (row.status !== "queued" || groupId || !bots.has(row.assignee.botId)) continue;
+ let byBot = queued.get(threadId);
+ if (!byBot) { byBot = new Map(); queued.set(threadId, byBot); }
+ if (!byBot.has(row.assignee.botId)) byBot.set(row.assignee.botId, this.project(row));
+ }
+ return { awaitingAnswer, activeDirect, queued };
+ }
+
children(id: string): HandoffView[] {
this.ready();
const parent = this.store.get(id);