1use super::*;
10use crate::backend::storage::agent_input_history::ForgottenBy;
11
12const DEFAULT_LIMIT: u32 = 200;
13const MAX_LIMIT: u32 = 500;
14const KINDS: [&str; 3] = ["message", "slash", "bang"];
15
16fn item(e: crate::backend::storage::agent_input_history::InputHistoryEntry) -> InputHistoryItem {
17 InputHistoryItem {
18 id: e.id,
19 agent_id: e.agent_id,
20 sent_at_ms: e.sent_at_ms,
21 text: e.text,
22 kind: e.kind,
23 source: e.source,
24 sends: e.sends,
25 }
26}
27
28fn kept_per_agent(state: &AppState) -> usize {
31 let extra = state.config_watcher.get_settings().extra;
32 extra.get("agent:inputhistory:max").and_then(|v| v.as_u64()).unwrap_or(10000) as usize
33}
34
35static BACKFILLING: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());
38
39fn maybe_backfill(state: &AppState, agent_id: &str) {
45 let max = kept_per_agent(state);
46 if max == 0 || state.mstore.input_history_backfilled(agent_id).unwrap_or(true) {
47 return;
48 }
49 if !BACKFILLING.lock().unwrap_or_else(|e| e.into_inner()).insert(agent_id.to_string()) {
50 return;
51 }
52 let (state, agent_id) = (state.clone(), agent_id.to_string());
53 tokio::spawn(async move {
54 let (s, id) = (state.clone(), agent_id.clone());
55 let filled = tokio::task::spawn_blocking(move || -> Result<usize, String> {
56 let Some(row) = s.mstore.agent_def_get(&id).map_err(|e| e.to_string())? else { return Ok(0) };
57 let owner = crate::backend::history::HistoryOwner::of_row(&row);
58 let typed = s.history_service.typed_by_user(&owner, max).map_err(|e| e.to_string())?;
59 s.mstore
60 .input_history_backfill(&id, &typed, max, agentmux_common::time::now_ms())
61 .map_err(|e| e.to_string())
62 })
63 .await;
64 BACKFILLING.lock().unwrap_or_else(|e| e.into_inner()).remove(&agent_id);
65 match filled {
66 Ok(Ok(0)) => {}
67 Ok(Ok(n)) => {
68 tracing::info!(agent_id = %agent_id, entries = n, "input history: filled from past conversations");
69 changed(&state, &agent_id, "backfill");
70 }
71 Ok(Err(e)) => tracing::warn!(agent_id = %agent_id, error = %e, "input history: not filled yet; the next read tries again"),
72 Err(e) => tracing::warn!(agent_id = %agent_id, error = %e, "input history: the fill stopped"),
73 }
74 });
75}
76
77fn forgotten_by(ctx: &RpcContext) -> ForgottenBy<'_> {
80 let name = if ctx.agent_id.is_empty() { "armory-ui" } else { ctx.agent_id.as_str() };
81 ForgottenBy { name, uid: "" }
82}
83
84fn changed(state: &AppState, agent_id: &str, what: &str) {
86 state.broker.publish_event::<crate::backend::mps_events::AgentInputHistoryChanged>(
87 &InputHistoryChangedEvent { agent_id: agent_id.to_string(), what: what.to_string() },
88 vec![],
89 0,
90 );
91}
92
93pub(crate) fn record_broadcast(state: &AppState, block_id: &str, text: &str) {
97 let max = kept_per_agent(state);
98 let Some(agent_id) = state
99 .mstore
100 .get::<crate::backend::obj::Block>(block_id)
101 .ok()
102 .flatten()
103 .and_then(|b| crate::backend::obj::block_meta_agent_id(&b.meta).map(|id| id.trim().to_string()))
104 .filter(|id| !id.is_empty())
105 else {
106 return;
107 };
108 if max == 0 {
109 return;
110 }
111 let entry = crate::backend::storage::agent_input_history::NewInputHistoryEntry {
112 agent_id: &agent_id,
113 sent_at_ms: agentmux_common::time::now_ms(),
114 text,
115 kind: "message",
116 source: "swarm",
117 session_id: None,
118 attachments: None,
119 };
120 match state.mstore.input_history_append(&entry, max) {
121 Ok(Some(_)) => changed(state, &agent_id, "history"),
122 Ok(None) => {}
123 Err(e) => tracing::warn!(block_id, error = %e, "input history: couldn't keep a broadcast"),
124 }
125}
126
127const TYPED_BY_THE_PERSON: &str = "only the person's own typing is kept as typed by them: ask the person to send it from the AgentMux window";
129
130pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
131 let s = state.clone();
132 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY, move |cmd: CommandInputHistoryData, _ctx| {
133 let s = s.clone();
134 async move { input_history(&s, cmd) }
135 });
136
137 let s = state.clone();
138 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY_APPEND, move |cmd: CommandInputHistoryAppendData, ctx| {
139 let s = s.clone();
140 async move {
141 ctx.operator_only(TYPED_BY_THE_PERSON)?;
142 input_history_append(&s, cmd)
143 }
144 });
145
146 let s = state.clone();
147 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY_SEARCH, move |cmd: CommandInputHistorySearchData, _ctx| {
148 let s = s.clone();
149 async move { input_history_search(&s, cmd) }
150 });
151
152 let s = state.clone();
153 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY_DELETE, move |cmd: CommandInputHistoryDeleteData, ctx| {
154 let s = s.clone();
155 async move { input_history_delete(&s, &ctx, cmd) }
156 });
157
158 let s = state.clone();
159 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY_CLEAR, move |cmd: CommandInputHistoryClearData, ctx| {
160 let s = s.clone();
161 async move { input_history_clear(&s, &ctx, cmd) }
162 });
163
164 let s = state.clone();
165 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY_TRASH, move |cmd: CommandInputHistoryTrashData, _ctx| {
166 let s = s.clone();
167 async move { input_history_trash(&s, cmd) }
168 });
169
170 let s = state.clone();
171 engine.register_typed(COMMAND_AGENT_INPUT_HISTORY_RESTORE, move |cmd: CommandInputHistoryRestoreData, ctx| {
172 let s = s.clone();
173 async move { input_history_restore(&s, &ctx, cmd) }
174 });
175
176 let s = state.clone();
177 engine.register_typed(COMMAND_AGENT_INPUT_DRAFT, move |cmd: CommandInputDraftData, ctx| {
178 let s = s.clone();
179 async move {
180 if cmd.text.is_some() {
181 ctx.operator_only(TYPED_BY_THE_PERSON)?;
182 }
183 input_draft(&s, cmd)
184 }
185 });
186}
187
188pub(crate) fn input_history(s: &AppState, cmd: CommandInputHistoryData) -> Result<InputHistoryResult, String> {
190 if cmd.before_id.is_none() {
191 maybe_backfill(s, &cmd.agent_id);
192 }
193 let limit = cmd.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
194 let entries = s
195 .mstore
196 .input_history_list(&cmd.agent_id, cmd.before_id, limit)
197 .map_err(|e| format!("agent.input-history: {e}"))?;
198 Ok(InputHistoryResult { entries: entries.into_iter().map(item).collect() })
199}
200
201pub(crate) fn input_history_append(s: &AppState, cmd: CommandInputHistoryAppendData) -> Result<InputHistoryAppendResult, String> {
203 if !KINDS.contains(&cmd.kind.as_str()) {
204 return Err(format!("agent.input-history-append: unknown kind {:?}", cmd.kind));
205 }
206 let source = cmd.source.as_deref().filter(|s| *s == "swarm").unwrap_or("composer");
207 let attachments = (!cmd.attachments.is_empty())
208 .then(|| serde_json::to_string(&cmd.attachments.iter().map(|n| serde_json::json!({ "name": n })).collect::<Vec<_>>()).ok())
209 .flatten();
210 let entry = crate::backend::storage::agent_input_history::NewInputHistoryEntry {
211 agent_id: &cmd.agent_id,
212 sent_at_ms: agentmux_common::time::now_ms(),
213 text: &cmd.text,
214 kind: &cmd.kind,
215 source,
216 session_id: None,
217 attachments: attachments.as_deref(),
218 };
219 let max = kept_per_agent(s);
220 if max == 0 {
221 return Ok(InputHistoryAppendResult { entry: None });
222 }
223 let saved = s.mstore.input_history_append(&entry, max).map_err(|e| format!("agent.input-history-append: {e}"))?;
224 if saved.is_some() {
225 changed(s, &cmd.agent_id, "history");
226 }
227 Ok(InputHistoryAppendResult { entry: saved.map(item) })
228}
229
230pub(crate) fn input_history_search(s: &AppState, cmd: CommandInputHistorySearchData) -> Result<InputHistoryResult, String> {
232 let limit = cmd.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
233 let entries = s
234 .mstore
235 .input_history_search(cmd.agent_id.as_deref(), &cmd.query, limit)
236 .map_err(|e| format!("agent.input-history-search: {e}"))?;
237 Ok(InputHistoryResult { entries: entries.into_iter().map(item).collect() })
238}
239
240pub(crate) fn input_history_delete(
242 s: &AppState,
243 ctx: &RpcContext,
244 cmd: CommandInputHistoryDeleteData,
245) -> Result<InputHistoryRemovedResult, String> {
246 let by = forgotten_by(ctx);
247 let forgotten = s
248 .mstore
249 .input_history_delete(cmd.id, by, agentmux_common::time::now_ms())
250 .map_err(|e| format!("agent.input-history-delete: {e}"))?;
251 if let Some((agent, _)) = &forgotten {
252 tracing::info!(agent_id = %agent, entry_id = cmd.id, by = by.name, "input history: an entry was forgotten");
254 changed(s, agent, "history");
255 }
256 Ok(InputHistoryRemovedResult { removed: u32::from(forgotten.is_some()), batch_id: forgotten.map(|(_, batch)| batch) })
257}
258
259pub(crate) fn input_history_clear(
261 s: &AppState,
262 ctx: &RpcContext,
263 cmd: CommandInputHistoryClearData,
264) -> Result<InputHistoryRemovedResult, String> {
265 let by = forgotten_by(ctx);
266 let (batch_id, removed) = s
267 .mstore
268 .input_history_clear(&cmd.agent_id, by, agentmux_common::time::now_ms())
269 .map_err(|e| format!("agent.input-history-clear: {e}"))?;
270 if removed > 0 {
271 tracing::info!(agent_id = %cmd.agent_id, entries = removed, by = by.name, "input history: an agent's history was cleared");
272 changed(s, &cmd.agent_id, "history");
273 }
274 Ok(InputHistoryRemovedResult { removed: removed as u32, batch_id })
275}
276
277pub(crate) fn input_history_trash(s: &AppState, cmd: CommandInputHistoryTrashData) -> Result<InputHistoryTrashResult, String> {
279 let batches = s
280 .mstore
281 .input_history_trash(cmd.agent_id.as_deref(), agentmux_common::time::now_ms())
282 .map_err(|e| format!("agent.input-history-trash: {e}"))?;
283 Ok(InputHistoryTrashResult {
284 batches: batches
285 .into_iter()
286 .map(|b| InputHistoryTrashItem {
287 batch_id: b.batch_id,
288 agent_id: b.agent_id,
289 deleted_at_ms: b.deleted_at_ms,
290 deleted_by: b.deleted_by,
291 count: b.count as u32,
292 sample: b.sample,
293 })
294 .collect(),
295 retention_ms: crate::backend::storage::agent_input_history::INPUT_HISTORY_TRASH_RETENTION_MS,
296 })
297}
298
299pub(crate) fn input_history_restore(
301 s: &AppState,
302 ctx: &RpcContext,
303 cmd: CommandInputHistoryRestoreData,
304) -> Result<InputHistoryRestoredResult, String> {
305 let restored = s
306 .mstore
307 .input_history_restore(&cmd.batch_id, agentmux_common::time::now_ms())
308 .map_err(|e| format!("agent.input-history-restore: {e}"))?;
309 let Some((agent, count)) = restored else { return Ok(InputHistoryRestoredResult { restored: 0 }) };
310 tracing::info!(agent_id = %agent, entries = count, by = forgotten_by(ctx).name, "input history: forgotten entries were restored");
311 changed(s, &agent, "restored");
312 Ok(InputHistoryRestoredResult { restored: count as u32 })
313}
314
315pub(crate) fn input_draft(s: &AppState, cmd: CommandInputDraftData) -> Result<InputDraftResult, String> {
317 if let Some(text) = &cmd.text {
318 let known = s
319 .mstore
320 .input_draft_set(&cmd.agent_id, text, agentmux_common::time::now_ms())
321 .map_err(|e| format!("agent.input-draft: {e}"))?;
322 if known {
323 changed(s, &cmd.agent_id, "draft");
324 }
325 }
326 let text = s.mstore.input_draft_get(&cmd.agent_id).map_err(|e| format!("agent.input-draft: {e}"))?;
327 Ok(InputDraftResult { text })
328}
329
330#[cfg(test)]
331mod tests {
332 use super::*;
333
334 #[test]
335 fn who_forgot_is_the_registered_agent_or_else_the_window() {
336 let window = RpcContext::default();
337 assert_eq!(forgotten_by(&window).name, "armory-ui");
338 let agent = RpcContext { agent_id: "korp".into(), ..Default::default() };
339 assert_eq!(forgotten_by(&agent).name, "korp");
340 }
341
342 #[tokio::test]
343 async fn forgetting_through_the_rpcs_is_recorded_and_restorable() {
344 let state = crate::server::tests::test_state();
345 let (engine, _rx) = WshRpcEngine::new();
346 register(&engine, &state);
347 state
348 .mstore
349 .conn()
350 .lock()
351 .unwrap()
352 .execute("INSERT INTO db_agents (id, name, provider) VALUES ('uid-9', 'A', 'claude')", [])
353 .unwrap();
354 let entry = crate::backend::storage::agent_input_history::NewInputHistoryEntry {
355 agent_id: "uid-9",
356 sent_at_ms: agentmux_common::time::now_ms(),
357 text: "ship it",
358 kind: "message",
359 source: "composer",
360 ..Default::default()
361 };
362 state.mstore.input_history_append(&entry, 100).unwrap();
363 let schema = engine.schema_json();
364 let rows = schema.as_array().unwrap();
365 for (cmd, req, resp) in [
366 (COMMAND_AGENT_INPUT_HISTORY_TRASH, "CommandInputHistoryTrashData", "InputHistoryTrashResult"),
367 (COMMAND_AGENT_INPUT_HISTORY_RESTORE, "CommandInputHistoryRestoreData", "InputHistoryRestoredResult"),
368 ] {
369 let row = rows.iter().find(|r| r["command"] == cmd).unwrap_or_else(|| panic!("{cmd} missing from the schema"));
370 assert_eq!((row["requestName"].as_str(), row["responseName"].as_str()), (Some(req), Some(resp)));
371 }
372 let forgotten = state
373 .mstore
374 .input_history_clear("uid-9", forgotten_by(&RpcContext { agent_id: "korp".into(), ..Default::default() }), agentmux_common::time::now_ms())
375 .unwrap();
376 assert_eq!(forgotten.1, 1);
377 let trash = state.mstore.input_history_trash(Some("uid-9"), agentmux_common::time::now_ms()).unwrap();
378 assert_eq!((trash.len(), trash[0].deleted_by.as_str()), (1, "korp"));
379 }
380
381 #[tokio::test]
382 async fn a_swarm_broadcast_is_kept_in_the_recipient_agents_history() {
383 let state = crate::server::tests::test_state();
384 state
385 .mstore
386 .conn()
387 .lock()
388 .unwrap()
389 .execute("INSERT INTO db_agents (id, name, provider) VALUES ('uid-1', 'A', 'claude')", [])
390 .unwrap();
391 let block = |oid: &str, agent: Option<&str>| {
392 let mut b = crate::backend::obj::Block { oid: oid.into(), ..Default::default() };
393 if let Some(a) = agent {
394 b.meta.insert("agentId".into(), serde_json::json!(a));
395 }
396 state.mstore.insert(&mut b).unwrap();
397 };
398 block("b-agent", Some(" uid-1 "));
399 {
400 let mut b = crate::backend::obj::Block { oid: "b-legacy".into(), ..Default::default() };
402 b.meta.insert("agent:id".into(), serde_json::json!("uid-1"));
403 state.mstore.insert(&mut b).unwrap();
404 }
405 block("b-quick", Some("claude"));
406 block("b-shell", None);
407 for b in ["b-agent", "b-quick", "b-shell"] {
408 record_broadcast(&state, b, "merge on approval");
409 }
410 record_broadcast(&state, "b-legacy", "and then release");
411 let kept = state.mstore.input_history_list("uid-1", None, 10).unwrap();
412 assert_eq!(kept.len(), 2);
413 assert_eq!(kept[0].text, "and then release");
414 let kept = &kept[1..];
415 assert_eq!((kept[0].text.as_str(), kept[0].source.as_str()), ("merge on approval", "swarm"));
416 assert!(state.mstore.input_history_list("claude", None, 10).unwrap().is_empty(), "a provider key isn't an agent");
417 assert_eq!(kept_per_agent(&state), 10000, "the default");
418 }
419
420 async fn state_with_agent(id: &str) -> AppState {
421 let state = crate::server::tests::test_state();
422 state
423 .mstore
424 .conn()
425 .lock()
426 .unwrap()
427 .execute("INSERT INTO db_agents (id, name, provider) VALUES (?1, 'A', 'claude')", [id])
428 .unwrap();
429 state
430 }
431
432 fn append_req(agent: &str, text: &str, kind: &str) -> CommandInputHistoryAppendData {
433 serde_json::from_value(serde_json::json!({ "agent_id": agent, "text": text, "kind": kind })).unwrap()
434 }
435
436 fn list_req(agent: &str) -> CommandInputHistoryData {
437 serde_json::from_value(serde_json::json!({ "agent_id": agent })).unwrap()
438 }
439
440 #[tokio::test]
441 async fn what_was_appended_is_listed_newest_first_and_an_unknown_kind_is_refused() {
442 let state = state_with_agent("uid-h1").await;
443 input_history_append(&state, append_req("uid-h1", "first", "message")).unwrap();
444 let saved = input_history_append(&state, append_req("uid-h1", "/clear", "slash")).unwrap();
445 assert_eq!(saved.entry.unwrap().text, "/clear");
446 let listed = input_history(&state, list_req("uid-h1")).unwrap();
447 assert_eq!(listed.entries.iter().map(|e| e.text.as_str()).collect::<Vec<_>>(), vec!["/clear", "first"]);
448
449 let err = input_history_append(&state, append_req("uid-h1", "x", "shout")).err().unwrap();
450 assert_eq!(err, "agent.input-history-append: unknown kind \"shout\"");
451 }
452
453 #[tokio::test]
454 async fn a_deleted_entry_goes_to_the_trash_and_comes_back_on_restore() {
455 let state = state_with_agent("uid-h2").await;
456 let id = input_history_append(&state, append_req("uid-h2", "keep me", "message")).unwrap().entry.unwrap().id;
457 let window = RpcContext::default();
458
459 let removed = input_history_delete(&state, &window, CommandInputHistoryDeleteData { id }).unwrap();
460 assert_eq!(removed.removed, 1);
461 assert!(input_history(&state, list_req("uid-h2")).unwrap().entries.is_empty());
462 let trash = input_history_trash(&state, CommandInputHistoryTrashData { agent_id: Some("uid-h2".into()) }).unwrap();
463 assert_eq!((trash.batches.len(), trash.batches[0].deleted_by.as_str()), (1, "armory-ui"));
464
465 let restored = input_history_restore(&state, &window, CommandInputHistoryRestoreData { batch_id: removed.batch_id.unwrap() }).unwrap();
466 assert_eq!(restored.restored, 1);
467 assert_eq!(input_history(&state, list_req("uid-h2")).unwrap().entries.len(), 1);
468 }
469
470 #[tokio::test]
471 async fn clearing_records_which_agent_did_it_and_clearing_nothing_changes_nothing() {
472 let state = state_with_agent("uid-h3").await;
473 let cleared_empty = input_history_clear(&state, &RpcContext::default(), CommandInputHistoryClearData { agent_id: "uid-h3".into() }).unwrap();
474 assert_eq!(cleared_empty.removed, 0);
475
476 input_history_append(&state, append_req("uid-h3", "a", "message")).unwrap();
477 input_history_append(&state, append_req("uid-h3", "b", "message")).unwrap();
478 let korp = RpcContext { agent_id: "korp".into(), ..Default::default() };
479 let cleared = input_history_clear(&state, &korp, CommandInputHistoryClearData { agent_id: "uid-h3".into() }).unwrap();
480 assert_eq!(cleared.removed, 2);
481 let trash = input_history_trash(&state, CommandInputHistoryTrashData { agent_id: Some("uid-h3".into()) }).unwrap();
482 assert_eq!(trash.batches[0].deleted_by, "korp");
483 }
484
485 #[tokio::test]
486 async fn a_draft_reads_back_what_was_stored_and_no_text_only_reads() {
487 let state = state_with_agent("uid-h4").await;
488 let set = |text: Option<&str>| CommandInputDraftData { agent_id: "uid-h4".into(), text: text.map(String::from) };
489 assert_eq!(input_draft(&state, set(None)).unwrap().text.as_deref().unwrap_or(""), "");
490 assert_eq!(input_draft(&state, set(Some("half a thought"))).unwrap().text.as_deref(), Some("half a thought"));
491 assert_eq!(input_draft(&state, set(None)).unwrap().text.as_deref(), Some("half a thought"), "reading leaves it");
492 }
493}