@native-sdk/cli 0.5.3 → 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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -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 +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  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 +3187 -264
  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 +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -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
 
@@ -181,6 +181,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
181
181
  | `skeleton`, `spinner` | loading leaves | size `skeleton` with `width`/`height` |
182
182
  | `icon` | vector icon leaf | `name` picks the icon: a bare literal is a curated built-in stroke icon (compile-checked; 49 names: search, plus, x, x-circle, check, check-circle, chevron-up/down/left/right, arrow-up/down/right, menu, panel-left, panel-right, settings, terminal, wrench, trash, edit, copy, external-link, play, pause, skip-back/forward, shuffle, repeat, music, volume, info, alert, download, save, folder, folder-open, file-text, sun, moon, eye, clock, git-pull-request, git-merge, git-branch, circle-dot, archive, refresh-cw, send); `app:<name>` reaches an icon the app registered at boot with `canvas.icons.registerAppIcons` (declare the table as `pub const app_icons` on the app root so `native check` verifies the name against the model contract), and one `{binding}` defers the choice to model data - an unknown resolved name draws the missing-icon fallback (a slashed circle) with a Debug warning naming the value, never a silent gap; tint with `foreground`, size with `width`/`height` |
183
183
  | `media-surface` | media surface leaf | composites a texture produced OUTSIDE the widget tree (video decoder, camera, an external renderer like mpv) into the layout like any widget — clipped, z-ordered, rounded. `surface="{binding}"` (required) binds the model-owned u64 surface id a Zig-tier producer targets (`runtime.acquireMediaSurfaceProducer` pushes RGBA8 frames, latest-wins, paced by the presented-frame clock; 0 = unbound, draws nothing; usable ids are nonzero values below the reserved bit 63). No intrinsic size — give it `width`/`height` or `grow`; display-only (presses fall through); `label` it (pictorial content). Texture contents are presentation chrome: goldens, reference screenshots, and session replay show the deterministic id-derived placeholder, never producer frames |
184
+ | `image` | runtime image leaf | draws a RUNTIME-REGISTERED image by its model-owned u64 ImageId — the id `Cmd.imageLoad` (TS) or `fx.loadImage`/`fx.registerImageBytes` (Zig) registered pixels under. `image="{binding}"` (required) binds a model field/fn; ids are model data, never markup literals, and 0 draws nothing (store the id only when the load reports loaded — see the Images section). No intrinsic size — give it `width`/`height` or `grow`; display-only (presses fall through); `label` it (pictorial content) |
184
185
  | `markdown` | rendered markdown subtree | leaf; `source` is one `{binding}` — see "Markdown in markup" |
185
186
  | `stepper` > `step` | composite stage track | `active="{index}"` (required) derives each step's completed/active/pending state; steps are text leaves (no attributes) joined by connectors; stepper also takes `key`, `global-key`, `label` |
186
187
  | `timeline` > `timeline-item` | composite ledger list | items only inside a timeline (for/if fine); items are leaves — `title` (required), `description`, `meta`, `indicator`, `variant`, `connector="false"` on the last item, `selected`; `on-press` makes the whole item pressable with a trailing chevron |
@@ -188,7 +189,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
188
189
  | `context-menu` | consumed by its parent | right-click menu on its DIRECT parent (a hit target or an element with `on-press`/`on-hold`); metadata, never a flow child. Children: `menu-item`s (`on-press` required, `disabled` optional, no `icon`) and bare `separator`s, with `if`/`else`/`for` around them. Attribute-less; presents natively where the host has a menu presenter, as an anchored surface elsewhere — see "Context menus" |
189
190
  | `input-group` > `textarea` + `input-group-actions` | composite grouped input | the composer shape: ONE bordered field wrapping exactly one `textarea` (first — document order is focus order) plus an optional `input-group-actions` row of controls inside the same border. The group wears the focus ring for its focused descendant and the textarea's own chrome dissolves automatically, so the whole group reads as one field; the textarea keeps its full behavior (`text`, `placeholder`, `on-input`, `on-submit`, `autofocus`). Group takes `label`, `width`, `height`, `min-width`, `grow`, `key`, `global-key`; the actions row takes `gap` and holds ordinary elements (`if`/`else`/`for` work — swap send for stop while streaming) — put a `<spacer grow="1"/>` between leading and trailing controls (`Ui.inputGroup`/`Ui.inputGroupActions` are the Zig-view equivalents) |
