Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Stop sending old workspace files after an own-home move is done
MaxWang0075905476c81a8
diff --git a/electron/cloud-send-main.d.mts b/electron/cloud-send-main.d.mtsindex d184208969..fafdb6534e 100644--- a/electron/cloud-send-main.d.mts+++ b/electron/cloud-send-main.d.mts@@ -29,7 +29,7 @@ export function installCloudSend(deps: {receive(proc: unknown, message: unknown): boolean;/** This computer's server's private port, asked as a send asks it: another move's sends share it. */handoff(what: { kind: string; [key: string]: unknown }): Promise<any>;- move(options?: { final?: boolean; scope?: string }): Promise<CloudSendOutcome>;+ move(options?: { final?: boolean; scope?: string; files?: boolean }): Promise<CloudSendOutcome>;check(options?: { scope?: string; stopped?(): boolean }): Promise<CloudMoveCheck>;switches(): Record<string, boolean>;snapshot(): CloudSendSnapshot;diff --git a/electron/cloud-send-main.mjs b/electron/cloud-send-main.mjsindex 8c6a3b2f57..87bae92f7a 100644--- a/electron/cloud-send-main.mjs+++ b/electron/cloud-send-main.mjs@@ -159,8 +159,8 @@ export function installCloudSend({ ipcMain, cloudPage, server, local, home, cook/** This computer's server's private port, asked as a send asks it: another move's sends share it. */handoff: (what) => handoff.request(server(), what),/** The one-time move to My Cloud (cloud-send.mjs): a pass that carries everything, `final` the one after this computer- * stops, and the check of what arrived. */- move: (options) => send.send({ reason: "move", final: options?.final === true, ...(options?.scope ? { scope: options.scope } : {}) }),+ * stops, and the check of what arrived. `files: false` leaves the bots' files. */+ move: (options) => send.send({ reason: "move", final: options?.final === true, ...(options?.scope ? { scope: options.scope } : {}), ...(options?.files === false ? { files: false } : {}) }),check: (options) => send.check(options),/** Each automation the move carried, and whether it was on here when it went. */switches: () => send.switches(),diff --git a/electron/cloud-send-move.node-test.mjs b/electron/cloud-send-move.node-test.mjsindex 257f7f79e7..04a1ceb2da 100644--- a/electron/cloud-send-move.node-test.mjs+++ b/electron/cloud-send-move.node-test.mjs@@ -1,4 +1,5 @@import assert from "node:assert/strict";+import { createHash } from "node:crypto";import test from "node:test";import { EMPTY, itemKey } from "./cloud-send-parts.mjs";@@ -464,3 +465,47 @@ test("a check that finds things missing names, for what may stay behind, each shassert.deepEqual(report.names, { b1: "b1", b2: "b2", "room:r1": "Launch room" });assert.deepEqual(report.owners, { "t-b1": "b1" }, "only the chats found short");});++/** A move whose workspace differs from My Cloud's, including a git ref: My Cloud keeps its own and the arrival goes beside it. */+function differingWorkspace() {+ const sha = (text) => createHash("sha256").update(text).digest("hex");+ const file = (path, text) => ({ path, size: Buffer.byteLength(text), sha256: sha(text) });+ const here = [file("workspaces/ember/.git/refs/heads/main", "old-ref"), file("workspaces/ember/notes.md", "mine")];+ const there = [file("workspaces/ember/.git/refs/heads/main", "new-ref"), file("workspaces/ember/notes.md", "theirs")];+ const text = { "workspaces/ember/.git/refs/heads/main": "old-ref", "workspaces/ember/notes.md": "mine" };+ const move = sides({ here: [bot("ember", { soul: "s" })], there: [bot("ember", { soul: "s" })], bots: { ember: { soul: "s" } },+ onCall: (method, route) => (method === "GET" && /^\/api\/cloud-send\/files(?:\?bot=ember)?$/u.test(route)+ ? reply(200, { v: 1, files: there, space: { freeBytes: 1e12, volumeBytes: 1e12 } }) : null) });+ const local = move.deps.local;+ move.deps.local = async (route, init) => {+ if (route === "/api/cloud-send/files" || route.startsWith("/api/cloud-send/files?")) {+ move.calls.push(`HERE GET ${route}`);+ if (route.startsWith("/api/cloud-send/files?path=")) {+ const body = text[new URL(`http://local${route}`).searchParams.get("path")];+ return body ? new Response(Buffer.from(body)) : json({}, 404);+ }+ return json({ v: 1, files: here });+ }+ return local(route, init);+ };+ return move;+}++const arrivedBeside = (calls) => calls.filter((call) => call.startsWith("UPLOAD /api/cloud-send/files"))+ .map((call) => new URL(`http://x${call.slice("UPLOAD ".length)}`).searchParams.get("path"));++test("a move sends a workspace file that differs, including under .git; a pass that leaves files does not list or send them", async () => {+ const topped = differingWorkspace();+ const outcome = await createCloudSend(topped.deps).send({ reason: "move", final: true, files: false });+ assert.deepEqual(outcome.result.files, { sent: 0, kept: 0 });+ assert.equal(topped.calls.some((call) => call.includes("/api/cloud-send/files")), false, "no listing and no copy beside My Cloud's file");+ assert.ok(topped.calls.includes("POST /api/cloud-send/memory"), "what a newer app learned to move still goes");++ const moving = differingWorkspace();+ const sent = await createCloudSend(moving.deps).send({ reason: "move", final: true });+ assert.deepEqual(sent.result.files, { sent: 2, kept: 2 });+ assert.deepEqual(arrivedBeside(moving.calls).sort(), [+ "workspaces/ember/.git/refs/heads/main (Amit's Mac)",+ "workspaces/ember/notes (Amit's Mac).md",+ ]);+});diff --git a/electron/cloud-send.d.mts b/electron/cloud-send.d.mtsindex fbab2c3323..03d4f8a68d 100644--- a/electron/cloud-send.d.mts+++ b/electron/cloud-send.d.mts@@ -228,8 +228,9 @@ export function createCloudSend(deps: {snapshot(): CloudSendSnapshot;compare(): Promise<CloudSendSnapshot>;/** `reason: "move"`: everything this computer has, apps and keys first; `final`: the pass after this computer stopped,- * which carries the sign-ins that refresh themselves and lets go of this computer's copies. */- send(options?: { keys?: string[] | null; force?: string[]; reason?: string; final?: boolean }): Promise<CloudSendOutcome>;+ * which carries the sign-ins that refresh themselves and lets go of this computer's copies. `files: false`: the bots'+ * files stay where they are. */+ send(options?: { keys?: string[] | null; force?: string[]; reason?: string; final?: boolean; files?: boolean }): Promise<CloudSendOutcome>;/** `scope`: only the bots a move of some of them carries. `stopped`: the person stopped the move, so a check waiting for My Cloud ends now. */check(options?: { scope?: string; stopped?(): boolean }): Promise<CloudMoveCheck>;/** Each automation a move carried ("routine:<id>", "call:<id>", "webhook:<id>", "app-event:<id>") and whether it wasdiff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjsindex 81e467eb25..c3e431e460 100644--- a/electron/cloud-send.mjs+++ b/electron/cloud-send.mjs@@ -334,12 +334,12 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>/** One send at a time; one asked while another runs waits for it, then runs as it was asked. A move (`reason: "move"`)* carries everything; its final pass (`final`) carries the sign-ins that refresh themselves too, and this computer lets- * go of each once My Cloud has it. */- async function send({ keys = null, force = [], reason = "button", final = false, scope = null } = {}) {+ * go of each once My Cloud has it. `files: false` leaves the bots' files. */+ async function send({ keys = null, force = [], reason = "button", final = false, scope = null, files = true } = {}) {while (running) await running.promise.catch(() => {});const origin = cloud.origin();if (!origin) throw new CloudSendError("no_cloud", "This computer has no My Cloud yet.");- const job = { reason, final: reason === "move" && final === true, scope, promise: null, chats: false };+ const job = { reason, final: reason === "move" && final === true, scope, files: files !== false, promise: null, chats: false };running = job;progress = null;localScope = scope;@@ -431,8 +431,10 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>if (move) {// Its notes about the person stay with them when a bot moves into a team.if (!team) await kinds.moveMemory(ctx, moved);- try { await kinds.moveFiles(ctx, moved, computer?.label); }- catch (error) { result.failed.push({ key: "files", kind: "files", label: "Files", error: sentence(error?.message) ?? "The files could not be sent." }); }+ if (job.files) {+ try { await kinds.moveFiles(ctx, moved, computer?.label); }+ catch (error) { result.failed.push({ key: "files", kind: "files", label: "Files", error: sentence(error?.message) ?? "The files could not be sent." }); }+ }}const after = parseSendSummary((await session.call("GET", summaryRoute)).body);if (after) remember(origin, ctx, after);diff --git a/electron/one-home.d.mts b/electron/one-home.d.mtsindex 0cae915bfc..ab50c39fbf 100644--- a/electron/one-home.d.mts+++ b/electron/one-home.d.mts@@ -82,7 +82,7 @@ export function missingOf(report: unknown): string;export function createOneHome(deps: {journal: { read(): unknown; write(value: unknown): void };cloud(): OneHomeCloud | null;- send: { move(options?: { final?: boolean }): Promise<unknown>; check(options?: { stopped?(): boolean }): Promise<{ ok: boolean }>; switches(): Record<string, boolean>; snapshot(): any };+ send: { move(options?: { final?: boolean; files?: boolean }): Promise<unknown>; check(options?: { stopped?(): boolean }): Promise<{ ok: boolean }>; switches(): Record<string, boolean>; snapshot(): any };local: {freeze(origin: string): Promise<{ frozen: true } | { busy: string; what?: string }>;unfreeze(options?: { automations?: "off" }): Promise<void>;diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex 554e567d1c..1e886cf3b6 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -168,7 +168,7 @@ export function arrivedCounts(here, there) {* journal: { read(): unknown, write(value: unknown): void },* cloud(): null | { origin: string | null, account: string, machine: string | null, ready: boolean, moves: boolean, ended: boolean, paid: boolean,* homecoming?: { installationId: string, name: string }, signIn?: string, verified?: boolean, id?: string, formerOrigins?: string[] },- * send: { move(options?: { final?: boolean }): Promise<unknown>, check(): Promise<{ ok: boolean }>, switches(): Record<string, boolean>, snapshot(): any },+ * send: { move(options?: { final?: boolean, files?: boolean }): Promise<unknown>, check(): Promise<{ ok: boolean }>, switches(): Record<string, boolean>, snapshot(): any },* local: { freeze(origin: string): Promise<{ frozen: true } | { busy: string, what?: string }>, unfreeze(options?: { automations?: "off" }): Promise<void>, frozen(): Promise<boolean>, json(route: string): Promise<any>,* call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }>, forget?(): Promise<void>,* marker?(): Promise<{ frozen: boolean, cloud?: string, place?: string }> },@@ -475,14 +475,14 @@ export function createOneHome(deps) {return next;}- /** Home is My Cloud: tops up what a newer app learned to move, deletes this computer's copy once it is old enough and- * My Cloud was paid for, and comes home if My Cloud ends. */+ /** Home is My Cloud: tops up what a newer app learned to move, never the bots' files the server already has, deletes this+ * computer's copy once it is old enough and My Cloud was paid for, and comes home if My Cloud ends. */async function steady(journal, cloud, waiting) {let next = await settle(journal, cloud);if (cloud?.ended) return ended(next, cloud);// Not while this computer's own copy isn't the server answering: it goes as soon as it is, rather than an hour later.if (!waiting && !next.forgot && deps.version && next.version !== deps.version && cloud?.ready && deps.ownCopy?.() !== false) {- try { await deps.send.move({ final: true }); next = write({ ...next, version: deps.version, retryAt: undefined }); }+ try { await deps.send.move({ final: true, files: false }); next = write({ ...next, version: deps.version, retryAt: undefined }); }catch (error) { log(`one home: the top-up waits (${error?.message ?? error})`); next = write({ ...next, retryAt: now() + HOUR }); }}if (!next.forgot && cloud?.paid && now() - next.doneAt >= KEPT_MS && deps.local.forget) {diff --git a/electron/one-home.node-test.mjs b/electron/one-home.node-test.mjsindex 169df9e57c..1e796697a7 100644--- a/electron/one-home.node-test.mjs+++ b/electron/one-home.node-test.mjs@@ -20,7 +20,7 @@ function world({ cloud = {}, switches = { "routine:r1": true, "routine:r2": falsconst w = {cloud: { origin: CLOUD, account: "acct-1", machine: CLOUD, ready: true, moves: true, ended: false, paid: false, ...cloud },server: { frozen: false, freezes: 0, unfreezes: 0, forgot: 0 },- passes: [], checked: 0, cloudCalls: [], localCalls: [], lent: [], phone: { paired: true, stopped: 0, started: 0 }, opened: [], restarted: 0, brought: [],+ passes: [], moveAsks: [], checked: 0, cloudCalls: [], localCalls: [], lent: [], phone: { paired: true, stopped: 0, started: 0 }, opened: [], restarted: 0, brought: [],again: null, version: "0.1.121",get journal() { return journal; },set journal(value) { journal = value; },@@ -38,8 +38,8 @@ function world({ cloud = {}, switches = { "routine:r1": true, "routine:r2": falscloud: () => (w.cloud ? { ...w.cloud } : null),send: {async move(options) {- const kind = options?.final ? "final" : "copy";- w.passes.push(kind);+ w.passes.push(options?.final ? "final" : "copy");+ w.moveAsks.push(options ?? {});const failure = moves.shift();if (failure) throw failure;},@@ -90,6 +90,7 @@ function world({ cloud = {}, switches = { "routine:r1": true, "routine:r2": falstimers: { set: (work, ms) => { const timer = { work, ms }; timers.push(timer); return timer; }, clear: (timer) => { const at = timers.indexOf(timer); if (at >= 0) timers.splice(at, 1); } },});},+ failNext(error) { moves.push(error); },relaunch() { w.home?.close(); timers.splice(0); w.home = w.make(); return w.home; },switchedOn: () => w.cloudCalls.filter(([method]) => method === "PATCH").map(([, route]) => route),};@@ -490,6 +491,37 @@ test("a newer app tops up once from the frozen copy, which is deleted 30 days afassert.equal(w.server.forgot, 1);});+test("a top-up after the move is done never sends workspace files, and a failed one retries the same way", async () => {+ const w = world();+ await w.home.kick();+ assert.deepEqual(w.moveAsks, [{}, { final: true }], "the move itself still carries the files");++ w.version = "0.1.122";+ await w.relaunch().kick();+ assert.deepEqual(w.moveAsks.at(-1), { final: true, files: false });+ assert.equal(w.journal.version, "0.1.122");+ await w.relaunch().kick();+ assert.equal(w.moveAsks.length, 3, "once per version");++ w.cloud.paid = false;+ w.advance(KEPT_MS);+ w.version = "0.1.123";+ await w.relaunch().kick();+ assert.equal(w.server.forgot, 0, "an unpaid copy, and a server of the person's own, is never deleted");+ assert.deepEqual(w.moveAsks.at(-1), { final: true, files: false }, "the old files are still not sent");++ const again = world();+ await again.home.kick();+ again.version = "0.1.122";+ again.failNext(new Error("offline"));+ await again.relaunch().kick();+ assert.equal(again.journal.version, "0.1.121", "a failed top-up does not count as made");+ again.advance(60 * 60_000);+ await again.tick();+ assert.equal(again.journal.version, "0.1.122");+ assert.deepEqual(again.moveAsks.slice(-2), [{ final: true, files: false }, { final: true, files: false }]);+});+test("one home reads the Admin's word: a ready Cloud the account may move to, and a held one that ended", () => {const state = (machine, extra = {}) => ({ status: "connected", account: { id: "acct-1" }, entitlement: { status: "active" }, machine, ...extra });assert.equal(oneHomeCloud({ status: "signed-out" }), null);diff --git a/electron/own-home-main.mjs b/electron/own-home-main.mjsindex 90c8d540d2..29984e9805 100644--- a/electron/own-home-main.mjs+++ b/electron/own-home-main.mjs@@ -135,7 +135,8 @@ export function installOwnHome({ localRequest, fetch: fetchImpl, environments, ht,});/** The chosen server as the move sees a Cloud: always ready, never ended once home is there, since nothing ends it; until- * then, a server forgotten in this app ends the move before anything runs there. */+ * then, a server forgotten in this app ends the move before anything runs there. Once the move is done the bots' files+ * stay there: this copy is never deleted, so a later pass must not send them again. */const target = () => {const picked = chosen();if (!picked) return null;@@ -145,7 +146,13 @@ export function installOwnHome({ localRequest, fetch: fetchImpl, environments, hconst home = createOneHome({journal,cloud: target,- send: { move: (options) => send.send({ reason: "move", final: options?.final === true }), check: () => send.check(), switches: () => send.switches(), snapshot: () => send.snapshot() },+ send: {+ move(options) {+ const done = parseJournal(journal.read())?.phase === "done";+ return send.send({ reason: "move", final: options?.final === true, ...(options?.files === false || done ? { files: false } : {}) });+ },+ check: () => send.check(), switches: () => send.switches(), snapshot: () => send.snapshot(),+ },local: {...local,freeze: async (origin) => freezeAnswer(await local.call("POST", "/api/move/freeze", { cloud: origin, place: chosen()?.name })),diff --git a/electron/own-home-main.node-test.mjs b/electron/own-home-main.node-test.mjsindex 9b1800876b..1569ad145b 100644--- a/electron/own-home-main.node-test.mjs+++ b/electron/own-home-main.node-test.mjs@@ -1,4 +1,5 @@import assert from "node:assert/strict";+import { createHash } from "node:crypto";import test from "node:test";import { handSaved, installOwnHome, openServerSession, OWNER_KNOWN_MS, OWNER_RETRY_MS, parseChoice } from "./own-home-main.mjs";@@ -157,3 +158,68 @@ test("a server that does not say who owns it is asked once at a time, and againassert.equal(to(family.origin), 2, "while its first ask still waits");own.close();});++test("after an own-home move is done, an app update does not send the old workspace files, and the copy is never deleted", async () => {+ const sha = (text) => createHash("sha256").update(text).digest("hex");+ const file = (path, text) => ({ path, size: Buffer.byteLength(text), sha256: sha(text) });+ const oldFiles = [file("workspaces/ember/.git/refs/heads/main", "old-ref"), file("workspaces/ember/notes.md", "mine")];+ const serverFiles = [file("workspaces/ember/.git/refs/heads/main", "new-ref"), file("workspaces/ember/notes.md", "theirs")];+ const bytes = { "workspaces/ember/.git/refs/heads/main": "old-ref", "workspaces/ember/notes.md": "mine" };+ const botItem = { key: "bot:ember", kind: "bot", label: "Ember", id: "ember", parts: { soul: "s" } };+ const summary = { v: 1, appVersion: "0.1.151", items: [botItem], chats: 1 };+ const choice = { v: 1, id: "g", origin: garage.origin, environmentId: ID, name: "Garage server", at: 1 };+ const cloud = { origin: garage.origin, account: `own:${ID}`, machine: garage.origin, name: "Garage server" };+ const journal = memory({ v: 1, phase: "done", cloud, doneAt: 1_000, version: "0.1.151", lent: true, told: true });+ const asked = [];+ const lines = [];+ const localRequest = async (route) => {+ const path = route.split("?")[0];+ const query = route.includes("?") ? route.slice(route.indexOf("?") + 1) : "";+ asked.push(`local ${route}`);+ if (path === "/api/cloud-send/files" && query.startsWith("path=")) {+ const body = bytes[new URLSearchParams(query).get("path")];+ return body ? new Response(Buffer.from(body)) : Response.json({}, { status: 404 });+ }+ if (path === "/api/cloud-send/files") return Response.json({ v: 1, files: oldFiles });+ if (path === "/api/cloud-send") return Response.json(summary);+ if (path === "/api/cloud-connections") return Response.json({ computer: { environmentId: "env-mac", label: "MacBook" }, connections: [], engines: [], commands: [] });+ if (path === "/api/bots") return Response.json({ bots: [{ id: "ember", name: "Ember", threadId: "t-ember" }] });+ if (path === "/api/cloud-send/memory") return Response.json(query.startsWith("bot=") ? { v: 1, files: [], journal: [] } : { v: 1, about: { learned: [], removed: [] }, teams: [] });+ if (path.endsWith("/skills")) return Response.json({ skills: [] });+ if (path.endsWith("/memory")) return Response.json({ topics: [] });+ if (path === "/api/cloud-send/chats") return Response.json({ v: 1, dataDir: "/desk/.openmausbot", conversations: [], attachments: [] });+ return Response.json({ v: 1 });+ };+ const fetch = async (url, init) => {+ const { pathname, search } = new URL(url);+ const method = init?.method ?? "GET";+ asked.push(`${method} ${pathname}${search}`);+ if (pathname === "/api/auth/session") return Response.json({ kind: "session", scopes: ["admin"], own: true });+ if (pathname === "/.well-known/openmausbot/environment") return Response.json({ environmentId: ID, capabilities: { move: 1 } });+ if (pathname === "/api/cloud-connections") return Response.json({ computer: { environmentId: "env-srv", label: "Garage" }, connections: [], engines: [], commands: [] });+ if (pathname === "/api/cloud-send/files" && method === "POST") return Response.json({ stored: true }, { status: 201 });+ if (pathname === "/api/cloud-send/files") return Response.json({ v: 1, files: serverFiles, space: { freeBytes: 1e12, volumeBytes: 1e12 } });+ if (pathname === "/api/cloud-send") return Response.json(summary);+ if (pathname === "/api/cloud-send/memory") return Response.json({ v: 1, files: 0, journal: 0, about: 0, teams: 0 });+ if (pathname === "/api/cloud-send/chats") return Response.json({ v: 1, conversations: [] });+ return Response.json({ v: 1 });+ };+ const open = (version) => installOwnHome({+ localRequest, fetch, environments: () => [garage], handoff: async () => ({}), journal, choice: memory(choice), sendState: memory(), cloudJournal: () => null,+ version, log: (line) => lines.push(line), now: () => 5_000_000,+ });+ const files = () => asked.filter((line) => line.includes("/api/cloud-send/files"));+ const first = open("0.1.152");+ await first.kick();+ assert.equal(first.journal().version, "0.1.152", lines.join("\n"));+ assert.equal(first.journal().phase, "done");+ assert.equal(first.journal().forgot, undefined, "a server of the person's own is never paid, so this copy is not deleted");+ assert.deepEqual(files(), [], "the version change does not list or send the old workspace, including .git");+ first.close();++ const second = open("0.1.153");+ await second.kick();+ assert.equal(second.journal().version, "0.1.153", lines.join("\n"));+ assert.deepEqual(files(), []);+ second.close();+});