@native-sdk/cli 0.5.2 → 0.5.3

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 (82) hide show
  1. package/build.zig +41 -0
  2. package/package.json +9 -9
  3. package/packages/core/package-lock.json +2 -2
  4. package/packages/core/package.json +1 -1
  5. package/packages/core/sdk/events.ts +39 -2
  6. package/packages/core/src/checker.ts +1 -1
  7. package/packages/core/src/emitter.ts +39 -3
  8. package/packages/core/src/infer.ts +53 -7
  9. package/skill-data/automation/SKILL.md +7 -4
  10. package/skill-data/core/references/app-model-runtime.md +3 -0
  11. package/skill-data/native-ui/SKILL.md +1 -0
  12. package/src/app_runner/root.zig +25 -0
  13. package/src/automation/protocol.zig +20 -1
  14. package/src/embed/host.zig +27 -0
  15. package/src/embed/tests.zig +69 -0
  16. package/src/embed/ui_host.zig +4 -0
  17. package/src/platform/macos/appkit_host.h +11 -0
  18. package/src/platform/macos/appkit_host.m +130 -0
  19. package/src/platform/macos/root.zig +34 -0
  20. package/src/platform/null_platform_tests.zig +39 -0
  21. package/src/platform/root.zig +3 -0
  22. package/src/platform/types.zig +109 -4
  23. package/src/primitives/canvas/chart.zig +7 -7
  24. package/src/primitives/canvas/chart_tests.zig +66 -0
  25. package/src/primitives/canvas/commands.zig +48 -0
  26. package/src/primitives/canvas/events.zig +161 -0
  27. package/src/primitives/canvas/font_ttf.zig +155 -8
  28. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  29. package/src/primitives/canvas/reference.zig +67 -8
  30. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  31. package/src/primitives/canvas/root.zig +25 -0
  32. package/src/primitives/canvas/ui.zig +35 -2
  33. package/src/primitives/canvas/ui_markup.zig +24 -0
  34. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  35. package/src/primitives/canvas/ui_markup_compiled.zig +40 -3
  36. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  37. package/src/primitives/canvas/ui_markup_contract.zig +9 -0
  38. package/src/primitives/canvas/ui_markup_contract_tests.zig +24 -0
  39. package/src/primitives/canvas/ui_markup_tests.zig +26 -0
  40. package/src/primitives/canvas/ui_markup_view.zig +53 -4
  41. package/src/primitives/canvas/ui_markup_view_tests.zig +73 -2
  42. package/src/primitives/canvas/ui_schema.zig +16 -0
  43. package/src/primitives/canvas/ui_schema_tests.zig +10 -11
  44. package/src/primitives/canvas/ui_tests.zig +31 -0
  45. package/src/primitives/canvas/vector.zig +258 -141
  46. package/src/primitives/canvas/widget_access.zig +1 -1
  47. package/src/primitives/canvas/widget_builtin_tests.zig +129 -0
  48. package/src/primitives/canvas/widget_layout.zig +9 -4
  49. package/src/primitives/canvas/widget_render.zig +78 -40
  50. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  51. package/src/primitives/canvas/widget_semantics.zig +6 -1
  52. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  53. package/src/primitives/canvas/widget_text_input.zig +118 -10
  54. package/src/primitives/canvas/widgets.zig +16 -0
  55. package/src/root.zig +5 -0
  56. package/src/runtime/api.zig +13 -0
  57. package/src/runtime/automation_commands.zig +33 -0
  58. package/src/runtime/automation_widget_dispatch.zig +64 -0
  59. package/src/runtime/canvas_font_tests.zig +272 -3
  60. package/src/runtime/canvas_fonts.zig +60 -20
  61. package/src/runtime/canvas_frame_helpers.zig +15 -0
  62. package/src/runtime/canvas_image_tests.zig +26 -0
  63. package/src/runtime/canvas_images.zig +33 -7
  64. package/src/runtime/canvas_limits.zig +44 -8
  65. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  66. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  67. package/src/runtime/canvas_widget_events.zig +24 -4
  68. package/src/runtime/canvas_widget_runtime.zig +24 -7
  69. package/src/runtime/canvas_widget_state.zig +6 -1
  70. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  71. package/src/runtime/core.zig +98 -6
  72. package/src/runtime/flow.zig +27 -0
  73. package/src/runtime/gpu_surface_events.zig +7 -0
  74. package/src/runtime/media_surface.zig +726 -0
  75. package/src/runtime/media_surface_tests.zig +1476 -0
  76. package/src/runtime/root.zig +9 -0
  77. package/src/runtime/session_journal.zig +30 -3
  78. package/src/runtime/session_tests.zig +126 -4
  79. package/src/runtime/tests.zig +1 -0
  80. package/src/runtime/ts_ui_app.zig +56 -0
  81. package/src/runtime/ui_app.zig +58 -0
  82. package/src/runtime/ui_app_tests.zig +334 -0
@@ -44,9 +44,37 @@ const render_fingerprints = @import("render_fingerprints.zig");
44
44
  const vector = @import("vector.zig");
45
45
  const font_ttf = @import("font_ttf.zig");
46
46
 
