Skip to main content

allot_shared/
ui.rs

1//! The tray flyout's view of the daemon, served whole by `GET /ui/state`.
2//!
3//! These types are the contract with the C# tray app: its types are generated from the JSON
4//! Schema of [`UiState`], and the golden fixtures in `contract/` pin the wire shape.
5
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    api::{HealthResponse, RunStats, Verdict},
10    types::{
11        Accuracy, DriveUsage, EndCause, JobProfile, JobRun, Lease, LeaseId, NoiseReport,
12        ResourceUsage, SessionKey, is_default,
13    },
14};
15
16/// Response of `GET /ui/state`: everything the flyout shows, in one poll.
17#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19pub struct UiState {
20    /// When the state was built, in milliseconds since the Unix epoch. Elapsed and waited
21    /// times are measured against it, so they do not depend on the tray app's clock.
22    pub generated_at_ms: i64,
23    /// The daemon itself.
24    pub service: HealthResponse,
25    /// When a Claude session first registered with this install, or `None` when none ever
26    /// has, which shows the first-run card.
27    pub first_session_at_ms: Option<i64>,
28    /// Every registered session, with or without leases.
29    pub sessions: Vec<UiSession>,
30    /// Active leases, oldest grant first.
31    pub active: Vec<ActiveJob>,
32    /// Queued leases, in queue order.
33    pub queue: Vec<QueuedJob>,
34    /// Machine meters for the Resources card.
35    pub meters: Meters,
36    /// Recently finished jobs, newest first.
37    pub recent: Vec<RecentRun>,
38    /// Kills and removals, with whether Claude has been told yet.
39    pub notices: Vec<Notice>,
40    /// Leases that ended in the last minute, however they ended, newest first, so the flyout
41    /// can hold a card that just went away with how it ended. Older allotd builds send none.
42    #[serde(default)]
43    pub ended: Vec<EndedLease>,
44}
45
46/// One registered Claude session.
47#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
49pub struct UiSession {
50    /// Session ID.
51    pub session: SessionKey,
52    /// Working directory of the session's most recent lease, which names its project; `None`
53    /// when no lease gave one.
54    pub cwd: Option<String>,
55    /// Live usage of the session's whole process subtree.
56    pub usage: ResourceUsage,
57}
58
59/// An active lease and the process its command runs as.
60#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct ActiveJob {
63    /// The lease.
64    pub lease: Lease,
65    /// The command's process, or `None` when the session has no process to show.
66    pub process: Option<JobProcess>,
67    /// For a benchmark lease, whether the machine was quiet when it was granted; `false` means
68    /// it was granted anyway after the longest quiet wait. `None` for other leases and when
69    /// the daemon restarted since the grant.
70    #[serde(default)]
71    pub quiet_at_start: Option<bool>,
72}
73
74/// The process shown for a job.
75#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct JobProcess {
78    /// Process ID.
79    pub pid: u32,
80    /// Executable name, for example `cargo.exe`.
81    pub name: String,
82    /// Full path of the executable, for its icon; `None` when it could not be read.
83    pub exe: Option<String>,
84    /// Whether it belongs to the command's bound process tree, the only tree a kill ends: its
85    /// busiest process, or its root while the tree is idle. `false` means it is the session's
86    /// busiest process, shown for display only.
87    pub bound: bool,
88}
89
90/// A queued lease and why it waits.
91#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93pub struct QueuedJob {
94    /// The lease.
95    pub lease: Lease,
96    /// Place in the queue, starting at 1.
97    pub position: u32,
98    /// Why it waits, the expected wait, and benchmark progress when it is a benchmark.
99    pub verdict: Verdict,
100}
101
102/// Machine meters with the share that leases reserve.
103#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct Meters {
106    /// Percentage of each resource that leases never take, from `admission.headroom_pct`.
107    pub headroom_pct: f32,
108    /// Processor load.
109    pub cpu: CpuMeter,
110    /// Physical memory.
111    pub ram: RamMeter,
112    /// Every GPU adapter.
113    pub gpus: Vec<GpuMeter>,
114    /// Every fixed drive, by drive letter on Windows and by mount point elsewhere.
115    pub drives: Vec<DriveUsage>,
116}
117
118/// Processor load.
119#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub struct CpuMeter {
122    /// Number of logical processors.
123    pub logical_cores: u32,
124    /// Total load over the last second, as a percentage of all logical processors.
125    pub usage_pct: f32,
126    /// Recent once-a-second loads for the sparkline, oldest first, at most 24.
127    pub history_pct: Vec<f32>,
128    /// Logical cores reserved by active leases.
129    pub reserved_cores: f32,
130}
131
132/// Physical memory.
133#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
135pub struct RamMeter {
136    /// Installed physical memory.
137    pub total_mb: u64,
138    /// Physical memory in use.
139    pub used_mb: u64,
140    /// Memory reserved by active leases.
141    pub reserved_mb: u64,
142}
143
144/// One GPU adapter.
145#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct GpuMeter {
148    /// Adapter name, for example `NVIDIA GeForce RTX 4070`.
149    pub name: String,
150    /// Load of the busiest engine group over the last second, in percent.
151    pub busiest_pct: f32,
152    /// Dedicated video memory in use; on a unified-memory adapter, the RAM the GPU has
153    /// allocated.
154    pub vram_used_mb: u64,
155    /// Dedicated video memory installed, when the OS reports it; `None` on a unified-memory
156    /// adapter.
157    pub vram_total_mb: Option<u64>,
158    /// Engine load reserved by active leases, in percent. Leases reserve on the adapter with
159    /// the most video memory only, so it is 0 on every other adapter.
160    pub reserved_pct: f32,
161    /// Video memory reserved by active leases; 0 on every adapter but the reserving one. On a
162    /// unified-memory adapter it comes out of RAM, on top of the RAM meter's reservation.
163    pub reserved_vram_mb: u64,
164    /// Whether the adapter's video memory is the machine's RAM, as on Apple Silicon.
165    // schemars leaves the default out of the schema for fields that skip it; the generated
166    // types need it.
167    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
168    #[cfg_attr(any(feature = "schema", test), schemars(extend("default" = false)))]
169    pub unified_memory: bool,
170    /// How well each job's GPU load is measured on this adapter.
171    #[serde(default, skip_serializing_if = "is_default")]
172    #[cfg_attr(any(feature = "schema", test), schemars(extend("default" = "exact")))]
173    pub process_load: Accuracy,
174}
175
176/// A finished job.
177#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
178#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
179pub struct RecentRun {
180    /// Lease the job ran under, if the lease is still stored.
181    pub lease_id: Option<LeaseId>,
182    /// Session that ran it; `None` for runs recorded before sessions were.
183    pub session: Option<SessionKey>,
184    /// The lease's label, usually the command as it was run.
185    pub command: String,
186    /// Working directory of the command.
187    pub cwd: String,
188    /// Profile the lease reserved.
189    pub declared: JobProfile,
190    /// Start of the run, in milliseconds since the Unix epoch.
191    pub started_at_ms: i64,
192    /// End of the run, in milliseconds since the Unix epoch.
193    pub ended_at_ms: i64,
194    /// Why it ended; `None` for runs recorded before causes were.
195    pub end_cause: Option<EndCause>,
196    /// Background load during the run; present only for benchmark leases.
197    pub noise: Option<NoiseReport>,
198    /// Median, p90 and max of the job's runs, as `allot history` shows them; `None` when no run
199    /// of the job counts, and from older daemons.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub stats: Option<RunStats>,
202}
203
204impl From<JobRun> for RecentRun {
205    fn from(run: JobRun) -> Self {
206        Self {
207            lease_id: run.lease_id,
208            session: run.session,
209            command: run.command,
210            cwd: run.cwd,
211            declared: run.declared,
212            started_at_ms: run.started_at_ms,
213            ended_at_ms: run.ended_at_ms,
214            end_cause: run.end_cause,
215            noise: run.noise,
216            stats: None,
217        }
218    }
219}
220
221/// A lease that ended a moment ago: released by its holder, ended by allotd, killed or removed.
222#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub struct EndedLease {
225    /// The lease.
226    pub lease_id: LeaseId,
227    /// Session that held it.
228    pub session: SessionKey,
229    /// The lease's label, usually the command.
230    pub command: String,
231    /// How it ended.
232    pub cause: EndCause,
233    /// allotd's reason for the end, for example "no command running and the session idle for
234    /// 180s"; empty when none was recorded.
235    pub reason: String,
236    /// When it was granted, or `None` for a request that never started.
237    pub granted_at_ms: Option<i64>,
238    /// When it ended, in milliseconds since the Unix epoch.
239    pub ended_at_ms: i64,
240}
241
242/// A kill or removal that Claude must hear about once.
243#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245pub struct Notice {
246    /// Lease the notice is about. A lease ends once, so this also identifies the notice.
247    pub lease_id: LeaseId,
248    /// Session to tell.
249    pub session: SessionKey,
250    /// What the user did: [`EndCause::Killed`] or [`EndCause::Removed`].
251    pub cause: EndCause,
252    /// The lease's label, usually the command.
253    pub command: String,
254    /// Claude Code's ID for the tool call the lease was bound to, or `None` when no hook
255    /// reported one. A hook compares it with its own call to say "this command".
256    #[serde(default)]
257    pub tool_use_id: Option<String>,
258    /// When the lease ended, in milliseconds since the Unix epoch.
259    pub ended_at_ms: i64,
260    /// When a hook or tool result told the session, or `None` while it has not been told.
261    pub delivered_at_ms: Option<i64>,
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::test_support::assert_json_round_trip;
268
269    #[test]
270    fn test_notice_json_round_trip_writes_cause_and_null_delivery() {
271        let notice = Notice {
272            lease_id: LeaseId(44),
273            session: SessionKey("3f2a9c1e-session".into()),
274            cause: EndCause::Removed,
275            command: "cargo test".into(),
276            tool_use_id: Some("toolu_01".into()),
277            ended_at_ms: 1_793_000_090_000,
278            delivered_at_ms: None,
279        };
280        assert_json_round_trip(&notice);
281        let value = serde_json::to_value(&notice).unwrap();
282        assert_eq!(value["lease_id"], 44);
283        assert_eq!(value["cause"], "removed");
284        assert_eq!(value["tool_use_id"], "toolu_01");
285        assert!(value["delivered_at_ms"].is_null());
286    }
287
288    #[test]
289    fn test_ended_lease_json_round_trip_writes_cause_and_null_grant() {
290        let ended = EndedLease {
291            lease_id: LeaseId(45),
292            session: SessionKey("3f2a9c1e-session".into()),
293            command: "npm test".into(),
294            cause: EndCause::Expired,
295            reason: "holder process exited".into(),
296            granted_at_ms: None,
297            ended_at_ms: 1_793_000_090_000,
298        };
299        assert_json_round_trip(&ended);
300        let value = serde_json::to_value(&ended).unwrap();
301        assert_eq!(value["cause"], "expired");
302        assert!(value["granted_at_ms"].is_null());
303    }
304
305    #[test]
306    fn test_ui_state_from_an_older_allotd_has_no_ended_leases() {
307        let mut value = serde_json::to_value(crate::contract::busy()).unwrap();
308        value.as_object_mut().unwrap().remove("ended");
309        let state: UiState = serde_json::from_value(value).unwrap();
310        assert!(state.ended.is_empty());
311    }
312
313    #[test]
314    fn test_gpu_meter_schema_defaults_match_the_rust_defaults() {
315        let schema = schemars::schema_for!(GpuMeter);
316        let properties = &schema.as_value()["properties"];
317        assert_eq!(
318            properties["process_load"]["default"],
319            serde_json::to_value(Accuracy::default()).unwrap()
320        );
321        assert_eq!(properties["unified_memory"]["default"], bool::default());
322    }
323
324    #[test]
325    fn test_gpu_meter_from_an_older_allotd_is_exact_and_not_unified() {
326        let old = r#"{"name":"RTX","busiest_pct":1.0,"vram_used_mb":0,"vram_total_mb":null,
327                      "reserved_pct":0.0,"reserved_vram_mb":0}"#;
328        let meter: GpuMeter = serde_json::from_str(old).unwrap();
329        assert!(!meter.unified_memory);
330        assert_eq!(meter.process_load, Accuracy::Exact);
331    }
332
333    #[test]
334    fn test_notice_from_an_older_allotd_has_no_tool_use_id() {
335        let old = r#"{"lease_id":1,"session":"s","cause":"killed","command":"cargo build",
336                      "ended_at_ms":5,"delivered_at_ms":null}"#;
337        let notice: Notice = serde_json::from_str(old).unwrap();
338        assert_eq!(notice.tool_use_id, None);
339    }
340}