Skip to content

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

Windows: lend a PC's apps and screen, say plainly when it can't, and let a Cloud's bot ask to turn it on (#3950)

Milind Soni9b2c10b20183
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3a40e4c94f..39836ca7b4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -289,7 +289,7 @@ jobs:
if: contains(needs.static.outputs.jobs, '"windows-cua"')
name: Windows CUA host smoke
runs-on: windows-latest
- timeout-minutes: 10
+ timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@ff378ebe6b225b0680b81c1ad4498ae0d1d3a5e3 # v6.0.10
@@ -301,6 +301,9 @@ jobs:
- name: Smoke the staged Windows CUA host (no computer actions)
timeout-minutes: 5
run: pnpm build:cua:win && pnpm smoke:cua-win
+ - name: Lend this PC's apps and screen as the installed app does (reads only, no input)
+ timeout-minutes: 5
+ run: pnpm smoke:cua-win-lend
electron-smokes:
needs: static
diff --git a/.github/workflows/windows-defender-check.yml b/.github/workflows/windows-defender-check.yml
new file mode 100644
index 0000000000..4d2c6dbe4f
--- /dev/null
+++ b/.github/workflows/windows-defender-check.yml
@@ -0,0 +1,52 @@
+# How Windows Security treats the real installer, on a fresh GitHub Windows machine. It builds the NSIS installer the
+# way the release's Windows job does, turns Defender's protection on the way a home PC has it (GitHub's image turns most
+# of it off and excludes every drive), saves the installer like a browser download (Zone.Identifier, ZoneId=3),
+# installs it silently, opens the app for two minutes and presses Start screen control. The summary and the
+# defender-check artifact say what Defender found, whether cua-driver-background.exe runs and what the app's log says
+# (scripts/defender-check-win.mjs). The run fails when Windows Security flagged the app or screen control doesn't run.
+#
+# By hand only: Run workflow in the Actions tab (`gh workflow run windows-defender-check.yml --ref <branch>`), or the
+# "defender-check" label on a pull request, which is also how it runs before this file is on main.
+name: Windows Defender check
+
+on:
+ workflow_dispatch:
+ pull_request:
+ types: [labeled]
+
+permissions:
+ contents: read
+
+jobs:
+ check:
+ name: Windows Security and the installer
+ if: github.event_name == 'workflow_dispatch' || github.event.label.name == 'defender-check'
+ runs-on: windows-latest
+ timeout-minutes: 75
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ # the pull request's own commit, not its merge with main
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+ - uses: pnpm/action-setup@ff378ebe6b225b0680b81c1ad4498ae0d1d3a5e3 # v6.0.10
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 24
+ cache: pnpm
+ - run: pnpm install --frozen-lockfile
+ - name: Clean generated output
+ shell: bash
+ run: rm -rf dist dist-server release
+ - run: pnpm package:win
+ - name: Install it like a download and watch Windows Security
+ timeout-minutes: 45
+ shell: bash
+ run: node scripts/defender-check-win.mjs --installer "$(ls release/OpenMausBot-*-setup.exe)" --out "$RUNNER_TEMP/defender-check"
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ if: always()
+ with:
+ name: defender-check
+ path: ${{ runner.temp }}/defender-check
+ if-no-files-found: warn
+ retention-days: 14
diff --git a/apps/docs/content/docs/getting-started/using-the-desktop-app-with-my-cloud.mdx b/apps/docs/content/docs/getting-started/using-the-desktop-app-with-my-cloud.mdx
index 60d01fae9e..d6cb311b8f 100644
--- a/apps/docs/content/docs/getting-started/using-the-desktop-app-with-my-cloud.mdx
+++ b/apps/docs/content/docs/getting-started/using-the-desktop-app-with-my-cloud.mdx
@@ -40,7 +40,7 @@ There is nothing to switch on. While the desktop app is open and signed in to Ma
- **Your files**: your home folder, to read and edit. The places that hold keys, passwords and sign-ins, such as `.ssh`, your shell's start-up files and git's settings, always stay private, and nothing changes the hidden files, Library or AppData in your home folder.
- **Your internet connection**, for the websites that turn away data centres, such as Instagram, YouTube and Google sign-in. Every other website loads straight from My Cloud, which is faster.
- **Your Chrome**, for bots whose browser profile is **My Chrome**. Chrome asks you to allow the connection.
-- **Your apps and screen**, once your Mac allows OpenMausBot Accessibility and Screen Recording. macOS asks the first time a bot needs them. On Windows they work right away.
+- **Your apps and screen**, once your Mac allows OpenMausBot Accessibility and Screen Recording. macOS asks the first time a bot needs them. On Windows they work as soon as screen control runs; if it isn't running, the taskbar icon's menu says why, with **Start screen control**.
Commands never run on your computer.
@@ -57,6 +57,12 @@ After the move to My Cloud, each bot's own project folder is lent with editing t
If you had turned sharing off, or the internet connection, in an earlier version, the app starts paused: choose **Resume** when you want your Clouds to use this computer.
+When your Clouds can't use this computer's apps and screen, the menu says so and why, with the one thing that fixes it, such as **Start screen control**.
+
+## When a bot needs your computer
+
+If a bot on the Cloud needs your computer and can't use it right now (you paused it, screen control isn't running, or the app is closed), it asks with one card in the chat: what it wants to do and why, and **Turn on**. The app on your computer asks too, once. Choose **Turn on** in either and the bot carries on by itself. If the app isn't open on your computer, the card says so, with **Get MausBot**: open it, and the bot carries on. **Not now** tells the bot to go without your computer.
+
While a Cloud can use it, the app opens by itself when you log in, out of sight. When this computer is away, asleep or with the app closed, those websites open from My Cloud's own connection and may turn your bots away. Reddit stays off either way.
## Signing in to Google and other passkey sites
diff --git a/computer-ask-preview.html b/computer-ask-preview.html
new file mode 100644
index 0000000000..2a8a5f00a3
--- /dev/null
+++ b/computer-ask-preview.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Turn On Your Computer Preview</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/computer-ask-preview.tsx"></script>
+ </body>
+</html>
diff --git a/docs/ci.md b/docs/ci.md
index 73eadd8013..57872bec9a 100644
--- a/docs/ci.md
+++ b/docs/ci.md
@@ -15,7 +15,8 @@ too) into areas, and runs only the jobs some area can affect:
| web | the rest of `src/`, `public/`, the root `*-preview.html` pages | the build, the eight Linux shards, the renderer smoke |
| script tests | `scripts/**/*.test.*` | the Linux shards (and Windows', see Windows), the renderer smoke, browser identity |
| server | `server/`, `shared/`, `enterprise/`, `companion/`, `evals/`, `skills/`, `deploy/`, the composio broker, the Dockerfile, and the renderer files the server or a smoke loads | the build, Linux shards (and Windows', see Windows), behavior evals, packaged server, open-source edition, the macOS smokes, renderer smoke, browser identity, browser driver, Linux package |
-| desktop | `electron/`, `build/`, `electron-builder.yml`, `index.html` | the same as server |
+| Windows computer control | the `electron/` modules that start computer control and lend a PC's screen: `cua`, `cua-failure`, `cua-connection`, `capabilities`, `screen-status`, `shared-cua-connection`, `shared-computer-access`, `lent-screen-tools`, `lent-screen-failures`, `paced-typing` | the same as server, and Windows CUA |
+| desktop | the rest of `electron/`, `build/`, `electron-builder.yml`, `index.html` | the same as server |
| control plane | `cloudflare/control-plane/` | the control-plane job |
| everything | anything else: `.github/` workflows, `package.json`, the lockfile and workspace, tsconfig, vite and vitest config, `third_party/`, `scripts/` code, unknown paths | every job |
@@ -35,9 +36,11 @@ areas run the union of their jobs. Why the mapping is what it is:
catalogs are read only by `src/` tests, the locale generator's test and an
Electron node test; `scripts/ci-scope.test.ts` fails if another test starts
reading them, or the docs, without being listed.
-- Windows CUA and the Linux ARM64 cloudflared installer test only their own
- scripts and pinned downloads, so only `scripts/` and dependency changes run
- them.
+- Windows CUA starts computer control the way the installed app does and
+ takes a Cloud's first look at the PC through the lend path, so a change to
+ those Electron modules runs it, as do `scripts/` and dependency changes. The
+ Linux ARM64 cloudflared installer tests only its own script and pinned
+ download.
## Lanes: pull requests, main and the full lane
@@ -156,7 +159,8 @@ half hours. Now:
Windows runners are slow to get and a Windows shard takes as long as a Linux
one, so a pull request runs the Windows jobs (the eight shards, the packaged
server smoke, browser identity, the browser driver and, for a change that can
-affect anything, the CUA smoke) only when its change can break Windows first
+affect anything or to the Electron modules it starts, the CUA smoke) only when
+its change can break Windows first
(`windowsReason` in `scripts/ci-scope.mjs`):
- the PR carries the `windows` label;
diff --git a/docs/verification/evidence/windows-lend/card-asking-dark.png b/docs/verification/evidence/windows-lend/card-asking-dark.png
new file mode 100644
index 0000000000..ef0d580c37
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-asking-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/card-asking-light.png b/docs/verification/evidence/windows-lend/card-asking-light.png
new file mode 100644
index 0000000000..54fed75ca1
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-asking-light.png differ
diff --git a/docs/verification/evidence/windows-lend/card-closed-dark.png b/docs/verification/evidence/windows-lend/card-closed-dark.png
new file mode 100644
index 0000000000..7e32ba3146
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-closed-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/card-closed-light.png b/docs/verification/evidence/windows-lend/card-closed-light.png
new file mode 100644
index 0000000000..cc47b9a324
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-closed-light.png differ
diff --git a/docs/verification/evidence/windows-lend/card-failed-dark.png b/docs/verification/evidence/windows-lend/card-failed-dark.png
new file mode 100644
index 0000000000..763e05d112
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-failed-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/card-failed-light.png b/docs/verification/evidence/windows-lend/card-failed-light.png
new file mode 100644
index 0000000000..cdd7f38a8f
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-failed-light.png differ
diff --git a/docs/verification/evidence/windows-lend/card-on-dark.png b/docs/verification/evidence/windows-lend/card-on-dark.png
new file mode 100644
index 0000000000..574f81c892
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-on-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/card-on-light.png b/docs/verification/evidence/windows-lend/card-on-light.png
new file mode 100644
index 0000000000..726232569c
Binary files /dev/null and b/docs/verification/evidence/windows-lend/card-on-light.png differ
diff --git a/docs/verification/evidence/windows-lend/pc-status-dark.png b/docs/verification/evidence/windows-lend/pc-status-dark.png
new file mode 100644
index 0000000000..09e311c2c4
Binary files /dev/null and b/docs/verification/evidence/windows-lend/pc-status-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/pc-status-light.png b/docs/verification/evidence/windows-lend/pc-status-light.png
new file mode 100644
index 0000000000..b22fff169b
Binary files /dev/null and b/docs/verification/evidence/windows-lend/pc-status-light.png differ
diff --git a/docs/verification/evidence/windows-lend/taskbar-blocked-dark.png b/docs/verification/evidence/windows-lend/taskbar-blocked-dark.png
new file mode 100644
index 0000000000..ffe0d914a8
Binary files /dev/null and b/docs/verification/evidence/windows-lend/taskbar-blocked-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/taskbar-blocked-light.png b/docs/verification/evidence/windows-lend/taskbar-blocked-light.png
new file mode 100644
index 0000000000..65e085c092
Binary files /dev/null and b/docs/verification/evidence/windows-lend/taskbar-blocked-light.png differ
diff --git a/docs/verification/evidence/windows-lend/taskbar-not-running-dark.png b/docs/verification/evidence/windows-lend/taskbar-not-running-dark.png
new file mode 100644
index 0000000000..240722ed9f
Binary files /dev/null and b/docs/verification/evidence/windows-lend/taskbar-not-running-dark.png differ
diff --git a/docs/verification/evidence/windows-lend/taskbar-not-running-light.png b/docs/verification/evidence/windows-lend/taskbar-not-running-light.png
new file mode 100644
index 0000000000..1cfce0eddf
Binary files /dev/null and b/docs/verification/evidence/windows-lend/taskbar-not-running-light.png differ
diff --git a/docs/verification/local-computer-launch.md b/docs/verification/local-computer-launch.md
index e0da5d0ce6..18cf9f67c3 100644
--- a/docs/verification/local-computer-launch.md
+++ b/docs/verification/local-computer-launch.md
@@ -78,6 +78,59 @@ custom `CUA_DRIVER_PATH` executables. An explicit override remains untouched;
an incomplete installed package reports a missing-driver error rather than
silently falling back to the console binary.
+`pnpm smoke:cua-win-lend`, which CI's Windows CUA job runs after that smoke,
+copies Electron under the installed app's name, so `app.isPackaged` is true,
+and places the staged files where `electron-builder.yml` puts them. In
+Electron's main process it runs `electron/cua.mjs`'s packaged start unchanged,
+then a Cloud's first look at the PC through the lend path: the tool list, the
+screen's size and the list of apps, over the proxy a lent screen starts with
+the environment it gets. It sends no input. It prints computer control's mode,
+the reason Windows gave when it did not start, and whether apps and screen
+would be lent. On a pull request it first runs the base branch's `electron/`
+the same way, so one run shows what the change does; only this branch's result
+decides the job.
+
+How Windows Security treats the real installer is the job of the Windows
+Defender check (`.github/workflows/windows-defender-check.yml`), run by hand
+or by the `defender-check` label on a pull request. On a fresh GitHub Windows
+machine it builds the installer the way the release does, turns Defender's
+protection on the way a home PC has it (GitHub's image turns most of it off and
+excludes every drive), saves the installer like a browser download
+(`Zone.Identifier`, `ZoneId=3`), installs it silently, opens the app for two
+minutes and presses Start screen control through the app's DevTools port. Its
+summary says what Defender found (threat detections and Operational events
+1116, 1117, 1006–1008 and 1015), whether `cua-driver-background.exe` runs, what
+the app's log says about computer control and whether Start screen control
+worked; the `defender-check` artifact holds the rest. It is Windows Server,
+not Windows 10 or 11: SmartScreen's "Windows protected your PC" screen and
+Smart App Control still need a person's PC.
+
+### When a Cloud can't use this computer
+
+The icon's menu says what the person's own Clouds can't use and why, with the
+one fix ("Screen control isn't running on this PC" and Start screen control).
+A Cloud's bot that needs the computer then calls `ask_for_computer`: one card
+in the chat with a one-tap Turn on, the same ask in this app's own prompt, and
+the request goes on by itself once the computer lends what was needed. Only on
+the person's own Cloud, never a Team Cloud.
+
+```sh
+node --test electron/screen-status.node-test.mjs electron/computer-asks.node-test.mjs
+pnpm exec vitest run electron/capabilities.test.mjs server/computer-asks.test.ts \
+ server/host/computer-asks-host.test.ts shared/computer-ask.test.ts src/components/ComputerAskCard.test.ts
+pnpm exec vitest run server/cloud-lending.e2e.test.ts -t "paused, the PC still hears"
+```
+
+The last one boots a real Cloud home and lends to it through the real
+connector: paused, the computer hears the bot's ask, Turn on on the card
+resumes it, and the bot's waiting call returns the computer.
+
+`node --experimental-strip-types scripts/verify-windows-lend.ts --shots <dir>`
+photographs the taskbar icon's menu as the real module builds it, the card in
+the real chat (`computer-ask-preview.html`) and the PC's own screen-control
+status, in a light and a dark look; `docs/verification/evidence/windows-lend/`
+holds the current set.
+
### Foreground typing and menu clicks
The bundled Windows driver (0.28.2) sends a foreground `type_text` as one burst
diff --git a/electron/ask-prompt.mjs b/electron/ask-prompt.mjs
new file mode 100644
index 0000000000..e2ce70c4a4
--- /dev/null
+++ b/electron/ask-prompt.mjs
@@ -0,0 +1,35 @@
+// This app's own prompt for a bot's ask: shown once nobody has touched the keyboard or mouse for a second, so a key meant
+// for something else never answers it, and never while the person is looking at that Cloud in this app, where the card is.
+import { askPromptWords } from "./screen-words.mjs";
+import { deviceWord } from "./lending-indicator.mjs";
+
+/** Waits at most this long for a quiet moment. */
+const QUIET_WAIT_MS = 15_000;
+
+/** `window()`: this app's main window, or null. `idleSeconds()`: seconds since the last touch, null when unknown. */
+export function createAskPrompt({ dialog, window, idleSeconds = () => null, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), platform = process.platform }) {
+ const open = () => { const win = window(); return win && !win.isDestroyed() ? win : null; };
+ const looking = env => {
+ const win = open();
+ if (!win?.isFocused()) return false;
+ try { return new URL(win.webContents.getURL()).origin === env.origin; } catch { return false; }
+ };
+ return async (env, ask, signal) => {
+ if (looking(env)) return null;
+ for (let waited = 0; waited < QUIET_WAIT_MS && !signal.aborted; waited += 500) {
+ const idle = idleSeconds();
+ if (typeof idle !== "number" || idle >= 1) break;
+ await wait(500);
+ }
+ if (signal.aborted || looking(env)) return null;
+ const words = askPromptWords(ask, { cloud: env.name, device: deviceWord(platform) });
+ const options = { type: "question", message: words.message, detail: words.detail, buttons: words.buttons, defaultId: 0, cancelId: 1, noLink: true, signal };
+ // Electron 43 runs a message box without a window synchronously on macOS, where `signal` cannot close it.
+ const parent = platform === "darwin" ? open() : null;
+ if (platform === "darwin" && !parent) return null;
+ if (parent && !parent.isVisible()) parent.show();
+ const { response } = await (parent ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options));
+ if (signal.aborted) return null;
+ return response === 0 ? "turn-on" : "not-now";
+ };
+}
diff --git a/electron/capabilities.cjs b/electron/capabilities.cjs
index 79b56b4b08..1d68a6524c 100644
--- a/electron/capabilities.cjs
+++ b/electron/capabilities.cjs
@@ -52,6 +52,12 @@ function linuxLocalControlSupport(platform, env) {
});
}
+/** Computer control's helper is gone, or the system refused to run it: access denied (os error 5), or Windows Security
+ * found it unsafe (os error 225, ERROR_VIRUS_INFECTED). */
+function driverBlocked(reason) {
+ return /binary not found|is missing|ENOENT|EPERM|EACCES|os error (?:2|5|225)\b|access is denied|virus/i.test(String(reason ?? ""));
+}
+
function localComputerReady(platform, connection) {
const validLegacyConnection = connection &&
(!Object.hasOwn(connection, "status") || connection.status === "ready") &&
@@ -156,7 +162,9 @@ function desktopCapabilities({
if (!localAvailable) {
localComputer.reasonCode =
localConnection?.reasonCode ??
- (hostPlatform === "darwin" ? "cua-driver-unavailable" : "unsupported-platform");
+ (hostPlatform === "darwin" || hostPlatform === "win32"
+ ? driverBlocked(localConnection?.reason) ? "cua-driver-blocked" : "cua-driver-unavailable"
+ : "unsupported-platform");
}
if (remote) {
@@ -212,6 +220,7 @@ function connectionEnabled(platform, connection) {
module.exports = {
connectionEnabled,
desktopCapabilities,
+ driverBlocked,
linuxLocalControlSupport,
linuxSession,
localComputerReady,
diff --git a/electron/capabilities.test.mjs b/electron/capabilities.test.mjs
index aeed7add72..5b1f0fe0fc 100644
--- a/electron/capabilities.test.mjs
+++ b/electron/capabilities.test.mjs
@@ -110,6 +110,15 @@ describe("desktop capabilities", () => {
});
});
+ it("tells a PC whose screen control was blocked from one that only stopped, never that Windows is unsupported", () => {
+ const reasonOf = (reason) => desktopCapabilities({ platform: "win32", packaged: true, localConnection: { mode: "unavailable", reason } }).localComputer.reasonCode;
+ expect(reasonOf("embedded host failed: Spawn: reason Access is denied. (os error 5)")).toBe("cua-driver-blocked");
+ expect(reasonOf("embedded host failed: Spawn: reason Operation did not complete successfully because the file contains a virus or potentially unwanted software. (os error 225)")).toBe("cua-driver-blocked");
+ expect(reasonOf("cua-driver binary not found")).toBe("cua-driver-blocked");
+ expect(reasonOf("embedded host failed: StartupTimeout: timeoutMs 10000")).toBe("cua-driver-unavailable");
+ expect(reasonOf("desktop-host-stopped")).toBe("cua-driver-unavailable");
+ });
+
it.each(["freebsd"])("fails closed on %s", (platform) => {
const capabilities = desktopCapabilities({
platform,
diff --git a/electron/cloud-lending.node-test.mjs b/electron/cloud-lending.node-test.mjs
index 60fad4e423..9ab3f97b4b 100644
--- a/electron/cloud-lending.node-test.mjs
+++ b/electron/cloud-lending.node-test.mjs
@@ -349,7 +349,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"], using: [], paused: true, terminal: false, busy: null });
+ assert.deepEqual(summaries.at(-1), { lending: [], clouds: ["My Cloud"], using: [], paused: true, terminal: false, busy: null, screen: null });
assert.equal(sharing.cloudState(env).problem, "paused");
});
diff --git a/electron/computer-asks.mjs b/electron/computer-asks.mjs
new file mode 100644
index 0000000000..aeabd15a66
--- /dev/null
+++ b/electron/computer-asks.mjs
@@ -0,0 +1,79 @@
+// What a bot on one of the person's own Clouds asks of this computer when it can't use it now.
+// Each ask comes up once in a prompt of this app's own; Turn on there, or on the card anywhere, does here what it takes.
+// After Not now nothing more comes up for that Cloud and need for a while: the card stays in the chat.
+import { fixableHere } from "./screen-words.mjs";
+
+/** After Not now in the prompt, the same Cloud asking for the same thing comes up again only after this long. */
+export const QUIET_AFTER_NOT_NOW_MS = 30 * 60_000;
+
+/**
+ * `prompt(env, ask, signal)`: this app's own prompt, "turn-on", "not-now", or null when it didn't show (the person is
+ * looking at that Cloud, where the card is) or `signal` closed it. `turnOn(env, ask)`: does here what the ask needs,
+ * `{ ok: true }`, `{ ok: false, reason }` (why it still can't) or `{ declined: true }`. `answered(envId)`: an answer
+ * waits to go to that Cloud.
+ */
+export function createComputerAsks({ prompt, turnOn, answered = () => {}, now = Date.now, log = () => {} }) {
+ /** Per ask: the card's Turn on taps already done here. */
+ const acted = new Map();
+ /** Per ask that came up: what closes its prompt. */
+ const prompted = new Map();
+ /** The Clouds whose prompt is up now: one at a time each, the next on a later poll. */
+ const showing = new Set();
+ const quietUntil = new Map();
+ const answers = new Map();
+
+ const answer = (envId, entry) => {
+ answers.set(envId, [...(answers.get(envId) ?? []).filter(other => other.id !== entry.id), entry]);
+ answered(envId);
+ };
+
+ async function act(env, ask) {
+ let result;
+ try { result = await turnOn(env, ask); }
+ catch (error) { log(`turning on for ${env.name}: ${error?.message ?? error}`); result = { ok: false }; }
+ if (result?.declined) answer(env.id, { id: ask.id, outcome: "declined" });
+ else if (result?.ok !== true) answer(env.id, { id: ask.id, outcome: "failed", ...(typeof result?.reason === "string" ? { reason: result.reason } : {}) });
+ }
+
+ return {
+ /** What waits to go to this Cloud with its next poll. */
+ pending: envId => answers.get(envId) ?? [],
+ /** They reached this Cloud. */
+ sent(envId, sent) {
+ const left = (answers.get(envId) ?? []).filter(entry => !sent.includes(entry));
+ if (left.length) answers.set(envId, left); else answers.delete(envId);
+ },
+ /** The asks a Cloud has open now. */
+ heard(env, asks) {
+ const open = new Map(asks.filter(ask => ask && typeof ask.id === "string").map(ask => [ask.id, ask]));
+ for (const [id, close] of prompted) if (open.get(id)?.state !== "asking") { close.abort(); prompted.delete(id); }
+ for (const ask of open.values()) {
+ const taps = Number.isSafeInteger(ask.turnOn) ? ask.turnOn : 0;
+ if (taps > (acted.get(ask.id) ?? 0)) {
+ acted.set(ask.id, taps);
+ prompted.get(ask.id)?.abort();
+ void act(env, ask);
+ continue;
+ }
+ const quiet = `${env.id}\n${ask.need}`;
+ if (ask.state !== "asking" || acted.has(ask.id) || prompted.has(ask.id) || showing.has(env.id) || !fixableHere(ask.reason) || (quietUntil.get(quiet) ?? 0) > now()) continue;
+ const close = new AbortController();
+ prompted.set(ask.id, close);
+ showing.add(env.id);
+ void Promise.resolve().then(() => prompt(env, ask, close.signal)).finally(() => showing.delete(env.id)).then(choice => {
+ if (close.signal.aborted || !choice) return;
+ if (choice === "turn-on") {
+ acted.set(ask.id, Math.max(taps, acted.get(ask.id) ?? 0));
+ answer(env.id, { id: ask.id, outcome: "turning-on" });
+ void act(env, ask);
+ return;
+ }
+ quietUntil.set(quiet, now() + QUIET_AFTER_NOT_NOW_MS);
+ answer(env.id, { id: ask.id, outcome: "declined" });
+ }, error => log(`asking about ${env.name}: ${error?.message ?? error}`));
+ }
+ },
+ /** Lending stopped for good: every prompt closes. */
+ close() { for (const close of prompted.values()) close.abort(); prompted.clear(); },
+ };
+}
diff --git a/electron/computer-asks.node-test.mjs b/electron/computer-asks.node-test.mjs
new file mode 100644
index 0000000000..f7b9346599
--- /dev/null
+++ b/electron/computer-asks.node-test.mjs
@@ -0,0 +1,183 @@
+// While this app is open, each of the person's own Clouds hears how this computer is and asks for it when a bot there
+// needs it: the app's own prompt comes up once per ask, and Turn on, there or on the card, does here what it takes.
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, 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 { ownCloud } from "./cloud-list.mjs";
+import { createComputerAsks, QUIET_AFTER_NOT_NOW_MS } from "./computer-asks.mjs";
+import { createComputerSharing } from "./computer-sharing.mjs";
+import { createLendingTarget } from "./lending-target.mjs";
+import { createAskPrompt } from "./ask-prompt.mjs";
+
+const HOME = "https://omb-u-fixture.fly.dev", TEAM = "https://omb-t-acme.fly.dev";
+const myCloud = { id: "my-cloud", name: "My Cloud", origin: HOME, home: true };
+const acme = { id: "acme", name: "Acme team", origin: TEAM, team: { id: "t-acme", role: "owner" } };
+const READY = { ready: true, lent: true, reason: null, fix: null };
+const BLOCKED = { ready: false, lent: false, reason: "blocked", fix: "start" };
+
+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}`);
+};
+
+/** A Cloud that takes asks: what this computer said each poll, and the asks it answers with. */
+function cloudHome() {
+ const json = value => ({ ok: true, status: 200, headers: { get: () => null }, body: (async function* () { yield Buffer.from(JSON.stringify(value)); })() });
+ const state = { environmentId: randomUUID(), sessionId: randomUUID(), connects: [], polls: [], asks: [], version: 0 };
+ state.say = asks => { state.asks = asks; state.version++; };
+ state.fetch = async (url, init) => {
+ const route = new URL(url).pathname;
+ if (route === "/api/auth/session") return json({ kind: "session", id: state.sessionId, scopes: ["admin", "client"], cloudHome: true });
+ if (route === "/.well-known/openmausbot/environment") {
+ return json({ environmentId: state.environmentId, capabilities: { sharedComputers: true, lendingDetails: true, deviceLink: true, myChromeLink: true, computerAsks: 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 === "/api/shared-computers/asks") {
+ state.polls.push(body);
+ if (body.heard === state.version) await delay(40, undefined, { signal: init?.signal }).catch(() => {});
+ init?.signal?.throwIfAborted();
+ return json({ version: state.version, asks: state.asks });
+ }
+ if (route.endsWith("/poll")) { await delay(40, undefined, { signal: init?.signal }).catch(() => {}); init?.signal?.throwIfAborted(); return json({ job: null }); }
+ return json({ ok: true });
+ };
+ return state;
+}
+
+function session() {
+ const state = { status: "connected", account: { id: "acct_1" }, machine: { status: "ready", origin: HOME }, clouds: [
+ { id: "c-home", origin: HOME, teamId: null, role: "owner", primary: true },
+ { id: "c-team", origin: TEAM, teamId: "t-acme", role: "owner" },
+ ] };
+ return { state: () => state, isOwnCloud: origin => state.machine?.origin === origin || state.clouds.some(cloud => ownCloud(cloud) && cloud.origin === origin) };
+}
+
+async function computer(t, { homes, places = [myCloud], screen = () => READY, prompt = async () => null, startScreen = async () => READY, confirmTerminal = async () => false }) {
+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-computer-asks-")));
+ t.after(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }));
+ const account = session();
+ const target = createLendingTarget({ account: () => account, environments: () => places });
+ const sharing = createComputerSharing({
+ file: path.join(dir, "profile", "computer-sharing.json"), environments: () => places, enabled: async () => false, home: path.join(dir, "home"),
+ fetch: (url, init) => homes[new URL(url).origin].fetch(url, init),
+ cloud: target.cloud, myCloud: target.environment, ownClouds: target.places, screen, prompt, startScreen, confirmTerminal,
+ hostControl: async () => ({ renew: async () => {}, release: async () => {} }),
+ WebSocket: class { close() {} send() {} },
+ });
+ t.after(() => sharing.close());
+ return sharing;
+}
+
+const ask = (fields = {}) => ({ id: "ask-1", need: "screen", reason: "paused", bot: "Scout", why: "Open the invoice in Excel", state: "asking", turnOn: 0, ...fields });
+
+test("paused, this computer still tells its own Cloud so, and the card's Turn on resumes it", async t => {
+ const homes = { [HOME]: cloudHome() };
+ const prompts = [];
+ const sharing = await computer(t, { homes, prompt: async (env, entry) => { prompts.push([env.id, entry.id]); return null; } });
+ sharing.start();
+ await until(() => homes[HOME].connects.length === 1, "lending to start");
+ sharing.pause();
+ await until(() => homes[HOME].polls.some(poll => poll.paused === true), "My Cloud to hear that this computer is paused");
+ assert.deepEqual(homes[HOME].polls.at(-1).screen, { ready: true, reason: null });
+ homes[HOME].say([ask()]);
+ await until(() => prompts.length === 1, "the app's own prompt");
+ homes[HOME].say([ask({ state: "turning-on", turnOn: 1 })]);
+ await until(() => !sharing.paused(), "Turn on to resume this computer");
+ await until(() => homes[HOME].connects.length === 2, "lending to come back");
+ assert.equal(homes[HOME].connects[1].computer, true);
+ await delay(150);
+ assert.equal(prompts.length, 1, "one prompt per ask");
+});
+
+test("screen control isn't running: Turn on starts it, and a start that fails tells the Cloud why", async t => {
+ const homes = { [HOME]: cloudHome() };
+ let status = BLOCKED, starts = 0, fixed = false;
+ const sharing = await computer(t, { homes, screen: () => status, startScreen: async () => { starts++; if (fixed) status = READY; return status; } });
+ sharing.start();
+ await until(() => homes[HOME].polls.some(poll => poll.screen.reason === "blocked"), "My Cloud to hear why apps and screen aren't lent");
+ homes[HOME].say([ask({ reason: "blocked", state: "turning-on", turnOn: 1 })]);
+ await until(() => homes[HOME].polls.some(poll => poll.answers.some(answer => answer.outcome === "failed")), "the failure to reach the Cloud");
+ assert.deepEqual(homes[HOME].polls.find(poll => poll.answers.length).answers, [{ id: "ask-1", outcome: "failed", reason: "blocked" }]);
+ assert.equal(starts, 1);
+ fixed = true;
+ homes[HOME].say([ask({ reason: "blocked", state: "turning-on", turnOn: 2 })]);
+ await until(() => starts === 2, "Try again to start it again");
+ await sharing.screenChanged();
+ await until(() => homes[HOME].connects.some(connect => connect.computer === true), "apps and screen to be lent");
+ await until(() => homes[HOME].polls.at(-1).screen.ready === true, "the Cloud to hear it works");
+});
+
+test("the app's own prompt: Turn on there acts at once, Not now keeps it quiet for that Cloud and need", async () => {
+ const answers = [], acted = [];
+ let choice = "turn-on";
+ const prompts = [];
+ const asks = createComputerAsks({ prompt: async (_env, entry) => { prompts.push(entry.id); return choice; }, turnOn: async (_env, entry) => { acted.push(entry.id); return { ok: true }; },
+ answered: () => {}, now: () => 1_000 });
+ const env = { id: "my-cloud", name: "My Cloud" };
+ asks.heard(env, [ask()]);
+ await until(() => acted.length === 1, "Turn on to act");
+ answers.push(...asks.pending(env.id));
+ assert.deepEqual(answers, [{ id: "ask-1", outcome: "turning-on" }]);
+ asks.sent(env.id, answers);
+ asks.heard(env, [ask({ state: "turning-on" })]);
+ await delay(10);
+ assert.deepEqual([prompts, acted], [["ask-1"], ["ask-1"]], "nothing comes up or runs twice");
+
+ choice = "not-now";
+ asks.heard(env, [ask({ id: "ask-2" })]);
+ await until(() => asks.pending(env.id).length === 1, "Not now to go back");
+ assert.deepEqual(asks.pending(env.id), [{ id: "ask-2", outcome: "declined" }]);
+ asks.heard(env, [ask({ id: "ask-3" })]);
+ asks.heard(env, [ask({ id: "ask-4", need: "terminal", reason: "terminal-off" })]);
+ await delay(10);
+ assert.deepEqual(prompts, ["ask-1", "ask-2", "ask-4"], `quiet for ${QUIET_AFTER_NOT_NOW_MS / 60_000} minutes for the same need only`);
+ asks.heard(env, [ask({ id: "ask-5", reason: "starting" })]);
+ await delay(10);
+ assert.equal(prompts.includes("ask-5"), false, "nothing to turn on while it starts by itself");
+});
+
+test("a prompt closes when the ask was answered elsewhere, and doesn't come up while the person looks at that Cloud", async () => {
+ const closed = [];
+ let shownTimes = 0;
+ const asks = createComputerAsks({ prompt: (_env, _entry, signal) => { shownTimes++; return new Promise(resolve => signal.addEventListener("abort", () => { closed.push(true); resolve(null); })); },
+ turnOn: async () => ({ ok: true }) });
+ const env = { id: "my-cloud", name: "My Cloud" };
+ asks.heard(env, [ask()]);
+ await delay(5);
+ asks.heard(env, [ask()]);
+ asks.heard(env, [ask()]);
+ await delay(5);
+ assert.equal(shownTimes, 1, "the same ask heard again while its prompt is up never shows another");
+ asks.heard(env, [ask(), ask({ id: "ask-other", need: "folders" })]);
+ await delay(5);
+ assert.equal(shownTimes, 1, "one prompt at a time for a Cloud: another ask waits until it closes");
+ asks.heard(env, []);
+ await until(() => closed.length === 1, "the prompt to close");
+
+ const shown = [];
+ const dialog = { showMessageBox: async (...args) => { shown.push(args); return { response: 0 }; } };
+ const focused = { isDestroyed: () => false, isFocused: () => true, isVisible: () => true, show: () => {}, webContents: { getURL: () => `${HOME}/chat` } };
+ const prompt = createAskPrompt({ dialog, window: () => focused, platform: "win32" });
+ assert.equal(await prompt({ id: "my-cloud", name: "My Cloud", origin: HOME }, ask(), new AbortController().signal), null, "the card is right there");
+ assert.equal(await prompt({ id: "client", name: "Client A", origin: "https://omb-c-a.fly.dev" }, ask(), new AbortController().signal), "turn-on");
+ assert.equal(shown.at(-1).length, 1, "a PC's prompt has no parent window, so it shows even with the app in the tray");
+ const mac = createAskPrompt({ dialog, window: () => null, platform: "darwin" });
+ assert.equal(await mac({ id: "client", name: "Client A", origin: "https://omb-c-a.fly.dev" }, ask(), new AbortController().signal), null,
+ "on a Mac only a window's sheet can be closed again, so no window, no prompt");
+});
+
+test("a Team Cloud never hears this computer", async t => {
+ const homes = { [HOME]: cloudHome(), [TEAM]: cloudHome() };
+ const sharing = await computer(t, { homes, places: [myCloud, acme] });
+ sharing.start();
+ await until(() => homes[HOME].polls.length > 0, "My Cloud to hear this computer");
+ await delay(100);
+ assert.equal(homes[TEAM].polls.length, 0);
+});
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mts
index 597a107c17..99717b1e4c 100644
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@ -41,13 +41,35 @@ export interface CloudLendingState {
/** Commands may be run on this computer as the person. */
terminal?: boolean;
}
+/** Computer control's state as lending reads it. */
+export interface ScreenStatus {
+ ready: boolean;
+ lent: boolean;
+ reason: "starting" | "permissions" | "blocked" | "off" | "not-running" | "unsupported" | null;
+ fix: "start" | "allow" | null;
+ message?: string;
+}
+/** A bot on one of the person's own Clouds needs this computer and can't use it now. */
+export interface ComputerAsk {
+ id: string;
+ need: "screen" | "folders" | "terminal";
+ reason: string;
+ bot: string;
+ why?: string;
+ state: "asking" | "turning-on" | "failed";
+ /** Taps on the card's Turn on so far. */
+ turnOn: number;
+}
/** What lending tells the menu-bar item: the Clouds lent to (while paused, the ones it would lend to) and using it now. */
export interface LendingSummary {
lending: string[];
clouds: string[];
using: string[];
paused: boolean;
+ terminal?: boolean;
busy: { env: string; action: string } | null;
+ /** Computer control's latest state, null until it is first read. */
+ screen: ScreenStatus | null;
}
export interface AutomaticGrant { folders: SharedFolder[]; screen: boolean; internet: true; chrome: true; terminal: false }
export type CloudLendingVerdict = { allow: true } | { pause: string } | { stop: "signed-out" | "account-changed" | "machine-changed" };
@@ -98,10 +120,18 @@ export function createComputerSharing(options: {
myCloud?: () => Workspace | null;
/** The saved servers that are the verified session's own Clouds, never a Team Cloud: each is lent this computer by itself. */
ownClouds?: () => Workspace[];
- /** Apps and screen can be lent here: computer control works, or only macOS's permissions are missing. */
- screen?: () => boolean | Promise<boolean>;
+ /** Computer control's state; its `lent` says whether apps and screen are lent: computer control works, or only macOS's
+ * permissions are missing. */
+ screen?: () => boolean | ScreenStatus | Promise<boolean | ScreenStatus>;
/** A Cloud's bot needs apps and screen while computer control isn't running: asks macOS for what it lacks. */
askForScreen?: (connection: unknown) => void;
+ /** This app's own prompt for an ask: "turn-on", "not-now", or null when it didn't show or `signal` closed it. */
+ prompt?: (env: Workspace, ask: ComputerAsk, signal: AbortSignal) => Promise<"turn-on" | "not-now" | null>;
+ /** Starts computer control again; its state after. */
+ startScreen?: () => Promise<ScreenStatus | null>;
+ /** Turns on running commands once the person confirms it on this computer; true when they did. */
+ confirmTerminal?: () => Promise<boolean>;
+ log?: (line: string) => void;
}): {
state(id: string): SharingState;
activity(id?: string, limit?: number): LendingActivityEntry[];
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index 5b6ce4bf84..a1c7971487 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -12,6 +12,7 @@ import { cuaUnavailable, SCREEN_LOCKED } from "./lent-screen-failures.mjs";
import { createLentScreenPresence } from "./lent-screen-presence.mjs";
import { BACKGROUND_HEADERS, CloudAsleepError, asleepAnswer, createCloudPowerGate } from "./cloud-power.mjs";
import { linkUrl, runDeviceLink } from "./device-link.mjs";
+import { createComputerAsks } from "./computer-asks.mjs";
import { LINK_ASLEEP, linkPath } from "./device-link-protocol.mjs";
import { shareableDrive } from "./shared-drives.mjs";
@@ -184,15 +185,22 @@ const BROWSE_NOTE_MS = 10 * 60_000;
* resumes by itself; at most every 15 minutes. `linkHeaders(env)`: the device link's sign-in, as the poll's fetch
* carries it (the session cookie). `myCloud()`: the saved server that is the person's own My Cloud, which the move's
* project folders are lent to. `ownClouds()`: the saved servers that are the verified session's own Clouds, never a
- * Team Cloud: each is lent this computer by itself (automaticGrant) unless lending is paused. `screen()`: whether apps
- * and screen can be lent here: computer control works, or only macOS's permissions are missing, which
- * `askForScreen(connection)` asks macOS for when a Cloud's bot first needs them. `cloudPower(origin)`: the Admin's word on
- * another Cloud of the person's own (the Clouds list's `power`), so a sleeping one is never dialled. */
+ * Team Cloud: each is lent this computer by itself (automaticGrant) unless lending is paused. `screen()`: computer
+ * control's state, whose `lent` says whether apps and screen are lent: computer control
+ * works, or only macOS's permissions are missing, which `askForScreen(connection)` asks macOS for when a Cloud's bot
+ * first needs them. `cloudPower(origin)`: the Admin's word on another Cloud of the person's own (the Clouds list's
+ * `power`), so a sleeping one is never dialled. While this app is open, paused or not, each of those Clouds hears how
+ * this computer is and asks for it when a bot there needs it: `prompt(env, ask, signal)` shows the ask in this app's
+ * own prompt, `startScreen()` starts computer control again (its state after), and `confirmTerminal()` turns on
+ * running commands once the person confirms it here. */
export function createComputerSharing({ file, fetch: fetchImpl, environments, cuaConnection, hostControl, screenLocked = () => false, idleSeconds = () => null, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),
- linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {}, cloudPower = () => null }) {
+ linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {}, cloudPower = () => null,
+ prompt = async () => null, startScreen = async () => null, confirmTerminal = async () => false, log = () => {} }) {
const protectedRoots = [path.dirname(file), ...protectedPaths.filter(entry => typeof entry === "string" && entry), ...personalSecretPaths(home)];
const activity = createLendingActivity(activityFile ?? path.join(path.dirname(file), "lending-activity.jsonl"));
const presence = createLentScreenPresence({ idleSeconds, now });
+ /** Computer control's latest state, for the icon's menu; null until it is first read. */
+ let screenNow = null;
let records = {};
let paused = false;
/** The Cloud account that confirmed lending the terminal; another account signed in here gets none until it confirms. */
@@ -226,8 +234,17 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
paused,
terminal: terminalAccount !== null && terminalAccount === signedInAccount(),
busy: executing ?? (browsing ? { env: browsing, action: "internet" } : null),
+ screen: screenNow,
};
};
+ /** Whether apps and screen are lent now; the icon's menu follows any change in why not. */
+ const readScreen = () => Promise.resolve().then(screen).then(status => status, () => null).then(status => {
+ const next = status && typeof status === "object" ? status : null;
+ const before = JSON.stringify(screenNow);
+ screenNow = next;
+ if (JSON.stringify(next) !== before) changed();
+ return status === true || next?.lent === true;
+ });
/** Each site My Cloud's browsers opened through this computer, or that its check refused, as activity. */
const noted = new Map();
const browsed = env => (target, result) => {
@@ -319,7 +336,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
.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, edits: descriptor.capabilities?.fileEdits === true };
+ 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, edits: descriptor.capabilities?.fileEdits === true, asks: descriptor.capabilities?.computerAsks === true };
};
const identity = async env => {
await requireEnabled();
@@ -594,7 +611,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
if (closed || paused || !ownClouds().some(verifiedCloud)) return;
const [[homeFolder = null], screenLent, projectFolders] = await Promise.all([
lendable([{ id: randomUUID(), path: home, write: true, home: true }]),
- Promise.resolve().then(screen).then(ready => ready === true, () => false),
+ readScreen(),
lendable(projects.map(where => ({ id: randomUUID(), path: where, write: true }))),
]);
for (const env of ownClouds()) {
@@ -608,6 +625,80 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
else if (!running.has(env.id) && validRecord(kept) && cloudLendingVerdict(kept.cloud, cloud(env), env).allow) run(env, kept);
}
};
+ /** This computer as the person's own Clouds hear it: paused, and why apps and screen or commands aren't lent. */
+ const thisComputer = async () => {
+ const status = await Promise.resolve().then(screen).then(value => value && typeof value === "object" ? value : null, () => null);
+ return { name: os.hostname().slice(0, 120) || "This computer", platform: LENT_PLATFORMS.has(process.platform) ? process.platform : null, paused,
+ screen: { ready: status?.ready === true, reason: status && !status.ready ? status.reason ?? null : null }, terminal: terminalAccount !== null && terminalAccount === signedInAccount() };
+ };
+ /** Every Cloud of the person's own may use this computer again. */
+ const resumeLending = () => {
+ if (!paused || closed) return;
+ paused = false;
+ try { store(records); } catch {}
+ 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);
+ }
+ changed();
+ wakeAsking();
+ return lendAutomatically();
+ };
+ /** Turn on, from this app's prompt or the card: what the ask needs, done here. */
+ const turnOn = async (env, ask) => {
+ if (paused) await resumeLending();
+ if (ask.need === "screen") {
+ let status = await Promise.resolve().then(screen).catch(() => null);
+ if (status && typeof status === "object" && !status.ready) status = await startScreen();
+ if (status && typeof status === "object" && !status.ready) return { ok: false, reason: status.reason ?? "not-running" };
+ }
+ if (ask.need === "terminal" && terminalAccount !== signedInAccount() && !(await confirmTerminal())) return { declined: true };
+ return { ok: true };
+ };
+ /** Per Cloud that takes asks: what stops its poll for good, and what ends its current poll early. */
+ const asking = new Map();
+ /** A Cloud too old to take asks is asked again only after this long. */
+ const olderClouds = new Map();
+ const asks = createComputerAsks({ prompt: (env, ask, signal) => prompt(env, ask, signal), turnOn, log, answered: id => asking.get(id)?.wake() });
+ const keepAsking = async (env, entry) => {
+ const { signal } = entry.stop;
+ let heard = -1, failures = 0, supported = null;
+ while (!signal.aborted && !closed) {
+ if (sleepsHere(env) && sleepGate(env).asleep()) { await sleepGate(env).wait(signal); continue; }
+ const early = new AbortController();
+ entry.wake = () => early.abort();
+ const answers = [...asks.pending(env.id)];
+ try {
+ supported ??= (await describe(env)).asks;
+ if (!supported) { olderClouds.set(env.id, now()); return; }
+ const news = await request(env, "/api/shared-computers/asks", { ...await thisComputer(), heard, answers }, AbortSignal.any([signal, early.signal, sleepGate(env).signal()]));
+ asks.sent(env.id, answers);
+ failures = 0;
+ if (Number.isSafeInteger(news?.version)) heard = news.version;
+ asks.heard(env, Array.isArray(news?.asks) ? news.asks : []);
+ } catch (error) {
+ if (signal.aborted) return;
+ if (early.signal.aborted || error instanceof CloudAsleepError) continue;
+ if (error?.status === 404) { olderClouds.set(env.id, now()); return; }
+ failures++;
+ try { await delay(LINK_RETRY_MS[Math.min(failures, LINK_RETRY_MS.length - 1)], undefined, { signal }); } catch { return; }
+ }
+ }
+ };
+ /** Each verified own Cloud hears this computer while this app is open; the others don't. */
+ const syncAsking = () => {
+ const wanted = closed ? new Set() : new Set(ownClouds().filter(verifiedCloud).map(env => env.id));
+ for (const [id, entry] of asking) if (!wanted.has(id)) { entry.stop.abort(); asking.delete(id); }
+ for (const env of ownClouds()) {
+ if (!wanted.has(env.id) || asking.has(env.id) || now() - (olderClouds.get(env.id) ?? -Infinity) < 30 * 60_000) continue;
+ const entry = { stop: new AbortController(), wake: () => {} };
+ asking.set(env.id, entry);
+ void keepAsking(env, entry).catch(() => {}).finally(() => { if (asking.get(env.id) === entry) asking.delete(env.id); });
+ }
+ };
+ /** This computer changed: each Cloud hears it now, not at its next poll. */
+ const wakeAsking = () => { for (const entry of asking.values()) entry.wake(); };
/** The Clouds whose grant the automatic pass runs: it runs a kept grant only once it lends what it should. */
const lentAutomatically = () => new Set(ownClouds().map(env => env.id));
/** One pass at a time: a change while one runs asks for one more after it. */
@@ -615,7 +706,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
const lendAutomatically = (projects = [], target = null) => {
if (passQueued && !projects.length) return passing;
passQueued = true;
- passing = passing.then(() => { passQueued = false; return automaticPass(projects, target); }).catch(() => {});
+ passing = passing.then(() => { passQueued = false; return automaticPass(projects, target); }).catch(() => {}).finally(syncAsking);
return passing;
};
return {
@@ -679,19 +770,9 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
status.set(env.id, { connected: false, problem: "paused" });
}
changed();
+ wakeAsking();
},
- resume() {
- if (!paused || closed) return;
- paused = false;
- try { store(records); } catch {}
- 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);
- }
- changed();
- return lendAutomatically();
- },
+ resume: () => resumeLending(),
/** Whether every Cloud of the signed-in account's own may run commands here as this user, across restarts too. */
lendTerminal(on) {
const account = on === true ? signedInAccount() : null;
@@ -703,10 +784,11 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
// A Cloud the pass can't verify now keeps its grant until it can, so its commands stop here.
if (!account) for (const [id, grant] of Object.entries(records)) if (grant?.cloud && grant.terminal === true) stop(id);
changed();
+ wakeAsking();
return lendAutomatically();
},
/** Computer control started or stopped: apps and screen follow. */
- screenChanged: () => lendAutomatically(),
+ screenChanged: () => readScreen().then(() => { wakeAsking(); return lendAutomatically(); }),
revoke(env) {
changeGrant(env.id);
disconnect(env, records[env.id]);
@@ -741,6 +823,6 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
}
void lendAutomatically();
},
- close() { closed = true; for (const id of running.keys()) stop(id); },
+ close() { closed = true; for (const id of running.keys()) stop(id); syncAsking(); asks.close(); },
};
}
diff --git a/electron/cua-failure.mjs b/electron/cua-failure.mjs
new file mode 100644
index 0000000000..c055abe285
--- /dev/null
+++ b/electron/cua-failure.mjs
@@ -0,0 +1,10 @@
+/** @trycua/cua-driver 0.28.2's errors carry only their kind as a message ("EmbeddedDriverError.Spawn"); the reason the
+ * system gave, the exit code or the timeout is in `inner`. */
+export function driverFailure(error) {
+ const kind = typeof error?.tag === "string" ? error.tag : null;
+ const inner = error?.inner && typeof error.inner === "object" ? error.inner : null;
+ if (!kind || !inner) return String(error?.message ?? error);
+ const said = Object.entries(inner).filter(([, value]) => value !== undefined && value !== null)
+ .map(([key, value]) => `${key} ${String(value)}`);
+ return said.length ? `${kind}: ${said.join("; ")}` : kind;
+}
diff --git a/electron/cua-windows-isolation.test.mjs b/electron/cua-windows-isolation.test.mjs
index a0380cefbb..f9ff155102 100644
--- a/electron/cua-windows-isolation.test.mjs
+++ b/electron/cua-windows-isolation.test.mjs
@@ -66,6 +66,35 @@ describe("Windows owned CUA host", () => {
expect(fixture.hosts[0].uniffiDestroy).toHaveBeenCalledOnce();
});
+ it("tries a start that failed for a passing reason again by itself, twice, and never a blocked helper", async () => {
+ vi.useFakeTimers();
+ try {
+ const exited = Object.assign(new Error("EmbeddedDriverError.ExitedBeforeReady"), { tag: "ExitedBeforeReady", inner: { code: 1 } });
+ fixture.start.mockRejectedValueOnce(exited).mockRejectedValueOnce(exited);
+ await expect(cua.startCua()).resolves.toMatchObject({ mode: "unavailable", reason: "embedded host failed: ExitedBeforeReady: code 1" });
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(fixture.start).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(fixture.start).toHaveBeenCalledTimes(3);
+ expect(JSON.parse(readFileSync(join(fixture.home, "cua-connection.json"), "utf8"))).toMatchObject({ mode: "embedded" });
+
+ fixture.start.mockReset();
+ fixture.start.mockRejectedValue(Object.assign(new Error("EmbeddedDriverError.Spawn"), { tag: "Spawn", inner: { reason: "Access is denied. (os error 5)" } }));
+ await expect(cua.startCua()).resolves.toMatchObject({ mode: "unavailable", reason: expect.stringContaining("Access is denied") });
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(fixture.start, "a blocked helper waits for the person").toHaveBeenCalledTimes(1);
+
+ fixture.start.mockReset();
+ fixture.start.mockRejectedValue(exited);
+ await cua.startCua();
+ await cua.stopCua();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(fixture.start, "Stop cancels a retry").toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("cancels a stalled start when the desktop stops", async () => {
fixture.start.mockImplementation(({ signal }) => new Promise((_, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
diff --git a/electron/cua.mjs b/electron/cua.mjs
index 947378d0ca..6a06379deb 100644
--- a/electron/cua.mjs
+++ b/electron/cua.mjs
@@ -12,6 +12,7 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
import localOriginModule from "./local-origin.cjs";
import { createLocalComputerGrant } from "./local-computer-grant.mjs";
+import { driverFailure } from "./cua-failure.mjs";
const { localOnly } = localOriginModule;
@@ -27,7 +28,7 @@ const {
reapStaleAppImageCuaBundles,
stageAppImageCuaBundle,
} = require("./cua-linux-bundle.cjs");
-const { linuxLocalControlSupport } = require("./capabilities.cjs");
+const { driverBlocked, linuxLocalControlSupport } = require("./capabilities.cjs");
const INSTALLED_DRIVER = "/Applications/CuaDriver.app/Contents/MacOS/cua-driver";
const STANDALONE_SOCKET = path.join(
@@ -46,6 +47,10 @@ const WIN_INSTALLED_DRIVERS = [
];
let embeddedHost = null;
let startupAbort = null;
+/** On Windows a start that failed for a reason that passes (a slow first start while the system scans the new helper)
+ * is tried again by itself after these waits; a blocked or missing helper is not. */
+const RETRY_AFTER_MS = [15_000, 60_000];
+let retryTimer = null;
let lifecycleGeneration = 0;
let macRetry = null;
let linuxRuntime = null;
@@ -259,8 +264,10 @@ async function startEmbedded(binary, signal) {
}
}
-export async function startCua() {
+export async function startCua({ attempt = 0 } = {}) {
if (process.platform === "linux") return ensureLinuxRuntime().initialize();
+ clearTimeout(retryTimer);
+ retryTimer = null;
lifecycleGeneration++;
startupAbort?.abort();
startupAbort = new AbortController();
@@ -288,13 +295,13 @@ export async function startCua() {
signal.throwIfAborted();
nextConnection = {
mode: "unavailable",
- reason: `embedded host failed: ${err?.message ?? err}; standalone launch failed: ${standaloneError?.message ?? standaloneError}`,
+ reason: `embedded host failed: ${driverFailure(err)}; standalone launch failed: ${standaloneError?.message ?? standaloneError}`,
};
}
if (!nextConnection) {
nextConnection = {
mode: "unavailable",
- reason: `embedded host failed: ${err?.message ?? err}`,
+ reason: `embedded host failed: ${driverFailure(err)}`,
};
}
}
@@ -316,6 +323,10 @@ export async function startCua() {
}
signal.throwIfAborted();
+ if (process.platform === "win32" && nextConnection.mode === "unavailable" && !driverBlocked(nextConnection.reason) && attempt < RETRY_AFTER_MS.length) {
+ retryTimer = setTimeout(() => { retryTimer = null; void startCua({ attempt: attempt + 1 }).catch(() => {}); }, RETRY_AFTER_MS[attempt]);
+ retryTimer.unref?.();
+ }
return persistAndNotify(nextConnection);
}
@@ -337,6 +348,8 @@ export async function cuaPermissionsStatus() {
}
export async function stopCua() {
+ clearTimeout(retryTimer);
+ retryTimer = null;
lifecycleGeneration++;
startupAbort?.abort();
startupAbort = null;
diff --git a/electron/lend-automatically.node-test.mjs b/electron/lend-automatically.node-test.mjs
index 7700205a26..a45fabf41f 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"], using: [], paused: true, terminal: false, busy: null });
+ assert.deepEqual(mac.summaries.at(-1), { lending: [], clouds: ["My Cloud", "Client A"], using: [], paused: true, terminal: false, 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);
@@ -473,7 +473,7 @@ test("the menu-bar item: which Clouds are using this Mac, Pause or Resume, the t
indicator.update({ clouds: [], using: [], paused: true });
assert.equal(trays[0].destroyed, true, "gone once there is no Cloud to resume");
assert.deepEqual(indicatorText({ clouds: ["A", "B", "C"], using: ["A", "B", "C"], paused: false }, "PC"),
- { line: "A, B and C are using this PC", title: "3 Clouds are using this PC" });
+ { line: "A, B and C are using this PC", title: "3 Clouds are using this PC", screen: null });
});
test("See activity shows this computer's own record in the app's language: every value escaped, no script, nothing loaded", async () => {
diff --git a/electron/lending-dialogs.mjs b/electron/lending-dialogs.mjs
index 630bed36ff..f26099578d 100644
--- a/electron/lending-dialogs.mjs
+++ b/electron/lending-dialogs.mjs
@@ -24,10 +24,11 @@ export function serverAccessDetail(env, { folders, terminal, computer }) {
export function createLendingDialogs({ dialog, window, validate, isHome = async () => false }) {
let askingTerminal = false;
return {
- /** Turning the terminal on runs `lend` only once the person confirms, one question at a time; turning it off never asks. */
+ /** Turning the terminal on runs `lend` only once the person confirms, one question at a time; turning it off never asks.
+ * True once `lend` ran. */
async lendTerminal(on, lend) {
if (on) {
- if (askingTerminal) return;
+ if (askingTerminal) return false;
askingTerminal = true;
try {
const { response } = await dialog.showMessageBox({
@@ -35,10 +36,11 @@ export function createLendingDialogs({ dialog, window, validate, isHome = async
message: "Let your Clouds run commands on this computer?",
detail: "Bots on your own Clouds could run any command on this computer as you, including reading and changing any file you can. You can turn this off from the OpenMausBot icon's menu.",
});
- if (response !== 0) return;
+ if (response !== 0) return false;
} finally { askingTerminal = false; }
}
await lend();
+ return true;
},
/** The folder or drive the person picks, read only and checked as every lent folder is; null when they cancel. The
* home folder is lent only when it is picked here and confirmed here: the folders above it and the system disk never are. */
diff --git a/electron/lending-indicator.mjs b/electron/lending-indicator.mjs
index 2600f377b0..04ad07df72 100644
--- a/electron/lending-indicator.mjs
+++ b/electron/lending-indicator.mjs
@@ -1,3 +1,5 @@
+import { screenFixLabel, screenLine } from "./screen-words.mjs";
+
/** The device word the person knows this computer by. */
export const deviceWord = (platform = process.platform) => platform === "darwin" ? "Mac" : platform === "win32" ? "PC" : "computer";
@@ -5,24 +7,30 @@ const listed = names => names.length < 3 ? names.join(" and ") : `${names.slice(
/** Beside the icon there is room for two names at most. */
const short = names => names.length < 3 ? listed(names) : `${names.length} Clouds`;
-export function indicatorText({ clouds, using, paused }, device) {
+/** `screen`: computer control's state; while it isn't ready the line says what the Clouds
+ * can't use, and `screen` why. */
+export function indicatorText({ clouds, using, paused, screen = null }, device) {
const it = `this ${device}`;
- if (paused) return { line: `Paused: ${listed(clouds)} can't use ${it}`, title: "Paused" };
- if (using.length) return { line: `${listed(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, title: `${short(using)} ${using.length > 1 ? "are" : "is"} using ${it}` };
- return { line: `${listed(clouds)} can use ${it}`, title: "" };
+ if (paused) return { line: `Paused: ${listed(clouds)} can't use ${it}`, title: "Paused", screen: null };
+ const why = screenLine(screen, device);
+ if (using.length) return { line: `${listed(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, title: `${short(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, screen: why };
+ return { line: why ? `${listed(clouds)} can use ${it}, but not its apps and screen` : `${listed(clouds)} can use ${it}`, title: "", screen: why };
}
-export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPause, onResume, onActivity, onTerminal, device = deviceWord() }) {
+export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPause, onResume, onActivity, onTerminal, onStartScreen = () => {}, device = deviceWord() }) {
let tray = null;
let shown = null;
const draw = view => {
if (!tray || tray.isDestroyed()) return;
- const { line, title } = indicatorText(view, device);
- tray.setToolTip(`OpenMausBot: ${line}`);
+ const { line, title, screen } = indicatorText(view, device);
+ const fix = screen ? screenFixLabel(view.screen) : null;
+ tray.setToolTip(`OpenMausBot: ${line}${screen ? `. ${screen}` : ""}`);
// Electron shows a tray title beside the icon on macOS only.
tray.setTitle?.(title);
tray.setContextMenu(Menu.buildFromTemplate([
{ label: line, enabled: false },
+ ...screen ? [{ label: screen, enabled: false }] : [],
+ ...fix ? [{ label: fix, click: () => onStartScreen() }] : [],
{ type: "separator" },
view.paused ? { label: "Resume", click: () => onResume() } : { label: "Pause", click: () => onPause() },
...view.paused ? [] : [{ label: `Let Clouds run commands on this ${device}`, type: "checkbox", checked: view.terminal,
@@ -32,8 +40,9 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPa
]));
};
return {
- update({ clouds = [], using = [], paused = false, terminal = false }) {
- const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true, terminal: terminal === true };
+ update({ clouds = [], using = [], paused = false, terminal = false, screen = null }) {
+ const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true, terminal: terminal === true,
+ screen: screen ? { ready: screen.ready === true, reason: screen.reason ?? null, fix: screen.fix ?? null, ...(screen.message ? { message: screen.message } : {}) } : null };
if (shown && JSON.stringify(next) === JSON.stringify(shown)) return;
shown = next;
if (!next.clouds.length) { if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; return; }
diff --git a/electron/lent-screen-failures.mjs b/electron/lent-screen-failures.mjs
index 36a37649dd..97fb26b91d 100644
--- a/electron/lent-screen-failures.mjs
+++ b/electron/lent-screen-failures.mjs
@@ -1,19 +1,22 @@
// Plain sentences for a lent screen that cannot work, with the fix the person can make on this computer. They reach
// the bot through the server and this computer's lending activity, so they name no path.
+import capabilitiesModule from "./capabilities.cjs";
+
+const { driverBlocked } = capabilitiesModule;
export const SCREEN_LOCKED =
"This computer's screen is locked, so its apps and screen cannot be seen or used. Unlock it and keep it unlocked while the bot works, then try again.";
export function helperMissing(platform = process.platform) {
return platform === "win32"
- ? "Computer control could not start on this PC: its helper, cua-driver.exe, is missing or blocked. Windows Security may have quarantined it: open Windows Security → Virus & threat protection → Protection history, restore or allow cua-driver.exe (or reinstall OpenMausBot), then restart OpenMausBot."
+ ? "Computer control could not start on this PC: its helper, cua-driver-background.exe or cua-driver.exe, is missing or blocked. Windows Security may have quarantined it: open Windows Security → Virus & threat protection → Protection history, restore or allow it (or reinstall OpenMausBot), then restart OpenMausBot."
: "Computer control could not start on this computer: its helper, cua-driver, is missing or blocked. Reinstall OpenMausBot, then restart it.";
}
/** `reason` is the desktop's own cua start-up failure, which never crosses to the server as written. */
export function cuaUnavailable(reason, platform = process.platform) {
const why = String(reason ?? "");
- if (/binary not found|is missing|ENOENT|EPERM|EACCES/i.test(why)) return helperMissing(platform);
+ if (driverBlocked(why)) return helperMissing(platform);
if (/Accessibility|Screen Recording|permission/i.test(why)) {
return "Computer control needs permission on this computer: allow Accessibility and Screen Recording for OpenMausBot in System Settings → Privacy & Security, then restart OpenMausBot.";
}
diff --git a/electron/main.mjs b/electron/main.mjs
index fb2baf3249..044582b09b 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -39,6 +39,7 @@ import { createLendingIndicator } from "./lending-indicator.mjs";
import { createLendingDialogs } from "./lending-dialogs.mjs";
import { createActivityWindow } from "./lending-activity-window.mjs";
import { missingPermissions } from "./lent-screen-failures.mjs";
+import { createScreenControl } from "./screen-control.mjs"; import { createAskPrompt } from "./ask-prompt.mjs";
let startupScreen = null;
let desktopTray = null;
import { collisionFreeDownloadPath, defaultSaveName, openLogsFolder, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
@@ -88,7 +89,7 @@ import capabilitiesModule from "./capabilities.cjs";
import environmentsModule from "./environments.cjs";
import localOriginModule from "./local-origin.cjs";
import { buildApplicationMenu } from "./menu.mjs";
-import { createComputerSharing, isHomeFolder, sharedCuaConnection, validateSharedFolders } from "./computer-sharing.mjs";
+import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs";
import { createHostScreenLease } from "./host-screen-lease.mjs";
import { acquireDataDirLease } from "./data-dir-lease.mjs";
import { switchLocalEnvironment } from "./environment-switch.mjs";
@@ -115,7 +116,7 @@ import { createCompanyBackups } from "./company-backups.mjs";
import { createCompanyBackupSchedule } from "./company-backup-schedule.mjs";
import { installServerSessions, reportOwnListeners } from "./server-session.mjs";
-const { desktopCapabilities, localComputerReady, nativeDesktopActions } = capabilitiesModule;
+const { desktopCapabilities, nativeDesktopActions } = capabilitiesModule;
const nativeActions = nativeDesktopActions(process.platform);
const require = createRequire(import.meta.url);
const { createDisplayMediaGuard, invokeDisplayMediaCallback, selectCaptureSource } = require(
@@ -1459,7 +1460,8 @@ function sharingController() {
fetch: (...args) => session.defaultSession.fetch(...args),
environments: () => environmentsState.environments,
enabled: refreshSharedComputersAllowed,
- cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: lendsScreen, askForScreen, power: cloudPower, cloudPower: origin => cloudAccount?.powerOf?.(origin) ?? null, reconnect: reconnectCloud,
+ cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: screenControl.now, askForScreen, power: cloudPower, cloudPower: origin => cloudAccount?.powerOf?.(origin) ?? null, reconnect: reconnectCloud,
+ prompt: createAskPrompt({ dialog, window: () => mainWindow, idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime() }), startScreen: screenControl.start, confirmTerminal: () => lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)), log: slog,
linkHeaders: async env => ({ cookie: (await session.defaultSession.cookies.get({ url: env.origin })).map(cookie => `${cookie.name}=${cookie.value}`).join("; ") }),
onChange: summary => { lendingIndicator().update(summary); loginItem.follow(summary.lending.length > 0); },
cuaConnection: () => cuaReady, screenLocked: () => powerMonitor.getSystemIdleState(1) === "locked", idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime(),
@@ -1469,14 +1471,7 @@ function sharingController() {
}
const lendingTarget = createLendingTarget({ account: () => cloudAccount, environments: () => environmentsState.environments, ownHome: () => ownHome?.home() ?? null });
-/** Apps and screen are lent once computer control works here, or on a Mac that lacks only macOS's permissions, which
- * macOS is asked for the first time a Cloud's bot needs them; read from computer control's running state. */
-async function lendsScreen() {
- if (desktopRemoteAccess) return false;
- const connection = await cuaReady.catch(() => null);
- return (sharedCuaConnection(connection) !== null && localComputerReady(process.platform, connection))
- || (process.platform === "darwin" && missingPermissions(connection?.reason).length > 0);
-}
+const screenControl = createScreenControl({ connection: () => cuaReady, remote: () => Boolean(desktopRemoteAccess), request: requestComputerUse, log: slog });
let screenAskedAt = -Infinity;
/** Computer control starts again, as Settings' Retry does, which asks macOS for what it never asked; at most every 10 minutes. */
function askForScreen(connection) {
@@ -1515,7 +1510,7 @@ let lendingTray = null;
function lendingIndicator() {
lendingTray ??= createLendingIndicator({
Tray, Menu, nativeImage, iconPath: APP_ICON, onPause: () => sharingController().pause(), onActivity: () => lendingActivity.show(),
- onResume: () => void sharingController().resume()?.catch(error => slog(`lending resume: ${error?.message ?? error}`)),
+ onResume: () => void sharingController().resume()?.catch(error => slog(`lending resume: ${error?.message ?? error}`)), onStartScreen: () => void screenControl.start(),
onTerminal: on => void lendingDialogs.lendTerminal(on, () => sharingController().lendTerminal(on)).catch(error => slog(`lending terminal: ${error?.message ?? error}`)),
});
return lendingTray;
@@ -2880,6 +2875,7 @@ async function broadcastDesktopCapabilities() {
}
setCuaStateListener((connection) => {
+ screenControl.changed(connection);
cuaReady = Promise.resolve(connection);
void computerSharing?.screenChanged();
void broadcastDesktopCapabilities().catch((error) => {
diff --git a/electron/screen-control.mjs b/electron/screen-control.mjs
new file mode 100644
index 0000000000..c04408f890
--- /dev/null
+++ b/electron/screen-control.mjs
@@ -0,0 +1,22 @@
+// Computer control as lending sees it: its state for the icon's menu and for the person's own Clouds, a start of it
+// again (from the icon's menu, or Turn on on a Cloud's card), and each change kept in the app's log.
+import { screenStatus } from "./screen-status.mjs";
+
+/** `connection()`: computer control's state as cua.mjs last published it (a promise). `request()`: start it again, which
+ * on a Mac asks macOS for what it never asked, and on Linux turns local control on. */
+export function createScreenControl({ connection, remote = () => false, request, log = () => {}, platform = process.platform }) {
+ const now = async () => screenStatus({ platform, connection: await Promise.resolve().then(connection).catch(() => null), remote: remote() });
+ return {
+ now,
+ /** Its state once it started again. */
+ async start() {
+ try { await request(); } catch (error) { log(`computer control: ${error?.message ?? error}`); }
+ return now();
+ },
+ /** Packaged on Windows nothing reads the console, so why computer control stopped is kept in the app's log. */
+ changed(next) {
+ const why = next?.reason ?? next?.message;
+ log(`computer control: ${next?.mode ?? next?.status ?? "unknown"}${why ? `: ${why}` : ""}`);
+ },
+ };
+}
diff --git a/electron/screen-status.mjs b/electron/screen-status.mjs
new file mode 100644
index 0000000000..a78363cf9c
--- /dev/null
+++ b/electron/screen-status.mjs
@@ -0,0 +1,40 @@
+// Whether this computer's apps and screen can be lent to the person's own Clouds now and, when they can't, why and the
+// one fix. Read from computer control's own state: reading it never starts or asks anything.
+import capabilitiesModule from "./capabilities.cjs";
+import { missingPermissions } from "./lent-screen-failures.mjs";
+import { sharedCuaConnection } from "./shared-cua-connection.mjs";
+
+const { driverBlocked, localComputerReady } = capabilitiesModule;
+
+/** A Linux session computer control refuses to drive (Wayland, no desktop, a driver that failed its check). */
+const LINUX_UNSUPPORTED = new Set(["linux-wayland-seat-safety-blocked", "headless-session", "unsupported-platform", "bundled-driver-invalid"]);
+
+/**
+ * `ready`: computer control works, so apps and screen are lent and used. `lent`: they are lent, which a Mac lacking only
+ * macOS's permissions also is, so a Cloud's bot can ask macOS for them. Otherwise `reason`:
+ * - "starting": computer control is still starting;
+ * - "permissions": macOS has not allowed Accessibility and Screen Recording;
+ * - "blocked": its helper is missing, or the system refused to run it;
+ * - "off": Linux control is off until the person turns it on;
+ * - "not-running": computer control stopped or failed to start;
+ * - "unsupported": it can't work in this session (Wayland, no desktop) or this app is a remote companion.
+ * `fix`: "start" (start computer control again, or turn Linux control on), "allow" (ask macOS), or null.
+ */
+export function screenStatus({ platform = process.platform, connection = null, remote = false } = {}) {
+ if (remote) return off("unsupported", null);
+ if (sharedCuaConnection(connection) !== null && localComputerReady(platform, connection)) return { ready: true, lent: true, reason: null, fix: null };
+ if (platform === "darwin" && missingPermissions(connection?.reason).length > 0) return { ready: false, lent: true, reason: "permissions", fix: "allow" };
+ if (platform === "linux") {
+ if (connection?.status === "disabled" || connection?.reasonCode === "opt-in-required") return off("off", "start");
+ if (connection?.status === "checking" || connection?.status === "starting") return off("starting", null);
+ if (LINUX_UNSUPPORTED.has(connection?.reasonCode)) return off("unsupported", null, connection?.message);
+ return off("not-running", "start");
+ }
+ if (platform !== "darwin" && platform !== "win32") return off("unsupported", null);
+ if (!connection || connection.reason === "not-started") return off("starting", null);
+ return driverBlocked(connection.reason) ? off("blocked", "start") : off("not-running", "start");
+}
+
+function off(reason, fix, message) {
+ return { ready: false, lent: false, reason, fix, ...(typeof message === "string" && message.trim() ? { message: message.trim().slice(0, 300) } : {}) };
+}
diff --git a/electron/screen-status.node-test.mjs b/electron/screen-status.node-test.mjs
new file mode 100644
index 0000000000..c80b00d767
--- /dev/null
+++ b/electron/screen-status.node-test.mjs
@@ -0,0 +1,100 @@
+// Whether this computer's apps and screen are lent to the person's own Clouds, and what the icon's menu says when they
+// aren't: read from computer control's own state on Windows, macOS and Linux.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { automaticGrant } from "./computer-sharing.mjs";
+import { createLendingIndicator, indicatorText } from "./lending-indicator.mjs";
+import { screenStatus } from "./screen-status.mjs";
+import { askPromptWords, screenFixLabel, screenLine } from "./screen-words.mjs";
+import { driverFailure } from "./cua-failure.mjs";
+
+const embedded = (extra = {}) => ({
+ mode: "embedded", socketPath: "\\\\.\\pipe\\cua-driver-1234", mcpCommand: "C:\\Program Files\\OpenMausBot\\resources\\cua-driver.exe",
+ mcpArgs: ["mcp", "--embedded", "--socket", "\\\\.\\pipe\\cua-driver-1234"], mcpEnv: { CUA_DRIVER_EMBEDDED: "1", CUA_DRIVER_HOST_BUNDLE_ID: "com.openmausbot.app" }, ...extra,
+});
+
+test("a PC lends its apps and screen once its own embedded computer control runs, and never through another driver", () => {
+ assert.deepEqual(screenStatus({ platform: "win32", connection: embedded() }), { ready: true, lent: true, reason: null, fix: null });
+ assert.equal(automaticGrant({ screen: screenStatus({ platform: "win32", connection: embedded() }).lent }).screen, true);
+ // A driver the person installed themselves answers on a pipe this app does not own.
+ const standalone = screenStatus({ platform: "win32", connection: embedded({ mode: "standalone" }) });
+ assert.deepEqual({ lent: standalone.lent, reason: standalone.reason }, { lent: false, reason: "not-running" });
+ assert.equal(automaticGrant({ screen: standalone.lent }).screen, false);
+ for (const broken of [embedded({ socketPath: "" }), embedded({ mcpArgs: ["serve"] }), embedded({ mcpEnv: { CUA_DRIVER_EMBEDDED: 1 } }), embedded({ status: "error" })]) {
+ assert.equal(screenStatus({ platform: "win32", connection: broken }).lent, false, JSON.stringify(broken));
+ }
+ assert.equal(screenStatus({ platform: "win32", connection: embedded(), remote: true }).lent, false, "a remote companion lends nothing of this computer");
+});
+
+test("why a PC's apps and screen aren't lent, and the one fix", () => {
+ const starting = screenStatus({ platform: "win32", connection: { mode: "unavailable", reason: "not-started" } });
+ assert.deepEqual({ reason: starting.reason, fix: starting.fix }, { reason: "starting", fix: null });
+ const timedOut = screenStatus({ platform: "win32", connection: { mode: "unavailable", reason: "embedded host failed: StartupTimeout: timeoutMs 10000" } });
+ assert.deepEqual({ reason: timedOut.reason, fix: timedOut.fix }, { reason: "not-running", fix: "start" });
+ for (const reason of [
+ "embedded host failed: Spawn: binaryPath C:\\OpenMausBot\\resources\\cua-driver-background.exe; reason Access is denied. (os error 5)",
+ "embedded host failed: Spawn: reason Operation did not complete successfully because the file contains a virus or potentially unwanted software. (os error 225)",
+ "cua-driver binary not found",
+ "embedded host failed: Packaged background CUA driver is missing; reinstall OpenMausBot",
+ ]) {
+ const blocked = screenStatus({ platform: "win32", connection: { mode: "unavailable", reason } });
+ assert.deepEqual({ reason: blocked.reason, fix: blocked.fix }, { reason: "blocked", fix: "start" }, reason);
+ }
+ assert.equal(screenLine(timedOut, "PC"), "Screen control isn't running on this PC");
+ assert.equal(screenFixLabel(timedOut), "Start screen control");
+ assert.equal(screenLine({ ready: false, reason: "blocked" }, "PC"), "Screen control is blocked: Windows Security may have stopped it");
+});
+
+test("a Mac lacking only macOS's permissions still lends them, so a bot's first need asks macOS; Linux control is off until turned on", () => {
+ const mac = screenStatus({ platform: "darwin", connection: { mode: "unavailable", reason: "embedded host failed: Accessibility and Screen Recording required; grant access in System Settings and restart OpenMausBot" } });
+ assert.deepEqual(mac, { ready: false, lent: true, reason: "permissions", fix: "allow" });
+ assert.equal(screenFixLabel(mac), "Allow screen control…");
+ const linux = screenStatus({ platform: "linux", connection: { schemaVersion: 1, platform: "linux", mode: "unavailable", enabled: false, status: "disabled", reasonCode: "opt-in-required" } });
+ assert.deepEqual({ lent: linux.lent, reason: linux.reason, fix: linux.fix }, { lent: false, reason: "off", fix: "start" });
+ assert.equal(screenFixLabel(linux), "Turn on screen control");
+ const wayland = screenStatus({ platform: "linux", connection: { mode: "unavailable", status: "unavailable", reasonCode: "linux-wayland-seat-safety-blocked",
+ message: "Local control is not available on Wayland yet. Sign out and choose Ubuntu on Xorg to use This computer." } });
+ assert.deepEqual({ reason: wayland.reason, fix: wayland.fix }, { reason: "unsupported", fix: null });
+ assert.equal(screenFixLabel(wayland), null, "nothing here can fix a Wayland session");
+});
+
+test("the icon's menu says plainly what the Clouds can't use, why, and offers the fix", () => {
+ const notRunning = screenStatus({ platform: "win32", connection: { mode: "unavailable", reason: "desktop-host-stopped" } });
+ assert.deepEqual(indicatorText({ clouds: ["My Cloud"], using: [], paused: false, screen: notRunning }, "PC"),
+ { line: "My Cloud can use this PC, but not its apps and screen", title: "", screen: "Screen control isn't running on this PC" });
+ assert.deepEqual(indicatorText({ clouds: ["My Cloud"], using: [], paused: false, screen: { ready: true, reason: null } }, "PC"),
+ { line: "My Cloud can use this PC", title: "", screen: null });
+ assert.equal(indicatorText({ clouds: ["My Cloud"], using: [], paused: true, screen: notRunning }, "PC").screen, null, "paused says only that");
+
+ const trays = [];
+ let started = 0;
+ class Tray { constructor() { trays.push(this); } on() {} setToolTip(tip) { this.tip = tip; } setTitle() {} setContextMenu(menu) { this.menu = menu; } isDestroyed() { return false; } destroy() {} }
+ const indicator = createLendingIndicator({ Tray, Menu: { buildFromTemplate: items => items }, nativeImage: { createFromPath: () => ({ resize: () => ({}) }) }, iconPath: "",
+ onPause: () => {}, onResume: () => {}, onActivity: () => {}, onTerminal: () => {}, onStartScreen: () => { started++; }, device: "PC" });
+ indicator.update({ clouds: ["My Cloud"], screen: notRunning });
+ const [line, why, fix] = trays[0].menu;
+ assert.deepEqual([line.label, line.enabled, why.label, why.enabled, fix.label], ["My Cloud can use this PC, but not its apps and screen", false, "Screen control isn't running on this PC", false, "Start screen control"]);
+ assert.equal(trays[0].tip, "OpenMausBot: My Cloud can use this PC, but not its apps and screen. Screen control isn't running on this PC");
+ fix.click();
+ assert.equal(started, 1, "one click starts screen control");
+ indicator.update({ clouds: ["My Cloud"], screen: { ready: true, lent: true, reason: null, fix: null } });
+ assert.deepEqual(trays[0].menu.filter(item => item.label).map(item => item.label), ["My Cloud can use this PC", "Pause", "Let Clouds run commands on this PC", "See activity"]);
+});
+
+test("the app's own prompt names the bot, its Cloud, what it wants and why, and why it can't now", () => {
+ assert.deepEqual(askPromptWords({ bot: "Scout", need: "screen", reason: "not-running", why: "Fill in the invoice in Excel" }, { cloud: "My Cloud", device: "PC" }), {
+ message: "Scout on My Cloud wants to use this PC's apps and screen",
+ detail: "“Fill in the invoice in Excel”\n\nScreen control isn't running on this PC.",
+ buttons: ["Turn on", "Not now"],
+ });
+ assert.equal(askPromptWords({ bot: "Scout", need: "folders", reason: "paused" }, { cloud: "My Cloud", device: "Mac" }).detail, "Using this Mac is paused.");
+ assert.equal(askPromptWords({ bot: "Scout", need: "terminal", reason: "terminal-off" }, { cloud: "My Cloud", device: "computer" }).message, "Scout on My Cloud wants to run commands on this computer");
+});
+
+test("a failed start keeps the reason Windows gave, not only the kind of failure", () => {
+ const spawn = Object.assign(new Error("EmbeddedDriverError.Spawn"), { tag: "Spawn", inner: { binaryPath: "C:\\x\\cua-driver-background.exe", reason: "Access is denied. (os error 5)" } });
+ assert.equal(driverFailure(spawn), "Spawn: binaryPath C:\\x\\cua-driver-background.exe; reason Access is denied. (os error 5)");
+ assert.equal(driverFailure(Object.assign(new Error("EmbeddedDriverError.StartupTimeout"), { tag: "StartupTimeout", inner: { timeoutMs: 10_000n } })), "StartupTimeout: timeoutMs 10000");
+ assert.equal(driverFailure(new Error("plain")), "plain");
+});
diff --git a/electron/screen-words.mjs b/electron/screen-words.mjs
new file mode 100644
index 0000000000..9222f6985b
--- /dev/null
+++ b/electron/screen-words.mjs
@@ -0,0 +1,52 @@
+// What the menu-bar or taskbar icon and this app's own prompt say when this computer's apps and screen can't be lent to
+// the person's own Clouds, from computer control's state.
+
+/** Why apps and screen aren't available, as one plain sentence without a full stop; null when they are. */
+export function screenLine(status, device) {
+ if (!status || status.ready) return null;
+ switch (status.reason) {
+ case "starting": return `Screen control is starting on this ${device}`;
+ case "permissions": return "macOS hasn't allowed screen control yet";
+ case "blocked": return device === "PC"
+ ? "Screen control is blocked: Windows Security may have stopped it"
+ : `Screen control is blocked on this ${device}`;
+ case "off": return `Screen control is off on this ${device}`;
+ case "unsupported": return status.message ? status.message.replace(/\.$/, "") : `Screen control can't work on this ${device}`;
+ default: return `Screen control isn't running on this ${device}`;
+ }
+}
+
+/** The one action that fixes it, as a menu item or button; null when nothing here can. */
+export function screenFixLabel(status) {
+ if (!status || status.ready || !status.fix) return null;
+ if (status.fix === "allow") return "Allow screen control…";
+ return status.reason === "off" ? "Turn on screen control" : "Start screen control";
+}
+
+const WANTS = {
+ screen: device => `use this ${device}'s apps and screen`,
+ folders: device => `use the files on this ${device}`,
+ terminal: device => `run commands on this ${device}`,
+};
+
+/** Why a bot's ask can't be met here now, from the reason its Cloud gives. */
+function askReason(reason, device) {
+ if (reason === "paused") return `Using this ${device} is paused.`;
+ if (reason === "terminal-off") return `Running commands isn't turned on for this ${device}.`;
+ if (reason === "permissions") return "macOS hasn't allowed OpenMausBot to see and use the screen yet. Turn on asks macOS.";
+ return `${screenLine({ ready: false, reason }, device)}.`;
+}
+
+/** The prompt this app shows by itself for one ask: who wants what, their words, why it can't now, and the fix. */
+export function askPromptWords(ask, { cloud, device }) {
+ const want = (WANTS[ask.need] ?? WANTS.screen)(device);
+ const why = typeof ask.why === "string" && ask.why.trim() ? `“${ask.why.trim()}”\n\n` : "";
+ return {
+ message: `${ask.bot} on ${cloud} wants to ${want}`,
+ detail: `${why}${askReason(ask.reason, device)}`,
+ buttons: ["Turn on", "Not now"],
+ };
+}
+
+/** A reason Turn on can fix on this computer. */
+export const fixableHere = reason => ["paused", "permissions", "blocked", "off", "not-running", "terminal-off"].includes(reason);
diff --git a/electron/shared-computer-access.mjs b/electron/shared-computer-access.mjs
index f94109079f..358048e51b 100644
--- a/electron/shared-computer-access.mjs
+++ b/electron/shared-computer-access.mjs
@@ -172,6 +172,9 @@ function killTree(child) {
/** No inherited API keys or provider credentials. On Windows a child without SystemRoot cannot start Winsock, one
* without USERPROFILE has no home, and one without TEMP or TMP puts temporary files in the Windows folder. */
const hostEnvironment = () => Object.fromEntries(["PATH", "PATHEXT", "HOME", "USERPROFILE", "SystemRoot", "TEMP", "TMP", "LANG"].filter(key => process.env[key]).map(key => [key, process.env[key]]));
+/** cua-driver 0.28.2 keeps its settings, history and cursor themes under Windows' own folders, which hold no secret. */
+const driverEnvironment = () => ({ ...hostEnvironment(), ...Object.fromEntries(["LOCALAPPDATA", "APPDATA", "ProgramData", "SystemDrive", "windir"]
+ .filter(key => process.env[key]).map(key => [key, process.env[key]])) });
export const validCommandSeconds = value => value === undefined || (Number.isInteger(value) && value >= 1 && value <= MAX_COMMAND_SECONDS);
@@ -228,7 +231,7 @@ export async function sharedCommand(command, cwd, signal, seconds = COMMAND_SECO
export function createSharedCua(connection, { platform = process.platform } = {}) {
const child = spawn(connection.mcpCommand, connection.mcpArgs, {
stdio: ["pipe", "pipe", "ignore"], windowsHide: true,
- env: { ...hostEnvironment(), ...connection.mcpEnv },
+ env: { ...driverEnvironment(), ...connection.mcpEnv },
});
let sequence = 0; let closed = false; let bytes = 0;
const pending = new Map();
diff --git a/electron/shared-computer-access.node-test.mjs b/electron/shared-computer-access.node-test.mjs
index 95616a04d3..4236ec6185 100644
--- a/electron/shared-computer-access.node-test.mjs
+++ b/electron/shared-computer-access.node-test.mjs
@@ -437,6 +437,25 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n'); });`
await assert.rejects(cua.call({ action: "computer_tools" }, signal), /disconnected/);
});
+test("the lent screen's driver gets Windows' own folders, and never this app's keys", async t => {
+ const { dir } = await fixture(t);
+ const script = path.join(dir, "cua-env-fixture.mjs");
+ await writeFile(script, `import readline from 'node:readline';
+readline.createInterface({input:process.stdin}).on('line', line => { const m=JSON.parse(line); if(!m.id)return;
+const env={ LOCALAPPDATA: process.env.LOCALAPPDATA ?? null, APPDATA: process.env.APPDATA ?? null, OPENAI_API_KEY: process.env.OPENAI_API_KEY ?? null };
+const result=m.method==='initialize'?{protocolVersion:'2024-11-05',capabilities:{tools:{}}}:m.method==='tools/list'?{tools:[{name:'list_apps'}]}:{content:[{type:'text',text:JSON.stringify(env)}]};
+process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n'); });`);
+ for (const [key, value] of [["LOCALAPPDATA", "C:\\Users\\you\\AppData\\Local"], ["APPDATA", "C:\\Users\\you\\AppData\\Roaming"], ["OPENAI_API_KEY", "sk-not-for-the-driver"]]) {
+ const before = process.env[key];
+ process.env[key] = value;
+ t.after(() => { if (before === undefined) delete process.env[key]; else process.env[key] = before; });
+ }
+ const cua = createSharedCua({ mcpCommand: process.execPath, mcpArgs: [script] });
+ t.after(() => cua.close());
+ const seen = JSON.parse((await cua.call({ action: "computer_call", tool_name: "list_apps" }, new AbortController().signal)).content[0].text);
+ assert.deepEqual(seen, { LOCALAPPDATA: "C:\\Users\\you\\AppData\\Local", APPDATA: "C:\\Users\\you\\AppData\\Roaming", OPENAI_API_KEY: null });
+});
+
test("a lent Windows screen types foreground text one character at a time on a driver that sends it in one burst", async t => {
const { dir } = await fixture(t);
const script = path.join(dir, "cua-windows-fixture.mjs");
diff --git a/package.json b/package.json
index 4c93909977..2a7eee7cff 100644
--- a/package.json
+++ b/package.json
@@ -59,6 +59,7 @@
"build:cua": "node scripts/prepare-cua.mjs",
"build:cua:win": "node scripts/prepare-cua-win.mjs",
"smoke:cua-win": "node scripts/smoke-cua-win-embedded.mjs",
+ "smoke:cua-win-lend": "node scripts/smoke-cua-win-lend.mjs",
"build:android-tools": "node scripts/prepare-android-tools.mjs",
"build:cloudflared": "node scripts/prepare-cloudflared.mjs",
"build:browser": "node scripts/prepare-browser.mjs",
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index ebbea18e03..6611325c11 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -30,6 +30,8 @@ export const AREA_CHECKS = {
"script-tests": ["linux-tests", "host-tests", "ui-smoke", "browser-identity"],
server: SERVER_CHECKS,
desktop: SERVER_CHECKS,
+ // The Windows CUA job starts these the way the installed app does, then lends the PC's screen through them.
+ "windows-computer-control": [...SERVER_CHECKS, "windows-cua"],
"control-plane": ["control-plane"],
everything: EVERY_CHECK,
};
@@ -79,6 +81,7 @@ const AREAS = [
[/^src\/locales\/(?:(?!en\.json$)[^/]+\.json|[^/]+\.test\.ts)$/, "locales"],
[/^(?:src|public)\/|^[^/]+-preview\.html$/, "web"],
[/^(?:server|shared|enterprise|companion|evals|skills|deploy|cloudflare\/composio-broker)\/|^(?:Dockerfile|\.dockerignore|compose\.yaml)$/, "server"],
+ [/^electron\/(?:cua|cua-failure|cua-connection|capabilities|screen-status|shared-cua-connection|shared-computer-access|lent-screen-tools|lent-screen-failures|paced-typing)\.[cm]js$/, "windows-computer-control"],
[/^(?:electron|build)\/|^(?:electron-builder\.yml|index\.html)$/, "desktop"],
[/^cloudflare\/control-plane\//, "control-plane"],
];
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index 48e1967532..36d17c4419 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -123,6 +123,12 @@ describe("CI path scope", () => {
expect(selectCiScope([file])).toEqual({ areas: ["server"], checks: checks("server") });
});
+ it.each([["electron/cua.mjs"], ["electron/shared-computer-access.mjs"], ["electron/capabilities.cjs"], ["electron/screen-status.mjs"]])(
+ "runs the Windows computer-control smokes too for %j, which they start as the installed app does", (file) => {
+ expect(selectCiScope([file])).toEqual({ areas: ["windows-computer-control"], checks: checks("server", "windows-computer-control") });
+ expect(selectCiScope([file]).checks).toContain("windows-cua");
+ });
+
it.each([["electron/main.mjs"], ["build/icon.icns"], ["electron-builder.yml"], ["index.html"]])("runs the server's checks for the desktop's %j", (file) => {
expect(selectCiScope([file])).toEqual({ areas: ["desktop"], checks: checks("server") });
});
diff --git a/scripts/ci-workflow.test.ts b/scripts/ci-workflow.test.ts
index 787aa73249..e774cf7c76 100644
--- a/scripts/ci-workflow.test.ts
+++ b/scripts/ci-workflow.test.ts
@@ -157,6 +157,17 @@ describe("CI concurrency", () => {
expect(sparse.sort()).toEqual(["scripts/release-ci.mjs", ...imports].sort());
});
+ it("builds the Windows Defender check's installer exactly as the release's Windows job does", () => {
+ const release = parse(readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8"));
+ const check = parse(readFileSync(new URL("../.github/workflows/windows-defender-check.yml", import.meta.url), "utf8"));
+ type Step = { uses?: string; with?: unknown; run?: string; shell?: string };
+ const toolchainToInstaller = (steps: Step[]) => steps.slice(1, steps.findIndex((step) => step.run === "pnpm package:win") + 1)
+ .map(({ uses, with: inputs, run, shell }) => ({ uses, with: inputs, run, shell }));
+ expect(toolchainToInstaller(check.jobs.check.steps).at(-1)?.run).toBe("pnpm package:win");
+ expect(toolchainToInstaller(check.jobs.check.steps)).toEqual(toolchainToInstaller(release.jobs.windows.steps));
+ expect(check.jobs.check["runs-on"]).toBe(release.jobs.windows["runs-on"]);
+ });
+
it("lets the scope read the previous commit's CI and a pull request's labels, and nothing more", () => {
// ci-scope.mjs runs a push's docs- or version-only diff without the runtime
// jobs only when the commit before it has its own green run, and a PR's
diff --git a/scripts/defender-check-win.mjs b/scripts/defender-check-win.mjs
new file mode 100644
index 0000000000..5c4de0269c
--- /dev/null
+++ b/scripts/defender-check-win.mjs
@@ -0,0 +1,707 @@
+#!/usr/bin/env node
+// How Windows Security treats the real installer on a fresh GitHub Windows runner, after `pnpm package:win`
+// (.github/workflows/windows-defender-check.yml). GitHub's image turns most of Defender off and excludes every drive, so
+// its protection is first set to a home PC's defaults. The installer is saved with a browser download's Zone.Identifier
+// (ZoneId=3), started the way a double-click starts it, and the app opened for two minutes; Start screen control is
+// then pressed through the app's DevTools port. report.md says what Defender found, whether cua-driver-background.exe
+// runs and whether Start screen control worked; the run fails when any of those went wrong. It changes Defender's
+// settings and installs the app, so it runs only on a GitHub Windows runner.
+//
+// node scripts/defender-check-win.mjs --installer release/OpenMausBot-<version>-setup.exe --out <folder> [--wait 120]
+import { execFile, execFileSync, spawn } from "node:child_process";
+import { appendFileSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { parseArgs } from "node:util";
+
+const { values: options } = parseArgs({
+ options: { installer: { type: "string" }, out: { type: "string" }, wait: { type: "string", default: "120" } },
+});
+if (process.platform !== "win32" || process.env.GITHUB_ACTIONS !== "true") {
+ console.error("defender-check-win turns Windows Security's protection on and installs the app, so it runs only on a GitHub Windows runner.");
+ process.exit(2);
+}
+if (!options.installer || !existsSync(options.installer) || !options.out) {
+ console.error("usage: node scripts/defender-check-win.mjs --installer <OpenMausBot-<version>-setup.exe> --out <folder> [--wait 120]");
+ process.exit(2);
+}
+
+const OUT = path.resolve(options.out);
+const SCRIPTS = path.join(OUT, "powershell");
+mkdirSync(SCRIPTS, { recursive: true });
+const WAIT_SECONDS = Math.max(10, Number(options.wait) || 120);
+const DEVTOOLS_PORT = 9339;
+const STARTED = new Date();
+const APP = "OpenMausBot.exe";
+const DRIVER = "cua-driver-background.exe";
+const DEFENDER_EVENTS = [1006, 1007, 1008, 1015, 1116, 1117];
+const MPCMDRUN = path.join(process.env.ProgramFiles ?? "C:\\Program Files", "Windows Defender", "MpCmdRun.exe");
+/** The app's own files: a detection naming one of these is about us, anything else is the machine's. */
+const OURS = /openmausbot|cua-driver|cua_driver|cua-sdk/i;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+const quote = (value) => `'${String(value).replaceAll("'", "''")}'`;
+const say = (line) => console.log(`[defender-check] ${line}`);
+/** PowerShell 5.1 can hand back a one-item list as the item itself. */
+const list = (value) => (Array.isArray(value) ? value : value == null ? [] : [value]);
+const firstLines = (text) => String(text ?? "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(0, 6).join(" | ");
+
+function run(file, args, timeout = 120_000, signal = undefined) {
+ return new Promise((resolve) => {
+ execFile(file, args, { timeout, signal, windowsHide: true, maxBuffer: 32 * 1024 * 1024 }, (error, stdout, stderr) => {
+ resolve({
+ code: error ? (typeof error.code === "number" ? error.code : null) : 0,
+ timedOut: Boolean(error?.killed),
+ out: String(stdout ?? "").trim(),
+ err: String(stderr ?? "").trim(),
+ error: error && typeof error.code !== "number" ? `${error.code ?? ""} ${error.message}`.trim() : undefined,
+ });
+ });
+ });
+}
+
+const PRELUDE = String.raw`$ErrorActionPreference = 'Stop'
+$ProgressPreference = 'SilentlyContinue'
+$WarningPreference = 'SilentlyContinue'
+Remove-TypeData -TypeName System.Array -ErrorAction SilentlyContinue`;
+let scriptCount = 0;
+
+/** Windows PowerShell 5.1, where the Defender cmdlets live. */
+async function ps(script, timeout = 120_000, signal = undefined) {
+ const base = path.join(SCRIPTS, String(++scriptCount).padStart(2, "0"));
+ writeFileSync(`${base}.ps1`, `\uFEFF${PRELUDE}
+try {
+$result = @(& {
+${script}
+})
+ConvertTo-Json -InputObject $result -Depth 6 -Compress | Set-Content -LiteralPath ${quote(`${base}.json`)} -Encoding UTF8
+} catch {
+[Console]::Error.WriteLine($_.Exception.Message)
+exit 1
+}
+`);
+ const result = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", `${base}.ps1`], timeout, signal);
+ if (result.code !== 0 || !existsSync(`${base}.json`)) {
+ throw new Error(result.timedOut ? `no answer within ${timeout / 1000} s` : firstLines(result.err || result.error || result.out) || `PowerShell ended with ${result.code}`);
+ }
+ const answer = JSON.parse(readFileSync(`${base}.json`, "utf8").replace(/^\uFEFF/, "") || "[]");
+ return Array.isArray(answer) ? answer : [answer];
+}
+
+const report = { started: STARTED.toISOString(), commit: git(["rev-parse", "HEAD"]), version: appVersion(), errors: [] };
+
+async function step(name, check) {
+ say(name);
+ try {
+ return await check();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ report.errors.push(`${name}: ${message}`);
+ say(`${name}: ${message}`);
+ return { error: message };
+ }
+}
+
+function git(args) {
+ try {
+ return execFileSync("git", args, { encoding: "utf8" }).trim();
+ } catch {
+ return process.env.GITHUB_SHA ?? "unknown";
+ }
+}
+
+function appVersion() {
+ try {
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
+ } catch {
+ return "unknown";
+ }
+}
+
+const MACHINE = String.raw`
+$os = Get-CimInstance Win32_OperatingSystem
+[pscustomobject]@{
+ os = "$($os.Caption)"; version = "$($os.Version)"; image = "$env:ImageOS $env:ImageVersion".Trim()
+ user = "$env:USERDOMAIN\$env:USERNAME"; session = (Get-Process -Id $PID).SessionId
+ defenderService = "$((Get-Service WinDefend -ErrorAction SilentlyContinue).Status)"
+}`;
+
+const defenderNow = (label) => ps(String.raw`
+Get-MpComputerStatus | Format-List * | Out-File -LiteralPath ${quote(path.join(OUT, `defender-status-${label}.txt`))} -Width 200
+Get-MpPreference | Format-List * | Out-File -LiteralPath ${quote(path.join(OUT, `defender-preferences-${label}.txt`))} -Width 200
+$status = Get-MpComputerStatus
+$preferences = Get-MpPreference
+$policies = foreach ($key in 'HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender', 'HKLM:\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection') {
+ if (Test-Path -LiteralPath $key) {
+ foreach ($item in @(Get-Item -LiteralPath $key) + @(Get-ChildItem -LiteralPath $key -Recurse)) {
+ foreach ($name in $item.Property) { "$($item.Name -replace '^HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\', '')\$name = $($item.GetValue($name))" }
+ }
+ }
+}
+[pscustomobject]@{
+ realTimeProtection = $status.RealTimeProtectionEnabled; onAccessProtection = $status.OnAccessProtectionEnabled
+ behaviourMonitoring = $status.BehaviorMonitorEnabled; downloadScanning = $status.IoavProtectionEnabled
+ antivirus = $status.AntivirusEnabled; runningMode = "$($status.AMRunningMode)"; tamperProtected = $status.IsTamperProtected
+ signatureVersion = "$($status.AntivirusSignatureVersion)"; signatureAge = $status.AntivirusSignatureAge; signatureUpdated = "$($status.AntivirusSignatureLastUpdated)"
+ engineVersion = "$($status.AMEngineVersion)"; productVersion = "$($status.AMProductVersion)"
+ cloudProtection = [int]$preferences.MAPSReporting; sampleSubmission = [int]$preferences.SubmitSamplesConsent
+ blockAtFirstSight = -not $preferences.DisableBlockAtFirstSeen; puaProtection = [int]$preferences.PUAProtection
+ exclusions = @(@($preferences.ExclusionPath) + @($preferences.ExclusionProcess) + @($preferences.ExclusionExtension) | Where-Object { $_ } | ForEach-Object { "$_" })
+ policies = @($policies)
+}`).then(([answer]) => ({ ...answer, exclusions: list(answer.exclusions), policies: list(answer.policies) }));
+
+/** A home PC's defaults: real-time, behaviour and download scanning, cloud protection with automatic safe samples
+ * (what block at first sight needs) and blocking unwanted apps; and none of the drive exclusions GitHub adds. */
+const TURN_ON = String.raw`
+$settings = foreach ($setting in @(
+ @{ DisableRealtimeMonitoring = $false }, @{ DisableBehaviorMonitoring = $false }, @{ DisableIOAVProtection = $false },
+ @{ DisableScriptScanning = $false }, @{ DisableArchiveScanning = $false }, @{ DisableBlockAtFirstSeen = $false },
+ @{ MAPSReporting = 2 }, @{ SubmitSamplesConsent = 1 }, @{ PUAProtection = 1 })) {
+ $name = @($setting.Keys)[0]
+ try { Set-MpPreference @setting; [pscustomobject]@{ setting = "$name = $($setting[$name])"; done = $true; why = '' } }
+ catch { [pscustomobject]@{ setting = "$name = $($setting[$name])"; done = $false; why = "$($_.Exception.Message)".Trim() } }
+}
+$preferences = Get-MpPreference
+$exclusions = foreach ($kind in 'ExclusionPath', 'ExclusionProcess', 'ExclusionExtension') {
+ foreach ($value in @($preferences.$kind | Where-Object { $_ })) {
+ $remove = @{}
+ $remove[$kind] = $value
+ try { Remove-MpPreference @remove; [pscustomobject]@{ exclusion = "$value"; removed = $true; why = '' } }
+ catch { [pscustomobject]@{ exclusion = "$value"; removed = $false; why = "$($_.Exception.Message)".Trim() } }
+ }
+}
+[pscustomobject]@{ settings = @($settings); exclusions = @($exclusions) }`;
+const turnOn = async () => {
+ const [answer] = await ps(TURN_ON);
+ return { settings: list(answer.settings), exclusions: list(answer.exclusions) };
+};
+
+const SMART_SCREEN = String.raw`
+function Read-Value($key, $name) { try { "$((Get-ItemProperty -LiteralPath $key -Name $name).$name)" } catch { '' } }
+[pscustomobject]@{
+ explorer = Read-Value 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer' 'SmartScreenEnabled'
+ policy = Read-Value 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\System' 'EnableSmartScreen'
+ policyLevel = Read-Value 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\System' 'ShellSmartScreenLevel'
+ smartAppControl = Read-Value 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' 'VerifiedAndReputablePolicyState'
+}`;
+
+async function waitForRealTime(ms) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const [on] = await ps("(Get-MpComputerStatus).RealTimeProtectionEnabled");
+ if (on === true || Date.now() > until) return on === true;
+ await sleep(3000);
+ }
+}
+
+const screenshot = (file) => ps(String.raw`
+Add-Type -AssemblyName System.Windows.Forms, System.Drawing
+$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
+$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height
+$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
+$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size)
+$bitmap.Save(${quote(file)}, [System.Drawing.Imaging.ImageFormat]::Png)
+$graphics.Dispose()
+$bitmap.Dispose()
+[pscustomobject]@{ file = ${quote(path.basename(file))}; width = $bounds.Width; height = $bounds.Height }`).then(([shot]) => shot, (error) => ({ error: error.message }));
+
+/** The windows on screen, and whether the installer or SmartScreen runs. */
+const onScreen = (installer) => ps(String.raw`
+$windows = @(Get-Process | Where-Object { $_.MainWindowTitle } | ForEach-Object { [pscustomobject]@{ pid = $_.Id; name = $_.ProcessName; title = $_.MainWindowTitle } })
+$processes = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -in 'smartscreen.exe', 'consent.exe', ${quote(path.basename(installer))} } | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; name = "$($_.Name)" } })
+[pscustomobject]@{ windows = $windows; processes = $processes }`).then(([seen]) => ({ windows: list(seen.windows), processes: list(seen.processes) }));
+
+/** Saved to Downloads with the mark a browser gives a download (the Internet zone), so Windows treats it as one. */
+async function saveAsDownload(installer) {
+ const [saved] = await ps(String.raw`
+$downloads = Join-Path $env:USERPROFILE 'Downloads'
+New-Item -ItemType Directory -Force -Path $downloads | Out-Null
+$target = Join-Path $downloads ${quote(path.basename(installer))}
+Copy-Item -LiteralPath ${quote(installer)} -Destination $target -Force
+Set-Content -LiteralPath $target -Stream Zone.Identifier -Value @('[ZoneTransfer]', 'ZoneId=3', 'ReferrerUrl=https://www.openmausbot.com/download', 'HostUrl=https://github.com/milind-soni/OpenMausBot/releases/latest/download/OpenMausBot-setup.exe')
+[pscustomobject]@{
+ path = $target; bytes = (Get-Item -LiteralPath $target).Length; sha256 = (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash
+ zone = @(Get-Content -LiteralPath $target -Stream Zone.Identifier) -join ' | '
+ signature = "$((Get-AuthenticodeSignature -LiteralPath $target).Status)"
+}`);
+ // Real-time protection acts on a file just written; give it the moment it takes.
+ await sleep(15_000);
+ return { ...saved, stillThere: existsSync(saved.path) };
+}
+
+/** Defender's verdict on a file or folder, without acting on it or logging it (so the event log keeps only what
+ * real-time protection did). */
+async function scan(target) {
+ const result = await run(MPCMDRUN, ["-Scan", "-ScanType", "3", "-File", target, "-DisableRemediation"], 900_000);
+ const output = `${result.out}\n${result.err}`.trim();
+ return {
+ target,
+ ran: result.code === 0 || result.code === 2,
+ clean: result.code === 0,
+ code: result.code,
+ threats: [...output.matchAll(/^\s*Threat\s*:\s*(.+)$/gim)].map((match) => match[1].trim()),
+ files: [...output.matchAll(/^\s*file\s*:\s*(.+)$/gim)].map((match) => match[1].trim()),
+ output: output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-12),
+ };
+}
+
+function installedFolder() {
+ const programs = path.join(process.env.LOCALAPPDATA ?? "", "Programs");
+ if (!existsSync(programs)) return null;
+ const name = readdirSync(programs).find((entry) => existsSync(path.join(programs, entry, APP)));
+ return name ? path.join(programs, name) : null;
+}
+
+/** First the way a double-click starts it: Windows' shell checks a downloaded file before it runs, and a prompt it shows
+ * waits for a click nobody gives here, with no installer running. Then, if that didn't install it, directly. */
+async function install(installer) {
+ const began = Date.now();
+ const stop = new AbortController();
+ const shellStart = ps(String.raw`
+$process = Start-Process -FilePath ${quote(installer)} -ArgumentList '/S' -PassThru
+$null = $process.Handle
+$exited = $process.WaitForExit(240000)
+if (-not $exited) { Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue }
+[pscustomobject]@{ exited = $exited; exitCode = $(if ($exited) { $process.ExitCode } else { $null }) }`, 300_000, stop.signal)
+ .then((answer) => answer[0], (error) => ({ error: error.message }));
+ const settled = await Promise.race([shellStart, sleep(30_000).then(() => null)]);
+ let held = null;
+ if (!settled) {
+ const [seen, shot] = await Promise.all([onScreen(installer).catch((error) => ({ error: error.message })), screenshot(path.join(OUT, "shell-start.png"))]);
+ const installing = seen.processes?.some((entry) => entry.name.toLowerCase() === path.basename(installer).toLowerCase());
+ held = { windows: seen.windows ?? [], processes: seen.processes ?? [], screenshot: shot, error: seen.error };
+ if (seen.processes && !installing) stop.abort();
+ }
+ const shell = { ...(await shellStart), held: Boolean(held && stop.signal.aborted), seen: held };
+ const shellSeconds = Math.round((Date.now() - began) / 1000);
+ let folder = installedFolder();
+ let direct = null;
+ if (!folder) {
+ // A start the shell never finished may have left the installer waiting.
+ await run("taskkill.exe", ["/F", "/IM", path.basename(installer)], 60_000);
+ const result = await run(installer, ["/S"], 300_000);
+ direct = { code: result.code, timedOut: result.timedOut, error: result.error };
+ folder = installedFolder();
+ }
+ return { shell: { ...shell, seconds: shellSeconds }, direct, folder, seconds: Math.round((Date.now() - began) / 1000) };
+}
+
+const installedFiles = (folder) => ps(String.raw`
+$root = ${quote(folder)}
+$names = @('OpenMausBot.exe', 'resources\cua-driver-background.exe', 'resources\cua-driver.exe')
+$sdk = Join-Path $root 'resources\cua-sdk'
+if (Test-Path -LiteralPath $sdk) {
+ $names += @(Get-ChildItem -LiteralPath $sdk -Recurse -File | Where-Object { $_.Extension -in '.exe', '.node', '.dll' } | ForEach-Object { $_.FullName.Substring($root.Length + 1) })
+}
+foreach ($name in $names) {
+ $file = Join-Path $root $name
+ if (Test-Path -LiteralPath $file) {
+ $signature = Get-AuthenticodeSignature -LiteralPath $file
+ [pscustomobject]@{ file = $name; present = $true; bytes = (Get-Item -LiteralPath $file).Length; sha256 = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash; signature = "$($signature.Status)"; signer = "$($signature.SignerCertificate.Subject)" }
+ } else {
+ [pscustomobject]@{ file = $name; present = $false; bytes = 0; sha256 = ''; signature = ''; signer = '' }
+ }
+}`);
+
+async function processes() {
+ const list = await ps(String.raw`
+Get-CimInstance Win32_Process -Filter "Name = '${APP}' OR Name = '${DRIVER}'" | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; name = "$($_.Name)"; path = "$($_.ExecutablePath)" } }`)
+ .catch(() => []);
+ const named = (name) => list.filter((entry) => String(entry.name).toLowerCase() === name.toLowerCase());
+ return { app: named(APP).length, driver: named(DRIVER).map((entry) => ({ pid: entry.pid, path: entry.path })) };
+}
+
+const describe = (now) => `${now.app ? `app running (${now.app} processes)` : "app not running"}; ${
+ now.driver.length ? `${DRIVER} running (pid ${now.driver.map((entry) => entry.pid).join(", ")})` : `${DRIVER} not running`}`;
+
+/** Opened as a person opens it, without the runner's own variables, plus a DevTools port for Start screen control. */
+async function watchApp(exe) {
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:CI|GITHUB_\w*|RUNNER_\w*|ACTIONS_\w*)$/i.test(key)));
+ const child = spawn(exe, [`--remote-debugging-port=${DEVTOOLS_PORT}`], {
+ env,
+ stdio: ["ignore", openSync(path.join(OUT, "app-stdout.log"), "w"), openSync(path.join(OUT, "app-stderr.log"), "w")],
+ });
+ const refused = await new Promise((resolve) => {
+ child.once("spawn", () => resolve(null));
+ child.once("error", (error) => resolve(error.message));
+ });
+ if (refused) return { opened: false, error: `the app didn't start: ${refused}` };
+ const began = Date.now();
+ const timeline = [];
+ let last = "";
+ let driverFirstSeen = null;
+ for (let second = 0; ; second += 10) {
+ const now = await processes();
+ const elapsed = Math.round((Date.now() - began) / 1000);
+ if (now.driver.length && driverFirstSeen === null) driverFirstSeen = elapsed;
+ const line = describe(now);
+ if (line !== last) timeline.push(`${elapsed} s: ${line}`);
+ last = line;
+ if (second >= WAIT_SECONDS) {
+ const shot = await screenshot(path.join(OUT, "app-open.png"));
+ return { opened: true, timeline, driverFirstSeen, appRunning: now.app > 0, driver: now.driver, screenshot: shot };
+ }
+ const wait = began + (second + 10) * 1000 - Date.now();
+ if (wait > 0) await sleep(wait);
+ }
+}
+
+async function devtools(url) {
+ const socket = new WebSocket(url);
+ await new Promise((resolve, reject) => {
+ socket.addEventListener("open", resolve, { once: true });
+ socket.addEventListener("error", () => reject(new Error("the app's DevTools port refused the connection")), { once: true });
+ });
+ let last = 0;
+ const waiting = new Map();
+ socket.addEventListener("message", (event) => {
+ const reply = JSON.parse(String(event.data));
+ const settle = waiting.get(reply.id);
+ if (!settle) return;
+ waiting.delete(reply.id);
+ settle(reply);
+ });
+ return {
+ close: () => socket.close(),
+ evaluate: (expression, ms = 30_000) => new Promise((resolve, reject) => {
+ const id = ++last;
+ const timer = setTimeout(() => {
+ waiting.delete(id);
+ reject(new Error(`no answer within ${ms / 1000} s`));
+ }, ms);
+ waiting.set(id, (reply) => {
+ clearTimeout(timer);
+ const failed = reply.error?.message ?? reply.result?.exceptionDetails?.exception?.description ?? reply.result?.exceptionDetails?.text;
+ if (failed) reject(new Error(failed));
+ else resolve(reply.result?.result?.value);
+ });
+ socket.send(JSON.stringify({ id, method: "Runtime.evaluate", params: { expression, awaitPromise: true, returnByValue: true } }));
+ }),
+ };
+}
+
+/** The app's own window: the local server's page, with the full desktop bridge. */
+async function appPage(ms) {
+ const until = Date.now() + ms;
+ while (Date.now() < until) {
+ try {
+ const pages = await (await fetch(`http://127.0.0.1:${DEVTOOLS_PORT}/json/list`)).json();
+ for (const page of pages.filter((entry) => entry.type === "page" && /^http:\/\/(?:127\.0\.0\.1|localhost):\d+\//.test(entry.url))) {
+ const tab = await devtools(page.webSocketDebuggerUrl);
+ try {
+ if (await tab.evaluate("typeof window.ogb?.localControl?.retry === 'function'")) return page;
+ } finally {
+ tab.close();
+ }
+ }
+ } catch {
+ // not up yet
+ }
+ await sleep(2000);
+ }
+ return null;
+}
+
+const SHOWN = "window.ogb.getCapabilities().then(({ localComputer }) => localComputer)";
+
+/** The call the Start screen control button makes. */
+async function pressStart() {
+ const page = await appPage(90_000);
+ if (!page) return { pressed: false, error: "the app's window never showed its page on the DevTools port" };
+ const tab = await devtools(page.webSocketDebuggerUrl);
+ try {
+ const shown = await tab.evaluate(SHOWN);
+ const before = (await processes()).driver;
+ const began = Date.now();
+ const answer = await tab.evaluate("window.ogb.localControl.retry()", 180_000);
+ const seconds = Math.round((Date.now() - began) / 1000);
+ await sleep(3000);
+ const after = (await processes()).driver;
+ const shownAfter = await tab.evaluate(SHOWN);
+ return { pressed: true, page: page.url, shown, before, answer, seconds, after, shownAfter };
+ } finally {
+ tab.close();
+ }
+}
+
+function appLog() {
+ const folder = path.join(process.env.APPDATA ?? "", "OpenMausBot", "logs");
+ const file = path.join(folder, "server.log");
+ if (!existsSync(file)) return { file, present: false, lines: [] };
+ for (const name of readdirSync(folder)) {
+ const source = path.join(folder, name);
+ if (statSync(source).isFile()) copyFileSync(source, path.join(OUT, `app-log-${name}`));
+ }
+ const lines = readFileSync(file, "utf8").split(/\r?\n/).filter((line) => /computer control|\[cua\]|cua-driver|screen control/i.test(line));
+ return { file, present: true, lines: lines.slice(-40) };
+}
+
+async function closeApp() {
+ await run("taskkill.exe", ["/F", "/T", "/IM", APP], 60_000);
+ await run("taskkill.exe", ["/F", "/IM", DRIVER], 60_000);
+ return { closed: true };
+}
+
+async function findings() {
+ const [found] = await ps(String.raw`
+$since = [datetime]::Parse(${quote(STARTED.toISOString())}).ToLocalTime()
+$detections = @(Get-MpThreatDetection -ErrorAction SilentlyContinue | ForEach-Object { [pscustomobject]@{
+ threatId = "$($_.ThreatID)"; time = "$($_.InitialDetectionTime)"; since = ($_.InitialDetectionTime -ge $since); process = "$($_.ProcessName)"
+ resources = @($_.Resources | ForEach-Object { "$_" }); action = "$($_.CleaningActionID)"; succeeded = $_.ActionSuccess; source = "$($_.DetectionSourceTypeID)" } })
+$threats = @(Get-MpThreat -ErrorAction SilentlyContinue | ForEach-Object { [pscustomobject]@{
+ threatId = "$($_.ThreatID)"; name = "$($_.ThreatName)"; severity = "$($_.SeverityID)"; active = $_.IsActive; executed = $_.DidThreatExecute
+ resources = @($_.Resources | ForEach-Object { "$_" }) } })
+$events = @(Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-Windows Defender/Operational'; Id = ${DEFENDER_EVENTS.join(", ")}; StartTime = $since } -ErrorAction SilentlyContinue | ForEach-Object {
+ [pscustomobject]@{ time = $_.TimeCreated.ToString('o'); id = $_.Id; message = "$($_.Message)" } })
+[pscustomobject]@{ detections = $detections; threats = $threats; events = $events }`);
+ const field = (message, name) => message.match(new RegExp(`^\\s*${name}:\\s*(.+)$`, "mi"))?.[1]?.trim() ?? "";
+ const events = list(found.events);
+ writeFileSync(path.join(OUT, "defender-events.txt"), events.map((event) => `${event.time} event ${event.id}\n${event.message}\n`).join("\n") || "none\n");
+ const threats = list(found.threats).map((threat) => ({ ...threat, resources: list(threat.resources) }));
+ const names = new Map(threats.map((threat) => [threat.threatId, threat.name]));
+ return {
+ detections: list(found.detections).filter((detection) => detection.since)
+ .map((detection) => ({ ...detection, resources: list(detection.resources).map((resource) => resource.replace(/^file:_/i, "")), name: names.get(detection.threatId) ?? "" })),
+ threats,
+ events: events.map((event) => ({
+ time: event.time,
+ id: event.id,
+ threat: field(event.message, "Name"),
+ path: field(event.message, "Path").replace(/^file:_/i, ""),
+ source: field(event.message, "Detection Source"),
+ action: field(event.message, "Action"),
+ process: field(event.message, "Process Name"),
+ })),
+ };
+}
+
+report.machine = await step("the machine", async () => (await ps(MACHINE))[0]);
+report.asFound = await step("Defender as GitHub's machine has it", () => defenderNow("as-found"));
+report.turnOn = await step("turn Defender's protection on as a home PC has it", turnOn);
+report.realTimeOn = await step("wait for real-time protection", () => waitForRealTime(45_000));
+report.cloud = await step("Defender's cloud connection", async () => {
+ const result = await run(MPCMDRUN, ["-ValidateMapsConnection"], 180_000);
+ return { reached: result.code === 0, output: firstLines(`${result.out}\n${result.err}`) || result.error || `ended with ${result.code}` };
+});
+report.signatureUpdate = await step("update Defender's signatures", async () => (await ps("Update-MpSignature\n'updated'", 900_000))[0]);
+report.protection = await step("Defender after turning it on", () => defenderNow("turned-on"));
+report.smartScreen = await step("SmartScreen on this machine", async () => (await ps(SMART_SCREEN))[0]);
+report.download = await step("save the installer like a browser download", () => saveAsDownload(path.resolve(options.installer)));
+const downloaded = report.download?.stillThere ? report.download.path : null;
+report.installerScan = downloaded ? await step("Defender's scan of the installer", () => scan(downloaded)) : null;
+report.install = downloaded ? await step("install it silently", () => install(downloaded)) : null;
+const folder = report.install?.folder ?? null;
+report.files = folder ? await step("the installed files", () => installedFiles(folder)) : null;
+report.app = folder ? await step(`open the app and watch it for ${WAIT_SECONDS} s`, () => watchApp(path.join(folder, APP))) : null;
+report.startScreen = report.app?.opened ? await step("press Start screen control", () => pressStart()) : null;
+report.log = await step("the app's log", () => appLog());
+await step("close the app", () => closeApp());
+report.appScan = folder ? await step("Defender's scan of the installed app", () => scan(folder)) : null;
+report.findings = await step("what Windows Security found", () => findings());
+report.end = await step("Defender at the end", () => defenderNow("end"));
+report.finished = new Date().toISOString();
+
+const verdict = judge(report);
+report.problems = verdict.problems;
+const markdown = render(report, verdict);
+writeFileSync(path.join(OUT, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
+writeFileSync(path.join(OUT, "report.md"), markdown);
+console.log(`\n${markdown}`);
+if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown);
+for (const problem of verdict.problems) console.log(`::error title=Windows Defender check::${problem}`);
+process.exitCode = verdict.problems.length ? 1 : 0;
+
+function judge(r) {
+ const problems = [];
+ const ourEvents = (r.findings?.events ?? []).filter((event) => OURS.test(`${event.path} ${event.process}`));
+ const ourDetections = (r.findings?.detections ?? []).filter((detection) => detection.resources.some((resource) => OURS.test(resource)));
+ for (const event of ourEvents) {
+ problems.push(`Windows Security flagged ${event.path || "an OpenMausBot file"}: ${event.threat || `event ${event.id}`}${event.action ? ` (${event.action})` : ""}`);
+ }
+ if (!ourEvents.length && ourDetections.length) problems.push(`Windows Security recorded ${ourDetections.length} detection(s) in OpenMausBot's files`);
+ if (r.download?.error) problems.push(`the installer couldn't be saved to Downloads: ${r.download.error}`);
+ else if (r.download && !r.download.stillThere) problems.push("the installer was gone 15 s after it was saved to Downloads");
+ if (r.installerScan?.ran && !r.installerScan.clean) problems.push(`Defender's scan of the installer found ${r.installerScan.threats.join(", ") || "a threat"}`);
+ if (r.appScan?.ran && !r.appScan.clean) problems.push(`Defender's scan of the installed app found ${r.appScan.threats.join(", ") || "a threat"} in ${r.appScan.files.join(", ") || "its files"}`);
+ if (r.download?.stillThere && !r.install?.folder) problems.push("the installer didn't install the app");
+ const missing = (Array.isArray(r.files) ? r.files : []).filter((file) => !file.present).map((file) => file.file);
+ if (missing.length) problems.push(`installed files are missing: ${missing.join(", ")}`);
+ if (r.install?.folder && !r.app?.opened) problems.push(`the app didn't open${r.app?.error ? `: ${r.app.error}` : ""}`);
+ if (r.app?.opened && !r.app.appRunning) problems.push(`the app wasn't running ${WAIT_SECONDS} s after it opened`);
+ if (r.app?.opened && !r.app.driver?.length) problems.push(`${DRIVER} wasn't running ${WAIT_SECONDS} s after the app opened`);
+ if (r.app?.opened) {
+ if (!r.startScreen?.pressed) problems.push(`Start screen control couldn't be pressed: ${r.startScreen?.error ?? "unknown"}`);
+ else if (r.startScreen.answer?.status !== "ready" || !r.startScreen.after?.length) {
+ problems.push(`Start screen control didn't start it: ${r.startScreen.answer?.message ?? r.startScreen.answer?.status ?? "no answer"}`);
+ }
+ }
+ const p = r.protection ?? {};
+ const weaker = [];
+ if (p.realTimeProtection !== true) weaker.push("real-time protection stayed off");
+ if (p.runningMode && !/normal/i.test(p.runningMode)) weaker.push(`Defender ran in ${p.runningMode}, so it reports without blocking`);
+ if (p.cloudProtection !== 2) weaker.push("cloud protection wasn't on");
+ else if (r.cloud && !r.cloud.reached) weaker.push("Defender couldn't reach its cloud, so cloud verdicts and block at first sight couldn't work");
+ if (p.exclusions?.length) weaker.push(`exclusions stayed: ${p.exclusions.join(", ")}`);
+ return { problems, weaker, ourEvents, otherEvents: (r.findings?.events ?? []).filter((event) => !ourEvents.includes(event)) };
+}
+
+function render(r, verdict) {
+ const lines = [];
+ const add = (line = "") => lines.push(line);
+ const yesNo = (value) => (value === true ? "yes" : value === false ? "no" : "unknown");
+ const cloud = (value) => ({ 0: "off", 1: "basic", 2: "advanced" })[value] ?? `unknown (${value})`;
+ const samples = (value) => ({ 0: "ask every time", 1: "send safe samples automatically", 2: "never send", 3: "send all samples automatically" })[value] ?? `unknown (${value})`;
+ const unwanted = (value) => ({ 0: "off", 1: "on", 2: "audit only" })[value] ?? `unknown (${value})`;
+ const failed = (part) => (part?.error ? `couldn't tell: ${part.error}` : null);
+ const before = r.asFound ?? {};
+ const after = r.protection ?? {};
+
+ add("## Windows Security and the OpenMausBot installer");
+ add();
+ add(`OpenMausBot ${r.version}, commit \`${String(r.commit).slice(0, 12)}\`, on ${r.machine?.os ?? "Windows"} ${r.machine?.version ?? ""} (GitHub's ${r.machine?.image || "windows-latest"}).`);
+ add();
+ if (verdict.problems.length) {
+ add("**Verdict: something went wrong for a person installing the app.**");
+ for (const problem of verdict.problems) add(`- ${problem}`);
+ } else {
+ add(`**Verdict: Windows Security left the installer and the app alone, and screen control runs.** ${DRIVER} was running ${WAIT_SECONDS} s after the app opened, and Start screen control started it again.`);
+ }
+ if (verdict.weaker.length) add(`\nThis is weaker evidence than it looks, because on GitHub's machine ${verdict.weaker.join("; ")}.`);
+ add();
+
+ add("### What GitHub's machine allowed");
+ if (failed(r.asFound)) add(`- Defender as found: ${failed(r.asFound)}`);
+ else {
+ add(`- As GitHub's machine comes: real-time protection ${before.realTimeProtection ? "on" : "off"}, cloud protection ${cloud(before.cloudProtection)}, block at first sight ${before.blockAtFirstSight ? "on" : "off"}, exclusions ${before.exclusions?.length ? before.exclusions.join(", ") : "none"}; signatures ${before.signatureVersion || "unknown"}.`);
+ }
+ for (const setting of r.turnOn?.settings ?? []) {
+ if (!setting.done) add(`- Refused: \`Set-MpPreference -${setting.setting.replace(" = ", " ")}\`: ${setting.why}`);
+ }
+ const refusedExclusions = (r.turnOn?.exclusions ?? []).filter((exclusion) => !exclusion.removed);
+ for (const exclusion of refusedExclusions) add(`- Couldn't remove the exclusion ${exclusion.exclusion}: ${exclusion.why}`);
+ if (r.turnOn?.settings?.length && r.turnOn.settings.every((setting) => setting.done) && !refusedExclusions.length) {
+ add(`- It let every setting through: \`Set-MpPreference\` turned real-time, behaviour, download and archive scanning, cloud protection, automatic safe samples, block at first sight and unwanted-app blocking on, and \`Remove-MpPreference\` took out ${(r.turnOn.exclusions ?? []).length} exclusion(s).`);
+ } else if (failed(r.turnOn)) add(`- Turning protection on: ${failed(r.turnOn)}`);
+ if (failed(r.protection)) add(`- Defender after turning it on: ${failed(r.protection)}`);
+ else {
+ add(`- During the check: real-time protection ${yesNo(after.realTimeProtection)}, running mode ${after.runningMode || "unknown"}, behaviour monitoring ${yesNo(after.behaviourMonitoring)}, download scanning ${yesNo(after.downloadScanning)}, cloud protection ${cloud(after.cloudProtection)} (${samples(after.sampleSubmission)}), block at first sight ${after.blockAtFirstSight ? "on" : "off"}, unwanted-app blocking ${unwanted(after.puaProtection)}, exclusions ${after.exclusions?.length ? after.exclusions.join(", ") : "none"}.`);
+ add(`- Signatures: ${before.signatureVersion || "unknown"} before, ${after.signatureVersion || "unknown"} after the update${r.signatureUpdate?.error ? ` (the update failed: ${r.signatureUpdate.error})` : ""}, ${after.signatureAge ?? "unknown"} day(s) old; engine ${after.engineVersion || "unknown"}, platform ${after.productVersion || "unknown"}.`);
+ if (r.cloud) add(`- Defender's cloud (\`MpCmdRun -ValidateMapsConnection\`): ${r.cloud.error ? `couldn't tell: ${r.cloud.error}` : r.cloud.reached ? "reached" : `**not reached**: ${r.cloud.output}`}.`);
+ if (after.policies?.length) {
+ const passive = after.policies.some((policy) => /ForceDefenderPassiveMode = 1/.test(policy)) && /normal/i.test(after.runningMode ?? "");
+ add(`- Defender policies GitHub sets on this machine: ${after.policies.join("; ")}${passive ? ". Passive mode applies only to a machine enrolled in Microsoft Defender for Endpoint; Defender reported Normal mode, so it acts on what it finds" : ""}.`);
+ }
+ }
+ if (r.end && !r.end.error) add(`- At the end: real-time protection ${yesNo(r.end.realTimeProtection)}, running mode ${r.end.runningMode || "unknown"}.`);
+ add();
+
+ add("### The installer");
+ if (failed(r.download)) add(`- Saving it to Downloads: ${failed(r.download)}`);
+ else if (r.download) {
+ add(`- Saved to Downloads with a browser's mark (\`${r.download.zone}\`): ${r.download.stillThere ? "still there 15 s later" : "**gone 15 s later**"}. ${r.download.bytes} bytes, SHA-256 \`${r.download.sha256}\`, signature: ${r.download.signature}.`);
+ }
+ if (r.installerScan) add(`- Defender's scan of the installer: ${scanLine(r.installerScan)}.`);
+ if (failed(r.install)) add(`- Installing: ${failed(r.install)}`);
+ else if (r.install) {
+ const shell = r.install.shell ?? {};
+ const titles = (shell.seen?.windows ?? []).map((window) => `"${window.title}" (${window.name})`);
+ const running = (shell.seen?.processes ?? []).map((entry) => entry.name);
+ const shellLine = shell.held
+ ? `held: 30 s later no installer was running${titles.length ? `; the windows on screen were ${titles.join(", ")}` : ""}${running.length ? `; running: ${running.join(", ")}` : ""}. A prompt was waiting for a click nobody gives here`
+ : shell.error
+ ? (/no answer within/.test(shell.error) ? `still waiting after ${shell.seconds} s` : `refused: ${shell.error}`)
+ : shell.exited
+ ? `finished in ${shell.seconds} s with exit code ${shell.exitCode}`
+ : "still running after 4 minutes";
+ add(`- Started the way a double-click starts it (\`/S\`, through the Windows shell): ${shellLine}.`);
+ if (shell.seen?.screenshot) add(`- The screen 30 s after that start: ${shotLine(shell.seen.screenshot)}.`);
+ if (r.install.direct) {
+ add(`- Started directly instead: ${r.install.direct.code === 0 ? "finished" : `ended with ${r.install.direct.code ?? r.install.direct.error ?? "a timeout"}`}.`);
+ }
+ add(`- Installed: ${r.install.folder ? `yes, in \`${r.install.folder}\`` : "**no**"}.`);
+ }
+ if (Array.isArray(r.files)) {
+ for (const file of r.files.filter((entry) => !/cua-sdk/i.test(entry.file) || !entry.present)) {
+ add(`- \`${file.file}\`: ${file.present ? `${file.bytes} bytes, signature ${file.signature}${file.signer ? ` (${file.signer})` : ""}` : "**missing**"}.`);
+ }
+ } else if (failed(r.files)) add(`- The installed files: ${failed(r.files)}`);
+ if (r.appScan) add(`- Defender's scan of the installed app, after it ran: ${scanLine(r.appScan)}.`);
+ add();
+
+ add("### Computer control");
+ if (failed(r.app)) add(`- Opening the app: ${failed(r.app)}`);
+ else if (r.app) {
+ if (!r.app.opened) add(`- The app didn't open: ${r.app.error}`);
+ else {
+ add(`- ${DRIVER} ${r.app.driver?.length ? `was running ${WAIT_SECONDS} s after the app opened (pid ${r.app.driver.map((entry) => entry.pid).join(", ")}, \`${r.app.driver[0].path}\`)` : `**wasn't running** ${WAIT_SECONDS} s after the app opened`}${r.app.driverFirstSeen !== null ? `; first seen ${r.app.driverFirstSeen} s after opening` : ""}.`);
+ add(`- What ran, second by second: ${r.app.timeline.join(" → ")}.`);
+ if (r.app.screenshot) add(`- The screen ${WAIT_SECONDS} s after the app opened: ${shotLine(r.app.screenshot)}.`);
+ }
+ }
+ if (failed(r.log)) add(`- The app's log: ${failed(r.log)}`);
+ else if (r.log) {
+ if (!r.log.present) add(`- The app's log: \`${r.log.file}\` wasn't written.`);
+ else if (!r.log.lines.length) add(`- The app's log (\`${r.log.file}\`) says nothing about computer control.`);
+ else {
+ add(`- The app's log (\`${r.log.file}\`) says:`);
+ add("```");
+ for (const line of r.log.lines) add(line);
+ add("```");
+ }
+ }
+ if (failed(r.startScreen)) add(`- Start screen control: ${failed(r.startScreen)}`);
+ else if (r.startScreen) {
+ if (!r.startScreen.pressed) add(`- Start screen control couldn't be pressed: ${r.startScreen.error}.`);
+ else {
+ const answer = r.startScreen.answer ?? {};
+ add(`- Before pressing it, the app showed: ${shownLine(r.startScreen.shown)}.`);
+ add(`- Start screen control (the button's own call, \`window.ogb.localControl.retry()\`): ${answer.status === "ready" ? "**worked**" : "**didn't work**"} in ${r.startScreen.seconds} s, answer \`${JSON.stringify(answer)}\`; ${DRIVER} ${r.startScreen.after?.length ? `running afterwards (pid ${r.startScreen.after.map((entry) => entry.pid).join(", ")}; before: ${r.startScreen.before?.map((entry) => entry.pid).join(", ") || "none"})` : "**not running afterwards**"}.`);
+ add(`- Afterwards the app showed: ${shownLine(r.startScreen.shownAfter)}.`);
+ }
+ }
+ add();
+
+ add("### What Windows Security found");
+ const findings = r.findings;
+ if (failed(findings)) add(`- ${failed(findings)}`);
+ else if (findings) {
+ add(`- Threat detections since the check started (\`Get-MpThreatDetection\`): ${findings.detections.length ? "" : "none."}`);
+ for (const detection of findings.detections) {
+ add(` - ${detection.time}: ${detection.name || detection.threatId} in ${detection.resources.join(", ")} (action ${detection.action}, ${detection.succeeded ? "done" : "not done"}).`);
+ }
+ add(`- Defender Operational events ${DEFENDER_EVENTS.join(", ")}: ${findings.events.length ? "" : "none."}`);
+ for (const event of findings.events) {
+ add(` - ${event.time}, event ${event.id}: ${event.threat || "(no name)"}${event.path ? ` in ${event.path}` : ""}${event.source ? `, by ${event.source}` : ""}${event.action ? `, action ${event.action}` : ""}${OURS.test(`${event.path} ${event.process}`) ? "" : " (not OpenMausBot's)"}.`);
+ }
+ }
+ add();
+
+ add("### Not covered here");
+ add(`- GitHub's machine runs ${r.machine?.os ?? "Windows Server"}, not Windows 10 or 11. SmartScreen's "Windows protected your PC" screen (an unsigned installer from the internet shows it; people click More info, then Run anyway) and Windows 11's Smart App Control only show on a person's PC.`);
+ if (r.smartScreen && !r.smartScreen.error) {
+ add(`- SmartScreen here: Explorer setting "${r.smartScreen.explorer || "not set"}", policy "${r.smartScreen.policy || "not set"}"; Smart App Control: ${r.smartScreen.smartAppControl === "" ? "not on this edition" : `state ${r.smartScreen.smartAppControl}`}.`);
+ }
+ add(`- The full report, Defender's own status lists, its events and the app's logs are in this run's \`defender-check\` artifact.`);
+ if (r.errors.length) {
+ add();
+ add("### Parts of the check that couldn't run");
+ for (const error of r.errors) add(`- ${error}`);
+ }
+ add();
+ return `${lines.join("\n")}\n`;
+}
+
+function shotLine(shot) {
+ return shot.error ? `no screenshot (${shot.error})` : `\`${shot.file}\` in the artifact (${shot.width}×${shot.height})`;
+}
+
+function scanLine(result) {
+ if (result.error) return `couldn't run: ${result.error}`;
+ if (!result.ran) return `couldn't run (MpCmdRun ended with ${result.code ?? "a timeout"}: ${result.output.slice(-2).join(" ")})`;
+ return result.clean ? "clean" : `**found ${result.threats.join(", ") || "a threat"}**${result.files.length ? ` in ${result.files.join(", ")}` : ""}`;
+}
+
+function shownLine(shown) {
+ if (!shown) return "nothing";
+ const why = [shown.reasonCode, shown.message].filter(Boolean).join(": ");
+ return `computer control ${shown.available ? "available" : "not available"} (${shown.status ?? "no status"}${why ? `; ${why}` : ""})${shown.driverVersion ? `, driver ${shown.driverVersion}` : ""}`;
+}
diff --git a/scripts/smoke-cua-win-lend.electron.cjs b/scripts/smoke-cua-win-lend.electron.cjs
new file mode 100644
index 0000000000..c5a92466de
--- /dev/null
+++ b/scripts/smoke-cua-win-lend.electron.cjs
@@ -0,0 +1,124 @@
+// Electron main for scripts/smoke-cua-win-lend.mjs, which starts it under a copy of Electron named like the installed app.
+const { app } = require("electron");
+const { spawn } = require("node:child_process");
+const { existsSync, writeFileSync } = require("node:fs");
+const { createInterface } = require("node:readline");
+const { join, resolve } = require("node:path");
+const { pathToFileURL } = require("node:url");
+
+const code = process.env.OMB_SMOKE_CODE || resolve(__dirname, "..", "electron");
+app.setPath("userData", process.env.OMB_SMOKE_USER_DATA);
+const report = { code: process.env.OMB_SMOKE_LABEL ?? "this branch", packaged: app.isPackaged, resourcesPath: process.resourcesPath };
+const say = (line) => console.log(`[lend smoke, ${report.code}] ${line}`);
+const load = (file) => import(pathToFileURL(join(code, file)).href);
+const firstText = (result) => String(result?.content?.find?.((part) => part?.type === "text")?.text ?? "");
+
+/** The driver's own tool list over its stdio MCP proxy, started with this process's whole environment. */
+async function driverTools(mcp) {
+ const child = spawn(mcp.mcpCommand, mcp.mcpArgs, { windowsHide: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...mcp.mcpEnv } });
+ const lines = createInterface({ input: child.stdout });
+ let stderr = "";
+ child.stderr.on("data", (bytes) => { stderr = (stderr + bytes).slice(-2000); });
+ const pending = new Map();
+ lines.on("line", (line) => {
+ let message;
+ try { message = JSON.parse(line); } catch { return; }
+ pending.get(message.id)?.(message);
+ });
+ const request = (id, method, params) => new Promise((done, fail) => {
+ const timer = setTimeout(() => fail(new Error(`${method} timed out; stderr: ${stderr}`)), 15_000);
+ child.once("exit", (code) => fail(new Error(`proxy exited ${code}; stderr: ${stderr}`)));
+ pending.set(id, (message) => {
+ clearTimeout(timer);
+ if (message.error) fail(new Error(JSON.stringify(message.error)));
+ else done(message.result);
+ });
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
+ });
+ try {
+ await request(1, "initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "omb-lend-smoke", version: "1" } });
+ child.stdin.write('{"jsonrpc":"2.0","method":"notifications/initialized"}\n');
+ return (await request(2, "tools/list", {}))?.tools ?? [];
+ } finally {
+ lines.close();
+ child.stdin.end();
+ child.kill();
+ }
+}
+
+async function smoke() {
+ const cua = await load("cua.mjs");
+ const { sharedCuaConnection } = await load("shared-cua-connection.mjs");
+ const { localComputerReady } = require(join(code, "capabilities.cjs"));
+ // A base branch from before screen-status.mjs decided as main.mjs's lendsScreen did there.
+ const screenStatus = existsSync(join(code, "screen-status.mjs")) ? (await load("screen-status.mjs")).screenStatus
+ : ({ connection }) => { const lent = sharedCuaConnection(connection) !== null && localComputerReady("win32", connection); return { ready: lent, lent, reason: lent ? null : "unknown", fix: null }; };
+ const { createSharedCua, executeSharedOperation } = await load("shared-computer-access.mjs");
+ const { LENT_SCREEN_ARGUMENTS } = await load("lent-screen-tools.mjs");
+ say(`packaged: ${app.isPackaged}; resources: ${process.resourcesPath}`);
+ if (!app.isPackaged) throw new Error("Electron did not take this copy for the installed app");
+
+ try {
+ return await lend(cua, { screenStatus, sharedCuaConnection, createSharedCua, executeSharedOperation, LENT_SCREEN_ARGUMENTS });
+ } finally {
+ await cua.stopCua();
+ }
+}
+
+async function lend(cua, { screenStatus, sharedCuaConnection, createSharedCua, executeSharedOperation, LENT_SCREEN_ARGUMENTS }) {
+ const started = Date.now();
+ const connection = await cua.startCua();
+ Object.assign(report, { mode: connection?.mode ?? null, reason: connection?.reason ?? null, startMs: Date.now() - started });
+ say(`computer control mode: ${report.mode} after ${report.startMs} ms${report.reason ? `: ${report.reason}` : ""}`);
+ const mcp = sharedCuaConnection(connection);
+ const status = screenStatus({ platform: "win32", connection });
+ Object.assign(report, { lendsScreen: status.lent, screen: status });
+ say(`apps and screen lent to the Cloud: ${status.lent ? "yes" : `no (${status.reason}; fix: ${status.fix ?? "none"})`}`);
+ if (!status.lent || mcp === null) return false;
+
+ try {
+ const tools = await driverTools(mcp);
+ report.driverTools = tools.length;
+ report.droppedRequired = tools.filter((tool) => Object.hasOwn(LENT_SCREEN_ARGUMENTS, tool.name)).flatMap((tool) =>
+ (tool.inputSchema?.required ?? []).filter((key) => !Object.hasOwn(LENT_SCREEN_ARGUMENTS[tool.name], key)).map((key) => `${tool.name}.${key}`));
+ report.unlent = tools.map((tool) => tool.name).filter((name) => !Object.hasOwn(LENT_SCREEN_ARGUMENTS, name));
+ say(`driver tools over the full environment: ${tools.length}; required arguments a lent screen drops: ${report.droppedRequired.join(", ") || "none"}`);
+ } catch (error) {
+ report.driverToolsError = String(error?.message ?? error);
+ say(`driver tools over the full environment failed: ${report.driverToolsError}`);
+ }
+
+ const grant = { enabled: true, computer: true, folders: [] };
+ let shared = null;
+ const open = async () => (shared ??= createSharedCua(mcp));
+ try {
+ const listed = await executeSharedOperation(grant, { action: "computer_tools" }, AbortSignal.timeout(45_000), open);
+ report.lentTools = JSON.parse(firstText(listed)).tools?.length ?? 0;
+ say(`lend path computer_tools: ${report.lentTools} tools`);
+ for (const tool_name of ["get_screen_size", "list_apps"]) {
+ const result = await executeSharedOperation(grant, { action: "computer_call", tool_name, arguments: {} }, AbortSignal.timeout(45_000), open);
+ report[tool_name] = { isError: result?.isError === true, text: firstText(result).slice(0, 300) };
+ say(`lend path ${tool_name}: ${result?.isError === true ? "error" : "ok"}: ${report[tool_name].text.slice(0, 160)}`);
+ }
+ } catch (error) {
+ report.lendError = String(error?.message ?? error);
+ say(`lend path failed: ${report.lendError}`);
+ } finally {
+ shared?.close();
+ }
+ return report.lentTools > 0 && report.get_screen_size?.isError === false && report.list_apps?.isError === false;
+}
+
+app.whenReady().then(async () => {
+ let ok = false;
+ try {
+ ok = await smoke();
+ } catch (error) {
+ report.error = String(error?.stack ?? error);
+ say(`failed: ${report.error}`);
+ }
+ report.ok = ok;
+ writeFileSync(process.env.OMB_SMOKE_REPORT, JSON.stringify(report, null, 2));
+ say(ok ? "smoke:cua-win-lend OK" : "smoke:cua-win-lend FAILED");
+ app.exit(ok ? 0 : 1);
+});
diff --git a/scripts/smoke-cua-win-lend.mjs b/scripts/smoke-cua-win-lend.mjs
new file mode 100644
index 0000000000..0ae24a2242
--- /dev/null
+++ b/scripts/smoke-cua-win-lend.mjs
@@ -0,0 +1,81 @@
+// Windows lend smoke: computer control starts as the installed app starts it, then a Cloud takes its first look at
+// this PC through the lend path, both in Electron's main process. Run after `pnpm build:cua:win`. It reads the
+// screen's size and the list of apps and sends no input. On a pull request (GITHUB_BASE_REF) it runs the base branch's
+// electron/ first, so one run shows the change; only this branch's result decides the exit code.
+//
+// Electron reports app.isPackaged from its executable's name (anything but electron.exe), and process.resourcesPath
+// is the resources folder beside the executable, so a renamed copy of Electron with the staged files placed where
+// electron-builder.yml puts them runs electron/cua.mjs's packaged branch unchanged.
+import { execFileSync, spawn } from "node:child_process";
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync } from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+if (process.platform !== "win32") {
+ console.error("smoke-cua-win-lend is Windows-only");
+ process.exit(1);
+}
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+// git checks text out with CRLF on Windows unless .gitattributes says otherwise.
+const builder = readFileSync(join(root, "electron-builder.yml"), "utf8").replace(/\r\n/g, "\n");
+const winSection = /^win:\n([\s\S]*?)^\S/m.exec(builder)?.[1] ?? "";
+const resources = [...winSection.matchAll(/- from: (dist-native\/cua-win32-x64\/\S+)\s+to: (\S+)/g)].map(([, from, to]) => ({ from, to }));
+if (resources.length < 3) throw new Error("electron-builder.yml no longer names the Windows CUA resources this smoke places");
+for (const { from } of resources) {
+ if (!existsSync(join(root, from))) throw new Error(`${from} is missing: run pnpm build:cua:win first`);
+}
+
+const work = mkdtempSync(join(tmpdir(), "omb-cua-lend-"));
+const installed = join(work, "OpenMausBot");
+cpSync(dirname(createRequire(import.meta.url)("electron")), installed, { recursive: true });
+renameSync(join(installed, "electron.exe"), join(installed, "OpenMausBot.exe"));
+for (const { from, to } of resources) cpSync(join(root, from), join(installed, "resources", to), { recursive: true });
+
+/** One smoke of the electron/ modules under `code`, in a data folder of its own; its exit code once it reported. */
+async function lendSmoke(label, code) {
+ const run = join(work, label.replace(/\W+/g, "-"));
+ mkdirSync(run, { recursive: true });
+ const report = join(run, "report.json");
+ const env = { ...process.env, OMB_SMOKE_USER_DATA: join(run, "user-data"), OMB_SMOKE_REPORT: report, OMB_SMOKE_CODE: code, OMB_SMOKE_LABEL: label,
+ CUA_DRIVER_RS_TELEMETRY_ENABLED: "0" };
+ delete env.CUA_DRIVER_PATH;
+ delete env.ELECTRON_RUN_AS_NODE;
+ console.log(`--- ${label}`);
+ const child = spawn(join(installed, "OpenMausBot.exe"), [join(root, "scripts", "smoke-cua-win-lend.electron.cjs")], {
+ env, stdio: ["ignore", "inherit", "inherit"], windowsHide: true,
+ });
+ const watchdog = setTimeout(() => {
+ console.error(`smoke:cua-win-lend timed out (${label})`);
+ spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
+ }, 150_000);
+ const exit = await new Promise((resolve) => {
+ child.once("error", (error) => { console.error(error); resolve(1); });
+ child.once("exit", (exitCode) => resolve(exitCode ?? 1));
+ });
+ clearTimeout(watchdog);
+ if (!existsSync(report)) { console.error(`the Electron side wrote no report (${label})`); return 1; }
+ console.log(`report (${label}): ${readFileSync(report, "utf8")}`);
+ return exit;
+}
+
+/** The base branch's electron/, from the remote the checkout came from; null when it can't be fetched. */
+function baseElectron(ref) {
+ try {
+ execFileSync("git", ["fetch", "--quiet", "--depth=1", "origin", ref], { cwd: root, stdio: "ignore", timeout: 60_000 });
+ const base = join(work, "base");
+ mkdirSync(base, { recursive: true });
+ execFileSync("tar", ["-x", "-f", "-", "-C", base], { input: execFileSync("git", ["archive", "FETCH_HEAD", "electron"], { cwd: root, maxBuffer: 256 * 1024 * 1024 }), timeout: 60_000 });
+ return join(base, "electron");
+ } catch (error) {
+ console.error(`the base branch's electron/ could not be read: ${error?.message ?? error}`);
+ return null;
+ }
+}
+
+const baseRef = process.env.GITHUB_BASE_REF;
+const base = baseRef ? baseElectron(baseRef) : null;
+if (base) await lendSmoke(`base branch ${baseRef}`, base);
+process.exit(await lendSmoke("this branch", join(root, "electron")));
diff --git a/scripts/verify-windows-lend.ts b/scripts/verify-windows-lend.ts
new file mode 100644
index 0000000000..64b83dbf4c
--- /dev/null
+++ b/scripts/verify-windows-lend.ts
@@ -0,0 +1,136 @@
+// What a person sees when their own Cloud can't use their PC: the taskbar icon's menu as the real module builds it, the
+// card a Cloud's bot raises in the real chat, and the PC's own screen-control status in the real panel.
+// Run: node --experimental-strip-types scripts/verify-windows-lend.ts --shots <dir>
+// It photographs each view in a light and a dark look with a headless Chrome in a throwaway profile (OMB_CDP_CHROME,
+// else the installed Google Chrome), then exits. Nothing here touches this computer's lending or the person's app.
+import { spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { mountPreview, type MountedPreview } from "./testing/preview-fixture.ts";
+import { createLendingIndicator } from "../electron/lending-indicator.mjs";
+
+const at = process.argv.indexOf("--shots");
+if (at === -1) throw new Error("--shots <dir> is required");
+const shots = resolve(process.argv[at + 1] ?? "");
+const CHROME = process.env.OMB_CDP_CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
+const ICON = `data:image/png;base64,${readFileSync(new URL("../electron/resources/app-icon.png", import.meta.url)).toString("base64")}`;
+
+async function openChrome(profile: string) {
+ const chrome = spawn(CHROME, ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--use-mock-keychain",
+ `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"], { stdio: "ignore" });
+ let port = "";
+ for (let i = 0; i < 100 && !port; i++) {
+ await delay(100);
+ try { port = readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0]!.trim(); } catch {}
+ }
+ if (!port) { chrome.kill(); throw new Error("Chrome did not start"); }
+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as Array<{ type: string; webSocketDebuggerUrl: string }>;
+ const socket = new WebSocket(targets.find((target) => target.type === "page")!.webSocketDebuggerUrl);
+ await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; });
+ let next = 0;
+ const waiting = new Map<number, { done: (value: any) => void; fail: (error: Error) => void }>();
+ socket.onmessage = (event) => {
+ const message = JSON.parse(String(event.data));
+ const call = waiting.get(message.id);
+ if (!call) return;
+ waiting.delete(message.id);
+ if (message.error) call.fail(new Error(message.error.message)); else call.done(message.result);
+ };
+ const send = (method: string, params: object = {}) => new Promise<any>((done, fail) => {
+ const id = ++next;
+ waiting.set(id, { done, fail });
+ socket.send(JSON.stringify({ id, method, params }));
+ });
+ const evaluate = async (expression: string) => (await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true })).result?.value;
+ return {
+ async shoot(url: string, ready: string, file: string, { width = 1100, height = 760, dark = false } = {}) {
+ await send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 2, mobile: false });
+ await send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: dark ? "dark" : "light" }] });
+ await send("Page.navigate", { url });
+ const end = Date.now() + 60_000;
+ while (!(await evaluate(`Boolean(document.querySelector(${JSON.stringify(ready)}))`).catch(() => false))) {
+ if (Date.now() > end) throw new Error(`${url.slice(0, 80)}: ${ready} never showed`);
+ await delay(250);
+ }
+ await delay(900);
+ const { data } = await send("Page.captureScreenshot", { format: "png" });
+ writeFileSync(file, Buffer.from(data, "base64"));
+ },
+ close() { socket.close(); chrome.kill(); },
+ };
+}
+
+const escape = (value: string) => value.replace(/[&<>"]/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[character]!);
+
+type MenuItem = { label?: string; type?: string; enabled?: boolean };
+/** The taskbar icon as the real module builds it for a PC whose screen control isn't running, its menu open. */
+function taskbar(screen: { ready: boolean; lent: boolean; reason: string; fix: string | null }): string {
+ const trays: Array<{ tip: string; menu: MenuItem[] }> = [];
+ class Tray {
+ tip = ""; menu: MenuItem[] = [];
+ constructor() { trays.push(this); }
+ on() {} setToolTip(value: string) { this.tip = value; } setTitle() {}
+ setContextMenu(menu: MenuItem[]) { this.menu = menu; } isDestroyed() { return false; } destroy() {}
+ }
+ createLendingIndicator({ Tray, Menu: { buildFromTemplate: (items: unknown) => items }, nativeImage: { createFromPath: () => ({ resize: () => ({}) }) }, iconPath: "",
+ onPause: () => {}, onResume: () => {}, onActivity: () => {}, onTerminal: () => {}, onStartScreen: () => {}, device: "PC" }).update({ clouds: ["My Cloud"], using: [], paused: false, screen });
+ const tray = trays.at(-1)!;
+ const items = tray.menu.map((item) => item.type === "separator" ? "<hr>" : item.type === "checkbox"
+ ? `<div class="item"><span class="box"></span>${escape(item.label ?? "")}</div>`
+ : `<div class="item${item.enabled === false ? " quiet" : ""}${/^(Start|Turn on|Allow) screen control/.test(item.label ?? "") ? " fix" : ""}">${escape(item.label ?? "")}</div>`).join("");
+ return `<!doctype html><html><head><meta charset="utf-8"><style>
+:root { color-scheme: light dark; --bar: rgba(243,243,243,.94); --ink: #1b1b1b; --quiet: #6b6b6b; --menu: #f9f9f9; --line: rgba(0,0,0,.1); --desk: linear-gradient(160deg,#b9d3ee,#e7ecf3); --accent: #005fb8; }
+@media (prefers-color-scheme: dark) { :root { --bar: rgba(32,32,32,.94); --ink: #f3f3f3; --quiet: #a6a6a6; --menu: #2c2c2c; --line: rgba(255,255,255,.12); --desk: linear-gradient(160deg,#1c2b3a,#101418); --accent: #60cdff; } }
+body { margin: 0; height: 100vh; background: var(--desk); font: 14px "Segoe UI", system-ui, -apple-system, sans-serif; color: var(--ink); }
+.bar { position: absolute; bottom: 0; left: 0; right: 0; height: 48px; background: var(--bar); display: flex; justify-content: flex-end; align-items: center; gap: 14px; padding: 0 16px; border-top: 1px solid var(--line); }
+.tray { display: flex; align-items: center; padding: 6px; border-radius: 6px; background: var(--line); } .tray img { width: 20px; height: 20px; }
+.clock { text-align: right; font-size: 12px; line-height: 16px; }
+.menu { position: absolute; right: 96px; bottom: 56px; min-width: 360px; padding: 4px; border-radius: 8px; background: var(--menu); box-shadow: 0 8px 28px rgba(0,0,0,.28); border: 1px solid var(--line); }
+.item { padding: 8px 12px; border-radius: 4px; } .quiet { color: var(--quiet); } .fix { color: var(--accent); font-weight: 600; background: var(--line); }
+.box { display: inline-block; width: 12px; height: 12px; border: 1px solid var(--quiet); border-radius: 3px; margin-right: 8px; vertical-align: -1px; }
+hr { border: 0; border-top: 1px solid var(--line); margin: 4px 8px; }
+.tip { position: absolute; right: 60px; bottom: 56px; display: none; }
+</style></head><body><div class="menu" data-menu>${items}</div><div class="bar"><div class="tray" title="${escape(tray.tip)}"><img src="${ICON}" alt=""></div><div class="clock">10:42<br>31-10-2026</div></div></body></html>`;
+}
+
+const data = (html: string) => `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
+const SKINS = [{ id: "daylight", look: "light", dark: false }, { id: "midnight", look: "dark", dark: true }];
+const MENUS = [
+ { name: "taskbar-not-running", screen: { ready: false, lent: false, reason: "not-running", fix: "start" } },
+ { name: "taskbar-blocked", screen: { ready: false, lent: false, reason: "blocked", fix: "start" } },
+];
+const VIEWS = [
+ { name: "card-asking", query: "view=asking", ready: "[data-ask-card]" },
+ { name: "card-closed", query: "view=closed", ready: "[data-ask-card]" },
+ { name: "card-failed", query: "view=failed", ready: "[data-ask-card]" },
+ { name: "card-on", query: "view=on", ready: "[data-computer-ask='on']" },
+ { name: "pc-status", query: "view=pc", ready: "[data-windows-local-control]", width: 560, height: 360 },
+];
+
+mkdirSync(shots, { recursive: true });
+const profile = mkdtempSync(join(tmpdir(), "omb-windows-lend-chrome-"));
+const chrome = await openChrome(profile);
+let ui: MountedPreview | undefined;
+try {
+ for (const skin of SKINS) {
+ for (const { name, screen } of MENUS) {
+ const file = join(shots, `${name}-${skin.look}.png`);
+ await chrome.shoot(data(taskbar(screen)), "[data-menu]", file, { width: 640, height: 360, dark: skin.dark });
+ console.log(file);
+ }
+ }
+ // The page asks no server for anything: its store is fixed and every /api call is answered in the page.
+ ui = await mountPreview({ info: { url: "http://127.0.0.1:9" } }, { entry: "/src/computer-ask-preview.tsx", route: "/__computer-ask.html", title: "Turn on your computer", logLevel: "warn" });
+ for (const view of VIEWS) for (const skin of SKINS) {
+ const file = join(shots, `${view.name}-${skin.look}.png`);
+ await chrome.shoot(`${ui.previewUrl}?skin=${skin.id}&${view.query}`, view.ready, file, { dark: skin.dark, ...(view.width ? { width: view.width, height: view.height } : {}) });
+ console.log(file);
+ }
+} finally {
+ chrome.close();
+ await ui?.close();
+ await delay(500);
+ rmSync(profile, { recursive: true, force: true });
+}
diff --git a/server/cloud-home-server.test.ts b/server/cloud-home-server.test.ts
index b94b443bca..34f717739d 100644
--- a/server/cloud-home-server.test.ts
+++ b/server/cloud-home-server.test.ts
@@ -367,13 +367,15 @@ it("offers its bots the browser and cloud computers only, and tells them they ca
const dump = join(home, "spawn-hang.json");
await expect.poll(() => existsSync(dump), { timeout: 15_000 }).toBe(true);
const { systemPrompt, mcpConfig } = JSON.parse(readFileSync(dump, "utf8"));
- expect(systemPrompt).toContain(cloudHomePrompt(true));
+ expect(systemPrompt).toContain(cloudHomePrompt(true, [], [], true));
expect(systemPrompt).toContain("check list_shared_computers");
+ expect(systemPrompt).toContain("call ask_for_computer");
+ expect(systemPrompt).toContain("never do it on their cloud computer or in the built-in browser instead unless they ask you to");
expect(systemPrompt).not.toMatch(/Local VM is an isolated desktop|user's host|host desktop|select an available Local VM/);
const agents = mcpConfig.mcpServers.agents;
expect(agents.env.OMB_CLOUD_HOME).toBe("1");
const preview = (await api("GET", `/api/bots/${botId}/system-prompt`)).body.sections as Array<{ id: string; text: string }>;
- expect(preview.find((section) => section.id === "cloud-home")?.text).toBe(cloudHomePrompt(true));
+ expect(preview.find((section) => section.id === "cloud-home")?.text).toBe(cloudHomePrompt(true, [], [], true));
const select = (surface?: string) => fetch(`${base}/api/internal/computer/select`, {
method: surface === undefined ? "GET" : "POST",
headers: { authorization: `Bearer ${agents.env.OMB_COMMS_TOKEN}`, ...(surface === undefined ? {} : { "content-type": "application/json" }) },
diff --git a/server/cloud-lending.e2e.test.ts b/server/cloud-lending.e2e.test.ts
index f6e4957a42..4254927adb 100644
--- a/server/cloud-lending.e2e.test.ts
+++ b/server/cloud-lending.e2e.test.ts
@@ -490,7 +490,7 @@ it("My Cloud remembers a lent computer across its restart, says it is offline by
expect(away.computers).toEqual([]);
expect(away.offline).toEqual([expect.objectContaining({ device, lent: true })]);
expect(away.say).toMatch(new RegExp(`^Their ${device} .+ is shared with the Cloud but offline \\(last online \\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d UTC\\)`, "u"));
- expect(away.say).toContain(`Ask them to open OpenMausBot on that ${device}; it reconnects by itself.`);
+ expect(away.say, "on the person's own Cloud the bot asks with a card instead of explaining the fix").toContain("If the request needs it, call ask_for_computer");
const refused = await call("shared_computer", { computer_id: id, action: "list_files", folder_id: randomUUID(), path: "." });
expect(refused.isError).toBe(true);
expect(JSON.stringify(refused)).toContain(`is offline: OpenMausBot on that ${device} is closed, or the ${device} is asleep or off.`);
@@ -562,3 +562,45 @@ it("a Mac signed in to My Cloud is lent by itself, its home folder with editing,
await expect.poll(async () => (await lentNow()).computers.length, { timeout: 8000 }).toBe(1);
rmSync(macHome, { recursive: true, force: true });
}, hostTimeout(60_000));
+
+it("paused, the PC still hears a bot that needs it: one card in the chat, the app's own prompt once, and Turn on on the card turns it on so the bot's call carries on", async () => {
+ const env = { id: "my-cloud", name: "My Cloud", origin: base };
+ connector?.close();
+ const pcHome = realpathSync(mkdtempSync(join(tmpdir(), "omb-asks-home-")));
+ rmSync(join(home, "desktop-profile"), { recursive: true, force: true });
+ const prompts: string[] = [];
+ connector = createComputerSharing({
+ file: join(home, "desktop-profile", "computer-sharing.json"), environments: () => [env], myCloud: () => env, ownClouds: () => [env], cuaConnection: async () => null, enabled: async () => false,
+ cloud: () => ({ status: "connected", accountId: "acct_fixture", origin: base }), home: pcHome,
+ screen: () => ({ ready: true, lent: true, reason: null, fix: null }),
+ prompt: async (_env: unknown, ask: { id: string }) => { prompts.push(ask.id); return null; },
+ fetch: (url: string, init: RequestInit) => fetch(url, { ...init, headers: { ...init.headers as Record<string, string>, authorization: `Bearer ${owner}`, host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}` } }),
+ linkHeaders: () => ({ authorization: `Bearer ${owner}`, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https" }),
+ });
+ const lending = connector;
+ lending.start();
+ const lentNow = async () => (await api("GET", "/api/shared-computers", { token: owner })).body;
+ await expect.poll(async () => (await lentNow()).computers[0]?.scopes.screen, { timeout: 8000 }).toBe(true);
+ lending.pause();
+ await expect.poll(async () => (await lentNow()).computers.length, { timeout: 5000 }).toBe(0);
+
+ const bot = (await api("POST", "/api/bots", { token: owner, body: { name: "Asker", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } } })).body.bot;
+ const call = await proxyFor(async () => {
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { token: owner, body: { text: "Open the invoice in Excel on my computer." } })).status).toBe(202);
+ }, bot.id);
+ const asked = call("ask_for_computer", { need: "screen", why: "Open the invoice in Excel" });
+ const card = async () => ((await api("GET", `/api/threads/${bot.threadId}/messages`, { token: owner })).body.messages ?? [])
+ .find((message: { card?: { computerAsk?: unknown } }) => message.card?.computerAsk)?.card;
+ await expect.poll(async () => (await card())?.computerAsk?.reason, { timeout: 15_000 }).toBe("paused");
+ expect(await card()).toMatchObject({ options: ["Turn on", "Not now"], requestType: "permission", tool: "turn_on_your_computer" });
+ await expect.poll(() => prompts.length, { timeout: 8000 }).toBe(1);
+
+ const { requestId } = await card();
+ expect((await api("POST", `/api/threads/${bot.threadId}/respond`, { token: owner, body: { requestId, behavior: "allow" } })).status).toBe(200);
+ const answer = await asked;
+ expect(answer.content[0].text).toContain("lends what you need now: computer_id");
+ expect(lending.paused()).toBe(false);
+ expect(await card()).toMatchObject({ answered: "allow", answeredBy: expect.any(Object), computerAsk: { state: "on" } });
+ expect(prompts, "the app's own prompt came up once").toHaveLength(1);
+ rmSync(pcHome, { recursive: true, force: true });
+}, hostTimeout(90_000));
diff --git a/server/computer-asks.test.ts b/server/computer-asks.test.ts
new file mode 100644
index 0000000000..a57981fbc9
--- /dev/null
+++ b/server/computer-asks.test.ts
@@ -0,0 +1,215 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ComputerAsks, type DesktopState, type OnlineComputer } from "./computer-asks.ts";
+import type { LentPlatform } from "./lent-computers.ts";
+import type { Message } from "./store.ts";
+
+const bot = { id: "scout", name: "Scout", color: "blue" } as unknown as Parameters<ComputerAsks["ask"]>[0]["bot"];
+const PC = { name: "HOME-PC", platform: "win32" } as const;
+const desktop = (fields: Partial<DesktopState> = {}): DesktopState => ({ ...PC, paused: false, screen: { ready: true, reason: null }, terminal: false, ...fields });
+const lends = (fields: Partial<OnlineComputer> = {}): OnlineComputer => ({ id: "pc-1", ...PC, computer: true, terminal: false, ...fields });
+
+function fixture({ known = [{ platform: "win32" }] }: { known?: Array<{ platform: LentPlatform | null }> } = {}) {
+ const threads = new Map<string, Message[]>();
+ const list = (threadId: string) => threads.get(threadId) ?? (threads.set(threadId, []), threads.get(threadId)!);
+ let next = 0;
+ let activity = "working";
+ const store = {
+ appendMessage: (threadId: string, message: Partial<Message>) => { const added = { id: `m${++next}`, at: Date.now(), ...message } as Message; list(threadId).push(added); return added; },
+ patchMessage: (threadId: string, id: string, patch: Partial<Message>) => { const found = list(threadId).find((message) => message.id === id); if (found) Object.assign(found, patch); return found ?? null; },
+ messagesFor: (threadId: string) => list(threadId),
+ projectBotForTask: () => ({ id: "scout", name: "Scout", busy: true, activity }),
+ setTaskActivity: (_id: string, _threadId: string, value: string) => { activity = value; },
+ groupByThread: () => null,
+ };
+ const state = { online: [] as OnlineComputer[], known, carried: [] as Array<{ threadId: string; requestMessageId: string; text: string }>, busy: false, notified: 0 };
+ const asks = new ComputerAsks({
+ store: store as never,
+ notify: () => { state.notified++; },
+ online: () => state.online,
+ known: () => state.known,
+ carryOn: (ask, text) => { if (state.busy) return false; state.carried.push({ threadId: ask.threadId, requestMessageId: ask.requestMessageId, text }); return true; },
+ });
+ const cards = (threadId = "t1") => list(threadId).filter((message) => message.card?.computerAsk);
+ const card = (threadId = "t1") => cards(threadId).at(-1)!.card!;
+ const present = (state: DesktopState, answers: Parameters<ComputerAsks["present"]>[1] = [], heard = -1) =>
+ asks.present(state, answers, { kind: "session", name: "Owner", person: "p_owner" }, heard, undefined, 10);
+ return { asks, state, store, cards, card, present, activity: () => activity };
+}
+
+describe("a bot on the person's own Cloud asks to turn on what it needs from their computer", () => {
+ beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(Date.UTC(2026, 9, 30, 12)); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("says it is ready at once, with no card, when the computer lends what is needed", async () => {
+ const f = fixture();
+ f.state.online = [lends()];
+ await expect(f.asks.ask({ threadId: "t1", bot, need: "screen", why: "Open Excel" })).resolves.toEqual({ state: "ready", computerId: "pc-1", device: "PC" });
+ expect(f.cards()).toHaveLength(0);
+ });
+
+ it("paused: one card with Turn on; the app there hears it; Turn on on the card turns it on and the waiting call carries on", async () => {
+ const f = fixture();
+ await f.present(desktop({ paused: true }));
+ const call = f.asks.ask({ threadId: "t1", bot, need: "screen", why: "Fill in the invoice in Excel", requestMessageId: "u1" });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(f.cards()).toHaveLength(1);
+ expect(f.card()).toMatchObject({
+ title: "Scout wants to use your PC's apps and screen",
+ subtitle: "Fill in the invoice in Excel\nUsing your PC is paused.",
+ options: ["Turn on", "Not now"], requestType: "permission", tool: "turn_on_your_computer",
+ computerAsk: { need: "screen", reason: "paused", device: "PC", state: "asking", why: "Fill in the invoice in Excel" },
+ });
+ expect(f.state.notified).toBe(1);
+ expect(f.activity()).toBe("waiting-on-you");
+ const heard = await f.present(desktop({ paused: true }));
+ expect(heard.asks).toEqual([expect.objectContaining({ need: "screen", reason: "paused", bot: "Scout", why: "Fill in the invoice in Excel", state: "asking", turnOn: 0 })]);
+
+ expect(f.asks.answer(f.card().requestId!, "allow")).toBe(true);
+ expect(f.card()).toMatchObject({ answered: "allow", computerAsk: { state: "turning-on" } });
+ expect((await f.present(desktop({ paused: true }), [], heard.version)).asks[0]).toMatchObject({ state: "turning-on", turnOn: 1 });
+
+ f.state.online = [lends()];
+ await f.present(desktop());
+ await expect(call).resolves.toEqual({ state: "ready", computerId: "pc-1", device: "PC" });
+ expect(f.card()).toMatchObject({ answered: "allow", computerAsk: { state: "on" } });
+ expect(f.card().dismissed).toBeUndefined();
+ expect(f.activity()).toBe("working");
+ expect(f.state.carried, "the waiting call carried on, so nothing else is started").toEqual([]);
+ });
+
+ it("not answered within the call: the bot is told to end its turn, and its request goes on by itself once it's on", async () => {
+ const f = fixture();
+ await f.present(desktop({ screen: { ready: false, reason: "not-running" } }));
+ f.state.online = [lends({ computer: false })];
+ const call = f.asks.ask({ threadId: "t1", bot, need: "screen", why: "Open Excel", requestMessageId: "u1" }, 2_000);
+ await vi.advanceTimersByTimeAsync(2_000);
+ const reply = await call;
+ expect(reply).toEqual({ state: "waiting", device: "PC", reason: "not-running" });
+ const said = ComputerAsks.say(reply, "Scout");
+ expect(said).toContain("End your turn now");
+ expect(said).toContain("Screen control isn't running on your PC.");
+ expect(said).toContain("Don't switch to your own cloud computer");
+
+ f.state.busy = true;
+ f.asks.answer(f.card().requestId!, "allow");
+ f.state.online = [lends()];
+ await f.present(desktop());
+ expect(f.card().computerAsk?.state).toBe("on");
+ expect(f.state.carried, "the conversation is busy: it waits").toEqual([]);
+ f.state.busy = false;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.state.carried).toEqual([{ threadId: "t1", requestMessageId: "u1", text: expect.stringContaining("Carry on with their request where you left off") }]);
+ });
+
+ it("Not now: the bot is told, and the same bot asking again in that conversation isn't put to them again for a while", async () => {
+ const f = fixture();
+ await f.present(desktop({ paused: true }));
+ const call = f.asks.ask({ threadId: "t1", bot, need: "folders", why: "Read the budget" });
+ await vi.advanceTimersByTimeAsync(0);
+ f.asks.answer(f.card().requestId!, "deny");
+ await expect(call).resolves.toEqual({ state: "declined", device: "PC", reason: "paused" });
+ expect(f.card()).toMatchObject({ answered: "deny", computerAsk: { state: "declined" } });
+ await expect(f.asks.ask({ threadId: "t1", bot, need: "folders" }, 10)).resolves.toMatchObject({ state: "declined" });
+ expect(f.cards()).toHaveLength(1);
+ vi.setSystemTime(Date.now() + 11 * 60_000);
+ await f.present(desktop({ paused: true }));
+ void f.asks.ask({ threadId: "t1", bot, need: "folders" }, 10);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(f.cards(), "asked again once a while has passed").toHaveLength(2);
+ });
+
+ it("the app closed: no Turn on, the fix is opening it; the card follows the app when it comes back", async () => {
+ const f = fixture();
+ const call = f.asks.ask({ threadId: "t1", bot, need: "screen", why: "Open Excel" }, 30_000);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(f.card()).toMatchObject({ options: ["Not now"], computerAsk: { reason: "closed", device: "PC" } });
+ expect(f.card().subtitle).toContain("MausBot isn't open on your PC. Open it there and Scout carries on.");
+ await f.present(desktop({ paused: true }));
+ expect(f.card()).toMatchObject({ options: ["Turn on", "Not now"], computerAsk: { reason: "paused" } });
+ f.state.online = [lends()];
+ await f.present(desktop());
+ await expect(call).resolves.toMatchObject({ state: "ready" });
+ expect(f.card(), "nobody tapped: the harness settled it, in nobody's words").toMatchObject({ answered: "allow", dismissed: true, computerAsk: { state: "on" } });
+ });
+
+ it("never lent: the card says to install the app; an app too old to answer says to update it", async () => {
+ const never = fixture({ known: [] });
+ void never.asks.ask({ threadId: "t1", bot, need: "screen" }, 30_000);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(never.card().computerAsk).toMatchObject({ reason: "never", device: "computer" });
+ const old = fixture();
+ old.state.online = [lends({ computer: false })];
+ void old.asks.ask({ threadId: "t1", bot, need: "screen" }, 30_000);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(old.card().computerAsk).toMatchObject({ reason: "update", device: "PC" });
+ });
+
+ it("the app's own prompt: its Turn on and Not now are the person's, and a start that fails says why and offers Try again", async () => {
+ const f = fixture();
+ await f.present(desktop({ screen: { ready: false, reason: "not-running" } }));
+ f.state.online = [lends({ computer: false })];
+ void f.asks.ask({ threadId: "t1", bot, need: "screen" }, 60_000);
+ await vi.advanceTimersByTimeAsync(0);
+ const id = f.card().requestId!;
+ await f.present(desktop({ screen: { ready: false, reason: "not-running" } }), [{ id, outcome: "turning-on" }]);
+ expect(f.card()).toMatchObject({ answered: "allow", answeredBy: { kind: "session", name: "Owner", person: "p_owner" }, computerAsk: { state: "turning-on" } });
+ await f.present(desktop({ screen: { ready: false, reason: "blocked" } }), [{ id, outcome: "failed", reason: "blocked" }]);
+ expect(f.card()).toMatchObject({ options: ["Try again", "Not now"], computerAsk: { state: "failed", reason: "blocked" } });
+ expect(f.card().answered, "back in front of the person").toBeUndefined();
+ expect(f.card().subtitle).toContain("Windows Security may have stopped it");
+ await expect(f.asks.ask({ threadId: "t1", bot, need: "screen" })).resolves.toEqual({ state: "failed", device: "PC", reason: "blocked" });
+ await f.present(desktop({ screen: { ready: false, reason: "blocked" } }), [{ id, outcome: "declined" }]);
+ expect(f.card()).toMatchObject({ answered: "deny", answeredBy: { kind: "session", name: "Owner", person: "p_owner" }, computerAsk: { state: "declined" } });
+ });
+
+ it("a Turn on that never takes says so after a while", async () => {
+ const f = fixture();
+ await f.present(desktop({ paused: true }));
+ void f.asks.ask({ threadId: "t1", bot, need: "screen" }, 1_000);
+ await vi.advanceTimersByTimeAsync(0);
+ f.asks.answer(f.card().requestId!, "allow");
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(f.card().computerAsk).toMatchObject({ state: "failed", reason: "closed" });
+ });
+
+ it("a Mac lacking macOS's permissions lends its screen but isn't ready: the card asks to allow it", async () => {
+ const f = fixture({ known: [{ platform: "darwin" }] });
+ await f.present(desktop({ name: "Mac", platform: "darwin", screen: { ready: false, reason: "permissions" } }));
+ f.state.online = [lends({ name: "Mac", platform: "darwin" })];
+ void f.asks.ask({ threadId: "t1", bot, need: "screen" }, 1_000);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(f.card()).toMatchObject({ options: ["Turn on", "Not now"], computerAsk: { reason: "permissions", device: "Mac" } });
+ await f.present(desktop({ name: "Mac", platform: "darwin" }));
+ expect(f.card().computerAsk?.state).toBe("on");
+ });
+
+ it("one card per need in a conversation; Stop ends it", async () => {
+ const f = fixture();
+ await f.present(desktop({ paused: true }));
+ const first = f.asks.ask({ threadId: "t1", bot, need: "screen" }, 60_000);
+ const second = f.asks.ask({ threadId: "t1", bot, need: "screen" }, 60_000);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(f.cards()).toHaveLength(1);
+ f.asks.cancel("t1");
+ await expect(first).resolves.toMatchObject({ state: "declined" });
+ await expect(second).resolves.toMatchObject({ state: "declined" });
+ expect(f.card()).toMatchObject({ dismissed: true, computerAsk: { state: "ended" } });
+ });
+
+ it("starting by itself: no card, the bot is told to call again in a moment", async () => {
+ const f = fixture();
+ await f.present(desktop({ screen: { ready: false, reason: "starting" } }));
+ const call = f.asks.ask({ threadId: "t1", bot, need: "screen" }, 2_000);
+ await vi.advanceTimersByTimeAsync(2_000);
+ await expect(call).resolves.toEqual({ state: "waiting", device: "PC", reason: "starting" });
+ expect(f.cards()).toHaveLength(0);
+ });
+
+ it("the words the bot gets never send it to its own cloud computer, and name the computer it can use", () => {
+ expect(ComputerAsks.say({ state: "ready", computerId: "pc-1", device: "PC" }, "Scout")).toContain("computer_id pc-1");
+ for (const state of ["declined", "failed", "unavailable"] as const) {
+ expect(ComputerAsks.say({ state, device: "PC", reason: "unsupported" }, "Scout")).toContain("Don't switch to your own cloud computer");
+ }
+ });
+});
diff --git a/server/computer-asks.ts b/server/computer-asks.ts
new file mode 100644
index 0000000000..64bc081fea
--- /dev/null
+++ b/server/computer-asks.ts
@@ -0,0 +1,431 @@
+// A bot on the person's own Cloud that needs their computer when it isn't available asks once, with a card that has a
+// one-tap Turn on. The app on that computer, while open, says what it can't lend and why (`present`), hears
+// each ask, and does what Turn on asks for there; the first answer, on the card or in that app, wins. Once the computer
+// lends what was needed the bot carries on: its waiting call returns, or its request continues by itself. Asks live in
+// memory, and a card a previous run left open is closed at startup.
+import { z } from "zod";
+
+import { newId } from "./contracts.ts";
+import { deviceWord, LENT_PLATFORMS, type LentComputer, type LentPlatform } from "./lent-computers.ts";
+import { optionCardsForTools } from "./message-db.ts";
+import { buildNotification, type Notification } from "./notify.ts";
+import type { BotRecord, Store } from "./store.ts";
+import type { CardAnswerer } from "../shared/wire.ts";
+import {
+ ASK_FOR_COMPUTER_TOOL, cleanAskWhy, COMPUTER_ASK_TOOL, computerAskHeadline, computerAskReasonLine, computerAskText, needsTheApp, turnsOnFromHere,
+ type ComputerAskCard, type ComputerAskReason, type ComputerAskState, type ComputerDevice, type ComputerNeed,
+} from "../shared/computer-ask.ts";
+
+/** Why apps and screen aren't lent, as the app on that computer reads it. */
+export const SCREEN_REASONS = ["starting", "permissions", "blocked", "off", "not-running", "unsupported"] as const;
+export type ScreenReason = (typeof SCREEN_REASONS)[number];
+
+/** What the app on a computer says about it each time it asks for news. */
+export interface DesktopState {
+ name: string;
+ platform: LentPlatform | null;
+ paused: boolean;
+ screen: { ready: boolean; reason: ScreenReason | null };
+ terminal: boolean;
+}
+
+/** That app's answer to an ask: the person tapped Turn on or Not now in it, or it tried and couldn't (`reason`: why now). */
+export interface DesktopAnswer { id: string; outcome: "turning-on" | "declined" | "failed"; reason?: ScreenReason | "paused" | "terminal-off" }
+
+/** POST /api/shared-computers/asks: the app's state, the last `version` it heard, and its answers since. */
+export const desktopPresence = z.object({
+ name: z.string().min(1).max(120),
+ platform: z.enum(LENT_PLATFORMS).nullable(),
+ paused: z.boolean(),
+ screen: z.object({ ready: z.boolean(), reason: z.enum(SCREEN_REASONS).nullable() }).strict(),
+ terminal: z.boolean(),
+ heard: z.number().int().min(-1),
+ answers: z.array(z.object({
+ id: z.string().min(1).max(100),
+ outcome: z.enum(["turning-on", "declined", "failed"]),
+ reason: z.enum([...SCREEN_REASONS, "paused", "terminal-off"]).optional(),
+ }).strict()).max(20),
+}).strict();
+
+/** What that app hears: each open ask, and how many times Turn on was tapped on the card, so it acts once per tap. */
+export interface DesktopAsk { id: string; need: ComputerNeed; reason: ComputerAskReason; bot: string; why?: string; state: ComputerAskState; turnOn: number }
+
+/** A computer lending to this Cloud now. */
+export interface OnlineComputer { id: string; name: string; platform?: LentPlatform; computer: boolean; terminal: boolean }
+
+/** Who answered on the card or in the app: kept on the card, so the conversation stays the owner's own. */
+export type Answerer = CardAnswerer;
+
+export interface ComputerAsksDeps {
+ store: Pick<Store, "appendMessage" | "patchMessage" | "messagesFor" | "projectBotForTask" | "setTaskActivity" | "groupByThread">;
+ notify?: (notification: Notification | null) => void;
+ online(): OnlineComputer[];
+ /** Computers lent before, newest first. */
+ known(): Array<Pick<LentComputer, "platform">>;
+ /** The request goes on in its conversation now that the computer lends what it needed; false when it can't yet (the
+ * conversation is busy, or someone wrote since). */
+ carryOn(ask: { botId: string; threadId: string; requestMessageId: string }, text: string): boolean;
+ now?: () => number;
+ setTimer?: typeof setTimeout;
+ clearTimer?: typeof clearTimeout;
+}
+
+/** Each long poll of the app on a computer, and each wait of a bot's call. */
+export const PRESENT_WAIT_MS = 20_000;
+export const ASK_WAIT_MS = 40_000;
+/** The app on a computer polls at least this often while it is open. */
+export const PRESENT_FRESH_MS = 45_000;
+/** A sleeping Cloud's computer takes this long to come back after the Cloud wakes: an ask waits for it first. */
+export const RECONNECT_GRACE_MS = 20_000;
+/** Turn on was tapped: the computer has this long to lend what is needed. */
+export const TURN_ON_MS = 90_000;
+/** After Not now, the same bot asking for the same thing in the same conversation is told so, not asked again. */
+export const NOT_NOW_MS = 10 * 60_000;
+/** A request goes on by itself once its conversation is free, for this long. */
+export const CARRY_ON_MS = 15 * 60_000;
+const CARRY_ON_EVERY_MS = 5_000;
+const REFRESH_MS = 15_000;
+const OPEN_LIMIT = 50;
+
+type Outcome = "ready" | "declined" | "failed" | "ended";
+
+interface Ask {
+ id: string; threadId: string; botId: string; botName: string; messageId: string; requestMessageId?: string;
+ need: ComputerNeed; why?: string; reason: ComputerAskReason; device: ComputerDevice; state: ComputerAskState;
+ turnOn: number; createdAt: number; settledAt?: number; deadline?: ReturnType<typeof setTimeout>;
+ waiters: Set<(outcome: Outcome) => void>;
+}
+
+export type AskReply =
+ | { state: "ready"; computerId: string; device: ComputerDevice }
+ | { state: "waiting" | "declined" | "failed" | "unavailable"; device: ComputerDevice; reason: ComputerAskReason };
+
+const OPEN: ReadonlySet<ComputerAskState> = new Set(["asking", "turning-on", "failed"]);
+
+export class ComputerAsks {
+ private asks = new Map<string, Ask>();
+ private desktops = new Map<string, { state: DesktopState; seen: number }>();
+ private version = 0;
+ private listeners = new Set<() => void>();
+ /** While any ask is open its reason is read again this often: an app that quits stops polling without a word. */
+ private ticking: ReturnType<typeof setTimeout> | null = null;
+ private readonly deps: ComputerAsksDeps;
+ private readonly now: () => number;
+ private readonly setTimer: typeof setTimeout;
+ private readonly clearTimer: typeof clearTimeout;
+
+ constructor(deps: ComputerAsksDeps) {
+ this.deps = deps;
+ this.now = deps.now ?? Date.now;
+ this.setTimer = deps.setTimer ?? setTimeout;
+ this.clearTimer = deps.clearTimer ?? clearTimeout;
+ }
+
+ /** The app on a computer: how it is, its answers, then (after at most `waitMs`) the asks it hasn't heard yet. */
+ async present(state: DesktopState, answers: DesktopAnswer[], answerer: Answerer, heard: number, signal?: AbortSignal, waitMs = PRESENT_WAIT_MS): Promise<{ version: number; asks: DesktopAsk[] }> {
+ const before = this.desktops.get(state.name);
+ this.desktops.set(state.name, { state, seen: this.now() });
+ for (const answer of answers) this.desktopAnswer(answer, answerer);
+ if (!before || JSON.stringify(before.state) !== JSON.stringify(state)) this.refresh();
+ if (heard === this.version && !signal?.aborted) {
+ await new Promise<void>((resolve) => {
+ const done = () => { this.clearTimer(timer); this.listeners.delete(done); signal?.removeEventListener("abort", done); resolve(); };
+ const timer = this.setTimer(done, waitMs);
+ this.listeners.add(done);
+ signal?.addEventListener("abort", done, { once: true });
+ });
+ }
+ const entry = this.desktops.get(state.name);
+ if (entry) entry.seen = this.now();
+ return { version: this.version, asks: [...this.asks.values()].filter((ask) => OPEN.has(ask.state)).map((ask) => ({
+ id: ask.id, need: ask.need, reason: ask.reason, bot: ask.botName, ...(ask.why ? { why: ask.why } : {}), state: ask.state, turnOn: ask.turnOn,
+ })) };
+ }
+
+ /** A bot's call: ready at once when the computer lends what's needed; otherwise one card, then a wait of at most `waitMs`. */
+ async ask(input: { threadId: string; bot: Pick<BotRecord, "id" | "name" | "color" | "avatarUrl" | "notifications">; need: ComputerNeed; why?: unknown; requestMessageId?: string },
+ waitMs = ASK_WAIT_MS): Promise<AskReply> {
+ const started = this.now();
+ let met = this.met(input.need);
+ if (met) return { state: "ready", computerId: met.id, device: this.device() };
+ const open = [...this.asks.values()].find((ask) => ask.threadId === input.threadId && ask.need === input.need && OPEN.has(ask.state));
+ if (open?.state === "failed") return { state: "failed", device: open.device, reason: open.reason };
+ if (open) return this.waitFor(open, waitMs);
+ const refused = [...this.asks.values()].find((ask) => ask.threadId === input.threadId && ask.need === input.need && ask.botId === input.bot.id &&
+ ask.state === "declined" && this.now() - (ask.settledAt ?? 0) < NOT_NOW_MS);
+ if (refused) return { state: "declined", device: refused.device, reason: refused.reason };
+ // A computer that was online a moment ago, or whose app is open, comes back by itself after the Cloud wakes.
+ let reason = this.reasonFor(input.need);
+ while ((reason === "closed" || reason === "starting") && this.now() - started < Math.min(RECONNECT_GRACE_MS, waitMs)) {
+ await this.changeOrTimeout(1_000);
+ met = this.met(input.need);
+ if (met) return { state: "ready", computerId: met.id, device: this.device() };
+ reason = this.reasonFor(input.need);
+ }
+ if (!turnsOnFromHere(reason) && !needsTheApp(reason)) return { state: reason === "starting" ? "waiting" : "unavailable", device: this.device(), reason };
+ if ([...this.asks.values()].filter((ask) => OPEN.has(ask.state)).length >= OPEN_LIMIT) return { state: "unavailable", device: this.device(), reason };
+ const ask = this.raise(input, reason);
+ return this.waitFor(ask, Math.max(1_000, waitMs - (this.now() - started)));
+ }
+
+ /** A tap on the card. True when it was one of these. */
+ answer(requestId: string, behavior: string | undefined): boolean {
+ const ask = this.asks.get(requestId);
+ if (!ask) return false;
+ if (!OPEN.has(ask.state)) return true;
+ if (behavior !== "allow") { this.settle(ask, "declined"); return true; }
+ if (!turnsOnFromHere(ask.reason)) return true;
+ this.turnOn(ask);
+ return true;
+ }
+
+ /** A computer connected, changed what it lends, or left. */
+ lendingChanged(): void { this.refresh(); }
+
+ /** The conversation was stopped or deleted: nothing it asked for is needed any more. */
+ cancel(threadId: string): void {
+ for (const ask of this.asks.values()) if (ask.threadId === threadId && OPEN.has(ask.state)) this.settle(ask, "ended");
+ }
+
+ /** A card a previous run left open can never be answered: closed at startup. */
+ dismissStale(): number {
+ let dismissed = 0;
+ for (const { threadId, messageId } of optionCardsForTools([COMPUTER_ASK_TOOL])) {
+ const card = this.deps.store.messagesFor(threadId).find((message) => message.id === messageId)?.card;
+ if (!card?.computerAsk || this.asks.has(card.requestId ?? "") || !OPEN.has(card.computerAsk.state)) continue;
+ if (this.deps.store.patchMessage(threadId, messageId, { card: { ...card, answered: card.answered ?? "deny", dismissed: true, computerAsk: { ...card.computerAsk, state: "ended" } } })) dismissed += 1;
+ }
+ return dismissed;
+ }
+
+ /** Why the computer can't give `need` now, read fresh. */
+ reasonFor(need: ComputerNeed): ComputerAskReason {
+ const desktop = this.freshDesktop();
+ if (desktop?.paused) return "paused";
+ if (desktop) {
+ if (need === "screen") return desktop.screen.ready ? "starting" : desktop.screen.reason ?? "starting";
+ if (need === "terminal") return desktop.terminal ? "starting" : "terminal-off";
+ return "starting";
+ }
+ if (this.deps.online().length) return "update";
+ return this.deps.known().length ? "closed" : "never";
+ }
+
+ /** Words for the bot, from a reply. */
+ static say(reply: AskReply, name: string): string {
+ if (reply.state === "ready") {
+ return `Their ${reply.device} lends what you need now: computer_id ${reply.computerId}. Go on with shared_computer; verify the result before saying it's done.`;
+ }
+ const line = computerAskReasonLine({ reason: reply.reason, device: reply.device }, name);
+ const why = computerAskText(line.key, line.params);
+ const stay = `Don't switch to your own cloud computer or browser instead unless they ask you to.`;
+ if (reply.state === "waiting" && reply.reason === "starting") return `${why} Call ${ASK_FOR_COMPUTER_TOOL} again in a moment. ${stay}`;
+ if (reply.state === "waiting") return `A card in this chat asks them to turn it on (${why}) and they haven't yet, so nothing was done on their ${reply.device}. Don't ask again or explain the fix in chat: the card says it. End your turn now: once it's on, you carry on here by yourself. ${stay}`;
+ if (reply.state === "declined") return `They chose Not now. Don't use their ${reply.device} for this: say in one sentence what you couldn't do, and that you can once they turn it on. ${stay}`;
+ if (reply.state === "failed") return `It didn't turn on: ${why} The card lets them try again. Say so in one sentence. ${stay}`;
+ return `${why} Nothing here can turn it on: say so in one sentence. ${stay}`;
+ }
+
+ private raise(input: { threadId: string; bot: Pick<BotRecord, "id" | "name" | "color" | "avatarUrl" | "notifications">; need: ComputerNeed; why?: unknown; requestMessageId?: string }, reason: ComputerAskReason): Ask {
+ const { store } = this.deps;
+ const device = this.device();
+ const why = cleanAskWhy(input.why);
+ const room = store.groupByThread(input.threadId);
+ const id = newId();
+ const view: ComputerAskCard = { need: input.need, reason, device, state: "asking", ...(why ? { why } : {}) };
+ const message = store.appendMessage(input.threadId, {
+ role: "bot",
+ kind: "options",
+ ...(room ? { from: { botId: input.bot.id, name: input.bot.name, color: input.bot.color } } : {}),
+ card: { ...cardWords(view, input.bot.name), requestId: id, requestType: "permission", tool: COMPUTER_ASK_TOOL, computerAsk: view },
+ });
+ const ask: Ask = {
+ id, threadId: input.threadId, botId: input.bot.id, botName: input.bot.name, messageId: message.id,
+ ...(input.requestMessageId && !room ? { requestMessageId: input.requestMessageId } : {}),
+ need: input.need, ...(why ? { why } : {}), reason, device, state: "asking", turnOn: 0, createdAt: this.now(), waiters: new Set(),
+ };
+ this.asks.set(id, ask);
+ this.tick();
+ const task = store.projectBotForTask(input.bot.id, input.threadId);
+ if (task?.busy) store.setTaskActivity(input.bot.id, input.threadId, "waiting-on-you");
+ this.deps.notify?.(buildNotification("approval", input.bot, input.threadId, cardWords(view, input.bot.name).title, {
+ avatarUrl: input.bot.avatarUrl, ...(room && !room.dm ? { group: { id: room.id, name: room.name } } : {}),
+ }));
+ this.bump();
+ return ask;
+ }
+
+ private waitFor(ask: Ask, waitMs: number): Promise<AskReply> {
+ const reply = (outcome: Outcome | "waiting"): AskReply => {
+ if (outcome === "ready") {
+ const met = this.met(ask.need);
+ if (met) return { state: "ready", computerId: met.id, device: ask.device };
+ }
+ if (outcome === "declined" || outcome === "ended") return { state: "declined", device: ask.device, reason: ask.reason };
+ if (outcome === "failed") return { state: "failed", device: ask.device, reason: ask.reason };
+ return { state: "waiting", device: ask.device, reason: ask.reason };
+ };
+ if (ask.state === "on") return Promise.resolve(reply("ready"));
+ return new Promise((resolve) => {
+ const done = (outcome: Outcome | "waiting") => { this.clearTimer(timer); ask.waiters.delete(done); resolve(reply(outcome)); };
+ const timer = this.setTimer(() => done("waiting"), waitMs);
+ ask.waiters.add(done);
+ });
+ }
+
+ private turnOn(ask: Ask): void {
+ ask.turnOn += 1;
+ ask.state = "turning-on";
+ if (ask.deadline) this.clearTimer(ask.deadline);
+ ask.deadline = this.setTimer(() => {
+ ask.deadline = undefined;
+ if (ask.state !== "turning-on") return;
+ ask.reason = this.reasonFor(ask.need);
+ this.fail(ask);
+ }, TURN_ON_MS);
+ this.patch(ask, { answered: "allow" });
+ this.bump();
+ }
+
+ private desktopAnswer(answer: DesktopAnswer, answerer: Answerer): void {
+ const ask = this.asks.get(answer.id);
+ if (!ask || !OPEN.has(ask.state)) return;
+ if (answer.outcome === "declined") { this.settle(ask, "declined", answerer); return; }
+ if (answer.outcome === "turning-on") {
+ if (ask.state === "turning-on") return;
+ this.turnOn(ask);
+ this.patch(ask, { answered: "allow", answeredBy: answerer });
+ return;
+ }
+ if (answer.reason) ask.reason = answer.reason;
+ this.fail(ask);
+ }
+
+ private fail(ask: Ask): void {
+ if (ask.deadline) { this.clearTimer(ask.deadline); ask.deadline = undefined; }
+ ask.state = "failed";
+ this.patch(ask, { answered: undefined, answeredBy: undefined });
+ for (const waiter of ask.waiters) waiter("failed");
+ this.bump();
+ }
+
+ /** Every open ask whose need the computer meets now is on; the others take the reason as it is now. */
+ private refresh(): void {
+ let changed = false;
+ for (const ask of this.asks.values()) {
+ if (!OPEN.has(ask.state)) continue;
+ const met = this.met(ask.need);
+ if (met) { this.on(ask); changed = true; continue; }
+ if (ask.state !== "asking") continue;
+ const reason = this.reasonFor(ask.need);
+ if (reason === ask.reason || reason === "starting") continue;
+ ask.reason = reason;
+ ask.device = this.device();
+ this.patch(ask, {});
+ changed = true;
+ }
+ if (changed) this.bump();
+ }
+
+ private on(ask: Ask): void {
+ if (ask.deadline) { this.clearTimer(ask.deadline); ask.deadline = undefined; }
+ const tapped = ask.state === "turning-on";
+ ask.state = "on";
+ ask.settledAt = this.now();
+ // Nobody tapped when the app there came back by itself: the harness settled it, in nobody's words.
+ this.patch(ask, tapped ? { answered: "allow" } : { answered: "allow", dismissed: true });
+ this.idle(ask);
+ const waiting = [...ask.waiters];
+ for (const waiter of waiting) waiter("ready");
+ if (!waiting.length && ask.requestMessageId) this.carryOn(ask, this.now());
+ }
+
+ private carryOn(ask: Ask, since: number): void {
+ const requestMessageId = ask.requestMessageId;
+ if (!requestMessageId) return;
+ const text = `[Their ${ask.device} lends what you asked for now.] Carry on with their request where you left off: list_shared_computers gives its computer_id for shared_computer. Verify the result before saying it's done.`;
+ if (this.deps.carryOn({ botId: ask.botId, threadId: ask.threadId, requestMessageId }, text)) return;
+ if (this.now() - since >= CARRY_ON_MS) return;
+ const timer = this.setTimer(() => this.carryOn(ask, since), CARRY_ON_EVERY_MS);
+ (timer as { unref?: () => void }).unref?.();
+ }
+
+ private settle(ask: Ask, state: "declined" | "ended", answerer?: Answerer): void {
+ if (ask.deadline) { this.clearTimer(ask.deadline); ask.deadline = undefined; }
+ ask.state = state;
+ ask.settledAt = this.now();
+ this.patch(ask, state === "ended" ? { answered: "deny", dismissed: true } : { answered: "deny", ...(answerer ? { answeredBy: answerer } : {}) });
+ this.idle(ask);
+ for (const waiter of ask.waiters) waiter(state);
+ this.bump();
+ }
+
+ private idle(ask: Ask): void {
+ const task = this.deps.store.projectBotForTask(ask.botId, ask.threadId);
+ if (task?.activity === "waiting-on-you") this.deps.store.setTaskActivity(task.id, ask.threadId, "working");
+ }
+
+ private patch(ask: Ask, fields: { answered?: string; answeredBy?: Answerer; dismissed?: boolean }): void {
+ const { store } = this.deps;
+ const card = store.messagesFor(ask.threadId).find((message) => message.id === ask.messageId)?.card;
+ if (!card) return;
+ const view: ComputerAskCard = { need: ask.need, reason: ask.reason, device: ask.device, state: ask.state, ...(ask.why ? { why: ask.why } : {}) };
+ const next = { ...card, ...cardWords(view, ask.botName), computerAsk: view, ...fields };
+ for (const key of ["answered", "answeredBy"] as const) if (Object.hasOwn(fields, key) && fields[key] === undefined) delete next[key];
+ store.patchMessage(ask.threadId, ask.messageId, { card: next });
+ }
+
+ private met(need: ComputerNeed): OnlineComputer | null {
+ return this.deps.online().find((computer) => {
+ if (need === "terminal") return computer.terminal;
+ if (need === "folders") return true;
+ const desktop = this.desktops.get(computer.name);
+ return computer.computer && (!desktop || this.now() - desktop.seen >= PRESENT_FRESH_MS || desktop.state.screen.ready);
+ }) ?? null;
+ }
+
+ private freshDesktop(): DesktopState | null {
+ let newest: { state: DesktopState; seen: number } | null = null;
+ for (const entry of this.desktops.values()) if (this.now() - entry.seen < PRESENT_FRESH_MS && (!newest || entry.seen > newest.seen)) newest = entry;
+ return newest?.state ?? null;
+ }
+
+ private device(): ComputerDevice {
+ return deviceWord(this.freshDesktop()?.platform ?? this.deps.online()[0]?.platform ?? this.deps.known()[0]?.platform ?? null);
+ }
+
+ private tick(): void {
+ if (this.ticking) return;
+ this.ticking = this.setTimer(() => {
+ this.ticking = null;
+ this.refresh();
+ if ([...this.asks.values()].some((ask) => OPEN.has(ask.state))) this.tick();
+ }, REFRESH_MS);
+ (this.ticking as { unref?: () => void }).unref?.();
+ }
+
+ private bump(): void {
+ this.version += 1;
+ for (const listener of this.listeners) listener();
+ }
+
+ private changeOrTimeout(ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ const done = () => { this.clearTimer(timer); this.listeners.delete(done); resolve(); };
+ const timer = this.setTimer(done, ms);
+ this.listeners.add(done);
+ });
+ }
+}
+
+/** The card's English, for clients that read only its title, subtitle and options. */
+function cardWords(view: ComputerAskCard, name: string): { title: string; subtitle: string; options: string[] } {
+ const headline = computerAskHeadline(view);
+ const reason = computerAskReasonLine(view, name);
+ const title = computerAskText(headline.key, { ...headline.params, name });
+ const subtitle = [view.why, computerAskText(reason.key, reason.params)].filter(Boolean).join("\n");
+ const options = turnsOnFromHere(view.reason)
+ ? [computerAskText(view.state === "failed" ? "computerAsk.action.tryAgain" : "computerAsk.action.turnOn", {}), computerAskText("computerAsk.action.notNow", {})]
+ : [computerAskText("computerAsk.action.notNow", {})];
+ return { title, subtitle, options };
+}
diff --git a/server/drivers/agents-bridge-wire.test.ts b/server/drivers/agents-bridge-wire.test.ts
index 8fca3ae718..7d8619b4e7 100644
--- a/server/drivers/agents-bridge-wire.test.ts
+++ b/server/drivers/agents-bridge-wire.test.ts
@@ -97,7 +97,7 @@ const BUDGET_BASELINE: Record<string, number> = {
"skills+voice+non-chief": 17093,
"skills+shared+non-chief": 16352,
"skills+shared+voice+non-chief": 17133,
- "skills+shared+voice+cloud-home": 16910,
+ "skills+shared+voice+cloud-home": 17266,
"skills+shared+voice+non-chief+cloud-home": 17131,
"skills+shared+voice+escalations": 16930,
"skills+shared+voice+escalations+x": 16991,
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.ts
index d65bacc67e..8a1df2385d 100644
--- a/server/drivers/agents-call.ts
+++ b/server/drivers/agents-call.ts
@@ -15,6 +15,7 @@ import { outOfBounds } from "./agents-schema.ts";
import { callResearchTool, RESEARCH_TOOL_NAMES } from "./agents-research-tools.ts";
import { callHelperTool, HELPER_TOOL_NAMES } from "./agents-helper-tools.ts";
import { callWaitTool, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts";
+import { callComputerAskTool, COMPUTER_ASK_TOOL_NAMES } from "./agents-computer-ask-tool.ts";
import { callMausBotTool, MAUSBOT_TOOL_NAMES } from "./agents-mausbot-tools.ts";
import { callPageTool, PAGE_TOOL_NAMES } from "./agents-pages-tools.ts";
import { callPersonTool, PERSON_TOOL_NAMES } from "./agents-person-tools.ts";
@@ -219,6 +220,7 @@ export async function callTool(called: string, input: Json, context: ToolCallCon
if (DEVS_TOOL_NAMES.has(name)) return callDevsTool(name, args, context);
if (TRIGGER_TOOL_NAMES.has(name)) return callTriggerTool(name, args, context);
if (WAIT_TOOL_NAMES.has(name)) return callWaitTool(name, args, context);
+ if (COMPUTER_ASK_TOOL_NAMES.has(name)) return callComputerAskTool(args, context);
// Second lock: with sharing off the catalog already omits these tools.
if (SHARED_COMPUTER_TOOL_NAMES.has(name) && !context.sharedComputers) {
return { text: "Computer sharing is turned off in this workspace. There are no shared computers to use.", isError: true };
diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.json
index 9b03bd138e..af1e573b9e 100644
--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json
+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json
@@ -344,8 +344,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 17248,
- "sha256": "f8cf96cf2eed4d6dac28bc178f5017df7c7adb2b505f81cd5536ee80c9efe1fa",
+ "bytes": 17266,
+ "sha256": "d88a513cc1bad7358f3cd27db3da71171f470caeb737d934a1d49bd1d9667c9e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -366,8 +366,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 17131,
- "sha256": "b8fed5a5dfaec1de4f5133d85bcdbd82ef3ae30403f4181d260c191dcf35abe1",
+ "bytes": 17149,
+ "sha256": "6543a09b99a7a08be472169d328c5b8186d02cd1b40a10424b5a4b6010b85c22",
"tools": [
"tool_result_read",
"list_room_targets",
diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json
index 9a5ea351c2..71ae433f45 100644
--- a/server/drivers/agents-catalog-goldens/profiles.json
+++ b/server/drivers/agents-catalog-goldens/profiles.json
@@ -768,8 +768,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 62047,
- "sha256": "ba173aa0ed0983aac23caae398251275e11c2d9f31a38cff224b0c364f3e8ae7",
+ "bytes": 62732,
+ "sha256": "ac6ae243a2d73135798c328c217de50cb9cd807aa8022ccafd89254a079766a3",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -812,6 +812,7 @@
"wait_until",
"list_waits",
"cancel_wait",
+ "ask_for_computer",
"propose_profile",
"propose_model",
"propose_team_memory",
@@ -821,8 +822,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 52990,
- "sha256": "c4e8af27c527477c8ffa2404b37f44778f20aa0af9ef68c8362a881fdeb06fe0",
+ "bytes": 53675,
+ "sha256": "b2b2d4b9a6db6b49f99751f7569d8b19201736606803724528fa6227a20610b1",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -858,6 +859,7 @@
"wait_until",
"list_waits",
"cancel_wait",
+ "ask_for_computer",
"propose_profile",
"propose_model",
"propose_team_memory",
diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.ts
index e4cb898c96..1eeafb3540 100644
--- a/server/drivers/agents-catalog-wire.test.ts
+++ b/server/drivers/agents-catalog-wire.test.ts
@@ -74,6 +74,8 @@ const MAUSBOT_TOOLS = ["list_unread_notifications", "mark_notifications_read"];
/** MausBot's tools may make its list at most this much longer than the same Chief's without them. */
const MAUSBOT_ADDS = 0.02;
const RESEARCH_TOOLS = ["x_search", "research_search", "research_endpoint", "research_call"];
+/** Only on the person's own Cloud: never on the fullest profile, a Team Cloud's. */
+const OWN_CLOUD_TOOLS = ["ask_for_computer"];
/** The fullest profile, checked in whole; every other one is pinned by tool names, bytes and sha256. */
const FULL = "skills+shared+voice+escalations+x+team";
@@ -96,7 +98,7 @@ const BUDGET_BASELINE: Record<string, number> = {
"skills+shared+non-chief": 52617,
"skills+shared+voice+non-chief": 53398,
"skills+shared+voice+cloud-home": 61536,
- "skills+shared+voice+non-chief+cloud-home": 52479,
+ "skills+shared+voice+non-chief+cloud-home": 53675,
"default+legacy-switches": 56624,
"default+mausbot": 57275,
"skills+shared+voice+mausbot": 63106,
@@ -206,7 +208,7 @@ describe("agents proxy tools/list golden", () => {
const full = new Map(toolsOf(wires[FULL]!).map((tool) => [tool.name, JSON.stringify(tool)]));
for (const [name, profile] of Object.entries(PROFILES)) {
for (const tool of toolsOf(wires[name]!)) {
- if (profile.env.OMB_CLOUD_HOME === "1" && tool.name === "select_computer") continue;
+ if (profile.env.OMB_CLOUD_HOME === "1" && (tool.name === "select_computer" || OWN_CLOUD_TOOLS.includes(tool.name))) continue;
if (profile.env.OMB_CHIEF_OF_STAFF === "0" && CHIEF_TARGET_TOOLS.includes(tool.name)) continue;
if (profile.env.OMB_MAUSBOT === "1" && MAUSBOT_TOOLS.includes(tool.name)) continue;
expect(JSON.stringify(tool), `${name}: ${tool.name}`).toBe(full.get(tool.name));
@@ -247,6 +249,15 @@ describe("agents proxy tools/list golden", () => {
}
});
+ it("mounts ask_for_computer only on a person's own Cloud that is lent their computer, never a Team Cloud", () => {
+ for (const [name, profile] of Object.entries(PROFILES)) {
+ expect(toolsOf(wires[name]!).some((tool) => tool.name === "ask_for_computer"), name)
+ .toBe(profile.env.OMB_CLOUD_HOME === "1" && profile.env.OMB_SHARED_COMPUTERS_ENABLED === "1" && profile.env.OMB_TEAM_PEOPLE !== "1");
+ }
+ const team = catalogProfileFromEnv({ ...PROFILES["skills+shared+voice+cloud-home"]!.env, OMB_TEAM_PEOPLE: "1", OMB_BOT_ID: "bot-golden" });
+ expect(availableTools(team).map((tool) => tool.name)).not.toContain("ask_for_computer");
+ });
+
it("ignores the switches that once picked a catalog profile", () => {
expect(wires["default+legacy-switches"]).toBe(wires.default);
const profile = catalogProfileFromEnv({ OMB_BOT_ID: "bot-golden", OMB_CHIEF_OF_STAFF: "1", OMB_COMPUTER_SELECTION: "1", OMB_ROOM_TURN: "1", OMB_OWN_THREAD_CREATION: "1", OMB_EXTERNAL_RUNTIME: "1", OMB_ACTIVE_WAITS: "0" });
@@ -265,7 +276,8 @@ describe("agents proxy tools/list golden", () => {
for (const name of cloudHome) {
const desktop = wires[name.slice(0, -"+cloud-home".length)]!;
const names = toolsOf(wires[name]!).map((tool) => tool.name);
- expect(names).toEqual(toolsOf(desktop).map((tool) => tool.name).filter((tool) => tool !== "vm_exec"));
+ expect(names).toEqual(expect.arrayContaining(OWN_CLOUD_TOOLS));
+ expect(names.filter((tool) => !OWN_CLOUD_TOOLS.includes(tool))).toEqual(toolsOf(desktop).map((tool) => tool.name).filter((tool) => tool !== "vm_exec"));
expect(select(desktop).inputSchema.properties.surface.enum).toEqual(["auto", "cloud", "vm", "local", "browser"]);
expect(toolsOf(desktop).map((tool) => tool.name)).toContain("vm_exec");
const surface = select(wires[name]!).inputSchema.properties.surface;
diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.ts
index a705c95e20..079fb38793 100644
--- a/server/drivers/agents-catalog.ts
+++ b/server/drivers/agents-catalog.ts
@@ -6,6 +6,7 @@ import { CHAT_CARD_TOOL_DEFINITIONS } from "./agents-chat-card-tools.ts";
import { DEVS_TOOL_DEFINITIONS } from "./agents-devs-tools.ts";
import { HELPER_TOOL_DEFINITIONS } from "./agents-helper-tools.ts";
import { WAIT_TOOL_DEFINITIONS, WAIT_TOOL_NAMES } from "./agents-wait-tools.ts";
+import { COMPUTER_ASK_TOOL_DEFINITIONS, COMPUTER_ASK_TOOL_NAMES } from "./agents-computer-ask-tool.ts";
import { MAUSBOT_TOOL_DEFINITIONS } from "./agents-mausbot-tools.ts";
import { PERSON_TOOL_DEFINITIONS, PERSON_TOOL_NAMES } from "./agents-person-tools.ts";
import { RESEARCH_TOOL_DEFINITIONS, RESEARCH_TOOL_NAMES } from "./agents-research-tools.ts";
@@ -645,6 +646,7 @@ const TOOL_DEFINITIONS = [
},
},
...WAIT_TOOL_DEFINITIONS,
+ ...COMPUTER_ASK_TOOL_DEFINITIONS,
{
name: "propose_profile",
description:
@@ -902,9 +904,10 @@ function catalogTools(profile: CatalogProfile) {
const AUTHORING_TOOLS = profile.skillAuthoring
? BOT_SCOPED_TOOLS
: BOT_SCOPED_TOOLS.filter((tool) => !SKILL_TOOL_NAMES.has(tool.name));
- const SHAREABLE_TOOLS = profile.sharedComputers
+ const SHAREABLE_TOOLS = (profile.sharedComputers
? AUTHORING_TOOLS
- : AUTHORING_TOOLS.filter((tool) => !SHARED_COMPUTER_TOOL_NAMES.has(tool.name));
+ : AUTHORING_TOOLS.filter((tool) => !SHARED_COMPUTER_TOOL_NAMES.has(tool.name)))
+ .filter((tool) => (profile.sharedComputers && profile.cloudHome && profile.team !== true) || !COMPUTER_ASK_TOOL_NAMES.has(tool.name));
const VOICE_READY_TOOLS = profile.voiceNotes
? SHAREABLE_TOOLS
: SHAREABLE_TOOLS.filter((tool) => !VOICE_TOOL_NAMES.has(tool.name));
diff --git a/server/drivers/agents-computer-ask-tool.ts b/server/drivers/agents-computer-ask-tool.ts
new file mode 100644
index 0000000000..8172934562
--- /dev/null
+++ b/server/drivers/agents-computer-ask-tool.ts
@@ -0,0 +1,28 @@
+import { ASK_FOR_COMPUTER_TOOL, COMPUTER_NEEDS } from "../../shared/computer-ask.ts";
+import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";
+import type { Json } from "./agents-client.ts";
+
+/** Only on the person's own Cloud (not a Team Cloud), where their own computer is lent to it. */
+export const COMPUTER_ASK_TOOL_NAMES: ReadonlySet<string> = new Set([ASK_FOR_COMPUTER_TOOL]);
+
+export async function callComputerAskTool(args: Json, context: ToolCallContext): Promise<ToolCallResult> {
+ const { ok, body } = await context.client.apiResponse("/api/internal/computer-asks", { method: "POST", body: JSON.stringify(args) });
+ return ok ? { text: String(body.text ?? "") } : { text: String(body.error ?? "The card did not go through. Try again shortly."), isError: true };
+}
+
+export const COMPUTER_ASK_TOOL_DEFINITIONS = [
+ {
+ name: ASK_FOR_COMPUTER_TOOL,
+ description:
+ "Ask the person to turn on what a request needs from their own computer when list_shared_computers or shared_computer says it isn't available: one card with your why and a one-tap Turn on. Waits up to 40 s; returns its computer_id once on. If not yet, end your turn: you carry on once it's on.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ need: { type: "string", enum: [...COMPUTER_NEEDS], description: "screen: its apps and screen; folders: its files; terminal: commands." },
+ why: { type: "string", maxLength: 200, description: "One sentence for the card: what you'll do there and why." },
+ },
+ required: ["need", "why"],
+ },
+ },
+];
diff --git a/server/environment.test.ts b/server/environment.test.ts
index 0c2e2e9a3c..678e327177 100644
--- a/server/environment.test.ts
+++ b/server/environment.test.ts
@@ -138,7 +138,7 @@ describe("environment identity", () => {
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, ownHome: false }).capabilities).not.toHaveProperty("move");
// A lent computer may lend its internet connection only to a Cloud home that lends at all.
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true, sharedComputers: true }).capabilities)
- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, fileEdits: true, deviceLink: true, myChromeLink: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });
+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, fileEdits: true, deviceLink: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });
expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities).not.toHaveProperty("deviceLink");
});
diff --git a/server/environment.ts b/server/environment.ts
index c41038fae7..b1b800d258 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -30,6 +30,9 @@ export interface EnvironmentDescriptor {
deviceLink?: true;
/** A personal Cloud home with lending on: a lent computer may lend its Chrome to the bots here. Never a team Cloud. */
myChromeLink?: true;
+ /** The same: the app on the person's computer says how it is and hears what the bots here ask of it
+ * (POST /api/shared-computers/asks). */
+ computerAsks?: true;
/** A lent computer may say it takes run_command's timeout_seconds; only then does this server send it. */
commandTimeouts?: true;
/** A lent computer may say it takes edit_file, append_file and delete_file; only then does this server send them. */
@@ -140,7 +143,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan
// lendingDetails: a lent computer may say its platform, and this server remembers what was lent to it.
...(input.sharedComputers === true ? { sharedComputers: true as const, lendingDetails: true as const, commandTimeouts: true as const, fileEdits: true as const } : {}),
...(input.sharedComputers === true && input.cloudHome === true ? { deviceLink: true as const } : {}),
- ...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const } : {}),
+ ...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const, computerAsks: true as const } : {}),
...(input.cloudHome === true ? { cloudHome: true as const, move: 1 as const } : {}),
...(input.ownHome === true && input.cloudHome !== true ? { move: 1 as const } : {}),
...(input.cloudHome === true && input.cloudTeam === true ? { cloudTeam: true as const } : {}),
diff --git a/server/host/computer-asks-host.test.ts b/server/host/computer-asks-host.test.ts
new file mode 100644
index 0000000000..d13688a9eb
--- /dev/null
+++ b/server/host/computer-asks-host.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createComputerAsksHost } from "./computer-asks-host.ts";
+import type { Message } from "../store.ts";
+
+const turn = { botId: "scout", threadId: "t1", generation: "g1" };
+
+function fixture({ computer = "on" as string, refusal = null as string | null, active = true } = {}) {
+ const lines: Message[] = [{ id: "u1", at: 1, role: "user", kind: "text", text: "Open the invoice in Excel on my PC." } as Message];
+ const store = {
+ appendMessage: (_threadId: string, message: Partial<Message>) => { const added = { id: `m${lines.length + 1}`, at: Date.now(), ...message } as Message; lines.push(added); return added; },
+ patchMessage: (_threadId: string, id: string, patch: Partial<Message>) => Object.assign(lines.find((line) => line.id === id) ?? {}, patch),
+ messagesFor: () => lines,
+ activePath: () => lines,
+ taskByThread: () => ({ id: "scout", threadId: "t1" }),
+ projectBotForTask: () => ({ id: "scout", name: "Scout", color: "blue", computer, busy: true, activity: "working" }),
+ setTaskActivity: () => {},
+ groupByThread: () => null,
+ };
+ const lending = { lendingNow: vi.fn(() => [] as Array<{ id: string; name: string; computer: boolean; terminal: boolean }>), known: () => [{ platform: "win32" as const }], changed: () => {}, askTool: null as string | null };
+ const continued: unknown[] = [];
+ const state = { busy: false };
+ const host = createComputerAsksHost({
+ store: store as never, notify: () => {}, lending: lending as never, principal: "cloud-home",
+ threadBusy: () => state.busy, queued: () => false,
+ continueRequest: async (...args) => { continued.push(args); },
+ refusal: () => refusal, request: () => ({ messageId: "u1", generations: new Set(["g1"]) }), active: () => active,
+ });
+ return { host, lines, lending, continued, state };
+}
+
+describe("ask_for_computer on the person's own Cloud", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("refuses an ended turn, a need it doesn't know, a bot with no computer, and a conversation that can't use the computer", async () => {
+ expect(await fixture({ active: false }).host.call(turn, { need: "screen" })).toMatchObject({ status: 401 });
+ expect(await fixture().host.call(turn, { need: "printer" })).toMatchObject({ status: 400 });
+ expect(await fixture({ computer: "off" }).host.call(turn, { need: "screen" })).toMatchObject({ status: 403, body: { error: expect.stringContaining("This bot has no computer") } });
+ const files = fixture({ computer: "off" });
+ files.lending.lendingNow.mockReturnValue([{ id: "pc-1", name: "PC", computer: false, terminal: false }]);
+ expect(await files.host.call(turn, { need: "folders" }), "files need no computer setting").toMatchObject({ status: 200, body: { state: "ready" } });
+ expect(await fixture({ refusal: "Someone else wrote in this conversation, so it can't use your PC." }).host.call(turn, { need: "screen" }))
+ .toEqual({ status: 403, body: { error: "Someone else wrote in this conversation, so it can't use your PC." } });
+ });
+
+ it("tells the shared computer texts to point at the ask, and answers ready at once when the computer lends what's needed", async () => {
+ const f = fixture();
+ expect(f.lending.askTool).toBe("ask_for_computer");
+ f.lending.lendingNow.mockReturnValue([{ id: "pc-1", name: "PC", computer: true, terminal: false }]);
+ expect(await f.host.call(turn, { need: "screen", why: "Open Excel" })).toEqual({ status: 200, body: { state: "ready", text: expect.stringContaining("computer_id pc-1") } });
+ });
+
+ it("carries the request on once the computer is on, only when the conversation is free and nobody wrote since", async () => {
+ const f = fixture();
+ const call = f.host.call(turn, { need: "screen", why: "Open Excel" });
+ await vi.advanceTimersByTimeAsync(40_000);
+ expect((await call).body).toMatchObject({ state: "waiting" });
+ expect(f.lines.find((line) => line.card?.computerAsk)?.card?.computerAsk, "the app isn't open there: the card says to open it").toMatchObject({ reason: "closed" });
+ f.state.busy = true;
+ f.lending.lendingNow.mockReturnValue([{ id: "pc-1", name: "PC", computer: true, terminal: false }]);
+ f.host.asks.lendingChanged();
+ expect(f.continued).toEqual([]);
+ f.state.busy = false;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.continued).toEqual([["scout", expect.stringContaining("Carry on with their request"), { threadId: "t1", cardContinuation: true, requestMessageId: "u1" }]]);
+ });
+
+ it("leaves the request alone when the person wrote since", async () => {
+ const f = fixture();
+ const call = f.host.call(turn, { need: "screen" });
+ await vi.advanceTimersByTimeAsync(40_000);
+ await call;
+ f.lines.push({ id: "u2", at: 2, role: "user", kind: "text", text: "Never mind, do it in the browser." } as Message);
+ f.lending.lendingNow.mockReturnValue([{ id: "pc-1", name: "PC", computer: true, terminal: false }]);
+ f.host.asks.lendingChanged();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(f.continued).toEqual([]);
+ });
+});
diff --git a/server/host/computer-asks-host.ts b/server/host/computer-asks-host.ts
new file mode 100644
index 0000000000..a8a6c31b6e
--- /dev/null
+++ b/server/host/computer-asks-host.ts
@@ -0,0 +1,79 @@
+// On the person's own Cloud: the asks its bots raise for their computer, read against what
+// lends now, the ask_for_computer call itself, and a request that goes on by itself once the computer is on.
+import type { ServerResponse } from "node:http";
+
+import { ComputerAsks } from "../computer-asks.ts";
+import type { json as sendJson } from "../harness/http.ts";
+import { PASS } from "../routes/table.ts";
+import type { Notification } from "../notify.ts";
+import type { SharedComputers } from "../shared-computers.ts";
+import type { Store } from "../store.ts";
+import { ASK_FOR_COMPUTER_TOOL, COMPUTER_NEEDS } from "../../shared/computer-ask.ts";
+
+type Turn = { botId: string; threadId: string; generation: string };
+
+export interface ComputerAsksHostDeps {
+ store: Store;
+ notify(notification: Notification | null): void;
+ lending: Pick<SharedComputers, "lendingNow" | "known"> & { changed: () => void; askTool: string | null };
+ /** Whose computers these are on a Cloud home. */
+ principal: string;
+ threadBusy(botId: string, threadId: string): boolean;
+ queued(botId: string, threadId: string): boolean;
+ continueRequest(botId: string, text: string, opts: { threadId: string; cardContinuation: true; requestMessageId: string }): Promise<unknown>;
+ /** Why this turn can't use the person's computer, in the words the bot says; null when it can. */
+ refusal(turn: Turn): string | null;
+ request(threadId: string): { messageId?: string; generations: ReadonlySet<string>; stopped?: boolean } | undefined;
+ /** The turn still runs: one that ended raises nothing. */
+ active(turn: Turn): boolean;
+}
+
+export function createComputerAsksHost(deps: ComputerAsksHostDeps) {
+ const { store } = deps;
+ const asks = new ComputerAsks({
+ store,
+ notify: deps.notify,
+ online: () => deps.lending.lendingNow(deps.principal),
+ known: () => deps.lending.known(deps.principal),
+ carryOn: ({ botId, threadId, requestMessageId }, text) => {
+ if (!store.taskByThread(botId, threadId)) return true;
+ if (deps.threadBusy(botId, threadId) || deps.queued(botId, threadId)) return false;
+ // Someone wrote since the bot asked: they lead now.
+ if (store.activePath(threadId).findLast((message) => message.role === "user" && message.kind === "text")?.id !== requestMessageId) return true;
+ void deps.continueRequest(botId, text, { threadId, cardContinuation: true, requestMessageId }).catch((error: unknown) => {
+ console.warn(`computer asks: the request could not go on: ${error instanceof Error ? error.message : String(error)}`);
+ });
+ return true;
+ },
+ });
+ deps.lending.changed = () => asks.lendingChanged();
+ deps.lending.askTool = ASK_FOR_COMPUTER_TOOL;
+
+ /** POST /api/internal/computer-asks: { need, why } from a bot's turn. */
+ async function call(turn: Turn, body: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
+ const input = body && typeof body === "object" ? body as { need?: unknown; why?: unknown } : {};
+ if (!deps.active(turn)) return { status: 401, body: { error: "This turn has ended." } };
+ const need = COMPUTER_NEEDS.find((candidate) => candidate === input.need);
+ if (!need) return { status: 400, body: { error: `need must be one of ${COMPUTER_NEEDS.join(", ")}` } };
+ const bot = store.projectBotForTask(turn.botId, turn.threadId);
+ if (!bot) return { status: 404, body: { error: "This bot no longer exists." } };
+ if (need === "screen" && bot.computer === "off") {
+ return { status: 403, body: { error: "This bot has no computer. Change its Computer setting to use their computer's apps and screen." } };
+ }
+ const refused = deps.refusal(turn);
+ if (refused) return { status: 403, body: { error: refused } };
+ const request = deps.request(turn.threadId);
+ const requestMessageId = request?.messageId && !request.stopped && request.generations.has(turn.generation) ? request.messageId : undefined;
+ const reply = await asks.ask({ threadId: turn.threadId, bot, need, why: input.why, ...(requestMessageId ? { requestMessageId } : {}) });
+ return { status: 200, body: { state: reply.state, text: ComputerAsks.say(reply, bot.name) } };
+ }
+
+ /** Inside index.ts's /api/internal/ block, after the capability bearer is checked: this route, or PASS. */
+ async function internal(ctx: { method: string; path: string; res: ServerResponse; json: typeof sendJson; turn: Turn; readBody: () => Promise<unknown> }): Promise<typeof PASS | void> {
+ if (ctx.method !== "POST" || ctx.path !== "/api/internal/computer-asks") return PASS;
+ const answer = await call(ctx.turn, await ctx.readBody());
+ ctx.json(ctx.res, answer.status, answer.body);
+ }
+
+ return { asks, call, internal };
+}
diff --git a/server/host/quota-switch.ts b/server/host/quota-switch.ts
index d56c97290e..7dcf7a01dc 100644
--- a/server/host/quota-switch.ts
+++ b/server/host/quota-switch.ts
@@ -20,6 +20,8 @@ export interface QuotaSwitchHostDeps extends Pick<QuotaSwitchDeps, "store" | "co
): ReturnType<QuotaSwitchDeps["gate"]>;
threadBusy(botId: string, threadId: string): boolean;
directRequestOwners: { get(threadId: string): QuotaRequest | undefined };
+ /** Other cards the harness raises and settles itself: true when it was one. */
+ ownCards?(requestId: string, behavior: "allow" | "deny" | "answer"): boolean;
startOrQueueDirectMessage(
botId: string, threadId: string, text: string, replyTo?: Message, sendId?: string, sender?: ResolvedSender,
trigger?: UsageTrigger, via?: "call", callId?: string, dataContext?: DataContext,
@@ -46,7 +48,7 @@ export function createQuotaSwitchHost(deps: QuotaSwitchHostDeps) {
/** Settles a card the harness raised itself (a peer approval, a use-your-computer ask or a quota-switch offer); undefined for any other card. */
async function harnessCardOutcome(threadId: string, requestId: string, behavior: "allow" | "deny" | "answer", message: unknown): Promise<string | undefined> {
if (!store.messagesFor(threadId).some(candidate => candidate.card?.requestId === requestId)) return undefined;
- if (resolvePeerComms(approvalBus, requestId, behavior) || resolveYourComputerAsk(requestId, behavior)) return behavior === "allow" ? "allowed-once" : "rejected";
+ if (resolvePeerComms(approvalBus, requestId, behavior) || resolveYourComputerAsk(requestId, behavior) || deps.ownCards?.(requestId, behavior)) return behavior === "allow" ? "allowed-once" : "rejected";
return await quotaSwitch.answer(threadId, requestId, behavior, message) ?? undefined;
}
diff --git a/server/index.ts b/server/index.ts
index f8ddc034f0..0c43e3ee3e 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -414,7 +414,7 @@ import { shellTimeoutHookResult } from "./shell-timeout-hint.ts";
import { spillToolResult } from "./tool-result-spill.ts";
import { gatedLocalComputer } from "./local-computer.ts";
import { desktopComputer, thisComputerNotReady } from "./desktop-computer.ts";
-import { askToUseYourComputer, cancelYourComputerAsks, dismissStaleYourComputerCards, yourComputerCallFrom, yourComputerWaiting } from "./your-computer-consent.ts";
+import { askToUseYourComputer, cancelYourComputerAsks, dismissStaleYourComputerCards, yourComputerCallFrom, yourComputerWaiting } from "./your-computer-consent.ts"; import { createComputerAsksHost } from "./host/computer-asks-host.ts";
import { discoverExistingPerBotLocalVms, localVmInventoryEntry } from "./local-vm-inventory.ts";
import { createLocalVmUpdater, LOCAL_VM_UPDATING_PROBLEM, recoverLocalVms, VPS_OUTDATED_HINT, vpsDesktopOutdated, withoutHostWhileUpdating } from "./desktop-updates.ts";
import { keepInstalledAppsBeforeRemove } from "./local-vm-profiles.ts";
@@ -2869,6 +2869,8 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudT
routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,
memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true });
const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) });
+const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,
+ refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalNotice(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;
const { stopThreadForPerson, stopOnTypedCommand, noteTeammatesLeftRunning } = createPersonStop({
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,
stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),
@@ -3033,7 +3035,7 @@ function previewSystemPrompt(bot: BotRecord) {
computer: previewPlan.computer && previewPlan.computer !== "off" && computerPromptKind ? previewPlan.computer : null,
browser: previewPlan.computer === undefined ? false : previewPlan.browser,
}, { note: previewPlan.note, cloudHome: Boolean(CLOUD_HOME) }) },
- { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(agentsMounted && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER)) + firstHourHooks.prompt(bot.id, bot.threadId) : "" },
+ { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(agentsMounted && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, bot.threadId) : "" },
{ id: "composio", label: "Connected apps", text: caps?.composioMcp && bot.composio !== false && composio.configured(cfg) ? composioSystemPrompt(bot.connectorTools) + describeConnectorScopes(bot.connectorScopes) : "" },
{ id: "highlevel", label: "HighLevel", text: caps?.highlevelMcp === true && highlevelHost.mounts(bot) ? highlevelHost.prompt(bot) : "" },
...phones.previewParts(bot, caps?.deviceMcp === true),
@@ -5014,7 +5016,7 @@ async function respondToCard(input: {
function closeOpenApprovals(threadId: string): void {
for (const key of pendingCommandRules.keys()) if (key.startsWith(`${threadId}:`)) pendingCommandRules.delete(key);
// Resolve peer approvals' in-memory promises first; patching their cards alone leaves the queue waiting.
- cancelPeerApprovalsForThread(threadId); cancelYourComputerAsks(threadId);
+ cancelPeerApprovalsForThread(threadId); cancelYourComputerAsks(threadId); computerAsks?.asks.cancel(threadId);
for (const message of store.messagesFor(threadId)) {
const card = message.card;
if (!card?.requestId || card.answered || card.dismissed) continue;
@@ -8510,7 +8512,7 @@ async function startTurn(
{ id: "computer", label: "Computer", text: computerPrompt(computerPromptKind) },
{ id: "team-computer", label: "Team computer", text: teamComputerPrompt(teamComputer) },
{ id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : ""), canSelect: computerSelectionTurns.has(threadId), cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened }) },
- { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER)) + firstHourHooks.prompt(bot.id, threadId) : "" },
+ { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, threadId) : "" },
{ id: "composio", label: "Connected apps", text: integrations.composio ? composioSystemPrompt(liveBot?.connectorTools ?? bot.connectorTools) + describeConnectorScopes((liveBot ?? bot).connectorScopes) : "" },
{ id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },
{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },
@@ -9739,11 +9741,11 @@ const approvalBus: ApprovalBus = { store, broadcast, notify, autoApply: fullAcce
onPeerApprovalPending: (from, target, action, sourceThreadId, message) => void reportEscalation({
kind: "peer-approval", bot: from, threadId: sourceThreadId, gate: peerApprovalGate(action, target.name), reason: message, alreadyNotified: true }) };
-const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, approvalBus, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover });
+const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, approvalBus, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover, ownCards: (requestId, behavior) => computerAsks?.asks.answer(requestId, behavior) ?? false });
// Peer approvals live only in memory: settle every peer card still open on disk, or it locks the composer forever.
{
- const stale = dismissStalePeerCards(approvalBus) + dismissStaleYourComputerCards(store);
+ const stale = dismissStalePeerCards(approvalBus) + dismissStaleYourComputerCards(store) + (computerAsks?.asks.dismissStale() ?? 0);
if (stale) console.log(`approvals: dismissed ${stale} card(s) left by a previous run`);
}
@@ -10329,7 +10331,7 @@ async function runClaimedGroupMemberTurn(
{ id: "computer", label: "Computer", text: computerPrompt(roomComputerPromptKind) },
{ id: "team-computer", label: "Team computer", text: teamComputerPrompt(roomTeamComputer) },
{ id: "plan", label: "Surface", text: surfacePrompt({ computer: roomTeamComputer ? "cloud" : roomVmTarget ? "vm" : surfaceOfComputerKind(roomComputerKind), browser: Boolean(integrations.browser) }, { note: roomPlan.note, cloudHome: Boolean(CLOUD_HOME) }) },
- { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER)) : "" },
+ { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) : "" },
{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },
{ id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },
{ id: "highlevel", label: "HighLevel", text: integrations.highlevel ? highlevelHost.prompt(readyBot) : "" },
@@ -12258,7 +12260,7 @@ ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: (
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,
- cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey, power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades }));
+ 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({
store, registry, handoffs, liveTurn: (threadId) => liveTurns.running(threadId), phoneSecretSubmissions, directTurnDispatchClaims, groupSpeakers,
@@ -13175,7 +13177,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });
}
};
- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await internalToolRoutes({ method, path, res, json, botId: internalSender.id, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
+ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await internalToolRoutes({ method, path, res, json, botId: internalSender.id, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS)) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
const delegatedThisTurn = (taskId: string) => {
(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);
};
diff --git a/server/lent-computers.ts b/server/lent-computers.ts
index f56f6eb696..602b37187a 100644
--- a/server/lent-computers.ts
+++ b/server/lent-computers.ts
@@ -113,14 +113,15 @@ const dateText = (at: number) => new Date(at).toISOString().slice(0, 16).replace
* What list_shared_computers adds for a bot when a computer it knows is not online: the computer by name and kind, since
* when, and the one sentence to say. Nothing when every known computer is online.
*/
-export function awayNotice(known: LentComputer[], online: ReadonlySet<string>): { offline?: Array<{ name: string; device: string; lastOnline: string; lent: boolean }>; say?: string } {
+export function awayNotice(known: LentComputer[], online: ReadonlySet<string>, askTool: string | null = null): { offline?: Array<{ name: string; device: string; lastOnline: string; lent: boolean }>; say?: string } {
const away = known.filter((computer) => !online.has(computer.id));
if (!away.length || known.some((computer) => online.has(computer.id))) return {};
const offline = away.slice(0, 3).map((computer) => ({ name: computer.name, device: deviceWord(computer.platform), lastOnline: dateText(computer.lastSeenAt), lent: computer.stoppedAt === null }));
const latest = away[0]!;
const device = deviceWord(latest.platform);
+ const ask = askTool ? ` If the request needs it, call ${askTool}: it asks them with a one-tap Turn on, and you carry on once it's on. Don't explain the fix in chat.` : null;
const say = latest.stoppedAt === null
- ? `Their ${device} ${latest.name} is shared with the Cloud but offline (last online ${dateText(latest.lastSeenAt)}): OpenMausBot on it is closed, or the ${device} is asleep or off. Ask them to open OpenMausBot on that ${device}; it reconnects by itself.`
- : `Their ${device} ${latest.name} no longer shares itself with the Cloud: OpenMausBot on it is paused, or signed out of MausBot Cloud. Ask them to choose Resume from OpenMausBot's icon in the ${device === "Mac" ? "menu bar" : "taskbar"} on that ${device}, or sign in there again.`;
+ ? `Their ${device} ${latest.name} is shared with the Cloud but offline (last online ${dateText(latest.lastSeenAt)}): OpenMausBot on it is closed, or the ${device} is asleep or off.${ask ?? ` Ask them to open OpenMausBot on that ${device}; it reconnects by itself.`}`
+ : `Their ${device} ${latest.name} no longer shares itself with the Cloud: OpenMausBot on it is paused, or signed out of MausBot Cloud.${ask ?? ` Ask them to choose Resume from OpenMausBot's icon in the ${device === "Mac" ? "menu bar" : "taskbar"} on that ${device}, or sign in there again.`}`;
return { offline, say };
}
diff --git a/server/routes/shared-computers.ts b/server/routes/shared-computers.ts
index 36fcb2273b..5e307e4486 100644
--- a/server/routes/shared-computers.ts
+++ b/server/routes/shared-computers.ts
@@ -5,6 +5,7 @@ import { answerAsleep, type CloudPower } from "../cloud-power.ts";
import type { DeviceLinks } from "../device-links.ts";
import { requestSource, type RequestAuth } from "../request-auth.ts";
import type { SessionRecord } from "../sessions.ts";
+import { desktopPresence, type Answerer, type ComputerAsks } from "../computer-asks.ts";
import { responseGone, sharedComputerRegistration, type SharedComputers } from "../shared-computers.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
import type { Upgrades } from "./upgrades.ts";
@@ -25,6 +26,9 @@ export function createSharedComputerRoutes(deps: {
/** A Cloud home's device links (a lent computer's internet connection); null elsewhere, where the path 404s. */
links: DeviceLinks | null;
upgrades: Upgrades;
+ /** On the person's own Cloud: what its bots ask of their computer, and the app there saying how it is. */
+ asks?: Pick<ComputerAsks, "present"> | null;
+ answerer?: (auth: RequestAuth) => Answerer;
}): RouteHandler {
deps.upgrades.route((path) => LINK.test(path));
return async ({ req, res, path, method, auth, json, readBody }: RouteContext): Promise<typeof PASS | void> => {
@@ -61,6 +65,19 @@ export function createSharedComputerRoutes(deps: {
deps.computers.register(registration, { session: auth.session.id, person: deps.cloudHomeLender ?? deps.personKey(auth.session) }, secret);
return json(res, 200, { ok: true });
}
+ if (path === "/api/shared-computers/asks") {
+ if (!deps.asks || !deps.cloudHomeLender) return json(res, 404, { error: "not found" });
+ if (!auth.scopes.includes("admin")) return json(res, 403, { error: "Only your own computers can answer the Cloud's bots." });
+ const parsed = desktopPresence.safeParse(body);
+ if (!parsed.success) return json(res, 400, { error: "Invalid computer state" });
+ const power = deps.power();
+ if (power?.sleeping()) return answerAsleep(res, json);
+ const { heard, answers, ...state } = parsed.data;
+ const news = await deps.asks.present(state, answers, deps.answerer?.(auth) ?? { kind: "worker" }, heard,
+ power ? AbortSignal.any([responseGone(res), power.sleepSignal()]) : responseGone(res));
+ if (power?.sleeping()) return answerAsleep(res, json);
+ return json(res, 200, news);
+ }
const route = /^\/api\/shared-computers\/([\w-]+)\/(poll|lease|result|disconnect)$/.exec(path);
if (!route) return json(res, 404, { error: "not found" });
const [, id, action] = route;
diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.ts
index c8261f1f86..a3dd879e72 100644
--- a/server/shared-computers.test.ts
+++ b/server/shared-computers.test.ts
@@ -360,6 +360,25 @@ describe("server-side scope check (audit M1)", () => {
expect(lending.screenNotLent(alice.person)).toEqual({});
broker.close(); lending.close();
});
+ it("on the person's own Cloud, every computer that can't give what's needed sends the bot to ask with a card, never to explain the fix", async () => {
+ const ask = 'call ask_for_computer with need "screen"';
+ expect(sharedComputerScopeRefusal({ ...lent, platform: "win32" }, { action: "computer_call" }, "ask_for_computer"))
+ .toBe("Apps and screen are not lent to this Cloud right now. Call ask_for_computer with need \"screen\" and what you want to do: it asks them with a one-tap Turn on, and you carry on once it's on. Don't explain the fix in chat, and don't use your own cloud computer instead unless they ask.");
+ expect(sharedComputerScopeRefusal({ ...lent, name: "HOME-PC" }, { action: "run_command" }, "ask_for_computer")).toContain('Call ask_for_computer with need "terminal"');
+ const broker = new SharedComputers(() => true);
+ broker.askTool = "ask_for_computer";
+ const changes: number[] = [];
+ broker.changed = () => changes.push(Date.now());
+ const pc = { ...registration(), platform: "win32" as const };
+ broker.register(pc, alice, secret);
+ expect(broker.screenNotLent(alice.person).screen).toBe(`Desktop doesn't lend its apps and screen right now. To use them, ${ask} and what you want to do: it asks them with a one-tap Turn on, and you carry on once it's on. Don't explain the fix in chat, and don't use your own cloud computer instead unless they ask.`);
+ expect(broker.lendingNow(alice.person)).toEqual([{ id: pc.id, name: "Desktop", platform: "win32", computer: false, terminal: false }]);
+ expect(broker.lendingNow(bob.person)).toEqual([]);
+ broker.disconnect(pc.id, alice.session, secret);
+ expect(changes, "connecting and stopping both tell the asks").toHaveLength(2);
+ await expect(broker.request({ computer_id: pc.id, action: "computer_call", tool_name: "list_apps" }, alice.person, () => false)).rejects.toThrow(/Call ask_for_computer with need "screen"/);
+ broker.close();
+ });
it("never queues an out-of-scope operation for the desktop", async () => {
const broker = new SharedComputers(() => true);
broker.register(lent, alice, secret);
diff --git a/server/shared-computers.ts b/server/shared-computers.ts
index 512a2ac011..e56a200e53 100644
--- a/server/shared-computers.ts
+++ b/server/shared-computers.ts
@@ -1,7 +1,7 @@
import { randomUUID, timingSafeEqual } from "node:crypto";
import { z } from "zod";
import type { DeviceLinks, LinkedComputer } from "./device-links.ts";
-import { awayNotice, deviceWord, lendScreenSteps, LENT_PLATFORMS, type LentComputers } from "./lent-computers.ts";
+import { awayNotice, deviceWord, lendScreenSteps, LENT_PLATFORMS, type LentComputers, type LentPlatform } from "./lent-computers.ts";
import type { LentCopies } from "./lent-copies.ts";
export { LentComputers } from "./lent-computers.ts";
@@ -73,12 +73,14 @@ export function responseGone(res: { once(event: "close", listener: () => void):
}
/** The desktop's grant is the authority and checks every operation again; the server just never queues work outside what it lends. */
-export function sharedComputerScopeRefusal(registration: Registration, operation: Pick<Operation, "action" | "folder_id">): string | null {
+export function sharedComputerScopeRefusal(registration: Registration, operation: Pick<Operation, "action" | "folder_id">, askTool: string | null = null): string | null {
switch (operation.action) {
case "run_command":
+ if (!registration.terminal && askTool) return `${registration.name} doesn't let this Cloud run commands right now. Call ${askTool} with need "terminal" and why: it asks them with a one-tap Turn on, and you carry on once it's on. Never run the command another way or anywhere else.`;
return registration.terminal ? null : `${registration.name} does not lend its terminal, so commands cannot run there. Do not try to run the command another way or anywhere else; use its folders, or tell the person in one sentence what to run themselves, or, when it is their own Cloud, that they can turn on "Let Clouds run commands on this ${deviceWord(registration.platform)}" from the OpenMausBot icon in its menu bar or taskbar.`;
case "computer_tools":
case "computer_call":
+ if (!registration.computer && askTool) return `Apps and screen are not lent to this Cloud right now. ${askHint(askTool, "screen")}`;
return registration.computer ? null : `Apps and screen are not lent to this server. ${lendScreenSteps(deviceWord(registration.platform))}`;
case "list_files":
case "read_file":
@@ -96,6 +98,10 @@ export function sharedComputerScopeRefusal(registration: Registration, operation
}
}
+/** What a bot does on the person's own Cloud when their computer can't give what it needs: ask, never explain the fix. */
+const askHint = (askTool: string, need: "screen" | "folders" | "terminal") =>
+ `Call ${askTool} with need "${need}" and what you want to do: it asks them with a one-tap Turn on, and you carry on once it's on. Don't explain the fix in chat, and don't use your own cloud computer instead unless they ask.`;
+
/** The person behind a request proven for this exact turn generation, not stopped, from a person's message; anything else is nobody. */
export function provenRequestPerson(
request: { messageId?: string; generations: ReadonlySet<string>; stopped?: boolean } | undefined,
@@ -116,6 +122,10 @@ export class SharedComputers {
private links: Pick<DeviceLinks, "drop"> | undefined;
/** A Cloud home's copies of lent folders: what a computer that is away still lends (server/lent-copies.ts). */
private copies: Pick<LentCopies, "away" | "answer"> | undefined;
+ /** A computer connected, changed what it lends, or stopped. */
+ changed: () => void = () => {};
+ /** On the person's own Cloud, the bots' tool that asks them to turn on what their computer doesn't give now. */
+ askTool: string | null = null;
constructor(sessionLive: (id: string) => boolean, lent?: LentComputers, links?: Pick<DeviceLinks, "drop">, copies?: Pick<LentCopies, "away" | "answer">) {
this.sessionLive = sessionLive; this.lent = lent; this.links = links; this.copies = copies;
}
@@ -131,6 +141,7 @@ export class SharedComputers {
if ((old.registration.internet === true) !== (registration.internet === true) || (old.registration.chrome === true) !== (registration.chrome === true)) this.links?.drop(key);
old.registration = registration; old.seen = Date.now();
this.remember(registration, old.owner.person);
+ this.changed();
return;
}
this.reap();
@@ -143,6 +154,7 @@ export class SharedComputers {
if (this.computers.size >= TOTAL) throw failure("Too many shared computers");
this.computers.set(key, { registration, owner: { ...owner }, secret, seen: Date.now(), jobs: new Map(), polls: 0 });
this.remember(registration, owner.person);
+ this.changed();
}
private remember(registration: Registration, person: string) {
this.lent?.connected(person, { id: registration.id, name: registration.name, platform: registration.platform,
@@ -165,6 +177,12 @@ export class SharedComputers {
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) } : {}) }));
}
+ /** What each of this person's online computers lends: its apps and screen, its terminal. */
+ lendingNow(principal: string | null): { id: string; name: string; platform?: LentPlatform; computer: boolean; terminal: boolean }[] {
+ if (!principal) return [];
+ return [...this.computers.values()].filter(entry => entry.owner.person === principal && this.online(entry))
+ .map(({ registration: { id, name, platform, computer, terminal } }) => ({ id, name, ...(platform ? { platform } : {}), computer, terminal }));
+ }
/** Every computer this person lent, now or before, newest first: online, offline since, or no longer lent. */
known(principal: string | null): KnownLentComputer[] {
if (!principal) return [];
@@ -180,13 +198,14 @@ export class SharedComputers {
away(principal: string | null) {
if (!principal) return {};
const online = this.list(principal);
- return { ...awayNotice(this.lent?.list(principal) ?? [], new Set(online.map(registration => registration.id))), ...this.copies?.away(principal, online) };
+ return { ...awayNotice(this.lent?.list(principal) ?? [], new Set(online.map(registration => registration.id)), this.askTool), ...this.copies?.away(principal, online) };
}
/** For a bot: how the person lends apps and screen, when an online computer of theirs lends neither. */
screenNotLent(principal: string | null): { screen?: string } {
if (!principal) return {};
const entry = [...this.computers.values()].find(candidate => candidate.owner.person === principal && this.online(candidate) && !candidate.registration.computer);
if (!entry) return {};
+ if (this.askTool) return { screen: `${entry.registration.name} doesn't lend its apps and screen right now. To use them, ${askHint(this.askTool, "screen").replace(/^Call/, "call")}` };
return { screen: `${entry.registration.name} does not lend its apps and screen. ${lendScreenSteps(deviceWord(entry.registration.platform))}` };
}
/** A computer that lends its internet connection but is away: the bots' browsers here use My Cloud's own connection
@@ -280,6 +299,7 @@ export class SharedComputers {
if (paused) this.lent?.seen(entry.owner.person, id); else this.lent?.stopped(entry.owner.person, id);
this.computers.delete(SharedComputers.key(session, id)); entry.wake?.(); this.links?.drop(SharedComputers.key(session, id));
for (const job of entry.jobs.values()) this.finish(entry, job, failure("Computer disconnected. An in-flight action may have completed; inspect before retrying."));
+ this.changed();
}
/** Another person's computer answers exactly like one that does not exist. */
async request(operation: Operation, principal: string | null, active: () => boolean): Promise<unknown> {
@@ -292,14 +312,15 @@ export class SharedComputers {
// Away: its lent folders answer from their copy here, a write to one lent with editing waits for it.
const copy = active() ? this.copies?.answer(operation, principal, this.list(principal)) : null;
if (copy) return copy;
- throw failure(known && this.sessionLive(known.owner.session)
+ const why = known && this.sessionLive(known.owner.session)
? lentButOffline(known.registration.name, known.seen, deviceWord(known.registration.platform))
- : this.offline(principal, operation.computer_id));
+ : this.offline(principal, operation.computer_id);
+ throw failure(this.askTool ? `${why} ${askHint(this.askTool, operation.action === "run_command" ? "terminal" : operation.action.startsWith("computer_") ? "screen" : "folders")}` : why);
}
await new Promise(resolve => setTimeout(resolve, 250));
}
const entry = lent()!;
- const refusal = sharedComputerScopeRefusal(entry.registration, operation);
+ const refusal = sharedComputerScopeRefusal(entry.registration, operation, this.askTool);
if (refusal) throw failure(refusal, 403);
if (entry.jobs.size >= 1) throw failure("This shared computer is busy. Wait for its current action to finish.");
if (!active()) throw failure("The requesting turn ended", 401);
diff --git a/server/system-prompt.ts b/server/system-prompt.ts
index eb79f9e838..381080c299 100644
--- a/server/system-prompt.ts
+++ b/server/system-prompt.ts
@@ -147,14 +147,19 @@ function theirComputer(lent: ReadonlyArray<{ name: string; platform: "darwin" |
return { theirs: `their ${device} (${name})`, device };
}
+/** `asks`: the person's own Cloud, whose bots ask them to turn on what their computer doesn't give now (ask_for_computer). */
export function cloudHomePrompt(sharedComputerTools: boolean, synced: ReadonlyArray<{ computerName: string; pcPath: string; cloudPath: string }> = [],
- lent: ReadonlyArray<{ name: string; platform: "darwin" | "win32" | "linux" | null }> = []): string {
+ lent: ReadonlyArray<{ name: string; platform: "darwin" | "win32" | "linux" | null }> = [], asks = false): string {
const { theirs, device } = theirComputer(lent);
+ const unavailable = asks
+ ? ` If it isn't online, or doesn't lend what you need (its apps and screen, its files, running commands), call ask_for_computer with what you want to do and why: it shows them one card with a one-tap Turn on, and you carry on once it's on. Don't explain the fix yourself, and never do it on their cloud computer or in the built-in browser instead unless they ask you to.`
+ : ` If none is online, say so in one sentence: use its say field when it has one (it names the computer and when it was last online), otherwise ask them to open OpenMausBot on that ${device}, signed in to MausBot Cloud: it shares that ${device} with you by itself.`;
return ` You run on ${CLOUD_HOME_PLACE}.` + (sharedComputerTools
- ? ` If they ask for something on ${theirs}, check list_shared_computers: a computer they share with the Cloud is reachable through shared_computer, within the folders and apps it allows. If none is online, say so in one sentence: use its say field when it has one (it names the computer and when it was last online), otherwise ask them to open OpenMausBot on that ${device}, signed in to MausBot Cloud: it shares that ${device} with you by itself.${device === "computer" ? " Call it their computer: never assume it is a Mac." : ` It is a ${device}: call it that, never a Mac unless it is one.`}`
+ ? ` If they ask for something on ${theirs}, check list_shared_computers: a computer they share with the Cloud is reachable through shared_computer, within the folders and apps it allows.${unavailable}${device === "computer" ? " Call it their computer: never assume it is a Mac." : ` It is a ${device}: call it that, never a Mac unless it is one.`}`
+ ` While that ${device} is away, each folder it lends that the Cloud keeps a copy of still works from that copy: list_shared_computers lists them under away_computers (copy null means a folder only on the ${device}), every read says how fresh the copy is, and a write to a folder lent with editing is saved here and reaches the ${device} when it's on (tell them so in a few words). A file or folder that isn't in the copy is only on the ${device}: say you'll get it when it's on.`
: ` You cannot see or use ${theirs}, its screen or its files from here. If they ask for something on it, say so in one sentence.`)
- + " Offer what works here: the built-in browser and their cloud computer, a desktop in the cloud. Call it their cloud computer, as the app does. Never ask them to set up this computer or a Local VM; neither exists here."
+ + (asks ? " For work that doesn't need their own computer, use what works here:" : " Offer what works here:")
+ + " the built-in browser and their cloud computer, a desktop in the cloud. Call it their cloud computer, as the app does. Never ask them to set up this computer or a Local VM; neither exists here."
+ syncedFoldersPrompt(synced);
}
diff --git a/shared/computer-ask.test.ts b/shared/computer-ask.test.ts
new file mode 100644
index 0000000000..27098badfa
--- /dev/null
+++ b/shared/computer-ask.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+
+import en from "../src/locales/en.json";
+import {
+ cleanAskWhy, COMPUTER_ASK_REASONS, COMPUTER_ASK_WORDS, computerAskReasonLine, computerAskText, needsTheApp, turnsOnFromHere,
+} from "./computer-ask.ts";
+
+const line = (reason: (typeof COMPUTER_ASK_REASONS)[number], device: "PC" | "Mac" | "computer") => {
+ const { key, params } = computerAskReasonLine({ reason, device }, "Scout");
+ return computerAskText(key, params);
+};
+
+describe("a bot's ask to turn on what it needs from the person's computer", () => {
+ it("says plainly why it isn't available, in the person's words for their computer", () => {
+ expect(line("paused", "PC")).toBe("Using your PC is paused.");
+ expect(line("not-running", "PC")).toBe("Screen control isn't running on your PC.");
+ expect(line("blocked", "PC")).toBe("Screen control is blocked on your PC: Windows Security may have stopped it.");
+ expect(line("blocked", "Mac")).toBe("Screen control is blocked on your Mac.");
+ expect(line("permissions", "Mac")).toBe("macOS hasn't allowed MausBot to see and use the screen yet.");
+ expect(line("closed", "PC")).toBe("MausBot isn't open on your PC. Open it there and Scout carries on.");
+ expect(line("never", "computer")).toBe("MausBot isn't on your computer yet. Install it, sign in to MausBot Cloud there, and Scout carries on.");
+ expect(line("update", "PC")).toBe("MausBot on your PC needs an update first. Update it, and Scout carries on.");
+ });
+
+ it("offers Turn on only where the app on that computer can do it, and the app itself where it's the fix", () => {
+ expect(COMPUTER_ASK_REASONS.filter(turnsOnFromHere)).toEqual(["paused", "permissions", "blocked", "off", "not-running", "terminal-off"]);
+ expect(COMPUTER_ASK_REASONS.filter(needsTheApp)).toEqual(["closed", "never", "update"]);
+ expect(COMPUTER_ASK_REASONS.filter((reason) => !turnsOnFromHere(reason) && !needsTheApp(reason))).toEqual(["starting", "unsupported"]);
+ });
+
+ it("keeps a bot's reason to one clean line on the card", () => {
+ expect(cleanAskWhy(" Fill in\nthe invoice‮ in Excel ")).toBe("Fill in the invoice in Excel");
+ expect(cleanAskWhy("x".repeat(300))).toHaveLength(200);
+ expect(cleanAskWhy(" ")).toBeUndefined();
+ expect(cleanAskWhy(42)).toBeUndefined();
+ });
+
+ it("matches the words the app shows, key for key", () => {
+ for (const [key, text] of Object.entries(COMPUTER_ASK_WORDS)) expect((en as Record<string, string>)[key], key).toBe(text);
+ });
+});
diff --git a/shared/computer-ask.ts b/shared/computer-ask.ts
new file mode 100644
index 0000000000..6cdf51dc8e
--- /dev/null
+++ b/shared/computer-ask.ts
@@ -0,0 +1,129 @@
+// A bot on the person's own Cloud that needs their computer (its apps and screen, its files, or its terminal) when it
+// isn't available asks once with a card: what it wants and why, why it isn't available, and the one-tap fix. The English
+// mirrors src/locales/en.json `computerAsk.*` exactly (a test holds them together): the server has no i18n.
+
+/** The card's tool name: no engine has a tool by this name, and "Always allow" is never offered for it. */
+export const COMPUTER_ASK_TOOL = "turn_on_your_computer";
+/** The bots' tool that raises the card. */
+export const ASK_FOR_COMPUTER_TOOL = "ask_for_computer";
+export const DESKTOP_DOWNLOAD_URL = "https://www.openmausbot.com/download";
+
+export const COMPUTER_NEEDS = ["screen", "folders", "terminal"] as const;
+export type ComputerNeed = (typeof COMPUTER_NEEDS)[number];
+
+/**
+ * Why the computer can't give what's needed now. From the app on that computer: "paused" (the person paused it from its
+ * icon), and for apps and screen "starting", "permissions" (macOS hasn't allowed it), "blocked" (its helper is missing
+ * or stopped, as Windows Security does), "off" (Linux control is off), "not-running" and "unsupported"; "terminal-off"
+ * (running commands isn't turned on). Without the app there: "closed" (it was used before), "never", and "update" (an
+ * app too old to answer the card).
+ */
+export const COMPUTER_ASK_REASONS = [
+ "paused", "starting", "permissions", "blocked", "off", "not-running", "unsupported", "terminal-off", "closed", "never", "update",
+] as const;
+export type ComputerAskReason = (typeof COMPUTER_ASK_REASONS)[number];
+
+/** "asking" until an answer; "turning-on" once Turn on was tapped; "on" once it lends what was needed; "failed" when the
+ * app there couldn't turn it on (Turn on again tries again); "declined" for Not now; "ended" when the conversation
+ * was stopped or deleted. */
+export type ComputerAskState = "asking" | "turning-on" | "on" | "failed" | "declined" | "ended";
+
+export type ComputerDevice = "PC" | "Mac" | "computer";
+
+export interface ComputerAskCard {
+ need: ComputerNeed;
+ reason: ComputerAskReason;
+ device: ComputerDevice;
+ state: ComputerAskState;
+ /** What the bot wants to do and why, in its own words, cleaned. */
+ why?: string;
+}
+
+export interface ComputerAskField {
+ /** A bot on the person's own Cloud asks to turn on what it needs from their computer. */
+ computerAsk?: ComputerAskCard;
+}
+
+/** A tap on Turn on can fix this from wherever the card is: the app on that computer does it. */
+export function turnsOnFromHere(reason: ComputerAskReason): boolean {
+ return reason === "paused" || reason === "permissions" || reason === "blocked" || reason === "off" || reason === "not-running" || reason === "terminal-off";
+}
+
+/** The fix is getting the app there: install it, open it, or update it. */
+export function needsTheApp(reason: ComputerAskReason): boolean {
+ return reason === "closed" || reason === "never" || reason === "update";
+}
+
+export const COMPUTER_ASK_WORDS = {
+ "computerAsk.want.screen": "{name} wants to use your {device}'s apps and screen",
+ "computerAsk.want.folders": "{name} wants to use the files on your {device}",
+ "computerAsk.want.terminal": "{name} wants to run commands on your {device}",
+ "computerAsk.reason.paused": "Using your {device} is paused.",
+ "computerAsk.reason.starting": "Screen control is still starting on your {device}.",
+ "computerAsk.reason.permissions": "macOS hasn't allowed {app} to see and use the screen yet.",
+ "computerAsk.reason.blocked": "Screen control is blocked on your {device}.",
+ "computerAsk.reason.blockedPc": "Screen control is blocked on your PC: Windows Security may have stopped it.",
+ "computerAsk.reason.off": "Screen control is off on your {device}.",
+ "computerAsk.reason.notRunning": "Screen control isn't running on your {device}.",
+ "computerAsk.reason.unsupported": "Screen control can't work on your {device} right now.",
+ "computerAsk.reason.terminalOff": "Running commands isn't turned on for your {device}.",
+ "computerAsk.reason.closed": "{app} isn't open on your {device}. Open it there and {name} carries on.",
+ "computerAsk.reason.never": "{app} isn't on your computer yet. Install it, sign in to MausBot Cloud there, and {name} carries on.",
+ "computerAsk.reason.update": "{app} on your {device} needs an update first. Update it, and {name} carries on.",
+ "computerAsk.action.turnOn": "Turn on",
+ "computerAsk.action.tryAgain": "Try again",
+ "computerAsk.action.notNow": "Not now",
+ "computerAsk.action.getApp": "Get {app}",
+ "computerAsk.state.turningOn": "Turning on…",
+ "computerAsk.state.on": "Turned on. {name} is carrying on.",
+ "computerAsk.state.failed": "It didn't turn on.",
+ "computerAsk.state.declined": "Not now",
+ "computerAsk.state.ended": "No longer needed",
+} as const;
+
+export type ComputerAskKey = keyof typeof COMPUTER_ASK_WORDS;
+
+/** The product's name as the person reads it, as the app fills `{app}`. */
+export const COMPUTER_ASK_APP = "MausBot";
+
+export function computerAskText(key: ComputerAskKey, params: Record<string, string>): string {
+ return COMPUTER_ASK_WORDS[key].replace(/\{(\w+)\}/g, (whole, name: string) => (name === "app" ? params.app ?? COMPUTER_ASK_APP : params[name] ?? whole));
+}
+
+const WANT_KEY: Record<ComputerNeed, ComputerAskKey> = {
+ screen: "computerAsk.want.screen",
+ folders: "computerAsk.want.folders",
+ terminal: "computerAsk.want.terminal",
+};
+
+/** The card's headline: who wants what, from which computer. */
+export function computerAskHeadline(card: Pick<ComputerAskCard, "need" | "device">): { key: ComputerAskKey; params: Record<string, string> } {
+ return { key: WANT_KEY[card.need], params: { device: card.device } };
+}
+
+/** Why it isn't available, as a catalog key and its values. */
+export function computerAskReasonLine(card: Pick<ComputerAskCard, "reason" | "device">, name: string): { key: ComputerAskKey; params: Record<string, string> } {
+ const params = { device: card.device, name };
+ switch (card.reason) {
+ case "paused": return { key: "computerAsk.reason.paused", params };
+ case "starting": return { key: "computerAsk.reason.starting", params };
+ case "permissions": return { key: "computerAsk.reason.permissions", params };
+ case "blocked": return { key: card.device === "PC" ? "computerAsk.reason.blockedPc" : "computerAsk.reason.blocked", params };
+ case "off": return { key: "computerAsk.reason.off", params };
+ case "unsupported": return { key: "computerAsk.reason.unsupported", params };
+ case "terminal-off": return { key: "computerAsk.reason.terminalOff", params };
+ case "closed": return { key: "computerAsk.reason.closed", params };
+ case "never": return { key: "computerAsk.reason.never", params };
+ case "update": return { key: "computerAsk.reason.update", params };
+ default: return { key: "computerAsk.reason.notRunning", params };
+ }
+}
+
+/** What a bot wrote as its reason, made safe for one line on the card: no control or direction characters, at most 200. */
+export function cleanAskWhy(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ // eslint-disable-next-line no-control-regex
+ const line = value.replace(/[\u0000-\u001f\u007f‪-‮⁦-⁩]+/g, " ").replace(/\s+/g, " ").trim();
+ if (!line) return undefined;
+ return line.length > 200 ? `${line.slice(0, 199).trimEnd()}…` : line;
+}
diff --git a/shared/wire.ts b/shared/wire.ts
index fa6d754891..26a148f713 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -13,7 +13,7 @@ import type { CredentialTargetId, CUSTOM_SECRET_TARGET, SecretDelivery } from ".
import type { TeamSetupRequest } from "./team-setup.ts"; import type { DefaultBotFields, HelperIntroField } from "./default-bot.ts";
import type { SetupCardFields } from "./setup-card.ts";
import type { RoutineRequestCardData } from "./routine-request.ts"; import type { SavedStepsMark } from "./saved-steps.ts";
-import type { WebhookRequestCardData } from "./webhook-request.ts"; import type { WaitCardField, WaitLineField } from "./wait-request.ts";
+import type { WebhookRequestCardData } from "./webhook-request.ts"; import type { WaitCardField, WaitLineField } from "./wait-request.ts"; import type { ComputerAskField } from "./computer-ask.ts";
import type { AppEventAttempt, AppTrigger, AppTriggerRequestCardData, AppTriggerService } from "./app-triggers.ts";
import type { ProfileRequestCardData } from "./profile-request.ts";
import type { PlaceRow } from "./place-view.ts";
@@ -645,7 +645,7 @@ export function nextOpenThread<T extends OpenThreadCandidate>(tasks: readonly T[
return [listed, open, own].map((candidates) => orderedThreadList(candidates)[0]).find((task) => task !== undefined);
}
-export interface OptionCardData extends WaitCardField {
+export interface OptionCardData extends WaitCardField, ComputerAskField {
/** calls: one per outbound call the card covers, in subtitle order. */
outboundRequest?: { tool: string; app: string | null; calls?: Array<{ app: string | null; label: string }> };
/** `revision`: the entry as it applied without a person, so Undo can tell it changed since. */
diff --git a/src/components/ApprovalCard.tsx b/src/components/ApprovalCard.tsx
index ff3e727e66..5759da01ba 100644
--- a/src/components/ApprovalCard.tsx
+++ b/src/components/ApprovalCard.tsx
@@ -15,6 +15,7 @@ import type { SkillShareRecord } from "../../shared/skill-request";
import { cardAutomation } from "@/lib/automations";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { yourComputerAsk } from "@/lib/your-computer";
+import { computerAskWords } from "@/lib/computer-ask";
import { TriggerCard } from "./TriggerCard";
import { CardHint } from "./CardHint";
@@ -456,6 +457,17 @@ export function ApprovalCard({
})
: undefined;
+ const turnOn = computerAskWords(card, bot?.name ?? t("approval.someone"));
+ if (turnOn) {
+ const state = card.computerAsk?.state;
+ const waiting = state === "asking" || state === "failed";
+ return (
+ <div data-computer-ask={state} className="w-full">
+ <CompactApprovalRow header={turnOn.line} summary={waiting ? turnOn.reason : undefined} detail="" showDetailInline={false} outcome={turnOn.outcome}
+ allowed={state === "on" || state === "turning-on"} byVoice={byVoice} waiting={waiting} answeredBelow={waiting && !card.dismissed} />
+ </div>
+ );
+ }
if (!isRoutineRequest && !isSkillRequest && !isProfileRequest && !isTeamSetup && !card.modelRequest) {
const waiting = !settled && !expired;
const ask = yourComputerAsk(card, bot?.name ?? t("approval.someone"));
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index 3b03b46f6d..227cc073fb 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -149,6 +149,8 @@ export function Composer({
// Visible branch only: an approval left on an abandoned branch must not block the composer.
const approvals = pendingApprovals(group ? group.messages : bot ? visibleMessages(bot) : []);
const approval = approvals[0];
+ // A Turn on card can wait while the person walks to their computer: they can still write meanwhile.
+ const blocking = Boolean(approval && !approval.message.card?.computerAsk);
const approvalBot = group
? members?.find((member) => member.id === approval?.message.from?.botId) ??
members?.find((member) => member.id === groupBusyBotId)
@@ -419,7 +421,7 @@ export function Composer({
busy,
locked,
pendingCount,
- Boolean(approval),
+ blocking,
);
const [steering, setSteering] = useState(false);
const interruptTurn = () => {
@@ -930,10 +932,10 @@ export function Composer({
}}
// Not disabled during an upload: a disabled element drops keyboard focus for good. send() refuses while one
// is pending.
- disabled={Boolean(approval) || locked}
+ disabled={blocking || locked}
aria-busy={bot?.awaitingThreadSnapshot || undefined}
placeholder={composerPlaceholder({
- simple: !advanced, locked: setupLocked, approval: Boolean(approval), attaching: attachmentPending, listening: recording,
+ simple: !advanced, locked: setupLocked, approval: blocking, attaching: attachmentPending, listening: recording,
replying: Boolean(replyTo), busy, canSteer, queued: pendingCount > 0, busyName, sendLabel, group, members: members ?? [],
jevOn: jevRoomRoutingOn(state.config), goal: channelMode === "goal", botName: bot?.name ?? "",
setupHint: group ? null : setupRequestPlaceholder(bot, threadId),
diff --git a/src/components/ComputerAskCard.test.ts b/src/components/ComputerAskCard.test.ts
new file mode 100644
index 0000000000..35851cac54
--- /dev/null
+++ b/src/components/ComputerAskCard.test.ts
@@ -0,0 +1,65 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+
+import { StoreProvider, type Bot, type Message } from "@/state/store";
+import type { ComputerAskCard } from "../../shared/computer-ask";
+import { ApprovalCard } from "./ApprovalCard";
+import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals, spokenApprovalPrompt } from "./PendingApproval";
+
+const bot = { id: "scout", name: "Scout" } as Bot;
+
+function ask(view: Partial<ComputerAskCard> = {}, answered?: string): Message {
+ return {
+ id: "ask-card", role: "bot", kind: "options", at: 1,
+ card: {
+ title: "Scout wants to use your PC's apps and screen", subtitle: "", options: ["Turn on", "Not now"], requestId: "ask-1", requestType: "permission",
+ tool: "turn_on_your_computer", ...(answered ? { answered } : {}),
+ computerAsk: { need: "screen", reason: "not-running", device: "PC", state: "asking", why: "Fill in the invoice in Excel", ...view },
+ },
+ } as Message;
+}
+
+const panel = (message: Message) => {
+ const [pending] = pendingApprovals([message]);
+ return renderToStaticMarkup(createElement(StoreProvider, null, createElement(PendingApprovalPanel, {
+ pending: pending!, count: 1, index: 0, botName: "Scout",
+ actions: createElement(PendingApprovalActions, { pending: pending!, threadId: "t1", bot, onCancelTurn: () => undefined, part: "primary" }),
+ })));
+};
+
+describe("a bot's ask to turn on what it needs from the person's computer", () => {
+ it("says who wants what and why, why it can't now, and offers Turn on and Not now", () => {
+ const markup = panel(ask());
+ expect(markup).toContain("Scout wants to use your PC&#x27;s apps and screen");
+ expect(markup).toContain("Fill in the invoice in Excel");
+ expect(markup).toContain("Screen control isn&#x27;t running on your PC.");
+ expect(markup).toContain(">Turn on</button>");
+ expect(markup).toContain(">Not now</button>");
+ expect(markup).not.toContain("Always allow");
+ expect(markup).not.toContain("Allow once");
+ });
+
+ it("when the app there is the fix, links to it instead of a Turn on that can't work", () => {
+ const markup = panel(ask({ reason: "closed" }));
+ expect(markup).toContain("MausBot isn&#x27;t open on your PC. Open it there and Scout carries on.");
+ expect(markup).toContain('href="https://www.openmausbot.com/download"');
+ expect(markup).toContain(">Get MausBot</a>");
+ expect(markup).not.toContain(">Turn on</button>");
+ });
+
+ it("after a start that failed, says so and offers Try again", () => {
+ const markup = panel(ask({ state: "failed", reason: "blocked" }));
+ expect(markup).toContain("It didn&#x27;t turn on. Screen control is blocked on your PC: Windows Security may have stopped it.");
+ expect(markup).toContain(">Try again</button>");
+ });
+
+ it("reads in the transcript as it goes: turning on, then on", () => {
+ const row = (message: Message) => renderToStaticMarkup(createElement(ApprovalCard, { bot, message, threadId: "t1" }));
+ expect(row(ask({ state: "turning-on" }, "allow"))).toContain("Turning on…");
+ expect(row(ask({ state: "on" }, "allow"))).toContain("Turned on. Scout is carrying on.");
+ expect(row(ask({ state: "on" }, "allow")), "once on, the old reason is gone").not.toContain("isn&#x27;t running");
+ expect(row(ask({ state: "declined" }, "deny"))).toContain("Not now");
+ expect(spokenApprovalPrompt(pendingApprovals([ask()])[0]!, "Scout")).toBe("Scout wants to use your PC's apps and screen. Screen control isn't running on your PC.");
+ });
+});
diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx
index dc813977fe..5e9bcaad4f 100644
--- a/src/components/ComputerPanel.tsx
+++ b/src/components/ComputerPanel.tsx
@@ -34,7 +34,7 @@ import { openProviderDesktop, useComputerTakeover } from "./computer-takeover";
import { SignInBanner } from "./SignInRequestCard";
import { LocalScreenPreview } from "./LocalScreenPreview";
import { LinuxLocalControl } from "./LinuxLocalControl";
-import { MacLocalControl } from "./MacLocalControl";
+import { MacLocalControl } from "./MacLocalControl"; import { WindowsLocalControl } from "./WindowsLocalControl";
import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";
import {
busyBoatView,
@@ -1677,7 +1677,7 @@ export function ComputerPanel({
{phase !== "team-boat" && (bot.computer !== undefined || computerStatusCurrent) && <>
<LocalScreenPreview />
<LinuxLocalControl />
- <MacLocalControl />
+ <MacLocalControl /><WindowsLocalControl />
</>}
{advanced ? <>
diff --git a/src/components/PendingApproval.tsx b/src/components/PendingApproval.tsx
index c39459de3c..daa89112d2 100644
--- a/src/components/PendingApproval.tsx
+++ b/src/components/PendingApproval.tsx
@@ -12,6 +12,8 @@ import { reviewedSkillSha256 } from "../../shared/skill-request";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { useInboxOrigin } from "./InboxLine";
import { yourComputerAsk } from "@/lib/your-computer";
+import { computerAskWords } from "@/lib/computer-ask";
+import { DESKTOP_DOWNLOAD_URL } from "../../shared/computer-ask";
interface ApprovalLabels {
[tool: string]: LocaleKey;
@@ -60,6 +62,8 @@ export function pendingApprovals(messages: Message[]): Pending[] {
}
export function spokenApprovalPrompt(pending: Pending, requester: string): string {
+ const turnOn = computerAskWords(pending.message.card, requester);
+ if (turnOn) return `${turnOn.line}. ${turnOn.reason}`;
const ask = yourComputerAsk(pending.message.card, requester);
if (ask) return `${requester}: ${ask.line}`;
if (pending.message.card?.teamSetupRequest) return `${requester}: ${pending.message.card.title} Review the details and choose ${pending.message.card.options[0]} or ${pending.message.card.options[1] ?? "Cancel"}.`;
@@ -115,9 +119,11 @@ function isDurable(pending: Pending): boolean {
/** What will happen, in plain words; the command shown whole when it is what will run, and everything the card holds
* behind Details. */
-function approvalWords(pending: Pending, botName?: string): { line: string; summary?: string; inline?: string; detail: string } {
+function approvalWords(pending: Pending, botName?: string): { line: string; summary?: string; inline?: string; note?: string; detail: string } {
const card = pending.message.card;
const outbound = card ? outboundSummary(card) : undefined;
+ const turnOn = computerAskWords(card, botName ?? t("approval.someone"));
+ if (turnOn) return { line: turnOn.line, summary: turnOn.why ?? turnOn.reason, ...(turnOn.why ? { note: turnOn.reason } : {}), detail: "" };
const ask = yourComputerAsk(card, botName ?? t("approval.someone"));
const detail = (pending.commandAllowlist?.command ?? ask?.detail ?? pending.detail).trim();
if (outbound) return { line: outbound.headline, ...(outbound.summary ? { summary: outbound.summary } : {}), detail };
@@ -156,7 +162,7 @@ export const PendingApprovalPanel = memo(function PendingApprovalPanel({
const heldNote = outbound?.opaque && pending.heldCode === "approval.held.outbound"
? t("approval.opaqueCode")
: tFromServer(pending.heldCode, pending.held);
- const { line, summary, inline, detail } = approvalWords(pending, botName ?? asker?.name);
+ const { line, summary, inline, note, detail } = approvalWords(pending, botName ?? asker?.name);
const detailsId = `approval-details-${pending.requestId}`;
const hidden = detail && detail !== inline ? detail : "";
const skill = pending.message.card?.skillRequest;
@@ -204,6 +210,7 @@ export const PendingApprovalPanel = memo(function PendingApprovalPanel({
</div>
{summary && <p dir="auto" className="mt-1.5 break-words text-[15px] font-medium leading-[22px] text-ink">{summary}</p>}
{inline && <AskDetail text={inline} mono label={t("approval.aria.reviewDetails")} />}
+ {note && <p dir="auto" data-computer-ask-reason className="mt-1 break-words text-[13px] leading-[18px] text-ink-secondary">{note}</p>}
{heldNote && (outbound ? (
<p className="mt-2 flex items-center gap-1.5 text-[13px] leading-[18px] text-warning">
<Send size={13} aria-hidden="true" className="shrink-0" />
@@ -274,6 +281,23 @@ export function PendingApprovalActions({
const marked = (action: string) => (tag ? { [`data-${tag}-action`]: action } : {});
const showPrimary = part !== "more";
const showMore = part !== "primary";
+ const turnOn = computerAskWords(pending.message.card, bot?.name ?? t("approval.someone"));
+ if (turnOn) {
+ if (!showPrimary) return null;
+ return (
+ <>
+ {turnOn.getApp && (
+ <a key="get" {...marked("get-app")} href={DESKTOP_DOWNLOAD_URL} target="_blank" rel="noreferrer" className={ASK_SECONDARY_BUTTON}>{turnOn.getApp}</a>
+ )}
+ <button key="deny" {...marked("deny")} type="button" onClick={() => decide("deny")} className={turnOn.turnOn ? ASK_SECONDARY_BUTTON : ASK_QUIET_ANSWER}>
+ {t("computerAsk.action.notNow")}
+ </button>
+ {turnOn.turnOn && (
+ <button key="allow" {...marked("allow")} type="button" onClick={() => decide("allow")} className={allow.className} style={allow.style}>{turnOn.turnOn}</button>
+ )}
+ </>
+ );
+ }
const always = durableRequest ? null
: bot && pending.allowKey
? { name: t("approval.action.alwaysAllow"), hint: t("approval.action.stopAsking", { name: bot.name, key: pending.allowKey }), run: () => decide("allow", true) }
diff --git a/src/components/WindowsLocalControl.tsx b/src/components/WindowsLocalControl.tsx
new file mode 100644
index 0000000000..c2c5cdcb6b
--- /dev/null
+++ b/src/components/WindowsLocalControl.tsx
@@ -0,0 +1,64 @@
+import { useState } from "react";
+import { AlertTriangle, Loader2, MonitorX } from "lucide-react";
+import { useDesktopCapabilities } from "./DesktopCapabilities";
+import { t } from "@/lib/i18n";
+
+/** On a PC whose screen control isn't running: that bots, and the person's Cloud's bots, can't use its apps and screen,
+ * why, and the one fix. */
+export function WindowsLocalControl() {
+ const { capabilities } = useDesktopCapabilities();
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const local = capabilities.localComputer;
+ if (capabilities.host.platform !== "win32" || local.reasonCode === "remote-server" || local.available) return null;
+
+ const start = async () => {
+ setPending(true);
+ setError(null);
+ try {
+ await window.ogb?.localControl?.retry();
+ } catch (reason) {
+ setError(reason instanceof Error ? reason.message : String(reason));
+ } finally {
+ setPending(false);
+ }
+ };
+
+ return (
+ <section data-windows-local-control={local.reasonCode ?? "unavailable"} className="mt-4 rounded-xl border border-warning/25 bg-warning/10 p-4">
+ <div className="flex items-start gap-3">
+ <MonitorX size={16} className="mt-0.5 shrink-0 text-warning" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <div className="text-[14px] font-medium text-ink">{t("computer.windows.title")}</div>
+ <p className="mt-1 text-[13px] leading-relaxed text-ink-secondary">
+ {t("computer.windows.body")}
+ {local.reasonCode === "cua-driver-blocked" && <> {t("computer.windows.blocked")}</>}
+ </p>
+ {local.message && (
+ <details className="mt-2 text-[12px] text-ink-secondary">
+ <summary className="cursor-pointer">{t("computer.windows.detail")}</summary>
+ <p className="mt-1 break-words">{local.message}</p>
+ </details>
+ )}
+ {error && (
+ <div role="alert" className="mt-2 flex gap-1.5 text-[12px] text-danger">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span>{error}</span>
+ </div>
+ )}
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => void start()}
+ disabled={pending}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50"
+ >
+ {pending && <Loader2 size={13} className="animate-spin" aria-hidden="true" />}
+ {t(pending ? "computer.windows.starting" : "computer.windows.start")}
+ </button>
+ </div>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/src/computer-ask-preview.tsx b/src/computer-ask-preview.tsx
new file mode 100644
index 0000000000..1e22bbc005
--- /dev/null
+++ b/src/computer-ask-preview.tsx
@@ -0,0 +1,92 @@
+// Dev-only gallery of what the person sees when their own Cloud can't use their PC, served at /computer-ask-preview.html;
+// not in the packaged app. It mounts the real chat over a fixed store with no server behind it, and this PC's own
+// screen-control status over fixed desktop capabilities.
+// ?view=asking|closed|failed|on|pc&skin=midnight|daylight
+import { StrictMode, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import type { ComputerAskCard } from "../shared/computer-ask";
+import { ChatView } from "@/components/ChatView";
+import { DesktopCapabilitiesProvider } from "@/components/DesktopCapabilities";
+import { WindowsLocalControl } from "@/components/WindowsLocalControl";
+import { setAdvancedMode } from "@/lib/interface-mode";
+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
+import { initialState, StoreContext, type AppState, type Bot, type Message } from "@/state/store";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const view = params.get("view") ?? "asking";
+const skin = params.get("skin") ?? "midnight";
+setAdvancedMode(false);
+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
+
+const AT = Date.now() - 6 * 60_000;
+const THREAD = "scout-invoice";
+const message = (id: string, minutes: number, fields: Partial<Message>): Message =>
+ ({ id, at: AT + minutes * 60_000, role: "bot", kind: "text", text: "", ...fields }) as Message;
+
+const ASK: Record<string, { ask: Partial<ComputerAskCard>; answered?: string }> = {
+ asking: { ask: { reason: "not-running", state: "asking" } },
+ closed: { ask: { reason: "closed", state: "asking" } },
+ failed: { ask: { reason: "blocked", state: "failed" } },
+ on: { ask: { reason: "not-running", state: "on" }, answered: "allow" },
+};
+
+function messages(): Message[] {
+ const shown = ASK[view] ?? ASK.asking!;
+ const card = {
+ title: "Scout wants to use your PC's apps and screen", subtitle: "", options: ["Turn on", "Not now"], requestId: "ask-1", requestType: "permission" as const,
+ tool: "turn_on_your_computer", ...(shown.answered ? { answered: shown.answered } : {}),
+ computerAsk: { need: "screen", device: "PC", why: "Fill in this month's invoice in Excel and save it as a PDF", ...shown.ask } as ComputerAskCard,
+ };
+ return [
+ message("ask", 0, { role: "user", text: "Can you fill in this month's invoice in Excel on my PC and save it as a PDF?" }),
+ message("reply", 1, { text: "I'll do it in Excel on your PC." }),
+ message("card", 2, { kind: "options", card }),
+ ...(view === "on" ? [message("after", 4, { text: "Your PC is on. Opening Excel now." })] : []),
+ ];
+}
+
+const bot: Bot = {
+ title: "", description: "", notifications: true, unread: false, modelSelection: { instanceId: "claude", model: "claude-opus-5-5" },
+ id: "scout", name: "Scout", color: "teal", threadId: THREAD, mainThreadId: THREAD, busy: view !== "on", activity: view === "on" ? "working" : "waiting-on-you",
+ tasks: [{ threadId: THREAD, title: "Invoice in Excel", createdAt: AT }], messages: messages(),
+} as Bot;
+
+function Frame({ children }: { children: ReactNode }) {
+ return <div className="flex h-dvh w-full overflow-hidden bg-app text-ink">{children}</div>;
+}
+
+function Gallery() {
+ if (view === "pc") {
+ return (
+ <DesktopCapabilitiesProvider>
+ <Frame><div className="mx-auto w-full max-w-[460px] p-6" data-preview="pc"><WindowsLocalControl /></div></Frame>
+ </DesktopCapabilitiesProvider>
+ );
+ }
+ const state: AppState = { ...initialState, bots: [bot], selectedId: bot.id, connected: true };
+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ return (
+ <StoreContext.Provider value={value}>
+ <Frame><div className="flex min-w-0 flex-1 flex-col" data-preview="chat"><ChatView bot={bot} /></div></Frame>
+ </StoreContext.Provider>
+ );
+}
+
+const realFetch = window.fetch.bind(window);
+window.fetch = async (input, init) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ if (!new URL(url, location.href).pathname.startsWith("/api/")) return realFetch(input, init);
+ return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
+};
+const blocked = "embedded host failed: Spawn: binaryPath C:\\Users\\you\\AppData\\Local\\Programs\\OpenMausBot\\resources\\cua-driver-background.exe; reason Operation did not complete successfully because the file contains a virus or potentially unwanted software. (os error 225)";
+const capabilities = {
+ remote: false, host: { platform: "win32", label: "Windows", session: "unknown", packaged: true, homeDir: "C:\\Users\\you" }, windowChrome: "win-caption",
+ screenPreview: { available: false, interaction: "none", reasonCode: "unsupported-platform" }, dictation: { available: false, engine: "none", onDevice: false },
+ localComputer: { available: false, support: "unsupported", enabled: false, status: "unavailable", reasonCode: "cua-driver-blocked", message: blocked },
+};
+if (view === "pc") {
+ Object.assign(window, { ogb: { platform: "win32", getCapabilities: async () => capabilities, onCapabilitiesChanged: () => () => {}, localControl: { retry: async () => ({}) } } });
+}
+
+createRoot(document.getElementById("root")!).render(<StrictMode><Gallery /></StrictMode>);
diff --git a/src/lib/computer-ask.ts b/src/lib/computer-ask.ts
new file mode 100644
index 0000000000..2916a18fe2
--- /dev/null
+++ b/src/lib/computer-ask.ts
@@ -0,0 +1,46 @@
+import { t } from "./i18n";
+import type { LocaleKey } from "@/locales";
+import {
+ computerAskHeadline, computerAskReasonLine, needsTheApp, turnsOnFromHere, type ComputerAskCard,
+} from "../../shared/computer-ask";
+import type { OptionCardData } from "../../shared/wire";
+
+export interface ComputerAskWords {
+ /** Who wants what, from which computer. */
+ line: string;
+ /** The bot's own reason, when it gave one. */
+ why?: string;
+ /** Why it isn't available now, with the fix when the fix is the app. */
+ reason: string;
+ /** Turn on (or Try again after a failure); absent when only the app there can fix it. */
+ turnOn?: string;
+ /** The app's download page, when the fix is installing, opening or updating it. */
+ getApp?: string;
+ /** How it ended, or that it is turning on; absent while it waits for an answer. */
+ outcome?: string;
+}
+
+const OUTCOME: Partial<Record<ComputerAskCard["state"], LocaleKey>> = {
+ "turning-on": "computerAsk.state.turningOn",
+ on: "computerAsk.state.on",
+ declined: "computerAsk.state.declined",
+ ended: "computerAsk.state.ended",
+};
+
+/** A bot's ask to turn on what it needs from the person's computer, in their language; undefined for any other card. */
+export function computerAskWords(card: Pick<OptionCardData, "computerAsk"> | undefined, name: string): ComputerAskWords | undefined {
+ const ask = card?.computerAsk;
+ if (!ask) return undefined;
+ const headline = computerAskHeadline(ask);
+ const reason = computerAskReasonLine(ask, name);
+ const failed = ask.state === "failed";
+ const outcome = OUTCOME[ask.state];
+ return {
+ line: t(headline.key as LocaleKey, { ...headline.params, name }),
+ ...(ask.why ? { why: ask.why } : {}),
+ reason: `${failed ? `${t("computerAsk.state.failed")} ` : ""}${t(reason.key as LocaleKey, reason.params)}`,
+ ...(turnsOnFromHere(ask.reason) ? { turnOn: t(failed ? "computerAsk.action.tryAgain" : "computerAsk.action.turnOn") } : {}),
+ ...(needsTheApp(ask.reason) ? { getApp: t("computerAsk.action.getApp") } : {}),
+ ...(outcome ? { outcome: t(outcome, { name }) } : {}),
+ };
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index f39731be12..2d39466876 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -759,6 +759,30 @@
"approval.yourComputer.app": "I need to use {app} on your computer. Allow once?",
"approval.yourComputer.screen": "I need to use your computer's screen for this. Allow once?",
"approval.yourComputer.detail": "{name} would see your screen and click and type on it, for this request only.",
+ "computerAsk.want.screen": "{name} wants to use your {device}'s apps and screen",
+ "computerAsk.want.folders": "{name} wants to use the files on your {device}",
+ "computerAsk.want.terminal": "{name} wants to run commands on your {device}",
+ "computerAsk.reason.paused": "Using your {device} is paused.",
+ "computerAsk.reason.starting": "Screen control is still starting on your {device}.",
+ "computerAsk.reason.permissions": "macOS hasn't allowed {app} to see and use the screen yet.",
+ "computerAsk.reason.blocked": "Screen control is blocked on your {device}.",
+ "computerAsk.reason.blockedPc": "Screen control is blocked on your PC: Windows Security may have stopped it.",
+ "computerAsk.reason.off": "Screen control is off on your {device}.",
+ "computerAsk.reason.notRunning": "Screen control isn't running on your {device}.",
+ "computerAsk.reason.unsupported": "Screen control can't work on your {device} right now.",
+ "computerAsk.reason.terminalOff": "Running commands isn't turned on for your {device}.",
+ "computerAsk.reason.closed": "{app} isn't open on your {device}. Open it there and {name} carries on.",
+ "computerAsk.reason.never": "{app} isn't on your computer yet. Install it, sign in to MausBot Cloud there, and {name} carries on.",
+ "computerAsk.reason.update": "{app} on your {device} needs an update first. Update it, and {name} carries on.",
+ "computerAsk.action.turnOn": "Turn on",
+ "computerAsk.action.tryAgain": "Try again",
+ "computerAsk.action.notNow": "Not now",
+ "computerAsk.action.getApp": "Get {app}",
+ "computerAsk.state.turningOn": "Turning on…",
+ "computerAsk.state.on": "Turned on. {name} is carrying on.",
+ "computerAsk.state.failed": "It didn't turn on.",
+ "computerAsk.state.declined": "Not now",
+ "computerAsk.state.ended": "No longer needed",
"approval.held.native": "The provider requires your approval for this action.",
"approval.held.sandbox": "This loosens the AI's own safety limits, so only Full access can approve it automatically.",
"approval.opaqueCode": "This runs code that could send or change things in your apps, so it always asks first.",
@@ -4446,6 +4470,12 @@
"computer.mac.permission.requiredOne": "{permission} is required for {app} to use this computer. Grant it in System Settings → Privacy & Security, then relaunch {app}.",
"computer.mac.permission.requiredBoth": "Screen Recording and Accessibility are required for {app} to use this computer. Grant them in System Settings → Privacy & Security, then relaunch {app}.",
"computer.mac.permission.generic": "Local computer control is not ready. {app} needs Accessibility and Screen Recording to use this Mac. Check Driver detail or System Settings, then click Retry.",
+ "computer.windows.title": "Screen control isn't running on this PC",
+ "computer.windows.body": "Bots here and on the Cloud can't use this PC's apps and screen until it runs.",
+ "computer.windows.blocked": "Windows Security may have stopped it. Allow it under Windows Security → Protection history, or reinstall {app}.",
+ "computer.windows.start": "Start screen control",
+ "computer.windows.starting": "Starting screen control…",
+ "computer.windows.detail": "What went wrong",
"computer.mac.permission.screenSettings": "Open Screen Recording Settings",
"computer.mac.permission.accessibilitySettings": "Open Accessibility Settings",
"computer.mac.permission.relaunch": "Relaunch {app}",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index a263310f82..285957b05d 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -75,7 +75,7 @@ import { reconcileSnapshotQueues, rememberConsumedQueueId, replaceBotQueues } fr
export type { MausColor } from "@/lib/mascot";
export type { RoutineRunCardData } from "../../shared/routine-run";
-export interface OptionCardData extends Pick<WireOptionCard, "fixedOptions" | "webhookRequest" | "appTriggerRequest" | "yourComputer" | "waitRequest" | "stopped"> {
+export interface OptionCardData extends Pick<WireOptionCard, "fixedOptions" | "webhookRequest" | "appTriggerRequest" | "yourComputer" | "computerAsk" | "waitRequest" | "stopped"> {
title: string;
subtitle: string;
options: string[];