Skip to main content

agentmux_srv/server/agent_handlers/
input.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::sync::Arc;
5
6use crate::backend::blockcontroller;
7use crate::backend::obj::Block;
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    AttachmentRef, CommandAgentInputData, CommandAgentStopData, CommandSubprocessSpawnData, COMMAND_AGENT_INPUT,
11    COMMAND_AGENT_STOP, COMMAND_SUBPROCESS_SPAWN, RpcContext,
12};
13
14use super::super::AppState;
15use super::turn_steps as steps;
16
17
18use crate::backend::spawn_env::block_identity::{
19    carry_agent_uid_env, carry_agent_workdir_env, deleted_agent_of_rowless_block, persisted_agent_identity,
20    split_agent_identity_env,
21};
22#[cfg(test)]
23use crate::backend::spawn_env::block_identity::{carry_block_identity_env, PersistedAgentIdentity};
24
25/// The slice of [`AppState`] an agent turn needs in order to be started.
26///
27/// Exists so [`run_agent_turn`] can be driven from somewhere other than the
28/// `agentinput` RPC handler it was originally inlined in. The second caller is
29/// the reactive handler's message sender (`bootstrap::install_agent_turn_delivery`):
30/// a `SubprocessController` starts a turn ONLY via this path, so without a
31/// non-RPC entry point every inter-agent message addressed to one was dropped.
32/// See `docs/reports/REPORT_JEKT_DELIVERY_DROPS_SUBPROCESS_AGENTS_2026_09_02.md`.
33///
34/// Field names match the local bindings the extracted body already used, so the
35/// body itself is unchanged by the extraction.
36#[derive(Clone)]
37pub struct AgentTurnDeps {
38    pub mstore: Arc<crate::backend::storage::store::Store>,
39    pub id_store: Arc<crate::backend::storage::store::Store>,
40    pub identity_store: Arc<crate::backend::storage::store::Store>,
41    /// Streaming-bash wrapper auth key — see SPEC_STREAMING_BASH_RUNNER_2026_05_11.md §7.
42    pub auth_key: String,
43    pub broker: Arc<crate::backend::mps::Broker>,
44    pub container_manager: Arc<crate::backend::container::ContainerRuntimeHandle>,
45    /// Named `filestore_gate` because the spawn-gate error frame MUST be
46    /// persisted through it, not merely live-broadcast (reagent P1, PR #2164).
47    pub filestore_gate: Arc<crate::backend::storage::filestore::FileStore>,
48    pub local_web_url: String,
49    pub event_bus_gate: Arc<crate::backend::eventbus::EventBus>,
50}
51
52impl AgentTurnDeps {
53    pub fn from_state(state: &AppState) -> Self {
54        Self {
55            mstore: state.mstore.clone(),
56            id_store: state.id_store.clone(),
57            identity_store: state.identity_store.clone(),
58            auth_key: state.auth_key.clone(),
59            broker: state.broker.clone(),
60            container_manager: state.container_manager.clone(),
61            filestore_gate: state.filestore.clone(),
62            local_web_url: state.local_web_url.clone(),
63            event_bus_gate: state.event_bus.clone(),
64        }
65    }
66}
67
68/// Start one agent turn for `block_id` with `message`.
69///
70/// This is the whole of what `AgentInputCommand` does, verbatim: re-read the
71/// spawn config from block meta, inject identity/muxbus/bashwrap env (failing
72/// closed on the oauth spawn gate), then dispatch to the persistent controller,
73/// the host subprocess path, or the container `docker exec` path as the block's
74/// `agentMode` and controller type require — and finally re-register the agent
75/// for reactive delivery.
76///
77/// Extracted from the `agentinput` handler body with no behavior change so a
78/// second, non-RPC caller can reach it; see [`AgentTurnDeps`].
79/// Whether starting a turn should also (re-)register the agent for reactive
80/// delivery.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum TurnRegistration {
83    /// The RPC / UI path. Registers, exactly as `AgentInputCommand` always has.
84    Register,
85    /// The reactive-delivery path (`bootstrap::install_agent_turn_delivery`).
86    /// Skipping is required, for two independent reasons:
87    ///
88    /// 1. **Redundant.** That caller resolved this block *by looking the agent
89    ///    up in the reactive handler's own registry* (`uid_to_block` /
90    ///    `name_to_blocks`), so the agent
91    ///    is registered by construction. There is nothing to re-register.
92    /// 2. **Deadlock.** `ReactiveHandler::inject_message` holds the global
93    ///    `Mutex<Handler>` across the message-sender call, and that sender
94    ///    drives this function to completion on the same thread. The
95    ///    registration below calls `get_global_handler().register_agent(...)`,
96    ///    which locks that same `std::sync::Mutex` — which is NOT reentrant.
97    ///    Registering here would block the thread on a lock it already holds,
98    ///    wedging the reactive handler process-wide, on essentially every
99    ///    successful delivery to a subprocess agent (reagent P0 on PR #2930).
100    Skip,
101}
102
103/// Why `run_agent_turn` refused to spawn, before any process started.
104pub(super) enum TurnGate {
105    /// Another AgentMux instance on this host runs this agent.
106    Admission(String),
107    /// The identity/credential spawn gate refused.
108    Identity(crate::identity::resolver::SpawnGateError),
109    /// The agent's harness is not started on the host in its folder (`mcp_folder_rule`).
110    Folder(String),
111}
112
113impl std::fmt::Display for TurnGate {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            TurnGate::Admission(refusal) | TurnGate::Folder(refusal) => f.write_str(refusal),
117            TurnGate::Identity(e) => write!(f, "{e}"),
118        }
119    }
120}
121
122/// A held message's join hint, armed for one dispatch. Dropped without
123/// `keep` (the dispatch failed), it is cleared, so no later message can take
124/// it (#4492).
125pub(super) struct ArmedJoinHint(Option<std::sync::Arc<crate::backend::blockcontroller::health::TurnActivityTracker>>);
126
127impl ArmedJoinHint {
128    pub(super) fn arm(
129        joins_turn: Option<u64>,
130        tracker: Option<std::sync::Arc<crate::backend::blockcontroller::health::TurnActivityTracker>>,
131    ) -> Self {
132        match (joins_turn, tracker) {
133            (Some(turn_id), Some(tracker)) => {
134                tracker.hint_join(turn_id);
135                Self(Some(tracker))
136            }
137            _ => Self(None),
138        }
139    }
140
141    /// The dispatch went through: the pass it starts takes the hint.
142    pub(super) fn keep(mut self) {
143        self.0 = None;
144    }
145}
146
147impl Drop for ArmedJoinHint {
148    fn drop(&mut self) {
149        if let Some(tracker) = self.0.take() {
150            tracker.clear_join_hint();
151        }
152    }
153}
154
155pub async fn run_agent_turn(
156    deps: &AgentTurnDeps,
157    block_id: String,
158    message: String,
159    message_id: Option<String>,
160    registration: TurnRegistration,
161    from: crate::backend::message_origin::MessageOrigin,
162    attachments: Vec<AttachmentRef>,
163) -> Result<(), String> {
164    run_agent_turn_joining(deps, block_id, message, message_id, registration, from, attachments, None, false).await
165}
166
167/// [`run_agent_turn`] for a message the pane held while turn `joins_turn`
168/// ran: if that turn is still settling (or only just ended), the message
169/// joins it rather than starting a new one (turn-model spec §4.3, J3).
170/// `resend`: the pane sends the message again, so it is delivered but not recorded a second time.
171#[allow(clippy::too_many_arguments)]
172pub async fn run_agent_turn_joining(
173    deps: &AgentTurnDeps,
174    block_id: String,
175    message: String,
176    message_id: Option<String>,
177    registration: TurnRegistration,
178    from: crate::backend::message_origin::MessageOrigin,
179    attachments: Vec<AttachmentRef>,
180    joins_turn: Option<u64>,
181    resend: bool,
182) -> Result<(), String> {
183    let origin = from.turn_origin();
184
185    let ctrl = blockcontroller::get_controller(&block_id)
186        .ok_or_else(|| format!("no controller for block {}", block_id))?;
187
188    // Re-read the spawn config from block metadata
189    let block: Block = deps.mstore
190        .get(&block_id)
191        .map_err(|e| format!("agentinput: load block: {e}"))?
192        .ok_or_else(|| format!("block {} not found", block_id))?;
193    steps::refuse_retired_harness(deps, &block_id, &block.meta)?;
194    let base = steps::spawn_base(&block);
195    let env_vars = crate::backend::blockcontroller::cmd_env_of(&block.meta);
196    let env_result = steps::gated_spawn_env(deps, &ctrl, &block, &block_id, env_vars).await;
197    let env_vars = match env_result {
198        Ok(env) => env,
199        Err(gate) => {
200            steps::surface_refusal(deps, &block_id, &gate.to_string());
201            return Err(match &gate {
202                TurnGate::Admission(refusal) | TurnGate::Folder(refusal) => refusal.clone(),
203                TurnGate::Identity(e) => format!("identity spawn gate: {e}"),
204            });
205        }
206    };
207    // Identity M2: the UID this turn's spawn env carries (M1a), kept for the
208    // Register-tail below so registration is keyed by identity without a
209    // second store read (spec §4.4.1 row 2). `None` when the block has no
210    // row yet — the tail then registers by name, counted.
211    let turn_uid: Option<String> = env_vars
212        .get("AGENTMUX_AGENT_UID")
213        .map(|u| u.trim().to_string())
214        .filter(|u| !u.is_empty());
215    let turn_agent_id = env_vars.get("AGENTMUX_AGENT_ID").cloned(); // the stable binding, as spawn parks it
216
217    let session_id_field =
218        crate::backend::obj::meta_get_string(&block.meta, "agent:session_id_field", "session_id");
219
220    let (message, inline_images, image_paths) = steps::prepare_attachments(deps, &ctrl, &block, &block_id, message, attachments).await?;
221    // The person's own words carry the mark only srv writes (`MessageOrigin::as_model_text`); the record drops it.
222    let message = from.as_model_text(&message).into_owned();
223    let (message, held_notes) = crate::backend::reactive::held_notes::attach_for_turn(&block_id, &message, origin);
224    let record = crate::backend::message_origin::RecordOrigin { origin: from.clone(), notes: held_notes.note_texts(), resend };
225    let turn = steps::Turn { deps, block: &block, block_id: &block_id, base, env_vars, session_id_field, message, message_id, from, joins_turn, record, inline_images, image_paths };
226
227    if let Some(app_server_ctrl) =
228        ctrl.as_any()
229            .downcast_ref::<blockcontroller::app_server_controller::AppServerController>()
230    {
231        steps::dispatch_app_server(turn, app_server_ctrl, ctrl.turn_tracker())?;
232    }
233    // Try persistent controller first, fall back to subprocess
234    else if let Some(persistent_ctrl) =
235        ctrl.as_any()
236            .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
237    {
238        steps::dispatch_persistent(turn, persistent_ctrl)?;
239    } else if let Some(subprocess_ctrl) =
240        ctrl.as_any()
241            .downcast_ref::<blockcontroller::subprocess::SubprocessController>()
242    {
243        steps::dispatch_subprocess(turn, subprocess_ctrl, ctrl.turn_tracker()).await?;
244    } else if let Some(acp_ctrl) =
245        blockcontroller::session_agent::session_agent(ctrl.as_ref())
246    {
247        steps::dispatch_session_agent(turn, acp_ctrl, ctrl.turn_tracker())?;
248    } else {
249        return Err(
250            "controller is not a SubprocessController, PersistentSubprocessController or session agent"
251                .to_string(),
252        );
253    }
254    held_notes.delivered();
255
256    // Registration is skipped on the reactive-delivery path — see
257    // `TurnRegistration::Skip` for why that is both redundant AND a hard
258    // deadlock requirement, not an optimisation.
259    if matches!(registration, TurnRegistration::Register) {
260        steps::register_turn_agent(&block, &block_id, &deps.local_web_url, turn_agent_id.as_deref(), turn_uid.as_deref());
261    }
262
263    Ok(())
264}
265
266pub fn register_agent_input_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
267    // subprocessspawn → spawn agent CLI as subprocess for a single turn
268    let state_spawn = state.clone();
269    engine.register_typed(COMMAND_SUBPROCESS_SPAWN, move |cmd: CommandSubprocessSpawnData, _ctx| {
270        let state = state_spawn.clone();
271        async move { subprocess_spawn(&state, cmd) }
272    });
273
274    // agentinput → send message to agent (persistent or per-turn subprocess).
275    // Everything the turn needs from AppState now travels as one
276    // `AgentTurnDeps` (see its doc comment for why it is a named struct rather
277    // than nine separate closure captures).
278    let deps_ai = AgentTurnDeps::from_state(state);
279    engine.register_typed(COMMAND_AGENT_INPUT, move |cmd: CommandAgentInputData, ctx| {
280        let deps = deps_ai.clone();
281        async move { agent_input(&deps, &ctx, cmd).await }
282    });
283
284    // agentstop → stop the running agent subprocess
285    let state_stop = state.clone();
286    engine.register_typed(COMMAND_AGENT_STOP, move |cmd: CommandAgentStopData, ctx| {
287        let mstore = state_stop.mstore.clone();
288        async move {
289            crate::server::pane_caller::agent_acts_on_own_pane(&mstore, &ctx, &cmd.blockid, "stopping an agent")?;
290            agent_stop(cmd)
291        }
292    });
293}
294
295/// `subprocessspawn`: run the CLI for one turn in the block's subprocess controller, creating it if needed.
296pub(crate) fn subprocess_spawn(state: &AppState, cmd: CommandSubprocessSpawnData) -> Result<(), String> {
297    let (mstore, broker, event_bus, filestore, boot_id) = (
298        state.mstore.clone(),
299        state.broker.clone(),
300        state.event_bus.clone(),
301        state.filestore.clone(),
302        state.boot_id.clone(),
303    );
304
305    tracing::info!(
306        block_id = %cmd.blockid,
307        cli = %cmd.cli_command,
308        "SubprocessSpawn"
309    );
310
311    // Get or create a SubprocessController for this block
312    let ctrl = match blockcontroller::get_controller(&cmd.blockid) {
313        Some(c)
314            if c.controller_type() == blockcontroller::BLOCK_CONTROLLER_SUBPROCESS =>
315        {
316            c
317        }
318        _ => {
319            // Create and register a new SubprocessController
320            let registry = mstore.shared_agent_registry();
321            let ctrl = blockcontroller::subprocess::SubprocessController::new(
322                cmd.tabid.clone(),
323                cmd.blockid.clone(),
324                Some(broker),
325                Some(event_bus),
326                Some(mstore),
327                Some(filestore),
328                registry,
329                boot_id,
330            );
331            let ctrl = std::sync::Arc::new(ctrl);
332            ctrl.set_self_ref();
333            blockcontroller::register_controller(&cmd.blockid, ctrl.clone());
334            ctrl as std::sync::Arc<dyn blockcontroller::Controller>
335        }
336    };
337
338    // Downcast to SubprocessController to call spawn_turn
339    let subprocess_ctrl = ctrl
340        .as_any()
341        .downcast_ref::<blockcontroller::subprocess::SubprocessController>()
342        .ok_or_else(|| "controller is not a SubprocessController".to_string())?;
343
344    let config = blockcontroller::subprocess::SubprocessSpawnConfig {
345        cli_command: cmd.cli_command,
346        cli_args: cmd.cli_args,
347        working_dir: cmd.working_dir,
348        env_vars: cmd.env_vars,
349        message: cmd.message,
350        resume_flag: "--resume".to_string(),
351        resume_strategy: "flag".to_string(),
352        prompt_arg_flag: String::new(),
353        session_id_field: "session_id".to_string(),
354        message_id: None,
355        // Direct-spawn legacy command — caller doesn't
356        // carry a reattach context. Greenfield session id
357        // is None; spawn_turn captures it from CLI stdout
358        // on the first turn as before.
359        session_id: None,
360        // COMMAND_SUBPROCESS_SPAWN has no block to read
361        // agentId from (dead code — unused by the
362        // frontend, per grep); empty disables leasing.
363        instance_id: String::new(),
364        record: None,
365    };
366    subprocess_ctrl.spawn_turn(config)?;
367    Ok(())
368}
369
370/// `agentinput`: a message typed into the composer (or a hidden reinjection), started as a turn.
371pub(crate) async fn agent_input(deps: &AgentTurnDeps, ctx: &RpcContext, cmd: CommandAgentInputData) -> Result<(), String> {
372    if cmd.prestart == Some(true) {
373        crate::server::pane_caller::agent_acts_on_own_pane(&deps.mstore, ctx, &cmd.blockid, "starting a pane's container")?;
374        return super::container_turn::prestart(deps, cmd.blockid).await;
375    }
376    // From the connection, before anything else runs (composer_origin.rs).
377    let origin = super::composer_origin::composer_origin(ctx, cmd.hidden.unwrap_or(false) || cmd.system.unwrap_or(false))?;
378    tracing::info!(block_id = %cmd.blockid, "AgentInput");
379    // Authoritative hidden-window gate for ambient digest reads
380    // (next_prompt_suggestion / activity_summary / activity_watcher)
381    // — set here, not reconstructed from transcript bytes. See
382    // crate::ambient::digest::set_hidden_reinjection_active's doc comment.
383    crate::ambient::digest::set_hidden_reinjection_active(
384        &cmd.blockid,
385        cmd.hidden.unwrap_or(false) && !crate::backend::memory::delivery::is_catch_up_text(&cmd.message),
386    );
387    // A re-delivery srv composed (`memorydelivery:compose`): its
388    // card is written once the message has gone to the agent
389    // (below), never for one that didn't start.
390    let fallback_card = cmd
391        .hidden
392        .unwrap_or(false)
393        .then_some(())
394        .and(cmd.delivery_id.as_deref())
395        .and_then(|id| crate::server::memory_delivery_handlers::take_fallback_frame(&cmd.blockid, id));
396    // A post-compaction memory reinjection also carries the
397    // agent's running summary (SPEC_DURABLE_CONVERSATION_MEMORY
398    // §4.4, "Compaction reuse").
399    let message = if cmd.hidden.unwrap_or(false) {
400        crate::backend::continuity_state::with_state_after_compaction(&deps.mstore, &cmd.blockid, cmd.message)
401    } else {
402        cmd.message
403    };
404    let block_id = cmd.blockid.clone();
405    run_agent_turn_joining(
406        deps,
407        cmd.blockid,
408        message,
409        cmd.message_id,
410        TurnRegistration::Register,
411        crate::backend::message_origin::MessageOrigin::from_composer(origin),
412        cmd.attachments.unwrap_or_default(),
413        cmd.joins_turn,
414        cmd.resend.unwrap_or(false),
415    )
416    .await?;
417    // Right after the hidden message's own transcript line: replay
418    // shows this card in its place (parseHistoryLines.ts).
419    if let Some(frame) = fallback_card {
420        crate::backend::cli_notice::append_to_pane(&deps.broker, &deps.filestore_gate, &deps.mstore, &block_id, &frame);
421    }
422    Ok(())
423}
424
425/// `agentstop`: stop the block's controller, and take its name-keyed side state down.
426pub(crate) fn agent_stop(cmd: CommandAgentStopData) -> Result<(), String> {
427    tracing::info!(block_id = %cmd.blockid, force = cmd.force, "AgentStop");
428    match blockcontroller::get_controller(&cmd.blockid) {
429        Some(_) => {
430            // The one teardown path, Stop policy (SPEC_AGENT_TEARDOWN_SINGLE_PATH §5).
431            crate::sagas::agent_teardown::stop_now(&cmd.blockid, !cmd.force)?;
432            // Deregister: unregister_block cleans up both agent_to_block and
433            // block_to_agent maps; remove_agent then removes the cloud poll entry
434            // using the logical agent_id recovered from block_to_agent.
435            let handler = crate::backend::reactive::handler::get_global_handler();
436            // Identity M2: a block can be bound under two names
437            // (display + stable); tear down the name-keyed side
438            // state for EACH, not just the display name — the
439            // stable name's file entry was written at spawn and
440            // its cloud subscription would otherwise leak.
441            let names = handler.unregister_block(&cmd.blockid);
442            let data_dir = crate::backend::base::get_mux_data_dir();
443            let sub = crate::muxbus::cloud_subscriber::get_global_subscriber();
444            for name in &names {
445                // Symmetric teardown for the registry writes added
446                // alongside SubprocessSpawn's register_agent call.
447                crate::backend::reactive::registry::remove(&data_dir, name);
448                crate::backend::reactive::registry::remove_shared_from_env(name);
449                if let Some(sub) = sub {
450                    sub.remove_agent(name);
451                }
452            }
453            // A stop leaves no registration behind, under any name: an entry a turn filed under the
454            // block's current name is not one of `names`, and would read as "running" afterwards.
455            crate::backend::reactive::registry::remove_for_block(&data_dir, &cmd.blockid, None);
456            crate::backend::reactive::registry::remove_shared_for_block_from_env(&cmd.blockid, None);
457            Ok(())
458        }
459        // Stopping a block with no controller is a no-op, not an
460        // error: the UI cannot tell "already stopped" from "never
461        // started", and either way the caller's intent is
462        // satisfied.
463        None => Ok(()),
464    }
465}
466
467#[cfg(test)]
468mod tests {
469
470    // ---- identity M0: split_agent_identity_env ---------------------------
471    //
472    // Fixture per SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md §9.3:
473    // two agents whose names collide under `derive_slug` ("AgentY" and
474    // "AGENTY" both lowercase to "agenty"), which `agent_def_insert` gave
475    // the suffixed slugs `agenty-2` / `agenty-3`. Every assertion below is
476    // made against that pair so a change that only works for one agent
477    // cannot pass.
478
479    use super::split_agent_identity_env;
480    use std::collections::HashMap;
481
482    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
483        pairs
484            .iter()
485            .map(|(k, v)| (k.to_string(), v.to_string()))
486            .collect()
487    }
488
489    /// The server launch path (`input.rs` fallback) — `cmd:env` carries
490    /// nothing identity-shaped, so both must be filled from what the server
491    /// knows. Positive case first (retro §5): prove they are SET before
492    /// proving anything about what they are not.
493    #[test]
494    fn server_path_sets_both_display_and_slug_from_server_knowledge() {
495        let mut e = env(&[("AGENTMUX_AGENT_ID", "AgentY")]);
496        split_agent_identity_env(&mut e, "AgentY", Some("agenty-3"));
497        assert_eq!(e["AGENTMUX_AGENT_DISPLAY"], "AgentY");
498        assert_eq!(e["AGENTMUX_AGENT_SLUG"], "agenty-3");
499    }
500
501    /// The frontend launch path (`launchAgentDefinition`) already set both
502    /// to the same values the server holds — nothing changes, nothing is
503    /// duplicated under a different key.
504    #[test]
505    fn frontend_path_with_agreeing_values_is_left_as_is() {
506        let before = env(&[
507            ("AGENTMUX_AGENT_ID", "agenty-2"),
508            ("AGENTMUX_AGENT_SLUG", "agenty-2"),
509            ("AGENTMUX_AGENT_DISPLAY", "AGENTY"),
510        ]);
511        let mut e = before.clone();
512        split_agent_identity_env(&mut e, "AGENTY", Some("agenty-2"));
513        assert_eq!(e, before);
514    }
515
516    /// §9.4: this phase must not change what `AGENTMUX_AGENT_ID` holds on
517    /// either path. Slug-valued on the frontend path, name-valued on the
518    /// server path — both survive byte-for-byte.
519    #[test]
520    fn agentmux_agent_id_is_never_touched_on_either_path() {
521        let mut frontend = env(&[("AGENTMUX_AGENT_ID", "agenty-2")]);
522        split_agent_identity_env(&mut frontend, "AGENTY", Some("agenty-2"));
523        assert_eq!(frontend["AGENTMUX_AGENT_ID"], "agenty-2");
524
525        let mut server = env(&[("AGENTMUX_AGENT_ID", "AgentY")]);
526        split_agent_identity_env(&mut server, "AgentY", Some("agenty-3"));
527        assert_eq!(server["AGENTMUX_AGENT_ID"], "AgentY");
528
529        let mut none = env(&[]);
530        split_agent_identity_env(&mut none, "AgentY", Some("agenty-3"));
531        assert!(
532            !none.contains_key("AGENTMUX_AGENT_ID"),
533            "must not invent one either"
534        );
535    }
536
537    /// The server's knowledge wins over a `cmd:env` snapshot: a rename after
538    /// launch moves `block.meta["agentName"]` but not the frozen env copy,
539    /// and the persisted slug is the collision-resolved one, not whatever
540    /// the frontend computed before the row existed.
541    #[test]
542    fn server_values_override_stale_cmd_env_snapshots() {
543        let mut e = env(&[
544            ("AGENTMUX_AGENT_DISPLAY", "AgentY"),
545            ("AGENTMUX_AGENT_SLUG", "agenty"),
546        ]);
547        split_agent_identity_env(&mut e, "AgentY (renamed)", Some("agenty-3"));
548        assert_eq!(e["AGENTMUX_AGENT_DISPLAY"], "AgentY (renamed)");
549        assert_eq!(e["AGENTMUX_AGENT_SLUG"], "agenty-3");
550    }
551
552    /// A quick-launch pane (`launchAgent`, provider key as `agentId`) has no
553    /// `db_agents` row and therefore no slug. The display name is still set;
554    /// the slug is NOT derived from it — that derivation is the lossy step
555    /// spec §1.1 identifies as the defect. A `cmd:env` slug survives as the
556    /// fallback.
557    #[test]
558    fn no_persisted_row_sets_display_only_and_keeps_any_cmd_env_slug() {
559        let mut bare = env(&[]);
560        split_agent_identity_env(&mut bare, "AgentY", None);
561        assert_eq!(bare["AGENTMUX_AGENT_DISPLAY"], "AgentY");
562        assert!(!bare.contains_key("AGENTMUX_AGENT_SLUG"));
563
564        let mut with_fallback = env(&[("AGENTMUX_AGENT_SLUG", "agenty-3")]);
565        split_agent_identity_env(&mut with_fallback, "AgentY", None);
566        assert_eq!(with_fallback["AGENTMUX_AGENT_SLUG"], "agenty-3");
567    }
568
569    /// An empty or whitespace display name (a pane with no `agentName` meta
570    /// yet) sets nothing and does not clobber a `cmd:env` value with "".
571    #[test]
572    fn empty_display_name_sets_nothing_and_preserves_cmd_env() {
573        let mut bare = env(&[]);
574        split_agent_identity_env(&mut bare, "   ", None);
575        assert!(!bare.contains_key("AGENTMUX_AGENT_DISPLAY"));
576
577        let mut with_fallback = env(&[("AGENTMUX_AGENT_DISPLAY", "AgentY")]);
578        split_agent_identity_env(&mut with_fallback, "", Some("  "));
579        assert_eq!(with_fallback["AGENTMUX_AGENT_DISPLAY"], "AgentY");
580        assert!(!with_fallback.contains_key("AGENTMUX_AGENT_SLUG"));
581    }
582
583    /// The whole point: after the split, the two colliding agents are
584    /// distinguishable by BOTH variables, whereas anything derived from the
585    /// display name alone is not.
586    #[test]
587    fn colliding_names_stay_separable_after_the_split() {
588        let mut a = env(&[("AGENTMUX_AGENT_ID", "AgentY")]);
589        let mut b = env(&[("AGENTMUX_AGENT_ID", "AGENTY")]);
590        split_agent_identity_env(&mut a, "AgentY", Some("agenty-3"));
591        split_agent_identity_env(&mut b, "AGENTY", Some("agenty-2"));
592
593        assert_ne!(a["AGENTMUX_AGENT_SLUG"], b["AGENTMUX_AGENT_SLUG"]);
594        assert_ne!(a["AGENTMUX_AGENT_DISPLAY"], b["AGENTMUX_AGENT_DISPLAY"]);
595        // …and the reason the slug has to come from the store rather than
596        // from the name: lowercased, the names are the same string.
597        assert_eq!(
598            a["AGENTMUX_AGENT_DISPLAY"].to_lowercase(),
599            b["AGENTMUX_AGENT_DISPLAY"].to_lowercase(),
600        );
601    }
602
603    // ---- identity M1: carry_agent_uid_env --------------------------------
604
605    use super::{carry_agent_uid_env, PersistedAgentIdentity};
606
607    fn identity(uid: &str, token: Option<&str>) -> PersistedAgentIdentity {
608        PersistedAgentIdentity { uid: uid.to_string(), slug: Some("agenty-3".to_string()), token: token.map(str::to_string), former: Default::default() }
609    }
610
611    /// Positive case first: a known row carries both values into the env.
612    #[test]
613    fn carry_sets_uid_and_token_from_the_row() {
614        let mut e = env(&[("AGENTMUX_AGENT_ID", "AgentY")]);
615        carry_agent_uid_env(&mut e, Some(&identity("4f3c-a91", Some("tok-a"))));
616        assert_eq!(e["AGENTMUX_AGENT_UID"], "4f3c-a91");
617        assert_eq!(e["AGENTMUX_AGENT_TOKEN"], "tok-a");
618        assert_eq!(e["AGENTMUX_AGENT_ID"], "AgentY", "§9.4: untouched");
619    }
620
621    /// Reserved-variable rule: a persisted `cmd:env` carrying ANOTHER
622    /// agent's UID and token (pane reuse, copied block) is overwritten, not
623    /// respected. For the token this is the difference between an agent
624    /// holding its own credential and holding someone else's.
625    #[test]
626    fn carry_overwrites_stale_cmd_env_values_unconditionally() {
627        let mut e = env(&[
628            ("AGENTMUX_AGENT_UID", "9b2e-7d4"),
629            ("AGENTMUX_AGENT_TOKEN", "tok-of-the-other-agent"),
630        ]);
631        carry_agent_uid_env(&mut e, Some(&identity("4f3c-a91", Some("tok-a"))));
632        assert_eq!(e["AGENTMUX_AGENT_UID"], "4f3c-a91");
633        assert_eq!(e["AGENTMUX_AGENT_TOKEN"], "tok-a");
634    }
635
636    /// No row (quick-launch pane, lookup failure): both are REMOVED. Leaving
637    /// a stale token in place would be worse than having none, and the
638    /// server has nothing truthful to put there.
639    #[test]
640    fn carry_removes_both_when_the_server_knows_no_identity() {
641        let mut e = env(&[
642            ("AGENTMUX_AGENT_ID", "AgentY"),
643            ("AGENTMUX_AGENT_UID", "stale"),
644            ("AGENTMUX_AGENT_TOKEN", "stale"),
645        ]);
646        carry_agent_uid_env(&mut e, None);
647        assert!(!e.contains_key("AGENTMUX_AGENT_UID"));
648        assert!(!e.contains_key("AGENTMUX_AGENT_TOKEN"));
649        assert_eq!(e["AGENTMUX_AGENT_ID"], "AgentY");
650    }
651
652    /// A row whose token could not be minted still carries its UID, and a
653    /// stale token is removed rather than kept — never a half-truth.
654    #[test]
655    fn carry_with_uid_but_no_token_sets_uid_and_removes_token() {
656        let mut e = env(&[("AGENTMUX_AGENT_TOKEN", "stale")]);
657        carry_agent_uid_env(&mut e, Some(&identity("4f3c-a91", None)));
658        assert_eq!(e["AGENTMUX_AGENT_UID"], "4f3c-a91");
659        assert!(!e.contains_key("AGENTMUX_AGENT_TOKEN"));
660    }
661
662    // ---- identity M0/M1: persisted_agent_identity against a real store ---
663
664    use super::persisted_agent_identity;
665    use crate::backend::storage::agents::AgentDefinition;
666    use crate::backend::storage::store::Store;
667
668    fn agent_def(id: &str, name: &str) -> AgentDefinition {
669        AgentDefinition {
670            seat: None,
671            conversation_visibility:
672                crate::backend::storage::agents::default_conversation_visibility(),
673            id: id.to_string(),
674            // Empty on purpose: `agent_def_insert` derives it from `name`
675            // and collision-resolves, exactly as the launch flow does.
676            slug: String::new(),
677            name: name.to_string(),
678            icon: "✦".to_string(),
679            provider: "claude".to_string(),
680            description: String::new(),
681            working_directory: String::new(),
682            shell: String::new(),
683            provider_flags: String::new(),
684            auto_start: 0,
685            restart_on_crash: 0,
686            idle_timeout_minutes: 0,
687            created_at: 0,
688            agent_type: "host".to_string(),
689            environment: String::new(),
690            agent_bus_id: String::new(),
691            is_seeded: 0,
692            accounts: String::new(),
693            parent_id: String::new(),
694            branch_label: String::new(),
695            updated_at: 0,
696            user_hidden: 0,
697            container_image: String::new(),
698            container_volumes: "[]".to_string(),
699            container_name: String::new(),
700            use_ambient_login: 0,
701            model_vendor_base_url: String::new(),
702            memory_id: String::new(),
703        }
704    }
705
706    fn block_with_agent_id(store: &Store, block_id: &str, agent_id: &str) {
707        let mut block = crate::backend::obj::Block {
708            oid: block_id.to_string(),
709            parentoref: String::new(),
710            version: 0,
711            runtimeopts: None,
712            stickers: None,
713            meta: {
714                let mut m = crate::backend::obj::MetaMapType::new();
715                m.insert("view".to_string(), serde_json::json!("agent"));
716                m.insert("agentId".to_string(), serde_json::json!(agent_id));
717                m
718            },
719            subblockids: None,
720        };
721        store.insert(&mut block).unwrap();
722    }
723
724    /// The §1.1 scenario end to end: two agents whose names collide under
725    /// `derive_slug` get `agenty` and `agenty-2` from `agent_def_insert`, and
726    /// the lookup returns each block's OWN row — its UID, its suffixed slug
727    /// (which no derivation from its name could produce), and a token that
728    /// is that row's and nobody else's.
729    #[test]
730    fn persisted_identity_returns_the_rows_uid_slug_and_own_token() {
731        let store = Store::open_in_memory().unwrap();
732        let mut first = agent_def("uid-first", "AgentY");
733        store.agent_def_insert(&mut first).unwrap();
734        let mut second = agent_def("uid-second", "AGENTY");
735        store.agent_def_insert(&mut second).unwrap();
736        assert_eq!(
737            first.slug, "agenty",
738            "fixture: first insert keeps the bare slug"
739        );
740        assert_eq!(
741            second.slug, "agenty-2",
742            "fixture: second insert is suffixed"
743        );
744
745        block_with_agent_id(&store, "block-first", "uid-first");
746        block_with_agent_id(&store, "block-second", "uid-second");
747
748        let a = persisted_agent_identity(&store, "block-first").expect("first resolves");
749        let b = persisted_agent_identity(&store, "block-second").expect("second resolves");
750        assert_eq!(a.uid, "uid-first");
751        assert_eq!(b.uid, "uid-second");
752        assert_eq!(a.slug.as_deref(), Some("agenty"));
753        assert_eq!(b.slug.as_deref(), Some("agenty-2"));
754
755        // The token is the persisted one for that UID, minted on this first
756        // spawn, and distinct between the two colliding agents.
757        let tok_a = a.token.clone().expect("token minted");
758        let tok_b = b.token.clone().expect("token minted");
759        assert_ne!(tok_a, tok_b);
760        assert_eq!(
761            store.agent_token_load("uid-first").unwrap().as_deref(),
762            Some(tok_a.as_str())
763        );
764        assert_eq!(
765            store.agent_token_load("uid-second").unwrap().as_deref(),
766            Some(tok_b.as_str())
767        );
768
769        // A second spawn of the same agent carries the SAME token — long-lived
770        // for the agent's lifetime (spec §6.3), not re-minted per spawn.
771        let a_again = persisted_agent_identity(&store, "block-first").unwrap();
772        assert_eq!(a_again.token.as_deref(), Some(tok_a.as_str()));
773    }
774
775    /// Identity M4b-2: the helper App Server and ACP use carries the
776    /// block's row UID and token into their own env, overwriting a stale
777    /// token, and strips both for a block with no row — outside a runtime
778    /// and, through `block_in_place`, on a multi-thread runtime worker.
779    #[test]
780    fn carry_agent_workdir_env_is_the_launch_cwd_for_host_agents_only() {
781        let meta = |pairs: &[(&str, &str)]| -> crate::backend::obj::MetaMapType {
782            pairs.iter().map(|(k, v)| (k.to_string(), serde_json::Value::String(v.to_string()))).collect()
783        };
784        let stale = || {
785            std::collections::HashMap::from([
786                ("AGENTMUX_AGENT_WORKDIR".to_string(), "C:/stale".to_string()),
787                ("AGENTMUX_MCP_CONFIG".to_string(), "C:/stale/.mcp.json".to_string()),
788            ])
789        };
790
791        let workdir = |e: &std::collections::HashMap<String, String>| std::path::PathBuf::from(&e["AGENTMUX_AGENT_WORKDIR"]);
792        let config = |e: &std::collections::HashMap<String, String>| std::path::PathBuf::from(&e["AGENTMUX_MCP_CONFIG"]);
793        let ws = std::env::temp_dir().join("clamk-0612a");
794        let ws_str = ws.to_string_lossy().into_owned();
795
796        for mode in ["host", "standalone"] {
797            let mut e = stale();
798            super::carry_agent_workdir_env(&mut e, &meta(&[("agentMode", mode), ("cmd:cwd", &ws_str)]));
799            assert_eq!(workdir(&e), ws, "{mode}");
800            assert_eq!(config(&e), crate::backend::mcp_config_file::config_path(&ws_str), "{mode}");
801        }
802        // No agentMode is a host agent, srv's default.
803        let mut e = stale();
804        super::carry_agent_workdir_env(&mut e, &meta(&[("cmd:cwd", &ws_str)]));
805        assert_eq!(workdir(&e), ws);
806        assert_eq!(config(&e), crate::backend::mcp_config_file::config_path(&ws_str));
807
808        // Exported as the absolute path the process starts in: a relative
809        // cwd resolves against srv's own cwd, `~` against the home dir.
810        let mut e = stale();
811        super::carry_agent_workdir_env(&mut e, &meta(&[("cmd:cwd", "projects/foo")]));
812        assert_eq!(workdir(&e), std::env::current_dir().unwrap().join("projects/foo"));
813        assert_eq!(
814            config(&e),
815            crate::backend::mcp_config_file::config_path(&std::env::current_dir().unwrap().join("projects/foo").to_string_lossy()),
816            "a relative cwd gives the same config path on both sides"
817        );
818        if let Some(home) = dirs::home_dir() {
819            let mut e = stale();
820            super::carry_agent_workdir_env(&mut e, &meta(&[("cmd:cwd", "~/.agentmux/agents/x-0930a")]));
821            assert_eq!(workdir(&e), home.join(".agentmux/agents/x-0930a"));
822            assert_eq!(config(&e), home.join(".agentmux/agents/x-0930a/.mcp.json"));
823        }
824
825        let mut e = stale();
826        super::carry_agent_workdir_env(&mut e, &meta(&[("agentMode", "container"), ("cmd:cwd", &ws_str)]));
827        assert!(!e.contains_key("AGENTMUX_AGENT_WORKDIR"), "container");
828        assert!(!e.contains_key("AGENTMUX_MCP_CONFIG"), "a container doctor uses the mounted path");
829        let mut e = stale();
830        super::carry_agent_workdir_env(&mut e, &meta(&[("agentMode", "host"), ("cmd:cwd", "  ")]));
831        assert!(!e.contains_key("AGENTMUX_AGENT_WORKDIR"), "no cwd");
832        assert!(!e.contains_key("AGENTMUX_MCP_CONFIG"), "no cwd, no config");
833    }
834
835    #[test]
836    fn carry_block_identity_env_carries_or_strips() {
837        let store = Store::open_in_memory().unwrap();
838        let mut def = agent_def("uid-carry", "Carrier");
839        store.agent_def_insert(&mut def).unwrap();
840        block_with_agent_id(&store, "block-carry", "uid-carry");
841        block_with_agent_id(&store, "block-carry-none", "claude");
842
843        let mut env = std::collections::HashMap::from([(
844            "AGENTMUX_AGENT_TOKEN".to_string(),
845            "stale-token".to_string(),
846        )]);
847        super::carry_block_identity_env(&store, "block-carry", &mut env);
848        assert_eq!(
849            env.get("AGENTMUX_AGENT_UID").map(String::as_str),
850            Some("uid-carry")
851        );
852        assert_eq!(
853            env.get("AGENTMUX_AGENT_TOKEN"),
854            store.agent_token_load("uid-carry").unwrap().as_ref()
855        );
856
857        let mut none = env.clone();
858        super::carry_block_identity_env(&store, "block-carry-none", &mut none);
859        assert!(
860            !none.contains_key("AGENTMUX_AGENT_UID") && !none.contains_key("AGENTMUX_AGENT_TOKEN")
861        );
862
863        let rt = tokio::runtime::Builder::new_multi_thread()
864            .worker_threads(1)
865            .build()
866            .unwrap();
867        let store = std::sync::Arc::new(store);
868        let on_worker = rt.block_on({
869            let store = store.clone();
870            async move {
871                tokio::spawn(async move {
872                    let mut env = std::collections::HashMap::new();
873                    super::carry_block_identity_env(&store, "block-carry", &mut env);
874                    env
875                })
876                .await
877                .unwrap()
878            }
879        });
880        assert_eq!(
881            on_worker.get("AGENTMUX_AGENT_UID").map(String::as_str),
882            Some("uid-carry")
883        );
884    }
885
886    /// A quick-launch pane carries a provider key as `agentId` and has no
887    /// `db_agents` row; a block that does not exist has nothing either.
888    /// Both are "no identity", never an error and never a derived value —
889    /// and, load-bearing for the token: no row means no token is minted.
890    #[test]
891    fn persisted_identity_is_none_for_quick_launch_panes_and_missing_blocks() {
892        let store = Store::open_in_memory().unwrap();
893        block_with_agent_id(&store, "block-quick", "claude");
894        assert_eq!(persisted_agent_identity(&store, "block-quick"), None);
895        assert_eq!(persisted_agent_identity(&store, "block-missing"), None);
896        assert_eq!(
897            store.agent_token_load("claude").unwrap(),
898            None,
899            "no token minted for a provider key"
900        );
901    }
902
903    /// Codex P1 on #3591: the builder re-checks deletion at its last read —
904    /// an agent deleted after the gate's lookup (no row resolves now, and the
905    /// shared registry holds only a retired record) is reported, so the spawn
906    /// is refused; a live agent is not.
907    #[test]
908    fn the_builder_recheck_reports_an_agent_deleted_after_the_gate() {
909        let tmp = tempfile::tempdir().unwrap();
910        let store = Store::open_in_memory().unwrap();
911        let defs = crate::registry::DefinitionStore::open(tmp.path().join("definitions")).unwrap();
912        store.set_def_registry(std::sync::Arc::new(defs));
913        let mut def = agent_def("uid-late-del", "LateDel");
914        store.agent_def_insert(&mut def).unwrap();
915        block_with_agent_id(&store, "block-late-del", "uid-late-del");
916        let live = persisted_agent_identity(&store, "block-late-del");
917        assert!(live.is_some());
918        assert_eq!(
919            super::deleted_agent_of_rowless_block(&store, "block-late-del", live.as_ref()),
920            None
921        );
922
923        assert!(store.agent_def_delete("uid-late-del").unwrap());
924        let after = persisted_agent_identity(&store, "block-late-del");
925        assert_eq!(after, None);
926        assert_eq!(
927            super::deleted_agent_of_rowless_block(&store, "block-late-del", after.as_ref())
928                .as_deref(),
929            Some("uid-late-del")
930        );
931    }
932
933    /// Spec §6.3: revoked on deletion. Deleting the agent through either
934    /// deletion entry point takes its token with it, so a later spawn on a
935    /// reused block cannot resurrect the old credential.
936    #[test]
937    fn deleting_the_agent_revokes_its_token() {
938        let store = Store::open_in_memory().unwrap();
939        let mut def = agent_def("uid-del", "Deleted");
940        store.agent_def_insert(&mut def).unwrap();
941        block_with_agent_id(&store, "block-del", "uid-del");
942        let minted = persisted_agent_identity(&store, "block-del").unwrap().token;
943        assert!(minted.is_some());
944
945        assert!(store.agent_def_delete("uid-del").unwrap());
946        assert_eq!(store.agent_token_load("uid-del").unwrap(), None);
947        assert_eq!(persisted_agent_identity(&store, "block-del"), None);
948
949        // …and via the launch-side entry point too.
950        let mut def2 = agent_def("uid-del2", "Deleted2");
951        store.agent_def_insert(&mut def2).unwrap();
952        block_with_agent_id(&store, "block-del2", "uid-del2");
953        assert!(persisted_agent_identity(&store, "block-del2")
954            .unwrap()
955            .token
956            .is_some());
957        assert!(store.instance_delete("uid-del2").unwrap());
958        assert_eq!(store.agent_token_load("uid-del2").unwrap(), None);
959    }
960}
961
962#[cfg(test)]
963#[path = "input_handler_tests.rs"]
964mod handler_tests;