snyvi 1.32.0

A fast, beautiful viewer for the documents your agents produce
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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
//! The sidebars' layout and their widgets over HTTP (`crate::widget`).
//!
//! The layout is the reader's: set from this page (or with the token, as
//! every reader's action may be), normalized, kept, and sent to every page
//! as a `layout` event, which reorders the sections it has in place.

use super::*;
use crate::widget::{self, Layout};
use axum::body::Bytes;

/// The layout, as every page draws it.
pub(crate) fn layout_json(app: &App) -> serde_json::Value {
    let l = app
        .store
        .clocked(|c, _| widget::layout(c))
        .unwrap_or_default();
    serde_json::to_value(l).unwrap_or_default()
}

/// The global widgets' seats, for every page's first paint.
pub(crate) fn global_seats_json(app: &App) -> serde_json::Value {
    let s = app
        .store
        .clocked(|c, _| widget::seats(c, 0))
        .unwrap_or_default();
    serde_json::to_value(s).unwrap_or_default()
}

/// A desk's widgets, for its rail.
pub(crate) async fn desk_widgets(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.clocked(|c, _| widget::seats(c, id)) {
        Ok(s) => Json(json!({ "widgets": s })).into_response(),
        Err(e) => err(e),
    }
}

/// Everything /sidebars arranges: the layout, every widget file with what
/// it asks and whether it is allowed as it is now, and every pushed widget
/// with its desk. A read, open as the project list is.
pub(crate) async fn list_widgets(State(app): S) -> Response {
    let found = widget::files::scan(&app.paths.config_dir);
    let desks = app.store.desks().unwrap_or_default();
    let r = app.store.clocked(|c, _| {
        let layout = widget::layout(c)?;
        let mut files = Vec::new();
        for f in &found {
            let p = widget::prefs(c, f.owner, &f.name)?;
            let hash = widget::files::hash(&f.folder);
            let owner_desk = desks.iter().find(|d| d.id == f.owner).map(|d| d.name.clone());
            files.push(match &f.spec {
                Ok(s) => json!({
                    "name": f.name, "owner": f.owner, "owner_desk": owner_desk,
                    "title": s.title, "scope": s.scope, "command": s.run.command,
                    "every": s.run.every, "folder": f.folder, "lines": s.lines,
                    "allowed": !p.trusted_hash.is_empty() && hash.as_deref().ok() == Some(p.trusted_hash.as_str()),
                    "changed": !p.trusted_hash.is_empty() && hash.as_deref().ok() != Some(p.trusted_hash.as_str()),
                    "error": widget::files::lint(s, &f.folder).err().or(hash.err()), "rerun_edits": p.rerun_edits, "hidden": p.hidden,
                    "fields": s.settings, "settings": s.settings_with(&p.settings),
                    "desks": p.desks, "until": p.until, "until_pane": p.until_pane,
                }),
                Err(why) => json!({ "name": f.name, "owner": f.owner, "owner_desk": owner_desk, "folder": f.folder, "error": why, "hidden": p.hidden }),
            });
        }
        let mut pushed = Vec::new();
        for d in std::iter::once(0).chain(desks.iter().map(|d| d.id)) {
            for s in widget::seats(c, d)? {
                if s.source == "push" {
                    let desk = desks.iter().find(|x| x.id == d).map(|x| x.name.clone());
                    pushed.push(json!({ "name": s.name, "desk_id": d, "desk": desk, "writer": s.writer, "updated_at": s.updated_at, "hidden": s.hidden, "agent": s.agent }));
                }
            }
        }
        let open: Vec<serde_json::Value> = desks
            .iter()
            .map(|d| json!({ "id": d.id, "name": d.name }))
            .collect();
        Ok(json!({ "layout": layout, "files": files, "pushed": pushed, "desks": open }))
    });
    match r {
        Ok(j) => Json(j).into_response(),
        Err(e) => err(e),
    }
}

/// Keep the reader's layout. Anything a page sends is normalized first, so
/// an id from a newer page is dropped and a missing one is put back, and
/// what is answered -- and sent to every page -- is what was kept.
pub(crate) async fn set_layout(State(app): S, headers: HeaderMap, body: Bytes) -> Response {
    if let Some(no) = refuse_reader(&app, &headers) {
        return no;
    }
    let Ok(l) = serde_json::from_slice::<Layout>(&body) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "not a layout" })),
        )
            .into_response();
    };
    match app.store.clocked(|c, now| widget::set_layout(c, &l, now)) {
        Ok(kept) => {
            let j = serde_json::to_value(&kept).unwrap_or_default();
            emit(&app, "layout", j.clone());
            Json(j).into_response()
        }
        Err(e) => err(e),
    }
}

// --- writing one ----------------------------------------------------------

/// What a writer posts: the widget's name, and its body -- Markdown as a
/// string, or the contract's object (`widget::Body::parse`). An empty body
/// clears. `desk` is for the token's route: a desk's id, or none for a
/// global widget; a panel's is its own desk.
#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct PushBody {
    name: String,
    body: serde_json::Value,
    desk: Option<i64>,
    writer: String,
    /// A panel's box: how long it suggests the box lasts, on the card.
    #[serde(rename = "for")]
    lasts: String,
}