190
191
 
191
- Not markup-expressible (deliberately — write these as Zig view functions with `canvas.Ui`): `image` (needs `ImageId` pixel references, runtime-registered — see the Images section), `icon_button` (`<button icon="...">` with empty content is the declarative icon button), `data_grid` (per-column cell templates), `popover`/`menu_surface` (anchored to runtime geometry), `segmented_control` (use `tabs`/`toggle-group`: `<button>` children of `<tabs>` lower to segmented triggers automatically, so the active tab lifts per the house treatment). Charts ARE expressible: `<chart>` with `<series values="{binding}">` children binding model f32 iterables — see the Charts section (`.band` series and dynamic series composition stay with `ui.chart`). Built-in vector icons ARE expressible: `<icon name="search"/>` (closed, compile-checked name set; `Ui.icon` is the Zig-view equivalent). App-authored icons: `canvas.svg_icon.parseComptime(@embedFile("icons/logo.svg"))` parses any SVG in the common 24x24 stroke-icon dialect at comptime; register the parsed table once at boot with `canvas.icons.registerAppIcons(&table)` and draw by name via `ui.appIcon(.{...}, "logo")` or `ElementOptions.icon` — registered names render exactly like built-ins on every draw path. Markup `<icon>`/`<button icon>` stay built-in-only (the compiled engine validates names at comptime, where runtime registrations cannot exist — engine parity). The one image binding markup DOES carry is the avatar's: `<avatar image="{user_image}">CT</avatar>` binds a `u64` ImageId model field/fn (the id is just model data; 0 keeps the initials fallback) — the embedded-asset exclusion stays.
192
+ Not markup-expressible (deliberately — write these as Zig view functions with `canvas.Ui`): `icon_button` (`<button icon="...">` with empty content is the declarative icon button), `data_grid` (per-column cell templates), `popover`/`menu_surface` (anchored to runtime geometry), `segmented_control` (use `tabs`/`toggle-group`: `<button>` children of `<tabs>` lower to segmented triggers automatically, so the active tab lifts per the house treatment). Charts ARE expressible: `<chart>` with `<series values="{binding}">` children binding model f32 iterables — see the Charts section (`.band` series and dynamic series composition stay with `ui.chart`). Built-in vector icons ARE expressible: `<icon name="search"/>` (closed, compile-checked name set; `Ui.icon` is the Zig-view equivalent). App-authored icons: `canvas.svg_icon.parseComptime(@embedFile("icons/logo.svg"))` parses any SVG in the common 24x24 stroke-icon dialect at comptime; register the parsed table once at boot with `canvas.icons.registerAppIcons(&table)` and draw by name via `ui.appIcon(.{...}, "logo")` or `ElementOptions.icon` — registered names render exactly like built-ins on every draw path. Markup `<icon>`/`<button icon>` stay built-in-only (the compiled engine validates names at comptime, where runtime registrations cannot exist — engine parity). Runtime images ARE expressible: `<image image="{cover}" width="120" height="80" label="Cover art"/>` and `<avatar image="{user_image}">CT</avatar>` bind a `u64` ImageId model field/fn (the id is just model data; 0 draws nothing / keeps the initials fallback) — see the Images section; the `image` binding is required on the leaf (an unbound `<image>` is dead markup) and stays avatar+image scoped.
192
193
 
193
194
  ## Attributes
194
195
 
@@ -473,10 +474,12 @@ For `<if test>`, prefer an explicit boolean predicate method over numeric truthi
473
474
 
474
475
  ## Messages
475
476
 
476
- `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.
477
478
 
478
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`).
479
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
+
480
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.
481
484
 
482
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.
@@ -736,6 +739,40 @@ pub const Msg = union(enum) {
736
739
 
737
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`.
738
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
+
739
776
  Test effects with the fake executor — deterministic, no processes, no network:
740
777
 
741
778
  ```zig
@@ -770,6 +807,7 @@ The `.wake` platform event is how live platforms marshal worker completions onto
770
807
  > - Host commands: `pendingHostAt(index: usize) ?HostRequest` · `feedHostResult(key: u64, ok: bool, bytes: []const u8)`.
771
808
  > - Timers: `pendingTimerAt(index: usize) ?TimerRequest` · `fireTimer(key: u64)` (one-shot slots retire after the fire).
772
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).
773
811
  >
