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