Skip to main content

adk_kernel/control/
settings.rs

1//! Quiet time, the daily spending limit and the mode while the kernel runs (spec 3.3 §10
2//! K3, §8.1), per area: a partition, or `default` on a kernel without partitions.
3//!
4//! | Route (under `/api`) | Caller | Does |
5//! |---|---|---|
6//! | `GET /kernel/settings` | operator, or a device with `read` | Every area's settings in force, the primary agent's area marked `primary` ([`SettingsResponse`]) |
7//! | `GET /kernel/settings/{partition}` | operator, or a device with `read` | One area's ([`AreaResponse`]) |
8//! | `POST /kernel/settings/{partition}/quiet-time` | the person at the kernel or the home | Sets or turns off quiet time ([`QuietTimeRequest`]) |
9//! | `POST /kernel/settings/{partition}/spending-limit` | the person at the kernel or the home | Sets or removes the daily spending limit ([`SpendingLimitRequest`]) |
10//! | `POST /kernel/settings/{partition}/mode` | the person at the kernel or the home | Sets how much the area's agents act alone ([`PartitionModeRequest`](super::api::PartitionModeRequest)) |
11//!
12//! A change is recorded as `kernel.control` (`settings.quiet_time`, `settings.spending_limit`,
13//! `settings.mode`, with `from` and `to`) before it is stored in the
14//! [`ControlStore`](super::ControlStore), and it replaces, for the area, the value the kernel
15//! and the area's partition record started with. Admission reads it at every claim, so it
16//! takes effect from the agents' next step: no proactive process of the area starts inside
17//! the new quiet time, and no background process starts past the new limit. A quiet window
18//! a workspace sets (`[kernel] quiet_hours` of its `.adk/harness.toml`) still holds beside
19//! the person's and is listed as `alsoQuiet`.
20//!
21//! A change holds while the area still starts with the value it replaced
22//! ([`AreaStart`](super::AreaStart)): a different start value — a later `adk-rust up --mode`,
23//! `adk-rust partitions set-mode` followed by a restart, or quiet hours and a cap set at
24//! start — is newer and takes over, and the change is dropped at the area's next change.
25//!
26//! | Mode change | When it applies |
27//! |---|---|
28//! | Stricter than the area's mode | At every agent's next step; it also holds the overnight tidy-up and the kernel's questions back |
29//! | Looser | Refused while an agent of the area is working, so no turn changes its rules midway (spec 3.1 I14); a session whose mode was set on its own, or tightened by the harness, keeps its mode |
30//! | To a mode the kernel refuses | Refused, saying why: `adk-rust up` refuses Go ahead beyond loopback without `--sandbox` |
31//!
32//! The changing routes need the `operator` scope and refuse a paired device's token: they
33//! are for the person at the kernel's own terminal or socket, or signed in to the home, never
34//! a phone's token alone or a chat channel, which reaches no kernel route.
35
36use std::collections::BTreeSet;
37use std::sync::Arc;
38
39use axum::Json;
40use axum::Router;
41use axum::extract::{Path as UrlPath, State};
42use axum::routing::{get, post};
43use serde::{Deserialize, Serialize};
44use serde_json::json;
45
46use super::api::PartitionModeRequest;
47use super::paths;
48use super::routes::{Caller, ControlBackend, record};
49use super::store::{AreaSettings, AreaStart, Change, ControlStore};
50use crate::error::{KernelError, NOT_FOUND_CODE, Result};
51use crate::kernel::Kernel;
52use crate::partition::{Partition, PartitionId, PartitionMode};
53use crate::sched::QuietHours;
54
55type Backend = State<Arc<dyn ControlBackend>>;
56
57/// One area's settings in force (spec 3.3 §10 K3), as the home's "What your agents can do"
58/// shows them.
59///
60/// # Example
61///
62/// ```rust
63/// use adk_kernel::control::api::AreaView;
64///
65/// let wire = serde_json::json!({
66///     "partition": "default",
67///     "primary": true,
68///     "quietTime": [{ "start": "22:00", "end": "07:00" }],
69///     "dailySpendingLimit": 5_000_000,
70///     "spentToday": 1_840_000,
71///     "mode": "ask"
72/// });
73/// let area: AreaView = serde_json::from_value(wire).unwrap();
74/// assert_eq!(area.daily_spending_limit, Some(5_000_000));
75/// assert!(area.primary, "the primary agent works in this area");
76/// assert!(area.changed.is_none() && area.also_quiet.is_empty());
77/// ```
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "camelCase")]
80#[non_exhaustive]
81pub struct AreaView {
82    /// The area.
83    pub partition: PartitionId,
84    /// Whether the primary agent works in this area: the partition the kernel's own target,
85    /// [`KernelConfig::app_name`](crate::KernelConfig::app_name), is bound to, else `default`.
86    /// The turns a terminal or the home sends run there, so they show this area's spend today
87    /// and daily spending limit (spec 3.3 §10 K3, §13 Q7).
88    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
89    pub primary: bool,
90    /// The person's quiet time: the window changed while the kernel runs, else those it
91    /// started with. Empty is no quiet time.
92    #[serde(default)]
93    pub quiet_time: Vec<QuietHours>,
94    /// Windows a workspace sets, which hold beside the person's.
95    #[serde(default, skip_serializing_if = "Vec::is_empty")]
96    pub also_quiet: Vec<QuietHours>,
97    /// The daily spending limit in micro-USD; `None` is no limit.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub daily_spending_limit: Option<u64>,
100    /// Spent in the area today (UTC day), in micro-USD.
101    #[serde(default)]
102    pub spent_today: u64,
103    /// How much the area's agents act alone; `None` when the kernel was not told the mode
104    /// its agents started in.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub mode: Option<PartitionMode>,
107    /// What the person changed while the kernel ran, with when and by whom.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub changed: Option<AreaSettings>,
110}
111
112/// `GET /kernel/settings` answer (spec 3.3 §10 K3).
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub struct SettingsResponse {
116    /// Every area, ordered by partition id.
117    pub areas: Vec<AreaView>,
118}
119
120/// The answer of a settings read or change: the area after it.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub struct AreaResponse {
124    /// The area.
125    pub area: AreaView,
126}
127
128/// `POST /kernel/settings/{partition}/quiet-time` body (spec 3.3 §10 K3): the new window,
129/// or `null` for no quiet time.
130///
131/// # Example
132///
133/// ```rust
134/// use adk_kernel::control::api::QuietTimeRequest;
135///
136/// let body: QuietTimeRequest = serde_json::from_str(r#"{"window":{"start":"23:00","end":"07:00"}}"#).unwrap();
137/// assert!(body.window.is_some());
138/// let off: QuietTimeRequest = serde_json::from_str(r#"{"window":null}"#).unwrap();
139/// assert!(off.window.is_none());
140/// ```
141#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase")]
143pub struct QuietTimeRequest {
144    /// The window; `None` turns quiet time off.
145    pub window: Option<QuietHours>,
146}
147
148/// `POST /kernel/settings/{partition}/spending-limit` body (spec 3.3 §10 K3): the new limit
149/// in micro-USD, or `null` for no limit.
150///
151/// # Example
152///
153/// ```rust
154/// use adk_kernel::control::api::SpendingLimitRequest;
155///
156/// let body = SpendingLimitRequest { micro_usd: Some(5_000_000) };
157/// assert_eq!(serde_json::to_value(&body).unwrap()["microUsd"], 5_000_000);
158/// ```
159#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(rename_all = "camelCase")]
161pub struct SpendingLimitRequest {
162    /// The limit per UTC day; `None` removes it.
163    pub micro_usd: Option<u64>,
164}
165
166/// What an area started with, before any change: the values a change replaces.
167#[derive(Debug, Clone, Default, PartialEq, Eq)]
168pub(crate) struct Start {
169    /// The kernel's quiet hours and the partition record's own.
170    pub(crate) quiet: Vec<QuietHours>,
171    /// The workspace's window, which a change never replaces.
172    pub(crate) beside: Vec<QuietHours>,
173    /// The lower of the kernel's daily spend cap and the partition record's.
174    pub(crate) cap: Option<u64>,
175    /// The mode the area's agents started in, else the partition record's.
176    pub(crate) mode: Option<PartitionMode>,
177}
178
179impl Start {
180    /// The start values a change records it replaced.
181    pub(crate) fn area(&self) -> AreaStart {
182        AreaStart::new(self.quiet.clone(), self.cap, self.mode)
183    }
184}
185
186/// How strict `mode` is: 0 for Go ahead, up to 3 for Just look.
187fn strictness(mode: PartitionMode) -> u8 {
188    match mode {
189        PartitionMode::Auto => 0,
190        PartitionMode::Ask => 1,
191        PartitionMode::Plan => 2,
192        PartitionMode::ReadOnly => 3,
193    }
194}
195
196/// The stricter of `a` and `b`.
197pub(crate) fn stricter(a: PartitionMode, b: PartitionMode) -> PartitionMode {
198    if strictness(b) > strictness(a) { b } else { a }
199}
200
201/// The quiet windows in force in an area: the changed window in place of `kernel` and the
202/// partition record's, while the area still starts with those, then the workspace's
203/// `beside` (spec 3.3 §10 K3).
204pub(crate) fn quiet_windows(
205    kernel: Option<QuietHours>,
206    beside: Option<QuietHours>,
207    record: Option<&Partition>,
208    changed: Option<&AreaSettings>,
209) -> Vec<QuietHours> {
210    let start: Vec<QuietHours> =
211        kernel.into_iter().chain(record.and_then(|record| record.quiet_hours)).collect();
212    let own = match changed.and_then(|settings| settings.quiet_time_over(&start)) {
213        Some(change) => change.value.into_iter().collect(),
214        None => start,
215    };
216    own.into_iter().chain(beside).collect()
217}
218
219/// The quiet windows that were in force in an area at `at`, as its changes record them
220/// (spec 3.3 §5.1): the person's quiet time set at or before `at`, else the start windows,
221/// then the workspace's.
222#[cfg(feature = "proc")]
223pub(crate) fn quiet_windows_at(
224    start: &Start,
225    changed: Option<&AreaSettings>,
226    at: chrono::DateTime<chrono::Utc>,
227) -> Vec<QuietHours> {
228    let current = changed.and_then(|settings| settings.quiet_time.as_ref());
229    let stale = changed.is_some_and(|settings| {
230        settings.quiet_time.is_some() && settings.quiet_time_over(&start.quiet).is_none()
231    });
232    let own = match changed.and_then(|settings| settings.quiet_time_at(at)) {
233        // A change the area's start has replaced since held until a restart the record does
234        // not date: the start windows judge what came after it.
235        Some(change) if stale && Some(change) == current => start.quiet.clone(),
236        Some(change) => change.value.into_iter().collect(),
237        None => start.quiet.clone(),
238    };
239    own.into_iter().chain(start.beside.iter().copied()).collect()
240}
241
242/// The daily spend cap in force in an area: the changed limit in place of `start`, the
243/// lower of the kernel's and the partition record's, while the area still starts with it
244/// (spec 3.3 §10 K3).
245pub(crate) fn spend_cap(start: Option<u64>, changed: Option<&AreaSettings>) -> Option<u64> {
246    match changed.and_then(|settings| settings.daily_spending_limit_over(start)) {
247        Some(change) => change.value,
248        None => start,
249    }
250}
251
252/// The mode the person changed for an area, while its agents still start in the mode it
253/// replaced and the kernel does not refuse it (spec 3.3 §10 K3).
254pub(crate) fn changed_mode(
255    start: Option<PartitionMode>,
256    changed: Option<&AreaSettings>,
257    control: &super::ControlPlaneConfig,
258) -> Option<PartitionMode> {
259    changed
260        .and_then(|settings| settings.mode_over(start))
261        .map(|change| change.value)
262        .filter(|mode| control.refused_mode(*mode).is_none())
263}
264
265/// The changes of `settings` the area still starts with the values of, as the person sees
266/// them: `None` when none is left.
267fn in_force(settings: AreaSettings, start: &AreaStart) -> Option<AreaSettings> {
268    let mut shown = AreaSettings::new(settings.partition.clone());
269    shown.quiet_time = settings.quiet_time_over(&start.quiet_time).cloned();
270    shown.daily_spending_limit =
271        settings.daily_spending_limit_over(start.daily_spending_limit).cloned();
272    shown.mode = settings.mode_over(start.mode).cloned();
273    let any =
274        shown.quiet_time.is_some() || shown.daily_spending_limit.is_some() || shown.mode.is_some();
275    any.then_some(shown)
276}
277
278/// The routes, relative to `/api`, over the backend in their state.
279pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
280    Router::new()
281        .route(paths::SETTINGS, get(list))
282        .route(paths::AREA_SETTINGS, get(one))
283        .route(paths::QUIET_TIME, post(set_quiet_time))
284        .route(paths::SPENDING_LIMIT, post(set_spending_limit))
285        .route(paths::AREA_MODE, post(set_mode))
286}
287
288/// The kernel behind `backend`, or a `Config` error naming why there is none.
289fn kernel_of(backend: &dyn ControlBackend) -> Result<&Kernel> {
290    backend.kernel().ok_or_else(|| KernelError::Config {
291        reason: "the settings routes read a kernel's admission settings; serve them from a \
292                 Kernel"
293            .into(),
294    })
295}
296
297/// Refuses a change from anyone but the person at the kernel or signed in to the home: the
298/// `operator` scope, and no paired device's token (spec 3.3 §10 K3, S-I7).
299pub(super) fn require_owner(caller: &Caller, action: &str) -> Result<()> {
300    caller.require_operator(action)?;
301    if caller.context.metadata.contains_key(crate::pairing::DEVICE_ID_METADATA) {
302        return Err(crate::pairing::forbidden(format!(
303            "a paired device may not {action}: change it in the home or on the kernel's own \
304             terminal"
305        )));
306    }
307    Ok(())
308}
309
310/// The areas of `kernel`: `default` when the partition table is empty or names it, every
311/// partition in the table, and every area with a change.
312async fn areas(kernel: &Kernel, store: &dyn ControlStore) -> Result<Vec<PartitionId>> {
313    let partitions = kernel.partitions().list().await?;
314    let mut ids: BTreeSet<PartitionId> = partitions.into_iter().map(|p| p.id).collect();
315    if ids.is_empty() {
316        ids.insert(PartitionId::default());
317    }
318    ids.extend(store.list_area_settings().await?.into_iter().map(|s| s.partition));
319    Ok(ids.into_iter().collect())
320}
321
322/// `id` when it names an area of `kernel`, else a `404` naming the areas there are.
323async fn known_area(kernel: &Kernel, store: &dyn ControlStore, id: String) -> Result<PartitionId> {
324    let id = PartitionId::new(id);
325    let known = areas(kernel, store).await?;
326    if known.contains(&id) || id.as_str() == PartitionId::DEFAULT {
327        return Ok(id);
328    }
329    let names = known.iter().map(PartitionId::as_str).collect::<Vec<_>>().join(", ");
330    Err(KernelError::Core(adk_core::AdkError::new(
331        adk_core::ErrorComponent::Server,
332        adk_core::ErrorCategory::NotFound,
333        NOT_FOUND_CODE,
334        format!("no area `{id}` on this kernel; its areas are {names}"),
335    )))
336}
337
338/// What `partition` started with on `kernel`.
339pub(crate) async fn start_of(kernel: &Kernel, partition: &PartitionId) -> Result<Start> {
340    let config = kernel.config();
341    let record = kernel.partitions().get(partition).await?;
342    let quiet = config
343        .quiet_hours
344        .into_iter()
345        .chain(record.as_ref().and_then(|record| record.quiet_hours))
346        .collect();
347    let cap = match &record {
348        Some(record) => config.quotas.stricter(&record.quotas).daily_spend_cap,
349        None => config.quotas.daily_spend_cap,
350    };
351    // The mode the area's harness started in governs it until the next start, whatever the
352    // partition record says now.
353    let mode = config
354        .control
355        .start_modes
356        .get(partition)
357        .copied()
358        .or_else(|| record.as_ref().map(|record| record.default_mode));
359    Ok(Start { quiet, beside: config.proactivity.quiet_hours.into_iter().collect(), cap, mode })
360}
361
362/// The settings in force in `partition` on `kernel`.
363pub(crate) async fn view(
364    kernel: &Kernel,
365    store: &dyn ControlStore,
366    partition: &PartitionId,
367) -> Result<AreaView> {
368    let start = start_of(kernel, partition).await?;
369    let changed = store.area_settings(partition).await?;
370    let quiet_time =
371        match changed.as_ref().and_then(|settings| settings.quiet_time_over(&start.quiet)) {
372            Some(change) => change.value.into_iter().collect(),
373            None => start.quiet.clone(),
374        };
375    let daily_spending_limit = spend_cap(start.cap, changed.as_ref());
376    let mode = changed_mode(start.mode, changed.as_ref(), &kernel.config().control);
377    let changed = changed.and_then(|settings| in_force(settings, &start.area()));
378    let sup = kernel.supervision();
379    let today = sup.clock.now().date_naive();
380    let scope = crate::stores::SpendScope::Partition(partition.clone());
381    let primary = kernel.partition_of_target(&kernel.config().app_name);
382    Ok(AreaView {
383        partition: partition.clone(),
384        primary: primary.unwrap_or(&PartitionId::default()) == partition,
385        quiet_time,
386        also_quiet: start.beside,
387        daily_spending_limit,
388        spent_today: sup.processes.spend(&scope, today, today).await?,
389        mode: mode.or(start.mode),
390        changed,
391    })
392}
393
394impl Kernel {
395    /// The settings in force in `partition` (spec 3.3 §10 K3), as
396    /// `GET /kernel/settings/{partition}` answers them: quiet time, the daily spending limit
397    /// with what was spent today, the mode, and whether the primary agent works there.
398    ///
399    /// # Example
400    ///
401    /// ```rust
402    /// use adk_kernel::{Kernel, PartitionId};
403    ///
404    /// # async fn example(kernel: &Kernel) -> adk_kernel::Result<()> {
405    /// let area = kernel.area_settings(&PartitionId::default()).await?;
406    /// let left = area.daily_spending_limit.map(|limit| limit.saturating_sub(area.spent_today));
407    /// # let _ = left;
408    /// # Ok(())
409    /// # }
410    /// ```
411    ///
412    /// # Errors
413    ///
414    /// Returns a store error when the partition table, the control store or the spend totals
415    /// cannot be read.
416    pub async fn area_settings(&self, partition: &PartitionId) -> Result<AreaView> {
417        let store = self.config().control.control_store.clone();
418        view(self, store.as_ref(), partition).await
419    }
420}
421
422async fn list(State(backend): Backend, caller: Caller) -> Result<Json<SettingsResponse>> {
423    caller.require_operator("read the settings")?;
424    let kernel = kernel_of(backend.as_ref())?;
425    let store = kernel.config().control.control_store.clone();
426    let mut views = Vec::new();
427    for area in areas(kernel, store.as_ref()).await? {
428        views.push(view(kernel, store.as_ref(), &area).await?);
429    }
430    Ok(Json(SettingsResponse { areas: views }))
431}
432
433async fn one(
434    State(backend): Backend,
435    caller: Caller,
436    UrlPath(partition): UrlPath<String>,
437) -> Result<Json<AreaResponse>> {
438    caller.require_operator("read the settings")?;
439    let kernel = kernel_of(backend.as_ref())?;
440    let store = kernel.config().control.control_store.clone();
441    let partition = known_area(kernel, store.as_ref(), partition).await?;
442    Ok(Json(AreaResponse { area: view(kernel, store.as_ref(), &partition).await? }))
443}
444
445/// What a change of one setting does to an area's record: it sets the change, made by
446/// `by` at `at`.
447type Set = Box<dyn Fn(&mut AreaSettings, &str, chrono::DateTime<chrono::Utc>) + Send + Sync>;
448
449/// A change of one setting.
450struct Setting {
451    /// The record's action, such as `settings.quiet_time`.
452    action: &'static str,
453    /// The admission label of the processes it releases, which meet it at their next step.
454    readmit: Option<&'static str>,
455    /// The setting's value in the area before.
456    from: fn(&AreaView) -> serde_json::Value,
457    /// Its value after.
458    to: serde_json::Value,
459    /// The mode it sets, which [`check_mode`] admits first.
460    mode: Option<PartitionMode>,
461    /// What it does to the area's record.
462    set: Set,
463}
464
465/// Whether an agent of `partition` is working now: a process of the area, not one of the
466/// kernel's own, is running.
467async fn working(kernel: &Kernel, partition: &PartitionId) -> Result<bool> {
468    let sup = kernel.supervision();
469    let filter = adk_core::RunFilter::default()
470        .app_name(kernel.config().app_name.clone())
471        .states([adk_core::RunState::Running]);
472    let running = sup.runs.list(filter).await?;
473    for run in running.iter().filter(|run| !run.target.starts_with("kernel.")) {
474        let area = sup.processes.get(&run.run_id).await?.map(|meta| meta.partition);
475        if area.unwrap_or_default() == *partition {
476            return Ok(true);
477        }
478    }
479    Ok(false)
480}
481
482/// Refuses a mode the kernel refuses, and a looser mode than `before`, the area's, while an
483/// agent of the area is working: a loosening applies from an agent's next turn, never midway
484/// through one (spec 3.1 I14, spec 3.3 §10 K3).
485async fn check_mode(
486    kernel: &Kernel,
487    partition: &PartitionId,
488    before: Option<PartitionMode>,
489    mode: PartitionMode,
490) -> Result<()> {
491    if let Some(reason) = kernel.config().control.refused_mode(mode) {
492        return Err(KernelError::Config { reason: reason.to_string() });
493    }
494    let loosens = match before {
495        Some(before) => strictness(mode) < strictness(before),
496        None => mode != PartitionMode::ReadOnly,
497    };
498    if loosens && working(kernel, partition).await? {
499        return Err(KernelError::Core(adk_core::AdkError::new(
500            adk_core::ErrorComponent::Server,
501            adk_core::ErrorCategory::Conflict,
502            crate::error::INVALID_STATE_CODE,
503            format!(
504                "an agent in area `{partition}` is working: let its agents do more once it \
505                 finishes, so no turn changes its rules midway"
506            ),
507        )));
508    }
509    Ok(())
510}
511
512/// Records the change with the setting's value before and after, stores it in the area's
513/// record, after dropping the changes the area's start values have replaced, wakes the
514/// processes admission held for it so they meet it at their next step, and answers with the
515/// area after it.
516async fn change(
517    backend: &dyn ControlBackend,
518    caller: &Caller,
519    partition: String,
520    setting: Setting,
521) -> Result<Json<AreaResponse>> {
522    require_owner(
523        caller,
524        &format!("change {}", setting.action.trim_start_matches("settings.").replace('_', " ")),
525    )?;
526    let kernel = kernel_of(backend)?;
527    let store = kernel.config().control.control_store.clone();
528    let partition = known_area(kernel, store.as_ref(), partition).await?;
529    let before = view(kernel, store.as_ref(), &partition).await?;
530    if let Some(mode) = setting.mode {
531        check_mode(kernel, &partition, before.mode, mode).await?;
532    }
533    let extra = [("from", (setting.from)(&before)), ("to", setting.to.clone())];
534    record(backend, caller, setting.action, Some(partition.as_str()), &extra).await?;
535    let start = start_of(kernel, &partition).await?.area();
536    let (by, at) = (caller.context.user_id.as_str(), kernel.config().clock.now());
537    let set = &setting.set;
538    store
539        .update_area_settings(&partition, &|settings: &mut AreaSettings| {
540            settings.settle(&start);
541            set(settings, by, at);
542        })
543        .await?;
544    if let Some(reason) = setting.readmit {
545        let filter = crate::stores::ProcessFilter::default().partition(partition.clone());
546        kernel.supervision().readmit(&filter, &[reason]).await;
547    }
548    Ok(Json(AreaResponse { area: view(kernel, store.as_ref(), &partition).await? }))
549}
550
551async fn set_quiet_time(
552    State(backend): Backend,
553    caller: Caller,
554    UrlPath(partition): UrlPath<String>,
555    Json(request): Json<QuietTimeRequest>,
556) -> Result<Json<AreaResponse>> {
557    let window = request.window;
558    if let Some(window) = window
559        && window.start == window.end
560    {
561        return Err(KernelError::Config {
562            reason: "quiet time needs a start and an end that differ; send `null` to turn it off"
563                .into(),
564        });
565    }
566    let setting = Setting {
567        action: "settings.quiet_time",
568        readmit: Some("quiet_hours"),
569        from: |before| json!(before.quiet_time),
570        to: json!(window),
571        mode: None,
572        set: Box::new(move |settings, by, at| {
573            settings.change_quiet_time(Change::new(window, by, at));
574        }),
575    };
576    change(backend.as_ref(), &caller, partition, setting).await
577}
578
579async fn set_spending_limit(
580    State(backend): Backend,
581    caller: Caller,
582    UrlPath(partition): UrlPath<String>,
583    Json(request): Json<SpendingLimitRequest>,
584) -> Result<Json<AreaResponse>> {
585    let limit = request.micro_usd;
586    let setting = Setting {
587        action: "settings.spending_limit",
588        readmit: Some("budget"),
589        from: |before| json!(before.daily_spending_limit),
590        to: json!(limit),
591        mode: None,
592        set: Box::new(move |settings, by, at| {
593            settings.daily_spending_limit = Some(Change::new(limit, by, at));
594        }),
595    };
596    change(backend.as_ref(), &caller, partition, setting).await
597}
598
599async fn set_mode(
600    State(backend): Backend,
601    caller: Caller,
602    UrlPath(partition): UrlPath<String>,
603    Json(request): Json<PartitionModeRequest>,
604) -> Result<Json<AreaResponse>> {
605    let mode = request.mode;
606    let setting = Setting {
607        action: "settings.mode",
608        readmit: None,
609        from: |before| json!(before.mode),
610        to: json!(mode),
611        mode: Some(mode),
612        set: Box::new(move |settings, by, at| settings.mode = Some(Change::new(mode, by, at))),
613    };
614    change(backend.as_ref(), &caller, partition, setting).await
615}
616
617#[cfg(test)]
618mod tests {
619    use chrono::Utc;
620
621    use super::*;
622
623    fn window(text: &str) -> QuietHours {
624        text.parse().unwrap()
625    }
626
627    #[test]
628    fn a_changed_window_replaces_the_start_windows_and_keeps_the_workspace_one() {
629        let kernel = Some(window("22:00-07:00"));
630        let beside = Some(window("12:00-13:00"));
631        let record = Partition::new("work", "work").with_quiet_hours(window("19:00-08:00"));
632        assert_eq!(
633            quiet_windows(kernel, beside, Some(&record), None),
634            [window("22:00-07:00"), window("19:00-08:00"), window("12:00-13:00")]
635        );
636        let changed = AreaSettings::new("work").with_quiet_time(Change::new(
637            Some(window("23:00-06:00")),
638            "ana",
639            Utc::now(),
640        ));
641        assert_eq!(
642            quiet_windows(kernel, beside, Some(&record), Some(&changed)),
643            [window("23:00-06:00"), window("12:00-13:00")]
644        );
645        let off = AreaSettings::new("work").with_quiet_time(Change::new(None, "ana", Utc::now()));
646        assert_eq!(
647            quiet_windows(kernel, beside, Some(&record), Some(&off)),
648            [window("12:00-13:00")]
649        );
650    }
651
652    /// A window kept in a named time zone keeps its local times when the clocks change,
653    /// where a fixed offset moves it by an hour (spec 3.3 §10 K3).
654    #[test]
655    fn a_window_in_a_time_zone_follows_daylight_saving_time() {
656        use chrono::TimeZone;
657
658        let body: QuietTimeRequest = serde_json::from_value(json!({
659            "window": { "start": "22:00", "end": "07:00", "timeZone": "Europe/London" }
660        }))
661        .unwrap();
662        let zoned = body.window.unwrap();
663        assert_eq!(serde_json::to_value(zoned).unwrap()["timeZone"], "Europe/London");
664        // Saved in summer from a browser at UTC+1.
665        let fixed = window("22:00-07:00").with_utc_offset_minutes(60);
666        let summer = Utc.with_ymd_and_hms(2026, 7, 1, 21, 30, 0).unwrap();
667        let winter = Utc.with_ymd_and_hms(2026, 12, 1, 21, 30, 0).unwrap();
668        assert!(zoned.contains(summer) && fixed.contains(summer), "22:30 in London");
669        assert!(!zoned.contains(winter), "21:30 in London: not quiet yet");
670        assert!(fixed.contains(winter), "a fixed offset has moved the window by an hour");
671        assert_eq!(
672            zoned.release_at(Utc.with_ymd_and_hms(2026, 12, 2, 6, 0, 0).unwrap()),
673            Utc.with_ymd_and_hms(2026, 12, 2, 7, 0, 0).unwrap()
674        );
675        let error = serde_json::from_value::<QuietTimeRequest>(json!({
676            "window": { "start": "22:00", "end": "07:00", "timeZone": "Mars/Olympus" }
677        }))
678        .unwrap_err();
679        assert!(error.to_string().contains("IANA"), "{error}");
680    }
681
682    #[test]
683    fn a_changed_limit_replaces_the_start_cap() {
684        assert_eq!(spend_cap(Some(5), None), Some(5));
685        let raised = AreaSettings::new("default").with_daily_spending_limit(Change::new(
686            Some(9),
687            "ana",
688            Utc::now(),
689        ));
690        assert_eq!(spend_cap(Some(5), Some(&raised)), Some(9));
691        let removed = AreaSettings::new("default").with_daily_spending_limit(Change::new(
692            None,
693            "ana",
694            Utc::now(),
695        ));
696        assert_eq!(spend_cap(Some(5), Some(&removed)), None);
697        let mode_only = AreaSettings::new("default").with_mode(Change::new(
698            PartitionMode::Auto,
699            "ana",
700            Utc::now(),
701        ));
702        assert_eq!(spend_cap(Some(5), Some(&mode_only)), Some(5), "another change keeps the cap");
703    }
704}