774
812
  > After feeding, drain with `try harness.runtime.dispatchPlatformEvent(app, .wake);` — results become Msgs through the same path live platforms use.
775
813
 
@@ -1064,7 +1102,7 @@ Tests that touch files or clocks get their `Io` from `std.testing.io`. The full
1064
1102
 
1065
1103
  ## Validate without building
1066
1104
 
1067
- `native markup check src/view.native` — instant grammar/structure validation with `file:line:column` errors, including the font-coverage tofu guard: literal text with a codepoint outside the bundled face (⌘, ✓, ⑂, dingbats, CJK) is a teaching error naming the character, because it renders as a tofu box on the reference/screenshot and mobile paths — use a vector icon (`icon=` / `<icon name>`) or plain words. Dynamic strings get the same lesson as a Debug-build `zero_canvas_ui` diagnostic when the view builds. The accessibility lint rides the same pass: unnamed interactive controls and role misuse are errors, unnamed images and redundant labels are warnings (`--strict` promotes).
1105
+ `native markup check src/view.native` — instant grammar/structure validation with `file:line:column` errors, including the font-coverage tofu guard: literal text with a codepoint outside the bundled face (⌘, ✓, ⑂, dingbats, CJK) is a teaching error naming the character, because it renders as a tofu box on the reference/screenshot and mobile paths — register a font that covers it (`UiApp.Options.fonts`) and bind the text from the model (the guard skips `{bindings}`), or use a vector icon (`icon=` / `<icon name>`) or plain words. Dynamic strings get the same lesson as a Debug-build `zero_canvas_ui` diagnostic when the view builds. The accessibility lint rides the same pass: unnamed interactive controls and role misuse are errors, unnamed images and redundant labels are warnings (`--strict` promotes).
1068
1106
 
1069
1107
  The model side checks at check time too: the model-contract step (refreshed by `native test`, or run directly as `zig build model-contract` in an app that owns its build) reflects Model/Msg into `zig-out/model-contract.zon`, and `native check` (or `markup check` run in the app directory) then verifies every binding path, iterable, `key` field, message tag, payload type, and expression type against the app's real surface — did-you-mean over your actual field names, and type errors naming the field's Zig type. It also WARNS on model state and Msg tags no view uses; opt update-only names out with `pub const view_unbound = .{ "next_id" };` on Model or Msg (`--strict` turns the warnings into failures) — state consumed only by a Zig-BUILT view needs `view_unbound` too, because the markup checker cannot see Zig view reads. A stale artifact degrades to grammar-only checking with a loud note ("model contract: not yet built - bindings checked structurally only; run `native test` to enable typed checks"); binding paths and message tags are always re-enforced when the app builds (and on hot reload).
1070
1108
 
@@ -121,7 +121,7 @@ export function update(model: Model, msg: Msg): Model | [Model, Cmd<Msg>] {
121
121
  }
