wsb-daemon 0.291.8591

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the host
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
//! Settings, in two places, because they belong to two things.
//!
//! * The WORKSHOP's — `/api/v1/settings`: how sessions are resumed in a
//!   terminal, how big each worktree's logs may grow, where the daemon is
//!   served, where agents' sessions are read from. Kept in `config.toml` in
//!   this host's folder of `$PRJ/.state`, or reported. They are the same whichever worktree
//!   is open, and readable with none open.
//! * A WORKTREE's — `/api/v1/worktrees/{id}/settings`: what its repository and
//!   project commit about themselves (`.wsb/repo.json`, `.wsb/project.json`),
//!   and what its own logs hold.
//!
//! They were one answer under each worktree, so with no worktree open none of
//! them could be read, not even the workshop's.

use wsb::prelude::*;
use axum::{
    extract::State,
    http::StatusCode,
    routing::get,
    Json, Router,
};
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::Arc,
};

use super::sessions::ErrorResponse;
use crate::workshop::WorkshopState;
use crate::web::home_dir;
use crate::web::state::WebState;
use wsb::settings::{ProjectSettings, RepoSettings};

#[derive(Debug, Serialize, Deserialize)]
pub struct TerminalSettings {
    pub mode: String,
    #[serde(default)]
    pub custom_bin: Option<String>,
    #[serde(default)]
    pub custom_args: Option<String>,
}

impl Default for TerminalSettings {
    fn default() -> Self {
        Self {
            mode: "auto".to_string(),
            custom_bin: None,
            custom_args: None,
        }
    }
}

/// Where this daemon is actually serving from.
///
/// Reported, never set. Which address the workbench is reachable on is decided
/// when the daemon starts — `wsb serve --listen` — and not by anything a page
/// can switch on.
///
/// It used to carry a `remote_access` flag the page could toggle and persist.
/// Nothing read it: the server bound loopback either way, so the toggle
/// promised remote access it never delivered — and had anything honoured it,
/// a box ticked once would have quietly reopened the port on every restart
/// afterwards.
#[derive(Debug, Serialize, Deserialize)]
pub struct ServerSettings {
    /// The bound address: `127.0.0.1` for a daemon only this host can
    /// reach, `0.0.0.0` for one every interface can.
    pub host: String,
    pub port: u16,
    /// Whether that address reaches beyond this host. Derived from `host`
    /// rather than stored, so it cannot disagree with where the socket is.
    pub reachable_remotely: bool,
}

/// A worktree's committed settings, and where each file is: the page edits
/// a file somebody then commits.
#[derive(Debug, Serialize, Deserialize)]
pub struct CommittedSettings<T> {
    /// The file the settings are in.
    pub path: String,
    pub settings: T,
}

/// How big each worktree's logs directory may grow: the workshop's one limit.
#[derive(Debug, Serialize, Deserialize)]
pub struct LogsLimit {
    /// The ceiling on each worktree's whole directory. Older entries are
    /// removed as it is approached, oldest first.
    pub max_bytes: u64,
    /// The smallest limit that may be set, so the page can say so rather than
    /// letting a value be rejected after it is typed.
    pub min_bytes: u64,
}

/// One worktree's logs directory: where it is, the limit it is held to, and
/// what it holds.
///
/// Every operation started from the workbench is written to a file there, so
/// the limit decides how much of the past a page can still show. The root is
/// reported and not settable — it is in the worktree's local state — and the
/// usage is measured on every read rather than remembered, because the thing
/// it describes is a directory that other processes also write to.
#[derive(Debug, Serialize, Deserialize)]
pub struct LogsSettings {
    /// Absolute path of the logs root.
    pub root: String,
    /// The workshop's limit, which this directory is held to.
    pub max_bytes: u64,
    pub usage: wsb::logs::Usage,
}

/// Workshop settings: the same whichever worktree is open.
#[derive(Debug, Serialize, Deserialize)]
pub struct WorkshopSettings {
    pub agent_dirs: HashMap<String, Vec<String>>,
    pub terminal: TerminalSettings,
    pub server: ServerSettings,
    pub logs: LogsLimit,
    /// How the workbench looks, in every browser that opens it; null until
    /// one is chosen.
    pub appearance: Option<AppearanceSettings>,
}

/// The densities, message layouts and transcript blocks the workbench has.
pub const DENSITIES: [&str; 4] = ["compact", "default", "comfortable", "spacious"];
pub const MESSAGE_LAYOUTS: [&str; 3] = ["default", "compact", "stream"];
pub const BLOCKS: [&str; 5] = ["user", "assistant", "thinking", "tool", "code"];

