Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Show the person what is keeping this computer from their Cloud (#5139)
Milind Soni1584c1abe6a7
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex 91b11c724b..bdda60389f 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -203,6 +203,9 @@ const LENT_PLATFORMS = new Set(["darwin", "win32", "linux"]);const RECONNECT_EVERY_MS = 15 * 60_000;/** Waits before the device link is dialled again, longer after each attempt that never opened. */const LINK_RETRY_MS = [2_000, 5_000, 15_000, 60_000];+/** Lending that is failing, as the menu and a notification say it; a sleeping Cloud or a Pause is no failure. */+const WHY_NOT_LENT = Object.freeze({ "connect-first": "native.lendTray.whySignIn", "machine-changed": "native.lendTray.whyMoved", "account-changed": "native.lendTray.whyAccount", "not-cloud": "native.lendTray.whyMoved", "not-own": "native.lendTray.whyMoved" });+const whyNotLent = problem => WHY_NOT_LENT[problem] ?? "native.lendTray.whyUnreachable";/** The link carried bytes this recently: the tray says the computer is in use. */const IN_USE_MS = 5_000;/** A site opened through this computer goes into its activity once per outcome in this long, so a page's many@@ -259,12 +262,14 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loconst browsing = [...inUse.keys()].find(id => linked.has(id));const lent = paused ? [] : environments().filter(env => (records[env.id]?.cloud || records[env.id]?.own) && records[env.id]?.enabled === true);const using = lent.filter(env => executing?.env === env.id || (inUse.has(env.id) && linked.has(env.id)));+ const problems = lendingProblems(lent);return {lending: lent.map(env => env.id),clouds: (paused ? [...ownClouds(), ...environments().filter(env => records[env.id]?.own && records[env.id].enabled === true)] : lent).map(env => env.name),// Lent, but the Cloud hasn't accepted this computer yet (or lost it): the menu must not say it can use it. A// sleeping My Cloud still can; it wakes when a bot needs this computer.waiting: lent.filter(env => !status.get(env.id)?.connected && status.get(env.id)?.problem !== "asleep").map(env => env.name),+ ...(problems.length ? { problems } : {}),using: using.map(env => env.name),paused,...(pauseError ? { pauseError } : {}),@@ -275,6 +280,23 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loscreen: screenNow,};};+ /** What is keeping this computer from a Cloud of the person's own, for the menu and one notification: a Cloud it can't+ * reach or stay signed in to, lending that ended by itself, and a signed-in My Cloud this app has no saved place for. */+ const lendingProblems = lent => {+ if (paused) return [];+ const failing = lent.flatMap(env => {+ const now = status.get(env.id);+ return now && !now.connected && now.problem !== "asleep" && now.problem !== "paused" && (now.problem || now.error) ? [{ name: env.name, why: t(whyNotLent(now.problem)) }] : [];+ });+ const ended = environments().flatMap(env => {+ const record = records[env.id], reason = record?.stopped?.reason;+ return record?.cloud && record.enabled !== true && (reason === "machine-changed" || reason === "account-changed") && !lent.includes(env) ? [{ name: env.name, why: t(whyNotLent(reason)) }] : [];+ });+ const signedIn = cloud();+ const homeless = signedIn?.status === "connected" && signedIn.origin && !environments().some(env => env.origin === signedIn.origin)+ ? [{ name: t("native.lendTray.myCloud"), why: t("native.lendTray.whyNoServer") }] : [];+ return [...failing, ...ended, ...homeless];+ };/** Whether apps and screen are lent now; the icon's menu follows any change in why not. */const readScreen = () => Promise.resolve().then(screen).then(status => status, () => null).then(status => {const next = status && typeof status === "object" ? status : null;diff --git a/electron/lend-automatically.node-test.mjs b/electron/lend-automatically.node-test.mjsindex ff4780b69d..c2c16788e8 100644--- a/electron/lend-automatically.node-test.mjs+++ b/electron/lend-automatically.node-test.mjs@@ -99,6 +99,50 @@ async function computer(t, { places = [myCloud, clientA, acme], screen = () => freturn { dir, file, target, summaries, dials, signedIn, get sharing() { return sharing; }, restart: () => { sharing.close(); sharing = make(); return sharing; } };}+test("a Cloud that won't take this computer, or a signed-in My Cloud with no saved place, says so where the person can see it", async t => {+ const refuses = cloudHome();+ const answer = refuses.fetch;+ refuses.fetch = async (url, init) => new URL(url).pathname === "/api/shared-computers/connect"+ ? { ok: false, status: 403, headers: { get: () => null }, body: (async function* () { yield Buffer.from("{}"); })() }+ : answer(url, init);+ const mac = await computer(t, { homes: { [HOME]: refuses }, places: [myCloud] });+ mac.sharing.start();+ await until(() => mac.summaries.at(-1)?.problems?.length === 1, "the refusal to be reported");+ assert.deepEqual(mac.summaries.at(-1).problems, [{ name: "My Cloud", why: "this app's sign-in to it ended. Open it from this app to sign in again." }]);+ assert.equal(indicatorText(mac.summaries.at(-1), "Mac").problems[0], "My Cloud can't use this Mac: this app's sign-in to it ended. Open it from this app to sign in again.");+ mac.sharing.pause();+ assert.equal(mac.summaries.at(-1).problems, undefined, "Paused is the person's own choice, not a problem");++ const homeless = await computer(t, { places: [] });+ homeless.sharing.start();+ await until(() => homeless.summaries.at(-1)?.problems?.length === 1, "the missing place to be reported");+ assert.deepEqual(homeless.summaries.at(-1).problems, [{ name: "My Cloud", why: "this app has no saved place for it yet. Open My Cloud from this app once." }]);+});++test("the menu shows what is keeping a Cloud away, and one notification says so once it has lasted", t => {+ const shown = [];+ class Notification { constructor(options) { this.options = options; } show() { shown.push(this.options); } }+ const timers = [];+ const trays = [];+ class Tray { constructor() { trays.push(this); } on() {} setToolTip(value) { this.tip = value; } setTitle() {} setContextMenu(menu) { this.menu = menu; } isDestroyed() { return false; } destroy() {} }+ const indicator = createLendingIndicator({ Tray, Menu: { buildFromTemplate: items => items }, nativeImage: { createFromPath: () => ({ resize: () => ({}) }) }, iconPath: "icon.png",+ onPause() {}, onResume() {}, onActivity() {}, onTerminal() {}, device: "Mac", Notification, setTimer: (run) => { timers.push(run); return { unref() {} }; }, clearTimer: () => { timers.length = 0; } });+ const problem = { name: "My Cloud", why: "this app can't reach it." };+ indicator.update({ clouds: [], using: [], paused: false, problems: [problem] });+ assert.equal(trays.length, 1, "shown even with nothing else lent yet");+ assert.equal(trays[0].menu[0].label, "My Cloud can't use this Mac: this app can't reach it.");+ assert.equal(shown.length, 0, "a blip is no news");+ timers.shift()();+ assert.deepEqual(shown, [{ title: "My Cloud can't use this Mac", body: "this app can't reach it." }]);+ indicator.update({ clouds: ["My Cloud"], using: [], paused: false, problems: [problem] });+ assert.equal(timers.length, 0, "already told");+ indicator.update({ clouds: ["My Cloud"], using: [], paused: false, problems: [] });+ indicator.update({ clouds: ["My Cloud"], using: [], paused: false, problems: [problem] });+ timers.shift()();+ assert.equal(shown.length, 2, "it came back, so it is news again");+ t.diagnostic("the notification names the Cloud and the fix");+});+test("each Cloud of the person's own is lent this computer by itself: the internet connection, their Chrome and the home folder with editing; not the terminal unless turned on", async t => {const homes = { [HOME]: cloudHome(), [OTHER]: cloudHome() };const dir = await scratch(t);diff --git a/electron/lending-indicator.mjs b/electron/lending-indicator.mjsindex f5b78ed585..6ce5a575f0 100644--- a/electron/lending-indicator.mjs+++ b/electron/lending-indicator.mjs@@ -11,35 +11,63 @@ const short = (names, t) => names.length < 3 ? listed(names, t) : t("native.lend* can't use, and `screen` why. *//** `waiting`: lent Clouds that haven't accepted this computer yet; they are never said to be able to use it, and* `pending` says who is still being waited for. */-export function indicatorText({ clouds, using, paused, pauseError, screen = null, waiting = [] }, device, t = nativeText.englishText.t) {+export function indicatorText({ clouds, using, paused, pauseError, screen = null, waiting = [], problems = [] }, device, t = nativeText.englishText.t) {const named = device === "computer" ? t("native.lendTray.computer") : device;if (pauseError) return { line: t("native.lendTray.pauseUnsaved"), title: t("native.lendTray.pauseUnsavedTitle"), screen: null };if (paused) return { line: t("native.lendTray.pausedLine", { clouds: listed(clouds, t), device: named }), title: t("native.lendTray.paused"), screen: null };+ const said = problems.map(problem => t("native.lendTray.problem", { cloud: problem.name, device: named, why: problem.why }));+ const wrong = said.length ? { problems: said } : {};+ if (!clouds.length && said.length) return { line: said[0], title: "", screen: null, problems: said.slice(1) };const why = screenLine(screen, device, t);const pending = waiting.length ? { pending: t("native.lendTray.waiting", { clouds: listed(waiting, t), device: named }) } : {};if (using.length) {const key = using.length > 1 ? "native.lendTray.usingMany" : "native.lendTray.usingOne";- return { line: t(key, { clouds: listed(using, t), device: named }), title: t(key, { clouds: short(using, t), device: named }), screen: why, ...pending };+ return { line: t(key, { clouds: listed(using, t), device: named }), title: t(key, { clouds: short(using, t), device: named }), screen: why, ...pending, ...wrong };}const ready = clouds.filter(name => !waiting.includes(name));- if (!ready.length) return { line: pending.pending ?? t("native.lendTray.canUse", { clouds: listed(clouds, t), device: named }), title: "", screen: why };+ if (!ready.length) return { line: pending.pending ?? t("native.lendTray.canUse", { clouds: listed(clouds, t), device: named }), title: "", screen: why, ...wrong };const line = t(why ? "native.lendTray.canUseWithoutScreen" : "native.lendTray.canUse", { clouds: listed(ready, t), device: named });- return { line, title: "", screen: why, ...pending };+ return { line, title: "", screen: why, ...pending, ...wrong };}-export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPause, onResume, onActivity, onTerminal, onStartScreen = () => {}, device = deviceWord(), t = nativeText.englishText.t }) {+/** How long lending has to stay broken before a notification says so: a blip is no news. */+const NOTICE_AFTER_MS = 10 * 60_000;++export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPause, onResume, onActivity, onTerminal, onStartScreen = () => {}, device = deviceWord(), t = nativeText.englishText.t, Notification = null, setTimer = setTimeout, clearTimer = clearTimeout }) {let tray = null;let shown = null;+ /** Each problem now, by what it says, until the notification for it goes out or it clears. */+ const noticeTimers = new Map(), notified = new Set();+ const followProblems = problems => {+ const now = new Set(problems.map(problem => `${problem.name}\n${problem.why}`));+ for (const key of noticeTimers.keys()) if (!now.has(key)) { clearTimer(noticeTimers.get(key)); noticeTimers.delete(key); }+ for (const key of notified) if (!now.has(key)) notified.delete(key);+ for (const problem of problems) {+ const key = `${problem.name}\n${problem.why}`;+ if (noticeTimers.has(key) || notified.has(key)) continue;+ const timer = setTimer(() => {+ noticeTimers.delete(key);+ notified.add(key);+ if (!Notification || Notification.isSupported?.() === false) return;+ try {+ new Notification({ title: t("native.lendTray.problemNoticeTitle", { cloud: problem.name, device: device === "computer" ? t("native.lendTray.computer") : device }), body: problem.why }).show();+ } catch {}+ }, NOTICE_AFTER_MS);+ timer?.unref?.();+ noticeTimers.set(key, timer);+ }+ };const draw = view => {if (!tray || tray.isDestroyed()) return;- const { line, title, screen, pending } = indicatorText(view, device, t);+ const { line, title, screen, pending, problems = [] } = indicatorText(view, device, t);const fix = screen ? screenFixLabel(view.screen, t) : null;- tray.setToolTip(`OpenMausBot: ${line}${pending ? `. ${pending}` : ""}${screen ? `. ${screen}` : ""}`);+ tray.setToolTip(`OpenMausBot: ${line}${pending ? `. ${pending}` : ""}${screen ? `. ${screen}` : ""}${problems.length ? `. ${problems.join(". ")}` : ""}`);// Electron shows a tray title beside the icon on macOS only.tray.setTitle?.(title);tray.setContextMenu(Menu.buildFromTemplate([{ label: line, enabled: false },...pending ? [{ label: pending, enabled: false }] : [],+ ...problems.map(problem => ({ label: problem, enabled: false })),...screen ? [{ label: screen, enabled: false }] : [],...fix ? [{ label: fix, click: () => onStartScreen() }] : [],{ type: "separator" },@@ -52,13 +80,14 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPa]));};return {- update({ clouds = [], using = [], paused = false, pauseError, terminal = false, terminalSwitch = true, screen = null, waiting = [] }) {- const next = { clouds: [...clouds], using: paused ? [] : [...using], waiting: paused ? [] : [...waiting], paused: paused === true, ...pauseError ? { pauseError } : {},+ update({ clouds = [], using = [], paused = false, pauseError, terminal = false, terminalSwitch = true, screen = null, waiting = [], problems = [] }) {+ const next = { clouds: [...clouds], using: paused ? [] : [...using], waiting: paused ? [] : [...waiting], problems: paused ? [] : problems.map(({ name, why }) => ({ name, why })), paused: paused === true, ...pauseError ? { pauseError } : {},terminal: terminal === true, terminalSwitch: terminalSwitch !== false,screen: screen ? { ready: screen.ready === true, reason: screen.reason ?? null, fix: screen.fix ?? null, ...(screen.message ? { message: screen.message } : {}) } : null };if (shown && JSON.stringify(next) === JSON.stringify(shown)) return;shown = next;- if (!next.clouds.length) { if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; return; }+ followProblems(next.problems);+ if (!next.clouds.length && !next.problems.length) { if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; return; }if (!tray || tray.isDestroyed()) {tray = new Tray(nativeImage.createFromPath(iconPath).resize({ width: 18, height: 18 }));tray.on("click", () => tray?.popUpContextMenu?.());@@ -66,6 +95,6 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPadraw(next);},relabel() { if (tray && !tray.isDestroyed() && shown) draw(shown); },- destroy() { if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; shown = null; },+ destroy() { for (const timer of noticeTimers.values()) clearTimer(timer); noticeTimers.clear(); if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; shown = null; },};}diff --git a/electron/main.mjs b/electron/main.mjsindex c759165e2d..4e5d546f79 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -1487,7 +1487,7 @@ const lendingActivity = createActivityWindow({ BrowserWindow, icon: APP_ICON, balet lendingTray = null;function lendingIndicator() {lendingTray ??= createLendingIndicator({- Tray, Menu, nativeImage, iconPath: APP_ICON, t: nativeT, onPause: () => sharingController().pause(), onActivity: () => lendingActivity.show(),+ Tray, Menu, nativeImage, Notification, iconPath: APP_ICON, t: nativeT, onPause: () => sharingController().pause(), onActivity: () => lendingActivity.show(),onResume: () => void sharingController().resume()?.catch(error => slog(`lending resume: ${error?.message ?? error}`)), onStartScreen: () => void screenControl.start(),onTerminal: on => void lendingDialogs.lendTerminal(on, () => sharingController().lendTerminal(on)).catch(error => slog(`lending terminal: ${error?.message ?? error}`)),});diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0caecda3d0..7c35949f3f 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -9410,6 +9410,14 @@"native.lendTray.usingMany": "{clouds} are using this {device}","native.lendTray.usingOne": "{clouds} is using this {device}","native.lendTray.canUse": "{clouds} can use this {device}",+ "native.lendTray.problem": "{cloud} can't use this {device}: {why}",+ "native.lendTray.problemNoticeTitle": "{cloud} can't use this {device}",+ "native.lendTray.myCloud": "My Cloud",+ "native.lendTray.whySignIn": "this app's sign-in to it ended. Open it from this app to sign in again.",+ "native.lendTray.whyMoved": "its address changed. Open it from this app to start lending again.",+ "native.lendTray.whyAccount": "you're signed in with a different account now. Sign in with the one you lent it from to keep lending.",+ "native.lendTray.whyNoServer": "this app has no saved place for it yet. Open My Cloud from this app once.",+ "native.lendTray.whyUnreachable": "this app can't reach it. Check the internet connection, and update OpenMausBot if it's out of date.","native.lendTray.waiting": "Waiting for {clouds} to accept this {device}","routines.event.automation": "Automation","routines.event.cronMoveHint": "Open this automation to change its repeating schedule and time zone.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 68fd1d7908..b1cb6ce84c 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -9382,6 +9382,14 @@"native.lendTray.usingMany": "{clouds} estão usando este {device}","native.lendTray.usingOne": "{clouds} está usando este {device}","native.lendTray.canUse": "{clouds} com acesso a este {device}",+ "native.lendTray.problem": "{cloud} não pode usar este {device}: {why}",+ "native.lendTray.problemNoticeTitle": "{cloud} não pode usar este {device}",+ "native.lendTray.myCloud": "My Cloud",+ "native.lendTray.whySignIn": "o login deste app nela terminou. Abra-a por este app para entrar de novo.",+ "native.lendTray.whyMoved": "o endereço dela mudou. Abra-a por este app para voltar a emprestar.",+ "native.lendTray.whyAccount": "você entrou com outra conta agora. Entre com a conta com que emprestou para continuar.",+ "native.lendTray.whyNoServer": "este app ainda não tem um lugar salvo para ela. Abra o My Cloud por este app uma vez.",+ "native.lendTray.whyUnreachable": "este app não consegue alcançá-la. Verifique a internet e atualize o OpenMausBot se estiver desatualizado.","native.lendTray.waiting": "Aguardando {clouds} aceitar este {device}","routines.event.automation": "Automação","routines.event.cronMoveHint": "Abra esta automação para mudar quando ela se repete e ajustar o fuso horário.",