@native-sdk/cli 0.5.4 → 0.6.0

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 (149) hide show
  1. package/build/app.zig +50 -1
  2. package/build.zig +534 -3
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +3 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +280 -8
  9. package/packages/core/sdk/core.ts +481 -2
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +599 -3
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +39 -2
  17. package/skill-data/ts-core/SKILL.md +4 -2
  18. package/src/app_runner/root.zig +32 -10
  19. package/src/automation/layout_fingerprint.zig +160 -0
  20. package/src/automation/protocol.zig +82 -33
  21. package/src/automation/root.zig +1 -0
  22. package/src/automation/server.zig +1 -1
  23. package/src/automation/snapshot.zig +68 -9
  24. package/src/automation/watcher.zig +1 -1
  25. package/src/embed/host.zig +5 -0
  26. package/src/embed/ui_host.zig +13 -0
  27. package/src/platform/linux/gtk_host.c +527 -13
  28. package/src/platform/linux/gtk_host.h +25 -0
  29. package/src/platform/linux/root.zig +280 -7
  30. package/src/platform/macos/appkit_host.h +104 -6
  31. package/src/platform/macos/appkit_host.m +1283 -66
  32. package/src/platform/macos/cef_host.mm +110 -1
  33. package/src/platform/macos/root.zig +287 -7
  34. package/src/platform/null_platform.zig +398 -4
  35. package/src/platform/null_platform_tests.zig +35 -0
  36. package/src/platform/root.zig +9 -0
  37. package/src/platform/types.zig +386 -14
  38. package/src/platform/windows/root.zig +298 -9
  39. package/src/platform/windows/webview2_host.cpp +330 -5
  40. package/src/primitives/app_manifest/validation.zig +18 -0
  41. package/src/primitives/canvas/a11y_audit.zig +33 -11
  42. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  43. package/src/primitives/canvas/drawing.zig +25 -0
  44. package/src/primitives/canvas/equality.zig +8 -0
  45. package/src/primitives/canvas/events.zig +103 -16
  46. package/src/primitives/canvas/frame.zig +125 -1
  47. package/src/primitives/canvas/layout_audit.zig +22 -5
  48. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  49. package/src/primitives/canvas/render_tests.zig +13 -10
  50. package/src/primitives/canvas/root.zig +48 -0
  51. package/src/primitives/canvas/terminal_box.zig +471 -0
  52. package/src/primitives/canvas/terminal_grid.zig +978 -0
  53. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  54. package/src/primitives/canvas/test_support.zig +1 -0
  55. package/src/primitives/canvas/tests.zig +1 -0
  56. package/src/primitives/canvas/text_tests.zig +39 -4
  57. package/src/primitives/canvas/tokens.zig +115 -12
  58. package/src/primitives/canvas/ui.zig +524 -5
  59. package/src/primitives/canvas/ui_markup.zig +195 -2
  60. package/src/primitives/canvas/ui_markup_compiled.zig +172 -1
  61. package/src/primitives/canvas/ui_markup_compiled_tests.zig +133 -8
  62. package/src/primitives/canvas/ui_markup_contract.zig +88 -5
  63. package/src/primitives/canvas/ui_markup_contract_tests.zig +39 -1
  64. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  65. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  66. package/src/primitives/canvas/ui_markup_tests.zig +149 -0
  67. package/src/primitives/canvas/ui_markup_view.zig +191 -0
  68. package/src/primitives/canvas/ui_markup_view_tests.zig +403 -19
  69. package/src/primitives/canvas/ui_schema.zig +97 -17
  70. package/src/primitives/canvas/ui_schema_tests.zig +18 -11
  71. package/src/primitives/canvas/ui_tests.zig +141 -9
  72. package/src/primitives/canvas/widget_access.zig +28 -2
  73. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  74. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  75. package/src/primitives/canvas/widget_layout.zig +59 -11
  76. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  77. package/src/primitives/canvas/widget_render.zig +272 -18
  78. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  79. package/src/primitives/canvas/widget_routing.zig +59 -7
  80. package/src/primitives/canvas/widget_runtime.zig +23 -0
  81. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  82. package/src/primitives/canvas/widget_semantics.zig +119 -11
  83. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  84. package/src/primitives/canvas/widget_tree.zig +17 -0
  85. package/src/primitives/canvas/widgets.zig +132 -0
  86. package/src/root.zig +16 -0
  87. package/src/runtime/api.zig +70 -1
  88. package/src/runtime/automation_commands.zig +20 -1
  89. package/src/runtime/automation_snapshot.zig +25 -1
  90. package/src/runtime/automation_widget_dispatch.zig +73 -8
  91. package/src/runtime/bridge_payload.zig +1 -0
  92. package/src/runtime/canvas_frame.zig +62 -7
  93. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  94. package/src/runtime/canvas_frame_helpers.zig +190 -1
  95. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  96. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  97. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  98. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  99. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  100. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  101. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  102. package/src/runtime/canvas_widget_display.zig +1 -1
  103. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  104. package/src/runtime/canvas_widget_events.zig +240 -24
  105. package/src/runtime/canvas_widget_runtime.zig +213 -29
  106. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  107. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  108. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  109. package/src/runtime/canvas_widget_state.zig +6 -0
  110. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  111. package/src/runtime/core.zig +73 -2
  112. package/src/runtime/effects.zig +6389 -54
  113. package/src/runtime/effects_channel_tests.zig +3519 -0
  114. package/src/runtime/effects_pty_tests.zig +1362 -0
  115. package/src/runtime/effects_tests.zig +14 -9
  116. package/src/runtime/effects_video_tests.zig +3609 -0
  117. package/src/runtime/flow.zig +25 -4
  118. package/src/runtime/gpu_surface_events.zig +473 -13
  119. package/src/runtime/media_surface.zig +116 -11
  120. package/src/runtime/media_surface_tests.zig +61 -0
  121. package/src/runtime/pty.zig +1252 -0
  122. package/src/runtime/pty_windows.zig +1780 -0
  123. package/src/runtime/root.zig +25 -0
  124. package/src/runtime/runtime_event_tests.zig +20 -1
  125. package/src/runtime/session_journal.zig +367 -61
  126. package/src/runtime/session_record.zig +16 -0
  127. package/src/runtime/session_replay.zig +395 -11
  128. package/src/runtime/session_tests.zig +109 -15
  129. package/src/runtime/terminal_session.zig +1569 -0
  130. package/src/runtime/terminal_session_tests.zig +450 -0
  131. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  132. package/src/runtime/terminal_vt_stub.zig +13 -0
  133. package/src/runtime/tests.zig +6 -0
  134. package/src/runtime/ts_core_host.zig +980 -140
  135. package/src/runtime/ts_core_host_tests.zig +1059 -1
  136. package/src/runtime/ts_ui_app.zig +16 -5
  137. package/src/runtime/ui_app.zig +2333 -63
  138. package/src/runtime/ui_app_tests.zig +3171 -744
  139. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  140. package/src/runtime/ui_app_window_tests.zig +268 -0
  141. package/src/runtime/view.zig +190 -2
  142. package/src/runtime/view_widget_scroll.zig +218 -68
  143. package/src/runtime/view_widget_text.zig +11 -2
  144. package/src/runtime/view_widget_tree.zig +111 -3
  145. package/src/runtime/window_storage.zig +45 -2
  146. package/src/runtime/window_view_runtime.zig +34 -2
  147. package/src/runtime/window_views.zig +1 -0
  148. package/src/terminal_session_tests_root.zig +15 -0
  149. package/src/tooling/templates.zig +25 -7
