Skip to content

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

fix(server): build ownThreads before the coordinator so a restart report can name the thread (#7777)

Ooi Pin Juna15f6ab26f16
diff --git a/server/coordinator-restart-report.e2e.test.ts b/server/coordinator-restart-report.e2e.test.ts
new file mode 100644
index 0000000000..528447ccee
--- /dev/null
+++ b/server/coordinator-restart-report.e2e.test.ts
@@ -0,0 +1,105 @@
+// A running routine on the parent thread forces the coordinator open during RoutineManager's constructor. A running
+// child already marked restart "rerun" settles in that open and reports at once. Both have to be on disk together.
+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { runControlOmb } from "../scripts/control-omb.ts";
+import { openRuntimeStore } from "./runtime/store.ts";
+import type { Assignment } from "./runtime/types.ts";
+import { launchRestartableServer } from "./testing/restartable-server.ts";
+
+const CHILD_TITLE = "Ledger check";
+const CHILD_ID = "child-cut";
+const ROOT_ID = "root-cut";
+
+it("reports a twice-cut own thread when a restart opens the coordinator, without reading ownThreads too early", async () => {
+ const server = await launchRestartableServer();
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${server.url}${path}`, {
+ method,
+ headers: { "content-type": "application/json", origin: server.url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const value = await response.json() as { task: { threadId: string } };
+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBeGreaterThanOrEqual(200);
+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBeLessThan(300);
+ return value;
+ };
+ try {
+ const { bot } = await runControlOmb(["new-bot", "--name", "Scout", "--url", server.url]) as { bot: { id: string } };
+ const parent = (await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Parent brief" })).task;
+ const child = (await api("POST", `/api/bots/${bot.id}/tasks`, { title: CHILD_TITLE })).task;
+ expect(parent.threadId).not.toBe(child.threadId);
+
+ await server.stop();
+ const logAt = statSync(server.logPath).size;
+ const now = Date.now();
+ const runtime = openRuntimeStore(join(server.dataDir, "runtime.db"));
+ try {
+ runtime.insert(assignment({
+ id: ROOT_ID, botId: bot.id, threadId: parent.threadId, status: "waiting", depth: 0, at: now,
+ }), { kind: "enqueued", at: now });
+ runtime.insert(assignment({
+ id: CHILD_ID, rootId: ROOT_ID, parentId: ROOT_ID, botId: bot.id, threadId: child.threadId,
+ requesterThreadId: parent.threadId, status: "running", depth: 1, restart: "rerun", at: now,
+ }), { kind: "started", at: now });
+ } finally {
+ runtime.close();
+ }
+ const routinesPath = join(server.dataDir, "routines.json");
+ const disk = existsSync(routinesPath)
+ ? JSON.parse(readFileSync(routinesPath, "utf8")) as { runs?: unknown[] }
+ : { version: 1, routines: [], runs: [] as unknown[] };
+ disk.runs = [...(disk.runs ?? []), {
+ id: "run-cut", routineId: "routine-cut", routineName: "Ledger routine", prompt: "Check the ledger",
+ target: "bot", botId: bot.id, runOn: "maus", scheduledFor: now, status: "running", manual: false,
+ triggerSource: "schedule", threadId: parent.threadId, startedAt: now, createdAt: now,
+ }];
+ writeFileSync(routinesPath, JSON.stringify(disk));
+
+ await server.start();
+ const segment = () => readFileSync(server.logPath).subarray(logAt).toString("utf8");
+ await expect.poll(async () => {
+ const log = segment();
+ const coordinatorErrors = log.split("\n").filter((line) =>
+ line.startsWith("coordinator:") && (line.includes("threw") || /Cannot access '[^']+' before initialization/.test(line)));
+ const response = await fetch(`${server.url}/api/threads/${parent.threadId}/messages?limit=100`, { headers: { origin: server.url } });
+ const body = response.ok ? await response.json() as { messages?: Array<{ roomRequest?: { id?: string; phase?: string }; tool?: { name?: string; ok?: boolean } }> } : { messages: [] };
+ const results = (body.messages ?? []).filter((message) => message.roomRequest?.id === CHILD_ID && message.roomRequest.phase === "result");
+ return {
+ coordinatorErrors,
+ count: results.length,
+ ok: results.map((message) => message.tool?.ok),
+ names: results.map((message) => message.tool?.name ?? ""),
+ };
+ }, { timeout: 20_000, interval: 200 }).toEqual({
+ coordinatorErrors: [],
+ count: 1,
+ ok: [false],
+ names: [expect.stringContaining(`#${CHILD_TITLE}`)],
+ });
+ } finally {
+ await server.close();
+ }
+}, 120_000);
+
+function assignment(input: {
+ id: string; botId: string; threadId: string; status: Assignment["status"]; depth: number; at: number;
+ rootId?: string; parentId?: string; requesterThreadId?: string; restart?: Assignment["restart"];
+}): Assignment {
+ const rootId = input.rootId ?? input.id;
+ return {
+ id: input.id, rootId, ...(input.parentId ? { parentId: input.parentId } : {}), depth: input.depth,
+ origin: { kind: "person", source: "chat", ref: input.requesterThreadId ?? input.threadId, quote: "Check the ledger" },
+ requester: input.parentId
+ ? { kind: "bot_turn", botId: input.botId, threadId: input.requesterThreadId ?? input.threadId }
+ : { kind: "person" },
+ assignee: { botId: input.botId, destination: { kind: "work_thread", threadId: input.threadId } },
+ mode: "work", reply: "resume", brief: "Check the ledger", status: input.status, level: "ask", levelSource: "own",
+ executions: input.status === "running" ? 1 : 0, restarts: input.restart === "rerun" ? 1 : 0,
+ ...(input.restart ? { restart: input.restart } : {}),
+ ...(input.status === "running" ? { startedAt: input.at } : {}),
+ createdAt: input.at, lastActivityAt: input.at, result: "", rework: false, version: 1,
+ };
+}
diff --git a/server/index.ts b/server/index.ts
index ab9743f755..8474ce5e05 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -3841,6 +3841,18 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:
steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });
const remoteTeammates = new RemoteTeammates(); const remoteHandoff = createRemoteHandoff({ teammates: remoteTeammates, coordinator: () => coordinator, localBots: () => store.bots, botName: (id) => store.bot(id)?.name, outside: (threadId) => (outsideLineage.outsideDrivenThread(threadId) || outsideLineage.cloudGuestDriven(threadId) ? OUTSIDE_STAYS_HERE : undefined), file: join(DATA_DIR, "remote-teammate-work.json"), log: (line) => console.error(line) }); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),
worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });
+const validateModelProposal = (selection: ModelSelection, current?: BotRecord): string | null => {
+ const checked = checkedModelSelection(selection, undefined, true);
+ if (!checked.ok) return checked.error; const unusable = registry.get(selection.instanceId)?.models.options.find((option) => option.id === selection.model && (option.orgBlocked || option.needsCliUpdate)); if (unusable) return unusable.orgBlocked ? "This account's organization turned that model off. Propose another one." : `That model needs version ${unusable.needsCliUpdate} of its engine's CLI. Update it, or propose another model.`;
+ if (current?.approvalGrant) return "Wait for the approval-level confirmation before changing this bot's model";
+ if (current) {
+ const mode = approvalModeFor(current);
+ if (!supportsApprovalMode(selection, mode) || engineSwitchNeedsAsk(mode, current.modelSelection, selection)) {
+ return `@${current.name}'s existing permissions are incompatible with that provider. Change its permissions in bot settings, then propose the model change again.`;
+ }
+ }
+ return null;
+}; const engineHints = createEngineHints({ registry, access: (id) => providerConfigs()[id]?.access ?? registry.access(id), managed: (id) => managedDesktop.owns(id), policy: policyModelRefusal, ...(hostedModels ? { offered: (selection) => hostedModels!.allows(selection) } : {}) }); const ownThreads = createOwnThreads({ store, registry, node: (id) => coordinator.node(id), current: turnSelection, proposalRefusal: validateModelProposal, givesWay: modelGivesWay, modelName, hint: engineHints.hint, broken: engineHints.broken, localOnce: (engines) => localModelsOnce(engines, directLocalModels(providerConfigs(), (id, saved) => { const engine = registry.get(id), live = threadEngine(id); if (!engine || !live || !readyToRun(live, selectionContext)) return null; return { name: engine.displayName || id, models: [...saved, ...engine.models.options.map((option) => option.id)].filter((model) => !hostedModels || hostedModels.allows({ instanceId: id, model })) }; })), sourceLevel: sourceApprovalMode, mayRaise: (threadId) => !outsideLineage.handsNoLevel(threadId) && (!CLOUD_HOME || cloudOwnerPerson(threadPersonKey(threadId))) && (!HOSTED_WORKSPACE || sharedWorkspaceFullAccessEnabled()) });
const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),
now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },
@@ -9051,19 +9063,7 @@ const chiefPeerTargetRule = (noun: string) => (proposerBotId: string, targetBotI
if (!canManage(proposer, target)) return departmentRefusal(proposer, target) ?? "that bot is not in a department this Chief manages";
return null;
};
-const validateModelProposal = (selection: ModelSelection, current?: BotRecord): string | null => {
- const checked = checkedModelSelection(selection, undefined, true);
- if (!checked.ok) return checked.error; const unusable = registry.get(selection.instanceId)?.models.options.find((option) => option.id === selection.model && (option.orgBlocked || option.needsCliUpdate)); if (unusable) return unusable.orgBlocked ? "This account's organization turned that model off. Propose another one." : `That model needs version ${unusable.needsCliUpdate} of its engine's CLI. Update it, or propose another model.`;
- if (current?.approvalGrant) return "Wait for the approval-level confirmation before changing this bot's model";
- if (current) {
- const mode = approvalModeFor(current);
- if (!supportsApprovalMode(selection, mode) || engineSwitchNeedsAsk(mode, current.modelSelection, selection)) {
- return `@${current.name}'s existing permissions are incompatible with that provider. Change its permissions in bot settings, then propose the model change again.`;
- }
- }
- return null;
-};
-const engineHints = createEngineHints({ registry, access: (id) => providerConfigs()[id]?.access ?? registry.access(id), managed: (id) => managedDesktop.owns(id), policy: policyModelRefusal, ...(hostedModels ? { offered: (selection) => hostedModels!.allows(selection) } : {}) }); const ownThreads = createOwnThreads({ store, registry, node: (id) => coordinator.node(id), current: turnSelection, proposalRefusal: validateModelProposal, givesWay: modelGivesWay, modelName, hint: engineHints.hint, broken: engineHints.broken, localOnce: (engines) => localModelsOnce(engines, directLocalModels(providerConfigs(), (id, saved) => { const engine = registry.get(id), live = threadEngine(id); if (!engine || !live || !readyToRun(live, selectionContext)) return null; return { name: engine.displayName || id, models: [...saved, ...engine.models.options.map((option) => option.id)].filter((model) => !hostedModels || hostedModels.allows({ instanceId: id, model })) }; })), sourceLevel: sourceApprovalMode, mayRaise: (threadId) => !outsideLineage.handsNoLevel(threadId) && (!CLOUD_HOME || cloudOwnerPerson(threadPersonKey(threadId))) && (!HOSTED_WORKSPACE || sharedWorkspaceFullAccessEnabled()) }); const burst = createBurstHost({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), tier: () => cloudPlanTier.tier(), maxParallel: () => cfg.burst?.maxParallel, hasRoom: () => engineMemory.laneHasRoom(), store, language: (threadId) => threadLanguage(threadId), startTurn: (botId, text, opts) => startTurn(botId, text, opts), stop: (botId, threadId, cause) => { void interruptDirectThread(botId, threadId, cause).catch(() => {}); }, threadBusy, opened: (threadId, parent) => threadStarters.set(threadId, openerFrom(parent)), origin: (run) => withPerson({ kind: "user", request: quoteInNote(run.task, 400) }, threadPersonKey(run.threadId)), approval: ownThreads.approvalFor, defaultModel: (bot, threadId) => burstDefaultModel({ own: store.taskByThread(bot.id, threadId)?.modelSelection ?? bot.modelSelection, catalog: (id) => registry.get(id)?.models, refused: (id) => quickFallback.refused(id), usable: (selection) => ownThreads.refusal(selection, bot) === null }), modelName, route: (notification) => teamMessages.route(notification, { routine: true }), announce: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); } });
+const burst = createBurstHost({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), tier: () => cloudPlanTier.tier(), maxParallel: () => cfg.burst?.maxParallel, hasRoom: () => engineMemory.laneHasRoom(), store, language: (threadId) => threadLanguage(threadId), startTurn: (botId, text, opts) => startTurn(botId, text, opts), stop: (botId, threadId, cause) => { void interruptDirectThread(botId, threadId, cause).catch(() => {}); }, threadBusy, opened: (threadId, parent) => threadStarters.set(threadId, openerFrom(parent)), origin: (run) => withPerson({ kind: "user", request: quoteInNote(run.task, 400) }, threadPersonKey(run.threadId)), approval: ownThreads.approvalFor, defaultModel: (bot, threadId) => burstDefaultModel({ own: store.taskByThread(bot.id, threadId)?.modelSelection ?? bot.modelSelection, catalog: (id) => registry.get(id)?.models, refused: (id) => quickFallback.refused(id), usable: (selection) => ownThreads.refusal(selection, bot) === null }), modelName, route: (notification) => teamMessages.route(notification, { routine: true }), announce: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); } });
const teamMemory = new TeamMemory(join(DATA_DIR, "team-memory.json"));
const teamMemoryRequests = createTeamMemoryRequests({ teamMemory, store, sectionKey: sectionContextKey, decide: (row) => appendDecision(DATA_DIR, row) });
const outsideWrites = createOutsideWrites({ store, notify, language: (threadId) => threadLanguage(threadId), decide: (row) => appendDecision(DATA_DIR, row),