snyvi 1.30.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
//! Widget files: a folder in `<config>/widgets/<name>/` holding a
//! `widget.json` and the command it names, which snyvi runs on a timer
//! while the widget is in view and draws what it prints (docs/WIDGETS.md).
//!
//! Nothing in here runs anything: this reads the folders, says what each
//! one asks for, hashes what the reader allowed, and writes a starter. The
//! running is the daemon's (`crate::server::widget_run`).

use super::{name_ok, LINES_DEFAULT, LINES_MAX, LINES_MIN};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// The most a widget's folder may hold, all its files together: what is
/// hashed is what was allowed, and a folder this size is read in a moment.
pub const FOLDER_MAX: u64 = 64 * 1024;
/// How often a command may run, and how long it may take.
pub const EVERY_MIN: u64 = 5;
pub const EVERY_DEFAULT: u64 = 60;
pub const TIMEOUT_MAX: u64 = 30;
pub const TIMEOUT_DEFAULT: u64 = 10;

/// Where the reader's widget folders are.
pub fn dir(config_dir: &Path) -> PathBuf {
    config_dir.join("widgets")
}

/// Where a widget runs: on the desk on the page, in the desk's folder, or
/// everywhere, in its own. Either way its own folder is first on PATH and
/// in `SNYVI_WIDGET_DIR`, so a desk widget reaches its script by name
/// (`lint`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
    #[default]
    Desk,
    Global,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Run {
    pub command: String,
    #[serde(default = "every_default")]
    pub every: u64,
    #[serde(default = "timeout_default")]
    pub timeout: u64,
}

fn every_default() -> u64 {
    EVERY_DEFAULT
}
fn timeout_default() -> u64 {
    TIMEOUT_DEFAULT
}

/// One setting, drawn by snyvi on /sidebars as a row: a string, a number,
/// a choice or on/off.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Field {
    #[serde(rename = "type")]
    pub kind: String,
    #[serde(default)]
    pub label: String,
    #[serde(default)]
    pub default: Value,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<String>,
}

/// What a `widget.json` says.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Spec {
    pub name: String,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub scope: Scope,
    pub run: Run,
    #[serde(default = "lines_default")]
    pub lines: u8,
    #[serde(default)]
    pub settings: BTreeMap<String, Field>,
}

fn lines_default() -> u8 {
    LINES_DEFAULT
}

impl Spec {
    /// The spec as it is run: every bound applied, the title filled in.
    fn bounded(mut self) -> Spec {
        self.run.every = self.run.every.max(EVERY_MIN);
        self.run.timeout = self.run.timeout.clamp(1, TIMEOUT_MAX);
        self.lines = self.lines.clamp(LINES_MIN, LINES_MAX);
        if self.title.trim().is_empty() {
            self.title = super::title_of(&self.name);
        }
        self.title = self.title.trim().chars().take(40).collect();
        self
    }

    /// The settings a run is given: each field's default, then what the
    /// reader set, for the fields the widget has.
    pub fn settings_with(&self, reader: &str) -> Value {
        let set: serde_json::Map<String, Value> = serde_json::from_str(reader).unwrap_or_default();
        let mut out = serde_json::Map::new();
        for (k, f) in &self.settings {
            out.insert(
                k.clone(),
                set.get(k).cloned().unwrap_or_else(|| f.default.clone()),
            );
        }
        Value::Object(out)
    }
}

/// A folder found under the widgets folder: its spec, or why it has none.
#[derive(Debug, Clone)]
pub struct Found {
    pub name: String,
    pub folder: PathBuf,
    pub spec: Result<Spec, String>,
}

/// Every widget folder, by name. A folder whose `widget.json` does not read,
/// or names another widget, is listed with the reason, so /sidebars can
/// say it rather than leave the reader guessing.
pub fn scan(config_dir: &Path) -> Vec<Found> {
    let Ok(rd) = std::fs::read_dir(dir(config_dir)) else {
        return Vec::new();
    };
    let mut out: Vec<Found> = rd
        .flatten()
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
        .filter_map(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            name_ok(&name).then(|| Found {
                spec: read(&e.path(), &name),
                name,
                folder: e.path(),
            })
        })
        .collect();
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// One folder's `widget.json`, read and bounded.
pub fn read(folder: &Path, name: &str) -> Result<Spec, String> {
    let text = std::fs::read_to_string(folder.join("widget.json"))
        .map_err(|_| "it has no widget.json".to_string())?;
    let spec: Spec =
        serde_json::from_str(&text).map_err(|e| format!("widget.json does not read: {e}"))?;
    if spec.name != name {
        return Err(format!(
            "widget.json says \"{}\", in a folder called {name}",
            spec.name
        ));
    }
    if spec.run.command.trim().is_empty() {
        return Err("widget.json has no run.command".into());
    }
    Ok(spec.bounded())
}