@@ -234,11 +234,20 @@ export class TypedAst {
234
234
 
235
235
  /// Union members of a discriminated union type node, with the discriminant
236
236
  /// literal of each member for the given tag property. Returns null when the
237
- /// node is not a union of object types each carrying a literal tag.
237
+ /// node is not a union of object types each carrying a literal tag. A bare
238
+ /// object literal whose tag property is a string LITERAL type is the
239
+ /// singleton case of the same shape (`type Msg = { kind: "inc" }` is a
240
+ /// one-arm tagged union, never a record holding a textual `kind`).
238
241
  discriminatedUnionMembers(node: tsImpl.TypeNode, tagName: string): UnionMemberInfo[] | null {
239
- if (!tsImpl.isUnionTypeNode(node)) return null;
242
+ const singleton = !tsImpl.isUnionTypeNode(node);
243
+ const memberNodes: readonly tsImpl.TypeNode[] = tsImpl.isUnionTypeNode(node)
244
+ ? node.types
245
+ : tsImpl.isTypeLiteralNode(node)
246
+ ? [node]
247
+ : [];
248
+ if (memberNodes.length === 0) return null;
240
249
  const members: UnionMemberInfo[] = [];
241
- for (const member of node.types) {
250
+ for (const member of memberNodes) {
242
251
  if (!tsImpl.isTypeLiteralNode(member)) return null;
243
252
  let tag: string | null = null;
244
253
  const fields: PropInfo[] = [];
@@ -246,16 +255,32 @@ export class TypedAst {
246
255
  if (!tsImpl.isPropertySignature(prop) || !prop.name || !tsImpl.isIdentifier(prop.name)) return null;
247
256
  const name = prop.name.text;
248
257
  if (name === tagName) {
258
+ // An optional tag is no discriminant: the source permits the
259
+ // untagged value while the projected union would demand the
260
+ // arm, so the shape is not this one.
261
+ if (prop.questionToken) return null;
249
262
  if (!prop.type) return null;
263
+ // The SINGLETON case claims the union reading only for a
264
+ // syntactic literal tag (`kind: "inc"`): a record whose
265
+ // `kind` field merely RESOLVES to one literal (an aliased
266
+ // member type) is a record with a tag-named field, not a
267
+ // one-arm union.
268
+ if (singleton && !(tsImpl.isLiteralTypeNode(prop.type) && tsImpl.isStringLiteral(prop.type.literal))) {
269
+ return null;
270
+ }
250
271
  const t = this.checker.getTypeFromTypeNode(prop.type);
251
272
  const value = this.literalValue(t);
252
273
  if (typeof value !== "string") return null;
253
274
  tag = value;
254
275
  continue;
255
276
  }
277
+ // An optional payload property has no native slot: the source
278
+ // permits the absent member while the emitted arm would demand
279
+ // it, so the shape is not this one (spell absence as `| null`).
280
+ if (prop.questionToken) return null;
256
281
  fields.push({
257
282
  name,
258
- optional: prop.questionToken !== undefined,
283
+ optional: false,
259
284
  readonly: hasReadonlyModifier(prop),
260
285
  typeNode: prop.type,
261
286
  declaration: prop,
@@ -306,6 +331,28 @@ export class TypedAst {
306
331
  return out;
307
332
  }
308
333
 
334
+ /// Properties of an object-literal type alias body, in declaration
335
+ /// order — null unless every member is a plain record property (an
336
+ /// identifier-named, annotated, non-optional property signature), so
337
+ /// a shape this walk cannot carry whole refuses as an unsupported
338
+ /// alias instead of registering a struct with silently missing
339
+ /// fields.
340
+ propsOfTypeLiteral(node: tsImpl.TypeLiteralNode): PropInfo[] | null {
341
+ const out: PropInfo[] = [];
342
+ for (const member of node.members) {
343
+ if (!tsImpl.isPropertySignature(member) || !member.name || !tsImpl.isIdentifier(member.name)) return null;
344
+ if (member.questionToken || !member.type) return null;
345
+ out.push({
346
+ name: member.name.text,
347
+ optional: false,
348
+ readonly: hasReadonlyModifier(member),
349
+ typeNode: member.type,
350
+ declaration: member,
351
+ });
352
+ }
353
+ return out;
354
+ }
355
+
309
356
  /// tsc's own assignability relation — thrown values checked against the
310
357
  /// core's declared error shape (the catch assertion's type node).
311
358
  isAssignableToNode(expr: tsImpl.Expression, typeNode: tsImpl.TypeNode): boolean {
@@ -39,7 +39,7 @@ export interface ZField {
39
39
 
40
40
  export interface StructInfo {
41
41
  readonly name: string;
42
- readonly decl: ts.InterfaceDeclaration | ts.ClassDeclaration;
42
+ readonly decl: ts.InterfaceDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration;
43
43
  /// Filled in the second collection pass (field types may reference types
44
44
  /// declared in any of the core's files, in any order).
45
45
  fields: readonly ZField[];
@@ -265,6 +265,24 @@ export class TypeTable {
265
265
  this.declOrder.push(name);
266
266
  continue;
267
267
  }
268
+ if (ts.isTypeLiteralNode(stmt.type) && this.tast.propsOfTypeLiteral(stmt.type) !== null) {
269
+ // A plain-record object-literal alias is a struct exactly like
270
+ // an interface; the alias FORM is how a contract projection
271
+ // spells a value-stored record (interfaces spell node
272
+ // storage), and the storage itself still comes from the
273
+ // promotion walk. Shapes the plain-record walk cannot carry
274
+ // whole (quoted or optional properties) stay unclassified and
275
+ // refuse at emission instead of losing fields silently.
276
+ this.structs.set(name, {
277
+ name,
278
+ decl: stmt,
279
+ fields: [],
280
+ exported,
281
+ promoted: true, // refined by markPromotions
282
+ });
283
+ this.declOrder.push(name);
284
+ continue;
285
+ }
268
286
  if (ts.isTypeReferenceNode(stmt.type) && ts.isIdentifier(stmt.type.typeName)) {
269
287
  const target = stmt.type.typeName.text;
270
288
  if (target === "Uint8Array") {
@@ -299,6 +317,11 @@ export class TypeTable {
299
317
  info.arms = disc.map((m) => ({ tag: m.tag, fields: m.fields.map((p) => this.fieldOf(p)) }));
300
318
  }
301
319
  }
320
+ const structInfo = this.structs.get(stmt.name.text);
321
+ if (structInfo && structInfo.decl === stmt && ts.isTypeLiteralNode(stmt.type)) {
322
+ const props = this.tast.propsOfTypeLiteral(stmt.type);
323
+ if (props) structInfo.fields = props.map((p) => this.fieldOf(p));
324
+ }
302
325
  }
303
326
  }
304
327
  }
@@ -364,6 +387,16 @@ export class TypeTable {
364
387
  }
365
388
  }
366
389
  }
390
+ // Declaration form pins storage for object-literal aliases: the
391
+ // alias spelling IS the value-storage form (a contract projection
392
+ // spells value records that way; interfaces stay with the
393
+ // reachability walk above), so an alias-declared record keeps its
394
+ // by-value layout however the Model reaches it. The walk still
395
+ // traversed its fields, so interface records nested inside it
396
+ // promote normally.
397
+ for (const info of this.structs.values()) {
398
+ if (ts.isTypeAliasDeclaration(info.decl)) pointerKind.delete(info.name);
399
+ }
367
400
  for (const name of pointerKind) {
368
401
  const info = this.structs.get(name);
369
402
  if (info) info.promoted = false;
@@ -117,7 +117,7 @@ Zero app code: on macOS every non-virtualized `scroll` region — and every wind
117
117
 
118
118
  ### Context menus: one declared menu, platform-decided presentation
119
119
 
120
- Authors write ONE menu; the platform decides how it presents. The default is the real OS context menu — on macOS a right/ctrl-click presents an `NSMenu` at the pointer and the selection dispatches the item's typed `Msg`. On hosts without a native menu presenter (Linux GTK and Windows Win32 today — their popover/`TrackPopupMenu` seams are documented future work), the SAME declared items present automatically as an anchored canvas surface floated against the declaring widget, with the standard anchored-surface behavior (Escape and outside-click dismiss, late z-pass, window clipping). Never two authored menus, never a canvas imitation where the OS menu exists.
120
+ Authors write ONE menu; the platform decides how it presents. The default is the real OS context menu at the pointer — `NSMenu` on macOS, `TrackPopupMenu` on Windows, `GtkPopoverMenu` on Linux — and the selection dispatches the item's typed `Msg`. On hosts without a native menu presenter (the mobile toolkit hosts and embed hosts today), the SAME declared items present automatically as an anchored canvas surface at the click point, with the standard anchored-surface behavior (Escape and outside-click dismiss, late z-pass, window clipping). Never two authored menus, never a canvas imitation where the OS menu exists.
121
121
 
122
122
  Markup declares the menu as a `<context-menu>` element — a DIRECT child of the pressable element whose right-click it answers (a hit target, or an element with a bound `on-press`/`on-hold`). It is metadata, not content: it renders nothing in the row's flow. Children are `menu-item`s (`on-press` required, `disabled` optional, the text content is the label) and bare `<separator/>`s, with `if`/`else`/`for` around them to swap or repeat items — a menu whose items all evaporate at runtime simply declares no menu (the All Notes row pattern). Conditional MENUS are spelled as conditional ITEMS: the `<context-menu>` itself takes no attributes and cannot sit behind a structure tag. No submenus: the platform channel carries flat items (label, enabled, separator) only.
123
123
 
@@ -474,10 +474,12 @@ For `<if test>`, prefer an explicit boolean predicate method over numeric truthi
474
474
 
475
475
  ## Messages
476
476
 
477
- `on-press`, `on-toggle`, `on-change`, `on-submit` (enter in a text field; primary+enter in a textarea, where enter inserts a newline), `on-dismiss` (dismissible surfaces: dialog, drawer, sheet, dropdown-menu — dispatched when Escape or a click outside dismisses the surface, so the model owns the close), and `on-hold` (press-and-hold, see the Pickers section) take `tag` or `tag:{payload}`. The tag must be a variant of your `Msg` union; payload bindings coerce to the variant's payload type: integers, floats, enums (from tag names), `[]const u8`, bool. `on-input` is special: name a `Msg` variant whose payload is `canvas.TextInputEvent` and the runtime delivers each text edit in it. `on-scroll` (the `scroll` element only) is the same shape: name a `Msg` variant whose payload is `canvas.ScrollState` and the runtime delivers the post-scroll state — `offset`, `viewport_extent`, `content_extent`, `maxOffset()` — after every user scroll (wheel, kinetic momentum steps, keyboard, accessibility). In Zig views the constructors are `Ui.inputMsg(.tag)` / `Ui.scrollMsg(.tag)` on `on_input` / `on_scroll`. `on-reach-end` (the `scroll` element only; `on_reach_end` in Zig views, any scroll container including the windowed virtual list) is a plain Msg dispatched when a user scroll comes within one viewport of the content end — the infinite-fetch signal, fired once per approach with hysteresis (re-arms past 1.5 viewports, which appending a batch causes by growing the extent). A programmatic jump to the end fires once and NEVER re-arms while the offset stays near the end — re-arming needs a post-scroll observation at least 1.5 viewports from it.
477
+ `on-press`, `on-toggle`, `on-change`, `on-submit` (enter in a text field; primary+enter in a textarea, where enter inserts a newline), `on-dismiss` (dismissible surfaces: dialog, drawer, sheet, dropdown-menu — dispatched when Escape or a click outside dismisses the surface, so the model owns the close), `on-hold` (press-and-hold, see the Pickers section), and `on-hover-enter`/`on-hover-leave` (the pointer-hover containment pair, below) take `tag` or `tag:{payload}`. The tag must be a variant of your `Msg` union; payload bindings coerce to the variant's payload type: integers, floats, enums (from tag names), `[]const u8`, bool. `on-input` is special: name a `Msg` variant whose payload is `canvas.TextInputEvent` and the runtime delivers each text edit in it. `on-scroll` (the `scroll` element only) is the same shape: name a `Msg` variant whose payload is `canvas.ScrollState` and the runtime delivers the post-scroll state — `offset`, `viewport_extent`, `content_extent`, `maxOffset()` — after every user scroll (wheel, kinetic momentum steps, keyboard, accessibility). In Zig views the constructors are `Ui.inputMsg(.tag)` / `Ui.scrollMsg(.tag)` on `on_input` / `on_scroll`. `on-reach-end` (the `scroll` element only; `on_reach_end` in Zig views, any scroll container including the windowed virtual list) is a plain Msg dispatched when a user scroll comes within one viewport of the content end — the infinite-fetch signal, fired once per approach with hysteresis (re-arms past 1.5 viewports, which appending a batch causes by growing the extent). A programmatic jump to the end fires once and NEVER re-arms while the offset stays near the end — re-arming needs a post-scroll observation at least 1.5 viewports from it.
478
478
 
479
479
  Scroll offsets follow the same mirror discipline as text: the Msg carries the offset the runtime ALREADY applied, so store it in the model and echo it back through the scroll's `value` — the echoed source value equals the runtime offset, which the scroll reconcile rule treats as "unchanged", so rebuilds never stomp live scrolling. `on-scroll` is how long content pages or lazy-loads: keep a bounded window in the model and slide it from `offset` (near-end when `offset + viewport_extent` approaches `content_extent`).
480
480
 
481
+ `on-hover-enter` and `on-hover-leave` (any element; `ElementOptions.on_hover_enter` / `on_hover_leave` in Zig views) are the pointer-hover containment pair — Elm's onMouseEnter/onMouseLeave: enter dispatches once when the pointer enters the element's hit region, leave once when it exits — discrete edges, never per-move, so hover previews, prefetch, and hover cards are ordinary Msgs. Binding either makes the element hover-hittable the way a bound press makes it pressable — but never pressable: clicks fall through, no accessibility action, and NO hover wash (the wash is the visual channel of acting controls; a `quiet_hover` content tile that binds hover stays visually quiet while the model hears it). Nested bound elements track containment independently (entering a bound row inside a bound card never leaves the card); enters fire outermost-first, leaves innermost-first. Every enter is answered by exactly one eventual leave — the leave Msg is captured while the element stands (kept fresh across rebuilds, retained if unbound), so it still arrives when the exit is the element unmounting. Exits resolve exactly like the hover wash: moving off and the pointer leaving the window are direct edges; content scrolling or reflowing out from under a stationary pointer re-hit-tests the last pointer position; a dismissal removing the surface under the pointer delivers that surface's leaves immediately, and whatever it reveals is entered when the model's close rebuild re-hit-tests (pair dismissible surfaces with `on-dismiss`, as always); overlays occlude hover the way they occlude clicks. Mouse/trackpad only — containment advances on hover-phase motion, a pointer floating without contact that touch physically cannot produce, so touch never synthesizes hover and hover-revealed affordances need a second path.
482
+
481
483
  A handler or update error DEGRADES, it does not exit the app: dispatch catches it, records it in a bounded ring (`runtime.dispatchErrors()`, the `error event=... name=...` lines and `dispatch_errors=` count in automation snapshots, and a `dispatch.error` trace record at error level), and the app keeps running. Trace-sink capacity failures likewise never fail dispatch — dropped records are counted (`dropped_trace_records=`), not fatal. Design for it: an arm that can fail should still surface its own status in the model; the error ring is the safety net, not the UX.
482
484
 
483
485
  Presses follow ONE rule: a click lands on the nearest pressable widget under the pointer — plain text, icons, images, badges, and layout containers let it fall through to their closest pressable ancestor, and dragging still selects text. "Pressable" means an interactive kind (button, checkbox, list-item, ...) or ANY element with a bound `on-press`/`on-toggle` — the handler itself makes the element a hit target, so a pressable row is just `<panel on-press="open:{id}">` (or `<row on-press=...>`, `ui.row(.{ .on_press = ... })`) with plain text children: no empty-text overlays, no duplicating the handler onto every text leaf. Nested pressables resolve to the deepest one (a button inside a pressable row wins over the row); editable text fields, scroll containers, and modal surfaces (dialog, drawer, sheet, popover, menus) always claim their own presses, so a click in a field inside a pressable row places the caret instead of activating the row. The value/text handlers (`on-change`, `on-submit`, `on-input`) still only belong on controls — both engines and `markup check` reject them on layout/decoration elements with a teaching error.
@@ -737,6 +739,40 @@ pub const Msg = union(enum) {
737
739
 
738
740
  Audio rules: `event.kind` is explicit — `.loaded` acknowledges a successful load (position ticks and `.completed` follow only after it), `.position` is a coarse honest readout (~500ms cadence — a readout, not a frame clock; drive animations from your model, not from tick density), `.completed` fires exactly once with position pinned to the duration, `.failed` reports an unreadable file with no url fallback, an async decode error, a network failure mid-stream (or offline with a cold cache), or a platform without audio playback (GTK/Win32 today — named unsupported, not half-implemented), `.rejected` reports loop-side validation (path and url both empty, or any string over `max_effect_audio_path_bytes`). `event.buffering` is the stream's honest stall flag — true while an un-paused stream waits for network bytes (local files and cache hits never buffer); show it as its own UI state, distinct from playing and paused. All payload fields are plain data — safe to store in the model, no drain-scratch copying. Pause/stop/seek/volume never echo events (the caller commanded them); seek and volume work mid-stream; volume is remembered across tracks. The streamed bytes cache at `cache_path` — key it by URL hash with `native_sdk.audioCachePath(&buffer, cache_dir, url)` under the app_dirs `.cache` directory (macOS `~/Library/Caches/<app>/audio/`, Linux `$XDG_CACHE_HOME/<app>/audio/`), so clearing the cache is deleting that one directory. The automation snapshot reports playback honestly (`audio key=... state=playing|paused|buffering source=local|cache|stream position_ms=... duration_ms=...`) — an advancing `position_ms` is the automation-visible evidence music is actually playing, and `source=` proves the resolution order. In the fake executor, `pendingAudio()` records the single channel's `key`/`path`/`url`/`cache_path`/`expected_bytes`/`playing`/`volume`, `feedAudioEvent(.position, 1_500, 89_160, true)` feeds any event by hand (draining through the same `.wake` path; `feedAudioEventBuffering` adds the stall flag), and `audioSnapshot()` exposes the mirrors; under the real executor the test harness's null platform is a deterministic fake player — `setAudioDuration(suffix, ms)` seeds durations, `takeAudioLoaded()` / `advanceAudio(delta_ms)` / `stallAudio()` synthesize the platform events a live host would deliver, position never advances on its own, `audio_local_files = false` models the assets-absent machine (local loads answer `AudioSourceNotFound`, which is what sends the cascade to the url), and a streamed track that runs to completion flips into the fake cache so the next play of the same url resolves `.cache`.
739
741
 
742
+ `fx.openChannel` is the external-source seam — the one sanctioned way an app-owned thread (a socket reader, a file watcher, a sampling worker) feeds the UI. Reach for it when the data originates OUTSIDE update and arrives on its own schedule: open a channel under a caller-chosen `u64` key, hand the returned thread-safe `ChannelHandle` to the source thread, and every accepted `handle.post(bytes)` arrives as one `on_event` Msg — no timer polling anywhere, the post itself wakes the loop. Channels are their own fixed table (8, `max_effect_channels`) and consume none of the 16 effect slots, but the key shares the effect families' one key space (a same-key fetch is blocked while the channel lives):
743
+
744
+ ```zig
745
+ pub const Msg = union(enum) {
746
+ sample: native_sdk.EffectChannelEvent, // the fixed payload type
747
+ ...
748
+ };
749
+
750
+ .start => {
751
+ const handle = fx.openChannel(.{
752
+ .key = monitor_key, // echoed in every event
753
+ .on_event = Effects.channelMsg(.sample),
754
+ .max_pending = 8, // staging bound, clamped 1..32 (default 32)
755
+ });
756
+ // Launch the source only for a LIVE handle — under session replay
757
+ // the open parks and handle.live() answers false, so the producer
758
+ // never starts (the journaled events are the whole stream either
759
+ // way). Posting from the source thread is thread-safe and never
760
+ // blocks (given the platform's conforming enqueue-only wake hook —
761
+ // every first-party host; see PlatformServices.wake_fn):
762
+ // handle.post(bytes) answers .accepted, .dropped_full,
763
+ // .dropped_oversized, or .closed.
764
+ if (handle.live()) startSampler(handle);
765
+ },
766
+ .stop => fx.closeChannel(monitor_key),
767
+ .sample => |event| switch (event.kind) {
768
+ .data => model.recordSample(event.bytes), // drain scratch — copy what the model keeps
769
+ .closed => model.noteMonitorStopped(event.dropped_total), // exactly once, final totals aboard
770
+ .rejected => model.noteMonitorUnavailable(), // duplicate live key or no idle slot
771
+ },
772
+ ```
773
+
774
+ Channel rules: `handle.post` answers a four-way `PostResult`, and the producer contract reads directly off it — `.accepted` (exactly one `.data` event delivers on the next drain), `.dropped_full` (transient back-pressure: skip this message and keep producing; the consumer's next drain relieves it), `.dropped_oversized` (a programming error no retry fixes: bound your bytes at `max_effect_channel_bytes`, 4 KiB), `.closed` (the occupancy is over: exit the producer loop for good — the handle is generation-stamped, so posting after close, after the slot was reused, or after runtime teardown is always memory-safe and always `.closed`). The back-pressure contract in one line: refused posts are never silent — they count into the event's `dropped_pending`/`dropped_total` counters and ride the next delivered event, and a refused post never wakes the host, so a producer storming a full stage cannot grow the loop's queue. `post` never blocks its producer given a conforming host wake (the platform's `wake_fn` is contractually a bounded, enqueue-only nudge — every first-party host conforms; see `PlatformServices.wake_fn`), and the runtime holds no channel lock across the wake, so even a violating embedder hook hangs only its own posting thread. The replay story, honestly: channel events journal at the effect boundary, so a recorded session replays the whole stream from the journal and never NEEDS the source — under replay `openChannel` parks the occupancy and returns an inert handle whose every post answers `.closed`. But the opening update re-executes (app code is app code), so a producer launched unconditionally really starts — connects and blocking setup before its first post included — and is only stopped AT that first post; `handle.live()` is the producer-launch check (false for parked replay handles, refused opens, and closed occupancies — advisory only, the post's own answer stays authoritative), so a producer gated on it never starts and replay stays fully offline. `fx.closeChannel(key)` flushes the staged backlog, delivers the one `.closed` terminal, and frees the key at that delivery; `fx.channelHandle(key)` re-resolves the open channel's handle loop-side. See `examples/channel-monitor` for the complete worker-loop pattern, including the wind-down discipline.
775
+
740
776
  Test effects with the fake executor — deterministic, no processes, no network:
741
777
 
742
778
  ```zig
@@ -771,6 +807,7 @@ The `.wake` platform event is how live platforms marshal worker completions onto
771
807
  > - Host commands: `pendingHostAt(index: usize) ?HostRequest` · `feedHostResult(key: u64, ok: bool, bytes: []const u8)`.
772
808
  > - Timers: `pendingTimerAt(index: usize) ?TimerRequest` · `fireTimer(key: u64)` (one-shot slots retire after the fire).
773
809
  > - Audio (one channel): `pendingAudio() ?AudioRequest` · `feedAudioEvent(kind: EffectAudioEventKind, position_ms: u64, duration_ms: u64, playing: bool)` · `feedAudioEventBuffering(kind, position_ms, duration_ms, playing, buffering: bool)` · `feedAudioSpectrum(bands: [32]u8, position_ms: u64, duration_ms: u64)` · `audioSnapshot() AudioSnapshot`.
810
+ > - Channels: `channelHandle(key: u64) ?ChannelHandle` (post from the test exactly as a source thread would — no feed needed for live posts) · `feedChannelEvent(key: u64, kind: EffectChannelEventKind, bytes: []const u8, dropped_pending: u32, dropped_total: u32) error{EffectNotFound, EffectQueueFull}!void` (hand-feeds an event, the replay path's seam).
774
811
  >
775
812
  > After feeding, drain with `try harness.runtime.dispatchPlatformEvent(app, .wake);` — results become Msgs through the same path live platforms use.
776
813
 
@@ -144,9 +144,9 @@ These map directly onto the host's effect engine — files, HTTP, the clipboard,
144
144
 
145
145
  One honesty note on `Cmd.persist()`: it compiles and encodes, but no shipping host implements the persist verb yet, so the checker teaches NS1028 as a WARNING (never failing the build). Persist real state with `Cmd.writeFile` and load it back with `Cmd.readFile` from `initialModel`'s boot command — the pattern every real app uses.
146
146
 
147
- ### The streaming ops: spawn and audio
147
+ ### The streaming ops: spawn, audio, and channels
148
148
 
149
- Two effect families deliver MANY results from one command — a keyed stream the app opens imperatively and drives (this is the opposite of `Sub`: a Sub is declared from the model and the host reconciles it; a stream is a `Cmd` with a lifecycle you cancel or stop). Routing still follows the `Cmd.request` rules: string-literal arm names, shapes checked by tsc and taught by NS1027.
149
+ Three effect families deliver MANY results from one command — a keyed stream the app opens imperatively and drives (this is the opposite of `Sub`: a Sub is declared from the model and the host reconciles it; a stream is a `Cmd` with a lifecycle you cancel or stop). Routing still follows the `Cmd.request` rules: string-literal arm names, shapes checked by tsc and taught by NS1027.
150
150
 
151
151
  - `Cmd.spawn(argv, { key?, stdin?, line?, exit, err })` — run a subprocess, streaming stdout line by line. `argv` is an inline array literal of bytes elements (`[asciiBytes("/bin/ps"), asciiBytes("-axo")]`, at most 16 elements, 2 KiB total; the array shape is NS1029, the bounds NS1030), and `stdin` (optional bytes, ≤ 4 KiB) is written to the child once. Each stdout line dispatches the `line` arm (one `Uint8Array` field) as it arrives, across dispatches; omit `line` to drop lines (an exit-only spawn, e.g. piping stdin to `pbcopy`). Exactly ONE terminal ends the stream: a clean exit dispatches the `exit` arm — one number field carrying the exit code (a non-zero code is still `exit`: the process ran; its failure code is yours to read) — and every other end dispatches `err` with the reason bytes: `signaled`, `cancelled`, `rejected` (a duplicate live key, or dynamic argv/stdin the engine refused), `spawn_failed` (the binary could not start). Lines over the engine's 4 KiB line bound arrive cut.
152
152
  - `Cmd.spawn(argv, { key?, stdin?, collect: true, exit, err })` — the same child, whole stdout buffered instead of streamed (the system-monitor shape: run `ps`, parse the block). No `line` arm (NS1027 teaches the conflict). The `exit` arm is a two-field record — one number field (the exit code) and one `Uint8Array` field (the collected stdout, up to 512 KiB), matched by type like `Cmd.fetch`'s arm. Collected stdout over the bound routes `err` with `truncated` — a cut block never parses as whole.
@@ -154,6 +154,8 @@ Two effect families deliver MANY results from one command — a keyed stream the
154
154
  - `Cmd.audioPlay(key, { path?, url?, cachePath?, expectedBytes? }, { event })` — open the audio event stream. One player is the whole surface, so a new `audioPlay` always REPLACES the current playback (the one key-reuse exception besides `Cmd.request`). The source cascade is the engine's: the local `path` is tried first, a missing file falls through to `url` (streamed progressively, cached at `cachePath` when given, integrity-gated by `expectedBytes` — omitted/0 means unknown size). At least one of `path`/`url` is required (NS1029); each is bytes, at most 1 KiB (NS1030). Prefer OMITTING `cachePath` for URL sources: when the app wiring configures a caches directory (`TsUiApp`'s `audio_cache_dir`), the host derives the conventional content-addressed cache path from the URL itself — your update never builds filesystem paths, and replay re-derives the same path by construction. Pass `cachePath` only to override that convention.
155
155
  - The `event` arm is the one SDK-fixed record shape, six fields matched by NAME: `state` (the `AudioState` string-literal union — import it from `@native-sdk/core/events`, or declare an alias with exactly the members `"loaded" | "position" | "completed" | "failed" | "rejected" | "spectrum"` in any order; the runtime matches members by name), `positionMs: number`, `durationMs: number` (milliseconds; the duration is the player's estimate), `playing: boolean`, `buffering: boolean` (true while a streamed url is stalled waiting for bytes), and `bands: Uint8Array` (the 32 spectrum band magnitudes, 0–255 each, all zeros outside `"spectrum"` events). Every playback event dispatches this arm — `"failed"` (unplayable source, decode/device failure) and `"rejected"` (an empty or over-long source) included, so failure is never silence — until `Cmd.audioStop` closes the stream. `"completed"` fires once at the natural end and does NOT close the stream: starting the next track from it is the idiom.
156
156
  - `Cmd.audioPause(key)` / `Cmd.audioResume(key)` / `Cmd.audioStop(key)` / `Cmd.audioSeek(key, ms)` / `Cmd.audioSetVolume(key, volume)` — fire-and-forget control verbs: no result of their own; their consequences arrive on the event stream (`audioResume` on a dead player reports one `"failed"` event, never silence). A verb whose key names no open stream is a no-op. `audioStop` is the audio stream's close — no events for the key after it (`Cmd.cancel` does not apply to audio). Volume is clamped 0..1 and remembered across tracks; a literal outside 0..1 (or a negative seek literal) stops the build (NS1030).
157
+ - `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb — transpiled cores are single-threaded, so the TS tier opens, closes, and receives while the posting handle lives on the native side (`Effects.channelHandle(key)`). `key` may be any number expression, a positive integer below 2^53 (a certain-to-be-refused literal stops the build, NS1030). The `event` arm is a five-field record matched by NAME: `key` (the channel key echoed verbatim, so concurrent channels sharing one arm stay distinguishable; a key the wire cannot carry exactly echoes 0), `state` (the `ChannelState` union — import it from `@native-sdk/core` or declare an alias with exactly the three members `"data" | "closed" | "rejected"` in any order; checked BOTH directions, since a narrower union would silently drop states the host emits), `bytes` (`Uint8Array` — the post's payload on `"data"` events, empty otherwise), and `droppedPending`/`droppedTotal` (numbers — the honest back-pressure counters: posts the native handle refused since the previous delivered event, and over the channel's whole life; refused posts count, never silence). One channel per key at a time — a duplicate live key dispatches `"rejected"` — and the key shares the engine's effect-key space (a same-key fetch is blocked while the channel lives). No timer polling anywhere: the source wakes the loop itself. Channel events journal at the effect boundary, so recorded sessions replay the whole stream from the journal — the native posting side is never needed at replay (a native producer that consults `ChannelHandle.live()` before launching keeps replay fully offline; one that launches unconditionally is stopped at its first post, which answers `.closed`).
158
+ - `Cmd.channelClose(key)` — close the open channel under the key, if any: staged posts flush, exactly one `"closed"` event (final drop totals aboard) dispatches the event arm, and the key frees. A key with no open channel no-ops.
157
159
  - `Cmd.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the decoded dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). Decode limits are the registered-image limits (16 slots, 1 MiB decoded pixels — avatar/cover scale, not photo scale); the encoded source bound is 1.25 MiB, and over-bound sources fail whole with `"too_large"`, never cut. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
158
160
 
159
161
  ### The window verbs
@@ -457,7 +457,12 @@ fn runNull(app: native_sdk.App, options: RunOptions, init: std.process.Init) !vo
457
457
  var app_info = options.appInfo(&buffers);
458
458
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
459
459
  const session_recorder = setupSessionRecorder(init, app_info);
460
- var null_platform = native_sdk.NullPlatform.initWithOptions(.{}, webEngine(), app_info);
460
+ // Heap wrapper, latch-gated free: worker threads hold this address
461
+ // as the channel wake context and an abandoned wake call may
462
+ // dereference it after this frame unwinds (see
463
+ // `NullPlatform.createWithOptions`/`destroy`).
464
+ const null_platform = try native_sdk.NullPlatform.createWithOptions(.{}, webEngine(), app_info);
465
+ defer null_platform.destroy();
461
466
  var trace_sink = StdoutTraceSink{};
462
467
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
463
468
  const log_setup = native_sdk.debug.setupLogging(init.io, init.environ_map, app_info.bundle_id, &log_buffers) catch null;
@@ -515,8 +520,12 @@ fn runMacos(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
515
520
  var app_info = options.appInfo(&buffers);
516
521
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
517
522
  const session_recorder = setupSessionRecorder(init, app_info);
518
- var mac_platform = try native_sdk.platform.macos.MacPlatform.initWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
519
- defer mac_platform.deinit();
523
+ // Heap wrapper, latch-gated free: worker threads hold this address
524
+ // as the channel wake context and an abandoned wake call may
525
+ // dereference it after this frame unwinds (see
526
+ // `MacPlatform.createWithOptions`/`destroy`).
527
+ const mac_platform = try native_sdk.platform.macos.MacPlatform.createWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
528
+ defer mac_platform.destroy();
520
529
  native_sdk.runtime.launch_timing.lap("host_ready");
521
530
  var trace_sink = StdoutTraceSink{};
522
531
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
@@ -573,8 +582,12 @@ fn runLinux(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
573
582
  var app_info = options.appInfo(&buffers);
574
583
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
575
584
  const session_recorder = setupSessionRecorder(init, app_info);
576
- var linux_platform = try native_sdk.platform.linux.LinuxPlatform.initWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
577
- defer linux_platform.deinit();
585
+ // Heap wrapper, latch-gated free: worker threads hold this address
586
+ // as the channel wake context and an abandoned wake call may
587
+ // dereference it after this frame unwinds (see
588
+ // `LinuxPlatform.createWithOptions`/`destroy`).
589
+ const linux_platform = try native_sdk.platform.linux.LinuxPlatform.createWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
590
+ defer linux_platform.destroy();
578
591
  var trace_sink = StdoutTraceSink{};
579
592
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
580
593
  const log_setup = native_sdk.debug.setupLogging(init.io, init.environ_map, app_info.bundle_id, &log_buffers) catch null;
@@ -629,8 +642,12 @@ fn runWindows(app: native_sdk.App, options: RunOptions, init: std.process.Init)
629
642
  var app_info = options.appInfo(&buffers);
630
643
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
631
644
  const session_recorder = setupSessionRecorder(init, app_info);
632
- var windows_platform = try native_sdk.platform.windows.WindowsPlatform.initWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
633
- defer windows_platform.deinit();
645
+ // Heap wrapper, latch-gated free: worker threads hold this address
646
+ // as the channel wake context and an abandoned wake call may
647
+ // dereference it after this frame unwinds (see
648
+ // `WindowsPlatform.createWithOptions`/`destroy`).
649
+ const windows_platform = try native_sdk.platform.windows.WindowsPlatform.createWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
650
+ defer windows_platform.destroy();
634
651
  var trace_sink = StdoutTraceSink{};
635
652
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
636
653
  const log_setup = native_sdk.debug.setupLogging(init.io, init.environ_map, app_info.bundle_id, &log_buffers) catch null;
@@ -772,7 +789,12 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
772
789
 
773
790
  var buffers: StateBuffers = undefined;
774
791
  const app_info = options.appInfo(&buffers);
775
- var null_platform = native_sdk.NullPlatform.initWithOptions(.{}, webEngine(), app_info);
792
+ // Heap wrapper, latch-gated free: worker threads hold this address
793
+ // as the channel wake context and an abandoned wake call may
794
+ // dereference it after this frame unwinds (see
795
+ // `NullPlatform.createWithOptions`/`destroy`).
796
+ const null_platform = try native_sdk.NullPlatform.createWithOptions(.{}, webEngine(), app_info);
797
+ defer null_platform.destroy();
776
798
  null_platform.gpu_surfaces = true;
777
799
  var replay_platform = null_platform.platform();
778
800
  // Same-platform replay must mirror the RECORDING host's rendering
@@ -792,7 +814,7 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
792
814
  // (and every replayed screenshot with an image in it) drops its
793
815
  // pixels. Journaled bytes stay the only input — the codec is a pure
794
816
  // bytes-to-pixels call and the network stays absent.
795
- native_sdk.platform.installHeadlessImageCodec(build_options.platform, &null_platform, &replay_platform.services);
817
+ native_sdk.platform.installHeadlessImageCodec(build_options.platform, null_platform, &replay_platform.services);
796
818
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
797
819
  defer std.heap.page_allocator.destroy(runtime);
798
820
  // Fonts registered at startup and media-surface texture buffers
@@ -825,7 +847,7 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
825
847
  }) catch |err| {
826
848
  switch (err) {
827
849
  error.JournalBadMagic,
828
- error.JournalUnsupportedVersion,
850
+ error.JournalFormatMismatch,
829
851
  error.JournalTruncated,
830
852
  error.JournalCorrupt,
831
853
  error.JournalRecordOverBudget,
@@ -0,0 +1,160 @@
1
+ //! Comptime layout fingerprints: build identity for wire formats that
2
+ //! never migrate.
3
+ //!
4
+ //! The session journal and the automation dropbox protocol refuse ANY
5
+ //! skew — both sides always rebuild from one checkout, no old shape is
6
+ //! ever read — so an ordered version integer carried no information
7
+ //! ("same or different" is the entire question) while costing two
8
+ //! recurring failures: parallel branches contending for the next
9
+ //! integer, and forgettable bumps. A fingerprint has neither: it is a
10
+ //! Wyhash over a canonical comptime-built DESCRIPTION of the layout
11
+ //! (the ui_schema registry's fingerprint idiom), and because the
12
+ //! description reflects over the actual declared types, a layout change
13
+ //! moves the identity with no manual step.
14
+ //!
15
+ //! `describe` renders a type structurally and deterministically:
16
+ //! integers/floats/bools by name, enums with every field name AND value
17
+ //! (journaled enums ride their declaration-order integers, so a reorder
18
+ //! must move the fingerprint), structs and unions with field names and
19
+ //! recursively-described types in declaration order (a tagged union's
20
+ //! tag enum included, names and values — discriminants are layout when
21
+ //! the tag rides the wire), optionals, arrays with lengths, slices, and
22
+ //! pointers. What reflection cannot see —
23
+ //! hand-written byte layouts inside codecs (bit assignments, chosen
24
+ //! integer widths, framing) — the caller states as deliberate constants
25
+ //! in its description string, with the coupling commented at the codec.
26
+ //!
27
+ //! Fingerprints are combined with a small manual `semantic_epoch` at
28
+ //! each call site: the escape hatch for a change in MEANING that leaves
29
+ //! the bytes identical, which no layout description can see.
30
+
31
+ const std = @import("std");
32
+
33
+ /// Wyhash over a canonical layout description. Stated once so every
34
+ /// fingerprint (and every test perturbing one) agrees on what a
35
+ /// fingerprint is.
36
+ pub fn hash(description: []const u8) u64 {
37
+ return std.hash.Wyhash.hash(0, description);
38
+ }
39
+
40
+ /// A canonical, structural, comptime description of `T`. Two types
41
+ /// describe equal exactly when their declared layouts match — field
42
+ /// names, field order, field types (recursively), enum values, array
43
+ /// lengths. Type NAMES are deliberately not included (a rename that
44
+ /// keeps the shape is not a layout change); field names are (decoders
45
+ /// key meaning off them).
46
+ pub fn describe(comptime T: type) []const u8 {
47
+ comptime {
48
+ @setEvalBranchQuota(200_000);
49
+ switch (@typeInfo(T)) {
50
+ .int, .float => return @typeName(T),
51
+ .bool => return "bool",
52
+ .void => return "void",
53
+ .@"enum" => |info| {
54
+ var out: []const u8 = "enum(" ++ @typeName(info.tag_type) ++ "){";
55
+ for (info.fields) |field| {
56
+ out = out ++ field.name ++ "=" ++ std.fmt.comptimePrint("{d}", .{field.value}) ++ ",";
57
+ }
58
+ return out ++ "}";
59
+ },
60
+ .@"struct" => |info| {
61
+ var out: []const u8 = "struct{";
62
+ for (info.fields) |field| {
63
+ out = out ++ field.name ++ ":" ++ describe(field.type) ++ ",";
64
+ }
65
+ return out ++ "}";
66
+ },
67
+ .@"union" => |info| {
68
+ // A tagged union's discriminant VALUES are layout when
69
+ // the tag rides the wire, so the tag enum (names and
70
+ // values) is part of the description — two unions with
71
+ // identical fields but swapped tag values must never
72
+ // fingerprint equal.
73
+ var out: []const u8 = if (info.tag_type) |tag|
74
+ "union(" ++ describe(tag) ++ "){"
75
+ else
76
+ "union{";
77
+ for (info.fields) |field| {
78
+ out = out ++ field.name ++ ":" ++ describe(field.type) ++ ",";
79
+ }
80
+ return out ++ "}";
81
+ },
82
+ .optional => |info| return "?" ++ describe(info.child),
83
+ .array => |info| return "[" ++ std.fmt.comptimePrint("{d}", .{info.len}) ++ "]" ++ describe(info.child),
84
+ .pointer => |info| switch (info.size) {
85
+ .slice => return "[]" ++ describe(info.child),
86
+ else => return "*" ++ if (info.child == anyopaque) "anyopaque" else describe(info.child),
87
+ },
88
+ .@"opaque" => return @typeName(T),
89
+ else => @compileError("layout fingerprint cannot describe " ++ @typeName(T)),
90
+ }
91
+ }
92
+ }
93
+
94
+ // -------------------------------------------------------------- tests
95
+
96
+ const testing = std.testing;
97
+
98
+ test "describe renders shape, not names" {
99
+ const A = struct { count: u32, label: []const u8 };
100
+ const B = struct { count: u32, label: []const u8 };
101
+ // Same shape, different type name: identical description.
102
+ try testing.expectEqualStrings(comptime describe(A), comptime describe(B));
103
+ try testing.expectEqualStrings("struct{count:u32,label:[]u8,}", comptime describe(A));
104
+ }
105
+
106
+ test "an added field moves the fingerprint with no manual step" {
107
+ // The forgettable-bump killer, pinned: a deliberately-different
108
+ // layout (one extra field) through the same description builder
109
+ // yields a different fingerprint.
110
+ const Base = struct { kind: u8, key: u64, payload: []const u8 };
111
+ const Extended = struct { kind: u8, key: u64, payload: []const u8, dropped: u32 };
112
+ try testing.expect(hash(comptime describe(Base)) != hash(comptime describe(Extended)));
113
+ }
114
+
115
+ test "field renames, reorders, and type changes all move the fingerprint" {
116
+ const Base = struct { width: u32, height: u32 };
117
+ const Renamed = struct { w: u32, height: u32 };
118
+ const Reordered = struct { height: u32, width: u32 };
119
+ const Widened = struct { width: u64, height: u32 };
120
+ const base = hash(comptime describe(Base));
121
+ try testing.expect(base != hash(comptime describe(Renamed)));
122
+ try testing.expect(base != hash(comptime describe(Reordered)));
123
+ try testing.expect(base != hash(comptime describe(Widened)));
124
+ }
125
+
126
+ test "enum reorders move the fingerprint (declaration values ride the wire)" {
127
+ const Forward = enum(u8) { header = 1, event = 2 };
128
+ const Swapped = enum(u8) { header = 2, event = 1 };
129
+ try testing.expect(hash(comptime describe(Forward)) != hash(comptime describe(Swapped)));
130
+ }
131
+
132
+ test "union tag discriminants move the fingerprint" {
133
+ // Identical field names and payload types, swapped tag VALUES: a
134
+ // serialized tag byte would decode as the wrong variant, so the
135
+ // descriptions must differ.
136
+ const TagForward = enum(u8) { data = 1, closed = 2 };
137
+ const TagSwapped = enum(u8) { data = 2, closed = 1 };
138
+ const Forward = union(TagForward) { data: u32, closed: void };
139
+ const Swapped = union(TagSwapped) { data: u32, closed: void };
140
+ try testing.expect(hash(comptime describe(Forward)) != hash(comptime describe(Swapped)));
141
+ try testing.expectEqualStrings(
142
+ "union(enum(u8){data=1,closed=2,}){data:u32,closed:void,}",
143
+ comptime describe(Forward),
144
+ );
145
+ }
146
+
147
+ test "describe reaches through optionals, arrays, slices, and nesting" {
148
+ const Inner = enum(u8) { light, dark };
149
+ const Outer = struct {
150
+ scheme: Inner,
151
+ point: ?struct { x: f32, y: f32 },
152
+ bands: [4]u8,
153
+ paths: []const []const u8,
154
+ handle: ?*anyopaque,
155
+ };
156
+ try testing.expectEqualStrings(
157
+ "struct{scheme:enum(u8){light=0,dark=1,},point:?struct{x:f32,y:f32,},bands:[4]u8,paths:[][]u8,handle:?*anyopaque,}",
158
+ comptime describe(Outer),
159
+ );
160
+ }