@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
@@ -40,13 +40,23 @@
40
40
  //! that consumes it. Nested dispatches (automation-driven events inside
41
41
  //! `frame_requested`) commit innermost-first for the same reason.
42
42
  //!
43
+ //! That feed-then-dispatch premise only holds if event boundaries are
44
+ //! CAUSAL: every result journaled ahead of an event must answer a
45
+ //! request issued by some EARLIER dispatch — otherwise the file-order
46
+ //! feed reaches a result whose request does not exist yet and replay
47
+ //! reports a false divergence. The live drain guarantees it: one drain
48
+ //! pass consumes only completions that existed when the pass began
49
+ //! (`Effects.DrainBoundary`), so a load spawned by an update handler
50
+ //! inside the pass — even one fast enough to finish before the pass
51
+ //! ends — delivers, and journals, under the NEXT wake's event record.
52
+ //!
43
53
  //! Enum payloads ride as their declaration-order integer values, so
44
54
  //! reordering any journaled enum is a format break: bump
45
55
  //! `format_version` when one moves.
46
56
  //!
47
57
  //! Coverage note: automation driving is fully journaled. Verbs that
48
58
  //! synthesize PLATFORM events (widget-click/hold/context-press/drag/
49
- //! wheel/key, resize, menu-command, shortcut, tray-action) journal
59
+ //! wheel/key/pinch, resize, menu-command, shortcut, tray-action) journal
50
60
  //! those events; every widget-action verb — including the direct-
51
61
  //! surface ones (focus, select, set_selection, set_text, and the
52
62
  //! composition edits) — journals as the outer-wins
@@ -75,8 +85,19 @@ pub const magic = "NSDKSJNL";
75
85
  /// composition verbs (`set_composition`/`commit_composition`/
76
86
  /// `cancel_composition`, codes 11-13) to the accessibility-action
77
87
  /// record's verb enum — a v3 reader hitting one of those codes would
78
- /// have reported the file corrupt instead of refusing the skew.
79
- pub const format_version: u32 = 4;
88
+ /// have reported the file corrupt instead of refusing the skew; v5
89
+ /// added the pinch magnification `scale` field to gpu-surface input
90
+ /// records (a layout change every v4 reader would misparse) plus the
91
+ /// `pinch_begin`/`pinch_change`/`pinch_end` input kinds (codes 12-14);
92
+ /// v6 added the `hidden` flag to window-frame records (the
93
+ /// `close_policy = .hide` window state — a layout change every v5
94
+ /// reader would misparse); v7 added the `.image` effect-result kind
95
+ /// (code 11) with its outcome/dimension fields and the blob-store
96
+ /// content address (`image_blob_hash`/`image_blob_len`) appended to
97
+ /// every effect record — a v6 reader would have called an image
98
+ /// record's kind code corrupt and misparsed the longer layouts, so it
99
+ /// refuses the skew at the preamble instead.
100
+ pub const format_version: u32 = 7;
80
101
 
81
102
  // ------------------------------------------------------------- budgets
82
103
  //
@@ -426,6 +447,8 @@ pub fn encodeEvent(event: platform.Event, buffer: []u8) JournalError![]const u8
426
447
  try cursor.writeBool(state.focused);
427
448
  try cursor.writeBool(state.maximized);
428
449
  try cursor.writeBool(state.fullscreen);
450
+ // v6: alive-but-policy-hidden (`close_policy = .hide`).
451
+ try cursor.writeBool(state.hidden);
429
452
  },
430
453
  .window_focused => |window_id| {
431
454
  try cursor.writeEnum(EventTag.window_focused);
@@ -530,6 +553,8 @@ pub fn encodeEvent(event: platform.Event, buffer: []u8) JournalError![]const u8
530
553
  try cursor.writeInt(u64, @intCast(composition_cursor));
531
554
  }
532
555
  try writeModifiers(&cursor, input.modifiers);
556
+ // v5: the pinch magnification delta (0 on non-pinch kinds).
557
+ try cursor.writeF32(input.scale);
533
558
  },
