Skip to main content

allot_shared/
api.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{
4    types::{
5        EndCause, Holder, JobClass, JobProfile, JobRun, Lease, LeaseKind, LeaseState, NoiseReport,
6        SessionKey, SessionUsage,
7    },
8    ui::Notice,
9};
10
11/// Response of `GET /health`.
12#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct HealthResponse {
15    /// Daemon version, from its `Cargo.toml`.
16    pub version: String,
17    /// Daemon process ID.
18    pub pid: u32,
19    /// Seconds since the daemon started.
20    pub uptime_secs: u64,
21    /// Why the last change to `config.toml` was rejected; the daemon keeps the config it had
22    /// until the file is fixed.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub config_error: Option<String>,
25}
26
27/// How a request states the resources a job needs.
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30#[non_exhaustive]
31pub enum ProfileSpec {
32    /// A named class, resolved through the daemon's config.
33    Class(JobClass),
34    /// A named preset from the daemon's config, for example `cpu_small`. The lease records it
35    /// as a custom profile with no class.
36    Preset(String),
37    /// Explicit values.
38    Custom(JobProfile),
39}
40
41/// Body of `POST /can-fit`.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct CanFitRequest {
44    /// Resources the job needs.
45    pub profile: ProfileSpec,
46    /// How the job would share the machine.
47    pub kind: LeaseKind,
48    /// The fewest cores the job can start with. Without it the class or preset's minimum
49    /// applies, and a custom profile keeps all its cores.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub min_cores: Option<f32>,
52    /// The command, so the daemon can raise the profile from similar past runs.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub label: Option<String>,
55    /// Working directory of the command; part of what makes runs similar.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub cwd: Option<String>,
58}
59
60/// The reason a verdict gives when ending every lease would still leave too little room, so
61/// only something outside Allot can make the request fit, if anything can.
62pub const REASON_BEYOND_LEASES: &str = "more than the machine can free";
63
64/// The admission engine's answer. Response of `POST /can-fit`.
65#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct Verdict {
68    /// Whether the job could start now.
69    pub fits: bool,
70    /// Human-readable explanations, one per limiting or notable factor.
71    pub reasons: Vec<String>,
72    /// Expected wait before the job fits, when the daemon can estimate it.
73    pub wait_estimate_secs: Option<u64>,
74    /// Where a benchmark at the head of the queue stands; `None` for other requests.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub benchmark: Option<BenchmarkProgress>,
77}
78
79/// Where a waiting benchmark lease stands, so its holder can report progress.
80#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
81#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
82#[serde(tag = "phase", rename_all = "snake_case")]
83#[non_exhaustive]
84pub enum BenchmarkProgress {
85    /// Other leases are still active; nothing new starts until they end.
86    Draining {
87        /// Active leases left.
88        active_leases: u32,
89    },
90    /// The machine has drained and its background load is being averaged.
91    Measuring {
92        /// Seconds averaged so far.
93        measured_secs: u64,
94        /// Seconds the average must cover.
95        needed_secs: u64,
96        /// Average total CPU load so far, in percent.
97        cpu_avg_pct: f32,
98        /// Average load of the busiest GPU engine so far, in percent.
99        gpu_avg_pct: f32,
100    },
101    /// The average is above the quiet limits. The lease is granted anyway, marked as not
102    /// quiet, once `grant_anyway_in_secs` have passed.
103    Noisy {
104        /// Average total CPU load over the quiet window, in percent.
105        cpu_avg_pct: f32,
106        /// Average load of the busiest GPU engine over the quiet window, in percent.
107        gpu_avg_pct: f32,
108        /// CPU limit of a quiet machine.
109        cpu_limit_pct: f32,
110        /// GPU limit of a quiet machine.
111        gpu_limit_pct: f32,
112        /// Seconds until the lease is granted without quiet.
113        grant_anyway_in_secs: u64,
114    },
115}
116
117/// Body of `POST /leases`.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct AcquireRequest {
120    /// Session asking for the lease.
121    pub holder: Holder,
122    /// Resources to reserve.
123    pub profile: ProfileSpec,
124    /// The fewest cores the job can start with. Without it the class or preset's minimum
125    /// applies, and a custom profile keeps all its cores.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub min_cores: Option<f32>,
128    /// How the lease shares the machine.
129    pub kind: LeaseKind,
130    /// What the lease is for, usually the command that will run.
131    pub label: String,
132    /// Working directory of the command; part of what makes runs similar.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub cwd: Option<String>,
135    /// How long the daemon may hold the request open waiting for the lease to become active.
136    pub wait_timeout_secs: u64,
137}
138
139/// Response of `POST /leases`.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct AcquireResponse {
142    /// The lease, `Active` if it was granted within the wait timeout and `Queued` otherwise.
143    pub lease: Lease,
144    /// Why the lease was granted or is still waiting.
145    pub verdict: Verdict,
146}
147
148/// Body of `POST /leases/{id}/wait`: keep waiting for a queued lease without losing its place.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150pub struct WaitRequest {
151    /// How long the daemon may hold the request open waiting for the lease to become active.
152    pub wait_timeout_secs: u64,
153}
154
155/// Query string of `POST /leases/{id}/heartbeat`, `POST /leases/{id}/wait`,
156/// `POST /leases/{id}/bind`, `DELETE /leases/{id}`, `GET /notices`, and
157/// `POST /notices/{id}/delivered`.
158///
159/// The daemon refuses a lease or notice call when the lease belongs to another session.
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct LeaseOwner {
162    /// Session that claims to own the lease.
163    pub session: SessionKey,
164}
165
166/// Response of `POST /leases/{id}/heartbeat`.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168pub struct HeartbeatResponse {
169    /// Current state, so a holder of a queued lease learns when it becomes active.
170    pub state: LeaseState,
171    /// New expiry, in milliseconds since the Unix epoch.
172    pub expires_at_ms: i64,
173    /// Why the lease ended, once it has; for example [`EndCause::Killed`] when the user
174    /// stopped its job.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub end_cause: Option<EndCause>,
177}
178
179/// Response of `DELETE /leases/{id}`.
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub struct ReleaseResponse {
182    /// The lease in its final state.
183    pub lease: Lease,
184    /// Background load while a benchmark lease was active. Only the release that ends the
185    /// lease carries it, and only when at least one sample was taken during the lease.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub noise: Option<NoiseReport>,
188    /// What the run used. Only the release that ends an active lease carries it.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub run: Option<RunReport>,
191    /// What the next run of the same request would reserve, now that this run counts. Only
192    /// with `run`, and only while allotd still knows the request, which a lease restored
193    /// across a daemon restart it does not.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub next: Option<NextReservation>,
196}
197
198/// What one finished run used.
199#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
200pub struct RunReport {
201    /// Cores and GPU load while its session was busy, peak RAM and VRAM, and run time in
202    /// `est_secs`: the values [`RunStats`] takes of each run.
203    pub used: JobProfile,
204    /// Whether estimates count the run; one that overlapped another lease of its session or
205    /// that the user killed does not.
206    pub counted: bool,
207}
208
209/// What a request would reserve if it were made again now.
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct NextReservation {
212    /// The profile acquire would reserve, before any shrink to fit.
213    pub profile: JobProfile,
214    /// What history changed, worded as acquire words it; empty when nothing changed.
215    pub reasons: Vec<String>,
216}
217
218/// Response of `POST /leases/{id}/kill`.
219#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
221pub struct KillResponse {
222    /// The lease, ended with cause `killed`.
223    pub lease: Lease,
224    /// Processes terminated, root first.
225    pub terminated: Vec<KilledProcess>,
226    /// Processes that could not be terminated, with what the OS said.
227    pub failed: Vec<UnkilledProcess>,
228    /// Processes in the tree left running on purpose, each with everything below it.
229    pub spared: Vec<UnkilledProcess>,
230    /// Why no process was terminated: the lease had no bound process tree, or its command had
231    /// already ended. The lease ended anyway. `None` when the bound tree was killed.
232    pub untouched_reason: Option<String>,
233}
234
235/// A process a kill terminated.
236#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct KilledProcess {
239    /// Process ID.
240    pub pid: u32,
241    /// Executable name, for example `cargo.exe`.
242    pub name: String,
243}
244
245/// A process in a killed tree that is still running.
246#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248pub struct UnkilledProcess {
249    /// Process ID.
250    pub pid: u32,
251    /// Executable name, for example `claude.exe`.
252    pub name: String,
253    /// Why it is still running.
254    pub reason: String,
255}
256
257/// Response of `POST /leases/{id}/remove`.
258#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct RemoveResponse {
261    /// The lease, ended with cause `removed` before it started.
262    pub lease: Lease,
263}
264
265/// Body of `POST /leases/{id}/bind`: the PreToolUse hook let a command run under the lease.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct BindRequest {
268    /// Claude Code's ID for the tool call that runs the command.
269    pub tool_use_id: String,
270    /// The command as the hook saw it, for the log.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub command: Option<String>,
273}
274
275/// Response of `GET /notices`.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct NoticesResponse {
278    /// Kills and removals the session has not been told about yet, oldest first.
279    pub notices: Vec<Notice>,
280}
281
282/// Response of `POST /notices/{id}/delivered`.
283#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
284pub struct DeliveredResponse {
285    /// `true` when this call recorded the delivery; `false` when an earlier one already had,
286    /// so the session must not be told again.
287    pub delivered: bool,
288}
289
290/// Query string of `GET /leases`. Each filter is optional; an empty query lists every lease.
291#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
292pub struct LeaseQuery {
293    /// Only leases held by this session.
294    pub session: Option<SessionKey>,
295    /// Only leases in this state.
296    pub state: Option<LeaseState>,
297}
298
299/// Response of `GET /leases`.
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301pub struct LeasesResponse {
302    /// Matching leases, oldest first.
303    pub leases: Vec<Lease>,
304}
305
306/// Response of `GET /sessions`.
307#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
308pub struct SessionsResponse {
309    /// Every registered session with its current usage.
310    pub sessions: Vec<SessionUsage>,
311}
312
313/// Body of `POST /sessions`. Registering the same session again is harmless; the daemon
314/// forgets a session once its holder process is gone.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct RegisterSessionRequest {
317    /// The session and its `claude.exe`.
318    pub holder: Holder,
319}
320
321/// Response of `GET /history`.
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
323pub struct HistoryResponse {
324    /// One entry per fingerprint, most recently run first.
325    pub jobs: Vec<JobSummary>,
326}
327
328/// What the history knows about one fingerprint.
329#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
331pub struct JobSummary {
332    /// Normalized command plus working directory.
333    pub fingerprint: String,
334    /// Label of the most recent run.
335    pub command: String,
336    /// Working directory of the most recent run.
337    pub cwd: String,
338    /// Stored runs.
339    pub runs: u32,
340    /// Runs the estimate is based on: the most recent ones without an overlapping lease.
341    pub estimate_runs: u32,
342    /// End of the most recent run, in milliseconds since the Unix epoch.
343    pub last_ended_at_ms: i64,
344    /// What the runs needed: p90 of peak memory, of CPU and GPU load while busy, and of run
345    /// time. `None` when every run overlapped another lease. The same as `stats.p90`.
346    pub learned: Option<JobProfile>,
347    /// Median, p90 and max over the runs the estimate is based on; `None` when every run
348    /// overlapped another lease, and from older daemons.
349    #[serde(default)]
350    pub stats: Option<RunStats>,
351}
352
353/// Median, p90 and max of what a job's runs used: the newest runs that neither overlapped
354/// another lease of their session nor were killed, at most as many as an estimate reads.
355/// Cores and GPU load are each run's average while its session was busy, RAM and VRAM its
356/// peak, and `est_secs` its run time.
357#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
358#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
359pub struct RunStats {
360    /// Runs the statistics come from.
361    pub runs: u32,
362    /// Nearest-rank median of each value.
363    pub median: JobProfile,
364    /// Nearest-rank 90th percentile of each value, which estimates raise and lower to.
365    pub p90: JobProfile,
366    /// Highest of each value.
367    pub max: JobProfile,
368}
369
370/// Query string of `GET /history/runs`.
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372pub struct HistoryRunsQuery {
373    /// Fingerprint whose runs to list.
374    pub fingerprint: String,
375    /// Most runs to return; the daemon's default when absent.
376    pub limit: Option<u32>,
377}
378
379/// Response of `GET /history/runs`.
380#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
381pub struct HistoryRunsResponse {
382    /// Runs with the fingerprint, newest first.
383    pub runs: Vec<JobRun>,
384    /// Statistics of the fingerprint over the runs an estimate reads, which may reach past
385    /// `runs`; `None` when no run counts, and from older daemons.
386    #[serde(default)]
387    pub stats: Option<RunStats>,
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use crate::test_support::{
394        assert_json_round_trip, sample_holder, sample_lease, sample_session_usage,
395    };
396
397    fn sample_verdict() -> Verdict {
398        Verdict {
399            fits: false,
400            reasons: vec!["RAM: 6144 MB requested, 4096 MB free after headroom".into()],
401            wait_estimate_secs: Some(90),
402            benchmark: None,
403        }
404    }
405
406    fn custom_profile() -> ProfileSpec {
407        ProfileSpec::Custom(JobProfile {
408            cores: 3.5,
409            ram_mb: 6144,
410            gpu_pct: 40.0,
411            vram_mb: 2048,
412            est_secs: 120,
413        })
414    }
415
416    #[test]
417    fn test_health_response_json_round_trip_preserves_every_field() {
418        assert_json_round_trip(&HealthResponse {
419            version: "0.1.0".into(),
420            pid: 4242,
421            uptime_secs: 3600,
422            config_error: Some("config.toml: invalid configuration: x".into()),
423        });
424    }
425
426    #[test]
427    fn test_can_fit_request_json_round_trip_preserves_both_profile_forms() {
428        assert_json_round_trip(&CanFitRequest {
429            profile: ProfileSpec::Class(JobClass::GpuHeavy),
430            kind: LeaseKind::Normal,
431            min_cores: None,
432            label: None,
433            cwd: None,
434        });
435        assert_json_round_trip(&CanFitRequest {
436            profile: custom_profile(),
437            kind: LeaseKind::BenchmarkExclusive,
438            min_cores: Some(2.0),
439            label: Some("cargo bench".into()),
440            cwd: Some(r"E:\work\app".into()),
441        });
442    }
443
444    #[test]
445    fn test_can_fit_request_without_label_and_cwd_deserializes_as_none() {
446        let request: CanFitRequest =
447            serde_json::from_str(r#"{"profile":{"class":"light"},"kind":"normal"}"#).unwrap();
448        assert_eq!((request.label, request.cwd), (None, None));
449    }
450
451    #[test]
452    fn test_profile_spec_json_is_externally_tagged() {
453        let class = serde_json::to_value(ProfileSpec::Class(JobClass::CpuHeavy)).unwrap();
454        assert_eq!(class, serde_json::json!({ "class": "cpu_heavy" }));
455        let custom = serde_json::to_value(custom_profile()).unwrap();
456        assert_eq!(custom["custom"]["ram_mb"], 6144);
457    }
458
459    #[test]
460    fn test_verdict_json_round_trip_preserves_every_field() {
461        assert_json_round_trip(&sample_verdict());
462        assert_json_round_trip(&Verdict {
463            fits: true,
464            reasons: vec![],
465            wait_estimate_secs: None,
466            benchmark: None,
467        });
468    }
469
470    #[test]
471    fn test_verdict_benchmark_progress_round_trips_every_phase() {
472        let phases = [
473            BenchmarkProgress::Draining { active_leases: 2 },
474            BenchmarkProgress::Measuring {
475                measured_secs: 4,
476                needed_secs: 10,
477                cpu_avg_pct: 6.5,
478                gpu_avg_pct: 0.0,
479            },
480            BenchmarkProgress::Noisy {
481                cpu_avg_pct: 12.5,
482                gpu_avg_pct: 1.0,
483                cpu_limit_pct: 10.0,
484                gpu_limit_pct: 10.0,
485                grant_anyway_in_secs: 35,
486            },
487        ];
488        for phase in phases {
489            assert_json_round_trip(&Verdict {
490                benchmark: Some(phase),
491                ..sample_verdict()
492            });
493        }
494        let value = serde_json::to_value(phases[0]).unwrap();
495        assert_eq!(
496            value,
497            serde_json::json!({ "phase": "draining", "active_leases": 2 })
498        );
499    }
500
501    #[test]
502    fn test_verdict_without_benchmark_field_deserializes_as_none() {
503        let verdict: Verdict =
504            serde_json::from_str(r#"{"fits":true,"reasons":[],"wait_estimate_secs":null}"#)
505                .unwrap();
506        assert_eq!(verdict.benchmark, None);
507    }
508
509    #[test]
510    fn test_acquire_request_json_round_trip_preserves_every_field() {
511        assert_json_round_trip(&AcquireRequest {
512            holder: sample_holder(),
513            profile: custom_profile(),
514            min_cores: Some(1.5),
515            kind: LeaseKind::Normal,
516            label: "cargo build --release".into(),
517            cwd: Some(r"E:\work\app".into()),
518            wait_timeout_secs: 30,
519        });
520    }
521
522    #[test]
523    fn test_acquire_response_json_round_trip_preserves_every_field() {
524        assert_json_round_trip(&AcquireResponse {
525            lease: sample_lease(),
526            verdict: sample_verdict(),
527        });
528    }
529
530    #[test]
531    fn test_lease_owner_json_round_trip_preserves_every_field() {
532        assert_json_round_trip(&LeaseOwner {
533            session: sample_holder().session,
534        });
535    }
536
537    #[test]
538    fn test_heartbeat_response_json_round_trip_preserves_every_field() {
539        assert_json_round_trip(&HeartbeatResponse {
540            state: LeaseState::Queued,
541            expires_at_ms: 1_793_000_060_000,
542            end_cause: None,
543        });
544        assert_json_round_trip(&HeartbeatResponse {
545            state: LeaseState::Expired,
546            expires_at_ms: 1_793_000_060_000,
547            end_cause: Some(EndCause::Killed),
548        });
549    }
550
551    #[test]
552    fn test_heartbeat_response_from_an_older_allotd_has_no_cause() {
553        let old: HeartbeatResponse =
554            serde_json::from_str(r#"{"state":"expired","expires_at_ms":5}"#).unwrap();
555        assert_eq!(old.end_cause, None);
556    }
557
558    #[test]
559    fn test_release_response_json_round_trip_preserves_every_field() {
560        assert_json_round_trip(&ReleaseResponse {
561            lease: sample_lease(),
562            noise: None,
563            run: None,
564            next: None,
565        });
566        let profile = sample_lease().profile;
567        assert_json_round_trip(&ReleaseResponse {
568            lease: sample_lease(),
569            noise: Some(NoiseReport {
570                avg_cpu_pct: 1.5,
571                peak_cpu_pct: 4.0,
572                avg_gpu_pct: 0.0,
573                peak_gpu_pct: 2.0,
574                quiet_at_start: true,
575            }),
576            run: Some(RunReport {
577                used: profile,
578                counted: true,
579            }),
580            next: Some(NextReservation {
581                profile,
582                reasons: vec!["cores 2.2 from p90 of 3 past run(s) plus 10% (declared 8.0)".into()],
583            }),
584        });
585    }
586
587    #[test]
588    fn test_release_response_from_an_older_allotd_has_no_run_or_next() {
589        let mut json = serde_json::to_value(ReleaseResponse {
590            lease: sample_lease(),
591            noise: None,
592            run: None,
593            next: None,
594        })
595        .unwrap();
596        assert!(
597            json.get("run").is_none() && json.get("next").is_none(),
598            "{json}"
599        );
600        json.as_object_mut().unwrap().remove("noise");
601        let old: ReleaseResponse = serde_json::from_value(json).unwrap();
602        assert_eq!((old.run, old.next), (None, None));
603    }
604
605    #[test]
606    fn test_wait_request_json_round_trip_preserves_every_field() {
607        assert_json_round_trip(&WaitRequest {
608            wait_timeout_secs: 90,
609        });
610    }
611
612    #[test]
613    fn test_lease_query_json_round_trip_preserves_empty_and_full_filters() {
614        assert_json_round_trip(&LeaseQuery::default());
615        assert_json_round_trip(&LeaseQuery {
616            session: Some(sample_holder().session),
617            state: Some(LeaseState::Active),
618        });
619    }
620
621    #[test]
622    fn test_lease_query_missing_fields_deserialize_as_none() {
623        let query: LeaseQuery = serde_json::from_str("{}").unwrap();
624        assert_eq!(query, LeaseQuery::default());
625    }
626
627    #[test]
628    fn test_leases_response_json_round_trip_preserves_every_field() {
629        assert_json_round_trip(&LeasesResponse {
630            leases: vec![sample_lease()],
631        });
632    }
633
634    #[test]
635    fn test_sessions_response_json_round_trip_preserves_every_field() {
636        assert_json_round_trip(&SessionsResponse {
637            sessions: vec![sample_session_usage()],
638        });
639    }
640
641    #[test]
642    fn test_history_dtos_json_round_trip_preserve_every_field() {
643        let ProfileSpec::Custom(p90) = custom_profile() else {
644            panic!("the custom profile fixture is not custom");
645        };
646        let stats = RunStats {
647            runs: 4,
648            median: JobProfile {
649                cores: 2.5,
650                ram_mb: 900,
651                ..p90
652            },
653            p90,
654            max: JobProfile {
655                est_secs: p90.est_secs * 2,
656                ..p90
657            },
658        };
659        let summary = JobSummary {
660            fingerprint: r"cargo build|e:\work\app".into(),
661            command: "cargo build".into(),
662            cwd: r"E:\work\app".into(),
663            runs: 5,
664            estimate_runs: 4,
665            last_ended_at_ms: 1_793_000_095_000,
666            learned: Some(stats.p90),
667            stats: Some(stats),
668        };
669        assert_json_round_trip(&HistoryResponse {
670            jobs: vec![
671                summary.clone(),
672                JobSummary {
673                    learned: None,
674                    stats: None,
675                    ..summary
676                },
677            ],
678        });
679        assert_json_round_trip(&HistoryRunsQuery {
680            fingerprint: "cargo build|".into(),
681            limit: Some(10),
682        });
683        assert_json_round_trip(&HistoryRunsResponse {
684            runs: Vec::new(),
685            stats: None,
686        });
687        assert_json_round_trip(&HistoryRunsResponse {
688            runs: Vec::new(),
689            stats: Some(stats),
690        });
691    }
692
693    #[test]
694    fn test_history_responses_from_an_older_allotd_have_no_stats() {
695        let summary: JobSummary = serde_json::from_str(
696            r#"{"fingerprint":"x|","command":"x","cwd":"","runs":1,"estimate_runs":0,
697                "last_ended_at_ms":5,"learned":null}"#,
698        )
699        .unwrap();
700        assert_eq!(summary.stats, None);
701        let runs: HistoryRunsResponse = serde_json::from_str(r#"{"runs":[]}"#).unwrap();
702        assert_eq!(runs.stats, None);
703    }
704
705    #[test]
706    fn test_kill_and_remove_responses_json_round_trip_preserve_every_field() {
707        assert_json_round_trip(&KillResponse {
708            lease: sample_lease(),
709            terminated: vec![KilledProcess {
710                pid: 30_112,
711                name: "bash.exe".into(),
712            }],
713            failed: vec![UnkilledProcess {
714                pid: 30_140,
715                name: "cargo.exe".into(),
716                reason: "Access is denied.".into(),
717            }],
718            spared: vec![UnkilledProcess {
719                pid: 30_150,
720                name: "claude.exe".into(),
721                reason: "protected".into(),
722            }],
723            untouched_reason: None,
724        });
725        let untouched = KillResponse {
726            lease: sample_lease(),
727            terminated: Vec::new(),
728            failed: Vec::new(),
729            spared: Vec::new(),
730            untouched_reason: Some("the lease has no bound process tree".into()),
731        };
732        assert_json_round_trip(&untouched);
733        assert_json_round_trip(&RemoveResponse {
734            lease: sample_lease(),
735        });
736    }
737
738    #[test]
739    fn test_bind_request_without_command_omits_it() {
740        let request = BindRequest {
741            tool_use_id: "toolu_01AbC".into(),
742            command: None,
743        };
744        assert_json_round_trip(&request);
745        let value = serde_json::to_value(&request).unwrap();
746        assert_eq!(value, serde_json::json!({ "tool_use_id": "toolu_01AbC" }));
747        assert_json_round_trip(&BindRequest {
748            command: Some("cargo build".into()),
749            ..request
750        });
751    }
752
753    #[test]
754    fn test_notice_dtos_json_round_trip_preserve_every_field() {
755        assert_json_round_trip(&NoticesResponse {
756            notices: Vec::new(),
757        });
758        assert_json_round_trip(&DeliveredResponse { delivered: true });
759    }
760
761    #[test]
762    fn test_register_session_request_json_round_trip_preserves_every_field() {
763        assert_json_round_trip(&RegisterSessionRequest {
764            holder: sample_holder(),
765        });
766    }
767}