/// A stamp of everything in a folder, cheap to take every round: what
/// changed in it moves it, and only then is the folder hashed again.
pub fn stamp(folder: &Path) -> Option<(u128, u64, usize)> {
    let mut newest = 0u128;
    let (mut bytes, mut n) = (0u64, 0usize);
    for f in files(folder) {
        let m = std::fs::metadata(&f).ok()?;
        let t = m
            .modified()
            .ok()?
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_nanos();
        newest = newest.max(t);
        bytes += m.len();
        n += 1;
    }
    Some((newest, bytes, n))
}

/// Every regular file under a folder, in a fixed order; links are not
/// followed, so the hash is of what is in the folder and nothing it points
/// to.
fn files(folder: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut todo = vec![folder.to_path_buf()];
    while let Some(d) = todo.pop() {
        let Ok(rd) = std::fs::read_dir(&d) else {
            continue;
        };
        for e in rd.flatten() {
            let Ok(t) = e.file_type() else { continue };
            if t.is_dir() {
                todo.push(e.path());
            } else if t.is_file() {
                out.push(e.path());
            }
        }
    }
    out.sort();
    out
}

/// The hash of a whole folder -- every file's path in it and its bytes --
/// which is what the reader allows: a change to anything in it, the script
/// or a file it reads, asks again. Refused past `FOLDER_MAX`.
pub fn hash(folder: &Path) -> Result<String, String> {
    let mut h = blake3::Hasher::new();
    let mut total = 0u64;
    for f in files(folder) {
        let rel = f
            .strip_prefix(folder)
            .unwrap_or(&f)
            .to_string_lossy()
            .replace('\\', "/");
        let bytes = std::fs::read(&f).map_err(|e| format!("could not read {rel}: {e}"))?;
        total += bytes.len() as u64;
        if total > FOLDER_MAX {
            return Err(format!(
                "the folder holds more than {} KB",
                FOLDER_MAX / 1024
            ));
        }
        h.update(rel.as_bytes());
        h.update(&[0]);
        h.update(&(bytes.len() as u64).to_le_bytes());
        h.update(&bytes);
    }
    Ok(h.finalize().to_hex().to_string())
}

/// The variable a run finds its own folder in, as the shell it runs in
/// writes it.
const DIR_VAR: &str = if cfg!(windows) {
    "%SNYVI_WIDGET_DIR%"
} else {
    "$SNYVI_WIDGET_DIR"
};

/// Whether a desk widget's command reaches the files in its own folder
/// (#111). A desk widget runs in the desk's folder, with its own first on
/// PATH and in `SNYVI_WIDGET_DIR`: a script of its own is named bare as the
/// command, or through the variable. A relative path to one of its files
/// (`./run.sh`), or its bare name as an argument (`sh run.sh`, `node x.js`),
/// is looked for in the desk's folder, where it is not -- so the run fails
/// on every desk, every time. Refused with how to write it. A global widget
/// runs in its own folder, where everything reaches.
pub fn lint(spec: &Spec, folder: &Path) -> Result<(), String> {
    if spec.scope == Scope::Global {
        return Ok(());
    }
    let ends = |w: &str| matches!(w, ";" | "&&" | "||" | "|" | "&" | "(" | "{");
    let mut first = true;
    for raw in spec.run.command.split_whitespace() {
        if ends(raw) {
            first = true;
            continue;
        }
        let then_first = raw.ends_with(';') || raw.ends_with('&') || raw.ends_with('|');
        let w = raw
            .trim_end_matches([';', '&', '|'])
            .trim_matches(|c| c == '"' || c == '\'');
        let skip = w.is_empty()
            || w.starts_with(['-', '$', '%', '~', '/', '\\'])
            || (first && w.contains('='))
            || w.contains("://");
        if !skip {
            let rel = w
                .strip_prefix("./")
                .or_else(|| w.strip_prefix(".\\"))
                .unwrap_or(w);
            let here = !rel.is_empty() && !rel.starts_with("..") && folder.join(rel).is_file();
            let pathed = w.contains(['/', '\\']);
            if here && (pathed || !first) {
                let sep = if cfg!(windows) { "\\" } else { "/" };
                return Err(format!(
                    "{rel} is in the widget's folder, but a desk widget runs in the desk's folder, where it is not: \
                     write \"{DIR_VAR}{sep}{rel}\" instead, or {rel} alone as the command for a script that runs by itself"
                ));
            }
            if here && first && !runnable(&folder.join(rel)) {
                return Err(format!(
                    "{rel} is named as the command but cannot run by itself: make it executable, \
                     or write sh \"{DIR_VAR}/{rel}\""
                ));
            }
        }
        // `LANG=C run.sh`: an assignment leaves the command still to come.
        if !(first && w.contains('=')) {
            first = false;
        }
        if then_first {
            first = true;
        }
    }
    Ok(())
}

