Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(local-profiles): ask before a switch stops work under way, with a choice to wait
AdityaUmale3b0779633ad9
diff --git a/electron/local-profiles.d.mts b/electron/local-profiles.d.mtsindex 14de844364..f7bae3f280 100644--- a/electron/local-profiles.d.mts+++ b/electron/local-profiles.d.mts@@ -49,6 +49,10 @@ export function createLocalProfiles(deps: {onLocal(): boolean;busy(): Promise<{ name: string; what?: string } | null>;trash(dir: string): Promise<void>;+ /** Asked once when a switch finds work under way in the workspace it would stop (`leaving`: its id, null for This+ * computer's own copy; `target`: the one that would open, null likewise; `name`: who works there, "" when unknown).+ * "wait": no time limit; "stop": at most settleMs from the answer; "cancel": nothing switches. */+ ask?: ((input: { leaving: string | null; target: string | null; name: string }) => Promise<"wait" | "stop" | "cancel">) | null;reserved?(): string | null;allowed?(): boolean;remember?(place: { profile: string } | null): void;diff --git a/electron/local-profiles.mjs b/electron/local-profiles.mjsindex 0c90e554e0..66a7b11e61 100644--- a/electron/local-profiles.mjs+++ b/electron/local-profiles.mjs@@ -139,7 +139,7 @@ export function createProfileRegistry({ dataDir, fs = nodeFs, now = Date.now, ra* what This Mac is called here (This Mac or This PC). `remember(place)`: the place the next launch opens:* the workspace that opened, or null once This computer's own copy is back.*/-export function createLocalProfiles({ registry, clean, dataDir, home, window: shown, showLocal, onLocal, busy, trash, reserved = () => null, allowed = () => true,+export function createLocalProfiles({ registry, clean, dataDir, home, window: shown, showLocal, onLocal, busy, trash, ask = null, reserved = () => null, allowed = () => true,remember = () => {}, changed = () => {}, log = () => {}, fs = nodeFs, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now, settleMs = SETTLE_MS }) {/** Each switch asked for; a newer one (another tile, My Cloud) ends the wait of the one before. */let turn = 0;@@ -150,17 +150,28 @@ export function createLocalProfiles({ registry, clean, dataDir, home, window: shconst running = () => clean.profile();const tell = () => { try { changed(); } catch {} };- /** Waits while the server that runs now still works and will stop for this switch, at most `settleMs`. False when a newer- * switch took over. */+ /** Waits while the server that runs now still works and will stop for this switch, at most `settleMs`, or as long as it+ * takes when `ask` says to wait. False when a newer switch took over or `ask` said to stay. */async function settle(mine, target, stops) {if (!stops) return true;- const until = now() + settleMs;+ let until = now() + settleMs;+ let asked = !ask;for (;;) {if (mine !== turn) return false;let who = null;try { who = await busy(); } catch {}if (mine !== turn) return false;if (!who) break;+ if (!asked) {+ // The person chooses: wait for the work however long it takes, stop it (the SETTLE_MS limit as before), or stay.+ asked = true;+ let choice = "stop";+ try { choice = await ask({ leaving: running(), target, name: who.name || "" }); } catch {}+ if (mine !== turn) return false;+ if (choice === "cancel") { turn++; if (settling) { settling = null; tell(); } return false; }+ until = choice === "wait" ? Infinity : now() + settleMs; // the minute starts once the person answered+ continue;+ }if (now() >= until) { log(`local profiles: ${target} opens though ${who.name || who.what || "a turn"} still works`); break; }if (settling?.id !== target || settling.name !== who.name) { settling = { id: target, name: who.name || "" }; tell(); }await sleep(SETTLE_POLL_MS);diff --git a/electron/local-profiles.node-test.mjs b/electron/local-profiles.node-test.mjsindex 92f0abf160..df7633f7ca 100644--- a/electron/local-profiles.node-test.mjs+++ b/electron/local-profiles.node-test.mjs@@ -16,7 +16,7 @@ function computer(t, { home = "cloud", frozen = home === "cloud" } = {}) {mkdirSync(dataDir, { recursive: true });if (frozen) writeFileSync(join(dataDir, "moved.json"), JSON.stringify({ v: 1, at: 1, cloud: "https://omb-t-1.fly.dev" }));let clock = 1_000;- const w = { dataDir, running: dataDir, swaps: [], home, shown: null, onScreen: "cloud", busy: [], trashed: [], trashFails: false, changes: 0, logs: [], waits: 0, remembered: [] };+ const w = { dataDir, running: dataDir, swaps: [], home, shown: null, onScreen: "cloud", busy: [], trashed: [], trashFails: false, changes: 0, logs: [], waits: 0, remembered: [], asked: [] };w.now = () => clock;w.clean = createCleanWorkspace({ dataDir: () => dataDir, running: () => w.running,swap: async (dir) => { w.swaps.push(dir); await new Promise((resolve) => setImmediate(resolve)); w.running = dir; w.onScreen = "local"; return { ok: true }; } });@@ -29,9 +29,10 @@ function computer(t, { home = "cloud", frozen = home === "cloud" } = {}) {},showLocal: () => { w.onScreen = "local"; }, onLocal: () => w.onScreen === "local",busy: async () => w.busy[0] ?? null,+ ask: async (input) => { w.asked.push(input); return w.answer ? w.answer(input) : "stop"; },trash: async (dir) => { if (w.trashFails) throw new Error("no Trash here"); w.trashed.push(dir); rmSync(dir, { recursive: true, force: true }); },reserved: () => "This Mac", remember: (place) => w.remembered.push(place), changed: () => { w.changes++; }, log: (line) => w.logs.push(line), now: w.now,- sleep: async (ms) => { clock += ms; w.waits++; w.onWait?.(); } });+ sleep: w.sleep = async (ms) => { clock += ms; w.waits++; w.onWait?.(); } });w.file = () => join(profilesDir(dataDir), PROFILES_FILE);w.saved = () => JSON.parse(readFileSync(w.file(), "utf8"));return w;@@ -159,6 +160,33 @@ test(`a switch waits at most ${SETTLE_MS / 1000} s: then the server stops as a qassert.match(w.logs.at(-1), /work opens though Scout still works/);});+test("the person picks how a busy switch goes: asked once, wait has no time limit, cancel opens nothing", async (t) => {+ const w = computer(t);+ w.profiles.create({ name: "Work" });+ await w.profiles.open(DEFAULT_PROFILE);+ assert.deepEqual(w.asked, [], "nothing busy: never asked");+ w.busy = [{ name: "Scout", what: "bot" }];+ w.answer = () => "wait";+ w.onWait = () => { if (w.waits === SETTLE_MS / 1000 + 5) w.busy = []; };+ assert.equal(await w.profiles.open("work"), true);+ assert.equal(w.waits, SETTLE_MS / 1000 + 5, "waited past the limit until Scout finished");+ assert.deepEqual(w.asked, [{ leaving: DEFAULT_PROFILE, target: "work", name: "Scout" }], "asked once");+ assert.equal(w.profiles.settling(), null);++ w.busy = [{ name: "Scout", what: "bot" }];+ w.waits = 0; w.asked = []; w.onWait = null; w.answer = () => "cancel";+ const swaps = w.swaps.length;+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), null, "stayed");+ assert.equal(w.swaps.length, swaps, "nothing stopped or started");+ assert.equal(w.waits, 0);+ assert.equal(w.asked.length, 1);++ w.answer = async () => { await w.sleep(2 * SETTLE_MS); return "stop"; };+ w.waits = 0;+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), true);+ assert.equal(w.waits, 1 + SETTLE_MS / 1000, "stop keeps the limit, counted from the answer");+});+test("nothing to wait for when the frozen copy runs: My Cloud's first This Mac opens at once", async (t) => {const w = computer(t);w.busy = [{ name: "never asked", what: "bot" }];diff --git a/electron/main.mjs b/electron/main.mjsindex a3a150b9bb..846a5b1259 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -2630,7 +2630,7 @@ function showHome(options) {}const showStartPlace = () => openStartPlace({ home: homeWindow, places: homePlaces, profiles: localProfiles, log: slog, server: id => { const entry = environmentsState.environments.find(candidate => candidate.id === id && handSaved(candidate)); return entry ? reopenSavedServer(entry, { saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (found) => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); persistEnvironments(withActive(environmentsState, found.id)); return navigateMainWindow(activeOrigin()); } }) : Promise.resolve(false); } }).catch(error => slog(`start: ${error?.message ?? error}`)); const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() });-const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };+const thisComputerName = () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"); const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: thisComputerName, ask: async ({ leaving, target, name: bot }) => { const label = id => (id && localProfiles.name(id)) || thisComputerName(); const name = label(leaving); const options = { type: "question", buttons: [nativeT("native.places.busyWait"), nativeT("native.places.busyStop"), nativeT("native.common.cancel")], defaultId: 0, cancelId: 2, message: bot ? nativeT("native.places.busyMessage", { bot, name }) : nativeT("native.places.busyMessageAny", { name }), detail: nativeT("native.places.busyDetail", { name, target: label(target) }) }; const shownOn = mainWindow && !mainWindow.isDestroyed() ? mainWindow : null; return ["wait", "stop", "cancel"][(await (shownOn ? dialog.showMessageBox(shownOn, options) : dialog.showMessageBox(options))).response] ?? "cancel"; }, remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],diff --git a/src/locales/en.json b/src/locales/en.jsonindex 8be16df278..79f082fad6 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -9486,6 +9486,11 @@"native.cloud.ready.quotedTitle": "“{name}” is ready","native.places.noLongerHere": "That place isn't here any more.","native.places.profileFailed": "This computer's own place didn't open. Try again in a moment.",+ "native.places.busyMessage": "{bot} is still working in {name}",+ "native.places.busyMessageAny": "Work is still under way in {name}",+ "native.places.busyDetail": "Only one place on this computer runs at a time. Switching to {target} stops {name}'s bots and automations until you come back. Wait, and {target} opens as soon as the work finishes; stop it, and it gets up to a minute before it stops.",+ "native.places.busyWait": "Wait for it to finish",+ "native.places.busyStop": "Stop it and switch","native.places.cannotAdd": "That isn't something to add here.","native.cloud.addSignIn": "Sign in to MausBot Cloud first.","native.cloud.addPlanAndName": "Choose a plan and a name to continue.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex d7daf535db..076c2d6f52 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -651,6 +651,11 @@"homeLine.profile": "{name} começa do zero, separado do My Cloud. Os bots que você tinha aqui estão no My Cloud; para trazer uma cópia antiga, importe o backup dela em Configurações → Backups.","homeLine.local": "{name} começa do zero: um lugar separado neste computador, com bots, conversas e arquivos próprios.","native.places.profileFailed": "O lugar próprio deste computador não abriu. Tente de novo em instantes.",+ "native.places.busyMessage": "{bot} ainda está trabalhando em {name}",+ "native.places.busyMessageAny": "Ainda há trabalho em andamento em {name}",+ "native.places.busyDetail": "Só um lugar roda por vez neste computador. Mudar para {target} para os bots e automações de {name} até você voltar. Se esperar, {target} abre assim que o trabalho terminar; se parar, ele tem até um minuto antes de parar.",+ "native.places.busyWait": "Esperar terminar",+ "native.places.busyStop": "Parar e mudar","rail.settingUp": "{name}: em configuração","rail.waiting": "{name}: aguardando pagamento","rail.attention": "{name}: aguardando você",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex dbaeee11a4..4a08f6a160 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -33737,7 +33737,12 @@"vault.choices.secret": "674c8e779f1cf487aed7a0bac207212a9c6befdc477c36831bb03db9d0ea687c","vault.choices.login": "b8882ff1b3da41df0ede863cc92e631ac828ab4f964f4e66ef751edf1ad18576","vault.choices.note": "ac0cee8d6047623427bb117e12f74028b2297651c85cbc69bf018af03bb47a98",- "vault.choices.error": "fc55267ee3d6c9b47bf7f2e4e04bebfae80778636ee69db98ec55e699f90ea88"+ "vault.choices.error": "fc55267ee3d6c9b47bf7f2e4e04bebfae80778636ee69db98ec55e699f90ea88",+ "native.places.busyMessage": "32d8f1dd6e0d2e4ac8b8f0439bc016f0524c62d07c5a191b47a4aaaefebdfb80",+ "native.places.busyMessageAny": "0c556ff52d91843d73cfa9232af0f2829c8ac1ace73d0a377c5e8d08816a9374",+ "native.places.busyDetail": "c6a9c3ceedbb50350174c7f0f632a1c22b98d343d09f09e47e0f93a273a2de44",+ "native.places.busyWait": "fd0383a0789a3d3eb7f5364d6e54d66b5c35291e933ce65db232f89522e03b3a",+ "native.places.busyStop": "caa52bc4eb1b79daff26ddfa58aaa33c8dba0142d325764438dea939c3b8a426"},"zh": {"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",