Skip to main content

agentmux_srv/server/agent_handlers/
mod.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4// # Fork, spawn and worker
5// A fork (the user's Quick Fork or Fork) is an exact copy of its agent,
6// conversation and pane history included (`fork_history.rs`). The `Agents`
7// `spawn` action makes a worker: the leader's definition plus a brief, no
8// conversation history. A process spawn starts any agent's CLI. Definitions:
9// docs/architecture/ARCHITECTURE_FORK_SPAWN_AND_WORKER_2026_10_17.md.
10mod account_label;
11mod api_retry;
12mod core;
13mod skills;
14mod history;
15pub(crate) mod rename;
16mod template;
17mod template_create;
18mod template_switch;
19mod template_image;
20mod fork_history;
21pub(crate) mod fork_slugs;
22// Builds a fork's and a worker's definition ("Fork, spawn and worker" above).
23pub(crate) use template::{copy_definition, name_available};
24pub(crate) use template_create::create_from_template;
25// The image a created container agent runs in (`Agents create` checks the same choices as the picker).
26pub(crate) use template_image::chosen_container_image;
27// Deletes an agent definition and what belongs to it (the `deleteagent` RPC and `Agents delete`).
28pub(crate) use core::delete_agent_definition;
29mod build_slot;
30mod identity;
31#[cfg(test)]
32mod identity_register_tests;
33#[cfg(test)]
34mod template_create_tests;
35#[cfg(test)]
36mod template_copy_tests;
37mod identity_delete;
38pub(crate) use identity_delete::delete_identity_account;
39mod endpoint;
40mod instance;
41mod session;
42pub(crate) mod seat;
43#[cfg(test)]
44mod transcript_write_tests;
45#[cfg(test)]
46mod transcript_key_tests;
47pub(crate) mod bundle;
48pub(crate) mod container_turn;
49mod composer_origin;
50pub(crate) use composer_origin::window_only;
51pub(crate) mod input;
52pub(crate) mod turn_steps;
53pub(crate) use crate::backend::spawn_env::identity as identity_env;
54mod side_question;
55
56use std::sync::Arc;
57
58
59use crate::backend::agent_session::archive;
60use crate::backend::rpc::engine::WshRpcEngine;
61
62use super::AppState;
63
64pub use input::register_agent_input_handlers;
65// `/btw` slash command backend — registered alongside
66// `register_agent_input_handlers` in `server/websocket.rs` (both need the
67// same `AgentTurnDeps`-shaped wiring), not folded into
68// `register_agent_handlers` below.
69pub use side_question::register as register_side_question_handlers;
70// Re-exported for `bootstrap::install_agent_turn_delivery`, which starts an
71// agent turn from the reactive handler's message sender rather than over RPC.
72pub use input::{run_agent_turn, run_agent_turn_joining, AgentTurnDeps, TurnRegistration};
73
74pub fn register_agent_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
75    core::register(engine, state);
76    endpoint::register(engine, state);
77    skills::register(engine, state);
78    history::register(engine, state);
79    template::register(engine, state);
80    fork_history::register(engine, state);
81    fork_slugs::register(engine, state);
82    api_retry::register(engine);
83    identity::register(engine, state);
84    build_slot::register(engine, state);
85    instance::register(engine, state);
86    session::register(engine, state);
87    seat::register(engine, state);
88    crate::sagas::sensitive_window::register(engine, state);
89    crate::sagas::agent_notice::register(engine, state);
90    crate::sagas::pane_confirm::register(engine);
91    crate::server::browser_sessions::register(engine, state);
92    crate::sagas::deeplink_open::register(engine);
93    crate::sagas::capture_mask::register(engine);
94    crate::sagas::sensitive_runners::register_all();
95    crate::server::pane_commands::register(engine, state);
96    bundle::register(engine, state);
97}
98
99/// Purge a deleted agent's rows from the IDENTITY store — the second
100/// physical database, reachable only from this layer.
101///
102/// `Store::agent_def_delete` / `instance_delete` purge the dependents they
103/// can see, but they run against the object store, and
104/// `db_agent_identity_links`, `db_agent_credentials` and both native-memory
105/// tables exist in BOTH schemas with the identity store holding the live
106/// rows (`SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md` —
107/// `listrecentsessions` reads links from
108/// `identity_store.agent_identity_list_all()`, not the object store's
109/// same-named table). Without this the delete leaves an agent's real
110/// credentials and account links on disk, which the Delete confirm dialog
111/// explicitly promises it removes.
112///
113/// Called by BOTH delete RPCs (`deleteagent` and `deleteagentinstance`):
114/// they are one deletion under two names, and a fix applied to only one of
115/// them is the same bug reachable by the other route (ReAgent P1 on
116/// PR #3262). Best-effort — the agent row is already gone by the time this
117/// runs, so a failure here is leftover rows to log, not a failed delete.
118///
119/// MuxBus keeps the cached cloud credentials in `id_store`, a third database
120/// in a normal boot, so the agent's rows there go too, in every channel.
121pub(crate) fn purge_identity_store_rows(
122    identity_store: &crate::backend::storage::store::Store,
123    id_store: &crate::backend::storage::store::Store,
124    agent_id: &str,
125    caller: &'static str,
126) {
127    if let Err(e) = id_store.agent_credentials_purge_agent(agent_id) {
128        tracing::warn!(agent_id, caller, error = %e, "cloud credentials left behind for deleted agent");
129    }
130    // The logins the person shared with it, and the "Always" it held for them (spec A9).
131    if let Err(e) = crate::backend::vault::shares::forget_agent(identity_store, agent_id) {
132        tracing::warn!(agent_id, caller, error = %e, "logins shared with a deleted agent left shared");
133    }
134    match identity_store.agent_dependents_purge(agent_id) {
135        Ok(0) => {}
136        Ok(removed) => tracing::debug!(
137            agent_id, caller, removed,
138            "purged identity-store rows for deleted agent"
139        ),
140        Err(e) => tracing::warn!(
141            agent_id, caller, error = %e,
142            "identity-store rows left behind for deleted agent"
143        ),
144    }
145}
146
147/// Read the per-block `output.state.json` snapshot from filestore and
148/// extract a `(preview, node_count)` pair for the AgentPicker's
149/// "Recent sessions" list.
150///
151/// The snapshot shape is owned by the frontend (see
152/// `frontend/app/view/agent/agent-view.tsx::writeSnapshotNow`):
153/// `{ schemaVersion, savedAt, highWaterMark, historyOffset, nodes: [DocumentNode...] }`.
154/// We only touch two fields:
155/// - `nodes.length` → `node_count`.
156/// - The first node with `type === "user_message"`, `message` field →
157///   `preview` (trimmed, newlines collapsed, max 240 chars).
158///
159/// On any error (snapshot missing, malformed JSON, no user message),
160/// returns `("", 0)`. Callers treat that the same as "no preview".
161fn read_session_preview(
162    filestore: &crate::backend::storage::filestore::FileStore,
163    block_id: &str,
164) -> (String, usize) {
165    let bytes = match filestore.read_file(block_id, "output.state.json") {
166        Ok(Some(b)) => b,
167        _ => return (String::new(), 0),
168    };
169    // Cap the parse budget — a misbehaving / corrupted snapshot
170    // shouldn't be able to stall this handler. 4MiB is well above the
171    // typical conversation snapshot (Maks's was ~750KiB for 169 nodes)
172    // but bounded enough to fail fast on garbage.
173    if bytes.len() > archive::MAX_PREVIEW_SNAPSHOT_BYTES {
174        tracing::warn!(
175            block_id = %block_id,
176            size = bytes.len(),
177            "listrecentsessions: snapshot too large; skipping preview"
178        );
179        return (String::new(), 0);
180    }
181    archive::snapshot_preview(&bytes)
182}
183
184#[cfg(test)]
185mod recent_sessions_tests {
186    use super::*;
187    use archive::collapse_preview;
188    use crate::backend::rpc_types::{ListRecentSessionsResult, COMMAND_LIST_RECENT_SESSIONS};
189    use crate::backend::storage::filestore::FileStore;
190
191    fn fresh_filestore() -> std::sync::Arc<FileStore> {
192        std::sync::Arc::new(FileStore::open_in_memory().unwrap())
193    }
194
195    fn write_snapshot(fs: &FileStore, block_id: &str, body: &str) {
196        // make_file then write_file mirrors the production
197        // BlockfileWriteState handler path.
198        let meta: crate::backend::storage::filestore::FileMeta =
199            std::collections::HashMap::new();
200        let opts = crate::backend::storage::filestore::FileOpts::default();
201        fs.make_file(block_id, "output.state.json", meta, opts)
202            .expect("make_file");
203        fs.write_file(block_id, "output.state.json", body.as_bytes())
204            .expect("write_file");
205    }
206
207    #[test]
208    fn collapse_preview_strips_newlines_and_caps_length() {
209        let s = "hello\n\nworld\n  next   line";
210        assert_eq!(collapse_preview(s), "hello world next line");
211        let long: String = "a".repeat(500);
212        let out = collapse_preview(&long);
213        // 240 chars + ellipsis.
214        assert!(out.ends_with('\u{2026}'));
215        assert!(out.chars().count() <= 241);
216    }
217
218    #[test]
219    fn read_session_preview_missing_returns_zero() {
220        let fs = fresh_filestore();
221        let (preview, count) = read_session_preview(&fs, "no-such-block");
222        assert_eq!(preview, "");
223        assert_eq!(count, 0);
224    }
225
226    #[test]
227    fn read_session_preview_extracts_first_user_message_skipping_context() {
228        let fs = fresh_filestore();
229        // Two user messages: first is the boilerplate Session Context;
230        // second is the user's real prompt. Preview should be the real one.
231        let snapshot = serde_json::json!({
232            "schemaVersion": 1,
233            "savedAt": "2026-05-23T08:00:00Z",
234            "highWaterMark": 169,
235            "historyOffset": 0,
236            "nodes": [
237                {
238                    "type": "user_message",
239                    "id": "u0",
240                    "timestamp": 0,
241                    "collapsed": false,
242                    "summary": "👤 User Message",
243                    "message": "# Session Context\nIdentity: Claude\n## Description\nStartup boilerplate"
244                },
245                { "type": "markdown", "id": "m0", "content": "ack" },
246                {
247                    "type": "user_message",
248                    "id": "u1",
249                    "timestamp": 100,
250                    "collapsed": false,
251                    "summary": "👤 User Message",
252                    "message": "check the agentmuxai/agentmux history, get the latest code"
253                }
254            ]
255        });
256        write_snapshot(&fs, "blk-1", &snapshot.to_string());
257        let (preview, count) = read_session_preview(&fs, "blk-1");
258        assert_eq!(count, 3);
259        assert!(preview.starts_with("check the agentmuxai/agentmux"));
260    }
261
262    #[test]
263    fn read_session_preview_falls_back_to_session_context_when_only_one() {
264        let fs = fresh_filestore();
265        let snapshot = serde_json::json!({
266            "schemaVersion": 1,
267            "nodes": [
268                {
269                    "type": "user_message",
270                    "id": "u0",
271                    "message": "# Session Context\nIdentity: Claude\nStartup boilerplate"
272                }
273            ]
274        });
275        write_snapshot(&fs, "blk-2", &snapshot.to_string());
276        let (preview, count) = read_session_preview(&fs, "blk-2");
277        assert_eq!(count, 1);
278        // Newlines collapsed; starts with the boilerplate marker.
279        assert!(preview.starts_with("# Session Context"));
280    }
281
282    #[test]
283    fn read_session_preview_handles_malformed_json() {
284        let fs = fresh_filestore();
285        write_snapshot(&fs, "blk-3", "not valid json {");
286        let (preview, count) = read_session_preview(&fs, "blk-3");
287        assert_eq!(preview, "");
288        assert_eq!(count, 0);
289    }
290
291    #[test]
292    fn read_session_preview_handles_no_user_messages() {
293        let fs = fresh_filestore();
294        let snapshot = serde_json::json!({
295            "schemaVersion": 1,
296            "nodes": [
297                { "type": "markdown", "id": "m0", "content": "system note" }
298            ]
299        });
300        write_snapshot(&fs, "blk-4", &snapshot.to_string());
301        let (preview, count) = read_session_preview(&fs, "blk-4");
302        assert_eq!(preview, "");
303        assert_eq!(count, 1);
304    }
305
306    // ── Integration test: full listrecentsessions handler ────────────
307    //
308    // Spins up the same engine + state shape as the production
309    // websocket path so the handler runs end-to-end against an
310    // in-memory mstore + filestore. Asserts the row shape, the
311    // identity filter, the snapshot-first sort, the preview extraction,
312    // and the cross-version "no snapshot" fallback. This is the
313    // backend correctness gate for the AgentPicker's Recent Sessions
314    // surface (cascade follow-up 2026-05-23).
315    use crate::backend::storage::store::{
316        AgentDefinition, AgentInstance, IdentityAccount, Bundle, SecretRef, Store,
317    };
318    use crate::backend::rpc::engine::WshRpcEngine;
319    use crate::server::AppState;
320    use std::sync::Arc;
321
322    /// Drive a single RPC round-trip against the in-memory engine,
323    /// asserting success + deserializing the JSON payload into `T`.
324    async fn call_rpc<T: serde::de::DeserializeOwned>(
325        engine: &Arc<WshRpcEngine>,
326        rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::backend::rpc_types::RpcMessage>,
327        command: &str,
328        data: serde_json::Value,
329    ) -> T {
330        let req_id = format!("test-{}", uuid::Uuid::new_v4());
331        let msg = crate::backend::rpc_types::RpcMessage {
332            command: command.to_string(),
333            reqid: req_id.clone(),
334            data: Some(data),
335            ..Default::default()
336        };
337        engine.handle_message(msg);
338        let resp = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
339            .await
340            .expect("handler timed out")
341            .expect("output channel closed");
342        assert_eq!(resp.resid, req_id, "unexpected response id");
343        assert!(resp.error.is_empty(), "handler returned error: {}", resp.error);
344        let payload = resp.data.unwrap_or(serde_json::Value::Null);
345        serde_json::from_value(payload).expect("response deserialize")
346    }
347
348    fn build_state_with_seed() -> (
349        AppState,
350        Arc<WshRpcEngine>,
351        tokio::sync::mpsc::UnboundedReceiver<crate::backend::rpc_types::RpcMessage>,
352    ) {
353        let mstore = Arc::new(Store::open_in_memory().unwrap());
354        let filestore = Arc::new(FileStore::open_in_memory().unwrap());
355        let event_bus = Arc::new(crate::backend::eventbus::EventBus::new());
356        let broker = Arc::new(crate::backend::mps::Broker::new());
357        let reactive_handler = crate::backend::reactive::get_global_handler();
358        let poller = Arc::new(crate::backend::reactive::Poller::new(
359            crate::backend::reactive::PollerConfig {
360                muxbus_url: None,
361                muxbus_token: None,
362                poll_interval_secs: 30,
363            },
364            reactive_handler,
365        ));
366        crate::backend::wcore::ensure_initial_data(&mstore).unwrap();
367        let config_watcher = Arc::new(crate::backend::wconfig::ConfigState::new());
368        let process_tracker = Arc::new(
369            crate::backend::process_tracker::registry::AgentProcessRegistry::new(Some(broker.clone())),
370        );
371        let process_broker = Arc::new(crate::broker::ProcessBroker::new(Some(broker.clone())));
372        let fs_watch_pool = crate::backend::fs_watch::FsWatchPool::new();
373        let state = AppState {
374            auth_key: "test".to_string(),
375            lan_key: "test-lan".to_string(),
376            boot_id: std::sync::Arc::from("test-boot"),
377            version: "test".to_string(),
378            hostname: "test-host".to_string(),
379            app_path: String::new(),
380            mstore: mstore.clone(),
381            shared_store: None,
382            move_staging: None,
383            id_store: mstore.clone(),
384            identity_store: mstore.clone(),
385            work_store: mstore.clone(),
386            cron_store: None,
387            filestore: filestore.clone(),
388            global_transcript_store: None,
389            event_bus: event_bus.clone(),
390            broker: broker.clone(),
391            reactive_handler,
392            poller,
393            config_watcher,
394            messagebus: Arc::new(crate::backend::messagebus::MessageBus::new()),
395            http_client: reqwest::Client::new(),
396            host_ipc: Arc::new(tokio::sync::Mutex::new(None)),
397            host_reg_secret: None,
398            local_web_url: String::new(),
399            subagent_watcher: Arc::new(crate::backend::subagent_watcher::SubagentWatcher::new(event_bus.clone(), mstore.clone(), mstore.clone(), mstore.clone())),
400            history_service: Arc::new(crate::backend::history::HistoryService::new()),
401            lan_discovery: Arc::new(crate::backend::lan::discovery::LanDiscoveryController::new(
402                "test-instance".to_string(),
403                "test-host".to_string(),
404                "0.28.20".to_string(),
405                0,
406                event_bus.clone(),
407                String::new(),
408            )),
409            lan_listeners: Arc::new(crate::backend::lan::listeners::LanListenerSupervisor::new(0, 0)),
410            fleet_feed: Arc::new(crate::backend::fleet_feed::FleetFeed::new(
411                "test-host".to_string(),
412                "test-channel".to_string(),
413                "0.0.0-test".to_string(),
414            )),
415            viewer: crate::backend::viewer::ViewerService::new(None, &broker),
416            lsp_supervisor: Arc::new(crate::backend::lsp::LspSupervisor::new(event_bus.clone())),
417            process_tracker,
418            process_broker,
419            dock_snapshots: Arc::new(crate::backend::dock_snapshot::DockSnapshotCache::new()),
420            narrated_events: Arc::new(crate::backend::narrated_events::NarratedEvents::new()),
421            srv_state: Arc::new(tokio::sync::Mutex::new(crate::state::State::default())),
422            srv_events_tx: tokio::sync::broadcast::channel::<agentmux_common::ipc::Event>(64).0,
423            saga_id_alloc: Arc::new(std::sync::atomic::AtomicU64::new(0)),
424            saga_log: Arc::new(crate::sagas::log::SagaLog::open_in_memory().unwrap()),
425            auth_session_manager: Arc::new(crate::identity::auth_session::AuthSessionManager::new()),
426            install_sessions: crate::server::install_handlers::InstallSessionRegistry::new(),
427            container_manager: Arc::new(crate::backend::container::ContainerRuntimeHandle::disabled()),
428            dev_proxy: crate::backend::dev_proxy::DevProxyRegistry::new(),
429            shell_sessions: crate::backend::shell_node::ShellSessionRegistry::new(),
430            cron_scheduler: crate::backend::cron::CronScheduler::new(
431                None,
432                reqwest::Client::new(),
433                String::new(),
434                "test".to_string(),
435                broker.clone(),
436            ),
437            editor_file_watcher: crate::backend::editor_file_watcher::EditorFileWatcher::new(
438                fs_watch_pool.clone(),
439                broker.clone(),
440            ),
441            media_file_watcher: crate::backend::media_file_watcher::MediaFileWatcher::new(
442                fs_watch_pool.clone(),
443                broker.clone(),
444            ),
445            files_watcher: crate::backend::files_watcher::FilesWatcher::new(
446                fs_watch_pool.clone(),
447                broker.clone(),
448            ),
449            fs_watch_pool: fs_watch_pool.clone(),
450        };
451
452        // Seed: 1 SEEDED definition (template), 1 account + direct
453        // identity link, 1 bundle. Phase 3b note: seeded as a
454        // template so that
455        // each instance projection in `db_agents` lands on its own row
456        // (`is_template = 0`, `id = inst.id`, `parent_template_id =
457        // def.id`) rather than folding into the def-projection and
458        // clobbering its name. The handler resolves `definition_name`
459        // via `defs.iter().find(|d| d.id == inst.definition_id)`, which
460        // hits the template row and returns "Claude Code". Under the
461        // pre-Phase 3b reader, def name was always preserved because
462        // `agent_def_list` queried `db_agent_definitions` directly;
463        // db_agents fold semantics require the seed shape to avoid
464        // the collision.
465        let def = AgentDefinition {
466            slug: "claude-code".to_string(),
467            is_seeded: 1,
468            ..crate::backend::storage::agents::test_agent_def("def-claude", "Claude Code", "claude", "host", 0, "")
469        };
470        let mut def_mut = def.clone();
471        mstore.agent_def_insert(&mut def_mut).unwrap();
472        // Identity display name resolves via the direct agent<->account
473        // link (db_agent_identity_links/db_accounts) now, not a bundle —
474        // see agent_handlers::session's listrecentsessions.
475        let account = IdentityAccount {
476            id: "acct-work".to_string(),
477            name: "Work".to_string(),
478            provider: "github".to_string(),
479            kind: "pat".to_string(),
480            display_name: String::new(),
481            secret_ref: SecretRef::Env { env_var: "GITHUB_TOKEN".to_string() },
482            context: serde_json::json!({}),
483            status: "unknown".to_string(),
484            created_at: 0,
485            updated_at: 0,
486        };
487        mstore.identity_upsert(&account).unwrap();
488        // Linked to the template: `db_agent_identity_links` still has its FK
489        // on `db_agent_definitions`, so a launched agent's own row cannot
490        // hold a link until Phase 3c re-points it. The handler therefore
491        // falls back to the template's links — see its own note.
492        mstore
493            .agent_identity_link("def-claude", "acct-work", "github")
494            .unwrap();
495        let memory = Bundle {
496            id: "mem-notes".to_string(),
497            name: "Notes".to_string(),
498            description: String::new(),
499            is_blank: false,
500            is_global: false,
501            provider: String::new(),
502            model: String::new(),
503            instructions: String::new(),
504            instructions_by_provider: "{}".to_string(),
505            context_files: "[]".to_string(),
506            mcp_servers: "[]".to_string(),
507            skills: "[]".to_string(),
508            sort_order: 0,
509            created_at: 0,
510            updated_at: 0,
511            is_system: false,
512        };
513        mstore.bundle_upsert(&memory).unwrap();
514
515        // 3 instances:
516        //   - blk-recent: has snapshot, more recent activity
517        //   - blk-older:  has snapshot, older activity
518        //   - blk-none:   no snapshot at all (legacy / pre-persistence row)
519        // All three share the same identity_id value so the filter test
520        // can also exercise it without re-seeding.
521        for (id, block, started) in [
522            ("inst-recent", "blk-recent", 1_700_000_100_000_i64),
523            ("inst-older", "blk-older", 1_700_000_000_000_i64),
524            ("inst-none", "blk-none", 1_700_000_050_000_i64),
525        ] {
526            let inst = AgentInstance {
527                identity_id: "id-work".to_string(),
528                memory_id: "mem-notes".to_string(),
529                instance_name: format!("name-{id}"),
530                working_directory: format!("/tmp/{id}"),
531                ..crate::backend::storage::agents::test_agent_instance(id, "def-claude", block, started)
532            };
533            mstore.instance_create(&inst).unwrap();
534        }
535
536        // Snapshots for the two with snapshots. Write the OLDER one
537        // first so its filestore-stamped modts is strictly less than the
538        // recent one — the handler sorts snapshot-bearing rows by modts
539        // desc, so writing blk-older second would invert the assertions.
540        // (Pre-Phase 3b this ordering was fragile because the dual-write
541        // chain ran fewer SQL statements between successive inserts, so
542        // adjacent writes landed in the same millisecond and the stable
543        // sort preserved instance_list_named's started_at order; now the
544        // additional db_agents UPDATE per instance widens the gap and
545        // distinct modts dominate the stable sort.)
546        let snap_older = serde_json::json!({
547            "schemaVersion": 1,
548            "nodes": [
549                {"type": "user_message", "id": "u0",
550                 "message": "earlier conversation"}
551            ]
552        });
553        write_snapshot(&filestore, "blk-older", &snap_older.to_string());
554        let snap_recent = serde_json::json!({
555            "schemaVersion": 1,
556            "nodes": [
557                {"type": "user_message", "id": "u0",
558                 "message": "# Session Context\nboilerplate"},
559                {"type": "markdown", "id": "m0", "content": "ack"},
560                {"type": "user_message", "id": "u1",
561                 "message": "fix the live-feed hover delay"}
562            ]
563        });
564        write_snapshot(&filestore, "blk-recent", &snap_recent.to_string());
565
566        let (engine, rx) = WshRpcEngine::new();
567        super::register_agent_handlers(&engine, &state);
568        (state, engine, rx)
569    }
570
571    #[tokio::test]
572    async fn handler_returns_sessions_with_previews_sorted_by_snapshot_first() {
573        let (_state, engine, mut rx) = build_state_with_seed();
574        let result: ListRecentSessionsResult = call_rpc(
575            &engine,
576            &mut rx,
577            COMMAND_LIST_RECENT_SESSIONS,
578            serde_json::json!({}),
579        )
580        .await;
581        let rows = result.rows;
582        assert!(result.degraded.is_empty(), "healthy seed must report no degraded sources");
583        assert_eq!(rows.len(), 3, "all three sessions surfaced");
584
585        // Sort: snapshot-bearing rows first (recent then older), then
586        // the no-snapshot row at the tail.
587        assert_eq!(rows[0].instance_id, "inst-recent");
588        assert!(rows[0].has_snapshot);
589        assert_eq!(rows[0].node_count, 3);
590        assert!(
591            rows[0].preview.starts_with("fix the live-feed"),
592            "preview should be the post-context user message, got {:?}",
593            rows[0].preview
594        );
595
596        assert_eq!(rows[1].instance_id, "inst-older");
597        assert!(rows[1].has_snapshot);
598        assert_eq!(rows[1].node_count, 1);
599        assert_eq!(rows[1].preview, "earlier conversation");
600
601        assert_eq!(rows[2].instance_id, "inst-none");
602        assert!(!rows[2].has_snapshot);
603        assert_eq!(rows[2].node_count, 0);
604        assert_eq!(rows[2].preview, "");
605
606        // Joins: definition + identity + memory names resolved.
607        // Consolidation Phase 3b: the row's name IS the agent's own name, and
608        // `instance_create` names a template launch after the launch. The
609        // template's "Claude Code" is no longer what this field carries — the
610        // picker renders `instance_name || definition_name` (MyAgentsList.tsx),
611        // so this is a fallback the UI only reaches for a nameless row.
612        assert_eq!(rows[0].definition_name, "name-inst-recent");
613        assert_eq!(rows[0].identity_name, "Work");
614        assert_eq!(rows[0].memory_name, "Notes");
615        assert_eq!(rows[0].block_id_hint, "blk-recent");
616    }
617
618    #[tokio::test]
619    async fn handler_identity_filter_restricts_rows() {
620        let (_state, engine, mut rx) = build_state_with_seed();
621        // Filter to a non-existent identity → empty list.
622        let result: ListRecentSessionsResult = call_rpc(
623            &engine,
624            &mut rx,
625            COMMAND_LIST_RECENT_SESSIONS,
626            serde_json::json!({ "identity_id": "no-such-bundle" }),
627        )
628        .await;
629        assert_eq!(result.rows.len(), 0);
630
631        // Filter to the seeded one → all three.
632        let result: ListRecentSessionsResult = call_rpc(
633            &engine,
634            &mut rx,
635            COMMAND_LIST_RECENT_SESSIONS,
636            serde_json::json!({ "identity_id": "id-work" }),
637        )
638        .await;
639        assert_eq!(result.rows.len(), 3);
640
641        // Empty-string identity_id is treated as "no filter" so the
642        // frontend can pass `""` without special-casing.
643        let result: ListRecentSessionsResult = call_rpc(
644            &engine,
645            &mut rx,
646            COMMAND_LIST_RECENT_SESSIONS,
647            serde_json::json!({ "identity_id": "" }),
648        )
649        .await;
650        assert_eq!(result.rows.len(), 3);
651    }
652
653    #[tokio::test]
654    async fn handler_respects_limit() {
655        let (_state, engine, mut rx) = build_state_with_seed();
656        let result: ListRecentSessionsResult = call_rpc(
657            &engine,
658            &mut rx,
659            COMMAND_LIST_RECENT_SESSIONS,
660            serde_json::json!({ "limit": 1 }),
661        )
662        .await;
663        assert_eq!(result.rows.len(), 1);
664        assert_eq!(result.rows[0].instance_id, "inst-recent");
665    }
666
667    // ---- Two-tier picker Phase 1: create-from-template + listagents filter ----
668    //
669    // SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md.
670
671    /// Same shape as build_state_with_seed but with a seeded template
672    /// and no instances, so the create-from-template path is exercised
673    /// against a known-good template row.
674    fn build_state_with_template_seed() -> (
675        AppState,
676        Arc<WshRpcEngine>,
677        tokio::sync::mpsc::UnboundedReceiver<crate::backend::rpc_types::RpcMessage>,
678    ) {
679        let mstore = Arc::new(Store::open_in_memory().unwrap());
680        let filestore = Arc::new(FileStore::open_in_memory().unwrap());
681        let event_bus = Arc::new(crate::backend::eventbus::EventBus::new());
682        let broker = Arc::new(crate::backend::mps::Broker::new());
683        let reactive_handler = crate::backend::reactive::get_global_handler();
684        let poller = Arc::new(crate::backend::reactive::Poller::new(
685            crate::backend::reactive::PollerConfig {
686                muxbus_url: None,
687                muxbus_token: None,
688                poll_interval_secs: 30,
689            },
690            reactive_handler,
691        ));
692        crate::backend::wcore::ensure_initial_data(&mstore).unwrap();
693        let config_watcher = Arc::new(crate::backend::wconfig::ConfigState::new());
694        let process_tracker = Arc::new(
695            crate::backend::process_tracker::registry::AgentProcessRegistry::new(Some(broker.clone())),
696        );
697        let process_broker = Arc::new(crate::broker::ProcessBroker::new(Some(broker.clone())));
698        let fs_watch_pool = crate::backend::fs_watch::FsWatchPool::new();
699        let state = AppState {
700            auth_key: "test".to_string(),
701            lan_key: "test-lan".to_string(),
702            boot_id: std::sync::Arc::from("test-boot"),
703            version: "test".to_string(),
704            hostname: "test-host".to_string(),
705            app_path: String::new(),
706            mstore: mstore.clone(),
707            shared_store: None,
708            move_staging: None,
709            id_store: mstore.clone(),
710            identity_store: mstore.clone(),
711            work_store: mstore.clone(),
712            cron_store: None,
713            filestore: filestore.clone(),
714            global_transcript_store: None,
715            event_bus: event_bus.clone(),
716            broker: broker.clone(),
717            reactive_handler,
718            poller,
719            config_watcher,
720            messagebus: Arc::new(crate::backend::messagebus::MessageBus::new()),
721            http_client: reqwest::Client::new(),
722            host_ipc: Arc::new(tokio::sync::Mutex::new(None)),
723            host_reg_secret: None,
724            local_web_url: String::new(),
725            subagent_watcher: Arc::new(crate::backend::subagent_watcher::SubagentWatcher::new(event_bus.clone(), mstore.clone(), mstore.clone(), mstore.clone())),
726            history_service: Arc::new(crate::backend::history::HistoryService::new()),
727            lan_discovery: Arc::new(crate::backend::lan::discovery::LanDiscoveryController::new(
728                "test-instance".to_string(),
729                "test-host".to_string(),
730                "0.28.20".to_string(),
731                0,
732                event_bus.clone(),
733                String::new(),
734            )),
735            lan_listeners: Arc::new(crate::backend::lan::listeners::LanListenerSupervisor::new(0, 0)),
736            fleet_feed: Arc::new(crate::backend::fleet_feed::FleetFeed::new(
737                "test-host".to_string(),
738                "test-channel".to_string(),
739                "0.0.0-test".to_string(),
740            )),
741            viewer: crate::backend::viewer::ViewerService::new(None, &broker),
742            lsp_supervisor: Arc::new(crate::backend::lsp::LspSupervisor::new(event_bus.clone())),
743            process_tracker,
744            process_broker,
745            dock_snapshots: Arc::new(crate::backend::dock_snapshot::DockSnapshotCache::new()),
746            narrated_events: Arc::new(crate::backend::narrated_events::NarratedEvents::new()),
747            srv_state: Arc::new(tokio::sync::Mutex::new(crate::state::State::default())),
748            srv_events_tx: tokio::sync::broadcast::channel::<agentmux_common::ipc::Event>(64).0,
749            saga_id_alloc: Arc::new(std::sync::atomic::AtomicU64::new(0)),
750            saga_log: Arc::new(crate::sagas::log::SagaLog::open_in_memory().unwrap()),
751            auth_session_manager: Arc::new(crate::identity::auth_session::AuthSessionManager::new()),
752            install_sessions: crate::server::install_handlers::InstallSessionRegistry::new(),
753            container_manager: Arc::new(crate::backend::container::ContainerRuntimeHandle::disabled()),
754            dev_proxy: crate::backend::dev_proxy::DevProxyRegistry::new(),
755            shell_sessions: crate::backend::shell_node::ShellSessionRegistry::new(),
756            cron_scheduler: crate::backend::cron::CronScheduler::new(
757                None,
758                reqwest::Client::new(),
759                String::new(),
760                "test".to_string(),
761                broker.clone(),
762            ),
763            editor_file_watcher: crate::backend::editor_file_watcher::EditorFileWatcher::new(
764                fs_watch_pool.clone(),
765                broker.clone(),
766            ),
767            media_file_watcher: crate::backend::media_file_watcher::MediaFileWatcher::new(
768                fs_watch_pool.clone(),
769                broker.clone(),
770            ),
771            files_watcher: crate::backend::files_watcher::FilesWatcher::new(
772                fs_watch_pool.clone(),
773                broker.clone(),
774            ),
775            fs_watch_pool: fs_watch_pool.clone(),
776        };
777
778        // One seeded template + one already-user-owned definition.
779        let mut tpl = AgentDefinition {
780            slug: String::new(),
781            description: "Anthropic's coding agent".to_string(),
782            provider_flags: "--model haiku".to_string(),
783            is_seeded: 1,
784            ..crate::backend::storage::agents::test_agent_def("tpl-claude", "Claude Code", "claude", "host", 1_700_000_000_000, "")
785        };
786        mstore.agent_def_insert(&mut tpl).unwrap();
787
788        let mut user_a = AgentDefinition {
789            slug: String::new(),
790            ..crate::backend::storage::agents::test_agent_def("user-a", "Maks", "claude", "host", 1_700_000_001_000, "")
791        };
792        mstore.agent_def_insert(&mut user_a).unwrap();
793
794        let (engine, rx) = WshRpcEngine::new();
795        super::register_agent_handlers(&engine, &state);
796        (state, engine, rx)
797    }
798
799    #[tokio::test]
800    async fn listagents_no_filter_returns_all() {
801        let (_state, engine, mut rx) = build_state_with_template_seed();
802        let agents: Vec<AgentDefinition> = call_rpc(
803            &engine,
804            &mut rx,
805            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
806            serde_json::json!({}),
807        )
808        .await;
809        assert!(agents.iter().any(|a| a.id == "tpl-claude"));
810        assert!(agents.iter().any(|a| a.id == "user-a"));
811    }
812
813    #[tokio::test]
814    async fn listagents_filter_templates_only() {
815        let (_state, engine, mut rx) = build_state_with_template_seed();
816        let agents: Vec<AgentDefinition> = call_rpc(
817            &engine,
818            &mut rx,
819            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
820            serde_json::json!({ "is_seeded": 1 }),
821        )
822        .await;
823        assert!(agents.iter().all(|a| a.is_seeded == 1));
824        assert!(agents.iter().any(|a| a.id == "tpl-claude"));
825        assert!(!agents.iter().any(|a| a.id == "user-a"));
826    }
827
828    #[tokio::test]
829    async fn listagents_filter_user_owned_only() {
830        let (_state, engine, mut rx) = build_state_with_template_seed();
831        let agents: Vec<AgentDefinition> = call_rpc(
832            &engine,
833            &mut rx,
834            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
835            serde_json::json!({ "is_seeded": 0 }),
836        )
837        .await;
838        assert!(agents.iter().all(|a| a.is_seeded == 0));
839        assert!(agents.iter().any(|a| a.id == "user-a"));
840        assert!(!agents.iter().any(|a| a.id == "tpl-claude"));
841    }
842
843    #[tokio::test]
844    async fn create_from_template_happy_path_clones_and_returns_id() {
845        let (_state, engine, mut rx) = build_state_with_template_seed();
846        let resp: crate::backend::rpc_types::AgentDefCreateFromTemplateResult = call_rpc(
847            &engine,
848            &mut rx,
849            crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
850            serde_json::json!({
851                "template_id": "tpl-claude",
852                "name": "Asaf",
853                "identity_id": "id-work",
854                "memory_id": "mem-notes",
855            }),
856        )
857        .await;
858        assert!(!resp.definition_id.is_empty());
859        assert_eq!(resp.identity_id, "id-work");
860        assert_eq!(resp.memory_id, "mem-notes");
861
862        // The new row is user-owned, carries provider + flags from template.
863        let agents: Vec<AgentDefinition> = call_rpc(
864            &engine,
865            &mut rx,
866            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
867            serde_json::json!({}),
868        )
869        .await;
870        let new_def = agents
871            .iter()
872            .find(|a| a.id == resp.definition_id)
873            .expect("new definition should appear in listagents");
874        assert_eq!(new_def.is_seeded, 0);
875        assert_eq!(new_def.name, "Asaf");
876        assert_eq!(new_def.provider, "claude");
877        assert_eq!(new_def.provider_flags, "--model haiku");
878        assert_eq!(new_def.parent_id, "tpl-claude");
879    }
880
881    /// #3573: the response carries the slug the backend gave the new row,
882    /// punctuation-trimmed and collision-suffixed, so the launch's
883    /// `AGENTMUX_AGENT_ID` names this agent and not another (or none).
884    #[tokio::test]
885    async fn create_from_template_returns_the_rows_own_slug() {
886        let (_state, engine, mut rx) = build_state_with_template_seed();
887        let mut created = Vec::new();
888        for name in ["Reviewer!", "Reviewer?"] {
889            let resp: crate::backend::rpc_types::AgentDefCreateFromTemplateResult = call_rpc(
890                &engine,
891                &mut rx,
892                crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
893                serde_json::json!({ "template_id": "tpl-claude", "name": name }),
894            )
895            .await;
896            created.push(resp);
897        }
898        let (first, second) = (&created[0], &created[1]);
899        assert_eq!(first.slug, "reviewer");
900        assert_eq!(second.slug, "reviewer-2");
901
902        let agents: Vec<AgentDefinition> = call_rpc(
903            &engine,
904            &mut rx,
905            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
906            serde_json::json!({}),
907        )
908        .await;
909        for resp in &created {
910            let row = agents.iter().find(|a| a.id == resp.definition_id).unwrap();
911            assert_eq!(row.slug, resp.slug);
912        }
913    }
914
915    // ---- A new agent definition has no bundle of its own ----
916    //
917    // REPORT_AGENT_BUNDLES_REFINE_OR_DROP_2026_11_03.md: the empty
918    // "<Name> — ABF" bundle every new agent used to get is no longer
919    // created.
920
921    #[tokio::test]
922    async fn create_from_template_creates_no_bundle() {
923        let (state, engine, mut rx) = build_state_with_template_seed();
924        let bundles_before = state.id_store.bundle_list().unwrap().len();
925        let resp: crate::backend::rpc_types::AgentDefCreateFromTemplateResult = call_rpc(
926            &engine,
927            &mut rx,
928            crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
929            serde_json::json!({
930                "template_id": "tpl-claude",
931                "name": "Asaf",
932            }),
933        )
934        .await;
935        let new_def = state
936            .mstore
937            .agent_def_get(&resp.definition_id)
938            .unwrap()
939            .expect("new definition should exist");
940        assert!(new_def.memory_id.is_empty(), "a new definition has no bundle of its own");
941        assert_eq!(state.id_store.bundle_list().unwrap().len(), bundles_before, "no bundle is created");
942    }
943
944    #[tokio::test]
945    async fn fork_agent_definition_creates_no_bundle() {
946        let (state, engine, mut rx) = build_state_with_template_seed();
947        let bundles_before = state.id_store.bundle_list().unwrap().len();
948        // forkagentdefinition returns the full new AgentDefinition directly.
949        let fork_resp: AgentDefinition = call_rpc(
950            &engine,
951            &mut rx,
952            crate::backend::rpc_types::COMMAND_FORK_AGENT_DEFINITION,
953            serde_json::json!({ "source_id": "user-a", "branch_label": "" }),
954        )
955        .await;
956        let fork = state
957            .mstore
958            .agent_def_get(&fork_resp.id)
959            .unwrap()
960            .expect("fork should exist");
961        assert!(fork.memory_id.is_empty(), "a fork has no bundle of its own");
962        assert_eq!(fork.memory_id, fork_resp.memory_id);
963        assert_eq!(state.id_store.bundle_list().unwrap().len(), bundles_before, "no bundle is created");
964    }
965
966    #[tokio::test]
967    async fn createagent_creates_no_bundle() {
968        let (state, engine, mut rx) = build_state_with_template_seed();
969        let bundles_before = state.id_store.bundle_list().unwrap().len();
970        let created: AgentDefinition = call_rpc(
971            &engine,
972            &mut rx,
973            crate::backend::rpc_types::COMMAND_CREATE_AGENT,
974            serde_json::json!({ "name": "Codex Agent", "provider": "codex" }),
975        )
976        .await;
977        assert!(created.memory_id.is_empty(), "a new agent has no bundle of its own");
978        let stored = state.mstore.agent_def_get(&created.id).unwrap().unwrap();
979        assert_eq!(stored.memory_id, "");
980        assert_eq!(state.id_store.bundle_list().unwrap().len(), bundles_before, "no bundle is created");
981        assert_eq!(stored.provider, "codex");
982    }
983
984    // agent.define's own provisioning coverage lives in
985    // server/app_api/agent_define.rs's test module (it calls
986    // agent_define_core directly — that RPC isn't wired onto this file's
987    // build_state_with_template_seed engine, which only registers
988    // register_agent_handlers, not app_api::register).
989
990    async fn call_rpc_expect_error(
991        engine: &Arc<WshRpcEngine>,
992        rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::backend::rpc_types::RpcMessage>,
993        command: &str,
994        data: serde_json::Value,
995    ) -> String {
996        let req_id = format!("test-{}", uuid::Uuid::new_v4());
997        let msg = crate::backend::rpc_types::RpcMessage {
998            command: command.to_string(),
999            reqid: req_id.clone(),
1000            data: Some(data),
1001            ..Default::default()
1002        };
1003        engine.handle_message(msg);
1004        let resp = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
1005            .await
1006            .expect("handler timed out")
1007            .expect("output channel closed");
1008        assert_eq!(resp.resid, req_id);
1009        assert!(
1010            !resp.error.is_empty(),
1011            "expected error, got success payload: {:?}",
1012            resp.data
1013        );
1014        resp.error
1015    }
1016
1017    #[tokio::test]
1018    async fn create_from_template_rejects_non_template_id() {
1019        let (_state, engine, mut rx) = build_state_with_template_seed();
1020        // "user-a" is is_seeded=0 — not a template.
1021        let err = call_rpc_expect_error(
1022            &engine,
1023            &mut rx,
1024            crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
1025            serde_json::json!({
1026                "template_id": "user-a",
1027                "name": "another",
1028            }),
1029        )
1030        .await;
1031        assert!(
1032            err.contains("not a seeded template"),
1033            "wrong error: {err}"
1034        );
1035    }
1036
1037    #[tokio::test]
1038    async fn create_from_template_rejects_unknown_template_id() {
1039        let (_state, engine, mut rx) = build_state_with_template_seed();
1040        let err = call_rpc_expect_error(
1041            &engine,
1042            &mut rx,
1043            crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
1044            serde_json::json!({
1045                "template_id": "no-such-id",
1046                "name": "x",
1047            }),
1048        )
1049        .await;
1050        assert!(err.contains("not found"), "wrong error: {err}");
1051    }
1052
1053    #[tokio::test]
1054    async fn create_from_template_rejects_duplicate_user_name() {
1055        let (_state, engine, mut rx) = build_state_with_template_seed();
1056        // "Maks" already exists as a user-owned agent.
1057        let err = call_rpc_expect_error(
1058            &engine,
1059            &mut rx,
1060            crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
1061            serde_json::json!({
1062                "template_id": "tpl-claude",
1063                "name": "Maks",
1064            }),
1065        )
1066        .await;
1067        assert!(
1068            err.contains("already exists"),
1069            "wrong error: {err}"
1070        );
1071    }
1072
1073    #[tokio::test]
1074    async fn create_from_template_rejects_empty_name() {
1075        let (_state, engine, mut rx) = build_state_with_template_seed();
1076        let err = call_rpc_expect_error(
1077            &engine,
1078            &mut rx,
1079            crate::backend::rpc_types::COMMAND_AGENT_DEF_CREATE_FROM_TEMPLATE,
1080            serde_json::json!({
1081                "template_id": "tpl-claude",
1082                "name": "   ",
1083            }),
1084        )
1085        .await;
1086        assert!(err.contains("non-empty"), "wrong error: {err}");
1087    }
1088
1089    // ---- Two-tier picker Phase 2: hide / unhide templates ----
1090    //
1091    // SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md Q2 Decision Y.
1092
1093    #[tokio::test]
1094    async fn hide_template_then_listagents_excludes_it_by_default() {
1095        let (_state, engine, mut rx) = build_state_with_template_seed();
1096
1097        // Before hide: template is in the default listagents result.
1098        let before: Vec<AgentDefinition> = call_rpc(
1099            &engine,
1100            &mut rx,
1101            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
1102            serde_json::json!({}),
1103        )
1104        .await;
1105        assert!(before.iter().any(|a| a.id == "tpl-claude"));
1106
1107        // Hide the template.
1108        let resp: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1109            &engine,
1110            &mut rx,
1111            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1112            serde_json::json!({ "definition_id": "tpl-claude" }),
1113        )
1114        .await;
1115        assert!(resp.ok);
1116
1117        // After hide: default listagents no longer surfaces it.
1118        let after: Vec<AgentDefinition> = call_rpc(
1119            &engine,
1120            &mut rx,
1121            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
1122            serde_json::json!({}),
1123        )
1124        .await;
1125        assert!(
1126            !after.iter().any(|a| a.id == "tpl-claude"),
1127            "hidden template should NOT appear by default",
1128        );
1129
1130        // But user-owned rows (is_seeded=0) still appear — hide only
1131        // affects templates.
1132        assert!(after.iter().any(|a| a.id == "user-a"));
1133
1134        // include_hidden = true brings it back (settings panel surface).
1135        let included: Vec<AgentDefinition> = call_rpc(
1136            &engine,
1137            &mut rx,
1138            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
1139            serde_json::json!({ "include_hidden": true }),
1140        )
1141        .await;
1142        let tpl = included
1143            .iter()
1144            .find(|a| a.id == "tpl-claude")
1145            .expect("hidden template should appear with include_hidden=true");
1146        assert_eq!(tpl.user_hidden, 1);
1147    }
1148
1149    /// The typed registration path records what it registers.
1150    ///
1151    /// This is the property the whole codegen plan rests on
1152    /// (`docs/specs/SPEC_RPC_BINDINGS_CODEGEN_2026_09_07.md`): the command →
1153    /// request/response mapping has to be data the process can hand out, and
1154    /// it has to come from registration itself rather than a second list
1155    /// someone maintains by hand. Asserting the exact type names means a
1156    /// rename that silently changes the generated bindings fails here.
1157    #[tokio::test]
1158    async fn register_typed_records_each_command_request_and_response_type() {
1159        let (_state, engine, _rx) = build_state_with_template_seed();
1160        let schema = engine.schema_json();
1161        let rows = schema.as_array().expect("schema is an array");
1162
1163        let find = |cmd: &str| {
1164            rows.iter()
1165                .find(|r| r["command"] == cmd)
1166                .unwrap_or_else(|| panic!("{cmd} missing from the schema — was it registered with register_handler instead of register_typed?"))
1167        };
1168
1169        for cmd in [
1170            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1171            crate::backend::rpc_types::COMMAND_AGENT_DEF_UNHIDE,
1172        ] {
1173            let row = find(cmd);
1174            assert_eq!(row["requestName"], "CommandAgentDefHideData", "{cmd} request type");
1175            assert_eq!(row["responseName"], "AgentDefHideResult", "{cmd} response type");
1176            // The full path is what disambiguates two same-named types in
1177            // different modules, so it must be a path, not a bare name.
1178            assert!(
1179                row["request"].as_str().unwrap().contains("::"),
1180                "{cmd} request should be fully qualified, got {:?}",
1181                row["request"]
1182            );
1183        }
1184
1185        // `getagentcontent` answers `Option<AgentContent>` rather than
1186        // hand-serializing to a `Value`. That distinction is invisible on the
1187        // wire — both send the same JSON — and only shows up here, in what the
1188        // registry recorded. Serializing by hand would record `Value` and quietly
1189        // drop this one endpoint out of the drift net the migration exists to
1190        // build, so assert the recorded type, not the response body.
1191        let content_row = find(crate::backend::rpc_types::COMMAND_GET_AGENT_CONTENT);
1192        let recorded = content_row["response"].as_str().unwrap_or_default();
1193        assert!(
1194            recorded.contains("AgentContent"),
1195            "getagentcontent should record AgentContent, got {recorded:?}",
1196        );
1197        assert!(
1198            !recorded.contains("serde_json::Value"),
1199            "getagentcontent must not hand-serialize its response — that records              Value and leaves it outside the drift net; got {recorded:?}",
1200        );
1201
1202        // `listagents` tolerates a null/malformed body for older clients, so its
1203        // request stays `Value` (see its registration in core.rs). Its response is
1204        // still recorded, which is where the drift risk lived.
1205        let list = find(crate::backend::rpc_types::COMMAND_LIST_AGENTS);
1206        assert_eq!(list["requestName"], "Value");
1207        assert_eq!(list["responseTs"]["name"], "Array<AgentDefinition>");
1208    }
1209
1210    /// A migrated handler answers exactly as it did before, including the
1211    /// error shape for a malformed request.
1212    #[tokio::test]
1213    async fn register_typed_preserves_the_wire_behaviour_of_a_migrated_handler() {
1214        let (_state, engine, mut rx) = build_state_with_template_seed();
1215
1216        // Happy path: unchanged response body.
1217        let resp: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1218            &engine,
1219            &mut rx,
1220            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1221            serde_json::json!({ "definition_id": "tpl-claude" }),
1222        )
1223        .await;
1224        assert!(resp.ok);
1225
1226        // Malformed request: still an RPC error, still prefixed with the
1227        // command name the hand-written body used.
1228        let err = call_rpc_expect_error(
1229            &engine,
1230            &mut rx,
1231            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1232            serde_json::json!({ "definition_id": 42 }),
1233        )
1234        .await;
1235        assert!(
1236            err.starts_with("agentdefhide:"),
1237            "error should keep the command prefix, got {err:?}",
1238        );
1239    }
1240
1241    #[tokio::test]
1242    async fn hide_then_unhide_round_trip() {
1243        let (_state, engine, mut rx) = build_state_with_template_seed();
1244        let _: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1245            &engine,
1246            &mut rx,
1247            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1248            serde_json::json!({ "definition_id": "tpl-claude" }),
1249        )
1250        .await;
1251        let resp: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1252            &engine,
1253            &mut rx,
1254            crate::backend::rpc_types::COMMAND_AGENT_DEF_UNHIDE,
1255            serde_json::json!({ "definition_id": "tpl-claude" }),
1256        )
1257        .await;
1258        assert!(resp.ok);
1259        // Listagents now shows it again, default-filter included.
1260        let agents: Vec<AgentDefinition> = call_rpc(
1261            &engine,
1262            &mut rx,
1263            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
1264            serde_json::json!({}),
1265        )
1266        .await;
1267        let tpl = agents
1268            .iter()
1269            .find(|a| a.id == "tpl-claude")
1270            .expect("unhidden template should appear");
1271        assert_eq!(tpl.user_hidden, 0);
1272    }
1273
1274    #[tokio::test]
1275    async fn hide_rejects_user_owned_definition() {
1276        let (_state, engine, mut rx) = build_state_with_template_seed();
1277        // "user-a" is is_seeded=0 — hide must reject.
1278        let err = call_rpc_expect_error(
1279            &engine,
1280            &mut rx,
1281            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1282            serde_json::json!({ "definition_id": "user-a" }),
1283        )
1284        .await;
1285        assert!(
1286            err.contains("not a seeded template"),
1287            "wrong error: {err}"
1288        );
1289    }
1290
1291    #[tokio::test]
1292    async fn hide_unknown_id_returns_ok_false() {
1293        let (_state, engine, mut rx) = build_state_with_template_seed();
1294        let resp: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1295            &engine,
1296            &mut rx,
1297            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1298            serde_json::json!({ "definition_id": "no-such-id" }),
1299        )
1300        .await;
1301        assert!(!resp.ok);
1302    }
1303
1304    #[tokio::test]
1305    async fn list_hidden_templates_returns_only_hidden_templates() {
1306        let (_state, engine, mut rx) = build_state_with_template_seed();
1307        // Empty initially.
1308        let empty: Vec<AgentDefinition> = call_rpc(
1309            &engine,
1310            &mut rx,
1311            crate::backend::rpc_types::COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES,
1312            serde_json::json!({}),
1313        )
1314        .await;
1315        assert!(empty.is_empty());
1316
1317        // Hide one; expect it to surface.
1318        let _: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1319            &engine,
1320            &mut rx,
1321            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1322            serde_json::json!({ "definition_id": "tpl-claude" }),
1323        )
1324        .await;
1325        let hidden: Vec<AgentDefinition> = call_rpc(
1326            &engine,
1327            &mut rx,
1328            crate::backend::rpc_types::COMMAND_AGENT_DEF_LIST_HIDDEN_TEMPLATES,
1329            serde_json::json!({}),
1330        )
1331        .await;
1332        assert_eq!(hidden.len(), 1);
1333        assert_eq!(hidden[0].id, "tpl-claude");
1334        assert_eq!(hidden[0].is_seeded, 1);
1335        assert_eq!(hidden[0].user_hidden, 1);
1336    }
1337
1338    #[tokio::test]
1339    async fn listagents_is_seeded_filter_with_include_hidden_combines() {
1340        // Templates-only filter + include_hidden = the settings panel's
1341        // canonical query if it ever wanted the full template universe.
1342        // Without include_hidden + is_seeded=1 the hidden ones drop out.
1343        let (_state, engine, mut rx) = build_state_with_template_seed();
1344        let _: crate::backend::rpc_types::AgentDefHideResult = call_rpc(
1345            &engine,
1346            &mut rx,
1347            crate::backend::rpc_types::COMMAND_AGENT_DEF_HIDE,
1348            serde_json::json!({ "definition_id": "tpl-claude" }),
1349        )
1350        .await;
1351        let templates_visible: Vec<AgentDefinition> = call_rpc(
1352            &engine,
1353            &mut rx,
1354            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
1355            serde_json::json!({ "is_seeded": 1 }),
1356        )
1357        .await;
1358        assert!(
1359            !templates_visible.iter().any(|a| a.id == "tpl-claude"),
1360            "hidden template should be excluded from is_seeded=1 default query",
1361        );
1362        let templates_all: Vec<AgentDefinition> = call_rpc(
1363            &engine,
1364            &mut rx,
1365            crate::backend::rpc_types::COMMAND_LIST_AGENTS,
1366            serde_json::json!({ "is_seeded": 1, "include_hidden": true }),
1367        )
1368        .await;
1369        assert!(templates_all.iter().any(|a| a.id == "tpl-claude"));
1370    }
1371}