impl PushBody {
    fn raw(&self) -> String {
        match &self.body {
            serde_json::Value::Null => String::new(),
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

fn refused(code: StatusCode, error: impl Into<String>) -> Response {
    (code, Json(json!({ "error": error.into() }))).into_response()
}

/// An agent in a panel sets a widget on its own desk (MCP `set_widget`).
pub(crate) async fn pane_set_widget(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<String>,
    body: Bytes,
) -> Response {
    let placed = match agent_pane(&app, &headers, &id) {
        Ok(p) => p,
        Err(no) => return *no,
    };
    let Ok(b) = serde_json::from_slice::<PushBody>(&body) else {
        return refused(StatusCode::BAD_REQUEST, "not a widget");
    };
    let writer = format!("panel {}", placed.pane.slot);
    let w = widget::Writer {
        source: widget::Source::Push,
        writer: &writer,
        pane: &id,
        title: "",
        owner: 0,
    };
    let desk = placed.desk_id;
    if !widget::name_ok(&b.name) {
        return push(&app, desk, &b.name, "", &w);
    }
    // The reader says yes to a panel's box once per desk and name (#111):
    // until then it waits behind a card on Your turn, and nothing is drawn.
    let raw = b.raw();
    let ask = app.store.clocked(|c, now| {
        widget::ask_grandfather(c, desk, &b.name, now)?;
        widget::ask_of(c, desk, &b.name)
    });
    match ask {
        Err(e) => err(e),
        Ok(Some(a)) if a.answer == "yes" => push(&app, desk, &b.name, &raw, &w),
        Ok(Some(a)) if a.answer == "no" => refused(
            StatusCode::CONFLICT,
            format!(
                "the user said not now to the box {} on this desk: leave it, or say in your reply why it would help",
                b.name
            ),
        ),
        // Removed by the reader: the panel that pushed it is told so; a
        // new panel asks again, with a card.
        Ok(Some(a)) if a.answer == "removed" && a.pane == id => refused(
            StatusCode::CONFLICT,
            format!(
                "the user removed the box {} from this desk: leave it removed unless they ask for it",
                b.name
            ),
        ),
        Ok(_) => ask_for_box(&app, desk, &id, &writer, &b, &raw),
    }
}

/// A panel's box the reader has not said yes to: its body waits, and the
/// card that asks is on Your turn -- one per desk and name, however often
/// the panel sends meanwhile. A clear while it waits takes the body back.
fn ask_for_box(
    app: &Arc<App>,
    desk: i64,
    pane: &str,
    writer: &str,
    b: &PushBody,
    raw: &str,
) -> Response {
    let cleared = matches!(widget::Body::parse(raw), Ok(widget::Sent::Clear));
    if let Err(why) = widget::Body::parse(raw) {
        return refused(StatusCode::BAD_REQUEST, why);
    }
    let preview: String = widget::Body::parse(raw)
        .ok()
        .and_then(|s| match s {
            widget::Sent::Body(b) => Some(b.md),
            widget::Sent::Clear => None,
        })
        .unwrap_or_default();
    let r = app.store.clocked(|c, now| {
        widget::ask_wait(
            c,
            desk,
            &b.name,
            pane,
            writer,
            if cleared { "" } else { raw },
            now,
        )?;
        if cleared || crate::thread::box_waiting(c, desk, &b.name)? {
            return Ok(None);
        }
        let s = crate::thread::Suggest {
            kind: "box".into(),
            name: b.name.clone(),
            cmd: preview.clone(),
            why: format!("{writer} wants a box on this desk"),
            by: writer.to_string(),
            pane: pane.to_string(),
            lasts: b.lasts.clone(),
            ..Default::default()
        };
        crate::thread::suggest(c, desk, &s, now).map(Some)
    });
    match r {
        Ok(None) => (
            StatusCode::ACCEPTED,
            Json(json!({ "waiting": true, "name": b.name, "cleared": cleared })),
        )
            .into_response(),
        Ok(Some(crate::thread::Suggested::Card(card))) => {
            threads_moved(app, desk);
            (
                StatusCode::ACCEPTED,
                Json(json!({ "waiting": true, "name": b.name, "suggestion": card })),
            )
                .into_response()
        }
        Ok(Some(crate::thread::Suggested::Full)) => refused(
            StatusCode::CONFLICT,
            "three suggestions are waiting on this desk already: the box can be asked for once the user answers one",
        ),
        Ok(Some(_)) => refused(StatusCode::BAD_REQUEST, "not a box"),
        Err(e) => err(e),
    }
}

/// Anything with the token sets a widget: a script, a git hook, cron, CI
/// (`snyvi widget set`). On a desk by its id, or global.
pub(crate) async fn set_widget(State(app): S, headers: HeaderMap, body: Bytes) -> Response {
    if !authorized(&app, &headers) {
        return StatusCode::UNAUTHORIZED.into_response();
    }
    let Ok(b) = serde_json::from_slice::<PushBody>(&body) else {
        return refused(StatusCode::BAD_REQUEST, "not a widget");
    };
    let desk = b.desk.unwrap_or(0);
    if desk != 0
        && !app
            .store
            .desks()
            .map(|ds| ds.iter().any(|d| d.id == desk))
            .unwrap_or(false)
    {
        return refused(StatusCode::NOT_FOUND, format!("there is no desk {desk}"));
    }
    let writer = if b.writer.trim().is_empty() {
        "a script".to_string()
    } else {
        b.writer.trim().chars().take(40).collect()
    };
    let w = widget::Writer {
        source: widget::Source::Push,
        writer: &writer,
        pane: "",
        title: "",
        owner: 0,
    };
    push(&app, desk, &b.name, &b.raw(), &w)
}

/// Read, draw, keep and say a pushed body, or clear the widget.
fn push(app: &Arc<App>, desk: i64, name: &str, raw: &str, w: &widget::Writer) -> Response {
    if !widget::name_ok(name) {
        return refused(
            StatusCode::BAD_REQUEST,
            "a widget's name is lowercase letters, digits and dashes, at most 32",
        );
    }
    let sent = match widget::Body::parse(raw) {
        Ok(s) => s,
        Err(why) => return refused(StatusCode::BAD_REQUEST, why),
    };
    let b = match sent {
        widget::Sent::Clear => {
            return match app
                .store
                .clocked(|c, _| widget::clear(c, desk, name, w.source))
            {
                Ok(was) => {
                    if was {
                        announce(app, desk, name);
                    }
                    Json(json!({ "cleared": was })).into_response()
                }
                Err(e) => err(e),
            };
        }
        widget::Sent::Body(b) => b,
    };
    let html = crate::render::widget_md(&b.md);
    match app
        .store
        .clocked(|c, now| widget::put(c, desk, name, &b, &html, w, now))
    {
        Ok(widget::Put::Done) => {
            announce(app, desk, name);
            Json(json!({ "ok": true, "desk": desk, "name": name })).into_response()
        }
        Ok(widget::Put::Full) => refused(
            StatusCode::CONFLICT,
            if desk == 0 {
                format!(
                    "there are {} global widgets, which is all there can be",
                    widget::GLOBAL_MAX
                )
            } else {
                format!(
                    "this desk has {} widgets, which is all it can have",
                    widget::DESK_MAX
                )
            },
        ),
        Ok(widget::Put::Owned) => refused(
            StatusCode::CONFLICT,
            format!(
                "a widget file is called {name}, and only it fills that seat: pick another name"
            ),
        ),
        Err(e) => err(e),
    }
}

/// How often one widget's seat is sent to the pages: an agent writing every
/// 100 ms is drawn twice a second, the last word always.
const COALESCE: std::time::Duration = std::time::Duration::from_millis(500);

/// When each widget -- (desk, name) -- was last sent, and whether a send is waiting.
type Announced = std::collections::HashMap<(i64, String), (Instant, bool)>;
static SENT: std::sync::LazyLock<std::sync::Mutex<Announced>> =
    std::sync::LazyLock::new(Default::default);

/// Tell the pages a widget changed: now, or once its half second is up --
/// whatever it says by then.
pub(crate) fn announce(app: &Arc<App>, desk: i64, name: &str) {
    let key = (desk, name.to_string());
    let now = Instant::now();
    let mut m = SENT.lock().unwrap();
    match m.get_mut(&key) {
        Some((at, waiting)) if now.duration_since(*at) < COALESCE => {
            if !*waiting {
                *waiting = true;
                let wait = COALESCE - now.duration_since(*at);
                let app = app.clone();
                tokio::spawn(async move {
                    tokio::time::sleep(wait).await;
                    SENT.lock()
                        .unwrap()
                        .insert(key.clone(), (Instant::now(), false));
                    send_seat(&app, key.0, &key.1);
                });
            }
        }
        _ => {
            m.insert(key, (now, false));
            drop(m);
            send_seat(app, desk, name);
        }
    }
}

/// One widget as the pages draw it, or the word that it is gone.
fn send_seat(app: &App, desk: i64, name: &str) {
    match app.store.clocked(|c, _| widget::seat_of(c, desk, name)) {
        Ok(Some(s)) => emit(app, "widget", serde_json::to_value(s).unwrap_or_default()),
        Ok(None) => emit(
            app,
            "widget",
            json!({ "desk_id": desk, "name": name, "cleared": true }),
        ),
        Err(_) => {}
    }
}

/// A panel closed: a box allowed for its life goes, and so does a widget
/// file the reader kept only while it was open -- switched off, not removed.
/// What else its agent pushed stays, dimmed, and says so.
pub(crate) fn pane_widgets_ended(app: &Arc<App>, pane: &str, slot: Option<i64>) {
    let said = slot.map_or("a panel since closed".to_string(), |n| {
        format!("panel {n} closed")
    });
    let found = widget::files::scan(&app.paths.config_dir);
    let Ok(seats) = app.store.clocked(|c, now| {
        let mut s = widget::asks_ending(c, now, |p| p != pane)?;
        for (d, n) in &s {
            widget::clear(c, *d, n, widget::Source::Push)?;
        }
        for f in &found {
            let p = widget::prefs(c, f.owner, &f.name)?;
            if p.until_pane == pane && !p.hidden {
                let off = widget::Change {
                    hidden: Some(true),
                    ..Default::default()
                };
                widget::set_prefs(c, f.owner, &f.name, &off, now)?;
                s.extend(
                    widget::desks_of(c, f.owner, &f.name)?
                        .into_iter()
                        .map(|d| (d, f.name.clone())),
                );
            }
        }
        s.extend(widget::of_pane(c, pane)?);
        widget::pane_ended(c, pane, &said)?;
        Ok(s)
    }) else {
        return;
    };
    for (desk, name) in seats {
        announce(app, desk, &name);
    }
}

// --- the reader's say over a widget file -------------------------------------

#[derive(Deserialize)]
#[serde(default)]
pub(crate) struct AllowBody {
    /// Allow the folder as it is now. False with `rerun_edits` changes the
    /// switch alone.
    allow: bool,
    rerun_edits: Option<bool>,
    /// The desk the widget belongs to; 0 for a shared or global one.
    owner: i64,
}

impl Default for AllowBody {
    fn default() -> AllowBody {
        AllowBody {
            allow: true,
            rerun_edits: None,
            owner: 0,
        }
    }
}

/// Allow a widget file's folder as it is now, and with it, whether the
/// reader's own edits rerun without asking. Only from the window: neither
/// the token an agent holds nor a page's `Origin` is enough to let a
/// command run on a timer.
pub(crate) async fn allow_widget(
    State(app): S,
    headers: HeaderMap,
    Path(name): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    body: Bytes,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    if !widget::name_ok(&name) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let b: AllowBody = serde_json::from_slice(&body).unwrap_or_default();
    let folder = widget::files::folder_of(&app.paths.config_dir, b.owner, &name);
    let spec = match widget::files::read(&folder, &name) {
        Ok(s) => s,
        Err(why) => return refused(StatusCode::NOT_FOUND, why),
    };
    if b.allow {
        if let Err(why) = widget::files::lint(&spec, &folder) {
            return refused(StatusCode::BAD_REQUEST, why);
        }
    }
    let hash = if b.allow {
        match widget::files::hash(&folder) {
            Ok(h) => Some(h),
            Err(why) => return refused(StatusCode::BAD_REQUEST, why),
        }
    } else {
        None
    };
    let ch = widget::Change {
        trusted_hash: hash.as_deref(),
        rerun_edits: b.rerun_edits,
        ..Default::default()
    };
    match app.store.clocked(|c, now| {
        let p = widget::set_prefs(c, b.owner, &name, &ch, now)?;
        let ds = if b.allow {
            widget::unstop(c, b.owner, &name, None)?
        } else {
            Vec::new()
        };
        Ok((p, ds))
    }) {
        Ok((p, ds)) => {
            for d in ds {
                announce(&app, d, &name);
            }
            Json(json!({ "ok": true, "prefs": p })).into_response()
        }
        Err(e) => err(e),
    }
}

#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct RetryBody {
    desk: Option<i64>,
    /// The desk the widget belongs to; 0 for a shared one.
    owner: i64,
}

/// Try again, on a widget file that stopped after failing: it runs at the
/// runner's next look, on that desk (or every desk it stopped on).
pub(crate) async fn retry_widget(
    State(app): S,
    headers: HeaderMap,
    Path(name): Path<String>,
    body: Bytes,
) -> Response {
    if let Some(no) = refuse_reader(&app, &headers) {
        return no;
    }
    if !widget::name_ok(&name) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let b: RetryBody = serde_json::from_slice(&body).unwrap_or_default();
    match app
        .store
        .clocked(|c, _| widget::unstop(c, b.owner, &name, b.desk))
    {
        Ok(ds) => {
            for d in &ds {
                announce(&app, *d, &name);
            }
            Json(json!({ "ok": true, "desks": ds })).into_response()
        }
        Err(e) => err(e),
    }
}

/// Tell the agent, from a failing widget file's box: the agent that
/// proposed it hears why it fails, whole, with its next prompt (#112). One
/// the reader wrote by hand has no agent to tell, and says so.
pub(crate) async fn tell_widget(
    State(app): S,
    headers: HeaderMap,
    Path(name): Path<String>,
    body: Bytes,
) -> Response {
    if let Some(no) = refuse_reader(&app, &headers) {
        return no;
    }
    if !widget::name_ok(&name) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let b: RetryBody = serde_json::from_slice(&body).unwrap_or_default();
    let desk = b.desk.unwrap_or(0);
    let told = app.store.clocked(|c, _| {
        let Some(seat) = widget::seat_of(c, desk, &name)? else {
            return Ok(None);
        };
        let why = seat
            .error
            .strip_prefix(widget::STOPPED)
            .unwrap_or(&seat.error);
        if why.is_empty() || seat.source != "file" {
            return Ok(None);
        }
        let note = format!(
            "The reader asks you to fix your widget {name}: its box says \"{why}\". \
             Fix it in its folder; the box runs it again once it changes."
        );
        crate::thread::tell_widget(c, seat.owner, &name, &note).map(Some)
    });
    match told {
        Ok(None) => refused(StatusCode::CONFLICT, "nothing to tell: it has not failed"),
        Ok(Some(told)) => Json(json!({ "told": told })).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct PrefsBody {
    hidden: Option<bool>,
    settings: Option<serde_json::Map<String, serde_json::Value>>,
    /// The desks it is on; none is every desk.
    desks: Option<Vec<i64>>,
    /// On this desk alone, from its box's menu.
    only_desk: Option<i64>,
    /// Off this desk, from its box's menu: the rest keep it.
    not_desk: Option<i64>,
    /// When it turns itself off (0: when the reader does), and the panel
    /// whose life it lasts.
    until: Option<i64>,
    until_pane: Option<String>,
    /// The desk the widget belongs to; 0 for a shared or global one.
    owner: i64,
    /// Share a desk's own widget: it moves out of the desk's folder, and is
    /// on that desk alone until the reader ticks more.
    share: bool,
    /// Make a shared widget this desk's own: it moves into the desk's
    /// folder, and leaves the other desks.
    keep_here: Option<i64>,
}

/// Switch a widget off or on, change its settings, the desks it is on, or
/// how long it lasts: the reader's, from /sidebars and its box's menu. Its
/// seats say so to every page. Off the last desk it was on is off. A desk's
/// own widget is on its desk alone: the desks are not its to change, and
/// off its desk is off.
pub(crate) async fn widget_prefs(
    State(app): S,
    headers: HeaderMap,
    Path(name): Path<String>,
    body: Bytes,
) -> Response {
    if let Some(no) = refuse_reader(&app, &headers) {
        return no;
    }
    if !widget::name_ok(&name) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let Ok(b) = serde_json::from_slice::<PrefsBody>(&body) else {
        return refused(StatusCode::BAD_REQUEST, "not a widget's settings");
    };
    if b.share && b.owner != 0 {
        return rehome_widget(&app, &name, b.owner, 0);
    }
    if let (Some(d), 0) = (b.keep_here, b.owner) {
        return rehome_widget(&app, &name, 0, d);
    }
    let owner = b.owner;
    let settings = b.settings.map(|m| serde_json::Value::Object(m).to_string());
    let open: Vec<i64> = app
        .store
        .desks()
        .unwrap_or_default()
        .iter()
        .map(|d| d.id)
        .collect();
    let r = app.store.clocked(|c, now| {
        let was = widget::prefs(c, owner, &name)?;
        let before = widget::desks_of(c, owner, &name)?;
        let mut hidden = b.hidden;
        let desks: Option<Vec<i64>> = match (b.only_desk, b.not_desk, &b.desks) {
            _ if owner != 0 => {
                if b.not_desk == Some(owner) {
                    hidden = Some(true);
                }
                None
            }
            (Some(d), _, _) => Some(vec![d]),
            (_, Some(d), _) => {
                let from = if was.desks.is_empty() {
                    open.clone()
                } else {
                    was.desks.clone()
                };
                let left: Vec<i64> = from.into_iter().filter(|x| *x != d).collect();
                if left.is_empty() {
                    hidden = Some(true);
                    None
                } else {
                    Some(left)
                }
            }
            (_, _, Some(ds)) => Some(ds.iter().copied().filter(|d| open.contains(d)).collect()),
            _ => None,
        };
        // On again, by its switch, after its time was up: on until the
        // reader says, or the runner would switch it off at its next look.
        let back = hidden == Some(false) && was.ended(now, |p| app.panes.is_running(p));
        let until = b.until.map(|u| u.max(0)).or(back.then_some(0));
        let until_pane = b.until_pane.as_deref().or(back.then_some(""));
        let ch = widget::Change {
            hidden,
            settings: settings.as_deref(),
            desks: desks.as_deref(),
            until,
            until_pane,
            ..Default::default()
        };
        let p = widget::set_prefs(c, owner, &name, &ch, now)?;
        let off = if owner == 0 {
            widget::off_desks(c, &name, &p.desks)?
        } else {
            Vec::new()
        };
        let mut told = before;
        for d in off {
            if !told.contains(&d) {
                told.push(d);
            }
        }
        Ok((p, told))
    });
    match r {
        Ok((p, desks)) => {
            for d in desks {
                announce(&app, d, &name);
            }
            Json(json!({ "ok": true, "prefs": p })).into_response()
        }
        Err(e) => err(e),
    }
}

/// Share a desk's own widget (`to` 0), or make a shared one a desk's own:
/// its folder moves, and what the reader decided -- allowed, settings, how
/// long -- goes with it. Shared, it is on the desk it came from and no
/// other until the reader ticks more, so nothing runs anywhere new; a
/// desk's own, it leaves every other desk. A global widget is on no desk.
fn rehome_widget(app: &Arc<App>, name: &str, from: i64, to: i64) -> Response {
    let cfg = &app.paths.config_dir;
    let (src, dst) = (
        widget::files::folder_of(cfg, from, name),
        widget::files::folder_of(cfg, to, name),
    );
    match widget::files::read(&src, name) {
        Err(why) => return refused(StatusCode::NOT_FOUND, why),
        Ok(s) if s.scope == widget::files::Scope::Global => {
            return refused(
                StatusCode::BAD_REQUEST,
                "a global widget is on the left, not on a desk",
            )
        }
        Ok(_) => {}
    }
    if to != 0
        && !app
            .store
            .desks()
            .map(|ds| ds.iter().any(|d| d.id == to))
            .unwrap_or(false)
    {
        return refused(StatusCode::NOT_FOUND, format!("there is no desk {to}"));
    }
    if let Some(why) = widget::files::taken_moving(cfg, from, to, name) {
        return refused(StatusCode::CONFLICT, why);
    }
    let moved = dst
        .parent()
        .map_or(Ok(()), std::fs::create_dir_all)
        .and_then(|_| std::fs::rename(&src, &dst));
    if let Err(e) = moved {
        return refused(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("could not move it: {e}"),
        );
    }
    match app
        .store
        .clocked(|c, now| widget::rehome(c, name, from, to, now))
    {
        Ok(desks) => {
            for d in desks.iter().chain((to != 0).then_some(&to)) {
                announce(app, *d, name);
            }
            Json(json!({ "ok": true, "owner": to })).into_response()
        }
        Err(e) => {
            // The record did not change: the folder goes back with it.
            let _ = std::fs::rename(&dst, &src);
            err(e)
        }
    }
}

// --- removing an agent's ----------------------------------------------------

#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct RemoveBody {
    /// The desk its box is on.
    desk: i64,
    /// The desk a widget file belongs to; 0 for a box a panel pushed.
    owner: i64,
    /// Undo's: the id its folder was kept under (`files::remove`).
    from: String,
}

/// Remove an agent's widget, from its box's menu or /sidebars: a desk's own
/// widget file moves to `widgets/.removed/` and the agent that proposed it
/// is told; a box a panel pushed goes, and that panel's next push of it is
/// refused. Nothing is deleted, and Undo (`restore_widget`) puts it back.
/// The window's alone, as Allow is: an agent's token removes nothing. A
/// shared or global widget file, and a script's box, are the reader's own
/// and have Turn off.
pub(crate) async fn remove_widget(
    State(app): S,
    headers: HeaderMap,
    Path(name): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    body: Bytes,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    if !widget::name_ok(&name) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let b: RemoveBody = serde_json::from_slice(&body).unwrap_or_default();
    if b.owner == 0 {
        return match app
            .store
            .clocked(|c, now| widget::remove_box(c, b.desk, &name, now))
        {
            Ok(true) => {
                announce(&app, b.desk, &name);
                Json(json!({ "ok": true })).into_response()
            }
            Ok(false) => refused(
                StatusCode::CONFLICT,
                "only a box an agent pushed can be removed: Turn off takes the rest out of view",
            ),
            Err(e) => err(e),
        };
    }
    let cfg = &app.paths.config_dir;
    let id = match widget::files::remove(cfg, b.owner, &name, crate::store::now()) {
        Ok(id) => id,
        Err(why) => return refused(StatusCode::NOT_FOUND, why),
    };
    let note = format!(
        "The reader removed your widget {name} from this desk. Leave it removed: \
         propose it again only if they ask for it."
    );
    let r = app.store.clocked(|c, _| {
        let desks = widget::desks_of(c, b.owner, &name)?;
        for d in &desks {
            widget::clear(c, *d, &name, widget::Source::File)?;
        }
        crate::thread::tell_widget(c, b.owner, &name, &note)?;
        Ok(desks)
    });
    match r {
        Ok(desks) => {
            for d in desks {
                announce(&app, d, &name);
            }
            Json(json!({ "ok": true, "from": id })).into_response()
        }
        Err(e) => {
            // The record did not change: the folder goes back with it.
            let _ = widget::files::restore(cfg, &id, b.owner, &name);
            err(e)
        }
    }
}

/// Undo a removal, within the moment its box offers it: a widget file's
/// folder back where it was -- allowed as it was, since what the reader
/// decided about it was kept -- or a box allowed again with what it last
/// showed.
pub(crate) async fn restore_widget(
    State(app): S,
    headers: HeaderMap,
    Path(name): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    body: Bytes,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    if !widget::name_ok(&name) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let b: RemoveBody = serde_json::from_slice(&body).unwrap_or_default();
    if b.owner != 0 {
        return match widget::files::restore(&app.paths.config_dir, &b.from, b.owner, &name) {
            Ok(()) => Json(json!({ "ok": true })).into_response(),
            Err(why) => refused(StatusCode::CONFLICT, why),
        };
    }
    match app
        .store
        .clocked(|c, now| widget::restore_box(c, b.desk, &name, now))
    {
        Ok(Some(a)) => {
            let pane = if app.panes.is_running(&a.pane) {
                a.pane.as_str()
            } else {
                ""
            };
            let w = widget::Writer {
                source: widget::Source::Push,
                writer: &a.writer,
                pane,
                title: "",
                owner: 0,
            };
            push(&app, b.desk, &name, &a.body, &w)
        }
        Ok(None) => refused(
            StatusCode::CONFLICT,
            format!("{name} was not removed from here"),
        ),
        Err(e) => err(e),
    }
}

// --- an agent proposing one ----------------------------------------------------

/// What `propose_widget` sends: a widget file, whole.
#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct ProposeBody {
    name: String,
    title: String,
    /// Before 1.32 an agent could ask for every desk or global; its widget
    /// is its desk's now, and a scope sent is not read.
    #[allow(dead_code)]
    scope: String,
    command: String,
    every: u64,
    timeout: u64,
    lines: u8,
    script_name: String,
    script: String,
    why: String,
    by: String,
    /// How long the agent suggests it lasts: `today`, `week`, `panel`.
    #[serde(rename = "for")]
    lasts: String,
}

/// The longest script a proposal may carry.
const SCRIPT_MAX: usize = 16 * 1024;

/// Where proposals wait until the reader adds them or not: under the
/// widgets folder, in a name no widget can have, so the runner never sees
/// them.
fn proposed_dir(app: &App) -> std::path::PathBuf {
    widget::files::dir(&app.paths.config_dir).join(".proposed")
}

/// An agent proposes a widget: the folder is written where proposals wait,
/// and the reader gets a card on Your turn -- Add, or Not now. Nothing runs
/// and nothing is in the widgets folder until Add. It is for the agent's
/// desk alone: sharing it is the reader's (1.32).
pub(crate) async fn pane_propose_widget(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<String>,
    body: Bytes,
) -> Response {
    let placed = match agent_pane(&app, &headers, &id) {
        Ok(p) => p,
        Err(no) => return *no,
    };
    let Ok(b) = serde_json::from_slice::<ProposeBody>(&body) else {
        return refused(StatusCode::BAD_REQUEST, "not a widget");
    };
    if !widget::name_ok(&b.name) {
        return refused(
            StatusCode::BAD_REQUEST,
            "a widget's name is lowercase letters, digits and dashes, at most 32",
        );
    }
    if let Some(why) = widget::files::taken(&app.paths.config_dir, placed.desk_id, &b.name) {
        return refused(StatusCode::CONFLICT, why);
    }
    let command = b.command.trim();
    if command.is_empty() || command.contains('\n') {
        return refused(StatusCode::BAD_REQUEST, "the command is one line");
    }
    let script_ok = b.script_name.is_empty()
        || (!b.script_name.contains(['/', '\\'])
            && !b.script_name.starts_with('.')
            && b.script_name != "widget.json");
    if !script_ok || b.script.len() > SCRIPT_MAX {
        return refused(
            StatusCode::BAD_REQUEST,
            "the script is one file of at most 16 KB, named without a folder",
        );
    }
    // Where it goes: this desk, alone.
    let place = "here";
    let spec = json!({
        "name": b.name,
        "title": b.title.trim(),
        "scope": "desk",
        "run": { "command": command, "every": if b.every == 0 { widget::files::EVERY_DEFAULT } else { b.every }, "timeout": if b.timeout == 0 { widget::files::TIMEOUT_DEFAULT } else { b.timeout } },
        "lines": if b.lines == 0 { widget::LINES_DEFAULT } else { b.lines },
    });
    let stage = proposed_dir(&app).join(format!("{}-{}", crate::store::now(), b.name));
    let wrote = (|| -> std::io::Result<()> {
        std::fs::create_dir_all(&stage)?;
        std::fs::write(
            stage.join("widget.json"),
            serde_json::to_string_pretty(&spec).unwrap_or_default() + "\n",
        )?;
        if !b.script_name.is_empty() {
            let p = stage.join(&b.script_name);
            std::fs::write(&p, &b.script)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755))?;
            }
        }
        Ok(())
    })();
    if let Err(e) = wrote {
        return refused(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("could not write it: {e}"),
        );
    }
    // Checked before the reader sees it: a command that cannot reach its own
    // script goes back to the agent with how to write it (#111).
    let read = widget::files::read(&stage, &b.name)
        .and_then(|s| widget::files::lint(&s, &stage).map(|_| s));
    let spec = match read {
        Ok(s) => s,
        Err(why) => {
            let _ = std::fs::remove_dir_all(&stage);
            return refused(StatusCode::BAD_REQUEST, why);
        }
    };
    let detail = json!({
        "where": place,
        "every": spec.run.every,
        "lines": spec.lines,
        "script_name": b.script_name,
        "script": b.script,
    });
    let s = crate::thread::Suggest {
        kind: "widget".into(),
        name: b.name.clone(),
        cmd: command.to_string(),
        folder: stage.to_string_lossy().to_string(),
        why: b.why,
        by: b.by,
        pane: id,
        lasts: b.lasts,
        detail: detail.to_string(),
    };
    let desk = placed.desk_id;
    match app
        .store
        .clocked(|c, now| crate::thread::suggest(c, desk, &s, now))
    {
        Ok(crate::thread::Suggested::Card(card)) => {
            threads_moved(&app, desk);
            (StatusCode::CREATED, Json(json!({ "suggestion": card }))).into_response()
        }
        Ok(crate::thread::Suggested::Full) => {
            let _ = std::fs::remove_dir_all(&stage);
            refused(
                StatusCode::CONFLICT,
                "three suggestions are waiting on this desk already",
            )
        }
        Ok(_) => {
            let _ = std::fs::remove_dir_all(&stage);
            refused(StatusCode::BAD_REQUEST, "say why, in a sentence")
        }
        Err(e) => {
            let _ = std::fs::remove_dir_all(&stage);
            err(e)
        }
    }
}

