@native-sdk/cli 0.5.2 → 0.5.4

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 (123) hide show
  1. package/build/app.zig +41 -1
  2. package/build.zig +264 -3
  3. package/native-sdk.d.ts +17 -1
  4. package/package.json +9 -9
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/rt/rt.zig +138 -3
  8. package/packages/core/sdk/core.ts +225 -3
  9. package/packages/core/sdk/events.ts +39 -2
  10. package/packages/core/src/checker.ts +1 -1
  11. package/packages/core/src/emitter.ts +2625 -262
  12. package/packages/core/src/infer.ts +53 -7
  13. package/skill-data/automation/SKILL.md +7 -4
  14. package/skill-data/core/references/app-model-runtime.md +3 -0
  15. package/skill-data/native-ui/SKILL.md +4 -2
  16. package/skill-data/ts-core/SKILL.md +9 -1
  17. package/src/app_runner/root.zig +106 -1
  18. package/src/app_runner/ts_core_main.zig +4 -0
  19. package/src/automation/protocol.zig +20 -1
  20. package/src/embed/host.zig +27 -0
  21. package/src/embed/tests.zig +187 -0
  22. package/src/embed/ui_host.zig +4 -0
  23. package/src/platform/linux/gtk_host.c +112 -3
  24. package/src/platform/linux/root.zig +71 -0
  25. package/src/platform/macos/appkit_host.h +59 -2
  26. package/src/platform/macos/appkit_host.m +663 -34
  27. package/src/platform/macos/cef_host.mm +262 -10
  28. package/src/platform/macos/root.zig +126 -4
  29. package/src/platform/null_platform.zig +298 -5
  30. package/src/platform/null_platform_tests.zig +39 -0
  31. package/src/platform/root.zig +36 -0
  32. package/src/platform/types.zig +247 -8
  33. package/src/platform/windows/root.zig +134 -0
  34. package/src/platform/windows/webview2_host.cpp +152 -40
  35. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  36. package/src/primitives/app_manifest/root.zig +1 -0
  37. package/src/primitives/app_manifest/types.zig +32 -0
  38. package/src/primitives/canvas/chart.zig +7 -7
  39. package/src/primitives/canvas/chart_tests.zig +66 -0
  40. package/src/primitives/canvas/commands.zig +48 -0
  41. package/src/primitives/canvas/events.zig +161 -0
  42. package/src/primitives/canvas/font_ttf.zig +155 -8
  43. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  44. package/src/primitives/canvas/reference.zig +67 -8
  45. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  46. package/src/primitives/canvas/root.zig +25 -0
  47. package/src/primitives/canvas/tests.zig +1 -0
  48. package/src/primitives/canvas/ui.zig +46 -9
  49. package/src/primitives/canvas/ui_markup.zig +82 -34
  50. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  51. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  52. package/src/primitives/canvas/ui_markup_compiled.zig +63 -11
  53. package/src/primitives/canvas/ui_markup_compiled_tests.zig +88 -0
  54. package/src/primitives/canvas/ui_markup_contract.zig +10 -1
  55. package/src/primitives/canvas/ui_markup_contract_tests.zig +50 -0
  56. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  57. package/src/primitives/canvas/ui_markup_tests.zig +55 -9
  58. package/src/primitives/canvas/ui_markup_view.zig +81 -14
  59. package/src/primitives/canvas/ui_markup_view_tests.zig +219 -7
  60. package/src/primitives/canvas/ui_schema.zig +29 -0
  61. package/src/primitives/canvas/ui_schema_tests.zig +11 -11
  62. package/src/primitives/canvas/ui_tests.zig +31 -0
  63. package/src/primitives/canvas/vector.zig +258 -141
  64. package/src/primitives/canvas/widget_access.zig +1 -1
  65. package/src/primitives/canvas/widget_builtin_tests.zig +129 -0
  66. package/src/primitives/canvas/widget_layout.zig +9 -4
  67. package/src/primitives/canvas/widget_render.zig +78 -40
  68. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  69. package/src/primitives/canvas/widget_semantics.zig +6 -1
  70. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  71. package/src/primitives/canvas/widget_text_input.zig +118 -10
  72. package/src/primitives/canvas/widgets.zig +16 -0
  73. package/src/root.zig +12 -0
  74. package/src/runtime/api.zig +15 -0
  75. package/src/runtime/automation_commands.zig +33 -0
  76. package/src/runtime/automation_widget_dispatch.zig +64 -0
  77. package/src/runtime/bridge_payload.zig +7 -0
  78. package/src/runtime/bridge_responses.zig +5 -0
  79. package/src/runtime/builtin_bridge.zig +9 -4
  80. package/src/runtime/canvas_font_tests.zig +711 -5
  81. package/src/runtime/canvas_fonts.zig +120 -25
  82. package/src/runtime/canvas_frame_helpers.zig +15 -0
  83. package/src/runtime/canvas_image_tests.zig +221 -0
  84. package/src/runtime/canvas_images.zig +78 -19
  85. package/src/runtime/canvas_limits.zig +44 -8
  86. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  87. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  88. package/src/runtime/canvas_widget_events.zig +24 -4
  89. package/src/runtime/canvas_widget_runtime.zig +24 -7
  90. package/src/runtime/canvas_widget_state.zig +6 -1
  91. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  92. package/src/runtime/core.zig +148 -9
  93. package/src/runtime/effects.zig +1664 -43
  94. package/src/runtime/effects_fetch_tests.zig +89 -1
  95. package/src/runtime/effects_file_tests.zig +41 -1
  96. package/src/runtime/effects_image_tests.zig +1304 -0
  97. package/src/runtime/effects_tests.zig +153 -0
  98. package/src/runtime/flow.zig +44 -0
  99. package/src/runtime/gpu_surface_events.zig +7 -0
  100. package/src/runtime/media_surface.zig +726 -0
  101. package/src/runtime/media_surface_tests.zig +1476 -0
  102. package/src/runtime/root.zig +20 -0
  103. package/src/runtime/session_blobs.zig +689 -0
  104. package/src/runtime/session_journal.zig +111 -20
  105. package/src/runtime/session_record.zig +27 -2
  106. package/src/runtime/session_replay.zig +168 -16
  107. package/src/runtime/session_tests.zig +2118 -4
  108. package/src/runtime/shell_layout.zig +7 -0
  109. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  110. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  111. package/src/runtime/tests.zig +3 -0
  112. package/src/runtime/ts_core_host.zig +439 -4
  113. package/src/runtime/ts_core_host_tests.zig +41 -0
  114. package/src/runtime/ts_ui_app.zig +63 -0
  115. package/src/runtime/ui_app.zig +169 -6
  116. package/src/runtime/ui_app_tests.zig +334 -0
  117. package/src/runtime/ui_app_window_tests.zig +468 -0
  118. package/src/runtime/window_command_bridge_tests.zig +117 -0
  119. package/src/runtime/window_storage.zig +32 -0
  120. package/src/runtime/window_views.zig +61 -1
  121. package/src/tooling/manifest.zig +75 -0
  122. package/src/tooling/raw_manifest.zig +2 -0
  123. package/src/tooling/templates.zig +219 -1
