Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Let bots on your own server use this computer: one switch where you add and see the server (#7264)

Milind Soni01892c58960e
diff --git a/apps/docs/content/docs/computers/index.mdx b/apps/docs/content/docs/computers/index.mdx
index ed1774582c..bc631c6853 100644
--- a/apps/docs/content/docs/computers/index.mdx
+++ b/apps/docs/content/docs/computers/index.mdx
@@ -15,6 +15,8 @@ A bot can work without a computer, use the computer running MausBot, or work ins
| Boat cloud computer | Hosted remote desktop | Always-available isolated Linux work |
| Self-hosted VPS | Hardened container over SSH | Using infrastructure you own |
+To let bots on your own server use your Windows PC or Mac, see [Let bots on your own server use this computer](/docs/computers/lend-to-your-server).
+
To use your own Linux server as the desktop, start with [Your own VPS (BYO)](/docs/computers/byo-vps), including the 0.1.151 and 0.1.152 existing-bot selector workaround.
## Auto, local, and cloud selection
diff --git a/apps/docs/content/docs/computers/lend-to-your-server.mdx b/apps/docs/content/docs/computers/lend-to-your-server.mdx
new file mode 100644
index 0000000000..26bd86e40e
--- /dev/null
+++ b/apps/docs/content/docs/computers/lend-to-your-server.mdx
@@ -0,0 +1,76 @@
+---
+title: Let bots on your own server use this computer
+description: Run MausBot on a VPS or home server and let its bots use the apps on your Windows PC or Mac.
+icon: Laptop
+---
+
+When MausBot runs on a server of your own (a Linux VPS, a home server, a Mac mini), its bots have no screen of their own
+there. The MausBot app on your PC or Mac can lend them yours: they then see and use the apps on your screen, while the
+app is open on that computer. It is one switch, and you can turn it off at any time.
+
+## What you need
+
+- A server of your own: one that only you sign in to, as its owner. That is a server started with
+ `npx openmausbot serve` (or the Docker or Podman install) with no members and at most one admin address. A team's
+ server, a server other people sign in to, and a MausBot Cloud are not "your own" for this: a Cloud lends by its own
+ rules, from the MausBot icon's menu.
+- The MausBot desktop app on the computer you want to lend: Windows on an x64 PC, or macOS 13 or later.
+- The app paired with the server as its owner: on the server, run `npx openmausbot pair --label "My PC"` and use the code
+ it prints (a `--phone` code can't lend a computer).
+
+## Turn it on
+
+### Windows
+
+1. Open MausBot on your PC.
+2. Open **Settings → This app → Your computers**, choose **Connect to a server**, and enter the server's address and code.
+3. Before you press Connect, turn on **Let its bots use this computer** in the same form. If the server is your own, it
+ can use this PC as soon as it is paired.
+4. Already connected? The server's row in **Your computers** (and its card on **Settings → Devices**, and the Screen
+ panel when you are on that server) has the switch **Let <server>'s bots use this computer**. One tap turns it on.
+
+Nothing else is needed on Windows. If Windows Security or Smart App Control blocks MausBot's computer-control helper
+(`cua-driver.exe`), the line under the switch says so; restart MausBot after allowing it.
+
+### macOS
+
+The steps are the same as on Windows. The first time, macOS has to allow MausBot to see and control the screen: the line
+under the switch says **One more step: macOS has to allow MausBot to see and control your screen**, with **Open System
+Settings**. Allow MausBot under **Privacy & Security → Accessibility** and **Screen Recording**. The line goes away by
+itself once macOS allows it; restart MausBot if macOS asks you to.
+
+### From the server's own page
+
+When the app shows the server (choose its circle at the window's left edge), the Screen panel has the same switch.
+Because that page comes from the server, turning it on from there asks you once more in a MausBot window of its own
+(**Allow** or **Not now**); turning it off is one tap.
+
+## What a bot can do
+
+Once it is on, every bot on that server can:
+
+- see what is on your screen and use your apps: open apps and web pages, click, type, read windows;
+- run the MCP servers you keep for it on this computer.
+
+Folders and a terminal are not lent unless you choose them: in Advanced mode, **Choose what it can use** next to the
+switch adds folders (read-only unless you allow edits) and the terminal. Only a conversation you started yourself can
+use your computer; one a routine, a webhook or another bot started is told why it can't, and says so.
+
+A bot does not need its **Works on** set to anything for this: it reaches your computer through its shared-computer
+tools, whatever its Works on is. Ask it in plain words: "open Notepad on my PC".
+
+## Turn it off
+
+- Turn the switch off, in any of the places above. It stops at once.
+- Or pause it, with your Clouds, from the MausBot icon's menu (the menu bar on a Mac, the tray on Windows).
+- Closing the app stops it until you open the app again.
+
+Both the app and the server need MausBot 0.1.179 or later for the switch; with an older one on either side, update it.
+
+## Limits
+
+- The app has to be open, and you signed in to your computer. While the screen is locked, the bot is told so and
+ can't use it.
+- Windows on x64 only for now. Windows on Arm and 32-bit Windows have no computer-control helper yet.
+- A bot uses your real screen, with the same control you have. Lend it only to a server you trust, and turn the switch off when you don't need it.
+- To turn lending off for a server entirely, set `features.sharedComputers` to `false` in that server's config.
diff --git a/apps/docs/content/docs/computers/local-computer.mdx b/apps/docs/content/docs/computers/local-computer.mdx
index c2ceb0ac1e..627248151b 100644
--- a/apps/docs/content/docs/computers/local-computer.mdx
+++ b/apps/docs/content/docs/computers/local-computer.mdx
@@ -10,6 +10,16 @@ Local control is off by default. The Electron main process owns the bundled CUA
The packaged app can request Accessibility and Screen Recording permission. After granting either permission, restart the control session when prompted so macOS applies the new grant.
+## Windows
+
+The Windows app (x64) ships its own computer-control helper, `cua-driver.exe` with `cua-driver-background.exe`. There is no
+permission to grant: once a bot is set to **This computer**, it can use the apps on your screen. If Windows Security or
+Smart App Control blocks the helper, the Screen panel says so; allow it and restart MausBot. Windows on Arm is not
+supported yet.
+
+To let bots on a server of your own (a VPS) use this PC instead, see
+[Let bots on your own server use this computer](/docs/computers/lend-to-your-server).
+
## Ubuntu
Ubuntu 24.04 GNOME host control is temporarily disabled while the real-seat input-safety blocker in issue #345 is resolved. Packaged builds retain the pinned runtime for reproducible review, but MausBot does not start it and clears legacy opt-ins. Chat, screen preview, Cloud, and Local VM remain available. Do not start the bundled driver manually as a workaround.
diff --git a/apps/docs/content/docs/computers/meta.json b/apps/docs/content/docs/computers/meta.json
index ca4a3e060c..ba2b18f142 100644
--- a/apps/docs/content/docs/computers/meta.json
+++ b/apps/docs/content/docs/computers/meta.json
@@ -1,5 +1,12 @@
{
"title": "Computers",
"icon": "Monitor",
- "pages": ["index", "local-computer", "local-vm", "cloud-and-vps", "byo-vps"]
+ "pages": [
+ "index",
+ "local-computer",
+ "lend-to-your-server",
+ "local-vm",
+ "cloud-and-vps",
+ "byo-vps"
+ ]
}
diff --git a/docs/byo-vps.md b/docs/byo-vps.md
index d122e0e101..ac579d4f7b 100644
--- a/docs/byo-vps.md
+++ b/docs/byo-vps.md
@@ -70,8 +70,9 @@ The live desktop's tunnel is the exception: it opens its own connection (`Contro
closing it never takes down a connection that docker commands share.
For long data-directory paths, the app keeps its control socket in a private, user-owned directory
under `/tmp` to stay within OpenSSH's socket-path limit; the config stays in the app data directory.
-Windows OpenSSH does not support connection sharing, so that platform keeps its normal SSH setup.
-The block below is still the recommended shape, and it is what your own `ssh` uses outside the app:
+On macOS and Linux, the block below is the recommended shape, and it is what your own `ssh` uses outside the app.
+On a Windows server, leave out the three `Control…` lines: Windows OpenSSH does not support connection sharing, so the
+app never adds them there, and `ssh` on Windows can fail when your alias sets them.
```
Host my-vps
@@ -86,8 +87,9 @@ Host my-vps
ConnectTimeout 10
```
-- `ControlMaster`/`ControlPath`/`ControlPersist` — every bot action is a docker-over-SSH exec; multiplexing turns
- per-command connects into milliseconds over one persistent connection. The live-desktop tunnel does not share it.
+- `ControlMaster`/`ControlPath`/`ControlPersist` (macOS and Linux only) — every bot action is a docker-over-SSH exec;
+ multiplexing turns per-command connects into milliseconds over one persistent connection. The live-desktop tunnel
+ does not share it.
- `ServerAliveInterval`/`ServerAliveCountMax`/`ConnectTimeout` — a dropped VPS must fail fast (under a
minute, and ten seconds to connect), not hang a turn waiting on a dead TCP session.
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 0ac9be2bd1..3b5bd43291 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -924,18 +924,23 @@ chats. A link copied elsewhere also works from the **Server** menu's **Add
Server from Copied Pairing Link…** (on Windows and Linux, press Alt to show
the menu bar).
-**Let your server use this computer.** When the desktop pairs with a code for
-everything (the server's owner), it asks once: **Let <server> use this
-computer?** with **Allow** or **Not now**. Allow lets the server's bots see and
-use the apps on this computer's screen, and run the MCP servers you keep for
-it, while the app is open. Folders and the terminal are added in **Settings →
-Servers**, where each server of yours has a **Share this computer** switch and
+**Let your server use this computer** (Windows x64, macOS 13 or later, Linux).
+When the desktop is paired with a code for everything (the server's owner), one
+switch, **Let <server>'s bots use this computer**, lets the server's bots see
+and use the apps on this computer's screen, and run the MCP servers you keep
+for it, while the app is open. It is in the add form (**Connect to a server**),
+on the server's row in **Settings → This app → Your computers**, on its card in
+**Settings → Devices**, and in the Screen panel on the server's own page (which
+asks once more in a native window, since that page comes from the server). On
+a Mac, macOS asks for Accessibility and Screen Recording the first time; on
+Windows there is nothing more. Folders and the terminal are added with
**Choose what it can use**; the switch turns it off at once, and the menu bar's
-OpenMausBot item pauses it with your Clouds. The server needs nothing turned on:
+or tray's MausBot item pauses it with your Clouds. See
+`apps/docs/content/docs/computers/lend-to-your-server.mdx`. The server needs nothing turned on:
it takes a computer from its owner's pairings only, and a phone code or another
person's pairing is never asked. Set `features.sharedComputers` to `false` in the
server's config to turn this off, or to `true` to let every paired session lend
-its computer. Nothing is shared without that Allow, unless you make the server
+its computer. Nothing is shared until you turn that switch on, unless you make the server
your bots' home (below). In **Settings → Servers → Computer
access**, choose read-only folders and optionally allow edits. Unrestricted
terminal and screen/app control are separate opt-ins, confirmed in a native
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mts
index 4d0d70cd3d..f426b5f0e0 100644
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@ -160,6 +160,8 @@ export function createComputerSharing(options: {
revoke(env: Workspace): SharingState;
/** `env` is a server of the person's own, checked now: its identity, else null. */
ownServer(env: Workspace): Promise<Identity | null>;
+ /** Why `env` is not a server of the person's own, or null when it is. */
+ ownRefusal(env: Workspace): Promise<"team" | "cloud" | "not-owner" | "shared" | "old" | "unreachable" | null>;
/** A server of the person's own whose pairing here was never asked about: its identity, for the popup; null once asked;
* false when it is not a server of the person's own. */
ownOffer(env: Workspace): Promise<Identity | null | false>;
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index c6b64ce028..aab379a932 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -4,7 +4,7 @@ import path from "node:path";
import os from "node:os";
import { randomBytes, randomUUID } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
-import { allowedServerOrigin } from "./server-address.mjs";
+import { allowedServerOrigin } from "./server-address.mjs"; import { ownServerRefusal } from "./own-server-refusal.mjs";
import { createSharedCua, executeSharedOperation, personalSecretPaths, sharedComputerError, validCommandSeconds } from "./shared-computer-access.mjs";
import { createLentMcp, LENT_MCP_ACTIONS, ownPorts, validLentMcpJob } from "./lent-mcp.mjs";
import { sharedCuaConnection } from "./shared-cua-connection.mjs";
@@ -446,8 +446,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
/** This desktop's sign-in on a server of the person's own, checked now (ownServerSession). */
const ownIdentity = async env => {
const described = await describe(env, false);
- if (!ownServerSession(described.auth)) throw Object.assign(new Error(t("native.lend.notOwnServer")), { problem: "not-own" });
- if (!described.supported) throw new Error(UPDATE_SERVER);
+ if (!ownServerSession(described.auth)) throw Object.assign(new Error(t("native.lend.notOwnServer")), { problem: "not-own", why: ownServerRefusal(described.auth) ?? "not-owner" });
+ if (!described.supported) throw Object.assign(new Error(UPDATE_SERVER), { why: "old" });
takes(env, { ...described, link: false, chrome: false });
return described.info;
};
@@ -865,7 +865,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
},
/** Whether `env` is a server of the person's own, checked now: its identity, or null (not paired as its admin, a team
* or Cloud, too old to take a lent computer, or not answering). */
- ownServer: env => ownIdentity(env).catch(() => null),
+ ownServer: env => ownIdentity(env).catch(() => null), /** Why `env` is not a server of the person's own: ownServerRefusal's word, "old", or "unreachable". */ ownRefusal: env => ownIdentity(env).then(() => null, error => error?.why ?? "unreachable"),
/** A server of the person's own whose pairing here was never asked about: its identity, for the popup; null once the
* person answered for this pairing (a grant they allowed carries over to a new pairing of that same server); false
* when it is not a server of their own. */
diff --git a/electron/lend-own-server.node-test.mjs b/electron/lend-own-server.node-test.mjs
index afb80a237b..66d1c40226 100644
--- a/electron/lend-own-server.node-test.mjs
+++ b/electron/lend-own-server.node-test.mjs
@@ -12,6 +12,9 @@ import { setTimeout as delay } from "node:timers/promises";
import { createComputerSharing, ownServerSession } from "./computer-sharing.mjs";
import { createLendingIndicator } from "./lending-indicator.mjs";
import { installServerLending } from "./server-lending.mjs";
+import { ownServerRefusal } from "./own-server-refusal.mjs";
+import { cloudPageSenderAllowed } from "./cloud-home.mjs";
+import { screenStatus } from "./screen-status.mjs";
const GARAGE = "http://192.168.1.20:8799";
const garage = { id: "garage", name: "Garage", origin: GARAGE, kind: "remote" };
@@ -75,6 +78,24 @@ test("only this desktop's admin pairing on a server that is no Cloud, team or ho
assert.equal(ownServerSession({ ...owner, cloudHome: true }), false, "a Cloud is lent by its own rules");
assert.equal(ownServerSession({ ...owner, hosted: true }), false);
assert.equal(ownServerSession({ ...owner, kind: "loopback" }), false);
+ // Why not, in one word the app turns into one line.
+ assert.equal(ownServerRefusal(owner), null);
+ assert.equal(ownServerRefusal({ ...owner, own: undefined }), "shared");
+ assert.equal(ownServerRefusal({ ...owner, scopes: ["client"] }), "not-owner");
+ assert.equal(ownServerRefusal({ ...owner, team: { id: "t", role: "admin" } }), "team");
+ assert.equal(ownServerRefusal({ ...owner, cloudHome: true }), "cloud");
+ assert.equal(ownServerRefusal(undefined), "not-owner");
+});
+
+test("ownRefusal asks the server itself: its own when it is, why not when it isn't", async t => {
+ const mine = await desktop(t, selfHosted());
+ assert.equal(await mine.sharing.ownRefusal(garage), null);
+ const shared = await desktop(t, selfHosted({ own: false }));
+ assert.equal(await shared.sharing.ownRefusal(garage), "shared");
+ const narrow = await desktop(t, selfHosted({ scopes: ["client"] }));
+ assert.equal(await narrow.sharing.ownRefusal(garage), "not-owner");
+ const team = await desktop(t, selfHosted({ extra: { team: { id: "t", role: "admin" } } }));
+ assert.equal(await team.sharing.ownRefusal(garage), "team");
});
test("once the person allows it, a server of their own gets the apps on the screen and its MCP servers, with the maintainer flag off; no folder or terminal unless chosen", async t => {
@@ -206,7 +227,7 @@ test("the menu-bar item keeps its Clouds' terminal switch only while a Cloud is
});
/** main's channels and popup, with this desktop's lending and native dialogs stood in for. */
-function mainLending({ response = 1, own = true, flag = false, offer } = {}) {
+function mainLending({ response = 1, own = true, flag = false, offer, refusal = "shared", screen = async () => ({ ready: true, lent: true, reason: null, fix: null }), now = () => 1_000 } = {}) {
const handlers = new Map(), calls = { lent: [], declined: [], saved: [], revoked: [], boxes: [] };
const win = { isDestroyed: () => false, webContents: { getURL: () => `${GARAGE}/` } };
const info = { sessionId: randomUUID(), environmentId: randomUUID() };
@@ -214,6 +235,7 @@ function mainLending({ response = 1, own = true, flag = false, offer } = {}) {
const controller = {
state: id => records[id] ?? { enabled: false, folders: [], terminal: false, computer: false },
ownServer: async () => (own ? info : null),
+ ownRefusal: async () => (own ? null : refusal),
ownOffer: async () => (offer !== undefined ? offer : own ? info : false),
lendOwn: async (env, grant) => { calls.lent.push([env.id, grant]); records[env.id] = { enabled: true, own: true, ...grant }; return records[env.id]; },
declineOwn: (env, seen) => { calls.declined.push([env.id, seen]); },
@@ -224,26 +246,55 @@ function mainLending({ response = 1, own = true, flag = false, offer } = {}) {
const lending = installServerLending({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (_channel, handler) => handler, sharing: () => controller,
dialogs: { chooseFolder: async () => null, confirmServerAccess: async () => true }, validate: async folders => folders ?? [], dialog, window: () => win,
saved: id => { if (id !== garage.id) throw new Error("unknown"); return garage; }, candidate: env => !env.cloud && !env.team && !env.home, flag: async () => flag,
- environments: () => [garage, { id: "acme", name: "Acme", origin: "https://omb-t-acme.fly.dev", team: { id: "t" } }], active: () => garage });
+ environments: () => [garage, { id: "acme", name: "Acme", origin: "https://omb-t-acme.fly.dev", team: { id: "t" } }], active: () => garage,
+ // This app's own page sends an empty event here; the server's own page sends { page: env }.
+ local: event => !event?.page && !event?.other, page: event => event?.page ?? null, screen, allowScreen: async () => { calls.allowScreen = (calls.allowScreen ?? 0) + 1; }, now });
return { handlers, calls, lending, win, info };
}
-test("right after pairing a server of the person's own, one popup in main's own dialog: Allow lends the apps on the screen, Not now nothing", async () => {
- const allowed = mainLending({ response: 0 });
- await allowed.lending.offer(allowed.win);
- assert.equal(allowed.calls.boxes.length, 1);
- assert.deepEqual(allowed.calls.boxes[0], { type: "question", message: "Let Garage use this computer?", detail: allowed.calls.boxes[0].detail, buttons: ["Allow", "Not now"], defaultId: 1, cancelId: 1 });
- assert.match(allowed.calls.boxes[0].detail, /apps on your screen.*folders you choose and run commands in a terminal/s);
- assert.deepEqual(allowed.calls.lent, [["garage", { folders: [], terminal: false, computer: true }]]);
+test("after pairing a server of the person's own, no popup: the add form's switch, when on, lends the apps on the screen", async () => {
+ const quiet = mainLending({ response: 0 });
+ await quiet.lending.offer(quiet.win);
+ assert.deepEqual(quiet.calls.boxes, [], "the question lives in the add form and on the server's row, never in a popup");
+ assert.deepEqual(quiet.calls.lent, []);
+
+ const wished = mainLending({ response: 1 });
+ assert.equal(await wished.handlers.get("lend:wish")({}, "192.168.1.20:8799", true), true);
+ await wished.lending.offer(wished.win);
+ assert.deepEqual(wished.calls.boxes, [], "the switch was the person's answer");
+ assert.deepEqual(wished.calls.lent, [["garage", { folders: [], terminal: false, computer: true }]]);
+ await wished.lending.offer(wished.win);
+ assert.equal(wished.calls.lent.length, 1, "a wish is used once");
+
+ const unwished = mainLending();
+ await unwished.handlers.get("lend:wish")({}, "http://192.168.1.20:8799", true);
+ await unwished.handlers.get("lend:wish")({}, "http://192.168.1.20:8799", false);
+ await unwished.lending.offer(unwished.win);
+ assert.deepEqual(unwished.calls.lent, [], "the switch turned off again");
- const notNow = mainLending({ response: 1 });
- await notNow.lending.offer(notNow.win);
- assert.deepEqual(notNow.calls.lent, []);
- assert.deepEqual(notNow.calls.declined, [["garage", notNow.info]]);
+ let clock = 1_000;
+ const stale = mainLending({ now: () => clock });
+ await stale.handlers.get("lend:wish")({}, "192.168.1.20", true);
+ clock += 11 * 60_000;
+ await stale.lending.offer(stale.win);
+ assert.deepEqual(stale.calls.lent, [], "an old wish lends nothing");
+
+ const typed = mainLending();
+ await typed.handlers.get("lend:wish")({}, "192.168.1.20", true);
+ await typed.handlers.get("lend:wish")({}, "192.168.1.2", true);
+ await typed.lending.offer(typed.win);
+ assert.deepEqual(typed.calls.lent, [], "only the address as last typed is wished for");
+
+ const elsewhere = mainLending();
+ await elsewhere.handlers.get("lend:wish")({}, "other.example", true);
+ await elsewhere.lending.offer(elsewhere.win);
+ assert.deepEqual(elsewhere.calls.lent, [], "a wish is for the server it was typed for");
+ await assert.rejects(elsewhere.handlers.get("lend:wish")({ page: garage }, "192.168.1.20", true), /main desktop window/, "a server's page can't wish itself lent");
const answered = mainLending({ response: 0, offer: null });
+ await answered.handlers.get("lend:wish")({}, "192.168.1.20", true);
await answered.lending.offer(answered.win);
- assert.deepEqual(answered.calls.boxes, [], "a pairing already answered is never asked again");
+ assert.deepEqual(answered.calls.lent, [], "a pairing already answered keeps its answer");
const notOwn = mainLending({ response: 0, own: false });
await notOwn.lending.offer(notOwn.win);
@@ -276,3 +327,90 @@ test("Settings: each server of the person's own has the switch, which asks the s
await other.handlers.get("sharing:revoke")({}, "garage");
assert.deepEqual(other.calls.revoked, ["garage"], "stopping never needs a flag");
});
+
+test("the switch: one tap on this app's own page lends and stops at once; a server's own page gets main's popup first", async () => {
+ const here = mainLending({ response: 1 });
+ assert.deepEqual(await here.handlers.get("lend:state")({}, "garage"), { name: "Garage", lendable: true, on: false, connected: false, paused: false });
+ const on = await here.handlers.get("lend:set")({}, "garage", true);
+ assert.equal(on.on, true);
+ assert.deepEqual(here.calls.boxes, [], "no popup from this app's own page");
+ assert.deepEqual(here.calls.lent, [["garage", { folders: [], terminal: false, computer: true }]]);
+ assert.equal((await here.handlers.get("lend:set")({}, "garage", false)).on, false);
+ assert.deepEqual(here.calls.revoked, ["garage"]);
+
+ // The server's own page (its Screen panel): about that server only, whatever id it sends.
+ const page = mainLending({ response: 1 });
+ assert.equal((await page.handlers.get("lend:set")({ page: garage }, "acme", true)).on, false, "Not now lends nothing");
+ assert.equal(page.calls.boxes[0].message, "Let Garage use this computer?");
+ assert.equal(page.calls.boxes[0].defaultId, 1);
+ const allowed = mainLending({ response: 0 });
+ assert.equal((await allowed.handlers.get("lend:set")({ page: garage }, null, true)).on, true);
+ assert.equal((await allowed.handlers.get("lend:set")({ page: garage }, null, false)).on, false, "stopping is one tap");
+ assert.equal(allowed.calls.boxes.length, 1);
+ const stranger = mainLending();
+ await assert.rejects(stranger.handlers.get("lend:state")({ page: null, other: true }, "garage"), /main desktop window/);
+
+ // Who may lend is unchanged: a server that isn't their own is never lent, from anywhere.
+ const notOwn = mainLending({ own: false });
+ await assert.rejects(notOwn.handlers.get("lend:set")({}, "garage", true), /Only your own server/);
+ assert.deepEqual(notOwn.calls.lent, []);
+});
+
+test("a server that can't be lent to says why in one word; a Cloud or team never asks the server", async () => {
+ for (const refusal of ["shared", "not-owner", "old", "team", "cloud", "unreachable"]) {
+ const { handlers } = mainLending({ own: false, refusal });
+ assert.deepEqual(await handlers.get("lend:state")({}, "garage"), { name: "Garage", lendable: false, why: refusal });
+ }
+ const flagged = mainLending({ own: false, flag: true });
+ assert.deepEqual(await flagged.handlers.get("lend:state")({}, "garage"), { name: "Garage", lendable: false, why: "settings" });
+ const team = { id: "acme", name: "Acme", origin: "https://omb-t-acme.fly.dev", team: { id: "t" } };
+ assert.deepEqual(await mainLending().handlers.get("lend:state")({ page: team }), { name: "Acme", lendable: false, why: "team" });
+ const cloud = { id: "home", name: "My Cloud", origin: "https://omb-h.fly.dev", home: true };
+ assert.deepEqual(await mainLending().handlers.get("lend:state")({ page: cloud }), { name: "My Cloud", lendable: false, why: "cloud" });
+ // A Cloud's or a team's page changes nothing: no stop written on its grant, no system prompt for the screen.
+ for (const page of [team, cloud]) {
+ const quiet = mainLending({ response: 0 });
+ await quiet.handlers.get("lend:set")({ page }, null, false);
+ await assert.rejects(quiet.handlers.get("lend:set")({ page }, null, true), /Only your own server/);
+ await quiet.handlers.get("lend:allow-screen")({ page }, null);
+ assert.deepEqual(quiet.calls.revoked, []);
+ assert.deepEqual(quiet.calls.lent, []);
+ assert.equal(quiet.calls.allowScreen, undefined);
+ assert.deepEqual(quiet.calls.boxes, []);
+ }
+ const off = mainLending();
+ await off.handlers.get("lend:allow-screen")({}, "garage");
+ assert.equal(off.calls.allowScreen, undefined, "nothing is asked of the system while the switch is off");
+});
+
+test("on, its apps and screen as the system allows them: macOS asks for its two permissions, Windows needs nothing more", async () => {
+ // The same computer control state, as screen-status.mjs reads it on each system.
+ const missing = { status: "unavailable", reason: "Accessibility and Screen Recording required" };
+ const mac = mainLending({ screen: async () => screenStatus({ platform: "darwin", connection: missing }) });
+ await mac.handlers.get("lend:set")({}, "garage", true);
+ assert.deepEqual(await mac.handlers.get("lend:state")({}, "garage"), { name: "Garage", lendable: true, on: true, connected: false, paused: false, screen: "permissions" });
+ await mac.handlers.get("lend:allow-screen")({}, "garage");
+ assert.equal(mac.calls.allowScreen, 1);
+ const ready = { status: "ready", path: "/x", socket: "/tmp/cua.sock", version: "0.45.4" };
+ const windows = mainLending({ screen: async () => screenStatus({ platform: "win32", connection: { ...ready, socket: "\\\\.\\pipe\\cua-omb-1" } }) });
+ await windows.handlers.get("lend:set")({}, "garage", true);
+ const view = await windows.handlers.get("lend:state")({}, "garage");
+ assert.equal(view.on, true);
+ assert.equal(view.screen === undefined || view.screen !== "permissions", true, "Windows never asks for macOS's permissions");
+ const blocked = mainLending({ screen: async () => screenStatus({ platform: "win32", connection: { status: "unavailable", reason: "spawn cua-driver.exe EACCES" } }) });
+ await blocked.handlers.get("lend:set")({}, "garage", true);
+ assert.notEqual((await blocked.handlers.get("lend:state")({}, "garage")).screen, "permissions");
+});
+
+test("main wires the switch's senders as tested here: this app's own page, or the main frame of the active server's page", async () => {
+ const main = await readFile(new URL("./main.mjs", import.meta.url), "utf8");
+ assert.match(main, /installServerLending\(\{[\s\S]{0,1500}?local: event => cloudPageAsking\(event\) === "local"/);
+ assert.match(main, /page: event => \{ const env = activeEnvironment\(environmentsState\); return env\?\.origin && env\.kind !== "local" && activePageOrigin\(event\) === env\.origin \? env : null; \}/);
+ // activePageOrigin is cloudPageSenderAllowed for the active origin: only the window's main frame, on that origin.
+ const mainFrame = { url: `${GARAGE}/chat` }, contents = { mainFrame };
+ const page = event => (cloudPageSenderAllowed(event, { contents, homeOrigin: GARAGE, activeOrigin: GARAGE }) ? garage : null);
+ assert.equal(page({ sender: contents, senderFrame: mainFrame }), garage);
+ assert.equal(page({ sender: contents, senderFrame: { url: `${GARAGE}/frame` } }), null, "a frame inside the page");
+ assert.equal(page({ sender: contents, senderFrame: Object.assign(mainFrame, { url: "https://evil.example/" }) }), null, "another origin");
+ assert.equal(page({ sender: {}, senderFrame: mainFrame }), null, "another window");
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 20a37a6191..0bb7eec038 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -2623,7 +2623,7 @@ installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => savedPlace(enviro
const lendingDialogs = createLendingDialogs({ dialog, window: () => mainWindow, validate: validateSharedFolders, isHome: isHomeFolder, t: nativeT });
// Settings → Servers' computer access, and the popup after pairing a server of the person's own (server-lending.mjs).
const serverLending = installServerLending({ ipcMain, guard: localWorkspaceOnly, sharing: sharingController, dialogs: lendingDialogs, validate: validateSharedFolders, dialog, window: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null),
- saved: savedWorkspace, candidate: lendableServer, flag: refreshSharedComputersAllowed, environments: () => environmentsState.environments, active: () => activeEnvironment(environmentsState), openSettings: openWorkspaceSettings, t: nativeT, log: slog });
+ saved: savedWorkspace, candidate: lendableServer, flag: refreshSharedComputersAllowed, environments: () => environmentsState.environments, active: () => activeEnvironment(environmentsState), openSettings: openWorkspaceSettings, t: nativeT, log: slog, screen: screenControl.now, allowScreen: screenControl.start, local: event => cloudPageAsking(event) === "local", page: event => { const env = activeEnvironment(environmentsState); return env?.origin && env.kind !== "local" && activePageOrigin(event) === env.origin ? env : null; } });
const cloudSync = installCloudFiles({ t: nativeT,
app, ipcMain, dialog, shell, powerMonitor, localWorkspaceOnly, localDataDir: desktopDataDir(),
diff --git a/electron/own-server-refusal.mjs b/electron/own-server-refusal.mjs
new file mode 100644
index 0000000000..1105e6207e
--- /dev/null
+++ b/electron/own-server-refusal.mjs
@@ -0,0 +1,12 @@
+// Why a server this desktop is signed in to is not one of the person's own (computer-sharing.mjs ownServerSession), so
+// lending this computer to it is not offered: one word, which the app turns into one line for the person.
+
+/** "team": a team's server; "cloud": a Cloud or hosted workspace, lent by its own rules; "not-owner": this app is not
+ * signed in there as its owner (admin); "shared": other people sign in there too. Null when it is their own. */
+export function ownServerRefusal(auth) {
+ if (auth?.team) return "team";
+ if (auth?.cloudHome === true || auth?.hosted === true) return "cloud";
+ if (auth?.kind !== "session" || !Array.isArray(auth.scopes) || !auth.scopes.includes("admin")) return "not-owner";
+ if (auth.own !== true) return "shared";
+ return null;
+}
diff --git a/electron/preload.cjs b/electron/preload.cjs
index d078c66ba4..746e1fa067 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -90,7 +90,7 @@ function railKeepsItsSize() {
if (typeof window !== "undefined") {
for (const type of ["resize", "DOMContentLoaded"]) window.addEventListener(type, () => { leaveRailRoom(); railKeepsItsSize(); });
}
-const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "placesTogether", "accountSheet", "desktopNotices", "desktopNotifications", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame", "softwareRendering", "appUpdate"]);
+const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "placesTogether", "accountSheet", "desktopNotices", "desktopNotifications", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame", "softwareRendering", "appUpdate", "lendComputer"]);
/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */
const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];
function updaterOffered() {
@@ -728,6 +728,16 @@ const bridge = {
pause: () => ipcRenderer.invoke("sharing:pause"),
resume: () => ipcRenderer.invoke("sharing:resume"),
},
+ // The one switch for lending this computer to a server of the person's own (server-lending.mjs). On a server's own page
+ // it is about that server only (main ignores the id), and a change needs the person's own click.
+ lendComputer: {
+ state: id => ipcRenderer.invoke("lend:state", isLocalPage ? id : null),
+ set: (id, on) => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("lend:set", isLocalPage ? id : null, on === true) : Promise.reject(new Error("Use the switch to change this.")),
+ allowScreen: id => isLocalPage || navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("lend:allow-screen", isLocalPage ? id : null) : Promise.reject(new Error("Use the button to allow this.")),
+ wish: isLocalPage ? (address, on) => ipcRenderer.invoke("lend:wish", String(address ?? ""), on === true) : undefined,
+ },
confirm: message => ipcRenderer.invoke("dialog:confirm", message),
/** The window onto My Cloud once it is the person's home: this computer's screen while My Cloud can't be opened, and
* on My Cloud's own page a new session when its own has ended. */
diff --git a/electron/server-lending.mjs b/electron/server-lending.mjs
index fcbc7d2b74..26d9170474 100644
--- a/electron/server-lending.mjs
+++ b/electron/server-lending.mjs
@@ -1,8 +1,8 @@
// Lending this computer to a server connected by hand (Settings → Servers). A server of the person's own (this desktop
-// is its admin: computer-sharing.mjs ownServerSession) gets it once the person allows it, in one popup right after
-// pairing (once for a pairing made before this) or from Settings' switch, with no maintainer flag; any other server only
-// while that flag is on, as before. Security: every grant is confirmed in main's own dialog, which no page can draw or
-// answer, and each one defaults to Not now; stopping never needs a flag.
+// is its admin: computer-sharing.mjs ownServerSession) gets it with one switch, with no maintainer flag: in the add form,
+// on its row in Settings, on its card in Devices and in its Screen panel. Any other server only while that flag is on, as
+// before. Security: only this app's own page turns it on with no question; a server's own page (its Screen panel) gets
+// main's own popup first, which no page can draw or answer and which defaults to Not now. Stopping is one tap anywhere.
import nativeText from "./native-text.cjs";
const OWN_CHECK_MS = 30_000;
@@ -12,10 +12,14 @@ const OWN_CHECK_MS = 30_000;
* validateSharedFolders. `saved(id)`: the saved server, or throws. `candidate(env)`: a server saved by hand that no Cloud
* rule lends (not My Cloud, another Cloud of the person's own, a team's Cloud or the server their bots moved to).
* `flag()`: the maintainer flag, read now. `environments()`: the saved places. `active()`: the place on screen.
- * `openSettings(id)`: Settings → Servers with that server's computer access open.
+ * `openSettings(id)`: Settings → Servers with that server's computer access open. `local(event)`: the sender is this app's
+ * own page in the main window. `page(event)`: the saved server whose page sent it, when that page is the main window's
+ * active server (never an id the page names). `screen()`: computer control's state (screen-status.mjs). `allowScreen()`:
+ * asks the system for what computer control lacks (macOS's Accessibility and Screen Recording).
*/
export function installServerLending({ ipcMain, guard, sharing, dialogs, validate, dialog, window, saved, candidate, flag, environments, active = () => null,
- openSettings = () => {}, now = Date.now, t = nativeText.englishText.t, log = () => {} }) {
+ openSettings = () => {}, now = Date.now, t = nativeText.englishText.t, log = () => {}, local = () => false, page = () => null, screen = async () => null,
+ allowScreen = async () => {} }) {
const checked = new Map();
/** A server of the person's own: one lent to before as theirs, else asked of the server, at most every 30 s. */
const own = async env => {
@@ -83,6 +87,68 @@ export function installServerLending({ ipcMain, guard, sharing, dialogs, validat
ipcMain.handle("sharing:pause", guard("sharing:pause", () => { sharing().pause(); }));
ipcMain.handle("sharing:resume", guard("sharing:resume", async () => { await sharing().resume(); }));
+ /** What lending this computer to `env` is, for the switch on its row, its card, the add form and its Screen panel: one
+ * shape everywhere (src/lib/use-lend-computer.ts). Never a folder or anything else this computer lends. */
+ const refusals = new Map();
+ const view = async env => {
+ if (!candidate(env)) return { name: env.name, lendable: false, why: env.team ? "team" : "cloud" };
+ if (!(await own(env))) {
+ // Asked of the server at most every 30 s, as `own` is: each open switch reads this every few seconds.
+ const kept = refusals.get(env.id);
+ const why = kept && kept.origin === env.origin && now() - kept.at < OWN_CHECK_MS ? kept.why
+ : await flag() ? "settings" : await sharing().ownRefusal(env).catch(() => "unreachable") ?? "unreachable";
+ if (!kept || kept.why !== why || now() - kept.at >= OWN_CHECK_MS) refusals.set(env.id, { at: now(), origin: env.origin, why });
+ return { name: env.name, lendable: false, why };
+ }
+ const { enabled, connected, paused, problem } = sharing().state(env.id);
+ const status = enabled === true ? await Promise.resolve().then(screen).catch(() => null) : null;
+ return { name: env.name, lendable: true, on: enabled === true, connected: connected === true, paused: paused === true || problem === "paused",
+ ...(status && !status.ready && status.reason ? { screen: status.reason } : {}) };
+ };
+ /** The server a lend:* call is about: the one named on this app's own page, or the server whose page asks (`fromPage`). */
+ const target = (event, id) => {
+ if (local(event)) return { env: saved(id), fromPage: false };
+ const env = page(event);
+ if (!env) throw new Error("These controls are only available in the main desktop window");
+ return { env, fromPage: true };
+ };
+ // The switch: on lends the apps on the screen at once from this app's own page; a server's own page could press it
+ // itself, so from there main's own popup (which no page can draw or answer) asks first. Off is one tap anywhere.
+ ipcMain.handle("lend:state", async (event, id) => view(target(event, id).env));
+ // Only a server of the person's own is ever changed here: a Cloud's or a team's page (or any other) changes nothing.
+ ipcMain.handle("lend:set", async (event, id, on) => {
+ const { env, fromPage } = target(event, id);
+ if (!(await own(env))) { if (on === true) throw new Error(t("native.lend.notOwnServer")); return view(env); }
+ if (on !== true) { sharing().revoke(env); return view(env); }
+ if (fromPage && !(await allows(env))) return view(env);
+ await sharing().lendOwn(env, firstGrant);
+ return view(env);
+ });
+ /** macOS's Accessibility and Screen Recording, the one step the system itself asks for. */
+ ipcMain.handle("lend:allow-screen", async (event, id) => {
+ const { env } = target(event, id);
+ if (await own(env) && sharing().state(env.id).enabled === true) await allowScreen();
+ return view(env);
+ });
+ /** The add form's switch: lend to the server about to be paired at `host`, if it turns out to be the person's own. Only
+ * from this app's own page; used once, by the next pairing of that host within ten minutes. */
+ const wishes = new Map();
+ const hostOf = origin => { try { return new URL(origin).hostname.toLowerCase(); } catch { return ""; } };
+ ipcMain.handle("lend:wish", async (event, address, on) => {
+ if (!local(event)) throw new Error("These controls are only available in the main desktop window");
+ const host = hostOf(/^[a-z][a-z0-9+.-]*:\/\//i.test(String(address ?? "")) ? String(address) : `https://${address ?? ""}`);
+ if (!host) return false;
+ // One wish at a time: the form's address as typed so far, never each partial host on the way.
+ wishes.clear();
+ if (on === true) wishes.set(host, now());
+ return true;
+ });
+ const wished = env => {
+ const host = hostOf(env.origin), at = wishes.get(host);
+ wishes.delete(host);
+ return at !== undefined && now() - at < 10 * 60_000;
+ };
+
const asking = new Set();
/** Still on that server: the person may have gone elsewhere while the server answered. */
const showing = (win, env) => {
@@ -90,8 +156,8 @@ export function installServerLending({ ipcMain, guard, sharing, dialogs, validat
try { return new URL(win.webContents.getURL()).origin === env.origin; } catch { return false; }
};
return {
- /** The window finished loading a server: a server of the person's own asks once per pairing; any other asks as before
- * while the maintainer flag is on. */
+ /** The window finished loading a server: a server of the person's own the add form's switch was on for is lent; any
+ * other server asks as before while the maintainer flag is on. */
async offer(win) {
const env = active();
if (!env || asking.has(env.id) || win.isDestroyed() || !candidate(env)) return;
@@ -99,9 +165,9 @@ export function installServerLending({ ipcMain, guard, sharing, dialogs, validat
try {
const info = await sharing().ownOffer(env);
if (info !== false) {
- if (!info || !showing(win, env)) return;
- if (await allows(env, win)) await sharing().lendOwn(env, firstGrant);
- else sharing().declineOwn(env, info);
+ // A server of their own is no longer asked in a popup: the add form's switch said what they want (`wished`),
+ // and the switch on its row, its card and its Screen panel says and changes it from then on.
+ if (info && wished(env) && showing(win, env)) await sharing().lendOwn(env, firstGrant);
return;
}
if (!(await flag()) || win.isDestroyed()) return;
diff --git a/lend-preview.html b/lend-preview.html
new file mode 100644
index 0000000000..9d61f8c891
--- /dev/null
+++ b/lend-preview.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Lend Preview</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/lend-preview.tsx"></script>
+ </body>
+</html>
diff --git a/server/index.ts b/server/index.ts
index 0066bf733c..3e10b333a4 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -633,7 +633,7 @@ import { clearInternalTurn, isInternalTurn, markInternalTurn } from "./internal-
import { createReactionRoutes } from "./routes/reactions.ts";
import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts";
import { createPersonReplies } from "./person-replies.ts";
-import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts";
+import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts"; import { ownServerLendingRefusal } from "./own-server-lending-refusal.ts";
import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";
import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
@@ -8262,7 +8262,7 @@ async function beginTurn(
{ id: "shell", label: "Long-running commands", text: worksInWorkspace ? longCommandsPrompt(computerPromptKind) : "" },
{ id: "computer", label: "Computer", text: computerPrompt(computerPromptKind) + noTerminal.turn(threadId, bot, { ownShell: worksInWorkspace, computerMounted: computerKind !== null, sharedTools: Boolean(integrations.agents && lendingEnabled()), canSelect: Boolean(computerSelectionTurns.get(threadId) && !computerSelectionTurns.get(threadId)?.handoff) }, { model: cloudEngine(instance, bot.modelSelection.model).name, routine: opts?.automationSource !== undefined }) },
{ id: "team-computer", label: "Team computer", text: teamComputerPrompt(teamComputer) },
- { id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : "") + (computerSelectionTurns.get(threadId)?.handoff && !integrations.browser ? HANDOFF_BROWSER_NOTE : ""), canSelect: computerSelectionTurns.has(threadId) && !computerSelectionTurns.get(threadId)?.handoff, selectionRules: !selectionRulesStable, cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened, ownComputer: CLOUD_HOME && integrations.agents && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER, typingSession) : undefined, lentToServer: lentToServer(integrations.agents, { botId: bot.id, threadId, generation: dispatchClaimId }), thisComputer: !CLOUD_HOME && bot.computer !== "off" && !inheritedTeamComputer(bot) && shouldMountLocalComputer({ requested: "local", providerSupportsLocal: instance.adapter.capabilities.localComputerMcp === true }) ? { bot: bot.name, botId: bot.id, platform: process.platform } : undefined }) }, { id: "computer-selection", label: "Choosing a computer", text: selectionRulesStable ? computerSelectionPrompt({ cloudHome: Boolean(CLOUD_HOME) }) : "" },
+ { id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : "") + (computerSelectionTurns.get(threadId)?.handoff && !integrations.browser ? HANDOFF_BROWSER_NOTE : ""), canSelect: computerSelectionTurns.has(threadId) && !computerSelectionTurns.get(threadId)?.handoff, selectionRules: !selectionRulesStable, cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened, ownComputer: CLOUD_HOME && integrations.agents && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER, typingSession) : undefined, lentToServer: lentToServer(integrations.agents, { botId: bot.id, threadId, generation: dispatchClaimId }), worksOnAuto: bot.computer === undefined, thisComputer: !CLOUD_HOME && bot.computer !== "off" && !inheritedTeamComputer(bot) && shouldMountLocalComputer({ requested: "local", providerSupportsLocal: instance.adapter.capabilities.localComputerMcp === true }) ? { bot: bot.name, botId: bot.id, platform: process.platform, desktopApp: DESKTOP_MANAGED || desktopComputer.granted() } : undefined }) }, { id: "computer-selection", label: "Choosing a computer", text: selectionRulesStable ? computerSelectionPrompt({ cloudHome: Boolean(CLOUD_HOME) }) : "" },
{ id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER, typingSession), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, threadId) : "" }, phoneLinkPart(),
{ id: "composio", label: "Connected apps", text: integrations.composio ? composioSystemPrompt(liveBot?.connectorTools ?? bot.connectorTools) + describeConnectorScopes((liveBot ?? bot).connectorScopes) : "" },
{ id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot, lentMcp.lines(liveBot ?? bot, { botId: bot.id, threadId, generation: dispatchClaimId }), teamConnections.mcpServerApps(liveBot ?? bot, { servers: cfg.mcpServers ?? {}, bridged: Boolean(integrations.composio), blocked: (slug) => managedPolicy.appsConnectRefusal([slug]) })) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },
@@ -13005,8 +13005,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (method === "GET" && path === "/api/internal/shared-computers" && botLending()) {
const principal = sharedComputerPrincipal(internalCapability); await sharedComputers.settledAfterWake(principal, () => internalCapabilityIsActive(internalCapability));
// `say` too: the bot says why instead of asking the person to open OpenMausBot, which can't help while the computer is lent already.
- const why = CLOUD_HOME && !principal && (CLOUD_TEAM || sharedComputers.status(CLOUD_HOME_LENDER).length > 0) ? cloudLendingRefusalNotice(internalCapability) : null;
- return json(res, 200, { computers: sharedComputers.list(principal), ...sharedComputers.away(principal), ...sharedComputers.screenNotLent(principal), ...(why ? { unavailable: cloudLendingRefusalForBot(internalCapability, false), say: why } : {}), ...(!CLOUD_HOME && turnPlaces.get(internalCapability.threadId)?.place !== "local" ? { thisComputer: `This computer itself is never in this list and needs no sharing. ${thisComputerSwitchFor(internalCapability, internalSender)}` } : {}) });
+ const why = CLOUD_HOME && !principal && (CLOUD_TEAM || sharedComputers.status(CLOUD_HOME_LENDER).length > 0) ? cloudLendingRefusalNotice(internalCapability) : null, ownRefusal = !CLOUD_HOME && !principal && ownHome.ownServer() ? ownServerLendingRefusal(sharedComputers.known(OWN_SERVER_LENDER).filter((computer) => computer.lent)) : null;
+ return json(res, 200, { computers: sharedComputers.list(principal), ...sharedComputers.away(principal), ...sharedComputers.screenNotLent(principal), ...(why ? { unavailable: cloudLendingRefusalForBot(internalCapability, false), say: why } : ownRefusal ?? {}), ...(!CLOUD_HOME && turnPlaces.get(internalCapability.threadId)?.place !== "local" ? { thisComputer: `This computer itself is never in this list and needs no sharing. ${thisComputerSwitchFor(internalCapability, internalSender)}` } : {}) });
}
if (method === "POST" && path === "/api/internal/shared-computers" && botLending()) {
const parsed = sharedComputerOperation.safeParse(await readInternalBody());
diff --git a/server/own-server-lending-refusal.ts b/server/own-server-lending-refusal.ts
new file mode 100644
index 0000000000..d77021e405
--- /dev/null
+++ b/server/own-server-lending-refusal.ts
@@ -0,0 +1,16 @@
+// A server of one person's own lends their computer only to a conversation they started with their own message
+// (shared-computers.ts provenRequestPerson). Any other conversation (one a bot, a routine or a webhook started, say) used to
+// get an empty list, which reads exactly like a computer that is off: it now gets why, for the bot and for the
+// person, in one line each. Only on a server nobody else signs in to, so nobody learns of another person's computer.
+import { theirComputer } from "./lent-computers.ts";
+import type { LentPlatform } from "./lent-computers.ts";
+
+/** `lent`: the computers the one owner lends this server now; none, and there is nothing to explain. */
+export function ownServerLendingRefusal(lent: ReadonlyArray<{ name: string; platform: LentPlatform | null }>): { unavailable: string; say: string } | null {
+ if (!lent.length) return null;
+ const { theirs, device } = theirComputer(lent);
+ return {
+ unavailable: `This conversation can't use ${theirs}: it is lent, and not offline, but only a conversation the person started themselves, with their own message, can use it. Tell them so in one sentence with the say field, and don't use another place instead unless they ask.`,
+ say: `Only a conversation you start yourself can use your ${device}. Ask for it in a new conversation with this bot.`,
+ };
+}
diff --git a/server/own-window-sends.test.ts b/server/own-window-sends.test.ts
index ab628fcfb2..2536966b50 100644
--- a/server/own-window-sends.test.ts
+++ b/server/own-window-sends.test.ts
@@ -1,14 +1,14 @@
import { randomUUID } from "node:crypto";
import { describe, expect, it } from "vitest";
-import { noteOwnWindowSend, ownWindowLine } from "./own-window-sends.ts";
+import { ownWindowLine, ownWindowSendStarting } from "./own-window-sends.ts";
describe("lines the desktop app's own window sent", () => {
it("knows a noted line by its thread, send and words, and nothing else", () => {
const threadId = randomUUID(), sendId = randomUUID(), text = "list my lent Mac";
const line = { role: "user", sendId, text };
expect(ownWindowLine(threadId, line)).toBe(false);
- noteOwnWindowSend(threadId, sendId, text);
+ ownWindowSendStarting(threadId, sendId, text)(true);
expect(ownWindowLine(threadId, line)).toBe(true);
expect(ownWindowLine(randomUUID(), line)).toBe(false);
expect(ownWindowLine(threadId, { ...line, text: "other words" })).toBe(false);
@@ -18,7 +18,7 @@ describe("lines the desktop app's own window sent", () => {
it("never a signed-in person's, a bot's, a relayed or an app's line, even with the same send", () => {
const threadId = randomUUID(), sendId = randomUUID(), text = "use my Mac";
- noteOwnWindowSend(threadId, sendId, text);
+ ownWindowSendStarting(threadId, sendId, text)(true);
const line = { role: "user", sendId, text };
expect(ownWindowLine(threadId, { ...line, sender: { name: "Guest", id: "p_guest" } })).toBe(false);
expect(ownWindowLine(threadId, { ...line, peerAsk: { botId: "b" } })).toBe(false);
@@ -27,4 +27,19 @@ describe("lines the desktop app's own window sent", () => {
expect(ownWindowLine(threadId, { ...line, aside: true })).toBe(false);
expect(ownWindowLine(threadId, { ...line, role: "bot" })).toBe(false);
});
+
+ it("knows a send while it is being accepted, and keeps it only once one was accepted", () => {
+ const threadId = randomUUID(), sendId = randomUUID(), text = "open my lent Mac";
+ const line = { role: "user", sendId, text };
+ const refused = ownWindowSendStarting(threadId, sendId, text);
+ expect(ownWindowLine(threadId, line), "the turn it starts may set up before the send answers").toBe(true);
+ refused(false);
+ expect(ownWindowLine(threadId, line)).toBe(false);
+ const first = ownWindowSendStarting(threadId, sendId, text), retry = ownWindowSendStarting(threadId, sendId, text);
+ retry(false);
+ expect(ownWindowLine(threadId, line), "a refused retry does not take the first send's proof").toBe(true);
+ first(true);
+ first(false);
+ expect(ownWindowLine(threadId, line)).toBe(true);
+ });
});
diff --git a/server/own-window-sends.ts b/server/own-window-sends.ts
index 8c3754f2cc..aea76e318b 100644
--- a/server/own-window-sends.ts
+++ b/server/own-window-sends.ts
@@ -11,8 +11,24 @@ const sends = createPhoneSends();
const proof = (threadId: string, sendId: string, text: string): string =>
createHash("sha256").update(JSON.stringify(["own-window", threadId, sendId, text])).digest("base64");
-export function noteOwnWindowSend(threadId: string, sendId: string, text: string): void {
- sends.note(proof(threadId, sendId, text));
+const inFlight = new Map<string, number>();
+
+/**
+ * A send from the window, known from before it is accepted: the turn it starts may set up (and read its line) before
+ * the send answers. The answer settles it: kept for a send that was accepted, gone for one that was refused.
+ */
+export function ownWindowSendStarting(threadId: string, sendId: string, text: string): (accepted: boolean) => void {
+ const key = proof(threadId, sendId, text);
+ inFlight.set(key, (inFlight.get(key) ?? 0) + 1);
+ let settled = false;
+ return (accepted) => {
+ if (settled) return;
+ settled = true;
+ const left = inFlight.get(key)! - 1;
+ if (left) inFlight.set(key, left);
+ else inFlight.delete(key);
+ if (accepted) sends.note(key);
+ };
}
type Line = { role?: string; text?: string; sendId?: string; sender?: unknown; peerAsk?: unknown; relayed?: boolean; via?: string; aside?: unknown };
@@ -20,5 +36,7 @@ type Line = { role?: string; text?: string; sendId?: string; sender?: unknown; p
/** A person's line the desktop app's own window sent: no signed-in sender, relay, app or bot wrote it. */
export function ownWindowLine(threadId: string, line: Line | undefined): boolean {
if (!line || line.role !== "user" || line.sender || line.peerAsk || line.relayed || line.via !== undefined || line.aside) return false;
- return line.sendId !== undefined && line.text !== undefined && sends.has(proof(threadId, line.sendId, line.text));
+ if (line.sendId === undefined || line.text === undefined) return false;
+ const key = proof(threadId, line.sendId, line.text);
+ return sends.has(key) || inFlight.has(key);
}
diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.ts
index b36ed5c494..6b9e3554eb 100644
--- a/server/routes/bot-messages.test.ts
+++ b/server/routes/bot-messages.test.ts
@@ -59,8 +59,8 @@ async function fixture(over: Partial<Record<keyof BotMessageRouteDeps, unknown>>
started: Array<{ text: string; opts: StartOpts }>;
relayed: Array<Parameters<BotMessageRouteDeps["relayedReaction"]>>;
serverPresses: Array<{ threadId: string; messageId: string; type: string }>; serverAnswer: "handled" | "refused" | null; records: string | null;
- fromPhone: boolean; phoneSends: string[];
- } = { accepted: [], hold: null, refuse: null, busy: false, prompts: [], started: [], relayed: [], serverPresses: [], serverAnswer: null, records: null, fromPhone: false, phoneSends: [] };
+ fromPhone: boolean; phoneSends: string[]; setupSaw: boolean[];
+ } = { accepted: [], hold: null, refuse: null, busy: false, prompts: [], started: [], relayed: [], serverPresses: [], serverAnswer: null, records: null, fromPhone: false, phoneSends: [], setupSaw: [] };
const startTurn: BotMessageRouteDeps["startTurn"] = async (botId, text, opts = {}) => {
state.started.push({ text, opts });
state.prompts.push(promptWithReply(text, opts.replyTo));
@@ -87,6 +87,8 @@ async function fixture(over: Partial<Record<keyof BotMessageRouteDeps, unknown>>
return { ok: true as const, queued: true as const, queueId: queued.id, threadId: input.threadId };
}
const message = store.appendMessage(input.threadId, { role: "user", kind: "text", text: input.text, replyToId: input.replyTo?.id, sendId: input.sendId });
+ // A turn that starts at once may set up (lent computers included) before the send answers.
+ state.setupSaw.push(ownWindowLine(input.threadId, message));
return { ok: true as const, threadId: input.threadId, message };
});
};
@@ -758,6 +760,20 @@ describe("POST /api/bots/:id/messages from the desktop app's own window", () =>
expect(ownWindowLine(threadId, plain.body.message)).toBe(true);
});
+ it("lets the turn a send starts at once see the window's line while it sets up", async () => {
+ const { threadId, state, post } = await fixture();
+ const plain = await post({ threadId, sendId: SEND, text: words });
+ expect(plain.status, JSON.stringify(plain.body)).toBe(202);
+ expect(state.setupSaw).toEqual([true]);
+ });
+
+ it("leaves no proof for a send that was refused", async () => {
+ const { threadId, state, post } = await fixture();
+ state.refuse = new DirectSendRefused(409, { error: "spend cap reached", code: "spend_cap" });
+ expect((await post({ threadId, sendId: SEND, text: words })).status).toBe(409);
+ expect(ownWindowLine(threadId, { role: "user", sendId: SEND, text: words })).toBe(false);
+ });
+
it("notes neither a press nor a relay", async () => {
const { store, bot, threadId, post, show } = await fixture();
const pressed = await post({ threadId, sendId: SEND, text: words, widgetAction: { messageId: show("routineForm"), ref: "confirm", values: { days: "mon,tue,wed,thu,fri,sat,sun", report: "discord:releases" } } });
diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index a52db414c4..d649de088b 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -36,7 +36,7 @@ import { extractSteerImages } from "../turn-images.ts";
import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";
import type { UsageTrigger } from "../usage-ledger.ts";
import { forgetSendingSession, noteSendingSession } from "../sending-sessions.ts";
-import { noteOwnWindowSend } from "../own-window-sends.ts";
+import { ownWindowSendStarting } from "../own-window-sends.ts";
import { noteTypedSend } from "../typed-sends.ts";
import { engineSessionOutdated, startFresh } from "../fresh-start.ts";
import { parseMentionPicks } from "../../shared/room-mentions.ts";
@@ -349,19 +349,21 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
const ownWindowSend = DESKTOP_MANAGED && auth.kind === "loopback" && !auth.companionDevice && sendId && !guarded && !press && !appSent
&& !store.messagesFor(threadId).some((line) => line.sendId === sendId) && !queuedSteeredMessage(bot.id, threadId, sendId);
if (pressKey) pressesInFlight.set(pressKey, sendId);
+ const ownWindowSettled = ownWindowSend ? ownWindowSendStarting(threadId, sendId, text) : undefined;
try {
const receipt = await acceptDirectSend({
botId: bot.id, threadId, text, sendId, replyTo, sender, trigger, dataContext, ...(app ? { app } : {}),
personPresent, admin: owners.admin(auth), ...(followUp ? { followUp } : {}),
...(mentions?.length && !press && !appSent ? { mentions } : {}),
}, guardedStart);
- if (ownWindowSend) noteOwnWindowSend(threadId, sendId, text);
+ ownWindowSettled?.(true);
press?.settle("queueId" in receipt ? receipt.queueId : undefined);
appContext?.deliver();
if (relayed && target && onBehalfOf) relayedReaction(threadId, target.id, onBehalfOf, relayed);
return json(res, 202, receipt);
} catch (error) {
slot?.release();
+ ownWindowSettled?.(false);
if (notedSession) forgetSendingSession(threadId, sendId!);
if (error instanceof DirectSendRefused) return json(res, error.status, error.body);
throw error;
diff --git a/server/self-hosted-lent-pc.e2e.test.ts b/server/self-hosted-lent-pc.e2e.test.ts
new file mode 100644
index 0000000000..0bbc16d0fd
--- /dev/null
+++ b/server/self-hosted-lent-pc.e2e.test.ts
@@ -0,0 +1,121 @@
+// A self-hosted server of one person's own (`openmausbot serve` on a VPS) with a synthetic engine, and the person's Windows
+// PC lent to it by the desktop app (apps and screen, no folder, no terminal). A conversation on Auto, with no Local VM set
+// up and no other computer chosen: its turn is told plainly that it has their PC and how to reach it (list_shared_computers,
+// then shared_computer), and nothing in the prompt sends it to a Local VM that is not set up. A conversation a bot
+// opened is told why it can't use the PC, never an empty list that reads like an offline PC.
+import { randomBytes, randomUUID } from "node:crypto";
+import { spawn, type ChildProcess } from "node:child_process";
+import { createInterface } from "node:readline";
+import { existsSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+import { launchVerificationServer, type VerificationServer } from "../scripts/control-omb.ts";
+
+const PC = { id: randomUUID(), secret: randomBytes(32).toString("hex") };
+let fixture: VerificationServer;
+let owner = "";
+let lending = true;
+const proxies: ChildProcess[] = [];
+
+async function api(method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
+ const response = await fetch(`${fixture.info.url}${path}`, {
+ method, headers: { "content-type": "application/json", origin: fixture.info.url, ...headers },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json().catch(() => null) as any };
+}
+const asOwner = { authorization: "" };
+
+beforeAll(async () => {
+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_MODE: "hang" });
+ const opened = await api("POST", "/api/auth/pairing", { label: "Windows desktop", scopes: ["admin", "client"] });
+ expect(opened.status, JSON.stringify(opened.body)).toBe(200);
+ owner = (await api("POST", "/api/auth/pair", { code: opened.body.code })).body.token;
+ asOwner.authorization = `Bearer ${owner}`;
+ // The desktop app's own-server check: this pairing is the one owner's.
+ expect((await api("GET", "/api/auth/session", undefined, asOwner)).body).toMatchObject({ own: true });
+ const environmentId = (await api("GET", "/.well-known/openmausbot/environment")).body.environmentId as string;
+ const headers = { ...asOwner, "x-omb-computer-secret": PC.secret };
+ const connected = await api("POST", "/api/shared-computers/connect", {
+ id: PC.id, name: "OFFICE-PC", environmentId, folders: [], terminal: false, computer: true, platform: "win32",
+ commandTimeouts: true, longCommands: true, fileEdits: true,
+ }, headers);
+ expect(connected.status, JSON.stringify(connected.body)).toBe(200);
+ void (async () => {
+ while (lending) {
+ const polled = await api("POST", `/api/shared-computers/${PC.id}/poll`, {}, headers).catch(() => null);
+ const job = polled?.body?.job as { id: string } | null | undefined;
+ if (!job) { if (!polled || polled.status !== 200) await new Promise((resolve) => setTimeout(resolve, 200)); continue; }
+ await api("POST", `/api/shared-computers/${PC.id}/result`, { jobId: job.id, result: { ok: true, value: { tools: [{ name: "launch_app" }, { name: "click" }] } } }, headers);
+ }
+ })();
+}, 40_000);
+
+afterAll(async () => {
+ lending = false;
+ for (const proxy of proxies) proxy.kill();
+ await fixture?.close();
+});
+
+type Turn = { systemPrompt?: string; mcpConfig: { mcpServers: { agents: { command: string; args: string[]; env: Record<string, string> } } } };
+const dump = () => join(fixture.info.dataDir, "fake-claude-dump.json");
+
+async function turnFor(start: () => Promise<void>): Promise<Turn> {
+ rmSync(dump(), { force: true });
+ await start();
+ await vi.waitFor(() => expect(existsSync(dump())).toBe(true), { timeout: 15_000 });
+ return JSON.parse(readFileSync(dump(), "utf8")) as Turn;
+}
+
+async function agentTools(turn: Turn) {
+ const agents = turn.mcpConfig.mcpServers.agents;
+ const proxy = spawn(agents.command, agents.args, { env: { PATH: process.env.PATH, HOME: fixture.info.dataDir, ...agents.env }, stdio: ["pipe", "pipe", "pipe"] });
+ proxies.push(proxy);
+ const replies = new Map<number, (value: any) => void>();
+ createInterface({ input: proxy.stdout! }).on("line", (line) => { const msg = JSON.parse(line); replies.get(msg.id)?.(msg.result ?? msg); replies.delete(msg.id); });
+ let next = 0;
+ const request = (method: string, params: unknown): Promise<any> => new Promise((resolve) => {
+ const id = ++next; replies.set(id, resolve);
+ proxy.stdin!.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
+ });
+ await request("initialize", { protocolVersion: "2024-11-05" });
+ return {
+ list: async () => ((await request("tools/list", {})).tools as Array<{ name: string }>).map((tool) => tool.name),
+ call: (name: string, args: unknown = {}) => request("tools/call", { name, arguments: args }) as Promise<{ isError?: boolean; content: Array<{ text: string }> }>,
+ };
+}
+
+it("tells an Auto turn on the person's own server that it has their lent PC and how to reach it, never a Local VM that isn't set up", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Helper" }, asOwner)).body.bot as { id: string; threadId: string; computer?: string };
+ expect(bot.computer).toBeUndefined();
+ const turn = await turnFor(async () => {
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Open Notepad on my PC.", threadId: bot.threadId }, asOwner)).status).toBe(202);
+ });
+ const prompt = turn.systemPrompt ?? "";
+ expect(prompt).toContain("No other computer is set for this conversation: for desktop apps, use their PC (OFFICE-PC) through shared_computer");
+ // No desktop app runs this server, so This computer is never offered as the way to the person's files.
+ expect(prompt).not.toContain("switch it to This computer");
+ expect(prompt).toContain("Their PC (OFFICE-PC) is reached only through shared_computer, never select_computer");
+ expect(prompt).toContain("check list_shared_computers, then use shared_computer on it (computer_tools, then computer_call, for its apps and screen)");
+ const tools = await agentTools(turn);
+ expect(await tools.list()).toEqual(expect.arrayContaining(["list_shared_computers", "shared_computer"]));
+ const listed = JSON.parse((await tools.call("list_shared_computers")).content[0]!.text);
+ expect(listed.computers).toEqual([expect.objectContaining({ id: PC.id, name: "OFFICE-PC", computer: true })]);
+}, 60_000);
+
+it("tells a conversation a routine started why it can't use the lent PC, instead of an empty list that reads as offline", async () => {
+ const bot = (await api("POST", "/api/bots", { name: "Nightly" }, asOwner)).body.bot as { id: string };
+ const turn = await turnFor(async () => {
+ const created = await api("POST", "/api/routines", {
+ name: "Nightly check", prompt: "Open Notepad on my PC.", botId: bot.id, enabled: false,
+ schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 },
+ }, asOwner);
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ expect((await api("POST", `/api/routines/${created.body.routine.id}/run`, undefined, asOwner)).status).toBe(201);
+ });
+ const tools = await agentTools(turn);
+ const listed = JSON.parse((await tools.call("list_shared_computers")).content[0]!.text);
+ expect(listed.computers).toEqual([]);
+ expect(listed.unavailable).toContain("This conversation can't use their PC (OFFICE-PC): it is lent, and not offline");
+ expect(listed.say).toBe("Only a conversation you start yourself can use your PC. Ask for it in a new conversation with this bot.");
+}, 60_000);
diff --git a/server/shared-computers.gate.test.ts b/server/shared-computers.gate.test.ts
index 574dfd4f27..fb6ae1cff9 100644
--- a/server/shared-computers.gate.test.ts
+++ b/server/shared-computers.gate.test.ts
@@ -189,8 +189,14 @@ it("features.sharedComputers true brings the whole surface back, for every paire
const listed = await internal("GET", "/api/internal/shared-computers");
expect(listed.status).toBe(200);
- // A bot not on This computer is told it is never in this list.
- expect(listed.body).toEqual({ computers: [], thisComputer: expect.stringContaining("This computer itself is never in this list") });
+ // A bot not on This computer is told it is never in this list. The fixture's Mac is lent, but this conversation was not
+ // started by the person, so the bot gets the reason and a line to pass on instead of an empty list that reads as offline.
+ expect(listed.body).toEqual({
+ computers: [],
+ thisComputer: expect.stringContaining("This computer itself is never in this list"),
+ unavailable: expect.stringContaining("only a conversation the person started themselves"),
+ say: expect.stringContaining("Only a conversation you start yourself"),
+ });
expect(await api("GET", "/api/shared-computers")).toEqual({ status: 200, body: { computers: [], known: [] } });
expect(await descriptorCapabilities()).toMatchObject({ sharedComputers: true });
diff --git a/server/surface.test.ts b/server/surface.test.ts
index 45d9b00e55..8cb87d2b9a 100644
--- a/server/surface.test.ts
+++ b/server/surface.test.ts
@@ -461,6 +461,24 @@ describe("surfacePrompt", () => {
expect(surfacePrompt({ computer: "vm", browser: false }, { canSelect: true, lentToServer: [], thisComputer }))
.toBe(surfacePrompt({ computer: "vm", browser: false }, { canSelect: true, thisComputer }));
});
+
+ // On a VPS with a lent PC and no place chosen, "select_computer is the way to connect them" sent a bot asked for
+ // desktop apps to a Local VM that was never set up, and This computer (the VPS) was offered for the person's files.
+ it("with a lent computer and no place set, says to use it for desktop apps, and offers This computer only where the app runs", () => {
+ const lent = [{ name: "OFFICE-PC", platform: "win32" as const }];
+ const vps = { bot: "Ada", platform: "linux" as const, desktopApp: false };
+ const none = surfacePrompt({ computer: null, browser: true }, { canSelect: true, lentToServer: lent, thisComputer: vps, worksOnAuto: true });
+ expect(none).toContain("No other computer is set for this conversation: for desktop apps, use their PC (OFFICE-PC) through shared_computer, and don't select a Local VM or another place for it unless they ask.");
+ expect(none).not.toContain("switch it to This computer");
+ expect(surfacePrompt({ computer: null, browser: true }, { canSelect: true, lentToServer: lent, thisComputer: { ...vps, desktopApp: true }, worksOnAuto: true })).toContain("switch it to This computer");
+ // Works on Off (which refuses the lent screen) or a place the person chose that isn't running: not told to use the PC.
+ expect(surfacePrompt({ computer: null, browser: true }, { canSelect: false, lentToServer: lent, worksOnAuto: false })).not.toContain("No other computer is set");
+ // A place chosen or pinned: the person picked it, so only the existing lines speak.
+ expect(surfacePrompt({ computer: "vm", browser: false }, { canSelect: true, lentToServer: lent, worksOnAuto: true })).not.toContain("No other computer is set");
+ expect(surfacePrompt({ computer: null, browser: true }, { pinned: "browser", lentToServer: lent, worksOnAuto: true })).not.toContain("No other computer is set");
+ // Nothing lent: unchanged.
+ expect(surfacePrompt({ computer: null, browser: true }, { canSelect: true, lentToServer: [], worksOnAuto: true })).not.toContain("No other computer is set");
+ });
});
describe("surface parsing", () => {
diff --git a/server/surface.ts b/server/surface.ts
index 03db690597..140192bad2 100644
--- a/server/surface.ts
+++ b/server/surface.ts
@@ -246,14 +246,15 @@ export function failedOnHostPath(command: unknown, result: { exitCode?: unknown;
}
/** On a server where This computer can be picked: a host path (or "my PC", when nothing is lent) is this computer, never the mounted place. */
-function ownFilesSentence(own: { bot: string; botId?: string; platform: NodeJS.Platform }, place: Surface | null, canSelect: boolean,
+function ownFilesSentence(own: { bot: string; botId?: string; platform: NodeJS.Platform; desktopApp?: boolean }, place: Surface | null, canSelect: boolean,
lent?: ReadonlyArray<{ name: string; platform: LentPlatform | null }>): string {
const example = HOST_PATHS[own.platform]?.example;
const unreachable = place ? `, which ${surfaceLabel(place)} cannot reach` : "";
const switchLine = thisComputerSwitch({ place, bot: own.bot, canSelect, ...(own.botId ? { botId: own.botId } : {}) });
- // A person who lends this server a computer has their own files there too: "my PC" no longer names this computer.
+ // A person who lends this server a computer has their own files there too: "my PC" no longer names this computer. A
+ // server no desktop app runs (a VPS) can never be switched to This computer, so the lent computer is the only way.
if (lent?.length) {
- return ` A file or folder at a path of this computer${example ? ` (a path such as ${example})` : ""} is on this computer${unreachable}. A file or folder on ${theirComputer(lent).theirs} is on that computer: reach it only through shared_computer, as above. When they don't say which computer a file is on, ask in one line. ${switchLine}`;
+ return ` A file or folder at a path of this computer${example ? ` (a path such as ${example})` : ""} is on this computer${unreachable}. A file or folder on ${theirComputer(lent).theirs} is on that computer: reach it only through shared_computer, as above. When they don't say which computer a file is on, ask in one line.${own.desktopApp === false ? "" : ` ${switchLine}`}`;
}
return ` A file or folder on the person's own computer (${example ? `a path such as ${example}, ` : ""}their Desktop, Documents, Downloads or OneDrive, or "my PC") is on this computer${unreachable}, and it is never one of the shared computers. ${switchLine}`;
}
@@ -304,8 +305,11 @@ export function surfacePrompt(
opts: { pinned?: Surface | null; note?: string; canSelect?: boolean; selectionRules?: boolean; cloudHome?: boolean; botOpened?: boolean;
ownComputer?: ReadonlyArray<{ name: string; platform: LentPlatform | null }>;
lentToServer?: ReadonlyArray<{ name: string; platform: LentPlatform | null }>;
- /** This computer can be picked for this bot here: its name, and the platform this server runs on. */
- thisComputer?: { bot: string; botId?: string; platform: NodeJS.Platform } } = {},
+ /** The bot's Works on is Auto: no place of its own was chosen (Off refuses the lent screen, and a chosen place is the person's). */
+ worksOnAuto?: boolean;
+ /** This computer can be picked for this bot here: its name, the platform this server runs on, and whether the desktop
+ * app runs this server (false: a server no app launched, whose This computer no bot can use). */
+ thisComputer?: { bot: string; botId?: string; platform: NodeJS.Platform; desktopApp?: boolean } } = {},
): string {
const reportBack = opts.botOpened && !opts.canSelect;
const computer = mounted.computer ? surfaceLabel(mounted.computer) : null;
@@ -348,6 +352,9 @@ export function surfacePrompt(
if (!opts.cloudHome && opts.lentToServer?.length) {
for (const [nowhere, places] of OWN_COMPUTER_WORDING) text = text.replace(nowhere, places);
text += ownComputerSentence(opts.lentToServer, computer);
+ // With no place chosen, "select_computer is the way to connect them" read as the way to the lent computer too, and a
+ // bot asked for desktop apps selected a Local VM that was never set up.
+ if (opts.worksOnAuto && !computer && !opts.pinned) text += ` No other computer is set for this conversation: for desktop apps, use ${theirComputer(opts.lentToServer).theirs} through shared_computer, and don't select a Local VM or another place for it unless they ask.`;
}
if (opts.thisComputer && !opts.cloudHome && !reportBack && mounted.computer !== "local") {
text += ownFilesSentence(opts.thisComputer, mounted.computer, Boolean(opts.canSelect), opts.lentToServer);
diff --git a/src/components/ComputerPanel.simple.test.ts b/src/components/ComputerPanel.simple.test.ts
index 01369d9fe7..865b6221cf 100644
--- a/src/components/ComputerPanel.simple.test.ts
+++ b/src/components/ComputerPanel.simple.test.ts
@@ -686,3 +686,19 @@ describe("Technical controls", () => {
expect(fixture.setAdvancedMode).toHaveBeenCalledWith(true);
});
});
+
+describe("the real panel carries the lend switch (LendComputerSwitch.dom.test.ts covers what it shows)", () => {
+ it("mounts LendHere under the screen, asking for the app's line only while the bot is set to This computer", async () => {
+ const { LendHere } = await import("./LendComputerSwitch");
+ fixture.localComputer = { available: false, support: "unsupported", enabled: false, status: "unavailable", reasonCode: "remote-server" };
+ fixture.seed = { phase: "local-unavailable", resolved: { botId: "scout", threadId: "thread-scout", computer: "local", cloudBackend: "box" } };
+ const onLocal = render(makeBot({ computer: "local" })).nodes.filter((node) => node.type === LendHere);
+ expect(onLocal).toHaveLength(1);
+ expect(onLocal[0]!.props.appNeeded).toBe(true);
+ fixture.values.length = 0; fixture.own = 0;
+ fixture.seed = { phase: "auto-unavailable", resolved: { botId: "scout", threadId: "thread-scout", computer: undefined, cloudBackend: "box" } };
+ const onAuto = render(makeBot()).nodes.filter((node) => node.type === LendHere);
+ expect(onAuto).toHaveLength(1);
+ expect(onAuto[0]!.props.appNeeded).toBe(false);
+ });
+});
diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx
index effaa0e536..fc7ef0b28a 100644
--- a/src/components/ComputerPanel.tsx
+++ b/src/components/ComputerPanel.tsx
@@ -39,7 +39,7 @@ import { FullScreenButton } from "./FullScreenButton"; import { LocalScreenPrevi
import { LinuxLocalControl } from "./LinuxLocalControl";
import { MacLocalControl } from "./MacLocalControl"; import { WindowsLocalControl } from "./WindowsLocalControl";
import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";
-import { busyBoatView, instanceSupportsLocalComputer, localComputerDisabledReason, localComputerSelectable, pageOnRemoteServer, persistedComputerSelectionMatches, isReadyBoatState, resolveBoatPanelAction, shouldPollCloudPreview } from "@/lib/local-computer";
+import { busyBoatView, instanceSupportsLocalComputer, localComputerDisabledReason, localComputerSelectable, pageOnRemoteServer, persistedComputerSelectionMatches, isReadyBoatState, resolveBoatPanelAction, shouldPollCloudPreview } from "@/lib/local-computer"; import { LendHere } from "./LendComputerSwitch";
import { moveBetweenTabs, PANEL_TABS, panelTabProps, scrollTabsWithWheel, TAB_PANEL_FOCUS, tabPanelProps, useAndroidTabFallback } from "./computer-panel-tabs";
import { releaseComputerPanelFocus, useComputerPanelEntry } from "@/lib/computer-panel-focus";
import { PANEL_MIN_WIDTH, useComputerPanelResize } from "./computer-panel-resize";
@@ -1508,7 +1508,7 @@ export function ComputerPanel({
)}
</div>
- {errorText && !cloudRefused && (
+ <LendHere appNeeded={phase === "local-unavailable"} />{errorText && !cloudRefused && (
<div className="mt-2 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger">
{errorText}
</div>
diff --git a/src/components/ConnectedWorkspacesSettings.test.ts b/src/components/ConnectedWorkspacesSettings.test.ts
index 50970bcbbd..e8e6a88bc5 100644
--- a/src/components/ConnectedWorkspacesSettings.test.ts
+++ b/src/components/ConnectedWorkspacesSettings.test.ts
@@ -188,21 +188,17 @@ it("a Cloud of the person's own has no lending control here, since this computer
expect(render().html).not.toContain("data-cloud-lending-link");
});
-it("a server of the person's own has Share this computer with the maintainer flag off: the switch asks main, and its computer access opens", async () => {
- const sharing = { state: vi.fn(), revoke: vi.fn(), servers: vi.fn().mockResolvedValue([{ id: "vps", enabled: false, connected: false, paused: false }]), allow: vi.fn().mockResolvedValue({ enabled: true }) };
+it("a server of the person's own: its row's lend switch (ServerList) stands in for the maintainer's button, and Choose opens its computer access", async () => {
+ const sharing = { state: vi.fn(), revoke: vi.fn(), servers: vi.fn().mockResolvedValue([{ id: "vps", enabled: true, connected: true, paused: false }]) };
stub({ computerSharing: sharing });
await mount();
render(); for (const effect of f.effects) effect(); await flush();
const { html, nodes: tree } = render();
- expect(html).toContain('data-server-share="vps"');
- expect(html).toContain("Share this computer");
expect(html, "the switch stands in for the maintainer's button").not.toContain('aria-label="Computer access for VPS"');
- const list = tree.find(node => (node.props as { onShare?: unknown }).onShare) as unknown as { props: { onShare: (id: string, on: boolean) => void } };
- list.props.onShare("vps", true); await flush();
- expect(sharing.allow).toHaveBeenCalledWith("vps");
+ const list = tree.find(node => (node.props as { onComputerAccess?: unknown }).onComputerAccess) as unknown as { props: { onComputerAccess: (id: string) => void; onShare?: unknown } };
+ expect(list.props.onShare, "the switch keeps its own state now").toBeUndefined();
+ list.props.onComputerAccess("vps"); await flush();
expect(render().html).toContain("Computer access · VPS");
- list.props.onShare("vps", false); await flush();
- expect(sharing.revoke).toHaveBeenCalledWith("vps");
});
it("shows local environment controls in Simplified Chinese", async () => {
diff --git a/src/components/ConnectedWorkspacesSettings.tsx b/src/components/ConnectedWorkspacesSettings.tsx
index cbf60e26af..6b437040fb 100644
--- a/src/components/ConnectedWorkspacesSettings.tsx
+++ b/src/components/ConnectedWorkspacesSettings.tsx
@@ -47,10 +47,6 @@ export function ConnectedWorkspacesSettings({ label, description }: { label?: st
const timer = setInterval(read, 5000);
return () => { current = false; clearInterval(timer); };
}, [sharing, saved]);
- const share = (id: string, on: boolean) => void perform(async () => {
- if (on) { if (await sharing?.allow?.(id)) setComputerId(id); } else await sharing?.revoke(id);
- if (sharing?.servers) setOwnServers(await sharing.servers());
- });
useEffect(() => {
const consume = (id?: string | null) => {
if (id) setComputerId(id);
@@ -92,7 +88,7 @@ export function ConnectedWorkspacesSettings({ label, description }: { label?: st
return <>
<SettingsGroup label={label} description={description} block="your-computers">
{!saved ? <SettingsRows><SettingRow title={t(error ? "servers.yours.loadFailed" : "servers.yours.loading")}>{null}</SettingRow></SettingsRows> :
- <ServerList saved={saved} busy={busy} sharingOffered={sharingOffered} ownServers={ownServers} appVersion={window.ogb?.app?.version ?? null} onShare={share}
+ <ServerList saved={saved} busy={busy} sharingOffered={sharingOffered} ownServers={ownServers} appVersion={window.ogb?.app?.version ?? null}
onSwitch={(id) => void perform(async () => { await bridge.switch(id); return true; })} onForget={(id) => void perform(() => bridge.forget(id))} onComputerAccess={setComputerId} />}
{saved && error && <p role="alert" className="px-4 text-[12px] leading-4 text-danger">{error}</p>}
</SettingsGroup>
diff --git a/src/components/LendComputerSwitch.dom.test.ts b/src/components/LendComputerSwitch.dom.test.ts
new file mode 100644
index 0000000000..b6b7015d85
--- /dev/null
+++ b/src/components/LendComputerSwitch.dom.test.ts
@@ -0,0 +1,135 @@
+// @vitest-environment happy-dom
+// "Let <server>'s bots use this computer" in each place it shows, over a stand-in for main's lend:* bridge: the Screen
+// panel on a server's own page (not lent, lent, waiting, permission missing, can't be lent, Cloud or team), the browser
+// with no app, this app's own page, and the add form.
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import { lendLine } from "@/lib/use-lend-computer";
+
+let capabilities: { host: { label: string; platform: string }; localComputer: { reasonCode?: string; available: boolean } };
+vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({ capabilities, ready: true }) }));
+const { AddFormLendSwitch, LendComputerSwitch, LendHere } = await import("./LendComputerSwitch");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement, root: Root | null = null;
+let view: DesktopLendView;
+const lendComputer = {
+ state: vi.fn(async (_id: string | null) => view),
+ set: vi.fn(async (_id: string | null, on: boolean) => { view = { ...(view as Extract<DesktopLendView, { lendable: true }>), on, connected: on }; return view; }),
+ allowScreen: vi.fn(async (_id: string | null) => { view = { ...(view as Extract<DesktopLendView, { lendable: true }>), screen: undefined }; return view; }),
+ wish: vi.fn(async () => true) as ((address: string, on: boolean) => Promise<boolean>) | undefined,
+};
+const REMOTE_PAGE = { host: { label: "macOS", platform: "darwin" }, localComputer: { reasonCode: "remote-server", available: false } };
+const own = (over: Partial<Extract<DesktopLendView, { lendable: true }>> = {}): DesktopLendView => ({ name: "hetzner-1", lendable: true, on: false, connected: false, paused: false, ...over });
+
+beforeEach(() => {
+ setLocale("en");
+ vi.clearAllMocks();
+ capabilities = REMOTE_PAGE;
+ Object.assign(window, { ogb: { lendComputer } });
+ host = document.createElement("div"); document.body.append(host);
+});
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); });
+
+async function show(element: ReturnType<typeof createElement>) {
+ root = createRoot(host);
+ await act(async () => { root!.render(element); });
+ await act(async () => { await Promise.resolve(); await Promise.resolve(); });
+}
+const click = async (element: Element | null | undefined) => { expect(element).toBeTruthy(); await act(async () => { (element as HTMLElement).click(); await Promise.resolve(); await Promise.resolve(); }); };
+const line = () => host.querySelector("[data-lend-line]")?.textContent;
+const toggle = () => host.querySelector("[role=switch]");
+
+it("Screen panel on your own server, not lent: what it means and one switch, which lends at once", async () => {
+ view = own();
+ await show(createElement(LendHere));
+ expect(host.textContent).toContain("Let hetzner-1’s bots use this computer");
+ expect(line()).toBe("Its bots can then see and use the apps on your screen while MausBot is open here.");
+ expect(toggle()?.getAttribute("aria-checked")).toBe("false");
+ await click(toggle());
+ expect(lendComputer.set).toHaveBeenCalledWith(null, true);
+ expect(toggle()?.getAttribute("aria-checked")).toBe("true");
+ expect(line()).toBe("On: hetzner-1’s bots can use the apps on your screen while MausBot is open here.");
+ await click(toggle());
+ expect(lendComputer.set).toHaveBeenLastCalledWith(null, false);
+ expect(toggle()?.getAttribute("aria-checked")).toBe("false");
+});
+
+it("Screen panel on your own server, lent: on, connecting, paused, and macOS's permission with the button that asks for it", async () => {
+ view = own({ on: true, connected: true });
+ await show(createElement(LendHere));
+ expect(line()).toBe("On: hetzner-1’s bots can use the apps on your screen while MausBot is open here.");
+ expect(host.querySelector("[data-lend-allow]")).toBeNull();
+ await act(async () => root!.unmount()); root = null;
+
+ view = own({ on: true, screen: "permissions" });
+ await show(createElement(LendHere));
+ expect(toggle()?.getAttribute("aria-checked"), "on, with one step left").toBe("true");
+ expect(line()).toBe("One more step: macOS has to allow MausBot to see and control your screen.");
+ await click(host.querySelector("[data-lend-allow]"));
+ expect(lendComputer.allowScreen).toHaveBeenCalledWith(null);
+ expect(host.querySelector("[data-lend-allow]"), "gone once the permission is there").toBeNull();
+
+ expect(lendLine(own({ on: true }))).toBe("On: connecting to hetzner-1…");
+ expect(lendLine(own({ on: true, paused: true }))).toBe("Paused from the MausBot icon’s menu. Resume it there.");
+ expect(lendLine(own({ on: true, connected: true, screen: "blocked" }))).toContain("computer control is blocked on this computer");
+});
+
+it("Screen panel on a server it can't be lent to: the reason in one line, no switch; a Cloud or team says nothing unless the bot is set to This computer", async () => {
+ view = { name: "office", lendable: false, why: "shared" };
+ await show(createElement(LendHere));
+ expect(host.querySelector("[data-lend-reason]")?.textContent).toBe("Bots on office can’t use this computer: other people sign in to it too.");
+ expect(toggle()).toBeNull();
+ await act(async () => root!.unmount()); root = null;
+
+ view = { name: "Acme", lendable: false, why: "team" };
+ await show(createElement(LendHere));
+ expect(host.textContent).toBe("");
+ await act(async () => root!.unmount()); root = null;
+ await show(createElement(LendHere, { appNeeded: true }));
+ expect(host.querySelector("[data-lend-reason]")?.textContent).toBe("Bots on Acme can’t use this computer: it’s a team’s server.");
+
+ expect(lendLine({ name: "My Cloud", lendable: false, why: "cloud" })).toBe("My Cloud uses this computer by its own Cloud rules, not this switch. Pause it from the MausBot icon’s menu.");
+ expect(lendLine({ name: "box", lendable: false, why: "not-owner" })).toBe("Bots on box can’t use this computer: this app isn’t paired with it as its owner.");
+ expect(lendLine({ name: "box", lendable: false, why: "old" })).toBe("Update box to let its bots use this computer.");
+ expect(lendLine({ name: "box", lendable: false, why: "unreachable" })).toBe("Can’t reach box to check whether its bots can use this computer.");
+});
+
+it("in a browser, for a bot set to This computer: only the app on a computer can lend it, with where to get the app", async () => {
+ Object.assign(window, { ogb: undefined });
+ capabilities = { host: { label: "Browser", platform: "unknown" }, localComputer: { available: false } };
+ await show(createElement(LendHere, { appNeeded: true }));
+ expect(host.querySelector("[data-lend-browser]")?.textContent).toContain("Or, in the MausBot app on a computer, connect to this server and turn on “Let its bots use this computer”.");
+ expect(host.querySelector("a")?.getAttribute("href")).toBe("https://www.openmausbot.com/download");
+ await act(async () => root!.unmount()); root = null;
+ await show(createElement(LendHere));
+ expect(host.textContent, "never in every browser panel").toBe("");
+});
+
+it("this app's own page: the panel shows nothing, while a server's row has the switch by its id", async () => {
+ capabilities = { host: { label: "macOS", platform: "darwin" }, localComputer: { available: true } };
+ view = own();
+ await show(createElement(LendHere));
+ expect(host.textContent).toBe("");
+ await act(async () => root!.unmount()); root = null;
+ await show(createElement(LendComputerSwitch, { id: "vps" }));
+ expect(lendComputer.state).toHaveBeenCalledWith("vps");
+ await click(toggle());
+ expect(lendComputer.set).toHaveBeenCalledWith("vps", true);
+});
+
+it("the add form: off by default, and its switch tells main what to do once that server is paired", async () => {
+ await show(createElement(AddFormLendSwitch, { address: "https://maus.example.com" }));
+ expect(host.textContent).toContain("Let its bots use this computer");
+ expect(host.textContent).toContain("Only for a server that’s yours alone.");
+ expect(toggle()?.getAttribute("aria-checked")).toBe("false");
+ expect(lendComputer.wish).toHaveBeenLastCalledWith("https://maus.example.com", false);
+ await click(toggle());
+ expect(lendComputer.wish).toHaveBeenLastCalledWith("https://maus.example.com", true);
+ await act(async () => root!.unmount()); root = null;
+ Object.assign(window, { ogb: { lendComputer: { ...lendComputer, wish: undefined } } });
+ await show(createElement(AddFormLendSwitch, { address: "https://maus.example.com" }));
+ expect(host.textContent, "a server's own page has no add form switch").toBe("");
+});
diff --git a/src/components/LendComputerSwitch.tsx b/src/components/LendComputerSwitch.tsx
new file mode 100644
index 0000000000..614808e646
--- /dev/null
+++ b/src/components/LendComputerSwitch.tsx
@@ -0,0 +1,69 @@
+// "Let <server>'s bots use this computer": one switch with one line under it, wherever a server of the person's own is
+// shown (src/lib/use-lend-computer.ts holds its state). A server it can't be lent to shows the one-line reason instead.
+import { useEffect, useState } from "react";
+import { DESKTOP_DOWNLOAD_URL } from "../../shared/computer-ask";
+import { productName } from "@/lib/brand";
+import { t } from "@/lib/i18n";
+import { pageOnRemoteServer } from "@/lib/local-computer";
+import { useDesktopCapabilities } from "./DesktopCapabilities";
+import { lendLine, useLendComputer } from "@/lib/use-lend-computer";
+import { cn } from "@/lib/cn";
+import { Switch } from "./SettingsPrimitives";
+
+type Look = "row" | "panel";
+
+/** `id`: the saved server on this app's own page, null on a server's own page. `onChoose`: Advanced's folders and terminal
+ * for it, offered once it is on. `quietReasons`: reasons a Cloud or team gives are left out (a panel that isn't about
+ * This computer). */
+export function LendComputerSwitch({ id, look = "row", onChoose, quietReasons = false, className }: { id: string | null; look?: Look; onChoose?: () => void; quietReasons?: boolean; className?: string }) {
+ const lend = useLendComputer(id);
+ const view = lend.view;
+ if (!lend.available || !view) return null;
+ const line = lendLine(view);
+ if (!view.lendable) {
+ if (quietReasons && (view.why === "cloud" || view.why === "team")) return null;
+ return <p data-lend-reason={view.why} className={cn("text-[12px] leading-4 text-ink-secondary", look === "panel" && "mt-3 text-center", className)}>{line}</p>;
+ }
+ const title = t("lend.title", { name: view.name });
+ return <div data-lend-switch={view.on ? "on" : "off"} className={cn("flex items-start gap-3 rounded-lg bg-inset px-3 py-2", look === "panel" && "mt-3 text-left", className)}>
+ <div className="min-w-0 flex-1">
+ <div className="text-[12px] font-medium text-ink">{title}</div>
+ <div data-lend-line className="text-[12px] leading-4 text-ink-secondary">{line}</div>
+ {view.on && view.screen === "permissions" && <button type="button" data-lend-allow disabled={lend.busy} onClick={() => void lend.allowScreen()}
+ className="mt-1 text-[12px] font-medium text-accent-text hover:underline disabled:opacity-50">{t("lend.screen.allow")}</button>}
+ {lend.error && <div role="alert" className="text-[12px] leading-4 text-danger">{lend.error}</div>}
+ </div>
+ {view.on && onChoose && <button type="button" onClick={onChoose} className="shrink-0 self-center text-[12px] font-medium text-accent-text hover:underline">{t("servers.share.choose")}</button>}
+ <Switch checked={lend.on} disabled={lend.busy} aria-label={title} className="self-center" onClick={() => void lend.set(!lend.on)} />
+ </div>;
+}
+
+/** The Screen panel: on a server's own page in the desktop app, its switch; in a browser, for a bot set to This computer,
+ * that only the app on a computer can lend it, with where to get it. Nothing on this app's own page. */
+export function LendHere({ appNeeded = false }: { appNeeded?: boolean }) {
+ const { capabilities } = useDesktopCapabilities();
+ if (window.ogb?.lendComputer && pageOnRemoteServer(capabilities)) return <LendComputerSwitch id={null} look="panel" quietReasons={!appNeeded} />;
+ if (!appNeeded || capabilities.host.label !== "Browser") return null;
+ return <p data-lend-browser className="mt-3 text-center text-[12px] leading-4 text-ink-secondary">
+ {t("lend.browser", { app: productName() })}{" "}
+ <a href={DESKTOP_DOWNLOAD_URL} target="_blank" rel="noreferrer" className="font-medium text-accent-text hover:underline">{t("computerAsk.action.getApp", { app: productName() })}</a>
+ </p>;
+}
+
+/** The add form: lend to the server being added once it is paired, if it turns out to be the person's own. Off unless
+ * turned on; never shown when pairing a saved server again, where off would read as stopping it. */
+export function AddFormLendSwitch({ address }: { address: string }) {
+ const wish = window.ogb?.lendComputer?.wish;
+ const [on, setOn] = useState(false);
+ const trimmed = address.trim();
+ useEffect(() => { if (wish && trimmed) void wish(trimmed, on).catch(() => {}); }, [wish, trimmed, on]);
+ if (!wish) return null;
+ const title = t("lend.addTitle");
+ return <div data-lend-add={on ? "on" : "off"} className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-medium text-ink">{title}</div>
+ <div className="text-[12px] leading-4 text-ink-secondary">{t("lend.addLine", { app: productName() })}</div>
+ </div>
+ <Switch checked={on} aria-label={title} className="self-center" onClick={() => setOn(!on)} />
+ </div>;
+}
diff --git a/src/components/PlaceAddSheet.tsx b/src/components/PlaceAddSheet.tsx
index 9b6165753a..b0592bf417 100644
--- a/src/components/PlaceAddSheet.tsx
+++ b/src/components/PlaceAddSheet.tsx
@@ -20,6 +20,7 @@ import { NewOrganization } from "./cloud-buy/NewOrganization";
import { BackLink, FIELD, Heading, PRIMARY_WIDE } from "./cloud-buy/parts";
import { Layer, useIsTopLayer } from "./Layer";
import { SwatchRadios } from "./SwatchRadios";
+import { AddFormLendSwitch } from "./LendComputerSwitch";
const PAIR_COMMAND = "npx openmausbot pair";
@@ -127,6 +128,8 @@ export function OwnServerLink({ onBack, onConnected, connect = null, start = nul
className="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 font-mono text-[14px] font-normal text-ink outline-none focus:border-accent/50" />
<span className="flex flex-col gap-1 text-[12px] font-normal text-ink-secondary">{t("connect.noCode")}<CommandLine command={PAIR_COMMAND} /></span>
</label>}
+ {/* The question after pairing lives here: on, a server of the person's own may use this computer once paired. */}
+ {!start?.locked && address.trim() && <AddFormLendSwitch address={address} />}
{shownProblem && <p role="alert" data-connect-problem className="text-[13px] text-danger">{shownProblem}</p>}
{canProbe && probing && !found && !shownProblem && <p data-connect-checking className="inline-flex items-center gap-1.5 text-[13px] text-ink-secondary">
<Loader2 size={13} className="animate-spin" aria-hidden="true" />{t("connect.checking")}
diff --git a/src/components/ServerList.test.ts b/src/components/ServerList.test.ts
index d7b3a48f31..a0b0fc9115 100644
--- a/src/components/ServerList.test.ts
+++ b/src/components/ServerList.test.ts
@@ -103,33 +103,36 @@ it("main's word that a status changed is read at once", async () => {
expect(row("mac").querySelector("[data-server-state]")).toBeNull();
});
-it("a server of the person's own has \"Share this computer\" with its switch; Choose what it can use opens only while it is on", async () => {
- const onShare = vi.fn();
- root = createRoot(host);
- const render = async (ownServers: Array<{ id: string; enabled: boolean; connected: boolean; paused: boolean }>) => {
- await act(async () => { root!.render(createElement(ServerList, { ...props, ownServers, onShare })); });
+it("each server saved by hand has the one lend switch: one tap on, one tap off, Choose only while on, the reason where it can't", async () => {
+ const views: Record<string, DesktopLendView> = {
+ vps: { name: "hetzner-1", lendable: true, on: false, connected: false, paused: false },
+ mini: { name: "office-mini", lendable: false, why: "shared" },
+ mac: { name: "Mac at home", lendable: false, why: "not-owner" },
+ open: { name: "old box", lendable: false, why: "old" },
};
- await render([{ id: "vps", enabled: false, connected: false, paused: false }]);
- const share = row("vps").querySelector("[data-server-share]")!;
- expect(share.textContent).toContain("Share this computer");
- expect(share.textContent).toContain("Let hetzner-1's bots use folders you choose, a terminal and the apps on your screen.");
- expect(row("mini").querySelector("[data-server-share]"), "only servers of the person's own").toBeNull();
- expect(row("cloud").querySelector("[data-server-share]")).toBeNull();
- expect(buttonIn(share, "Choose what it can use")).toBeUndefined();
- const toggle = share.querySelector("[role=switch]")!;
- expect(toggle.getAttribute("aria-checked")).toBe("false");
- expect(toggle.getAttribute("aria-label")).toBe("Share this computer with hetzner-1");
- await click(toggle);
- expect(onShare).toHaveBeenCalledWith("vps", true);
-
- await render([{ id: "vps", enabled: true, connected: true, paused: false }]);
+ const lendComputer = {
+ state: vi.fn(async (id: string | null) => views[id!]!),
+ set: vi.fn(async (id: string | null, on: boolean) => { views[id!] = { ...(views[id!] as Extract<DesktopLendView, { lendable: true }>), on, connected: on }; return views[id!]!; }),
+ allowScreen: vi.fn(), wish: vi.fn(async () => true),
+ };
+ Object.assign(window, { ogb: { environments, workspaces, lendComputer } });
+ await mount();
+ await act(async () => { await Promise.resolve(); await Promise.resolve(); });
+ const lend = row("vps").querySelector("[data-lend-switch]")!;
+ expect(lend.textContent).toContain("Let hetzner-1’s bots use this computer");
+ expect(lend.textContent).toContain("Its bots can then see and use the apps on your screen while MausBot is open here.");
+ expect(row("cloud").querySelector("[data-lend-switch], [data-lend-reason]"), "My Cloud lends by its own rules").toBeNull();
+ expect(row("mini").querySelector("[data-lend-reason]")?.textContent).toBe("Bots on office-mini can’t use this computer: other people sign in to it too.");
+ expect(row("mac").querySelector("[data-lend-reason]")?.textContent).toBe("Bots on Mac at home can’t use this computer: this app isn’t paired with it as its owner.");
+ expect(row("open").querySelector("[data-lend-reason]")?.textContent).toBe("Update old box to let its bots use this computer.");
+ expect(buttonIn(lend, "Choose what it can use")).toBeUndefined();
+ await click(lend.querySelector("[role=switch]"));
+ expect(lendComputer.set).toHaveBeenCalledWith("vps", true);
expect(row("vps").querySelector("[role=switch]")?.getAttribute("aria-checked")).toBe("true");
- expect(row("vps").querySelector("[data-server-share]")?.textContent).toContain("hetzner-1's bots can use this computer while this app is open.");
+ expect(row("vps").querySelector("[data-lend-line]")?.textContent).toBe("On: hetzner-1’s bots can use the apps on your screen while MausBot is open here.");
await click(buttonIn(row("vps"), "Choose what it can use"));
expect(props.onComputerAccess).toHaveBeenCalledWith("vps");
await click(row("vps").querySelector("[role=switch]"));
- expect(onShare).toHaveBeenLastCalledWith("vps", false);
-
- await render([{ id: "vps", enabled: true, connected: false, paused: true }]);
- expect(row("vps").querySelector("[data-server-share]")?.textContent).toContain("Paused: hetzner-1's bots can't use this computer until you resume.");
+ expect(lendComputer.set).toHaveBeenLastCalledWith("vps", false);
+ expect(row("vps").querySelector("[role=switch]")?.getAttribute("aria-checked")).toBe("false");
});
diff --git a/src/components/ServerList.tsx b/src/components/ServerList.tsx
index aacbaf5aa9..3ce0a8c1a1 100644
--- a/src/components/ServerList.tsx
+++ b/src/components/ServerList.tsx
@@ -9,7 +9,8 @@ import { useCopyFeedback } from "@/lib/copy-text";
import { byHand } from "@/lib/saved-servers";
import { t } from "@/lib/i18n";
import { OwnServerLink, RailSheet } from "./PlaceAddSheet";
-import { SettingsLinkRow, SettingsRows, Switch } from "./SettingsPrimitives";
+import { SettingsLinkRow, SettingsRows } from "./SettingsPrimitives";
+import { LendComputerSwitch } from "./LendComputerSwitch";
import { PlaceBadge } from "./settings/SettingsNav";
type Saved = Awaited<ReturnType<NonNullable<NonNullable<Window["ogb"]>["environments"]>["state"]>>;
@@ -63,22 +64,9 @@ function StatusLine({ status, onTryNow, onPairAgain, onEdit }: { status: ServerS
</div>;
}
-/** "Share this computer" for a server of the person's own: the same switch and words wherever lending is shown. */
-function ShareRow({ name, share, busy, onShare, onOpen }: { name: string; share: OwnServerSharing; busy: boolean; onShare: (on: boolean) => void; onOpen: () => void }) {
- const line = !share.enabled ? "servers.share.off" : share.paused ? "servers.share.paused" : "servers.share.on";
- return <div data-server-share={share.id} className="mt-2 flex items-center gap-3 rounded-lg bg-inset px-3 py-2">
- <div className="min-w-0 flex-1">
- <div className="text-[12px] font-medium text-ink">{t("servers.share.title")}</div>
- <div className="text-[12px] text-ink-secondary">{t(line, { name })}</div>
- </div>
- {share.enabled && <button type="button" disabled={busy} onClick={onOpen} className="shrink-0 text-[12px] font-medium text-accent-text hover:underline disabled:opacity-50">{t("servers.share.choose")}</button>}
- <Switch checked={share.enabled} disabled={busy} aria-label={t("servers.share.for", { name })} onClick={() => onShare(!share.enabled)} />
- </div>;
-}
-
-export function ServerList({ saved, busy, sharingOffered, ownServers = [], appVersion, onSwitch, onForget, onComputerAccess, onShare = () => {} }: {
+export function ServerList({ saved, busy, sharingOffered, ownServers = [], appVersion, onSwitch, onForget, onComputerAccess }: {
saved: Saved; busy: boolean; sharingOffered: boolean; ownServers?: OwnServerSharing[]; appVersion: string | null;
- onSwitch: (id: string) => void; onForget: (id: string) => void; onComputerAccess: (id: string) => void; onShare?: (id: string, on: boolean) => void;
+ onSwitch: (id: string) => void; onForget: (id: string) => void; onComputerAccess: (id: string) => void;
}) {
const bridge = window.ogb?.environments;
const [statuses, setStatuses] = useState<ServerStatus[]>([]);
@@ -125,7 +113,8 @@ export function ServerList({ saved, busy, sharingOffered, ownServers = [], appVe
{entry.id !== "local" && !entry.home && <button type="button" disabled={busy} data-danger="" aria-label={t("servers.removeName", { name: entry.name })} title={t("servers.removeName", { name: entry.name })}
onClick={() => onForget(entry.id)} className="settings-quiet shrink-0 cursor-pointer">{t("remote.devices.removeShort")}</button>}
</div>
- {share && <div className="pl-11"><ShareRow name={entry.name} share={share} busy={busy} onShare={(on) => onShare(entry.id, on)} onOpen={() => onComputerAccess(entry.id)} /></div>}
+ {/* "Let its bots use this computer": the same switch as its card, the add form and its Screen panel. */}
+ {byHand(entry) && <LendComputerSwitch id={entry.id} className="ms-11 mt-2" onChoose={() => onComputerAccess(entry.id)} />}
{showUpdate && <div className="pl-11"><UpdateNote name={entry.name} status={status!} appVersion={appVersion!} onHide={() => setHidden((list) => [...list, `${entry.id}:${status!.version}`])} /></div>}
</div>;
})}
diff --git a/src/components/devices/DeviceList.tsx b/src/components/devices/DeviceList.tsx
index ce5f2b1f1e..69cfc3933c 100644
--- a/src/components/devices/DeviceList.tsx
+++ b/src/components/devices/DeviceList.tsx
@@ -4,6 +4,7 @@ import { t } from "@/lib/i18n";
import { lastSeen } from "@/lib/pairing-time";
import { deviceGroup, type Device, type DeviceAction, type DeviceGroup } from "@/lib/devices";
import { SettingsGroup, SettingsRows } from "../SettingsPrimitives";
+import { LendComputerSwitch } from "../LendComputerSwitch";
import { DOT, KIND_ICON, groupLabel, kindLabel, routeLabel, statusText } from "./device-words";
const GROUPS: readonly DeviceGroup[] = ["computers", "servers", "phones"];
@@ -45,6 +46,9 @@ function ActionButton({ device, action, quiet, onAction }: { device: Device; act
}
const actionKey = (action: DeviceAction) => `${action.type}:${"source" in action ? action.source.id : ""}`;
+/** A server saved by hand on This computer's own page: the saved id its lend switch is about. */
+const lendsHere = (device: Device) => (window.ogb?.lendComputer?.wish && device.address && device.kind !== "cloud" ? device.sources.find((source) => source.type === "place")?.id ?? null : null);
+
/** What a device is, how it connects and what bots can do with it, then its other actions. */
export function DeviceDetails({ device, actions, onAction, now }: { device: Device; actions: readonly DeviceAction[]; onAction: (device: Device, action: DeviceAction) => void; now: number }) {
return <>
@@ -56,9 +60,11 @@ export function DeviceDetails({ device, actions, onAction, now }: { device: Devi
{device.lastSeen && device.status !== "online" && <Detail label={t("devicesPage.detail.lastSeen")}>{lastSeen(device.lastSeen, now)}</Detail>}
<Detail label={t("devicesPage.detail.bots")}>
{device.canRunBots ? t("devicesPage.detail.runsBots") : device.canHostComputer ? t("devicesPage.detail.hostsComputer") : t("devicesPage.detail.reachesBots")}
- {device.usesThisComputer && <span className="block">{t("servers.share.on", { name: device.name })}</span>}
+ {device.usesThisComputer && !lendsHere(device) && <span className="block">{t("servers.share.on", { name: device.name })}</span>}
</Detail>
</dl>
+ {/* A server of the person's own, saved by hand: the same switch as its row in Your computers. */}
+ {lendsHere(device) && <LendComputerSwitch id={lendsHere(device)!} />}
{actions.length > 0 && <div className="flex flex-wrap items-center gap-x-4 gap-y-2">{actions.map((action) => <ActionButton key={actionKey(action)} device={device} action={action} quiet onAction={onAction} />)}</div>}
</>;
}
diff --git a/src/components/settings/closed-scale.test.ts b/src/components/settings/closed-scale.test.ts
index 6c1fef16bb..e305e41641 100644
--- a/src/components/settings/closed-scale.test.ts
+++ b/src/components/settings/closed-scale.test.ts
@@ -115,7 +115,7 @@ const DEBT: Record<string, number> = {
"src/components/ProIntroduction.tsx": 2,
"src/components/ProfileSettings.tsx": 3,
"src/components/Select.tsx": 9,
- "src/components/ServerList.tsx": 4,
+ "src/components/ServerList.tsx": 2,
"src/components/SettingsPrimitives.tsx": 3,
"src/components/SidebarPopoverMenu.tsx": 1,
"src/components/SidebarProfileMenu.tsx": 2,
diff --git a/src/components/settings/pages/AppPages.lend.dom.test.ts b/src/components/settings/pages/AppPages.lend.dom.test.ts
new file mode 100644
index 0000000000..ee5dd5b036
--- /dev/null
+++ b/src/components/settings/pages/AppPages.lend.dom.test.ts
@@ -0,0 +1,53 @@
+// @vitest-environment happy-dom
+// Settings → This app in Simple mode: Your computers (where a server is added and its lend switch is) shows there too,
+// on This computer's own page and on a server's own page, where that server's switch sits under its row.
+import { act, createElement, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+
+let advanced = false;
+vi.mock("../settings-shell", () => ({ useSettingsShell: () => ({
+ ctx: { desktop: true, advanced, client: false, home: false, here: true, cloud: false },
+ place: { kind: "server", name: "hetzner-1", color: null, named: true }, go: vi.fn(),
+}) }));
+vi.mock("../settings-context", () => ({ useOtherPlaces: () => [], versionLine: () => "MausBot 0.1.178" }));
+vi.mock("../inert", () => ({ useSwitchToComputer: () => ({ name: "This computer" }), InertRow: ({ title }: { title: string }) => createElement("div", { "data-inert": title }) }));
+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => vi.fn() }));
+vi.mock("../../ConnectedWorkspacesSettings", () => ({ ConnectedWorkspacesSettings: ({ label }: { label: string }) => createElement("section", { "data-your-computers": label }) }));
+vi.mock("../../RemoteComputerSection", () => ({ RemoteComputerSection: () => null }));
+vi.mock("../../NotificationSettingsRows", () => ({ NotificationRows: () => null }));
+vi.mock("../../AppSettingsRows", async (original) => ({ ...(await original<object>()), LanguageRow: () => null, UpdatesRow: () => null, ReplayTourRow: () => null }));
+vi.mock("../../AboutDialog", () => ({ AboutDialog: () => null }));
+vi.mock("../../DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({ capabilities: { host: { label: "macOS", platform: "darwin" }, localComputer: { reasonCode: "remote-server", available: false } }, ready: true }) }));
+const { AppPage } = await import("./AppPages");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement, root: Root | null = null;
+const mount = async (children?: ReactNode) => {
+ root = createRoot(host);
+ await act(async () => { root!.render(children ?? createElement(AppPage)); });
+ await act(async () => { await Promise.resolve(); await Promise.resolve(); });
+};
+
+beforeEach(() => { setLocale("en"); advanced = false; host = document.createElement("div"); document.body.append(host); });
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); });
+
+it("Simple mode shows Your computers on This computer's own page, as Advanced does", async () => {
+ Object.assign(window, { ogb: { environments: { state: vi.fn() } } });
+ await mount();
+ expect(host.querySelector("[data-your-computers]")?.getAttribute("data-your-computers")).toBe("Your computers");
+ await act(async () => root!.unmount()); root = null;
+ advanced = true;
+ await mount();
+ expect(host.querySelector("[data-your-computers]")).toBeTruthy();
+});
+
+it("on a server's own page in Simple mode, its lend switch sits under its row, and the inert environments group stays Advanced", async () => {
+ const lendComputer = { state: vi.fn(async () => ({ name: "hetzner-1", lendable: true, on: false, connected: false, paused: false })), set: vi.fn(), allowScreen: vi.fn() };
+ Object.assign(window, { ogb: { workspaces: { add: vi.fn() }, lendComputer } });
+ await mount();
+ expect(lendComputer.state).toHaveBeenCalledWith(null);
+ expect(host.querySelector("[data-lend-switch]")?.textContent).toContain("Let hetzner-1’s bots use this computer");
+ expect(host.querySelector("[data-settings-block=\"environments\"]"), "the inert environments group stays Advanced").toBeNull();
+});
diff --git a/src/components/settings/pages/AppPages.tsx b/src/components/settings/pages/AppPages.tsx
index 594acf47cc..aa4108c369 100644
--- a/src/components/settings/pages/AppPages.tsx
+++ b/src/components/settings/pages/AppPages.tsx
@@ -13,6 +13,7 @@ import {
} from "../../AppSettingsRows";
import { ChromeRailRow } from "../../ChromeRailToggle";
import { ConnectedWorkspacesSettings } from "../../ConnectedWorkspacesSettings";
+import { LendComputerSwitch } from "../../LendComputerSwitch";
import { CustomThemesSettings } from "../../CustomThemesSettings";
import { DiagnosticsRow } from "../../DiagnosticsRow";
import { NotificationRows } from "../../NotificationSettingsRows";
@@ -63,8 +64,8 @@ export function AppPage() {
</SettingsRows>
</SettingsGroup>
)}
- {/* Your computers is Advanced: in Simple the rail switches places, and the page stays one window tall. */}
- {ctx.desktop && ctx.advanced && (window.ogb?.environments
+ {/* Your computers, in Simple too: where a server is added, and where "Let its bots use this computer" is switched. */}
+ {ctx.desktop && (window.ogb?.environments
? <ConnectedWorkspacesSettings label={t("settings.app.computers")} description={t("settings.app.computersLine")} />
: !ctx.client && <PlacesFromHere />)}
{ctx.desktop && ctx.advanced && <RemoteComputerSection hideWhenUnavailable legacyOnly />}
@@ -89,7 +90,7 @@ export function AppPage() {
/** A Cloud's page in the desktop window: the places list reads the rail through the workspaces bridge, which works on
* every page; only the environments on this computer need This computer's own page. */
function PlacesFromHere() {
- const { place } = useSettingsShell();
+ const { place, ctx } = useSettingsShell();
const others = useOtherPlaces("app");
const workspaces = window.ogb?.workspaces;
if (!workspaces) return null;
@@ -99,6 +100,8 @@ function PlacesFromHere() {
<SettingRow title={place.name} leading={<PlaceBadge place={place} size={24} />} subtitle={t("servers.managed")}>
<span className="text-[13px] leading-5 text-ink-secondary">{t("servers.current")}</span>
</SettingRow>
+ {/* On a server's own page: the same switch its row has on This computer's page. */}
+ {window.ogb?.lendComputer && <LendComputerSwitch id={null} className="mx-4 mb-3 ms-[60px]" />}
{others.map((other) => (
<SettingRow key={other.key} title={other.name} leading={<PlaceBadge place={{ kind: other.kind === "computer" ? "computer" : "cloud", name: other.name, color: other.color }} size={24} />}
subtitle={other.kind === "computer" ? t("servers.localHint") : undefined}>
@@ -109,9 +112,9 @@ function PlacesFromHere() {
onClick={() => void workspaces.add?.("address")} data={{ "data-server-connect": "" }} />}
</SettingsRows>
</SettingsGroup>
- <SettingsGroup label={t("connectedWorkspaces.localTitle")} block="environments">
+ {ctx.advanced && <SettingsGroup label={t("connectedWorkspaces.localTitle")} block="environments">
<SettingsRows><InertRow title={t("connectedWorkspaces.newEnvironment")} /></SettingsRows>
- </SettingsGroup>
+ </SettingsGroup>}
</>;
}
diff --git a/src/devices-preview.tsx b/src/devices-preview.tsx
index a5c1098ab6..7315c7d7fc 100644
--- a/src/devices-preview.tsx
+++ b/src/devices-preview.tsx
@@ -55,6 +55,10 @@ const statuses = full ? [
{ id: "mini", state: "connected", since: now - 9e8, version: "0.1.171", behind: true, install: "global" },
{ id: "vps", state: "cantReach", since: now - 40 * MIN, version: "0.1.180", behind: false, install: "docker" },
] : [];
+const lendViews: Record<string, DesktopLendView> = {
+ mini: { name: "Studio Mac mini", lendable: true, on: true, connected: true, paused: false },
+ vps: { name: "Hetzner box", lendable: true, on: false, connected: false, paused: false },
+};
const ogb = {
platform: "darwin",
app: { version: "0.1.180" },
@@ -64,6 +68,9 @@ const ogb = {
environments: { state: async () => ({ localOrigin: "http://127.0.0.1:8799", remote: false, packaged: true, activeId: "local", environments }), status: async () => statuses,
switch: async () => {}, forget: async () => {}, retry: async () => {}, addFromLink: async () => {}, create: async () => ({ ok: true, state: null }), pickDir: async () => ({ ok: false }) },
computerSharing: { servers: async () => (full ? [{ id: "mini", enabled: true, connected: true, paused: false }] : []) },
+ // The one lend switch on a server's card (src/lib/use-lend-computer.ts): the Mac mini lends, the VPS doesn't yet.
+ lendComputer: { state: async (id: string | null) => lendViews[id ?? ""] ?? lendViews.vps!, set: async (id: string | null, on: boolean) => (lendViews[id ?? ""] = { ...(lendViews[id ?? ""] as Extract<DesktopLendView, { lendable: true }>), on, connected: on }),
+ allowScreen: async (id: string | null) => lendViews[id ?? ""]!, wish: async () => true },
workspaces: { state: () => new Promise(() => {}), places: () => new Promise(() => {}), add: async () => {}, probe: async () => ({ outcome: "problem", problem: "empty" }) },
} : {}),
};
diff --git a/src/lend-preview.tsx b/src/lend-preview.tsx
new file mode 100644
index 0000000000..4b9633034f
--- /dev/null
+++ b/src/lend-preview.tsx
@@ -0,0 +1,127 @@
+// Dev-only gallery of "Let <server>'s bots use this computer", served at /lend-preview.html; not in the packaged app. It
+// mounts the real switch, the real Settings window and the real add form over a fake desktop bridge (no main process,
+// no server), so each state can be looked at and photographed.
+// ?view=panel&state=off|on|connecting|permissions|shared|team|old|browser (the Screen panel's part, on a server's page)
+// ?view=settings&section=app|devices&state=off|on&add=1&select=<device id> (This computer's own Settings)
+// &skin=midnight|daylight&advanced=1
+import { StrictMode, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { Monitor } from "lucide-react";
+import { DesktopCapabilitiesProvider } from "@/components/DesktopCapabilities";
+import { LendHere } from "@/components/LendComputerSwitch";
+import { SettingsModal } from "@/components/SettingsModal";
+import { productName } from "@/lib/brand";
+import { loadLocale, t } from "@/lib/i18n";
+import { setAdvancedMode } from "@/lib/interface-mode";
+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
+import { initialState, StoreContext } from "@/state/store";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const view = params.get("view") === "settings" ? "settings" : "panel";
+const stateName = params.get("state") ?? "off";
+const skin = params.get("skin") ?? "midnight";
+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
+setAdvancedMode(params.get("advanced") === "1");
+await loadLocale(params.get("lang") ?? "en");
+
+const name = "Hetzner box";
+const views: Record<string, DesktopLendView> = {
+ off: { name, lendable: true, on: false, connected: false, paused: false },
+ on: { name, lendable: true, on: true, connected: true, paused: false },
+ connecting: { name, lendable: true, on: true, connected: false, paused: false },
+ permissions: { name, lendable: true, on: true, connected: true, paused: false, screen: "permissions" },
+ shared: { name: "Office server", lendable: false, why: "shared" },
+ team: { name: "Acme team", lendable: false, why: "team" },
+ old: { name, lendable: false, why: "old" },
+};
+let lent = views[stateName] ?? views.off!;
+const lendComputer = {
+ state: async () => lent,
+ set: async (_id: string | null, on: boolean) => { lent = { ...(lent as Extract<DesktopLendView, { lendable: true }>), on, connected: on }; return lent; },
+ allowScreen: async () => { lent = { ...(lent as Extract<DesktopLendView, { lendable: true }>), screen: undefined }; return lent; },
+ ...(view === "settings" ? { wish: async () => true } : {}),
+};
+const browser = stateName === "browser";
+const now = Date.now();
+const environments = [
+ { id: "local", kind: "local" as const, name: "This computer" },
+ { id: "vps", kind: "remote" as const, name, origin: "https://maus.example.com" },
+];
+const capabilities = {
+ host: { platform: "darwin", label: "macOS", session: "", packaged: true, homeDir: "" },
+ windowChrome: "native", windowFrame: true,
+ screenPreview: { available: false, interaction: "none", reasonCode: "remote-server" },
+ dictation: { available: false, engine: "none", onDevice: false, reasonCode: "remote-server" },
+ localComputer: { available: false, support: "unsupported", enabled: false, status: "unavailable", reasonCode: view === "panel" ? "remote-server" : undefined },
+};
+const ogb = browser ? undefined : {
+ platform: "darwin",
+ app: { version: "0.1.178", ownPage: view === "settings" },
+ getCapabilities: async () => capabilities,
+ onCapabilitiesChanged: () => () => {},
+ lendComputer,
+ ...(view === "settings" ? {
+ environments: { state: async () => ({ localOrigin: "http://127.0.0.1:8799", remote: false, packaged: true, activeId: "local", environments }),
+ status: async () => [{ id: "vps", state: "connected", since: now - 9e8, version: "0.1.178", behind: false, install: "docker" }],
+ switch: async () => {}, forget: async () => {}, retry: async () => {}, addFromLink: async () => {}, create: async () => ({ ok: true, state: null }), pickDir: async () => ({ ok: false }) },
+ computerSharing: { servers: async () => [{ id: "vps", enabled: lent.lendable && lent.on, connected: true, paused: false }] },
+ workspaces: { state: () => new Promise(() => {}), places: () => new Promise(() => {}), add: async () => {},
+ probe: async () => ({ outcome: "found", origin: "https://maus.example.com", label: "maus.example.com", version: "0.1.178", transport: "https" }) },
+ } : {}),
+};
+(globalThis as unknown as { ogb: unknown }).ogb = ogb;
+
+const config = { profile: { name: "Ada", email: "[email protected]" }, membership: { authority: "local", pairingCodes: true }, managedPolicy: null, vps: { configured: false, servers: [] } };
+globalThis.fetch = async (input: RequestInfo | URL) => {
+ const path = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.href).pathname;
+ if (path === "/api/config") return Response.json(config);
+ if (path === "/api/auth/session") return Response.json({ kind: "loopback", trust: "owner" });
+ if (path === "/api/auth/sessions") return Response.json({ sessions: [], current: null });
+ if (path === "/api/phones") return Response.json({ phones: [] });
+ return Response.json({ error: "not in the preview" }, { status: 404 });
+};
+
+/** The Screen panel's computer tab around the switch, as on a server's own page: a stand-in frame with the panel's own
+ * words, not the real panel (ComputerPanel.simple.test.ts checks the real one carries LendHere). */
+function PanelFrame() {
+ const [bot] = useState("Ada");
+ return <div className="flex min-h-screen justify-end bg-app">
+ <aside className="flex w-[380px] flex-col border-l border-hairline/40 bg-panel px-5 pb-5">
+ <div className="mb-1.5 mt-4 text-[13px] text-ink-secondary">{`${bot}’s screen`}</div>
+ <div className="relative flex aspect-[16/10] w-full items-center justify-center overflow-hidden rounded-xl bg-card">
+ <div className="flex flex-col items-center gap-2 px-6 text-center text-ink-secondary"><Monitor size={22} /><span className="text-[12px]">{browser ? t("computer.problem.localNeedsApp", { app: productName() }) : t("computer.problem.lendRemoteServer")}</span></div>
+ </div>
+ {/* As for a bot set to This computer, the panel's own line over the screen; the switch or reason under it. */}
+ <div data-preview-ready><LendHere appNeeded={browser || stateName === "team"} /></div>
+ </aside>
+ </div>;
+}
+
+const state = { ...initialState, config: config as never, appSettingsOpen: true, appSettingsSection: (params.get("section") === "devices" ? "devices" : "app") as never };
+createRoot(document.getElementById("root")!).render(
+ <StrictMode>
+ <DesktopCapabilitiesProvider>
+ {view === "panel" ? <PanelFrame /> : <StoreContext.Provider value={{ state, dispatch: () => {} } as never}>
+ <div className="min-h-screen bg-app" />
+ <SettingsModal />
+ </StoreContext.Provider>}
+ </DesktopCapabilitiesProvider>
+ </StrictMode>,
+);
+
+const after = (ms: number, run: () => void) => window.setTimeout(run, ms);
+if (params.get("add") === "1") after(900, () => {
+ document.querySelector<HTMLElement>("[data-server-connect]")?.click();
+ after(300, () => {
+ const input = document.querySelector<HTMLInputElement>("[data-own-server-link]");
+ if (!input) return;
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "https://maus.example.com#code=7KQ2-M9XD-H4TP");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ after(200, () => { if (params.get("wish") === "1") document.querySelector<HTMLElement>("[data-lend-add] [role=switch]")?.click(); });
+ });
+});
+const select = params.get("select");
+if (select) after(900, () => document.querySelector<HTMLElement>(`[data-device-node="${select}"]`)?.click());
+// The switch sits low on This app's page: bring it into view for a picture.
+if (view === "settings") after(params.get("add") === "1" ? 1600 : 1000, () => document.querySelector("[data-lend-add], [data-lend-switch], [data-device-node]")?.scrollIntoView({ block: "center" }));
diff --git a/src/lib/local-computer.test.ts b/src/lib/local-computer.test.ts
index 8860bdaed4..9a6056aa12 100644
--- a/src/lib/local-computer.test.ts
+++ b/src/lib/local-computer.test.ts
@@ -63,7 +63,7 @@ describe("local computer UI eligibility", () => {
localComputer: { available: false, reasonCode: "remote-server" },
} as DesktopCapabilities;
expect(localComputerSelectable({ capabilities, providerSupportsLocal: true })).toBe(false);
- expect(localComputerDisabledReason({ capabilities, providerSupportsLocal: true })).toBe(en["computer.problem.localRemoteServer"]);
+ expect(localComputerDisabledReason({ capabilities, providerSupportsLocal: true })).toBe(en["computer.problem.lendRemoteServer"]);
}
});
diff --git a/src/lib/local-computer.ts b/src/lib/local-computer.ts
index a3f7f1fd4a..5285ec1a70 100644
--- a/src/lib/local-computer.ts
+++ b/src/lib/local-computer.ts
@@ -39,7 +39,7 @@ export function localComputerDisabledReason({
}): string | null {
if (!providerSupportsLocal) return t("computer.problem.localAiCannot");
if (capabilities.localComputer.available) return null;
- if (pageOnRemoteServer(capabilities)) return t("computer.problem.localRemoteServer");
+ if (pageOnRemoteServer(capabilities)) return t("computer.problem.lendRemoteServer");
if (capabilities.host.platform === "linux") {
if (capabilities.localComputer.reasonCode === "linux-wayland-seat-safety-blocked") return t("computer.problem.localWaylandBlocked");
if (capabilities.localComputer.reasonCode === "wayland-compositor-unsupported") return t("computer.problem.localWaylandDesktop");
diff --git a/src/lib/use-lend-computer.ts b/src/lib/use-lend-computer.ts
new file mode 100644
index 0000000000..a8572968f3
--- /dev/null
+++ b/src/lib/use-lend-computer.ts
@@ -0,0 +1,72 @@
+// The one switch for "Let <server>'s bots use this computer", the same wherever it shows: a server's row in Settings
+// (Your computers), its card on the Devices page, the add form, and that server's own Screen panel. All of them read and
+// change one state, in this app's main process (electron/server-lending.mjs), through this hook.
+import { useCallback, useEffect, useRef, useState } from "react";
+import { productName } from "@/lib/brand";
+import { t } from "@/lib/i18n";
+
+export type LendView = DesktopLendView;
+
+/** How often an open switch reads the state again: a permission granted in System Settings turns its line off by itself. */
+const READ_EVERY_MS = 4000;
+
+/** The line under the switch, or in its place when the server can't be lent to: one plain sentence. */
+export function lendLine(view: LendView, app = productName()): string {
+ const name = view.name;
+ if (!view.lendable) {
+ switch (view.why) {
+ case "team": return t("lend.why.team", { name });
+ case "cloud": return t("lend.why.cloud", { name, app });
+ case "shared": return t("lend.why.shared", { name });
+ case "not-owner": return t("lend.why.notOwner", { name });
+ case "old": return t("lend.why.old", { name });
+ case "settings": return t("lend.why.settings", { name });
+ default: return t("lend.why.unreachable", { name });
+ }
+ }
+ if (!view.on) return t("lend.off", { app });
+ if (view.paused) return t("lend.paused", { app });
+ if (view.screen === "permissions") return t("lend.screen.permissions", { app });
+ if (view.screen === "starting") return t("lend.screen.starting");
+ if (view.screen === "blocked") return t("lend.screen.blocked", { app });
+ if (view.screen === "not-running") return t("lend.screen.notRunning", { app });
+ if (view.screen === "off") return t("lend.screen.off");
+ if (view.screen === "unsupported") return t("lend.screen.unsupported");
+ if (!view.connected) return t("lend.connecting", { name });
+ return t("lend.on", { name, app });
+}
+
+/** `id`: the saved server, on this app's own page; null on a server's own page, where it is that server. `enabled`: false
+ * reads nothing (a row that isn't a server saved by hand). */
+export function useLendComputer(id: string | null, enabled = true) {
+ const bridge = window.ogb?.lendComputer;
+ const [view, setView] = useState<LendView | null>(null);
+ const [pending, setPending] = useState<boolean | null>(null);
+ const [error, setError] = useState("");
+ const busy = useRef(false);
+ useEffect(() => {
+ if (!bridge || !enabled) { setView(null); return; }
+ let alive = true;
+ const read = () => void bridge.state(id).then((next) => { if (alive && !busy.current) setView(next); }).catch(() => {});
+ read();
+ const timer = window.setInterval(read, READ_EVERY_MS);
+ return () => { alive = false; window.clearInterval(timer); };
+ }, [bridge, id, enabled]);
+ const run = useCallback(async (act: (lend: NonNullable<typeof bridge>) => Promise<LendView>, next: boolean | null) => {
+ if (!bridge || busy.current) return;
+ busy.current = true; setPending(next); setError("");
+ try { setView(await act(bridge)); }
+ catch (failure) { setError(String((failure as Error)?.message ?? failure).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/, "")); }
+ finally { busy.current = false; setPending(null); }
+ }, [bridge]);
+ return {
+ available: Boolean(bridge),
+ view,
+ /** What the switch shows: the tap at once, then what main says. */
+ on: pending ?? (view?.lendable === true && view.on),
+ busy: pending !== null,
+ error,
+ set: (on: boolean) => run((lend) => lend.set(id, on), on),
+ allowScreen: () => run((lend) => lend.allowScreen(id), null),
+ };
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 43106fa77c..9fd29fd621 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -5387,7 +5387,6 @@
"computer.problem.localWindows": "Bots can't use this PC right now. Restart {app}, and if that doesn't help, open Settings → This app → Help.",
"computer.problem.localMac": "Bots can't use this Mac yet. Check that {app} is allowed under Screen Recording and Accessibility in System Settings → Privacy & Security, then restart it.",
"computer.problem.localMacTooOld": "Bots can't use this Mac: local desktop control needs macOS 15 Sequoia or later. Update macOS to use it.",
- "computer.problem.localRemoteServer": "Bots on your own server can't use this computer. Switch back to This computer to use it.",
"computer.problem.oldImage": "The private desktop is out of date; replace it",
"computer.problem.unmanaged": "The existing container was not created by {app}; recreate it",
"computer.problem.publicViewer": "The private desktop's viewer is open to the network; replace it",
@@ -9110,6 +9109,29 @@
"servers.share.paused": "Paused: {name}'s bots can't use this computer until you resume.",
"servers.share.choose": "Choose what it can use",
"servers.share.for": "Share this computer with {name}",
+ "lend.title": "Let {name}’s bots use this computer",
+ "lend.off": "Its bots can then see and use the apps on your screen while {app} is open here.",
+ "lend.on": "On: {name}’s bots can use the apps on your screen while {app} is open here.",
+ "lend.connecting": "On: connecting to {name}…",
+ "lend.paused": "Paused from the {app} icon’s menu. Resume it there.",
+ "lend.screen.permissions": "One more step: macOS has to allow {app} to see and control your screen.",
+ "lend.screen.allow": "Open System Settings",
+ "lend.screen.starting": "On: computer control is starting…",
+ "lend.screen.blocked": "On, but computer control is blocked on this computer. Restart {app}, and if that doesn’t help, open Settings → This app → Help.",
+ "lend.screen.notRunning": "On, but computer control isn’t running. Restart {app} to start it.",
+ "lend.screen.off": "On, but local control is off on this computer. Turn it on in the Screen panel.",
+ "lend.screen.unsupported": "On, but bots can’t use the screen in this kind of desktop session.",
+ "lend.why.team": "Bots on {name} can’t use this computer: it’s a team’s server.",
+ "lend.why.cloud": "{name} uses this computer by its own Cloud rules, not this switch. Pause it from the {app} icon’s menu.",
+ "lend.why.shared": "Bots on {name} can’t use this computer: other people sign in to it too.",
+ "lend.why.notOwner": "Bots on {name} can’t use this computer: this app isn’t paired with it as its owner.",
+ "lend.why.old": "Update {name} to let its bots use this computer.",
+ "lend.why.unreachable": "Can’t reach {name} to check whether its bots can use this computer.",
+ "lend.why.settings": "Choose what {name}’s bots can use on this computer under Your computers in Settings → This app.",
+ "lend.browser": "Or, in the {app} app on a computer, connect to this server and turn on “Let its bots use this computer”.",
+ "lend.addTitle": "Let its bots use this computer",
+ "lend.addLine": "Only for a server that’s yours alone. Its bots can use the apps on your screen while {app} is open here.",
+ "computer.problem.lendRemoteServer": "This bot can’t use This computer from here.",
"routines.status.deferred": "Deferred: target busy",
"routines.run.review": "Review",
"routines.run.open": "Open run",
diff --git a/src/locales/it.json b/src/locales/it.json
index 80593e38e3..17506182b5 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -5350,7 +5350,6 @@
"computer.problem.localWindows": "Al momento i bot non possono usare questo PC. Riavvia {app} e, se non basta, apri Impostazioni → Questa app → Aiuto.",
"computer.problem.localMac": "I bot non possono ancora usare questo Mac. Controlla che {app} sia consentito in Registrazione schermo e Accessibilità, in Impostazioni di Sistema → Privacy e sicurezza, poi riavvialo.",
"computer.problem.localMacTooOld": "Bots non può usare questo Mac: il controllo desktop locale ha bisogno di macOS 15 Sequoia o più tardi. Aggiornare macOS per usarlo.",
- "computer.problem.localRemoteServer": "I bot sul tuo server non possono usare questo computer. Torna a Questo computer per usarlo.",
"computer.problem.oldImage": "Il desktop privato non è aggiornato; sostituiscilo",
"computer.problem.unmanaged": "Il container esistente non è stato creato da {app}; ricrealo",
"computer.problem.publicViewer": "Il visore del desktop privato è aperto alla rete; sostituiscilo",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index a83edfbbef..bab907ff6f 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -7173,7 +7173,6 @@
"computer.problem.localNotReady": "ボットはまだこのコンピューターを使えません。{app} を再起動して、もう一度お試しください。",
"computer.problem.localNeedsApp": "ボットにこのコンピューターを使わせることができるのは、ここにある {app} アプリだけです。使うには、ここでアプリを開いてください。",
"computer.problem.localMac": "ボットはまだこの Mac を使えません。「システム設定 → プライバシーとセキュリティ」の「画面収録」と「アクセシビリティ」で {app} が許可されているか確認してから、再起動してください。",
- "computer.problem.localRemoteServer": "自分のサーバー上のボットは、このコンピューターを使えません。使うには「このコンピューター」に切り替えてください。",
"ask.header.asks": "{name}からの質問",
"ask.settled.chose": "選んだ回答:",
"ask.settled.answered": "あなたの回答:",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index 2c3aaf7e8f..13ca184e63 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -4408,7 +4408,6 @@
"computer.problem.localNeedsApp": "이 컴퓨터의 {app} 앱만 봇이 이 컴퓨터를 쓰게 할 수 있어요. 쓰려면 여기서 앱을 여세요.",
"computer.problem.localWindows": "지금은 봇이 이 PC를 쓸 수 없어요. {app}을 다시 시작하고, 그래도 안 되면 설정 → 이 앱 → 도움말을 여세요.",
"computer.problem.localMac": "아직 봇이 이 Mac을 쓸 수 없어요. 시스템 설정 → 개인정보 보호 및 보안의 화면 기록과 손쉬운 사용에서 {app}이 허용되어 있는지 확인한 뒤 다시 시작하세요.",
- "computer.problem.localRemoteServer": "내 서버에 있는 봇은 이 컴퓨터를 쓸 수 없어요. 쓰려면 이 컴퓨터로 돌아오세요.",
"computer.problem.oldImage": "비공개 데스크톱이 오래됐어요. 교체하세요",
"computer.problem.unmanaged": "기존 컨테이너는 {app}이 만든 것이 아니에요. 다시 만드세요",
"computer.problem.publicViewer": "비공개 데스크톱의 뷰어가 네트워크에 열려 있어요. 교체하세요",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3ca3a0bb8f..5f3f82e0e3 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -8175,7 +8175,6 @@
"computer.problem.localWindows": "Os bots não conseguem usar este PC agora. Reinicie o app {app}. Se não resolver, abra Configurações → Este app → Ajuda.",
"computer.problem.localMac": "Os bots ainda não conseguem usar este Mac. Confira se o app {app} tem permissão em Gravação de Tela e Acessibilidade, em Ajustes do Sistema → Privacidade e Segurança, e reinicie o app.",
"computer.problem.localMacTooOld": "Os bots não conseguem usar este Mac: o controle local da área de trabalho precisa do macOS 15 Sequoia ou posterior. Atualize o macOS para usá-lo.",
- "computer.problem.localRemoteServer": "Os bots no seu próprio servidor não conseguem usar este computador. Volte para Este computador para usá-lo.",
"ask.header.asks": "{name} pergunta",
"ask.settled.chose": "Você escolheu:",
"ask.settled.answered": "Você respondeu:",
@@ -9042,6 +9041,29 @@
"servers.share.paused": "Pausado: os bots de {name} não podem usar este computador até você retomar.",
"servers.share.choose": "Escolher o que ele pode usar",
"servers.share.for": "Compartilhar este computador com {name}",
+ "lend.title": "Deixar os bots de {name} usarem este computador",
+ "lend.off": "Os bots dele poderão ver e usar os apps na sua tela enquanto o {app} estiver aberto aqui.",
+ "lend.on": "Ligado: os bots de {name} podem usar os apps na sua tela enquanto o {app} estiver aberto aqui.",
+ "lend.connecting": "Ligado: conectando a {name}…",
+ "lend.paused": "Pausado pelo menu do ícone do {app}. Retome por lá.",
+ "lend.screen.permissions": "Falta um passo: o macOS precisa permitir que o {app} veja e controle sua tela.",
+ "lend.screen.allow": "Abrir Ajustes do Sistema",
+ "lend.screen.starting": "Ligado: o controle do computador está iniciando…",
+ "lend.screen.blocked": "Ligado, mas o controle do computador está bloqueado neste computador. Reinicie o {app} e, se não resolver, abra Configurações → Este app → Ajuda.",
+ "lend.screen.notRunning": "Ligado, mas o controle do computador não está em execução. Reinicie o {app} para iniciá-lo.",
+ "lend.screen.off": "Ligado, mas o controle local está desligado neste computador. Ative-o no painel Tela.",
+ "lend.screen.unsupported": "Ligado, mas os bots não podem usar a tela neste tipo de sessão de desktop.",
+ "lend.why.team": "Os bots de {name} não podem usar este computador: é um servidor de equipe.",
+ "lend.why.cloud": "{name} usa este computador pelas regras da própria Cloud, não por este botão. Pause pelo menu do ícone do {app}.",
+ "lend.why.shared": "Os bots de {name} não podem usar este computador: outras pessoas também entram nele.",
+ "lend.why.notOwner": "Os bots de {name} não podem usar este computador: este app não está pareado com ele como dono.",
+ "lend.why.old": "Atualize {name} para deixar os bots dele usarem este computador.",
+ "lend.why.unreachable": "Não foi possível falar com {name} para saber se os bots dele podem usar este computador.",
+ "lend.why.settings": "Escolha o que os bots de {name} podem usar neste computador em Seus computadores, em Configurações → Este app.",
+ "lend.browser": "Ou, no app {app} em um computador, conecte-se a este servidor e ative “Deixar os bots dele usarem este computador”.",
+ "lend.addTitle": "Deixar os bots dele usarem este computador",
+ "lend.addLine": "Só para um servidor que é só seu. Os bots dele podem usar os apps na sua tela enquanto o {app} estiver aberto aqui.",
+ "computer.problem.lendRemoteServer": "Este bot não pode usar Este computador daqui.",
"routines.status.deferred": "Adiada: destino ocupado",
"routines.run.review": "Revisar",
"routines.run.open": "Abrir execução",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 25d8c264ee..5d0e8e2410 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -25506,7 +25506,6 @@
"room.panel.minutes": "e1bded87ee24b702d6c1baf5edf99fccfc0d2e1d5bca603aef4937fb6c282fe2",
"room.panel.hour": "f8b8883f0c9d8d823a8df096ebde57ec04abe9f9cbc4eea1cbc3454c5025c484",
"room.panel.hours": "9bd7df2f709a9827167a40e5c7726cac1e27fc5ce1d60520c9ba2c3b0dcb5dca",
- "computer.problem.localRemoteServer": "0594af9d73bdc307e27d400bf0b6ff7ff5569829fd1dbc2f864f5155d84a2d78",
"computer.err.vpsAlias": "52c5b481767fc15ac38249c350b30e6716194ddf3ac9b083e000587145e7a535",
"computer.err.vpsNotReady": "505ec35db383e1d8836a70f4b489efb4512cdb14c427bbd3d71716f927dd35d1",
"computer.err.vpsReplaceNotReady": "e626e41d174bbb973ed2480564ab28a72452bc0819e3353a7869a9f8eab3c33a",
@@ -34023,7 +34022,6 @@
"computer.problem.localNeedsApp": "03a223f45612e158e37e7310fe69c4dce196b5516e95e51bc18a7e4c955d4813",
"computer.problem.localWindows": "bf61045ef196a15e97143acf2ac139316c82525319a0499f6b2089f42199b7e9",
"computer.problem.localMac": "01ad405bc58e40a8e469b4fc707e9c56243f8168af043e6d0c56082d4cb32f53",
- "computer.problem.localRemoteServer": "0594af9d73bdc307e27d400bf0b6ff7ff5569829fd1dbc2f864f5155d84a2d78",
"ask.header.asks": "bb065f98972232b5d6b3ca3e367960f6c9800325d39285241f40bc60724c4838",
"ask.settled.chose": "4c402ce9ea7e79b8d6021991e837bcbe1b0e252c169d7f342fb7f7acbb429dc3",
"ask.settled.answered": "cf6ed7768b8aec5adfb1f1ff68d2bcda3468e0a0f9e38d48abf2dc36fbc35556",
@@ -45521,7 +45519,6 @@
"remote.client.server.fullTitle": "3a6288bf75b9707b3eec3f16ebab870264e691e75f40905bca29be896f74c49f",
"remote.client.server.clientTitle": "74f080ad654ff3e32155777fdab7cf37bdc9f0951b9a6035f9bcc23a745731df",
"remote.client.server.clientNote": "11d2223e5ed6e6e6fe3b1eecb03afe054076808c351359aec1143fef44841cf4",
- "computer.problem.localRemoteServer": "0594af9d73bdc307e27d400bf0b6ff7ff5569829fd1dbc2f864f5155d84a2d78",
"limits.windowAtLimit": "887a824b14957bc1e2620e6731725b7423db4190ba20869777c6dca52966c034",
"limits.clearsOnReply": "931814ce262849cd845878c58709abffa8a7fec7a284d42f2696bf4a1aedfd9a",
"mcp.check.overLimit": "6a66ce52fd23d5d6f8afd2974bba672a6bb5d58328c978aebf62d4ed0b457a14",
@@ -55122,7 +55119,6 @@
"room.panel.minutes": "e1bded87ee24b702d6c1baf5edf99fccfc0d2e1d5bca603aef4937fb6c282fe2",
"room.panel.hour": "f8b8883f0c9d8d823a8df096ebde57ec04abe9f9cbc4eea1cbc3454c5025c484",
"room.panel.hours": "9bd7df2f709a9827167a40e5c7726cac1e27fc5ce1d60520c9ba2c3b0dcb5dca",
- "computer.problem.localRemoteServer": "0594af9d73bdc307e27d400bf0b6ff7ff5569829fd1dbc2f864f5155d84a2d78",
"computer.problem.unmanaged": "2edc98326c858c500fa1e8f5a2e595510214cc586f048307e1ee12e0b45024ec",
"computer.err.vpsAlias": "52c5b481767fc15ac38249c350b30e6716194ddf3ac9b083e000587145e7a535",
"computer.err.vpsNotReady": "505ec35db383e1d8836a70f4b489efb4512cdb14c427bbd3d71716f927dd35d1",
@@ -98403,7 +98399,6 @@
"room.panel.hour": "f8b8883f0c9d8d823a8df096ebde57ec04abe9f9cbc4eea1cbc3454c5025c484",
"room.panel.hours": "9bd7df2f709a9827167a40e5c7726cac1e27fc5ce1d60520c9ba2c3b0dcb5dca",
"computer.problem.localMacTooOld": "4704202223ba0e31a713b9925a8e1d8effd8bf1014b2a9746d61aeed79b5738a",
- "computer.problem.localRemoteServer": "0594af9d73bdc307e27d400bf0b6ff7ff5569829fd1dbc2f864f5155d84a2d78",
"computer.err.vmOpenSettings": "ca8a867721b6c4c90c1eb98ab312a5e1ec95799f4e2f30acee80387bfc3ce939",
"computer.err.vpsNotReady": "505ec35db383e1d8836a70f4b489efb4512cdb14c427bbd3d71716f927dd35d1",
"computer.err.vpsReplaceNotReady": "e626e41d174bbb973ed2480564ab28a72452bc0819e3353a7869a9f8eab3c33a",
@@ -108302,7 +108297,6 @@
"model.orgBlocked": "ba5ec24678b71d2e6f241fce7ecce15154440e448e9b398143818559a349162e",
"planUsage.monthlySpend": "030f6d6d05272adcd18033906e1caa8b866da2455570ddec9ee4f1eb3133a0ce",
"planUsage.spendAmounts": "5e98824d2436c6d11bf3cfb6ea93f009289ce3b39132c1c589929346bde96afe",
- "computer.problem.localRemoteServer": "0594af9d73bdc307e27d400bf0b6ff7ff5569829fd1dbc2f864f5155d84a2d78",
"connectors.card.mcpSignInHint": "88dd9d2998afa88507b8d9e182279c62094db2e532f8f3cab41ad22137b04667",
"connectors.card.signInTo": "eca7d36631398ebb81526155180c485798f48f36a9d77bc65d64f8b06df22489",
"connectors.card.signIn": "bfd402b2f6f3812529b55596136d3a11c51616317e3b1cd999928e2d4eae7d3f",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 1680fd8088..d67bc17253 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4786,7 +4786,6 @@
"computer.problem.localNotReady": "機器人目前還無法使用這台電腦。請重新啟動 {app} 後再試一次。",
"computer.problem.localNeedsApp": "只有這台電腦上的 {app} 應用程式能讓機器人使用它。請在這裡開啟應用程式來使用。",
"computer.problem.localMac": "機器人目前還無法使用這台 Mac。請到「系統設定 → 隱私權與安全性」確認 {app} 已在「螢幕錄製」和「輔助使用」中獲得允許,然後重新啟動它。",
- "computer.problem.localRemoteServer": "你自己伺服器上的機器人無法使用這台電腦。請切換回「這台電腦」以使用它。",
"computer.problem.oldImage": "私人桌面已過時;請更換它",
"computer.problem.unmanaged": "現有的容器並非由 {app} 建立;請重新建立",
"computer.problem.publicViewer": "私人桌面的檢視器對網路公開;請更換它",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index c011481601..90df794353 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -4796,7 +4796,6 @@
"computer.problem.localNotReady": "机器人暂时还不能使用这台电脑。请重启 {app} 后再试一次。",
"computer.problem.localNeedsApp": "只有这台电脑上的 {app} 应用才能让机器人使用它。请在这里打开应用来使用。",
"computer.problem.localMac": "机器人暂时还不能使用这台 Mac。请在「系统设置 → 隐私与安全性」中确认 {app} 已在「屏幕录制」和「辅助功能」中获得允许,然后重启它。",
- "computer.problem.localRemoteServer": "你自己的服务器上的机器人无法使用这台电脑。请切换回「这台电脑」后再使用。",
"computer.problem.oldImage": "私有桌面已过时;请替换它",
"computer.problem.unmanaged": "现有容器不是由 {app} 创建的;请重新创建",
"computer.problem.publicViewer": "私有桌面的查看器对网络公开;请替换它",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index a18af32779..a50e978eeb 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -25,6 +25,11 @@ const __APP_VERSION__: string;
type DesktopSharedFolder = import("../../electron/computer-sharing.mjs").SharedFolder;
type DesktopComputerSharing = import("../../electron/computer-sharing.mjs").SharingState;
type DesktopLendingActivity = import("../../electron/computer-sharing.mjs").LendingActivityEntry;
+ /** Lending this computer to one server, as the switch shows it (electron/server-lending.mjs view). `why`: what keeps it
+ * from being lent there. `screen`: why its apps and screen don't work yet while it is on (screen-status.mjs). */
+ type DesktopLendView =
+ | { name: string; lendable: true; on: boolean; connected: boolean; paused: boolean; screen?: "starting" | "permissions" | "blocked" | "off" | "not-running" | "unsupported" }
+ | { name: string; lendable: false; why: "team" | "cloud" | "not-owner" | "shared" | "old" | "unreachable" | "settings" };
type DesktopCapabilities = {
host: {
@@ -313,6 +318,17 @@ const __APP_VERSION__: string;
pause?(): Promise<void>;
resume?(): Promise<void>;
};
+ /** The one switch for lending this computer to a server of the person's own (electron/server-lending.mjs). On this
+ * app's own page `id` names the saved server; on a server's own page it is that server, whatever `id` says. */
+ lendComputer?: {
+ state(id: string | null): Promise<DesktopLendView>;
+ set(id: string | null, on: boolean): Promise<DesktopLendView>;
+ /** macOS: asks for Accessibility and Screen Recording, the one step the system itself requires. */
+ allowScreen(id: string | null): Promise<DesktopLendView>;
+ /** The add form's switch (this app's own page only): lend to the server about to be paired at `address` if it
+ * turns out to be the person's own. */
+ wish?(address: string, on: boolean): Promise<boolean>;
+ };
confirm(message: string): Promise<boolean>;
getCapabilities(): Promise<DesktopCapabilities>;
onCapabilitiesChanged(cb: (capabilities: DesktopCapabilities) => void): () => void;