@native-sdk/cli 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/build/app.zig +371 -5
  2. package/build/ts_run.mjs +102 -0
  3. package/build.zig +255 -1
  4. package/build.zig.zon +1 -0
  5. package/package.json +19 -10
  6. package/packages/core/package-lock.json +44 -0
  7. package/packages/core/package.json +38 -0
  8. package/packages/core/rt/rt.zig +1579 -0
  9. package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
  10. package/packages/core/sdk/core.ts +694 -0
  11. package/packages/core/sdk/events.ts +137 -0
  12. package/packages/core/sdk/text.ts +519 -0
  13. package/packages/core/src/checker.ts +1869 -0
  14. package/packages/core/src/cli.ts +68 -0
  15. package/packages/core/src/devhost.ts +291 -0
  16. package/packages/core/src/devhost_resolver.mjs +22 -0
  17. package/packages/core/src/diagnostics.ts +417 -0
  18. package/packages/core/src/emitter.ts +8815 -0
  19. package/packages/core/src/infer.ts +1515 -0
  20. package/packages/core/src/modules.ts +173 -0
  21. package/packages/core/src/ownership.ts +740 -0
  22. package/packages/core/src/text_polyfill.ts +337 -0
  23. package/packages/core/src/text_tables.ts +408 -0
  24. package/packages/core/src/transpile.ts +146 -0
  25. package/packages/core/src/typed_ast.ts +546 -0
  26. package/packages/core/src/types.ts +815 -0
  27. package/skill-data/native-ui/SKILL.md +14 -0
  28. package/skill-data/ts-core/SKILL.md +493 -0
  29. package/skill-data/zig/SKILL.md +10 -0
  30. package/src/app_runner/root.zig +24 -0
  31. package/src/app_runner/ts_core_main.zig +231 -0
  32. package/src/platform/windows/webview2_host.cpp +24 -0
  33. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  34. package/src/primitives/app_manifest/root.zig +5 -0
  35. package/src/primitives/canvas/commands.zig +14 -7
  36. package/src/primitives/canvas/layout_audit.zig +5 -5
  37. package/src/primitives/canvas/lazy_tls.zig +73 -0
  38. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  39. package/src/primitives/canvas/root.zig +11 -0
  40. package/src/primitives/canvas/tests.zig +1 -0
  41. package/src/primitives/canvas/text_atlas.zig +40 -32
  42. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  43. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  44. package/src/primitives/canvas/text_spans.zig +39 -26
  45. package/src/primitives/canvas/tokens.zig +69 -0
  46. package/src/primitives/canvas/ui.zig +125 -0
  47. package/src/primitives/canvas/ui_markup.zig +22 -3
  48. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  49. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  50. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  51. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  52. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  53. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  54. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  55. package/src/primitives/canvas/ui_schema.zig +8 -0
  56. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  57. package/src/primitives/canvas/widget_builtin_tests.zig +309 -5
  58. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  59. package/src/primitives/canvas/widget_layout.zig +138 -2
  60. package/src/primitives/canvas/widget_metrics.zig +16 -8
  61. package/src/primitives/canvas/widget_render.zig +25 -15
  62. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  63. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  64. package/src/root.zig +7 -0
  65. package/src/runtime/canvas_frame.zig +57 -36
  66. package/src/runtime/canvas_images.zig +9 -3
  67. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  68. package/src/runtime/canvas_widget_runtime.zig +7 -4
  69. package/src/runtime/core.zig +16 -0
  70. package/src/runtime/effects.zig +1525 -133
  71. package/src/runtime/effects_fetch_tests.zig +42 -0
  72. package/src/runtime/effects_file_tests.zig +220 -0
  73. package/src/runtime/effects_host_tests.zig +594 -0
  74. package/src/runtime/effects_tests.zig +287 -0
  75. package/src/runtime/root.zig +18 -0
  76. package/src/runtime/session_replay.zig +7 -1
  77. package/src/runtime/tests.zig +2 -0
  78. package/src/runtime/ts_core_host.zig +1505 -0
  79. package/src/runtime/ts_core_host_tests.zig +1408 -0
  80. package/src/runtime/ts_ui_app.zig +469 -0
  81. package/src/runtime/ui_app.zig +189 -38
  82. package/src/runtime/ui_app_tests.zig +221 -0
  83. package/src/runtime/ui_app_window_tests.zig +182 -0
  84. package/src/runtime/view_canvas.zig +24 -17
  85. package/src/runtime/view_widget_tree.zig +2 -2
  86. package/src/tooling/codesign.zig +212 -105
  87. package/src/tooling/doctor.zig +78 -0
  88. package/src/tooling/manifest.zig +47 -0
  89. package/src/tooling/package.zig +435 -20
  90. package/src/tooling/raw_manifest.zig +15 -0
  91. package/src/tooling/root.zig +1 -0
  92. package/src/tooling/templates.zig +777 -34
  93. package/src/tooling/ts_core.zig +1099 -0
  94. package/src/tooling/verbs.zig +105 -2
