sim-web-shell 0.1.8

sim-web-shell: the binary that serves the SIM WebUI shell.
Documentation
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
//! Tests for the shell asset routing.

use std::sync::Arc;

use crate::{AtelierCliLib, BrowseCliLib, ServeConfig, assets::asset_for, serve_with_cx};
use sim_codec_lisp::LispCodecLib;
use sim_kernel::{Args, Cx, DefaultFactory, NoopEvalPolicy, Symbol, Value, read_eval_capability};
use sim_lib_server::CookbookWebState;
use sim_test_support::core_cx;

#[test]
fn root_serves_the_shell_page() {
    let asset = asset_for("/").expect("root must resolve to the shell");
    assert_eq!(asset.content_type, "text/html; charset=utf-8");
    let body = std::str::from_utf8(asset.body).expect("shell is utf-8");
    assert!(
        body.contains("SIM Web-UI"),
        "shell page must carry the title"
    );
}

#[test]
fn index_html_aliases_root() {
    let root = asset_for("/").expect("root");
    let index = asset_for("/index.html").expect("index");
    assert_eq!(root.body, index.body);
}

#[test]
fn query_strings_are_ignored_when_routing() {
    let asset = asset_for("/styles/theme.css?v=1").expect("css with query string");
    assert_eq!(asset.content_type, "text/css; charset=utf-8");
}

#[test]
fn unknown_paths_fail_closed() {
    assert!(asset_for("/secret").is_none());
    assert!(asset_for("/../Cargo.toml").is_none());
}

#[test]
fn interpreter_modules_are_served_as_javascript() {
    for path in [
        "/interpreter/app.js",
        "/interpreter/scene.js",
        "/interpreter/diff.js",
        "/interpreter/intent.js",
    ] {
        let asset = asset_for(path).unwrap_or_else(|| panic!("{path} must be served"));
        assert_eq!(asset.content_type, "text/javascript; charset=utf-8");
        assert!(!asset.body.is_empty(), "{path} must have a body");
    }
}

#[test]
fn the_session_bridge_module_is_served() {
    let asset = asset_for("/interpreter/session.js").expect("session module must be served");
    assert_eq!(asset.content_type, "text/javascript; charset=utf-8");
    let body = std::str::from_utf8(asset.body).unwrap();
    assert!(
        body.contains("/api/session/intent"),
        "the bridge posts intents to the session route"
    );
}

#[test]
fn the_app_wires_the_live_session_bridge() {
    let js = asset_text("/interpreter/app.js");
    assert!(
        js.contains("postIntent"),
        "app forwards intents to the bridge"
    );
    assert!(js.contains("openSession"), "app opens the initial scene");
    assert!(
        js.contains("sim-scene-patch"),
        "app dispatches scene patches for diff.js to apply"
    );
}

#[test]
fn the_shell_page_loads_the_interpreter_module() {
    let asset = asset_for("/").expect("root");
    let body = std::str::from_utf8(asset.body).unwrap();
    assert!(
        body.contains("/interpreter/app.js"),
        "the shell page must load the interpreter entry module"
    );
}

#[test]
fn root_shell_has_cookbook_nav_link() {
    let body = asset_text("/");
    assert!(
        body.contains("href=\"/cookbook\""),
        "root links to cookbook"
    );
    assert!(body.contains(">Cookbook<"), "link is labeled Cookbook");
    assert!(body.contains("href=\"/atelier\""), "root links to Atelier");
    assert!(body.contains(">Atelier<"), "link is labeled Atelier");
}

#[test]
fn cookbook_route_serves_page_layout() {
    let asset = asset_for("/cookbook").expect("cookbook page");
    assert_eq!(asset.content_type, "text/html; charset=utf-8");
    let body = std::str::from_utf8(asset.body).unwrap();
    assert!(body.contains("id=\"cookbook-search\""), "has search box");
    assert!(body.contains("id=\"cookbook-tree\""), "has left rail tree");
    assert!(body.contains("id=\"recipe-pane\""), "has main pane");
    assert!(
        body.contains("data-api-root=\"/api/cookbook\""),
        "uses cookbook API"
    );
}

#[test]
fn cookbook_assets_are_served() {
    let css = asset_for("/cookbook/cookbook.css").expect("cookbook css");
    assert_eq!(css.content_type, "text/css; charset=utf-8");
    let js = asset_for("/cookbook/cookbook.js").expect("cookbook js");
    assert_eq!(js.content_type, "text/javascript; charset=utf-8");
}