/// Whether a file runs by itself: executable here, and on Windows by its
/// extension, which the shell goes by.
fn runnable(f: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(f).is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
    }
    #[cfg(not(unix))]
    {
        f.extension().is_some()
    }
}

/// A starter widget, for `snyvi widget new`: a `widget.json` and a script
/// that prints a body, on this system's shell.
pub fn starter(name: &str, scope: Scope) -> (String, &'static str, String) {
    let script = if cfg!(windows) { "run.ps1" } else { "run.sh" };
    // By name, as a desk widget must (`lint`): its folder is first on PATH.
    let command = if cfg!(windows) {
        format!("powershell -NoProfile -ExecutionPolicy Bypass -File \"{DIR_VAR}\\run.ps1\"")
    } else {
        "run.sh".to_string()
    };
    let spec = Spec {
        name: name.to_string(),
        title: super::title_of(name),
        scope,
        run: Run {
            command,
            every: 30,
            timeout: 5,
        },
        lines: 2,
        settings: BTreeMap::new(),
    };
    let json = serde_json::to_string_pretty(&spec).unwrap_or_default() + "\n";
    let body = if cfg!(windows) {
        "# stdin: {\"desk\":{...},\"settings\":{...},\"snyvi\":\"<version>\"}\n\
         # Print Markdown, or one JSON object: {\"body\":\"...\",\"tone\":\"ok\",\"count\":\"3\"}\n\
         $now = Get-Date -Format HH:mm\n\
         Write-Output \"**$(Split-Path -Leaf (Get-Location))** · $now\"\n"
            .to_string()
    } else {
        "#!/bin/sh\n\
         # stdin: {\"desk\":{...},\"settings\":{...},\"snyvi\":\"<version>\"}\n\
         # cwd: the desk's folder (a desk widget) or this folder (a global one);\n\
         # this folder is $SNYVI_WIDGET_DIR, first on PATH.\n\
         # Print Markdown, or one JSON object: {\"body\":\"...\",\"tone\":\"ok\",\"count\":\"3\"}\n\
         printf '**%s** · %s\\n' \"$(basename \"$PWD\")\" \"$(date +%H:%M)\"\n"
            .to_string()
    };
    (json, script, body)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn folder(tag: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("snyvi-wfiles-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(dir(&d).join("git")).unwrap();
        d
    }

    #[test]
    fn a_spec_is_read_and_bounded() {
        let cfg = folder("read");
        let w = dir(&cfg).join("git");
        std::fs::write(
            w.join("widget.json"),
            r#"{"name":"git","run":{"command":"./run.sh","every":1,"timeout":99},"lines":9,
               "settings":{"base":{"type":"string","default":"main"}}}"#,
        )
        .unwrap();
        let found = scan(&cfg);
        assert_eq!(found.len(), 1);
        let s = found[0].spec.clone().unwrap();
        assert_eq!(
            (s.run.every, s.run.timeout, s.lines),
            (EVERY_MIN, TIMEOUT_MAX, LINES_MAX)
        );
        assert_eq!(s.title, "Git");
        assert_eq!(
            s.settings_with(r#"{"base":"dev","other":1}"#),
            serde_json::json!({ "base": "dev" })
        );
        assert_eq!(s.settings_with("{}"), serde_json::json!({ "base": "main" }));
        let _ = std::fs::remove_dir_all(&cfg);
    }

    #[test]
    fn a_folder_that_says_another_name_is_listed_with_why() {
        let cfg = folder("name");
        std::fs::write(
            dir(&cfg).join("git").join("widget.json"),
            r#"{"name":"ci","run":{"command":"x"}}"#,
        )
        .unwrap();
        let found = scan(&cfg);
        assert!(found[0]
            .spec
            .as_ref()
            .unwrap_err()
            .contains("in a folder called git"));
        let _ = std::fs::remove_dir_all(&cfg);
    }

    #[test]
    fn the_hash_covers_every_file_and_has_a_cap() {
        let cfg = folder("hash");
        let w = dir(&cfg).join("git");
        std::fs::write(w.join("run.sh"), "echo a").unwrap();
        let a = hash(&w).unwrap();
        std::fs::create_dir_all(w.join("lib")).unwrap();
        std::fs::write(w.join("lib").join("x.sh"), "echo b").unwrap();
        let b = hash(&w).unwrap();
        assert_ne!(a, b, "a file the script could source is in the hash");
        assert_eq!(b, hash(&w).unwrap());
        std::fs::write(w.join("big"), vec![b'x'; FOLDER_MAX as usize]).unwrap();
        assert!(hash(&w).unwrap_err().contains("more than 64 KB"));
        let _ = std::fs::remove_dir_all(&cfg);
    }

    #[cfg(unix)]
    fn desk_spec(command: &str) -> Spec {
        Spec {
            name: "git".into(),
            title: "Git".into(),
            scope: Scope::Desk,
            run: Run {
                command: command.into(),
                every: 30,
                timeout: 5,
            },
            lines: 2,
            settings: BTreeMap::new(),
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_desk_widget_must_reach_its_own_files() {
        use std::os::unix::fs::PermissionsExt;
        let cfg = folder("lint");
        let w = dir(&cfg).join("git");
        std::fs::write(w.join("run.sh"), "#!/bin/sh\necho hi\n").unwrap();
        std::fs::set_permissions(w.join("run.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::write(w.join("x.js"), "1").unwrap();
        for bad in [
            "./run.sh",
            "sh run.sh",
            "node x.js",
            "cd . && sh ./run.sh",
            "true; node x.js",
        ] {
            let why = lint(&desk_spec(bad), &w).unwrap_err();
            assert!(why.contains("$SNYVI_WIDGET_DIR/"), "{bad}: {why}");
        }
        for good in [
            "run.sh",
            "sh \"$SNYVI_WIDGET_DIR/run.sh\"",
            "node \"$SNYVI_WIDGET_DIR/x.js\"",
            "git status --short",
            "LANG=C run.sh",
            "true && run.sh",
        ] {
            assert_eq!(lint(&desk_spec(good), &w), Ok(()), "{good}");
        }
        // A script named as the command has to be able to run.
        std::fs::set_permissions(w.join("run.sh"), std::fs::Permissions::from_mode(0o644)).unwrap();
        assert!(lint(&desk_spec("run.sh"), &w)
            .unwrap_err()
            .contains("make it executable"));
        // A global widget runs in its own folder: anything reaches.
        let mut g = desk_spec("sh ./run.sh");
        g.scope = Scope::Global;
        assert_eq!(lint(&g, &w), Ok(()));
        let _ = std::fs::remove_dir_all(&cfg);
    }

    #[cfg(unix)]
    #[test]
    fn a_starter_passes_its_own_check() {
        use std::os::unix::fs::PermissionsExt;
        let cfg = folder("starter");
        let w = dir(&cfg).join("git");
        let (json, script, body) = starter("git", Scope::Desk);
        std::fs::write(w.join("widget.json"), json).unwrap();
        std::fs::write(w.join(script), body).unwrap();
        std::fs::set_permissions(w.join(script), std::fs::Permissions::from_mode(0o755)).unwrap();
        let spec = read(&w, "git").unwrap();
        assert_eq!(lint(&spec, &w), Ok(()));
        let _ = std::fs::remove_dir_all(&cfg);
    }

    #[test]
    fn a_starter_reads_back() {
        let (json, _, _) = starter("disk-free", Scope::Global);
        let s: Spec = serde_json::from_str(&json).unwrap();
        assert_eq!(
            (s.name.as_str(), s.title.as_str(), s.scope),
            ("disk-free", "Disk free", Scope::Global)
        );
    }
}