@@ -0,0 +1,1408 @@
1
+ //! Bridge coverage for `TsCoreHost` against a hand-written core that
2
+ //! replicates the transpiler's emitted ABI (rt kernel, commit walker,
3
+ //! `UpdateResult`/`InitResult`, wire-encoded commands and
4
+ //! subscriptions). Hand-encoding the wire records here pins the v2
5
+ //! byte layout independently of the rt builders that normally produce
6
+ //! it; the transpiled-fixture end-to-end suite (tests/ts-core) drives
7
+ //! the same bridge with genuinely emitted code through a full UiApp.
8
+ //! Everything runs the effects channel directly with the fake executor
9
+ //! — deterministic request/feed round trips, no platform.
10
+
11
+ const std = @import("std");
12
+ const effects_mod = @import("effects.zig");
13
+ const runtime_clock = @import("clock.zig");
14
+ const ts_core_host = @import("ts_core_host.zig");
15
+
16
+ // ------------------------------------------------------ the mini core
17
+ //
18
+ // The emitted-core ABI in miniature: a two-region kernel, a poller
19
+ // model, and an update that exercises every wire record. Cmd/Sub bytes
20
+ // are hand-encoded to the documented v2 layout. Polling starts OFF so
21
+ // the real-executor tests below (which bind no platform timer service)
22
+ // never arm a timer; the e2e suite covers boot-time subscriptions
23
+ // through a full UiApp with live null-platform services.
24
+
25
+ const mini_core = struct {
26
+ pub const rt = struct {
27
+ var frame_buf: [64 * 1024]u8 align(16) = undefined;
28
+ var frame_off: usize = 0;
29
+ var heap_buf: [64 * 1024]u8 align(16) = undefined;
30
+ var heap_off: usize = 0;
31
+
32
+ pub fn frameAlloc(comptime T: type, n: usize) []T {
33
+ const aligned = std.mem.alignForward(usize, frame_off, @alignOf(T));
34
+ const next = aligned + n * @sizeOf(T);
35
+ if (next > frame_buf.len) @panic("mini core: frame overflow");
36
+ frame_off = next;
37
+ const ptr: [*]T = @ptrCast(@alignCast(frame_buf[aligned..].ptr));
38
+ return ptr[0..n];
39
+ }
40
+
41
+ pub fn frameReset() void {
42
+ frame_off = 0;
43
+ }
44
+
45
+ pub fn resetAll() void {
46
+ frame_off = 0;
47
+ heap_off = 0;
48
+ }
49
+
50
+ fn inFrame(addr: usize) bool {
51
+ const base = @intFromPtr(&frame_buf);
52
+ return addr >= base and addr < base + frame_buf.len;
53
+ }
54
+
55
+ fn heapAlloc(comptime T: type, n: usize) []T {
56
+ const aligned = std.mem.alignForward(usize, heap_off, @alignOf(T));
57
+ const next = aligned + n * @sizeOf(T);
58
+ if (next > heap_buf.len) @panic("mini core: heap overflow");
59
+ heap_off = next;
60
+ const ptr: [*]T = @ptrCast(@alignCast(heap_buf[aligned..].ptr));
61
+ return ptr[0..n];
62
+ }
63
+ };
64
+
65
+ /// The audio event state union, deliberately declared in an order
66
+ /// DIFFERENT from the engine's `EffectAudioEventKind`: the bridge
67
+ /// matches members by NAME, so the app's declaration order is free.
68
+ pub const AudioState = enum { spectrum, loaded, completed, position, rejected, failed };
69
+
70
+ pub const Model = struct {
71
+ polling: bool,
72
+ fast: bool,
73
+ ticks: i64,
74
+ last_ms: f64,
75
+ stamp_ms: f64,
76
+ errs: i64,
77
+ saved: bool,
78
+ code: i64,
79
+ status: []const u8,
80
+ last_err: []const u8,
81
+ // Spawn stream mirrors.
82
+ line_count: i64,
83
+ last_line: []const u8,
84
+ exit_code: i64,
85
+ output: []const u8,
86
+ // Audio stream mirrors.
87
+ audio_state: AudioState,
88
+ position_ms: f64,
89
+ duration_ms: f64,
90
+ playing: bool,
91
+ buffering: bool,
92
+ bands: []const u8,
93
+ audio_events: i64,
94
+ };
95
+
96
+ pub const Msg = union(enum) {
97
+ toggle, // 0: pure — pauses/resumes the subscription
98
+ speed, // 1: pure — switches the tick interval (re-arm case)
99
+ refresh, // 2: keyed request (replaces a live "status" request)
100
+ pair, // 3: two unkeyed requests in one batch (ordering)
101
+ abort, // 4: cancel "status"
102
+ stamp, // 5: Cmd.now -> .stamped
103
+ note, // 6: persist ++ host(scalars) ++ host_bytes
104
+ loaded: []const u8, // 7: ok route (bytes)
105
+ failed: []const u8, // 8: err route (reason bytes)
106
+ tick: f64, // 9: subscription arm
107
+ stamped: f64, // 10: now arm / delay arm
108
+ save_file, // 11: write_file "save" -> wrote/failed
109
+ wrote, // 12: write_file's payload-less ok route
110
+ load_file, // 13: read_file "load" -> loaded/failed
111
+ get, // 14: fetch "get" -> fetched/failed
112
+ fetched: struct { status: i64, body: []const u8 }, // 15: fetch ok record
113
+ copy, // 16: clip_write (fire-and-forget)
114
+ paste, // 17: clip_read "paste" -> loaded/failed
115
+ arm_delay, // 18: delay "boom" 250ms -> stamped
116
+ halt, // 19: cancel "boom"
117
+ drop_load, // 20: cancel "load"
118
+ dup_load, // 21: two read_file "load" in one batch (dup reject)
119
+ run_lines, // 22: spawn "job" lines -> got_line/job_done/failed
120
+ run_quiet, // 23: spawn "job" lines, NO line arm (0xFF)
121
+ run_collect, // 24: spawn "job" collect -> sampled/failed
122
+ got_line: []const u8, // 25: spawn line arm
123
+ job_done: i64, // 26: line-mode exit arm (the code)
124
+ sampled: struct { code: i64, output: []const u8 }, // 27: collect exit record
125
+ stop_job, // 28: cancel "job" (mid-stream)
126
+ dup_job, // 29: two spawns under one key in one batch
127
+ play, // 30: audio_play "track" (local path) -> audio_evt
128
+ play_stream, // 31: audio_play "track" (url + cache + expected)
129
+ audio_evt: struct { // 32: the six-field audio event arm (the
130
+ // emitted shape — payload fields keep their TS names)
131
+ state: AudioState,
132
+ positionMs: f64,
133
+ durationMs: f64,
134
+ playing: bool,
135
+ buffering: bool,
136
+ bands: []const u8,
137
+ },
138
+ pause_it, // 33: audio_ctl pause "track"
139
+ resume_it, // 34: audio_ctl resume "track"
140
+ stop_it, // 35: audio_ctl stop "track"
141
+ seek_it, // 36: audio_ctl seek "track" 45000ms
142
+ vol_it, // 37: audio_ctl volume "track" 0.25
143
+ ctl_stray, // 38: audio_ctl pause "other" (key gate no-op)
144
+ play_bare_url, // 39: audio_play "track" (url, NO cache path)
145
+ drop_save, // 40: cancel "save" (silent write_file drop)
146
+ drop_get, // 41: cancel "get" (silent fetch drop)
147
+ drop_paste, // 42: cancel "paste" (silent clip_read drop)
148
+ };
149
+
150
+ pub const InitResult = struct { model: *const Model, cmd: []const u8 };
151
+ pub const UpdateResult = struct { model: *const Model, cmd: []const u8 };
152
+
153
+ fn frameCreate(value: Model) *Model {
154
+ const slot = rt.frameAlloc(Model, 1);
155
+ slot[0] = value;
156
+ return &slot[0];
157
+ }
158
+
159
+ pub fn initialModel() InitResult {
160
+ return .{
161
+ .model = frameCreate(.{
162
+ .polling = false,
163
+ .fast = false,
164
+ .ticks = 0,
165
+ .last_ms = -1,
166
+ .stamp_ms = -1,
167
+ .errs = 0,
168
+ .saved = false,
169
+ .code = -1,
170
+ .status = "",
171
+ .last_err = "",
172
+ .line_count = 0,
173
+ .last_line = "",
174
+ .exit_code = -1,
175
+ .output = "",
176
+ .audio_state = .rejected,
177
+ .position_ms = -1,
178
+ .duration_ms = -1,
179
+ .playing = false,
180
+ .buffering = false,
181
+ .bands = "",
182
+ .audio_events = 0,
183
+ }),
184
+ .cmd = cmdRequest("status.read", "status", 7, 8, "boot"),
185
+ };
186
+ }
187
+
188
+ pub fn update(model: *const Model, msg: Msg) UpdateResult {
189
+ switch (msg) {
190
+ .toggle => {
191
+ const out = frameCreate(model.*);
192
+ out.polling = !model.polling;
193
+ return .{ .model = out, .cmd = "" };
194
+ },
195
+ .speed => {
196
+ const out = frameCreate(model.*);
197
+ out.fast = !model.fast;
198
+ return .{ .model = out, .cmd = "" };
199
+ },
200
+ .refresh => return .{ .model = model, .cmd = cmdRequest("status.read", "status", 7, 8, model.status) },
201
+ .pair => {
202
+ const first = cmdRequest("a.read", "", 7, 8, "1");
203
+ const second = cmdRequest("b.read", "", 7, 8, "2");
204
+ const out = rt.frameAlloc(u8, first.len + second.len);
205
+ @memcpy(out[0..first.len], first);
206
+ @memcpy(out[first.len..], second);
207
+ return .{ .model = model, .cmd = out };
208
+ },
209
+ .abort => return .{ .model = model, .cmd = cmdCancel("status") },
210
+ .stamp => return .{ .model = model, .cmd = cmdNow(10) },
211
+ .note => {
212
+ const persist = [_]u8{0x01};
213
+ const host = cmdHost("gain.set", &.{ 0.5, 2.0 });
214
+ const host_bytes = cmdHostBytes("blob.put", "hi");
215
+ const out = rt.frameAlloc(u8, persist.len + host.len + host_bytes.len);
216
+ @memcpy(out[0..1], &persist);
217
+ @memcpy(out[1..][0..host.len], host);
218
+ @memcpy(out[1 + host.len ..], host_bytes);
219
+ return .{ .model = model, .cmd = out };
220
+ },
221
+ .loaded => |body| {
222
+ const out = frameCreate(model.*);
223
+ out.status = body;
224
+ return .{ .model = out, .cmd = "" };
225
+ },
226
+ .failed => |why| {
227
+ const out = frameCreate(model.*);
228
+ out.errs = model.errs + 1;
229
+ out.last_err = why;
230
+ return .{ .model = out, .cmd = "" };
231
+ },
232
+ .save_file => return .{ .model = model, .cmd = cmdWriteFile("save", 12, 8, "notes.bin", model.status) },
233
+ .wrote => {
234
+ const out = frameCreate(model.*);
235
+ out.saved = true;
236
+ return .{ .model = out, .cmd = "" };
237
+ },
238
+ .load_file => return .{ .model = model, .cmd = cmdReadFile("load", 7, 8, "notes.bin") },
239
+ .get => {
240
+ const headers = [_]FetchHeader{.{ .name = "accept", .value = "text/plain" }};
241
+ return .{ .model = model, .cmd = cmdFetch("get", 15, 8, 1, 0, "https://status.test/q", &headers, "ask") };
242
+ },
243
+ .fetched => |response| {
244
+ const out = frameCreate(model.*);
245
+ out.code = response.status;
246
+ out.status = response.body;
247
+ return .{ .model = out, .cmd = "" };
248
+ },
249
+ .copy => return .{ .model = model, .cmd = cmdClipWrite("hi") },
250
+ .paste => return .{ .model = model, .cmd = cmdClipRead("paste", 7, 8) },
251
+ .arm_delay => return .{ .model = model, .cmd = cmdDelay("boom", 250, 10) },
252
+ .halt => return .{ .model = model, .cmd = cmdCancel("boom") },
253
+ .drop_load => return .{ .model = model, .cmd = cmdCancel("load") },
254
+ .dup_load => {
255
+ const first = cmdReadFile("load", 7, 8, "notes.bin");
256
+ const second = cmdReadFile("load", 7, 8, "notes.bin");
257
+ const out = rt.frameAlloc(u8, first.len + second.len);
258
+ @memcpy(out[0..first.len], first);
259
+ @memcpy(out[first.len..], second);
260
+ return .{ .model = model, .cmd = out };
261
+ },
262
+ .tick => |at| {
263
+ const out = frameCreate(model.*);
264
+ out.ticks = model.ticks + 1;
265
+ out.last_ms = at;
266
+ return .{ .model = out, .cmd = "" };
267
+ },
268
+ .stamped => |at| {
269
+ const out = frameCreate(model.*);
270
+ out.stamp_ms = at;
271
+ return .{ .model = out, .cmd = "" };
272
+ },
273
+ .run_lines => return .{ .model = model, .cmd = cmdSpawn("job", 25, 26, 8, 0, &.{ "/bin/probe", "--fast" }, "feed me") },
274
+ .run_quiet => return .{ .model = model, .cmd = cmdSpawn("job", 0xFF, 26, 8, 0, &.{"/bin/quiet"}, "") },
275
+ .run_collect => return .{ .model = model, .cmd = cmdSpawn("job", 0xFF, 27, 8, 1, &.{ "/bin/ps", "-axo" }, "") },
276
+ .got_line => |line| {
277
+ const out = frameCreate(model.*);
278
+ out.line_count = model.line_count + 1;
279
+ out.last_line = line;
280
+ return .{ .model = out, .cmd = "" };
281
+ },
282
+ .job_done => |code| {
283
+ const out = frameCreate(model.*);
284
+ out.exit_code = code;
285
+ return .{ .model = out, .cmd = "" };
286
+ },
287
+ .sampled => |result| {
288
+ const out = frameCreate(model.*);
289
+ out.exit_code = result.code;
290
+ out.output = result.output;
291
+ return .{ .model = out, .cmd = "" };
292
+ },
293
+ .stop_job => return .{ .model = model, .cmd = cmdCancel("job") },
294
+ .dup_job => {
295
+ const first = cmdSpawn("job", 0xFF, 26, 8, 0, &.{"/bin/one"}, "");
296
+ const second = cmdSpawn("job", 0xFF, 26, 8, 0, &.{"/bin/two"}, "");
297
+ const out = rt.frameAlloc(u8, first.len + second.len);
298
+ @memcpy(out[0..first.len], first);
299
+ @memcpy(out[first.len..], second);
300
+ return .{ .model = model, .cmd = out };
301
+ },
302
+ .play => return .{ .model = model, .cmd = cmdAudioPlay("track", 32, "music/a.mp3", "", "", 0) },
303
+ .play_stream => return .{ .model = model, .cmd = cmdAudioPlay("track", 32, "", "https://cdn.test/a.mp3", "cache/a.mp3", 4096) },
304
+ .audio_evt => |event| {
305
+ const out = frameCreate(model.*);
306
+ out.audio_state = event.state;
307
+ out.position_ms = event.positionMs;
308
+ out.duration_ms = event.durationMs;
309
+ out.playing = event.playing;
310
+ out.buffering = event.buffering;
311
+ out.bands = event.bands;
312
+ out.audio_events = model.audio_events + 1;
313
+ return .{ .model = out, .cmd = "" };
314
+ },
315
+ .pause_it => return .{ .model = model, .cmd = cmdAudioCtl("track", 0, 0) },
316
+ .resume_it => return .{ .model = model, .cmd = cmdAudioCtl("track", 1, 0) },
317
+ .stop_it => return .{ .model = model, .cmd = cmdAudioCtl("track", 2, 0) },
318
+ .seek_it => return .{ .model = model, .cmd = cmdAudioCtl("track", 3, 45_000) },
319
+ .vol_it => return .{ .model = model, .cmd = cmdAudioCtl("track", 4, 0.25) },
320
+ .ctl_stray => return .{ .model = model, .cmd = cmdAudioCtl("other", 0, 0) },
321
+ .play_bare_url => return .{ .model = model, .cmd = cmdAudioPlay("track", 32, "", "https://cdn.test/b.mp3", "", 0) },
322
+ .drop_save => return .{ .model = model, .cmd = cmdCancel("save") },
323
+ .drop_get => return .{ .model = model, .cmd = cmdCancel("get") },
324
+ .drop_paste => return .{ .model = model, .cmd = cmdCancel("paste") },
325
+ }
326
+ }
327
+
328
+ pub fn subscriptions(model: *const Model) []const u8 {
329
+ if (!model.polling) return "";
330
+ return subTimer("tick", if (model.fast) 40 else 100, 9);
331
+ }
332
+
333
+ pub fn commitModelRoot(next: *const Model) *const Model {
334
+ if (!rt.inFrame(@intFromPtr(next))) return next;
335
+ const out = rt.heapAlloc(Model, 1);
336
+ out[0] = next.*;
337
+ out[0].status = commitBytes(next.status);
338
+ out[0].last_err = commitBytes(next.last_err);
339
+ out[0].last_line = commitBytes(next.last_line);
340
+ out[0].output = commitBytes(next.output);
341
+ out[0].bands = commitBytes(next.bands);
342
+ return &out[0];
343
+ }
344
+
345
+ fn commitBytes(bytes: []const u8) []const u8 {
346
+ if (bytes.len == 0 or !rt.inFrame(@intFromPtr(bytes.ptr))) return bytes;
347
+ const out = rt.heapAlloc(u8, bytes.len);
348
+ @memcpy(out, bytes);
349
+ return out;
350
+ }
351
+
352
+ // Hand-encoded v2 wire records (rt.zig's documented layout).
353
+
354
+ fn cmdNow(msg_tag: u8) []const u8 {
355
+ const out = rt.frameAlloc(u8, 2);
356
+ out[0] = 0x02;
357
+ out[1] = msg_tag;
358
+ return out;
359
+ }
360
+
361
+ fn cmdHost(name: []const u8, args: []const f64) []const u8 {
362
+ const out = rt.frameAlloc(u8, 3 + name.len + args.len * 8);
363
+ out[0] = 0x03;
364
+ out[1] = @intCast(name.len);
365
+ @memcpy(out[2..][0..name.len], name);
366
+ out[2 + name.len] = @intCast(args.len);
367
+ for (args, 0..) |arg, i| {
368
+ std.mem.writeInt(u64, out[3 + name.len + i * 8 ..][0..8], @bitCast(arg), .little);
369
+ }
370
+ return out;
371
+ }
372
+
373
+ fn cmdHostBytes(name: []const u8, payload: []const u8) []const u8 {
374
+ const out = rt.frameAlloc(u8, 2 + name.len + 4 + payload.len);
375
+ out[0] = 0x04;
376
+ out[1] = @intCast(name.len);
377
+ @memcpy(out[2..][0..name.len], name);
378
+ std.mem.writeInt(u32, out[2 + name.len ..][0..4], @intCast(payload.len), .little);
379
+ @memcpy(out[2 + name.len + 4 ..][0..payload.len], payload);
380
+ return out;
381
+ }
382
+
383
+ fn cmdRequest(name: []const u8, key: []const u8, ok_tag: u8, err_tag: u8, payload: []const u8) []const u8 {
384
+ const out = rt.frameAlloc(u8, 2 + name.len + 1 + key.len + 2 + 4 + payload.len);
385
+ out[0] = 0x05;
386
+ out[1] = @intCast(name.len);
387
+ @memcpy(out[2..][0..name.len], name);
388
+ var off: usize = 2 + name.len;
389
+ out[off] = @intCast(key.len);
390
+ @memcpy(out[off + 1 ..][0..key.len], key);
391
+ off += 1 + key.len;
392
+ out[off] = ok_tag;
393
+ out[off + 1] = err_tag;
394
+ std.mem.writeInt(u32, out[off + 2 ..][0..4], @intCast(payload.len), .little);
395
+ @memcpy(out[off + 6 ..][0..payload.len], payload);
396
+ return out;
397
+ }
398
+
399
+ fn cmdCancel(key: []const u8) []const u8 {
400
+ const out = rt.frameAlloc(u8, 2 + key.len);
401
+ out[0] = 0x06;
402
+ out[1] = @intCast(key.len);
403
+ @memcpy(out[2..][0..key.len], key);
404
+ return out;
405
+ }
406
+
407
+ const FetchHeader = struct { name: []const u8, value: []const u8 };
408
+
409
+ fn writeRoutedHead(out: []u8, op: u8, key: []const u8, ok_tag: u8, err_tag: u8) usize {
410
+ out[0] = op;
411
+ out[1] = @intCast(key.len);
412
+ @memcpy(out[2..][0..key.len], key);
413
+ out[2 + key.len] = ok_tag;
414
+ out[3 + key.len] = err_tag;
415
+ return 4 + key.len;
416
+ }
417
+
418
+ fn writeLongBytes(out: []u8, at: usize, bytes: []const u8) usize {
419
+ std.mem.writeInt(u32, out[at..][0..4], @intCast(bytes.len), .little);
420
+ @memcpy(out[at + 4 ..][0..bytes.len], bytes);
421
+ return at + 4 + bytes.len;
422
+ }
423
+
424
+ fn cmdReadFile(key: []const u8, ok_tag: u8, err_tag: u8, file_path: []const u8) []const u8 {
425
+ const out = rt.frameAlloc(u8, 4 + key.len + 4 + file_path.len);
426
+ var off = writeRoutedHead(out, 0x07, key, ok_tag, err_tag);
427
+ off = writeLongBytes(out, off, file_path);
428
+ return out;
429
+ }
430
+
431
+ fn cmdWriteFile(key: []const u8, ok_tag: u8, err_tag: u8, file_path: []const u8, bytes: []const u8) []const u8 {
432
+ const out = rt.frameAlloc(u8, 4 + key.len + 4 + file_path.len + 4 + bytes.len);
433
+ var off = writeRoutedHead(out, 0x08, key, ok_tag, err_tag);
434
+ off = writeLongBytes(out, off, file_path);
435
+ off = writeLongBytes(out, off, bytes);
436
+ return out;
437
+ }
438
+
439
+ fn cmdFetch(key: []const u8, ok_tag: u8, err_tag: u8, method: u8, timeout_ms: u32, url: []const u8, headers: []const FetchHeader, body: []const u8) []const u8 {
440
+ var header_bytes: usize = 0;
441
+ for (headers) |h| header_bytes += 1 + h.name.len + 4 + h.value.len;
442
+ const out = rt.frameAlloc(u8, 4 + key.len + 1 + 4 + 4 + url.len + 1 + header_bytes + 4 + body.len);
443
+ var off = writeRoutedHead(out, 0x09, key, ok_tag, err_tag);
444
+ out[off] = method;
445
+ std.mem.writeInt(u32, out[off + 1 ..][0..4], timeout_ms, .little);
446
+ off += 5;
447
+ off = writeLongBytes(out, off, url);
448
+ out[off] = @intCast(headers.len);
449
+ off += 1;
450
+ for (headers) |h| {
451
+ out[off] = @intCast(h.name.len);
452
+ @memcpy(out[off + 1 ..][0..h.name.len], h.name);
453
+ off += 1 + h.name.len;
454
+ off = writeLongBytes(out, off, h.value);
455
+ }
456
+ off = writeLongBytes(out, off, body);
457
+ return out;
458
+ }
459
+
460
+ fn cmdClipWrite(bytes: []const u8) []const u8 {
461
+ const out = rt.frameAlloc(u8, 1 + 4 + bytes.len);
462
+ out[0] = 0x0A;
463
+ _ = writeLongBytes(out, 1, bytes);
464
+ return out;
465
+ }
466
+
467
+ fn cmdClipRead(key: []const u8, ok_tag: u8, err_tag: u8) []const u8 {
468
+ const out = rt.frameAlloc(u8, 4 + key.len);
469
+ _ = writeRoutedHead(out, 0x0B, key, ok_tag, err_tag);
470
+ return out;
471
+ }
472
+
473
+ fn cmdDelay(key: []const u8, after_ms: f64, msg_tag: u8) []const u8 {
474
+ const out = rt.frameAlloc(u8, 2 + key.len + 8 + 1);
475
+ out[0] = 0x0C;
476
+ out[1] = @intCast(key.len);
477
+ @memcpy(out[2..][0..key.len], key);
478
+ std.mem.writeInt(u64, out[2 + key.len ..][0..8], @bitCast(after_ms), .little);
479
+ out[2 + key.len + 8] = msg_tag;
480
+ return out;
481
+ }
482
+
483
+ fn cmdSpawn(key: []const u8, line_tag: u8, exit_tag: u8, err_tag: u8, mode: u8, argv: []const []const u8, stdin: []const u8) []const u8 {
484
+ var argv_bytes: usize = 0;
485
+ for (argv) |arg| argv_bytes += 4 + arg.len;
486
+ const out = rt.frameAlloc(u8, 2 + key.len + 5 + argv_bytes + 4 + stdin.len);
487
+ out[0] = 0x0D;
488
+ out[1] = @intCast(key.len);
489
+ @memcpy(out[2..][0..key.len], key);
490
+ var off: usize = 2 + key.len;
491
+ out[off] = line_tag;
492
+ out[off + 1] = exit_tag;
493
+ out[off + 2] = err_tag;
494
+ out[off + 3] = mode;
495
+ out[off + 4] = @intCast(argv.len);
496
+ off += 5;
497
+ for (argv) |arg| off = writeLongBytes(out, off, arg);
498
+ _ = writeLongBytes(out, off, stdin);
499
+ return out;
500
+ }
501
+
502
+ fn cmdAudioPlay(key: []const u8, event_tag: u8, audio_path: []const u8, url: []const u8, cache_path: []const u8, expected_bytes: f64) []const u8 {
503
+ const out = rt.frameAlloc(u8, 2 + key.len + 1 + 4 + audio_path.len + 4 + url.len + 4 + cache_path.len + 8);
504
+ out[0] = 0x0E;
505
+ out[1] = @intCast(key.len);
506
+ @memcpy(out[2..][0..key.len], key);
507
+ var off: usize = 2 + key.len;
508
+ out[off] = event_tag;
509
+ off += 1;
510
+ off = writeLongBytes(out, off, audio_path);
511
+ off = writeLongBytes(out, off, url);
512
+ off = writeLongBytes(out, off, cache_path);
513
+ std.mem.writeInt(u64, out[off..][0..8], @bitCast(expected_bytes), .little);
514
+ return out;
515
+ }
516
+
517
+ fn cmdAudioCtl(key: []const u8, verb: u8, value: f64) []const u8 {
518
+ const out = rt.frameAlloc(u8, 2 + key.len + 1 + 8);
519
+ out[0] = 0x0F;
520
+ out[1] = @intCast(key.len);
521
+ @memcpy(out[2..][0..key.len], key);
522
+ out[2 + key.len] = verb;
523
+ std.mem.writeInt(u64, out[2 + key.len + 1 ..][0..8], @bitCast(value), .little);
524
+ return out;
525
+ }
526
+
527
+ fn subTimer(key: []const u8, every_ms: f64, msg_tag: u8) []const u8 {
528
+ const out = rt.frameAlloc(u8, 2 + key.len + 8 + 1);
529
+ out[0] = 0x01;
530
+ out[1] = @intCast(key.len);
531
+ @memcpy(out[2..][0..key.len], key);
532
+ std.mem.writeInt(u64, out[2 + key.len ..][0..8], @bitCast(every_ms), .little);
533
+ out[2 + key.len + 8] = msg_tag;
534
+ return out;
535
+ }
536
+ };
537
+
538
+ const Host = ts_core_host.TsCoreHost(mini_core);
539
+ const Fx = Host.Fx;
540
+
541
+ const boot_request_key: u64 = ts_core_host.request_key_base + 0;
542
+ const tick_timer_key: u64 = ts_core_host.timer_key_base + 0;
543
+
544
+ // The channel is a large fixed-buffer struct; one static instance per
545
+ // test process keeps it off the test stack. Tests run sequentially.
546
+ var channel: Fx = undefined;
547
+
548
+ fn freshChannel() *Fx {
549
+ channel = Fx.init(std.testing.allocator);
550
+ channel.executor = .fake;
551
+ return &channel;
552
+ }
553
+
554
+ // -------------------------------------------------------------- tests
555
+
556
+ test "init commits the boot model and issues the init request before the first frame" {
557
+ const fx = freshChannel();
558
+ defer fx.deinit();
559
+ Host.init(fx);
560
+
561
+ try std.testing.expect(!Host.model().polling);
562
+ try std.testing.expectEqualStrings("", Host.model().status);
563
+
564
+ // The boot command parked as a keyed host request, slot 0.
565
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingHostCount());
566
+ const request = fx.pendingHostAt(0).?;
567
+ try std.testing.expectEqual(boot_request_key, request.key);
568
+ try std.testing.expectEqualStrings("status.read", request.name);
569
+ try std.testing.expectEqualStrings("boot", request.payload);
570
+ }
571
+
572
+ test "a routed result dispatches the ok arm and the bytes commit into the model heap" {
573
+ const fx = freshChannel();
574
+ defer fx.deinit();
575
+ Host.init(fx);
576
+
577
+ try fx.feedHostResult(boot_request_key, true, "ready");
578
+ Host.drain(fx);
579
+ try std.testing.expectEqualStrings("ready", Host.model().status);
580
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingHostCount());
581
+
582
+ // The model's copy survives the engine retiring its drain scratch:
583
+ // a later delivery (which frees the previous drain buffer) must not
584
+ // disturb it. That is the frame-copy contract working.
585
+ const kept = Host.model().status;
586
+ Host.dispatch(fx, .refresh);
587
+ try fx.feedHostResult(boot_request_key, false, "nope");
588
+ Host.drain(fx);
589
+ try std.testing.expectEqualStrings("ready", kept);
590
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
591
+ try std.testing.expectEqualStrings("ready", Host.model().status);
592
+ }
593
+
594
+ test "re-issuing a live key replaces the pending request and delivers exactly once" {
595
+ const fx = freshChannel();
596
+ defer fx.deinit();
597
+ Host.init(fx);
598
+
599
+ // The boot request (wire key "status") is in flight; refresh
600
+ // re-issues the same wire key with a different payload.
601
+ Host.dispatch(fx, .{ .loaded = "cache" });
602
+ Host.dispatch(fx, .refresh);
603
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingHostCount());
604
+ const request = fx.pendingHostAt(0).?;
605
+ try std.testing.expectEqual(boot_request_key, request.key);
606
+ try std.testing.expectEqualStrings("cache", request.payload);
607
+
608
+ try fx.feedHostResult(boot_request_key, true, "fresh");
609
+ Host.drain(fx);
610
+ try std.testing.expectEqualStrings("fresh", Host.model().status);
611
+ // Exactly one terminal: the queue is empty and the key is retired.
612
+ try std.testing.expect(fx.takeMsg() == null);
613
+ try std.testing.expectError(error.EffectNotFound, fx.feedHostResult(boot_request_key, true, "late"));
614
+ }
615
+
616
+ test "cancel drops the in-flight request silently" {
617
+ const fx = freshChannel();
618
+ defer fx.deinit();
619
+ Host.init(fx);
620
+
621
+ Host.dispatch(fx, .abort);
622
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingHostCount());
623
+ try std.testing.expectError(error.EffectNotFound, fx.feedHostResult(boot_request_key, true, "late"));
624
+ // Silent: nothing to drain, neither arm ran.
625
+ try std.testing.expect(fx.takeMsg() == null);
626
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
627
+ try std.testing.expectEqualStrings("", Host.model().status);
628
+
629
+ // A cancel that lands after the answer (fed, not yet drained) still
630
+ // drops the result.
631
+ Host.dispatch(fx, .refresh);
632
+ try fx.feedHostResult(boot_request_key, true, "raced");
633
+ Host.dispatch(fx, .abort);
634
+ Host.drain(fx);
635
+ try std.testing.expectEqualStrings("", Host.model().status);
636
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
637
+ }
638
+
639
+ test "unkeyed requests dispatch in completion order" {
640
+ const fx = freshChannel();
641
+ defer fx.deinit();
642
+ Host.init(fx);
643
+ // Retire the boot request so the tables start clean.
644
+ try fx.feedHostResult(boot_request_key, true, "");
645
+ Host.drain(fx);
646
+
647
+ Host.dispatch(fx, .pair);
648
+ try std.testing.expectEqual(@as(usize, 2), fx.pendingHostCount());
649
+ const first = fx.pendingHostAt(0).?;
650
+ const second = fx.pendingHostAt(1).?;
651
+ try std.testing.expectEqualStrings("a.read", first.name);
652
+ try std.testing.expectEqualStrings("b.read", second.name);
653
+ try std.testing.expect(first.key != second.key);
654
+
655
+ // Answer out of issue order: completion order wins at the drain,
656
+ // so the second answer is the last one the model absorbed.
657
+ try fx.feedHostResult(second.key, true, "from-b");
658
+ try fx.feedHostResult(first.key, true, "from-a");
659
+ Host.drain(fx);
660
+ try std.testing.expectEqualStrings("from-a", Host.model().status);
661
+ }
662
+
663
+ test "subscription reconcile arms, pauses, resumes, and re-arms on interval change" {
664
+ const fx = freshChannel();
665
+ defer fx.deinit();
666
+ Host.init(fx);
667
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingTimerCount());
668
+
669
+ // New key arms the first free slot, repeating, wire interval.
670
+ Host.dispatch(fx, .toggle);
671
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingTimerCount());
672
+ const timer = fx.pendingTimerAt(0).?;
673
+ try std.testing.expectEqual(tick_timer_key, timer.key);
674
+ try std.testing.expectEqual(@as(u64, 100), timer.interval_ms);
675
+ try std.testing.expectEqual(effects_mod.TimerMode.repeating, timer.mode);
676
+
677
+ // Missing key cancels; reappearing key re-arms into the same slot
678
+ // (slot order, never hash order).
679
+ Host.dispatch(fx, .toggle);
680
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingTimerCount());
681
+ Host.dispatch(fx, .toggle);
682
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingTimerCount());
683
+ try std.testing.expectEqual(tick_timer_key, fx.pendingTimerAt(0).?.key);
684
+
685
+ // Interval change re-arms the same key in place.
686
+ Host.dispatch(fx, .speed);
687
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingTimerCount());
688
+ try std.testing.expectEqual(tick_timer_key, fx.pendingTimerAt(0).?.key);
689
+ try std.testing.expectEqual(@as(u64, 40), fx.pendingTimerAt(0).?.interval_ms);
690
+ }
691
+
692
+ test "timer fires dispatch the named arm with the fire time" {
693
+ const fx = freshChannel();
694
+ defer fx.deinit();
695
+ Host.init(fx);
696
+ Host.dispatch(fx, .toggle);
697
+
698
+ try fx.fireTimer(tick_timer_key);
699
+ try fx.fireTimer(tick_timer_key);
700
+ Host.drain(fx);
701
+ try std.testing.expectEqual(@as(i64, 2), Host.model().ticks);
702
+ // Fake fires carry timestamp 0 (the fake executor has no clock).
703
+ try std.testing.expectEqual(@as(f64, 0), Host.model().last_ms);
704
+ }
705
+
706
+ test "Cmd.now dispatches synchronously with the journaled clock" {
707
+ const fx = freshChannel();
708
+ defer fx.deinit();
709
+ var clock = runtime_clock.TestClock{};
710
+ clock.setWallMs(1_234);
711
+ fx.clock = clock.clock();
712
+
713
+ const Capture = struct {
714
+ var kinds: [8]effects_mod.EffectResultKind = undefined;
715
+ var count: usize = 0;
716
+ fn record(context: *anyopaque, record_value: effects_mod.EffectResultRecord) void {
717
+ _ = context;
718
+ kinds[count] = record_value.kind;
719
+ count += 1;
720
+ }
721
+ };
722
+ Capture.count = 0;
723
+ var context: u8 = 0;
724
+ fx.bindJournal(.{ .context = &context, .record_fn = Capture.record });
725
+
726
+ Host.init(fx);
727
+ Host.dispatch(fx, .stamp);
728
+ // Synchronous: the stamped arm ran before dispatch returned, with
729
+ // the clock read journaled for replay.
730
+ try std.testing.expectEqual(@as(f64, 1_234), Host.model().stamp_ms);
731
+ try std.testing.expectEqual(@as(usize, 1), Capture.count);
732
+ try std.testing.expectEqual(effects_mod.EffectResultKind.clock, Capture.kinds[0]);
733
+ }
734
+
735
+ test "fire-and-forget records ride the host-call binding in wire order" {
736
+ const fx = freshChannel();
737
+ defer fx.deinit();
738
+ fx.executor = .real;
739
+
740
+ const Stub = struct {
741
+ var names: [4][32]u8 = undefined;
742
+ var payloads: [4][32]u8 = undefined;
743
+ var lens: [4][2]usize = undefined;
744
+ var count: usize = 0;
745
+ fn send(context: *anyopaque, name: []const u8, payload: []const u8) void {
746
+ _ = context;
747
+ @memcpy(names[count][0..name.len], name);
748
+ @memcpy(payloads[count][0..payload.len], payload);
749
+ lens[count] = .{ name.len, payload.len };
750
+ count += 1;
751
+ }
752
+ fn request(context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void {
753
+ _ = context;
754
+ _ = name;
755
+ _ = key;
756
+ _ = payload;
757
+ }
758
+ };
759
+ Stub.count = 0;
760
+ var context: u8 = 0;
761
+ fx.bindHostCalls(.{ .context = &context, .send_fn = Stub.send, .request_fn = Stub.request });
762
+
763
+ Host.init(fx);
764
+ Host.dispatch(fx, .note);
765
+
766
+ // persist -> core.persist, host -> the scalar arg block (f64 LE),
767
+ // host_bytes -> the raw payload; wire record order preserved.
768
+ try std.testing.expectEqual(@as(usize, 3), Stub.count);
769
+ try std.testing.expectEqualStrings("core.persist", Stub.names[0][0..Stub.lens[0][0]]);
770
+ try std.testing.expectEqual(@as(usize, 0), Stub.lens[0][1]);
771
+ try std.testing.expectEqualStrings("gain.set", Stub.names[1][0..Stub.lens[1][0]]);
772
+ var args: [16]u8 = undefined;
773
+ std.mem.writeInt(u64, args[0..8], @bitCast(@as(f64, 0.5)), .little);
774
+ std.mem.writeInt(u64, args[8..16], @bitCast(@as(f64, 2.0)), .little);
775
+ try std.testing.expectEqualSlices(u8, &args, Stub.payloads[1][0..Stub.lens[1][1]]);
776
+ try std.testing.expectEqualStrings("blob.put", Stub.names[2][0..Stub.lens[2][0]]);
777
+ try std.testing.expectEqualStrings("hi", Stub.payloads[2][0..Stub.lens[2][1]]);
778
+ }
779
+
780
+ test "a request round-trips through a real host-call binding" {
781
+ const fx = freshChannel();
782
+ defer fx.deinit();
783
+ fx.executor = .real;
784
+
785
+ // The stub host service answers synchronously from request_fn —
786
+ // the same feed path an async host completion uses later.
787
+ const Stub = struct {
788
+ var bound: ?*Fx = null;
789
+ fn send(context: *anyopaque, name: []const u8, payload: []const u8) void {
790
+ _ = context;
791
+ _ = name;
792
+ _ = payload;
793
+ }
794
+ fn request(context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void {
795
+ _ = context;
796
+ _ = payload;
797
+ if (std.mem.eql(u8, name, "status.read")) {
798
+ bound.?.feedHostResult(key, true, "live-answer") catch unreachable;
799
+ } else {
800
+ bound.?.feedHostResult(key, false, "no such service") catch unreachable;
801
+ }
802
+ }
803
+ };
804
+ Stub.bound = fx;
805
+ var context: u8 = 0;
806
+ fx.bindHostCalls(.{ .context = &context, .send_fn = Stub.send, .request_fn = Stub.request });
807
+
808
+ Host.init(fx);
809
+ Host.drain(fx);
810
+ try std.testing.expectEqualStrings("live-answer", Host.model().status);
811
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
812
+ }
813
+
814
+ test "a real-mode request without bound host services rejects loudly through the err arm" {
815
+ const fx = freshChannel();
816
+ defer fx.deinit();
817
+ fx.executor = .real;
818
+
819
+ Host.init(fx);
820
+ Host.drain(fx);
821
+ // The boot request could not run: exactly one err-route Msg.
822
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
823
+ try std.testing.expectEqualStrings("", Host.model().status);
824
+ }
825
+
826
+ // ------------------------------------------------- named engine ops
827
+
828
+ const load_effect_key: u64 = ts_core_host.effect_key_base + 0;
829
+
830
+ test "read_file issues the engine op and routes ok bytes / err reason arms" {
831
+ const fx = freshChannel();
832
+ defer fx.deinit();
833
+ Host.init(fx);
834
+
835
+ Host.dispatch(fx, .load_file);
836
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFileCount());
837
+ const request = fx.pendingFileAt(0).?;
838
+ try std.testing.expectEqual(load_effect_key, request.key);
839
+ try std.testing.expectEqual(effects_mod.EffectFileOp.read, request.op);
840
+ try std.testing.expectEqualStrings("notes.bin", request.path);
841
+
842
+ try fx.feedFileResult(load_effect_key, .ok, "disk bytes");
843
+ Host.drain(fx);
844
+ try std.testing.expectEqualStrings("disk bytes", Host.model().status);
845
+
846
+ // The entry retired: the same slot re-issues, and a non-ok outcome
847
+ // routes the err arm with the outcome's name as bytes.
848
+ Host.dispatch(fx, .load_file);
849
+ try fx.feedFileResult(load_effect_key, .not_found, "");
850
+ Host.drain(fx);
851
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
852
+ try std.testing.expectEqualStrings("not_found", Host.model().last_err);
853
+ try std.testing.expectEqualStrings("disk bytes", Host.model().status);
854
+ }
855
+
856
+ test "write_file routes its payload-less ok arm and err reasons" {
857
+ const fx = freshChannel();
858
+ defer fx.deinit();
859
+ Host.init(fx);
860
+ Host.dispatch(fx, .{ .loaded = "content" });
861
+
862
+ Host.dispatch(fx, .save_file);
863
+ const request = fx.pendingFileAt(0).?;
864
+ try std.testing.expectEqual(effects_mod.EffectFileOp.write, request.op);
865
+ try std.testing.expectEqualStrings("notes.bin", request.path);
866
+ try std.testing.expectEqualStrings("content", request.bytes);
867
+
868
+ try fx.feedFileResult(load_effect_key, .ok, "");
869
+ Host.drain(fx);
870
+ try std.testing.expect(Host.model().saved);
871
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
872
+
873
+ Host.dispatch(fx, .save_file);
874
+ try fx.feedFileResult(load_effect_key, .io_failed, "");
875
+ Host.drain(fx);
876
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
877
+ try std.testing.expectEqualStrings("io_failed", Host.model().last_err);
878
+ }
879
+
880
+ test "fetch decodes the wire record whole and routes the { status, body } ok arm by field type" {
881
+ const fx = freshChannel();
882
+ defer fx.deinit();
883
+ Host.init(fx);
884
+
885
+ Host.dispatch(fx, .get);
886
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFetchCount());
887
+ const request = fx.pendingFetchAt(0).?;
888
+ try std.testing.expectEqual(load_effect_key, request.key);
889
+ try std.testing.expectEqual(std.http.Method.POST, request.method);
890
+ try std.testing.expectEqualStrings("https://status.test/q", request.url);
891
+ try std.testing.expectEqual(@as(usize, 1), request.headers.len);
892
+ try std.testing.expectEqualStrings("accept", request.headers[0].name);
893
+ try std.testing.expectEqualStrings("text/plain", request.headers[0].value);
894
+ try std.testing.expectEqualStrings("ask", request.body);
895
+
896
+ // A non-2xx status is still the ok route: an HTTP-level error is a
897
+ // delivered response, exactly the engine's contract.
898
+ try fx.feedResponse(load_effect_key, 404, "missing");
899
+ Host.drain(fx);
900
+ try std.testing.expectEqual(@as(i64, 404), Host.model().code);
901
+ try std.testing.expectEqualStrings("missing", Host.model().status);
902
+
903
+ // Transport failures route the err arm with the outcome name.
904
+ Host.dispatch(fx, .get);
905
+ try fx.feedResponseOutcome(load_effect_key, .timed_out, 0, "");
906
+ Host.drain(fx);
907
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
908
+ try std.testing.expectEqualStrings("timed_out", Host.model().last_err);
909
+ try std.testing.expectEqual(@as(i64, 404), Host.model().code);
910
+ }
911
+
912
+ test "fetch wire timeout 0 arms the engine default" {
913
+ const fx = freshChannel();
914
+ defer fx.deinit();
915
+ Host.init(fx);
916
+ Host.dispatch(fx, .get);
917
+ // The fake table records what the engine armed; wire 0 must never
918
+ // reach the engine as a zero timeout.
919
+ const slot = fx.pendingFetchAt(0).?;
920
+ _ = slot;
921
+ // FetchRequest carries no timeout; the arm not rejecting (a zero
922
+ // timeout is rejected by fetch validation) is the observable proof.
923
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFetchCount());
924
+ }
925
+
926
+ test "clip_write is fire-and-forget on a rotating key; clip_read routes ok and err arms" {
927
+ const fx = freshChannel();
928
+ defer fx.deinit();
929
+ Host.init(fx);
930
+
931
+ Host.dispatch(fx, .copy);
932
+ Host.dispatch(fx, .copy);
933
+ try std.testing.expectEqual(@as(usize, 2), fx.pendingClipboardCount());
934
+ const first = fx.pendingClipboardAt(0).?;
935
+ const second = fx.pendingClipboardAt(1).?;
936
+ try std.testing.expectEqual(effects_mod.EffectClipboardOp.write, first.op);
937
+ try std.testing.expectEqualStrings("hi", first.text);
938
+ try std.testing.expectEqual(ts_core_host.clip_write_key_base + 0, first.key);
939
+ try std.testing.expectEqual(ts_core_host.clip_write_key_base + 1, second.key);
940
+
941
+ // No routing: terminals deliver to nobody, models untouched.
942
+ try fx.feedClipboardResult(first.key, .ok, "");
943
+ try fx.feedClipboardResult(second.key, .failed, "");
944
+ Host.drain(fx);
945
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
946
+
947
+ Host.dispatch(fx, .paste);
948
+ const read = fx.pendingClipboardAt(0).?;
949
+ try std.testing.expectEqual(effects_mod.EffectClipboardOp.read, read.op);
950
+ try std.testing.expectEqual(load_effect_key, read.key);
951
+ try fx.feedClipboardResult(load_effect_key, .ok, "pasted text");
952
+ Host.drain(fx);
953
+ try std.testing.expectEqualStrings("pasted text", Host.model().status);
954
+
955
+ Host.dispatch(fx, .paste);
956
+ try fx.feedClipboardResult(load_effect_key, .failed, "");
957
+ Host.drain(fx);
958
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
959
+ try std.testing.expectEqualStrings("failed", Host.model().last_err);
960
+ }
961
+
962
+ test "a delay arms one-shot, re-arms on re-issue, fires once, and cancels silently" {
963
+ const fx = freshChannel();
964
+ defer fx.deinit();
965
+ Host.init(fx);
966
+
967
+ const delay_key: u64 = ts_core_host.delay_key_base + 0;
968
+ Host.dispatch(fx, .arm_delay);
969
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingTimerCount());
970
+ const timer = fx.pendingTimerAt(0).?;
971
+ try std.testing.expectEqual(delay_key, timer.key);
972
+ try std.testing.expectEqual(@as(u64, 250), timer.interval_ms);
973
+ try std.testing.expectEqual(effects_mod.TimerMode.one_shot, timer.mode);
974
+
975
+ // Re-issuing the live key re-arms the SAME slot (replace, not a
976
+ // second timer) — the debounce discipline.
977
+ Host.dispatch(fx, .arm_delay);
978
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingTimerCount());
979
+ try std.testing.expectEqual(delay_key, fx.pendingTimerAt(0).?.key);
980
+
981
+ // The fire dispatches the named number arm once and retires the
982
+ // slot: a second fire finds nothing.
983
+ try fx.fireTimer(delay_key);
984
+ Host.drain(fx);
985
+ try std.testing.expectEqual(@as(f64, 0), Host.model().stamp_ms);
986
+ try std.testing.expectError(error.EffectNotFound, fx.fireTimer(delay_key));
987
+
988
+ // Cancel is silent: armed, cancelled, never fires, nothing routes.
989
+ Host.dispatch(fx, .arm_delay);
990
+ Host.dispatch(fx, .halt);
991
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingTimerCount());
992
+ try std.testing.expectError(error.EffectNotFound, fx.fireTimer(delay_key));
993
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
994
+ }
995
+
996
+ test "reissuing a live named-op key replaces the op - the superseded result is dropped silently" {
997
+ const fx = freshChannel();
998
+ defer fx.deinit();
999
+ Host.init(fx);
1000
+
1001
+ // Two reads under one wire key in one command value: the second
1002
+ // REPLACES the first — the superseded op's engine call is cancelled
1003
+ // and only the new op stays live, under the next engine key.
1004
+ Host.dispatch(fx, .dup_load);
1005
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFileCount());
1006
+ // The superseded terminal routes NOTHING: no err arm, no message.
1007
+ Host.drain(fx);
1008
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1009
+ try std.testing.expectEqualStrings("", Host.model().last_err);
1010
+
1011
+ // Only the second op's result dispatches.
1012
+ try fx.feedFileResult(ts_core_host.effect_key_base + 1, .ok, "second wins");
1013
+ Host.drain(fx);
1014
+ try std.testing.expectEqualStrings("second wins", Host.model().status);
1015
+ }
1016
+
1017
+ test "issuing fetch under a live key replaces it - only the second response dispatches" {
1018
+ const fx = freshChannel();
1019
+ defer fx.deinit();
1020
+ Host.init(fx);
1021
+
1022
+ Host.dispatch(fx, .get);
1023
+ Host.dispatch(fx, .get);
1024
+ // One live fetch: the replacement, on the next engine key.
1025
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFetchCount());
1026
+ Host.drain(fx);
1027
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1028
+
1029
+ try fx.feedResponse(ts_core_host.effect_key_base + 1, 200, "fresh");
1030
+ Host.drain(fx);
1031
+ try std.testing.expectEqual(@as(i64, 200), Host.model().code);
1032
+ try std.testing.expectEqualStrings("fresh", Host.model().status);
1033
+ }
1034
+
1035
+ test "cancelling a named engine op is silent - no arm dispatches and the key frees" {
1036
+ const fx = freshChannel();
1037
+ defer fx.deinit();
1038
+ Host.init(fx);
1039
+
1040
+ Host.dispatch(fx, .load_file);
1041
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFileCount());
1042
+ Host.dispatch(fx, .drop_load);
1043
+ // The engine's `.cancelled` terminal retires the entry; the bridge
1044
+ // swallows it — nothing routes, matching request and delay.
1045
+ Host.drain(fx);
1046
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingFileCount());
1047
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1048
+ try std.testing.expectEqualStrings("", Host.model().last_err);
1049
+
1050
+ // The dropped entry retired with its swallowed terminal: the key is
1051
+ // free again and a fresh op under it delivers normally.
1052
+ Host.dispatch(fx, .load_file);
1053
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFileCount());
1054
+ try fx.feedFileResult(load_effect_key, .ok, "after cancel");
1055
+ Host.drain(fx);
1056
+ try std.testing.expectEqualStrings("after cancel", Host.model().status);
1057
+ }
1058
+
1059
+ test "cancel is silent for every named-op family - write_file, fetch, clip_read" {
1060
+ const fx = freshChannel();
1061
+ defer fx.deinit();
1062
+ Host.init(fx);
1063
+
1064
+ Host.dispatch(fx, .save_file);
1065
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFileCount());
1066
+ Host.dispatch(fx, .drop_save);
1067
+ Host.drain(fx);
1068
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingFileCount());
1069
+ try std.testing.expect(!Host.model().saved);
1070
+
1071
+ Host.dispatch(fx, .get);
1072
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingFetchCount());
1073
+ Host.dispatch(fx, .drop_get);
1074
+ Host.drain(fx);
1075
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingFetchCount());
1076
+ try std.testing.expectEqual(@as(i64, -1), Host.model().code);
1077
+
1078
+ Host.dispatch(fx, .paste);
1079
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingClipboardCount());
1080
+ Host.dispatch(fx, .drop_paste);
1081
+ Host.drain(fx);
1082
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingClipboardCount());
1083
+
1084
+ // Nothing routed anywhere: no ok arms, no err arms.
1085
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1086
+ try std.testing.expectEqualStrings("", Host.model().last_err);
1087
+ try std.testing.expectEqualStrings("", Host.model().status);
1088
+ }
1089
+
1090
+ // ------------------------------------------------------ spawn streams
1091
+
1092
+ const job_spawn_key: u64 = ts_core_host.spawn_key_base + 0;
1093
+
1094
+ test "a spawn stream decodes whole, routes lines repeatedly, and retires on the exit" {
1095
+ const fx = freshChannel();
1096
+ defer fx.deinit();
1097
+ Host.init(fx);
1098
+
1099
+ Host.dispatch(fx, .run_lines);
1100
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingSpawnCount());
1101
+ const request = fx.pendingSpawnAt(0).?;
1102
+ try std.testing.expectEqual(job_spawn_key, request.key);
1103
+ try std.testing.expectEqual(@as(usize, 2), request.argv.len);
1104
+ try std.testing.expectEqualStrings("/bin/probe", request.argv[0]);
1105
+ try std.testing.expectEqualStrings("--fast", request.argv[1]);
1106
+ try std.testing.expectEqualStrings("feed me", request.stdin);
1107
+ try std.testing.expectEqual(effects_mod.EffectOutputMode.lines, request.output);
1108
+
1109
+ // The NON-RETIRING stream contract: lines route the line arm across
1110
+ // separate drains, and the entry stays live between them.
1111
+ try fx.feedLine(job_spawn_key, "cpu 12.5");
1112
+ Host.drain(fx);
1113
+ try std.testing.expectEqual(@as(i64, 1), Host.model().line_count);
1114
+ try std.testing.expectEqualStrings("cpu 12.5", Host.model().last_line);
1115
+ try fx.feedLine(job_spawn_key, "cpu 40");
1116
+ try fx.feedLine(job_spawn_key, "cpu 7");
1117
+ Host.drain(fx);
1118
+ try std.testing.expectEqual(@as(i64, 3), Host.model().line_count);
1119
+ try std.testing.expectEqualStrings("cpu 7", Host.model().last_line);
1120
+
1121
+ // Exactly one terminal retires the entry: the exit code routes the
1122
+ // number arm, and the key is dead to further feeds.
1123
+ try fx.feedExit(job_spawn_key, 0);
1124
+ Host.drain(fx);
1125
+ try std.testing.expectEqual(@as(i64, 0), Host.model().exit_code);
1126
+ try std.testing.expectError(error.EffectNotFound, fx.feedLine(job_spawn_key, "late"));
1127
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1128
+
1129
+ // The wire key is free again for a fresh stream in the same slot.
1130
+ Host.dispatch(fx, .run_lines);
1131
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingSpawnCount());
1132
+ try std.testing.expectEqual(job_spawn_key, fx.pendingSpawnAt(0).?.key);
1133
+ }
1134
+
1135
+ test "a line spawn without a line arm drops lines and still routes its exit" {
1136
+ const fx = freshChannel();
1137
+ defer fx.deinit();
1138
+ Host.init(fx);
1139
+
1140
+ Host.dispatch(fx, .run_quiet);
1141
+ // No line routing (wire tag 0xFF): fed lines dispatch nothing.
1142
+ try fx.feedLine(job_spawn_key, "ignored");
1143
+ Host.drain(fx);
1144
+ try std.testing.expectEqual(@as(i64, 0), Host.model().line_count);
1145
+
1146
+ try fx.feedExit(job_spawn_key, 3);
1147
+ Host.drain(fx);
1148
+ try std.testing.expectEqual(@as(i64, 3), Host.model().exit_code);
1149
+ }
1150
+
1151
+ test "a collect spawn routes its exit as the { code, output } record by field type" {
1152
+ const fx = freshChannel();
1153
+ defer fx.deinit();
1154
+ Host.init(fx);
1155
+
1156
+ Host.dispatch(fx, .run_collect);
1157
+ const request = fx.pendingSpawnAt(0).?;
1158
+ try std.testing.expectEqual(effects_mod.EffectOutputMode.collect, request.output);
1159
+ try std.testing.expectEqualStrings("/bin/ps", request.argv[0]);
1160
+
1161
+ try fx.feedOutput(job_spawn_key, "PID CPU\n17 99.0\n");
1162
+ try fx.feedExit(job_spawn_key, 0);
1163
+ Host.drain(fx);
1164
+ try std.testing.expectEqual(@as(i64, 0), Host.model().exit_code);
1165
+ try std.testing.expectEqualStrings("PID CPU\n17 99.0\n", Host.model().output);
1166
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1167
+
1168
+ // A non-zero code is still the exit route — the process RAN; its
1169
+ // failure code is the app's to read.
1170
+ Host.dispatch(fx, .run_collect);
1171
+ try fx.feedExit(job_spawn_key, 1);
1172
+ Host.drain(fx);
1173
+ try std.testing.expectEqual(@as(i64, 1), Host.model().exit_code);
1174
+ try std.testing.expectEqual(@as(i64, 0), Host.model().errs);
1175
+ }
1176
+
1177
+ test "a truncated collect routes err - a cut stdout never parses as whole" {
1178
+ const fx = freshChannel();
1179
+ defer fx.deinit();
1180
+ Host.init(fx);
1181
+
1182
+ Host.dispatch(fx, .run_collect);
1183
+ // Overfill the collect buffer past the engine bound; the fake
1184
+ // executor mirrors the real truncation flag.
1185
+ const chunk = "x" ** 4096;
1186
+ var fed: usize = 0;
1187
+ while (fed <= effects_mod.max_effect_collect_bytes) : (fed += chunk.len) {
1188
+ try fx.feedOutput(job_spawn_key, chunk);
1189
+ }
1190
+ try fx.feedExit(job_spawn_key, 0);
1191
+ Host.drain(fx);
1192
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
1193
+ try std.testing.expectEqualStrings("truncated", Host.model().last_err);
1194
+ try std.testing.expectEqualStrings("", Host.model().output);
1195
+ }
1196
+
1197
+ test "cancelling a spawn mid-stream routes its err arm with cancelled and frees the key" {
1198
+ const fx = freshChannel();
1199
+ defer fx.deinit();
1200
+ Host.init(fx);
1201
+
1202
+ Host.dispatch(fx, .run_lines);
1203
+ try fx.feedLine(job_spawn_key, "first");
1204
+ Host.drain(fx);
1205
+ try std.testing.expectEqual(@as(i64, 1), Host.model().line_count);
1206
+
1207
+ // Mid-stream cancel: the engine ends the child and delivers the
1208
+ // `.cancelled` exit — never silent — retiring the entry.
1209
+ Host.dispatch(fx, .stop_job);
1210
+ Host.drain(fx);
1211
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
1212
+ try std.testing.expectEqualStrings("cancelled", Host.model().last_err);
1213
+ try std.testing.expectError(error.EffectNotFound, fx.feedLine(job_spawn_key, "late"));
1214
+ try std.testing.expectEqual(@as(i64, 1), Host.model().line_count);
1215
+
1216
+ // The key is free for a fresh stream.
1217
+ Host.dispatch(fx, .run_lines);
1218
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingSpawnCount());
1219
+ }
1220
+
1221
+ test "a duplicate spawn key rejects the new spawn through its err arm (the one exception)" {
1222
+ const fx = freshChannel();
1223
+ defer fx.deinit();
1224
+ Host.init(fx);
1225
+
1226
+ // A running subprocess is never killed implicitly: unlike the named
1227
+ // ops, a live spawn key REJECTS the new spawn — cancel it first.
1228
+ Host.dispatch(fx, .dup_job);
1229
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingSpawnCount());
1230
+ try std.testing.expectEqualStrings("/bin/one", fx.pendingSpawnAt(0).?.argv[0]);
1231
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
1232
+ try std.testing.expectEqualStrings("rejected", Host.model().last_err);
1233
+
1234
+ // The surviving stream still delivers normally.
1235
+ try fx.feedExit(job_spawn_key, 0);
1236
+ Host.drain(fx);
1237
+ try std.testing.expectEqual(@as(i64, 0), Host.model().exit_code);
1238
+ }
1239
+
1240
+ test "non-exited spawn ends route the err arm with the reason name" {
1241
+ const fx = freshChannel();
1242
+ defer fx.deinit();
1243
+ Host.init(fx);
1244
+
1245
+ Host.dispatch(fx, .run_lines);
1246
+ try fx.feedExitReason(job_spawn_key, -1, .spawn_failed);
1247
+ Host.drain(fx);
1248
+ try std.testing.expectEqual(@as(i64, 1), Host.model().errs);
1249
+ try std.testing.expectEqualStrings("spawn_failed", Host.model().last_err);
1250
+
1251
+ Host.dispatch(fx, .run_lines);
1252
+ try fx.feedExitReason(job_spawn_key, 9, .signaled);
1253
+ Host.drain(fx);
1254
+ try std.testing.expectEqual(@as(i64, 2), Host.model().errs);
1255
+ try std.testing.expectEqualStrings("signaled", Host.model().last_err);
1256
+ // Neither end touched the exit-arm mirror.
1257
+ try std.testing.expectEqual(@as(i64, -1), Host.model().exit_code);
1258
+ }
1259
+
1260
+ // ------------------------------------------------------- audio stream
1261
+
1262
+ test "audio_play decodes whole and events route the six-field arm by name" {
1263
+ const fx = freshChannel();
1264
+ defer fx.deinit();
1265
+ Host.init(fx);
1266
+
1267
+ Host.dispatch(fx, .play);
1268
+ const request = fx.pendingAudio().?;
1269
+ try std.testing.expectEqual(ts_core_host.audio_key_base, request.key);
1270
+ try std.testing.expectEqualStrings("music/a.mp3", request.path);
1271
+ try std.testing.expectEqualStrings("", request.url);
1272
+ try std.testing.expectEqual(@as(u64, 0), request.expected_bytes);
1273
+
1274
+ // The loaded acknowledgment routes the event arm; the state member
1275
+ // is matched by NAME (the mini core scrambles its declaration
1276
+ // order on purpose).
1277
+ try fx.feedAudioEvent(.loaded, 0, 183_000, true);
1278
+ Host.drain(fx);
1279
+ try std.testing.expectEqual(mini_core.AudioState.loaded, Host.model().audio_state);
1280
+ try std.testing.expectEqual(@as(f64, 183_000), Host.model().duration_ms);
1281
+ try std.testing.expect(Host.model().playing);
1282
+ try std.testing.expectEqual(@as(i64, 1), Host.model().audio_events);
1283
+
1284
+ // Position ticks keep flowing through the same non-retiring entry.
1285
+ try fx.feedAudioEvent(.position, 1_500, 183_000, true);
1286
+ try fx.feedAudioEvent(.position, 2_000, 183_000, true);
1287
+ Host.drain(fx);
1288
+ try std.testing.expectEqual(mini_core.AudioState.position, Host.model().audio_state);
1289
+ try std.testing.expectEqual(@as(f64, 2_000), Host.model().position_ms);
1290
+ try std.testing.expectEqual(@as(i64, 3), Host.model().audio_events);
1291
+
1292
+ // Spectrum bands arrive as bytes and commit into the model heap.
1293
+ var bands: [16]u8 = undefined;
1294
+ var full: [32]u8 = @splat(0);
1295
+ for (&bands, 0..) |*b, i| b.* = @intCast(i * 3);
1296
+ @memcpy(full[0..16], &bands);
1297
+ try fx.feedAudioSpectrum(full, 2_500, 183_000);
1298
+ Host.drain(fx);
1299
+ try std.testing.expectEqual(mini_core.AudioState.spectrum, Host.model().audio_state);
1300
+ try std.testing.expectEqual(@as(usize, 32), Host.model().bands.len);
1301
+ try std.testing.expectEqualSlices(u8, full[0..32], Host.model().bands);
1302
+
1303
+ // completed does NOT close the stream (apps start the next track
1304
+ // from it); the entry keeps routing.
1305
+ try fx.feedAudioEvent(.completed, 183_000, 183_000, false);
1306
+ Host.drain(fx);
1307
+ try std.testing.expectEqual(mini_core.AudioState.completed, Host.model().audio_state);
1308
+ try std.testing.expect(!Host.model().playing);
1309
+ try std.testing.expectEqual(@as(i64, 5), Host.model().audio_events);
1310
+ }
1311
+
1312
+ test "audio_ctl verbs drive the engine channel, gated by the wire key" {
1313
+ const fx = freshChannel();
1314
+ defer fx.deinit();
1315
+ Host.init(fx);
1316
+
1317
+ Host.dispatch(fx, .play);
1318
+ try std.testing.expect(fx.audioSnapshot().playing);
1319
+
1320
+ // A verb aimed at a key that is not the open stream is a no-op.
1321
+ Host.dispatch(fx, .ctl_stray);
1322
+ try std.testing.expect(fx.audioSnapshot().playing);
1323
+
1324
+ Host.dispatch(fx, .pause_it);
1325
+ try std.testing.expect(!fx.audioSnapshot().playing);
1326
+ Host.dispatch(fx, .resume_it);
1327
+ try std.testing.expect(fx.audioSnapshot().playing);
1328
+
1329
+ Host.dispatch(fx, .seek_it);
1330
+ try std.testing.expectEqual(@as(u64, 45_000), fx.audioSnapshot().position_ms);
1331
+
1332
+ Host.dispatch(fx, .vol_it);
1333
+ try std.testing.expectEqual(@as(f32, 0.25), fx.pendingAudio().?.volume);
1334
+
1335
+ // stop closes the stream: the channel idles, the entry retires,
1336
+ // and a straggler feed finds nothing.
1337
+ Host.dispatch(fx, .stop_it);
1338
+ try std.testing.expect(!fx.audioSnapshot().active);
1339
+ try std.testing.expectError(error.EffectNotFound, fx.feedAudioEvent(.position, 50_000, 183_000, true));
1340
+ }
1341
+
1342
+ test "a replacing audio_play re-keys the stream and the url source decodes whole" {
1343
+ const fx = freshChannel();
1344
+ defer fx.deinit();
1345
+ Host.init(fx);
1346
+
1347
+ Host.dispatch(fx, .play);
1348
+ // One player is the whole surface: the new play replaces in place.
1349
+ Host.dispatch(fx, .play_stream);
1350
+ const request = fx.pendingAudio().?;
1351
+ try std.testing.expectEqualStrings("", request.path);
1352
+ try std.testing.expectEqualStrings("https://cdn.test/a.mp3", request.url);
1353
+ try std.testing.expectEqualStrings("cache/a.mp3", request.cache_path);
1354
+ try std.testing.expectEqual(@as(u64, 4096), request.expected_bytes);
1355
+
1356
+ // A failure event on the replaced stream routes honestly (never
1357
+ // silent) and does not close the entry.
1358
+ try fx.feedAudioEventBuffering(.failed, 0, 0, false, false);
1359
+ Host.drain(fx);
1360
+ try std.testing.expectEqual(mini_core.AudioState.failed, Host.model().audio_state);
1361
+ Host.dispatch(fx, .pause_it);
1362
+ try std.testing.expect(!fx.audioSnapshot().playing);
1363
+ }
1364
+
1365
+ test "boot commits the model before any effects and performBoot fires the boot command once" {
1366
+ const fx = freshChannel();
1367
+ defer fx.deinit();
1368
+
1369
+ // The pre-effects half: the committed boot model is readable, no
1370
+ // effect has been issued, and the frame arena is reset.
1371
+ Host.boot();
1372
+ try std.testing.expect(!Host.model().polling);
1373
+ try std.testing.expectEqual(@as(usize, 0), fx.pendingHostCount());
1374
+
1375
+ // The effects half re-derives the boot command from the pure
1376
+ // initialModel and performs it exactly as init does.
1377
+ Host.performBoot(fx);
1378
+ try std.testing.expectEqual(@as(usize, 1), fx.pendingHostCount());
1379
+ const request = fx.pendingHostAt(0).?;
1380
+ try std.testing.expectEqual(boot_request_key, request.key);
1381
+ try std.testing.expectEqualStrings("status.read", request.name);
1382
+ try std.testing.expectEqualStrings("boot", request.payload);
1383
+ }
1384
+
1385
+ test "a URL audio_play with no cache path derives the content-addressed path when configured" {
1386
+ const fx = freshChannel();
1387
+ defer fx.deinit();
1388
+ Host.init(fx);
1389
+
1390
+ // No caches directory configured: the record plays stream-only,
1391
+ // exactly as its empty wire field says.
1392
+ Host.dispatch(fx, .play_bare_url);
1393
+ try std.testing.expectEqualStrings("", fx.pendingAudio().?.cache_path);
1394
+
1395
+ // Configured: the bridge derives the engine's conventional path
1396
+ // from the URL alone — the same `audioCachePath` soundboard's
1397
+ // wiring computes.
1398
+ Host.setAudioCacheDir("/tmp/native-caches");
1399
+ Host.dispatch(fx, .play_bare_url);
1400
+ var expected_buffer: [512]u8 = undefined;
1401
+ const expected = try effects_mod.audioCachePath(&expected_buffer, "/tmp/native-caches", "https://cdn.test/b.mp3");
1402
+ try std.testing.expectEqualStrings(expected, fx.pendingAudio().?.cache_path);
1403
+
1404
+ // A record that names its own cache path keeps it: derivation only
1405
+ // fills the empty field.
1406
+ Host.dispatch(fx, .play_stream);
1407
+ try std.testing.expectEqualStrings("cache/a.mp3", fx.pendingAudio().?.cache_path);
1408
+ }