Skip to content

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

Let your own server use this computer: one popup after pairing, and a switch in Settings → Servers (#4829)

Milind Soni1cf7a2246f3b
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index b8cbb46387..e287d108a8 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -587,8 +587,12 @@ Cloud and each other Cloud the verified session lists as theirs
never a server that only signed in with their account. A server of the person's
own that they made their bots' home (**Make <server> my home**, docs/self-hosting.md)
is lent the same way, last, once the move is done and while that server says it
-is theirs alone. Other users (desktop only, self-hosted, hosted team workspaces)
-keep computer sharing exactly as before: off unless a maintainer sets
+is theirs alone. A self-hosted server this desktop paired with as its owner
+(admin scope, no team or Cloud) is asked about once, in a popup, and lent only
+after the person's Allow (`lendOwn`, `electron/server-lending.mjs`); the server
+takes a computer from its admin pairings alone unless `features.sharedComputers`
+is `false` (off) or `true` (every paired session, as before). Other servers and
+hosted team workspaces keep computer sharing off unless a maintainer sets
`features.sharedComputers` by hand.
### What each Cloud gets
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index ed5079c242..c8e9476f2f 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -570,9 +570,19 @@ 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).
-After pairing, **Share this computer?** offers **Choose access** or **Not now**.
-Nothing is shared automatically, unless you make the server your bots' home
-(below). In **Settings → Servers → Computer
+**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
+**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:
+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
+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
dialog. They can access information outside the selected folders. Share only
diff --git a/electron/bridge-contract.json b/electron/bridge-contract.json
index 2762a63010..65f532f2f6 100644
--- a/electron/bridge-contract.json
+++ b/electron/bridge-contract.json
@@ -104,9 +104,13 @@
"companyBackups.state",
"computerSharing",
"computerSharing.activity",
+ "computerSharing.allow",
"computerSharing.chooseFolder",
+ "computerSharing.pause",
+ "computerSharing.resume",
"computerSharing.revoke",
"computerSharing.save",
+ "computerSharing.servers",
"computerSharing.state",
"confirm",
"copyText",
diff --git a/electron/cloud-lending.node-test.mjs b/electron/cloud-lending.node-test.mjs
index 223bca5e16..43602d0431 100644
--- a/electron/cloud-lending.node-test.mjs
+++ b/electron/cloud-lending.node-test.mjs
@@ -360,7 +360,7 @@ test("Pause is instant: the Cloud is told, running work is cancelled, nothing mo
home.push({ action: "computer_call", tool_name: "click", arguments: {} });
await delay(300);
assert.equal((await readFile(driver.calls, "utf8")).trim(), "drag");
- assert.deepEqual(summaries.at(-1), { lending: [], clouds: ["My Cloud"], waiting: [], using: [], paused: true, terminal: false, busy: null, screen: null });
+ assert.deepEqual(summaries.at(-1), { lending: [], clouds: ["My Cloud"], waiting: [], using: [], paused: true, terminal: false, terminalSwitch: true, busy: null, screen: null });
assert.equal(sharing.cloudState(env).problem, "paused");
});
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mts
index 2f715e9e2f..0d0141722c 100644
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@ -4,7 +4,13 @@ export interface SharingState {
folders: SharedFolder[];
terminal: boolean;
computer: boolean;
+ /** Lent to a server of the person's own, which they allowed here: no maintainer flag, and Pause holds it. */
+ own?: boolean;
+ /** Lending is paused from the OpenMausBot icon's menu or Settings. */
+ paused?: boolean;
connected?: boolean;
+ /** Why it is not connected: "paused", or "not-own" / "machine-changed" once lending to that server ended. */
+ problem?: string;
error?: string;
}
interface Workspace { id: string; name: string; origin: string }
@@ -69,6 +75,8 @@ export interface LendingSummary {
using: string[];
paused: boolean;
terminal?: boolean;
+ /** The menu shows the Clouds' terminal switch: a Cloud of the person's own is signed in here. */
+ terminalSwitch?: boolean;
busy: { env: string; action: string } | null;
/** Computer control's latest state, null until it is first read. */
screen: ScreenStatus | null;
@@ -83,6 +91,8 @@ export function lendsAsWanted(record: unknown, wanted: AutomaticGrant): boolean;
export function isHomeFolder(target: string): Promise<boolean>;
export function existingFolders<T>(folders: unknown[], validate: (folders: unknown[]) => Promise<T[]>): Promise<T[]>;
export function validateSharedFolders(folders: unknown, options?: { homeEdits?: boolean }): Promise<SharedFolder[]>;
+/** The sign-in a server answers with (/api/auth/session) is this desktop's admin pairing on a server of the person's own. */
+export function ownServerSession(auth: unknown): boolean;
export function validSharedOperation(operation: unknown, computerId: string): boolean;
export function createComputerSharing(options: {
file: string;
@@ -144,6 +154,15 @@ export function createComputerSharing(options: {
decline(env: Workspace, identity: Identity): void;
save(env: Workspace, input: Pick<SharingState, "folders" | "terminal" | "computer">, identity: Identity): Promise<SharingState>;
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>;
+ /** 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>;
+ /** The person allowed a server of their own to use this computer. */
+ lendOwn(env: Workspace, input: Partial<Pick<SharingState, "folders" | "terminal" | "computer">>): Promise<SharingState>;
+ /** Not now: nothing is lent, and this pairing is not asked again. */
+ declineOwn(env: Workspace, identity: Identity): void;
forget(env: Workspace): void;
cloudState(env: Workspace | null | undefined): CloudLendingState;
/** The folders lent to My Cloud, for Files' copies of them (electron/lent-folders.mjs). */
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index dbe42969a2..0713a97c90 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -138,6 +138,14 @@ export function cloudLendingVerdict(binding, current, env) {
return { allow: true };
}
+/** A server of the person's own, by this desktop's sign-in there: its admin (owner) pairing on a server nobody else signs
+ * in to, as the server says (`own`, server/own-home.ts), and no Cloud, team or hosted server. Lent only once the person
+ * allows it here (lendOwn), without the maintainer flag. Security: never a non-admin pairing, a server others sign in to,
+ * a team's server or a Cloud (a Cloud is lent as one, by its own rules). */
+export function ownServerSession(auth) {
+ return auth?.kind === "session" && auth.own === true && Array.isArray(auth.scopes) && auth.scopes.includes("admin") && auth.cloudHome !== true && !auth.team && auth.hosted !== true;
+}
+
/** What a Cloud that keeps MCP servers for this computer hears: it runs them, and which installs here it is. */
const lendsMcp = environments => {
const ids = Array.isArray(environments) ? environments.filter(uuid).slice(0, 8) : [];
@@ -189,6 +197,7 @@ export function lendsAsWanted(record, wanted) {
}
class Paused extends Error {}
+const UPDATE_SERVER = "Update this server to enable computer sharing";
const LENT_PLATFORMS = new Set(["darwin", "win32", "linux"]);
const RECONNECT_EVERY_MS = 15 * 60_000;
@@ -246,17 +255,19 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
const changed = () => { if (!closed) try { onChange(summary()); } catch {} };
const summary = () => {
const browsing = [...inUse.keys()].find(id => linked.has(id));
- const lent = paused ? [] : environments().filter(env => records[env.id]?.cloud && records[env.id]?.enabled === true);
+ const lent = paused ? [] : environments().filter(env => (records[env.id]?.cloud || records[env.id]?.own) && records[env.id]?.enabled === true);
const using = lent.filter(env => executing?.env === env.id || (inUse.has(env.id) && linked.has(env.id)));
return {
lending: lent.map(env => env.id),
- clouds: (paused ? ownClouds() : lent).map(env => env.name),
+ clouds: (paused ? [...ownClouds(), ...environments().filter(env => records[env.id]?.own && records[env.id].enabled === true)] : lent).map(env => env.name),
// Lent, but the Cloud hasn't accepted this computer yet (or lost it): the menu must not say it can use it. A
// sleeping My Cloud still can; it wakes when a bot needs this computer.
waiting: lent.filter(env => !status.get(env.id)?.connected && status.get(env.id)?.problem !== "asleep").map(env => env.name),
using: using.map(env => env.name),
paused,
terminal: terminalAccount !== null && terminalAccount === signedInAccount(),
+ // The menu's terminal switch is the Clouds' one; a server of the person's own lends the terminal from Settings.
+ terminalSwitch: ownClouds().length > 0,
busy: executing ?? (browsing ? { env: browsing, action: "internet" } : null),
screen: screenNow,
};
@@ -294,7 +305,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
if (allowed && !closed && !maintainerOff) return;
maintainerOff = true;
for (const env of environments()) {
- if (records[env.id]?.cloud || !running.has(env.id)) continue;
+ if (records[env.id]?.cloud || records[env.id]?.own || !running.has(env.id)) continue;
if (status.get(env.id)?.connected) disconnect(env, records[env.id]); else stop(env.id);
}
throw new Error("Computer sharing is turned off on this computer. Restart the desktop after enabling it.");
@@ -306,6 +317,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
changed();
};
const requireGrant = async (env, grant) => {
+ // A server of the person's own was allowed here: no maintainer flag, but Pause and quitting hold it as they hold Clouds.
+ if (grant.own === true) { if (closed || paused) throw new Paused("Lending is paused."); return; }
if (!grant.cloud) return requireEnabled();
// Quitting only pauses: a check in flight at close must never switch lending off for the next launch.
if (closed) throw new Paused("This app is closing.");
@@ -354,12 +367,14 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
if (!response.ok) throw Object.assign(new Error(response.status === 401 || response.status === 403 ? "Pair this desktop again before sharing computer access." : `Server request failed (${response.status}). Update the server if needed.`), { status: response.status });
return json;
};
- const describe = async env => {
+ const describe = async (env, required = true) => {
const [auth, descriptor] = await Promise.all([request(env, "/api/auth/session"), request(env, "/.well-known/openmausbot/environment")])
.catch(error => { throw error.status === 401 || error.status === 403 ? Object.assign(error, { problem: "connect-first" }) : error; });
if (auth.kind !== "session" || !uuid(auth.id) || !uuid(descriptor.environmentId)) throw Object.assign(new Error("Complete server pairing or sign-in first"), { problem: "connect-first" });
- if (descriptor.capabilities?.sharedComputers !== true) throw new Error("Update this server to enable computer sharing");
- return { auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: descriptor.capabilities?.lendingDetails === true, link: descriptor.capabilities?.deviceLink === true, chrome: descriptor.capabilities?.myChromeLink === true, timeouts: descriptor.capabilities?.commandTimeouts === true, long: descriptor.capabilities?.longCommands === true, edits: descriptor.capabilities?.fileEdits === true, asks: descriptor.capabilities?.computerAsks === true, mcp: descriptor.capabilities?.lentMcp === true };
+ // A server of the person's own says what it takes from them in their own sign-in's answer (`lending`), never before pairing.
+ const offered = { ...descriptor.capabilities, ...(ownServerSession(auth) && auth.lending && typeof auth.lending === "object" ? auth.lending : {}) };
+ if (required && offered.sharedComputers !== true) throw new Error(UPDATE_SERVER);
+ return { supported: offered.sharedComputers === true, auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: offered.lendingDetails === true, link: offered.deviceLink === true, chrome: offered.myChromeLink === true, timeouts: offered.commandTimeouts === true, long: offered.longCommands === true, edits: offered.fileEdits === true, asks: offered.computerAsks === true, mcp: offered.lentMcp === true };
};
const identity = async env => {
await requireEnabled();
@@ -371,20 +386,28 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
/** A server of the person's own their bots moved to: lent as their Clouds are, to its one owner's sign-in alone, at the
* server the move chose (lending-target.mjs `own:<environment id>`). */
const ownHomeId = env => { const current = cloud(env); return current?.origin === env.origin && current.accountId?.startsWith("own:") ? current.accountId.slice(4) : null; };
+ /** What the server says it takes, remembered for its connect; a server of the person's own never gets the device link. */
+ const takes = (env, { details, link, chrome: takesChrome, timeouts, long, edits, mcp }) => {
+ for (const [set, on] of [[supportsDetails, details], [supportsLink, link], [supportsChrome, takesChrome], [supportsTimeouts, timeouts], [supportsLong, long], [supportsEdits, edits], [supportsMcp, mcp]]) {
+ if (on) set.add(env.id); else set.delete(env.id);
+ }
+ };
const cloudIdentity = async env => {
- const { auth, info, details, link, chrome: takesChrome, timeouts, long, edits, mcp } = await describe(env);
+ const described = await describe(env), { auth, info } = described;
const own = ownHomeId(env);
if (own !== null && (auth.own !== true || info.environmentId !== own)) throw Object.assign(new Error(t("native.lend.homeChanged")), { problem: "not-cloud" });
if ((own === null && auth.cloudHome !== true) || !Array.isArray(auth.scopes) || !auth.scopes.includes("admin")) throw Object.assign(new Error("This server is not My Cloud"), { problem: "not-cloud" });
- if (details) supportsDetails.add(env.id); else supportsDetails.delete(env.id);
- if (link) supportsLink.add(env.id); else supportsLink.delete(env.id);
- if (takesChrome) supportsChrome.add(env.id); else supportsChrome.delete(env.id);
- if (timeouts) supportsTimeouts.add(env.id); else supportsTimeouts.delete(env.id);
- if (long) supportsLong.add(env.id); else supportsLong.delete(env.id);
- if (edits) supportsEdits.add(env.id); else supportsEdits.delete(env.id);
- if (mcp) supportsMcp.add(env.id); else supportsMcp.delete(env.id);
+ takes(env, described);
return info;
};
+ /** 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);
+ takes(env, { ...described, link: false, chrome: false });
+ return described.info;
+ };
/** The Clouds that keep MCP servers for this computer to run. */
const supportsMcp = new Set();
const supportsDetails = new Set();
@@ -425,7 +448,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
};
const run = (env, grant) => {
stop(env.id);
- if (closed || !grant.enabled || (grant.cloud ? paused : maintainerOff)) return;
+ if (closed || !grant.enabled || (grant.cloud || grant.own ? paused : maintainerOff)) return;
const live = { abort: new AbortController(), cua: null, mcp: null };
running.set(env.id, live);
const signal = live.abort.signal;
@@ -446,6 +469,15 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
grant = { ...grant, ...info };
if (records[env.id]?.id === grant.id) store({ ...records, [env.id]: grant });
}
+ } else if (grant.own) {
+ // Pairing this desktop again keeps lending, as an admin of that same server only; any other answer ends it.
+ const info = await ownIdentity(env);
+ if (signal.aborted || running.get(env.id) !== live) break;
+ if (info.environmentId !== grant.environmentId) { endCloud(env, "machine-changed"); break; }
+ if (info.sessionId !== grant.sessionId) {
+ grant = { ...grant, sessionId: info.sessionId };
+ if (records[env.id]?.id === grant.id) store({ ...records, [env.id]: grant });
+ }
} else if (!matches(grant, await identity(env))) throw new Error("Server sign-in changed. Review computer access again in Settings.");
// A folder deleted since is left out, so the rest (the internet connection too) keeps working; any other refusal
// still stops lending.
@@ -464,7 +496,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
...(supportsTimeouts.has(env.id) ? { commandTimeouts: true } : {}),
...(supportsLong.has(env.id) ? { longCommands: true } : {}),
...(supportsEdits.has(env.id) ? { fileEdits: true } : {}),
- ...(grant.cloud && supportsMcp.has(env.id) ? lendsMcp(localEnvironments()) : {}),
+ ...((grant.cloud || grant.own) && supportsMcp.has(env.id) ? lendsMcp(localEnvironments()) : {}),
}, signal, grant.secret);
if (signal.aborted) break;
status.set(env.id, { connected: true });
@@ -517,7 +549,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
const connection = await cuaConnection();
jobSignal.throwIfAborted();
const mcp = sharedCuaConnection(connection);
- if (!mcp) { if (grant.cloud) try { askForScreen(connection); } catch {} throw new Error(cuaUnavailable(connection?.reason, process.platform, t)); }
+ if (!mcp) { if (grant.cloud || grant.own) try { askForScreen(connection); } catch {} throw new Error(cuaUnavailable(connection?.reason, process.platform, t)); }
live.cua = createSharedCua(mcp, { t });
}
return live.cua;
@@ -538,6 +570,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
await call("result", { jobId: job.id, result });
}
} catch (error) {
+ if (error?.problem === "not-own" && grant.own) { endCloud(env, "not-own"); break; }
if (error instanceof Paused) {
if (running.get(env.id) === live) disconnect(env, grant, true);
status.set(env.id, { connected: false, problem: "paused" });
@@ -574,7 +607,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
: { chrome: lent?.cloud ? lent.enabled === true && lent.chrome === true : false };
const state = id => {
const grant = records[id];
- return { enabled: grant?.enabled === true, folders: Array.isArray(grant?.folders) ? grant.folders : [], terminal: grant?.terminal === true, computer: grant?.computer === true, ...status.get(id) };
+ return { enabled: grant?.enabled === true, folders: Array.isArray(grant?.folders) ? grant.folders : [], terminal: grant?.terminal === true, computer: grant?.computer === true,
+ ...(grant?.own ? { own: true, ...(paused ? { paused: true } : {}) } : {}), ...status.get(id) };
};
// `resumes`: lending waits (for the Cloud sign-in, say) and resumes by itself, so the server keeps it as lent, not stopped.
/** Disconnects still waiting for their Cloud's answer. */
@@ -676,7 +710,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
const automatic = lentAutomatically();
for (const env of environments()) {
const grant = records[env.id];
- if (grant?.cloud && !automatic.has(env.id) && validRecord(grant) && !running.has(env.id) && cloudLendingVerdict(grant.cloud, cloud(env), env).allow) run(env, grant);
+ if (!validRecord(grant) || running.has(env.id)) continue;
+ if (grant.own || (grant.cloud && !automatic.has(env.id) && cloudLendingVerdict(grant.cloud, cloud(env), env).allow)) run(env, grant);
}
changed();
wakeAsking();
@@ -772,6 +807,33 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
disconnect(env, records[env.id]);
store({ ...records, [env.id]: grant }); run(env, grant); changed(); return state(env.id);
},
+ /** 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),
+ /** 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. */
+ async ownOffer(env) {
+ const info = await ownIdentity(env).catch(() => null), kept = records[env.id];
+ if (!info) return false;
+ if (kept && kept.environmentId === info.environmentId && (kept.sessionId === info.sessionId || (kept.own && kept.enabled === true))) return null;
+ return info;
+ },
+ /** The person allowed a server of their own to use this computer: what `input` lends, checked as every grant is, the
+ * home folder read only. Security: only while this desktop is that server's admin now; no folder unless chosen. */
+ async lendOwn(env, input) {
+ const version = changeGrant(env.id);
+ if (closed) throw new Error("Lending is unavailable while the app is closing.");
+ const info = await ownIdentity(env);
+ const folders = await validateSharedFolders(input?.folders ?? []);
+ const grant = { ...info, id: randomUUID(), secret: randomBytes(32).toString("hex"), enabled: true, own: true, folders, terminal: input?.terminal === true, computer: input?.computer === true };
+ if (!folders.length && !grant.terminal && !grant.computer) throw new Error("Choose at least one folder or capability to share");
+ if (grantVersions.get(env.id) !== version) return state(env.id);
+ disconnect(env, records[env.id]);
+ store({ ...records, [env.id]: grant }); run(env, grant); changed(); return state(env.id);
+ },
+ /** Not now: nothing is lent, and this pairing is not asked again. */
+ declineOwn(env, info) { changeGrant(env.id); disconnect(env, records[env.id]); store({ ...records, [env.id]: { ...info, enabled: false, own: true, folders: [], terminal: false, computer: false } }); changed(); },
cloudState,
/** What Files copies to My Cloud (electron/lent-folders.mjs): the folders lent to it, with this grant's id and the
* places no grant reaches, and `paused` while lending is; `{ off: true }` while nothing is lent to it. */
@@ -805,7 +867,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
paused = true;
try { store(records); } catch {}
for (const env of environments()) {
- if (!records[env.id]?.cloud) continue;
+ if (!records[env.id]?.cloud && !records[env.id]?.own) continue;
if (running.has(env.id)) disconnect(env, records[env.id]);
status.set(env.id, { connected: false, problem: "paused" });
}
@@ -843,7 +905,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo
const grant = records[env.id];
if (!validRecord(grant)) continue;
if (grant.cloud) { if (!automatic.has(env.id) && cloudLendingVerdict(grant.cloud, cloud(env), env).allow) run(env, grant); }
- else if (maintainer && !maintainerOff) run(env, grant);
+ else if (grant.own || (maintainer && !maintainerOff)) run(env, grant);
}
changed();
void lendAutomatically();
diff --git a/electron/lend-automatically.node-test.mjs b/electron/lend-automatically.node-test.mjs
index 0a5110d8d0..ff4780b69d 100644
--- a/electron/lend-automatically.node-test.mjs
+++ b/electron/lend-automatically.node-test.mjs
@@ -209,7 +209,7 @@ test("Pause stops every Cloud at once and lasts across restarts; Resume lends ag
await until(() => homes[HOME].connects.length === 1 && homes[OTHER].connects.length === 1, "both Clouds to be lent");
mac.sharing.pause();
await until(() => homes[HOME].disconnects.length === 1 && homes[OTHER].disconnects.length === 1, "both Clouds to be told");
- assert.deepEqual(mac.summaries.at(-1), { lending: [], clouds: ["My Cloud", "Client A"], waiting: [], using: [], paused: true, terminal: false, busy: null, screen: null });
+ assert.deepEqual(mac.summaries.at(-1), { lending: [], clouds: ["My Cloud", "Client A"], waiting: [], using: [], paused: true, terminal: false, terminalSwitch: true, busy: null, screen: null });
assert.equal(mac.sharing.lentToCloud(myCloud).paused, true, "Files keeps My Cloud's copies, and holds bots' changes there");
const plans = path.join(mac.dir, "Plans");
await mkdir(plans);
diff --git a/electron/lend-own-server.node-test.mjs b/electron/lend-own-server.node-test.mjs
new file mode 100644
index 0000000000..1cfea4d3df
--- /dev/null
+++ b/electron/lend-own-server.node-test.mjs
@@ -0,0 +1,268 @@
+// A server of the person's own (this desktop paired there as its admin) gets this computer once the person allows it, with
+// no maintainer flag: the popup after pairing and Settings' switch (server-lending.mjs), what is lent, Not now, Stop,
+// Pause, a new pairing, and the pairings that never count as their own.
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, readFile, realpath, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+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";
+
+const GARAGE = "http://192.168.1.20:8799";
+const garage = { id: "garage", name: "Garage", origin: GARAGE, kind: "remote" };
+
+const until = async (check, what, ms = 5000) => {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) { if (await check()) return; await delay(10); }
+ assert.fail(`timed out waiting for ${what}`);
+};
+
+async function scratch(t) {
+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-lend-own-server-")));
+ t.after(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }));
+ return dir;
+}
+
+/** A self-hosted server as this desktop's sign-in there sees it: `scopes`, whether nobody else signs in there (`own`, which
+ * the server says only to its one owner, with what it takes from them), and whether it is a team's or a Cloud. Its public
+ * description offers no lending, as before pairing. */
+function selfHosted({ scopes = ["admin", "client"], own = true, extra = {}, mcp = true } = {}) {
+ const json = (value, status = 200) => ({ ok: status < 400, status, headers: { get: () => null }, body: (async function* () { yield Buffer.from(JSON.stringify(value)); })() });
+ const state = { environmentId: randomUUID(), sessionId: randomUUID(), scopes, own, extra, connects: [], disconnects: [], polls: 0 };
+ state.fetch = async (url, init) => {
+ const route = new URL(url).pathname;
+ const owner = state.own && state.scopes.includes("admin");
+ if (route === "/api/auth/session") return json({ kind: "session", id: state.sessionId, scopes: state.scopes, ...(owner ? { own: true, lending: { sharedComputers: true, lendingDetails: true, fileEdits: true, ...(mcp ? { lentMcp: true } : {}) } } : {}), ...state.extra });
+ if (route === "/.well-known/openmausbot/environment") return json({ environmentId: state.environmentId, capabilities: { remoteSessions: true } });
+ const body = init?.body ? JSON.parse(init.body) : {};
+ if (route === "/api/shared-computers/connect") { state.connects.push(body); return json({ ok: true }); }
+ if (route.endsWith("/poll")) {
+ state.polls++;
+ await delay(50, undefined, { signal: init?.signal }).catch(() => {});
+ init?.signal?.throwIfAborted();
+ return json({ job: null });
+ }
+ if (route.endsWith("/disconnect")) { state.disconnects.push(body); return json({ ok: true }); }
+ return json({ ok: true });
+ };
+ return state;
+}
+
+/** This desktop with the maintainer flag off, lending as main wires it; `restart()` is the app opening again. */
+async function desktop(t, server, { ownClouds = () => [] } = {}) {
+ const dir = await scratch(t);
+ const file = path.join(dir, "profile", "computer-sharing.json");
+ const summaries = [];
+ const make = () => createComputerSharing({ file, environments: () => [garage], enabled: async () => false, home: path.join(dir, "home"), cuaConnection: async () => null,
+ fetch: (url, init) => server.fetch(url, init), ownClouds, localEnvironments: () => [server.environmentId], onChange: summary => summaries.push(summary) });
+ let sharing = make();
+ t.after(() => sharing.close());
+ return { file, summaries, get sharing() { return sharing; }, restart: () => { sharing.close(); sharing = make(); sharing.start({ maintainer: false }); return sharing; } };
+}
+
+test("only this desktop's admin pairing on a server that is no Cloud, team or hosted workspace counts as the person's own", () => {
+ const owner = { kind: "session", id: randomUUID(), scopes: ["admin", "client"], own: true };
+ assert.equal(ownServerSession(owner), true);
+ assert.equal(ownServerSession({ ...owner, own: undefined }), false, "a server others sign in to");
+ assert.equal(ownServerSession({ ...owner, scopes: ["client"] }), false, "a narrower pairing");
+ assert.equal(ownServerSession({ ...owner, scopes: undefined }), false);
+ assert.equal(ownServerSession({ ...owner, team: { id: "t", role: "admin" } }), false, "a team's server");
+ 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);
+});
+
+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 => {
+ const server = selfHosted();
+ const mac = await desktop(t, server);
+ const info = await mac.sharing.ownOffer(garage);
+ assert.deepEqual(info, { sessionId: server.sessionId, environmentId: server.environmentId });
+ assert.equal(server.connects.length, 0, "asking lends nothing");
+ const lent = await mac.sharing.lendOwn(garage, { folders: [], terminal: false, computer: true });
+ assert.equal(lent.own, true);
+ assert.equal(lent.enabled, true);
+ await until(() => server.connects.length === 1 && mac.sharing.state(garage.id).connected, "the server to take this computer");
+ const [connect] = server.connects;
+ assert.deepEqual({ computer: connect.computer, terminal: connect.terminal, folders: connect.folders, mcpServers: connect.mcpServers, environments: connect.environments, fileEdits: connect.fileEdits },
+ { computer: true, terminal: false, folders: [], mcpServers: true, environments: [server.environmentId], fileEdits: true });
+ assert.equal("internet" in connect || "chrome" in connect, false, "the device link is a Cloud's alone");
+ assert.equal(await mac.sharing.ownOffer(garage), null, "answered for this pairing");
+ assert.deepEqual(mac.summaries.at(-1).lending, [garage.id]);
+ assert.deepEqual(mac.summaries.at(-1).clouds, ["Garage"], "the menu-bar item names it like a Cloud");
+ assert.equal(mac.summaries.at(-1).terminalSwitch, false, "the Clouds' terminal switch stays out of the menu without a Cloud");
+});
+
+test("a narrower pairing, a server others sign in to, a team's server or a Cloud is never asked about and is never lent", async t => {
+ for (const [what, server] of [["client scope", selfHosted({ scopes: ["client"] })], ["others sign in there", selfHosted({ own: false })], ["team", selfHosted({ extra: { team: { id: "t", role: "admin" } } })], ["Cloud", selfHosted({ extra: { cloudHome: true } })]]) {
+ const mac = await desktop(t, server);
+ assert.equal(await mac.sharing.ownServer(garage), null, what);
+ assert.equal(await mac.sharing.ownOffer(garage), false, what);
+ await assert.rejects(mac.sharing.lendOwn(garage, { computer: true }), /Only your own server can use this computer/, what);
+ await delay(30);
+ assert.equal(server.connects.length, 0, what);
+ assert.equal(mac.sharing.state(garage.id).enabled, false, what);
+ }
+});
+
+test("Not now lends nothing and this pairing is not asked again; pairing again asks again", async t => {
+ const server = selfHosted();
+ const mac = await desktop(t, server);
+ const info = await mac.sharing.ownOffer(garage);
+ mac.sharing.declineOwn(garage, info);
+ assert.equal(await mac.sharing.ownOffer(garage), null);
+ mac.restart();
+ await delay(50);
+ assert.equal(server.connects.length, 0);
+ assert.equal(mac.sharing.state(garage.id).enabled, false);
+ server.sessionId = randomUUID();
+ assert.deepEqual(await mac.sharing.ownOffer(garage), { sessionId: server.sessionId, environmentId: server.environmentId });
+});
+
+test("Stop ends it at once: the server is told, polling stops, and it stays off after the app opens again", async t => {
+ const server = selfHosted();
+ const mac = await desktop(t, server);
+ await mac.sharing.lendOwn(garage, { computer: true });
+ await until(() => server.polls > 0, "the first poll");
+ const stopped = mac.sharing.revoke(garage);
+ assert.equal(stopped.enabled, false);
+ await until(() => server.disconnects.length === 1, "the server to be told");
+ const polls = server.polls;
+ await delay(150);
+ assert.equal(server.polls, polls, "nothing polls after Stop");
+ mac.restart();
+ await delay(80);
+ assert.equal(server.connects.length, 1, "Stop lasts across restarts");
+ assert.equal(await mac.sharing.ownOffer(garage), null, "Stop is an answer too");
+});
+
+test("a new pairing of the same server keeps lending; that server getting other people, or another server behind the address, ends it", async t => {
+ const server = selfHosted();
+ const mac = await desktop(t, server);
+ await mac.sharing.lendOwn(garage, { computer: true });
+ await until(() => server.connects.length === 1, "lending to start");
+ server.sessionId = randomUUID();
+ mac.restart();
+ await until(() => server.connects.length === 2, "lending to go on after pairing again");
+ assert.equal(JSON.parse(await readFile(mac.file, "utf8")).records.garage.sessionId, server.sessionId, "bound to the new pairing");
+
+ server.own = false;
+ mac.restart();
+ await until(() => mac.sharing.state(garage.id).problem === "not-own", "lending to end");
+ assert.equal(mac.sharing.state(garage.id).enabled, false);
+ assert.equal(server.connects.length, 2, "nothing is lent to a narrower pairing");
+
+ const other = selfHosted();
+ const moved = await desktop(t, other);
+ await moved.sharing.lendOwn(garage, { computer: true });
+ await until(() => other.connects.length === 1, "lending to start");
+ other.environmentId = randomUUID();
+ moved.restart();
+ await until(() => moved.sharing.state(garage.id).problem === "machine-changed", "lending to another server to end");
+ assert.equal(other.connects.length, 1);
+});
+
+test("Pause holds a server of the person's own as it holds Clouds, across restarts, and Resume lends again", async t => {
+ const server = selfHosted();
+ const mac = await desktop(t, server);
+ await mac.sharing.lendOwn(garage, { computer: true });
+ await until(() => server.connects.length === 1, "lending to start");
+ mac.sharing.pause();
+ assert.equal(mac.sharing.state(garage.id).problem, "paused", "Pause is instant, as for a Cloud");
+ await until(() => server.disconnects.length === 1, "the server to be told");
+ assert.equal(mac.sharing.state(garage.id).paused, true);
+ assert.deepEqual({ paused: mac.summaries.at(-1).paused, clouds: mac.summaries.at(-1).clouds, lending: mac.summaries.at(-1).lending }, { paused: true, clouds: ["Garage"], lending: [] });
+ mac.restart();
+ await delay(80);
+ assert.equal(server.connects.length, 1, "still paused after the app opens again");
+ assert.equal(server.disconnects.length, 1, "nothing even dials it while paused");
+ await mac.sharing.resume();
+ await until(() => server.connects.length === 2, "Resume to lend again");
+});
+
+test("the menu-bar item keeps its Clouds' terminal switch only while a Cloud is signed in here", () => {
+ const menus = [];
+ const tray = createLendingIndicator({ Tray: class { setToolTip() {} setTitle() {} setContextMenu(menu) { menus.push(menu); } on() {} isDestroyed() { return false; } destroy() {} },
+ Menu: { buildFromTemplate: items => items }, nativeImage: { createFromPath: () => ({ resize: () => ({}) }) }, iconPath: "", onPause() {}, onResume() {}, onActivity() {}, onTerminal() {}, device: "Mac" });
+ const labels = () => menus.at(-1).map(item => item.label);
+ tray.update({ clouds: ["Garage"], terminalSwitch: false });
+ assert.deepEqual(labels(), ["Garage can use this Mac", undefined, "Pause", "See activity"]);
+ tray.update({ clouds: ["My Cloud", "Garage"], terminalSwitch: true });
+ assert.ok(labels().includes("Let Clouds run commands on this Mac"));
+});
+
+/** 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 } = {}) {
+ const handlers = new Map(), calls = { lent: [], declined: [], saved: [], revoked: [], boxes: [] };
+ const win = { isDestroyed: () => false, webContents: { getURL: () => `${GARAGE}/` } };
+ const info = { sessionId: randomUUID(), environmentId: randomUUID() };
+ const records = {};
+ const controller = {
+ state: id => records[id] ?? { enabled: false, folders: [], terminal: false, computer: false },
+ ownServer: async () => (own ? info : null),
+ 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]); },
+ revoke: env => { calls.revoked.push(env.id); records[env.id] = { ...records[env.id], enabled: false }; return records[env.id]; },
+ identity: async () => info, save: async (env, grant) => { calls.saved.push([env.id, grant]); return {}; }, observe: async () => info, decline: () => {}, activity: () => [],
+ };
+ const dialog = { showMessageBox: async (...args) => { calls.boxes.push(args.at(-1)); return { response }; } };
+ 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 });
+ 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 }]]);
+
+ const notNow = mainLending({ response: 1 });
+ await notNow.lending.offer(notNow.win);
+ assert.deepEqual(notNow.calls.lent, []);
+ assert.deepEqual(notNow.calls.declined, [["garage", notNow.info]]);
+
+ const answered = mainLending({ response: 0, offer: null });
+ await answered.lending.offer(answered.win);
+ assert.deepEqual(answered.calls.boxes, [], "a pairing already answered is never asked again");
+
+ const notOwn = mainLending({ response: 0, own: false });
+ await notOwn.lending.offer(notOwn.win);
+ assert.deepEqual(notOwn.calls.boxes, [], "another server is asked about only while the maintainer flag is on");
+ assert.deepEqual(notOwn.calls.lent, []);
+});
+
+test("Settings: each server of the person's own has the switch, which asks the same popup; turning it off needs no flag", async () => {
+ const { handlers, calls } = mainLending({ response: 0 });
+ assert.deepEqual(await handlers.get("sharing:servers")({}), [{ id: "garage", enabled: false, connected: false, paused: false }], "never the team's server");
+ assert.equal((await handlers.get("sharing:state")({}, "garage")).own, true, "its state reads without the maintainer flag");
+ const lent = await handlers.get("sharing:allow")({}, "garage");
+ assert.equal(lent.enabled, true);
+ assert.equal(calls.boxes[0].message, "Let Garage use this computer?");
+ assert.deepEqual(calls.lent, [["garage", { folders: [], terminal: false, computer: true }]]);
+ await handlers.get("sharing:save")({}, "garage", { folders: [], terminal: true, computer: true });
+ assert.deepEqual(calls.lent.at(-1), ["garage", { folders: [], terminal: true, computer: true }], "a change lends as theirs, never through the maintainer path");
+ assert.deepEqual(calls.saved, []);
+ await handlers.get("sharing:revoke")({}, "garage");
+ assert.deepEqual(calls.revoked, ["garage"]);
+
+ const declined = mainLending({ response: 1 });
+ assert.equal(await declined.handlers.get("sharing:allow")({}, "garage"), null);
+ assert.deepEqual(declined.calls.lent, []);
+
+ const other = mainLending({ own: false });
+ await assert.rejects(other.handlers.get("sharing:allow")({}, "garage"), /Only your own server/);
+ await assert.rejects(other.handlers.get("sharing:state")({}, "garage"), /turned off on this server/, "another server still needs the maintainer flag");
+ assert.deepEqual(await other.handlers.get("sharing:servers")({}), []);
+ await other.handlers.get("sharing:revoke")({}, "garage");
+ assert.deepEqual(other.calls.revoked, ["garage"], "stopping never needs a flag");
+});
diff --git a/electron/lending-dialogs.node-test.mjs b/electron/lending-dialogs.node-test.mjs
index 4a31864935..b58496957e 100644
--- a/electron/lending-dialogs.node-test.mjs
+++ b/electron/lending-dialogs.node-test.mjs
@@ -1,9 +1,8 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import test from "node:test";
-import vm from "node:vm";
import { createLendingDialogs, serverAccessDetail } from "./lending-dialogs.mjs";
+import { installServerLending } from "./server-lending.mjs";
import nativeText from "./native-text.cjs";
function fakeDialog({ response = 1, picked = { canceled: true, filePaths: [] } } = {}) {
@@ -119,25 +118,14 @@ test("a server's computer access is allowed only by the dialog's own Allow, and
assert.match(quiet[2], /^Computer control: can view your screen/);
});
-const MAIN = readFileSync(new URL("./main.mjs", import.meta.url), "utf8").replace(/\r\n/g, "\n");
-function mainSection(start, end) {
- const from = MAIN.indexOf(start), to = MAIN.indexOf(end, from);
- assert.ok(from >= 0 && to > from, `main.mjs section moved: ${start}`);
- return MAIN.slice(from, to);
-}
-
function mainSharing({ response }) {
const handlers = new Map(), saved = [], win = liveWindow();
const { dialog, calls } = fakeDialog({ response, picked: { canceled: false, filePaths: ["/Users/me/Plans"] } });
const team = { id: "team", name: "Team server", origin: "https://team.example.test" };
- const context = vm.createContext({
- createLendingDialogs, nativeT: nativeText.englishText.t, dialog, mainWindow: win, validateSharedFolders: named, isHomeFolder: async () => false,
- ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, localWorkspaceOnly: (_channel, handler) => handler,
- requireSharedComputers: async () => {}, savedWorkspace: () => team,
- sharingController: () => ({ identity: async () => ({ id: "info" }), save: async (env, grant, info) => { saved.push([env.id, grant, info]); } }),
- });
- vm.runInContext(mainSection("const lendingDialogs = createLendingDialogs(", 'ipcMain.handle("sharing:revoke"')
- + mainSection('ipcMain.handle("sharing:save"', "const cloudSync = installCloudFiles("), context);
+ const controller = { state: () => ({}), ownServer: async () => null, identity: async () => ({ id: "info" }), save: async (env, grant, info) => { saved.push([env.id, grant, info]); } };
+ installServerLending({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (_channel, handler) => handler, sharing: () => controller,
+ dialogs: createLendingDialogs({ dialog, window: () => win, validate: named, isHome: async () => false }), validate: named, dialog, window: () => win,
+ saved: () => team, candidate: () => true, flag: async () => true, environments: () => [team] });
return { handlers, saved, calls };
}
diff --git a/electron/lending-indicator.mjs b/electron/lending-indicator.mjs
index ca07b62404..1298c9d917 100644
--- a/electron/lending-indicator.mjs
+++ b/electron/lending-indicator.mjs
@@ -43,15 +43,15 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPa
...fix ? [{ label: fix, click: () => onStartScreen() }] : [],
{ type: "separator" },
view.paused ? { label: t("native.lendTray.resume"), click: () => onResume() } : { label: t("native.lendTray.pause"), click: () => onPause() },
- ...view.paused ? [] : [{ label: t("native.lendTray.terminal", { device: device === "computer" ? t("native.lendTray.computer") : device }), type: "checkbox", checked: view.terminal,
+ ...view.paused || !view.terminalSwitch ? [] : [{ label: t("native.lendTray.terminal", { device: device === "computer" ? t("native.lendTray.computer") : device }), type: "checkbox", checked: view.terminal,
// Electron 43 ticks a checkbox on click by itself: the menu keeps the saved choice until the person confirms one.
click: () => { draw(view); onTerminal(!view.terminal); } }],
{ label: t("native.lendTray.activity"), click: () => onActivity() },
]));
};
return {
- update({ clouds = [], using = [], paused = false, terminal = false, screen = null, waiting = [] }) {
- const next = { clouds: [...clouds], using: paused ? [] : [...using], waiting: paused ? [] : [...waiting], paused: paused === true, terminal: terminal === true,
+ update({ clouds = [], using = [], paused = false, terminal = false, terminalSwitch = true, screen = null, waiting = [] }) {
+ const next = { clouds: [...clouds], using: paused ? [] : [...using], waiting: paused ? [] : [...waiting], paused: paused === true, terminal: terminal === true, terminalSwitch: terminalSwitch !== false,
screen: screen ? { ready: screen.ready === true, reason: screen.reason ?? null, fix: screen.fix ?? null, ...(screen.message ? { message: screen.message } : {}) } : null };
if (shown && JSON.stringify(next) === JSON.stringify(shown)) return;
shown = next;
diff --git a/electron/main.mjs b/electron/main.mjs
index ab12407f6d..e575acb10b 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -90,7 +90,7 @@ import environmentsModule from "./environments.cjs";
import { pairingPageUrl } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs";
import localOriginModule from "./local-origin.cjs";
import { buildApplicationMenu } from "./menu.mjs";
-import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";
+import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { installServerLending } from "./server-lending.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";
import { createHostScreenLease } from "./host-screen-lease.mjs";
import { acquireDataDirLease } from "./data-dir-lease.mjs";
import { reviveAfterFailedSwitch, switchLocalEnvironment } from "./environment-switch.mjs";
@@ -1419,7 +1419,6 @@ ipcMain.on("desktop:unread-count", (event, value) => {
const { LOCAL_ID, activeEnvironment, activeRemote, allowedOrigins, bootEnvironmentDir, otherPlaces, savedPlace, startupEnvironmentDir, withActive, withEnvironment, withEnvironmentLook, withLocalEnvironment, withMicrophone, withPlaceColor, withoutEnvironment, withOwnCloud, withTeam, placesMenuOptions, workspaceMenuTemplate, workspaceNavigationAllowed, workspaceSenderAllowed, workspaceSummary, workspaceWindowTitle } = environmentsModule;
let environmentsState = { environments: [], activeId: LOCAL_ID };
let computerSharing;
-const sharingPrompts = new Set();
let sharedComputersAllowed = false;
@@ -1431,11 +1430,6 @@ async function refreshSharedComputersAllowed() {
return sharedComputersAllowed;
}
-async function requireSharedComputers() {
- if (await refreshSharedComputersAllowed()) return;
- throw new Error("Computer sharing is turned off on this server.");
-}
-
function sharingController() {
computerSharing ??= createComputerSharing({
file: path.join(app.getPath("userData"), "computer-sharing.json"),
@@ -1500,25 +1494,8 @@ function lendingIndicator() {
return lendingTray;
}
-async function offerComputerSharing(win) {
- const env = activeEnvironment(environmentsState);
- if (!env || sharingPrompts.has(env.id) || win.isDestroyed()) return;
- if (env.origin === cloudAccount?.homeTarget()?.origin || cloudAccount?.isOwnCloud(env.origin) || env.origin === ownHome?.home()?.origin) return;
- if (!(await refreshSharedComputersAllowed()) || win.isDestroyed()) return;
- sharingPrompts.add(env.id);
- try {
- const info = await sharingController().observe(env);
- if (!info || win.isDestroyed() || activeEnvironment(environmentsState)?.id !== env.id || new URL(win.webContents.getURL()).origin !== env.origin) return;
- const choice = await dialog.showMessageBox(win, {
- type: "question", message: nativeT("native.dialog.share.title", { name: env.name }),
- detail: nativeT("native.dialog.share.detail"),
- buttons: [nativeT("native.dialog.share.choose"), nativeT("native.dialog.share.notNow")], defaultId: 1, cancelId: 1,
- });
- sharingController().decline(env, info);
- if (choice.response === 0) openWorkspaceSettings(env.id);
- } catch {}
- finally { sharingPrompts.delete(env.id); }
-}
+/** A server saved by hand that no Cloud rule lends: never My Cloud, another Cloud of the person's own, a team's Cloud or the server their bots moved to. */
+const lendableServer = env => Boolean(env?.origin) && env.kind !== "local" && !env.home && !env.cloud && !env.team && env.origin !== cloudAccount?.homeTarget()?.origin && !cloudAccount?.isOwnCloud(env.origin) && env.origin !== ownHome?.home()?.origin;
function environmentsFile() {
return path.join(app.getPath("userData"), cloudTarget(process.env).environments);
@@ -2099,7 +2076,7 @@ function createWindow({ deferNavigation = false } = {}) {
deliverPackageInstall(win);
deliverChatLink(win); desktopNotifications.arrived();
});
- win.webContents.on("did-finish-load", () => void offerComputerSharing(win));
+ win.webContents.on("did-finish-load", () => void serverLending.offer(win));
// Electron has no default context menu.
win.webContents.on("context-menu", (_event, params) => {
@@ -2678,33 +2655,10 @@ const announceAddedCloud = createAddedCloudNotice({ t: nativeT, Notification, fo
installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => savedPlace(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),
setColor: (id, swatch) => ensureCloudAccount().setCloudColor(id, swatch), save: (id, color) => persistEnvironments(withPlaceColor(environmentsState, id, color)),
rail: { owns: event => chromeRail.owns(event), places: railList, saved: id => savedPlace(environmentsState, id) }, t: nativeT });
-ipcMain.handle("sharing:state", localWorkspaceOnly("sharing:state", async (_event, id) => {
- await requireSharedComputers();
- return sharingController().state(savedWorkspace(id).id);
-}));
const lendingDialogs = createLendingDialogs({ dialog, window: () => mainWindow, validate: validateSharedFolders, isHome: isHomeFolder, t: nativeT });
-ipcMain.handle("sharing:folder", localWorkspaceOnly("sharing:folder", async () => {
- await requireSharedComputers();
- return lendingDialogs.chooseFolder(nativeT("native.picker.shareFolder"));
-}));
-ipcMain.handle("sharing:revoke", localWorkspaceOnly("sharing:revoke", async (_event, id) => {
- await requireSharedComputers();
- return sharingController().revoke(savedWorkspace(id));
-}));
-// What that server's bots did here: the local log, never a server's claim.
-ipcMain.handle("sharing:activity", localWorkspaceOnly("sharing:activity", async (_event, id) => {
- await requireSharedComputers();
- return sharingController().activity(savedWorkspace(id).id, 50);
-}));
-ipcMain.handle("sharing:save", localWorkspaceOnly("sharing:save", async (_event, id, input) => {
- await requireSharedComputers();
- const env = savedWorkspace(id);
- const info = await sharingController().identity(env);
- const grant = { folders: await validateSharedFolders(input?.folders), terminal: input?.terminal === true, computer: input?.computer === true };
- if (!(await lendingDialogs.confirmServerAccess(env, grant))) return null;
- savedWorkspace(id);
- return sharingController().save(env, grant, info);
-}));
+// 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 });
const cloudSync = installCloudFiles({ t: nativeT,
app, ipcMain, dialog, shell, powerMonitor, localWorkspaceOnly, localDataDir: desktopDataDir(),
diff --git a/electron/place-look.node-test.mjs b/electron/place-look.node-test.mjs
index 07d835a713..72e7850933 100644
--- a/electron/place-look.node-test.mjs
+++ b/electron/place-look.node-test.mjs
@@ -92,7 +92,7 @@ test("a page changes only its own place's colour: a Cloud's on the Admin first,
test("main's own wiring: This computer's page reads and changes its own colour, kept with this app's saved places, no Admin asked", async () => {
const source = readFileSync(new URL("./main.mjs", import.meta.url), "utf8").replace(/\r\n/g, "\n");
- const start = source.indexOf("installPlaceLook({ ipcMain, guard: workspaceOnly"), end = source.indexOf('ipcMain.handle("sharing:state"', start);
+ const start = source.indexOf("installPlaceLook({ ipcMain, guard: workspaceOnly"), end = source.indexOf("const lendingDialogs = createLendingDialogs(", start);
assert.ok(start >= 0 && end > start, "main installs the colour's channels");
const handlers = new Map(), persisted = [];
const context = vm.createContext({ installPlaceLook, nativeT: nativeText.englishText.t, savedPlace: environments.savedPlace, withPlaceColor: environments.withPlaceColor,
diff --git a/electron/preload.cjs b/electron/preload.cjs
index c500daba44..da01c30ac1 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -635,6 +635,10 @@ const bridge = {
save: (id, grant) => ipcRenderer.invoke("sharing:save", id, grant),
revoke: id => ipcRenderer.invoke("sharing:revoke", id),
activity: id => ipcRenderer.invoke("sharing:activity", id),
+ servers: () => ipcRenderer.invoke("sharing:servers"),
+ allow: id => ipcRenderer.invoke("sharing:allow", id),
+ pause: () => ipcRenderer.invoke("sharing:pause"),
+ resume: () => ipcRenderer.invoke("sharing:resume"),
},
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
diff --git a/electron/server-lending.mjs b/electron/server-lending.mjs
new file mode 100644
index 0000000000..fcbc7d2b74
--- /dev/null
+++ b/electron/server-lending.mjs
@@ -0,0 +1,120 @@
+// 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.
+import nativeText from "./native-text.cjs";
+
+const OWN_CHECK_MS = 30_000;
+
+/**
+ * `sharing()`: the computer-sharing controller, made when first needed. `validate`: computer-sharing.mjs
+ * 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.
+ */
+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 = () => {} }) {
+ 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 => {
+ if (!candidate(env)) return false;
+ if (sharing().state(env.id).own === true) return true;
+ const hit = checked.get(env.id);
+ if (hit && hit.origin === env.origin && now() - hit.at < OWN_CHECK_MS) return hit.own;
+ const answer = Boolean(await sharing().ownServer(env));
+ checked.set(env.id, { at: now(), origin: env.origin, own: answer });
+ return answer;
+ };
+ const requireOwnOrFlag = async env => {
+ if (await own(env)) return true;
+ if (await flag()) return false;
+ throw new Error("Computer sharing is turned off on this server.");
+ };
+ /** The one question, the same after pairing and from Settings' switch. */
+ const allows = async (env, parent = window()) => {
+ const options = { type: "question", message: t("native.lend.own.title", { name: env.name }), detail: t("native.lend.own.detail"),
+ buttons: [t("native.lend.own.allow"), t("native.dialog.share.notNow")], defaultId: 1, cancelId: 1 };
+ return (await (parent ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options))).response === 0;
+ };
+ /** Allow lends the apps on the screen now; folders and the terminal are chosen in Settings. */
+ const firstGrant = { folders: [], terminal: false, computer: true };
+
+ ipcMain.handle("sharing:state", guard("sharing:state", async (_event, id) => {
+ const env = saved(id);
+ const mine = await requireOwnOrFlag(env);
+ return { ...sharing().state(env.id), ...(mine ? { own: true } : {}) };
+ }));
+ // Picking a folder lends nothing by itself: a save does, and is checked there.
+ ipcMain.handle("sharing:folder", guard("sharing:folder", () => dialogs.chooseFolder(t("native.picker.shareFolder"))));
+ ipcMain.handle("sharing:revoke", guard("sharing:revoke", (_event, id) => sharing().revoke(saved(id))));
+ // What that server's bots did here: the local log, never a server's claim.
+ ipcMain.handle("sharing:activity", guard("sharing:activity", async (_event, id) => {
+ const env = saved(id);
+ await requireOwnOrFlag(env);
+ return sharing().activity(env.id, 50);
+ }));
+ ipcMain.handle("sharing:save", guard("sharing:save", async (_event, id, input) => {
+ const env = saved(id);
+ const mine = await requireOwnOrFlag(env);
+ const info = mine ? null : await sharing().identity(env);
+ const grant = { folders: await validate(input?.folders), terminal: input?.terminal === true, computer: input?.computer === true };
+ if (!(await dialogs.confirmServerAccess(env, grant))) return null;
+ saved(id);
+ return mine ? sharing().lendOwn(env, grant) : sharing().save(env, grant, info);
+ }));
+ /** Settings → Servers: each server of the person's own, and how lending to it is. */
+ ipcMain.handle("sharing:servers", guard("sharing:servers", async () => {
+ const places = environments().filter(env => env.kind !== "local" && env.origin && candidate(env));
+ const mine = await Promise.all(places.map(env => own(env).catch(() => false)));
+ return places.filter((_env, index) => mine[index]).map(env => {
+ const { enabled, connected, paused } = sharing().state(env.id);
+ return { id: env.id, enabled: enabled === true, connected: connected === true, paused: paused === true };
+ });
+ }));
+ /** Settings' switch turned on: the same popup, then what Allow lends. */
+ ipcMain.handle("sharing:allow", guard("sharing:allow", async (_event, id) => {
+ const env = saved(id);
+ if (!(await own(env))) throw new Error(t("native.lend.notOwnServer"));
+ if (!(await allows(env))) return null;
+ return sharing().lendOwn(env, firstGrant);
+ }));
+ ipcMain.handle("sharing:pause", guard("sharing:pause", () => { sharing().pause(); }));
+ ipcMain.handle("sharing:resume", guard("sharing:resume", async () => { await sharing().resume(); }));
+
+ const asking = new Set();
+ /** Still on that server: the person may have gone elsewhere while the server answered. */
+ const showing = (win, env) => {
+ if (win.isDestroyed() || active()?.id !== env.id) return false;
+ 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. */
+ async offer(win) {
+ const env = active();
+ if (!env || asking.has(env.id) || win.isDestroyed() || !candidate(env)) return;
+ asking.add(env.id);
+ 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);
+ return;
+ }
+ if (!(await flag()) || win.isDestroyed()) return;
+ const seen = await sharing().observe(env);
+ if (!seen || !showing(win, env)) return;
+ const choice = await dialog.showMessageBox(win, {
+ type: "question", message: t("native.dialog.share.title", { name: env.name }), detail: t("native.dialog.share.detail"),
+ buttons: [t("native.dialog.share.choose"), t("native.dialog.share.notNow")], defaultId: 1, cancelId: 1,
+ });
+ sharing().decline(env, seen);
+ if (choice.response === 0) openSettings(env.id);
+ } catch (error) { log(`computer sharing offer: ${error?.message ?? error}`); }
+ finally { asking.delete(env.id); }
+ },
+ };
+}
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 9c2319c5ef..3f1d4bdda4 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -103,6 +103,7 @@ export const VITEST_SUBSETS = {
"server/parked-cards.e2e.test.ts",
"server/question-cards.e2e.test.ts",
"server/shared-computers.e2e.test.ts",
+ "server/shared-computers.gate.test.ts",
"server/team-move.e2e.test.ts",
"server/use-my-mac.e2e.test.ts",
"server/workspace-banner.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index f799cfb39d..74a10ac87a 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -240,6 +240,7 @@ describe("CI outputs", () => {
"server/parked-cards.e2e.test.ts",
"server/question-cards.e2e.test.ts",
"server/shared-computers.e2e.test.ts",
+ "server/shared-computers.gate.test.ts",
"server/team-move.e2e.test.ts",
"server/use-my-mac.e2e.test.ts",
"server/workspace-banner.e2e.test.ts",
diff --git a/server/config.ts b/server/config.ts
index f1c8f41d52..d6da25abb7 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -674,10 +674,10 @@ export function builtInBrowserEnabled(cfg: AppConfig, _env: NodeJS.ProcessEnv =
return cfg.features?.browser !== false;
}
-/** Security: off unless true because a read-only folder grant can still be escalated to a shell. */
-export function sharedComputersEnabled(cfg: AppConfig): boolean {
- return cfg.features?.sharedComputers === true;
-}
+/** Security: every paired session may lend its computer only when true, because a read-only folder grant can still be escalated to a shell. */
+export function sharedComputersEnabled(cfg: AppConfig): boolean { return cfg.features?.sharedComputers === true; }
+/** A self-hosted server's own admin pairings may lend their computer unless this is false (each desktop asks its person first). */
+export function ownerLendingEnabled(cfg: AppConfig): boolean { return cfg.features?.sharedComputers !== false; }
export function claudeUserMcpEnabled(cfg: Pick<AppConfig, "features">): boolean {
return cfg.features?.claudeUserMcp === true;
diff --git a/server/environment.ts b/server/environment.ts
index a878a943d8..abaf318e54 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -157,6 +157,10 @@ export function serverInstall(env: NodeJS.ProcessEnv = process.env, script = pro
return prefix === "npx openmausbot" ? "npx" : "global";
}
+/** What a server only its one owner signs in to takes from that owner's own desktop by default: told in the owner's own
+ * /api/auth/session answer, never in the description anyone may read before pairing. */
+export const OWNER_LENDING = Object.freeze({ sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true } as const);
+
export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; sharedComputers?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor {
return {
environmentId: input.environmentId,
diff --git a/server/index.ts b/server/index.ts
index 79b629aad5..3ba2072fd0 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -172,7 +172,7 @@ import {
captureQuietMs,
roomMemoryCaptureEnabled,
tidyHour,
- sharedComputersEnabled,
+ sharedComputersEnabled, ownerLendingEnabled,
builtInBrowserEnabled,
persistableInstanceConfigs,
type AppConfig,
@@ -523,7 +523,7 @@ import {
import { createGracefulShutdown } from "./graceful-shutdown.ts";
import { acquireDataDirLeaseForProcess } from "./data-dir-lease.ts";
import { createWorkspaceAccess, describeEdition, editionForSettings, editionStatus, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer, workspaceMembership, type WorkspaceAccess } from "./enterprise.ts";
-import { environmentDescriptor, loadEnvironmentId, serverVersion } from "./environment.ts";
+import { environmentDescriptor, loadEnvironmentId, OWNER_LENDING, serverVersion } from "./environment.ts";
import { WorkspaceBackupMaintenance } from "./workspace-backup-maintenance.ts";
import { createWorkspaceBackupRoutes, isWorkspaceBackupSessionControl } from "./workspace-backup-http.ts";
import { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRestoreResult } from "./workspace-backup.ts";
@@ -699,7 +699,7 @@ const CLOUD_TEAM = CLOUD_HOME?.team ?? null, CLOUD_PERSONAL = CLOUD_HOME !== nul
const appLanguage = (): string | undefined => cfg.language ?? CLOUD_TEAM?.language; const personLanguages = createPersonLanguages({ dataDir: DATA_DIR, configured: appLanguage, privateTo: (threadId) => teamHost.privateTo(threadId) }); const threadLanguage = personLanguages.forThread; setConversationLanguage(threadLanguage);
if (CLOUD_HOME) repairMovedWorkspacePaths(DATA_DIR);
if (CLOUD_PERSONAL) sessions.requireAdmin(userError("serverError.cloud.personal"));
-const lendingEnabled = () => sharedComputersEnabled(cfg) || CLOUD_HOME !== null || ownHome.here();
+const lendingEnabled = () => sharedComputersEnabled(cfg) || CLOUD_HOME !== null || ownHome.here(); const ownerLends = () => ownerLendingEnabled(cfg) && ownHome.takesMove(); const botLending = () => lendingEnabled() || (ownerLends() && sharedComputers.anyLent()); // ownerLends: a server only its one owner signs in to (own-home.ts) takes that owner's computer by default, never anyone else's (routes/shared-computers.ts); the desktop asks its person first, and the public description stays as it was.
const CLOUD_HOME_LENDER = "cloud-home";
/** Owner-written routines and owner-started runs: the only routine turns that may use a lent Mac. */
const cloudRoutineAuthors = CLOUD_HOME ? createCloudRoutineAuthors(join(DATA_DIR, "lending-routines.json")) : null;
@@ -1837,7 +1837,7 @@ function agentsIntegration(
) {
const bot = store.bot(botId), speaking = botForThread(botId, threadId) ?? bot;
// Only advertises the tools; the routes behind them refuse regardless.
- const host = { skillAuthoring: skillAuthoringEnabled(cfg), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM), escalations: chiefEscalationsEnabled(cfg),
+ const host = { skillAuthoring: skillAuthoringEnabled(cfg), sharedComputers: botLending(), cloudHome: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM), escalations: chiefEscalationsEnabled(cfg),
voiceNotes: tts.voiceReady(cfg, speaking?.voice) && speaking?.voiceNotes !== false, x: Boolean(researchCredential(cfg.treg?.key)), research: researchAvailability.available(), imageGeneration: imageGenerationReady(cfg), meetings: boat.boatConfigured(cfg) };
return { ...agentsProxyLaunch(), env: agentsServerEnv({ threadId, bot: bot ?? { id: botId }, room: Boolean(store.groupByThread(threadId)), teamComputer: Boolean(bot && inheritedTeamComputer(bot)), host },
{ generation, depth, skillAuthoring, roomHandoffId, ...(hostFiles && !CLOUD_HOME && !HOSTED_WORKSPACE ? { deliversSavedFiles: true } : {}) },
@@ -2840,7 +2840,7 @@ const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, stor
const routineHolds = CLOUD_HOME ? createRoutineHoldsHost({ dataDir: DATA_DIR, store, mcpServers: () => Object.keys(cfg.mcpServers ?? {}).length, log: (line) => console.warn(line),
appsConnected: async () => composio.configured(cfg) ? Object.values(await composio.connectedServices(cfg)).some((service) => service.connected) : false }) : null;
const skillsHost = createSkillsLibraryHost({ store, cfg, appendSkillRequestCard, engineConfig: (instanceId) => providerConfigs()[instanceId], instanceOf: (instanceId) => { const instance = registry.get(instanceId); return instance ? { instanceId, driverKind: instance.driverKind } : undefined; } });
-const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, heldKeys, dataDir: DATA_DIR, email: { accounts: () => emailService.store.list(), adopt: (accounts) => emailService.adopt(accounts) }, stayedNotices: { bots: () => store.bots, language: (threadId) => threadLanguage(threadId), say: (threadId, text, kind) => { store.appendMessage(threadId, kind === "line" ? { role: "bot", kind: "text", text } : { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok: true } }); }, notify: (text, bot, threadId) => notify(buildNoticeNotification(bot, threadId, text)), lent: (runsOn) => { const at = sharedComputers.runsOn(CLOUD_HOME_LENDER, runsOn); return Boolean(at.online ?? at.known?.lent); } }, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) }); const lentMcp = createLentMcp({ cfg: () => cfg, computers: sharedComputers, policy: (servers) => managedPolicy.filterMcp(servers), bot: (id) => store.bot(id), principal: (turn) => (CLOUD_TEAM || !lendingEnabled() ? null : sharedComputerPrincipal(turn)), notice: (turn) => (CLOUD_HOME ? cloudLendingRefusalNotice(turn) : null), refusal: (turn) => (CLOUD_HOME ? cloudLendingRefusalForBot(turn) : null), mint: (turn) => mintInternalCapability({ ...turn, kind: "lent", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), active: (turn) => activeInternalGenerationByThread.get(turn.threadId) === turn.generation, origin: `http://127.0.0.1:${PORT}`, personal: CLOUD_PERSONAL, place: CLOUD_HOME ? "My Cloud" : "this server" }); // Security: a team Cloud lends nothing, so nobody's own computer serves its bots.
+const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, heldKeys, dataDir: DATA_DIR, email: { accounts: () => emailService.store.list(), adopt: (accounts) => emailService.adopt(accounts) }, stayedNotices: { bots: () => store.bots, language: (threadId) => threadLanguage(threadId), say: (threadId, text, kind) => { store.appendMessage(threadId, kind === "line" ? { role: "bot", kind: "text", text } : { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok: true } }); }, notify: (text, bot, threadId) => notify(buildNoticeNotification(bot, threadId, text)), lent: (runsOn) => { const at = sharedComputers.runsOn(CLOUD_HOME_LENDER, runsOn); return Boolean(at.online ?? at.known?.lent); } }, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) }); const lentMcp = createLentMcp({ cfg: () => cfg, computers: sharedComputers, policy: (servers) => managedPolicy.filterMcp(servers), bot: (id) => store.bot(id), principal: (turn) => (CLOUD_TEAM || !botLending() ? null : sharedComputerPrincipal(turn)), notice: (turn) => (CLOUD_HOME ? cloudLendingRefusalNotice(turn) : null), refusal: (turn) => (CLOUD_HOME ? cloudLendingRefusalForBot(turn) : null), mint: (turn) => mintInternalCapability({ ...turn, kind: "lent", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), active: (turn) => activeInternalGenerationByThread.get(turn.threadId) === turn.generation, origin: `http://127.0.0.1:${PORT}`, personal: CLOUD_PERSONAL, place: CLOUD_HOME ? "My Cloud" : "this server" }); // Security: a team Cloud lends nothing, so nobody's own computer serves its bots.
const emailHost = createEmailHost({ service: emailService, dataDir: DATA_DIR, bot: (id) => store.bot(id), inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); }, appAllowed: () => managedPolicy.appAllowed("email"), onChange: (listener) => store.onChange(listener as never), markOutside: (threadId) => outsideLineage.mark(threadId) });
const phones = createPhones({
dataDir: DATA_DIR, shared: Boolean(HOSTED_WORKSPACE || CLOUD_TEAM), cloudHome: Boolean(CLOUD_HOME), cloudOwnerKey: CLOUD_OWNER_KEY,
@@ -12118,7 +12118,7 @@ const cloudMoveRoutes = createCloudMoveRoutes();
ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") })); ROUTES.push(createStopLineRoutes());
const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();
ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) }));
-ROUTES.push(createSharedComputerRoutes({ enabled: lendingEnabled, computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,
+ROUTES.push(createSharedComputerRoutes({ enabled: (auth) => lendingEnabled() || (ownerLends() && ownHome.owner(auth)), computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,
cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey, power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades, asks: computerAsks?.asks ?? null, answerer: cardAnswererFor }));
// `routines` is assigned at boot, so it is read per request.
ROUTES.push(createBotMessageRoutes({
@@ -12402,7 +12402,7 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persi
sharedComputers, sharedComputerControl, closeBrowser, browserEngineSwitched,
hostedModels: Boolean(hostedModels),
cloudHome: Boolean(CLOUD_HOME),
- lendingEnabled, providerConfigs, localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy,
+ lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy,
localVmImageBusy: { get: () => localVmImageBusy },
localVmModeChangeBusy: { set: (busy) => { localVmModeChangeBusy = busy; } },
providerConfigBusy: { get: () => providerConfigBusy, set: (busy) => { providerConfigBusy = busy; } },
@@ -12770,7 +12770,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
...(auth.session.email ? { email: auth.session.email } : {}),
...(auth.session.owner ? { owner: auth.session.owner } : {}),
...(HOSTED_WORKSPACE ? { hosted: true } : {}),
- ...(CLOUD_HOME ? { cloudHome: true } : {}), ...(ownHome.owner(auth) ? { own: true } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),
+ ...(CLOUD_HOME ? { cloudHome: true } : {}), ...(ownHome.owner(auth) ? { own: true, ...(ownerLends() ? { lending: OWNER_LENDING } : {}) } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),
...(CLOUD_PERSONAL && !cloudOwnerSession(auth) ? { cloudGuest: true, openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),
...(reactorFor(auth).by !== "user" ? { reactor: reactorFor(auth).by } : {}),
},
@@ -13215,15 +13215,15 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, 200, { claimed: true });
}
// Off: a 404 like a route that never existed. On: a turn sees only the computers of the person it provably acts for.
- if (method === "GET" && path === "/api/internal/shared-computers" && lendingEnabled()) {
+ if (method === "GET" && path === "/api/internal/shared-computers" && botLending()) {
const principal = sharedComputerPrincipal(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), say: why } : {}) });
}
- if (method === "POST" && path === "/api/internal/shared-computers" && lendingEnabled()) {
+ if (method === "POST" && path === "/api/internal/shared-computers" && botLending()) {
const parsed = sharedComputerOperation.safeParse(await readInternalBody());
- if (!lendingEnabled()) return json(res, 404, { error: "unknown internal endpoint" });
+ if (!botLending()) return json(res, 404, { error: "unknown internal endpoint" });
if (!parsed.success) return json(res, 400, { error: "Invalid shared computer operation" });
// The bot's own "no computer" setting holds on a lent screen too.
if (["computer_tools", "computer_call"].includes(parsed.data.action) && store.bot(internalCapability.botId)?.computer === "off") {
@@ -13232,7 +13232,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const principal = sharedComputerPrincipal(internalCapability);
const why = (CLOUD_TEAM ? managedPolicy.computerRefusal("thisComputer") : null) ?? (CLOUD_HOME && !principal ? cloudLendingRefusalForBot(internalCapability) : null);
if (why) return json(res, 403, { error: why });
- return json(res, 200, { result: lentScreenResult(parsed.data, await sharedComputers.request(parsed.data, principal, () => lendingEnabled() && internalCapabilityIsActive(internalCapability))) });
+ return json(res, 200, { result: lentScreenResult(parsed.data, await sharedComputers.request(parsed.data, principal, () => botLending() && internalCapabilityIsActive(internalCapability))) });
}
if (method === "GET" && path === "/api/internal/agents") {
const sender = internalSender;
diff --git a/server/lent-computers.ts b/server/lent-computers.ts
index ba2478c639..82d1c475e7 100644
--- a/server/lent-computers.ts
+++ b/server/lent-computers.ts
@@ -109,6 +109,9 @@ export class LentComputers {
this.save();
}
+ /** Anyone's computer is still lent (online or away). */
+ any(): boolean { return this.computers.some((computer) => computer.stoppedAt === null); }
+
list(person: string | null): LentComputer[] {
if (!person) return [];
return this.computers.filter((computer) => computer.person === person).sort((a, b) => b.lastSeenAt - a.lastSeenAt);
diff --git a/server/own-home.e2e.test.ts b/server/own-home.e2e.test.ts
index 0faa4847e5..08ddeeabdb 100644
--- a/server/own-home.e2e.test.ts
+++ b/server/own-home.e2e.test.ts
@@ -155,6 +155,9 @@ it("this computer then works for Garage server by itself, and never for the serv
expect(sharing.cloudState(garage.place)).toMatchObject({ enabled: true, terminal: false });
expect(sharing.state(family.place.id).enabled).toBe(false);
expect((await family.as("GET", "/api/shared-computers")).status, "nothing is lent where others sign in").not.toBe(200);
+ expect(await sharing.ownServer(family.place), "a server others sign in to is never offered as the person's own").toBeNull();
+ await expect(sharing.lendOwn(family.place, { computer: true })).rejects.toThrow();
+ expect((await family.as("GET", "/api/auth/session")).body, "nor told what it would take").not.toHaveProperty("lending");
// Pause: Garage server stops using this computer, until Resume.
sharing.pause();
await expect.poll(async () => ((await garage.as("GET", "/api/shared-computers")).body?.computers ?? []).filter((computer: { online?: boolean; connected?: boolean }) => computer.online !== false && computer.connected !== false).length,
diff --git a/server/routes/shared-computers.ts b/server/routes/shared-computers.ts
index 5e307e4486..f258c9e319 100644
--- a/server/routes/shared-computers.ts
+++ b/server/routes/shared-computers.ts
@@ -13,7 +13,8 @@ import type { Upgrades } from "./upgrades.ts";
const LINK = /^\/api\/shared-computers\/([\w-]+)\/link$/;
export function createSharedComputerRoutes(deps: {
- enabled: () => boolean;
+ /** For this request: the maintainer flag, a Cloud home or a moved home; or, on a server only its one owner signs in to, that owner. */
+ enabled: (auth: RequestAuth) => boolean;
computers: SharedComputers;
sessionLive: (id: string) => boolean;
environmentId: string;
@@ -33,11 +34,11 @@ export function createSharedComputerRoutes(deps: {
deps.upgrades.route((path) => LINK.test(path));
return async ({ req, res, path, method, auth, json, readBody }: RouteContext): Promise<typeof PASS | void> => {
if (path !== "/api/shared-computers" && !path.startsWith("/api/shared-computers/")) return PASS;
- if (method === "GET" && path === "/api/shared-computers" && deps.enabled()) {
+ if (method === "GET" && path === "/api/shared-computers" && deps.enabled(auth)) {
return json(res, 200, { computers: deps.computers.status(deps.principal(auth)), known: deps.computers.known(deps.principal(auth)) });
}
const link = LINK.exec(path);
- if (link && method === "GET" && deps.enabled() && deps.links) {
+ if (link && method === "GET" && deps.enabled(auth) && deps.links) {
const pending = deps.upgrades.pending(req);
if (!pending) return json(res, 426, { error: "WebSocket upgrade required" });
if (auth.kind !== "session") return json(res, 403, { error: "Pair this desktop first" });
@@ -49,11 +50,11 @@ export function createSharedComputerRoutes(deps: {
res.detachSocket(pending.socket);
return;
}
- if (method !== "POST" || path === "/api/shared-computers" || !deps.enabled()) return PASS;
+ if (method !== "POST" || path === "/api/shared-computers" || !deps.enabled(auth)) return PASS;
if (auth.kind !== "session") return json(res, 403, { error: "Pair this desktop first" });
if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) return json(res, 415, { error: "JSON required" });
const body = await readBody(req, 4_000_000);
- if (!deps.enabled()) return json(res, 404, { error: `no route: ${method} ${path}` });
+ if (!deps.enabled(auth)) return json(res, 404, { error: `no route: ${method} ${path}` });
if (!deps.sessionLive(auth.session.id)) return json(res, 401, { error: "Session ended" });
const secret = String(req.headers["x-omb-computer-secret"] ?? "");
if (path === "/api/shared-computers/connect") {
diff --git a/server/shared-computers.gate.test.ts b/server/shared-computers.gate.test.ts
index 72df37c80d..66edecf832 100644
--- a/server/shared-computers.gate.test.ts
+++ b/server/shared-computers.gate.test.ts
@@ -3,7 +3,10 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
-import { afterAll, beforeAll, expect, it } from "vitest";
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+
+import { createComputerSharing } from "../electron/computer-sharing.mjs";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { freePortBlock } from "./testing/ports.ts";
@@ -22,10 +25,10 @@ let botId = "";
interface ApiResult { status: number; body: Record<string, unknown> }
-const api = async (method: string, path: string, body?: unknown): Promise<ApiResult> => {
+const api = async (method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<ApiResult> => {
const res = await fetch(`${BASE}${path}`, {
method,
- headers: { origin: BASE, ...(body === undefined ? {} : { "content-type": "application/json" }) },
+ headers: { origin: BASE, ...(body === undefined ? {} : { "content-type": "application/json" }), ...headers },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
const parsed: unknown = await res.json().catch(() => ({}));
@@ -99,7 +102,100 @@ afterAll(async () => {
await removeTempDir(home);
});
-it("answers every shared-computer route the way a route this build never had answers", async () => {
+/** A session paired with these scopes: admin and client is the owner's "everything" code, client alone a narrower one. */
+async function paired(scopes: string[]): Promise<{ token: string; id: string }> {
+ const opened = await api("POST", "/api/auth/pairing", { label: `Desktop ${scopes.join("+")}`, scopes });
+ expect(opened.status).toBe(200);
+ const pair = (await api("POST", "/api/auth/pair", { code: opened.body.code })).body as { token: string; session: { id: string } };
+ expect(pair.token).toMatch(/^omb_sess_/);
+ return { token: pair.token, id: pair.session.id };
+}
+const bearer = (token: string) => ({ authorization: `Bearer ${token}` });
+const registration = async () => ({ id: randomUUID(), name: "Fixture Mac", environmentId: (await api("GET", "/.well-known/openmausbot/environment")).body.environmentId, folders: [], terminal: false, computer: true });
+const connectAs = async (token: string) => api("POST", "/api/shared-computers/connect", await registration(), { ...bearer(token), "x-omb-computer-secret": "a".repeat(64) });
+
+/** The desktop's own lending, signed in to this server with `token` as its pairing. */
+function desktop(token: string) {
+ const env = { id: "own-server", name: "Gate server", origin: BASE };
+ const sharing = createComputerSharing({
+ file: join(home, `desktop-${randomUUID()}`, "computer-sharing.json"), environments: () => [env], cuaConnection: async () => null, enabled: async () => false,
+ fetch: (url: string, init: RequestInit) => fetch(url, { ...init, headers: { ...(init.headers as Record<string, string>), ...bearer(token) } }),
+ });
+ return { env, sharing };
+}
+
+it("before pairing, a server describes no lending and answers every shared-computer route the way a route this build never had answers", async () => {
+ expect(await descriptorCapabilities()).not.toHaveProperty("sharedComputers");
+ const absent = await api("POST", "/api/not-a-feature/connect");
+ expect(absent).toEqual({ status: 404, body: { error: "no route: POST /api/not-a-feature/connect" } });
+ for (const path of PUBLIC_ROUTES) expect(await api("POST", path, {}), path).toEqual({ status: 404, body: { error: `no route: POST ${path}` } });
+ expect(await api("GET", "/api/shared-computers")).toEqual({ status: 404, body: { error: "no route: GET /api/shared-computers" } });
+});
+
+it("while nothing is lent, the bot-facing route hides behind the unknown-endpoint answer", async () => {
+ expect(await internal("GET", "/api/internal/not-a-feature")).toEqual({ status: 404, body: { error: "unknown internal endpoint" } });
+ expect(await internal("GET", "/api/internal/shared-computers")).toEqual({ status: 404, body: { error: "unknown internal endpoint" } });
+ expect(await internal("POST", "/api/internal/shared-computers", { computer_id: "x", action: "list_files" })).toEqual({ status: 404, body: { error: "unknown internal endpoint" } });
+});
+
+it("on a server only its owner signs in to, only the owner's pairing hears what it takes and may lend; a narrower pairing is refused", async () => {
+ const member = await paired(["client"]);
+ expect((await api("GET", "/api/auth/session", undefined, bearer(member.token))).body).not.toHaveProperty("lending");
+ expect(await connectAs(member.token)).toEqual({ status: 403, body: { error: "forbidden: this session lacks the admin scope" } });
+ const owner = await paired(["admin", "client"]);
+ expect((await api("GET", "/api/auth/session", undefined, bearer(owner.token))).body).toMatchObject({ own: true, lending: { sharedComputers: true, lentMcp: true } });
+ expect((await connectAs(owner.token)).status).toBe(200);
+ expect(await descriptorCapabilities(), "the public description stays as it was").not.toHaveProperty("sharedComputers");
+});
+
+it("the desktop lends to a server of the person's own once they allow it, with no maintainer flag anywhere, and Stop ends it at once", async () => {
+ const owner = await paired(["admin", "client"]);
+ const { env, sharing } = desktop(owner.token);
+ try {
+ expect(await sharing.ownServer(env)).toMatchObject({ sessionId: owner.id });
+ const offered = await sharing.ownOffer(env);
+ expect(offered).toMatchObject({ sessionId: owner.id });
+ const lent = await sharing.lendOwn(env, { computer: true });
+ expect(lent).toMatchObject({ enabled: true, own: true, computer: true, terminal: false, folders: [] });
+ const listed = async () => ((await api("GET", "/api/shared-computers", undefined, bearer(owner.token))).body.computers ?? []) as Array<{ online: boolean; scopes: { screen: boolean; terminal: boolean } }>;
+ await vi.waitFor(async () => expect((await listed()).some((computer) => computer.online && computer.scopes.screen && !computer.scopes.terminal)).toBe(true), { timeout: 15_000 });
+ expect(await sharing.ownOffer(env), "answered for this pairing: not asked again").toBeNull();
+ expect((await internal("GET", "/api/internal/shared-computers")).status, "the bots' route once a computer is lent").toBe(200);
+ sharing.revoke(env);
+ await vi.waitFor(async () => expect((await listed()).some((computer) => computer.online)).toBe(false), { timeout: 15_000 });
+ } finally { sharing.close(); }
+});
+
+it("a narrower pairing is never a server of the person's own: no popup, and nothing is lent", async () => {
+ const member = await paired(["client"]);
+ const { env, sharing } = desktop(member.token);
+ try {
+ expect(await sharing.ownServer(env)).toBeNull();
+ expect(await sharing.ownOffer(env)).toBe(false);
+ await expect(sharing.lendOwn(env, { computer: true })).rejects.toThrow(/Only your own server can use this computer/);
+ } finally { sharing.close(); }
+});
+
+it("features.sharedComputers true brings the whole surface back, for every paired session", async () => {
+ expect((await api("PATCH", "/api/config", { features: { sharedComputers: true } })).status).toBe(200);
+ expect((await api("GET", "/api/config")).body.features).toMatchObject({ sharedComputers: true });
+
+ const connect = await api("POST", "/api/shared-computers/connect", {});
+ expect(connect.status).toBe(403);
+ expect(connect.body).toEqual({ error: "Pair this desktop first" });
+
+ const listed = await internal("GET", "/api/internal/shared-computers");
+ expect(listed.status).toBe(200);
+ expect(listed.body).toEqual({ computers: [] });
+ expect(await api("GET", "/api/shared-computers")).toEqual({ status: 200, body: { computers: [], known: [] } });
+
+ expect(await descriptorCapabilities()).toMatchObject({ sharedComputers: true });
+ expect((await connectAs((await paired(["client"])).token)).status).toBe(200);
+});
+
+// Last: turning it off ends lending on this server until it restarts (routes/config.ts).
+it("features.sharedComputers false turns it all off: every route answers the way a route this build never had answers", async () => {
+ expect((await api("PATCH", "/api/config", { features: { sharedComputers: false } })).status).toBe(200);
// The control: a path with no handler anywhere in the server.
const absent = await api("POST", "/api/not-a-feature/connect");
expect(absent.status).toBe(404);
@@ -111,9 +207,10 @@ it("answers every shared-computer route the way a route this build never had ans
expect(gated.body, path).toEqual({ error: `no route: POST ${path}` });
}
expect(await api("GET", "/api/shared-computers")).toEqual({ status: 404, body: { error: "no route: GET /api/shared-computers" } });
+ expect(await descriptorCapabilities()).not.toHaveProperty("sharedComputers");
});
-it("hides the bot-facing route behind the same unknown-endpoint answer", async () => {
+it("with it off, the bot-facing route hides behind the same unknown-endpoint answer", async () => {
const control = await internal("GET", "/api/internal/not-a-feature");
expect(control.status).toBe(404);
expect(control.body).toEqual({ error: "unknown internal endpoint" });
@@ -126,23 +223,3 @@ it("hides the bot-facing route behind the same unknown-endpoint answer", async (
expect(used.status).toBe(404);
expect(used.body).toEqual({ error: "unknown internal endpoint" });
});
-
-it("advertises no sharedComputers capability while the gate is off", async () => {
- expect(await descriptorCapabilities()).not.toHaveProperty("sharedComputers");
-});
-
-it("brings the whole surface back when features.sharedComputers is turned on", async () => {
- expect((await api("PATCH", "/api/config", { features: { sharedComputers: true } })).status).toBe(200);
- expect((await api("GET", "/api/config")).body.features).toMatchObject({ sharedComputers: true });
-
- const connect = await api("POST", "/api/shared-computers/connect", {});
- expect(connect.status).toBe(403);
- expect(connect.body).toEqual({ error: "Pair this desktop first" });
-
- const listed = await internal("GET", "/api/internal/shared-computers");
- expect(listed.status).toBe(200);
- expect(listed.body).toEqual({ computers: [] });
- expect(await api("GET", "/api/shared-computers")).toEqual({ status: 200, body: { computers: [], known: [] } });
-
- expect(await descriptorCapabilities()).toMatchObject({ sharedComputers: true });
-});
diff --git a/server/shared-computers.ts b/server/shared-computers.ts
index f1ad76e42e..b410f42bae 100644
--- a/server/shared-computers.ts
+++ b/server/shared-computers.ts
@@ -205,6 +205,8 @@ export class SharedComputers {
if (!entry || !this.sessionLive(session) || !/^[a-f0-9]{64}$/.test(secret) || !timingSafeEqual(Buffer.from(secret), Buffer.from(entry.secret))) throw failure("Shared computer is disconnected or not authorized", 403);
return entry;
}
+ /** Some computer is lent here, online or away: only then do the bots of a server that takes its admins' computers see the tools. */
+ anyLent(): boolean { return this.computers.size > 0 || (this.lent?.any() ?? false); }
list(principal: string | null) {
if (!principal) return [];
return [...this.computers.values()].filter(entry => entry.owner.person === principal && this.online(entry)).map(({ registration: { platform, ...rest } }) => ({ ...rest, ...(platform ? { device: deviceWord(platform) } : {}) }));
diff --git a/src/components/ComputerSharingSettings.tsx b/src/components/ComputerSharingSettings.tsx
index c974045edc..e1ede443ed 100644
--- a/src/components/ComputerSharingSettings.tsx
+++ b/src/components/ComputerSharingSettings.tsx
@@ -7,9 +7,10 @@ import { LendingActivityList } from "./LendingActivity";
import { t } from "@/lib/i18n";
/** Security: grants are edited locally and confirmed by a native dialog, never by the hosted page. */
-export function ComputerSharingSettings({ workspace, onClose }: { workspace: { id: string; name: string; origin: string }; onClose: () => void }) {
+/** `own`: a server of the person's own (this desktop is its admin), lent without the maintainer flag once they allowed it. */
+export function ComputerSharingSettings({ workspace, own = false, onClose }: { workspace: { id: string; name: string; origin: string }; own?: boolean; onClose: () => void }) {
const { state: appState } = useStore();
- const offered = sharedComputersEnabled(appState.config);
+ const offered = own || sharedComputersEnabled(appState.config);
const bridge = offered ? window.ogb?.computerSharing : undefined;
const [state, setState] = useState<DesktopComputerSharing | null>(null);
const [folders, setFolders] = useState<DesktopSharedFolder[]>([]);
@@ -51,7 +52,14 @@ export function ComputerSharingSettings({ workspace, onClose }: { workspace: { i
<p role="status" className="text-ink-secondary">{!state ? t("computerSharing.loading") : !state.enabled ? t("computerSharing.notShared") : state.connected ? t("computerSharing.sharing") : "Waiting for the workspace to connect"}</p>
<button type="button" aria-label={t("computerSharing.close")} onClick={onClose} className="rounded p-1 text-ink-secondary hover:bg-control"><X size={16} /></button>
</div>
- <p className="text-ink-secondary">Choose what this workspace’s bots can use. Shared files and screen content may be sent to its AI provider. Access stays on when you switch workspaces, until you stop sharing or close the desktop app.</p>
+ <p className="text-ink-secondary">{own ? t("computerSharing.ownIntro", { name: workspace.name }) : "Choose what this workspace’s bots can use. Shared files and screen content may be sent to its AI provider. Access stays on when you switch workspaces, until you stop sharing or close the desktop app."}</p>
+ {own && state?.enabled && <div data-sharing-pause className="flex items-center gap-3 rounded-lg bg-inset px-3 py-2">
+ <p className="min-w-0 flex-1 text-[12px] text-ink-secondary">{t(state.paused ? "computerSharing.paused" : "computerSharing.pauseHint")}</p>
+ <button type="button" disabled={busy} onClick={() => void perform(async () => {
+ await (state.paused ? bridge.resume?.() : bridge.pause?.());
+ const next = await bridge.state(workspace.id); if (mounted.current) setState(next);
+ })} className="shrink-0 rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50">{t(state.paused ? "computerSharing.resume" : "computerSharing.pause")}</button>
+ </div>}
<fieldset disabled={busy || !state} className="flex flex-col gap-3 disabled:opacity-50">
<legend className="mb-2 font-medium text-ink">{t("computerSharing.folders")}</legend>
{folders.length === 0 && <p className="text-[12px] text-ink-secondary">{t("computerSharing.noFolders")}</p>}
diff --git a/src/components/ConnectedWorkspacesSettings.test.ts b/src/components/ConnectedWorkspacesSettings.test.ts
index 8809ea6cbc..2c1d7bf46f 100644
--- a/src/components/ConnectedWorkspacesSettings.test.ts
+++ b/src/components/ConnectedWorkspacesSettings.test.ts
@@ -186,6 +186,23 @@ 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 }) };
+ 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");
+ 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 () => {
stubEnvironments(); setLocale("zh"); await mount();
const { html } = render();
diff --git a/src/components/ConnectedWorkspacesSettings.tsx b/src/components/ConnectedWorkspacesSettings.tsx
index 054cb113c7..49702947c9 100644
--- a/src/components/ConnectedWorkspacesSettings.tsx
+++ b/src/components/ConnectedWorkspacesSettings.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from "react";
import { Check, Laptop, Loader2, Trash2 } from "lucide-react";
import { Card } from "./SettingsPrimitives";
import { ComputerSharingSettings } from "./ComputerSharingSettings";
-import { ServerList } from "./ServerList";
+import { ServerList, type OwnServerSharing } from "./ServerList";
import { useStore } from "@/state/store";
import { sharedComputersEnabled } from "@/lib/feature-flags";
@@ -15,6 +15,9 @@ export function ConnectedWorkspacesSettings() {
// Security: the desktop bridge alone is not enough; never offer access the server refuses.
const { state } = useStore();
const sharingOffered = sharedComputersEnabled(state.config) && Boolean(window.ogb?.computerSharing);
+ // A server of the person's own takes this computer without that flag, once they allow it in main's popup.
+ const sharing = window.ogb?.computerSharing;
+ const [ownServers, setOwnServers] = useState<OwnServerSharing[]>([]);
const [saved, setSaved] = useState<SavedWorkspaces | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
@@ -32,6 +35,18 @@ export function ConnectedWorkspacesSettings() {
.catch(() => { if (generation.current === current) setError(t("servers.loadFailed")); });
return () => { generation.current++; };
}, [bridge]);
+ useEffect(() => {
+ if (!sharing?.servers || !saved) return;
+ let current = true;
+ const read = () => void sharing.servers!().then((next) => { if (current) setOwnServers(next); }).catch(() => {});
+ read();
+ 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);
@@ -64,6 +79,7 @@ export function ConnectedWorkspacesSettings() {
const confirmAction = (message: string) => window.ogb?.confirm ? window.ogb.confirm(message) : window.confirm(message);
const connected = saved?.environments.find(entry => entry.id === computerId);
const computerWorkspace = connected?.origin && !connected.home ? { id: connected.id, name: connected.name, origin: connected.origin } : undefined;
+ const ownComputer = Boolean(computerWorkspace && ownServers.some((own) => own.id === computerWorkspace.id));
const locals = saved?.environments.filter(entry => entry.kind === "local") ?? [];
const forgetEntry = locals.find(entry => entry.id === envForget);
return <>
@@ -138,10 +154,10 @@ export function ConnectedWorkspacesSettings() {
</Card>}
<Card title={t("servers.yours.title")} subtitle={t("servers.yours.subtitle")}>
{!saved ? <p role="status" className="text-[13px] text-ink-secondary">{t(error ? "servers.yours.loadFailed" : "servers.yours.loading")}</p> :
- <ServerList saved={saved} busy={busy} sharingOffered={sharingOffered} appVersion={window.ogb?.app?.version ?? null}
+ <ServerList saved={saved} busy={busy} sharingOffered={sharingOffered} ownServers={ownServers} appVersion={window.ogb?.app?.version ?? null} onShare={share}
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="mt-2 text-[12px] text-danger">{error}</p>}
</Card>
- {sharingOffered && computerWorkspace && <ComputerSharingSettings key={computerWorkspace.id} workspace={computerWorkspace} onClose={() => setComputerId(null)} />}
+ {(sharingOffered || ownComputer) && computerWorkspace && <ComputerSharingSettings key={computerWorkspace.id} workspace={computerWorkspace} own={ownComputer} onClose={() => setComputerId(null)} />}
</>;
}
diff --git a/src/components/ServerList.test.ts b/src/components/ServerList.test.ts
index 335daed396..07ce2d2451 100644
--- a/src/components/ServerList.test.ts
+++ b/src/components/ServerList.test.ts
@@ -100,3 +100,34 @@ it("main's word that a status changed is read at once", async () => {
expect(row("mini").querySelector("[data-server-state]")?.textContent).toBe("Reconnecting…");
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 })); });
+ };
+ 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 }]);
+ 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.");
+ 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.");
+});
diff --git a/src/components/ServerList.tsx b/src/components/ServerList.tsx
index 22ee51e748..10bd875116 100644
--- a/src/components/ServerList.tsx
+++ b/src/components/ServerList.tsx
@@ -9,11 +9,14 @@ import { cloudColor } from "@/lib/cloud-look";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { OwnServerLink, RailSheet } from "./PlaceAddSheet";
+import { Switch } from "./SettingsPrimitives";
import { CloudTile } from "./cloud-buy/parts";
type Saved = Awaited<ReturnType<NonNullable<NonNullable<Window["ogb"]>["environments"]>["state"]>>;
type Entry = Saved["environments"][number];
type Sheet = { address: string; locked: boolean; title: string } | null;
+/** A saved server of the person's own (this desktop is its admin), and how lending this computer to it is. */
+export type OwnServerSharing = { id: string; enabled: boolean; connected: boolean; paused: boolean };
const TRANSPORT = { https: "servers.transport.https", tailscale: "servers.transport.tailscale", "private-http": "servers.transport.privateHttp", loopback: "servers.transport.loopback" } as const;
const byHand = (entry: Entry) => entry.kind !== "local" && Boolean(entry.origin) && !entry.home && !entry.cloud && !("team" in entry && entry.team);
@@ -59,9 +62,22 @@ function StatusLine({ status, onTryNow, onPairAgain, onEdit }: { status: ServerS
</div>;
}
-export function ServerList({ saved, busy, sharingOffered, appVersion, onSwitch, onForget, onComputerAccess }: {
- saved: Saved; busy: boolean; sharingOffered: boolean; appVersion: string | null;
- onSwitch: (id: string) => void; onForget: (id: string) => void; onComputerAccess: (id: string) => void;
+/** "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 = () => {} }: {
+ 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;
}) {
const bridge = window.ogb?.environments;
const [statuses, setStatuses] = useState<ServerStatus[]>([]);
@@ -88,6 +104,7 @@ export function ServerList({ saved, busy, sharingOffered, appVersion, onSwitch,
const where = entry.id === "local" ? t("servers.localHint")
: !byHand(entry) ? (entry.home ? t("servers.managed") : new URL(entry.origin!).host)
: `${new URL(entry.origin!).host} · ${t(TRANSPORT[serverTransport(entry.origin!)])}`;
+ const share = ownServers.find((own) => own.id === entry.id);
const showUpdate = status?.behind === true && appVersion !== null && !hidden.includes(`${entry.id}:${status.version}`);
return <li key={entry.id} data-server-row={entry.id} className="py-3">
<div className="flex items-center gap-3">
@@ -102,11 +119,12 @@ export function ServerList({ saved, busy, sharingOffered, appVersion, onSwitch,
className="rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50">{t("servers.switch")}</button>}
{byHand(entry) && status?.state !== "signedOut" && <button type="button" disabled={busy} onClick={() => pairAgain(entry)}
className="rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50">{t("servers.pairAgain")}</button>}
- {entry.id !== "local" && !entry.home && !entry.cloud && sharingOffered && <button type="button" disabled={busy} aria-label={t("servers.computerAccessFor", { name: entry.name })} onClick={() => onComputerAccess(entry.id)} className="rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control">{t("servers.computerAccess")}</button>}
+ {entry.id !== "local" && !entry.home && !entry.cloud && !share && sharingOffered && <button type="button" disabled={busy} aria-label={t("servers.computerAccessFor", { name: entry.name })} onClick={() => onComputerAccess(entry.id)} className="rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control">{t("servers.computerAccess")}</button>}
{byHand(entry) && <CopyAddress origin={entry.origin!} name={entry.name} />}
{entry.id !== "local" && !entry.home && <button type="button" disabled={busy} aria-label={t("servers.removeName", { name: entry.name })} title={t("servers.removeName", { name: entry.name })}
onClick={() => onForget(entry.id)} className="rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50"><Trash2 size={14} /></button>}
</div>
+ {share && <ShareRow name={entry.name} share={share} busy={busy} onShare={(on) => onShare(entry.id, on)} onOpen={() => onComputerAccess(entry.id)} />}
{showUpdate && <UpdateNote name={entry.name} status={status!} appVersion={appVersion!} onHide={() => setHidden((list) => [...list, `${entry.id}:${status!.version}`])} />}
</li>;
})}
diff --git a/src/locales/de.json b/src/locales/de.json
index f619d58775..5afc352b14 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -3342,6 +3342,12 @@
"servers.behind.copy": "Update-Befehl kopieren",
"servers.behind.hide": "Hinweis ausblenden",
"servers.pairAgainTitle": "Erneut mit {name} koppeln",
+ "servers.share.title": "Diesen Computer teilen",
+ "servers.share.off": "Lass die Bots von {name} von dir gewählte Ordner, ein Terminal und die Apps auf deinem Bildschirm nutzen.",
+ "servers.share.on": "Die Bots von {name} können diesen Computer nutzen, solange diese App geöffnet ist.",
+ "servers.share.paused": "Pausiert: Die Bots von {name} können diesen Computer erst wieder nutzen, wenn du fortsetzt.",
+ "servers.share.choose": "Auswählen, was er nutzen darf",
+ "servers.share.for": "Diesen Computer mit {name} teilen",
"native.dialog.removeServer.button": "Entfernen",
"native.dialog.removeServer.title": "{name} aus dieser App entfernen?",
"native.dialog.removeServer.detail": "Der Server läuft weiter und deine Bots bleiben dort. Zum erneuten Hinzufügen brauchst du einen neuen Kopplungscode.",
diff --git a/src/locales/en.json b/src/locales/en.json
index 9731a7eb9f..e45c5be6dd 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -8252,6 +8252,11 @@
"computerSharing.share": "Share selected access",
"computerSharing.stop": "Stop sharing",
"computerSharing.stopHint": "Stopping blocks new requests and cancels running work where possible. An action already sent to an app may still finish.",
+ "computerSharing.ownIntro": "Choose what {name}'s bots can use on this computer while this app is open. Files and screen content they use go to that server and its AI provider.",
+ "computerSharing.pauseHint": "Pause stops every server and Cloud from using this computer until you resume.",
+ "computerSharing.paused": "Paused: no server or Cloud can use this computer until you resume.",
+ "computerSharing.pause": "Pause",
+ "computerSharing.resume": "Resume",
"servers.loadFailed": "Could not load saved servers. Please reopen this page.",
"servers.desktopOnly": "Manage server connections in the desktop app.",
"servers.intro": "One desktop app, wherever your bots live. Switching servers does not move or replace your bots, conversations, or provider accounts.",
@@ -8286,6 +8291,12 @@
"servers.localHint": "Local bots and conversations",
"servers.computerAccessFor": "Computer access for {name}",
"servers.computerAccess": "Computer access",
+ "servers.share.title": "Share this computer",
+ "servers.share.off": "Let {name}'s bots use folders you choose, a terminal and the apps on your screen.",
+ "servers.share.on": "{name}'s bots can use this computer while this app is open.",
+ "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}",
"routines.status.deferred": "Deferred: target busy",
"routines.run.review": "Review",
"routines.run.open": "Open run",
@@ -9006,6 +9017,10 @@
"native.dialog.share.detail": "Let this server’s bots use folders and capabilities you choose while this desktop app is running. Nothing is shared unless you enable it. You can change this later in Settings → Servers.",
"native.dialog.share.choose": "Choose access",
"native.dialog.share.notNow": "Not now",
+ "native.lend.own.title": "Let {name} use this computer?",
+ "native.lend.own.detail": "Its bots can then see and use the apps on your screen while this app is open. In Settings → Servers you can also let them use folders you choose and run commands in a terminal. Turn it off there any time, or pause it from the OpenMausBot icon's menu.",
+ "native.lend.own.allow": "Allow",
+ "native.lend.notOwnServer": "Only your own server can use this computer. Pair this app with it again as its owner.",
"native.dialog.updateServers.title": "Could not update servers",
"native.dialog.updateServers.saveFailed": "Could not save server connections on this computer. Please try again.",
"native.dialog.switchEnv.title": "Could not switch environments",
diff --git a/src/locales/es.json b/src/locales/es.json
index 160752b988..024749399c 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -5992,6 +5992,12 @@
"servers.behind.copy": "Copiar comando de actualización",
"servers.behind.hide": "Ocultar este aviso",
"servers.pairAgainTitle": "Volver a vincular con {name}",
+ "servers.share.title": "Compartir este ordenador",
+ "servers.share.off": "Deja que los bots de {name} usen las carpetas que elijas, una terminal y las apps de tu pantalla.",
+ "servers.share.on": "Los bots de {name} pueden usar este ordenador mientras esta app esté abierta.",
+ "servers.share.paused": "En pausa: los bots de {name} no pueden usar este ordenador hasta que lo reanudes.",
+ "servers.share.choose": "Elegir qué puede usar",
+ "servers.share.for": "Compartir este ordenador con {name}",
"native.dialog.removeServer.button": "Quitar",
"native.dialog.removeServer.title": "¿Quitar {name} de esta app?",
"native.dialog.removeServer.detail": "El servidor sigue funcionando y tus bots se quedan allí. Necesitarás un código de vinculación nuevo para volver a añadirlo.",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 74dd7e83ff..17f80fcb29 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -3208,6 +3208,12 @@
"servers.behind.copy": "Copier la commande de mise à jour",
"servers.behind.hide": "Masquer cette note",
"servers.pairAgainTitle": "Appairer à nouveau avec {name}",
+ "servers.share.title": "Partager cet ordinateur",
+ "servers.share.off": "Laisse les bots de {name} utiliser les dossiers que tu choisis, un terminal et les apps de ton écran.",
+ "servers.share.on": "Les bots de {name} peuvent utiliser cet ordinateur tant que cette app est ouverte.",
+ "servers.share.paused": "En pause : les bots de {name} ne peuvent pas utiliser cet ordinateur tant que tu ne reprends pas.",
+ "servers.share.choose": "Choisir ce qu’il peut utiliser",
+ "servers.share.for": "Partager cet ordinateur avec {name}",
"native.dialog.removeServer.button": "Retirer",
"native.dialog.removeServer.title": "Retirer {name} de cette app ?",
"native.dialog.removeServer.detail": "Le serveur continue de tourner et vos bots y restent. Il vous faudra un nouveau code d'appairage pour le rajouter.",
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 77fb56a311..c03e07ad03 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -3060,6 +3060,12 @@
"servers.behind.copy": "अपडेट कमांड कॉपी करें",
"servers.behind.hide": "यह नोट छिपाएँ",
"servers.pairAgainTitle": "{name} से फिर से पेयर करें",
+ "servers.share.title": "यह कंप्यूटर शेयर करें",
+ "servers.share.off": "{name} के बॉट्स को आपके चुने हुए फ़ोल्डर, एक टर्मिनल और आपकी स्क्रीन के ऐप इस्तेमाल करने दें।",
+ "servers.share.on": "जब तक यह ऐप खुला है, {name} के बॉट्स इस कंप्यूटर का इस्तेमाल कर सकते हैं।",
+ "servers.share.paused": "रुका हुआ: जब तक आप फिर से शुरू नहीं करते, {name} के बॉट्स इस कंप्यूटर का इस्तेमाल नहीं कर सकते।",
+ "servers.share.choose": "चुनें कि यह क्या इस्तेमाल कर सकता है",
+ "servers.share.for": "यह कंप्यूटर {name} के साथ शेयर करें",
"native.dialog.removeServer.button": "हटाएँ",
"native.dialog.removeServer.title": "{name} को इस ऐप से हटाएँ?",
"native.dialog.removeServer.detail": "सर्वर चलता रहेगा और आपके बॉट वहीं रहेंगे। इसे फिर से जोड़ने के लिए नया पेयरिंग कोड चाहिए होगा।",
diff --git a/src/locales/it.json b/src/locales/it.json
index a0d737a1a4..46d336a2fc 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -6616,6 +6616,12 @@
"servers.behind.copy": "Copia il comando di aggiornamento",
"servers.behind.hide": "Nascondi questa nota",
"servers.pairAgainTitle": "Abbina di nuovo con {name}",
+ "servers.share.title": "Condividi questo computer",
+ "servers.share.off": "Lascia che i bot di {name} usino le cartelle che scegli, un terminale e le app sul tuo schermo.",
+ "servers.share.on": "I bot di {name} possono usare questo computer finché questa app è aperta.",
+ "servers.share.paused": "In pausa: i bot di {name} non possono usare questo computer finché non riprendi.",
+ "servers.share.choose": "Scegli cosa può usare",
+ "servers.share.for": "Condividi questo computer con {name}",
"native.dialog.removeServer.button": "Rimuovi",
"native.dialog.removeServer.title": "Rimuovere {name} da questa app?",
"native.dialog.removeServer.detail": "Il server continua a funzionare e i tuoi bot restano lì. Per aggiungerlo di nuovo ti servirà un nuovo codice di abbinamento.",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index ec742ff7fe..6e4c6408a2 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -7669,6 +7669,12 @@
"servers.behind.copy": "アップデートコマンドをコピー",
"servers.behind.hide": "このメモを隠す",
"servers.pairAgainTitle": "{name} ともう一度ペアリング",
+ "servers.share.title": "このコンピューターを共有",
+ "servers.share.off": "{name} のボットが、選んだフォルダー、ターミナル、画面上のアプリを使えるようにします。",
+ "servers.share.on": "このアプリが開いている間、{name} のボットはこのコンピューターを使えます。",
+ "servers.share.paused": "一時停止中:再開するまで {name} のボットはこのコンピューターを使えません。",
+ "servers.share.choose": "使えるものを選ぶ",
+ "servers.share.for": "このコンピューターを {name} と共有",
"native.dialog.removeServer.button": "削除",
"native.dialog.removeServer.title": "{name} をこのアプリから削除しますか?",
"native.dialog.removeServer.detail": "サーバーは動き続け、ボットもそこに残ります。もう一度追加するには新しいペアリングコードが必要です。",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index d14a1b9e6a..d6c66f8719 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -7338,6 +7338,12 @@
"servers.behind.copy": "업데이트 명령 복사",
"servers.behind.hide": "이 안내 숨기기",
"servers.pairAgainTitle": "{name}와(과) 다시 페어링",
+ "servers.share.title": "이 컴퓨터 공유",
+ "servers.share.off": "{name}의 봇이 내가 고른 폴더, 터미널, 화면의 앱을 쓸 수 있게 합니다.",
+ "servers.share.on": "이 앱이 열려 있는 동안 {name}의 봇이 이 컴퓨터를 쓸 수 있습니다.",
+ "servers.share.paused": "일시 중지됨: 다시 시작할 때까지 {name}의 봇은 이 컴퓨터를 쓸 수 없습니다.",
+ "servers.share.choose": "쓸 수 있는 것 고르기",
+ "servers.share.for": "이 컴퓨터를 {name}와 공유",
"native.dialog.removeServer.button": "제거",
"native.dialog.removeServer.title": "이 앱에서 {name}을(를) 제거할까요?",
"native.dialog.removeServer.detail": "서버는 계속 실행되고 봇도 그대로 남습니다. 다시 추가하려면 새 페어링 코드가 필요합니다.",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index e9b892ed96..c7a678aa02 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -6754,6 +6754,12 @@
"servers.behind.copy": "Kopiuj polecenie aktualizacji",
"servers.behind.hide": "Ukryj tę uwagę",
"servers.pairAgainTitle": "Sparuj ponownie z {name}",
+ "servers.share.title": "Udostępnij ten komputer",
+ "servers.share.off": "Pozwól botom z {name} używać wybranych folderów, terminala i aplikacji na ekranie.",
+ "servers.share.on": "Boty z {name} mogą używać tego komputera, dopóki ta aplikacja jest otwarta.",
+ "servers.share.paused": "Wstrzymano: boty z {name} nie mogą używać tego komputera, dopóki nie wznowisz.",
+ "servers.share.choose": "Wybierz, czego może używać",
+ "servers.share.for": "Udostępnij ten komputer serwerowi {name}",
"native.dialog.removeServer.button": "Usuń",
"native.dialog.removeServer.title": "Usunąć {name} z tej aplikacji?",
"native.dialog.removeServer.detail": "Serwer dalej działa, a Twoje boty tam zostają. Aby dodać go ponownie, potrzebny będzie nowy kod parowania.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 0aa15f115e..1aec9ec9eb 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -8235,6 +8235,11 @@
"computerSharing.share": "Compartilhar o acesso escolhido",
"computerSharing.stop": "Parar de compartilhar",
"computerSharing.stopHint": "Parar de compartilhar bloqueia novos pedidos e cancela o trabalho em andamento quando possível. Uma ação já enviada a um app ainda pode terminar.",
+ "computerSharing.ownIntro": "Escolha o que os bots de {name} podem usar neste computador enquanto este app estiver aberto. Os arquivos e o conteúdo da tela que eles usarem vão para esse servidor e para o provedor de IA dele.",
+ "computerSharing.pauseHint": "Pausar impede que qualquer servidor ou Cloud use este computador até você retomar.",
+ "computerSharing.paused": "Pausado: nenhum servidor ou Cloud pode usar este computador até você retomar.",
+ "computerSharing.pause": "Pausar",
+ "computerSharing.resume": "Retomar",
"servers.loadFailed": "Não foi possível carregar os servidores salvos. Reabra esta página.",
"servers.desktopOnly": "Gerencie as conexões com servidores no app para computador.",
"servers.intro": "Um só app para computador, onde quer que seus bots estejam. Trocar de servidor não move nem substitui seus bots, conversas ou contas de provedores.",
@@ -8269,6 +8274,12 @@
"servers.localHint": "Bots e conversas locais",
"servers.computerAccessFor": "Acesso ao computador para {name}",
"servers.computerAccess": "Acesso ao computador",
+ "servers.share.title": "Compartilhar este computador",
+ "servers.share.off": "Deixe os bots de {name} usarem as pastas que você escolher, um terminal e os apps da sua tela.",
+ "servers.share.on": "Os bots de {name} podem usar este computador enquanto este app estiver aberto.",
+ "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}",
"routines.status.deferred": "Adiada: destino ocupado",
"routines.run.review": "Revisar",
"routines.run.open": "Abrir execução",
@@ -8978,6 +8989,10 @@
"native.dialog.share.detail": "Deixe os bots deste servidor usarem as pastas e os recursos que você escolher enquanto este app para computador estiver aberto. Só o que você ativar será compartilhado. Você pode mudar isso depois em Configurações → Servidores.",
"native.dialog.share.choose": "Escolher acesso",
"native.dialog.share.notNow": "Agora não",
+ "native.lend.own.title": "Deixar {name} usar este computador?",
+ "native.lend.own.detail": "Os bots dele poderão ver e usar os apps da sua tela enquanto este app estiver aberto. Em Configurações → Servidores você também pode deixá-los usar as pastas que escolher e executar comandos em um terminal. Desligue isso lá quando quiser ou pause no menu do ícone do OpenMausBot.",
+ "native.lend.own.allow": "Permitir",
+ "native.lend.notOwnServer": "Só o seu próprio servidor pode usar este computador. Pareie este app com ele de novo como dono.",
"native.dialog.updateServers.title": "Não foi possível atualizar os servidores",
"native.dialog.updateServers.saveFailed": "Não foi possível salvar as conexões com servidores neste computador. Tente novamente.",
"native.dialog.switchEnv.title": "Não foi possível trocar de ambiente",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 74dd1d4e67..b21d374799 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -6816,6 +6816,12 @@
"servers.behind.copy": "Скопировать команду обновления",
"servers.behind.hide": "Скрыть заметку",
"servers.pairAgainTitle": "Сопрячь заново с {name}",
+ "servers.share.title": "Поделиться этим компьютером",
+ "servers.share.off": "Разрешите ботам {name} пользоваться выбранными папками, терминалом и приложениями на экране.",
+ "servers.share.on": "Боты {name} могут пользоваться этим компьютером, пока это приложение открыто.",
+ "servers.share.paused": "На паузе: боты {name} не могут пользоваться этим компьютером, пока вы не продолжите.",
+ "servers.share.choose": "Выбрать, чем он может пользоваться",
+ "servers.share.for": "Поделиться этим компьютером с {name}",
"native.dialog.removeServer.button": "Удалить",
"native.dialog.removeServer.title": "Удалить {name} из этого приложения?",
"native.dialog.removeServer.detail": "Сервер продолжит работать, и ваши боты останутся на нём. Чтобы добавить его снова, понадобится новый код сопряжения.",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index a1587765de..df17ec57b8 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5491,6 +5491,12 @@
"servers.behind.copy": "Güncelleme komutunu kopyala",
"servers.behind.hide": "Bu notu gizle",
"servers.pairAgainTitle": "{name} ile yeniden eşleştir",
+ "servers.share.title": "Bu bilgisayarı paylaş",
+ "servers.share.off": "{name} botlarının seçtiğin klasörleri, bir terminali ve ekranındaki uygulamaları kullanmasına izin ver.",
+ "servers.share.on": "{name} botları bu uygulama açıkken bu bilgisayarı kullanabilir.",
+ "servers.share.paused": "Duraklatıldı: sen devam ettirene kadar {name} botları bu bilgisayarı kullanamaz.",
+ "servers.share.choose": "Neleri kullanabileceğini seç",
+ "servers.share.for": "Bu bilgisayarı {name} ile paylaş",
"native.dialog.removeServer.button": "Kaldır",
"native.dialog.removeServer.title": "{name} bu uygulamadan kaldırılsın mı?",
"native.dialog.removeServer.detail": "Sunucu çalışmaya devam eder ve botlarınız orada kalır. Yeniden eklemek için yeni bir eşleştirme kodu gerekir.",
diff --git a/src/locales/uk.json b/src/locales/uk.json
index f04428b5f8..3031f00142 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -3501,6 +3501,12 @@
"servers.behind.copy": "Копіювати команду оновлення",
"servers.behind.hide": "Сховати примітку",
"servers.pairAgainTitle": "Прив'язати знову до {name}",
+ "servers.share.title": "Поділитися цим комп’ютером",
+ "servers.share.off": "Дозвольте ботам {name} користуватися вибраними теками, терміналом і застосунками на екрані.",
+ "servers.share.on": "Боти {name} можуть користуватися цим комп’ютером, поки цей застосунок відкритий.",
+ "servers.share.paused": "На паузі: боти {name} не можуть користуватися цим комп’ютером, доки ви не продовжите.",
+ "servers.share.choose": "Вибрати, чим він може користуватися",
+ "servers.share.for": "Поділитися цим комп’ютером з {name}",
"native.dialog.removeServer.button": "Вилучити",
"native.dialog.removeServer.title": "Вилучити {name} із цього застосунку?",
"native.dialog.removeServer.detail": "Сервер працюватиме далі, а ваші боти залишаться на ньому. Щоб додати його знову, знадобиться новий код прив'язки.",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 5a7f32e5cf..92abc55b66 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5491,6 +5491,12 @@
"servers.behind.copy": "Sao chép lệnh cập nhật",
"servers.behind.hide": "Ẩn ghi chú này",
"servers.pairAgainTitle": "Ghép nối lại với {name}",
+ "servers.share.title": "Chia sẻ máy tính này",
+ "servers.share.off": "Cho bot của {name} dùng các thư mục bạn chọn, một terminal và các ứng dụng trên màn hình của bạn.",
+ "servers.share.on": "Bot của {name} có thể dùng máy tính này khi ứng dụng này đang mở.",
+ "servers.share.paused": "Đã tạm dừng: bot của {name} không thể dùng máy tính này cho đến khi bạn tiếp tục.",
+ "servers.share.choose": "Chọn những gì nó được dùng",
+ "servers.share.for": "Chia sẻ máy tính này với {name}",
"native.dialog.removeServer.button": "Xóa",
"native.dialog.removeServer.title": "Xóa {name} khỏi ứng dụng này?",
"native.dialog.removeServer.detail": "Máy chủ vẫn chạy và các bot của bạn vẫn ở đó. Bạn sẽ cần mã ghép nối mới để thêm lại.",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index a099a054d0..97b79792d8 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -8250,6 +8250,11 @@
"computerSharing.share": "分享選取的存取權",
"computerSharing.stop": "停止分享",
"computerSharing.stopHint": "停止後會封鎖新的要求,並盡可能取消執行中的工作。已傳送給應用程式的動作可能仍會完成。",
+ "computerSharing.ownIntro": "選擇 {name} 的機器人在這個 App 開著時可以使用這台電腦的哪些東西。它們使用的檔案和螢幕內容會傳到那台伺服器和它的 AI 供應商。",
+ "computerSharing.pauseHint": "暫停會讓所有伺服器和 Cloud 都無法使用這台電腦,直到你繼續。",
+ "computerSharing.paused": "已暫停:在你繼續之前,沒有任何伺服器或 Cloud 可以使用這台電腦。",
+ "computerSharing.pause": "暫停",
+ "computerSharing.resume": "繼續",
"servers.loadFailed": "無法載入已儲存的伺服器。請重新開啟此頁面。",
"servers.desktopOnly": "請在桌面應用程式中管理伺服器連線。",
"servers.intro": "無論你的機器人在哪裡,都用同一個桌面應用程式。切換伺服器不會移動或取代你的機器人、對話或供應商帳號。",
@@ -8284,6 +8289,12 @@
"servers.localHint": "本機的機器人和對話",
"servers.computerAccessFor": "{name} 的電腦存取權",
"servers.computerAccess": "電腦存取權",
+ "servers.share.title": "分享這台電腦",
+ "servers.share.off": "讓 {name} 的機器人使用你選的資料夾、終端機和螢幕上的 App。",
+ "servers.share.on": "這個 App 開著時,{name} 的機器人可以使用這台電腦。",
+ "servers.share.paused": "已暫停:在你繼續之前,{name} 的機器人無法使用這台電腦。",
+ "servers.share.choose": "選擇它能用什麼",
+ "servers.share.for": "與 {name} 分享這台電腦",
"routines.status.deferred": "已延後:目標忙碌中",
"routines.run.review": "檢視",
"routines.run.open": "開啟執行",
@@ -9004,6 +9015,10 @@
"native.dialog.share.detail": "在這個桌面應用程式執行期間,讓這台伺服器的機器人使用你選擇的資料夾和功能。除非你開啟,否則不會分享任何東西。你之後可以在「設定 → 伺服器」中變更。",
"native.dialog.share.choose": "選擇存取權",
"native.dialog.share.notNow": "暫時不要",
+ "native.lend.own.title": "要讓 {name} 使用這台電腦嗎?",
+ "native.lend.own.detail": "在這個 App 開著時,它的機器人就能看到並使用你螢幕上的 App。你也可以在「設定 → 伺服器」中讓它們使用你選的資料夾,並在終端機執行指令。你隨時可以在那裡關閉,或從 OpenMausBot 圖示的選單中暫停。",
+ "native.lend.own.allow": "允許",
+ "native.lend.notOwnServer": "只有你自己的伺服器能使用這台電腦。請以擁有者身分再次將這個 App 與它配對。",
"native.dialog.updateServers.title": "無法更新伺服器",
"native.dialog.updateServers.saveFailed": "無法在這台電腦上儲存伺服器連線。請再試一次。",
"native.dialog.switchEnv.title": "無法切換環境",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index b146d3ed8c..c3bf2d0751 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -7555,6 +7555,12 @@
"servers.behind.copy": "复制更新命令",
"servers.behind.hide": "隐藏此提示",
"servers.pairAgainTitle": "与 {name} 重新配对",
+ "servers.share.title": "共享这台电脑",
+ "servers.share.off": "让 {name} 的机器人使用你选的文件夹、终端和屏幕上的应用。",
+ "servers.share.on": "这个应用打开时,{name} 的机器人可以使用这台电脑。",
+ "servers.share.paused": "已暂停:在你继续之前,{name} 的机器人无法使用这台电脑。",
+ "servers.share.choose": "选择它能用什么",
+ "servers.share.for": "与 {name} 共享这台电脑",
"native.dialog.removeServer.button": "移除",
"native.dialog.removeServer.title": "要从这个应用移除 {name} 吗?",
"native.dialog.removeServer.detail": "服务器会继续运行,你的机器人也会留在那里。之后要再添加,需要新的配对码。",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index aa3934098f..908f38449d 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -276,6 +276,13 @@ const __APP_VERSION__: string;
revoke(id: string): Promise<DesktopComputerSharing>;
/** This computer's own record of what that server's bots did here, newest first. */
activity(id: string): Promise<DesktopLendingActivity[]>;
+ /** Each saved server of the person's own (this desktop is its admin) and how lending to it is. */
+ servers?(): Promise<Array<{ id: string; enabled: boolean; connected: boolean; paused: boolean }>>;
+ /** Asks in main's own popup, then lends that server of the person's own the apps on the screen; null on Not now. */
+ allow?(id: string): Promise<DesktopComputerSharing | null>;
+ /** Every Cloud and server of the person's own stops using this computer until resume(), as the icon's menu does. */
+ pause?(): Promise<void>;
+ resume?(): Promise<void>;
};
confirm(message: string): Promise<boolean>;
getCapabilities(): Promise<DesktopCapabilities>;