Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
One list: a My Cloud bot in place streams live, keeps its conversation's own actions, and recovers a refused session
milind-soni09becbbc11b4
diff --git a/electron/place-chat-main.mjs b/electron/place-chat-main.mjsindex 105c289b8d..dc1f8b9716 100644--- a/electron/place-chat-main.mjs+++ b/electron/place-chat-main.mjs@@ -88,9 +88,10 @@ export function createPlaceChatMain({ cloud, grant, wake, server, fetch: fetchImreturn {/** Gets the session ready for a click on a My Cloud row: the one already open (told to the server again, which may* have restarted since), or a new one. `{ ok: false }` when there is no My Cloud or it can't sign this in. */- ensure() {+ ensure({ fresh = false } = {}) {const key = scope();- if (session && session.key !== key) this.close();+ // `fresh`: My Cloud refused the one held (it was signed out there): a new one replaces it.+ if (session && (session.key !== key || fresh)) this.close();if (session) { tell({ origin: session.origin, token: session.token }); return Promise.resolve({ ok: true }); }if (!opening) {const mine = epoch;diff --git a/electron/place-chat-main.node-test.mjs b/electron/place-chat-main.node-test.mjsindex e25b91e9ee..7f66f82cbd 100644--- a/electron/place-chat-main.node-test.mjs+++ b/electron/place-chat-main.node-test.mjs@@ -73,6 +73,15 @@ test("the session is signed out at My Cloud and dropped from the server when letassert.deepEqual(f.asked.map(([url]) => url.slice(CLOUD.length)), ["/api/auth/logout", "/api/auth/pair"], "the old one signed out, a new one opened");});+test("a session My Cloud refused is replaced when asked: the old one let go, a new one opened", async () => {+ const f = setup();+ await f.chat.ensure();+ f.asked.length = 0;+ assert.deepEqual(await f.chat.ensure({ fresh: true }), { ok: true });+ assert.deepEqual(f.asked.map(([url]) => url.slice(CLOUD.length)), ["/api/auth/logout", "/api/auth/pair"]);+ assert.equal(f.grants, 2);+});+test("no My Cloud, no session", async () => {const f = setup({ cloud: { origin: null, account: null, asleep: false } });assert.deepEqual(await f.chat.ensure(), { ok: false });@@ -119,8 +128,9 @@ test("the page asks to open in place over its own channel, and main answers forconst handlers = new Map();const asked = [];installPlacesTogether({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, asking: (event) => event.page,- together: { openInPlace: async (asking, id) => { asked.push([asking, id]); return { ok: true }; } } });+ together: { openInPlace: async (asking, id, options) => { asked.push([asking, id, options]); return { ok: true }; } } });assert.deepEqual(await handlers.get("places-together:open-in-place")({ page: "local" }, "scout"), { ok: true });- assert.deepEqual(asked, [["computer", "scout"]]);+ await handlers.get("places-together:open-in-place")({ page: "local" }, "scout", true);+ assert.deepEqual(asked, [["computer", "scout", { fresh: false }], ["computer", "scout", { fresh: true }]]);await assert.rejects(async () => handlers.get("places-together:open-in-place")({ page: null }, "scout"));});diff --git a/electron/places-together.d.mts b/electron/places-together.d.mtsindex e0f1a76bd8..52acb94911 100644--- a/electron/places-together.d.mts+++ b/electron/places-together.d.mts@@ -78,7 +78,7 @@ export interface PlacesTogetherBridge {/** This computer's page only: gets one of My Cloud's listed bots ready to open in this window (main opens the session* this computer's server forwards it with, waking My Cloud first if it sleeps). `ok` false: open it with `open` instead.* Older apps lack it. */- openInPlace?(botId: string): Promise<{ ok: boolean }>;+ openInPlace?(botId: string, fresh?: boolean): Promise<{ ok: boolean }>;onChanged(callback: () => void): () => void;/** Keeps where the person moved bots in the one list; what main keeps now. Older apps lack it. */arrange?(entries: ArrangedBot[]): Promise<ArrangedBot[]>;@@ -125,7 +125,7 @@ export interface PlacesTogether {commandsChanged(on: boolean): void;switchedOff(): boolean;chosen(): boolean | null;- openInPlace(asking: BotHome, botId: string): Promise<{ ok: boolean }>;+ openInPlace(asking: BotHome, botId: string, options?: { fresh?: boolean }): Promise<{ ok: boolean }>;close(): void;}export function createPlacesTogether(deps: Record<string, unknown>): PlacesTogether;diff --git a/electron/places-together.mjs b/electron/places-together.mjsindex 749b9759a0..8c5873d856 100644--- a/electron/places-together.mjs+++ b/electron/places-together.mjs@@ -538,9 +538,10 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locareturn true;},/** A row's click on this computer's page, where a My Cloud bot opens in this window: the session this computer's server- * forwards it with is readied (waking My Cloud first), with the row "waking" meanwhile. `ok` false: the page opens it+ * forwards it with is readied (waking My Cloud first), with the row "waking" meanwhile; `fresh`, a new one in place of+ * one My Cloud refused. `ok` false: the page opens it* with `open` instead, on My Cloud's own page. Only a bot main listed itself, for this Cloud and account. */- async openInPlace(asking, botId) {+ async openInPlace(asking, botId, { fresh = false } = {}) {sameScope();if (asking !== "computer" || !active() || !inPlace) return { ok: false };const row = kept.get("cloud")?.bots.find((bot) => bot.id === botId);@@ -549,7 +550,7 @@ export function createPlacesTogether({ pref, cloud, powerChecked, computer, locareadying += 1;tell();try {- const ready = await inPlace.ensure();+ const ready = await inPlace.ensure({ fresh });return { ok: mine === epoch && active() && ready?.ok === true };} catch { return { ok: false }; }finally { if (mine === epoch) { readying = Math.max(0, readying - 1); tell(); } }@@ -641,7 +642,7 @@ export function installPlacesTogether({ ipcMain, asking, together, rail = () =>return together.set(page, value === true, { listOnly: from === "notice" });});ipcMain.handle("places-together:open", (event, botId) => together.open(side(event), String(botId)));- ipcMain.handle("places-together:open-in-place", (event, botId) => together.openInPlace(side(event), String(botId)));+ ipcMain.handle("places-together:open-in-place", (event, botId, fresh) => together.openInPlace(side(event), String(botId), { fresh: fresh === true }));ipcMain.handle("places-together:arrange", (event, entries) => together.arrange(side(event), entries));ipcMain.handle("places-together:new-bot-choice", (event) => together.newBotChoice(side(event)));ipcMain.handle("places-together:new-bot", (event) => together.newBot(side(event)));diff --git a/electron/preload.cjs b/electron/preload.cjsindex 2d83b54535..b4ec20662a 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -650,7 +650,7 @@ const bridge = {open: botId => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("places-together:open", String(botId)) : Promise.reject(new Error("Choose a bot to open it.")),// A My Cloud bot opened in this computer's window (main readies the session this computer's server forwards it with).- openInPlace: botId => (isLocalPage ? ipcRenderer.invoke("places-together:open-in-place", String(botId)) : Promise.resolve({ ok: false })),+ openInPlace: (botId, fresh) => (isLocalPage ? ipcRenderer.invoke("places-together:open-in-place", String(botId), fresh === true) : Promise.resolve({ ok: false })),// Where the person dragged bots in the one list: main keeps it beside the switch, and checks every entry.arrange: entries => ipcRenderer.invoke("places-together:arrange", Array.isArray(entries) ? entries.slice(0, 2000) : []),onChanged: cb => {diff --git a/server/places/place-proxy.test.ts b/server/places/place-proxy.test.tsindex f8560cc1c1..a3d6ad97f6 100644--- a/server/places/place-proxy.test.ts+++ b/server/places/place-proxy.test.ts@@ -96,6 +96,16 @@ describe("the conversation of a My Cloud bot, through this computer's server", (expect(JSON.parse(seen[1]!.body)).toEqual({ threadId: "t1" });});+ it("forwards the conversation's own settings, edits, reactions and approvals, but never the bot's", async () => {+ for (const [method, path] of [["PATCH", "/api/bots/cloud:scout/tasks/cloud:t1"], ["POST", "/api/bots/cloud:scout/messages/m1/edit"], ["POST", "/api/bots/cloud:scout/active-branch"],+ ["POST", "/api/threads/cloud:t1/messages/m1/reactions"], ["POST", "/api/threads/cloud:t1/respond"], ["POST", "/api/threads/cloud:t1/undo"], ["POST", "/api/bots/cloud:scout/always-allow"]] as const) {+ expect((await ask(path, { method, body: JSON.stringify({ threadId: "cloud:t1", pinnedMessageId: "m1" }) })).status, path).toBe(200);+ }+ expect(seen.map(({ method, url }) => `${method} ${url}`)).toEqual(["PATCH /api/bots/scout/tasks/t1", "POST /api/bots/scout/messages/m1/edit", "POST /api/bots/scout/active-branch",+ "POST /api/threads/t1/messages/m1/reactions", "POST /api/threads/t1/respond", "POST /api/threads/t1/undo", "POST /api/bots/scout/always-allow"]);+ expect(seen.every(({ body }) => JSON.parse(body).threadId === "t1")).toBe(true);+ });+it("serves My Cloud's file by the page's name for it", async () => {answerWith = (_req, res) => void res.writeHead(200, { "content-type": "image/png", "content-length": "3" }).end(Buffer.from([1, 2, 3]));const answer = await ask("/api/attachments/cloud--aa11-bb22.png");@@ -117,8 +127,8 @@ describe("the conversation of a My Cloud bot, through this computer's server", (});it("refuses what a conversation does not need, without asking My Cloud: settings, deleting the bot, renaming", async () => {- for (const [method, path] of [["PATCH", "/api/bots/cloud:scout"], ["DELETE", "/api/bots/cloud:scout"], ["GET", "/api/bots/cloud:scout/soul"], ["PATCH", "/api/bots/cloud:scout/tasks/cloud:t1"]] as const) {- const answer = await ask(path, { method, ...(method === "PATCH" ? { body: "{}" } : {}) });+ for (const [method, path] of [["PATCH", "/api/bots/cloud:scout"], ["DELETE", "/api/bots/cloud:scout"], ["GET", "/api/bots/cloud:scout/soul"], ["POST", "/api/bots/cloud:scout/computer/provision"]] as const) {+ const answer = await ask(path, { method, ...(method === "GET" || method === "DELETE" ? {} : { body: "{}" }) });expect(answer.status).toBe(404);expect(await codeOf(answer)).toBe("place_unsupported");}diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.tsindex 777335a6ea..c647f68c62 100644--- a/server/places/place-proxy.ts+++ b/server/places/place-proxy.ts@@ -5,7 +5,8 @@// process's memory only, and every answer is rebuilt here from My Cloud's body with its ids in this page's names.//// Only what a conversation needs goes through (ROUTES): reading it and its other conversations, its live turns, sending,-// stopping, answering its cards, marking it read and its files. Anything else asked of such a bot is refused plainly+// stopping, editing and reacting, answering its cards and approvals, the conversation's own settings, marking it read+// and its files. Anything else asked of such a bot is refused plainly// with the words to open My Cloud's own page, which the bot's row offers.//// Who may ask: only the app's own window, by the desktop capability Chromium adds to its requests below JavaScript, from@@ -37,6 +38,15 @@ const ROUTES: ReadonlyArray<readonly [string, RegExp]> = [["GET", /^\/api\/bots\/[\w-]+$/],["POST", /^\/api\/bots\/[\w-]+\/tasks$/],["POST", /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+$/],+ // The conversation's own settings: its title, a pinned message, Work until done, how it asks before acting; and+ // archiving it. The bot's settings stay on its own page.+ ["PATCH", /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+$/],+ ["DELETE", /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+$/],+ ["POST", /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+\/title$/],+ ["POST", /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+\/forks$/],+ ["POST", /^\/api\/bots\/[\w-]+\/messages\/[\w-]+\/edit$/],+ ["POST", /^\/api\/bots\/[\w-]+\/active-branch$/],+ ["POST", /^\/api\/bots\/[\w-]+\/always-allow$/],["POST", /^\/api\/bots\/[\w-]+\/messages$/],["POST", /^\/api\/bots\/[\w-]+\/read$/],["POST", /^\/api\/bots\/[\w-]+\/interrupt$/],@@ -44,6 +54,10 @@ const ROUTES: ReadonlyArray<readonly [string, RegExp]> = [["POST", /^\/api\/bots\/[\w-]+\/queue\/[\w-]+\/steer$/],["POST", /^\/api\/bots\/[\w-]+\/cards\/[\w-]+$/],["POST", /^\/api\/threads\/[\w-]+\/respond$/],+ ["POST", /^\/api\/threads\/[\w-]+\/undo$/],+ ["POST", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/reactions$/],+ ["GET", /^\/api\/threads\/[\w-]+\/job$/],+ ["POST", /^\/api\/threads\/[\w-]+\/job\/[\w-]+\/stop$/],["GET", /^\/api\/threads\/[\w-]+\/messages$/],["GET", /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/(?:image|file|tool)$/],["GET", /^\/api\/attachments\/[\w.-]+$/],diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex a53897e13f..d81216df5f 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -315,8 +315,8 @@ export function Composer({const slash = composerSlashTrigger(text, caret);const locale = activeLocale();- const slashSkills = useSlashSkills(group ? undefined : bot?.id, threadId, Boolean(slash) && slash?.start !== dismissedSlashAt);- const canLearn = skillAuthoringEnabled(state.config) &&+ const slashSkills = useSlashSkills(group || isPlaceId(bot?.id) ? undefined : bot?.id, threadId, Boolean(slash) && slash?.start !== dismissedSlashAt);+ const canLearn = skillAuthoringEnabled(state.config) && !isPlaceId(bot?.id) &&(group ? (members ?? []).some((member) => supportsAgents(state.instances, member)) : supportsAgents(state.instances, bot));const commandCandidates = useMemo(() => {if (!slash || slash.start === dismissedSlashAt) return [];diff --git a/src/components/Sidebar.in-place.dom.test.ts b/src/components/Sidebar.in-place.dom.test.tsindex 5a57c00298..252014ca8a 100644--- a/src/components/Sidebar.in-place.dom.test.ts+++ b/src/components/Sidebar.in-place.dom.test.ts@@ -138,6 +138,19 @@ describe("a My Cloud bot opens in this window", () => {expect(dispatch.mock.calls.some(([action]) => action.type === "select")).toBe(false);});+ it("a session My Cloud signed out is replaced once, and the bot opens here all the same", async () => {+ window.ogb = { placesTogether: page } as never;+ await render();+ const good = served;+ let first = true;+ served = (path) => { if (first) { first = false; return new Response(JSON.stringify({ error: "x", code: "place_signin" }), { status: 502 }); } return good(path); };+ await act(async () => q('[data-sidebar-bot-row="cloud:scout"]')!.click());+ await settled();+ expect(page.openInPlace.mock.calls).toEqual([["scout"], ["scout", true]]);+ expect(page.open).not.toHaveBeenCalled();+ expect(dispatch.mock.calls.map(([action]) => action).at(-1)).toEqual({ type: "select", id: "cloud:scout" });+ });+it("an app without it opens on My Cloud's page, as before", async () => {const { openInPlace: _gone, ...older } = page;window.ogb = { placesTogether: older } as never;diff --git a/src/lib/live-events.ts b/src/lib/live-events.tsindex 81cc63d647..86b5793c57 100644--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@ -107,6 +107,8 @@ export function placeFrames<T extends (frame: LiveFrame) => void>(sink: T): T {return sink;}export function placeFrame(frame: ServerFrame): void {+ // The chat's status line, steps and streaming reply read every live frame before the store does, as for this page's own.+ tapLiveFrame(frame);placeSink?.(frame as LiveFrame);}diff --git a/src/lib/place-chat.dom.test.ts b/src/lib/place-chat.dom.test.tsindex f3b8c40943..4dfff40646 100644--- a/src/lib/place-chat.dom.test.ts+++ b/src/lib/place-chat.dom.test.ts@@ -8,6 +8,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";import { StoreProvider, useStore } from "@/state/store";import { PlaceChatKeeper } from "@/components/PlacedBotMenu";import { openPlaceBot, resetPlaceChatForTest } from "./place-chat";+import { liveReplies, resetLiveReplies } from "@/state/live-reply";class Source {static made: Source[] = [];@@ -53,6 +54,7 @@ beforeEach(async () => {afterEach(async () => {await act(async () => root.unmount());resetPlaceChatForTest();+ resetLiveReplies();vi.unstubAllGlobals();delete (window as { ogb?: unknown }).ogb;});@@ -112,3 +114,14 @@ it("a click overtaken by the person choosing something else lands nowhere", asynexpect(store.state.selectedId).toBe("git");expect(bots()).toEqual(["ledger", "git"]);});++it("a turn streams in place: each delta of the reply shows live under the conversation's place id, as this page's own do", async () => {+ await act(async () => { await openPlaceBot("scout", store.dispatch); });+ await settle();+ const runtime = (event: Record<string, unknown>) => placed().say({ kind: "runtime", event: { eventId: `e${Math.random()}`, provider: "claudeAgent", threadId: "cloud:t1", createdAt: "2026-11-27T10:00:00.000Z", turnId: "turn-1", ...event } });+ await act(async () => { runtime({ type: "turn.started" }); runtime({ type: "content.delta", streamKind: "assistant_text", delta: "Two of the four " }); });+ expect(liveReplies("cloud:t1").map((item) => item.text)).toEqual(["Two of the four "]);+ await act(async () => runtime({ type: "content.delta", streamKind: "assistant_text", delta: "have a balcony." }));+ expect(liveReplies("cloud:t1").map((item) => item.text)).toEqual(["Two of the four have a balcony."]);+ expect(liveReplies("t1")).toEqual([]);+});diff --git a/src/lib/place-chat.ts b/src/lib/place-chat.tsindex 9cd824101b..cdcf54278d 100644--- a/src/lib/place-chat.ts+++ b/src/lib/place-chat.ts@@ -59,14 +59,21 @@ export async function openPlaceBot(id: string, dispatch: Dispatch<Action>): Promtry { opened = await page.openInPlace(id); } catch { opened = null; }if (overtaken()) return "overtaken";if (!opened?.ok) return there();- let bot: Bot;- try {- ({ bot } = await api<{ bot: Bot }>(`/api/bots/${encodeURIComponent(key)}?messages=${OPEN_MESSAGES}`));- if (!bot || bot.id !== key) throw new Error("not this bot");- } catch {- return overtaken() ? "overtaken" : there();+ let bot: Bot | null = null;+ const read = async () => {+ const answer = await api<{ bot: Bot }>(`/api/bots/${encodeURIComponent(key)}?messages=${OPEN_MESSAGES}`);+ if (!answer?.bot || answer.bot.id !== key) throw new Error("not this bot");+ return answer.bot;+ };+ try { bot = await read(); } catch (error) {+ // The session was signed out at My Cloud, or this computer's server restarted without it: main opens a new one, once.+ const code = (error as { body?: { code?: unknown } }).body?.code;+ if (!overtaken() && (code === "place_signin" || code === "place_closed")) {+ try { if ((await page.openInPlace(id, true))?.ok && !overtaken()) bot = await read(); } catch { bot = null; }+ }}if (overtaken()) return "overtaken";+ if (!bot) return there();dispatch({ type: "botPatched", bot: placeBot(bot) });dispatch({ type: "select", id: key });chosen = key;