#[test]
fn atelier_route_serves_page_layout() {
    let asset = asset_for("/atelier").expect("atelier page");
    assert_eq!(asset.content_type, "text/html; charset=utf-8");
    let body = std::str::from_utf8(asset.body).unwrap();
    assert!(body.contains("id=\"atelier-app\""), "has Atelier app mount");
    assert!(
        body.contains("data-api-root=\"/api/atelier\""),
        "uses Atelier API"
    );
    assert!(body.contains("/atelier/atelier.js"), "loads Atelier script");
}

#[test]
fn atelier_assets_are_served() {
    let css = asset_for("/atelier/atelier.css").expect("atelier css");
    assert_eq!(css.content_type, "text/css; charset=utf-8");
    let js = asset_for("/atelier/atelier.js").expect("atelier js");
    assert_eq!(js.content_type, "text/javascript; charset=utf-8");
}

#[test]
fn atelier_script_targets_shell_api_and_panels() {
    let js = asset_text("/atelier/atelier.js");
    for expected in [
        "/api/atelier",
        "#atelier-navigation",
        "#atelier-panels",
        "#atelier-radar",
        "#atelier-firewall",
    ] {
        assert!(js.contains(expected), "missing {expected}");
    }
}

#[test]
fn atelier_cli_lib_claims_loaded_cli_entrypoint() {
    let mut cx = cli_cx();
    cx.load_lib(&AtelierCliLib).unwrap();
    let envelope = cli_envelope(&mut cx, "atelier", &["atelier", "--dry-run"]);
    let value = cx
        .call_function(
            &Symbol::qualified("cli", "main/atelier"),
            Args::new(vec![envelope]),
        )
        .unwrap();

    assert!(value.object().truth(&mut cx).unwrap());
}

#[test]
fn browse_cli_lib_claims_loaded_cli_entrypoint() {
    let mut cx = cli_cx();
    cx.load_lib(&BrowseCliLib).unwrap();
    let envelope = cli_envelope(&mut cx, "browse", &["browse"]);
    let value = cx
        .call_function(
            &Symbol::qualified("cli", "main/browse"),
            Args::new(vec![envelope]),
        )
        .unwrap();

    assert!(value.object().truth(&mut cx).unwrap());
}

#[test]
fn cookbook_script_targets_required_apis() {
    let js = asset_text("/cookbook/cookbook.js");
    for expected in [
        "/api/cookbook",
        "/search?q=",
        "/recipe/",
        "/run",
        "method: \"POST\"",
    ] {
        assert!(js.contains(expected), "missing {expected}");
    }
    assert!(js.contains("Next recipe ->"), "has next control text");
}

#[test]
fn cookbook_script_renders_grouped_tree_with_badges() {
    // The browser renders the two-level family -> domain grouped tree with a
    // runnable/descriptor badge on each leaf.
    let js = asset_text("/cookbook/cookbook.js");
    for expected in [
        "data.families",
        "state.families",
        "family-title",
        "domain-title",
        "recipeBadge",
        "sandbox-descriptor",
    ] {
        assert!(js.contains(expected), "missing {expected}");
    }
    let css = asset_text("/cookbook/cookbook.css");
    for expected in [".badge.runnable", ".badge.descriptor", ".domain-title"] {
        assert!(css.contains(expected), "css missing {expected}");
    }
}

#[test]
fn cookbook_script_renders_lifecycle_actions() {
    let js = asset_text("/cookbook/cookbook.js");
    for expected in [
        "recipe.action === \"load\"",
        "recipe.action === \"unload\"",
        "recipe.lib",
        "recipe.loaded",
        "actionLabel(recipe)",
        "runSelectedRecipe(recipe, results)",
        "await loadCookbook({",
        "recipe.action === \"unload\" ? \"load\" : null",
        "dataset.recipeAction",
        "dataset.recipeLib",
        "dataset.recipeLoaded",
    ] {
        assert!(js.contains(expected), "missing {expected}");
    }
    let css = asset_text("/cookbook/cookbook.css");
    for expected in [
        ".badge.lifecycle.load",
        ".badge.lifecycle.unload",
        ".lifecycle-meta",
        ".recipe-actions button.lifecycle-action.load",
        ".recipe-actions button.lifecycle-action.unload",
    ] {
        assert!(css.contains(expected), "css missing {expected}");
    }
}

#[test]
fn web_serve_does_not_preload_demo_codecs() {
    let serve = include_str!("serve.rs");
    for forbidden in [
        "JsonCodecLib",
        "BinaryCodecLib",
        "ChatCodecLib",
        "AlgolCodecLib",
        "install_codecs",
    ] {
        assert!(
            !serve.contains(forbidden),
            "serve.rs still contains {forbidden}"
        );
    }
    assert!(
        serve.contains("CookbookWebState::seeded()"),
        "serve.rs must build cookbook state from the loadable directory"
    );

    let mut cx = cli_cx();
    serve_with_cx(
        &mut cx,
        &ServeConfig {
            dry_run: true,
            ..ServeConfig::default()
        },
    )
    .unwrap();
    let loaded: Vec<String> = cx
        .registry()
        .libs()
        .iter()
        .map(|lib| lib.manifest.id.as_qualified_str())
        .collect();
    for forbidden in [
        "codec/json",
        "codec/binary",
        "codec/chat",
        "codec/algol",
        "numbers/i64",
        "numbers/cas",
    ] {
        assert!(
            !loaded.iter().any(|id| id == forbidden),
            "dry-run preloaded {forbidden}: {loaded:?}"
        );
    }
}