122
122
  ```
123
123
 
124
- The command set (Cmd wire format v2):
124
+ The command set (Cmd wire format v3):
125
125
 
126
126
  - `Cmd.none` — no effects; returning a bare `Model` is sugar for `[model, Cmd.none]`.
127
127
  - `Cmd.persist()` — ask the host to persist the committed model.
@@ -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,16 @@ 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.
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.
160
+
161
+ ### The window verbs
162
+
163
+ The menu-bar lifecycle pair — fire-and-forget, no routing and no result Msg (the window's own frame event carries the resulting state):
164
+
165
+ - `Cmd.showWindow(label)` — un-hide + activate the window with the declared label (a string literal — window labels are declarations, in `app.zon` or a `windows_fn` descriptor): the counterpart to a `close_policy = "hide"` close and the tray "Open" consequence; also restores a minimized window. An unknown label is a no-op.
166
+ - `Cmd.quitApp()` — the graceful terminate, and the tray "Quit" consequence: the host quits through the SAME shutdown path a last-window close takes, so the stop hook runs exactly once and a recording session seals its journal.
157
167
 
158
168
  Commands are constructed inline in the return path and nowhere else (NS1017): never in the Model or a Msg, never in a local, never in a helper. This is what keeps effects inside the dispatch cycle and replay honest.
159
169
 
@@ -64,6 +64,7 @@ pub const RunOptions = struct {
64
64
  .version = manifestStringField("version"),
65
65
  .description = manifestStringField("description"),
66
66
  .has_web_content = manifestHasWebContent(),
67
+ .declares_tray = manifestDeclaresTrayCapability(),
67
68
  .window_title = self.window_title,
68
69
  .bundle_id = self.bundle_id,
69
70
  .icon_path = self.icon_path,
@@ -96,6 +97,9 @@ pub const RunOptions = struct {
96
97
  // enforced floor is host state from the first frame on.
97
98
  info.main_window.min_width = manifestShellStartupMinSize("min_width");
98
99
  info.main_window.min_height = manifestShellStartupMinSize("min_height");
100
+ // Close handling is host window state like the titlebar:
101
+ // the manifest's declaration rides the host create.
102
+ info.main_window.close_policy = manifestShellStartupClosePolicy();
99
103
  }
100
104
  return info;
101
105
  }
@@ -156,6 +160,7 @@ fn manifestWindow(comptime window: anytype, comptime index: usize) native_sdk.Wi
156
160
  .titlebar = windowTitlebarStyle(window),
157
161
  .min_width = windowMinSize(window, "min_width"),
158
162
  .min_height = windowMinSize(window, "min_height"),
163
+ .close_policy = windowClosePolicy(window),
159
164
  };
160
165
  }
161
166
 
@@ -202,6 +207,17 @@ fn manifestShellStartupResizable() bool {
202
207
  return windowBool(shell.windows[0], "resizable", true);
203
208
  }
204
209
 
210
+ /// The startup window's close policy for scene-first apps: app.zon's
211
+ /// `.shell.windows[0].close_policy`. Like the titlebar, close handling
212
+ /// is host window state fixed at create time.
213
+ fn manifestShellStartupClosePolicy() native_sdk.WindowClosePolicy {
214
+ if (comptime !@hasField(@TypeOf(app_manifest), "shell")) return .quit;
215
+ const shell = app_manifest.shell;
216
+ if (comptime !@hasField(@TypeOf(shell), "windows")) return .quit;
217
+ if (comptime shell.windows.len == 0) return .quit;
218
+ return windowClosePolicy(shell.windows[0]);
219
+ }
220
+
205
221
  /// The startup window's content min-size floor for scene-first apps:
206
222
  /// app.zon's `.shell.windows[0].min_width`/`.min_height` (0 = none).
207
223
  fn manifestShellStartupMinSize(comptime field: []const u8) f32 {
@@ -358,6 +374,42 @@ fn windowRestorePolicy(comptime window: anytype) native_sdk.WindowRestorePolicy
358
374
  @compileError("unknown app.zon window restore_policy");
359
375
  }
360
376
 
377
+ /// What the window's close affordance does, from app.zon. `.hide` is
378
+ /// validated against the TARGET platform at comptime: a host with no
379
+ /// affordance to bring a hidden window back (GTK has no status item;
380
+ /// windows without a declared tray, since hiding removes the taskbar
381
+ /// entry and windows has no dock) refuses the declaration here, at
382
+ /// build time, instead of stranding a hidden window at runtime.
383
+ fn windowClosePolicy(comptime window: anytype) native_sdk.WindowClosePolicy {
384
+ if (comptime !@hasField(@TypeOf(window), "close_policy")) return .quit;
385
+ const value = window.close_policy;
386
+ if (comptime std.mem.eql(u8, value, "quit")) return .quit;
387
+ if (comptime std.mem.eql(u8, value, "hide")) {
388
+ if (comptime std.mem.eql(u8, build_options.platform, "linux")) {
389
+ @compileError("app.zon window close_policy \"hide\" is not supported on linux: the GTK host has no status item (tray), so nothing could bring the hidden window back - declare \"quit\" (the default), or scope the .hide declaration to macos/windows builds");
390
+ }
391
+ if (comptime std.mem.eql(u8, build_options.platform, "windows")) {
392
+ if (comptime !manifestDeclaresTrayCapability()) {
393
+ @compileError("app.zon window close_policy \"hide\" on windows requires the \"tray\" capability: hiding removes the taskbar entry and windows has no dock-reopen path, so only a status item (tray) could bring the hidden window back - add \"tray\" to .capabilities and install a status item, or declare \"quit\" (the default); macos needs no capability because the dock reopen path always exists");
394
+ }
395
+ }
396
+ return .hide;
397
+ }
398
+ @compileError("unknown app.zon window close_policy - supported values: \"quit\" (close really closes; the default) and \"hide\" (the menu-bar-app shape: close hides the window and the app keeps running)");
399
+ }
400
+
401
+ /// Whether app.zon declares the "tray" capability — the status item
402
+ /// `.hide` leans on where the OS has no built-in re-show affordance.
403
+ /// Evaluated at comptime over the manifest import, like the web scan.
404
+ fn manifestDeclaresTrayCapability() bool {
405
+ if (comptime !@hasField(@TypeOf(app_manifest), "capabilities")) return false;
406
+ inline for (app_manifest.capabilities) |capability| {
407
+ const name: []const u8 = capability;
408
+ if (comptime std.mem.eql(u8, name, "tray")) return true;
409
+ }
410
+ return false;
411
+ }
412
+
361
413
  fn shortcutModifiers(comptime shortcut: anytype) native_sdk.ShortcutModifiers {
362
414
  const values = if (@hasField(@TypeOf(shortcut), "modifiers")) shortcut.modifiers else .{};
363
415
  var modifiers: native_sdk.ShortcutModifiers = .{};
@@ -405,7 +457,12 @@ fn runNull(app: native_sdk.App, options: RunOptions, init: std.process.Init) !vo
405
457
  var app_info = options.appInfo(&buffers);
406
458
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
407
459
  const session_recorder = setupSessionRecorder(init, app_info);
408
- 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();
409
466
  var trace_sink = StdoutTraceSink{};
410
467
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
411
468
  const log_setup = native_sdk.debug.setupLogging(init.io, init.environ_map, app_info.bundle_id, &log_buffers) catch null;
@@ -463,8 +520,12 @@ fn runMacos(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
463
520
  var app_info = options.appInfo(&buffers);
464
521
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
465
522
  const session_recorder = setupSessionRecorder(init, app_info);
466
- var mac_platform = try native_sdk.platform.macos.MacPlatform.initWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
467
- 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();
468
529
  native_sdk.runtime.launch_timing.lap("host_ready");
469
530
  var trace_sink = StdoutTraceSink{};
470
531
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
@@ -521,8 +582,12 @@ fn runLinux(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
521
582
  var app_info = options.appInfo(&buffers);
522
583
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
523
584
  const session_recorder = setupSessionRecorder(init, app_info);
524
- var linux_platform = try native_sdk.platform.linux.LinuxPlatform.initWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
525
- 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();
526
591
  var trace_sink = StdoutTraceSink{};
527
592
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
528
593
  const log_setup = native_sdk.debug.setupLogging(init.io, init.environ_map, app_info.bundle_id, &log_buffers) catch null;
@@ -577,8 +642,12 @@ fn runWindows(app: native_sdk.App, options: RunOptions, init: std.process.Init)
577
642
  var app_info = options.appInfo(&buffers);
578
643
  const store = prepareStateStore(init.io, init.environ_map, &app_info, &buffers);
579
644
  const session_recorder = setupSessionRecorder(init, app_info);
580
- var windows_platform = try native_sdk.platform.windows.WindowsPlatform.initWithOptions(native_sdk.geometry.SizeF.init(720, 480), webEngine(), app_info);
581
- 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();
582
651
  var trace_sink = StdoutTraceSink{};
583
652
  var log_buffers: native_sdk.debug.LogPathBuffers = .{};
584
653
  const log_setup = native_sdk.debug.setupLogging(init.io, init.environ_map, app_info.bundle_id, &log_buffers) catch null;
@@ -649,6 +718,22 @@ const SessionRecordContext = struct {
649
718
  }
650
719
  };
651
720
 
721
+ /// The blob directory beside a session journal: `blobs/` in the
722
+ /// journal's directory — large effect payloads (an image load's source
723
+ /// bytes) live there content-addressed, referenced from journal
724
+ /// records by hash + length (see session_blobs.zig).
725
+ fn sessionBlobStore(io: std.Io, journal_path: []const u8) ?*native_sdk.runtime.SessionBlobDirStore {
726
+ var dir_buffer: [1024]u8 = undefined;
727
+ const parent = std.fs.path.dirname(journal_path) orelse ".";
728
+ const blob_dir = std.fmt.bufPrint(&dir_buffer, "{s}/blobs", .{parent}) catch return null;
729
+ const store = std.heap.page_allocator.create(native_sdk.runtime.SessionBlobDirStore) catch return null;
730
+ store.* = native_sdk.runtime.SessionBlobDirStore.init(io, blob_dir) catch {
731
+ std.heap.page_allocator.destroy(store);
732
+ return null;
733
+ };
734
+ return store;
735
+ }
736
+
652
737
  /// `NATIVE_SDK_SESSION_RECORD=<path>`: create the journal file and a
653
738
  /// recorder that streams the session into it from the very first
654
739
  /// dispatched event (init determinism needs init-time effect results).
@@ -663,6 +748,7 @@ fn setupSessionRecorder(init: std.process.Init, app_info: native_sdk.AppInfo) ?*
663
748
  context.* = .{ .io = init.io, .file = file };
664
749
  const recorder = std.heap.page_allocator.create(native_sdk.runtime.SessionRecorder) catch return null;
665
750
  recorder.* = native_sdk.runtime.SessionRecorder.init(context.sink());
751
+ if (sessionBlobStore(init.io, path)) |store| recorder.blob_sink = store.sink();
666
752
  recorder.begin(native_sdk.runtime.sessionHeaderNow(
667
753
  native_sdk.runtime.sessionPlatformName(),
668
754
  app_info.app_name,
@@ -703,7 +789,12 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
703
789
 
704
790
  var buffers: StateBuffers = undefined;
705
791
  const app_info = options.appInfo(&buffers);
706
- 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();
707
798
  null_platform.gpu_surfaces = true;
708
799
  var replay_platform = null_platform.platform();
709
800
  // Same-platform replay must mirror the RECORDING host's rendering
@@ -717,6 +808,13 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
717
808
  native_sdk.platform.macos.installHeadlessTextServices(&replay_platform.services);
718
809
  null_platform.gpu_surface_scroll_drivers = true;
719
810
  }
811
+ // Replayed image loads decode too: successful `.image` records feed
812
+ // their journaled blob-store bytes back through decode+register, so
813
+ // the codec must be the recording host's own or every replayed load
814
+ // (and every replayed screenshot with an image in it) drops its
815
+ // pixels. Journaled bytes stay the only input — the codec is a pure
816
+ // bytes-to-pixels call and the network stays absent.
817
+ native_sdk.platform.installHeadlessImageCodec(build_options.platform, null_platform, &replay_platform.services);
720
818
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
721
819
  defer std.heap.page_allocator.destroy(runtime);
722
820
  // Fonts registered at startup and media-surface texture buffers
@@ -742,10 +840,14 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
742
840
  !std.mem.eql(u8, value, "0")
743
841
  else
744
842
  true;
745
- const report = native_sdk.runtime.replaySession(runtime, app, journal_bytes, .{ .verify = verify }) catch |err| {
843
+ const blob_store = sessionBlobStore(init.io, journal_path);
844
+ const report = native_sdk.runtime.replaySession(runtime, app, journal_bytes, .{
845
+ .verify = verify,
846
+ .blobs = if (blob_store) |store| store.source() else null,
847
+ }) catch |err| {
746
848
  switch (err) {
747
849
  error.JournalBadMagic,
748
- error.JournalUnsupportedVersion,
850
+ error.JournalFormatMismatch,
749
851
  error.JournalTruncated,
750
852
  error.JournalCorrupt,
751
853
  error.JournalRecordOverBudget,
@@ -136,6 +136,10 @@ pub fn main(init: std.process.Init) !void {
136
136
  // heap-allocates and constructs in place, so neither rides the stack.
137
137
  const app_state = try Adapter.create(std.heap.page_allocator, .{
138
138
  .audio_cache_dir = audio_cache_dir,
139
+ // Image loads share the same launch-resolved caches directory:
140
+ // the bridge keys the two caches into their own segments
141
+ // (audio/ and images/), so one directory serves both.
142
+ .image_cache_dir = audio_cache_dir,
139
143
  .boot_images = boot_images_buffer[0..boot_image_count],
140
144
  .env_values = env_values_buffer[0..env_value_count],
141
145
  }, options);