Skip to main content

agentmux_srv/server/agent_handlers/
history.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    COMMAND_APPEND_AGENT_HISTORY, COMMAND_LIST_AGENT_HISTORY, COMMAND_SEARCH_AGENT_HISTORY,
11    CommandAppendAgentHistoryData, CommandListAgentHistoryData, CommandSearchAgentHistoryData,
12};
13
14use super::super::actor::require_own_transcript;
15use super::super::AppState;
16
17pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
18    // appendagenthistory → append a history entry, broadcast agenthistory:changed
19    let mstore_afh = state.mstore.clone();
20    let broker_afh = state.broker.clone();
21    engine.register_typed(
22        COMMAND_APPEND_AGENT_HISTORY,
23        move |cmd: CommandAppendAgentHistoryData, ctx| {
24            let mstore = mstore_afh.clone();
25            let broker = broker_afh.clone();
26            async move {
27                require_own_transcript(&ctx, &mstore, &cmd.agent_id, "an agent's history")?;
28                let entry = mstore.agent_history_append(&cmd.agent_id, &cmd.entry)
29                    .map_err(|e| format!("appendagenthistory: {e}"))?;
30                broker.publish_event::<crate::backend::mps_events::AgentHistoryChanged>(&(), vec![], 0);
31                Ok(entry)
32            }
33        },
34    );
35
36    // listagenthistory → return history entries with pagination
37    let mstore_lfh = state.mstore.clone();
38    engine.register_typed(
39        COMMAND_LIST_AGENT_HISTORY,
40        move |cmd: CommandListAgentHistoryData, _ctx| {
41            let mstore = mstore_lfh.clone();
42            async move {
43                let entries = mstore.agent_history_list(
44                    &cmd.agent_id,
45                    cmd.session_date.as_deref(),
46                    cmd.limit,
47                    cmd.offset,
48                ).map_err(|e| format!("listagenthistory: {e}"))?;
49                Ok(entries)
50            }
51        },
52    );
53
54    // searchagenthistory → search history entries by query
55    let mstore_sfh = state.mstore.clone();
56    engine.register_typed(
57        COMMAND_SEARCH_AGENT_HISTORY,
58        move |cmd: CommandSearchAgentHistoryData, _ctx| {
59            let mstore = mstore_sfh.clone();
60            async move {
61                let entries = mstore.agent_history_search(&cmd.agent_id, &cmd.query, cmd.limit)
62                    .map_err(|e| format!("searchagenthistory: {e}"))?;
63                Ok(entries)
64            }
65        },
66    );
67
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use crate::backend::rpc_types::{CommandListAgentHistoryData, CommandSearchAgentHistoryData};
74
75    /// All three history commands record their request and response types.
76    #[tokio::test]
77    async fn register_typed_records_every_history_command() {
78        let state = crate::server::tests::test_state();
79        let (engine, _rx) = WshRpcEngine::new();
80        register(&engine, &state);
81        let schema = engine.schema_json();
82        let rows = schema.as_array().unwrap();
83        let find = |cmd: &str| {
84            rows.iter()
85                .find(|r| r["command"] == cmd)
86                .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
87        };
88
89        let append = find(COMMAND_APPEND_AGENT_HISTORY);
90        assert_eq!(append["requestName"], "CommandAppendAgentHistoryData");
91        assert_eq!(append["responseName"], "AgentHistory");
92
93        for (cmd, req) in [
94            (COMMAND_LIST_AGENT_HISTORY, "CommandListAgentHistoryData"),
95            (COMMAND_SEARCH_AGENT_HISTORY, "CommandSearchAgentHistoryData"),
96        ] {
97            let row = find(cmd);
98            assert_eq!(row["requestName"], req, "{cmd} request");
99            let resp = row["responseName"].as_str().unwrap();
100            assert!(
101                resp.starts_with("alloc::vec::Vec<") && resp.contains("AgentHistory"),
102                "{cmd} should answer Vec<AgentHistory>, got {resp:?}",
103            );
104        }
105    }
106
107    /// The pagination fields are `serde(default)` on `i64`, which ts-rs cannot
108    /// mark optional -- the stubs derive `ListAgentHistoryInput` /
109    /// `SearchAgentHistoryInput` to restore it. Pin the server half: drop a
110    /// default and those derived TS types become a lie.
111    #[test]
112    fn the_pagination_fields_may_be_omitted() {
113        let list: CommandListAgentHistoryData =
114            serde_json::from_value(serde_json::json!({ "agent_id": "a1" }))
115                .expect("limit and offset are both defaulted");
116        assert_eq!(list.limit, 50, "listagenthistory defaults limit to 50");
117        assert_eq!(list.offset, 0);
118        assert!(list.session_date.is_none());
119
120        let search: CommandSearchAgentHistoryData =
121            serde_json::from_value(serde_json::json!({ "agent_id": "a1", "query": "x" }))
122                .expect("limit is defaulted");
123        assert_eq!(search.limit, 50, "searchagenthistory shares the same default");
124    }
125}