/// How the workbench looks: kept with the workshop rather than in a browser,
/// so another browser or another device opens it looking the same.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AppearanceSettings {
    /// `auto`, which follows the system's light or dark, or a theme's label.
    pub theme: String,
    /// One of [`DENSITIES`].
    pub density: String,
    /// One of [`MESSAGE_LAYOUTS`].
    pub message_layout: String,
    /// The transcript blocks not shown, each one of [`BLOCKS`].
    #[serde(default)]
    pub hidden_blocks: Vec<String>,
}


/// One worktree's settings.
#[derive(Debug, Serialize, Deserialize)]
pub struct WorktreeSettings {
    /// The worktree's root.
    pub root: String,
    /// `.wsb/repo.json` of the worktree's main repo.
    pub repo: CommittedSettings<RepoSettings>,
    /// `.wsb/project.json` of the worktree's main repo.
    pub project: CommittedSettings<ProjectSettings>,
    pub logs: LogsSettings,
}

/// What a page changes of workshop settings.
///
/// Unknown parts are refused rather than ignored: a page that sends a
/// worktree's committed settings here would otherwise be told they were saved.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateWorkshopSettingsRequest {
    #[serde(default)]
    pub terminal: Option<TerminalSettingsUpdate>,
    #[serde(default)]
    pub logs: Option<LogsSettingsUpdate>,
    /// Written whole.
    #[serde(default)]
    pub appearance: Option<AppearanceSettings>,
}

/// What a page changes of a worktree's settings, each part whole: the
/// repository's or the project's committed settings replace the file, after
/// being checked as a hand edit would be. Unknown parts are refused, as the
/// workshop's are.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateWorktreeSettingsRequest {
    #[serde(default)]
    pub repo: Option<RepoSettings>,
    #[serde(default)]
    pub project: Option<ProjectSettings>,
}

#[derive(Debug, Deserialize)]
pub struct LogsSettingsUpdate {
    pub max_bytes: u64,
}

#[derive(Debug, Deserialize)]
pub struct TerminalSettingsUpdate {
    pub mode: String,
    #[serde(default)]
    pub custom_bin: Option<String>,
    #[serde(default)]
    pub custom_args: Option<String>,
}

#[derive(Default)]
struct UserConfig {
    terminal: TerminalSettings,
    logs: LogsConfig,
    appearance: Option<AppearanceSettings>,
}

/// The part of the logs policy a person sets. Everything else about the
/// directory is measured or declared.
#[derive(Debug, Clone, Copy)]
struct LogsConfig {
    max_bytes: u64,
}

impl Default for LogsConfig {
    fn default() -> Self {
        Self {
            max_bytes: wsb::logs::DEFAULT_MAX_BYTES,
        }
    }
}

/// The limit in force, for the sweeper — which runs on a timer and has no
/// request to read it from.
///
/// Read from the file on every call rather than cached: the limit is changed
/// from a page, and a sweeper holding a copy from startup would keep enforcing
/// the old number until the daemon restarted.
pub fn configured_max_bytes() -> u64 {
    load_user_config()
        .map(|config| config.logs.max_bytes)
        .unwrap_or(wsb::logs::DEFAULT_MAX_BYTES)
        .max(wsb::logs::MIN_MAX_BYTES)
}

/// A worktree wsb does not manage has no settings to read or write: an
/// ordinary state of a checkout `prj` made, refused by name rather than
/// failing as an error of the server's.
fn require_set_up(root: &Path) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
    if RepoSettings::exists(root) {
        Ok(())
    } else {
        Err((
            StatusCode::CONFLICT,
            Json(ErrorResponse {
                error: format!(
                    "wsb is not set up in {}: run `wsb init` there to give it settings",
                    root.display()
                ),
            }),
        ))
    }
}

/// Workshop settings, at the workshop's address rather than a worktree's.
pub fn workshop_routes() -> Router<Arc<WorkshopState>> {
    Router::new().route("/api/v1/settings", get(get_workshop_settings).put(update_workshop_settings))
}

pub async fn get_workshop_settings(
    State(workshop): State<Arc<WorkshopState>>,
) -> Result<Json<WorkshopSettings>, (StatusCode, Json<ErrorResponse>)> {
    load_workshop_settings(workshop.listen, workshop.port)
        .await
        .map(Json)
        .map_err(internal_error)
}

