Skip to main content

agentmux_srv/server/app_api/
history_usage.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `history.usage`: the history total in the status bar, and its panel.
5//! The window's, not an agent API: a connection registered as an agent is
6//! refused. Measuring walks tens of thousands of files, so an answer is reused
7//! for [`FRESH_FOR`] unless the request asks to `refresh`.
8
9use std::sync::Mutex;
10use std::time::{Duration, Instant};
11
12use super::tower_pane::not_an_agent_api;
13use super::*;
14use crate::backend::history_usage;
15
16/// How long a measurement answers later requests.
17const FRESH_FOR: Duration = Duration::from_secs(300);
18
19static LAST: Mutex<Option<(Instant, HistoryUsage)>> = Mutex::new(None);
20
21pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
22    // `history.reclaim`: ask for (or withdraw) giving the shared store's free
23    // space back at the next start (filestore::reclaim).
24    engine.register_typed(COMMAND_HISTORY_RECLAIM, move |req: HistoryReclaimReq, ctx| async move {
25        not_an_agent_api(&ctx)?;
26        use crate::backend::storage::filestore::reclaim;
27        let Some(db) = crate::backend::agent_session::global_transcript_store().and_then(|s| s.path().map(|p| p.to_path_buf())) else {
28            return Err("history.reclaim: the shared pane-history store isn't open".to_string());
29        };
30        let done = match req.action.as_str() {
31            "request" => reclaim::request(&db, "operator", agentmux_common::time::now_ms_u64()),
32            "cancel" => reclaim::cancel(&db),
33            other => return Err(format!("history.reclaim: unknown action {other:?} (request or cancel)")),
34        };
35        done.map_err(|e| format!("history.reclaim: {e}"))?;
36        tracing::info!(action = %req.action, "history reclaim: {}", if req.action == "request" { "asked for at the next start" } else { "withdrawn" });
37        Ok(history_usage::reclaim_of(&db))
38    });
39    let mstore = state.mstore.clone();
40    engine.register_typed(COMMAND_HISTORY_USAGE, move |req: HistoryUsageReq, ctx| {
41        let mstore = mstore.clone();
42        async move {
43            not_an_agent_api(&ctx)?;
44            if !req.refresh {
45                let cached = LAST.lock().unwrap().as_ref().filter(|(at, _)| at.elapsed() < FRESH_FOR).map(|(_, u)| u.clone());
46                if let Some(mut usage) = cached {
47                    // The sizes keep; what a running build holds off can change any minute and costs little to read.
48                    if usage.problem.as_ref().is_none_or(|p| p.key == "compression_waiting") {
49                        usage.problem = tokio::task::spawn_blocking(history_usage::waiting_now).await.map_err(|e| format!("history.usage: {e}"))?;
50                    }
51                    return Ok(usage);
52                }
53            }
54            let Some(roots) = history_usage::Roots::on_this_machine() else {
55                return Err("history.usage: the data folders can't be resolved".to_string());
56            };
57            // The walk and the store reads: off the async workers.
58            let usage = tokio::task::spawn_blocking(move || {
59                let names: std::collections::HashMap<String, String> = mstore
60                    .agent_def_list()
61                    .map(|defs| defs.into_iter().map(|d| (d.id, d.name)).collect())
62                    .unwrap_or_default();
63                let transcripts = crate::backend::agent_session::global_transcript_store();
64                history_usage::compute(&roots, transcripts.map(|t| &**t), |id| names.get(id).cloned(), agentmux_common::time::now_ms_u64())
65            })
66            .await
67            .map_err(|e| format!("history.usage: {e}"))?;
68            *LAST.lock().unwrap() = Some((Instant::now(), usage.clone()));
69            Ok(usage)
70        }
71    });
72}