1use 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
22fn 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 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 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 #[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 #[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 {
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 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 #[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 #[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 #[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 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 #[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 #[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 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 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 #[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 #[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 #[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 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 #[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 #[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 #[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}