pub async fn update_workshop_settings(
    State(workshop): State<Arc<WorkshopState>>,
    Json(body): Json<UpdateWorkshopSettingsRequest>,
) -> Result<Json<WorkshopSettings>, (StatusCode, Json<ErrorResponse>)> {
    validate_workshop_update(&body).map_err(refused)?;
    let swept = body.logs.is_some();
    write_workshop_settings(body).await.map_err(internal_error)?;
    if swept {
        // Enforced NOW, in every worktree open here. A new limit that takes
        // effect at the next operation is a limit somebody lowers to reclaim
        // disk and then watches not reclaim any, with nothing to say why. A
        // worktree not open yet is swept when it opens.
        for worktree in workshop.all().await {
            crate::web::log_janitor::sweep_now(&worktree.web).await;
        }
    }
    get_workshop_settings(State(workshop)).await
}

pub async fn get_settings(
    State(state): State<WebState>,
) -> Result<Json<WorktreeSettings>, (StatusCode, Json<ErrorResponse>)> {
    let repo_root = worktree_root_of(&state);
    require_set_up(&repo_root)?;
    let settings = load_worktree_settings(&repo_root)
        .await
        .map_err(internal_error)?;
    Ok(Json(settings))
}

pub async fn update_settings(
    State(state): State<WebState>,
    Json(body): Json<UpdateWorktreeSettingsRequest>,
) -> Result<Json<WorktreeSettings>, (StatusCode, Json<ErrorResponse>)> {
    let repo_root = worktree_root_of(&state);
    require_set_up(&repo_root)?;
    write_committed(&repo_root, body.repo, body.project)
        .await
        .map_err(internal_error)?;
    get_settings(State(state)).await
}

async fn load_workshop_settings(listen: std::net::IpAddr, port: u16) -> anyhow::Result<WorkshopSettings> {
    let user_config = tokio::task::spawn_blocking(load_user_config).await??;
    Ok(WorkshopSettings {
        agent_dirs: load_agent_dirs()?,
        terminal: user_config.terminal,
        server: ServerSettings {
            host: listen.to_string(),
            port,
            reachable_remotely: !listen.is_loopback(),
        },
        logs: LogsLimit {
            max_bytes: user_config.logs.max_bytes,
            min_bytes: wsb::logs::MIN_MAX_BYTES,
        },
        appearance: user_config.appearance,
    })
}

async fn load_worktree_settings(repo_root: &Path) -> anyhow::Result<WorktreeSettings> {
    let logs = logs_settings(repo_root).await?;
    let root = repo_root.to_path_buf();
    let (repo, project) = tokio::task::spawn_blocking(move || {
        anyhow::Ok((RepoSettings::require(&root)?, ProjectSettings::load(&root)?))
    })
    .await??;

    Ok(WorktreeSettings {
        root: repo_root.display().to_string(),
        repo: CommittedSettings {
            path: RepoSettings::path(repo_root).display().to_string(),
            settings: repo,
        },
        project: CommittedSettings {
            path: ProjectSettings::path(repo_root).display().to_string(),
            settings: project,
        },
        logs,
    })
}

/// Where a worktree's logs are, what they may grow to, and what they hold
/// right now.
///
/// The usage is a walk of the directory, so it happens off the runtime: a
/// settings page that blocked the server while counting a gigabyte of test
/// sessions would be a settings page that hangs on the hosts it matters on.
async fn logs_settings(repo_root: &Path) -> anyhow::Result<LogsSettings> {
    let root = repo_root.to_path_buf();
    let (logs_root, usage, max_bytes) = tokio::task::spawn_blocking(move || {
        let logs_root = wsb::logs::root(&root)?;
        let usage = wsb::logs::usage(&logs_root);
        anyhow::Ok((logs_root, usage, configured_max_bytes()))
    })
    .await??;
    Ok(LogsSettings {
        root: logs_root.display().to_string(),
        max_bytes,
        usage,
    })
}

/// Write the committed settings a change names, each file whole.
async fn write_committed(
    repo_root: &Path,
    repo: Option<RepoSettings>,
    project: Option<ProjectSettings>,
) -> anyhow::Result<()> {
    let root = repo_root.to_path_buf();
    tokio::task::spawn_blocking(move || {
        if let Some(repo) = repo {
            repo.save(&root)?;
        }
        if let Some(project) = project {
            project.save(&root)?;
        }
        anyhow::Ok(())
    })
    .await?
}

