1use std::collections::{HashMap, HashSet};
14use std::path::Path;
15use std::sync::Arc;
16
17use super::super::account_label::{self, AccountLine};
18use super::super::read_session_preview;
19use super::definition_summary_attempted;
20use crate::backend::agent_session::history_summary::{self, AgentHistory, HistoryRead};
21use crate::backend::mps::Broker;
22use crate::backend::rpc_types::{CommandListRecentSessionsData, ListRecentSessionsResult, RecentSessionRow};
23use crate::backend::storage::filestore::FileStore;
24use crate::backend::storage::store::{AgentDefinition, AgentIdentityLink, AgentInstance, Bundle, IdentityAccount, Store};
25use crate::registry::{NamedAgentRecord, NamedAgentRecordV1, Registry};
26
27const DEFAULT_LIMIT: usize = 20;
28const MAX_LIMIT: usize = 100;
29
30pub(super) type DegradedSources = Vec<&'static str>;
32
33#[derive(Clone)]
35pub(super) struct RecentSessionsDeps {
36 pub mstore: Arc<Store>,
37 pub id_store: Arc<Store>,
38 pub identity_store: Arc<Store>,
39 pub filestore: Arc<FileStore>,
40 pub broker: Arc<Broker>,
41}
42
43pub(super) fn request_limits(requested: usize) -> (usize, usize) {
46 let limit = if requested == 0 { DEFAULT_LIMIT } else { requested.min(MAX_LIMIT) };
47 (limit, (limit * 10).max(50).min(500))
48}
49
50fn identity_filter(cmd: &CommandListRecentSessionsData) -> Option<&str> {
51 cmd.identity_id.as_deref().map(|s| s.trim()).filter(|s| !s.is_empty())
52}
53
54pub(super) async fn list_recent_sessions(
55 deps: &RecentSessionsDeps,
56 data: serde_json::Value,
57) -> Result<ListRecentSessionsResult, String> {
58 let t0 = std::time::Instant::now();
59 let cmd: CommandListRecentSessionsData = serde_json::from_value(data).unwrap_or_default();
61 let (limit, raw_limit) = request_limits(cmd.limit);
62 let mut degraded: DegradedSources = Vec::new();
63
64 let instances = load_instances(&deps.mstore, raw_limit, identity_filter(&cmd), &mut degraded);
65 let sources = load_sources(deps, &mut degraded);
66 let account_names = account_label::names_by_id(&sources.accounts, &sources.mirror_accounts);
67 let links_by_agent = group_links(&sources.links);
68 let degraded_lookups = account_label::Degraded {
69 links: degraded.contains(&"identity_links"),
70 accounts: degraded.contains(&"accounts") && (sources.mirror_failed || sources.mirror_accounts.is_empty()),
71 };
72
73 let histories =
77 history_summary::read_histories(instances.iter().map(|i| i.definition_id.clone()).collect()).await;
78 if histories.values().any(|h| matches!(h, HistoryRead::Failed)) {
79 degraded.push("transcript");
80 }
81
82 let mut unresolved_links = 0usize;
83 let mut rows: Vec<RecentSessionRow> = Vec::with_capacity(instances.len());
84 for inst in instances {
85 let def = sources.defs.iter().find(|d| d.id == inst.definition_id);
86 let line = account_line_for(&inst, def, &sources.defs, &links_by_agent, &account_names, degraded_lookups);
87 unresolved_links += line.unresolved;
88 let memory_name = memory_name(&inst, &sources.memories);
89 let mut activity = activity_from_transcript(&inst, histories.get(&inst.definition_id), &deps.filestore)
90 .unwrap_or_else(|| activity_from_snapshot(&inst, &deps.filestore, &mut degraded));
91 fill_preview_from_summary(deps, &inst, def, &mut activity, &mut degraded);
92 rows.push(build_row(&deps.mstore, &sources.defs, inst, def, line.text, memory_name, activity));
93 }
94
95 sort_recent_first(&mut rows);
96 rows.truncate(limit);
97
98 tracing::info!(
100 rows = rows.len(),
101 degraded = ?degraded,
102 unresolved_account_links = unresolved_links,
105 elapsed_ms = t0.elapsed().as_millis() as u64,
106 "listrecentsessions: completed"
107 );
108
109 Ok(ListRecentSessionsResult { rows, degraded: degraded.iter().map(|s| s.to_string()).collect() })
112}
113
114fn load_instances(
120 mstore: &Store,
121 raw_limit: usize,
122 identity_filter: Option<&str>,
123 degraded: &mut DegradedSources,
124) -> Vec<AgentInstance> {
125 match mstore.shared_agent_registry() {
126 Some(reg) => registry_instances(mstore, ®, raw_limit, identity_filter, degraded),
127 None => mstore.instance_list_named(raw_limit, None, identity_filter, true).unwrap_or_else(|e| {
128 tracing::warn!(
129 error = %e,
130 "listrecentsessions: local instance_list_named failed \
131 (no shared registry attached) — degrading to empty list"
132 );
133 degraded.push("local_instances");
134 Vec::new()
135 }),
136 }
137}
138
139fn registry_instances(
143 mstore: &Store,
144 reg: &Registry,
145 raw_limit: usize,
146 identity_filter: Option<&str>,
147 degraded: &mut DegradedSources,
148) -> Vec<AgentInstance> {
149 let agents_root = mstore.registry_agents_base();
150 let records = reg.list_active().unwrap_or_else(|e| {
151 tracing::warn!(
152 error = %e,
153 "listrecentsessions: registry list_active failed — \
154 degrading to local-only instances for this call"
155 );
156 degraded.push("registry");
157 Vec::new()
158 });
159 let records = newest_launch_per_agent(records, identity_filter, raw_limit);
160 let local = mstore.instance_list_named(raw_limit, None, identity_filter, true).unwrap_or_else(|e| {
163 tracing::warn!(
164 error = %e,
165 "listrecentsessions: local instance_list_named failed — \
166 degrading to registry-only instances for this call"
167 );
168 degraded.push("local_instances");
169 Vec::new()
170 });
171 let local_by_key = newest_local_by_key(local);
172 let mut out: Vec<AgentInstance> = records
173 .into_iter()
174 .map(|rec| overlay_or_synthesize(rec.data, &local_by_key, agents_root.as_deref()))
175 .collect();
176 append_local_only(&mut out, local_by_key);
177 out
178}
179
180pub(super) fn newest_launch_per_agent(
184 mut records: Vec<NamedAgentRecord>,
185 identity_filter: Option<&str>,
186 raw_limit: usize,
187) -> Vec<NamedAgentRecord> {
188 if let Some(idf) = identity_filter {
189 records.retain(|r| r.data.identity_id.as_deref() == Some(idf));
190 }
191 records.sort_by(|a, b| {
192 a.data
193 .definition_id
194 .cmp(&b.data.definition_id)
195 .then_with(|| a.data.instance_name.cmp(&b.data.instance_name))
196 .then_with(|| b.data.last_launched_at_ms.cmp(&a.data.last_launched_at_ms))
197 });
198 records.dedup_by(|a, b| a.data.definition_id == b.data.definition_id && a.data.instance_name == b.data.instance_name);
199 records.sort_by(|a, b| b.data.last_launched_at_ms.cmp(&a.data.last_launched_at_ms));
200 records.truncate(raw_limit);
201 records
202}
203
204pub(super) type AgentKey = (String, String);
205
206pub(super) fn newest_local_by_key(local: Vec<AgentInstance>) -> HashMap<AgentKey, AgentInstance> {
209 let mut local_by_key: HashMap<AgentKey, AgentInstance> = HashMap::new();
210 for li in local {
211 let key = (li.definition_id.clone(), li.instance_name.clone());
212 match local_by_key.get(&key) {
213 Some(e) if e.started_at >= li.started_at => {}
214 _ => {
215 local_by_key.insert(key, li);
216 }
217 }
218 }
219 local_by_key
220}
221
222fn overlay_or_synthesize(
224 d: NamedAgentRecordV1,
225 local_by_key: &HashMap<AgentKey, AgentInstance>,
226 agents_root: Option<&Path>,
227) -> AgentInstance {
228 let key = (d.definition_id.clone(), d.instance_name.clone());
229 match local_by_key.get(&key) {
230 Some(li) => with_registry_session_id(li, d.session_id.as_deref()),
231 None => synthesized_instance(d, agents_root),
232 }
233}
234
235pub(super) fn with_registry_session_id(local: &AgentInstance, registry_session_id: Option<&str>) -> AgentInstance {
239 if local.session_id.is_empty() {
240 if let Some(sid) = registry_session_id.filter(|s| !s.is_empty()) {
241 let mut merged = local.clone();
242 merged.session_id = sid.to_string();
243 return merged;
244 }
245 }
246 local.clone()
247}
248
249pub(super) fn synthesized_instance(d: NamedAgentRecordV1, agents_root: Option<&Path>) -> AgentInstance {
252 let working_directory = match d.source_agents_base.as_deref() {
253 Some(src) => Path::new(src).join(&d.working_dir).to_string_lossy().to_string(),
254 None => match agents_root {
255 Some(root) => root.join(&d.working_dir).to_string_lossy().to_string(),
256 None => d.working_dir.clone(),
257 },
258 };
259 AgentInstance {
260 id: d.instance_id,
261 definition_id: d.definition_id,
262 parent_instance_id: String::new(),
263 block_id: String::new(),
264 session_id: d.session_id.unwrap_or_default(),
265 status: "available".to_string(),
266 github_context: String::new(),
267 started_at: d.last_launched_at_ms,
268 ended_at: 0,
269 created_at: d.created_at_ms,
270 identity_id: d.identity_id.unwrap_or_default(),
271 memory_id: d.memory_id.unwrap_or_default(),
272 instance_name: d.instance_name,
273 working_directory,
274 display_hidden: false,
275 }
276}
277
278pub(super) fn append_local_only(out: &mut Vec<AgentInstance>, local_by_key: HashMap<AgentKey, AgentInstance>) {
280 let have_keys: HashSet<AgentKey> =
281 out.iter().map(|i| (i.definition_id.clone(), i.instance_name.clone())).collect();
282 for (key, li) in local_by_key {
283 if !have_keys.contains(&key) {
284 out.push(li);
285 }
286 }
287}
288
289struct PickerSources {
293 defs: Vec<AgentDefinition>,
294 links: Vec<AgentIdentityLink>,
295 accounts: Vec<IdentityAccount>,
296 mirror_accounts: Vec<IdentityAccount>,
299 mirror_failed: bool,
300 memories: Vec<Bundle>,
301}
302
303fn load_sources(deps: &RecentSessionsDeps, degraded: &mut DegradedSources) -> PickerSources {
304 let mut defs = deps.mstore.agent_def_list().unwrap_or_else(|e| {
305 tracing::warn!(
306 error = %e,
307 "listrecentsessions: agent_def_list failed — degrading to empty \
308 (rows will show \"(missing definition)\")"
309 );
310 degraded.push("agent_defs");
311 Vec::new()
312 });
313 let known: HashSet<String> = defs.iter().map(|d| d.id.clone()).collect();
316 defs.extend(deps.mstore.agent_def_unreadable_stand_ins().into_iter().filter(|d| !known.contains(&d.id)));
317 let links = deps.identity_store.agent_identity_list_all().unwrap_or_else(|e| {
320 tracing::warn!(
321 error = %e,
322 "listrecentsessions: agent_identity_list_all failed — degrading to \
323 empty (rows will show no account line)"
324 );
325 degraded.push("identity_links");
326 Vec::new()
327 });
328 let accounts = deps.id_store.identity_list(None).unwrap_or_else(|e| {
329 tracing::warn!(
331 error = %e,
332 "listrecentsessions: identity_list failed — degrading to empty \
333 (the global mirror fills in what it can; a link it cannot resolve shows no account line)"
334 );
335 degraded.push("accounts");
336 Vec::new()
337 });
338 let own_ids: HashSet<&str> = accounts.iter().map(|a| a.id.as_str()).collect();
339 let mut mirror_failed = false;
340 let mirror_accounts: Vec<IdentityAccount> = if links.iter().any(|l| !own_ids.contains(l.account_id.as_str())) {
341 deps.identity_store.identity_list(None).unwrap_or_else(|e| {
342 tracing::warn!(error = %e, "listrecentsessions: the global account mirror could not be read");
343 mirror_failed = true;
344 Vec::new()
345 })
346 } else {
347 Vec::new()
348 };
349 let memories = deps.id_store.bundle_list().unwrap_or_else(|e| {
350 tracing::warn!(
351 error = %e,
352 "listrecentsessions: bundle_list failed — degrading to empty \
353 (rows will show \"(missing memory)\")"
354 );
355 degraded.push("memories");
356 Vec::new()
357 });
358 PickerSources { defs, links, accounts, mirror_accounts, mirror_failed, memories }
359}
360
361pub(super) fn group_links(links: &[AgentIdentityLink]) -> HashMap<&str, Vec<&AgentIdentityLink>> {
362 let mut by_agent: HashMap<&str, Vec<&AgentIdentityLink>> = HashMap::new();
363 for link in links {
364 by_agent.entry(link.agent_id.as_str()).or_default().push(link);
365 }
366 by_agent
367}
368
369fn account_line_for(
374 inst: &AgentInstance,
375 def: Option<&AgentDefinition>,
376 defs: &[AgentDefinition],
377 links_by_agent: &HashMap<&str, Vec<&AgentIdentityLink>>,
378 account_names: &HashMap<&str, &str>,
379 degraded_lookups: account_label::Degraded,
380) -> AccountLine {
381 let template = def.filter(|d| !d.parent_id.is_empty()).and_then(|d| defs.iter().find(|t| t.id == d.parent_id));
383 let links_key = match links_by_agent.get(inst.definition_id.as_str()) {
384 Some(_) => inst.definition_id.as_str(),
385 None => template.map(|t| t.id.as_str()).unwrap_or(inst.definition_id.as_str()),
386 };
387 account_label::account_line(links_by_agent.get(links_key).map(|v| v.as_slice()), account_names, degraded_lookups)
388}
389
390pub(super) fn memory_name(inst: &AgentInstance, memories: &[Bundle]) -> String {
391 if inst.memory_id.is_empty() {
392 return "(vanilla CLI)".to_string();
393 }
394 memories
395 .iter()
396 .find(|m| m.id == inst.memory_id)
397 .map(|m| m.name.clone())
398 .unwrap_or_else(|| "(missing memory)".to_string())
399}
400
401pub(super) struct Activity {
405 pub(super) has_snapshot: bool,
406 pub(super) last_active_at: i64,
407 pub(super) preview: String,
408 pub(super) node_count: usize,
409 pub(super) snapshot_check_failed: bool,
410}
411
412impl Activity {
413 fn none(started_at: i64) -> Self {
415 Activity { has_snapshot: false, last_active_at: started_at, preview: String::new(), node_count: 0, snapshot_check_failed: false }
416 }
417
418 fn check_failed(started_at: i64) -> Self {
420 Activity { snapshot_check_failed: true, ..Self::none(started_at) }
421 }
422}
423
424fn transcript_activity(h: &AgentHistory, started_at: i64) -> Activity {
427 Activity {
428 has_snapshot: true,
429 last_active_at: if h.last_activity_ms > 0 { h.last_activity_ms } else { started_at },
430 preview: h.last_user_message.clone(),
431 node_count: 0,
432 snapshot_check_failed: false,
433 }
434}
435
436pub(super) fn activity_from_transcript(inst: &AgentInstance, read: Option<&HistoryRead>, filestore: &FileStore) -> Option<Activity> {
439 match read {
440 Some(HistoryRead::Transcript(h)) => Some(transcript_activity(h, inst.started_at)),
441 Some(HistoryRead::Failed) => Some(Activity::check_failed(inst.started_at)),
442 Some(HistoryRead::Damaged) if inst.block_id.is_empty() => None,
445 Some(HistoryRead::Damaged) => match history_summary::read_block_history(filestore, &inst.block_id) {
446 HistoryRead::Transcript(h) => Some(transcript_activity(&h, inst.started_at)),
447 HistoryRead::NoTranscript => None,
448 HistoryRead::Failed | HistoryRead::Damaged => Some(Activity::check_failed(inst.started_at)),
449 },
450 Some(HistoryRead::NoTranscript) | None => None,
451 }
452}
453
454pub(super) fn activity_from_snapshot(inst: &AgentInstance, filestore: &FileStore, degraded: &mut DegradedSources) -> Activity {
459 if inst.block_id.is_empty() {
460 return Activity::none(inst.started_at);
461 }
462 match filestore.stat(&inst.block_id, "output.state.json") {
463 Ok(Some(file)) => {
464 let modts = if file.modts > 0 { file.modts } else { inst.started_at };
465 let (preview, node_count) = read_session_preview(filestore, &inst.block_id);
466 Activity { has_snapshot: true, last_active_at: modts, preview, node_count, snapshot_check_failed: false }
467 }
468 Ok(None) => Activity::none(inst.started_at),
469 Err(e) => {
470 tracing::warn!(
471 error = %e,
472 definition_id = %inst.definition_id,
473 block_id = %inst.block_id,
474 "listrecentsessions: filestore.stat(output.state.json) failed — \
475 row will report snapshot_check_failed instead of silently \
476 looking like it never had a snapshot"
477 );
478 if !degraded.contains(&"snapshot_stat") {
479 degraded.push("snapshot_stat");
480 }
481 Activity::check_failed(inst.started_at)
482 }
483 }
484}
485
486fn fill_preview_from_summary(
491 deps: &RecentSessionsDeps,
492 inst: &AgentInstance,
493 def: Option<&AgentDefinition>,
494 activity: &mut Activity,
495 degraded: &mut DegradedSources,
496) {
497 if activity.has_snapshot || inst.block_id.is_empty() {
498 return;
499 }
500 match deps.mstore.agent_activity_summary_get(&inst.definition_id) {
501 Ok(Some(existing)) if !existing.summary.is_empty() => {
502 activity.preview = existing.summary;
503 }
504 Ok(None) | Ok(Some(_)) if definition_summary_attempted().lock().unwrap().insert(inst.definition_id.clone()) => {
510 spawn_definition_summary(deps, inst, def);
511 }
512 Ok(None) | Ok(Some(_)) => {}
513 Err(e) => {
514 tracing::warn!(
515 error = %e,
516 definition_id = %inst.definition_id,
517 "listrecentsessions: agent_activity_summary_get failed — \
518 row keeps its plain fallback preview text"
519 );
520 if !degraded.contains(&"activity_summary") {
521 degraded.push("activity_summary");
522 }
523 }
524 }
525}
526
527fn spawn_definition_summary(deps: &RecentSessionsDeps, inst: &AgentInstance, def: Option<&AgentDefinition>) {
530 let mstore = deps.mstore.clone();
531 let filestore = deps.filestore.clone();
532 let broker = deps.broker.clone();
533 let definition_id = inst.definition_id.clone();
534 let block_id = inst.block_id.clone();
535 let provider_id = def.map(|d| d.provider.clone()).unwrap_or_default();
536 tokio::spawn(async move {
537 let result = crate::ambient::tasks::generate_definition_activity_summary(
538 &mstore,
539 &filestore,
540 &broker,
541 &definition_id,
542 &block_id,
543 &provider_id,
544 )
545 .await;
546 if let Some(generated) = result {
547 if let Some(tokens) = generated.tokens {
548 tracing::debug!(
549 definition_id = %definition_id,
550 ?tokens,
551 "listrecentsessions: definition activity summary generated"
552 );
553 }
554 }
555 });
556}
557
558pub(super) fn handover_of(mstore: &Store, definition_id: &str) -> Option<crate::backend::rpc_types::HandoverSummary> {
562 crate::backend::agent_runtime_state::handover_summary(mstore, definition_id)
563}
564
565fn build_row(
566 mstore: &Store,
567 defs: &[AgentDefinition],
568 inst: AgentInstance,
569 def: Option<&AgentDefinition>,
570 identity_name: String,
571 memory_name: String,
572 activity: Activity,
573) -> RecentSessionRow {
574 let seat = crate::backend::agent_seat::summary_in(mstore, defs, &inst.definition_id);
575 let handover = handover_of(mstore, &inst.definition_id);
576 let needs_key = crate::backend::model_gateway::pending_route::pending_of(mstore, &inst.definition_id).map(|p| p.key_label);
577 RecentSessionRow {
578 instance_id: inst.id,
579 instance_name: inst.instance_name,
580 definition_id: inst.definition_id.clone(),
581 definition_name: def.map(|d| d.name.clone()).unwrap_or_else(|| "(missing definition)".to_string()),
582 provider: def.map(|d| d.provider.clone()).unwrap_or_default(),
583 model_vendor_base_url: def.map(|d| d.model_vendor_base_url.clone()).unwrap_or_default(),
584 working_directory: inst.working_directory,
585 identity_id: inst.identity_id,
586 identity_name,
587 memory_id: inst.memory_id,
588 memory_name,
589 block_id_hint: inst.block_id,
590 session_id: inst.session_id,
593 preview: activity.preview,
594 node_count: activity.node_count,
595 last_active_at: activity.last_active_at,
596 has_snapshot: activity.has_snapshot,
597 snapshot_check_failed: activity.snapshot_check_failed,
598 agent_created_at: def.map(|d| d.created_at).unwrap_or(0),
599 started_at: inst.started_at,
600 agent_type: def.map(|d| d.agent_type.clone()).unwrap_or_default(),
601 seat,
602 handover,
603 needs_key,
604 }
605}
606
607pub(super) fn sort_recent_first(rows: &mut [RecentSessionRow]) {
610 rows.sort_by(|a, b| match (a.has_snapshot, b.has_snapshot) {
611 (true, true) | (false, false) => b.last_active_at.cmp(&a.last_active_at),
612 (true, false) => std::cmp::Ordering::Less,
613 (false, true) => std::cmp::Ordering::Greater,
614 });
615}