/// How long the reader said a widget lasts, from the card: until when, and
/// the panel whose life it lasts.
#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct Lasts {
    pub(crate) until: i64,
    pub(crate) until_pane: String,
}

/// The reader added a proposed widget: its folder moves into the folder of
/// the desk the card was on, allowed as it is, that desk's own, for as long
/// as the reader chose. A card from before 1.32 that said every desk, or
/// global, is shared as it said. Refused if a widget took the name
/// meanwhile.
pub(crate) fn install_proposed(
    app: &App,
    card: &crate::thread::Suggestion,
    lasts: &Lasts,
) -> Result<(), String> {
    let (name, staged) = (card.name.as_str(), card.folder.as_str());
    let stage = std::path::PathBuf::from(staged);
    if !stage.starts_with(proposed_dir(app)) || !stage.is_dir() {
        return Err("the proposal is not there any more".into());
    }
    let spec = widget::files::read(&stage, name)?;
    widget::files::lint(&spec, &stage)?;
    let shared = spec.scope == widget::files::Scope::Global
        || card.detail.get("where").and_then(|w| w.as_str()) != Some("here");
    let owner = if shared { 0 } else { card.desk_id };
    let cfg = &app.paths.config_dir;
    if let Some(why) = widget::files::taken(cfg, owner, name) {
        return Err(why);
    }
    let to = widget::files::folder_of(cfg, owner, name);
    to.parent()
        .map_or(Ok(()), std::fs::create_dir_all)
        .and_then(|_| std::fs::rename(&stage, &to))
        .map_err(|e| format!("could not move it in: {e}"))?;
    let hash = widget::files::hash(&to)?;
    let desks: Vec<i64> = Vec::new();
    let ch = widget::Change {
        hidden: Some(false),
        trusted_hash: Some(&hash),
        desks: Some(&desks),
        until: Some(lasts.until.max(0)),
        until_pane: Some(&lasts.until_pane),
        ..Default::default()
    };
    app.store
        .clocked(|c, now| widget::set_prefs(c, owner, name, &ch, now))
        .map(|_| ())
        .map_err(|e| e.to_string())
}