47
- /// Element budget for one glyph outline: the bundled face's densest
48
- /// glyphs stay well under this (maxp: 96 points per simple glyph).
49
- const reference_glyph_path_capacity: usize = 256;
47
+ /// Element budget for one glyph outline, derived from the parser's
48
+ /// glyph budgets so every glyph a parsed face maps fits: a contour
49
+ /// emits at most one element per point plus a move, a closing quad, and
50
+ /// a close (points + 3*contours), taken over BOTH glyph forms the gate
51
+ /// admits — a simple glyph's maxima and a composite's flattened maxima
52
+ /// (`maxp.maxCompositePoints`/`maxCompositeContours`, which is what
53
+ /// this builder actually receives when a composite renders). The
54
+ /// budgets are currently equal, so the max is 1408 either way; the
55
+ /// derivation keeps capacity honest if they ever diverge. Stack shape:
56
+ /// at 28 B per element this is ~39 KiB in `drawGlyphOutline`; the edge
57
+ /// accumulator below it is the per-thread heap-resident
58
+ /// `vector.GlyphRasterizer` (see `reference_glyph_raster_scratch`), so
59
+ /// the builder is the only glyph raster state on the stack.
60
+ const reference_glyph_path_capacity: usize = @max(
61
+ font_ttf.max_glyph_points + 3 * font_ttf.max_glyph_contours,
62
+ font_ttf.max_composite_points + 3 * font_ttf.max_composite_contours,
63
+ );
64
+
65
+ /// Per-thread rasterizer for glyph fills: `vector.GlyphRasterizer`'s
66
+ /// derived budgets guarantee every outline the font registration gate
67
+ /// admits rasterizes (never a block fallback), which sizes it at
68
+ /// ~508 KiB — a per-thread heap slot behind one TLS pointer (the
69
+ /// lazy_tls pattern), not a stack temporary and not static TLS. Only
70
+ /// threads that ink a glyph through the reference renderer allocate it.
71
+ /// The array carries no default and stays uninitialized, exactly like
72
+ /// the stack `Rasterizer` it replaces; `vector.fillGlyphPath` resets it
73
+ /// per glyph.
74
+ const ReferenceGlyphRasterScratch = struct {
75
+ raster: vector.GlyphRasterizer,
76
+ };
77
+ const reference_glyph_raster_scratch = @import("lazy_tls.zig").LazyTls(ReferenceGlyphRasterScratch);
50
78
 
51
79
  const referenceBlurKernel = reference_blur.referenceBlurKernel;
52
80
  const referenceBlurSampleWithKernel = reference_blur.referenceBlurSampleWithKernel;
@@ -62,6 +90,19 @@ pub const ReferenceImage = struct {
62
90
  width: usize,
63
91
  height: usize,
64
92
  pixels: []const u8,
93
+ /// Precomputed content fingerprint for the GPU cache planner
94
+ /// (`renderImageFingerprintForResource` uses it when nonzero instead
95
+ /// of hashing `pixels` at plan time). Media-surface textures set it
96
+ /// at adoption so a 60 fps producer never pays a full-buffer hash
97
+ /// per planned frame; 0 — every registered canvas image — keeps the
98
+ /// classic hash-the-bytes keying byte-identically.
99
+ content_fingerprint: u64 = 0,
100
+ /// PRESENTATION-ONLY resource: composited by live GPU/packet hosts,
101
+ /// invisible to the deterministic reference renderer (see the
102
+ /// policy comment in `findReferenceImage`). Media-surface textures
103
+ /// ride the image pipeline with this set, so producer output can
104
+ /// never leak into goldens, screenshots, or replay pixel marks.
105
+ presentation_only: bool = false,
65
106
  };
66
107
 
67
108
  /// One runtime-registered font face the reference renderer resolves text