/// Whether a change to workshop settings can be written at all, checked
/// before any of it is.
fn validate_workshop_update(body: &UpdateWorkshopSettingsRequest) -> anyhow::Result<()> {
    if let Some(logs) = &body.logs {
        validate_logs_update(logs.max_bytes)?;
    }
    if let Some(terminal) = &body.terminal {
        validate_terminal_settings(terminal)?;
    }
    if let Some(appearance) = &body.appearance {
        validate_appearance(appearance)?;
    }
    Ok(())
}

/// Write a checked change into `config.toml`.
async fn write_workshop_settings(body: UpdateWorkshopSettingsRequest) -> anyhow::Result<()> {
    tokio::task::spawn_blocking(move || {
        update_user_config(|table| {
            if let Some(logs) = &body.logs {
                set_logs_table(table, logs.max_bytes);
            }
            if let Some(appearance) = &body.appearance {
                set_appearance_table(table, appearance);
            }
            if let Some(terminal) = &body.terminal {
                set_terminal_table(
                    table,
                    &TerminalSettings {
                        mode: terminal.mode.clone(),
                        custom_bin: terminal.custom_bin.clone(),
                        custom_args: terminal.custom_args.clone(),
                    },
                );
            }
        })
    })
    .await?
}

fn load_agent_dirs() -> anyhow::Result<HashMap<String, Vec<String>>> {
    let home = home_dir()?;
    let mut dirs = HashMap::new();
    dirs.insert(
        "claude".to_string(),
        vec![home.join(".claude").join("projects").display().to_string()],
    );
    Ok(dirs)
}

fn load_user_config() -> anyhow::Result<UserConfig> {
    let path = user_config_path()?;
    if !path.exists() {
        return Ok(UserConfig::default());
    }

    let content = std::fs::read_to_string(&path)?;
    let table: toml::Table = content.parse()?;

    let terminal = table
        .get("terminal")
        .and_then(toml::Value::as_table)
        .map(parse_terminal_table)
        .transpose()?
        .unwrap_or_default();

    // A limit below the floor is raised to it rather than refused: the file is
    // hand-editable, and a daemon that will not start because somebody typed a
    // small number is worse than one that says what it is enforcing.
    let logs = table
        .get("logs")
        .and_then(toml::Value::as_table)
        .and_then(|logs| logs.get("max_bytes"))
        .and_then(toml::Value::as_integer)
        .filter(|bytes| *bytes > 0)
        .map(|bytes| LogsConfig {
            max_bytes: (bytes as u64).max(wsb::logs::MIN_MAX_BYTES),
        })
        .unwrap_or_default();

    let appearance = match table.get("appearance") {
        None => None,
        Some(toml::Value::Table(appearance)) => {
            Some(parse_appearance_table(appearance).with_context(|| format!("reading {}", path.display()))?)
        }
        Some(_) => anyhow::bail!("reading {}: [appearance] is a table", path.display()),
    };

    Ok(UserConfig { terminal, logs, appearance })
}

/// The appearance `config.toml` names, checked as a change from a page is: a
/// value the workbench does not have is refused, naming it, rather than read
/// as something else.
fn parse_appearance_table(table: &toml::Table) -> anyhow::Result<AppearanceSettings> {
    let appearance: AppearanceSettings = toml::Value::Table(table.clone())
        .try_into()
        .context("[appearance] is not an appearance")?;
    validate_appearance(&appearance).context("[appearance]")?;
    Ok(appearance)
}

fn validate_appearance(appearance: &AppearanceSettings) -> anyhow::Result<()> {
    if appearance.theme.trim().is_empty() {
        anyhow::bail!("appearance.theme is `auto` or a theme's label, not empty");
    }
    if !DENSITIES.contains(&appearance.density.as_str()) {
        anyhow::bail!("appearance.density must be one of {}; got '{}'", DENSITIES.join(", "), appearance.density);
    }
    if !MESSAGE_LAYOUTS.contains(&appearance.message_layout.as_str()) {
        anyhow::bail!(
            "appearance.message_layout must be one of {}; got '{}'",
            MESSAGE_LAYOUTS.join(", "),
            appearance.message_layout
        );
    }
    if let Some(block) = appearance.hidden_blocks.iter().find(|block| !BLOCKS.contains(&block.as_str())) {
        anyhow::bail!("appearance.hidden_blocks names {}; blocks are {}", block, BLOCKS.join(", "));
    }
    Ok(())
}