/// The reader allowed a panel's box: what waits behind the card is drawn,
/// and from now on the panel's updates go straight in -- until when the
/// reader said.
pub(crate) fn allow_box(
    app: &Arc<App>,
    card: &crate::thread::Suggestion,
    lasts: &Lasts,
) -> Result<(), String> {
    let (desk, name) = (card.desk_id, card.name.as_str());
    let ask = app
        .store
        .clocked(|c, now| {
            widget::ask_answer(
                c,
                desk,
                name,
                "yes",
                lasts.until.max(0),
                &lasts.until_pane,
                now,
            )?;
            widget::ask_of(c, desk, name)
        })
        .map_err(|e| e.to_string())?
        .ok_or("the box is not there any more")?;
    if ask.body.trim().is_empty() {
        return Ok(());
    }
    let w = widget::Writer {
        source: widget::Source::Push,
        writer: &ask.writer,
        pane: &ask.pane,
        title: "",
        owner: 0,
    };
    let r = push(app, desk, name, &ask.body, &w);
    if r.status().is_success() {
        Ok(())
    } else {
        Err(format!("snyvi answered {}", r.status()))
    }
}

/// What Try once printed, drawn, or why it printed nothing usable.
pub(crate) async fn try_proposed(app: &App, card: &crate::thread::Suggestion) -> serde_json::Value {
    let stage = std::path::PathBuf::from(&card.folder);
    if !stage.starts_with(proposed_dir(app)) || !stage.is_dir() {
        return json!({ "error": "the proposal is not there any more" });
    }
    let spec = match widget::files::read(&stage, &card.name)
        .and_then(|s| widget::files::lint(&s, &stage).map(|_| s))
    {
        Ok(s) => s,
        Err(why) => return json!({ "error": why }),
    };
    let desk = app.store.desk(card.desk_id).ok().flatten();
    let cwd = match (spec.scope, &desk) {
        (widget::files::Scope::Global, _) => stage.clone(),
        (_, Some(d)) if !d.root.is_empty() && std::path::Path::new(&d.root).is_dir() => {
            std::path::PathBuf::from(&d.root)
        }
        _ => return json!({ "error": "this desk has no folder to run it in" }),
    };
    let stdin = json!({
        "desk": desk.as_ref().map(|d| json!({ "id": d.id, "name": d.name, "folder": d.root })),
        "settings": spec.settings_with("{}"),
        "snyvi": VERSION,
    });
    let path = super::widget_run::path_now();
    match super::widget_run::run_once(&spec, &stage, &cwd, &path, &stdin).await {
        super::widget_run::Ran::Failed(why) => {
            json!({ "error": format!("{why} (in {})", crate::text::tilde(&cwd)) })
        }
        super::widget_run::Ran::Printed(out) => match widget::Body::parse(&out) {
            Err(why) => json!({ "error": why }),
            Ok(widget::Sent::Clear) => json!({ "html": "", "empty": true }),
            Ok(widget::Sent::Body(b)) => json!({
                "html": crate::render::widget_md(&b.md), "count": b.count, "tone": b.tone.as_str(),
            }),
        },
    }
}