534
559
  .gpu_surface_scroll_driver => |driver| {
535
560
  try cursor.writeEnum(EventTag.gpu_surface_scroll_driver);
@@ -611,6 +636,7 @@ pub fn decodeEvent(bytes: []const u8, storage: *EventDecodeStorage) JournalError
611
636
  .focused = try cursor.readBool(),
612
637
  .maximized = try cursor.readBool(),
613
638
  .fullscreen = try cursor.readBool(),
639
+ .hidden = try cursor.readBool(),
614
640
  } };
615
641
  },
616
642
  .window_focused => .{ .window_focused = try cursor.readInt(u64) },
@@ -740,23 +766,27 @@ pub fn decodeEvent(bytes: []const u8, storage: *EventDecodeStorage) JournalError
740
766
  if (try cursor.readBool()) {
741
767
  composition_cursor = std.math.cast(usize, try cursor.readInt(u64)) orelse return error.JournalCorrupt;
742
768
  }
743
- break :blk .{ .gpu_surface_input = .{
744
- .window_id = window_id,
745
- .label = label,
746
- .kind = kind,
747
- .timestamp_ns = timestamp_ns,
748
- .pointer_id = pointer_id,
749
- .x = x,
750
- .y = y,
751
- .button = button,
752
- .pressure = pressure,
753
- .delta_x = delta_x,
754
- .delta_y = delta_y,
755
- .key = key,
756
- .text = text,
757
- .composition_cursor = composition_cursor,
758
- .modifiers = try readModifiers(&cursor),
759
- } };
769
+ break :blk .{
770
+ .gpu_surface_input = .{
771
+ .window_id = window_id,
772
+ .label = label,
773
+ .kind = kind,
774
+ .timestamp_ns = timestamp_ns,
775
+ .pointer_id = pointer_id,
776
+ .x = x,
777
+ .y = y,
778
+ .button = button,
779
+ .pressure = pressure,
780
+ .delta_x = delta_x,
781
+ .delta_y = delta_y,
782
+ .key = key,
783
+ .text = text,
784
+ .composition_cursor = composition_cursor,
785
+ .modifiers = try readModifiers(&cursor),
786
+ // v5: the pinch magnification delta (0 on non-pinch kinds).
787
+ .scale = try cursor.readF32(),
788
+ },
789
+ };
760
790
  },
761
791
  .gpu_surface_scroll_driver => blk: {
762
792
  const window_id = try cursor.readInt(u64);
@@ -837,6 +867,13 @@ pub fn encodeEffect(record: EffectResultRecord, buffer: []u8) JournalError![]con
837
867
  try cursor.writeBool(record.audio_playing);
838
868
  try cursor.writeBool(record.audio_buffering);
839
869
  try cursor.writeBytes(&record.audio_bands);
870
+ // v7: image terminals — outcome, decoded dimensions, and the blob
871
+ // store content address of the journaled source bytes.
872
+ try cursor.writeEnum(record.image_outcome);
873
+ try cursor.writeInt(u64, record.image_width);
874
+ try cursor.writeInt(u64, record.image_height);
875
+ try cursor.writeBytes(&record.image_blob_hash);
876
+ try cursor.writeInt(u64, record.image_blob_len);
840
877
  return buffer[0..cursor.len];
841
878
  }
842
879
 
@@ -869,6 +906,12 @@ pub fn decodeEffect(bytes: []const u8) JournalError!EffectResultRecord {
869
906
  .audio_buffering = try cursor.readBool(),
870
907
  };
871
908
  @memcpy(&record.audio_bands, try cursor.readBytes(record.audio_bands.len));
909
+ // v7: image terminals.
910
+ record.image_outcome = try cursor.readEnum(runtime_effects.EffectImageOutcome);
911
+ record.image_width = try cursor.readInt(u64);
912
+ record.image_height = try cursor.readInt(u64);
913
+ @memcpy(&record.image_blob_hash, try cursor.readBytes(record.image_blob_hash.len));
914
+ record.image_blob_len = try cursor.readInt(u64);
872
915
  if (!cursor.done()) return error.JournalCorrupt;
873
916
  return record;
874
917
  }
@@ -1130,6 +1173,22 @@ test "event codec round-trips every payload variant" {
1130
1173
  } });