fn set_appearance_table(table: &mut toml::Table, appearance: &AppearanceSettings) {
    let mut written = toml::Table::new();
    written.insert("theme".to_string(), toml::Value::String(appearance.theme.clone()));
    written.insert("density".to_string(), toml::Value::String(appearance.density.clone()));
    written.insert("message_layout".to_string(), toml::Value::String(appearance.message_layout.clone()));
    written.insert(
        "hidden_blocks".to_string(),
        toml::Value::Array(appearance.hidden_blocks.iter().cloned().map(toml::Value::String).collect()),
    );
    table.insert("appearance".to_string(), toml::Value::Table(written));
}

fn parse_terminal_table(table: &toml::Table) -> anyhow::Result<TerminalSettings> {
    let mode = table
        .get("mode")
        .and_then(toml::Value::as_str)
        .unwrap_or("auto")
        .to_string();
    let custom_bin = table
        .get("custom_bin")
        .and_then(toml::Value::as_str)
        .map(ToString::to_string);
    let custom_args = table
        .get("custom_args")
        .and_then(toml::Value::as_str)
        .map(ToString::to_string);

    let terminal = TerminalSettings {
        mode,
        custom_bin,
        custom_args,
    };
    validate_terminal_settings(&TerminalSettingsUpdate {
        mode: terminal.mode.clone(),
        custom_bin: terminal.custom_bin.clone(),
        custom_args: terminal.custom_args.clone(),
    })?;
    Ok(terminal)
}

fn validate_terminal_settings(terminal: &TerminalSettingsUpdate) -> anyhow::Result<()> {
    match terminal.mode.as_str() {
        "auto" | "custom" | "clipboard" => {}
        other => anyhow::bail!(
            "terminal.mode must be one of auto, custom, clipboard; got '{}'",
            other
        ),
    }
    if terminal.mode == "custom" {
        if terminal
            .custom_bin
            .as_ref()
            .map(|value| value.trim().is_empty())
            .unwrap_or(true)
        {
            anyhow::bail!("terminal.custom_bin is required when terminal.mode is 'custom'");
        }
    }
    Ok(())
}

/// Refuse a limit that would make the workbench appear to lose output.
///
/// Separate from the handler so it can be tested without a server: the number
/// is the only part of this that can be wrong in a way somebody notices weeks
/// later, as logs that vanish while they are being read.
fn validate_logs_update(max_bytes: u64) -> anyhow::Result<()> {
    if max_bytes < wsb::logs::MIN_MAX_BYTES {
        anyhow::bail!(
            "the logs limit cannot be below {} — a limit smaller than one run's output \
             removes the log a page is showing as fast as it is written",
            wsb::logs::human_bytes(wsb::logs::MIN_MAX_BYTES)
        );
    }
    Ok(())
}

/// Write the logs limit into the user's config file.
fn set_logs_table(table: &mut toml::Table, max_bytes: u64) {
    let logs_table = table
        .entry("logs".to_string())
        .or_insert_with(|| toml::Value::Table(toml::Table::new()));
    let logs_table = logs_table
        .as_table_mut()
        .expect("logs entry must remain a table");
    logs_table.insert(
        "max_bytes".to_string(),
        toml::Value::Integer(max_bytes as i64),
    );
}

fn set_terminal_table(table: &mut toml::Table, terminal: &TerminalSettings) {
    let terminal_table = table
        .entry("terminal".to_string())
        .or_insert_with(|| toml::Value::Table(toml::Table::new()));
    let terminal_table = terminal_table
        .as_table_mut()
        .expect("terminal entry must remain a table");
    terminal_table.insert(
        "mode".to_string(),
        toml::Value::String(terminal.mode.clone()),
    );
    match &terminal.custom_bin {
        Some(custom_bin) => {
            terminal_table.insert(
                "custom_bin".to_string(),
                toml::Value::String(custom_bin.clone()),
            );
        }
        None => {
            terminal_table.remove("custom_bin");
        }
    }
    match &terminal.custom_args {
        Some(custom_args) => {
            terminal_table.insert(
                "custom_args".to_string(),
                toml::Value::String(custom_args.clone()),
            );
        }
        None => {
            terminal_table.remove("custom_args");
        }
    }
}

fn update_user_config(mut apply: impl FnMut(&mut toml::Table)) -> anyhow::Result<()> {
    let path = user_config_path()?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut table: toml::Table = if path.exists() {
        std::fs::read_to_string(&path)?.parse()?
    } else {
        toml::Table::new()
    };
    apply(&mut table);
    std::fs::write(&path, toml::to_string_pretty(&table)?)?;
    Ok(())
}

/// Workshop settings: `config.toml` in this host's folder of `$PRJ/.state`,
/// beside the daemon that reads them.
fn user_config_path() -> anyhow::Result<PathBuf> {
    Ok(wsb::daemon::host_dir()
        .map_err(|e| anyhow::anyhow!(e))?
        .join("config.toml"))
}

