Skip to main content

agentmux_srv/server/app_api/
connections.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The connection RPCs the frontend's connection UI already calls
5//! (`conntypeahead.tsx`, `blockframe.tsx`'s `ConnStatusOverlay`), which had no
6//! handler until now (P0 of SPEC_REMOTE_TERMINALS_AND_DURABLE_SESSIONS_2026_10_02.md).
7//!
8//! A connection AgentMux cannot run is refused with a status the pane shows,
9//! instead of the pane silently starting a local shell under a remote name:
10//! WSL off Windows or for a distro that is not installed (P1), and SSH where
11//! there is no `ssh` (P2).
12
13use super::*;
14use crate::backend::mps::Broker;
15use crate::backend::remote::remotes;
16use crate::backend::remote::sessions;
17use crate::backend::remote::status::{self, state};
18use crate::backend::remote::ConnTarget;
19
20pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
21    // Lists. One call each, with the constant spelled out: the RPC contract
22    // test resolves every registered command name statically.
23    //
24    // The requests are `serde_json::Value`: these handlers read what they need
25    // loosely (a missing field is ""), and `Value` takes anything, so typing them
26    // only records the response (docs/reports/REPORT_MIGRATION_WRAPUP_STATUS_2026_09_16.md
27    // §5.4c). The frontend stubs keep their precise request types
28    // (generated-manifest.json `dataType`).
29    engine.register_typed(COMMAND_CONN_LIST, |_data: serde_json::Value, _ctx| async move { Ok(conn_list().await) });
30    engine.register_typed(COMMAND_CONN_LIST_AWS, |_data: serde_json::Value, _ctx| async move {
31        Ok(Vec::<String>::new())
32    });
33    // Installed WSL distributions (empty off Windows, or with no WSL).
34    engine.register_typed(COMMAND_WSL_LIST, |_data: serde_json::Value, _ctx| async move {
35        Ok(crate::backend::remote::wsl::list().await)
36    });
37
38    let broker = state.broker.clone();
39    engine.register_typed(COMMAND_CONN_ENSURE, move |data: serde_json::Value, _ctx| {
40        let broker = broker.clone();
41        // `{ connname, logblockid? }`
42        async move { ensure(&broker, &str_field(&data, "connname")).await }
43    });
44
45    let app = state.clone();
46    engine.register_typed(COMMAND_CONN_CONNECT, move |data: serde_json::Value, _ctx| {
47        let app = app.clone();
48        // `{ host, keywords?, logblockid? }`
49        async move { connect(&app, &str_field(&data, "host"), &str_field(&data, "logblockid")).await }
50    });
51
52    let broker = state.broker.clone();
53    engine.register_typed(COMMAND_CONN_DISCONNECT, move |data: serde_json::Value, _ctx| {
54        let broker = broker.clone();
55        async move { conn_disconnect(&broker, &data).await }
56    });
57
58    let app = state.clone();
59    engine.register_typed(COMMAND_CONN_SESSIONS, move |data: serde_json::Value, _ctx| {
60        let app = app.clone();
61        async move { conn_sessions(&app, &data).await }
62    });
63    let app = state.clone();
64    engine.register_typed(COMMAND_CONN_SESSION_END, move |data: serde_json::Value, _ctx| {
65        let app = app.clone();
66        async move { conn_session_end(&app, &data).await }
67    });
68
69    // Connectors → Remotes (docs/specs/SPEC_REMOTES_PANE_2026_10_05.md §4.6): its list,
70    // a remote's settings, and forgetting a recent one.
71    let config = state.config_watcher.clone();
72    engine.register_typed(COMMAND_REMOTES_LIST, move |_cmd: CommandRemotesListData, _ctx| {
73        let config = config.clone();
74        async move { Ok(remotes::list(config.get_full_config().connections.clone()).await) }
75    });
76    let app = state.clone();
77    engine.register_typed(COMMAND_REMOTE_SET_CONFIG, move |cmd: CommandRemoteSetConfigData, _ctx| {
78        let app = app.clone();
79        async move { remote_set_config(&app, cmd) }
80    });
81    let app = state.clone();
82    engine.register_typed(COMMAND_REMOTE_FORGET, move |cmd: CommandRemoteForgetData, _ctx| {
83        let app = app.clone();
84        async move { remote_forget(&app, cmd) }
85    });
86    // Removing the helper ends the host's sessions, so it is the user's
87    // decision, made in the approval window, as ending one session is.
88    let app = state.clone();
89    engine.register_typed(COMMAND_REMOTE_HELPER_REMOVE, move |cmd: CommandRemoteHelperRemoveData, _ctx| {
90        let app = app.clone();
91        async move { remove_helper(&app, &cmd.connection, &cmd.blockid).await }
92    });
93    // Adding a host writes the user's ssh config, which every ssh on the
94    // machine reads (git's included), so it is the user's decision, made in
95    // the approval window: a new alias could otherwise send another tool's
96    // ssh somewhere else.
97    let app = state.clone();
98    engine.register_typed(COMMAND_REMOTE_ADD, move |cmd: CommandRemoteAddData, _ctx| {
99        let app = app.clone();
100        async move { add_remote(&app, cmd).await }
101    });
102    // Testing logs in with the user's keys, so only to a host AgentMux
103    // already lists (the user's own ssh config, settings or a connection
104    // they made), never one an RPC names.
105    let app = state.clone();
106    engine.register_typed(COMMAND_REMOTE_TEST, move |cmd: CommandRemoteTestData, _ctx| {
107        let app = app.clone();
108        async move { test_remote(&app, &cmd.connection, &cmd.blockid).await }
109    });
110    let app = state.clone();
111    engine.register_typed(COMMAND_REMOTE_AGENT_REVOKE, move |cmd: CommandRemoteAgentRevokeData, _ctx| {
112        let app = app.clone();
113        async move { remote_agent_revoke(&app, cmd) }
114    });
115    engine.register_typed(COMMAND_REMOTE_SSH_LOCATE, move |cmd: CommandRemoteSshLocateData, _ctx| async move {
116        remote_ssh_locate(cmd).await
117    });
118}
119
120/// The picker's "Remote" section: the user's ssh config hosts and any other
121/// SSH connection used this session. The typeahead adds `local` and the
122/// WSL distros itself.
123pub(crate) async fn conn_list() -> Vec<String> {
124    let hosts = tokio::task::spawn_blocking(crate::backend::remote::ssh_config::hosts)
125        .await
126        .unwrap_or_default();
127    remote_names(&hosts, &status::all())
128}
129
130/// `conndisconnect`; `data` is the connection name, as a bare string.
131pub(crate) async fn conn_disconnect(broker: &Broker, data: &serde_json::Value) -> Result<(), String> {
132    let name = data.as_str().unwrap_or_default().to_string();
133    match ConnTarget::parse(&name) {
134        // Closes the shared connection: the sessions on it end,
135        // and the next pane logs in again.
136        Ok(ConnTarget::Ssh(_)) => crate::backend::remote::link::disconnect(&name).await,
137        Ok(ConnTarget::Wsl(_)) => {
138            status::set(Some(broker), &name, state::DISCONNECTED, None);
139        }
140        _ => {}
141    }
142    Ok(())
143}
144
145/// A host's durable sessions, for Connectors → Remotes' "Sessions…"
146/// (spec §7.6). Listing runs one fixed, read-only command over ssh, as the
147/// UI's other connection calls do. Ending one is the user's decision,
148/// made in the host's own window (`ask_user`): anything holding srv's
149/// auth key can send this RPC, an agent included, but none can answer
150/// that window.
151pub(crate) async fn conn_sessions(state: &AppState, data: &serde_json::Value) -> Result<Vec<sessions::HostSession>, String> {
152    let (conn, block) = (str_field(data, "connname"), str_field(data, "blockid"));
153    let ask = (!block.is_empty()).then_some(sessions::AskIn {
154        block_id: &block,
155        auth_key: &state.auth_key,
156    });
157    let list = sessions::list(&state.mstore, &conn, ask).await?;
158    // Connectors → Remotes shows the count without opening ssh itself.
159    remotes::note_sessions(&conn, list.len());
160    Ok(list)
161}
162
163/// `connsessionend`: ends one durable session, after the user says yes in the asking pane's window.
164pub(crate) async fn conn_session_end(state: &AppState, data: &serde_json::Value) -> Result<bool, String> {
165    let (conn, id, block) = (
166        str_field(data, "connname"),
167        str_field(data, "sessionid"),
168        str_field(data, "blockid"),
169    );
170    if block.is_empty() {
171        return Err("ending a session needs the pane asking, to ask the user in".into());
172    }
173    if !crate::backend::blockcontroller::durable_ssh::valid_session_id(&id) {
174        return Err(format!("{:?} is not a session id", one_line(&id, 80)));
175    }
176    confirm_session_end(state, &block, &conn, &id).await?;
177    let ask = sessions::AskIn {
178        block_id: &block,
179        auth_key: &state.auth_key,
180    };
181    sessions::end(&conn, &id, Some(ask)).await
182}
183
184/// `remote.setconfig`.
185pub(crate) fn remote_set_config(state: &AppState, cmd: CommandRemoteSetConfigData) -> Result<(), String> {
186    let name = remote_name(&cmd.connection)?;
187    crate::backend::config_watcher_fs::set_connection_values(&state.config_watcher, &state.event_bus, &name, &cmd.values)?;
188    remotes::publish_change(&state.broker);
189    Ok(())
190}
191
192/// `remote.forget`.
193pub(crate) fn remote_forget(state: &AppState, cmd: CommandRemoteForgetData) -> Result<(), String> {
194    let name = remote_name(&cmd.connection)?;
195    if remotes::forget_recent(&name).map_err(|e| format!("could not forget {name}: {e}"))? {
196        remotes::publish_change(&state.broker);
197    }
198    Ok(())
199}
200
201/// `remote.agentrevoke`. Revoking only takes access away (the agent is asked again on its next
202/// use of the host), so it needs no question.
203pub(crate) fn remote_agent_revoke(state: &AppState, cmd: CommandRemoteAgentRevokeData) -> Result<(), String> {
204    let name = ssh_host(&cmd.connection, NOT_SSH)?;
205    let revoked = crate::backend::remote::agent_access::revoke(&cmd.agent, &name)
206        .map_err(|e| format!("could not revoke {}'s access to {name}: {e}", one_line(&cmd.agent, 60)))?;
207    if revoked {
208        tracing::info!(agent = %one_line(&cmd.agent, 60), connection = %name, "agent ssh access: revoked");
209        remotes::publish_change(&state.broker);
210    }
211    Ok(())
212}
213
214/// `remote.sshlocate`: where in the user's ssh config a connection is defined.
215pub(crate) async fn remote_ssh_locate(cmd: CommandRemoteSshLocateData) -> Result<Option<RemoteSshLocation>, String> {
216    let found = tokio::task::spawn_blocking(move || {
217        let (config, ssh_dir) = crate::backend::remote::ssh_config_edit::user_paths()?;
218        crate::backend::remote::ssh_config_edit::locate_in(&config, &ssh_dir, &cmd.connection)
219    })
220    .await
221    .map_err(|e| e.to_string())?;
222    Ok(found.map(|(path, line)| RemoteSshLocation {
223        path: path.to_string_lossy().into_owned(),
224        line: line as u32,
225    }))
226}
227
228/// Add a host to the user's ssh config (§4.4 of SPEC_REMOTES_PANE_2026_10_05.md),
229/// once they confirm the exact block in pane `cmd.blockid`.
230async fn add_remote(state: &AppState, cmd: CommandRemoteAddData) -> Result<(), String> {
231    use crate::backend::remote::ssh_config_edit::{self, NewHost};
232    if cmd.blockid.is_empty() {
233        return Err("adding a remote needs the pane asking, to ask the user in".into());
234    }
235    let host = NewHost {
236        alias: cmd.alias,
237        hostname: cmd.hostname,
238        user: cmd.user,
239        port: cmd.port,
240        identity_file: cmd.identityfile,
241        proxy_jump: cmd.proxyjump,
242    };
243    let block = ssh_config_edit::host_block(&host)?;
244    let (config, ssh_dir) =
245        ssh_config_edit::user_paths().ok_or_else(|| "there is no home folder for an ssh config".to_string())?;
246    let question = serde_json::json!({
247        "kind": "consent",
248        "title": format!("Add {} to your ssh config", one_line(&host.alias, 80)),
249        "message": format!(
250            "Add this to the end of {}?\n\n{}\nEvery ssh on this computer will use it.",
251            config.display(),
252            block
253        ),
254        "ok_label": "Add",
255        "cancel_label": "Cancel",
256    });
257    let answer = ask_in_pane(state, &cmd.blockid, question).await?;
258    if !(answer.answered && answer.approve) {
259        return Err("kept: the user chose not to add it".into());
260    }
261    tokio::task::spawn_blocking(move || ssh_config_edit::add_host_in(&config, &ssh_dir, &host))
262        .await
263        .map_err(|e| e.to_string())??;
264    remotes::publish_change(&state.broker);
265    Ok(())
266}
267
268const NOT_SSH: &str = "is not an SSH host";
269
270/// `connection`'s canonical name if it is an SSH host; otherwise
271/// "<connection> `otherwise`".
272fn ssh_host(connection: &str, otherwise: &str) -> Result<String, String> {
273    match ConnTarget::parse(connection)? {
274        t @ ConnTarget::Ssh(_) => Ok(t.name()),
275        _ => Err(format!("{} {otherwise}", one_line(connection, 80))),
276    }
277}
278
279/// [`ssh_host`] for a host AgentMux already lists (the user's ssh config,
280/// settings, or a connection they made), for what logs in with the user's
281/// keys: never to one an RPC names, since anything holding srv's key can send
282/// one, an agent included.
283async fn known_ssh_host(state: &AppState, connection: &str) -> Result<String, String> {
284    let name = ssh_host(connection, NOT_SSH)?;
285    let known = remotes::list(state.config_watcher.get_full_config().connections.clone())
286        .await
287        .iter()
288        .any(|r| r.kind == "ssh" && r.name == name);
289    if !known {
290        return Err(format!("{} isn't one of your remotes", one_line(&name, 80)));
291    }
292    Ok(name)
293}
294
295/// Log in to SSH host `name` (a [`known_ssh_host`]) and run `true`, with
296/// ssh's prompts going to the user in the window of pane `block`, if any.
297/// The connection's status follows (`link::login`), and the connection stays
298/// up a while after (`ControlPersist`), so the next pane on it asks nothing.
299async fn log_in(state: &AppState, name: &str, block: &str) -> Result<(), String> {
300    use crate::backend::remote::{host::HostSsh, link};
301    let mut host = HostSsh::for_connection(name)?;
302    let _grant = (!block.is_empty()).then(|| host.ask_user_in(block, name, &state.auth_key)).flatten();
303    link::login(name, async {
304        host.run("true", None, SSH_WITH_PROMPTS).await.and_then(|o| o.ok()).map(|_| ())
305    })
306    .await
307}
308
309/// What `connconnect` does (a Remotes row's Connect, a pane's Reconnect): log
310/// in to an SSH host; for anything else, what `connensure` does.
311async fn connect(state: &AppState, connection: &str, block: &str) -> Result<(), String> {
312    ensure(&state.broker, connection).await?;
313    if !matches!(ConnTarget::parse(connection)?, ConnTarget::Ssh(_)) {
314        return Ok(());
315    }
316    let name = known_ssh_host(state, connection).await?;
317    log_in(state, &name, block).await
318}
319
320/// Log in to `connection` and run `true` (§4.4): success, or ssh's message.
321async fn test_remote(state: &AppState, connection: &str, block: &str) -> Result<RemoteTestResult, String> {
322    let name = known_ssh_host(state, connection).await?;
323    Ok(match log_in(state, &name, block).await {
324        Ok(()) => RemoteTestResult { ok: true, message: String::new() },
325        Err(message) => RemoteTestResult { ok: false, message },
326    })
327}
328
329/// Remove AgentMux's helper from SSH host `connection` (Remotes, §4.9 of
330/// SPEC_REMOTES_PANE_2026_10_05.md), once the user confirms in pane `block`,
331/// naming the sessions that will end.
332async fn remove_helper(state: &AppState, connection: &str, block: &str) -> Result<(), String> {
333    use crate::backend::remote::{files, helper_hosts, helper_install, host::HostSsh};
334    let name = ssh_host(connection, "has no AgentMux helper to remove")?;
335    if block.is_empty() {
336        return Err("removing the helper needs the pane asking, to ask the user in".into());
337    }
338    let ask = sessions::AskIn { block_id: block, auth_key: &state.auth_key };
339    let running = sessions::list(&state.mstore, &name, Some(ask)).await?;
340    let ends = match running.len() {
341        0 => "No sessions are running there.".to_string(),
342        1 => "The 1 session running there ends, with everything running in it.".to_string(),
343        n => format!("The {n} sessions running there end, with everything running in them."),
344    };
345    let question = serde_json::json!({
346        "kind": "consent",
347        "title": format!("Remove AgentMux's helper from {}", one_line(&name, 80)),
348        "message": format!(
349            "Remove AgentMux's helper from {}?\n\n{ends} It deletes ~/.agentmux-remote there; file browsing and terminals that survive disconnects need it installed again.",
350            one_line(&name, 80)
351        ),
352        "ok_label": "Remove",
353        "cancel_label": "Keep It",
354        // A destructive answer is drawn in the danger tone, not the loud
355        // attention fill.
356        "destructive": true,
357    });
358    let answer = ask_in_pane(state, block, question).await?;
359    if !(answer.answered && answer.approve) {
360        return Err("kept: the user chose not to remove it".into());
361    }
362    let mut host = HostSsh::for_connection(&name)?;
363    let _grant = host.ask_user_in(block, &name, &state.auth_key);
364    let out = host
365        .run(&helper_install::remove_command(), None, SSH_WITH_PROMPTS)
366        .await?
367        .ok()?;
368    if out.trim() != "ok" {
369        return Err(format!("removing the helper from {name} did not finish ({})", one_line(&out, 200)));
370    }
371    files::close(&name).await;
372    // For every name of the machine: they all had this one helper.
373    if let Err(e) = helper_hosts::forget_helper_on_machine(&name).await {
374        tracing::warn!(connection = %name, error = %e, "could not forget the removed helper");
375    }
376    // Its next need asks again (spec §4.9), whatever was answered before.
377    crate::backend::remote::helper_consent::forget_answers(&name);
378    remotes::note_sessions(&name, 0);
379    remotes::publish_change(&state.broker);
380    tracing::info!(connection = %name, sessions = running.len(), "removed the helper");
381    Ok(())
382}
383
384/// Give the helper install its question (SPEC_REMOTES_PANE_2026_10_05.md
385/// §4.9): asked in the pane that needs it, and `conn:helper` from the settings.
386pub fn install_helper_consent(state: &AppState) {
387    use crate::backend::remote::helper_consent;
388    let app = state.clone();
389    let config = state.config_watcher.clone();
390    let (writer, event_bus, broker) = (state.config_watcher.clone(), state.event_bus.clone(), state.broker.clone());
391    helper_consent::install(helper_consent::Deps {
392        ask: Box::new(move |block, question| {
393            let app = app.clone();
394            Box::pin(async move {
395                let a = ask_in_pane(&app, &block, question).await?;
396                Ok(helper_consent::Answer { answered: a.answered, approve: a.approve, remember: a.checkbox })
397            })
398        }),
399        settings: Box::new(move |connection| {
400            let full = config.get_full_config();
401            let host = full
402                .connections
403                .iter()
404                .find(|(name, _)| crate::backend::remote::conn::same_connection(name, connection))
405                .map(|(_, k)| k.conn_helper.clone())
406                .unwrap_or_default();
407            (host, full.settings.conn_helper.clone())
408        }),
409        remember: Box::new(move |connection, value| {
410            let mut values = serde_json::Map::new();
411            values.insert("conn:helper".into(), serde_json::json!(value));
412            crate::backend::config_watcher_fs::set_connection_values(&writer, &event_bus, connection, &values)?;
413            remotes::publish_change(&broker);
414            Ok(())
415        }),
416    });
417}
418
419/// A connection the Remotes commands may act on: a WSL distribution or an SSH
420/// destination, never `local` or something `ConnTarget` refuses.
421fn remote_name(connection: &str) -> Result<String, String> {
422    match ConnTarget::parse(connection)? {
423        ConnTarget::Local => Err("local is not a remote".to_string()),
424        _ => Ok(connection.trim().to_string()),
425    }
426}
427
428/// The user's yes to ending session `id` on `conn`, asked in pane `block`.
429/// `Err` unless they said yes.
430async fn confirm_session_end(
431    state: &AppState,
432    block: &str,
433    conn: &str,
434    id: &str,
435) -> Result<(), String> {
436    // `consent`: a plain question of AgentMux's own, not a relayed ssh prompt.
437    let question = serde_json::json!({
438        "kind": "consent",
439        "title": format!("End a session on {}", one_line(conn, 80)),
440        "message": format!(
441            "End the durable session {id} on {}?\n\nIts shell, and everything running in it, stops. This cannot be undone.",
442            one_line(conn, 80)
443        ),
444        "ok_label": "End Session",
445        "cancel_label": "Keep It",
446        "destructive": true,
447    });
448    let answer = ask_in_pane(state, block, question).await?;
449    if answer.answered && answer.approve {
450        Ok(())
451    } else {
452        Err("kept: the user chose not to end it".to_string())
453    }
454}
455
456fn str_field(data: &serde_json::Value, key: &str) -> String {
457    data.get(key)
458        .and_then(|v| v.as_str())
459        .unwrap_or_default()
460        .to_string()
461}
462
463/// What `connensure` does: accept `local`; accept a WSL distro that is
464/// installed (Windows only), which is then connected; accept an SSH
465/// destination where the system `ssh` is, claiming nothing (only a login
466/// connects it: a pane's ssh, or `connconnect`); refuse a bad name with the
467/// reason, recorded as the status the pane's overlay shows.
468pub(crate) async fn ensure(broker: &Broker, name: &str) -> Result<(), String> {
469    let (installed, ssh_found) = match ConnTarget::parse(name)? {
470        ConnTarget::Wsl(_) => (crate::backend::remote::wsl::list().await, false),
471        ConnTarget::Ssh(_) => (Vec::new(), crate::backend::remote::ssh::binary().is_some()),
472        ConnTarget::Local => (Vec::new(), false),
473    };
474    ensure_with(broker, name, &installed, cfg!(windows), ssh_found)
475}
476
477/// [`ensure`] with the installed distros, the platform and whether `ssh` was
478/// found given, so it is testable anywhere.
479pub(crate) fn ensure_with(
480    broker: &Broker,
481    name: &str,
482    wsl_installed: &[String],
483    on_windows: bool,
484    ssh_found: bool,
485) -> Result<(), String> {
486    let target = ConnTarget::parse(name)?;
487    let message = match &target {
488        ConnTarget::Local => return Ok(()),
489        ConnTarget::Wsl(_) if !on_windows => "WSL is only available on Windows".to_string(),
490        ConnTarget::Wsl(distro) if wsl_installed.iter().any(|d| d.eq_ignore_ascii_case(distro)) => {
491            status::set(Some(broker), name, state::CONNECTED, None);
492            return Ok(());
493        }
494        ConnTarget::Wsl(distro) => {
495            format!("WSL distribution '{distro}' is not installed (wsl.exe --list shows what is)")
496        }
497        ConnTarget::Ssh(_) if ssh_found => return Ok(()),
498        ConnTarget::Ssh(_) => crate::backend::remote::ssh::missing_binary_message(),
499    };
500    // Keyed by the name exactly as the pane's meta holds it, not the canonical
501    // form: the pane's overlay looks its status up by `meta.connection`, so
502    // " area54 " or "host:022" would otherwise never see their error (#4248).
503    status::set(Some(broker), name, state::ERROR, Some(&message));
504    Err(message)
505}
506
507/// Where an agent's `Shell` or `PtyShell` runs.
508#[derive(Debug, Clone, PartialEq, Eq)]
509pub(crate) enum AgentTarget {
510    Local,
511    /// An installed WSL distro.
512    Wsl(String),
513    /// An SSH destination: runs only with the user's consent
514    /// ([`consent_for_ssh`]), and every ssh prompt goes to the user
515    /// (`remote::askpass`), never to the agent.
516    Ssh(crate::backend::remote::conn::SshDest),
517}
518
519/// The connection an agent's `Shell` or `PtyShell` call asked for, checked the
520/// same way a pane's is ([`ensure`]), `Err` with the reason when it cannot run.
521pub(crate) async fn for_agent(broker: &Broker, name: Option<&str>) -> Result<AgentTarget, String> {
522    let name = name.unwrap_or_default();
523    ensure(broker, name).await?;
524    Ok(match ConnTarget::parse(name)? {
525        ConnTarget::Local => AgentTarget::Local,
526        ConnTarget::Wsl(distro) => AgentTarget::Wsl(distro),
527        ConnTarget::Ssh(dest) => AgentTarget::Ssh(dest),
528    })
529}
530
531/// How a dialog names an agent: its id, as one plain capped line.
532pub(crate) fn agent_label(agent: Option<&str>) -> String {
533    agent
534        .map(|a| one_line(a, 60))
535        .unwrap_or_else(|| "An agent with no AgentMux id".to_string())
536}
537
538/// One line of agent-supplied text for a dialog: shown as plain text, newlines
539/// folded and length capped, so it cannot lay out a message of its own.
540pub(crate) fn one_line(text: &str, max: usize) -> String {
541    let flat: String = text
542        .chars()
543        .map(|c| if c.is_control() { ' ' } else { c })
544        .collect();
545    let flat = flat.split_whitespace().collect::<Vec<_>>().join(" ");
546    if flat.chars().count() <= max {
547        flat
548    } else {
549        format!("{}…", flat.chars().take(max).collect::<String>())
550    }
551}
552
553/// How long the user has to answer a consent or askpass dialog.
554const DIALOG_TIMEOUT_MS: u64 = 120_000;
555
556/// How long an ssh run whose prompts go to the approval window may take: the
557/// dialog's own wait, and some to spare.
558const SSH_WITH_PROMPTS: std::time::Duration = std::time::Duration::from_millis(DIALOG_TIMEOUT_MS + 30_000);
559
560/// The user's answer to [`ask_user`]. `answered` is false when the window was
561/// closed, timed out, or could not be opened.
562#[derive(Debug, Default, Clone, serde::Deserialize)]
563pub(crate) struct UserAnswer {
564    #[serde(default)]
565    pub answered: bool,
566    #[serde(default)]
567    pub approve: bool,
568    /// For a `secret` question: never logged.
569    #[serde(default)]
570    pub text: String,
571    #[serde(default)]
572    pub checkbox: bool,
573}
574
575/// The host that can put a question to the user and relay their answer. Only
576/// the host can: agents hold the key srv's own routes take (see `ask_user`).
577/// With none connected (headless) there is no one to ask, and whatever needs
578/// the answer must not happen, nor wait for one.
579pub(crate) async fn host_to_ask_user(state: &AppState) -> Result<crate::server::HostIpc, String> {
580    state
581        .host_ipc
582        .lock()
583        .await
584        .clone()
585        .ok_or_else(|| "no AgentMux window is connected to ask the user in".to_string())
586}
587
588/// Ask the user a question about the agent in `agent_block_id`, in an approval
589/// subwindow the host opens over the window showing it (crates/cef
590/// `ssh_approval`), and wait for the answer.
591///
592/// Through the host's own IPC server and its token, which no agent holds, and
593/// answered in a window the browser API never resolves a pane into: an agent
594/// can neither click this answer nor forge it, unlike a modal in the main
595/// window answered through srv's own services (both reachable with the auth
596/// key every agent has). With no host connected (headless) there is no one to
597/// ask: `Err`, so whatever needed the answer does not happen.
598pub(crate) async fn ask_user(
599    state: &AppState,
600    agent_block_id: &str,
601    question: serde_json::Value,
602) -> Result<UserAnswer, String> {
603    let host = host_to_ask_user(state).await?;
604    // The agent's pane waits on the user until this returns: the waiting tone
605    // and notification for it (REPORT_AGENT_ATTENTION_CTA_CONTRAST_AND_TONE_2026_10_10.md §2).
606    let title = question.get("title").and_then(|t| t.as_str()).unwrap_or("An agent needs your answer").to_string();
607    let _asking = crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, agent_block_id, "consent", &title);
608    let mut body = question;
609    body["block_id"] = serde_json::json!(agent_block_id);
610    body["timeout_ms"] = serde_json::json!(DIALOG_TIMEOUT_MS);
611    let url = format!("http://127.0.0.1:{}/agentmux/approval/ask", host.port);
612    let resp = state
613        .http_client
614        .post(&url)
615        .header("Authorization", format!("Bearer {}", host.token))
616        .timeout(std::time::Duration::from_millis(DIALOG_TIMEOUT_MS + 15_000))
617        .json(&body)
618        .send()
619        .await
620        .map_err(|e| format!("could not ask the user: {e}"))?;
621    if !resp.status().is_success() {
622        return Err(format!(
623            "could not ask the user: the window host answered HTTP {}",
624            resp.status()
625        ));
626    }
627    let v: serde_json::Value = resp
628        .json()
629        .await
630        .map_err(|e| format!("could not ask the user: {e}"))?;
631    if v.get("ok").and_then(|o| o.as_bool()) != Some(true) {
632        let e = v
633            .get("error")
634            .and_then(|e| e.as_str())
635            .unwrap_or("no answer");
636        return Err(format!("could not ask the user: {e}"));
637    }
638    serde_json::from_value(v.get("data").cloned().unwrap_or_default())
639        .map_err(|e| format!("could not ask the user: {e}"))
640}
641
642/// Ask the person `question`, the confirmation of their own click in pane
643/// `block_id`, as a modal over that pane (`sagas::pane_confirm`). With no pane
644/// named there is nowhere of its own to ask it, so it goes to the approval
645/// window ([`ask_user`]) as before. Either way an agent calling the command
646/// can't give the answer.
647pub(crate) async fn ask_in_pane(
648    state: &AppState,
649    block_id: &str,
650    question: serde_json::Value,
651) -> Result<UserAnswer, String> {
652    use crate::sagas::pane_confirm;
653    if block_id.is_empty() {
654        return ask_user(state, block_id, question).await;
655    }
656    let a = pane_confirm::ask(state, block_id, pane_confirm::Question::from_json(&question)).await?;
657    Ok(UserAnswer { answered: a.answered, approve: a.approve, text: String::new(), checkbox: a.checkbox })
658}
659
660/// The agent an SSH request comes from, proven: its signed identity
661/// (`UiAutomationAuth`, made with its own jekt key, which no other agent
662/// holds) verified, and the pane derived from it, never taken from the
663/// request. `Err` unless that pane is `agent_block_id`: every agent holds
664/// srv's auth key, so a request body alone could name another agent's pane
665/// and borrow its "Always allow".
666pub(crate) fn verified_agent(
667    state: &AppState,
668    agent_block_id: &str,
669    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
670) -> Result<String, String> {
671    verified_agent_as(state, None, agent_block_id, auth)
672}
673
674/// [`verified_agent`] for a caller whose token is known (`caller`): a container agent has a token and no signing
675/// key, and is proven by the token as `Browser` proves it. An SSH connection keeps the signature alone
676/// ([`verified_agent`]): it runs with the person's own identity.
677pub(crate) fn verified_agent_as(
678    state: &AppState,
679    caller: Option<&crate::server::caller::Caller>,
680    agent_block_id: &str,
681    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
682) -> Result<String, String> {
683    let auth = auth.ok_or_else(|| {
684        "an SSH connection needs the agent's signed identity, which this call did not carry (respawn the agent to give it a signing key)".to_string()
685    })?;
686    let pane = crate::server::ui_handlers::verified_block_id(state, caller, auth)
687        .map_err(|e| format!("could not verify which agent is asking: {e}"))?;
688    if pane != agent_block_id {
689        return Err("this request names another agent's pane".to_string());
690    }
691    Ok(auth.agent_id.clone())
692}
693
694/// Tell the user that the agent `agent_id` (verified, [`verified_agent`]) in
695/// `agent_block_id` wants to run `what` on the SSH `connection` with the user's
696/// identity (spec §8.2), and whether it may. `connection` is the canonical name
697/// (`ConnTarget::name`), so one host is one consent however it is spelled.
698/// "Always" for that agent and host is remembered (`remote::agent_access`) and
699/// shows nothing again; otherwise the agent's pane shows a card with a
700/// countdown that goes ahead on its own (`agent_notice`), which the user can
701/// stop, hurry or turn into "Always".
702pub(crate) async fn consent_for_ssh(
703    state: &AppState,
704    agent_block_id: &str,
705    agent_id: &str,
706    connection: &str,
707    what: &str,
708) -> Result<(), String> {
709    use crate::sagas::agent_notice::{self, Kind, Notice, Outcome};
710    let agent_id = Some(agent_id.to_string()).filter(|a| !a.trim().is_empty());
711    let agent = agent_label(agent_id.as_deref());
712    let connection = connection.trim();
713    let notice = Notice {
714        kind: Kind::SshAccess,
715        block_id: agent_block_id.to_string(),
716        agent_id: agent_id.clone().unwrap_or_default(),
717        agent: agent.clone(),
718        connection: connection.to_string(),
719        headline: format!("{} is using {}", one_line(&agent, 60), one_line(connection, 80)),
720        body: format!("It will run this on {}, as you, with your SSH keys.", one_line(connection, 80)),
721        quote: one_line(what, 400),
722        always_label: format!("Always allow {} on {}", one_line(&agent, 40), one_line(connection, 80)),
723        waived: None,
724    };
725    let outcome = agent_notice::announce(state, notice, || super::agent_spawn::requester_here(state, agent_block_id)).await;
726    tracing::info!(agent = %agent, connection = %connection, what = %one_line(what, 200), outcome = ?outcome, "agent ssh access");
727    match outcome {
728        Outcome::Go(_) => Ok(()),
729        Outcome::Stopped => Err(format!("the user stopped {agent} using {connection}")),
730        Outcome::Gone => Err(format!("{agent}'s pane was closed before it could use {connection}")),
731    }
732}
733
734/// Remember "always" for `agent` on `connection` under `config_home`, and tell
735/// every open Connectors → Remotes, whose host rows list these grants.
736pub(crate) fn remember_always_in(
737    broker: &Broker,
738    config_home: &std::path::Path,
739    agent: &str,
740    connection: &str,
741) -> std::io::Result<()> {
742    crate::backend::remote::agent_access::remember_in(config_home, agent, connection)?;
743    remotes::publish_change(broker);
744    Ok(())
745}
746
747/// `POST /api/v1/askpass` body, from `agentmux-bashwrap` as ssh's askpass.
748#[derive(Debug, serde::Deserialize)]
749pub(crate) struct AskpassRequest {
750    secret: String,
751    prompt: String,
752    /// ssh's `SSH_ASKPASS_PROMPT`: `confirm`, `none`, or empty.
753    #[serde(default)]
754    hint: String,
755}
756
757/// `POST /api/v1/askpass`: show an ssh prompt to the user ([`ask_user`]) and
758/// return the answer (`remote::askpass`). Only a live secret is answered, and
759/// the secret, not anything in the request, says which agent and host the
760/// question names.
761pub(crate) async fn handle_askpass(
762    axum::extract::State(state): axum::extract::State<AppState>,
763    axum::Json(req): axum::Json<AskpassRequest>,
764) -> axum::response::Response {
765    use crate::backend::remote::askpass::{self, PromptKind};
766    use axum::http::StatusCode;
767    use axum::response::IntoResponse;
768    let refuse = |code: StatusCode, error: String| {
769        (code, axum::Json(serde_json::json!({ "error": error }))).into_response()
770    };
771    let Some(grant) = askpass::lookup(&req.secret) else {
772        return refuse(StatusCode::FORBIDDEN, "no such ssh prompt".to_string());
773    };
774    let kind = askpass::classify(&req.prompt, &req.hint);
775    // The grant's names are AgentMux's own, shown as plain capped lines all
776    // the same; ssh's prompt is ssh's text.
777    let question = serde_json::json!({
778        "kind": match kind {
779            PromptKind::YesNo => "yesno",
780            PromptKind::Info => "info",
781            PromptKind::Secret => "secret",
782        },
783        "title": format!("SSH: {}", one_line(&grant.connection, 80)),
784        "message": format!(
785            "ssh, connecting to {} for {}, {}:\n\n{}",
786            one_line(&grant.connection, 80),
787            if grant.user_pane {
788                "your terminal".to_string()
789            } else {
790                agent_label(Some(grant.agent.as_str()).filter(|a| !a.is_empty()))
791            },
792            if kind == PromptKind::Info { "says" } else { "asks" },
793            req.prompt.trim().chars().take(2000).collect::<String>()
794        ),
795        "ok_label": match kind {
796            PromptKind::YesNo => "Yes",
797            PromptKind::Info => "OK",
798            PromptKind::Secret => "OK",
799        },
800        "cancel_label": if kind == PromptKind::YesNo { "No" } else { "Cancel" },
801    });
802    // A notice ("touch your security key") is waited on like a question, but
803    // ssh does not wait for it: it kills askpass once done. That drops this
804    // request, which drops the request to the host, whose cleanup closes the
805    // window, so the notice goes exactly when ssh is done with it.
806    match ask_user(&state, &grant.agent_block_id, question).await {
807        Ok(answer) if answer.answered => {
808            // Never logged: the answer may be a password.
809            let text = match kind {
810                PromptKind::YesNo if answer.approve => "yes".to_string(),
811                PromptKind::YesNo => "no".to_string(),
812                PromptKind::Secret if answer.approve => answer.text,
813                PromptKind::Secret => {
814                    return refuse(StatusCode::GONE, "cancelled".to_string());
815                }
816                PromptKind::Info => String::new(),
817            };
818            axum::Json(serde_json::json!({ "answer": text })).into_response()
819        }
820        Ok(_) => refuse(StatusCode::GONE, "not answered".to_string()),
821        Err(e) => refuse(StatusCode::CONFLICT, e),
822    }
823}
824
825/// One row of the agent `ConnList` tool.
826#[derive(Debug, Clone, PartialEq, serde::Serialize)]
827pub(crate) struct ConnEntry {
828    pub connection: String,
829    /// `local`, `wsl` or `ssh`.
830    pub kind: &'static str,
831    /// `connected`, `available` (usable, not opened yet), or a status from
832    /// `remote::status` (`connecting`, `disconnected`, `error`).
833    pub status: String,
834    #[serde(skip_serializing_if = "String::is_empty")]
835    pub error: String,
836    /// Whether an agent can pass it as `connection`: every connection AgentMux
837    /// can run. An SSH host also asks the user for consent the first time
838    /// ([`consent_for_ssh`]).
839    pub agent_can_use: bool,
840}
841
842/// The picker's remote names: the ssh config hosts, then any other SSH
843/// connection known this session, each once.
844pub(crate) fn remote_names(ssh_hosts: &[String], known: &[ConnStatus]) -> Vec<String> {
845    use crate::backend::remote::conn::same_connection;
846    let mut out: Vec<String> = ssh_hosts.to_vec();
847    for s in known {
848        let is_ssh = matches!(ConnTarget::parse(&s.connection), Ok(ConnTarget::Ssh(_)));
849        if is_ssh && !out.iter().any(|n| same_connection(n, &s.connection)) {
850            out.push(s.connection.clone());
851        }
852    }
853    out
854}
855
856/// The connections there are: this machine, each installed WSL distro, the
857/// user's ssh config hosts, and any other connection a pane has used this
858/// session, with its status and whether an agent can use it.
859pub(crate) fn list(
860    wsl_installed: &[String],
861    ssh_hosts: &[String],
862    known: &[ConnStatus],
863) -> Vec<ConnEntry> {
864    use crate::backend::remote::conn::same_connection;
865    let status_of = |name: &str| known.iter().find(|s| same_connection(&s.connection, name));
866    let mut out = vec![ConnEntry {
867        connection: "local".to_string(),
868        kind: "local",
869        status: state::CONNECTED.to_string(),
870        error: String::new(),
871        agent_can_use: true,
872    }];
873    for distro in wsl_installed {
874        let name = ConnTarget::Wsl(distro.clone()).name();
875        let (status, error) = match status_of(&name) {
876            Some(s) => (s.status.clone(), s.error.clone()),
877            None => ("available".to_string(), String::new()),
878        };
879        out.push(ConnEntry {
880            connection: name,
881            kind: "wsl",
882            status,
883            error,
884            agent_can_use: true,
885        });
886    }
887    for host in ssh_hosts {
888        let (status, error) = match status_of(host) {
889            Some(s) => (s.status.clone(), s.error.clone()),
890            None => ("available".to_string(), String::new()),
891        };
892        out.push(ConnEntry {
893            connection: host.clone(),
894            kind: "ssh",
895            status,
896            error,
897            agent_can_use: true,
898        });
899    }
900    for s in known {
901        if out
902            .iter()
903            .any(|e| same_connection(&e.connection, &s.connection))
904        {
905            continue;
906        }
907        let kind = match ConnTarget::parse(&s.connection) {
908            Ok(ConnTarget::Wsl(_)) => "wsl",
909            Ok(ConnTarget::Ssh(_)) => "ssh",
910            _ => continue,
911        };
912        out.push(ConnEntry {
913            connection: s.connection.clone(),
914            kind,
915            status: s.status.clone(),
916            error: s.error.clone(),
917            agent_can_use: true,
918        });
919    }
920    out
921}
922
923/// `GET /api/v1/conn/list`: the agent `ConnList` tool (spec §8.1).
924pub(crate) async fn handle_conn_list() -> axum::Json<Vec<ConnEntry>> {
925    let installed = crate::backend::remote::wsl::list().await;
926    let hosts = tokio::task::spawn_blocking(crate::backend::remote::ssh_config::hosts)
927        .await
928        .unwrap_or_default();
929    axum::Json(list(&installed, &hosts, &status::all()))
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935
936    #[test]
937    fn local_is_accepted_and_remote_is_refused_with_a_status() {
938        let broker = Broker::new();
939        let none: &[String] = &[];
940        let ensure = |name: &str| ensure_with(&broker, name, none, true, false);
941        assert_eq!(ensure("local"), Ok(()));
942        assert_eq!(ensure(""), Ok(()));
943
944        let err = ensure("test-ensure-host").unwrap_err();
945        assert!(err.contains("need the ssh command"), "{err}");
946        // With ssh: accepted, and nothing claimed. Having an ssh command is
947        // not a login: the host showed connected before anything had
948        // connected (#4513). A pane's ssh, or a login, says how it is.
949        assert_eq!(
950            ensure_with(&broker, "test-ensure-ssh-ok", none, true, true),
951            Ok(())
952        );
953        assert!(!status::all()
954            .iter()
955            .any(|s| s.connection == "test-ensure-ssh-ok" && s.connected));
956        let st = status::all()
957            .into_iter()
958            .find(|s| s.connection == "test-ensure-host")
959            .unwrap();
960        assert_eq!(
961            (st.status.as_str(), st.error.as_str()),
962            (state::ERROR, err.as_str())
963        );
964
965        // A name that is not a connection says why, and records nothing.
966        assert!(ensure("-oProxyCommand=calc")
967            .unwrap_err()
968            .contains("cannot start with '-'"));
969        assert!(!status::all().iter().any(|s| s.connection.starts_with('-')));
970    }
971
972    #[test]
973    fn an_installed_wsl_distro_connects_and_a_missing_one_says_so() {
974        let broker = Broker::new();
975        let installed = vec!["Ubuntu".to_string(), "Debian".to_string()];
976        assert_eq!(
977            ensure_with(&broker, "wsl://ubuntu", &installed, true, false),
978            Ok(())
979        );
980        let st = status::all()
981            .into_iter()
982            .find(|s| s.connection == "wsl://ubuntu")
983            .unwrap();
984        assert!(st.connected);
985
986        let err = ensure_with(&broker, "wsl://Arch", &installed, true, false).unwrap_err();
987        assert!(err.contains("'Arch' is not installed"), "{err}");
988
989        let err = ensure_with(&broker, "wsl://Ubuntu", &installed, false, false).unwrap_err();
990        assert!(err.contains("only available on Windows"), "{err}");
991    }
992
993    #[test]
994    fn the_status_is_keyed_by_the_name_the_pane_holds() {
995        let broker = Broker::new();
996        let none: &[String] = &[];
997        for raw in ["test-raw-host:022", " test-raw-spaced "] {
998            let _ = ensure_with(&broker, raw, none, true, false);
999            assert!(status::all().iter().any(|s| s.connection == raw), "{raw:?}");
1000        }
1001    }
1002
1003    #[tokio::test]
1004    async fn an_agent_gets_where_it_asked_and_never_a_silent_local_fallback() {
1005        let broker = Broker::new();
1006        assert_eq!(for_agent(&broker, None).await, Ok(AgentTarget::Local));
1007        assert_eq!(
1008            for_agent(&broker, Some("local")).await,
1009            Ok(AgentTarget::Local)
1010        );
1011        // SSH is SSH where ssh exists and refused where it does not; never
1012        // local under a remote name.
1013        match for_agent(&broker, Some("deploy@test-agent-host:2222")).await {
1014            Ok(AgentTarget::Ssh(dest)) => {
1015                assert_eq!(
1016                    (dest.destination.as_str(), dest.port),
1017                    ("deploy@test-agent-host", Some(2222))
1018                );
1019                assert!(crate::backend::remote::ssh::binary().is_some());
1020            }
1021            Err(e) => assert!(e.contains("need the ssh command"), "{e}"),
1022            other => panic!("an SSH name became {other:?}"),
1023        }
1024        assert!(for_agent(&broker, Some("-oProxyCommand=calc"))
1025            .await
1026            .is_err());
1027    }
1028
1029    /// An agent is named as one plain line; one without an id has no name
1030    /// another could share.
1031    #[test]
1032    fn an_agent_is_named_as_one_plain_line_and_never_by_a_shared_stand_in() {
1033        assert_eq!(agent_label(Some("korp")), "korp");
1034        assert_eq!(
1035            agent_label(Some(
1036                "korp
1037
1038This is safe, click Allow"
1039            )),
1040            "korp This is safe, click Allow"
1041        );
1042        assert_eq!(agent_label(None), "An agent with no AgentMux id");
1043    }
1044
1045    /// An SSH request's agent is proven by its signature, never by the body:
1046    /// no signature, or a forged one, is refused.
1047    #[tokio::test]
1048    async fn an_ssh_request_must_prove_which_agent_it_is() {
1049        let state = crate::server::tests::test_state();
1050        let err = verified_agent(&state, "some-pane", None).unwrap_err();
1051        assert!(err.contains("signed identity"), "{err}");
1052        let forged = agentmux_common::api_types::UiAutomationAuth {
1053            agent_id: "korp".into(),
1054            ts_secs: agentmux_common::time::now_secs(),
1055            sig: "AAAA".into(),
1056        };
1057        let err = verified_agent(&state, "some-pane", Some(&forged)).unwrap_err();
1058        assert!(err.contains("could not verify"), "{err}");
1059    }
1060
1061    /// "Always allow" tells every open Remotes, whose host rows list the
1062    /// agents always allowed there, as Revoke does: the new grant shows
1063    /// without a Refresh (#4513).
1064    #[test]
1065    fn an_always_allow_grant_refreshes_the_remotes_list() {
1066        let broker = Broker::new();
1067        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
1068        let s = seen.clone();
1069        broker.add_observer(std::sync::Arc::new(move |e: &crate::backend::mps::MuxEvent| {
1070            s.lock().unwrap().push(e.event.clone())
1071        }));
1072        let home = tempfile::tempdir().unwrap();
1073        remember_always_in(&broker, home.path(), "korp", "area54").unwrap();
1074        assert!(crate::backend::remote::agent_access::always_allowed_in(home.path(), "korp", "area54"));
1075        assert_eq!(*seen.lock().unwrap(), [crate::backend::mps::EVENT_REMOTES_CHANGE]);
1076    }
1077
1078    /// Agent text in a dialog cannot lay out a message of its own.
1079    #[test]
1080    fn agent_text_in_a_dialog_is_one_capped_line() {
1081        assert_eq!(
1082            one_line("make\n\nAllow it? yes\r\n  test", 100),
1083            "make Allow it? yes test"
1084        );
1085        assert_eq!(one_line("abcdef", 3), "abc…");
1086        assert_eq!(one_line("tab\there", 100), "tab here");
1087    }
1088
1089    fn st(connection: &str, status: &str, error: &str) -> ConnStatus {
1090        ConnStatus {
1091            status: status.to_string(),
1092            connection: connection.to_string(),
1093            error: error.to_string(),
1094            ..Default::default()
1095        }
1096    }
1097
1098    #[test]
1099    fn the_list_is_local_then_the_distros_then_the_ssh_hosts_then_what_panes_have_used() {
1100        let installed = vec!["Ubuntu".to_string(), "Debian".to_string()];
1101        let hosts = vec!["area54".to_string(), "nas".to_string()];
1102        let known = vec![
1103            // Accepted as typed; still the installed Ubuntu, listed once.
1104            st("wsl://ubuntu", state::CONNECTED, ""),
1105            st("area54", state::ERROR, "could not connect"),
1106            st("deploy@10.0.0.5", state::CONNECTED, ""),
1107            st("wsl://Arch", state::ERROR, "not installed"),
1108            // Not a connection: never listed.
1109            st("local", state::CONNECTED, ""),
1110        ];
1111        let got: Vec<(String, &str, String, bool)> = list(&installed, &hosts, &known)
1112            .into_iter()
1113            .map(|e| (e.connection, e.kind, e.status, e.agent_can_use))
1114            .collect();
1115        let want = [
1116            ("local", "local", "connected", true),
1117            ("wsl://Ubuntu", "wsl", "connected", true),
1118            ("wsl://Debian", "wsl", "available", true),
1119            ("area54", "ssh", "error", true),
1120            ("nas", "ssh", "available", true),
1121            ("deploy@10.0.0.5", "ssh", "connected", true),
1122            ("wsl://Arch", "wsl", "error", true),
1123        ];
1124        let want: Vec<(String, &str, String, bool)> = want
1125            .iter()
1126            .map(|(c, k, s, a)| (c.to_string(), *k, s.to_string(), *a))
1127            .collect();
1128        assert_eq!(got, want);
1129    }
1130
1131    /// The picker's "Remote" section: config hosts first, then other SSH
1132    /// connections used this session, never WSL or local.
1133    #[test]
1134    fn the_picker_gets_the_ssh_hosts_and_the_ssh_connections_used() {
1135        let hosts = vec!["area54".to_string(), "nas".to_string()];
1136        let known = vec![
1137            st("area54", state::CONNECTED, ""),
1138            st("deploy@10.0.0.5:2222", state::DISCONNECTED, ""),
1139            st("wsl://Ubuntu", state::CONNECTED, ""),
1140            st("local", state::CONNECTED, ""),
1141        ];
1142        assert_eq!(
1143            remote_names(&hosts, &known),
1144            ["area54", "nas", "deploy@10.0.0.5:2222"]
1145        );
1146    }
1147
1148    fn state() -> AppState {
1149        crate::server::tests::test_state()
1150    }
1151
1152    #[tokio::test]
1153    async fn ending_a_session_needs_the_pane_asking_and_a_real_session_id() {
1154        let state = state();
1155        let end = |block: &str, id: &str| serde_json::json!({ "connname": "host", "sessionid": id, "blockid": block });
1156        let err = conn_session_end(&state, &end("", "s-1")).await.unwrap_err();
1157        assert_eq!(err, "ending a session needs the pane asking, to ask the user in");
1158        let err = conn_session_end(&state, &end("blk", "../x")).await.unwrap_err();
1159        assert!(err.contains("is not a session id"), "{err}");
1160    }
1161
1162    #[tokio::test]
1163    async fn disconnecting_a_wsl_distro_marks_it_disconnected() {
1164        let broker = Broker::new();
1165        conn_disconnect(&broker, &serde_json::json!("wsl://test-disconnect-distro")).await.unwrap();
1166        let st = status::all().into_iter().find(|s| s.connection == "wsl://test-disconnect-distro").expect("a status was recorded");
1167        assert_eq!(st.status, state::DISCONNECTED);
1168        // Anything else is accepted and ignored.
1169        conn_disconnect(&broker, &serde_json::json!(null)).await.unwrap();
1170    }
1171
1172    #[tokio::test]
1173    async fn the_remotes_commands_refuse_local_and_revoke_refuses_a_non_ssh_host() {
1174        let state = state();
1175        let err = remote_forget(&state, CommandRemoteForgetData { connection: "local".into() }).unwrap_err();
1176        assert_eq!(err, "local is not a remote");
1177        let cfg = CommandRemoteSetConfigData { connection: "local".into(), values: Default::default() };
1178        assert_eq!(remote_set_config(&state, cfg).unwrap_err(), "local is not a remote");
1179        let revoke = CommandRemoteAgentRevokeData { agent: "a".into(), connection: "wsl://Ubuntu".into() };
1180        assert!(remote_agent_revoke(&state, revoke).unwrap_err().ends_with(NOT_SSH));
1181    }
1182}