Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a bot's memory where it was when its main thread is saved for it
luishron123a1d4e7dc2880
diff --git a/server/index.ts b/server/index.tsindex dd6d857650..2a82ef25a8 100644--- a/server/index.ts+++ b/server/index.ts@@ -2854,7 +2854,7 @@ const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threads/** Strips provider session ids (resumeCursors) here, not at call sites, so no broadcast or paired phone ever gets them. */const wireBot = (bot: BotRecord, onlyThreadId?: string): WireBot => {- const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, home: _home, ...rest } = bot;+ const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, mainThreadKept: _mainThreadKept, home: _home, ...rest } = bot;// Clients see Ask while an elevated grant awaits the desktop's confirmation, never a grant that may still roll back.const visible = approvalGrant && !approvalGrant.threadOnly? { ...rest, approvalMode: "ask" as const, autoApprove: false }@@ -2874,7 +2874,7 @@ function toolScopeForTurn(botId: string) {}const wireTrustedApprovalBot = (bot: NonNullable<ReturnType<typeof store.bot>>) => {- const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, home: _home, ...rest } = bot;+ const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, mainThreadKept: _mainThreadKept, home: _home, ...rest } = bot;const awaiting = threadsAwaitingTeammates();return { ...rest, approvalMode: approvalModeFor(rest), mainThreadId: botMainThread(bot.id), avatarUrl: rest.avatarUrl ?? null, ...(tasks ? { tasks: tasks.map((task) => wireTask(task, bot.modelSelection, awaiting)) } : {}) };};diff --git a/server/main-thread.e2e.test.ts b/server/main-thread.e2e.test.tsindex 5eba468b40..0ed292ea61 100644--- a/server/main-thread.e2e.test.ts+++ b/server/main-thread.e2e.test.ts@@ -218,14 +218,15 @@ it("keeps the main thread an install already had across an update, then moves it// What an install saved before a main thread was kept: threads stamped where the person wrote, and no choice.await server.stop();const file = join(server.dataDir, "bots.json");- writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, ...rest }) => rest)));+ writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, mainThreadKept: _kept, ...rest }) => rest)));expect(saved().tasks.find((task: any) => task.threadId === second).askedAt).toEqual(expect.any(Number));await server.start();expect(await main(), "the thread the person last wrote in, as before the update").toBe(second);await write(third);expect(await main()).toBe(second);await server.stop();- expect(saved().mainThreadChoice).toBe(second);+ expect(saved()).toMatchObject({ mainThreadKept: second });+ expect(saved().mainThreadChoice).toBeUndefined();await server.start();expect(await main()).toBe(second);@@ -269,7 +270,7 @@ it("keeps the selected thread as the main one across an update for a bot nobody// What an install saved before a main thread was kept: no choice, the second thread selected, nothing written anywhere.await server.stop();const file = join(server.dataDir, "bots.json");- writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, ...rest }) => rest)));+ writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, mainThreadKept: _kept, ...rest }) => rest)));expect(saved()).toMatchObject({ threadId: second });expect(saved().tasks.some((task: any) => task.askedAt !== undefined)).toBe(false);await server.start();@@ -278,7 +279,8 @@ it("keeps the selected thread as the main one across an update for a bot nobodyexpect((await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).threadId).toBe(first);expect(await main(), "selecting another thread moves nothing").toBe(second);await server.stop();- expect(saved().mainThreadChoice).toBe(second);+ expect(saved()).toMatchObject({ mainThreadKept: second });+ expect(saved().mainThreadChoice).toBeUndefined();await server.start();expect(await main()).toBe(second);} finally {@@ -321,3 +323,50 @@ it("moves an archived or deleted main thread to the only open one, a thread theawait fixture.close();}}, 120_000);++it("leaves an install's memory where it was when the update saves its main thread, and moves it only with the person's own choice", async () => {+ const server = await launchRestartableServer();+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ 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 any;+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(status);+ return value;+ };+ const cli = (...args: string[]) => runControlOmb([...args, "--url", server.url]) as Promise<any>;+ try {+ const { bot } = await cli("new-bot", "--name", "Counsel");+ const oldest = bot.activeTaskId as string;+ const main = async () => (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).mainThreadId;+ const ownNotes = async (threadId: string) => (await api("GET", `/api/bots/${bot.id}/memory/thread/${threadId}`)).scoped as boolean;+ const saved = () => readRegistry(server.dataDir).bots.find((candidate: any) => candidate.id === bot.id);+ const written = (await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Acme NDA", approvalMode: "ask" }, 201)).task.threadId as string;+ await cli("send", "--bot", bot.id, "--task", written, "--text", "Note this.");+ await expect.poll(async () => ((await api("GET", `/api/threads/${written}/messages?limit=50`)).messages as any[]).some((message) => message.role !== "user"), { timeout: 20_000 }).toBe(true);+ await expect.poll(async () => (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).busy, { timeout: 20_000 }).toBe(false);++ // What an install saved before a main thread was kept: no choice, so the oldest conversation held the bot's memory.+ await server.stop();+ const file = join(server.dataDir, "bots.json");+ writeFileSync(file, JSON.stringify((JSON.parse(readFileSync(file, "utf8")) as any[]).map(({ mainThreadChoice: _choice, mainThreadKept: _kept, ...rest }) => rest)));+ await server.start();+ expect(await main(), "the thread the person last wrote in, as before the update").toBe(written);+ expect([await ownNotes(oldest), await ownNotes(written)], "the oldest conversation still holds the bot's memory").toEqual([false, true]);+ await api("POST", `/api/bots/${bot.id}/tasks/${oldest}`);+ await server.stop();+ expect(saved()).toMatchObject({ mainThreadKept: written });+ expect(saved().mainThreadChoice).toBeUndefined();+ await server.start();+ expect([await main(), await ownNotes(oldest), await ownNotes(written)]).toEqual([written, false, true]);++ await api("PATCH", `/api/bots/${bot.id}`, { mainThreadChoice: written });+ expect([await main(), await ownNotes(oldest), await ownNotes(written)], "the person's choice takes the bot's memory, as it did").toEqual([written, true, false]);+ await server.stop();+ expect(saved()).toMatchObject({ mainThreadChoice: written });+ expect(saved().mainThreadKept).toBeUndefined();+ } finally {+ await server.close();+ }+}, 180_000);diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 842778f58b..e7e6b5dd7b 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -241,6 +241,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {// Same 400 for unknown and ineligible ids, so a private thread's existence is not revealed.if (body.mainThreadChoice !== undefined) {const chosen = typeof body.mainThreadChoice === "string" ? deps.mainThreadTasks(m[1]).find((task) => task.threadId === body.mainThreadChoice) : null;+ patch.mainThreadKept = undefined;if (body.mainThreadChoice === null) patch.mainThreadChoice = undefined;else if (chosen && !chosen.routineRunId && chosen.archivedAt === undefined) patch.mainThreadChoice = chosen.threadId;else return json(res, 400, { error: "mainThreadChoice must be one of this bot's conversations" });diff --git a/server/store.ts b/server/store.tsindex 74c6c6f390..1a4abd672d 100644--- a/server/store.ts+++ b/server/store.ts@@ -153,7 +153,7 @@ export function titleFromLlm(raw: string): string | null {export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {tasks?: TaskRecord[];avatarUrl?: string;- resumeCursors: Record<string, unknown>; /** Set on a stand-in: the place this bot lives in, and its id there. */ home?: { place: string; placeName: string; botId: string; /** What that place is, as the sidebar's rows say it. */ kind?: "computer" | "cloud"; /** It cannot be reached now: the link is off or its place is unlinked ("off"), or its place no longer has it ("missing"). */ gone?: "off" | "missing" }; mainThreadChoice?: string; // mainThreadChoice ("Set as main thread") is host-only; clients get mainThreadId.+ resumeCursors: Record<string, unknown>; /** Set on a stand-in: the place this bot lives in, and its id there. */ home?: { place: string; placeName: string; botId: string; /** What that place is, as the sidebar's rows say it. */ kind?: "computer" | "cloud"; /** It cannot be reached now: the link is off or its place is unlinked ("off"), or its place no longer has it ("missing"). */ gone?: "off" | "missing" }; mainThreadChoice?: string; mainThreadKept?: string; // Host-only; clients get mainThreadId. mainThreadChoice is the person's "Set as main thread"; mainThreadKept is the one saved for them so it stays put, and no memory follows it./** Elevation journal: Full/Custom runs as Ask until Electron confirms the prepared reply; a marker surviving a restart is revoked on load. */approvalGrant?: {requestId: string;@@ -170,7 +170,7 @@ export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {assignedSkills?: string[];}-export type BotWirePrivateKeys = "resumeCursors" | "home" | "mainThreadChoice" | "tasks" | "avatarUrl" | "approvalGrant" | "lastProfileRequestId" | "lastTeamSetupReceipt" | "packageBase" | "assignedSkills";+export type BotWirePrivateKeys = "resumeCursors" | "home" | "mainThreadChoice" | "mainThreadKept" | "tasks" | "avatarUrl" | "approvalGrant" | "lastProfileRequestId" | "lastTeamSetupReceipt" | "packageBase" | "assignedSkills";export type BotWireProjection = Pick<BotRecord, Exclude<keyof BotRecord, BotWirePrivateKeys>>;export type BotWireProjectionIsExact = AssertExact<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection> & AssertSameKeys<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection>;export const botWireProjectionIsExact: BotWireProjectionIsExact = true;@@ -1459,7 +1459,7 @@ export class Store {for (const g of rooms) this.emit({ type: "group", groupId: g.id });return true;}- /** A bot's saved main thread, after saving the one `keep` names for it: no save of its own, it goes with the bot's next one. */ keepMainThread(id: string, keep: (chosen?: string) => string | undefined): string | undefined { const bot = this.own(id), next = bot && keep(bot.mainThreadChoice); if (!bot || !next) return this.bot(id)?.mainThreadChoice; this.registry.changedInPlace({ kind: "bot", id }); return bot.mainThreadChoice = next; }+ /** A bot's saved main thread, after saving the one `keep` names for it: no save of its own, it goes with the bot's next one. */ keepMainThread(id: string, keep: (chosen?: string) => string | undefined): string | undefined { const bot = this.own(id), next = bot && keep(bot.mainThreadKept ?? bot.mainThreadChoice); if (!bot || !next) { const saved = this.bot(id); return saved?.mainThreadKept ?? saved?.mainThreadChoice; } this.registry.changedInPlace({ kind: "bot", id }); return bot.mainThreadKept = next; }patchBot(id: string, patch: Partial<BotRecord>): BotRecord | null {const bot = this.own(id);if (!bot) return null; patch = reshowWhenMoved(bot, patch);