Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(macrod): add interactive quickstart (#6137)
Wolf Mermelsteinf087648d0042
diff --git a/.gitignore b/.gitignoreindex 816de9dfc2..7464c83384 100644--- a/.gitignore+++ b/.gitignore@@ -41,8 +41,6 @@ infra/local/generated/# crates/cursor_acp/fixtures/real/ before committing one./recordings/-# Per-developer macrod daemon config and the state files it writes next to-# it (the credentials file holds this machine's harness bearer token).-/macro.toml-/macro.credentials.json-/macro.webhook-state.json+# Per-developer macrod config contains this machine's harness bearer token.+/macrod.toml+/macrod.webhook-state.jsondiff --git a/Cargo.lock b/Cargo.lockindex 27418003cf..91d68e373e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -943,6 +943,24 @@ dependencies = ["derive_arbitrary",]+[[package]]+name = "arboard"+version = "3.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"+dependencies = [+ "clipboard-win",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "parking_lot",+ "percent-encoding",+ "windows-sys 0.59.0",+ "wl-clipboard-rs",+ "x11rb",+]+[[package]]name = "arc-swap"version = "1.9.2"@@ -3520,6 +3538,15 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"+[[package]]+name = "clipboard-win"+version = "5.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"+dependencies = [+ "error-code",+]+[[package]]name = "cloudfront_sign"version = "0.3.0"@@ -3564,6 +3591,7 @@ dependencies = ["agent_runtime_protocol","agent_session","agent_trigger",+ "arboard","bot_id","channel_sender","channels",@@ -3575,6 +3603,7 @@ dependencies = ["futures","harness_id","harnesses",+ "macro_env_var","macro_event_broker","macro_user_id","macro_uuid",@@ -3584,7 +3613,9 @@ dependencies = ["rustls 0.23.40","serde","serde_json",+ "shell-words","strum 0.27.2",+ "tempfile","thiserror 2.0.18","tokio","tokio-retry",@@ -3594,7 +3625,9 @@ dependencies = ["toml_edit 0.22.27","tracing","tracing-subscriber",+ "tui-input","uuid",+ "webbrowser","webhook","workspace-hack",]@@ -5568,6 +5601,12 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1"+[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"+[[package]]name = "dtoa"version = "1.0.11"@@ -6267,6 +6306,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "error-code"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"+[[package]]name = "etcetera"version = "0.8.0"@@ -11399,6 +11444,18 @@ 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.11.1",+ "objc2",+ "objc2-core-graphics",+ "objc2-foundation",+]+[[package]]name = "objc2-cloud-kit"version = "0.3.2"@@ -11835,6 +11892,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "os_pipe"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "outref"version = "0.5.2"@@ -12880,6 +12947,15 @@ 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 = "quick_cache"version = "0.6.22"@@ -16887,6 +16963,17 @@ dependencies = ["web-sys",]+[[package]]+name = "tree_magic_mini"+version = "3.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"+dependencies = [+ "memchr",+ "nom 8.0.0",+ "petgraph 0.8.3",+]+[[package]]name = "triomphe"version = "0.1.15"@@ -16903,6 +16990,15 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "tui-input"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "911e93158bf80bbc94bad533b2b16e3d711e1132d69a6a6980c3920a63422c19"+dependencies = [+ "unicode-width 0.2.0",+]+[[package]]name = "tungstenite"version = "0.28.0"@@ -17766,6 +17862,76 @@ dependencies = ["semver",]+[[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.4",+ "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.11.1",+ "rustix 1.1.4",+ "wayland-backend",+ "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.11.1",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-wlr"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"+dependencies = [+ "bitflags 2.11.1",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "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 = [+ "pkg-config",+]+[[package]]name = "web-sys"version = "0.3.103"@@ -17798,6 +17964,22 @@ dependencies = ["string_cache_codegen 0.6.1",]+[[package]]+name = "webbrowser"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef62a3d5f7b2411119a11b6f62570dbff91d7105e011a20fb83fbf8f5761c40f"+dependencies = [+ "jni 0.22.4",+ "log",+ "ndk-context",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "url",+ "web-sys",+]+[[package]]name = "webhook"version = "0.1.0"@@ -18378,6 +18560,24 @@ dependencies = ["wasmparser",]+[[package]]+name = "wl-clipboard-rs"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9651471a32e87d96ef3a127715382b2d11cc7c8bb9822ded8a7cc94072eb0a3"+dependencies = [+ "libc",+ "log",+ "os_pipe",+ "rustix 1.1.4",+ "thiserror 2.0.18",+ "tree_magic_mini",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-wlr",+]+[[package]]name = "worker"version = "0.8.1"@@ -18557,6 +18757,8 @@ dependencies = ["num-bigint","num-integer","num-traits",+ "objc2",+ "objc2-foundation","once_cell","opentelemetry","opentelemetry-http",@@ -18653,6 +18855,23 @@ dependencies = ["tap",]+[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "gethostname",+ "rustix 1.1.4",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"+[[package]]name = "xmlparser"version = "0.13.6"diff --git a/Cargo.toml b/Cargo.tomlindex 39b80d3df6..0b64a9362c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -140,6 +140,7 @@ apollo-parser = "0.8"# https://github.com/agentclientprotocol/rust-sdk/pull/294# Swap back to a plain version once upstream cuts a release containing it.agent-client-protocol = { git = "https://github.com/agentclientprotocol/rust-sdk", rev = "8769d16d10e0c9fa7e662ee18424a4313b06ea88" }+arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }askama = "0.14"async-graphql = "7.2.1"async-lock = "3"@@ -276,6 +277,7 @@ serde_json = { version = "1.0.132" }serde_repr = "0.1"serde_with = { version = "3.12.0", features = ["base64"] }serde_yaml = "0.9"+shell-words = "1.1.1"specta = { version = "=2.0.0-rc.25", features = ["derive"] }specta-serde = "=0.0.12"specta-typescript = "=0.0.12"@@ -311,6 +313,7 @@ tracing = "0.1.44"tracing-opentelemetry = "0.32.1"tracing-subscriber = { version = "0.3.22", features = ["env-filter", "json"] }tracing-tree = "0.4.0"+tui-input = { version = "0.14.0", default-features = false }# Pin the official upstream revision used by the browser cache. Cache writes use# deferred transactions so browser WASM does not initialize Turso's temp database.turso_core = { git = "https://github.com/tursodatabase/turso", rev = "79163249538197d01dec5ea7f65519454ed792e2", default-features = false }@@ -334,6 +337,7 @@ wasm-bindgen-futures = "0.4"wasm-bindgen-test = "0.3"web-sys = "0.3"web-time = "1.1.0"+webbrowser = { version = "=1.2.2", features = ["hardened"] }worker = "0.8.1"# this is pinned to match axum 0.7.9 dependency requirementsasync-stripe = { version = "0.41", default-features = false, features = [diff --git a/apps/web/src/components/app/split-layout/layoutUrlSync.ts b/apps/web/src/components/app/split-layout/layoutUrlSync.tsindex 01d4239dfd..bd3773bcac 100644--- a/apps/web/src/components/app/split-layout/layoutUrlSync.ts+++ b/apps/web/src/components/app/split-layout/layoutUrlSync.ts@@ -121,6 +121,18 @@ export function createLayoutUrlSync(const nextState = managerUrlState();const pathChanged = nextState.segments.join('/') !== pairs().join('/');+ const currentQuery = new URLSearchParams(environment.search());+ // On a direct macrod pairing link, the settings split initially serializes+ // its default tab before the settings wrapper reads `settings/harness`.+ // Let that wrapper select Harness instead of replacing the requested URL.+ if (+ pathChanged &&+ pairs()[0] === 'settings' &&+ pairs()[1] === 'harness' &&+ currentQuery.get('pair')+ ) {+ return;+ }const nextPairs = decodePairs(nextState.segments);const affectedSplit = getUrlSyncAffectedSplit(splitManager,@@ -133,9 +145,7 @@ export function createLayoutUrlSync(// Preserve unrelated query/hash state for query-only updates. Path// changes retain the existing split-navigation behavior of clearing// content-specific location state.- const query = pathChanged- ? new URLSearchParams()- : new URLSearchParams(environment.search());+ const query = pathChanged ? new URLSearchParams() : currentQuery;if (nextState.preview) {query.set(PREVIEW_QUERY_PARAM, nextState.preview);} else {diff --git a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.tsindex 5051d8b398..1b52cb8681 100644--- a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts@@ -252,4 +252,34 @@ describe('layout URL synchronization', () => {harness.dispose();});++ it('preserves a macrod pairing code while settings canonicalizes its tab', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'settings' }],+ urlSegments: ['settings', 'harness'],+ search: '?pair=3GTM-FNJ9&discard=value',+ });++ await flushUrlSync();++ expect(harness.navigate).not.toHaveBeenCalled();++ harness.dispose();+ });++ it('does not stall settings URL synchronization for an empty pairing code', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'settings' }],+ urlSegments: ['settings', 'harness'],+ search: '?pair=',+ });++ await flushUrlSync();++ expect(harness.navigate).toHaveBeenCalledWith('/settings/account', {+ replace: true,+ });++ harness.dispose();+ });});diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.tomlindex 1017ee2a69..e1ae4869af 100644--- a/crates/coding_agent_worker/Cargo.toml+++ b/crates/coding_agent_worker/Cargo.toml@@ -16,16 +16,18 @@ agent-client-protocol = { workspace = true }agent_runtime_protocol = { path = "../agent_runtime_protocol" }agent_session = { path = "../agent_session" }agent_trigger = { path = "../agent_trigger" }+arboard = { workspace = true }bot_id = { path = "../bot_id" }chrono = { workspace = true }clap = { workspace = true }crossterm = { workspace = true }-harness_id = { path = "../harness_id" }-harnesses = { path = "../harnesses", default-features = false }dashmap = { workspace = true }eventsource-stream = { workspace = true }futures = { workspace = true }+harness_id = { path = "../harness_id" }+harnesses = { path = "../harnesses", default-features = false }macro_event_broker = { path = "../macro_event_broker", default-features = false }+macro_env_var = { path = "../macro_env_var" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }ratatui = { workspace = true }@@ -36,6 +38,7 @@ rootcause = { workspace = true }rustls = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }+shell-words = { workspace = true }strum = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true, features = ["macros", "process", "rt-multi-thread", "signal", "time"] }@@ -45,8 +48,10 @@ tokio-tungstenite = { workspace = true }toml = { workspace = true }toml_edit = { workspace = true }tracing = { workspace = true }-uuid = { workspace = true }tracing-subscriber = { workspace = true }+tui-input = { workspace = true }+uuid = { workspace = true }+webbrowser = { workspace = true }webhook = { path = "../webhook", default-features = false }workspace-hack = { version = "0.1", path = "../workspace-hack" }@@ -56,4 +61,5 @@ channel_sender = { path = "../channel_sender" }channels = { path = "../channels", default-features = false }chrono = { workspace = true }harness_id = { path = "../harness_id", features = ["test-utils"] }+tempfile = { workspace = true }tokio = { workspace = true, features = ["io-util", "net"] }diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.tomlindex 306ff1d9e0..ac6b9231dc 100644--- a/crates/coding_agent_worker/config.example.toml+++ b/crates/coding_agent_worker/config.example.toml@@ -1,9 +1,8 @@-# Everything a coding agent daemon needs to serve one harness's sessions.+# Everything an agent harness daemon needs to serve one harness's sessions.#-# Deliberately credential-free: `macrod` starts unpaired and the control-# panel offers pairing (press p). Pairing shows a code, you approve it in the-# web app (choosing private or team), and the minted credential is kept in-# `macro.credentials.json` next to this file.+# This example omits credentials, so `macrod` starts in Quickstart. Pairing+# shows a code for approval in the web app, then adds a `[credentials]` table+# containing a bearer token to this file. Keep the resulting config private.[macro]# Base URL of the agent-harness service. Its ws(s) twin hosts the runtime@@ -24,7 +23,7 @@ name = "erics-macbook"scope = "private"[harness]-command = "opencode"+command = "hermes"args = ["acp"][workspace]diff --git a/crates/coding_agent_worker/default.macrod.toml b/crates/coding_agent_worker/default.macrod.tomlnew file mode 100644index 0000000000..4b92508036--- /dev/null+++ b/crates/coding_agent_worker/default.macrod.toml@@ -0,0 +1,16 @@+# macrod configuration. Pairing adds a bearer token here; keep this file private.++[macro]+api_url = "https://agent-harness.macro.com"+storage_url = "https://gateway.macro.com/dss"+web_url = "https://macro.com/app"++[identity]+scope = "private"++[harness]+command = "hermes"+args = ["acp"]++[workspace]+path = "."diff --git a/crates/coding_agent_worker/justfile b/crates/coding_agent_worker/justfileindex 96d28adf6c..384822b9ef 100644--- a/crates/coding_agent_worker/justfile+++ b/crates/coding_agent_worker/justfile@@ -3,9 +3,7 @@# just run# RUST_LOG=coding_agent_worker=trace just run # tap the ACP wire (Logs tab)#-# Reads the repo-root macro.toml by default; override with CONFIG=/path/to.toml.--CONFIG := env("CONFIG", justfile_directory() + "/../../macro.toml")+# Reads macrod.toml from the repository root.ROOT := justfile_directory() + "/../.."SCRIPTS := ROOT + "/tooling/xtask/crates/xtask_workflows/src/workflows/scripts"@@ -13,7 +11,7 @@ SCRIPTS := ROOT + "/tooling/xtask/crates/xtask_workflows/src/workflows/scripts"# Serve this harness's agent sessions inside the control panel: registration,# bound agents, live sessions, config, pairing, and logs - one process.run:- SQLX_OFFLINE=true cargo run -p coding_agent_worker -- --config {{ CONFIG }}+ cd {{ ROOT }} && SQLX_OFFLINE=true cargo run -p coding_agent_worker# Build the release `macrod` the way the tag workflow does, and prove it is as# self-contained as it claims. Runs the workflow's own scripts rather than adiff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rsindex c04eee47fa..47a61725e6 100644--- a/crates/coding_agent_worker/src/config.rs+++ b/crates/coding_agent_worker/src/config.rs@@ -2,11 +2,11 @@//! streams from and the harness it runs per session. See//! `config.example.toml` at the crate root.//!-//! Deliberately credential-free: identity comes from pairing (press `p` in-//! the control panel), which persists the harness credential in a state file-//! next to this config.+//! Pairing (press `p` in the control panel) adds the harness credential to+//! this file. Treat it as sensitive because that credential is a bearer token.-use serde::Deserialize;+use harness_id::HarnessId;+use serde::{Deserialize, Serialize};use std::path::{Path, PathBuf};#[cfg(test)]@@ -22,6 +22,9 @@ pub struct Config {/// How this daemon introduces itself when pairing.#[serde(default)]pub identity: Identity,+ /// The approved harness credential, absent until pairing completes.+ #[serde(default)]+ pub credentials: Option<HarnessCredentials>,/// Unused: kept so existing configs that still declare a webhook listener/// continue to parse. The daemon listens over SSE and no longer serves HTTP.#[serde(default)]@@ -33,6 +36,40 @@ pub struct Config {pub workspace: Workspace,}+/// Whether the approved harness is private to its owner or shared with a team.+///+/// This can differ from [`Identity::scope`], which remains the requested scope+/// for the next pairing.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum HarnessScope {+ /// Owned by one user.+ User,+ /// Owned by a team.+ Team,+}++/// The credential pairing minted for this daemon.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct HarnessCredentials {+ /// The registered harness this daemon serves.+ pub harness_id: HarnessId,+ /// The bearer token (`mhns_...`).+ pub token: String,+ /// The approved harness ownership scope.+ pub scope: HarnessScope,+}++impl HarnessCredentials {+ /// Whether this credential has the expected non-empty bearer-token shape.+ pub fn is_valid(&self) -> bool {+ self.token+ .strip_prefix("mhns_")+ .is_some_and(|secret| !secret.is_empty())+ }+}+/// The Macro deployment this harness's sessions live in.#[derive(Debug, Clone, Deserialize)]#[serde(deny_unknown_fields)]diff --git a/crates/coding_agent_worker/src/config/test.rs b/crates/coding_agent_worker/src/config/test.rsindex e50404ffb9..ca48b68fdc 100644--- a/crates/coding_agent_worker/src/config/test.rs+++ b/crates/coding_agent_worker/src/config/test.rs@@ -5,10 +5,37 @@ const EXAMPLE: &str = include_str!("../../config.example.toml");#[test]fn the_example_config_parses() {let config: Config = toml::from_str(EXAMPLE).expect("example config parses");- assert_eq!(config.harness.command, "opencode");+ assert_eq!(config.harness.command, "hermes");assert_eq!(config.harness.args, vec!["acp"]);assert_eq!(config.identity.name.as_deref(), Some("erics-macbook"));assert_eq!(config.identity.scope, IdentityScope::Private);+ assert_eq!(config.credentials, None);+}++#[test]+fn embedded_credentials_parse_with_their_approved_scope() {+ let with_credentials = format!(+ "{EXAMPLE}\n[credentials]\nharness_id = \"{}\"\ntoken = \"mhns_secret\"\nscope = \"team\"\n",+ harness_id::HarnessId::TEST_A+ );+ let config: Config = toml::from_str(&with_credentials).expect("embedded credentials parse");+ let credentials = config.credentials.expect("credentials");++ assert_eq!(credentials.harness_id, harness_id::HarnessId::TEST_A);+ assert_eq!(credentials.scope, HarnessScope::Team);+ assert!(credentials.is_valid());+ assert_eq!(config.identity.scope, IdentityScope::Private);+}++#[test]+fn malformed_bearer_token_is_not_valid() {+ let credentials = HarnessCredentials {+ harness_id: harness_id::HarnessId::TEST_A,+ token: "not-a-harness-token".to_owned(),+ scope: HarnessScope::User,+ };++ assert!(!credentials.is_valid());}#[test]diff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rsindex 84f8db1abf..28cbde1cb9 100644--- a/crates/coding_agent_worker/src/daemon.rs+++ b/crates/coding_agent_worker/src/daemon.rs@@ -10,14 +10,16 @@ use std::time::Duration;use rootcause::prelude::ResultExt as _;use tokio_util::sync::CancellationToken;-use crate::config::Config;+use crate::config::{Config, HarnessCredentials};use crate::dispatch::Dispatcher;use crate::outbound::agent_session::HarnessApi;-use crate::outbound::credentials::HarnessCredentials;use crate::outbound::stream::EventStreamClient;use crate::runtime::Runtime;use crate::trigger::{TriggerEvent, handle_event, trigger_filters};+#[cfg(test)]+mod test;+/// How often the bound-agent set is re-read so a newly bound agent starts/// triggering without a restart. Short on purpose: a mention sent before the/// stream covers the new agent is dropped for good, so this interval is the@@ -96,20 +98,21 @@ impl Daemon {!self.task.is_finished()}- /// Stop serving: drop the stream and end the reconnect loop.+ /// Stop serving without waiting for an in-flight network request or trigger.////// A live harness bridge (the WebSocket + spawned harness process) is not/// torn down here; it dies with the process, and a restarted daemon's/// fresh dial displaces it at the gateway.pub async fn stop(self) {self.cancel.cancel();+ self.task.abort();let _ = self.task.await;tracing::info!("daemon stopped");}}/// Absolute form of the config path, so a `chdir` into the workspace never-/// re-points relative reads and writes of the config and its state files.+/// re-points relative reads and writes of the config.pub fn absolute_config_path(config_path: &Path) -> PathBuf {std::path::absolute(config_path).unwrap_or_else(|_| config_path.to_owned())}diff --git a/crates/coding_agent_worker/src/daemon/test.rs b/crates/coding_agent_worker/src/daemon/test.rsnew file mode 100644index 0000000000..e5d0bc4275--- /dev/null+++ b/crates/coding_agent_worker/src/daemon/test.rs@@ -0,0 +1,13 @@+use super::*;++#[tokio::test]+async fn stop_does_not_wait_for_in_flight_work() {+ let daemon = Daemon {+ cancel: CancellationToken::new(),+ task: tokio::spawn(std::future::pending()),+ };++ tokio::time::timeout(Duration::from_secs(1), daemon.stop())+ .await+ .expect("daemon shutdown should abort in-flight work");+}diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rsindex 8c77e711b3..fea22627a8 100644--- a/crates/coding_agent_worker/src/main.rs+++ b/crates/coding_agent_worker/src/main.rs@@ -1,4 +1,4 @@-//! The coding agent daemon: serve a registered harness's agent sessions from+//! The agent harness daemon: serve a registered harness's agent sessions from//! this machine.//!//! `macrod` is one process and one command: the serving core (SSE listener,@@ -9,7 +9,7 @@//!//! A first run starts unpaired: the panel offers pairing (press `p`), the//! user approves the printed code in the web app, and the minted harness-//! credential is persisted next to the config. Once paired, each+//! credential is embedded in the sensitive `macrod.toml`. Once paired, each//! `agent_trigger.new` delivery opens a session over the harness service's//! API, dials its runtime gateway, spawns the configured harness in ACP mode,//! bridges its stdio to the websocket, and forwards the mention as the first@@ -26,7 +26,6 @@ mod trigger;mod tui;use clap::Parser;-use std::path::PathBuf;use std::process::ExitCode;use crate::daemon::absolute_config_path;@@ -37,9 +36,9 @@ use crate::daemon::absolute_config_path;#[derive(Parser)]#[command(name = "macrod", version)]struct Args {- /// Path to the daemon's TOML config.- #[arg(long, default_value = "macro.toml")]- config: PathBuf,+ /// Internal browser helper, isolated so terminal browsers cannot claim the TUI's stdin.+ #[arg(long, hide = true)]+ open_url: Option<String>,}#[tokio::main]@@ -50,9 +49,18 @@ async fn main() -> ExitCode {let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();let args = Args::parse();+ if let Some(url) = args.open_url {+ return match webbrowser::open(&url) {+ Ok(()) => ExitCode::SUCCESS,+ Err(error) => {+ eprintln!("could not open browser: {error}");+ ExitCode::FAILURE+ }+ };+ }// The daemon chdirs into the workspace, so the config path must stop// being relative before anything re-reads or rewrites it.- let config_path = absolute_config_path(&args.config);+ let config_path = absolute_config_path(std::path::Path::new("macrod.toml"));// The TUI owns the terminal, so its logs go to a ring buffer it renders.let logs = tui::LogBuffer::install();diff --git a/crates/coding_agent_worker/src/outbound/agent_session.rs b/crates/coding_agent_worker/src/outbound/agent_session.rsindex 647ccf1d20..a518a64164 100644--- a/crates/coding_agent_worker/src/outbound/agent_session.rs+++ b/crates/coding_agent_worker/src/outbound/agent_session.rs@@ -11,8 +11,7 @@ use agent_session::inbound::axum_router::{use macro_user_id::user_id::MacroUserIdStr;use reqwest::StatusCode;-use crate::config::MacroApi;-use crate::outbound::credentials::HarnessCredentials;+use crate::config::{HarnessCredentials, MacroApi};const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";const HARNESS_ACTING_USER_HEADER: &str = "x-macro-harness-for-macro-user-id";diff --git a/crates/coding_agent_worker/src/outbound/credentials.rs b/crates/coding_agent_worker/src/outbound/credentials.rsdeleted file mode 100644index 19ee5c18ce..0000000000--- a/crates/coding_agent_worker/src/outbound/credentials.rs+++ /dev/null@@ -1,107 +0,0 @@-//! The daemon's persisted identity: which harness this machine is, and the-//! bearer token that proves it.-//!-//! Written once by pairing and read at every boot, in a state file next to-//! the config. Losing the file is recoverable by pairing again.--use std::path::{Path, PathBuf};--use harness_id::HarnessId;-use rootcause::prelude::ResultExt as _;-use serde::{Deserialize, Serialize};--#[cfg(test)]-mod test;--/// Whether the harness is private to its owner or shared with a team.-///-/// Persisted because the event stream must live in the matching workspace: a-/// team harness listens in the team workspace so teammates' agents' triggers-/// reach it.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum HarnessScope {- /// Owned by one user.- User,- /// Owned by a team.- Team,-}--/// The credential pairing minted for this daemon.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct HarnessCredentials {- /// The registered harness this daemon serves.- pub harness_id: HarnessId,- /// The bearer token (`mhns_...`).- pub token: String,- /// The harness's ownership scope.- pub scope: HarnessScope,-}--/// Where credentials live and how they are read back.-pub trait CredentialStore {- /// The persisted credentials, or `None` before the first pairing.- fn load(&self) -> rootcause::Result<Option<HarnessCredentials>>;-- /// Persist newly minted credentials.- fn save(&self, credentials: &HarnessCredentials) -> rootcause::Result<()>;-}--/// Credentials in a mode-600 JSON file next to the config.-pub struct FileCredentialStore {- path: PathBuf,-}--impl FileCredentialStore {- /// The store for the daemon config at `config_path`.- pub fn for_config(config_path: &Path) -> Self {- Self {- path: credentials_path(config_path),- }- }-- /// Where the file lives, so tests can inspect and corrupt it.- #[cfg(test)]- pub fn path(&self) -> &Path {- &self.path- }-- fn failure(&self) -> String {- format!(- "failed to use the credentials file at {}",- self.path.display()- )- }-}--/// Where the credentials live: next to the config they belong to.-pub fn credentials_path(config_path: &Path) -> PathBuf {- config_path.with_extension("credentials.json")-}--impl CredentialStore for FileCredentialStore {- fn load(&self) -> rootcause::Result<Option<HarnessCredentials>> {- let found = std::fs::read_to_string(&self.path);- if let Err(error) = &found- && error.kind() == std::io::ErrorKind::NotFound- {- return Ok(None);- }- let raw = found.context(self.failure())?;- // Credentials we cannot parse are credentials we do not have; the- // caller sends the user back through pairing.- Ok(serde_json::from_str(&raw).ok())- }-- fn save(&self, credentials: &HarnessCredentials) -> rootcause::Result<()> {- let raw = serde_json::to_string_pretty(credentials).expect("a serializable credential");- std::fs::write(&self.path, raw).context(self.failure())?;- // The token authenticates this harness; keep it out of other users' reach.- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt as _;- let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));- }- Ok(())- }-}diff --git a/crates/coding_agent_worker/src/outbound/credentials/test.rs b/crates/coding_agent_worker/src/outbound/credentials/test.rsdeleted file mode 100644index aab80a9480..0000000000--- a/crates/coding_agent_worker/src/outbound/credentials/test.rs+++ /dev/null@@ -1,40 +0,0 @@-use super::*;-use harness_id::HarnessId;--fn credentials() -> HarnessCredentials {- HarnessCredentials {- harness_id: HarnessId::TEST_A,- token: "mhns_abc_secret".to_owned(),- scope: HarnessScope::Team,- }-}--#[test]-fn round_trips_and_restricts_permissions() {- let dir = std::env::temp_dir().join(format!("macrod-cred-test-{}", std::process::id()));- std::fs::create_dir_all(&dir).unwrap();- let config_path = dir.join("macro.toml");- let store = FileCredentialStore::for_config(&config_path);-- assert!(store.load().unwrap().is_none());-- store.save(&credentials()).unwrap();- assert_eq!(store.load().unwrap(), Some(credentials()));- assert_eq!(store.path(), dir.join("macro.credentials.json").as_path());-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt as _;- let mode = std::fs::metadata(store.path())- .unwrap()- .permissions()- .mode();- assert_eq!(mode & 0o777, 0o600);- }-- // Unparseable state is treated as absent, sending the user to re-pair.- std::fs::write(store.path(), "not json").unwrap();- assert!(store.load().unwrap().is_none());-- let _ = std::fs::remove_dir_all(&dir);-}diff --git a/crates/coding_agent_worker/src/outbound/mod.rs b/crates/coding_agent_worker/src/outbound/mod.rsindex 434e924fcc..a43845f61b 100644--- a/crates/coding_agent_worker/src/outbound/mod.rs+++ b/crates/coding_agent_worker/src/outbound/mod.rs@@ -7,7 +7,6 @@//! runtime surprise on someone's laptop.pub mod agent_session;-pub mod credentials;pub mod link;pub mod pairing;pub mod stream;diff --git a/crates/coding_agent_worker/src/outbound/pairing.rs b/crates/coding_agent_worker/src/outbound/pairing.rsindex 5a1bd34796..bb47461024 100644--- a/crates/coding_agent_worker/src/outbound/pairing.rs+++ b/crates/coding_agent_worker/src/outbound/pairing.rs@@ -12,8 +12,7 @@ use reqwest::StatusCode;use rootcause::prelude::ResultExt as _;use uuid::Uuid;-use crate::config::Config;-use crate::outbound::credentials::{HarnessCredentials, HarnessScope};+use crate::config::{Config, HarnessCredentials, HarnessScope};/// One claim poll's answer.#[derive(Debug)]diff --git a/crates/coding_agent_worker/src/outbound/stream.rs b/crates/coding_agent_worker/src/outbound/stream.rsindex 1151b78f3e..02b5f5c209 100644--- a/crates/coding_agent_worker/src/outbound/stream.rs+++ b/crates/coding_agent_worker/src/outbound/stream.rs@@ -18,8 +18,7 @@ use rootcause::prelude::ResultExt as _;use serde::de::DeserializeOwned;use webhook::domain::models::{WebhookFilter, WebhookScope};-use crate::config::MacroApi;-use crate::outbound::credentials::{HarnessCredentials, HarnessScope};+use crate::config::{HarnessCredentials, HarnessScope, MacroApi};#[cfg(test)]mod test;diff --git a/crates/coding_agent_worker/src/outbound/stream/test.rs b/crates/coding_agent_worker/src/outbound/stream/test.rsindex 0bf2560910..ef505108a7 100644--- a/crates/coding_agent_worker/src/outbound/stream/test.rs+++ b/crates/coding_agent_worker/src/outbound/stream/test.rs@@ -1,6 +1,5 @@use super::*;-use crate::config::MacroApi;-use crate::outbound::credentials::{HarnessCredentials, HarnessScope};+use crate::config::{HarnessCredentials, HarnessScope, MacroApi};use harness_id::HarnessId;use webhook::domain::models::WebhookFilter;diff --git a/crates/coding_agent_worker/src/runtime.rs b/crates/coding_agent_worker/src/runtime.rsindex 96a94d66de..10c51e86f3 100644--- a/crates/coding_agent_worker/src/runtime.rs+++ b/crates/coding_agent_worker/src/runtime.rs@@ -20,9 +20,8 @@ use tokio_retry::RetryIf;use tokio_retry::strategy::{ExponentialBackoff, FixedInterval};use tokio_tungstenite::tungstenite;-use crate::config::{Harness, MacroApi};+use crate::config::{Harness, HarnessCredentials, MacroApi};use crate::harness;-use crate::outbound::credentials::HarnessCredentials;use crate::outbound::link;/// A dial races the delivery that asked for it, so it retries quickly anddiff --git a/crates/coding_agent_worker/src/tui.rs b/crates/coding_agent_worker/src/tui.rsindex 72e6dbd5e5..7abad01820 100644--- a/crates/coding_agent_worker/src/tui.rs+++ b/crates/coding_agent_worker/src/tui.rs@@ -3,610 +3,20 @@//! `macrod` runs the serving core (SSE listener, harness bridge) inside a//! terminal UI that shows what the server knows about this harness - its//! registration, the agents bound to it, their sessions, and the daemon's-//! own logs - and drives its lifecycle: edit `macro.toml`, pair (or re-pair,+//! own logs - and drives its lifecycle: edit `macrod.toml`, pair (or re-pair,//! restarting the core on the new credential), and retire the harness.+mod agent_catalog;mod api;+mod app;mod config_form;+mod input;+mod logging;+mod platform;mod process;+mod quickstart;+mod runner;mod ui;-use std::path::{Path, PathBuf};-use std::time::{Duration, Instant};--use crossterm::event::{Event as TermEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};-use harnesses::domain::models::CreatedPairing;-use rootcause::prelude::ResultExt as _;--use crate::config::Config;-use crate::daemon::Daemon;-use crate::outbound::credentials::{CredentialStore as _, FileCredentialStore, HarnessCredentials};-use crate::outbound::pairing::{ClaimStatus, PairingClient};--use api::{HarnessSelfApi, Snapshot};-use config_form::{ConfigForm, FIELDS, FieldKind};--/// How often the dashboard re-reads the server.-const REFRESH_EVERY: Duration = Duration::from_secs(3);-/// Spinner cadence and input latency budget.-const TICK: Duration = Duration::from_millis(120);--/// The daemon's own log lines, rendered by the Logs tab.-///-/// The TUI owns the terminal, so tracing must not write to it; this is the-/// sink the subscriber writes into instead.-#[derive(Clone, Default)]-pub struct LogBuffer {- lines: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<String>>>,-}--impl LogBuffer {- const CAPACITY: usize = 500;-- /// Install the global tracing subscriber writing into a fresh buffer.- pub fn install() -> Self {- let buffer = Self::default();- let sink = buffer.clone();- tracing_subscriber::fmt()- .with_env_filter(- tracing_subscriber::EnvFilter::try_from_default_env()- .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),- )- .with_ansi(false)- .with_writer(move || sink.clone())- .init();- buffer- }-- /// The most recent lines, oldest first.- pub(crate) fn tail(&self, count: usize) -> Vec<String> {- let lines = self.lines.lock().expect("log buffer lock");- lines.iter().rev().take(count).rev().cloned().collect()- }-}--impl std::io::Write for LogBuffer {- fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {- let mut lines = self.lines.lock().expect("log buffer lock");- for line in String::from_utf8_lossy(bytes).lines() {- if line.trim().is_empty() {- continue;- }- if lines.len() == Self::CAPACITY {- lines.pop_front();- }- lines.push_back(line.to_owned());- }- Ok(bytes.len())- }-- fn flush(&mut self) -> std::io::Result<()> {- Ok(())- }-}--/// Which tab is showing.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(crate) enum Tab {- Overview,- Sessions,- Config,- Logs,-}--impl Tab {- const ALL: [Tab; 4] = [Tab::Overview, Tab::Sessions, Tab::Config, Tab::Logs];-- pub(crate) fn title(self) -> &'static str {- match self {- Tab::Overview => "Overview",- Tab::Sessions => "Sessions",- Tab::Config => "Config",- Tab::Logs => "Logs",- }- }-- fn next(self) -> Tab {- match self {- Tab::Overview => Tab::Sessions,- Tab::Sessions => Tab::Config,- Tab::Config => Tab::Logs,- Tab::Logs => Tab::Overview,- }- }-}--/// A modal claiming the keyboard, when one is up.-pub(crate) enum Mode {- /// Browsing; keys act on the current tab.- Normal,- /// Editing one config field's value.- EditField {- /// Index into [`FIELDS`].- index: usize,- /// The text being typed.- buffer: String,- },- /// Confirming harness removal.- ConfirmDelete,- /// A pairing in flight: code shown, waiting for approval.- Pairing {- /// The open pairing.- created: CreatedPairing,- /// When the claim was last polled.- last_poll: Instant,- },-}--/// Everything the UI renders from.-pub(crate) struct App {- pub(crate) config_path: PathBuf,- pub(crate) config: Config,- pub(crate) credentials: Option<HarnessCredentials>,- pub(crate) snapshot: Snapshot,- /// This process's pid - the TUI and the daemon are this one process.- pub(crate) pid: u32,- /// The spawned harness child, when serving and one is found.- pub(crate) harness_process: Option<process::Child>,- pub(crate) tab: Tab,- pub(crate) mode: Mode,- pub(crate) selected_field: usize,- pub(crate) form: ConfigForm,- pub(crate) status: Option<(String, bool)>,- pub(crate) spinner: usize,- pub(crate) logs: LogBuffer,- pub(crate) daemon: Option<Daemon>,- last_refresh: Option<Instant>,- quit: bool,-}--impl App {- fn load(config_path: &Path, logs: LogBuffer) -> rootcause::Result<Self> {- let config = Config::load(config_path)?;- let credentials = FileCredentialStore::for_config(config_path).load()?;- let form = ConfigForm::load(config_path)?;- Ok(Self {- config_path: config_path.to_owned(),- config,- credentials,- snapshot: Snapshot::default(),- pid: std::process::id(),- harness_process: None,- tab: Tab::Overview,- mode: Mode::Normal,- selected_field: 0,- form,- status: None,- spinner: 0,- logs,- daemon: None,- last_refresh: None,- quit: false,- })- }-- /// Whether the in-process serving core is up.- pub(crate) fn serving(&self) -> bool {- self.daemon.as_ref().is_some_and(Daemon::is_running)- }-- /// (Re)start the serving core on the current config and credential.- async fn restart_daemon(&mut self) {- if let Some(daemon) = self.daemon.take() {- daemon.stop().await;- }- let Some(credentials) = self.credentials.clone() else {- return;- };- match Daemon::start(self.config.clone(), credentials, &self.config_path).await {- Ok(daemon) => self.daemon = Some(daemon),- Err(error) => self.fail(format!("daemon failed to start: {error}")),- }- }-- /// Stop the serving core, if it is up.- async fn stop_daemon(&mut self) {- if let Some(daemon) = self.daemon.take() {- daemon.stop().await;- }- }-- /// The approval URL of the pairing in flight, when one is.- fn pairing_url(&self) -> Option<String> {- match &self.mode {- Mode::Pairing { created, .. } => {- Some(self.config.macro_api.pairing_approval_url(&created.code))- }- _ => None,- }- }-- pub(crate) fn paired(&self) -> bool {- self.credentials.is_some()- }-- fn api(&self) -> Option<HarnessSelfApi> {- self.credentials- .as_ref()- .map(|credentials| HarnessSelfApi::new(&self.config, credentials))- }-- fn ok(&mut self, message: impl Into<String>) {- self.status = Some((message.into(), false));- }-- fn fail(&mut self, message: impl Into<String>) {- self.status = Some((message.into(), true));- }-- async fn refresh(&mut self) {- // Local process facts refresh with the dashboard, not with the network.- self.harness_process = if self.serving() {- process::harness_child(&self.config.harness.command)- } else {- None- };- let Some(api) = self.api() else {- self.snapshot = Snapshot::default();- return;- };- match api.snapshot().await {- Ok(snapshot) => {- self.snapshot = snapshot;- self.last_refresh = Some(Instant::now());- }- Err(error) => self.fail(format!("refresh failed: {error}")),- }- }-- async fn maybe_refresh(&mut self) {- let due = self- .last_refresh- .is_none_or(|last| last.elapsed() >= REFRESH_EVERY);- if due {- self.refresh().await;- }- }-- async fn start_pairing(&mut self) {- // Re-read the config so an edit saved a moment ago (a new name or- // scope) is what this pairing asks for.- match Config::load(&self.config_path) {- Ok(config) => self.config = config,- Err(error) => return self.fail(format!("config reload failed: {error}")),- }- let client = PairingClient::new(&self.config);- match client.start(&self.config).await {- Ok(created) => {- // The approval page pre-fills the code, so opening the- // browser is usually the whole remaining gesture.- let url = self.config.macro_api.pairing_approval_url(&created.code);- open_in_browser(&url);- self.mode = Mode::Pairing {- created,- last_poll: Instant::now(),- };- }- Err(error) => self.fail(format!("pairing failed to start: {error}")),- }- }-- async fn poll_pairing(&mut self) {- // Copy what the poll needs out of the mode first, so the network call- // below is free to report back into `self`.- let (pairing_id, device_secret) = {- let Mode::Pairing { created, last_poll } = &mut self.mode else {- return;- };- let interval = Duration::from_secs(created.poll_interval_seconds.max(1));- if last_poll.elapsed() < interval {- return;- }- *last_poll = Instant::now();- if created.expires_at <= chrono::Utc::now() {- self.mode = Mode::Normal;- return self.fail("the pairing expired before it was approved");- }- (created.pairing_id, created.device_secret.clone())- };- let client = PairingClient::new(&self.config);- match client.claim(pairing_id, &device_secret).await {- Ok(ClaimStatus::Pending) => {}- Ok(ClaimStatus::Claimed(credentials)) => {- let store = FileCredentialStore::for_config(&self.config_path);- if let Err(error) = store.save(&credentials) {- self.mode = Mode::Normal;- return self.fail(format!("could not save credentials: {error}"));- }- self.credentials = Some(credentials);- self.mode = Mode::Normal;- self.restart_daemon().await;- if self.serving() {- self.ok("paired and serving");- }- self.refresh().await;- }- Ok(ClaimStatus::Gone(reason)) => {- self.mode = Mode::Normal;- self.fail(reason);- }- Err(error) => {- self.mode = Mode::Normal;- self.fail(format!("pairing poll failed: {error}"));- }- }- }-- async fn delete_harness(&mut self) {- let Some(api) = self.api() else {- return self.fail("not paired");- };- if let Err(error) = api.delete_self().await {- return self.fail(format!("{error}"));- }- // The credential is dead either way; stop serving with it and drop- // the local state that belonged to it so the next pairing starts- // clean.- self.stop_daemon().await;- let _ = std::fs::remove_file(crate::outbound::credentials::credentials_path(- &self.config_path,- ));- let _ = std::fs::remove_file(self.config_path.with_extension("webhook-state.json"));- self.credentials = None;- self.snapshot = Snapshot::default();- self.ok("harness removed - press p to pair again");- }-- async fn on_key(&mut self, key: KeyEvent) {- if key.kind != KeyEventKind::Press {- return;- }- // Ctrl-C always quits, whatever is up.- if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {- self.quit = true;- return;- }-- match self.mode {- Mode::Normal => self.on_normal_key(key).await,- Mode::ConfirmDelete => {- self.mode = Mode::Normal;- if matches!(key.code, KeyCode::Char('y') | KeyCode::Char('Y')) {- self.delete_harness().await;- }- }- Mode::Pairing { .. } => match key.code {- KeyCode::Esc => {- self.mode = Mode::Normal;- self.ok("pairing abandoned; the code expires on its own");- }- KeyCode::Char('o') => {- let url = self.pairing_url();- if let Some(url) = url {- if open_in_browser(&url) {- self.ok("opened the approval page");- } else {- self.fail("could not open a browser; use the printed link");- }- }- }- KeyCode::Char('c') => {- let code = match &self.mode {- Mode::Pairing { created, .. } => Some(created.code.clone()),- _ => None,- };- if let Some(code) = code {- if copy_to_clipboard(&code) {- self.ok(format!("copied {code}"));- } else {- self.fail("no clipboard tool found; select the code to copy it");- }- }- }- _ => {}- },- Mode::EditField { .. } => self.on_edit_key(key).await,- }- }-- async fn on_edit_key(&mut self, key: KeyEvent) {- let Mode::EditField { index, buffer } = &mut self.mode else {- return;- };- match key.code {- KeyCode::Esc => self.mode = Mode::Normal,- KeyCode::Backspace => {- buffer.pop();- }- KeyCode::Char(ch) => buffer.push(ch),- KeyCode::Enter => {- let index = *index;- let input = buffer.clone();- self.mode = Mode::Normal;- self.commit_edit(index, input).await;- }- _ => {}- }- }-- async fn commit_edit(&mut self, index: usize, input: String) {- let field = &FIELDS[index];- if let Err(message) = self.form.apply(field, &input) {- return self.fail(message);- }- match self.form.save() {- Ok(()) => match Config::load(&self.config_path) {- Ok(config) => {- self.config = config;- // The core reads config at start, so a save while serving- // means a restart to apply it.- if self.serving() {- self.restart_daemon().await;- self.ok("saved and applied");- } else {- self.ok("saved");- }- }- Err(error) => self.fail(format!("saved, but reload failed: {error}")),- },- Err(error) => {- // Reload the form so the rejected edit does not linger in the- // document.- if let Ok(form) = ConfigForm::load(&self.config_path) {- self.form = form;- }- self.fail(format!("{error}"));- }- }- }-- async fn on_normal_key(&mut self, key: KeyEvent) {- match key.code {- KeyCode::Char('q') => self.quit = true,- KeyCode::Tab => self.tab = self.tab.next(),- KeyCode::Char('1') => self.tab = Tab::Overview,- KeyCode::Char('2') => self.tab = Tab::Sessions,- KeyCode::Char('3') => self.tab = Tab::Config,- KeyCode::Char('4') => self.tab = Tab::Logs,- KeyCode::Char('r') => {- self.last_refresh = None;- self.maybe_refresh().await;- }- KeyCode::Char('p') => self.start_pairing().await,- KeyCode::Char('d') if self.paired() => self.mode = Mode::ConfirmDelete,- KeyCode::Up | KeyCode::Char('k') if self.tab == Tab::Config => {- self.selected_field = self.selected_field.saturating_sub(1);- }- KeyCode::Down | KeyCode::Char('j') if self.tab == Tab::Config => {- self.selected_field = (self.selected_field + 1).min(FIELDS.len() - 1);- }- KeyCode::Enter if self.tab == Tab::Config => {- let field = &FIELDS[self.selected_field];- if field.kind == FieldKind::Scope {- // Toggle rather than type: the only values are the two.- let next = if self.form.display(field) == "team" {- "private"- } else {- "team"- };- if self.form.apply(field, next).is_ok() {- match self.form.save() {- Ok(()) => self.ok(format!("scope: {next} (applies at next pairing)")),- Err(error) => self.fail(format!("{error}")),- }- }- } else {- self.mode = Mode::EditField {- index: self.selected_field,- buffer: self.form.display(field),- };- }- }- _ => {}- }- }-}--/// Run the control panel - and the daemon inside it - until the user quits.-pub async fn run(config_path: &Path, logs: LogBuffer) -> rootcause::Result<()> {- let mut app = App::load(config_path, logs)?;-- let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel();- // A dedicated thread owns the blocking crossterm read; the loop below- // stays async and free to poll the network.- std::thread::spawn(move || {- while let Ok(event) = crossterm::event::read() {- if input_tx.send(event).is_err() {- return;- }- }- });-- let mut terminal = ratatui::init();- let outcome = run_loop(&mut terminal, &mut app, &mut input_rx).await;- ratatui::restore();- outcome-}--/// Open a URL in the default browser, reporting whether the spawn worked.-fn open_in_browser(url: &str) -> bool {- #[cfg(target_os = "macos")]- let launcher = "open";- #[cfg(not(target_os = "macos"))]- let launcher = "xdg-open";- std::process::Command::new(launcher)- .arg(url)- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .spawn()- .is_ok()-}--/// Put text on the system clipboard, reporting whether a tool was found.-fn copy_to_clipboard(text: &str) -> bool {- use std::io::Write as _;- #[cfg(target_os = "macos")]- let candidates: &[&[&str]] = &[&["pbcopy"]];- #[cfg(not(target_os = "macos"))]- let candidates: &[&[&str]] = &[&["wl-copy"], &["xclip", "-selection", "clipboard"]];- for candidate in candidates {- let spawned = std::process::Command::new(candidate[0])- .args(&candidate[1..])- .stdin(std::process::Stdio::piped())- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .spawn();- if let Ok(mut child) = spawned {- let wrote = child- .stdin- .take()- .and_then(|mut stdin| stdin.write_all(text.as_bytes()).ok())- .is_some();- if wrote && child.wait().is_ok_and(|status| status.success()) {- return true;- }- }- }- false-}--async fn run_loop(- terminal: &mut ratatui::DefaultTerminal,- app: &mut App,- input: &mut tokio::sync::mpsc::UnboundedReceiver<TermEvent>,-) -> rootcause::Result<()> {- let mut tick = tokio::time::interval(TICK);- // Paired already? Start serving before the first frame.- if app.paired() {- app.restart_daemon().await;- }- app.refresh().await;-- loop {- terminal- .draw(|frame| ui::render(frame, app))- .context("failed to draw the terminal UI")?;-- tokio::select! {- event = input.recv() => {- match event {- Some(TermEvent::Key(key)) => app.on_key(key).await,- Some(_) => {}- None => return Ok(()),- }- }- _ = tick.tick() => {- app.spinner = app.spinner.wrapping_add(1);- app.poll_pairing().await;- if matches!(app.mode, Mode::Normal) {- app.maybe_refresh().await;- }- }- }-- if app.quit {- app.stop_daemon().await;- return Ok(());- }- }-}+pub use logging::LogBuffer;+pub use runner::run;diff --git a/crates/coding_agent_worker/src/tui/agent_catalog.rs b/crates/coding_agent_worker/src/tui/agent_catalog.rsnew file mode 100644index 0000000000..196b7454ca--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog.rs@@ -0,0 +1,252 @@+//! Supported ACP agents and the local commands needed to launch them.++mod claude_code;+mod codex;+mod hermes;+mod open_claw;+mod open_code;++use std::path::{Path, PathBuf};++use crate::config::Harness;++#[cfg(test)]+mod test;++mod environment {+ macro_env_var::maybe_env_var! {+ pub struct Path;+ }+}++static PRESETS: &[&dyn AgentPreset] = &[+ &hermes::Hermes,+ &claude_code::ClaudeCode,+ &codex::Codex,+ &open_claw::OpenClaw,+ &open_code::OpenCode,+];++/// A command and arguments that start an ACP agent.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LaunchSpec {+ /// Command resolved through the daemon's `PATH` when a session starts.+ pub command: String,+ /// Arguments passed to the command.+ pub args: Vec<String>,+}++impl LaunchSpec {+ fn new(command: &str, args: impl IntoIterator<Item = &'static str>) -> Self {+ Self {+ command: command.to_owned(),+ args: args.into_iter().map(str::to_owned).collect(),+ }+ }+}++/// A supported agent whose complete launch requirements are installed.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DetectedAgent {+ /// Typed preset identity used by the UI.+ pub kind: AgentKind,+ /// Human-readable agent name.+ pub name: &'static str,+ /// Launch configuration to persist when selected.+ pub launch: LaunchSpec,+ /// Short explanation for adapter-backed launchers.+ pub note: Option<&'static str>,+}++/// Agent identity after converting executable discovery into UI state.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AgentKind {+ Hermes,+ ClaudeCode,+ Codex,+ OpenClaw,+ OpenCode,+ Custom,+}++/// Result of checking one preset against the local machine.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Availability {+ /// Every prerequisite exists and this launch specification can be used.+ Available(DetectedAgent),+ /// Commands that must be installed before the preset can be offered.+ Unavailable { missing: Vec<&'static str> },+}++/// Lookup boundary used by agent presets and replaced with a fake in tests.+pub trait CommandLookup {+ /// Resolve an executable through the environment's command search path.+ fn resolve(&self, command: &str) -> Option<&Path>;+}++/// Commands discovered on the process's `PATH`.+pub struct PathCommands {+ found: std::collections::HashMap<&'static str, PathBuf>,+}++impl PathCommands {+ /// Scan once for every command understood by the built-in presets.+ pub fn discover() -> Self {+ let paths = environment::Path::new()+ .and_then(|path| path.value().map(std::ffi::OsString::from))+ .map(|path| std::env::split_paths(&path).collect::<Vec<_>>())+ .unwrap_or_default();+ let mut found = std::collections::HashMap::new();+ for command in [+ "hermes",+ "hermes-acp",+ "claude",+ "codex",+ "npm",+ "npx",+ "openclaw",+ "opencode",+ ] {+ if let Some(path) = find_command(&paths, command) {+ found.insert(command, path);+ }+ }+ Self { found }+ }+}++fn find_command(paths: &[PathBuf], command: &str) -> Option<PathBuf> {+ #[cfg(windows)]+ let names = [+ command.to_owned(),+ format!("{command}.exe"),+ format!("{command}.cmd"),+ format!("{command}.bat"),+ ];+ #[cfg(not(windows))]+ let names = [command.to_owned()];++ paths+ .iter()+ .flat_map(|directory| names.iter().map(move |name| directory.join(name)))+ .find(|candidate| is_executable(candidate))+}++#[cfg(unix)]+fn is_executable(path: &Path) -> bool {+ use std::os::unix::fs::PermissionsExt as _;++ path.metadata()+ .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)+}++#[cfg(not(unix))]+fn is_executable(path: &Path) -> bool {+ path.is_file()+}++impl CommandLookup for PathCommands {+ fn resolve(&self, command: &str) -> Option<&Path> {+ self.found.get(command).map(PathBuf::as_path)+ }+}++/// One known way to expose an installed agent harness over ACP.+pub trait AgentPreset: Sync {+ /// Typed preset identity.+ fn kind(&self) -> AgentKind;+ /// Human-readable name.+ fn name(&self) -> &'static str;+ /// Resolve prerequisites and the corresponding launch specification.+ fn detect(&self, commands: &dyn CommandLookup) -> Availability;+ /// Whether an existing raw harness config represents this preset.+ fn recognizes(&self, harness: &Harness) -> bool;+}++fn direct(+ preset: &dyn AgentPreset,+ commands: &dyn CommandLookup,+ command: &'static str,+ args: impl IntoIterator<Item = &'static str>,+) -> Availability {+ if commands.resolve(command).is_none() {+ return Availability::Unavailable {+ missing: vec![command],+ };+ }+ Availability::Available(DetectedAgent {+ kind: preset.kind(),+ name: preset.name(),+ launch: LaunchSpec::new(command, args),+ note: None,+ })+}++fn npm_adapter(+ preset: &dyn AgentPreset,+ commands: &dyn CommandLookup,+ cli: &'static str,+ package: &'static str,+) -> Availability {+ let missing = [cli, "npm", "npx"]+ .into_iter()+ .filter(|command| commands.resolve(command).is_none())+ .collect::<Vec<_>>();+ if !missing.is_empty() {+ return Availability::Unavailable { missing };+ }+ Availability::Available(DetectedAgent {+ kind: preset.kind(),+ name: preset.name(),+ launch: LaunchSpec::new("npx", ["-y", package]),+ note: Some("via npm ACP adapter"),+ })+}++fn is_launch(harness: &Harness, command: &str, args: &[&str]) -> bool {+ harness.command == command+ && harness+ .args+ .iter()+ .map(String::as_str)+ .eq(args.iter().copied())+}++/// Return installed agents in product-preference order.+pub fn discover(commands: &dyn CommandLookup) -> Vec<DetectedAgent> {+ PRESETS+ .iter()+ .filter_map(|preset| match preset.detect(commands) {+ Availability::Available(agent) => Some(agent),+ Availability::Unavailable { .. } => None,+ })+ .collect()+}++/// Friendly name for an existing launch configuration.+pub fn name_for(harness: &Harness) -> Option<&'static str> {+ PRESETS+ .iter()+ .find(|preset| preset.recognizes(harness))+ .map(|preset| preset.name())+}++/// Parse a custom command line into an ACP launch specification.+pub fn custom(command_line: &str) -> Result<DetectedAgent, String> {+ let mut parts = shell_words::split(command_line)+ .map_err(|error| format!("Could not parse the command: {error}"))?+ .into_iter();+ let command = parts+ .next()+ .filter(|command| !command.is_empty())+ .ok_or_else(|| "Command must not be empty".to_owned())?;+ Ok(DetectedAgent {+ kind: AgentKind::Custom,+ name: "Custom command",+ launch: LaunchSpec {+ command,+ args: parts.collect(),+ },+ note: None,+ })+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs b/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rsnew file mode 100644index 0000000000..02609198bd--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs@@ -0,0 +1,24 @@+use super::{AgentKind, AgentPreset, Availability, CommandLookup, is_launch, npm_adapter};+use crate::config::Harness;++const ADAPTER: &str = "@agentclientprotocol/[email protected]";++pub(super) struct ClaudeCode;++impl AgentPreset for ClaudeCode {+ fn kind(&self) -> AgentKind {+ AgentKind::ClaudeCode+ }++ fn name(&self) -> &'static str {+ "Claude Code"+ }++ fn detect(&self, commands: &dyn CommandLookup) -> Availability {+ npm_adapter(self, commands, "claude", ADAPTER)+ }++ fn recognizes(&self, harness: &Harness) -> bool {+ is_launch(harness, "npx", &["-y", ADAPTER])+ }+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs b/crates/coding_agent_worker/src/tui/agent_catalog/codex.rsnew file mode 100644index 0000000000..0b54469ed9--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs@@ -0,0 +1,24 @@+use super::{AgentKind, AgentPreset, Availability, CommandLookup, is_launch, npm_adapter};+use crate::config::Harness;++const ADAPTER: &str = "@agentclientprotocol/[email protected]";++pub(super) struct Codex;++impl AgentPreset for Codex {+ fn kind(&self) -> AgentKind {+ AgentKind::Codex+ }++ fn name(&self) -> &'static str {+ "Codex CLI"+ }++ fn detect(&self, commands: &dyn CommandLookup) -> Availability {+ npm_adapter(self, commands, "codex", ADAPTER)+ }++ fn recognizes(&self, harness: &Harness) -> bool {+ is_launch(harness, "npx", &["-y", ADAPTER])+ }+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/hermes.rs b/crates/coding_agent_worker/src/tui/agent_catalog/hermes.rsnew file mode 100644index 0000000000..208d610aa3--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/hermes.rs@@ -0,0 +1,26 @@+use super::{AgentKind, AgentPreset, Availability, CommandLookup, direct, is_launch};+use crate::config::Harness;++pub(super) struct Hermes;++impl AgentPreset for Hermes {+ fn kind(&self) -> AgentKind {+ AgentKind::Hermes+ }++ fn name(&self) -> &'static str {+ "Hermes Agent"+ }++ fn detect(&self, commands: &dyn CommandLookup) -> Availability {+ if commands.resolve("hermes").is_some() {+ direct(self, commands, "hermes", ["acp"])+ } else {+ direct(self, commands, "hermes-acp", [])+ }+ }++ fn recognizes(&self, harness: &Harness) -> bool {+ is_launch(harness, "hermes", &["acp"]) || is_launch(harness, "hermes-acp", &[])+ }+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/open_claw.rs b/crates/coding_agent_worker/src/tui/agent_catalog/open_claw.rsnew file mode 100644index 0000000000..f18613e43d--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/open_claw.rs@@ -0,0 +1,22 @@+use super::{AgentKind, AgentPreset, Availability, CommandLookup, direct, is_launch};+use crate::config::Harness;++pub(super) struct OpenClaw;++impl AgentPreset for OpenClaw {+ fn kind(&self) -> AgentKind {+ AgentKind::OpenClaw+ }++ fn name(&self) -> &'static str {+ "OpenClaw"+ }++ fn detect(&self, commands: &dyn CommandLookup) -> Availability {+ direct(self, commands, "openclaw", ["acp"])+ }++ fn recognizes(&self, harness: &Harness) -> bool {+ is_launch(harness, "openclaw", &["acp"])+ }+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/open_code.rs b/crates/coding_agent_worker/src/tui/agent_catalog/open_code.rsnew file mode 100644index 0000000000..6781b3f60c--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/open_code.rs@@ -0,0 +1,22 @@+use super::{AgentKind, AgentPreset, Availability, CommandLookup, direct, is_launch};+use crate::config::Harness;++pub(super) struct OpenCode;++impl AgentPreset for OpenCode {+ fn kind(&self) -> AgentKind {+ AgentKind::OpenCode+ }++ fn name(&self) -> &'static str {+ "OpenCode"+ }++ fn detect(&self, commands: &dyn CommandLookup) -> Availability {+ direct(self, commands, "opencode", ["acp"])+ }++ fn recognizes(&self, harness: &Harness) -> bool {+ is_launch(harness, "opencode", &["acp"])+ }+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/test.rs b/crates/coding_agent_worker/src/tui/agent_catalog/test.rsnew file mode 100644index 0000000000..a591e54b0b--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/test.rs@@ -0,0 +1,81 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};++use super::*;++struct Commands(HashMap<&'static str, PathBuf>);++impl Commands {+ fn new(commands: &[&'static str]) -> Self {+ Self(+ commands+ .iter()+ .map(|command| (*command, PathBuf::from(format!("/bin/{command}"))))+ .collect(),+ )+ }+}++impl CommandLookup for Commands {+ fn resolve(&self, command: &str) -> Option<&Path> {+ self.0.get(command).map(PathBuf::as_path)+ }+}++#[test]+fn direct_agents_need_only_their_command() {+ let agents = discover(&Commands::new(&["hermes", "openclaw", "opencode"]));++ assert_eq!(+ agents.iter().map(|agent| agent.kind).collect::<Vec<_>>(),+ [AgentKind::Hermes, AgentKind::OpenClaw, AgentKind::OpenCode]+ );+ assert_eq!(agents[0].launch, LaunchSpec::new("hermes", ["acp"]));+}++#[test]+fn hermes_acp_launcher_is_used_as_a_fallback() {+ let agents = discover(&Commands::new(&["hermes-acp"]));++ assert_eq!(agents.len(), 1);+ assert_eq!(agents[0].launch, LaunchSpec::new("hermes-acp", []));+}++#[test]+fn adapter_agents_require_the_cli_and_npm_tooling() {+ assert!(discover(&Commands::new(&["claude", "npm"])).is_empty());++ let agents = discover(&Commands::new(&["claude", "codex", "npm", "npx"]));+ assert_eq!(+ agents.iter().map(|agent| agent.kind).collect::<Vec<_>>(),+ [AgentKind::ClaudeCode, AgentKind::Codex]+ );+ assert_eq!(agents[0].launch.command, "npx");+ assert_eq!(agents[0].note, Some("via npm ACP adapter"));+}++#[test]+fn existing_launch_specs_are_recognized() {+ let harness = Harness {+ command: "hermes".to_owned(),+ args: vec!["acp".to_owned()],+ };+ assert_eq!(name_for(&harness), Some("Hermes Agent"));++ let custom = Harness {+ command: "my-agent".to_owned(),+ args: Vec::new(),+ };+ assert_eq!(name_for(&custom), None);+}++#[test]+fn custom_commands_preserve_quoted_arguments() {+ let agent = custom(r#"my-agent --mode acp --name "Macro Agent""#).expect("custom command");++ assert_eq!(agent.launch.command, "my-agent");+ assert_eq!(+ agent.launch.args,+ ["--mode", "acp", "--name", "Macro Agent"]+ );+}diff --git a/crates/coding_agent_worker/src/tui/api.rs b/crates/coding_agent_worker/src/tui/api.rsindex b71f8ab235..fc1a4fa555 100644--- a/crates/coding_agent_worker/src/tui/api.rs+++ b/crates/coding_agent_worker/src/tui/api.rs@@ -5,7 +5,7 @@ use reqwest::StatusCode;use rootcause::prelude::ResultExt as _;use crate::config::Config;-use crate::outbound::credentials::HarnessCredentials;+use crate::config::HarnessCredentials;const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";diff --git a/crates/coding_agent_worker/src/tui/app.rs b/crates/coding_agent_worker/src/tui/app.rsnew file mode 100644index 0000000000..2a06ed8941--- /dev/null+++ b/crates/coding_agent_worker/src/tui/app.rs@@ -0,0 +1,564 @@+#[cfg(test)]+mod test;++use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};+use harnesses::domain::models::CreatedPairing;+use tui_input::Input;++use super::agent_catalog::{self, DetectedAgent, PathCommands};+use super::api::{HarnessSelfApi, Snapshot};+use super::config_form::{ConfigForm, SETTINGS, Setting};+use super::input::handle_text_input;+use super::logging::LogBuffer;+use super::platform::{BrowserTarget, copy_to_clipboard};+use super::process;+use crate::config::{Config, HarnessCredentials};+use crate::daemon::Daemon;+use crate::outbound::pairing::{ClaimStatus, PairingClient};++/// How often the dashboard re-reads the server.+pub(crate) const REFRESH_EVERY: Duration = Duration::from_secs(3);++/// Which tab is showing.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum Tab {+ Overview,+ Sessions,+ Config,+ Logs,+}++impl Tab {+ pub(crate) const ALL: [Tab; 4] = [Tab::Overview, Tab::Sessions, Tab::Config, Tab::Logs];++ pub(crate) fn title(self) -> &'static str {+ match self {+ Tab::Overview => "Overview",+ Tab::Sessions => "Sessions",+ Tab::Config => "Config",+ Tab::Logs => "Logs",+ }+ }++ fn next(self) -> Tab {+ match self {+ Tab::Overview => Tab::Sessions,+ Tab::Sessions => Tab::Config,+ Tab::Config => Tab::Logs,+ Tab::Logs => Tab::Overview,+ }+ }++ fn previous(self) -> Tab {+ match self {+ Tab::Overview => Tab::Logs,+ Tab::Sessions => Tab::Overview,+ Tab::Config => Tab::Sessions,+ Tab::Logs => Tab::Config,+ }+ }+}++/// A modal claiming the keyboard, when one is up.+pub(crate) enum Mode {+ /// Browsing; keys act on the current tab.+ Normal,+ /// Editing one config setting's value.+ EditSetting {+ /// Index into [`SETTINGS`].+ index: usize,+ /// The text being typed.+ buffer: Input,+ },+ /// Choosing from the ACP agents installed on this machine.+ AgentPicker {+ /// Selected agent index.+ selected: usize,+ },+ /// Entering an arbitrary ACP command line.+ CustomAgent { buffer: Input },+ /// Confirming harness removal.+ ConfirmDelete,+ /// A pairing in flight: code shown, waiting for approval.+ Pairing {+ /// The open pairing.+ created: CreatedPairing,+ /// When the claim was last polled.+ last_poll: Instant,+ },+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ApplyConfig {+ Now,+ NextPairing,+}++/// Everything the UI renders from.+pub(crate) struct App {+ pub(crate) config_path: PathBuf,+ pub(crate) config: Config,+ pub(crate) credentials: Option<HarnessCredentials>,+ pub(crate) snapshot: Snapshot,+ /// This process's pid - the TUI and the daemon are this one process.+ pub(crate) pid: u32,+ /// The spawned harness child, when serving and one is found.+ pub(crate) harness_process: Option<process::Child>,+ pub(crate) tab: Tab,+ pub(crate) mode: Mode,+ pub(crate) selected_setting: usize,+ pub(crate) form: ConfigForm,+ pub(crate) agents: Vec<DetectedAgent>,+ pub(crate) status: Option<(String, bool)>,+ pub(crate) spinner: usize,+ pub(crate) logs: LogBuffer,+ pub(crate) daemon: Option<Daemon>,+ pub(crate) pending_browser: Option<BrowserTarget>,+ last_refresh: Option<Instant>,+ pub(crate) quit: bool,+}++impl App {+ pub(crate) fn load(config_path: &Path, logs: LogBuffer) -> rootcause::Result<Self> {+ let config = Config::load(config_path)?;+ let credentials = config+ .credentials+ .clone()+ .filter(HarnessCredentials::is_valid);+ let form = ConfigForm::load(config_path)?;+ let agents = agent_catalog::discover(&PathCommands::discover());+ Ok(Self {+ config_path: config_path.to_owned(),+ config,+ credentials,+ snapshot: Snapshot::default(),+ pid: std::process::id(),+ harness_process: None,+ tab: Tab::Overview,+ mode: Mode::Normal,+ selected_setting: 0,+ form,+ agents,+ status: None,+ spinner: 0,+ logs,+ daemon: None,+ pending_browser: None,+ last_refresh: None,+ quit: false,+ })+ }++ /// Whether the in-process serving core is up.+ pub(crate) fn serving(&self) -> bool {+ self.daemon.as_ref().is_some_and(Daemon::is_running)+ }++ /// (Re)start the serving core on the current config and credential.+ pub(crate) async fn restart_daemon(&mut self) -> bool {+ if let Some(daemon) = self.daemon.take() {+ daemon.stop().await;+ }+ let Some(credentials) = self.credentials.clone() else {+ return false;+ };+ match Daemon::start(self.config.clone(), credentials, &self.config_path).await {+ Ok(daemon) => {+ self.daemon = Some(daemon);+ true+ }+ Err(error) => {+ self.fail(format!("daemon failed to start: {error}"));+ false+ }+ }+ }++ /// Stop the serving core, if it is up.+ pub(crate) async fn stop_daemon(&mut self) {+ if let Some(daemon) = self.daemon.take() {+ daemon.stop().await;+ }+ }++ /// The approval URL of the pairing in flight, when one is.+ fn pairing_url(&self) -> Option<String> {+ match &self.mode {+ Mode::Pairing { created, .. } => {+ Some(self.config.macro_api.pairing_approval_url(&created.code))+ }+ _ => None,+ }+ }++ pub(crate) fn paired(&self) -> bool {+ self.credentials.is_some()+ }++ fn api(&self) -> Option<HarnessSelfApi> {+ self.credentials+ .as_ref()+ .map(|credentials| HarnessSelfApi::new(&self.config, credentials))+ }++ pub(crate) fn ok(&mut self, message: impl Into<String>) {+ self.status = Some((message.into(), false));+ }++ pub(crate) fn fail(&mut self, message: impl Into<String>) {+ self.status = Some((message.into(), true));+ }++ pub(crate) async fn refresh(&mut self) {+ // Local process facts refresh with the dashboard, not with the network.+ self.harness_process = if self.serving() {+ process::harness_child(&self.config.harness.command)+ } else {+ None+ };+ let Some(api) = self.api() else {+ self.snapshot = Snapshot::default();+ return;+ };+ match api.snapshot().await {+ Ok(snapshot) => {+ self.snapshot = snapshot;+ self.last_refresh = Some(Instant::now());+ }+ Err(error) => self.fail(format!("refresh failed: {error}")),+ }+ }++ pub(crate) async fn maybe_refresh(&mut self) {+ let due = self+ .last_refresh+ .is_none_or(|last| last.elapsed() >= REFRESH_EVERY);+ if due {+ self.refresh().await;+ }+ }++ pub(crate) async fn start_pairing(&mut self) {+ // Re-read the config so an edit saved a moment ago (a new name or+ // scope) is what this pairing asks for.+ match Config::load(&self.config_path) {+ Ok(config) => self.config = config,+ Err(error) => return self.fail(format!("config reload failed: {error}")),+ }+ let client = PairingClient::new(&self.config);+ match client.start(&self.config).await {+ Ok(created) => {+ // The approval page pre-fills the code, so opening the+ // browser is usually the whole remaining gesture.+ let url = self.config.macro_api.pairing_approval_url(&created.code);+ self.pending_browser = Some(BrowserTarget::Pairing(url));+ self.mode = Mode::Pairing {+ created,+ last_poll: Instant::now(),+ };+ }+ Err(error) => self.fail(format!("pairing failed to start: {error}")),+ }+ }++ pub(crate) async fn poll_pairing(&mut self) {+ // Copy what the poll needs out of the mode first, so the network call+ // below is free to report back into `self`.+ let (pairing_id, device_secret) = {+ let Mode::Pairing { created, last_poll } = &mut self.mode else {+ return;+ };+ let interval = Duration::from_secs(created.poll_interval_seconds.max(1));+ if last_poll.elapsed() < interval {+ return;+ }+ *last_poll = Instant::now();+ if created.expires_at <= chrono::Utc::now() {+ self.mode = Mode::Normal;+ return self.fail("the pairing expired before it was approved");+ }+ (created.pairing_id, created.device_secret.clone())+ };+ let client = PairingClient::new(&self.config);+ match client.claim(pairing_id, &device_secret).await {+ Ok(ClaimStatus::Pending) => {}+ Ok(ClaimStatus::Claimed(credentials)) => {+ if let Err(error) = self.form.persist_credentials(&credentials) {+ self.mode = Mode::Normal;+ return self.fail(format!("could not save credentials: {error}"));+ }+ match Config::load(&self.config_path) {+ Ok(config) => self.config = config,+ Err(error) => {+ self.mode = Mode::Normal;+ return self.fail(format!("could not reload credentials: {error}"));+ }+ }+ self.credentials = Some(credentials);+ self.mode = Mode::Normal;+ self.restart_daemon().await;+ if self.serving() {+ self.ok("paired and serving");+ }+ self.refresh().await;+ }+ Ok(ClaimStatus::Gone(reason)) => {+ self.mode = Mode::Normal;+ self.fail(reason);+ }+ Err(error) => {+ self.mode = Mode::Normal;+ self.fail(format!("pairing poll failed: {error}"));+ }+ }+ }++ async fn delete_harness(&mut self) {+ let Some(api) = self.api() else {+ return self.fail("not paired");+ };+ if let Err(error) = api.delete_self().await {+ return self.fail(format!("{error}"));+ }+ // The credential is dead either way; stop serving with it and drop+ // the local state that belonged to it so the next pairing starts+ // clean.+ self.stop_daemon().await;+ if let Err(error) = self.form.clear_credentials() {+ return self.fail(format!(+ "harness removed, but credentials could not be cleared: {error}"+ ));+ }+ match Config::load(&self.config_path) {+ Ok(config) => self.config = config,+ Err(error) => {+ return self.fail(format!("credentials cleared, but reload failed: {error}"));+ }+ }+ let _ = std::fs::remove_file(self.config_path.with_extension("webhook-state.json"));+ self.credentials = None;+ self.snapshot = Snapshot::default();+ self.ok("harness removed - press p to pair again");+ }++ pub(crate) async fn on_key(&mut self, key: KeyEvent) {+ if key.kind != KeyEventKind::Press {+ return;+ }+ // Ctrl-C always quits, whatever is up.+ if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {+ self.quit = true;+ return;+ }++ match self.mode {+ Mode::Normal => self.on_normal_key(key).await,+ Mode::ConfirmDelete => {+ self.mode = Mode::Normal;+ if matches!(key.code, KeyCode::Char('y') | KeyCode::Char('Y')) {+ self.delete_harness().await;+ }+ }+ Mode::Pairing { .. } => {+ match key.code {+ KeyCode::Esc => {+ self.mode = Mode::Normal;+ self.ok("pairing abandoned; the code expires on its own");+ }+ KeyCode::Char('o') => {+ let url = self.pairing_url();+ if let Some(url) = url {+ self.pending_browser = Some(BrowserTarget::Pairing(url));+ }+ }+ KeyCode::Char('c') => {+ let code = match &self.mode {+ Mode::Pairing { created, .. } => Some(created.code.clone()),+ _ => None,+ };+ if let Some(code) = code {+ if copy_to_clipboard(&code) {+ self.ok(format!("copied {code}"));+ } else {+ self.fail("could not access the system clipboard; select the code to copy it");+ }+ }+ }+ _ => {}+ }+ }+ Mode::EditSetting { .. } => self.on_edit_key(key).await,+ Mode::AgentPicker { .. } => self.on_agent_picker_key(key).await,+ Mode::CustomAgent { .. } => self.on_custom_agent_key(key).await,+ }+ }++ async fn on_edit_key(&mut self, key: KeyEvent) {+ let Mode::EditSetting { index, buffer } = &mut self.mode else {+ return;+ };+ match key.code {+ KeyCode::Esc => self.mode = Mode::Normal,+ KeyCode::Backspace => {+ handle_text_input(buffer, key);+ }+ KeyCode::Enter => {+ let index = *index;+ let input = buffer.value().to_owned();+ self.mode = Mode::Normal;+ self.commit_edit(index, input).await;+ }+ _ => handle_text_input(buffer, key),+ }+ }++ async fn commit_edit(&mut self, index: usize, input: String) {+ let setting = SETTINGS[index];+ if let Err(message) = self.form.apply_text(setting, &input) {+ return self.fail(message);+ }+ let apply = match setting {+ Setting::Workspace => ApplyConfig::Now,+ Setting::Name => ApplyConfig::NextPairing,+ Setting::Agent | Setting::Scope => unreachable!("not edited as text"),+ };+ self.save_config(apply).await;+ }++ async fn on_agent_picker_key(&mut self, key: KeyEvent) {+ let Mode::AgentPicker { selected } = &mut self.mode else {+ return;+ };+ match key.code {+ KeyCode::Esc => self.mode = Mode::Normal,+ KeyCode::Up | KeyCode::Char('k') => *selected = selected.saturating_sub(1),+ KeyCode::Down | KeyCode::Char('j') => {+ *selected = (*selected + 1).min(self.agents.len());+ }+ KeyCode::Char('?') => self.pending_browser = Some(BrowserTarget::BringYourOwn),+ KeyCode::Enter => {+ if *selected == self.agents.len() {+ let command = shell_words::join(+ std::iter::once(self.config.harness.command.as_str())+ .chain(self.config.harness.args.iter().map(String::as_str)),+ );+ self.mode = Mode::CustomAgent {+ buffer: command.into(),+ };+ } else {+ let agent = self.agents.get(*selected).cloned();+ self.mode = Mode::Normal;+ if let Some(agent) = agent {+ self.form.apply_agent(&agent);+ self.save_config(ApplyConfig::Now).await;+ }+ }+ }+ _ => {}+ }+ }++ async fn on_custom_agent_key(&mut self, key: KeyEvent) {+ let Mode::CustomAgent { buffer } = &mut self.mode else {+ return;+ };+ match key.code {+ KeyCode::Esc => {+ self.mode = Mode::AgentPicker {+ selected: self.agents.len(),+ };+ }+ KeyCode::Enter => match agent_catalog::custom(buffer.value()) {+ Ok(agent) => {+ self.mode = Mode::Normal;+ self.form.apply_agent(&agent);+ self.save_config(ApplyConfig::Now).await;+ }+ Err(error) => self.fail(error),+ },+ _ => handle_text_input(buffer, key),+ }+ }++ async fn save_config(&mut self, apply: ApplyConfig) {+ match self.form.save() {+ Ok(()) => match Config::load(&self.config_path) {+ Ok(config) => {+ self.config = config;+ // The core reads config at start, so a save while serving+ // means a restart to apply it.+ if apply == ApplyConfig::Now && self.paired() {+ if self.restart_daemon().await {+ self.ok("saved and applied");+ }+ } else if apply == ApplyConfig::NextPairing && self.paired() {+ self.ok("saved; applies at next pairing");+ } else {+ self.ok("saved");+ }+ }+ Err(error) => self.fail(format!("saved, but reload failed: {error}")),+ },+ Err(error) => {+ // Reload the form so the rejected edit does not linger in the+ // document.+ if let Ok(form) = ConfigForm::load(&self.config_path) {+ self.form = form;+ }+ self.fail(format!("{error}"));+ }+ }+ }++ async fn on_normal_key(&mut self, key: KeyEvent) {+ match key.code {+ KeyCode::Char('q') => self.quit = true,+ KeyCode::Tab => self.tab = self.tab.next(),+ KeyCode::Right | KeyCode::Char('l') => self.tab = self.tab.next(),+ KeyCode::Left | KeyCode::Char('h') => self.tab = self.tab.previous(),+ KeyCode::Char('1') => self.tab = Tab::Overview,+ KeyCode::Char('2') => self.tab = Tab::Sessions,+ KeyCode::Char('3') => self.tab = Tab::Config,+ KeyCode::Char('4') => self.tab = Tab::Logs,+ KeyCode::Char('r') => {+ self.last_refresh = None;+ self.maybe_refresh().await;+ }+ KeyCode::Char('p') => self.start_pairing().await,+ KeyCode::Char('d') if self.paired() => self.mode = Mode::ConfirmDelete,+ KeyCode::Up | KeyCode::Char('k') if self.tab == Tab::Config => {+ self.selected_setting = self.selected_setting.saturating_sub(1);+ }+ KeyCode::Down | KeyCode::Char('j') if self.tab == Tab::Config => {+ self.selected_setting = (self.selected_setting + 1).min(SETTINGS.len() - 1);+ }+ KeyCode::Enter if self.tab == Tab::Config => match SETTINGS[self.selected_setting] {+ Setting::Agent => {+ let selected = self+ .agents+ .iter()+ .position(|agent| {+ agent.launch.command == self.config.harness.command+ && agent.launch.args == self.config.harness.args+ })+ .unwrap_or(self.agents.len());+ self.mode = Mode::AgentPicker { selected };+ }+ Setting::Scope => {+ self.form.toggle_scope(&self.config);+ self.save_config(ApplyConfig::NextPairing).await;+ }+ setting @ (Setting::Workspace | Setting::Name) => {+ self.mode = Mode::EditSetting {+ index: self.selected_setting,+ buffer: self.form.edit_value(setting).into(),+ };+ }+ },+ _ => {}+ }+ }+}diff --git a/crates/coding_agent_worker/src/tui/app/test.rs b/crates/coding_agent_worker/src/tui/app/test.rsnew file mode 100644index 0000000000..d74d7d52b7--- /dev/null+++ b/crates/coding_agent_worker/src/tui/app/test.rs@@ -0,0 +1,9 @@+use super::*;++#[test]+fn tabs_wrap_in_both_directions() {+ assert_eq!(Tab::Overview.previous(), Tab::Logs);+ assert_eq!(Tab::Overview.next(), Tab::Sessions);+ assert_eq!(Tab::Logs.next(), Tab::Overview);+ assert_eq!(Tab::Logs.previous(), Tab::Config);+}diff --git a/crates/coding_agent_worker/src/tui/config_form.rs b/crates/coding_agent_worker/src/tui/config_form.rsindex 3719f0b2fd..3e82dd14b8 100644--- a/crates/coding_agent_worker/src/tui/config_form.rs+++ b/crates/coding_agent_worker/src/tui/config_form.rs@@ -1,97 +1,64 @@-//! The editable view of `macro.toml` the TUI's Config tab presents.-//!-//! Edits go through `toml_edit` so the user's comments and layout survive a-//! save. Every field is validated the same way the daemon's own loader is:-//! the whole document is re-parsed as [`crate::config::Config`] before it is-//! written, so the TUI cannot save a config `macrod` would refuse to boot.+//! Focused, comment-preserving edits to `macrod.toml`.use std::path::{Path, PathBuf};use rootcause::prelude::ResultExt as _;use toml_edit::{DocumentMut, Item, value};-/// One editable field: where it lives in the TOML and how to show it.+use super::agent_catalog::{DetectedAgent, name_for};+use crate::config::{Config, HarnessCredentials, IdentityScope};++#[cfg(test)]+mod test;++mod environment {+ macro_env_var::maybe_env_var! {+ pub struct DevMode;+ }+}++const DEFAULT_CONFIG: &str = include_str!("../../default.macrod.toml");+const DEV_API_URL: &str = "https://agent-harness-dev.macro.com";+const DEV_STORAGE_URL: &str = "https://dev-gateway.macro.com/dss";+const DEV_WEB_URL: &str = "https://dev.macro.com/app";+#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub struct Field {- /// Display label.- pub label: &'static str,- /// `[section]` the key lives in.- pub section: &'static str,- /// Key within the section.- pub key: &'static str,- /// How the value is edited and rendered.- pub kind: FieldKind,+enum Deployment {+ Production,+ Development,}-/// How a field's value is represented while editing.+/// User-facing settings shown by the Config tab and Quickstart.#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum FieldKind {- /// A plain string.- Text,- /// A string that may be absent; an empty edit removes the key.- OptionalText,- /// A string array, edited comma-separated.- List,- /// `private` / `team`, toggled rather than typed.+pub enum Setting {+ /// Installed ACP agent to launch.+ Agent,+ /// Directory sessions run in.+ Workspace,+ /// Display name requested during pairing.+ Name,+ /// Private or team ownership requested during pairing.Scope,}-/// Every field the Config tab exposes, in display order.-pub const FIELDS: &[Field] = &[- Field {- label: "Harness name",- section: "identity",- key: "name",- kind: FieldKind::OptionalText,- },- Field {- label: "Scope",- section: "identity",- key: "scope",- kind: FieldKind::Scope,- },- Field {- label: "Harness command",- section: "harness",- key: "command",- kind: FieldKind::Text,- },- Field {- label: "Harness args",- section: "harness",- key: "args",- kind: FieldKind::List,- },- Field {- label: "Workspace path",- section: "workspace",- key: "path",- kind: FieldKind::Text,- },- Field {- label: "Workspace repo URL",- section: "workspace",- key: "repo_url",- kind: FieldKind::OptionalText,- },- Field {- label: "Agent-harness API URL",- section: "macro",- key: "api_url",- kind: FieldKind::Text,- },- Field {- label: "Storage API URL",- section: "macro",- key: "storage_url",- kind: FieldKind::Text,- },- Field {- label: "Web app URL",- section: "macro",- key: "web_url",- kind: FieldKind::OptionalText,- },+impl Setting {+ /// Display label.+ pub fn label(self) -> &'static str {+ match self {+ Self::Agent => "Agent",+ Self::Workspace => "Workspace",+ Self::Name => "Name",+ Self::Scope => "Access",+ }+ }+}++/// Settings in keyboard navigation order.+pub const SETTINGS: &[Setting] = &[+ Setting::Agent,+ Setting::Workspace,+ Setting::Name,+ Setting::Scope,];/// The config document being viewed and edited.@@ -101,7 +68,7 @@ pub struct ConfigForm {}impl ConfigForm {- /// Load the config file into an editable document.+ /// Load an existing config as an editable document.pub fn load(path: &Path) -> rootcause::Result<Self> {let raw = std::fs::read_to_string(path).context(format!("failed to read config at {}", path.display()))?;@@ -114,71 +81,209 @@ impl ConfigForm {})}- /// The current display value of a field.- pub fn display(&self, field: &Field) -> String {- let item = self- .doc- .get(field.section)- .and_then(|section| section.get(field.key));- match (field.kind, item) {- (FieldKind::List, Some(Item::Value(value))) => value- .as_array()- .map(|array| {- array- .iter()- .filter_map(|entry| entry.as_str())- .collect::<Vec<_>>()- .join(", ")- })- .unwrap_or_default(),- (FieldKind::Scope, item) => item.and_then(Item::as_str).unwrap_or("private").to_owned(),- (_, Some(Item::Value(value))) => value.as_str().unwrap_or_default().to_owned(),- _ => String::new(),+ /// Create a config from embedded defaults, selecting dev when `DEV_MODE` is present.+ pub fn create(path: &Path, agent: &DetectedAgent, workspace: &Path) -> rootcause::Result<()> {+ let deployment = if environment::DevMode::new().is_some() {+ Deployment::Development+ } else {+ Deployment::Production+ };+ Self::create_for_deployment(path, agent, workspace, deployment)+ }++ fn create_for_deployment(+ path: &Path,+ agent: &DetectedAgent,+ workspace: &Path,+ deployment: Deployment,+ ) -> rootcause::Result<()> {+ if !workspace.is_absolute() || !workspace.is_dir() {+ rootcause::bail!("the Quickstart workspace must be an existing absolute directory");}+ let doc = DEFAULT_CONFIG+ .parse::<DocumentMut>()+ .expect("the embedded macrod config template must be valid TOML");+ let mut form = Self {+ path: path.to_owned(),+ doc,+ };+ form.apply_agent(agent);+ form.set_string("workspace", "path", &workspace.to_string_lossy());+ if deployment == Deployment::Development {+ form.set_string("macro", "api_url", DEV_API_URL);+ form.set_string("macro", "storage_url", DEV_STORAGE_URL);+ form.set_string("macro", "web_url", DEV_WEB_URL);+ }+ form.save()}- /// Apply an edited value to a field, in memory.- pub fn apply(&mut self, field: &Field, input: &str) -> Result<(), String> {+ /// Display a user-facing setting from the validated config.+ pub fn display(&self, setting: Setting, config: &Config) -> String {+ match setting {+ Setting::Agent => name_for(&config.harness)+ .map(str::to_owned)+ .unwrap_or_else(|| format!("Custom ({})", config.harness.command)),+ Setting::Workspace => config.workspace.path.display().to_string(),+ Setting::Name => config+ .identity+ .name+ .clone()+ .unwrap_or_else(|| "Hostname default".to_owned()),+ Setting::Scope => match config.identity.scope {+ crate::config::IdentityScope::Private => "Private".to_owned(),+ crate::config::IdentityScope::Team => "Team".to_owned(),+ },+ }+ }++ /// Current editable text for a setting that accepts typed input.+ pub fn edit_value(&self, setting: Setting) -> String {+ match setting {+ Setting::Workspace => self.string("workspace", "path").unwrap_or_default(),+ Setting::Name => self.string("identity", "name").unwrap_or_default(),+ Setting::Agent | Setting::Scope => String::new(),+ }+ }++ /// Apply typed input to a text setting.+ pub fn apply_text(&mut self, setting: Setting, input: &str) -> Result<(), String> {let input = input.trim();- let section = self.doc[field.section].or_insert(toml_edit::table());- match field.kind {- FieldKind::Text => {+ match setting {+ Setting::Workspace => {if input.is_empty() {- return Err(format!("{} must not be empty", field.label));+ return Err("Workspace must not be empty".to_owned());+ }+ if !Path::new(input).is_absolute() {+ return Err("Workspace must be an absolute path".to_owned());+ }+ if !Path::new(input).is_dir() {+ return Err("Workspace must be an existing directory".to_owned());}- section[field.key] = value(input);+ self.set_string("workspace", "path", input);}- FieldKind::OptionalText => {+ Setting::Name => {if input.is_empty() {- if let Some(table) = section.as_table_like_mut() {- table.remove(field.key);- }+ self.remove("identity", "name");} else {- section[field.key] = value(input);+ self.set_string("identity", "name", input);}}- FieldKind::List => {- let mut array = toml_edit::Array::new();- for entry in input.split(',').map(str::trim).filter(|s| !s.is_empty()) {- array.push(entry);- }- section[field.key] = value(array);+ Setting::Agent | Setting::Scope => {+ return Err(format!("{} is selected rather than typed", setting.label()));}- FieldKind::Scope => match input {- "private" | "team" => section[field.key] = value(input),- other => return Err(format!("scope must be private or team, not {other}")),- },}Ok(())}- /// Validate the whole document as a daemon config and write it out.+ /// Apply a detected agent's concrete launch specification.+ pub fn apply_agent(&mut self, agent: &DetectedAgent) {+ self.set_string("harness", "command", &agent.launch.command);+ let mut args = toml_edit::Array::new();+ for arg in &agent.launch.args {+ args.push(arg.as_str());+ }+ let section = self.doc["harness"].or_insert(toml_edit::table());+ section["args"] = value(args);+ }++ /// Apply Quickstart values to this document without replacing other settings.+ pub fn apply_quickstart(+ &mut self,+ agent: &DetectedAgent,+ workspace: &Path,+ scope: IdentityScope,+ ) {+ self.apply_agent(agent);+ self.set_string("workspace", "path", &workspace.to_string_lossy());+ self.set_scope(scope);+ }++ /// Toggle between private and team pairing scope.+ pub fn toggle_scope(&mut self, config: &Config) {+ let next = match config.identity.scope {+ crate::config::IdentityScope::Private => "team",+ crate::config::IdentityScope::Team => "private",+ };+ self.set_string("identity", "scope", next);+ }++ /// Set the requested scope without changing any approved credential scope.+ pub fn set_scope(&mut self, scope: IdentityScope) {+ let scope = match scope {+ IdentityScope::Private => "private",+ IdentityScope::Team => "team",+ };+ self.set_string("identity", "scope", scope);+ }++ /// Persist the credential minted by pairing in this config document.+ pub fn persist_credentials(+ &mut self,+ credentials: &HarnessCredentials,+ ) -> rootcause::Result<()> {+ self.set_string(+ "credentials",+ "harness_id",+ &credentials.harness_id.to_string(),+ );+ self.set_string("credentials", "token", &credentials.token);+ let scope = match credentials.scope {+ crate::config::HarnessScope::User => "user",+ crate::config::HarnessScope::Team => "team",+ };+ self.set_string("credentials", "scope", scope);+ self.save()+ }++ /// Remove the embedded credential while preserving the rest of the file.+ pub fn clear_credentials(&mut self) -> rootcause::Result<()> {+ self.doc.remove("credentials");+ self.save()+ }++ /// Validate the complete document and write it out.pub fn save(&self) -> rootcause::Result<()> {let rendered = self.doc.to_string();- toml::from_str::<crate::config::Config>(&rendered)+ toml::from_str::<Config>(&rendered).context("the edited config would not load; the value was rejected before writing")?;- std::fs::write(&self.path, rendered)+ write_sensitive(&self.path, rendered.as_bytes()).context(format!("failed to write config at {}", self.path.display()))?;Ok(())}++ fn string(&self, section: &str, key: &str) -> Option<String> {+ self.doc+ .get(section)+ .and_then(|section| section.get(key))+ .and_then(Item::as_str)+ .map(str::to_owned)+ }++ fn set_string(&mut self, section: &str, key: &str, input: &str) {+ let section = self.doc[section].or_insert(toml_edit::table());+ section[key] = value(input);+ }++ fn remove(&mut self, section: &str, key: &str) {+ if let Some(table) = self.doc[section].as_table_like_mut() {+ table.remove(key);+ }+ }+}++fn write_sensitive(path: &Path, contents: &[u8]) -> std::io::Result<()> {+ use std::io::Write as _;++ let mut options = std::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};+ options.mode(0o600);+ if path.exists() {+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;+ }+ }+ let mut file = options.open(path)?;+ file.write_all(contents)}diff --git a/crates/coding_agent_worker/src/tui/config_form/test.rs b/crates/coding_agent_worker/src/tui/config_form/test.rsnew file mode 100644index 0000000000..758ba94ebb--- /dev/null+++ b/crates/coding_agent_worker/src/tui/config_form/test.rs@@ -0,0 +1,188 @@+use std::fs;++use super::*;+use crate::config::{HarnessCredentials, HarnessScope};+use crate::tui::agent_catalog::{CommandLookup, discover};+use harness_id::HarnessId;++struct HermesOnly;++impl CommandLookup for HermesOnly {+ fn resolve(&self, command: &str) -> Option<&Path> {+ (command == "hermes").then_some(Path::new("/bin/hermes"))+ }+}++#[test]+fn creates_a_valid_production_config() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let agent = discover(&HermesOnly).remove(0);++ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)+ .expect("create config");+ let config = Config::load(&path).expect("load generated config");++ assert_eq!(config.harness.command, "hermes");+ assert_eq!(config.harness.args, ["acp"]);+ assert_eq!(config.workspace.path, directory.path());+ assert_eq!(config.macro_api.api_url, "https://agent-harness.macro.com");+ assert_eq!(+ config.macro_api.storage_url,+ "https://gateway.macro.com/dss"+ );+ assert_eq!(config.credentials, None);+ assert_private_mode(&path);+}++#[test]+fn creates_a_dev_config_when_dev_mode_is_set() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let agent = discover(&HermesOnly).remove(0);++ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Development)+ .expect("create config");+ let config = Config::load(&path).expect("load generated config");++ assert_eq!(config.macro_api.api_url, DEV_API_URL);+ assert_eq!(config.macro_api.storage_url, DEV_STORAGE_URL);+ assert_eq!(config.macro_api.web_url, DEV_WEB_URL);+}++#[test]+fn editing_a_setting_preserves_comments() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let agent = discover(&HermesOnly).remove(0);+ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)+ .expect("create config");+ let original = fs::read_to_string(&path).expect("read config");+ assert!(original.contains("# macrod configuration"));++ let workspace = directory.path().join("other");+ fs::create_dir(&workspace).expect("create workspace");+ let mut form = ConfigForm::load(&path).expect("load form");+ form.apply_text(Setting::Workspace, &workspace.to_string_lossy())+ .expect("edit");+ form.save().expect("save form");++ let edited = fs::read_to_string(&path).expect("read edited config");+ assert!(edited.contains("# macrod configuration"));+ assert!(edited.contains(&format!("path = {:?}", workspace.to_string_lossy())));+ assert_private_mode(&path);+}++#[test]+fn persists_and_clears_embedded_credentials_without_losing_comments() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let agent = discover(&HermesOnly).remove(0);+ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)+ .expect("create config");+ let credentials = HarnessCredentials {+ harness_id: HarnessId::TEST_A,+ token: "mhns_abc_secret".to_owned(),+ scope: HarnessScope::Team,+ };++ let mut form = ConfigForm::load(&path).expect("load form");+ form.persist_credentials(&credentials)+ .expect("persist credentials");+ let paired = Config::load(&path).expect("load paired config");+ assert_eq!(paired.credentials, Some(credentials));+ assert!(+ fs::read_to_string(&path)+ .expect("read config")+ .contains("# macrod configuration")+ );+ assert_private_mode(&path);++ form.clear_credentials().expect("clear credentials");+ let unpaired = Config::load(&path).expect("load unpaired config");+ assert_eq!(unpaired.credentials, None);+ assert!(+ !fs::read_to_string(&path)+ .expect("read config")+ .contains("[credentials]")+ );+ assert_private_mode(&path);+}++#[test]+fn quickstart_edits_preserve_existing_deployment_and_comments() {+ let directory = tempfile::tempdir().expect("temp dir");+ let workspace = directory.path().join("workspace");+ fs::create_dir(&workspace).expect("create workspace");+ let path = directory.path().join("macrod.toml");+ fs::write(+ &path,+ format!(+ "# keep me\n[macro]\napi_url = \"https://custom-api\"\nstorage_url = \"https://custom-storage\"\nweb_url = \"https://custom-web\"\n\n[identity]\nscope = \"private\"\n\n[harness]\ncommand = \"old\"\nargs = []\n\n[workspace]\npath = {:?}\n",+ directory.path().to_string_lossy()+ ),+ )+ .expect("write existing config");+ let agent = discover(&HermesOnly).remove(0);++ let mut form = ConfigForm::load(&path).expect("load existing config");+ form.apply_quickstart(&agent, &workspace, IdentityScope::Team);+ form.save().expect("save Quickstart changes");++ let config = Config::load(&path).expect("load edited config");+ assert_eq!(config.macro_api.api_url, "https://custom-api");+ assert_eq!(config.macro_api.storage_url, "https://custom-storage");+ assert_eq!(config.macro_api.web_url, "https://custom-web");+ assert_eq!(config.harness.command, "hermes");+ assert_eq!(config.workspace.path, workspace);+ assert_eq!(config.identity.scope, IdentityScope::Team);+ assert!(+ fs::read_to_string(&path)+ .expect("read config")+ .contains("# keep me")+ );+ assert_private_mode(&path);+}++#[test]+fn rejects_a_missing_workspace_edit() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let agent = discover(&HermesOnly).remove(0);+ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)+ .expect("create config");++ let mut form = ConfigForm::load(&path).expect("load form");+ assert_eq!(+ form.apply_text(Setting::Workspace, "/path/that/does/not/exist"),+ Err("Workspace must be an existing directory".to_owned())+ );+}++#[test]+fn rejects_a_relative_workspace_edit() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let agent = discover(&HermesOnly).remove(0);+ ConfigForm::create_for_deployment(&path, &agent, directory.path(), Deployment::Production)+ .expect("create config");++ let mut form = ConfigForm::load(&path).expect("load form");+ assert_eq!(+ form.apply_text(Setting::Workspace, "../other"),+ Err("Workspace must be an absolute path".to_owned())+ );+}++#[cfg(unix)]+fn assert_private_mode(path: &Path) {+ use std::os::unix::fs::PermissionsExt as _;++ assert_eq!(+ fs::metadata(path).unwrap().permissions().mode() & 0o777,+ 0o600+ );+}++#[cfg(not(unix))]+fn assert_private_mode(_path: &Path) {}diff --git a/crates/coding_agent_worker/src/tui/input.rs b/crates/coding_agent_worker/src/tui/input.rsnew file mode 100644index 0000000000..f900a58f58--- /dev/null+++ b/crates/coding_agent_worker/src/tui/input.rs@@ -0,0 +1,32 @@+#[cfg(test)]+mod test;++use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+use tui_input::{Input, InputRequest};++pub(crate) fn handle_text_input(input: &mut Input, key: KeyEvent) {+ let request = match (key.code, key.modifiers) {+ (KeyCode::Backspace, KeyModifiers::NONE) => Some(InputRequest::DeletePrevChar),+ (KeyCode::Delete, KeyModifiers::NONE) => Some(InputRequest::DeleteNextChar),+ (KeyCode::Left, KeyModifiers::NONE) => Some(InputRequest::GoToPrevChar),+ (KeyCode::Right, KeyModifiers::NONE) => Some(InputRequest::GoToNextChar),+ (KeyCode::Left, KeyModifiers::CONTROL) => Some(InputRequest::GoToPrevWord),+ (KeyCode::Right, KeyModifiers::CONTROL) => Some(InputRequest::GoToNextWord),+ (KeyCode::Home, KeyModifiers::NONE) | (KeyCode::Char('a'), KeyModifiers::CONTROL) => {+ Some(InputRequest::GoToStart)+ }+ (KeyCode::End, KeyModifiers::NONE) | (KeyCode::Char('e'), KeyModifiers::CONTROL) => {+ Some(InputRequest::GoToEnd)+ }+ (KeyCode::Char('w'), KeyModifiers::CONTROL) => Some(InputRequest::DeletePrevWord),+ (KeyCode::Char('u'), KeyModifiers::CONTROL) => Some(InputRequest::DeleteLine),+ (KeyCode::Char('k'), KeyModifiers::CONTROL) => Some(InputRequest::DeleteTillEnd),+ (KeyCode::Char(ch), KeyModifiers::NONE | KeyModifiers::SHIFT) => {+ Some(InputRequest::InsertChar(ch))+ }+ _ => None,+ };+ if let Some(request) = request {+ input.handle(request);+ }+}diff --git a/crates/coding_agent_worker/src/tui/input/test.rs b/crates/coding_agent_worker/src/tui/input/test.rsnew file mode 100644index 0000000000..da6adcb392--- /dev/null+++ b/crates/coding_agent_worker/src/tui/input/test.rs@@ -0,0 +1,19 @@+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+use tui_input::Input;++use super::handle_text_input;++fn key(code: KeyCode) -> KeyEvent {+ KeyEvent::new(code, KeyModifiers::NONE)+}++#[test]+fn text_input_supports_cursor_movement_and_insertion() {+ let mut input: Input = "ac".into();++ handle_text_input(&mut input, key(KeyCode::Left));+ handle_text_input(&mut input, key(KeyCode::Char('b')));++ assert_eq!(input.value(), "abc");+ assert_eq!(input.cursor(), 2);+}diff --git a/crates/coding_agent_worker/src/tui/logging.rs b/crates/coding_agent_worker/src/tui/logging.rsnew file mode 100644index 0000000000..8a8550876b--- /dev/null+++ b/crates/coding_agent_worker/src/tui/logging.rs@@ -0,0 +1,56 @@+use std::collections::VecDeque;+use std::sync::{Arc, Mutex};++/// The daemon's own log lines, rendered by the Logs tab.+///+/// The TUI owns the terminal, so tracing must not write to it; this is the+/// sink the subscriber writes into instead.+#[derive(Clone, Default)]+pub struct LogBuffer {+ lines: Arc<Mutex<VecDeque<String>>>,+}++impl LogBuffer {+ const CAPACITY: usize = 500;++ /// Install the global tracing subscriber writing into a fresh buffer.+ pub fn install() -> Self {+ let buffer = Self::default();+ let sink = buffer.clone();+ tracing_subscriber::fmt()+ .with_env_filter(+ tracing_subscriber::EnvFilter::try_from_default_env()+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),+ )+ .with_ansi(false)+ .with_writer(move || sink.clone())+ .init();+ buffer+ }++ /// The most recent lines, oldest first.+ pub(crate) fn tail(&self, count: usize) -> Vec<String> {+ let lines = self.lines.lock().expect("log buffer lock");+ lines.iter().rev().take(count).rev().cloned().collect()+ }+}++impl std::io::Write for LogBuffer {+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {+ let mut lines = self.lines.lock().expect("log buffer lock");+ for line in String::from_utf8_lossy(bytes).lines() {+ if line.trim().is_empty() {+ continue;+ }+ if lines.len() == Self::CAPACITY {+ lines.pop_front();+ }+ lines.push_back(line.to_owned());+ }+ Ok(bytes.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}diff --git a/crates/coding_agent_worker/src/tui/platform.rs b/crates/coding_agent_worker/src/tui/platform.rsnew file mode 100644index 0000000000..1c3a0e3ed6--- /dev/null+++ b/crates/coding_agent_worker/src/tui/platform.rs@@ -0,0 +1,60 @@+pub(crate) const BYO_AGENT_URL: &str = "https://docs.macro.com/AI/bring-your-own";++pub(crate) enum BrowserTarget {+ Pairing(String),+ BringYourOwn,+}++pub(crate) fn open_pending_browser(pending: &mut Option<BrowserTarget>) -> Option<(String, bool)> {+ let target = pending.take()?;+ let (url, success, failure) = match target {+ BrowserTarget::Pairing(url) => (+ url,+ "sent the approval page to your browser",+ "could not launch a browser; use the pairing link",+ ),+ BrowserTarget::BringYourOwn => (+ BYO_AGENT_URL.to_owned(),+ "opened the bring your own agent guide",+ "could not launch a browser; open the bring your own agent guide manually",+ ),+ };+ Some(match launch_browser_helper(&url) {+ Ok(()) => (success.to_owned(), false),+ Err(error) => (format!("{failure} ({error})"), true),+ })+}++pub(crate) fn launch_browser_helper(url: &str) -> std::io::Result<()> {+ let executable = std::env::current_exe()?;+ std::process::Command::new(executable)+ .args(["--open-url", url])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .map(|_| ())+}++pub(crate) fn browser_status(result: std::io::Result<()>) -> (String, bool) {+ match result {+ Ok(()) => ("Opened the bring your own agent guide".to_owned(), false),+ Err(error) => (format!("Could not launch a browser: {error}"), true),+ }+}++/// Put text on the system clipboard.+pub(crate) fn copy_to_clipboard(text: &str) -> bool {+ thread_local! {+ static CLIPBOARD: std::cell::RefCell<Option<arboard::Clipboard>> = const { std::cell::RefCell::new(None) };+ }+ CLIPBOARD.with(|owner| {+ let mut owner = owner.borrow_mut();+ if owner.is_none() {+ *owner = arboard::Clipboard::new().ok();+ }+ owner+ .as_mut()+ .is_some_and(|clipboard| clipboard.set_text(text).is_ok())+ })+}diff --git a/crates/coding_agent_worker/src/tui/quickstart.rs b/crates/coding_agent_worker/src/tui/quickstart.rsnew file mode 100644index 0000000000..e02b8dd0f1--- /dev/null+++ b/crates/coding_agent_worker/src/tui/quickstart.rs@@ -0,0 +1,226 @@+#[cfg(test)]+mod test;++use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};+use rootcause::prelude::ResultExt as _;+use tui_input::Input;++use super::agent_catalog::{self, AgentKind, DetectedAgent, PathCommands};+use super::input::handle_text_input;+use super::platform::{BYO_AGENT_URL, browser_status, launch_browser_helper};+use crate::config::{Config, IdentityScope};++/// Editable state shown until `macrod.toml` has a working credential.+pub(crate) struct Quickstart {+ pub(crate) agents: Vec<DetectedAgent>,+ pub(crate) selected_agent: Option<DetectedAgent>,+ pub(crate) focus: QuickstartFocus,+ pub(crate) workspace: String,+ pub(crate) scope: IdentityScope,+ pub(crate) mode: QuickstartMode,+ pub(crate) status: Option<(String, bool)>,+}++/// Keyboard focus inside Quickstart.+pub(crate) enum QuickstartMode {+ Normal,+ CustomAgent { buffer: Input },+ EditWorkspace { buffer: Input },+}++/// Focused control in the flat Quickstart form.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum QuickstartFocus {+ Agent(usize),+ Workspace,+ Scope,+ Submit,+}++pub(crate) enum QuickstartAction {+ Continue,+ Create,+ Quit,+}++impl Quickstart {+ pub(crate) fn new() -> rootcause::Result<Self> {+ let workspace = std::env::current_dir()+ .context("failed to find the current directory for Quickstart")?+ .display()+ .to_string();+ Ok(Self {+ agents: agent_catalog::discover(&PathCommands::discover()),+ selected_agent: None,+ focus: QuickstartFocus::Agent(0),+ workspace,+ scope: IdentityScope::Private,+ mode: QuickstartMode::Normal,+ status: None,+ })+ }++ pub(crate) fn from_config(config: &Config) -> Self {+ Self::from_config_with_agents(config, agent_catalog::discover(&PathCommands::discover()))+ }++ fn from_config_with_agents(config: &Config, agents: Vec<DetectedAgent>) -> Self {+ let selected_agent = agents+ .iter()+ .find(|agent| {+ agent.launch.command == config.harness.command+ && agent.launch.args == config.harness.args+ })+ .cloned()+ .or_else(|| {+ Some(DetectedAgent {+ kind: AgentKind::Custom,+ name: "Custom command",+ launch: super::agent_catalog::LaunchSpec {+ command: config.harness.command.clone(),+ args: config.harness.args.clone(),+ },+ note: None,+ })+ });+ let focus = selected_agent+ .as_ref()+ .and_then(|selected| agents.iter().position(|agent| agent.kind == selected.kind))+ .map_or(QuickstartFocus::Agent(agents.len()), QuickstartFocus::Agent);+ Self {+ agents,+ selected_agent,+ focus,+ workspace: config.workspace.path.display().to_string(),+ scope: config.identity.scope,+ mode: QuickstartMode::Normal,+ status: None,+ }+ }++ pub(crate) fn on_key(&mut self, key: KeyEvent) -> QuickstartAction {+ if key.kind != KeyEventKind::Press {+ return QuickstartAction::Continue;+ }+ if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {+ return QuickstartAction::Quit;+ }+ match &mut self.mode {+ QuickstartMode::Normal => match key.code {+ KeyCode::Char('q') => QuickstartAction::Quit,+ KeyCode::Up | KeyCode::BackTab | KeyCode::Char('k') => {+ self.focus = match self.focus {+ QuickstartFocus::Agent(index) => {+ QuickstartFocus::Agent(index.saturating_sub(1))+ }+ QuickstartFocus::Workspace => QuickstartFocus::Agent(self.agents.len()),+ QuickstartFocus::Scope => QuickstartFocus::Workspace,+ QuickstartFocus::Submit => QuickstartFocus::Scope,+ };+ QuickstartAction::Continue+ }+ KeyCode::Down | KeyCode::Tab | KeyCode::Char('j') => {+ self.focus = match self.focus {+ QuickstartFocus::Agent(index) if index < self.agents.len() => {+ QuickstartFocus::Agent(index + 1)+ }+ QuickstartFocus::Agent(_) => QuickstartFocus::Workspace,+ QuickstartFocus::Workspace => QuickstartFocus::Scope,+ QuickstartFocus::Scope | QuickstartFocus::Submit => QuickstartFocus::Submit,+ };+ QuickstartAction::Continue+ }+ KeyCode::Char('?') if self.focus == QuickstartFocus::Agent(self.agents.len()) => {+ self.status = Some(browser_status(launch_browser_helper(BYO_AGENT_URL)));+ QuickstartAction::Continue+ }+ KeyCode::Enter => match self.focus {+ QuickstartFocus::Agent(index) if index == self.agents.len() => {+ let value = self+ .selected_agent+ .as_ref()+ .filter(|agent| agent.kind == AgentKind::Custom)+ .map(|agent| {+ shell_words::join(+ std::iter::once(agent.launch.command.as_str())+ .chain(agent.launch.args.iter().map(String::as_str)),+ )+ })+ .unwrap_or_default();+ self.mode = QuickstartMode::CustomAgent {+ buffer: value.into(),+ };+ QuickstartAction::Continue+ }+ QuickstartFocus::Agent(index) => {+ self.selected_agent = self.agents.get(index).cloned();+ self.status = None;+ QuickstartAction::Continue+ }+ QuickstartFocus::Workspace => {+ self.mode = QuickstartMode::EditWorkspace {+ buffer: self.workspace.clone().into(),+ };+ QuickstartAction::Continue+ }+ QuickstartFocus::Scope => {+ self.scope = match self.scope {+ IdentityScope::Private => IdentityScope::Team,+ IdentityScope::Team => IdentityScope::Private,+ };+ QuickstartAction::Continue+ }+ QuickstartFocus::Submit if self.selected_agent.is_none() => {+ self.status =+ Some(("Choose an agent harness before continuing".to_owned(), true));+ QuickstartAction::Continue+ }+ QuickstartFocus::Submit => QuickstartAction::Create,+ },+ _ => QuickstartAction::Continue,+ },+ QuickstartMode::CustomAgent { buffer } => match key.code {+ KeyCode::Esc => {+ self.mode = QuickstartMode::Normal;+ self.focus = QuickstartFocus::Agent(self.agents.len());+ QuickstartAction::Continue+ }+ KeyCode::Enter => match agent_catalog::custom(buffer.value()) {+ Ok(agent) => {+ self.selected_agent = Some(agent);+ self.status = None;+ self.mode = QuickstartMode::Normal;+ QuickstartAction::Continue+ }+ Err(error) => {+ self.status = Some((error, true));+ QuickstartAction::Continue+ }+ },+ _ => {+ handle_text_input(buffer, key);+ QuickstartAction::Continue+ }+ },+ QuickstartMode::EditWorkspace { buffer } => match key.code {+ KeyCode::Esc => {+ self.mode = QuickstartMode::Normal;+ QuickstartAction::Continue+ }+ KeyCode::Enter if buffer.value().trim().is_empty() => {+ self.status = Some(("Workspace must not be empty".to_owned(), true));+ QuickstartAction::Continue+ }+ KeyCode::Enter => {+ self.workspace = buffer.value().trim().to_owned();+ self.mode = QuickstartMode::Normal;+ QuickstartAction::Continue+ }+ _ => {+ handle_text_input(buffer, key);+ QuickstartAction::Continue+ }+ },+ }+ }+}diff --git a/crates/coding_agent_worker/src/tui/quickstart/test.rs b/crates/coding_agent_worker/src/tui/quickstart/test.rsnew file mode 100644index 0000000000..9406ea25e4--- /dev/null+++ b/crates/coding_agent_worker/src/tui/quickstart/test.rs@@ -0,0 +1,129 @@+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++use super::*;+use crate::config::{Harness, MacroApi, Workspace};++fn key(code: KeyCode) -> KeyEvent {+ KeyEvent::new(code, KeyModifiers::NONE)+}++#[test]+fn quickstart_uses_one_flat_focus_order_without_preselecting_an_agent() {+ let mut quickstart = Quickstart {+ agents: Vec::new(),+ selected_agent: None,+ focus: QuickstartFocus::Agent(0),+ workspace: "/tmp".to_owned(),+ scope: IdentityScope::Private,+ mode: QuickstartMode::Normal,+ status: None,+ };++ quickstart.on_key(key(KeyCode::Down));+ assert_eq!(quickstart.focus, QuickstartFocus::Workspace);+ quickstart.on_key(key(KeyCode::Down));+ assert_eq!(quickstart.focus, QuickstartFocus::Scope);+ quickstart.on_key(key(KeyCode::Down));+ assert_eq!(quickstart.focus, QuickstartFocus::Submit);+ quickstart.on_key(key(KeyCode::Up));+ assert_eq!(quickstart.focus, QuickstartFocus::Scope);+ assert!(quickstart.selected_agent.is_none());+}++#[test]+fn tab_and_shift_tab_reach_and_leave_the_submit_button() {+ let mut quickstart = Quickstart {+ agents: Vec::new(),+ selected_agent: None,+ focus: QuickstartFocus::Agent(0),+ workspace: "/tmp".to_owned(),+ scope: IdentityScope::Private,+ mode: QuickstartMode::Normal,+ status: None,+ };++ quickstart.on_key(key(KeyCode::Tab));+ quickstart.on_key(key(KeyCode::Tab));+ quickstart.on_key(key(KeyCode::Tab));+ assert_eq!(quickstart.focus, QuickstartFocus::Submit);++ quickstart.on_key(key(KeyCode::BackTab));+ assert_eq!(quickstart.focus, QuickstartFocus::Scope);+}++#[test]+fn custom_agent_reedit_preserves_arguments() {+ let mut quickstart = Quickstart {+ agents: Vec::new(),+ selected_agent: Some(agent_catalog::custom("agent --mode 'acp bridge'").unwrap()),+ focus: QuickstartFocus::Agent(0),+ workspace: "/tmp".to_owned(),+ scope: IdentityScope::Private,+ mode: QuickstartMode::Normal,+ status: None,+ };++ quickstart.on_key(key(KeyCode::Enter));++ let QuickstartMode::CustomAgent { buffer } = quickstart.mode else {+ panic!("custom command should enter edit mode");+ };+ assert_eq!(buffer.value(), "agent --mode 'acp bridge'");+}++#[test]+fn unpaired_config_prefills_recognized_agent_workspace_and_scope() {+ let config = config(Harness {+ command: "hermes".to_owned(),+ args: vec!["acp".to_owned()],+ });+ let agents = vec![DetectedAgent {+ kind: AgentKind::Hermes,+ name: "Hermes",+ launch: agent_catalog::LaunchSpec {+ command: "hermes".to_owned(),+ args: vec!["acp".to_owned()],+ },+ note: None,+ }];++ let quickstart = Quickstart::from_config_with_agents(&config, agents);++ assert_eq!(quickstart.selected_agent.unwrap().kind, AgentKind::Hermes);+ assert_eq!(quickstart.workspace, "/existing/workspace");+ assert_eq!(quickstart.scope, IdentityScope::Team);+ assert_eq!(quickstart.focus, QuickstartFocus::Agent(0));+}++#[test]+fn unpaired_config_prefills_custom_command_with_all_arguments() {+ let config = config(Harness {+ command: "my-agent".to_owned(),+ args: vec!["--mode".to_owned(), "acp bridge".to_owned()],+ });++ let quickstart = Quickstart::from_config_with_agents(&config, Vec::new());+ let selected = quickstart.selected_agent.expect("selected custom agent");++ assert_eq!(selected.kind, AgentKind::Custom);+ assert_eq!(selected.launch.command, "my-agent");+ assert_eq!(selected.launch.args, ["--mode", "acp bridge"]);+ assert_eq!(quickstart.focus, QuickstartFocus::Agent(0));+}++fn config(harness: Harness) -> Config {+ let mut config: Config =+ toml::from_str(include_str!("../../../config.example.toml")).expect("example config");+ config.macro_api = MacroApi {+ api_url: "https://agent-harness.example.com".to_owned(),+ storage_url: "https://storage.example.com".to_owned(),+ web_url: "https://example.com/app".to_owned(),+ };+ config.identity.scope = IdentityScope::Team;+ config.harness = harness;+ config.workspace = Workspace {+ path: "/existing/workspace".into(),+ repo_url: None,+ };+ config+}diff --git a/crates/coding_agent_worker/src/tui/runner.rs b/crates/coding_agent_worker/src/tui/runner.rsnew file mode 100644index 0000000000..4736f7cb46--- /dev/null+++ b/crates/coding_agent_worker/src/tui/runner.rs@@ -0,0 +1,220 @@+use std::path::Path;+use std::time::Duration;++use crossterm::event::Event as TermEvent;+use rootcause::prelude::ResultExt as _;++use super::app::{App, Mode};+use super::config_form::ConfigForm;+use super::logging::LogBuffer;+use super::platform::open_pending_browser;+use super::quickstart::{Quickstart, QuickstartAction};+use super::ui;+use crate::config::{Config, IdentityScope};++#[cfg(test)]+mod test;++/// Spinner cadence and input latency budget.+const TICK: Duration = Duration::from_millis(120);++/// Run the control panel - and the daemon inside it - until the user quits.+pub async fn run(config_path: &Path, logs: LogBuffer) -> rootcause::Result<()> {+ let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel();+ // A dedicated thread owns the blocking crossterm read; the loop below+ // stays async and free to poll the network.+ std::thread::spawn(move || {+ while let Ok(event) = crossterm::event::read() {+ if input_tx.send(event).is_err() {+ return;+ }+ }+ });++ let mut terminal = ratatui::init();+ let existing_config = match Config::load(config_path) {+ Ok(config) => Some(config),+ Err(crate::config::ConfigError::Io { source, .. })+ if source.kind() == std::io::ErrorKind::NotFound =>+ {+ None+ }+ Err(error) => {+ ratatui::restore();+ return Err(error.into());+ }+ };+ let needs_quickstart = existing_config+ .as_ref()+ .is_none_or(|config| !config_is_working(config));+ let quickstarted = if !needs_quickstart {+ false+ } else {+ match run_quickstart(+ &mut terminal,+ config_path,+ existing_config.as_ref(),+ &mut input_rx,+ )+ .await+ {+ Ok(created) => created,+ Err(error) => {+ ratatui::restore();+ return Err(error);+ }+ }+ };+ if needs_quickstart && !quickstarted {+ ratatui::restore();+ return Ok(());+ }+ if !config_path.exists() {+ ratatui::restore();+ return Ok(());+ }+ let mut app = match App::load(config_path, logs) {+ Ok(app) => app,+ Err(error) => {+ ratatui::restore();+ return Err(error);+ }+ };+ let outcome = run_loop(&mut terminal, &mut app, &mut input_rx, quickstarted).await;+ ratatui::restore();+ outcome+}++async fn run_quickstart(+ terminal: &mut ratatui::DefaultTerminal,+ config_path: &Path,+ existing_config: Option<&Config>,+ input: &mut tokio::sync::mpsc::UnboundedReceiver<TermEvent>,+) -> rootcause::Result<bool> {+ let mut quickstart = match existing_config {+ Some(config) => Quickstart::from_config(config),+ None => Quickstart::new()?,+ };+ loop {+ terminal+ .draw(|frame| ui::render_quickstart(frame, &quickstart, config_path))+ .context("failed to draw Quickstart")?;+ let Some(event) = input.recv().await else {+ return Ok(false);+ };+ let TermEvent::Key(key) = event else {+ continue;+ };+ match quickstart.on_key(key) {+ QuickstartAction::Continue => {}+ QuickstartAction::Quit => return Ok(false),+ QuickstartAction::Create => {+ let Some(agent) = quickstart.selected_agent.as_ref() else {+ quickstart.status =+ Some(("Press Enter on Agent to choose one".to_owned(), true));+ continue;+ };+ let workspace = match std::path::absolute(&quickstart.workspace) {+ Ok(workspace) => workspace,+ Err(error) => {+ quickstart.status =+ Some((format!("Could not resolve the workspace: {error}"), true));+ continue;+ }+ };+ if !workspace.is_dir() {+ quickstart.status = Some((+ format!("Workspace does not exist: {}", workspace.display()),+ true,+ ));+ continue;+ }+ let saved = if existing_config.is_some() {+ ConfigForm::load(config_path).and_then(|mut form| {+ form.apply_quickstart(agent, &workspace, quickstart.scope);+ form.save()+ })+ } else {+ ConfigForm::create(config_path, agent, &workspace).and_then(|()| {+ if quickstart.scope == IdentityScope::Private {+ return Ok(());+ }+ let mut form = ConfigForm::load(config_path)?;+ form.set_scope(quickstart.scope);+ form.save()+ })+ };+ match saved {+ Ok(()) => {+ return Ok(true);+ }+ Err(error) => quickstart.status = Some((format!("{error}"), true)),+ }+ }+ }+ }+}++fn config_is_working(config: &Config) -> bool {+ config+ .credentials+ .as_ref()+ .is_some_and(crate::config::HarnessCredentials::is_valid)+}++async fn run_loop(+ terminal: &mut ratatui::DefaultTerminal,+ app: &mut App,+ input: &mut tokio::sync::mpsc::UnboundedReceiver<TermEvent>,+ pair_on_start: bool,+) -> rootcause::Result<()> {+ let mut tick = tokio::time::interval(TICK);+ // Paired already? Start serving before the first frame.+ if app.paired() {+ app.restart_daemon().await;+ }+ app.refresh().await;+ if pair_on_start {+ app.start_pairing().await;+ apply_pending_browser(app);+ }++ loop {+ terminal+ .draw(|frame| ui::render(frame, app))+ .context("failed to draw the terminal UI")?;++ tokio::select! {+ event = input.recv() => {+ match event {+ Some(TermEvent::Key(key)) => app.on_key(key).await,+ Some(_) => {}+ None => return Ok(()),+ }+ apply_pending_browser(app);+ }+ _ = tick.tick() => {+ app.spinner = app.spinner.wrapping_add(1);+ app.poll_pairing().await;+ if matches!(app.mode, Mode::Normal) {+ app.maybe_refresh().await;+ }+ }+ }++ if app.quit {+ app.stop_daemon().await;+ return Ok(());+ }+ }+}++fn apply_pending_browser(app: &mut App) {+ if let Some((message, is_error)) = open_pending_browser(&mut app.pending_browser) {+ if is_error {+ app.fail(message);+ } else {+ app.ok(message);+ }+ }+}diff --git a/crates/coding_agent_worker/src/tui/runner/test.rs b/crates/coding_agent_worker/src/tui/runner/test.rsnew file mode 100644index 0000000000..cf9f49ca01--- /dev/null+++ b/crates/coding_agent_worker/src/tui/runner/test.rs@@ -0,0 +1,21 @@+use harness_id::HarnessId;++use super::*;+use crate::config::{HarnessCredentials, HarnessScope};++#[test]+fn working_state_requires_valid_embedded_credentials() {+ let mut config: Config =+ toml::from_str(include_str!("../../../config.example.toml")).expect("example config");+ assert!(!config_is_working(&config));++ config.credentials = Some(HarnessCredentials {+ harness_id: HarnessId::TEST_A,+ token: "invalid".to_owned(),+ scope: HarnessScope::User,+ });+ assert!(!config_is_working(&config));++ config.credentials.as_mut().unwrap().token = "mhns_secret".to_owned();+ assert!(config_is_working(&config));+}diff --git a/crates/coding_agent_worker/src/tui/ui.rs b/crates/coding_agent_worker/src/tui/ui.rsindex b43cc68f1f..0d817f4767 100644--- a/crates/coding_agent_worker/src/tui/ui.rs+++ b/crates/coding_agent_worker/src/tui/ui.rs@@ -1,27 +1,21 @@//! Rendering for the macrod control panel. Pure: reads [`App`], draws frames.-use chrono::{DateTime, Utc};-use harnesses::domain::models::HarnessOwner;+mod layout;+mod modals;+mod pages;+mod quickstart;+mod shell;+mod theme;+use ratatui::Frame;-use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};-use ratatui::style::{Color, Modifier, Style, Stylize as _};-use ratatui::text::{Line, Span};-use ratatui::widgets::{- Block, BorderType, Borders, Cell, Clear, List, ListItem, Padding, Paragraph, Row, Table, Tabs,- Wrap,-};+use ratatui::layout::{Constraint, Direction, Layout};-use super::config_form::FIELDS;-use super::{App, Mode, Tab};+use super::app::{App, Mode};-const ACCENT: Color = Color::Cyan;-const OK: Color = Color::Green;-const WARN: Color = Color::Yellow;-const ERR: Color = Color::Red;-const DIM: Color = Color::DarkGray;-const SPINNER: [&str; 8] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧"];+pub(crate) use quickstart::render_quickstart;pub(crate) fn render(frame: &mut Frame, app: &App) {+ theme::render_background(frame);let [header, tabs, body, footer] = Layout::default().direction(Direction::Vertical).constraints([@@ -32,504 +26,18 @@ pub(crate) fn render(frame: &mut Frame, app: &App) {]).areas(frame.area());- render_header(frame, app, header);- render_tabs(frame, app, tabs);- match app.tab {- Tab::Overview => render_overview(frame, app, body),- Tab::Sessions => render_sessions(frame, app, body),- Tab::Config => render_config(frame, app, body),- Tab::Logs => render_logs(frame, app, body),- }- render_footer(frame, app, footer);+ shell::render_header(frame, app, header);+ shell::render_tabs(frame, app, tabs);+ pages::render(frame, app, body);+ shell::render_footer(frame, app, footer);match &app.mode {- Mode::ConfirmDelete => render_confirm_delete(frame, app),- Mode::Pairing { created, .. } => render_pairing(frame, app, created),- Mode::Normal | Mode::EditField { .. } => {}- }-}--fn render_header(frame: &mut Frame, app: &App, area: Rect) {- let (dot, dot_style, state) = match &app.snapshot.harness {- Some(harness) if harness.connected => ("●", Style::new().fg(OK), "connected"),- Some(_) => ("●", Style::new().fg(WARN), "paired, runtime not dialed in"),- None if app.paired() => ("○", Style::new().fg(WARN), "paired, unreachable"),- None => ("○", Style::new().fg(DIM), "not paired"),- };- let name = app- .snapshot- .harness- .as_ref()- .map(|harness| harness.name.clone())- .or_else(|| app.config.identity.name.clone())- .unwrap_or_else(|| "macrod".to_owned());-- let serving: Vec<Span> = if app.serving() {- vec![Span::styled(" ⏵ serving SSE", Style::new().fg(OK))]- } else if app.paired() {- vec![Span::styled(" ⏸ daemon stopped", Style::new().fg(ERR))]- } else {- Vec::new()- };- let mut spans = vec![- Span::styled(" macrod ", Style::new().fg(Color::Black).bg(ACCENT).bold()),- Span::raw(" "),- Span::styled(name, Style::new().bold()),- Span::raw(" "),- Span::styled(dot, dot_style),- Span::raw(" "),- Span::styled(state, Style::new().fg(DIM)),- ];- spans.extend(serving);- spans.push(Span::styled(- format!(" pid {}", app.pid),- Style::new().fg(DIM),- ));- let title = Line::from(spans);- let block = Block::default()- .borders(Borders::ALL)- .border_type(BorderType::Rounded)- .border_style(Style::new().fg(DIM));- frame.render_widget(Paragraph::new(title).block(block), area);-}--fn render_tabs(frame: &mut Frame, app: &App, area: Rect) {- let titles = Tab::ALL- .iter()- .enumerate()- .map(|(index, tab)| Line::from(format!(" {} {} ", index + 1, tab.title())));- let selected = Tab::ALL.iter().position(|tab| *tab == app.tab).unwrap_or(0);- let tabs = Tabs::new(titles)- .select(selected)- .style(Style::new().fg(DIM))- .highlight_style(Style::new().fg(ACCENT).add_modifier(Modifier::BOLD))- .divider("│");- frame.render_widget(tabs, area);-}--fn render_overview(frame: &mut Frame, app: &App, area: Rect) {- let [left, right] = Layout::default()- .direction(Direction::Horizontal)- .constraints([Constraint::Percentage(55), Constraint::Percentage(45)])- .areas(area);-- let mut lines: Vec<Line> = Vec::new();- match &app.snapshot.harness {- Some(harness) => {- let scope = match &harness.owner {- HarnessOwner::User { .. } => Span::styled("private", Style::new().fg(WARN)),- HarnessOwner::Team { .. } => Span::styled("team", Style::new().fg(ACCENT)),- };- lines.push(field(- "Name",- Span::styled(&harness.name, Style::new().bold()),- ));- lines.push(field("Scope", scope));- lines.push(field(- "Id",- Span::styled(harness.id.to_string(), Style::new().fg(DIM)),- ));- lines.push(field(- "Last connected",- Span::raw(- harness- .last_connected_at- .map(ago)- .unwrap_or_else(|| "never".to_owned()),- ),- ));- lines.push(field("Registered by", Span::raw(&harness.created_by)));- if app.serving() {- lines.push(field(- "Harness proc",- match &app.harness_process {- Some((pid, name)) => Span::raw(format!("{name} · pid {pid}")),- None => Span::styled(- "not spawned - starts on the first trigger",- Style::new().fg(DIM).italic(),- ),- },- ));- }- lines.push(Line::raw(""));- lines.push(Line::styled(- if app.serving() {- "Serving from this window; the dot turns green once a session dials in."- } else {- "The daemon is not running; check the Logs tab for why."- },- Style::new().fg(DIM),- ));- }- None if app.paired() => {- lines.push(Line::styled(- "Credentials on disk, but the server does not know this harness.",- Style::new().fg(WARN),- ));- lines.push(Line::raw("It was likely removed. Press p to pair again."));- }- None => {- lines.push(Line::styled(- "This daemon is not paired yet.",- Style::new().bold(),- ));- lines.push(Line::raw(""));- lines.push(Line::from(vec![- Span::raw("Press "),- Span::styled("p", Style::new().fg(ACCENT).bold()),- Span::raw(" to pair it with "),- Span::styled(&app.config.macro_api.web_url, Style::new().fg(DIM)),- ]));- }- }- frame.render_widget(- Paragraph::new(lines)- .wrap(Wrap { trim: false })- .block(card("Harness")),- left,- );-- let agents: Vec<ListItem> = if app.snapshot.agents.is_empty() {- vec![ListItem::new(Line::styled(- if app.paired() {- "No agents bound yet - create one in Settings → Agents."- } else {- "Agents appear here once paired."- },- Style::new().fg(DIM),- ))]- } else {- app.snapshot- .agents- .iter()- .map(|agent| {- ListItem::new(Line::from(vec![- Span::styled(format!("@{}", agent.handle), Style::new().fg(ACCENT).bold()),- Span::raw(" "),- Span::raw(agent.name.clone()),- ]))- })- .collect()- };- frame.render_widget(- List::new(agents).block(card(format!(- "Bound agents ({})",- app.snapshot.agents.len()- ))),- right,- );-}--fn render_sessions(frame: &mut Frame, app: &App, area: Rect) {- if app.snapshot.sessions.is_empty() {- let message = if app.paired() {- "No sessions yet - @mention a bound agent in a channel."- } else {- "Sessions appear here once paired."- };- frame.render_widget(- Paragraph::new(Line::styled(message, Style::new().fg(DIM))).block(card("Sessions")),- area,- );- return;- }-- let header = Row::new(["Agent", "Session", "Status", "Model", "Owner", "Updated"])- .style(Style::new().fg(DIM).add_modifier(Modifier::BOLD));- let rows = app.snapshot.sessions.iter().map(|session| {- Row::new(vec![- Cell::from(Span::styled(- format!("@{}", session.bot_handle),- Style::new().fg(ACCENT),- )),- Cell::from(session.name.clone()),- Cell::from(Span::styled(- session.status.clone(),- status_style(&session.status),- )),- Cell::from(session.model.clone()),- Cell::from(Span::styled(session.owner_id.clone(), Style::new().fg(DIM))),- Cell::from(ago(session.modified_at)),- ])- });- let table = Table::new(- rows,- [- Constraint::Length(14),- Constraint::Min(18),- Constraint::Length(14),- Constraint::Length(12),- Constraint::Min(16),- Constraint::Length(10),- ],- )- .header(header)- .column_spacing(2)- .block(card(format!("Sessions ({})", app.snapshot.sessions.len())));- frame.render_widget(table, area);-}--fn render_config(frame: &mut Frame, app: &App, area: Rect) {- let editing = match &app.mode {- Mode::EditField { index, buffer } => Some((*index, buffer.as_str())),- _ => None,- };-- let items: Vec<ListItem> = FIELDS- .iter()- .enumerate()- .map(|(index, definition)| {- let selected = index == app.selected_field;- let marker = if selected { "▸ " } else { " " };- let label_style = if selected {- Style::new().fg(ACCENT).bold()- } else {- Style::new()- };- let value: Span = match editing {- Some((edit_index, buffer)) if edit_index == index => Span::styled(- format!("{buffer}▏"),- Style::new().fg(Color::Black).bg(ACCENT),- ),- _ => {- let shown = app.form.display(definition);- if shown.is_empty() {- Span::styled("(unset)", Style::new().fg(DIM).italic())- } else {- Span::raw(shown)- }- }- };- ListItem::new(Line::from(vec![- Span::styled(format!("{marker}{:<22}", definition.label), label_style),- value,- ]))- })- .collect();-- frame.render_widget(- List::new(items).block(card(format!(- "macro.toml · {}",- app.config_path.display()- ))),- area,- );-}--fn render_logs(frame: &mut Frame, app: &App, area: Rect) {- let capacity = area.height.saturating_sub(2) as usize;- let lines: Vec<Line> = app- .logs- .tail(capacity.max(1))- .into_iter()- .map(|line| {- let style = if line.contains("ERROR") {- Style::new().fg(ERR)- } else if line.contains("WARN") {- Style::new().fg(WARN)- } else {- Style::new().fg(DIM)- };- Line::styled(line, style)- })- .collect();- let body: Vec<Line> = if lines.is_empty() {- vec![Line::styled(- "Nothing logged yet - triggers and dials show up here.",- Style::new().fg(DIM),- )]- } else {- lines- };- frame.render_widget(Paragraph::new(body).block(card("Daemon logs")), area);-}--fn render_footer(frame: &mut Frame, app: &App, area: Rect) {- let line = if let Some((message, is_error)) = &app.status {- Line::styled(- format!(" {message}"),- Style::new().fg(if *is_error { ERR } else { OK }),- )- } else {- let hints: &[(&str, &str)] = match (&app.mode, app.tab) {- (Mode::EditField { .. }, _) => &[("enter", "save"), ("esc", "cancel")],- (Mode::ConfirmDelete, _) => &[("y", "remove"), ("esc", "keep")],- (Mode::Pairing { .. }, _) => {- &[("o", "open link"), ("c", "copy code"), ("esc", "abandon")]- }- (_, Tab::Config) => &[- ("↑↓", "select"),- ("enter", "edit/toggle"),- ("tab", "next tab"),- ("q", "quit"),- ],- _ => &[- ("p", "pair"),- ("d", "remove harness"),- ("r", "refresh"),- ("tab", "next tab"),- ("q", "quit"),- ],- };- let mut spans = Vec::new();- for (key, action) in hints {- spans.push(Span::styled(- format!(" {key} "),- Style::new().fg(Color::Black).bg(DIM),- ));- spans.push(Span::styled(format!(" {action} "), Style::new().fg(DIM)));+ Mode::ConfirmDelete => modals::render_confirm_delete(frame, app),+ Mode::Pairing { created, .. } => modals::render_pairing(frame, app, created),+ Mode::AgentPicker { selected } => {+ modals::render_agent_picker(frame, &app.agents, *selected)}- Line::from(spans)- };- frame.render_widget(Paragraph::new(line), area);-}--fn render_confirm_delete(frame: &mut Frame, app: &App) {- let area = centered(52, 8, frame.area());- frame.render_widget(Clear, area);- let name = app- .snapshot- .harness- .as_ref()- .map(|harness| harness.name.as_str())- .unwrap_or("this harness");- let text = vec![- Line::raw(""),- Line::from(vec![- Span::raw("Remove "),- Span::styled(name, Style::new().bold()),- Span::raw("?"),- ]),- Line::styled(- "Agents bound to it stop running until it is re-paired.",- Style::new().fg(DIM),- ),- Line::raw(""),- Line::from(vec![- Span::styled(" y ", Style::new().fg(Color::Black).bg(ERR)),- Span::raw(" remove "),- Span::styled(" esc ", Style::new().fg(Color::Black).bg(DIM)),- Span::raw(" keep"),- ]),- ];- frame.render_widget(- Paragraph::new(text)- .alignment(Alignment::Center)- .block(modal("Remove harness", ERR)),- area,- );-}--fn render_pairing(- frame: &mut Frame,- app: &App,- created: &harnesses::domain::models::CreatedPairing,-) {- let url = app.config.macro_api.pairing_approval_url(&created.code);- let width = (url.len() as u16 + 6).clamp(56, frame.area().width.saturating_sub(4));- let area = centered(width, 12, frame.area());- frame.render_widget(Clear, area);- let minutes = (created.expires_at - Utc::now()).num_minutes().max(0);- let spinner = SPINNER[app.spinner % SPINNER.len()];-- // The code and the URL are rendered as plain contiguous runs on their own- // lines, left-aligned: that keeps them selectable for copy-paste and lets- // terminals linkify the URL for cmd/ctrl+click.- let text = vec![- Line::raw(""),- Line::from(vec![- Span::styled(" code ", Style::new().fg(DIM)),- Span::styled(- created.code.clone(),- Style::new().fg(ACCENT).add_modifier(Modifier::BOLD),- ),- Span::styled(" (c to copy)", Style::new().fg(DIM)),- ]),- Line::from(vec![- Span::styled(" link ", Style::new().fg(DIM)),- Span::styled(url, Style::new().underlined()),- ]),- Line::raw(""),- Line::styled(- " The browser opened to the approval page with the code",- Style::new().fg(DIM),- ),- Line::styled(- " pre-filled - confirm it matches, then approve.",- Style::new().fg(DIM),- ),- Line::raw(""),- Line::from(vec![- Span::raw(" "),- Span::styled(spinner, Style::new().fg(ACCENT)),- Span::styled(- format!(" waiting for approval · expires in {minutes} min"),- Style::new().fg(DIM),- ),- ]),- ];- frame.render_widget(- Paragraph::new(text)- .alignment(Alignment::Left)- .block(modal("Pair this daemon", ACCENT)),- area,- );-}--fn card(title: impl Into<String>) -> Block<'static> {- Block::default()- .title(format!(" {} ", title.into()))- .title_style(Style::new().fg(ACCENT).bold())- .borders(Borders::ALL)- .border_type(BorderType::Rounded)- .border_style(Style::new().fg(DIM))- .padding(Padding::horizontal(1))-}--fn modal(title: &str, color: Color) -> Block<'static> {- Block::default()- .title(format!(" {title} "))- .title_style(Style::new().fg(color).bold())- .borders(Borders::ALL)- .border_type(BorderType::Double)- .border_style(Style::new().fg(color))-}--fn field<'a>(label: &str, value: Span<'a>) -> Line<'a> {- Line::from(vec![- Span::styled(format!("{label:<16}"), Style::new().fg(DIM)),- value,- ])-}--fn status_style(status: &str) -> Style {- // The session status vocabulary: `event` is a live session, `no_messages`- // one that never heard anything, `disconnected` one whose runtime is gone.- match status {- "event" => Style::new().fg(OK),- "no_messages" => Style::new().fg(DIM),- "disconnected" => Style::new().fg(ERR),- _ => Style::new().fg(WARN),- }-}--fn ago(when: DateTime<Utc>) -> String {- let seconds = (Utc::now() - when).num_seconds().max(0);- match seconds {- 0..=59 => format!("{seconds}s ago"),- 60..=3599 => format!("{}m ago", seconds / 60),- 3600..=86_399 => format!("{}h ago", seconds / 3600),- _ => format!("{}d ago", seconds / 86_400),- }-}--fn centered(width: u16, height: u16, area: Rect) -> Rect {- let width = width.min(area.width.saturating_sub(2));- let height = height.min(area.height.saturating_sub(2));- Rect {- x: area.x + (area.width.saturating_sub(width)) / 2,- y: area.y + (area.height.saturating_sub(height)) / 2,- width,- height,+ Mode::CustomAgent { buffer } => modals::render_custom_agent(frame, buffer),+ Mode::Normal | Mode::EditSetting { .. } => {}}}diff --git a/crates/coding_agent_worker/src/tui/ui/layout.rs b/crates/coding_agent_worker/src/tui/ui/layout.rsnew file mode 100644index 0000000000..7e19221354--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/layout.rs@@ -0,0 +1,61 @@+use chrono::{DateTime, Utc};+use ratatui::Frame;+use ratatui::layout::Rect;+use ratatui::style::Style;+use ratatui::text::{Line, Span};+use ratatui::widgets::Paragraph;+use tui_input::Input;++use super::theme::{DIM, ERR, OK, WARN};++pub(super) fn render_input(frame: &mut Frame, input: &Input, area: Rect, style: Style) {+ let width = area.width.saturating_sub(1).max(1) as usize;+ let scroll = input.visual_scroll(width);+ frame.render_widget(+ Paragraph::new(input.value())+ .style(style)+ .scroll((0, scroll as u16)),+ area,+ );+ let cursor = input.visual_cursor().max(scroll) - scroll;+ frame.set_cursor_position((area.x + cursor as u16, area.y));+}++pub(super) fn field<'a>(label: &str, value: Span<'a>) -> Line<'a> {+ Line::from(vec![+ Span::styled(format!("{label:<16}"), Style::new().fg(DIM)),+ value,+ ])+}++pub(super) fn status_style(status: &str) -> Style {+ // The session status vocabulary: `event` is a live session, `no_messages`+ // one that never heard anything, `disconnected` one whose runtime is gone.+ match status {+ "event" => Style::new().fg(OK),+ "no_messages" => Style::new().fg(DIM),+ "disconnected" => Style::new().fg(ERR),+ _ => Style::new().fg(WARN),+ }+}++pub(super) fn ago(when: DateTime<Utc>) -> String {+ let seconds = (Utc::now() - when).num_seconds().max(0);+ match seconds {+ 0..=59 => format!("{seconds}s ago"),+ 60..=3599 => format!("{}m ago", seconds / 60),+ 3600..=86_399 => format!("{}h ago", seconds / 3600),+ _ => format!("{}d ago", seconds / 86_400),+ }+}++pub(super) fn centered(width: u16, height: u16, area: Rect) -> Rect {+ let width = width.min(area.width.saturating_sub(2));+ let height = height.min(area.height.saturating_sub(2));+ Rect {+ x: area.x + (area.width.saturating_sub(width)) / 2,+ y: area.y + (area.height.saturating_sub(height)) / 2,+ width,+ height,+ }+}diff --git a/crates/coding_agent_worker/src/tui/ui/modals.rs b/crates/coding_agent_worker/src/tui/ui/modals.rsnew file mode 100644index 0000000000..4147f71e2a--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/modals.rs@@ -0,0 +1,182 @@+use chrono::Utc;+use ratatui::Frame;+use ratatui::layout::{Alignment, Rect};+use ratatui::style::{Modifier, Style, Stylize as _};+use ratatui::text::{Line, Span};+use ratatui::widgets::{Clear, Paragraph};+use tui_input::Input;++use super::layout::{centered, render_input};+use super::theme::{ACCENT, DIM, ERR, SPINNER, THEME, WARN, modal};+use crate::tui::agent_catalog::DetectedAgent;+use crate::tui::app::App;++pub(super) fn render_agent_picker(frame: &mut Frame, agents: &[DetectedAgent], selected: usize) {+ let height = (agents.len() as u16 + 11).clamp(11, 20);+ let area = centered(62, height, frame.area());+ frame.render_widget(Clear, area);+ let mut lines = vec![+ Line::styled("Detected agents are ready to launch.", Style::new().fg(DIM)),+ Line::raw(""),+ ];+ if agents.is_empty() {+ lines.push(Line::styled(+ "No known agents detected on PATH.",+ Style::new().fg(WARN),+ ));+ } else {+ lines.extend(agents.iter().enumerate().map(|(index, agent)| {+ let marker = if index == selected { "▸ " } else { " " };+ let style = if index == selected {+ Style::new().fg(ACCENT).bold()+ } else {+ Style::new()+ };+ let detail = agent.note.unwrap_or("");+ Line::from(vec![+ Span::styled(format!("{marker}{:<20}", agent.name), style),+ Span::styled(detail, Style::new().fg(DIM)),+ ])+ }));+ }+ let custom_style = if selected == agents.len() {+ Style::new().fg(ACCENT).bold()+ } else {+ Style::new()+ };+ let marker = if selected == agents.len() {+ "▸ "+ } else {+ " "+ };+ lines.push(Line::styled(+ format!("{marker}Custom command..."),+ custom_style,+ ));+ lines.push(Line::raw(""));+ lines.push(Line::from(vec![+ Span::styled(" ? ", Style::new().fg(THEME.accent_text).bg(ACCENT)),+ Span::styled(" Bring your own agent guide", Style::new().fg(DIM)),+ ]));+ frame.render_widget(+ Paragraph::new(lines).block(modal("Choose an agent", ACCENT)),+ area,+ );+}++pub(super) fn render_custom_agent(frame: &mut Frame, buffer: &Input) {+ let area = centered(66, 10, frame.area());+ frame.render_widget(Clear, area);+ let block = modal("Custom ACP agent", ACCENT);+ let inner = block.inner(area);+ frame.render_widget(block, area);+ frame.render_widget(+ Paragraph::new("Command to run via ACP").style(Style::new().fg(DIM)),+ Rect { height: 1, ..inner },+ );+ let input_area = Rect {+ y: inner.y + 2,+ height: 1,+ ..inner+ };+ if buffer.value().is_empty() {+ frame.render_widget(+ Paragraph::new("hermes acp").style(Style::new().fg(DIM).italic()),+ input_area,+ );+ frame.set_cursor_position((input_area.x, input_area.y));+ } else {+ render_input(frame, buffer, input_area, Style::new().fg(ACCENT));+ }+}++pub(super) fn render_confirm_delete(frame: &mut Frame, app: &App) {+ let area = centered(52, 9, frame.area());+ frame.render_widget(Clear, area);+ let name = app+ .snapshot+ .harness+ .as_ref()+ .map(|harness| harness.name.as_str())+ .unwrap_or("this harness");+ let text = vec![+ Line::raw(""),+ Line::from(vec![+ Span::raw("Remove "),+ Span::styled(name, Style::new().bold()),+ Span::raw("?"),+ ]),+ Line::styled(+ "Agents bound to it stop running until it is re-paired.",+ Style::new().fg(DIM),+ ),+ Line::raw(""),+ Line::from(vec![+ Span::styled(" y ", Style::new().fg(THEME.background).bg(ERR)),+ Span::raw(" remove "),+ Span::styled(" esc ", Style::new().fg(THEME.background).bg(DIM)),+ Span::raw(" keep"),+ ]),+ ];+ frame.render_widget(+ Paragraph::new(text)+ .alignment(Alignment::Center)+ .block(modal("Remove harness", ERR)),+ area,+ );+}++pub(super) fn render_pairing(+ frame: &mut Frame,+ app: &App,+ created: &harnesses::domain::models::CreatedPairing,+) {+ let url = app.config.macro_api.pairing_approval_url(&created.code);+ let available_width = frame.area().width.saturating_sub(2);+ let desired_width = url.chars().count() as u16 + 12;+ let width = desired_width.min(available_width).max(1);+ let area = centered(width, 12, frame.area());+ frame.render_widget(Clear, area);+ let minutes = (created.expires_at - Utc::now()).num_minutes().max(0);+ let spinner = SPINNER[app.spinner % SPINNER.len()];++ // The code and the URL are rendered as plain contiguous runs on their own+ // lines, left-aligned: that keeps them selectable for copy-paste and lets+ // terminals linkify the URL for cmd/ctrl+click.+ let text = vec![+ Line::raw(""),+ Line::from(vec![+ Span::styled(" code ", Style::new().fg(DIM)),+ Span::styled(+ created.code.clone(),+ Style::new().fg(ACCENT).add_modifier(Modifier::BOLD),+ ),+ Span::styled(" (c to copy)", Style::new().fg(DIM)),+ ]),+ Line::from(vec![+ Span::styled(" link ", Style::new().fg(DIM)),+ Span::styled(url, Style::new().underlined()),+ ]),+ Line::raw(""),+ Line::styled(+ " Open the approval page and confirm the code matches,",+ Style::new().fg(DIM),+ ),+ Line::styled(" then pair macrod.", Style::new().fg(DIM)),+ Line::raw(""),+ Line::from(vec![+ Span::raw(" "),+ Span::styled(spinner, Style::new().fg(ACCENT)),+ Span::styled(+ format!(" Waiting for approval · Expires in {minutes} min"),+ Style::new().fg(DIM),+ ),+ ]),+ ];+ frame.render_widget(+ Paragraph::new(text)+ .alignment(Alignment::Left)+ .block(modal("Pair macrod", ACCENT)),+ area,+ );+}diff --git a/crates/coding_agent_worker/src/tui/ui/pages.rs b/crates/coding_agent_worker/src/tui/ui/pages.rsnew file mode 100644index 0000000000..488c14cd64--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/pages.rs@@ -0,0 +1,18 @@+mod config;+mod logs;+mod overview;+mod sessions;++use ratatui::Frame;+use ratatui::layout::Rect;++use crate::tui::app::{App, Tab};++pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {+ match app.tab {+ Tab::Overview => overview::render(frame, app, area),+ Tab::Sessions => sessions::render(frame, app, area),+ Tab::Config => config::render(frame, app, area),+ Tab::Logs => logs::render(frame, app, area),+ }+}diff --git a/crates/coding_agent_worker/src/tui/ui/pages/config.rs b/crates/coding_agent_worker/src/tui/ui/pages/config.rsnew file mode 100644index 0000000000..986281a0e4--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/pages/config.rs@@ -0,0 +1,69 @@+use ratatui::Frame;+use ratatui::layout::Rect;+use ratatui::style::{Style, Stylize as _};+use ratatui::widgets::Paragraph;++use super::super::layout::render_input;+use super::super::theme::{ACCENT, DIM, WARN, card, focus_marker, focus_style};+use crate::config::IdentityScope;+use crate::tui::app::{App, Mode};+use crate::tui::config_form::SETTINGS;++pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {+ let block = card(format!("macrod.toml · {}", app.config_path.display()));+ let inner = block.inner(area);+ frame.render_widget(block, area);+ for (index, setting) in SETTINGS.iter().enumerate() {+ let selected = index == app.selected_setting;+ let row = Rect {+ y: inner.y + index as u16,+ height: 1,+ ..inner+ };+ frame.render_widget(+ Paragraph::new(format!("{}{:<16}", focus_marker(selected), setting.label()))+ .style(focus_style(selected)),+ row,+ );+ let value_area = Rect {+ x: row.x + 18,+ width: row.width.saturating_sub(18),+ ..row+ };+ match &app.mode {+ Mode::EditSetting {+ index: edit_index,+ buffer,+ } if *edit_index == index => {+ render_input(frame, buffer, value_area, Style::new().fg(ACCENT));+ }+ _ => {+ let shown = app.form.display(*setting, &app.config);+ let style = if shown.is_empty() {+ Style::new().fg(DIM).italic()+ } else {+ Style::new()+ };+ frame.render_widget(+ Paragraph::new(if shown.is_empty() { "(unset)" } else { &shown }).style(style),+ value_area,+ );+ }+ }+ }+ if app.config.identity.scope == IdentityScope::Team {+ let warning = Rect {+ x: inner.x,+ y: inner.y + SETTINGS.len() as u16 + 1,+ width: inner.width,+ height: 1,+ };+ frame.render_widget(+ Paragraph::new(+ "Warning: teammates can command agents on this machine. Trust your team.",+ )+ .style(Style::new().fg(WARN)),+ warning,+ );+ }+}diff --git a/crates/coding_agent_worker/src/tui/ui/pages/logs.rs b/crates/coding_agent_worker/src/tui/ui/pages/logs.rsnew file mode 100644index 0000000000..7942f832e7--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/pages/logs.rs@@ -0,0 +1,36 @@+use ratatui::Frame;+use ratatui::layout::Rect;+use ratatui::style::Style;+use ratatui::text::Line;+use ratatui::widgets::Paragraph;++use super::super::theme::{DIM, ERR, WARN, card};+use crate::tui::app::App;++pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {+ let capacity = area.height.saturating_sub(2) as usize;+ let lines: Vec<Line> = app+ .logs+ .tail(capacity.max(1))+ .into_iter()+ .map(|line| {+ let style = if line.contains("ERROR") {+ Style::new().fg(ERR)+ } else if line.contains("WARN") {+ Style::new().fg(WARN)+ } else {+ Style::new().fg(DIM)+ };+ Line::styled(line, style)+ })+ .collect();+ let body: Vec<Line> = if lines.is_empty() {+ vec![Line::styled(+ "Nothing logged yet - triggers and dials show up here.",+ Style::new().fg(DIM),+ )]+ } else {+ lines+ };+ frame.render_widget(Paragraph::new(body).block(card("Daemon logs")), area);+}diff --git a/crates/coding_agent_worker/src/tui/ui/pages/overview.rs b/crates/coding_agent_worker/src/tui/ui/pages/overview.rsnew file mode 100644index 0000000000..9e80cfa39e--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/pages/overview.rs@@ -0,0 +1,123 @@+use harnesses::domain::models::HarnessOwner;+use ratatui::Frame;+use ratatui::layout::{Constraint, Direction, Layout, Rect};+use ratatui::style::{Style, Stylize as _};+use ratatui::text::{Line, Span};+use ratatui::widgets::{List, ListItem, Paragraph, Wrap};++use super::super::layout::{ago, field};+use super::super::theme::{ACCENT, DIM, WARN, card};+use crate::tui::app::App;++pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {+ let [left, right] = Layout::default()+ .direction(Direction::Horizontal)+ .constraints([Constraint::Percentage(55), Constraint::Percentage(45)])+ .areas(area);++ let mut lines: Vec<Line> = Vec::new();+ match &app.snapshot.harness {+ Some(harness) => {+ let scope = match &harness.owner {+ HarnessOwner::User { .. } => Span::styled("private", Style::new().fg(WARN)),+ HarnessOwner::Team { .. } => Span::styled("team", Style::new().fg(ACCENT)),+ };+ lines.push(field(+ "Name",+ Span::styled(&harness.name, Style::new().bold()),+ ));+ lines.push(field("Scope", scope));+ lines.push(field(+ "Id",+ Span::styled(harness.id.to_string(), Style::new().fg(DIM)),+ ));+ lines.push(field(+ "Last connected",+ Span::raw(+ harness+ .last_connected_at+ .map(ago)+ .unwrap_or_else(|| "never".to_owned()),+ ),+ ));+ lines.push(field("Registered by", Span::raw(&harness.created_by)));+ if app.serving() {+ lines.push(field(+ "Harness proc",+ match &app.harness_process {+ Some((pid, name)) => Span::raw(format!("{name} · pid {pid}")),+ None => Span::styled(+ "not spawned - starts on the first trigger",+ Style::new().fg(DIM).italic(),+ ),+ },+ ));+ }+ lines.push(Line::raw(""));+ lines.push(Line::styled(+ if app.serving() {+ "Serving from this window; the dot turns green once a session dials in."+ } else {+ "The daemon is not running; check the Logs tab for why."+ },+ Style::new().fg(DIM),+ ));+ }+ None if app.paired() => {+ lines.push(Line::styled(+ "Credentials on disk, but the server does not know this harness.",+ Style::new().fg(WARN),+ ));+ lines.push(Line::raw("It was likely removed. Press p to pair again."));+ }+ None => {+ lines.push(Line::styled(+ "This daemon is not paired yet.",+ Style::new().bold(),+ ));+ lines.push(Line::raw(""));+ lines.push(Line::from(vec![+ Span::raw("Press "),+ Span::styled("p", Style::new().fg(ACCENT).bold()),+ Span::raw(" to pair it with "),+ Span::styled(&app.config.macro_api.web_url, Style::new().fg(DIM)),+ ]));+ }+ }+ frame.render_widget(+ Paragraph::new(lines)+ .wrap(Wrap { trim: false })+ .block(card("Harness")),+ left,+ );++ let agents: Vec<ListItem> = if app.snapshot.agents.is_empty() {+ vec![ListItem::new(Line::styled(+ if app.paired() {+ "No agents bound yet - create one in Settings → Agents."+ } else {+ "Agents appear here once paired."+ },+ Style::new().fg(DIM),+ ))]+ } else {+ app.snapshot+ .agents+ .iter()+ .map(|agent| {+ ListItem::new(Line::from(vec![+ Span::styled(format!("@{}", agent.handle), Style::new().fg(ACCENT).bold()),+ Span::raw(" "),+ Span::raw(agent.name.clone()),+ ]))+ })+ .collect()+ };+ frame.render_widget(+ List::new(agents).block(card(format!(+ "Bound agents ({})",+ app.snapshot.agents.len()+ ))),+ right,+ );+}diff --git a/crates/coding_agent_worker/src/tui/ui/pages/sessions.rs b/crates/coding_agent_worker/src/tui/ui/pages/sessions.rsnew file mode 100644index 0000000000..d958a294c9--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/pages/sessions.rs@@ -0,0 +1,58 @@+use ratatui::Frame;+use ratatui::layout::{Constraint, Rect};+use ratatui::style::{Modifier, Style};+use ratatui::text::{Line, Span};+use ratatui::widgets::{Cell, Paragraph, Row, Table};++use super::super::layout::{ago, status_style};+use super::super::theme::{ACCENT, DIM, card};+use crate::tui::app::App;++pub(super) fn render(frame: &mut Frame, app: &App, area: Rect) {+ if app.snapshot.sessions.is_empty() {+ let message = if app.paired() {+ "No sessions yet - @mention a bound agent in a channel."+ } else {+ "Sessions appear here once paired."+ };+ frame.render_widget(+ Paragraph::new(Line::styled(message, Style::new().fg(DIM))).block(card("Sessions")),+ area,+ );+ return;+ }++ let header = Row::new(["Agent", "Session", "Status", "Model", "Owner", "Updated"])+ .style(Style::new().fg(DIM).add_modifier(Modifier::BOLD));+ let rows = app.snapshot.sessions.iter().map(|session| {+ Row::new(vec![+ Cell::from(Span::styled(+ format!("@{}", session.bot_handle),+ Style::new().fg(ACCENT),+ )),+ Cell::from(session.name.clone()),+ Cell::from(Span::styled(+ session.status.clone(),+ status_style(&session.status),+ )),+ Cell::from(session.model.clone()),+ Cell::from(Span::styled(session.owner_id.clone(), Style::new().fg(DIM))),+ Cell::from(ago(session.modified_at)),+ ])+ });+ let table = Table::new(+ rows,+ [+ Constraint::Length(14),+ Constraint::Min(18),+ Constraint::Length(14),+ Constraint::Length(12),+ Constraint::Min(16),+ Constraint::Length(10),+ ],+ )+ .header(header)+ .column_spacing(2)+ .block(card(format!("Sessions ({})", app.snapshot.sessions.len())));+ frame.render_widget(table, area);+}diff --git a/crates/coding_agent_worker/src/tui/ui/quickstart.rs b/crates/coding_agent_worker/src/tui/ui/quickstart.rsnew file mode 100644index 0000000000..47691343de--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/quickstart.rs@@ -0,0 +1,272 @@+use ratatui::Frame;+use ratatui::layout::{Alignment, Constraint, Layout, Rect};+use ratatui::style::{Style, Stylize as _};+use ratatui::text::{Line, Span};+use ratatui::widgets::{Block, BorderType, Borders, Clear, Padding, Paragraph};++use super::layout::{centered, render_input};+use super::theme::{ACCENT, DIM, ERR, OK, THEME, WARN, focus_marker, focus_style, modal};+use crate::config::IdentityScope;+use crate::tui::agent_catalog::AgentKind;+use crate::tui::quickstart::{Quickstart, QuickstartFocus, QuickstartMode};++pub(crate) fn render_quickstart(+ frame: &mut Frame,+ setup: &Quickstart,+ config_path: &std::path::Path,+) {+ super::theme::render_background(frame);+ let discovered_height = (setup.agents.len() as u16 + 2).clamp(3, 9);+ let area = centered(+ 84,+ frame.area().height.saturating_sub(2).min(27),+ frame.area(),+ );+ frame.render_widget(Clear, area);+ let block = modal("Quickstart", ACCENT).padding(Padding::new(2, 2, 1, 1));+ let inner = block.inner(area);+ frame.render_widget(block, area);+ let [+ intro,+ discovered_area,+ custom_area,+ _form_spacer,+ workspace_area,+ scope_area,+ _button_spacer,+ submit_area,+ warning_area,+ _details_spacer,+ details_area,+ ] = Layout::vertical([+ Constraint::Length(3),+ Constraint::Length(discovered_height),+ Constraint::Length(3),+ Constraint::Length(1),+ Constraint::Length(1),+ Constraint::Length(1),+ Constraint::Min(1),+ Constraint::Length(3),+ Constraint::Length(1),+ Constraint::Length(1),+ Constraint::Length(1),+ ])+ .areas(inner);++ let mut intro_lines = vec![+ Line::from(vec![+ Span::styled(+ " MACRO ",+ Style::new().fg(THEME.accent_text).bg(ACCENT).bold(),+ ),+ Span::raw(" "),+ Span::styled("Welcome to macrod.", Style::new().bold()),+ ]),+ Line::styled("Let's get your harness connected.", Style::new().fg(DIM)),+ ];+ if let Some((message, is_error)) = &setup.status {+ intro_lines.push(Line::styled(+ message,+ Style::new().fg(if *is_error { ERR } else { OK }),+ ));+ }+ frame.render_widget(Paragraph::new(intro_lines), intro);+ render_discovered_agents(frame, setup, discovered_area);+ render_quickstart_custom(frame, setup, custom_area);++ let workspace_focused = setup.focus == QuickstartFocus::Workspace;+ frame.render_widget(+ Paragraph::new(Line::from(vec![Span::styled(+ format!("{}{:<14}", focus_marker(workspace_focused), "Workspace"),+ Style::new().fg(DIM),+ )])),+ workspace_area,+ );+ let workspace_value_area = Rect {+ x: workspace_area.x + 16,+ width: workspace_area.width.saturating_sub(16),+ ..workspace_area+ };+ match &setup.mode {+ QuickstartMode::EditWorkspace { buffer } => {+ render_input(frame, buffer, workspace_value_area, Style::new().fg(ACCENT))+ }+ _ => frame.render_widget(+ Paragraph::new(setup.workspace.as_str()).style(focus_style(workspace_focused)),+ workspace_value_area,+ ),+ }++ let scope_focused = setup.focus == QuickstartFocus::Scope;+ let scope = match setup.scope {+ IdentityScope::Private => "Private",+ IdentityScope::Team => "Team",+ };+ frame.render_widget(+ Paragraph::new(Line::from(vec![+ Span::styled(+ format!("{}{:<14}", focus_marker(scope_focused), "Access"),+ Style::new().fg(DIM),+ ),+ Span::styled(scope, focus_style(scope_focused)),+ ])),+ scope_area,+ );+ if setup.scope == IdentityScope::Team {+ frame.render_widget(+ Paragraph::new(+ "Warning: teammates can command agents on this machine. Trust your team.",+ )+ .style(Style::new().fg(WARN))+ .alignment(Alignment::Center),+ warning_area,+ );+ }++ let submit_focused = setup.focus == QuickstartFocus::Submit;+ let button_style = if submit_focused {+ Style::new().fg(THEME.accent_text).bg(ACCENT).bold()+ } else {+ Style::new().fg(ACCENT).bold()+ };+ let button_area = Rect {+ x: submit_area.x + submit_area.width.saturating_sub(22) / 2,+ width: 22.min(submit_area.width),+ ..submit_area+ };+ frame.render_widget(+ Paragraph::new("Create and pair")+ .style(button_style)+ .alignment(Alignment::Center)+ .block(+ Block::default()+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(ACCENT)),+ ),+ button_area,+ );+ frame.render_widget(+ Paragraph::new(config_path.display().to_string())+ .style(Style::new().fg(DIM))+ .alignment(Alignment::Right),+ details_area,+ );+ let hint = match setup.mode {+ QuickstartMode::EditWorkspace { .. } => " Enter save Esc cancel ",+ QuickstartMode::CustomAgent { .. } => " Enter save Esc back ",+ QuickstartMode::Normal if setup.focus == QuickstartFocus::Agent(setup.agents.len()) => {+ " ↑↓/jk select Enter change ? guide q quit "+ }+ QuickstartMode::Normal => " ↑↓/jk select Enter choose/change q quit ",+ };+ let footer = Rect {+ x: area.x,+ y: area.bottom(),+ width: area.width,+ height: 1,+ };+ frame.render_widget(+ Paragraph::new(Line::styled(hint, Style::new().fg(DIM))).alignment(Alignment::Center),+ footer,+ );+}++fn render_discovered_agents(frame: &mut Frame, setup: &Quickstart, area: Rect) {+ let block = Block::default()+ .title(" Discovered ")+ .title_style(Style::new().fg(DIM))+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(THEME.border))+ .padding(Padding::horizontal(1));+ let inner = block.inner(area);+ frame.render_widget(block, area);++ if setup.agents.is_empty() {+ frame.render_widget(+ Paragraph::new("No supported agent harnesses found on PATH")+ .style(Style::new().fg(WARN)),+ Rect { height: 1, ..inner },+ );+ return;+ }++ for (index, agent) in setup.agents.iter().enumerate() {+ let focused = setup.focus == QuickstartFocus::Agent(index);+ let chosen = setup+ .selected_agent+ .as_ref()+ .is_some_and(|selected| selected.kind == agent.kind);+ let row = Rect {+ y: inner.y + index as u16,+ height: 1,+ ..inner+ };+ frame.render_widget(+ Paragraph::new(Line::from(vec![+ Span::styled(focus_marker(focused), Style::new().fg(ACCENT)),+ Span::styled(if chosen { "● " } else { "○ " }, Style::new().fg(ACCENT)),+ Span::styled(format!("{:<20}", agent.name), focus_style(focused)),+ Span::styled(agent.note.unwrap_or(""), Style::new().fg(DIM)),+ ])),+ row,+ );+ }+}++fn render_quickstart_custom(frame: &mut Frame, setup: &Quickstart, area: Rect) {+ let block = Block::default()+ .title(" Custom ")+ .title_style(Style::new().fg(DIM))+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(THEME.border))+ .padding(Padding::horizontal(1));+ let inner = block.inner(area);+ frame.render_widget(block, area);++ let index = setup.agents.len();+ let focused = setup.focus == QuickstartFocus::Agent(index);+ let chosen = setup+ .selected_agent+ .as_ref()+ .is_some_and(|agent| agent.kind == AgentKind::Custom);+ let row = Rect { height: 1, ..inner };+ frame.render_widget(+ Paragraph::new(Line::from(vec![+ Span::styled(focus_marker(focused), Style::new().fg(ACCENT)),+ Span::styled(if chosen { "● " } else { "○ " }, Style::new().fg(ACCENT)),+ ])),+ row,+ );+ let value_area = Rect {+ x: row.x + 4,+ width: row.width.saturating_sub(4),+ ..row+ };+ match &setup.mode {+ QuickstartMode::CustomAgent { buffer } if buffer.value().is_empty() => {+ frame.render_widget(+ Paragraph::new("hermes acp").style(Style::new().fg(DIM).italic()),+ value_area,+ );+ frame.set_cursor_position((value_area.x, value_area.y));+ }+ QuickstartMode::CustomAgent { buffer } => {+ render_input(frame, buffer, value_area, Style::new().fg(ACCENT))+ }+ _ => {+ let value = setup+ .selected_agent+ .as_ref()+ .filter(|agent| agent.kind == AgentKind::Custom)+ .map(|agent| format!("Custom: {}", agent.launch.command))+ .unwrap_or_else(|| "Custom command...".to_owned());+ frame.render_widget(+ Paragraph::new(value).style(focus_style(focused)),+ value_area,+ );+ }+ }+}diff --git a/crates/coding_agent_worker/src/tui/ui/shell.rs b/crates/coding_agent_worker/src/tui/ui/shell.rsnew file mode 100644index 0000000000..b78ce64a14--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/shell.rs@@ -0,0 +1,117 @@+use ratatui::Frame;+use ratatui::layout::Rect;+use ratatui::style::{Modifier, Style, Stylize as _};+use ratatui::text::{Line, Span};+use ratatui::widgets::{Block, BorderType, Borders, Paragraph, Tabs};++use super::theme::{ACCENT, DIM, ERR, OK, THEME, WARN};+use crate::tui::app::{App, Mode, Tab};++pub(super) fn render_header(frame: &mut Frame, app: &App, area: Rect) {+ let (dot, dot_style, state) = match &app.snapshot.harness {+ Some(harness) if harness.connected => ("●", Style::new().fg(OK), "connected"),+ Some(_) => ("●", Style::new().fg(WARN), "paired, runtime not dialed in"),+ None if app.paired() => ("○", Style::new().fg(WARN), "paired, unreachable"),+ None => ("○", Style::new().fg(DIM), "not paired"),+ };+ let name = app+ .snapshot+ .harness+ .as_ref()+ .map(|harness| harness.name.clone())+ .or_else(|| app.config.identity.name.clone())+ .unwrap_or_else(|| "macrod".to_owned());++ let serving: Vec<Span> = if app.serving() {+ vec![Span::styled(" ⏵ serving SSE", Style::new().fg(OK))]+ } else if app.paired() {+ vec![Span::styled(" ⏸ daemon stopped", Style::new().fg(ERR))]+ } else {+ Vec::new()+ };+ let mut spans = vec![+ Span::styled(+ " macrod ",+ Style::new().fg(THEME.accent_text).bg(ACCENT).bold(),+ ),+ Span::raw(" "),+ Span::styled(name, Style::new().bold()),+ Span::raw(" "),+ Span::styled(dot, dot_style),+ Span::raw(" "),+ Span::styled(state, Style::new().fg(DIM)),+ ];+ spans.extend(serving);+ spans.push(Span::styled(+ format!(" pid {}", app.pid),+ Style::new().fg(DIM),+ ));+ let title = Line::from(spans);+ let block = Block::default()+ .style(Style::new().fg(THEME.text).bg(THEME.surface))+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(THEME.border));+ frame.render_widget(Paragraph::new(title).block(block), area);+}++pub(super) fn render_tabs(frame: &mut Frame, app: &App, area: Rect) {+ let titles = Tab::ALL+ .iter()+ .enumerate()+ .map(|(index, tab)| Line::from(format!(" {} {} ", index + 1, tab.title())));+ let selected = Tab::ALL.iter().position(|tab| *tab == app.tab).unwrap_or(0);+ let tabs = Tabs::new(titles)+ .select(selected)+ .style(Style::new().fg(DIM))+ .highlight_style(Style::new().fg(ACCENT).add_modifier(Modifier::BOLD))+ .divider("│");+ frame.render_widget(tabs, area);+}++pub(super) fn render_footer(frame: &mut Frame, app: &App, area: Rect) {+ let line = if let Some((message, is_error)) = &app.status {+ Line::styled(+ format!(" {message}"),+ Style::new().fg(if *is_error { ERR } else { OK }),+ )+ } else {+ let hints: &[(&str, &str)] = match (&app.mode, app.tab) {+ (Mode::EditSetting { .. }, _) => &[("enter", "save"), ("esc", "cancel")],+ (Mode::AgentPicker { .. }, _) => &[+ ("↑↓/jk", "select"),+ ("enter", "choose"),+ ("?", "guide"),+ ("esc", "cancel"),+ ],+ (Mode::CustomAgent { .. }, _) => &[("enter", "save"), ("esc", "back")],+ (Mode::ConfirmDelete, _) => &[("y", "remove"), ("esc", "keep")],+ (Mode::Pairing { .. }, _) => {+ &[("o", "open link"), ("c", "copy code"), ("esc", "abandon")]+ }+ (_, Tab::Config) => &[+ ("↑↓", "select"),+ ("enter", "edit/toggle"),+ ("←→/hl", "tabs"),+ ("q", "quit"),+ ],+ _ => &[+ ("p", "pair"),+ ("d", "remove harness"),+ ("r", "refresh"),+ ("←→/hl", "tabs"),+ ("q", "quit"),+ ],+ };+ let mut spans = Vec::new();+ for (key, action) in hints {+ spans.push(Span::styled(+ format!(" {key} "),+ Style::new().fg(THEME.background).bg(DIM),+ ));+ spans.push(Span::styled(format!(" {action} "), Style::new().fg(DIM)));+ }+ Line::from(spans)+ };+ frame.render_widget(Paragraph::new(line), area);+}diff --git a/crates/coding_agent_worker/src/tui/ui/theme.rs b/crates/coding_agent_worker/src/tui/ui/theme.rsnew file mode 100644index 0000000000..511bce8099--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/theme.rs@@ -0,0 +1,79 @@+use ratatui::Frame;+use ratatui::style::{Color, Style, Stylize as _};+use ratatui::widgets::{Block, BorderType, Borders, Padding};++pub(super) struct Theme {+ pub(super) background: Color,+ pub(super) surface: Color,+ pub(super) text: Color,+ pub(super) muted: Color,+ pub(super) border: Color,+ pub(super) accent: Color,+ pub(super) accent_text: Color,+ pub(super) success: Color,+ pub(super) warning: Color,+ pub(super) error: Color,+}++// Macro orange is the product's `--color-orange` token (#f97316). Keeping the+// complete palette here makes a future brand or contrast adjustment one edit.+pub(super) const THEME: Theme = Theme {+ background: Color::Rgb(21, 17, 14),+ surface: Color::Rgb(33, 26, 20),+ text: Color::Rgb(255, 248, 240),+ muted: Color::Rgb(199, 185, 171),+ border: Color::Rgb(128, 106, 85),+ accent: Color::Rgb(249, 115, 22),+ accent_text: Color::Rgb(24, 13, 5),+ success: Color::Rgb(74, 222, 128),+ warning: Color::Rgb(255, 178, 36),+ error: Color::Rgb(255, 107, 107),+};++pub(super) const ACCENT: Color = THEME.accent;+pub(super) const OK: Color = THEME.success;+pub(super) const WARN: Color = THEME.warning;+pub(super) const ERR: Color = THEME.error;+pub(super) const DIM: Color = THEME.muted;+pub(super) const SPINNER: [&str; 8] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧"];++pub(super) fn card(title: impl Into<String>) -> Block<'static> {+ Block::default()+ .style(Style::new().fg(THEME.text).bg(THEME.surface))+ .title(format!(" {} ", title.into()))+ .title_style(Style::new().fg(ACCENT).bold())+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(THEME.border))+ .padding(Padding::horizontal(1))+}++pub(super) fn modal(title: &str, color: Color) -> Block<'static> {+ Block::default()+ .style(Style::new().fg(THEME.text).bg(THEME.surface))+ .padding(Padding::new(1, 1, 1, 1))+ .title(format!(" {title} "))+ .title_style(Style::new().fg(color).bold())+ .borders(Borders::ALL)+ .border_type(BorderType::Double)+ .border_style(Style::new().fg(color))+}++pub(super) fn render_background(frame: &mut Frame) {+ frame.render_widget(+ Block::default().style(Style::new().fg(THEME.text).bg(THEME.background)),+ frame.area(),+ );+}++pub(super) fn focus_marker(focused: bool) -> &'static str {+ if focused { "▸ " } else { " " }+}++pub(super) fn focus_style(focused: bool) -> Style {+ if focused {+ Style::new().fg(ACCENT).bold()+ } else {+ Style::new()+ }+}diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex 73dc7a64f3..d2da72630c 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -302,6 +302,7 @@ once_cell = { version = "1", default-features = false, features = ["critical-secrand-93f6ce9d446188ac = { package = "rand", version = "0.10" }rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }signal-hook-mio = { version = "0.2", default-features = false, features = ["support-v0_8", "support-v1_0"] }+smallvec = { version = "1", default-features = false, features = ["union"] }spin = { version = "0.9" }tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "ring"] }tokio-util = { version = "0.7", default-features = false, features = ["io-util"] }@@ -323,6 +324,7 @@ once_cell = { version = "1", default-features = false, features = ["critical-secrand-93f6ce9d446188ac = { package = "rand", version = "0.10" }rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }signal-hook-mio = { version = "0.2", default-features = false, features = ["support-v0_8", "support-v1_0"] }+smallvec = { version = "1", default-features = false, features = ["union"] }spin = { version = "0.9" }tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "ring"] }tokio-util = { version = "0.7", default-features = false, features = ["io-util"] }@@ -340,6 +342,8 @@ hyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", dehyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }mio = { version = "1", features = ["net", "os-ext"] }+objc2 = { version = "0.6" }+objc2-foundation = { version = "0.3" }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }@@ -361,6 +365,8 @@ hyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", dehyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }mio = { version = "1", features = ["net", "os-ext"] }+objc2 = { version = "0.6" }+objc2-foundation = { version = "0.3" }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }