diff --git a/CHANGELOG.md b/CHANGELOG.md index 530e243..a3f18a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,57 @@ and released versions are intended to follow Semantic Versioning. - An OpenCode session's age now follows its latest real message. A model or agent switch used to bump it, so several sessions could all read "6 hours". +- `agentview opencode attach SESSION_ID [--cwd DIR]` attaches one TUI to the + session on this agentview's own OpenCode server, replacing the process. +- Jumping into a remote OpenCode session attaches through the host's agentview + supervisor, so turns typed in that TUI show as Working on both dashboards; + a direct TUI would run on its own server instance whose state managed + discovery cannot see. Hosts without the subcommand fall back to the direct + TUI. + +- `space` on a remote OpenCode row fetches the session's full transcript for + Peek from the host over SSH. The export lands in a temp file first because + `opencode export` truncates a piped export at 64 KiB, and a bounded tail of + larger exports is salvaged message by message. + +- `agentview opencode launch "task" --cwd DIR [--model M]` starts one managed + OpenCode session in the background through the supervisor's own server and + prints it as JSON — the same launch path the dashboard composer uses. +- A remote OpenCode launch with a task goes through that host's agentview + supervisor, so the session is managed there: Completed when idle, and + visible as managed on both dashboards. Hosts running an agentview without + the subcommand fall back to the interactive TUI launch. + +- New sessions can start on a watched SSH host: `ctrl+o` and the directory + view offer each host's known folders as `[host] /path`, and submitting a + task hands the terminal to that harness on the host over SSH — Claude and + Codex receive the task as their argument, and OpenCode's task is typed into + its editor as soon as the remote screen shows it accepting input. Model + picks and `--yolo` stay local-only. + +- `/remote` in the dashboard lists the watched SSH hosts, and + `/remote add HOST` / `/remote remove HOST` change the set without a + restart. The list is read on every refresh and persisted to + `~/.local/state/agentview/ssh-targets.json` immediately; each host keeps + its own completed-history budget. + +- `Enter` jumps into a remote session: the dashboard suspends and agentview + runs the provider's own attach or resume on that host over SSH — + `claude attach`/`--resume`, `opencode --session`, and `codex resume` are + supported; other harnesses are refused with a notice. Remote commands + export the per-user agent CLI homes into PATH and fall back to `~/.tmp` + for `TMPDIR` on hosts where `/tmp` is mounted noexec. + +- SSH host support (the `--ssh-host` entries here, `/remote`, remote jump-in + and launch, and `agentview opencode attach` and `launch`) is contributed by + [@BaoshanPang](https://github.com/BaoshanPang). +- `--ssh-host HOST` observes the sessions a passwordless SSH host runs through + its own agentview: each refresh runs `agentview --json` on that host and + merges the snapshot into the dashboard, with remote rows tagged with the + host and inspect-only. The host list is remembered in + `~/.local/state/agentview/ssh-targets.json`, and a host running under + `AGENTVIEW_REMOTE=1` observes nothing so two machines watching each other + cannot fan out. - When [agent-bouncer](https://github.com/moritzWa/agent-bouncer) is installed, a panel above the input lists its running and waiting heavy jobs and when the diff --git a/README.md b/README.md index 75b24d2..896f60d 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,12 @@ own interface. - **Start in any folder** with `/cd` or `Ctrl+O`. Write multi-line drafts, paste long text, attach clipboard images with `Ctrl+V`, and select text with `Shift+arrow` or words with `Option+Shift+arrow`. +- **Watch other machines in the same list** with `--ssh-host 176`: one refresh + runs agentview on that passwordless-SSH host and merges its sessions in, + tagged with the host name. `Enter` jumps into a remote session over SSH, + `Ctrl+O` starts a new one in any of its folders (typed task included), and + `/remote add` or `/remote remove` changes the set mid-session. Thanks to + [@BaoshanPang](https://github.com/BaoshanPang). - **Move or migrate a session:** `F6` changes folders; `/migrate` changes harnesses through [session-migrate](https://session-migrate.github.io/). OpenCode folder moves preserve the session ID and history. diff --git a/docs/cli.md b/docs/cli.md index 89ecb2f..22e148b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -76,6 +76,8 @@ betteragentview is already up to date. | `--openhands-bin PATH` / `--no-host-openhands` | Select or disable OpenHands native control plus bounded event-store discovery. | | `--docker-container NAME_OR_ID` | Observe Claude and Codex in one explicitly selected running container; repeatable. | | `--docker-bin PATH` | Use a particular Docker executable; default `docker`. | +| `--ssh-host HOST` | Observe sessions on a passwordless SSH host that runs agentview; repeatable. The host list is remembered in the state directory after the first run. | +| `--ssh-bin PATH` | Use a particular SSH client for `--ssh-host` targets; default `ssh`. | | `--session-migrate-bin PATH` | Use a particular session-migrate executable for `F6` moves and `/migrate`; default `session-migrate`. | | `--harness` / `--launch-provider claude\|codex\|pi\|omp\|opencode\|cursor\|copilot\|antigravity\|mistral-vibe\|muse\|qwen\|kimi\|grok\|kilo\|openhands\|terminal` | Initial harness for new-session prompts; default Claude. Each configured coding harness opens its native full-screen UI; Terminal opens the user's shell. `oh-my-pi` and `kilo-code` are accepted aliases. | | `--launch-cwd PATH` | Working directory for newly launched host sessions; default current directory. | @@ -448,6 +450,19 @@ host Codex, missing Codex, active threads, external threads, Docker threads, and providers without a documented archive operation are refused or reported as ineligible. betteragentview does not call deletion an archive. +## Starting a managed session from the command line + +```console +agentview opencode launch "fix the flaky test" --cwd ~/work/repo +agentview opencode launch "fix the flaky test" --cwd ~/work/repo --model anthropic/claude-opus-5-5 +``` + +The supervisor creates the session on its own server, records ownership before +the turn starts, and submits the task. The created session prints as JSON. This +is the same launch path the dashboard composer uses, so the session is managed: +it shows Completed when idle, restarts resume it, and it can be opened, +replied to, and interrupted from any dashboard that owns it. + ## Restarting the OpenCode server betteragentview runs one OpenCode server that its attached OpenCode sessions use. @@ -521,6 +536,71 @@ need a server whose `/tui/select-session` accepts `client`; betteragentview read server's `/doc` to check, because older servers accept the field and then switch every attached window. +## SSH host targets + +`agentview --ssh-host HOST` observes the sessions another machine runs through +its own agentview. One refresh runs `agentview --json` on that host over SSH +and merges the result into the dashboard, so every provider installed there +appears once, tagged with its host: + +```console +agentview --ssh-host 176 +agentview --ssh-host 176 --ssh-host 177 +``` + +Inside the dashboard, `/remote` lists the watched hosts and +`/remote add HOST` / `/remote remove HOST` change the set without a restart; +the change persists to `~/.local/state/agentview/ssh-targets.json` immediately. + +Requirements and behavior: + +- The host must be reachable non-interactively (`BatchMode`): keys set up with + `ssh-copy-id`, no passphrase prompt. Anything else fails fast as a dashboard + warning; the rest of the dashboard is unaffected. +- agentview must be installed on the remote host and on its PATH for + non-interactive shells (`~/.local/bin` is probed). +- Remote rows are tagged with the host and Peek shows it as their runtime. + `Enter` jumps in: the dashboard suspends, agentview runs the provider's own + attach/resume on that host over SSH (`claude attach`/`--resume`, + `opencode --session`, `codex resume`), and `Enter`/`Right` resumes a + backgrounded SSH client like any local session. Harnesses without a native + remote attach (including the Terminal harness and launch) are refused with a + notice, and inline reply/interrupt stay local-only. +- OpenCode jumps in attach through the host's own agentview + (`agentview opencode attach`), so the TUI connects to that supervisor's + server: turns typed there show as Working on both dashboards and idle ones + as Completed. A direct TUI would run on its own server instance whose state + managed discovery cannot see. Hosts running an older agentview reject the + subcommand and fall back to the direct TUI. +- `space` fetches a remote OpenCode session's full transcript for Peek from + the host (`opencode export` into a temp file, since that CLI truncates a + piped export at 64 KiB); the newest messages are kept. Claude and Codex + remote transcripts are not fetched yet. +- New sessions can start on a watched host: `ctrl+o` (and the directory view) + offers each host's known folders as `[host] /path`; picking one and + submitting a task hands the terminal to that harness on the host — + Claude and Codex receive the task as their argument, and OpenCode's task is + typed into its editor the moment the host's screen shows it accepting + input, exactly as a local native launch. Model picks and `--yolo` + permission bypass stay local-only. +- OpenCode sessions with a task start through the host's own agentview + supervisor (`agentview opencode launch` over SSH), so they are managed + there: Completed when idle, and controllable from the host's dashboard too. + The host must run an agentview that has the subcommand; older ones fall + back to the interactive TUI launch. +- The host list is persisted to + `~/.local/state/agentview/ssh-targets.json` after the first + `--ssh-host` run or `/remote add`, so later plain `agentview` launches keep + watching those hosts. Remove a host with `/remote remove HOST` or by + deleting it from that file. +- A host that is itself being observed (its agentview runs with + `AGENTVIEW_REMOTE=1`) observes nothing, so two machines pointing at each + other cannot fan out. +- Remote commands export a PATH with the per-user agent homes + (`~/.local/bin`, `~/.opencode/bin`, `~/.npm-global/bin`, `~/.bun/bin`, + `~/bin`) because non-interactive shells miss them, and fall back to + `~/.tmp` for `TMPDIR` on hosts where `/tmp` is mounted noexec. + ## Managed Docker lifecycle Managed Docker is distinct from `--docker-container`. The latter enrolls one diff --git a/src/adapters/antigravity.rs b/src/adapters/antigravity.rs index b3c1048..5f29aec 100644 --- a/src/adapters/antigravity.rs +++ b/src/adapters/antigravity.rs @@ -400,6 +400,7 @@ pub fn parse_antigravity_last_conversations( let runtime_id = match &runtime { Runtime::Host => "host", Runtime::Docker { container_id, .. } => container_id, + Runtime::Ssh { host } => host, }; let workspace_name = cwd .file_name() diff --git a/src/adapters/claude.rs b/src/adapters/claude.rs index 26b77a7..28b0d19 100644 --- a/src/adapters/claude.rs +++ b/src/adapters/claude.rs @@ -247,6 +247,7 @@ fn normalize_record(record: ClaudeRecord, runtime: Runtime) -> AgentSession { let runtime_id = match &runtime { Runtime::Host => "host", Runtime::Docker { container_id, .. } => container_id, + Runtime::Ssh { host } => host, }; AgentSession { diff --git a/src/adapters/codex.rs b/src/adapters/codex.rs index d7231f9..a38b8b4 100644 --- a/src/adapters/codex.rs +++ b/src/adapters/codex.rs @@ -444,6 +444,7 @@ fn normalize_thread(thread: CodexThread, runtime: Runtime) -> AgentSession { let runtime_id = match &runtime { Runtime::Host => "host", Runtime::Docker { container_id, .. } => container_id, + Runtime::Ssh { host } => host, }; // The summary remains observable, but transcript/control capabilities are // granted only after the host supervisor proves exact ownership. diff --git a/src/adapters/copilot.rs b/src/adapters/copilot.rs index 3ba5587..8db3cdc 100644 --- a/src/adapters/copilot.rs +++ b/src/adapters/copilot.rs @@ -1222,6 +1222,7 @@ fn normalize_copilot_session(session: CopilotSessionInfo, runtime: Runtime) -> A let runtime_id = match &runtime { Runtime::Host => "host", Runtime::Docker { container_id, .. } => container_id, + Runtime::Ssh { host } => host, }; let fallback_name = session .cwd diff --git a/src/adapters/mod.rs b/src/adapters/mod.rs index e1dfb8b..7756431 100644 --- a/src/adapters/mod.rs +++ b/src/adapters/mod.rs @@ -25,6 +25,7 @@ mod pi; mod qwen; mod screen_status; mod session_migrate_native; +pub(crate) mod ssh_remote; mod terminal_harness; use std::collections::{BTreeMap, BTreeSet}; @@ -84,13 +85,18 @@ pub use muse::{ }; pub use opencode::{ default_opencode_ownership_path, parse_opencode_session_list, OpenCodeController, - OpenCodeInvocation, OpenCodeOwnership, OpenCodeSource, + OpenCodeInvocation, OpenCodeOwnership, OpenCodeSource, OPENCODE_READY_MARKER, }; pub use pi::{default_pi_session_dir, parse_pi_session, PiController, PiSource}; pub use qwen::{default_qwen_ownership_path, QwenController, QwenOwnership, QwenSource}; pub use session_migrate_native::{ SessionMigrateNativeController, SessionMigrateNativeOwnership, SessionMigrateNativeSource, }; +pub use ssh_remote::{ + default_ssh_targets_path, load_ssh_targets, load_ssh_targets_at, save_ssh_targets, + save_ssh_targets_at, validate_host, SshHostSource, SshHostsSource, SshTargetList, SshTargets, + REMOTE_GUARD_ENV, REMOTE_PATH_PREFIX, +}; pub use terminal_harness::{is_shell_install_choice, shell_install_name, TerminalHarness}; use crate::domain::{AgentSession, Provider, Runtime, SessionKind, SessionSnapshot, SessionState}; @@ -459,7 +465,7 @@ fn deduplicate_sessions(sessions: &mut Vec) { sessions.extend(unique.into_values()); } -fn bound_completed_history( +pub(crate) fn bound_completed_history( sessions: &mut Vec, kept: &std::collections::BTreeSet, request: &DiscoveryRequest, diff --git a/src/adapters/opencode.rs b/src/adapters/opencode.rs index 06d9090..efdb3cb 100644 --- a/src/adapters/opencode.rs +++ b/src/adapters/opencode.rs @@ -51,7 +51,9 @@ const MANAGED_LIST_SHARED_FOR: Duration = Duration::from_millis(1500); /// Quiet after the title changes, so the frame that set it has finished. const SHARED_CLIENT_SETTLE: Duration = Duration::from_millis(40); const MAX_RESTORABLE_SESSIONS: usize = 2_000; -const OPENCODE_READY_MARKER: &str = "Ask anything"; +/// The empty OpenCode editor shows this once it accepts input; a launch +/// submits its task only after it is on screen. +pub const OPENCODE_READY_MARKER: &str = "Ask anything"; type HolderProbe = Arc Vec + Send + Sync>; @@ -1991,6 +1993,7 @@ impl OpenCodeSource { match &self.runtime { Runtime::Host => "host".into(), Runtime::Docker { container_id, .. } => container_id.clone(), + Runtime::Ssh { host } => host.clone(), } } @@ -2622,6 +2625,7 @@ fn normalize_record(record: OpenCodeRecord, runtime: Runtime) -> AgentSession { let runtime_id = match &runtime { Runtime::Host => "host", Runtime::Docker { container_id, .. } => container_id, + Runtime::Ssh { host } => host, }; let capabilities = if runtime == Runtime::Host { BTreeSet::from([Capability::Inspect]) diff --git a/src/adapters/ssh_remote.rs b/src/adapters/ssh_remote.rs new file mode 100644 index 0000000..f4e9c02 --- /dev/null +++ b/src/adapters/ssh_remote.rs @@ -0,0 +1,1039 @@ +//! Sessions on passwordless SSH hosts that run agentview themselves. +//! +//! One refresh runs `agentview --json` on the remote host over SSH and merges +//! the returned snapshot. Remote rows are observation-first: their +//! capabilities are reduced to `Inspect`, their process IDs are cleared, and +//! their runtime becomes [`Runtime::Ssh`]. Opening one is routed by +//! `ControlHub::open` to the provider's native attach over SSH; inline reply +//! and launch stay local-only. The remote agentview receives +//! `AGENTVIEW_REMOTE=1` so a host that is also a target never fans out +//! recursively. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; + +use super::{DiscoveryRequest, SessionSource, SourceDiscovery}; +use crate::domain::{AgentSession, Capability, Runtime}; +use crate::fs_util; +use crate::paused::{ensure_private_directory, RegistryLock}; +use crate::process::{CancellableProcessRunner, CommandRequest, CommandRunner}; + +/// Set in the remote command so the remote agentview ignores its own SSH +/// targets: a machine that both runs sessions and watches others must not +/// observe itself. +pub const REMOTE_GUARD_ENV: &str = "AGENTVIEW_REMOTE"; + +/// A remote command runs through a non-interactive shell whose PATH misses the +/// per-user agent CLI homes (OpenCode installs into `~/.opencode/bin`, npm +/// globals into `~/.npm-global/bin`). Discovery and remote open both export +/// this so the same binaries are reachable in both directions, and child +/// processes inherit it. +pub const REMOTE_PATH_PREFIX: &str = + "export PATH=\"$HOME/.local/bin:$HOME/.opencode/bin:$HOME/.npm-global/bin:$HOME/.bun/bin:$HOME/bin:$PATH\""; + +const REGISTRY_VERSION: u32 = 1; +/// A full remote discovery runs every provider on that host. +const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(45); + +pub struct SshHostSource { + label: String, + host: String, + ssh_bin: String, + runner: Arc, +} + +impl SshHostSource { + pub fn new(host: impl Into) -> Self { + Self::with_ssh_bin(host, "ssh") + } + + pub fn with_ssh_bin(host: impl Into, ssh_bin: impl Into) -> Self { + Self::with_runner_and_bin(host, ssh_bin, Arc::new(CancellableProcessRunner::default())) + } + + pub fn with_runner_and_bin( + host: impl Into, + ssh_bin: impl Into, + runner: Arc, + ) -> Self { + let host = host.into(); + Self { + label: format!("{host} (ssh)"), + host, + ssh_bin: ssh_bin.into(), + runner, + } + } + + #[cfg(test)] + fn with_runner(host: impl Into, runner: Arc) -> Self { + Self::with_runner_and_bin(host, "ssh", runner) + } + + fn remote_command(&self) -> String { + format!( + "{REMOTE_PATH_PREFIX}; export {REMOTE_GUARD_ENV}=1; agentview \ + --json --include-interactive --include-external" + ) + } + + fn ssh_request(&self) -> CommandRequest { + let mut command = CommandRequest::new( + self.ssh_bin.clone(), + vec![ + "-o".into(), + "BatchMode=yes".into(), + "-o".into(), + "ConnectTimeout=10".into(), + self.host.clone(), + self.remote_command(), + ], + ); + command.timeout = DISCOVERY_TIMEOUT; + command + } + + pub(crate) fn discover_remote(&self, _request: &DiscoveryRequest) -> Result { + let output = self.runner.run(&self.ssh_request())?; + if output.status != 0 { + bail!( + "agentview on {host} exited with status {status}: {stderr}", + host = self.host, + status = output.status, + stderr = output.stderr_lossy() + ); + } + let (mut sessions, mut warnings) = parse_remote_snapshot(&output.stdout)?; + for session in &mut sessions { + remap_row(session, &self.host); + } + let prefix = format!("{}: ", self.host); + for warning in &mut warnings { + *warning = format!("{prefix}{warning}"); + } + Ok(SourceDiscovery { + sessions, + warnings, + kept: Default::default(), + }) + } +} + +impl SessionSource for SshHostSource { + fn label(&self) -> &str { + &self.label + } + + fn discover(&self, request: &DiscoveryRequest) -> Result> { + Ok(self.discover_remote(request)?.sessions) + } + + fn discover_with_warnings(&self, request: &DiscoveryRequest) -> Result { + self.discover_remote(request) + } + + fn cancel(&self) { + self.runner.cancel(); + } +} + +/// The SSH hosts this dashboard watches, shared between the discovery source +/// and the dashboard so `/remote add` and `/remote remove` take effect on the +/// next refresh. `frozen` hosts refuse changes: a machine that is itself being +/// observed (`AGENTVIEW_REMOTE=1`) observes nothing. `save_path` persists +/// every change; `None` keeps tests and fixtures from touching state. +#[derive(Clone, Debug)] +pub struct SshTargetList { + hosts: Arc>>, + frozen: bool, + save_path: Option, +} + +impl SshTargetList { + /// A list that refuses changes and watches nothing. + pub fn disabled() -> Self { + Self { + hosts: Arc::new(Mutex::new(BTreeSet::new())), + frozen: true, + save_path: None, + } + } + + pub fn enabled(hosts: Vec, save_path: PathBuf) -> Self { + Self { + hosts: Arc::new(Mutex::new(hosts.into_iter().collect())), + frozen: false, + save_path: Some(save_path), + } + } + + pub fn hosts(&self) -> BTreeSet { + self.hosts + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } + + /// Watch one more host. Returns whether the list changed. + pub fn insert(&self, host: &str) -> Result { + if self.frozen { + bail!("remote hosts are disabled while agentview runs as a watched host"); + } + validate_host(host)?; + let changed = self + .hosts + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(host.to_owned()); + if changed { + self.persist()?; + } + Ok(changed) + } + + /// Stop watching one host. Returns whether the list changed. + pub fn remove(&self, host: &str) -> Result { + if self.frozen { + bail!("remote hosts are disabled while agentview runs as a watched host"); + } + let changed = self + .hosts + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(host); + if changed { + self.persist()?; + } + Ok(changed) + } + + fn persist(&self) -> Result<()> { + match &self.save_path { + Some(path) => { + let hosts = self.hosts(); + save_ssh_targets_at(path, &hosts) + } + None => Ok(()), + } + } +} + +/// A watched host is asked again no sooner than this after its last answer. +const MIN_REFETCH: Duration = Duration::from_secs(3); + +/// What the dashboard last learned from one host. +#[derive(Default)] +struct HostCache { + result: Option>, + in_flight: bool, + finished_at: Option, +} + +/// One dashboard source for every watched SSH host. The host list is read on +/// each refresh, so /remote add and /remote remove change what the next +/// refresh reports without restarting agentview. Runners stay per host so an +/// in-flight SSH discovery can still be cancelled on exit. +/// +/// In the dashboard a refresh never waits for a host: it reports each host's +/// last answer and starts a new fetch in the background, so a slow or dead +/// host cannot delay the status of local sessions. One-shot callers such as +/// --json wait for the hosts instead. +pub struct SshHostsSource { + label: String, + hosts: SshTargetList, + ssh_bin: String, + runners: Mutex>>, + background: bool, + cache: Arc>>, +} + +impl SshHostsSource { + pub fn new(hosts: SshTargetList, ssh_bin: impl Into) -> Self { + Self { + label: "SSH hosts".into(), + hosts, + ssh_bin: ssh_bin.into(), + runners: Mutex::new(BTreeMap::new()), + background: false, + cache: Arc::new(Mutex::new(BTreeMap::new())), + } + } + + /// Report each host's last answer and refetch in the background, instead + /// of waiting for the hosts on every refresh. + pub fn in_background(mut self) -> Self { + self.background = true; + self + } + + fn host_source(&self, host: &str) -> SshHostSource { + let runner = self + .runners + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .entry(host.to_owned()) + .or_insert_with(|| { + Arc::new(CancellableProcessRunner::default()) as Arc + }) + .clone(); + SshHostSource::with_runner_and_bin(host, &self.ssh_bin, runner) + } + + fn discover_in_background( + &self, + hosts: &std::collections::BTreeSet, + request: &DiscoveryRequest, + ) -> SourceDiscovery { + let mut merged = SourceDiscovery::default(); + for host in hosts { + let start = { + let mut cache = self + .cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let entry = cache.entry(host.clone()).or_default(); + let due = !entry.in_flight + && entry + .finished_at + .map_or(true, |finished| finished.elapsed() >= MIN_REFETCH); + if due { + entry.in_flight = true; + } + due + }; + if start { + let source = self.host_source(host); + let cache = Arc::clone(&self.cache); + let request = request.clone(); + let host = host.clone(); + std::thread::spawn(move || { + let result = fetch_host(&source, &request); + let mut cache = cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let entry = cache.entry(host).or_default(); + entry.result = Some(result); + entry.in_flight = false; + entry.finished_at = Some(std::time::Instant::now()); + }); + } + } + let cache = self + .cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for host in hosts { + match cache.get(host).and_then(|entry| entry.result.as_ref()) { + Some(Ok(discovered)) => merge_host(&mut merged, discovered.clone()), + Some(Err(warning)) => merged.warnings.push(warning.clone()), + None => {} + } + } + merged + } +} + +impl SessionSource for SshHostsSource { + fn label(&self) -> &str { + &self.label + } + + fn discover(&self, request: &DiscoveryRequest) -> Result> { + Ok(self.discover_with_warnings(request)?.sessions) + } + + fn discover_with_warnings(&self, request: &DiscoveryRequest) -> Result { + let hosts = self.hosts.hosts(); + self.runners + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .retain(|host, _| hosts.contains(host)); + self.cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .retain(|host, _| hosts.contains(host)); + if hosts.is_empty() { + return Ok(SourceDiscovery::default()); + } + if self.background { + return Ok(self.discover_in_background(&hosts, request)); + } + let sources = hosts + .iter() + .map(|host| self.host_source(host)) + .collect::>(); + aggregate_host_discoveries(&sources, request) + } + + fn cancel(&self) { + for runner in self + .runners + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .values() + { + runner.cancel(); + } + } +} + +/// Ask one host and apply its own completed-history budget. Each host keeps +/// its own budget, so adding a host never steals another host's completed +/// rows. +fn fetch_host( + source: &SshHostSource, + request: &DiscoveryRequest, +) -> std::result::Result { + let label = source.label().to_owned(); + let mut discovered = source + .discover_remote(request) + .map_err(|error| format!("{label}: {error:#}"))?; + let mut kept = std::mem::take(&mut discovered.kept); + if super::bound_completed_history(&mut discovered.sessions, &kept, request) { + discovered.warnings.push(format!( + "{label} completed history is limited to {} records for this refresh; increase --history-limit to load more", + request.history_limit.max(1) + )); + } + // The rows that survive each host's own budget are listed on purpose, so + // the engine-level budget over the merged list never drops one host's + // rows for another host's. + for session in &discovered.sessions { + if session.state == crate::domain::SessionState::Completed { + kept.insert(session.id.clone()); + } + } + discovered.kept = kept; + Ok(discovered) +} + +fn merge_host(merged: &mut SourceDiscovery, mut discovered: SourceDiscovery) { + merged.sessions.append(&mut discovered.sessions); + merged.warnings.append(&mut discovered.warnings); + merged.kept.extend(discovered.kept); +} + +/// Discover every host concurrently and merge the results, waiting for all of +/// them. +fn aggregate_host_discoveries( + sources: &[SshHostSource], + request: &DiscoveryRequest, +) -> Result { + let mut merged = SourceDiscovery::default(); + std::thread::scope(|scope| { + let workers = sources + .iter() + .map(|source| scope.spawn(move || fetch_host(source, request))) + .collect::>(); + for worker in workers { + match worker.join() { + Ok(Ok(discovered)) => merge_host(&mut merged, discovered), + Ok(Err(warning)) => merged.warnings.push(warning), + Err(_) => merged + .warnings + .push("SSH host: provider discovery panicked".into()), + } + } + }); + Ok(merged) +} + +/// Reduce one remote row to a read-only observation of that host. +fn remap_row(session: &mut AgentSession, host: &str) { + session.id = format!("ssh:{host}:{}", session.id); + session.runtime = match &session.runtime { + Runtime::Docker { container_name, .. } => Runtime::Ssh { + host: format!("{host}/{container_name}"), + }, + _ => Runtime::Ssh { + host: host.to_owned(), + }, + }; + session.pid = None; + session.capabilities = BTreeSet::from([Capability::Inspect]); +} + +/// Parse the remote `agentview --json` output. Shell banners before or after +/// the document are ignored, and sessions a newer agentview added remain +/// parseable one by one. +fn parse_remote_snapshot(stdout: &[u8]) -> Result<(Vec, Vec)> { + let text = String::from_utf8_lossy(stdout); + let start = text + .find('{') + .context("agentview on the remote host printed no JSON")?; + let end = text + .rfind('}') + .context("agentview on the remote host printed an incomplete JSON document")?; + if start >= end { + bail!("agentview on the remote host printed an unexpected JSON shape"); + } + let document = &text[start..=end]; + if let Ok(snapshot) = serde_json::from_str::(document) { + return Ok((snapshot.sessions, snapshot.warnings)); + } + let value: serde_json::Value = serde_json::from_str(document) + .context("invalid agentview --json output from the remote host")?; + let mut sessions = Vec::new(); + let mut skipped = 0_usize; + for record in value + .get("sessions") + .and_then(serde_json::Value::as_array) + .into_iter() + .flatten() + { + match serde_json::from_value::(record.clone()) { + Ok(session) => sessions.push(session), + Err(_) => skipped += 1, + } + } + let mut warnings = value + .get("warnings") + .and_then(serde_json::Value::as_array) + .into_iter() + .flatten() + .filter_map(|warning| warning.as_str().map(str::to_owned)) + .collect::>(); + if skipped > 0 { + warnings.push(format!( + "{skipped} sessions were skipped because this agentview does not know their format" + )); + } + Ok((sessions, warnings)) +} + +/// SSH hosts this installation watches, persisted so awareness survives +/// restarts without repeating `--ssh-host` on every launch. +#[derive(Debug, Default, Deserialize, Serialize)] +pub struct SshTargets { + pub hosts: BTreeSet, +} + +#[derive(Debug, Deserialize, Serialize)] +struct SshTargetsDocument { + version: u32, + hosts: Vec, +} + +pub fn default_ssh_targets_path() -> Result { + if let Some(state_home) = crate::fs_util::xdg_home("XDG_STATE_HOME") { + return Ok(PathBuf::from(state_home) + .join("agentview") + .join("ssh-targets.json")); + } + let home = std::env::var_os("HOME").context("HOME is not set")?; + Ok(PathBuf::from(home).join(".local/state/agentview/ssh-targets.json")) +} + +/// Hosts from the state file. A missing file means no targets. +pub fn load_ssh_targets() -> Result { + load_ssh_targets_at(&default_ssh_targets_path()?) +} + +pub fn load_ssh_targets_at(path: &std::path::Path) -> Result { + let Ok(input) = fs::read_to_string(path) else { + return Ok(SshTargets::default()); + }; + let document: SshTargetsDocument = serde_json::from_str(&input) + .with_context(|| format!("invalid SSH targets registry {}", path.display()))?; + if document.version != REGISTRY_VERSION { + bail!( + "unsupported SSH targets registry version {} in {}", + document.version, + path.display() + ); + } + let mut hosts = BTreeSet::new(); + for host in document.hosts { + validate_host(&host).with_context(|| format!("invalid SSH target {}", path.display()))?; + hosts.insert(host); + } + Ok(SshTargets { hosts }) +} + +/// Persist the merged host set. Explicit `--ssh-host` flags make an agentview +/// aware of a host for every future run. +pub fn save_ssh_targets(hosts: &BTreeSet) -> Result<()> { + save_ssh_targets_at(&default_ssh_targets_path()?, hosts) +} + +pub fn save_ssh_targets_at(path: &std::path::Path, hosts: &BTreeSet) -> Result<()> { + for host in hosts { + validate_host(host)?; + } + if let Some(parent) = path.parent() { + ensure_private_directory(parent)?; + } + let _lock = RegistryLock::acquire(&path.with_file_name("ssh-targets.lock"))?; + let document = SshTargetsDocument { + version: REGISTRY_VERSION, + hosts: hosts.iter().cloned().collect(), + }; + fs_util::write_private_json(path, &document) + .with_context(|| format!("failed to write {}", path.display())) +} + +/// Only host aliases and plain hostnames are accepted: each part becomes an +/// SSH argument, and anything that could act as a flag or contain shell +/// separation is rejected. +pub fn validate_host(host: &str) -> Result<()> { + let first = host + .chars() + .next() + .context("SSH target must not be empty")?; + if first == '-' { + bail!("SSH target must not start with '-'"); + } + if host.chars().any(|character| { + character.is_whitespace() || character == ';' || character == '$' || character == '\'' + }) { + bail!("SSH target contains unsupported characters"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::process::CommandOutput; + use std::sync::Mutex; + + struct FakeRunner { + expected: CommandRequest, + output: Mutex>, + } + + impl CommandRunner for FakeRunner { + fn run(&self, request: &CommandRequest) -> Result { + assert_eq!(request, &self.expected); + Ok(self.output.lock().unwrap().take().unwrap()) + } + } + + fn snapshot_fixture() -> String { + serde_json::json!({ + "sessions": [ + { + "id": "opencode:host:ses_one", + "provider_session_id": "ses_one", + "provider": "opencode", + "runtime": {"kind": "host"}, + "kind": "managed", + "name": "Fix the parser", + "cwd": "/home/bpang/mywork", + "state": "working", + "summary": "Rewriting the lexer", + "raw_state": "managed_server", + "pid": 496692, + "started_at": 1793134692584_u64, + "updated_at": 1793134809515_u64, + "pull_requests": null, + "capabilities": ["inspect", "reply", "interrupt"] + }, + { + "id": "claude:host:11111111-2222-3333-4444-555555555555", + "provider_session_id": "11111111-2222-3333-4444-555555555555", + "provider": "claude", + "runtime": {"kind": "docker", "container_id": "abc123", + "container_name": "dev", "image": "ubuntu:22.04"}, + "kind": "background", + "name": "claude-1111111", + "cwd": "/srv/work", + "state": "completed", + "summary": "finished", + "raw_state": null, + "pid": 42, + "started_at": null, + "updated_at": 1793134700000_u64, + "pull_requests": null, + "capabilities": ["inspect"] + } + ], + "warnings": ["Docker: permission denied"] + }) + .to_string() + } + + fn source_with(output: String) -> SshHostSource { + let expected = CommandRequest { + program: "ssh".into(), + args: vec![ + "-o".into(), + "BatchMode=yes".into(), + "-o".into(), + "ConnectTimeout=10".into(), + "176".into(), + format!( + "{REMOTE_PATH_PREFIX}; export AGENTVIEW_REMOTE=1; agentview --json --include-interactive --include-external" + ), + ], + current_dir: None, + timeout: DISCOVERY_TIMEOUT, + stdout_file: None, + }; + SshHostSource::with_runner( + "176", + Arc::new(FakeRunner { + expected, + output: Mutex::new(Some(CommandOutput { + status: 0, + stdout: output.into_bytes(), + stderr: Vec::new(), + })), + }), + ) + } + + #[test] + fn discovery_merges_remote_rows_as_inspect_only_ssh_sessions() { + let source = source_with(snapshot_fixture()); + let discovered = source + .discover_with_warnings(&DiscoveryRequest::default()) + .unwrap(); + + let rows = &discovered.sessions; + assert_eq!(rows.len(), 2); + let opencode = &rows[0]; + assert_eq!(opencode.id, "ssh:176:opencode:host:ses_one"); + assert_eq!(opencode.runtime, Runtime::Ssh { host: "176".into() }); + assert_eq!(opencode.pid, None); + assert_eq!(opencode.capabilities, BTreeSet::from([Capability::Inspect])); + assert_eq!(opencode.name, "Fix the parser"); + assert_eq!(opencode.state, crate::domain::SessionState::Working); + + let claude = &rows[1]; + assert_eq!( + claude.id, + "ssh:176:claude:host:11111111-2222-3333-4444-555555555555" + ); + assert_eq!( + claude.runtime, + Runtime::Ssh { + host: "176/dev".into() + } + ); + + assert_eq!(discovered.warnings, vec!["176: Docker: permission denied"]); + } + + #[test] + fn banner_noise_around_the_document_is_ignored() { + let output = format!( + "Fortinet authorized uses only.\n{}\nAgentview out.\n", + snapshot_fixture() + ); + let source = source_with(output); + let discovered = source + .discover_with_warnings(&DiscoveryRequest::default()) + .unwrap(); + assert_eq!(discovered.sessions.len(), 2); + } + + #[test] + fn a_failed_remote_run_reports_the_stderr() { + let failing = { + let mut source = SshHostSource::new("176"); + let expected = source.ssh_request(); + struct Failing { + expected: CommandRequest, + } + impl CommandRunner for Failing { + fn run(&self, request: &CommandRequest) -> Result { + assert_eq!(request, &self.expected); + Ok(CommandOutput { + status: 255, + stdout: Vec::new(), + stderr: b"ssh: Could not resolve hostname nope".to_vec(), + }) + } + } + source.runner = Arc::new(Failing { expected }); + source + }; + let error = failing.discover(&DiscoveryRequest::default()).unwrap_err(); + assert!( + error.to_string().contains("status 255"), + "unexpected error: {error:#}" + ); + + // A zero status with no JSON still fails with a clear message. + let error = source_with(String::new()) + .discover(&DiscoveryRequest::default()) + .unwrap_err(); + assert!( + error.to_string().contains("printed no JSON"), + "unexpected error: {error:#}" + ); + } + + #[test] + fn unknown_future_sessions_are_skipped_with_a_warning() { + let output = r#"{ + "sessions": [ + {"id": "opencode:host:ses_old", "provider_session_id": "ses_old", + "provider": "opencode", "runtime": {"kind": "host"}, "kind": "managed", + "name": "old", "cwd": "/w", "state": "working", "summary": "", "raw_state": null, + "pid": null, "started_at": null, "updated_at": null, "pull_requests": null, + "capabilities": []}, + {"id": "future:host:ses_new", "provider_session_id": "ses_new", + "provider": "future", "runtime": {"kind": "host"}, "kind": "managed", + "name": "new", "cwd": "/w", "state": "working", "summary": "", "raw_state": null, + "pid": null, "started_at": null, "updated_at": null, "pull_requests": null, + "capabilities": [], "brandNewField": true} + ], + "warnings": [] + }"# + .to_string(); + let source = source_with(output); + let discovered = source + .discover_with_warnings(&DiscoveryRequest::default()) + .unwrap(); + assert_eq!(discovered.sessions.len(), 1); + assert_eq!( + discovered.warnings, + vec!["176: 1 sessions were skipped because this agentview does not know their format"] + ); + } + + #[test] + fn ssh_targets_round_trip_and_validate() { + validate_host("176").unwrap(); + validate_host("bpang@172.30.80.176").unwrap(); + validate_host("-oFoo=bar").unwrap_err(); + validate_host("17 6").unwrap_err(); + validate_host("a;b").unwrap_err(); + + let directory = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap(); + } + let path = directory.path().join("ssh-targets.json"); + assert!(load_ssh_targets_at(&path).unwrap().hosts.is_empty()); + let mut hosts = BTreeSet::new(); + hosts.insert("176".into()); + hosts.insert("177".into()); + save_ssh_targets_at(&path, &hosts).unwrap(); + assert_eq!(load_ssh_targets_at(&path).unwrap().hosts, hosts); + + let corrupt = directory.path().join("corrupt.json"); + fs::write(&corrupt, "{\"version\": 9, \"hosts\": []}").unwrap(); + assert!(load_ssh_targets_at(&corrupt).is_err()); + } + + #[test] + fn ssh_target_list_persists_changes_and_refuses_when_frozen() { + validate_host("-oProxy=evil").unwrap_err(); + assert!(SshTargetList::disabled() + .insert("176") + .unwrap_err() + .to_string() + .contains("remote hosts are disabled")); + + let directory = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap(); + } + let registry = directory.path().join("ssh-targets.json"); + let list = SshTargetList::enabled(Vec::new(), registry.clone()); + + assert!(list.insert("176").unwrap()); + assert_eq!(list.hosts(), ["176".to_owned()].into_iter().collect()); + assert_eq!(load_ssh_targets_at(®istry).unwrap().hosts, list.hosts()); + assert!(!list.insert("176").unwrap()); + assert!(list.insert("bad host").is_err()); + assert!(!list.remove("177").unwrap()); + assert!(list.remove("176").unwrap()); + assert!(list.hosts().is_empty()); + assert!(load_ssh_targets_at(®istry).unwrap().hosts.is_empty()); + } + + #[test] + fn ssh_hosts_source_reports_nothing_when_no_host_is_watched() { + let source = SshHostsSource::new(SshTargetList::disabled(), "ssh"); + let discovered = source + .discover_with_warnings(&DiscoveryRequest::default()) + .unwrap(); + assert!(discovered.sessions.is_empty()); + assert!(discovered.warnings.is_empty()); + } + + struct SlowRunner { + delay: Duration, + output: String, + } + + impl CommandRunner for SlowRunner { + fn run(&self, _request: &CommandRequest) -> Result { + std::thread::sleep(self.delay); + Ok(CommandOutput { + status: 0, + stdout: self.output.clone().into_bytes(), + stderr: Vec::new(), + }) + } + } + + fn slow_hosts_source(delay: Duration, background: bool) -> SshHostsSource { + let source = SshHostsSource::new( + SshTargetList::enabled( + vec!["176".into()], + std::env::temp_dir().join("agentview-test-unused.json"), + ), + "ssh", + ); + source.runners.lock().unwrap().insert( + "176".into(), + Arc::new(SlowRunner { + delay, + output: snapshot_fixture(), + }), + ); + if background { + source.in_background() + } else { + source + } + } + + #[test] + fn a_slow_host_does_not_delay_a_dashboard_refresh() { + let source = slow_hosts_source(Duration::from_millis(600), true); + let request = DiscoveryRequest::default(); + + let started = std::time::Instant::now(); + let first = source.discover_with_warnings(&request).unwrap(); + assert!(started.elapsed() < Duration::from_millis(300)); + assert!(first.sessions.is_empty()); + + let deadline = std::time::Instant::now() + Duration::from_secs(5); + loop { + let started = std::time::Instant::now(); + let next = source.discover_with_warnings(&request).unwrap(); + assert!(started.elapsed() < Duration::from_millis(300)); + if next.sessions.len() == 2 { + break; + } + assert!( + std::time::Instant::now() < deadline, + "remote rows never arrived" + ); + std::thread::sleep(Duration::from_millis(50)); + } + } + + #[test] + fn one_shot_discovery_still_waits_for_the_host() { + let source = slow_hosts_source(Duration::from_millis(200), false); + let discovered = source + .discover_with_warnings(&DiscoveryRequest::default()) + .unwrap(); + assert_eq!(discovered.sessions.len(), 2); + } + + fn completed_fixture(host: &str, count: usize) -> String { + let sessions = (0..count) + .map(|index| { + serde_json::json!({ + "id": format!("opencode:host:ses_{host}_{index}"), + "provider_session_id": format!("ses_{host}_{index}"), + "provider": "opencode", + "runtime": {"kind": "host"}, + "kind": "managed", + "name": format!("{host} finished {index}"), + "cwd": "/home/bpang/mywork", + "state": if index == 0 { "working" } else { "completed" }, + "summary": "done", + "raw_state": "managed_server", + "pid": 1000 + index, + "started_at": 1793134692584_u64, + "updated_at": 1793134809515_u64 + index as u64, + "pull_requests": null, + "capabilities": ["inspect"] + }) + }) + .collect::>(); + serde_json::json!({ "sessions": sessions, "warnings": [] }).to_string() + } + + fn fake_host(host: &str, output: String) -> SshHostSource { + let expected = SshHostSource::new(host).ssh_request(); + SshHostSource::with_runner( + host, + Arc::new(FakeRunner { + expected, + output: Mutex::new(Some(CommandOutput { + status: 0, + stdout: output.into_bytes(), + stderr: Vec::new(), + })), + }), + ) + } + + #[test] + fn aggregation_keeps_each_host_completed_budget_and_prefixes_warnings() { + let request = DiscoveryRequest { + include_completed: true, + history_limit: 2, + ..DiscoveryRequest::default() + }; + // Each host reports one working row plus three completed rows, so the + // per-host budget keeps the two newest completed rows per host. + let sources = vec![ + fake_host("176", completed_fixture("a", 4)), + fake_host("177", completed_fixture("b", 4)), + ]; + let merged = aggregate_host_discoveries(&sources, &request).unwrap(); + + assert_eq!(merged.sessions.len(), 6); + let completed = merged + .sessions + .iter() + .filter(|session| session.state == crate::domain::SessionState::Completed) + .count(); + assert_eq!(completed, 4); + assert_eq!(merged.kept.len(), 4); + assert_eq!(merged.warnings.len(), 2); + assert!(merged.warnings[0].starts_with("176 (ssh) completed history is limited")); + assert!(merged.warnings[1].starts_with("177 (ssh) completed history is limited")); + } + + #[test] + fn aggregation_reports_one_unreachable_host_without_losing_the_others() { + let request = DiscoveryRequest { + include_completed: true, + ..DiscoveryRequest::default() + }; + let failing = { + let source = SshHostSource::new("177"); + let expected = source.ssh_request(); + struct Failing { + expected: CommandRequest, + } + impl CommandRunner for Failing { + fn run(&self, request: &CommandRequest) -> Result { + assert_eq!(request, &self.expected); + Ok(CommandOutput { + status: 255, + stdout: Vec::new(), + stderr: b"ssh: connect refused".to_vec(), + }) + } + } + SshHostSource::with_runner("177", Arc::new(Failing { expected })) + }; + let sources = vec![fake_host("176", completed_fixture("a", 2)), failing]; + let merged = aggregate_host_discoveries(&sources, &request).unwrap(); + assert_eq!(merged.sessions.len(), 2); + assert!(merged.warnings.len() == 1 && merged.warnings[0].starts_with("177 (ssh): ")); + } +} diff --git a/src/app.rs b/src/app.rs index 11d8c7f..1de5d5e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -66,6 +66,7 @@ const DASHBOARD_COMMANDS: &[&str] = &[ "/scheduled", "/defer", "/keep", + "/remote", "/filter", "/migrate", "/usage", @@ -87,6 +88,23 @@ pub enum Overlay { Confirm(ConfirmTarget), } +/// Where the next new session starts: a local folder, or a folder on a +/// watched SSH host, which launches the harness there over SSH. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum LaunchDirectory { + Local(PathBuf), + Remote { host: String, path: PathBuf }, +} + +/// One folder offered by the folder picker. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DirectoryChoice { + pub label: String, + pub path: PathBuf, + /// `None` for a local folder; the SSH host name otherwise. + pub host: Option, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CursorMovement { Left, @@ -210,6 +228,9 @@ pub enum AppAction { SetCompletedVisibility { include_completed: bool, }, + /// `/remote add` or `/remote remove` changed the watched SSH hosts; the + /// next refresh discovers the new set. + RemoteHostsChanged, LoadModels { provider: Provider, }, @@ -236,6 +257,9 @@ pub enum AppAction { prompt: String, /// Directory picked in the directory view; `None` uses the launch cwd. cwd: Option, + /// When set, the session starts on that SSH host and `cwd` is a path + /// there. + host: Option, }, Reply { session_id: String, @@ -328,7 +352,7 @@ struct WorkReturn { input_anchor: Option, pasted: PastedParts, native_session: Option, - launch_directory: Option, + launch_directory: Option, } #[derive(Debug)] @@ -367,10 +391,15 @@ pub struct App { pub do_not_remember: ModelMemoryPolicy, /// Ctrl+B is waiting for the model catalog before it switches providers. pending_provider_switch: bool, - /// Directory chosen with `/cd` for the next new session. It wins over the - /// directory view selection and is cleared once a session launches there. - pub launch_directory_override: Option, + /// Directory chosen with `/cd` or the folder picker for the next new + /// session. It wins over the directory view selection and is cleared once + /// a session launches there. A remote choice starts the session on that + /// SSH host. + pub launch_directory_override: Option, pub directory_candidates: Vec, + /// Folders known on watched SSH hosts, offered by the folder picker next + /// to the local ones. Cleared for the move picker, which stays local. + pub remote_directory_candidates: Vec<(String, PathBuf)>, pub directory_filter: String, pub directory_selection: usize, /// Escape returns to the new-task draft when the picker was opened from it. @@ -462,6 +491,10 @@ pub struct App { pub voice: crate::voice::PanelStatus, /// Show the Voice Mode shortcut in the footer: nobody has used it yet. pub voice_hint: bool, + /// Watched SSH hosts, shared with the discovery source so `/remote` takes + /// effect on the next refresh. Empty and frozen until the dashboard + /// installs the real list. + pub ssh_targets: crate::adapters::SshTargetList, } impl App { @@ -524,6 +557,7 @@ impl App { pending_provider_switch: false, launch_directory_override: None, directory_candidates: Vec::new(), + remote_directory_candidates: Vec::new(), directory_filter: String::new(), directory_selection: 0, directory_picker_from_composer: false, @@ -589,6 +623,7 @@ impl App { queue: None, voice: crate::voice::PanelStatus::idle(), voice_hint: false, + ssh_targets: crate::adapters::SshTargetList::disabled(), }; app.rebuild_snapshot_cache(); app.reconcile_selection(); @@ -996,10 +1031,15 @@ impl App { } /// The project directory selected in the directory view, which the header - /// shows and new sessions start in. - pub fn launch_directory(&self) -> Option { + /// shows and new sessions start in. A selection on a watched SSH host + /// starts the next session there. + pub fn launch_directory(&self) -> Option { if let Some(directory) = &self.launch_directory_override { - if self.scope_allows(directory) { + let allowed = match directory { + LaunchDirectory::Local(path) => self.scope_allows(path), + LaunchDirectory::Remote { .. } => !self.work_only, + }; + if allowed { return Some(directory.clone()); } } @@ -1013,21 +1053,27 @@ impl App { .iter() .find(|s| self.scope_allows(&s.cwd)) }) - .map(|s| s.cwd.clone()); + .map(|s| LaunchDirectory::Local(s.cwd.clone())); } if self.view_mode != ViewMode::Directory { return None; } - self.selected_session() - .map(|session| project_group_path(&session.cwd)) - .or_else(|| { - self.selected_group().and_then(|group| { - group - .sessions - .first() - .map(|index| project_group_path(&self.snapshot.sessions[*index].cwd)) - }) + let session = self.selected_session().cloned().or_else(|| { + self.selected_group().and_then(|group| { + group + .sessions + .first() + .map(|index| self.snapshot.sessions[*index].clone()) }) + })?; + let path = project_group_path(&session.cwd); + Some(match &session.runtime { + crate::domain::Runtime::Ssh { host } => LaunchDirectory::Remote { + host: host.clone(), + path, + }, + _ => LaunchDirectory::Local(path), + }) } pub fn activate(&mut self) -> AppAction { @@ -3640,7 +3686,14 @@ impl App { self.pasted = pasted; return self.open_model_picker(); } - let cwd = self.launch_directory(); + let launch_directory = self.launch_directory(); + let (cwd, host) = match &launch_directory { + Some(LaunchDirectory::Remote { host, path }) => { + (Some(path.clone()), Some(host.clone())) + } + Some(LaunchDirectory::Local(path)) => (Some(path.clone()), None), + None => (None, None), + }; self.launch_directory_override = None; let model = self.launch_model.clone(); self.drop_exceptional_model(); @@ -3649,6 +3702,7 @@ impl App { model, prompt: pasted.expand(&input), cwd, + host, }; } let (command, argument) = input @@ -3689,6 +3743,7 @@ impl App { }, "/cd" => self.select_launch_directory(argument), "/completed" => return self.select_completed_visibility(argument), + "/remote" => return self.manage_remote_hosts(argument), // Alternative to ctrl+g, which multiplexers such as Zellij bind // to their own lock mode before agentview can see it. "/hidden" | "/restore" => return AppAction::BrowseHidden, @@ -3787,6 +3842,10 @@ impl App { } else { match self .launch_directory() + .and_then(|directory| match directory { + LaunchDirectory::Local(base) => Some(base), + LaunchDirectory::Remote { .. } => None, + }) .or_else(|| std::env::current_dir().ok()) { Some(base) => base.join(path), @@ -3796,7 +3855,7 @@ impl App { match path.canonicalize() { Ok(directory) if directory.is_dir() => { self.set_notice(format!("next session starts in {}", directory.display())); - self.launch_directory_override = Some(directory); + self.launch_directory_override = Some(LaunchDirectory::Local(directory)); } _ => self.set_notice(format!("{} is not an existing directory", path.display())), } @@ -3809,6 +3868,22 @@ impl App { pub fn open_directory_picker(&mut self) { let home = std::env::var_os("HOME").map(PathBuf::from); self.directory_candidates = directory_candidates(&self.snapshot.sessions, home.as_deref()); + // Folders on the watched SSH hosts, most recent first: the snapshot + // is already sorted by recency, so keep its order and deduplicate. + let mut remote = self + .snapshot + .sessions + .iter() + .filter_map(|session| match &session.runtime { + crate::domain::Runtime::Ssh { host } => { + Some((host.clone(), project_group_path(&session.cwd))) + } + _ => None, + }) + .collect::>(); + let mut seen = BTreeSet::new(); + remote.retain(|pair| seen.insert(pair.clone())); + self.remote_directory_candidates = remote; self.directory_filter.clear(); self.directory_selection = 0; self.directory_picker_from_composer = @@ -3841,14 +3916,18 @@ impl App { } let session_id = session.id.clone(); self.open_directory_picker(); + self.remote_directory_candidates.clear(); self.moving_session = Some(session_id); } /// Candidates matching the search. A typed absolute or `~` path that /// names an existing folder is offered first even when it is not a known - /// candidate. One that names a missing folder inside an existing one is - /// offered first too, and confirming it creates the folder. - pub fn directory_choices(&self) -> Vec { + /// candidate — one that names a missing folder inside an existing one is + /// offered too, and confirming it creates the folder. Local folders come + /// first, then the folders of watched SSH hosts, and a typed + /// `host:/path` for a watched host offers that folder on the host even + /// when nothing has run in it yet. + pub fn directory_choices(&self) -> Vec { let filter = self.directory_filter.trim(); let home = std::env::var_os("HOME").map(PathBuf::from); let typed = expand_typed_directory(filter, home.as_deref()).filter(|path| { @@ -3859,7 +3938,12 @@ impl App { .split_whitespace() .map(str::to_owned) .collect::>(); - let matches = self + let matches_filter = |label: &str| { + terms + .iter() + .all(|term| label.to_lowercase().contains(term.as_str())) + }; + let mut choices = self .directory_candidates .iter() .filter(|path| typed.as_ref() != Some(*path)) @@ -3867,13 +3951,48 @@ impl App { let label = display_directory(path, home.as_deref()).to_lowercase(); terms.iter().all(|term| label.contains(term.as_str())) }) - .cloned(); - typed - .clone() - .into_iter() - .chain(matches) .filter(|path| self.scope_allows(path)) - .collect() + .map(|path| DirectoryChoice { + label: display_directory(path, home.as_deref()), + path: path.clone(), + host: None, + }) + .collect::>(); + if let Some(typed) = typed.filter(|path| self.scope_allows(path)) { + choices.insert( + 0, + DirectoryChoice { + label: display_directory(&typed, home.as_deref()), + path: typed, + host: None, + }, + ); + } + if !self.work_only { + let typed_remote = typed_remote_choice(filter, &self.ssh_targets.hosts()); + if let Some(typed_remote) = &typed_remote { + choices.insert(0, typed_remote.clone()); + } + choices.extend( + self.remote_directory_candidates + .iter() + .filter(|(host, path)| { + let label = remote_directory_label(host, path); + matches_filter(&label) + }) + .filter(|(host, path)| { + !typed_remote.as_ref().is_some_and(|typed| { + typed.host.as_deref() == Some(host.as_str()) && typed.path == *path + }) + }) + .map(|(host, path)| DirectoryChoice { + label: remote_directory_label(host, path), + path: path.clone(), + host: Some(host.clone()), + }), + ); + } + choices } pub fn move_directory_selection(&mut self, delta: isize) { @@ -3898,30 +4017,50 @@ impl App { } fn confirm_directory_selection(&mut self) -> AppAction { - let Some(directory) = self + let Some(choice) = self .directory_choices() .get(self.directory_selection) .cloned() else { return AppAction::None; }; - if !directory.exists() { - if let Err(error) = std::fs::create_dir(&directory) { - self.set_notice(format!("cannot create {}: {error}", directory.display())); + // Confirming a typed folder that does not exist yet creates it — for + // local picks only; a remote folder must exist on its host. + if choice.host.is_none() && !choice.path.exists() { + if let Err(error) = std::fs::create_dir(&choice.path) { + self.set_notice(format!("cannot create {}: {error}", choice.path.display())); return AppAction::None; } } - let directory = directory.canonicalize().unwrap_or(directory); if let Some(session_id) = self.moving_session.clone() { - return self.confirm_move(session_id, directory); + if choice.host.is_some() { + self.set_notice("moving currently supports host sessions only"); + return AppAction::None; + } + return self.confirm_move(session_id, choice.path); } let from_composer = self.directory_picker_from_composer; + let directory = match choice.host { + Some(host) => LaunchDirectory::Remote { + host, + path: choice.path, + }, + None => LaunchDirectory::Local(choice.path.canonicalize().unwrap_or(choice.path)), + }; + self.set_notice(match &directory { + LaunchDirectory::Remote { host, path } => { + format!("next session starts on {host} in {}", path.display()) + } + LaunchDirectory::Local(directory) => { + format!("next session starts in {}", directory.display()) + } + }); self.launch_directory_override = Some(directory); self.directory_filter.clear(); self.directory_candidates.clear(); + self.remote_directory_candidates.clear(); if from_composer { self.overlay = Overlay::Composer(ComposerMode::NewSession); - self.notice = None; } else { self.start_new_session(None); } @@ -4074,6 +4213,64 @@ impl App { AppAction::SetCompletedVisibility { include_completed } } + /// `/remote` lists the watched SSH hosts, `/remote add HOST` and + /// `/remote remove HOST` change the set. The change persists immediately + /// and the next refresh discovers the new set. + fn manage_remote_hosts(&mut self, argument: &str) -> AppAction { + let (verb, rest) = argument + .split_once(char::is_whitespace) + .map_or((argument, ""), |(verb, rest)| (verb, rest.trim())); + match verb.to_ascii_lowercase().as_str() { + "" | "list" => { + let hosts = self.ssh_targets.hosts(); + self.set_notice(if hosts.is_empty() { + "no remote hosts; add one with /remote add HOST".into() + } else { + format!( + "watching {}", + hosts + .iter() + .map(|host| format!("{host} (ssh)")) + .collect::>() + .join(", ") + ) + }); + } + "add" => { + if rest.is_empty() { + self.set_notice("use /remote add HOST"); + return AppAction::None; + } + match self.ssh_targets.insert(rest) { + Ok(true) => { + self.set_notice(format!( + "{rest} (ssh) added; it appears on the next refresh" + )); + return AppAction::RemoteHostsChanged; + } + Ok(false) => self.set_notice(format!("{rest} (ssh) is already watched")), + Err(error) => self.set_notice(format!("{error:#}")), + } + } + "remove" | "rm" => { + if rest.is_empty() { + self.set_notice("use /remote remove HOST"); + return AppAction::None; + } + match self.ssh_targets.remove(rest) { + Ok(true) => { + self.set_notice(format!("{rest} (ssh) removed; gone on the next refresh")); + return AppAction::RemoteHostsChanged; + } + Ok(false) => self.set_notice(format!("{rest} is not a watched host")), + Err(error) => self.set_notice(format!("{error:#}")), + } + } + _ => self.set_notice("use /remote, /remote add HOST, or /remote remove HOST"), + } + AppAction::None + } + fn reconcile_model_selection(&mut self) { let len = self.model_choices().len(); self.model_selection = self.model_selection.min(len.saturating_sub(1)); @@ -4271,6 +4468,36 @@ pub fn display_directory(path: &Path, home: Option<&Path>) -> String { } } +/// A remote folder keeps its absolute remote path and names its host, since +/// the local HOME abbreviation does not apply there. +pub(crate) fn remote_directory_label(host: &str, path: &std::path::Path) -> String { + format!("[{host}] {}", path.display()) +} + +/// A typed `host:/path` for a watched SSH host, offered even when nothing has +/// run in that folder yet: the local typed-path fast path can only offer +/// folders that exist on this machine. +fn typed_remote_choice(filter: &str, hosts: &BTreeSet) -> Option { + let (host, path) = filter.split_once(':')?; + if !hosts.contains(host) { + return None; + } + let path = path.trim(); + if !path.starts_with('/') { + return None; + } + let path = PathBuf::from(path.trim_end_matches('/')); + Some(DirectoryChoice { + label: remote_directory_label(host, &path), + path: if path.as_os_str().is_empty() { + PathBuf::from("/") + } else { + path + }, + host: Some(host.to_owned()), + }) +} + pub(crate) fn project_group_path(path: &std::path::Path) -> PathBuf { let components = path.components().collect::>(); let worktree_marker = components @@ -4388,6 +4615,114 @@ mod tests { } } + fn remote_session(id: &str, host: &str, cwd: &str, state: SessionState) -> AgentSession { + AgentSession { + runtime: Runtime::Ssh { host: host.into() }, + cwd: cwd.into(), + id: format!("ssh:{host}:{id}"), + ..session(id, state) + } + } + + #[test] + fn the_folder_picker_offers_remote_folders_and_launches_on_that_host() { + let remote = remote_session( + "ses_one", + "176", + "/home/bpang/mywork/ns3", + SessionState::Completed, + ); + let mut app = app_with(vec![remote, session("local", SessionState::Completed)]); + app.open_directory_picker(); + + let choices = app.directory_choices(); + let remote_index = choices + .iter() + .position(|choice| choice.host.as_deref() == Some("176")) + .expect("remote folder in the picker"); + assert_eq!( + choices[remote_index].path, + PathBuf::from("/home/bpang/mywork/ns3") + ); + assert!(choices[remote_index].label.starts_with("[176] ")); + assert!(choices.iter().all(|choice| choice.host.is_some() + || choice.path != PathBuf::from("/home/bpang/mywork/ns3"))); + + app.directory_selection = remote_index; + assert_eq!(app.activate(), AppAction::None); + assert_eq!( + app.launch_directory_override, + Some(LaunchDirectory::Remote { + host: "176".into(), + path: PathBuf::from("/home/bpang/mywork/ns3"), + }) + ); + + app.start_new_session(None); + app.input = "fix the sim".into(); + assert_eq!( + app.activate(), + AppAction::Launch { + provider: Provider::Claude, + model: None, + prompt: "fix the sim".into(), + cwd: Some(PathBuf::from("/home/bpang/mywork/ns3")), + host: Some("176".into()), + } + ); + assert_eq!(app.launch_directory_override, None); + } + + #[test] + fn a_remote_directory_view_selection_starts_sessions_on_that_host() { + let remote = remote_session( + "ses_one", + "176", + "/home/bpang/mywork/ns3", + SessionState::Working, + ); + let mut app = app_with(vec![remote]); + app.set_view_mode(ViewMode::Directory); + assert_eq!( + app.launch_directory(), + Some(LaunchDirectory::Remote { + host: "176".into(), + path: PathBuf::from("/home/bpang/mywork/ns3"), + }) + ); + app.start_new_session(None); + app.input = "build".into(); + assert_eq!( + app.activate(), + AppAction::Launch { + provider: Provider::Claude, + model: None, + prompt: "build".into(), + cwd: Some(PathBuf::from("/home/bpang/mywork/ns3")), + host: Some("176".into()), + } + ); + } + + #[test] + fn moving_a_session_offers_no_remote_folders() { + let remote = remote_session( + "ses_one", + "176", + "/home/bpang/mywork/ns3", + SessionState::Completed, + ); + let mut app = app_with(vec![remote, session("local", SessionState::Completed)]); + app.select_and_reveal_session("local"); + app.start_move(); + assert!(app.moving_session.is_some()); + assert!(app.remote_directory_candidates.is_empty()); + assert!(app + .directory_choices() + .iter() + .all(|choice| choice.host.is_none())); + } + #[test] fn work_view_filters_both_lists_and_restores_the_personal_draft() { let dir = tempfile::tempdir().unwrap(); @@ -4420,7 +4755,13 @@ mod tests { assert!(!app.select_and_reveal_session("personal-chat")); } app.directory_candidates = vec![work.clone(), dir.path().join("personal")]; - assert_eq!(app.directory_choices(), vec![work]); + assert_eq!( + app.directory_choices() + .into_iter() + .map(|choice| choice.path) + .collect::>(), + vec![work] + ); app.open_restore_picker(Vec::new()); assert!(app.hidden_choices().iter().all(|r| r.id == "work-chat")); app.set_work_only(false, None); @@ -4573,6 +4914,45 @@ mod tests { .contains(&SelectionKey::Session("opencode:host:ses_parent".into()))); } + #[test] + fn typing_host_path_offers_any_folder_on_a_watched_host() { + let mut app = app_with(vec![]); + app.ssh_targets = crate::adapters::SshTargetList::enabled( + vec!["176".into()], + std::env::temp_dir().join("agentview-test-unused.json"), + ); + app.open_directory_picker(); + app.directory_filter = "176:/extra".into(); + app.directory_selection = 0; + + let choices = app.directory_choices(); + assert_eq!( + choices.first(), + Some(&DirectoryChoice { + label: "[176] /extra".into(), + path: PathBuf::from("/extra"), + host: Some("176".into()), + }) + ); + + // Trailing slashes collapse and the root is accepted. + app.directory_filter = "176:/".into(); + assert_eq!( + app.directory_choices().first().unwrap().path, + PathBuf::from("/") + ); + + // Unwatched hosts and relative paths get nothing. + app.directory_filter = "999:/extra".into(); + assert!(app.directory_choices().is_empty()); + app.directory_filter = "176:extra".into(); + assert!(app.directory_choices().is_empty()); + + // An unknown host prefix never becomes a local typed path either. + app.directory_filter = "999:/etc".into(); + assert!(app.directory_choices().is_empty()); + } + #[test] fn navigation_wraps_across_headers_and_rows() { let mut app = App::new(SessionSnapshot { @@ -6471,7 +6851,10 @@ mod tests { app.start_new_session(None); app.input = "/cd fresh".into(); app.activate(); - assert_eq!(app.launch_directory(), Some(fresh.clone())); + assert_eq!( + app.launch_directory(), + Some(LaunchDirectory::Local(fresh.clone())) + ); app.start_new_session(None); app.input = "task".into(); @@ -6535,12 +6918,22 @@ mod tests { for character in "picker-target".chars() { app.push_input(character); } - assert_eq!(app.directory_choices(), vec![picked.clone()]); + assert_eq!( + app.directory_choices(), + vec![DirectoryChoice { + label: display_directory(&picked, None), + path: picked.clone(), + host: None + }] + ); assert_eq!(app.activate(), AppAction::None); assert_eq!(app.overlay, Overlay::Composer(ComposerMode::NewSession)); assert_eq!(app.input, "fix the bug"); - assert_eq!(app.launch_directory(), Some(picked.clone())); + assert_eq!( + app.launch_directory(), + Some(LaunchDirectory::Local(picked.clone())) + ); assert!(matches!( app.activate(), AppAction::Launch { cwd: Some(cwd), .. } if cwd == picked @@ -6570,10 +6963,15 @@ mod tests { for character in typed.display().to_string().chars() { app.push_input(character); } - assert_eq!(app.directory_choices().first(), Some(&typed)); + assert_eq!( + app.directory_choices() + .first() + .map(|choice| choice.path.clone()), + Some(typed.clone()) + ); app.activate(); assert_eq!(app.overlay, Overlay::Composer(ComposerMode::NewSession)); - assert_eq!(app.launch_directory(), Some(typed)); + assert_eq!(app.launch_directory(), Some(LaunchDirectory::Local(typed))); } #[test] @@ -6588,12 +6986,22 @@ mod tests { for character in created.display().to_string().chars() { app.push_input(character); } - assert_eq!(app.directory_choices().first(), Some(&created)); + assert_eq!( + app.directory_choices().first(), + Some(&DirectoryChoice { + label: display_directory(&created, None), + path: created.clone(), + host: None, + }) + ); assert!(!created.exists()); app.activate(); assert!(created.is_dir()); - assert_eq!(app.launch_directory(), Some(created)); + assert_eq!( + app.launch_directory(), + Some(LaunchDirectory::Local(created)) + ); } #[test] @@ -7112,6 +7520,7 @@ mod tests { model: None, prompt: "build it".into(), cwd: None, + host: None, } ); @@ -7482,6 +7891,7 @@ mod tests { model: Some("opus".into()), prompt: "ship it".into(), cwd: None, + host: None, } ); @@ -7726,7 +8136,6 @@ mod tests { #[test] fn completed_command_requests_toggle_or_explicit_visibility_without_guessing() { let mut app = App::with_completed_visibility(SessionSnapshot::default(), false); - app.start_new_session(None); app.input = "/completed".into(); assert_eq!( @@ -7756,6 +8165,109 @@ mod tests { assert!(app.notice.as_deref().unwrap().contains("/completed show")); } + #[test] + fn remote_command_lists_adds_and_removes_ssh_hosts() { + let mut app = App::new(SessionSnapshot::default()); + app.start_new_session(None); + app.input = "/remote".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("no remote hosts; add one with /remote add HOST")); + + // A plain App has a frozen list, so changes are refused. + app.start_new_session(None); + app.input = "/remote add 177".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("remote hosts are disabled")); + + // An enabled list accepts adds, deduplicates, and persists them. + let directory = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)) + .unwrap(); + } + let registry = directory.path().join("ssh-targets.json"); + app.ssh_targets = crate::adapters::SshTargetList::enabled(Vec::new(), registry.clone()); + + app.start_new_session(None); + app.input = "/remote add 177".into(); + assert_eq!(app.activate(), AppAction::RemoteHostsChanged); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("177 (ssh) added; it appears on the next refresh")); + assert_eq!( + crate::adapters::load_ssh_targets_at(®istry) + .unwrap() + .hosts, + ["177".to_owned()].into_iter().collect() + ); + + app.start_new_session(None); + app.input = "/remote add 177".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("177 (ssh) is already watched")); + + app.start_new_session(None); + app.input = "/remote".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app.notice.as_deref().unwrap().contains("watching 177")); + + app.start_new_session(None); + app.input = "/remote remove 177".into(); + assert_eq!(app.activate(), AppAction::RemoteHostsChanged); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("177 (ssh) removed; gone on the next refresh")); + assert!(crate::adapters::load_ssh_targets_at(®istry) + .unwrap() + .hosts + .is_empty()); + + app.start_new_session(None); + app.input = "/remote remove 177".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("177 is not a watched host")); + + app.start_new_session(None); + app.input = "/remote update 177".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("use /remote, /remote add HOST")); + + app.start_new_session(None); + app.input = "/remote add not a host".into(); + assert_eq!(app.activate(), AppAction::None); + assert!(app + .notice + .as_deref() + .unwrap() + .contains("SSH target contains unsupported characters")); + } + #[test] fn model_picker_loads_filters_pages_and_preserves_the_task_draft() { let mut app = App::with_launch_targets( diff --git a/src/control.rs b/src/control.rs index 018186d..9a69ab9 100644 --- a/src/control.rs +++ b/src/control.rs @@ -20,7 +20,9 @@ use crate::domain::{ SessionState, }; use crate::migration::MigrationRegistry; -use crate::process::{CommandRequest, CommandRunner, ProcessRunner}; +use crate::process::{ + CancellableProcessRunner, CommandOutput, CommandRequest, CommandRunner, ProcessRunner, +}; #[derive(Clone, Debug, Eq, PartialEq)] pub struct LaunchRequest { @@ -109,6 +111,7 @@ pub struct ControlHubConfig { pub claude_bin: String, pub codex_bin: String, pub docker_bin: String, + pub ssh_bin: String, pub launch_provider: Provider, pub launch_cwd: PathBuf, pub provider_io_enabled: bool, @@ -371,6 +374,7 @@ pub struct ControlHub { launch_cwd: PathBuf, provider_io_enabled: bool, yolo: bool, + ssh_bin: String, migration_registry: Option, /// A fixture's stand-in harnesses, models and past sessions. fixture_demo: Option>, @@ -426,6 +430,7 @@ impl ControlHub { launch_cwd: config.launch_cwd, provider_io_enabled: config.provider_io_enabled, yolo: config.yolo, + ssh_bin: config.ssh_bin, migration_registry: None, fixture_demo: None, }) @@ -679,7 +684,7 @@ impl ControlHub { } pub fn launch(&self, prompt: String) -> Result { - self.launch_with(self.launch_provider.clone(), None, prompt, None) + self.launch_with(self.launch_provider.clone(), None, prompt, None, None) } fn resolve_launch_cwd(&self, cwd: Option) -> Result { @@ -701,7 +706,11 @@ impl ControlHub { model: Option, prompt: String, cwd: Option, + host: Option, ) -> Result { + if let Some(host) = host { + return self.launch_remote(provider, model, prompt, cwd, &host); + } self.ensure_provider_io()?; let controller = self.controller(&provider)?; let model = validate_model(model)?; @@ -739,7 +748,11 @@ impl ControlHub { model: Option, prompt: String, cwd: Option, + host: Option, ) -> Result { + if let Some(host) = host { + return self.launch_remote(provider, model, prompt, cwd, &host); + } self.ensure_provider_io()?; let controller = self.controller(&provider)?; let model = validate_model(model)?; @@ -771,6 +784,97 @@ impl ControlHub { } } + /// Start a fresh provider session on a watched SSH host: hand the + /// terminal to the provider's own TUI there. Model picks and permission + /// bypass are local-only; the typed task is sent only by harnesses whose + /// CLI takes it as an argument (Claude and Codex). + fn launch_remote( + &self, + provider: Provider, + model: Option, + prompt: String, + cwd: Option, + host: &str, + ) -> Result { + self.ensure_provider_io()?; + let program = match provider { + Provider::Claude => "claude", + Provider::OpenCode => "opencode", + Provider::Codex => "codex", + other => bail!("starting {} on {host} is not supported", other.label()), + }; + if model.is_some() { + bail!( + "model selection is local-only; starting {program} on {host} uses its default model" + ); + } + if self.yolo { + bail!( + "permission bypass is local-only; restart without --yolo to start sessions on {host}" + ); + } + let label = provider.label(); + // A remote OpenCode launch with a task goes through that host's own + // agentview supervisor, so the session is managed there: it shows as + // Completed when idle and both dashboards agree. Hosts running an + // agentview without the subcommand fall back to the interactive TUI. + if provider == Provider::OpenCode && !prompt.trim().is_empty() && cwd.is_some() { + let request = remote_managed_launch_command( + host, + prompt.trim(), + cwd.as_deref().unwrap(), + &self.ssh_bin, + ); + let output = CancellableProcessRunner::default().run(&request)?; + if output.status == 0 { + let (id, title) = parse_remote_managed_launch(&output.stdout)?; + return Ok(ControlOutcome { + message: format!("started managed OpenCode session {title} on {host}"), + provider_session_hint: Some(id), + }); + } + if !managed_launch_unavailable(&output) { + bail!( + "managed OpenCode launch on {host} failed: {}", + output.stderr_lossy() + ); + } + } + // OpenCode's positional is a project path and `--prompt` only + // pre-fills its editor, so the task is typed into the PTY once the + // empty editor is on screen — over SSH exactly as locally. Claude and + // Codex take the task as their first argument. + let exit = if provider == Provider::OpenCode && !prompt.trim().is_empty() { + let command = remote_launch_command(provider.clone(), "", cwd, host, &self.ssh_bin)?; + let initial_input = format!("\x1b[200~{}\x1b[201~\r", prompt.trim()).into_bytes(); + crate::native_session::run_with_initial_input_after_screen( + command, + &format!("ssh:{host}:launch:{label}"), + &initial_input, + crate::adapters::OPENCODE_READY_MARKER, + )? + } else { + let command = + remote_launch_command(provider.clone(), &prompt, cwd, host, &self.ssh_bin)?; + crate::native_session::run(command, &format!("ssh:{host}:launch:{label}"))? + }; + match exit { + crate::native_session::NativeSessionExit::Backgrounded => Ok(ControlOutcome { + message: format!("backgrounded {label} on {host}"), + provider_session_hint: None, + }), + crate::native_session::NativeSessionExit::Exited(status) if status.success() => { + Ok(ControlOutcome { + message: format!("returned from {label} on {host}"), + provider_session_hint: None, + }) + } + crate::native_session::NativeSessionExit::Exited(status) => { + bail!("{label} on {host} exited with status {status}") + } + } + } + pub fn interrupt(&self, session: &AgentSession) -> Result { self.ensure_provider_io()?; if !session.capabilities.contains(&Capability::Interrupt) { @@ -784,6 +888,9 @@ impl ControlHub { if !session.capabilities.contains(&Capability::Inspect) { bail!("inspection authority was not granted for this session"); } + if let Runtime::Ssh { host } = &session.runtime { + return inspect_remote(session, host, &self.ssh_bin); + } self.controller(&session.provider)?.inspect(session) } @@ -903,6 +1010,27 @@ impl ControlHub { pub fn open(&self, session: &AgentSession) -> Result { PREVIEW_GENERATION.fetch_add(1, Ordering::SeqCst); self.ensure_provider_io()?; + if let Runtime::Ssh { host: _ } = &session.runtime { + if session.provider == Provider::OpenCode { + // Prefer the host's agentview attach; hosts running an older + // agentview reject the subcommand with clap's exit code 2 and + // the direct TUI is used instead. + let attach = remote_open_command(session, &self.ssh_bin, true); + let outcome = match attach { + Ok(command) => run_interactive(command, session), + Err(error) => Err(error), + }; + return match outcome { + Err(error) if is_remote_attach_fallback_error(&error) => { + let command = remote_open_command(session, &self.ssh_bin, false)?; + run_interactive(command, session) + } + other => other, + }; + } + let command = remote_open_command(session, &self.ssh_bin, false)?; + return run_interactive(command, session); + } let controller = self.controller(&session.provider)?; if self .migration_registry @@ -1476,6 +1604,9 @@ impl ProviderController for ClaudeController { short_claude_id(&session.provider_session_id), ], ), + Runtime::Ssh { host } => { + bail!("Claude session runs on remote host {host}") + } }; request.timeout = Duration::from_secs(8); read_command_output(&self.runner.run(&request)?, "Claude logs") @@ -1541,6 +1672,9 @@ impl ProviderController for ClaudeController { ]); run_interactive(command, session) } + Runtime::Ssh { host } => { + bail!("Claude session runs on remote host {host}") + } } } } @@ -1700,7 +1834,7 @@ impl ProviderController for CodexController { } fn inspect(&self, session: &AgentSession) -> Result { - match session.runtime { + match &session.runtime { Runtime::Host => self .supervisor .as_ref() @@ -1709,6 +1843,9 @@ impl ProviderController for CodexController { Runtime::Docker { .. } => { bail!("Docker Codex transcript inspection is observe-only") } + Runtime::Ssh { host } => { + bail!("Codex session runs on remote host {host}") + } } } @@ -1845,6 +1982,9 @@ impl ProviderController for CodexController { ]); command } + Runtime::Ssh { host } => { + bail!("Codex session runs on remote host {host}") + } }; if yolo { run_interactive_yolo(command, session, "Codex") @@ -2093,6 +2233,7 @@ fn runtime_key(runtime: &Runtime) -> String { match runtime { Runtime::Host => "host".into(), Runtime::Docker { container_id, .. } => format!("docker:{container_id}"), + Runtime::Ssh { host } => format!("ssh:{host}"), } } @@ -2173,6 +2314,295 @@ fn short_claude_id(provider_session_id: &str) -> String { provider_session_id.chars().take(8).collect() } +/// Build the SSH command that hands the terminal to one provider-native +/// session on a remote host. The provider binary resolves through the same +/// PATH augmentation discovery uses, the working directory is restored first, +/// and every value is quoted because ssh joins the remote command into one +/// shell line. +fn remote_open_command( + session: &AgentSession, + ssh_bin: &str, + prefer_agentview: bool, +) -> Result { + let Runtime::Ssh { host } = &session.runtime else { + bail!("session is not on a remote SSH host"); + }; + let (program, arguments) = match &session.provider { + Provider::Claude => { + if session.raw_state.as_deref() + == Some(crate::adapters::claude_history::HISTORY_RAW_STATE) + { + // No process runs an ended session to attach to, and Claude + // finds a transcript only from the folder it was started in. + ( + "claude", + vec![ + "--resume".to_string(), + remote_shell_quote(&session.provider_session_id), + ], + ) + } else { + ( + "claude", + vec![ + "attach".to_string(), + remote_shell_quote(&short_claude_id(&session.provider_session_id)), + ], + ) + } + } + // Attaching through the host's own agentview keeps the TUI on the + // supervisor's server, so turns typed there stay visible to managed + // discovery; a direct TUI would run on its own server instance. + Provider::OpenCode if prefer_agentview => ( + "agentview", + vec![ + "opencode".to_string(), + "attach".to_string(), + remote_shell_quote(&session.provider_session_id), + "--cwd".to_string(), + remote_shell_quote(&session.cwd.display().to_string()), + ], + ), + Provider::OpenCode => ( + "opencode", + vec![ + "--session".to_string(), + remote_shell_quote(&session.provider_session_id), + ], + ), + Provider::Codex => ( + "codex", + vec![ + "resume".to_string(), + remote_shell_quote(&session.provider_session_id), + ], + ), + other => bail!( + "jumping into a {} session on {host} is not supported; open it on the host", + other.label() + ), + }; + // Values stay quoted; the PATH export resolves provider binaries the way + // a non-interactive remote shell cannot, and the TMPDIR export covers + // hosts whose /tmp is mounted noexec, where Bun-CLI renderers (OpenCode) + // cannot map their libraries from /tmp. + let remote = format!( + "mkdir -p \"$HOME/.tmp\"; export TMPDIR=\"${{TMPDIR:-$HOME/.tmp}}\"; {}; cd {} && {} {}", + crate::adapters::ssh_remote::REMOTE_PATH_PREFIX, + remote_shell_quote(&session.cwd.display().to_string()), + program, + arguments.join(" ") + ); + Ok(ssh_interactive_command(host, remote, ssh_bin)) +} + +/// The SSH command that asks the remote host's own agentview to start one +/// managed OpenCode session: created on the supervisor's server, ownership +/// recorded before the turn starts, so the host's dashboard and this one both +/// see it as a managed session. +fn remote_managed_launch_command( + host: &str, + prompt: &str, + cwd: &std::path::Path, + ssh_bin: &str, +) -> CommandRequest { + let remote = format!( + "mkdir -p \"$HOME/.tmp\"; export TMPDIR=\"${{TMPDIR:-$HOME/.tmp}}\"; {}; agentview opencode launch {} --cwd {}", + crate::adapters::ssh_remote::REMOTE_PATH_PREFIX, + remote_shell_quote(prompt), + remote_shell_quote(&cwd.display().to_string()), + ); + let mut request = CommandRequest::new( + ssh_bin, + vec![ + "-o".into(), + "BatchMode=yes".into(), + "-o".into(), + "ConnectTimeout=10".into(), + host.into(), + remote, + ], + ); + request.timeout = Duration::from_secs(30); + request +} + +/// `(provider session id, title)` from the remote launch's JSON output. +fn parse_remote_managed_launch(stdout: &[u8]) -> Result<(String, String)> { + #[derive(serde::Deserialize)] + struct Created { + id: String, + #[serde(default)] + title: String, + } + let created: Created = serde_json::from_slice(stdout) + .context("the remote agentview launch returned no managed session")?; + Ok((created.id, created.title)) +} + +/// Whether the remote host's agentview cannot start managed sessions at all +/// (an older agentview without the subcommand, or no agentview on PATH), which +/// is worth a fallback rather than a failure. +fn managed_launch_unavailable(output: &CommandOutput) -> bool { + output.status == 127 || output.stderr_lossy().contains("unrecognized subcommand") +} + +/// One interactive SSH command: force a remote PTY, never prompt, fail fast on +/// unreachable hosts, and pass the whole remote command as one shell line. +fn ssh_interactive_command(host: &str, remote: String, ssh_bin: &str) -> Command { + let mut command = Command::new(ssh_bin); + command.args([ + "-t".to_string(), + "-o".to_string(), + "BatchMode=yes".to_string(), + "-o".to_string(), + "ConnectTimeout=10".to_string(), + host.to_string(), + "--".to_string(), + remote, + ]); + command +} + +/// The SSH command that starts a fresh provider TUI on a remote host: restore +/// the chosen directory first, then start the harness. OpenCode's positional +/// is a project path, not a task, so its typed draft is never auto-sent; +/// Claude and Codex take the task as their first argument. +fn remote_launch_command( + provider: Provider, + prompt: &str, + cwd: Option, + host: &str, + ssh_bin: &str, +) -> Result { + let program = match provider { + Provider::Claude => "claude", + Provider::OpenCode => "opencode", + Provider::Codex => "codex", + other => bail!("starting {} on {host} is not supported", other.label()), + }; + let arguments = match provider { + Provider::OpenCode => Vec::new(), + _ if prompt.trim().is_empty() => Vec::new(), + _ => vec![remote_shell_quote(prompt.trim())], + }; + let program_line = if arguments.is_empty() { + program.to_string() + } else { + format!("{} {}", program, arguments.join(" ")) + }; + let command_line = match cwd.as_deref() { + Some(directory) => format!( + "cd {} && {}", + remote_shell_quote(&directory.display().to_string()), + program_line + ), + None => program_line, + }; + let remote = format!( + "mkdir -p \"$HOME/.tmp\"; export TMPDIR=\"${{TMPDIR:-$HOME/.tmp}}\"; {}; {}", + crate::adapters::ssh_remote::REMOTE_PATH_PREFIX, + command_line + ); + Ok(ssh_interactive_command(host, remote, ssh_bin)) +} + +/// Quote one token for the remote shell that ssh hands the command to. +fn remote_shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + +/// Clap rejects an unknown subcommand with exit status 2, which is the one +/// recoverable way an older remote agentview refuses `opencode attach`. +fn is_remote_attach_fallback_error(error: &anyhow::Error) -> bool { + error.to_string().contains("exited with status 2") +} + +/// The SSH command that reads one OpenCode session's transcript on a remote +/// host. `opencode export` truncates at 64 KiB when stdout is a pipe, so the +/// export lands in a temp file first and a bounded tail is returned; the +/// newest messages sit at the end. +fn remote_inspect_command( + session: &AgentSession, + host: &str, + ssh_bin: &str, +) -> Result { + if session.provider != Provider::OpenCode { + bail!( + "remote transcript inspection is not supported for {} yet; read it on {host}", + session.provider.label() + ); + } + let file = "\"$HOME/.tmp/agentview-inspect.json\""; + let remote = format!( + "mkdir -p \"$HOME/.tmp\"; export TMPDIR=\"${{TMPDIR:-$HOME/.tmp}}\"; {}; \ + opencode export {} > {file} && {{ size=$(wc -c < {file}); \ + if [ \"$size\" -le 400000 ]; then cat {file}; else tail -c 400000 {file}; fi; }}; \ + status=$?; rm -f {file}; exit $status", + crate::adapters::ssh_remote::REMOTE_PATH_PREFIX, + remote_shell_quote(&session.provider_session_id), + ); + let mut request = CommandRequest::new( + ssh_bin, + vec![ + "-o".into(), + "BatchMode=yes".into(), + "-o".into(), + "ConnectTimeout=10".into(), + host.into(), + remote, + ], + ); + request.timeout = Duration::from_secs(60); + Ok(request) +} + +/// Parse the remote export. A bounded tail of a larger export starts and ends +/// mid-document, so the complete trailing messages are recovered by cutting at +/// the message boundaries OpenCode's pretty printer emits. The salvage runs on +/// the whole text: a tail fragment's first `{` usually sits inside a nested +/// object, past the boundary it needs. +fn parse_remote_export(stdout: &[u8]) -> Result { + let text = String::from_utf8_lossy(stdout); + if let Some(start) = text.find('{') { + if let Ok(value) = serde_json::from_str::(&text[start..]) { + return Ok(value); + } + } + let message_starts = text + .match_indices("\n {") + .map(|(index, _)| index + 1) + .collect::>(); + let first = *message_starts + .first() + .context("the remote transcript tail held no complete OpenCode message")?; + let Some(last_close) = text[first..].rfind("\n }") else { + bail!("the remote transcript tail held no complete OpenCode message"); + }; + let slice = text[first..first + last_close + "\n }".len()].trim_end_matches(','); + let wrapped = format!("{{\"messages\": [{slice}\n ]}}"); + serde_json::from_str(&wrapped).context("could not parse the remote transcript tail") +} + +/// Read one remote session's transcript for the Peek panel. OpenCode sessions +/// export through the host's own CLI; other providers are refused for now. +fn inspect_remote(session: &AgentSession, host: &str, ssh_bin: &str) -> Result { + let request = remote_inspect_command(session, host, ssh_bin)?; + let output = CancellableProcessRunner::default().run(&request)?; + if output.status != 0 { + bail!( + "transcript read on {host} exited with status {status}: {stderr}", + status = output.status, + stderr = output.stderr_lossy() + ); + } + let value = parse_remote_export(&output.stdout)?; + let messages = value.get("messages").unwrap_or(&value); + crate::opencode_supervisor::render_messages(messages) + .or_else(|_| crate::opencode_supervisor::render_messages(&value)) +} + fn is_interruptible_claude_session(session: &AgentSession) -> bool { session.provider == Provider::Claude && session.runtime == Runtime::Host @@ -2411,6 +2841,7 @@ mod tests { launch_cwd: PathBuf::from("/work"), provider_io_enabled: true, yolo: false, + ssh_bin: "ssh".into(), migration_registry: None, fixture_demo: None, }; @@ -2828,6 +3259,7 @@ exit 0 launch_cwd: directory.path().into(), provider_io_enabled: false, yolo: false, + ssh_bin: "ssh".into(), migration_registry: None, fixture_demo: None, }; @@ -2885,6 +3317,7 @@ exit 0 launch_cwd: PathBuf::from("/work"), provider_io_enabled: true, yolo: false, + ssh_bin: "ssh".into(), migration_registry: None, fixture_demo: None, } @@ -3148,9 +3581,15 @@ exit 0 }] ); assert_eq!( - hub.launch_with(Provider::Pi, Some("custom".into()), "prompt".into(), None) - .unwrap_err() - .to_string(), + hub.launch_with( + Provider::Pi, + Some("custom".into()), + "prompt".into(), + None, + None, + ) + .unwrap_err() + .to_string(), "Pi does not expose model selection" ); @@ -3190,7 +3629,7 @@ exit 0 .unwrap(); let error = hub - .launch_with(Provider::Pi, None, "safe prompt".into(), None) + .launch_with(Provider::Pi, None, "safe prompt".into(), None, None) .unwrap_err() .to_string(); @@ -3273,4 +3712,317 @@ exit 0 capabilities: BTreeSet::new(), } } + + fn remote_session(provider: Provider, raw_state: Option<&str>) -> AgentSession { + AgentSession { + runtime: Runtime::Ssh { host: "176".into() }, + provider, + provider_session_id: "11111111-2222-3333-4444-555555555555".into(), + raw_state: raw_state.map(str::to_owned), + cwd: PathBuf::from("/home/bpang/my work"), + ..session("11111111") + } + } + + fn command_argv(command: &Command) -> Vec { + #[cfg(unix)] + { + command + .get_args() + .map(|argument| argument.to_string_lossy().into_owned()) + .collect() + } + #[cfg(not(unix))] + { + Vec::new() + } + } + + fn remote_command_line(inner: &str) -> String { + format!( + "mkdir -p \"$HOME/.tmp\"; export TMPDIR=\"${{TMPDIR:-$HOME/.tmp}}\"; {}; {}", + crate::adapters::ssh_remote::REMOTE_PATH_PREFIX, + inner + ) + } + + #[test] + #[cfg(unix)] + fn remote_open_attaches_a_live_claude_session_over_ssh() { + let command = remote_open_command( + &remote_session(Provider::Claude, Some("working")), + "ssh", + false, + ) + .unwrap(); + assert_eq!(command.get_program().to_string_lossy(), "ssh"); + assert_eq!( + command_argv(&command), + vec![ + "-t", + "-o", + "BatchMode=yes", + "-o", + "ConnectTimeout=10", + "176", + "--", + remote_command_line("cd '/home/bpang/my work' && claude attach '11111111'") + .as_str(), + ] + ); + } + + #[test] + #[cfg(unix)] + fn remote_open_resumes_an_ended_claude_session() { + let command = remote_open_command( + &remote_session( + Provider::Claude, + Some(crate::adapters::claude_history::HISTORY_RAW_STATE), + ), + "ssh", + false, + ) + .unwrap(); + let last = command_argv(&command).pop().unwrap(); + assert_eq!( + last, + remote_command_line( + "cd '/home/bpang/my work' && claude --resume '11111111-2222-3333-4444-555555555555'" + ) + ); + } + + #[test] + #[cfg(unix)] + fn remote_open_resumes_opencode_and_codex_sessions() { + let session_id = "11111111-2222-3333-4444-555555555555"; + let opencode = + remote_open_command(&remote_session(Provider::OpenCode, None), "ssh", true).unwrap(); + assert_eq!( + command_argv(&opencode).pop().unwrap(), + remote_command_line(&format!( + "cd '/home/bpang/my work' && agentview opencode attach '{session_id}' --cwd '/home/bpang/my work'" + )) + ); + let plain = + remote_open_command(&remote_session(Provider::OpenCode, None), "ssh", false).unwrap(); + assert_eq!( + command_argv(&plain).pop().unwrap(), + remote_command_line(&format!( + "cd '/home/bpang/my work' && opencode --session '{session_id}'" + )) + ); + let codex = + remote_open_command(&remote_session(Provider::Codex, None), "ssh", false).unwrap(); + assert_eq!( + command_argv(&codex).pop().unwrap(), + remote_command_line(&format!( + "cd '/home/bpang/my work' && codex resume '{session_id}'" + )) + ); + } + + #[test] + fn remote_open_refuses_unsupported_providers() { + let error = remote_open_command(&remote_session(Provider::Terminal, None), "ssh", false) + .unwrap_err(); + assert!( + error.to_string().contains("not supported"), + "unexpected error: {error:#}" + ); + } + + #[test] + fn remote_shell_quote_survives_embedded_quotes() { + assert_eq!(remote_shell_quote("a'b"), "'a'\\''b'"); + } + + fn launch_command_argv(provider: Provider, prompt: &str, cwd: Option) -> Vec { + let command = remote_launch_command(provider, prompt, cwd, "176", "ssh").unwrap(); + command + .get_args() + .map(|argument| argument.to_string_lossy().into_owned()) + .collect() + } + + #[test] + fn remote_launch_starts_claude_with_the_typed_task_in_the_picked_folder() { + let argv = launch_command_argv( + Provider::Claude, + "fix the sim", + Some(PathBuf::from("/home/bpang/my work")), + ); + assert_eq!(argv.first().unwrap(), "-t"); + assert_eq!(argv.get(5).unwrap(), "176"); + let remote = argv.last().unwrap(); + assert!(remote.starts_with("mkdir -p \"$HOME/.tmp\"; export TMPDIR=")); + assert!(remote.contains("export PATH=\"$HOME/.local/bin:$HOME/.opencode/bin:")); + assert!(remote.ends_with("cd '/home/bpang/my work' && claude 'fix the sim'")); + } + + #[test] + fn remote_launch_opens_opencode_without_sending_the_task() { + let remote = launch_command_argv(Provider::OpenCode, "fix it", None) + .pop() + .unwrap(); + assert!(remote.ends_with("opencode"), "{remote}"); + } + + #[test] + fn remote_launch_codex_sends_the_task_and_an_empty_prompt_starts_plain() { + let remote = launch_command_argv(Provider::Codex, "ship it", None) + .pop() + .unwrap(); + assert!(remote.ends_with("codex 'ship it'"), "{remote}"); + let remote = launch_command_argv(Provider::Claude, " ", None) + .pop() + .unwrap(); + assert!(remote.ends_with("claude"), "{remote}"); + } + + #[test] + fn remote_launch_refuses_unsupported_harnesses() { + let error = remote_launch_command(Provider::Terminal, "", None, "176", "ssh").unwrap_err(); + assert!( + error.to_string().contains("not supported"), + "unexpected error: {error:#}" + ); + } + + #[test] + fn remote_managed_launch_asks_the_host_agentview_to_start_the_session() { + use std::path::Path; + let request = remote_managed_launch_command( + "176", + "check hostname", + Path::new("/home/bpang/my work"), + "ssh", + ); + assert_eq!(request.program, "ssh"); + assert_eq!( + request.args[..6], + [ + "-o", + "BatchMode=yes", + "-o", + "ConnectTimeout=10", + "176", + "mkdir -p \"$HOME/.tmp\"; export TMPDIR=\"${TMPDIR:-$HOME/.tmp}\"; export PATH=\"$HOME/.local/bin:$HOME/.opencode/bin:$HOME/.npm-global/bin:$HOME/.bun/bin:$HOME/bin:$PATH\"; agentview opencode launch 'check hostname' --cwd '/home/bpang/my work'" + ] + ); + assert_eq!(request.timeout, Duration::from_secs(30)); + } + + #[test] + fn remote_managed_launch_output_parses_to_id_and_title() { + let (id, title) = parse_remote_managed_launch( + br#"{ + "id": "ses_new", + "cwd": "/work", + "title": "check hostname", + "summary": "check hostname", + "state": "working", + "raw_state": "managed_server", + "server_pid": 42, + "created_at_ms": 1, + "updated_at_ms": 2 +}"#, + ) + .unwrap(); + assert_eq!(id, "ses_new"); + assert_eq!(title, "check hostname"); + assert!(parse_remote_managed_launch(b"not json").is_err()); + } + + #[test] + fn only_an_older_agentview_falls_back_from_the_managed_launch() { + let unavailable = CommandOutput { + status: 2, + stdout: Vec::new(), + stderr: b"error: unrecognized subcommand 'launch'".to_vec(), + }; + assert!(managed_launch_unavailable(&unavailable)); + let missing = CommandOutput { + status: 127, + stdout: Vec::new(), + stderr: b"agentview: command not found".to_vec(), + }; + assert!(managed_launch_unavailable(&missing)); + let failed = CommandOutput { + status: 1, + stdout: Vec::new(), + stderr: b"the OpenCode launch prompt cannot be empty".to_vec(), + }; + assert!(!managed_launch_unavailable(&failed)); + } + + fn export_fixture() -> String { + serde_json::json!({ + "info": {"id": "ses_x", "title": "Install GitLab CE"}, + "messages": [ + {"info": {"role": "user"}, "parts": [{"type": "text", "text": "install gitlab"}]}, + {"info": {"role": "assistant"}, "parts": [ + {"type": "tool", "state": {"status": "completed"}}, + {"type": "text", "text": "docker compose up -d\nGitLab CE is running"} + ]}, + {"info": {"role": "user"}, "parts": [{"type": "text", "text": "now check the logs"}]} + ] + }) + .to_string() + } + + #[test] + fn remote_inspect_renders_the_transcript_text() { + let transcript = parse_remote_export(export_fixture().as_bytes()).unwrap(); + let rendered = + crate::opencode_supervisor::render_messages(transcript.get("messages").unwrap()) + .unwrap(); + assert!(rendered.contains("User: install gitlab")); + assert!(rendered.contains("Assistant: docker compose up -d")); + assert!(!rendered.contains("tool")); + } + + #[test] + fn remote_inspect_salvages_a_truncated_tail() { + // OpenCode's export is pretty-printed: message objects open at a + // four-space indent, which is what the tail salvage cuts at. + let full = serde_json::to_string_pretty( + &serde_json::from_str::(&export_fixture()).unwrap(), + ) + .unwrap(); + // Cut into the middle of the second message: the tail holds only the + // last complete message plus the trailing close of the document. + let cut = full.find("GitLab CE is running").unwrap() + 8; + let tail = &full[cut..]; + let transcript = parse_remote_export(tail.as_bytes()).unwrap(); + let rendered = + crate::opencode_supervisor::render_messages(transcript.get("messages").unwrap()) + .unwrap(); + assert!(rendered.contains("User: now check the logs"), "{rendered}"); + assert!(!rendered.contains("install gitlab"), "{rendered}"); + } + + #[test] + fn remote_insight_command_reads_a_bounded_tail_through_a_temp_file() { + use std::path::Path; + let session = remote_session(Provider::OpenCode, None); + let request = remote_inspect_command(&session, "176", "ssh").unwrap(); + let remote = request.args.last().unwrap(); + assert!(remote.contains("opencode export '11111111-2222-3333-4444-555555555555' > \"$HOME/.tmp/agentview-inspect.json\"")); + assert!(remote.contains("cat") && remote.contains("tail -c 400000")); + assert!(remote.contains("rm -f \"$HOME/.tmp/agentview-inspect.json\"")); + assert_eq!(request.args.get(4).unwrap(), "176"); + let _ = Path::new("unused"); + } + + #[test] + fn remote_inspect_refuses_other_providers() { + let error = remote_inspect_command(&remote_session(Provider::Claude, None), "176", "ssh") + .unwrap_err(); + assert!( + error.to_string().contains("not supported for Claude"), + "unexpected error: {error:#}" + ); + } } diff --git a/src/domain.rs b/src/domain.rs index be957cc..0688839 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -122,6 +122,12 @@ pub enum Runtime { container_name: String, image: String, }, + /// A passwordless SSH host that runs its own agentview, whose snapshot + /// this dashboard merges. `Enter` hands the terminal to the provider's + /// own attach or resume on that host; other control stays local. + Ssh { + host: String, + }, } /// How the provider reports the session's execution style. @@ -139,6 +145,7 @@ impl Runtime { match self { Self::Host => "host", Self::Docker { container_name, .. } => container_name, + Self::Ssh { host } => host, } } } diff --git a/src/main.rs b/src/main.rs index d27b5f4..84ed0c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,15 +9,16 @@ use clap::{Parser, Subcommand, ValueEnum}; use agentview::adapters::{ default_cursor_versions_dir, default_managed_docker_registry_path, default_pi_session_dir, - generate_managed_instance_id, AntigravityController, AntigravityOwnership, AntigravitySource, - ClaudeSource, CodexSource, CopilotController, CopilotOwnedSource, CopilotSource, - CopilotSupervisor, CursorController, CursorHistorySource, DiscoveryEngine, DiscoveryRequest, - DockerTarget, FixtureSource, KimiController, KimiOwnership, KimiSource, - ManagedDockerCreateSpec, ManagedDockerService, ManagedDockerStatus, MistralVibeController, - MistralVibeOwnership, MistralVibeSource, MuseController, MuseOwnership, MuseSource, - OpenCodeController, OpenCodeSource, PiController, PiSource, QwenController, QwenOwnership, - QwenSource, SessionMigrateNativeController, SessionMigrateNativeOwnership, - SessionMigrateNativeSource, TerminalHarness, + default_ssh_targets_path, generate_managed_instance_id, load_ssh_targets, save_ssh_targets, + validate_host, AntigravityController, AntigravityOwnership, AntigravitySource, ClaudeSource, + CodexSource, CopilotController, CopilotOwnedSource, CopilotSource, CopilotSupervisor, + CursorController, CursorHistorySource, DiscoveryEngine, DiscoveryRequest, DockerTarget, + FixtureSource, KimiController, KimiOwnership, KimiSource, ManagedDockerCreateSpec, + ManagedDockerService, ManagedDockerStatus, MistralVibeController, MistralVibeOwnership, + MistralVibeSource, MuseController, MuseOwnership, MuseSource, OpenCodeController, + OpenCodeSource, PiController, PiSource, QwenController, QwenOwnership, QwenSource, + SessionMigrateNativeController, SessionMigrateNativeOwnership, SessionMigrateNativeSource, + SshHostsSource, SshTargetList, TerminalHarness, REMOTE_GUARD_ENV, }; #[cfg(not(target_os = "linux"))] use agentview::adapters::{CursorOwnership, OpenCodeOwnership}; @@ -242,6 +243,29 @@ enum SessionCommand { #[derive(Clone, Debug, Eq, PartialEq, Subcommand)] enum OpenCodeCommand { + /// Attach one TUI to the session on this agentview's own OpenCode server, + /// replacing this process, so turns stay visible to managed discovery. + /// Sessions this agentview does not manage need `--cwd`. + Attach { + #[arg(value_name = "SESSION_ID")] + session_id: String, + /// Workspace for sessions this agentview does not manage. + #[arg(long, value_name = "PATH")] + cwd: Option, + }, + /// Start one managed OpenCode session in the background: the supervisor + /// creates it on its own server, records ownership, and submits the task. + /// Prints the created session as JSON. + Launch { + #[arg(value_name = "PROMPT")] + prompt: String, + /// Workspace the session starts in. + #[arg(long, value_name = "PATH")] + cwd: PathBuf, + /// OpenCode model in `provider/model` form. + #[arg(long, value_name = "MODEL")] + model: Option, + }, /// Adopt explicitly verified existing V2 sessions from a private manifest. /// This does not start or resume any turns. HandoffImport { manifest: PathBuf }, @@ -540,6 +564,15 @@ struct Cli { #[arg(long = "docker-container", value_name = "NAME_OR_ID", global = true)] docker_containers: Vec, + /// Observe sessions on a passwordless SSH host that runs agentview. The + /// host list is remembered in the state directory after the first run. + #[arg(long = "ssh-host", value_name = "HOST", global = true)] + ssh_hosts: Vec, + + /// SSH client used to reach `--ssh-host` targets. + #[arg(long, default_value = "ssh", value_name = "PATH", global = true)] + ssh_bin: String, + /// Docker executable used for explicitly enrolled container targets. #[arg(long, default_value = "docker", value_name = "PATH", global = true)] docker_bin: String, @@ -809,6 +842,7 @@ fn main() -> Result<()> { if let Some((_, completed)) = &list_preferences { request.include_completed = *completed; } + let ssh_hosts = ssh_targets(&cli)?; // Secure the shared state root before any provider supervisor creates a // child directory. With a conventional 0022 umask, create_dir_all on a // provider path would otherwise leave the common parent at 0755 and the @@ -902,6 +936,7 @@ fn main() -> Result<()> { claude_bin: cli.claude_bin.clone(), codex_bin: cli.codex_bin.clone(), docker_bin: cli.docker_bin.clone(), + ssh_bin: cli.ssh_bin.clone(), launch_provider, launch_cwd: launch_cwd.clone(), provider_io_enabled, @@ -1167,6 +1202,11 @@ fn main() -> Result<()> { } let mut engine = DiscoveryEngine::new(); + let ssh_target_list = if cli.fixture.is_some() { + SshTargetList::disabled() + } else { + SshTargetList::enabled(ssh_hosts, default_ssh_targets_path()?) + }; // Successful imports remain visible without broadening discovery to every // historical provider conversation. engine.add_source(migration_registry.clone()); @@ -1360,8 +1400,8 @@ fn main() -> Result<()> { if let Some(terminal_harness) = terminal_harness { engine.add_source(terminal_harness); } - for container in cli.docker_containers { - let target = DockerTarget::inspect(&container, &cli.docker_bin)?; + for container in &cli.docker_containers { + let target = DockerTarget::inspect(container, &cli.docker_bin)?; let display_image = target.display_image(); engine.add_source(ClaudeSource::docker( target.name.clone(), @@ -1370,6 +1410,14 @@ fn main() -> Result<()> { )); engine.add_source(CodexSource::docker(target.name, target.id, display_image)); } + // One source reads the host list on every refresh, so /remote add and + // /remote remove inside the dashboard change the next refresh. + let ssh_source = SshHostsSource::new(ssh_target_list.clone(), cli.ssh_bin.clone()); + engine.add_source(if cli.json { + ssh_source + } else { + ssh_source.in_background() + }); } if cli.json { let mut snapshot = engine.discover(&request); @@ -1446,6 +1494,7 @@ fn main() -> Result<()> { cli.theme, theme::resolve(cli.theme), cli.mouse_hover, + ssh_target_list, )?; Ok(()) @@ -1488,8 +1537,61 @@ fn discovery_request(cli: &Cli) -> DiscoveryRequest { } } +/// SSH hosts this run observes: the persisted registry plus explicit +/// `--ssh-host` flags, persisted back after a successful merge so awareness +/// survives restarts. A host running under `AGENTVIEW_REMOTE=1` observes +/// nothing itself, so a watched machine never fans out recursively. +fn ssh_targets(cli: &Cli) -> Result> { + if std::env::var_os(REMOTE_GUARD_ENV).is_some() { + return Ok(Vec::new()); + } + for host in &cli.ssh_hosts { + validate_host(host).with_context(|| format!("invalid --ssh-host value {host}"))?; + } + let persisted = load_ssh_targets()?; + let mut hosts = persisted.hosts.clone(); + hosts.extend(cli.ssh_hosts.iter().cloned()); + if !cli.ssh_hosts.is_empty() { + save_ssh_targets(&hosts)?; + } + Ok(hosts.into_iter().collect()) +} + fn run_opencode_command(command: &OpenCodeCommand, cli: &Cli) -> Result<()> { match command { + OpenCodeCommand::Attach { session_id, cwd } => { + let supervisor = OpenCodeSupervisor::host(cli.opencode_bin.clone())?; + let mut command = match supervisor.native_attach_command(session_id) { + Ok(command) => command, + Err(error) => match cwd { + Some(cwd) => supervisor + .native_attach_command_for_external(session_id, cwd) + .context("this agentview does not manage that session")?, + None => return Err(error).context( + "this agentview does not manage that session; pass --cwd to attach anyway", + ), + }, + }; + // Hand the terminal to the TUI and wait, so the ssh PTY keeps + // working and the exit status reaches the caller. + let status = command + .status() + .context("failed to attach to the session")?; + if !status.success() { + bail!("the OpenCode session exited with status {status}"); + } + Ok(()) + } + OpenCodeCommand::Launch { prompt, cwd, model } => { + let session = OpenCodeSupervisor::host(cli.opencode_bin.clone())?.launch_with_model( + prompt, + cwd, + model.as_deref(), + )?; + serde_json::to_writer_pretty(io::stdout().lock(), &session)?; + println!(); + Ok(()) + } OpenCodeCommand::HandoffImport { manifest } => { let report = OpenCodeSupervisor::host(cli.opencode_bin.clone())?.import_handoff(manifest)?; @@ -1816,6 +1918,7 @@ fn run_completed_archive( claude_bin: cli.claude_bin.clone(), codex_bin: cli.codex_bin.clone(), docker_bin: cli.docker_bin.clone(), + ssh_bin: cli.ssh_bin.clone(), launch_provider: Provider::Codex, launch_cwd: std::env::current_dir()?, provider_io_enabled: true, diff --git a/src/opencode_supervisor.rs b/src/opencode_supervisor.rs index cab365f..f837038 100644 --- a/src/opencode_supervisor.rs +++ b/src/opencode_supervisor.rs @@ -118,7 +118,7 @@ pub struct LaunchReport { pub prompt_accepted: bool, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ManagedOpenCodeSession { pub id: String, pub cwd: PathBuf, @@ -3233,7 +3233,7 @@ fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option { .position(|window| window == needle) } -fn render_messages(value: &Value) -> Result { +pub(crate) fn render_messages(value: &Value) -> Result { let messages = value .as_array() .context("OpenCode message endpoint did not return an array")?; diff --git a/src/terminal.rs b/src/terminal.rs index 47873ea..7833097 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -146,6 +146,7 @@ struct LaunchJob { model: Option, prompt: String, cwd: Option, + host: Option, known_session_ids: BTreeSet, selection_at_launch: Option, } @@ -274,6 +275,7 @@ pub fn run_dashboard( theme_preference: ThemePreference, color_scheme: ColorScheme, mouse_hover: bool, + ssh_targets: crate::adapters::SshTargetList, ) -> Result<()> { let dashboard_started = Instant::now(); let mut first_draw_logged = false; @@ -398,6 +400,7 @@ pub fn run_dashboard( crate::perf_log::event("last_harness_cleanup_failed", format_args!("{error:#}")); } app.do_not_remember = last_harness.policy().clone(); + app.ssh_targets = ssh_targets; app.remembered_models = last_harness.models().into_iter().collect(); app.launch_model = app.remembered_models.get(&app.launch_provider).cloned(); if let Ok(links) = crate::session_tree::ParentLinks::load_default() { @@ -1540,13 +1543,21 @@ pub fn run_dashboard( model, prompt, cwd, + host, } => { if let Err(error) = last_harness.save(&provider) { app.set_notice(format!( "failed to remember harness: {error:#}" )); } - match control.launch_presentation(&provider) { + // A remote launch always hands the terminal + // to the provider's TUI on that host. + let presentation = if host.is_some() { + Ok(LaunchPresentation::Foreground) + } else { + control.launch_presentation(&provider) + }; + match presentation { Ok(LaunchPresentation::Foreground) => { app.set_notice(format!( "starting {} native session…", @@ -1560,6 +1571,7 @@ pub fn run_dashboard( model, prompt, cwd, + host, control, ) } @@ -1583,6 +1595,7 @@ pub fn run_dashboard( model, prompt, cwd, + host, known_session_ids, selection_at_launch: app.selection.clone(), }, @@ -2085,12 +2098,14 @@ fn schedule_launch(control: ControlHub, job: LaunchJob, sender: mpsc::Sender( terminal: &mut T, app: &mut App, @@ -2139,6 +2155,7 @@ fn dispatch_foreground_launch( model: Option, prompt: String, cwd: Option, + host: Option, control: &C, ) -> ActionEffect { let known_session_ids = provider_session_ids(app, &provider); @@ -2148,7 +2165,7 @@ fn dispatch_foreground_launch( } let retry_model = model.clone(); let retry_prompt = prompt.clone(); - let result = control.launch_foreground_session(provider.clone(), model, prompt, cwd); + let result = control.launch_foreground_session(provider.clone(), model, prompt, cwd, host); let resume = terminal.resume_dashboard(); match (result, resume) { (Ok(outcome), Ok(())) => { @@ -3057,6 +3074,7 @@ trait DashboardControl { model: Option, prompt: String, cwd: Option, + host: Option, ) -> Result; fn launch_foreground_session( &self, @@ -3064,8 +3082,9 @@ trait DashboardControl { model: Option, prompt: String, cwd: Option, + host: Option, ) -> Result { - self.launch_session(provider, model, prompt, cwd) + self.launch_session(provider, model, prompt, cwd, host) } fn authenticate_provider(&self, provider: &Provider) -> Result { Err(anyhow!( @@ -3124,8 +3143,9 @@ impl DashboardControl for ControlHub { model: Option, prompt: String, cwd: Option, + host: Option, ) -> Result { - self.launch_with(provider, model, prompt, cwd) + self.launch_with(provider, model, prompt, cwd, host) } fn launch_foreground_session( @@ -3134,8 +3154,9 @@ impl DashboardControl for ControlHub { model: Option, prompt: String, cwd: Option, + host: Option, ) -> Result { - self.launch_foreground_with(provider, model, prompt, cwd) + self.launch_foreground_with(provider, model, prompt, cwd, host) } fn authenticate_provider(&self, provider: &Provider) -> Result { @@ -3199,6 +3220,10 @@ fn dispatch_action( completed_visibility: Some(include_completed), ..ActionEffect::default() }, + AppAction::RemoteHostsChanged => ActionEffect { + refresh: true, + ..ActionEffect::default() + }, AppAction::LoadModels { provider } => ActionEffect { load_models: Some(provider), ..ActionEffect::default() @@ -3318,13 +3343,14 @@ fn dispatch_action( model, prompt, cwd, + host, } => { if app.work_only && !cwd.as_ref().is_some_and(|path| app.scope_allows(path)) { app.set_notice("choose a work folder before starting a session"); return ActionEffect::default(); } let known_session_ids = provider_session_ids(app, &provider); - let result = control.launch_session(provider.clone(), model, prompt, cwd); + let result = control.launch_session(provider.clone(), model, prompt, cwd, host); match result { Ok(outcome) => { app.set_notice(outcome.message); @@ -3406,6 +3432,7 @@ fn handle_action_legacy( AppAction::None | AppAction::Quit | AppAction::SetCompletedVisibility { .. } + | AppAction::RemoteHostsChanged | AppAction::LoadModels { .. } | AppAction::Authenticate { .. } | AppAction::SetupProvider { .. } @@ -4978,6 +5005,7 @@ mod tests { model: None, prompt: "ship".into(), cwd: None, + host: None, }] ); @@ -5003,6 +5031,7 @@ mod tests { model: None, prompt: "one\ntwo".into(), cwd: None, + host: None, }] ); } @@ -5161,6 +5190,7 @@ mod tests { model: None, prompt: "ship".into(), cwd: None, + host: None, } ); } @@ -5643,6 +5673,7 @@ mod tests { _model: Option, prompt: String, _cwd: Option, + _host: Option, ) -> Result { let mut outcome = self.invoke("launch", prompt)?; outcome.provider_session_hint = self.launch_hint.map(str::to_owned); @@ -5984,6 +6015,7 @@ mod tests { model: None, prompt: "build".into(), cwd: None, + host: None, }, AppAction::Reply { session_id: "worker".into(), @@ -6046,6 +6078,7 @@ mod tests { model: Some("openai/gpt-5".into()), prompt: "build".into(), cwd: None, + host: None, }, &control, ); @@ -6131,6 +6164,7 @@ mod tests { model: None, prompt: "build".into(), cwd: None, + host: None, known_session_ids: BTreeSet::from(["pi:host:old".into()]), selection_at_launch: None, }, @@ -6484,6 +6518,7 @@ mod tests { model: None, prompt: "x".into(), cwd: None, + host: None, }, "launch failed", ), diff --git a/src/ui.rs b/src/ui.rs index d9d5253..b0fc4ac 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -7,9 +7,8 @@ use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph, Wrap}; use unicode_segmentation::UnicodeSegmentation; use crate::app::{ - display_directory, hidden_picker_rows_for_height, is_active_session_state, App, ComposerMode, - ConfirmTarget, Overlay, SelectionKey, ViewMode, MIGRATION_PICKER_PAGE_SIZE, - MODEL_PICKER_PAGE_SIZE, + hidden_picker_rows_for_height, is_active_session_state, App, ComposerMode, ConfirmTarget, + Overlay, SelectionKey, ViewMode, MIGRATION_PICKER_PAGE_SIZE, MODEL_PICKER_PAGE_SIZE, }; use crate::domain::{AgentSession, Capability, Provider, SessionState}; use crate::usage::Pace; @@ -1033,7 +1032,13 @@ fn render_tree_session_row( + display_width(&right); let summary_width = (width as usize).saturating_sub(fixed).max(1); // Indent the status marker with its session, keeping later columns aligned. - let name = pad_to_width(truncate(&session.name, name_width), name_width); + // Remote sessions are tagged with their host so the list alone says where + // a row runs; Peek repeats the host as its runtime label. + let display_name = match &session.runtime { + crate::domain::Runtime::Ssh { host } => format!("[{host}] {}", session.name), + _ => session.name.clone(), + }; + let name = pad_to_width(truncate(&display_name, name_width), name_width); let mut spans = vec![ Span::styled( if selected { "❯ " } else { " " }, @@ -2212,6 +2217,7 @@ fn help_sections(app: &App) -> Vec { ("/keep", "keep visible; retain reminder"), ("/restore", "bring back a hidden session"), ("/completed", "show or hide finished"), + ("/remote", "watch or drop SSH hosts"), ("/cd path", "start in any directory"), ("/harness name", "switch harness"), ("/model name", "pick model or Terminal shell"), @@ -2660,7 +2666,6 @@ fn hidden_snippet_line( fn render_directory_picker(frame: &mut Frame<'_>, app: &App, area: Rect) { let choices = app.directory_choices(); - let home = std::env::var_os("HOME").map(std::path::PathBuf::from); let popup_width = area.width.saturating_sub(2).min(84).max(30); let visible_rows = hidden_picker_rows_for_height(area.height); let result_rows = choices.len().clamp(1, visible_rows); @@ -2684,7 +2689,7 @@ fn render_directory_picker(frame: &mut Frame<'_>, app: &App, area: Rect) { )])]; lines[0].spans.extend(if app.directory_filter.is_empty() { vec![Span::styled( - "type part of a folder name, or a path like ~/Code/app (new folders are created)", + "type a folder name, ~/Code/app, or host:/path on a watched host (new local folders are created)", Style::default().fg(palette().dim), )] } else { @@ -2703,10 +2708,16 @@ fn render_directory_picker(frame: &mut Frame<'_>, app: &App, area: Rect) { .enumerate() .skip(start) .take(visible_rows) - .map(|(index, path)| { + .map(|(index, choice)| { let selected = index == app.directory_selection; - let label = sanitize_inline(&display_directory(path, home.as_deref())); - let suffix = if path.exists() { "" } else { " (new folder)" }; + let label = sanitize_inline(&choice.label); + // Only local folders can be created on confirm; a remote + // folder must already exist on its host. + let suffix = if choice.host.is_none() && !choice.path.exists() { + " (new folder)" + } else { + "" + }; let label = truncate( &label, inner_width @@ -2719,6 +2730,10 @@ fn render_directory_picker(frame: &mut Frame<'_>, app: &App, area: Rect) { .bg(palette().selected_bg) .fg(palette().selected_fg) .add_modifier(Modifier::BOLD) + } else if choice.host.is_some() { + // A folder on a watched SSH host starts the next + // session there. + Style::default().bg(palette().bg).fg(palette().dim) } else { Style::default().bg(palette().bg).fg(palette().fg) }, @@ -3242,15 +3257,28 @@ fn sanitize_multiline(input: &str) -> String { } fn launch_directory_name(app: &App) -> String { - app.launch_directory() - .or_else(|| std::env::current_dir().ok()) - .map(|path| { - path.file_name() + match app.launch_directory() { + Some(crate::app::LaunchDirectory::Remote { host, path }) => { + let name = path + .file_name() .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| path.display().to_string()) - }) - .map(|name| sanitize_inline(&name)) - .unwrap_or_else(|| "unknown directory".into()) + .unwrap_or_else(|| path.display().to_string()); + sanitize_inline(&format!("[{host}] {name}")) + } + other => other + .and_then(|directory| match directory { + crate::app::LaunchDirectory::Local(path) => Some(path), + crate::app::LaunchDirectory::Remote { .. } => None, + }) + .or_else(|| std::env::current_dir().ok()) + .map(|path| { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.display().to_string()) + }) + .map(|name| sanitize_inline(&name)) + .unwrap_or_else(|| "unknown directory".into()), + } } fn abbreviate_path(path: &std::path::Path) -> String { @@ -4663,7 +4691,7 @@ mod tests { warnings: vec![], }); app.toggle_help(); - let backend = TestBackend::new(120, 32); + let backend = TestBackend::new(120, 33); let mut terminal = Terminal::new(backend).unwrap(); terminal.draw(|frame| render(frame, &app)).unwrap(); diff --git a/src/voice/host.rs b/src/voice/host.rs index 159257b..ec88eb3 100644 --- a/src/voice/host.rs +++ b/src/voice/host.rs @@ -600,6 +600,7 @@ impl VoiceHost for DashboardHost { None, task.to_owned(), Some(cwd.to_owned()), + None, )?; match outcome.provider_session_hint { Some(id) => Ok(format!("opencode:host:{id}")), @@ -730,6 +731,7 @@ mod tests { claude_bin: String::new(), codex_bin: String::new(), docker_bin: String::new(), + ssh_bin: String::new(), launch_provider: Provider::OpenCode, launch_cwd: dir.clone(), provider_io_enabled: true, diff --git a/tests/provider_matrix.rs b/tests/provider_matrix.rs index 82c7442..d67a20c 100644 --- a/tests/provider_matrix.rs +++ b/tests/provider_matrix.rs @@ -5,7 +5,7 @@ use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use agentview::adapters::{ - DiscoveryEngine, DiscoveryRequest, FixtureSource, OpenCodeSource, PiSource, + DiscoveryEngine, DiscoveryRequest, FixtureSource, OpenCodeSource, PiSource, SshHostSource, }; use agentview::domain::Provider; use tempfile::tempdir; @@ -43,6 +43,89 @@ fn pi_store() -> tempfile::TempDir { directory } +/// A stand-in `ssh` executable that answers like a passwordless host whose +/// agentview reports one managed OpenCode session. +fn ssh_script() -> (tempfile::TempDir, PathBuf) { + let directory = tempdir().unwrap(); + let executable = directory.path().join("ssh"); + fs::write( + &executable, + r#"#!/bin/sh +for argument in "$@"; do + case "$argument" in + 176) + host=176 + ;; + AGENTVIEW_REMOTE=1*) + ;; + *) + remote="$argument" + ;; + esac +done +[ "$host" = 176 ] || exit 66 +[ "${remote#*AGENTVIEW_REMOTE=1}" != "$remote" ] || exit 67 +printf '%s\n' "$remote" >&2 +cat <<'JSON' +{ + "sessions": [ + { + "id": "opencode:host:ses_remote", + "provider_session_id": "ses_remote", + "provider": "opencode", + "runtime": {"kind": "host"}, + "kind": "managed", + "name": "Remote build", + "cwd": "/home/bpang/mywork", + "state": "working", + "summary": "Compiling", + "raw_state": "managed_server", + "pid": 496692, + "started_at": 1793134692584, + "updated_at": 1793134809515, + "pull_requests": null, + "capabilities": ["inspect", "reply", "interrupt"] + } + ], + "warnings": [] +} +JSON +"#, + ) + .unwrap(); + let mut permissions = fs::metadata(&executable).unwrap().permissions(); + permissions.set_mode(0o700); + fs::set_permissions(&executable, permissions).unwrap(); + (directory, executable) +} + +#[test] +fn ssh_host_merges_remote_agentview_sessions_as_inspect_only() { + let (_directory, ssh) = ssh_script(); + let mut engine = DiscoveryEngine::new(); + engine.add_source(SshHostSource::with_ssh_bin( + "176", + ssh.display().to_string(), + )); + + let snapshot = engine.discover(&DiscoveryRequest::default()); + + assert!(snapshot.warnings.is_empty(), "{:?}", snapshot.warnings); + assert_eq!(snapshot.sessions.len(), 1); + let session = &snapshot.sessions[0]; + assert_eq!(session.id, "ssh:176:opencode:host:ses_remote"); + assert_eq!(session.provider, Provider::OpenCode); + assert_eq!( + session.runtime, + agentview::domain::Runtime::Ssh { host: "176".into() } + ); + assert_eq!(session.pid, None); + assert_eq!(session.capabilities.len(), 1); + assert!(session + .capabilities + .contains(&agentview::domain::Capability::Inspect)); +} + #[test] fn pi_discovers_in_isolation() { let store = pi_store();