@@ -772,9 +813,12 @@ pub const ReferenceRenderSurface = struct {
772
813
 
773
814
  /// Paint one glyph: the real Geist outline through the vector core
774
815
  /// when the codepoint resolves, the historical block rect otherwise
775
- /// (unmapped codepoints, glyphs beyond the outline budgets, or draws
776
- /// carrying no text bytes). Layout is untouched — the pen position
777
- /// and advance still come from the deterministic estimator.
816
+ /// (unmapped codepoints, glyphs of hostile faces whose `maxp`
817
+ /// under-declares — the per-glyph parse backstops — or draws
818
+ /// carrying no text bytes; never a gate-admitted glyph, whose raster
819
+ /// budgets are derived from the registration gate). Layout is
820
+ /// untouched — the pen position and advance still come from the
821
+ /// deterministic estimator.
778
822
  fn drawGlyphBox(
779
823
  self: ReferenceRenderSurface,
780
824
  command: RenderCommand,
@@ -839,8 +883,14 @@ pub const ReferenceRenderSurface = struct {
839
883
  .coverage_blend = .srgb,
840
884
  };
841
885
  // The outline is already in device space; TrueType interiorness
842
- // is the nonzero rule.
843
- vector.fillPath(
886
+ // is the nonzero rule. The glyph raster budgets are derived from
887
+ // the registration gate's outline budgets, so a gate-admitted
888
+ // face never trips `VectorPathTooComplex` here — the remaining
889
+ // fallback triggers are a clip band wider than
890
+ // `max_raster_width` (surface-shaped, not font-shaped) and
891
+ // nothing else.
892
+ vector.fillGlyphPath(
893
+ &reference_glyph_raster_scratch.get().raster,
844
894
  builder.slice(),
845
895
  Affine.identity(),
846
896
  .nonzero,
@@ -1255,6 +1305,15 @@ fn referenceImagePixelLen(width: usize, height: usize) ?usize {
1255
1305
 
1256
1306
  fn findReferenceImage(images: []const ReferenceImage, id: ImageId) ?ReferenceImage {
1257
1307
  for (images) |image| {
1308
+ // THE REFERENCE-RENDERER MEDIA POLICY: presentation-only
1309
+ // resources (media-surface textures pushed by external
1310
+ // producers) do not exist for the deterministic CPU path. The
1311
+ // draw referencing one skips — exactly like an unregistered id —
1312
+ // so the surface's id-derived placeholder beneath it is what
1313
+ // reference renders, screenshots, replay pixel marks, and
1314
+ // GOLDENS show. Goldens can therefore never depend on producer
1315
+ // output; only live GPU/packet hosts composite the real texture.
1316
+ if (image.presentation_only) continue;
1258
1317
  if (image.id == id) return image;
1259
1318
  }
1260
1319
  return null;
@@ -53,6 +53,14 @@ pub fn renderImageFingerprintForResource(image_id: ImageId, image: ?ReferenceIma
53
53
  var hash = renderImageFingerprint(image_id);
54
54
  hash = resourceHashUsize(hash, value.width);
55
55
  hash = resourceHashUsize(hash, value.height);
56
+ // A precomputed content fingerprint stands in for the pixel bytes:
57
+ // media-surface textures stamp one at adoption so the planner never
58
+ // re-hashes a full video frame per plan. Any content change changes
59
+ // the stamp, so upload/retain/evict keying is untouched; resources
60
+ // without one (every registered canvas image) hash bytes as always.
61
+ if (value.content_fingerprint != 0) {
62
+ return resourceHashU64(hash, value.content_fingerprint);
63
+ }
56
64
  hash = resourceHashBytes(hash, value.pixels);
57
65
  return hash;
58
66
  }
@@ -58,6 +58,28 @@ pub const ObjectId = u64;
58
58
  pub const ImageId = u64;
59
59
  pub const FontId = u64;
60
60
 
61
+ /// Reserved namespace bit for MEDIA-SURFACE textures inside the ImageId
62
+ /// value space: a media surface bound to `surface_id` composites the
63
+ /// texture registered under `surface_id | media_surface_image_id_bit`,
64
+ /// so producer-pushed textures and app-registered canvas images can
65
+ /// never collide in the one flat id space draw commands reference.
66
+ /// Surface ids and registered canvas image ids must both stay BELOW the
67
+ /// bit — `Runtime.acquireMediaSurfaceProducer` and
68
+ /// `Runtime.registerCanvasImage` reject ids with it set, loudly.
69
+ pub const media_surface_image_id_bit: ImageId = 1 << 63;
70
+
71
+ /// The texture image id a media surface's draw command references for a
72
+ /// bound surface id (see `media_surface_image_id_bit`).
73
+ pub fn mediaSurfaceTextureImageId(surface_id: u64) ImageId {
74
+ return surface_id | media_surface_image_id_bit;
75
+ }
76
+
77
+ /// The media surface's deterministic id-derived placeholder color
78
+ /// (widget_render.zig): what the reference renderer — goldens,
79
+ /// screenshots, replay pixel marks — shows for a bound surface, live
80
+ /// texture or not. Exported so tests pin the placeholder policy.
81
+ pub const mediaSurfacePlaceholderColor = @import("widget_render.zig").mediaSurfacePlaceholderColor;
82
+
61
83
  pub const default_sans_font_id: FontId = 1;
62
84
  pub const default_mono_font_id: FontId = 2;
63
85
  // Reserved sans variant ids for inline span styling. The deterministic
@@ -172,6 +194,7 @@ pub const CommandRef = command_model.CommandRef;
172
194
  pub const DiffKind = command_model.DiffKind;
173
195
  pub const DiffChange = command_model.DiffChange;
174
196
  pub const Builder = command_model.Builder;
197
+ pub const max_display_list_text_bytes = command_model.max_display_list_text_bytes;
175
198
 
176
199
  // Canvas render data and cache plans live in `render.zig`; root keeps the public API stable.
177
200
  pub const max_render_state_stack = render_model.max_render_state_stack;
@@ -566,6 +589,8 @@ pub const WidgetInvalidation = event_model.WidgetInvalidation;
566
589
  pub const WidgetClipboardAction = event_model.WidgetClipboardAction;
567
590
  pub const widgetKeyboardClipboardAction = event_model.widgetKeyboardClipboardAction;
568
591
  pub const widgetKeyboardNewlineTextEditEvent = event_model.widgetKeyboardNewlineTextEditEvent;
592
+ pub const widgetKindSingleLineTextEntry = event_model.widgetKindSingleLineTextEntry;
593
+ pub const sanitizedSingleLineTextInputEvent = event_model.sanitizedSingleLineTextInputEvent;
569
594
  pub const widgetKeyboardControlIntent = event_model.widgetKeyboardControlIntent;
570
595
  pub const semanticActions = event_model.semanticActions;
571
596
  pub const widgetSemanticControlIntent = event_model.widgetSemanticControlIntent;
@@ -455,7 +455,12 @@ pub fn Ui(comptime Msg: type) type {
455
455
  /// app registered at runtime (`Runtime.registerCanvasImage`,
456
456
  /// `fx.registerImageBytes`). 0 — the "no image" sentinel —
457
457
  /// keeps the widget on its non-image rendering (an avatar
458
- /// falls back to initials).
458
+ /// falls back to initials). For `media_surface` this same
459
+ /// channel carries the SURFACE id its producer targets
460
+ /// (`Runtime.acquireMediaSurfaceProducer`, markup
461
+ /// `surface={binding}`) — the identical model-owned-u64
462
+ /// shape, one bit of the id space apart (see
463
+ /// `canvas.media_surface_image_id_bit`).
459
464
  image: canvas.ImageId = 0,
460
465
  /// Vector icon name drawn inside icon-bearing controls
461
466
  /// (`button`, `toggle_button`, `icon_button`, `list_item`,
@@ -1170,7 +1175,18 @@ pub fn Ui(comptime Msg: type) type {
1170
1175
  else
1171
1176
  canvas.widgetKeyboardNewlineTextEditEvent(widget.kind, keyboard) orelse keyboard.textEditEvent();
1172
1177
  if (edit) |text_edit| {
1173
- if (self.msgForTextEdit(target_id, text_edit)) |msg| return msg;
1178
+ // Single-line kinds sanitize the edit with the
1179
+ // SAME rule the runtime seam applies before
1180
+ // stamping (strip line breaks; suppress inserts
1181
+ // that strip to nothing), so the fallback
1182
+ // derivation for events that never crossed the
1183
+ // runtime can never feed a model mirror bytes
1184
+ // the retained editor would refuse. Stamped
1185
+ // edits are already sanitized and pass through
1186
+ // untouched.
1187
+ if (canvas.sanitizedSingleLineTextInputEvent(widget.kind, text_edit)) |sanitized| {
1188
+ if (self.msgForTextEdit(target_id, sanitized)) |msg| return msg;
1189
+ }
1174
1190
  }
1175
1191
  }
1176
1192
  return null;
@@ -1726,6 +1742,23 @@ pub fn Ui(comptime Msg: type) type {
1726
1742
  return self.el(.image, options, .{});
1727
1743
  }
1728
1744
 
1745
+ /// The media surface leaf (markup `<media-surface surface={id}>`):
1746
+ /// composites a texture PRODUCED OUTSIDE the widget tree — a
1747
+ /// video decoder, a camera pipeline, an external renderer —
1748
+ /// into the layout like any widget. `options.image` carries the
1749
+ /// SURFACE id the producer targets
1750
+ /// (`Runtime.acquireMediaSurfaceProducer`), a model-owned u64 in
1751
+ /// the ImageId value space; 0 draws nothing (the image-leaf
1752
+ /// convention). Until the first producer frame arrives, live
1753
+ /// hosts show the surface's deterministic id-derived placeholder
1754
+ /// — which is also ALL the reference renderer (goldens,
1755
+ /// screenshots, replay pixel marks) ever shows, because texture
1756
+ /// contents are presentation chrome by policy. Size it like an
1757
+ /// image: definite width/height or flex grow (no intrinsic size).
1758
+ pub fn mediaSurface(self: *Self, options: ElementOptions) Node {
1759
+ return self.el(.media_surface, options, .{});
1760
+ }
1761
+
1729
1762
  /// A built-in vector icon leaf: `name` is one of
1730
1763
  /// `canvas.icons.known_icon_names` (compile error otherwise), so
1731
1764
  /// icon references never rot. Size comes from `options.size` /
@@ -1250,6 +1250,10 @@ pub const tooltip_delay_dependent_attr_message = "tooltip-delay needs anchor on
1250
1250
  pub const avatar_image_message = "image takes one {binding} to a u64 ImageId the app registered at runtime (fx.registerImageBytes) - runtime image ids are model data, not markup literals; 0 renders the initials fallback";
1251
1251
  pub const avatar_image_element_message = "image is only supported on avatar - the other image-bearing widgets (image, icon-button) stay Zig views (ui.image with ElementOptions.image)";
1252
1252
 
1253
+ pub const media_surface_surface_message = "surface takes one {binding} to the u64 surface id a producer targets (runtime.acquireMediaSurfaceProducer) - surface ids are model data, not markup literals; 0 leaves the surface unbound and it draws nothing";
1254
+ pub const media_surface_surface_element_message = "surface is only supported on media-surface - it names the producer rendezvous of the media surface's texture channel; anywhere else it would be silently inert";
1255
+ pub const media_surface_missing_surface_message = "media-surface requires surface={binding} naming the u64 surface id its producer targets - without one the surface can never show anything (dead markup, same policy as icon without name)";
1256
+
1253
1257
  /// The built-in vector icon vocabulary behind `<icon name="..."/>`.
1254
1258
  /// Registry section mirroring `canvas.icons.known_icon_names` (the
1255
1259
  /// comptime-parsed registry; this layer stays std-only); a test in
@@ -2928,6 +2932,12 @@ fn validateNode(document: MarkupDocument, node: MarkupNode, parent_element: ?[]c
2928
2932
  if (node.attr("name") == null) return errorAt(node, icon_missing_name_message);
2929
2933
  if (node.children.len > 0) return errorAt(node.children[0], icon_children_message);
2930
2934
  }
2935
+ if (std.mem.eql(u8, node.name, "media-surface")) {
2936
+ // A media surface without a producer rendezvous can never
2937
+ // show anything: statically dead markup, refused with a
2938
+ // teaching (the icon-without-name policy).
2939
+ if (node.attr("surface") == null) return errorAt(node, media_surface_missing_surface_message);
2940
+ }
2931
2941
  if (std.mem.eql(u8, node.name, "split")) {
2932
2942
  // Exactly two pane children, statically: the divider sits
2933
2943
  // between fixed panes, so conditional/repeated content
@@ -3063,6 +3073,20 @@ fn validateNode(document: MarkupDocument, node: MarkupNode, parent_element: ?[]c
3063
3073
  }
3064
3074
  continue;
3065
3075
  }
3076
+ if (std.mem.eql(u8, attribute.name, "surface")) {
3077
+ // The media-surface producer rendezvous, media-surface
3078
+ // scoped: surface ids are model data a producer
3079
+ // targets, never markup literals (the runtime-image-id
3080
+ // grammar exactly).
3081
+ if (!std.mem.eql(u8, node.name, "media-surface")) {
3082
+ return attrError(node, attribute, media_surface_surface_element_message);
3083
+ }
3084
+ const expression = parseAttrExpression(attribute.value);
3085
+ if (expression == null or expression.? != .binding) {
3086
+ return attrError(node, attribute, media_surface_surface_message);
3087
+ }
3088
+ continue;
3089
+ }
3066
3090
  if (std.mem.eql(u8, attribute.name, "anchor")) {
3067
3091
  // Anchored floating placement, dropdown-menu-scoped:
3068
3092
  // a literal side so the compiled engine resolves it
@@ -152,6 +152,31 @@ test "NSUI round-trips the input-group vocabulary under its fresh codes" {
152
152
  try testing.expectEqual(@as(u16, 63), schema.elementByName("input-group-actions").?.code);
153
153
  }
154
154
 
155
+ test "NSUI round-trips the media surface under its fresh codes" {
156
+ // media-surface and its surface binding serialize like any element —
157
+ // fresh registry codes ride the wire automatically, no schema bump —
158
+ // so a media document survives encode/decode node-for-node.
159
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
160
+ defer arena_state.deinit();
161
+ const arena = arena_state.allocator();
162
+ const source =
163
+ \\<column gap="8">
164
+ \\ <media-surface surface="{preview}" width="320" height="180" label="Camera preview" />
165
+ \\</column>
166
+ ;
167
+ const document = try parseSource(arena, source);
168
+ try testing.expectEqual(@as(?markup.MarkupErrorInfo, null), markup.validate(document));
169
+
170
+ var diagnostic = nsui.CodecDiagnostic{};
171
+ const bytes = try nsui.encode(arena, document, .{}, &diagnostic);
172
+ const decoded = try nsui.decode(arena, bytes, &diagnostic);
173
+ try expectNodesEqual(document.root.?, decoded.root.?);
174
+
175
+ // The wire carries the registry codes, never the names.
176
+ try testing.expectEqual(@as(u16, 66), schema.elementByName("media-surface").?.code);
177
+ try testing.expectEqual(@as(u16, 81), schema.attrByName("surface").?.code);
178
+ }
179
+
155
180
  test "NSUI round-trips the split layout-tween pair under its fresh codes" {
156
181
  // resize-duration/resize-easing serialize like any attribute — fresh
157
182
  // registry codes ride the wire automatically, no schema bump — so a
@@ -1589,6 +1589,8 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
1589
1589
  };
1590
1590
  } else if (comptime std.mem.eql(u8, attribute.name, "image")) {
1591
1591
  applyImageAttr(node, attribute.value, entries, ui, model, scope, options);
1592
+ } else if (comptime std.mem.eql(u8, attribute.name, "surface")) {
1593
+ applySurfaceAttr(node, attribute.value, entries, ui, model, scope, options);
1592
1594
  } else if (comptime std.mem.eql(u8, attribute.name, "name")) {
1593
1595
  // Consumed by the icon branch in buildElement; a
1594
1596
  // compile error on any other element (interpreter and
@@ -1666,8 +1668,35 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
1666
1668
  }
1667
1669
  const path = comptime markup.parseAttrExpression(raw).?.binding;
1668
1670
  comptime requireVariant(pathVariant(node, entries, path, true), &.{.integer}, node, markup.avatar_image_message);
1671
+ // Range-checked before the u64 cast (the interpreter fails
1672
+ // the same way): a signed model field (`image: i64 = -1`)
1673
+ // can deliver a negative — fail the build, never trap.
1669
1674
  options.image = switch (bindingValue(node, entries, path, ui, model, scope, true)) {
1670
- .integer => |int| @intCast(int),
1675
+ .integer => |int| if (int < 0) runtimeFail(canvas.ImageId, ui) else @intCast(int),
1676
+ else => runtimeFail(canvas.ImageId, ui),
1677
+ };
1678
+ }
1679
+
1680
+ /// Comptime mirror of the interpreter's `applySurfaceAttr`:
1681
+ /// `surface="{binding}"` on media-surface resolves to the
1682
+ /// model-owned u64 surface id a producer targets —
1683
+ /// media-surface-only, binding-only, integer-valued, all checked
1684
+ /// at comptime with the interpreter's messages. The id rides
1685
+ /// `options.image` into `Widget.image_id`, the media surface's
1686
+ /// surface-id channel.
1687
+ fn applySurfaceAttr(comptime node: markup.MarkupNode, comptime raw: []const u8, comptime entries: []const ScopeEntry, ui: *Ui, model: *const ModelT, scope: anytype, options: *Ui.ElementOptions) void {
1688
+ comptime {
1689
+ if (!std.mem.eql(u8, node.name, "media-surface")) fail(node, markup.media_surface_surface_element_message);
1690
+ const expression = markup.parseAttrExpression(raw) orelse fail(node, markup.media_surface_surface_message);
1691
+ if (expression != .binding) fail(node, markup.media_surface_surface_message);
1692
+ }
1693
+ const path = comptime markup.parseAttrExpression(raw).?.binding;
1694
+ comptime requireVariant(pathVariant(node, entries, path, true), &.{.integer}, node, markup.media_surface_surface_message);
1695
+ // Range-checked before the u64 cast (the interpreter fails
1696
+ // the same way): a signed model field (`surface: i64 = -1`)
1697
+ // can deliver a negative — fail the build, never trap.
1698
+ options.image = switch (bindingValue(node, entries, path, ui, model, scope, true)) {
1699
+ .integer => |int| if (int < 0) runtimeFail(canvas.ImageId, ui) else @intCast(int),
1671
1700
  else => runtimeFail(canvas.ImageId, ui),
1672
1701
  };
1673
1702
  }
@@ -1778,7 +1807,10 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
1778
1807
 
1779
1808
  fn uiKeyFromValue(value: Value, ui: *Ui) canvas.UiKey {
1780
1809
  return switch (value) {
1781
- .integer => |int| canvas.uiKey(@as(u64, @intCast(int))),
1810
+ // Keys are identity, not quantities: a negative integer
1811
+ // id maps bijectively into the u64 key space (the
1812
+ // interpreter's itemKey/attrKey rule), never a trap.
1813
+ .integer => |int| canvas.uiKey(@as(u64, @bitCast(int))),
1782
1814
  .string => |text| canvas.uiKey(text),
1783
1815
  else => blk: {
1784
1816
  ui.failed = true;
@@ -1977,8 +2009,13 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
1977
2009
  switch (comptime @typeInfo(T)) {
1978
2010
  .int => {
1979
2011
  comptime requireVariant(variant, &.{.integer}, node, "payload type does not match the message");
2012
+ // Range-checked against the payload's own integer
2013
+ // type before the cast (the interpreter fails the
2014
+ // same way): a binding's i64 can deliver a negative
2015
+ // to an unsigned payload or overflow a small one.
2016
+ // Signed payloads keep their negative range.
1980
2017
  return switch (value) {
1981
- .integer => |int| @intCast(int),
2018
+ .integer => |int| if (int < std.math.minInt(T) or int > std.math.maxInt(T)) runtimeFail(T, ui) else @intCast(int),
1982
2019
  else => runtimeFail(T, ui),
1983
2020
  };
1984
2021
  },
@@ -1218,6 +1218,39 @@ test "compiled avatar image binding matches the interpreter and the hand-written
1218
1218
  try testing.expectEqualStrings("CT", fixture.findByText(empty.root, .avatar, "CT").?.text);
1219
1219
  }
1220
1220
 
1221
+ // ------------------------------- negative id bindings fail, never trap
1222
+
1223
+ const AvatarNegativeCompiled = canvas.CompiledMarkupView(fixture.AvatarModel, fixture.AvatarMsg, fixture.avatar_negative_markup_source);
1224
+ const SurfaceUi = fixture.SurfaceUi;
1225
+ const SurfaceCompiled = canvas.CompiledMarkupView(fixture.SurfaceModel, fixture.SurfaceMsg, fixture.surface_markup_source);
1226
+ const SurfaceNegativeCompiled = canvas.CompiledMarkupView(fixture.SurfaceModel, fixture.SurfaceMsg, fixture.surface_negative_markup_source);
1227
+
1228
+ test "compiled avatar and media-surface id bindings refuse negative model values instead of trapping" {
1229
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1230
+ defer arena_state.deinit();
1231
+ const arena = arena_state.allocator();
1232
+
1233
+ // The u64 surface id resolves like the interpreter's.
1234
+ var ok_ui = SurfaceUi.init(arena);
1235
+ const ok_tree = try ok_ui.finalize(SurfaceCompiled.build(&ok_ui, &fixture.SurfaceModel{}));
1236
+ const surface = ok_tree.root.children[0];
1237
+ try testing.expectEqual(canvas.WidgetKind.media_surface, surface.kind);
1238
+ try testing.expectEqual(@as(canvas.ImageId, 5), surface.image_id);
1239
+
1240
+ // A negative i64 binding into either u64 id seam latches the
1241
+ // failed build (the interpreter's teaching error mirrors it), and
1242
+ // finalize surfaces the failure — never an @intCast trap.
1243
+ var avatar_ui = AvatarUi.init(arena);
1244
+ const avatar_node = AvatarNegativeCompiled.build(&avatar_ui, &fixture.AvatarModel{});
1245
+ try testing.expect(avatar_ui.failed);
1246
+ try testing.expectError(error.OutOfMemory, avatar_ui.finalize(avatar_node));
1247
+
1248
+ var surface_ui = SurfaceUi.init(arena);
1249
+ const surface_node = SurfaceNegativeCompiled.build(&surface_ui, &fixture.SurfaceModel{});
1250
+ try testing.expect(surface_ui.failed);
1251
+ try testing.expectError(error.OutOfMemory, surface_ui.finalize(surface_node));
1252
+ }
1253
+
1221
1254
  // ------------------------------------------------------ text wrap parity
1222
1255
 
1223
1256
  const WrapUi = fixture.WrapUi;
@@ -1196,6 +1196,15 @@ const Checker = struct {
1196
1196
  try self.requireAttrKind(node, attribute, resolved.kind, &.{.integer}, markup.avatar_image_message);
1197
1197
  continue;
1198
1198
  }
1199
+ if (std.mem.eql(u8, attribute.name, "surface")) {
1200
+ // Media-surface ids are model integers (engine parity —
1201
+ // the runtime-image-id shape exactly).
1202
+ const expression = markup.parseAttrExpression(attribute.value) orelse continue;
1203
+ if (expression != .binding) continue;
1204
+ const resolved = try self.resolveBinding(node, expression.binding, true);
1205
+ try self.requireAttrKind(node, attribute, resolved.kind, &.{.integer}, markup.media_surface_surface_message);
1206
+ continue;
1207
+ }
1199
1208
  if (std.mem.eql(u8, attribute.name, "icon") or
1200
1209
  (std.mem.eql(u8, attribute.name, "name") and std.mem.eql(u8, node.name, "icon")))
1201
1210
  {
@@ -719,6 +719,30 @@ test "expression type errors name the model field and its Zig type" {
719
719
  try testing.expect(std.mem.indexOf(u8, message, "name: []const u8") != null);
720
720
  }
721
721
 
722
+ test "the media-surface surface binding checks as a model integer" {
723
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
724
+ defer arena_state.deinit();
725
+ const arena = arena_state.allocator();
726
+
727
+ // An integer-producing binding passes — the exact grammar `native
728
+ // check`'s model-aware pass applies to TS and Zig cores alike.
729
+ const good = try parseFixture(arena,
730
+ \\<column>
731
+ \\ <media-surface surface="{count}" label="Preview" />
732
+ \\</column>
733
+ );
734
+ try testing.expectEqual(null, try contractMessage(arena, good, null));
735
+
736
+ // A non-integer binding is refused with the surface teaching.
737
+ const wrong = try parseFixture(arena,
738
+ \\<column>
739
+ \\ <media-surface surface="{name}" label="Preview" />
740
+ \\</column>
741
+ );
742
+ const message = (try contractMessage(arena, wrong, null)).?;
743
+ try testing.expectEqualStrings(markup.media_surface_surface_message, message);
744
+ }
745
+
722
746
  test "app: icon references check against the contract's registered icon list" {
723
747
  var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
724
748
  defer arena_state.deinit();
@@ -698,6 +698,32 @@ test "the avatar image attribute validates as one binding, avatar-only" {
698
698
  }
699
699
  }
700
700
 
701
+ test "the media-surface surface attribute validates as one binding, required, media-surface-only" {
702
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
703
+ defer arena_state.deinit();
704
+ const arena = arena_state.allocator();
705
+
706
+ // One {binding} on media-surface is the whole grammar.
707
+ var parser = markup.Parser.init(arena, "<row>\n <media-surface surface=\"{preview}\" label=\"Preview\" />\n</row>");
708
+ try testing.expectEqual(@as(?markup.MarkupErrorInfo, null), markup.validate(try parser.parse()));
709
+
710
+ const cases = [_]struct { source: []const u8, message: []const u8 }{
711
+ // Surface ids are model data, never markup literals.
712
+ .{ .source = "<row>\n <media-surface surface=\"7\" label=\"Preview\" />\n</row>", .message = markup.media_surface_surface_message },
713
+ .{ .source = "<row>\n <media-surface surface=\"{a == b}\" label=\"Preview\" />\n</row>", .message = markup.media_surface_surface_message },
714
+ // Scoped to media-surface: anywhere else it would be inert.
715
+ .{ .source = "<row>\n <panel surface=\"{preview}\" />\n</row>", .message = markup.media_surface_surface_element_message },
716
+ // ...and required: an unbound surface is statically dead markup.
717
+ .{ .source = "<row>\n <media-surface label=\"Preview\" />\n</row>", .message = markup.media_surface_missing_surface_message },
718
+ };
719
+ for (cases) |case| {
720
+ var case_parser = markup.Parser.init(arena, case.source);
721
+ const info = markup.validate(try case_parser.parse()) orelse return error.TestUnexpectedResult;
722
+ try testing.expectEqualStrings(case.message, info.message);
723
+ try testing.expectEqual(@as(usize, 2), info.line);
724
+ }
725
+ }
726
+
701
727
  test "wrap and issue-link-base validate as vocabulary with teaching errors" {
702
728
  var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
703
729
  defer arena_state.deinit();
@@ -1449,7 +1449,11 @@ pub fn MarkupView(comptime ModelT: type, comptime MsgT: type) type {
1449
1449
  return self.failKey(node, "key does not name a field on the item");
1450
1450
  };
1451
1451
  return switch (value) {
1452
- .integer => |int| canvas.uiKey(@as(u64, @intCast(int))),
1452
+ // Keys are identity, not quantities: a negative integer
1453
+ // id (an i64 database id, a -1 sentinel) is a distinct,
1454
+ // legitimate identity, so it maps bijectively into the
1455
+ // u64 key space instead of trapping in a signed cast.
1456
+ .integer => |int| canvas.uiKey(@as(u64, @bitCast(int))),
1453
1457
  .string => |text| canvas.uiKey(text),
1454
1458
  else => self.failKey(node, "key fields must be integers or strings"),
1455
1459
  };
@@ -1495,6 +1499,10 @@ pub fn MarkupView(comptime ModelT: type, comptime MsgT: type) type {
1495
1499
  try self.applyImageAttr(scope, node, options, attribute);
1496
1500
  continue;
1497
1501
  }
1502
+ if (std.mem.eql(u8, attribute.name, "surface")) {
1503
+ try self.applySurfaceAttr(scope, node, options, attribute);
1504
+ continue;
1505
+ }
1498
1506
  if (std.mem.eql(u8, attribute.name, "name")) {
1499
1507
  // Consumed by the icon branch in buildElement.
1500
1508
  if (!std.mem.eql(u8, node.name, "icon")) {
@@ -1572,12 +1580,42 @@ pub fn MarkupView(comptime ModelT: type, comptime MsgT: type) type {
1572
1580
  const typed = markup.attrTyped(attribute);
1573
1581
  if (typed != .binding) return self.failVoid(node, markup.avatar_image_message);
1574
1582
  const value = try self.evalBinding(scope, node, typed.binding, true);
1583
+ // Range-checked before the u64 cast: expression values are
1584
+ // i64, so a signed model field (`image: i64 = -1`) can
1585
+ // deliver a negative — the teaching failure, never a trap.
1575
1586
  options.image = switch (value) {
1576
- .integer => |int| @intCast(int),
1587
+ .integer => |int| if (int < 0)
1588
+ return self.failVoid(node, markup.avatar_image_message)
1589
+ else
1590
+ @intCast(int),
1577
1591
  else => return self.failVoid(node, markup.avatar_image_message),
1578
1592
  };
1579
1593
  }
1580
1594
 
1595
+ /// `surface="{binding}"` on media-surface: the model-owned u64
1596
+ /// surface id a producer targets — media-surface-only,
1597
+ /// binding-only, integer-valued (the runtime-image-id grammar
1598
+ /// exactly). The id rides `options.image` into
1599
+ /// `Widget.image_id`, the media surface's surface-id channel.
1600
+ fn applySurfaceAttr(self: *Self, scope: *Scope, node: markup.MarkupNode, options: *Ui.ElementOptions, attribute: markup.MarkupAttr) BuildError!void {
1601
+ if (!std.mem.eql(u8, node.name, "media-surface")) {
1602
+ return self.failVoid(node, markup.media_surface_surface_element_message);
1603
+ }
1604
+ const typed = markup.attrTyped(attribute);
1605
+ if (typed != .binding) return self.failVoid(node, markup.media_surface_surface_message);
1606
+ const value = try self.evalBinding(scope, node, typed.binding, true);
1607
+ // Range-checked before the u64 cast: expression values are
1608
+ // i64, so a signed model field (`surface: i64 = -1`) can
1609
+ // deliver a negative — the teaching failure, never a trap.
1610
+ options.image = switch (value) {
1611
+ .integer => |int| if (int < 0)
1612
+ return self.failVoid(node, markup.media_surface_surface_message)
1613
+ else
1614
+ @intCast(int),
1615
+ else => return self.failVoid(node, markup.media_surface_surface_message),
1616
+ };
1617
+ }
1618
+
1581
1619
  /// `icon="save"` on button, toggle-button, list-item, or
1582
1620
  /// menu-item: the same icon value grammar as `<icon name>` — a
1583
1621
  /// built-in literal can never rot silently, app:<name> and one
@@ -1702,7 +1740,9 @@ pub fn MarkupView(comptime ModelT: type, comptime MsgT: type) type {
1702
1740
  fn attrKey(self: *Self, scope: *Scope, node: markup.MarkupNode, attribute: markup.MarkupAttr) BuildError!canvas.UiKey {
1703
1741
  const value = try self.evalAttrExpression(scope, node, attribute);
1704
1742
  return switch (value) {
1705
- .integer => |int| canvas.uiKey(@as(u64, @intCast(int))),
1743
+ // Bijective like itemKey: a negative integer key is a
1744
+ // distinct identity, never a trap.
1745
+ .integer => |int| canvas.uiKey(@as(u64, @bitCast(int))),
1706
1746
  .string => |text| canvas.uiKey(text),
1707
1747
  else => self.failKey(node, "keys must be integers or strings"),
1708
1748
  };
@@ -1806,8 +1846,17 @@ pub fn MarkupView(comptime ModelT: type, comptime MsgT: type) type {
1806
1846
 
1807
1847
  fn coerce(self: *Self, comptime T: type, node: markup.MarkupNode, value: Value) BuildError!T {
1808
1848
  return switch (@typeInfo(T)) {
1849
+ // Range-checked against the payload's own integer type
1850
+ // before the cast (the option-attribute pattern): a
1851
+ // binding's i64 can deliver a negative to an unsigned
1852
+ // payload or overflow a small one — the teaching
1853
+ // failure, never a trap. Signed payloads keep their
1854
+ // negative range (minInt is the honest lower bound).
1809
1855
  .int => switch (value) {
1810
- .integer => |int| @intCast(int),
1856
+ .integer => |int| if (int < std.math.minInt(T) or int > std.math.maxInt(T))
1857
+ self.failCoerce(T, node)
1858
+ else
1859
+ @intCast(int),
1811
1860
  else => self.failCoerce(T, node),
1812
1861
  },
1813
1862
  .float => switch (value) {