Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Lent computer's menu names the bot using it, with its colour dot
Bugfixer 262c78570d876
diff --git a/electron/cloud-buy.d.mts b/electron/cloud-buy.d.mtsindex bb5481897a..8e3d580268 100644--- a/electron/cloud-buy.d.mts+++ b/electron/cloud-buy.d.mts@@ -5,7 +5,6 @@ export declare const CLOUD_NAME_MAX: number;export declare const CLOUD_COLOR_HEX: Readonly<Record<CloudColor, string>>;export declare function cleanCloudName(value: unknown): string | null;export declare function cleanCloudColor(value: unknown): CloudColor | null;-export declare function colorDotPng(hex: string, size: number, diameter?: number): string;export declare function colorDotIcons<T extends { addRepresentation(options: { scaleFactor: number; dataURL: string }): void; isEmpty(): boolean }>(nativeImage: { createEmpty(): T }): (color: unknown) => T | null;export interface CloudLookRecord { accountId: string; name: string; color: CloudColor }export declare function lookFile(file: () => string, fs: { readFileSync(path: string, encoding: "utf8"): string; writeFileSync(path: string, data: string, options: { mode: number }): void }): { read(): CloudLookRecord | null; write(value: CloudLookRecord): void };diff --git a/electron/cloud-buy.mjs b/electron/cloud-buy.mjsindex 3d7979d889..1edab5c05e 100644--- a/electron/cloud-buy.mjs+++ b/electron/cloud-buy.mjs@@ -1,11 +1,11 @@// The buying sheet's main-process side: the email sign-in, the kept checkout page, the Cloud's name and colour, and// "{name} is ready". Every handler takes the page's words as plain text and checks them here; no token, checkout// address or account leaves main (Copy link writes the clipboard from here).-import { deflateSync } from "node:zlib";import environments from "./environments.cjs";import { CHECKOUT_SOURCES } from "./cloud-account.mjs";import { CLOUD_HOME_NAME } from "./cloud-home.mjs";import nativeText from "./native-text.cjs";+import { dotIcons } from "./color-dot.mjs";export const CLOUD_COLORS = environments.ENTRY_COLORS;export const DEFAULT_CLOUD_COLOR = "blue";@@ -22,45 +22,8 @@ export function cleanCloudName(value) {}export const cleanCloudColor = value => (CLOUD_COLORS.includes(value) ? value : null);-const CRC = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });-const crc32 = bytes => { let c = 0xffffffff; for (const byte of bytes) c = CRC[(c ^ byte) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };-const pngChunk = (type, data) => {- const out = Buffer.alloc(12 + data.length);- out.writeUInt32BE(data.length, 0); out.write(type, 4, "latin1"); data.copy(out, 8);- out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);- return out;-};-/** A filled circle with a soft edge, as a PNG data URL (straight RGBA, so no platform's pixel order matters). */-export function colorDotPng(hex, size, diameter = size * 0.72) {- const [red, green, blue] = [1, 3, 5].map(at => Number.parseInt(hex.slice(at, at + 2), 16));- const rows = Buffer.alloc(size * (size * 4 + 1)), center = size / 2, radius = diameter / 2;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const alpha = Math.max(0, Math.min(1, radius + 0.5 - Math.hypot(x + 0.5 - center, y + 0.5 - center)));- rows.set([red, green, blue, Math.round(alpha * 255)], y * (size * 4 + 1) + 1 + x * 4);- }- }- const header = Buffer.alloc(13);- header.writeUInt32BE(size, 0); header.writeUInt32BE(size, 4); header.set([8, 6, 0, 0, 0], 8);- const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), pngChunk("IHDR", header), pngChunk("IDAT", deflateSync(rows)), pngChunk("IEND", Buffer.alloc(0))]);- return `data:image/png;base64,${png.toString("base64")}`;-}-/** The native switcher's dot for a saved colour (14 pt, sharp at 2x), drawn once per colour; null where it cannot be drawn. */-export function colorDotIcons(nativeImage) {- const made = new Map();- return color => {- if (!cleanCloudColor(color)) return null;- if (!made.has(color)) {- try {- const image = nativeImage.createEmpty();- for (const scaleFactor of [1, 2]) image.addRepresentation({ scaleFactor, dataURL: colorDotPng(CLOUD_COLOR_HEX[color], 14 * scaleFactor) });- made.set(color, image.isEmpty() ? null : image);- } catch { made.set(color, null); }- }- return made.get(color) ?? null;- };-}+export const colorDotIcons = nativeImage => dotIcons(nativeImage, CLOUD_COLOR_HEX);/** The name and colour chosen while the Cloud is set up, kept for its account until the Cloud is listed (userData). */export function lookFile(file, fs) {diff --git a/electron/cloud-buy.node-test.mjs b/electron/cloud-buy.node-test.mjsindex 7edbba4566..b16056a86e 100644--- a/electron/cloud-buy.node-test.mjs+++ b/electron/cloud-buy.node-test.mjs@@ -3,8 +3,9 @@ import test from "node:test";import { readFileSync } from "node:fs";import vm from "node:vm";import { inflateSync } from "node:zlib";-import { CLOUD_COLORS, CLOUD_COLOR_HEX, cleanCloudColor, cleanCloudName, cloudLinkOpensSheet, colorDotIcons, colorDotPng, createCloudLook, createCloudReadyNotice,+import { CLOUD_COLORS, CLOUD_COLOR_HEX, cleanCloudColor, cleanCloudName, cloudLinkOpensSheet, colorDotIcons, createCloudLook, createCloudReadyNotice,installCloudBuy, lookFile } from "./cloud-buy.mjs";+import { colorDotPng } from "./color-dot.mjs";import environments from "./environments.cjs";const origin = "https://omb-u-1a2b3c4d5e6f.fly.dev";diff --git a/electron/color-dot.mjs b/electron/color-dot.mjsnew file mode 100644index 0000000000..dac38ff9f7--- /dev/null+++ b/electron/color-dot.mjs@@ -0,0 +1,46 @@+// A coloured dot for native menus (the Cloud switcher, the lending icon's menu), drawn as a PNG without a canvas.+import { deflateSync } from "node:zlib";++const CRC = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });+const crc32 = bytes => { let c = 0xffffffff; for (const byte of bytes) c = CRC[(c ^ byte) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };+const pngChunk = (type, data) => {+ const out = Buffer.alloc(12 + data.length);+ out.writeUInt32BE(data.length, 0); out.write(type, 4, "latin1"); data.copy(out, 8);+ out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);+ return out;+};+/** A filled circle with a soft edge, as a PNG data URL (straight RGBA, so no platform's pixel order matters). */+export function colorDotPng(hex, size, diameter = size * 0.72) {+ const [red, green, blue] = [1, 3, 5].map(at => Number.parseInt(hex.slice(at, at + 2), 16));+ const rows = Buffer.alloc(size * (size * 4 + 1)), center = size / 2, radius = diameter / 2;+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < size; x++) {+ const alpha = Math.max(0, Math.min(1, radius + 0.5 - Math.hypot(x + 0.5 - center, y + 0.5 - center)));+ rows.set([red, green, blue, Math.round(alpha * 255)], y * (size * 4 + 1) + 1 + x * 4);+ }+ }+ const header = Buffer.alloc(13);+ header.writeUInt32BE(size, 0); header.writeUInt32BE(size, 4); header.set([8, 6, 0, 0, 0], 8);+ const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), pngChunk("IHDR", header), pngChunk("IDAT", deflateSync(rows)), pngChunk("IEND", Buffer.alloc(0))]);+ return `data:image/png;base64,${png.toString("base64")}`;+}++/** Each mascot colour in the default skin (src/lib/mascot.ts MAUS_COLORS), for a bot's dot in a native menu. */+export const BOT_COLOR_HEX = Object.freeze({ green: "#009957", blue: "#377FE6", red: "#D94B52", orange: "#E78531", purple: "#8057C8", cyan: "#0EA5C6",+ pink: "#D84F8B", yellow: "#D8A729", teal: "#01A492", coral: "#E5634E", silver: "#A8ADB4", chrome: "#B3BAC4" });++/** A menu dot for each colour named in `hexes` (14 pt, sharp at 2x), drawn once per colour; null where it cannot be drawn. */+export function dotIcons(nativeImage, hexes = BOT_COLOR_HEX) {+ const made = new Map();+ return color => {+ if (typeof color !== "string" || !Object.hasOwn(hexes, color)) return null;+ if (!made.has(color)) {+ try {+ const image = nativeImage.createEmpty();+ for (const scaleFactor of [1, 2]) image.addRepresentation({ scaleFactor, dataURL: colorDotPng(hexes[color], 14 * scaleFactor) });+ made.set(color, image.isEmpty() ? null : image);+ } catch { made.set(color, null); }+ }+ return made.get(color) ?? null;+ };+}diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex bdda60389f..d21745a357 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -18,6 +18,7 @@ import { createComputerAsks } from "./computer-asks.mjs";import { LINK_ASLEEP, linkPath } from "./device-link-protocol.mjs";import { shareableDrive } from "./shared-drives.mjs";import nativeText from "./native-text.cjs";+import { actingBot } from "./lending-indicator.mjs";const uuid = value => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(value);const DATA_VOLUME = "/System/Volumes/Data";@@ -208,6 +209,8 @@ const WHY_NOT_LENT = Object.freeze({ "connect-first": "native.lendTray.whySignInconst 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;+/** The menu keeps naming the bot that acted here this long after its last action, so it doesn't flicker between steps. */+const ACTING_MS = 30_000;/** A site opened through this computer goes into its activity once per outcome in this long, so a page's many* connections are one line. */const BROWSE_NOTE_MS = 10 * 60_000;@@ -254,6 +257,17 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo/** The Clouds whose device link is open now. */const linked = new Set();const inUse = new Map();+ /** Each bot that acted here lately, by Cloud and bot name, until ACTING_MS after its last action. */+ const acting = new Map();+ const actedFor = (id, by) => {+ const key = `${id}\n${by.name}`;+ clearTimeout(acting.get(key)?.timer);+ const timer = setTimeout(() => { acting.delete(key); changed(); }, ACTING_MS);+ timer.unref?.();+ acting.set(key, { env: id, by, timer });+ };+ const forgetActing = id => { for (const [key, entry] of acting) if (id === undefined || entry.env === id) { clearTimeout(entry.timer); acting.delete(key); } };+ const actingOn = env => status.get(env.id)?.connected ? [...acting.values()].filter(entry => entry.env === env.id) : [];let closed = false;let maintainerOff = false;let executing = null;@@ -261,7 +275,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loconst summary = () => {const 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 using = lent.filter(env => executing?.env === env.id || actingOn(env).length || (inUse.has(env.id) && linked.has(env.id)));+ const bots = using.flatMap(env => actingOn(env).map(({ by }) => ({ ...by, cloud: env.name })));const problems = lendingProblems(lent);return {lending: lent.map(env => env.id),@@ -271,6 +286,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lowaiting: 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),+ ...(bots.length ? { bots } : {}),paused,...(pauseError ? { pauseError } : {}),terminal: terminalAccount !== null && terminalAccount === signedInAccount(),@@ -470,7 +486,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loconst stop = id => {const live = running.get(id);if (live) { live.abort.abort(); live.cua?.close(); live.mcp?.close(); running.delete(id); }- status.set(id, { connected: false });+ status.set(id, { connected: false }); forgetActing(id);};const run = (env, grant) => {stop(env.id);@@ -541,7 +557,9 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, locontinue;}if (executing) { await call("result", { jobId: job.id, result: sharedComputerError(new Error("This computer is busy with another server")) }); continue; }+ const by = actingBot(job.by);executing = { env: env.id, action: job.operation.action };+ if (by) actedFor(env.id, by);changed();const jobAbort = new AbortController();const jobSignal = AbortSignal.any([signal, jobAbort.signal]);@@ -586,7 +604,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, loif (control) presence.acted(job.operation.tool_name, job.operation.arguments);await renewal?.catch(() => {});await control?.release().catch(() => {});- executing = null; changed();+ executing = null; if (by) actedFor(env.id, by); changed();}activity.record({env, action: job.operation.action, detail: describeSharedOperation(grant, job.operation), ok: result?.isError !== true,@@ -975,6 +993,6 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo}void lendAutomatically();},- close() { closed = true; for (const id of running.keys()) stop(id); syncAsking(); asks.close(); },+ close() { closed = true; forgetActing(); for (const id of running.keys()) stop(id); syncAsking(); asks.close(); },};}diff --git a/electron/lend-automatically.node-test.mjs b/electron/lend-automatically.node-test.mjsindex c2c16788e8..6a8e46290a 100644--- a/electron/lend-automatically.node-test.mjs+++ b/electron/lend-automatically.node-test.mjs@@ -12,7 +12,7 @@ import { setTimeout as delay } from "node:timers/promises";import { ownCloud } from "./cloud-list.mjs";import { automaticGrant, createComputerSharing, lendsAsWanted } from "./computer-sharing.mjs";import { activityPage, createActivityWindow } from "./lending-activity-window.mjs";-import { createLendingIndicator, indicatorText } from "./lending-indicator.mjs";+import { actingBot, createLendingIndicator, indicatorText } from "./lending-indicator.mjs";import { createLendingTarget } from "./lending-target.mjs";import { WORDS } from "./lending-words.mjs";@@ -37,7 +37,7 @@ async function scratch(t) {function cloudHome({ link = true, chrome = true } = {}) {const json = (value, status = 200) => ({ ok: status < 400, status, headers: { get: () => null }, body: (async function* () { yield Buffer.from(JSON.stringify(value)); })() });const state = { environmentId: randomUUID(), sessionId: randomUUID(), connects: [], results: [], queue: [], disconnects: [], calls: 0 };- state.push = operation => state.queue.push({ id: randomUUID(), operation: { computer_id: state.connects.at(-1).id, ...operation } });+ state.push = (operation, by) => state.queue.push({ id: randomUUID(), operation: { computer_id: state.connects.at(-1).id, ...operation }, ...(by ? { by } : {}) });state.fetch = async (url, init) => {state.calls++;const route = new URL(url).pathname;@@ -507,6 +507,58 @@ test("the move's project folders are lent to My Cloud with editing on top; whileawait assert.rejects(mac.sharing.lendProjects([app]), /waits/);});+test("the menu-bar item names the bot acting on this Mac, with its colour, and keeps naming it between its steps", async t => {+ const homes = { [HOME]: cloudHome() };+ const mac = await computer(t, { homes, places: [myCloud] });+ mac.sharing.start();+ await until(() => homes[HOME].connects.length === 1, "My Cloud to be lent this computer");+ homes[HOME].push({ action: "computer_tools" }, { name: " IT Support ", color: "teal", secret: "never kept" });+ await until(() => homes[HOME].results.length === 1, "the bot's action to run");+ assert.deepEqual(mac.summaries.at(-1).bots, [{ name: "IT Support", color: "teal", cloud: "My Cloud" }]);+ assert.deepEqual(mac.summaries.at(-1).using, ["My Cloud"], "the action is over, but the bot is still named until its next step");+ assert.equal(indicatorText(mac.summaries.at(-1), "Mac").title, "IT Support is using this Mac");+ // A step that names no bot (an older Cloud) keeps the name; a second bot is named beside the first.+ homes[HOME].push({ action: "computer_tools" });+ await until(() => homes[HOME].results.length === 2, "the unnamed action to run");+ homes[HOME].push({ action: "computer_tools" }, { name: "Writer", color: "pink" });+ await until(() => homes[HOME].results.length === 3, "the second bot's action to run");+ assert.deepEqual(mac.summaries.at(-1).bots.map(bot => bot.name), ["IT Support", "Writer"]);+ assert.equal(indicatorText(mac.summaries.at(-1), "Mac").title, "IT Support and Writer are using this Mac");+ // Pausing ends it at once.+ mac.sharing.pause();+ await until(() => mac.summaries.at(-1).paused === true, "the pause");+ assert.equal(mac.summaries.at(-1).bots, undefined);+});++test("a bot's name from a Cloud is shown only as short plain text, and its colour only as a colour word", () => {+ assert.deepEqual(actingBot({ name: " Word\n assistant ", color: "purple" }), { name: "Word assistant", color: "purple" });+ assert.deepEqual(actingBot({ name: "Support", color: "#fff; rm" }), { name: "Support", color: null });+ for (const by of [null, {}, { name: "" }, { name: 7 }, { name: "x".repeat(65) }, { name: "Bell\u0007" }, { name: "Support\u202Eevil" }, { name: "Zero\u200Bwidth" }]) assert.equal(actingBot(by), null, JSON.stringify(by));+});++test("the menu names each bot using this Mac with its colour dot; See activity is one click from it", () => {+ const trays = [];+ class Tray { constructor() { trays.push(this); } on() {} setToolTip(value) { this.tip = value; } setTitle(value) { this.title = value; } setContextMenu(menu) { this.menu = menu; } isDestroyed() { return false; } destroy() {} }+ const image = () => { const reps = []; return { reps, addRepresentation: rep => reps.push(rep), isEmpty: () => reps.length === 0 }; };+ const clicked = [];+ const indicator = createLendingIndicator({ Tray, Menu: { buildFromTemplate: items => items }, nativeImage: { createFromPath: () => ({ resize: () => ({}) }), createEmpty: image }, iconPath: "icon.png",+ onPause: () => {}, onResume: () => {}, onActivity: () => clicked.push("activity"), onTerminal: () => {}, device: "Mac" });+ const labels = () => trays[0].menu.map(item => item.type === "separator" ? "-" : item.label);+ indicator.update({ clouds: ["My Cloud", "Client A"], using: ["My Cloud", "Client A"], bots: [{ name: "IT Support", color: "teal", cloud: "My Cloud" }] });+ assert.deepEqual(labels(), ["IT Support on My Cloud is using this Mac", "Client A is using this Mac", "-", "Pause", "Let Clouds run commands on this Mac", "See activity"]);+ const [bot, cloud] = trays[0].menu;+ assert.deepEqual(bot.icon.reps.map(rep => [rep.scaleFactor, rep.dataURL.startsWith("data:image/png;base64,")]), [[1, true], [2, true]]);+ assert.equal(cloud.enabled, false);+ bot.click();+ assert.deepEqual(clicked, ["activity"]);+ assert.equal(trays[0].title, "IT Support and Client A are using this Mac");+ assert.equal(trays[0].tip, "OpenMausBot: IT Support on My Cloud is using this Mac. Client A is using this Mac");+ indicator.update({ clouds: ["My Cloud"], using: ["My Cloud"], bots: [{ name: "Helper", color: null, cloud: "My Cloud" }] });+ assert.deepEqual([labels()[0], trays[0].menu[0].icon], ["Helper on My Cloud is using this Mac", undefined], "no dot for a colour this app doesn't know");+ indicator.update({ clouds: ["My Cloud"], using: ["My Cloud"], bots: [{ name: "Helper", color: "red", cloud: "My Cloud" }], paused: true });+ assert.equal(labels()[0], "Paused: My Cloud can't use this Mac");+});+test("the menu-bar item: which Clouds are using this Mac, Pause or Resume, the terminal switch and See activity", () => {const trays = [];class Tray {diff --git a/electron/lending-indicator.mjs b/electron/lending-indicator.mjsindex 6ce5a575f0..3f8655540f 100644--- a/electron/lending-indicator.mjs+++ b/electron/lending-indicator.mjs@@ -1,5 +1,6 @@import nativeText from "./native-text.cjs";import { screenFixLabel, screenLine } from "./screen-words.mjs";+import { dotIcons } from "./color-dot.mjs";/** The device word the person knows this computer by. */export const deviceWord = (platform = process.platform) => platform === "darwin" ? "Mac" : platform === "win32" ? "PC" : "computer";@@ -7,11 +8,21 @@ export const deviceWord = (platform = process.platform) => platform === "darwin"const listed = (names, t) => names.length < 3 ? names.join(t("native.lendTray.and")) : `${names.slice(0, -1).join(", ")}${t("native.lendTray.and")}${names.at(-1)}`;const short = (names, t) => names.length < 3 ? listed(names, t) : t("native.lendTray.clouds", { count: names.length });+// oxlint-disable-next-line no-control-regex+const NOT_PRINTABLE = /[\x00-\x1f\x7f-\x9f\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/;+/** The bot a Cloud says an action is for: a short plain name and a colour word, or null. Older Clouds send none. */+export function actingBot(by) {+ const name = typeof by?.name === "string" ? by.name.trim().replace(/\s+/g, " ") : "";+ if (!name || [...name].length > 64 || NOT_PRINTABLE.test(name)) return null;+ return { name, color: typeof by.color === "string" && /^[a-z]{1,16}$/.test(by.color) ? by.color : null };+}+/** `screen`: computer control's state; while it isn't ready the line says what the Clouds* 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 = [], problems = [] }, device, t = nativeText.englishText.t) {+/** `bots`: the bots acting here now, each with the Cloud it acts from; the menu names them, each with its colour dot. */+export function indicatorText({ clouds, using, bots = [], 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 };@@ -21,8 +32,11 @@ export function indicatorText({ clouds, using, paused, pauseError, screen = nullconst 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, ...wrong };+ const say = (names, form) => t(names.length > 1 ? "native.lendTray.usingMany" : "native.lendTray.usingOne", { clouds: form(names, t), device: named });+ const acting = bots.filter(bot => using.includes(bot.cloud));+ const rest = using.filter(name => !acting.some(bot => bot.cloud === name));+ const byBot = acting.length ? { acting: acting.map(bot => ({ label: t("native.lendTray.botUsing", { bot: bot.name, cloud: bot.cloud, device: named }), color: bot.color })) } : {};+ return { line: rest.length ? say(rest, listed) : null, title: say([...acting.map(bot => bot.name), ...rest], short), screen: why, ...byBot, ...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, ...wrong };@@ -36,6 +50,7 @@ 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;+ const dot = dotIcons(nativeImage);/** 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 => {@@ -59,13 +74,16 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPa};const draw = view => {if (!tray || tray.isDestroyed()) return;- const { line, title, screen, pending, problems = [] } = indicatorText(view, device, t);+ const { line, title, screen, pending, problems = [], acting = [] } = indicatorText(view, device, t);const fix = screen ? screenFixLabel(view.screen, t) : null;- tray.setToolTip(`OpenMausBot: ${line}${pending ? `. ${pending}` : ""}${screen ? `. ${screen}` : ""}${problems.length ? `. ${problems.join(". ")}` : ""}`);+ const said = [...acting.map(bot => bot.label), ...line ? [line] : []].join(". ");+ tray.setToolTip(`OpenMausBot: ${said}${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 },+ // A bot's line opens the activity, so it shows in full colour rather than greyed out.+ ...acting.map(bot => { const icon = dot(bot.color); return { label: bot.label, ...icon ? { icon } : {}, click: () => onActivity() }; }),+ ...line ? [{ label: line, enabled: false }] : [],...pending ? [{ label: pending, enabled: false }] : [],...problems.map(problem => ({ label: problem, enabled: false })),...screen ? [{ label: screen, enabled: false }] : [],@@ -80,8 +98,8 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPa]));};return {- 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 } : {},+ update({ clouds = [], using = [], bots = [], paused = false, pauseError, terminal = false, terminalSwitch = true, screen = null, waiting = [], problems = [] }) {+ const next = { clouds: [...clouds], using: paused ? [] : [...using], bots: paused ? [] : bots.map(({ name, color, cloud }) => ({ name, color, cloud })), 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;diff --git a/server/index.ts b/server/index.tsindex 688c469b7a..51ff29a63c 100644--- a/server/index.ts+++ b/server/index.ts@@ -13205,7 +13205,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const principal = sharedComputerPrincipal(internalCapability);const why = (CLOUD_TEAM ? managedPolicy.computerRefusal("thisComputer") : null) ?? (CLOUD_HOME && !principal ? cloudLendingRefusalForBot(internalCapability) : null);if (why) return json(res, 403, { error: why });- return json(res, 200, { result: lentScreenResult(parsed.data, await sharedComputers.request(parsed.data, principal, () => botLending() && internalCapabilityIsActive(internalCapability))) });+ return json(res, 200, { result: lentScreenResult(parsed.data, await sharedComputers.request(parsed.data, principal, () => botLending() && internalCapabilityIsActive(internalCapability), store.bot(internalCapability.botId))) });}if (method === "GET" && path === "/api/internal/agents") {const sender = internalSender;diff --git a/server/lent-mcp.ts b/server/lent-mcp.tsindex dc3dfb19af..d5e4e3d0e3 100644--- a/server/lent-mcp.ts+++ b/server/lent-mcp.ts@@ -85,7 +85,7 @@ export function lentDefinition(name: string, server: StoredMcpServer): LentMcpSeconst definitionKey = (definition: LentMcpServer) => createHash("sha256").update(JSON.stringify(definition)).digest("hex");type ElsewhereServer = StoredMcpServer & { runsOn: McpRunsOn };-type Bot = { id: string; mcpServers?: string[]; toolScope?: unknown };+type Bot = { id: string; name?: string; color?: string; mcpServers?: string[]; toolScope?: unknown };/** The saved servers that run on another computer and that this bot's turns use: on, for this bot, in its list and its* tool selection. */@@ -223,7 +223,7 @@ export function createLentMcp(deps: LentMcpDeps) {const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown };if (typeof params.name !== "string" || !params.name) return callError(id, "Name the tool to call.");const args = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments as Record<string, unknown> : {};- const result = await deps.computers.request({ computer_id: state.computerId, action: "mcp_call", server: definition, tool_name: params.name, arguments: args }, principal, active);+ const result = await deps.computers.request({ computer_id: state.computerId, action: "mcp_call", server: definition, tool_name: params.name, arguments: args }, principal, active, bot?.name && bot.color ? { name: bot.name, color: bot.color } : null);return reply(id, result && typeof result === "object" ? result : { content: [] });} catch (error) {return refuse(error instanceof Error ? error.message : `${name} did not answer.`);diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.tsindex 05f6389711..60585e03e7 100644--- a/server/shared-computers.test.ts+++ b/server/shared-computers.test.ts@@ -97,6 +97,22 @@ describe("shared computer authority and lifecycle", () => {await expect(broker.request(operation, alice.person, () => true)).rejects.toThrow(/offline/);broker.close();});+ it("tells the computer which bot an action is for: its name and colour only", async () => {+ const broker = new SharedComputers(() => true);+ const computer = registration({ computer: true }); broker.register(computer, alice, secret);+ const operation = { computer_id: computer.id, action: "computer_tools" as const };+ const bot = { id: "b1", name: "IT Support", color: "teal", soul: "private" };+ const result = broker.request(operation, alice.person, () => true, bot);+ const job = await broker.poll(computer.id, "owner", secret);+ expect(job).toEqual({ id: job!.id, operation, by: { name: "IT Support", color: "teal" } });+ broker.complete(computer.id, "owner", secret, job!.id, { ok: true });+ await expect(result).resolves.toEqual({ ok: true });+ const unnamed = broker.request(operation, alice.person, () => true);+ const plain = await broker.poll(computer.id, "owner", secret);+ expect(plain).toEqual({ id: plain!.id, operation });+ broker.complete(computer.id, "owner", secret, plain!.id, {}); await unnamed;+ broker.close();+ });it("waits for a command as long as the command may run, and a non-command action still 45 seconds", async () => {vi.useFakeTimers();const lent = () => {diff --git a/server/shared-computers.ts b/server/shared-computers.tsindex 6c1fbd8fdd..7b62edbe48 100644--- a/server/shared-computers.ts+++ b/server/shared-computers.ts@@ -68,8 +68,10 @@ export type KnownLentComputer = {id: string; name: string; platform: "darwin" | "win32" | "linux" | null; online: boolean; busy: boolean; lent: boolean;lastSeenAt: number; lastUsedAt: number | null; scopes: { folders: number; terminal: boolean; screen: boolean; internet: boolean; chrome: boolean };};+/** The bot an action is for, so the lent computer's menu can name it with its colour. */+export type ActingBot = { name: string; color: string };type Job = {- id: string; operation: Operation; active: () => boolean; sent: boolean; leased: boolean; resolve: (result: unknown) => void; reject: (error: Error) => void;+ id: string; operation: Operation; by?: ActingBot; active: () => boolean; sent: boolean; leased: boolean; resolve: (result: unknown) => void; reject: (error: Error) => void;timer: NodeJS.Timeout; delivery?: NodeJS.Timeout;};type Computer = { registration: Registration; owner: SharedComputerOwner; secret: string; seen: number; jobs: Map<string, Job>; wake?: () => void; polls: number };@@ -331,7 +333,7 @@ export class SharedComputers {if (entry.polls !== mine || gone?.aborted) return null;for (const job of entry.jobs.values()) {if (!job.active()) { this.finish(entry, job, failure("The requesting turn ended")); continue; }- if (!job.sent) { this.send(entry, job); return { id: job.id, operation: job.operation }; }+ if (!job.sent) { this.send(entry, job); return { id: job.id, operation: job.operation, ...(job.by ? { by: job.by } : {}) }; }}return null;};@@ -382,7 +384,7 @@ export class SharedComputers {this.changed();}/** Another person's computer answers exactly like one that does not exist. */- async request(operation: Operation, principal: string | null, active: () => boolean): Promise<unknown> {+ async request(operation: Operation, principal: string | null, active: () => boolean, by?: ActingBot | null): Promise<unknown> {if (!principal) throw failure("This conversation cannot use a shared computer: only a conversation started by the person who shared it can.", 403);const lent = () => [...this.computers.values()].find(candidate => candidate.registration.id === operation.computer_id && candidate.owner.person === principal);for (const deadline = Date.now() + RECONNECT_WAIT_MS; ;) {@@ -421,7 +423,7 @@ export class SharedComputers {const forDesktop = entry.registration.fileEdits ? timed : withoutEdits;return new Promise((resolve, reject) => {const id = randomUUID();- const job: Job = { id, operation: forDesktop, active, sent: false, leased: false, resolve, reject, timer: setTimeout(() => this.finish(entry, job, failure("Computer action timed out. Its outcome is unknown; inspect before retrying.")), jobDeadlineMs(entry.registration, operation)) };+ const job: Job = { id, operation: forDesktop, ...(by ? { by: { name: by.name, color: by.color } } : {}), active, sent: false, leased: false, resolve, reject, timer: setTimeout(() => this.finish(entry, job, failure("Computer action timed out. Its outcome is unknown; inspect before retrying.")), jobDeadlineMs(entry.registration, operation)) };entry.jobs.set(id, job); entry.wake?.();});}diff --git a/src/lib/mascot.test.ts b/src/lib/mascot.test.tsindex 9f3d0e0f6a..d63099dc35 100644--- a/src/lib/mascot.test.ts+++ b/src/lib/mascot.test.ts@@ -1,3 +1,4 @@+import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";import { t } from "./i18n";@@ -60,3 +61,10 @@ describe("chrome", () => {expect(colorSwatch("blue")).toBe(MAUS_COLORS.blue);});});++describe("the lent computer's menu dots", () => {+ it("use the mascot colours, so a bot's dot there matches its mascot", () => {+ const table = /BOT_COLOR_HEX = Object\.freeze\(\{([^}]+)\}\)/.exec(readFileSync(new URL("../../electron/color-dot.mjs", import.meta.url), "utf8"))?.[1] ?? "";+ expect(Object.fromEntries([...table.matchAll(/(\w+): "(#[0-9A-F]{6})"/gi)].map(([, name, hex]) => [name, hex]))).toEqual(MAUS_COLORS);+ });+});diff --git a/src/locales/en.json b/src/locales/en.jsonindex aefd5b77e7..d0846540e1 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -9653,6 +9653,7 @@"native.lendTray.paused": "Paused","native.lendTray.usingMany": "{clouds} are using this {device}","native.lendTray.usingOne": "{clouds} is using this {device}",+ "native.lendTray.botUsing": "{bot} on {cloud} 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}",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex aba9105544..e6105cf4ab 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -9609,6 +9609,7 @@"native.lendTray.paused": "Pausado","native.lendTray.usingMany": "{clouds} estão usando este {device}","native.lendTray.usingOne": "{clouds} está usando este {device}",+ "native.lendTray.botUsing": "{bot} em {cloud} 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}",