Skip to main content

agentmux_srv/server/app_api/
history_agents.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The History pane: `history.agents` lists every agent whose history
5//! the global transcript store holds (`backend::history_registry`), and
6//! `history.agent_sessions` one agent's sessions from its record. The Agent
7//! History view's `history.locate` finds the line to load up to for a time or
8//! a session's end. The window's, not agent APIs: a connection registered as
9//! an agent is refused.
10
11use super::tower_pane::not_an_agent_api;
12use super::*;
13use crate::backend::agent_session::{OUTPUT_FILE, TSIDX_FILE};
14use crate::backend::blockcontroller::shell::{extend_output_idx, lines_before_byte, stamps};
15use crate::backend::history_registry::{self, AgentInfo};
16use crate::backend::storage::filestore::FileStore;
17
18pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
19    let mstore = state.mstore.clone();
20    engine.register_typed(COMMAND_HISTORY_AGENTS, move |_req: HistoryAgentsReq, ctx| {
21        let mstore = mstore.clone();
22        async move {
23            not_an_agent_api(&ctx)?;
24            let Some(store) = crate::backend::agent_session::global_transcript_store().cloned() else {
25                return Err("history.agents: no transcript store".to_string());
26            };
27            tokio::task::spawn_blocking(move || {
28                let defs: std::collections::HashMap<String, AgentInfo> = mstore
29                    .agent_def_list()
30                    .map_err(|e| format!("history.agents: {e}"))?
31                    .into_iter()
32                    // `parent_id` also names the template an agent was made from; only
33                    // a fork has a branch label (`forkagentdefinition`).
34                    .map(|d| {
35                        let fork_of = if d.branch_label.is_empty() { String::new() } else { d.parent_id };
36                        (d.id, AgentInfo { name: d.name, provider: d.provider, fork_of })
37                    })
38                    .collect();
39                let agents = history_registry::agents(&store, |id| defs.get(id).cloned()).map_err(|e| format!("history.agents: {e}"))?;
40                Ok(HistoryAgents { agents })
41            })
42            .await
43            .map_err(|e| format!("history.agents: {e}"))?
44        }
45    });
46
47    let history = state.history_service.clone();
48    engine.register_typed(COMMAND_HISTORY_AGENT_SESSIONS, move |req: HistoryAgentSessionsReq, ctx| {
49        let history = history.clone();
50        async move {
51            not_an_agent_api(&ctx)?;
52            if !crate::backend::agent_session::is_valid_definition_id(&req.definition_id) {
53                return Err(format!("history.agent_sessions: invalid agent id {:?}", req.definition_id));
54            }
55            // The first read of a long record scans it: off the async workers.
56            tokio::task::spawn_blocking(move || history.agent_sessions(&req.definition_id))
57                .await
58                .map_err(|e| format!("history.agent_sessions: {e}"))
59        }
60    });
61
62    let filestore = state.filestore.clone();
63    let global_store = state.global_transcript_store.clone();
64    let mstore = state.mstore.clone();
65    engine.register_typed(COMMAND_HISTORY_LOCATE, move |req: HistoryLocateReq, ctx| {
66        let (filestore, global_store, mstore) = (filestore.clone(), global_store.clone(), mstore.clone());
67        async move {
68            not_an_agent_api(&ctx)?;
69            let source = super::blockfile::history_output_source(
70                &filestore,
71                &global_store,
72                &mstore,
73                &req.block_id,
74                OUTPUT_FILE,
75                req.archive_zone.as_deref(),
76            )?;
77            let (store, zone) = source.unwrap_or_else(|| (filestore.clone(), req.block_id.clone()));
78            tokio::task::spawn_blocking(move || locate(&store, &zone, req.at_ms, req.at_byte))
79                .await
80                .map_err(|e| format!("history.locate: {e}"))?
81        }
82    });
83}
84
85/// The line a reader showing `zone`'s transcript up to `at_byte`, or up to the
86/// last line received at or before `at_ms`, stops at. Neither: the end.
87fn locate(fs: &FileStore, zone: &str, at_ms: Option<u64>, at_byte: Option<u64>) -> Result<HistoryLocation, String> {
88    let size = fs.stat(zone, OUTPUT_FILE).map_err(|e| format!("history.locate: {e}"))?.map_or(0, |f| f.size.max(0) as u64);
89    let byte = match (at_byte, at_ms) {
90        (Some(byte), _) => byte.min(size),
91        (None, Some(ms)) => {
92            let ts_size = fs.stat(zone, TSIDX_FILE).map_err(|e| format!("history.locate: {e}"))?.map_or(0, |f| f.size);
93            // History recorded before the receive-time sidecar existed has no
94            // times: say so, rather than land at the end.
95            if ts_size <= 0 && size > 0 {
96                return Err("history.locate: this conversation has no recorded times; jump to a session instead".to_string());
97            }
98            let read = |off: i64, len: i64| fs.read_at(zone, TSIDX_FILE, off, len).map(|(_, data)| Some(data));
99            stamps::byte_after_time(&read, ts_size, ms as i64)
100                .map_err(|e| format!("history.locate: {e}"))?
101                .ok_or_else(|| "history.locate: the timestamps can't be read yet".to_string())?
102                .unwrap_or(size)
103        }
104        (None, None) => size,
105    };
106    // The index is a cache of `output`: bring it up to date first.
107    extend_output_idx(fs, zone);
108    let (line, total) = lines_before_byte(fs, zone, byte).ok_or_else(|| "history.locate: the line index isn't ready; try again".to_string())?;
109    Ok(HistoryLocation { line, total })
110}
111
112#[cfg(test)]
113#[path = "history_agents_tests.rs"]
114mod tests;