#[test]
fn standalone_serve_config_uses_seeded_fixture_directory() {
    let mut cx = cookbook_cx();
    let response = crate::serve::cookbook_index_for_test(&mut cx, &ServeConfig::default()).unwrap();
    assert_eq!(response.status, 200, "{}", response.body);
    let json: serde_json::Value = serde_json::from_str(&response.body).unwrap();
    let libs = json["libs"]
        .as_array()
        .unwrap_or_else(|| panic!("libs array in {}", response.body));

    assert!(
        libs.iter()
            .any(|lib| lib["id"].as_str() == Some("numbers/cas")),
        "{}",
        response.body
    );
}

#[test]
fn serve_config_can_use_host_cookbook_state() {
    let mut cx = cookbook_cx();
    let response = crate::serve::cookbook_index_for_test(
        &mut cx,
        &ServeConfig {
            cookbook: Some(Arc::new(CookbookWebState::empty())),
            ..ServeConfig::default()
        },
    )
    .unwrap();
    assert_eq!(response.status, 200, "{}", response.body);
    let json: serde_json::Value = serde_json::from_str(&response.body).unwrap();

    assert_eq!(
        json["libs"]
            .as_array()
            .unwrap_or_else(|| panic!("libs array in {}", response.body))
            .len(),
        0
    );
    assert!(!response.body.contains("numbers/cas"), "{}", response.body);
}

fn asset_text(path: &str) -> String {
    let asset = asset_for(path).unwrap_or_else(|| panic!("{path} must be served"));
    std::str::from_utf8(asset.body).unwrap().to_owned()
}

fn cli_cx() -> Cx {
    Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory))
}

fn cookbook_cx() -> Cx {
    let mut cx = core_cx();
    let lisp = LispCodecLib::new(cx.registry_mut().fresh_codec_id()).unwrap();
    cx.load_lib(&lisp).unwrap();
    cx.grant(read_eval_capability());
    cx
}

fn cli_envelope(cx: &mut Cx, verb: &str, args: &[&str]) -> Value {
    let verb = cx.factory().string(verb.to_owned()).unwrap();
    let args = cx
        .factory()
        .list(
            args.iter()
                .map(|arg| cx.factory().string((*arg).to_owned()).unwrap())
                .collect(),
        )
        .unwrap();
    cx.factory()
        .table(vec![
            (Symbol::new("verb"), verb),
            (Symbol::new("args"), args),
        ])
        .unwrap()
}

#[test]
fn the_theme_defines_motion_focus_and_reduced_motion_rules() {
    let css = asset_text("/styles/theme.css");
    // Reduced-motion mode disables animation in the interpreter, not per lens.
    assert!(
        css.contains("prefers-reduced-motion"),
        "honors OS reduced-motion"
    );
    assert!(
        css.contains("data-reduced-motion"),
        "honors explicit reduced-motion"
    );
    // Visible focus on canvas/graph surfaces, not only DOM controls.
    assert!(
        css.contains(":focus-visible"),
        "defines a visible focus ring"
    );
    assert!(css.contains("--focus-ring"), "has a focus-ring token");
    // Motion and icon tokens live in the theme, not per lens.
    assert!(css.contains("--motion-base"), "has motion tokens");
    assert!(css.contains("--icon-play"), "has an icon set");
    // Status never relies on color alone: badges carry a shape glyph.
    assert!(
        css.contains(".badge.error::before"),
        "status carries a non-color token"
    );
}

#[test]
fn the_interpreter_labels_interactive_nodes_for_screen_readers() {
    let js = asset_text("/interpreter/scene.js");
    assert!(
        js.contains("aria-label"),
        "interactive nodes carry screen-reader labels"
    );
    assert!(js.contains("tabindex"), "canvas nodes are focusable");
    assert!(js.contains("role"), "interactive nodes carry roles");
}

#[test]
fn the_shell_supports_reduced_motion_and_keyboard_operation() {
    let js = asset_text("/interpreter/app.js");
    assert!(
        js.contains("prefers-reduced-motion"),
        "applies reduced-motion"
    );
    assert!(js.contains("keydown"), "installs a keyboard spine");
}