@@ -0,0 +1,1304 @@
1
+ //! Image-load effect coverage: `fx.loadImage` through the fake executor
2
+ //! (request capture, byte feeds that run the REAL decode+register path,
3
+ //! the failure taxonomy, cancel) and the real executor's source cascade
4
+ //! — local files via `std.testing.tmpDir`, network sources against a
5
+ //! loopback `std.http.Server` fixture spawned inside the test (no
6
+ //! external network is ever touched), including the content-addressed
7
+ //! cache install and the offline cache hit behind it.
8
+
9
+ const std = @import("std");
10
+ const builtin = @import("builtin");
11
+ const canvas = @import("canvas");
12
+ const geometry = @import("geometry");
13
+ const app_manifest = @import("app_manifest");
14
+ const core = @import("core.zig");
15
+ const ui_app_model = @import("ui_app.zig");
16
+ const effects_mod = @import("effects.zig");
17
+ const canvas_limits = @import("canvas_limits.zig");
18
+
19
+ const canvas_label = "image-canvas";
20
+
21
+ const image_views = [_]app_manifest.ShellView{
22
+ .{ .label = canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
23
+ };
24
+ const image_windows = [_]app_manifest.ShellWindow{.{
25
+ .label = "main",
26
+ .title = "Images",
27
+ .width = 400,
28
+ .height = 300,
29
+ .views = &image_views,
30
+ }};
31
+ const image_scene: app_manifest.ShellConfig = .{ .windows = &image_windows };
32
+
33
+ /// The burst test's stand-in entry for a non-image terminal in the
34
+ /// delivery-order log — outside the burst's 1..=burst_load_count id
35
+ /// range, so it can never shadow an image terminal.
36
+ const interleave_marker: u64 = 500;
37
+
38
+ /// Loads issued by the `.burst` arm: past both the pending ring's 32
39
+ /// entries and the image stage's inline capacity, so a single dispatch
40
+ /// proves the stage spills instead of evicting.
41
+ const burst_load_count = 33;
42
+
43
+ const ImageModel = struct {
44
+ result_count: usize = 0,
45
+ last: ?effects_mod.EffectImageResult = null,
46
+ rejected_count: usize = 0,
47
+ /// Delivery-order log for the burst test: each image terminal
48
+ /// records its echoed id, the interleaved spawn rejection records
49
+ /// `interleave_marker`.
50
+ order: [40]u64 = @splat(0),
51
+ order_len: usize = 0,
52
+
53
+ /// `EffectImageResult` is all plain data — storing it whole is the
54
+ /// documented contract (no borrowed slices to copy).
55
+ fn record(model: *ImageModel, result: effects_mod.EffectImageResult) void {
56
+ model.result_count += 1;
57
+ model.last = result;
58
+ if (result.outcome == .rejected) model.rejected_count += 1;
59
+ model.logOrder(result.id);
60
+ }
61
+
62
+ fn logOrder(model: *ImageModel, value: u64) void {
63
+ if (model.order_len < model.order.len) {
64
+ model.order[model.order_len] = value;
65
+ model.order_len += 1;
66
+ }
67
+ }
68
+ };
69
+
70
+ const ImageMsg = union(enum) {
71
+ start,
72
+ start_fire_and_forget,
73
+ stop,
74
+ burst,
75
+ result: effects_mod.EffectImageResult,
76
+ spawn_exit: effects_mod.EffectExit,
77
+ };
78
+
79
+ const ImageApp = ui_app_model.UiApp(ImageModel, ImageMsg);
80
+ const ImageEffects = ImageApp.Effects;
81
+
82
+ const image_id: u64 = 42;
83
+
84
+ // Set by each test before dispatching `.start`; globals keep the update
85
+ // function closure-free.
86
+ var test_id: u64 = image_id;
87
+ var test_path: []const u8 = "";
88
+ var test_url: []const u8 = "";
89
+ var test_cache_path: []const u8 = "";
90
+ var test_expected_bytes: u64 = 0;
91
+ var test_timeout_ms: u32 = effects_mod.default_effect_fetch_timeout_ms;
92
+ /// The gallery-refresh idiom: when set, the update reacts to an image
93
+ /// terminal by immediately reloading the same id (one-shot, so the
94
+ /// reload's own terminal does not cascade).
95
+ var test_reload_on_result: bool = false;
96
+
97
+ fn imageUpdate(model: *ImageModel, msg: ImageMsg, fx: *ImageEffects) void {
98
+ switch (msg) {
99
+ .start => fx.loadImage(.{
100
+ .id = test_id,
101
+ .path = test_path,
102
+ .url = test_url,
103
+ .cache_path = test_cache_path,
104
+ .expected_bytes = test_expected_bytes,
105
+ .timeout_ms = test_timeout_ms,
106
+ .on_result = ImageEffects.imageMsg(.result),
107
+ }),
108
+ .start_fire_and_forget => fx.loadImage(.{
109
+ .id = test_id,
110
+ .path = test_path,
111
+ .url = test_url,
112
+ .cache_path = test_cache_path,
113
+ .expected_bytes = test_expected_bytes,
114
+ .timeout_ms = test_timeout_ms,
115
+ .on_result = null,
116
+ }),
117
+ .stop => fx.cancel(test_id),
118
+ .burst => {
119
+ // One dispatch, no drain in between: every load below is
120
+ // refused loop-side (no source at all), each staging its
121
+ // one terminal before any can deliver. A rejected spawn
122
+ // (empty argv) lands between load 5 and load 6 so the
123
+ // delivery order across BOTH pending structures stays
124
+ // pinned, not just the order within the image stage.
125
+ var id: u64 = 1;
126
+ while (id <= 5) : (id += 1) burstLoad(fx, id);
127
+ fx.spawn(.{ .key = interleave_marker, .argv = &.{}, .on_exit = ImageEffects.exitMsg(.spawn_exit) });
128
+ while (id <= burst_load_count) : (id += 1) burstLoad(fx, id);
129
+ },
130
+ .result => |result| {
131
+ model.record(result);
132
+ if (test_reload_on_result) {
133
+ test_reload_on_result = false;
134
+ fx.loadImage(.{
135
+ .id = test_id,
136
+ .path = test_path,
137
+ .url = test_url,
138
+ .cache_path = test_cache_path,
139
+ .expected_bytes = test_expected_bytes,
140
+ .timeout_ms = test_timeout_ms,
141
+ .on_result = ImageEffects.imageMsg(.result),
142
+ });
143
+ }
144
+ },
145
+ .spawn_exit => model.logOrder(interleave_marker),
146
+ }
147
+ }
148
+
149
+ /// A load with no source at all: refused before any I/O, delivering
150
+ /// exactly one `.rejected` terminal that echoes `id`.
151
+ fn burstLoad(fx: *ImageEffects, id: u64) void {
152
+ fx.loadImage(.{
153
+ .id = id,
154
+ .path = "",
155
+ .url = "",
156
+ .cache_path = "",
157
+ .expected_bytes = 0,
158
+ .on_result = ImageEffects.imageMsg(.result),
159
+ });
160
+ }
161
+
162
+ fn imageView(ui: *ImageApp.Ui, model: *const ImageModel) ImageApp.Ui.Node {
163
+ return ui.column(.{ .gap = 4, .padding = 8 }, .{
164
+ ui.text(.{}, ui.fmt("{d} results", .{model.result_count})),
165
+ ui.button(.{ .on_press = .start }, "Load"),
166
+ ui.button(.{ .on_press = .stop }, "Cancel"),
167
+ });
168
+ }
169
+
170
+ const Harness = struct {
171
+ harness: *core.TestHarness(),
172
+ app_state: *ImageApp,
173
+ app: core.App,
174
+
175
+ fn create() !Harness {
176
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
177
+ errdefer harness.destroy(std.testing.allocator);
178
+ harness.null_platform.gpu_surfaces = true;
179
+ // The deterministic decode seam: the strict PNG subset
180
+ // `canvas.png.writeRgba8` emits decodes without a bundled codec.
181
+ harness.null_platform.image_decode = true;
182
+ const app_state = try std.testing.allocator.create(ImageApp);
183
+ errdefer std.testing.allocator.destroy(app_state);
184
+ app_state.* = ImageApp.init(std.heap.page_allocator, .{}, .{
185
+ .name = "effects-image",
186
+ .scene = image_scene,
187
+ .canvas_label = canvas_label,
188
+ .update_fx = imageUpdate,
189
+ .view = imageView,
190
+ });
191
+ const app = app_state.app();
192
+ try harness.start(app);
193
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
194
+ .label = canvas_label,
195
+ .size = geometry.SizeF.init(400, 300),
196
+ .scale_factor = 1,
197
+ .frame_index = 1,
198
+ .timestamp_ns = 1_000_000,
199
+ .nonblank = true,
200
+ } });
201
+ try std.testing.expect(app_state.installed);
202
+ // Test defaults back to the shared globals.
203
+ test_id = image_id;
204
+ test_path = "";
205
+ test_url = "";
206
+ test_cache_path = "";
207
+ test_expected_bytes = 0;
208
+ test_timeout_ms = effects_mod.default_effect_fetch_timeout_ms;
209
+ test_reload_on_result = false;
210
+ return .{ .harness = harness, .app_state = app_state, .app = app };
211
+ }
212
+
213
+ fn destroy(self: *Harness) void {
214
+ self.app_state.deinit();
215
+ std.testing.allocator.destroy(self.app_state);
216
+ self.harness.destroy(std.testing.allocator);
217
+ }
218
+
219
+ /// Consume all pending wake requests and deliver a single `.wake`
220
+ /// platform event for the batch.
221
+ fn drainWakes(self: *Harness) !void {
222
+ var nudged = false;
223
+ while (self.harness.null_platform.takeWake()) |_| nudged = true;
224
+ if (nudged) try self.harness.runtime.dispatchPlatformEvent(self.app, .wake);
225
+ }
226
+ };
227
+
228
+ /// A tiny deterministic RGBA fixture encoded as the strict PNG subset
229
+ /// the null platform's decode seam parses.
230
+ fn encodePngFixture(buffer: []u8, width: usize, height: usize) []const u8 {
231
+ var pixels: [64 * 64 * 4]u8 = undefined;
232
+ const byte_len = width * height * 4;
233
+ var seed: u8 = 17;
234
+ for (pixels[0..byte_len]) |*byte| {
235
+ byte.* = seed;
236
+ seed = seed *% 29 +% 3;
237
+ }
238
+ var writer = std.Io.Writer.fixed(buffer);
239
+ canvas.png.writeRgba8(&writer, width, height, pixels[0..byte_len]) catch unreachable;
240
+ return writer.buffered();
241
+ }
242
+
243
+ fn waitForResult(h: *Harness, count: usize) !void {
244
+ const io = std.testing.io;
245
+ var waited_ms: usize = 0;
246
+ while (waited_ms < 20_000) : (waited_ms += 10) {
247
+ try h.drainWakes();
248
+ if (h.app_state.model.result_count >= count) return;
249
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(10), .awake);
250
+ }
251
+ return error.TestTimedOut;
252
+ }
253
+
254
+ // ------------------------------------------------------------ fake executor
255
+
256
+ test "fake executor records the whole load request shape and feeds bytes through the real decode path" {
257
+ var h = try Harness.create();
258
+ defer h.destroy();
259
+ h.app_state.effects.executor = .fake;
260
+
261
+ test_path = "assets/cover.png";
262
+ test_url = "https://cdn.example.com/cover.png";
263
+ test_cache_path = "cache/images/abc.png";
264
+ test_expected_bytes = 512;
265
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
266
+
267
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.effects.pendingImageLoadCount());
268
+ const request = h.app_state.effects.pendingImageLoadAt(0).?;
269
+ try std.testing.expectEqual(image_id, request.id);
270
+ try std.testing.expectEqualStrings("assets/cover.png", request.path);
271
+ try std.testing.expectEqualStrings("https://cdn.example.com/cover.png", request.url);
272
+ try std.testing.expectEqualStrings("cache/images/abc.png", request.cache_path);
273
+ try std.testing.expectEqual(@as(u64, 512), request.expected_bytes);
274
+
275
+ // Feeding encoded bytes exercises decode + register end to end:
276
+ // the Msg carries the decoded dimensions and the pixels are live
277
+ // in the registry under the requested id.
278
+ var encoded_buffer: [2048]u8 = undefined;
279
+ const encoded = encodePngFixture(&encoded_buffer, 3, 2);
280
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
281
+ try h.drainWakes();
282
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.result_count);
283
+ const result = h.app_state.model.last.?;
284
+ try std.testing.expectEqual(image_id, result.id);
285
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, result.outcome);
286
+ try std.testing.expectEqual(@as(usize, 3), result.width);
287
+ try std.testing.expectEqual(@as(usize, 2), result.height);
288
+ const registered = h.harness.runtime.registeredCanvasImage(image_id).?;
289
+ try std.testing.expectEqual(@as(usize, 3), registered.width);
290
+ try std.testing.expectEqual(@as(usize, 2), registered.height);
291
+
292
+ // The slot retired: the same id loads again.
293
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
294
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.effects.pendingImageLoadCount());
295
+ }
296
+
297
+ test "undecodable and oversized feeds fail with the registry's own classes" {
298
+ var h = try Harness.create();
299
+ defer h.destroy();
300
+ h.app_state.effects.executor = .fake;
301
+
302
+ test_path = "assets/cover.png";
303
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
304
+ try h.app_state.effects.feedImageBytes(image_id, "not an image");
305
+ try h.drainWakes();
306
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.decode_failed, h.app_state.model.last.?.outcome);
307
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(image_id) == null);
308
+
309
+ // A host without a codec is `.unsupported`, mirroring
310
+ // `error.UnsupportedService` on the direct path.
311
+ h.harness.null_platform.image_decode = false;
312
+ var encoded_buffer: [2048]u8 = undefined;
313
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
314
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
315
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
316
+ try h.drainWakes();
317
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.unsupported, h.app_state.model.last.?.outcome);
318
+ h.harness.null_platform.image_decode = true;
319
+
320
+ // Over the encoded-source bound: `.too_large` without decoding.
321
+ const decodes_before = h.harness.null_platform.image_decode_count;
322
+ const oversized = try std.testing.allocator.alloc(u8, effects_mod.max_effect_image_bytes + 1);
323
+ defer std.testing.allocator.free(oversized);
324
+ @memset(oversized, 7);
325
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
326
+ try h.app_state.effects.feedImageBytes(image_id, oversized);
327
+ try h.drainWakes();
328
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.too_large, h.app_state.model.last.?.outcome);
329
+ try std.testing.expectEqual(decodes_before, h.harness.null_platform.image_decode_count);
330
+ }
331
+
332
+ test "a full registry fails the load with registry_full, never silence" {
333
+ var h = try Harness.create();
334
+ defer h.destroy();
335
+ h.app_state.effects.executor = .fake;
336
+
337
+ var encoded_buffer: [2048]u8 = undefined;
338
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
339
+ var id: u64 = 1000;
340
+ while (id < 1000 + canvas_limits.max_registered_canvas_images) : (id += 1) {
341
+ _ = try h.harness.runtime.registerCanvasImageBytes(id, encoded);
342
+ }
343
+
344
+ test_path = "assets/one-too-many.png";
345
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
346
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
347
+ try h.drainWakes();
348
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.registry_full, h.app_state.model.last.?.outcome);
349
+ }
350
+
351
+ test "a registry allocation failure fails the load with alloc_failed, never decode_failed" {
352
+ // The registry allocates each slot's pixel buffer lazily, at the
353
+ // slot's first registration, from the runtime's frozen allocator —
354
+ // so a FailingAllocator there is exactly an OOM at registration
355
+ // time: AFTER a successful decode, with perfectly valid bytes. The
356
+ // load's terminal must say resource exhaustion (`alloc_failed`),
357
+ // never report the bytes corrupt (`decode_failed`).
358
+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
359
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
360
+ defer harness.destroy(std.testing.allocator);
361
+ harness.null_platform.gpu_surfaces = true;
362
+ harness.null_platform.image_decode = true;
363
+ // Rebind the runtime over the injectable allocator BEFORE anything
364
+ // starts — the slot-buffer OOM tests' convention
365
+ // (canvas_image_tests' `startedGpuHarnessWithRuntimeAllocator`).
366
+ core.Runtime.initAt(&harness.runtime, .{
367
+ .platform = harness.null_platform.platform(),
368
+ .trace_sink = harness.trace_sink.sink(),
369
+ .allocator = failing.allocator(),
370
+ .environ = std.testing.environ,
371
+ });
372
+ harness.runtime.dispatch_error_policy = .propagate;
373
+
374
+ const app_state = try std.testing.allocator.create(ImageApp);
375
+ defer std.testing.allocator.destroy(app_state);
376
+ app_state.* = ImageApp.init(std.heap.page_allocator, .{}, .{
377
+ .name = "effects-image-oom",
378
+ .scene = image_scene,
379
+ .canvas_label = canvas_label,
380
+ .update_fx = imageUpdate,
381
+ .view = imageView,
382
+ });
383
+ defer app_state.deinit();
384
+ const app = app_state.app();
385
+ try harness.start(app);
386
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
387
+ .label = canvas_label,
388
+ .size = geometry.SizeF.init(400, 300),
389
+ .scale_factor = 1,
390
+ .frame_index = 1,
391
+ .timestamp_ns = 1_000_000,
392
+ .nonblank = true,
393
+ } });
394
+ app_state.effects.executor = .fake;
395
+ test_id = image_id;
396
+ test_path = "assets/cover.png";
397
+ test_url = "";
398
+ test_cache_path = "";
399
+ test_expected_bytes = 0;
400
+ test_timeout_ms = effects_mod.default_effect_fetch_timeout_ms;
401
+ test_reload_on_result = false;
402
+
403
+ var encoded_buffer: [2048]u8 = undefined;
404
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
405
+ try app_state.dispatch(&harness.runtime, 1, .start);
406
+ try app_state.effects.feedImageBytes(image_id, encoded);
407
+ // Exhaust the runtime allocator before the drain delivers: the
408
+ // registry's lazy slot-buffer allocation is the next (and only)
409
+ // runtime allocation on the decode+register path.
410
+ failing.fail_index = failing.alloc_index;
411
+ while (harness.null_platform.takeWake()) |_| {}
412
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
413
+ failing.fail_index = std.math.maxInt(usize);
414
+ try std.testing.expectEqual(@as(usize, 1), app_state.model.result_count);
415
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.alloc_failed, app_state.model.last.?.outcome);
416
+ try std.testing.expect(harness.runtime.registeredCanvasImage(image_id) == null);
417
+
418
+ // Memory heals: the SAME bytes load and register on retry, proving
419
+ // the class was resource exhaustion, not corruption.
420
+ try app_state.dispatch(&harness.runtime, 1, .start);
421
+ try app_state.effects.feedImageBytes(image_id, encoded);
422
+ while (harness.null_platform.takeWake()) |_| {}
423
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
424
+ try std.testing.expectEqual(@as(usize, 2), app_state.model.result_count);
425
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, app_state.model.last.?.outcome);
426
+ try std.testing.expect(harness.runtime.registeredCanvasImage(image_id) != null);
427
+ }
428
+
429
+ test "recorded terminals feed verbatim: the failure classes and a loaded record's re-registration" {
430
+ var h = try Harness.create();
431
+ defer h.destroy();
432
+ h.app_state.effects.executor = .fake;
433
+
434
+ test_path = "assets/cover.png";
435
+ const classes = [_]effects_mod.EffectImageOutcome{ .not_found, .io_failed, .connect_failed, .tls_failed, .protocol_failed, .timed_out, .decode_failed, .alloc_failed };
436
+ for (classes, 1..) |class, count| {
437
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
438
+ try h.app_state.effects.feedImageResult(image_id, class, 0, 0, 0, "");
439
+ try h.drainWakes();
440
+ try std.testing.expectEqual(count, h.app_state.model.result_count);
441
+ try std.testing.expectEqual(class, h.app_state.model.last.?.outcome);
442
+ }
443
+
444
+ // An `.http_status` record carries its status through.
445
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
446
+ try h.app_state.effects.feedImageResult(image_id, .http_status, 0, 0, 404, "");
447
+ try h.drainWakes();
448
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.http_status, h.app_state.model.last.?.outcome);
449
+ try std.testing.expectEqual(@as(u16, 404), h.app_state.model.last.?.status);
450
+
451
+ // A recorded `.loaded` delivers the journaled dimensions verbatim
452
+ // AND re-registers the recorded bytes for presentation.
453
+ var encoded_buffer: [2048]u8 = undefined;
454
+ const encoded = encodePngFixture(&encoded_buffer, 3, 2);
455
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
456
+ try h.app_state.effects.feedImageResult(image_id, .loaded, 3, 2, 200, encoded);
457
+ try h.drainWakes();
458
+ const result = h.app_state.model.last.?;
459
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, result.outcome);
460
+ try std.testing.expectEqual(@as(usize, 3), result.width);
461
+ try std.testing.expectEqual(@as(usize, 2), result.height);
462
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(image_id) != null);
463
+
464
+ // A recorded `.loaded` whose bytes the replay host cannot decode
465
+ // still delivers the recorded Msg — the divergence is loud on
466
+ // stderr and presentation-only, never a different Msg stream.
467
+ test_id = image_id + 1;
468
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
469
+ try h.app_state.effects.feedImageResult(image_id + 1, .loaded, 8, 8, 0, "jpeg bytes this host cannot decode");
470
+ try h.drainWakes();
471
+ const undecodable = h.app_state.model.last.?;
472
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, undecodable.outcome);
473
+ try std.testing.expectEqual(@as(usize, 8), undecodable.width);
474
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(image_id + 1) == null);
475
+ }
476
+
477
+ test "load requests that cannot run are rejected loudly, never silently" {
478
+ var h = try Harness.create();
479
+ defer h.destroy();
480
+ h.app_state.effects.executor = .fake;
481
+
482
+ // No source at all.
483
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
484
+ try h.drainWakes();
485
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.rejected_count);
486
+
487
+ // Id 0 is the no-image sentinel; the media-surface namespace is
488
+ // reserved — both mirror `registerCanvasImage`'s refusals.
489
+ test_path = "assets/cover.png";
490
+ test_id = 0;
491
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
492
+ try h.drainWakes();
493
+ try std.testing.expectEqual(@as(usize, 2), h.app_state.model.rejected_count);
494
+ test_id = canvas.media_surface_image_id_bit | 7;
495
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
496
+ try h.drainWakes();
497
+ try std.testing.expectEqual(@as(usize, 3), h.app_state.model.rejected_count);
498
+ test_id = image_id;
499
+
500
+ // A non-http(s) url.
501
+ test_path = "";
502
+ test_url = "file:///etc/passwd";
503
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
504
+ try h.drainWakes();
505
+ try std.testing.expectEqual(@as(usize, 4), h.app_state.model.rejected_count);
506
+
507
+ // An over-bound path.
508
+ var long_path: [effects_mod.max_effect_image_path_bytes + 1]u8 = undefined;
509
+ @memset(&long_path, 'a');
510
+ test_url = "";
511
+ test_path = &long_path;
512
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
513
+ try h.drainWakes();
514
+ try std.testing.expectEqual(@as(usize, 5), h.app_state.model.rejected_count);
515
+
516
+ // A duplicate active key.
517
+ test_path = "assets/cover.png";
518
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
519
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
520
+ try h.drainWakes();
521
+ try std.testing.expectEqual(@as(usize, 6), h.app_state.model.rejected_count);
522
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.effects.pendingImageLoadCount());
523
+ }
524
+
525
+ test "a burst of validation rejections past the pending ring delivers every terminal, in order" {
526
+ var h = try Harness.create();
527
+ defer h.destroy();
528
+ h.app_state.effects.executor = .fake;
529
+
530
+ // 33 sourceless loads plus one rejected spawn in ONE dispatch:
531
+ // more loop-side terminals than the 32-entry pending ring holds.
532
+ // Image results carry no drop counter, so ring overflow would have
533
+ // to evict one silently — breaking the exactly-one-terminal-per-
534
+ // load contract — which is why image terminals stage in the
535
+ // non-lossy side stage instead of the ring.
536
+ try h.app_state.dispatch(&h.harness.runtime, 1, .burst);
537
+ try h.drainWakes();
538
+
539
+ // Every load's terminal arrived: exactly one each, all rejected.
540
+ try std.testing.expectEqual(@as(usize, burst_load_count), h.app_state.model.result_count);
541
+ try std.testing.expectEqual(@as(usize, burst_load_count), h.app_state.model.rejected_count);
542
+
543
+ // Delivery preserved enqueue order across BOTH pending structures:
544
+ // loads 1..5, the spawn rejection, then loads 6..33.
545
+ try std.testing.expectEqual(@as(usize, burst_load_count + 1), h.app_state.model.order_len);
546
+ var expected_id: u64 = 1;
547
+ for (h.app_state.model.order[0..h.app_state.model.order_len], 0..) |value, position| {
548
+ if (position == 5) {
549
+ try std.testing.expectEqual(interleave_marker, value);
550
+ continue;
551
+ }
552
+ try std.testing.expectEqual(expected_id, value);
553
+ expected_id += 1;
554
+ }
555
+ }
556
+
557
+ test "cancelling a fake image load delivers one cancelled terminal" {
558
+ var h = try Harness.create();
559
+ defer h.destroy();
560
+ h.app_state.effects.executor = .fake;
561
+
562
+ test_path = "assets/cover.png";
563
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
564
+ try h.app_state.dispatch(&h.harness.runtime, 1, .stop);
565
+ try h.drainWakes();
566
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.result_count);
567
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.cancelled, h.app_state.model.last.?.outcome);
568
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.effects.pendingImageLoadCount());
569
+ // Terminal means terminal: a straggler feed reports EffectNotFound.
570
+ try std.testing.expectError(error.EffectNotFound, h.app_state.effects.feedImageBytes(image_id, "late"));
571
+ }
572
+
573
+ test "an update that reloads the same id from its own terminal parks instead of rejecting" {
574
+ var h = try Harness.create();
575
+ defer h.destroy();
576
+ h.app_state.effects.executor = .fake;
577
+
578
+ test_path = "assets/cover.png";
579
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
580
+
581
+ // Queue the terminal, then reconstruct the real worker's race
582
+ // window: `imageWorkerMain` posts its entry FIRST and stores
583
+ // `.draining` on the next line, so a preemption between the two
584
+ // lets the drain dispatch the result while the slot still reads
585
+ // `.running`. The test cannot force that OS preemption; it CAN
586
+ // produce the exact state the preempted worker leaves behind —
587
+ // terminal in the queue, slot `.running` — by rewinding the fed
588
+ // slot's state before draining. What the drain does from that
589
+ // state is precisely the ordering under test: it must retire the
590
+ // slot before the result reaches update, so the reload below
591
+ // parks as a fresh load instead of rejecting as a duplicate.
592
+ var encoded_buffer: [2048]u8 = undefined;
593
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
594
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
595
+ for (&h.app_state.effects.slots) |*slot| {
596
+ if (slot.kind == .image and slot.key == image_id) slot.state.store(.running, .release);
597
+ }
598
+
599
+ // The gallery-refresh idiom: update answers the terminal with a
600
+ // reload of the same id.
601
+ test_reload_on_result = true;
602
+ try h.drainWakes();
603
+ try h.drainWakes();
604
+
605
+ // Exactly one terminal (the loaded one) — a rejected duplicate
606
+ // would have delivered a second, `.rejected`, result.
607
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.result_count);
608
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, h.app_state.model.last.?.outcome);
609
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.model.rejected_count);
610
+
611
+ // The reload parked as a live request: feeding it completes the
612
+ // second load. (A rejected reload leaves no active occupancy with
613
+ // a feedable buffer — this feed would report EffectNotFound.)
614
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
615
+ try h.drainWakes();
616
+ try std.testing.expectEqual(@as(usize, 2), h.app_state.model.result_count);
617
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, h.app_state.model.last.?.outcome);
618
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.model.rejected_count);
619
+ }
620
+
621
+ test "an unrelated dispatch reloading the id inside the undelivered window rejects; the window ends at delivery" {
622
+ var h = try Harness.create();
623
+ defer h.destroy();
624
+ h.app_state.effects.executor = .fake;
625
+
626
+ test_path = "assets/cover.png";
627
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
628
+
629
+ // Park the terminal undelivered: the feed queues the entry and
630
+ // stores `.draining`, and no drain runs before the next dispatch —
631
+ // the posted-but-undelivered window a real worker leaves between
632
+ // its post and the loop's drain. (The test above rewinds the state
633
+ // to `.running` to model a PREEMPTED worker; here the store has
634
+ // landed, so this is exactly the state `findActiveSlot` no longer
635
+ // sees.)
636
+ var encoded_buffer: [2048]u8 = undefined;
637
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
638
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
639
+
640
+ // An UNRELATED dispatch (a second user action, not the terminal
641
+ // handler) reloads the same id while the terminal is still
642
+ // undelivered. Under session replay this same load must reject —
643
+ // there the first request is still a parked `.running` fake until
644
+ // its recorded terminal feeds — so the live executor must reject
645
+ // too, or the recorded stream and the replayed stream disagree.
646
+ // Rejected means no new parked request.
647
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
648
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.effects.pendingImageLoadCount());
649
+
650
+ // Delivery order: the staged rejection drains first, then the
651
+ // queued loaded terminal.
652
+ try h.drainWakes();
653
+ try std.testing.expectEqual(@as(usize, 2), h.app_state.model.result_count);
654
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.rejected_count);
655
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, h.app_state.model.last.?.outcome);
656
+
657
+ // The occupied window ends exactly at delivery: the identical
658
+ // reload now parks as a fresh load and completes on its own feed.
659
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
660
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.effects.pendingImageLoadCount());
661
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
662
+ try h.drainWakes();
663
+ try std.testing.expectEqual(@as(usize, 3), h.app_state.model.result_count);
664
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.rejected_count);
665
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, h.app_state.model.last.?.outcome);
666
+ }
667
+
668
+ // ------------------------------------------------------------ real executor
669
+
670
+ test "real executor loads a local file through decode and registration" {
671
+ var tmp = std.testing.tmpDir(.{});
672
+ defer tmp.cleanup();
673
+ const io = std.testing.io;
674
+ var h = try Harness.create();
675
+ defer h.destroy();
676
+
677
+ var encoded_buffer: [4096]u8 = undefined;
678
+ const encoded = encodePngFixture(&encoded_buffer, 4, 3);
679
+ try tmp.dir.writeFile(io, .{ .sub_path = "cover.png", .data = encoded });
680
+
681
+ var path_buffer: [256]u8 = undefined;
682
+ test_path = try std.fmt.bufPrint(&path_buffer, ".zig-cache/tmp/{s}/cover.png", .{tmp.sub_path[0..]});
683
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
684
+ try waitForResult(&h, 1);
685
+ const result = h.app_state.model.last.?;
686
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, result.outcome);
687
+ try std.testing.expectEqual(@as(usize, 4), result.width);
688
+ try std.testing.expectEqual(@as(usize, 3), result.height);
689
+ const registered = h.harness.runtime.registeredCanvasImage(image_id).?;
690
+ try std.testing.expectEqual(@as(usize, 4), registered.width);
691
+ try std.testing.expectEqual(@as(usize, 3), registered.height);
692
+ }
693
+
694
+ test "real executor reports a missing local file with no url as not_found" {
695
+ var tmp = std.testing.tmpDir(.{});
696
+ defer tmp.cleanup();
697
+ var h = try Harness.create();
698
+ defer h.destroy();
699
+
700
+ var path_buffer: [256]u8 = undefined;
701
+ test_path = try std.fmt.bufPrint(&path_buffer, ".zig-cache/tmp/{s}/absent.png", .{tmp.sub_path[0..]});
702
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
703
+ try waitForResult(&h, 1);
704
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.not_found, h.app_state.model.last.?.outcome);
705
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(image_id) == null);
706
+ }
707
+
708
+ test "real executor reports connection refused as connect_failed" {
709
+ var h = try Harness.create();
710
+ defer h.destroy();
711
+
712
+ // Bind an ephemeral port, then close it: nothing listens there.
713
+ var threaded = std.Io.Threaded.init(std.testing.allocator, .{});
714
+ defer threaded.deinit();
715
+ const io = threaded.io();
716
+ const address = try std.Io.net.IpAddress.parseIp4("127.0.0.1", 0);
717
+ var listener = try std.Io.net.IpAddress.listen(&address, io, .{});
718
+ const dead_port = listener.socket.address.getPort();
719
+ listener.deinit(io);
720
+
721
+ var url_buffer: [128]u8 = undefined;
722
+ test_url = std.fmt.bufPrint(&url_buffer, "http://127.0.0.1:{d}/cover.png", .{dead_port}) catch unreachable;
723
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
724
+ try waitForResult(&h, 1);
725
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.connect_failed, h.app_state.model.last.?.outcome);
726
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(image_id) == null);
727
+ }
728
+
729
+ // A loopback HTTP fixture serving image routes (the fetch test
730
+ // fixture's shape, image-flavored).
731
+ const Fixture = struct {
732
+ allocator: std.mem.Allocator,
733
+ threaded: *std.Io.Threaded,
734
+ listener: std.Io.net.Server,
735
+ port: u16,
736
+ accept_future: std.Io.Future(void),
737
+ stopping: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
738
+ request_count: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
739
+ png_storage: [4096]u8 = undefined,
740
+ png_len: usize = 0,
741
+
742
+ fn start(allocator: std.mem.Allocator) !*Fixture {
743
+ const self = try allocator.create(Fixture);
744
+ errdefer allocator.destroy(self);
745
+ const threaded = try allocator.create(std.Io.Threaded);
746
+ errdefer allocator.destroy(threaded);
747
+ threaded.* = std.Io.Threaded.init(allocator, .{});
748
+ errdefer threaded.deinit();
749
+ const io = threaded.io();
750
+ const address = try std.Io.net.IpAddress.parseIp4("127.0.0.1", 0);
751
+ var listener = try std.Io.net.IpAddress.listen(&address, io, .{ .reuse_address = true });
752
+ errdefer listener.deinit(io);
753
+ self.* = .{
754
+ .allocator = allocator,
755
+ .threaded = threaded,
756
+ .listener = listener,
757
+ .port = listener.socket.address.getPort(),
758
+ .accept_future = undefined,
759
+ };
760
+ self.png_len = encodePngFixture(&self.png_storage, 4, 3).len;
761
+ self.accept_future = try std.Io.concurrent(io, serverMain, .{self});
762
+ return self;
763
+ }
764
+
765
+ fn stop(self: *Fixture) void {
766
+ const io = self.threaded.io();
767
+ self.stopping.store(true, .release);
768
+ self.accept_future.cancel(io);
769
+ self.listener.deinit(io);
770
+ self.threaded.deinit();
771
+ const allocator = self.allocator;
772
+ allocator.destroy(self.threaded);
773
+ allocator.destroy(self);
774
+ }
775
+
776
+ fn url(self: *const Fixture, buffer: []u8, path: []const u8) []const u8 {
777
+ return std.fmt.bufPrint(buffer, "http://127.0.0.1:{d}{s}", .{ self.port, path }) catch unreachable;
778
+ }
779
+
780
+ fn serverMain(self: *Fixture) void {
781
+ const io = self.threaded.io();
782
+ while (!self.stopping.load(.acquire)) {
783
+ const stream = self.listener.accept(io) catch return;
784
+ self.handleConnection(io, stream) catch {};
785
+ stream.close(io);
786
+ }
787
+ }
788
+
789
+ fn handleConnection(self: *Fixture, io: std.Io, stream: std.Io.net.Stream) !void {
790
+ var recv_buffer: [8192]u8 = undefined;
791
+ var send_buffer: [8192]u8 = undefined;
792
+ var conn_reader = stream.reader(io, &recv_buffer);
793
+ var conn_writer = stream.writer(io, &send_buffer);
794
+ var server = std.http.Server.init(&conn_reader.interface, &conn_writer.interface);
795
+ var request = try server.receiveHead();
796
+ _ = self.request_count.fetchAdd(1, .monotonic);
797
+ const target = request.head.target;
798
+ if (std.mem.eql(u8, target, "/cover.png")) {
799
+ try request.respond(self.png_storage[0..self.png_len], .{
800
+ .keep_alive = false,
801
+ .extra_headers = &.{.{ .name = "content-type", .value = "image/png" }},
802
+ });
803
+ } else if (std.mem.eql(u8, target, "/broken.png")) {
804
+ try request.respond("these bytes are no image", .{ .keep_alive = false });
805
+ } else {
806
+ try request.respond("nope", .{ .status = .not_found, .keep_alive = false });
807
+ }
808
+ }
809
+ };
810
+
811
+ test "real executor fetches a url source, installs the cache, and hits it offline next time" {
812
+ var tmp = std.testing.tmpDir(.{});
813
+ defer tmp.cleanup();
814
+ const io = std.testing.io;
815
+ var h = try Harness.create();
816
+ defer h.destroy();
817
+ const fixture = try Fixture.start(std.testing.allocator);
818
+
819
+ var cache_dir_buffer: [256]u8 = undefined;
820
+ const cache_dir = try std.fmt.bufPrint(&cache_dir_buffer, ".zig-cache/tmp/{s}/caches", .{tmp.sub_path[0..]});
821
+ var url_buffer: [128]u8 = undefined;
822
+ var cache_buffer: [512]u8 = undefined;
823
+ test_url = fixture.url(&url_buffer, "/cover.png");
824
+ test_cache_path = try effects_mod.imageCachePath(&cache_buffer, cache_dir, test_url);
825
+ test_expected_bytes = @intCast(fixture.png_len);
826
+
827
+ // Missing local path falls through to the url (the audio cascade).
828
+ var path_buffer: [256]u8 = undefined;
829
+ test_path = try std.fmt.bufPrint(&path_buffer, ".zig-cache/tmp/{s}/absent.png", .{tmp.sub_path[0..]});
830
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
831
+ try waitForResult(&h, 1);
832
+ var result = h.app_state.model.last.?;
833
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, result.outcome);
834
+ try std.testing.expectEqual(@as(usize, 4), result.width);
835
+ try std.testing.expectEqual(@as(u16, 200), result.status);
836
+ try std.testing.expect(fixture.request_count.load(.acquire) >= 1);
837
+
838
+ // The verified download was installed under the content address,
839
+ // whole, with no .partial debris beside it.
840
+ const cached = try std.Io.Dir.cwd().readFileAlloc(io, test_cache_path, std.testing.allocator, .limited(8192));
841
+ defer std.testing.allocator.free(cached);
842
+ try std.testing.expectEqualSlices(u8, fixture.png_storage[0..fixture.png_len], cached);
843
+
844
+ // Stop the server: the second load must resolve from the cache —
845
+ // no network, same pixels.
846
+ fixture.stop();
847
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
848
+ try waitForResult(&h, 2);
849
+ result = h.app_state.model.last.?;
850
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, result.outcome);
851
+ try std.testing.expectEqual(@as(usize, 4), result.width);
852
+ try std.testing.expectEqual(@as(usize, 3), result.height);
853
+ // The cache hit reports status 0, the documented contract: status
854
+ // is the HTTP status only for loads that performed an exchange, and
855
+ // this one never touched the network (the server is gone) — a
856
+ // fabricated 200 would claim an exchange that never happened, and
857
+ // the 0 lets apps tell a cached .loaded from a network one (the
858
+ // first load's real 200 above).
859
+ try std.testing.expectEqual(@as(u16, 0), result.status);
860
+ }
861
+
862
+ test "cache install temp names are writer-unique" {
863
+ // Two operations toward the SAME cache path (two ids loading one
864
+ // URL) must never share a temp: a shared name lets one writer
865
+ // truncate the other's bytes mid-write, or rename a half-written
866
+ // file into the cache name.
867
+ var first_buffer: [512]u8 = undefined;
868
+ var second_buffer: [512]u8 = undefined;
869
+ const cache_path = "/tmp/caches/images/abc123.png";
870
+ const first = try effects_mod.imageCachePartialPath(&first_buffer, cache_path, 7, 0xaaaa);
871
+ const second = try effects_mod.imageCachePartialPath(&second_buffer, cache_path, 8, 0xaaaa);
872
+ try std.testing.expect(!std.mem.eql(u8, first, second));
873
+ // Both stay recognizable install debris beside their cache path.
874
+ try std.testing.expect(std.mem.startsWith(u8, first, cache_path));
875
+ try std.testing.expect(std.mem.endsWith(u8, first, ".partial"));
876
+ try std.testing.expect(std.mem.startsWith(u8, second, cache_path));
877
+ try std.testing.expect(std.mem.endsWith(u8, second, ".partial"));
878
+
879
+ // The generation alone is only channel-local: two channels in one
880
+ // process (or two processes sharing the platform cache directory)
881
+ // can install at the SAME generation concurrently. The random
882
+ // writer token keeps their temps distinct — a name built from the
883
+ // generation alone would collide here and recreate the
884
+ // truncate/rename race.
885
+ const third = try effects_mod.imageCachePartialPath(&second_buffer, cache_path, 7, 0xbbbb);
886
+ try std.testing.expect(!std.mem.eql(u8, first, third));
887
+
888
+ try std.testing.expectError(error.InvalidImageOptions, effects_mod.imageCachePartialPath(&first_buffer, "", 7, 0xaaaa));
889
+ }
890
+
891
+ test "concurrent loads of one url both complete with an intact cache and no temp debris" {
892
+ var tmp = std.testing.tmpDir(.{});
893
+ defer tmp.cleanup();
894
+ const io = std.testing.io;
895
+ var h = try Harness.create();
896
+ defer h.destroy();
897
+ const fixture = try Fixture.start(std.testing.allocator);
898
+ defer fixture.stop();
899
+
900
+ var cache_dir_buffer: [256]u8 = undefined;
901
+ const cache_dir = try std.fmt.bufPrint(&cache_dir_buffer, ".zig-cache/tmp/{s}/caches", .{tmp.sub_path[0..]});
902
+ var url_buffer: [128]u8 = undefined;
903
+ var cache_buffer: [512]u8 = undefined;
904
+ test_url = fixture.url(&url_buffer, "/cover.png");
905
+ test_cache_path = try effects_mod.imageCachePath(&cache_buffer, cache_dir, test_url);
906
+ test_expected_bytes = @intCast(fixture.png_len);
907
+
908
+ // Two ids over the SAME url, in flight together: each install
909
+ // writes its own operation-unique temp toward the shared cache
910
+ // path, so whichever rename lands last publishes a WHOLE file.
911
+ test_id = 91;
912
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
913
+ test_id = 92;
914
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
915
+ try waitForResult(&h, 2);
916
+
917
+ // Both loads decoded and registered — neither terminal was lost or
918
+ // degraded by the other's install.
919
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(91) != null);
920
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(92) != null);
921
+
922
+ // The cache entry is whole (never a torn write published by an
923
+ // early rename), and no install temp survives beside it.
924
+ const cached = try std.Io.Dir.cwd().readFileAlloc(io, test_cache_path, std.testing.allocator, .limited(8192));
925
+ defer std.testing.allocator.free(cached);
926
+ try std.testing.expectEqualSlices(u8, fixture.png_storage[0..fixture.png_len], cached);
927
+
928
+ var images_dir_buffer: [512]u8 = undefined;
929
+ const images_dir = try std.fmt.bufPrint(&images_dir_buffer, "{s}/images", .{cache_dir});
930
+ var dir = try std.Io.Dir.cwd().openDir(io, images_dir, .{ .iterate = true });
931
+ defer dir.close(io);
932
+ var iterator = dir.iterate();
933
+ var file_count: usize = 0;
934
+ while (try iterator.next(io)) |entry| {
935
+ try std.testing.expect(!std.mem.endsWith(u8, entry.name, ".partial"));
936
+ file_count += 1;
937
+ }
938
+ try std.testing.expectEqual(@as(usize, 1), file_count);
939
+ }
940
+
941
+ /// Create a FIFO at `path` (POSIX-only; callers gate on the platform) —
942
+ /// the file-effect tests' convention. The cache probe opens it
943
+ /// read-only, which blocks inside `open` while no writer exists: the
944
+ /// deterministic way to park a load INSIDE the cache probe so a cancel
945
+ /// lands there.
946
+ fn makeFifo(path: []const u8) !void {
947
+ var command_buffer: [512]u8 = undefined;
948
+ const command = try std.fmt.bufPrint(&command_buffer, "mkfifo '{s}'", .{path});
949
+ const result = try std.process.run(std.testing.allocator, std.testing.io, .{
950
+ .argv = &.{ "/bin/sh", "-c", command },
951
+ });
952
+ defer std.testing.allocator.free(result.stdout);
953
+ defer std.testing.allocator.free(result.stderr);
954
+ try std.testing.expect(result.term == .exited and result.term.exited == 0);
955
+ }
956
+
957
+ test "a cancel landing inside the cache probe terminates cancelled and never fetches" {
958
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
959
+ const io = std.testing.io;
960
+ var tmp = std.testing.tmpDir(.{});
961
+ defer tmp.cleanup();
962
+ var h = try Harness.create();
963
+ defer h.destroy();
964
+ const fixture = try Fixture.start(std.testing.allocator);
965
+ defer fixture.stop();
966
+
967
+ // The cache "entry" is a reader-less FIFO: the probe's open blocks
968
+ // until the cancel interrupts it. Cancel delivery is one-shot — the
969
+ // Canceled return IS the delivery — so a probe that swallowed it
970
+ // into a cache miss would fall through to the network with nothing
971
+ // left to interrupt the fetch.
972
+ var cache_buffer: [256]u8 = undefined;
973
+ const cache_path = try std.fmt.bufPrint(&cache_buffer, ".zig-cache/tmp/{s}/probe.fifo", .{tmp.sub_path[0..]});
974
+ try makeFifo(cache_path);
975
+
976
+ var url_buffer: [128]u8 = undefined;
977
+ test_url = fixture.url(&url_buffer, "/cover.png");
978
+ test_cache_path = cache_path;
979
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
980
+ // Let the worker reach the blocking open (a cancel that lands even
981
+ // earlier still terminates the load before the probe — either way
982
+ // the network must stay untouched).
983
+ try std.Io.sleep(io, std.Io.Duration.fromMilliseconds(100), .awake);
984
+ try h.app_state.dispatch(&h.harness.runtime, 1, .stop);
985
+ try waitForResult(&h, 1);
986
+
987
+ // Exactly one terminal, `.cancelled` — and the spent cancel never
988
+ // leaked the load into a network fetch: the fixture saw ZERO
989
+ // requests, and nothing was registered.
990
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.result_count);
991
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.cancelled, h.app_state.model.last.?.outcome);
992
+ try std.testing.expectEqual(@as(u32, 0), fixture.request_count.load(.acquire));
993
+ try std.testing.expect(h.harness.runtime.registeredCanvasImage(image_id) == null);
994
+ }
995
+
996
+ test "real executor reports non-2xx statuses and undecodable bodies honestly" {
997
+ var h = try Harness.create();
998
+ defer h.destroy();
999
+ const fixture = try Fixture.start(std.testing.allocator);
1000
+ defer fixture.stop();
1001
+
1002
+ var url_buffer: [128]u8 = undefined;
1003
+ test_url = fixture.url(&url_buffer, "/missing.png");
1004
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
1005
+ try waitForResult(&h, 1);
1006
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.http_status, h.app_state.model.last.?.outcome);
1007
+ try std.testing.expectEqual(@as(u16, 404), h.app_state.model.last.?.status);
1008
+
1009
+ test_url = fixture.url(&url_buffer, "/broken.png");
1010
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
1011
+ try waitForResult(&h, 2);
1012
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.decode_failed, h.app_state.model.last.?.outcome);
1013
+ }
1014
+
1015
+ test "imageCachePath keys by url hash under images/ and keeps the extension" {
1016
+ var buffer: [512]u8 = undefined;
1017
+ const path = try effects_mod.imageCachePath(&buffer, "/tmp/caches", "https://cdn.example.com/art/cover.png?sig=abc");
1018
+ try std.testing.expect(std.mem.startsWith(u8, path, "/tmp/caches/images/"));
1019
+ // The query-string suffix never smuggles into the file name; the
1020
+ // dot-extension survives only when plausible.
1021
+ try std.testing.expect(std.mem.indexOfAny(u8, path, "?#&") == null);
1022
+
1023
+ const clean = try effects_mod.imageCachePath(&buffer, "/tmp/caches", "https://cdn.example.com/art/cover.png");
1024
+ try std.testing.expect(std.mem.endsWith(u8, clean, ".png"));
1025
+ var second_buffer: [512]u8 = undefined;
1026
+ const again = try effects_mod.imageCachePath(&second_buffer, "/tmp/caches", "https://cdn.example.com/art/cover.png");
1027
+ try std.testing.expectEqualStrings(clean, again);
1028
+ // A different url gets a different address, and the audio cache
1029
+ // lives in its own segment.
1030
+ const other = try effects_mod.imageCachePath(&second_buffer, "/tmp/caches", "https://cdn.example.com/art/other.png");
1031
+ try std.testing.expect(!std.mem.eql(u8, clean, other));
1032
+ try std.testing.expectError(error.InvalidImageOptions, effects_mod.imageCachePath(&buffer, "", "https://x.example/a.png"));
1033
+ }
1034
+
1035
+ // -------------------------------------------------- export surface pin
1036
+
1037
+ /// The public SDK root, exactly as an external Zig app imports it: an
1038
+ /// app writing an `Effects.imageMsg` Msg arm (and reasoning about the
1039
+ /// image bounds) needs these names on the public root, not
1040
+ /// module-internal paths — the media-surface export pin's convention.
1041
+ const sdk = @import("../root.zig");
1042
+
1043
+ test "the image effect surface is exported through the public root" {
1044
+ // The payload/outcome types on the SDK root and the runtime root
1045
+ // ARE the effects module's, so an external Msg arm and an internal
1046
+ // drain speak one type.
1047
+ comptime std.debug.assert(sdk.EffectImageResult == effects_mod.EffectImageResult);
1048
+ comptime std.debug.assert(sdk.EffectImageOutcome == effects_mod.EffectImageOutcome);
1049
+ comptime std.debug.assert(sdk.runtime.EffectImageResult == sdk.EffectImageResult);
1050
+ comptime std.debug.assert(sdk.runtime.EffectImageOutcome == sdk.EffectImageOutcome);
1051
+ // The bounds an app sizes buffers and teaching against, exported on
1052
+ // both roots beside the audio limits they mirror.
1053
+ comptime std.debug.assert(sdk.max_effect_image_path_bytes == effects_mod.max_effect_image_path_bytes);
1054
+ comptime std.debug.assert(sdk.max_effect_image_bytes == effects_mod.max_effect_image_bytes);
1055
+ comptime std.debug.assert(sdk.effect_image_blob_hash_len == effects_mod.effect_image_blob_hash_len);
1056
+ comptime std.debug.assert(sdk.runtime.max_effect_image_path_bytes == effects_mod.max_effect_image_path_bytes);
1057
+ comptime std.debug.assert(sdk.runtime.max_effect_image_bytes == effects_mod.max_effect_image_bytes);
1058
+ comptime std.debug.assert(sdk.runtime.effect_image_blob_hash_len == effects_mod.effect_image_blob_hash_len);
1059
+
1060
+ // Compile-shaped and driven: the exact Msg arm an external app
1061
+ // writes over the public constructor and payload type.
1062
+ const AppMsg = union(enum) { cover_loaded: sdk.EffectImageResult };
1063
+ const make = sdk.Effects(AppMsg).imageMsg(.cover_loaded);
1064
+ const msg = make(.{ .id = 7, .outcome = .loaded, .width = 2, .height = 3, .status = 200 });
1065
+ try std.testing.expectEqual(@as(u64, 7), msg.cover_loaded.id);
1066
+ try std.testing.expectEqual(sdk.EffectImageOutcome.loaded, msg.cover_loaded.outcome);
1067
+
1068
+ // The cache-path convention is callable through the public root
1069
+ // (and both roots resolve to one function), sized by the exported
1070
+ // path bound.
1071
+ var buffer: [sdk.max_effect_image_path_bytes]u8 = undefined;
1072
+ const path = try sdk.imageCachePath(&buffer, "/tmp/caches", "https://cdn.example.com/art/cover.png");
1073
+ var runtime_buffer: [sdk.runtime.max_effect_image_path_bytes]u8 = undefined;
1074
+ const runtime_path = try sdk.runtime.imageCachePath(&runtime_buffer, "/tmp/caches", "https://cdn.example.com/art/cover.png");
1075
+ try std.testing.expectEqualStrings(path, runtime_path);
1076
+ try std.testing.expect(std.mem.startsWith(u8, path, "/tmp/caches/images/"));
1077
+ }
1078
+
1079
+ test "a fetch terminal still undelivered occupies its key against loadImage" {
1080
+ var h = try Harness.create();
1081
+ defer h.destroy();
1082
+ h.app_state.effects.executor = .fake;
1083
+
1084
+ // A fetch — a different family in the same shared key space — parks
1085
+ // under the fake executor; feeding its response queues the terminal
1086
+ // and stores `.draining`, with delivery still ahead.
1087
+ h.app_state.effects.fetch(.{ .key = image_id, .url = "http://example.test/cover" });
1088
+ try h.app_state.effects.feedResponse(image_id, 200, "ok");
1089
+
1090
+ // Under session replay the fetch is still a parked `.running` fake
1091
+ // at this dispatch (its journaled terminal feeds at the recorded
1092
+ // delivery position), so a live executor that accepts this image
1093
+ // load journals a Msg stream replay cannot reproduce. Rejected
1094
+ // means no new parked image request.
1095
+ test_path = "assets/cover.png";
1096
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
1097
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.effects.pendingImageLoadCount());
1098
+ }
1099
+
1100
+ test "an image terminal still undelivered occupies its id against a spawn of the same key" {
1101
+ var h = try Harness.create();
1102
+ defer h.destroy();
1103
+ h.app_state.effects.executor = .fake;
1104
+
1105
+ test_path = "assets/cover.png";
1106
+ try h.app_state.dispatch(&h.harness.runtime, 1, .start);
1107
+ var encoded_buffer: [2048]u8 = undefined;
1108
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
1109
+ try h.app_state.effects.feedImageBytes(image_id, encoded);
1110
+
1111
+ // Inside the posted-but-undelivered window a spawn of the same key
1112
+ // must reject: the families share one key space, and under session
1113
+ // replay the image request is still a parked `.running` fake here
1114
+ // — the parked fake rejects the spawn, so a live executor that
1115
+ // accepted it would journal a Msg stream replay cannot reproduce.
1116
+ h.app_state.effects.spawn(.{ .key = image_id, .argv = &.{"noop"}, .on_exit = ImageEffects.exitMsg(.spawn_exit) });
1117
+ try std.testing.expectEqual(@as(usize, 0), h.app_state.effects.pendingSpawnCount());
1118
+
1119
+ // Delivery frees the key: after the drain the same spawn parks.
1120
+ try h.drainWakes();
1121
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.model.result_count);
1122
+ h.app_state.effects.spawn(.{ .key = image_id, .argv = &.{"noop"}, .on_exit = ImageEffects.exitMsg(.spawn_exit) });
1123
+ try std.testing.expectEqual(@as(usize, 1), h.app_state.effects.pendingSpawnCount());
1124
+ }
1125
+
1126
+ /// Fails exactly one allocation — the next one matching the staged
1127
+ /// image source buffer's distinctive size — and delegates everything
1128
+ /// else. `std.testing.FailingAllocator` fails every allocation from
1129
+ /// its fail index on, which would take the same dispatch's view
1130
+ /// rebuild down with the load; this failure is surgical.
1131
+ const ImageBufferFailingAllocator = struct {
1132
+ backing: std.mem.Allocator,
1133
+ armed: bool = false,
1134
+
1135
+ const vtable: std.mem.Allocator.VTable = .{
1136
+ .alloc = alloc,
1137
+ .resize = resize,
1138
+ .remap = remap,
1139
+ .free = free,
1140
+ };
1141
+
1142
+ fn allocator(self: *ImageBufferFailingAllocator) std.mem.Allocator {
1143
+ return .{ .ptr = self, .vtable = &vtable };
1144
+ }
1145
+
1146
+ fn alloc(ptr: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
1147
+ const self: *ImageBufferFailingAllocator = @ptrCast(@alignCast(ptr));
1148
+ if (self.armed and len == effects_mod.max_effect_image_bytes + 1) {
1149
+ self.armed = false;
1150
+ return null;
1151
+ }
1152
+ return self.backing.vtable.alloc(self.backing.ptr, len, alignment, ret_addr);
1153
+ }
1154
+
1155
+ fn resize(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
1156
+ const self: *ImageBufferFailingAllocator = @ptrCast(@alignCast(ptr));
1157
+ return self.backing.vtable.resize(self.backing.ptr, memory, alignment, new_len, ret_addr);
1158
+ }
1159
+
1160
+ fn remap(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
1161
+ const self: *ImageBufferFailingAllocator = @ptrCast(@alignCast(ptr));
1162
+ return self.backing.vtable.remap(self.backing.ptr, memory, alignment, new_len, ret_addr);
1163
+ }
1164
+
1165
+ fn free(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void {
1166
+ const self: *ImageBufferFailingAllocator = @ptrCast(@alignCast(ptr));
1167
+ self.backing.vtable.free(self.backing.ptr, memory, alignment, ret_addr);
1168
+ }
1169
+ };
1170
+
1171
+ test "a start-failure rejection holds the id until it drains; a reload inside the window rejects" {
1172
+ // The failing allocator backs the APP (and so the effects
1173
+ // channel): the staged source buffer is loadImage's first and only
1174
+ // channel allocation, drawn before any slot is claimed.
1175
+ var failing: ImageBufferFailingAllocator = .{ .backing = std.heap.page_allocator };
1176
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1177
+ defer harness.destroy(std.testing.allocator);
1178
+ harness.null_platform.gpu_surfaces = true;
1179
+ harness.null_platform.image_decode = true;
1180
+ const app_state = try std.testing.allocator.create(ImageApp);
1181
+ defer std.testing.allocator.destroy(app_state);
1182
+ app_state.* = ImageApp.init(failing.allocator(), .{}, .{
1183
+ .name = "effects-image-start-fail",
1184
+ .scene = image_scene,
1185
+ .canvas_label = canvas_label,
1186
+ .update_fx = imageUpdate,
1187
+ .view = imageView,
1188
+ });
1189
+ defer app_state.deinit();
1190
+ const app = app_state.app();
1191
+ try harness.start(app);
1192
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1193
+ .label = canvas_label,
1194
+ .size = geometry.SizeF.init(400, 300),
1195
+ .scale_factor = 1,
1196
+ .frame_index = 1,
1197
+ .timestamp_ns = 1_000_000,
1198
+ .nonblank = true,
1199
+ } });
1200
+ app_state.effects.executor = .fake;
1201
+ test_id = image_id;
1202
+ test_path = "assets/cover.png";
1203
+ test_url = "";
1204
+ test_cache_path = "";
1205
+ test_expected_bytes = 0;
1206
+ test_timeout_ms = effects_mod.default_effect_fetch_timeout_ms;
1207
+ test_reload_on_result = false;
1208
+
1209
+ // Fail exactly the staged source buffer's allocation: the load is
1210
+ // refused with executor truth (a non-regenerating staged
1211
+ // rejection) before any slot is claimed, so no request parks.
1212
+ failing.armed = true;
1213
+ try app_state.dispatch(&harness.runtime, 1, .start);
1214
+ try std.testing.expect(!failing.armed);
1215
+ try std.testing.expectEqual(@as(usize, 0), app_state.effects.pendingImageLoadCount());
1216
+
1217
+ // A reload inside the staged window must reject: under session
1218
+ // replay the failed request is a parked `.running` fake here (its
1219
+ // journaled terminal feeds at the recorded delivery position — the
1220
+ // replayed request allocates its own buffer and parks), so a live
1221
+ // accept would journal a Msg stream replay rejects.
1222
+ try app_state.dispatch(&harness.runtime, 1, .start);
1223
+ try std.testing.expectEqual(@as(usize, 0), app_state.effects.pendingImageLoadCount());
1224
+
1225
+ // Both staged rejections deliver on the drain, in staging order.
1226
+ while (harness.null_platform.takeWake()) |_| {}
1227
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1228
+ try std.testing.expectEqual(@as(usize, 2), app_state.model.result_count);
1229
+ try std.testing.expectEqual(@as(usize, 2), app_state.model.rejected_count);
1230
+
1231
+ // The window ends at delivery: the same id parks and loads.
1232
+ try app_state.dispatch(&harness.runtime, 1, .start);
1233
+ try std.testing.expectEqual(@as(usize, 1), app_state.effects.pendingImageLoadCount());
1234
+ var encoded_buffer: [2048]u8 = undefined;
1235
+ const encoded = encodePngFixture(&encoded_buffer, 1, 1);
1236
+ try app_state.effects.feedImageBytes(image_id, encoded);
1237
+ while (harness.null_platform.takeWake()) |_| {}
1238
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1239
+ try std.testing.expectEqual(@as(usize, 3), app_state.model.result_count);
1240
+ try std.testing.expectEqual(effects_mod.EffectImageOutcome.loaded, app_state.model.last.?.outcome);
1241
+ try std.testing.expectEqual(@as(usize, 2), app_state.model.rejected_count);
1242
+ }
1243
+
1244
+ test "a fire-and-forget start failure still stages: the id stays occupied until the terminal drains" {
1245
+ var failing: ImageBufferFailingAllocator = .{ .backing = std.heap.page_allocator };
1246
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1247
+ defer harness.destroy(std.testing.allocator);
1248
+ harness.null_platform.gpu_surfaces = true;
1249
+ harness.null_platform.image_decode = true;
1250
+ const app_state = try std.testing.allocator.create(ImageApp);
1251
+ defer std.testing.allocator.destroy(app_state);
1252
+ app_state.* = ImageApp.init(failing.allocator(), .{}, .{
1253
+ .name = "effects-image-ff-start-fail",
1254
+ .scene = image_scene,
1255
+ .canvas_label = canvas_label,
1256
+ .update_fx = imageUpdate,
1257
+ .view = imageView,
1258
+ });
1259
+ defer app_state.deinit();
1260
+ const app = app_state.app();
1261
+ try harness.start(app);
1262
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1263
+ .label = canvas_label,
1264
+ .size = geometry.SizeF.init(400, 300),
1265
+ .scale_factor = 1,
1266
+ .frame_index = 1,
1267
+ .timestamp_ns = 1_000_000,
1268
+ .nonblank = true,
1269
+ } });
1270
+ app_state.effects.executor = .fake;
1271
+ test_id = image_id;
1272
+ test_path = "assets/cover.png";
1273
+ test_url = "";
1274
+ test_cache_path = "";
1275
+ test_expected_bytes = 0;
1276
+ test_timeout_ms = effects_mod.default_effect_fetch_timeout_ms;
1277
+ test_reload_on_result = false;
1278
+
1279
+ // A fire-and-forget load (no on_result) whose source buffer
1280
+ // allocation fails: executor truth, so the terminal must stage —
1281
+ // occupying the id — even though no Msg will ever deliver from it.
1282
+ failing.armed = true;
1283
+ try app_state.dispatch(&harness.runtime, 1, .start_fire_and_forget);
1284
+ try std.testing.expect(!failing.armed);
1285
+ try std.testing.expectEqual(@as(usize, 0), app_state.effects.pendingImageLoadCount());
1286
+
1287
+ // Inside the staged window a reload of the same id must reject,
1288
+ // exactly as it does when the failed load carried a handler: under
1289
+ // session replay the fire-and-forget request is a parked
1290
+ // `.running` fake until its journaled terminal feeds.
1291
+ try app_state.dispatch(&harness.runtime, 1, .start);
1292
+ try std.testing.expectEqual(@as(usize, 0), app_state.effects.pendingImageLoadCount());
1293
+
1294
+ // The drain delivers the reload's rejection only — the
1295
+ // fire-and-forget terminal retires silently (no handler, no Msg).
1296
+ while (harness.null_platform.takeWake()) |_| {}
1297
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1298
+ try std.testing.expectEqual(@as(usize, 1), app_state.model.result_count);
1299
+ try std.testing.expectEqual(@as(usize, 1), app_state.model.rejected_count);
1300
+
1301
+ // The window ends at the drain: the same id parks again.
1302
+ try app_state.dispatch(&harness.runtime, 1, .start);
1303
+ try std.testing.expectEqual(@as(usize, 1), app_state.effects.pendingImageLoadCount());
1304
+ }