From b2bedda17e3b063b0c9f57d0b0068370bd8d7d3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Mon, 9 Nov 2026 22:05:15 +0100 Subject: [PATCH 1/3] feat: act on another machine's services from the CLI and MCP PR 5 of remote machines (docs/remote-machines.md, "CLI" and "MCP"). The daemon already viewed and controlled other machines for the app; a terminal and an agent can now do the same. - `--machine` on `services status`, `logs`, `dev`, `stop` and `restart`. It resolves an exact id, then an exact name ignoring case, among the active machines; this machine's own id or name acts locally. A service must be unique on the target or come with `--project`. - `dev --machine` refuses every option but `--project`, `--env` and `--profile` before asking the daemon anything. - A control holds a watch open, since the daemon sends one only over an open session, and its first snapshot gives what the control expects. What that snapshot already refuses is not sent. - Human output on a terminal, JSON otherwise. A refusal says what the app says for its code and exits 2; an outcome that never came back prints the fresh state and exits 3; a run that failed exits 1. - `remote_inventory` and `remote_output_read` errors now carry their code on the management socket, so the CLI and agents see it. - MCP: `list_machines`, and `machine` on the six service tools; with it, `cwd` is ignored and `service_start` takes only service, project, env and profile. Refusals of controls and lost outcomes tell the agent what to do next. --- ...remote-machines-from-the-cli-and-agents.md | 10 + docs/README.md | 18 + docs/remote-machines.md | 5 +- src/application/ports/daemon_connection.rs | 4 + src/cli/machines.rs | 41 +- src/cli/mcp/instructions.md | 6 + src/cli/mcp/mod.rs | 64 +- src/cli/mcp/tools.rs | 213 +++++- src/cli/mod.rs | 1 + src/cli/remote/control.rs | 607 ++++++++++++++++++ src/cli/remote/inventory.rs | 504 +++++++++++++++ src/cli/remote/logs.rs | 357 ++++++++++ src/cli/remote/mod.rs | 419 ++++++++++++ src/daemon/mgmt_socket.rs | 38 +- src/daemon/remote/tests.rs | 1 + src/daemon/remote/tests/cli.rs | 302 +++++++++ src/desktop/remote.rs | 3 +- src/infrastructure/mgmt_client.rs | 45 ++ src/main.rs | 226 ++++++- tests/remote_cli.rs | 50 ++ 20 files changed, 2841 insertions(+), 73 deletions(-) create mode 100644 changes/remote-machines-from-the-cli-and-agents.md create mode 100644 src/cli/remote/control.rs create mode 100644 src/cli/remote/inventory.rs create mode 100644 src/cli/remote/logs.rs create mode 100644 src/cli/remote/mod.rs create mode 100644 src/daemon/remote/tests/cli.rs create mode 100644 tests/remote_cli.rs diff --git a/changes/remote-machines-from-the-cli-and-agents.md b/changes/remote-machines-from-the-cli-and-agents.md new file mode 100644 index 00000000..d6d16145 --- /dev/null +++ b/changes/remote-machines-from-the-cli-and-agents.md @@ -0,0 +1,10 @@ +--- +type: new +link: docs/README.md#remote-machines +--- + +## Check and control another machine's services from a terminal or an agent + +Add `--machine ` to `services status`, `logs`, `dev`, `stop` and `restart` to act on +another of your machines, as the app's machine switcher does. Coding agents get the same +through `list_machines` and a `machine` argument on the service tools. diff --git a/docs/README.md b/docs/README.md index 065ea38d..8e54ad1e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -515,6 +515,23 @@ there, the card gives the one command to run on it instead, such as A service started from an app older than 1.5 shows "Relaunch to share". Relaunch it, after a confirmation, and its output and controls work from then on. +**From a terminal or an agent.** Add `--machine ` to act on another machine's +services. Without `--env`, it uses the primary checkout there, and a service name that +exists in two projects needs `--project`. + +```bash +localify services status --machine teo-desktop +localify logs web --machine teo-desktop -f +localify dev web --machine teo-desktop --profile staging +localify restart web --machine teo-desktop +``` + +`dev --machine` takes only `--project`, `--env` and `--profile`: the other machine decides +whether the service starts in its app or in the background. A refusal prints why and +exits with code 2; a control whose outcome never came back prints the service's current +state and exits with code 3. Agents get the same through the `machine` argument of the +service tools, and `list_machines`. + How it works, for contributors: [remote-machines.md](remote-machines.md). ## Access from other devices @@ -600,6 +617,7 @@ for debug output. `localify --help` lists the rest. | `localify billing` | Manage the subscription | | `localify public-url create\|list\|remove\|protect\|unprotect\|claim` | Manage public URLs | | `localify machines [pair\|unpair\|remove\|settings]` | Pair machines and choose what they may do here | +| `localify services status\|logs\|dev\|stop\|restart ... --machine ` | The same on another machine | | **Other** | | | `localify completions ` | Generate shell completions | diff --git a/docs/remote-machines.md b/docs/remote-machines.md index ace106ad..90c80245 100644 --- a/docs/remote-machines.md +++ b/docs/remote-machines.md @@ -813,7 +813,8 @@ localify restart --machine [--project ] [--env ] - **Resolving a service:** there is no folder to read on another machine, so a service name must be unique on the target, or come with `--project`, and `--env` names a non-primary checkout. An ambiguous name lists the matches. - **What `--machine` refuses:** with `dev`, every option but `--project`, `--env` and `--profile`: no command after `--`, no `--detach`, `--in-app`, `--env-file`, `--confirm-profile` or `--domain`. The target decides where the service runs. - **Launch flags:** `--launch-id`, `--launch-expires`, `--remote-launch`, `--expect-rev`, `--request` and `--replace-legacy` are hidden flags for dispatchers, documented here and not in `--help`. -- **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2. +- **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2. `unknown` is progress, "Outcome unknown. Checking B…", never where a control stops. A control the snapshot already refuses (its `controls`, or a legacy run, which the app relaunches after a confirmation) is refused the same way without being sent. A run that failed exits with code 1. With JSON, progress goes to stderr, so stdout holds one document: `{outcome, code, message, …}`. `logs` prints plain lines, as without `--machine`, and its next cursor on stderr. +- **This machine:** its own id or name acts locally, `dev` as `--in-app` does, since the options it takes are the ones `--in-app` takes. - `pair` and `remove` need a terminal: an agent cannot pair or remove machines. ## MCP @@ -821,7 +822,7 @@ localify restart --machine [--project ] [--env ] - `list_machines`: the roster with states, read-only. - An optional `machine` argument on `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` and `service_restart`, and on no other tool. With it, a tool ignores `cwd`. - With `machine`, `service_start` takes only `service`, `project`, `env` and `profile`. `background`, `env_files`, `confirm_profile`, `command` and `domain` make it fail with an error that says the target decides how its services start. It never creates a project. -- `service_logs` with `machine` returns a cursor `:`. +- `service_logs` with `machine` returns a cursor `:`. `list_services` and `service_status` with `machine` both give the target's snapshot (`services status --machine`). - Pairing, unpairing, settings and removal have no tool. Like signing in (ADR 0018), they stay a person's decision. - An error from a target reaches the agent with its code and message, so `control_disabled` tells it to ask the user to allow controls on that machine, and an outcome it could not learn (`lost`) tells it to check `service_status` before trying again. diff --git a/src/application/ports/daemon_connection.rs b/src/application/ports/daemon_connection.rs index 0350f5ae..60ba0a3c 100644 --- a/src/application/ports/daemon_connection.rs +++ b/src/application/ports/daemon_connection.rs @@ -25,6 +25,10 @@ pub enum DaemonConnectionError { ConnectionFailed(#[source] anyhow::Error), #[error("Protocol error: {0}")] ProtocolError(String), + /// Another machine, or the way to it, refused: the contract's code and + /// its message (docs/remote-machines.md, "Errors"). + #[error("{message}")] + Remote { code: String, message: String }, } /// Port for communicating with a running daemon process. diff --git a/src/cli/machines.rs b/src/cli/machines.rs index 4854a349..2a60e947 100644 --- a/src/cli/machines.rs +++ b/src/cli/machines.rs @@ -18,6 +18,7 @@ use crate::config::LocalifyPaths; use crate::infrastructure::cloud::api::CloudClient; use crate::infrastructure::cloud::credentials::CredentialsStore; use crate::infrastructure::cloud::http::{CloudHttp, block_on}; +use crate::infrastructure::mgmt_client::MgmtSocketClient; #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum Switch { @@ -34,36 +35,34 @@ impl Switch { /// One machine of `remote_machines`. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(rename_all = "camelCase")] -struct Machine { - id: String, - name: String, +pub(super) struct Machine { + pub(super) id: String, + pub(super) name: String, #[serde(rename = "self")] - is_self: bool, + pub(super) is_self: bool, paired: bool, - state: String, + pub(super) state: String, #[serde(default)] version: Option, #[serde(default)] sharing: Option, } -fn daemon_error(error: DaemonConnectionError) -> anyhow::Error { +pub(super) fn daemon_error(error: DaemonConnectionError) -> anyhow::Error { match error { DaemonConnectionError::NotRunning => anyhow!( "Remote machines go through the {} daemon, which is not running. Start it with: {} start", BRANDING.app_name, BRANDING.cli_command() ), - DaemonConnectionError::ProtocolError(message) => anyhow!(message), + DaemonConnectionError::ProtocolError(message) + | DaemonConnectionError::Remote { message, .. } => anyhow!(message), other => anyhow!("Could not reach the daemon: {other}"), } } -fn machines(ctx: &AppContext, probe: bool) -> Result> { - let list = ctx - .mgmt_client - .remote_machines(probe) - .map_err(daemon_error)?; +pub(super) fn machines(client: &MgmtSocketClient, probe: bool) -> Result> { + let list = client.remote_machines(probe).map_err(daemon_error)?; serde_json::from_value(list).context("The daemon sent a machine list this version cannot read") } @@ -168,21 +167,21 @@ fn state_label(state: &str) -> &str { /// A machine the person named. #[derive(Debug, Clone, PartialEq, Eq)] -struct Candidate { - id: String, - name: String, - is_self: bool, +pub(super) struct Candidate { + pub(super) id: String, + pub(super) name: String, + pub(super) is_self: bool, } /// An exact machine id, else an exact name ignoring case. A name that /// matches two machines lists both. -fn resolve(candidates: &[Candidate], query: &str) -> Result { +pub(super) fn resolve(candidates: &[Candidate], query: &str) -> Result { if let Some(found) = candidates.iter().find(|machine| machine.id == query) { return Ok(found.clone()); } let named: Vec<&Candidate> = candidates .iter() - .filter(|machine| machine.name.eq_ignore_ascii_case(query)) + .filter(|machine| machine.name.to_lowercase() == query.to_lowercase()) .collect(); match named.as_slice() { [one] => Ok((*one).clone()), @@ -212,7 +211,7 @@ fn resolve(candidates: &[Candidate], query: &str) -> Result { } } -fn candidates(machines: &[Machine]) -> Vec { +pub(super) fn candidates(machines: &[Machine]) -> Vec { machines .iter() .map(|machine| Candidate { @@ -246,7 +245,7 @@ fn typed_yes(prompt: &str) -> Result { /// `localify machines pair `, as the viewer. pub fn pair(query: &str, ctx: &AppContext) -> Result<()> { require_person("Pair")?; - let target = resolve(&candidates(&machines(ctx, false)?), query)?; + let target = resolve(&candidates(&machines(&ctx.mgmt_client, false)?), query)?; if target.is_self { bail!("{} is this machine: pair it from another one.", target.name); } @@ -346,7 +345,7 @@ pub fn accept(ctx: &AppContext) -> Result<()> { /// `localify machines unpair `: deletes the pin, and tells the /// machine when a session is open. pub fn unpair(query: &str, json_flag: bool, ctx: &AppContext) -> Result<()> { - let machines = machines(ctx, false)?; + let machines = machines(&ctx.mgmt_client, false)?; let paired: Vec = machines .into_iter() .filter(|machine| machine.paired) diff --git a/src/cli/mcp/instructions.md b/src/cli/mcp/instructions.md index cc04463a..62997f0c 100644 --- a/src/cli/mcp/instructions.md +++ b/src/cli/mcp/instructions.md @@ -33,6 +33,12 @@ Public URLs (Localify Cloud), only when the user wants to reach an app from anot - Serving public URLs takes Localify Cloud Pro: $7.99 a month or $79 a year, after a 7-day free trial that asks for a card. Paying is the user's call too: when a tool answers that a plan is needed, tell them the price and the trial and ask them to run `localify subscribe`. When a tool answers that a limit is reached and names a command that raises it, suggest the user run that command. Never start a checkout or pass on a checkout link. `whoami` shows the plan (`plan.entitled`, dates, limits and usage) and why this machine's tunnel is blocked, if it is. - `public_url_list` shows which machine serves each URL and its `state`: `suspended` when the plan does not cover it, `taken_down` when it was removed for abuse. `public_url_claim` moves one to this machine; `public_url_remove` takes it offline. When every serving slot is taken, removing the URLs another machine serves, or claiming them here, frees its slot. +Other machines (Localify Cloud), only when the user asks about a service on another of their machines: +- `list_machines` lists the account's machines. Pass a name or id as `machine` to `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` or `service_restart` to act on that machine. `cwd` is ignored there, and `env` names one of its worktrees. +- The other machine decides how a service starts: with `machine`, `service_start` takes only `service`, `project`, `env` and `profile`, and never creates a project. +- A refusal carries the other machine's code. On `control_disabled` or `background_disabled`, ask the user to allow remote controls on that machine. When a control ends `lost`, its outcome is unknown: call `service_status` before you try again. +- Pairing, unpairing and a machine's settings are the user's to change. + When something does not work: - Call `status` first. A domain that does not resolve: the daemon may be stopped (`daemon` start) or Localify not installed (`install_localify`). A page saying the target is unavailable: the app is not listening; read its logs. - Do not edit /etc/hosts, run another proxy, bypass certificate errors, edit Localify's config file, or run Localify with sudo. diff --git a/src/cli/mcp/mod.rs b/src/cli/mcp/mod.rs index a65432e2..81dbcaed 100644 --- a/src/cli/mcp/mod.rs +++ b/src/cli/mcp/mod.rs @@ -135,6 +135,9 @@ fn call_tool(params: &Value, runner: &CliRunner) -> Result { /// can be raised, the command that raises it stays in the text, for the /// agent to suggest. fn for_an_agent(text: String) -> String { + if let Some(hint) = remote_hint(&text) { + return format!("{text}\n\n{hint}"); + } if text.contains(RAISE_LIMIT) { return format!( "{text}\n\nRaising the limit is a purchase, so it is the user's call: suggest they run that command themselves, then try again. Do not start a checkout or pass on a checkout link." @@ -149,10 +152,33 @@ fn for_an_agent(text: String) -> String { ) } +/// What an agent does when another machine refused, or did not say how a +/// control ended (docs/remote-machines.md, "MCP"). The CLI prints these as +/// JSON when its output is not a terminal. +fn remote_hint(text: &str) -> Option { + let cli = BRANDING.cli_command(); + if text.contains(r#""code": "control_disabled""#) + || text.contains(r#""code": "background_disabled""#) + { + return Some(format!( + "That machine decides who may control its services. Ask the user to allow remote controls on it: Settings → Remote access in Localify there, or `{cli} machines settings --control on` run there (with `--background-starts on` for starts while its app is closed)." + )); + } + if text.contains(r#""outcome": "lost""#) { + return Some( + "Call service_status with the same machine to see what happened before you try again." + .to_string(), + ); + } + None +} + fn prepare(tool: &Tool, args: &ToolArgs) -> Result<(Vec, Option)> { let argv = (tool.build)(args)?; + // A tool acting on another machine has no folder of this one to read. + let here = args.string("machine")?.is_none(); let cwd = match args.string("cwd")? { - Some(cwd) if tool.uses_cwd => Some(existing_dir(&cwd)?), + Some(cwd) if tool.uses_cwd && here => Some(existing_dir(&cwd)?), _ => None, }; Ok((argv, cwd)) @@ -354,6 +380,42 @@ mod tests { ); } + #[test] + fn a_tool_on_another_machine_ignores_cwd() { + let tool = TOOLS + .iter() + .find(|tool| tool.name == "service_logs") + .unwrap(); + let here = ToolArgs::new(&json!({ "service": "web", "cwd": "relative/path" })).unwrap(); + let there = ToolArgs::new( + &json!({ "service": "web", "cwd": "relative/path", "machine": "teo-mini" }), + ) + .unwrap(); + + assert!(prepare(tool, &here).is_err()); + let (argv, cwd) = prepare(tool, &there).unwrap(); + assert_eq!(cwd, None); + assert_eq!(argv, ["logs", "web", "--machine=teo-mini"]); + } + + #[test] + fn an_error_from_another_machine_reaches_the_agent_with_its_code_and_what_to_do() { + let refused = "{\n \"outcome\": \"refused\",\n \"code\": \"control_disabled\",\n \"message\": \"teo-mini doesn't allow remote controls.\"\n}"; + + let text = for_an_agent(refused.to_string()); + + assert!(text.starts_with(refused)); + assert!( + text.contains("Ask the user to allow remote controls"), + "{text}" + ); + + let lost = "{\n \"outcome\": \"lost\",\n \"code\": \"timeout\"\n}"; + assert!( + for_an_agent(lost.to_string()).contains("Call service_status with the same machine") + ); + } + #[test] fn an_unknown_method_is_an_error() { let response = handle_line(&request("resources/list", json!({})), &runner()).unwrap(); diff --git a/src/cli/mcp/tools.rs b/src/cli/mcp/tools.rs index 36694629..eb8b9c88 100644 --- a/src/cli/mcp/tools.rs +++ b/src/cli/mcp/tools.rs @@ -90,18 +90,65 @@ const CONFIRM_PROFILE: Param = param( "Repeats the profile name to start a danger = true profile. Pass it only when the user asked for that profile in this task.", ); const LINES: Param = param("lines", Kind::Integer, "Number of lines to return."); +const MACHINE: Param = param( + "machine", + Kind::String, + "Another machine of the account, by name or id as list_machines shows it: acts on its services instead of this machine's. cwd is ignored, and without env, the tool uses the primary checkout there.", +); const PUBLIC_URL: Param = required( "url", Kind::String, "The public URL, its slug or its id, as public_url_list shows them.", ); -/// `stop` or `restart` of one service. +/// `stop` or `restart` of one service, here or on another machine. fn service_command(verb: &str, args: &ToolArgs) -> Result> { Args::new(&[verb]) .positional(args.required("service")?)? .option("--project", args.string("project")?) .option("--env", args.string("env")?) + .option("--machine", args.string("machine")?) + .done() +} + +/// `list_services` and `service_status` on another machine: its snapshot, +/// every service with its states. +fn machine_status(machine: String) -> Result> { + Args::new(&["services", "status"]) + .option("--machine", Some(machine)) + .flag("--json", true) + .done() +} + +/// `service_start` with `machine`: a start that the other machine runs as it +/// decides, so only the service and its profile can be named. +fn start_on_machine(machine: String, args: &ToolArgs) -> Result> { + let refused: Vec<&str> = [ + ("background", args.optional_flag("background")?.is_some()), + ("env_files", !args.list("env_files")?.is_empty()), + ("confirm_profile", args.string("confirm_profile")?.is_some()), + ("command", !args.list("command")?.is_empty()), + ("domain", args.string("domain")?.is_some()), + ("replace", args.optional_flag("replace")?.is_some()), + ] + .into_iter() + .filter_map(|(name, given)| given.then_some(name)) + .collect(); + if !refused.is_empty() { + bail!( + "With machine, service_start takes only service, project, env and profile: {machine} decides how its services start. Remove {}.", + refused.join(", ") + ); + } + let Some(service) = args.string("service")? else { + bail!("With machine, service_start needs service: there is no folder to read it from."); + }; + Args::new(&["dev"]) + .positional(service)? + .option("--machine", Some(machine)) + .option("--project", args.string("project")?) + .option("--env", args.string("env")?) + .option("--profile", args.string("profile")?) .done() } @@ -134,22 +181,37 @@ pub const TOOLS: &[Tool] = &[ build: |_| Ok(argv(&["list"])), }, Tool { - name: "list_services", - description: "Lists the services of every project (JSON): ID, project, URL, domains, folder, dev command and local target.", + name: "list_machines", + description: "Lists the other machines of this Localify Cloud account (JSON): name, id, connection state, whether they are paired and share their services. Pass a name or id as machine to list_services, service_status, service_logs, service_start, service_stop or service_restart to act there.", params: &[], uses_cwd: false, read_only: true, destructive: false, - build: |_| Ok(argv(&["services", "list", "--json"])), + build: |_| Ok(argv(&["machines", "--json"])), + }, + Tool { + name: "list_services", + description: "Lists the services of every project (JSON): ID, project, URL, domains, folder, dev command and local target. With machine, the services of that machine and their states.", + params: &[MACHINE], + uses_cwd: false, + read_only: true, + destructive: false, + build: |args| match args.string("machine")? { + Some(machine) => machine_status(machine), + None => Ok(argv(&["services", "list", "--json"])), + }, }, Tool { name: "service_status", - description: "Shows every service Localify started, in every environment (JSON): running or not, PID, URL, port, origin (app, background, terminal), start time, and exit code once it stopped.", - params: &[], + description: "Shows every service Localify started, in every environment (JSON): running or not, PID, URL, port, origin (app, background, terminal), start time, and exit code once it stopped. With machine, every service of that machine: process, port, output and public URL, and which controls it allows.", + params: &[MACHINE], uses_cwd: false, read_only: true, destructive: false, - build: |_| Ok(argv(&["services", "status", "--json"])), + build: |args| match args.string("machine")? { + Some(machine) => machine_status(machine), + None => Ok(argv(&["services", "status", "--json"])), + }, }, Tool { name: "get_service_url", @@ -201,11 +263,19 @@ pub const TOOLS: &[Tool] = &[ Kind::Boolean, "Stop the running instance first, then start it again. Without it, a service that already runs is left running and nothing starts.", ), + param( + "machine", + Kind::String, + "Start it on another machine of the account, by name or id as list_machines shows it. That machine decides where it runs, so only service, project, env and profile may be passed with it.", + ), ], uses_cwd: true, read_only: false, destructive: false, build: |args| { + if let Some(machine) = args.string("machine")? { + return start_on_machine(machine, args); + } let mut command = Args::new(&["dev"]); if let Some(service) = args.string("service")? { command = command.positional(service)?; @@ -227,8 +297,8 @@ pub const TOOLS: &[Tool] = &[ }, Tool { name: "service_stop", - description: "Stops a service Localify started (in the app, the background or a terminal), with everything it launched.", - params: &[SERVICE, PROJECT, ENV], + description: "Stops a service Localify started (in the app, the background or a terminal), with everything it launched. With machine, on that machine, when it allows remote controls.", + params: &[SERVICE, PROJECT, ENV, MACHINE], uses_cwd: true, read_only: false, destructive: false, @@ -236,8 +306,8 @@ pub const TOOLS: &[Tool] = &[ }, Tool { name: "service_restart", - description: "Stops a service and starts it again where it ran, on the same launch profile, and returns once it listens.", - params: &[SERVICE, PROJECT, ENV], + description: "Stops a service and starts it again where it ran, on the same launch profile, and returns once it listens. With machine, on that machine, when it allows remote controls.", + params: &[SERVICE, PROJECT, ENV, MACHINE], uses_cwd: true, read_only: false, destructive: false, @@ -256,6 +326,7 @@ pub const TOOLS: &[Tool] = &[ Kind::String, "Cursor from the previous service_logs call, as it returned it, to read only newer lines.", ), + MACHINE, ], uses_cwd: true, read_only: true, @@ -266,6 +337,7 @@ pub const TOOLS: &[Tool] = &[ .option("--project", args.string("project")?) .option("--env", args.string("env")?) .option("--lines", args.integer("lines")?) + .option("--machine", args.string("machine")?) .option( "--cursor", args.string("cursor").or_else(|_| args.integer("cursor")).map_err(|_| { @@ -1293,6 +1365,125 @@ mod tests { assert!(build("public_url_claim", json!({ "url": "--all" })).is_err()); } + #[test] + fn only_the_service_tools_take_a_machine() { + let mut with_machine: Vec<&str> = TOOLS + .iter() + .filter(|tool| tool.params.iter().any(|param| param.name == "machine")) + .map(|tool| tool.name) + .collect(); + with_machine.sort_unstable(); + + assert_eq!( + with_machine, + [ + "list_services", + "service_logs", + "service_restart", + "service_start", + "service_status", + "service_stop", + ] + ); + let machines = TOOLS + .iter() + .find(|tool| tool.name == "list_machines") + .unwrap(); + assert!(machines.read_only && !machines.uses_cwd); + assert_eq!( + build("list_machines", json!({})).unwrap(), + ["machines", "--json"] + ); + } + + #[test] + fn each_service_tool_acts_on_another_machine_with_machine() { + let status = ["services", "status", "--machine=teo-mini", "--json"]; + assert_eq!( + build("list_services", json!({ "machine": "teo-mini" })).unwrap(), + status + ); + assert_eq!( + build("service_status", json!({ "machine": "teo-mini" })).unwrap(), + status + ); + assert_eq!( + build( + "service_logs", + json!({ "service": "web", "machine": "teo-mini", "cursor": "R:4" }) + ) + .unwrap(), + ["logs", "web", "--machine=teo-mini", "--cursor=R:4"] + ); + assert_eq!( + build( + "service_stop", + json!({ "service": "web", "machine": "m2", "env": "feat" }) + ) + .unwrap(), + ["stop", "web", "--env=feat", "--machine=m2"] + ); + assert_eq!( + build( + "service_restart", + json!({ "service": "web", "project": "app", "machine": "m2" }) + ) + .unwrap(), + ["restart", "web", "--project=app", "--machine=m2"] + ); + assert_eq!( + build( + "service_start", + json!({ "service": "web", "machine": "m2", "env": "feat", "profile": "staging" }) + ) + .unwrap(), + [ + "dev", + "web", + "--machine=m2", + "--env=feat", + "--profile=staging" + ] + ); + // A machine is a value, never a flag. + assert_eq!( + build( + "service_stop", + json!({ "service": "web", "machine": "--all" }) + ) + .unwrap(), + ["stop", "web", "--machine=--all"] + ); + } + + #[test] + fn service_start_on_another_machine_takes_only_service_project_env_and_profile() { + for (name, value) in [ + ("background", json!(true)), + ("background", json!(false)), + ("env_files", json!([".env.local"])), + ("confirm_profile", json!("prod")), + ("command", json!(["pnpm", "dev"])), + ("domain", json!("web.localify")), + ("replace", json!(true)), + ] { + let mut arguments = json!({ "service": "web", "machine": "teo-mini" }); + arguments[name] = value; + + let error = build("service_start", arguments).unwrap_err().to_string(); + + assert!( + error.contains("teo-mini decides how its services start"), + "{error}" + ); + assert!(error.ends_with(&format!("Remove {name}.")), "{error}"); + } + let error = build("service_start", json!({ "machine": "teo-mini" })) + .unwrap_err() + .to_string(); + assert!(error.contains("needs service"), "{error}"); + } + #[test] fn wrong_types_are_refused() { assert!(build("service_logs", json!({ "service": "web", "lines": "ten" })).is_err()); diff --git a/src/cli/mod.rs b/src/cli/mod.rs index cfcc705d..43280dcc 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -21,6 +21,7 @@ pub mod project_env; pub mod public_url; pub mod register; pub mod reload; +pub mod remote; pub mod remove_project; pub mod restart; pub mod route; diff --git a/src/cli/remote/control.rs b/src/cli/remote/control.rs new file mode 100644 index 00000000..f16476fe --- /dev/null +++ b/src/cli/remote/control.rs @@ -0,0 +1,607 @@ +//! `dev`, `stop` and `restart` with `--machine`: a control that the target +//! runs through whoever owns the service there (docs/remote-machines.md, +//! "Controls"). The daemon sends a control only over a session already +//! open, so a watch holds one open, and its first snapshot is the state the +//! control expects. A control prints its progress, then its result; an +//! outcome that could not be learned prints the fresh state and exits with +//! [`LOST`]. + +use std::io::{ErrorKind, Write}; +use std::time::Duration; + +use anyhow::{Result, anyhow}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use super::inventory::{Item, ServiceQuery, Snapshot, fetch, find, write_item}; +use super::{Console, LOST, Peer, Refusal, remote_error, viewer_message}; +use crate::application::ports::DaemonConnectionError; +use crate::infrastructure::mgmt_client::{MgmtSocketClient, MgmtStream}; +use crate::infrastructure::remote::wire::{ + AppPresence, ControlAction, ControlOutcome, ControlPhase, +}; + +/// How long the first snapshot may take: a lease, a session and every page. +const SNAPSHOT_WAIT: Duration = Duration::from_secs(60); +/// The exit code of a control that ran and failed. +const FAILED: i32 = 1; + +/// Starts, stops or restarts `query`'s service on `peer`. `profile` is for a +/// start only; a restart keeps the run's profile. +pub fn control( + client: &MgmtSocketClient, + peer: &Peer, + action: ControlAction, + query: &ServiceQuery<'_>, + profile: Option<&str>, + console: &mut Console, +) -> Result { + let mut watch = client + .remote_stream(&json!({ "cmd": "remote_watch", "machineId": peer.id })) + .map_err(|error| remote_error(error, peer))?; + let snapshot = first_snapshot(&mut watch, peer)?; + let items = snapshot.shared_items(peer)?; + let (item, _) = find(&items, query, &peer.name)?; + allowed(item, action, &peer.name)?; + let asked = Asked { + peer, + action, + service: &item.service.name, + ids: json!({ + "projectId": item.project.id, + "environment": item.environment.slug, + "serviceId": item.service.id, + }), + app_running: snapshot.machine.app == AppPresence::Running, + }; + let request = json!({ + "cmd": "remote_control", + "machineId": peer.id, + "action": action, + "service": asked.ids, + "profile": profile.filter(|_| action == ControlAction::Start), + "expect": { + "runId": item.run.as_ref().and_then(|run| run.run_id.clone()), + "configRev": item.service.config_rev, + }, + }); + let mut stream = client + .remote_stream(&request) + .map_err(|error| remote_error(error, peer))?; + let events = std::iter::from_fn(|| stream.next_answer().transpose()); + let ended = follow(events, &asked, console)?; + drop(watch); + report(ended, &asked, console, || fresh(client, peer, query)) +} + +/// What a control was asked for, to say what happens to it. +struct Asked<'a> { + peer: &'a Peer, + action: ControlAction, + service: &'a str, + ids: Value, + app_running: bool, +} + +/// The watch's first snapshot, or why the target can't be watched. +fn first_snapshot(watch: &mut MgmtStream, peer: &Peer) -> Result { + let not_responding = || anyhow!(Refusal::from_target("not_responding", "", &peer.name)); + watch.set_timeout(Some(SNAPSHOT_WAIT))?; + loop { + let event = match watch.next_answer() { + Ok(Some(event)) => event, + Ok(None) => return Err(not_responding()), + Err(DaemonConnectionError::ConnectionFailed(error)) if timed_out(&error) => { + return Err(not_responding()); + } + Err(error) => return Err(remote_error(error, peer)), + }; + match event["event"].as_str() { + Some("snapshot") => return Snapshot::parse(event), + Some("lost") => { + return Err(anyhow!(Refusal::from_target( + event["code"].as_str().unwrap_or_default(), + event["message"].as_str().unwrap_or_default(), + &peer.name, + ))); + } + _ => continue, + } + } +} + +fn timed_out(error: &anyhow::Error) -> bool { + error + .downcast_ref::() + .is_some_and(|error| matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut)) +} + +/// Refuses before sending what the snapshot already refuses: the same +/// checks the target makes, with the code it would give. +fn allowed(item: &Item, action: ControlAction, machine: &str) -> Result<()> { + let service = &item.service.name; + let legacy = item.run.as_ref().is_some_and(|run| run.legacy); + let code = match item.controls.get(action.as_str()) { + // A legacy run is relaunched from the app, after a confirmation. + Some(state) if state.allowed && legacy => "legacy_run", + Some(state) if !state.allowed => state.code.as_deref().unwrap_or("conflict"), + _ => return Ok(()), + }; + let refusal = match (code, action) { + ("conflict", ControlAction::Start) => Refusal::new( + "conflict", + format!("'{service}' already runs on {machine}."), + ), + ("conflict", _) => Refusal::new( + "conflict", + format!("'{service}' isn't running on {machine}."), + ), + (code, _) => Refusal::from_target(code, "", machine), + }; + Err(anyhow!(refusal)) +} + +/// One event of `remote_control`. +#[derive(Debug, Deserialize)] +#[serde( + tag = "event", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +enum Event { + Sent, + Progress { + phase: ControlPhase, + }, + Result { + outcome: ControlOutcome, + code: Option, + message: String, + run_id: Option, + }, + Unknown, + Lost { + code: String, + }, +} + +/// How a control ended, for this CLI. +#[derive(Debug, PartialEq, Eq)] +enum Ended { + Result { + outcome: ControlOutcome, + code: Option, + message: String, + run_id: Option, + }, + Lost { + code: String, + }, +} + +/// Prints the progress of the control until its result or `lost`. +fn follow( + events: impl Iterator>, + asked: &Asked<'_>, + console: &mut Console, +) -> Result { + // A stop says the same thing when sent and when dispatched. + let mut said = String::new(); + for event in events { + let event = event.map_err(|error| remote_error(error, asked.peer))?; + let event: Event = serde_json::from_value(event).map_err(|error| { + anyhow!("The daemon sent a control event this version cannot read: {error}") + })?; + let line = match event { + Event::Sent => progress(asked, None), + Event::Progress { phase } => progress(asked, Some(phase)), + Event::Unknown => format!("Outcome unknown. Checking {}…", asked.peer.name), + Event::Result { + outcome, + code, + message, + run_id, + } => { + return Ok(Ended::Result { + outcome, + code, + message, + run_id, + }); + } + Event::Lost { code } => return Ok(Ended::Lost { code }), + }; + if line != said { + console.note(&line)?; + said = line; + } + } + // The daemon closed the stream without an outcome. + Ok(Ended::Lost { + code: "closed".to_string(), + }) +} + +/// What a control is doing, as the app's chip says it. +fn progress(asked: &Asked<'_>, phase: Option) -> String { + let machine = &asked.peer.name; + match (asked.action, phase) { + (ControlAction::Stop, _) => format!("Stopping '{}' on {machine}…", asked.service), + (_, Some(ControlPhase::Started)) => format!("Started on {machine}. Waiting for its port…"), + (_, Some(ControlPhase::Dispatched)) if asked.app_running => { + format!("Starting in the app on {machine}…") + } + (_, Some(ControlPhase::Dispatched)) => format!("Starting in the background on {machine}…"), + (ControlAction::Restart, None) => format!("Restarting '{}' on {machine}…", asked.service), + (ControlAction::Start, None) => format!("Starting '{}' on {machine}…", asked.service), + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Outcome<'a> { + outcome: &'a str, + action: ControlAction, + machine: &'a Peer, + service: &'a Value, + message: String, + #[serde(skip_serializing_if = "Option::is_none")] + code: Option, + #[serde(skip_serializing_if = "Option::is_none")] + run_id: Option, + /// For `lost`: the service as the target shows it now. + #[serde(skip_serializing_if = "Option::is_none")] + status: Option, +} + +/// Prints the result and gives the exit code: 0 once done or started, 1 +/// when the run failed, a refusal for [`super::REFUSED`], [`LOST`] when the +/// outcome could not be learned. `fresh` reads the service's state again. +fn report( + ended: Ended, + asked: &Asked<'_>, + console: &mut Console, + fresh: impl FnOnce() -> Result<(Item, Value)>, +) -> Result { + let machine = &asked.peer.name; + let (outcome, code, message, run_id) = match ended { + Ended::Lost { code } => return lost(&code, asked, console, fresh), + Ended::Result { + outcome: ControlOutcome::Unknown, + .. + } => return lost("unknown", asked, console, fresh), + Ended::Result { + outcome: outcome @ (ControlOutcome::Refused | ControlOutcome::Conflict), + code, + message, + .. + } => { + let code = code.unwrap_or_else(|| outcome_name(outcome).to_string()); + return Err(anyhow!(Refusal::from_target(&code, &message, machine))); + } + Ended::Result { + outcome, + code, + message, + run_id, + } => (outcome, code, message, run_id), + }; + let text = match outcome { + ControlOutcome::Done if asked.action == ControlAction::Stop => { + format!("'{}' stopped on {machine}.", asked.service) + } + ControlOutcome::Done => format!("'{}' is running on {machine}.", asked.service), + ControlOutcome::Starting => format!("Started on {machine}, not listening yet."), + _ if message.is_empty() => format!("'{}' failed to start on {machine}.", asked.service), + _ => message, + }; + let exit = if outcome == ControlOutcome::Failed { + FAILED + } else { + 0 + }; + if console.json { + console.json(&Outcome { + outcome: outcome_name(outcome), + action: asked.action, + machine: asked.peer, + service: &asked.ids, + message: text, + code, + run_id, + status: None, + })?; + } else if exit == 0 { + writeln!(console.out, "{text}")?; + } else { + writeln!(console.err, "{text}")?; + } + Ok(exit) +} + +/// An outcome the target could not tell: says so, then shows the service +/// as it is now, and exits with [`LOST`]. The control is never sent again. +fn lost( + code: &str, + asked: &Asked<'_>, + console: &mut Console, + fresh: impl FnOnce() -> Result<(Item, Value)>, +) -> Result { + let machine = &asked.peer.name; + let message = match code { + "not_shared" => format!("{machine} stopped sharing before it said what happened."), + "not_paired" | "key_mismatch" => format!( + "{machine} didn't say what happened. {}", + viewer_message(code, machine, "") + ), + _ => format!("{machine} didn't say what happened. Its current state is below."), + }; + let now = fresh(); + if console.json { + console.json(&Outcome { + outcome: "lost", + action: asked.action, + machine: asked.peer, + service: &asked.ids, + message, + code: Some(code.to_string()), + run_id: None, + status: now.ok().map(|(_, raw)| raw), + })?; + return Ok(LOST); + } + writeln!(console.err, "{message}")?; + match now { + Ok((item, _)) => write_item(&mut console.out, &item, machine)?, + Err(error) => writeln!( + console.err, + "Its current state could not be read: {error:#}" + )?, + } + Ok(LOST) +} + +fn outcome_name(outcome: ControlOutcome) -> &'static str { + match outcome { + ControlOutcome::Done => "done", + ControlOutcome::Starting => "starting", + ControlOutcome::Refused => "refused", + ControlOutcome::Conflict => "conflict", + ControlOutcome::Failed => "failed", + ControlOutcome::Unknown => "unknown", + } +} + +/// The service as the target shows it now. +fn fresh( + client: &MgmtSocketClient, + peer: &Peer, + query: &ServiceQuery<'_>, +) -> Result<(Item, Value)> { + let (snapshot, _) = fetch(client, peer)?; + let items = snapshot.shared_items(peer)?; + let (item, raw) = find(&items, query, &peer.name)?; + Ok((item.clone(), (*raw).clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cli::remote::REFUSED; + use crate::cli::remote::inventory::tests::item; + + fn peer() -> Peer { + Peer { + id: "mB".into(), + name: "teo-mini".into(), + } + } + + fn asked(peer: &Peer, action: ControlAction) -> Asked<'_> { + Asked { + peer, + action, + service: "web", + ids: json!({ "projectId": "app", "environment": null, "serviceId": "web" }), + app_running: true, + } + } + + fn console(json: bool) -> Console, Vec> { + Console { + json, + out: Vec::new(), + err: Vec::new(), + } + } + + fn text(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() + } + + fn run( + events: Vec, + action: ControlAction, + console: &mut Console, Vec>, + ) -> Result { + let peer = peer(); + let asked = asked(&peer, action); + let ended = follow(events.into_iter().map(Ok), &asked, console)?; + let fresh = || { + let raw = item("app", None, "web"); + Ok((serde_json::from_value(raw.clone())?, raw)) + }; + let result = report(ended, &asked, console, fresh); + super::super::finish(console, result) + } + + #[test] + fn a_control_prints_its_progress_then_its_result() { + let mut console = console(false); + let events = vec![ + json!({ "event": "sent", "requestId": "q" }), + json!({ "event": "progress", "phase": "dispatched" }), + json!({ "event": "progress", "phase": "started" }), + json!({ "event": "result", "outcome": "done", "code": null, "message": "", "runId": "R2" }), + ]; + + let code = run(events, ControlAction::Restart, &mut console).unwrap(); + + assert_eq!(code, 0); + assert_eq!( + text(&console.out), + "Restarting 'web' on teo-mini…\nStarting in the app on teo-mini…\nStarted on teo-mini. Waiting for its port…\n'web' is running on teo-mini.\n" + ); + } + + #[test] + fn in_json_progress_goes_to_stderr_and_the_result_is_one_document() { + let mut console = console(true); + let events = vec![ + json!({ "event": "sent", "requestId": "q" }), + json!({ "event": "result", "outcome": "done", "code": null, "message": "", "runId": null }), + ]; + + let code = run(events, ControlAction::Stop, &mut console).unwrap(); + + assert_eq!(code, 0); + assert_eq!(text(&console.err), "Stopping 'web' on teo-mini…\n"); + let printed: Value = serde_json::from_slice(&console.out).unwrap(); + assert_eq!(printed["outcome"], "done"); + assert_eq!(printed["action"], "stop"); + assert_eq!(printed["message"], "'web' stopped on teo-mini."); + assert_eq!(printed["service"]["serviceId"], "web"); + } + + #[test] + fn a_refusal_from_the_target_exits_2_with_its_code() { + for json in [true, false] { + let mut console = console(json); + let events = vec![json!({ + "event": "result", "outcome": "refused", "code": "background_disabled", + "message": "Localify isn't open on this machine, and it doesn't allow background starts.", + "runId": null, + })]; + + let code = run(events, ControlAction::Start, &mut console).unwrap(); + + assert_eq!(code, REFUSED); + let said = + "Localify isn't open on teo-mini, and teo-mini doesn't allow background starts."; + if json { + let printed: Value = serde_json::from_slice(&console.out).unwrap(); + assert_eq!(printed["code"], "background_disabled"); + assert_eq!(printed["message"], said); + } else { + assert!( + text(&console.err).starts_with(said), + "{}", + text(&console.err) + ); + } + } + } + + #[test] + fn a_refusal_before_sending_has_no_sent_event_and_the_connection_state() { + let mut console = console(true); + let events = vec![json!({ + "event": "result", "outcome": "refused", "code": "peer_offline", + "message": "Offline.", "runId": null, + })]; + + assert_eq!( + run(events, ControlAction::Stop, &mut console).unwrap(), + REFUSED + ); + let printed: Value = serde_json::from_slice(&console.out).unwrap(); + assert_eq!(printed["message"], "teo-mini is offline."); + } + + #[test] + fn a_lost_outcome_prints_the_fresh_status_and_exits_3() { + let events = || { + vec![ + json!({ "event": "sent", "requestId": "q" }), + json!({ "event": "unknown", "code": "closed", "message": "Session lost." }), + json!({ "event": "lost", "code": "timeout", "message": "No outcome." }), + ] + }; + let mut human = console(false); + assert_eq!( + run(events(), ControlAction::Restart, &mut human).unwrap(), + LOST + ); + assert!(text(&human.out).contains("Outcome unknown. Checking teo-mini…\n")); + assert!( + text(&human.out).contains("APP / web\n Running, in the app"), + "{}", + text(&human.out) + ); + assert!(text(&human.err).starts_with("teo-mini didn't say what happened.")); + + let mut json = console(true); + assert_eq!( + run(events(), ControlAction::Restart, &mut json).unwrap(), + LOST + ); + let printed: Value = serde_json::from_slice(&json.out).unwrap(); + assert_eq!(printed["outcome"], "lost"); + assert_eq!(printed["code"], "timeout"); + assert_eq!(printed["status"]["process"], "running"); + } + + #[test] + fn a_failed_start_exits_1_with_the_targets_last_lines() { + let mut console = console(false); + let events = vec![json!({ + "event": "result", "outcome": "failed", "code": "failed", + "message": "web exited with code 1.\nError: port in use", "runId": "R2", + })]; + + assert_eq!( + run(events, ControlAction::Start, &mut console).unwrap(), + FAILED + ); + assert_eq!( + text(&console.err), + "web exited with code 1.\nError: port in use\n" + ); + } + + #[test] + fn what_the_snapshot_refuses_is_never_sent() { + let web = |controls: Value, legacy: bool| -> Item { + let mut value = item("app", None, "web"); + value["controls"] = controls; + value["run"]["legacy"] = json!(legacy); + serde_json::from_value(value).unwrap() + }; + let running = web( + json!({ + "start": { "allowed": false, "code": "conflict" }, + "stop": { "allowed": true }, + "restart": { "allowed": false, "code": "owner_gone" }, + }), + false, + ); + let refused = |item: &Item, action| { + let error = allowed(item, action, "teo-mini").unwrap_err(); + error.downcast_ref::().unwrap().clone() + }; + + assert!(allowed(&running, ControlAction::Stop, "teo-mini").is_ok()); + let start = refused(&running, ControlAction::Start); + assert_eq!( + (start.code.as_str(), start.message.as_str()), + ("conflict", "'web' already runs on teo-mini.") + ); + assert_eq!( + refused(&running, ControlAction::Restart).message, + "Stop it, then start it again." + ); + + let legacy = web(json!({ "restart": { "allowed": true } }), true); + assert_eq!(refused(&legacy, ControlAction::Restart).code, "legacy_run"); + } +} diff --git a/src/cli/remote/inventory.rs b/src/cli/remote/inventory.rs new file mode 100644 index 00000000..fcc7175f --- /dev/null +++ b/src/cli/remote/inventory.rs @@ -0,0 +1,504 @@ +//! Another machine's services, from its inventory snapshot +//! (docs/remote-machines.md, "Inventory"), and `services status --machine`. + +use std::collections::BTreeMap; +use std::io::Write; + +use anyhow::{Context, Result, anyhow, bail}; +use serde::Deserialize; +use serde_json::Value; + +use super::{Console, Peer, Refusal, remote_error}; +use crate::infrastructure::mgmt_client::MgmtSocketClient; +use crate::infrastructure::remote::wire::{AppPresence, MachineSummary}; + +/// A service on the target, named as `--project` and `--env` name it there: +/// there is no folder to read on another machine. +#[derive(Debug, Clone, Copy)] +pub struct ServiceQuery<'a> { + pub service: &'a str, + pub project: Option<&'a str>, + /// A checkout other than the primary one, by slug or name. + pub env: Option<&'a str>, +} + +/// A target's whole snapshot, as `remote_inventory` and `remote_watch` give +/// it. Items stay as sent, for JSON, and are read through [`Item`]. +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Snapshot { + pub(super) machine: MachineSummary, + #[serde(default)] + pub(super) truncated: bool, + pub(super) items: Vec, +} + +/// The fields of an `InventoryItem` the CLI reads. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Item { + pub(super) project: Named, + pub(super) environment: Environment, + pub(super) service: ServiceRef, + pub(super) local_url: String, + pub(super) owner: Option, + pub(super) run: Option, + pub(super) process: String, + pub(super) port: Port, + pub(super) output: Output, + pub(super) public_url: Option, + #[serde(default)] + pub(super) controls: BTreeMap, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Named { + pub(super) id: String, + pub(super) name: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Environment { + pub(super) slug: Option, + pub(super) name: String, + pub(super) primary: bool, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct ServiceRef { + pub(super) id: String, + pub(super) name: String, + pub(super) config_rev: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Run { + pub(super) run_id: Option, + #[serde(default)] + pub(super) legacy: bool, + pub(super) exit: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Exit { + pub(super) code: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Port { + pub(super) number: u16, + pub(super) reachable: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Output { + pub(super) available: bool, + pub(super) run_id: Option, + pub(super) reason: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct PublicUrl { + pub(super) url: String, + pub(super) serving: bool, + pub(super) reason: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Allowed { + pub(super) allowed: bool, + pub(super) code: Option, +} + +impl Snapshot { + pub(super) fn parse(value: Value) -> Result { + serde_json::from_value(value) + .context("The daemon sent a snapshot this version of Localify cannot read") + } + + /// The services, or `not_shared` when the target shares nothing. + pub(super) fn shared_items(&self, peer: &Peer) -> Result> { + if !self.machine.settings.share { + return Err(anyhow!(Refusal::from_target("not_shared", "", &peer.name))); + } + self.items + .iter() + .map(|raw| { + let item = serde_json::from_value(raw.clone()) + .context("The daemon sent a service this version of Localify cannot read")?; + Ok((item, raw)) + }) + .collect() + } +} + +/// One snapshot of the target, every page. +pub(super) fn fetch(client: &MgmtSocketClient, peer: &Peer) -> Result<(Snapshot, Value)> { + let value = client + .remote_inventory(&peer.id) + .map_err(|error| remote_error(error, peer))?; + Ok((Snapshot::parse(value.clone())?, value)) +} + +/// The one service `query` names. An ambiguous name lists the matches. +pub(super) fn find<'a, T>( + items: &'a [(Item, T)], + query: &ServiceQuery<'_>, + machine: &str, +) -> Result<&'a (Item, T)> { + let matches: Vec<&(Item, T)> = items + .iter() + .filter(|(item, _)| in_environment(item, query.env)) + .filter(|(item, _)| { + query + .project + .is_none_or(|project| names_project(item, project)) + }) + .filter(|(item, _)| item.service.id == query.service || item.service.name == query.service) + .collect(); + match matches.as_slice() { + [one] => Ok(one), + [] => bail!("{}", no_such_service(items, query, machine)), + many => { + let listed: Vec = many + .iter() + .map(|(item, _)| format!(" {}", selector(item))) + .collect(); + bail!( + "'{}' names more than one service on {machine}. Pass --project with one of:\n{}", + query.service, + listed.join("\n") + ) + } + } +} + +fn in_environment(item: &Item, env: Option<&str>) -> bool { + match env { + None => item.environment.primary, + Some(env) => { + item.environment.slug.as_deref() == Some(env) + || item.environment.name.to_lowercase() == env.to_lowercase() + } + } +} + +fn names_project(item: &Item, project: &str) -> bool { + item.project.id == project || item.project.name.to_lowercase() == project.to_lowercase() +} + +fn no_such_service(items: &[(Item, T)], query: &ServiceQuery<'_>, machine: &str) -> String { + let known: Vec = items + .iter() + .map(|(item, _)| format!(" {}", selector(item))) + .collect(); + let mut message = format!("No service '{}' on {machine}", query.service); + if let Some(project) = query.project { + message.push_str(&format!(" in project '{project}'")); + } + if let Some(env) = query.env { + message.push_str(&format!(" in environment '{env}'")); + } + if known.is_empty() { + message.push_str(&format!(": {machine} has no service.")); + } else { + message.push_str(&format!(". Its services:\n{}", known.join("\n"))); + } + message +} + +/// How the CLI names a target's service: `web --project app [--env feat]`. +pub(super) fn selector(item: &Item) -> String { + let mut selector = format!("{} --project {}", item.service.id, item.project.id); + if let Some(slug) = item + .environment + .slug + .as_deref() + .filter(|_| !item.environment.primary) + { + selector.push_str(&format!(" --env {slug}")); + } + selector +} + +/// `services status --machine`: every service of the target with its four +/// states; the snapshot as the daemon gave it, as JSON. +pub fn status( + client: &MgmtSocketClient, + peer: &Peer, + console: &mut Console, +) -> Result { + let (snapshot, raw) = fetch(client, peer)?; + let items = snapshot.shared_items(peer)?; + if console.json { + console.json(&raw)?; + return Ok(0); + } + writeln!(console.out, "{}", machine_line(&snapshot.machine))?; + if items.is_empty() { + writeln!(console.out, "{} has no service.", peer.name)?; + } + for (item, _) in &items { + writeln!(console.out)?; + write_item(&mut console.out, item, &peer.name)?; + } + if snapshot.truncated { + writeln!( + console.out, + "\n{} has more services than one snapshot holds; these are the first.", + peer.name + )?; + } + Ok(0) +} + +fn machine_line(machine: &MachineSummary) -> String { + let os = if machine.os == "macos" { + "macOS" + } else { + "Linux" + }; + let app = match machine.app { + AppPresence::Running => "app open", + AppPresence::Absent => "app closed", + }; + let controls = match (machine.settings.control, machine.settings.background_starts) { + (false, _) => "remote controls off", + (true, false) => "remote controls on", + (true, true) => "remote controls and background starts on", + }; + format!( + "{} · {os} · Localify {} · {app} · {controls}", + machine.name, machine.version + ) +} + +/// A service's name, then its states on one line, and its URLs. +pub(super) fn write_item(out: &mut impl Write, item: &Item, machine: &str) -> Result<()> { + let environment = if item.environment.primary { + String::new() + } else { + format!(" [{}]", item.environment.name) + }; + writeln!( + out, + "{} / {}{environment}", + item.project.name, item.service.name + )?; + let owner = match item.owner.as_deref() { + Some("app") => ", in the app", + Some("background") => ", in the background", + Some("terminal") => ", in a terminal", + Some("unknown") => ", an unknown process", + _ => "", + }; + let port = match item.port.reachable { + Some(true) => "reachable", + Some(false) => "not reachable", + None => "not checked", + }; + writeln!( + out, + " {}{owner} · port {} {port} · output {}", + process_state(item), + item.port.number, + output_state(item) + )?; + writeln!(out, " {} (opens on {machine} only)", item.local_url)?; + if let Some(public) = &item.public_url { + writeln!(out, " {} ({})", public.url, public_state(public))?; + } + Ok(()) +} + +/// The process state, as the app's chip says it. +pub(super) fn process_state(item: &Item) -> String { + if item.process == "running" { + return if item.port.reachable == Some(false) { + "Starting".to_string() + } else { + "Running".to_string() + }; + } + match item.run.as_ref().and_then(|run| run.exit.as_ref()?.code) { + Some(code) if code != 0 => format!("Exited with {code}"), + _ => "Stopped".to_string(), + } +} + +fn output_state(item: &Item) -> &'static str { + if item.output.available { + return "available"; + } + match item.output.reason.as_deref() { + Some("terminal") => "in a terminal", + Some("unknown_owner") => "of an unknown process", + Some("legacy_run") => "needs a relaunch to share", + _ => "none yet", + } +} + +fn public_state(public: &PublicUrl) -> &'static str { + if public.serving { + return "serving"; + } + match public.reason.as_deref() { + Some("suspended") => "suspended", + Some("taken_down") => "taken down", + Some("served_elsewhere") => "served elsewhere", + Some("tunnel_down") => "tunnel down", + _ => "not serving", + } +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + use serde_json::json; + + pub(in crate::cli::remote) fn item(project: &str, env: Option<&str>, service: &str) -> Value { + json!({ + "project": { "id": project, "name": project.to_uppercase() }, + "environment": { + "slug": env, "name": env.unwrap_or("Primary"), + "primary": env.is_none(), "branch": null, + }, + "service": { "id": service, "name": service, "configRev": "0123456789abcdef" }, + "localUrl": format!("https://{service}.{project}.localify"), + "owner": "app", + "run": { + "runId": "RRRRRRRRRRRRRRRRRRRRRR", "legacy": false, + "startedAt": "2026-11-09T09:00:00Z", "profile": null, + "profileDanger": false, "exit": null, + }, + "process": "running", + "port": { "number": 4100, "reachable": true }, + "output": { "available": true, "runId": "RRRRRRRRRRRRRRRRRRRRRR" }, + "publicUrl": null, + "controls": { + "start": { "allowed": false, "code": "conflict" }, + "stop": { "allowed": true }, + "restart": { "allowed": true }, + }, + }) + } + + pub(in crate::cli::remote) fn snapshot(share: bool, items: Vec) -> Value { + json!({ + "machine": { + "machineId": "mB", "name": "teo-mini", "version": "1.7.0", "os": "macos", + "settings": { "share": share, "control": true, "backgroundStarts": false }, + "app": "running", + }, + "epoch": "e", "rev": 1, "truncated": false, "items": items, + }) + } + + fn peer() -> Peer { + Peer { + id: "mB".into(), + name: "teo-mini".into(), + } + } + + fn items(values: Vec) -> Vec<(Item, ())> { + values + .into_iter() + .map(|value| (serde_json::from_value(value).unwrap(), ())) + .collect() + } + + fn query<'a>( + service: &'a str, + project: Option<&'a str>, + env: Option<&'a str>, + ) -> ServiceQuery<'a> { + ServiceQuery { + service, + project, + env, + } + } + + #[test] + fn a_service_is_found_in_the_primary_checkout_unless_env_names_another() { + let all = items(vec![ + item("app", None, "web"), + item("app", Some("feat"), "web"), + ]); + + let (primary, _) = find(&all, &query("web", None, None), "mini").unwrap(); + assert!(primary.environment.primary); + let (feat, _) = find(&all, &query("web", None, Some("feat")), "mini").unwrap(); + assert_eq!(feat.environment.slug.as_deref(), Some("feat")); + } + + #[test] + fn a_name_in_two_projects_needs_project() { + let all = items(vec![item("app", None, "web"), item("blog", None, "web")]); + + let error = find(&all, &query("web", None, None), "mini") + .unwrap_err() + .to_string(); + assert!( + error.contains("web --project app") && error.contains("web --project blog"), + "{error}" + ); + + let (found, _) = find(&all, &query("web", Some("BLOG"), None), "mini").unwrap(); + assert_eq!(found.project.id, "blog"); + } + + #[test] + fn an_unknown_service_lists_the_targets_services() { + let all = items(vec![ + item("app", None, "web"), + item("app", Some("feat"), "api"), + ]); + + let error = find(&all, &query("worker", None, None), "mini") + .unwrap_err() + .to_string(); + + assert!(error.starts_with("No service 'worker' on mini."), "{error}"); + assert!(error.contains("api --project app --env feat"), "{error}"); + } + + #[test] + fn a_target_that_shares_nothing_is_refused_not_shared() { + let snapshot = Snapshot::parse(snapshot(false, Vec::new())).unwrap(); + + let error = snapshot.shared_items(&peer()).unwrap_err(); + + assert_eq!(error.downcast_ref::().unwrap().code, "not_shared"); + } + + #[test] + fn an_item_shows_its_four_states() { + let mut value = item("app", Some("feat"), "web"); + value["port"]["reachable"] = json!(false); + value["publicUrl"] = + json!({ "url": "https://web.localify.fyi", "serving": false, "reason": "tunnel_down" }); + let item: Item = serde_json::from_value(value).unwrap(); + let mut out = Vec::new(); + + write_item(&mut out, &item, "teo-mini").unwrap(); + + assert_eq!( + String::from_utf8(out).unwrap(), + "APP / web [feat]\n Starting, in the app · port 4100 not reachable · output available\n https://web.app.localify (opens on teo-mini only)\n https://web.localify.fyi (tunnel down)\n" + ); + } + + #[test] + fn a_stopped_service_shows_a_failed_exit() { + let mut value = item("app", None, "web"); + value["process"] = json!("stopped"); + value["run"]["exit"] = json!({ "at": "2026-11-09T10:42:00Z", "code": 1 }); + let item: Item = serde_json::from_value(value).unwrap(); + + assert_eq!(process_state(&item), "Exited with 1"); + } +} diff --git a/src/cli/remote/logs.rs b/src/cli/remote/logs.rs new file mode 100644 index 00000000..42eb203b --- /dev/null +++ b/src/cli/remote/logs.rs @@ -0,0 +1,357 @@ +//! `logs --machine`: a run's output on another machine, as plain +//! lines (docs/remote-machines.md, "Output"). Reads are bounded on the +//! target; a cursor `:` reads on from where the last call +//! stopped, as it does locally. + +use std::collections::VecDeque; +use std::io::Write; + +use anyhow::{Context, Result, anyhow}; +use serde_json::{Value, json}; + +use super::inventory::{Item, ServiceQuery, fetch, find, process_state}; +use super::{Console, Peer, Refusal, remote_error}; +use crate::infrastructure::mgmt_client::{MgmtSocketClient, MgmtStream}; +use crate::infrastructure::remote::wire::{MAX_READ_BYTES, OutputData, OutputLine}; +use crate::infrastructure::runs::RunId; + +/// Without a cursor, the last lines come from at most this much of the end. +const TAIL_BYTES: u64 = 64 * 1024; +/// How much one `--cursor` call reads at most; the next cursor goes on. +const READ_BUDGET: u64 = 256 * 1024; + +pub struct LogsQuery<'a> { + pub service: ServiceQuery<'a>, + pub lines: usize, + pub follow: bool, + pub cursor: Option<&'a str>, +} + +/// Prints the last lines of the service's run, or what came after the +/// cursor, then follows it when asked. A reader that is not a terminal also +/// gets the cursor to pass next time. +pub fn logs( + client: &MgmtSocketClient, + peer: &Peer, + query: &LogsQuery<'_>, + console: &mut Console, +) -> Result { + let cursor = query.cursor.map(Cursor::parse).transpose()?; + let (snapshot, _) = fetch(client, peer)?; + let items = snapshot.shared_items(peer)?; + let (item, _) = find(&items, &query.service, &peer.name)?; + let run_id = readable_run(item, &peer.name)?; + writeln!( + console.err, + "'{}' on {}: {}.\n", + item.service.name, + peer.name, + process_state(item) + )?; + let mut reader = Reader { + client, + peer, + run_id: &run_id, + service: &item.service.name, + console, + }; + let mut offset = match cursor { + Some(cursor) if cursor.run_id == run_id => reader.read_on(cursor.offset)?, + Some(_) => { + reader.note(&format!( + "'{}' restarted since that cursor: reading its current run from the start.", + item.service.name + ))?; + reader.read_on(0)? + } + None => reader.tail(query.lines)?, + }; + if query.follow { + offset = reader.follow(offset)?; + } + if query.cursor.is_some() || reader.console.json { + writeln!(reader.console.err, "\nNext cursor: {run_id}:{offset}")?; + } + Ok(0) +} + +/// Where a read goes on from: `:`. +#[derive(Debug, PartialEq, Eq)] +struct Cursor { + run_id: String, + offset: u64, +} + +impl Cursor { + fn parse(value: &str) -> Result { + let invalid = || { + format!( + "'{value}' is not a cursor of another machine. Pass back the `:` the previous `logs --machine` call printed." + ) + }; + let (run_id, offset) = value.split_once(':').with_context(invalid)?; + RunId::parse(run_id).with_context(invalid)?; + Ok(Self { + run_id: run_id.to_string(), + offset: offset.parse().with_context(invalid)?, + }) + } +} + +/// The run whose output can be read, or why none can. +fn readable_run(item: &Item, machine: &str) -> Result { + if let (true, Some(run_id)) = (item.output.available, &item.output.run_id) { + return Ok(run_id.clone()); + } + let service = &item.service.name; + let message = match item.output.reason.as_deref() { + Some("terminal") => { + format!("'{service}' runs in a terminal on {machine}: its output is only there.") + } + Some("unknown_owner") => format!( + "An unknown process holds the port of '{service}' on {machine}, and its output can't be read." + ), + Some("legacy_run") => format!( + "'{service}' started before this version of Localify on {machine}. Relaunch it there to share its output." + ), + _ => format!("'{service}' has not run on {machine} yet."), + }; + Err(anyhow!(Refusal::new("output_unavailable", message))) +} + +struct Reader<'a, O, E> { + client: &'a MgmtSocketClient, + peer: &'a Peer, + run_id: &'a str, + service: &'a str, + console: &'a mut Console, +} + +impl Reader<'_, O, E> { + fn note(&mut self, line: &str) -> Result<()> { + writeln!(self.console.err, "{line}")?; + Ok(()) + } + + fn read(&self, offset: u64) -> Result { + let value = self + .client + .remote_output_read(&self.peer.id, self.run_id, offset, MAX_READ_BYTES) + .map_err(|error| self.restarted(remote_error(error, self.peer)))?; + data(value) + } + + /// `gone` from a read means the service restarted since it was looked at. + fn restarted(&self, error: anyhow::Error) -> anyhow::Error { + match error.downcast_ref::() { + Some(refusal) if refusal.code == "gone" => anyhow!(Refusal::new( + "gone", + format!( + "'{}' restarted on {}. Read its output again without --cursor.", + self.service, self.peer.name + ), + )), + _ => error, + } + } + + /// Prints from `offset` until caught up, the run ended, or + /// [`READ_BUDGET`] was read; returns where it stopped. + fn read_on(&mut self, mut offset: u64) -> Result { + let started = offset; + loop { + let chunk = self.read(offset)?; + self.print(&chunk)?; + let caught_up = chunk.next == offset; + offset = chunk.next; + if caught_up || chunk.ended || offset - started >= READ_BUDGET { + return Ok(offset); + } + } + } + + /// The last `count` lines: a follow from the last [`TAIL_BYTES`] gives + /// where they start, and reads go on to the end. + fn tail(&mut self, count: usize) -> Result { + let mut follow = self.open_follow(json!({ "tail": TAIL_BYTES }))?; + let first = match self.next_data(&mut follow)? { + Followed::Data(data) => data, + Followed::Ended(refusal) => return Err(anyhow!(refusal)), + Followed::Closed => return Ok(0), + }; + drop(follow); + let start = first.offset; + let mut lines = VecDeque::new(); + let mut chunk = first; + loop { + lines.extend(chunk.lines.iter().cloned()); + while lines.len() > count { + lines.pop_front(); + } + if chunk.ended || chunk.next - start >= READ_BUDGET { + break; + } + let next = self.read(chunk.next)?; + if next.next == chunk.next && !next.ended { + break; + } + chunk = next; + } + self.print_lines(lines.iter())?; + self.print_end(&chunk)?; + Ok(chunk.next) + } + + /// Prints new lines as they come, until the run ends or restarts. + fn follow(&mut self, mut offset: u64) -> Result { + let mut follow = self.open_follow(json!({ "offset": offset }))?; + loop { + match self.next_data(&mut follow)? { + Followed::Data(chunk) => { + self.print(&chunk)?; + offset = chunk.next; + if chunk.ended { + self.note(&format!("The run of '{}' ended.", self.service))?; + return Ok(offset); + } + } + Followed::Ended(refusal) if refusal.code == "gone" => { + self.note(&format!( + "'{}' restarted on {}.", + self.service, self.peer.name + ))?; + return Ok(offset); + } + Followed::Ended(refusal) => return Err(anyhow!(refusal)), + Followed::Closed => return Ok(offset), + } + } + } + + fn open_follow(&self, from: Value) -> Result { + let mut command = json!({ + "cmd": "remote_output_follow", + "machineId": self.peer.id, + "runId": self.run_id, + }); + if let (Some(command), Some(from)) = (command.as_object_mut(), from.as_object()) { + command.extend(from.clone()); + } + self.client + .remote_stream(&command) + .map_err(|error| remote_error(error, self.peer)) + } + + fn next_data(&self, follow: &mut MgmtStream) -> Result { + let Some(event) = follow + .next_answer() + .map_err(|error| remote_error(error, self.peer))? + else { + return Ok(Followed::Closed); + }; + match event["event"].as_str() { + Some("data") => Ok(Followed::Data(data(event)?)), + Some("ended") => Ok(Followed::Ended(Refusal::from_target( + event["code"].as_str().unwrap_or_default(), + event["message"].as_str().unwrap_or_default(), + &self.peer.name, + ))), + _ => Ok(Followed::Closed), + } + } + + fn print(&mut self, chunk: &OutputData) -> Result<()> { + if chunk.rotated.is_some() { + self.note("Earlier output was dropped.")?; + } + self.print_lines(chunk.lines.iter())?; + self.print_end(chunk) + } + + fn print_lines<'l>(&mut self, lines: impl Iterator) -> Result<()> { + for line in lines { + if line.cut { + write!(self.console.out, "{}", line.text)?; + } else { + writeln!(self.console.out, "{}", line.text)?; + } + } + Ok(()) + } + + fn print_end(&mut self, chunk: &OutputData) -> Result<()> { + if chunk.ended && chunk.interrupted { + let line = format!( + "Output was cut off when Localify stopped on {}.", + self.peer.name + ); + self.note(&line)?; + } + Ok(()) + } +} + +enum Followed { + Data(OutputData), + /// The follow stopped before its run did, with the target's reason. + Ended(Refusal), + /// The daemon closed the stream. + Closed, +} + +fn data(mut value: Value) -> Result { + // A follow event carries `event` beside the data's own fields. + if let Some(fields) = value.as_object_mut() { + fields.remove("event"); + } + serde_json::from_value(value).context("The daemon sent output this version cannot read") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cli::remote::inventory::tests::item; + + #[test] + fn a_cursor_is_a_run_id_and_an_offset() { + assert_eq!( + Cursor::parse("RRRRRRRRRRRRRRRRRRRRRR:120").unwrap(), + Cursor { + run_id: "RRRRRRRRRRRRRRRRRRRRRR".into(), + offset: 120 + } + ); + assert!(Cursor::parse("120").is_err()); + assert!(Cursor::parse("short:1").is_err()); + assert!(Cursor::parse("RRRRRRRRRRRRRRRRRRRRRR:-1").is_err()); + } + + #[test] + fn output_that_cannot_be_read_says_why() { + let mut value = item("app", None, "web"); + value["output"] = json!({ "available": false, "reason": "terminal" }); + let terminal: Item = serde_json::from_value(value).unwrap(); + + let error = readable_run(&terminal, "teo-mini").unwrap_err(); + + let refusal = error.downcast_ref::().unwrap(); + assert_eq!(refusal.code, "output_unavailable"); + assert_eq!( + refusal.message, + "'web' runs in a terminal on teo-mini: its output is only there." + ); + } + + #[test] + fn a_follow_event_reads_as_output() { + let event = json!({ + "event": "data", "re": "f1", "runId": "R", "offset": 0, "next": 6, + "lines": [{ "text": "ready" }], "ended": false, + }); + + let data = data(event).unwrap(); + + assert_eq!(data.next, 6); + assert_eq!(data.lines[0].text, "ready"); + } +} diff --git a/src/cli/remote/mod.rs b/src/cli/remote/mod.rs new file mode 100644 index 00000000..e522ed2c --- /dev/null +++ b/src/cli/remote/mod.rs @@ -0,0 +1,419 @@ +//! `--machine`: the services of another machine of the account, through this +//! machine's daemon, which holds the session to it (docs/remote-machines.md, +//! "CLI"). Status and output come from its snapshots and reads; `dev`, `stop` +//! and `restart` become controls. What the other machine refuses is said as +//! the app says it ("Errors"), and exits with [`REFUSED`]. + +mod control; +mod inventory; +mod logs; + +use std::io::{self, Stderr, Stdout, Write}; + +use anyhow::{Result, anyhow}; +use serde::Serialize; + +pub use control::control; +pub use inventory::{ServiceQuery, status}; +pub use logs::{LogsQuery, logs}; + +pub use crate::infrastructure::remote::wire::ControlAction; + +use super::machines::{Machine as Listed, candidates, daemon_error, machines, resolve}; +use super::output::wants_json; +use crate::application::ports::DaemonConnectionError; +use crate::infrastructure::mgmt_client::MgmtSocketClient; + +/// The exit code of a refusal: by the other machine, or before anything +/// was sent to it. +pub const REFUSED: i32 = 2; +/// The exit code of a control whose outcome could not be learned. +pub const LOST: i32 = 3; + +/// Where a command with `--machine` acts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Machine { + /// This machine's own id or name: as without `--machine`. + Local, + Remote(Peer), +} + +/// Another machine of the account, as the roster names it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Peer { + pub id: String, + pub name: String, +} + +/// Resolves `--machine`: an exact id, else an exact name ignoring case, +/// among the account's active machines. Pins of machines that left the +/// account are not candidates. +pub fn machine(query: &str, client: &MgmtSocketClient) -> Result { + pick(&machines(client, false)?, query) +} + +fn pick(listed: &[Listed], query: &str) -> Result { + let active: Vec = listed + .iter() + .filter(|machine| machine.state != "signed_out") + .cloned() + .collect(); + let found = resolve(&candidates(&active), query)?; + if found.is_self { + return Ok(Machine::Local); + } + Ok(Machine::Remote(Peer { + id: found.id, + name: found.name, + })) +} + +/// Runs `remote` on the machine `query` names, or `local` when it names +/// this one, as without `--machine`. +pub fn on_machine( + query: &str, + client: &MgmtSocketClient, + local: impl FnOnce() -> Result<()>, + remote: impl FnOnce(&Peer) -> Result, +) -> Result { + match machine(query, client)? { + Machine::Local => local().map(|()| 0), + Machine::Remote(peer) => remote(&peer), + } +} + +/// Where a remote command writes: a person reads text, anything else one +/// JSON document on stdout, with progress on stderr. +pub struct Console { + pub json: bool, + pub out: O, + pub err: E, +} + +impl Console { + pub fn standard(json_flag: bool) -> Self { + Self { + json: wants_json(json_flag), + out: io::stdout(), + err: io::stderr(), + } + } +} + +impl Console { + /// A line beside the result: on stdout for a person, on stderr with JSON. + fn note(&mut self, line: &str) -> Result<()> { + if self.json { + writeln!(self.err, "{line}")?; + } else { + writeln!(self.out, "{line}")?; + } + Ok(()) + } + + fn json(&mut self, value: &impl Serialize) -> Result<()> { + writeln!(self.out, "{}", serde_json::to_string_pretty(value)?)?; + Ok(()) + } +} + +/// Runs a `--machine` command, then ends the process with its exit code. A +/// [`Refusal`] is printed as one, and exits with [`REFUSED`]. +pub fn run( + json_flag: bool, + command: impl FnOnce(&mut Console) -> Result, +) -> Result<()> { + let mut console = Console::standard(json_flag); + let result = command(&mut console); + let code = finish(&mut console, result)?; + if code != 0 { + std::process::exit(code); + } + Ok(()) +} + +/// The exit code of a command's result, once a refusal is printed. +pub(crate) fn finish( + console: &mut Console, + result: Result, +) -> Result { + match result { + Ok(code) => Ok(code), + Err(error) => match error.downcast::() { + Ok(refusal) => refusal.print(console).map(|()| REFUSED), + Err(error) => Err(error), + }, + } +} + +/// Something the other machine refused, or the CLI before sending it: the +/// contract's code, what the viewer says, and the target's own words when +/// they add something. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, thiserror::Error)] +#[error("{message}")] +pub struct Refusal { + pub code: String, + pub message: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, +} + +impl Refusal { + /// A refusal decided here, with its own message. + pub fn new(code: &str, message: impl Into) -> Self { + Self { + code: code.to_string(), + message: message.into(), + detail: None, + } + } + + /// A target's refusal, said as the viewer says it. + pub fn from_target(code: &str, target_message: &str, machine: &str) -> Self { + let message = viewer_message(code, machine, target_message); + let detail = (!target_message.is_empty() && target_message != message) + .then(|| target_message.to_string()); + Self { + code: code.to_string(), + message, + detail, + } + } + + fn print(&self, console: &mut Console) -> Result<()> { + if console.json { + #[derive(Serialize)] + struct Refused<'a> { + outcome: &'static str, + #[serde(flatten)] + refusal: &'a Refusal, + } + return console.json(&Refused { + outcome: "refused", + refusal: self, + }); + } + writeln!(console.err, "{}", self.message)?; + if let Some(detail) = &self.detail { + writeln!(console.err, "{detail}")?; + } + Ok(()) + } +} + +/// A daemon error on a remote command: a refusal with its code when the +/// other machine, or the way to it, refused. +fn remote_error(error: DaemonConnectionError, peer: &Peer) -> anyhow::Error { + match error { + DaemonConnectionError::Remote { code, message } => { + anyhow!(Refusal::from_target(&code, &message, &peer.name)) + } + other => daemon_error(other), + } +} + +/// What the viewer says for a target's error code: the table of "Errors", +/// as the app's `remoteErrorMessage` (desktop-ui/src/lib/util.remote.ts) +/// says it. A code it does not know keeps the target's message. +pub fn viewer_message(code: &str, machine: &str, fallback: &str) -> String { + match code { + "not_paired" => format!("This machine is not paired with {machine}. Pair them again."), + "key_mismatch" => "Don't trust this machine until you pair it again.".to_string(), + "not_shared" => format!( + "{machine} doesn't share its projects. Turn on sharing in Localify on {machine}." + ), + "control_disabled" => format!("{machine} doesn't allow remote controls."), + "background_disabled" => format!( + "Localify isn't open on {machine}, and {machine} doesn't allow background starts." + ), + "not_owned" => format!("This runs in a terminal on {machine}. Stop it there."), + "legacy_run" => "Relaunch it on that machine to enable remote control.".to_string(), + "owner_gone" => "Stop it, then start it again.".to_string(), + "refused_profile" => format!("Start it on {machine} to use this profile."), + "unknown_service" => format!("This service no longer exists on {machine}."), + "conflict" => format!("{machine} changed in the meantime."), + "expired" => { + format!("The request took too long to reach {machine}. Nothing was started.") + } + "busy" => format!("Something else is starting or stopping it on {machine}."), + "too_many" => { + format!("This machine sent {machine} too many requests lately. Try again later.") + } + "unauthorized" | "lease_expired" => "Remote access is not available right now.".to_string(), + "subscription_required" => "Remote access needs Localify Cloud Pro.".to_string(), + "unsupported" => format!("Update Localify on {machine}."), + "peer_offline" => format!("{machine} is offline."), + "not_connected" => format!("Not connected to {machine}."), + "connecting" => format!("Still connecting to {machine}. Try again once it is connected."), + "not_responding" => format!("{machine} isn't responding right now."), + "revoked" => format!("{machine} was removed from the account."), + "unpaired" => format!("{machine} is no longer paired with this machine."), + _ => fallback.to_string(), + } +} + +/// `dev --machine` takes a service, `--project`, `--env` and `--profile` +/// only: the target decides where and how its services run. `given` names +/// the other options that were passed. +pub fn only_target_options(given: &[&str]) -> Result<()> { + if given.is_empty() { + return Ok(()); + } + Err(anyhow!(Refusal::new( + "refused_argument", + format!( + "With --machine, dev takes only a service, --project, --env and --profile: the other machine decides how its services start. Remove {}.", + given.join(", ") + ), + ))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn listed(id: &str, name: &str, is_self: bool, state: &str) -> Listed { + serde_json::from_value(serde_json::json!({ + "id": id, "name": name, "self": is_self, "paired": !is_self, "state": state, + })) + .unwrap() + } + + fn roster() -> Vec { + vec![ + listed("m1", "teo-mini", true, "connected"), + listed("m2", "Laptop", false, "connected"), + listed("m3", "desk", false, "offline"), + listed("m4", "old-desk", false, "signed_out"), + ] + } + + fn remote(id: &str, name: &str) -> Machine { + Machine::Remote(Peer { + id: id.into(), + name: name.into(), + }) + } + + #[test] + fn a_machine_is_found_by_id_then_by_name_ignoring_case() { + assert_eq!(pick(&roster(), "m2").unwrap(), remote("m2", "Laptop")); + assert_eq!(pick(&roster(), "LAPTOP").unwrap(), remote("m2", "Laptop")); + // Offline is still active: the command says why it can't reach it. + assert_eq!(pick(&roster(), "desk").unwrap(), remote("m3", "desk")); + } + + #[test] + fn this_machines_own_id_or_name_acts_locally() { + assert_eq!(pick(&roster(), "m1").unwrap(), Machine::Local); + assert_eq!(pick(&roster(), "Teo-Mini").unwrap(), Machine::Local); + } + + #[test] + fn two_names_differing_only_in_case_list_both_ids() { + let mut machines = roster(); + machines.push(listed("m5", "LAPTOP", false, "offline")); + + let error = pick(&machines, "laptop").unwrap_err().to_string(); + + assert!( + error.contains("Laptop (m2)") && error.contains("LAPTOP (m5)"), + "{error}" + ); + } + + #[test] + fn an_unknown_name_lists_the_active_roster() { + let error = pick(&roster(), "nas").unwrap_err().to_string(); + + assert!(error.contains("No machine named 'nas'"), "{error}"); + assert!( + error.contains("Laptop (m2)") && error.contains("desk (m3)"), + "{error}" + ); + // A machine that left the account is neither listed nor found. + assert!(!error.contains("old-desk"), "{error}"); + assert!(pick(&roster(), "old-desk").is_err()); + } + + fn console(json: bool) -> Console, Vec> { + Console { + json, + out: Vec::new(), + err: Vec::new(), + } + } + + fn text(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() + } + + #[test] + fn a_refusal_exits_2_with_its_code_in_json() { + let mut console = console(true); + let refusal = Refusal::from_target("control_disabled", "", "teo-mini"); + + let code = finish(&mut console, Err(anyhow!(refusal))).unwrap(); + + assert_eq!(code, REFUSED); + let printed: serde_json::Value = serde_json::from_slice(&console.out).unwrap(); + assert_eq!(printed["outcome"], "refused"); + assert_eq!(printed["code"], "control_disabled"); + assert_eq!( + printed["message"], + "teo-mini doesn't allow remote controls." + ); + assert!(console.err.is_empty()); + } + + #[test] + fn a_refusal_for_a_person_is_its_message_on_stderr() { + let mut console = console(false); + let refusal = Refusal::from_target( + "conflict", + "The service changed since it was looked at. It is running already.", + "teo-mini", + ); + + let code = finish(&mut console, Err(anyhow!(refusal))).unwrap(); + + assert_eq!(code, REFUSED); + assert!(console.out.is_empty()); + assert_eq!( + text(&console.err), + "teo-mini changed in the meantime.\nThe service changed since it was looked at. It is running already.\n" + ); + } + + #[test] + fn any_other_error_stays_an_error() { + let mut console = console(true); + + assert!(finish(&mut console, Err(anyhow!("daemon down"))).is_err()); + assert_eq!(finish(&mut console, Ok(0)).unwrap(), 0); + } + + #[test] + fn an_unknown_code_keeps_the_targets_message() { + let refusal = Refusal::from_target("output_unavailable", "No stream.", "mini"); + + assert_eq!(refusal.message, "No stream."); + assert_eq!(refusal.detail, None); + } + + #[test] + fn dev_on_another_machine_refuses_every_other_option() { + assert!(only_target_options(&[]).is_ok()); + + let error = only_target_options(&["--detach", "a command after --"]).unwrap_err(); + let refusal = error.downcast_ref::().unwrap(); + assert_eq!(refusal.code, "refused_argument"); + assert!( + refusal + .message + .ends_with("Remove --detach, a command after --."), + "{}", + refusal.message + ); + } +} diff --git a/src/daemon/mgmt_socket.rs b/src/daemon/mgmt_socket.rs index 89f36079..74012d82 100644 --- a/src/daemon/mgmt_socket.rs +++ b/src/daemon/mgmt_socket.rs @@ -171,6 +171,11 @@ struct MgmtResponse { ok: bool, #[serde(skip_serializing_if = "Option::is_none")] error: Option, + /// The contract's code of a remote failure, so the CLI and the MCP + /// server can say why another machine refused (docs/remote-machines.md, + /// "Errors"). + #[serde(skip_serializing_if = "Option::is_none")] + code: Option, #[serde(skip_serializing_if = "Option::is_none")] data: Option, } @@ -180,6 +185,7 @@ impl MgmtResponse { Self { ok: true, error: None, + code: None, data: Some(data), } } @@ -188,6 +194,17 @@ impl MgmtResponse { Self { ok: false, error: Some(msg.into()), + code: None, + data: None, + } + } + + /// What another machine, or the way to it, refused, with its code. + fn failure(failure: Failure) -> Self { + Self { + ok: false, + error: Some(failure.message), + code: Some(failure.code), data: None, } } @@ -518,21 +535,22 @@ async fn remote_answer(remote: &RemoteLink, command: MgmtCommand) -> MgmtRespons MgmtCommand::RemoteAccessRestore { machine_id } => remote .restore_access(&machine_id) .map(|removed| serde_json::json!({ "ok": true, "removed": removed })), - MgmtCommand::RemoteInventory { machine_id } => remote - .inventory(&machine_id) - .await - .map_err(failure_error) - .and_then(|inventory| Ok(serde_json::to_value(inventory)?)), + MgmtCommand::RemoteInventory { machine_id } => match remote.inventory(&machine_id).await { + Ok(inventory) => serde_json::to_value(inventory).map_err(anyhow::Error::from), + Err(failure) => return MgmtResponse::failure(failure), + }, MgmtCommand::RemoteOutputRead { machine_id, run_id, offset, max_bytes, - } => remote + } => match remote .read_output(&machine_id, &run_id, offset, max_bytes) .await - .map_err(failure_error) - .and_then(|data| Ok(serde_json::to_value(data)?)), + { + Ok(data) => serde_json::to_value(data).map_err(anyhow::Error::from), + Err(failure) => return MgmtResponse::failure(failure), + }, _ => return MgmtResponse::error("Not a remote command"), }; match answer { @@ -621,10 +639,6 @@ async fn stream_events( } } -fn failure_error(failure: Failure) -> anyhow::Error { - anyhow::anyhow!("{}", failure.message) -} - /// `remote_access`: `waiting`, then the answer. Closing the connection /// first sends `access.cancel`. async fn stream_access( diff --git a/src/daemon/remote/tests.rs b/src/daemon/remote/tests.rs index da8ab382..860a9b58 100644 --- a/src/daemon/remote/tests.rs +++ b/src/daemon/remote/tests.rs @@ -3,6 +3,7 @@ //! Viewing, and the PR 3 gate, are in `viewing`. mod access; +mod cli; mod control; mod convergence; mod viewing; diff --git a/src/daemon/remote/tests/cli.rs b/src/daemon/remote/tests/cli.rs new file mode 100644 index 00000000..bb19c492 --- /dev/null +++ b/src/daemon/remote/tests/cli.rs @@ -0,0 +1,302 @@ +//! `--machine` end to end: the CLI's remote commands (`cli::remote`) against +//! a real management socket, served by viewer A's link, with target B on the +//! fake relay running the real control executor over its in-memory host. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use arc_swap::ArcSwap; +use serde_json::Value; +use tempfile::TempDir; + +use super::{Daemon, pair, two}; +use crate::application::inventory::{ + EnvironmentRef, ProfileChecks, ProjectRef, RunFacts, RunOrigin, RunProcess, ServiceFacts, + ServiceRef, +}; +use crate::cli::remote::{ + Console, ControlAction, LogsQuery, Machine, Peer, REFUSED, ServiceQuery, control, finish, logs, + machine, status, +}; +use crate::daemon::lifecycle::ShutdownHandle; +use crate::daemon::mgmt_socket::{DaemonPorts, MachineServices, serve}; +use crate::daemon::public_tunnel::PublicTunnel; +use crate::daemon::remote::fake_relay::{FakeCloud, FakeService}; +use crate::daemon::router::RuntimeState; +use crate::infrastructure::inventory::LocalInventory; +use crate::infrastructure::mgmt_client::MgmtSocketClient; +use crate::infrastructure::remote::store::SettingsChange; +use crate::infrastructure::remote::wire::AppPresence; +use crate::infrastructure::runs::output::{ + EndReason, RunEnd, StreamWriter, create_run_dir, publish_end, +}; + +const RUN: &str = "RRRRRRRRRRRRRRRRRRRRRR"; + +fn web() -> FakeService { + let run = RunFacts { + run_id: Some(RUN.into()), + origin: RunOrigin::App, + legacy: false, + has_stream: true, + process: RunProcess::Running, + started_at: "2026-11-09T09:00:00Z".into(), + profile: None, + profile_danger: false, + exit: None, + legacy_id: None, + }; + FakeService { + facts: ServiceFacts { + project: ProjectRef { + id: "app".into(), + name: "App".into(), + }, + environment: EnvironmentRef { + slug: None, + name: "Primary".into(), + primary: true, + branch: None, + }, + service: ServiceRef { + id: "web".into(), + name: "web".into(), + config_rev: "0123456789abcdef".into(), + }, + local_url: "https://web.app.localify".into(), + port: 4100, + reachable: Some(true), + run: Some(run), + public_url: None, + profiles: ProfileChecks { + start: true, + restart: true, + }, + }, + record_names: None, + } +} + +async fn controls(b: &Daemon, on: bool) { + let change = SettingsChange { + share: Some(true), + control: Some(on), + background_starts: Some(false), + }; + b.link.change_settings(change).await.unwrap(); +} + +/// A's management socket, as its daemon serves it. +async fn socket(a: &Daemon) -> (PathBuf, ShutdownHandle, TempDir) { + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join("mgmt.sock"); + let config = dir.path().join("config.toml"); + std::fs::write(&config, "").unwrap(); + let inventory = Arc::new( + LocalInventory::new(config, dir.path().join("data")) + .unwrap() + .with_services_dir(dir.path().join("services")), + ); + let shutdown = ShutdownHandle::default(); + let (reload, _) = tokio::sync::mpsc::channel(1); + let serving = (socket.clone(), shutdown.clone(), a.link.clone()); + tokio::spawn(async move { + let (socket, shutdown, remote) = serving; + let state = Arc::new(ArcSwap::from_pointee(RuntimeState::new(Vec::new()))); + let ports = DaemonPorts { + http: 80, + https: 443, + dns: 1053, + }; + let services = MachineServices { + tunnel: PublicTunnel::new(1), + inventory, + remote, + updates: None, + }; + let _ = serve(socket, state, reload, shutdown, ports, services).await; + }); + for _ in 0..100 { + if socket.exists() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + (socket, shutdown, dir) +} + +/// Runs a CLI command on a blocking thread, as the `localify` process +/// would, and gives back its exit code and what it printed. +async fn cli( + socket: &Path, + json: bool, + command: impl FnOnce(&MgmtSocketClient, &mut Console, Vec>) -> anyhow::Result + + Send + + 'static, +) -> (i32, String, String) { + let socket = socket.to_path_buf(); + tokio::task::spawn_blocking(move || { + let client = MgmtSocketClient::new(&socket); + let mut console = Console { + json, + out: Vec::new(), + err: Vec::new(), + }; + let result = command(&client, &mut console); + let code = finish(&mut console, result).unwrap(); + let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned(); + (code, text(&console.out), text(&console.err)) + }) + .await + .unwrap() +} + +fn mini() -> Peer { + Peer { + id: "mB".into(), + name: "teo-mini".into(), + } +} + +fn web_query() -> ServiceQuery<'static> { + ServiceQuery { + service: "web", + project: None, + env: None, + } +} + +#[tokio::test] +async fn the_cli_reads_and_controls_another_machine_through_the_daemon() { + let cloud = FakeCloud::start().await; + let (a, b) = two(&cloud).await; + pair(&a, &b).await; + controls(&b, true).await; + b.source.set_app(AppPresence::Running); + b.source.host().state().services = vec![web()]; + let run_dir = b.dir.path().join("services/output").join(RUN); + create_run_dir(&run_dir).unwrap(); + let mut writer = StreamWriter::create(&run_dir).unwrap(); + writer.append(b"one\ntwo\nthree\n").unwrap(); + b.source.set_run(RUN, Ok(run_dir.clone())); + let (socket, _shutdown, _dir) = socket(&a).await; + + // `--machine` names B by its name in any case, and A itself locally. + let resolving = socket.clone(); + let (there, here) = tokio::task::spawn_blocking(move || { + let client = MgmtSocketClient::new(&resolving); + ( + machine("TEO-MINI", &client).unwrap(), + machine("mA", &client).unwrap(), + ) + }) + .await + .unwrap(); + assert_eq!((there, here), (Machine::Remote(mini()), Machine::Local)); + + let (code, out, _) = cli(&socket, true, |client, console| { + status(client, &mini(), console) + }) + .await; + assert_eq!(code, 0); + let snapshot: Value = serde_json::from_str(&out).unwrap(); + assert_eq!(snapshot["items"][0]["service"]["id"], "web"); + assert_eq!(snapshot["items"][0]["output"]["runId"], RUN); + + // The last lines, then the cursor to read on from. + let (code, out, err) = cli(&socket, true, |client, console| { + let query = LogsQuery { + service: web_query(), + lines: 2, + follow: false, + cursor: None, + }; + logs(client, &mini(), &query, console) + }) + .await; + assert_eq!(code, 0, "{err}"); + assert_eq!(out, "two\nthree\n"); + assert!(err.ends_with(&format!("Next cursor: {RUN}:14\n")), "{err}"); + + writer.append(b"four\n").unwrap(); + let (code, out, err) = cli(&socket, false, |client, console| { + let cursor = format!("{RUN}:14"); + let query = LogsQuery { + service: web_query(), + lines: 50, + follow: false, + cursor: Some(&cursor), + }; + logs(client, &mini(), &query, console) + }) + .await; + assert_eq!(code, 0, "{err}"); + assert_eq!(out, "four\n"); + assert!(err.ends_with(&format!("Next cursor: {RUN}:19\n")), "{err}"); + + // Following stops once the run ends. + let follow = cli(&socket, false, |client, console| { + let query = LogsQuery { + service: web_query(), + lines: 1, + follow: true, + cursor: None, + }; + logs(client, &mini(), &query, console) + }); + let ending = async { + tokio::time::sleep(Duration::from_millis(500)).await; + writer.append(b"five\n").unwrap(); + publish_end(&run_dir, &RunEnd::now(EndReason::Complete, writer.offset())).unwrap(); + }; + let ((code, out, err), ()) = tokio::time::timeout(Duration::from_secs(20), async { + tokio::join!(follow, ending) + }) + .await + .expect("the follow ended with the run"); + assert_eq!(code, 0, "{err}"); + assert_eq!(out, "four\nfive\n"); + assert!(err.contains("The run of 'web' ended."), "{err}"); + + // A stop B allows goes through, with its progress first. + let (code, out, err) = cli(&socket, false, |client, console| { + control( + client, + &mini(), + ControlAction::Stop, + &web_query(), + None, + console, + ) + }) + .await; + assert_eq!(code, 0, "{err}"); + assert_eq!( + out, + "Stopping 'web' on teo-mini…\n'web' stopped on teo-mini.\n" + ); + assert_eq!(b.source.host().state().stops.len(), 1); + + // With controls off on B, nothing is sent and the refusal says why. + controls(&b, false).await; + let (code, out, _) = cli(&socket, true, |client, console| { + control( + client, + &mini(), + ControlAction::Start, + &web_query(), + None, + console, + ) + }) + .await; + assert_eq!(code, REFUSED); + let refused: Value = serde_json::from_str(&out).unwrap(); + assert_eq!(refused["code"], "control_disabled"); + assert_eq!( + refused["message"], + "teo-mini doesn't allow remote controls." + ); + assert!(b.source.host().state().handed.is_empty()); +} diff --git a/src/desktop/remote.rs b/src/desktop/remote.rs index e1acbf1a..ea96e2f7 100644 --- a/src/desktop/remote.rs +++ b/src/desktop/remote.rs @@ -22,7 +22,8 @@ fn daemon_error(error: DaemonConnectionError) -> anyhow::Error { DaemonConnectionError::NotRunning => anyhow!( "The Localify daemon is not running, and remote machines go through it. Start it in Settings." ), - DaemonConnectionError::ProtocolError(message) => anyhow!(message), + DaemonConnectionError::ProtocolError(message) + | DaemonConnectionError::Remote { message, .. } => anyhow!(message), other => anyhow!("Could not reach the Localify daemon: {other}"), } } diff --git a/src/infrastructure/mgmt_client.rs b/src/infrastructure/mgmt_client.rs index 559b8da4..d770f794 100644 --- a/src/infrastructure/mgmt_client.rs +++ b/src/infrastructure/mgmt_client.rs @@ -14,6 +14,10 @@ use crate::infrastructure::cloud::types::{PublicStatus, PublicUrl}; use crate::infrastructure::launch_sessions::{LaunchSessionDto, LaunchSessionUpdate}; use crate::infrastructure::updates::UpdateStatus; +/// How long a one-shot remote command may take: the daemon waits 30 s for +/// the other machine, after a lease and a session it may have to open. +const REMOTE_ANSWER_WAIT: Duration = Duration::from_secs(45); + /// What the daemon should do after it stops serving. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ShutdownKind { @@ -191,6 +195,36 @@ impl MgmtSocketClient { Ok(response["data"]["removed"].as_bool().unwrap_or(false)) } + /// Another machine's inventory: one snapshot, every page. Opens a + /// session when none is, which takes a few seconds; a refusal carries + /// its code. + pub fn remote_inventory( + &self, + machine_id: &str, + ) -> Result { + let command = serde_json::json!({ "cmd": "remote_inventory", "machineId": machine_id }); + let mut response = self.send_command_within(&command.to_string(), REMOTE_ANSWER_WAIT)?; + Ok(response["data"].take()) + } + + /// One bounded read of a run's output on another machine: an + /// `output.data`, or a refusal with its code (`gone` once the service + /// restarted). + pub fn remote_output_read( + &self, + machine_id: &str, + run_id: &str, + offset: u64, + max_bytes: u32, + ) -> Result { + let command = serde_json::json!({ + "cmd": "remote_output_read", "machineId": machine_id, + "runId": run_id, "offset": offset, "maxBytes": max_bytes, + }); + let mut response = self.send_command_within(&command.to_string(), REMOTE_ANSWER_WAIT)?; + Ok(response["data"].take()) + } + /// A streaming command (`remote_pair`, `remote_events`): one answer per /// line until the daemon or the caller closes it. pub fn remote_stream( @@ -292,6 +326,11 @@ impl MgmtStream { Ok(read_answer(&mut self.reader)?.map(|mut answer| answer["data"].take())) } + /// How long `next_answer` waits for a line; `None` waits forever. + pub fn set_timeout(&self, timeout: Option) -> std::io::Result<()> { + self.reader.get_ref().set_read_timeout(timeout) + } + /// A handle that closes the stream from another thread: shutting it /// down ends what the stream watched, and `next_answer` returns. #[allow(dead_code)] // Used by the desktop through the library crate. @@ -321,6 +360,12 @@ fn read_answer( .as_str() .unwrap_or("unknown error") .to_string(); + if let Some(code) = resp["code"].as_str() { + return Err(DaemonConnectionError::Remote { + code: code.to_string(), + message: msg, + }); + } return Err(DaemonConnectionError::ProtocolError(msg)); } diff --git a/src/main.rs b/src/main.rs index cc371eaf..5ad14040 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,6 +50,10 @@ struct ServiceSelector { /// Project environment (worktree) name or slug. Defaults to the current worktree's. #[arg(long, requires = "service")] env: Option, + + /// Act on the service of another machine of this account, by name or id (`machines` lists them). Without --env, its primary checkout. + #[arg(long, requires = "service", value_name = "MACHINE")] + machine: Option, } /// Launch profile options shared by `dev` and `run`. @@ -83,6 +87,8 @@ impl LaunchProfileFlags { } } +// Parsed once per process: the size of `dev`'s flags costs nothing. +#[allow(clippy::large_enum_variant)] #[derive(Subcommand)] enum Commands { /// Initial setup - configures DNS and prepares Localify for use @@ -309,6 +315,10 @@ enum Commands { )] replace_legacy: Option, + /// Start the service on another machine of this account, by name or id (`machines` lists them). Takes only --project, --env and --profile: that machine decides where it runs. + #[arg(long, requires = "service", value_name = "MACHINE")] + machine: Option, + /// Temporary command override, passed after `--` #[arg(last = true, value_name = "COMMAND")] command: Vec, @@ -913,6 +923,10 @@ enum ServicesCommands { /// Print structured JSON #[arg(long)] json: bool, + + /// Show the services of another machine of this account instead, by name or id (`machines` lists them) + #[arg(long, value_name = "MACHINE")] + machine: Option, }, } @@ -1001,6 +1015,36 @@ fn ensure_rustls_crypto_provider() -> Result<()> { } } +/// A service of another machine, as `--project` and `--env` name it there. +fn service_query<'a>( + name: &'a str, + selector: &'a ServiceSelector, +) -> cli::remote::ServiceQuery<'a> { + cli::remote::ServiceQuery { + service: name, + project: selector.project.as_deref(), + env: selector.env.as_deref(), + } +} + +/// `stop` and `restart` with `--machine`: a control on that machine, or +/// `local` when it names this one. +fn control_on_machine( + machine: &str, + action: cli::remote::ControlAction, + selector: &ServiceSelector, + ctx: &AppContext, + local: impl FnOnce() -> Result<()>, +) -> Result<()> { + let name = selector.service.as_deref().unwrap_or_default(); + cli::remote::run(false, |console| { + let query = service_query(name, selector); + cli::remote::on_machine(machine, &ctx.mgmt_client, local, |peer| { + cli::remote::control(&ctx.mgmt_client, peer, action, &query, None, console) + }) + }) +} + /// Ends this process with a service's exit code, so `localify dev web && next` /// stops where the service failed or was interrupted (130). fn exit_with(code: i32) -> Result<()> { @@ -1291,7 +1335,21 @@ fn main() -> Result<()> { } Commands::Services { command } => match command { ServicesCommands::List { json } => cli::services::list(&ctx, json), - ServicesCommands::Status { json } => cli::background::status(json), + ServicesCommands::Status { + json, + machine: Some(machine), + } => cli::remote::run(json, |console| { + cli::remote::on_machine( + &machine, + &ctx.mgmt_client, + || cli::background::status(json), + |peer| cli::remote::status(&ctx.mgmt_client, peer, console), + ) + }), + ServicesCommands::Status { + json, + machine: None, + } => cli::background::status(json), }, Commands::Get { service, @@ -1324,6 +1382,78 @@ fn main() -> Result<()> { &ctx, &paths, )?), + Commands::Dev { + machine: Some(machine), + service, + domain, + project, + env, + launch_profile, + in_app, + detach, + replace, + launch_id, + remote_launch, + launch_expires, + expect_rev, + request, + replace_legacy, + command, + } => { + let given: Vec<&str> = [ + ("a command after --", !command.is_empty()), + ("--detach", detach), + ("--in-app", in_app), + ("--env-file", !launch_profile.env_file.is_empty()), + ( + "--confirm-profile", + launch_profile.confirm_profile.is_some(), + ), + ("--no-masking", launch_profile.no_masking), + ("--domain", domain.is_some()), + ("--replace", replace.is_some()), + ("--launch-id", launch_id.is_some()), + ("--remote-launch", remote_launch.is_some()), + ("--launch-expires", launch_expires.is_some()), + ("--expect-rev", expect_rev.is_some()), + ("--request", request.is_some()), + ("--replace-legacy", replace_legacy.is_some()), + ] + .into_iter() + .filter_map(|(option, given)| given.then_some(option)) + .collect(); + // `requires = "service"` makes clap ask for it. + let service = service.unwrap_or_default(); + let profile = launch_profile.profile.as_deref(); + cli::remote::run(false, |console| { + cli::remote::only_target_options(&given)?; + // This machine runs it as the target would: in the app. + let local = || { + cli::background::start_in_app( + cli::services::RunTarget { + service: Some(&service), + project: project.as_deref(), + environment: env.as_deref(), + init_domain: None, + }, + profile, + cli::services::Replace::No, + config_path, + &ctx, + &paths.data_dir, + ) + }; + let query = cli::remote::ServiceQuery { + service: &service, + project: project.as_deref(), + env: env.as_deref(), + }; + cli::remote::on_machine(&machine, &ctx.mgmt_client, local, |peer| { + let action = cli::remote::ControlAction::Start; + cli::remote::control(&ctx.mgmt_client, peer, action, &query, profile, console) + }) + }) + } Commands::Dev { detach: true, service, @@ -1478,22 +1608,50 @@ fn main() -> Result<()> { cli::start::execute(foreground, cli.verbose, config_path, &paths, &config.daemon) } Commands::Stop { service } => match service.service { - Some(name) => cli::background::stop( - &name, - service.project.as_deref(), - service.env.as_deref(), - &ctx, - ), + Some(ref name) => { + let local = || { + cli::background::stop( + name, + service.project.as_deref(), + service.env.as_deref(), + &ctx, + ) + }; + match service.machine.as_deref() { + Some(machine) => control_on_machine( + machine, + cli::remote::ControlAction::Stop, + &service, + &ctx, + local, + ), + None => local(), + } + } None => cli::stop::execute(&ctx, &paths, &config.daemon), }, Commands::Restart { service } => match service.service { - Some(name) => cli::background::restart( - &name, - service.project.as_deref(), - service.env.as_deref(), - config_path, - &ctx, - ), + Some(ref name) => { + let local = || { + cli::background::restart( + name, + service.project.as_deref(), + service.env.as_deref(), + config_path, + &ctx, + ) + }; + match service.machine.as_deref() { + Some(machine) => control_on_machine( + machine, + cli::remote::ControlAction::Restart, + &service, + &ctx, + local, + ), + None => local(), + } + } None => cli::restart::execute(cli.verbose, config_path, &ctx, &paths, &config.daemon), }, Commands::Status => cli::status::execute(&ctx, &config.daemon), @@ -1505,17 +1663,35 @@ fn main() -> Result<()> { clear, follow, } => match service.service { - Some(name) => cli::background::logs( - cli::background::LogsArgs { - service: &name, - project: service.project.as_deref(), - environment: service.env.as_deref(), - lines, - follow, - cursor: cursor.as_deref(), - }, - &ctx, - ), + Some(ref name) => { + let local = || { + cli::background::logs( + cli::background::LogsArgs { + service: name, + project: service.project.as_deref(), + environment: service.env.as_deref(), + lines, + follow, + cursor: cursor.as_deref(), + }, + &ctx, + ) + }; + match service.machine.as_deref() { + Some(machine) => cli::remote::run(false, |console| { + let query = cli::remote::LogsQuery { + service: service_query(name, &service), + lines, + follow, + cursor: cursor.as_deref(), + }; + cli::remote::on_machine(machine, &ctx.mgmt_client, local, |peer| { + cli::remote::logs(&ctx.mgmt_client, peer, &query, console) + }) + }), + None => local(), + } + } None => cli::logs::execute(lines, clear, follow, &paths), }, Commands::Reload => { diff --git a/tests/remote_cli.rs b/tests/remote_cli.rs new file mode 100644 index 00000000..62c0985e --- /dev/null +++ b/tests/remote_cli.rs @@ -0,0 +1,50 @@ +//! `--machine` as the `localify` binary parses it (docs/remote-machines.md, +//! "CLI"): `dev` on another machine refuses every option but `--project`, +//! `--env` and `--profile` before it asks the daemon anything. + +use std::process::{Command, Output}; + +fn localify(args: &[&str]) -> Output { + let dir = tempfile::tempdir().unwrap(); + Command::new(env!("CARGO_BIN_EXE_localify")) + .arg("--config") + .arg(dir.path().join("config.toml")) + .args(args) + .env("HOME", dir.path()) + .output() + .unwrap() +} + +#[test] +fn dev_on_another_machine_refuses_every_other_option_with_exit_2() { + for (extra, named) in [ + (vec!["--detach"], "--detach"), + (vec!["--in-app"], "--in-app"), + (vec!["--env-file", ".env"], "--env-file"), + (vec!["--confirm-profile", "prod"], "--confirm-profile"), + (vec!["--domain", "web.localify"], "--domain"), + (vec!["--", "pnpm", "dev"], "a command after --"), + ] { + let mut args = vec!["dev", "web", "--machine", "teo-mini"]; + args.extend(extra); + + let output = localify(&args); + + assert_eq!(output.status.code(), Some(2), "{args:?}"); + // Not a terminal: one JSON document with the code. + let refused: serde_json::Value = serde_json::from_slice(&output.stdout) + .unwrap_or_else(|_| panic!("{}", String::from_utf8_lossy(&output.stdout))); + assert_eq!(refused["outcome"], "refused"); + assert_eq!(refused["code"], "refused_argument"); + let message = refused["message"].as_str().unwrap(); + assert!(message.ends_with(&format!("Remove {named}.")), "{message}"); + } +} + +#[test] +fn machine_needs_a_service() { + let output = localify(&["stop", "--machine", "teo-mini"]); + + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("")); +} From 69ae848ce49d991a7778ab789a32385536fc0c38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Mon, 9 Nov 2026 22:22:22 +0100 Subject: [PATCH 2/3] fix: keep --machine and machine on the machine they name A Codex review of the remote CLI and MCP found four ways a request could act on the wrong run or the wrong machine, or say less than the contract asks: - MCP tools without a `machine` argument ignored one and ran here, in the server's folder. They now refuse it before building or running anything. - A legacy run that had already stopped blocked a fresh start the target allowed. Only a live legacy run is refused before sending; otherwise the target's `controls` decide. - `logs --machine --follow` stopped when the service restarted. On `gone`, it now reads the service's current run from the target's snapshot and follows it from offset 0, and a restart racing the first read is read the same way. - A `conflict` printed only "B changed in the meantime." It now prints the service's fresh state with it, in text and JSON, still exits 2, and never resends the control. docs/remote-machines.md says `dev` on this machine's own id behaves as `dev --in-app`, and records the four behaviours above. --- docs/remote-machines.md | 7 +- src/cli/mcp/mod.rs | 46 +++++++++++++ src/cli/mcp/tools.rs | 5 ++ src/cli/remote/control.rs | 105 ++++++++++++++++++++++++++-- src/cli/remote/logs.rs | 86 ++++++++++++++++++----- src/daemon/remote/tests/cli.rs | 122 ++++++++++++++++++++++++++++++++- 6 files changed, 342 insertions(+), 29 deletions(-) diff --git a/docs/remote-machines.md b/docs/remote-machines.md index 90c80245..7a53e1d8 100644 --- a/docs/remote-machines.md +++ b/docs/remote-machines.md @@ -809,18 +809,17 @@ localify stop --machine [--project ] [--env ] localify restart --machine [--project ] [--env ] ``` -- **Resolving `--machine`:** an exact machine id; otherwise an exact name, ignoring case, among the active machines of the roster. Active names are unique, since a same-name sign-in replaces the older machine; a name that still matches two, differing only in case, is an error that lists both with their ids. A name of no active machine lists the roster. This machine's own id or name acts locally, as without `--machine`. +- **Resolving `--machine`:** an exact machine id; otherwise an exact name, ignoring case, among the active machines of the roster. Active names are unique, since a same-name sign-in replaces the older machine; a name that still matches two, differing only in case, is an error that lists both with their ids. A name of no active machine lists the roster. This machine's own id or name acts locally; `dev` behaves as `dev --in-app`, and the other commands behave as without `--machine`. - **Resolving a service:** there is no folder to read on another machine, so a service name must be unique on the target, or come with `--project`, and `--env` names a non-primary checkout. An ambiguous name lists the matches. - **What `--machine` refuses:** with `dev`, every option but `--project`, `--env` and `--profile`: no command after `--`, no `--detach`, `--in-app`, `--env-file`, `--confirm-profile` or `--domain`. The target decides where the service runs. - **Launch flags:** `--launch-id`, `--launch-expires`, `--remote-launch`, `--expect-rev`, `--request` and `--replace-legacy` are hidden flags for dispatchers, documented here and not in `--help`. -- **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2. `unknown` is progress, "Outcome unknown. Checking B…", never where a control stops. A control the snapshot already refuses (its `controls`, or a legacy run, which the app relaunches after a confirmation) is refused the same way without being sent. A run that failed exits with code 1. With JSON, progress goes to stderr, so stdout holds one document: `{outcome, code, message, …}`. `logs` prints plain lines, as without `--machine`, and its next cursor on stderr. -- **This machine:** its own id or name acts locally, `dev` as `--in-app` does, since the options it takes are the ones `--in-app` takes. +- **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2; a `conflict` prints "B changed in the meantime." with the service's fresh state, and the control is never sent again. `unknown` is progress, "Outcome unknown. Checking B…", never where a control stops. A control the snapshot already refuses (its `controls`, or a live legacy run, which the app relaunches after a confirmation) is refused the same way without being sent. A run that failed exits with code 1. With JSON, progress goes to stderr, so stdout holds one document: `{outcome, code, message, …}`. `logs` prints plain lines, as without `--machine`, and its next cursor on stderr. When the service restarts during a read or `--follow` (`gone`), it reads the service's current run from offset 0. - `pair` and `remove` need a terminal: an agent cannot pair or remove machines. ## MCP - `list_machines`: the roster with states, read-only. -- An optional `machine` argument on `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` and `service_restart`, and on no other tool. With it, a tool ignores `cwd`. +- An optional `machine` argument on `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` and `service_restart`, and on no other tool. With it, a tool ignores `cwd`. Any other tool given `machine` fails before it runs anything, rather than acting on this machine. - With `machine`, `service_start` takes only `service`, `project`, `env` and `profile`. `background`, `env_files`, `confirm_profile`, `command` and `domain` make it fail with an error that says the target decides how its services start. It never creates a project. - `service_logs` with `machine` returns a cursor `:`. `list_services` and `service_status` with `machine` both give the target's snapshot (`services status --machine`). - Pairing, unpairing, settings and removal have no tool. Like signing in (ADR 0018), they stay a person's decision. diff --git a/src/cli/mcp/mod.rs b/src/cli/mcp/mod.rs index 81dbcaed..07c92bc9 100644 --- a/src/cli/mcp/mod.rs +++ b/src/cli/mcp/mod.rs @@ -174,6 +174,20 @@ fn remote_hint(text: &str) -> Option { } fn prepare(tool: &Tool, args: &ToolArgs) -> Result<(Vec, Option)> { + // A tool without `machine` would act on this machine instead: refuse it + // before building or running anything (docs/remote-machines.md, "MCP"). + if args.has("machine") && !tool.params.iter().any(|param| param.name == "machine") { + let remote: Vec<&str> = TOOLS + .iter() + .filter(|tool| tool.params.iter().any(|param| param.name == "machine")) + .map(|tool| tool.name) + .collect(); + bail!( + "{} acts on this machine only and takes no machine. Only {} act on another machine.", + tool.name, + remote.join(", ") + ); + } let argv = (tool.build)(args)?; // A tool acting on another machine has no folder of this one to read. let here = args.string("machine")?.is_none(); @@ -398,6 +412,38 @@ mod tests { assert_eq!(argv, ["logs", "web", "--machine=teo-mini"]); } + #[test] + fn a_tool_without_machine_refuses_one_instead_of_acting_here() { + let local_only: Vec<&Tool> = TOOLS + .iter() + .filter(|tool| !tool.params.iter().any(|param| param.name == "machine")) + .collect(); + assert!(local_only.len() > 30, "{}", local_only.len()); + + for tool in local_only { + let response = handle_line( + &request( + "tools/call", + json!({ + "name": tool.name, + "arguments": { "machine": "B", "cwd": "/", "command": ["true"] }, + }), + ), + &runner(), + ) + .unwrap(); + + let text = response["result"]["content"][0]["text"].as_str().unwrap(); + assert_eq!(response["result"]["isError"], true, "{}: {text}", tool.name); + assert!( + text.starts_with(&format!("{} acts on this machine only", tool.name)) + && text.contains("service_status"), + "{}: {text}", + tool.name + ); + } + } + #[test] fn an_error_from_another_machine_reaches_the_agent_with_its_code_and_what_to_do() { let refused = "{\n \"outcome\": \"refused\",\n \"code\": \"control_disabled\",\n \"message\": \"teo-mini doesn't allow remote controls.\"\n}"; diff --git a/src/cli/mcp/tools.rs b/src/cli/mcp/tools.rs index eb8b9c88..ef0b8d69 100644 --- a/src/cli/mcp/tools.rs +++ b/src/cli/mcp/tools.rs @@ -1072,6 +1072,11 @@ impl ToolArgs { } } + /// Whether the call passed `name` with a value, of any type. + pub fn has(&self, name: &str) -> bool { + !matches!(self.values.get(name), None | Some(Value::Null)) + } + pub fn string(&self, name: &str) -> Result> { match self.values.get(name) { None | Some(Value::Null) => Ok(None), diff --git a/src/cli/remote/control.rs b/src/cli/remote/control.rs index f16476fe..e2256c61 100644 --- a/src/cli/remote/control.rs +++ b/src/cli/remote/control.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::inventory::{Item, ServiceQuery, Snapshot, fetch, find, write_item}; -use super::{Console, LOST, Peer, Refusal, remote_error, viewer_message}; +use super::{Console, LOST, Peer, REFUSED, Refusal, remote_error, viewer_message}; use crate::application::ports::DaemonConnectionError; use crate::infrastructure::mgmt_client::{MgmtSocketClient, MgmtStream}; use crate::infrastructure::remote::wire::{ @@ -120,10 +120,11 @@ fn timed_out(error: &anyhow::Error) -> bool { /// checks the target makes, with the code it would give. fn allowed(item: &Item, action: ControlAction, machine: &str) -> Result<()> { let service = &item.service.name; - let legacy = item.run.as_ref().is_some_and(|run| run.legacy); + // A live legacy run is relaunched from the app, after a confirmation. One + // that ended is only a record: the target's `controls` say what it allows. + let live_legacy = item.process == "running" && item.run.as_ref().is_some_and(|run| run.legacy); let code = match item.controls.get(action.as_str()) { - // A legacy run is relaunched from the app, after a confirmation. - Some(state) if state.allowed && legacy => "legacy_run", + Some(state) if state.allowed && live_legacy => "legacy_run", Some(state) if !state.allowed => state.code.as_deref().unwrap_or("conflict"), _ => return Ok(()), }; @@ -277,7 +278,11 @@ fn report( .. } => { let code = code.unwrap_or_else(|| outcome_name(outcome).to_string()); - return Err(anyhow!(Refusal::from_target(&code, &message, machine))); + let refusal = Refusal::from_target(&code, &message, machine); + if code == "conflict" { + return conflict(refusal, machine, console, fresh); + } + return Err(anyhow!(refusal)); } Ended::Result { outcome, @@ -319,6 +324,36 @@ fn report( Ok(exit) } +/// `conflict`: the target changed since the snapshot the control expected. +/// Says so with the service as it is now, and exits with [`REFUSED`]. The +/// control is never sent again. +fn conflict( + refusal: Refusal, + machine: &str, + console: &mut Console, + fresh: impl FnOnce() -> Result<(Item, Value)>, +) -> Result { + let now = fresh(); + if console.json { + let mut document = serde_json::to_value(&refusal)?; + document["outcome"] = json!("refused"); + if let Ok((_, raw)) = &now { + document["status"] = raw.clone(); + } + console.json(&document)?; + return Ok(REFUSED); + } + refusal.print(console)?; + match now { + Ok((item, _)) => write_item(&mut console.out, &item, machine)?, + Err(error) => writeln!( + console.err, + "Its current state could not be read: {error:#}" + )?, + } + Ok(REFUSED) +} + /// An outcome the target could not tell: says so, then shows the service /// as it is now, and exits with [`LOST`]. The control is never sent again. fn lost( @@ -387,7 +422,6 @@ fn fresh( #[cfg(test)] mod tests { use super::*; - use crate::cli::remote::REFUSED; use crate::cli::remote::inventory::tests::item; fn peer() -> Peer { @@ -551,6 +585,46 @@ mod tests { assert_eq!(printed["status"]["process"], "running"); } + #[test] + fn a_conflict_prints_the_fresh_state_and_exits_2() { + let events = || { + vec![ + json!({ "event": "sent", "requestId": "q" }), + json!({ + "event": "result", "outcome": "conflict", "code": "conflict", + "message": "The run changed.", "runId": null, + }), + ] + }; + + let mut human = console(false); + assert_eq!( + run(events(), ControlAction::Restart, &mut human).unwrap(), + REFUSED + ); + assert!( + text(&human.err).starts_with("teo-mini changed in the meantime.\n"), + "{}", + text(&human.err) + ); + assert!( + text(&human.out).contains("APP / web\n Running, in the app"), + "{}", + text(&human.out) + ); + + let mut json = console(true); + assert_eq!( + run(events(), ControlAction::Restart, &mut json).unwrap(), + REFUSED + ); + let printed: Value = serde_json::from_slice(&json.out).unwrap(); + assert_eq!(printed["outcome"], "refused"); + assert_eq!(printed["code"], "conflict"); + assert_eq!(printed["message"], "teo-mini changed in the meantime."); + assert_eq!(printed["status"]["process"], "running"); + } + #[test] fn a_failed_start_exits_1_with_the_targets_last_lines() { let mut console = console(false); @@ -604,4 +678,23 @@ mod tests { let legacy = web(json!({ "restart": { "allowed": true } }), true); assert_eq!(refused(&legacy, ControlAction::Restart).code, "legacy_run"); } + + #[test] + fn a_legacy_run_that_ended_does_not_block_a_fresh_start() { + let mut value = item("app", None, "web"); + value["process"] = json!("stopped"); + value["owner"] = json!(null); + value["run"]["legacy"] = json!(true); + value["run"]["runId"] = json!(null); + value["controls"] = json!({ + "start": { "allowed": true }, + "stop": { "allowed": false, "code": "conflict" }, + "restart": { "allowed": false, "code": "conflict" }, + }); + let stopped: Item = serde_json::from_value(value).unwrap(); + + assert!(allowed(&stopped, ControlAction::Start, "teo-mini").is_ok()); + let error = allowed(&stopped, ControlAction::Stop, "teo-mini").unwrap_err(); + assert_eq!(error.downcast_ref::().unwrap().code, "conflict"); + } } diff --git a/src/cli/remote/logs.rs b/src/cli/remote/logs.rs index 42eb203b..fa7c7396 100644 --- a/src/cli/remote/logs.rs +++ b/src/cli/remote/logs.rs @@ -51,30 +51,54 @@ pub fn logs( let mut reader = Reader { client, peer, - run_id: &run_id, - service: &item.service.name, + query: &query.service, + run_id, + service: item.service.name.clone(), console, }; - let mut offset = match cursor { - Some(cursor) if cursor.run_id == run_id => reader.read_on(cursor.offset)?, + let first = match &cursor { + Some(cursor) if cursor.run_id == reader.run_id => reader.read_on(cursor.offset), Some(_) => { reader.note(&format!( "'{}' restarted since that cursor: reading its current run from the start.", - item.service.name + reader.service ))?; - reader.read_on(0)? + reader.read_on(0) } - None => reader.tail(query.lines)?, + None => reader.tail(query.lines), + }; + // The service restarted between the snapshot and the read: its new run + // is read as a cursor of another run would be. + let mut offset = match first { + Err(error) if is_gone(&error) => { + reader.move_to_current_run()?; + match cursor { + Some(_) => reader.read_on(0)?, + None => reader.tail(query.lines)?, + } + } + other => other?, }; if query.follow { offset = reader.follow(offset)?; } if query.cursor.is_some() || reader.console.json { - writeln!(reader.console.err, "\nNext cursor: {run_id}:{offset}")?; + writeln!( + reader.console.err, + "\nNext cursor: {}:{offset}", + reader.run_id + )?; } Ok(0) } +/// `gone`: the run is no longer the service's last run. +fn is_gone(error: &anyhow::Error) -> bool { + error + .downcast_ref::() + .is_some_and(|refusal| refusal.code == "gone") +} + /// Where a read goes on from: `:`. #[derive(Debug, PartialEq, Eq)] struct Cursor { @@ -122,8 +146,10 @@ fn readable_run(item: &Item, machine: &str) -> Result { struct Reader<'a, O, E> { client: &'a MgmtSocketClient, peer: &'a Peer, - run_id: &'a str, - service: &'a str, + query: &'a ServiceQuery<'a>, + /// The run being read; it moves to the next run when the service restarts. + run_id: String, + service: String, console: &'a mut Console, } @@ -136,7 +162,7 @@ impl Reader<'_, O, E> { fn read(&self, offset: u64) -> Result { let value = self .client - .remote_output_read(&self.peer.id, self.run_id, offset, MAX_READ_BYTES) + .remote_output_read(&self.peer.id, &self.run_id, offset, MAX_READ_BYTES) .map_err(|error| self.restarted(remote_error(error, self.peer)))?; data(value) } @@ -147,7 +173,7 @@ impl Reader<'_, O, E> { Some(refusal) if refusal.code == "gone" => anyhow!(Refusal::new( "gone", format!( - "'{}' restarted on {}. Read its output again without --cursor.", + "'{}' restarted on {} again. Read its output again.", self.service, self.peer.name ), )), @@ -155,6 +181,30 @@ impl Reader<'_, O, E> { } } + /// After `gone`: moves to the service's current run, as the target's + /// snapshot shows it, to read it from offset 0. + fn move_to_current_run(&mut self) -> Result<()> { + let (snapshot, _) = fetch(self.client, self.peer)?; + let items = snapshot.shared_items(self.peer)?; + let (item, _) = find(&items, self.query, &self.peer.name)?; + let run_id = readable_run(item, &self.peer.name)?; + if run_id == self.run_id { + return Err(anyhow!(Refusal::new( + "gone", + format!( + "'{}' restarted on {}, and its new run isn't shown yet. Read its output again.", + self.service, self.peer.name + ), + ))); + } + self.note(&format!( + "'{}' restarted on {}: reading its new run from the start.", + self.service, self.peer.name + ))?; + self.run_id = run_id; + Ok(()) + } + /// Prints from `offset` until caught up, the run ended, or /// [`READ_BUDGET`] was read; returns where it stopped. fn read_on(&mut self, mut offset: u64) -> Result { @@ -202,7 +252,8 @@ impl Reader<'_, O, E> { Ok(chunk.next) } - /// Prints new lines as they come, until the run ends or restarts. + /// Prints new lines as they come, until the run ends. When the service + /// restarts, follows its new run from offset 0. fn follow(&mut self, mut offset: u64) -> Result { let mut follow = self.open_follow(json!({ "offset": offset }))?; loop { @@ -216,11 +267,10 @@ impl Reader<'_, O, E> { } } Followed::Ended(refusal) if refusal.code == "gone" => { - self.note(&format!( - "'{}' restarted on {}.", - self.service, self.peer.name - ))?; - return Ok(offset); + drop(follow); + self.move_to_current_run()?; + offset = 0; + follow = self.open_follow(json!({ "offset": offset }))?; } Followed::Ended(refusal) => return Err(anyhow!(refusal)), Followed::Closed => return Ok(offset), diff --git a/src/daemon/remote/tests/cli.rs b/src/daemon/remote/tests/cli.rs index bb19c492..3d53fed1 100644 --- a/src/daemon/remote/tests/cli.rs +++ b/src/daemon/remote/tests/cli.rs @@ -22,7 +22,8 @@ use crate::cli::remote::{ use crate::daemon::lifecycle::ShutdownHandle; use crate::daemon::mgmt_socket::{DaemonPorts, MachineServices, serve}; use crate::daemon::public_tunnel::PublicTunnel; -use crate::daemon::remote::fake_relay::{FakeCloud, FakeService}; +use crate::daemon::remote::fake_relay::{FakeCloud, FakeService, FakeSource}; +use crate::daemon::remote::local::RunLookup; use crate::daemon::router::RuntimeState; use crate::infrastructure::inventory::LocalInventory; use crate::infrastructure::mgmt_client::MgmtSocketClient; @@ -33,6 +34,8 @@ use crate::infrastructure::runs::output::{ }; const RUN: &str = "RRRRRRRRRRRRRRRRRRRRRR"; +/// The run that replaces [`RUN`] when the service restarts. +const NEXT_RUN: &str = "SSSSSSSSSSSSSSSSSSSSSS"; fn web() -> FakeService { let run = RunFacts { @@ -300,3 +303,120 @@ async fn the_cli_reads_and_controls_another_machine_through_the_daemon() { ); assert!(b.source.host().state().handed.is_empty()); } + +/// B with `web` running as [`RUN`], whose output holds `output`, and A's +/// management socket. +async fn web_on_b( + cloud: &FakeCloud, + output: &[u8], +) -> (Daemon, Daemon, PathBuf, ShutdownHandle, TempDir) { + let (a, b) = two(cloud).await; + pair(&a, &b).await; + controls(&b, true).await; + b.source.set_app(AppPresence::Running); + b.source.host().state().services = vec![web()]; + let run_dir = b.dir.path().join("services/output").join(RUN); + create_run_dir(&run_dir).unwrap(); + StreamWriter::create(&run_dir) + .unwrap() + .append(output) + .unwrap(); + b.source.set_run(RUN, Ok(run_dir)); + let (socket, shutdown, dir) = socket(&a).await; + (a, b, socket, shutdown, dir) +} + +/// `web` restarts on B, whose state is in `dir`: [`NEXT_RUN`] replaces +/// [`RUN`], with `output`, and ends. `RUN` is gone, with its folder. +fn restart_on(source: &FakeSource, dir: &Path, output: &[u8]) { + let next_dir = dir.join("services/output").join(NEXT_RUN); + create_run_dir(&next_dir).unwrap(); + let mut writer = StreamWriter::create(&next_dir).unwrap(); + writer.append(output).unwrap(); + publish_end( + &next_dir, + &RunEnd::now(EndReason::Complete, writer.offset()), + ) + .unwrap(); + source.set_run(NEXT_RUN, Ok(next_dir)); + if let Some(run) = source.host().state().services[0].facts.run.as_mut() { + run.run_id = Some(NEXT_RUN.into()); + } + // The next run of a service deletes the last one's folder. + std::fs::remove_dir_all(dir.join("services/output").join(RUN)).unwrap(); + source.set_run(RUN, Err(RunLookup::Gone)); +} + +fn follow_web(lines: usize) -> LogsQuery<'static> { + LogsQuery { + service: web_query(), + lines, + follow: true, + cursor: None, + } +} + +#[tokio::test] +async fn following_goes_on_with_the_run_that_replaces_a_restarted_one() { + let cloud = FakeCloud::start().await; + let (_a, b, socket, _shutdown, _dir) = web_on_b(&cloud, b"one\n").await; + + let follow = cli(&socket, true, |client, console| { + logs(client, &mini(), &follow_web(5), console) + }); + let restarting = async { + tokio::time::sleep(Duration::from_millis(500)).await; + restart_on(&b.source, b.dir.path(), b"new one\nnew two\n"); + }; + let ((code, out, err), ()) = tokio::time::timeout(Duration::from_secs(20), async { + tokio::join!(follow, restarting) + }) + .await + .expect("the follow ended with the new run"); + + assert_eq!(code, 0, "{err}"); + assert_eq!(out, "one\nnew one\nnew two\n"); + assert!( + err.contains("'web' restarted on teo-mini: reading its new run from the start."), + "{err}" + ); + assert!(err.contains("The run of 'web' ended."), "{err}"); + assert!( + err.ends_with(&format!("Next cursor: {NEXT_RUN}:16\n")), + "{err}" + ); +} + +#[tokio::test] +async fn a_restart_between_the_snapshot_and_the_first_read_reads_the_new_run() { + let cloud = FakeCloud::start().await; + let (_a, b, socket, _shutdown, _dir) = web_on_b(&cloud, b"one\n").await; + // The CLI's snapshot still shows RUN; once it is built, web restarts. + b.source.set_build_time(300); + let built = b.source.builds(); + let (watcher, dir) = (b.source.clone(), b.dir.path().to_path_buf()); + let restarting = tokio::spawn(async move { + while watcher.builds() == built { + tokio::time::sleep(Duration::from_millis(5)).await; + } + tokio::time::sleep(Duration::from_millis(50)).await; + restart_on(&watcher, &dir, b"new\n"); + }); + + let (code, out, err) = cli(&socket, true, |client, console| { + logs(client, &mini(), &follow_web(5), console) + }) + .await; + restarting.await.unwrap(); + + assert_eq!(code, 0, "{err}"); + assert_eq!(out, "new\n"); + assert!( + err.contains("'web' restarted on teo-mini: reading its new run from the start."), + "{err}" + ); + assert!( + err.ends_with(&format!("Next cursor: {NEXT_RUN}:4\n")), + "{err}" + ); +} From f2b6842391f1dc8a01e72d6384501409d50701a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Mon, 9 Nov 2026 22:27:07 +0100 Subject: [PATCH 3/3] fix(remote): read a run that replaced the snapshot's from its start, and keep the watch through a conflict's report After a restart between the snapshot and the first read, `logs --machine` without a cursor tailed the new run, so a run longer than --lines lost its first lines although the note said it was read from the start. And the control's watch was dropped before the report fetched the fresh state, so a conflict's state could need a new handshake or go missing. --- src/cli/remote/control.rs | 5 ++++- src/cli/remote/logs.rs | 7 +++---- src/daemon/remote/tests/cli.rs | 9 +++++---- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/cli/remote/control.rs b/src/cli/remote/control.rs index e2256c61..1353f889 100644 --- a/src/cli/remote/control.rs +++ b/src/cli/remote/control.rs @@ -70,8 +70,11 @@ pub fn control( .map_err(|error| remote_error(error, peer))?; let events = std::iter::from_fn(|| stream.next_answer().transpose()); let ended = follow(events, &asked, console)?; + // The watch keeps the session open until the report has fetched the fresh + // state a conflict or a lost outcome prints, so that needs no new handshake. + let reported = report(ended, &asked, console, || fresh(client, peer, query)); drop(watch); - report(ended, &asked, console, || fresh(client, peer, query)) + reported } /// What a control was asked for, to say what happens to it. diff --git a/src/cli/remote/logs.rs b/src/cli/remote/logs.rs index fa7c7396..dfcba326 100644 --- a/src/cli/remote/logs.rs +++ b/src/cli/remote/logs.rs @@ -71,11 +71,10 @@ pub fn logs( // is read as a cursor of another run would be. let mut offset = match first { Err(error) if is_gone(&error) => { + // Its new run started after the snapshot: everything it printed + // is new to this reader, so it is read from its first byte. reader.move_to_current_run()?; - match cursor { - Some(_) => reader.read_on(0)?, - None => reader.tail(query.lines)?, - } + reader.read_on(0)? } other => other?, }; diff --git a/src/daemon/remote/tests/cli.rs b/src/daemon/remote/tests/cli.rs index 3d53fed1..803b034b 100644 --- a/src/daemon/remote/tests/cli.rs +++ b/src/daemon/remote/tests/cli.rs @@ -400,23 +400,24 @@ async fn a_restart_between_the_snapshot_and_the_first_read_reads_the_new_run() { tokio::time::sleep(Duration::from_millis(5)).await; } tokio::time::sleep(Duration::from_millis(50)).await; - restart_on(&watcher, &dir, b"new\n"); + restart_on(&watcher, &dir, b"new\nsecond\nthird\n"); }); let (code, out, err) = cli(&socket, true, |client, console| { - logs(client, &mini(), &follow_web(5), console) + // Fewer lines than the new run printed: it is still read from its start. + logs(client, &mini(), &follow_web(1), console) }) .await; restarting.await.unwrap(); assert_eq!(code, 0, "{err}"); - assert_eq!(out, "new\n"); + assert_eq!(out, "new\nsecond\nthird\n"); assert!( err.contains("'web' restarted on teo-mini: reading its new run from the start."), "{err}" ); assert!( - err.ends_with(&format!("Next cursor: {NEXT_RUN}:4\n")), + err.ends_with(&format!("Next cursor: {NEXT_RUN}:17\n")), "{err}" ); }