1131
1174
  try testing.expectEqualStrings("settings", decoded.window_frame_changed.label);
1132
1175
  try testing.expect(!decoded.window_frame_changed.open);
1176
+ try testing.expect(!decoded.window_frame_changed.hidden);
1177
+ }
1178
+ {
1179
+ // v6: a policy-hide keeps the window alive (`open` true) and
1180
+ // rides the `hidden` flag — both must survive the round trip.
1181
+ const decoded = try roundTripEvent(.{ .window_frame_changed = .{
1182
+ .id = 1,
1183
+ .label = "main",
1184
+ .title = "Player",
1185
+ .frame = geometry.RectF.init(0, 0, 480, 360),
1186
+ .open = true,
1187
+ .focused = false,
1188
+ .hidden = true,
1189
+ } });
1190
+ try testing.expect(decoded.window_frame_changed.open);
1191
+ try testing.expect(decoded.window_frame_changed.hidden);
1133
1192
  }
1134
1193
  {
1135
1194
  const decoded = try roundTripEvent(.{ .bridge_message = .{
@@ -1230,6 +1289,26 @@ test "event codec round-trips every payload variant" {
1230
1289
  try testing.expectEqualStrings("7", decoded.gpu_surface_input.text);
1231
1290
  try testing.expectEqual(@as(?usize, 3), decoded.gpu_surface_input.composition_cursor);
1232
1291
  try testing.expect(decoded.gpu_surface_input.modifiers.control);
1292
+ try testing.expectEqual(@as(f32, 0), decoded.gpu_surface_input.scale);
1293
+ }
1294
+ {
1295
+ // v5: pinch records carry the magnification delta and the
1296
+ // gesture kinds appended at codes 12-14.
1297
+ const decoded = try roundTripEvent(.{ .gpu_surface_input = .{
1298
+ .label = "timeline-canvas",
1299
+ .kind = .pinch_change,
1300
+ .timestamp_ns = 6,
1301
+ .x = 160,
1302
+ .y = 120,
1303
+ .scale = 0.25,
1304
+ } });
1305
+ try testing.expectEqual(platform.GpuSurfaceInputKind.pinch_change, decoded.gpu_surface_input.kind);
1306
+ try testing.expectEqual(@as(f32, 0.25), decoded.gpu_surface_input.scale);
1307
+ try testing.expectEqual(@as(f32, 160), decoded.gpu_surface_input.x);
1308
+ const begin = try roundTripEvent(.{ .gpu_surface_input = .{ .label = "timeline-canvas", .kind = .pinch_begin } });
1309
+ try testing.expectEqual(platform.GpuSurfaceInputKind.pinch_begin, begin.gpu_surface_input.kind);
1310
+ const end = try roundTripEvent(.{ .gpu_surface_input = .{ .label = "timeline-canvas", .kind = .pinch_end } });
1311
+ try testing.expectEqual(platform.GpuSurfaceInputKind.pinch_end, end.gpu_surface_input.kind);
1233
1312
  }
1234
1313
  {
1235
1314
  const decoded = try roundTripEvent(.{ .widget_accessibility_action = .{
@@ -1447,6 +1526,18 @@ test "reader refuses bad magic and version skew" {
1447
1526
  // journaled composition verb code corrupt).
1448
1527
  std.mem.writeInt(u32, skewed[magic.len..][0..4], format_version - 1, .little);
1449
1528
  try testing.expectError(error.JournalUnsupportedVersion, Reader.init(skewed[0..len]));
1529
+ // A concrete v6 journal (the version main ships, without the image
1530
+ // fields on effect records) is version skew, never corruption: the
1531
+ // preamble gate must fire before any record layout is consulted.
1532
+ var v6_preamble: [preamble_len]u8 = undefined;
1533
+ @memcpy(v6_preamble[0..magic.len], magic);
1534
+ std.mem.writeInt(u32, v6_preamble[magic.len..][0..4], 6, .little);
1535
+ try testing.expectError(error.JournalUnsupportedVersion, Reader.init(&v6_preamble));
1536
+ // The teaching names the version this build speaks, so the reader of
1537
+ // the error can see the skew rather than suspect file damage.
1538
+ const teaching = describeError(error.JournalUnsupportedVersion);
1539
+ try testing.expect(std.mem.indexOf(u8, teaching, "v7") != null);
1540
+ try testing.expect(std.mem.indexOf(u8, teaching, "re-record") != null);
1450
1541
  }
1451
1542
 
1452
1543
  test "reader fails loudly on truncation at every boundary" {
@@ -25,6 +25,7 @@ const platform = @import("../platform/root.zig");
25
25
  const runtime_clock = @import("clock.zig");
26
26
  const runtime_effects = @import("effects.zig");
27
27
  const journal = @import("session_journal.zig");
28
+ const session_blobs = @import("session_blobs.zig");
28
29
 
29
30
  pub const Header = journal.Header;
30
31
 
@@ -37,6 +38,13 @@ pub const RecorderSink = struct {
37
38
 
38
39
  pub const SessionRecorder = struct {
39
40
  sink: RecorderSink,
41
+ /// Where large effect payloads go out of line (`blobs/` beside the
42
+ /// journal, content-addressed — see session_blobs.zig). Bound by
43
+ /// the owner alongside the sink; null means no blob storage, and
44
+ /// the first effect result that NEEDS one (an image load's source
45
+ /// bytes) fails the recording loudly rather than journaling a
46
+ /// record replay could never resolve.
47
+ blob_sink: ?session_blobs.SessionBlobSink = null,
40
48
  began: bool = false,
41
49
  finished: bool = false,
42
50
  failed: bool = false,
@@ -185,10 +193,27 @@ pub const SessionRecorder = struct {
185
193
  }
186
194
 
187
195
  /// Record one drained effect result (the `Effects.bindJournal`
188
- /// callback target).
196
+ /// callback target). Image results carry their ENCODED source
197
+ /// bytes in `payload`; those move into the content-addressed blob
198
+ /// store at this moment — effect-result time — and the journal
199
+ /// record keeps only the address and length, so records stay small
200
+ /// and identical payloads share one blob.
189
201
  pub fn recordEffect(self: *SessionRecorder, record: runtime_effects.EffectResultRecord) void {
190
202
  if (!self.began or self.failed or self.finished) return;
191
- const payload = journal.encodeEffect(record, &self.effect_buffer) catch {
203
+ var journaled = record;
204
+ if (record.kind == .image and record.payload.len > 0) {
205
+ const blob_sink = self.blob_sink orelse {
206
+ return self.fail("an image effect result needs the session blob store, and none is bound - wire SessionRecorder.blob_sink (the app runner creates blobs/ beside the journal)");
207
+ };
208
+ const hash = session_blobs.hashBytes(record.payload);
209
+ blob_sink.write_fn(blob_sink.context, hash, record.payload) catch |err| {
210
+ return self.fail(@errorName(err));
211
+ };
212
+ journaled.image_blob_hash = hash;
213
+ journaled.image_blob_len = record.payload.len;
214
+ journaled.payload = "";
215
+ }
216
+ const payload = journal.encodeEffect(journaled, &self.effect_buffer) catch {
192
217
  return self.fail("an effect result exceeded max_session_record_bytes");
193
218
  };
194
219
  self.writeRecord(.effect, payload);
@@ -28,9 +28,11 @@
28
28
 
29
29
  const std = @import("std");
30
30
  const canvas = @import("canvas");
31
+ const canvas_limits = @import("canvas_limits.zig");
31
32
  const automation_protocol = @import("../automation/protocol.zig");
32
33
  const core = @import("core.zig");
33
34
  const journal = @import("session_journal.zig");
35
+ const session_blobs = @import("session_blobs.zig");
34
36
 
35
37
  pub const ReplayError = error{
36
38
  /// The journal was recorded on a different platform; v1 replay is
@@ -46,6 +48,22 @@ pub const ReplayError = error{
46
48
  /// The app registered no replay hook (`App.replay_fn`), but the
47
49
  /// journal carries effect results that need one.
48
50
  ReplayUnsupportedApp,
51
+ /// The journal references a session blob (an image record's source
52
+ /// bytes) but no blob source was provided, the blob is missing, or
53
+ /// its bytes fail their content hash — the journal directory was
54
+ /// moved without its `blobs/`, or the store was damaged.
55
+ ReplayMissingBlob,
56
+ /// A record's fields contradict each other in a way the recorder
57
+ /// can never produce (an image record claiming `.loaded` with a
58
+ /// zero-length blob: the recorder journals `.loaded` only after the
59
+ /// bytes decoded and registered, and empty bytes cannot decode; or
60
+ /// decoded dimensions the canvas registry would never have accepted
61
+ /// — zero or over-budget on `.loaded`, nonzero on any other
62
+ /// outcome) — the journal is damaged or hand-edited.
63
+ /// `JournalCorrupt` is the structural sibling (payloads that fail
64
+ /// to decode at all); this class is for records that decode fine
65
+ /// but lie.
66
+ ReplayDamagedRecord,
49
67
  };
50
68
 
51
69
  /// Bounded mismatch detail (first N are kept; the count keeps counting).
@@ -68,6 +86,11 @@ pub const ReplayOptions = struct {
68
86
  /// Refuse a journal recorded on another platform (the v1 bar).
69
87
  /// Tests recording under the null platform disable this.
70
88
  require_same_platform: bool = true,
89
+ /// Where journal records' out-of-line payloads resolve from (the
90
+ /// `blobs/` directory beside the journal — see session_blobs.zig).
91
+ /// Only consulted when a record references a blob; a journal
92
+ /// without image records replays fine with none.
93
+ blobs: ?session_blobs.SessionBlobSource = null,
71
94
  };
72
95
 
73
96
  pub const ReplayReport = struct {
@@ -152,28 +175,109 @@ pub fn replaySession(
152
175
  try runtime.dispatchPlatformEvent(app, event);
153
176
  report.events_replayed += 1;
154
177
  },
155
- .effect => |effect| {
178
+ .effect => |effect_record| {
179
+ var effect = effect_record;
180
+ // A `.loaded` image record ALWAYS names source bytes:
181
+ // the recorder journals `.loaded` only after those
182
+ // exact bytes decoded and registered (a failed decode
183
+ // rewrites the outcome before it journals, and empty
184
+ // bytes cannot decode), so a zero-length blob here is
185
+ // journal damage, not a session shape. Refuse before
186
+ // any skip/feed decision — resolving blobs only for
187
+ // records that claim bytes would otherwise let the
188
+ // damaged record sail past the blob-integrity gate and
189
+ // deliver a pixel-less "loaded" the recording never
190
+ // produced.
191
+ if (effect.kind == .image and effect.image_outcome == .loaded and effect.image_blob_len == 0) {
192
+ std.debug.print(
193
+ "replay refused after event {d}: image record for id {d} claims .loaded with a zero-length blob - a recorded .loaded always carries its source bytes, so the journal is damaged or hand-edited; re-record the session\n",
194
+ .{ report.events_replayed, effect.key },
195
+ );
196
+ return error.ReplayDamagedRecord;
197
+ }
198
+ // Decoded dimensions obey the recorder the same way: a
199
+ // live `.loaded` journals only after the canvas registry
200
+ // accepted the pixels (nonzero width and height, and
201
+ // width * height * 4 bytes within
202
+ // `max_registered_canvas_image_pixel_bytes` — the same
203
+ // bound `registerCanvasImage` enforces), and every other
204
+ // outcome journals 0x0. Refuse out-of-bound dims HERE:
205
+ // the fed values flow verbatim into the app's Msg — and,
206
+ // on the TS core host, through `@intCast` into
207
+ // i64-classed arm fields, a safety panic on absurd
208
+ // values — before any decode could disprove them.
209
+ // `status` needs no twin gate: it is u16 at the journal
210
+ // codec, in the completion entry, and in
211
+ // `EffectImageResult`, so every downstream cast
212
+ // (i64/f64 arm fields) holds by type.
213
+ if (effect.kind == .image and imageDimsDamaged(effect)) {
214
+ std.debug.print(
215
+ "replay refused after event {d}: image record for id {d} claims .{s} with dimensions {d}x{d} - a recorded .loaded always carries nonzero decoded dimensions within the registered-image pixel budget and every other outcome records 0x0, so the journal is damaged or hand-edited; re-record the session\n",
216
+ .{ report.events_replayed, effect.key, @tagName(effect.image_outcome), effect.image_width, effect.image_height },
217
+ );
218
+ return error.ReplayDamagedRecord;
219
+ }
156
220
  if (effectRegeneratesUnderReplay(effect)) {
157
221
  report.effects_skipped += 1;
158
222
  continue;
159
223
  }
160
- app.replayControl(.{ .feed = effect }) catch |err| switch (err) {
161
- error.EffectNotFound => {
162
- std.debug.print(
163
- "replay diverged after event {d}: journaled {s} result for effect key {d} has no matching pending request - the replayed updates issued different effects than the recording (nondeterminism outside the effect boundary?)\n",
164
- .{ report.events_replayed, @tagName(effect.kind), effect.key },
165
- );
166
- return error.ReplayEffectDivergence;
167
- },
168
- error.ReplayUnsupported => {
224
+ // Resolve out-of-line payloads: an image record's
225
+ // source bytes come from the blob store, verified
226
+ // against the journaled address and length, and feed
227
+ // as `payload` — the recorded bytes, byte-identical,
228
+ // no network. The scratch lives until the feed below
229
+ // returns (the fed bytes are copied into the stub
230
+ // executor's slot buffer).
231
+ var blob_scratch: ?[]u8 = null;
232
+ defer if (blob_scratch) |scratch| std.heap.page_allocator.free(scratch);
233
+ if (effect.kind == .image and effect.image_blob_len > 0) {
234
+ const bytes = resolveBlob(effect, options.blobs, &blob_scratch) catch |err| {
169
235
  std.debug.print(
170
- "replay refused: the journal carries effect results but this app registered no replay hook (App.replay_fn - UiApp wires it automatically)\n",
171
- .{},
236
+ "replay refused after event {d}: image record for id {d} references blob {s} ({d} bytes) that could not be resolved ({s}) - replay needs the journal's blobs/ directory beside it\n",
237
+ .{ report.events_replayed, effect.key, session_blobs.hexName(effect.image_blob_hash), effect.image_blob_len, @errorName(err) },
172
238
  );
173
- return error.ReplayUnsupportedApp;
174
- },
175
- else => return err,
176
- };
239
+ return error.ReplayMissingBlob;
240
+ };
241
+ effect.payload = bytes;
242
+ }
243
+ // Feed with back-pressure: results journal in delivery
244
+ // order, so one recorded drain pass can carry more
245
+ // results than the completion queue holds (a live
246
+ // recording's workers keep refilling the queue while
247
+ // the loop drains it). A feed that reports the queue
248
+ // full drains the loop through the same `.wake`
249
+ // dispatch the platform delivers live — the parked
250
+ // request keeps its bytes, and delivery stays
251
+ // queue-ordered — then feeds once more. That one drain
252
+ // empties the whole queue, so a second refusal is a
253
+ // real fault and propagates.
254
+ var drained_for_room = false;
255
+ feed: while (true) {
256
+ app.replayControl(.{ .feed = effect }) catch |err| switch (err) {
257
+ error.EffectQueueFull => {
258
+ if (drained_for_room) return err;
259
+ drained_for_room = true;
260
+ try runtime.dispatchPlatformEvent(app, .wake);
261
+ continue :feed;
262
+ },
263
+ error.EffectNotFound => {
264
+ std.debug.print(
265
+ "replay diverged after event {d}: journaled {s} result for effect key {d} has no matching pending request - the replayed updates issued different effects than the recording (nondeterminism outside the effect boundary?)\n",
266
+ .{ report.events_replayed, @tagName(effect.kind), effect.key },
267
+ );
268
+ return error.ReplayEffectDivergence;
269
+ },
270
+ error.ReplayUnsupported => {
271
+ std.debug.print(
272
+ "replay refused: the journal carries effect results but this app registered no replay hook (App.replay_fn - UiApp wires it automatically)\n",
273
+ .{},
274
+ );
275
+ return error.ReplayUnsupportedApp;
276
+ },
277
+ else => return err,
278
+ };
279
+ break :feed;
280
+ }
177
281
  report.effects_fed += 1;
178
282
  },
179
283
  .checkpoint => |checkpoint| {
@@ -209,6 +313,43 @@ pub fn replaySession(
209
313
  return report;
210
314
  }
211
315
 
316
+ /// Read one journal-referenced blob into fresh scratch (handed to the
317
+ /// caller through `scratch_out` for freeing) and verify it against the
318
+ /// record: present, exact length, and hashing to its address — the
319
+ /// same hostile-input honesty the journal reader keeps.
320
+ fn resolveBlob(
321
+ record: journal.EffectResultRecord,
322
+ blobs: ?session_blobs.SessionBlobSource,
323
+ scratch_out: *?[]u8,
324
+ ) anyerror![]const u8 {
325
+ const blob_source = blobs orelse return error.BlobMissing;
326
+ if (record.image_blob_len > session_blobs.max_blob_bytes) return error.BlobOverBudget;
327
+ const blob_len: usize = @intCast(record.image_blob_len);
328
+ // One spare byte proves the stored blob is not LONGER than the
329
+ // record claims (the source reads at most the buffer).
330
+ const scratch = try std.heap.page_allocator.alloc(u8, blob_len + 1);
331
+ scratch_out.* = scratch;
332
+ const bytes = try blob_source.read_fn(blob_source.context, record.image_blob_hash, scratch);
333
+ if (bytes.len != blob_len) return error.BlobCorrupt;
334
+ return bytes;
335
+ }
336
+
337
+ /// Whether an image record's journaled dimensions contradict what the
338
+ /// recorder can produce (see the gate in `replaySession`): `.loaded`
339
+ /// carries nonzero width and height whose RGBA8 byte size — computed
340
+ /// overflow-checked, a hand-edited product that wraps u64 is damage,
341
+ /// not a small image — fits `registerCanvasImage`'s per-image slot
342
+ /// bound; every other outcome carries 0x0.
343
+ fn imageDimsDamaged(record: journal.EffectResultRecord) bool {
344
+ if (record.image_outcome != .loaded) {
345
+ return record.image_width != 0 or record.image_height != 0;
346
+ }
347
+ if (record.image_width == 0 or record.image_height == 0) return true;
348
+ const pixels = std.math.mul(u64, record.image_width, record.image_height) catch return true;
349
+ const pixel_bytes = std.math.mul(u64, pixels, 4) catch return true;
350
+ return pixel_bytes > canvas_limits.max_registered_canvas_image_pixel_bytes;
351
+ }
352
+
212
353
  /// Journaled results that regenerate deterministically from the
213
354
  /// replayed updates themselves — feeding them would double-deliver:
214
355
  /// rejections (the same over-capacity/duplicate-key validation refuses
@@ -229,6 +370,17 @@ fn effectRegeneratesUnderReplay(record: journal.EffectResultRecord) bool {
229
370
  // Host-request rejections mark themselves with the exit reason
230
371
  // (the `.host` record encoding); host answers must be fed.
231
372
  .host => record.exit_reason == .rejected,
373
+ // Image `.rejected` terminals journal from BOTH sides of the
374
+ // executor seam, so the outcome alone is not provenance: only
375
+ // loop-side validation refusals — which the replayed
376
+ // `loadImage` regenerates — mark themselves with the exit
377
+ // reason (the `.host` records' convention, above). Worker-side
378
+ // rejections (a URL that passes the loop's scheme check but
379
+ // cannot become a request, an executor that could not start a
380
+ // cancelable load) keep `.exited`: the fake executor parks
381
+ // those requests, so the journaled record is the ONLY terminal
382
+ // and must be fed like every other worker truth.
383
+ .image => record.exit_reason == .rejected,
232
384
  // Launch-env deliveries are exactly what must NOT regenerate:
233
385
  // the recorded values feed the replayed envMsgs dispatch so the
234
386
  // replay launch's environment is never consulted.