Skip to main content

agentmux_srv/server/app_api/
agent_io.rs

1use super::*;
2use crate::backend::runtime_adapter::{RuntimeAdapter, RuntimeKind};
3
4pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
5    register_agent_send(engine, state);
6    register_agent_stop(engine, state);
7    register_agent_status(engine, state);
8    register_agent_list(engine, state);
9    register_agent_output(engine, state);
10    register_agent_process_list(engine, state);
11    register_agent_tracked_blocks(engine, state);
12    register_swarm_other_instances(engine, state);
13    register_ambient_outcomes(engine);
14    register_agent_open_panes(engine, state);
15    register_agent_kill_process(engine, state);
16    register_agent_kill_tree(engine, state);
17    crate::server::agent_runtime::register(engine, state);
18}
19
20fn register_agent_process_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
21    let process_tracker = state.process_tracker.clone();
22    engine.register_typed(COMMAND_AGENT_PROCESS_LIST, move |cmd: AgentProcessListCommand, _ctx| {
23        let process_tracker = process_tracker.clone();
24        async move {
25                let members = process_tracker.list_block(&cmd.block_id);
26                let confidence = process_tracker.confidence_of(&cmd.block_id);
27                let processes: Vec<AgentProcessInfo> = members
28                    .into_iter()
29                    .map(|m| AgentProcessInfo {
30                        pid: m.pid,
31                        command: m.command,
32                        rss_bytes: m.rss_bytes,
33                        started_at_ms: m.started_at_ms,
34                    })
35                    .collect();
36                Ok(AgentProcessListResult {
37                    block_id: cmd.block_id,
38                    confidence,
39                    processes,
40                })
41        }
42    });
43}
44
45fn register_agent_tracked_blocks(engine: &Arc<WshRpcEngine>, state: &AppState) {
46    let process_broker = state.process_broker.clone();
47    // No argument: `Value` takes whatever the caller sends.
48    engine.register_typed(COMMAND_AGENT_TRACKED_BLOCKS, move |_data: serde_json::Value, _ctx| {
49        let process_broker = process_broker.clone();
50        async move {
51                // Was: `process_tracker.list_all_blocks()` unioned with
52                // `reactive::get_global_handler().list_active_blocks()` — two
53                // structurally different, independently-populated registries
54                // concatenated with no reconciliation (a provider-chain
55                // anti-pattern — see
56                // docs/specs/REPORT_PROCESS_ARCHITECTURE_STATE_AND_RETHINK_2026_07_22.md
57                // §1/§3.0.2). `ProcessBroker::list_agent_panes()` sources
58                // discovery from `blockcontroller::get_all_controllers()`
59                // instead (authoritative for every controller type, closing
60                // the coverage gap the old `process_tracker`-only half had
61                // for `shell`/`acp` blocks) filtered down to agent panes —
62                // `list()` alone would also include plain terminals, which
63                // this RPC's contract has never included (reagent/codex P1).
64                let block_ids: Vec<String> = process_broker
65                    .list_agent_panes()
66                    .into_iter()
67                    .map(|status| status.block_id)
68                    .collect();
69                Ok(AgentTrackedBlocksResult { block_ids })
70        }
71    });
72}
73
74/// This machine's label for each account signed in on it, by the account's stable
75/// id. An account with no stable id (an API key, say) is left out.
76fn account_labels(id_store: &crate::backend::storage::store::Store) -> crate::backend::swarm_remote::AccountLabels {
77    let all = id_store.identity_list(None).unwrap_or_default();
78    all.iter()
79        .filter_map(|a| Some((crate::identity::stable_account::stable_account_id(a)?, super::agent_spawn::account_label_in(a, &all))))
80        .collect()
81}
82
83/// `swarm.other-instances`: this machine's other channels (the host-global shared
84/// registry) and the LAN hosts (the LAN discovery peer list), with their agents'
85/// names (Phases 1 and 2 of SPEC_SWARM_OTHER_HOSTS_AND_CHANNELS_2026_10_02.md)
86/// and, where their instance reports it, their state (Phase 4). No content, no
87/// credentials and no addresses. A peer's agent's account is named only when the
88/// same account is signed in here, and then by this machine's own label for it.
89fn register_swarm_other_instances(engine: &Arc<WshRpcEngine>, state: &AppState) {
90    let hostname = state.hostname.clone();
91    let own_url = state.local_web_url.clone();
92    let lan_discovery = state.lan_discovery.clone();
93    let http = state.http_client.clone();
94    let id_store = state.id_store.clone();
95    // The response stays `Value`: the frontend models the snapshot with its own
96    // types (swarm-remote.ts), which the stub keeps (generated-manifest.json `returns`).
97    engine.register_typed(COMMAND_SWARM_OTHER_INSTANCES, move |_data: serde_json::Value, _ctx| {
98        let hostname = hostname.clone();
99        let own_url = own_url.clone();
100        let lan_peers = lan_discovery.get_instances();
101        let http = http.clone();
102        let id_store = id_store.clone();
103        async move {
104                // Directory, file and store reads; off the async runtime's worker
105                // threads. The definitions give an older channel's agents their
106                // provider (REPORT_SWARM_REMOTE_PROVIDER_ICON_RCA_2026_10_18.md §6.1);
107                // this machine's accounts name the ones a peer's agents run on.
108                let (entries, defined, account_labels) = tokio::task::spawn_blocking(move || {
109                    let entries = crate::registry::resolve_shared_reactive_dir()
110                        .map(|dir| crate::backend::reactive::registry::list_all_shared(&dir))
111                        .unwrap_or_default();
112                    let defined = crate::backend::swarm_remote::defined_providers(&entries);
113                    (entries, defined, account_labels(&id_store))
114                })
115                .await
116                .unwrap_or_default();
117                let own_addrs = crate::backend::lan::listeners::cached_local_addresses();
118                let own_wan_id = crate::backend::swarm_cloud::own_wan_id();
119                let own_channel = crate::backend::reactive::registry::local_channel_id();
120                let now_ms = agentmux_common::time::now_ms_u64();
121                let targets = crate::backend::swarm_remote::channel_status_targets(&entries, &own_channel, &own_url, now_ms);
122                let statuses = crate::backend::swarm_remote::channel_statuses(&http, &targets).await;
123                let mut snapshot = crate::backend::swarm_remote::snapshot(
124                    &entries,
125                    &statuses,
126                    &lan_peers,
127                    &own_addrs,
128                    &crate::backend::swarm_remote::paired_computers(),
129                    &hostname,
130                    &own_channel,
131                    &own_url,
132                    now_ms,
133                );
134                crate::backend::swarm_remote::fill_defined_providers(&mut snapshot, &entries, &defined);
135                crate::backend::swarm_remote::fill_account_labels(&mut snapshot, &account_labels);
136                let cloud = crate::muxbus::cloud_installs::view().await;
137                crate::backend::swarm_cloud::add_cloud(&mut snapshot, cloud.as_ref(), own_wan_id.as_deref(), &lan_peers, now_ms);
138                serde_json::to_value(&snapshot).map_err(|e| format!("swarm.other-instances: {e}"))
139        }
140    });
141}
142
143/// `ambient.outcomes`: how ambient calls have ended since srv started, so "the
144/// swarm has been blank for an hour" is visible without a database copy
145/// (SPEC_AMBIENT_SWARM_SUMMARY_HARDENING_2026_10_02.md section 5.8).
146fn register_ambient_outcomes(engine: &Arc<WshRpcEngine>) {
147    // `Value` response, as for swarm.other-instances: the frontend keeps its own type.
148    engine.register_typed(COMMAND_AMBIENT_OUTCOMES, |_data: serde_json::Value, _ctx| async move {
149        serde_json::to_value(crate::ambient::outcome::snapshot()).map_err(|e| format!("ambient.outcomes: {e}"))
150    });
151}
152
153/// `agent.open-panes`: every agent pane in this instance, wherever it is.
154/// A renderer only knows the panes in its own window, so "is this agent
155/// open?" asked of a renderer misses one in a floating or other window —
156/// My agents then offered a reattach for an agent that was live, and the
157/// second pane could never run (SPEC_AGENT_SAME_PROCESS_DUPLICATE_PANE_
158/// RECOVERY_2026_10_01.md §2 G0). Same source as `agent.tracked-blocks`.
159fn register_agent_open_panes(engine: &Arc<WshRpcEngine>, state: &AppState) {
160    let process_broker = state.process_broker.clone();
161    let mstore = state.mstore.clone();
162    engine.register_typed(COMMAND_AGENT_OPEN_PANES, move |_data: serde_json::Value, _ctx| {
163        let process_broker = process_broker.clone();
164        let mstore = mstore.clone();
165        async move {
166                let block_ids: Vec<String> = process_broker
167                    .list_agent_panes()
168                    .into_iter()
169                    .map(|status| status.block_id)
170                    .collect();
171                let panes = tokio::task::spawn_blocking(move || open_agent_panes(&mstore, &block_ids))
172                    .await
173                    .map_err(|e| format!("agent.open-panes: {e}"))?;
174                Ok(AgentOpenPanesResult { panes })
175        }
176    });
177}
178
179/// Where each of `block_ids` is open: its agent, tab, and the windows
180/// showing its workspace. The agent is resolved like the rest of srv
181/// resolves a block's agent (`instance_get_active_for_block`: `agentId`,
182/// the legacy `agent:id`, a template-launched row, the latest launch on the
183/// block) so a pane from an older build is not reported closed (Codex P1 on
184/// #4127); the raw meta id is the fallback when that finds no row. Blocks
185/// with no resolvable agent or no parent tab are skipped. Workspaces and
186/// windows are read once for the whole list.
187pub(crate) fn open_agent_panes(store: &Store, block_ids: &[String]) -> Vec<AgentOpenPane> {
188    let workspaces = store.get_all::<Workspace>().unwrap_or_default();
189    let windows = store.get_all::<obj::Window>().unwrap_or_default();
190    let mut panes: Vec<AgentOpenPane> = block_ids
191        .iter()
192        .filter_map(|block_id| {
193            let block = store.get::<Block>(block_id).ok().flatten()?;
194            let agent_id = match store.instance_get_active_for_block(block_id) {
195                Ok(Some(row)) if !row.id.is_empty() => row.id,
196                _ => {
197                    let meta_id = obj::meta_get_string(&block.meta, "agentId", "");
198                    if meta_id.is_empty() {
199                        obj::meta_get_string(&block.meta, "agent:id", "")
200                    } else {
201                        meta_id
202                    }
203                }
204            };
205            if agent_id.is_empty() {
206                return None;
207            }
208            let tab_id = block.parentoref.strip_prefix("tab:")?.to_string();
209            let tab = store.get::<Tab>(&tab_id).ok().flatten()?;
210            let mut window_ids: Vec<String> = workspaces
211                .iter()
212                .find(|w| w.tabids.contains(&tab_id) || w.pinnedtabids.contains(&tab_id))
213                .map(|ws| {
214                    windows
215                        .iter()
216                        .filter(|w| w.workspaceid == ws.oid)
217                        .map(|w| w.oid.clone())
218                        .collect()
219                })
220                .unwrap_or_default();
221            window_ids.sort();
222            Some(AgentOpenPane { block_id: block_id.clone(), agent_id, tab_id, tab_name: tab.name, window_ids })
223        })
224        .collect();
225    panes.sort_by(|a, b| a.block_id.cmp(&b.block_id));
226    panes
227}
228
229/// Every pane of the agent whose definition id is `agent_id`, in every
230/// window and tab of this instance, running or not (a pane whose agent has
231/// stopped, a pane in a window nobody is looking at): where it is open, as
232/// [`open_agent_panes`] reports it. `window_ids` is empty for a pane no window
233/// shows. One agent should have one pane; a caller that is about to make one
234/// (an import, a restore, a drag) asks this first and reuses what it finds
235/// instead of creating a second.
236pub(crate) fn agent_panes_of(store: &Store, agent_id: &str) -> Vec<AgentOpenPane> {
237    if agent_id.is_empty() {
238        return Vec::new();
239    }
240    let agent_blocks: Vec<String> = store
241        .get_all::<Block>()
242        .unwrap_or_default()
243        .into_iter()
244        .filter(|b| {
245            ["agentId", "agent:id", "view"].iter().any(|k| {
246                let v = obj::meta_get_string(&b.meta, k, "");
247                !v.is_empty() && (*k != "view" || v == "agent")
248            })
249        })
250        .map(|b| b.oid)
251        .collect();
252    open_agent_panes(store, &agent_blocks)
253        .into_iter()
254        .filter(|pane| pane.agent_id == agent_id)
255        .collect()
256}
257
258/// An agent's connection ends processes only under its own block or a worker's it opened. Another
259/// agent's go through `agent.stop`, which gives the person their override window, so killing them
260/// directly would skip it.
261pub(crate) async fn refuse_other_agents_processes(state: &AppState, caller: &str, block_id: &str) -> Result<(), String> {
262    match window_caller_for(state, caller, block_id).await {
263        Some(_) => Err(format!(
264            "FORBIDDEN: block {block_id} belongs to another agent; stop it with Agents stop (its user gets a window to keep it running)"
265        )),
266        None => Ok(()),
267    }
268}
269
270/// `fleet.bulk-stop` from the agent `caller`: its own block and its workers stop at once, every
271/// other agent's opens the override window (`pending` in the answer) and stops when it runs out.
272/// A `staged` rollout can't be applied to those windows (they all open at once), so it is refused
273/// when any target is another agent's.
274pub(crate) async fn agent_bulk_stop(
275    state: &AppState,
276    caller: &str,
277    targets: Vec<String>,
278    signal: Option<&str>,
279    staged: Option<StagePlanInput>,
280) -> Result<FleetActionResult, String> {
281    let (mut waits, mut at_once, mut by) = (Vec::new(), Vec::new(), None);
282    for block_id in targets {
283        match window_caller_for(state, caller, &block_id).await {
284            Some(who) => {
285                by.get_or_insert(who);
286                waits.push(block_id);
287            }
288            None => at_once.push(block_id),
289        }
290    }
291    if staged.is_some() && !waits.is_empty() {
292        return Err("staged rollouts don't apply to other agents' blocks from an agent; stop them without `staged`".to_string());
293    }
294    let mut result = if at_once.is_empty() {
295        FleetActionResult::default()
296    } else {
297        super::fleet::fleet_bulk_stop_impl(state, at_once, signal, staged.clone()).await
298    };
299    if let Some(by) = by {
300        let (now, pending) = super::fleet::fleet_stop_keep_pane_with_override(state, &by, waits, signal, staged).await;
301        result.succeeded.extend(now.succeeded);
302        result.failed.extend(now.failed);
303        result.aborted_early |= now.aborted_early;
304        result.pending.extend(pending.into_iter().map(|v| v.block_id));
305    }
306    Ok(result)
307}
308
309fn register_agent_kill_process(engine: &Arc<WshRpcEngine>, state: &AppState) {
310    let state = state.clone();
311    engine.register_typed(COMMAND_AGENT_KILL_PROCESS, move |cmd: AgentKillProcessCommand, ctx| {
312        let state = state.clone();
313        async move {
314                refuse_other_agents_processes(&state, &ctx.agent_id, &cmd.block_id).await?;
315                tracing::info!(
316                    block_id = %cmd.block_id,
317                    pid = cmd.pid,
318                    "agent.kill-process"
319                );
320                let ok = state.process_tracker.kill_pid(&cmd.block_id, cmd.pid);
321                Ok(AgentKillResult { ok })
322        }
323    });
324}
325
326fn register_agent_kill_tree(engine: &Arc<WshRpcEngine>, state: &AppState) {
327    let state = state.clone();
328    engine.register_typed(COMMAND_AGENT_KILL_TREE, move |cmd: AgentKillTreeCommand, ctx| {
329        let state = state.clone();
330        async move {
331                refuse_other_agents_processes(&state, &ctx.agent_id, &cmd.block_id).await?;
332                tracing::info!(block_id = %cmd.block_id, "agent.kill-tree");
333                let ok = state.process_tracker.kill_tree(&cmd.block_id);
334                Ok(AgentKillResult { ok })
335        }
336    });
337}
338
339/// The environment an `agent.send` spawn is given: `cmd:env` through
340/// `build_persistent_spawn_env`, exactly as the `agentinput` path builds it
341/// — identity gate, MuxBus token, wrapper auth, agent identity (UID + token
342/// for a row-backed block, `AGENTMUX_AGENT_ID` from `agentName` when
343/// `cmd:env` lacks it), git identity, tools PATH. Identity M4b-1 (spec
344/// §6.5.8); factored out so the carriage is testable.
345pub(crate) async fn agent_send_spawn_env(
346    mstore: Arc<crate::backend::storage::store::Store>,
347    id_store: Arc<crate::backend::storage::store::Store>,
348    identity_store: Arc<crate::backend::storage::store::Store>,
349    broker: Option<Arc<crate::backend::mps::Broker>>,
350    block: &Block,
351    block_id: &str,
352    auth_key: &str,
353) -> Result<std::collections::HashMap<String, String>, crate::identity::resolver::SpawnGateError> {
354    let env_vars = crate::backend::blockcontroller::cmd_env_of(&block.meta);
355    crate::backend::spawn_env::build::build_persistent_spawn_env(
356        mstore,
357        id_store,
358        identity_store,
359        broker,
360        &block.meta,
361        block_id,
362        auth_key,
363        env_vars,
364    )
365    .await
366}
367
368/// The launch settings `agent.send` reads from the block's metadata, shared by
369/// the persistent and subprocess dispatch.
370struct SendLaunch {
371    cli_command: String,
372    cli_args: Vec<String>,
373    working_dir: String,
374    env_vars: std::collections::HashMap<String, String>,
375    session_id_field: String,
376}
377
378/// A pre-spawn identity gate refusal: put the error frame where the pane
379/// reads it, record the structured failure, and return the RPC error.
380fn refuse_spawn_gate(
381    state: &AppState,
382    block_id: &str,
383    gate: &crate::identity::resolver::SpawnGateError,
384) -> String {
385    show_refused_spawn(state, block_id, &gate.to_string());
386    format!("identity spawn gate: {gate}")
387}
388
389/// As `agentinput` does first: a harness other than Claude Code is not started on the host in a folder a
390/// container agent can write (`mcp_folder_rule`), and the pane is told why. A Claude turn there goes on, and the
391/// pane is told which servers of the folder's own file it is not given. Asked off the async workers (it reads
392/// the disk).
393async fn folder_gate(state: &AppState, block: &Block) -> Result<(), String> {
394    let meta = block.meta.clone();
395    let refusal = tokio::task::spawn_blocking(move || crate::backend::mcp_folder_rule::turn_refusal(&meta))
396        .await
397        .unwrap_or_else(|_| Some(crate::backend::mcp_folder_rule::TURN_REFUSAL.to_string()));
398    if let Some(why) = refusal {
399        show_refused_spawn(state, &block.oid, &why);
400        return Err(why);
401    }
402    crate::server::mcp_folder_notice::tell(&state.broker, &state.filestore, &state.mstore, block).await;
403    Ok(())
404}
405
406/// Put a refused spawn's reason where the pane reads it, and record the structured failure.
407fn show_refused_spawn(state: &AppState, block_id: &str, reason: &str) {
408    let error_frame = serde_json::json!({
409        "type": "result",
410        "is_error": true,
411        "subtype": "error_during_execution",
412        "error": {"message": format!("[AgentMux] {reason}")}
413    })
414    .to_string();
415    // Some(filestore): the frame must be PERSISTED to the
416    // block file, not just live-broadcast — otherwise the
417    // error vanishes on pane reload/reconnect (reagent P1,
418    // PR #2164 round 2). And to the agent's global zone,
419    // which is what a pane with an agentId reloads from
420    // (Phase 5a-3c).
421    // Not for the refusal a pane bound with Open here expects and answers with Move here: it reaches
422    // the recovery row below, and stays out of the history (open_here_mark.rs).
423    if !crate::backend::open_here_mark::expected_for_block(&state.mstore, block_id, reason) {
424        let global_zone = crate::backend::transcript::append::resolve_global_output_zone(
425            &Some(state.mstore.clone()),
426            block_id,
427        );
428        crate::backend::blockcontroller::shell::handle_append_block_file(
429            &state.broker,
430            block_id,
431            crate::backend::blockcontroller::subprocess::SUBPROCESS_OUTPUT_SUBJECT,
432            format!("{error_frame}\n").as_bytes(),
433            Some(&state.filestore),
434            global_zone.as_deref(),
435        );
436    }
437    // codex P1, PR #2802: same fix as agent_handlers/
438    // input.rs's agentinput handler — the frame above
439    // only lands in the block's raw output log, which
440    // the recovery banner does NOT read from. Classify
441    // + persist + publish so the structured card
442    // (agent:last_failure meta + EVENT_AGENT_FAILURE)
443    // populates for this pre-spawn refusal too.
444    let gate_failure = crate::agents::failure::classify(
445        None,
446        None,
447        reason,
448        None,
449    );
450    crate::backend::blockcontroller::core::persist_last_failure(
451        block_id,
452        Some(&gate_failure),
453        &Some(state.mstore.clone()),
454        &Some(state.event_bus.clone()),
455    );
456    state.broker.publish_event::<crate::backend::mps_events::AgentFailed>(&gate_failure, vec![format!("block:{block_id}")], 1);
457}
458
459/// `agent.send` to a persistent-CLI block. Returns the controller's session id.
460fn send_via_persistent(
461    persistent_ctrl: &blockcontroller::persistent::PersistentSubprocessController,
462    block: &Block,
463    launch: SendLaunch,
464    message: String,
465    record: crate::backend::message_origin::RecordOrigin,
466) -> Result<Option<String>, String> {
467    let SendLaunch { cli_command, cli_args, working_dir, env_vars, session_id_field } = launch;
468    // Container agents use per-turn docker exec — incompatible with a
469    // long-lived persistent subprocess. Fail loudly instead of silently
470    // spawning the CLI on the host.
471    if !RuntimeKind::of_block_meta(&block.meta).adapter().accepts_persistent_controller() {
472        return Err("container agents require a subprocess controller; this provider uses a persistent controller".to_string());
473    }
474    // Resume parity with the subprocess path: pass the resume
475    // flag + captured session id so a respawn (e.g. after a
476    // /model change) continues the same conversation.
477    let resume_flag = obj::meta_get_string(
478        &block.meta, "agent:resume_flag", "--resume",
479    );
480    let persisted_session_id = obj::meta_get_string(
481        &block.meta, "agent:sessionid", "",
482    );
483    let config = blockcontroller::persistent::PersistentSpawnConfig {
484        cli_command,
485        cli_args,
486        working_dir,
487        env_vars,
488        session_id_field,
489        resume_flag,
490        session_id: persisted_session_id,
491        message_id: None,
492    };
493    persistent_ctrl.send_message_from(message, config, None, record)?;
494    Ok(persistent_ctrl.session_id())
495}
496
497/// `agent.send` to a per-turn subprocess block (a host CLI or a container exec).
498async fn send_via_subprocess(
499    state: &AppState,
500    subprocess_ctrl: &blockcontroller::subprocess::SubprocessController,
501    block: &Block,
502    block_id: &str,
503    launch: SendLaunch,
504    message: String,
505    record: crate::backend::message_origin::RecordOrigin,
506) -> Result<(), String> {
507    let SendLaunch { cli_command, cli_args, working_dir, mut env_vars, session_id_field } = launch;
508    let resume_flag = obj::meta_get_string(
509        &block.meta, "agent:resume_flag", "--resume",
510    );
511    let resume_strategy = obj::meta_get_string(
512        &block.meta,
513        "agent:resume_strategy",
514        if session_id_field == "thread_id" {
515            "codex-exec"
516        } else if resume_flag.is_empty() {
517            "none"
518        } else {
519            "flag"
520        },
521    );
522    let prompt_arg_flag =
523        obj::meta_get_string(&block.meta, "agent:prompt_arg_flag", "");
524    // Picker reattach (parallel of the websocket-path
525    // logic): hydrate the persisted session id from
526    // block meta so spawn_turn appends --resume <sid>
527    // on the FIRST turn after reattach.
528    let persisted_session_id = obj::meta_get_string(
529        &block.meta, "agent:sessionid", "",
530    );
531
532    // Container agent: a Docker socket API exec per turn (P1a: no secrets in argv).
533    // Host agent: a regular CLI subprocess. The adapter is the one place the two differ.
534    let adapter: Box<dyn RuntimeAdapter> = match RuntimeKind::of_block_meta(&block.meta) {
535        RuntimeKind::Host => RuntimeKind::Host.adapter(),
536        RuntimeKind::Container => {
537            let cm = state.container_manager.get_or_explain().await?;
538            // The same container, mounts and `AGENTMUX_LOCAL_URL` rewrite the
539            // `agentinput` path builds: without the rewrite a container agent opened
540            // via the MuxAPI path gets no sidecar URL at all.
541            Box::new(crate::server::agent_handlers::container_turn::container_adapter_for_block(
542                cm,
543                block_id,
544                &block.meta,
545                &mut env_vars,
546                &working_dir,
547                state.broker.clone(),
548                state.filestore.clone(),
549                state.mstore.clone(),
550            ))
551        }
552    };
553    adapter.materialize(subprocess_ctrl);
554    // Cross-process session-lease key (registry::LeaseStore). Only a host turn enforces it.
555    let instance_id = obj::meta_get_string(&block.meta, "agentId", "");
556    let config = blockcontroller::subprocess::SubprocessSpawnConfig {
557        cli_command,
558        cli_args,
559        working_dir,
560        env_vars,
561        message,
562        resume_flag,
563        resume_strategy,
564        prompt_arg_flag,
565        session_id_field,
566        message_id: None,
567        session_id: if persisted_session_id.is_empty() { None } else { Some(persisted_session_id) },
568        instance_id,
569        record: Some(record.clone()),
570    };
571    adapter.launch(subprocess_ctrl, config)?;
572    Ok(())
573}
574
575/// `agent.send`: deliver a message to the agent running in a block, by
576/// whichever controller type the block has.
577pub(crate) async fn agent_send(state: &AppState, cmd: CommandAgentSendData) -> Result<AgentSendResult, String> {
578    tracing::info!(block_id = %cmd.block_id, "agent.send");
579    // The caller of this command is not proven here, so it is never the human.
580    let record = crate::backend::message_origin::RecordOrigin::new(
581        crate::backend::message_origin::MessageOrigin::of(crate::backend::blockcontroller::health::TriggerKind::Agent),
582    );
583
584    let ctrl = blockcontroller::get_controller(&cmd.block_id)
585        .ok_or_else(|| format!("NOT_RUNNING: no controller for block {}", cmd.block_id))?;
586
587    // Re-read spawn config from block metadata (same pattern as agentinput)
588    let block: Block = state
589        .mstore
590        .get(&cmd.block_id)
591        .map_err(|e| format!("agent.send: {e}"))?
592        .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", cmd.block_id))?;
593
594    let cli_command = obj::meta_get_string(&block.meta, "cmd", "claude");
595    let cli_args: Vec<String> = match block.meta.get("cmd:args") {
596        Some(serde_json::Value::Array(arr)) => arr
597            .iter()
598            .filter_map(|v| v.as_str().map(|s| s.to_string()))
599            .collect(),
600        _ => vec![],
601    };
602    folder_gate(state, &block).await?;
603    // Same backstop as `agentinput`: this path has no frontend rebuild.
604    let cli_args = crate::backend::agent_runtime::with_runtime_flags(&block.meta, cli_args);
605    let working_dir = obj::meta_get_string(&block.meta, "cmd:cwd", "");
606    // Identity M4b-1 (spec §6.5.8): the same env builder as
607    // `agentinput`, so a row-backed block's process carries its
608    // UID + token — and the wrapper auth, MuxBus, identity and
609    // PATH vars `agentinput` gives — instead of a hand copy that
610    // had only the identity gate. Same gate error, same arm below.
611    let env_vars = match agent_send_spawn_env(
612        state.mstore.clone(),
613        state.id_store.clone(),
614        state.identity_store.clone(),
615        Some(state.broker.clone()),
616        &block,
617        &cmd.block_id,
618        // Identity M4b-1: `build_persistent_spawn_env` re-injects the wrapper's
619        // auth key, as `agentinput` does.
620        &state.auth_key,
621    )
622    .await
623    {
624        Ok(env) => env,
625        Err(gate) => return Err(refuse_spawn_gate(state, &cmd.block_id, &gate)),
626    };
627    let session_id_field = obj::meta_get_string(
628        &block.meta, "agent:session_id_field", "session_id",
629    );
630    let launch = SendLaunch { cli_command, cli_args, working_dir, env_vars, session_id_field };
631
632    // Dispatch to persistent or subprocess controller
633    let mut session_id = None;
634    // App Server owns a persistent thread/turn process and has its own
635    // typed protocol path — mirrors the websocket agentinput dispatch in
636    // agent_handlers/input.rs, which was already updated for this
637    // controller type. Without this branch, an app-server-backed agent
638    // opened via agent.open could never receive a turn via agent.send
639    // (ReAgent P1, PR #3215).
640    if let Some(app_server_ctrl) = ctrl
641        .as_any()
642        .downcast_ref::<blockcontroller::app_server_controller::AppServerController>()
643    {
644        app_server_ctrl.send_message_from(cmd.message, Vec::new(), false, Some(&record))?;
645    } else if let Some(persistent_ctrl) = ctrl
646        .as_any()
647        .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
648    {
649        session_id = send_via_persistent(persistent_ctrl, &block, launch, cmd.message, record)?;
650    } else if let Some(subprocess_ctrl) = ctrl
651        .as_any()
652        .downcast_ref::<blockcontroller::subprocess::SubprocessController>()
653    {
654        send_via_subprocess(state, subprocess_ctrl, &block, &cmd.block_id, launch, cmd.message, record).await?;
655    } else if let Some(acp_ctrl) =
656        blockcontroller::session_agent::session_agent(ctrl.as_ref())
657    {
658        // If the agent exited, start it again; the message waits
659        // for the new session.
660        acp_ctrl.ensure_started(block.meta.clone())?;
661        acp_ctrl.send_message(cmd.message, None, Some(&record))?;
662    } else {
663        return Err("NOT_RUNNING: controller type not supported".to_string());
664    }
665
666    Ok(AgentSendResult {
667        block_id: cmd.block_id,
668        status: "running".to_string(),
669        session_id,
670    })
671}
672
673/// `agent.send` from a connection: the text goes into the agent's input unmarked, as the person's own turn, so only the
674/// AgentMux window sends it. An agent reaches another agent with the Message tool, which is delivered as a jekt.
675pub(crate) async fn agent_send_from(state: &AppState, ctx: &RpcContext, cmd: CommandAgentSendData) -> Result<AgentSendResult, String> {
676    crate::server::agent_handlers::window_only(ctx)?;
677    agent_send(state, cmd).await
678}
679
680fn register_agent_send(engine: &Arc<WshRpcEngine>, state: &AppState) {
681    let s = state.clone();
682    engine.register_typed(COMMAND_AGENT_SEND, move |cmd: CommandAgentSendData, ctx| {
683        let s = s.clone();
684        async move { agent_send_from(&s, &ctx, cmd).await }
685    });
686}
687
688/// Core `agent.stop` logic, factored out so `fleet.bulk-stop`
689/// (`server/app_api/fleet.rs`) can loop it per target instead of
690/// duplicating the controller-lookup/stop/status-read sequence.
691pub(crate) async fn stop_one_agent_block(
692    state: &AppState,
693    block_id: &str,
694    signal: Option<&str>,
695    stop_background: Option<bool>,
696) -> Result<AgentStopResult, String> {
697    tracing::info!(block_id = %block_id, signal = ?signal, ?stop_background, "agent.stop");
698
699    let force = matches!(signal, Some("SIGKILL") | Some("SIGTERM"));
700    crate::sagas::agent_teardown::stop(state, block_id, !force, stop_background).await?;
701
702    let exit_code = blockcontroller::get_block_controller_status(block_id)
703        .map(|s| s.shellprocexitcode);
704
705    Ok(AgentStopResult {
706        block_id: block_id.to_string(),
707        status: "done".to_string(),
708        exit_code,
709    })
710}
711
712fn register_agent_stop(engine: &Arc<WshRpcEngine>, state: &AppState) {
713    let state = state.clone();
714    engine.register_typed(COMMAND_AGENT_STOP_API, move |cmd: CommandAgentStopApiData, ctx| {
715        let state = state.clone();
716        async move {
717            // A connection registered as an agent that stops another agent waits for the person's
718            // override window, like `Agents stop`; the window's own connection stops at once.
719            if let Some(pending) = override_window_for(&state, &ctx.agent_id, &cmd).await {
720                return Ok(pending);
721            }
722            stop_one_agent_block(&state, &cmd.block_id, cmd.signal.as_deref(), cmd.stop_background).await
723        }
724    });
725}
726
727/// The agent an override window is opened for, when `caller` (a connection's registered agent,
728/// empty for the person's window) acts on `block_id` that is another agent's: `Some(by)`, the caller's
729/// uid (its name when it has none). `None` for the window itself, the agent's own block and a worker
730/// it opened, which it ends at once.
731pub(crate) async fn window_caller_for(state: &AppState, caller: &str, block_id: &str) -> Option<String> {
732    if caller.trim().is_empty() {
733        return None;
734    }
735    let (store, block, name) = (state.mstore.clone(), block_id.to_string(), caller.to_string());
736    let (caller_uid, target_uid) = tokio::task::spawn_blocking(move || {
737        (crate::backend::agent_resolve::resolve_agent_id(&store, &name).ok(), crate::backend::agent_resolve::uid_for_block(&store, &block))
738    })
739    .await
740    .ok()?;
741    if let (Some(c), Some(t)) = (&caller_uid, &target_uid) {
742        if !super::agent_lifecycle::needs_window(&state.mstore, c, t) {
743            return None;
744        }
745    }
746    Some(caller_uid.unwrap_or_else(|| caller.to_string()))
747}
748
749/// The answer when `agent.stop` on `cmd.block_id` opened an override window for the agent `caller`
750/// (a connection's registered agent, empty for the window), or `None` when the stop is immediate:
751/// the window's own, the agent's own block, or a worker it opened.
752async fn override_window_for(state: &AppState, caller: &str, cmd: &CommandAgentStopApiData) -> Option<AgentStopResult> {
753    let by = window_caller_for(state, caller, &cmd.block_id).await?;
754    let (_, pending) = super::fleet::fleet_stop_keep_pane_with_override_opts(state, &by, vec![cmd.block_id.clone()], cmd.signal.as_deref(), cmd.stop_background, None).await;
755    pending.into_iter().next().map(|_| AgentStopResult { block_id: cmd.block_id.clone(), status: "pending_override".to_string(), exit_code: None })
756}
757
758fn register_agent_status(engine: &Arc<WshRpcEngine>, state: &AppState) {
759    let mstore = state.mstore.clone();
760
761    engine.register_typed(COMMAND_AGENT_STATUS, move |cmd: CommandAgentStatusData, _ctx| {
762        let mstore = mstore.clone();
763        async move {
764                let block: Block = mstore
765                    .get(&cmd.block_id)
766                    .map_err(|e| format!("agent.status: {e}"))?
767                    .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", cmd.block_id))?;
768
769                let agent_id = obj::meta_get_string(&block.meta, "agentId", "");
770                let provider = obj::meta_get_string(&block.meta, "agentProvider", "");
771                let controller_type = obj::meta_get_string(&block.meta, "controller", "");
772
773                let runtime = blockcontroller::get_block_controller_status(&cmd.block_id);
774                let status = runtime.as_ref()
775                    .map(|s| s.shellprocstatus.clone())
776                    .unwrap_or_else(|| "init".to_string());
777                let exit_code = runtime.as_ref()
778                    .and_then(|s| if s.shellprocstatus == "done" { Some(s.shellprocexitcode) } else { None });
779                let pid = None; // PID not currently exposed in status struct
780
781                // Get session ID from block meta
782                let session_id = block.meta.get("agent:sessionid")
783                    .and_then(|v| v.as_str())
784                    .map(|s| s.to_string());
785
786                Ok(AgentStatusResult {
787                    block_id: cmd.block_id,
788                    agent_id,
789                    provider,
790                    controller_type,
791                    status,
792                    session_id,
793                    pid,
794                    exit_code,
795                })
796        }
797    });
798}
799
800/// The agents of `agent.list`: every agent block in a tab or parked (a parked one has an empty `tab_id`).
801pub(crate) fn agent_list_entries(mstore: &Store) -> Result<Vec<AgentListEntry>, String> {
802    let mut agents = Vec::new();
803    for (block, tab) in super::agent_block::blocks_in_tabs_or_parked(mstore)? {
804        let agent_id = obj::meta_get_string(&block.meta, "agentId", "");
805        if agent_id.is_empty() {
806            continue;
807        }
808        let provider = obj::meta_get_string(&block.meta, "agentProvider", "");
809        let status = blockcontroller::get_block_controller_status(&block.oid)
810            .map(|s| s.shellprocstatus)
811            .unwrap_or_else(|| "init".to_string());
812        let session_id = block.meta.get("agent:sessionid").and_then(|v| v.as_str()).map(|s| s.to_string());
813        let route_cost_usd = crate::backend::model_gateway::spend::session_usd(&agent_id);
814        agents.push(AgentListEntry { block_id: block.oid.clone(), tab_id: tab.unwrap_or_default(), agent_id, provider, status, session_id, route_cost_usd });
815    }
816    Ok(agents)
817}
818
819fn register_agent_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
820    let mstore = state.mstore.clone();
821
822    // No argument: `Value` takes whatever the caller sends.
823    engine.register_typed(COMMAND_AGENT_LIST, move |_data: serde_json::Value, _ctx| {
824        let mstore = mstore.clone();
825        async move {
826                let agents = agent_list_entries(&mstore).map_err(|e| format!("agent.list: {e}"))?;
827
828                Ok(AgentListResult { agents })
829        }
830    });
831}
832
833fn register_agent_output(engine: &Arc<WshRpcEngine>, state: &AppState) {
834    let broker = state.broker.clone();
835
836    engine.register_typed(COMMAND_AGENT_OUTPUT, move |cmd: CommandAgentOutputData, _ctx| {
837        let broker = broker.clone();
838        async move {
839                let scope = format!("block:{}", cmd.block_id);
840                let max = cmd.max_lines.unwrap_or(1000);
841                let after = cmd.after_line.unwrap_or(0);
842
843                // Read persisted blockfile events from broker history
844                let mut all_lines: Vec<String> = Vec::new();
845                {
846                    let events = broker.read_event_history(
847                        crate::backend::mps::EVENT_BLOCK_FILE,
848                        &scope,
849                        max + after, // read enough to cover offset
850                    );
851                    for event in events {
852                        if let Some(ref data) = event.data {
853                            if let Some(data64) = data.get("data64").and_then(|v| v.as_str()) {
854                                if let Ok(bytes) = base64::engine::general_purpose::STANDARD
855                                    .decode(data64)
856                                {
857                                    let text = String::from_utf8_lossy(&bytes);
858                                    for line in text.lines() {
859                                        if !line.trim().is_empty() {
860                                            all_lines.push(line.to_string());
861                                        }
862                                    }
863                                }
864                            }
865                        }
866                    }
867                }
868
869                let total = all_lines.len();
870                let lines: Vec<String> = all_lines.into_iter()
871                    .skip(after)
872                    .take(max)
873                    .collect();
874                let has_more = after + lines.len() < total;
875
876                Ok(AgentOutputResult {
877                    block_id: cmd.block_id,
878                    lines,
879                    total_lines: total,
880                    has_more,
881                })
882        }
883    });
884}
885
886#[cfg(test)]
887mod tests {
888    use super::*;
889    use crate::backend::storage::agents::test_agent_def;
890    use crate::backend::storage::store::Store;
891
892    fn block_with(store: &Store, block_id: &str, agent_id: &str) -> Block {
893        let mut block = Block {
894            oid: block_id.to_string(),
895            parentoref: String::new(),
896            version: 0,
897            runtimeopts: None,
898            stickers: None,
899            meta: {
900                let mut m = obj::MetaMapType::new();
901                m.insert("view".to_string(), serde_json::json!("agent"));
902                m.insert("agentId".to_string(), serde_json::json!(agent_id));
903                m.insert("agentName".to_string(), serde_json::json!("AgentY"));
904                m.insert("cmd:env".to_string(), serde_json::json!({"KEEP_ME": "1"}));
905                m
906            },
907            subblockids: None,
908        };
909        store.insert(&mut block).unwrap();
910        block
911    }
912
913    async fn env_for(
914        store: &Arc<Store>,
915        block: &Block,
916    ) -> std::collections::HashMap<String, String> {
917        agent_send_spawn_env(
918            store.clone(),
919            store.clone(),
920            store.clone(),
921            None,
922            block,
923            &block.oid,
924            "test-key",
925        )
926        .await
927        .expect("no spawn gate for a provider without credentials")
928    }
929
930    /// Identity M4b-1 (spec §6.5.8): an `agent.send` spawn on a row-backed
931    /// block carries that row's UID and its own token — the env
932    /// `agentinput` builds — plus the block's `cmd:env` and the wrapper
933    /// auth key. Before M4b-1 it got `cmd:env` + identity injection only.
934    #[tokio::test]
935    async fn an_agent_send_spawn_carries_the_rows_uid_and_token() {
936        let store = Arc::new(Store::open_in_memory().unwrap());
937        store.apply_identity_schema_for_tests().unwrap();
938        // A provider with no credential class, so the spawn gate (which
939        // refuses an OAuth-class agent with no bound account) stays out of
940        // a test about identity carriage.
941        let mut def = test_agent_def(
942            "uid-send-y",
943            "AgentY",
944            "test-no-credentials",
945            "agent",
946            1,
947            "",
948        );
949        def.slug = "agenty".to_string();
950        store.agent_def_insert(&mut def).unwrap();
951        let block = block_with(&store, "block-send-y", "uid-send-y");
952
953        let env = env_for(&store, &block).await;
954        assert_eq!(
955            env.get("AGENTMUX_AGENT_UID").map(String::as_str),
956            Some("uid-send-y")
957        );
958        let token = store
959            .agent_token_load("uid-send-y")
960            .unwrap()
961            .expect("minted");
962        assert_eq!(env.get("AGENTMUX_AGENT_TOKEN"), Some(&token));
963        assert_eq!(
964            env.get("KEEP_ME").map(String::as_str),
965            Some("1"),
966            "cmd:env kept"
967        );
968        assert_eq!(
969            env.get("AGENTMUX_AUTH_KEY").map(String::as_str),
970            Some("test-key")
971        );
972    }
973
974    /// Plain-`gh` guard: a spawn built through `build_persistent_spawn_env` —
975    /// the path `agentinput`, eager resume and `agent.send` all share — points
976    /// `GH_CONFIG_DIR` at the agent's login-free dir, overriding a value the
977    /// block's `cmd:env` carries (e.g. a human's real gh config).
978    #[tokio::test]
979    async fn an_agent_send_spawn_overrides_gh_config_dir_with_the_guard_dir() {
980        let store = Arc::new(Store::open_in_memory().unwrap());
981        store.apply_identity_schema_for_tests().unwrap();
982        let mut def = test_agent_def("uid-gh-y", "AgentY", "test-no-credentials", "agent", 1, "");
983        def.slug = "agenty".to_string();
984        store.agent_def_insert(&mut def).unwrap();
985        let mut block = block_with(&store, "block-gh-y", "uid-gh-y");
986        block.meta.insert(
987            "cmd:env".to_string(),
988            serde_json::json!({"GH_CONFIG_DIR": "/home/human/.config/gh"}),
989        );
990        store.update(&mut block).unwrap();
991
992        let env = env_for(&store, &block).await;
993        let dir = std::path::PathBuf::from(env.get("GH_CONFIG_DIR").expect("always set"));
994        assert_eq!(dir.parent(), Some(crate::backend::gh_guard::guard_config_home().as_path()));
995        assert!(
996            dir.file_name().unwrap().to_string_lossy().starts_with("gh-"),
997            "{}",
998            dir.display()
999        );
1000        assert_ne!(dir, std::path::PathBuf::from("/home/human/.config/gh"));
1001    }
1002
1003    /// A block with no row (a provider-key pane) gets neither.
1004    #[tokio::test]
1005    async fn an_agent_send_spawn_without_a_row_carries_no_uid_or_token() {
1006        let store = Arc::new(Store::open_in_memory().unwrap());
1007        store.apply_identity_schema_for_tests().unwrap();
1008        let block = block_with(&store, "block-send-none", "claude");
1009        let env = env_for(&store, &block).await;
1010        assert!(!env.contains_key("AGENTMUX_AGENT_UID"));
1011        assert!(!env.contains_key("AGENTMUX_AGENT_TOKEN"));
1012    }
1013}
1014
1015#[cfg(test)]
1016mod open_panes_tests {
1017    use super::*;
1018    use crate::backend::storage::store::Store;
1019
1020    fn insert_tab(store: &Store, name: &str) -> Tab {
1021        let mut tab = Tab { oid: uuid::Uuid::new_v4().to_string(), name: name.to_string(), ..Default::default() };
1022        store.insert(&mut tab).unwrap();
1023        tab
1024    }
1025
1026    fn insert_workspace(store: &Store, tab_ids: &[&str]) -> Workspace {
1027        let mut ws = Workspace {
1028            oid: uuid::Uuid::new_v4().to_string(),
1029            tabids: tab_ids.iter().map(|t| t.to_string()).collect(),
1030            ..Default::default()
1031        };
1032        store.insert(&mut ws).unwrap();
1033        ws
1034    }
1035
1036    fn insert_window(store: &Store, workspace_id: &str) -> obj::Window {
1037        let mut w = obj::Window { oid: uuid::Uuid::new_v4().to_string(), workspaceid: workspace_id.to_string(), ..Default::default() };
1038        store.insert(&mut w).unwrap();
1039        w
1040    }
1041
1042    fn insert_block(store: &Store, tab_id: &str, agent_id: Option<&str>) -> String {
1043        let mut meta = obj::MetaMapType::new();
1044        if let Some(a) = agent_id {
1045            meta.insert("agentId".to_string(), serde_json::json!(a));
1046        }
1047        let mut block = Block {
1048            oid: uuid::Uuid::new_v4().to_string(),
1049            parentoref: format!("tab:{tab_id}"),
1050            meta,
1051            ..Default::default()
1052        };
1053        store.insert(&mut block).unwrap();
1054        block.oid
1055    }
1056
1057    /// The 2026-10-01 case: Korp torn off into a floating window (its own
1058    /// workspace and `Window`), a second agent in the main window. Both are
1059    /// reported, each with the window that shows it.
1060    #[test]
1061    fn lists_agent_panes_in_every_window_including_a_floating_one() {
1062        let store = Store::open_in_memory().unwrap();
1063        let main_tab = insert_tab(&store, "Tab 2");
1064        let main_ws = insert_workspace(&store, &[&main_tab.oid]);
1065        let main_win = insert_window(&store, &main_ws.oid);
1066        let float_tab = insert_tab(&store, "");
1067        let float_ws = insert_workspace(&store, &[&float_tab.oid]);
1068        let float_win = insert_window(&store, &float_ws.oid);
1069
1070        let agent3 = insert_block(&store, &main_tab.oid, Some("agent3-def"));
1071        let korp = insert_block(&store, &float_tab.oid, Some("korp-def"));
1072
1073        let panes = open_agent_panes(&store, &[agent3.clone(), korp.clone()]);
1074        let korp_pane = panes.iter().find(|p| p.block_id == korp).expect("floating pane listed");
1075        assert_eq!(korp_pane.agent_id, "korp-def");
1076        assert_eq!(korp_pane.tab_id, float_tab.oid);
1077        assert_eq!(korp_pane.window_ids, vec![float_win.oid]);
1078        let a3 = panes.iter().find(|p| p.block_id == agent3).expect("main pane listed");
1079        assert_eq!(a3.tab_name, "Tab 2");
1080        assert_eq!(a3.window_ids, vec![main_win.oid]);
1081    }
1082
1083    /// Every pane of one agent, wherever it is, and no other agent's.
1084    #[test]
1085    fn agent_panes_of_finds_all_of_an_agents_panes_and_only_its_own() {
1086        let store = Store::open_in_memory().unwrap();
1087        let tab_a = insert_tab(&store, "Tab 4");
1088        let ws_a = insert_workspace(&store, &[&tab_a.oid]);
1089        let win_a = insert_window(&store, &ws_a.oid);
1090        let tab_b = insert_tab(&store, "Tab 4");
1091        let ws_b = insert_workspace(&store, &[&tab_b.oid]);
1092        let win_b = insert_window(&store, &ws_b.oid);
1093        // A workspace no window shows.
1094        let tab_c = insert_tab(&store, "Parked");
1095        insert_workspace(&store, &[&tab_c.oid]);
1096
1097        let first = insert_block(&store, &tab_a.oid, Some("qtest-def"));
1098        let second = insert_block(&store, &tab_b.oid, Some("qtest-def"));
1099        let parked = insert_block(&store, &tab_c.oid, Some("qtest-def"));
1100        let other = insert_block(&store, &tab_a.oid, Some("korp-def"));
1101        insert_block(&store, &tab_a.oid, None);
1102
1103        let panes = agent_panes_of(&store, "qtest-def");
1104        let mut got: Vec<&str> = panes.iter().map(|p| p.block_id.as_str()).collect();
1105        got.sort();
1106        let mut want = vec![first.as_str(), second.as_str(), parked.as_str()];
1107        want.sort();
1108        assert_eq!(got, want);
1109        assert!(!panes.iter().any(|p| p.block_id == other));
1110        let by_block = |id: &str| panes.iter().find(|p| p.block_id == id).unwrap();
1111        assert_eq!(by_block(&first).window_ids, vec![win_a.oid]);
1112        assert_eq!(by_block(&second).window_ids, vec![win_b.oid]);
1113        assert!(by_block(&parked).window_ids.is_empty(), "a pane no window shows is still a pane");
1114        assert!(agent_panes_of(&store, "nobody-def").is_empty());
1115        assert!(agent_panes_of(&store, "").is_empty());
1116    }
1117
1118    /// A pane from an older build carries only the legacy `agent:id` key.
1119    #[test]
1120    fn resolves_a_legacy_agent_id_pane_to_its_agent_row() {
1121        let store = Store::open_in_memory().unwrap();
1122        let mut def = crate::backend::storage::agents::test_agent_def(
1123            "uid-legacy",
1124            "Korp",
1125            "test-no-credentials",
1126            "agent",
1127            1,
1128            "",
1129        );
1130        store.agent_def_insert(&mut def).unwrap();
1131        let tab = insert_tab(&store, "t");
1132        insert_workspace(&store, &[&tab.oid]);
1133        let mut meta = obj::MetaMapType::new();
1134        meta.insert("agent:id".to_string(), serde_json::json!("uid-legacy"));
1135        let mut block = Block {
1136            oid: uuid::Uuid::new_v4().to_string(),
1137            parentoref: format!("tab:{}", tab.oid),
1138            meta,
1139            ..Default::default()
1140        };
1141        store.insert(&mut block).unwrap();
1142
1143        let panes = open_agent_panes(&store, &[block.oid.clone()]);
1144        assert_eq!(panes.len(), 1);
1145        assert_eq!(panes[0].agent_id, "uid-legacy");
1146    }
1147
1148    #[test]
1149    fn skips_non_agent_and_orphan_blocks_and_reports_a_windowless_workspace() {
1150        let store = Store::open_in_memory().unwrap();
1151        let tab = insert_tab(&store, "t");
1152        insert_workspace(&store, &[&tab.oid]); // open in no window
1153        let terminal = insert_block(&store, &tab.oid, None);
1154        let agent = insert_block(&store, &tab.oid, Some("def"));
1155        let missing = "no-such-block".to_string();
1156
1157        let panes = open_agent_panes(&store, &[terminal, agent.clone(), missing]);
1158        assert_eq!(panes.len(), 1);
1159        assert_eq!(panes[0].block_id, agent);
1160        assert!(panes[0].window_ids.is_empty());
1161    }
1162}