Skip to main content

agentmux_srv/server/agent_handlers/
session.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The session RPCs: `listrecentsessions` (the My Agents list, `recent.rs`) and the agent-anchored session zone
5//! (`zone.rs`). `register` only wires each command to its named function.
6
7use std::sync::Arc;
8
9use crate::backend::rpc::engine::WshRpcEngine;
10use crate::backend::rpc_types::{
11    CommandAgentSessionAppendOutputData, CommandAgentSessionArchiveData, CommandAgentSessionListArchivesData,
12    CommandAgentSessionReadData, CommandAgentSessionWriteStateData, COMMAND_AGENT_SESSION_APPEND_OUTPUT,
13    COMMAND_AGENT_SESSION_ARCHIVE, COMMAND_AGENT_SESSION_LIST_ARCHIVES, COMMAND_AGENT_SESSION_READ,
14    COMMAND_AGENT_SESSION_WRITE_STATE, COMMAND_LIST_RECENT_SESSIONS,
15};
16
17use super::super::AppState;
18
19mod recent;
20mod zone;
21
22/// At-most-once-per-process-lifetime claim set for definition-summary
23/// generation attempts triggered from `listrecentsessions` — see the call
24/// site in `recent.rs` and `db_agent_activity_summaries` (OBJECT_SCHEMA_VERSION
25/// v28). `HashSet::insert` returns `true` only the first time a given
26/// `definition_id` is claimed; every later call for the same id (a repeat
27/// poll of "My Agents") sees `false` and does not re-spawn.
28fn definition_summary_attempted() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {
29    static SET: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
30        std::sync::OnceLock::new();
31    SET.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
32}
33
34pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
35    register_recent_sessions(engine, state);
36    register_session_zone(engine, state);
37}
38
39fn register_recent_sessions(engine: &Arc<WshRpcEngine>, state: &AppState) {
40    let deps = recent::RecentSessionsDeps {
41        mstore: state.mstore.clone(),
42        id_store: state.id_store.clone(),
43        identity_store: state.identity_store.clone(),
44        filestore: state.filestore.clone(),
45        broker: state.broker.clone(),
46    };
47    // `Value` request: a malformed one means the defaults.
48    engine.register_typed(COMMAND_LIST_RECENT_SESSIONS, move |data: serde_json::Value, _ctx| {
49        let deps = deps.clone();
50        async move { recent::list_recent_sessions(&deps, data).await }
51    });
52}
53
54fn register_session_zone(engine: &Arc<WshRpcEngine>, state: &AppState) {
55    let filestore = state.filestore.clone();
56    engine.register_typed(COMMAND_AGENT_SESSION_READ, move |cmd: CommandAgentSessionReadData, _ctx| {
57        let filestore = filestore.clone();
58        async move { zone::read_session(&filestore, &cmd) }
59    });
60
61    let (filestore, mstore) = (state.filestore.clone(), state.mstore.clone());
62    engine.register_typed(COMMAND_AGENT_SESSION_WRITE_STATE, move |cmd: CommandAgentSessionWriteStateData, ctx| {
63        let (filestore, mstore) = (filestore.clone(), mstore.clone());
64        async move { zone::write_state(&filestore, &mstore, &ctx, &cmd) }
65    });
66
67    let (filestore, mstore) = (state.filestore.clone(), state.mstore.clone());
68    engine.register_typed(COMMAND_AGENT_SESSION_APPEND_OUTPUT, move |cmd: CommandAgentSessionAppendOutputData, ctx| {
69        let (filestore, mstore) = (filestore.clone(), mstore.clone());
70        async move { zone::append_output(&filestore, &mstore, &ctx, &cmd) }
71    });
72
73    let (filestore, mstore) = (state.filestore.clone(), state.mstore.clone());
74    engine.register_typed(COMMAND_AGENT_SESSION_ARCHIVE, move |cmd: CommandAgentSessionArchiveData, ctx| {
75        let (filestore, mstore) = (filestore.clone(), mstore.clone());
76        async move { zone::archive(&filestore, &mstore, &ctx, &cmd) }
77    });
78
79    let filestore = state.filestore.clone();
80    engine.register_typed(COMMAND_AGENT_SESSION_LIST_ARCHIVES, move |cmd: CommandAgentSessionListArchivesData, _ctx| {
81        let filestore = filestore.clone();
82        async move { zone::list_archives(&filestore, &cmd) }
83    });
84}
85
86#[cfg(test)]
87mod characterization_tests;
88
89#[cfg(test)]
90mod direct_tests;
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::backend::storage::store::{AgentDefinition, AgentInstance};
96    use crate::backend::rpc_types::{ListRecentSessionsResult, RpcMessage};
97    use crate::registry::{
98        DefinitionRecord, DefinitionRecordV1, DefinitionStore, NamedAgentRecord,
99        NamedAgentRecordV1, Registry,
100    };
101    use crate::server::tests::test_state;
102
103    fn named_record(instance_id: &str, definition_id: &str) -> NamedAgentRecord {
104        NamedAgentRecord {
105            schema_version: 1,
106            data: NamedAgentRecordV1 {
107                instance_id: instance_id.to_string(),
108                instance_name: format!("session-{instance_id}"),
109                definition_id: definition_id.to_string(),
110                identity_id: None,
111                memory_id: None,
112                session_id: None,
113                working_dir: format!("{definition_id}-workdir"),
114                source_agents_base: None,
115                created_at_ms: 1,
116                last_launched_at_ms: 1,
117                created_by_version: "test".to_string(),
118                last_launched_by_version: "test".to_string(),
119            },
120        }
121    }
122
123    fn definition_record(id: &str) -> DefinitionRecord {
124        DefinitionRecord {
125            schema_version: 1,
126            data: DefinitionRecordV1 {
127                id: id.to_string(),
128                name: format!("Agent {id}"),
129                provider: "claude".to_string(),
130                is_seeded: 0,
131                ..Default::default()
132            },
133        }
134    }
135
136    /// Seeds `state.mstore` with N cross-channel registry + definition
137    /// records (as they'd exist on a REAL machine before a fresh channel
138    /// ever boots) and returns the dispatch machinery ready to call
139    /// `listrecentsessions`.
140    fn setup_with_n_cross_channel_agents(
141        n: usize,
142    ) -> (
143        AppState,
144        std::sync::Arc<WshRpcEngine>,
145        tokio::sync::mpsc::UnboundedReceiver<RpcMessage>,
146        tempfile::TempDir,
147        tempfile::TempDir,
148    ) {
149        let state = test_state();
150        let registry_dir = tempfile::tempdir().unwrap();
151        let def_dir = tempfile::tempdir().unwrap();
152        let registry = Registry::open(registry_dir.path().to_path_buf()).unwrap();
153        let def_store = DefinitionStore::open(def_dir.path().to_path_buf()).unwrap();
154        for i in 0..n {
155            let id = format!("inst-{i}");
156            let def_id = format!("def-{i}");
157            registry.upsert(&named_record(&id, &def_id)).unwrap();
158            def_store.upsert(&definition_record(&def_id)).unwrap();
159        }
160        state.mstore.set_registry(std::sync::Arc::new(registry));
161        state.mstore.set_def_registry(std::sync::Arc::new(def_store));
162
163        let (engine, output_rx) = WshRpcEngine::new();
164        register(&engine, &state);
165        (state, engine, output_rx, registry_dir, def_dir)
166    }
167
168    async fn dispatch_list_recent_sessions(
169        engine: &std::sync::Arc<WshRpcEngine>,
170        output_rx: &mut tokio::sync::mpsc::UnboundedReceiver<RpcMessage>,
171    ) -> RpcMessage {
172        engine.handle_message(RpcMessage {
173            command: COMMAND_LIST_RECENT_SESSIONS.to_string(),
174            reqid: "req-1".to_string(),
175            data: Some(serde_json::json!({ "limit": 20 })),
176            ..Default::default()
177        });
178        tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
179            .await
180            .unwrap()
181            .unwrap()
182    }
183
184    /// Retro
185    /// `docs/retro/retro-my-agents-fresh-channel-regression-2026-07-27.md`
186    /// §9 rec 5: this exact path (fresh channel + pre-populated global
187    /// registry) had broken three separate times with no regression test
188    /// covering it. Directly exercises the RPC end-to-end against a real
189    /// `Registry`/`DefinitionStore` on disk — the same code path a fresh
190    /// `task package` channel hits on its very first "My Agents" fetch.
191    #[tokio::test]
192    async fn cross_channel_registry_agents_populate_a_fresh_channels_my_agents_list() {
193        let (_state, engine, mut output_rx, _reg_dir, _def_dir) =
194            setup_with_n_cross_channel_agents(3);
195
196        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
197
198        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
199        let result: ListRecentSessionsResult =
200            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
201        assert_eq!(
202            result.rows.len(),
203            3,
204            "all 3 cross-channel registry agents must appear on a channel that never created any of them locally"
205        );
206        assert!(
207            result.degraded.is_empty(),
208            "a fully healthy call must report no degraded sources, got: {:?}",
209            result.degraded
210        );
211    }
212
213    /// Retro §4/§9 rec 1 — the core hardening this test locks in. Before
214    /// this fix, `identity_list()` failing on one unparseable `db_accounts`
215    /// row (PR #2296's exact incident: an oauth secret_ref serde-tag
216    /// mismatch) `?`-aborted the ENTIRE `listrecentsessions` response,
217    /// zeroing "My Agents" even though the registry/definitions themselves
218    /// were completely healthy. Reproduces that exact malformed-row shape
219    /// directly via raw SQL (bypassing `identity_upsert`, which would
220    /// never produce an invalid `secret_ref`) and asserts the response
221    /// still contains every agent — only the identity-name enrichment
222    /// degrades, not the whole list.
223    #[tokio::test]
224    async fn a_malformed_identity_account_row_is_tolerated_without_degrading_the_accounts_source() {
225        let (state, engine, mut output_rx, _reg_dir, _def_dir) =
226            setup_with_n_cross_channel_agents(2);
227
228        // Same malformed shape as the real PR #2296 incident: a
229        // `secret_ref.backend` tag no `SecretRef` variant matches.
230        //
231        // Updated for ANALYSIS_ARMORY_STASH_CREDENTIAL_VISIBILITY_GAP_2026_08_04:
232        // `identity_list` itself now skips a malformed row (with a warning)
233        // instead of erroring the whole call (backend/storage/identities.rs),
234        // so this scenario no longer reaches the `unwrap_or_else` degrade
235        // path below at all — the "accounts" source is no longer degraded
236        // by a single bad row, it's just quietly correct. The `degraded`
237        // push at that call site still exists and is still meaningful for a
238        // genuine `identity_list` error (e.g. a real DB failure); it's
239        // simply no longer reachable via this specific fixture.
240        {
241            let conn = state.mstore.conn().lock().unwrap();
242            conn.execute(
243                "INSERT INTO db_accounts
244                    (id, name, provider, kind, display_name, secret_ref, context, status, created_at, updated_at)
245                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
246                rusqlite::params![
247                    "acct-broken",
248                    "broken-account",
249                    "claude",
250                    "oauth",
251                    "",
252                    r#"{"backend":"totally_bogus_backend"}"#,
253                    "{}",
254                    "unknown",
255                    0i64,
256                    0i64,
257                ],
258            )
259            .unwrap();
260        }
261
262        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
263
264        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
265        let result: ListRecentSessionsResult =
266            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
267        assert_eq!(
268            result.rows.len(),
269            2,
270            "a single malformed db_accounts row must not zero out the whole \
271             My Agents list"
272        );
273        // The improved behavior: identity_list's own per-row tolerance means
274        // this is no longer a "source failure" at all — nothing degraded,
275        // the malformed row was just silently excluded. Contrast with the
276        // OLD assertion this test used to make (`degraded` contains
277        // "accounts") — that was evidence of a real, if survivable, failure;
278        // this is evidence there wasn't one. The `degraded.push("accounts")`
279        // call site (above, in the handler) is still meaningful for a
280        // genuine `identity_list` error — just no longer reachable via this
281        // fixture.
282        assert!(
283            !result.degraded.contains(&"accounts".to_string()),
284            "a single malformed row must not degrade the accounts source at all \
285             (identity_list now tolerates it internally), got: {:?}",
286            result.degraded
287        );
288    }
289
290    /// docs/reports/REPORT_AGENT_PICKER_FIELD_ORDER_SORT_AND_DATA_GAPS_AUDIT_2026_08_24.md
291    /// §4: when `agent_identity_list_all()` itself fails, no row can say whether
292    /// its agent is bound. A failure must not read like a healthy "No auth", so
293    /// the account line is left empty (SPEC_MY_AGENTS_TILES_AUTH_AND_HISTORY_2026_10_03.md
294    /// §5.2 R5). Forces the failure by dropping `db_agent_identity_links` outright
295    /// and asserts every row has an empty account line, with `degraded`
296    /// reporting "identity_links".
297    #[tokio::test]
298    async fn identity_links_source_failure_leaves_the_account_line_empty_not_no_auth() {
299        let (state, engine, mut output_rx, _reg_dir, _def_dir) =
300            setup_with_n_cross_channel_agents(2);
301
302        {
303            let conn = state.mstore.conn().lock().unwrap();
304            conn.execute("DROP TABLE db_agent_identity_links", []).unwrap();
305        }
306
307        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
308
309        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
310        let result: ListRecentSessionsResult =
311            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
312        assert_eq!(result.rows.len(), 2, "the identity_links failure must not zero out the whole list");
313        assert!(
314            result.degraded.contains(&"identity_links".to_string()),
315            "got: {:?}",
316            result.degraded
317        );
318        for row in &result.rows {
319            assert_eq!(
320                row.identity_name, "",
321                "a source FAILURE must claim nothing: an unbound agent reads \"No auth\" and a \
322                 backend outage must not look identical to that"
323            );
324        }
325    }
326
327    /// A failed ACCOUNTS lookup (the global mirror unreadable too) must not turn a
328    /// bound agent into "No auth": its account may be perfectly good. The linked
329    /// agent's line is left empty; an agent with no link is still plainly unbound.
330    #[tokio::test]
331    async fn a_failed_accounts_lookup_leaves_a_linked_agents_line_empty_not_no_auth() {
332        let (state, engine, mut output_rx, _reg_dir, _def_dir) = setup_with_n_cross_channel_agents(2);
333        {
334            let conn = state.identity_store.conn().lock().unwrap();
335            conn.execute_batch(
336                "PRAGMA foreign_keys=OFF; INSERT INTO db_agent_identity_links (agent_id, account_id, provider)                  VALUES ('def-0', 'acct-that-is-fine', 'claude');",
337            )
338            .unwrap();
339        }
340        {
341            let conn = state.id_store.conn().lock().unwrap();
342            conn.execute_batch("PRAGMA foreign_keys=OFF; DROP TABLE db_accounts;").unwrap();
343        }
344        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
345        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
346        let result: ListRecentSessionsResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
347        assert!(result.degraded.contains(&"accounts".to_string()), "got: {:?}", result.degraded);
348        let line = |def: &str| result.rows.iter().find(|r| r.definition_id == def).unwrap().identity_name.clone();
349        assert_eq!(line("def-0"), "", "a link we cannot resolve because the lookup failed is unknown, not unbound");
350        assert_eq!(line("def-1"), "No auth", "an agent with no link is unbound whatever the accounts lookup did");
351    }
352
353    /// A healthy list: agents with no account link read "No auth", and none of the
354    /// retired labels appears anywhere.
355    #[tokio::test]
356    async fn an_agent_with_no_account_link_says_no_auth_and_the_old_labels_are_gone() {
357        let (_state, engine, mut output_rx, _reg_dir, _def_dir) = setup_with_n_cross_channel_agents(2);
358        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
359        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
360        let result: ListRecentSessionsResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
361        assert_eq!(result.rows.len(), 2);
362        for row in &result.rows {
363            assert_eq!(row.identity_name, "No auth");
364            for old in ["(missing account)", "(ambient creds)", "(unknown account)"] {
365                assert_ne!(row.identity_name, old);
366            }
367        }
368    }
369
370    /// Minimal local (not cross-channel registry) `AgentDefinition` —
371    /// mirrors `storage/agents/mod.rs`'s own private `test_agent_def` test fixture
372    /// shape, duplicated here rather than widening that helper's
373    /// visibility for one caller.
374    fn local_agent_def(id: &str) -> AgentDefinition {
375        AgentDefinition {
376            conversation_visibility: "private".to_string(),
377            ..crate::backend::storage::agents::test_agent_def(id, &format!("Agent {id}"), "claude", "standalone", 1, "")
378        }
379    }
380
381    fn local_agent_instance(id: &str, definition_id: &str, block_id: &str) -> AgentInstance {
382        AgentInstance {
383            status: "available".to_string(),
384            instance_name: id.to_string(),
385            ..crate::backend::storage::agents::test_agent_instance(id, definition_id, block_id, 1)
386        }
387    }
388
389    /// docs/reports/REPORT_AGENT_PICKER_FIELD_ORDER_SORT_AND_DATA_GAPS_AUDIT_2026_08_24.md
390    /// §5a: a row with no structured `output.state.json` snapshot but a
391    /// PERSISTED `db_agent_activity_summaries` row for its definition must
392    /// surface that summary as `preview`, still reporting `has_snapshot:
393    /// false` (accurate — there genuinely is no structured snapshot; the
394    /// summary is a substitute, not a claim that one exists).
395    #[tokio::test]
396    async fn snapshot_less_row_uses_a_persisted_definition_summary_as_preview() {
397        let state = test_state();
398        let mut def = local_agent_def("def-local-1");
399        state.mstore.agent_def_insert(&mut def).unwrap();
400        state
401            .mstore
402            .instance_create(&local_agent_instance("inst-local-1", "def-local-1", "block-local-1"))
403            .unwrap();
404        state
405            .mstore
406            .agent_activity_summary_set("def-local-1", "Fixed the login race condition", 1000)
407            .unwrap();
408
409        let (engine, mut output_rx) = WshRpcEngine::new();
410        register(&engine, &state);
411        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
412
413        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
414        let result: ListRecentSessionsResult =
415            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
416        assert_eq!(result.rows.len(), 1);
417        let row = &result.rows[0];
418        assert!(!row.has_snapshot, "no output.state.json was ever written for this instance");
419        assert_eq!(
420            row.preview, "Fixed the login race condition",
421            "persisted definition summary must surface as the row's preview \
422             when there's no real snapshot to preview instead"
423        );
424    }
425
426    /// Counterpart to the above: when NOTHING is persisted yet for the
427    /// definition, the row's `preview` stays empty and the frontend shows its
428    /// own empty-state text ("No conversations yet").
429    /// Generation itself (a real Haiku CLI round-trip) is fire-and-forget
430    /// and not asserted here — this only locks in that a missing summary
431    /// never surfaces as a fabricated non-empty preview.
432    #[tokio::test]
433    async fn snapshot_less_row_with_no_persisted_summary_leaves_preview_empty() {
434        let state = test_state();
435        let mut def = local_agent_def("def-local-2");
436        state.mstore.agent_def_insert(&mut def).unwrap();
437        state
438            .mstore
439            .instance_create(&local_agent_instance("inst-local-2", "def-local-2", "block-local-2"))
440            .unwrap();
441
442        let (engine, mut output_rx) = WshRpcEngine::new();
443        register(&engine, &state);
444        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
445
446        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
447        let result: ListRecentSessionsResult =
448            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
449        assert_eq!(result.rows.len(), 1);
450        let row = &result.rows[0];
451        assert!(!row.has_snapshot);
452        assert_eq!(row.preview, "", "no summary persisted yet — preview must stay empty, not fabricated");
453    }
454
455    /// Put an `output` file in the (test) global transcript store for `def_id`.
456    fn install_transcript(store: &std::sync::Arc<crate::backend::storage::filestore::FileStore>, def_id: &str, ndjson: &str) {
457        let zone = format!("agent:{def_id}:current");
458        store
459            .make_file(&zone, "output", Default::default(), crate::backend::storage::filestore::FileOpts::default())
460            .unwrap();
461        store.write_file(&zone, "output", ndjson.as_bytes()).unwrap();
462    }
463
464    fn user_line(text: &str) -> String {
465        serde_json::json!({"type":"user","message":{"role":"user","content":text}}).to_string()
466    }
467
468    /// Clears the thread's test transcript store when a test ends, pass or fail.
469    struct TranscriptStoreGuard;
470    impl Drop for TranscriptStoreGuard {
471        fn drop(&mut self) {
472            crate::backend::agent_session::history_summary::set_test_store(None);
473        }
474    }
475
476    /// The preview, last-active time and "has history" flag come from the agent's
477    /// global transcript, so a registry-only row (no local instance, no block id)
478    /// with a transcript shows what it was last asked.
479    #[tokio::test]
480    async fn a_row_with_no_block_takes_its_preview_from_the_global_transcript() {
481        let (_state, engine, mut output_rx, _reg_dir, _def_dir) = setup_with_n_cross_channel_agents(2);
482        let store = std::sync::Arc::new(crate::backend::storage::filestore::FileStore::open_in_memory().unwrap());
483        install_transcript(&store, "def-0", &format!("{}\n{}", user_line("# Session Context\nboot"), user_line("ship the tiles")));
484        crate::backend::agent_session::history_summary::set_test_store(Some(store));
485        let _guard = TranscriptStoreGuard;
486
487        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
488        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
489        let result: ListRecentSessionsResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
490        let with = result.rows.iter().find(|r| r.definition_id == "def-0").unwrap();
491        assert!(with.block_id_hint.is_empty(), "the row has no local block");
492        assert!(with.has_snapshot);
493        assert!(!with.snapshot_check_failed);
494        assert_eq!(with.preview, "ship the tiles");
495        assert!(with.last_active_at > 1, "last-active comes from the transcript, got {}", with.last_active_at);
496        let without = result.rows.iter().find(|r| r.definition_id == "def-1").unwrap();
497        assert!(!without.has_snapshot, "an agent with no transcript has no history");
498        assert!(!without.snapshot_check_failed, "no transcript is a state, not a failed read");
499        assert_eq!(without.preview, "");
500    }
501
502    /// A transcript that holds no user prompt is still history: the row says so
503    /// (has_snapshot) rather than claiming the agent never ran.
504    #[tokio::test]
505    async fn a_transcript_without_a_prompt_still_counts_as_history() {
506        let (_state, engine, mut output_rx, _reg_dir, _def_dir) = setup_with_n_cross_channel_agents(1);
507        let store = std::sync::Arc::new(crate::backend::storage::filestore::FileStore::open_in_memory().unwrap());
508        install_transcript(&store, "def-0", r#"{"type":"stream_event","event":{}}"#);
509        crate::backend::agent_session::history_summary::set_test_store(Some(store));
510        let _guard = TranscriptStoreGuard;
511
512        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
513        let result: ListRecentSessionsResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
514        assert_eq!(result.rows.len(), 1);
515        assert!(result.rows[0].has_snapshot);
516        assert_eq!(result.rows[0].preview, "");
517    }
518
519    /// Consolidation Phase 3b (reagent P1 on PR #3080): the row's display
520    /// fields must come from the AGENT's own row, never from the template it
521    /// was launched off. The template is consulted for exactly one thing —
522    /// the legacy-shaped identity-link fallback — and an agent whose
523    /// provider/name/type has since drifted from its template must report its
524    /// own current values, as it did before consolidation.
525    #[tokio::test]
526    async fn a_launched_agents_row_reports_its_own_config_not_its_templates() {
527        let state = test_state();
528        let mut tmpl = local_agent_def("tmpl-drift");
529        tmpl.is_seeded = 1;
530        tmpl.name = "Template".to_string();
531        tmpl.provider = "claude".to_string();
532        tmpl.agent_type = "standalone".to_string();
533        state.mstore.agent_def_insert(&mut tmpl).unwrap();
534
535        let mut own = local_agent_def("agent-drift");
536        own.parent_id = "tmpl-drift".to_string();
537        state.mstore.agent_def_insert(&mut own).unwrap();
538        state
539            .mstore
540            .instance_create(&local_agent_instance("launch-1", "agent-drift", "block-drift"))
541            .unwrap();
542
543        // The agent drifts from the template it was cloned from.
544        own.name = "Renamed by the user".to_string();
545        own.provider = "codex".to_string();
546        own.agent_type = "orchestrator".to_string();
547        state.mstore.agent_def_update(&mut own).unwrap();
548
549        let (engine, mut output_rx) = WshRpcEngine::new();
550        register(&engine, &state);
551        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
552
553        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
554        let result: ListRecentSessionsResult =
555            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
556        assert_eq!(result.rows.len(), 1);
557        let row = &result.rows[0];
558        assert_eq!(row.definition_name, "Renamed by the user");
559        assert_eq!(row.provider, "codex", "the template's 'claude' must not shadow the agent's own provider");
560        assert_eq!(row.agent_type, "orchestrator");
561    }
562
563    /// docs/reports/REPORT_AGENT_PICKER_FIELD_ORDER_SORT_AND_DATA_GAPS_AUDIT_2026_08_24.md
564    /// §5, bullet 1: `filestore.stat()`'s `Err` (I/O error, lock
565    /// contention, DB read failure) used to collapse into the exact same
566    /// branch as `Ok(None)` (genuinely no snapshot) — a transient storage
567    /// error on a row that DOES have real history rendered identically to
568    /// "never had one," with no log line. Forces the failure
569    /// deterministically the same way the identity_links test above does
570    /// (`DROP TABLE`), rather than relying on real I/O flakiness.
571    #[tokio::test]
572    async fn filestore_stat_error_is_distinguished_from_genuinely_no_snapshot() {
573        let state = test_state();
574        let mut def = local_agent_def("def-local-3");
575        state.mstore.agent_def_insert(&mut def).unwrap();
576        state
577            .mstore
578            .instance_create(&local_agent_instance("inst-local-3", "def-local-3", "block-local-3"))
579            .unwrap();
580
581        {
582            let conn = state.filestore.conn().lock().unwrap();
583            conn.execute("DROP TABLE db_wave_file", []).unwrap();
584        }
585
586        let (engine, mut output_rx) = WshRpcEngine::new();
587        register(&engine, &state);
588        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
589
590        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
591        let result: ListRecentSessionsResult =
592            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
593        assert_eq!(result.rows.len(), 1, "a stat() failure on one row must not zero out the whole list");
594        let row = &result.rows[0];
595        assert!(!row.has_snapshot, "a failed stat() is not evidence a snapshot exists");
596        assert!(
597            row.snapshot_check_failed,
598            "a stat() I/O error must be distinguishable from a genuine Ok(None) — \
599             otherwise a transient failure looks identical to \"never had history\""
600        );
601        assert!(
602            result.degraded.contains(&"snapshot_stat".to_string()),
603            "got: {:?}",
604            result.degraded
605        );
606    }
607
608    /// Counterpart: a genuine `Ok(None)` (the block really never wrote a
609    /// snapshot) must NOT set `snapshot_check_failed` — only an actual
610    /// `Err` does. Without this, the fix above could be made to pass by
611    /// setting the flag unconditionally whenever `has_snapshot` is false,
612    /// which would just move the ambiguity rather than remove it.
613    #[tokio::test]
614    async fn genuinely_missing_snapshot_does_not_set_the_check_failed_flag() {
615        let state = test_state();
616        let mut def = local_agent_def("def-local-4");
617        state.mstore.agent_def_insert(&mut def).unwrap();
618        state
619            .mstore
620            .instance_create(&local_agent_instance("inst-local-4", "def-local-4", "block-local-4"))
621            .unwrap();
622
623        let (engine, mut output_rx) = WshRpcEngine::new();
624        register(&engine, &state);
625        let resp = dispatch_list_recent_sessions(&engine, &mut output_rx).await;
626
627        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
628        let result: ListRecentSessionsResult =
629            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
630        let row = &result.rows[0];
631        assert!(!row.has_snapshot);
632        assert!(
633            !row.snapshot_check_failed,
634            "a genuine Ok(None) — the block simply never wrote a snapshot — is not a check failure"
635        );
636    }
637
638    /// reagent P1, PR #2786: without a dedup gate, a definition that can
639    /// never be summarized (no cmd meta, no raw output, CLI failure) gets
640    /// re-spawned on every `listrecentsessions` poll forever —
641    /// `ambient::gateway().admit()` alone only coalesces CONCURRENT
642    /// triggers, not sequential ones, since its guard drops (freeing the
643    /// slot) the moment one call finishes. This tests
644    /// `definition_summary_attempted()`'s claim set directly rather than
645    /// the RPC dispatch (which can't observe whether a background
646    /// `tokio::spawn` happened without mocking the Haiku CLI) — a unique
647    /// id avoids cross-test interference with the process-wide static set.
648    #[test]
649    fn definition_summary_attempted_claims_a_definition_id_at_most_once() {
650        let id = "def-dedup-test-unique-9f3a1b".to_string();
651        assert!(
652            definition_summary_attempted().lock().unwrap().insert(id.clone()),
653            "first claim for a fresh id must succeed"
654        );
655        assert!(
656            !definition_summary_attempted().lock().unwrap().insert(id.clone()),
657            "second claim for the same id must be rejected — this is the fix for \
658             reagent's unbounded-retry finding on PR #2786"
659        );
660    }
661}