/// The worktree these routes act on, from the state they were reached
/// through — not from the process's directory, which belongs to no worktree
/// now that one daemon serves the workshop.
fn worktree_root_of(state: &WebState) -> PathBuf {
    state.worktree_root.clone()
}

fn internal_error(error: impl std::fmt::Display) -> (StatusCode, Json<ErrorResponse>) {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(ErrorResponse {
            // The whole chain: what was being done, and why it failed.
            error: format!("{error:#}"),
        }),
    )
}

/// A change the page asked for that cannot be written: the page's to fix, so
/// not the server's error.
fn refused(error: impl std::fmt::Display) -> (StatusCode, Json<ErrorResponse>) {
    (
        StatusCode::UNPROCESSABLE_ENTITY,
        Json(ErrorResponse {
            // The whole chain: what was being done, and why it failed.
            error: format!("{error:#}"),
        }),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use wsb::test_environment::Environment;

    /// A repository wsb manages, as `wsb init` leaves it.
    fn managed(root: &Path) {
        wsb::git_backend::init_repository(root).unwrap();
        RepoSettings {
            name: "machinefabric".to_string(),
            alias: "mf".to_string(),
            templates_root: ".".to_string(),
            version: wsb::settings::VersionSettings::at_major(7),
        }
        .save(root)
        .unwrap();
    }

    /// TEST8997: the settings page reports the logs directory that is
    /// actually written to.
    ///
    /// A settings page that showed a different path — a remembered one, a
    /// default it computed itself — would send somebody to an empty directory
    /// to look for the log of an operation they just watched run.
    #[tokio::test]
    async fn test8997_the_reported_root_is_the_one_that_is_written() {
        let dir = tempfile::tempdir().unwrap();
        let workshop = tempfile::tempdir().unwrap();
        let _env = Environment::set(&[("PRJ", ""), (wsb::daemon::HOST_DIR_ENV, &workshop.path().to_string_lossy())]);
        let settings = logs_settings(dir.path()).await.expect("settings load");

        assert_eq!(settings.root, wsb::logs::root(dir.path()).unwrap().display().to_string());
        assert_eq!(settings.max_bytes, configured_max_bytes(), "the directory is held to the workshop's limit");
        // Every stream is named even when nothing has been written yet: a
        // page listing only non-empty ones reads as if the others do not
        // exist.
        for stream in wsb::logs::Stream::ALL {
            assert!(settings.usage.by_group.contains_key(stream.dir_name()));
        }
    }

    /// TEST8998: a limit below the floor is refused, and says why.
    #[test]
    fn test8998_a_limit_below_the_floor_is_refused() {
        let error = validate_logs_update(1024).expect_err("a 1 KB limit is not a limit");
        let message = error.to_string();
        assert!(message.contains("cannot be below"), "{message}");
        assert!(
            message.contains("removes the log a page is showing"),
            "the refusal has to say what would go wrong: {message}"
        );
        validate_logs_update(wsb::logs::MIN_MAX_BYTES).expect("the floor itself is allowed");
        validate_logs_update(wsb::logs::DEFAULT_MAX_BYTES).expect("the default is allowed");
    }

    /// TEST20117: a worktree's settings are its committed files, each named,
    /// and its own logs; what it writes back is the committed file, checked as
    /// a hand edit is. Workshop settings are not among them.
    #[test]
    fn test20117_a_worktrees_settings_are_its_committed_files() {
        let repo = TempDir::new().unwrap();
        let workshop = TempDir::new().unwrap();
        managed(repo.path());
        let _env = Environment::set(&[("PRJ", ""), (wsb::daemon::HOST_DIR_ENV, &workshop.path().to_string_lossy())]);
        let rt = tokio::runtime::Runtime::new().unwrap();
        let settings = rt.block_on(load_worktree_settings(repo.path())).unwrap();

        assert_eq!(settings.root, repo.path().display().to_string());
        assert_eq!(settings.repo.path, RepoSettings::path(repo.path()).display().to_string());
        assert_eq!((settings.repo.settings.alias.as_str(), settings.repo.settings.version.major), ("mf", 7));
        assert!(settings.project.settings.boards.is_empty());
        assert_eq!(settings.logs.root, wsb::logs::root(repo.path()).unwrap().display().to_string());
        let answer = serde_json::to_value(&settings).unwrap();
        for part in ["terminal", "server", "agent_dirs"] {
            assert!(answer.get(part).is_none(), "a worktree's settings carry the workshop's {part}");
        }

        // A change is written to the committed file, whole.
        let mut repo_settings = settings.repo.settings;
        repo_settings.version.major = 8;
        let project = ProjectSettings { boards: vec!["owner/7".to_string()], ignored_submodules: Vec::new() };
        rt.block_on(write_committed(repo.path(), Some(repo_settings), Some(project))).unwrap();
        let read = rt.block_on(load_worktree_settings(repo.path())).unwrap();
        assert_eq!(read.repo.settings.version.major, 8);
        assert_eq!(read.project.settings.boards, vec!["owner/7".to_string()]);

        // Workshop settings sent here are refused, not reported saved.
        let terminal = serde_json::json!({ "terminal": { "mode": "clipboard" } });
        assert!(serde_json::from_value::<UpdateWorktreeSettingsRequest>(terminal).is_err());

        // A worktree wsb does not manage has no settings to show.
        let plain = TempDir::new().unwrap();
        assert_eq!(require_set_up(plain.path()).unwrap_err().0, StatusCode::CONFLICT);
    }

    /// A daemon started with `--listen` reports where it actually is.
    #[test]
    fn server_settings_report_the_address_the_daemon_is_bound_to() {
        let workshop = TempDir::new().unwrap();
        let _env = Environment::set(&[("PRJ", ""), (wsb::daemon::HOST_DIR_ENV, &workshop.path().to_string_lossy())]);

        let rt = tokio::runtime::Runtime::new().unwrap();
        let settings = rt
            .block_on(load_workshop_settings(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 4123))
            .unwrap();

        assert_eq!(settings.server.host, "0.0.0.0");
        assert_eq!(settings.server.port, 4123);
        assert!(
            settings.server.reachable_remotely,
            "a daemon on every interface must say so: the page warns about it, \
             and nothing else in the workbench asks for a password"
        );
    }

    #[test]
    fn update_user_config_persists_terminal_settings() {
        let workshop = TempDir::new().unwrap();
        let _env = Environment::set(&[(wsb::daemon::HOST_DIR_ENV, &workshop.path().to_string_lossy())]);

        update_user_config(|table| {
            set_terminal_table(
                table,
                &TerminalSettings {
                    mode: "clipboard".to_string(),
                    custom_bin: None,
                    custom_args: None,
                },
            );
        })
        .unwrap();

        assert_eq!(load_user_config().unwrap().terminal.mode, "clipboard");
    }

    async fn call(router: &Router, method: &str, body: Option<serde_json::Value>) -> (StatusCode, serde_json::Value) {
        use tower::ServiceExt;
        let request = axum::http::Request::builder()
            .method(method)
            .uri("/api/v1/settings")
            .header("content-type", "application/json")
            .body(body.map_or_else(axum::body::Body::empty, |body| axum::body::Body::from(body.to_string())))
            .expect("a request");
        let response = router.clone().oneshot(request).await.expect("the router answers");
        let status = response.status();
        let bytes = hyper::body::to_bytes(response.into_body()).await.expect("a body");
        (status, serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null))
    }

    /// TEST20230: workshop settings are read and written at the workshop's
    /// address, with no worktree open: the terminal and the logs limit go to
    /// its `config.toml`, a change that cannot be written is refused before
    /// any of it is, and a worktree's committed settings sent there are
    /// refused rather than reported saved.
    ///
    /// They were one answer under each worktree, so with none open the
    /// workbench could not show its Settings at all, not even its appearance.
    #[tokio::test]
    async fn test20230_the_workshops_settings_need_no_worktree() {
        let host_dir = TempDir::new().unwrap();
        let _env = Environment::set(&[("PRJ", ""), (wsb::daemon::HOST_DIR_ENV, &host_dir.path().to_string_lossy())]);
        let workshop = WorkshopState::new(
            host_dir.path().to_path_buf(),
            &host_dir.path().join("wsb.db"),
            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            4123,
            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            0,
        )
        .expect("a workshop");
        assert!(workshop.all().await.is_empty(), "no worktree is open");
        let router = workshop_routes().with_state(workshop);

        let (status, read) = call(&router, "GET", None).await;
        assert_eq!(status, StatusCode::OK, "{read}");
        assert_eq!(read["terminal"]["mode"], "auto");
        assert_eq!(read["server"]["port"], 4123);
        assert_eq!(read["logs"]["max_bytes"], wsb::logs::DEFAULT_MAX_BYTES);
        assert_eq!(read["logs"]["min_bytes"], wsb::logs::MIN_MAX_BYTES);
        assert!(read.get("repo").is_none(), "workshop settings carry a worktree's: {read}");

        let limit = wsb::logs::MIN_MAX_BYTES * 2;
        let change = serde_json::json!({
            "terminal": { "mode": "custom", "custom_bin": "/usr/bin/kitty", "custom_args": "-- bash -lc {cmd}" },
            "logs": { "max_bytes": limit },
        });
        let (status, written) = call(&router, "PUT", Some(change)).await;
        assert_eq!(status, StatusCode::OK, "{written}");
        assert_eq!((written["terminal"]["mode"].as_str(), written["logs"]["max_bytes"].as_u64()), (Some("custom"), Some(limit)));
        let config = std::fs::read_to_string(host_dir.path().join("config.toml")).unwrap();
        assert!(config.contains("/usr/bin/kitty") && config.contains(&limit.to_string()), "{config}");
        assert_eq!(configured_max_bytes(), limit, "the sweeper does not see the new limit");

        // A terminal that cannot launch, beside a limit that could be written:
        // neither is.
        let (status, said) = call(
            &router,
            "PUT",
            Some(serde_json::json!({ "terminal": { "mode": "custom" }, "logs": { "max_bytes": limit * 2 } })),
        )
        .await;
        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{said}");
        assert!(said["error"].as_str().unwrap_or_default().contains("custom_bin"), "{said}");
        assert_eq!(std::fs::read_to_string(host_dir.path().join("config.toml")).unwrap(), config, "a refused change was written");

        let (status, said) = call(&router, "PUT", Some(serde_json::json!({ "repo": { "name": "x" } }))).await;
        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "a worktree's settings were taken as the workshop's: {said}");
    }

    /// TEST20232: the appearance is kept in the workshop's `config.toml`:
    /// none until one is chosen, what was chosen given back, a value the
    /// workbench does not have refused before anything is written, and a
    /// hand edit naming one refused when it is read, naming the key, rather
    /// than shown as something else.
    #[tokio::test]
    async fn test20232_the_appearance_is_kept_with_the_workshop() {
        let host_dir = TempDir::new().unwrap();
        let _env = Environment::set(&[("PRJ", ""), (wsb::daemon::HOST_DIR_ENV, &host_dir.path().to_string_lossy())]);
        let workshop = WorkshopState::new(
            host_dir.path().to_path_buf(),
            &host_dir.path().join("wsb.db"),
            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            4123,
            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            0,
        )
        .expect("a workshop");
        let router = workshop_routes().with_state(workshop);
        let config = host_dir.path().join("config.toml");

        let (status, read) = call(&router, "GET", None).await;
        assert_eq!(status, StatusCode::OK, "{read}");
        assert!(read["appearance"].is_null(), "an appearance nobody chose: {read}");

        let chosen = serde_json::json!({
            "theme": "WSB Dark",
            "density": "comfortable",
            "message_layout": "stream",
            "hidden_blocks": ["thinking", "tool"],
        });
        let (status, written) = call(&router, "PUT", Some(serde_json::json!({ "appearance": chosen }))).await;
        assert_eq!(status, StatusCode::OK, "{written}");
        assert_eq!(written["appearance"], chosen);
        assert_eq!(call(&router, "GET", None).await.1["appearance"], chosen, "the appearance was not kept");
        let kept = std::fs::read_to_string(&config).unwrap();
        assert!(kept.contains("[appearance]") && kept.contains("WSB Dark"), "{kept}");

        for (key, value) in [
            ("density", serde_json::json!("dense")),
            ("message_layout", serde_json::json!("grid")),
            ("hidden_blocks", serde_json::json!(["images"])),
            ("theme", serde_json::json!(" ")),
        ] {
            let mut refused = chosen.clone();
            refused[key] = value;
            let (status, said) = call(&router, "PUT", Some(serde_json::json!({ "appearance": refused }))).await;
            assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{key}: {said}");
            assert!(said["error"].as_str().unwrap_or_default().contains(key), "{key}: {said}");
            assert_eq!(std::fs::read_to_string(&config).unwrap(), kept, "a refused {key} was written");
        }

        std::fs::write(&config, kept.replace("comfortable", "roomy")).unwrap();
        let (status, said) = call(&router, "GET", None).await;
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "a density the workbench does not have was read: {said}");
        let message = said["error"].as_str().unwrap_or_default();
        assert!(message.contains("config.toml") && message.contains("density"), "{message}");
    }
}