From bb629417a0585d150609a1447553b0be1a87b795 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 01:12:20 -0600 Subject: [PATCH] =?UTF-8?q?feat(fleet-agent):=20fleet=20shell=20--target?= =?UTF-8?q?=20actions=20=E2=80=94=20dispatch=20through=20placement=20and?= =?UTF-8?q?=20wait=20for=20the=20result=20(#12236=20item=206)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `fleet shell` gains a fourth target beside laptop/codespace/local: `--target actions [--repo OWNER/NAME]` sends the command to a GitHub Actions surface through placement (fleet queue dispatch) and waits on the placement session until it is terminal. - Target::Actions(repo): the repo comes from --repo, else the checkout's origin remote; auto never picks actions. - The plan is the dispatch call itself, so --print shows exactly what will be submitted; run() drives it with the patient call (dispatch changes state on the far side), then polls `queue session result` every 15s up to --timeout (default 3600). - The verdict prints as a record (handle, state, run_url) and the exit code is 0 when the run succeeded, 1 when it failed or was cancelled (new Done::PrintedCode). A wait that expires is a Down error naming the reconnect command and the handle. - --detach dispatches and prints the handle without waiting. Interactive use, --build and --cwd are refused with reasons: there is no shell, host build lock or caller cwd on a runner. - `fleet shell targets` lists actions, reachable when the surface registry holds a github-actions or blacksmith surface. Tests: 6 new (plan shape + refusals, flag/origin resolution, the dispatch-wait-verdict flow for success and failure, detach, expired wait, targets listing); fleet-agent suite 89 passed. Live acceptance (worktree-built binary): `fleet shell --target actions --repo dezren39/fleet -- echo lane-ih-smoke` dispatched to the fleet-forks surface and reported state=succeeded; the run (developing-today-forks/fleet actions run 45128891905) completed with conclusion success. --- pkgs/fleet/crates/fleet-agent/src/lib.rs | 4 + pkgs/fleet/crates/fleet-agent/src/shell.rs | 241 +++++++++++++++- pkgs/fleet/crates/fleet-agent/src/tests.rs | 320 ++++++++++++++++++++- 3 files changed, 544 insertions(+), 21 deletions(-) diff --git a/pkgs/fleet/crates/fleet-agent/src/lib.rs b/pkgs/fleet/crates/fleet-agent/src/lib.rs index 30e93426e9..4e85a9debc 100644 --- a/pkgs/fleet/crates/fleet-agent/src/lib.rs +++ b/pkgs/fleet/crates/fleet-agent/src/lib.rs @@ -556,6 +556,10 @@ pub fn run_shell(config: &Config, args: &[String]) -> i32 { print(&v); EXIT_OK } + Ok(shell::Done::PrintedCode(v, code)) => { + print(&v); + code + } Ok(shell::Done::Ran(code)) => code, Err(e) => { eprintln!( diff --git a/pkgs/fleet/crates/fleet-agent/src/shell.rs b/pkgs/fleet/crates/fleet-agent/src/shell.rs index 3995351a61..4c12031bdc 100644 --- a/pkgs/fleet/crates/fleet-agent/src/shell.rs +++ b/pkgs/fleet/crates/fleet-agent/src/shell.rs @@ -3,9 +3,11 @@ //! A limited sandbox is the wrong place to compile. This verb picks a //! better one and gets out of the way: the fleet laptop (through the //! laptop-agent transport ladder: its broker, the Cloudflare tunnel, -//! the tailnet, then ssh), a codespace, or this machine when this -//! machine is already the right place. It adds no transport; it builds -//! the argv for the verb that already knows how to get there. +//! the tailnet, then ssh), a codespace, a GitHub Actions runner +//! (through placement: `fleet queue dispatch`, then the session is +//! polled to its result), or this machine when this machine is +//! already the right place. It adds no transport; it builds the argv +//! for the verb that already knows how to get there. //! //! `auto` (the default) resolves in this order: `FLEET_SHELL_TARGET`; //! here, when this seat is the laptop; the laptop, when it answers; a @@ -17,7 +19,7 @@ use fleet_config::Config; use serde_json::{Value, json}; -use crate::{AgentError, R, World, argv, parse, usage}; +use crate::{AgentError, R, World, argv, check_repo, parse, usage}; pub const USAGE: &str = "\ usage: fleet shell [options] [-- COMMAND...] @@ -25,18 +27,30 @@ usage: fleet shell [options] [-- COMMAND...] Run COMMAND where builds belong, or open a shell there with no COMMAND. - --target auto|laptop|codespace|local where (default: auto) + --target auto|laptop|codespace|actions|local where (default: auto) --codespace NAME which codespace (default: the first available) + --repo OWNER/NAME the repository an actions run executes + (default: this checkout's origin) --cwd DIR directory to run in (Cargo workspace for shared lane) --build a heavy build: take a fleet-build-lock slot; Cargo workspaces use a shared target lane - --timeout SECS how long a laptop command may run + --timeout SECS how long a laptop command may run; on the + actions target, how long to wait for the run --detach start it as a laptop job and return its id - (follow with: fleet laptop-agent poll JOB --wait N) + (follow with: fleet laptop-agent poll JOB --wait N); + on the actions target, dispatch and return the + session handle instead of waiting --print print the plan as JSON instead of running it auto resolves: FLEET_SHELL_TARGET, then here if this seat is the laptop, then the -laptop if it answers, then a codespace, then here."; +laptop if it answers, then a codespace, then here. auto never picks actions. + +The actions target dispatches COMMAND through placement (fleet queue dispatch) +to a registered GitHub Actions surface and waits for the session result: the +exit code is 0 when the run succeeded and 1 when it failed or was cancelled, +and the printed record carries the run URL — the run's own output lives on +that page (gh run view --log). Reconnect to a run you stopped waiting on with: +fleet queue session result HANDLE"; pub const DEFAULT_TIMEOUT_SECS: u64 = 120; pub const BUILD_TIMEOUT_SECS: u64 = 3600; @@ -47,6 +61,8 @@ pub enum Target { Local, Laptop, Codespace(String), + /// A GitHub Actions run of the repository, through placement. + Actions(String), } impl Target { @@ -55,6 +71,7 @@ impl Target { Target::Local => "local", Target::Laptop => "laptop", Target::Codespace(_) => "codespace", + Target::Actions(_) => "actions", } } } @@ -74,6 +91,7 @@ impl Plan { json!({ "target": self.target.id(), "codespace": match &self.target { Target::Codespace(n) => Some(n.clone()), _ => None }, + "repo": match &self.target { Target::Actions(r) => Some(r.clone()), _ => None }, "program": self.program, "args": self.args, "because": self.because, @@ -83,6 +101,9 @@ impl Plan { pub enum Done { Printed(Value), + /// Print this record, then exit with this code: the actions + /// target's verdict, where the code is the run's pass/fail. + PrintedCode(Value, i32), Ran(i32), } @@ -152,18 +173,50 @@ fn parse_target(word: &str) -> R<&'static str> { "local" => Ok("local"), "laptop" => Ok("laptop"), "codespace" => Ok("codespace"), + "actions" => Ok("actions"), other => Err(usage(format!( - "unknown target '{other}': auto, laptop, codespace or local" + "unknown target '{other}': auto, laptop, codespace, actions or local" ))), } } +/// The `owner/name` a git remote URL points at, for the shapes git +/// and GitHub actually use; None for anything else. +fn repo_from_remote(url: &str) -> Option { + let url = url.trim().trim_end_matches('/').trim_end_matches(".git"); + let path = url + .rsplit_once("github.com/") + .map(|(_, rest)| rest) + .or_else(|| url.rsplit_once("github.com:").map(|(_, rest)| rest))?; + check_repo(path).ok() +} + +/// The repository an actions run executes: the caller's `--repo`, +/// else this checkout's origin remote. +fn actions_repo(world: &dyn World, asked: Option) -> R { + if let Some(repo) = asked { + return check_repo(&repo); + } + let out = world.program("git", &argv(&["remote", "get-url", "origin"])); + if out.ok() { + if let Some(repo) = repo_from_remote(out.stdout.trim()) { + return Ok(repo); + } + } + Err(AgentError::Down( + "the actions target needs a repository: pass --repo OWNER/NAME \ + (or run inside a checkout whose origin is on GitHub)" + .to_string(), + )) +} + /// Decide where. An explicit target is used as given; only `auto` falls back. pub fn resolve( config: &Config, world: &dyn World, asked: &str, codespace: Option, + repo: Option, ) -> R<(Target, String)> { let from_env = world.env("FLEET_SHELL_TARGET"); let (want, source) = match (asked, &from_env) { @@ -173,6 +226,10 @@ pub fn resolve( match want { "local" => Ok((Target::Local, format!("{source} says local"))), "laptop" => Ok((Target::Laptop, format!("{source} says laptop"))), + "actions" => { + let repo = actions_repo(world, repo)?; + Ok((Target::Actions(repo), format!("{source} says actions"))) + } "codespace" => { let name = codespace.or_else(|| first_codespace(world)).ok_or_else(|| { AgentError::Down( @@ -591,6 +648,39 @@ pub fn plan(target: Target, because: String, words: &[String], opts: &Options) - ("fleet".to_string(), args) } } + Target::Actions(repo) => { + if interactive { + return Err(usage( + "the actions target runs a COMMAND on a GitHub Actions runner; \ + it cannot open a shell", + )); + } + if opts.build { + return Err(usage( + "--build takes a host build-lock slot; the actions target \ + dispatches through placement instead — drop --build", + )); + } + if opts.cwd.is_some() { + return Err(usage( + "--cwd does not apply to the actions target: the command runs \ + in the runner's checkout of the repository", + )); + } + // The plan is the dispatch step; run() drives it through + // the session verbs instead of attaching to it. + let args = argv(&[ + "queue", + "dispatch", + "--repo", + repo, + "--command", + &command, + "--dispatch", + "--json", + ]); + ("fleet".to_string(), args) + } Target::Codespace(name) => { if opts.detach { return Err(usage( @@ -621,6 +711,26 @@ pub fn plan(target: Target, because: String, words: &[String], opts: &Options) - }) } +/// Whether placement has a GitHub Actions surface to dispatch to, +/// read from the surface registry the queue verbs print. +fn actions_reachable(world: &dyn World) -> bool { + let out = world.fleet(&argv(&["queue", "surfaces"])); + let Some(registry) = out.json() else { + return false; + }; + registry + .get("surfaces") + .and_then(Value::as_array) + .is_some_and(|surfaces| { + surfaces.iter().any(|s| { + matches!( + s.get("kind").and_then(Value::as_str), + Some("github-actions") | Some("blacksmith") + ) + }) + }) +} + fn targets(config: &Config, world: &dyn World) -> Value { let laptop_seat = is_laptop_seat(config, world); let laptop = laptop_seat || laptop_answers(world); @@ -631,18 +741,115 @@ fn targets(config: &Config, world: &dyn World) -> Value { "how": if laptop_seat { "this seat is the laptop" } else { "fleet laptop-agent (broker, Cloudflare tunnel, tailnet, ssh)" }}, {"target": "codespace", "reachable": codespace.is_some(), "codespace": codespace, "how": "gh codespace ssh"}, + {"target": "actions", "reachable": actions_reachable(world), + "how": "fleet queue dispatch (placement over the registered Actions surfaces)"}, {"target": "local", "reachable": true, "how": "this machine"}, ], - "auto_would_pick": resolve(config, world, "auto", None).map(|(t, why)| json!({"target": t.id(), "because": why})).unwrap_or(Value::Null), + "auto_would_pick": resolve(config, world, "auto", None, None).map(|(t, why)| json!({"target": t.id(), "because": why})).unwrap_or(Value::Null), }) } +/// How long to wait between session polls on the actions target. +pub const ACTIONS_POLL_SECS: u64 = 15; +/// The wait budget when --timeout does not say: an Actions run is a +/// build, so it gets the build budget, not the laptop command one. +pub const ACTIONS_DEFAULT_TIMEOUT_SECS: u64 = BUILD_TIMEOUT_SECS; + +/// Drive one actions plan: dispatch through placement, then (unless +/// detached) poll the session to its terminal result. The plan's +/// program/args are the dispatch call itself. +fn run_actions(world: &dyn World, plan: &Plan, opts: &Options) -> R { + let repo = match &plan.target { + Target::Actions(repo) => repo.clone(), + _ => return Ok(Done::Ran(world.attach(&plan.program, &plan.args))), + }; + // Dispatch changes state on the far side (a session and a + // workflow run), so it gets the patient call: cutting it short + // would orphan the run. + let dispatched = world.fleet_patient(&plan.args); + if !dispatched.ok() { + return Err(AgentError::Down(format!( + "placement dispatch did not answer: {}", + dispatched.why() + ))); + } + let record = dispatched + .json() + .ok_or_else(|| AgentError::Down("placement dispatch answered without JSON".to_string()))?; + let handle = record + .get("handle") + .and_then(Value::as_str) + .ok_or_else(|| { + AgentError::Down("placement dispatch answered without a session handle".to_string()) + })? + .to_string(); + if opts.detach { + return Ok(Done::Printed(json!({ + "target": "actions", + "repo": repo, + "handle": handle, + "state": record.get("state").cloned().unwrap_or(Value::Null), + "run_url": record.get("run_url").cloned().unwrap_or(Value::Null), + "because": plan.because, + "note": format!("dispatched, not waited on; reconnect with: fleet queue session result {handle}"), + }))); + } + let budget = opts.timeout.unwrap_or(ACTIONS_DEFAULT_TIMEOUT_SECS); + let deadline = world.now() + budget; + loop { + let out = world.fleet(&argv(&["queue", "session", "result", &handle, "--json"])); + if !out.ok() { + return Err(AgentError::Down(format!( + "session result for {handle} did not answer: {}", + out.why() + ))); + } + let result = out.json().ok_or_else(|| { + AgentError::Down(format!("session result for {handle} answered without JSON")) + })?; + let terminal = result + .get("terminal") + .and_then(Value::as_bool) + .unwrap_or(false); + if terminal { + let state = result + .get("state") + .and_then(Value::as_str) + .unwrap_or("unknown") + .to_string(); + let code = if state == "succeeded" { 0 } else { 1 }; + return Ok(Done::PrintedCode( + json!({ + "target": "actions", + "repo": repo, + "handle": handle, + "state": state, + "run_url": result.get("run_url").cloned().unwrap_or(Value::Null), + "because": plan.because, + }), + code, + )); + } + if world.now() >= deadline { + let state = result + .get("state") + .and_then(Value::as_str) + .unwrap_or("unknown"); + return Err(AgentError::Down(format!( + "run {handle} still {state} after {budget}s; \ + reconnect with: fleet queue session result {handle}" + ))); + } + std::thread::sleep(std::time::Duration::from_secs(ACTIONS_POLL_SECS)); + } +} + /// `fleet shell ...`. pub fn run(config: &Config, world: &dyn World, args: &[String]) -> R { let a = parse( args, &["--build", "--detach", "--print"], - &["--target", "--codespace", "--cwd", "--timeout"], + &["--target", "--codespace", "--repo", "--cwd", "--timeout"], )?; match a.positional.as_slice() { [] => {} @@ -659,16 +866,26 @@ pub fn run(config: &Config, world: &dyn World, args: &[String]) -> R { } } let asked = a.last("--target").unwrap_or_else(|| "auto".to_string()); - let (target, because) = resolve(config, world, &asked, a.last("--codespace"))?; + let (target, because) = resolve( + config, + world, + &asked, + a.last("--codespace"), + a.last("--repo"), + )?; let opts = Options { cwd: a.last("--cwd"), build: a.has("--build"), timeout: a.uint("--timeout")?, detach: a.has("--detach"), }; + let actions = matches!(target, Target::Actions(_)); let plan = plan(target, because, &a.tail, &opts)?; if a.has("--print") { return Ok(Done::Printed(plan.to_json())); } + if actions { + return run_actions(world, &plan, &opts); + } Ok(Done::Ran(world.attach(&plan.program, &plan.args))) } diff --git a/pkgs/fleet/crates/fleet-agent/src/tests.rs b/pkgs/fleet/crates/fleet-agent/src/tests.rs index c87e38eb85..98d4d43370 100644 --- a/pkgs/fleet/crates/fleet-agent/src/tests.rs +++ b/pkgs/fleet/crates/fleet-agent/src/tests.rs @@ -2088,7 +2088,7 @@ fn config() -> fleet_config::Config { fn auto_on_the_laptop_runs_here_without_probing() { let fake = Fake::new(); fake.set_env("FLEET_LOCATION", "laptop"); - let (target, because) = shell::resolve(&config(), &fake, "auto", None).unwrap(); + let (target, because) = shell::resolve(&config(), &fake, "auto", None, None).unwrap(); assert_eq!(target, Target::Local); assert!(because.contains("laptop")); assert!(fake.calls().is_empty()); @@ -2099,7 +2099,9 @@ fn auto_elsewhere_prefers_the_laptop_then_a_codespace_then_here() { let fake = Fake::new(); fake.on("fleet laptop-agent health", vec![ok(json!({"ok": true}))]); assert_eq!( - shell::resolve(&config(), &fake, "auto", None).unwrap().0, + shell::resolve(&config(), &fake, "auto", None, None) + .unwrap() + .0, Target::Laptop ); @@ -2109,7 +2111,9 @@ fn auto_elsewhere_prefers_the_laptop_then_a_codespace_then_here() { vec![ok(json!([{"name": "sleepy", "state": "Shutdown"}, {"name": "awake", "state": "Available"}]))], ); assert_eq!( - shell::resolve(&config(), &fake, "auto", None).unwrap().0, + shell::resolve(&config(), &fake, "auto", None, None) + .unwrap() + .0, Target::Codespace("awake".to_string()), "a running codespace is preferred over the first listed" ); @@ -2120,7 +2124,7 @@ fn auto_elsewhere_prefers_the_laptop_then_a_codespace_then_here() { vec![fail(3, "no leg answered")], ) .on("gh codespace list", vec![fail(1, "HTTP 403")]); - let (target, because) = shell::resolve(&config(), &fake, "auto", None).unwrap(); + let (target, because) = shell::resolve(&config(), &fake, "auto", None, None).unwrap(); assert_eq!(target, Target::Local); assert!(because.contains("running here"), "{because}"); } @@ -2135,7 +2139,9 @@ fn an_explicit_target_is_never_swapped_for_another() { // Asked for the laptop while it is down: still the laptop, so the caller // sees the failure instead of a build quietly running in a sandbox. assert_eq!( - shell::resolve(&config(), &fake, "laptop", None).unwrap().0, + shell::resolve(&config(), &fake, "laptop", None, None) + .unwrap() + .0, Target::Laptop ); assert!(fake.calls().is_empty(), "an explicit target is not probed"); @@ -2143,7 +2149,7 @@ fn an_explicit_target_is_never_swapped_for_another() { let fake = Fake::new(); fake.on("gh codespace list", vec![ok(json!([]))]); assert!(matches!( - shell::resolve(&config(), &fake, "codespace", None), + shell::resolve(&config(), &fake, "codespace", None, None), Err(AgentError::Down(_)) )); } @@ -2153,17 +2159,21 @@ fn the_environment_can_pin_auto_and_a_bad_pin_is_refused() { let fake = Fake::new(); fake.set_env("FLEET_SHELL_TARGET", "local"); assert_eq!( - shell::resolve(&config(), &fake, "auto", None).unwrap().0, + shell::resolve(&config(), &fake, "auto", None, None) + .unwrap() + .0, Target::Local ); fake.set_env("FLEET_SHELL_TARGET", "moon"); assert!(matches!( - shell::resolve(&config(), &fake, "auto", None), + shell::resolve(&config(), &fake, "auto", None, None), Err(AgentError::Usage(_)) )); // An explicit --target wins over the environment. assert_eq!( - shell::resolve(&config(), &fake, "laptop", None).unwrap().0, + shell::resolve(&config(), &fake, "laptop", None, None) + .unwrap() + .0, Target::Laptop ); } @@ -2188,6 +2198,7 @@ fn shell_runs_the_plan_or_prints_it() { assert!(command.contains("cargo check")); } shell::Done::Ran(_) => panic!("--print must not run"), + shell::Done::PrintedCode(_, _) => panic!("--print must not run"), } assert!(fake.attached.borrow().is_empty()); let ran = shell::run(&config(), &fake, &argv(&["--", "uname", "-a"])).unwrap(); @@ -2203,6 +2214,297 @@ fn shell_runs_the_plan_or_prints_it() { )); } +#[test] +fn an_actions_plan_is_the_placement_dispatch() { + let plan = shell::plan( + Target::Actions("dezren39/fleet".to_string()), + "test".into(), + &words(&["cargo", "test", "-p", "fleet-agent"]), + &opts(), + ) + .unwrap(); + assert_eq!(plan.program, "fleet"); + assert_eq!( + plan.args, + argv(&[ + "queue", + "dispatch", + "--repo", + "dezren39/fleet", + "--command", + "cargo test -p fleet-agent", + "--dispatch", + "--json", + ]) + ); + let printed = plan.to_json(); + assert_eq!(printed["target"], "actions"); + assert_eq!(printed["repo"], "dezren39/fleet"); + // No shell to open, no host build lock, no runner cwd. + assert!(matches!( + shell::plan( + Target::Actions("dezren39/fleet".into()), + "t".into(), + &[], + &opts() + ), + Err(AgentError::Usage(_)) + )); + assert!(matches!( + shell::plan( + Target::Actions("dezren39/fleet".into()), + "t".into(), + &words(&["true"]), + &Options { + build: true, + ..opts() + }, + ), + Err(AgentError::Usage(_)) + )); + assert!(matches!( + shell::plan( + Target::Actions("dezren39/fleet".into()), + "t".into(), + &words(&["true"]), + &Options { + cwd: Some("/tmp".into()), + ..opts() + }, + ), + Err(AgentError::Usage(_)) + )); +} + +#[test] +fn actions_resolution_takes_the_flag_then_the_checkout_origin() { + let fake = Fake::new(); + let (target, _) = shell::resolve( + &config(), + &fake, + "actions", + None, + Some("dezren39/fleet".into()), + ) + .unwrap(); + assert_eq!(target, Target::Actions("dezren39/fleet".to_string())); + assert!(fake.calls().is_empty(), "an explicit --repo is not probed"); + + // No flag: the checkout's origin, in either URL shape. + for url in [ + "git@github.com:developing-today/code.git\n", + "https://github.com/developing-today/code.git\n", + ] { + let fake = Fake::new(); + fake.on( + "git remote get-url origin", + vec![Out { + code: 0, + stdout: url.to_string(), + stderr: String::new(), + }], + ); + let (target, _) = shell::resolve(&config(), &fake, "actions", None, None).unwrap(); + assert_eq!(target, Target::Actions("developing-today/code".to_string())); + } + + // No flag and no usable origin: a clear refusal, never a guess. + let fake = Fake::new(); + fake.on("git remote get-url origin", vec![fail(128, "no remote")]); + assert!(matches!( + shell::resolve(&config(), &fake, "actions", None, None), + Err(AgentError::Down(_)) + )); + // A malformed --repo is a usage error. + let fake = Fake::new(); + assert!(matches!( + shell::resolve(&config(), &fake, "actions", None, Some("noslash".into())), + Err(AgentError::Usage(_)) + )); + // auto never picks actions, even with a repo at hand. + let fake = Fake::new(); + fake.set_env("FLEET_LOCATION", "laptop"); + assert_eq!( + shell::resolve( + &config(), + &fake, + "auto", + None, + Some("dezren39/fleet".into()) + ) + .unwrap() + .0, + Target::Local + ); +} + +#[test] +fn an_actions_run_dispatches_waits_and_reports_the_verdict() { + let fake = Fake::new(); + fake.on( + "fleet queue dispatch", + vec![ok(json!({"handle": "fp_test", "state": "queued", "run_url": "https://example.invalid/runs/1"}))], + ) + .on( + "fleet queue session result", + vec![ok(json!({"handle": "fp_test", "state": "succeeded", "terminal": true, "run_url": "https://example.invalid/runs/1"}))], + ); + let done = shell::run( + &config(), + &fake, + &argv(&[ + "--target", + "actions", + "--repo", + "dezren39/fleet", + "--", + "cargo", + "test", + ]), + ) + .unwrap(); + match done { + shell::Done::PrintedCode(record, code) => { + assert_eq!(code, 0); + assert_eq!(record["state"], "succeeded"); + assert_eq!(record["handle"], "fp_test"); + } + _ => panic!("an actions run prints its record with the verdict code"), + } + assert!(fake.called("fleet queue dispatch --repo dezren39/fleet")); + assert!(fake.called("fleet queue session result fp_test --json")); + assert!( + fake.attached.borrow().is_empty(), + "nothing is attached locally" + ); + + // A failed run is exit 1, with the same record shape. + let fake = Fake::new(); + fake.on( + "fleet queue dispatch", + vec![ok(json!({"handle": "fp_bad", "state": "queued"}))], + ) + .on( + "fleet queue session result", + vec![ok( + json!({"handle": "fp_bad", "state": "failed", "terminal": true}), + )], + ); + let done = shell::run( + &config(), + &fake, + &argv(&[ + "--target", + "actions", + "--repo", + "dezren39/fleet", + "--", + "cargo", + "test", + ]), + ) + .unwrap(); + assert!(matches!(done, shell::Done::PrintedCode(_, 1))); +} + +#[test] +fn an_actions_detach_returns_the_handle_without_waiting() { + let fake = Fake::new(); + fake.on( + "fleet queue dispatch", + vec![ok( + json!({"handle": "fp_away", "state": "dispatched", "run_url": null}), + )], + ); + let done = shell::run( + &config(), + &fake, + &argv(&[ + "--target", + "actions", + "--repo", + "dezren39/fleet", + "--detach", + "--", + "cargo", + "build", + ]), + ) + .unwrap(); + match done { + shell::Done::Printed(record) => { + assert_eq!(record["handle"], "fp_away"); + assert!(record["note"].as_str().unwrap().contains("session result")); + } + _ => panic!("a detached actions run prints the dispatch record"), + } + assert!(!fake.called("session result"), "detach never polls"); +} + +#[test] +fn an_actions_wait_that_expires_names_the_reconnect() { + let fake = Fake::new(); + fake.on( + "fleet queue dispatch", + vec![ok(json!({"handle": "fp_slow", "state": "queued"}))], + ) + .on( + "fleet queue session result", + vec![ok( + json!({"handle": "fp_slow", "state": "running", "terminal": false}), + )], + ); + // A zero budget: the first non-terminal answer is already late. + let err = shell::run( + &config(), + &fake, + &argv(&[ + "--target", + "actions", + "--repo", + "dezren39/fleet", + "--timeout", + "0", + "--", + "cargo", + "test", + ]), + ); + match err { + Err(AgentError::Down(msg)) => { + assert!(msg.contains("fp_slow"), "{msg}"); + assert!(msg.contains("session result"), "{msg}"); + } + Err(e) => panic!("expected a Down error naming the reconnect, got: {e}"), + Ok(_) => panic!("expected a Down error naming the reconnect, got a result"), + } +} + +#[test] +fn the_targets_listing_names_actions_and_its_reachability() { + let fake = Fake::new(); + fake.set_env("FLEET_LOCATION", "laptop"); + fake.on( + "fleet queue surfaces", + vec![ok( + json!({"surfaces": [{"id": "x", "kind": "github-actions"}]}), + )], + ); + let done = shell::run(&config(), &fake, &argv(&["targets"])).unwrap(); + match done { + shell::Done::Printed(listing) => { + let actions = listing["targets"] + .as_array() + .unwrap() + .iter() + .find(|t| t["target"] == "actions") + .expect("actions is listed"); + assert_eq!(actions["reachable"], true); + } + _ => panic!("targets prints its listing"), + } +} + proptest! { /// A quoted word, handed to a real shell, comes back unchanged. #[test]