Skip to main content

agentmux_srv/server/agent_handlers/session/
recent.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `listrecentsessions`, moved out of `register` unchanged as named steps. It joins the agents the shared
5//! registry knows with this channel's own instances, enriches each with its definition, account line, memory
6//! and last activity, and answers the picker's "My Agents" list. The cascade follow-up (2026-05-23) added it;
7//! the reattach itself is the existing continuation flow (`continueOfInstanceId` + `workDirOverride`, PR #977).
8//!
9//! Every data source degrades to empty on its own failure and is named in the reply's `degraded` list, so one
10//! bad row cannot blank the whole list (the My Agents regression of 2026-07-27, PR #2296's oauth serde-tag
11//! mismatch) and a caller can tell "no agents" from "a source failed".
12
13use 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
30/// The data sources that fell back to empty during one call, by name.
31pub(super) type DegradedSources = Vec<&'static str>;
32
33/// What the handler reads, cloned into the registered closure.
34#[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
43/// The rows asked for (0 means the default, and the most is 100), and how many candidates to pull so that
44/// filtering by snapshot and identity does not run out: ten times the rows, within 50 to 500.
45pub(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    // A malformed request means the defaults.
60    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    // What each agent was last asked comes from its global transcript (keyed by agent id), not from this
74    // channel's per-block snapshot, so a closed pane, an agent never launched here and a registry-only row all
75    // get a real preview.
76    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    // The completion trace: whether the call ran, how long it took, and which sources fell back to empty.
99    tracing::info!(
100        rows = rows.len(),
101        degraded = ?degraded,
102        // Links to an account this store cannot find (deleted, or an unparseable secret_ref skipped by
103        // identity_list): those agents show "No auth", and this says how many.
104        unresolved_account_links = unresolved_links,
105        elapsed_ms = t0.elapsed().as_millis() as u64,
106        "listrecentsessions: completed"
107    );
108
109    // `degraded` reaches the caller too: with every source degrading to empty instead of erroring the RPC, a
110    // transport-level success no longer tells "genuinely zero agents" from "a source failed".
111    Ok(ListRecentSessionsResult { rows, degraded: degraded.iter().map(|s| s.to_string()).collect() })
112}
113
114// ── Which agents ───────────────────────────────────────────────────────────
115
116/// The agents to list. "My Agents" sources from the cross-version registry when there is one, so agents made in
117/// any build, channel or version appear, not only this instance's local sessions; without a registry (CI, odd
118/// environments) it is this channel's own instances.
119fn 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, &reg, 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
139/// The registry's agents, each replaced by this channel's own instance of it when there is one, plus the local
140/// agents no registry record represents (made before the live mirror could register them, or orphan
141/// continuations whose head was deleted).
142fn 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    // Local agents in picker mode (include_continuations): each chain collapses to one row, and an orphan
161    // continuation surfaces as its own root, so it does not vanish from "My Agents".
162    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
180/// The records of the identity asked for (when one is), one per (definition, name) keeping the newest launch
181/// (the registry read path lacks SQLite's chain-root collapse, so two fresh heads of one agent would double up),
182/// newest first, at most `raw_limit`.
183pub(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
206/// This channel's instances by (definition id, instance name), the same key the registry dedup uses, keeping the
207/// newest, so the overlay and the local-only append agree on identity.
208pub(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
222/// The local instance when this channel has one (the fresher source), else an instance made from the record.
223fn 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
235/// The local row, with the registry's session id when the local one is empty rather than an empty id the
236/// picker's reattach would read as "start fresh" (SPEC_PANE_CLOSE_REOPEN_CONTINUITY_GUARANTEE_2026_07_27.md
237/// §4.1). The local row is normally fresher, but this holds for a row that predates the live write or raced it.
238pub(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
249/// A cross-channel row: no live block, and its workdir rebuilt from the record's source base (v3) or this
250/// channel's agents base (legacy).
251pub(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
278/// The local agents whose (definition, name) no registry row represents, appended after the registry's.
279pub(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
289// ── What each row shows ────────────────────────────────────────────────────
290
291/// What the rows are enriched from, each read once for the whole call.
292struct PickerSources {
293    defs: Vec<AgentDefinition>,
294    links: Vec<AgentIdentityLink>,
295    accounts: Vec<IdentityAccount>,
296    /// The global account mirror, read only when a link points at an account this channel's store does not hold
297    /// (an isolated channel).
298    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    // An agent whose definition this build cannot read still has its name here, so its row is not "(missing definition)": a
314    // start says why it cannot be opened.
315    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    // Identity names resolve off the direct agent<->account links (db_agent_identity_links, db_accounts), bulk
318    // fetched once and grouped by agent rather than queried per row.
319    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        // The call PR #2296 broke: it now degrades in isolation instead of aborting the handler.
330        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
369/// The agent's own account links, falling back to its template's. A launch-only agent can hold a link of its
370/// own (the FK targets `db_agents` since Phase 3c, #3088), but nothing writes one there yet: the only binding UI
371/// targets a template or user agent's own definition id. Until a launch-scoped binding path exists, dropping the
372/// fallback would make a launched agent's identity disappear (retire it with Phase 3d).
373fn 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    // The template it came from (empty `parent_id` for an agent never cloned from one), used only here.
382    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
401// ── Last activity ──────────────────────────────────────────────────────────
402
403/// When an agent was last active and what it was last asked: from its transcript, else this channel's snapshot.
404pub(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    /// Nothing to show: the launch time stands in for the last activity.
414    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    /// The read failed, which the row reports instead of looking like an agent with no history.
419    fn check_failed(started_at: i64) -> Self {
420        Activity { snapshot_check_failed: true, ..Self::none(started_at) }
421    }
422}
423
424/// `node_count` is 0: counting messages would mean reading the whole transcript, so the tile shows none rather
425/// than a guess.
426fn 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
436/// The agent's global transcript, keyed by its id. None when there is none to use, so the per-block snapshot,
437/// which old builds wrote, answers instead.
438pub(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        // The agent's zone in the shared store is corrupt (`transcript::damage`): this channel's own copy of the
443        // conversation, kept under the pane's block id, answers.
444        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
454/// This channel's per-block snapshot: a stat first (cheap, and it gives the sort time), the content only when it
455/// exists. `Ok(None)` (the block never wrote one) and `Err` (a filestore I/O error) are different rows: a real
456/// error on an agent that does have history must not read as "never had one"
457/// (REPORT_AGENT_PICKER_FIELD_ORDER_SORT_AND_DATA_GAPS_AUDIT_2026_08_24.md §5).
458pub(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
486/// No structured snapshot to preview: use the agent's persisted summary, or ask for one once per definition per
487/// process (a Haiku summary of its raw terminal output, REPORT_AGENT_PICKER_FIELD_ORDER_SORT_AND_DATA_GAPS_AUDIT
488/// §5a). Only for a local row with a real block: a cross-channel row has no local raw output, and keeps the
489/// plain fallback text, which is accurate for it.
490fn 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        // `insert` is true only the first time a definition is claimed in this process (as
505        // `SubagentWatcher.naming_triggered` does, #2786): the ambient gateway's `admit` only
506        // coalesces concurrent triggers, so without it a definition that can never be summarized would be
507        // re-spawned on every later call. A successful summary persists and is found by the arm above. A stored
508        // row with an empty summary is treated as none.
509        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
527/// Fire and forget: a real Haiku CLI round trip must not block the response. Its spend is logged and no more:
528/// no UI total exists for any background ambient call (#2786).
529fn 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
558// ── The row, and the order ─────────────────────────────────────────────────
559
560/// Where the agent went, when it carries a hand-over mark (the same answer its runtime row gives).
561pub(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        // The CLI-captured session id, so the picker's reattach can `--resume <sid>` on the first turn of the new
591        // block; without it the new subprocess starts a fresh session and the CLI re-injects the startup context.
592        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
607/// Rows with a snapshot first (newest activity first), then the rest by launch time, so live conversations stay
608/// on top while legacy rows still surface.
609pub(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}