All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
OpenRunner: native app and agent tooling for self-hosted GitHub runners
Adib Hanna333c6ac5b18e
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..0dcb022--- /dev/null+++ b/.gitignore@@ -0,0 +1,3 @@+/target+.DS_Store+dist/diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..ae65934--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,95 @@+# Working with OpenRunner as an agent++OpenRunner manages a fleet of self-hosted GitHub Actions runners. The fleet is made up of machines (reached over `ssh`, or directly for `host = "local"`) and the runners installed on them.++Use the MCP tools when they're connected: start the server with `openrunner mcp`, and see the README for setup. Otherwise use the CLI with `--json`. Both front the same API and return the same shapes.++## Ground rules++1. **Start with `fleet_status`** (`openrunner status --json`) and read `attention` first. It lists what's wrong, most severe first, with the `machine_id` or `runner_id` each item is about.+2. **The state may be stale.** `fleet_status` uses the last machine check. Look at `last_check_at` and each machine's `checked_at`. Call `check_machines` (or `fleet_status` with `refresh: true`) when you need it fresh. Checks are read-only.+3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine` and `remove_machine` only edit `fleet.toml`.+4. **Use the hints.** Errors have a `code`:+ - `not_found`+ - `invalid`+ - `busy`+ - `github`+ - `unreachable`+ - `operation_failed`+ - `internal`++ Many errors also have a `hint`, often a command such as `gh auth refresh -h github.com -s admin:org`. Pass hints to the user verbatim; don't improvise around permission problems.+5. **Long operations wait by default** and return a `log_tail`. With `wait: false` you get an `operation_id`; poll `get_operation` until `status` is no longer `running`.++## Ids++- **Machine:** a slug of its name, such as `mac-studio`. The display name is accepted too.+- **Runner:** `<machine-id>/<runner-name>`, such as `mac-studio/mac-studio-01`. A runner that GitHub knows but no machine lists is `github/<name>`. A bare runner name works when it's unique.+- **Runner state:** `working`, `idle`, `offline` or `unknown`. `source` says where the state came from:+ - `github`: live;+ - `probe`: the last machine check;+ - `none`: no information yet.++## Common requests++**"Add my server and put two runners on it."**++1. Call `list_ssh_hosts` to find the user's alias, or ask for `user@host`.+2. Call `add_machine(name, host)`. Its result includes the first check. If the status is `offline`, the machine isn't reachable with key-based ssh. Show the error and stop.+3. Make sure a GitHub scope is watched (`fleet_status.github.watching`). If none is, ask which org or repo to use and call `github_scopes(add: [...])`. A failure there usually needs `admin:org`; show the hint.+4. Call `install_runners(machine_id, count: 2)`. Pass `scope` if more than one org or repo is watched. The default `mode: "auto"` picks a service where possible, else Docker containers (Linux without passwordless sudo), else a background run.sh; the log says which. Use `mode: "docker"` when the user wants isolated runners; only pass `docker_socket: true` if they explicitly want jobs to use Docker and trust the workflows (it's root-equivalent on the host).+5. Report the new runner ids and their states from the result.++**"Why is runner X offline?"**++1. Call `get_machine` on its machine. Check the machine's `status` first: an unreachable machine explains everything on it. Then check the runner's `state`, `source`, `service_state`, and the diagnostics with its `runner_id`.+2. Call `runner_action(X, "logs")` to read its newest `_diag` log.+3. Explain the cause and propose a fix, such as `runner_action(X, "start")`. Do it only if the user agrees or already asked.++**"Restart everything on machine Y."**++1. Call `get_machine(Y)` to get its runner ids.+2. Call `runner_action(id, "restart")` for each, one at a time. A machine accepts one changing operation at a time; `busy` means wait and retry.+3. Summarize the final states.++**"Why isn't my job starting?"**++1. Call `list_jobs`. A queued job with `matching_online: 0` has no online runner with all of its labels.+2. Compare the job's labels with the runners' labels (`list_runners`). The fix is usually to start an offline runner, or to install one with the missing label (`install_runners(labels: [...])`).++## Workspaces: borrowing a machine to work on++A workspace is a persistent folder on one of the user's machines, optionally a git checkout, that you use as your own work environment. It's like a remote dev box: `workspace_exec` runs shell commands there with the machine user's login environment. Ids look like `ws-7f3a2c`.++- **Reuse before you create.** Call `workspace_list` first. Use one workspace per task and keep using it across steps.+- **Destroy when you're done.** Nothing is deleted automatically. Pull or push anything worth keeping first.+- **A non-zero `exit_code` is a normal result,** not a tool error. Read `stderr`.+- **Long-running things go in the background.** Use `background: true` for servers and watchers, then read the returned `log_path` with `workspace_read_file`.+- **It's a real machine.** Commands run as the user, not in a sandbox. Don't do anything outside the workspace that you wouldn't do in their terminal without asking.++**"Run the test suite on Linux."**++1. Call `workspace_create(platform: "linux", repo: "<owner/repo>", ref: "<branch>")`. Omit `machine_id` to get the least-loaded Linux machine.+2. Install dependencies and run the tests with `workspace_exec`, e.g. `npm ci && npm test`. Raise `timeout_secs` if the suite is slow (max 3600).+3. Report the exit code and the failing tests from `stdout`/`stderr`, then `workspace_destroy` unless the user wants to keep it.++**"Start a dev server and check it."**++1. In an existing workspace, call `workspace_exec(command: "npm run dev", background: true)`. Note the `log_path`.+2. Wait a moment, then read the log with `workspace_read_file(path: <log_path>)` and probe the server with `workspace_exec(command: "curl -sS localhost:3000/health")`.+3. Background processes stop when the workspace is destroyed.++**"Push my local changes, run the tests there, and pull the fix back."**++1. Create a workspace on the target machine (no `repo`, or the same repo so `.git` exists), then call `workspace_sync(local_path: "<absolute path to the user's checkout>", direction: "push")`.+2. Run the tests with `workspace_exec`. Fix things with `workspace_write_file` or `workspace_exec`, and review with `workspace_changes`.+3. Confirm with the user, then `workspace_sync(direction: "pull")`. Only pass `delete: true` when they want deletions mirrored into their checkout.++The CLI equivalents are `openrunner workspace create|ls|show|exec|cat|write|files|changes|sync|rm|allow`, aliased as `openrunner ws`. `ws exec` exits with the command's own exit code.++## Don'ts++- Don't edit `fleet.toml`, `settings.json` or `state.json` by hand while the tools can do it.+- Don't pass tokens around. OpenRunner gets registration tokens itself from the user's `gh` login.+- Don't use `delete_files: true` unless the user wants the runner's folder gone.+- Don't leave workspaces behind, and don't turn workspaces on for a machine (`workspace_allow`) unless the user asks.diff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..09328b5--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,7766 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aes"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"+dependencies = [+ "cfg-if",+ "cipher",+ "cpufeatures 0.2.17",+ "zeroize",+]++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "const-random",+ "once_cell",+ "version_check",+ "zerocopy",+]++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "aligned"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"+dependencies = [+ "as-slice",+]++[[package]]+name = "aligned-vec"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"+dependencies = [+ "equator",+]++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys 0.61.2",+]++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"++[[package]]+name = "ar_archive_writer"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"+dependencies = [+ "object",+]++[[package]]+name = "arbitrary"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"++[[package]]+name = "arg_enum_proc_macro"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "as-raw-xcb-connection"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"++[[package]]+name = "as-slice"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"+dependencies = [+ "stable_deref_trait",+]++[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading",+]++[[package]]+name = "ash-window"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52bca67b61cb81e5553babde81b8211f713cb6db79766f80168f3e5f40ea6c82"+dependencies = [+ "ash",+ "raw-window-handle",+ "raw-window-metal",+]++[[package]]+name = "ashpd"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39"+dependencies = [+ "async-fs",+ "async-net",+ "enumflags2",+ "futures-channel",+ "futures-util",+ "rand 0.9.5",+ "serde",+ "serde_repr",+ "url",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols 0.32.13",+ "zbus",+]++[[package]]+name = "ashpd"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33a3c86f3fd70c0ffa500ed189abfa90b5a52398a45d5dc372fcc38ebeb7a645"+dependencies = [+ "async-fs",+ "async-net",+ "enumflags2",+ "futures-channel",+ "futures-util",+ "rand 0.9.5",+ "serde",+ "serde_repr",+ "url",+ "zbus",+]++[[package]]+name = "async-broadcast"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"+dependencies = [+ "event-listener 5.4.2",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-channel"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"+dependencies = [+ "concurrent-queue",+ "event-listener 2.5.3",+ "futures-core",+]++[[package]]+name = "async-channel"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"+dependencies = [+ "concurrent-queue",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-compression"+version = "0.4.50"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee19bd99b43e3691acbad4e840420a4881cea6c0b66a208125a824f8fd53f5a1"+dependencies = [+ "compression-codecs",+ "compression-core",+ "futures-io",+ "pin-project-lite",+]++[[package]]+name = "async-executor"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"+dependencies = [+ "async-task",+ "concurrent-queue",+ "fastrand 2.5.0",+ "futures-lite 2.6.1",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "async-fs"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"+dependencies = [+ "async-lock",+ "blocking",+ "futures-lite 2.6.1",+]++[[package]]+name = "async-global-executor"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c"+dependencies = [+ "async-channel 2.5.0",+ "async-executor",+ "async-io",+ "async-lock",+ "blocking",+ "futures-lite 2.6.1",+ "once_cell",+]++[[package]]+name = "async-io"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"+dependencies = [+ "autocfg",+ "cfg-if",+ "concurrent-queue",+ "futures-io",+ "futures-lite 2.6.1",+ "parking",+ "polling",+ "rustix 1.1.5",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-lock"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"+dependencies = [+ "event-listener 5.4.2",+ "event-listener-strategy",+ "pin-project-lite",+]++[[package]]+name = "async-net"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"+dependencies = [+ "async-io",+ "blocking",+ "futures-lite 2.6.1",+]++[[package]]+name = "async-process"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"+dependencies = [+ "async-channel 2.5.0",+ "async-io",+ "async-lock",+ "async-signal",+ "async-task",+ "blocking",+ "cfg-if",+ "event-listener 5.4.2",+ "futures-lite 2.6.1",+ "rustix 1.1.5",+]++[[package]]+name = "async-recursion"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "async-signal"+version = "0.2.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"+dependencies = [+ "async-io",+ "async-lock",+ "atomic-waker",+ "cfg-if",+ "futures-core",+ "futures-io",+ "rustix 1.1.5",+ "signal-hook-registry",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-std"+version = "1.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b"+dependencies = [+ "async-channel 1.9.0",+ "async-global-executor",+ "async-io",+ "async-lock",+ "async-process",+ "crossbeam-utils",+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-lite 2.6.1",+ "gloo-timers",+ "kv-log-macro",+ "log",+ "memchr",+ "once_cell",+ "pin-project-lite",+ "pin-utils",+ "slab",+ "wasm-bindgen-futures",+]++[[package]]+name = "async-task"+version = "4.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"++[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "async_zip"+version = "0.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b9f7252833d5ed4b00aa9604b563529dd5e11de9c23615de2dcdf91eb87b52"+dependencies = [+ "async-compression",+ "crc32fast",+ "futures-lite 2.6.1",+ "pin-project",+ "thiserror 1.0.69",+]++[[package]]+name = "atomic"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba"++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "av-scenechange"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"+dependencies = [+ "aligned",+ "anyhow",+ "arg_enum_proc_macro",+ "arrayvec",+ "log",+ "num-rational",+ "num-traits",+ "pastey",+ "rayon",+ "thiserror 2.0.21",+ "v_frame",+ "y4m",+]++[[package]]+name = "av1-grain"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"+dependencies = [+ "anyhow",+ "arrayvec",+ "log",+ "nom 8.0.0",+ "num-rational",+ "v_frame",+]++[[package]]+name = "avif-serialize"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38"+dependencies = [+ "arrayvec",+]++[[package]]+name = "aws-lc-rs"+version = "1.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"+dependencies = [+ "aws-lc-sys",+ "zeroize",+]++[[package]]+name = "aws-lc-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"+dependencies = [+ "cc",+ "cmake",+ "dunce",+ "fs_extra",+ "pkg-config",+]++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "bindgen"+version = "0.71.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"+dependencies = [+ "bitflags 2.13.2",+ "cexpr",+ "clang-sys",+ "itertools 0.13.0",+ "log",+ "prettyplease",+ "proc-macro2",+ "quote",+ "regex",+ "rustc-hash 2.1.3",+ "shlex 1.3.0",+ "syn 2.0.119",+]++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bit_field"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "bitstream-io"+version = "4.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f"+dependencies = [+ "no_std_io2",+]++[[package]]+name = "blade-graphics"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e71cfb73b98eb9f58ee84048aa1bdf4e7497fd20c141b57523499fa066b48fed"+dependencies = [+ "ash",+ "ash-window",+ "bitflags 2.13.2",+ "bytemuck",+ "codespan-reporting",+ "glow",+ "gpu-alloc",+ "gpu-alloc-ash",+ "hidden-trait",+ "js-sys",+ "khronos-egl",+ "libloading",+ "log",+ "mint",+ "naga",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-metal",+ "objc2-quartz-core",+ "objc2-ui-kit",+ "once_cell",+ "raw-window-handle",+ "slab",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "blade-macros"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27142319e2f4c264581067eaccb9f80acccdde60d8b4bf57cc50cd3152f109ca"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "blade-util"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a6be3a82c001ba7a17b6f8e413ede5d1004e6047213f8efaf0ffc15b5c4904c"+dependencies = [+ "blade-graphics",+ "bytemuck",+ "log",+ "profiling",+]++[[package]]+name = "block"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]++[[package]]+name = "blocking"+version = "1.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"+dependencies = [+ "async-channel 2.5.0",+ "async-task",+ "futures-io",+ "futures-lite 2.6.1",+ "piper",+]++[[package]]+name = "bstr"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"+dependencies = [+ "memchr",+ "serde_core",+]++[[package]]+name = "built"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "calloop"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"+dependencies = [+ "bitflags 2.13.2",+ "log",+ "polling",+ "rustix 0.38.44",+ "slab",+ "thiserror 1.0.69",+]++[[package]]+name = "calloop-wayland-source"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"+dependencies = [+ "calloop",+ "rustix 0.38.44",+ "wayland-backend",+ "wayland-client",+]++[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]++[[package]]+name = "cbindgen"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff"+dependencies = [+ "heck 0.4.1",+ "indexmap",+ "log",+ "proc-macro2",+ "quote",+ "serde",+ "serde_json",+ "syn 2.0.119",+ "tempfile",+ "toml 0.8.23",+]++[[package]]+name = "cc"+version = "1.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex 2.0.1",+]++[[package]]+name = "cexpr"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"+dependencies = [+ "nom 7.1.3",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "cgl"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff"+dependencies = [+ "libc",+]++[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "rand_core 0.10.1",+]++[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "js-sys",+ "num-traits",+ "serde",+ "wasm-bindgen",+ "windows-link 0.2.1",+]++[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common 0.1.7",+ "inout",+ "zeroize",+]++[[package]]+name = "clang-sys"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"+dependencies = [+ "glob",+ "libc",+ "libloading",+]++[[package]]+name = "clap"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "clap_lex"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"++[[package]]+name = "cmake"+version = "0.1.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+dependencies = [+ "cc",+]++[[package]]+name = "cocoa"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c"+dependencies = [+ "bitflags 1.3.2",+ "block",+ "cocoa-foundation 0.1.2",+ "core-foundation 0.9.4",+ "core-graphics 0.23.2",+ "foreign-types",+ "libc",+ "objc",+]++[[package]]+name = "cocoa"+version = "0.26.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2"+dependencies = [+ "bitflags 2.13.2",+ "block",+ "cocoa-foundation 0.2.0",+ "core-foundation 0.10.0",+ "core-graphics 0.24.0",+ "foreign-types",+ "libc",+ "objc",+]++[[package]]+name = "cocoa-foundation"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c6234cbb2e4c785b456c0644748b1ac416dd045799740356f8363dfe00c93f7"+dependencies = [+ "bitflags 1.3.2",+ "block",+ "core-foundation 0.9.4",+ "core-graphics-types 0.1.3",+ "libc",+ "objc",+]++[[package]]+name = "cocoa-foundation"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d"+dependencies = [+ "bitflags 2.13.2",+ "block",+ "core-foundation 0.10.0",+ "core-graphics-types 0.2.0",+ "libc",+ "objc",+]++[[package]]+name = "codespan-reporting"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"+dependencies = [+ "serde",+ "termcolor",+ "unicode-width",+]++[[package]]+name = "color_quant"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"++[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"++[[package]]+name = "combine"+version = "4.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "command-fds"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b60b5124979fccd9addd89d8b97a1d6eebb4950694520c75ddd722535ea443f"+dependencies = [+ "nix 0.31.3",+ "thiserror 2.0.21",+]++[[package]]+name = "compression-codecs"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98fc98460ba0ad5317075d3632b8dfc45d0be8c4a49347c2a38272019717614a"+dependencies = [+ "compression-core",+ "deflate64",+ "flate2",+ "memchr",+]++[[package]]+name = "compression-core"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414"++[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "const-oid"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"++[[package]]+name = "const-random"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"+dependencies = [+ "const-random-macro",+]++[[package]]+name = "const-random-macro"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"+dependencies = [+ "getrandom 0.2.17",+ "once_cell",+ "tiny-keccak",+]++[[package]]+name = "convert_case"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation 0.9.4",+ "core-graphics-types 0.1.3",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.10.0",+ "core-graphics-types 0.2.0",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-helmer-fork"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32eb7c354ae9f6d437a6039099ce7ecd049337a8109b23d73e48e8ffba8e9cd5"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.9.4",+ "core-graphics-types 0.1.3",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation 0.9.4",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.10.0",+ "libc",+]++[[package]]+name = "core-graphics2"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e4583956b9806b69f73fcb23aee05eb3620efc282972f08f6a6db7504f8334d"+dependencies = [+ "bitflags 2.13.2",+ "block",+ "cfg-if",+ "core-foundation 0.10.0",+ "libc",+]++[[package]]+name = "core-text"+version = "21.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a593227b66cbd4007b2a050dfdd9e1d1318311409c8d600dc82ba1b15ca9c130"+dependencies = [+ "core-foundation 0.10.0",+ "core-graphics 0.24.0",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-video"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d45e71d5be22206bed53c3c3cb99315fc4c3d31b8963808c6bc4538168c4f8ef"+dependencies = [+ "block",+ "core-foundation 0.10.0",+ "core-graphics2",+ "io-surface",+ "libc",+ "metal",+]++[[package]]+name = "core_detect"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"++[[package]]+name = "core_maths"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"+dependencies = [+ "libm",+]++[[package]]+name = "cosmic-text"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da46a9d5a8905cc538a4a5bceb6a4510de7a51049c5588c0114efce102bcbbe8"+dependencies = [+ "bitflags 2.13.2",+ "fontdb 0.16.2",+ "log",+ "rangemap",+ "rustc-hash 1.1.0",+ "rustybuzz 0.14.1",+ "self_cell",+ "smol_str",+ "swash",+ "sys-locale",+ "ttf-parser 0.21.1",+ "unicode-bidi",+ "unicode-linebreak",+ "unicode-script",+ "unicode-segmentation",+]++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-queue"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "rand_core 0.6.4",+ "typenum",+]++[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "ctor"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec09e802f5081de6157da9a75701d6c713d8dc3ba52571fd4bd25f412644e8a6"+dependencies = [+ "ctor-proc-macro",+ "dtor",+]++[[package]]+name = "ctor-proc-macro"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2"++[[package]]+name = "data-url"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"++[[package]]+name = "deflate64"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"++[[package]]+name = "derive_more"+version = "0.99.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f"+dependencies = [+ "convert_case",+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.119",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer 0.10.4",+ "crypto-common 0.1.7",+ "subtle",+]++[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.1",+ "const-oid",+ "crypto-common 0.2.2",+]++[[package]]+name = "dirs"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"+dependencies = [+ "dirs-sys 0.3.7",+]++[[package]]+name = "dirs"+version = "5.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"+dependencies = [+ "dirs-sys 0.4.1",+]++[[package]]+name = "dirs"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"+dependencies = [+ "dirs-sys 0.5.0",+]++[[package]]+name = "dirs-sys"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"+dependencies = [+ "libc",+ "redox_users 0.4.6",+ "winapi",+]++[[package]]+name = "dirs-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"+dependencies = [+ "libc",+ "option-ext",+ "redox_users 0.4.6",+ "windows-sys 0.48.0",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users 0.5.3",+ "windows-sys 0.61.2",+]++[[package]]+name = "dispatch"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+]++[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading",+]++[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"++[[package]]+name = "dtor"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97cbdf2ad6846025e8e25df05171abfb30e3ababa12ee0a0e44b9bbe570633a8"+dependencies = [+ "dtor-proc-macro",+]++[[package]]+name = "dtor-proc-macro"+version = "0.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055"++[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"++[[package]]+name = "dwrote"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02"+dependencies = [+ "lazy_static",+ "libc",+ "winapi",+ "wio",+]++[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "embed-resource"+version = "3.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml 1.1.7+spec-1.1.0",+ "vswhom",+ "winreg",+]++[[package]]+name = "encoding_rs"+version = "0.8.42"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"+dependencies = [+ "cfg-if",+ "core_detect",+ "multiversion_no_op",+ "rustversion",+ "scopeguard",+ "simdutf8",+]++[[package]]+name = "endi"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"++[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+ "serde",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "equator"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"+dependencies = [+ "equator-macro",+]++[[package]]+name = "equator-macro"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "erased-serde"+version = "0.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"+dependencies = [+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "etagere"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342"+dependencies = [+ "euclid",+ "svg_fmt",+]++[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]++[[package]]+name = "event-listener"+version = "2.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"++[[package]]+name = "event-listener"+version = "5.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"+dependencies = [+ "parking",+ "pin-project-lite",+]++[[package]]+name = "event-listener-strategy"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"+dependencies = [+ "event-listener 5.4.2",+ "pin-project-lite",+]++[[package]]+name = "exr"+version = "1.74.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3"+dependencies = [+ "bit_field",+ "half",+ "lebe",+ "miniz_oxide 0.8.9",+ "num-complex",+ "pulp",+ "rayon-core",+ "smallvec",+ "zune-inflate",+]++[[package]]+name = "fastrand"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"+dependencies = [+ "instant",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "fax"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "filedescriptor"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"+dependencies = [+ "libc",+ "thiserror 1.0.69",+ "winapi",+]++[[package]]+name = "filetime"+version = "0.2.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"+dependencies = [+ "cfg-if",+ "libc",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"++[[package]]+name = "flate2"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "float-cmp"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"++[[package]]+name = "float-ord"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d"++[[package]]+name = "float_next_after"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"++[[package]]+name = "flume"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"+dependencies = [+ "futures-core",+ "futures-sink",+ "nanorand",+ "spin",+]++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"++[[package]]+name = "font-types"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274"+dependencies = [+ "bytemuck",+]++[[package]]+name = "fontconfig-parser"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"+dependencies = [+ "roxmltree",+]++[[package]]+name = "fontdb"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3"+dependencies = [+ "fontconfig-parser",+ "log",+ "memmap2",+ "slotmap",+ "tinyvec",+ "ttf-parser 0.20.0",+]++[[package]]+name = "fontdb"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"+dependencies = [+ "fontconfig-parser",+ "log",+ "memmap2",+ "slotmap",+ "tinyvec",+ "ttf-parser 0.25.1",+]++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "freetype-sys"+version = "0.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+]++[[package]]+name = "fs_extra"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"++[[package]]+name = "futf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"+dependencies = [+ "mac",+ "new_debug_unreachable",+]++[[package]]+name = "futures"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-channel"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"+dependencies = [+ "futures-core",+ "futures-sink",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-executor"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"++[[package]]+name = "futures-lite"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce"+dependencies = [+ "fastrand 1.9.0",+ "futures-core",+ "futures-io",+ "memchr",+ "parking",+ "pin-project-lite",+ "waker-fn",+]++[[package]]+name = "futures-lite"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"+dependencies = [+ "fastrand 2.5.0",+ "futures-core",+ "futures-io",+ "parking",+ "pin-project-lite",+]++[[package]]+name = "futures-macro"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "futures-sink"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix 1.1.5",+ "windows-link 0.2.1",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi 6.0.0",+ "rand_core 0.10.1",+ "wasm-bindgen",+]++[[package]]+name = "gif"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+dependencies = [+ "color_quant",+ "weezl",+]++[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"++[[package]]+name = "globset"+version = "0.4.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"+dependencies = [+ "aho-corasick",+ "bstr",+ "log",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "gloo-timers"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"+dependencies = [+ "futures-channel",+ "futures-core",+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "glow"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08"+dependencies = [+ "js-sys",+ "slotmap",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "gpu-alloc"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9"+dependencies = [+ "bitflags 2.13.2",+ "gpu-alloc-types",+]++[[package]]+name = "gpu-alloc-ash"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "643756f08ef6def813c776199e4766596395a4c6530373c9a4374a64de2f53a1"+dependencies = [+ "ash",+ "gpu-alloc-types",+ "tinyvec",+]++[[package]]+name = "gpu-alloc-types"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "gpui"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "979b45cfa6ec723b6f42330915a1b3769b930d02b2d505f9697f8ca602bee707"+dependencies = [+ "anyhow",+ "as-raw-xcb-connection",+ "ashpd 0.11.1",+ "async-task",+ "bindgen",+ "blade-graphics",+ "blade-macros",+ "blade-util",+ "block",+ "bytemuck",+ "calloop",+ "calloop-wayland-source",+ "cbindgen",+ "cocoa 0.26.0",+ "cocoa-foundation 0.2.0",+ "core-foundation 0.10.0",+ "core-foundation-sys",+ "core-graphics 0.24.0",+ "core-text",+ "core-video",+ "cosmic-text",+ "ctor",+ "derive_more",+ "embed-resource",+ "etagere",+ "filedescriptor",+ "flume",+ "foreign-types",+ "futures",+ "gpui-macros",+ "gpui_collections",+ "gpui_http_client",+ "gpui_media",+ "gpui_refineable",+ "gpui_semantic_version",+ "gpui_sum_tree",+ "gpui_util",+ "gpui_util_macros",+ "image",+ "inventory",+ "itertools 0.14.0",+ "libc",+ "log",+ "lyon",+ "metal",+ "naga",+ "num_cpus",+ "objc",+ "oo7",+ "open",+ "parking",+ "parking_lot",+ "pathfinder_geometry",+ "pin-project",+ "postage",+ "profiling",+ "rand 0.9.5",+ "raw-window-handle",+ "resvg",+ "schemars",+ "seahash",+ "serde",+ "serde_json",+ "slotmap",+ "smallvec",+ "smol",+ "stacksafe",+ "strum 0.27.2",+ "taffy",+ "thiserror 2.0.21",+ "usvg",+ "uuid",+ "waker-fn",+ "wayland-backend",+ "wayland-client",+ "wayland-cursor",+ "wayland-protocols 0.31.2",+ "wayland-protocols-plasma",+ "windows 0.61.3",+ "windows-core 0.61.2",+ "windows-numerics",+ "windows-registry 0.5.3",+ "x11-clipboard",+ "x11rb",+ "xkbcommon",+ "zed-font-kit",+ "zed-scap",+ "zed-xim",+]++[[package]]+name = "gpui-macros"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bcb02dd63a2859714ac7b6b476937617c3c744157af1b49f7c904023a79039be"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "gpui_collections"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae39dc6d3d201be97e4bc08d96dbef2bc5b5c3d5734e05786e8cc3043342351c"+dependencies = [+ "indexmap",+ "rustc-hash 2.1.3",+]++[[package]]+name = "gpui_derive_refineable"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "644de174341a87b3478bd65b66bca38af868bcf2b2e865700523734f83cfc664"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "gpui_http_client"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23822b0a6d2c5e6a42507980a0ab3848610ea908942c8ef98187f646f690335e"+dependencies = [+ "anyhow",+ "async-compression",+ "async-fs",+ "bytes",+ "derive_more",+ "futures",+ "gpui_util",+ "http",+ "http-body",+ "log",+ "parking_lot",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tempfile",+ "url",+ "zed-async-tar",+ "zed-reqwest",+]++[[package]]+name = "gpui_media"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05cb8912ae17371725132d2b7eec6797a255accc95d58ee5c1134b529810f14b"+dependencies = [+ "anyhow",+ "bindgen",+ "core-foundation 0.10.0",+ "core-video",+ "ctor",+ "foreign-types",+ "metal",+ "objc",+]++[[package]]+name = "gpui_perf"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40a0961dcf598955130e867f4b731150a20546427b41b1a63767c1037a86d77"+dependencies = [+ "gpui_collections",+ "serde",+ "serde_json",+]++[[package]]+name = "gpui_refineable"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "258cb099254e9468181aee5614410fba61db4ae115fc1d51b4a0b985f60d6641"+dependencies = [+ "gpui_derive_refineable",+]++[[package]]+name = "gpui_semantic_version"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "201e45eff7b695528fb3af6560a534943fbc2db5323d755b9d198bd743948e35"+dependencies = [+ "anyhow",+ "serde",+]++[[package]]+name = "gpui_sum_tree"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4f3bedd573fafafa13d1200b356c588cf094fb2786e3684bb3f5ea59b549fa9"+dependencies = [+ "arrayvec",+ "log",+ "rayon",+]++[[package]]+name = "gpui_util"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68faea25903ae524de9af83990b9aa51bcbc8dd085929ac0aea7fd41905e05c3"+dependencies = [+ "anyhow",+ "async-fs",+ "async_zip",+ "command-fds",+ "dirs 4.0.0",+ "dunce",+ "futures",+ "futures-lite 1.13.0",+ "globset",+ "gpui_collections",+ "itertools 0.14.0",+ "libc",+ "log",+ "nix 0.29.0",+ "regex",+ "rust-embed",+ "schemars",+ "serde",+ "serde_json",+ "serde_json_lenient",+ "shlex 1.3.0",+ "smol",+ "take-until",+ "tempfile",+ "tendril",+ "unicase",+ "walkdir",+ "which",+]++[[package]]+name = "gpui_util_macros"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c28f65ef47fb97e21e82fd4dd75ccc2506eda010c846dc8054015ea234f1a22"+dependencies = [+ "gpui_perf",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "grid"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12101ecc8225ea6d675bc70263074eab6169079621c2186fe0c66590b2df9681"++[[package]]+name = "h2"+version = "0.4.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "num-traits",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"++[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "heck"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "hexf-parse"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"++[[package]]+name = "hidden-trait"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ed9e850438ac849bec07e7d09fbe9309cbd396a5988c30b010580ce08860df"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 1.0.109",+]++[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac",+]++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest 0.10.7",+]++[[package]]+name = "home"+version = "0.5.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hybrid-array"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"+dependencies = [+ "typenum",+]++[[package]]+name = "hyper"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "h2",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "rustls-native-certs",+ "tokio",+ "tokio-rustls",+ "tower-service",+]++[[package]]+name = "hyper-util"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"+dependencies = [+ "base64 0.23.1",+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "httparse",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "system-configuration 0.7.0",+ "tokio",+ "tower-service",+ "tracing",+ "windows-registry 0.6.1",+]++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core 0.62.2",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "icu_collections"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"++[[package]]+name = "icu_properties"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"++[[package]]+name = "icu_provider"+version = "2.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "color_quant",+ "exr",+ "gif",+ "image-webp",+ "moxcms",+ "num-traits",+ "png 0.18.1",+ "qoi",+ "ravif",+ "rayon",+ "rgb",+ "tiff",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "image-webp"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"+dependencies = [+ "byteorder-lite",+ "quick-error",+]++[[package]]+name = "imagesize"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"++[[package]]+name = "imgref"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+ "serde",+ "serde_core",+]++[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "block-padding",+ "generic-array",+]++[[package]]+name = "instant"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"+dependencies = [+ "cfg-if",+]++[[package]]+name = "interpolate_name"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "inventory"+version = "0.3.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c"+dependencies = [+ "rustversion",+]++[[package]]+name = "io-surface"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "554b8c5d64ec09a3a520fe58e4d48a73e00ff32899cdcbe32a4877afd4968b8e"+dependencies = [+ "cgl",+ "core-foundation 0.10.0",+ "core-foundation-sys",+ "leaky-cow",+]++[[package]]+name = "ipnet"+version = "2.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"++[[package]]+name = "is-docker"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"+dependencies = [+ "once_cell",+]++[[package]]+name = "is-wsl"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"+dependencies = [+ "is-docker",+ "once_cell",+]++[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"++[[package]]+name = "itertools"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+dependencies = [+ "either",+]++[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys",+ "log",+ "simd_cesu8",+ "thiserror 2.0.21",+ "walkdir",+ "windows-link 0.2.1",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn 2.0.119",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.3",+ "libc",+]++[[package]]+name = "js-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "libloading",+]++[[package]]+name = "kurbo"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62"+dependencies = [+ "arrayvec",+ "euclid",+ "smallvec",+]++[[package]]+name = "kv-log-macro"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f"+dependencies = [+ "log",+]++[[package]]+name = "lazy_static"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"+dependencies = [+ "spin",+]++[[package]]+name = "leak"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd100e01f1154f2908dfa7d02219aeab25d0b9c7fa955164192e3245255a0c73"++[[package]]+name = "leaky-cow"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40a8225d44241fd324a8af2806ba635fc7c8a7e9a7de4d5cf3ef54e71f5926fc"+dependencies = [+ "leak",+]++[[package]]+name = "lebe"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"++[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"++[[package]]+name = "libfuzzer-sys"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"+dependencies = [+ "arbitrary",+ "cc",+]++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link 0.2.1",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "libredox"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"+dependencies = [+ "libc",+]++[[package]]+name = "linux-raw-sys"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"+dependencies = [+ "serde_core",+ "value-bag",+]++[[package]]+name = "loop9"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062"+dependencies = [+ "imgref",+]++[[package]]+name = "lru-slab"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"++[[package]]+name = "lyon"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7"+dependencies = [+ "lyon_algorithms",+ "lyon_tessellation",+]++[[package]]+name = "lyon_algorithms"+version = "1.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdfa8785f95e57914ddb35e3b59994aeba6f5e79e9cfd03da1c269f010f36009"+dependencies = [+ "lyon_path",+ "num-traits",+]++[[package]]+name = "lyon_geom"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92"+dependencies = [+ "arrayvec",+ "euclid",+ "num-traits",+]++[[package]]+name = "lyon_path"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e"+dependencies = [+ "lyon_geom",+ "num-traits",+]++[[package]]+name = "lyon_tessellation"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43b8dcf906637ecef61b3c0740c7a4e7f27caeb31257cfac0cc579ce15be6005"+dependencies = [+ "float_next_after",+ "lyon_path",+ "num-traits",+]++[[package]]+name = "mac"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"++[[package]]+name = "malloc_buf"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"+dependencies = [+ "libc",+]++[[package]]+name = "matchers"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"+dependencies = [+ "regex-automata",+]++[[package]]+name = "maybe-rayon"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"+dependencies = [+ "cfg-if",+ "rayon",+]++[[package]]+name = "md-5"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+dependencies = [+ "cfg-if",+ "digest 0.10.7",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"+dependencies = [+ "libc",+]++[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]++[[package]]+name = "metal"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ecfd3296f8c56b7c1f6fbac3c71cefa9d78ce009850c45000015f206dc7fa21"+dependencies = [+ "bitflags 2.13.2",+ "block",+ "core-graphics-types 0.1.3",+ "foreign-types",+ "log",+ "objc",+ "paste",+]++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "mime_guess"+version = "2.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"+dependencies = [+ "mime",+ "unicase",+]++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mint"+version = "0.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e53debba6bda7a793e5f99b8dacf19e626084f525f7829104ba9898f367d85ff"++[[package]]+name = "mio"+version = "1.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "multiversion_no_op"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"++[[package]]+name = "naga"+version = "25.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags 2.13.2",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.15.5",+ "hexf-parse",+ "indexmap",+ "log",+ "num-traits",+ "once_cell",+ "rustc-hash 1.1.0",+ "spirv",+ "strum 0.26.3",+ "thiserror 2.0.21",+ "unicode-ident",+]++[[package]]+name = "nanorand"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "new_debug_unreachable"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"++[[package]]+name = "nix"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "cfg_aliases",+ "libc",+]++[[package]]+name = "nix"+version = "0.31.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "cfg_aliases",+ "libc",+]++[[package]]+name = "no_std_io2"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003"+dependencies = [+ "memchr",+]++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "nom"+version = "8.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"+dependencies = [+ "memchr",+]++[[package]]+name = "noop_proc_macro"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"++[[package]]+name = "ntapi"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"+dependencies = [+ "winapi",+]++[[package]]+name = "nu-ansi-term"+version = "0.50.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "num"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"+dependencies = [+ "num-bigint",+ "num-complex",+ "num-integer",+ "num-iter",+ "num-rational",+ "num-traits",+]++[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-bigint-dig"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"+dependencies = [+ "lazy_static",+ "libm",+ "num-integer",+ "num-iter",+ "num-traits",+ "rand 0.8.8",+ "serde",+ "smallvec",+ "zeroize",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "bytemuck",+ "num-traits",+]++[[package]]+name = "num-derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "num-integer"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "num_cpus"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"+dependencies = [+ "hermit-abi",+ "libc",+]++[[package]]+name = "objc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"+dependencies = [+ "malloc_buf",+ "objc_exception",+]++[[package]]+name = "objc-foundation"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"+dependencies = [+ "block",+ "objc",+ "objc_id",+]++[[package]]+name = "objc2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-metal",+]++[[package]]+name = "objc2-ui-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "objc_exception"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4"+dependencies = [+ "cc",+]++[[package]]+name = "objc_id"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b"+dependencies = [+ "objc",+]++[[package]]+name = "object"+version = "0.39.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"+dependencies = [+ "memchr",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"++[[package]]+name = "oo7"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3299dd401feaf1d45afd8fd1c0586f10fcfb22f244bb9afa942cec73503b89d"+dependencies = [+ "aes",+ "ashpd 0.12.3",+ "async-fs",+ "async-io",+ "async-lock",+ "blocking",+ "cbc",+ "cipher",+ "digest 0.10.7",+ "endi",+ "futures-lite 2.6.1",+ "futures-util",+ "getrandom 0.3.4",+ "hkdf",+ "hmac",+ "md-5",+ "num",+ "num-bigint-dig",+ "pbkdf2",+ "rand 0.9.5",+ "serde",+ "sha2 0.10.9",+ "subtle",+ "zbus",+ "zbus_macros",+ "zeroize",+ "zvariant",+]++[[package]]+name = "open"+version = "5.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc"+dependencies = [+ "is-wsl",+ "libc",+]++[[package]]+name = "openrunner"+version = "0.1.0"+dependencies = [+ "anyhow",+ "base64 0.22.1",+ "chrono",+ "clap",+ "cocoa 0.26.0",+ "dirs 7.0.0",+ "futures",+ "gpui",+ "reqwest",+ "serde",+ "serde_json",+ "tokio",+ "toml 1.1.7+spec-1.1.0",+ "toml_edit 0.25.16+spec-1.1.0",+ "tracing",+ "tracing-subscriber",+ "unicode-segmentation",+]++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"++[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"++[[package]]+name = "ordered-stream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"+dependencies = [+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "parking"+version = "2.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall 0.5.18",+ "smallvec",+ "windows-link 0.2.1",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "pastey"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"++[[package]]+name = "pathfinder_geometry"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3"+dependencies = [+ "log",+ "pathfinder_simd",+]++[[package]]+name = "pathfinder_simd"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777"+dependencies = [+ "rustc_version",+]++[[package]]+name = "pbkdf2"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"+dependencies = [+ "digest 0.10.7",+ "hmac",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pico-args"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"++[[package]]+name = "pin-project"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pin-utils"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113"++[[package]]+name = "piper"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"+dependencies = [+ "atomic-waker",+ "fastrand 2.5.0",+ "futures-io",+]++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix 1.1.5",+ "windows-sys 0.61.2",+]++[[package]]+name = "pollster"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"++[[package]]+name = "postage"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1"+dependencies = [+ "atomic",+ "crossbeam-queue",+ "futures",+ "log",+ "parking_lot",+ "pin-project",+ "pollster",+ "static_assertions",+ "thiserror 1.0.69",+]++[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "prettyplease"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+dependencies = [+ "proc-macro2",+ "syn 2.0.119",+]++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit 0.25.16+spec-1.1.0",+]++[[package]]+name = "proc-macro-error-attr2"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"+dependencies = [+ "proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro-error2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"+dependencies = [+ "proc-macro-error-attr2",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"+dependencies = [+ "profiling-procmacros",+]++[[package]]+name = "profiling-procmacros"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "psm"+version = "0.1.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"+dependencies = [+ "ar_archive_writer",+ "cc",+]++[[package]]+name = "pulp"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a"+dependencies = [+ "bytemuck",+ "cfg-if",+ "libm",+ "num-complex",+ "paste",+ "pulp-wasm-simd-flag",+ "raw-cpuid",+ "reborrow",+ "version_check",+]++[[package]]+name = "pulp-wasm-simd-flag"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740"++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "qoi"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"+dependencies = [+ "bytemuck",+]++[[package]]+name = "quick-error"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"++[[package]]+name = "quick-xml"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"+dependencies = [+ "memchr",+]++[[package]]+name = "quinn"+version = "0.11.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash 2.1.3",+ "rustls",+ "socket2",+ "thiserror 2.0.21",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"+dependencies = [+ "aws-lc-rs",+ "bytes",+ "getrandom 0.4.3",+ "lru-slab",+ "rand 0.10.3",+ "rand_pcg",+ "ring",+ "rustc-hash 2.1.3",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror 2.0.21",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.61.2",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]++[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha 0.9.0",+ "rand_core 0.9.5",+]++[[package]]+name = "rand"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core 0.10.1",+]++[[package]]+name = "rangemap"+version = "1.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"++[[package]]+name = "rav1e"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"+dependencies = [+ "aligned-vec",+ "arbitrary",+ "arg_enum_proc_macro",+ "arrayvec",+ "av-scenechange",+ "av1-grain",+ "bitstream-io",+ "built",+ "cfg-if",+ "interpolate_name",+ "itertools 0.14.0",+ "libc",+ "libfuzzer-sys",+ "log",+ "maybe-rayon",+ "new_debug_unreachable",+ "noop_proc_macro",+ "num-derive",+ "num-traits",+ "paste",+ "profiling",+ "rand 0.9.5",+ "rand_chacha 0.9.0",+ "simd_helpers",+ "thiserror 2.0.21",+ "v_frame",+ "wasm-bindgen",+]++[[package]]+name = "ravif"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45"+dependencies = [+ "avif-serialize",+ "imgref",+ "loop9",+ "quick-error",+ "rav1e",+ "rayon",+ "rgb",+]++[[package]]+name = "raw-cpuid"+version = "11.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "raw-window-metal"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76e8caa82e31bb98fee12fa8f051c94a6aa36b07cddb03f0d4fc558988360ff1"+dependencies = [+ "cocoa 0.25.0",+ "core-graphics 0.23.2",+ "objc",+ "raw-window-handle",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "read-fonts"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"+dependencies = [+ "bytemuck",+ "font-types",+ "once_cell",+]++[[package]]+name = "reborrow"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"++[[package]]+name = "redox_syscall"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"+dependencies = [+ "bitflags 1.3.2",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "redox_users"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 1.0.69",+]++[[package]]+name = "redox_users"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"+dependencies = [+ "libredox",+ "thiserror 2.0.21",+]++[[package]]+name = "ref-cast"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"+dependencies = [+ "base64 0.23.1",+ "bytes",+ "encoding_rs",+ "futures-core",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "rustls-platform-verifier",+ "serde",+ "serde_json",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "resvg"+version = "0.45.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"+dependencies = [+ "log",+ "pico-args",+ "rgb",+ "svgtypes",+ "tiny-skia",+ "usvg",+]++[[package]]+name = "rgb"+version = "0.8.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"+dependencies = [+ "bytemuck",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "roxmltree"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"++[[package]]+name = "rust-embed"+version = "8.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23"+dependencies = [+ "rust-embed-impl",+ "rust-embed-utils",+ "walkdir",+]++[[package]]+name = "rust-embed-impl"+version = "8.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053"+dependencies = [+ "mime_guess",+ "proc-macro2",+ "quote",+ "rust-embed-utils",+ "syn 2.0.119",+ "walkdir",+]++[[package]]+name = "rust-embed-utils"+version = "8.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a"+dependencies = [+ "globset",+ "sha2 0.11.0",+ "walkdir",+]++[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "0.38.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustix"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.12.1",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"+dependencies = [+ "aws-lc-rs",+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]++[[package]]+name = "rustls-pemfile"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-platform-verifier"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"+dependencies = [+ "core-foundation 0.10.0",+ "core-foundation-sys",+ "jni",+ "log",+ "once_cell",+ "rustls",+ "rustls-native-certs",+ "rustls-platform-verifier-android",+ "rustls-webpki",+ "security-framework",+ "security-framework-sys",+ "webpki-root-certs",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls-platform-verifier-android"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"++[[package]]+name = "rustls-webpki"+version = "0.103.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"+dependencies = [+ "aws-lc-rs",+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "rustybuzz"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "libm",+ "smallvec",+ "ttf-parser 0.21.1",+ "unicode-bidi-mirroring 0.2.0",+ "unicode-ccc 0.2.0",+ "unicode-properties",+ "unicode-script",+]++[[package]]+name = "rustybuzz"+version = "0.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "core_maths",+ "log",+ "smallvec",+ "ttf-parser 0.25.1",+ "unicode-bidi-mirroring 0.4.0",+ "unicode-ccc 0.4.0",+ "unicode-properties",+ "unicode-script",+]++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "schannel"+version = "0.1.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "schemars"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"+dependencies = [+ "dyn-clone",+ "indexmap",+ "ref-cast",+ "schemars_derive",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98c67716b46af2f0b8cf752abc930f6f9aecfbf671ecfb531db8a31dbe4e2ba"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 3.0.6",+]++[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "screencapturekit"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a5eeeb57ac94960cfe5ff4c402be6585ae4c8d29a2cf41b276048c2e849d64e"+dependencies = [+ "screencapturekit-sys",+]++[[package]]+name = "screencapturekit-sys"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22411b57f7d49e7fe08025198813ee6fd65e1ee5eff4ebc7880c12c82bde4c60"+dependencies = [+ "block",+ "dispatch",+ "objc",+ "objc-foundation",+ "objc_id",+ "once_cell",+]++[[package]]+name = "seahash"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.10.0",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "self_cell"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_derive_internals"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_fmt"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e497af288b3b95d067a23a4f749f2861121ffcb2f6d8379310dcda040c345ed"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "indexmap",+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_json_lenient"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540"+dependencies = [+ "indexmap",+ "itoa",+ "memchr",+ "ryu",+ "serde",+]++[[package]]+name = "serde_repr"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_spanned"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"+dependencies = [+ "serde",+]++[[package]]+name = "serde_spanned"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "sha1_smol"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest 0.10.7",+]++[[package]]+name = "sha2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "digest 0.11.3",+]++[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "simd_cesu8"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"+dependencies = [+ "rustc_version",+ "simdutf8",+]++[[package]]+name = "simd_helpers"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"+dependencies = [+ "quote",+]++[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"++[[package]]+name = "simplecss"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"+dependencies = [+ "log",+]++[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"++[[package]]+name = "skrifa"+version = "0.44.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"+dependencies = [+ "bytemuck",+ "read-fonts",+]++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]++[[package]]+name = "smallvec"+version = "1.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"++[[package]]+name = "smol"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a33bd3e260892199c3ccfc487c88b2da2265080acb316cd920da72fdfd7c599f"+dependencies = [+ "async-channel 2.5.0",+ "async-executor",+ "async-fs",+ "async-io",+ "async-lock",+ "async-net",+ "async-process",+ "blocking",+ "futures-lite 2.6.1",+]++[[package]]+name = "smol_str"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"++[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "spin"+version = "0.9.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"+dependencies = [+ "lock_api",+]++[[package]]+name = "spirv"+version = "0.3.0+sdk-1.3.268.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "stacker"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"+dependencies = [+ "cc",+ "cfg-if",+ "libc",+ "psm",+ "windows-sys 0.61.2",+]++[[package]]+name = "stacksafe"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d9c1172965d317e87ddb6d364a040d958b40a1db82b6ef97da26253a8b3d090"+dependencies = [+ "stacker",+ "stacksafe-macro",+]++[[package]]+name = "stacksafe-macro"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "172175341049678163e979d9107ca3508046d4d2a7c6682bee46ac541b17db69"+dependencies = [+ "proc-macro-error2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"+dependencies = [+ "float-cmp",+]++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "strum"+version = "0.26.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"+dependencies = [+ "strum_macros 0.26.4",+]++[[package]]+name = "strum"+version = "0.27.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"+dependencies = [+ "strum_macros 0.27.2",+]++[[package]]+name = "strum_macros"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "rustversion",+ "syn 2.0.119",+]++[[package]]+name = "strum_macros"+version = "0.27.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "sval"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b81b254da21fe1fcc4e3a74fe39b46e25e3a863078f8b71c954d47f84889dbc6"++[[package]]+name = "sval_buffer"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50be352d2822ffafb59e3e2ddac9d5ee60f2eeadbb7b5a2a951b9f3651e87a6f"+dependencies = [+ "sval",+ "sval_ref",+ "zerocopy",+]++[[package]]+name = "sval_dynamic"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b048ca293b998d9a45659159f94a64063791e74cdc670164943dbb434405573d"+dependencies = [+ "sval",+]++[[package]]+name = "sval_fmt"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6b5888e40f80568733217f27b7317b845f463400ced36c424b1a804730e53b2"+dependencies = [+ "itoa",+ "ryu",+ "sval",+]++[[package]]+name = "sval_json"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17664d6bb6b74947afaab9d7c991caa9bf5638d4dee16fcbef637f440796049"+dependencies = [+ "itoa",+ "ryu",+ "sval",+]++[[package]]+name = "sval_nested"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07c059969ca5ca163ea7fef6c9661758973d17691aba92abdcf5c428f4ec122c"+dependencies = [+ "sval",+ "sval_buffer",+ "sval_ref",+]++[[package]]+name = "sval_ref"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42d6b29ff568c85c87561807f51d2adfff4b6016c6363133f7cd1652a12548f3"+dependencies = [+ "sval",+]++[[package]]+name = "sval_serde"+version = "2.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f33ec9edc42b12764d5c90ca0a1d84189c6bde81ed27507f1e661c6e4e05853"+dependencies = [+ "serde_core",+ "sval",+ "sval_nested",+]++[[package]]+name = "svg_fmt"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb"++[[package]]+name = "svgtypes"+version = "0.15.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"+dependencies = [+ "kurbo",+ "siphasher",+]++[[package]]+name = "swash"+version = "0.2.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e"+dependencies = [+ "skrifa",+ "yazi",+ "zeno",+]++[[package]]+name = "syn"+version = "1.0.109"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "sys-locale"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"+dependencies = [+ "libc",+]++[[package]]+name = "sysinfo"+version = "0.31.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "355dbe4f8799b304b05e1b0f05fc59b2a18d36645cf169607da45bde2f69a1be"+dependencies = [+ "core-foundation-sys",+ "libc",+ "memchr",+ "ntapi",+ "rayon",+ "windows 0.57.0",+]++[[package]]+name = "system-configuration"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.9.4",+ "system-configuration-sys",+]++[[package]]+name = "system-configuration"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.9.4",+ "system-configuration-sys",+]++[[package]]+name = "system-configuration-sys"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "taffy"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a13e5d13f79d558b5d353a98072ca8ca0e99da429467804de959aa8c83c9a004"+dependencies = [+ "arrayvec",+ "grid",+ "serde",+ "slotmap",+]++[[package]]+name = "take-until"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8bdb6fa0dfa67b38c1e66b7041ba9dcf23b99d8121907cd31c807a332f7a0bbb"++[[package]]+name = "tao-core-video-sys"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "271450eb289cb4d8d0720c6ce70c72c8c858c93dd61fc625881616752e6b98f6"+dependencies = [+ "cfg-if",+ "core-foundation-sys",+ "libc",+ "objc",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand 2.5.0",+ "getrandom 0.4.3",+ "once_cell",+ "rustix 1.1.5",+ "windows-sys 0.61.2",+]++[[package]]+name = "tendril"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"+dependencies = [+ "futf",+ "mac",+ "utf-8",+]++[[package]]+name = "termcolor"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+dependencies = [+ "winapi-util",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "thread_local"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"+dependencies = [+ "cfg-if",+]++[[package]]+name = "tiff"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"+dependencies = [+ "fax",+ "flate2",+ "half",+ "quick-error",+ "weezl",+ "zune-jpeg",+]++[[package]]+name = "tiny-keccak"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"+dependencies = [+ "crunchy",+]++[[package]]+name = "tiny-skia"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png 0.17.16",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]++[[package]]+name = "tinystr"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"++[[package]]+name = "tokio"+version = "1.53.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "parking_lot",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "tokio-rustls"+version = "0.26.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-socks"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7e2948f60dbe26b35f2c7fb74ac2854c1fddded0fe9d7548fcc674a246f7615"+dependencies = [+ "either",+ "futures-util",+ "thiserror 1.0.69",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "libc",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "toml"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"+dependencies = [+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.11",+ "toml_edit 0.22.27",+]++[[package]]+name = "toml"+version = "1.1.7+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7874cd34dd99040fc24e30923aa64a60a81ff3ddfe2b8129ccc84ba24949deed"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned 1.1.2",+ "toml_datetime 1.1.2+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.4",+]++[[package]]+name = "toml_datetime"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"+dependencies = [+ "serde",+]++[[package]]+name = "toml_datetime"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.22.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"+dependencies = [+ "indexmap",+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.11",+ "toml_write",+ "winnow 0.7.15",+]++[[package]]+name = "toml_edit"+version = "0.25.16+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88f38f3af8bf71841c67a990f4e2b52143b2d0a1a994c72513ff4c14977fc722"+dependencies = [+ "indexmap",+ "toml_datetime 1.1.2+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.4",+]++[[package]]+name = "toml_parser"+version = "1.1.4+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bed810ee007d8e7f9cf20b4774e7198142fa27186e0f805871da7f3c39eaf333"+dependencies = [+ "winnow 1.0.4",+]++[[package]]+name = "toml_write"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"++[[package]]+name = "toml_writer"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-http"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"+dependencies = [+ "bitflags 2.13.2",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+ "url",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+ "valuable",+]++[[package]]+name = "tracing-log"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"+dependencies = [+ "log",+ "once_cell",+ "tracing-core",+]++[[package]]+name = "tracing-subscriber"+version = "0.3.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"+dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex-automata",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing",+ "tracing-core",+ "tracing-log",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "ttf-parser"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4"++[[package]]+name = "ttf-parser"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"++[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+dependencies = [+ "core_maths",+]++[[package]]+name = "typeid"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "uds_windows"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"+dependencies = [+ "memoffset",+ "tempfile",+ "windows-sys 0.61.2",+]++[[package]]+name = "unicase"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"++[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"++[[package]]+name = "unicode-bidi-mirroring"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86"++[[package]]+name = "unicode-bidi-mirroring"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"++[[package]]+name = "unicode-ccc"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656"++[[package]]+name = "unicode-ccc"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"++[[package]]+name = "unicode-ident"+version = "1.0.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"++[[package]]+name = "unicode-linebreak"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"++[[package]]+name = "unicode-properties"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"++[[package]]+name = "unicode-script"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode-vo"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+ "serde_derive",+]++[[package]]+name = "usvg"+version = "0.45.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef"+dependencies = [+ "base64 0.22.1",+ "data-url",+ "flate2",+ "fontdb 0.23.0",+ "imagesize",+ "kurbo",+ "log",+ "pico-args",+ "roxmltree",+ "rustybuzz 0.20.1",+ "simplecss",+ "siphasher",+ "strict-num",+ "svgtypes",+ "tiny-skia-path",+ "unicode-bidi",+ "unicode-script",+ "unicode-vo",+ "xmlwriter",+]++[[package]]+name = "utf-8"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"++[[package]]+name = "uuid"+version = "1.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a"+dependencies = [+ "getrandom 0.4.3",+ "js-sys",+ "serde_core",+ "sha1_smol",+ "wasm-bindgen",+]++[[package]]+name = "v_frame"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"+dependencies = [+ "aligned-vec",+ "num-traits",+ "wasm-bindgen",+]++[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"++[[package]]+name = "value-bag"+version = "1.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2799ffb329a792ecfd902b71306c8a815a6ef1c0470fa9953a6aa4d4cecbe511"+dependencies = [+ "value-bag-serde1",+ "value-bag-sval2",+]++[[package]]+name = "value-bag-serde1"+version = "1.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0941feceafbe7a8f59ea1096d45b97002884a41306315ad797b3684b63a81d8c"+dependencies = [+ "erased-serde",+ "serde_core",+ "serde_fmt",+]++[[package]]+name = "value-bag-sval2"+version = "1.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "839752af8179287d27eb2b94164641b1ede9e60ab7424163388dc21ebd0508cd"+dependencies = [+ "sval",+ "sval_buffer",+ "sval_dynamic",+ "sval_fmt",+ "sval_json",+ "sval_ref",+ "sval_serde",+]++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "waker-fn"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.79"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "wayland-backend"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"+dependencies = [+ "cc",+ "downcast-rs",+ "rustix 1.1.5",+ "scoped-tls",+ "smallvec",+ "wayland-sys",+]++[[package]]+name = "wayland-client"+version = "0.31.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"+dependencies = [+ "bitflags 2.13.2",+ "rustix 1.1.5",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-cursor"+version = "0.31.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"+dependencies = [+ "rustix 1.1.5",+ "wayland-client",+ "xcursor",+]++[[package]]+name = "wayland-protocols"+version = "0.31.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f81f365b8b4a97f422ac0e8737c438024b5951734506b0e1d775c73030561f4"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols"+version = "0.32.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-plasma"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23803551115ff9ea9bce586860c5c5a971e360825a0309264102a9495a5ff479"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols 0.31.2",+ "wayland-scanner",+]++[[package]]+name = "wayland-scanner"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"+dependencies = [+ "proc-macro2",+ "quick-xml",+ "quote",+]++[[package]]+name = "wayland-sys"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"+dependencies = [+ "dlib",+ "log",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "web-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-root-certs"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"++[[package]]+name = "which"+version = "6.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"+dependencies = [+ "either",+ "home",+ "rustix 0.38.44",+ "winsafe",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "windows"+version = "0.57.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"+dependencies = [+ "windows-core 0.57.0",+ "windows-targets 0.52.6",+]++[[package]]+name = "windows"+version = "0.61.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"+dependencies = [+ "windows-collections",+ "windows-core 0.61.2",+ "windows-future",+ "windows-link 0.1.3",+ "windows-numerics",+]++[[package]]+name = "windows-capture"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a4df73e95feddb9ec1a7e9c2ca6323b8c97d5eeeff78d28f1eccdf19c882b24"+dependencies = [+ "parking_lot",+ "rayon",+ "thiserror 2.0.21",+ "windows 0.61.3",+ "windows-future",+]++[[package]]+name = "windows-collections"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"+dependencies = [+ "windows-core 0.61.2",+]++[[package]]+name = "windows-core"+version = "0.57.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d"+dependencies = [+ "windows-implement 0.57.0",+ "windows-interface 0.57.0",+ "windows-result 0.1.2",+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-core"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"+dependencies = [+ "windows-implement 0.60.2",+ "windows-interface 0.59.3",+ "windows-link 0.1.3",+ "windows-result 0.3.4",+ "windows-strings 0.4.2",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement 0.60.2",+ "windows-interface 0.59.3",+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]++[[package]]+name = "windows-future"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.57.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.57.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+]++[[package]]+name = "windows-registry"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4286ad90ddb45071efd1a66dfa43eb02dd0dfbae1545ad6cc3c51cf34d7e8ba3"+dependencies = [+ "windows-result 0.3.4",+ "windows-strings 0.3.1",+ "windows-targets 0.53.5",+]++[[package]]+name = "windows-registry"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"+dependencies = [+ "windows-link 0.1.3",+ "windows-result 0.3.4",+ "windows-strings 0.4.2",+]++[[package]]+name = "windows-registry"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"+dependencies = [+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]++[[package]]+name = "windows-result"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-result"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-strings"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-strings"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-sys"+version = "0.48.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"+dependencies = [+ "windows-targets 0.48.5",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-targets"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"+dependencies = [+ "windows_aarch64_gnullvm 0.48.5",+ "windows_aarch64_msvc 0.48.5",+ "windows_i686_gnu 0.48.5",+ "windows_i686_msvc 0.48.5",+ "windows_x86_64_gnu 0.48.5",+ "windows_x86_64_gnullvm 0.48.5",+ "windows_x86_64_msvc 0.48.5",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm 0.52.6",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-targets"+version = "0.53.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"+dependencies = [+ "windows-link 0.2.1",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",+]++[[package]]+name = "windows-threading"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"++[[package]]+name = "windows_aarch64_msvc"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_aarch64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"++[[package]]+name = "windows_i686_gnu"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"++[[package]]+name = "windows_i686_msvc"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_i686_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"++[[package]]+name = "windows_x86_64_gnu"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"++[[package]]+name = "windows_x86_64_msvc"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "windows_x86_64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"++[[package]]+name = "winnow"+version = "0.7.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"+dependencies = [+ "memchr",+]++[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+dependencies = [+ "memchr",+]++[[package]]+name = "winreg"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"+dependencies = [+ "cfg-if",+ "windows-sys 0.61.2",+]++[[package]]+name = "winsafe"+version = "0.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"++[[package]]+name = "wio"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5"+dependencies = [+ "winapi",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"++[[package]]+name = "x11"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"+dependencies = [+ "libc",+ "pkg-config",+]++[[package]]+name = "x11-clipboard"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "662d74b3d77e396b8e5beb00b9cad6a9eccf40b2ef68cc858784b14c41d535a3"+dependencies = [+ "libc",+ "x11rb",+]++[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "as-raw-xcb-connection",+ "gethostname",+ "libc",+ "rustix 1.1.5",+ "x11rb-protocol",+ "xcursor",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"++[[package]]+name = "xattr"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d1526bbe5aaeb5eb06885f4d987bcdfa5e23187055de9b83fe00156a821fabc"+dependencies = [+ "libc",+]++[[package]]+name = "xcb"+version = "1.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "quick-xml",+ "x11",+]++[[package]]+name = "xcursor"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"++[[package]]+name = "xim-ctext"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ac61a7062c40f3c37b6e82eeeef835d5cc7824b632a72784a89b3963c33284c"+dependencies = [+ "encoding_rs",+]++[[package]]+name = "xim-parser"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dcee45f89572d5a65180af3a84e7ddb24f5ea690a6d3aa9de231281544dd7b7"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "xkbcommon"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9"+dependencies = [+ "as-raw-xcb-connection",+ "libc",+ "memmap2",+ "xkeysym",+]++[[package]]+name = "xkeysym"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"++[[package]]+name = "xmlwriter"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"++[[package]]+name = "y4m"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"++[[package]]+name = "yazi"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"++[[package]]+name = "yeslogic-fontconfig-sys"+version = "6.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76"+dependencies = [+ "dlib",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zbus"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"+dependencies = [+ "async-broadcast",+ "async-executor",+ "async-io",+ "async-lock",+ "async-process",+ "async-recursion",+ "async-task",+ "async-trait",+ "blocking",+ "enumflags2",+ "event-listener 5.4.2",+ "futures-core",+ "futures-lite 2.6.1",+ "hex",+ "libc",+ "ordered-stream",+ "rustix 1.1.5",+ "serde",+ "serde_repr",+ "tracing",+ "uds_windows",+ "uuid",+ "windows-sys 0.61.2",+ "winnow 1.0.4",+ "zbus_macros",+ "zbus_names",+ "zvariant",+]++[[package]]+name = "zbus_macros"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "zbus_names",+ "zvariant",+ "zvariant_utils",+]++[[package]]+name = "zbus_names"+version = "4.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"+dependencies = [+ "serde",+ "winnow 1.0.4",+ "zvariant",+]++[[package]]+name = "zcheapstr"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"+dependencies = [+ "serde",+]++[[package]]+name = "zed-async-tar"+version = "0.5.0-zed"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6cf4b5f655e29700e473cb1acd914ab112b37b62f96f7e642d5fc6a0c02eb881"+dependencies = [+ "async-std",+ "filetime",+ "libc",+ "pin-project",+ "redox_syscall 0.2.16",+ "xattr",+]++[[package]]+name = "zed-font-kit"+version = "0.14.1-zed"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3898e450f36f852edda72e3f985c34426042c4951790b23b107f93394f9bff5"+dependencies = [+ "bitflags 2.13.2",+ "byteorder",+ "core-foundation 0.10.0",+ "core-graphics 0.24.0",+ "core-text",+ "dirs 5.0.1",+ "dwrote",+ "float-ord",+ "freetype-sys",+ "lazy_static",+ "libc",+ "log",+ "pathfinder_geometry",+ "pathfinder_simd",+ "walkdir",+ "winapi",+ "yeslogic-fontconfig-sys",+]++[[package]]+name = "zed-reqwest"+version = "0.12.15-zed"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac2d05756ff48539950c3282ad7acf3817ad3f08797c205ad1c34a2ce03b9970"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "encoding_rs",+ "futures-core",+ "futures-util",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "ipnet",+ "js-sys",+ "log",+ "mime",+ "mime_guess",+ "once_cell",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-native-certs",+ "rustls-pemfile",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "system-configuration 0.6.1",+ "tokio",+ "tokio-rustls",+ "tokio-socks",+ "tokio-util",+ "tower",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+ "windows-registry 0.4.0",+]++[[package]]+name = "zed-scap"+version = "0.0.8-zed"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6b338d705ae33a43ca00287c11129303a7a0aa57b101b72a1c08c863f698ac8"+dependencies = [+ "anyhow",+ "cocoa 0.25.0",+ "core-graphics-helmer-fork",+ "log",+ "objc",+ "rand 0.8.8",+ "screencapturekit",+ "screencapturekit-sys",+ "sysinfo",+ "tao-core-video-sys",+ "windows 0.61.3",+ "windows-capture",+ "x11",+ "xcb",+]++[[package]]+name = "zed-xim"+version = "0.4.0-zed"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c0b46ed118eba34d9ba53d94ddc0b665e0e06a2cf874cfa2dd5dec278148642"+dependencies = [+ "ahash",+ "hashbrown 0.14.5",+ "log",+ "x11rb",+ "xim-ctext",+ "xim-parser",+]++[[package]]+name = "zeno"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524"++[[package]]+name = "zerocopy"+version = "0.8.62"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.62"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-inflate"+version = "0.2.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]++[[package]]+name = "zvariant"+version = "5.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147"+dependencies = [+ "endi",+ "enumflags2",+ "serde",+ "url",+ "winnow 1.0.4",+ "zcheapstr",+ "zvariant_derive",+ "zvariant_utils",+]++[[package]]+name = "zvariant_derive"+version = "5.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "zvariant_utils",+]++[[package]]+name = "zvariant_utils"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"+dependencies = [+ "proc-macro2",+ "quote",+ "serde",+ "syn 3.0.6",+ "winnow 1.0.4",+]diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..d7cebb4--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,44 @@+[package]+name = "openrunner"+version = "0.1.0"+edition = "2024"+description = "A fast native dashboard for your fleet of self-hosted GitHub Actions runners, built with GPUI"+license = "LicenseRef-Proprietary"+publish = false+repository = "https://github.com/adibhanna/openrunner"+readme = "README.md"+keywords = ["github-actions", "self-hosted", "runners", "ci", "dashboard"]+categories = ["command-line-utilities", "development-tools"]++[dependencies]+anyhow = "1"+base64 = "0.22"+chrono = { version = "0.4", features = ["serde"] }+clap = { version = "4", features = ["derive", "env"] }+dirs = "7"+futures = "0.3"+gpui = { version = "0.2.2", optional = true }+reqwest = { version = "0.13", features = ["json"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+tokio = { version = "1", features = ["full"] }+toml = "1"+toml_edit = "0.25"+unicode-segmentation = { version = "1", optional = true }+tracing = "0.1"+tracing-subscriber = { version = "0.3", features = ["env-filter"] }++[target.'cfg(target_os = "macos")'.dependencies]+# Already part of GPUI's dependency tree; used to set the Dock icon when running+# the bare binary (an .app bundle gets it from its Info.plist instead).+cocoa = { version = "=0.26.0", optional = true }++[features]+default = ["gui"]+# The native window. Build with `--no-default-features` for a headless CLI + MCP+# server that needs no GUI libraries (Linux servers, CI, agent boxes).+gui = ["dep:gpui", "dep:unicode-segmentation", "dep:cocoa"]++[profile.release]+lto = "thin"+strip = truediff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d841651--- /dev/null+++ b/LICENSE@@ -0,0 +1,9 @@+Copyright (c) 2026 Adib Hanna. All rights reserved.++This software and its source code are proprietary and confidential. No part of+it may be copied, modified, distributed, sublicensed or used, in whole or in+part, except under the terms of a separate written license agreement with the+copyright holder.++Third-party components included with this software are licensed under their+own terms; see THIRD_PARTY_NOTICES.md.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..391b9bf--- /dev/null+++ b/README.md@@ -0,0 +1,284 @@+# OpenRunner++A fast, native dashboard for your own fleet of self-hosted GitHub Actions runners, built to be run by you **or by your AI agents**.++Point it at the machines you own (a Mac Studio under the desk, a NUC, a Linux box, a Windows laptop) and OpenRunner shows:++- which runners are working, idle or offline;+- what each machine's CPU, memory, disk and uptime look like;+- which jobs are queued, and which of them no runner can take.++It can also set the machines up. It installs runners, registers them with GitHub, and can start, stop, restart, inspect or remove them.++And it lets agents **borrow a machine as a work environment**: an [agent workspace](#agent-workspaces) is a persistent folder (optionally a git checkout) on one of your machines where an agent runs commands, edits files and syncs code.++- **Native and fast.** The window is built with [GPUI](https://www.gpui.rs), the GPU-accelerated UI framework behind the Zed editor. It runs on macOS, Linux and Windows.+- **Agent-first.** Every capability is available as an MCP server (`openrunner mcp`) and as scriptable commands with `--json`. Claude Code, Codex and other agents can check the fleet, explain problems and fix them.+- **Uses what you already have.** Machines are reached with your system `ssh`, so your keys, agent and `~/.ssh/config` aliases just work. GitHub access uses your `gh` login.++## Install++```sh+git clone https://github.com/adibhanna/openrunner && cd openrunner+cargo build --release+./target/release/openrunner # opens the window+```++Requirements:++- A recent stable Rust (edition 2024).+- On macOS, Xcode (GPUI compiles Metal shaders).+- On Linux, GPUI's system libraries. On Ubuntu/Debian:+ `sudo apt install libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev libvulkan-dev libfontconfig-dev libx11-xcb-dev libxcb1-dev`.++For servers, CI boxes and agent machines there's a headless build with no GUI libraries: just the CLI and the MCP server.++```sh+cargo build --release --no-default-features+```++There's nothing else to set up. Fonts and icons are compiled into the binary.++To get a real app with the OpenRunner icon:++- **macOS:** `./scripts/bundle-macos.sh` builds `dist/OpenRunner.app` (ad-hoc signed). Drag it to Applications. Agents can still use the binary inside it: `OpenRunner.app/Contents/MacOS/openrunner mcp`.+- **Linux:** install `assets/linux/openrunner.desktop` and `assets/brand/icon-512.png` (as `openrunner.png`).+- **Windows:** the icon is `assets/brand/openrunner.ico`.++## Quick start++```sh+openrunner --demo # explore a simulated fleet first; nothing real is touched+openrunner # your fleet: starts with this computer in fleet.toml+openrunner add-machine --name "Mac Studio" --host [email protected]+openrunner watch acme # live runner status and jobs for the acme org+openrunner install mac-studio --count 2 # two runners, registered with acme, as services+openrunner status+```++## The app++- **Overview:** a *fleet pulse* chart of how busy your online runners are, counts of working, idle, offline and queued, what needs attention (with a button that fixes or explains each item), and a card per machine with live CPU, memory and disk.+- **Machines and runners:** install runners on a machine, and start, stop, restart, show logs for or remove each one.+- **Activity (⌘J):** one timeline of everything happening on the fleet: operations started in the app (with live output) and every command agents ran in workspaces, filterable by kind or failures.+- **Workspaces:** see what agents are doing on your machines (every command, its exit code and output), review a workspace's git changes, copy a shell command to step in, or destroy it.+- **Jobs:** queued and running self-hosted jobs, and which queued jobs no online runner can take.+- **Appearance:** follow the system, or pin light or dark, each with its own theme. Built-in themes:+ - dark: OpenRunner Graphite, macOS Dark, Gruvbox Dark, Catppuccin Mocha / Macchiato / Frappé, Tokyo Night, Nord, Rosé Pine, Solarized Dark, Dracula, Everforest Dark, Kanagawa Wave, GitHub Dark;+ - light: OpenRunner Paper, macOS Light, Gruvbox Light, Catppuccin Latte, Tokyo Night Day, Nord Light, Rosé Pine Dawn, Solarized Light, Everforest Light, Kanagawa Lotus, GitHub Light.++ The macOS themes also switch to the system fonts (SF Pro, and SF Mono when it's installed). The choice is saved in `ui.json` next to `fleet.toml`.++Keyboard: ⌘R check now · ⇧⌘R sync GitHub · ⌘N add machine · ⌘1 / ⌘2 overview / jobs · ⌘F or `/` search the fleet · ⌘J activity · ⌘[ / ⌘] back / forward · ⌘, settings. On Linux and Windows, use Ctrl instead of ⌘.++## The inventory: `fleet.toml`++OpenRunner keeps its files in `~/.config/openrunner/`, or in `$OPENRUNNER_HOME` if that's set. Run `openrunner paths` to see where they are.++- `fleet.toml` lists your machines. You can edit it by hand. OpenRunner also edits it when you add machines or install runners, and keeps your comments when it does.+- `settings.json` holds the watched GitHub orgs and repos, and the polling intervals.+- `state.json` holds the last machine check.++```toml+[[machine]]+name = "Mac Studio"+host = "[email protected]" # anything `ssh` accepts, or "local" for this computer+runners = ["mac-studio-01", "mac-studio-02"] # expected runners; missing ones are flagged+# runner_dirs = ["/Volumes/Fast/runners/*"] # extra places to look (globs)+# shell = "powershell" # Windows; auto-detected when omitted+# user = "ci" port = 2222 ssh_options = ["-i", "~/.ssh/ci"]+# discover = false # don't list runners found but not declared+# notes = "Under the desk"++[[machine]]+name = "StudioNAS" # no runners: shown under "Other machines"+host = "nas"+```++Runners installed in the usual places are discovered automatically: `~/actions-runner*`, `~/actions-runner/*`, `~/runners/*`, `/opt/actions-runner*` and `C:\actions-runner\*`. A runner is found from its `.runner` file and its running `Runner.Listener` / `Runner.Worker` processes.++## GitHub++Watch an org or a repo in Settings, or with `openrunner watch acme` (or `acme/api`). OpenRunner then reads live runner status (online, busy) and the queued and running jobs of the most recently pushed repos.++The token comes from `OPENRUNNER_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, or `gh auth token`. Polling uses conditional requests, so unchanged responses don't count against your rate limit.++Reading and registering **org** runners needs an org admin token with the `admin:org` scope:++```sh+gh auth refresh -h github.com -s admin:org+```++Repo runners need admin access to the repo. For GitHub Enterprise Server, set the API URL in Settings or run `openrunner settings --api-url https://HOST/api/v3`.++## Use it from AI agents++OpenRunner ships an [MCP](https://modelcontextprotocol.io) server. Print setup snippets that point at your binary:++```sh+openrunner mcp --print-config+```++**Claude Code**++```sh+claude mcp add openrunner -- /path/to/openrunner mcp+```++**Codex** (`~/.codex/config.toml`)++```toml+[mcp_servers.openrunner]+command = "/path/to/openrunner"+args = ["mcp"]+```++**Other MCP clients** (Claude Desktop, Cursor, …)++```json+{ "mcpServers": { "openrunner": { "command": "/path/to/openrunner", "args": ["mcp"] } } }+```++Add `"--demo"` after `"mcp"` to let an agent practice on the simulated fleet.++The MCP server has these tools:++| Tool | What it does |+| --- | --- |+| `fleet_status` | Counts, GitHub state, every machine, and the `attention` list. Start here. |+| `get_machine` | One machine's resources, runners and diagnostics, with hints. |+| `list_runners` | Runners, optionally filtered by machine or state. |+| `list_jobs` | Queued and running jobs, including which ones no runner can take. |+| `check_machines` | Runs the read-only machine check over ssh now. |+| `add_machine`, `remove_machine` | Edit `fleet.toml`. Nothing on the machine changes. |+| `install_runners` | Downloads, registers and starts runners on a machine. |+| `runner_action` | Starts, stops, restarts or removes a runner, or reads its logs. |+| `get_operation`, `list_operations` | Progress and output of long operations. |+| `github_scopes` | Watches or unwatches orgs and repos, with access checks. |+| `get_settings`, `update_settings`, `list_ssh_hosts` | Settings, and the hosts from your `~/.ssh/config`. |+| `workspace_create`, `workspace_list`, `workspace_get` | Check out a machine as a work environment; see what exists. |+| `workspace_exec` | Runs a command in a workspace (or starts it in the background). |+| `workspace_read_file`, `workspace_write_file`, `workspace_list_files` | Work with a workspace's files. |+| `workspace_changes`, `workspace_sync` | Review the git diff; rsync code to or from your local checkout. |+| `workspace_destroy`, `workspace_allow` | Clean up; turn workspaces on or off for a machine. |++Every tool returns structured JSON. Failures come back with a `code` an agent can branch on:++- `not_found`+- `invalid`+- `busy`+- `github`+- `unreachable`+- `operation_failed`+- `internal`++Many failures also include a `hint` with the exact command that fixes them. [AGENTS.md](AGENTS.md) has guidance written for agents.++### The CLI, for scripts and agents without MCP++Every command takes `--json`. In that mode stdout carries JSON only, and errors are printed as `{"error": {...}}`. Progress and logs go to stderr. Exit codes:++- `0`: success.+- `1`: the operation failed.+- `2`: bad input, or the thing wasn't found.++```sh+openrunner status [--refresh] # overview + what needs attention+openrunner machines | machine <id>+openrunner runners [--machine <id>] [--state offline]+openrunner jobs+openrunner add-machine --name <name> --host <ssh-host> [--no-check]+openrunner remove-machine <id>+openrunner install <machine-id> [--scope acme] [--count N | --name a --name b] [--label gpu] [--mode auto|service|background|docker] [--image IMAGE] [--docker-socket] [--no-wait]+openrunner runner <start|stop|restart|logs|remove> <runner-id> [--delete-files]+openrunner watch <org|owner/repo>... / unwatch ...+openrunner settings [--poll 20] [--scan-repos 10] [--check-interval 15]+openrunner ssh-hosts+openrunner check [--json] # one-shot full report+openrunner workspace … # agent workspaces, see below (alias: ws)+```++Ids:++- Machines are slugs of their names, such as `mac-studio`.+- Runners are `<machine-id>/<runner-name>`, such as `mac-studio/mac-studio-01`.+- A runner that GitHub knows but no machine lists is `github/<name>`.++Every command also accepts `--demo`.++The window, the CLI and MCP servers can all run at once. They share the files in the config directory and pick up each other's changes: settings, edits to `fleet.toml`, and newer machine checks.++## Agent workspaces++Think of [Amp's Orbs](https://ampcode.com/news/agents-in-orbs), but on your own hardware. An agent asks for a workspace and gets a persistent folder on one of your machines, optionally with a repo cloned at a branch or ref. It then works there like it would on a remote dev box:++- **Run commands** with your login environment (Homebrew, nvm, asdf and the rest of your `PATH`). Long-running things such as dev servers go in the background, with their output in a log file inside the workspace.+- **Read, write and list files.**+- **Review** with `git status` and the diff.+- **Sync code** both ways with your local checkout over rsync: push uncommitted local changes to test them on Linux, pull a fix back.++**Host or Docker.** By default commands run directly on the machine. With `isolation: "docker"` (CLI `--docker`), each workspace gets its own fresh container instead, from an image the agent picks (`node:22`, `python:3.13`, `rust:1`, …; default `buildpack-deps:bookworm`). The workspace folder is mounted at `/workspace`, the container runs as the ssh user so files aren't root-owned, and a container that disappears (reboot, `docker system prune`) is recreated on the next command with the files intact. `docker_socket` shares the machine's Docker for docker-in-docker; that's root-equivalent, so only use it when the task needs it. Docker workspaces need Docker on the machine and the ssh user in the `docker` group. They aren't available on Windows machines yet.++The machine can be named, or picked for you: the least-loaded online machine that allows workspaces, optionally matching a platform such as `linux` or `darwin-arm64`. Private GitHub repos are cloned with your `gh` login; the token is passed through the environment for that one command and never written to disk or logs.++Every command an agent runs is recorded with its exit code, duration and the end of its output. You can see that history in the app's Workspaces page, or open a terminal in any workspace with `openrunner workspace shell <id>`.++```sh+openrunner ws create --platform linux --repo acme/api --ref main+openrunner ws create --docker --image node:22 --repo acme/web # an isolated container+openrunner ws exec ws-7f3a2c -- cargo test # exits with the command's exit code+openrunner ws exec ws-7f3a2c --background -- npm run dev+openrunner ws cat ws-7f3a2c .openrunner/logs/1.log+echo 'hello' | openrunner ws write ws-7f3a2c notes.txt+openrunner ws files ws-7f3a2c src --depth 1+openrunner ws changes ws-7f3a2c+openrunner ws sync ws-7f3a2c ~/code/api --push # or --pull, add --delete to mirror deletions+openrunner ws shell ws-7f3a2c # an interactive shell in the workspace, for you+openrunner ws ls+openrunner ws rm ws-7f3a2c [--keep-files]+openrunner ws allow studionas --off # forbid workspaces on a machine+```++`ws exec` passes the command's stdout and stderr through and exits with its exit code (124 if it timed out), so it composes in scripts. With `--json` it prints the full result instead.++**Safety.** Host workspace commands run as the ssh user on your machine, with that user's permissions; they aren't sandboxed. Use Docker isolation for code you don't trust. Workspaces are on by default for every machine with a host. Turn them off per machine with `workspaces = false` in `fleet.toml`, the toggle on the machine's page in the app, or `openrunner workspace allow <machine> --off`. Nothing is deleted automatically: workspaces stay until you or an agent destroys them. Folders live under `~/openrunner/workspaces/<id>` on each machine (`workspace_root` in `fleet.toml` changes that).++## How checks and installs work++- **Checks are read-only.** A small script is sent over `ssh` (`sh` on macOS and Linux, PowerShell on Windows), or run directly for `host = "local"`. It reports CPU, memory, disk, uptime and load, and finds the installed runners, their versions, their services and whether they're running. Checks run on a schedule (every 15 minutes by default) or on request.+- **Installs only happen when you ask.** OpenRunner checks the machine, gets a short-lived registration token from GitHub, and installs each runner in one of these modes (`--mode` / `mode`, default `auto`):+ - **service:** downloads the latest `actions-runner` for the machine's platform into `~/actions-runner/<name>`, runs `config.sh --unattended`, and installs a service: launchd on macOS (the user must be logged in), systemd on Linux (needs **passwordless sudo** for `svc.sh`), a Windows service on Windows.+ - **docker:** one container per runner, `openrunner-<name>`, from GitHub's official image (`ghcr.io/actions/actions-runner:<latest runner version>`, or `--image`). The runner's files live in a named volume of the same name, registration happens in a throwaway container that reads the token from stdin (so it never shows up in `docker inspect` or a process list), and the container runs with `--restart unless-stopped`, so it comes back with the Docker daemon. No sudo needed; the user just has to be in the `docker` group. The runners get the `docker` label, and jobs run in a clean Ubuntu userland. `--docker-socket` shares the host's Docker socket so jobs can use Docker; that's root-equivalent access to the machine, so only use it for trusted workflows.+ - **background:** `run.sh` started with `nohup`; no root needed, but it doesn't come back after a reboot (`--no-service` is the same).+ - **auto** picks service when the machine allows it (macOS, Windows, Linux with passwordless sudo or as root), else docker when Docker is usable, else background, and says which it picked in the operation log.+- **Remove** stops the runner, uninstalls its service (or removes its container) and deregisters it with a removal token. It deletes the folder (or the container's volume) only if you ask.+- Docker runners show up in checks with their container's state; a container that keeps restarting is flagged with the `docker logs` command to look at.+- Registration and removal tokens are masked in all output and never logged.+- `ssh` runs with `BatchMode=yes`, so a machine that needs a password just shows up as unreachable. Make sure `ssh <host>` works with keys first.++## Develop++```sh+cargo test # unit + demo-mode integration tests+cargo run -- --demo # the window, simulated fleet+cargo run -- status --demo --json+```++Source layout:++- `src/fleet`: the engine and snapshot model.+- `src/probe`: machine checks.+- `src/github`: the GitHub API client.+- `src/ops`: installs and runner control.+- `src/fleet/workspaces/`: agent workspaces (host and Docker).+- `src/api.rs`: the agent API.+- `src/mcp.rs`: the MCP server.+- `src/ui`: the GPUI window.++`Cargo.lock` pins `libc` to 0.2.189: GPUI's HTTP client pulls in `xattr` 0.2, which doesn't build on Linux against newer `libc` releases. Don't run a blanket `cargo update` without rebuilding on Linux.++## License++Copyright © 2026 Adib Hanna. All rights reserved. OpenRunner is proprietary software; see `LICENSE`.++It includes third-party components under their own licenses, listed in `THIRD_PARTY_NOTICES.md`: the Geist fonts (SIL Open Font License, `assets/fonts/OFL.txt`), the Lucide icons (ISC, `assets/icons/LICENSE.txt`), GPUI (Apache-2.0) and the Rust crates in `Cargo.lock`.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..25800f3--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,14 @@+# Third-party notices++OpenRunner includes the following third-party components. Their licenses+must ship with every copy of OpenRunner.++| Component | License | Notice |+|---|---|---|+| Geist and Geist Mono fonts (Vercel) | SIL Open Font License 1.1 | `assets/fonts/OFL.txt` |+| Lucide icons | ISC | `assets/icons/LICENSE.txt` |+| GPUI (Zed Industries) | Apache-2.0 | <https://github.com/zed-industries/zed> |+| Rust crates listed in `Cargo.lock` | MIT and/or Apache-2.0 (mostly), see each crate | Generate the full list before each release, e.g. with `cargo about generate` |++Before shipping a release, regenerate the crate list and include the license+texts in the app bundle (for example `OpenRunner.app/Contents/Resources/`).diff --git a/assets/brand/OpenRunner.icns b/assets/brand/OpenRunner.icnsnew file mode 100644index 0000000..109ce35Binary files /dev/null and b/assets/brand/OpenRunner.icns differdiff --git a/assets/brand/icon-128.png b/assets/brand/icon-128.pngnew file mode 100644index 0000000..2a717b8Binary files /dev/null and b/assets/brand/icon-128.png differdiff --git a/assets/brand/icon-512.png b/assets/brand/icon-512.pngnew file mode 100644index 0000000..8972011Binary files /dev/null and b/assets/brand/icon-512.png differdiff --git a/assets/brand/icon.svg b/assets/brand/icon.svgnew file mode 100644index 0000000..74cc337--- /dev/null+++ b/assets/brand/icon.svg@@ -0,0 +1,88 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">+ <!-- OpenRunner app icon: an original cartoon roadrunner sprinting across a sunset. -->+ <defs>+ <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#6f5cff"/>+ <stop offset="0.55" stop-color="#b373ff"/>+ <stop offset="1" stop-color="#ff9d63"/>+ </linearGradient>+ <linearGradient id="body" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#3a2fb0"/>+ <stop offset="1" stop-color="#241b7a"/>+ </linearGradient>+ <clipPath id="tile"><rect x="100" y="100" width="824" height="824" rx="185"/></clipPath>+ </defs>++ <g clip-path="url(#tile)">+ <rect x="100" y="100" width="824" height="824" fill="url(#sky)"/>+ <!-- sun and desert -->+ <circle cx="745" cy="455" r="170" fill="#ffd98c" opacity="0.55"/>+ <path d="M100 760 C 260 720, 420 745, 560 728 C 700 712, 820 735, 924 720 L 924 924 L 100 924 Z" fill="#ff8a57" opacity="0.65"/>+ <path d="M100 820 C 300 790, 520 812, 700 796 C 800 788, 870 795, 924 790 L 924 924 L 100 924 Z" fill="#f2703f" opacity="0.7"/>+ <ellipse cx="520" cy="782" rx="200" ry="18" fill="#3a1d55" opacity="0.25"/>++ <g transform="translate(70 92) scale(0.85)">+ <!-- speed lines -->+ <g stroke="#ffffff" stroke-linecap="round" opacity="0.85">+ <line x1="150" y1="590" x2="285" y2="590" stroke-width="20"/>+ <line x1="120" y1="650" x2="300" y2="650" stroke-width="20"/>+ <line x1="175" y1="710" x2="310" y2="710" stroke-width="20"/>+ </g>++ <!-- dust -->+ <g fill="#fff6ec">+ <circle cx="315" cy="792" r="40"/>+ <circle cx="262" cy="808" r="30"/>+ <circle cx="368" cy="810" r="27"/>+ <circle cx="218" cy="818" r="18"/>+ </g>++ <g stroke="#160f3d" stroke-width="14" stroke-linejoin="round" stroke-linecap="round">+ <!-- back leg, pushing off -->+ <path d="M470 640 L 430 728 L 345 772" fill="none" stroke-width="40"/>+ <path d="M470 640 L 430 728 L 345 772" fill="none" stroke="#ff8a2a" stroke-width="22"/>+ <path d="M345 772 L 300 760 M345 772 L 306 790 M345 772 L 330 806" fill="none" stroke-width="30"/>+ <path d="M345 772 L 300 760 M345 772 L 306 790 M345 772 L 330 806" fill="none" stroke="#ff8a2a" stroke-width="14"/>++ <!-- tail -->+ <path d="M392 548 C 318 520, 250 470, 170 392 C 214 404, 236 420, 252 436 C 238 410, 232 392, 230 370 C 290 430, 350 480, 420 520 Z" fill="url(#body)"/>+ <path d="M402 600 C 320 590, 250 560, 188 520 C 250 528, 330 540, 410 566 Z" fill="#4b3fd1"/>++ <!-- body -->+ <ellipse cx="505" cy="565" rx="152" ry="102" transform="rotate(-18 505 565)" fill="url(#body)"/>+ <ellipse cx="540" cy="612" rx="100" ry="50" transform="rotate(-18 540 612)" fill="#ece7ff" stroke="none"/>++ <!-- front leg, reaching forward -->+ <path d="M560 640 L 628 718 L 712 742" fill="none" stroke-width="40"/>+ <path d="M560 640 L 628 718 L 712 742" fill="none" stroke="#ff8a2a" stroke-width="22"/>+ <path d="M712 742 L 760 730 M712 742 L 762 754 M712 742 L 748 778" fill="none" stroke-width="30"/>+ <path d="M712 742 L 760 730 M712 742 L 762 754 M712 742 L 748 778" fill="none" stroke="#ff8a2a" stroke-width="14"/>++ <!-- wing, swept back -->+ <path d="M520 520 C 470 470, 395 438, 318 440 C 352 462, 372 478, 384 494 C 356 494, 336 500, 318 512 C 380 530, 440 560, 490 590 Z" fill="#5a4de6"/>++ <!-- neck -->+ <path d="M556 532 C 566 456, 606 396, 656 352 L 742 382 C 700 418, 676 470, 668 556 Z" fill="url(#body)"/>+ <path d="M700 410 C 684 446, 674 488, 668 530" fill="none" stroke="#ece7ff" stroke-width="20" stroke-linecap="round" stroke-opacity="0.9"/>++ <!-- crest -->+ <path d="M648 268 C 596 214, 552 186, 488 176 C 548 214, 580 252, 616 300 Z" fill="#2a2090"/>+ <path d="M672 254 C 642 186, 618 146, 572 112 C 636 144, 682 194, 706 248 Z" fill="#3a2fb0"/>+ <path d="M704 248 C 708 186, 698 144, 676 102 C 732 146, 748 200, 738 256 Z" fill="#5a4de6"/>++ <!-- head -->+ <circle cx="700" cy="322" r="88" fill="url(#body)"/>++ <!-- beak -->+ <path d="M770 300 L 930 330 L 770 352 Z" fill="#ffc93c"/>+ <path d="M766 346 L 900 350 L 762 372 Z" fill="#ffb21e"/>++ <!-- eye and brow -->+ <ellipse cx="724" cy="300" rx="36" ry="42" fill="#ffffff"/>+ <circle cx="738" cy="306" r="16" fill="#160f3d" stroke="none"/>+ <circle cx="744" cy="298" r="5.5" fill="#ffffff" stroke="none"/>+ <path d="M684 252 Q 720 238 760 258" fill="none" stroke-width="12"/>+ </g>+ </g>+ </g>+</svg>diff --git a/assets/brand/openrunner.ico b/assets/brand/openrunner.iconew file mode 100644index 0000000..b1edfaeBinary files /dev/null and b/assets/brand/openrunner.ico differdiff --git a/assets/fonts/OFL.txt b/assets/fonts/OFL.txtnew file mode 100644index 0000000..04e95fc--- /dev/null+++ b/assets/fonts/OFL.txt@@ -0,0 +1,93 @@+Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.\ No newline at end of filediff --git a/assets/fonts/geist-400.ttf b/assets/fonts/geist-400.ttfnew file mode 100644index 0000000..9ee626bBinary files /dev/null and b/assets/fonts/geist-400.ttf differdiff --git a/assets/fonts/geist-500.ttf b/assets/fonts/geist-500.ttfnew file mode 100644index 0000000..8f5e69eBinary files /dev/null and b/assets/fonts/geist-500.ttf differdiff --git a/assets/fonts/geist-600.ttf b/assets/fonts/geist-600.ttfnew file mode 100644index 0000000..a855683Binary files /dev/null and b/assets/fonts/geist-600.ttf differdiff --git a/assets/fonts/geist-mono-400.ttf b/assets/fonts/geist-mono-400.ttfnew file mode 100644index 0000000..2b3e12bBinary files /dev/null and b/assets/fonts/geist-mono-400.ttf differdiff --git a/assets/fonts/geist-mono-500.ttf b/assets/fonts/geist-mono-500.ttfnew file mode 100644index 0000000..089a375Binary files /dev/null and b/assets/fonts/geist-mono-500.ttf differdiff --git a/assets/icons/LICENSE.txt b/assets/icons/LICENSE.txtnew file mode 100644index 0000000..718bb3f--- /dev/null+++ b/assets/icons/LICENSE.txt@@ -0,0 +1,43 @@+ISC License++Copyright (c) 2026 Lucide Icons and Contributors++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++---++The following Lucide icons are derived from the Feather project:++airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out++The MIT License (MIT) (for the icons listed above)++Copyright (c) 2013-present Cole Bemis++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/assets/icons/activity.svg b/assets/icons/activity.svgnew file mode 100644index 0000000..486f8ec--- /dev/null+++ b/assets/icons/activity.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-activity"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" />+</svg>diff --git a/assets/icons/arrow-left.svg b/assets/icons/arrow-left.svgnew file mode 100644index 0000000..4e840a3--- /dev/null+++ b/assets/icons/arrow-left.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-arrow-left"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m12 19-7-7 7-7" />+ <path d="M19 12H5" />+</svg>diff --git a/assets/icons/arrow-right.svg b/assets/icons/arrow-right.svgnew file mode 100644index 0000000..c22f33a--- /dev/null+++ b/assets/icons/arrow-right.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-arrow-right"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M5 12h14" />+ <path d="m12 5 7 7-7 7" />+</svg>diff --git a/assets/icons/box.svg b/assets/icons/box.svgnew file mode 100644index 0000000..232c048--- /dev/null+++ b/assets/icons/box.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-box"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z" />+ <path d="m3.3 7 8.7 5 8.7-5" />+ <path d="M12 22V12" />+</svg>diff --git a/assets/icons/check.svg b/assets/icons/check.svgnew file mode 100644index 0000000..8e6d47c--- /dev/null+++ b/assets/icons/check.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-check"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M20 6 9 17l-5-5" />+</svg>diff --git a/assets/icons/chevron-down.svg b/assets/icons/chevron-down.svgnew file mode 100644index 0000000..7611370--- /dev/null+++ b/assets/icons/chevron-down.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-chevron-down"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m6 9 6 6 6-6" />+</svg>diff --git a/assets/icons/chevron-right.svg b/assets/icons/chevron-right.svgnew file mode 100644index 0000000..881629d--- /dev/null+++ b/assets/icons/chevron-right.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-chevron-right"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m9 18 6-6-6-6" />+</svg>diff --git a/assets/icons/circle-alert.svg b/assets/icons/circle-alert.svgnew file mode 100644index 0000000..3822f66--- /dev/null+++ b/assets/icons/circle-alert.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-circle-alert"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+ <line x1="12" x2="12" y1="8" y2="12" />+ <line x1="12" x2="12.01" y1="16" y2="16" />+</svg>diff --git a/assets/icons/circle-check.svg b/assets/icons/circle-check.svgnew file mode 100644index 0000000..6298f1c--- /dev/null+++ b/assets/icons/circle-check.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-circle-check"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+ <path d="m16 9-5.5 5.5L8 12" />+</svg>diff --git a/assets/icons/circle-x.svg b/assets/icons/circle-x.svgnew file mode 100644index 0000000..e0e55bf--- /dev/null+++ b/assets/icons/circle-x.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-circle-x"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+ <path d="m15 9-6 6" />+ <path d="m9 9 6 6" />+</svg>diff --git a/assets/icons/circle.svg b/assets/icons/circle.svgnew file mode 100644index 0000000..ee94cb5--- /dev/null+++ b/assets/icons/circle.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-circle"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+</svg>diff --git a/assets/icons/clock.svg b/assets/icons/clock.svgnew file mode 100644index 0000000..80e794a--- /dev/null+++ b/assets/icons/clock.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-clock"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+ <path d="M12 6v6l4 2" />+</svg>diff --git a/assets/icons/copy.svg b/assets/icons/copy.svgnew file mode 100644index 0000000..87ccb1f--- /dev/null+++ b/assets/icons/copy.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-copy"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />+ <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />+</svg>diff --git a/assets/icons/cpu.svg b/assets/icons/cpu.svgnew file mode 100644index 0000000..c687f80--- /dev/null+++ b/assets/icons/cpu.svg@@ -0,0 +1,28 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-cpu"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12 20v2" />+ <path d="M12 2v2" />+ <path d="M17 20v2" />+ <path d="M17 2v2" />+ <path d="M2 12h2" />+ <path d="M2 17h2" />+ <path d="M2 7h2" />+ <path d="M20 12h2" />+ <path d="M20 17h2" />+ <path d="M20 7h2" />+ <path d="M7 20v2" />+ <path d="M7 2v2" />+ <rect x="4" y="4" width="16" height="16" rx="2" />+ <rect x="8" y="8" width="8" height="8" rx="1" />+</svg>diff --git a/assets/icons/ellipsis.svg b/assets/icons/ellipsis.svgnew file mode 100644index 0000000..2afb68c--- /dev/null+++ b/assets/icons/ellipsis.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-ellipsis"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="1" />+ <circle cx="19" cy="12" r="1" />+ <circle cx="5" cy="12" r="1" />+</svg>diff --git a/assets/icons/external-link.svg b/assets/icons/external-link.svgnew file mode 100644index 0000000..69e8892--- /dev/null+++ b/assets/icons/external-link.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-external-link"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15 3h6v6" />+ <path d="M10 14 21 3" />+ <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />+</svg>diff --git a/assets/icons/folder-open.svg b/assets/icons/folder-open.svgnew file mode 100644index 0000000..92e830e--- /dev/null+++ b/assets/icons/folder-open.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-folder-open"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2" />+</svg>diff --git a/assets/icons/gauge.svg b/assets/icons/gauge.svgnew file mode 100644index 0000000..1116133--- /dev/null+++ b/assets/icons/gauge.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-gauge"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m12 14 4-4" />+ <path d="M3.34 19a10 10 0 1 1 17.32 0" />+</svg>diff --git a/assets/icons/git-branch.svg b/assets/icons/git-branch.svgnew file mode 100644index 0000000..f30b7af--- /dev/null+++ b/assets/icons/git-branch.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-git-branch"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15 6a9 9 0 0 0-9 9V3" />+ <circle cx="18" cy="6" r="3" />+ <circle cx="6" cy="18" r="3" />+</svg>diff --git a/assets/icons/hard-drive.svg b/assets/icons/hard-drive.svgnew file mode 100644index 0000000..0e933d4--- /dev/null+++ b/assets/icons/hard-drive.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-hard-drive"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M10 16h.01" />+ <path d="M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z" />+ <path d="M21.946 12.013H2.054" />+ <path d="M6 16h.01" />+</svg>diff --git a/assets/icons/inbox.svg b/assets/icons/inbox.svgnew file mode 100644index 0000000..a7246e9--- /dev/null+++ b/assets/icons/inbox.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-inbox"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <polyline points="22 12 16 12 14 15 10 15 8 12 2 12" />+ <path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z" />+</svg>diff --git a/assets/icons/info.svg b/assets/icons/info.svgnew file mode 100644index 0000000..d7cccaf--- /dev/null+++ b/assets/icons/info.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-info"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" />+ <path d="M12 16v-4" />+ <path d="M12 8h.01" />+</svg>diff --git a/assets/icons/laptop.svg b/assets/icons/laptop.svgnew file mode 100644index 0000000..4d5e1ce--- /dev/null+++ b/assets/icons/laptop.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-laptop"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z" />+ <path d="M20.054 15.987H3.946" />+</svg>diff --git a/assets/icons/layers.svg b/assets/icons/layers.svgnew file mode 100644index 0000000..4b7ca3f--- /dev/null+++ b/assets/icons/layers.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-layers"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z" />+ <path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12" />+ <path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17" />+</svg>diff --git a/assets/icons/layout-grid.svg b/assets/icons/layout-grid.svgnew file mode 100644index 0000000..26d788d--- /dev/null+++ b/assets/icons/layout-grid.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-layout-grid"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="7" height="7" x="3" y="3" rx="1" />+ <rect width="7" height="7" x="14" y="3" rx="1" />+ <rect width="7" height="7" x="14" y="14" rx="1" />+ <rect width="7" height="7" x="3" y="14" rx="1" />+</svg>diff --git a/assets/icons/list.svg b/assets/icons/list.svgnew file mode 100644index 0000000..3f7c669--- /dev/null+++ b/assets/icons/list.svg@@ -0,0 +1,20 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-list"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M3 5h.01" />+ <path d="M3 12h.01" />+ <path d="M3 19h.01" />+ <path d="M8 5h13" />+ <path d="M8 12h13" />+ <path d="M8 19h13" />+</svg>diff --git a/assets/icons/loader-circle.svg b/assets/icons/loader-circle.svgnew file mode 100644index 0000000..42bd641--- /dev/null+++ b/assets/icons/loader-circle.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-loader-circle"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+</svg>diff --git a/assets/icons/memory-stick.svg b/assets/icons/memory-stick.svgnew file mode 100644index 0000000..0e0dac6--- /dev/null+++ b/assets/icons/memory-stick.svg@@ -0,0 +1,25 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-memory-stick"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12 12v-2" />+ <path d="M12 18v-2" />+ <path d="M16 12v-2" />+ <path d="M16 18v-2" />+ <path d="M2 11h1.5" />+ <path d="M20 18v-2" />+ <path d="M20.5 11H22" />+ <path d="M4 18v-2" />+ <path d="M8 12v-2" />+ <path d="M8 18v-2" />+ <rect x="2" y="6" width="20" height="10" rx="2" />+</svg>diff --git a/assets/icons/minus.svg b/assets/icons/minus.svgnew file mode 100644index 0000000..1ed89e7--- /dev/null+++ b/assets/icons/minus.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-minus"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M5 12h14" />+</svg>diff --git a/assets/icons/monitor.svg b/assets/icons/monitor.svgnew file mode 100644index 0000000..137b234--- /dev/null+++ b/assets/icons/monitor.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-monitor"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="20" height="14" x="2" y="3" rx="2" />+ <line x1="8" x2="16" y1="21" y2="21" />+ <line x1="12" x2="12" y1="17" y2="21" />+</svg>diff --git a/assets/icons/network.svg b/assets/icons/network.svgnew file mode 100644index 0000000..15949ea--- /dev/null+++ b/assets/icons/network.svg@@ -0,0 +1,19 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-network"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect x="16" y="16" width="6" height="6" rx="1" />+ <rect x="2" y="16" width="6" height="6" rx="1" />+ <rect x="9" y="2" width="6" height="6" rx="1" />+ <path d="M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3" />+ <path d="M12 12V8" />+</svg>diff --git a/assets/icons/panel-bottom.svg b/assets/icons/panel-bottom.svgnew file mode 100644index 0000000..32ab78e--- /dev/null+++ b/assets/icons/panel-bottom.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-panel-bottom"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="18" height="18" x="3" y="3" rx="2" />+ <path d="M3 15h18" />+</svg>diff --git a/assets/icons/play.svg b/assets/icons/play.svgnew file mode 100644index 0000000..40da4c9--- /dev/null+++ b/assets/icons/play.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-play"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" />+</svg>diff --git a/assets/icons/plus.svg b/assets/icons/plus.svgnew file mode 100644index 0000000..2295b76--- /dev/null+++ b/assets/icons/plus.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-plus"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M5 12h14" />+ <path d="M12 5v14" />+</svg>diff --git a/assets/icons/radio.svg b/assets/icons/radio.svgnew file mode 100644index 0000000..0a3ff1f--- /dev/null+++ b/assets/icons/radio.svg@@ -0,0 +1,19 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-radio"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M16.247 7.761a6 6 0 0 1 0 8.478" />+ <path d="M19.075 4.933a10 10 0 0 1 0 14.134" />+ <path d="M4.925 19.067a10 10 0 0 1 0-14.134" />+ <path d="M7.753 16.239a6 6 0 0 1 0-8.478" />+ <circle cx="12" cy="12" r="2" />+</svg>diff --git a/assets/icons/refresh-cw.svg b/assets/icons/refresh-cw.svgnew file mode 100644index 0000000..2fb76b9--- /dev/null+++ b/assets/icons/refresh-cw.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-refresh-cw"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />+ <path d="M21 3v5h-5" />+ <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" />+ <path d="M8 16H3v5" />+</svg>diff --git a/assets/icons/rotate-ccw.svg b/assets/icons/rotate-ccw.svgnew file mode 100644index 0000000..6ff6fd2--- /dev/null+++ b/assets/icons/rotate-ccw.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-rotate-ccw"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />+ <path d="M3 3v5h5" />+</svg>diff --git a/assets/icons/scroll-text.svg b/assets/icons/scroll-text.svgnew file mode 100644index 0000000..f8c2a83--- /dev/null+++ b/assets/icons/scroll-text.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-scroll-text"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15 12h-5" />+ <path d="M15 8h-5" />+ <path d="M19 17V5a2 2 0 0 0-2-2H4" />+ <path d="M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3" />+</svg>diff --git a/assets/icons/search.svg b/assets/icons/search.svgnew file mode 100644index 0000000..9a60456--- /dev/null+++ b/assets/icons/search.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-search"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m21 21-4.34-4.34" />+ <circle cx="11" cy="11" r="8" />+</svg>diff --git a/assets/icons/server.svg b/assets/icons/server.svgnew file mode 100644index 0000000..6713298--- /dev/null+++ b/assets/icons/server.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-server"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="20" height="8" x="2" y="2" rx="2" ry="2" />+ <rect width="20" height="8" x="2" y="14" rx="2" ry="2" />+ <line x1="6" x2="6.01" y1="6" y2="6" />+ <line x1="6" x2="6.01" y1="18" y2="18" />+</svg>diff --git a/assets/icons/settings.svg b/assets/icons/settings.svgnew file mode 100644index 0000000..cf0a159--- /dev/null+++ b/assets/icons/settings.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-settings"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" />+ <circle cx="12" cy="12" r="3" />+</svg>diff --git a/assets/icons/square.svg b/assets/icons/square.svgnew file mode 100644index 0000000..4826e47--- /dev/null+++ b/assets/icons/square.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-square"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="18" height="18" x="3" y="3" rx="2" />+</svg>diff --git a/assets/icons/terminal.svg b/assets/icons/terminal.svgnew file mode 100644index 0000000..fe4b6ae--- /dev/null+++ b/assets/icons/terminal.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-terminal"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M12 19h8" />+ <path d="m4 17 6-6-6-6" />+</svg>diff --git a/assets/icons/trash-2.svg b/assets/icons/trash-2.svgnew file mode 100644index 0000000..06050bd--- /dev/null+++ b/assets/icons/trash-2.svg@@ -0,0 +1,19 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-trash-2"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M10 11v6" />+ <path d="M14 11v6" />+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />+ <path d="M3 6h18" />+ <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />+</svg>diff --git a/assets/icons/triangle-alert.svg b/assets/icons/triangle-alert.svgnew file mode 100644index 0000000..642bb63--- /dev/null+++ b/assets/icons/triangle-alert.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-triangle-alert"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" />+ <path d="M12 9v4" />+ <path d="M12 17h.01" />+</svg>diff --git a/assets/icons/workflow.svg b/assets/icons/workflow.svgnew file mode 100644index 0000000..d65a27d--- /dev/null+++ b/assets/icons/workflow.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-workflow"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="8" height="8" x="3" y="3" rx="2" />+ <path d="M7 11v4a2 2 0 0 0 2 2h4" />+ <rect width="8" height="8" x="13" y="13" rx="2" />+</svg>diff --git a/assets/icons/x.svg b/assets/icons/x.svgnew file mode 100644index 0000000..98dcead--- /dev/null+++ b/assets/icons/x.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-x"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M18 6 6 18" />+ <path d="m6 6 12 12" />+</svg>diff --git a/assets/icons/zap.svg b/assets/icons/zap.svgnew file mode 100644index 0000000..fcaaf43--- /dev/null+++ b/assets/icons/zap.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-zap"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z" />+</svg>diff --git a/assets/linux/openrunner.desktop b/assets/linux/openrunner.desktopnew file mode 100644index 0000000..806d40f--- /dev/null+++ b/assets/linux/openrunner.desktop@@ -0,0 +1,9 @@+[Desktop Entry]+Type=Application+Name=OpenRunner+Comment=Run and control your self-hosted GitHub Actions runners+Exec=openrunner+Icon=openrunner+Terminal=false+StartupWMClass=openrunner+Categories=Development;diff --git a/scripts/bundle-macos.sh b/scripts/bundle-macos.shnew file mode 100755index 0000000..22c59d5--- /dev/null+++ b/scripts/bundle-macos.sh@@ -0,0 +1,39 @@+#!/bin/sh+# Builds OpenRunner.app (release build + Info.plist + icon) into dist/.+# The bundle runs the same binary: with no arguments it opens the window, and+# `OpenRunner.app/Contents/MacOS/openrunner mcp` still works for agents.+set -eu++cd "$(dirname "$0")/.."+version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1)+app=dist/OpenRunner.app++cargo build --release+rm -rf "$app"+mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"+cp target/release/openrunner "$app/Contents/MacOS/openrunner"+cp assets/brand/OpenRunner.icns "$app/Contents/Resources/OpenRunner.icns"++cat > "$app/Contents/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleName</key><string>OpenRunner</string>+ <key>CFBundleDisplayName</key><string>OpenRunner</string>+ <key>CFBundleIdentifier</key><string>dev.openrunner.OpenRunner</string>+ <key>CFBundleExecutable</key><string>openrunner</string>+ <key>CFBundleIconFile</key><string>OpenRunner</string>+ <key>CFBundlePackageType</key><string>APPL</string>+ <key>CFBundleShortVersionString</key><string>$version</string>+ <key>CFBundleVersion</key><string>$version</string>+ <key>LSMinimumSystemVersion</key><string>12.0</string>+ <key>LSApplicationCategoryType</key><string>public.app-category.developer-tools</string>+ <key>NSHighResolutionCapable</key><true/>+</dict>+</plist>+PLIST++# Ad-hoc signature so Gatekeeper treats it as one app; replace with a Developer ID to distribute.+codesign --force --deep --sign - "$app" >/dev/null 2>&1 || echo "warning: codesign failed; the app still runs locally" >&2+echo "Built $app"diff --git a/src/api.rs b/src/api.rsnew file mode 100644index 0000000..b05ff0f--- /dev/null+++ b/src/api.rs@@ -0,0 +1,2085 @@+//! The agent-facing API: one layer behind both the MCP server (`openrunner mcp`)+//! and the scriptable CLI (`openrunner status --json`, `openrunner install`, ...).+//!+//! Responses are compact and explicit on purpose: stable ids, plain state+//! strings, a one-line `summary` where it helps, and operation logs capped to a+//! tail. Errors carry a `code` an agent can branch on and, when we know it, a+//! `hint` with the exact fix.++use std::collections::{BTreeMap, HashSet};+use std::path::{Component, Path};+use std::sync::Arc;+use std::time::Duration;++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};++use crate::fleet::Engine;+use crate::fleet::model::{Job, Machine, Operation, Runner, Snapshot, WorkspaceCommand, WorkspaceInfo};+use crate::fleet::workspaces::{CreateWorkspace, ExecOptions, SyncDirection};+use crate::ops::{InstallMode, InstallRequest, NewMachine, RunnerAction};+use crate::util;++/// GitHub data older than this is refreshed before answering.+const GITHUB_MAX_AGE_SECS: i64 = 30;+const DEFAULT_TAIL: usize = 80;+const LOGS_TAIL: usize = 200;+const INSTALL_TIMEOUT_SECS: u64 = 900;+const ACTION_TIMEOUT_SECS: u64 = 180;+const CHECK_WAIT: Duration = Duration::from_secs(60);++// ---------------------------------------------------------------------------+// Errors++#[derive(Debug, Clone, Serialize)]+pub struct ApiError {+ /// "not_found" | "invalid" | "busy" | "github" | "unreachable" | "operation_failed" | "internal"+ pub code: &'static str,+ pub message: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+ /// For "operation_failed": the operation and the state it left things in.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub details: Option<serde_json::Value>,+}++impl ApiError {+ fn new(code: &'static str, message: impl Into<String>) -> ApiError {+ ApiError { code, message: message.into(), hint: None, details: None }+ }++ pub fn not_found(message: impl Into<String>) -> ApiError {+ ApiError::new("not_found", message)+ }++ pub fn invalid(message: impl Into<String>) -> ApiError {+ ApiError::new("invalid", message)+ }++ fn with_hint(mut self, hint: impl Into<String>) -> ApiError {+ self.hint = Some(hint.into());+ self+ }++ /// Exit code for the CLI: 2 for bad input, 1 for everything else.+ pub fn exit_code(&self) -> u8 {+ match self.code {+ "not_found" | "invalid" => 2,+ _ => 1,+ }+ }+}++impl std::fmt::Display for ApiError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.message)?;+ if let Some(h) = &self.hint {+ write!(f, " (hint: {h})")?;+ }+ Ok(())+ }+}++/// Maps a message from the ops layer onto an error code.+fn op_error(message: String) -> ApiError {+ let lower = message.to_ascii_lowercase();+ let code = if lower.contains("another operation") || lower.contains("still running") {+ "busy"+ } else if lower.contains("isn't in fleet.toml") || lower.contains("isn't in the fleet") {+ "not_found"+ } else {+ "invalid"+ };+ ApiError::new(code, message)+}++pub type ApiResult<T> = Result<T, ApiError>;++/// Who's asking, so hints name the right next step: an MCP tool or a CLI command.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Surface {+ Mcp,+ Cli,+}++impl Surface {+ fn say(self, mcp: impl Into<String>, cli: impl Into<String>) -> String {+ match self {+ Surface::Mcp => mcp.into(),+ Surface::Cli => cli.into(),+ }+ }+}++// ---------------------------------------------------------------------------+// Requests. Doc comments here double as the tool documentation.++fn yes() -> bool {+ true+}++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct StatusRequest {+ /// Check every machine over SSH and sync GitHub before answering (slower, up to ~45s per unreachable machine).+ pub refresh: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct MachineRequest {+ /// Machine id, e.g. "mac-studio".+ pub machine_id: String,+}++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct RunnersRequest {+ /// Only runners on this machine.+ pub machine_id: Option<String>,+ /// Only runners in this state: working, idle, offline or unknown.+ pub state: Option<String>,+}++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct CheckRequest {+ /// Check only this machine; omit to check all of them.+ pub machine_id: Option<String>,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct AddMachineRequest {+ /// Display name, e.g. "Mac Studio". The id is derived from it.+ pub name: String,+ /// An ssh destination ("[email protected]", an ~/.ssh/config alias) or "local" for this computer.+ pub host: String,+ /// Check the machine right away and return what was found (default true).+ #[serde(default = "yes")]+ pub check: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct InstallRunnersRequest {+ pub machine_id: String,+ /// GitHub org ("acme") or repo ("acme/api") to register with. Optional when exactly one is watched.+ #[serde(default)]+ pub scope: Option<String>,+ /// Runner names. When empty, `count` names like "<machine-id>-01" are picked.+ #[serde(default)]+ pub names: Vec<String>,+ /// How many runners to install when `names` is empty (default 1).+ #[serde(default)]+ pub count: Option<usize>,+ /// Extra labels; GitHub adds self-hosted, the OS and the architecture itself.+ #[serde(default)]+ pub labels: Vec<String>,+ /// Org runner group (org scopes only).+ #[serde(default)]+ pub runner_group: Option<String>,+ /// Legacy: false is the same as mode "background". Prefer `mode`.+ #[serde(default = "yes")]+ pub as_service: bool,+ /// "auto" (default): a service when the machine allows it, else Docker when available, else background.+ /// "service": launchd / systemd / Windows service (Linux needs passwordless sudo).+ /// "background": run.sh, no root needed, not restarted after a reboot.+ /// "docker": one container per runner from GitHub's actions-runner image, restarted by Docker.+ #[serde(default)]+ pub mode: Option<String>,+ /// mode "docker": image to use (default ghcr.io/actions/actions-runner:<latest runner version>).+ #[serde(default)]+ pub image: Option<String>,+ /// mode "docker": give jobs the host's Docker socket (root-equivalent access to the machine).+ #[serde(default)]+ pub docker_socket: bool,+ /// Wait for the install to finish (default true).+ #[serde(default = "yes")]+ pub wait: bool,+ /// How long to wait, in seconds (default 900).+ #[serde(default)]+ pub timeout_secs: Option<u64>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum ActionName {+ Start,+ Stop,+ Restart,+ Logs,+ Remove,+}++impl std::str::FromStr for ActionName {+ type Err = ApiError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s.to_ascii_lowercase().as_str() {+ "start" => Ok(ActionName::Start),+ "stop" => Ok(ActionName::Stop),+ "restart" => Ok(ActionName::Restart),+ "logs" | "log" => Ok(ActionName::Logs),+ "remove" | "rm" | "delete" => Ok(ActionName::Remove),+ other => Err(ApiError::invalid(format!("Unknown action \"{other}\". Use start, stop, restart, logs or remove."))),+ }+ }+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct RunnerActionRequest {+ /// Runner id: "<machine-id>/<runner-name>", or "github/<name>" for a runner no machine lists.+ pub runner_id: String,+ pub action: ActionName,+ /// With action=remove: also delete the runner's folder on the machine.+ #[serde(default)]+ pub delete_files: bool,+ /// Wait for the action to finish (default true).+ #[serde(default = "yes")]+ pub wait: bool,+ /// How long to wait, in seconds (default 180).+ #[serde(default)]+ pub timeout_secs: Option<u64>,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct OperationRequest {+ pub operation_id: u64,+ /// How many log lines to return from the end (default 80).+ #[serde(default)]+ pub tail: Option<usize>,+}++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct GitHubScopesRequest {+ /// Orgs ("acme") or repos ("acme/api") to start watching. Each is checked against GitHub first.+ pub add: Vec<String>,+ /// Orgs or repos to stop watching.+ pub remove: Vec<String>,+}++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct UpdateSettingsRequest {+ /// How often the window polls GitHub, in seconds (min 10).+ pub github_poll_seconds: Option<u32>,+ /// How many recently pushed repos per org to scan for queued/running jobs (0-50).+ pub scan_repos: Option<u32>,+ /// Automatic machine checks, in minutes (0 = only on request).+ pub check_interval_minutes: Option<u32>,+ /// GitHub REST API base (GitHub Enterprise Server: https://HOST/api/v3).+ pub api_url: Option<String>,+}++// ---------------------------------------------------------------------------+// Responses++#[derive(Debug, Serialize)]+pub struct StatusResponse {+ pub summary: String,+ pub counts: Counts,+ pub github: GitHubOut,+ pub last_check_at: Option<DateTime<Utc>>,+ /// Problems worth acting on, most severe first. Read these first.+ pub attention: Vec<AttentionOut>,+ pub machines: Vec<MachineSummary>,+ pub inventory: InventoryOut,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+ pub demo: bool,+}++#[derive(Debug, Serialize)]+pub struct Counts {+ pub machines: usize,+ pub runners: usize,+ pub working: usize,+ pub idle: usize,+ pub offline: usize,+ pub unknown: usize,+ pub queued_jobs: usize,+ pub running_jobs: usize,+}++#[derive(Debug, Serialize)]+pub struct GitHubOut {+ /// At least one org or repo is watched.+ pub configured: bool,+ /// Runner states come live from GitHub (otherwise from the last machine check).+ pub live: bool,+ /// Where the token came from: "gh", "GITHUB_TOKEN", ...; null when none was found.+ pub token: Option<String>,+ pub login: Option<String>,+ pub watching: Vec<ScopeOut>,+ /// Orgs/repos named in runner configs on the machines that aren't watched yet.+ pub detected: Vec<String>,+ pub last_sync_at: Option<DateTime<Utc>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct ScopeOut {+ /// "org" or "repo"+ pub kind: String,+ pub name: String,+ pub runners: usize,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct AttentionOut {+ /// "error" | "warning" | "info"+ pub level: String,+ pub title: String,+ pub detail: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub machine_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub runner_id: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct InventoryOut {+ pub path: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct MachineSummary {+ pub id: String,+ pub name: String,+ pub host: String,+ /// "online" | "offline" (unreachable) | "unchecked" | "manual" (no host)+ pub status: String,+ pub checking: bool,+ /// e.g. "darwin-arm64", "linux-x64", "windows-x64"+ pub platform: String,+ /// e.g. "3/7 working", "2 idle", "no runners"+ pub runners: String,+ pub runner_counts: RunnerCounts,+ pub cpu_pct: Option<f64>,+ pub mem_pct: Option<f64>,+ pub disk_free: Option<String>,+ pub disk_free_bytes: Option<u64>,+ pub uptime: Option<String>,+ /// Warnings and errors (info items don't count).+ pub problems: usize,+ /// Worst diagnostic level: "error" | "warning" | "unknown" | "info" | null+ pub worst: Option<String>,+ pub checked_at: Option<DateTime<Utc>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct RunnerCounts {+ pub total: usize,+ pub working: usize,+ pub idle: usize,+ pub offline: usize,+ pub unknown: usize,+}++#[derive(Debug, Serialize)]+pub struct MachineDetail {+ #[serde(flatten)]+ pub summary: MachineSummary,+ pub os_version: Option<String>,+ pub cores: Option<u32>,+ pub load: Vec<f64>,+ pub mem_used_bytes: Option<u64>,+ pub mem_total_bytes: Option<u64>,+ pub disk_total_bytes: Option<u64>,+ pub notes: Option<String>,+ pub runners: Vec<RunnerOut>,+ pub diagnostics: Vec<DiagnosticOut>,+}++#[derive(Debug, Clone, Serialize)]+pub struct DiagnosticOut {+ /// "error" | "warning" | "unknown" | "info"+ pub level: String,+ pub code: String,+ pub message: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub runner_id: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct RunnerOut {+ pub id: String,+ pub name: String,+ pub machine_id: Option<String>,+ /// "working" | "idle" | "offline" | "unknown"+ pub state: String,+ /// Where `state` came from: "github" (live), "probe" (last machine check) or "none".+ pub source: String,+ /// Listed in fleet.toml (vs discovered on the machine or on GitHub).+ pub declared: bool,+ pub labels: Vec<String>,+ pub version: Option<String>,+ pub dir: Option<String>,+ pub service: Option<String>,+ pub service_state: Option<String>,+ pub registered_to: Option<String>,+ pub github_status: Option<String>,+ pub job: Option<JobOut>,+}++#[derive(Debug, Clone, Serialize)]+pub struct JobOut {+ pub id: u64,+ pub name: String,+ pub workflow: String,+ pub repo: String,+ pub branch: Option<String>,+ /// "queued" | "in_progress" | "waiting"+ pub status: String,+ pub labels: Vec<String>,+ pub runner_id: Option<String>,+ pub url: String,+ pub created_at: DateTime<Utc>,+ pub started_at: Option<DateTime<Utc>>,+ /// Seconds queued (queued jobs) or running (running jobs).+ pub age_secs: i64,+ /// Queued jobs: how many online runners have every label the job asks for.+ pub matching_online: usize,+}++#[derive(Debug, Serialize)]+pub struct JobsResponse {+ pub summary: String,+ pub queued: Vec<JobOut>,+ pub running: Vec<JobOut>,+ pub scanned_repos: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct OperationOut {+ pub id: u64,+ /// "install" | "start" | "stop" | "restart" | "remove" | "logs"+ pub kind: String,+ pub title: String,+ /// "running" | "succeeded" | "failed"+ pub status: String,+ pub machine_id: Option<String>,+ pub runner_id: Option<String>,+ pub started_at: DateTime<Utc>,+ pub finished_at: Option<DateTime<Utc>>,+ pub error: Option<String>,+ /// The last lines of output. "▸ " lines are OpenRunner's steps, "✓ " successes,+ /// "error: "/"warning: " problems; anything else is output from the machine.+ pub log_tail: Vec<String>,+ pub log_lines: usize,+ pub truncated: bool,+}++#[derive(Debug, Serialize)]+pub struct ActionResponse {+ pub operation: OperationOut,+ /// False when `wait` was off or the timeout passed; poll get_operation.+ pub finished: bool,+ pub machine: Option<MachineSummary>,+ /// Runners the operation touched, as they are now (empty after a remove).+ pub runners: Vec<RunnerOut>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub next: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct AddMachineResponse {+ pub machine_id: String,+ pub machine: Option<MachineDetail>,+ pub next: String,+}++#[derive(Debug, Serialize)]+pub struct ScopeResult {+ pub scope: String,+ /// "added" | "removed" | "already_watching" | "not_watching" | "failed"+ pub result: String,+ pub runners: Option<usize>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub hint: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct ScopesResponse {+ pub results: Vec<ScopeResult>,+ pub watching: Vec<ScopeOut>,+}++#[derive(Debug, Serialize)]+pub struct SettingsOut {+ pub github_orgs: Vec<String>,+ pub github_repos: Vec<String>,+ pub github_poll_seconds: u32,+ pub scan_repos: u32,+ pub check_interval_minutes: u32,+ pub api_url: String,+ pub config_dir: String,+ pub inventory: String,+}++#[derive(Debug, Serialize)]+pub struct SshHostsResponse {+ /// Host aliases from ~/.ssh/config, usable as `host` in add_machine.+ pub hosts: Vec<String>,+}++// ---------------------------------------------------------------------------+// Conversions++pub fn machine_summary(m: &Machine) -> MachineSummary {+ let p = m.probe.as_ref().filter(|p| p.ok);+ let problems = m.diagnostics.iter().filter(|d| matches!(d.level.as_str(), "warning" | "error")).count();+ let worst = ["error", "warning", "unknown", "info"]+ .into_iter()+ .find(|l| m.diagnostics.iter().any(|d| d.level == *l))+ .map(str::to_string);+ let s = &m.summary;+ let runners = if s.total == 0 {+ "no runners".to_string()+ } else if s.working > 0 {+ format!("{}/{} working", s.working, s.total)+ } else if s.idle == s.total {+ format!("{} idle", s.idle)+ } else if s.offline > 0 {+ format!("{}/{} offline", s.offline, s.total)+ } else {+ format!("{} unknown", s.unknown)+ };+ MachineSummary {+ id: m.id.clone(),+ name: m.name.clone(),+ host: m.host.clone(),+ status: m.status.clone(),+ checking: m.checking,+ platform: m.platform.clone(),+ runners,+ runner_counts: RunnerCounts { total: s.total, working: s.working, idle: s.idle, offline: s.offline, unknown: s.unknown },+ cpu_pct: p.and_then(|p| p.cpu_pct).map(round1),+ mem_pct: p.and_then(|p| Some(round1(p.mem_used? as f64 * 100.0 / p.mem_total?.max(1) as f64))),+ disk_free: p.and_then(|p| p.disk_free).map(util::bytes),+ disk_free_bytes: p.and_then(|p| p.disk_free),+ uptime: p.and_then(|p| p.uptime_sec).map(util::uptime),+ problems,+ worst,+ checked_at: m.probe.as_ref().map(|p| p.checked_at),+ error: m.probe.as_ref().filter(|p| !p.ok).and_then(|p| p.error.clone()),+ }+}++fn machine_detail(s: &Snapshot, m: &Machine) -> MachineDetail {+ let p = m.probe.as_ref().filter(|p| p.ok);+ MachineDetail {+ summary: machine_summary(m),+ os_version: p.and_then(|p| p.os_version.clone()),+ cores: p.and_then(|p| p.cores),+ load: p.map(|p| p.load.clone()).unwrap_or_default(),+ mem_used_bytes: p.and_then(|p| p.mem_used),+ mem_total_bytes: p.and_then(|p| p.mem_total),+ disk_total_bytes: p.and_then(|p| p.disk_total),+ notes: m.notes.clone(),+ runners: m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).map(|r| runner_out(s, r)).collect(),+ diagnostics: m+ .diagnostics+ .iter()+ .map(|d| DiagnosticOut {+ level: d.level.clone(),+ code: d.code.clone(),+ message: d.message.clone(),+ hint: d.hint.clone(),+ runner_id: d.runner_id.clone(),+ })+ .collect(),+ }+}++fn runner_out(s: &Snapshot, r: &Runner) -> RunnerOut {+ let job = r.job_id.and_then(|id| s.jobs.running.iter().find(|j| j.id == id)).map(job_out);+ RunnerOut {+ id: r.id.clone(),+ name: r.name.clone(),+ machine_id: r.machine_id.clone(),+ state: r.state.clone(),+ source: r.source.clone(),+ declared: r.declared,+ labels: r.labels.clone(),+ version: r.local.as_ref().and_then(|l| l.version.clone()),+ dir: r.local.as_ref().map(|l| l.dir.clone()),+ service: r.local.as_ref().and_then(|l| l.service.clone()),+ service_state: r.local.as_ref().and_then(|l| l.service_state.clone()),+ registered_to: r+ .github+ .as_ref()+ .map(|g| g.scope.clone())+ .or_else(|| r.local.as_ref().and_then(|l| l.url.as_deref()).and_then(crate::github::scope_from_runner_url)),+ github_status: r.github.as_ref().map(|g| if g.busy { "busy".to_string() } else { g.status.clone() }),+ job,+ }+}++fn job_out(j: &Job) -> JobOut {+ let since = if j.status == "in_progress" { j.started_at.unwrap_or(j.created_at) } else { j.created_at };+ JobOut {+ id: j.id,+ name: j.name.clone(),+ workflow: j.workflow.clone(),+ repo: j.repo.clone(),+ branch: j.branch.clone(),+ status: j.status.clone(),+ labels: j.labels.clone(),+ runner_id: j.runner_id.clone(),+ url: j.url.clone(),+ created_at: j.created_at,+ started_at: j.started_at,+ age_secs: (Utc::now() - since).num_seconds().max(0),+ matching_online: j.matching_online,+ }+}++pub fn operation_out(o: &Operation, tail: usize) -> OperationOut {+ let start = o.log.len().saturating_sub(tail);+ OperationOut {+ id: o.id,+ kind: o.kind.clone(),+ title: o.title.clone(),+ status: o.status.clone(),+ machine_id: o.machine_id.clone(),+ runner_id: o.runner_id.clone(),+ started_at: o.started_at,+ finished_at: o.finished_at,+ error: o.error.clone(),+ log_tail: o.log[start..].to_vec(),+ log_lines: o.log.len(),+ truncated: start > 0,+ }+}++fn round1(v: f64) -> f64 {+ (v * 10.0).round() / 10.0+}++fn find_machine<'a>(s: &'a Snapshot, id: &str) -> ApiResult<&'a Machine> {+ s.machines.iter().find(|m| m.id == id || m.name.eq_ignore_ascii_case(id)).ok_or_else(|| {+ let ids: Vec<&str> = s.machines.iter().map(|m| m.id.as_str()).collect();+ ApiError::not_found(format!("No machine \"{id}\".")).with_hint(if ids.is_empty() {+ "The fleet is empty; add a machine first.".to_string()+ } else {+ format!("Known machine ids: {}", ids.join(", "))+ })+ })+}++fn find_runner<'a>(s: &'a Snapshot, id: &str) -> ApiResult<&'a Runner> {+ // Accept a bare runner name too, as long as it's unambiguous.+ if let Some(r) = s.runners.iter().find(|r| r.id == id) {+ return Ok(r);+ }+ let by_name: Vec<&Runner> = s.runners.iter().filter(|r| r.name.eq_ignore_ascii_case(id)).collect();+ match by_name.as_slice() {+ [one] => Ok(one),+ _ => {+ let close: Vec<&str> = s+ .runners+ .iter()+ .filter(|r| r.id.contains(id) || id.contains(r.name.as_str()))+ .map(|r| r.id.as_str())+ .take(8)+ .collect();+ Err(ApiError::not_found(format!("No runner \"{id}\".")).with_hint(if close.is_empty() {+ "Runner ids look like \"<machine-id>/<runner-name>\"; list_runners shows them all.".to_string()+ } else {+ format!("Did you mean: {}", close.join(", "))+ }))+ }+ }+}++// ---------------------------------------------------------------------------+// Freshness++/// Picks up other processes' changes, and syncs GitHub when it's stale.+async fn freshen(engine: &Arc<Engine>) -> Arc<Snapshot> {+ engine.refresh_from_disk();+ let s = engine.current();+ let stale = s.github.last_sync_at.is_none_or(|t| (Utc::now() - t).num_seconds() > GITHUB_MAX_AGE_SECS);+ if (s.github.configured || s.demo) && stale {+ engine.sync_github().await;+ }+ engine.current()+}++/// Waits until a machine has a check result and isn't being checked.+async fn wait_checked(engine: &Arc<Engine>, machine_id: &str, timeout: Duration) {+ let mut rx = engine.subscribe();+ let done = |s: &Snapshot| s.machines.iter().find(|m| m.id == machine_id).is_none_or(|m| !m.checking && m.probe.is_some());+ let _ = tokio::time::timeout(timeout, async {+ loop {+ if done(&rx.borrow_and_update()) {+ return;+ }+ if rx.changed().await.is_err() {+ return;+ }+ }+ })+ .await;+}++/// Waits for an operation to leave "running", calling `on_line` for every new log line.+/// Returns the operation as it is when it finishes or the timeout passes, or None if it's unknown.+pub async fn wait_operation(engine: &Arc<Engine>, id: u64, timeout: Duration, mut on_line: impl FnMut(&str)) -> Option<Operation> {+ let mut rx = engine.subscribe();+ let mut printed = 0;+ let deadline = tokio::time::Instant::now() + timeout;+ loop {+ let op = rx.borrow_and_update().operations.iter().find(|o| o.id == id).cloned()?;+ for line in op.log.iter().skip(printed) {+ on_line(line);+ }+ printed = op.log.len();+ if op.status != "running" {+ return Some(op);+ }+ match tokio::time::timeout_at(deadline, rx.changed()).await {+ Ok(Ok(())) => continue,+ _ => return Some(op),+ }+ }+}++// ---------------------------------------------------------------------------+// Read++pub async fn status(engine: &Arc<Engine>, req: StatusRequest, surface: Surface) -> ApiResult<StatusResponse> {+ let s = if req.refresh {+ engine.refresh_from_disk();+ engine.run_check(None).await;+ engine.sync_github().await;+ engine.current()+ } else {+ freshen(engine).await+ };+ Ok(status_from(&s, surface))+}++pub fn status_from(s: &Snapshot, surface: Surface) -> StatusResponse {+ let c = &s.counts;+ let g = &s.github;+ let token = (!g.token_source.is_empty()).then(|| g.token_source.clone());++ let gh_hint = if token.is_none() && !s.demo {+ Some("No GitHub token: run `gh auth login`, or set GITHUB_TOKEN.".to_string())+ } else if !g.configured {+ Some(match g.detected.first() {+ Some(d) => surface.say(+ format!("Not watching GitHub yet. Runner configs mention \"{d}\": call github_scopes with add=[\"{d}\"]."),+ format!("Not watching GitHub yet. Runner configs mention \"{d}\": run `openrunner watch {d}`."),+ ),+ None => surface.say(+ "Not watching GitHub yet: call github_scopes with add=[\"<org>\"] or [\"owner/repo\"].",+ "Not watching GitHub yet: run `openrunner watch <org>` (or owner/repo).",+ ),+ })+ } else {+ g.scopes.iter().find_map(|sc| sc.hint.clone())+ };++ let attention = s+ .attention+ .iter()+ .map(|a| {+ let target = a.action.as_ref().and_then(|x| x.target.clone());+ let kind = a.action.as_ref().map(|x| x.kind.as_str()).unwrap_or("");+ AttentionOut {+ level: a.level.clone(),+ title: a.title.clone(),+ detail: a.detail.clone(),+ machine_id: (kind == "machine").then(|| target.clone()).flatten(),+ runner_id: (kind == "runner").then_some(target).flatten(),+ }+ })+ .collect::<Vec<_>>();++ let never_checked = s.check.finished_at.is_none() && s.machines.iter().all(|m| m.probe.is_none());+ let summary = format!(+ "{} machine{}, {} runner{}: {} working, {} idle, {} offline{}. {} queued job{}, {} running.{}",+ c.machines,+ plural(c.machines),+ c.runners,+ plural(c.runners),+ c.working,+ c.idle,+ c.offline,+ if c.unknown > 0 { format!(", {} unknown", c.unknown) } else { String::new() },+ c.queued,+ plural(c.queued),+ c.running,+ match attention.len() {+ 0 => " Nothing needs attention.".to_string(),+ n => format!(" {n} item{} need{} attention.", plural(n), if n == 1 { "s" } else { "" }),+ }+ );++ StatusResponse {+ summary,+ counts: Counts {+ machines: c.machines,+ runners: c.runners,+ working: c.working,+ idle: c.idle,+ offline: c.offline,+ unknown: c.unknown,+ queued_jobs: c.queued,+ running_jobs: c.running,+ },+ github: GitHubOut {+ configured: g.configured,+ live: g.live,+ token,+ login: g.login.clone(),+ watching: g.scopes.iter().map(|sc| ScopeOut { kind: sc.kind.clone(), name: sc.name.clone(), runners: sc.runners, error: sc.error.clone(), hint: sc.hint.clone() }).collect(),+ detected: g.detected.clone(),+ last_sync_at: g.last_sync_at,+ error: g.error.clone(),+ hint: gh_hint,+ },+ last_check_at: s.check.finished_at,+ attention,+ machines: s.machines.iter().map(machine_summary).collect(),+ inventory: InventoryOut { path: s.inventory.path.clone(), error: s.inventory.error.clone() },+ hint: never_checked.then(|| {+ surface.say(+ "No machine has been checked yet; call check_machines (or fleet_status with refresh=true).",+ "No machine has been checked yet; run `openrunner status --refresh` (or `openrunner check`).",+ )+ }),+ demo: s.demo,+ }+}++fn plural(n: usize) -> &'static str {+ if n == 1 { "" } else { "s" }+}++pub async fn machine(engine: &Arc<Engine>, req: MachineRequest) -> ApiResult<MachineDetail> {+ let s = freshen(engine).await;+ let m = find_machine(&s, &req.machine_id)?;+ Ok(machine_detail(&s, m))+}++pub async fn machines(engine: &Arc<Engine>) -> ApiResult<Vec<MachineSummary>> {+ let s = freshen(engine).await;+ Ok(s.machines.iter().map(machine_summary).collect())+}++pub async fn runners(engine: &Arc<Engine>, req: RunnersRequest) -> ApiResult<Vec<RunnerOut>> {+ let s = freshen(engine).await;+ if let Some(m) = &req.machine_id {+ find_machine(&s, m)?;+ }+ if let Some(st) = &req.state {+ if !matches!(st.as_str(), "working" | "idle" | "offline" | "unknown") {+ return Err(ApiError::invalid(format!("Unknown state \"{st}\". Use working, idle, offline or unknown.")));+ }+ }+ let machine_id = req.machine_id.as_ref().and_then(|m| find_machine(&s, m).ok()).map(|m| m.id.clone());+ Ok(s.runners+ .iter()+ .filter(|r| machine_id.as_ref().is_none_or(|m| r.machine_id.as_ref() == Some(m)))+ .filter(|r| req.state.as_ref().is_none_or(|st| &r.state == st))+ .map(|r| runner_out(&s, r))+ .collect())+}++pub async fn jobs(engine: &Arc<Engine>, surface: Surface) -> ApiResult<JobsResponse> {+ let s = freshen(engine).await;+ let stuck = s.jobs.queued.iter().filter(|j| j.matching_online == 0).count();+ Ok(JobsResponse {+ summary: format!(+ "{} queued{}, {} running, across {} scanned repo{}.",+ s.jobs.queued.len(),+ if stuck > 0 { format!(" ({stuck} with no online runner that matches)") } else { String::new() },+ s.jobs.running.len(),+ s.github.scanned_repos.len(),+ plural(s.github.scanned_repos.len())+ ),+ queued: s.jobs.queued.iter().map(job_out).collect(),+ running: s.jobs.running.iter().map(job_out).collect(),+ scanned_repos: s.github.scanned_repos.clone(),+ hint: (!s.github.configured && !s.demo).then(|| {+ surface.say(+ "Jobs come from GitHub: call github_scopes with add=[\"<org>\"] first.",+ "Jobs come from GitHub: run `openrunner watch <org>` first.",+ )+ }),+ })+}++pub fn operations(engine: &Arc<Engine>) -> Vec<OperationOut> {+ engine.current().operations.iter().map(|o| operation_out(o, 0)).collect()+}++pub fn operation(engine: &Arc<Engine>, req: OperationRequest) -> ApiResult<OperationOut> {+ let s = engine.current();+ let o = s.operations.iter().find(|o| o.id == req.operation_id).ok_or_else(|| {+ ApiError::not_found(format!("No operation {} in this OpenRunner process.", req.operation_id))+ .with_hint("Operation ids are per process; list_operations shows the ones this server started.")+ })?;+ Ok(operation_out(o, req.tail.unwrap_or(DEFAULT_TAIL)))+}++pub fn settings(engine: &Arc<Engine>) -> SettingsOut {+ engine.refresh_from_disk();+ let s = engine.settings();+ let p = engine.paths();+ SettingsOut {+ github_orgs: s.github.orgs,+ github_repos: s.github.repos,+ github_poll_seconds: s.github_poll_seconds,+ scan_repos: s.github.scan_repos,+ check_interval_minutes: s.check_interval_minutes,+ api_url: s.github.api_url,+ config_dir: crate::config::display_path(&p.dir),+ inventory: engine.current().inventory.path.clone(),+ }+}++pub fn ssh_hosts() -> SshHostsResponse {+ SshHostsResponse { hosts: crate::ops::ssh_hosts() }+}++// ---------------------------------------------------------------------------+// Act++pub async fn check(engine: &Arc<Engine>, req: CheckRequest) -> ApiResult<Vec<MachineSummary>> {+ engine.refresh_from_disk();+ let only = match &req.machine_id {+ Some(id) => {+ let s = engine.current();+ let m = find_machine(&s, id)?;+ if m.host.is_empty() {+ return Err(ApiError::invalid(format!("{} has no host in fleet.toml, so it can't be checked.", m.name)));+ }+ Some(m.id.clone())+ }+ None => None,+ };+ match &only {+ Some(id) => {+ engine.run_check(Some(vec![id.clone()])).await;+ // Another check of the same machine may have been in flight; wait it out.+ wait_checked(engine, id, CHECK_WAIT).await;+ }+ None => engine.run_check(None).await,+ }+ engine.sync_github().await;+ let s = engine.current();+ Ok(s.machines.iter().filter(|m| only.as_ref().is_none_or(|id| &m.id == id)).map(machine_summary).collect())+}++pub async fn add_machine(engine: &Arc<Engine>, req: AddMachineRequest, surface: Surface) -> ApiResult<AddMachineResponse> {+ engine.refresh_from_disk();+ let id = engine.add_machine(NewMachine { name: req.name, host: req.host }).map_err(op_error)?;+ let machine = if req.check {+ wait_checked(engine, &id, CHECK_WAIT).await;+ let s = engine.current();+ s.machines.iter().find(|m| m.id == id).map(|m| machine_detail(&s, m))+ } else {+ None+ };+ let next = match machine.as_ref().map(|m| m.summary.status.as_str()) {+ Some("online") => surface.say(+ format!("Machine is reachable. Install runners with install_runners(machine_id=\"{id}\", count=N)."),+ format!("Machine is reachable. Install runners with `openrunner install {id} --count N`."),+ ),+ Some("offline") => surface.say(+ "The machine didn't answer over ssh. Make sure key-based `ssh <host>` works without a password prompt, then call check_machines.",+ "The machine didn't answer over ssh. Make sure key-based `ssh <host>` works without a password prompt, then run `openrunner check`.",+ ),+ _ => surface.say(format!("Call check_machines(machine_id=\"{id}\") to check it."), "Run `openrunner check` to check it.".to_string()),+ };+ Ok(AddMachineResponse { machine_id: id, machine, next })+}++pub async fn remove_machine(engine: &Arc<Engine>, req: MachineRequest) -> ApiResult<MachineSummary> {+ engine.refresh_from_disk();+ let s = engine.current();+ let m = find_machine(&s, &req.machine_id)?.clone();+ engine.remove_machine(&m.id).map_err(op_error)?;+ Ok(machine_summary(&m))+}++pub async fn install_runners(engine: &Arc<Engine>, req: InstallRunnersRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<ActionResponse> {+ let s = freshen(engine).await;+ let machine_id = find_machine(&s, &req.machine_id)?.id.clone();++ let scope = match req.scope.map(|x| x.trim().to_string()).filter(|x| !x.is_empty()) {+ Some(scope) => scope,+ None => {+ let settings = engine.settings();+ let watched: Vec<String> = settings.github.orgs.iter().chain(settings.github.repos.iter()).cloned().collect();+ match watched.as_slice() {+ [one] => one.clone(),+ [] => {+ return Err(ApiError::invalid("Say which GitHub org or repo to register the runners with (scope).").with_hint(surface.say(+ "Watch it first with github_scopes(add=[\"<org>\"]), or pass scope=\"<org>\" / \"owner/repo\".",+ "Watch it first with `openrunner watch <org>`, or pass --scope <org> / owner/repo.",+ )));+ }+ many => return Err(ApiError::invalid(format!("Several orgs/repos are watched ({}); pass scope.", many.join(", ")))),+ }+ }+ };++ let names = if req.names.is_empty() {+ let count = req.count.unwrap_or(1);+ if count == 0 || count > 32 {+ return Err(ApiError::invalid("count must be between 1 and 32."));+ }+ engine.suggest_runner_names(&machine_id, count)+ } else {+ req.names+ };++ let mode = InstallMode::parse(req.mode.as_deref().unwrap_or("auto"), req.image, req.docker_socket).map_err(ApiError::invalid)?;+ let op = engine+ .install_runners(InstallRequest {+ machine_id: machine_id.clone(),+ scope,+ names: names.clone(),+ labels: req.labels,+ group: req.runner_group,+ as_service: req.as_service,+ mode,+ })+ .map_err(op_error)?;+ finish_action(engine, op, req.wait, req.timeout_secs.unwrap_or(INSTALL_TIMEOUT_SECS), DEFAULT_TAIL, Some(machine_id), names, surface, on_line).await+}++pub async fn runner_action(engine: &Arc<Engine>, req: RunnerActionRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<ActionResponse> {+ let s = freshen(engine).await;+ let runner = find_runner(&s, &req.runner_id)?.clone();++ // Control needs the runner's folder from a machine check; get one if this process has none.+ if let Some(mid) = &runner.machine_id {+ let unchecked = s.machines.iter().find(|m| &m.id == mid).is_some_and(|m| m.probe.is_none());+ if unchecked && req.action != ActionName::Remove {+ engine.run_check(Some(vec![mid.clone()])).await;+ wait_checked(engine, mid, CHECK_WAIT).await;+ }+ }++ let action = match req.action {+ ActionName::Start => RunnerAction::Start,+ ActionName::Stop => RunnerAction::Stop,+ ActionName::Restart => RunnerAction::Restart,+ ActionName::Logs => RunnerAction::Logs,+ ActionName::Remove => RunnerAction::Remove { delete_files: req.delete_files },+ };+ let op = engine.runner_action(&runner.id, action).map_err(op_error)?;+ let tail = if req.action == ActionName::Logs { LOGS_TAIL } else { DEFAULT_TAIL };+ let timeout = req.timeout_secs.unwrap_or(ACTION_TIMEOUT_SECS);+ finish_action(engine, op, req.wait, timeout, tail, runner.machine_id.clone(), vec![runner.name.clone()], surface, on_line).await+}++#[allow(clippy::too_many_arguments)]+async fn finish_action(+ engine: &Arc<Engine>,+ op: u64,+ wait: bool,+ timeout_secs: u64,+ tail: usize,+ machine_id: Option<String>,+ runner_names: Vec<String>,+ surface: Surface,+ on_line: impl FnMut(&str),+) -> ApiResult<ActionResponse> {+ let operation = if wait {+ wait_operation(engine, op, Duration::from_secs(timeout_secs.max(1)), on_line).await+ } else {+ engine.current().operations.iter().find(|o| o.id == op).cloned()+ }+ .ok_or_else(|| ApiError::new("internal", format!("Operation {op} disappeared.")))?;++ let s = engine.current();+ let finished = operation.status != "running";+ let names: HashSet<String> = runner_names.iter().map(|n| n.to_ascii_lowercase()).collect();+ let response = ActionResponse {+ finished,+ machine: machine_id.as_ref().and_then(|id| s.machines.iter().find(|m| &m.id == id)).map(machine_summary),+ runners: s.runners.iter().filter(|r| names.contains(&r.name.to_ascii_lowercase())).map(|r| runner_out(&s, r)).collect(),+ next: (!finished).then(|| {+ surface.say(+ format!("Still running. Poll get_operation(operation_id={op}) until status isn't \"running\"."),+ "Still running in the background; this command stopped waiting. Check the result with `openrunner status`.",+ )+ }),+ operation: operation_out(&operation, tail),+ };++ if operation.status == "failed" {+ let message = operation.error.clone().unwrap_or_else(|| "The operation failed.".into());+ let hint = failure_hint(&message);+ return Err(ApiError {+ code: "operation_failed",+ message,+ hint,+ details: serde_json::to_value(&response).ok(),+ });+ }+ Ok(response)+}++/// A next step for common failures, when the message doesn't already carry one.+fn failure_hint(message: &str) -> Option<String> {+ let m = message.to_ascii_lowercase();+ if m.contains("admin:org") {+ Some("gh auth refresh -h github.com -s admin:org".into())+ } else if m.contains("sudo") {+ Some("Allow passwordless sudo for the runner user on that machine, or install with mode \"docker\" or \"background\".".into())+ } else if m.contains("timed out") || m.contains("connection refused") || m.contains("could not resolve") {+ Some("The machine didn't answer over ssh. Check that `ssh <host>` works without a password prompt.".into())+ } else {+ None+ }+}++pub async fn github_scopes(engine: &Arc<Engine>, req: GitHubScopesRequest) -> ApiResult<ScopesResponse> {+ engine.refresh_from_disk();+ let mut settings = engine.settings();+ let mut results = Vec::new();++ for raw in &req.remove {+ let name = crate::config::strip_github_url(raw);+ let before = settings.github.orgs.len() + settings.github.repos.len();+ settings.github.orgs.retain(|o| !o.eq_ignore_ascii_case(&name));+ settings.github.repos.retain(|r| !r.eq_ignore_ascii_case(&name));+ let removed = settings.github.orgs.len() + settings.github.repos.len() < before;+ results.push(ScopeResult {+ scope: name,+ result: if removed { "removed" } else { "not_watching" }.into(),+ runners: None,+ error: None,+ hint: None,+ });+ }++ for raw in &req.add {+ let name = crate::config::strip_github_url(raw);+ if name.is_empty() {+ continue;+ }+ let watched = settings.github.orgs.iter().chain(settings.github.repos.iter()).any(|x| x.eq_ignore_ascii_case(&name));+ if watched {+ results.push(ScopeResult { scope: name, result: "already_watching".into(), runners: None, error: None, hint: None });+ continue;+ }+ let t = engine.test_scope(&name).await;+ if t.error.is_none() {+ match t.kind {+ crate::github::ScopeKind::Repo => settings.github.repos.push(t.name.clone()),+ crate::github::ScopeKind::Org => settings.github.orgs.push(t.name.clone()),+ }+ results.push(ScopeResult { scope: t.name, result: "added".into(), runners: Some(t.runners), error: None, hint: None });+ } else {+ results.push(ScopeResult { scope: t.name, result: "failed".into(), runners: None, error: t.error, hint: t.hint });+ }+ }++ engine.update_settings(settings).map_err(ApiError::invalid)?;+ engine.sync_github().await;+ let s = engine.current();+ let watching = s+ .github+ .scopes+ .iter()+ .map(|sc| ScopeOut { kind: sc.kind.clone(), name: sc.name.clone(), runners: sc.runners, error: sc.error.clone(), hint: sc.hint.clone() })+ .collect();+ Ok(ScopesResponse { results, watching })+}++pub fn update_settings(engine: &Arc<Engine>, req: UpdateSettingsRequest) -> ApiResult<SettingsOut> {+ engine.refresh_from_disk();+ let mut s = engine.settings();+ if let Some(v) = req.github_poll_seconds {+ s.github_poll_seconds = v;+ }+ if let Some(v) = req.scan_repos {+ s.github.scan_repos = v;+ }+ if let Some(v) = req.check_interval_minutes {+ s.check_interval_minutes = v;+ }+ if let Some(v) = req.api_url {+ s.github.api_url = v;+ }+ engine.update_settings(s).map_err(ApiError::invalid)?;+ Ok(settings(engine))+}++// ---------------------------------------------------------------------------+// Workspaces: a persistent work environment on one of the user's machines.++const EXEC_DEFAULT_TIMEOUT_SECS: u64 = 600;+const EXEC_MAX_TIMEOUT_SECS: u64 = 3600;+const READ_DEFAULT_BYTES: usize = 256 * 1024;+const READ_MAX_BYTES: usize = 2 * 1024 * 1024;+const LIST_DEFAULT_DEPTH: u32 = 2;+const LIST_MAX_DEPTH: u32 = 10;+const HISTORY_IN_GET: usize = 20;++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct WorkspaceCreateRequest {+ /// Machine id to use. Omit to let OpenRunner pick the least-loaded online machine that allows workspaces.+ pub machine_id: Option<String>,+ /// When picking a machine: platform prefix it must match, e.g. "linux", "linux-x64", "darwin-arm64", "windows".+ pub platform: Option<String>,+ /// Short label, e.g. "api-tests". Defaults to the repo name.+ pub name: Option<String>,+ /// Git URL, or "owner/repo" for GitHub, to clone into the workspace.+ pub repo: Option<String>,+ /// Branch, tag or commit to check out.+ #[serde(rename = "ref")]+ pub git_ref: Option<String>,+ /// New branch to create and switch to after checkout.+ pub branch: Option<String>,+ /// "host" (default): run directly on the machine as its ssh user. "docker": a fresh+ /// container per workspace with the folder mounted at /workspace.+ #[serde(default)]+ pub isolation: Option<String>,+ /// Docker image for isolation "docker", e.g. "node:22", "python:3.13", "rust:1".+ #[serde(default)]+ pub image: Option<String>,+ /// Share the machine's Docker socket with the container (docker-in-docker; root-equivalent).+ #[serde(default)]+ pub docker_socket: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceRequest {+ /// Workspace id, e.g. "ws-7f3a2c".+ pub workspace_id: String,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceExecRequest {+ pub workspace_id: String,+ /// Shell command, run with the machine user's login shell environment.+ pub command: String,+ /// Folder relative to the workspace to run in.+ #[serde(default)]+ pub cwd: Option<String>,+ /// Extra environment variables.+ #[serde(default)]+ pub env: BTreeMap<String, String>,+ /// Kill it after this many seconds (default 600, max 3600). Ignored with background.+ #[serde(default)]+ pub timeout_secs: Option<u64>,+ /// Start it detached (servers, watchers) and return right away with its pid and log file.+ #[serde(default)]+ pub background: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceReadRequest {+ pub workspace_id: String,+ /// File path relative to the workspace.+ pub path: String,+ /// Read at most this many bytes (default 262144, max 2097152).+ #[serde(default)]+ pub max_bytes: Option<usize>,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceWriteRequest {+ pub workspace_id: String,+ /// File path relative to the workspace; parent folders are created.+ pub path: String,+ /// Text content (UTF-8).+ pub content: String,+ /// Append instead of replacing.+ #[serde(default)]+ pub append: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceFilesRequest {+ pub workspace_id: String,+ /// Folder relative to the workspace (default: the workspace itself).+ #[serde(default)]+ pub path: Option<String>,+ /// How deep to list (default 2, max 10).+ #[serde(default)]+ pub depth: Option<u32>,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceSyncRequest {+ pub workspace_id: String,+ /// Folder on this computer. Relative paths are resolved against this process's working directory.+ pub local_path: String,+ /// "push" copies the local folder into the workspace; "pull" copies the workspace into the local folder.+ pub direction: SyncDirection,+ /// Also delete files on the receiving side that the sending side doesn't have.+ #[serde(default)]+ pub delete: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceDestroyRequest {+ pub workspace_id: String,+ /// Keep the folder on the machine; only forget the workspace.+ #[serde(default)]+ pub keep_files: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WorkspaceAllowRequest {+ pub machine_id: String,+ /// Whether agents may create workspaces on the machine.+ pub allowed: bool,+}++#[derive(Debug, Clone, Serialize)]+pub struct WorkspaceOut {+ pub id: String,+ pub name: String,+ pub machine_id: String,+ pub machine_name: String,+ pub host: String,+ pub platform: String,+ /// Absolute path on the machine.+ pub path: String,+ pub repo: Option<String>,+ #[serde(rename = "ref")]+ pub git_ref: Option<String>,+ pub branch: Option<String>,+ pub owner: Option<String>,+ /// "host" or "docker".+ pub isolation: String,+ /// Docker image, for docker workspaces.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub image: Option<String>,+ /// Container name, for docker workspaces.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub container: Option<String>,+ /// "creating" | "ready" | "failed" | "destroying"+ pub status: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+ pub created_at: DateTime<Utc>,+ pub last_used_at: DateTime<Utc>,+ /// Total commands run here.+ pub commands: usize,+ /// For a human at a terminal: opens a shell in the workspace.+ pub shell: String,+ pub last_command: Option<CommandOut>,+ /// Recent commands, newest last (workspace_get only).+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub history: Vec<CommandOut>,+}++#[derive(Debug, Clone, Serialize)]+pub struct CommandOut {+ pub command: String,+ pub exit_code: Option<i32>,+ pub started_at: DateTime<Utc>,+ pub duration_ms: u64,+ pub background: bool,+ pub timed_out: bool,+ pub by: Option<String>,+ pub output_tail: Vec<String>,+}++#[derive(Debug, Serialize)]+pub struct WorkspacesResponse {+ pub summary: String,+ pub workspaces: Vec<WorkspaceOut>,+ /// Machines that accept new workspaces (allowed, and not known to be unreachable).+ pub available_machines: Vec<String>,+}++#[derive(Debug, Serialize)]+pub struct WorkspaceCreated {+ pub workspace: WorkspaceOut,+ pub next: String,+}++#[derive(Debug, Serialize)]+pub struct ExecOut {+ pub workspace_id: String,+ pub command: String,+ /// The command's exit status; null when it timed out or runs in the background.+ pub exit_code: Option<i32>,+ pub stdout: String,+ pub stderr: String,+ pub duration_ms: u64,+ pub timed_out: bool,+ /// Output was longer than the cap; the middle was dropped.+ pub truncated: bool,+ pub background_pid: Option<u32>,+ /// Background commands: where their output goes, relative to the workspace.+ pub log_path: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub next: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct FileOut {+ pub workspace_id: String,+ pub path: String,+ pub size: u64,+ pub truncated: bool,+ /// Not text; `content` is empty.+ pub binary: bool,+ pub content: String,+}++#[derive(Debug, Serialize)]+pub struct WriteOut {+ pub workspace_id: String,+ pub path: String,+ /// File size after the write, in bytes.+ pub size: u64,+}++#[derive(Debug, Serialize)]+pub struct FileEntryOut {+ pub path: String,+ /// "file" | "dir" | "link"+ pub kind: String,+ pub size: u64,+}++#[derive(Debug, Serialize)]+pub struct FilesOut {+ pub workspace_id: String,+ pub path: String,+ pub entries: Vec<FileEntryOut>,+}++#[derive(Debug, Serialize)]+pub struct ChangesOut {+ pub workspace_id: String,+ /// `git status` and the uncommitted diff (capped), or a note when it isn't a git checkout.+ pub changes: String,+}++#[derive(Debug, Serialize)]+pub struct SyncOut {+ pub workspace_id: String,+ pub local_path: String,+ pub direction: SyncDirection,+ pub summary: String,+}++#[derive(Debug, Serialize)]+pub struct DestroyOut {+ pub workspace_id: String,+ pub kept_files: bool,+}++#[derive(Debug, Serialize)]+pub struct AllowOut {+ pub machine_id: String,+ pub workspaces_allowed: bool,+}++fn command_out(c: &WorkspaceCommand) -> CommandOut {+ CommandOut {+ command: c.command.clone(),+ exit_code: c.exit_code,+ started_at: c.started_at,+ duration_ms: c.duration_ms,+ background: c.background,+ timed_out: c.timed_out,+ by: c.by.clone(),+ output_tail: c.output_tail.clone(),+ }+}++pub fn workspace_out(w: &WorkspaceInfo, history: usize) -> WorkspaceOut {+ let start = w.history.len().saturating_sub(history);+ WorkspaceOut {+ id: w.id.clone(),+ name: w.name.clone(),+ machine_id: w.machine_id.clone(),+ machine_name: w.machine_name.clone(),+ host: w.host.clone(),+ platform: w.platform.clone(),+ path: w.path.clone(),+ repo: w.repo.clone(),+ git_ref: w.git_ref.clone(),+ branch: w.branch.clone(),+ isolation: w.isolation.clone(),+ image: w.image.clone(),+ container: w.container.clone(),+ owner: w.owner.clone(),+ status: w.status.clone(),+ error: w.error.clone(),+ created_at: w.created_at,+ last_used_at: w.last_used_at,+ commands: w.commands,+ shell: w.shell.clone(),+ last_command: w.history.last().map(command_out),+ history: if history == 0 { Vec::new() } else { w.history[start..].iter().map(command_out).collect() },+ }+}++/// Maps a message from the workspace backend onto an error code.+fn ws_error(message: String, surface: Surface) -> ApiError {+ let m = message.to_ascii_lowercase();+ let code = if m.contains("not implemented") || m.contains("implemented yet") {+ "internal"+ } else if m.contains("no workspace") || m.contains("unknown workspace") || m.contains("isn't in fleet.toml") || m.contains("no machine") || m.contains("not found") {+ "not_found"+ } else if m.contains("unreachable")+ || m.contains("timed out")+ || m.contains("connection refused")+ || m.contains("could not resolve")+ || m.contains("didn't answer")+ || m.contains("no route to host")+ {+ "unreachable"+ } else if m.contains("still being created") || m.contains("being destroyed") || m.contains("busy") {+ "busy"+ } else {+ "invalid"+ };+ let mut err = ApiError::new(code, message);+ if code == "unreachable" {+ err = err.with_hint("The machine didn't answer over ssh. Check that `ssh <host>` works without a password prompt, or pick another machine.");+ } else if m.contains("doesn't allow") || m.contains("not allowed") || m.contains("disabled") {+ err = err.with_hint(surface.say(+ "Turn workspaces on for that machine (workspace_allow, the toggle in the app, or `workspaces = true` in fleet.toml), or pick another machine.",+ "Turn workspaces on for that machine (`openrunner workspace allow <machine-id>`, the toggle in the app, or `workspaces = true` in fleet.toml), or pick another machine.",+ ));+ } else if m.contains("rsync") {+ err = err.with_hint("Install rsync on both this computer and the machine.");+ } else if m.contains("docker isn't available") || m.contains("couldn't pull") || m.contains("couldn't start a container") {+ err = err.with_hint("Install Docker on that machine (and add the ssh user to the docker group), use isolation \"host\", or pick a machine where Docker works.");+ }+ err+}++/// The current workspaces, including ones other OpenRunner processes created.+fn current_workspaces(engine: &Arc<Engine>) -> Vec<WorkspaceInfo> {+ engine.refresh_from_disk();+ engine.workspaces()+}++fn find_workspace(engine: &Arc<Engine>, id: &str, surface: Surface) -> ApiResult<WorkspaceInfo> {+ let all = current_workspaces(engine);+ let id = id.trim();+ if let Some(w) = all.iter().find(|w| w.id == id) {+ return Ok(w.clone());+ }+ // A unique name works too, like machine names do.+ let by_name: Vec<&WorkspaceInfo> = all.iter().filter(|w| w.name.eq_ignore_ascii_case(id)).collect();+ if let [one] = by_name.as_slice() {+ return Ok((*one).clone());+ }+ Err(ApiError::not_found(format!("No workspace \"{id}\".")).with_hint(if all.is_empty() {+ surface.say("There are no workspaces; create one with workspace_create.", "There are no workspaces; create one with `openrunner workspace create`.")+ } else {+ let known = all.iter().map(|w| w.id.as_str()).collect::<Vec<_>>().join(", ");+ surface.say(+ &format!("Known workspaces: {known}. Or create one with workspace_create."),+ &format!("Known workspaces: {known}. Or create one with `openrunner workspace create`."),+ )+ }))+}++/// Paths inside a workspace must be relative and stay inside it.+fn workspace_path(raw: &str) -> ApiResult<String> {+ let p = raw.trim();+ let windows_abs = p.len() >= 2 && p.as_bytes()[1] == b':';+ if p.starts_with('/') || p.starts_with('\\') || p.starts_with('~') || windows_abs {+ return Err(ApiError::invalid(format!("\"{raw}\" isn't relative to the workspace.")).with_hint("Use a path relative to the workspace folder, e.g. \"src/main.rs\"."));+ }+ let mut depth: i32 = 0;+ for c in Path::new(&p.replace('\\', "/")).components() {+ match c {+ Component::ParentDir => depth -= 1,+ Component::Normal(_) => depth += 1,+ _ => {}+ }+ if depth < 0 {+ return Err(ApiError::invalid(format!("\"{raw}\" points outside the workspace.")));+ }+ }+ Ok(p.to_string())+}++pub fn workspaces_list(engine: &Arc<Engine>) -> WorkspacesResponse {+ let all = current_workspaces(engine);+ let s = engine.current();+ // Unchecked machines count: creating a workspace checks the machine first.+ let available: Vec<String> = s.machines.iter().filter(|m| m.workspaces_allowed && m.status != "offline").map(|m| m.id.clone()).collect();+ let ready = all.iter().filter(|w| w.status == "ready").count();+ WorkspacesResponse {+ summary: format!(+ "{} workspace{} ({} ready). {} machine{} available for new ones{}.",+ all.len(),+ plural(all.len()),+ ready,+ available.len(),+ plural(available.len()),+ if available.is_empty() { "" } else { ": " }.to_string() + &available.join(", ")+ ),+ workspaces: all.iter().map(|w| workspace_out(w, 0)).collect(),+ available_machines: available,+ }+}++pub fn workspace_get(engine: &Arc<Engine>, req: WorkspaceRequest, surface: Surface) -> ApiResult<WorkspaceOut> {+ Ok(workspace_out(&find_workspace(engine, &req.workspace_id, surface)?, HISTORY_IN_GET))+}++pub async fn workspace_create(engine: &Arc<Engine>, req: WorkspaceCreateRequest, owner: &str, surface: Surface) -> ApiResult<WorkspaceCreated> {+ engine.refresh_from_disk();+ let machine = match req.machine_id.as_deref().map(str::trim).filter(|m| !m.is_empty()) {+ Some(id) => {+ let s = engine.current();+ let m = find_machine(&s, id)?;+ if !m.workspaces_allowed {+ return Err(ApiError::invalid(format!("{} doesn't allow workspaces.", m.name))+ .with_hint(surface.say(+ format!("Turn them on with workspace_allow(machine_id=\"{}\", allowed=true) if the user agrees, or pick another machine.", m.id),+ format!("Turn them on with `openrunner workspace allow {}`, or pick another machine.", m.id),+ )));+ }+ Some(m.id.clone())+ }+ None => None,+ };+ let clean = |v: Option<String>| v.map(|x| x.trim().to_string()).filter(|x| !x.is_empty());+ let iso = crate::fleet::workspaces::WorkspaceIsolation {+ isolation: clean(req.isolation),+ image: clean(req.image),+ docker_socket: req.docker_socket,+ };+ let created = engine+ .create_workspace_with(+ CreateWorkspace {+ machine,+ platform: clean(req.platform),+ name: clean(req.name),+ repo: clean(req.repo),+ git_ref: clean(req.git_ref),+ branch: clean(req.branch),+ owner: Some(owner.to_string()),+ },+ iso,+ )+ .await+ .map_err(|e| ws_error(e, surface))?;+ let id = &created.id;+ let next = surface.say(+ format!("Run commands with workspace_exec(workspace_id=\"{id}\", command=...). Review edits with workspace_changes. Call workspace_destroy(workspace_id=\"{id}\") when the task is done."),+ format!("Run commands with `openrunner workspace exec {id} -- <command>`; review edits with `openrunner workspace changes {id}`; destroy it with `openrunner workspace rm {id}` when done."),+ );+ Ok(WorkspaceCreated { workspace: workspace_out(&created, 0), next })+}++pub async fn workspace_exec(engine: &Arc<Engine>, req: WorkspaceExecRequest, by: &str, surface: Surface) -> ApiResult<ExecOut> {+ let command = req.command.trim().to_string();+ if command.is_empty() {+ return Err(ApiError::invalid("command is empty."));+ }+ let timeout = req.timeout_secs.unwrap_or(EXEC_DEFAULT_TIMEOUT_SECS);+ if timeout == 0 || timeout > EXEC_MAX_TIMEOUT_SECS {+ return Err(ApiError::invalid(format!("timeout_secs must be between 1 and {EXEC_MAX_TIMEOUT_SECS}."))+ .with_hint(surface.say("For longer work, run it with background=true and read its log file.", "For longer work, run it with --background and read its log file.")));+ }+ for key in req.env.keys() {+ let valid = !key.is_empty() && !key.starts_with(|c: char| c.is_ascii_digit()) && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');+ if !valid {+ return Err(ApiError::invalid(format!("\"{key}\" isn't a valid environment variable name.")));+ }+ }+ let cwd = req.cwd.as_deref().map(workspace_path).transpose()?.filter(|c| !c.is_empty() && c != ".");+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ let result = engine+ .workspace_exec(+ &w.id,+ &command,+ ExecOptions {+ timeout_secs: Some(timeout),+ env: req.env.into_iter().collect(),+ cwd,+ background: req.background,+ by: Some(by.to_string()),+ },+ )+ .await+ .map_err(|e| ws_error(e, surface))?;+ let pid = result.background_pid.map(|p| p.to_string()).unwrap_or_else(|| "?".into());+ let next = if let Some(log) = &result.log_path {+ Some(surface.say(+ format!("Running in the background (pid {pid}). Read its output with workspace_read_file(path=\"{log}\") or workspace_exec(command=\"tail -n 50 {log}\")."),+ format!("Running in the background (pid {pid}). Read its output with `openrunner workspace cat {} {log}`.", w.id),+ ))+ } else if result.timed_out {+ Some(surface.say(+ format!("Killed after {timeout}s. Raise timeout_secs (max {EXEC_MAX_TIMEOUT_SECS}) or run it with background=true."),+ format!("Killed after {timeout}s. Raise --timeout (max {EXEC_MAX_TIMEOUT_SECS}) or run it with --background."),+ ))+ } else {+ None+ };+ Ok(ExecOut {+ workspace_id: w.id,+ command,+ exit_code: result.exit_code,+ stdout: result.stdout,+ stderr: result.stderr,+ duration_ms: result.duration_ms,+ timed_out: result.timed_out,+ truncated: result.truncated,+ background_pid: result.background_pid,+ log_path: result.log_path,+ next,+ })+}++pub async fn workspace_read_file(engine: &Arc<Engine>, req: WorkspaceReadRequest, surface: Surface) -> ApiResult<FileOut> {+ let path = workspace_path(&req.path)?;+ if path.is_empty() {+ return Err(ApiError::invalid("path is empty."));+ }+ let max = req.max_bytes.unwrap_or(READ_DEFAULT_BYTES);+ if max == 0 || max > READ_MAX_BYTES {+ return Err(ApiError::invalid(format!("max_bytes must be between 1 and {READ_MAX_BYTES}.")));+ }+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ let f = engine.workspace_read_file(&w.id, &path, max).await.map_err(|e| ws_error(e, surface))?;+ Ok(FileOut { workspace_id: w.id, path: f.path, size: f.size, truncated: f.truncated, binary: f.binary, content: f.content })+}++pub async fn workspace_write_file(engine: &Arc<Engine>, req: WorkspaceWriteRequest, surface: Surface) -> ApiResult<WriteOut> {+ let path = workspace_path(&req.path)?;+ if path.is_empty() || path.ends_with('/') {+ return Err(ApiError::invalid("path must name a file."));+ }+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ let size = engine.workspace_write_file(&w.id, &path, &req.content, req.append).await.map_err(|e| ws_error(e, surface))?;+ Ok(WriteOut { workspace_id: w.id, path, size })+}++pub async fn workspace_list_files(engine: &Arc<Engine>, req: WorkspaceFilesRequest, surface: Surface) -> ApiResult<FilesOut> {+ let path = workspace_path(req.path.as_deref().unwrap_or(""))?;+ let depth = req.depth.unwrap_or(LIST_DEFAULT_DEPTH);+ if depth == 0 || depth > LIST_MAX_DEPTH {+ return Err(ApiError::invalid(format!("depth must be between 1 and {LIST_MAX_DEPTH}.")));+ }+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ let entries = engine.workspace_list_files(&w.id, &path, depth).await.map_err(|e| ws_error(e, surface))?;+ Ok(FilesOut {+ workspace_id: w.id,+ path: if path.is_empty() { ".".into() } else { path },+ entries: entries.into_iter().map(|e| FileEntryOut { path: e.path, kind: e.kind, size: e.size }).collect(),+ })+}++pub async fn workspace_changes(engine: &Arc<Engine>, req: WorkspaceRequest, surface: Surface) -> ApiResult<ChangesOut> {+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ let changes = engine.workspace_changes(&w.id).await.map_err(|e| ws_error(e, surface))?;+ Ok(ChangesOut { workspace_id: w.id, changes })+}++pub async fn workspace_sync(engine: &Arc<Engine>, req: WorkspaceSyncRequest, surface: Surface) -> ApiResult<SyncOut> {+ let raw = req.local_path.trim();+ if raw.is_empty() {+ return Err(ApiError::invalid("local_path is empty."));+ }+ let expanded = match raw.strip_prefix("~/") {+ Some(rest) => dirs::home_dir().map(|h| h.join(rest)).unwrap_or_else(|| raw.into()),+ None => std::path::PathBuf::from(raw),+ };+ let local = if expanded.is_absolute() {+ expanded+ } else {+ std::env::current_dir().map(|d| d.join(&expanded)).unwrap_or(expanded)+ };+ if req.direction == SyncDirection::Push && !local.is_dir() {+ return Err(ApiError::invalid(format!("{} isn't a folder on this computer.", local.display())));+ }+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ let local_str = local.display().to_string();+ let summary = engine.workspace_sync(&w.id, &local_str, req.direction, req.delete).await.map_err(|e| ws_error(e, surface))?;+ Ok(SyncOut { workspace_id: w.id, local_path: local_str, direction: req.direction, summary })+}++pub async fn workspace_destroy(engine: &Arc<Engine>, req: WorkspaceDestroyRequest, surface: Surface) -> ApiResult<DestroyOut> {+ let w = find_workspace(engine, &req.workspace_id, surface)?;+ engine.destroy_workspace(&w.id, req.keep_files).await.map_err(|e| ws_error(e, surface))?;+ Ok(DestroyOut { workspace_id: w.id, kept_files: req.keep_files })+}++pub fn workspace_allow(engine: &Arc<Engine>, req: WorkspaceAllowRequest, surface: Surface) -> ApiResult<AllowOut> {+ engine.refresh_from_disk();+ let s = engine.current();+ let m = find_machine(&s, &req.machine_id)?;+ if m.host.is_empty() {+ return Err(ApiError::invalid(format!("{} has no host in fleet.toml, so it can't host workspaces.", m.name)));+ }+ let id = m.id.clone();+ engine.set_workspaces_allowed(&id, req.allowed).map_err(|e| ws_error(e, surface))?;+ Ok(AllowOut { machine_id: id, workspaces_allowed: req.allowed })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config::Paths;++ fn demo() -> Arc<Engine> {+ Engine::new(Paths::resolve(Some(std::env::temp_dir().join("openrunner-api-test")), None), true)+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn status_reads_the_demo_fleet() {+ let engine = demo();+ let s = status(&engine, StatusRequest { refresh: true }, Surface::Mcp).await.unwrap();+ assert_eq!(s.counts.machines, 9);+ assert!(s.demo && s.github.live);+ assert!(s.summary.contains("9 machines"), "{}", s.summary);+ let laravel = s.machines.iter().find(|m| m.id == "laravel-macbook").unwrap();+ assert_eq!(laravel.status, "offline");+ assert!(laravel.error.is_some());+ assert!(s.attention.iter().any(|a| a.machine_id.as_deref() == Some("laravel-macbook")));++ let err = machine(&engine, MachineRequest { machine_id: "nope".into() }).await.unwrap_err();+ assert_eq!(err.code, "not_found");+ assert!(err.hint.unwrap().contains("mac-studio"));+ let m = machine(&engine, MachineRequest { machine_id: "Mac Studio".into() }).await.unwrap();+ assert_eq!(m.runners.len(), 7);+ assert!(runners(&engine, RunnersRequest { state: Some("busy".into()), ..Default::default() }).await.is_err());+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn adds_a_machine_and_controls_its_runner() {+ let engine = demo();+ engine.run_check(None).await;++ let added = add_machine(&engine, AddMachineRequest { name: "Beelink".into(), host: "beelink".into(), check: true }, Surface::Mcp).await.unwrap();+ assert_eq!(added.machine_id, "beelink");+ assert_eq!(added.machine.as_ref().unwrap().summary.status, "online");++ let mut lines = 0;+ let installed = install_runners(+ &engine,+ InstallRunnersRequest {+ machine_id: "beelink".into(),+ scope: None, // the demo watches exactly one org+ names: vec![],+ count: Some(1),+ labels: vec!["gpu".into()],+ runner_group: None,+ as_service: true,+ mode: None,+ image: None,+ docker_socket: false,+ wait: true,+ timeout_secs: Some(60),+ },+ Surface::Mcp,+ |_| lines += 1,+ )+ .await+ .unwrap();+ assert!(installed.finished && installed.operation.status == "succeeded", "{:?}", installed.operation);+ assert!(lines > 5);+ assert_eq!(installed.runners.len(), 1);+ let rid = installed.runners[0].id.clone();+ assert_eq!(rid, "beelink/beelink-01");++ let act = |action, wait| RunnerActionRequest { runner_id: rid.clone(), action, delete_files: true, wait, timeout_secs: Some(30) };+ let logs = runner_action(&engine, act(ActionName::Logs, true), Surface::Mcp, |_| {}).await.unwrap();+ assert!(!logs.operation.log_tail.is_empty());+ let stopped = runner_action(&engine, act(ActionName::Stop, true), Surface::Mcp, |_| {}).await.unwrap();+ assert_eq!(stopped.runners[0].state, "offline");+ let started = runner_action(&engine, act(ActionName::Start, false), Surface::Mcp, |_| {}).await.unwrap();+ assert!(!started.finished && started.next.is_some());+ let op = wait_operation(&engine, started.operation.id, Duration::from_secs(30), |_| {}).await.unwrap();+ assert_eq!(op.status, "succeeded");+ assert_eq!(operation(&engine, OperationRequest { operation_id: op.id, tail: Some(1) }).unwrap().log_tail.len(), 1);++ let removed = runner_action(&engine, act(ActionName::Remove, true), Surface::Mcp, |_| {}).await.unwrap();+ assert!(removed.runners.is_empty());+ remove_machine(&engine, MachineRequest { machine_id: "beelink".into() }).await.unwrap();+ assert!(!engine.current().machines.iter().any(|m| m.id == "beelink"));++ // Installing on the unreachable laptop fails as an operation, with a hint.+ let err = install_runners(+ &engine,+ InstallRunnersRequest {+ machine_id: "laravel-macbook".into(),+ scope: Some("acme".into()),+ names: vec!["laravel-01".into()],+ count: None,+ labels: vec![],+ runner_group: None,+ as_service: true,+ mode: None,+ image: None,+ docker_socket: false,+ wait: true,+ timeout_secs: Some(30),+ },+ Surface::Mcp,+ |_| {},+ )+ .await+ .unwrap_err();+ assert_eq!(err.code, "operation_failed");+ assert!(err.hint.is_some() && err.details.is_some());+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn hints_name_the_callers_next_step() {+ // A fresh demo engine: nothing checked yet.+ let engine = demo();+ let s = engine.current();+ assert!(status_from(&s, Surface::Mcp).hint.unwrap().contains("check_machines"));+ let cli = status_from(&s, Surface::Cli).hint.unwrap();+ assert!(cli.contains("openrunner status --refresh") && !cli.contains("check_machines"), "{cli}");+ }++ #[test]+ fn workspace_paths_stay_inside() {+ assert_eq!(workspace_path("src/main.rs").unwrap(), "src/main.rs");+ assert_eq!(workspace_path("a/../b").unwrap(), "a/../b");+ assert_eq!(workspace_path("").unwrap(), "");+ for bad in ["/etc/passwd", "~/x", "../x", "a/../../x", "C:\\x", "\\\\server\\x"] {+ assert_eq!(workspace_path(bad).unwrap_err().code, "invalid", "{bad}");+ }+ }++ #[test]+ fn workspace_errors_map_to_codes() {+ assert_eq!(ws_error("No workspace \"ws-x\".".into(), Surface::Mcp).code, "not_found");+ assert_eq!(ws_error("ssh: connect to host x port 22: Operation timed out".into(), Surface::Mcp).code, "unreachable");+ assert_eq!(ws_error("Workspaces aren't implemented yet.".into(), Surface::Mcp).code, "internal");+ assert!(ws_error("Mac Studio doesn't allow workspaces.".into(), Surface::Cli).hint.unwrap().contains("openrunner workspace allow"));+ let e = ws_error("Mac Studio doesn't allow workspaces.".into(), Surface::Mcp);+ assert_eq!(e.code, "invalid");+ assert!(e.hint.unwrap().contains("workspace_allow"));+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn workspace_requests_are_validated_before_the_backend() {+ let engine = demo();+ let exec = |command: &str, timeout: Option<u64>, cwd: Option<&str>| WorkspaceExecRequest {+ workspace_id: "ws-nope".into(),+ command: command.into(),+ cwd: cwd.map(str::to_string),+ env: BTreeMap::new(),+ timeout_secs: timeout,+ background: false,+ };+ assert_eq!(workspace_exec(&engine, exec(" ", None, None), "test", Surface::Mcp).await.unwrap_err().code, "invalid");+ assert_eq!(workspace_exec(&engine, exec("ls", Some(0), None), "test", Surface::Mcp).await.unwrap_err().code, "invalid");+ assert_eq!(workspace_exec(&engine, exec("ls", Some(99_999), None), "test", Surface::Mcp).await.unwrap_err().code, "invalid");+ assert_eq!(workspace_exec(&engine, exec("ls", None, Some("../..")), "test", Surface::Mcp).await.unwrap_err().code, "invalid");+ let mut bad_env = exec("ls", None, None);+ bad_env.env.insert("1BAD".into(), "x".into());+ assert_eq!(workspace_exec(&engine, bad_env, "test", Surface::Mcp).await.unwrap_err().code, "invalid");+ // Valid input, unknown workspace.+ let missing = workspace_exec(&engine, exec("ls", None, Some("src")), "test", Surface::Cli).await.unwrap_err();+ assert!(missing.hint.as_deref().unwrap_or_default().contains("openrunner workspace create"), "{missing:?}");+ assert_eq!(missing.code, "not_found");++ let read = WorkspaceReadRequest { workspace_id: "ws-nope".into(), path: "/etc/hosts".into(), max_bytes: None };+ assert_eq!(workspace_read_file(&engine, read, Surface::Mcp).await.unwrap_err().code, "invalid");+ let files = WorkspaceFilesRequest { workspace_id: "ws-nope".into(), path: None, depth: Some(50) };+ assert_eq!(workspace_list_files(&engine, files, Surface::Mcp).await.unwrap_err().code, "invalid");+ let sync = WorkspaceSyncRequest {+ workspace_id: "ws-nope".into(),+ local_path: "/definitely/not/a/folder".into(),+ direction: SyncDirection::Push,+ delete: false,+ };+ assert_eq!(workspace_sync(&engine, sync, Surface::Mcp).await.unwrap_err().code, "invalid");+ let create = WorkspaceCreateRequest { machine_id: Some("nope".into()), ..Default::default() };+ assert_eq!(workspace_create(&engine, create, "test", Surface::Mcp).await.unwrap_err().code, "not_found");+ assert_eq!(workspace_allow(&engine, WorkspaceAllowRequest { machine_id: "nope".into(), allowed: true }, Surface::Mcp).unwrap_err().code, "not_found");+ }++ /// Needs the workspace backend (src/fleet/workspaces.rs); run with `cargo test -- --ignored`+ /// once it's implemented. Exercises the whole agent flow on the demo fleet.+ #[tokio::test(flavor = "multi_thread")]+ #[ignore = "needs the workspace backend"]+ async fn workspace_flow_in_demo() {+ let engine = demo();+ engine.run_check(None).await;+ let created = workspace_create(+ &engine,+ WorkspaceCreateRequest { platform: Some("linux".into()), repo: Some("acme/api".into()), ..Default::default() },+ "test-agent",+ Surface::Mcp,+ )+ .await+ .unwrap();+ let id = created.workspace.id.clone();+ assert_eq!(created.workspace.status, "ready");+ assert_eq!(created.workspace.owner.as_deref(), Some("test-agent"));+ assert!(created.workspace.platform.starts_with("linux"));++ let ran = workspace_exec(+ &engine,+ WorkspaceExecRequest { workspace_id: id.clone(), command: "pwd".into(), cwd: None, env: BTreeMap::new(), timeout_secs: None, background: false },+ "test-agent",+ Surface::Mcp,+ )+ .await+ .unwrap();+ assert_eq!(ran.exit_code, Some(0));++ workspace_write_file(&engine, WorkspaceWriteRequest { workspace_id: id.clone(), path: "notes/a.txt".into(), content: "hi".into(), append: false }, Surface::Mcp)+ .await+ .unwrap();+ let read = workspace_read_file(&engine, WorkspaceReadRequest { workspace_id: id.clone(), path: "notes/a.txt".into(), max_bytes: None }, Surface::Mcp).await.unwrap();+ assert_eq!(read.content, "hi");+ let files = workspace_list_files(&engine, WorkspaceFilesRequest { workspace_id: id.clone(), path: None, depth: None }, Surface::Mcp).await.unwrap();+ assert!(!files.entries.is_empty());+ workspace_changes(&engine, WorkspaceRequest { workspace_id: id.clone() }, Surface::Mcp).await.unwrap();++ let got = workspace_get(&engine, WorkspaceRequest { workspace_id: id.clone() }, Surface::Mcp).unwrap();+ assert!(got.commands >= 1 && !got.history.is_empty());+ assert!(workspaces_list(&engine).workspaces.iter().any(|w| w.id == id));++ workspace_destroy(&engine, WorkspaceDestroyRequest { workspace_id: id.clone(), keep_files: false }, Surface::Mcp).await.unwrap();+ assert_eq!(workspace_get(&engine, WorkspaceRequest { workspace_id: id }, Surface::Mcp).unwrap_err().code, "not_found");+ }+}diff --git a/src/cli.rs b/src/cli.rsnew file mode 100644index 0000000..2eddb7f--- /dev/null+++ b/src/cli.rs@@ -0,0 +1,383 @@+//! Plain-text renderings of API responses for people at a terminal. Agents+//! should use `--json` (or the MCP server) instead; these are free to change.++use std::fmt::Write;++use crate::api::{+ ActionResponse, AddMachineResponse, ApiError, CommandOut, FileOut, FilesOut, JobOut, JobsResponse, MachineDetail,+ MachineSummary, RunnerOut, ScopesResponse, SettingsOut, StatusResponse, WorkspaceCreated, WorkspaceOut,+ WorkspacesResponse,+};+use crate::util;++pub fn status(s: &StatusResponse) -> String {+ let mut out = String::new();+ let _ = writeln!(out, "{}", s.summary);+ let g = &s.github;+ let gh = if g.live {+ let names: Vec<&str> = g.watching.iter().map(|w| w.name.as_str()).collect();+ format!("live from {}", names.join(", "))+ } else if g.configured {+ "configured, not reachable".to_string()+ } else {+ "not watching any org".to_string()+ };+ let _ = writeln!(out, "GitHub: {gh}{}", g.login.as_ref().map(|l| format!(" (as {l})")).unwrap_or_default());+ if let Some(h) = &g.hint {+ let _ = writeln!(out, " hint: {h}");+ }+ out.push('\n');+ out.push_str(&machines(&s.machines));+ if !s.attention.is_empty() {+ let _ = writeln!(out, "\nNeeds attention:");+ for a in &s.attention {+ let mark = match a.level.as_str() {+ "error" => "✖",+ "warning" => "!",+ _ => "·",+ };+ let _ = writeln!(out, " {mark} {}", a.title);+ if !a.detail.is_empty() {+ let _ = writeln!(out, " {}", a.detail);+ }+ }+ }+ if let Some(h) = &s.hint {+ let _ = writeln!(out, "\n{h}");+ }+ out+}++pub fn machines(list: &[MachineSummary]) -> String {+ if list.is_empty() {+ return "No machines. Add one with `openrunner add-machine --name <name> --host <ssh-host>`.\n".into();+ }+ let rows: Vec<Vec<String>> = list+ .iter()+ .map(|m| {+ vec![+ m.id.clone(),+ m.status.clone(),+ dash(&m.platform),+ m.runners.clone(),+ m.cpu_pct.map(|v| format!("{v:.0}%")).unwrap_or_else(|| "—".into()),+ m.mem_pct.map(|v| format!("{v:.0}%")).unwrap_or_else(|| "—".into()),+ m.disk_free.clone().unwrap_or_else(|| "—".into()),+ m.uptime.clone().unwrap_or_else(|| "—".into()),+ match (m.problems, m.worst.as_deref()) {+ (0, Some("unknown")) => "unknown".into(),+ (0, _) => "ok".into(),+ (n, _) => format!("{n} problem{}", if n == 1 { "" } else { "s" }),+ },+ ]+ })+ .collect();+ table(&["MACHINE", "STATUS", "PLATFORM", "RUNNERS", "CPU", "MEM", "DISK FREE", "UPTIME", "HEALTH"], &rows)+}++pub fn machine(m: &MachineDetail) -> String {+ let s = &m.summary;+ let mut out = String::new();+ let _ = writeln!(out, "{} ({}) {}", s.name, s.id, s.status);+ let _ = writeln!(+ out,+ "{} · {}{}",+ if s.host.is_empty() { "no host" } else { &s.host },+ dash(&s.platform),+ m.os_version.as_ref().map(|v| format!(" · {v}")).unwrap_or_default()+ );+ if let Some(e) = &s.error {+ let _ = writeln!(out, "error: {e}");+ }+ if s.status == "online" {+ let _ = writeln!(+ out,+ "cpu {} mem {} disk free {} up {}",+ s.cpu_pct.map(|v| format!("{v:.0}%")).unwrap_or_else(|| "—".into()),+ s.mem_pct.map(|v| format!("{v:.0}%")).unwrap_or_else(|| "—".into()),+ s.disk_free.clone().unwrap_or_else(|| "—".into()),+ s.uptime.clone().unwrap_or_else(|| "—".into())+ );+ }+ out.push('\n');+ out.push_str(&runners(&m.runners));+ if !m.diagnostics.is_empty() {+ let _ = writeln!(out, "\nDiagnostics:");+ for d in &m.diagnostics {+ let _ = writeln!(out, " [{}] {}", d.level, d.message);+ if let Some(h) = &d.hint {+ let _ = writeln!(out, " {h}");+ }+ }+ }+ out+}++pub fn added_machine(r: &AddMachineResponse) -> String {+ let mut out = format!("Added {}", r.machine_id);+ if let Some(m) = &r.machine {+ let _ = write!(out, ": {} {} {}", m.summary.status, dash(&m.summary.platform), m.summary.runners);+ if let Some(e) = &m.summary.error {+ let _ = write!(out, "\n {e}");+ }+ }+ let _ = writeln!(out, "\n{}", r.next);+ out+}++pub fn runners(list: &[RunnerOut]) -> String {+ if list.is_empty() {+ return "No runners.\n".into();+ }+ let rows: Vec<Vec<String>> = list+ .iter()+ .map(|r| {+ vec![+ r.id.clone(),+ r.state.clone(),+ match r.source.as_str() {+ "github" => "live".into(),+ "probe" => "last check".into(),+ _ => "—".into(),+ },+ r.version.clone().unwrap_or_else(|| "—".into()),+ r.service_state.clone().unwrap_or_else(|| "—".into()),+ r.job.as_ref().map(|j| format!("{} ({})", j.name, j.repo)).unwrap_or_default(),+ ]+ })+ .collect();+ table(&["RUNNER", "STATE", "SOURCE", "VERSION", "SERVICE", "JOB"], &rows)+}++pub fn jobs(j: &JobsResponse) -> String {+ let mut out = format!("{}\n", j.summary);+ let line = |out: &mut String, job: &JobOut, running: bool| {+ let age = util::short_duration(job.age_secs.max(0) as u64);+ let _ = writeln!(+ out,+ " {} {} {} · {} [{}] {}{}",+ if running { "▶" } else { "…" },+ job.name,+ job.repo,+ job.workflow,+ job.labels.join(", "),+ if running { format!("running {age}") } else { format!("waiting {age}") },+ match (&job.runner_id, running) {+ (Some(r), true) => format!(" on {r}"),+ (_, false) if job.matching_online == 0 => " — no online runner matches".into(),+ _ => String::new(),+ }+ );+ };+ for job in &j.running {+ line(&mut out, job, true);+ }+ for job in &j.queued {+ line(&mut out, job, false);+ }+ if let Some(h) = &j.hint {+ let _ = writeln!(out, "{h}");+ }+ out+}++pub fn action(r: &ActionResponse) -> String {+ let o = &r.operation;+ let mut out = String::new();+ match o.status.as_str() {+ "succeeded" => {+ let _ = writeln!(out, "✓ {} (operation {})", o.title, o.id);+ }+ "running" => {+ let _ = writeln!(out, "… {} is still running (operation {})", o.title, o.id);+ }+ _ => {+ let _ = writeln!(out, "✖ {} failed: {}", o.title, o.error.clone().unwrap_or_default());+ }+ }+ // The log already streamed to stderr while we waited; logs are the exception people want on stdout.+ if o.kind == "logs" {+ for l in &o.log_tail {+ let _ = writeln!(out, "{l}");+ }+ }+ for runner in &r.runners {+ let _ = writeln!(out, " {} {}", runner.id, runner.state);+ }+ if let Some(n) = &r.next {+ let _ = writeln!(out, "{n}");+ }+ out+}++pub fn scopes(r: &ScopesResponse) -> String {+ let mut out = String::new();+ for res in &r.results {+ let _ = write!(out, "{}: {}", res.scope, res.result.replace('_', " "));+ if let Some(n) = res.runners {+ let _ = write!(out, " ({n} runner{})", if n == 1 { "" } else { "s" });+ }+ if let Some(e) = &res.error {+ let _ = write!(out, " — {e}");+ }+ out.push('\n');+ if let Some(h) = &res.hint {+ let _ = writeln!(out, " hint: {h}");+ }+ }+ let watching: Vec<String> = r.watching.iter().map(|w| format!("{} ({})", w.name, w.runners)).collect();+ let _ = writeln!(out, "Watching: {}", if watching.is_empty() { "nothing".into() } else { watching.join(", ") });+ out+}++pub fn settings(s: &SettingsOut) -> String {+ format!(+ "orgs {}\nrepos {}\ngithub poll {}s\nscan repos per org {}\ncheck interval {}\napi url {}\nconfig dir {}\ninventory {}\n",+ dash(&s.github_orgs.join(", ")),+ dash(&s.github_repos.join(", ")),+ s.github_poll_seconds,+ s.scan_repos,+ if s.check_interval_minutes == 0 { "off".to_string() } else { format!("{}m", s.check_interval_minutes) },+ s.api_url,+ s.config_dir,+ s.inventory+ )+}++pub fn workspaces(r: &WorkspacesResponse) -> String {+ let mut out = format!("{}\n", r.summary);+ if r.workspaces.is_empty() {+ out.push_str("Create one with `openrunner workspace create [--machine <id>] [--repo owner/repo]`.\n");+ return out;+ }+ out.push('\n');+ let rows: Vec<Vec<String>> = r+ .workspaces+ .iter()+ .map(|w| {+ vec![+ w.id.clone(),+ w.name.clone(),+ w.status.clone(),+ w.machine_id.clone(),+ w.repo.clone().map(|r| match w.branch.as_ref().or(w.git_ref.as_ref()) {+ Some(at) => format!("{r}@{at}"),+ None => r,+ }).unwrap_or_else(|| "—".into()),+ w.owner.clone().unwrap_or_else(|| "—".into()),+ format!("{}", w.commands),+ ago(w.last_used_at),+ ]+ })+ .collect();+ out.push_str(&table(&["WORKSPACE", "NAME", "STATUS", "MACHINE", "REPO", "OWNER", "CMDS", "USED"], &rows));+ out+}++pub fn workspace_created(r: &WorkspaceCreated) -> String {+ let w = &r.workspace;+ format!(+ "✓ {} ({}) on {} · {}\n shell: {}\nRun commands with `openrunner workspace exec {} -- <command>`; destroy it with `openrunner workspace rm {}`.\n",+ w.id, w.name, w.machine_name, w.path, w.shell, w.id, w.id+ )+}++pub fn workspace(w: &WorkspaceOut) -> String {+ let mut out = String::new();+ let _ = writeln!(out, "{} ({}) {}", w.name, w.id, w.status);+ let _ = writeln!(out, "{} ({}) · {} · {}", w.machine_name, w.machine_id, dash(&w.platform), w.path);+ if let Some(repo) = &w.repo {+ let at = w.branch.as_ref().or(w.git_ref.as_ref()).map(|r| format!(" @ {r}")).unwrap_or_default();+ let _ = writeln!(out, "repo {repo}{at}");+ }+ let _ = writeln!(+ out,+ "owner {} · created {} · used {} · {} command{}",+ w.owner.as_deref().unwrap_or("—"),+ ago(w.created_at),+ ago(w.last_used_at),+ w.commands,+ if w.commands == 1 { "" } else { "s" }+ );+ if let Some(e) = &w.error {+ let _ = writeln!(out, "error: {e}");+ }+ let _ = writeln!(out, "shell: {}", w.shell);+ if !w.history.is_empty() {+ let _ = writeln!(out, "\nRecent commands:");+ for c in &w.history {+ let _ = writeln!(out, " {} {}", exit_mark(c), c.command);+ }+ }+ out+}++fn exit_mark(c: &CommandOut) -> String {+ match (c.exit_code, c.timed_out, c.background) {+ (_, true, _) => "[timeout]".into(),+ (_, _, true) => "[bg]".into(),+ (Some(code), _, _) => format!("[{code}]"),+ (None, _, _) => "[…]".into(),+ }+}++pub fn file(f: &FileOut) -> String {+ if f.binary {+ return format!("{} is a binary file ({} bytes); not shown.\n", f.path, f.size);+ }+ let mut out = f.content.clone();+ if f.truncated {+ if !out.ends_with('\n') {+ out.push('\n');+ }+ out.push_str(&format!("[truncated: {} of {} bytes shown]\n", f.content.len(), f.size));+ }+ out+}++pub fn files(f: &FilesOut) -> String {+ if f.entries.is_empty() {+ return format!("{} is empty.\n", f.path);+ }+ let rows: Vec<Vec<String>> = f+ .entries+ .iter()+ .map(|e| vec![if e.kind == "dir" { format!("{}/", e.path) } else { e.path.clone() }, if e.kind == "file" { util::bytes(e.size) } else { e.kind.clone() }])+ .collect();+ table(&["PATH", "SIZE"], &rows)+}++fn ago(t: chrono::DateTime<chrono::Utc>) -> String {+ let secs = (chrono::Utc::now() - t).num_seconds().max(0) as u64;+ if secs < 10 { "just now".into() } else { format!("{} ago", util::short_duration(secs)) }+}++pub fn error(e: &ApiError) -> String {+ let mut out = format!("error: {}\n", e.message);+ if let Some(h) = &e.hint {+ let _ = writeln!(out, "hint: {h}");+ }+ out+}++fn dash(s: &str) -> String {+ if s.is_empty() { "—".into() } else { s.to_string() }+}++fn table(headers: &[&str], rows: &[Vec<String>]) -> String {+ let mut widths: Vec<usize> = headers.iter().map(|h| h.chars().count()).collect();+ for r in rows {+ for (i, c) in r.iter().enumerate() {+ widths[i] = widths[i].max(c.chars().count());+ }+ }+ let fmt = |cells: Vec<String>| -> String {+ let line: Vec<String> = cells.iter().enumerate().map(|(i, c)| format!("{c:<w$}", w = widths[i])).collect();+ format!("{}\n", line.join(" ").trim_end())+ };+ let mut out = fmt(headers.iter().map(|h| h.to_string()).collect());+ for r in rows {+ out.push_str(&fmt(r.clone()));+ }+ out+}diff --git a/src/config.rs b/src/config.rsnew file mode 100644index 0000000..820facb--- /dev/null+++ b/src/config.rs@@ -0,0 +1,429 @@+//! On-disk configuration.+//!+//! - `fleet.toml` — the inventory: machines and the runners they host. Edited by hand.+//! - `settings.json` — app settings changed from the dashboard (GitHub orgs/repos, intervals).+//! - `state.json` — the last machine check, so a restart still shows "checked 42m ago".++use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};++use anyhow::{Context, Result};+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};++use crate::probe::{ProbeResult, Shell};+use crate::util::slug;++#[derive(Debug, Clone)]+pub struct Paths {+ pub dir: PathBuf,+ pub inventory: PathBuf,+ pub settings: PathBuf,+ pub state: PathBuf,+ /// Agent workspaces, shared by every OpenRunner process (see fleet::workspaces).+ pub workspaces: PathBuf,+}++impl Paths {+ /// `$OPENRUNNER_HOME`, else `$XDG_CONFIG_HOME/openrunner`, else `~/.config/openrunner`.+ pub fn resolve(dir: Option<PathBuf>, inventory: Option<PathBuf>) -> Paths {+ let dir = dir+ .or_else(|| std::env::var_os("OPENRUNNER_HOME").map(PathBuf::from))+ .or_else(|| std::env::var_os("XDG_CONFIG_HOME").map(|d| PathBuf::from(d).join("openrunner")))+ .or_else(|| dirs::home_dir().map(|h| h.join(".config").join("openrunner")))+ .unwrap_or_else(|| PathBuf::from(".openrunner"));+ Paths {+ inventory: inventory.unwrap_or_else(|| dir.join("fleet.toml")),+ settings: dir.join("settings.json"),+ state: dir.join("state.json"),+ workspaces: dir.join("workspaces.json"),+ dir,+ }+ }+}++/// Shortens paths under the home directory to `~/...` for display.+pub fn display_path(path: &Path) -> String {+ if let Some(home) = dirs::home_dir() {+ if let Ok(rest) = path.strip_prefix(&home) {+ return format!("~/{}", rest.display());+ }+ }+ path.display().to_string()+}++// ---------------------------------------------------------------------------+// Inventory (fleet.toml)++#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+struct InventoryFile {+ #[serde(default, rename = "machine")]+ machines: Vec<MachineSpec>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct MachineSpec {+ pub name: String,+ /// Stable id used in URLs. Defaults to a slug of `name`.+ #[serde(default)]+ pub id: String,+ /// "local" for this computer, any `ssh` destination otherwise. Empty: listed but never checked.+ #[serde(default)]+ pub host: String,+ #[serde(default)]+ pub user: Option<String>,+ #[serde(default)]+ pub port: Option<u16>,+ /// Shown until the first successful check, e.g. "darwin-arm64".+ #[serde(default)]+ pub platform: Option<String>,+ /// "sh" or "powershell". Auto-detected when omitted.+ #[serde(default)]+ pub shell: Option<Shell>,+ /// Runner names expected on this machine. Missing ones are flagged.+ #[serde(default)]+ pub runners: Vec<String>,+ /// Extra glob patterns to look for runner folders (each containing a `.runner` file).+ #[serde(default)]+ pub runner_dirs: Vec<String>,+ /// Include runners found on the machine that aren't listed in `runners`.+ #[serde(default = "yes")]+ pub discover: bool,+ /// Let AI agents create workspaces on this machine.+ #[serde(default = "yes")]+ pub workspaces: bool,+ /// Where workspaces live on the machine. Default `~/openrunner/workspaces`.+ #[serde(default)]+ pub workspace_root: Option<String>,+ /// Extra arguments for `ssh`, e.g. ["-i", "~/.ssh/ci"].+ #[serde(default)]+ pub ssh_options: Vec<String>,+ #[serde(default)]+ pub notes: Option<String>,+}++fn yes() -> bool {+ true+}++impl MachineSpec {+ pub fn is_local(&self) -> bool {+ matches!(self.host.trim().to_ascii_lowercase().as_str(), "local" | "localhost" | "127.0.0.1" | "::1")+ }++ pub fn is_checkable(&self) -> bool {+ !self.host.trim().is_empty()+ }+}++#[derive(Debug, Clone, Default)]+pub struct Inventory {+ pub machines: Vec<MachineSpec>,+ pub warnings: Vec<String>,+}++impl Inventory {+ pub fn parse(text: &str) -> Result<Inventory> {+ let file: InventoryFile = toml::from_str(text).map_err(|e| anyhow::anyhow!("{}", e.to_string().trim()))?;+ let mut inv = Inventory { machines: Vec::new(), warnings: Vec::new() };+ let mut ids = HashSet::new();+ let mut runner_owner: HashMap<String, String> = HashMap::new();++ for mut m in file.machines {+ m.name = m.name.trim().to_string();+ if m.name.is_empty() {+ inv.warnings.push("A [[machine]] has an empty name and was skipped.".into());+ continue;+ }+ let id = assign_machine_id(&m.name, &m.id, &mut ids);+ if id != machine_id_base(&m.name, &m.id) {+ inv.warnings.push(format!("Two machines are called \"{}\"; the second one is shown as \"{id}\".", m.name));+ }+ m.id = id;+ m.runners.retain(|r| !r.trim().is_empty());+ for r in &m.runners {+ if let Some(other) = runner_owner.insert(r.to_ascii_lowercase(), m.name.clone()) {+ if other != m.name {+ inv.warnings.push(format!("Runner \"{r}\" is listed under both {other} and {}.", m.name));+ }+ }+ }+ inv.machines.push(m);+ }+ Ok(inv)+ }++ pub fn load(path: &Path) -> Result<Inventory> {+ let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", display_path(path)))?;+ Inventory::parse(&text)+ }+}++fn machine_id_base(name: &str, explicit_id: &str) -> String {+ if explicit_id.trim().is_empty() { slug(name) } else { slug(explicit_id) }+}++/// A machine's id: its `id` (or `name`) slugged, with "-2", "-3"... appended to+/// repeats in file order. Shared with the fleet.toml editor so both agree.+pub fn assign_machine_id(name: &str, explicit_id: &str, taken: &mut HashSet<String>) -> String {+ let base = machine_id_base(name, explicit_id);+ let mut id = base.clone();+ let mut n = 2;+ while !taken.insert(id.clone()) {+ id = format!("{base}-{n}");+ n += 1;+ }+ id+}++/// The inventory written on first run: just this computer, with runners discovered.+pub fn default_inventory() -> String {+ let host = local_hostname();+ format!(+ r#"# OpenRunner fleet inventory+#+# Each [[machine]] is a computer that hosts self-hosted GitHub Actions runners,+# or one you just want to keep an eye on. OpenRunner checks machines over SSH+# (or directly when host = "local") and reads CPU, memory, disk, uptime and+# which runners are installed and running. Checks are read-only.+#+# Runners installed in the usual places (~/actions-runner*, ~/runners/*,+# /opt/actions-runner*, C:\actions-runner*) are discovered automatically.+# List them in `runners` so a missing one gets flagged.++[[machine]]+name = "{host}"+host = "local"+# runners = ["{runner}-01"]++# [[machine]]+# name = "Mac Studio"+# host = "[email protected]" # anything `ssh` accepts, including ~/.ssh/config aliases+# runners = ["mac-studio-01", "mac-studio-02"]+# runner_dirs = ["/Volumes/Fast/runners/*"] # extra places to look for runners++# [[machine]]+# name = "Windows NUC"+# host = "nuc"+# shell = "powershell" # auto-detected when omitted++# [[machine]]+# name = "StudioNAS" # no runners: listed under "Other machines"+# host = "nas"+"#,+ runner = slug(&host),+ )+}++pub fn local_hostname() -> String {+ let raw = std::process::Command::new("hostname")+ .arg("-s")+ .output()+ .ok()+ .filter(|o| o.status.success())+ .or_else(|| std::process::Command::new("hostname").output().ok())+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())+ .unwrap_or_default();+ if raw.is_empty() { "This computer".into() } else { raw }+}++// ---------------------------------------------------------------------------+// Settings (settings.json)++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase", default)]+pub struct Settings {+ pub github: GitHubSettings,+ pub github_poll_seconds: u32,+ /// 0 turns automatic machine checks off.+ pub check_interval_minutes: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase", default)]+pub struct GitHubSettings {+ pub orgs: Vec<String>,+ pub repos: Vec<String>,+ /// Recently pushed repos per org to scan for queued and running jobs.+ pub scan_repos: u32,+ pub api_url: String,+}++impl Default for Settings {+ fn default() -> Self {+ Settings { github: GitHubSettings::default(), github_poll_seconds: 20, check_interval_minutes: 15 }+ }+}++impl Default for GitHubSettings {+ fn default() -> Self {+ GitHubSettings { orgs: Vec::new(), repos: Vec::new(), scan_repos: 10, api_url: "https://api.github.com".into() }+ }+}++impl Settings {+ pub fn load(path: &Path) -> Settings {+ match std::fs::read_to_string(path) {+ Ok(text) => match serde_json::from_str::<Settings>(&text) {+ Ok(s) => s.normalized().unwrap_or_default(),+ Err(e) => {+ tracing::warn!("ignoring {}: {e}", display_path(path));+ Settings::default()+ }+ },+ Err(_) => Settings::default(),+ }+ }++ pub fn save(&self, path: &Path) -> Result<()> {+ write_atomic(path, &serde_json::to_vec_pretty(self)?)+ }++ /// Trims, de-duplicates and validates. Returns a message suitable for the UI on error.+ pub fn normalized(mut self) -> Result<Settings, String> {+ let mut seen = HashSet::new();+ let mut orgs = Vec::new();+ for raw in &self.github.orgs {+ let org = strip_github_url(raw);+ if org.is_empty() {+ continue;+ }+ if org.contains('/') || !valid_name(&org) {+ return Err(format!("\"{raw}\" isn't a valid organization name."));+ }+ if seen.insert(org.to_ascii_lowercase()) {+ orgs.push(org);+ }+ }+ let mut repos = Vec::new();+ for raw in &self.github.repos {+ let repo = strip_github_url(raw);+ if repo.is_empty() {+ continue;+ }+ match repo.split_once('/') {+ Some((owner, name)) if valid_name(owner) && valid_name(name) && !name.contains('/') => {}+ _ => return Err(format!("\"{raw}\" isn't a repository. Use owner/name.")),+ }+ if seen.insert(repo.to_ascii_lowercase()) {+ repos.push(repo);+ }+ }+ self.github.orgs = orgs;+ self.github.repos = repos;+ self.github.scan_repos = self.github.scan_repos.min(50);+ let api = self.github.api_url.trim().trim_end_matches('/');+ self.github.api_url = if api.is_empty() { "https://api.github.com".into() } else { api.into() };+ if !self.github.api_url.starts_with("https://") && !self.github.api_url.starts_with("http://") {+ return Err("The GitHub API URL must start with https://".into());+ }+ self.github_poll_seconds = self.github_poll_seconds.clamp(10, 3600);+ self.check_interval_minutes = self.check_interval_minutes.min(24 * 60);+ Ok(self)+ }+}++/// Accepts "acme", "acme/api", "https://github.com/acme/api(.git)" and returns "acme" / "acme/api".+pub fn strip_github_url(raw: &str) -> String {+ let mut s = raw.trim();+ for prefix in ["https://", "http://"] {+ if let Some(rest) = s.strip_prefix(prefix) {+ s = rest.split_once('/').map(|(_, path)| path).unwrap_or("");+ }+ }+ s.trim_matches('/').trim_end_matches(".git").to_string()+}++fn valid_name(s: &str) -> bool {+ !s.is_empty() && s.len() <= 100 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))+}++// ---------------------------------------------------------------------------+// Persisted state (state.json)++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct PersistedState {+ pub probes: HashMap<String, ProbeResult>,+ pub check_started_at: Option<DateTime<Utc>>,+ pub check_finished_at: Option<DateTime<Utc>>,+}++impl PersistedState {+ pub fn load(path: &Path) -> PersistedState {+ std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()+ }++ pub fn save(&self, path: &Path) -> Result<()> {+ write_atomic(path, &serde_json::to_vec(self)?)+ }+}++pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;+ }+ let tmp = path.with_extension("tmp");+ std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?;+ std::fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_inventory_and_dedupes_ids() {+ let inv = Inventory::parse(+ r#"+ [[machine]]+ name = "Mac Studio"+ host = "studio"+ runners = ["mac-studio-01", ""]++ [[machine]]+ name = "Mac Studio"+ host = "local"+ "#,+ )+ .unwrap();+ assert_eq!(inv.machines[0].id, "mac-studio");+ assert_eq!(inv.machines[1].id, "mac-studio-2");+ assert_eq!(inv.machines[0].runners, vec!["mac-studio-01"]);+ assert!(inv.machines[1].is_local());+ assert!(inv.machines[0].discover);+ assert_eq!(inv.warnings.len(), 1);+ }++ #[test]+ fn rejects_unknown_keys() {+ let err = Inventory::parse("[[machine]]\nname = \"a\"\nhots = \"x\"\n").unwrap_err();+ assert!(err.to_string().contains("hots"), "{err}");+ }++ #[test]+ fn default_inventory_parses() {+ let inv = Inventory::parse(&default_inventory()).unwrap();+ assert_eq!(inv.machines.len(), 1);+ assert!(inv.machines[0].is_local());+ }++ #[test]+ fn normalizes_settings() {+ let mut s = Settings::default();+ s.github.orgs = vec![" acme ".into(), "https://github.com/Acme".into(), "".into()];+ s.github.repos = vec!["https://github.com/acme/api.git".into()];+ s.github_poll_seconds = 1;+ let s = s.normalized().unwrap();+ assert_eq!(s.github.orgs, vec!["acme"]);+ assert_eq!(s.github.repos, vec!["acme/api"]);+ assert_eq!(s.github_poll_seconds, 10);++ let mut bad = Settings::default();+ bad.github.repos = vec!["just-a-name".into()];+ assert!(bad.normalized().is_err());+ }+}diff --git a/src/demo.rs b/src/demo.rsnew file mode 100644index 0000000..ce71048--- /dev/null+++ b/src/demo.rs@@ -0,0 +1,684 @@+//! `openrunner serve --demo`: a simulated fleet with jobs arriving, running and+//! finishing, so the dashboard can be explored without any real machines.++use std::sync::Mutex;+use std::time::Duration;++use chrono::{DateTime, Utc};++use crate::config::{Inventory, MachineSpec, Settings};+use crate::github::{GitHubData, JobData, Rate, RunnerData, ScopeData, ScopeKind, ScopeTest};+use crate::probe::{ProbeResult, ProbedRunner, Shell};++const ORG: &str = "acme";++const INVENTORY: &str = r#"+[[machine]]+name = "Mac Mini"+host = "[email protected]"+runners = ["mac-mini-01"]++[[machine]]+name = "Mac Studio"+host = "[email protected]"+runners = ["mac-studio-01", "mac-studio-02", "mac-studio-03", "mac-studio-04", "mac-studio-05", "mac-studio-06", "mac-studio-07"]++[[machine]]+name = "Omarchy Laptop"+host = "omarchy"+runners = ["omarchy-01"]++[[machine]]+name = "Tahoe Macbook"+host = "tahoe.local"+runners = ["tahoe-01", "tahoe-02"]++[[machine]]+name = "Ubuntu NUC"+host = "nuc-ubuntu"+runners = ["minis-01-01"]++[[machine]]+name = "Windows Laptop"+host = "win-laptop"+shell = "powershell"+runners = ["windows-01"]++[[machine]]+name = "Windows NUC"+host = "nuc-win"+shell = "powershell"+runners = ["minis-02-01"]++[[machine]]+name = "Laravel Macbook"+host = "laravel-mbp.local"+platform = "darwin-arm64"+notes = "Loaner laptop, usually asleep."++[[machine]]+name = "StudioNAS"+host = "nas"+notes = "Build artifact cache."+"#;++struct Hardware {+ id: &'static str,+ os: &'static str,+ arch: &'static str,+ os_version: &'static str,+ cores: u32,+ mem_gb: u64,+ base_mem: f64,+ disk_total_gb: u64,+ disk_free_gb: f64,+ up_hours: u64,+ reachable: bool,+ /// Docker server version, if the machine has Docker.+ docker: Option<&'static str>,+ /// Linux: "passwordless" | "password" (systemd services need passwordless sudo).+ sudo: Option<&'static str>,+}++const HARDWARE: &[Hardware] = &[+ Hardware { id: "mac-mini", os: "darwin", arch: "arm64", os_version: "macOS 26.1", cores: 10, mem_gb: 32, base_mem: 0.38, disk_total_gb: 1000, disk_free_gb: 381.0, up_hours: 23, reachable: true, docker: None, sudo: None },+ Hardware { id: "mac-studio", os: "darwin", arch: "arm64", os_version: "macOS 26.1", cores: 24, mem_gb: 128, base_mem: 0.18, disk_total_gb: 1000, disk_free_gb: 106.0, up_hours: 116 * 24, reachable: true, docker: Some("29.0.1"), sudo: None },+ Hardware { id: "omarchy-laptop", os: "linux", arch: "x86_64", os_version: "Arch Linux", cores: 16, mem_gb: 32, base_mem: 0.45, disk_total_gb: 1000, disk_free_gb: 328.0, up_hours: 37 * 24 + 15, reachable: true, docker: Some("29.1.3"), sudo: Some("passwordless") },+ Hardware { id: "tahoe-macbook", os: "darwin", arch: "arm64", os_version: "macOS 26.0", cores: 12, mem_gb: 36, base_mem: 0.41, disk_total_gb: 500, disk_free_gb: 122.0, up_hours: 67 * 24 + 20, reachable: true, docker: None, sudo: None },+ Hardware { id: "ubuntu-nuc", os: "linux", arch: "x86_64", os_version: "Ubuntu 24.04.3 LTS", cores: 8, mem_gb: 64, base_mem: 0.10, disk_total_gb: 1000, disk_free_gb: 914.0, up_hours: 43, reachable: true, docker: Some("29.1.3"), sudo: Some("password") },+ Hardware { id: "windows-laptop", os: "windows", arch: "ARM64", os_version: "Microsoft Windows 11 Pro", cores: 12, mem_gb: 32, base_mem: 0.40, disk_total_gb: 512, disk_free_gb: 159.0, up_hours: 4 * 24 + 20, reachable: true, docker: None, sudo: None },+ Hardware { id: "windows-nuc", os: "windows", arch: "AMD64", os_version: "Microsoft Windows 11 Pro", cores: 8, mem_gb: 32, base_mem: 0.33, disk_total_gb: 1000, disk_free_gb: 920.0, up_hours: 37, reachable: true, docker: None, sudo: None },+ Hardware { id: "laravel-macbook", os: "darwin", arch: "arm64", os_version: "macOS 26.1", cores: 12, mem_gb: 36, base_mem: 0.3, disk_total_gb: 1000, disk_free_gb: 400.0, up_hours: 3, reachable: false, docker: None, sudo: None },+ Hardware { id: "studionas", os: "linux", arch: "x86_64", os_version: "Debian GNU/Linux 12 (bookworm)", cores: 4, mem_gb: 16, base_mem: 0.18, disk_total_gb: 8000, disk_free_gb: 6.8, up_hours: 87 * 24 + 7, reachable: true, docker: Some("28.5.1"), sudo: Some("password") },+];++struct Template {+ repo: &'static str,+ workflow: &'static str,+ name: &'static str,+ labels: &'static [&'static str],+ min_secs: u64,+ max_secs: u64,+}++const TEMPLATES: &[Template] = &[+ Template { repo: "acme/desktop", workflow: "CI", name: "build (macos-arm64)", labels: &["self-hosted", "macOS", "ARM64"], min_secs: 90, max_secs: 300 },+ Template { repo: "acme/desktop", workflow: "CI", name: "test (macos)", labels: &["self-hosted", "macOS"], min_secs: 60, max_secs: 180 },+ Template { repo: "acme/desktop", workflow: "Release", name: "notarize", labels: &["self-hosted", "macOS", "ARM64"], min_secs: 120, max_secs: 240 },+ Template { repo: "acme/api", workflow: "CI", name: "test", labels: &["self-hosted", "Linux", "X64"], min_secs: 45, max_secs: 150 },+ Template { repo: "acme/api", workflow: "Deploy", name: "deploy (staging)", labels: &["self-hosted", "Linux"], min_secs: 30, max_secs: 90 },+ Template { repo: "acme/web", workflow: "CI", name: "e2e (windows)", labels: &["self-hosted", "Windows"], min_secs: 90, max_secs: 240 },+ Template { repo: "acme/web", workflow: "CI", name: "lint", labels: &["self-hosted", "Linux"], min_secs: 20, max_secs: 60 },+ Template { repo: "acme/mobile", workflow: "Release", name: "archive (ios)", labels: &["self-hosted", "macOS", "ARM64"], min_secs: 180, max_secs: 420 },+ Template { repo: "acme/infra", workflow: "Nightly", name: "integration", labels: &["self-hosted", "Linux", "X64"], min_secs: 120, max_secs: 360 },+];++const BRANCHES: &[&str] = &["main", "main", "main", "feat/fleet-view", "fix/flaky-e2e", "release/2.4"];+const ACTORS: &[&str] = &["dependabot[bot]", "maya", "theo", "sam", "priya"];++struct SimRunner {+ name: String,+ machine: Option<String>,+ labels: Vec<String>,+ online: bool,+ job: Option<u64>,+ version: &'static str,+ /// Installed as a Docker container (openrunner-<name>).+ docker: bool,+}++struct SimJob {+ id: u64,+ run_id: u64,+ template: usize,+ labels: Vec<String>,+ branch: &'static str,+ actor: &'static str,+ created_at: DateTime<Utc>,+ started_at: Option<DateTime<Utc>>,+ runner: Option<String>,+ duration: i64,+}++struct Sim {+ rng: u64,+ last_tick: DateTime<Utc>,+ next_id: u64,+ runners: Vec<SimRunner>,+ jobs: Vec<SimJob>,+}++pub struct World {+ sim: Mutex<Sim>,+ /// fleet.toml for the demo, edited in memory by add/remove machine and installs.+ inventory: Mutex<String>,+ /// Files in the demo's agent workspaces, by workspace id (see fleet::workspaces).+ pub(crate) workspace_files: Mutex<std::collections::HashMap<String, crate::fleet::workspaces::DemoTree>>,+}++/// Machines added in the demo get these specs.+const GENERIC: Hardware = Hardware {+ id: "",+ os: "linux",+ arch: "x86_64",+ os_version: "Ubuntu 24.04.3 LTS",+ cores: 8,+ mem_gb: 32,+ base_mem: 0.12,+ disk_total_gb: 500,+ disk_free_gb: 410.0,+ up_hours: 2,+ reachable: true,+ docker: Some("29.1.3"),+ sudo: Some("password"),+};++fn hardware(machine_id: &str) -> &'static Hardware {+ HARDWARE.iter().find(|h| h.id == machine_id).unwrap_or(&GENERIC)+}++impl World {+ pub fn new() -> World {+ let now = Utc::now();+ let mac = || labels(&["self-hosted", "macOS", "ARM64"]);+ let mut runners: Vec<SimRunner> = Vec::new();+ let mut add = |name: &str, machine: Option<&str>, l: Vec<String>, version: &'static str| {+ runners.push(SimRunner { name: name.into(), machine: machine.map(String::from), labels: l, online: true, job: None, version, docker: false });+ };+ add("mac-mini-01", Some("mac-mini"), mac(), "2.325.0");+ for i in 1..=7 {+ add(&format!("mac-studio-{i:02}"), Some("mac-studio"), mac(), "2.329.0");+ }+ add("omarchy-01", Some("omarchy-laptop"), labels(&["self-hosted", "Linux", "X64"]), "2.329.0");+ add("tahoe-01", Some("tahoe-macbook"), mac(), "2.329.0");+ add("tahoe-02", Some("tahoe-macbook"), mac(), "2.329.0");+ add("minis-01-01", Some("ubuntu-nuc"), labels(&["self-hosted", "Linux", "X64"]), "2.329.0");+ add("windows-01", Some("windows-laptop"), labels(&["self-hosted", "Windows", "ARM64"]), "2.329.0");+ add("minis-02-01", Some("windows-nuc"), labels(&["self-hosted", "Windows", "X64"]), "2.329.0");+ // Registered on GitHub, but not in fleet.toml.+ add("linux-spot-01", None, labels(&["self-hosted", "Linux", "X64", "spot"]), "2.329.0");++ let mut sim = Sim { rng: now.timestamp_nanos_opt().unwrap_or(1) as u64 | 1, last_tick: now, next_id: 9_000_100, runners, jobs: Vec::new() };+ // A stopped runner, to show what that looks like.+ if let Some(r) = sim.runners.iter_mut().find(|r| r.name == "mac-studio-06") {+ r.online = false;+ }+ // Start mid-afternoon: a few jobs already running, one that no runner can take.+ for (t, runner, ago) in [(0, "mac-studio-01", 70), (7, "mac-studio-05", 140), (1, "mac-mini-01", 35), (4, "minis-01-01", 20), (5, "minis-02-01", 50)] {+ let id = sim.new_job(t, now - chrono::Duration::seconds(ago + 5));+ let job = sim.jobs.iter_mut().find(|j| j.id == id).unwrap();+ job.started_at = Some(now - chrono::Duration::seconds(ago));+ job.runner = Some(runner.into());+ sim.runners.iter_mut().find(|r| r.name == runner).unwrap().job = Some(id);+ }+ let gpu = sim.new_job(8, now - chrono::Duration::minutes(6));+ if let Some(j) = sim.jobs.iter_mut().find(|j| j.id == gpu) {+ j.labels = labels(&["self-hosted", "Linux", "gpu"]);+ }+ World {+ sim: Mutex::new(sim),+ inventory: Mutex::new(INVENTORY.trim_start().to_string()),+ workspace_files: Mutex::new(std::collections::HashMap::new()),+ }+ }++ pub fn inventory(&self) -> Inventory {+ let text = self.inventory.lock().unwrap();+ Inventory::parse(&text).unwrap_or_else(|_| Inventory::parse(INVENTORY).expect("demo inventory parses"))+ }++ pub fn settings(&self) -> Settings {+ let mut s = Settings::default();+ s.github.orgs = vec![ORG.into()];+ s.check_interval_minutes = 5;+ s+ }++ pub async fn probe(&self, spec: &MachineSpec) -> ProbeResult {+ let delay = { self.sim.lock().unwrap().range(400, 1800) };+ tokio::time::sleep(Duration::from_millis(delay)).await;++ let hw = hardware(&spec.id);+ if !hw.reachable {+ return ProbeResult {+ checked_at: Utc::now(),+ duration_ms: 8000,+ ok: false,+ error: Some(format!("ssh: connect to host {} port 22: Operation timed out", spec.host)),+ ..Default::default()+ };+ }++ let mut sim = self.sim.lock().unwrap();+ sim.tick(Utc::now());+ let now = Utc::now();+ let mine: Vec<(String, bool, bool, &'static str, bool)> = sim+ .runners+ .iter()+ .filter(|r| r.machine.as_deref() == Some(spec.id.as_str()))+ .map(|r| (r.name.clone(), r.online, r.job.is_some(), r.version, r.docker))+ .collect();+ let busy = mine.iter().filter(|r| r.2).count() as f64;+ let cpu = (3.0 + busy * 38.0 / (hw.cores as f64 / 8.0).max(1.0) + sim.noise(6.0)).clamp(1.0, 99.0);+ let mem_total = hw.mem_gb * 1024 * 1024 * 1024;+ let mem = (hw.base_mem + busy * 0.07 + sim.noise(0.02)).clamp(0.05, 0.97);+ let mut pid = 3000 + sim.range(0, 500) as u32;+ let runners = mine+ .iter()+ .map(|(name, online, working, version, docker)| {+ pid += 37;+ if *docker {+ let container = format!("openrunner-{name}");+ return ProbedRunner {+ dir: crate::probe::container_dir(&container),+ name: name.clone(),+ url: Some(format!("https://github.com/{ORG}")),+ version: Some(version.to_string()),+ listener_pid: online.then_some(pid),+ worker_pid: working.then_some(pid + 11),+ image: Some(format!("ghcr.io/actions/actions-runner:{version}")),+ container_state: Some(if *online { "running" } else { "exited" }.into()),+ restarts: Some(0),+ container: Some(container),+ ..Default::default()+ };+ }+ let dir = match hw.os {+ "windows" => format!("C:\\actions-runner\\{name}"),+ "linux" => format!("/home/ci/actions-runner/{name}"),+ _ => format!("/Users/ci/actions-runner/{name}"),+ };+ ProbedRunner {+ dir,+ name: name.clone(),+ url: Some(format!("https://github.com/{ORG}")),+ version: Some(version.to_string()),+ service: Some(format!("actions.runner.{ORG}.{name}")),+ service_state: Some(if *online { "active" } else { "inactive" }.into()),+ listener_pid: online.then_some(pid),+ worker_pid: working.then_some(pid + 11),+ ..Default::default()+ }+ })+ .collect();+ ProbeResult {+ checked_at: now,+ duration_ms: delay,+ ok: true,+ error: None,+ shell: Some(if hw.os == "windows" { Shell::Powershell } else { Shell::Sh }),+ hostname: Some(spec.id.clone()),+ os: Some(hw.os.into()),+ arch: Some(hw.arch.into()),+ os_version: Some(hw.os_version.into()),+ cores: Some(hw.cores),+ cpu_pct: Some((cpu * 10.0).round() / 10.0),+ mem_total: Some(mem_total),+ mem_used: Some((mem_total as f64 * mem) as u64),+ disk_total: Some(hw.disk_total_gb * 1_000_000_000),+ disk_free: Some((hw.disk_free_gb * 1e9) as u64),+ disk_path: Some(match hw.os {+ "windows" => "C:".into(),+ "darwin" => "/System/Volumes/Data".into(),+ _ => "/".into(),+ }),+ uptime_sec: Some(hw.up_hours * 3600 + (now.timestamp() % 3600) as u64),+ load: if hw.os == "windows" { Vec::new() } else { vec![busy * 1.6 + 0.4, busy * 1.4 + 0.5, busy * 1.2 + 0.6] },+ runners,+ docker: hw.docker.map(String::from),+ docker_error: None,+ sudo: hw.sudo.map(String::from),+ }+ }++ pub fn github(&self, settings: &Settings) -> GitHubData {+ let now = Utc::now();+ let mut sim = self.sim.lock().unwrap();+ sim.tick(now);+ let watching_acme = settings.github.orgs.iter().any(|o| o.eq_ignore_ascii_case(ORG));+ let scopes = settings+ .github+ .orgs+ .iter()+ .map(|o| (ScopeKind::Org, o.clone()))+ .chain(settings.github.repos.iter().map(|r| (ScopeKind::Repo, r.clone())))+ .map(|(kind, name)| ScopeData {+ runners: if kind == ScopeKind::Org && name.eq_ignore_ascii_case(ORG) {+ sim.runners+ .iter()+ .enumerate()+ .map(|(i, r)| RunnerData {+ id: 100 + i as u64,+ name: r.name.clone(),+ os: os_for(&r.labels).into(),+ status: if r.online { "online" } else { "offline" }.into(),+ busy: r.job.is_some(),+ labels: r.labels.clone(),+ })+ .collect()+ } else {+ Vec::new()+ },+ kind,+ name,+ synced_at: Some(now),+ error: None,+ hint: None,+ })+ .collect();+ let jobs = if watching_acme {+ sim.jobs+ .iter()+ .map(|j| {+ let t = &TEMPLATES[j.template];+ JobData {+ id: j.id,+ run_id: j.run_id,+ name: t.name.into(),+ workflow: t.workflow.into(),+ repo: t.repo.into(),+ branch: Some(j.branch.into()),+ event: Some(if j.branch == "main" { "push" } else { "pull_request" }.into()),+ actor: Some(j.actor.into()),+ url: format!("https://github.com/{}/actions/runs/{}/job/{}", t.repo, j.run_id, j.id),+ status: if j.started_at.is_some() { "in_progress" } else { "queued" }.into(),+ labels: j.labels.clone(),+ runner_name: j.runner.clone(),+ created_at: j.created_at,+ started_at: j.started_at,+ }+ })+ .collect()+ } else {+ Vec::new()+ };+ let remaining = 4800 - (now.timestamp() % 600) as u32;+ GitHubData {+ synced_at: Some(now),+ token_source: "gh".into(),+ login: Some("you".into()),+ error: None,+ scopes,+ jobs,+ scanned_repos: if watching_acme {+ ["acme/desktop", "acme/api", "acme/web", "acme/mobile", "acme/infra"].map(String::from).to_vec()+ } else {+ Vec::new()+ },+ rate: Some(Rate { limit: 5000, remaining, reset_at: now + chrono::Duration::minutes(37) }),+ latest_runner_version: Some("2.329.0".into()),+ }+ }++ // -----------------------------------------------------------------------+ // Control operations (see crate::ops), simulated.++ /// Applies an edit to the demo's fleet.toml text.+ pub fn edit_inventory(&self, edit: impl FnOnce(&str) -> Result<String, String>) -> Result<(), String> {+ let mut text = self.inventory.lock().unwrap();+ *text = edit(&text)?;+ Ok(())+ }++ /// Err with an ssh-style message when the demo machine is "asleep".+ pub fn reachable(&self, machine_id: &str, host: &str) -> Result<(), String> {+ if hardware(machine_id).reachable {+ Ok(())+ } else {+ Err(format!("ssh: connect to host {host} port 22: Operation timed out"))+ }+ }++ /// ("osx" | "linux" | "win", "arm64" | "x64") as the runner download names them.+ pub fn runner_platform(&self, machine_id: &str) -> (&'static str, &'static str) {+ let hw = hardware(machine_id);+ let os = match hw.os {+ "darwin" => "osx",+ "windows" => "win",+ _ => "linux",+ };+ let arch = if hw.arch.eq_ignore_ascii_case("arm64") { "arm64" } else { "x64" };+ (os, arch)+ }++ /// Adds runners to the simulation; `docker` makes them container runners.+ pub fn install_runners(&self, machine_id: &str, names: &[String], extra_labels: &[String], docker: bool) {+ let hw = hardware(machine_id);+ let os = match hw.os {+ "darwin" => "macOS",+ "windows" => "Windows",+ _ => "Linux",+ };+ let arch = if hw.arch.eq_ignore_ascii_case("arm64") { "ARM64" } else { "X64" };+ let mut sim = self.sim.lock().unwrap();+ for name in names {+ // A container runner's OS is Linux whatever the host is.+ let mut l = if docker { labels(&["self-hosted", "Linux", arch]) } else { labels(&["self-hosted", os, arch]) };+ l.extend(extra_labels.iter().cloned());+ sim.runners.push(SimRunner {+ name: name.clone(),+ machine: Some(machine_id.to_string()),+ labels: l,+ online: true,+ job: None,+ version: "2.329.0",+ docker,+ });+ }+ }++ /// Start (online) or stop (offline) a runner. Stopping hands its job back to the queue.+ pub fn set_runner_online(&self, name: &str, online: bool) {+ let mut sim = self.sim.lock().unwrap();+ if let Some(i) = sim.runners.iter().position(|r| r.name.eq_ignore_ascii_case(name)) {+ if !online {+ sim.requeue(i);+ }+ sim.runners[i].online = online;+ }+ }++ pub fn remove_runner(&self, name: &str) {+ let mut sim = self.sim.lock().unwrap();+ if let Some(i) = sim.runners.iter().position(|r| r.name.eq_ignore_ascii_case(name)) {+ sim.requeue(i);+ sim.runners.remove(i);+ }+ }++ /// A plausible tail of a runner's _diag/Runner_*.log.+ pub fn diag_log(&self, name: &str) -> Vec<String> {+ let now = Utc::now();+ let sim = self.sim.lock().unwrap();+ let runner = sim.runners.iter().find(|r| r.name.eq_ignore_ascii_case(name));+ let online = runner.is_some_and(|r| r.online);+ let job = runner.and_then(|r| r.job).and_then(|id| sim.jobs.iter().find(|j| j.id == id));+ let hw = runner.and_then(|r| r.machine.as_deref()).map(hardware).unwrap_or(&GENERIC);+ let arm = hw.arch.eq_ignore_ascii_case("arm64");+ let (bin, built, runtime) = match hw.os {+ "windows" => (+ format!("C:\\actions-runner\\{name}\\bin"),+ format!("Windows ({}) - win-{}", if arm { "ARM64" } else { "X64" }, if arm { "arm64" } else { "x64" }),+ "Microsoft Windows 10.0.26100".to_string(),+ ),+ "linux" => (+ format!("/home/ci/actions-runner/{name}/bin"),+ format!("Linux ({}) - linux-{}", if arm { "ARM64" } else { "X64" }, if arm { "arm64" } else { "x64" }),+ "Linux 6.8.0-45-generic #45-Ubuntu SMP".to_string(),+ ),+ _ => (+ format!("/Users/ci/actions-runner/{name}/bin"),+ "macOS (ARM64) - osx-arm64".to_string(),+ "Darwin 25.1.0 Darwin Kernel Version 25.1.0".to_string(),+ ),+ };+ let at = |secs_ago: i64| (now - chrono::Duration::seconds(secs_ago)).format("%Y-%m-%d %H:%M:%SZ").to_string();+ let mut lines = vec![+ format!("[{} INFO HostContext] Well known directory 'Bin': '{bin}'", at(5400)),+ format!("[{} INFO Listener] Runner is built for {built}.", at(5400)),+ format!("[{} INFO Listener] RuntimeInformation: {runtime}.", at(5400)),+ format!("[{} INFO Listener] Version: 2.329.0", at(5400)),+ format!("[{} INFO Listener] Commit: 6b5f7cf8a5e0c4c3b1c0d6e2", at(5400)),+ format!("[{} INFO ConfigurationStore] HasCredentials()", at(5399)),+ format!("[{} INFO CredentialManager] GetCredentialProvider", at(5399)),+ format!("[{} INFO RunnerServer] EstablishVssConnection", at(5398)),+ format!("[{} INFO MessageListener] Connect to server.", at(5398)),+ format!("[{} INFO MessageListener] Create session.", at(5397)),+ format!("[{} INFO MessageListener] Session created.", at(5396)),+ format!("[{} INFO Terminal] WRITE LINE: √ Connected to GitHub", at(5396)),+ format!("[{} INFO Terminal] WRITE LINE: Current runner version: '2.329.0'", at(5395)),+ format!("[{} INFO Terminal] WRITE LINE: Listening for Jobs", at(5395)),+ ];+ let past_job = match hw.os {+ "windows" => "e2e (windows)",+ "linux" => "test",+ _ => "build (macos-arm64)",+ };+ for k in 0..4 {+ let t = 4200 - k * 900;+ lines.push(format!("[{} INFO MessageListener] Message '{}' received from session.", at(t), 1000 + k));+ lines.push(format!("[{} INFO JobDispatcher] Job request {} for plan 6f3c… received.", at(t), 18_000_200 + k));+ lines.push(format!("[{} INFO JobDispatcher] Start renew job request {}.", at(t - 1), 18_000_200 + k));+ lines.push(format!("[{} INFO Terminal] WRITE LINE: Running job: {past_job}", at(t - 1)));+ lines.push(format!("[{} INFO JobDispatcher] Worker finished for job. Code: 100", at(t - 240)));+ lines.push(format!("[{} INFO Terminal] WRITE LINE: Job {past_job} completed with result: Succeeded", at(t - 240)));+ }+ match (online, job) {+ (false, _) => lines.push(format!("[{} INFO Listener] Runner execution has been cancelled. Exiting.", at(30))),+ (true, Some(j)) => {+ let t = &TEMPLATES[j.template];+ lines.push(format!("[{} INFO JobDispatcher] Job request {} for plan 9a1d… received.", at(20), j.id));+ lines.push(format!("[{} INFO Terminal] WRITE LINE: Running job: {}", at(19), t.name));+ }+ (true, None) => lines.push(format!("[{} INFO MessageListener] No message retrieved from session, keep polling.", at(15))),+ }+ lines+ }++ pub fn test_scope(&self, scope: &str) -> ScopeTest {+ let name = crate::config::strip_github_url(scope);+ let kind = if name.contains('/') { ScopeKind::Repo } else { ScopeKind::Org };+ let runners = if name.eq_ignore_ascii_case(ORG) { self.sim.lock().unwrap().runners.len() } else { 0 };+ ScopeTest { kind, name, runners, error: None, hint: None }+ }+}++impl Sim {+ /// Puts the runner's job (if any) back in the queue.+ fn requeue(&mut self, runner: usize) {+ if let Some(id) = self.runners[runner].job.take() {+ if let Some(j) = self.jobs.iter_mut().find(|j| j.id == id) {+ j.started_at = None;+ j.runner = None;+ }+ }+ }++ fn next(&mut self) -> u64 {+ // xorshift64*+ self.rng ^= self.rng >> 12;+ self.rng ^= self.rng << 25;+ self.rng ^= self.rng >> 27;+ self.rng.wrapping_mul(0x2545_F491_4F6C_DD1D)+ }++ fn range(&mut self, lo: u64, hi: u64) -> u64 {+ lo + self.next() % (hi - lo).max(1)+ }++ fn chance(&mut self, p: f64) -> bool {+ (self.next() % 10_000) as f64 / 10_000.0 < p+ }++ fn noise(&mut self, amp: f64) -> f64 {+ ((self.next() % 2001) as f64 / 1000.0 - 1.0) * amp+ }++ fn new_job(&mut self, template: usize, created_at: DateTime<Utc>) -> u64 {+ self.next_id += 1;+ let id = self.next_id;+ let t = &TEMPLATES[template];+ let duration = self.range(t.min_secs, t.max_secs) as i64;+ let branch = BRANCHES[self.range(0, BRANCHES.len() as u64) as usize];+ let actor = ACTORS[self.range(0, ACTORS.len() as u64) as usize];+ self.jobs.push(SimJob {+ id,+ run_id: 18_000_000 + id,+ template,+ labels: labels(t.labels),+ branch,+ actor,+ created_at,+ started_at: None,+ runner: None,+ duration,+ });+ id+ }++ /// Advances the simulation: finish jobs, enqueue new ones, hand queued jobs to idle runners.+ fn tick(&mut self, now: DateTime<Utc>) {+ let dt = (now - self.last_tick).num_milliseconds().max(0) as f64 / 1000.0;+ self.last_tick = now;++ let finished: Vec<u64> = self+ .jobs+ .iter()+ .filter(|j| j.started_at.is_some_and(|s| (now - s).num_seconds() >= j.duration))+ .map(|j| j.id)+ .collect();+ self.jobs.retain(|j| !finished.contains(&j.id));+ for r in &mut self.runners {+ if r.job.is_some_and(|id| finished.contains(&id)) {+ r.job = None;+ }+ }++ // Roughly one new job every 15 seconds, sometimes a burst from a push.+ if self.chance((dt / 15.0).min(0.9)) {+ let n = if self.chance(0.25) { 3 } else { 1 };+ for _ in 0..n {+ let t = self.range(0, TEMPLATES.len() as u64) as usize;+ self.new_job(t, now);+ }+ }++ let mut queued: Vec<usize> = (0..self.jobs.len()).filter(|&i| self.jobs[i].started_at.is_none()).collect();+ queued.sort_by_key(|&i| self.jobs[i].created_at);+ for i in queued {+ // Runners take a few seconds to pick a job up.+ if (now - self.jobs[i].created_at).num_seconds() < 4 {+ continue;+ }+ let job_labels = self.jobs[i].labels.clone();+ let candidates: Vec<usize> = (0..self.runners.len())+ .filter(|&r| {+ let rr = &self.runners[r];+ rr.online && rr.job.is_none() && job_labels.iter().all(|l| rr.labels.iter().any(|x| x.eq_ignore_ascii_case(l)))+ })+ .collect();+ if candidates.is_empty() {+ continue;+ }+ let pick = candidates[self.range(0, candidates.len() as u64) as usize];+ let job_id = self.jobs[i].id;+ self.runners[pick].job = Some(job_id);+ self.jobs[i].started_at = Some(now);+ self.jobs[i].runner = Some(self.runners[pick].name.clone());+ }+ }+}++fn labels(l: &[&str]) -> Vec<String> {+ l.iter().map(|s| s.to_string()).collect()+}++fn os_for(labels: &[String]) -> &'static str {+ if labels.iter().any(|l| l == "macOS") {+ "macOS"+ } else if labels.iter().any(|l| l == "Windows") {+ "Windows"+ } else {+ "Linux"+ }+}diff --git a/src/fleet/build.rs b/src/fleet/build.rsnew file mode 100644index 0000000..ee46c2e--- /dev/null+++ b/src/fleet/build.rs@@ -0,0 +1,932 @@+//! Merges the inventory, the last machine checks and live GitHub data into a+//! `Snapshot`. Pure: everything it needs is passed in, so it's easy to test.++use std::collections::{HashMap, HashSet};++use chrono::{DateTime, Utc};++use super::model::*;+use crate::config::{Inventory, MachineSpec, Settings};+use crate::github::{is_github_hosted_label, scope_from_runner_url, GitHubData, JobData, RunnerData};+use crate::probe::{ProbeResult, ProbedRunner};+use crate::util;++const LOW_DISK_BYTES: u64 = 20_000_000_000;+const LOW_DISK_FRACTION: f64 = 0.10;+const HIGH_MEMORY_FRACTION: f64 = 0.95;+/// A Docker runner restarted this often is crash-looping.+const CRASH_LOOP_RESTARTS: u32 = 5;+/// A queued job nobody can pick up gets flagged after this long.+const STUCK_JOB_SECS: i64 = 120;++pub struct Inputs<'a> {+ pub now: DateTime<Utc>,+ pub demo: bool,+ pub inventory: &'a Inventory,+ pub inventory_info: InventoryInfo,+ pub settings: &'a Settings,+ pub probes: &'a HashMap<String, ProbeResult>,+ pub checking: &'a HashSet<String>,+ pub check: CheckInfo,+ pub github: Option<&'a GitHubData>,+ pub github_syncing: bool,+ pub token_source: String,+}++pub fn build(input: &Inputs) -> Snapshot {+ let gh = input.github;+ let configured = !input.settings.github.orgs.is_empty() || !input.settings.github.repos.is_empty();++ // Every runner GitHub reported, by lowercase name.+ let mut gh_runners: HashMap<String, (String, &RunnerData)> = HashMap::new();+ if let Some(gh) = gh {+ for scope in gh.scopes.iter().filter(|s| s.error.is_none()) {+ let scope_id = format!("{}:{}", scope.kind.as_str(), scope.name);+ for r in &scope.runners {+ gh_runners.entry(r.name.to_ascii_lowercase()).or_insert((scope_id.clone(), r));+ }+ }+ }+ let github_live = gh.is_some_and(|g| g.scopes.iter().any(|s| s.error.is_none()));+ let latest_version = gh.and_then(|g| g.latest_runner_version.as_deref());+ let running_jobs: Vec<&JobData> =+ gh.map(|g| g.jobs.iter().filter(|j| j.status == "in_progress").collect()).unwrap_or_default();++ let mut claimed: HashSet<String> = HashSet::new();+ let mut machines = Vec::new();+ let mut runners = Vec::new();++ for spec in &input.inventory.machines {+ let probe = input.probes.get(&spec.id);+ let probe_ok = probe.filter(|p| p.ok);+ let mut diagnostics = Vec::new();++ // Runner names on this machine: declared first, then discovered.+ let mut names: Vec<(String, bool)> = spec.runners.iter().map(|n| (n.clone(), true)).collect();+ if let Some(p) = probe_ok {+ if spec.discover {+ let mut found: Vec<&ProbedRunner> = p.runners.iter().collect();+ found.sort_by(|a, b| a.name.cmp(&b.name));+ for r in found {+ if !names.iter().any(|(n, _)| n.eq_ignore_ascii_case(&r.name)) {+ names.push((r.name.clone(), false));+ }+ }+ }+ }++ let mut runner_ids = Vec::new();+ for (name, declared) in names {+ let key = name.to_ascii_lowercase();+ let id = format!("{}/{}", spec.id, name);+ let local = probe_ok.and_then(|p| p.runners.iter().find(|r| r.name.eq_ignore_ascii_case(&name)));+ let gh_entry = if claimed.contains(&key) { None } else { gh_runners.get(&key) };+ if gh_entry.is_some() {+ claimed.insert(key.clone());+ }++ let (state, source) = match (gh_entry, local, probe_ok) {+ (Some((_, r)), _, _) => (github_state(r), "github"),+ (None, Some(l), _) => (local_state(l), "probe"),+ (None, None, Some(_)) => ("offline", "probe"),+ (None, None, None) => ("unknown", "none"),+ };++ runner_diagnostics(&mut diagnostics, &id, &name, declared, local, probe_ok, gh_entry.map(|e| e.1), github_live, latest_version);++ let job = running_jobs.iter().find(|j| j.runner_name.as_deref().is_some_and(|n| n.eq_ignore_ascii_case(&name)));+ runners.push(Runner {+ id: id.clone(),+ name: name.clone(),+ machine_id: Some(spec.id.clone()),+ state: state.into(),+ source: source.into(),+ declared,+ labels: gh_entry.map(|(_, r)| r.labels.clone()).unwrap_or_default(),+ github: gh_entry.map(|(scope, r)| github_runner(scope, r)),+ local: local.map(local_runner),+ job_id: job.map(|j| j.id),+ });+ runner_ids.push(id);+ }++ let status = match probe {+ _ if !spec.is_checkable() => "manual",+ None => "unchecked",+ Some(p) if p.ok => "online",+ Some(_) => "offline",+ };+ machine_diagnostics(&mut diagnostics, spec, probe);+ diagnostics.sort_by_key(|d| level_rank(&d.level));++ let platform = probe_ok+ .map(|p| util::platform(p.os.as_deref().unwrap_or(""), p.arch.as_deref().unwrap_or("")))+ .filter(|p| !p.is_empty())+ .or_else(|| spec.platform.clone())+ .unwrap_or_default();++ let summary = summarize(runners.iter().filter(|r| runner_ids.contains(&r.id)));+ machines.push(Machine {+ id: spec.id.clone(),+ name: spec.name.clone(),+ host: spec.host.trim().to_string(),+ local: spec.is_local(),+ platform,+ kind: if runner_ids.is_empty() && spec.runners.is_empty() { "other" } else { "runner" }.into(),+ status: status.into(),+ checking: input.checking.contains(&spec.id),+ notes: spec.notes.clone(),+ runner_ids,+ summary,+ probe: probe.map(to_probe),+ diagnostics,+ workspaces_allowed: spec.workspaces && spec.is_checkable(),+ });+ }++ // Runners GitHub knows about that no machine claimed.+ let mut unassigned: Vec<(&String, &RunnerData)> = gh_runners+ .iter()+ .filter(|(key, _)| !claimed.contains(*key))+ .map(|(_, (scope, r))| (scope, *r))+ .collect();+ unassigned.sort_by(|a, b| a.1.name.cmp(&b.1.name));+ for (scope, r) in &unassigned {+ let job = running_jobs.iter().find(|j| j.runner_name.as_deref().is_some_and(|n| n.eq_ignore_ascii_case(&r.name)));+ runners.push(Runner {+ id: format!("github/{}", r.name),+ name: r.name.clone(),+ machine_id: None,+ state: github_state(r).into(),+ source: "github".into(),+ declared: false,+ labels: r.labels.clone(),+ github: Some(github_runner(scope, r)),+ local: None,+ job_id: job.map(|j| j.id),+ });+ }++ let jobs = build_jobs(gh, &runners);+ let counts = {+ let s = summarize(runners.iter());+ Counts {+ machines: machines.len(),+ runner_machines: machines.iter().filter(|m| m.kind == "runner").count(),+ other_machines: machines.iter().filter(|m| m.kind == "other").count(),+ runners: runners.len(),+ working: s.working,+ idle: s.idle,+ offline: s.offline,+ unknown: s.unknown,+ queued: jobs.queued.len(),+ running: jobs.running.len(),+ }+ };++ let detected = detected_scopes(input.settings, input.probes);+ let github = GitHubInfo {+ configured,+ live: github_live,+ syncing: input.github_syncing,+ token_source: gh.map(|g| g.token_source.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| input.token_source.clone()),+ login: gh.and_then(|g| g.login.clone()),+ last_sync_at: gh.and_then(|g| g.synced_at),+ error: gh.and_then(|g| g.error.clone()),+ scopes: gh+ .map(|g| {+ g.scopes+ .iter()+ .map(|s| ScopeStatus {+ kind: s.kind.as_str().into(),+ name: s.name.clone(),+ runners: s.runners.len(),+ synced_at: s.synced_at,+ error: s.error.clone(),+ hint: s.hint.clone(),+ })+ .collect()+ })+ .unwrap_or_default(),+ rate_limit: gh.and_then(|g| g.rate).map(|r| RateLimit { limit: r.limit, remaining: r.remaining, reset_at: r.reset_at }),+ detected,+ scanned_repos: gh.map(|g| g.scanned_repos.clone()).unwrap_or_default(),+ poll_seconds: input.settings.github_poll_seconds,+ };++ let attention = attention(input, &machines, &runners, &jobs, &github, unassigned.len());+ let updated_at = [input.check.finished_at, github.last_sync_at].into_iter().flatten().max();++ Snapshot {+ version: 0,+ generated_at: input.now,+ updated_at,+ demo: input.demo,+ inventory: input.inventory_info.clone(),+ check: input.check.clone(),+ github,+ counts,+ machines,+ runners,+ jobs,+ attention,+ operations: Vec::new(),+ workspaces: Vec::new(),+ }+}++fn github_state(r: &RunnerData) -> &'static str {+ match (r.status.as_str(), r.busy) {+ ("online", true) => "working",+ ("online", false) => "idle",+ _ => "offline",+ }+}++fn local_state(r: &ProbedRunner) -> &'static str {+ match (r.listener_pid, r.worker_pid) {+ (_, Some(_)) => "working",+ (Some(_), None) => "idle",+ _ => "offline",+ }+}++fn github_runner(scope: &str, r: &RunnerData) -> GitHubRunner {+ GitHubRunner {+ id: r.id,+ status: r.status.clone(),+ busy: r.busy,+ os: r.os.clone(),+ scope: scope.to_string(),+ labels: r.labels.clone(),+ }+}++fn local_runner(r: &ProbedRunner) -> LocalRunner {+ LocalRunner {+ dir: r.dir.clone(),+ url: r.url.clone(),+ version: r.version.clone(),+ service: r.service.clone(),+ service_state: r.service_state.clone(),+ listener: r.listener_pid.is_some(),+ worker: r.worker_pid.is_some(),+ listener_pid: r.listener_pid,+ worker_pid: r.worker_pid,+ container: r.container.clone(),+ image: r.image.clone(),+ container_state: r.container_state.clone(),+ restarts: r.restarts,+ }+}++fn to_probe(p: &ProbeResult) -> Probe {+ Probe {+ checked_at: p.checked_at,+ duration_ms: p.duration_ms,+ ok: p.ok,+ error: p.error.clone(),+ hostname: p.hostname.clone(),+ os: p.os.clone(),+ arch: p.arch.clone(),+ os_version: p.os_version.clone(),+ cores: p.cores,+ cpu_pct: p.cpu_pct,+ mem_total: p.mem_total,+ mem_used: p.mem_used,+ disk_total: p.disk_total,+ disk_free: p.disk_free,+ disk_path: p.disk_path.clone(),+ uptime_sec: p.uptime_sec,+ load: p.load.clone(),+ docker: p.docker.clone(),+ sudo: p.sudo.clone(),+ }+}++fn summarize<'a>(runners: impl Iterator<Item = &'a Runner>) -> RunnerSummary {+ let mut s = RunnerSummary::default();+ for r in runners {+ s.total += 1;+ match r.state.as_str() {+ "working" => s.working += 1,+ "idle" => s.idle += 1,+ "offline" => s.offline += 1,+ _ => s.unknown += 1,+ }+ }+ s+}++fn diag(level: &str, code: &str, message: String, hint: Option<String>, runner_id: Option<&str>) -> Diagnostic {+ Diagnostic { level: level.into(), code: code.into(), message, hint, runner_id: runner_id.map(str::to_string) }+}++fn level_rank(level: &str) -> u8 {+ match level {+ "error" => 0,+ "warning" => 1,+ "unknown" => 2,+ _ => 3,+ }+}++#[allow(clippy::too_many_arguments)]+fn runner_diagnostics(+ out: &mut Vec<Diagnostic>,+ id: &str,+ name: &str,+ declared: bool,+ local: Option<&ProbedRunner>,+ probe_ok: Option<&ProbeResult>,+ gh: Option<&RunnerData>,+ github_live: bool,+ latest_version: Option<&str>,+) {+ let rid = Some(id);+ if let Some(p) = probe_ok {+ match local {+ None if declared => out.push(diag(+ "warning",+ "runner-missing",+ format!("{name} isn't installed here: no runner folder with that name was found."),+ Some(if p.os.as_deref() == Some("windows") {+ "If it lives somewhere unusual, add its folder to runner_dirs in fleet.toml.".into()+ } else {+ "If it lives somewhere unusual, add its folder to runner_dirs in fleet.toml (globs work).".into()+ }),+ rid,+ )),+ Some(l) if l.container.is_some() && (l.container_state.as_deref() == Some("restarting") || l.restarts.unwrap_or(0) >= CRASH_LOOP_RESTARTS) => {+ let c = l.container.as_deref().unwrap_or_default();+ out.push(diag(+ "warning",+ "container-restarting",+ format!("{name}'s container keeps restarting ({} restarts).", l.restarts.unwrap_or(0)),+ Some(format!("docker logs --tail 50 {c}")),+ rid,+ ));+ }+ Some(l) if l.container.is_some() && l.listener_pid.is_none() => {+ let c = l.container.as_deref().unwrap_or_default();+ let state = l.container_state.as_deref().unwrap_or("stopped");+ out.push(diag("warning", "runner-stopped", format!("{name}'s container is {state}."), Some(format!("docker start {c}")), rid));+ }+ Some(l) if l.listener_pid.is_none() => {+ let hint = match (l.service.is_some(), p.os.as_deref()) {+ (true, Some("linux")) => format!("cd {} && sudo ./svc.sh start", l.dir),+ (true, Some("windows")) => format!("Start-Service {}", l.service.as_deref().unwrap_or_default()),+ (true, _) => format!("cd {} && ./svc.sh start", l.dir),+ (false, Some("windows")) => format!("cd {}; .\\run.cmd", l.dir),+ (false, _) => format!("cd {} && ./run.sh", l.dir),+ };+ out.push(diag("warning", "runner-stopped", format!("{name} is installed but not running."), Some(hint), rid));+ }+ Some(l) if gh.is_some_and(|g| g.status == "offline") => out.push(diag(+ "warning",+ "github-offline",+ format!("{name} is running here, but GitHub reports it offline."),+ Some(match &l.container {+ Some(c) => format!("docker logs --tail 50 {c}"),+ None => format!("Check the newest log in {}/_diag", l.dir),+ }),+ rid,+ )),+ _ => {}+ }+ if let (Some(l), Some(latest)) = (local, latest_version) {+ if let Some(v) = l.version.as_deref() {+ if version_lt(v, latest) {+ out.push(diag("info", "update-available", format!("{name} runs {v}; {latest} is available."), None, rid));+ }+ }+ }+ } else if gh.is_some_and(|g| g.status == "offline") {+ out.push(diag("warning", "github-offline", format!("{name} is offline on GitHub."), None, rid));+ }++ if github_live && gh.is_none() && (local.is_some() || declared) {+ out.push(diag(+ "unknown",+ "not-on-github",+ format!("{name} wasn't found in the GitHub orgs and repos you watch."),+ local+ .and_then(|l| l.url.as_deref())+ .and_then(scope_from_runner_url)+ .map(|s| format!("It's registered to {s}. Add it in Settings.")),+ rid,+ ));+ }+}++fn machine_diagnostics(out: &mut Vec<Diagnostic>, spec: &MachineSpec, probe: Option<&ProbeResult>) {+ if !spec.is_checkable() {+ out.push(diag(+ "info",+ "no-host",+ "No host configured, so this machine isn't checked.".into(),+ Some("Set host in fleet.toml (an ssh destination, or \"local\").".into()),+ None,+ ));+ return;+ }+ let Some(p) = probe else { return };+ if !p.ok {+ let reason = p.error.clone().unwrap_or_else(|| "The check failed.".into());+ let hint = (!spec.is_local()).then(|| format!("ssh {} # must work without a password prompt", spec.host.trim()));+ out.push(diag("error", "unreachable", format!("Unreachable: {reason}"), hint, None));+ return;+ }+ if let (Some(total), Some(free)) = (p.disk_total, p.disk_free) {+ if free < LOW_DISK_BYTES || (free as f64) < total as f64 * LOW_DISK_FRACTION {+ out.push(diag(+ "warning",+ "low-disk",+ format!("Low disk space: {} free of {}.", util::bytes(free), util::bytes(total)),+ Some("Runner _work folders and toolcaches grow over time; clean them up or add space.".into()),+ None,+ ));+ }+ }+ if let Some(err) = &p.docker_error {+ out.push(diag(+ "info",+ "docker-unusable",+ format!("Docker is installed but can't be used: {err}"),+ Some("sudo usermod -aG docker $USER # then log in again".into()),+ None,+ ));+ }+ if let (Some(total), Some(used)) = (p.mem_total, p.mem_used) {+ if used as f64 > total as f64 * HIGH_MEMORY_FRACTION {+ out.push(diag(+ "warning",+ "high-memory",+ format!("Memory is nearly full: {} of {} used.", util::bytes(used), util::bytes(total)),+ None,+ None,+ ));+ }+ }+}++/// "2.317.0" < "2.321.0"+fn version_lt(a: &str, b: &str) -> bool {+ let parse = |v: &str| -> Vec<u32> { v.trim_start_matches('v').split('.').map(|p| p.parse().unwrap_or(0)).collect() };+ parse(a) < parse(b)+}++fn labels_satisfied(job: &[String], runner: &[String]) -> bool {+ !runner.is_empty() && job.iter().all(|l| runner.iter().any(|r| r.eq_ignore_ascii_case(l)))+}++fn build_jobs(gh: Option<&GitHubData>, runners: &[Runner]) -> Jobs {+ let Some(gh) = gh else { return Jobs::default() };+ let by_name: HashMap<String, &Runner> = runners.iter().map(|r| (r.name.to_ascii_lowercase(), r)).collect();+ let mut jobs = Jobs::default();++ for j in &gh.jobs {+ let runner = j.runner_name.as_deref().and_then(|n| by_name.get(&n.to_ascii_lowercase()));+ let self_hosted_label = j.labels.iter().any(|l| l.eq_ignore_ascii_case("self-hosted"));+ let matching: Vec<&Runner> = if j.labels.is_empty() {+ Vec::new()+ } else {+ runners.iter().filter(|r| labels_satisfied(&j.labels, &r.labels)).collect()+ };++ let keep = match j.status.as_str() {+ "in_progress" => runner.is_some() || self_hosted_label,+ _ => {+ self_hosted_label+ || !matching.is_empty()+ || (!j.labels.is_empty() && !j.labels.iter().all(|l| is_github_hosted_label(l)))+ }+ };+ if !keep {+ continue;+ }++ let job = Job {+ id: j.id,+ run_id: j.run_id,+ name: j.name.clone(),+ workflow: j.workflow.clone(),+ repo: j.repo.clone(),+ branch: j.branch.clone(),+ event: j.event.clone(),+ actor: j.actor.clone(),+ url: j.url.clone(),+ status: j.status.clone(),+ labels: j.labels.clone(),+ runner_name: j.runner_name.clone(),+ runner_id: runner.map(|r| r.id.clone()),+ created_at: j.created_at,+ started_at: j.started_at,+ matching_online: matching.iter().filter(|r| matches!(r.state.as_str(), "working" | "idle")).count(),+ matching: matching.iter().map(|r| r.id.clone()).collect(),+ };+ if j.status == "in_progress" { jobs.running.push(job) } else { jobs.queued.push(job) }+ }+ jobs.queued.sort_by_key(|j| j.created_at);+ jobs.running.sort_by_key(|j| j.started_at.unwrap_or(j.created_at));+ jobs+}++/// Orgs/repos named in runner configs that aren't being watched yet.+fn detected_scopes(settings: &Settings, probes: &HashMap<String, ProbeResult>) -> Vec<String> {+ let watched: HashSet<String> =+ settings.github.orgs.iter().chain(settings.github.repos.iter()).map(|s| s.to_ascii_lowercase()).collect();+ let mut found: Vec<String> = Vec::new();+ for p in probes.values().filter(|p| p.ok) {+ for r in &p.runners {+ if let Some(scope) = r.url.as_deref().and_then(scope_from_runner_url) {+ let owner = scope.split('/').next().unwrap_or_default().to_ascii_lowercase();+ let lower = scope.to_ascii_lowercase();+ if !watched.contains(&lower) && !watched.contains(&owner) && !found.iter().any(|f| f.eq_ignore_ascii_case(&scope)) {+ found.push(scope);+ }+ }+ }+ }+ found.sort();+ found+}++fn attention(+ input: &Inputs,+ machines: &[Machine],+ runners: &[Runner],+ jobs: &Jobs,+ github: &GitHubInfo,+ unassigned: usize,+) -> Vec<Attention> {+ let mut out = Vec::new();+ let action = |label: &str, kind: &str, target: Option<String>| Some(Action { label: label.into(), kind: kind.into(), target });++ if let Some(err) = &input.inventory_info.error {+ out.push(Attention {+ id: "inventory-error".into(),+ level: "error".into(),+ title: "fleet.toml couldn't be read".into(),+ detail: format!("{err} Showing the last good inventory."),+ action: None,+ });+ }++ let no_token = github.token_source.is_empty() && !input.demo;+ if no_token {+ out.push(Attention {+ id: "github-token".into(),+ level: "warning".into(),+ title: "Connect GitHub".into(),+ detail: "Sign in with `gh auth login` (or set GITHUB_TOKEN) to see live runner status and queued jobs.".into(),+ action: action("Settings", "settings", None),+ });+ } else if !github.configured {+ let who = github.detected.first().cloned().unwrap_or_else(|| "your runners".into());+ out.push(Attention {+ id: "github-setup".into(),+ level: "warning".into(),+ title: format!("Watch {who} on GitHub live"),+ detail: "Runner state now comes from the last check. Add the organization in Settings (it uses your gh login) for live status and jobs.".into(),+ action: action("Add organization", "settings", None),+ });+ }++ for s in github.scopes.iter().filter(|s| s.error.is_some()) {+ let mut detail = s.error.clone().unwrap_or_default();+ if let Some(h) = &s.hint {+ detail.push_str(&format!(" Run `{h}`."));+ }+ out.push(Attention {+ id: format!("scope-{}-{}", s.kind, s.name),+ level: "error".into(),+ title: format!("Can't read runners for {}", s.name),+ detail,+ action: action("Settings", "settings", None),+ });+ }++ let unreachable: Vec<&Machine> = machines.iter().filter(|m| m.status == "offline").collect();+ match unreachable.as_slice() {+ [] => {}+ [m] => out.push(Attention {+ id: "unreachable".into(),+ level: "warning".into(),+ title: format!("{} is unreachable", m.name),+ detail: m.probe.as_ref().and_then(|p| p.error.clone()).unwrap_or_default(),+ action: action("View machine", "machine", Some(m.id.clone())),+ }),+ many => out.push(Attention {+ id: "unreachable".into(),+ level: "warning".into(),+ title: format!("{} machines are unreachable", many.len()),+ detail: many.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", "),+ action: action("Check again", "check", None),+ }),+ }++ // Runners that should be up but aren't, on machines we could reach (unreachable ones are covered above).+ let down: Vec<&Runner> = runners+ .iter()+ .filter(|r| r.state == "offline")+ .filter(|r| match &r.machine_id {+ Some(mid) => machines.iter().any(|m| &m.id == mid && m.status != "offline"),+ None => true,+ })+ .collect();+ match down.as_slice() {+ [] => {}+ [r] => out.push(Attention {+ id: "runners-offline".into(),+ level: "warning".into(),+ title: format!("{} is offline", r.name),+ detail: machines+ .iter()+ .flat_map(|m| &m.diagnostics)+ .find(|d| d.runner_id.as_deref() == Some(&r.id))+ .map(|d| d.message.clone())+ .unwrap_or_else(|| "It isn't connected to GitHub.".into()),+ action: action("View runner", "runner", Some(r.id.clone())),+ }),+ many => out.push(Attention {+ id: "runners-offline".into(),+ level: "warning".into(),+ title: format!("{} runners are offline", many.len()),+ detail: many.iter().map(|r| r.name.as_str()).collect::<Vec<_>>().join(", "),+ action: None,+ }),+ }++ let stuck: Vec<&Job> = jobs+ .queued+ .iter()+ .filter(|j| j.matching_online == 0 && (input.now - j.created_at).num_seconds() >= STUCK_JOB_SECS)+ .collect();+ if let Some(first) = stuck.first() {+ let waited = util::short_duration((input.now - first.created_at).num_seconds().max(0) as u64);+ let labels = first.labels.join(", ");+ let (title, detail) = if stuck.len() == 1 {+ (+ format!("“{}” can't find a runner", first.name),+ format!("Queued {waited} in {} — no online runner has the labels {labels}.", first.repo),+ )+ } else {+ (+ format!("{} jobs can't find a runner", stuck.len()),+ format!("The oldest, “{}” in {}, has waited {waited} for {labels}.", first.name, first.repo),+ )+ };+ out.push(Attention { id: "stuck-jobs".into(), level: "warning".into(), title, detail, action: action("View queue", "queue", None) });+ }++ for m in machines {+ if let Some(d) = m.diagnostics.iter().find(|d| d.code == "low-disk") {+ out.push(Attention {+ id: format!("low-disk-{}", m.id),+ level: "warning".into(),+ title: format!("{} is low on disk", m.name),+ detail: d.message.clone(),+ action: action("View machine", "machine", Some(m.id.clone())),+ });+ }+ }++ if unassigned > 0 {+ let names: Vec<&str> = runners.iter().filter(|r| r.machine_id.is_none()).map(|r| r.name.as_str()).take(5).collect();+ out.push(Attention {+ id: "unassigned".into(),+ level: "info".into(),+ title: if unassigned == 1 {+ format!("{} isn't in fleet.toml", names[0])+ } else {+ format!("{unassigned} GitHub runners aren't in fleet.toml")+ },+ detail: format!(+ "{} {} registered on GitHub but no machine lists {}. Add {} to a [[machine]]'s runners to track {}.",+ names.join(", "),+ if unassigned == 1 { "is" } else { "are" },+ if unassigned == 1 { "it" } else { "them" },+ if unassigned == 1 { "it" } else { "them" },+ if unassigned == 1 { "its host" } else { "their hosts" },+ ),+ action: None,+ });+ }++ if let Some(rate) = &github.rate_limit {+ if rate.limit > 0 && (rate.remaining as f64) < rate.limit as f64 * 0.1 {+ out.push(Attention {+ id: "rate-limit".into(),+ level: "warning".into(),+ title: "GitHub API rate limit is almost used up".into(),+ detail: format!(+ "{} of {} requests left until {}. Raise the poll interval in Settings.",+ rate.remaining,+ rate.limit,+ rate.reset_at.with_timezone(&chrono::Local).format("%H:%M")+ ),+ action: action("Settings", "settings", None),+ });+ }+ }++ for (i, w) in input.inventory_info.warnings.iter().enumerate() {+ out.push(Attention {+ id: format!("inventory-warning-{i}"),+ level: "info".into(),+ title: "fleet.toml".into(),+ detail: w.clone(),+ action: None,+ });+ }++ out.sort_by_key(|a| level_rank(&a.level));+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::github::{ScopeData, ScopeKind};++ fn inventory(toml: &str) -> Inventory {+ Inventory::parse(toml).unwrap()+ }++ fn probe_with(runners: Vec<ProbedRunner>) -> ProbeResult {+ ProbeResult {+ checked_at: Utc::now(),+ ok: true,+ os: Some("darwin".into()),+ arch: Some("arm64".into()),+ disk_total: Some(1_000_000_000_000),+ disk_free: Some(500_000_000_000),+ runners,+ ..Default::default()+ }+ }++ fn local(name: &str, listener: bool, worker: bool) -> ProbedRunner {+ ProbedRunner {+ dir: format!("/Users/ci/{name}"),+ name: name.into(),+ listener_pid: listener.then_some(10),+ worker_pid: worker.then_some(11),+ url: Some("https://github.com/acme".into()),+ ..Default::default()+ }+ }++ fn gh_runner(name: &str, status: &str, busy: bool, labels: &[&str]) -> RunnerData {+ RunnerData {+ id: 1,+ name: name.into(),+ os: "macOS".into(),+ status: status.into(),+ busy,+ labels: labels.iter().map(|s| s.to_string()).collect(),+ }+ }++ fn run(inv: &Inventory, settings: &Settings, probes: &HashMap<String, ProbeResult>, gh: Option<&GitHubData>) -> Snapshot {+ build(&Inputs {+ now: Utc::now(),+ demo: false,+ inventory: inv,+ inventory_info: InventoryInfo::default(),+ settings,+ probes,+ checking: &HashSet::new(),+ check: CheckInfo::default(),+ github: gh,+ github_syncing: false,+ token_source: "gh".into(),+ })+ }++ #[test]+ fn probe_only_states_and_missing_runners() {+ let inv = inventory(+ r#"+ [[machine]]+ name = "Studio"+ host = "studio"+ runners = ["s-01", "s-02", "s-03"]++ [[machine]]+ name = "NAS"+ host = "nas"+ "#,+ );+ let mut probes = HashMap::new();+ probes.insert("studio".to_string(), probe_with(vec![local("s-01", true, true), local("s-02", true, false), local("extra", false, false)]));+ let snap = run(&inv, &Settings::default(), &probes, None);++ let state = |id: &str| snap.runners.iter().find(|r| r.id == id).unwrap().state.clone();+ assert_eq!(state("studio/s-01"), "working");+ assert_eq!(state("studio/s-02"), "idle");+ assert_eq!(state("studio/s-03"), "offline"); // declared, not installed+ assert_eq!(state("studio/extra"), "offline"); // discovered, stopped+ assert_eq!(snap.machines[0].kind, "runner");+ assert_eq!(snap.machines[1].kind, "other");+ assert_eq!(snap.machines[1].status, "unchecked");+ let codes: Vec<&str> = snap.machines[0].diagnostics.iter().map(|d| d.code.as_str()).collect();+ assert!(codes.contains(&"runner-missing"));+ assert!(codes.contains(&"runner-stopped"));+ assert_eq!(snap.counts.working, 1);+ // Not watching GitHub yet, and the runner config names the org.+ assert_eq!(snap.github.detected, vec!["acme"]);+ assert!(snap.attention.iter().any(|a| a.id == "github-setup" && a.title.contains("acme")));+ }++ #[test]+ fn github_state_wins_and_jobs_are_matched() {+ let inv = inventory("[[machine]]\nname = \"Studio\"\nhost = \"studio\"\nrunners = [\"s-01\"]\n");+ let mut probes = HashMap::new();+ probes.insert("studio".to_string(), probe_with(vec![local("s-01", true, false)]));+ let mut settings = Settings::default();+ settings.github.orgs = vec!["acme".into()];+ let now = Utc::now();+ let job = |id: u64, status: &str, labels: &[&str], runner: Option<&str>| JobData {+ id,+ run_id: 1,+ name: format!("job-{id}"),+ workflow: "CI".into(),+ repo: "acme/api".into(),+ branch: None,+ event: None,+ actor: None,+ url: String::new(),+ status: status.into(),+ labels: labels.iter().map(|s| s.to_string()).collect(),+ runner_name: runner.map(str::to_string),+ created_at: now - chrono::Duration::minutes(10),+ started_at: None,+ };+ let gh = GitHubData {+ synced_at: Some(now),+ token_source: "gh".into(),+ scopes: vec![ScopeData {+ kind: ScopeKind::Org,+ name: "acme".into(),+ runners: vec![+ gh_runner("s-01", "online", true, &["self-hosted", "macOS", "ARM64"]),+ gh_runner("cloud-01", "offline", false, &["self-hosted", "linux"]),+ ],+ synced_at: Some(now),+ error: None,+ hint: None,+ }],+ jobs: vec![+ job(1, "in_progress", &["self-hosted", "macOS"], Some("s-01")),+ job(2, "queued", &["self-hosted", "macos"], None),+ job(3, "queued", &["self-hosted", "gpu"], None),+ job(4, "queued", &["ubuntu-latest"], None),+ job(5, "in_progress", &["ubuntu-latest"], Some("GitHub Actions 3")),+ ],+ ..Default::default()+ };+ let snap = run(&inv, &settings, &probes, Some(&gh));++ let s01 = snap.runners.iter().find(|r| r.name == "s-01").unwrap();+ assert_eq!(s01.state, "working");+ assert_eq!(s01.source, "github");+ assert_eq!(s01.job_id, Some(1));+ // GitHub runner with no machine.+ let cloud = snap.runners.iter().find(|r| r.name == "cloud-01").unwrap();+ assert!(cloud.machine_id.is_none());+ assert_eq!(cloud.id, "github/cloud-01");++ assert_eq!(snap.jobs.running.iter().map(|j| j.id).collect::<Vec<_>>(), vec![1]);+ assert_eq!(snap.jobs.queued.iter().map(|j| j.id).collect::<Vec<_>>(), vec![2, 3]);+ assert_eq!(snap.jobs.queued[0].matching, vec!["studio/s-01"]);+ assert_eq!(snap.jobs.queued[0].matching_online, 1);+ assert_eq!(snap.jobs.queued[1].matching_online, 0);+ assert!(snap.attention.iter().any(|a| a.id == "stuck-jobs"));+ assert!(snap.attention.iter().any(|a| a.id == "unassigned"));+ assert!(snap.github.live);+ }++ #[test]+ fn unreachable_machine_is_an_error_diagnostic() {+ let inv = inventory("[[machine]]\nname = \"Mini\"\nhost = \"mini\"\nrunners = [\"m-01\"]\n");+ let mut probes = HashMap::new();+ probes.insert(+ "mini".to_string(),+ ProbeResult { ok: false, error: Some("ssh: connect timed out".into()), ..Default::default() },+ );+ let snap = run(&inv, &Settings::default(), &probes, None);+ assert_eq!(snap.machines[0].status, "offline");+ assert_eq!(snap.machines[0].diagnostics[0].code, "unreachable");+ assert_eq!(snap.runners[0].state, "unknown");+ assert!(snap.attention.iter().any(|a| a.id == "unreachable"));+ }++ #[test]+ fn compares_versions() {+ assert!(version_lt("2.317.0", "2.321.0"));+ assert!(!version_lt("2.321.0", "2.321.0"));+ assert!(version_lt("2.99.0", "2.100.0"));+ }+}diff --git a/src/fleet/engine.rs b/src/fleet/engine.rsnew file mode 100644index 0000000..552aa40--- /dev/null+++ b/src/fleet/engine.rs@@ -0,0 +1,746 @@+//! Owns fleet state, runs the GitHub poll loop and scheduled machine checks, and+//! publishes a fresh `Snapshot` (as JSON) every time something changes.++use std::collections::{HashMap, HashSet, VecDeque};+use std::path::Path;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant, SystemTime};++use chrono::{DateTime, Utc};+use futures::stream::{FuturesUnordered, StreamExt};+use tokio::runtime::Handle;+use tokio::sync::{watch, Notify};++use super::build::{build, Inputs};+use super::model::{CheckInfo, InventoryInfo, Operation, Snapshot};+use super::workspaces::{self as workspaces, WorkspaceRecord};+use crate::config::{default_inventory, display_path, write_atomic, Inventory, MachineSpec, Paths, PersistedState, Settings};+use crate::demo::World;+use crate::github::{self, GitHubData, ScopeTest};+use crate::probe::{self, ProbeResult};++const DEMO_POLL: Duration = Duration::from_secs(3);+const MAX_OPERATIONS: usize = 30;+const MAX_OP_LOG_LINES: usize = 2000;+/// Operation output can be chatty; coalesce snapshot publishes to this rate.+const OP_PUBLISH_INTERVAL: Duration = Duration::from_millis(120);++struct State {+ inventory: Inventory,+ inventory_info: InventoryInfo,+ inventory_mtime: Option<SystemTime>,+ settings: Settings,+ probes: HashMap<String, ProbeResult>,+ checking: HashSet<String>,+ check_running: bool,+ check_started_at: Option<DateTime<Utc>>,+ check_finished_at: Option<DateTime<Utc>>,+ github: Option<GitHubData>,+ github_syncing: bool,+ token_source: String,+ version: u64,+ operations: VecDeque<Operation>,+ next_op: u64,+ last_publish: Option<Instant>,+ publish_scheduled: bool,+ /// Modification times of the files we last read or wrote, so changes made+ /// by another OpenRunner process (the window, the CLI, an agent's MCP+ /// server) are noticed. See `sync_from_disk`.+ settings_mtime: Option<SystemTime>,+ state_mtime: Option<SystemTime>,+ /// Agent workspaces (see fleet::workspaces), shared through workspaces.json.+ workspaces: Vec<WorkspaceRecord>,+ workspaces_mtime: Option<SystemTime>,+}++pub struct Engine {+ paths: Paths,+ demo: Option<Arc<World>>,+ github: github::Client,+ rt: Handle,+ state: Mutex<State>,+ tx: watch::Sender<Arc<Snapshot>>,+ sync_now: Notify,+ settings_changed: Notify,+}++impl Engine {+ /// Must be called from within a tokio runtime; background work runs there.+ pub fn new(paths: Paths, demo: bool) -> Arc<Engine> {+ let world = demo.then(|| Arc::new(World::new()));+ let (inventory, inventory_info, settings, persisted) = match &world {+ Some(w) => (+ w.inventory(),+ InventoryInfo { path: "demo://fleet.toml".into(), loaded_at: Some(Utc::now()), ..Default::default() },+ w.settings(),+ PersistedState::default(),+ ),+ None => {+ ensure_inventory(&paths);+ (+ Inventory::default(),+ InventoryInfo { path: display_path(&paths.inventory), ..Default::default() },+ Settings::load(&paths.settings),+ PersistedState::load(&paths.state),+ )+ }+ };+ let state = State {+ inventory,+ inventory_info,+ inventory_mtime: None,+ settings,+ probes: persisted.probes,+ checking: HashSet::new(),+ check_running: false,+ check_started_at: persisted.check_started_at,+ check_finished_at: persisted.check_finished_at,+ github: None,+ github_syncing: false,+ token_source: String::new(),+ version: 0,+ operations: VecDeque::new(),+ next_op: 1,+ last_publish: None,+ publish_scheduled: false,+ settings_mtime: mtime(&paths.settings),+ state_mtime: mtime(&paths.state),+ workspaces: match &world {+ Some(w) => workspaces::demo_seed(w),+ None => workspaces::load_registry(&paths.workspaces),+ },+ workspaces_mtime: mtime(&paths.workspaces),+ };+ let (tx, _) = watch::channel(Arc::new(Snapshot::default()));+ let engine = Arc::new(Engine {+ paths,+ demo: world,+ github: github::Client::new(),+ rt: Handle::current(),+ state: Mutex::new(state),+ tx,+ sync_now: Notify::new(),+ settings_changed: Notify::new(),+ });+ {+ let mut st = engine.state.lock().unwrap();+ if engine.demo.is_none() {+ engine.reload_inventory(&mut st, true);+ let known: HashSet<&String> = st.inventory.machines.iter().map(|m| &m.id).collect();+ let stale: Vec<String> = st.probes.keys().filter(|id| !known.contains(id)).cloned().collect();+ for id in stale {+ st.probes.remove(&id);+ }+ }+ engine.publish(&mut st);+ }+ engine+ }++ pub fn is_demo(&self) -> bool {+ self.demo.is_some()+ }++ pub fn paths(&self) -> &Paths {+ &self.paths+ }++ /// The tokio runtime the engine runs on. UI code uses it to run async engine calls.+ pub fn runtime(&self) -> &Handle {+ &self.rt+ }++ /// Starts the background loops. Call once.+ pub fn start(self: &Arc<Self>) {+ let me = self.clone();+ self.rt.spawn(async move { me.github_loop().await });+ let me = self.clone();+ self.rt.spawn(async move { me.check_loop().await });+ }++ pub fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {+ self.tx.subscribe()+ }++ pub fn current(&self) -> Arc<Snapshot> {+ self.tx.borrow().clone()+ }++ pub fn settings(&self) -> Settings {+ self.state.lock().unwrap().settings.clone()+ }++ pub fn update_settings(&self, new: Settings) -> Result<Settings, String> {+ let new = new.normalized()?;+ if self.demo.is_none() {+ new.save(&self.paths.settings).map_err(|e| format!("Couldn't save settings: {e:#}"))?;+ }+ {+ let mut st = self.state.lock().unwrap();+ st.settings_mtime = mtime(&self.paths.settings);+ let scopes_changed = st.settings.github != new.github;+ st.settings = new.clone();+ if scopes_changed && new.github.orgs.is_empty() && new.github.repos.is_empty() {+ st.github = None;+ }+ self.publish(&mut st);+ }+ self.settings_changed.notify_waiters();+ self.sync_now.notify_one();+ Ok(new)+ }++ pub async fn test_scope(&self, scope: &str) -> ScopeTest {+ let settings = self.settings();+ match &self.demo {+ Some(w) => w.test_scope(scope),+ None => self.github.test_scope(&settings.github, scope).await,+ }+ }++ /// Kicks off a machine check (all machines, or one) plus a GitHub refresh.+ pub fn trigger_check(self: &Arc<Self>, machine: Option<String>) {+ let me = self.clone();+ self.rt.spawn(async move { me.run_check(machine.map(|m| vec![m])).await });+ self.sync_now.notify_one();+ }++ #[cfg_attr(not(feature = "gui"), allow(dead_code))]+ pub fn trigger_sync(&self) {+ self.sync_now.notify_one();+ }++ /// One-shot check for the CLI: probe every machine, sync GitHub once, return the snapshot.+ pub async fn check_once(self: &Arc<Self>, with_github: bool) -> Snapshot {+ self.run_check(None).await;+ if with_github {+ self.sync_github().await;+ }+ (*self.current()).clone()+ }++ /// Picks up what other OpenRunner processes wrote to the shared config+ /// directory: fleet.toml edits, settings.json changes, and newer machine+ /// checks in state.json. Cheap when nothing changed (three `stat` calls).+ pub fn refresh_from_disk(&self) {+ if self.demo.is_some() {+ return;+ }+ let settings_changed = {+ let mut st = self.state.lock().unwrap();+ let inventory_changed = self.reload_inventory(&mut st, false);+ let settings_changed = self.reload_settings(&mut st);+ let state_changed = self.merge_disk_state(&mut st);+ let workspaces_changed = self.reload_workspaces(&mut st);+ if inventory_changed || settings_changed || state_changed || workspaces_changed {+ self.publish(&mut st);+ }+ settings_changed+ };+ if settings_changed {+ self.settings_changed.notify_waiters();+ self.sync_now.notify_one();+ }+ }++ // -----------------------------------------------------------------------+ // Plumbing for control operations (see crate::ops)++ pub(crate) fn github(&self) -> &github::Client {+ &self.github+ }++ pub(crate) fn demo_world(&self) -> Option<&Arc<World>> {+ self.demo.as_ref()+ }++ pub(crate) fn inventory_path(&self) -> &Path {+ &self.paths.inventory+ }++ /// The machine's inventory entry and its last check.+ pub(crate) fn machine(&self, id: &str) -> Option<(MachineSpec, Option<ProbeResult>)> {+ let st = self.state.lock().unwrap();+ let spec = st.inventory.machines.iter().find(|m| m.id == id)?.clone();+ Some((spec, st.probes.get(id).cloned()))+ }++ /// Re-reads fleet.toml right away (after OpenRunner edited it) and publishes.+ pub(crate) fn reload_inventory_now(&self) {+ let mut st = self.state.lock().unwrap();+ match &self.demo {+ Some(w) => {+ st.inventory = w.inventory();+ st.inventory_info.loaded_at = Some(Utc::now());+ }+ None => {+ self.reload_inventory(&mut st, true);+ }+ }+ let known: HashSet<String> = st.inventory.machines.iter().map(|m| m.id.clone()).collect();+ st.probes.retain(|id, _| known.contains(id));+ self.publish(&mut st);+ }++ /// Starts tracking an operation and returns its id.+ pub(crate) fn begin_op(&self, kind: &str, title: String, machine_id: Option<String>, runner_id: Option<String>) -> u64 {+ let mut st = self.state.lock().unwrap();+ let id = st.next_op;+ st.next_op += 1;+ st.operations.push_front(Operation {+ id,+ kind: kind.into(),+ title,+ machine_id,+ runner_id,+ status: "running".into(),+ started_at: Utc::now(),+ finished_at: None,+ log: Vec::new(),+ error: None,+ });+ // Drop the oldest finished operations.+ while st.operations.len() > MAX_OPERATIONS {+ match st.operations.iter().rposition(|o| o.status != "running") {+ Some(i) => {+ st.operations.remove(i);+ }+ None => break,+ }+ }+ self.publish(&mut st);+ id+ }++ /// Appends output to an operation. Publishing is coalesced.+ pub(crate) fn op_log(self: &Arc<Self>, id: u64, line: impl Into<String>) {+ let mut st = self.state.lock().unwrap();+ let Some(op) = st.operations.iter_mut().find(|o| o.id == id) else { return };+ op.log.push(line.into());+ if op.log.len() > MAX_OP_LOG_LINES {+ let extra = op.log.len() - MAX_OP_LOG_LINES;+ op.log.drain(..extra);+ }+ let due = st.last_publish.is_none_or(|t| t.elapsed() >= OP_PUBLISH_INTERVAL);+ if due {+ self.publish(&mut st);+ } else if !st.publish_scheduled {+ st.publish_scheduled = true;+ let me = self.clone();+ self.rt.spawn(async move {+ tokio::time::sleep(OP_PUBLISH_INTERVAL).await;+ let mut st = me.state.lock().unwrap();+ st.publish_scheduled = false;+ me.publish(&mut st);+ });+ }+ }++ pub(crate) fn op_finish(&self, id: u64, result: Result<(), String>) {+ let mut st = self.state.lock().unwrap();+ if let Some(op) = st.operations.iter_mut().find(|o| o.id == id) {+ op.finished_at = Some(Utc::now());+ match result {+ Ok(()) => op.status = "succeeded".into(),+ Err(e) => {+ op.status = "failed".into();+ op.error = Some(e);+ }+ }+ }+ self.publish(&mut st);+ }++ /// True while another operation is changing this machine.+ pub(crate) fn machine_busy(&self, machine_id: &str) -> bool {+ let st = self.state.lock().unwrap();+ st.operations+ .iter()+ .any(|o| o.status == "running" && o.kind != "logs" && o.machine_id.as_deref() == Some(machine_id))+ }++ /// Forgets finished operations (the activity panel's "Clear").+ /// The stored workspaces (see fleet::workspaces).+ pub(crate) fn workspace_records(&self) -> Vec<WorkspaceRecord> {+ self.state.lock().unwrap().workspaces.clone()+ }++ /// Changes the workspaces: in demo mode in memory, otherwise in workspaces.json+ /// under its lock (re-read first, so other processes' changes survive).+ pub(crate) fn update_workspaces<R>(&self, f: impl FnOnce(&mut Vec<WorkspaceRecord>) -> R) -> Result<R, String> {+ if self.demo.is_some() {+ let mut st = self.state.lock().unwrap();+ let result = f(&mut st.workspaces);+ self.publish(&mut st);+ return Ok(result);+ }+ let (result, list, modified) = workspaces::update_registry(&self.paths.workspaces, f)?;+ let mut st = self.state.lock().unwrap();+ st.workspaces = list;+ st.workspaces_mtime = modified;+ self.publish(&mut st);+ Ok(result)+ }++ /// Re-reads workspaces.json if another process changed it. Returns true if it did.+ fn reload_workspaces(&self, st: &mut State) -> bool {+ if self.demo.is_some() {+ return false;+ }+ let modified = mtime(&self.paths.workspaces);+ if modified == st.workspaces_mtime {+ return false;+ }+ st.workspaces_mtime = modified;+ st.workspaces = workspaces::load_registry(&self.paths.workspaces);+ true+ }++ #[cfg_attr(not(feature = "gui"), allow(dead_code))]+ pub fn clear_operations(&self) {+ let mut st = self.state.lock().unwrap();+ st.operations.retain(|o| o.status == "running");+ self.publish(&mut st);+ }++ // -----------------------------------------------------------------------++ async fn github_loop(self: Arc<Self>) {+ loop {+ self.sync_github().await;+ let poll = if self.demo.is_some() {+ DEMO_POLL+ } else {+ Duration::from_secs(self.state.lock().unwrap().settings.github_poll_seconds as u64)+ };+ tokio::select! {+ _ = tokio::time::sleep(poll) => {}+ _ = self.sync_now.notified() => {}+ }+ // Pick up fleet.toml edits (and settings/checks from other OpenRunner+ // processes) without waiting for the next full check.+ let before = self.state.lock().unwrap().inventory.machines.len();+ self.refresh_from_disk();+ let new_machines: Vec<String> = {+ let st = self.state.lock().unwrap();+ if st.inventory.machines.len() != before {+ st.inventory.machines.iter().filter(|m| !st.probes.contains_key(&m.id)).map(|m| m.id.clone()).collect()+ } else {+ Vec::new()+ }+ };+ if !new_machines.is_empty() {+ let me = self.clone();+ self.rt.spawn(async move { me.run_check(Some(new_machines)).await });+ }+ }+ }++ pub(crate) async fn sync_github(&self) {+ let settings = {+ let mut st = self.state.lock().unwrap();+ st.github_syncing = true;+ self.publish(&mut st);+ st.settings.clone()+ };+ let configured = !settings.github.orgs.is_empty() || !settings.github.repos.is_empty();+ let (data, token_source) = match &self.demo {+ Some(w) => (Some(w.github(&settings)), "gh".to_string()),+ None if configured => {+ let data = self.github.sync(&settings.github).await;+ let source = data.token_source.clone();+ (Some(data), source)+ }+ None => (None, self.github.token_source().await),+ };+ let mut st = self.state.lock().unwrap();+ // Settings may have changed while we were syncing; don't resurrect removed scopes.+ if st.settings.github == settings.github {+ st.github = data;+ }+ st.token_source = token_source;+ st.github_syncing = false;+ self.publish(&mut st);+ }++ async fn check_loop(self: Arc<Self>) {+ loop {+ let (interval, last) = {+ let st = self.state.lock().unwrap();+ (st.settings.check_interval_minutes, st.check_finished_at)+ };+ let wait = match (interval, last) {+ // Never checked: check once at startup even when automatic checks are off.+ (_, None) => Some(Duration::ZERO),+ (0, Some(_)) => None,+ (m, Some(t)) => {+ let due = t + chrono::Duration::minutes(m as i64);+ Some((due - Utc::now()).to_std().unwrap_or(Duration::ZERO))+ }+ };+ match wait {+ Some(d) => {+ tokio::select! {+ _ = tokio::time::sleep(d) => self.run_check(None).await,+ _ = self.settings_changed.notified() => {}+ }+ }+ None => self.settings_changed.notified().await,+ }+ }+ }++ /// Probes the given machines (or all), publishing as each one finishes.+ pub(crate) async fn run_check(self: &Arc<Self>, only: Option<Vec<String>>) {+ let full = only.is_none();+ let jobs: Vec<(MachineSpec, Option<probe::Shell>)> = {+ let mut st = self.state.lock().unwrap();+ if full && st.check_running {+ return;+ }+ if self.demo.is_none() {+ self.reload_inventory(&mut st, false);+ }+ let specs: Vec<MachineSpec> = st+ .inventory+ .machines+ .iter()+ .filter(|m| m.is_checkable())+ .filter(|m| only.as_ref().is_none_or(|ids| ids.contains(&m.id)))+ .filter(|m| !st.checking.contains(&m.id))+ .cloned()+ .collect();+ if full {+ st.check_running = true;+ st.check_started_at = Some(Utc::now());+ }+ for s in &specs {+ st.checking.insert(s.id.clone());+ }+ self.publish(&mut st);+ specs.into_iter().map(|s| {+ let shell = st.probes.get(&s.id).and_then(|p| p.shell);+ (s, shell)+ }).collect()+ };++ let mut pending: FuturesUnordered<_> = jobs+ .into_iter()+ .map(|(spec, shell)| {+ let demo = self.demo.clone();+ async move {+ let result = match demo {+ Some(w) => w.probe(&spec).await,+ None => probe::probe(&spec, shell).await,+ };+ (spec.id, result)+ }+ })+ .collect();++ while let Some((id, result)) = pending.next().await {+ let mut st = self.state.lock().unwrap();+ st.checking.remove(&id);+ st.probes.insert(id, result);+ self.publish(&mut st);+ }++ let mut st = self.state.lock().unwrap();+ if full {+ st.check_running = false;+ st.check_finished_at = Some(Utc::now());+ let known: HashSet<String> = st.inventory.machines.iter().map(|m| m.id.clone()).collect();+ st.probes.retain(|id, _| known.contains(id));+ self.settings_changed.notify_waiters(); // reschedule the next automatic check+ }+ if self.demo.is_none() {+ // Another process may have checked machines since we last looked;+ // fold those in first so this write doesn't throw them away.+ self.merge_disk_state(&mut st);+ let persisted = PersistedState {+ probes: st.probes.clone(),+ check_started_at: st.check_started_at,+ check_finished_at: st.check_finished_at,+ };+ match persisted.save(&self.paths.state) {+ Ok(()) => st.state_mtime = mtime(&self.paths.state),+ Err(e) => tracing::warn!("saving state: {e:#}"),+ }+ }+ self.publish(&mut st);+ }++ /// Re-reads settings.json if another process changed it. Returns true if the settings changed.+ fn reload_settings(&self, st: &mut State) -> bool {+ let modified = mtime(&self.paths.settings);+ if modified == st.settings_mtime {+ return false;+ }+ st.settings_mtime = modified;+ let loaded = Settings::load(&self.paths.settings);+ if loaded == st.settings {+ return false;+ }+ if loaded.github != st.settings.github && loaded.github.orgs.is_empty() && loaded.github.repos.is_empty() {+ st.github = None;+ }+ st.settings = loaded;+ true+ }++ /// Merges state.json into our probes when another process wrote it: per+ /// machine, the newer check wins, and machines we're checking right now are+ /// left alone. Returns true if anything changed.+ fn merge_disk_state(&self, st: &mut State) -> bool {+ let modified = mtime(&self.paths.state);+ if modified == st.state_mtime {+ return false;+ }+ st.state_mtime = modified;+ let disk = PersistedState::load(&self.paths.state);+ let known: HashSet<&str> = st.inventory.machines.iter().map(|m| m.id.as_str()).collect();+ let mut newer = Vec::new();+ for (id, probe) in disk.probes {+ let ours = st.probes.get(&id).map(|p| p.checked_at);+ if known.contains(id.as_str()) && !st.checking.contains(&id) && ours.is_none_or(|t| probe.checked_at > t) {+ newer.push((id, probe));+ }+ }+ let mut changed = !newer.is_empty();+ st.probes.extend(newer);+ if disk.check_finished_at > st.check_finished_at {+ st.check_started_at = disk.check_started_at;+ st.check_finished_at = disk.check_finished_at;+ changed = true;+ }+ changed+ }++ /// Re-reads fleet.toml when it changed (or `force`). Returns true if the inventory changed.+ /// On a parse error the last good inventory stays in place and the error is shown.+ fn reload_inventory(&self, st: &mut State, force: bool) -> bool {+ let path = &self.paths.inventory;+ let mtime = std::fs::metadata(path).and_then(|m| m.modified()).ok();+ if !force && mtime == st.inventory_mtime {+ return false;+ }+ st.inventory_mtime = mtime;+ st.inventory_info.path = display_path(path);+ match Inventory::load(path) {+ Ok(inv) => {+ st.inventory_info.error = None;+ st.inventory_info.warnings = inv.warnings.clone();+ st.inventory_info.loaded_at = Some(Utc::now());+ st.inventory = inv;+ true+ }+ Err(e) => {+ let msg = format!("{e:#}");+ if st.inventory_info.error.as_deref() != Some(&msg) {+ tracing::warn!("{msg}");+ }+ st.inventory_info.error = Some(msg);+ true+ }+ }+ }++ fn publish(&self, st: &mut State) {+ st.version += 1;+ st.last_publish = Some(Instant::now());+ let interval = st.settings.check_interval_minutes;+ let next_at = match (interval, st.check_finished_at) {+ (0, _) => None,+ (m, Some(t)) => Some(t + chrono::Duration::minutes(m as i64)),+ (_, None) => None,+ };+ let mut snapshot = build(&Inputs {+ now: Utc::now(),+ demo: self.demo.is_some(),+ inventory: &st.inventory,+ inventory_info: st.inventory_info.clone(),+ settings: &st.settings,+ probes: &st.probes,+ checking: &st.checking,+ check: CheckInfo {+ running: st.check_running,+ started_at: st.check_started_at,+ finished_at: st.check_finished_at,+ next_at,+ interval_minutes: interval,+ },+ github: st.github.as_ref(),+ github_syncing: st.github_syncing,+ token_source: st.token_source.clone(),+ });+ snapshot.version = st.version;+ snapshot.operations = st.operations.iter().cloned().collect();+ snapshot.workspaces = workspaces::snapshot_infos(&st.workspaces, &snapshot.machines, &st.inventory.machines);+ self.tx.send_replace(Arc::new(snapshot));+ }+}++fn mtime(path: &Path) -> Option<SystemTime> {+ std::fs::metadata(path).and_then(|m| m.modified()).ok()+}++/// Writes a starter fleet.toml (this computer only) the first time OpenRunner runs.+pub fn ensure_inventory(paths: &Paths) {+ if paths.inventory.exists() {+ return;+ }+ match write_atomic(&paths.inventory, default_inventory().as_bytes()) {+ Ok(()) => tracing::info!("created {}", display_path(&paths.inventory)),+ Err(e) => tracing::warn!("couldn't create {}: {e:#}", display_path(&paths.inventory)),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Two OpenRunner processes (say, the window and an agent's MCP server) share one config dir.+ #[tokio::test(flavor = "multi_thread")]+ async fn picks_up_changes_from_other_processes() {+ let dir = std::env::temp_dir().join(format!("openrunner-xproc-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("fleet.toml"), "[[machine]]\nname = \"Box\"\nhost = \"box.invalid\"\n").unwrap();+ let paths = Paths::resolve(Some(dir.clone()), None);+ let window = Engine::new(paths.clone(), false);+ let agent = Engine::new(paths.clone(), false);++ // Settings saved by one show up in the other.+ let mut s = agent.settings();+ s.github.orgs = vec!["acme".into()];+ agent.update_settings(s).unwrap();+ window.refresh_from_disk();+ assert_eq!(window.settings().github.orgs, vec!["acme"]);++ // A newer check written by one replaces the other's; an older one doesn't.+ let probe = |ok: bool, mins_ago: i64| ProbeResult {+ checked_at: Utc::now() - chrono::Duration::minutes(mins_ago),+ ok,+ os: Some("linux".into()),+ arch: Some("x86_64".into()),+ ..Default::default()+ };+ let write = |p: ProbeResult| {+ let mut state = PersistedState::default();+ state.check_finished_at = Some(p.checked_at);+ state.probes.insert("box".into(), p);+ state.save(&paths.state).unwrap();+ };+ write(probe(true, 1));+ window.refresh_from_disk();+ assert_eq!(window.current().machines[0].status, "online");+ assert_eq!(window.current().machines[0].platform, "linux-x64");++ write(probe(false, 30));+ std::thread::sleep(Duration::from_millis(5));+ window.refresh_from_disk();+ assert_eq!(window.current().machines[0].status, "online", "an older check must not win");++ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/src/fleet/mod.rs b/src/fleet/mod.rsnew file mode 100644index 0000000..05b0e45--- /dev/null+++ b/src/fleet/mod.rs@@ -0,0 +1,7 @@+pub mod build;+pub mod engine;+pub mod model;+pub mod report;+pub mod workspaces;++pub use engine::Engine;diff --git a/src/fleet/model.rs b/src/fleet/model.rsnew file mode 100644index 0000000..4ae7bf8--- /dev/null+++ b/src/fleet/model.rs@@ -0,0 +1,366 @@+//! The snapshot is the single document the dashboard renders. It is rebuilt+//! whenever inventory, machine checks or GitHub data change, and pushed to+//! browsers over SSE. Keep `web/src/types.ts` in sync with this file.++use chrono::{DateTime, Utc};+use serde::Serialize;++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct Snapshot {+ pub version: u64,+ pub generated_at: DateTime<Utc>,+ /// Latest of the last machine check and the last GitHub sync.+ pub updated_at: Option<DateTime<Utc>>,+ pub demo: bool,+ pub inventory: InventoryInfo,+ pub check: CheckInfo,+ pub github: GitHubInfo,+ pub counts: Counts,+ pub machines: Vec<Machine>,+ pub runners: Vec<Runner>,+ pub jobs: Jobs,+ pub attention: Vec<Attention>,+ /// Control operations (install, start, stop, ...), newest first.+ pub operations: Vec<Operation>,+ /// Agent workspaces on fleet machines, most recently used first.+ pub workspaces: Vec<WorkspaceInfo>,+}++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct InventoryInfo {+ pub path: String,+ pub loaded_at: Option<DateTime<Utc>>,+ pub error: Option<String>,+ pub warnings: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct CheckInfo {+ pub running: bool,+ pub started_at: Option<DateTime<Utc>>,+ pub finished_at: Option<DateTime<Utc>>,+ pub next_at: Option<DateTime<Utc>>,+ /// 0 means automatic checks are off.+ pub interval_minutes: u32,+}++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct GitHubInfo {+ /// At least one org or repo is configured.+ pub configured: bool,+ /// The last sync reached GitHub for at least one scope.+ pub live: bool,+ pub syncing: bool,+ /// "GITHUB_TOKEN", "GH_TOKEN", "OPENRUNNER_GITHUB_TOKEN", "gh" or "" when no token was found.+ pub token_source: String,+ pub login: Option<String>,+ pub last_sync_at: Option<DateTime<Utc>>,+ pub error: Option<String>,+ pub scopes: Vec<ScopeStatus>,+ pub rate_limit: Option<RateLimit>,+ /// Orgs/repos found in runner config files that aren't configured yet.+ pub detected: Vec<String>,+ pub scanned_repos: Vec<String>,+ pub poll_seconds: u32,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ScopeStatus {+ /// "org" or "repo"+ pub kind: String,+ pub name: String,+ pub runners: usize,+ pub synced_at: Option<DateTime<Utc>>,+ pub error: Option<String>,+ pub hint: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RateLimit {+ pub limit: u32,+ pub remaining: u32,+ pub reset_at: DateTime<Utc>,+}++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct Counts {+ pub machines: usize,+ pub runner_machines: usize,+ pub other_machines: usize,+ pub runners: usize,+ pub working: usize,+ pub idle: usize,+ pub offline: usize,+ pub unknown: usize,+ pub queued: usize,+ pub running: usize,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Machine {+ pub id: String,+ pub name: String,+ /// SSH destination, "local", or "" when the machine can't be checked.+ pub host: String,+ pub local: bool,+ /// e.g. "darwin-arm64", "linux-x64", "windows-x64". From the last check, else the inventory hint.+ pub platform: String,+ /// "runner" when it hosts runners, otherwise "other".+ pub kind: String,+ /// "online" | "offline" | "unchecked" | "manual"+ pub status: String,+ pub checking: bool,+ pub notes: Option<String>,+ pub runner_ids: Vec<String>,+ pub summary: RunnerSummary,+ pub probe: Option<Probe>,+ pub diagnostics: Vec<Diagnostic>,+ /// Agents may create workspaces here (fleet.toml `workspaces`, default true).+ pub workspaces_allowed: bool,+}++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct RunnerSummary {+ pub total: usize,+ pub working: usize,+ pub idle: usize,+ pub offline: usize,+ pub unknown: usize,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Probe {+ pub checked_at: DateTime<Utc>,+ pub duration_ms: u64,+ pub ok: bool,+ pub error: Option<String>,+ pub hostname: Option<String>,+ pub os: Option<String>,+ pub arch: Option<String>,+ pub os_version: Option<String>,+ pub cores: Option<u32>,+ pub cpu_pct: Option<f64>,+ pub mem_total: Option<u64>,+ pub mem_used: Option<u64>,+ pub disk_total: Option<u64>,+ pub disk_free: Option<u64>,+ pub disk_path: Option<String>,+ pub uptime_sec: Option<u64>,+ pub load: Vec<f64>,+ /// Docker server version, when the machine's user can use Docker.+ pub docker: Option<String>,+ /// Linux: "root" | "passwordless" | "password" — whether OpenRunner can install systemd services.+ pub sudo: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Diagnostic {+ /// "error" | "warning" | "unknown" | "info"+ pub level: String,+ pub code: String,+ pub message: String,+ pub hint: Option<String>,+ pub runner_id: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Runner {+ /// "<machineId>/<name>", or "github/<name>" when no machine claims it.+ pub id: String,+ pub name: String,+ /// None when GitHub knows the runner but the inventory doesn't.+ pub machine_id: Option<String>,+ /// "working" | "idle" | "offline" | "unknown"+ pub state: String,+ /// Where `state` came from: "github" (live) | "probe" (last check) | "none"+ pub source: String,+ /// Listed in fleet.toml (as opposed to discovered on the machine or on GitHub).+ pub declared: bool,+ pub labels: Vec<String>,+ pub github: Option<GitHubRunner>,+ pub local: Option<LocalRunner>,+ /// The job this runner is running, if known (see `jobs.running`).+ pub job_id: Option<u64>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct GitHubRunner {+ pub id: u64,+ /// "online" | "offline"+ pub status: String,+ pub busy: bool,+ pub os: String,+ /// "org:<name>" or "repo:<owner>/<name>"+ pub scope: String,+ pub labels: Vec<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct LocalRunner {+ pub dir: String,+ /// gitHubUrl from the runner's .runner file+ pub url: Option<String>,+ pub version: Option<String>,+ /// launchd / systemd / Windows service name, if installed as a service+ pub service: Option<String>,+ /// "active" | "inactive" | "unknown"+ pub service_state: Option<String>,+ pub listener: bool,+ pub worker: bool,+ pub listener_pid: Option<u32>,+ pub worker_pid: Option<u32>,+ /// Docker runners: the container (its `dir` is `docker://<container>`).+ pub container: Option<String>,+ pub image: Option<String>,+ /// "running" | "exited" | "restarting" | "created" | "paused" | "dead"+ pub container_state: Option<String>,+ /// Restarts Docker has done; a climbing count means a crash loop.+ pub restarts: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct Jobs {+ pub queued: Vec<Job>,+ pub running: Vec<Job>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Job {+ pub id: u64,+ pub run_id: u64,+ pub name: String,+ pub workflow: String,+ pub repo: String,+ pub branch: Option<String>,+ pub event: Option<String>,+ pub actor: Option<String>,+ pub url: String,+ /// "queued" | "in_progress" | "waiting"+ pub status: String,+ pub labels: Vec<String>,+ pub runner_name: Option<String>,+ pub runner_id: Option<String>,+ pub created_at: DateTime<Utc>,+ pub started_at: Option<DateTime<Utc>>,+ /// Queued jobs: runner ids whose labels satisfy the job's labels.+ pub matching: Vec<String>,+ /// How many of `matching` are currently online (working or idle).+ pub matching_online: usize,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Attention {+ pub id: String,+ /// "error" | "warning" | "info"+ pub level: String,+ pub title: String,+ pub detail: String,+ pub action: Option<Action>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Action {+ pub label: String,+ /// "settings" | "check" | "machine" | "runner" | "link" | "queue"+ pub kind: String,+ /// machine/runner id or URL, depending on `kind`+ pub target: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Operation {+ pub id: u64,+ /// "install" | "start" | "stop" | "restart" | "remove" | "logs" | "machine"+ pub kind: String,+ /// e.g. "Install mac-studio-08 on Mac Studio"+ pub title: String,+ pub machine_id: Option<String>,+ pub runner_id: Option<String>,+ /// "running" | "succeeded" | "failed"+ pub status: String,+ pub started_at: DateTime<Utc>,+ pub finished_at: Option<DateTime<Utc>>,+ /// Output lines, with secrets masked.+ pub log: Vec<String>,+ pub error: Option<String>,+}++/// A work environment an agent checked out on a fleet machine: a folder+/// (optionally a git checkout) where it runs commands and edits files.+#[derive(Debug, Clone, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WorkspaceInfo {+ /// "ws-7f3a2c"+ pub id: String,+ /// Human label: the name given at creation, else the repo name.+ pub name: String,+ pub machine_id: String,+ pub machine_name: String,+ pub host: String,+ pub platform: String,+ /// Absolute path on the machine.+ pub path: String,+ pub repo: Option<String>,+ pub git_ref: Option<String>,+ pub branch: Option<String>,+ /// Who created it, e.g. the MCP client name ("claude-code") or "cli" / "app".+ pub owner: Option<String>,+ /// "creating" | "ready" | "failed" | "destroying"+ pub status: String,+ pub error: Option<String>,+ pub created_at: DateTime<Utc>,+ pub last_used_at: DateTime<Utc>,+ /// Total commands run, including ones dropped from `history`.+ pub commands: usize,+ /// Recent commands, oldest first (capped).+ pub history: Vec<WorkspaceCommand>,+ /// For a human: opens a shell in the workspace, e.g. `ssh -t studio 'cd ~/openrunner/workspaces/ws-7f3a2c && exec $SHELL -l'`.+ pub shell: String,+ /// "host" (commands run directly on the machine) or "docker" (inside a container).+ #[serde(default = "host_isolation")]+ pub isolation: String,+ /// Docker workspaces: the image the container runs, e.g. "node:22".+ #[serde(default)]+ pub image: Option<String>,+ /// Docker workspaces: the container's name, e.g. "openrunner-ws-7f3a2c".+ #[serde(default)]+ pub container: Option<String>,+}++fn host_isolation() -> String {+ "host".into()+}++#[derive(Debug, Clone, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WorkspaceCommand {+ pub command: String,+ /// None while running, for background commands, or when it timed out.+ pub exit_code: Option<i32>,+ pub started_at: DateTime<Utc>,+ pub duration_ms: u64,+ /// Last lines of combined output.+ pub output_tail: Vec<String>,+ pub background: bool,+ pub timed_out: bool,+ pub by: Option<String>,+}diff --git a/src/fleet/report.rs b/src/fleet/report.rsnew file mode 100644index 0000000..782337a--- /dev/null+++ b/src/fleet/report.rs@@ -0,0 +1,136 @@+//! Plain-text fleet report for `openrunner check`.++use std::fmt::Write;++use chrono::Utc;++use super::model::{Machine, Snapshot};+use crate::util;++pub fn render(s: &Snapshot, color: bool) -> String {+ let paint = |code: &str, text: &str| if color { format!("\x1b[{code}m{text}\x1b[0m") } else { text.to_string() };+ let dim = |t: &str| paint("2", t);+ let bold = |t: &str| paint("1", t);+ let now = Utc::now();+ let c = &s.counts;+ let mut out = String::new();++ let _ = writeln!(out, "{} {}", bold("Fleet overview"), dim(&format!("{} machines · {} runners", c.machines, c.runners)));+ let _ = writeln!(+ out,+ "{} working {} idle {} offline {} unknown {} queued",+ paint("34", &c.working.to_string()),+ paint("32", &c.idle.to_string()),+ c.offline,+ c.unknown,+ c.queued+ );+ let source = if s.github.live { "live from GitHub".to_string() } else { "from the machine check (GitHub not connected)".to_string() };+ let _ = writeln!(out, "{}", dim(&format!("Inventory {} · runner state {source}", s.inventory.path)));+ out.push('\n');++ let headers = ["MACHINE", "PLATFORM", "RUNNERS", "CPU", "MEM", "DISK FREE", "UPTIME", "DIAGNOSTICS"];+ let rows: Vec<[String; 8]> = s.machines.iter().map(|m| row(m)).collect();+ let mut widths = headers.map(str::len);+ for r in &rows {+ for (i, cell) in r.iter().enumerate() {+ widths[i] = widths[i].max(cell.chars().count());+ }+ }+ let line = |cells: &[String]| {+ cells.iter().enumerate().map(|(i, c)| format!("{c:<w$}", w = widths[i])).collect::<Vec<_>>().join(" ").trim_end().to_string()+ };+ let _ = writeln!(out, "{}", dim(&line(&headers.map(String::from))));+ for (m, r) in s.machines.iter().zip(&rows) {+ let text = line(r);+ let text = match m.status.as_str() {+ "offline" => paint("31", &text),+ "online" => text,+ _ => dim(&text),+ };+ let _ = writeln!(out, "{text}");+ }++ if !s.jobs.running.is_empty() || !s.jobs.queued.is_empty() {+ out.push('\n');+ for j in &s.jobs.running {+ let since = j.started_at.unwrap_or(j.created_at);+ let _ = writeln!(+ out,+ "{} {} {} {} {}",+ paint("34", "▶"),+ j.runner_name.as_deref().unwrap_or("?"),+ j.name,+ dim(&j.repo),+ dim(&util::short_duration((now - since).num_seconds().max(0) as u64))+ );+ }+ for j in &s.jobs.queued {+ let _ = writeln!(+ out,+ "{} {} {} {} {}",+ dim("…"),+ j.name,+ dim(&j.repo),+ dim(&format!("[{}]", j.labels.join(", "))),+ dim(&format!("waiting {}", util::short_duration((now - j.created_at).num_seconds().max(0) as u64)))+ );+ }+ }++ if !s.attention.is_empty() {+ let _ = writeln!(out, "\n{}", bold(&format!("Needs attention ({})", s.attention.len())));+ for a in &s.attention {+ let mark = match a.level.as_str() {+ "error" => paint("31", "✖"),+ "warning" => paint("33", "!"),+ _ => dim("i"),+ };+ let _ = writeln!(out, " {mark} {}", a.title);+ if !a.detail.is_empty() {+ let _ = writeln!(out, " {}", dim(&a.detail));+ }+ }+ }+ out+}++fn row(m: &Machine) -> [String; 8] {+ let p = m.probe.as_ref().filter(|p| p.ok);+ let dash = || "—".to_string();+ let runners = if m.kind == "other" {+ match m.status.as_str() {+ "online" => "connected".into(),+ "offline" => "offline".into(),+ _ => "not checked".into(),+ }+ } else {+ let s = &m.summary;+ if s.working > 0 {+ format!("{}/{} working", s.working, s.total)+ } else if s.idle == s.total {+ format!("{} idle", s.idle)+ } else if s.offline > 0 {+ format!("{}/{} offline", s.offline, s.total)+ } else {+ format!("{} unknown", s.unknown)+ }+ };+ let cpu = p.and_then(|p| p.cpu_pct).map(|v| format!("{v:.0}%")).unwrap_or_else(dash);+ let mem = p+ .and_then(|p| Some((p.mem_used? as f64 / p.mem_total? as f64) * 100.0))+ .map(|v| format!("{v:.0}%"))+ .unwrap_or_else(dash);+ let disk = p.and_then(|p| p.disk_free).map(util::bytes).unwrap_or_else(dash);+ let uptime = p.and_then(|p| p.uptime_sec).map(util::uptime).unwrap_or_else(dash);+ let warnings = m.diagnostics.iter().filter(|d| matches!(d.level.as_str(), "warning" | "error")).count();+ let unknown = m.diagnostics.iter().filter(|d| d.level == "unknown").count();+ let diagnostics = match m.status.as_str() {+ "offline" => "unreachable".to_string(),+ "unchecked" | "manual" => "not checked".to_string(),+ _ if warnings > 0 => format!("{warnings} warning{}", if warnings == 1 { "" } else { "s" }),+ _ if unknown > 0 => format!("{unknown} unknown"),+ _ => "no warnings".to_string(),+ };+ [m.name.clone(), if m.platform.is_empty() { dash() } else { m.platform.clone() }, runners, cpu, mem, disk, uptime, diagnostics]+}diff --git a/src/fleet/workspaces/demo.rs b/src/fleet/workspaces/demo.rsnew file mode 100644index 0000000..0835eff--- /dev/null+++ b/src/fleet/workspaces/demo.rs@@ -0,0 +1,554 @@+//! Workspaces in demo mode: no ssh, no files on disk. Commands get believable+//! canned output and files live in memory, so the app and agents can try the+//! whole flow safely.++use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;+use std::sync::Arc;+use std::time::Duration;++use chrono::Utc;++use super::registry::WorkspaceRecord;+use super::{ExecResult, FileContent, FileEntry, SyncDirection, file_content};+use crate::demo::World;+use crate::fleet::Engine;+use crate::fleet::model::{WorkspaceCommand, WorkspaceInfo};++/// A workspace's files in demo mode.+#[derive(Debug, Clone, Default)]+pub struct DemoTree {+ pub files: BTreeMap<String, String>,+ /// Files that came with the checkout; others written later show as untracked.+ pub original: BTreeSet<String>,+ pub changed: BTreeSet<String>,+ pub branch: String,+ pub git: bool,+}++async fn pause(ms: u64) {+ tokio::time::sleep(Duration::from_millis(ms)).await;+}++fn demo_path(platform: &str, id: &str) -> String {+ if platform.starts_with("darwin") {+ format!("/Users/ci/openrunner/workspaces/{id}")+ } else if platform.starts_with("windows") {+ format!("C:\\Users\\ci\\openrunner\\workspaces\\{id}")+ } else {+ format!("/home/ci/openrunner/workspaces/{id}")+ }+}++/// Files a fresh checkout of `repo` gets.+fn template(repo: Option<&str>) -> Vec<(&'static str, String)> {+ let name = repo.map(|r| r.rsplit('/').next().unwrap_or(r).trim_end_matches(".git").to_string());+ match name.as_deref() {+ None => Vec::new(),+ Some("api") => vec![+ ("README.md", "# acme/api\n\nThe Acme checkout and orders API.\n\n npm ci\n npm test\n".into()),+ ("package.json", "{\n \"name\": \"@acme/api\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"tsx watch src/server.ts\",\n \"test\": \"vitest run\"\n }\n}\n".into()),+ ("src/server.ts", "import { createServer } from './app';\n\ncreateServer().listen(3000, () => console.log('api listening on :3000'));\n".into()),+ ("src/routes/checkout.ts", "export function total(items: Item[], discount = 0) {\n const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);\n return subtotal * (1 - discount) * 1.08;\n}\n".into()),+ ("e2e/checkout.spec.ts", "import { test, expect } from '@playwright/test';\n\ntest('applies the discount before tax', async ({ page }) => {\n await page.goto('/checkout');\n await expect(page.getByTestId('total')).toHaveText('$97.20');\n});\n".into()),+ (".github/workflows/ci.yml", "name: CI\non: [push, pull_request]\njobs:\n test:\n runs-on: [self-hosted, Linux, X64]\n steps:\n - uses: actions/checkout@v4\n - run: npm ci && npm test\n".into()),+ ],+ Some("desktop") => vec![+ ("README.md", "# acme/desktop\n\nThe Acme desktop app (SwiftUI).\n\n swift build\n swift test\n".into()),+ ("Package.swift", "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(name: \"Desktop\", platforms: [.macOS(.v14)], targets: [.executableTarget(name: \"Desktop\"), .testTarget(name: \"DesktopTests\", dependencies: [\"Desktop\"])])\n".into()),+ ("Sources/Desktop/App.swift", "import SwiftUI\n\n@main\nstruct DesktopApp: App {\n var body: some Scene { WindowGroup { ContentView() } }\n}\n".into()),+ ("Tests/DesktopTests/AppTests.swift", "import Testing\n@testable import Desktop\n\n@Test func launches() { #expect(true) }\n".into()),+ ],+ Some(other) => vec![+ ("README.md", format!("# {other}\n")),+ ("package.json", format!("{{\n \"name\": \"{other}\",\n \"scripts\": {{ \"test\": \"vitest run\" }}\n}}\n")),+ ("src/index.ts", "export const hello = () => 'world';\n".into()),+ ],+ }+}++fn tree_for(repo: Option<&str>, branch: &str) -> DemoTree {+ let files: BTreeMap<String, String> = template(repo).into_iter().map(|(k, v)| (k.to_string(), v)).collect();+ DemoTree { original: files.keys().cloned().collect(), files, changed: BTreeSet::new(), branch: branch.to_string(), git: repo.is_some() }+}++fn command(cmd: &str, exit: i32, ago_secs: i64, ms: u64, tail: &[&str], by: &str) -> WorkspaceCommand {+ WorkspaceCommand {+ command: cmd.into(),+ exit_code: Some(exit),+ started_at: Utc::now() - chrono::Duration::seconds(ago_secs),+ duration_ms: ms,+ output_tail: tail.iter().map(|s| s.to_string()).collect(),+ background: false,+ timed_out: false,+ by: Some(by.into()),+ }+}++/// Workspaces agents have been using (one of them in a container), so the app has something to show.+pub(super) fn seed(world: &World) -> Vec<WorkspaceRecord> {+ let now = Utc::now();+ let api_id = "ws-k3p9xa";+ let desk_id = "ws-7d2m4q";+ let web_id = "ws-q8v2rn";+ let mut api_tree = tree_for(Some("acme/api"), "fix/flaky-e2e");+ api_tree.files.insert(+ "e2e/checkout.spec.ts".into(),+ "import { test, expect } from '@playwright/test';\n\ntest('applies the discount before tax', async ({ page }) => {\n await page.goto('/checkout');\n await page.getByTestId('total').waitFor();\n await expect(page.getByTestId('total')).toHaveText('$97.20');\n});\n".into(),+ );+ api_tree.changed.insert("e2e/checkout.spec.ts".into());+ let desk_tree = tree_for(Some("acme/desktop"), "main");+ {+ let mut files = world.workspace_files.lock().unwrap();+ files.insert(api_id.into(), api_tree);+ files.insert(desk_id.into(), desk_tree);+ files.insert(web_id.into(), tree_for(Some("acme/web"), "chore/node-22"));+ }++ let api = WorkspaceInfo {+ id: api_id.into(),+ name: "api".into(),+ machine_id: "ubuntu-nuc".into(),+ machine_name: "Ubuntu NUC".into(),+ host: "nuc-ubuntu".into(),+ platform: "linux-x64".into(),+ path: demo_path("linux-x64", api_id),+ repo: Some("acme/api".into()),+ git_ref: Some("main".into()),+ branch: Some("fix/flaky-e2e".into()),+ owner: Some("claude-code".into()),+ status: "ready".into(),+ error: None,+ created_at: now - chrono::Duration::hours(2),+ last_used_at: now - chrono::Duration::minutes(4),+ commands: 4,+ history: vec![+ command("git status", 0, 6900, 41, &["On branch fix/flaky-e2e", "nothing to commit, working tree clean"], "claude-code"),+ command("npm ci", 0, 6840, 9120, &["added 412 packages, and audited 413 packages in 9s", "found 0 vulnerabilities"], "claude-code"),+ command(+ "npm test -- e2e/checkout.spec.ts",+ 1,+ 1500,+ 14210,+ &[+ " ✗ e2e/checkout.spec.ts > applies the discount before tax (5003 ms)",+ " → Timed out 5000ms waiting for expect(locator).toHaveText(expected)",+ " Test Files 1 failed (1)",+ " Tests 1 failed | 11 passed (12)",+ ],+ "claude-code",+ ),+ command(+ "npm test -- e2e/checkout.spec.ts",+ 0,+ 250,+ 11840,+ &[" ✓ e2e/checkout.spec.ts (12 tests) 9.42s", " Test Files 1 passed (1)", " Tests 12 passed (12)"],+ "claude-code",+ ),+ ],+ shell: String::new(),+ isolation: "host".into(),+ image: None,+ container: None,+ };+ let desk = WorkspaceInfo {+ id: desk_id.into(),+ name: "desktop".into(),+ machine_id: "mac-studio".into(),+ machine_name: "Mac Studio".into(),+ host: "[email protected]".into(),+ platform: "darwin-arm64".into(),+ path: demo_path("darwin-arm64", desk_id),+ repo: Some("acme/desktop".into()),+ git_ref: Some("main".into()),+ branch: None,+ owner: Some("codex".into()),+ status: "ready".into(),+ error: None,+ created_at: now - chrono::Duration::hours(26),+ last_used_at: now - chrono::Duration::hours(3),+ commands: 2,+ history: vec![+ command("swift build", 0, 11200, 48200, &["Building for debugging...", "Build complete! (48.20s)"], "codex"),+ command(+ "swift test",+ 0,+ 10900,+ 31800,+ &["Test Suite 'All tests' passed at 2026-10-07 13:22:41.118.", "\t Executed 58 tests, with 0 failures (0 unexpected) in 4.211 seconds"],+ "codex",+ ),+ ],+ shell: String::new(),+ isolation: "host".into(),+ image: None,+ container: None,+ };+ let web = WorkspaceInfo {+ id: web_id.into(),+ name: "web".into(),+ machine_id: "ubuntu-nuc".into(),+ machine_name: "Ubuntu NUC".into(),+ host: "nuc-ubuntu".into(),+ platform: "linux-x64".into(),+ path: demo_path("linux-x64", web_id),+ repo: Some("acme/web".into()),+ git_ref: Some("main".into()),+ branch: Some("chore/node-22".into()),+ owner: Some("claude-code".into()),+ status: "ready".into(),+ error: None,+ created_at: now - chrono::Duration::minutes(50),+ last_used_at: now - chrono::Duration::minutes(12),+ commands: 3,+ history: vec![+ command("node -v", 0, 2900, 180, &["v22.11.0"], "claude-code"),+ command("npm ci", 0, 2840, 21400, &["added 655 packages, and audited 656 packages in 21s", "found 0 vulnerabilities"], "claude-code"),+ command("npm run build", 0, 720, 38900, &["vite v6.0.3 building for production...", "✓ 1342 modules transformed.", "✓ built in 37.62s"], "claude-code"),+ ],+ shell: String::new(),+ isolation: "docker".into(),+ image: Some("node:22".into()),+ container: Some(super::container_name(web_id)),+ };+ vec![+ WorkspaceRecord { info: api, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },+ WorkspaceRecord { info: desk, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },+ WorkspaceRecord { info: web, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },+ ]+}++pub(super) async fn create(engine: &Arc<Engine>, op: u64, rec: &WorkspaceRecord, repo: Option<&str>) -> Result<String, String> {+ let w = engine.demo_world().cloned().ok_or("not in demo mode")?;+ let info = &rec.info;+ engine.op_log(op, format!("▸ Creating {} on {} ({})", info.id, info.machine_name, info.host));+ pause(300).await;+ w.reachable(&info.machine_id, &info.host).map_err(|e| format!("{} is unreachable: {e}", info.machine_name))?;+ let path = demo_path(&info.platform, &info.id);+ engine.op_log(op, format!("Folder: {path}"));+ let branch = info.branch.clone().or_else(|| info.git_ref.clone()).unwrap_or_else(|| "main".into());+ if let Some(r) = repo {+ engine.op_log(op, format!("Cloning {r}"));+ for line in [+ "Cloning into '.'...".to_string(),+ "remote: Enumerating objects: 1284, done.".into(),+ "remote: Counting objects: 100% (1284/1284), done.".into(),+ "remote: Compressing objects: 100% (731/731), done.".into(),+ "Receiving objects: 100% (1284/1284), 2.31 MiB | 18.40 MiB/s, done.".into(),+ "Resolving deltas: 100% (402/402), done.".into(),+ ] {+ engine.op_log(op, line);+ pause(120).await;+ }+ if let Some(b) = &info.branch {+ engine.op_log(op, format!("Switched to a new branch '{b}'"));+ }+ engine.op_log(op, format!("Checked out {branch} at 3f9c2e1"));+ }+ if let (Some(image), Some(container)) = (&info.image, &info.container) {+ engine.op_log(op, format!("Pulling {image}"));+ for line in [format!("Digest: sha256:4f6e1b2a9c0d…"), format!("Status: Downloaded newer image for {image}")] {+ pause(250).await;+ engine.op_log(op, line);+ }+ engine.op_log(op, format!("Starting container {container} from {image}"));+ pause(300).await;+ engine.op_log(op, format!("Container {container} is running"));+ }+ w.workspace_files.lock().unwrap().insert(info.id.clone(), tree_for(repo, &branch));+ Ok(path)+}++pub(super) async fn exec(engine: &Arc<Engine>, rec: &WorkspaceRecord, cmd: &str, cwd: &str, background: bool) -> Result<ExecResult, String> {+ let w = engine.demo_world().cloned().ok_or("not in demo mode")?;+ w.reachable(&rec.info.machine_id, &rec.info.host).map_err(|e| format!("{} is unreachable: {e}", rec.info.machine_name))?;+ if background {+ let n = engine+ .update_workspaces(|list| {+ list.iter_mut().find(|r| r.info.id == rec.info.id).map(|r| {+ let n = r.next_log.max(1);+ r.next_log = n + 1;+ n+ })+ })?+ .unwrap_or(1);+ let log = format!(".openrunner/logs/{n}.log");+ let mut files = w.workspace_files.lock().unwrap();+ let tree = files.entry(rec.info.id.clone()).or_default();+ tree.files.insert(log.clone(), format!("$ {cmd}\n> ready on http://localhost:3000\n"));+ let pid = 40_000 + (cmd.len() as u32 * 37 + n * 101) % 20_000;+ return Ok(ExecResult {+ exit_code: None,+ stdout: String::new(),+ stderr: String::new(),+ duration_ms: 0,+ timed_out: false,+ truncated: false,+ background_pid: Some(pid),+ log_path: Some(log),+ });+ }+ pause(150 + (cmd.len() as u64 * 13) % 400).await;+ let (stdout, stderr, code) = respond(&w, &rec.info, cmd.trim(), cwd).await;+ Ok(ExecResult {+ exit_code: Some(code),+ stdout,+ stderr,+ duration_ms: 0,+ timed_out: false,+ truncated: false,+ background_pid: None,+ log_path: None,+ })+}++/// Canned output for the commands agents run most.+async fn respond(w: &World, info: &WorkspaceInfo, cmd: &str, cwd: &str) -> (String, String, i32) {+ let ok = |s: &str| (s.to_string(), String::new(), 0);+ let tree = w.workspace_files.lock().unwrap().get(&info.id).cloned().unwrap_or_default();+ let root = if info.container.is_some() { "/workspace".to_string() } else { info.path.clone() };+ let here = if cwd.is_empty() { root } else { format!("{root}/{cwd}") };+ let linux = !info.platform.starts_with("darwin");+ let first = cmd.split_whitespace().next().unwrap_or("");+ match cmd {+ "pwd" => return ok(&here),+ "whoami" => return ok("ci"),+ "hostname" => return ok(&info.machine_id),+ "true" | ":" => return ok(""),+ "false" => return (String::new(), String::new(), 1),+ "node -v" | "node --version" => return ok("v22.11.0"),+ "npm -v" | "npm --version" => return ok("10.9.0"),+ "cargo --version" => return ok("cargo 1.91.0 (ea2d97820 2025-10-10)"),+ "rustc --version" => return ok("rustc 1.91.0 (f8297e351 2025-10-28)"),+ "go version" => return ok(if linux { "go version go1.25.3 linux/amd64" } else { "go version go1.25.3 darwin/arm64" }),+ "python3 --version" | "python --version" => return ok("Python 3.12.3"),+ "uname" => return ok(if linux { "Linux" } else { "Darwin" }),+ "uname -a" => {+ return ok(if linux {+ "Linux nuc-ubuntu 6.8.0-45-generic #45-Ubuntu SMP PREEMPT_DYNAMIC x86_64 x86_64 x86_64 GNU/Linux"+ } else {+ "Darwin mac-studio.local 25.1.0 Darwin Kernel Version 25.1.0 arm64"+ })+ }+ "env" | "printenv" => return ok(&format!("HOME=/home/ci\nSHELL=/bin/bash\nOPENRUNNER_WORKSPACE={}\nNO_COLOR=1\nPWD={here}", info.id)),+ _ => {}+ }+ if first == "ls" {+ let long = cmd.contains("-l");+ let prefix = if cwd.is_empty() { String::new() } else { format!("{cwd}/") };+ let mut names: BTreeSet<String> = BTreeSet::new();+ for path in tree.files.keys().filter(|p| p.starts_with(&prefix) && !p.starts_with(".openrunner")) {+ if let Some(name) = path[prefix.len()..].split('/').next() {+ names.insert(name.to_string());+ }+ }+ let lines: Vec<String> = names+ .iter()+ .filter(|n| cmd.contains("-a") || !n.starts_with('.'))+ .map(|n| {+ if long {+ let dir = tree.files.keys().any(|p| p.starts_with(&format!("{prefix}{n}/")));+ let size = tree.files.get(&format!("{prefix}{n}")).map(|c| c.len()).unwrap_or(4096);+ format!("{} 1 ci ci {size:>6} Oct 8 10:12 {n}", if dir { "drwxr-xr-x" } else { "-rw-r--r--" })+ } else {+ n.clone()+ }+ })+ .collect();+ return ok(&lines.join("\n"));+ }+ if let Some(rest) = cmd.strip_prefix("cat ") {+ let mut out = String::new();+ for f in rest.split_whitespace() {+ let key = if cwd.is_empty() { f.to_string() } else { format!("{cwd}/{f}") };+ match tree.files.get(key.trim_start_matches("./")) {+ Some(c) => out.push_str(c),+ None => return (out, format!("cat: {f}: No such file or directory"), 1),+ }+ }+ return ok(out.trim_end());+ }+ if let Some(rest) = cmd.strip_prefix("echo ") {+ return ok(rest.trim().trim_matches(['"', '\'']));+ }+ if let Some(n) = cmd.strip_prefix("exit ") {+ return (String::new(), String::new(), n.trim().parse().unwrap_or(1));+ }+ if let Some(n) = cmd.strip_prefix("sleep ") {+ let secs: f64 = n.trim().parse().unwrap_or(1.0);+ pause((secs.min(2.0) * 1000.0) as u64).await;+ return ok("");+ }+ if cmd.starts_with("git ") {+ if !tree.git {+ return (String::new(), "fatal: not a git repository (or any of the parent directories): .git".into(), 128);+ }+ if cmd.starts_with("git status") {+ return ok(&status_text(&tree, false));+ }+ if cmd.starts_with("git log") {+ return ok(+ "3f9c2e1 Fix flaky checkout e2e wait\n9b81a04 Bump vitest to 3.2\n77d0c3e Add discount-before-tax rule\nc12e9fa Split checkout routes\n5aa0b17 CI: run e2e on self-hosted Linux",+ );+ }+ if cmd.starts_with("git diff") {+ return ok(&diff_text(&tree));+ }+ if cmd.starts_with("git branch") {+ return ok(&format!("* {}", tree.branch));+ }+ if cmd.starts_with("git rev-parse") {+ return ok("3f9c2e1d8a4b6c0e9f7a5b3c1d2e4f6a8b0c9d7e");+ }+ return ok("");+ }+ let test = ["npm test", "npm run test", "pnpm test", "yarn test", "bun test", "npx vitest", "npx playwright test"];+ if test.iter().any(|t| cmd.starts_with(t)) {+ return ok(" ✓ src/routes/checkout.test.ts (9 tests) 212ms\n ✓ e2e/checkout.spec.ts (12 tests) 9.42s\n\n Test Files 2 passed (2)\n Tests 21 passed (21)\n Start at 10:41:07\n Duration 10.31s");+ }+ if cmd.starts_with("npm ci") || cmd.starts_with("npm install") || cmd.starts_with("pnpm install") {+ return ok("added 412 packages, and audited 413 packages in 9s\n\n68 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities");+ }+ if cmd.starts_with("cargo test") {+ return ok("running 42 tests\ntest result: ok. 42 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.84s");+ }+ if cmd.starts_with("cargo build") {+ return (String::new(), " Compiling acme v0.1.0\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 12.40s".into(), 0);+ }+ if cmd.starts_with("swift test") {+ return ok("Test Suite 'All tests' passed.\n\t Executed 58 tests, with 0 failures (0 unexpected) in 4.211 seconds");+ }+ if cmd.starts_with("swift build") {+ return ok("Building for debugging...\nBuild complete! (41.07s)");+ }+ ok(&format!("(demo) ran on {}: {cmd}", info.machine_name))+}++fn status_text(tree: &DemoTree, short: bool) -> String {+ let mut lines = Vec::new();+ if short {+ lines.push(format!("## {}", tree.branch));+ for f in &tree.changed {+ lines.push(format!("{} {f}", if tree.original.contains(f) { " M" } else { "??" }));+ }+ return lines.join("\n");+ }+ lines.push(format!("On branch {}", tree.branch));+ if tree.changed.is_empty() {+ lines.push("nothing to commit, working tree clean".into());+ return lines.join("\n");+ }+ let modified: Vec<&String> = tree.changed.iter().filter(|f| tree.original.contains(*f)).collect();+ let untracked: Vec<&String> = tree.changed.iter().filter(|f| !tree.original.contains(*f)).collect();+ if !modified.is_empty() {+ lines.push("Changes not staged for commit:".into());+ lines.extend(modified.iter().map(|f| format!("\tmodified: {f}")));+ }+ if !untracked.is_empty() {+ lines.push("Untracked files:".into());+ lines.extend(untracked.iter().map(|f| format!("\t{f}")));+ }+ lines.join("\n")+}++fn diff_text(tree: &DemoTree) -> String {+ tree.changed+ .iter()+ .filter(|f| tree.original.contains(*f))+ .map(|f| {+ let body: Vec<String> = tree.files.get(f).map(|c| c.lines().take(6).map(|l| format!("+{l}")).collect()).unwrap_or_default();+ format!("diff --git a/{f} b/{f}\n--- a/{f}\n+++ b/{f}\n@@ -1,5 +1,6 @@\n{}", body.join("\n"))+ })+ .collect::<Vec<_>>()+ .join("\n")+}++pub(super) fn read(w: &World, rec: &WorkspaceRecord, rel: &str, max: usize) -> Result<FileContent, String> {+ let files = w.workspace_files.lock().unwrap();+ let tree = files.get(&rec.info.id).cloned().unwrap_or_default();+ match tree.files.get(rel) {+ Some(c) => {+ let bytes = c.as_bytes();+ let cut = bytes[..bytes.len().min(max)].to_vec();+ Ok(file_content(rel.to_string(), cut, bytes.len() as u64, max))+ }+ None if tree.files.keys().any(|p| p.starts_with(&format!("{rel}/"))) => Err(format!("{rel} is a folder")),+ None => Err(format!("File {rel} not found in the workspace.")),+ }+}++pub(super) fn write(w: &World, rec: &WorkspaceRecord, rel: &str, content: &str, append: bool) -> u64 {+ let mut files = w.workspace_files.lock().unwrap();+ let tree = files.entry(rec.info.id.clone()).or_default();+ let entry = tree.files.entry(rel.to_string()).or_default();+ if append {+ entry.push_str(content);+ } else {+ *entry = content.to_string();+ }+ let size = entry.len() as u64;+ tree.changed.insert(rel.to_string());+ size+}++pub(super) fn list(w: &World, rec: &WorkspaceRecord, rel: &str, depth: u32) -> Result<Vec<FileEntry>, String> {+ let files = w.workspace_files.lock().unwrap();+ let tree = files.get(&rec.info.id).cloned().unwrap_or_default();+ let prefix = if rel.is_empty() { String::new() } else { format!("{rel}/") };+ if !rel.is_empty() && !tree.files.keys().any(|p| p.starts_with(&prefix)) {+ return Err(format!("Folder {rel} not found in the workspace."));+ }+ let mut entries: BTreeMap<String, FileEntry> = BTreeMap::new();+ for (path, content) in tree.files.iter().filter(|(p, _)| p.starts_with(&prefix) && !p.starts_with(".openrunner")) {+ let parts: Vec<&str> = path[prefix.len()..].split('/').collect();+ for i in 0..parts.len().min(depth as usize) {+ let sub = format!("{prefix}{}", parts[..=i].join("/"));+ let is_file = i + 1 == parts.len();+ entries.entry(sub.clone()).or_insert(FileEntry {+ path: sub,+ kind: if is_file { "file" } else { "dir" }.into(),+ size: if is_file { content.len() as u64 } else { 0 },+ });+ }+ }+ Ok(entries.into_values().collect())+}++pub(super) fn changes(w: &World, rec: &WorkspaceRecord) -> String {+ let files = w.workspace_files.lock().unwrap();+ let tree = files.get(&rec.info.id).cloned().unwrap_or_default();+ if !tree.git {+ return "This workspace isn't a git checkout, so there's nothing to diff.".into();+ }+ format!("## git status\n{}\n\n## git diff\n{}", status_text(&tree, true), diff_text(&tree))+}++pub(super) async fn destroy(engine: &Arc<Engine>, op: u64, rec: &WorkspaceRecord, keep: bool) -> Result<(), String> {+ let w = engine.demo_world().cloned().ok_or("not in demo mode")?;+ engine.op_log(op, format!("▸ Cleaning up on {} ({})", rec.info.machine_name, rec.info.host));+ pause(300).await;+ w.reachable(&rec.info.machine_id, &rec.info.host).map_err(|e| format!("{} is unreachable: {e}", rec.info.machine_name))?;+ for pid in &rec.background_pids {+ engine.op_log(op, format!("Stopped background process {pid}"));+ }+ if keep {+ engine.op_log(op, format!("Kept the files in {}", rec.info.path));+ } else {+ w.workspace_files.lock().unwrap().remove(&rec.info.id);+ engine.op_log(op, format!("Deleted {}", rec.info.path));+ }+ Ok(())+}++pub(super) async fn sync(rec: &WorkspaceRecord, local: &Path, direction: SyncDirection, delete: bool) -> String {+ pause(600).await;+ let (from, to) = match direction {+ SyncDirection::Push => (local.display().to_string(), format!("{}:{}", rec.info.host, rec.info.path)),+ SyncDirection::Pull => (format!("{}:{}", rec.info.host, rec.info.path), local.display().to_string()),+ };+ format!(+ "(demo) {from}/ → {to}/{}\nNumber of files: 214 (reg: 187, dir: 27)\nNumber of regular files transferred: 12\nTotal file size: 2.31M bytes\nTotal transferred file size: 48.20K bytes\nsent 51.02K bytes received 1.18K bytes 34.80K bytes/sec",+ if delete { " (with --delete)" } else { "" }+ )+}diff --git a/src/fleet/workspaces/mod.rs b/src/fleet/workspaces/mod.rsnew file mode 100644index 0000000..3e2ed84--- /dev/null+++ b/src/fleet/workspaces/mod.rs@@ -0,0 +1,1370 @@+//! Agent workspaces: a folder on a fleet machine (optionally a git checkout)+//! that an AI agent checks out as its work environment — runs commands, reads+//! and writes files, syncs a local tree — like Amp's Orbs, on your own hardware.+//!+//! Workspaces persist until destroyed; nothing is cleaned up automatically.+//! They live in `<config dir>/workspaces.json` so the window and every agent+//! process (MCP server, CLI) see the same set.+//!+//! Path checks keep agents from wandering out of a workspace by mistake; they+//! aren't a sandbox — `workspace_exec` runs whatever it's given as the+//! machine's ssh user.+//!+//! PUBLIC API — the UI, the MCP server and the CLI depend on these signatures.++mod demo;+mod registry;+mod transport;++use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{Duration, Instant};++use base64::Engine as _;+use base64::engine::general_purpose::STANDARD as B64;+use chrono::Utc;+use serde::{Deserialize, Serialize};++use super::Engine;+use super::model::{Machine, WorkspaceCommand, WorkspaceInfo};+use crate::config::MachineSpec;+use crate::ops::remote::{self, Param, ps_quote, sh_quote, with_params};+use crate::probe::Shell;+pub(crate) use registry::WorkspaceRecord;+use transport::{Limits, Output};++pub use demo::DemoTree;++const LIB_SH: &str = include_str!("scripts/lib.sh");+const EXEC_SH: &str = include_str!("scripts/exec.sh");+const EXEC_PS1: &str = include_str!("scripts/exec.ps1");+const FILES_SH: &str = include_str!("scripts/files.sh");+const FILES_PS1: &str = include_str!("scripts/files.ps1");+const CHANGES_SH: &str = include_str!("scripts/changes.sh");+const CREATE_SH: &str = include_str!("scripts/create.sh");+const DESTROY_SH: &str = include_str!("scripts/destroy.sh");+const OTHER_PS1: &str = include_str!("scripts/other.ps1");+const DOCKER_SH: &str = include_str!("scripts/docker.sh");+const EXEC_DOCKER_SH: &str = include_str!("scripts/exec_docker.sh");++/// Image for docker workspaces when none is given: Debian with git, curl and+/// a compiler toolchain (what the official language images build on).+pub const DEFAULT_IMAGE: &str = "buildpack-deps:bookworm";++const DEFAULT_ROOT: &str = "~/openrunner/workspaces";+const DEFAULT_ROOT_WINDOWS: &str = "~\\openrunner\\workspaces";++pub const EXEC_TIMEOUT_DEFAULT: u64 = 600;+pub const EXEC_TIMEOUT_MAX: u64 = 3600;+/// Extra time OpenRunner waits beyond the command's own timeout before hanging up.+const EXEC_GRACE: u64 = 30;+const FILE_TIMEOUT: Duration = Duration::from_secs(60);+const CREATE_TIMEOUT: Duration = Duration::from_secs(15 * 60);+const DESTROY_TIMEOUT: Duration = Duration::from_secs(2 * 60);+const SYNC_TIMEOUT: Duration = Duration::from_secs(30 * 60);+pub const READ_DEFAULT: usize = 256 * 1024;+pub const READ_MAX: usize = 1024 * 1024;+pub const WRITE_MAX: usize = 5 * 1024 * 1024;+pub const LIST_DEPTH_DEFAULT: u32 = 2;+pub const LIST_DEPTH_MAX: u32 = 10;+pub const LIST_MAX_ENTRIES: usize = 2000;+const CHANGES_LIMITS: Limits = Limits { head: 60 * 1024, tail: 4 * 1024, line: 4 * 1024 };+const COMMAND_MAX: usize = 64 * 1024;+const TAIL_LINE_MAX: usize = 400;+/// Machines with less free disk than this aren't picked automatically.+const MIN_FREE_DISK: u64 = 5_000_000_000;++/// Where and what to create.+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct CreateWorkspace {+ /// Machine id. None picks the least-loaded online machine that allows workspaces+ /// (and matches `platform` when given).+ pub machine: Option<String>,+ /// Platform prefix to match when picking a machine: "linux", "linux-x64", "darwin-arm64", "windows".+ pub platform: Option<String>,+ /// Label; defaults to the repo name, else the id.+ pub name: Option<String>,+ /// Git URL, or "owner/repo" for GitHub.+ pub repo: Option<String>,+ /// Branch, tag or commit to check out.+ pub git_ref: Option<String>,+ /// Create and switch to a new branch after checkout.+ pub branch: Option<String>,+ /// Who is creating it ("claude-code", "cli", "app", ...).+ pub owner: Option<String>,+}++/// How a workspace's commands run. Separate from `CreateWorkspace` so existing+/// callers keep compiling; `create_workspace` uses the default (host).+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct WorkspaceIsolation {+ /// "host" (default): commands run directly on the machine as the ssh user.+ /// "docker": a fresh container per workspace, with the folder mounted at /workspace.+ pub isolation: Option<String>,+ /// Docker image, e.g. "node:22", "rust:1", "python:3.13". Defaults to `DEFAULT_IMAGE`.+ pub image: Option<String>,+ /// Share the host's docker socket with the container (docker-in-docker). Off by default.+ pub docker_socket: bool,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct ExecOptions {+ /// Seconds before the command is killed (default 600, max 3600). Ignored for background commands.+ pub timeout_secs: Option<u64>,+ pub env: Vec<(String, String)>,+ /// Folder relative to the workspace to run in.+ pub cwd: Option<String>,+ /// Start it detached (dev servers, watchers); output goes to a log file in the workspace.+ pub background: bool,+ pub by: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ExecResult {+ /// None if it timed out or runs in the background.+ pub exit_code: Option<i32>,+ pub stdout: String,+ pub stderr: String,+ pub duration_ms: u64,+ pub timed_out: bool,+ /// Output was longer than the cap; the middle was dropped.+ pub truncated: bool,+ pub background_pid: Option<u32>,+ /// Background commands: log file path relative to the workspace.+ pub log_path: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct FileContent {+ pub path: String,+ pub content: String,+ pub size: u64,+ pub truncated: bool,+ /// Not valid UTF-8; `content` is empty.+ pub binary: bool,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct FileEntry {+ /// Relative to the workspace.+ pub path: String,+ /// "file" | "dir" | "link"+ pub kind: String,+ pub size: u64,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum SyncDirection {+ /// Local folder → workspace.+ Push,+ /// Workspace → local folder.+ Pull,+}++impl Engine {+ /// Creates a workspace and waits until it's ready (folder made, repo cloned).+ #[cfg_attr(not(test), allow(dead_code))]+ pub async fn create_workspace(self: &Arc<Self>, req: CreateWorkspace) -> Result<WorkspaceInfo, String> {+ self.create_workspace_with(req, WorkspaceIsolation::default()).await+ }++ /// Like `create_workspace`, choosing how commands run: on the host, or in a+ /// fresh docker container (folder mounted at /workspace).+ pub async fn create_workspace_with(self: &Arc<Self>, req: CreateWorkspace, iso: WorkspaceIsolation) -> Result<WorkspaceInfo, String> {+ self.refresh_from_disk();+ let docker = match clean_opt(iso.isolation).map(|s| s.to_ascii_lowercase()).as_deref() {+ None | Some("host") | Some("none") => false,+ Some("docker") | Some("container") => true,+ Some(other) => return Err(format!("\"{other}\" isn't an isolation OpenRunner knows. Use \"host\" or \"docker\".")),+ };+ let image_req = clean_opt(iso.image);+ if !docker && image_req.is_some() {+ return Err("An image only applies to docker workspaces; pass isolation \"docker\" too.".into());+ }+ let image = if docker { Some(validate_image(image_req.as_deref().unwrap_or(DEFAULT_IMAGE))?) } else { None };+ let name = clean_opt(req.name);+ if let Some(n) = &name {+ if n.chars().count() > 80 || n.chars().any(char::is_control) {+ return Err("The workspace name is too long or has odd characters.".into());+ }+ }+ let git_ref = clean_opt(req.git_ref);+ let branch = clean_opt(req.branch);+ for r in git_ref.iter().chain(branch.iter()) {+ validate_git_ref(r)?;+ }+ let settings = self.settings();+ let gh_host = github_web_host(&settings.github.api_url);+ let repo = clean_opt(req.repo).map(|r| normalize_repo(&r, &gh_host)).transpose()?;+ if repo.is_none() && (git_ref.is_some() || branch.is_some()) {+ return Err("gitRef and branch need a repo to clone.".into());+ }++ // Pick the machine and make sure we know what it runs.+ let snap = self.current();+ let machine_id = match clean_opt(req.machine) {+ Some(m) => {+ let found = snap+ .machines+ .iter()+ .find(|x| x.id == m || x.name.eq_ignore_ascii_case(&m))+ .ok_or_else(|| format!("Machine \"{m}\" not found in the fleet. Known machines: {}.", machine_names(&snap.machines)))?;+ if found.host.is_empty() {+ return Err(format!("{} has no host in fleet.toml, so OpenRunner can't reach it.", found.name));+ }+ if !found.workspaces_allowed {+ return Err(format!(+ "Workspaces are turned off for {}. Turn them on from its page in OpenRunner, or remove `workspaces = false` from its entry in fleet.toml.",+ found.name+ ));+ }+ found.id.clone()+ }+ None => pick_machine_for(&snap.machines, clean_opt(req.platform).as_deref(), docker)?.id.clone(),+ };+ let (spec, mut probe) = self.machine(&machine_id).ok_or("Machine not found in fleet.toml anymore.")?;+ if self.demo_world().is_none() && !probe.as_ref().is_some_and(|p| p.ok) {+ self.run_check(Some(vec![spec.id.clone()])).await;+ probe = self.machine(&spec.id).and_then(|(_, p)| p);+ match &probe {+ Some(p) if p.ok => {}+ Some(p) => return Err(format!("{} is unreachable: {}", spec.name, p.error.clone().unwrap_or_default())),+ None => return Err(format!("{} is unreachable: the check didn't run.", spec.name)),+ }+ }+ let windows = remote::shell_for(&spec, probe.as_ref()) == Shell::Powershell;+ if docker && windows {+ return Err(format!("Docker workspaces aren't supported on Windows machines yet ({}). Use isolation \"host\" there.", spec.name));+ }+ let machine = self.current().machines.iter().find(|m| m.id == spec.id).cloned();++ let id = self.unused_workspace_id();+ let root = spec.workspace_root.clone().filter(|r| !r.trim().is_empty()).unwrap_or_else(|| {+ if windows { DEFAULT_ROOT_WINDOWS.into() } else { DEFAULT_ROOT.into() }+ });+ let sep = if windows { "\\" } else { "/" };+ let now = Utc::now();+ let info = WorkspaceInfo {+ id: id.clone(),+ name: name.unwrap_or_else(|| repo.as_ref().map(|r| r.short_name.clone()).unwrap_or_else(|| id.clone())),+ machine_id: spec.id.clone(),+ machine_name: spec.name.clone(),+ host: spec.host.trim().to_string(),+ platform: machine.as_ref().map(|m| m.platform.clone()).unwrap_or_default(),+ path: format!("{}{sep}{id}", root.trim_end_matches(['/', '\\'])),+ repo: repo.as_ref().map(|r| r.shown.clone()),+ git_ref: git_ref.clone(),+ branch: branch.clone(),+ owner: clean_opt(req.owner),+ status: "creating".into(),+ error: None,+ created_at: now,+ last_used_at: now,+ commands: 0,+ history: Vec::new(),+ shell: String::new(),+ isolation: if docker { "docker" } else { "host" }.into(),+ image: image.clone(),+ container: docker.then(|| container_name(&id)),+ };+ let record = WorkspaceRecord { info, background_pids: Vec::new(), windows, next_log: 1, docker_socket: docker && iso.docker_socket };+ self.update_workspaces(|list| list.push(record.clone()))?;++ let title = match &image {+ Some(img) => format!("Create workspace {id} on {} ({img})", spec.name),+ None => format!("Create workspace {id} on {}", spec.name),+ };+ let op = self.begin_op("workspace", title, Some(spec.id.clone()), None);+ let result = match self.demo_world() {+ Some(_) => demo::create(self, op, &record, repo.as_ref().map(|r| r.shown.as_str())).await.map_err(|e| (e, None)),+ None => self.run_create(op, &spec, &record, &root, repo.as_ref()).await,+ };+ let finished = match result {+ Ok(path) => {+ self.update_workspaces(|list| {+ if let Some(r) = list.iter_mut().find(|r| r.info.id == id) {+ r.info.status = "ready".into();+ r.info.path = path.clone();+ r.info.last_used_at = Utc::now();+ }+ })?;+ self.op_log(op, format!("✓ Workspace {id} is ready at {path}"));+ self.op_finish(op, Ok(()));+ Ok(())+ }+ Err((e, folder)) => {+ // Keep the folder's path (if one was made) so destroying the workspace cleans it up.+ let _ = self.update_workspaces(|list| {+ if let Some(r) = list.iter_mut().find(|r| r.info.id == id) {+ r.info.status = "failed".into();+ r.info.error = Some(e.clone());+ if let Some(p) = folder.clone() {+ r.info.path = p;+ }+ }+ });+ self.op_log(op, format!("error: {e}"));+ self.op_finish(op, Err(e.clone()));+ Err(e)+ }+ };+ finished?;+ self.workspace_info(&id).ok_or_else(|| "The workspace was created but then disappeared.".to_string())+ }++ /// Runs a shell command in the workspace with the machine user's login environment.+ pub async fn workspace_exec(self: &Arc<Self>, id: &str, command: &str, opts: ExecOptions) -> Result<ExecResult, String> {+ let command = command.trim();+ if command.is_empty() {+ return Err("Give a command to run.".into());+ }+ if command.len() > COMMAND_MAX {+ return Err("That command is too long; write a script file with workspace_write_file and run it.".into());+ }+ let rec = self.ready_workspace(id)?;+ let cwd = match opts.cwd.as_deref() {+ Some(c) => rel_path(c)?,+ None => String::new(),+ };+ for (k, v) in &opts.env {+ validate_env(k, v)?;+ }+ let timeout = opts.timeout_secs.unwrap_or(EXEC_TIMEOUT_DEFAULT).clamp(1, EXEC_TIMEOUT_MAX);+ let started_at = Utc::now();+ let started = Instant::now();++ let result = match self.demo_world() {+ Some(_) => demo::exec(self, &rec, command, &cwd, opts.background).await?,+ None => {+ let spec = self.workspace_machine(&rec)?;+ let log = if opts.background {+ let n = self.update_workspaces(|list| {+ list.iter_mut().find(|r| r.info.id == rec.info.id).map(|r| {+ let n = r.next_log.max(1);+ r.next_log = n + 1;+ n+ })+ })?;+ Some(format!(".openrunner/logs/{}.log", n.unwrap_or(1)))+ } else {+ None+ };+ self.run_exec(&spec, &rec, command, &cwd, &opts.env, timeout, log).await?+ }+ };++ let duration_ms = started.elapsed().as_millis() as u64;+ let result = ExecResult { duration_ms, ..result };+ let entry = WorkspaceCommand {+ command: command.to_string(),+ exit_code: result.exit_code,+ started_at,+ duration_ms,+ output_tail: output_tail(&result.stdout, &result.stderr),+ background: opts.background,+ timed_out: result.timed_out,+ by: clean_opt(opts.by),+ };+ let pid = result.background_pid;+ self.update_workspaces(|list| {+ if let Some(r) = list.iter_mut().find(|r| r.info.id == rec.info.id) {+ r.info.history.push(entry);+ registry::cap_history(&mut r.info);+ r.info.commands += 1;+ r.info.last_used_at = Utc::now();+ // Container pids mean nothing on the host; removing the container stops those.+ if let (Some(p), None) = (pid, &r.info.container) {+ r.background_pids.push(p);+ }+ }+ })?;+ Ok(result)+ }++ pub async fn workspace_read_file(&self, id: &str, path: &str, max_bytes: usize) -> Result<FileContent, String> {+ let rec = self.ready_workspace(id)?;+ let rel = rel_path(path)?;+ if rel.is_empty() {+ return Err("Give the path of a file in the workspace.".into());+ }+ let max = if max_bytes == 0 { READ_DEFAULT } else { max_bytes.min(READ_MAX) };+ if let Some(w) = self.demo_world() {+ return demo::read(w, &rec, &rel, max);+ }+ let spec = self.workspace_machine(&rec)?;+ let max_s = max.to_string();+ let out = self+ .run_files(&spec, &rec, &[("OR_ACTION", Param::Str("read")), ("OR_REL", Param::Str(&rel)), ("OR_MAX", Param::Str(&max_s))])+ .await?;+ let size: u64 = field(&out.stdout, "size").and_then(|s| s.parse().ok()).unwrap_or(0);+ let data = field(&out.stdout, "data").unwrap_or_default();+ let bytes = B64.decode(data.trim()).map_err(|e| format!("Couldn't decode the file from the machine: {e}"))?;+ Ok(file_content(rel, bytes, size, max))+ }++ /// Writes (or appends) a text file, creating parent folders. Returns the new size.+ pub async fn workspace_write_file(&self, id: &str, path: &str, content: &str, append: bool) -> Result<u64, String> {+ let rec = self.ready_workspace(id)?;+ let rel = rel_path(path)?;+ if rel.is_empty() {+ return Err("Give the path of a file in the workspace.".into());+ }+ if content.len() > WRITE_MAX {+ return Err(format!("That's more than {} — copy big files with workspace_sync instead.", crate::util::bytes(WRITE_MAX as u64)));+ }+ let size = match self.demo_world() {+ Some(w) => demo::write(w, &rec, &rel, content, append),+ None => {+ let spec = self.workspace_machine(&rec)?;+ let encoded = B64.encode(content.as_bytes());+ let out = self+ .run_files(+ &spec,+ &rec,+ &[+ ("OR_ACTION", Param::Str("write")),+ ("OR_REL", Param::Str(&rel)),+ ("OR_B64", Param::Str(&encoded)),+ ("OR_APPEND", Param::Bool(append)),+ ],+ )+ .await?;+ field(&out.stdout, "size").and_then(|s| s.parse().ok()).unwrap_or(content.len() as u64)+ }+ };+ self.touch_workspace(&rec.info.id);+ Ok(size)+ }++ pub async fn workspace_list_files(&self, id: &str, path: &str, depth: u32) -> Result<Vec<FileEntry>, String> {+ let rec = self.ready_workspace(id)?;+ let rel = rel_path(path)?;+ let depth = if depth == 0 { LIST_DEPTH_DEFAULT } else { depth.min(LIST_DEPTH_MAX) };+ if let Some(w) = self.demo_world() {+ return demo::list(w, &rec, &rel, depth);+ }+ let spec = self.workspace_machine(&rec)?;+ let depth_s = depth.to_string();+ let out = self+ .run_files(&spec, &rec, &[("OR_ACTION", Param::Str("list")), ("OR_REL", Param::Str(&rel)), ("OR_DEPTH", Param::Str(&depth_s))])+ .await?;+ Ok(parse_listing(&out.stdout, &rel))+ }++ /// `git status` plus the diff of uncommitted changes (capped), or a note when it isn't a git checkout.+ pub async fn workspace_changes(&self, id: &str) -> Result<String, String> {+ let rec = self.ready_workspace(id)?;+ if let Some(w) = self.demo_world() {+ return Ok(demo::changes(w, &rec));+ }+ let spec = self.workspace_machine(&rec)?;+ let (script, windows) = if rec.windows {+ (with_params(Shell::Powershell, &[("OR_ACTION", Param::Str("changes")), ("OR_DIR", Param::Str(&rec.info.path))], OTHER_PS1), true)+ } else {+ (with_params(Shell::Sh, &[("OR_DIR", Param::Str(&rec.info.path))], CHANGES_SH), false)+ };+ let out = run_checked(&spec, windows, script, FILE_TIMEOUT, CHANGES_LIMITS, &[], None).await?;+ let mut text = out.stdout;+ if out.truncated {+ text.push_str("\n[the diff was cut; run `git diff` with workspace_exec for the rest]");+ }+ Ok(text)+ }++ /// rsync between a folder on this computer and the workspace. Returns rsync's summary.+ pub async fn workspace_sync(&self, id: &str, local_path: &str, direction: SyncDirection, delete: bool) -> Result<String, String> {+ let rec = self.ready_workspace(id)?;+ let local = expand_home(local_path.trim());+ if local.as_os_str().is_empty() {+ return Err("Give a local folder to sync.".into());+ }+ if let Some(_w) = self.demo_world() {+ let summary = demo::sync(&rec, &local, direction, delete).await;+ self.touch_workspace(&rec.info.id);+ return Ok(summary);+ }+ if rec.windows {+ return Err("Sync uses rsync, which OpenRunner doesn't support for Windows machines. Use workspace_write_file or git instead.".into());+ }+ let spec = self.workspace_machine(&rec)?;+ let have_rsync = tokio::process::Command::new("rsync")+ .arg("--version")+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .await+ .is_ok_and(|s| s.success());+ if !have_rsync {+ return Err("rsync isn't installed on this computer, so OpenRunner can't sync folders.".into());+ }+ match direction {+ SyncDirection::Push if !local.is_dir() => return Err(format!("{} isn't a folder on this computer.", local.display())),+ SyncDirection::Pull => std::fs::create_dir_all(&local).map_err(|e| format!("Couldn't create {}: {e}", local.display()))?,+ _ => {}+ }+ let args = rsync_args(&spec, &rec.info.path, &local.to_string_lossy(), direction, delete);+ let run = tokio::process::Command::new("rsync").args(&args).kill_on_drop(true).output();+ let output = tokio::time::timeout(SYNC_TIMEOUT, run)+ .await+ .map_err(|_| "The sync took longer than 30 minutes and was stopped.".to_string())?+ .map_err(|e| format!("Couldn't run rsync: {e}"))?;+ if !output.status.success() {+ let err = String::from_utf8_lossy(&output.stderr);+ let tail: Vec<&str> = err.lines().filter(|l| !l.trim().is_empty()).rev().take(4).collect();+ return Err(format!("rsync failed: {}", tail.into_iter().rev().collect::<Vec<_>>().join(" ")));+ }+ self.touch_workspace(&rec.info.id);+ let out = String::from_utf8_lossy(&output.stdout);+ let lines: Vec<&str> = out.lines().filter(|l| !l.trim().is_empty()).collect();+ Ok(lines[lines.len().saturating_sub(16)..].join("\n"))+ }++ /// Stops background commands and removes the workspace (and its folder unless `keep_files`).+ pub async fn destroy_workspace(self: &Arc<Self>, id: &str, keep_files: bool) -> Result<(), String> {+ self.refresh_from_disk();+ let rec = self.find_workspace(id)?;+ let wid = rec.info.id.clone();+ let title = if keep_files { format!("Forget workspace {wid}") } else { format!("Delete workspace {wid}") };+ let op = self.begin_op("workspace", title, Some(rec.info.machine_id.clone()), None);+ let previous = rec.info.status.clone();+ self.update_workspaces(|list| {+ if let Some(r) = list.iter_mut().find(|r| r.info.id == wid) {+ r.info.status = "destroying".into();+ }+ })?;++ // A path still starting with "~" was never confirmed by the machine: no folder was made.+ let has_folder = !rec.info.path.starts_with('~');+ let cleaned: Result<(), String> = match (self.demo_world(), self.machine(&rec.info.machine_id)) {+ (Some(_), _) => demo::destroy(self, op, &rec, keep_files).await,+ (None, Some((spec, _))) if spec.is_checkable() && has_folder => self.run_destroy(op, &spec, &rec, keep_files).await,+ (None, Some(_)) => {+ self.op_log(op, format!("No folder was created on {}; forgetting the workspace.", rec.info.machine_name));+ Ok(())+ }+ (None, None) => {+ self.op_log(op, format!("warning: {} isn't in fleet.toml anymore, so its files can't be cleaned up; forgetting the workspace.", rec.info.machine_name));+ Ok(())+ }+ };+ match cleaned {+ Ok(()) => {+ self.update_workspaces(|list| list.retain(|r| r.info.id != wid))?;+ self.op_log(op, format!("✓ Workspace {wid} is gone"));+ self.op_finish(op, Ok(()));+ Ok(())+ }+ Err(e) => {+ let _ = self.update_workspaces(|list| {+ if let Some(r) = list.iter_mut().find(|r| r.info.id == wid) {+ r.info.status = previous.clone();+ }+ });+ self.op_log(op, format!("error: {e}"));+ self.op_finish(op, Err(e.clone()));+ Err(e)+ }+ }+ }++ /// Current workspaces, most recently used first.+ pub fn workspaces(&self) -> Vec<WorkspaceInfo> {+ self.current().workspaces.clone()+ }++ /// Turns agent workspaces on or off for a machine (edits fleet.toml).+ pub fn set_workspaces_allowed(self: &Arc<Self>, machine_id: &str, allowed: bool) -> Result<(), String> {+ if self.machine(machine_id).is_none() {+ return Err(format!("Machine \"{machine_id}\" not found in fleet.toml."));+ }+ let edit = |text: &str| crate::ops::inventory_edit::set_workspaces(text, machine_id, allowed);+ match self.demo_world() {+ Some(w) => w.edit_inventory(edit)?,+ None => crate::ops::inventory_edit::edit_file(self.inventory_path(), edit)?,+ }+ self.reload_inventory_now();+ Ok(())+ }++ // -----------------------------------------------------------------------++ fn find_workspace(&self, id: &str) -> Result<WorkspaceRecord, String> {+ let id = id.trim();+ let records = self.workspace_records();+ if let Some(r) = records.iter().find(|r| r.info.id == id) {+ return Ok(r.clone());+ }+ let by_name: Vec<&WorkspaceRecord> = records.iter().filter(|r| r.info.name.eq_ignore_ascii_case(id)).collect();+ match by_name.as_slice() {+ [one] => Ok((*one).clone()),+ [] => Err(format!("Workspace \"{id}\" not found. Use list_workspaces to see the workspaces.")),+ _ => Err(format!("Several workspaces are called \"{id}\"; use the id (ws-…).")),+ }+ }++ /// The workspace, if it's ready for commands.+ fn ready_workspace(&self, id: &str) -> Result<WorkspaceRecord, String> {+ self.refresh_from_disk();+ let rec = self.find_workspace(id)?;+ match rec.info.status.as_str() {+ "ready" => Ok(rec),+ "creating" => Err(format!("Workspace {} is being created; try again once it's ready.", rec.info.id)),+ "destroying" => Err(format!("Workspace {} is being destroyed.", rec.info.id)),+ _ => Err(format!(+ "Workspace {} failed to set up ({}). Destroy it and create a new one.",+ rec.info.id,+ rec.info.error.clone().unwrap_or_default()+ )),+ }+ }++ fn workspace_machine(&self, rec: &WorkspaceRecord) -> Result<MachineSpec, String> {+ let (spec, _) = self.machine(&rec.info.machine_id).ok_or_else(|| {+ format!(+ "Machine {} not found in fleet.toml anymore, so OpenRunner can't reach workspace {}. Destroy it with keepFiles to forget it.",+ rec.info.machine_name, rec.info.id+ )+ })?;+ if !spec.is_checkable() {+ return Err(format!("{} has no host in fleet.toml.", spec.name));+ }+ Ok(spec)+ }++ fn workspace_info(&self, id: &str) -> Option<WorkspaceInfo> {+ self.current().workspaces.iter().find(|w| w.id == id).cloned()+ }++ fn unused_workspace_id(&self) -> String {+ let taken: Vec<String> = self.workspace_records().into_iter().map(|r| r.info.id).collect();+ loop {+ let id = format!("ws-{}", random_id(6));+ if !taken.contains(&id) {+ return id;+ }+ }+ }++ fn touch_workspace(&self, id: &str) {+ let _ = self.update_workspaces(|list| {+ if let Some(r) = list.iter_mut().find(|r| r.info.id == id) {+ r.info.last_used_at = Utc::now();+ }+ });+ }++ async fn run_create(+ self: &Arc<Self>,+ op: u64,+ spec: &MachineSpec,+ rec: &WorkspaceRecord,+ root: &str,+ repo: Option<&Repo>,+ ) -> Result<String, (String, Option<String>)> {+ self.op_log(op, format!("▸ Creating {} on {} ({})", rec.info.id, spec.name, spec.host.trim()));+ let folder: Arc<std::sync::Mutex<Option<String>>> = Arc::default();+ let attempt = |auth: Option<String>| {+ let folder = folder.clone();+ async move {+ let auth_s = auth.clone().unwrap_or_default();+ let repo_url = repo.map(|r| r.url.clone()).unwrap_or_default();+ let repo_shown = repo.map(|r| r.shown.clone()).unwrap_or_default();+ let git_ref = rec.info.git_ref.clone().unwrap_or_default();+ let branch = rec.info.branch.clone().unwrap_or_default();+ let container = rec.info.container.clone().unwrap_or_default();+ let image = rec.info.image.clone().unwrap_or_default();+ let mut params = vec![+ ("OR_ROOT", Param::Str(root)),+ ("OR_ID", Param::Str(&rec.info.id)),+ ("OR_REPO", Param::Str(&repo_url)),+ ("OR_REPO_SHOWN", Param::Str(&repo_shown)),+ ("OR_REF", Param::Str(&git_ref)),+ ("OR_BRANCH", Param::Str(&branch)),+ ("OR_AUTH", Param::Str(&auth_s)),+ ];+ let script = if rec.windows {+ params.insert(0, ("OR_ACTION", Param::Str("create")));+ with_params(Shell::Powershell, ¶ms, OTHER_PS1)+ } else {+ params.extend([+ ("OR_CONTAINER", Param::Str(&container)),+ ("OR_IMAGE", Param::Str(&image)),+ ("OR_SOCKET", Param::Bool(rec.docker_socket)),+ ]);+ with_params(Shell::Sh, ¶ms, &create_script(!container.is_empty()))+ };+ let mut secrets = Vec::new();+ if let Some(a) = &auth {+ secrets.push(a.clone());+ if let Some(enc) = a.strip_prefix("AUTHORIZATION: basic ") {+ secrets.push(enc.to_string());+ if let Some(tok) = B64.decode(enc).ok().and_then(|b| String::from_utf8(b).ok()) {+ if let Some(t) = tok.strip_prefix("x-access-token:") {+ secrets.push(t.to_string());+ }+ }+ }+ }+ let me = self.clone();+ let log = move |line: &str| match line.strip_prefix("path=") {+ Some(p) => {+ *folder.lock().unwrap() = Some(p.trim().to_string());+ me.op_log(op, format!("Folder: {p}"))+ }+ None if line == "ready" => {}+ None => me.op_log(op, line.to_string()),+ };+ run_checked(spec, rec.windows, script, CREATE_TIMEOUT, Limits::OUTPUT, &secrets, Some(&log)).await+ }+ };+ let fail = |message: String| (message, folder.lock().unwrap().clone());++ let out = match attempt(None).await {+ Ok(out) => out,+ Err(e) => {+ // A private GitHub repo: try again with the user's token, passed only through the environment.+ let retry = match repo {+ Some(r) if r.on_github && e.code == Some(4) => {+ self.github().git_credentials(&self.settings().github).await.filter(|(host, _)| *host == r.host)+ }+ _ => None,+ };+ let Some((_, token)) = retry else { return Err(fail(e.message)) };+ self.op_log(op, "▸ The clone needs credentials; retrying with your GitHub token");+ let header = format!("AUTHORIZATION: basic {}", B64.encode(format!("x-access-token:{token}")));+ attempt(Some(header)).await.map_err(|e| fail(e.message))?+ }+ };+ field(&out.stdout, "path").ok_or_else(|| fail("The machine didn't report the workspace folder.".to_string()))+ }++ #[allow(clippy::too_many_arguments)]+ async fn run_exec(+ &self,+ spec: &MachineSpec,+ rec: &WorkspaceRecord,+ command: &str,+ cwd: &str,+ env: &[(String, String)],+ timeout: u64,+ log: Option<String>,+ ) -> Result<ExecResult, String> {+ let timeout_s = timeout.to_string();+ let log_s = log.clone().unwrap_or_default();+ let shell = if rec.windows { Shell::Powershell } else { Shell::Sh };+ let params = [+ ("OR_DIR", Param::Str(&rec.info.path)),+ ("OR_CWD", Param::Str(cwd)),+ ("OR_CMD", Param::Str(command)),+ ("OR_TIMEOUT", Param::Str(&timeout_s)),+ ("OR_BG", Param::Bool(log.is_some())),+ ("OR_LOG", Param::Str(&log_s)),+ ("OR_ID", Param::Str(&rec.info.id)),+ ];+ let exports = env_exports(shell, env);+ let script = match (&rec.info.container, shell) {+ (Some(container), Shell::Sh) => {+ let image = rec.info.image.clone().unwrap_or_else(|| DEFAULT_IMAGE.to_string());+ let names: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();+ let names = names.join(" ");+ let all = [+ ("OR_DIR", Param::Str(&rec.info.path)),+ ("OR_CWD", Param::Str(cwd)),+ ("OR_CMD", Param::Str(command)),+ ("OR_TIMEOUT", Param::Str(&timeout_s)),+ ("OR_BG", Param::Bool(log.is_some())),+ ("OR_LOG", Param::Str(&log_s)),+ ("OR_ID", Param::Str(&rec.info.id)),+ ("OR_CONTAINER", Param::Str(container)),+ ("OR_IMAGE", Param::Str(&image)),+ ("OR_SOCKET", Param::Bool(rec.docker_socket)),+ ("OR_ENV", Param::Str(&names)),+ ];+ with_params(shell, &all, &format!("{exports}{LIB_SH}\n{DOCKER_SH}\n{EXEC_DOCKER_SH}"))+ }+ (_, Shell::Sh) => with_params(shell, ¶ms, &format!("{exports}{LIB_SH}\n{EXEC_SH}")),+ (_, Shell::Powershell) => with_params(shell, ¶ms, &format!("{exports}{EXEC_PS1}")),+ };+ let marker = transport::new_marker();+ let out = transport::run(+ spec,+ rec.windows,+ &marker,+ transport::with_marker(&marker, rec.windows, &script),+ Duration::from_secs(timeout + EXEC_GRACE),+ Limits::OUTPUT,+ &[],+ None,+ )+ .await?;+ exec_result(out, &spec.name, log)+ }++ async fn run_files(&self, spec: &MachineSpec, rec: &WorkspaceRecord, params: &[(&str, Param<'_>)]) -> Result<Output, String> {+ let mut all = vec![("OR_DIR", Param::Str(&rec.info.path))];+ for (k, v) in params {+ all.push((k, match v {+ Param::Str(s) => Param::Str(s),+ Param::List(l) => Param::List(l),+ Param::Bool(b) => Param::Bool(*b),+ }));+ }+ let (script, windows) = if rec.windows {+ (with_params(Shell::Powershell, &all, FILES_PS1), true)+ } else {+ (with_params(Shell::Sh, &all, FILES_SH), false)+ };+ run_checked(spec, windows, script, FILE_TIMEOUT, Limits::DATA, &[], None).await.map_err(|e| e.message)+ }++ async fn run_destroy(self: &Arc<Self>, op: u64, spec: &MachineSpec, rec: &WorkspaceRecord, keep: bool) -> Result<(), String> {+ self.op_log(op, format!("▸ Cleaning up on {} ({})", spec.name, spec.host.trim()));+ let pids: Vec<String> = rec.background_pids.iter().map(u32::to_string).collect();+ let pids = pids.join(" ");+ let script = if rec.windows {+ with_params(+ Shell::Powershell,+ &[+ ("OR_ACTION", Param::Str("destroy")),+ ("OR_DIR", Param::Str(&rec.info.path)),+ ("OR_ID", Param::Str(&rec.info.id)),+ ("OR_PIDS", Param::Str(&pids)),+ ("OR_KEEP", Param::Bool(keep)),+ ],+ OTHER_PS1,+ )+ } else {+ let container = rec.info.container.clone().unwrap_or_default();+ let image = rec.info.image.clone().unwrap_or_default();+ with_params(+ Shell::Sh,+ &[+ ("OR_DIR", Param::Str(&rec.info.path)),+ ("OR_ID", Param::Str(&rec.info.id)),+ ("OR_PIDS", Param::Str(&pids)),+ ("OR_KEEP", Param::Bool(keep)),+ ("OR_CONTAINER", Param::Str(&container)),+ ("OR_IMAGE", Param::Str(&image)),+ ],+ &format!("{LIB_SH}\n{DESTROY_SH}"),+ )+ };+ let me = self.clone();+ let log = move |line: &str| me.op_log(op, line.to_string());+ run_checked(spec, rec.windows, script, DESTROY_TIMEOUT, Limits::OUTPUT, &[], Some(&log)).await.map(|_| ()).map_err(|e| e.message)+ }+}++// ---------------------------------------------------------------------------+// Registry plumbing used by the engine.++pub(crate) fn load_registry(path: &std::path::Path) -> Vec<WorkspaceRecord> {+ registry::load(path)+}++pub(crate) fn update_registry<R>(+ path: &std::path::Path,+ f: impl FnOnce(&mut Vec<WorkspaceRecord>) -> R,+) -> Result<(R, Vec<WorkspaceRecord>, Option<std::time::SystemTime>), String> {+ registry::update(path, f)+}++pub(crate) fn demo_seed(world: &crate::demo::World) -> Vec<WorkspaceRecord> {+ demo::seed(world)+}++/// What the snapshot shows: stored records with current machine names and a+/// ready-to-run shell command, most recently used first.+pub(crate) fn snapshot_infos(records: &[WorkspaceRecord], machines: &[Machine], specs: &[MachineSpec]) -> Vec<WorkspaceInfo> {+ let mut out: Vec<WorkspaceInfo> = records+ .iter()+ .map(|r| {+ let mut info = r.info.clone();+ if let Some(m) = machines.iter().find(|m| m.id == info.machine_id) {+ info.machine_name = m.name.clone();+ info.host = m.host.clone();+ if !m.platform.is_empty() {+ info.platform = m.platform.clone();+ }+ }+ if let Some(spec) = specs.iter().find(|s| s.id == info.machine_id) {+ info.shell = match &info.container {+ Some(c) => docker_shell_command(spec, c),+ None => shell_command(spec, &info.path, r.windows),+ };+ }+ info+ })+ .collect();+ out.sort_by(|a, b| b.last_used_at.cmp(&a.last_used_at));+ out+}++// ---------------------------------------------------------------------------+// Helpers++/// A failure from a workspace script: the reason and the script's exit code.+struct ScriptError {+ message: String,+ code: Option<i32>,+}++/// Runs a script that reports failure through its exit status (`error: ...` on stderr).+async fn run_checked(+ spec: &MachineSpec,+ windows: bool,+ script: String,+ timeout: Duration,+ limits: Limits,+ secrets: &[String],+ on_line: Option<&(dyn Fn(&str) + Send + Sync)>,+) -> Result<Output, ScriptError> {+ let marker = transport::new_marker();+ let out = transport::run(spec, windows, &marker, transport::with_marker(&marker, windows, &script), timeout, limits, secrets, on_line)+ .await+ .map_err(|message| ScriptError { message, code: None })?;+ if out.timed_out {+ return Err(ScriptError { message: format!("{} is unreachable: no answer within {}s.", spec.name, timeout.as_secs()), code: None });+ }+ if !out.started {+ return Err(ScriptError { message: format!("{} is unreachable: {}", spec.name, out.reason()), code: out.status });+ }+ match out.status {+ Some(0) => Ok(out),+ code => Err(ScriptError { message: out.reason(), code }),+ }+}++impl From<ScriptError> for String {+ fn from(e: ScriptError) -> String {+ e.message+ }+}++fn exec_result(out: Output, machine: &str, log: Option<String>) -> Result<ExecResult, String> {+ if !out.started {+ return Err(format!("{machine} is unreachable: {}", out.reason()));+ }+ const SETUP: [&str; 5] = [+ "error: the workspace folder is gone",+ "error: there's no folder",+ "error: docker isn't available",+ "error: couldn't pull",+ "error: couldn't start a container",+ ];+ let setup_error = out.exit == Some(97) && out.stderr.lines().next().is_some_and(|l| SETUP.iter().any(|p| l.starts_with(p)));+ if setup_error {+ return Err(out.reason());+ }+ if out.exit.is_none() && !out.timed_out {+ return Err(format!("The ssh connection to {machine} dropped while the command ran: {}", out.reason()));+ }+ let background_pid = if log.is_some() { field(&out.stdout, "pid").and_then(|p| p.parse().ok()) } else { None };+ Ok(ExecResult {+ exit_code: if out.timed_out || log.is_some() { None } else { out.exit },+ stdout: if log.is_some() { String::new() } else { out.stdout },+ stderr: out.stderr,+ duration_ms: 0,+ timed_out: out.timed_out,+ truncated: out.truncated,+ background_pid,+ log_path: log,+ })+}++/// `export NAME='value'` (sh) or `$env:NAME = 'value'` (PowerShell) lines.+fn env_exports(shell: Shell, env: &[(String, String)]) -> String {+ env.iter()+ .map(|(k, v)| match shell {+ Shell::Sh => format!("export {k}={}\n", sh_quote(v)),+ Shell::Powershell => format!("$env:{k} = {}\n", ps_quote(v)),+ })+ .collect()+}++/// The value of a `key=value` line in script output.+fn field(text: &str, key: &str) -> Option<String> {+ let prefix = format!("{key}=");+ text.lines().find_map(|l| l.strip_prefix(&prefix)).map(|v| v.trim().to_string())+}++fn file_content(path: String, bytes: Vec<u8>, size: u64, max: usize) -> FileContent {+ let truncated = size > max as u64 || bytes.len() < size as usize;+ let text = match String::from_utf8(bytes) {+ Ok(t) => Some(t),+ // A cut can land inside a multi-byte character; keep the valid part.+ Err(e) if truncated && e.utf8_error().error_len().is_none() => {+ let valid = e.utf8_error().valid_up_to();+ let mut b = e.into_bytes();+ b.truncate(valid);+ String::from_utf8(b).ok()+ }+ Err(_) => None,+ };+ match text.filter(|t| !t.contains('\0')) {+ Some(content) => FileContent { path, content, size, truncated, binary: false },+ None => FileContent { path, content: String::new(), size, truncated, binary: true },+ }+}++fn parse_listing(text: &str, base: &str) -> Vec<FileEntry> {+ text.lines()+ .filter_map(|l| {+ let mut parts = l.splitn(3, '\t');+ let kind = match parts.next()? {+ "d" => "dir",+ "l" => "link",+ _ => "file",+ };+ let size = parts.next()?.trim().parse().unwrap_or(0);+ let rel = parts.next()?.trim_start_matches("./");+ if rel.is_empty() {+ return None;+ }+ let path = if base.is_empty() { rel.to_string() } else { format!("{base}/{rel}") };+ Some(FileEntry { path, kind: kind.into(), size: if kind == "dir" { 0 } else { size } })+ })+ .take(LIST_MAX_ENTRIES)+ .collect()+}++/// The last lines of a command's output, for history.+fn output_tail(stdout: &str, stderr: &str) -> Vec<String> {+ let lines: Vec<String> = stdout+ .lines()+ .chain(stderr.lines())+ .filter(|l| !l.trim().is_empty())+ .map(|l| if l.chars().count() > TAIL_LINE_MAX { format!("{}…", l.chars().take(TAIL_LINE_MAX).collect::<String>()) } else { l.to_string() })+ .collect();+ lines[lines.len().saturating_sub(registry::TAIL_LINES)..].to_vec()+}++fn clean_opt(s: Option<String>) -> Option<String> {+ s.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())+}++/// A path relative to the workspace, normalized to forward slashes. Rejects+/// absolute paths and `..`, so agents don't wander out by accident.+pub fn rel_path(p: &str) -> Result<String, String> {+ let p = p.trim();+ let drive = p.len() >= 2 && p.as_bytes()[1] == b':' && p.as_bytes()[0].is_ascii_alphabetic();+ if p.starts_with('/') || p.starts_with('\\') || p.starts_with('~') || drive {+ return Err(format!("\"{p}\" isn't inside the workspace. Paths are relative to the workspace folder."));+ }+ let mut parts = Vec::new();+ for seg in p.split(['/', '\\']) {+ match seg {+ "" | "." => {}+ ".." => return Err(format!("\"{p}\" leaves the workspace. Paths can't use \"..\".")),+ s if s.chars().any(char::is_control) => return Err(format!("\"{p}\" has control characters.")),+ s => parts.push(s),+ }+ }+ Ok(parts.join("/"))+}++fn validate_env(name: &str, value: &str) -> Result<(), String> {+ let ok = !name.is_empty()+ && name.len() <= 128+ && name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')+ && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');+ if !ok {+ return Err(format!("\"{name}\" isn't a valid environment variable name."));+ }+ if value.contains('\0') {+ return Err(format!("The value of {name} contains a NUL byte."));+ }+ Ok(())+}++fn validate_git_ref(r: &str) -> Result<(), String> {+ let bad = r.len() > 200+ || r.starts_with('-')+ || r.contains("..")+ || r.ends_with('/')+ || r.ends_with(".lock")+ || r.chars().any(|c| c.is_whitespace() || c.is_control() || "~^:?*[\\".contains(c));+ if bad { Err(format!("\"{r}\" isn't a valid git branch, tag or commit.")) } else { Ok(()) }+}++/// A repository to clone.+struct Repo {+ /// What git clones.+ url: String,+ /// Shown in the UI and logs (no credentials).+ shown: String,+ /// "api" for acme/api.+ short_name: String,+ host: String,+ /// https on the GitHub host OpenRunner has a token for.+ on_github: bool,+}++fn github_web_host(api_url: &str) -> String {+ let host = api_url.split("://").nth(1).unwrap_or(api_url).split('/').next().unwrap_or("api.github.com");+ if host == "api.github.com" { "github.com".into() } else { host.to_string() }+}++/// "owner/repo" means GitHub; anything else must look like a git URL or a path on the machine.+fn normalize_repo(raw: &str, gh_host: &str) -> Result<Repo, String> {+ let raw = raw.trim();+ if raw.starts_with('-') || raw.chars().any(|c| c.is_whitespace() || c.is_control()) {+ return Err(format!("\"{raw}\" isn't a repository OpenRunner can clone."));+ }+ let short = |s: &str| {+ s.trim_end_matches('/').rsplit(['/', ':']).next().unwrap_or(s).trim_end_matches(".git").to_string()+ };+ let simple = raw.split('/').count() == 2+ && !raw.contains(':')+ && !raw.starts_with('.')+ && raw.split('/').all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)));+ if simple {+ let path = raw.trim_end_matches(".git");+ return Ok(Repo {+ url: format!("https://{gh_host}/{path}.git"),+ shown: path.to_string(),+ short_name: short(path),+ host: gh_host.to_string(),+ on_github: true,+ });+ }+ let is_url = ["https://", "http://", "ssh://", "git://", "file://"].iter().any(|p| raw.starts_with(p));+ let scp_like = raw.contains('@') && raw.contains(':') && !raw.contains("://");+ let path_like = raw.starts_with('/') || raw.starts_with("~/");+ if !(is_url || scp_like || path_like) {+ return Err(format!("\"{raw}\" isn't a repository. Use owner/repo for GitHub, or a git URL."));+ }+ // Never echo credentials embedded in a URL.+ let shown = match raw.split_once("://") {+ Some((scheme, rest)) => match rest.split_once('@') {+ Some((_, after)) if rest.find('@') < rest.find('/') => format!("{scheme}://{after}"),+ _ => raw.to_string(),+ },+ None => raw.to_string(),+ };+ let host = raw+ .split_once("://")+ .map(|(_, rest)| rest.split('/').next().unwrap_or("").rsplit('@').next().unwrap_or("").to_string())+ .unwrap_or_default();+ Ok(Repo {+ url: raw.to_string(),+ short_name: short(&shown),+ on_github: raw.starts_with("https://") && host.eq_ignore_ascii_case(gh_host),+ host,+ shown,+ })+}++fn machine_names(machines: &[Machine]) -> String {+ machines.iter().map(|m| m.id.as_str()).collect::<Vec<_>>().join(", ")+}++/// "macos" → "darwin", "x86_64" → "x64", ... so agents can say it however they like.+fn normalize_platform(p: &str) -> String {+ let p = p.trim().to_ascii_lowercase().replace('_', "-");+ let (os, arch) = p.split_once('-').map(|(o, a)| (o.to_string(), Some(a.to_string()))).unwrap_or((p.clone(), None));+ let os = match os.as_str() {+ "mac" | "macos" | "osx" | "apple" => "darwin".to_string(),+ "win" | "win32" => "windows".to_string(),+ o => o.to_string(),+ };+ let arch = arch.map(|a| match a.as_str() {+ "amd64" | "x86-64" | "x8664" | "86-64" => "x64".to_string(),+ "aarch64" => "arm64".to_string(),+ a => a.to_string(),+ });+ match arch {+ Some(a) => format!("{os}-{a}"),+ None => os,+ }+}++/// The online machine that allows workspaces with the most headroom.+#[cfg_attr(not(test), allow(dead_code))]+pub(crate) fn pick_machine<'a>(machines: &'a [Machine], platform: Option<&str>) -> Result<&'a Machine, String> {+ pick_machine_for(machines, platform, false)+}++/// Like `pick_machine`; for docker workspaces, prefers machines whose last+/// check found docker (when no check has reported docker yet, any will do —+/// the create step checks for real).+pub(crate) fn pick_machine_for<'a>(machines: &'a [Machine], platform: Option<&str>, docker: bool) -> Result<&'a Machine, String> {+ let want = platform.map(normalize_platform);+ let platform_ok = |m: &Machine| want.as_deref().is_none_or(|w| m.platform.starts_with(w));+ let disk_ok = |m: &Machine| m.probe.as_ref().and_then(|p| p.disk_free).is_none_or(|f| f >= MIN_FREE_DISK);+ let mut candidates: Vec<&Machine> = machines+ .iter()+ .filter(|m| m.status == "online" && m.workspaces_allowed && platform_ok(m) && disk_ok(m) && !(docker && m.platform.starts_with("windows")))+ .collect();+ if docker && candidates.iter().any(|m| m.probe.as_ref().is_some_and(|p| p.docker.is_some())) {+ candidates.retain(|m| m.probe.as_ref().is_some_and(|p| p.docker.is_some()));+ }+ let score = |m: &Machine| {+ let p = m.probe.as_ref();+ let cpu = p.and_then(|p| p.cpu_pct).unwrap_or(50.0);+ let mem = p.and_then(|p| Some(p.mem_used? as f64 / p.mem_total?.max(1) as f64 * 100.0)).unwrap_or(50.0);+ let low_disk = p.and_then(|p| p.disk_free).is_some_and(|f| f < 20_000_000_000);+ cpu + mem + m.summary.working as f64 * 20.0 + if low_disk { 100.0 } else { 0.0 }+ };+ candidates+ .into_iter()+ .min_by(|a, b| score(a).total_cmp(&score(b)).then_with(|| a.name.cmp(&b.name)))+ .ok_or_else(|| {+ let what = match (&want, docker) {+ (Some(w), true) => format!("allows workspaces, runs {w} and can run docker"),+ (Some(w), false) => format!("allows workspaces and runs {w}"),+ (None, true) => "allows workspaces and can run docker".into(),+ (None, false) => "allows workspaces".into(),+ };+ let online: Vec<String> = machines+ .iter()+ .filter(|m| m.status == "online")+ .map(|m| format!("{} ({}{})", m.id, m.platform, if m.workspaces_allowed { "" } else { ", workspaces off" }))+ .collect();+ if online.is_empty() {+ format!("No machine is online right now. Run check_machines, or add a machine.")+ } else {+ format!("No online machine {what} and has free disk. Online: {}.", online.join(", "))+ }+ })+}++/// A command a human can paste to get a shell inside the workspace.+pub(crate) fn shell_command(spec: &MachineSpec, path: &str, windows: bool) -> String {+ if spec.is_local() {+ return if windows { format!("Set-Location {}", ps_quote(path)) } else { format!("cd {} && exec \"$SHELL\" -l", sh_quote(path)) };+ }+ let mut parts = vec!["ssh".to_string(), "-t".to_string()];+ if let Some(port) = spec.port {+ parts.push(format!("-p {port}"));+ }+ if let Some(user) = spec.user.as_deref().filter(|u| !u.is_empty()) {+ parts.push(format!("-l {user}"));+ }+ parts.extend(spec.ssh_options.iter().map(|o| display_arg(o)));+ parts.push(spec.host.trim().to_string());+ let inner = if windows {+ format!("\"powershell -NoExit -Command Set-Location '{path}'\"")+ } else {+ format!("\"cd '{path}' && exec \\$SHELL -l\"")+ };+ parts.push(inner);+ parts.join(" ")+}++/// `openrunner-ws-<id>`.+pub(crate) fn container_name(id: &str) -> String {+ format!("openrunner-ws-{}", id.trim_start_matches("ws-"))+}++/// A docker image reference: registry/name:tag or name@sha256:..., nothing that+/// could be read as a flag.+fn validate_image(image: &str) -> Result<String, String> {+ let ok = !image.is_empty()+ && image.len() <= 255+ && !image.starts_with(['-', '.', '/', ':', '@'])+ && image.chars().all(|c| c.is_ascii_alphanumeric() || "-_./:@".contains(c));+ if ok { Ok(image.to_string()) } else { Err(format!("\"{image}\" isn't a docker image name (like node:22 or ghcr.io/acme/dev:latest).")) }+}++/// The create script: make the folder (and clone) on the host, then, for docker+/// workspaces, check docker first and start the container last.+fn create_script(docker: bool) -> String {+ if docker {+ format!(+ "{DOCKER_SH}\nor_docker_check || exit 6\n{CREATE_SH}\nor_docker_up \"$(pwd -P)\" || exit 6\necho \"Container $OR_CONTAINER is running\"\n"+ )+ } else {+ CREATE_SH.to_string()+ }+}++/// A shell inside a docker workspace's container, for a human.+pub(crate) fn docker_shell_command(spec: &MachineSpec, container: &str) -> String {+ let inner = format!("docker start {container} >/dev/null && docker exec -it -w /workspace {container} sh -c 'exec bash 2>/dev/null || exec sh'");+ if spec.is_local() {+ return inner;+ }+ let mut parts = vec!["ssh".to_string(), "-t".to_string()];+ if let Some(port) = spec.port {+ parts.push(format!("-p {port}"));+ }+ if let Some(user) = spec.user.as_deref().filter(|u| !u.is_empty()) {+ parts.push(format!("-l {user}"));+ }+ parts.extend(spec.ssh_options.iter().map(|o| display_arg(o)));+ parts.push(spec.host.trim().to_string());+ parts.push(format!("\"{inner}\""));+ parts.join(" ")+}++fn display_arg(a: &str) -> String {+ if a.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:@~,".contains(c)) { a.to_string() } else { sh_quote(a) }+}++fn rsync_args(spec: &MachineSpec, remote_path: &str, local: &str, direction: SyncDirection, delete: bool) -> Vec<String> {+ let mut args = vec!["-az".to_string(), "--stats".to_string(), "--exclude=/.openrunner/".to_string()];+ if delete {+ args.push("--delete".into());+ }+ let remote = if spec.is_local() {+ format!("{}/", remote_path.trim_end_matches('/'))+ } else {+ let mut ssh = crate::probe::ssh_args(spec);+ ssh.pop(); // the host goes in the remote path+ let ssh: Vec<String> = ssh.iter().map(|a| display_arg(a)).collect();+ args.push("-e".into());+ args.push(format!("ssh {}", ssh.join(" ")));+ format!("{}:{}/", spec.host.trim(), remote_path.trim_end_matches('/'))+ };+ let local = format!("{}/", local.trim_end_matches('/'));+ match direction {+ SyncDirection::Push => {+ args.push(local);+ args.push(remote);+ }+ SyncDirection::Pull => {+ args.push(remote);+ args.push(local);+ }+ }+ args+}++fn expand_home(p: &str) -> std::path::PathBuf {+ match (p.strip_prefix("~/"), dirs::home_dir()) {+ (Some(rest), Some(home)) => home.join(rest),+ _ if p == "~" => dirs::home_dir().unwrap_or_default(),+ _ => std::path::PathBuf::from(p),+ }+}++/// Lowercase base36, from a small per-process generator (no extra dependency).+pub(crate) fn random_id(len: usize) -> String {+ static STATE: AtomicU64 = AtomicU64::new(0);+ let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(1)+ ^ (std::process::id() as u64).rotate_left(32);+ let mut x = STATE.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed).wrapping_add(seed);+ const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";+ (0..len)+ .map(|_| {+ // splitmix64+ x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut z = x;+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^= z >> 31;+ DIGITS[(z % 36) as usize] as char+ })+ .collect()+}++#[cfg(test)]+mod tests;diff --git a/src/fleet/workspaces/registry.rs b/src/fleet/workspaces/registry.rsnew file mode 100644index 0000000..a7b900d--- /dev/null+++ b/src/fleet/workspaces/registry.rs@@ -0,0 +1,234 @@+//! `workspaces.json`: the workspaces every OpenRunner process shares (the+//! window, the CLI, each agent's MCP server). Writers take a lock file, re-read,+//! change, and write atomically, so two processes never drop each other's edits.++use std::fs::OpenOptions;+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant, SystemTime};++use serde::{Deserialize, Serialize};++use crate::config::{display_path, write_atomic};+use crate::fleet::model::WorkspaceInfo;++const LOCK_WAIT: Duration = Duration::from_secs(5);+/// A lock older than this was left by a process that died mid-write.+const STALE_LOCK: Duration = Duration::from_secs(10);+pub const MAX_HISTORY: usize = 100;+pub const TAIL_LINES: usize = 30;++/// A workspace as stored: what the snapshot shows plus a little bookkeeping.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WorkspaceRecord {+ #[serde(flatten)]+ pub info: WorkspaceInfo,+ /// Background commands it started, killed on destroy.+ #[serde(default)]+ pub background_pids: Vec<u32>,+ /// The machine speaks PowerShell.+ #[serde(default)]+ pub windows: bool,+ /// Numbers the background logs: `.openrunner/logs/<n>.log`.+ #[serde(default)]+ pub next_log: u32,+ /// Docker workspaces: the host's docker socket is shared with the container+ /// (kept so a missing container is recreated the same way).+ #[serde(default)]+ pub docker_socket: bool,+}++#[derive(Debug, Default, Serialize, Deserialize)]+struct RegistryFile {+ #[serde(default)]+ version: u32,+ #[serde(default)]+ workspaces: Vec<WorkspaceRecord>,+}++/// Reads the registry. A missing or unreadable file is an empty registry.+pub fn load(path: &Path) -> Vec<WorkspaceRecord> {+ match std::fs::read_to_string(path) {+ Ok(text) => match serde_json::from_str::<RegistryFile>(&text) {+ Ok(f) => f.workspaces,+ Err(e) => {+ tracing::warn!("ignoring {}: {e}", display_path(path));+ Vec::new()+ }+ },+ Err(_) => Vec::new(),+ }+}++/// Locks, re-reads, applies `f`, writes. Returns `f`'s result, the new list and the file's mtime.+pub fn update<R>(+ path: &Path,+ f: impl FnOnce(&mut Vec<WorkspaceRecord>) -> R,+) -> Result<(R, Vec<WorkspaceRecord>, Option<SystemTime>), String> {+ let _lock = Lock::acquire(&lock_path(path))?;+ let mut list = load(path);+ let result = f(&mut list);+ let file = RegistryFile { version: 1, workspaces: list };+ let bytes = serde_json::to_vec_pretty(&file).map_err(|e| e.to_string())?;+ write_atomic(path, &bytes).map_err(|e| format!("Couldn't save workspaces: {e:#}"))?;+ let mtime = std::fs::metadata(path).and_then(|m| m.modified()).ok();+ Ok((result, file.workspaces, mtime))+}++/// Keeps the newest commands and trims long output lines.+pub fn cap_history(info: &mut WorkspaceInfo) {+ if info.history.len() > MAX_HISTORY {+ let extra = info.history.len() - MAX_HISTORY;+ info.history.drain(..extra);+ }+}++fn lock_path(path: &Path) -> PathBuf {+ path.with_extension("lock")+}++struct Lock(PathBuf);++impl Lock {+ fn acquire(path: &Path) -> Result<Lock, String> {+ if let Some(dir) = path.parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ let started = Instant::now();+ loop {+ match OpenOptions::new().write(true).create_new(true).open(path) {+ Ok(_) => return Ok(Lock(path.to_path_buf())),+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {+ let age = std::fs::metadata(path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok());+ if age.is_some_and(|a| a > STALE_LOCK) {+ let _ = std::fs::remove_file(path);+ continue;+ }+ if started.elapsed() > LOCK_WAIT {+ return Err(format!("{} is locked by another OpenRunner process.", display_path(path)));+ }+ std::thread::sleep(Duration::from_millis(15));+ }+ Err(e) => return Err(format!("Couldn't lock {}: {e}", display_path(path))),+ }+ }+ }+}++impl Drop for Lock {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.0);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::Utc;++ pub fn record(id: &str) -> WorkspaceRecord {+ WorkspaceRecord {+ info: WorkspaceInfo {+ id: id.into(),+ name: id.into(),+ machine_id: "box".into(),+ machine_name: "Box".into(),+ host: "box".into(),+ platform: "linux-x64".into(),+ path: format!("/home/ci/openrunner/workspaces/{id}"),+ repo: None,+ git_ref: None,+ branch: None,+ owner: Some("test".into()),+ status: "ready".into(),+ error: None,+ created_at: Utc::now(),+ last_used_at: Utc::now(),+ commands: 0,+ history: Vec::new(),+ shell: String::new(),+ isolation: "host".into(),+ image: None,+ container: None,+ },+ background_pids: vec![42],+ windows: false,+ next_log: 1,+ docker_socket: false,+ }+ }++ fn temp(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("openrunner-reg-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir.join("workspaces.json")+ }++ #[test]+ fn round_trips_and_keeps_bookkeeping() {+ let path = temp("rt");+ let (_, list, mtime) = update(&path, |l| l.push(record("ws-aaaaaa"))).unwrap();+ assert_eq!(list.len(), 1);+ assert!(mtime.is_some());+ let loaded = load(&path);+ assert_eq!(loaded[0].info.id, "ws-aaaaaa");+ assert_eq!(loaded[0].background_pids, vec![42]);+ // The info fields sit at the top level next to the bookkeeping.+ let text = std::fs::read_to_string(&path).unwrap();+ assert!(text.contains("\"machineId\": \"box\"") && text.contains("\"backgroundPids\""), "{text}");+ assert!(!lock_path(&path).exists(), "lock released");+ let _ = std::fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn concurrent_writers_dont_lose_updates() {+ let path = temp("conc");+ let handles: Vec<_> = (0..8)+ .map(|i| {+ let path = path.clone();+ std::thread::spawn(move || {+ update(&path, |l| l.push(record(&format!("ws-{i:06}")))).unwrap();+ })+ })+ .collect();+ for h in handles {+ h.join().unwrap();+ }+ assert_eq!(load(&path).len(), 8);+ let _ = std::fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn breaks_stale_locks_and_times_out_on_live_ones() {+ let path = temp("lock");+ let lock = lock_path(&path);+ std::fs::write(&lock, "").unwrap();+ // Make it look old.+ let old = std::time::SystemTime::now() - Duration::from_secs(60);+ std::fs::File::options().write(true).open(&lock).unwrap().set_modified(old).unwrap();+ assert!(update(&path, |l| l.push(record("ws-bbbbbb"))).is_ok());+ assert_eq!(load(&path).len(), 1);+ let _ = std::fs::remove_dir_all(path.parent().unwrap());+ }++ #[test]+ fn caps_history() {+ let mut r = record("ws-cccccc");+ for i in 0..(MAX_HISTORY + 5) {+ r.info.history.push(crate::fleet::model::WorkspaceCommand {+ command: format!("echo {i}"),+ exit_code: Some(0),+ started_at: Utc::now(),+ duration_ms: 1,+ output_tail: vec![],+ background: false,+ timed_out: false,+ by: None,+ });+ }+ cap_history(&mut r.info);+ assert_eq!(r.info.history.len(), MAX_HISTORY);+ assert_eq!(r.info.history[0].command, "echo 5");+ }+}diff --git a/src/fleet/workspaces/scripts/changes.sh b/src/fleet/workspaces/scripts/changes.shnew file mode 100644index 0000000..7e57bd9--- /dev/null+++ b/src/fleet/workspaces/scripts/changes.sh@@ -0,0 +1,10 @@+# git status and the diff of uncommitted work. Prepended: OR_DIR+cd "$OR_DIR" 2>/dev/null || { echo "error: the workspace folder is gone: $OR_DIR" >&2; exit 97; }+export GIT_PAGER=cat PAGER=cat NO_COLOR=1+if ! command -v git >/dev/null 2>&1; then echo "git isn't installed on this machine, so there's no change tracking."; exit 0; fi+if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then echo "This workspace isn't a git checkout, so there's nothing to diff."; exit 0; fi+echo "## git status"+git status --short --branch+echo+echo "## git diff"+if git rev-parse --verify -q HEAD >/dev/null 2>&1; then git --no-pager diff --no-color HEAD; else git --no-pager diff --no-color --cached; fidiff --git a/src/fleet/workspaces/scripts/create.sh b/src/fleet/workspaces/scripts/create.shnew file mode 100644index 0000000..ebd40eb--- /dev/null+++ b/src/fleet/workspaces/scripts/create.sh@@ -0,0 +1,40 @@+# Creates a workspace folder and optionally clones a repository into it.+# Prepended: OR_ROOT OR_ID OR_STEP (all | clone) OR_REPO OR_REPO_SHOWN OR_REF OR_BRANCH OR_AUTH+# OR_AUTH is an http.extraHeader value; it only ever lives in this process's environment.++or_root=$OR_ROOT+case "$or_root" in "~") or_root=$HOME ;; "~/"*) or_root="$HOME/${or_root#\~/}" ;; esac+mkdir -p "$or_root/$OR_ID" || { echo "error: couldn't create $or_root/$OR_ID" >&2; exit 3; }+cd "$or_root/$OR_ID" || { echo "error: couldn't open $or_root/$OR_ID" >&2; exit 3; }+or_here=$(pwd -P)+case "$or_here" in */"$OR_ID") ;; *) echo "error: unexpected workspace folder $or_here" >&2; exit 3 ;; esac+printf 'path=%s\n' "$or_here"++if [ -n "$OR_REPO" ]; then+ command -v git >/dev/null 2>&1 || { echo "error: git isn't installed on $(hostname)" >&2; exit 3; }+ export GIT_TERMINAL_PROMPT=0+ if [ -n "$OR_AUTH" ]; then+ export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$OR_AUTH"+ fi+ # Start from an empty folder (a retry may follow a failed attempt).+ find . -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null+ echo "Cloning $OR_REPO_SHOWN"+ if [ -n "$OR_REF" ]; then+ # Branches and tags clone shallow; a commit needs history.+ if ! git clone --progress --depth 1 --branch "$OR_REF" "$OR_REPO" . 2>&1; then+ find . -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null+ echo "$OR_REF isn't a branch or tag; cloning full history to check it out"+ git clone --progress "$OR_REPO" . 2>&1 || { echo "error: git clone failed" >&2; exit 4; }+ git -c advice.detachedHead=false checkout "$OR_REF" 2>&1 || { echo "error: couldn't check out $OR_REF" >&2; exit 5; }+ fi+ else+ git clone --progress --depth 1 "$OR_REPO" . 2>&1 || { echo "error: git clone failed" >&2; exit 4; }+ fi+ if [ -n "$OR_BRANCH" ]; then+ git checkout -b "$OR_BRANCH" 2>&1 || { echo "error: couldn't create branch $OR_BRANCH" >&2; exit 5; }+ fi+ printf '.openrunner/\n' >> .git/info/exclude 2>/dev/null+ echo "Checked out $(git rev-parse --abbrev-ref HEAD 2>/dev/null) at $(git rev-parse --short HEAD 2>/dev/null)"+fi+mkdir -p .openrunner/logs+echo "ready"diff --git a/src/fleet/workspaces/scripts/destroy.sh b/src/fleet/workspaces/scripts/destroy.shnew file mode 100644index 0000000..2bb207a--- /dev/null+++ b/src/fleet/workspaces/scripts/destroy.sh@@ -0,0 +1,32 @@+# Stops a workspace's background commands and deletes its folder.+# Prepended: OR_DIR OR_ID OR_PIDS (space separated) OR_KEEP, and for docker+# workspaces OR_CONTAINER and OR_IMAGE.+if [ -n "$OR_CONTAINER" ]; then+ if command -v docker >/dev/null 2>&1; then+ if docker rm -f "$OR_CONTAINER" >/dev/null 2>&1; then echo "Removed container $OR_CONTAINER"; else echo "Container $OR_CONTAINER was already gone"; fi+ else+ echo "warning: docker isn't available, so container $OR_CONTAINER couldn't be removed"+ fi+fi+for or_pid in $OR_PIDS; do+ if kill -0 "$or_pid" 2>/dev/null; then+ or_kill_tree "$or_pid" TERM+ echo "Stopped background process $or_pid"+ fi+done+if [ "$OR_KEEP" = 1 ]; then echo "Kept the files in $OR_DIR"; exit 0; fi+# Only ever delete a workspace folder.+case "$OR_DIR" in */"$OR_ID") ;; *) echo "error: refusing to delete $OR_DIR" >&2; exit 3 ;; esac+if [ -d "$OR_DIR" ]; then+ if ! rm -rf "$OR_DIR" 2>/dev/null; then+ # Files a container created as root (e.g. through a shared docker socket):+ # delete them from a throwaway container of the same image.+ if [ -n "$OR_IMAGE" ] && command -v docker >/dev/null 2>&1; then+ docker run --rm --user 0:0 --entrypoint sh -v "${OR_DIR%/*}:/parent" "$OR_IMAGE" -c "rm -rf /parent/$OR_ID" >/dev/null 2>&1+ fi+ [ ! -e "$OR_DIR" ] || { echo "error: couldn't delete $OR_DIR" >&2; exit 3; }+ fi+ echo "Deleted $OR_DIR"+else+ echo "$OR_DIR was already gone"+fidiff --git a/src/fleet/workspaces/scripts/docker.sh b/src/fleet/workspaces/scripts/docker.shnew file mode 100644index 0000000..2457bf0--- /dev/null+++ b/src/fleet/workspaces/scripts/docker.sh@@ -0,0 +1,55 @@+# Docker helpers for container workspaces. Expects OR_ID OR_CONTAINER OR_IMAGE OR_SOCKET.+# The workspace folder stays on the host and is bind-mounted at /workspace; the+# container runs as the host user so files never end up owned by root.++# or_docker_check: docker is installed and the daemon answers.+or_docker_check() {+ if ! command -v docker >/dev/null 2>&1; then+ echo "error: docker isn't available on $(hostname): the docker command isn't installed" >&2+ return 1+ fi+ if ! or_dk_err=$(docker info --format '{{.ServerVersion}}' 2>&1 >/dev/null); then+ echo "error: docker isn't available on $(hostname): $(printf '%s' "$or_dk_err" | grep -v '^$' | tail -n 1)" >&2+ return 1+ fi+}++# or_docker_up DIR [quiet]: makes sure the workspace's container is running,+# creating it (and pulling the image) when it doesn't exist.+or_docker_up() {+ or_dk_state=$(docker inspect -f '{{.State.Running}}' "$OR_CONTAINER" 2>/dev/null) || or_dk_state=missing+ case "$or_dk_state" in+ true) return 0 ;;+ false)+ docker start "$OR_CONTAINER" >/dev/null 2>&1 && return 0+ docker rm -f "$OR_CONTAINER" >/dev/null 2>&1 ;;+ esac+ if ! docker image inspect "$OR_IMAGE" >/dev/null 2>&1; then+ [ -n "$2" ] || echo "Pulling $OR_IMAGE"+ if ! or_dk_out=$(docker pull "$OR_IMAGE" 2>&1); then+ echo "error: couldn't pull $OR_IMAGE: $(printf '%s' "$or_dk_out" | grep -v '^$' | tail -n 1)" >&2+ return 1+ fi+ [ -n "$2" ] || printf '%s\n' "$or_dk_out" | tail -n 2+ fi+ mkdir -p "$1/.openrunner/home" "$1/.openrunner/logs" "$1/.openrunner/run"+ or_dk_sock=""+ if [ "$OR_SOCKET" = 1 ]; then+ if [ -S /var/run/docker.sock ]; then+ or_dk_gid=$(ls -lnL /var/run/docker.sock | awk '{ print $4 }')+ or_dk_sock="-v /var/run/docker.sock:/var/run/docker.sock --group-add $or_dk_gid"+ else+ echo "warning: there's no /var/run/docker.sock to share with the container"+ fi+ fi+ [ -n "$2" ] || echo "Starting container $OR_CONTAINER from $OR_IMAGE"+ # A shell loop keeps it alive (works on any image with sh, unlike `sleep infinity`).+ # shellcheck disable=SC2086+ if ! or_dk_out=$(docker run -d --name "$OR_CONTAINER" --label "openrunner.workspace=$OR_ID" --init \+ --user "$(id -u):$(id -g)" -e HOME=/workspace/.openrunner/home \+ -v "$1:/workspace" -w /workspace $or_dk_sock \+ --entrypoint sh "$OR_IMAGE" -c 'trap "exit 0" TERM INT; while :; do sleep 3600 & wait $!; done' 2>&1); then+ echo "error: couldn't start a container from $OR_IMAGE: $(printf '%s' "$or_dk_out" | grep -v '^$' | tail -n 1)" >&2+ return 1+ fi+}diff --git a/src/fleet/workspaces/scripts/exec.ps1 b/src/fleet/workspaces/scripts/exec.ps1new file mode 100644index 0000000..b3dad97--- /dev/null+++ b/src/fleet/workspaces/scripts/exec.ps1@@ -0,0 +1,34 @@+# Runs one command in a workspace (Windows, best effort). Prepended: $OR_DIR $OR_CWD+# $OR_CMD $OR_TIMEOUT $OR_BG $OR_LOG $OR_ID and `$env:NAME = ...` lines.+# Timeouts are enforced by OpenRunner hanging up; the command isn't killed on the machine.++$ErrorActionPreference = 'Continue'+function Or-Fail($msg) { [Console]::Error.WriteLine("error: $msg"); [Console]::Error.WriteLine("${OR_MARK}:exit=97"); exit 0 }+try { Set-Location -LiteralPath $OR_DIR -ErrorAction Stop } catch { Or-Fail "the workspace folder is gone: $OR_DIR" }+if ($OR_CWD) { try { Set-Location -LiteralPath $OR_CWD -ErrorAction Stop } catch { Or-Fail "there's no folder $OR_CWD in the workspace" } }+$env:OPENRUNNER_WORKSPACE = $OR_ID+$env:NO_COLOR = '1'+$env:GIT_TERMINAL_PROMPT = '0'++if ($OR_BG) {+ New-Item -ItemType Directory -Force -Path (Join-Path $OR_DIR '.openrunner\logs') | Out-Null+ $log = Join-Path $OR_DIR $OR_LOG+ $p = Start-Process -FilePath 'powershell' -ArgumentList @('-NoProfile', '-NonInteractive', '-Command', $OR_CMD) `+ -RedirectStandardOutput $log -RedirectStandardError "$log.err" -WindowStyle Hidden -PassThru+ Write-Output "pid=$($p.Id)"+ [Console]::Error.WriteLine("${OR_MARK}:exit=0")+ exit 0+}++$global:LASTEXITCODE = 0+$code = 0+try {+ Invoke-Expression $OR_CMD+ if (-not $?) { $code = 1 }+ if ($LASTEXITCODE) { $code = $LASTEXITCODE }+} catch {+ [Console]::Error.WriteLine($_.ToString())+ $code = 1+}+[Console]::Error.WriteLine("${OR_MARK}:exit=$code")+exit 0diff --git a/src/fleet/workspaces/scripts/exec.sh b/src/fleet/workspaces/scripts/exec.shnew file mode 100644index 0000000..2867e73--- /dev/null+++ b/src/fleet/workspaces/scripts/exec.sh@@ -0,0 +1,36 @@+# Runs one command in a workspace. Prepended: OR_DIR OR_CWD OR_CMD OR_TIMEOUT OR_BG OR_LOG OR_ID+# and `export NAME=...` lines for the caller's environment variables.++or_fail() { echo "error: $1" >&2; printf '%s:exit=97\n' "$OR_MARK" >&2; exit 0; }+cd "$OR_DIR" 2>/dev/null || or_fail "the workspace folder is gone: $OR_DIR"+if [ -n "$OR_CWD" ]; then cd "$OR_CWD" 2>/dev/null || or_fail "there's no folder $OR_CWD in the workspace"; fi+export OPENRUNNER_WORKSPACE="$OR_ID" NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat++# Run the command with the user's own shell when it's an sh-family one.+or_shell=sh+case "$SHELL" in */bash|*/zsh|*/ksh) or_shell=$SHELL ;; esac++if [ "$OR_BG" = 1 ]; then+ mkdir -p "$OR_DIR/.openrunner/logs"+ nohup "$or_shell" -c "$OR_CMD" > "$OR_DIR/$OR_LOG" 2>&1 < /dev/null &+ printf 'pid=%s\n' "$!"+ printf '%s:exit=0\n' "$OR_MARK" >&2+ exit 0+fi++"$or_shell" -c "$OR_CMD" < /dev/null &+or_pid=$!+# Watchdog: on timeout, kill the whole process tree (not just the shell).+(+ sleep "$OR_TIMEOUT"+ printf '%s:timeout\n' "$OR_MARK" >&2+ or_kill_tree "$or_pid" TERM+ sleep 3+ or_kill_tree "$or_pid" KILL+) < /dev/null > /dev/null &+or_watch=$!+wait "$or_pid"+or_code=$?+or_kill_tree "$or_watch" KILL+printf '%s:exit=%s\n' "$OR_MARK" "$or_code" >&2+exit 0diff --git a/src/fleet/workspaces/scripts/exec_docker.sh b/src/fleet/workspaces/scripts/exec_docker.shnew file mode 100644index 0000000..fe5d9f4--- /dev/null+++ b/src/fleet/workspaces/scripts/exec_docker.sh@@ -0,0 +1,71 @@+# Runs one command inside a workspace's container. Prepended: OR_DIR OR_CWD OR_CMD+# OR_TIMEOUT OR_BG OR_LOG OR_ID OR_CONTAINER OR_IMAGE OR_SOCKET OR_ENV (names of+# exported variables to pass in), plus the docker.sh and lib.sh helpers.++or_fail() { echo "error: $1" >&2; printf '%s:exit=97\n' "$OR_MARK" >&2; exit 0; }+or_setup_failed() { printf '%s:exit=97\n' "$OR_MARK" >&2; exit 0; }+[ -d "$OR_DIR" ] || or_fail "the workspace folder is gone: $OR_DIR"+if [ -n "$OR_CWD" ] && [ ! -d "$OR_DIR/$OR_CWD" ]; then or_fail "there's no folder $OR_CWD in the workspace"; fi+or_docker_check || or_setup_failed+or_docker_up "$OR_DIR" quiet || or_setup_failed+mkdir -p "$OR_DIR/.openrunner/run" "$OR_DIR/.openrunner/logs"++export OPENRUNNER_WORKSPACE="$OR_ID" NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat+or_envs="-e OPENRUNNER_WORKSPACE -e NO_COLOR -e GIT_TERMINAL_PROMPT -e GIT_PAGER -e PAGER"+for or_n in $OR_ENV; do or_envs="$or_envs -e $or_n"; done+or_wd=/workspace${OR_CWD:+/$OR_CWD}+# The command's pid (inside the container) is written here, so a timeout can kill it.+or_pidfile=".openrunner/run/$OR_MARK.pid"++if [ "$OR_BG" = 1 ]; then+ # shellcheck disable=SC2086+ docker exec -d -w "$or_wd" $or_envs "$OR_CONTAINER" \+ sh -c 'echo $$ > "/workspace/$1"; exec sh -c "$2" > "/workspace/$3" 2>&1 < /dev/null' sh "$or_pidfile" "$OR_CMD" "$OR_LOG"+ or_i=0+ while [ ! -s "$OR_DIR/$or_pidfile" ] && [ "$or_i" -lt 50 ]; do sleep 0.1; or_i=$((or_i + 1)); done+ printf 'pid=%s\n' "$(cat "$OR_DIR/$or_pidfile" 2>/dev/null)"+ rm -f "$OR_DIR/$or_pidfile"+ printf '%s:exit=0\n' "$OR_MARK" >&2+ exit 0+fi++# The command gets its own process group (setsid; sh job control needs a tty),+# so a timeout kills everything it started, not just the shell.+# shellcheck disable=SC2086+docker exec -w "$or_wd" $or_envs "$OR_CONTAINER" \+ sh -c 'if command -v setsid >/dev/null 2>&1; then setsid sh -c "$2" < /dev/null & else sh -c "$2" < /dev/null & fi+ p=$!; echo "$p" > "/workspace/$1"; wait "$p"; c=$?; rm -f "/workspace/$1"; exit "$c"' \+ sh "$or_pidfile" "$OR_CMD" < /dev/null &+or_pid=$!+# Inside the container: signal the command's group, or (no setsid in the image)+# walk /proc for its descendants.+or_killer='t=$1; s=$2+kill -"$s" -"$t" 2>/dev/null && exit 0+all=" $t "; more=1+while [ "$more" = 1 ]; do more=0+ for f in /proc/[0-9]*/stat; do+ read -r pid _ _ ppid _ < "$f" 2>/dev/null || continue+ case "$all" in *" $pid "*) continue ;; esac+ case "$all" in *" $ppid "*) all="$all$pid "; more=1 ;; esac+ done+done+kill -"$s" $all 2>/dev/null'++(+ sleep "$OR_TIMEOUT"+ printf '%s:timeout\n' "$OR_MARK" >&2+ or_cpid=$(cat "$OR_DIR/$or_pidfile" 2>/dev/null)+ if [ -n "$or_cpid" ]; then+ docker exec "$OR_CONTAINER" sh -c "$or_killer" sh "$or_cpid" TERM >/dev/null 2>&1+ sleep 3+ docker exec "$OR_CONTAINER" sh -c "$or_killer" sh "$or_cpid" KILL >/dev/null 2>&1+ fi+ or_kill_tree "$or_pid" KILL+) < /dev/null > /dev/null &+or_watch=$!+wait "$or_pid"+or_code=$?+or_kill_tree "$or_watch" KILL+rm -f "$OR_DIR/$or_pidfile"+printf '%s:exit=%s\n' "$OR_MARK" "$or_code" >&2+exit 0diff --git a/src/fleet/workspaces/scripts/files.ps1 b/src/fleet/workspaces/scripts/files.ps1new file mode 100644index 0000000..29ee54a--- /dev/null+++ b/src/fleet/workspaces/scripts/files.ps1@@ -0,0 +1,44 @@+# Reads, writes or lists files in a workspace (Windows, best effort).+# Prepended: $OR_ACTION $OR_DIR $OR_REL $OR_MAX $OR_APPEND $OR_B64 $OR_DEPTH++$ErrorActionPreference = 'Stop'+try { Set-Location -LiteralPath $OR_DIR } catch { [Console]::Error.WriteLine("error: the workspace folder is gone: $OR_DIR"); exit 97 }+$full = if ($OR_REL) { Join-Path $OR_DIR $OR_REL } else { $OR_DIR }++switch ($OR_ACTION) {+ 'read' {+ if (-not (Test-Path -LiteralPath $full)) { [Console]::Error.WriteLine("error: there's no file $OR_REL in the workspace"); exit 3 }+ $item = Get-Item -LiteralPath $full -Force+ if ($item.PSIsContainer) { [Console]::Error.WriteLine("error: $OR_REL is a folder"); exit 3 }+ Write-Output "size=$($item.Length)"+ $stream = [IO.File]::OpenRead($full)+ try {+ $count = [Math]::Min([int64]$OR_MAX, $item.Length)+ $buf = New-Object byte[] $count+ $read = $stream.Read($buf, 0, $count)+ Write-Output ("data=" + [Convert]::ToBase64String($buf, 0, $read))+ } finally { $stream.Dispose() }+ }+ 'write' {+ $parent = Split-Path -Parent $full+ if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }+ $bytes = [Convert]::FromBase64String($OR_B64)+ $mode = if ($OR_APPEND) { [IO.FileMode]::Append } else { [IO.FileMode]::Create }+ $stream = New-Object IO.FileStream($full, $mode)+ try { $stream.Write($bytes, 0, $bytes.Length) } finally { $stream.Dispose() }+ Write-Output "size=$((Get-Item -LiteralPath $full -Force).Length)"+ }+ 'list' {+ if (-not (Test-Path -LiteralPath $full -PathType Container)) { [Console]::Error.WriteLine("error: there's no folder $OR_REL in the workspace"); exit 3 }+ $root = (Get-Item -LiteralPath $full -Force).FullName.TrimEnd('\') + '\'+ Get-ChildItem -LiteralPath $full -Recurse -Depth ([int]$OR_DEPTH - 1) -Force |+ Where-Object { $_.FullName -notmatch '\\(\.git|\.openrunner)(\\|$)' } |+ Select-Object -First 2001 |+ ForEach-Object {+ $kind = if ($_.LinkType) { 'l' } elseif ($_.PSIsContainer) { 'd' } else { 'f' }+ $size = if ($_.PSIsContainer) { 0 } else { $_.Length }+ $rel = $_.FullName.Substring($root.Length).Replace('\', '/')+ Write-Output "$kind`t$size`t$rel"+ }+ }+}diff --git a/src/fleet/workspaces/scripts/files.sh b/src/fleet/workspaces/scripts/files.shnew file mode 100644index 0000000..0b1ab47--- /dev/null+++ b/src/fleet/workspaces/scripts/files.sh@@ -0,0 +1,40 @@+# Reads, writes or lists files in a workspace. Prepended: OR_ACTION OR_DIR OR_REL+# OR_MAX OR_APPEND OR_B64 OR_DEPTH. Paths were validated to stay inside the workspace.++cd "$OR_DIR" 2>/dev/null || { echo "error: the workspace folder is gone: $OR_DIR" >&2; exit 97; }+or_size() { ls -ldn "$1" 2>/dev/null | awk '{ print $5 }'; }++case "$OR_ACTION" in+read)+ [ -e "$OR_REL" ] || { echo "error: there's no file $OR_REL in the workspace" >&2; exit 3; }+ [ -d "$OR_REL" ] && { echo "error: $OR_REL is a folder" >&2; exit 3; }+ printf 'size=%s\n' "$(or_size "$OR_REL")"+ printf 'data='+ head -c "$OR_MAX" "$OR_REL" | base64 | tr -d '\n\r'+ printf '\n'+ ;;+write)+ case "$OR_REL" in */*) mkdir -p "${OR_REL%/*}" || { echo "error: couldn't create the folder for $OR_REL" >&2; exit 3; } ;; esac+ if printf 'YQ==' | base64 -d >/dev/null 2>&1; then or_dec='base64 -d'; else or_dec='base64 -D'; fi+ if [ "$OR_APPEND" = 1 ]; then+ printf '%s' "$OR_B64" | $or_dec >> "$OR_REL" || { echo "error: couldn't write $OR_REL" >&2; exit 3; }+ else+ printf '%s' "$OR_B64" | $or_dec > "$OR_REL" || { echo "error: couldn't write $OR_REL" >&2; exit 3; }+ fi+ printf 'size=%s\n' "$(or_size "$OR_REL")"+ ;;+list)+ or_target=${OR_REL:-.}+ [ -d "$or_target" ] || { echo "error: there's no folder $OR_REL in the workspace" >&2; exit 3; }+ cd "$or_target" || exit 3+ # Lines: kind<TAB>size<TAB>path, kind f (file), d (folder) or l (link).+ if find . -maxdepth 0 -printf '' >/dev/null 2>&1; then+ find . -mindepth 1 -maxdepth "$OR_DEPTH" \( -name .git -o -name .openrunner \) -prune -o -printf '%y\t%s\t%P\n' | head -n 2001+ else+ find . -mindepth 1 -maxdepth "$OR_DEPTH" \( -name .git -o -name .openrunner \) -prune -o -print | head -n 2001 | while IFS= read -r or_p; do+ if [ -L "$or_p" ]; then or_k=l; elif [ -d "$or_p" ]; then or_k=d; else or_k=f; fi+ printf '%s\t%s\t%s\n' "$or_k" "$(or_size "$or_p")" "${or_p#./}"+ done+ fi+ ;;+esacdiff --git a/src/fleet/workspaces/scripts/lib.sh b/src/fleet/workspaces/scripts/lib.shnew file mode 100644index 0000000..8a605c1--- /dev/null+++ b/src/fleet/workspaces/scripts/lib.sh@@ -0,0 +1,19 @@+# Helpers shared by workspace scripts.++# A process and all of its descendants (portable: ps on macOS and Linux).+or_tree() {+ ps -A -o pid= -o ppid= 2>/dev/null | awk -v root="$1" '+ { parent[$1] = $2 }+ END {+ keep[root] = 1; print root; changed = 1+ while (changed) {+ changed = 0+ for (p in parent) if (!(p in keep) && (parent[p] in keep)) { keep[p] = 1; print p; changed = 1 }+ }+ }'+}++# or_kill_tree PID SIGNAL+or_kill_tree() {+ for or_p in $(or_tree "$1"); do kill -"$2" "$or_p" 2>/dev/null; done+}diff --git a/src/fleet/workspaces/scripts/other.ps1 b/src/fleet/workspaces/scripts/other.ps1new file mode 100644index 0000000..51f799e--- /dev/null+++ b/src/fleet/workspaces/scripts/other.ps1@@ -0,0 +1,63 @@+# Create, changes and destroy for Windows workspaces (best effort). $OR_ACTION picks one.+# create: $OR_ROOT $OR_ID $OR_REPO $OR_REPO_SHOWN $OR_REF $OR_BRANCH $OR_AUTH+# changes: $OR_DIR+# destroy: $OR_DIR $OR_ID $OR_PIDS $OR_KEEP++$ErrorActionPreference = 'Continue'+$env:GIT_TERMINAL_PROMPT = '0'+$env:GIT_PAGER = 'cat'++switch ($OR_ACTION) {+ 'create' {+ $root = $OR_ROOT -replace '^~', $HOME+ $dir = Join-Path $root $OR_ID+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ Set-Location -LiteralPath $dir+ Write-Output "path=$((Get-Location).Path)"+ if ($OR_REPO) {+ if (-not (Get-Command git -ErrorAction SilentlyContinue)) { [Console]::Error.WriteLine("error: git isn't installed on $env:COMPUTERNAME"); exit 3 }+ if ($OR_AUTH) { $env:GIT_CONFIG_COUNT = '1'; $env:GIT_CONFIG_KEY_0 = 'http.extraHeader'; $env:GIT_CONFIG_VALUE_0 = $OR_AUTH }+ Get-ChildItem -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue+ Write-Output "Cloning $OR_REPO_SHOWN"+ if ($OR_REF) {+ git clone --depth 1 --branch $OR_REF $OR_REPO . 2>&1 | ForEach-Object { "$_" }+ if ($LASTEXITCODE -ne 0) {+ Get-ChildItem -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue+ git clone $OR_REPO . 2>&1 | ForEach-Object { "$_" }+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine('error: git clone failed'); exit 4 }+ git checkout $OR_REF 2>&1 | ForEach-Object { "$_" }+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("error: couldn't check out $OR_REF"); exit 5 }+ }+ } else {+ git clone --depth 1 $OR_REPO . 2>&1 | ForEach-Object { "$_" }+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine('error: git clone failed'); exit 4 }+ }+ if ($OR_BRANCH) {+ git checkout -b $OR_BRANCH 2>&1 | ForEach-Object { "$_" }+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("error: couldn't create branch $OR_BRANCH"); exit 5 }+ }+ Add-Content -Path '.git\info\exclude' -Value '.openrunner/'+ }+ New-Item -ItemType Directory -Force -Path '.openrunner\logs' | Out-Null+ Write-Output 'ready'+ }+ 'changes' {+ try { Set-Location -LiteralPath $OR_DIR -ErrorAction Stop } catch { [Console]::Error.WriteLine("error: the workspace folder is gone: $OR_DIR"); exit 97 }+ if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Output "git isn't installed on this machine, so there's no change tracking."; exit 0 }+ git rev-parse --is-inside-work-tree 2>$null | Out-Null+ if ($LASTEXITCODE -ne 0) { Write-Output "This workspace isn't a git checkout, so there's nothing to diff."; exit 0 }+ Write-Output '## git status'+ git status --short --branch+ Write-Output ''+ Write-Output '## git diff'+ git --no-pager diff --no-color HEAD+ }+ 'destroy' {+ foreach ($p in ($OR_PIDS -split ' ' | Where-Object { $_ })) {+ if (Get-Process -Id $p -ErrorAction SilentlyContinue) { taskkill /PID $p /T /F | Out-Null; Write-Output "Stopped background process $p" }+ }+ if ($OR_KEEP) { Write-Output "Kept the files in $OR_DIR"; exit 0 }+ if (-not $OR_DIR.TrimEnd('\').EndsWith("\$OR_ID")) { [Console]::Error.WriteLine("error: refusing to delete $OR_DIR"); exit 3 }+ if (Test-Path -LiteralPath $OR_DIR) { Remove-Item -LiteralPath $OR_DIR -Recurse -Force; Write-Output "Deleted $OR_DIR" } else { Write-Output "$OR_DIR was already gone" }+ }+}diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rsnew file mode 100644index 0000000..a4cd1dc--- /dev/null+++ b/src/fleet/workspaces/tests.rs@@ -0,0 +1,610 @@+use std::path::{Path, PathBuf};++use super::*;+use crate::config::Paths;+use crate::fleet::model::{Probe, RunnerSummary};++#[test]+fn keeps_paths_inside_the_workspace() {+ assert_eq!(rel_path("").unwrap(), "");+ assert_eq!(rel_path("./src//lib.rs").unwrap(), "src/lib.rs");+ assert_eq!(rel_path("a\\b").unwrap(), "a/b");+ for bad in ["/etc/passwd", "~/x", "../x", "a/../../b", "C:\\Windows", "\\\\server\\x"] {+ assert!(rel_path(bad).is_err(), "{bad} should be rejected");+ }+}++#[test]+fn validates_env_and_refs() {+ assert!(validate_env("NODE_ENV", "test").is_ok());+ assert!(validate_env("_X1", "").is_ok());+ assert!(validate_env("1X", "a").is_err());+ assert!(validate_env("A-B", "a").is_err());+ assert!(validate_git_ref("main").is_ok());+ assert!(validate_git_ref("fix/flaky-e2e").is_ok());+ assert!(validate_git_ref("v2.4.0").is_ok());+ for bad in ["-x", "a..b", "a b", "x~1", "x:y", "feat/"] {+ assert!(validate_git_ref(bad).is_err(), "{bad}");+ }+}++#[test]+fn normalizes_repos() {+ let r = normalize_repo("acme/api", "github.com").unwrap();+ assert_eq!(r.url, "https://github.com/acme/api.git");+ assert_eq!((r.shown.as_str(), r.short_name.as_str(), r.on_github), ("acme/api", "api", true));+ let r = normalize_repo("https://x:[email protected]/acme/api.git", "github.com").unwrap();+ assert_eq!(r.shown, "https://github.com/acme/api.git");+ assert!(r.on_github && !r.shown.contains("secret"));+ let r = normalize_repo("[email protected]:acme/api.git", "github.com").unwrap();+ assert!(!r.on_github, "ssh remotes use the machine's own keys");+ assert_eq!(r.short_name, "api");+ assert_eq!(normalize_repo("/srv/git/tool.git", "github.com").unwrap().short_name, "tool");+ assert!(normalize_repo("--upload-pack=x", "github.com").is_err());+ assert!(normalize_repo("just-a-word", "github.com").is_err());+ assert_eq!(github_web_host("https://ghe.acme.internal/api/v3"), "ghe.acme.internal");+}++fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, allowed: bool, status: &str) -> Machine {+ Machine {+ id: id.into(),+ name: id.into(),+ host: id.into(),+ local: false,+ platform: platform.into(),+ kind: "runner".into(),+ status: status.into(),+ checking: false,+ notes: None,+ runner_ids: Vec::new(),+ summary: RunnerSummary { total: 2, working, idle: 2 - working.min(2), offline: 0, unknown: 0 },+ probe: Some(Probe {+ checked_at: Utc::now(),+ duration_ms: 10,+ ok: true,+ error: None,+ hostname: None,+ os: None,+ arch: None,+ os_version: None,+ cores: Some(8),+ cpu_pct: Some(cpu),+ mem_total: Some(100),+ mem_used: Some(40),+ disk_total: Some(1_000_000_000_000),+ disk_free: Some(disk_free),+ disk_path: None,+ uptime_sec: None,+ load: Vec::new(),+ docker: None,+ sudo: None,+ }),+ diagnostics: Vec::new(),+ workspaces_allowed: allowed,+ }+}++#[test]+fn picks_the_quietest_matching_machine() {+ let machines = vec![+ machine("busy-linux", "linux-x64", 70.0, 2, 500_000_000_000, true, "online"),+ machine("quiet-linux", "linux-x64", 5.0, 0, 500_000_000_000, true, "online"),+ machine("quiet-mac", "darwin-arm64", 1.0, 0, 500_000_000_000, true, "online"),+ machine("full-disk", "linux-x64", 0.0, 0, 1_000_000_000, true, "online"),+ machine("forbidden", "linux-x64", 0.0, 0, 500_000_000_000, false, "online"),+ machine("asleep", "linux-x64", 0.0, 0, 500_000_000_000, true, "offline"),+ ];+ assert_eq!(pick_machine(&machines, None).unwrap().id, "quiet-mac");+ assert_eq!(pick_machine(&machines, Some("linux")).unwrap().id, "quiet-linux");+ assert_eq!(pick_machine(&machines, Some("macos")).unwrap().id, "quiet-mac");+ assert_eq!(pick_machine(&machines, Some("Linux_x86_64")).unwrap().id, "quiet-linux");+ // Docker workspaces prefer machines whose check found docker.+ let mut with_docker = machines.clone();+ if let Some(p) = with_docker.iter_mut().find(|m| m.id == "quiet-linux").and_then(|m| m.probe.as_mut()) {+ p.docker = Some("29.8.1".into());+ }+ assert_eq!(pick_machine_for(&with_docker, None, true).unwrap().id, "quiet-linux");+ assert_eq!(pick_machine_for(&machines, None, true).unwrap().id, "quiet-mac", "no docker info anywhere: any machine");+ let err = pick_machine(&machines, Some("windows")).unwrap_err();+ assert!(err.contains("windows") && err.contains("forbidden (linux-x64, workspaces off)"), "{err}");+}++#[test]+fn quotes_env_and_builds_commands() {+ let env = vec![("MSG".to_string(), "it's \"fine\" $HOME".to_string())];+ assert_eq!(env_exports(Shell::Sh, &env), "export MSG='it'\\''s \"fine\" $HOME'\n");+ assert_eq!(env_exports(Shell::Powershell, &env), "$env:MSG = 'it''s \"fine\" $HOME'\n");++ let spec: MachineSpec = toml::from_str("name = \"Box\"\nhost = \"ci@box\"\nport = 2222\nssh_options = [\"-i\", \"~/.ssh/ci key\"]").unwrap();+ let shell = shell_command(&spec, "/home/ci/openrunner/workspaces/ws-abc123", false);+ assert_eq!(shell, "ssh -t -p 2222 -i '~/.ssh/ci key' ci@box \"cd '/home/ci/openrunner/workspaces/ws-abc123' && exec \\$SHELL -l\"");+ let local: MachineSpec = toml::from_str("name = \"Here\"\nhost = \"local\"").unwrap();+ assert_eq!(shell_command(&local, "/tmp/w/ws-1", false), "cd '/tmp/w/ws-1' && exec \"$SHELL\" -l");++ let args = rsync_args(&spec, "/w/ws-1", "/src/app/", SyncDirection::Push, true);+ assert!(args.contains(&"--delete".to_string()) && args.contains(&"--exclude=/.openrunner/".to_string()));+ assert_eq!(&args[args.len() - 2..], &["/src/app/".to_string(), "ci@box:/w/ws-1/".to_string()]);+ let e = args.iter().position(|a| a == "-e").unwrap();+ assert!(args[e + 1].starts_with("ssh -T -o BatchMode=yes") && args[e + 1].ends_with("-i '~/.ssh/ci key'"), "{}", args[e + 1]);+ let pull = rsync_args(&local, "/w/ws-1", "/dst", SyncDirection::Pull, false);+ assert_eq!(&pull[pull.len() - 2..], &["/w/ws-1/".to_string(), "/dst/".to_string()]);+ assert!(!pull.contains(&"-e".to_string()));+}++#[test]+fn parses_script_output() {+ assert_eq!(field("noise\nsize=12\ndata=abc\n", "size").as_deref(), Some("12"));+ let entries = parse_listing("d\t4096\tsrc\nf\t120\tsrc/main.rs\nl\t9\tlatest\n", "app");+ assert_eq!(entries.len(), 3);+ assert_eq!((entries[0].path.as_str(), entries[0].kind.as_str(), entries[0].size), ("app/src", "dir", 0));+ assert_eq!((entries[1].path.as_str(), entries[1].size), ("app/src/main.rs", 120));+ assert_eq!(entries[2].kind, "link");++ let tail = output_tail(&(0..40).map(|i| format!("out {i}")).collect::<Vec<_>>().join("\n"), "err!");+ assert_eq!(tail.len(), registry::TAIL_LINES);+ assert_eq!(tail.last().unwrap(), "err!");++ let text = file_content("a.txt".into(), "héllo".as_bytes()[..2].to_vec(), 6, 2);+ assert!(text.truncated && !text.binary && text.content == "h", "a cut inside a character keeps the valid prefix");+ let bin = file_content("a.bin".into(), vec![0x89, b'P', b'N', b'G', 0, 1], 6, 100);+ assert!(bin.binary && bin.content.is_empty());+ assert!(random_id(6).chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));+ assert_ne!(random_id(8), random_id(8));+}++#[tokio::test(flavor = "multi_thread")]+async fn demo_flow() {+ let dir = std::env::temp_dir().join(format!("openrunner-ws-demo-{}", std::process::id()));+ let engine = Engine::new(Paths::resolve(Some(dir.clone()), None), true);+ engine.run_check(None).await;+ assert_eq!(engine.workspaces().len(), 3, "demo seeds three workspaces");+ assert!(engine.workspaces().iter().any(|w| w.isolation == "docker" && w.image.as_deref() == Some("node:22")), "one is a container");+ assert!(!dir.join("workspaces.json").exists(), "demo never writes to disk");++ let info = engine+ .create_workspace(CreateWorkspace {+ platform: Some("linux".into()),+ repo: Some("acme/api".into()),+ branch: Some("agent/try-fix".into()),+ owner: Some("test-agent".into()),+ ..Default::default()+ })+ .await+ .unwrap();+ assert_eq!(info.status, "ready");+ assert!(info.platform.starts_with("linux"), "{info:?}");+ assert!(info.shell.starts_with("ssh -t"), "{}", info.shell);++ let r = engine.workspace_exec(&info.id, "pwd", ExecOptions::default()).await.unwrap();+ assert_eq!((r.exit_code, r.stdout.as_str()), (Some(0), info.path.as_str()));+ engine.workspace_write_file(&info.id, "notes/plan.md", "1. fix it\n", false).await.unwrap();+ let size = engine.workspace_write_file(&info.id, "notes/plan.md", "2. test it\n", true).await.unwrap();+ assert_eq!(size, 21);+ let f = engine.workspace_read_file(&info.id, "notes/plan.md", 0).await.unwrap();+ assert_eq!(f.content, "1. fix it\n2. test it\n");+ let files = engine.workspace_list_files(&info.id, "", 1).await.unwrap();+ assert!(files.iter().any(|e| e.path == "notes" && e.kind == "dir"), "{files:?}");+ assert!(files.iter().any(|e| e.path == "package.json"), "{files:?}");+ let changes = engine.workspace_changes(&info.id).await.unwrap();+ assert!(changes.contains("?? notes/plan.md"), "{changes}");+ let bg = engine.workspace_exec(&info.id, "npm run dev", ExecOptions { background: true, ..Default::default() }).await.unwrap();+ assert!(bg.background_pid.is_some() && bg.log_path.as_deref() == Some(".openrunner/logs/1.log"));++ let ws = engine.workspaces().into_iter().find(|w| w.id == info.id).unwrap();+ assert_eq!(ws.commands, 2);+ assert_eq!(ws.history[0].command, "pwd");+ assert!(engine.workspace_exec(&info.id, "ls", ExecOptions { cwd: Some("../..".into()), ..Default::default() }).await.is_err());++ // The asleep laptop can't host one; workspaces can be turned off per machine.+ let err = engine.create_workspace(CreateWorkspace { machine: Some("laravel-macbook".into()), ..Default::default() }).await.unwrap_err();+ assert!(err.contains("unreachable"), "{err}");+ engine.set_workspaces_allowed("ubuntu-nuc", false).unwrap();+ let err = engine.create_workspace(CreateWorkspace { machine: Some("ubuntu-nuc".into()), ..Default::default() }).await.unwrap_err();+ assert!(err.contains("turned off"), "{err}");+ engine.set_workspaces_allowed("ubuntu-nuc", true).unwrap();++ engine.destroy_workspace(&info.id, false).await.unwrap();+ assert!(!engine.workspaces().iter().any(|w| w.id == info.id));+ let err = engine.workspace_exec(&info.id, "pwd", ExecOptions::default()).await.unwrap_err();+ assert!(err.contains("not found"), "{err}");+}++// ---------------------------------------------------------------------------+// A real workspace on this computer (host = "local"), in a temp dir.++fn git(dir: &Path, args: &[&str]) {+ let out = std::process::Command::new("git").args(args).current_dir(dir).output().expect("git runs");+ assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));+}++/// A bare repo with one commit on `main` and a `feature` branch.+fn bare_repo(tmp: &Path) -> PathBuf {+ let src = tmp.join("src-repo");+ std::fs::create_dir_all(&src).unwrap();+ git(&src, &["init", "-q", "-b", "main"]);+ std::fs::write(src.join("README.md"), "# tool\n").unwrap();+ git(&src, &["-c", "user.email=t@t", "-c", "user.name=t", "add", "."]);+ git(&src, &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "-m", "first"]);+ git(&src, &["branch", "feature"]);+ let bare = tmp.join("tool.git");+ git(tmp, &["clone", "-q", "--bare", src.to_str().unwrap(), bare.to_str().unwrap()]);+ bare+}++fn alive(pid: u32) -> bool {+ std::process::Command::new("kill")+ .args(["-0", &pid.to_string()])+ .stderr(std::process::Stdio::null())+ .status()+ .is_ok_and(|s| s.success())+}++#[cfg(unix)]+#[tokio::test(flavor = "multi_thread")]+async fn local_end_to_end() {+ let tmp = std::env::temp_dir().join(format!("openrunner-ws-local-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).unwrap();+ let tmp = tmp.canonicalize().unwrap();+ let root = tmp.join("workspaces");+ std::fs::write(+ tmp.join("fleet.toml"),+ format!("[[machine]]\nname = \"Here\"\nhost = \"local\"\nworkspace_root = \"{}\"\n", root.display()),+ )+ .unwrap();+ let repo = bare_repo(&tmp);+ let paths = Paths::resolve(Some(tmp.clone()), None);+ let engine = Engine::new(paths.clone(), false);+ engine.run_check(None).await;++ let info = engine+ .create_workspace(CreateWorkspace {+ machine: Some("here".into()),+ repo: Some(repo.display().to_string()),+ git_ref: Some("feature".into()),+ branch: Some("agent/work".into()),+ owner: Some("test".into()),+ ..Default::default()+ })+ .await+ .unwrap();+ assert_eq!(info.status, "ready");+ assert_eq!(info.name, "tool");+ assert_eq!(Path::new(&info.path), root.join(&info.id));+ assert!(root.join(&info.id).join("README.md").exists());++ // Another process (an agent's MCP server) sees it right away.+ let other = Engine::new(paths.clone(), false);+ assert!(other.workspaces().iter().any(|w| w.id == info.id));++ // stdout, stderr and the exit code come back separately; quoting survives.+ let r = engine+ .workspace_exec(&info.id, "echo \"hi $GREETING\"; echo oops >&2; git branch --show-current; exit 3", ExecOptions {+ env: vec![("GREETING".into(), "it's me".into())],+ by: Some("test".into()),+ ..Default::default()+ })+ .await+ .unwrap();+ assert_eq!(r.exit_code, Some(3), "{r:?}");+ assert_eq!(r.stdout, "hi it's me\nagent/work");+ assert_eq!(r.stderr, "oops");++ // cwd and OPENRUNNER_WORKSPACE.+ std::fs::create_dir_all(root.join(&info.id).join("sub")).unwrap();+ let r = other.workspace_exec(&info.id, "basename \"$PWD\"; echo $OPENRUNNER_WORKSPACE", ExecOptions { cwd: Some("sub".into()), ..Default::default() }).await.unwrap();+ assert_eq!(r.stdout, format!("sub\n{}", info.id));++ // A timeout kills the whole tree, not just the shell.+ let r = engine+ .workspace_exec(&info.id, "sleep 30 & echo $! > child.pid; wait", ExecOptions { timeout_secs: Some(1), ..Default::default() })+ .await+ .unwrap();+ assert!(r.timed_out && r.exit_code.is_none(), "{r:?}");+ let child: u32 = std::fs::read_to_string(root.join(&info.id).join("child.pid")).unwrap().trim().parse().unwrap();+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert!(!alive(child), "the timed-out command's child was killed");++ // Background commands keep running until the workspace is destroyed.+ let bg = engine.workspace_exec(&info.id, "echo started; sleep 300", ExecOptions { background: true, ..Default::default() }).await.unwrap();+ let pid = bg.background_pid.expect("pid");+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(alive(pid));+ let log = engine.workspace_read_file(&info.id, bg.log_path.as_deref().unwrap(), 0).await.unwrap();+ assert_eq!(log.content.trim(), "started");++ // Files.+ engine.workspace_write_file(&info.id, "src/a.txt", "line 1\n", false).await.unwrap();+ assert_eq!(engine.workspace_write_file(&info.id, "src/a.txt", "line 2\n", true).await.unwrap(), 14);+ let f = engine.workspace_read_file(&info.id, "src/a.txt", 0).await.unwrap();+ assert_eq!((f.content.as_str(), f.size, f.truncated), ("line 1\nline 2\n", 14, false));+ let f = engine.workspace_read_file(&info.id, "src/a.txt", 3).await.unwrap();+ assert_eq!((f.content.as_str(), f.truncated), ("lin", true));+ assert!(engine.workspace_read_file(&info.id, "missing.txt", 0).await.unwrap_err().contains("no file"));+ assert!(engine.workspace_read_file(&info.id, "../../etc/passwd", 0).await.is_err());+ let list = engine.workspace_list_files(&info.id, "", 2).await.unwrap();+ assert!(list.iter().any(|e| e.path == "src/a.txt" && e.kind == "file" && e.size == 14), "{list:?}");+ assert!(list.iter().any(|e| e.path == "src" && e.kind == "dir"));+ assert!(!list.iter().any(|e| e.path.starts_with(".git") || e.path.starts_with(".openrunner")), "{list:?}");++ // Changes.+ std::fs::write(root.join(&info.id).join("README.md"), "# tool\nedited\n").unwrap();+ let changes = engine.workspace_changes(&info.id).await.unwrap();+ assert!(changes.contains("## agent/work") && changes.contains(" M README.md") && changes.contains("+edited"), "{changes}");++ // Sync both ways (when rsync is around).+ if std::process::Command::new("rsync").arg("--version").output().is_ok_and(|o| o.status.success()) {+ let local = tmp.join("local-copy");+ let summary = engine.workspace_sync(&info.id, local.to_str().unwrap(), SyncDirection::Pull, false).await.unwrap();+ assert!(local.join("README.md").exists(), "{summary}");+ assert!(!local.join(".openrunner").exists(), "OpenRunner's own folder isn't synced");+ std::fs::write(local.join("pushed.txt"), "from local\n").unwrap();+ engine.workspace_sync(&info.id, local.to_str().unwrap(), SyncDirection::Push, false).await.unwrap();+ assert!(root.join(&info.id).join("pushed.txt").exists());+ }++ let ws = engine.workspaces().into_iter().find(|w| w.id == info.id).unwrap();+ assert_eq!(ws.commands, 4);+ assert_eq!(ws.history[0].exit_code, Some(3));+ assert!(ws.history[0].output_tail.contains(&"oops".to_string()));+ assert!(ws.history[2].timed_out);+ assert!(ws.history[3].background);++ // Destroy stops background commands and deletes the folder.+ other.destroy_workspace(&info.id, false).await.unwrap();+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(!alive(pid), "background command stopped");+ assert!(!root.join(&info.id).exists());+ engine.refresh_from_disk();+ assert!(engine.workspaces().is_empty());++ // A bad repo fails cleanly and stays listed as failed until destroyed.+ let err = engine+ .create_workspace(CreateWorkspace { machine: Some("here".into()), repo: Some(tmp.join("nope.git").display().to_string()), ..Default::default() })+ .await+ .unwrap_err();+ assert!(err.contains("clone"), "{err}");+ let failed = engine.workspaces();+ assert_eq!(failed.len(), 1);+ assert_eq!(failed[0].status, "failed");+ assert!(root.join(&failed[0].id).exists(), "the partial folder is recorded");+ assert!(engine.workspace_exec(&failed[0].id, "pwd", ExecOptions::default()).await.unwrap_err().contains("failed to set up"));+ engine.destroy_workspace(&failed[0].id, false).await.unwrap();+ assert!(!root.join(&failed[0].id).exists(), "destroy cleans up the partial folder");++ let _ = std::fs::remove_dir_all(&tmp);+}++// ---------------------------------------------------------------------------+// Docker isolation++#[test]+fn docker_names_images_and_commands() {+ assert_eq!(container_name("ws-7f3a2c"), "openrunner-ws-7f3a2c");+ for ok in ["node:22", "rust:1", "python:3.13-slim", "ghcr.io/acme/dev:latest", "busybox@sha256:abc123"] {+ assert_eq!(validate_image(ok).unwrap(), ok);+ }+ for bad in ["", "-it", "node 22", "node;rm -rf /", "$(id)", ":tag", "../x"] {+ assert!(validate_image(bad).is_err(), "{bad:?}");+ }+ let script = create_script(true);+ let check = script.find("or_docker_check || exit 6").unwrap();+ let clone = script.find("git clone").unwrap();+ let up = script.find("or_docker_up \"$(pwd -P)\"").unwrap();+ assert!(check < clone && clone < up, "docker is checked before cloning and started after");+ assert!(!create_script(false).contains("or_docker"));++ let spec: MachineSpec = toml::from_str("name = \"Box\"\nhost = \"beelink\"\nport = 2222").unwrap();+ let shell = docker_shell_command(&spec, "openrunner-ws-abc");+ assert!(shell.starts_with("ssh -t -p 2222 beelink \"docker start openrunner-ws-abc"), "{shell}");+ assert!(shell.contains("docker exec -it -w /workspace openrunner-ws-abc"), "{shell}");+ let local: MachineSpec = toml::from_str("name = \"Here\"\nhost = \"local\"").unwrap();+ assert!(docker_shell_command(&local, "openrunner-ws-abc").starts_with("docker start"));+}++#[tokio::test(flavor = "multi_thread")]+async fn demo_docker_flow() {+ let dir = std::env::temp_dir().join(format!("openrunner-ws-demo-docker-{}", std::process::id()));+ let engine = Engine::new(Paths::resolve(Some(dir), None), true);+ engine.run_check(None).await;+ let docker = |image: Option<&str>| WorkspaceIsolation { isolation: Some("docker".into()), image: image.map(str::to_string), docker_socket: false };++ let info = engine+ .create_workspace_with(CreateWorkspace { machine: Some("ubuntu-nuc".into()), repo: Some("acme/web".into()), ..Default::default() }, docker(Some("node:22")))+ .await+ .unwrap();+ assert_eq!((info.isolation.as_str(), info.image.as_deref()), ("docker", Some("node:22")));+ assert_eq!(info.container.as_deref(), Some(container_name(&info.id).as_str()));+ assert!(info.shell.contains("docker exec -it -w /workspace"), "{}", info.shell);+ let r = engine.workspace_exec(&info.id, "pwd", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "/workspace", "commands run inside the container");++ // The default image, and the validation errors agents can hit.+ let plain = engine.create_workspace_with(CreateWorkspace { machine: Some("ubuntu-nuc".into()), ..Default::default() }, docker(None)).await.unwrap();+ assert_eq!(plain.image.as_deref(), Some(DEFAULT_IMAGE));+ let err = engine+ .create_workspace_with(CreateWorkspace::default(), WorkspaceIsolation { isolation: Some("vm".into()), ..Default::default() })+ .await+ .unwrap_err();+ assert!(err.contains("isn't an isolation"), "{err}");+ let err = engine+ .create_workspace_with(CreateWorkspace::default(), WorkspaceIsolation { image: Some("node:22".into()), ..Default::default() })+ .await+ .unwrap_err();+ assert!(err.contains("only applies to docker"), "{err}");+ let err = engine.create_workspace_with(CreateWorkspace::default(), docker(Some("node 22"))).await.unwrap_err();+ assert!(err.contains("isn't a docker image"), "{err}");+ let err = engine.create_workspace_with(CreateWorkspace { machine: Some("windows-nuc".into()), ..Default::default() }, docker(None)).await.unwrap_err();+ assert!(err.contains("Windows"), "{err}");++ engine.destroy_workspace(&info.id, false).await.unwrap();+ engine.destroy_workspace(&plain.id, false).await.unwrap();+}++/// A real container workspace on this computer. Needs docker (and pulls+/// busybox); run with `cargo test -- --ignored local_docker`.+#[cfg(unix)]+#[ignore]+#[tokio::test(flavor = "multi_thread")]+async fn local_docker_end_to_end() {+ let docker_ok = std::process::Command::new("docker").args(["info", "--format", "{{.ServerVersion}}"]).output().is_ok_and(|o| o.status.success());+ if !docker_ok {+ eprintln!("skipping: docker isn't available here");+ return;+ }+ let tmp = std::env::temp_dir().join(format!("openrunner-ws-docker-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).unwrap();+ let tmp = tmp.canonicalize().unwrap();+ let root = tmp.join("workspaces");+ std::fs::write(tmp.join("fleet.toml"), format!("[[machine]]\nname = \"Here\"\nhost = \"local\"\nworkspace_root = \"{}\"\n", root.display())).unwrap();+ let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);+ engine.run_check(None).await;+ let info = engine+ .create_workspace_with(+ CreateWorkspace { machine: Some("here".into()), ..Default::default() },+ WorkspaceIsolation { isolation: Some("docker".into()), image: Some("busybox:1.36".into()), docker_socket: false },+ )+ .await+ .unwrap();+ let container = info.container.clone().unwrap();++ let r = engine.workspace_exec(&info.id, "pwd; id -u; echo $GREETING > made.txt", ExecOptions { env: vec![("GREETING".into(), "hi".into())], ..Default::default() }).await.unwrap();+ assert_eq!(r.exit_code, Some(0), "{r:?}");+ assert!(r.stdout.starts_with("/workspace"), "{r:?}");+ let me = String::from_utf8(std::process::Command::new("id").arg("-u").output().unwrap().stdout).unwrap();+ assert!(r.stdout.contains(me.trim()), "runs as the host user: {r:?}");+ assert_eq!(std::fs::read_to_string(root.join(&info.id).join("made.txt")).unwrap(), "hi\n", "the folder is mounted");++ let r = engine.workspace_exec(&info.id, "exit 7", ExecOptions::default()).await.unwrap();+ assert_eq!(r.exit_code, Some(7));+ let r = engine.workspace_exec(&info.id, "sleep 60", ExecOptions { timeout_secs: Some(2), ..Default::default() }).await.unwrap();+ assert!(r.timed_out, "{r:?}");+ let ps = std::process::Command::new("docker").args(["exec", &container, "ps"]).output().unwrap();+ assert!(!String::from_utf8_lossy(&ps.stdout).contains("sleep 60"), "the timed-out command died inside the container");++ // A missing container is recreated on the next command.+ std::process::Command::new("docker").args(["rm", "-f", &container]).output().unwrap();+ let r = engine.workspace_exec(&info.id, "cat made.txt", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "hi");++ engine.destroy_workspace(&info.id, false).await.unwrap();+ let gone = std::process::Command::new("docker").args(["inspect", &container]).output().unwrap();+ assert!(!gone.status.success(), "the container was removed");+ assert!(!root.join(&info.id).exists());+ let _ = std::fs::remove_dir_all(&tmp);+}++/// The full docker flow on a real remote machine over ssh. Set+/// OPENRUNNER_TEST_DOCKER_HOST to an ssh destination with docker (it pulls+/// node:22) and run `cargo test -- --ignored remote_docker`.+#[cfg(unix)]+#[ignore]+#[tokio::test(flavor = "multi_thread")]+async fn remote_docker_end_to_end() {+ let Ok(host) = std::env::var("OPENRUNNER_TEST_DOCKER_HOST") else {+ eprintln!("skipping: set OPENRUNNER_TEST_DOCKER_HOST");+ return;+ };+ let ssh = |cmd: &str| {+ let out = std::process::Command::new("ssh").args(["-o", "BatchMode=yes", &host, cmd]).output().unwrap();+ (out.status.success(), String::from_utf8_lossy(&out.stdout).trim().to_string())+ };+ let tmp = std::env::temp_dir().join(format!("openrunner-ws-remote-docker-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).unwrap();+ std::fs::write(+ tmp.join("fleet.toml"),+ format!("[[machine]]\nname = \"Remote\"\nhost = \"{host}\"\nworkspace_root = \"~/openrunner-test/workspaces\"\n"),+ )+ .unwrap();+ let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);+ engine.run_check(None).await;++ let info = engine+ .create_workspace_with(+ CreateWorkspace { machine: Some("remote".into()), repo: Some("octocat/Hello-World".into()), owner: Some("test".into()), ..Default::default() },+ WorkspaceIsolation { isolation: Some("docker".into()), image: Some("node:22".into()), docker_socket: false },+ )+ .await+ .unwrap();+ let container = info.container.clone().unwrap();+ assert_eq!(info.status, "ready");+ let (running, _) = ssh(&format!("docker inspect -f '{{{{.State.Running}}}}' {container}"));+ assert!(running, "the container is up");++ // Inside the container: node, git on the clone, the host user's uid, /workspace.+ let r = engine.workspace_exec(&info.id, "node -v; git status --short --branch; id -u; pwd", ExecOptions::default()).await.unwrap();+ assert_eq!(r.exit_code, Some(0), "{r:?}");+ assert!(r.stdout.starts_with("v22."), "{r:?}");+ assert!(r.stdout.contains("## master") && r.stdout.ends_with("/workspace"), "{r:?}");+ let (_, uid) = ssh("id -u");+ assert!(r.stdout.contains(&format!("\n{uid}\n")), "runs as the ssh user: {r:?}");++ // A background server, reached from inside the container.+ let bg = engine+ .workspace_exec(&info.id, "node -e \"require('http').createServer((q,s)=>s.end('pong')).listen(8765)\"", ExecOptions { background: true, ..Default::default() })+ .await+ .unwrap();+ assert!(bg.background_pid.is_some() && bg.log_path.is_some(), "{bg:?}");+ tokio::time::sleep(Duration::from_millis(1500)).await;+ let r = engine.workspace_exec(&info.id, "curl -s http://127.0.0.1:8765/", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "pong", "{r:?}");++ // A timeout kills the command inside the container, children included.+ let r = engine.workspace_exec(&info.id, "sh -c 'sleep 61' & sleep 62; wait", ExecOptions { timeout_secs: Some(2), ..Default::default() }).await.unwrap();+ assert!(r.timed_out && r.exit_code.is_none(), "{r:?}");+ tokio::time::sleep(Duration::from_millis(500)).await;+ let r = engine+ .workspace_exec(&info.id, "for p in /proc/[0-9]*; do tr '\\0' ' ' < $p/cmdline 2>/dev/null; echo; done | grep -c '^sleep 6[12]' || true", ExecOptions::default())+ .await+ .unwrap();+ assert_eq!(r.stdout.trim(), "0", "nothing left running: {r:?}");++ // Files (through the host path) and git changes.+ engine.workspace_write_file(&info.id, "notes/plan.md", "1. fix it\n", false).await.unwrap();+ let r = engine.workspace_exec(&info.id, "cat notes/plan.md", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "1. fix it");+ let (_, owner) = ssh(&format!("stat -c %U {}/notes/plan.md", info.path));+ let (_, me) = ssh("id -un");+ assert_eq!(owner, me, "files aren't root-owned");+ engine.workspace_exec(&info.id, "echo 'from the container' >> README", ExecOptions::default()).await.unwrap();+ let changes = engine.workspace_changes(&info.id).await.unwrap();+ assert!(changes.contains("+from the container"), "{changes}");++ // Sync both ways.+ let local = tmp.join("local");+ engine.workspace_sync(&info.id, local.to_str().unwrap(), SyncDirection::Pull, false).await.unwrap();+ assert!(local.join("README").exists());+ std::fs::write(local.join("pushed.txt"), "from my laptop\n").unwrap();+ engine.workspace_sync(&info.id, local.to_str().unwrap(), SyncDirection::Push, false).await.unwrap();+ let r = engine.workspace_exec(&info.id, "cat pushed.txt", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "from my laptop");++ // The container disappears (reboot, prune): the next command brings it back.+ ssh(&format!("docker rm -f {container}"));+ let r = engine.workspace_exec(&info.id, "cat notes/plan.md", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "1. fix it", "{r:?}");++ // Destroy removes the container and the folder.+ engine.destroy_workspace(&info.id, false).await.unwrap();+ let (exists, _) = ssh(&format!("docker inspect {container}"));+ assert!(!exists, "container removed");+ let (folder, _) = ssh(&format!("test -e {}", info.path));+ assert!(!folder, "folder removed");++ // docker_socket shares the host's docker with the (non-root) container user.+ let dind = engine+ .create_workspace_with(+ CreateWorkspace { machine: Some("remote".into()), ..Default::default() },+ WorkspaceIsolation { isolation: Some("docker".into()), image: Some("node:22".into()), docker_socket: true },+ )+ .await+ .unwrap();+ let r = engine.workspace_exec(&dind.id, "test -S /var/run/docker.sock && test -w /var/run/docker.sock && echo writable", ExecOptions::default()).await.unwrap();+ assert_eq!(r.stdout, "writable", "{r:?}");+ engine.destroy_workspace(&dind.id, false).await.unwrap();++ ssh("rmdir ~/openrunner-test/workspaces ~/openrunner-test 2>/dev/null");+ let _ = std::fs::remove_dir_all(&tmp);+}diff --git a/src/fleet/workspaces/transport.rs b/src/fleet/workspaces/transport.rsnew file mode 100644index 0000000..17182b7--- /dev/null+++ b/src/fleet/workspaces/transport.rs@@ -0,0 +1,426 @@+//! Runs workspace scripts on a machine. Unlike machine checks, these run in the+//! user's *login* shell, so Homebrew, nvm, asdf and friends are on PATH just as+//! in their own terminal.+//!+//! Login profiles may print things, so every script first prints a random+//! marker on both streams and everything before it is dropped. Scripts report+//! the command's exit status as `<marker>:exit=N` on stderr, which can't be+//! confused with ssh's own exit codes.++use std::collections::VecDeque;+use std::process::Stdio;+use std::time::Duration;++use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};+use tokio::process::Command;++use crate::config::MachineSpec;+use crate::ops::remote::clean_line;+use crate::probe;++/// sh-family login shells read the script from stdin as a login shell; anything+/// else (fish, nushell, xonsh) falls back to a login `sh`. Valid in every one+/// of those shells, since ssh hands the remote command to the user's shell.+const LOGIN_WRAPPER: &str =+ r#"case "$SHELL" in */bash|*/zsh|*/sh|*/ksh|*/dash) exec "$SHELL" -l -s;; *) exec sh -l -s;; esac"#;+const PS_READ_STDIN: &str = "[Console]::In.ReadToEnd() | Invoke-Expression";+/// After the script reports its exit status, give stragglers holding the+/// output pipes (a server the command left running) this long, then hang up.+const AFTER_EXIT_GRACE: Duration = Duration::from_secs(2);++/// How much output to keep. The middle of anything longer is dropped.+#[derive(Clone, Copy)]+pub struct Limits {+ pub head: usize,+ pub tail: usize,+ /// Longer lines are cut.+ pub line: usize,+}++impl Limits {+ pub const OUTPUT: Limits = Limits { head: 16 * 1024, tail: 48 * 1024, line: 16 * 1024 };+ pub const DATA: Limits = Limits { head: 8 * 1024 * 1024, tail: 0, line: 8 * 1024 * 1024 };+}++#[derive(Debug, Default)]+pub struct Output {+ pub stdout: String,+ pub stderr: String,+ /// The process's own exit status (ssh or the local shell).+ pub status: Option<i32>,+ /// From `<marker>:exit=N`, when the script reports it.+ pub exit: Option<i32>,+ pub timed_out: bool,+ pub truncated: bool,+ /// The script started (the marker came through).+ pub started: bool,+ /// stderr from before the script started: ssh errors, broken profiles.+ pub preamble: String,+}++impl Output {+ /// A short reason for a failure: the script's `error: ...` line, else the last stderr lines.+ pub fn reason(&self) -> String {+ let lines: Vec<&str> = self.stderr.lines().chain(self.preamble.lines()).map(str::trim).filter(|l| !l.is_empty()).collect();+ if let Some(e) = lines.iter().find_map(|l| l.strip_prefix("error: ")) {+ return e.to_string();+ }+ let tail: Vec<&str> = lines.iter().rev().take(3).rev().copied().collect();+ match (tail.is_empty(), self.status) {+ (false, _) => tail.join(" "),+ (true, Some(c)) => format!("The command on the machine exited with status {c}."),+ (true, None) => "The command on the machine was terminated.".into(),+ }+ }+}++pub fn new_marker() -> String {+ format!("__openrunner_{}__", super::random_id(12))+}++/// Prepends the marker preamble for `windows` (PowerShell) or sh scripts.+pub fn with_marker(marker: &str, windows: bool, script: &str) -> String {+ if windows {+ format!("$OR_MARK = '{marker}'\nWrite-Output $OR_MARK\n[Console]::Error.WriteLine($OR_MARK)\n{script}")+ } else {+ // zsh as a login shell: behave like sh for the rest of the script.+ format!(+ "if [ -n \"$ZSH_VERSION\" ]; then emulate sh 2>/dev/null; fi\nOR_MARK='{marker}'\nprintf '%s\\n' \"$OR_MARK\"\nprintf '%s\\n' \"$OR_MARK\" >&2\n{script}"+ )+ }+}++fn command(spec: &MachineSpec, windows: bool) -> Command {+ if spec.is_local() {+ if windows {+ let mut c = Command::new("powershell");+ c.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_READ_STDIN]);+ c+ } else {+ let mut c = Command::new("/bin/sh");+ c.args(["-c", LOGIN_WRAPPER]);+ c+ }+ } else {+ let mut c = Command::new("ssh");+ c.args(probe::ssh_args(spec));+ c.arg(if windows {+ format!("powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{PS_READ_STDIN}\"")+ } else {+ format!("sh -c '{LOGIN_WRAPPER}'")+ });+ c+ }+}++/// Runs `script` (already wrapped by `with_marker`) and collects its output.+/// `on_line` sees each cleaned stdout/stderr line as it arrives (for streaming+/// into an operation log). `secrets` are masked everywhere.+pub async fn run(+ spec: &MachineSpec,+ windows: bool,+ marker: &str,+ script: String,+ timeout: Duration,+ limits: Limits,+ secrets: &[String],+ on_line: Option<&(dyn Fn(&str) + Send + Sync)>,+) -> Result<Output, String> {+ let mut cmd = command(spec, windows);+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);+ let mut child = cmd.spawn().map_err(|e| {+ if spec.is_local() { format!("Couldn't start a shell: {e}") } else { format!("Couldn't run ssh: {e}") }+ })?;+ let mut stdin = child.stdin.take().ok_or("No stdin for the script")?;+ let mut stdout = child.stdout.take().ok_or("No stdout for the script")?;+ let mut stderr = child.stderr.take().ok_or("No stderr for the script")?;++ let mut out = Collector::new(marker, limits, secrets, false);+ let mut err = Collector::new(marker, Limits::OUTPUT, secrets, true);++ let work = async {+ // The script is small (or a bounded file upload); write it whole, then close stdin.+ let writer = async {+ let _ = stdin.write_all(script.as_bytes()).await;+ drop(stdin);+ };+ let reader = async {+ let (mut out_open, mut err_open) = (true, true);+ let mut ob = [0u8; 8192];+ let mut eb = [0u8; 8192];+ let mut exit_deadline: Option<tokio::time::Instant> = None;+ while out_open || err_open {+ let grace = async {+ match exit_deadline {+ Some(d) => tokio::time::sleep_until(d).await,+ None => std::future::pending::<()>().await,+ }+ };+ tokio::select! {+ n = read(&mut stdout, &mut ob), if out_open => match n {+ Some(n) => out.push(&ob[..n], on_line),+ None => out_open = false,+ },+ n = read(&mut stderr, &mut eb), if err_open => match n {+ Some(n) => {+ err.push(&eb[..n], on_line);+ if err.exit.is_some() && exit_deadline.is_none() {+ exit_deadline = Some(tokio::time::Instant::now() + AFTER_EXIT_GRACE);+ }+ }+ None => err_open = false,+ },+ _ = grace => break,+ }+ }+ };+ tokio::join!(writer, reader);+ };++ let finished = tokio::time::timeout(timeout, work).await.is_ok();+ let status = if finished {+ match tokio::time::timeout(AFTER_EXIT_GRACE, child.wait()).await {+ Ok(Ok(s)) => s.code(),+ _ => {+ let _ = child.kill().await;+ None+ }+ }+ } else {+ let _ = child.kill().await;+ None+ };++ out.finish(on_line);+ err.finish(on_line);+ let started = out.started || err.started;+ let (stdout, out_trunc) = out.text();+ let (stderr, err_trunc) = err.text();+ Ok(Output {+ stdout,+ stderr,+ status,+ exit: err.exit,+ timed_out: err.timed_out || !finished,+ truncated: out_trunc || err_trunc,+ started,+ preamble: err.preamble.join("\n"),+ })+}++async fn read(r: &mut (impl AsyncRead + Unpin), buf: &mut [u8]) -> Option<usize> {+ match r.read(buf).await {+ Ok(0) | Err(_) => None,+ Ok(n) => Some(n),+ }+}++/// Splits a byte stream into cleaned lines, drops the login-profile preamble,+/// picks out marker lines, and keeps a bounded head and tail.+struct Collector<'a> {+ marker: &'a str,+ limits: Limits,+ secrets: &'a [String],+ is_stderr: bool,+ partial: Vec<u8>,+ partial_cut: bool,+ started: bool,+ preamble: Vec<String>,+ head: Vec<String>,+ head_bytes: usize,+ tail: VecDeque<String>,+ tail_bytes: usize,+ dropped_bytes: usize,+ cut: bool,+ exit: Option<i32>,+ timed_out: bool,+}++impl<'a> Collector<'a> {+ fn new(marker: &'a str, limits: Limits, secrets: &'a [String], is_stderr: bool) -> Self {+ Collector {+ marker,+ limits,+ secrets,+ is_stderr,+ partial: Vec::new(),+ partial_cut: false,+ started: false,+ preamble: Vec::new(),+ head: Vec::new(),+ head_bytes: 0,+ tail: VecDeque::new(),+ tail_bytes: 0,+ dropped_bytes: 0,+ cut: false,+ exit: None,+ timed_out: false,+ }+ }++ fn push(&mut self, bytes: &[u8], on_line: Option<&(dyn Fn(&str) + Send + Sync)>) {+ for &b in bytes {+ if b == b'\n' {+ let raw = std::mem::take(&mut self.partial);+ if std::mem::take(&mut self.partial_cut) {+ self.cut = true;+ }+ self.line(&String::from_utf8_lossy(&raw), on_line);+ } else if self.partial.len() < self.line_cap() {+ self.partial.push(b);+ } else {+ self.partial_cut = true;+ }+ }+ }++ /// Until the marker shows up, lines may be login-profile noise or the marker+ /// itself, so a tiny cap can't be allowed to cut the marker.+ fn line_cap(&self) -> usize {+ if self.started { self.limits.line } else { self.limits.line.max(4096) }+ }++ fn finish(&mut self, on_line: Option<&(dyn Fn(&str) + Send + Sync)>) {+ if !self.partial.is_empty() {+ let raw = std::mem::take(&mut self.partial);+ self.line(&String::from_utf8_lossy(&raw), on_line);+ }+ }++ fn line(&mut self, raw: &str, on_line: Option<&(dyn Fn(&str) + Send + Sync)>) {+ let mut text = raw.to_string();+ if !self.started {+ match text.find(self.marker) {+ // Profile output can share the marker's line if it didn't end with a newline.+ Some(i) if text[i + self.marker.len()..].trim().is_empty() => {+ self.started = true;+ return;+ }+ _ => {+ if self.preamble.len() < 20 {+ let clean = clean_line(&text, self.secrets);+ if !clean.trim().is_empty() {+ self.preamble.push(clean);+ }+ }+ return;+ }+ }+ }+ if self.is_stderr {+ let exit_tag = format!("{}:exit=", self.marker);+ if let Some(i) = text.find(&exit_tag) {+ self.exit = text[i + exit_tag.len()..].trim().parse().ok();+ text.truncate(i);+ if text.trim().is_empty() {+ return;+ }+ }+ let timeout_tag = format!("{}:timeout", self.marker);+ if let Some(i) = text.find(&timeout_tag) {+ self.timed_out = true;+ text.truncate(i);+ if text.trim().is_empty() {+ return;+ }+ }+ }+ let clean = clean_line(&text, self.secrets);+ if let Some(cb) = on_line {+ if !clean.trim().is_empty() {+ cb(&clean);+ }+ }+ self.store(clean);+ }++ fn store(&mut self, line: String) {+ let size = line.len() + 1;+ if self.head_bytes + size <= self.limits.head {+ self.head_bytes += size;+ self.head.push(line);+ return;+ }+ self.tail_bytes += size;+ self.tail.push_back(line);+ while self.tail_bytes > self.limits.tail {+ match self.tail.pop_front() {+ Some(l) => {+ self.tail_bytes -= l.len() + 1;+ self.dropped_bytes += l.len() + 1;+ }+ None => break,+ }+ }+ }++ /// The kept text and whether anything was dropped.+ fn text(&self) -> (String, bool) {+ let mut lines: Vec<&str> = self.head.iter().map(String::as_str).collect();+ let note;+ if self.dropped_bytes > 0 {+ note = format!("[… {} of output omitted …]", crate::util::bytes(self.dropped_bytes as u64));+ lines.push(¬e);+ }+ lines.extend(self.tail.iter().map(String::as_str));+ (lines.join("\n"), self.dropped_bytes > 0 || self.cut)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn collect(marker: &str, limits: Limits, input: &str, stderr: bool) -> (Collector<'static>, String, bool) {+ let marker: &'static str = Box::leak(marker.to_string().into_boxed_str());+ let mut c = Collector::new(marker, limits, &[], stderr);+ c.push(input.as_bytes(), None);+ c.finish(None);+ let (t, cut) = c.text();+ (c, t, cut)+ }++ #[test]+ fn drops_profile_noise_and_reads_markers() {+ let m = "__openrunner_test__";+ let (c, text, _) = collect(m, Limits::OUTPUT, &format!("Welcome!{m}\nreal error\nlast{m}:exit=3\n"), true);+ assert!(c.started);+ assert_eq!(c.preamble, Vec::<String>::new(), "noise on the marker's line is dropped");+ assert_eq!(c.exit, Some(3));+ assert_eq!(text, "real error\nlast");++ let (c, text, _) = collect(m, Limits::OUTPUT, &format!("motd line\n{m}\n\u{1b}[31mred\u{1b}[0m\n{m}:timeout\n"), true);+ assert_eq!(c.preamble, vec!["motd line"]);+ assert!(c.timed_out);+ assert_eq!(text, "red");+ }++ #[test]+ fn caps_long_output_keeping_head_and_tail() {+ let m = "__openrunner_cap__";+ let limits = Limits { head: 20, tail: 20, line: 1000 };+ let body: String = (0..100).map(|i| format!("line {i:03}\n")).collect();+ let (_, text, truncated) = collect(m, limits, &format!("{m}\n{body}"), false);+ assert!(truncated);+ assert!(text.starts_with("line 000\nline 001"), "{text}");+ assert!(text.ends_with("line 098\nline 099"), "{text}");+ assert!(text.contains("omitted"), "{text}");+ }++ #[test]+ fn cuts_huge_lines() {+ let m = "__openrunner_line__";+ let limits = Limits { head: 1 << 20, tail: 0, line: 10 };+ let (_, text, truncated) = collect(m, limits, &format!("{m}\n{}\nok\n", "x".repeat(50)), false);+ assert!(truncated);+ assert_eq!(text, "xxxxxxxxxx\nok");+ }++ #[test]+ fn wraps_scripts_with_markers() {+ let sh = with_marker("MK", false, "echo hi\n");+ assert!(sh.contains("OR_MARK='MK'") && sh.ends_with("echo hi\n"));+ let ps = with_marker("MK", true, "Write-Output hi\n");+ assert!(ps.starts_with("$OR_MARK = 'MK'"));+ }+}diff --git a/src/github/mod.rs b/src/github/mod.rsnew file mode 100644index 0000000..7bf6c40--- /dev/null+++ b/src/github/mod.rs@@ -0,0 +1,868 @@+//! GitHub REST API: runner status for orgs/repos, plus queued and running jobs+//! from recently active repos. Requests are conditional (ETag), so polling an+//! unchanged endpoint returns 304 and doesn't count against the rate limit.++use std::collections::HashMap;+use std::sync::Mutex;+use std::time::{Duration, Instant};++use chrono::{DateTime, TimeZone, Utc};+use futures::stream::{self, StreamExt};+use reqwest::header::{ACCEPT, AUTHORIZATION, ETAG, IF_NONE_MATCH, LINK, USER_AGENT};+use reqwest::StatusCode;+use serde::de::DeserializeOwned;+use serde::Deserialize;++use crate::config::GitHubSettings;++const CONCURRENCY: usize = 6;+const ORG_REPOS_TTL: Duration = Duration::from_secs(300);+const RELEASE_TTL: Duration = Duration::from_secs(6 * 3600);++// ---------------------------------------------------------------------------+// Results handed to the fleet engine++#[derive(Debug, Clone, Default)]+pub struct GitHubData {+ pub synced_at: Option<DateTime<Utc>>,+ pub token_source: String,+ pub login: Option<String>,+ /// A problem that stopped the whole sync (e.g. no token).+ pub error: Option<String>,+ pub scopes: Vec<ScopeData>,+ pub jobs: Vec<JobData>,+ pub scanned_repos: Vec<String>,+ pub rate: Option<Rate>,+ pub latest_runner_version: Option<String>,+}++#[derive(Debug, Clone)]+pub struct ScopeData {+ pub kind: ScopeKind,+ pub name: String,+ pub runners: Vec<RunnerData>,+ pub synced_at: Option<DateTime<Utc>>,+ pub error: Option<String>,+ pub hint: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ScopeKind {+ Org,+ Repo,+}++impl ScopeKind {+ pub fn as_str(self) -> &'static str {+ match self {+ ScopeKind::Org => "org",+ ScopeKind::Repo => "repo",+ }+ }+}++#[derive(Debug, Clone)]+pub struct RunnerData {+ pub id: u64,+ pub name: String,+ pub os: String,+ pub status: String,+ pub busy: bool,+ pub labels: Vec<String>,+}++#[derive(Debug, Clone)]+pub struct JobData {+ pub id: u64,+ pub run_id: u64,+ pub name: String,+ pub workflow: String,+ pub repo: String,+ pub branch: Option<String>,+ pub event: Option<String>,+ pub actor: Option<String>,+ pub url: String,+ pub status: String,+ pub labels: Vec<String>,+ pub runner_name: Option<String>,+ pub created_at: DateTime<Utc>,+ pub started_at: Option<DateTime<Utc>>,+}++#[derive(Debug, Clone, Copy)]+pub struct Rate {+ pub limit: u32,+ pub remaining: u32,+ pub reset_at: DateTime<Utc>,+}++#[derive(Debug, Clone)]+pub struct ScopeTest {+ pub kind: ScopeKind,+ pub name: String,+ pub runners: usize,+ pub error: Option<String>,+ pub hint: Option<String>,+}++// ---------------------------------------------------------------------------+// API shapes++#[derive(Deserialize)]+struct ApiRunners {+ runners: Vec<ApiRunner>,+}++#[derive(Deserialize)]+struct ApiRunner {+ id: u64,+ name: String,+ #[serde(default)]+ os: String,+ status: String,+ #[serde(default)]+ busy: bool,+ #[serde(default)]+ labels: Vec<ApiLabel>,+}++#[derive(Deserialize)]+struct ApiLabel {+ name: String,+}++#[derive(Deserialize)]+struct ApiRuns {+ workflow_runs: Vec<ApiRun>,+}++#[derive(Deserialize)]+struct ApiRun {+ id: u64,+ #[serde(default)]+ event: Option<String>,+ #[serde(default)]+ actor: Option<ApiUser>,+}++#[derive(Deserialize)]+struct ApiUser {+ login: String,+}++#[derive(Deserialize)]+struct ApiJobs {+ jobs: Vec<ApiJob>,+}++#[derive(Deserialize)]+struct ApiJob {+ id: u64,+ run_id: u64,+ name: String,+ status: String,+ #[serde(default)]+ labels: Vec<String>,+ #[serde(default)]+ runner_name: Option<String>,+ created_at: DateTime<Utc>,+ #[serde(default)]+ started_at: Option<DateTime<Utc>>,+ #[serde(default)]+ html_url: Option<String>,+ #[serde(default)]+ workflow_name: Option<String>,+ #[serde(default)]+ head_branch: Option<String>,+}++#[derive(Deserialize)]+struct ApiRepo {+ full_name: String,+ #[serde(default)]+ archived: bool,+ #[serde(default)]+ disabled: bool,+}++#[derive(Deserialize)]+struct ApiRelease {+ tag_name: String,+}++#[derive(Deserialize)]+struct ApiErrorBody {+ #[serde(default)]+ message: String,+}++// ---------------------------------------------------------------------------+// Client++#[derive(Debug)]+pub struct ApiError {+ pub status: Option<StatusCode>,+ pub message: String,+}++impl std::fmt::Display for ApiError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.message)+ }+}++#[derive(Clone)]+struct Token {+ value: String,+ source: String,+}++struct Cached {+ etag: String,+ body: std::sync::Arc<[u8]>,+ next: Option<String>,+}++pub struct Client {+ http: reqwest::Client,+ api_url: Mutex<String>,+ token: Mutex<Option<Token>>,+ cache: Mutex<HashMap<String, Cached>>,+ rate: Mutex<Option<Rate>>,+ login: Mutex<Option<String>>,+ org_repos: Mutex<HashMap<String, (Instant, Vec<String>)>>,+ release: Mutex<Option<(Instant, String)>>,+}++impl Client {+ pub fn new() -> Client {+ let http = reqwest::Client::builder()+ .timeout(Duration::from_secs(20))+ .connect_timeout(Duration::from_secs(8))+ .build()+ .expect("building HTTP client");+ Client {+ http,+ api_url: Mutex::new("https://api.github.com".into()),+ token: Mutex::new(None),+ cache: Mutex::new(HashMap::new()),+ rate: Mutex::new(None),+ login: Mutex::new(None),+ org_repos: Mutex::new(HashMap::new()),+ release: Mutex::new(None),+ }+ }++ fn set_api_url(&self, url: &str) {+ let mut current = self.api_url.lock().unwrap();+ if *current != url {+ *current = url.to_string();+ // A different server means different credentials and cached responses.+ *self.token.lock().unwrap() = None;+ *self.login.lock().unwrap() = None;+ self.cache.lock().unwrap().clear();+ }+ }++ /// GitHub host for `gh auth token --hostname`.+ fn gh_hostname(&self) -> String {+ let api = self.api_url.lock().unwrap().clone();+ let host = api.split("://").nth(1).unwrap_or(&api).split('/').next().unwrap_or("github.com");+ if host == "api.github.com" { "github.com".into() } else { host.to_string() }+ }++ async fn token(&self) -> Option<Token> {+ if let Some(t) = self.token.lock().unwrap().clone() {+ return Some(t);+ }+ let found = resolve_token(&self.gh_hostname()).await;+ *self.token.lock().unwrap() = found.clone();+ found+ }++ fn forget_token(&self) {+ *self.token.lock().unwrap() = None;+ }++ pub fn rate(&self) -> Option<Rate> {+ *self.rate.lock().unwrap()+ }++ /// GET a JSON endpoint, following `Link: rel="next"` up to `max_pages`.+ async fn get_all<T: DeserializeOwned>(&self, path: &str, max_pages: usize) -> Result<Vec<T>, ApiError> {+ let mut out = Vec::new();+ let mut url = self.url(path);+ for _ in 0..max_pages {+ let (page, next) = self.get_page::<T>(&url, true).await?;+ out.push(page);+ match next {+ Some(n) => url = n,+ None => break,+ }+ }+ Ok(out)+ }++ async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {+ Ok(self.get_page(&self.url(path), true).await?.0)+ }++ fn url(&self, path: &str) -> String {+ if path.starts_with("http") { path.to_string() } else { format!("{}{}", self.api_url.lock().unwrap(), path) }+ }++ fn get_page<'a, T: DeserializeOwned>(+ &'a self,+ url: &'a str,+ retry_auth: bool,+ ) -> futures::future::BoxFuture<'a, Result<(T, Option<String>), ApiError>> {+ Box::pin(async move {+ let Some(token) = self.token().await else {+ return Err(ApiError { status: None, message: "No GitHub token".into() });+ };+ let cached_etag = self.cache.lock().unwrap().get(url).map(|c| c.etag.clone());+ let mut req = self+ .http+ .get(url)+ .header(AUTHORIZATION, format!("Bearer {}", token.value))+ .header(ACCEPT, "application/vnd.github+json")+ .header("X-GitHub-Api-Version", "2022-11-28")+ .header(USER_AGENT, concat!("openrunner/", env!("CARGO_PKG_VERSION")));+ if let Some(etag) = &cached_etag {+ req = req.header(IF_NONE_MATCH, etag);+ }+ let resp = req.send().await.map_err(|e| ApiError {+ status: None,+ message: format!("Couldn't reach GitHub: {}", root_cause(&e)),+ })?;+ self.record_rate(resp.headers());+ let status = resp.status();++ if status == StatusCode::NOT_MODIFIED {+ let cache = self.cache.lock().unwrap();+ if let Some(c) = cache.get(url) {+ let value = serde_json::from_slice(&c.body).map_err(|e| decode_error(url, e))?;+ return Ok((value, c.next.clone()));+ }+ }+ if status == StatusCode::UNAUTHORIZED && retry_auth {+ // gh tokens can be rotated by `gh auth refresh`; look it up again once.+ self.forget_token();+ return self.get_page(url, false).await;+ }+ if !status.is_success() {+ let rate_limited = resp+ .headers()+ .get("x-ratelimit-remaining")+ .and_then(|v| v.to_str().ok())+ .is_some_and(|v| v == "0");+ let body = resp.bytes().await.unwrap_or_default();+ let message = serde_json::from_slice::<ApiErrorBody>(&body).map(|b| b.message).unwrap_or_default();+ let message = if rate_limited {+ "GitHub API rate limit reached".to_string()+ } else if message.is_empty() {+ format!("GitHub returned {status}")+ } else {+ message+ };+ return Err(ApiError { status: Some(status), message });+ }++ let etag = resp.headers().get(ETAG).and_then(|v| v.to_str().ok()).map(str::to_string);+ let next = resp.headers().get(LINK).and_then(|v| v.to_str().ok()).and_then(next_link);+ let body: std::sync::Arc<[u8]> = resp+ .bytes()+ .await+ .map_err(|e| ApiError { status: None, message: format!("Reading GitHub response: {e}") })?+ .to_vec()+ .into();+ let value = serde_json::from_slice(&body).map_err(|e| decode_error(url, e))?;+ if let Some(etag) = etag {+ self.cache.lock().unwrap().insert(url.to_string(), Cached { etag, body, next: next.clone() });+ }+ Ok((value, next))+ })+ }++ fn record_rate(&self, headers: &reqwest::header::HeaderMap) {+ let num = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<i64>().ok());+ if let (Some(limit), Some(remaining), Some(reset)) =+ (num("x-ratelimit-limit"), num("x-ratelimit-remaining"), num("x-ratelimit-reset"))+ {+ // Only the core REST bucket matters here.+ let resource = headers.get("x-ratelimit-resource").and_then(|v| v.to_str().ok()).unwrap_or("core");+ if resource == "core" {+ *self.rate.lock().unwrap() = Some(Rate {+ limit: limit as u32,+ remaining: remaining as u32,+ reset_at: Utc.timestamp_opt(reset, 0).single().unwrap_or_else(Utc::now),+ });+ }+ }+ }++ async fn login(&self) -> Option<String> {+ if let Some(l) = self.login.lock().unwrap().clone() {+ return Some(l);+ }+ #[derive(Deserialize)]+ struct User {+ login: String,+ }+ let user: User = self.get("/user").await.ok()?;+ *self.login.lock().unwrap() = Some(user.login.clone());+ Some(user.login)+ }++ async fn runners(&self, kind: ScopeKind, name: &str) -> Result<Vec<RunnerData>, ApiError> {+ let path = match kind {+ ScopeKind::Org => format!("/orgs/{name}/actions/runners?per_page=100"),+ ScopeKind::Repo => format!("/repos/{name}/actions/runners?per_page=100"),+ };+ let pages: Vec<ApiRunners> = self.get_all(&path, 10).await?;+ Ok(pages+ .into_iter()+ .flat_map(|p| p.runners)+ .map(|r| RunnerData {+ id: r.id,+ name: r.name,+ os: r.os,+ status: r.status,+ busy: r.busy,+ labels: r.labels.into_iter().map(|l| l.name).collect(),+ })+ .collect())+ }++ /// The most recently pushed, non-archived repos of an org (cached for a few minutes).+ async fn org_repos(&self, org: &str, limit: usize) -> Vec<String> {+ if limit == 0 {+ return Vec::new();+ }+ let key = format!("{org}:{limit}");+ if let Some((at, repos)) = self.org_repos.lock().unwrap().get(&key) {+ if at.elapsed() < ORG_REPOS_TTL {+ return repos.clone();+ }+ }+ let per_page = (limit + 5).min(100);+ let path = format!("/orgs/{org}/repos?sort=pushed&direction=desc&per_page={per_page}");+ let repos: Vec<String> = match self.get::<Vec<ApiRepo>>(&path).await {+ Ok(list) => list.into_iter().filter(|r| !r.archived && !r.disabled).map(|r| r.full_name).take(limit).collect(),+ Err(e) => {+ tracing::debug!("listing repos for {org}: {e}");+ Vec::new()+ }+ };+ self.org_repos.lock().unwrap().insert(key, (Instant::now(), repos.clone()));+ repos+ }++ /// Queued and in-progress jobs for one repo.+ async fn active_jobs(&self, repo: &str) -> Vec<JobData> {+ let mut runs = Vec::new();+ for status in ["queued", "in_progress"] {+ match self.get::<ApiRuns>(&format!("/repos/{repo}/actions/runs?status={status}&per_page=30")).await {+ Ok(r) => runs.extend(r.workflow_runs),+ Err(e) => tracing::debug!("listing {status} runs for {repo}: {e}"),+ }+ }+ runs.sort_by_key(|r| r.id);+ runs.dedup_by_key(|r| r.id);++ let per_run = stream::iter(runs)+ .map(|run| async move {+ let jobs = self+ .get::<ApiJobs>(&format!("/repos/{repo}/actions/runs/{}/jobs?per_page=100", run.id))+ .await+ .map(|j| j.jobs)+ .unwrap_or_default();+ jobs.into_iter()+ .filter(|j| matches!(j.status.as_str(), "queued" | "in_progress" | "waiting" | "pending"))+ .map(|j| JobData {+ id: j.id,+ run_id: j.run_id,+ name: j.name,+ workflow: j.workflow_name.unwrap_or_default(),+ repo: repo.to_string(),+ branch: j.head_branch,+ event: run.event.clone(),+ actor: run.actor.as_ref().map(|a| a.login.clone()),+ url: j.html_url.unwrap_or_else(|| format!("https://github.com/{repo}/actions/runs/{}", j.run_id)),+ status: if j.status == "pending" { "queued".into() } else { j.status },+ labels: j.labels,+ runner_name: j.runner_name.filter(|n| !n.is_empty()),+ created_at: j.created_at,+ started_at: j.started_at,+ })+ .collect::<Vec<_>>()+ })+ .buffer_unordered(CONCURRENCY)+ .collect::<Vec<_>>()+ .await;+ per_run.into_iter().flatten().collect()+ }++ async fn latest_runner_version(&self) -> Option<String> {+ if let Some((at, v)) = self.release.lock().unwrap().clone() {+ if at.elapsed() < RELEASE_TTL {+ return Some(v);+ }+ }+ let rel: ApiRelease = self.get("/repos/actions/runner/releases/latest").await.ok()?;+ let v = rel.tag_name.trim_start_matches('v').to_string();+ *self.release.lock().unwrap() = Some((Instant::now(), v.clone()));+ Some(v)+ }++ /// One full pass: runners for every configured scope, then active jobs.+ pub async fn sync(&self, settings: &GitHubSettings) -> GitHubData {+ self.set_api_url(&settings.api_url);+ let mut data = GitHubData::default();+ let Some(token) = self.token().await else {+ data.error = Some("No GitHub token found. Run `gh auth login` or set GITHUB_TOKEN.".into());+ return data;+ };+ data.token_source = token.source;+ data.login = self.login().await;++ let scopes: Vec<(ScopeKind, String)> = settings+ .orgs+ .iter()+ .map(|o| (ScopeKind::Org, o.clone()))+ .chain(settings.repos.iter().map(|r| (ScopeKind::Repo, r.clone())))+ .collect();++ data.scopes = stream::iter(scopes)+ .map(|(kind, name)| async move {+ let result = self.runners(kind, &name).await;+ let (runners, error, hint) = match result {+ Ok(r) => (r, None, None),+ Err(e) => {+ let (msg, hint) = explain(kind, &name, &e, &data_token_source(self));+ (Vec::new(), Some(msg), hint)+ }+ };+ ScopeData {+ kind,+ synced_at: error.is_none().then(Utc::now),+ name,+ runners,+ error,+ hint,+ }+ })+ .buffered(CONCURRENCY)+ .collect()+ .await;++ // Repos to scan for jobs: the configured ones plus each org's most recently pushed repos.+ let mut repos: Vec<String> = settings.repos.clone();+ for org in &settings.orgs {+ for r in self.org_repos(org, settings.scan_repos as usize).await {+ if !repos.iter().any(|x| x.eq_ignore_ascii_case(&r)) {+ repos.push(r);+ }+ }+ }+ data.jobs = stream::iter(repos.clone())+ .map(|repo| async move { self.active_jobs(&repo).await })+ .buffer_unordered(CONCURRENCY)+ .collect::<Vec<_>>()+ .await+ .into_iter()+ .flatten()+ .collect();+ data.scanned_repos = repos;+ data.latest_runner_version = self.latest_runner_version().await;+ data.rate = self.rate();+ data.synced_at = Some(Utc::now());+ if !data.scopes.is_empty() && data.scopes.iter().all(|s| s.error.is_some()) {+ data.error = data.scopes.first().and_then(|s| s.error.clone());+ }+ data+ }++ /// Validates an org or repo before it's added in Settings.+ pub async fn test_scope(&self, settings: &GitHubSettings, scope: &str) -> ScopeTest {+ self.set_api_url(&settings.api_url);+ let name = crate::config::strip_github_url(scope);+ let kind = if name.contains('/') { ScopeKind::Repo } else { ScopeKind::Org };+ if self.token().await.is_none() {+ return ScopeTest {+ kind,+ name,+ runners: 0,+ error: Some("No GitHub token found.".into()),+ hint: Some("gh auth login".into()),+ };+ }+ match self.runners(kind, &name).await {+ Ok(r) => ScopeTest { kind, name, runners: r.len(), error: None, hint: None },+ Err(e) => {+ let (msg, hint) = explain(kind, &name, &e, &data_token_source(self));+ ScopeTest { kind, name, runners: 0, error: Some(msg), hint }+ }+ }+ }++ // -----------------------------------------------------------------------+ // Writes, used by runner provisioning. Never cached.++ /// A short-lived token for `config.sh --token` (registering new runners).+ pub async fn registration_token(&self, settings: &GitHubSettings, scope: &str) -> Result<String, String> {+ let (kind, name) = parse_scope(scope);+ let doing = format!("Registering runners with {name}");+ self.scoped_token(settings, kind, &name, "registration-token", &doing).await+ }++ /// A short-lived token for `config.sh remove --token` (deregistering a runner).+ pub async fn remove_token(&self, settings: &GitHubSettings, scope: &str) -> Result<String, String> {+ let (kind, name) = parse_scope(scope);+ let doing = format!("Removing runners from {name}");+ self.scoped_token(settings, kind, &name, "remove-token", &doing).await+ }++ /// Deletes a runner registration directly, for runners whose machine is gone.+ pub async fn delete_runner(&self, settings: &GitHubSettings, scope: &str, runner_id: u64) -> Result<(), String> {+ self.set_api_url(&settings.api_url);+ let (kind, name) = parse_scope(scope);+ let path = format!("{}/actions/runners/{runner_id}", scope_path(kind, &name));+ match self.send(reqwest::Method::DELETE, &path).await {+ Ok(_) => Ok(()),+ Err(e) => Err(with_hint(explain_doing(kind, &name, &e, &data_token_source(self), &format!("Removing runners from {name}")))),+ }+ }++ /// The newest actions/runner release, e.g. "2.329.0".+ pub async fn latest_runner_release(&self, settings: &GitHubSettings) -> Option<String> {+ self.set_api_url(&settings.api_url);+ self.latest_runner_version().await+ }++ /// The URL runners are registered against, e.g. https://github.com/acme.+ pub fn web_url(&self, settings: &GitHubSettings, scope: &str) -> String {+ self.set_api_url(&settings.api_url);+ let (_, name) = parse_scope(scope);+ format!("https://{}/{name}", self.gh_hostname())+ }++ async fn scoped_token(&self, settings: &GitHubSettings, kind: ScopeKind, name: &str, which: &str, doing: &str) -> Result<String, String> {+ #[derive(Deserialize)]+ struct TokenBody {+ token: String,+ }+ self.set_api_url(&settings.api_url);+ if self.token().await.is_none() {+ return Err("No GitHub token found. Run `gh auth login` or set GITHUB_TOKEN.".into());+ }+ let path = format!("{}/actions/runners/{which}", scope_path(kind, name));+ match self.send(reqwest::Method::POST, &path).await {+ Ok(body) => serde_json::from_slice::<TokenBody>(&body)+ .map(|b| b.token)+ .map_err(|e| format!("Unexpected response from GitHub: {e}")),+ Err(e) => Err(with_hint(explain_doing(kind, name, &e, &data_token_source(self), doing))),+ }+ }++ /// An uncached request; retries once with a fresh token on 401.+ async fn send(&self, method: reqwest::Method, path: &str) -> Result<Vec<u8>, ApiError> {+ let url = self.url(path);+ for attempt in 0..2 {+ let Some(token) = self.token().await else {+ return Err(ApiError { status: None, message: "No GitHub token".into() });+ };+ let resp = self+ .http+ .request(method.clone(), &url)+ .header(AUTHORIZATION, format!("Bearer {}", token.value))+ .header(ACCEPT, "application/vnd.github+json")+ .header("X-GitHub-Api-Version", "2022-11-28")+ .header(USER_AGENT, concat!("openrunner/", env!("CARGO_PKG_VERSION")))+ .send()+ .await+ .map_err(|e| ApiError { status: None, message: format!("Couldn't reach GitHub: {}", root_cause(&e)) })?;+ self.record_rate(resp.headers());+ let status = resp.status();+ if status == StatusCode::UNAUTHORIZED && attempt == 0 {+ self.forget_token();+ continue;+ }+ let body = resp.bytes().await.map(|b| b.to_vec()).unwrap_or_default();+ if status.is_success() {+ return Ok(body);+ }+ let message = serde_json::from_slice::<ApiErrorBody>(&body).map(|b| b.message).unwrap_or_default();+ let message = if message.is_empty() { format!("GitHub returned {status}") } else { message };+ return Err(ApiError { status: Some(status), message });+ }+ Err(ApiError { status: Some(StatusCode::UNAUTHORIZED), message: "GitHub rejected the token.".into() })+ }++ pub async fn token_source(&self) -> String {+ self.token().await.map(|t| t.source).unwrap_or_default()+ }++ /// The GitHub web host (e.g. "github.com") and the user's token, for cloning+ /// private repositories into agent workspaces. The caller must keep the token+ /// out of argv and logs.+ pub async fn git_credentials(&self, settings: &GitHubSettings) -> Option<(String, String)> {+ self.set_api_url(&settings.api_url);+ let token = self.token().await?;+ Some((self.gh_hostname(), token.value))+ }+}++fn data_token_source(client: &Client) -> String {+ client.token.lock().unwrap().as_ref().map(|t| t.source.clone()).unwrap_or_default()+}++/// Turns API failures into a sentence and, where possible, the command that fixes it.+fn explain(kind: ScopeKind, name: &str, e: &ApiError, token_source: &str) -> (String, Option<String>) {+ explain_doing(kind, name, e, token_source, &format!("Reading {name}'s runners"))+}++/// Like `explain`, for a specific action ("Registering runners with acme").+fn explain_doing(kind: ScopeKind, name: &str, e: &ApiError, token_source: &str, doing: &str) -> (String, Option<String>) {+ let via_gh = token_source == "gh";+ match (kind, e.status.map(|s| s.as_u16())) {+ (_, Some(401)) => (+ "GitHub rejected the token.".into(),+ Some(if via_gh { "gh auth login".into() } else { "Check GITHUB_TOKEN".into() }),+ ),+ (ScopeKind::Org, Some(403)) if !e.message.contains("rate limit") => (+ format!("{doing} needs an org admin token with the admin:org scope."),+ via_gh.then(|| "gh auth refresh -h github.com -s admin:org".into()),+ ),+ (ScopeKind::Org, Some(404)) => (format!("Organization {name} wasn't found, or you aren't an admin of it."), None),+ (ScopeKind::Repo, Some(403 | 404)) if !e.message.contains("rate limit") => {+ (format!("{name} wasn't found, or you don't have admin access to it."), None)+ }+ _ => (e.message.clone(), None),+ }+}++fn with_hint((msg, hint): (String, Option<String>)) -> String {+ match hint {+ Some(h) => format!("{msg} Run `{h}`."),+ None => msg,+ }+}++/// "acme", "org:acme" -> (Org, "acme"); "acme/api", "repo:acme/api" -> (Repo, "acme/api")+pub fn parse_scope(scope: &str) -> (ScopeKind, String) {+ let s = scope.trim();+ let s = s.strip_prefix("org:").or_else(|| s.strip_prefix("repo:")).unwrap_or(s);+ let name = crate::config::strip_github_url(s);+ let kind = if name.contains('/') { ScopeKind::Repo } else { ScopeKind::Org };+ (kind, name)+}++fn scope_path(kind: ScopeKind, name: &str) -> String {+ match kind {+ ScopeKind::Org => format!("/orgs/{name}"),+ ScopeKind::Repo => format!("/repos/{name}"),+ }+}++/// `OPENRUNNER_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, then `gh auth token`.+async fn resolve_token(hostname: &str) -> Option<Token> {+ for var in ["OPENRUNNER_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN"] {+ if let Ok(v) = std::env::var(var) {+ if !v.trim().is_empty() {+ return Some(Token { value: v.trim().to_string(), source: var.to_string() });+ }+ }+ }+ let out = tokio::process::Command::new("gh")+ .args(["auth", "token", "--hostname", hostname])+ .output()+ .await+ .ok()?;+ let value = String::from_utf8_lossy(&out.stdout).trim().to_string();+ (out.status.success() && !value.is_empty()).then(|| Token { value, source: "gh".into() })+}++fn next_link(header: &str) -> Option<String> {+ header.split(',').find_map(|part| {+ let (url, rel) = part.split_once(';')?;+ rel.contains("rel=\"next\"").then(|| url.trim().trim_start_matches('<').trim_end_matches('>').to_string())+ })+}++fn decode_error(url: &str, e: serde_json::Error) -> ApiError {+ ApiError { status: None, message: format!("Unexpected response from {url}: {e}") }+}++fn root_cause(e: &(dyn std::error::Error + 'static)) -> String {+ let mut cur = e;+ while let Some(next) = cur.source() {+ cur = next;+ }+ cur.to_string()+}++/// Labels GitHub uses for its own hosted runners. A job asking only for these+/// isn't waiting for one of our machines.+pub fn is_github_hosted_label(label: &str) -> bool {+ let l = label.to_ascii_lowercase();+ ["ubuntu-", "windows-", "macos-"].iter().any(|p| l.starts_with(p))+}++/// "https://github.com/acme" -> "acme", "https://github.com/acme/api" -> "acme/api"+pub fn scope_from_runner_url(url: &str) -> Option<String> {+ let rest = url.trim().strip_prefix("https://").or_else(|| url.trim().strip_prefix("http://"))?;+ let (_, path) = rest.split_once('/')?;+ let parts: Vec<&str> = path.trim_matches('/').split('/').filter(|p| !p.is_empty()).collect();+ match parts.as_slice() {+ ["enterprises", ..] => None,+ [org] => Some(org.to_string()),+ [owner, repo] => Some(format!("{owner}/{repo}")),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_link_header() {+ let h = r#"<https://api.github.com/orgs/acme/actions/runners?page=2>; rel="next", <https://api.github.com/orgs/acme/actions/runners?page=5>; rel="last""#;+ assert_eq!(next_link(h).as_deref(), Some("https://api.github.com/orgs/acme/actions/runners?page=2"));+ assert_eq!(next_link(r#"<x>; rel="prev""#), None);+ }++ #[test]+ fn scopes_from_urls() {+ assert_eq!(scope_from_runner_url("https://github.com/acme").as_deref(), Some("acme"));+ assert_eq!(scope_from_runner_url("https://github.com/acme/api/").as_deref(), Some("acme/api"));+ assert_eq!(scope_from_runner_url("https://github.com/enterprises/big"), None);+ }++ #[test]+ fn parses_scopes() {+ assert_eq!(parse_scope("org:acme"), (ScopeKind::Org, "acme".into()));+ assert_eq!(parse_scope("repo:acme/api"), (ScopeKind::Repo, "acme/api".into()));+ assert_eq!(parse_scope(" https://github.com/acme/api "), (ScopeKind::Repo, "acme/api".into()));+ assert_eq!(scope_path(ScopeKind::Org, "acme"), "/orgs/acme");+ }++ #[test]+ fn explains_registration_errors() {+ let e = ApiError { status: Some(StatusCode::FORBIDDEN), message: "Resource not accessible".into() };+ let msg = with_hint(explain_doing(ScopeKind::Org, "acme", &e, "gh", "Registering runners with acme"));+ assert_eq!(+ msg,+ "Registering runners with acme needs an org admin token with the admin:org scope. Run `gh auth refresh -h github.com -s admin:org`."+ );+ }++ #[test]+ fn explains_org_permission_errors() {+ let e = ApiError { status: Some(StatusCode::FORBIDDEN), message: "Must have admin rights".into() };+ let (msg, hint) = explain(ScopeKind::Org, "acme", &e, "gh");+ assert!(msg.contains("admin:org"));+ assert_eq!(hint.as_deref(), Some("gh auth refresh -h github.com -s admin:org"));+ }+}diff --git a/src/main.rs b/src/main.rsnew file mode 100644index 0000000..92e4c32--- /dev/null+++ b/src/main.rs@@ -0,0 +1,996 @@+mod api;+mod cli;+mod config;+mod demo;+mod fleet;+mod github;+mod mcp;+mod ops;+mod probe;+#[cfg(feature = "gui")]+mod ui;+mod util;++use std::io::IsTerminal;+use std::path::PathBuf;+use std::process::ExitCode;+use std::sync::Arc;++use anyhow::Context;+use clap::{Args, Parser, Subcommand};+use serde::Serialize;++use crate::api::{ApiError, ApiResult};+use crate::config::{Paths, display_path};+use crate::fleet::Engine;++/// A fast native dashboard for your fleet of self-hosted GitHub Actions runners,+/// built to be driven by AI agents too (`openrunner mcp`, or any command with --json).+#[derive(Parser)]+#[command(name = "openrunner", version, about, args_conflicts_with_subcommands = true)]+struct Cli {+ #[command(subcommand)]+ command: Option<Command>,++ #[command(flatten)]+ open: OpenArgs,+}++#[derive(Subcommand)]+enum Command {+ /// Open the dashboard window (the default)+ Open(OpenArgs),+ /// Fleet overview: counts, GitHub state, machines, and what needs attention+ Status(StatusArgs),+ /// List machines with resources and runner summaries+ Machines(AgentArgs),+ /// Everything about one machine: runners, diagnostics, resources+ Machine(MachineArgs),+ /// Add a machine to fleet.toml (and check it)+ AddMachine(AddMachineArgs),+ /// Remove a machine from fleet.toml (nothing on the machine changes)+ RemoveMachine(MachineArgs),+ /// List runners+ Runners(RunnersArgs),+ /// Queued and running self-hosted jobs+ Jobs(AgentArgs),+ /// Install runners on a machine and register them with GitHub+ Install(InstallArgs),+ /// Start, stop, restart, show logs for, or remove a runner+ Runner(RunnerArgs),+ /// Watch GitHub orgs or repos (owner/name) for live runner status and jobs+ Watch(ScopesArgs),+ /// Stop watching GitHub orgs or repos+ Unwatch(ScopesArgs),+ /// Show or change settings+ Settings(SettingsArgs),+ /// Host aliases from ~/.ssh/config, for add-machine+ SshHosts(AgentArgs),+ /// Agent workspaces: persistent work environments on your machines+ #[command(alias = "ws", subcommand)]+ Workspace(WorkspaceCommand),+ /// Run the MCP server on stdio for AI agents (Claude Code, Codex, ...)+ Mcp(McpArgs),+ /// Check every machine once and print a fleet report+ Check(CheckArgs),+ /// Write a starter fleet.toml+ Init(InitArgs),+ /// Print where OpenRunner keeps its files+ Paths(CommonArgs),+}++#[derive(Args, Clone)]+struct CommonArgs {+ /// Config directory [default: ~/.config/openrunner, or $OPENRUNNER_HOME]+ #[arg(long, value_name = "DIR")]+ config_dir: Option<PathBuf>,++ /// Inventory file [default: <config-dir>/fleet.toml]+ #[arg(long, short = 'f', value_name = "FILE")]+ inventory: Option<PathBuf>,+}++impl CommonArgs {+ fn paths(&self) -> Paths {+ Paths::resolve(self.config_dir.clone(), self.inventory.clone())+ }+}++#[derive(Args, Clone)]+struct OpenArgs {+ #[command(flatten)]+ common: CommonArgs,++ /// Run against a simulated fleet instead of your real machines+ #[arg(long)]+ demo: bool,++ /// Open a specific view at launch (for screenshots and debugging), e.g.+ /// "jobs", "settings", "machine:<id>", "runner:<id>", "install:<machine-id>", "add-machine", "logs:<runner-id>"+ #[arg(long, hide = true, value_name = "VIEW")]+ view: Option<String>,+}++/// Flags every agent-facing command takes.+#[derive(Args, Clone)]+struct AgentArgs {+ #[command(flatten)]+ common: CommonArgs,++ /// Use a simulated fleet (safe to experiment with; nothing touches real machines or GitHub)+ #[arg(long)]+ demo: bool,++ /// Print machine-readable JSON on stdout (errors as {"error": {...}})+ #[arg(long)]+ json: bool,+}++#[derive(Args)]+struct StatusArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Re-check every machine over ssh and sync GitHub first+ #[arg(long)]+ refresh: bool,+}++#[derive(Args)]+struct MachineArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Machine id (e.g. mac-studio) or name+ machine_id: String,+}++#[derive(Args)]+struct AddMachineArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Display name, e.g. "Mac Studio"+ #[arg(long)]+ name: String,++ /// ssh destination (user@host, an ~/.ssh/config alias) or "local"+ #[arg(long)]+ host: String,++ /// Don't check the machine after adding it+ #[arg(long)]+ no_check: bool,+}++#[derive(Args)]+struct RunnersArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Only runners on this machine+ #[arg(long, value_name = "ID")]+ machine: Option<String>,++ /// Only runners in this state+ #[arg(long, value_parser = ["working", "idle", "offline", "unknown"])]+ state: Option<String>,+}++#[derive(Args)]+struct InstallArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Machine to install on+ machine_id: String,++ /// GitHub org or owner/repo to register with (optional when exactly one is watched)+ #[arg(long)]+ scope: Option<String>,++ /// How many runners (named <machine-id>-01, -02, ...)+ #[arg(long, conflicts_with = "name")]+ count: Option<usize>,++ /// Runner name (repeat for several)+ #[arg(long = "name", value_name = "NAME")]+ name: Vec<String>,++ /// Extra label (repeat for several)+ #[arg(long = "label", value_name = "LABEL")]+ label: Vec<String>,++ /// Org runner group+ #[arg(long, value_name = "GROUP")]+ group: Option<String>,++ /// How the runners run: auto (service, else docker, else background), service, background, docker+ #[arg(long, value_name = "MODE", default_value = "auto")]+ mode: String,++ /// Docker image for --mode docker [default: ghcr.io/actions/actions-runner:<latest runner version>]+ #[arg(long, value_name = "IMAGE")]+ image: Option<String>,++ /// With --mode docker: give jobs the host's Docker socket (root-equivalent; trusted workflows only)+ #[arg(long)]+ docker_socket: bool,++ /// Same as --mode background (runs run.sh; won't survive a reboot)+ #[arg(long, conflicts_with = "mode")]+ no_service: bool,++ /// Return right away with the operation id+ #[arg(long)]+ no_wait: bool,++ /// Seconds to wait+ #[arg(long, default_value_t = 900)]+ timeout: u64,+}++#[derive(Args)]+struct RunnerArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// start, stop, restart, logs or remove+ #[arg(value_parser = ["start", "stop", "restart", "logs", "remove"])]+ action: String,++ /// Runner id (<machine-id>/<name>, github/<name>) or a unique runner name+ runner_id: String,++ /// With remove: also delete the runner's folder+ #[arg(long)]+ delete_files: bool,++ /// Return right away with the operation id+ #[arg(long)]+ no_wait: bool,++ /// Seconds to wait+ #[arg(long, default_value_t = 180)]+ timeout: u64,+}++#[derive(Args)]+struct ScopesArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Orgs (acme) or repos (acme/api)+ #[arg(required = true)]+ scopes: Vec<String>,+}++#[derive(Args)]+struct SettingsArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// GitHub poll interval in seconds+ #[arg(long, value_name = "SECS")]+ poll: Option<u32>,++ /// Recently pushed repos per org to scan for jobs+ #[arg(long, value_name = "N")]+ scan_repos: Option<u32>,++ /// Automatic machine check interval in minutes (0 = off)+ #[arg(long, value_name = "MINS")]+ check_interval: Option<u32>,++ /// GitHub REST API base (GitHub Enterprise Server)+ #[arg(long, value_name = "URL")]+ api_url: Option<String>,+}++#[derive(Subcommand)]+enum WorkspaceCommand {+ /// Create a workspace on a machine (optionally cloning a repo)+ Create(WsCreateArgs),+ /// List workspaces+ #[command(alias = "list")]+ Ls(AgentArgs),+ /// One workspace with its recent commands+ Show(WsIdArgs),+ /// Run a command in a workspace; exits with the command's exit code+ Exec(WsExecArgs),+ /// Print a file from a workspace+ Cat(WsPathArgs),+ /// Write stdin to a file in a workspace+ Write(WsWriteArgs),+ /// List files in a workspace+ Files(WsFilesArgs),+ /// git status and diff of a workspace+ Changes(WsIdArgs),+ /// Copy a local folder to a workspace (--push) or back (--pull) with rsync+ Sync(WsSyncArgs),+ /// Open an interactive shell in a workspace+ Shell(WsShellArgs),+ /// Destroy a workspace (stops its background commands, deletes its folder)+ #[command(alias = "destroy")]+ Rm(WsRmArgs),+ /// Allow (or with --off, forbid) workspaces on a machine+ Allow(WsAllowArgs),+}++#[derive(Args)]+struct WsCreateArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Machine id; omit to pick the least-loaded machine that allows workspaces+ #[arg(long, value_name = "ID")]+ machine: Option<String>,++ /// When picking: platform prefix (linux, linux-x64, darwin-arm64, windows)+ #[arg(long)]+ platform: Option<String>,++ /// Short label (defaults to the repo name)+ #[arg(long)]+ name: Option<String>,++ /// Git URL or owner/repo to clone+ #[arg(long)]+ repo: Option<String>,++ /// Branch, tag or commit to check out+ #[arg(long = "ref", value_name = "REF")]+ git_ref: Option<String>,++ /// New branch to create after checkout+ #[arg(long)]+ branch: Option<String>,++ /// Run in a fresh Docker container (shorthand for --isolation docker)+ #[arg(long, conflicts_with = "isolation")]+ docker: bool,++ /// "host" (default) or "docker"+ #[arg(long, value_name = "ISOLATION")]+ isolation: Option<String>,++ /// Docker image for docker workspaces, e.g. node:22+ #[arg(long, value_name = "IMAGE")]+ image: Option<String>,++ /// Share the machine's Docker socket with the container (docker-in-docker)+ #[arg(long)]+ docker_socket: bool,+}++#[derive(Args)]+struct WsIdArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Workspace id (ws-…) or unique name+ workspace_id: String,+}++#[derive(Args)]+struct WsExecArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Workspace id (ws-…) or unique name+ workspace_id: String,++ /// Folder relative to the workspace to run in+ #[arg(long)]+ cwd: Option<String>,++ /// Environment variable (repeat for several)+ #[arg(long = "env", value_name = "KEY=VALUE")]+ env: Vec<String>,++ /// Kill the command after this many seconds (max 3600)+ #[arg(long, default_value_t = 600)]+ timeout: u64,++ /// Start it detached and print its pid and log file+ #[arg(long)]+ background: bool,++ /// The command, after `--`. One argument is used as a shell string; several are quoted and joined.+ #[arg(last = true, required = true, value_name = "COMMAND")]+ command: Vec<String>,+}++#[derive(Args)]+struct WsPathArgs {+ #[command(flatten)]+ agent: AgentArgs,++ workspace_id: String,++ /// Path relative to the workspace+ path: String,++ /// Read at most this many bytes+ #[arg(long, value_name = "BYTES")]+ max_bytes: Option<usize>,+}++#[derive(Args)]+struct WsWriteArgs {+ #[command(flatten)]+ agent: AgentArgs,++ workspace_id: String,++ /// Path relative to the workspace+ path: String,++ /// Append instead of replacing+ #[arg(long)]+ append: bool,+}++#[derive(Args)]+struct WsFilesArgs {+ #[command(flatten)]+ agent: AgentArgs,++ workspace_id: String,++ /// Folder relative to the workspace+ path: Option<String>,++ /// How deep to list+ #[arg(long, default_value_t = 2)]+ depth: u32,+}++#[derive(Args)]+#[command(group(clap::ArgGroup::new("direction").required(true).args(["push", "pull"])))]+struct WsSyncArgs {+ #[command(flatten)]+ agent: AgentArgs,++ workspace_id: String,++ /// Folder on this computer+ local_path: String,++ /// Copy the local folder into the workspace+ #[arg(long)]+ push: bool,++ /// Copy the workspace into the local folder+ #[arg(long)]+ pull: bool,++ /// Also delete files on the receiving side that the sender doesn't have+ #[arg(long)]+ delete: bool,+}++#[derive(Args)]+struct WsShellArgs {+ #[command(flatten)]+ common: CommonArgs,++ /// Use a simulated fleet (prints the command instead of running it)+ #[arg(long)]+ demo: bool,++ workspace_id: String,+}++#[derive(Args)]+struct WsRmArgs {+ #[command(flatten)]+ agent: AgentArgs,++ workspace_id: String,++ /// Keep the folder on the machine; only forget the workspace+ #[arg(long)]+ keep_files: bool,+}++#[derive(Args)]+struct WsAllowArgs {+ #[command(flatten)]+ agent: AgentArgs,++ /// Machine id+ machine_id: String,++ /// Forbid workspaces instead+ #[arg(long)]+ off: bool,+}++#[derive(Args)]+struct McpArgs {+ #[command(flatten)]+ common: CommonArgs,++ /// Serve a simulated fleet+ #[arg(long)]+ demo: bool,++ /// Print setup snippets for Claude Code, Codex and other MCP clients, then exit+ #[arg(long)]+ print_config: bool,+}++#[derive(Args)]+struct CheckArgs {+ #[command(flatten)]+ common: CommonArgs,++ /// Use a simulated fleet+ #[arg(long)]+ demo: bool,++ /// Print the full snapshot as JSON+ #[arg(long)]+ json: bool,++ /// Skip GitHub; use only what the machines report+ #[arg(long)]+ no_github: bool,+}++#[derive(Args)]+struct InitArgs {+ #[command(flatten)]+ common: CommonArgs,++ /// Overwrite an existing fleet.toml+ #[arg(long)]+ force: bool,+}++fn main() -> ExitCode {+ // Logs always go to stderr: stdout is reserved for --json output and MCP messages.+ tracing_subscriber::fmt()+ .with_env_filter(+ tracing_subscriber::EnvFilter::try_from_env("OPENRUNNER_LOG").unwrap_or_else(|_| "openrunner=info".into()),+ )+ .with_writer(std::io::stderr)+ .with_ansi(std::io::stderr().is_terminal())+ .with_target(false)+ .without_time()+ .init();++ let cli = Cli::parse();+ let runtime = match tokio::runtime::Runtime::new().context("starting the async runtime") {+ Ok(rt) => rt,+ Err(e) => {+ eprintln!("error: {e:#}");+ return ExitCode::FAILURE;+ }+ };+ let code = match cli.command {+ None => open(cli.open, &runtime),+ Some(Command::Open(args)) => open(args, &runtime),+ Some(Command::Status(a)) => {+ let req = api::StatusRequest { refresh: a.refresh };+ run(&runtime, &a.agent, async move |e| api::status(&e, req, api::Surface::Cli).await, cli::status)+ }+ Some(Command::Machines(a)) => run(&runtime, &a, async move |e| api::machines(&e).await, |m| cli::machines(m)),+ Some(Command::Machine(a)) => {+ let req = api::MachineRequest { machine_id: a.machine_id };+ run(&runtime, &a.agent, async move |e| api::machine(&e, req).await, cli::machine)+ }+ Some(Command::AddMachine(a)) => {+ let req = api::AddMachineRequest { name: a.name, host: a.host, check: !a.no_check };+ run(&runtime, &a.agent, async move |e| api::add_machine(&e, req, api::Surface::Cli).await, cli::added_machine)+ }+ Some(Command::RemoveMachine(a)) => {+ let req = api::MachineRequest { machine_id: a.machine_id };+ run(&runtime, &a.agent, async move |e| api::remove_machine(&e, req).await, |m| {+ format!("Removed {} ({}) from fleet.toml. Nothing on the machine changed.\n", m.name, m.id)+ })+ }+ Some(Command::Runners(a)) => {+ let req = api::RunnersRequest { machine_id: a.machine, state: a.state };+ run(&runtime, &a.agent, async move |e| api::runners(&e, req).await, |r| cli::runners(r))+ }+ Some(Command::Jobs(a)) => run(&runtime, &a, async move |e| api::jobs(&e, api::Surface::Cli).await, cli::jobs),+ Some(Command::Install(a)) => {+ let req = api::InstallRunnersRequest {+ machine_id: a.machine_id,+ scope: a.scope,+ names: a.name,+ count: a.count,+ labels: a.label,+ runner_group: a.group,+ as_service: !a.no_service,+ mode: Some(if a.no_service { "background".into() } else { a.mode }),+ image: a.image,+ docker_socket: a.docker_socket,+ wait: !a.no_wait,+ timeout_secs: Some(a.timeout),+ };+ run(&runtime, &a.agent, async move |e| api::install_runners(&e, req, api::Surface::Cli, stream_line).await, cli::action)+ }+ Some(Command::Runner(a)) => {+ let action = match a.action.parse::<api::ActionName>() {+ Ok(action) => action,+ Err(e) => return ExitCode::from(report_error(&a.agent, &e)),+ };+ let req = api::RunnerActionRequest {+ runner_id: a.runner_id,+ action,+ delete_files: a.delete_files,+ wait: !a.no_wait,+ timeout_secs: Some(a.timeout),+ };+ run(&runtime, &a.agent, async move |e| api::runner_action(&e, req, api::Surface::Cli, stream_line).await, cli::action)+ }+ Some(Command::Watch(a)) => {+ let req = api::GitHubScopesRequest { add: a.scopes, remove: vec![] };+ run(&runtime, &a.agent, async move |e| api::github_scopes(&e, req).await, cli::scopes)+ }+ Some(Command::Unwatch(a)) => {+ let req = api::GitHubScopesRequest { add: vec![], remove: a.scopes };+ run(&runtime, &a.agent, async move |e| api::github_scopes(&e, req).await, cli::scopes)+ }+ Some(Command::Settings(a)) => {+ let req = api::UpdateSettingsRequest {+ github_poll_seconds: a.poll,+ scan_repos: a.scan_repos,+ check_interval_minutes: a.check_interval,+ api_url: a.api_url,+ };+ let changing = req.github_poll_seconds.is_some()+ || req.scan_repos.is_some()+ || req.check_interval_minutes.is_some()+ || req.api_url.is_some();+ run(+ &runtime,+ &a.agent,+ async move |e| if changing { api::update_settings(&e, req) } else { Ok(api::settings(&e)) },+ cli::settings,+ )+ }+ Some(Command::SshHosts(a)) => run(&runtime, &a, async move |_| Ok(api::ssh_hosts()), |h| {+ if h.hosts.is_empty() { "No hosts in ~/.ssh/config.\n".into() } else { format!("{}\n", h.hosts.join("\n")) }+ }),+ Some(Command::Workspace(cmd)) => workspace(cmd, &runtime),+ Some(Command::Mcp(a)) => mcp(a, &runtime),+ Some(Command::Check(args)) => {+ let _guard = runtime.enter();+ let engine = Engine::new(args.common.paths(), args.demo);+ let snapshot = runtime.block_on(engine.check_once(!args.no_github));+ if args.json {+ println!("{}", serde_json::to_string_pretty(&snapshot).unwrap_or_default());+ } else {+ let color = std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();+ print!("{}", fleet::report::render(&snapshot, color));+ }+ 0+ }+ Some(Command::Init(args)) => init(args),+ Some(Command::Paths(args)) => {+ let p = args.paths();+ println!("config dir {}", display_path(&p.dir));+ println!("inventory {}", display_path(&p.inventory));+ println!("settings {}", display_path(&p.settings));+ println!("state {}", display_path(&p.state));+ 0+ }+ };+ ExitCode::from(code)+}++fn open(args: OpenArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ // The engine runs on tokio; the window runs on GPUI's main-thread executor.+ let _guard = runtime.enter();+ let engine = Engine::new(args.common.paths(), args.demo);+ engine.start();+ if engine.is_demo() {+ tracing::info!("demo mode: simulated fleet, nothing is read from or written to disk");+ } else {+ tracing::info!("inventory {}", display_path(&engine.paths().inventory));+ }+ #[cfg(feature = "gui")]+ {+ ui::run(engine, args.view);+ 0+ }+ #[cfg(not(feature = "gui"))]+ {+ let _ = (engine, args.view);+ eprintln!("This build of OpenRunner has no window (built without the `gui` feature).");+ eprintln!("Use the commands (`openrunner --help`) or the MCP server (`openrunner mcp`).");+ 2+ }+}++/// Runs one agent-facing command: JSON or human output on stdout, errors with a+/// code (0 ok, 1 failed, 2 bad input / not found).+fn run<T: Serialize>(+ runtime: &tokio::runtime::Runtime,+ args: &AgentArgs,+ f: impl AsyncFnOnce(Arc<Engine>) -> ApiResult<T>,+ human: impl FnOnce(&T) -> String,+) -> u8 {+ let _guard = runtime.enter();+ let engine = Engine::new(args.common.paths(), args.demo);+ match runtime.block_on(f(engine)) {+ Ok(value) => {+ if args.json {+ println!("{}", serde_json::to_string_pretty(&value).unwrap_or_default());+ } else {+ print!("{}", human(&value));+ }+ 0+ }+ Err(e) => report_error(args, &e),+ }+}++fn report_error(args: &AgentArgs, e: &ApiError) -> u8 {+ if args.json {+ println!("{}", serde_json::to_string_pretty(&serde_json::json!({ "error": e })).unwrap_or_default());+ } else {+ eprint!("{}", cli::error(e));+ }+ e.exit_code()+}++/// Operation output streams to stderr while a command waits.+fn stream_line(line: &str) {+ eprintln!(" {line}");+}++/// Who the CLI records as a workspace's owner and a command's author.+const CLI_OWNER: &str = "cli";+const CLI: api::Surface = api::Surface::Cli;++fn workspace(cmd: WorkspaceCommand, runtime: &tokio::runtime::Runtime) -> u8 {+ match cmd {+ WorkspaceCommand::Create(a) => {+ let req = api::WorkspaceCreateRequest {+ machine_id: a.machine,+ platform: a.platform,+ name: a.name,+ repo: a.repo,+ git_ref: a.git_ref,+ branch: a.branch,+ isolation: if a.docker { Some("docker".into()) } else { a.isolation },+ image: a.image,+ docker_socket: a.docker_socket,+ };+ run(runtime, &a.agent, async move |e| api::workspace_create(&e, req, CLI_OWNER, CLI).await, cli::workspace_created)+ }+ WorkspaceCommand::Ls(a) => run(runtime, &a, async move |e| Ok(api::workspaces_list(&e)), cli::workspaces),+ WorkspaceCommand::Show(a) => {+ let req = api::WorkspaceRequest { workspace_id: a.workspace_id };+ run(runtime, &a.agent, async move |e| api::workspace_get(&e, req, CLI), cli::workspace)+ }+ WorkspaceCommand::Exec(a) => workspace_exec(a, runtime),+ WorkspaceCommand::Cat(a) => {+ let req = api::WorkspaceReadRequest { workspace_id: a.workspace_id, path: a.path, max_bytes: a.max_bytes };+ run(runtime, &a.agent, async move |e| api::workspace_read_file(&e, req, CLI).await, cli::file)+ }+ WorkspaceCommand::Write(a) => {+ let mut content = String::new();+ if let Err(e) = std::io::Read::read_to_string(&mut std::io::stdin(), &mut content) {+ return report_error(&a.agent, &ApiError::invalid(format!("Couldn't read stdin as UTF-8 text: {e}")));+ }+ let req = api::WorkspaceWriteRequest { workspace_id: a.workspace_id, path: a.path, content, append: a.append };+ run(runtime, &a.agent, async move |e| api::workspace_write_file(&e, req, CLI).await, |w| {+ format!("Wrote {} ({} bytes) in {}.\n", w.path, w.size, w.workspace_id)+ })+ }+ WorkspaceCommand::Files(a) => {+ let req = api::WorkspaceFilesRequest { workspace_id: a.workspace_id, path: a.path, depth: Some(a.depth) };+ run(runtime, &a.agent, async move |e| api::workspace_list_files(&e, req, CLI).await, cli::files)+ }+ WorkspaceCommand::Changes(a) => {+ let req = api::WorkspaceRequest { workspace_id: a.workspace_id };+ run(runtime, &a.agent, async move |e| api::workspace_changes(&e, req, CLI).await, |c| {+ let mut out = c.changes.clone();+ if !out.ends_with('\n') {+ out.push('\n');+ }+ out+ })+ }+ WorkspaceCommand::Sync(a) => {+ let direction = if a.push { fleet::workspaces::SyncDirection::Push } else { fleet::workspaces::SyncDirection::Pull };+ let req = api::WorkspaceSyncRequest { workspace_id: a.workspace_id, local_path: a.local_path, direction, delete: a.delete };+ run(runtime, &a.agent, async move |e| api::workspace_sync(&e, req, CLI).await, |r| {+ let mut out = r.summary.clone();+ if !out.ends_with('\n') {+ out.push('\n');+ }+ out+ })+ }+ WorkspaceCommand::Shell(a) => workspace_shell(a, runtime),+ WorkspaceCommand::Rm(a) => {+ let req = api::WorkspaceDestroyRequest { workspace_id: a.workspace_id, keep_files: a.keep_files };+ run(runtime, &a.agent, async move |e| api::workspace_destroy(&e, req, CLI).await, |d| {+ if d.kept_files {+ format!("Forgot {}; its folder is still on the machine.\n", d.workspace_id)+ } else {+ format!("Destroyed {}.\n", d.workspace_id)+ }+ })+ }+ WorkspaceCommand::Allow(a) => {+ let req = api::WorkspaceAllowRequest { machine_id: a.machine_id, allowed: !a.off };+ run(runtime, &a.agent, async move |e| api::workspace_allow(&e, req, CLI), |r| {+ format!("Workspaces are now {} on {}.\n", if r.workspaces_allowed { "allowed" } else { "off" }, r.machine_id)+ })+ }+ }+}++/// `workspace exec`: passes the command's output through and exits with its exit code+/// (124 when it timed out, like `timeout(1)`), so it composes in scripts.+fn workspace_exec(a: WsExecArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ let mut env = std::collections::BTreeMap::new();+ for pair in &a.env {+ match pair.split_once('=') {+ Some((k, v)) => {+ env.insert(k.to_string(), v.to_string());+ }+ None => return report_error(&a.agent, &ApiError::invalid(format!("--env needs KEY=VALUE, got \"{pair}\"."))),+ }+ }+ let req = api::WorkspaceExecRequest {+ workspace_id: a.workspace_id,+ command: shell_join(&a.command),+ cwd: a.cwd,+ env,+ timeout_secs: Some(a.timeout),+ background: a.background,+ };+ let _guard = runtime.enter();+ let engine = Engine::new(a.agent.common.paths(), a.agent.demo);+ match runtime.block_on(api::workspace_exec(&engine, req, CLI_OWNER, CLI)) {+ Ok(out) => {+ if a.agent.json {+ println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());+ } else {+ use std::io::Write;+ // Captured output loses its final newline; put it back so the shell prompt+ // (or the next line) doesn't run into the last line of output.+ let newline = |s: &str| if s.is_empty() || s.ends_with('\n') { "" } else { "\n" };+ let _ = write!(std::io::stdout(), "{}{}", out.stdout, newline(&out.stdout));+ let _ = write!(std::io::stderr(), "{}{}", out.stderr, newline(&out.stderr));+ if let Some(log) = &out.log_path {+ eprintln!("started in the background (pid {}), log: {log}", out.background_pid.map(|p| p.to_string()).unwrap_or_else(|| "?".into()));+ } else if out.timed_out {+ eprintln!("openrunner: timed out after {}s", out.duration_ms / 1000);+ } else if out.truncated {+ eprintln!("openrunner: output was truncated (the middle was dropped)");+ }+ }+ match (out.exit_code, out.timed_out) {+ (_, true) => 124,+ (Some(code), _) => u8::try_from(code).unwrap_or(1),+ (None, _) => 0,+ }+ }+ Err(e) => report_error(&a.agent, &e),+ }+}++/// Joins `exec -- cmd args...`: a single argument is taken as a shell string+/// ("make test && make lint"); several are quoted as needed and joined.+fn shell_join(args: &[String]) -> String {+ if let [one] = args {+ return one.clone();+ }+ args.iter()+ .map(|a| {+ let safe = !a.is_empty() && a.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:@%+,".contains(c));+ if safe { a.clone() } else { format!("'{}'", a.replace('\'', r"'\''")) }+ })+ .collect::<Vec<_>>()+ .join(" ")+}++/// `workspace shell`: replaces this process with an interactive shell in the workspace.+fn workspace_shell(a: WsShellArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ let agent = AgentArgs { common: a.common.clone(), demo: a.demo, json: false };+ let _guard = runtime.enter();+ let engine = Engine::new(a.common.paths(), a.demo);+ let w = match api::workspace_get(&engine, api::WorkspaceRequest { workspace_id: a.workspace_id }, CLI) {+ Ok(w) => w,+ Err(e) => return report_error(&agent, &e),+ };+ if a.demo {+ eprintln!("demo: would run: {}", w.shell);+ return 0;+ }+ eprintln!("{} on {} · {}", w.id, w.machine_name, w.path);+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ let err = std::process::Command::new("/bin/sh").arg("-c").arg(&w.shell).exec();+ eprintln!("error: couldn't start the shell: {err}");+ 1+ }+ #[cfg(not(unix))]+ {+ match std::process::Command::new("cmd").args(["/C", &w.shell]).status() {+ Ok(status) => status.code().and_then(|c| u8::try_from(c).ok()).unwrap_or(1),+ Err(err) => {+ eprintln!("error: couldn't start the shell: {err}");+ 1+ }+ }+ }+}++fn mcp(args: McpArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ if args.print_config {+ print!("{}", mcp::print_config());+ return 0;+ }+ let _guard = runtime.enter();+ // No background loops: tools refresh what they need on demand.+ let engine = Engine::new(args.common.paths(), args.demo);+ match runtime.block_on(mcp::serve_stdio(engine)) {+ Ok(()) => 0,+ Err(e) => {+ tracing::error!("mcp: {e:#}");+ 1+ }+ }+}++fn init(args: InitArgs) -> u8 {+ let paths = args.common.paths();+ if paths.inventory.exists() && !args.force {+ eprintln!("error: {} already exists (use --force to overwrite)", display_path(&paths.inventory));+ return 2;+ }+ if let Err(e) = config::write_atomic(&paths.inventory, config::default_inventory().as_bytes()) {+ eprintln!("error: {e:#}");+ return 1;+ }+ println!("Wrote {}", display_path(&paths.inventory));+ println!("Add your machines, then run `openrunner` to open the dashboard.");+ 0+}++#[cfg(test)]+mod tests {+ use super::*;+ use clap::CommandFactory;++ #[test]+ fn cli_definition_is_valid() {+ Cli::command().debug_assert();+ }++ #[test]+ fn joins_exec_commands() {+ let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();+ assert_eq!(shell_join(&v(&["make test && make lint"])), "make test && make lint");+ assert_eq!(shell_join(&v(&["echo", "hello world", "it's"])), "echo 'hello world' 'it'\\''s'");+ assert_eq!(shell_join(&v(&["cargo", "test", "--release"])), "cargo test --release");+ }++ #[test]+ fn parses_workspace_commands() {+ let cli = Cli::try_parse_from(["openrunner", "ws", "exec", "ws-abc123", "--env", "A=1", "--", "npm", "test"]).unwrap();+ match cli.command {+ Some(Command::Workspace(WorkspaceCommand::Exec(a))) => {+ assert_eq!(a.workspace_id, "ws-abc123");+ assert_eq!(a.command, vec!["npm", "test"]);+ assert_eq!(a.env, vec!["A=1"]);+ }+ _ => panic!("expected workspace exec"),+ }+ assert!(Cli::try_parse_from(["openrunner", "workspace", "sync", "ws-1", "."]).is_err(), "needs --push or --pull");+ assert!(Cli::try_parse_from(["openrunner", "workspace", "sync", "ws-1", ".", "--push", "--pull"]).is_err());+ assert!(Cli::try_parse_from(["openrunner", "workspace", "create", "--platform", "linux", "--repo", "acme/api", "--ref", "main", "--json"]).is_ok());+ }+}diff --git a/src/mcp.rs b/src/mcp.rsnew file mode 100644index 0000000..401b081--- /dev/null+++ b/src/mcp.rs@@ -0,0 +1,716 @@+//! `openrunner mcp`: a Model Context Protocol server over stdio, so agents+//! (Claude Code, Codex, any MCP client) can inspect and run the fleet.+//!+//! Transport: newline-delimited JSON-RPC 2.0 on stdin/stdout. Stdout carries+//! protocol messages only; logs go to stderr. Requests are handled+//! concurrently, so a long install doesn't block a `ping` or a status call.++use std::sync::{Arc, Mutex};++use serde::Serialize;+use serde::de::DeserializeOwned;+use serde_json::{Value, json};+use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};+use tokio::sync::mpsc;++use crate::api::{self, ApiError, Surface};+use crate::fleet::Engine;++const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];++const INSTRUCTIONS: &str = "\+OpenRunner manages a fleet of self-hosted GitHub Actions runners: the machines that host them \+(reached with the system ssh, or directly for host \"local\") and the runners on each.++Start with fleet_status and read its `attention` list first; it names the problems worth fixing \+and the machine/runner they're about. Ids: machines are slugs like \"mac-studio\"; runners are \+\"<machine-id>/<runner-name>\", or \"github/<name>\" for a runner GitHub knows but no machine lists.++Read-only: fleet_status, get_machine, list_runners, list_jobs, check_machines (runs a read-only \+check over ssh), get_operation, list_operations, get_settings, list_ssh_hosts.+Changes things: add_machine / remove_machine edit fleet.toml only. install_runners and \+runner_action run commands on real machines and register or deregister runners on GitHub; \+confirm with the user before stopping, removing or installing unless they asked for exactly that.++install_runners and runner_action wait for the operation by default and return a log tail; pass \+wait=false to get an operation_id and poll get_operation. Errors have a `code` (not_found, \+invalid, busy, github, unreachable, operation_failed, internal) and often a `hint` with the exact \+command that fixes the problem; show hints to the user rather than guessing.++Workspaces: you can also check out one of the user's machines as your own work environment. \+workspace_create makes a persistent folder there (optionally cloning a repo at a ref) and returns \+a workspace_id; workspace_exec runs shell commands in it with the machine user's login environment \+(use background=true for servers, then read the log file it returns); workspace_read_file, \+workspace_write_file and workspace_list_files work with its files; workspace_changes shows git \+status and diff; workspace_sync moves code between the user's local checkout and the workspace. \+Prefer one workspace per task, reuse it across steps, and call workspace_destroy when the task is \+done: nothing is deleted automatically. Commands run as the user on a real machine, so don't do \+anything there you wouldn't do in their own terminal without asking.";++/// Per-connection state: who the client is, so workspaces and commands record their owner.+#[derive(Default)]+pub struct Session {+ client: Mutex<Option<String>>,+}++impl Session {+ /// The MCP client's name from `initialize` (e.g. "claude-code"), else "mcp".+ pub fn owner(&self) -> String {+ self.client.lock().unwrap().clone().unwrap_or_else(|| "mcp".into())+ }+}++/// Serves MCP on this process's stdin/stdout until stdin closes.+pub async fn serve_stdio(engine: Arc<Engine>) -> anyhow::Result<()> {+ let stdin = tokio::io::BufReader::new(tokio::io::stdin());+ serve(engine, stdin, tokio::io::stdout()).await+}++pub async fn serve<R, W>(engine: Arc<Engine>, mut reader: R, mut writer: W) -> anyhow::Result<()>+where+ R: AsyncBufRead + Unpin,+ W: AsyncWrite + Unpin + Send + 'static,+{+ let session = Arc::new(Session::default());+ let (tx, mut rx) = mpsc::unbounded_channel::<Value>();+ let writer_task = tokio::spawn(async move {+ while let Some(msg) = rx.recv().await {+ let mut line = serde_json::to_vec(&msg).unwrap_or_default();+ line.push(b'\n');+ if writer.write_all(&line).await.is_err() || writer.flush().await.is_err() {+ break;+ }+ }+ });++ let mut line = String::new();+ loop {+ line.clear();+ if reader.read_line(&mut line).await? == 0 {+ break;+ }+ let text = line.trim();+ if text.is_empty() {+ continue;+ }+ let msg: Value = match serde_json::from_str(text) {+ Ok(v) => v,+ Err(e) => {+ let _ = tx.send(error_response(Value::Null, -32700, &format!("Parse error: {e}")));+ continue;+ }+ };+ let Some(obj) = msg.as_object() else {+ let _ = tx.send(error_response(Value::Null, -32600, "Expected a JSON-RPC object"));+ continue;+ };+ let method = obj.get("method").and_then(Value::as_str).unwrap_or_default().to_string();+ let params = obj.get("params").cloned().unwrap_or(Value::Null);+ let Some(id) = obj.get("id").cloned() else {+ // Notifications (initialized, cancelled, ...) need no reply.+ continue;+ };+ if method.is_empty() {+ // A response to something we never send; ignore.+ continue;+ }+ let engine = engine.clone();+ let session = session.clone();+ let tx = tx.clone();+ tokio::spawn(async move {+ let reply = match handle(&engine, &session, &method, params).await {+ Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),+ Err((code, message)) => error_response(id, code, &message),+ };+ let _ = tx.send(reply);+ });+ }+ drop(tx);+ let _ = writer_task.await;+ Ok(())+}++fn error_response(id: Value, code: i64, message: &str) -> Value {+ json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })+}++async fn handle(engine: &Arc<Engine>, session: &Session, method: &str, params: Value) -> Result<Value, (i64, String)> {+ match method {+ "initialize" => {+ let client = params.pointer("/clientInfo/name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty());+ if let Some(name) = client {+ *session.client.lock().unwrap() = Some(name.chars().take(64).collect());+ }+ let requested = params.get("protocolVersion").and_then(Value::as_str).unwrap_or_default();+ let version = PROTOCOL_VERSIONS.iter().find(|v| **v == requested).copied().unwrap_or(PROTOCOL_VERSIONS[0]);+ Ok(json!({+ "protocolVersion": version,+ "capabilities": { "tools": { "listChanged": false } },+ "serverInfo": { "name": "openrunner", "title": "OpenRunner", "version": env!("CARGO_PKG_VERSION") },+ "instructions": INSTRUCTIONS,+ }))+ }+ "ping" => Ok(json!({})),+ "tools/list" => Ok(json!({ "tools": tools() })),+ "tools/call" => {+ let name = params.get("name").and_then(Value::as_str).ok_or((-32602, "tools/call needs a tool name".to_string()))?;+ if !tools().iter().any(|t| t["name"] == name) {+ return Err((-32602, format!("Unknown tool: {name}")));+ }+ let args = params.get("arguments").cloned().filter(|a| !a.is_null()).unwrap_or_else(|| json!({}));+ Ok(call_tool(engine, session, name, args).await)+ }+ "resources/list" => Ok(json!({ "resources": [] })),+ "prompts/list" => Ok(json!({ "prompts": [] })),+ _ => Err((-32601, format!("Method not found: {method}"))),+ }+}++/// Runs a tool and wraps the outcome as an MCP tool result. Failures are+/// results with `isError: true`, not protocol errors, so the model sees them.+pub async fn call_tool(engine: &Arc<Engine>, session: &Session, name: &str, args: Value) -> Value {+ let outcome = dispatch(engine, session, name, args).await;+ match outcome {+ Ok(value) => {+ let text = readable_text(name, &value);+ tool_result(value, text, false)+ }+ Err(err) => tool_result(json!({ "error": err }), None, true),+ }+}++/// Plain text for results a model reads better unwrapped than as JSON: command+/// output, file contents, diffs. `structuredContent` always has the full object.+fn readable_text(tool: &str, v: &Value) -> Option<String> {+ let str_of = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default();+ match tool {+ "workspace_exec" => {+ let mut out = if let Some(pid) = v.get("background_pid").and_then(Value::as_u64) {+ format!("started in the background (pid {pid}), log: {}\n", str_of("log_path"))+ } else if v.get("timed_out").and_then(Value::as_bool) == Some(true) {+ format!("timed out after {} ms\n", v["duration_ms"])+ } else {+ format!("exit code: {} ({} ms)\n", v.get("exit_code").map(|c| c.to_string()).unwrap_or_else(|| "null".into()), v["duration_ms"])+ };+ if v.get("truncated").and_then(Value::as_bool) == Some(true) {+ out.push_str("(output truncated: the middle was dropped)\n");+ }+ for stream in ["stdout", "stderr"] {+ let text = str_of(stream);+ if !text.is_empty() {+ out.push_str(&format!("\n{stream}:\n```\n{}\n```\n", text.trim_end_matches('\n')));+ }+ }+ if let Some(next) = v.get("next").and_then(Value::as_str) {+ out.push_str(&format!("\n{next}\n"));+ }+ Some(out)+ }+ "workspace_read_file" => {+ let mut out = format!("{} ({} bytes{})\n", str_of("path"), v["size"], if v["truncated"] == true { ", truncated" } else { "" });+ if v["binary"] == true {+ out.push_str("(binary file; content not shown)\n");+ } else {+ out.push_str(&format!("```\n{}\n```\n", str_of("content").trim_end_matches('\n')));+ }+ Some(out)+ }+ "workspace_changes" => Some(str_of("changes").to_string()),+ _ => None,+ }+}++fn tool_result(value: Value, text: Option<String>, is_error: bool) -> Value {+ let text = text.unwrap_or_else(|| serde_json::to_string_pretty(&value).unwrap_or_default());+ json!({+ "content": [{ "type": "text", "text": text }],+ "structuredContent": value,+ "isError": is_error,+ })+}++fn args<T: DeserializeOwned>(value: Value) -> Result<T, ApiError> {+ serde_json::from_value(value).map_err(|e| ApiError::invalid(format!("Bad arguments: {e}")))+}++fn ok<T: Serialize>(value: T) -> Result<Value, ApiError> {+ serde_json::to_value(value).map_err(|e| ApiError::invalid(e.to_string()))+}++async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value) -> Result<Value, ApiError> {+ match name {+ "fleet_status" => ok(api::status(engine, args(a)?, Surface::Mcp).await?),+ "get_machine" => ok(api::machine(engine, args(a)?).await?),+ "list_runners" => ok(json!({ "runners": api::runners(engine, args(a)?).await? })),+ "list_jobs" => ok(api::jobs(engine, Surface::Mcp).await?),+ "check_machines" => ok(json!({ "machines": api::check(engine, args(a)?).await? })),+ "add_machine" => ok(api::add_machine(engine, args(a)?, Surface::Mcp).await?),+ "remove_machine" => ok(json!({ "removed": api::remove_machine(engine, args(a)?).await? })),+ "install_runners" => ok(api::install_runners(engine, args(a)?, Surface::Mcp, |_| {}).await?),+ "runner_action" => ok(api::runner_action(engine, args(a)?, Surface::Mcp, |_| {}).await?),+ "get_operation" => ok(api::operation(engine, args(a)?)?),+ "list_operations" => ok(json!({ "operations": api::operations(engine) })),+ "github_scopes" => ok(api::github_scopes(engine, args(a)?).await?),+ "get_settings" => ok(api::settings(engine)),+ "update_settings" => ok(api::update_settings(engine, args(a)?)?),+ "list_ssh_hosts" => ok(api::ssh_hosts()),+ "workspace_create" => ok(api::workspace_create(engine, args(a)?, &session.owner(), Surface::Mcp).await?),+ "workspace_list" => ok(api::workspaces_list(engine)),+ "workspace_get" => ok(api::workspace_get(engine, args(a)?, Surface::Mcp)?),+ "workspace_exec" => ok(api::workspace_exec(engine, args(a)?, &session.owner(), Surface::Mcp).await?),+ "workspace_read_file" => ok(api::workspace_read_file(engine, args(a)?, Surface::Mcp).await?),+ "workspace_write_file" => ok(api::workspace_write_file(engine, args(a)?, Surface::Mcp).await?),+ "workspace_list_files" => ok(api::workspace_list_files(engine, args(a)?, Surface::Mcp).await?),+ "workspace_changes" => ok(api::workspace_changes(engine, args(a)?, Surface::Mcp).await?),+ "workspace_sync" => ok(api::workspace_sync(engine, args(a)?, Surface::Mcp).await?),+ "workspace_destroy" => ok(api::workspace_destroy(engine, args(a)?, Surface::Mcp).await?),+ "workspace_allow" => ok(api::workspace_allow(engine, args(a)?, Surface::Mcp)?),+ other => Err(ApiError::not_found(format!("Unknown tool: {other}"))),+ }+}++fn annotations(title: &str, read_only: bool, destructive: bool, idempotent: bool, open_world: bool) -> Value {+ json!({+ "title": title,+ "readOnlyHint": read_only,+ "destructiveHint": destructive,+ "idempotentHint": idempotent,+ "openWorldHint": open_world,+ })+}++fn schema(properties: Value, required: &[&str]) -> Value {+ json!({ "type": "object", "properties": properties, "required": required, "additionalProperties": false })+}++const MACHINE_ID: &str = "Machine id (a slug like \"mac-studio\"; the display name also works).";+const WORKSPACE_ID: &str = "Workspace id from workspace_create or workspace_list, e.g. \"ws-7f3a2c\".";+const WS_PATH: &str = "Path relative to the workspace folder, e.g. \"src/main.rs\". Absolute paths and \"..\" escapes are rejected.";+const RUNNER_ID: &str = "Runner id: \"<machine-id>/<runner-name>\", or \"github/<name>\" for a runner no machine lists. A bare runner name works when unique.";++/// The tool catalog. Descriptions are written for a model deciding what to call.+pub fn tools() -> Vec<Value> {+ vec![+ json!({+ "name": "fleet_status",+ "description": "Overview of the whole fleet: counts of working/idle/offline runners, queued jobs, GitHub connection, every machine with CPU/memory/disk/uptime and a runner summary, and an `attention` list of problems (unreachable machines, stopped runners, jobs no runner can take, low disk). Call this first. Uses the last machine check unless refresh=true, which re-checks every machine over ssh first.",+ "inputSchema": schema(json!({+ "refresh": { "type": "boolean", "description": "Re-check all machines over ssh and sync GitHub before answering. Slower; default false." }+ }), &[]),+ "annotations": annotations("Fleet status", true, false, true, true),+ }),+ json!({+ "name": "get_machine",+ "description": "Everything about one machine: resources, OS, each runner on it (state, where the state came from, labels, version, service, current job) and diagnostics with hints. Use it to explain why a machine or runner has a problem.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("Get machine", true, false, true, false),+ }),+ json!({+ "name": "list_runners",+ "description": "List runners, optionally only those on one machine or in one state. Runners GitHub knows but no machine lists have machine_id null.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "state": { "type": "string", "enum": ["working", "idle", "offline", "unknown"], "description": "Only runners in this state." }+ }), &[]),+ "annotations": annotations("List runners", true, false, true, false),+ }),+ json!({+ "name": "list_jobs",+ "description": "Queued and running self-hosted jobs from the watched GitHub orgs/repos, with labels, age, and for queued jobs how many online runners could take them (0 means the job is stuck until a matching runner comes online).",+ "inputSchema": schema(json!({}), &[]),+ "annotations": annotations("List jobs", true, false, true, true),+ }),+ json!({+ "name": "check_machines",+ "description": "Run the read-only machine check now (over ssh, or locally for host \"local\"): CPU, memory, disk, uptime, installed runners and whether they're running. One machine or all. Changes nothing on the machines.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": "Only this machine; omit for all." } }), &[]),+ "annotations": annotations("Check machines", true, false, true, true),+ }),+ json!({+ "name": "add_machine",+ "description": "Add a machine to the fleet (written to fleet.toml, comments preserved) and check it. `host` is anything the system ssh accepts (user@host, an ~/.ssh/config alias; see list_ssh_hosts) or \"local\" for this computer. Key-based ssh must work without a password prompt. Doesn't install anything.",+ "inputSchema": schema(json!({+ "name": { "type": "string", "description": "Display name, e.g. \"Mac Studio\"." },+ "host": { "type": "string", "description": "ssh destination or \"local\"." },+ "check": { "type": "boolean", "description": "Check it right away and return what was found. Default true." }+ }), &["name", "host"]),+ "annotations": annotations("Add machine", false, false, false, true),+ }),+ json!({+ "name": "remove_machine",+ "description": "Remove a machine from fleet.toml. Nothing on the machine changes and its runners stay registered on GitHub; use runner_action remove first to take runners down.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("Remove machine", false, true, true, false),+ }),+ json!({+ "name": "install_runners",+ "description": "Install GitHub Actions runners on a machine and register each with the GitHub org/repo (`scope`) using a registration token from the user's gh login, then add them to fleet.toml. How they run (`mode`): \"auto\" (default) picks a boot-time service when the machine allows it (macOS, Windows, Linux with passwordless sudo), else Docker containers when Docker is available, else a background run.sh; \"docker\" runs one container per runner from GitHub's actions-runner image (no sudo, restarted by Docker, jobs get a clean Linux userland). Modifies the real machine and GitHub. Needs admin on the org (admin:org scope) or repo. Names default to \"<machine-id>-01\", \"-02\", ...",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "scope": { "type": "string", "description": "GitHub org (\"acme\") or repo (\"acme/api\"). Optional when exactly one is watched." },+ "names": { "type": "array", "items": { "type": "string" }, "description": "Runner names (letters, digits, '-', '_', '.')." },+ "count": { "type": "integer", "minimum": 1, "maximum": 32, "description": "How many to install when names is empty. Default 1." },+ "labels": { "type": "array", "items": { "type": "string" }, "description": "Extra labels; self-hosted, OS and architecture are added by GitHub." },+ "runner_group": { "type": "string", "description": "Org runner group (org scopes only)." },+ "mode": { "type": "string", "enum": ["auto", "service", "background", "docker"], "description": "How the runners run. Default \"auto\" (service, else docker, else background)." },+ "image": { "type": "string", "description": "mode docker only: runner image. Default ghcr.io/actions/actions-runner:<latest runner version>." },+ "docker_socket": { "type": "boolean", "description": "mode docker only: mount the host's Docker socket so jobs can use Docker. Root-equivalent access to the machine; only for trusted workflows. Default false." },+ "as_service": { "type": "boolean", "description": "Legacy: false means mode \"background\". Prefer mode." },+ "wait": { "type": "boolean", "description": "Wait for the install to finish. Default true." },+ "timeout_secs": { "type": "integer", "minimum": 1, "description": "How long to wait. Default 900." }+ }), &["machine_id"]),+ "annotations": annotations("Install runners", false, false, false, true),+ }),+ json!({+ "name": "runner_action",+ "description": "Control one runner on its machine: start, stop or restart its service; logs (read-only tail of its newest _diag log); or remove (stop, uninstall the service, deregister from GitHub, drop it from fleet.toml, optionally delete its folder). For a runner no machine lists (\"github/<name>\"), remove deregisters it on GitHub. stop and remove take the runner offline; confirm with the user first.",+ "inputSchema": schema(json!({+ "runner_id": { "type": "string", "description": RUNNER_ID },+ "action": { "type": "string", "enum": ["start", "stop", "restart", "logs", "remove"] },+ "delete_files": { "type": "boolean", "description": "With remove: also delete the runner's folder. Default false." },+ "wait": { "type": "boolean", "description": "Wait for it to finish. Default true." },+ "timeout_secs": { "type": "integer", "minimum": 1, "description": "How long to wait. Default 180." }+ }), &["runner_id", "action"]),+ "annotations": annotations("Runner action", false, true, false, true),+ }),+ json!({+ "name": "get_operation",+ "description": "Status and output of an install or runner action started by this server (use after wait=false or a timeout). Lines starting with \"▸ \" are OpenRunner's steps, \"✓ \" successes, \"error: \" problems.",+ "inputSchema": schema(json!({+ "operation_id": { "type": "integer" },+ "tail": { "type": "integer", "minimum": 0, "description": "Log lines from the end. Default 80." }+ }), &["operation_id"]),+ "annotations": annotations("Get operation", true, false, true, false),+ }),+ json!({+ "name": "list_operations",+ "description": "Operations this server has run (installs, starts, stops, logs, removals), newest first, without their output.",+ "inputSchema": schema(json!({}), &[]),+ "annotations": annotations("List operations", true, false, true, false),+ }),+ json!({+ "name": "github_scopes",+ "description": "Watch or stop watching GitHub orgs/repos. Watching gives live runner status and job data. Each added scope is checked first; reading org runners needs an org admin token (admin:org), and failures come back with the command that fixes them.",+ "inputSchema": schema(json!({+ "add": { "type": "array", "items": { "type": "string" }, "description": "Orgs (\"acme\") or repos (\"acme/api\") to watch." },+ "remove": { "type": "array", "items": { "type": "string" }, "description": "Orgs or repos to stop watching." }+ }), &[]),+ "annotations": annotations("GitHub scopes", false, false, true, true),+ }),+ json!({+ "name": "get_settings",+ "description": "Current settings: watched orgs/repos, polling and check intervals, file locations.",+ "inputSchema": schema(json!({}), &[]),+ "annotations": annotations("Get settings", true, false, true, false),+ }),+ json!({+ "name": "update_settings",+ "description": "Change polling and check intervals or the GitHub API URL (for GitHub Enterprise Server). Only the fields given change.",+ "inputSchema": schema(json!({+ "github_poll_seconds": { "type": "integer", "minimum": 10, "description": "How often the window polls GitHub." },+ "scan_repos": { "type": "integer", "minimum": 0, "maximum": 50, "description": "Recently pushed repos per org scanned for jobs." },+ "check_interval_minutes": { "type": "integer", "minimum": 0, "description": "Automatic machine checks; 0 = only on request." },+ "api_url": { "type": "string", "description": "GitHub REST API base, e.g. https://ghe.example.com/api/v3." }+ }), &[]),+ "annotations": annotations("Update settings", false, false, true, false),+ }),+ json!({+ "name": "list_ssh_hosts",+ "description": "Host aliases from the user's ~/.ssh/config, to suggest as `host` for add_machine.",+ "inputSchema": schema(json!({}), &[]),+ "annotations": annotations("List ssh hosts", true, false, true, false),+ }),+ json!({+ "name": "workspace_create",+ "description": "Check out one of the user's own machines as your work environment, like a remote dev box: creates a persistent folder there (optionally cloning a git repo at a ref, or creating a new branch) and returns a workspace_id for the other workspace_* tools. Omit machine_id to get the least-loaded online machine that allows workspaces, filtered by `platform` (e.g. \"linux\" to run tests on Linux). Use one workspace per task and reuse it across steps. Nothing is deleted automatically: call workspace_destroy when done. Private GitHub repos are cloned with the user's gh login.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": "Machine to use; omit to let OpenRunner pick." },+ "platform": { "type": "string", "description": "When picking: platform prefix such as \"linux\", \"linux-x64\", \"darwin-arm64\", \"windows\"." },+ "name": { "type": "string", "description": "Short label, e.g. \"api-tests\". Defaults to the repo name." },+ "repo": { "type": "string", "description": "Git URL, or \"owner/repo\" for GitHub, to clone into the workspace." },+ "ref": { "type": "string", "description": "Branch, tag or commit to check out." },+ "branch": { "type": "string", "description": "New branch to create and switch to after checkout." },+ "isolation": { "type": "string", "enum": ["host", "docker"], "description": "\"host\" (default): commands run directly on the machine with its tools and login environment. \"docker\": a fresh, isolated container per workspace (folder mounted at /workspace); pick the toolchain with `image`. Prefer docker for untrusted code or when you need a clean environment." },+ "image": { "type": "string", "description": "Docker image for isolation \"docker\", e.g. \"node:22\", \"python:3.13\", \"rust:1\", \"golang:1.25\". Defaults to buildpack-deps:bookworm. Choose an image that already has your tools: the container runs as the ssh user, so apt-get install won't work." },+ "docker_socket": { "type": "boolean", "description": "Share the machine's Docker socket with the container (docker-in-docker). Root-equivalent on that machine; only when the task needs Docker." }+ }), &[]),+ "annotations": annotations("Create workspace", false, false, false, true),+ }),+ json!({+ "name": "workspace_list",+ "description": "All workspaces (yours and other agents'): machine, folder, repo/ref, owner, status, last command, and which machines can take new workspaces. Check here before creating a new one; reuse a ready workspace for the same task.",+ "inputSchema": schema(json!({}), &[]),+ "annotations": annotations("List workspaces", true, false, true, false),+ }),+ json!({+ "name": "workspace_get",+ "description": "One workspace with its recent command history (command, exit code, duration, output tail) and the shell command a human can use to open a terminal in it.",+ "inputSchema": schema(json!({ "workspace_id": { "type": "string", "description": WORKSPACE_ID } }), &["workspace_id"]),+ "annotations": annotations("Get workspace", true, false, true, false),+ }),+ json!({+ "name": "workspace_exec",+ "description": "Run a shell command in a workspace on the user's machine, with that user's login environment (their PATH, Homebrew, nvm, ...). Returns exit_code, stdout and stderr (long output is capped, keeping the start and end). A non-zero exit_code is a normal result, not a tool error. Commands default to a 600s timeout (max 3600). For servers and watchers pass background=true: it returns right away with a pid and a log_path to read later. Commands run as the user on a real machine; ask before anything destructive outside the workspace.",+ "inputSchema": schema(json!({+ "workspace_id": { "type": "string", "description": WORKSPACE_ID },+ "command": { "type": "string", "description": "Shell command, e.g. \"npm test\" or \"cargo build --release 2>&1 | tail -50\"." },+ "cwd": { "type": "string", "description": "Folder relative to the workspace to run in." },+ "env": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Extra environment variables." },+ "timeout_secs": { "type": "integer", "minimum": 1, "maximum": 3600, "description": "Kill it after this many seconds. Default 600. Ignored with background." },+ "background": { "type": "boolean", "description": "Start detached and return its pid and log file. Default false." }+ }), &["workspace_id", "command"]),+ "annotations": annotations("Run command in workspace", false, false, false, true),+ }),+ json!({+ "name": "workspace_read_file",+ "description": "Read a text file from a workspace (default up to 256 KB; binary files are reported, not returned). Also use it to read the log of a background command.",+ "inputSchema": schema(json!({+ "workspace_id": { "type": "string", "description": WORKSPACE_ID },+ "path": { "type": "string", "description": WS_PATH },+ "max_bytes": { "type": "integer", "minimum": 1, "maximum": 2097152, "description": "Read at most this many bytes. Default 262144." }+ }), &["workspace_id", "path"]),+ "annotations": annotations("Read workspace file", true, false, true, false),+ }),+ json!({+ "name": "workspace_write_file",+ "description": "Write (or append to) a text file in a workspace, creating parent folders. Replaces the whole file unless append=true.",+ "inputSchema": schema(json!({+ "workspace_id": { "type": "string", "description": WORKSPACE_ID },+ "path": { "type": "string", "description": WS_PATH },+ "content": { "type": "string", "description": "UTF-8 text." },+ "append": { "type": "boolean", "description": "Append instead of replacing. Default false." }+ }), &["workspace_id", "path", "content"]),+ "annotations": annotations("Write workspace file", false, false, false, false),+ }),+ json!({+ "name": "workspace_list_files",+ "description": "List files and folders in a workspace (skips .git internals), with sizes.",+ "inputSchema": schema(json!({+ "workspace_id": { "type": "string", "description": WORKSPACE_ID },+ "path": { "type": "string", "description": "Folder relative to the workspace. Default: the workspace itself." },+ "depth": { "type": "integer", "minimum": 1, "maximum": 10, "description": "How deep to list. Default 2." }+ }), &["workspace_id"]),+ "annotations": annotations("List workspace files", true, false, true, false),+ }),+ json!({+ "name": "workspace_changes",+ "description": "Review what changed in a workspace: `git status` plus the uncommitted diff (capped). Use it before reporting back or syncing changes to the user's checkout.",+ "inputSchema": schema(json!({ "workspace_id": { "type": "string", "description": WORKSPACE_ID } }), &["workspace_id"]),+ "annotations": annotations("Workspace changes", true, false, true, false),+ }),+ json!({+ "name": "workspace_sync",+ "description": "Copy code between a folder on this computer (usually the user's local checkout) and a workspace with rsync over ssh. direction=push sends the local folder to the workspace (e.g. to test uncommitted local changes on another OS); direction=pull brings the workspace's files back. delete=true also removes files on the receiving side that the sender doesn't have; pulling with delete into the user's checkout can remove their files, so confirm first.",+ "inputSchema": schema(json!({+ "workspace_id": { "type": "string", "description": WORKSPACE_ID },+ "local_path": { "type": "string", "description": "Folder on this computer; absolute is safest (relative paths resolve against the MCP server's working directory)." },+ "direction": { "type": "string", "enum": ["push", "pull"] },+ "delete": { "type": "boolean", "description": "Mirror deletions to the receiving side. Default false." }+ }), &["workspace_id", "local_path", "direction"]),+ "annotations": annotations("Sync workspace", false, true, false, true),+ }),+ json!({+ "name": "workspace_destroy",+ "description": "Done with a workspace: stops background commands it started and deletes its folder on the machine (keep_files=true keeps the folder and only forgets the workspace). Uncommitted work in it is lost; pull or push it first if it matters.",+ "inputSchema": schema(json!({+ "workspace_id": { "type": "string", "description": WORKSPACE_ID },+ "keep_files": { "type": "boolean", "description": "Keep the folder on the machine. Default false." }+ }), &["workspace_id"]),+ "annotations": annotations("Destroy workspace", false, true, true, true),+ }),+ json!({+ "name": "workspace_allow",+ "description": "Turn agent workspaces on or off for a machine (edits fleet.toml, comments preserved). Machines allow them by default; only change this when the user asks.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "allowed": { "type": "boolean" }+ }), &["machine_id", "allowed"]),+ "annotations": annotations("Allow workspaces", false, false, true, false),+ }),+ ]+}++/// Ready-to-paste setup for common MCP clients.+pub fn print_config() -> String {+ let exe = std::env::current_exe()+ .ok()+ .and_then(|p| p.canonicalize().ok())+ .map(|p| p.display().to_string())+ .unwrap_or_else(|| "openrunner".into());+ let json_block = serde_json::to_string_pretty(&json!({+ "mcpServers": { "openrunner": { "command": exe, "args": ["mcp"] } }+ }))+ .unwrap_or_default();+ format!(+ "# Claude Code\nclaude mcp add openrunner -- {exe} mcp\n\n\+ # Codex (~/.codex/config.toml)\n[mcp_servers.openrunner]\ncommand = \"{exe}\"\nargs = [\"mcp\"]\n\n\+ # Other MCP clients (Claude Desktop, Cursor, ...)\n{json_block}\n\n\+ # Try it safely first with a simulated fleet: add \"--demo\" after \"mcp\".\n"+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config::Paths;+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};++ fn demo() -> Arc<Engine> {+ Engine::new(Paths::resolve(Some(std::env::temp_dir().join("openrunner-mcp-test")), None), true)+ }++ #[test]+ fn tool_schemas_are_well_formed() {+ let tools = tools();+ assert_eq!(tools.len(), 26);+ let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();+ names.sort();+ names.dedup();+ assert_eq!(names.len(), tools.len(), "duplicate tool names");+ for t in &tools {+ let name = t["name"].as_str().unwrap();+ assert!(name.chars().all(|c| c.is_ascii_lowercase() || c == '_'), "{name}");+ assert!(t["description"].as_str().unwrap().len() > 40, "{name}");+ assert_eq!(t["inputSchema"]["type"], "object", "{name}");+ for req in t["inputSchema"]["required"].as_array().unwrap() {+ assert!(t["inputSchema"]["properties"].get(req.as_str().unwrap()).is_some(), "{name}: {req}");+ }+ assert!(t["annotations"]["readOnlyHint"].is_boolean());+ assert_eq!(t["inputSchema"]["additionalProperties"], false, "{name}");+ }+ }++ #[test]+ fn workspace_tools_are_annotated_for_what_they_do() {+ let tools = tools();+ let get = |n: &str| tools.iter().find(|t| t["name"] == n).unwrap_or_else(|| panic!("missing {n}")).clone();+ for read_only in ["workspace_list", "workspace_get", "workspace_read_file", "workspace_list_files", "workspace_changes"] {+ assert_eq!(get(read_only)["annotations"]["readOnlyHint"], true, "{read_only}");+ }+ for changes in ["workspace_create", "workspace_exec", "workspace_write_file", "workspace_sync", "workspace_destroy", "workspace_allow"] {+ assert_eq!(get(changes)["annotations"]["readOnlyHint"], false, "{changes}");+ }+ assert_eq!(get("workspace_destroy")["annotations"]["destructiveHint"], true);+ let exec = get("workspace_exec");+ assert_eq!(exec["inputSchema"]["required"], json!(["workspace_id", "command"]));+ assert_eq!(exec["inputSchema"]["properties"]["env"]["type"], "object");+ assert_eq!(get("workspace_sync")["inputSchema"]["properties"]["direction"]["enum"], json!(["push", "pull"]));+ assert!(INSTRUCTIONS.contains("workspace_create"));+ }++ #[test]+ fn exec_results_read_as_text() {+ let text = readable_text(+ "workspace_exec",+ &json!({ "exit_code": 1, "duration_ms": 1200, "stdout": "ok\n", "stderr": "boom", "timed_out": false, "truncated": false, "background_pid": null }),+ )+ .unwrap();+ assert!(text.starts_with("exit code: 1 (1200 ms)"), "{text}");+ assert!(text.contains("stdout:\n```\nok\n```") && text.contains("stderr:\n```\nboom\n```"), "{text}");+ let bg = readable_text("workspace_exec", &json!({ "background_pid": 42, "log_path": ".openrunner/logs/1.log", "duration_ms": 5 })).unwrap();+ assert!(bg.contains("pid 42") && bg.contains(".openrunner/logs/1.log"));+ assert!(readable_text("fleet_status", &json!({})).is_none());+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn initialize_records_the_client_as_owner() {+ let engine = demo();+ let session = Session::default();+ assert_eq!(session.owner(), "mcp");+ handle(&engine, &session, "initialize", json!({"protocolVersion":"2025-06-18","clientInfo":{"name":"claude-code","version":"2"}})).await.unwrap();+ assert_eq!(session.owner(), "claude-code");+ }++ /// Needs the workspace backend (src/fleet/workspaces.rs); run with `cargo test -- --ignored`.+ #[tokio::test(flavor = "multi_thread")]+ #[ignore = "needs the workspace backend"]+ async fn workspace_tools_round_trip_in_demo() {+ let engine = demo();+ engine.run_check(None).await;+ let session = Session::default();+ handle(&engine, &session, "initialize", json!({"clientInfo":{"name":"codex"}})).await.unwrap();+ let created = call_tool(&engine, &session, "workspace_create", json!({"platform":"linux","repo":"acme/api"})).await;+ assert_eq!(created["isError"], false, "{created}");+ let id = created["structuredContent"]["workspace"]["id"].as_str().unwrap().to_string();+ assert_eq!(created["structuredContent"]["workspace"]["owner"], "codex");+ let ran = call_tool(&engine, &session, "workspace_exec", json!({"workspace_id": id, "command": "pwd"})).await;+ assert_eq!(ran["isError"], false, "{ran}");+ assert!(ran["content"][0]["text"].as_str().unwrap().starts_with("exit code: 0"));+ let destroyed = call_tool(&engine, &session, "workspace_destroy", json!({"workspace_id": id})).await;+ assert_eq!(destroyed["isError"], false, "{destroyed}");+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn speaks_mcp_over_a_stream() {+ let engine = demo();+ let (client, server) = tokio::io::duplex(1 << 20);+ let (server_read, server_write) = tokio::io::split(server);+ let task = tokio::spawn(serve(engine, BufReader::new(server_read), server_write));+ let (client_read, mut client_write) = tokio::io::split(client);+ let mut lines = BufReader::new(client_read).lines();+ let mut recv = async || -> Value {+ let line = tokio::time::timeout(std::time::Duration::from_secs(30), lines.next_line()).await.expect("reply in time");+ serde_json::from_str(&line.unwrap().unwrap()).unwrap()+ };++ let mut send = async |msg: Value| {+ let mut bytes = serde_json::to_vec(&msg).unwrap();+ bytes.push(b'\n');+ client_write.write_all(&bytes).await.unwrap();+ };+ send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1"}}})).await;+ let init: Value = recv().await;+ assert_eq!(init["id"], 1);+ assert_eq!(init["result"]["protocolVersion"], "2025-03-26");+ assert_eq!(init["result"]["serverInfo"]["name"], "openrunner");+ assert!(init["result"]["instructions"].as_str().unwrap().contains("fleet_status"));++ send(json!({"jsonrpc":"2.0","method":"notifications/initialized"})).await;+ send(json!({"jsonrpc":"2.0","id":2,"method":"tools/list"})).await;+ let list: Value = recv().await;+ assert_eq!(list["result"]["tools"].as_array().unwrap().len(), tools().len());++ send(json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"fleet_status","arguments":{}}})).await;+ let status: Value = recv().await;+ assert_eq!(status["result"]["isError"], false);+ assert_eq!(status["result"]["structuredContent"]["counts"]["machines"], 9);+ assert!(status["result"]["content"][0]["text"].as_str().unwrap().contains("\"summary\""));++ // Tool failures are results with isError, carrying a code an agent can branch on.+ send(json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"get_machine","arguments":{"machine_id":"nope"}}})).await;+ let missing: Value = recv().await;+ assert_eq!(missing["result"]["isError"], true);+ assert_eq!(missing["result"]["structuredContent"]["error"]["code"], "not_found");++ send(json!({"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"runner_action","arguments":{"runner_id":"x","action":"explode"}}})).await;+ let bad: Value = recv().await;+ assert_eq!(bad["result"]["structuredContent"]["error"]["code"], "invalid");++ // Workspace arguments are validated before anything runs.+ send(json!({"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"workspace_read_file","arguments":{"workspace_id":"ws-x","path":"../../etc/passwd"}}})).await;+ let escape: Value = recv().await;+ assert_eq!(escape["result"]["isError"], true);+ assert_eq!(escape["result"]["structuredContent"]["error"]["code"], "invalid");+ send(json!({"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"workspace_exec","arguments":{"workspace_id":"ws-x"}}})).await;+ let missing_arg: Value = recv().await;+ assert_eq!(missing_arg["result"]["structuredContent"]["error"]["code"], "invalid");+ send(json!({"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"workspace_get","arguments":{"workspace_id":"ws-nope"}}})).await;+ let unknown_ws: Value = recv().await;+ assert_eq!(unknown_ws["result"]["structuredContent"]["error"]["code"], "not_found");++ send(json!({"jsonrpc":"2.0","id":6,"method":"nope/nothing"})).await;+ let unknown: Value = recv().await;+ assert_eq!(unknown["error"]["code"], -32601);++ send(json!({"jsonrpc":"2.0","id":7,"method":"ping"})).await;+ let pong: Value = recv().await;+ assert_eq!(pong["id"], 7);++ // Closing the client ends the session.+ drop(send);+ drop(recv);+ drop(client_write);+ drop(lines);+ tokio::time::timeout(std::time::Duration::from_secs(10), task).await.expect("server exits on EOF").unwrap().unwrap();+ }+}diff --git a/src/ops/inventory_edit.rs b/src/ops/inventory_edit.rsnew file mode 100644index 0000000..9f241ca--- /dev/null+++ b/src/ops/inventory_edit.rs@@ -0,0 +1,312 @@+//! Edits fleet.toml in place with `toml_edit`, so the user's comments, ordering+//! and formatting survive when OpenRunner adds or removes machines and runners.+//! Every function works on text, which lets demo mode reuse them on its+//! in-memory inventory.++use std::collections::HashSet;+use std::path::Path;+use std::sync::Mutex;++use toml_edit::{value, Array, ArrayOfTables, DocumentMut, Item, Table};++use crate::config::{assign_machine_id, display_path, write_atomic, Inventory};++/// Serializes edits so two operations finishing together don't drop each other's change.+static FILE_LOCK: Mutex<()> = Mutex::new(());++/// Reads the file (missing is fine), applies `edit`, validates and writes it back atomically.+pub fn edit_file(path: &Path, edit: impl FnOnce(&str) -> Result<String, String>) -> Result<(), String> {+ let _guard = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let text = match std::fs::read_to_string(path) {+ Ok(t) => t,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),+ Err(e) => return Err(format!("Couldn't read {}: {e}", display_path(path))),+ };+ let updated = edit(&text)?;+ write_atomic(path, updated.as_bytes()).map_err(|e| format!("Couldn't write {}: {e:#}", display_path(path)))+}++/// Appends a `[[machine]]` with `name` and `host`. Returns the new text and the machine's id.+pub fn add_machine(text: &str, name: &str, host: &str) -> Result<(String, String), String> {+ let name = name.trim();+ let host = host.trim();+ let mut doc = parse(text)?;+ // Comment lines right after the last table (before a blank line), like a+ // commented-out `# runners = [...]`, belong to that table: keep them above the+ // new one. The rest of the trailing comments stay at the end of the file.+ let trailing = doc.trailing().as_str().unwrap_or("").to_string();+ let (attached, rest) = split_attached(&trailing);+ let (attached, rest) = (attached.to_string(), rest.to_string());+ {+ let machines = machines_mut(&mut doc)?;+ if machines.iter().any(|t| table_name(t).eq_ignore_ascii_case(name)) {+ return Err(format!("A machine called \"{name}\" is already in fleet.toml."));+ }+ let mut table = Table::new();+ table["name"] = value(name);+ table["host"] = value(host);+ // A blank line before the header keeps the file readable.+ table.decor_mut().set_prefix(format!("{attached}\n"));+ machines.push(table);+ }+ doc.set_trailing(rest);+ let out = doc.to_string();+ let id = Inventory::parse(&out)+ .map_err(|e| format!("fleet.toml would be invalid: {e}"))?+ .machines+ .last()+ .map(|m| m.id.clone())+ .ok_or("The machine wasn't added.")?;+ Ok((out, id))+}++/// Removes the machine with this id (as `Inventory::parse` assigns ids).+pub fn remove_machine(text: &str, machine_id: &str) -> Result<String, String> {+ let mut doc = parse(text)?;+ let machines = machines_mut(&mut doc)?;+ let index = find_machine(machines, machine_id)?;+ let prefix = machines.get(index).and_then(|t| t.decor().prefix()).and_then(|p| p.as_str()).unwrap_or("").to_string();+ machines.remove(index);++ // Comments above the first [[machine]] belong to it in toml_edit, but the part+ // before the last blank line is the file's header. Keep that.+ let header = if index == 0 { file_header(&prefix) } else { "" };+ if !header.is_empty() {+ match machines.get_mut(0) {+ Some(next) => {+ let rest = next.decor().prefix().and_then(|p| p.as_str()).unwrap_or("").trim_start_matches('\n').to_string();+ next.decor_mut().set_prefix(format!("{header}{rest}"));+ }+ None => {+ let trailing = doc.trailing().as_str().unwrap_or("").to_string();+ doc.set_trailing(format!("{header}{trailing}"));+ }+ }+ }+ finish(doc)+}++/// Splits document trailing text into the comment lines glued to the last table and the rest.+fn split_attached(trailing: &str) -> (&str, &str) {+ if trailing.is_empty() || trailing.starts_with('\n') {+ return ("", trailing);+ }+ match trailing.find("\n\n") {+ Some(i) => (&trailing[..=i], &trailing[i + 1..]),+ None => (trailing, ""),+ }+}++/// The leading part of a decor prefix up to and including its last blank line.+fn file_header(prefix: &str) -> &str {+ match prefix.rfind("\n\n") {+ Some(i) => &prefix[..i + 2],+ None => "",+ }+}++/// Adds runner names to a machine's `runners` list (creating it if needed). Names already listed are skipped.+pub fn add_runners(text: &str, machine_id: &str, names: &[String]) -> Result<String, String> {+ let mut doc = parse(text)?;+ let machines = machines_mut(&mut doc)?;+ let index = find_machine(machines, machine_id)?;+ let table = machines.get_mut(index).ok_or("Machine not found.")?;+ match table.get_mut("runners") {+ Some(item) => {+ let list = item.as_array_mut().ok_or("`runners` in fleet.toml isn't a list.")?;+ for n in names {+ if !list.iter().any(|v| v.as_str().is_some_and(|s| s.eq_ignore_ascii_case(n))) {+ list.push(n.as_str());+ }+ }+ }+ None => {+ let mut list = Array::new();+ for n in names {+ list.push(n.as_str());+ }+ table["runners"] = value(list);+ }+ }+ finish(doc)+}++/// Removes a runner name from a machine's `runners` list. Not listed is not an error.+pub fn remove_runner(text: &str, machine_id: &str, name: &str) -> Result<String, String> {+ let mut doc = parse(text)?;+ let machines = machines_mut(&mut doc)?;+ let index = find_machine(machines, machine_id)?;+ let table = machines.get_mut(index).ok_or("Machine not found.")?;+ if let Some(list) = table.get_mut("runners").and_then(Item::as_array_mut) {+ list.retain(|v| !v.as_str().is_some_and(|s| s.eq_ignore_ascii_case(name)));+ }+ finish(doc)+}++/// Allows or forbids agent workspaces on a machine. Allowed is the default, so+/// allowing removes the key rather than writing `workspaces = true`.+pub fn set_workspaces(text: &str, machine_id: &str, allowed: bool) -> Result<String, String> {+ let mut doc = parse(text)?;+ let machines = machines_mut(&mut doc)?;+ let index = find_machine(machines, machine_id)?;+ let table = machines.get_mut(index).ok_or("Machine not found.")?;+ if allowed {+ table.remove("workspaces");+ } else {+ table["workspaces"] = value(false);+ }+ finish(doc)+}++fn parse(text: &str) -> Result<DocumentMut, String> {+ text.parse::<DocumentMut>().map_err(|e| format!("fleet.toml has a syntax error, so it wasn't changed: {}", e.to_string().trim()))+}++fn finish(doc: DocumentMut) -> Result<String, String> {+ let out = doc.to_string();+ Inventory::parse(&out).map_err(|e| format!("fleet.toml would be invalid: {e}"))?;+ Ok(out)+}++fn machines_mut(doc: &mut DocumentMut) -> Result<&mut ArrayOfTables, String> {+ if doc.get("machine").is_none() {+ doc.insert("machine", Item::ArrayOfTables(ArrayOfTables::new()));+ }+ doc.get_mut("machine")+ .and_then(Item::as_array_of_tables_mut)+ .ok_or_else(|| "fleet.toml defines `machine` in a form OpenRunner can't edit. Use [[machine]] tables.".to_string())+}++fn table_name(t: &Table) -> &str {+ t.get("name").and_then(Item::as_str).map(str::trim).unwrap_or("")+}++/// Index of the table whose id matches, replaying `Inventory::parse`'s id rules+/// (unnamed tables are skipped and get no id).+fn find_machine(machines: &ArrayOfTables, machine_id: &str) -> Result<usize, String> {+ let mut taken = HashSet::new();+ for (i, t) in machines.iter().enumerate() {+ let name = table_name(t);+ if name.is_empty() {+ continue;+ }+ let explicit = t.get("id").and_then(Item::as_str).unwrap_or("");+ if assign_machine_id(name, explicit, &mut taken) == machine_id {+ return Ok(i);+ }+ }+ Err(format!("Machine \"{machine_id}\" isn't in fleet.toml."))+}++#[cfg(test)]+mod workspace_tests {+ use super::*;++ #[test]+ fn toggles_workspaces_keeping_comments() {+ let text = "# fleet\n[[machine]]\nname = \"Box\" # main box\nhost = \"box\"\n";+ let off = set_workspaces(text, "box", false).unwrap();+ assert!(off.contains("# main box") && off.contains("workspaces = false"), "{off}");+ assert!(!Inventory::parse(&off).unwrap().machines[0].workspaces);+ let on = set_workspaces(&off, "box", true).unwrap();+ assert!(!on.contains("workspaces"), "{on}");+ assert!(Inventory::parse(&on).unwrap().machines[0].workspaces);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config::default_inventory;++ const FILE: &str = r#"# My fleet+# (hand written)++[[machine]]+name = "Mac Studio" # the big one+host = "ci@studio"+runners = ["studio-01", "studio-02"]++# The NAS doesn't run jobs.+[[machine]]+name = "NAS"+host = "nas"+"#;++ #[test]+ fn adds_a_machine_and_keeps_comments() {+ let (out, id) = add_machine(FILE, "Beelink", "beelink").unwrap();+ assert_eq!(id, "beelink");+ assert!(out.starts_with("# My fleet\n# (hand written)\n"));+ assert!(out.contains("name = \"Mac Studio\" # the big one"));+ assert!(out.contains("# The NAS doesn't run jobs."));+ assert!(out.ends_with("[[machine]]\nname = \"Beelink\"\nhost = \"beelink\"\n"), "{out}");+ assert_eq!(Inventory::parse(&out).unwrap().machines.len(), 3);+ assert!(add_machine(&out, "beelink", "x").is_err());+ }++ #[test]+ fn adds_to_the_default_inventory_and_an_empty_file() {+ let (out, id) = add_machine(&default_inventory(), "Beelink", "beelink").unwrap();+ assert_eq!(id, "beelink");+ // The local machine's commented-out runners line stays with it, the examples stay last.+ let local = out.find("host = \"local\"").unwrap();+ let commented = out.find("# runners = [").unwrap();+ let beelink = out.find("name = \"Beelink\"").unwrap();+ let examples = out.find("# name = \"Mac Studio\"").unwrap();+ assert!(local < commented && commented < beelink && beelink < examples, "{out}");+ assert!(out.contains("host = \"local\"\n# runners = ["), "{out}");+ assert!(out.contains("]\n\n[[machine]]\nname = \"Beelink\"\nhost = \"beelink\"\n\n# [[machine]]"), "{out}");+ assert_eq!(Inventory::parse(&out).unwrap().machines.len(), 2);+ let (out, id) = add_machine("", "First", "local").unwrap();+ assert_eq!(id, "first");+ assert!(Inventory::parse(&out).unwrap().machines[0].is_local());+ }++ #[test]+ fn duplicate_names_get_the_same_ids_as_the_parser() {+ let text = "[[machine]]\nname = \"Box\"\nhost = \"a\"\n\n[[machine]]\nname = \"Box\"\nhost = \"b\"\n";+ let out = add_runners(text, "box-2", &["b-01".into()]).unwrap();+ let inv = Inventory::parse(&out).unwrap();+ assert!(inv.machines[0].runners.is_empty());+ assert_eq!(inv.machines[1].runners, vec!["b-01"]);+ }++ #[test]+ fn adds_and_removes_runners() {+ let out = add_runners(FILE, "mac-studio", &["studio-03".into(), "STUDIO-01".into()]).unwrap();+ assert!(out.contains(r#"runners = ["studio-01", "studio-02", "studio-03"]"#), "{out}");+ let out = add_runners(&out, "nas", &["nas-01".into()]).unwrap();+ assert_eq!(Inventory::parse(&out).unwrap().machines[1].runners, vec!["nas-01"]);+ let out = remove_runner(&out, "mac-studio", "studio-02").unwrap();+ assert_eq!(Inventory::parse(&out).unwrap().machines[0].runners, vec!["studio-01", "studio-03"]);+ assert!(out.contains("# the big one"));+ }++ #[test]+ fn removes_a_machine() {+ let out = remove_machine(FILE, "mac-studio").unwrap();+ let inv = Inventory::parse(&out).unwrap();+ assert_eq!(inv.machines.len(), 1);+ assert_eq!(inv.machines[0].name, "NAS");+ assert!(out.starts_with("# My fleet\n# (hand written)\n\n# The NAS doesn't run jobs.\n[[machine]]"), "{out}");+ assert!(!out.contains("Mac Studio"));+ assert!(remove_machine(FILE, "nope").is_err());++ // Removing the last machine keeps the header too.+ let out = remove_machine(&out, "nas").unwrap();+ assert!(out.starts_with("# My fleet\n# (hand written)\n"), "{out}");+ assert!(Inventory::parse(&out).unwrap().machines.is_empty());++ // Removing a later machine takes its own comment with it.+ let out = remove_machine(FILE, "nas").unwrap();+ assert!(!out.contains("The NAS"));+ assert!(out.starts_with("# My fleet"));+ }++ #[test]+ fn refuses_broken_files() {+ assert!(add_machine("[[machine]\nname=", "x", "y").is_err());+ assert!(add_machine("machine = 3\n", "x", "y").is_err());+ }+}diff --git a/src/ops/mod.rs b/src/ops/mod.rsnew file mode 100644index 0000000..488a3f9--- /dev/null+++ b/src/ops/mod.rs@@ -0,0 +1,1307 @@+//! Control operations: add machines, install runners on them, and start, stop,+//! restart, inspect or remove those runners. Each operation runs in the+//! background, streams its output into `Snapshot::operations`, and refreshes the+//! affected machine when it finishes.+//!+//! Operation log conventions: lines starting with "▸ " are OpenRunner's own+//! steps, "✓ " marks a success, "error: " and "warning: " are problems; anything+//! else is output from the machine.+//!+//! PUBLIC API — the UI depends on these signatures.++pub(crate) mod inventory_edit;+pub(crate) mod remote;++use std::collections::HashSet;+use std::sync::Arc;+use std::time::Duration;++use crate::config::{MachineSpec, Settings};+use crate::fleet::model::Runner;+use crate::fleet::Engine;+use crate::github::scope_from_runner_url;+use crate::probe::{self, ProbeResult, Shell};+use remote::{with_params, Param};++const INSTALL_SH: &str = include_str!("scripts/install.sh");+const INSTALL_PS1: &str = include_str!("scripts/install.ps1");+const CONTROL_SH: &str = include_str!("scripts/control.sh");+const CONTROL_PS1: &str = include_str!("scripts/control.ps1");+const INSTALL_DOCKER_SH: &str = include_str!("scripts/install_docker.sh");+const CONTROL_DOCKER_SH: &str = include_str!("scripts/control_docker.sh");+/// GitHub's official runner image; tagged with each runner release.+const RUNNER_IMAGE: &str = "ghcr.io/actions/actions-runner";++const INSTALL_TIMEOUT: Duration = Duration::from_secs(15 * 60);+const CONTROL_TIMEOUT: Duration = Duration::from_secs(3 * 60);+/// Used when GitHub can't tell us the latest runner release.+const FALLBACK_RUNNER_VERSION: &str = "2.329.0";++/// Install one or more runners on a machine.+#[derive(Debug, Clone)]+pub struct InstallRequest {+ pub machine_id: String,+ /// The org ("acme") or repo ("acme/api") to register the runners with.+ pub scope: String,+ /// One runner per name, e.g. ["mac-studio-08", "mac-studio-09"].+ pub names: Vec<String>,+ /// Extra labels on top of the defaults GitHub adds (self-hosted, OS, arch).+ pub labels: Vec<String>,+ /// Org runner group; None means "Default".+ pub group: Option<String>,+ /// Legacy switch, still honoured: false with `mode: Auto` means `Background`.+ pub as_service: bool,+ /// How the runner runs on the machine. `Auto` picks per machine at install time.+ pub mode: InstallMode,+}++/// How an installed runner runs on its machine.+#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub enum InstallMode {+ /// Service when the machine allows it (macOS, Windows, Linux with passwordless+ /// sudo), else Docker when it's available, else Background.+ #[default]+ Auto,+ /// launchd / systemd / Windows service: starts at boot. Linux needs passwordless sudo.+ Service,+ /// run.sh in the background: no root needed, but gone after a reboot.+ Background,+ /// A container per runner from GitHub's actions-runner image, restarted by the+ /// Docker daemon. No sudo needed; jobs run in a clean Linux userland.+ Docker {+ /// None: ghcr.io/actions/actions-runner:<latest runner version>.+ image: Option<String>,+ /// Mount the host's Docker socket so jobs can use Docker (root-equivalent).+ docker_socket: bool,+ },+}++impl InstallMode {+ /// "auto" | "service" | "background" | "docker"+ pub fn name(&self) -> &'static str {+ match self {+ InstallMode::Auto => "auto",+ InstallMode::Service => "service",+ InstallMode::Background => "background",+ InstallMode::Docker { .. } => "docker",+ }+ }++ /// From the API/CLI spelling. `image` and `docker_socket` only apply to docker.+ pub fn parse(mode: &str, image: Option<String>, docker_socket: bool) -> Result<InstallMode, String> {+ let image = image.map(|i| i.trim().to_string()).filter(|i| !i.is_empty());+ let mode = match mode.trim().to_ascii_lowercase().as_str() {+ "" | "auto" => InstallMode::Auto,+ "service" => InstallMode::Service,+ "background" | "run" => InstallMode::Background,+ "docker" | "container" => InstallMode::Docker { image: image.clone(), docker_socket },+ other => return Err(format!("\"{other}\" isn't an install mode. Use auto, service, background or docker.")),+ };+ if !matches!(mode, InstallMode::Docker { .. }) && (image.is_some() || docker_socket) {+ return Err("image and docker_socket only apply to mode \"docker\".".into());+ }+ Ok(mode)+ }+}++/// What `Auto` means on this machine, plus a sentence for the log when the choice+/// isn't the obvious one.+pub(crate) fn resolve_mode(mode: &InstallMode, as_service: bool, probe: &ProbeResult) -> (InstallMode, Option<String>) {+ let docker = || InstallMode::Docker { image: None, docker_socket: false };+ match mode {+ InstallMode::Auto if !as_service => (InstallMode::Background, None),+ InstallMode::Auto => match probe.os.as_deref() {+ Some("linux") => match probe.sudo.as_deref() {+ Some("root" | "passwordless") => (InstallMode::Service, None),+ _ if probe.docker.is_some() => (+ docker(),+ Some("sudo asks for a password here, so a systemd service isn't possible; using Docker containers instead".into()),+ ),+ _ => (+ InstallMode::Background,+ Some("sudo asks for a password and Docker isn't available here, so the runners start in the background and won't come back after a reboot".into()),+ ),+ },+ _ => (InstallMode::Service, None),+ },+ other => (other.clone(), None),+ }+}++fn valid_image(image: &str) -> bool {+ !image.is_empty()+ && image.len() <= 255+ && !image.starts_with(['-', '.', '/', ':'])+ && image.chars().all(|c| c.is_ascii_alphanumeric() || "._-/:@".contains(c))+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RunnerAction {+ Start,+ Stop,+ Restart,+ /// Tail the newest _diag log into the operation output (read-only).+ Logs,+ /// Stop, uninstall the service, deregister from GitHub, and drop it from fleet.toml.+ Remove { delete_files: bool },+}++impl RunnerAction {+ pub fn label(self) -> &'static str {+ match self {+ RunnerAction::Start => "Start",+ RunnerAction::Stop => "Stop",+ RunnerAction::Restart => "Restart",+ RunnerAction::Logs => "Logs",+ RunnerAction::Remove { .. } => "Remove",+ }+ }++ fn kind(self) -> &'static str {+ match self {+ RunnerAction::Start => "start",+ RunnerAction::Stop => "stop",+ RunnerAction::Restart => "restart",+ RunnerAction::Logs => "logs",+ RunnerAction::Remove { .. } => "remove",+ }+ }+}++/// A machine to add to fleet.toml.+#[derive(Debug, Clone)]+pub struct NewMachine {+ pub name: String,+ /// An ssh destination ("[email protected]", an ~/.ssh/config alias) or "local".+ pub host: String,+}++impl Engine {+ /// Starts installing runners. Returns the operation id.+ pub fn install_runners(self: &Arc<Self>, req: InstallRequest) -> Result<u64, String> {+ let req = self.validate_install(req)?;+ let (spec, probe) = self.machine(&req.machine_id).ok_or("That machine isn't in fleet.toml anymore.")?;+ let title = match req.names.as_slice() {+ [one] => format!("Install {one} on {}", spec.name),+ many => format!("Install {} runners on {}", many.len(), spec.name),+ };+ let op = self.begin_op("install", title, Some(spec.id.clone()), None);+ let me = self.clone();+ self.runtime().spawn(async move {+ let result = match me.demo_world().cloned() {+ Some(_) => demo_install(&me, op, &req, &spec).await,+ None => install(&me, op, &req, &spec, probe).await,+ };+ finish(&me, op, result);+ });+ Ok(op)+ }++ /// Starts an action on a runner (id as in `Runner::id`). Returns the operation id.+ pub fn runner_action(self: &Arc<Self>, runner_id: &str, action: RunnerAction) -> Result<u64, String> {+ let snap = self.current();+ let runner = snap.runners.iter().find(|r| r.id == runner_id).cloned().ok_or("That runner isn't in the fleet anymore.")?;+ let machine = runner.machine_id.as_deref().and_then(|id| self.machine(id));+ let reachable = runner+ .machine_id+ .as_deref()+ .and_then(|id| snap.machines.iter().find(|m| m.id == id))+ .is_some_and(|m| m.status == "online");+ let dir = runner.local.as_ref().map(|l| l.dir.clone());+ let container = runner.local.as_ref().and_then(|l| l.container.clone());++ let plan = match action {+ RunnerAction::Remove { delete_files } => {+ let on_machine = machine.as_ref().filter(|(spec, _)| spec.is_checkable() && reachable && dir.is_some());+ match on_machine {+ Some((spec, probe)) => {+ let scope = runner_scope(&runner).ok_or_else(|| {+ format!("OpenRunner doesn't know which GitHub org or repo {} is registered with.", runner.name)+ })?;+ Plan::OnMachine {+ spec: spec.clone(),+ probe: probe.clone(),+ dir: dir.clone().unwrap_or_default(),+ container: container.clone(),+ scope: Some(scope),+ delete_files,+ }+ }+ None if runner.github.is_some() => Plan::GitHubOnly,+ None if runner.declared => Plan::InventoryOnly,+ None => return Err(format!("{} isn't on a reachable machine or on GitHub, so there's nothing to remove.", runner.name)),+ }+ }+ _ => {+ let (spec, probe) = machine.clone().ok_or_else(|| {+ format!("{} isn't on a machine in fleet.toml, so OpenRunner can't control it. It can only be removed from GitHub.", runner.name)+ })?;+ if !spec.is_checkable() {+ return Err(format!("{} has no host in fleet.toml.", spec.name));+ }+ let dir = dir.clone().ok_or_else(|| {+ format!("{} wasn't found on {} at the last check. Check the machine again, or install the runner.", runner.name, spec.name)+ })?;+ Plan::OnMachine { spec, probe, dir, container, scope: None, delete_files: false }+ }+ };++ if action != RunnerAction::Logs {+ if let Some(mid) = runner.machine_id.as_deref() {+ if self.machine_busy(mid) {+ return Err("Another operation is already changing this machine. Wait for it to finish.".into());+ }+ }+ }++ let title = match action {+ RunnerAction::Logs => format!("Logs · {}", runner.name),+ other => format!("{} {}", other.label(), runner.name),+ };+ let op = self.begin_op(action.kind(), title, runner.machine_id.clone(), Some(runner.id.clone()));+ let me = self.clone();+ self.runtime().spawn(async move {+ let result = match me.demo_world().cloned() {+ Some(_) => demo_action(&me, op, &runner, action).await,+ None => run_action(&me, op, &runner, action, plan).await,+ };+ finish(&me, op, result);+ });+ Ok(op)+ }++ /// Adds a machine to fleet.toml (keeping its comments and formatting) and checks it.+ /// Returns the new machine's id.+ pub fn add_machine(self: &Arc<Self>, machine: NewMachine) -> Result<String, String> {+ let name = machine.name.trim().to_string();+ let host = machine.host.trim().to_string();+ validate_machine(&name, &host)?;+ let taken = self.current().machines.iter().any(|m| m.name.eq_ignore_ascii_case(&name));+ if taken {+ return Err(format!("A machine called \"{name}\" is already in the fleet."));+ }++ let mut new_id = None;+ let edit = |text: &str| {+ let (out, id) = inventory_edit::add_machine(text, &name, &host)?;+ new_id = Some(id);+ Ok(out)+ };+ match self.demo_world() {+ Some(w) => w.edit_inventory(edit)?,+ None => inventory_edit::edit_file(self.inventory_path(), edit)?,+ }+ let id = new_id.ok_or("The machine wasn't added.")?;+ self.reload_inventory_now();+ self.trigger_check(Some(id.clone()));+ Ok(id)+ }++ /// Removes a machine from fleet.toml. Doesn't touch the machine itself.+ pub fn remove_machine(self: &Arc<Self>, machine_id: &str) -> Result<(), String> {+ if self.machine(machine_id).is_none() {+ return Err("That machine isn't in fleet.toml anymore.".into());+ }+ if self.machine_busy(machine_id) {+ return Err("An operation is still running on this machine. Wait for it to finish.".into());+ }+ let edit = |text: &str| inventory_edit::remove_machine(text, machine_id);+ match self.demo_world() {+ Some(w) => w.edit_inventory(edit)?,+ None => inventory_edit::edit_file(self.inventory_path(), edit)?,+ }+ self.reload_inventory_now();+ Ok(())+ }++ /// Unused runner names for a machine: "<machine-id>-01", "-02", ... skipping taken ones.+ pub fn suggest_runner_names(&self, machine_id: &str, count: usize) -> Vec<String> {+ let taken: HashSet<String> = self.current().runners.iter().map(|r| r.name.to_ascii_lowercase()).collect();+ (1..)+ .map(|i| format!("{machine_id}-{i:02}"))+ .filter(|n| !taken.contains(&n.to_ascii_lowercase()))+ .take(count)+ .collect()+ }++ fn validate_install(&self, mut req: InstallRequest) -> Result<InstallRequest, String> {+ let (spec, _) = self.machine(&req.machine_id).ok_or("That machine isn't in fleet.toml anymore.")?;+ if !spec.is_checkable() {+ return Err(format!("{} has no host in fleet.toml, so OpenRunner can't reach it.", spec.name));+ }+ if self.machine_busy(&spec.id) {+ return Err(format!("Another operation is already changing {}. Wait for it to finish.", spec.name));+ }++ req.scope = crate::config::strip_github_url(&req.scope);+ if req.scope.is_empty() {+ return Err("Pick the GitHub org or repo to register the runners with.".into());+ }+ if req.scope.split('/').count() > 2 || !req.scope.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {+ return Err(format!("\"{}\" isn't an org or owner/repo.", req.scope));+ }++ req.names = req.names.iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).collect();+ if req.names.is_empty() {+ return Err("Give the runner a name.".into());+ }+ let taken: HashSet<String> = self.current().runners.iter().map(|r| r.name.to_ascii_lowercase()).collect();+ let mut seen = HashSet::new();+ for n in &req.names {+ if !valid_runner_name(n) {+ return Err(format!("\"{n}\" isn't a valid runner name. Use letters, numbers, '-', '_' and '.'."));+ }+ if !seen.insert(n.to_ascii_lowercase()) {+ return Err(format!("\"{n}\" is listed twice."));+ }+ if taken.contains(&n.to_ascii_lowercase()) {+ return Err(format!("A runner called \"{n}\" already exists."));+ }+ }++ req.labels = req.labels.iter().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect();+ for l in &req.labels {+ if l.len() > 100 || !l.chars().all(|c| c.is_ascii_alphanumeric() || "-_.:/".contains(c)) {+ return Err(format!("\"{l}\" isn't a valid label. Use letters, numbers, '-', '_', '.', ':' and '/'."));+ }+ }+ if let InstallMode::Docker { image: Some(image), .. } = &req.mode {+ if !valid_image(image) {+ return Err(format!("\"{image}\" isn't a Docker image reference."));+ }+ }+ if matches!(req.mode, InstallMode::Docker { .. }) && (spec.shell == Some(Shell::Powershell)) {+ return Err(format!("Docker runners need a machine with a POSIX shell; {} uses PowerShell.", spec.name));+ }+ req.group = req.group.map(|g| g.trim().to_string()).filter(|g| !g.is_empty() && !g.eq_ignore_ascii_case("default"));+ if let Some(g) = &req.group {+ if g.len() > 100 || !g.chars().all(|c| c.is_ascii_alphanumeric() || " -_.".contains(c)) {+ return Err(format!("\"{g}\" isn't a valid runner group name."));+ }+ if req.scope.contains('/') {+ return Err("Runner groups only apply to organization runners.".into());+ }+ }+ Ok(req)+ }+}++/// Host aliases from ~/.ssh/config (no wildcards), for the "Add machine" suggestions.+pub fn ssh_hosts() -> Vec<String> {+ let Some(home) = dirs::home_dir() else { return Vec::new() };+ std::fs::read_to_string(home.join(".ssh").join("config")).map(|t| parse_ssh_hosts(&t)).unwrap_or_default()+}++/// Git hosting entries in ~/.ssh/config aren't machines you'd put runners on.+fn is_git_host(name: &str) -> bool {+ let n = name.to_ascii_lowercase();+ ["github.com", "gitlab.com", "bitbucket.org", "codeberg.org", "ssh.dev.azure.com", "vs-ssh.visualstudio.com"]+ .iter()+ .any(|g| n == *g || n.ends_with(&format!(".{g}")))+}++fn parse_ssh_hosts(text: &str) -> Vec<String> {+ let mut hosts: Vec<String> = Vec::new();+ for line in text.lines() {+ let line = line.trim();+ if line.starts_with('#') {+ continue;+ }+ // "Host a b", "Host=a", "host a # comment"+ let (key, rest) = match line.split_once(|c: char| c.is_whitespace() || c == '=') {+ Some(parts) => parts,+ None => continue,+ };+ if !key.eq_ignore_ascii_case("host") {+ continue;+ }+ let rest = rest.split('#').next().unwrap_or("");+ for name in rest.split(|c: char| c.is_whitespace() || c == '=').map(|n| n.trim_matches('"')) {+ if !name.is_empty() && !name.contains(['*', '?', '!']) && !is_git_host(name) && !hosts.iter().any(|h| h == name) {+ hosts.push(name.to_string());+ }+ }+ }+ hosts.sort();+ hosts+}++// ---------------------------------------------------------------------------++enum Plan {+ /// Run the control script on the runner's machine.+ OnMachine { spec: MachineSpec, probe: Option<ProbeResult>, dir: String, container: Option<String>, scope: Option<String>, delete_files: bool },+ /// The machine is gone or unreachable: deregister through the GitHub API.+ GitHubOnly,+ /// Not installed anywhere we can see; just drop it from fleet.toml.+ InventoryOnly,+}++fn step(engine: &Arc<Engine>, op: u64, text: impl std::fmt::Display) {+ engine.op_log(op, format!("▸ {text}"));+}++fn finish(engine: &Arc<Engine>, op: u64, result: Result<(), String>) {+ if let Err(e) = &result {+ engine.op_log(op, format!("error: {e}"));+ }+ engine.op_finish(op, result);+}++fn valid_runner_name(n: &str) -> bool {+ !n.is_empty()+ && n.len() <= 64+ && !n.starts_with(['-', '.'])+ && n.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))+}++fn validate_machine(name: &str, host: &str) -> Result<(), String> {+ if name.is_empty() {+ return Err("Give the machine a name.".into());+ }+ if name.len() > 80 || name.chars().any(char::is_control) {+ return Err("That name is too long or has odd characters.".into());+ }+ if host.is_empty() {+ return Err("Enter an ssh destination (like [email protected] or an ~/.ssh/config alias), or \"local\".".into());+ }+ // A leading '-' would be read by ssh as an option.+ if host.starts_with('-') || host.len() > 255 || !host.chars().all(|c| c.is_ascii_alphanumeric() || "@._-:[]%".contains(c)) {+ return Err(format!("\"{host}\" isn't an ssh destination OpenRunner can use."));+ }+ Ok(())+}++/// "org:acme" -> "acme"; falls back to the gitHubUrl in the runner's .runner file.+fn runner_scope(runner: &Runner) -> Option<String> {+ runner+ .github+ .as_ref()+ .map(|g| g.scope.split_once(':').map(|(_, s)| s.to_string()).unwrap_or_else(|| g.scope.clone()))+ .or_else(|| runner.local.as_ref().and_then(|l| l.url.as_deref()).and_then(scope_from_runner_url))+}++/// Names the install script reported as done ("✓ <name> is installed").+fn installed_names(engine: &Engine, op: u64, names: &[String]) -> Vec<String> {+ let snap = engine.current();+ let Some(o) = snap.operations.iter().find(|o| o.id == op) else { return Vec::new() };+ names.iter().filter(|n| o.log.iter().any(|l| l == &format!("✓ {n} is installed"))).cloned().collect()+}++async fn install(engine: &Arc<Engine>, op: u64, req: &InstallRequest, spec: &MachineSpec, probe: Option<ProbeResult>) -> Result<(), String> {+ let settings: Settings = engine.settings();+ // Always look at the machine first: the install mode depends on what it can do+ // right now (sudo, Docker), and the last check may be old.+ step(engine, op, format!("Checking {}", spec.name));+ let probe = probe::probe(spec, probe.and_then(|p| p.shell)).await;+ if !probe.ok {+ return Err(format!("Couldn't reach {}: {}", spec.name, probe.error.unwrap_or_default()));+ }+ let (mode, why) = resolve_mode(&req.mode, req.as_service, &probe);+ engine.op_log(op, format!("Install mode: {}{}", mode_label(&mode), why.map(|w| format!(" ({w})")).unwrap_or_default()));+ if let InstallMode::Docker { image, docker_socket } = &mode {+ return install_docker(engine, op, req, spec, &probe, image.clone(), *docker_socket).await;+ }+ let as_service = mode == InstallMode::Service;+ let shell = remote::shell_for(spec, Some(&probe));++ step(engine, op, format!("Requesting a registration token from GitHub for {}", req.scope));+ let token = engine.github().registration_token(&settings.github, &req.scope).await?;+ step(engine, op, "Looking up the latest runner release");+ let version = engine+ .github()+ .latest_runner_release(&settings.github)+ .await+ .unwrap_or_else(|| FALLBACK_RUNNER_VERSION.to_string());+ engine.op_log(op, format!("actions-runner {version}"));++ step(engine, op, format!("Installing on {} ({})", spec.name, spec.host.trim()));+ let url = engine.github().web_url(&settings.github, &req.scope);+ let labels = req.labels.join(",");+ let group = req.group.clone().unwrap_or_default();+ let params = [+ ("OR_VERSION", Param::Str(&version)),+ ("OR_URL", Param::Str(&url)),+ ("OR_TOKEN", Param::Str(&token)),+ ("OR_NAMES", Param::List(&req.names)),+ ("OR_LABELS", Param::Str(&labels)),+ ("OR_GROUP", Param::Str(&group)),+ ("OR_SERVICE", Param::Bool(as_service)),+ ("OR_BASE", Param::Str("")),+ ];+ let script = match shell {+ Shell::Sh => with_params(shell, ¶ms, INSTALL_SH),+ Shell::Powershell => with_params(shell, ¶ms, INSTALL_PS1),+ };+ let ran = remote::run(engine, op, spec, shell, script, &[token], INSTALL_TIMEOUT).await;+ record_installed(engine, op, req, spec, ran).await+}++fn mode_label(mode: &InstallMode) -> String {+ match mode {+ InstallMode::Auto | InstallMode::Service => mode.name().into(),+ InstallMode::Background => "background (run.sh, not restarted after a reboot)".into(),+ InstallMode::Docker { image, docker_socket } => format!(+ "Docker{}{}",+ image.as_ref().map(|i| format!(" ({i})")).unwrap_or_default(),+ if *docker_socket { ", with the host's Docker socket" } else { "" }+ ),+ }+}++/// Containers from GitHub's runner image: no sudo, restarted by the Docker daemon.+#[allow(clippy::too_many_arguments)]+async fn install_docker(+ engine: &Arc<Engine>,+ op: u64,+ req: &InstallRequest,+ spec: &MachineSpec,+ probe: &ProbeResult,+ image: Option<String>,+ docker_socket: bool,+) -> Result<(), String> {+ if probe.docker.is_none() {+ let why = probe.docker_error.clone().unwrap_or_else(|| "it isn't installed".into());+ return Err(format!("Docker isn't usable on {}: {why}", spec.name));+ }+ if probe.os.as_deref() == Some("windows") {+ return Err("Docker runners aren't supported on Windows machines yet.".into());+ }+ let settings = engine.settings();+ step(engine, op, format!("Requesting a registration token from GitHub for {}", req.scope));+ let token = engine.github().registration_token(&settings.github, &req.scope).await?;+ let (image, fallback) = match image {+ Some(i) => (i, String::new()),+ None => {+ step(engine, op, "Looking up the latest runner release");+ let version = engine.github().latest_runner_release(&settings.github).await.unwrap_or_else(|| FALLBACK_RUNNER_VERSION.to_string());+ (format!("{RUNNER_IMAGE}:{version}"), format!("{RUNNER_IMAGE}:latest"))+ }+ };+ let url = engine.github().web_url(&settings.github, &req.scope);+ let labels = docker_labels(&req.labels).join(",");+ let group = req.group.clone().unwrap_or_default();+ step(engine, op, format!("Starting runner containers on {} ({})", spec.name, spec.host.trim()));+ let script = docker_install_script(&image, &fallback, &url, &req.scope, &token, &req.names, &labels, &group, docker_socket, false);+ let ran = remote::run(engine, op, spec, Shell::Sh, script, &[token], INSTALL_TIMEOUT).await;+ record_installed(engine, op, req, spec, ran).await+}++/// The user's labels plus "docker", so workflows can target container runners.+fn docker_labels(labels: &[String]) -> Vec<String> {+ let mut out = labels.to_vec();+ if !out.iter().any(|l| l.eq_ignore_ascii_case("docker")) {+ out.push("docker".into());+ }+ out+}++#[allow(clippy::too_many_arguments)]+fn docker_install_script(+ image: &str,+ fallback: &str,+ url: &str,+ scope: &str,+ token: &str,+ names: &[String],+ labels: &str,+ group: &str,+ docker_socket: bool,+ stub: bool,+) -> String {+ let params = [+ ("OR_IMAGE", Param::Str(image)),+ ("OR_IMAGE_FALLBACK", Param::Str(fallback)),+ ("OR_URL", Param::Str(url)),+ ("OR_SCOPE", Param::Str(scope)),+ ("OR_TOKEN", Param::Str(token)),+ ("OR_NAMES", Param::List(names)),+ ("OR_LABELS", Param::Str(labels)),+ ("OR_GROUP", Param::Str(group)),+ ("OR_SOCKET", Param::Bool(docker_socket)),+ ("OR_STUB", Param::Bool(stub)),+ ];+ with_params(Shell::Sh, ¶ms, INSTALL_DOCKER_SH)+}++/// Adds what got installed to fleet.toml (even if a later runner failed) and refreshes.+async fn record_installed(engine: &Arc<Engine>, op: u64, req: &InstallRequest, spec: &MachineSpec, ran: Result<(), String>) -> Result<(), String> {+ let done = if ran.is_ok() { req.names.clone() } else { installed_names(engine, op, &req.names) };+ if !done.is_empty() {+ step(engine, op, format!("Adding {} to fleet.toml", done.join(", ")));+ let edit = inventory_edit::edit_file(engine.inventory_path(), |t| inventory_edit::add_runners(t, &spec.id, &done));+ if let Err(e) = edit {+ engine.op_log(op, format!("warning: {e} The runners still show up because OpenRunner discovers them."));+ }+ engine.reload_inventory_now();+ }+ refresh(engine, op, Some(spec)).await;+ ran+}++async fn run_action(engine: &Arc<Engine>, op: u64, runner: &Runner, action: RunnerAction, plan: Plan) -> Result<(), String> {+ let settings = engine.settings();+ match plan {+ Plan::OnMachine { spec, probe, dir, container, scope, delete_files } => {+ let shell = if container.is_some() { Shell::Sh } else { remote::shell_for(&spec, probe.as_ref()) };+ let mut secrets = Vec::new();+ let mut token = String::new();+ if let (RunnerAction::Remove { .. }, Some(scope)) = (action, scope.as_deref()) {+ step(engine, op, format!("Requesting a removal token from GitHub for {scope}"));+ token = engine.github().remove_token(&settings.github, scope).await?;+ secrets.push(token.clone());+ }+ step(engine, op, format!("{} {} on {}", verb(action), runner.name, spec.name));+ let script = match &container {+ Some(c) => control_docker_script(action, c, &token, delete_files),+ None => {+ let params = [+ ("OR_ACTION", Param::Str(action.kind())),+ ("OR_DIR", Param::Str(&dir)),+ ("OR_TOKEN", Param::Str(&token)),+ ("OR_DELETE", Param::Bool(delete_files)),+ ];+ match shell {+ Shell::Sh => with_params(shell, ¶ms, CONTROL_SH),+ Shell::Powershell => with_params(shell, ¶ms, CONTROL_PS1),+ }+ }+ };+ remote::run(engine, op, &spec, shell, script, &secrets, CONTROL_TIMEOUT).await?;+ if let RunnerAction::Remove { .. } = action {+ forget_runner(engine, op, runner);+ }+ if action != RunnerAction::Logs {+ refresh(engine, op, Some(&spec)).await;+ }+ Ok(())+ }+ Plan::GitHubOnly => {+ let gh = runner.github.as_ref().ok_or("GitHub doesn't know this runner.")?;+ step(engine, op, format!("Removing {} from GitHub ({})", runner.name, gh.scope));+ engine.github().delete_runner(&settings.github, &gh.scope, gh.id).await?;+ engine.op_log(op, format!("✓ {} is no longer registered", runner.name));+ if runner.machine_id.is_some() {+ engine.op_log(op, "The runner's files on its machine weren't touched, because OpenRunner couldn't reach it.");+ }+ forget_runner(engine, op, runner);+ refresh(engine, op, None).await;+ Ok(())+ }+ Plan::InventoryOnly => {+ forget_runner(engine, op, runner);+ refresh(engine, op, None).await;+ Ok(())+ }+ }+}++fn control_docker_script(action: RunnerAction, container: &str, token: &str, delete_files: bool) -> String {+ let params = [+ ("OR_ACTION", Param::Str(action.kind())),+ ("OR_CONTAINER", Param::Str(container)),+ ("OR_TOKEN", Param::Str(token)),+ ("OR_DELETE", Param::Bool(delete_files)),+ ];+ with_params(Shell::Sh, ¶ms, CONTROL_DOCKER_SH)+}++/// Drops a removed runner from fleet.toml if it was listed there.+fn forget_runner(engine: &Arc<Engine>, op: u64, runner: &Runner) {+ let (Some(mid), true) = (runner.machine_id.as_deref(), runner.declared) else { return };+ step(engine, op, format!("Removing {} from fleet.toml", runner.name));+ let edit = |t: &str| inventory_edit::remove_runner(t, mid, &runner.name);+ let result = match engine.demo_world() {+ Some(w) => w.edit_inventory(edit),+ None => inventory_edit::edit_file(engine.inventory_path(), edit),+ };+ if let Err(e) = result {+ engine.op_log(op, format!("warning: {e}"));+ }+ engine.reload_inventory_now();+}++/// Re-checks the machine (if any) and syncs GitHub so the dashboard shows the result.+async fn refresh(engine: &Arc<Engine>, op: u64, spec: Option<&MachineSpec>) {+ if let Some(spec) = spec {+ step(engine, op, format!("Checking {}", spec.name));+ engine.run_check(Some(vec![spec.id.clone()])).await;+ }+ engine.sync_github().await;+}++fn verb(action: RunnerAction) -> &'static str {+ match action {+ RunnerAction::Start => "Starting",+ RunnerAction::Stop => "Stopping",+ RunnerAction::Restart => "Restarting",+ RunnerAction::Logs => "Reading the log of",+ RunnerAction::Remove { .. } => "Removing",+ }+}++// ---------------------------------------------------------------------------+// Demo mode: the same steps against the simulated fleet, nothing leaves the process.++async fn pause(ms: u64) {+ tokio::time::sleep(Duration::from_millis(ms)).await;+}++async fn demo_install(engine: &Arc<Engine>, op: u64, req: &InstallRequest, spec: &MachineSpec) -> Result<(), String> {+ let w = engine.demo_world().cloned().ok_or("not in demo mode")?;+ step(engine, op, format!("Checking {}", spec.name));+ pause(300).await;+ w.reachable(&spec.id, spec.host.trim())?;+ let probe = w.probe(spec).await;+ let (mode, why) = resolve_mode(&req.mode, req.as_service, &probe);+ engine.op_log(op, format!("Install mode: {}{}", mode_label(&mode), why.map(|w| format!(" ({w})")).unwrap_or_default()));+ if let InstallMode::Docker { image, docker_socket } = &mode {+ if probe.docker.is_none() {+ return Err(format!("Docker isn't usable on {}: it isn't installed", spec.name));+ }+ return demo_install_docker(engine, op, req, spec, image.clone(), *docker_socket).await;+ }+ let as_service = mode == InstallMode::Service;+ step(engine, op, format!("Requesting a registration token from GitHub for {}", req.scope));+ pause(500).await;+ step(engine, op, "Looking up the latest runner release");+ pause(300).await;+ engine.op_log(op, "actions-runner 2.329.0");+ step(engine, op, format!("Installing on {} ({})", spec.name, spec.host.trim()));+ pause(400).await;+ w.reachable(&spec.id, spec.host.trim())?;++ let (os, arch) = w.runner_platform(&spec.id);+ let home = match os {+ "win" => "C:\\actions-runner".to_string(),+ "linux" => "/home/ci/actions-runner".to_string(),+ _ => "/Users/ci/actions-runner".to_string(),+ };+ let sep = if os == "win" { "\\" } else { "/" };+ engine.op_log(op, format!("Downloading actions-runner 2.329.0 for {os}-{arch}…"));+ pause(900).await;+ for name in &req.names {+ let dir = format!("{home}{sep}{name}");+ let url = format!("https://github.com/{}", req.scope);+ let lines = [+ format!("Setting up {name} in {dir}"),+ "--------------------------------------------------------------------------------".into(),+ "| Self-hosted runner registration |".into(),+ "--------------------------------------------------------------------------------".into(),+ "# Authentication".into(),+ format!("√ Connected to GitHub ({url})"),+ "# Runner Registration".into(),+ format!("√ Runner successfully added ({name})"),+ "√ Runner connection is good".into(),+ "# Runner settings".into(),+ "√ Settings Saved.".into(),+ ];+ for l in lines {+ engine.op_log(op, l);+ pause(140).await;+ }+ if as_service {+ engine.op_log(op, format!("Installing {name} as a service…"));+ pause(300).await;+ engine.op_log(op, match os {+ "osx" => format!("Creating launch runner in /Users/ci/Library/LaunchAgents/actions.runner.{}.{name}.plist", req.scope.replace('/', "-")),+ "win" => format!("Service actions.runner.{}.{name} successfully installed", req.scope.replace('/', "-")),+ _ => format!("Creating launch runner in /etc/systemd/system/actions.runner.{}.{name}.service", req.scope.replace('/', "-")),+ });+ engine.op_log(op, format!("Starting actions.runner.{}.{name}", req.scope.replace('/', "-")));+ } else {+ engine.op_log(op, format!("Starting {name} in the background (not a service, so it won't come back after a reboot)…"));+ }+ pause(250).await;+ engine.op_log(op, format!("✓ {name} is installed"));+ }++ w.install_runners(&spec.id, &req.names, &req.labels, false);+ step(engine, op, format!("Adding {} to fleet.toml", req.names.join(", ")));+ w.edit_inventory(|t| inventory_edit::add_runners(t, &spec.id, &req.names))?;+ engine.reload_inventory_now();+ refresh(engine, op, Some(spec)).await;+ Ok(())+}++async fn demo_install_docker(engine: &Arc<Engine>, op: u64, req: &InstallRequest, spec: &MachineSpec, image: Option<String>, docker_socket: bool) -> Result<(), String> {+ let w = engine.demo_world().cloned().ok_or("not in demo mode")?;+ step(engine, op, format!("Requesting a registration token from GitHub for {}", req.scope));+ pause(500).await;+ let image = image.unwrap_or_else(|| format!("{RUNNER_IMAGE}:2.329.0"));+ step(engine, op, format!("Starting runner containers on {} ({})", spec.name, spec.host.trim()));+ engine.op_log(op, format!("Pulling {image} (about 2 GB the first time)…"));+ pause(400).await;+ for l in ["2.329.0: Pulling from actions/actions-runner", "Digest: sha256:7c1f0d2e9a4b…", &format!("Status: Downloaded newer image for {image}")] {+ engine.op_log(op, l.to_string());+ pause(250).await;+ }+ if docker_socket {+ engine.op_log(op, "warning: the runners get this machine's Docker socket, which is root-equivalent access to the machine. Only run trusted workflows on them.");+ }+ for name in &req.names {+ engine.op_log(op, format!("Setting up {name} (container openrunner-{name}, volume openrunner-{name})"));+ pause(300).await;+ for l in [+ "# Authentication".to_string(),+ format!("√ Connected to GitHub (https://github.com/{})", req.scope),+ "# Runner Registration".into(),+ format!("√ Runner successfully added ({name})"),+ "√ Runner connection is good".into(),+ "√ Settings Saved.".into(),+ ] {+ engine.op_log(op, l);+ pause(140).await;+ }+ engine.op_log(op, format!("✓ {name} is installed"));+ }+ w.install_runners(&spec.id, &req.names, &docker_labels(&req.labels), true);+ step(engine, op, format!("Adding {} to fleet.toml", req.names.join(", ")));+ w.edit_inventory(|t| inventory_edit::add_runners(t, &spec.id, &req.names))?;+ engine.reload_inventory_now();+ refresh(engine, op, Some(spec)).await;+ Ok(())+}++async fn demo_action(engine: &Arc<Engine>, op: u64, runner: &Runner, action: RunnerAction) -> Result<(), String> {+ let w = engine.demo_world().cloned().ok_or("not in demo mode")?;+ let machine = runner.machine_id.as_deref().and_then(|id| engine.machine(id));+ if let Some((spec, _)) = &machine {+ step(engine, op, format!("{} {} on {}", verb(action), runner.name, spec.name));+ pause(400).await;+ w.reachable(&spec.id, spec.host.trim())?;+ }+ let container = runner.local.as_ref().and_then(|l| l.container.clone());+ let service = match &container {+ Some(c) => format!("container {c}"),+ None => format!("service actions.runner.acme.{}", runner.name),+ };+ match action {+ RunnerAction::Start => {+ engine.op_log(op, format!("Starting {service}…"));+ pause(700).await;+ w.set_runner_online(&runner.name, true);+ engine.op_log(op, "✓ Started");+ }+ RunnerAction::Stop => {+ engine.op_log(op, format!("Stopping {service}…"));+ pause(700).await;+ w.set_runner_online(&runner.name, false);+ engine.op_log(op, "✓ Stopped");+ }+ RunnerAction::Restart => {+ engine.op_log(op, format!("Stopping {service}…"));+ pause(500).await;+ w.set_runner_online(&runner.name, false);+ engine.op_log(op, format!("Starting {service}…"));+ pause(700).await;+ w.set_runner_online(&runner.name, true);+ engine.op_log(op, "✓ Restarted");+ }+ RunnerAction::Logs => {+ let dir = runner.local.as_ref().map(|l| l.dir.clone()).unwrap_or_default();+ engine.op_log(op, match &container {+ Some(c) => format!("==> docker logs {c} (last 200 lines)"),+ None => format!("==> {dir}/_diag/Runner_20261008-141502-utc.log (last 200 lines)"),+ });+ for line in w.diag_log(&runner.name) {+ engine.op_log(op, line);+ }+ return Ok(());+ }+ RunnerAction::Remove { delete_files } => {+ if runner.machine_id.is_none() {+ step(engine, op, format!("Removing {} from GitHub (org:acme)", runner.name));+ pause(600).await;+ } else {+ step(engine, op, "Requesting a removal token from GitHub for acme");+ pause(400).await;+ engine.op_log(op, format!("Stopping {service}…"));+ pause(400).await;+ if container.is_none() {+ engine.op_log(op, "Uninstalling the service…");+ pause(300).await;+ }+ engine.op_log(op, "Removing the runner from GitHub…");+ engine.op_log(op, "√ Runner removed successfully");+ if let Some(c) = &container {+ engine.op_log(op, format!("Removed container {c}"));+ if delete_files {+ engine.op_log(op, format!("Deleted volume {c}"));+ }+ } else if delete_files {+ let dir = runner.local.as_ref().map(|l| l.dir.clone()).unwrap_or_default();+ engine.op_log(op, format!("Deleted {dir}"));+ }+ }+ w.remove_runner(&runner.name);+ engine.op_log(op, "✓ Removed");+ forget_runner(engine, op, runner);+ }+ }+ refresh(engine, op, machine.as_ref().map(|(spec, _)| spec)).await;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_ssh_config_hosts() {+ let text = "\+Host beelink beelink-dev+ HostName 10.0.0.4+Host *.internal+Host=umbrel+host github.com # comment+Host !bad ok? fine+Match host x+";+ assert_eq!(parse_ssh_hosts(text), vec!["beelink", "beelink-dev", "fine", "umbrel"]);+ }++ #[test]+ fn parses_install_modes() {+ assert_eq!(InstallMode::parse("", None, false).unwrap(), InstallMode::Auto);+ assert_eq!(InstallMode::parse("Service", None, false).unwrap(), InstallMode::Service);+ assert_eq!(+ InstallMode::parse("docker", Some(" ghcr.io/me/runner:1 ".into()), true).unwrap(),+ InstallMode::Docker { image: Some("ghcr.io/me/runner:1".into()), docker_socket: true }+ );+ assert!(InstallMode::parse("vm", None, false).is_err());+ assert!(InstallMode::parse("service", Some("x".into()), false).is_err(), "image only goes with docker");+ assert!(valid_image("ghcr.io/actions/actions-runner:2.329.0"));+ assert!(valid_image("me/runner@sha256:abc"));+ assert!(!valid_image("--privileged"));+ assert!(!valid_image("a b"));+ assert_eq!(docker_labels(&["gpu".into()]), vec!["gpu", "docker"]);+ assert_eq!(docker_labels(&["Docker".into()]), vec!["Docker"]);+ }++ #[test]+ fn auto_mode_follows_the_machine() {+ let machine = |os: &str, sudo: Option<&str>, docker: Option<&str>| ProbeResult {+ ok: true,+ os: Some(os.into()),+ sudo: sudo.map(String::from),+ docker: docker.map(String::from),+ ..Default::default()+ };+ let auto = |p: &ProbeResult| resolve_mode(&InstallMode::Auto, true, p).0;+ assert_eq!(auto(&machine("darwin", None, Some("29"))), InstallMode::Service);+ assert_eq!(auto(&machine("windows", None, None)), InstallMode::Service);+ assert_eq!(auto(&machine("linux", Some("passwordless"), Some("29"))), InstallMode::Service);+ assert_eq!(auto(&machine("linux", Some("root"), None)), InstallMode::Service);+ assert_eq!(auto(&machine("linux", Some("password"), Some("29"))), InstallMode::Docker { image: None, docker_socket: false });+ let (mode, why) = resolve_mode(&InstallMode::Auto, true, &machine("linux", Some("password"), None));+ assert_eq!(mode, InstallMode::Background);+ assert!(why.unwrap().contains("reboot"));+ // The legacy switch still means "background", and explicit modes are kept.+ assert_eq!(resolve_mode(&InstallMode::Auto, false, &machine("darwin", None, None)).0, InstallMode::Background);+ assert_eq!(resolve_mode(&InstallMode::Service, true, &machine("linux", Some("password"), None)).0, InstallMode::Service);+ }++ #[test]+ fn docker_install_script_keeps_the_token_out_of_argv() {+ let script = docker_install_script(+ "ghcr.io/actions/actions-runner:2.329.0",+ "ghcr.io/actions/actions-runner:latest",+ "https://github.com/acme",+ "acme",+ "SECRET'TOKEN",+ &["b-01".into()],+ "gpu,docker",+ "",+ false,+ false,+ );+ assert!(script.starts_with("OR_IMAGE='ghcr.io/actions/actions-runner:2.329.0'\n"));+ assert!(script.contains("OR_TOKEN='SECRET'\\''TOKEN'\n"), "{}", &script[..400]);+ // The token is only ever piped in on stdin.+ assert!(script.contains("printf '%s' \"$OR_TOKEN\" | docker run --rm -i"));+ assert!(!script.contains("--token \"$OR_TOKEN\""));+ }++ #[test]+ fn validates_names_and_hosts() {+ assert!(valid_runner_name("mac-studio-08"));+ assert!(valid_runner_name("win_01.a"));+ assert!(!valid_runner_name("-x"));+ assert!(!valid_runner_name("a b"));+ assert!(!valid_runner_name("a'b"));+ assert!(validate_machine("Beelink", "[email protected]").is_ok());+ assert!(validate_machine("Beelink", "local").is_ok());+ assert!(validate_machine("Beelink", "-oProxyCommand=x").is_err());+ assert!(validate_machine("Beelink", "a b").is_err());+ assert!(validate_machine("", "x").is_err());+ }+}++/// End-to-end: real engine, real scripts, against a stub runner on this machine.+#[cfg(all(test, unix))]+mod engine_tests {+ use std::os::unix::fs::PermissionsExt;+ use std::path::Path;++ use super::*;+ use crate::config::Paths;+ use crate::fleet::model::Operation;++ fn write_exec(path: &Path, body: &str) {+ std::fs::write(path, body).unwrap();+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }++ /// A runner folder whose scripts behave like the real ones, minus GitHub.+ fn stub_runner(dir: &Path, name: &str) {+ std::fs::create_dir_all(dir.join("bin")).unwrap();+ std::fs::create_dir_all(dir.join("_diag")).unwrap();+ std::fs::write(dir.join(".runner"), format!("{{\"agentName\":\"{name}\",\"gitHubUrl\":\"https://github.com/acme\"}}")).unwrap();+ std::fs::write(dir.join("_diag/Runner_20261008-120000-utc.log"), "[INFO Listener] Listening for Jobs\n").unwrap();+ write_exec(&dir.join("config.sh"), "#!/bin/sh\nexit 0\n");+ write_exec(&dir.join("run.sh"), "#!/bin/sh\nDIR=$(cd \"$(dirname \"$0\")\" && pwd)\n\"$DIR/bin/Runner.Listener\" run\n");+ write_exec(&dir.join("bin/Runner.Listener"), "#!/bin/sh\n[ \"$1\" = --version ] && { echo 2.329.0; exit 0; }\nsleep 120\n");+ }++ async fn wait(engine: &Arc<Engine>, op: u64) -> Operation {+ for _ in 0..600 {+ if let Some(o) = engine.current().operations.iter().find(|o| o.id == op && o.status != "running") {+ return o.clone();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("operation {op} didn't finish");+ }++ fn state(engine: &Engine, id: &str) -> String {+ engine.current().runners.iter().find(|r| r.id == id).map(|r| r.state.clone()).unwrap_or_default()+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn controls_a_local_runner() {+ let tmp = std::env::temp_dir().join(format!("openrunner-ops-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ let base = tmp.join("runners");+ stub_runner(&base.join("or-test-01"), "or-test-01");+ std::fs::write(+ tmp.join("fleet.toml"),+ format!("# test fleet\n[[machine]]\nname = \"Here\"\nhost = \"local\"\nrunners = [\"or-test-01\"]\nrunner_dirs = [\"{}/*\"]\n", base.display()),+ )+ .unwrap();++ let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);+ engine.run_check(None).await;+ let id = "here/or-test-01";+ assert_eq!(state(&engine, id), "offline", "{:?}", engine.current().machines[0].diagnostics);++ let op = engine.runner_action(id, RunnerAction::Logs).unwrap();+ let o = wait(&engine, op).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert!(o.log.iter().any(|l| l.contains("Listening for Jobs")), "{:?}", o.log);++ let o = wait(&engine, engine.runner_action(id, RunnerAction::Start).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert_eq!(state(&engine, id), "idle");++ let o = wait(&engine, engine.runner_action(id, RunnerAction::Stop).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert!(o.log.iter().any(|l| l == "Stopped."), "{:?}", o.log);+ assert_eq!(state(&engine, id), "offline");++ // Machines can be added and removed without losing the file's comments.+ let new_id = engine.add_machine(NewMachine { name: "Spare".into(), host: "spare.local".into() }).unwrap();+ assert_eq!(new_id, "spare");+ assert!(engine.current().machines.iter().any(|m| m.id == "spare"));+ engine.remove_machine("spare").unwrap();+ let text = std::fs::read_to_string(tmp.join("fleet.toml")).unwrap();+ assert!(text.starts_with("# test fleet") && !text.contains("Spare"), "{text}");+ assert_eq!(engine.suggest_runner_names("here", 2), vec!["here-01", "here-02"]);++ let _ = std::fs::remove_dir_all(&tmp);+ }++ #[tokio::test(flavor = "multi_thread")]+ async fn demo_docker_install() {+ let engine = Engine::new(Paths::resolve(Some(std::env::temp_dir()), None), true);+ engine.run_check(Some(vec!["ubuntu-nuc".into()])).await;+ // sudo asks for a password on the demo NUC, so Auto picks Docker.+ let req = InstallRequest {+ machine_id: "ubuntu-nuc".into(),+ scope: "acme".into(),+ names: vec!["nuc-docker-01".into()],+ labels: vec![],+ group: None,+ as_service: true,+ mode: InstallMode::Auto,+ };+ let o = wait(&engine, engine.install_runners(req).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert!(o.log.iter().any(|l| l.starts_with("Install mode: Docker")), "{:?}", o.log);+ let snap = engine.current();+ let r = snap.runners.iter().find(|r| r.id == "ubuntu-nuc/nuc-docker-01").expect("installed runner shows up");+ let local = r.local.as_ref().unwrap();+ assert_eq!(local.container.as_deref(), Some("openrunner-nuc-docker-01"));+ assert_eq!(local.dir, "docker://openrunner-nuc-docker-01");+ assert!(r.labels.iter().any(|l| l == "docker"), "{:?}", r.labels);+ assert_eq!(snap.machines.iter().find(|m| m.id == "ubuntu-nuc").unwrap().probe.as_ref().unwrap().docker.as_deref(), Some("29.1.3"));++ let o = wait(&engine, engine.runner_action("ubuntu-nuc/nuc-docker-01", RunnerAction::Stop).unwrap()).await;+ assert_eq!(o.status, "succeeded");+ assert!(o.log.iter().any(|l| l.contains("container openrunner-nuc-docker-01")), "{:?}", o.log);+ assert_eq!(state(&engine, "ubuntu-nuc/nuc-docker-01"), "offline");+ }++ /// Lines an operation logged (after the coalesced publish catches up).+ async fn op_log(engine: &Engine, op: u64) -> Vec<String> {+ tokio::time::sleep(Duration::from_millis(300)).await;+ engine.current().operations.iter().find(|o| o.id == op).map(|o| o.log.clone()).unwrap_or_default()+ }++ /// Real Docker on a real machine, without GitHub: registration is stubbed, and the one+ /// path that does reach GitHub uses a fake token that can't register anything.+ /// Run with: OPENRUNNER_TEST_DOCKER_HOST=<ssh host> cargo test docker_runner_lifecycle -- --ignored+ #[tokio::test(flavor = "multi_thread")]+ #[ignore = "needs a machine with Docker: OPENRUNNER_TEST_DOCKER_HOST=<ssh host>"]+ async fn docker_runner_lifecycle_on_real_host() {+ let Ok(host) = std::env::var("OPENRUNNER_TEST_DOCKER_HOST") else { return };+ let tmp = std::env::temp_dir().join(format!("openrunner-docker-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).unwrap();+ std::fs::write(tmp.join("fleet.toml"), format!("[[machine]]\nname = \"Box\"\nhost = \"{host}\"\n")).unwrap();+ let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);+ engine.run_check(None).await;+ let (spec, probe) = engine.machine("box").unwrap();+ let probe = probe.expect("checked");+ assert!(probe.ok, "{:?}", probe.error);+ assert!(probe.docker.is_some(), "Docker should be usable on {host}");+ let image = "ghcr.io/actions/actions-runner:latest";+ let name = format!("ortest-{}", std::process::id());+ let id = format!("box/{name}");+ let run_script = |script: String| {+ let engine = engine.clone();+ let spec = spec.clone();+ async move {+ let op = engine.begin_op("test", "test".into(), Some("box".into()), None);+ let ran = remote::run(&engine, op, &spec, Shell::Sh, script, &["FAKE0TOKEN".into()], INSTALL_TIMEOUT).await;+ engine.op_finish(op, Ok(()));+ (ran, op_log(&engine, op).await)+ }+ };++ // Leftovers from an earlier run of this test that panicked.+ let _ = run_script(+ "docker ps -aq --filter name=openrunner-ortest- | xargs -r docker rm -f; docker volume ls -q --filter name=openrunner-ortest- | xargs -r docker volume rm".into(),+ )+ .await;++ // 1. A real registration attempt with a fake token fails cleanly: GitHub says no,+ // and no volume or container is left behind.+ let script = docker_install_script(image, "", "https://github.com/openrunner-test-no-such-org-7f3a", "openrunner-test-no-such-org-7f3a", "FAKE0TOKEN", &[name.clone()], "docker", "", false, false);+ let (ran, log) = run_script(script).await;+ assert!(ran.is_err(), "{log:?}");+ assert!(log.iter().any(|l| l.contains("404") || l.contains("Not Found")), "{log:?}");+ assert!(log.iter().all(|l| !l.contains("FAKE0TOKEN")), "token leaked into the log: {log:?}");+ let (_, leftovers) = run_script(format!("docker volume ls -q --filter name=openrunner-{name}; docker ps -aq --filter name=openrunner-{name}")).await;+ assert!(leftovers.is_empty(), "{leftovers:?}");++ // 2. Install with registration stubbed: a long-running container with a restart policy.+ let script = docker_install_script(image, "", "https://github.com/openrunner-test", "openrunner-test", "FAKE0TOKEN", &[name.clone()], "docker", "", false, true);+ let (ran, log) = run_script(script).await;+ assert!(ran.is_ok(), "{log:?}");+ assert!(log.iter().any(|l| l == &format!("✓ {name} is installed")), "{log:?}");+ let (_, inspect) = run_script(format!("docker inspect -f '{{{{.HostConfig.RestartPolicy.Name}}}} {{{{index .Config.Labels \"openrunner.runner\"}}}}' openrunner-{name}; docker inspect openrunner-{name} | grep -c FAKE0TOKEN")).await;+ assert_eq!(inspect, vec![format!("unless-stopped {name}"), "0".to_string()], "{inspect:?}");++ // 3. Machine checks find it as a container runner.+ engine.run_check(Some(vec!["box".into()])).await;+ let snap = engine.current();+ let r = snap.runners.iter().find(|r| r.id == id).unwrap_or_else(|| panic!("{id} not found in {:?}", snap.runners.iter().map(|r| &r.id).collect::<Vec<_>>()));+ let local = r.local.clone().unwrap();+ assert_eq!(local.container.as_deref(), Some(format!("openrunner-{name}").as_str()));+ assert_eq!(local.container_state.as_deref(), Some("running"));+ assert_eq!(local.url.as_deref(), Some("https://github.com/openrunner-test"));+ assert_eq!(r.state, "idle", "{local:?}");++ // 4. Stop / start / restart / logs through the engine (none of these talk to GitHub).+ let o = wait(&engine, engine.runner_action(&id, RunnerAction::Stop).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert_eq!(state(&engine, &id), "offline");+ let o = wait(&engine, engine.runner_action(&id, RunnerAction::Start).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert_eq!(state(&engine, &id), "idle");+ let o = wait(&engine, engine.runner_action(&id, RunnerAction::Restart).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert_eq!(state(&engine, &id), "idle");+ let o = wait(&engine, engine.runner_action(&id, RunnerAction::Logs).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert!(o.log.iter().any(|l| l.contains(&format!("docker logs openrunner-{name}"))), "{:?}", o.log);++ // 5. Remove without a GitHub token (nothing registered), deleting the volume too.+ let runner = engine.current().runners.iter().find(|r| r.id == id).cloned().unwrap();+ let (spec, probe) = engine.machine("box").unwrap();+ let plan = Plan::OnMachine { spec, probe, dir: local.dir.clone(), container: local.container.clone(), scope: None, delete_files: true };+ let op = engine.begin_op("remove", "test".into(), Some("box".into()), Some(id.clone()));+ let removed = run_action(&engine, op, &runner, RunnerAction::Remove { delete_files: true }, plan).await;+ engine.op_finish(op, Ok(()));+ let log = op_log(&engine, op).await;+ assert!(removed.is_ok(), "{log:?}");+ assert!(log.iter().any(|l| l == &format!("Deleted volume openrunner-{name}")), "{log:?}");+ assert!(!engine.current().runners.iter().any(|r| r.id == id));++ let _ = std::fs::remove_dir_all(&tmp);+ }++ #[tokio::test(flavor = "multi_thread")]+ #[ignore = "slow: runs the demo's simulated delays (~15s)"]+ async fn demo_install_stop_remove() {+ let engine = Engine::new(Paths::resolve(Some(std::env::temp_dir()), None), true);+ engine.run_check(None).await;++ let req = InstallRequest {+ machine_id: "ubuntu-nuc".into(),+ scope: "acme".into(),+ names: engine.suggest_runner_names("ubuntu-nuc", 2),+ labels: vec!["gpu".into()],+ group: None,+ as_service: true,+ mode: InstallMode::Auto,+ };+ assert_eq!(req.names, vec!["ubuntu-nuc-01", "ubuntu-nuc-02"]);+ let o = wait(&engine, engine.install_runners(req).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ let snap = engine.current();+ let r = snap.runners.iter().find(|r| r.id == "ubuntu-nuc/ubuntu-nuc-01").expect("installed runner shows up");+ assert!(r.declared && r.labels.contains(&"gpu".to_string()), "{r:?}");++ let o = wait(&engine, engine.runner_action("ubuntu-nuc/ubuntu-nuc-01", RunnerAction::Stop).unwrap()).await;+ assert_eq!(o.status, "succeeded");+ assert_eq!(state(&engine, "ubuntu-nuc/ubuntu-nuc-01"), "offline");++ let o = wait(&engine, engine.runner_action("ubuntu-nuc/ubuntu-nuc-01", RunnerAction::Remove { delete_files: true }).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ assert!(!engine.current().runners.iter().any(|r| r.name == "ubuntu-nuc-01"));++ // The GitHub-only runner can be deregistered; the asleep laptop can't take installs.+ let o = wait(&engine, engine.runner_action("github/linux-spot-01", RunnerAction::Remove { delete_files: false }).unwrap()).await;+ assert_eq!(o.status, "succeeded", "{:?}", o.log);+ let req = InstallRequest {+ machine_id: "laravel-macbook".into(),+ scope: "acme".into(),+ names: vec!["laravel-01".into()],+ labels: vec![],+ group: None,+ as_service: true,+ mode: InstallMode::Auto,+ };+ let o = wait(&engine, engine.install_runners(req).unwrap()).await;+ assert_eq!(o.status, "failed");+ assert!(o.error.unwrap_or_default().contains("timed out"));++ let id = engine.add_machine(NewMachine { name: "Beelink".into(), host: "beelink".into() }).unwrap();+ engine.run_check(Some(vec![id.clone()])).await;+ let m = engine.current().machines.iter().find(|m| m.id == id).cloned().unwrap();+ assert_eq!(m.status, "online");+ assert_eq!(m.platform, "linux-x64");+ }+}diff --git a/src/ops/remote.rs b/src/ops/remote.rsnew file mode 100644index 0000000..b934999--- /dev/null+++ b/src/ops/remote.rs@@ -0,0 +1,242 @@+//! Runs a script on a machine and streams its output into an operation's log.+//! Same transport as machine checks: the script goes over stdin to `sh -s`+//! (locally or through the system `ssh`), or to PowerShell on Windows.++use std::process::Stdio;+use std::sync::Arc;+use std::time::Duration;++use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+use tokio::process::Command;++use crate::config::MachineSpec;+use crate::fleet::Engine;+use crate::probe::{self, ProbeResult, Shell};++/// `-Command -` runs stdin line by line and breaks multi-line blocks; read it whole instead.+const PS_READ_STDIN: &str = "[Console]::In.ReadToEnd() | Invoke-Expression";+const STDERR_TAIL: usize = 4;++/// The shell a machine speaks: pinned in fleet.toml, else what the last check used, else by OS.+pub fn shell_for(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Shell {+ spec.shell+ .or_else(|| probe.and_then(|p| p.shell))+ .unwrap_or_else(|| match probe.and_then(|p| p.os.as_deref()) {+ Some("windows") => Shell::Powershell,+ _ if spec.is_local() && cfg!(windows) => Shell::Powershell,+ _ => Shell::Sh,+ })+}++/// A script parameter, quoted for the target shell.+pub enum Param<'a> {+ Str(&'a str),+ List(&'a [String]),+ Bool(bool),+}++/// Prepends `name='value'` assignments (sh) or `$name = 'value'` (PowerShell) to a script.+pub fn with_params(shell: Shell, params: &[(&str, Param)], script: &str) -> String {+ let mut out = String::new();+ for (name, value) in params {+ let line = match (shell, value) {+ (Shell::Sh, Param::Str(s)) => format!("{name}={}\n", sh_quote(s)),+ (Shell::Sh, Param::List(l)) => format!("{name}={}\n", sh_quote(&l.join(" "))),+ (Shell::Sh, Param::Bool(b)) => format!("{name}={}\n", if *b { 1 } else { 0 }),+ (Shell::Powershell, Param::Str(s)) => format!("${name} = {}\n", ps_quote(s)),+ (Shell::Powershell, Param::List(l)) => {+ format!("${name} = @({})\n", l.iter().map(|s| ps_quote(s)).collect::<Vec<_>>().join(", "))+ }+ (Shell::Powershell, Param::Bool(b)) => format!("${name} = ${b}\n"),+ };+ out.push_str(&line);+ }+ out.push_str(script);+ out+}++pub(crate) fn sh_quote(s: &str) -> String {+ format!("'{}'", s.replace('\'', r"'\''"))+}++pub(crate) fn ps_quote(s: &str) -> String {+ format!("'{}'", s.replace('\'', "''"))+}++/// Runs `script` on the machine, forwarding every output line (secrets masked) to+/// the operation log. Errors carry the last stderr lines, which is where the+/// scripts put their `error: ...` explanation.+pub async fn run(+ engine: &Arc<Engine>,+ op: u64,+ spec: &MachineSpec,+ shell: Shell,+ script: String,+ secrets: &[String],+ timeout: Duration,+) -> Result<(), String> {+ let mut cmd = command(spec, shell);+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);+ let mut child = cmd.spawn().map_err(|e| {+ if spec.is_local() { format!("Couldn't start the script: {e}") } else { format!("Couldn't run ssh: {e}") }+ })?;++ let mut stdin = child.stdin.take().ok_or("No stdin for the script")?;+ let stdout = child.stdout.take().ok_or("No stdout for the script")?;+ let stderr = child.stderr.take().ok_or("No stderr for the script")?;++ let work = async {+ // Ignore write errors (e.g. ssh exiting early); stderr says why.+ let _ = stdin.write_all(script.as_bytes()).await;+ drop(stdin);++ let mut out_lines = BufReader::new(stdout).lines();+ let mut err_lines = BufReader::new(stderr).lines();+ let mut tail: Vec<String> = Vec::new();+ let (mut out_open, mut err_open) = (true, true);+ while out_open || err_open {+ tokio::select! {+ line = out_lines.next_line(), if out_open => match line {+ Ok(Some(l)) => log_line(engine, op, &l, secrets),+ _ => out_open = false,+ },+ line = err_lines.next_line(), if err_open => match line {+ Ok(Some(l)) => {+ let clean = clean_line(&l, secrets);+ if !clean.trim().is_empty() {+ tail.push(clean.clone());+ if tail.len() > STDERR_TAIL {+ tail.remove(0);+ }+ engine.op_log(op, clean);+ }+ }+ _ => err_open = false,+ },+ }+ }+ let status = child.wait().await.map_err(|e| e.to_string())?;+ if status.success() {+ Ok(())+ } else {+ let reason = tail+ .iter()+ .rev()+ .find_map(|l| l.strip_prefix("error: ").map(str::to_string))+ .or_else(|| tail.last().cloned())+ .unwrap_or_else(|| match status.code() {+ Some(c) => format!("The script exited with status {c}."),+ None => "The script was terminated.".into(),+ });+ Err(reason.trim_start_matches("Write-Error: ").to_string())+ }+ };++ match tokio::time::timeout(timeout, work).await {+ Ok(result) => result,+ Err(_) => Err(format!("Gave up after {} minutes.", timeout.as_secs() / 60)),+ }+}++fn command(spec: &MachineSpec, shell: Shell) -> Command {+ if spec.is_local() {+ match shell {+ Shell::Sh => {+ let mut c = Command::new("/bin/sh");+ c.arg("-s");+ c+ }+ Shell::Powershell => {+ let mut c = Command::new("powershell");+ c.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_READ_STDIN]);+ c+ }+ }+ } else {+ let mut c = Command::new("ssh");+ c.args(probe::ssh_args(spec));+ c.arg(match shell {+ Shell::Sh => "sh -s".to_string(),+ Shell::Powershell => {+ format!("powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{PS_READ_STDIN}\"")+ }+ });+ c+ }+}++fn log_line(engine: &Arc<Engine>, op: u64, line: &str, secrets: &[String]) {+ let clean = clean_line(line, secrets);+ if !clean.trim().is_empty() {+ engine.op_log(op, clean);+ }+}++/// Masks secrets, drops ANSI escapes and carriage-return progress redraws.+pub fn clean_line(line: &str, secrets: &[String]) -> String {+ let line = line.rsplit('\r').find(|s| !s.is_empty()).unwrap_or("");+ let mut out = strip_ansi(line);+ for s in secrets.iter().filter(|s| s.len() >= 4) {+ out = out.replace(s.as_str(), "••••••");+ }+ out.trim_end().to_string()+}++pub(crate) fn strip_ansi(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut chars = s.chars().peekable();+ while let Some(c) = chars.next() {+ if c == '\u{1b}' {+ if chars.peek() == Some(&'[') {+ chars.next();+ // CSI: parameters, then one final byte in @..~+ for c in chars.by_ref() {+ if ('@'..='~').contains(&c) {+ break;+ }+ }+ }+ continue;+ }+ out.push(c);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn quotes_params() {+ let names = vec!["a-01".to_string(), "b-02".to_string()];+ let sh = with_params(+ Shell::Sh,+ &[("OR_TOKEN", Param::Str("it's")), ("OR_NAMES", Param::List(&names)), ("OR_SERVICE", Param::Bool(true))],+ "echo hi\n",+ );+ assert_eq!(sh, "OR_TOKEN='it'\\''s'\nOR_NAMES='a-01 b-02'\nOR_SERVICE=1\necho hi\n");+ let ps = with_params(+ Shell::Powershell,+ &[("OR_TOKEN", Param::Str("it's")), ("OR_NAMES", Param::List(&names)), ("OR_SERVICE", Param::Bool(false))],+ "",+ );+ assert_eq!(ps, "$OR_TOKEN = 'it''s'\n$OR_NAMES = @('a-01', 'b-02')\n$OR_SERVICE = $false\n");+ }++ #[test]+ fn cleans_lines() {+ let secrets = vec!["AABBCCDDEEFF".to_string()];+ assert_eq!(clean_line("--token AABBCCDDEEFF --name x", &secrets), "--token •••••• --name x");+ assert_eq!(clean_line("\u{1b}[32m√ Connected\u{1b}[0m ", &[]), "√ Connected");+ assert_eq!(clean_line("10%\r50%\r100%", &[]), "100%");+ }++ #[test]+ fn picks_shells() {+ let spec: MachineSpec = toml::from_str("name = \"w\"\nhost = \"win\"").unwrap();+ let probe = ProbeResult { os: Some("windows".into()), ok: true, ..Default::default() };+ assert_eq!(shell_for(&spec, Some(&probe)), Shell::Powershell);+ assert_eq!(shell_for(&spec, None), Shell::Sh);+ }+}diff --git a/src/ops/scripts/control.ps1 b/src/ops/scripts/control.ps1new file mode 100644index 0000000..86bc502--- /dev/null+++ b/src/ops/scripts/control.ps1@@ -0,0 +1,75 @@+# OpenRunner: control one installed runner (Windows).+# OpenRunner prepends: $OR_ACTION (start|stop|restart|logs|remove), $OR_DIR,+# $OR_TOKEN (remove only), $OR_DELETE (bool).++$ErrorActionPreference = 'Stop'+$ProgressPreference = 'SilentlyContinue'+trap { Write-Error ("error: " + $_.Exception.Message); exit 1 }+function say($m) { Write-Output $m }++if (-not $OR_DIR -or -not (Test-Path $OR_DIR)) { throw "$OR_DIR doesn't exist." }+Set-Location $OR_DIR++$svcFile = Join-Path $OR_DIR '.service'+$svcName = if (Test-Path $svcFile) { (Get-Content $svcFile | Select-Object -First 1).Trim() } else { $null }++function Get-RunnerProcesses {+ Get-CimInstance Win32_Process -Filter "Name='Runner.Listener.exe' OR Name='Runner.Worker.exe'" |+ Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith("$OR_DIR\bin\", [StringComparison]::OrdinalIgnoreCase) }+}++function Start-Runner {+ if ($svcName) {+ say "Starting service $svcName…"+ Start-Service -Name $svcName+ } elseif (Get-RunnerProcesses) {+ say 'Already running.'+ } else {+ say 'Starting run.cmd in the background (no service installed)…'+ Start-Process -FilePath (Join-Path $OR_DIR 'run.cmd') -WorkingDirectory $OR_DIR -WindowStyle Hidden+ }+}++function Stop-Runner {+ if ($svcName) {+ say "Stopping service $svcName…"+ Stop-Service -Name $svcName -Force+ return+ }+ $procs = @(Get-RunnerProcesses)+ if ($procs.Count -eq 0) { say 'Not running.'; return }+ foreach ($p in $procs) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue }+ say 'Stopped.'+}++switch ($OR_ACTION) {+ 'start' { Start-Runner }+ 'stop' { Stop-Runner }+ 'restart' { Stop-Runner; Start-Sleep -Seconds 1; Start-Runner }+ 'logs' {+ $log = Get-ChildItem -Path (Join-Path $OR_DIR '_diag') -Filter 'Runner_*.log' -ErrorAction SilentlyContinue |+ Sort-Object LastWriteTime -Descending | Select-Object -First 1+ if (-not $log) { say "No runner logs yet in $OR_DIR\_diag." }+ else { say "==> $($log.FullName) (last 200 lines)"; Get-Content -Path $log.FullName -Tail 200 }+ }+ 'remove' {+ Stop-Runner+ if (Test-Path (Join-Path $OR_DIR '.runner')) {+ say 'Removing the runner from GitHub…'+ # config.cmd remove also uninstalls the Windows service.+ & .\config.cmd remove --token $OR_TOKEN+ if ($LASTEXITCODE -ne 0) { throw "config.cmd remove failed (exit $LASTEXITCODE)" }+ }+ if ($OR_DELETE) {+ if ((Test-Path (Join-Path $OR_DIR 'config.cmd')) -and (Test-Path (Join-Path $OR_DIR 'bin'))) {+ Set-Location $env:SystemDrive\+ Remove-Item -Recurse -Force $OR_DIR+ say "Deleted $OR_DIR"+ } else {+ throw "$OR_DIR doesn't look like a runner folder; not deleting it."+ }+ }+ say '✓ Removed'+ }+ default { throw "Unknown action: $OR_ACTION" }+}diff --git a/src/ops/scripts/control.sh b/src/ops/scripts/control.shnew file mode 100644index 0000000..29d1766--- /dev/null+++ b/src/ops/scripts/control.sh@@ -0,0 +1,135 @@+# OpenRunner: control one installed runner (macOS / Linux).+# OpenRunner prepends these variables:+# OR_ACTION start | stop | restart | logs | remove+# OR_DIR the runner folder (contains config.sh and .runner)+# OR_TOKEN remove token (remove only)+# OR_DELETE 1 to delete the folder after removing++set -u+say() { printf '%s\n' "$*"; }+fail() { printf 'error: %s\n' "$*" >&2; exit 1; }++[ -n "$OR_DIR" ] || fail "No runner folder given."+cd "$OR_DIR" 2>/dev/null || fail "$OR_DIR doesn't exist."++os=$(uname -s)+SUDO=""+if [ "$os" = Linux ] && [ "$(id -u)" != 0 ]; then+ SUDO="sudo -n"+fi+[ "$os" = Linux ] && [ "$(id -u)" = 0 ] && export RUNNER_ALLOW_RUNASROOT=1++has_service() { [ -f .service ]; }++svc() {+ if [ -n "$SUDO" ]; then+ $SUDO ./svc.sh "$@" || fail "svc.sh $1 failed. Linux services need root: allow passwordless sudo for $(id -un), or run on the machine: cd $OR_DIR && sudo ./svc.sh $1"+ else+ ./svc.sh "$@" || fail "svc.sh $1 failed."+ fi+}++# Snapshot the process list before filtering it: a filter running alongside ps+# would see itself (macOS awk even rewrites its argv so `-v x=path` shows as `x path`).+processes() {+ procs=$(ps -A -o pid= -o command= 2>/dev/null)+ printf '%s\n' "$procs"+}++# PIDs of this runner's Listener and the run-helper.sh loop that restarts it.+# run.sh itself exits once run-helper.sh does.+runner_pids() {+ processes | OR_D="$OR_DIR" awk '+ { for (i = 2; i <= NF; i++) if ($i == ENVIRON["OR_D"] "/bin/Runner.Listener" || $i == ENVIRON["OR_D"] "/run-helper.sh") { print $1; break } }'+}++listener_pid() {+ processes | OR_D="$OR_DIR" awk '{ for (i = 2; i <= NF; i++) if ($i == ENVIRON["OR_D"] "/bin/Runner.Listener") { print $1; exit } }'+}++start_runner() {+ if has_service; then+ say "Starting service $(head -n1 .service)…"+ svc start+ elif [ -n "$(listener_pid)" ]; then+ say "Already running."+ else+ say "Starting run.sh in the background (no service installed)…"+ nohup ./run.sh </dev/null >/dev/null 2>&1 &+ fi+}++stop_runner() {+ if has_service; then+ say "Stopping service $(head -n1 .service)…"+ svc stop+ return+ fi+ pids=$(runner_pids)+ if [ -z "$pids" ]; then+ say "Not running."+ return+ fi+ say "Stopping $(printf '%s' "$pids" | wc -w | tr -d ' ') process(es)…"+ # shellcheck disable=SC2086+ kill $pids 2>/dev/null+ i=0+ while [ -n "$(listener_pid)" ] && [ $i -lt 20 ]; do+ sleep 0.5+ i=$((i + 1))+ done+ pid=$(listener_pid)+ if [ -n "$pid" ]; then+ kill -9 "$pid" 2>/dev/null+ fi+ say "Stopped."+}++case "$OR_ACTION" in+ start)+ start_runner+ ;;+ stop)+ stop_runner+ ;;+ restart)+ stop_runner+ sleep 1+ start_runner+ ;;+ logs)+ log=$(ls -t _diag/Runner_*.log 2>/dev/null | head -n1)+ if [ -z "$log" ]; then+ say "No runner logs yet in $OR_DIR/_diag."+ else+ say "==> $OR_DIR/$log (last 200 lines)"+ tail -n 200 "$log"+ fi+ ;;+ remove)+ stop_runner+ if has_service; then+ say "Uninstalling the service…"+ svc uninstall+ fi+ if [ -f .runner ]; then+ say "Removing the runner from GitHub…"+ ./config.sh remove --token "$OR_TOKEN" || fail "config.sh remove failed."+ fi+ if [ "$OR_DELETE" = 1 ]; then+ # Only ever delete something that looks like a runner folder.+ case "$OR_DIR" in+ / | "$HOME" | "$HOME/" | "") fail "Refusing to delete $OR_DIR." ;;+ esac+ if [ -f "$OR_DIR/config.sh" ] && [ -d "$OR_DIR/bin" ]; then+ cd / && rm -rf "$OR_DIR" && say "Deleted $OR_DIR"+ else+ fail "$OR_DIR doesn't look like a runner folder; not deleting it."+ fi+ fi+ say "✓ Removed"+ ;;+ *)+ fail "Unknown action: $OR_ACTION"+ ;;+esacdiff --git a/src/ops/scripts/control_docker.sh b/src/ops/scripts/control_docker.shnew file mode 100644index 0000000..ba7c68c--- /dev/null+++ b/src/ops/scripts/control_docker.sh@@ -0,0 +1,76 @@+# OpenRunner: control one runner that lives in a Docker container.+# OpenRunner prepends these variables:+# OR_ACTION start | stop | restart | logs | remove+# OR_CONTAINER the container, e.g. openrunner-beelink-01+# OR_TOKEN remove token (remove only; empty skips deregistration)+# OR_DELETE 1 to delete the runner's volume after removing++set -u+say() { printf '%s\n' "$*"; }+fail() { printf 'error: %s\n' "$*" >&2; exit 1; }++c=$OR_CONTAINER+[ -n "$c" ] || fail "No container given."+command -v docker >/dev/null 2>&1 || fail "Docker isn't installed on this machine."+docker container inspect "$c" >/dev/null 2>&1 || fail "There's no container called $c on this machine."++state() { docker inspect -f '{{.State.Status}}' "$c" 2>/dev/null; }++case "$OR_ACTION" in+ start)+ if [ "$(state)" = running ]; then+ say "Already running."+ else+ say "Starting $c…"+ docker start "$c" >/dev/null || fail "docker start $c failed."+ say "Started."+ fi+ ;;+ stop)+ if [ "$(state)" = running ]; then+ say "Stopping $c (jobs get 30 seconds to finish)…"+ docker stop -t 30 "$c" >/dev/null || fail "docker stop $c failed."+ say "Stopped."+ else+ say "Not running."+ fi+ ;;+ restart)+ say "Restarting $c…"+ docker restart -t 30 "$c" >/dev/null || fail "docker restart $c failed."+ say "Restarted."+ ;;+ logs)+ say "==> docker logs $c (last 200 lines)"+ docker logs --tail 200 "$c" 2>&1+ ;;+ remove)+ image=$(docker inspect -f '{{.Config.Image}}' "$c")+ vol=$(docker inspect -f '{{index .Config.Labels "openrunner.volume"}}' "$c" 2>/dev/null)+ if [ -z "$vol" ]; then+ vol=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/home/runner"}}{{.Name}}{{end}}{{end}}' "$c" 2>/dev/null)+ fi+ if [ "$(state)" = running ]; then+ say "Stopping $c…"+ docker stop -t 30 "$c" >/dev/null 2>&1+ fi+ if [ -n "$vol" ] && docker run --rm -v "$vol:/home/runner" --entrypoint test "$image" -f /home/runner/.runner 2>/dev/null; then+ if [ -n "$OR_TOKEN" ]; then+ say "Removing the runner from GitHub…"+ printf '%s' "$OR_TOKEN" | docker run --rm -i -e ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=0 -v "$vol:/home/runner" --entrypoint bash "$image" \+ -c 'export ACTIONS_RUNNER_INPUT_TOKEN="$(cat)"; exec ./config.sh remove' || fail "config.sh remove failed; the container was left stopped."+ else+ say "warning: no removal token, so the runner stays registered on GitHub."+ fi+ fi+ docker rm -f "$c" >/dev/null || fail "docker rm $c failed."+ say "Removed container $c"+ if [ "$OR_DELETE" = 1 ] && [ -n "$vol" ]; then+ docker volume rm "$vol" >/dev/null && say "Deleted volume $vol"+ fi+ say "✓ Removed"+ ;;+ *)+ fail "Unknown action: $OR_ACTION"+ ;;+esacdiff --git a/src/ops/scripts/install.ps1 b/src/ops/scripts/install.ps1new file mode 100644index 0000000..af2b54c--- /dev/null+++ b/src/ops/scripts/install.ps1@@ -0,0 +1,61 @@+# OpenRunner: install GitHub Actions runners (Windows).+# OpenRunner prepends: $OR_VERSION, $OR_URL, $OR_TOKEN, $OR_NAMES (array),+# $OR_LABELS, $OR_GROUP, $OR_SERVICE (bool), $OR_BASE (empty: C:\actions-runner).++$ErrorActionPreference = 'Stop'+$ProgressPreference = 'SilentlyContinue'+trap { Write-Error ("error: " + $_.Exception.Message); exit 1 }+function say($m) { Write-Output $m }++$arch = switch ($env:PROCESSOR_ARCHITECTURE) {+ 'AMD64' { 'x64' }+ 'ARM64' { 'arm64' }+ default { throw "Unsupported CPU architecture: $env:PROCESSOR_ARCHITECTURE" }+}+$base = if ($OR_BASE) { $OR_BASE } else { "$env:SystemDrive\actions-runner" }+$pkg = "actions-runner-win-$arch-$OR_VERSION.zip"+$url = "https://github.com/actions/runner/releases/download/v$OR_VERSION/$pkg"+$cache = Join-Path $base '.cache'++if ($OR_SERVICE) {+ $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {+ throw "Installing a Windows service needs an administrator account. Connect as an admin, or turn off ""Install as a service""."+ }+}+foreach ($name in $OR_NAMES) {+ if (Test-Path (Join-Path (Join-Path $base $name) '.runner')) {+ throw "$base\$name already has a configured runner. Remove it first or pick another name."+ }+}++New-Item -ItemType Directory -Force -Path $cache | Out-Null+$zip = Join-Path $cache $pkg+if (Test-Path $zip) {+ say "Using cached $pkg"+} else {+ say "Downloading actions-runner $OR_VERSION for win-$arch…"+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12+ Invoke-WebRequest -Uri $url -OutFile "$zip.part" -UseBasicParsing+ Move-Item "$zip.part" $zip -Force+}++foreach ($name in $OR_NAMES) {+ $dir = Join-Path $base $name+ say "Setting up $name in $dir"+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ Expand-Archive -Path $zip -DestinationPath $dir -Force+ Push-Location $dir+ $cfg = @('--unattended', '--url', $OR_URL, '--token', $OR_TOKEN, '--name', $name, '--work', '_work', '--replace')+ if ($OR_LABELS) { $cfg += @('--labels', $OR_LABELS) }+ if ($OR_GROUP) { $cfg += @('--runnergroup', $OR_GROUP) }+ if ($OR_SERVICE) { $cfg += '--runasservice' }+ & .\config.cmd @cfg+ if ($LASTEXITCODE -ne 0) { throw "config.cmd failed for $name (exit $LASTEXITCODE)" }+ if (-not $OR_SERVICE) {+ Start-Process -FilePath (Join-Path $dir 'run.cmd') -WorkingDirectory $dir -WindowStyle Hidden+ say "Started $name in the background (not a service, so it won't come back after a reboot)"+ }+ Pop-Location+ say "✓ $name is installed"+}diff --git a/src/ops/scripts/install.sh b/src/ops/scripts/install.shnew file mode 100644index 0000000..cedaa83--- /dev/null+++ b/src/ops/scripts/install.sh@@ -0,0 +1,99 @@+# OpenRunner: install GitHub Actions runners (macOS / Linux).+# OpenRunner prepends these variables:+# OR_VERSION runner release, e.g. 2.329.0+# OR_URL https://github.com/<org> or https://github.com/<owner>/<repo>+# OR_TOKEN registration token (short-lived)+# OR_NAMES runner names, space separated+# OR_LABELS extra labels, comma separated (may be empty)+# OR_GROUP runner group (may be empty)+# OR_SERVICE 1 to install as a service, 0 to start with run.sh+# OR_BASE install root (empty: $HOME/actions-runner)++set -u+say() { printf '%s\n' "$*"; }+fail() { printf 'error: %s\n' "$*" >&2; exit 1; }++os=$(uname -s)+arch=$(uname -m)+case "$os" in+ Darwin) ros=osx ;;+ Linux) ros=linux ;;+ *) fail "Unsupported operating system: $os" ;;+esac+case "$arch" in+ x86_64 | amd64) rarch=x64 ;;+ arm64 | aarch64) rarch=arm64 ;;+ armv7l | armv6l | arm) rarch=arm ;;+ *) fail "Unsupported CPU architecture: $arch" ;;+esac++base="${OR_BASE:-$HOME/actions-runner}"+pkg="actions-runner-$ros-$rarch-$OR_VERSION.tar.gz"+url="https://github.com/actions/runner/releases/download/v$OR_VERSION/$pkg"+cache="$base/.cache"++SUDO=""+if [ "$ros" = linux ] && [ "$(id -u)" != 0 ]; then+ SUDO="sudo -n"+fi+if [ "$ros" = linux ] && [ "$(id -u)" = 0 ]; then+ # config.sh refuses to run as root unless told it's intended.+ export RUNNER_ALLOW_RUNASROOT=1+ say "Running as root; the runners will run as root too."+fi++# Fail before touching anything if the service can't be installed.+if [ "$OR_SERVICE" = 1 ] && [ -n "$SUDO" ]; then+ if ! sudo -n true 2>/dev/null; then+ fail "Installing a Linux service needs root, and sudo asks for a password over ssh. Allow passwordless sudo for $(id -un), or turn off \"Install as a service\" and later run: sudo ./svc.sh install $(id -un) && sudo ./svc.sh start"+ fi+fi++for name in $OR_NAMES; do+ if [ -f "$base/$name/.runner" ]; then+ fail "$base/$name already has a configured runner. Remove it first or pick another name."+ fi+done++mkdir -p "$cache" || fail "Couldn't create $cache"+if [ -s "$cache/$pkg" ]; then+ say "Using cached $pkg"+else+ say "Downloading actions-runner $OR_VERSION for $ros-$rarch…"+ if command -v curl >/dev/null 2>&1; then+ curl -fsSL --retry 3 -o "$cache/$pkg.part" "$url" || fail "Download failed: $url"+ elif command -v wget >/dev/null 2>&1; then+ wget -q -O "$cache/$pkg.part" "$url" || fail "Download failed: $url"+ else+ fail "Neither curl nor wget is installed."+ fi+ mv "$cache/$pkg.part" "$cache/$pkg" || fail "Couldn't save $pkg"+fi++for name in $OR_NAMES; do+ dir="$base/$name"+ say "Setting up $name in $dir"+ mkdir -p "$dir" || fail "Couldn't create $dir"+ tar xzf "$cache/$pkg" -C "$dir" || fail "Couldn't unpack $pkg into $dir"+ cd "$dir" || fail "Couldn't enter $dir"++ set -- --unattended --url "$OR_URL" --token "$OR_TOKEN" --name "$name" --work _work --replace+ [ -n "$OR_LABELS" ] && set -- "$@" --labels "$OR_LABELS"+ [ -n "$OR_GROUP" ] && set -- "$@" --runnergroup "$OR_GROUP"+ ./config.sh "$@" || fail "config.sh failed for $name. On Linux, missing libraries can be installed with: sudo $dir/bin/installdependencies.sh"++ if [ "$OR_SERVICE" = 1 ]; then+ say "Installing $name as a service…"+ if [ "$ros" = linux ]; then+ $SUDO ./svc.sh install "$(id -un)" || fail "svc.sh install failed for $name"+ $SUDO ./svc.sh start || fail "svc.sh start failed for $name"+ else+ ./svc.sh install || fail "svc.sh install failed for $name"+ ./svc.sh start || fail "svc.sh start failed for $name. macOS runs runner services in the user's login session: make sure $(id -un) is logged in (automatic login helps on headless Macs)."+ fi+ else+ say "Starting $name in the background (not a service, so it won't come back after a reboot)…"+ nohup ./run.sh </dev/null >/dev/null 2>&1 &+ fi+ say "✓ $name is installed"+donediff --git a/src/ops/scripts/install_docker.sh b/src/ops/scripts/install_docker.shnew file mode 100644index 0000000..a48f3d6--- /dev/null+++ b/src/ops/scripts/install_docker.sh@@ -0,0 +1,124 @@+# OpenRunner: install GitHub Actions runners as Docker containers (Linux, or any+# machine with a Docker daemon that runs Linux containers).+# OpenRunner prepends these variables:+# OR_IMAGE runner image, e.g. ghcr.io/actions/actions-runner:2.329.0+# OR_IMAGE_FALLBACK image to try when OR_IMAGE can't be pulled (may be empty)+# OR_URL https://github.com/<org> or https://github.com/<owner>/<repo>+# OR_SCOPE the org or owner/repo (stored as a container label)+# OR_TOKEN registration token (short-lived)+# OR_NAMES runner names, space separated+# OR_LABELS labels, comma separated (may be empty)+# OR_GROUP runner group (may be empty)+# OR_SOCKET 1 to give the runner the host's Docker socket+# OR_STUB tests only: 1 skips GitHub registration and runs a stand-in listener+#+# Each runner gets a named volume mounted at /home/runner (Docker fills it from+# the image the first time), a one-off container that registers it, and then a+# long-running container `openrunner-<name>` that runs run.sh and restarts with+# the Docker daemon. The token reaches config.sh only through stdin and the+# environment of a throwaway container: never argv, never `docker inspect`.++set -u+say() { printf '%s\n' "$*"; }+fail() { printf 'error: %s\n' "$*" >&2; exit 1; }++command -v docker >/dev/null 2>&1 || fail "Docker isn't installed on this machine."+if ! docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then+ why=$(docker version 2>&1 | grep -i -m1 -E 'permission denied|cannot connect|error')+ fail "Docker is installed but $(id -un) can't use it (${why:-no daemon}). Add $(id -un) to the docker group: sudo usermod -aG docker $(id -un), then log in again."+fi++for name in $OR_NAMES; do+ if docker container inspect "openrunner-$name" >/dev/null 2>&1; then+ fail "A container called openrunner-$name already exists. Remove it first or pick another name."+ fi+done++# Shows the useful lines of `docker pull` and reports whether the image is now here.+pull() {+ docker pull "$1" 2>&1 | while IFS= read -r line; do+ case "$line" in+ *"Pulling from"* | Digest:* | Status:* | *"Pull complete"* | *"Error"* | *"error"* | *"denied"* | *"not found"*) say "$line" ;;+ esac+ done+ docker image inspect "$1" >/dev/null 2>&1+}++image=$OR_IMAGE+if docker image inspect "$image" >/dev/null 2>&1; then+ say "Using $image (already on this machine)"+else+ say "Pulling $image (about 2 GB the first time)…"+ if ! pull "$image"; then+ if [ -n "$OR_IMAGE_FALLBACK" ] && [ "$OR_IMAGE_FALLBACK" != "$image" ]; then+ say "warning: couldn't pull $image; trying $OR_IMAGE_FALLBACK"+ image=$OR_IMAGE_FALLBACK+ pull "$image" || fail "Couldn't pull $image."+ else+ fail "Couldn't pull $image."+ fi+ fi+fi++socket_args=""+if [ "$OR_SOCKET" = 1 ]; then+ sock=/var/run/docker.sock+ [ -S "$sock" ] || fail "There's no Docker socket at $sock to share with the runners."+ gid=$(stat -c %g "$sock" 2>/dev/null || stat -f %g "$sock" 2>/dev/null)+ socket_args="-v $sock:$sock --group-add ${gid:-0}"+ say "warning: the runners get this machine's Docker socket, which is root-equivalent access to the machine. Only run trusted workflows on them."+fi++for name in $OR_NAMES; do+ c="openrunner-$name"+ vol="openrunner-$name"+ say "Setting up $name (container $c, volume $vol)"+ docker volume create --label "openrunner.runner=$name" "$vol" >/dev/null || fail "Couldn't create the volume $vol."++ if [ "$OR_STUB" = 1 ]; then+ # Tests only: write a .runner like config.sh would, without talking to GitHub.+ docker run --rm -v "$vol:/home/runner" --entrypoint bash "$image" -c \+ 'printf "{\"agentName\":\"%s\",\"gitHubUrl\":\"%s\"}" "$1" "$2" > /home/runner/.runner' openrunner "$name" "$OR_URL" \+ || fail "Couldn't prepare $vol."+ say "√ Runner successfully added ($name, stubbed)"+ else+ set -- --unattended --url "$OR_URL" --name "$name" --work _work --replace+ [ -n "$OR_LABELS" ] && set -- "$@" --labels "$OR_LABELS"+ [ -n "$OR_GROUP" ] && set -- "$@" --runnergroup "$OR_GROUP"+ # The token travels on stdin into the throwaway container's environment.+ if ! printf '%s' "$OR_TOKEN" | docker run --rm -i -e ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=0 -v "$vol:/home/runner" --entrypoint bash "$image" \+ -c 'export ACTIONS_RUNNER_INPUT_TOKEN="$(cat)"; exec ./config.sh "$@"' openrunner "$@"; then+ docker volume rm "$vol" >/dev/null 2>&1+ fail "config.sh failed for $name; nothing was left behind."+ fi+ fi++ set -- -d --name "$c" --hostname "$name" --restart unless-stopped \+ --label "openrunner.runner=$name" --label "openrunner.scope=$OR_SCOPE" --label "openrunner.volume=$vol" \+ -v "$vol:/home/runner"+ if [ "$OR_STUB" = 1 ]; then+ # Tests only: a process named like the runner's listener, so checks see it.+ set -- "$@" --entrypoint bash+ # shellcheck disable=SC2086+ docker run "$@" $socket_args "$image" -c 'trap "exit 0" TERM INT; (exec -a /home/runner/bin/Runner.Listener sleep infinity) & wait' >/dev/null \+ || fail "Couldn't start the $c container."+ else+ set -- "$@" --entrypoint /home/runner/run.sh+ # shellcheck disable=SC2086+ docker run "$@" $socket_args "$image" >/dev/null || fail "Couldn't start the $c container."+ fi++ # It should stay up: a container that exits right away (bad credentials, missing+ # libraries) would otherwise restart forever.+ sleep 8+ state=$(docker inspect -f '{{.State.Status}} {{.RestartCount}}' "$c" 2>/dev/null)+ case "$state" in+ "running 0") ;;+ *)+ say "The $c container isn't staying up ($state). Its last output:"+ docker logs --tail 20 "$c" 2>&1+ fail "$name didn't start. Remove it with: docker rm -f $c && docker volume rm $vol"+ ;;+ esac+ say "✓ $name is installed"+donediff --git a/src/probe/mod.rs b/src/probe/mod.rsnew file mode 100644index 0000000..9932196--- /dev/null+++ b/src/probe/mod.rs@@ -0,0 +1,527 @@+//! Machine checks. A small read-only script runs on each machine (directly for+//! `host = "local"`, otherwise over the system `ssh`, so ~/.ssh/config, keys and+//! agents all just work) and reports resource usage plus installed runners.++use std::process::Stdio;+use std::time::{Duration, Instant};++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use tokio::io::AsyncWriteExt;+use tokio::process::Command;++use crate::config::MachineSpec;++const PROBE_SH: &str = include_str!("scripts/probe.sh");+const PROBE_PS1: &str = include_str!("scripts/probe.ps1");+const TIMEOUT: Duration = Duration::from_secs(45);+/// `-Command -` runs stdin line by line and breaks multi-line blocks; read it whole instead.+const PS_READ_STDIN: &str = "[Console]::In.ReadToEnd() | Invoke-Expression";++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Shell {+ Sh,+ Powershell,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct ProbeResult {+ pub checked_at: DateTime<Utc>,+ pub duration_ms: u64,+ pub ok: bool,+ pub error: Option<String>,+ pub shell: Option<Shell>,+ pub hostname: Option<String>,+ pub os: Option<String>,+ pub arch: Option<String>,+ pub os_version: Option<String>,+ pub cores: Option<u32>,+ pub cpu_pct: Option<f64>,+ pub mem_total: Option<u64>,+ pub mem_used: Option<u64>,+ pub disk_total: Option<u64>,+ pub disk_free: Option<u64>,+ pub disk_path: Option<String>,+ pub uptime_sec: Option<u64>,+ pub load: Vec<f64>,+ pub runners: Vec<ProbedRunner>,+ /// Docker server version when the machine's user can talk to the daemon.+ pub docker: Option<String>,+ /// Why Docker is installed but unusable (e.g. "permission denied").+ pub docker_error: Option<String>,+ /// Linux only: "root" | "passwordless" | "password" — whether services can be installed.+ pub sudo: Option<String>,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct ProbedRunner {+ pub dir: String,+ /// agentName from .runner; falls back to the folder name.+ pub name: String,+ /// gitHubUrl from .runner, e.g. https://github.com/acme or https://github.com/acme/api+ pub url: Option<String>,+ pub version: Option<String>,+ pub service: Option<String>,+ pub service_state: Option<String>,+ pub listener_pid: Option<u32>,+ pub worker_pid: Option<u32>,+ /// Set when the runner lives in a Docker container (`dir` is then `docker://<container>`).+ pub container: Option<String>,+ pub image: Option<String>,+ /// Docker's state: "running" | "exited" | "restarting" | "created" | "paused" | "dead"+ pub container_state: Option<String>,+ /// How many times Docker restarted it (a climbing count means it's crash-looping).+ pub restarts: Option<u32>,+}++/// The `dir` of a runner that lives in a container.+pub fn container_dir(container: &str) -> String {+ format!("docker://{container}")+}++impl ProbeResult {+ pub fn failed(started: Instant, error: impl Into<String>) -> ProbeResult {+ ProbeResult {+ checked_at: Utc::now(),+ duration_ms: started.elapsed().as_millis() as u64,+ ok: false,+ error: Some(error.into()),+ ..Default::default()+ }+ }+}++/// Checks one machine. Never fails: problems are reported in `ProbeResult::error`.+pub async fn probe(spec: &MachineSpec, remembered: Option<Shell>) -> ProbeResult {+ let started = Instant::now();+ if !spec.is_checkable() {+ return ProbeResult::failed(started, "No host configured");+ }+ let shell = spec.shell.or(remembered).unwrap_or(if spec.is_local() && cfg!(windows) {+ Shell::Powershell+ } else {+ Shell::Sh+ });++ let first = run(spec, shell).await;+ let result = match first {+ // A Windows host without a POSIX shell: try PowerShell once, unless the user pinned the shell.+ Err(RunError::Output { ref stderr, .. })+ if shell == Shell::Sh && spec.shell.is_none() && !spec.is_local() && looks_like_no_sh(stderr) =>+ {+ run(spec, Shell::Powershell).await.map(|out| (out, Shell::Powershell))+ }+ other => other.map(|out| (out, shell)),+ };++ match result {+ Ok((stdout, shell)) => {+ let mut r = parse(&stdout);+ r.shell = Some(shell);+ r.checked_at = Utc::now();+ r.duration_ms = started.elapsed().as_millis() as u64;+ if !r.ok {+ r.error = Some("The machine answered, but the check printed nothing usable.".into());+ }+ r+ }+ Err(e) => ProbeResult::failed(started, e.to_string()),+ }+}++#[derive(Debug)]+enum RunError {+ Spawn(String),+ Timeout,+ Output { code: Option<i32>, stderr: String },+}++impl std::fmt::Display for RunError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ RunError::Spawn(e) => write!(f, "{e}"),+ RunError::Timeout => write!(f, "Timed out after {}s", TIMEOUT.as_secs()),+ RunError::Output { code, stderr } => {+ let msg = last_lines(stderr, 3);+ match (msg.is_empty(), code) {+ (false, _) => write!(f, "{msg}"),+ (true, Some(c)) => write!(f, "Exited with status {c}"),+ (true, None) => write!(f, "Terminated by a signal"),+ }+ }+ }+ }+}++async fn run(spec: &MachineSpec, shell: Shell) -> Result<String, RunError> {+ let script = script_for(spec, shell);+ let mut cmd = if spec.is_local() {+ match shell {+ Shell::Sh => {+ let mut c = Command::new("/bin/sh");+ c.arg("-s");+ c+ }+ Shell::Powershell => {+ let mut c = Command::new("powershell");+ c.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_READ_STDIN]);+ c+ }+ }+ } else {+ let mut c = Command::new("ssh");+ c.args(ssh_args(spec));+ c.arg(match shell {+ Shell::Sh => "sh -s".to_string(),+ Shell::Powershell => {+ format!("powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{PS_READ_STDIN}\"")+ }+ });+ c+ };+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);++ let mut child = cmd.spawn().map_err(|e| {+ RunError::Spawn(if spec.is_local() { format!("Couldn't start the check: {e}") } else { format!("Couldn't run ssh: {e}") })+ })?;+ let mut stdin = child.stdin.take().expect("piped stdin");+ let output = async move {+ // The script is small; ignore write errors (e.g. ssh exiting early) and read why from stderr.+ let _ = stdin.write_all(script.as_bytes()).await;+ drop(stdin);+ child.wait_with_output().await+ };+ let output = tokio::time::timeout(TIMEOUT, output)+ .await+ .map_err(|_| RunError::Timeout)?+ .map_err(|e| RunError::Spawn(e.to_string()))?;++ let stdout = String::from_utf8_lossy(&output.stdout).into_owned();+ // Scripts end with key=value output even if one command inside failed; only treat it as a+ // failure when nothing came back.+ if !output.status.success() && !stdout.lines().any(|l| l.starts_with("probe=")) {+ return Err(RunError::Output {+ code: output.status.code(),+ stderr: String::from_utf8_lossy(&output.stderr).into_owned(),+ });+ }+ Ok(stdout)+}++pub fn ssh_args(spec: &MachineSpec) -> Vec<String> {+ let mut args: Vec<String> = [+ "-T",+ "-o", "BatchMode=yes",+ "-o", "ConnectTimeout=8",+ "-o", "ServerAliveInterval=5",+ "-o", "ServerAliveCountMax=3",+ "-o", "StrictHostKeyChecking=accept-new",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();+ if let Some(port) = spec.port {+ args.extend(["-p".into(), port.to_string()]);+ }+ if let Some(user) = spec.user.as_deref().filter(|u| !u.is_empty()) {+ args.extend(["-l".into(), user.to_string()]);+ }+ args.extend(spec.ssh_options.iter().cloned());+ args.push(spec.host.trim().to_string());+ args+}++fn script_for(spec: &MachineSpec, shell: Shell) -> String {+ match shell {+ Shell::Sh => {+ let dirs = spec.runner_dirs.join("\n").replace('\'', r"'\''");+ format!("OR_DIRS='{dirs}'\n{PROBE_SH}")+ }+ Shell::Powershell => {+ let dirs: Vec<String> = spec.runner_dirs.iter().map(|d| format!("'{}'", d.replace('\'', "''"))).collect();+ format!("$OR_DIRS = @({})\n{PROBE_PS1}", dirs.join(", "))+ }+ }+}++fn looks_like_no_sh(stderr: &str) -> bool {+ let s = stderr.to_ascii_lowercase();+ s.contains("is not recognized") || s.contains("'sh' is not") || s.contains("the term 'sh'")+}++fn last_lines(s: &str, n: usize) -> String {+ let lines: Vec<&str> = s.lines().map(str::trim).filter(|l| !l.is_empty()).collect();+ lines[lines.len().saturating_sub(n)..].join(" ")+}++/// Parses the probe's key=value output. Unknown keys and noise (e.g. a chatty+/// shell profile) are ignored.+pub fn parse(out: &str) -> ProbeResult {+ let mut r = ProbeResult::default();+ let mut runners: Vec<(usize, ProbedRunner)> = Vec::new();+ let mut containers: Vec<(usize, ContainerLines)> = Vec::new();++ for line in out.lines() {+ let Some((key, value)) = line.split_once('=') else { continue };+ let value = value.trim();+ let text = || (!value.is_empty()).then(|| value.to_string());+ match key.trim() {+ "probe" => r.ok = true,+ "os" => r.os = text(),+ "arch" => r.arch = text(),+ "hostname" => r.hostname = text(),+ "os_version" => r.os_version = text().filter(|v| v != "macOS"),+ "cores" => r.cores = value.parse().ok(),+ "cpu_pct" => r.cpu_pct = value.parse::<f64>().ok().map(|v| v.clamp(0.0, 100.0)),+ "mem_total" => r.mem_total = value.parse().ok().filter(|v| *v > 0),+ "mem_used" => r.mem_used = value.parse().ok(),+ "disk_total" => r.disk_total = value.parse().ok().filter(|v| *v > 0),+ "disk_free" => r.disk_free = value.parse().ok(),+ "disk_path" => r.disk_path = text(),+ "uptime_s" => r.uptime_sec = value.parse().ok(),+ "load" => r.load = value.split_whitespace().filter_map(|v| v.parse().ok()).take(3).collect(),+ "docker" => r.docker = text(),+ "docker_error" => r.docker_error = text(),+ "sudo" => r.sudo = text(),+ k if k.starts_with('c') && k.contains('.') => {+ let (idx, field) = k[1..].split_once('.').unwrap();+ let Ok(idx) = idx.parse::<usize>() else { continue };+ let pos = match containers.iter().position(|(i, _)| *i == idx) {+ Some(p) => p,+ None => {+ containers.push((idx, ContainerLines::default()));+ containers.len() - 1+ }+ };+ containers[pos].1.set(field, value);+ }+ k if k.starts_with('r') && k.contains('.') => {+ let (idx, field) = k[1..].split_once('.').unwrap();+ let Ok(idx) = idx.parse::<usize>() else { continue };+ let pos = match runners.iter().position(|(i, _)| *i == idx) {+ Some(p) => p,+ None => {+ runners.push((idx, ProbedRunner::default()));+ runners.len() - 1+ }+ };+ let runner = &mut runners[pos].1;+ match field {+ "dir" => runner.dir = value.to_string(),+ "config" => {+ if let Some((name, url)) = parse_runner_config(value) {+ runner.name = name;+ runner.url = url;+ }+ }+ "listener" => runner.listener_pid = value.parse().ok(),+ "worker" => runner.worker_pid = value.parse().ok(),+ "version" => runner.version = text().map(|v| v.trim_start_matches('v').to_string()),+ "service" => runner.service = text(),+ "service_state" => runner.service_state = text(),+ _ => {}+ }+ }+ _ => {}+ }+ }++ if let (Some(total), Some(used)) = (r.mem_total, r.mem_used) {+ r.mem_used = Some(used.min(total));+ }+ r.runners = runners+ .into_iter()+ .map(|(_, mut runner)| {+ if runner.name.is_empty() {+ runner.name = runner.dir.rsplit(['/', '\\']).next().unwrap_or_default().to_string();+ }+ runner+ })+ .filter(|runner| !runner.dir.is_empty())+ .collect();+ r.runners.extend(containers.into_iter().filter_map(|(_, c)| c.into_runner()));+ r+}++/// One `c<N>.<field>=` group from the probe: a runner container.+#[derive(Default)]+struct ContainerLines {+ container: String,+ state: String,+ image: String,+ label_name: String,+ label_scope: String,+ restarts: Option<u32>,+ listener: Option<u32>,+ worker: Option<u32>,+ config: Option<(String, Option<String>)>,+ version: Option<String>,+}++impl ContainerLines {+ fn set(&mut self, field: &str, value: &str) {+ match field {+ "container" => self.container = value.to_string(),+ "state" => self.state = value.to_string(),+ "image" => self.image = value.to_string(),+ "name" => self.label_name = value.to_string(),+ "scope" => self.label_scope = value.to_string(),+ "restarts" => self.restarts = value.parse().ok(),+ "listener" => self.listener = value.parse().ok(),+ "worker" => self.worker = value.parse().ok(),+ "config" => self.config = parse_runner_config(value),+ "version" => self.version = (!value.is_empty()).then(|| value.trim_start_matches('v').to_string()),+ _ => {}+ }+ }++ fn into_runner(self) -> Option<ProbedRunner> {+ if self.container.is_empty() {+ return None;+ }+ // The runner's own config wins; then OpenRunner's label; then the container name.+ let (config_name, config_url) = self.config.unwrap_or_default();+ let name = [config_name, self.label_name, self.container.clone()].into_iter().find(|n| !n.is_empty())?;+ let url = config_url.or_else(|| (!self.label_scope.is_empty()).then(|| format!("https://github.com/{}", self.label_scope)));+ // An image tagged with the runner version tells us the version of a stopped container.+ let tag_version = self.image.rsplit_once(':').map(|(_, t)| t).filter(|t| t.split('.').count() == 3 && t.chars().all(|c| c.is_ascii_digit() || c == '.'));+ let running = self.state == "running";+ Some(ProbedRunner {+ dir: container_dir(&self.container),+ name,+ url,+ version: self.version.or_else(|| tag_version.map(str::to_string)),+ service: None,+ service_state: None,+ listener_pid: if running { self.listener } else { None },+ worker_pid: if running { self.worker } else { None },+ container: Some(self.container),+ image: (!self.image.is_empty()).then_some(self.image),+ container_state: (!self.state.is_empty()).then_some(self.state),+ restarts: self.restarts,+ })+ }+}++/// Reads agentName and gitHubUrl from a runner's `.runner` JSON (which may start with a BOM).+fn parse_runner_config(raw: &str) -> Option<(String, Option<String>)> {+ let v: serde_json::Value = serde_json::from_str(raw.trim_start_matches('\u{feff}')).ok()?;+ let name = v.get("agentName")?.as_str()?.to_string();+ let url = v.get("gitHubUrl").and_then(|u| u.as_str()).map(str::to_string);+ Some((name, url))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_probe_output() {+ let out = "\+Welcome to my shell profile!+probe=1+os=darwin+arch=arm64+hostname=studio+os_version=macOS 15.6+cores=24+load=1.20 1.05 0.98+uptime_s=10022400+mem_total=137438953472+mem_used=40000000000+cpu_pct=43.0+disk_total=994662584320+disk_free=106000000000+disk_path=/System/Volumes/Data+r0.dir=/Users/ci/actions-runner-01+r0.config=\u{feff}{ \"agentId\": 12, \"agentName\": \"mac-studio-01\", \"gitHubUrl\": \"https://github.com/acme\", \"workFolder\": \"_work\"}+r0.listener=4242+r0.worker=+r0.version=2.328.0+r0.service=actions.runner.acme.mac-studio-01+r0.service_state=active+r1.dir=/Users/ci/runners/broken+r1.config=not json+r1.listener=+";+ let r = parse(out);+ assert!(r.ok);+ assert_eq!(r.os.as_deref(), Some("darwin"));+ assert_eq!(r.cores, Some(24));+ assert_eq!(r.load, vec![1.2, 1.05, 0.98]);+ assert_eq!(r.cpu_pct, Some(43.0));+ assert_eq!(r.disk_free, Some(106_000_000_000));+ assert_eq!(r.runners.len(), 2);+ assert_eq!(r.runners[0].name, "mac-studio-01");+ assert_eq!(r.runners[0].url.as_deref(), Some("https://github.com/acme"));+ assert_eq!(r.runners[0].listener_pid, Some(4242));+ assert_eq!(r.runners[0].worker_pid, None);+ assert_eq!(r.runners[0].service_state.as_deref(), Some("active"));+ assert_eq!(r.runners[1].name, "broken");+ }++ #[test]+ fn parses_docker_and_runner_containers() {+ let out = "\+probe=1+os=linux+sudo=password+docker=29.8.1+c0.container=openrunner-beelink-01+c0.state=running+c0.image=ghcr.io/actions/actions-runner:2.338.0+c0.name=beelink-01+c0.scope=acme+c0.restarts=0+c0.listener=4242+c0.worker=4300+c0.config={\"agentName\":\"beelink-01\",\"gitHubUrl\":\"https://github.com/acme\"}+c0.version=2.339.1+c1.container=old-runner+c1.state=exited+c1.image=ghcr.io/actions/actions-runner:2.329.0+c1.name=+c1.scope=+c1.restarts=7+";+ let r = parse(out);+ assert_eq!(r.docker.as_deref(), Some("29.8.1"));+ assert_eq!(r.sudo.as_deref(), Some("password"));+ assert_eq!(r.runners.len(), 2);+ let a = &r.runners[0];+ assert_eq!(a.name, "beelink-01");+ assert_eq!(a.dir, "docker://openrunner-beelink-01");+ assert_eq!(a.container.as_deref(), Some("openrunner-beelink-01"));+ assert_eq!((a.listener_pid, a.worker_pid), (Some(4242), Some(4300)));+ assert_eq!(a.version.as_deref(), Some("2.339.1"), "the running binary wins over the image tag");+ assert_eq!(a.url.as_deref(), Some("https://github.com/acme"));+ // A stopped container from someone else: named after the container, version from the tag.+ let b = &r.runners[1];+ assert_eq!(b.name, "old-runner");+ assert_eq!(b.container_state.as_deref(), Some("exited"));+ assert_eq!(b.listener_pid, None);+ assert_eq!(b.version.as_deref(), Some("2.329.0"));+ assert_eq!(b.restarts, Some(7));+ assert_eq!(b.url, None);+ }++ #[test]+ fn empty_output_is_not_ok() {+ assert!(!parse("").ok);+ }++ #[test]+ fn builds_ssh_args() {+ let spec: MachineSpec = toml::from_str(+ "name = \"x\"\nhost = \"ci@studio\"\nport = 2222\nssh_options = [\"-i\", \"~/.ssh/ci\"]",+ )+ .unwrap();+ let args = ssh_args(&spec);+ assert_eq!(args.last().unwrap(), "ci@studio");+ assert!(args.windows(2).any(|w| w == ["-p", "2222"]));+ assert!(args.windows(2).any(|w| w == ["-i", "~/.ssh/ci"]));+ }+}diff --git a/src/probe/scripts/probe.ps1 b/src/probe/scripts/probe.ps1new file mode 100644index 0000000..05e2e0b--- /dev/null+++ b/src/probe/scripts/probe.ps1@@ -0,0 +1,69 @@+# OpenRunner machine probe (Windows). Read-only.+# Prints key=value lines; runner N is reported as rN.<key>=<value>.+# $OR_DIRS (array of glob patterns) is prepended by OpenRunner.++$ErrorActionPreference = 'SilentlyContinue'+$ProgressPreference = 'SilentlyContinue'+function kv($k, $v) { Write-Output ("{0}={1}" -f $k, $v) }++$os = Get-CimInstance Win32_OperatingSystem+kv 'probe' 1+kv 'os' 'windows'+kv 'arch' $env:PROCESSOR_ARCHITECTURE+kv 'hostname' $env:COMPUTERNAME+kv 'os_version' $os.Caption+kv 'cores' ([Environment]::ProcessorCount)+$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average+if ($cpu -ne $null) { kv 'cpu_pct' ([math]::Round($cpu, 1)) }+if ($os) {+ kv 'mem_total' ([int64]$os.TotalVisibleMemorySize * 1024)+ kv 'mem_used' (([int64]$os.TotalVisibleMemorySize - [int64]$os.FreePhysicalMemory) * 1024)+ kv 'uptime_s' ([int64]((Get-Date) - $os.LastBootUpTime).TotalSeconds)+}+$drive = Get-CimInstance Win32_LogicalDisk -Filter ("DeviceID='{0}'" -f $env:SystemDrive)+if ($drive) {+ kv 'disk_total' ([int64]$drive.Size)+ kv 'disk_free' ([int64]$drive.FreeSpace)+ kv 'disk_path' $env:SystemDrive+}++# --- Runners -----------------------------------------------------------------+$procs = @(Get-CimInstance Win32_Process -Filter "Name='Runner.Listener.exe' OR Name='Runner.Worker.exe'")+$dirs = New-Object System.Collections.Generic.List[string]+foreach ($p in $procs) {+ if ($p.ExecutablePath) { $dirs.Add((Split-Path (Split-Path $p.ExecutablePath -Parent) -Parent)) }+}+$patterns = @($OR_DIRS) + @(+ "$env:SystemDrive\actions-runner\*", "$env:SystemDrive\actions-runner*", "$env:SystemDrive\runners\*", "$env:SystemDrive\actions-runners\*",+ "$env:USERPROFILE\actions-runner*", "$env:USERPROFILE\runners\*"+)+foreach ($pattern in $patterns) {+ if (-not $pattern) { continue }+ $pattern = $pattern -replace '^~', $env:USERPROFILE+ foreach ($d in (Get-Item -Path $pattern -Force)) {+ if ($d.PSIsContainer -and (Test-Path (Join-Path $d.FullName '.runner'))) { $dirs.Add($d.FullName) }+ }+}++$i = 0+foreach ($d in ($dirs | Sort-Object -Unique)) {+ $cfg = Join-Path $d '.runner'+ if (-not (Test-Path $cfg)) { continue }+ $p = "r$i"+ kv "$p.dir" $d+ kv "$p.config" ((Get-Content -Raw $cfg) -replace "[\r\n]", '')+ $listener = $procs | Where-Object { $_.Name -eq 'Runner.Listener.exe' -and $_.ExecutablePath -like "$d\bin\*" } | Select-Object -First 1+ $worker = $procs | Where-Object { $_.Name -eq 'Runner.Worker.exe' -and $_.ExecutablePath -like "$d\bin\*" } | Select-Object -First 1+ kv "$p.listener" $listener.ProcessId+ kv "$p.worker" $worker.ProcessId+ $exe = Join-Path $d 'bin\Runner.Listener.exe'+ if (Test-Path $exe) { kv "$p.version" ((& $exe --version) | Select-Object -First 1) }+ $svcFile = Join-Path $d '.service'+ if (Test-Path $svcFile) {+ $svc = (Get-Content $svcFile | Select-Object -First 1).Trim()+ kv "$p.service" $svc+ $s = Get-Service -Name $svc+ if ($s) { kv "$p.service_state" ($(if ($s.Status -eq 'Running') { 'active' } else { 'inactive' })) } else { kv "$p.service_state" 'unknown' }+ }+ $i+++}diff --git a/src/probe/scripts/probe.sh b/src/probe/scripts/probe.shnew file mode 100644index 0000000..437a1db--- /dev/null+++ b/src/probe/scripts/probe.sh@@ -0,0 +1,182 @@+# OpenRunner machine probe (macOS / Linux). Read-only.+# Prints key=value lines; runner N is reported as rN.<key>=<value>.+# OR_DIRS (newline-separated glob patterns) is prepended by OpenRunner.++LC_ALL=C+export LC_ALL+PATH="$PATH:/usr/sbin:/sbin:/usr/bin:/bin:/usr/local/bin"++kv() { printf '%s=%s\n' "$1" "$2"; }++os=$(uname -s 2>/dev/null | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz')+now=$(date +%s)+kv probe 1+kv os "$os"+kv arch "$(uname -m 2>/dev/null)"+kv hostname "$(hostname 2>/dev/null)"++case "$os" in+darwin)+ kv os_version "macOS $(sw_vers -productVersion 2>/dev/null)"+ kv cores "$(sysctl -n hw.ncpu 2>/dev/null)"+ kv load "$(sysctl -n vm.loadavg 2>/dev/null | tr -d '{}')"+ boot=$(sysctl -n kern.boottime 2>/dev/null | sed -n 's/^{ sec = \([0-9]*\),.*/\1/p')+ [ -n "$boot" ] && kv uptime_s "$((now - boot))"+ memsize=$(sysctl -n hw.memsize 2>/dev/null)+ kv mem_total "$memsize"+ # "Memory used" as Activity Monitor shows it: app memory + wired + compressed.+ vm_stat 2>/dev/null | awk -v total="$memsize" '+ function n(s) { sub(/\.$/, "", s); return s + 0 }+ /page size of/ { ps = $8 }+ /^Anonymous pages/ { anon = n($3) }+ /^Pages purgeable/ { purg = n($3) }+ /^Pages active/ { active = n($3) }+ /^Pages wired down/ { wired = n($4) }+ /^Pages occupied by compressor/ { comp = n($5) }+ END {+ if (!ps) exit+ used = (anon > 0) ? (anon - purg + wired + comp) * ps : (active + wired + comp) * ps+ if (total > 0 && used > total) used = total+ printf "mem_used=%.0f\n", used+ }'+ # Second sample of top is the CPU usage over the last second.+ top -l 2 -n 0 -s 1 2>/dev/null | awk '/CPU usage/ { idle = $7 } END { sub(/%/, "", idle); if (idle != "") printf "cpu_pct=%.1f\n", 100 - idle }'+ disk=/+ [ -d /System/Volumes/Data ] && disk=/System/Volumes/Data+ ;;+linux)+ if [ -r /etc/os-release ]; then+ kv os_version "$(. /etc/os-release 2>/dev/null; printf '%s' "${PRETTY_NAME:-Linux}")"+ else+ kv os_version "Linux $(uname -r 2>/dev/null)"+ fi+ kv cores "$(getconf _NPROCESSORS_ONLN 2>/dev/null || nproc 2>/dev/null)"+ kv load "$(cut -d' ' -f1-3 /proc/loadavg 2>/dev/null)"+ kv uptime_s "$(cut -d. -f1 /proc/uptime 2>/dev/null)"+ awk '/^MemTotal:/ { t = $2 } /^MemAvailable:/ { a = $2 }+ END { if (t) printf "mem_total=%.0f\nmem_used=%.0f\n", t * 1024, (t - a) * 1024 }' /proc/meminfo 2>/dev/null+ s1=$(head -n1 /proc/stat 2>/dev/null)+ sleep 1+ s2=$(head -n1 /proc/stat 2>/dev/null)+ printf '%s\n%s\n' "$s1" "$s2" | awk '+ { t = 0; for (i = 2; i <= NF; i++) t += $i; idle = $5 + $6 }+ NR == 1 { t1 = t; i1 = idle }+ NR == 2 { dt = t - t1; if (dt > 0) printf "cpu_pct=%.1f\n", (1 - (idle - i1) / dt) * 100 }'+ disk=/+ ;;+*)+ kv os_version "$(uname -sr 2>/dev/null)"+ disk=/+ ;;+esac++df -kP "$disk" 2>/dev/null | awk 'NR == 2 { printf "disk_total=%.0f\ndisk_free=%.0f\ndisk_path=%s\n", $2 * 1024, $4 * 1024, $6 }'++# --- Runners -----------------------------------------------------------------+# A runner is a folder with a .runner config. Find them from running+# Runner.Listener / Runner.Worker processes and from the usual install places.++procs=$(ps -A -o pid= -o command= 2>/dev/null | grep -E '/bin/Runner\.(Listener|Worker)( |$)' | grep -v grep)++candidates() {+ printf '%s\n' "$procs" | awk '{+ for (i = 2; i <= NF; i++) if ($i ~ /^\/.*\/bin\/Runner\.(Listener|Worker)$/) { sub(/\/bin\/Runner\.[A-Za-z]*$/, "", $i); print $i; break }+ }'+ old_ifs=$IFS+ IFS='+'+ for pattern in $OR_DIRS \+ "$HOME"/actions-runner/* "$HOME"/actions-runner* "$HOME"/runners/* "$HOME"/actions-runners/* "$HOME"/actions/* \+ /opt/actions-runner* /opt/runners/* /opt/actions-runners/* /srv/actions-runner* /srv/runners/* \+ /var/lib/actions-runner* /Users/*/actions-runner* /home/*/actions-runner*; do+ case "$pattern" in "~"|"~/"*) pattern="$HOME${pattern#\~}" ;; esac+ for d in $pattern; do+ [ -f "$d/.runner" ] && printf '%s\n' "${d%/}"+ done+ done+ IFS=$old_ifs+}++pid_of() { printf '%s\n' "$procs" | awk -v bin="$1" '{ for (i = 2; i <= NF; i++) if ($i == bin) { print $1; exit } }'; }++candidates | sort -u | {+ i=0+ while IFS= read -r d; do+ [ -n "$d" ] && [ -f "$d/.runner" ] || continue+ p="r$i"+ kv "$p.dir" "$d"+ kv "$p.config" "$(tr -d '\r\n' < "$d/.runner" 2>/dev/null)"+ kv "$p.listener" "$(pid_of "$d/bin/Runner.Listener")"+ kv "$p.worker" "$(pid_of "$d/bin/Runner.Worker")"+ if [ -x "$d/bin/Runner.Listener" ]; then+ # Some builds print log lines too; the version is the bare x.y.z line.+ kv "$p.version" "$("$d/bin/Runner.Listener" --version 2>/dev/null | grep -E '^v?[0-9]+\.[0-9]+\.[0-9]+' | tail -n1)"+ fi+ if [ -f "$d/.service" ]; then+ svc=$(head -n1 "$d/.service" 2>/dev/null)+ kv "$p.service" "$svc"+ state=unknown+ case "$os" in+ darwin)+ svc_name=$(basename "$svc" .plist)+ if launchctl list "$svc_name" >/dev/null 2>&1; then state=active; else state=inactive; fi ;;+ linux)+ if command -v systemctl >/dev/null 2>&1; then+ if systemctl is-active --quiet "$svc" 2>/dev/null; then state=active; else state=inactive; fi+ fi ;;+ esac+ kv "$p.service_state" "$state"+ fi+ i=$((i + 1))+ done+}++# --- sudo (Linux) --------------------------------------------------------------+# Whether a systemd service can be installed without a password prompt.+if [ "$os" = linux ]; then+ if [ "$(id -u)" = 0 ]; then+ kv sudo root+ elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then+ kv sudo passwordless+ else+ kv sudo password+ fi+fi++# --- Docker -------------------------------------------------------------------+# Runner containers: the ones OpenRunner made (label openrunner.runner) and any+# other container running GitHub's actions-runner image.+if command -v docker >/dev/null 2>&1; then+ dv=$(docker version --format '{{.Server.Version}}' 2>/dev/null)+ if [ -n "$dv" ]; then+ kv docker "$dv"+ docker ps -a --no-trunc --format '{{.Names}}|{{.State}}|{{.Image}}|{{.Label "openrunner.runner"}}|{{.Label "openrunner.scope"}}' 2>/dev/null | {+ j=0+ while IFS='|' read -r cname cstate cimage rname rscope; do+ case "$cimage" in+ *actions-runner*) ;;+ *) [ -n "$rname" ] || continue ;;+ esac+ p="c$j"+ kv "$p.container" "$cname"+ kv "$p.state" "$cstate"+ kv "$p.image" "$cimage"+ kv "$p.name" "$rname"+ kv "$p.scope" "$rscope"+ kv "$p.restarts" "$(docker inspect -f '{{.RestartCount}}' "$cname" 2>/dev/null)"+ if [ "$cstate" = running ]; then+ top=$(docker top "$cname" -o pid,args 2>/dev/null)+ kv "$p.listener" "$(printf '%s\n' "$top" | awk '/Runner\.Listener/ { print $1; exit }')"+ kv "$p.worker" "$(printf '%s\n' "$top" | awk '/Runner\.Worker/ { print $1; exit }')"+ kv "$p.config" "$(docker exec "$cname" sh -c 'cat /home/runner/.runner 2>/dev/null' 2>/dev/null | tr -d '\r\n')"+ kv "$p.version" "$(docker exec "$cname" sh -c '/home/runner/bin/Runner.Listener --version 2>/dev/null' 2>/dev/null | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | tail -n1)"+ fi+ j=$((j + 1))+ done+ }+ else+ kv docker_error "$(docker version 2>&1 | grep -i -m1 -E 'permission denied|cannot connect|error' | cut -c1-200)"+ fi+fi++kv elapsed_s "$(( $(date +%s) - now ))"diff --git a/src/ui/activity.rs b/src/ui/activity.rsnew file mode 100644index 0000000..770dbb3--- /dev/null+++ b/src/ui/activity.rs@@ -0,0 +1,447 @@+//! The Activity page: one timeline of everything happening on the fleet —+//! operations started here (installs, restarts, logs, workspace setup) and the+//! commands agents ran in workspaces — with the selected item's output.++use chrono::{DateTime, Utc};+use gpui::{AnyElement, ClipboardItem, Context, FontWeight, SharedString, div, prelude::*, px};++use super::detail::op_status_icon;+use super::format;+use super::kit::{self, Button, card, icon};+use super::root::{Root, Route};+use super::theme::{ActiveTheme, Theme, mono_font};+use crate::fleet::model::{Operation, Snapshot, WorkspaceCommand, WorkspaceInfo};++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum ActivityItem {+ Op(u64),+ /// A command in a workspace's history.+ Command { workspace: String, index: usize },+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum ActivityFilter {+ #[default]+ All,+ Operations,+ Agents,+ Failed,+}++/// Feed entries, newest first.+enum Entry<'a> {+ Op(&'a Operation),+ Command(&'a WorkspaceInfo, usize, &'a WorkspaceCommand),+}++impl Entry<'_> {+ fn at(&self) -> DateTime<Utc> {+ match self {+ Entry::Op(o) => o.started_at,+ Entry::Command(_, _, c) => c.started_at,+ }+ }++ fn item(&self) -> ActivityItem {+ match self {+ Entry::Op(o) => ActivityItem::Op(o.id),+ Entry::Command(w, i, _) => ActivityItem::Command { workspace: w.id.clone(), index: *i },+ }+ }++ fn failed(&self) -> bool {+ match self {+ Entry::Op(o) => o.status == "failed",+ Entry::Command(_, _, c) => c.timed_out || c.exit_code.is_some_and(|e| e != 0),+ }+ }+}++const MAX_ENTRIES: usize = 300;++fn feed(s: &Snapshot, filter: ActivityFilter) -> Vec<Entry<'_>> {+ let mut entries: Vec<Entry> = Vec::new();+ if filter != ActivityFilter::Agents {+ entries.extend(s.operations.iter().map(Entry::Op));+ }+ if filter != ActivityFilter::Operations {+ for w in &s.workspaces {+ entries.extend(w.history.iter().enumerate().map(|(i, c)| Entry::Command(w, i, c)));+ }+ }+ if filter == ActivityFilter::Failed {+ entries.retain(|e| e.failed());+ }+ entries.sort_by_key(|e| std::cmp::Reverse(e.at()));+ entries.truncate(MAX_ENTRIES);+ entries+}++impl Root {+ /// The selected item, falling back to the newest one in the feed.+ pub(super) fn selected_activity(&self, s: &Snapshot) -> Option<ActivityItem> {+ let entries = feed(s, self.activity_filter);+ self.activity_selected+ .clone()+ .filter(|sel| entries.iter().any(|e| &e.item() == sel))+ .or_else(|| entries.first().map(|e| e.item()))+ }++ pub(super) fn render_activity(&mut self, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let entries = feed(&s, self.activity_filter);+ let selected = self.selected_activity(&s);+ let running = s.operations.iter().filter(|o| o.status == "running").count();++ let filters = [+ (ActivityFilter::All, "All"),+ (ActivityFilter::Operations, "Operations"),+ (ActivityFilter::Agents, "Agent commands"),+ (ActivityFilter::Failed, "Failed"),+ ];+ let filter_bar = div()+ .flex()+ .gap(px(2.))+ .p(px(3.))+ .rounded(px(9.))+ .bg(theme.element)+ .border_1()+ .border_color(theme.border_variant)+ .children(filters.into_iter().map(|(f, label)| {+ let active = self.activity_filter == f;+ div()+ .id(label)+ .h(px(26.))+ .px(px(10.))+ .flex()+ .items_center()+ .rounded(px(7.))+ .cursor_pointer()+ .text_size(px(12.5))+ .text_color(if active { theme.text } else { theme.text_muted })+ .when(active, |d| d.bg(theme.surface).border_1().border_color(theme.border).shadow_sm())+ .child(label)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.activity_filter = f;+ cx.notify()+ }))+ }));++ let list: Vec<AnyElement> = entries.iter().map(|e| self.feed_row(&theme, e, selected.as_ref() == Some(&e.item()), cx)).collect();+ let empty = entries.is_empty();+ let detail = match &selected {+ Some(ActivityItem::Op(id)) => s.operations.iter().find(|o| o.id == *id).map(|o| self.op_detail(&theme, o, cx)),+ Some(ActivityItem::Command { workspace, index }) => s+ .workspaces+ .iter()+ .find(|w| &w.id == workspace)+ .and_then(|w| w.history.get(*index).map(|c| command_detail(&theme, w, c, cx))),+ None => None,+ };+ let has_detail = detail.is_some();++ div()+ .size_full()+ .flex()+ .flex_col()+ .child(+ div()+ .flex()+ .flex_none()+ .items_center()+ .gap(px(12.))+ .px(px(28.))+ .pt(px(18.))+ .pb(px(14.))+ .child(filter_bar)+ .child(div().flex_1())+ .when(running > 0, |d| {+ d.child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(kit::spinner("activity-running", 12., theme.accent))+ .child(format!("{running} running")),+ )+ })+ .child(+ Button::new("activity-clear", "Clear finished")+ .icon("trash-2")+ .disabled(s.operations.iter().all(|o| o.status == "running"))+ .on_click(cx.listener(|this, _, _, _| this.engine.clear_operations())),+ ),+ )+ .child(+ div()+ .flex()+ .flex_1()+ .min_h(px(0.))+ .gap(px(16.))+ .px(px(28.))+ .pb(px(24.))+ .child(+ card(&theme).w(px((self.content_width * 0.36).clamp(260., 380.))).flex_none().overflow_hidden().child(+ div()+ .id("activity-feed")+ .size_full()+ .overflow_y_scroll()+ .p(px(6.))+ .children(list)+ .when(empty, |d| {+ d.child(kit::empty_state(+ &theme,+ "activity",+ "Nothing yet. Installs, restarts, log requests and the commands agents run in workspaces show up here.",+ ))+ }),+ ),+ )+ .child(div().flex().flex_col().flex_1().min_w(px(0.)).children(detail).when(!has_detail, |d| {+ d.child(+ card(&theme)+ .flex_1()+ .items_center()+ .justify_center()+ .text_size(px(12.5))+ .text_color(theme.text_placeholder)+ .child("Select an entry to see its output."),+ )+ })),+ )+ }++ fn feed_row(&self, theme: &Theme, e: &Entry, selected: bool, cx: &mut Context<Self>) -> AnyElement {+ let item = e.item();+ let (status, title, subtitle) = match e {+ Entry::Op(o) => (op_status_icon(theme, o), o.title.clone(), format!("{} · {}", kind_label(&o.kind), format::ago(Some(o.started_at)))),+ Entry::Command(w, _, c) => (+ command_icon(theme, c),+ c.command.clone(),+ format!(+ "{} in {} · {}",+ c.by.clone().or_else(|| w.owner.clone()).unwrap_or_else(|| "someone".into()),+ w.name,+ format::ago(Some(c.started_at))+ ),+ ),+ };+ let is_command = matches!(e, Entry::Command(..));+ div()+ .id(SharedString::from(format!("feed-{item:?}")))+ .flex()+ .items_start()+ .gap(px(10.))+ .px(px(10.))+ .py(px(8.))+ .rounded(px(8.))+ .cursor_pointer()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(div().pt(px(2.)).child(status))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().truncate().text_size(px(12.5)).when(is_command, |d| d.font_family(mono_font())).child(title))+ .child(div().truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(subtitle)),+ )+ .on_click(cx.listener(move |this, _, _, cx| {+ this.activity_selected = Some(item.clone());+ this.activity_seen_len = usize::MAX;+ cx.notify()+ }))+ .into_any_element()+ }++ fn op_detail(&self, theme: &Theme, op: &Operation, cx: &mut Context<Self>) -> AnyElement {+ let copy_text = op.log.join("\n");+ let machine = op+ .machine_id+ .clone()+ .and_then(|id| self.snapshot.machines.iter().find(|m| m.id == id).map(|m| (id, m.name.clone())));+ let runner = op.runner_id.clone();+ let when = match op.finished_at {+ Some(t) => format!(+ "{} {} · took {}",+ if op.status == "succeeded" { "Finished" } else { "Failed" },+ format::ago(Some(t)),+ crate::util::short_duration((t - op.started_at).num_seconds().max(0) as u64)+ ),+ None => format!("Running for {}", format::elapsed(op.started_at)),+ };+ let lines: Vec<AnyElement> = op.log.iter().map(|l| log_line(theme, l)).collect();+ let meta = div()+ .flex()+ .flex_wrap()+ .items_center()+ .gap(px(8.))+ .text_size(px(12.))+ .text_color(theme.text_placeholder)+ .child(when)+ .children(machine.map(|(id, name)| {+ div()+ .id("op-machine")+ .cursor_pointer()+ .text_color(theme.text_accent)+ .child(name)+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(id.clone()), window, cx)))+ }))+ .children(runner.map(|id| {+ div()+ .id("op-runner")+ .cursor_pointer()+ .text_color(theme.text_accent)+ .child(id.rsplit('/').next().unwrap_or_default().to_string())+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Runner(id.clone()), window, cx)))+ }))+ .into_any_element();+ let body = div()+ .id(SharedString::from(format!("op-log-{}", op.id)))+ .flex_1()+ .min_h(px(0.))+ .overflow_y_scroll()+ .track_scroll(&self.activity_scroll)+ .p(px(14.))+ .font_family(mono_font())+ .text_size(px(12.))+ .line_height(px(19.))+ .children(lines)+ .when_some(op.error.clone().filter(|e| !op.log.iter().any(|l| l.contains(e.as_str()))), |d, e| {+ d.child(div().mt(px(6.)).flex().gap(px(6.)).text_color(theme.error).child(icon("circle-x", 13., theme.error)).child(e))+ })+ .when(op.log.is_empty() && op.status == "running", |d| d.child(div().text_color(theme.text_placeholder).child("Waiting for output…")))+ .into_any_element();+ detail_frame(theme, op_status_icon(theme, op), op.title.clone(), meta, copy_text, body)+ }+}++fn command_detail(theme: &Theme, w: &WorkspaceInfo, c: &WorkspaceCommand, cx: &mut Context<Root>) -> AnyElement {+ let ws = w.id.clone();+ let outcome = match (c.background, c.timed_out, c.exit_code) {+ (true, _, _) => "started in the background".to_string(),+ (_, true, _) => "timed out".to_string(),+ (_, _, Some(code)) => format!("exit {code} in {}", crate::util::short_duration(c.duration_ms / 1000)),+ _ => "running".to_string(),+ };+ let meta = div()+ .flex()+ .flex_wrap()+ .items_center()+ .gap(px(8.))+ .text_size(px(12.))+ .text_color(theme.text_placeholder)+ .child(format!(+ "{} · {} · {outcome}",+ c.by.clone().or_else(|| w.owner.clone()).unwrap_or_else(|| "someone".into()),+ format::ago(Some(c.started_at)),+ ))+ .child(+ div()+ .id("cmd-workspace")+ .cursor_pointer()+ .text_color(theme.text_accent)+ .child(format!("{} on {}", w.name, w.machine_name))+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Workspace(ws.clone()), window, cx))),+ )+ .into_any_element();+ let mut lines: Vec<AnyElement> = vec![div().text_color(theme.text_accent).child(format!("$ {}", c.command)).into_any_element()];+ lines.extend(c.output_tail.iter().map(|l| div().text_color(theme.text_muted).child(l.clone()).into_any_element()));+ if c.output_tail.is_empty() {+ lines.push(div().text_color(theme.text_placeholder).child("(no output)").into_any_element());+ }+ let body = div()+ .id("cmd-output")+ .flex_1()+ .min_h(px(0.))+ .overflow_y_scroll()+ .p(px(14.))+ .font_family(mono_font())+ .text_size(px(12.))+ .line_height(px(19.))+ .children(lines)+ .into_any_element();+ detail_frame(theme, command_icon(theme, c), c.command.clone(), meta, c.output_tail.join("\n"), body)+}++/// Header (status, title, meta, copy) above a scrolling output pane.+fn detail_frame(theme: &Theme, status: AnyElement, title: String, meta: AnyElement, copy_text: String, body: AnyElement) -> AnyElement {+ card(theme)+ .flex_1()+ .min_h(px(0.))+ .overflow_hidden()+ .child(+ div()+ .flex()+ .flex_none()+ .items_start()+ .gap(px(10.))+ .px(px(16.))+ .py(px(12.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(div().pt(px(2.)).child(status))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(3.))+ .child(div().truncate().text_size(px(14.)).font_weight(FontWeight::MEDIUM).child(title))+ .child(meta),+ )+ .child(Button::icon_only("detail-copy", "copy").tooltip("Copy output").on_click(move |_, _, cx| {+ cx.write_to_clipboard(ClipboardItem::new_string(copy_text.clone()))+ })),+ )+ .child(div().flex().flex_col().flex_1().min_h(px(0.)).bg(theme.sidebar).child(body))+ .into_any_element()+}++fn command_icon(theme: &Theme, c: &WorkspaceCommand) -> AnyElement {+ let color = match (c.background, c.timed_out, c.exit_code) {+ (true, _, _) => theme.info,+ (_, true, _) => theme.warning,+ (_, _, Some(0)) => theme.success,+ (_, _, Some(_)) => theme.error,+ _ => theme.text_placeholder,+ };+ icon("terminal", 13., color).into_any_element()+}++fn kind_label(kind: &str) -> &'static str {+ match kind {+ "install" => "install",+ "start" => "start",+ "stop" => "stop",+ "restart" => "restart",+ "logs" => "logs",+ "remove" => "remove",+ "workspace" => "workspace",+ "machine" => "machine",+ _ => "operation",+ }+}++/// Colors OpenRunner's own lines (see the conventions in crate::ops).+fn log_line(theme: &Theme, line: &str) -> AnyElement {+ let color = if line.starts_with("▸ ") {+ theme.text_accent+ } else if line.starts_with("✓ ") {+ theme.success+ } else if line.starts_with("error: ") || line.starts_with("Error") {+ theme.error+ } else if line.starts_with("warning: ") {+ theme.warning+ } else {+ theme.text_muted+ };+ div().text_color(color).child(line.to_string()).into_any_element()+}diff --git a/src/ui/assets.rs b/src/ui/assets.rsnew file mode 100644index 0000000..35dc7e6--- /dev/null+++ b/src/ui/assets.rs@@ -0,0 +1,84 @@+//! Icons and fonts compiled into the binary, so the app is a single file.++use std::borrow::Cow;++use anyhow::Result;+use gpui::{App, AssetSource, SharedString};++macro_rules! icons {+ ($($name:literal),* $(,)?) => {+ const ICONS: &[(&str, &[u8])] = &[+ $(($name, include_bytes!(concat!("../../assets/icons/", $name, ".svg")))),*+ ];+ };+}++icons!(+ "activity", "box", "check", "chevron-down", "chevron-right", "circle", "circle-alert", "circle-check",+ "circle-x", "clock", "copy", "cpu", "ellipsis", "external-link", "folder-open", "git-branch",+ "hard-drive", "inbox", "info", "laptop", "layers", "layout-grid", "list", "loader-circle",+ "memory-stick", "minus", "monitor", "network", "panel-bottom", "play", "plus", "refresh-cw",+ "rotate-ccw", "scroll-text", "search", "server", "settings", "square", "terminal", "trash-2",+ "triangle-alert", "x", "zap", "arrow-left", "arrow-right", "gauge", "radio", "workflow",+);++const FONTS: &[&[u8]] = &[+ include_bytes!("../../assets/fonts/geist-400.ttf"),+ include_bytes!("../../assets/fonts/geist-500.ttf"),+ include_bytes!("../../assets/fonts/geist-600.ttf"),+ include_bytes!("../../assets/fonts/geist-mono-400.ttf"),+ include_bytes!("../../assets/fonts/geist-mono-500.ttf"),+];++/// The app icon, for the Dock when running outside an .app bundle.+pub const APP_ICON_PNG: &[u8] = include_bytes!("../../assets/brand/icon-512.png");+/// Small copy of the icon for the sidebar.+const BRAND_PNG: &[u8] = include_bytes!("../../assets/brand/icon-128.png");++pub struct Assets;++impl AssetSource for Assets {+ fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {+ if path == "brand/icon.png" {+ return Ok(Some(Cow::Borrowed(BRAND_PNG)));+ }+ let name = path.strip_prefix("icons/").and_then(|p| p.strip_suffix(".svg"));+ Ok(name.and_then(|n| ICONS.iter().find(|(icon, _)| *icon == n)).map(|(_, bytes)| Cow::Borrowed(*bytes)))+ }++ fn list(&self, path: &str) -> Result<Vec<SharedString>> {+ Ok(ICONS+ .iter()+ .map(|(name, _)| SharedString::from(format!("icons/{name}.svg")))+ .filter(|p| p.starts_with(path))+ .collect())+ }+}++pub fn load_fonts(cx: &mut App) {+ let fonts = FONTS.iter().map(|f| Cow::Borrowed(*f)).collect();+ if let Err(e) = cx.text_system().add_fonts(fonts) {+ tracing::warn!("couldn't load bundled fonts: {e}");+ }+}++/// Shows the OpenRunner icon in the Dock. Bundled builds get it from Info.plist;+/// this covers `cargo run` and `cargo install`.+#[cfg(target_os = "macos")]+pub fn set_dock_icon() {+ use cocoa::appkit::{NSApp, NSApplication, NSImage};+ use cocoa::base::nil;+ use cocoa::foundation::NSData;+ // SAFETY: called on the main thread after GPUI has created NSApplication;+ // the PNG bytes are 'static and copied into NSData.+ unsafe {+ let data = NSData::dataWithBytes_length_(nil, APP_ICON_PNG.as_ptr() as *const std::ffi::c_void, APP_ICON_PNG.len() as u64);+ let image = NSImage::initWithData_(NSImage::alloc(nil), data);+ if image != nil {+ NSApp().setApplicationIconImage_(image);+ }+ }+}++#[cfg(not(target_os = "macos"))]+pub fn set_dock_icon() {}diff --git a/src/ui/detail.rs b/src/ui/detail.rsnew file mode 100644index 0000000..8aa8c9c--- /dev/null+++ b/src/ui/detail.rs@@ -0,0 +1,587 @@+//! Machine and runner pages, where runners are installed and controlled.++use gpui::{AnyElement, Context, FontWeight, SharedString, div, prelude::*, px};++use super::format;+use super::kit::{self, Button, ButtonStyle, card, chip, icon, kv, meter, pill, section_title};+use super::overview::page;+use super::theme::{ActiveTheme, mono_font, Theme};+use super::root::{Route, Root};+use crate::fleet::model::{Diagnostic, Machine, Operation, Runner, Snapshot};+use crate::ops::RunnerAction;++impl Root {+ pub(super) fn render_machine(&mut self, id: &str, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let Some(m) = s.machines.iter().find(|m| m.id == id).cloned() else {+ return gone(&theme, "This machine is no longer in fleet.toml.").into_any_element();+ };+ let p = m.probe.as_ref().filter(|p| p.ok);+ let busy = s.operations.iter().any(|o| o.status == "running" && o.machine_id.as_deref() == Some(&m.id) && o.kind != "logs");++ let mut meta = vec![if m.host.is_empty() { "no host".to_string() } else { m.host.clone() }];+ if !m.platform.is_empty() {+ meta.push(m.platform.clone());+ }+ if let Some(v) = p.and_then(|p| p.os_version.clone()) {+ meta.push(v);+ }+ let checked = match &m.probe {+ Some(p) => format!("Checked {} in {:.1}s", format::ago(Some(p.checked_at)), p.duration_ms as f64 / 1000.0),+ None => "Not checked yet".into(),+ };++ let header = div()+ .flex()+ .items_start()+ .justify_between()+ .gap(px(16.))+ .child(+ div()+ .flex()+ .items_start()+ .gap(px(12.))+ .child(+ div()+ .size(px(40.))+ .rounded(px(8.))+ .bg(theme.element)+ .border_1()+ .border_color(theme.border_variant)+ .flex()+ .items_center()+ .justify_center()+ .child(icon(format::machine_icon(&m), 20., theme.text_muted)),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(m.name.clone()))+ .child(pill(status_label(&m), theme.machine_status(&m.status))),+ )+ .child(div().font_family(mono_font()).text_size(px(12.)).text_color(theme.text_muted).child(meta.join(" · ")))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(checked)),+ ),+ )+ .child(+ div()+ .flex()+ .gap(px(6.))+ .child({+ let mid = m.id.clone();+ Button::new("m-install", "Install runner")+ .icon("plus")+ .style(ButtonStyle::Primary)+ .disabled(m.host.is_empty() || busy)+ .on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))+ })+ .child({+ let mid = m.id.clone();+ Button::new("m-check", "Check")+ .icon("refresh-cw")+ .loading(m.checking)+ .disabled(m.host.is_empty())+ .on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone()))))+ })+ .child({+ let machine = m.clone();+ Button::icon_only("m-remove", "trash-2")+ .style(ButtonStyle::Danger)+ .tooltip("Remove from fleet")+ .on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_machine(&machine, window, cx)))+ }),+ );++ let mut body = page("machine-page", &self.page_scroll).child(header);++ if let Some(err) = m.probe.as_ref().and_then(|p| p.error.clone()).filter(|_| m.status == "offline") {+ body = body.child(error_box(&theme, &err));+ }++ if let Some(p) = p {+ let mem = format::mem_fraction(&m);+ let disk = format::disk_used_fraction(&m);+ body = body.child(+ div()+ .flex()+ .gap(px(12.))+ .child(metric_card(+ &theme,+ "CPU",+ p.cpu_pct.map(|v| format!("{v:.0}%")),+ p.cores.map(|c| format!("{c} cores")),+ p.cpu_pct.map(|v| v as f32 / 100.0),+ theme.accent,+ ))+ .child(metric_card(+ &theme,+ "Memory",+ mem.map(|f| format!("{:.0}%", f * 100.0)),+ p.mem_used.zip(p.mem_total).map(|(u, t)| format!("{} of {}", format::bytes(u), format::bytes(t))),+ mem,+ theme.accent,+ ))+ .child(metric_card(+ &theme,+ "Disk free",+ p.disk_free.map(format::bytes),+ p.disk_total.map(|t| format!("of {} · {}", format::bytes(t), p.disk_path.clone().unwrap_or_default())),+ disk,+ if format::disk_low(&m) { theme.error } else { theme.accent },+ ))+ .child(metric_card(+ &theme,+ "Uptime",+ p.uptime_sec.map(format::uptime),+ (!p.load.is_empty()).then(|| format!("load {}", p.load.iter().map(|l| format!("{l:.2}")).collect::<Vec<_>>().join(" "))),+ None,+ theme.accent,+ )),+ );+ }++ let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();+ if m.kind == "runner" || !runners.is_empty() {+ let rows: Vec<AnyElement> = runners.iter().enumerate().map(|(i, r)| self.machine_runner_row(&theme, &s, r, i, busy, cx)).collect();+ body = body.child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Runners", Some(runners.len())))+ .child(card(&theme).children(rows)),+ );+ } else if !m.host.is_empty() {+ let mid = m.id.clone();+ body = body.child(+ card(&theme)+ .p(px(16.))+ .flex_row()+ .items_center()+ .gap(px(12.))+ .child(icon("box", 16., theme.text_placeholder))+ .child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(+ "No runners on this machine yet. Install one and it will register with GitHub and start picking up jobs.",+ ))+ .child(+ Button::new("m-install-empty", "Install runner")+ .icon("plus")+ .on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx))),+ ),+ );+ }++ body = body.child(diagnostics_section(&theme, &m.diagnostics, &s));+ if !m.host.is_empty() {+ body = body.child(self.machine_workspaces(&theme, &s, &m, cx));+ }+ body = body.child(self.operations_section(&theme, &s, |o| o.machine_id.as_deref() == Some(id), cx));+ if let Some(notes) = &m.notes {+ body = body.child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Notes", None))+ .child(card(&theme).p(px(14.)).child(div().w_full().text_size(px(12.5)).text_color(theme.text_muted).child(notes.clone()))),+ );+ }+ body.into_any_element()+ }++ fn machine_runner_row(&self, theme: &Theme, s: &Snapshot, r: &Runner, i: usize, busy: bool, cx: &mut Context<Self>) -> AnyElement {+ let id = r.id.clone();+ let job = r.job_id.and_then(|j| s.jobs.running.iter().find(|x| x.id == j));+ let local = r.local.as_ref();+ let service = local.and_then(|l| l.service_state.clone()).map(|st| format!("service {st}")).unwrap_or_else(|| {+ if local.is_some() { "no service".into() } else { "not installed".into() }+ });+ div()+ .id(SharedString::from(format!("mr-{}", r.id)))+ .group("runner-row")+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(14.))+ .py(px(9.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(kit::runner_glyph(theme, &r.state, 10.))+ .child(+ div()+ .flex()+ .flex_col()+ .w(px(190.))+ .flex_none()+ .child(div().truncate().font_family(mono_font()).text_size(px(12.5)).child(r.name.clone()))+ .child(div().text_size(px(11.5)).text_color(theme.state(&r.state)).child(state_label(r))),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().truncate().text_size(px(12.5)).text_color(if job.is_some() { theme.text } else { theme.text_placeholder }).child(+ job.map(|j| j.name.clone()).unwrap_or_else(|| if r.state == "working" { "Running a job".into() } else { "—".into() }),+ ))+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(+ "{}{}",+ local.and_then(|l| l.version.clone()).map(|v| format!("v{v} · ")).unwrap_or_default(),+ service+ ))),+ )+ .child(self.runner_actions(theme, r, busy, "row", cx))+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Runner(id.clone()), window, cx)))+ .into_any_element()+ }++ /// Start / stop / restart / logs / remove buttons for a runner.+ fn runner_actions(&self, theme: &Theme, r: &Runner, busy: bool, prefix: &'static str, cx: &mut Context<Self>) -> impl IntoElement {+ let controllable = r.local.is_some() && r.machine_id.is_some();+ let running = r.local.as_ref().is_some_and(|l| l.listener);+ let mk = |action: RunnerAction, icon_name: &'static str, tip: &'static str, enabled: bool| {+ let id = r.id.clone();+ Button::icon_only(SharedString::from(format!("{prefix}-{}-{}", action.label(), r.id)), icon_name)+ .tooltip(tip)+ .disabled(!enabled)+ .on_click(cx.listener(move |this, _, _, cx| this.runner_action(&id, action, cx)))+ };+ let runner = r.clone();+ div()+ .flex()+ .flex_none()+ .gap(px(2.))+ .child(mk(RunnerAction::Start, "play", "Start", controllable && !running && !busy))+ .child(mk(RunnerAction::Stop, "square", "Stop", controllable && running && !busy))+ .child(mk(RunnerAction::Restart, "rotate-ccw", "Restart", controllable && !busy))+ .child(mk(RunnerAction::Logs, "scroll-text", "Show logs", controllable))+ .child(+ Button::icon_only(SharedString::from(format!("{prefix}-remove-{}", r.id)), "trash-2")+ .style(ButtonStyle::Danger)+ .tooltip("Remove runner")+ .disabled(busy)+ .on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_runner(&runner, window, cx))),+ )+ .text_color(theme.text_muted)+ }++ pub(super) fn render_runner(&mut self, id: &str, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let Some(r) = s.runners.iter().find(|r| r.id == id).cloned() else {+ return gone(&theme, "This runner is gone. It was removed, or renamed on its machine.").into_any_element();+ };+ let machine = r.machine_id.as_deref().and_then(|mid| s.machines.iter().find(|m| m.id == mid)).cloned();+ let busy = machine.as_ref().is_some_and(|m| {+ s.operations.iter().any(|o| o.status == "running" && o.machine_id.as_deref() == Some(&m.id) && o.kind != "logs")+ });+ let job = r.job_id.and_then(|j| s.jobs.running.iter().find(|x| x.id == j)).cloned();+ let source = match r.source.as_str() {+ "github" => "live from GitHub",+ "probe" => "from the last machine check",+ _ => "no data yet",+ };++ let header = div()+ .flex()+ .items_start()+ .justify_between()+ .gap(px(16.))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(6.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(kit::runner_glyph(&theme, &r.state, 14.))+ .child(div().font_family(mono_font()).text_size(px(20.)).font_weight(FontWeight::MEDIUM).child(r.name.clone()))+ .child(pill(state_label(&r), theme.state(&r.state))),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .children(machine.as_ref().map(|m| {+ let mid = m.id.clone();+ div()+ .id("runner-machine-link")+ .flex()+ .items_center()+ .gap(px(5.))+ .cursor_pointer()+ .text_color(theme.text_accent)+ .child(icon(format::machine_icon(m), 12., theme.text_accent))+ .child(m.name.clone())+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(mid.clone()), window, cx)))+ }))+ .when(machine.is_none(), |d| d.child("Not in fleet.toml"))+ .child("·")+ .child(format!("State {source}"))+ .when(!r.declared && r.machine_id.is_some(), |d| d.child("·").child("discovered")),+ )+ .child(div().flex().flex_wrap().gap(px(4.)).children(r.labels.iter().map(|l| chip(&theme, l.clone())))),+ )+ .child(self.runner_actions(&theme, &r, busy, "page", cx));++ let mut body = page("runner-page", &self.page_scroll).child(header);++ if let Some(j) = &job {+ let url = j.url.clone();+ body = body.child(+ card(&theme)+ .p(px(14.))+ .flex_row()+ .items_center()+ .gap(px(12.))+ .border_color(theme.accent.opacity(0.4))+ .child(kit::spinner("runner-job-spin", 15., theme.accent))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().text_size(px(13.)).child(j.name.clone()))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!(+ "{} · {}{}",+ j.repo,+ j.workflow,+ j.actor.as_ref().map(|a| format!(" · by {a}")).unwrap_or_default()+ ))),+ )+ .child(div().font_family(mono_font()).text_size(px(13.)).text_color(theme.text_muted).child(format::elapsed(j.started_at.unwrap_or(j.created_at))))+ .child(Button::new("runner-job-open", "Open").icon("external-link").on_click(move |_, _, cx| cx.open_url(&url))),+ );+ }++ let gh = match &r.github {+ Some(g) => card(&theme)+ .px(px(14.))+ .py(px(8.))+ .child(kv(&theme, "Status", status_dot_text(&theme, &g.status, if g.status == "online" { theme.success } else { theme.text_placeholder })))+ .child(kv(&theme, "Busy", if g.busy { "yes" } else { "no" }))+ .child(kv(&theme, "Registered to", kit::mono(g.scope.clone())))+ .child(kv(&theme, "Runner id", kit::mono(g.id.to_string())))+ .child(kv(&theme, "OS", g.os.clone())),+ None => card(&theme).p(px(14.)).child(div().text_size(px(12.5)).text_color(theme.text_placeholder).child(+ if s.github.configured {+ "GitHub doesn't list this runner in the orgs and repos you watch."+ } else {+ "Add your GitHub organization in Settings to see this runner's live status."+ },+ )),+ };+ let local = match &r.local {+ Some(l) => card(&theme)+ .px(px(14.))+ .py(px(8.))+ .child(kv(&theme, "Folder", kit::mono(l.dir.clone())))+ .child(kv(&theme, "Version", kit::mono(l.version.clone().unwrap_or_else(|| "—".into()))))+ .child(kv(&theme, "Service", kit::mono(match (&l.service, &l.service_state) {+ (Some(sv), Some(st)) => format!("{sv} ({st})"),+ (Some(sv), None) => sv.clone(),+ _ => "not installed as a service".into(),+ })))+ .child(kv(&theme, "Listener", kit::mono(l.listener_pid.map(|p| format!("running · pid {p}")).unwrap_or_else(|| "stopped".into()))))+ .child(kv(&theme, "Worker", kit::mono(l.worker_pid.map(|p| format!("running a job · pid {p}")).unwrap_or_else(|| "idle".into()))))+ .children(l.url.clone().map(|u| kv(&theme, "Config URL", kit::mono(u)))),+ None => card(&theme).p(px(14.)).child(div().text_size(px(12.5)).text_color(theme.text_placeholder).child(+ if machine.is_some() { "Not found on the machine at the last check." } else { "No machine in fleet.toml runs this runner." },+ )),+ };+ let wide = self.content_width >= 900.;+ body = body.child(+ div()+ .flex()+ .when(!wide, |d| d.flex_col())+ .gap(px(if wide { 16. } else { 26. }))+ .child(div().flex().flex_col().flex_1().min_w(px(0.)).gap(px(10.)).child(section_title(&theme, "GitHub", None)).child(gh))+ .child(div().flex().flex_col().flex_1().min_w(px(0.)).gap(px(10.)).child(section_title(&theme, "On the machine", None)).child(local)),+ );++ let diags: Vec<Diagnostic> =+ machine.iter().flat_map(|m| m.diagnostics.iter()).filter(|d| d.runner_id.as_deref() == Some(id)).cloned().collect();+ body = body.child(diagnostics_section(&theme, &diags, &s));+ let rid = r.id.clone();+ body = body.child(self.operations_section(&theme, &s, move |o| o.runner_id.as_deref() == Some(&rid), cx));+ body.into_any_element()+ }++ fn operations_section(&self, theme: &Theme, s: &Snapshot, filter: impl Fn(&Operation) -> bool, cx: &mut Context<Self>) -> AnyElement {+ let ops: Vec<&Operation> = s.operations.iter().filter(|o| filter(o)).take(6).collect();+ if ops.is_empty() {+ return div().into_any_element();+ }+ let rows: Vec<AnyElement> = ops+ .iter()+ .enumerate()+ .map(|(i, o)| {+ let id = o.id;+ div()+ .id(SharedString::from(format!("op-row-{}", o.id)))+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(14.))+ .py(px(8.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(op_status_icon(theme, o))+ .child(div().flex_1().truncate().text_size(px(12.5)).child(o.title.clone()))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format::ago(Some(o.started_at))))+ .on_click(cx.listener(move |this, _, _, cx| this.show_operation(id, cx)))+ .into_any_element()+ })+ .collect();+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Recent operations", None))+ .child(card(theme).children(rows))+ .into_any_element()+ }+}++pub(super) fn op_status_icon(theme: &Theme, o: &Operation) -> AnyElement {+ match o.status.as_str() {+ "running" => kit::spinner(SharedString::from(format!("op-spin-{}", o.id)), 13., theme.accent).into_any_element(),+ "succeeded" => icon("circle-check", 13., theme.success).into_any_element(),+ _ => icon("circle-x", 13., theme.error).into_any_element(),+ }+}++fn diagnostics_section(theme: &Theme, diags: &[Diagnostic], _s: &Snapshot) -> AnyElement {+ let rows: Vec<AnyElement> = diags+ .iter()+ .enumerate()+ .map(|(i, d)| {+ let color = theme.level(&d.level);+ let icon_name = match d.level.as_str() {+ "error" => "circle-x",+ "warning" => "triangle-alert",+ "unknown" => "circle",+ _ => "info",+ };+ div()+ .flex()+ .items_start()+ .gap(px(10.))+ .px(px(14.))+ .py(px(9.))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(div().pt(px(1.)).child(icon(icon_name, 14., color)))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(4.))+ .child(div().text_size(px(12.5)).child(d.message.clone()))+ .children(d.hint.clone().map(|h| copyable(theme, i, h))),+ )+ .into_any_element()+ })+ .collect();+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Diagnostics", Some(diags.len())))+ .child(card(theme).when(rows.is_empty(), |d| d.child(kit::empty_state(theme, "circle-check", "No warnings."))).children(rows))+ .into_any_element()+}++/// A hint line; commands get a copy button.+fn copyable(theme: &Theme, i: usize, text: String) -> impl IntoElement {+ let looks_like_command = ["gh ", "ssh ", "sudo ", "cd ", "Start-Service", "systemctl", "launchctl"].iter().any(|p| text.starts_with(p));+ let copy = text.clone();+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .child(+ div()+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .when(looks_like_command, |d| d.font_family(mono_font()).px(px(6.)).py(px(2.)).rounded(px(4.)).bg(theme.element))+ .child(text),+ )+ .when(looks_like_command, |d| {+ d.child(Button::icon_only(("copy-hint", i), "copy").tooltip("Copy").on_click(move |_, _, cx| {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(copy.clone()))+ }))+ })+}++fn metric_card(theme: &Theme, title: &'static str, value: Option<String>, sub: Option<String>, fraction: Option<f32>, color: gpui::Hsla) -> impl IntoElement {+ card(theme)+ .flex_1()+ .min_w(px(0.))+ .px(px(14.))+ .py(px(12.))+ .gap(px(6.))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(title))+ .child(div().font_family(mono_font()).text_size(px(20.)).child(value.unwrap_or_else(|| "—".into())))+ .children(fraction.map(|f| meter(theme, f, color)))+ .children(sub.map(|s| div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(s)))+}++fn error_box(theme: &Theme, err: &str) -> impl IntoElement {+ div()+ .flex()+ .items_start()+ .gap(px(10.))+ .p(px(12.))+ .rounded(px(8.))+ .border_1()+ .border_color(theme.error.opacity(0.5))+ .bg(theme.error.opacity(0.08))+ .child(icon("circle-x", 14., theme.error))+ .child(div().flex_1().font_family(mono_font()).text_size(px(12.)).child(err.to_string()))+}++fn gone(theme: &Theme, text: &'static str) -> impl IntoElement {+ div().size_full().flex().items_center().justify_center().text_color(theme.text_placeholder).child(text)+}++fn status_dot_text(_theme: &Theme, text: &str, color: gpui::Hsla) -> impl IntoElement {+ div().flex().items_center().gap(px(6.)).child(kit::dot(color, 7.)).child(text.to_string())+}++fn status_label(m: &Machine) -> &'static str {+ match m.status.as_str() {+ "online" => "Online",+ "offline" => "Unreachable",+ "manual" => "No host",+ _ => "Not checked",+ }+}++fn state_label(r: &Runner) -> &'static str {+ match r.state.as_str() {+ "working" => "Working",+ "idle" => "Idle",+ "offline" => "Offline",+ _ => "Unknown",+ }+}diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rsnew file mode 100644index 0000000..a27be1b--- /dev/null+++ b/src/ui/dialogs.rs@@ -0,0 +1,779 @@+//! Modal dialogs: add a machine, install runners on one, confirm a removal.++use std::sync::Arc;++use gpui::{+ AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, SharedString, Subscription,+ Window, div, prelude::*, px,+};++use super::input::{InputEvent, TextInput};+use super::kit::{Button, ButtonStyle, checkbox, icon, label};+use super::theme::{ActiveTheme, mono_font, Theme};+use crate::fleet::Engine;+use crate::fleet::workspaces::{CreateWorkspace, DEFAULT_IMAGE, WorkspaceIsolation};+use crate::fleet::model::Snapshot;+use crate::ops::{InstallRequest, NewMachine, ssh_hosts};++pub enum DialogEvent {+ Dismissed,+ OperationStarted(u64),+ MachineAdded(String),+ OpenSettings,+ /// The root view runs it, so it can open the workspace when it's ready.+ CreateWorkspace(CreateWorkspace, WorkspaceIsolation),+}++fn frame(theme: &Theme, title: impl Into<SharedString>, intro: Option<SharedString>) -> gpui::Div {+ div()+ .w(px(500.))+ .flex()+ .flex_col()+ .gap(px(14.))+ .p(px(18.))+ .rounded(px(10.))+ .bg(theme.elevated)+ .border_1()+ .border_color(theme.border)+ .shadow_lg()+ .text_color(theme.text)+ .child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child(title.into()))+ .children(intro.map(|t| div().text_size(px(12.5)).text_color(theme.text_muted).child(t)))+}++fn field(theme: &Theme, name: &'static str, input: impl IntoElement, help: Option<&'static str>) -> impl IntoElement {+ div()+ .flex()+ .flex_col()+ .gap(px(6.))+ .child(label(theme, name).text_size(px(12.)).text_color(theme.text_muted))+ .child(input)+ .children(help.map(|h| div().text_size(px(11.5)).text_color(theme.text_placeholder).child(h)))+}++fn error_line(theme: &Theme, error: &Option<String>) -> Option<impl IntoElement> {+ error.as_ref().map(|e| {+ div()+ .flex()+ .items_start()+ .gap(px(8.))+ .p(px(10.))+ .rounded(px(6.))+ .bg(theme.error.opacity(0.1))+ .text_size(px(12.5))+ .text_color(theme.text)+ .child(icon("circle-alert", 14., theme.error))+ .child(div().flex_1().child(e.clone()))+ })+}++fn footer(children: Vec<AnyElement>) -> impl IntoElement {+ div().flex().justify_end().gap(px(8.)).pt(px(4.)).children(children)+}++// ---------------------------------------------------------------------------++pub struct AddMachineDialog {+ engine: Arc<Engine>,+ name: Entity<TextInput>,+ host: Entity<TextInput>,+ hosts: Vec<String>,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for AddMachineDialog {}++impl AddMachineDialog {+ pub fn new(engine: Arc<Engine>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let name = cx.new(|cx| TextInput::new(cx, "Mac Studio"));+ let host = cx.new(|cx| TextInput::new(cx, "[email protected], an ~/.ssh/config alias, or local").mono());+ let on_input = |this: &mut Self, _: &Entity<TextInput>, e: &InputEvent, _: &mut Window, cx: &mut Context<Self>| match e {+ InputEvent::Submit => this.submit(cx),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => {+ this.error = None;+ cx.notify()+ }+ };+ let subs = vec![cx.subscribe_in(&name, window, on_input), cx.subscribe_in(&host, window, on_input)];+ AddMachineDialog { engine, name, host, hosts: ssh_hosts(), error: None, _subscriptions: subs }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.name.focus_handle(cx)+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ let machine = NewMachine { name: self.name.read(cx).text().to_string(), host: self.host.read(cx).text().to_string() };+ match self.engine.add_machine(machine) {+ Ok(id) => cx.emit(DialogEvent::MachineAdded(id)),+ Err(e) => {+ self.error = Some(e);+ cx.notify();+ }+ }+ }++ fn pick(&mut self, host: String, name: String, cx: &mut Context<Self>) {+ self.host.update(cx, |h, cx| h.set_text(host, cx));+ if self.name.read(cx).text().trim().is_empty() {+ self.name.update(cx, |n, cx| n.set_text(name, cx));+ }+ }+}++impl Render for AddMachineDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let mut suggestions: Vec<AnyElement> = vec![+ suggestion(&theme, "sugg-local", "This computer", "laptop")+ .on_click(cx.listener(|this, _, _, cx| this.pick("local".into(), crate::config::local_hostname(), cx)))+ .into_any_element(),+ ];+ for (i, h) in self.hosts.iter().take(12).enumerate() {+ let host = h.clone();+ suggestions.push(+ suggestion(&theme, SharedString::from(format!("sugg-{i}")), h.clone(), "terminal")+ .on_click(cx.listener(move |this, _, _, cx| this.pick(host.clone(), host.clone(), cx)))+ .into_any_element(),+ );+ }+ frame(+ &theme,+ "Add a machine",+ Some("OpenRunner reaches machines with your system ssh, keys and ~/.ssh/config. Checks are read-only; nothing is installed until you ask.".into()),+ )+ .child(field(&theme, "Name", self.name.clone(), None))+ .child(field(&theme, "SSH host", self.host.clone(), Some("Key-based login must work without a password prompt.")))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(6.))+ .child(label(&theme, "Suggestions"))+ .child(div().flex().flex_wrap().gap(px(6.)).children(suggestions)),+ )+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("am-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("am-add", "Add machine").style(ButtonStyle::Primary).key_hint("↵").on_click(cx.listener(|this, _, _, cx| this.submit(cx))).into_any_element(),+ ]))+ }+}++fn suggestion(theme: &Theme, id: impl Into<gpui::ElementId>, text: impl Into<SharedString>, icon_name: &'static str) -> gpui::Stateful<gpui::Div> {+ div()+ .id(id)+ .flex()+ .items_center()+ .gap(px(5.))+ .h(px(24.))+ .px(px(8.))+ .rounded(px(5.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.element)+ .cursor_pointer()+ .hover(|st| st.bg(theme.element_hover))+ .text_size(px(12.))+ .font_family(mono_font())+ .text_color(theme.text_muted)+ .child(icon(icon_name, 12., theme.text_placeholder))+ .child(text.into())+}++// ---------------------------------------------------------------------------++pub struct InstallDialog {+ engine: Arc<Engine>,+ machine_id: String,+ scopes: Vec<String>,+ scope: Option<String>,+ count: usize,+ names: Entity<TextInput>,+ labels: Entity<TextInput>,+ mode: ModeChoice,+ image: Entity<TextInput>,+ docker_socket: bool,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for InstallDialog {}++/// How the runner process is kept alive on the machine.+#[derive(Clone, Copy, PartialEq, Eq)]+enum ModeChoice {+ Auto,+ Service,+ Docker,+ Background,+}++impl InstallDialog {+ pub fn new(engine: Arc<Engine>, snapshot: Arc<Snapshot>, machine_id: String, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let settings = engine.settings();+ let mut scopes: Vec<String> = settings.github.orgs.iter().chain(settings.github.repos.iter()).cloned().collect();+ for d in &snapshot.github.detected {+ if !scopes.iter().any(|s| s.eq_ignore_ascii_case(d)) {+ scopes.push(d.clone());+ }+ }+ let suggested = engine.suggest_runner_names(&machine_id, 1).join(", ");+ let names = cx.new(|cx| TextInput::new(cx, "runner-01, runner-02").mono().with_text(suggested));+ let labels = cx.new(|cx| TextInput::new(cx, "gpu, xcode-16 (optional)").mono());+ let image = cx.new(|cx| TextInput::new(cx, "ghcr.io/actions/actions-runner (latest)").mono());+ let on_input = |this: &mut Self, _: &Entity<TextInput>, e: &InputEvent, _: &mut Window, cx: &mut Context<Self>| match e {+ InputEvent::Submit => this.submit(cx),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => {+ this.error = None;+ cx.notify()+ }+ };+ let subs = vec![cx.subscribe_in(&names, window, on_input), cx.subscribe_in(&labels, window, on_input)];+ InstallDialog {+ engine,+ machine_id,+ scope: scopes.first().cloned(),+ scopes,+ count: 1,+ names,+ labels,+ mode: ModeChoice::Auto,+ image,+ docker_socket: false,+ error: None,+ _subscriptions: subs,+ }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.names.focus_handle(cx)+ }++ fn set_count(&mut self, count: usize, cx: &mut Context<Self>) {+ self.count = count.clamp(1, 16);+ let names = self.engine.suggest_runner_names(&self.machine_id, self.count).join(", ");+ self.names.update(cx, |n, cx| n.set_text(names, cx));+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ let Some(scope) = self.scope.clone() else {+ self.error = Some("Choose where to register the runners.".into());+ cx.notify();+ return;+ };+ let split = |s: &str| -> Vec<String> {+ s.split([',', ' ', '\n']).map(str::trim).filter(|x| !x.is_empty()).map(str::to_string).collect()+ };+ let req = InstallRequest {+ machine_id: self.machine_id.clone(),+ scope,+ names: split(self.names.read(cx).text()),+ labels: split(self.labels.read(cx).text()),+ group: None,+ as_service: self.mode != ModeChoice::Background,+ mode: match self.mode {+ ModeChoice::Auto => crate::ops::InstallMode::Auto,+ ModeChoice::Service => crate::ops::InstallMode::Service,+ ModeChoice::Background => crate::ops::InstallMode::Background,+ ModeChoice::Docker => crate::ops::InstallMode::Docker {+ image: Some(self.image.read(cx).text().trim().to_string()).filter(|i| !i.is_empty()),+ docker_socket: self.docker_socket,+ },+ },+ };+ match self.engine.install_runners(req) {+ Ok(op) => cx.emit(DialogEvent::OperationStarted(op)),+ Err(e) => {+ self.error = Some(e);+ cx.notify();+ }+ }+ }+}++impl Render for InstallDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let snapshot = self.engine.current();+ let machine = snapshot.machines.iter().find(|m| m.id == self.machine_id);+ let machine_name = machine.map(|m| m.name.clone()).unwrap_or_else(|| self.machine_id.clone());+ let platform = machine.map(|m| m.platform.clone()).filter(|p| !p.is_empty());+ let linux = platform.as_deref().is_some_and(|p| p.starts_with("linux"));++ let scope_picker: AnyElement = if self.scopes.is_empty() {+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .p(px(10.))+ .rounded(px(6.))+ .bg(theme.warning.opacity(0.1))+ .text_size(px(12.5))+ .child(icon("triangle-alert", 14., theme.warning))+ .child(div().flex_1().child("Runners register with a GitHub organization or repository. Add one in Settings first."))+ .child(Button::new("inst-settings", "Settings").on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::OpenSettings))))+ .into_any_element()+ } else {+ div()+ .flex()+ .flex_wrap()+ .gap(px(6.))+ .children(self.scopes.iter().enumerate().map(|(i, sc)| {+ let selected = self.scope.as_deref() == Some(sc.as_str());+ let value = sc.clone();+ div()+ .id(("inst-scope", i))+ .flex()+ .items_center()+ .gap(px(6.))+ .h(px(26.))+ .px(px(10.))+ .rounded(px(6.))+ .border_1()+ .cursor_pointer()+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.12) } else { theme.element })+ .text_size(px(12.5))+ .font_family(mono_font())+ .child(icon(if sc.contains('/') { "git-branch" } else { "layers" }, 12., if selected { theme.accent } else { theme.text_placeholder }))+ .child(sc.clone())+ .on_click(cx.listener(move |this, _, _, cx| {+ this.scope = Some(value.clone());+ cx.notify()+ }))+ }))+ .into_any_element()+ };++ let count = self.count;+ let stepper = div()+ .flex()+ .items_center()+ .gap(px(4.))+ .child(Button::icon_only("inst-minus", "minus").disabled(count <= 1).on_click(cx.listener(move |this, _, _, cx| this.set_count(count - 1, cx))))+ .child(div().w(px(28.)).flex().justify_center().font_family(mono_font()).child(count.to_string()))+ .child(Button::icon_only("inst-plus", "plus").disabled(count >= 16).on_click(cx.listener(move |this, _, _, cx| this.set_count(count + 1, cx))));++ let mode_picker = self.mode_picker(&theme, machine, linux, cx);++ frame(+ &theme,+ format!("Install runners on {machine_name}"),+ Some(+ match &platform {+ Some(p) => format!("Downloads the latest GitHub Actions runner for {p}, registers it with GitHub and starts it."),+ None => "The machine is checked first to pick the right runner build, then it's downloaded, registered and started.".into(),+ }+ .into(),+ ),+ )+ .child(field(&theme, "Register with", scope_picker, None))+ .child(+ div()+ .flex()+ .gap(px(14.))+ .child(div().flex_none().child(field(&theme, "How many", stepper, None)))+ .child(div().flex_1().child(field(&theme, "Names", self.names.clone(), None))),+ )+ .child(field(&theme, "Extra labels", self.labels.clone(), Some("GitHub adds self-hosted, the OS and the architecture automatically.")))+ .child(field(&theme, "Run as", mode_picker, None))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("inst-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("inst-go", if count == 1 { "Install runner".to_string() } else { format!("Install {count} runners") })+ .style(ButtonStyle::Primary)+ .disabled(self.scope.is_none())+ .on_click(cx.listener(|this, _, _, cx| this.submit(cx)))+ .into_any_element(),+ ]))+ }+}++impl InstallDialog {+ /// Auto / Service / Docker / Background, with what the last check says about the machine.+ fn mode_picker(&self, theme: &Theme, machine: Option<&crate::fleet::model::Machine>, linux: bool, cx: &mut Context<Self>) -> AnyElement {+ let probe = machine.and_then(|m| m.probe.as_ref()).filter(|p| p.ok);+ let docker = probe.and_then(|p| p.docker.as_deref()).map(|v| v.trim().to_string()).filter(|v| !v.is_empty());+ let sudo_ok = probe.and_then(|p| p.sudo.as_deref()).is_some_and(|s| matches!(s, "root" | "passwordless"));+ let service_works = !linux || sudo_ok;+ let auto_pick = if service_works {+ "a service"+ } else if docker.is_some() {+ "Docker"+ } else {+ "a background process"+ };+ let options: [(ModeChoice, &'static str, &'static str, String, bool); 4] = [+ (ModeChoice::Auto, "Auto", "zap", format!("Best fit for this machine: {auto_pick}."), true),+ (+ ModeChoice::Service,+ "Service",+ "server",+ if !linux {+ "Starts at boot (launchd on macOS, a service on Windows).".into()+ } else if sudo_ok {+ "systemd service; starts at boot.".into()+ } else {+ "systemd needs passwordless sudo, which this machine doesn't allow.".into()+ },+ service_works,+ ),+ (+ ModeChoice::Docker,+ "Docker",+ "box",+ match &docker {+ Some(v) => format!("Docker {v}: a container per runner that restarts with Docker. No sudo."),+ None => "Docker wasn't found at the last check.".into(),+ },+ docker.is_some(),+ ),+ (ModeChoice::Background, "Background", "play", "No root needed, but stops when the machine restarts.".into(), true),+ ];+ let card = |(choice, title, icon_name, detail, available): (ModeChoice, &'static str, &'static str, String, bool), cx: &mut Context<Self>| {+ let selected = self.mode == choice;+ div()+ .id(title)+ .flex_1()+ .min_w(px(0.))+ .flex()+ .items_start()+ .gap(px(8.))+ .p(px(9.))+ .rounded(px(8.))+ .border_1()+ .cursor_pointer()+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })+ .when(!available, |d| d.opacity(0.6))+ .child(div().pt(px(1.)).child(icon(icon_name, 13., if selected { theme.accent } else { theme.text_placeholder })))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).child(title))+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(detail)),+ )+ .on_click(cx.listener(move |this, _, _, cx| {+ this.mode = choice;+ cx.notify()+ }))+ .into_any_element()+ };+ let [a, b, c, d] = options;+ let row1 = div().flex().gap(px(8.)).child(card(a, cx)).child(card(b, cx));+ let row2 = div().flex().gap(px(8.)).child(card(c, cx)).child(card(d, cx));+ let socket = self.docker_socket;+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(row1)+ .child(row2)+ .when(self.mode == ModeChoice::Docker, |el| {+ el.child(self.image.clone()).child(checkbox(+ theme,+ "inst-docker-socket",+ socket,+ "Let jobs use the machine's Docker (mounts the socket; root-equivalent)",+ cx.listener(|this, value: &bool, _, cx| {+ this.docker_socket = *value;+ cx.notify()+ }),+ ))+ })+ .into_any_element()+ }+}++// ---------------------------------------------------------------------------++type ConfirmAction = Box<dyn Fn(bool, &Arc<Engine>) -> Result<Option<u64>, String>>;++pub struct ConfirmDialog {+ engine: Arc<Engine>,+ title: String,+ detail: String,+ confirm_label: &'static str,+ option_label: Option<&'static str>,+ option: bool,+ action: ConfirmAction,+ error: Option<String>,+ focus: FocusHandle,+}++impl EventEmitter<DialogEvent> for ConfirmDialog {}++impl ConfirmDialog {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ title: String,+ detail: String,+ confirm_label: &'static str,+ option_label: Option<&'static str>,+ action: impl Fn(bool, &Arc<Engine>) -> Result<Option<u64>, String> + 'static,+ engine: Arc<Engine>,+ _: &mut Window,+ cx: &mut Context<Self>,+ ) -> Self {+ ConfirmDialog {+ engine,+ title,+ detail,+ confirm_label,+ option_label,+ option: false,+ action: Box::new(action),+ error: None,+ focus: cx.focus_handle(),+ }+ }++ fn confirm(&mut self, cx: &mut Context<Self>) {+ match (self.action)(self.option, &self.engine) {+ Ok(Some(op)) => cx.emit(DialogEvent::OperationStarted(op)),+ Ok(None) => cx.emit(DialogEvent::Dismissed),+ Err(e) => {+ self.error = Some(e);+ cx.notify();+ }+ }+ }+}++impl Focusable for ConfirmDialog {+ fn focus_handle(&self, _: &App) -> FocusHandle {+ self.focus.clone()+ }+}++impl Render for ConfirmDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let option = self.option;+ frame(&theme, self.title.clone(), Some(self.detail.clone().into()))+ .track_focus(&self.focus)+ .children(self.option_label.map(|l| {+ checkbox(&theme, "confirm-option", option, l, cx.listener(|this, value: &bool, _, cx| {+ this.option = *value;+ cx.notify()+ }))+ }))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("cf-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("cf-go", self.confirm_label)+ .style(ButtonStyle::Outlined)+ .icon("trash-2")+ .on_click(cx.listener(|this, _, _, cx| this.confirm(cx)))+ .into_any_element(),+ ]))+ }+}++// ---------------------------------------------------------------------------++pub struct NewWorkspaceDialog {+ engine: Arc<Engine>,+ /// None = let OpenRunner pick the least busy machine.+ machine: Option<String>,+ name: Entity<TextInput>,+ repo: Entity<TextInput>,+ git_ref: Entity<TextInput>,+ branch: Entity<TextInput>,+ /// Run inside a fresh Docker container instead of directly on the machine.+ docker: bool,+ image: Entity<TextInput>,+ docker_socket: bool,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for NewWorkspaceDialog {}++/// Common images agents ask for; any image name works.+const IMAGE_PRESETS: &[&str] = &["node:22", "python:3.13", "rust:1", "golang:1.25", DEFAULT_IMAGE];++impl NewWorkspaceDialog {+ pub fn new(engine: Arc<Engine>, machine: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let name = cx.new(|cx| TextInput::new(cx, "api-tests (optional)"));+ let repo = cx.new(|cx| TextInput::new(cx, "acme/api or a git URL (optional)").mono());+ let git_ref = cx.new(|cx| TextInput::new(cx, "main").mono());+ let branch = cx.new(|cx| TextInput::new(cx, "new branch (optional)").mono());+ let image = cx.new(|cx| TextInput::new(cx, DEFAULT_IMAGE).mono());+ let on_input = |_: &mut Self, _: &Entity<TextInput>, e: &InputEvent, _: &mut Window, cx: &mut Context<Self>| match e {+ InputEvent::Submit => cx.emit(DialogEvent::Dismissed),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => cx.notify(),+ };+ let subs = [&name, &repo, &git_ref, &branch, &image].into_iter().map(|i| cx.subscribe_in(i, window, on_input)).collect();+ NewWorkspaceDialog { engine, machine, name, repo, git_ref, branch, docker: false, image, docker_socket: false, _subscriptions: subs }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.repo.focus_handle(cx)+ }++ pub fn set_docker(&mut self, docker: bool, cx: &mut Context<Self>) {+ self.docker = docker;+ cx.notify();+ }++ /// "On the machine" vs "In a Docker container", with the image picker for the latter.+ fn environment_picker(&self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {+ let option = |id: &'static str, docker: bool, icon_name: &'static str, title: &'static str, detail: &'static str, cx: &mut Context<Self>| {+ let selected = self.docker == docker;+ div()+ .id(id)+ .flex_1()+ .min_w(px(0.))+ .flex()+ .items_start()+ .gap(px(10.))+ .p(px(10.))+ .rounded(px(8.))+ .border_1()+ .cursor_pointer()+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })+ .child(div().pt(px(1.)).child(icon(icon_name, 14., if selected { theme.accent } else { theme.text_placeholder })))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).child(title))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)),+ )+ .on_click(cx.listener(move |this, _, _, cx| {+ this.docker = docker;+ cx.notify()+ }))+ };+ let host = option("env-host", false, "server", "On the machine", "Runs as your ssh user with its tools.", cx);+ let docker = option("env-docker", true, "box", "In a Docker container", "A fresh, isolated container per workspace.", cx);+ let socket = self.docker_socket;+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(div().flex().gap(px(8.)).child(host).child(docker))+ .when(self.docker, |d| {+ d.child(self.image.clone())+ .child(div().flex().flex_wrap().gap(px(6.)).children(IMAGE_PRESETS.iter().enumerate().map(|(i, img)| {+ let value = img.to_string();+ div()+ .id(("img-preset", i))+ .h(px(22.))+ .px(px(8.))+ .flex()+ .items_center()+ .rounded(px(5.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.element)+ .cursor_pointer()+ .hover(|st| st.bg(theme.element_hover))+ .font_family(mono_font())+ .text_size(px(11.5))+ .text_color(theme.text_muted)+ .child(*img)+ .on_click(cx.listener(move |this, _, _, cx| this.image.update(cx, |i, cx| i.set_text(value.clone(), cx))))+ })))+ .child(checkbox(theme, "ws-docker-socket", socket, "Share the machine's Docker socket (docker-in-docker)", cx.listener(|this, value: &bool, _, cx| {+ this.docker_socket = *value;+ cx.notify()+ })))+ })+ .into_any_element()+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ let text = |e: &Entity<TextInput>, cx: &Context<Self>| Some(e.read(cx).text().trim().to_string()).filter(|t| !t.is_empty());+ let iso = if self.docker {+ WorkspaceIsolation { isolation: Some("docker".into()), image: text(&self.image, cx), docker_socket: self.docker_socket }+ } else {+ WorkspaceIsolation::default()+ };+ cx.emit(DialogEvent::CreateWorkspace(+ CreateWorkspace {+ machine: self.machine.clone(),+ platform: None,+ name: text(&self.name, cx),+ repo: text(&self.repo, cx),+ git_ref: text(&self.git_ref, cx),+ branch: text(&self.branch, cx),+ owner: Some("app".into()),+ },+ iso,+ ));+ }+}++impl Render for NewWorkspaceDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let snapshot = self.engine.current();+ let choices: Vec<(Option<String>, String, bool)> = std::iter::once((None, "Least busy".to_string(), true))+ .chain(snapshot.machines.iter().filter(|m| m.workspaces_allowed).map(|m| (Some(m.id.clone()), m.name.clone(), m.status == "online")))+ .collect();+ let picker = div().flex().flex_wrap().gap(px(6.)).children(choices.into_iter().enumerate().map(|(i, (id, label, online))| {+ let selected = self.machine == id;+ div()+ .id(("ws-machine", i))+ .flex()+ .items_center()+ .gap(px(6.))+ .h(px(26.))+ .px(px(10.))+ .rounded(px(6.))+ .border_1()+ .cursor_pointer()+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.12) } else { theme.element })+ .text_size(px(12.5))+ .child(if id.is_none() {+ icon("zap", 12., if selected { theme.accent } else { theme.text_placeholder }).into_any_element()+ } else {+ div().size(px(7.)).rounded_full().bg(if online { theme.success } else { theme.text_placeholder }).into_any_element()+ })+ .child(label)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.machine = id.clone();+ cx.notify()+ }))+ }));+ frame(+ &theme,+ "New workspace",+ Some("A folder on one of your machines, optionally a git checkout, for an agent (or you) to work in. It stays until you destroy it.".into()),+ )+ .child(field(&theme, "Machine", picker, None))+ .child(field(&theme, "Environment", self.environment_picker(&theme, cx), None))+ .child(field(&theme, "Repository", self.repo.clone(), Some("Private GitHub repos clone with your gh login if the machine can't.")))+ .child(+ div()+ .flex()+ .gap(px(12.))+ .child(div().flex_1().child(field(&theme, "Check out", self.git_ref.clone(), None)))+ .child(div().flex_1().child(field(&theme, "Branch", self.branch.clone(), None))),+ )+ .child(field(&theme, "Name", self.name.clone(), None))+ .child(footer(vec![+ Button::new("nw-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("nw-create", "Create workspace")+ .style(ButtonStyle::Primary)+ .icon("terminal")+ .on_click(cx.listener(|this, _, _, cx| this.submit(cx)))+ .into_any_element(),+ ]))+ }+}diff --git a/src/ui/format.rs b/src/ui/format.rsnew file mode 100644index 0000000..5a35507--- /dev/null+++ b/src/ui/format.rs@@ -0,0 +1,116 @@+use chrono::{DateTime, Utc};++use crate::fleet::model::{Machine, Snapshot};+use crate::util;++pub fn ago(t: Option<DateTime<Utc>>) -> String {+ match t {+ None => "never".into(),+ Some(t) => {+ let secs = (Utc::now() - t).num_seconds().max(0) as u64;+ if secs < 10 { "just now".into() } else { format!("{} ago", util::short_duration(secs)) }+ }+ }+}++pub fn until(t: DateTime<Utc>) -> String {+ let secs = (t - Utc::now()).num_seconds();+ if secs <= 0 { "now".into() } else { format!("in {}", util::short_duration(secs as u64)) }+}++/// Live elapsed time like "4m 07s", for running jobs.+pub fn elapsed(since: DateTime<Utc>) -> String {+ let secs = (Utc::now() - since).num_seconds().max(0) as u64;+ if secs < 60 {+ format!("{secs}s")+ } else if secs < 3600 {+ format!("{}m {:02}s", secs / 60, secs % 60)+ } else {+ format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60)+ }+}++pub fn bytes(n: u64) -> String {+ util::bytes(n)+}++pub fn uptime(secs: u64) -> String {+ util::uptime(secs)+}++pub fn mem_fraction(m: &Machine) -> Option<f32> {+ let p = m.probe.as_ref().filter(|p| p.ok)?;+ Some((p.mem_used? as f64 / p.mem_total?.max(1) as f64) as f32)+}++pub fn disk_used_fraction(m: &Machine) -> Option<f32> {+ let p = m.probe.as_ref().filter(|p| p.ok)?;+ let total = p.disk_total?.max(1);+ Some(1.0 - (p.disk_free? as f64 / total as f64) as f32)+}++pub fn disk_low(m: &Machine) -> bool {+ m.diagnostics.iter().any(|d| d.code == "low-disk")+}++/// "3/7 working", "2 idle", "1/2 offline", ... for a machine with runners.+pub fn runner_summary(m: &Machine) -> String {+ let s = &m.summary;+ if s.total == 0 {+ return match m.status.as_str() {+ "online" => "connected".into(),+ "offline" => "unreachable".into(),+ _ => "not checked".into(),+ };+ }+ if s.working > 0 {+ format!("{}/{} working", s.working, s.total)+ } else if s.idle == s.total {+ format!("{} idle", s.idle)+ } else if s.offline > 0 {+ format!("{}/{} offline", s.offline, s.total)+ } else if s.unknown == s.total {+ format!("{} unknown", s.unknown)+ } else {+ format!("{} idle", s.idle)+ }+}++/// "No warnings", "2 warnings", "1 unknown", "Unreachable", "Not checked".+pub fn diagnostics_summary(m: &Machine) -> (String, &'static str) {+ if m.checking && m.probe.is_none() {+ return ("Checking…".into(), "muted");+ }+ match m.status.as_str() {+ "offline" => return ("Unreachable".into(), "error"),+ "unchecked" | "manual" => return ("Not checked".into(), "muted"),+ _ => {}+ }+ let warnings = m.diagnostics.iter().filter(|d| matches!(d.level.as_str(), "warning" | "error")).count();+ let unknown = m.diagnostics.iter().filter(|d| d.level == "unknown").count();+ if warnings > 0 {+ (format!("{warnings} warning{}", if warnings == 1 { "" } else { "s" }), "warning")+ } else if unknown > 0 {+ (format!("{unknown} unknown"), "muted")+ } else {+ ("No warnings".into(), "muted")+ }+}++pub fn machine_icon(m: &Machine) -> &'static str {+ let name = m.name.to_ascii_lowercase();+ if m.kind == "other" {+ "hard-drive"+ } else if name.contains("laptop") || name.contains("macbook") || name.contains("book") {+ "laptop"+ } else if m.platform.starts_with("windows") {+ "monitor"+ } else {+ "server"+ }+}++/// The org/repo shown next to the app name.+pub fn scope_label(s: &Snapshot) -> Option<String> {+ s.github.scopes.first().map(|sc| sc.name.clone()).or_else(|| s.github.detected.first().cloned())+}diff --git a/src/ui/input.rs b/src/ui/input.rsnew file mode 100644index 0000000..277accb--- /dev/null+++ b/src/ui/input.rs@@ -0,0 +1,558 @@+//! A single-line text input, adapted from GPUI's input example (GPUI has no+//! built-in text field). Emits `InputEvent`s for changes, Enter and Escape.++use std::ops::Range;++use gpui::{+ App, Bounds, ClipboardItem, Context, CursorStyle, ElementId, ElementInputHandler, Entity,+ EntityInputHandler, EventEmitter, FocusHandle, Focusable, GlobalElementId, KeyBinding, LayoutId,+ MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point, ShapedLine,+ SharedString, Style, TextRun, UTF16Selection, Window, actions, div, fill, point, prelude::*, px,+ relative, size,+};+use unicode_segmentation::UnicodeSegmentation;++use super::theme::{ActiveTheme, mono_font, ui_font};++actions!(+ text_input,+ [Backspace, Delete, Left, Right, SelectLeft, SelectRight, SelectAll, Home, End, Paste, Cut, Copy, Enter, Escape]+);++const CONTEXT: &str = "TextInput";++pub fn bind_keys(cx: &mut App) {+ cx.bind_keys([+ KeyBinding::new("backspace", Backspace, Some(CONTEXT)),+ KeyBinding::new("delete", Delete, Some(CONTEXT)),+ KeyBinding::new("left", Left, Some(CONTEXT)),+ KeyBinding::new("right", Right, Some(CONTEXT)),+ KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),+ KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),+ KeyBinding::new("secondary-a", SelectAll, Some(CONTEXT)),+ KeyBinding::new("secondary-v", Paste, Some(CONTEXT)),+ KeyBinding::new("secondary-c", Copy, Some(CONTEXT)),+ KeyBinding::new("secondary-x", Cut, Some(CONTEXT)),+ KeyBinding::new("home", Home, Some(CONTEXT)),+ KeyBinding::new("end", End, Some(CONTEXT)),+ KeyBinding::new("secondary-left", Home, Some(CONTEXT)),+ KeyBinding::new("secondary-right", End, Some(CONTEXT)),+ KeyBinding::new("enter", Enter, Some(CONTEXT)),+ KeyBinding::new("escape", Escape, Some(CONTEXT)),+ ]);+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum InputEvent {+ Changed,+ Submit,+ Cancel,+}++pub struct TextInput {+ focus_handle: FocusHandle,+ content: SharedString,+ placeholder: SharedString,+ selected_range: Range<usize>,+ selection_reversed: bool,+ marked_range: Option<Range<usize>>,+ last_layout: Option<ShapedLine>,+ last_bounds: Option<Bounds<Pixels>>,+ is_selecting: bool,+ mono: bool,+}++impl EventEmitter<InputEvent> for TextInput {}++impl TextInput {+ pub fn new(cx: &mut Context<Self>, placeholder: impl Into<SharedString>) -> Self {+ TextInput {+ focus_handle: cx.focus_handle(),+ content: SharedString::default(),+ placeholder: placeholder.into(),+ selected_range: 0..0,+ selection_reversed: false,+ marked_range: None,+ last_layout: None,+ last_bounds: None,+ is_selecting: false,+ mono: false,+ }+ }++ pub fn mono(mut self) -> Self {+ self.mono = true;+ self+ }++ pub fn with_text(mut self, text: impl Into<SharedString>) -> Self {+ self.content = text.into();+ self.selected_range = self.content.len()..self.content.len();+ self+ }++ pub fn text(&self) -> &str {+ &self.content+ }++ pub fn set_text(&mut self, text: impl Into<SharedString>, cx: &mut Context<Self>) {+ self.content = text.into();+ self.selected_range = self.content.len()..self.content.len();+ self.marked_range = None;+ cx.emit(InputEvent::Changed);+ cx.notify();+ }++ fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {+ if self.selected_range.is_empty() {+ self.move_to(self.previous_boundary(self.cursor_offset()), cx);+ } else {+ self.move_to(self.selected_range.start, cx)+ }+ }++ fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {+ if self.selected_range.is_empty() {+ self.move_to(self.next_boundary(self.selected_range.end), cx);+ } else {+ self.move_to(self.selected_range.end, cx)+ }+ }++ fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {+ self.select_to(self.previous_boundary(self.cursor_offset()), cx);+ }++ fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {+ self.select_to(self.next_boundary(self.cursor_offset()), cx);+ }++ fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {+ self.move_to(0, cx);+ self.select_to(self.content.len(), cx)+ }++ fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {+ self.move_to(0, cx);+ }++ fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {+ self.move_to(self.content.len(), cx);+ }++ fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {+ if self.selected_range.is_empty() {+ self.select_to(self.previous_boundary(self.cursor_offset()), cx)+ }+ self.replace_text_in_range(None, "", window, cx)+ }++ fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {+ if self.selected_range.is_empty() {+ self.select_to(self.next_boundary(self.cursor_offset()), cx)+ }+ self.replace_text_in_range(None, "", window, cx)+ }++ fn enter(&mut self, _: &Enter, _: &mut Window, cx: &mut Context<Self>) {+ cx.emit(InputEvent::Submit);+ }++ fn escape(&mut self, _: &Escape, _: &mut Window, cx: &mut Context<Self>) {+ cx.emit(InputEvent::Cancel);+ }++ fn on_mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {+ window.focus(&self.focus_handle);+ self.is_selecting = true;+ if event.modifiers.shift {+ self.select_to(self.index_for_mouse_position(event.position), cx);+ } else {+ self.move_to(self.index_for_mouse_position(event.position), cx)+ }+ }++ fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _: &mut Context<Self>) {+ self.is_selecting = false;+ }++ fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {+ if self.is_selecting {+ self.select_to(self.index_for_mouse_position(event.position), cx);+ }+ }++ fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {+ self.replace_text_in_range(None, &text.replace(['\n', '\r'], " "), window, cx);+ }+ }++ fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {+ if !self.selected_range.is_empty() {+ cx.write_to_clipboard(ClipboardItem::new_string(self.content[self.selected_range.clone()].to_string()));+ }+ }++ fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {+ if !self.selected_range.is_empty() {+ cx.write_to_clipboard(ClipboardItem::new_string(self.content[self.selected_range.clone()].to_string()));+ self.replace_text_in_range(None, "", window, cx)+ }+ }++ fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {+ self.selected_range = offset..offset;+ cx.notify()+ }++ fn cursor_offset(&self) -> usize {+ if self.selection_reversed { self.selected_range.start } else { self.selected_range.end }+ }++ fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {+ if self.content.is_empty() {+ return 0;+ }+ let (Some(bounds), Some(line)) = (self.last_bounds.as_ref(), self.last_layout.as_ref()) else {+ return 0;+ };+ if position.y < bounds.top() {+ return 0;+ }+ if position.y > bounds.bottom() {+ return self.content.len();+ }+ line.closest_index_for_x(position.x - bounds.left())+ }++ fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {+ if self.selection_reversed {+ self.selected_range.start = offset+ } else {+ self.selected_range.end = offset+ };+ if self.selected_range.end < self.selected_range.start {+ self.selection_reversed = !self.selection_reversed;+ self.selected_range = self.selected_range.end..self.selected_range.start;+ }+ cx.notify()+ }++ fn offset_from_utf16(&self, offset: usize) -> usize {+ let mut utf8_offset = 0;+ let mut utf16_count = 0;+ for ch in self.content.chars() {+ if utf16_count >= offset {+ break;+ }+ utf16_count += ch.len_utf16();+ utf8_offset += ch.len_utf8();+ }+ utf8_offset+ }++ fn offset_to_utf16(&self, offset: usize) -> usize {+ let mut utf16_offset = 0;+ let mut utf8_count = 0;+ for ch in self.content.chars() {+ if utf8_count >= offset {+ break;+ }+ utf8_count += ch.len_utf8();+ utf16_offset += ch.len_utf16();+ }+ utf16_offset+ }++ fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {+ self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)+ }++ fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {+ self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)+ }++ fn previous_boundary(&self, offset: usize) -> usize {+ self.content.grapheme_indices(true).rev().find_map(|(idx, _)| (idx < offset).then_some(idx)).unwrap_or(0)+ }++ fn next_boundary(&self, offset: usize) -> usize {+ self.content+ .grapheme_indices(true)+ .find_map(|(idx, _)| (idx > offset).then_some(idx))+ .unwrap_or(self.content.len())+ }+}++impl EntityInputHandler for TextInput {+ fn text_for_range(+ &mut self,+ range_utf16: Range<usize>,+ actual_range: &mut Option<Range<usize>>,+ _: &mut Window,+ _: &mut Context<Self>,+ ) -> Option<String> {+ let range = self.range_from_utf16(&range_utf16);+ actual_range.replace(self.range_to_utf16(&range));+ Some(self.content[range].to_string())+ }++ fn selected_text_range(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) -> Option<UTF16Selection> {+ Some(UTF16Selection { range: self.range_to_utf16(&self.selected_range), reversed: self.selection_reversed })+ }++ fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {+ self.marked_range.as_ref().map(|range| self.range_to_utf16(range))+ }++ fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {+ self.marked_range = None;+ }++ fn replace_text_in_range(&mut self, range_utf16: Option<Range<usize>>, new_text: &str, _: &mut Window, cx: &mut Context<Self>) {+ let range = range_utf16+ .as_ref()+ .map(|r| self.range_from_utf16(r))+ .or(self.marked_range.clone())+ .unwrap_or(self.selected_range.clone());+ self.content = (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..]).into();+ self.selected_range = range.start + new_text.len()..range.start + new_text.len();+ self.marked_range.take();+ cx.emit(InputEvent::Changed);+ cx.notify();+ }++ fn replace_and_mark_text_in_range(+ &mut self,+ range_utf16: Option<Range<usize>>,+ new_text: &str,+ new_selected_range_utf16: Option<Range<usize>>,+ _: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let range = range_utf16+ .as_ref()+ .map(|r| self.range_from_utf16(r))+ .or(self.marked_range.clone())+ .unwrap_or(self.selected_range.clone());+ self.content = (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..]).into();+ self.marked_range = (!new_text.is_empty()).then(|| range.start..range.start + new_text.len());+ self.selected_range = new_selected_range_utf16+ .as_ref()+ .map(|r| self.range_from_utf16(r))+ .map(|new_range| new_range.start + range.start..new_range.end + range.end)+ .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());+ cx.emit(InputEvent::Changed);+ cx.notify();+ }++ fn bounds_for_range(&mut self, range_utf16: Range<usize>, bounds: Bounds<Pixels>, _: &mut Window, _: &mut Context<Self>) -> Option<Bounds<Pixels>> {+ let last_layout = self.last_layout.as_ref()?;+ let range = self.range_from_utf16(&range_utf16);+ Some(Bounds::from_corners(+ point(bounds.left() + last_layout.x_for_index(range.start), bounds.top()),+ point(bounds.left() + last_layout.x_for_index(range.end), bounds.bottom()),+ ))+ }++ fn character_index_for_point(&mut self, point: Point<Pixels>, _: &mut Window, _: &mut Context<Self>) -> Option<usize> {+ let line_point = self.last_bounds?.localize(&point)?;+ let last_layout = self.last_layout.as_ref()?;+ let utf8_index = last_layout.index_for_x(point.x - line_point.x)?;+ Some(self.offset_to_utf16(utf8_index))+ }+}++struct TextElement {+ input: Entity<TextInput>,+}++struct PrepaintState {+ line: Option<ShapedLine>,+ cursor: Option<PaintQuad>,+ selection: Option<PaintQuad>,+}++impl IntoElement for TextElement {+ type Element = Self;++ fn into_element(self) -> Self::Element {+ self+ }+}++impl Element for TextElement {+ type RequestLayoutState = ();+ type PrepaintState = PrepaintState;++ fn id(&self) -> Option<ElementId> {+ None+ }++ fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {+ None+ }++ fn request_layout(+ &mut self,+ _: Option<&GlobalElementId>,+ _: Option<&gpui::InspectorElementId>,+ window: &mut Window,+ cx: &mut App,+ ) -> (LayoutId, Self::RequestLayoutState) {+ let mut style = Style::default();+ style.size.width = relative(1.).into();+ style.size.height = window.line_height().into();+ (window.request_layout(style, [], cx), ())+ }++ fn prepaint(+ &mut self,+ _: Option<&GlobalElementId>,+ _: Option<&gpui::InspectorElementId>,+ bounds: Bounds<Pixels>,+ _: &mut Self::RequestLayoutState,+ window: &mut Window,+ cx: &mut App,+ ) -> Self::PrepaintState {+ let theme = cx.theme();+ let input = self.input.read(cx);+ let content = input.content.clone();+ let selected_range = input.selected_range.clone();+ let cursor = input.cursor_offset();+ let style = window.text_style();++ let (display_text, text_color) =+ if content.is_empty() { (input.placeholder.clone(), theme.text_placeholder) } else { (content, style.color) };++ let run = TextRun {+ len: display_text.len(),+ font: style.font(),+ color: text_color,+ background_color: None,+ underline: None,+ strikethrough: None,+ };+ let runs = match input.marked_range.as_ref() {+ Some(marked) if !input.content.is_empty() => vec![+ TextRun { len: marked.start, ..run.clone() },+ TextRun {+ len: marked.end - marked.start,+ underline: Some(gpui::UnderlineStyle { color: Some(run.color), thickness: px(1.0), wavy: false }),+ ..run.clone()+ },+ TextRun { len: display_text.len() - marked.end, ..run },+ ]+ .into_iter()+ .filter(|run| run.len > 0)+ .collect(),+ _ => vec![run],+ };++ let font_size = style.font_size.to_pixels(window.rem_size());+ let line = window.text_system().shape_line(display_text, font_size, &runs, None);++ let cursor_pos = if input.content.is_empty() { px(0.) } else { line.x_for_index(cursor) };+ let (selection, cursor) = if selected_range.is_empty() {+ (+ None,+ Some(fill(+ Bounds::new(point(bounds.left() + cursor_pos, bounds.top() + px(2.)), size(px(1.5), bounds.size.height - px(4.))),+ theme.accent,+ )),+ )+ } else {+ (+ Some(fill(+ Bounds::from_corners(+ point(bounds.left() + line.x_for_index(selected_range.start), bounds.top()),+ point(bounds.left() + line.x_for_index(selected_range.end), bounds.bottom()),+ ),+ theme.selection,+ )),+ None,+ )+ };+ PrepaintState { line: Some(line), cursor, selection }+ }++ fn paint(+ &mut self,+ _: Option<&GlobalElementId>,+ _: Option<&gpui::InspectorElementId>,+ bounds: Bounds<Pixels>,+ _: &mut Self::RequestLayoutState,+ prepaint: &mut Self::PrepaintState,+ window: &mut Window,+ cx: &mut App,+ ) {+ let focus_handle = self.input.read(cx).focus_handle.clone();+ window.handle_input(&focus_handle, ElementInputHandler::new(bounds, self.input.clone()), cx);+ if let Some(selection) = prepaint.selection.take() {+ window.paint_quad(selection)+ }+ let Some(line) = prepaint.line.take() else { return };+ let _ = line.paint(bounds.origin, window.line_height(), window, cx);+ if focus_handle.is_focused(window) {+ if let Some(cursor) = prepaint.cursor.take() {+ window.paint_quad(cursor);+ }+ }+ self.input.update(cx, |input, _| {+ input.last_layout = Some(line);+ input.last_bounds = Some(bounds);+ });+ }+}++impl Render for TextInput {+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let focused = self.focus_handle.is_focused(window);+ div()+ .flex()+ .items_center()+ .key_context(CONTEXT)+ .track_focus(&self.focus_handle(cx))+ .cursor(CursorStyle::IBeam)+ .on_action(cx.listener(Self::backspace))+ .on_action(cx.listener(Self::delete))+ .on_action(cx.listener(Self::left))+ .on_action(cx.listener(Self::right))+ .on_action(cx.listener(Self::select_left))+ .on_action(cx.listener(Self::select_right))+ .on_action(cx.listener(Self::select_all))+ .on_action(cx.listener(Self::home))+ .on_action(cx.listener(Self::end))+ .on_action(cx.listener(Self::paste))+ .on_action(cx.listener(Self::cut))+ .on_action(cx.listener(Self::copy))+ .on_action(cx.listener(Self::enter))+ .on_action(cx.listener(Self::escape))+ .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))+ .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))+ .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))+ .on_mouse_move(cx.listener(Self::on_mouse_move))+ .w_full()+ .min_w(px(0.))+ .h(px(28.))+ .px(px(8.))+ .rounded(px(6.))+ .border_1()+ .border_color(if focused { theme.border_focused } else { theme.border_variant })+ .bg(theme.canvas)+ .text_color(theme.text)+ .font_family(if self.mono { mono_font() } else { ui_font() })+ .text_size(px(13.))+ .line_height(px(18.))+ .overflow_hidden()+ .child(TextElement { input: cx.entity() })+ }+}++impl Focusable for TextInput {+ fn focus_handle(&self, _: &App) -> FocusHandle {+ self.focus_handle.clone()+ }+}diff --git a/src/ui/kit.rs b/src/ui/kit.rsnew file mode 100644index 0000000..57dda9c--- /dev/null+++ b/src/ui/kit.rs@@ -0,0 +1,364 @@+//! Small building blocks in Zed's visual language: flat surfaces, hairline+//! borders, ghost buttons, monospace numbers.++use std::time::Duration;++use gpui::{+ Animation, AnimationExt, AnyView, App, ClickEvent, Div, ElementId, FontWeight, Hsla, IntoElement,+ ParentElement, RenderOnce, SharedString, Styled, Svg, Transformation, Window, div, percentage, prelude::*, px,+ svg,+};++use super::theme::{ActiveTheme, mono_font, Theme};++pub fn icon(name: &str, size: f32, color: Hsla) -> Svg {+ svg().path(SharedString::from(format!("icons/{name}.svg"))).size(px(size)).flex_none().text_color(color)+}++pub fn spinner(id: impl Into<ElementId>, size: f32, color: Hsla) -> impl IntoElement {+ icon("loader-circle", size, color).with_animation(+ id,+ Animation::new(Duration::from_millis(900)).repeat(),+ |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),+ )+}++pub fn mono(text: impl Into<SharedString>) -> Div {+ div().font_family(mono_font()).child(text.into())+}++pub fn dot(color: Hsla, size: f32) -> Div {+ div().flex_none().size(px(size)).rounded_full().bg(color)+}++/// A runner as a small square: filled when connected, dashed outline when not.+pub fn runner_glyph(theme: &Theme, state: &str, size: f32) -> Div {+ let base = div().flex_none().size(px(size)).rounded(px(2.5));+ match state {+ "working" | "idle" => base.bg(theme.state(state)),+ _ => base.border_1().border_dashed().border_color(theme.text_placeholder),+ }+}++pub fn pill(text: impl Into<SharedString>, color: Hsla) -> Div {+ div()+ .flex_none()+ .px(px(6.))+ .h(px(18.))+ .flex()+ .items_center()+ .rounded(px(4.))+ .bg(color.opacity(0.14))+ .text_color(color)+ .text_size(px(11.))+ .font_weight(FontWeight::MEDIUM)+ .child(text.into())+}++pub fn chip(theme: &Theme, text: impl Into<SharedString>) -> Div {+ div()+ .flex_none()+ .px(px(5.))+ .h(px(18.))+ .flex()+ .items_center()+ .rounded(px(4.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.element)+ .text_color(theme.text_muted)+ .text_size(px(11.))+ .font_family(mono_font())+ .child(text.into())+}++/// Shortcut labels are written Mac-style ("⇧⌘R"); elsewhere they read "Ctrl+Shift+R".+pub fn keys(text: &str) -> String {+ if cfg!(target_os = "macos") {+ text.to_string()+ } else {+ text.replace("⇧⌘", "Ctrl+Shift+").replace('⌘', "Ctrl+")+ }+}++pub fn kbd(theme: &Theme, text: impl Into<SharedString>) -> Div {+ div()+ .flex_none()+ .px(px(4.))+ .h(px(16.))+ .flex()+ .items_center()+ .rounded(px(3.))+ .border_1()+ .border_color(theme.border_variant)+ .text_color(theme.text_placeholder)+ .text_size(px(10.5))+ .font_family(mono_font())+ .child(keys(&text.into()))+}++/// A thin horizontal meter. `fraction` is clamped to 0..=1.+pub fn meter(theme: &Theme, fraction: f32, color: Hsla) -> Div {+ let f = fraction.clamp(0.0, 1.0);+ div()+ .w_full()+ .h(px(3.))+ .rounded_full()+ .bg(theme.track)+ .child(div().h_full().rounded_full().bg(color).w(gpui::relative(f.max(if f > 0.0 { 0.02 } else { 0.0 }))))+}++/// A bordered surface, the basic container for page sections.+pub fn card(theme: &Theme) -> Div {+ div().flex().flex_col().rounded(px(8.)).border_1().border_color(theme.border_variant).bg(theme.surface)+}++pub fn section_title(theme: &Theme, title: impl Into<SharedString>, count: Option<usize>) -> Div {+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .text_size(px(13.))+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(theme.text)+ .child(title.into())+ .children(count.map(|n| div().font_family(mono_font()).text_color(theme.text_placeholder).font_weight(FontWeight::NORMAL).child(n.to_string())))+}++pub fn label(theme: &Theme, text: impl Into<SharedString>) -> Div {+ div().text_size(px(11.)).text_color(theme.text_placeholder).child(text.into())+}++pub fn empty_state(theme: &Theme, icon_name: &str, text: impl Into<SharedString>) -> Div {+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .px(px(12.))+ .py(px(14.))+ .text_size(px(12.5))+ .text_color(theme.text_placeholder)+ .child(icon(icon_name, 14., theme.text_placeholder))+ .child(text.into())+}++/// A two-column key/value line for detail panes.+pub fn kv(theme: &Theme, key: impl Into<SharedString>, value: impl IntoElement) -> Div {+ div()+ .flex()+ .items_start()+ .gap(px(12.))+ .py(px(5.))+ .text_size(px(12.5))+ .child(div().w(px(112.)).flex_none().text_color(theme.text_placeholder).child(key.into()))+ .child(div().flex_1().min_w(px(0.)).text_color(theme.text).child(value))+}++// ---------------------------------------------------------------------------+// Buttons++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum ButtonStyle {+ /// Filled with the accent color.+ Primary,+ /// Bordered element background.+ Outlined,+ /// No background until hovered.+ Ghost,+ /// Ghost, tinted with the error color.+ Danger,+}++type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;++#[derive(IntoElement)]+pub struct Button {+ id: ElementId,+ label: Option<SharedString>,+ icon: Option<&'static str>,+ style: ButtonStyle,+ disabled: bool,+ loading: bool,+ key_hint: Option<SharedString>,+ tooltip: Option<SharedString>,+ on_click: Option<ClickHandler>,+}++impl Button {+ pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {+ Button {+ id: id.into(),+ label: Some(label.into()),+ icon: None,+ style: ButtonStyle::Outlined,+ disabled: false,+ loading: false,+ key_hint: None,+ tooltip: None,+ on_click: None,+ }+ }++ pub fn icon_only(id: impl Into<ElementId>, icon: &'static str) -> Self {+ Button { label: None, icon: Some(icon), style: ButtonStyle::Ghost, ..Button::new(id, "") }+ }++ pub fn icon(mut self, icon: &'static str) -> Self {+ self.icon = Some(icon);+ self+ }++ pub fn style(mut self, style: ButtonStyle) -> Self {+ self.style = style;+ self+ }++ pub fn disabled(mut self, disabled: bool) -> Self {+ self.disabled = disabled;+ self+ }++ pub fn loading(mut self, loading: bool) -> Self {+ self.loading = loading;+ self+ }++ pub fn key_hint(mut self, hint: impl Into<SharedString>) -> Self {+ self.key_hint = Some(keys(&hint.into()).into());+ self+ }++ pub fn tooltip(mut self, text: impl Into<SharedString>) -> Self {+ self.tooltip = Some(text.into());+ self+ }++ pub fn on_click(mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {+ self.on_click = Some(Box::new(handler));+ self+ }+}++impl RenderOnce for Button {+ fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {+ let theme = cx.theme();+ let icon_only = self.label.is_none();+ let (bg, hover, fg, border) = match self.style {+ ButtonStyle::Primary => (theme.accent, theme.accent.opacity(0.85), theme.accent_text, None),+ ButtonStyle::Outlined => (theme.element, theme.element_hover, theme.text, Some(theme.border_variant)),+ ButtonStyle::Ghost => (gpui::transparent_black(), theme.ghost_hover, theme.text_muted, None),+ ButtonStyle::Danger => (gpui::transparent_black(), theme.error.opacity(0.14), theme.error, None),+ };+ let disabled = self.disabled || self.loading;+ let mut el = div()+ .id(self.id.clone())+ .flex()+ .flex_none()+ .items_center()+ .justify_center()+ .gap(px(5.))+ .h(px(26.))+ .when(icon_only, |d| d.w(px(26.)))+ .when(!icon_only, |d| d.px(px(9.)))+ .rounded(px(6.))+ .bg(bg)+ .text_color(fg)+ .text_size(px(12.5))+ .font_weight(FontWeight::MEDIUM)+ .when_some(border, |d, b| d.border_1().border_color(b))+ .when(disabled, |d| d.opacity(0.5))+ .when(!disabled, |d| d.cursor_pointer().hover(move |s| s.bg(hover)));+ if self.loading {+ el = el.child(spinner(ElementId::Name(format!("{}-spin", self.id).into()), 13., fg));+ } else if let Some(i) = self.icon {+ el = el.child(icon(i, if icon_only { 15. } else { 13. }, fg));+ }+ if let Some(label) = self.label {+ el = el.child(label);+ }+ if let Some(hint) = self.key_hint {+ el = el.child(+ div()+ .text_size(px(10.5))+ .font_family(mono_font())+ .text_color(if self.style == ButtonStyle::Primary { fg.opacity(0.75) } else { theme.text_placeholder })+ .child(hint),+ );+ }+ if let Some(tip) = self.tooltip {+ el = el.tooltip(move |window, cx| Tooltip::view(tip.clone(), window, cx));+ }+ if let (Some(handler), false) = (self.on_click, disabled) {+ el = el.on_click(move |e, w, cx| {+ cx.stop_propagation();+ handler(e, w, cx)+ });+ }+ el+ }+}++pub struct Tooltip {+ text: SharedString,+}++impl Tooltip {+ pub fn view(text: SharedString, _: &mut Window, cx: &mut App) -> AnyView {+ let text = keys(&text).into();+ cx.new(|_| Tooltip { text }).into()+ }+}++impl Render for Tooltip {+ fn render(&mut self, _: &mut Window, cx: &mut gpui::Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ div()+ .pl(px(8.))+ .pt(px(10.))+ .child(+ div()+ .px(px(8.))+ .py(px(4.))+ .rounded(px(6.))+ .bg(theme.elevated)+ .border_1()+ .border_color(theme.border)+ .shadow_md()+ .text_size(px(12.))+ .text_color(theme.text)+ .child(self.text.clone()),+ )+ }+}++/// A checkbox row; `on_toggle` receives the new value.+pub fn checkbox(+ theme: &Theme,+ id: impl Into<ElementId>,+ checked: bool,+ text: impl Into<SharedString>,+ on_toggle: impl Fn(&bool, &mut Window, &mut App) + 'static,+) -> impl IntoElement {+ div()+ .id(id)+ .flex()+ .items_center()+ .gap(px(8.))+ .cursor_pointer()+ .text_size(px(12.5))+ .text_color(theme.text)+ .child(+ div()+ .size(px(15.))+ .flex()+ .items_center()+ .justify_center()+ .rounded(px(4.))+ .border_1()+ .border_color(if checked { theme.accent } else { theme.border })+ .bg(if checked { theme.accent } else { theme.canvas })+ .when(checked, |d| d.child(icon("check", 11., theme.accent_text))),+ )+ .child(text.into())+ .on_click(move |_, w, cx| on_toggle(&!checked, w, cx))+}diff --git a/src/ui/mod.rs b/src/ui/mod.rsnew file mode 100644index 0000000..3af2767--- /dev/null+++ b/src/ui/mod.rs@@ -0,0 +1,85 @@+//! The native window, built with GPUI (Zed's UI framework).++mod activity;+mod assets;+mod detail;+mod dialogs;+mod format;+mod input;+mod kit;+mod overview;+mod settings;+mod theme;+mod themes;+mod workspaces;+mod root;++use std::sync::Arc;++use gpui::{App, Application, Bounds, Focusable, TitlebarOptions, WindowBounds, WindowOptions, point, prelude::*, px, size};++use crate::fleet::Engine;+use theme::Appearance;+use root::{Quit, Root};++pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {+ Application::new().with_assets(assets::Assets).run(move |cx: &mut App| {+ assets::load_fonts(cx);+ assets::set_dock_icon();+ // UI preferences live next to the inventory; demo mode keeps them in memory.+ let prefs_path = (!engine.is_demo()).then(|| engine.paths().dir.join("ui.json"));+ let appearance = Appearance::load(prefs_path);+ cx.set_global(appearance.resolve(cx.window_appearance()));+ cx.set_global(appearance);+ input::bind_keys(cx);+ root::bind_keys(cx);+ cx.on_action(|_: &Quit, cx| cx.quit());+ cx.set_menus(root::menus());++ // `--view size:960x640` (screenshots and layout checks) overrides the default size.+ let (w, h) = initial_view+ .as_deref()+ .and_then(|v| v.split(',').find_map(|p| p.trim().strip_prefix("size:")))+ .and_then(|s| s.split_once('x'))+ .and_then(|(w, h)| Some((w.parse::<f32>().ok()?, h.parse::<f32>().ok()?)))+ .unwrap_or((1380., 880.));+ let bounds = Bounds::centered(None, size(px(w), px(h)), cx);+ let titlebar = if cfg!(target_os = "macos") {+ TitlebarOptions { title: Some("OpenRunner".into()), appears_transparent: true, traffic_light_position: Some(point(px(13.), px(12.))) }+ } else {+ TitlebarOptions { title: Some("OpenRunner".into()), appears_transparent: false, traffic_light_position: None }+ };+ let window = cx.open_window(+ WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(bounds)),+ titlebar: Some(titlebar),+ window_min_size: Some(size(px(960.), px(600.))),+ app_id: Some("openrunner".into()),+ ..Default::default()+ },+ |window, cx| {+ theme::apply(window, cx);+ let view = cx.new(|cx| Root::new(engine.clone(), window, cx));+ window.focus(&view.focus_handle(cx));+ if let Some(v) = &initial_view {+ // Comma-separated, e.g. "theme:gruvbox-light,machine:mac-studio".+ view.update(cx, |ws, cx| v.split(',').for_each(|v| ws.open_view(v.trim(), window, cx)));+ }+ view+ },+ );+ if let Err(e) = window {+ tracing::error!("couldn't open a window: {e:#}");+ cx.quit();+ return;+ }+ // Closing the window quits, like a single-window utility should.+ cx.on_window_closed(|cx| {+ if cx.windows().is_empty() {+ cx.quit();+ }+ })+ .detach();+ cx.activate(true);+ });+}diff --git a/src/ui/overview.rs b/src/ui/overview.rsnew file mode 100644index 0000000..2081cd2--- /dev/null+++ b/src/ui/overview.rs@@ -0,0 +1,668 @@+//! The overview (fleet pulse, stats, attention, machine cards) and the jobs page.++use gpui::{AnyElement, Context, Div, FontWeight, Hsla, ScrollHandle, SharedString, Stateful, Window, div, prelude::*, px, relative};++use super::format;+use super::kit::{self, Button, ButtonStyle, card, chip, icon, meter, section_title};+use super::theme::{ActiveTheme, mono_font, Theme};+use super::root::{Route, SIDEBAR_WIDTH, Root};+use crate::fleet::model::{Job, Machine, Snapshot};++const CARD_MIN_WIDTH: f32 = 290.;+const GAP: f32 = 14.;+const PAGE_PADDING: f32 = 28.;++/// A scrollable page body with consistent padding.+pub(super) fn page(id: &'static str, scroll: &ScrollHandle) -> Stateful<Div> {+ div()+ .id(id)+ .size_full()+ .overflow_y_scroll()+ .track_scroll(scroll)+ .px(px(PAGE_PADDING))+ .pt(px(22.))+ .pb(px(40.))+ .flex()+ .flex_col()+ .gap(px(26.))+}++impl Root {+ pub(super) fn render_overview(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let content_width = f32::from(window.viewport_size().width) - SIDEBAR_WIDTH - PAGE_PADDING * 2.;++ let mut body = page("overview-page", &self.page_scroll).child(self.pulse_card(&theme, &s)).child(stat_tiles(&theme, &s));++ if let Some(err) = &s.inventory.error {+ body = body.child(callout(&theme, "error", "fleet.toml has an error", err.clone(), None));+ }+ if !s.attention.is_empty() {+ body = body.child(self.render_attention(&theme, &s, cx));+ }+ // Side by side when there's room, stacked otherwise.+ let wide = content_width >= 1000.;+ body.child(self.render_machine_grid(&theme, &s, content_width, cx)).child(+ div()+ .flex()+ .when(!wide, |d| d.flex_col())+ .gap(px(if wide { GAP } else { 26. }))+ .child(div().flex_1().min_w(px(0.)).child(self.render_running(&theme, &s, cx)))+ .child(div().flex_1().min_w(px(0.)).child(self.render_queued(&theme, &s, "ov-q"))),+ )+ }++ /// Fleet utilization (busy / online runners) over the last few minutes.+ fn pulse_card(&self, theme: &Theme, s: &Snapshot) -> impl IntoElement {+ let c = &s.counts;+ let online = c.working + c.idle;+ let pct = if online == 0 { 0.0 } else { c.working as f32 / online as f32 };+ let samples: Vec<_> = self.pulse.iter().copied().collect();+ let slots = 64usize;+ let pad = slots.saturating_sub(samples.len());+ let bars: Vec<AnyElement> = (0..slots)+ .map(|i| {+ let sample = (i >= pad).then(|| samples[i - pad]);+ let frac = sample.map(|p| if p.online == 0 { 0.0 } else { p.working as f32 / p.online as f32 }).unwrap_or(0.0);+ let last = i + 1 == slots;+ div()+ .flex_1()+ .h_full()+ .flex()+ .flex_col()+ .justify_end()+ .when_some(sample, |d, _| {+ d.child(+ div()+ .w_full()+ .rounded(px(2.))+ .h(relative(frac.max(0.04)))+ .bg(if last { theme.accent } else { theme.accent.opacity(0.45) }),+ )+ })+ .when(sample.is_none(), |d| d.child(div().w_full().h(px(2.)).rounded(px(1.)).bg(theme.track)))+ .into_any_element()+ })+ .collect();+ let compared = if s.check.running {+ "Checking machines now…".to_string()+ } else if s.check.finished_at.is_some() {+ format!("Machines compared with {} {}", s.inventory.path, format::ago(s.check.finished_at))+ } else {+ format!("Machines not checked yet · {}", s.inventory.path)+ };+ card(theme)+ .flex_row()+ .gap(px(24.))+ .p(px(20.))+ .child(+ div()+ .flex()+ .flex_col()+ .w(px(250.))+ .flex_none()+ .gap(px(6.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(icon("gauge", 13., theme.text_accent))+ .child("Fleet pulse"),+ )+ .child(+ div()+ .flex()+ .items_end()+ .gap(px(4.))+ .child(+ div()+ .font_family(mono_font())+ .text_size(px(40.))+ .line_height(px(44.))+ .font_weight(FontWeight::MEDIUM)+ .child(format!("{:.0}", pct * 100.)),+ )+ .child(div().pb(px(6.)).font_family(mono_font()).text_size(px(18.)).text_color(theme.text_muted).child("%")),+ )+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(format!("{} of {} online runners busy", c.working, online)))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(compared)),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(8.))+ .child(div().flex().items_end().gap(px(3.)).h(px(84.)).children(bars))+ .child(+ div()+ .flex()+ .justify_between()+ .text_size(px(11.))+ .text_color(theme.text_placeholder)+ .child("utilization, last few minutes")+ .child("now"),+ ),+ )+ }++ fn render_attention(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {+ let items: Vec<AnyElement> = s+ .attention+ .iter()+ .map(|a| {+ let button = a.action.clone().map(|action| {+ Button::new(SharedString::from(format!("att-{}", a.id)), action.label.clone())+ .on_click(cx.listener(move |this, _, window, cx| this.run_attention_action(&action, window, cx)))+ .into_any_element()+ });+ callout(theme, &a.level, a.title.clone(), a.detail.clone(), button).into_any_element()+ })+ .collect();+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Needs attention", Some(s.attention.len())))+ .child(div().flex().flex_col().gap(px(8.)).children(items))+ }++ fn render_machine_grid(&self, theme: &Theme, s: &Snapshot, width: f32, cx: &mut Context<Self>) -> impl IntoElement {+ let mut machines: Vec<&Machine> = s.machines.iter().filter(|m| m.kind == "runner").collect();+ machines.extend(s.machines.iter().filter(|m| m.kind == "other"));+ let cols = (((width + GAP) / (CARD_MIN_WIDTH + GAP)).floor() as usize).clamp(1, 4);+ let card_width = ((width - GAP * (cols as f32 - 1.)) / cols as f32).floor();+ // Explicit rows rather than flex-wrap, so the section's height is always right.+ let cards: Vec<AnyElement> = machines.iter().map(|m| self.machine_card(theme, s, m, card_width, cx)).collect();+ let mut rows: Vec<AnyElement> = Vec::new();+ let mut iter = cards.into_iter().peekable();+ while iter.peek().is_some() {+ let row: Vec<AnyElement> = iter.by_ref().take(cols).collect();+ rows.push(div().flex().gap(px(GAP)).children(row).into_any_element());+ }++ let legend = div()+ .flex()+ .items_center()+ .gap(px(12.))+ .text_size(px(11.5))+ .text_color(theme.text_muted)+ .child(div().flex().items_center().gap(px(5.)).child(kit::runner_glyph(theme, "working", 8.)).child("Working"))+ .child(div().flex().items_center().gap(px(5.)).child(kit::runner_glyph(theme, "idle", 8.)).child("Idle"))+ .child(div().flex().items_center().gap(px(5.)).child(kit::runner_glyph(theme, "offline", 8.)).child("Offline"));++ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(+ div()+ .flex()+ .items_center()+ .justify_between()+ .child(section_title(theme, "Machines", Some(s.machines.len())))+ .child(+ div().flex().items_center().gap(px(14.)).child(legend).child(+ Button::new("ov-add-machine", "Add machine")+ .icon("plus")+ .on_click(cx.listener(|this, _, window, cx| this.show_add_machine(window, cx))),+ ),+ ),+ )+ .child(div().flex().flex_col().gap(px(GAP)).children(rows))+ .when(machines.is_empty(), |d| {+ d.child(card(theme).w_full().child(kit::empty_state(theme, "server", "No machines yet. Add the first one to start watching its runners.")))+ })+ }++ fn machine_card(&self, theme: &Theme, s: &Snapshot, m: &Machine, width: f32, cx: &mut Context<Self>) -> AnyElement {+ let id = m.id.clone();+ let p = m.probe.as_ref().filter(|p| p.ok);+ let (diag, tone) = format::diagnostics_summary(m);+ let diag_color = match tone {+ "error" => theme.error,+ "warning" => theme.warning,+ _ => theme.text_placeholder,+ };++ let body: AnyElement = match p {+ Some(p) => {+ let cpu = p.cpu_pct.map(|v| v as f32 / 100.);+ let mem = format::mem_fraction(m);+ let disk = format::disk_used_fraction(m);+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(meter_row(theme, "CPU", cpu.map(|f| format!("{:.0}%", f * 100.)), cpu, theme.accent))+ .child(meter_row(theme, "Memory", mem.map(|f| format!("{:.0}%", f * 100.)), mem, theme.accent))+ .child(meter_row(+ theme,+ "Disk",+ p.disk_free.map(|f| format!("{} free", format::bytes(f))),+ disk,+ if format::disk_low(m) { theme.error } else { theme.accent },+ ))+ .into_any_element()+ }+ None => {+ let text = match m.status.as_str() {+ "offline" => m.probe.as_ref().and_then(|p| p.error.clone()).unwrap_or_else(|| "Unreachable".into()),+ "manual" => "No host configured, so it isn't checked.".into(),+ _ if m.checking => "Checking…".into(),+ _ => "Not checked yet.".into(),+ };+ div()+ .h(px(70.))+ .flex()+ .items_center()+ .text_size(px(12.))+ .text_color(if m.status == "offline" { theme.error } else { theme.text_placeholder })+ .child(div().line_clamp(3).child(text))+ .into_any_element()+ }+ };++ div()+ .id(SharedString::from(format!("mcard-{}", m.id)))+ .w(px(width))+ .flex()+ .flex_col()+ .gap(px(14.))+ .p(px(16.))+ .rounded(px(12.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .cursor_pointer()+ .hover(|st| st.border_color(theme.accent.opacity(0.55)))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(+ div()+ .size(px(32.))+ .flex_none()+ .rounded(px(8.))+ .bg(theme.element)+ .flex()+ .items_center()+ .justify_center()+ .child(icon(format::machine_icon(m), 16., theme.text_muted)),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().truncate().text_size(px(14.)).font_weight(FontWeight::MEDIUM).child(m.name.clone()))+ .child(div().truncate().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(+ if m.platform.is_empty() { m.host.clone() } else { m.platform.clone() },+ )),+ )+ .child(if m.checking {+ kit::spinner(SharedString::from(format!("mcard-spin-{}", m.id)), 12., theme.text_muted).into_any_element()+ } else {+ kit::pill(status_word(m), theme.machine_status(&m.status)).into_any_element()+ }),+ )+ .when(m.kind == "runner", |d| {+ d.child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(div().flex().flex_wrap().gap(px(3.)).children(+ m.runner_ids.iter().filter_map(|rid| s.runners.iter().find(|r| &r.id == rid)).map(|r| kit::runner_glyph(theme, &r.state, 11.)),+ ))+ .child(div().flex_1())+ .child(div().font_family(mono_font()).text_size(px(11.5)).text_color(theme.text_muted).child(format::runner_summary(m))),+ )+ })+ .child(body)+ .child(+ div()+ .flex()+ .items_center()+ .justify_between()+ .pt(px(10.))+ .border_t_1()+ .border_color(theme.border_variant)+ .text_size(px(11.5))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(5.))+ .text_color(theme.text_placeholder)+ .child(icon("clock", 12., theme.text_placeholder))+ .child(p.and_then(|p| p.uptime_sec).map(|u| format!("up {}", format::uptime(u))).unwrap_or_else(|| "—".into())),+ )+ .child(div().text_color(diag_color).child(diag)),+ )+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(id.clone()), window, cx)))+ .into_any_element()+ }++ fn render_running(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {+ let working: Vec<_> = s.runners.iter().filter(|r| r.state == "working").collect();+ let rows: Vec<AnyElement> = working+ .iter()+ .enumerate()+ .map(|(i, r)| {+ let job = r.job_id.and_then(|id| s.jobs.running.iter().find(|j| j.id == id));+ let id = r.id.clone();+ div()+ .id(SharedString::from(format!("run-{}", r.id)))+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(14.))+ .py(px(9.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(div().flex_none().w(px(3.)).h(px(26.)).rounded_full().bg(theme.accent))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().truncate().text_size(px(13.)).child(job.map(|j| j.name.clone()).unwrap_or_else(|| "Running a job".into())))+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(+ "{} · {}",+ r.name,+ job.map(|j| j.repo.clone()).unwrap_or_else(|| "job details need GitHub".into())+ ))),+ )+ .children(+ job.and_then(|j| j.started_at)+ .map(|t| div().flex_none().font_family(mono_font()).text_size(px(12.)).text_color(theme.text_muted).child(format::elapsed(t))),+ )+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Runner(id.clone()), window, cx)))+ .into_any_element()+ })+ .collect();+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Working now", Some(working.len())))+ .child(card(theme).when(rows.is_empty(), |d| d.child(kit::empty_state(theme, "circle", "No runner is working right now."))).children(rows))+ }++ pub(super) fn render_queued(&self, theme: &Theme, s: &Snapshot, prefix: &str) -> impl IntoElement {+ let rows: Vec<AnyElement> = s.jobs.queued.iter().enumerate().map(|(i, j)| queued_row(theme, j, i, prefix)).collect();+ let empty = if !s.github.configured && !s.demo {+ kit::empty_state(theme, "inbox", "Waiting for job data from GitHub.")+ } else {+ kit::empty_state(theme, "inbox", "No queued self-hosted jobs.")+ };+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Queued", Some(s.jobs.queued.len())))+ .child(card(theme).when(rows.is_empty(), |d| d.child(empty)).children(rows))+ }++ pub(super) fn render_jobs(&mut self, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let running: Vec<AnyElement> = s.jobs.running.iter().enumerate().map(|(i, j)| self.running_job_row(&theme, j, i, cx)).collect();+ let scanned = if s.github.scanned_repos.is_empty() {+ "No repositories scanned yet.".to_string()+ } else {+ format!("Scanning {} repos: {}", s.github.scanned_repos.len(), s.github.scanned_repos.join(", "))+ };+ page("jobs-page", &self.page_scroll)+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(scanned))+ .when(!s.github.configured && !s.demo, |d| {+ d.child(callout(+ &theme,+ "warning",+ "Jobs come from GitHub",+ "Add your organization or repositories in Settings to see what's queued and running.".into(),+ Some(+ Button::new("jobs-settings", "Open settings")+ .style(ButtonStyle::Primary)+ .on_click(cx.listener(|this, _, window, cx| this.navigate(Route::Settings, window, cx)))+ .into_any_element(),+ ),+ ))+ })+ .child(self.render_queued(&theme, &s, "jobs-q"))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Running", Some(s.jobs.running.len())))+ .child(card(&theme).when(running.is_empty(), |d| d.child(kit::empty_state(&theme, "circle", "Nothing is running."))).children(running)),+ )+ }++ fn running_job_row(&self, theme: &Theme, j: &Job, i: usize, cx: &mut Context<Self>) -> AnyElement {+ let url = j.url.clone();+ let runner = j.runner_id.clone();+ div()+ .id(("running-job", i))+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(14.))+ .py(px(10.))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(div().flex_none().w(px(3.)).h(px(26.)).rounded_full().bg(theme.accent))+ .child(job_title(theme, j))+ .child(+ div()+ .id(("running-job-runner", i))+ .w(px(150.))+ .flex_none()+ .truncate()+ .font_family(mono_font())+ .text_size(px(12.))+ .text_color(theme.text_accent)+ .when(runner.is_some(), |d| d.cursor_pointer())+ .child(j.runner_name.clone().unwrap_or_else(|| "—".into()))+ .on_click(cx.listener(move |this, _, window, cx| {+ if let Some(r) = &runner {+ this.navigate(Route::Runner(r.clone()), window, cx)+ }+ })),+ )+ .child(+ div()+ .w(px(80.))+ .flex_none()+ .font_family(mono_font())+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(format::elapsed(j.started_at.unwrap_or(j.created_at))),+ )+ .child(Button::icon_only(("running-job-open", i), "external-link").tooltip("Open on GitHub").on_click(move |_, _, cx| cx.open_url(&url)))+ .into_any_element()+ }+}++/// A message with a tinted background: attention items, warnings, errors.+pub(super) fn callout(theme: &Theme, level: &str, title: impl Into<SharedString>, detail: String, action: Option<AnyElement>) -> impl IntoElement {+ let color = theme.level(level);+ let icon_name = match level {+ "error" => "circle-x",+ "warning" => "triangle-alert",+ _ => "info",+ };+ div()+ .flex()+ .items_center()+ .gap(px(12.))+ .pl(px(12.))+ .pr(px(12.))+ .py(px(10.))+ .rounded(px(10.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .child(+ div()+ .flex_none()+ .size(px(28.))+ .rounded(px(7.))+ .bg(color.opacity(0.16))+ .flex()+ .items_center()+ .justify_center()+ .child(icon(icon_name, 14., color)),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(title.into()))+ .when(!detail.is_empty(), |d| d.child(div().text_size(px(12.)).text_color(theme.text_muted).child(detail))),+ )+ .children(action)+}++fn stat_tiles(theme: &Theme, s: &Snapshot) -> impl IntoElement {+ let c = &s.counts;+ let stuck = s.jobs.queued.iter().filter(|j| j.matching_online == 0).count();+ let tile = |icon_name: &'static str, color: Hsla, title: &'static str, value: usize, sub: String| {+ card(theme)+ .flex_1()+ .min_w(px(0.))+ .p(px(16.))+ .gap(px(10.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().size(px(24.)).rounded(px(7.)).bg(color.opacity(0.16)).flex().items_center().justify_center().child(icon(icon_name, 13., color)))+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(title)),+ )+ .child(div().font_family(mono_font()).text_size(px(28.)).line_height(px(30.)).font_weight(FontWeight::MEDIUM).child(value.to_string()))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(sub))+ };+ div()+ .flex()+ .gap(px(GAP))+ .child(tile("zap", theme.accent, "Working", c.working, format!("of {} runners", c.runners)))+ .child(tile("circle-check", theme.success, "Idle", c.idle, "online, ready for jobs".into()))+ .child(tile(+ "circle-x",+ theme.text_placeholder,+ "Offline",+ c.offline,+ if c.unknown > 0 { format!("{} more unknown", c.unknown) } else { "not connected".into() },+ ))+ .child(tile(+ "clock",+ if stuck > 0 { theme.warning } else { theme.info },+ "Queued",+ c.queued,+ if stuck > 0 { format!("{stuck} can't find a runner") } else { "self-hosted, scanned repos".into() },+ ))+}++fn meter_row(theme: &Theme, label: &'static str, value: Option<String>, fraction: Option<f32>, color: Hsla) -> impl IntoElement {+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .text_size(px(11.5))+ .child(div().w(px(50.)).flex_none().text_color(theme.text_placeholder).child(label))+ .child(div().flex_1().child(meter(theme, fraction.unwrap_or(0.), color)))+ .child(+ div()+ .w(px(76.))+ .flex_none()+ .flex()+ .justify_end()+ .font_family(mono_font())+ .text_color(theme.text_muted)+ .child(value.unwrap_or_else(|| "—".into())),+ )+}++fn status_word(m: &Machine) -> &'static str {+ match m.status.as_str() {+ "online" => "online",+ "offline" => "unreachable",+ "manual" => "no host",+ _ => "unchecked",+ }+}++fn queued_row(theme: &Theme, j: &Job, i: usize, prefix: &str) -> AnyElement {+ let url = j.url.clone();+ let stuck = j.matching_online == 0;+ div()+ .id(SharedString::from(format!("{prefix}-{i}")))+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(14.))+ .py(px(10.))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(div().flex_none().w(px(3.)).h(px(26.)).rounded_full().bg(if stuck { theme.warning } else { theme.track }))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(6.))+ .child(job_title(theme, j))+ .child(div().flex().flex_wrap().gap(px(4.)).children(j.labels.iter().map(|l| chip(theme, l.clone())))),+ )+ .child(+ div()+ .w(px(150.))+ .flex_none()+ .flex()+ .flex_col()+ .items_end()+ .child(div().font_family(mono_font()).text_size(px(12.)).text_color(theme.text_muted).child(format!("waiting {}", format::elapsed(j.created_at))))+ .child(div().text_size(px(11.)).text_color(if stuck { theme.warning } else { theme.text_placeholder }).child(if stuck {+ "no online runner matches".to_string()+ } else {+ format!("{} runner{} can take it", j.matching_online, if j.matching_online == 1 { "" } else { "s" })+ })),+ )+ .child(+ Button::icon_only(SharedString::from(format!("{prefix}-open-{i}")), "external-link")+ .tooltip("Open on GitHub")+ .on_click(move |_, _, cx| cx.open_url(&url)),+ )+ .into_any_element()+}++fn job_title(theme: &Theme, j: &Job) -> impl IntoElement {+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().truncate().text_size(px(13.)).child(j.name.clone()))+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(+ "{} · {}{}",+ j.repo,+ j.workflow,+ j.branch.as_ref().map(|b| format!(" · {b}")).unwrap_or_default()+ )))+}diff --git a/src/ui/root.rs b/src/ui/root.rsnew file mode 100644index 0000000..636bdbd--- /dev/null+++ b/src/ui/root.rs@@ -0,0 +1,1265 @@+//! The root view: a full-height fleet sidebar, a page area with its own+//! toolbar and history, and an activity drawer that slides over from the right.++use std::collections::{HashSet, VecDeque};+use std::sync::Arc;+use std::time::{Duration, Instant};++use gpui::{+ AnyElement, App, ClickEvent, Context, Entity, FocusHandle, Focusable, FontWeight, KeyBinding, Menu, MenuItem,+ ScrollHandle, SharedString, Subscription, Task, Window, actions, div, prelude::*, px,+};++use super::dialogs::{AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewWorkspaceDialog};+use super::format;+use super::input::{InputEvent, TextInput};+use super::kit::{self, Button, ButtonStyle, icon, runner_glyph, spinner};+use super::settings::SettingsPage;+use super::theme::{ActiveTheme, mono_font, Theme, ui_font};+use super::workspaces::WorkspaceUi;+use super::activity::{ActivityFilter, ActivityItem};+use crate::fleet::workspaces::{CreateWorkspace, WorkspaceIsolation};+use crate::fleet::Engine;+use crate::fleet::model::{Action, Machine, Runner, Snapshot};+use crate::ops::RunnerAction;++actions!(+ openrunner,+ [+ CheckNow,+ SyncGitHub,+ ShowOverview,+ ShowJobs,+ OpenSettings,+ FocusFilter,+ GoBack,+ GoForward,+ ToggleActivity,+ AddMachine,+ Dismiss,+ Quit+ ]+);++const WORKSPACE: &str = "Root";+pub(super) const SIDEBAR_WIDTH: f32 = 256.;+/// Utilization samples kept for the overview's pulse chart.+const PULSE_SAMPLES: usize = 64;+const PULSE_EVERY: Duration = Duration::from_secs(5);++pub fn bind_keys(cx: &mut App) {+ cx.bind_keys([+ KeyBinding::new("secondary-r", CheckNow, None),+ KeyBinding::new("secondary-shift-r", SyncGitHub, None),+ KeyBinding::new("secondary-1", ShowOverview, None),+ KeyBinding::new("secondary-2", ShowJobs, None),+ KeyBinding::new("secondary-,", OpenSettings, None),+ KeyBinding::new("secondary-f", FocusFilter, None),+ KeyBinding::new("secondary-[", GoBack, None),+ KeyBinding::new("secondary-]", GoForward, None),+ KeyBinding::new("secondary-j", ToggleActivity, None),+ KeyBinding::new("secondary-n", AddMachine, None),+ KeyBinding::new("secondary-q", Quit, None),+ KeyBinding::new("escape", Dismiss, Some(WORKSPACE)),+ KeyBinding::new("/", FocusFilter, Some(WORKSPACE)),+ ]);+}++pub fn menus() -> Vec<Menu> {+ vec![+ Menu {+ name: "OpenRunner".into(),+ items: vec![MenuItem::action("Settings…", OpenSettings), MenuItem::separator(), MenuItem::action("Quit OpenRunner", Quit)],+ },+ Menu {+ name: "Fleet".into(),+ items: vec![+ MenuItem::action("Check Now", CheckNow),+ MenuItem::action("Sync GitHub", SyncGitHub),+ MenuItem::separator(),+ MenuItem::action("Add Machine…", AddMachine),+ ],+ },+ Menu {+ name: "View".into(),+ items: vec![+ MenuItem::action("Overview", ShowOverview),+ MenuItem::action("Jobs", ShowJobs),+ MenuItem::action("Activity", ToggleActivity),+ MenuItem::separator(),+ MenuItem::action("Back", GoBack),+ MenuItem::action("Forward", GoForward),+ ],+ },+ ]+}++#[derive(Clone, PartialEq, Eq, Debug)]+pub enum Route {+ Overview,+ Jobs,+ Workspaces,+ Workspace(String),+ Activity,+ Machine(String),+ Runner(String),+ Settings,+}++pub enum Modal {+ AddMachine(Entity<AddMachineDialog>),+ Install(Entity<InstallDialog>),+ Confirm(Entity<ConfirmDialog>),+ NewWorkspace(Entity<NewWorkspaceDialog>),+}++pub struct Notice {+ pub text: SharedString,+ pub error: bool,+ pub at: Instant,+}++/// One point on the pulse chart.+#[derive(Clone, Copy)]+pub struct PulseSample {+ pub working: usize,+ pub online: usize,+}++pub struct Root {+ pub(super) engine: Arc<Engine>,+ pub(super) snapshot: Arc<Snapshot>,+ pub(super) focus: FocusHandle,+ pub(super) route: Route,+ back: Vec<Route>,+ forward: Vec<Route>,+ pub(super) filter: Entity<TextInput>,+ pub(super) collapsed: HashSet<String>,+ pub(super) other_open: bool,+ pub(super) activity_filter: ActivityFilter,+ pub(super) activity_selected: Option<ActivityItem>,+ pub(super) activity_scroll: ScrollHandle,+ pub(super) activity_seen_len: usize,+ pub(super) modal: Option<Modal>,+ pub(super) settings: Option<Entity<SettingsPage>>,+ pub(super) notice: Option<Notice>,+ pub(super) page_scroll: ScrollHandle,+ pub(super) pulse: VecDeque<PulseSample>,+ last_pulse: Option<Instant>,+ /// Width of the page area, for layouts that change with the window size.+ pub(super) content_width: f32,+ pub(super) ws_ui: WorkspaceUi,+ _tasks: Vec<Task<()>>,+ _subscriptions: Vec<Subscription>,+}++impl Root {+ pub fn new(engine: Arc<Engine>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let filter = cx.new(|cx| TextInput::new(cx, "Search fleet"));+ let mut subscriptions = vec![cx.subscribe_in(&filter, window, |this, _, event: &InputEvent, window, cx| match event {+ InputEvent::Changed => cx.notify(),+ InputEvent::Cancel => {+ this.filter.update(cx, |f, cx| f.set_text("", cx));+ window.focus(&this.focus);+ }+ InputEvent::Submit => {+ // Enter opens the first match.+ if let Some(target) = this.first_filter_match(cx) {+ this.navigate(target, window, cx);+ }+ }+ })];+ subscriptions.push(cx.observe_window_appearance(window, |_, window, cx| {+ super::theme::apply(window, cx);+ cx.notify();+ }));++ // Snapshots arrive from the engine's tokio runtime over a watch channel.+ let mut rx = engine.subscribe();+ let snapshot = rx.borrow_and_update().clone();+ let updates = cx.spawn(async move |this, cx| {+ while rx.changed().await.is_ok() {+ let next = rx.borrow_and_update().clone();+ if this.update(cx, |this, cx| this.apply_snapshot(next, cx)).is_err() {+ break;+ }+ }+ });+ // Relative times ("2m ago", running job timers) tick once a second.+ let ticker = cx.spawn(async move |this, cx| {+ loop {+ cx.background_executor().timer(Duration::from_secs(1)).await;+ let alive = this.update(cx, |this, cx| {+ if this.notice.as_ref().is_some_and(|n| n.at.elapsed() > Duration::from_secs(6)) {+ this.notice = None;+ }+ this.record_pulse();+ cx.notify()+ });+ if alive.is_err() {+ break;+ }+ }+ });++ let mut ws = Root {+ engine,+ snapshot,+ focus: cx.focus_handle(),+ route: Route::Overview,+ back: Vec::new(),+ forward: Vec::new(),+ filter,+ collapsed: HashSet::new(),+ other_open: false,+ activity_filter: ActivityFilter::default(),+ activity_selected: None,+ activity_scroll: ScrollHandle::new(),+ activity_seen_len: 0,+ modal: None,+ settings: None,+ notice: None,+ page_scroll: ScrollHandle::new(),+ pulse: VecDeque::with_capacity(PULSE_SAMPLES),+ last_pulse: None,+ content_width: 1000.,+ ws_ui: WorkspaceUi::default(),+ _tasks: vec![updates, ticker],+ _subscriptions: subscriptions,+ };+ ws.record_pulse();+ ws+ }++ fn apply_snapshot(&mut self, snapshot: Arc<Snapshot>, cx: &mut Context<Self>) {+ // Keep the activity log pinned to the bottom while output streams in.+ let selected = self.selected_operation_id_in(&snapshot);+ let len = selected.and_then(|id| snapshot.operations.iter().find(|o| o.id == id)).map(|o| o.log.len()).unwrap_or(0);+ if len != self.activity_seen_len {+ self.activity_seen_len = len;+ self.activity_scroll.scroll_to_bottom();+ }+ self.snapshot = snapshot;+ cx.notify();+ }++ fn record_pulse(&mut self) {+ if self.last_pulse.is_some_and(|t| t.elapsed() < PULSE_EVERY) {+ return;+ }+ self.last_pulse = Some(Instant::now());+ let c = &self.snapshot.counts;+ if self.pulse.len() == PULSE_SAMPLES {+ self.pulse.pop_front();+ }+ self.pulse.push_back(PulseSample { working: c.working, online: c.working + c.idle });+ }++ // -----------------------------------------------------------------------+ // Navigation++ pub(super) fn navigate(&mut self, route: Route, window: &mut Window, cx: &mut Context<Self>) {+ self.show(route, cx);+ self.on_route_changed(window, cx);+ }++ /// Navigation that doesn't need the window (the settings page is created on first render).+ pub(super) fn show(&mut self, route: Route, cx: &mut Context<Self>) {+ if route == self.route {+ return;+ }+ let previous = std::mem::replace(&mut self.route, route);+ self.back.push(previous);+ self.forward.clear();+ self.page_scroll = ScrollHandle::new();+ cx.notify();+ }++ /// Shows an operation's live output on the Activity page.+ pub(super) fn show_operation(&mut self, op: u64, cx: &mut Context<Self>) {+ self.activity_filter = ActivityFilter::All;+ self.activity_selected = Some(ActivityItem::Op(op));+ self.activity_seen_len = usize::MAX;+ self.show(Route::Activity, cx);+ }++ fn on_route_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ if self.route == Route::Settings && self.settings.is_none() {+ let engine = self.engine.clone();+ self.settings = Some(cx.new(|cx| SettingsPage::new(engine, window, cx)));+ }+ self.page_scroll = ScrollHandle::new();+ cx.notify();+ }++ /// Opens a view by name; see `--view` in main.rs.+ pub fn open_view(&mut self, view: &str, window: &mut Window, cx: &mut Context<Self>) {+ let (kind, arg) = view.split_once(':').unwrap_or((view, ""));+ match kind {+ "jobs" => self.navigate(Route::Jobs, window, cx),+ "workspaces" => self.navigate(Route::Workspaces, window, cx),+ "workspace" => self.navigate(Route::Workspace(arg.into()), window, cx),+ "new-workspace" => {+ self.show_new_workspace(None, window, cx);+ if arg == "docker" {+ if let Some(Modal::NewWorkspace(d)) = &self.modal {+ d.update(cx, |d, cx| d.set_docker(true, cx));+ }+ }+ }+ "confirm-remove" => {+ if let Some(r) = self.snapshot.runners.iter().find(|r| r.id == arg).cloned() {+ self.confirm_remove_runner(&r, window, cx);+ }+ }+ "size" => {}+ "settings" => self.navigate(Route::Settings, window, cx),+ "machine" => self.navigate(Route::Machine(arg.into()), window, cx),+ "runner" => self.navigate(Route::Runner(arg.into()), window, cx),+ "install" => {+ self.navigate(Route::Machine(arg.into()), window, cx);+ self.show_install_dialog(arg, window, cx);+ }+ "add-machine" => self.show_add_machine(window, cx),+ "logs" => {+ self.navigate(Route::Runner(arg.into()), window, cx);+ // Give the first machine check a moment, so the runner's folder is known.+ let runner = arg.to_string();+ let task = cx.spawn(async move |this, cx| {+ cx.background_executor().timer(Duration::from_secs(3)).await;+ let _ = this.update(cx, |this, cx| this.runner_action(&runner, RunnerAction::Logs, cx));+ });+ self._tasks.push(task);+ }+ "activity" => self.show(Route::Activity, cx),+ "bottom" => {+ self.page_scroll.scroll_to_bottom();+ if let (Route::Settings, Some(page)) = (&self.route, &self.settings) {+ page.read(cx).scroll.scroll_to_bottom();+ }+ }+ "theme" => {+ let id = arg.to_string();+ if let Some(p) = super::themes::find(&id) {+ let dark = p.dark;+ super::theme::update_appearance(window, cx, |a, _| {+ if dark { a.dark = id.clone() } else { a.light = id.clone() }+ a.mode = if dark { super::theme::Mode::Dark } else { super::theme::Mode::Light };+ });+ }+ }+ _ => tracing::warn!("unknown view {view:?}"),+ }+ }++ /// Lets a background UI task finish on its own. They only hold a weak handle+ /// to this view, so a closed window just makes them no-ops.+ pub(super) fn track(&mut self, task: Task<()>) {+ task.detach();+ }++ pub(super) fn notify_user(&mut self, text: impl Into<SharedString>, error: bool, cx: &mut Context<Self>) {+ self.notice = Some(Notice { text: text.into(), error, at: Instant::now() });+ cx.notify();+ }++ pub(super) fn run_attention_action(&mut self, action: &Action, window: &mut Window, cx: &mut Context<Self>) {+ match action.kind.as_str() {+ "settings" => self.navigate(Route::Settings, window, cx),+ "check" => self.engine.trigger_check(action.target.clone()),+ "machine" => {+ if let Some(t) = &action.target {+ self.navigate(Route::Machine(t.clone()), window, cx)+ }+ }+ "runner" => {+ if let Some(t) = &action.target {+ self.navigate(Route::Runner(t.clone()), window, cx)+ }+ }+ "queue" => self.navigate(Route::Jobs, window, cx),+ "link" => {+ if let Some(t) = &action.target {+ cx.open_url(t)+ }+ }+ _ => {}+ }+ }++ // -----------------------------------------------------------------------+ // Commands shared by pages++ pub(super) fn show_install_dialog(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let snapshot = self.snapshot.clone();+ let machine_id = machine_id.to_string();+ let dialog = cx.new(|cx| InstallDialog::new(engine, snapshot, machine_id, window, cx));+ self.show_modal(Modal::Install(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ pub(super) fn show_add_machine(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| AddMachineDialog::new(engine, window, cx));+ self.show_modal(Modal::AddMachine(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ pub(super) fn confirm_remove_runner(&mut self, runner: &Runner, window: &mut Window, cx: &mut Context<Self>) {+ let on_machine = runner.local.is_some();+ let detail = match (&runner.machine_id, on_machine) {+ (Some(_), true) => format!(+ "{} will be stopped, its service uninstalled, and it will be deregistered from GitHub and removed from fleet.toml.",+ runner.name+ ),+ _ => format!("{} will be deregistered from GitHub.", runner.name),+ };+ let runner_id = runner.id.clone();+ let dialog = cx.new(|cx| {+ ConfirmDialog::new(+ format!("Remove {}?", runner.name),+ detail,+ "Remove runner",+ on_machine.then_some("Also delete the runner folder"),+ move |delete_files, engine| engine.runner_action(&runner_id, RunnerAction::Remove { delete_files }).map(Some),+ self.engine.clone(),+ window,+ cx,+ )+ });+ self.show_modal(Modal::Confirm(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ pub(super) fn confirm_remove_machine(&mut self, machine: &Machine, window: &mut Window, cx: &mut Context<Self>) {+ let machine_id = machine.id.clone();+ let dialog = cx.new(|cx| {+ ConfirmDialog::new(+ format!("Remove {} from the fleet?", machine.name),+ "It's taken out of fleet.toml. Nothing on the machine changes, and its runners stay registered.".into(),+ "Remove machine",+ None,+ move |_, engine| engine.remove_machine(&machine_id).map(|_| None),+ self.engine.clone(),+ window,+ cx,+ )+ });+ self.show_modal(Modal::Confirm(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ pub(super) fn show_new_workspace(&mut self, machine: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| NewWorkspaceDialog::new(engine, machine, window, cx));+ self.show_modal(Modal::NewWorkspace(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ /// Creates a workspace in the background; opens it when ready.+ fn create_workspace(&mut self, req: CreateWorkspace, iso: WorkspaceIsolation, window: &mut Window, cx: &mut Context<Self>) {+ // Its setup shows up on the Activity page as the newest operation.+ self.activity_filter = ActivityFilter::All;+ self.activity_selected = None;+ self.show(Route::Activity, cx);+ let engine = self.engine.clone();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.create_workspace_with(req, iso).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update_in(cx, |this, window, cx| match result {+ Ok(ws) => this.navigate(Route::Workspace(ws.id), window, cx),+ Err(e) => this.notify_user(e, true, cx),+ });+ });+ self.track(task);+ }++ pub(super) fn confirm_destroy_workspace(&mut self, id: &str, name: &str, window: &mut Window, cx: &mut Context<Self>) {+ let wid = id.to_string();+ let dialog = cx.new(|cx| {+ ConfirmDialog::new(+ format!("Destroy {name}?"),+ "Background commands it started are stopped and its folder is deleted from the machine.".into(),+ "Destroy workspace",+ Some("Keep the files on the machine"),+ move |keep_files, engine| {+ let engine = engine.clone();+ let wid = wid.clone();+ // Runs as an operation; progress and errors show in Activity.+ engine.runtime().clone().spawn(async move {+ if let Err(e) = engine.destroy_workspace(&wid, keep_files).await {+ tracing::warn!("destroying {wid}: {e}");+ }+ });+ Ok(None)+ },+ self.engine.clone(),+ window,+ cx,+ )+ });+ self.show_modal(Modal::Confirm(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ pub(super) fn runner_action(&mut self, runner_id: &str, action: RunnerAction, cx: &mut Context<Self>) {+ match self.engine.runner_action(runner_id, action) {+ Ok(op) => self.show_operation(op, cx),+ Err(e) => self.notify_user(e, true, cx),+ }+ }++ fn show_modal(&mut self, modal: Modal, window: &mut Window, cx: &mut Context<Self>) {+ let focus = match &modal {+ Modal::AddMachine(d) => d.read(cx).first_focus(cx),+ Modal::Install(d) => d.read(cx).first_focus(cx),+ Modal::Confirm(d) => d.focus_handle(cx),+ Modal::NewWorkspace(d) => d.read(cx).first_focus(cx),+ };+ window.focus(&focus);+ self.modal = Some(modal);+ cx.notify();+ }++ fn on_dialog_event<D>(&mut self, _: &Entity<D>, event: &DialogEvent, window: &mut Window, cx: &mut Context<Self>) {+ self.modal = None;+ match event {+ DialogEvent::Dismissed => {}+ DialogEvent::OperationStarted(op) => self.show_operation(*op, cx),+ DialogEvent::MachineAdded(id) => self.navigate(Route::Machine(id.clone()), window, cx),+ DialogEvent::OpenSettings => self.navigate(Route::Settings, window, cx),+ DialogEvent::CreateWorkspace(req, iso) => self.create_workspace(req.clone(), iso.clone(), window, cx),+ }+ window.focus(&self.focus);+ cx.notify();+ }++ pub(super) fn filter_query(&self, cx: &App) -> String {+ self.filter.read(cx).text().trim().to_lowercase()+ }++ fn first_filter_match(&self, cx: &App) -> Option<Route> {+ let q = self.filter_query(cx);+ if q.is_empty() {+ return None;+ }+ let s = &self.snapshot;+ s.machines+ .iter()+ .find(|m| m.name.to_lowercase().contains(&q))+ .map(|m| Route::Machine(m.id.clone()))+ .or_else(|| s.runners.iter().find(|r| r.name.to_lowercase().contains(&q)).map(|r| Route::Runner(r.id.clone())))+ }++ pub(super) fn selected_operation_id_in(&self, s: &Snapshot) -> Option<u64> {+ match self.selected_activity(s) {+ Some(ActivityItem::Op(id)) => Some(id),+ _ => None,+ }+ }++ // -----------------------------------------------------------------------+ // Action handlers++ fn check_now(&mut self, _: &CheckNow, _: &mut Window, _: &mut Context<Self>) {+ self.engine.trigger_check(None);+ }++ fn sync_github(&mut self, _: &SyncGitHub, _: &mut Window, _: &mut Context<Self>) {+ self.engine.trigger_sync();+ }++ fn show_overview(&mut self, _: &ShowOverview, window: &mut Window, cx: &mut Context<Self>) {+ self.navigate(Route::Overview, window, cx);+ }++ fn show_jobs(&mut self, _: &ShowJobs, window: &mut Window, cx: &mut Context<Self>) {+ self.navigate(Route::Jobs, window, cx);+ }++ fn open_settings(&mut self, _: &OpenSettings, window: &mut Window, cx: &mut Context<Self>) {+ self.navigate(Route::Settings, window, cx);+ }++ fn focus_filter(&mut self, _: &FocusFilter, window: &mut Window, cx: &mut Context<Self>) {+ window.focus(&self.filter.focus_handle(cx));+ }++ fn go_back(&mut self, _: &GoBack, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(prev) = self.back.pop() {+ let current = std::mem::replace(&mut self.route, prev);+ self.forward.push(current);+ self.on_route_changed(window, cx);+ }+ }++ fn go_forward(&mut self, _: &GoForward, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(next) = self.forward.pop() {+ let current = std::mem::replace(&mut self.route, next);+ self.back.push(current);+ self.on_route_changed(window, cx);+ }+ }++ fn toggle_activity(&mut self, _: &ToggleActivity, window: &mut Window, cx: &mut Context<Self>) {+ if self.route == Route::Activity {+ self.go_back(&GoBack, window, cx);+ } else {+ self.show(Route::Activity, cx);+ }+ }++ fn add_machine(&mut self, _: &AddMachine, window: &mut Window, cx: &mut Context<Self>) {+ self.show_add_machine(window, cx);+ }++ fn dismiss(&mut self, _: &Dismiss, window: &mut Window, cx: &mut Context<Self>) {+ if self.modal.take().is_some() {+ window.focus(&self.focus);+ }+ cx.notify();+ }++ // -----------------------------------------------------------------------+ // Sidebar++ fn render_sidebar(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let q = self.filter_query(cx);+ let matches_runner = |r: &Runner| q.is_empty() || r.name.to_lowercase().contains(&q);+ let selected_machine = match &self.route {+ Route::Machine(id) => Some(id.clone()),+ _ => None,+ };+ let selected_runner = match &self.route {+ Route::Runner(id) => Some(id.clone()),+ _ => None,+ };+ let running_ops = s.operations.iter().filter(|o| o.status == "running").count();+ let mac_titlebar = cfg!(target_os = "macos") && !window.is_fullscreen();++ let mut rows: Vec<AnyElement> = Vec::new();+ let runner_machines: Vec<&Machine> = s.machines.iter().filter(|m| m.kind == "runner").collect();+ let others: Vec<&Machine> = s.machines.iter().filter(|m| m.kind == "other").collect();+ let unassigned: Vec<&Runner> = s.runners.iter().filter(|r| r.machine_id.is_none() && matches_runner(r)).collect();++ rows.push(self.section_header("Machines", runner_machines.len(), true, cx).into_any_element());+ for m in &runner_machines {+ let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();+ let machine_match = q.is_empty() || m.name.to_lowercase().contains(&q);+ let visible: Vec<&Runner> = runners.iter().copied().filter(|r| machine_match || matches_runner(r)).collect();+ if !machine_match && visible.is_empty() {+ continue;+ }+ let open = !self.collapsed.contains(&m.id) || !q.is_empty();+ rows.push(self.machine_row(&theme, &s, m, open, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());+ if open {+ for r in visible {+ rows.push(self.runner_row(&theme, &s, r, selected_runner.as_deref() == Some(&r.id), cx).into_any_element());+ }+ }+ }+ if !unassigned.is_empty() {+ rows.push(self.section_header("On GitHub only", unassigned.len(), false, cx).into_any_element());+ for r in unassigned {+ rows.push(self.runner_row(&theme, &s, r, selected_runner.as_deref() == Some(&r.id), cx).into_any_element());+ }+ }+ let others_visible: Vec<&&Machine> = others.iter().filter(|m| q.is_empty() || m.name.to_lowercase().contains(&q)).collect();+ if !others_visible.is_empty() {+ let open = self.other_open || !q.is_empty();+ rows.push(+ div()+ .id("others-toggle")+ .flex()+ .items_center()+ .gap(px(6.))+ .mt(px(14.))+ .mx(px(10.))+ .px(px(8.))+ .h(px(24.))+ .rounded(px(6.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .text_size(px(11.5))+ .text_color(theme.text_placeholder)+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 12., theme.text_placeholder))+ .child(format!("Other machines · {}", others_visible.len()))+ .on_click(cx.listener(|this, _, _, cx| {+ this.other_open = !this.other_open;+ cx.notify()+ }))+ .into_any_element(),+ );+ if open {+ for m in others_visible {+ rows.push(self.machine_row(&theme, &s, m, false, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());+ }+ }+ }+ if s.machines.is_empty() {+ rows.push(+ div()+ .mx(px(18.))+ .my(px(8.))+ .text_size(px(12.5))+ .text_color(theme.text_placeholder)+ .child("No machines yet. Add one to start watching its runners.")+ .into_any_element(),+ );+ }++ div()+ .flex()+ .flex_col()+ .flex_none()+ .w(px(SIDEBAR_WIDTH))+ .h_full()+ .bg(theme.sidebar)+ .border_r_1()+ .border_color(theme.border_variant)+ // Room for the macOS traffic lights; the window drags from here.+ .when(mac_titlebar, |d| {+ d.child(div().id("sidebar-drag").h(px(40.)).flex_none().on_click(|e: &ClickEvent, window, _| {+ if e.click_count() == 2 {+ window.titlebar_double_click();+ }+ }))+ })+ .child(self.brand(&theme, &s))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(2.))+ .px(px(10.))+ .pt(px(6.))+ .child(self.nav_item("nav-overview", "gauge", "Overview", None, Route::Overview, cx))+ .child(self.nav_item("nav-jobs", "workflow", "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, cx))+ .child(self.nav_item("nav-workspaces", "terminal", "Workspaces", Some(s.workspaces.len()), Route::Workspaces, cx))+ .child(self.activity_nav(&theme, running_ops, cx))+ .child(self.nav_item("nav-settings", "settings", "Settings", None, Route::Settings, cx)),+ )+ .child(+ div().px(px(12.)).pt(px(12.)).pb(px(4.)).child(+ div()+ .relative()+ .child(self.filter.clone())+ .child(div().absolute().right(px(7.)).top(px(6.)).child(kit::kbd(&theme, "/"))),+ ),+ )+ .child(div().id("fleet-list").flex_1().min_h(px(0.)).overflow_y_scroll().pb(px(12.)).children(rows))+ .child(self.connection_card(&theme, &s, cx))+ }++ fn brand(&self, theme: &Theme, s: &Snapshot) -> impl IntoElement {+ let scope = format::scope_label(s);+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(16.))+ .pt(px(if cfg!(target_os = "macos") { 2. } else { 14. }))+ .pb(px(8.))+ .child(gpui::img("brand/icon.png").size(px(32.)).flex_none())+ .child(+ div()+ .flex()+ .flex_col()+ .min_w(px(0.))+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("OpenRunner"))+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(+ "{} · {} runners",+ scope.unwrap_or_else(|| "self-hosted".into()),+ s.counts.runners+ ))),+ )+ .when(s.demo, |d| d.child(div().flex_1()).child(kit::pill("demo", theme.warning)))+ }++ fn nav_item(&self, id: &'static str, icon_name: &'static str, text: &'static str, count: Option<usize>, route: Route, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ // A workspace page keeps "Workspaces" highlighted.+ let active = self.route == route || (route == Route::Workspaces && matches!(self.route, Route::Workspace(_)));+ div()+ .id(id)+ .flex()+ .items_center()+ .gap(px(10.))+ .h(px(30.))+ .px(px(10.))+ .rounded(px(8.))+ .cursor_pointer()+ .text_size(px(13.))+ .text_color(if active { theme.text } else { theme.text_muted })+ .when(active, |d| d.bg(theme.element_selected))+ .when(!active, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(icon(icon_name, 15., if active { theme.text_accent } else { theme.text_placeholder }))+ .child(text)+ .child(div().flex_1())+ .children(count.filter(|n| *n > 0).map(|n| {+ div()+ .px(px(6.))+ .h(px(18.))+ .flex()+ .items_center()+ .rounded_full()+ .bg(theme.element_hover)+ .font_family(mono_font())+ .text_size(px(11.))+ .text_color(theme.text_muted)+ .child(n.to_string())+ }))+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(route.clone(), window, cx)))+ }++ fn activity_nav(&self, theme: &Theme, running: usize, cx: &mut Context<Self>) -> impl IntoElement {+ let open = self.route == Route::Activity;+ div()+ .id("nav-activity")+ .flex()+ .items_center()+ .gap(px(10.))+ .h(px(30.))+ .px(px(10.))+ .rounded(px(8.))+ .cursor_pointer()+ .text_size(px(13.))+ .text_color(if open { theme.text } else { theme.text_muted })+ .when(open, |d| d.bg(theme.element_selected))+ .when(!open, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(icon("activity", 15., if open { theme.text_accent } else { theme.text_placeholder }))+ .child("Activity")+ .child(div().flex_1())+ .when(running > 0, |d| d.child(spinner("nav-activity-spin", 13., theme.accent)))+ .when(running == 0, |d| d.child(kit::kbd(theme, "⌘J")))+ .on_click(cx.listener(|this, _, _, cx| this.show(Route::Activity, cx)))+ }++ fn section_header(&self, title: &'static str, count: usize, with_add: bool, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .h(px(28.))+ .mt(px(10.))+ .pl(px(20.))+ .pr(px(12.))+ .text_size(px(11.5))+ .font_weight(FontWeight::MEDIUM)+ .text_color(theme.text_placeholder)+ .child(title)+ .child(div().font_family(mono_font()).child(count.to_string()))+ .child(div().flex_1())+ .when(with_add, |d| {+ d.child(+ Button::icon_only("sidebar-add-machine", "plus")+ .tooltip("Add machine ⌘N")+ .on_click(cx.listener(|this, _, window, cx| this.show_add_machine(window, cx))),+ )+ })+ }++ fn machine_row(&self, theme: &Theme, s: &Snapshot, m: &Machine, open: bool, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {+ let id = m.id.clone();+ let toggle_id = m.id.clone();+ let has_runners = !m.runner_ids.is_empty();+ let glyphs: Vec<AnyElement> = m+ .runner_ids+ .iter()+ .filter_map(|rid| s.runners.iter().find(|r| &r.id == rid))+ .take(8)+ .map(|r| runner_glyph(theme, &r.state, 7.).into_any_element())+ .collect();+ let extra = m.runner_ids.len().saturating_sub(8);+ div()+ .id(SharedString::from(format!("side-m-{}", m.id)))+ .group("machine-row")+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(30.))+ .mx(px(10.))+ .pl(px(6.))+ .pr(px(8.))+ .rounded(px(8.))+ .cursor_pointer()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(+ div()+ .id(SharedString::from(format!("side-t-{}", m.id)))+ .size(px(14.))+ .flex()+ .items_center()+ .justify_center()+ .when(has_runners, |d| {+ d.invisible()+ .group_hover("machine-row", |st| st.visible())+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 11., theme.text_placeholder))+ .on_click(cx.listener(move |this, _, _, cx| {+ cx.stop_propagation();+ if !this.collapsed.remove(&toggle_id) {+ this.collapsed.insert(toggle_id.clone());+ }+ cx.notify()+ }))+ }),+ )+ .child(if m.checking {+ spinner(SharedString::from(format!("side-spin-{}", m.id)), 10., theme.text_muted).into_any_element()+ } else {+ kit::dot(theme.machine_status(&m.status), 7.).into_any_element()+ })+ .child(+ div()+ .flex_1()+ .min_w(px(0.))+ .truncate()+ .text_size(px(13.))+ .font_weight(FontWeight::MEDIUM)+ .text_color(if selected { theme.text } else { theme.text })+ .child(m.name.clone()),+ )+ .child(div().flex().flex_none().gap(px(2.)).children(glyphs))+ .when(extra > 0, |d| d.child(div().font_family(mono_font()).text_size(px(10.5)).text_color(theme.text_placeholder).child(format!("+{extra}"))))+ .when(m.kind == "other", |d| {+ d.child(div().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(m.platform.clone()))+ })+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(id.clone()), window, cx)))+ }++ fn runner_row(&self, theme: &Theme, s: &Snapshot, r: &Runner, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {+ let id = r.id.clone();+ let job = r.job_id.and_then(|j| s.jobs.running.iter().find(|x| x.id == j));+ let right = match (r.state.as_str(), job) {+ ("working", Some(j)) => ellipsize(&j.name, 14),+ ("working", None) => "working".into(),+ ("offline", _) => "offline".into(),+ ("unknown", _) => "unknown".into(),+ _ => String::new(),+ };+ let dim = matches!(r.state.as_str(), "offline" | "unknown");+ div()+ .id(SharedString::from(format!("side-r-{}", r.id)))+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(26.))+ .mx(px(10.))+ .pl(px(28.))+ .pr(px(8.))+ .rounded(px(7.))+ .cursor_pointer()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(div().flex_none().w(px(3.)).h(px(12.)).rounded_full().bg(if dim { theme.track } else { theme.state(&r.state) }))+ // The runner name wins; the job name takes whatever room is left.+ .child(+ div()+ .flex_none()+ .font_family(mono_font())+ .text_size(px(12.))+ .text_color(if dim { theme.text_placeholder } else { theme.text_muted })+ .child(r.name.clone()),+ )+ .child(+ div()+ .flex_1()+ .min_w(px(0.))+ .flex()+ .justify_end()+ .overflow_hidden()+ .whitespace_nowrap()+ .text_size(px(11.))+ .text_color(if r.state == "working" { theme.text_accent } else { theme.text_placeholder })+ .child(right),+ )+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Runner(id.clone()), window, cx)))+ }++ fn connection_card(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {+ let (color, title) = github_status(theme, s);+ let detail = match (s.check.running, s.check.next_at) {+ (true, _) => "Checking machines…".to_string(),+ (false, Some(next)) => format!("Checked {} · next {}", format::ago(s.check.finished_at), format::until(next)),+ (false, None) if s.check.finished_at.is_some() => format!("Checked {}", format::ago(s.check.finished_at)),+ _ => "Machines not checked yet".into(),+ };+ div().flex_none().p(px(10.)).border_t_1().border_color(theme.border_variant).child(+ div()+ .id("connection")+ .flex()+ .items_start()+ .gap(px(10.))+ .px(px(10.))+ .py(px(9.))+ .rounded(px(10.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .cursor_pointer()+ .hover(|st| st.border_color(theme.border))+ .child(div().pt(px(4.)).child(kit::dot(color, 8.)))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().truncate().text_size(px(12.5)).text_color(theme.text).child(title))+ .child(div().truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(detail)),+ )+ .on_click(cx.listener(|this, _, window, cx| this.navigate(Route::Settings, window, cx))),+ )+ }++ // -----------------------------------------------------------------------+ // Toolbar and overlays++ fn render_toolbar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let (section, title) = route_title(&s, &self.route);+ div()+ .id("toolbar")+ .flex()+ .flex_none()+ .items_center()+ .gap(px(10.))+ .h(px(52.))+ .px(px(16.))+ .border_b_1()+ .border_color(theme.border_variant)+ .on_click(|e: &ClickEvent, window, _| {+ if e.click_count() == 2 {+ window.titlebar_double_click();+ }+ })+ .child(+ div()+ .flex()+ .gap(px(2.))+ .child(+ Button::icon_only("back", "arrow-left")+ .tooltip("Back ⌘[")+ .disabled(self.back.is_empty())+ .on_click(cx.listener(|this, _, window, cx| this.go_back(&GoBack, window, cx))),+ )+ .child(+ Button::icon_only("forward", "arrow-right")+ .tooltip("Forward ⌘]")+ .disabled(self.forward.is_empty())+ .on_click(cx.listener(|this, _, window, cx| this.go_forward(&GoForward, window, cx))),+ ),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .min_w(px(0.))+ .text_size(px(13.5))+ .when_some(section, |d, sec| {+ d.child(div().text_color(theme.text_placeholder).child(sec)).child(div().text_color(theme.text_placeholder).child("›"))+ })+ .child(div().truncate().font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(title)),+ )+ .child(div().flex_1())+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("Updated {}", format::ago(s.updated_at))))+ .child(+ Button::icon_only("sync", "refresh-cw")+ .loading(s.github.syncing && s.github.configured)+ .tooltip("Sync GitHub ⇧⌘R")+ .on_click(cx.listener(|this, _, _, _| this.engine.trigger_sync())),+ )+ .child(+ Button::new("check-now", if s.check.running { "Checking" } else { "Check now" })+ .style(ButtonStyle::Primary)+ .icon("refresh-cw")+ .loading(s.check.running)+ .key_hint("⌘R")+ .on_click(cx.listener(|this, _, _, _| this.engine.trigger_check(None))),+ )+ }++ fn render_notice(&self, theme: &Theme) -> Option<AnyElement> {+ let n = self.notice.as_ref()?;+ let color = if n.error { theme.error } else { theme.success };+ Some(+ div()+ .absolute()+ .bottom(px(18.))+ .right(px(18.))+ .child(+ div()+ .w(px(400.))+ .flex()+ .items_start()+ .gap(px(10.))+ .px(px(14.))+ .py(px(11.))+ .rounded(px(10.))+ .bg(theme.elevated)+ .border_1()+ .border_color(theme.border)+ .shadow_lg()+ .text_size(px(12.5))+ .text_color(theme.text)+ .child(div().flex_none().w(px(3.)).h(px(16.)).rounded_full().bg(color))+ .child(div().flex_1().min_w(px(0.)).whitespace_normal().child(n.text.clone())),+ )+ .into_any_element(),+ )+ }++ fn render_page(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {+ match self.route.clone() {+ Route::Overview => self.render_overview(window, cx).into_any_element(),+ Route::Jobs => self.render_jobs(cx).into_any_element(),+ Route::Workspaces => self.render_workspaces(cx).into_any_element(),+ Route::Workspace(id) => self.render_workspace(&id, cx),+ Route::Activity => self.render_activity(cx).into_any_element(),+ Route::Machine(id) => self.render_machine(&id, cx),+ Route::Runner(id) => self.render_runner(&id, cx),+ Route::Settings => match &self.settings {+ Some(page) => page.clone().into_any_element(),+ None => {+ self.on_route_changed(window, cx);+ div().into_any_element()+ }+ },+ }+ }+}++impl Render for Root {+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ self.content_width = f32::from(window.viewport_size().width) - SIDEBAR_WIDTH - 56.;+ let window_height = f32::from(window.viewport_size().height);+ // Dialogs sit lower on tall windows and scroll when they don't fit.+ let modal_top = if window_height > 800. { 96. } else { 40. };+ let modal_max_height = (window_height - modal_top - 24.).max(200.);+ let page = self.render_page(window, cx);+ let modal = self.modal.as_ref().map(|m| match m {+ Modal::AddMachine(d) => d.clone().into_any_element(),+ Modal::Install(d) => d.clone().into_any_element(),+ Modal::Confirm(d) => d.clone().into_any_element(),+ Modal::NewWorkspace(d) => d.clone().into_any_element(),+ });+ let notice = self.render_notice(&theme);++ div()+ .id("workspace")+ .key_context(WORKSPACE)+ .track_focus(&self.focus)+ .on_action(cx.listener(Self::check_now))+ .on_action(cx.listener(Self::sync_github))+ .on_action(cx.listener(Self::show_overview))+ .on_action(cx.listener(Self::show_jobs))+ .on_action(cx.listener(Self::open_settings))+ .on_action(cx.listener(Self::focus_filter))+ .on_action(cx.listener(Self::go_back))+ .on_action(cx.listener(Self::go_forward))+ .on_action(cx.listener(Self::toggle_activity))+ .on_action(cx.listener(Self::add_machine))+ .on_action(cx.listener(Self::dismiss))+ .relative()+ .flex()+ .size_full()+ .bg(theme.canvas)+ .text_color(theme.text)+ .font_family(ui_font())+ .text_size(px(13.))+ .child(self.render_sidebar(window, cx))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(self.render_toolbar(cx))+ .child(div().flex_1().min_h(px(0.)).child(page)),+ )+ .children(notice)+ .when_some(modal, |d, modal| {+ d.child(+ div()+ .id("modal-layer")+ .absolute()+ .inset_0()+ .bg(theme.scrim)+ .flex()+ .justify_center()+ .pt(px(modal_top))+ .occlude()+ .on_click(cx.listener(|this, _, window, cx| {+ this.modal = None;+ window.focus(&this.focus);+ cx.notify()+ }))+ .child(+ div()+ .id("modal")+ .max_h(px(modal_max_height))+ .overflow_y_scroll()+ .rounded(px(10.))+ .on_click(|_, _, cx| cx.stop_propagation())+ .child(modal),+ ),+ )+ })+ }+}++impl Focusable for Root {+ fn focus_handle(&self, _: &App) -> FocusHandle {+ self.focus.clone()+ }+}++pub(super) fn github_status(theme: &Theme, s: &Snapshot) -> (gpui::Hsla, String) {+ let g = &s.github;+ if g.token_source.is_empty() && !s.demo {+ (theme.warning, "GitHub not connected".into())+ } else if !g.configured {+ (theme.warning, "No GitHub org · using last check".into())+ } else if g.scopes.iter().all(|sc| sc.error.is_some()) && !g.scopes.is_empty() {+ (theme.error, g.error.clone().unwrap_or_else(|| "GitHub error".into()))+ } else if g.live {+ (theme.success, format!("Live · synced {}", format::ago(g.last_sync_at)))+ } else {+ (theme.text_placeholder, "Connecting to GitHub…".into())+ }+}++/// (section, title) for the toolbar.+fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {+ match route {+ Route::Overview => (None, "Overview".into()),+ Route::Jobs => (None, "Jobs".into()),+ Route::Workspaces => (None, "Workspaces".into()),+ Route::Activity => (None, "Activity".into()),+ Route::Workspace(id) => (Some("Workspaces"), s.workspaces.iter().find(|w| &w.id == id).map(|w| w.name.clone()).unwrap_or_else(|| id.clone())),+ Route::Settings => (None, "Settings".into()),+ Route::Machine(id) => (Some("Machines"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),+ Route::Runner(id) => {+ let r = s.runners.iter().find(|r| &r.id == id);+ let machine = r.and_then(|r| r.machine_id.as_deref()).and_then(|mid| s.machines.iter().find(|m| m.id == mid));+ (Some(if machine.is_some() { "Runners" } else { "GitHub" }), r.map(|r| r.name.clone()).unwrap_or_else(|| id.clone()))+ }+ }+}++/// "build (macos-arm64)" -> "build (macos-arm6…" when longer than `max` characters.+fn ellipsize(s: &str, max: usize) -> String {+ if s.chars().count() <= max { s.to_string() } else { format!("{}…", s.chars().take(max - 1).collect::<String>()) }+}diff --git a/src/ui/settings.rs b/src/ui/settings.rsnew file mode 100644index 0000000..a3f0486--- /dev/null+++ b/src/ui/settings.rs@@ -0,0 +1,662 @@+//! Settings: which GitHub orgs/repos to watch, polling intervals, the inventory file.++use std::sync::Arc;+use std::time::{Duration, Instant};++use gpui::{AnyElement, Context, Entity, SharedString, Subscription, Task, Window, div, prelude::*, px};++use super::input::{InputEvent, TextInput};+use super::kit::{self, Button, ButtonStyle, card, icon, mono, section_title};+use super::theme::{self as theme_mod, ActiveTheme, Appearance, mono_font, Mode, Theme};+use super::themes::{PALETTES, Palette};+use crate::config::Settings;+use crate::fleet::Engine;+use crate::fleet::model::Snapshot;++pub struct SettingsPage {+ engine: Arc<Engine>,+ snapshot: Arc<Snapshot>,+ add: Entity<TextInput>,+ poll: Entity<TextInput>,+ scan: Entity<TextInput>,+ interval: Entity<TextInput>,+ testing: bool,+ add_result: Option<(bool, String, Option<String>)>,+ save_error: Option<String>,+ saved_at: Option<Instant>,+ pub scroll: gpui::ScrollHandle,+ _tasks: Vec<Task<()>>,+ _subscriptions: Vec<Subscription>,+}++impl SettingsPage {+ pub fn new(engine: Arc<Engine>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let s = engine.settings();+ let add = cx.new(|cx| TextInput::new(cx, "acme or acme/api").mono());+ let poll = cx.new(|cx| TextInput::new(cx, "20").mono().with_text(s.github_poll_seconds.to_string()));+ let scan = cx.new(|cx| TextInput::new(cx, "10").mono().with_text(s.github.scan_repos.to_string()));+ let interval = cx.new(|cx| TextInput::new(cx, "15").mono().with_text(s.check_interval_minutes.to_string()));++ let mut subs = vec![cx.subscribe_in(&add, window, |this, _, e: &InputEvent, _, cx| match e {+ InputEvent::Submit => this.add_scope(None, cx),+ InputEvent::Changed => {+ this.add_result = None;+ cx.notify()+ }+ InputEvent::Cancel => {}+ })];+ for input in [&poll, &scan, &interval] {+ subs.push(cx.subscribe_in(input, window, |this, _, e: &InputEvent, _, cx| {+ if *e == InputEvent::Submit {+ this.save_intervals(cx)+ }+ }));+ }++ let mut rx = engine.subscribe();+ let snapshot = rx.borrow_and_update().clone();+ let updates = cx.spawn(async move |this, cx| {+ while rx.changed().await.is_ok() {+ let next = rx.borrow_and_update().clone();+ if this+ .update(cx, |this, cx| {+ this.snapshot = next;+ cx.notify()+ })+ .is_err()+ {+ break;+ }+ }+ });++ SettingsPage {+ engine,+ snapshot,+ add,+ poll,+ scan,+ interval,+ testing: false,+ add_result: None,+ save_error: None,+ saved_at: None,+ scroll: gpui::ScrollHandle::new(),+ _tasks: vec![updates],+ _subscriptions: subs,+ }+ }++ /// Checks access to an org or repo, then adds it. `preset` comes from a detected-scope chip.+ fn add_scope(&mut self, preset: Option<String>, cx: &mut Context<Self>) {+ let scope = preset.unwrap_or_else(|| self.add.read(cx).text().trim().to_string());+ if scope.is_empty() || self.testing {+ return;+ }+ self.testing = true;+ self.add_result = None;+ cx.notify();+ let engine = self.engine.clone();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ let scope = scope.clone();+ async move { engine.test_scope(&scope).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await;+ let _ = this.update(cx, |this, cx| {+ this.testing = false;+ match result {+ Ok(t) if t.error.is_none() => {+ let mut s = this.engine.settings();+ let list = if t.name.contains('/') { &mut s.github.repos } else { &mut s.github.orgs };+ if !list.iter().any(|x| x.eq_ignore_ascii_case(&t.name)) {+ list.push(t.name.clone());+ }+ match this.engine.update_settings(s) {+ Ok(_) => {+ this.add_result = Some((+ true,+ format!("Watching {} · {} runner{} found", t.name, t.runners, if t.runners == 1 { "" } else { "s" }),+ None,+ ));+ this.add.update(cx, |a, cx| a.set_text("", cx));+ }+ Err(e) => this.add_result = Some((false, e, None)),+ }+ }+ Ok(t) => this.add_result = Some((false, t.error.unwrap_or_default(), t.hint)),+ Err(e) => this.add_result = Some((false, format!("The check failed: {e}"), None)),+ }+ cx.notify();+ });+ });+ self._tasks.push(task);+ }++ fn remove_scope(&mut self, name: &str, cx: &mut Context<Self>) {+ let mut s = self.engine.settings();+ s.github.orgs.retain(|o| o != name);+ s.github.repos.retain(|r| r != name);+ if let Err(e) = self.engine.update_settings(s) {+ self.save_error = Some(e);+ }+ cx.notify();+ }++ fn save_intervals(&mut self, cx: &mut Context<Self>) {+ let num = |input: &Entity<TextInput>, what: &str| -> Result<u32, String> {+ input.read(cx).text().trim().parse::<u32>().map_err(|_| format!("{what} must be a whole number."))+ };+ let parsed = (|| -> Result<Settings, String> {+ let mut s = self.engine.settings();+ s.github_poll_seconds = num(&self.poll, "The GitHub poll interval")?;+ s.github.scan_repos = num(&self.scan, "Repos to scan")?;+ s.check_interval_minutes = num(&self.interval, "The check interval")?;+ Ok(s)+ })();+ match parsed.and_then(|s| self.engine.update_settings(s)) {+ Ok(saved) => {+ self.save_error = None;+ self.saved_at = Some(Instant::now());+ // Show the clamped values.+ self.poll.update(cx, |i, cx| i.set_text(saved.github_poll_seconds.to_string(), cx));+ self.scan.update(cx, |i, cx| i.set_text(saved.github.scan_repos.to_string(), cx));+ self.interval.update(cx, |i, cx| i.set_text(saved.check_interval_minutes.to_string(), cx));+ let clear = cx.spawn(async move |this, cx| {+ cx.background_executor().timer(Duration::from_secs(3)).await;+ let _ = this.update(cx, |this, cx| {+ this.saved_at = None;+ cx.notify()+ });+ });+ self._tasks.push(clear);+ }+ Err(e) => self.save_error = Some(e),+ }+ cx.notify();+ }++ fn github_section(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {+ let s = &self.snapshot;+ let settings = self.engine.settings();+ let account: AnyElement = if s.github.token_source.is_empty() && !s.demo {+ note(theme, "triangle-alert", theme.warning, "No GitHub token found. Run `gh auth login` in a terminal, or set GITHUB_TOKEN.").into_any_element()+ } else {+ let who = s.github.login.clone().map(|l| format!("Signed in as {l}")).unwrap_or_else(|| "Token found".into());+ let via = match s.github.token_source.as_str() {+ "gh" => "using your gh login".to_string(),+ "" => String::new(),+ var => format!("from ${var}"),+ };+ note(theme, "circle-check", theme.success, format!("{who} {via}")).into_any_element()+ };++ let watched: Vec<(String, &'static str)> = settings+ .github+ .orgs+ .iter()+ .map(|o| (o.clone(), "layers"))+ .chain(settings.github.repos.iter().map(|r| (r.clone(), "git-branch")))+ .collect();+ let rows: Vec<AnyElement> = watched+ .iter()+ .enumerate()+ .map(|(i, (name, icon_name))| {+ let status = s.github.scopes.iter().find(|sc| &sc.name == name);+ let (color, text) = match status {+ Some(sc) if sc.error.is_some() => (theme.error, sc.error.clone().unwrap_or_default()),+ Some(sc) if sc.synced_at.is_some() => {+ (theme.text_muted, format!("{} runner{}", sc.runners, if sc.runners == 1 { "" } else { "s" }))+ }+ _ => (theme.text_placeholder, "syncing…".to_string()),+ };+ let hint = status.and_then(|sc| sc.hint.clone());+ let remove = name.clone();+ div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .px(px(14.))+ .py(px(9.))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(icon(icon_name, 14., theme.text_muted))+ .child(div().font_family(mono_font()).text_size(px(13.)).child(name.clone()))+ .child(div().flex_1().truncate().text_size(px(12.)).text_color(color).child(text))+ .child(+ Button::icon_only(("scope-remove", i), "x")+ .tooltip("Stop watching")+ .on_click(cx.listener(move |this, _, _, cx| this.remove_scope(&remove, cx))),+ ),+ )+ .children(hint.map(|h| hint_line(theme, i, h)))+ .into_any_element()+ })+ .collect();++ let detected: Vec<AnyElement> = s+ .github+ .detected+ .iter()+ .enumerate()+ .map(|(i, d)| {+ let scope = d.clone();+ div()+ .id(("detected", i))+ .flex()+ .items_center()+ .gap(px(5.))+ .h(px(24.))+ .px(px(8.))+ .rounded(px(5.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.element)+ .cursor_pointer()+ .hover(|st| st.bg(theme.element_hover))+ .font_family(mono_font())+ .text_size(px(12.))+ .child(icon("plus", 12., theme.text_muted))+ .child(d.clone())+ .on_click(cx.listener(move |this, _, _, cx| this.add_scope(Some(scope.clone()), cx)))+ .into_any_element()+ })+ .collect();++ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "GitHub", None))+ .child(+ div()+ .w_full()+ .text_size(px(12.5))+ .text_color(theme.text_muted)+ .child("Live runner status and jobs come from the organizations and repositories you watch. Reading org runners needs an org admin token (admin:org)."),+ )+ .child(account)+ .child(+ card(theme)+ .children(rows)+ .when(watched.is_empty(), |d| d.child(kit::empty_state(theme, "layers", "Not watching anything yet.")))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .p(px(10.))+ .border_t_1()+ .border_color(theme.border_variant)+ // Wrap inputs in a flex column (like dialog fields) so they stretch to the+ // row instead of overflowing it.+ .child(div().flex().flex_col().flex_1().min_w(px(0.)).child(self.add.clone()))+ .child(+ Button::new("scope-add", "Add")+ .style(ButtonStyle::Primary)+ .icon("plus")+ .loading(self.testing)+ .on_click(cx.listener(|this, _, _, cx| this.add_scope(None, cx))),+ ),+ ),+ )+ .children(self.add_result.as_ref().map(|(ok, msg, hint)| {+ div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .child(note(theme, if *ok { "circle-check" } else { "circle-alert" }, if *ok { theme.success } else { theme.error }, msg.clone()))+ .children(hint.clone().map(|h| hint_line(theme, 99, h)))+ }))+ .when(!detected.is_empty(), |d| {+ d.child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child("Found in runner configs:"))+ .children(detected),+ )+ })+ }++ fn checks_section(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {+ let row = |label: &'static str, input: Entity<TextInput>, unit: &'static str, help: &'static str, first: bool| {+ div()+ .flex()+ .items_center()+ .when(!first, |d| d.border_t_1().border_color(theme.border_variant))+ .gap(px(12.))+ .px(px(14.))+ .py(px(10.))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().text_size(px(13.)).child(label))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(help)),+ )+ .child(div().w(px(80.)).flex_none().flex().flex_col().child(input))+ .child(div().w(px(60.)).text_size(px(12.)).text_color(theme.text_muted).child(unit))+ };+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Polling", None))+ .child(+ card(theme)+ .child(row("Sync GitHub every", self.poll.clone(), "seconds", "Unchanged responses don't count against the API rate limit.", true))+ .child(row(+ "Scan recent repos for jobs",+ self.scan.clone(),+ "per org",+ "The most recently pushed repositories are checked for queued and running jobs.",+ false,+ ))+ .child(row(+ "Check machines every",+ self.interval.clone(),+ "minutes",+ "Runs the read-only machine check over SSH. 0 means only when you ask.",+ false,+ )),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(Button::new("save-intervals", "Save").style(ButtonStyle::Primary).on_click(cx.listener(|this, _, _, cx| this.save_intervals(cx))))+ .when(self.saved_at.is_some(), |d| d.child(div().text_size(px(12.)).text_color(theme.success).child("Saved")))+ .children(self.save_error.clone().map(|e| div().text_size(px(12.)).text_color(theme.error).child(e))),+ )+ }++ fn appearance_section(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {+ let appearance = cx.global::<Appearance>().clone();+ let mode_button = |mode: Mode, label: &'static str, icon_name: &'static str| {+ let selected = appearance.mode == mode;+ div()+ .id(label)+ .flex()+ .items_center()+ .gap(px(6.))+ .h(px(28.))+ .px(px(12.))+ .rounded(px(7.))+ .cursor_pointer()+ .text_size(px(12.5))+ .text_color(if selected { theme.text } else { theme.text_muted })+ .when(selected, |d| d.bg(theme.surface).border_1().border_color(theme.border).shadow_sm())+ .when(!selected, |d| d.hover(|st| st.text_color(theme.text)))+ .child(icon(icon_name, 13., if selected { theme.text_accent } else { theme.text_placeholder }))+ .child(label)+ .on_click(cx.listener(move |_, _, window, cx| theme_mod::update_appearance(window, cx, |a, _| a.mode = mode)))+ };+ let grid = |dark: bool, cx: &mut Context<Self>| {+ let chosen = if dark { appearance.dark.clone() } else { appearance.light.clone() };+ let swatches: Vec<AnyElement> = PALETTES.iter().filter(|p| p.dark == dark).map(|p| {+ let id = p.id;+ swatch(theme, p, p.id == chosen, theme.id == p.id).on_click(cx.listener(move |_, _, window, cx| {+ theme_mod::update_appearance(window, cx, |a, system| {+ let system_dark = matches!(system, gpui::WindowAppearance::Dark | gpui::WindowAppearance::VibrantDark);+ if dark {+ a.dark = id.into();+ } else {+ a.light = id.into();+ }+ // Picking a theme you can't currently see switches to it.+ let showing_dark = match a.mode {+ Mode::Dark => true,+ Mode::Light => false,+ Mode::System => system_dark,+ };+ if showing_dark != dark {+ a.mode = if dark { Mode::Dark } else { Mode::Light };+ }+ })+ })).into_any_element()+ }).collect();+ swatch_rows(swatches)+ };+ let modes = [+ mode_button(Mode::System, "System", "monitor").into_any_element(),+ mode_button(Mode::Light, "Light", "circle").into_any_element(),+ mode_button(Mode::Dark, "Dark", "radio").into_any_element(),+ ];+ let dark_grid = grid(true, cx);+ let light_grid = grid(false, cx);+ div()+ .flex()+ .flex_col()+ .gap(px(12.))+ .child(section_title(theme, "Appearance", None))+ .child(+ div()+ .flex()+ .items_center()+ .justify_between()+ .child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child("Follow the system, or pin light or dark. Each has its own theme."))+ .child(+ div()+ .flex()+ .gap(px(2.))+ .p(px(3.))+ .rounded(px(9.))+ .bg(theme.element)+ .border_1()+ .border_color(theme.border_variant)+ .children(modes),+ ),+ )+ .child(kit::label(theme, "Dark themes").text_size(px(12.)).text_color(theme.text_muted))+ .child(dark_grid)+ .child(kit::label(theme, "Light themes").text_size(px(12.)).text_color(theme.text_muted))+ .child(light_grid)+ }++ fn inventory_section(&self, theme: &Theme) -> impl IntoElement {+ let path = self.engine.paths().inventory.clone();+ let reveal = path.clone();+ let shown = self.snapshot.inventory.path.clone();+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Inventory", None))+ .child(+ card(theme)+ .p(px(14.))+ .gap(px(10.))+ .child(div().w_full().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(+ "Machines and the runners they should host live in fleet.toml. OpenRunner edits it when you add machines or install runners, and keeps your comments.",+ ))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().flex_1().truncate().font_family(mono_font()).text_size(px(12.5)).child(shown))+ .when(!self.snapshot.demo, |d| {+ d.child(Button::new("inv-open", "Open").icon("external-link").on_click(move |_, _, cx| cx.open_with_system(&path)))+ .child(Button::new("inv-reveal", "Reveal").icon("folder-open").on_click(move |_, _, cx| cx.reveal_path(&reveal)))+ }),+ ),+ )+ }+}++impl Render for SettingsPage {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let shortcuts = [+ ("⌘R", "Check now"),+ ("⇧⌘R", "Sync GitHub"),+ ("⌘N", "Add machine"),+ ("⌘1 / ⌘2", "Overview / Jobs"),+ ("⌘F or /", "Filter the fleet"),+ ("⌘J", "Toggle activity"),+ ("⌘[ / ⌘]", "Back / forward"),+ ("⌘,", "Settings"),+ ];+ div()+ .id("settings-page")+ .size_full()+ .overflow_y_scroll()+ .track_scroll(&self.scroll)+ .px(px(28.))+ .pt(px(24.))+ .pb(px(40.))+ .child(+ div()+ .w_full()+ .max_w(px(760.))+ .flex()+ .flex_col()+ .gap(px(28.))+ .child(self.github_section(&theme, cx))+ .child(self.appearance_section(&theme, cx))+ .child(self.checks_section(&theme, cx))+ .child(self.inventory_section(&theme))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Keyboard", None))+ .child(card(&theme).px(px(14.)).py(px(6.)).children(shortcuts.iter().map(|(k, what)| {+ div()+ .flex()+ .items_center()+ .justify_between()+ .py(px(5.))+ .text_size(px(12.5))+ .child(div().text_color(theme.text_muted).child(*what))+ .child(kit::kbd(&theme, *k))+ }))),+ ),+ )+ }+}++fn note(_theme: &Theme, icon_name: &'static str, color: gpui::Hsla, text: impl Into<SharedString>) -> impl IntoElement {+ div().flex().items_center().gap(px(8.)).text_size(px(12.5)).child(icon(icon_name, 14., color)).child(text.into())+}++fn hint_line(theme: &Theme, i: usize, hint: String) -> impl IntoElement {+ let copy = hint.clone();+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .pl(px(24.))+ .child(mono(hint).text_size(px(12.)).px(px(6.)).py(px(2.)).rounded(px(4.)).bg(theme.element).text_color(theme.text_muted))+ .child(Button::icon_only(("hint-copy", i), "copy").tooltip("Copy").on_click(move |_, _, cx| {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(copy.clone()))+ }))+}++/// A miniature of the theme: sidebar, a card, the accent and the status colors.+fn swatch(theme: &Theme, p: &Palette, chosen: bool, showing: bool) -> gpui::Stateful<gpui::Div> {+ let t = p.theme();+ let bar = |w: f32, color: gpui::Hsla| div().w(px(w)).h(px(4.)).rounded_full().bg(color);+ div()+ .id(SharedString::from(format!("theme-{}", p.id)))+ .w(px(164.))+ .flex()+ .flex_col()+ .gap(px(7.))+ .cursor_pointer()+ .child(+ div()+ .h(px(78.))+ .flex()+ .rounded(px(10.))+ .overflow_hidden()+ .border_2()+ .border_color(if chosen { theme.accent } else { theme.border_variant })+ .hover(|st| st.border_color(if chosen { theme.accent } else { theme.border }))+ .child(+ div()+ .w(px(36.))+ .h_full()+ .bg(t.sidebar)+ .flex()+ .flex_col()+ .gap(px(5.))+ .px(px(6.))+ .pt(px(10.))+ .child(div().size(px(10.)).rounded(px(3.)).bg(t.accent))+ .child(bar(20., t.text_placeholder.opacity(0.7)))+ .child(bar(16., t.text_placeholder.opacity(0.5)))+ .child(bar(18., t.text_placeholder.opacity(0.5))),+ )+ .child(+ div()+ .flex_1()+ .h_full()+ .bg(t.canvas)+ .p(px(8.))+ .flex()+ .flex_col()+ .gap(px(7.))+ .child(+ div()+ .h(px(30.))+ .rounded(px(6.))+ .bg(t.surface)+ .border_1()+ .border_color(t.border_variant)+ .flex()+ .flex_col()+ .justify_center()+ .gap(px(4.))+ .px(px(7.))+ .child(bar(46., t.text.opacity(0.85)))+ .child(div().flex().gap(px(3.)).child(div().size(px(6.)).rounded(px(1.5)).bg(t.accent)).child(div().size(px(6.)).rounded(px(1.5)).bg(t.success)).child(div().size(px(6.)).rounded(px(1.5)).bg(t.success)).child(div().size(px(6.)).rounded(px(1.5)).border_1().border_color(t.text_placeholder))),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(4.))+ .child(div().size(px(6.)).rounded_full().bg(t.warning))+ .child(div().size(px(6.)).rounded_full().bg(t.error))+ .child(div().size(px(6.)).rounded_full().bg(t.info))+ .child(div().flex_1())+ .child(div().w(px(24.)).h(px(9.)).rounded(px(3.)).bg(t.accent)),+ ),+ ),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .text_size(px(12.))+ .text_color(if chosen { theme.text } else { theme.text_muted })+ .child(p.name)+ .when(showing, |d| d.child(icon("check", 12., theme.text_accent))),+ )+}++/// Swatches in explicit rows of four. A wrapping flex container inside this+/// auto-width column gets measured as a single row and the sections below+/// overlap it.+fn swatch_rows(swatches: Vec<AnyElement>) -> gpui::Div {+ let mut rows = Vec::new();+ let mut iter = swatches.into_iter().peekable();+ while iter.peek().is_some() {+ let row: Vec<AnyElement> = iter.by_ref().take(4).collect();+ rows.push(div().flex().gap(px(12.)).children(row));+ }+ div().flex().flex_col().gap(px(14.)).children(rows)+}diff --git a/src/ui/theme.rs b/src/ui/theme.rsnew file mode 100644index 0000000..f27751a--- /dev/null+++ b/src/ui/theme.rs@@ -0,0 +1,197 @@+//! The active theme, resolved from the user's appearance preference (system,+//! light or dark, plus a chosen light and dark theme) and kept as a GPUI global.++use std::path::PathBuf;+use std::sync::{OnceLock, RwLock};++use gpui::{App, Global, Hsla, Window, WindowAppearance};+use serde::{Deserialize, Serialize};++use super::themes::{self, DEFAULT_DARK, DEFAULT_LIGHT};++pub const UI_FONT: &str = "Geist";+pub const MONO_FONT: &str = "Geist Mono";++/// The fonts of the active theme. Most themes use the bundled Geist; the macOS+/// themes use the system font. Read at render time by `ui_font()` / `mono_font()`.+static FONTS: RwLock<(&str, &str)> = RwLock::new((UI_FONT, MONO_FONT));+/// Picked once: SF Mono when installed, else Menlo, else Geist Mono.+static SYSTEM_MONO: OnceLock<&'static str> = OnceLock::new();++pub fn ui_font() -> &'static str {+ FONTS.read().map(|f| f.0).unwrap_or(UI_FONT)+}++pub fn mono_font() -> &'static str {+ FONTS.read().map(|f| f.1).unwrap_or(MONO_FONT)+}++#[derive(Clone, Copy)]+pub struct Theme {+ pub id: &'static str,+ /// Use the platform's own UI and monospace fonts (the macOS themes).+ pub system_fonts: bool,+ /// The sidebar, which runs the full height of the window.+ pub sidebar: Hsla,+ /// The main content background.+ pub canvas: Hsla,+ /// Cards.+ pub surface: Hsla,+ /// Dialogs, drawers, tooltips.+ pub elevated: Hsla,+ pub border: Hsla,+ pub border_variant: Hsla,+ pub border_focused: Hsla,+ pub element: Hsla,+ pub element_hover: Hsla,+ pub element_selected: Hsla,+ pub ghost_hover: Hsla,+ pub text: Hsla,+ pub text_muted: Hsla,+ pub text_placeholder: Hsla,+ pub text_accent: Hsla,+ pub accent: Hsla,+ pub accent_text: Hsla,+ pub success: Hsla,+ pub warning: Hsla,+ pub error: Hsla,+ pub info: Hsla,+ pub selection: Hsla,+ pub scrim: Hsla,+ pub track: Hsla,+}++impl Global for Theme {}++impl Theme {+ /// Color for a runner state: working, idle, offline, unknown.+ pub fn state(&self, state: &str) -> Hsla {+ match state {+ "working" => self.accent,+ "idle" => self.success,+ _ => self.text_placeholder,+ }+ }++ /// Color for a diagnostic / attention level.+ pub fn level(&self, level: &str) -> Hsla {+ match level {+ "error" => self.error,+ "warning" => self.warning,+ "info" => self.info,+ _ => self.text_placeholder,+ }+ }++ pub fn machine_status(&self, status: &str) -> Hsla {+ match status {+ "online" => self.success,+ "offline" => self.error,+ _ => self.text_placeholder,+ }+ }+}++pub trait ActiveTheme {+ fn theme(&self) -> Theme;+}++impl ActiveTheme for App {+ fn theme(&self) -> Theme {+ *self.global::<Theme>()+ }+}++// ---------------------------------------------------------------------------+// Appearance preference (ui.json)++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Mode {+ System,+ Light,+ Dark,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(default)]+pub struct Appearance {+ pub mode: Mode,+ pub light: String,+ pub dark: String,+ /// Where to save; None in demo mode.+ #[serde(skip)]+ pub path: Option<PathBuf>,+}++impl Default for Appearance {+ fn default() -> Self {+ Appearance { mode: Mode::System, light: DEFAULT_LIGHT.into(), dark: DEFAULT_DARK.into(), path: None }+ }+}++impl Global for Appearance {}++impl Appearance {+ pub fn load(path: Option<PathBuf>) -> Appearance {+ let mut a: Appearance = path+ .as_ref()+ .and_then(|p| std::fs::read_to_string(p).ok())+ .and_then(|t| serde_json::from_str(&t).ok())+ .unwrap_or_default();+ a.path = path;+ a+ }++ fn save(&self) {+ let Some(path) = &self.path else { return };+ match serde_json::to_vec_pretty(self) {+ Ok(bytes) => {+ if let Err(e) = crate::config::write_atomic(path, &bytes) {+ tracing::warn!("saving appearance: {e:#}");+ }+ }+ Err(e) => tracing::warn!("saving appearance: {e}"),+ }+ }++ /// The theme to show given the system's light/dark appearance.+ pub fn resolve(&self, system: WindowAppearance) -> Theme {+ let dark = match self.mode {+ Mode::Dark => true,+ Mode::Light => false,+ Mode::System => matches!(system, WindowAppearance::Dark | WindowAppearance::VibrantDark),+ };+ let (id, fallback) = if dark { (&self.dark, DEFAULT_DARK) } else { (&self.light, DEFAULT_LIGHT) };+ themes::find(id).filter(|p| p.dark == dark).or_else(|| themes::find(fallback)).expect("default themes exist").theme()+ }+}++/// Re-resolves the theme for this window (after a preference or system change).+pub fn apply(window: &Window, cx: &mut App) {+ let theme = cx.global::<Appearance>().resolve(window.appearance());+ let fonts = if theme.system_fonts {+ let mono = *SYSTEM_MONO.get_or_init(|| {+ let names = cx.text_system().all_font_names();+ ["SF Mono", "Menlo"].into_iter().find(|f| names.iter().any(|n| n == f)).unwrap_or(MONO_FONT)+ });+ (".SystemUIFont", mono)+ } else {+ (UI_FONT, MONO_FONT)+ };+ if let Ok(mut f) = FONTS.write() {+ *f = fonts;+ }+ cx.set_global(theme);+}++/// Changes the appearance preference, saves it, and re-themes the window.+pub fn update_appearance(window: &mut Window, cx: &mut App, f: impl FnOnce(&mut Appearance, WindowAppearance)) {+ let system = window.appearance();+ let mut appearance = cx.global::<Appearance>().clone();+ f(&mut appearance, system);+ appearance.save();+ cx.set_global(appearance);+ apply(window, cx);+ window.refresh();+}diff --git a/src/ui/themes.rs b/src/ui/themes.rsnew file mode 100644index 0000000..699a765--- /dev/null+++ b/src/ui/themes.rs@@ -0,0 +1,267 @@+//! Built-in color themes. Each is a small palette of base colors; hover,+//! selection and track colors are derived so every theme behaves the same.++use gpui::{Hsla, Rgba, black, rgba};++use super::theme::Theme;++pub struct Palette {+ pub id: &'static str,+ pub name: &'static str,+ pub dark: bool,+ /// Use the platform's UI font instead of the bundled Geist.+ pub system_fonts: bool,+ pub sidebar: u32,+ pub canvas: u32,+ pub surface: u32,+ pub elevated: u32,+ pub border: u32,+ pub border_variant: u32,+ pub text: u32,+ pub text_muted: u32,+ pub text_placeholder: u32,+ /// Brand color; also the "working" state.+ pub accent: u32,+ /// Also the "idle" state.+ pub success: u32,+ pub warning: u32,+ pub error: u32,+ pub info: u32,+}++macro_rules! palette {+ ($id:literal, $name:literal, $dark:literal,+ sidebar $sidebar:literal, canvas $canvas:literal, surface $surface:literal, elevated $elevated:literal,+ border $border:literal, $border_variant:literal,+ text $text:literal, $muted:literal, $placeholder:literal,+ accent $accent:literal, success $success:literal, warning $warning:literal, error $error:literal, info $info:literal) => {+ Palette {+ id: $id,+ name: $name,+ dark: $dark,+ system_fonts: false,+ sidebar: $sidebar,+ canvas: $canvas,+ surface: $surface,+ elevated: $elevated,+ border: $border,+ border_variant: $border_variant,+ text: $text,+ text_muted: $muted,+ text_placeholder: $placeholder,+ accent: $accent,+ success: $success,+ warning: $warning,+ error: $error,+ info: $info,+ }+ };+}++pub const DEFAULT_DARK: &str = "graphite";+pub const DEFAULT_LIGHT: &str = "paper";++pub static PALETTES: &[Palette] = &[+ // --- Dark ---------------------------------------------------------------+ palette!("graphite", "OpenRunner Graphite", true,+ sidebar 0x0f1013, canvas 0x15161a, surface 0x1b1c21, elevated 0x202127, border 0x2b2d35, 0x24262d,+ text 0xececf1, 0xa2a4ae, 0x6c6f7b,+ accent 0x8b7cff, success 0x4ad6a7, warning 0xf2b347, error 0xff6b6b, info 0x6cb8ff),+ // Apple's dark Aqua: system blue accent, graphite surfaces, SF fonts.+ Palette {+ id: "macos-dark",+ name: "macOS Dark",+ dark: true,+ system_fonts: true,+ sidebar: 0x2a2a2c,+ canvas: 0x1e1e1e,+ surface: 0x282828,+ elevated: 0x2c2c2e,+ border: 0x3d3d3f,+ border_variant: 0x333335,+ text: 0xf5f5f7,+ text_muted: 0xa1a1a6,+ text_placeholder: 0x6e6e73,+ accent: 0x0a84ff,+ success: 0x30d158,+ warning: 0xff9f0a,+ error: 0xff453a,+ info: 0x40c8e0,+ },+ palette!("gruvbox-dark", "Gruvbox Dark", true,+ sidebar 0x1d2021, canvas 0x282828, surface 0x32302f, elevated 0x3c3836, border 0x504945, 0x3c3836,+ text 0xebdbb2, 0xbdae93, 0x928374,+ accent 0xfe8019, success 0xb8bb26, warning 0xfabd2f, error 0xfb4934, info 0x83a598),+ palette!("catppuccin-mocha", "Catppuccin Mocha", true,+ sidebar 0x181825, canvas 0x1e1e2e, surface 0x262637, elevated 0x313244, border 0x45475a, 0x313244,+ text 0xcdd6f4, 0xa6adc8, 0x7f849c,+ accent 0xcba6f7, success 0xa6e3a1, warning 0xf9e2af, error 0xf38ba8, info 0x89b4fa),+ palette!("catppuccin-macchiato", "Catppuccin Macchiato", true,+ sidebar 0x1e2030, canvas 0x24273a, surface 0x2b2f44, elevated 0x363a4f, border 0x494d64, 0x363a4f,+ text 0xcad3f5, 0xa5adcb, 0x8087a2,+ accent 0xc6a0f6, success 0xa6da95, warning 0xeed49f, error 0xed8796, info 0x8aadf4),+ palette!("catppuccin-frappe", "Catppuccin Frappé", true,+ sidebar 0x292c3c, canvas 0x303446, surface 0x383c50, elevated 0x414559, border 0x51576d, 0x414559,+ text 0xc6d0f5, 0xa5adce, 0x838ba7,+ accent 0xca9ee6, success 0xa6d189, warning 0xe5c890, error 0xe78284, info 0x8caaee),+ palette!("tokyo-night", "Tokyo Night", true,+ sidebar 0x16161e, canvas 0x1a1b26, surface 0x1f2335, elevated 0x24283b, border 0x3b4261, 0x292e42,+ text 0xc0caf5, 0xa9b1d6, 0x565f89,+ accent 0x7aa2f7, success 0x9ece6a, warning 0xe0af68, error 0xf7768e, info 0x7dcfff),+ palette!("nord", "Nord", true,+ sidebar 0x2a2f3a, canvas 0x2e3440, surface 0x343a48, elevated 0x3b4252, border 0x4c566a, 0x3b4252,+ text 0xeceff4, 0xd8dee9, 0x7b88a1,+ accent 0x88c0d0, success 0xa3be8c, warning 0xebcb8b, error 0xbf616a, info 0x81a1c1),+ palette!("rose-pine", "Rosé Pine", true,+ sidebar 0x1f1d2e, canvas 0x191724, surface 0x1f1d2e, elevated 0x26233a, border 0x403d52, 0x26233a,+ text 0xe0def4, 0x908caa, 0x6e6a86,+ accent 0xc4a7e7, success 0x9ccfd8, warning 0xf6c177, error 0xeb6f92, info 0xebbcba),+ palette!("solarized-dark", "Solarized Dark", true,+ sidebar 0x00252f, canvas 0x002b36, surface 0x073642, elevated 0x0a3d4a, border 0x2a525c, 0x0d3f4b,+ text 0xe2ded0, 0x93a1a1, 0x657b83,+ accent 0x268bd2, success 0x859900, warning 0xb58900, error 0xdc322f, info 0x2aa198),+ palette!("dracula", "Dracula", true,+ sidebar 0x21222c, canvas 0x282a36, surface 0x2e303e, elevated 0x343746, border 0x44475a, 0x343746,+ text 0xf8f8f2, 0xbfc0cc, 0x6272a4,+ accent 0xbd93f9, success 0x50fa7b, warning 0xffb86c, error 0xff5555, info 0x8be9fd),+ palette!("everforest-dark", "Everforest Dark", true,+ sidebar 0x232a2e, canvas 0x2d353b, surface 0x343f44, elevated 0x3d484d, border 0x475258, 0x3d484d,+ text 0xd3c6aa, 0x9da9a0, 0x7a8478,+ accent 0x7fbbb3, success 0xa7c080, warning 0xdbbc7f, error 0xe67e80, info 0x83c092),+ palette!("kanagawa-wave", "Kanagawa Wave", true,+ sidebar 0x16161d, canvas 0x1f1f28, surface 0x2a2a37, elevated 0x363646, border 0x54546d, 0x363646,+ text 0xdcd7ba, 0xc8c093, 0x727169,+ accent 0x7e9cd8, success 0x98bb6c, warning 0xe6c384, error 0xe46876, info 0x7fb4ca),+ palette!("github-dark", "GitHub Dark", true,+ sidebar 0x010409, canvas 0x0d1117, surface 0x161b22, elevated 0x1c2128, border 0x30363d, 0x21262d,+ text 0xe6edf3, 0x9198a1, 0x6e7681,+ accent 0x4493f8, success 0x3fb950, warning 0xd29922, error 0xf85149, info 0x58a6ff),+ // --- Light --------------------------------------------------------------+ palette!("paper", "OpenRunner Paper", false,+ sidebar 0xf0f0f3, canvas 0xfafafb, surface 0xffffff, elevated 0xffffff, border 0xe2e2e8, 0xebebf0,+ text 0x16171c, 0x5c5f6a, 0x8c8f9a,+ accent 0x6d5cf6, success 0x12a27a, warning 0xc8870e, error 0xe5484d, info 0x2f80ed),+ // Apple's light Aqua, like System Settings: white grouped boxes on a light grey window.+ Palette {+ id: "macos-light",+ name: "macOS Light",+ dark: false,+ system_fonts: true,+ sidebar: 0xe8e8ea,+ canvas: 0xf5f5f7,+ surface: 0xffffff,+ elevated: 0xffffff,+ border: 0xd2d2d7,+ border_variant: 0xe3e3e6,+ text: 0x1d1d1f,+ text_muted: 0x6e6e73,+ text_placeholder: 0xa1a1a6,+ accent: 0x007aff,+ success: 0x28c840,+ warning: 0xff9500,+ error: 0xff3b30,+ info: 0x30b0c7,+ },+ palette!("gruvbox-light", "Gruvbox Light", false,+ sidebar 0xf2e5bc, canvas 0xfbf1c7, surface 0xf9f5d7, elevated 0xf9f5d7, border 0xd5c4a1, 0xebdbb2,+ text 0x3c3836, 0x665c54, 0x928374,+ accent 0xaf3a03, success 0x79740e, warning 0xb57614, error 0x9d0006, info 0x076678),+ palette!("catppuccin-latte", "Catppuccin Latte", false,+ sidebar 0xe6e9ef, canvas 0xeff1f5, surface 0xf7f8fb, elevated 0xffffff, border 0xccd0da, 0xdce0e8,+ text 0x4c4f69, 0x6c6f85, 0x8c8fa1,+ accent 0x8839ef, success 0x40a02b, warning 0xdf8e1d, error 0xd20f39, info 0x1e66f5),+ palette!("tokyo-night-day", "Tokyo Night Day", false,+ sidebar 0xd6d8df, canvas 0xe1e2e7, surface 0xe9e9ed, elevated 0xf2f2f5, border 0xc4c8da, 0xd0d3de,+ text 0x3760bf, 0x6172b0, 0x848cb5,+ accent 0x2e7de9, success 0x587539, warning 0x8c6c3e, error 0xf52a65, info 0x007197),+ palette!("nord-light", "Nord Light", false,+ sidebar 0xe5e9f0, canvas 0xeceff4, surface 0xf5f7fa, elevated 0xffffff, border 0xd8dee9, 0xe5e9f0,+ text 0x2e3440, 0x4c566a, 0x7b88a1,+ accent 0x5e81ac, success 0x6a8e4f, warning 0xc49b3a, error 0xbf616a, info 0x81a1c1),+ palette!("rose-pine-dawn", "Rosé Pine Dawn", false,+ sidebar 0xf2e9e1, canvas 0xfaf4ed, surface 0xfffaf3, elevated 0xfffaf3, border 0xdfdad9, 0xf2e9e1,+ text 0x575279, 0x797593, 0x9893a5,+ accent 0x907aa9, success 0x56949f, warning 0xea9d34, error 0xb4637a, info 0x286983),+ palette!("solarized-light", "Solarized Light", false,+ sidebar 0xeee8d5, canvas 0xfdf6e3, surface 0xf8f1dd, elevated 0xfdf6e3, border 0xe0d9c4, 0xeee8d5,+ text 0x073642, 0x586e75, 0x93a1a1,+ accent 0x268bd2, success 0x859900, warning 0xb58900, error 0xdc322f, info 0x2aa198),+ palette!("everforest-light", "Everforest Light", false,+ sidebar 0xf4f0d9, canvas 0xfdf6e3, surface 0xfffbef, elevated 0xfffbef, border 0xe0dcc7, 0xefebd4,+ text 0x5c6a72, 0x829181, 0xa6b0a0,+ accent 0x3a94c5, success 0x8da101, warning 0xdfa000, error 0xf85552, info 0x35a77c),+ palette!("kanagawa-lotus", "Kanagawa Lotus", false,+ sidebar 0xe5ddb0, canvas 0xf2ecbc, surface 0xf7f2cf, elevated 0xf9f5d8, border 0xd5cea3, 0xe4dcb2,+ text 0x545464, 0x716e61, 0x8a8980,+ accent 0x4d699b, success 0x6f894e, warning 0xcc6d00, error 0xc84053, info 0x597b75),+ palette!("github-light", "GitHub Light", false,+ sidebar 0xf6f8fa, canvas 0xffffff, surface 0xffffff, elevated 0xffffff, border 0xd0d7de, 0xd8dee4,+ text 0x1f2328, 0x59636e, 0x818b98,+ accent 0x0969da, success 0x1a7f37, warning 0x9a6700, error 0xd1242f, info 0x0969da),+];++pub fn find(id: &str) -> Option<&'static Palette> {+ PALETTES.iter().find(|p| p.id == id)+}++fn color(hex: u32) -> Hsla {+ let rgba: Rgba = rgba((hex << 8) | 0xff);+ rgba.into()+}++/// Perceived brightness, 0..1, for picking readable text on a colored fill.+fn luminance(c: Hsla) -> f32 {+ let rgba: Rgba = c.into();+ 0.2126 * rgba.r + 0.7152 * rgba.g + 0.0722 * rgba.b+}++impl Palette {+ pub fn theme(&self) -> Theme {+ let text = color(self.text);+ let accent = color(self.accent);+ let dark = self.dark;+ Theme {+ id: self.id,+ system_fonts: self.system_fonts,+ sidebar: color(self.sidebar),+ canvas: color(self.canvas),+ surface: color(self.surface),+ elevated: color(self.elevated),+ border: color(self.border),+ border_variant: color(self.border_variant),+ border_focused: accent,+ element: text.opacity(if dark { 0.05 } else { 0.035 }),+ element_hover: text.opacity(if dark { 0.09 } else { 0.065 }),+ element_selected: accent.opacity(if dark { 0.18 } else { 0.13 }),+ ghost_hover: text.opacity(if dark { 0.06 } else { 0.05 }),+ text,+ text_muted: color(self.text_muted),+ text_placeholder: color(self.text_placeholder),+ text_accent: accent,+ accent,+ accent_text: if luminance(accent) > 0.55 { color(self.canvas).blend(black().opacity(0.4)) } else { gpui::white() },+ success: color(self.success),+ warning: color(self.warning),+ error: color(self.error),+ info: color(self.info),+ selection: accent.opacity(0.3),+ scrim: black().opacity(if dark { 0.55 } else { 0.22 }),+ track: text.opacity(if dark { 0.1 } else { 0.08 }),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ids_are_unique_and_defaults_exist() {+ let mut ids: Vec<_> = PALETTES.iter().map(|p| p.id).collect();+ ids.sort();+ ids.dedup();+ assert_eq!(ids.len(), PALETTES.len());+ assert!(find(DEFAULT_DARK).is_some_and(|p| p.dark));+ assert!(find(DEFAULT_LIGHT).is_some_and(|p| !p.dark));+ }+}diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rsnew file mode 100644index 0000000..0ebe4a4--- /dev/null+++ b/src/ui/workspaces.rs@@ -0,0 +1,540 @@+//! Agent workspaces: folders on fleet machines that agents check out as their+//! work environment. Lists them, shows what agents ran, and lets you step in.++use std::collections::HashSet;++use gpui::{AnyElement, ClipboardItem, Context, FontWeight, SharedString, div, prelude::*, px};++use super::format;+use super::kit::{self, Button, ButtonStyle, card, icon, kv, section_title};+use super::overview::{callout, page};+use super::root::{Root, Route};+use super::theme::{ActiveTheme, mono_font, Theme};+use crate::fleet::model::{WorkspaceCommand, WorkspaceInfo};++/// Per-view state for the workspace pages, kept on the root view.+#[derive(Default)]+pub struct WorkspaceUi {+ /// Loaded `git status` + diff per workspace id.+ pub changes: std::collections::HashMap<String, Result<String, String>>,+ pub loading_changes: HashSet<String>,+ /// History entries whose output is expanded: (workspace id, command index).+ pub expanded: HashSet<(String, usize)>,+}++impl Root {+ pub(super) fn render_workspaces(&mut self, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let rows: Vec<AnyElement> = s.workspaces.iter().map(|w| self.workspace_card(&theme, w, cx)).collect();+ let allowed = s.machines.iter().filter(|m| m.workspaces_allowed).count();++ page("workspaces-page", &self.page_scroll)+ .child(+ div()+ .flex()+ .items_start()+ .justify_between()+ .gap(px(20.))+ .child(+ div().flex().flex_col().flex_1().min_w(px(0.)).max_w(px(760.)).gap(px(4.)).child(+ div().text_size(px(12.5)).text_color(theme.text_muted).child(+ "A workspace is a folder on one of your machines, optionally a git checkout, that an agent uses as its work environment: it runs commands, edits files and syncs code there. Workspaces persist until destroyed.",+ ),+ ).child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!(+ "{allowed} of {} machines accept workspaces. Agents create them with the workspace_create MCP tool or `openrunner workspace create`.",+ s.machines.len()+ ))),+ )+ .child(+ Button::new("ws-new", "New workspace")+ .icon("plus")+ .style(ButtonStyle::Primary)+ .on_click(cx.listener(|this, _, window, cx| this.show_new_workspace(None, window, cx))),+ ),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Workspaces", Some(s.workspaces.len())))+ .children(rows)+ .when(s.workspaces.is_empty(), |d| {+ d.child(card(&theme).child(kit::empty_state(&theme, "terminal", "No workspaces yet. Ask an agent to create one, or make one here.")))+ }),+ )+ }++ fn workspace_card(&self, theme: &Theme, w: &WorkspaceInfo, cx: &mut Context<Self>) -> AnyElement {+ let id = w.id.clone();+ let shell = w.shell.clone();+ let last = w.history.last();+ div()+ .id(SharedString::from(format!("wscard-{}", w.id)))+ .flex()+ .flex_col()+ .gap(px(12.))+ .p(px(16.))+ .rounded(px(12.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .cursor_pointer()+ .hover(|st| st.border_color(theme.accent.opacity(0.55)))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(+ div()+ .size(px(32.))+ .flex_none()+ .rounded(px(8.))+ .bg(theme.accent.opacity(0.14))+ .flex()+ .items_center()+ .justify_center()+ .child(icon("terminal", 15., theme.text_accent)),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().truncate().text_size(px(14.)).font_weight(FontWeight::MEDIUM).child(w.name.clone()))+ .child(div().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(w.id.clone())),+ )+ .child(div().truncate().text_size(px(12.)).text_color(theme.text_muted).child(workspace_subtitle(w))),+ )+ .when(w.isolation == "docker", |d| d.child(docker_pill(theme, w)))+ .children(w.owner.clone().map(|o| kit::pill(o, theme.info)))+ .child(status_pill(theme, w))+ .child(+ Button::icon_only(SharedString::from(format!("ws-copy-{}", w.id)), "copy")+ .tooltip("Copy shell command")+ .on_click(move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new_string(shell.clone()))),+ ),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(10.))+ .py(px(7.))+ .rounded(px(8.))+ .bg(theme.sidebar)+ .font_family(mono_font())+ .text_size(px(12.))+ .child(div().text_color(theme.text_placeholder).child("$"))+ .child(div().flex_1().min_w(px(0.)).truncate().text_color(if last.is_some() { theme.text } else { theme.text_placeholder }).child(+ last.map(|c| c.command.clone()).unwrap_or_else(|| "no commands yet".into()),+ ))+ .children(last.map(|c| exit_badge(theme, c))),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(14.))+ .text_size(px(11.5))+ .text_color(theme.text_placeholder)+ .child(format!("{} command{}", w.commands, if w.commands == 1 { "" } else { "s" }))+ .child(format!("used {}", format::ago(Some(w.last_used_at))))+ .child(format!("created {}", format::ago(Some(w.created_at))))+ .child(div().flex_1())+ .child(div().truncate().font_family(mono_font()).child(w.path.clone())),+ )+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Workspace(id.clone()), window, cx)))+ .into_any_element()+ }++ pub(super) fn render_workspace(&mut self, id: &str, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let Some(w) = s.workspaces.iter().find(|w| w.id == id).cloned() else {+ return div()+ .size_full()+ .flex()+ .items_center()+ .justify_center()+ .text_color(theme.text_placeholder)+ .child("This workspace was destroyed.")+ .into_any_element();+ };+ let shell = w.shell.clone();+ let path = w.path.clone();+ let machine_id = w.machine_id.clone();++ let header = div()+ .flex()+ .items_start()+ .justify_between()+ .gap(px(16.))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(6.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(w.name.clone()))+ .child(div().font_family(mono_font()).text_size(px(12.)).text_color(theme.text_placeholder).child(w.id.clone()))+ .when(w.isolation == "docker", |d| d.child(docker_pill(&theme, &w)))+ .child(status_pill(&theme, &w)),+ )+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(workspace_subtitle(&w))),+ )+ .child(+ div()+ .flex()+ .gap(px(6.))+ .child(+ Button::new("ws-copy-shell", "Copy shell command")+ .icon("terminal")+ .on_click(move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new_string(shell.clone()))),+ )+ .child({+ let wid = w.id.clone();+ Button::new("ws-changes", "Changes")+ .icon("git-branch")+ .loading(self.ws_ui.loading_changes.contains(&w.id))+ .on_click(cx.listener(move |this, _, _, cx| this.load_workspace_changes(&wid, cx)))+ })+ .child({+ let wid = w.id.clone();+ let name = w.name.clone();+ Button::icon_only("ws-destroy", "trash-2")+ .style(ButtonStyle::Danger)+ .tooltip("Destroy workspace")+ .disabled(w.status == "destroying")+ .on_click(cx.listener(move |this, _, window, cx| this.confirm_destroy_workspace(&wid, &name, window, cx)))+ }),+ );++ let details = card(&theme)+ .px(px(14.))+ .py(px(8.))+ .child(kv(+ &theme,+ "Machine",+ div()+ .id("ws-machine-link")+ .flex()+ .items_center()+ .gap(px(6.))+ .cursor_pointer()+ .text_color(theme.text_accent)+ .child(w.machine_name.clone())+ .child(div().font_family(mono_font()).text_color(theme.text_placeholder).child(format!("{} · {}", w.host, w.platform)))+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(machine_id.clone()), window, cx))),+ ))+ .child(kv(+ &theme,+ "Folder",+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .child(kit::mono(w.path.clone()))+ .child(Button::icon_only("ws-copy-path", "copy").tooltip("Copy path").on_click(move |_, _, cx| {+ cx.write_to_clipboard(ClipboardItem::new_string(path.clone()))+ })),+ ))+ .child(kv(+ &theme,+ "Environment",+ if w.isolation == "docker" {+ kit::mono(format!(+ "Docker · {}{}",+ w.image.clone().unwrap_or_default(),+ w.container.as_ref().map(|c| format!(" · {c}")).unwrap_or_default()+ ))+ .into_any_element()+ } else {+ div().child("Directly on the machine").into_any_element()+ },+ ))+ .children(w.repo.clone().map(|r| kv(&theme, "Repository", kit::mono(r))))+ .children(w.git_ref.clone().map(|r| kv(&theme, "Checked out", kit::mono(r))))+ .children(w.branch.clone().map(|b| kv(&theme, "Branch", kit::mono(b))))+ .children(w.owner.clone().map(|o| kv(&theme, "Created by", o)))+ .child(kv(&theme, "Created", format!("{} · last used {}", format::ago(Some(w.created_at)), format::ago(Some(w.last_used_at)))));++ let mut body = page("workspace-page", &self.page_scroll).child(header);+ if let Some(err) = &w.error {+ body = body.child(callout(&theme, "error", "Workspace error", err.clone(), None));+ }+ body = body.child(details);++ if let Some(result) = self.ws_ui.changes.get(&w.id) {+ let (text, failed) = match result {+ Ok(t) => (t.clone(), false),+ Err(e) => (e.clone(), true),+ };+ body = body.child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Changes", None))+ .child(+ card(&theme)+ .p(px(12.))+ .font_family(mono_font())+ .text_size(px(11.5))+ .line_height(px(18.))+ .children(text.lines().take(400).map(|l| diff_line(&theme, l, failed))),+ ),+ );+ }++ let history: Vec<AnyElement> =+ w.history.iter().enumerate().rev().map(|(i, c)| self.history_row(&theme, &w.id, i, c, cx)).collect();+ body.child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Commands", Some(w.commands)))+ .child(+ card(&theme)+ .children(history)+ .when(w.history.is_empty(), |d| d.child(kit::empty_state(&theme, "terminal", "Nothing has run here yet."))),+ ),+ )+ .into_any_element()+ }++ fn history_row(&self, theme: &Theme, ws: &str, i: usize, c: &WorkspaceCommand, cx: &mut Context<Self>) -> AnyElement {+ let key = (ws.to_string(), i);+ let open = self.ws_ui.expanded.contains(&key);+ let toggle = key.clone();+ div()+ .id(SharedString::from(format!("wsh-{ws}-{i}")))+ .flex()+ .flex_col()+ .border_b_1()+ .border_color(theme.border_variant)+ .child(+ div()+ .id(SharedString::from(format!("wsh-head-{ws}-{i}")))+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(14.))+ .py(px(8.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 12., theme.text_placeholder))+ .child(div().flex_1().min_w(px(0.)).truncate().font_family(mono_font()).text_size(px(12.5)).child(c.command.clone()))+ .children(c.by.clone().map(|b| div().text_size(px(11.)).text_color(theme.text_placeholder).child(b)))+ .child(div().w(px(64.)).flex_none().text_size(px(11.5)).text_color(theme.text_placeholder).child(if c.background {+ "background".to_string()+ } else {+ crate::util::short_duration(c.duration_ms / 1000)+ }))+ .child(div().w(px(70.)).flex_none().text_size(px(11.5)).text_color(theme.text_placeholder).child(format::ago(Some(c.started_at))))+ .child(exit_badge(theme, c))+ .on_click(cx.listener(move |this, _, _, cx| {+ if !this.ws_ui.expanded.remove(&toggle) {+ this.ws_ui.expanded.insert(toggle.clone());+ }+ cx.notify()+ })),+ )+ .when(open, |d| {+ d.child(+ div()+ .mx(px(14.))+ .mb(px(10.))+ .p(px(10.))+ .rounded(px(8.))+ .bg(theme.sidebar)+ .font_family(mono_font())+ .text_size(px(11.5))+ .line_height(px(17.))+ .text_color(theme.text_muted)+ .children(c.output_tail.iter().map(|l| div().child(l.clone())))+ .when(c.output_tail.is_empty(), |d| d.child(div().text_color(theme.text_placeholder).child("(no output)"))),+ )+ })+ .into_any_element()+ }++ /// The machine page's list of workspaces, plus the switch that allows them.+ pub(super) fn machine_workspaces(&self, theme: &Theme, s: &crate::fleet::model::Snapshot, m: &crate::fleet::model::Machine, cx: &mut Context<Self>) -> AnyElement {+ let mine: Vec<&WorkspaceInfo> = s.workspaces.iter().filter(|w| w.machine_id == m.id).collect();+ let rows: Vec<AnyElement> = mine+ .iter()+ .enumerate()+ .map(|(i, w)| {+ let id = w.id.clone();+ div()+ .id(SharedString::from(format!("mws-{}", w.id)))+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(14.))+ .py(px(9.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(icon("terminal", 13., theme.text_accent))+ .child(div().text_size(px(13.)).child(w.name.clone()))+ .child(div().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(w.id.clone()))+ .child(div().flex_1())+ .children(w.owner.clone().map(|o| div().text_size(px(11.5)).text_color(theme.text_placeholder).child(o)))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("used {}", format::ago(Some(w.last_used_at)))))+ .child(status_pill(theme, w))+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Workspace(id.clone()), window, cx)))+ .into_any_element()+ })+ .collect();+ let machine_id = m.id.clone();+ let new_on = m.id.clone();+ let allowed = m.workspaces_allowed;+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(+ div()+ .flex()+ .items_center()+ .justify_between()+ .child(section_title(theme, "Agent workspaces", Some(mine.len())))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(12.))+ .child(kit::checkbox(theme, "ws-allow", allowed, "Allow agents to create workspaces here", cx.listener(move |this, value: &bool, _, cx| {+ if let Err(e) = this.engine.set_workspaces_allowed(&machine_id, *value) {+ this.notify_user(e, true, cx);+ }+ })))+ .child(+ Button::new("ws-new-here", "New workspace")+ .icon("plus")+ .disabled(!allowed)+ .on_click(cx.listener(move |this, _, window, cx| this.show_new_workspace(Some(new_on.clone()), window, cx))),+ ),+ ),+ )+ .child(if rows.is_empty() {+ card(theme)+ .child(kit::empty_state(+ theme,+ "terminal",+ if allowed { "No workspaces here. Agents create them with workspace_create." } else { "Agents can't create workspaces on this machine." },+ ))+ .into_any_element()+ } else {+ card(theme).children(rows).into_any_element()+ })+ .into_any_element()+ }++ fn load_workspace_changes(&mut self, id: &str, cx: &mut Context<Self>) {+ if !self.ws_ui.loading_changes.insert(id.to_string()) {+ return;+ }+ cx.notify();+ let engine = self.engine.clone();+ let wid = id.to_string();+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ let wid = wid.clone();+ async move { engine.workspace_changes(&wid).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| {+ this.ws_ui.loading_changes.remove(&wid);+ this.ws_ui.changes.insert(wid, result);+ cx.notify()+ });+ });+ self.track(task);+ }+}++fn workspace_subtitle(w: &WorkspaceInfo) -> String {+ let mut parts = vec![w.machine_name.clone()];+ if let Some(repo) = &w.repo {+ let at = w.branch.as_ref().or(w.git_ref.as_ref()).map(|r| format!(" @ {r}")).unwrap_or_default();+ parts.push(format!("{repo}{at}"));+ }+ parts.join(" · ")+}++fn status_pill(theme: &Theme, w: &WorkspaceInfo) -> AnyElement {+ match w.status.as_str() {+ "ready" => kit::pill("ready", theme.success).into_any_element(),+ "creating" => div()+ .flex()+ .items_center()+ .gap(px(5.))+ .child(kit::spinner(SharedString::from(format!("ws-spin-{}", w.id)), 11., theme.accent))+ .child(kit::pill("creating", theme.accent))+ .into_any_element(),+ "destroying" => kit::pill("destroying", theme.warning).into_any_element(),+ _ => kit::pill("failed", theme.error).into_any_element(),+ }+}++fn exit_badge(theme: &Theme, c: &WorkspaceCommand) -> AnyElement {+ let (text, color) = match (c.exit_code, c.timed_out, c.background) {+ (_, true, _) => ("timed out".to_string(), theme.warning),+ (_, _, true) => ("bg".to_string(), theme.info),+ (Some(0), _, _) => ("0".to_string(), theme.success),+ (Some(code), _, _) => (code.to_string(), theme.error),+ (None, _, _) => ("…".to_string(), theme.text_placeholder),+ };+ div()+ .flex_none()+ .min_w(px(28.))+ .px(px(6.))+ .h(px(18.))+ .flex()+ .items_center()+ .justify_center()+ .rounded(px(4.))+ .bg(color.opacity(0.14))+ .text_color(color)+ .font_family(mono_font())+ .text_size(px(11.))+ .child(text)+ .into_any_element()+}++fn diff_line(theme: &Theme, line: &str, failed: bool) -> AnyElement {+ let color = if failed {+ theme.error+ } else if line.starts_with('+') && !line.starts_with("+++") {+ theme.success+ } else if line.starts_with('-') && !line.starts_with("---") {+ theme.error+ } else if line.starts_with("@@") || line.starts_with("##") {+ theme.text_accent+ } else {+ theme.text_muted+ };+ div().text_color(color).child(line.to_string()).into_any_element()+}++fn docker_pill(theme: &Theme, w: &WorkspaceInfo) -> AnyElement {+ kit::pill(format!("docker · {}", w.image.clone().unwrap_or_else(|| "container".into())), theme.info).into_any_element()+}diff --git a/src/util.rs b/src/util.rsnew file mode 100644index 0000000..2c72f69--- /dev/null+++ b/src/util.rs@@ -0,0 +1,87 @@+/// "Mac Studio (M2)" -> "mac-studio-m2"+pub fn slug(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for c in s.chars() {+ if c.is_ascii_alphanumeric() {+ out.push(c.to_ascii_lowercase());+ } else if !out.ends_with('-') && !out.is_empty() {+ out.push('-');+ }+ }+ let out = out.trim_end_matches('-').to_string();+ if out.is_empty() { "machine".into() } else { out }+}++/// ("Darwin", "arm64") -> "darwin-arm64", ("Linux", "x86_64") -> "linux-x64", ("windows", "AMD64") -> "windows-x64"+pub fn platform(os: &str, arch: &str) -> String {+ let os = os.trim().to_ascii_lowercase();+ let arch = match arch.trim().to_ascii_lowercase().as_str() {+ "arm64" | "aarch64" => "arm64".to_string(),+ "x86_64" | "amd64" | "x64" => "x64".to_string(),+ "i386" | "i686" | "x86" => "x86".to_string(),+ a if a.starts_with("armv7") || a == "arm" => "arm".to_string(),+ a => a.to_string(),+ };+ match (os.is_empty(), arch.is_empty()) {+ (true, _) => String::new(),+ (false, true) => os,+ (false, false) => format!("{os}-{arch}"),+ }+}++/// 381_000_000_000 -> "381 GB" (decimal units, like Finder and `df -H`)+pub fn bytes(n: u64) -> String {+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];+ let mut v = n as f64;+ let mut unit = 0;+ while v >= 1000.0 && unit < UNITS.len() - 1 {+ v /= 1000.0;+ unit += 1;+ }+ if v < 10.0 && unit > 0 { format!("{v:.1} {}", UNITS[unit]) } else { format!("{v:.0} {}", UNITS[unit]) }+}++/// 83_400 -> "23h 10m", 10_022_400 -> "116d 0h", 95 -> "1m"+pub fn uptime(secs: u64) -> String {+ let (d, h, m) = (secs / 86_400, (secs % 86_400) / 3600, (secs % 3600) / 60);+ if d > 0 {+ format!("{d}d {h}h")+ } else if h > 0 {+ format!("{h}h {m}m")+ } else {+ format!("{m}m")+ }+}++/// 42 -> "42s", 754 -> "12m", 5400 -> "1h 30m"+pub fn short_duration(secs: u64) -> String {+ if secs < 60 {+ format!("{secs}s")+ } else if secs < 3600 {+ format!("{}m", secs / 60)+ } else if secs < 86_400 {+ let (h, m) = (secs / 3600, (secs % 3600) / 60);+ if m == 0 { format!("{h}h") } else { format!("{h}h {m}m") }+ } else {+ format!("{}d", secs / 86_400)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn formats() {+ assert_eq!(slug("Mac Studio (M2)"), "mac-studio-m2");+ assert_eq!(slug(" -- "), "machine");+ assert_eq!(platform("Darwin", "arm64"), "darwin-arm64");+ assert_eq!(platform("linux", "x86_64"), "linux-x64");+ assert_eq!(platform("windows", "AMD64"), "windows-x64");+ assert_eq!(bytes(381_000_000_000), "381 GB");+ assert_eq!(bytes(6_800_000_000), "6.8 GB");+ assert_eq!(uptime(83_400), "23h 10m");+ assert_eq!(uptime(116 * 86_400), "116d 0h");+ assert_eq!(short_duration(754), "12m");+ }+}