@native-sdk/cli 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/build.zig +41 -0
  2. package/package.json +9 -9
  3. package/packages/core/package-lock.json +2 -2
  4. package/packages/core/package.json +1 -1
  5. package/packages/core/sdk/events.ts +39 -2
  6. package/packages/core/src/checker.ts +1 -1
  7. package/packages/core/src/emitter.ts +39 -3
  8. package/packages/core/src/infer.ts +53 -7
  9. package/skill-data/automation/SKILL.md +7 -4
  10. package/skill-data/core/references/app-model-runtime.md +3 -0
  11. package/skill-data/native-ui/SKILL.md +3 -2
  12. package/src/app_runner/root.zig +25 -0
  13. package/src/automation/protocol.zig +20 -1
  14. package/src/embed/host.zig +27 -0
  15. package/src/embed/tests.zig +69 -0
  16. package/src/embed/ui_host.zig +4 -0
  17. package/src/platform/macos/appkit_host.h +11 -0
  18. package/src/platform/macos/appkit_host.m +130 -0
  19. package/src/platform/macos/root.zig +34 -0
  20. package/src/platform/null_platform_tests.zig +39 -0
  21. package/src/platform/root.zig +3 -0
  22. package/src/platform/types.zig +118 -4
  23. package/src/primitives/canvas/chart.zig +7 -7
  24. package/src/primitives/canvas/chart_tests.zig +66 -0
  25. package/src/primitives/canvas/commands.zig +48 -0
  26. package/src/primitives/canvas/events.zig +161 -0
  27. package/src/primitives/canvas/font_ttf.zig +155 -8
  28. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  29. package/src/primitives/canvas/reference.zig +67 -8
  30. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  31. package/src/primitives/canvas/root.zig +26 -0
  32. package/src/primitives/canvas/tokens.zig +170 -7
  33. package/src/primitives/canvas/ui.zig +62 -7
  34. package/src/primitives/canvas/ui_markup.zig +51 -4
  35. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  36. package/src/primitives/canvas/ui_markup_compiled.zig +49 -4
  37. package/src/primitives/canvas/ui_markup_compiled_tests.zig +160 -0
  38. package/src/primitives/canvas/ui_markup_contract.zig +9 -0
  39. package/src/primitives/canvas/ui_markup_contract_tests.zig +24 -0
  40. package/src/primitives/canvas/ui_markup_tests.zig +73 -0
  41. package/src/primitives/canvas/ui_markup_view.zig +63 -5
  42. package/src/primitives/canvas/ui_markup_view_tests.zig +151 -2
  43. package/src/primitives/canvas/ui_schema.zig +31 -1
  44. package/src/primitives/canvas/ui_schema_tests.zig +11 -11
  45. package/src/primitives/canvas/ui_tests.zig +31 -0
  46. package/src/primitives/canvas/vector.zig +258 -141
  47. package/src/primitives/canvas/widget_access.zig +1 -1
  48. package/src/primitives/canvas/widget_builtin_tests.zig +259 -0
  49. package/src/primitives/canvas/widget_layout.zig +13 -5
  50. package/src/primitives/canvas/widget_layout_tests.zig +82 -0
  51. package/src/primitives/canvas/widget_render.zig +78 -40
  52. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  53. package/src/primitives/canvas/widget_semantics.zig +6 -1
  54. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  55. package/src/primitives/canvas/widget_text_input.zig +118 -10
  56. package/src/primitives/canvas/widget_tree.zig +14 -2
  57. package/src/primitives/canvas/widgets.zig +28 -0
  58. package/src/root.zig +5 -0
  59. package/src/runtime/api.zig +13 -0
  60. package/src/runtime/automation_commands.zig +33 -0
  61. package/src/runtime/automation_widget_dispatch.zig +159 -28
  62. package/src/runtime/canvas_font_tests.zig +272 -3
  63. package/src/runtime/canvas_fonts.zig +60 -20
  64. package/src/runtime/canvas_frame.zig +15 -0
  65. package/src/runtime/canvas_frame_helpers.zig +15 -0
  66. package/src/runtime/canvas_image_tests.zig +26 -0
  67. package/src/runtime/canvas_images.zig +33 -7
  68. package/src/runtime/canvas_limits.zig +44 -8
  69. package/src/runtime/canvas_widget_anchored_tests.zig +253 -65
  70. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  71. package/src/runtime/canvas_widget_context_menu.zig +3 -2
  72. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  73. package/src/runtime/canvas_widget_events.zig +1295 -7
  74. package/src/runtime/canvas_widget_floating_tests.zig +2801 -0
  75. package/src/runtime/canvas_widget_runtime.zig +24 -7
  76. package/src/runtime/canvas_widget_scroll_drivers.zig +1 -1
  77. package/src/runtime/canvas_widget_state.zig +88 -6
  78. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  79. package/src/runtime/core.zig +112 -6
  80. package/src/runtime/flow.zig +51 -1
  81. package/src/runtime/gpu_surface_events.zig +51 -5
  82. package/src/runtime/media_surface.zig +726 -0
  83. package/src/runtime/media_surface_tests.zig +1476 -0
  84. package/src/runtime/root.zig +9 -0
  85. package/src/runtime/session_journal.zig +52 -13
  86. package/src/runtime/session_record.zig +166 -0
  87. package/src/runtime/session_tests.zig +575 -0
  88. package/src/runtime/tests.zig +1 -0
  89. package/src/runtime/ts_ui_app.zig +56 -0
  90. package/src/runtime/ui_app.zig +64 -1
  91. package/src/runtime/ui_app_tests.zig +794 -0
  92. package/src/runtime/view.zig +86 -0
  93. package/src/runtime/view_widget_text.zig +18 -1
  94. package/src/runtime/view_widget_tree.zig +339 -20
  95. package/src/runtime/widget_bridge.zig +26 -0
  96. package/src/runtime/window_storage.zig +61 -15
  97. package/src/runtime/window_view_runtime.zig +13 -0
  98. package/src/runtime/window_views.zig +6 -0
package/build.zig CHANGED
@@ -536,6 +536,10 @@ pub fn build(b: *std.Build) void {
536
536
  addFileContainsCheckStep(b, file_contains_checker, test_step, "test-docs-shell-manifest-contracts", "Verify app.zon docs describe shell compatibility window labels", &.{
537
537
  .{ .path = "docs/src/app/app-zon/page.mdx", .pattern = "labels must stay unique across both lists" },
538
538
  });
539
+ addFileContainsCheckStep(b, file_contains_checker, test_step, "test-docs-media-producer-contracts", "Verify the media producer docs' typed callback stays mirrored by the compile-shaped pin in media_surface_tests.zig", &.{
540
+ .{ .path = "docs/src/app/media-producers/page.mdx", .pattern = "producer: media.MediaSurfaceProducer" },
541
+ .{ .path = "src/runtime/media_surface_tests.zig", .pattern = "producer: media.MediaSurfaceProducer" },
542
+ });
539
543
  addFileContainsCheckStep(b, file_contains_checker, test_step, "test-js-view-helper-contracts", "Verify injected view helpers support label-first updates", &.{
540
544
  .{ .path = "src/platform/macos/appkit_host.m", .pattern = "update:function(options,patch)" },
541
545
  .{ .path = "src/platform/macos/cef_host.mm", .pattern = "update:function(options,patch)" },
@@ -636,6 +640,43 @@ pub fn build(b: *std.Build) void {
636
640
  .{ .path = "src/platform/macos/appkit_host.m", .pattern = "- (void)requestRetainedCanvasFrame" },
637
641
  .{ .path = "src/platform/macos/appkit_host.m", .pattern = "[self requestRetainedCanvasFrame];" },
638
642
  });
643
+ addFileContainsCheckStep(b, file_contains_checker, test_step, "test-appkit-pinch-terminal-delta", "Verify the macOS pinch stream forwards a terminal Ended/Cancelled magnification as a change before the end marker", &.{
644
+ // AppKit documents every magnifyWithEvent: as carrying the
645
+ // magnification since the previous event — the terminal one
646
+ // included. The Ended/Cancelled branch must forward a nonzero
647
+ // terminal magnification as PINCH_CHANGE before PINCH_END (zero
648
+ // magnification: end only), or the cumulative product of
649
+ // (1 + delta) diverges from what the OS delivered. Cancelled
650
+ // deliberately shares the path: pinch applies deltas
651
+ // incrementally with no rollback.
652
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "if (phase & (NSEventPhaseEnded | NSEventPhaseCancelled)) {" },
653
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "[self emitPinchChangeForEvent:event];\n [self emitPinchInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_PINCH_END event:event magnification:0];" },
654
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "PINCH_END event:event magnification:0];" },
655
+ });
656
+ addFileContainsCheckStep(b, file_contains_checker, test_step, "test-appkit-pinch-magnification-doctrine", "Verify the macOS host forwards raw NSEvent.magnification as the multiplicative pinch delta (the engine convention), with the per-event floor", &.{
657
+ // The reading of NSEvent.magnification is SETTLED and this step
658
+ // exists to keep it settled: Apple's API-reference prose says
659
+ // "add", Apple's own Event Handling Guide example multiplies,
660
+ // and every browser engine (WebKit, Chromium) treats raw
661
+ // magnification as the multiplicative per-event delta. The
662
+ // doctrine comment at magnifyWithEvent: carries the receipts;
663
+ // these pins hold both the comment and the code to it. Any
664
+ // sum-based "additive normalization" of magnification must
665
+ // change emitPinchChangeForEvent:'s pinned body — and thereby
666
+ // fail this step, on purpose. Re-read the doctrine comment
667
+ // before touching either.
668
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "m_magnification += m_magnification * scaleWithResistance;" },
669
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "pinch_update.scale = event.magnification + 1.0;" },
670
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "Ruling: raw event.magnification IS the multiplicative per-event" },
671
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "Do NOT reintroduce a running-sum" },
672
+ // The raw forwarding, pinned as one body: the only transform
673
+ // between the OS and the wire is the per-event floor (a single
674
+ // magnification at or below -1 would emit a factor <= 0 — a
675
+ // zoom inverted through zero scale, physically impossible).
676
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "static const double NativeSdkPinchMagnificationFloor = -1.0 + 0x1p-10;" },
677
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "return magnification < NativeSdkPinchMagnificationFloor ? NativeSdkPinchMagnificationFloor : magnification;" },
678
+ .{ .path = "src/platform/macos/appkit_host.m", .pattern = "- (void)emitPinchChangeForEvent:(NSEvent *)event {\n const double magnification = NativeSdkClampedPinchMagnification(event.magnification);\n if (magnification == 0) return;\n [self emitPinchInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_PINCH_CHANGE event:event magnification:magnification];\n}" },
679
+ });
639
680
  addFileContainsCheckStep(b, file_contains_checker, test_step, "test-appkit-gpu-input-paces-retained-canvas", "Verify GPU input frame requests are paced to the display interval", &.{
640
681
  .{ .path = "src/platform/macos/appkit_host.m", .pattern = "NativeSdkRetainedFrameIntervalNanoseconds" },
641
682
  .{ .path = "src/platform/macos/appkit_host.m", .pattern = "retainedFrameLastEmitNs" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@native-sdk/cli",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "The Native SDK: the complete toolkit for building native desktop applications — declarative markup, native rendering, WebView surfaces, and OS capabilities",
5
5
  "type": "module",
6
6
  "bin": {
@@ -32,14 +32,14 @@
32
32
  "@typescript/typescript6": "6.0.2"
33
33
  },
34
34
  "optionalDependencies": {
35
- "@native-sdk/cli-darwin-arm64": "0.5.1",
36
- "@native-sdk/cli-darwin-x64": "0.5.1",
37
- "@native-sdk/cli-linux-arm64-gnu": "0.5.1",
38
- "@native-sdk/cli-linux-arm64-musl": "0.5.1",
39
- "@native-sdk/cli-linux-x64-gnu": "0.5.1",
40
- "@native-sdk/cli-linux-x64-musl": "0.5.1",
41
- "@native-sdk/cli-win32-arm64": "0.5.1",
42
- "@native-sdk/cli-win32-x64": "0.5.1"
35
+ "@native-sdk/cli-darwin-arm64": "0.5.3",
36
+ "@native-sdk/cli-darwin-x64": "0.5.3",
37
+ "@native-sdk/cli-linux-arm64-gnu": "0.5.3",
38
+ "@native-sdk/cli-linux-arm64-musl": "0.5.3",
39
+ "@native-sdk/cli-linux-x64-gnu": "0.5.3",
40
+ "@native-sdk/cli-linux-x64-musl": "0.5.3",
41
+ "@native-sdk/cli-win32-arm64": "0.5.3",
42
+ "@native-sdk/cli-win32-x64": "0.5.3"
43
43
  },
44
44
  "repository": {
45
45
  "type": "git",
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@native-sdk/core",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@native-sdk/core",
9
- "version": "0.5.1",
9
+ "version": "0.5.3",
10
10
  "devDependencies": {
11
11
  "@typescript/old": "npm:typescript@6.0.3",
12
12
  "@typescript/typescript6": "6.0.2"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@native-sdk/core",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "The TypeScript authoring tier: the app-core subset, its dev-time transpiler to arena-backed Zig, and the SDK module cores import",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,8 +26,9 @@
26
26
  // - `TextInputEvent`, `ScrollState`: Msg-arm PAYLOAD fields —
27
27
  // `{ kind: "draft_edit"; edit: TextInputEvent }`,
28
28
  // `{ kind: "scrolled"; scroll: ScrollState }`.
29
- // - `FrameEvent`, `KeyEvent`: the wiring channels' parameter records —
30
- // `frameMsg(model, frame: FrameEvent)`, `keyMsg(key: KeyEvent)`.
29
+ // - `FrameEvent`, `KeyEvent`, `PinchEvent`: the wiring channels'
30
+ // parameter records — `frameMsg(model, frame: FrameEvent)`,
31
+ // `keyMsg(key: KeyEvent)`, `pinchMsg(pinch: PinchEvent)`.
31
32
  // - `ColorScheme`, `ChromeInsets`, `ChromeButtons`, `AudioState`: field
32
33
  // types INSIDE the arm records the `appearanceMsg`/`chromeMsg`/audio
33
34
  // routes name (the arms themselves stay inline unions of `kind` plus
@@ -72,6 +73,42 @@ export interface KeyEvent {
72
73
  readonly super: boolean;
73
74
  }
74
75
 
76
+ /// The pinch phase vocabulary — a NAMED begin/change/end alias (the host
77
+ /// matches enum members by name, so this is the `phase` field's type in
78
+ /// `pinchMsg`'s parameter record). A host-cancelled gesture folds into
79
+ /// "end": pinch delivers incremental deltas the app applies as they
80
+ /// arrive, so there is no transient state to roll back. A terminal host
81
+ /// event that still measured a nonzero delta delivers it as a final
82
+ /// "change" before the "end", so the cumulative product always matches
83
+ /// what the OS reported.
84
+ export type PinchPhase = "begin" | "change" | "end";
85
+
86
+ /// The pinch channel's record (`pinchMsg(pinch)`): the trackpad pinch
87
+ /// gesture, phase-explicit. `windowId`/`label` name the source window and
88
+ /// gpu-surface view — `x`/`y` are view-local, so a coordinate without its
89
+ /// view is not a position, and multi-window apps tell pinches apart by
90
+ /// these. `scale` is the magnification DELTA for this event (nonzero
91
+ /// only on "change"), and the delta is MULTIPLICATIVE: the cumulative
92
+ /// gesture scale is the running product of `1 + scale` — apply it
93
+ /// memorylessly, `zoom *= 1 + scale`, no gesture-start bookkeeping. On
94
+ /// macOS this is AppKit's raw per-event `NSEvent.magnification`, which
95
+ /// IS that multiplicative delta per the browser-engine convention, so
96
+ /// the product matches the zoom the same gesture performs in Safari and
97
+ /// Chrome. `x`/`y` is the pointer anchor in view-local canvas
98
+ /// points — the pointer location during the gesture (hosts report gesture
99
+ /// events at the pointer, not at a midpoint between the fingers), so a
100
+ /// zoom can anchor under the cursor. Pinch is a view-global gesture — it
101
+ /// never routes through widgets — so this is the honest home for timeline
102
+ /// and canvas zoom. Only hosts with a pinch source emit it (macOS today).
103
+ export interface PinchEvent {
104
+ readonly windowId: number;
105
+ readonly label: string;
106
+ readonly phase: PinchPhase;
107
+ readonly scale: number;
108
+ readonly x: number;
109
+ readonly y: number;
110
+ }
111
+
75
112
  /// The appearance vocabulary — a NAMED light/dark alias (the host matches
76
113
  /// enum members by name, so this is the `colorScheme` field's type in the
77
114
  /// arm `appearanceMsg` names).
@@ -795,7 +795,7 @@ export class SubsetChecker {
795
795
  /// entry points, but the exports themselves live in the entry module.
796
796
  private static readonly entryOnlyExports = new Set([
797
797
  "update", "initialModel", "subscriptions",
798
- "commandMsg", "keyMsg", "frameMsg", "appearanceMsg", "chromeMsg", "envMsgs",
798
+ "commandMsg", "keyMsg", "frameMsg", "pinchMsg", "appearanceMsg", "chromeMsg", "envMsgs",
799
799
  "viewUnbound",
800
800
  ]);
801
801
 
@@ -1171,7 +1171,7 @@ export class Emitter {
1171
1171
  }
1172
1172
 
1173
1173
  /// Validate the generated-wiring channel exports (`appearanceMsg`,
1174
- /// `chromeMsg`, `frameMsg`, `keyMsg`; `envMsgs` validates during its own
1174
+ /// `chromeMsg`, `frameMsg`, `keyMsg`, `pinchMsg`; `envMsgs` validates during its own
1175
1175
  /// emission and `commandMsg` needs only its fn form): the wiring builds
1176
1176
  /// these host events structurally from the declarations, so a wrong
1177
1177
  /// shape must be a teaching NS1033 at check time — transpile-clean
@@ -1252,7 +1252,7 @@ export class Emitter {
1252
1252
  }
1253
1253
  if (ts.isFunctionDeclaration(stmt) && stmt.name && this.isExportedDecl(stmt)) {
1254
1254
  const name = stmt.name.text;
1255
- if (name !== "frameMsg" && name !== "keyMsg") continue;
1255
+ if (name !== "frameMsg" && name !== "keyMsg" && name !== "pinchMsg") continue;
1256
1256
  const returnsMsgOrNull = ((): boolean => {
1257
1257
  if (!stmt.type) return false;
1258
1258
  const t = this.table.resolveTypeNode(stmt.type);
@@ -1281,7 +1281,7 @@ export class Emitter {
1281
1281
  "NS1033",
1282
1282
  );
1283
1283
  }
1284
- } else {
1284
+ } else if (name === "keyMsg") {
1285
1285
  const paramT = stmt.parameters.length === 1 && stmt.parameters[0].type
1286
1286
  ? this.table.resolveTypeNode(stmt.parameters[0].type!)
1287
1287
  : null;
@@ -1300,6 +1300,42 @@ export class Emitter {
1300
1300
  "NS1033",
1301
1301
  );
1302
1302
  }
1303
+ } else {
1304
+ // pinchMsg: { windowId, label: string,
1305
+ // phase: <named "begin"|"change"|"end" alias>, scale, x, y }
1306
+ // — matched by NAME (the wiring maps the phase enum by
1307
+ // member name and widens the numbers; windowId/label are the
1308
+ // source identity — x/y are view-local, so a coordinate
1309
+ // without its view is not a position).
1310
+ const paramT = stmt.parameters.length === 1 && stmt.parameters[0].type
1311
+ ? this.table.resolveTypeNode(stmt.parameters[0].type!)
1312
+ : null;
1313
+ const fields = paramT ? recordFields(paramT) : null;
1314
+ const phase = fields ? fieldNamed(fields, "phase") : undefined;
1315
+ const phaseEnum = phase && phase.type.k === "enum" ? this.table.enums.get(phase.type.name) : null;
1316
+ const phaseOk =
1317
+ phaseEnum !== null &&
1318
+ phaseEnum !== undefined &&
1319
+ phaseEnum.members.length === 3 &&
1320
+ phaseEnum.members.includes("begin") &&
1321
+ phaseEnum.members.includes("change") &&
1322
+ phaseEnum.members.includes("end");
1323
+ const ok =
1324
+ fields !== null &&
1325
+ fields.length === 6 &&
1326
+ phaseOk &&
1327
+ fieldNamed(fields, "label")?.type.k === "string" &&
1328
+ (["windowId", "scale", "x", "y"] as const).every((n) => {
1329
+ const f = fieldNamed(fields, n);
1330
+ return f !== undefined && isNum(f.type.k);
1331
+ });
1332
+ if (!ok) {
1333
+ this.fail(
1334
+ stmt,
1335
+ '`pinchMsg` takes one `PinchEvent` parameter, exactly `{ windowId: number; label: string; phase: PinchPhase; scale: number; x: number; y: number }` where PinchPhase is a named "begin" | "change" | "end" alias',
1336
+ "NS1033",
1337
+ );
1338
+ }
1303
1339
  }
1304
1340
  }
1305
1341
  }
@@ -23,7 +23,7 @@
23
23
  // into a slot some use forces to be an integer — that is a conflict reported
24
24
  // as a teaching error (NS1016), never a downstream Zig type error.
25
25
 
26
- import { ts, TypedAst } from "./typed_ast.ts";
26
+ import { ts, TypedAst, exportListBindings } from "./typed_ast.ts";
27
27
  import { constFunctionValue } from "./ownership.ts";
28
28
  import { thrownShapeOf } from "./checker.ts";
29
29
  import type { TypeTable } from "./types.ts";
@@ -491,15 +491,61 @@ export class IntInference {
491
491
  markType("Msg");
492
492
  // Only the ENTRY module's exports face the host ABI (the wiring and
493
493
  // markup bind through the entry). An exported function in an imported
494
- // module is an ordinary cross-module call, so proof still applies.
494
+ // module is an ordinary cross-module call, so proof still applies —
495
+ // unless the entry's export list re-exports it, which puts it on the
496
+ // entry surface like any other export.
497
+ //
498
+ // Both export spellings mark: the inline modifier and an un-renamed
499
+ // export list entry (`export { pinchMsg }`) export the DECLARATION
500
+ // itself (the emitter's isExportedDecl seam emits them identically),
501
+ // so boundary classing must see them identically too. Renamed entries
502
+ // stay out on purpose: renamed wiring names never reach inference
503
+ // (the checker fences them, NS1014/NS1047), and a renamed ordinary
504
+ // function keeps its historical classing.
505
+ const entryExportedFns = new Set<ts.FunctionDeclaration>();
495
506
  for (const stmt of this.files[0].statements) {
496
507
  if (ts.isFunctionDeclaration(stmt) && stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
508
+ entryExportedFns.add(stmt);
509
+ }
510
+ }
511
+ for (const b of exportListBindings(this.tast, this.files[0])) {
512
+ if (!b.renamed && b.target && ts.isFunctionDeclaration(b.target)) entryExportedFns.add(b.target);
513
+ }
514
+ for (const stmt of entryExportedFns) {
515
+ for (const p of stmt.parameters) {
516
+ const slot = this.slots.get(p);
517
+ if (slot) {
518
+ slot.external = true;
519
+ slot.hostBoundary = true;
520
+ slot.proven = false;
521
+ }
522
+ }
523
+ // The pinch channel's parameter record is intrinsically
524
+ // fractional: magnification deltas are ~0.01..0.3 per event and
525
+ // the pointer anchor is sub-point, so its number fields are HOST
526
+ // values, never provable integers. Marking them boundary-fed
527
+ // keeps a core's `pinch.scale === 0` comparison from
528
+ // int-claiming the slot (which would round every zoom product
529
+ // to whole numbers); the integer side of such a comparison
530
+ // widens to f64 instead. The loop marks EVERY field of the
531
+ // record, so any field the channel grows (windowId, the source
532
+ // identity, included) is boundary-classed without a new rule.
533
+ // frameMsg/keyMsg records keep their historical by-usage
534
+ // classing.
535
+ if (stmt.name?.text === "pinchMsg") {
497
536
  for (const p of stmt.parameters) {
498
- const slot = this.slots.get(p);
499
- if (slot) {
500
- slot.external = true;
501
- slot.hostBoundary = true;
502
- slot.proven = false;
537
+ if (!p.type) continue;
538
+ const t = this.table.resolveTypeNode(p.type);
539
+ if (t.k !== "struct") continue;
540
+ const struct = this.table.structs.get(t.name);
541
+ if (!struct) continue;
542
+ for (const f of struct.fields) {
543
+ const slot = this.slots.get(f.decl);
544
+ if (slot) {
545
+ slot.external = true;
546
+ slot.hostBoundary = true;
547
+ slot.proven = false;
548
+ }
503
549
  }
504
550
  }
505
551
  }
@@ -71,6 +71,8 @@ native automate widget-drag canvas 4 0.25 0.82
71
71
  native automate widget-wheel canvas 5 18
72
72
  native automate widget-key canvas tab
73
73
  native automate widget-key canvas cmd+c
74
+ native automate widget-pinch canvas 1.5
75
+ native automate widget-pinch canvas 0.5 120 80
74
76
  native automate profile on
75
77
  native automate profile off
76
78
  native automate bridge '{"id":"smoke","command":"native.ping","payload":{"source":"automation"}}'
@@ -113,10 +115,11 @@ Semantics:
113
115
  8. Use `native automate widget-drag <view-label> <widget-id> <start-x-ratio> <end-x-ratio> [start-y-ratio end-y-ratio]` for continuous pointer controls.
114
116
  9. Use `native automate widget-wheel <view-label> <widget-id> <delta-y>` for retained widget scroll input. Wheel targets must be interactive/scrollable widgets — a plain layout column or text node is not a wheel target; aim at the scroll/list widget id from the snapshot. Failures land in the snapshot as named reasons: `error event=automation.widget_wheel name=WheelTargetUnknown|WheelTargetNotInteractive|WheelTargetHasEmptyBounds detail="<command args>"`.
115
117
  10. Use `native automate widget-key <view-label> <key> [text]` for focused retained widget keyboard input. The key accepts modifier chords — `cmd+a`, `cmd+c`, `cmd+v`, `cmd+x`, `ctrl+shift+arrowleft` (`cmd` sets the primary shortcut modifier on every platform) — so select-all/copy/cut/paste and shift-extended selection are drivable; after a copy, widget lines in the snapshot show the live selection as `selection=a..b`, and the copied text lands on the real system clipboard (`pbpaste` on macOS).
116
- 11. Use `native automate screenshot <view-label> [scale]` to capture the named `gpu_surface` view's canvas as `screenshot-<view-label>.png` (the CLI prints the artifact path and waits for the file).
117
- 12. Use `native automate tray-action <item-id>` to select a status-item dropdown row through the same platform event a real menu-bar click emits (command dispatch with source `.tray`). The live tray is visible in `snapshot.txt` as a `tray title="..." items=N` line followed by ` tray-item #id label="..." command="..." enabled=...` rows — the macOS menu bar is outside every window capture, so the snapshot is the only automation evidence the model-driven tray exists, and the `#id` there is what `tray-action` takes. Unknown ids degrade into the dispatch-error ring as `automation.tray_action`.
118
- 13. Use `native automate reload` to request a WebView reload.
119
- 14. Use `native automate profile on` to enable per-stage frame timing: while on, `snapshot.txt` carries a `frame_profile` line with rolling p50/p90/max microseconds per pipeline stage (`rebuild`, `layout`, `reconcile`, `emit`, `a11y`, `plan`, `patch`, `encode`, `present`, `host_decode`, `host_draw`), each with a lifetime sample count (`<stage>_n=`). Drive some interactions, then `native automate snapshot | grep -o 'frame_profile.*'` to read where frame time goes; `profile off` stops recording and drops the line. Turning it on starts a fresh sample window.
118
+ 11. Use `native automate widget-pinch <view-label> <scale> [x y]` for trackpad pinch gestures against a gpu-surface view: the runtime dispatches the real `pinch_begin`/`pinch_change`/`pinch_end` platform events, with one change carrying `scale - 1`. `<scale>` is the FINAL multiplicative zoom for the gesture — the cumulative gesture scale (the product of `1 + delta`) lands exactly on it — `1.5` zooms in 50%, `0.5` zooms out to half. The optional anchor point is view-local points, defaulting to the view center. Apps hear it through the pinch channel (`Options.on_pinch` / the TS core's `pinchMsg`).
119
+ 12. Use `native automate screenshot <view-label> [scale]` to capture the named `gpu_surface` view's canvas as `screenshot-<view-label>.png` (the CLI prints the artifact path and waits for the file).
120
+ 13. Use `native automate tray-action <item-id>` to select a status-item dropdown row through the same platform event a real menu-bar click emits (command dispatch with source `.tray`). The live tray is visible in `snapshot.txt` as a `tray title="..." items=N` line followed by ` tray-item #id label="..." command="..." enabled=...` rows — the macOS menu bar is outside every window capture, so the snapshot is the only automation evidence the model-driven tray exists, and the `#id` there is what `tray-action` takes. Unknown ids degrade into the dispatch-error ring as `automation.tray_action`.
121
+ 14. Use `native automate reload` to request a WebView reload.
122
+ 15. Use `native automate profile on` to enable per-stage frame timing: while on, `snapshot.txt` carries a `frame_profile` line with rolling p50/p90/max microseconds per pipeline stage (`rebuild`, `layout`, `reconcile`, `emit`, `a11y`, `plan`, `patch`, `encode`, `present`, `host_decode`, `host_draw`), each with a lifetime sample count (`<stage>_n=`). Drive some interactions, then `native automate snapshot | grep -o 'frame_profile.*'` to read where frame time goes; `profile off` stops recording and drops the line. Turning it on starts a fresh sample window.
120
123
 
121
124
  ## Screenshots
122
125
 
@@ -111,6 +111,7 @@ Use `EmbeddedApp` when another host owns the main loop:
111
111
 
112
112
  ```zig
113
113
  var embedded = native_sdk.embed.EmbeddedApp.init(my_app.app(), my_platform);
114
+ defer embedded.deinit();
114
115
  try embedded.start();
115
116
  try embedded.frame();
116
117
  try embedded.resize(new_surface);
@@ -119,6 +120,8 @@ try embedded.stop();
119
120
 
120
121
  This is useful for mobile hosts, game engines, custom render loops, and headless tests. The repository includes iOS and Android examples that link `libnative-sdk.a` through Swift/Kotlin host apps.
121
122
 
123
+ `stop()` tells the app it is shutting down; `deinit()` releases what the embedded runtime owns on the heap (registered canvas font bytes). It is idempotent, so `defer embedded.deinit()` right after `init` is the idiom — an embedder that creates and destroys apps in one process leaks the font registry per cycle without it. The C ABI's `native_sdk_app_destroy` runs the same deinit through its host wrapper.
124
+
122
125
  ## Headless tests
123
126
 
124
127
  Use `NullPlatform` or `TestHarness` when GUI behavior is not required:
@@ -171,7 +171,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
171
171
  | `resizable` | resizable | engine-managed drag handle; `width` sets the initial width |
172
172
  | `split` | split | two-pane horizontal splitter: exactly two element children (nest splits for more panes), the engine synthesizes the draggable divider between them. `value` binds the model-owned first-pane fraction (0 lays out at 0.5), `on-resize` names an f32 Msg variant dispatched with every applied fraction (echo it back through `value` — see Splitters), `min-width` on the panes bounds the drag, `gap` sets the divider band thickness. The divider is focusable: Left/Right (Shift for bigger steps) adjust, Home/End jump to the clamp edges |
173
173
  | `tree` | tree | disclosure-tree container (vertical flow): descendant rows carrying `role="treeitem"` — at ANY nesting depth — form one roving keyboard focus set with the ARIA tree keymap. Up/Down walk visible rows (selection follows focus through each row's `on-press`), Left collapses an expanded row or moves to the parent row, Right expands a collapsed row or moves to the first child row, Home/End jump to the edges, Enter/Space activate. Expandable rows bind `expanded` and `on-toggle`; the model owns selection and expansion (collapsed children are simply not rendered) |
174
- | `text`, `badge`, `tooltip` | text leaves | text content, `{}` interpolation allowed; `text` line policy via `wrap` (`"true"` word-wraps; `"false"`/unset paint one honest line, overflow eliding by default — `overflow="clip"` opts out), and `text` alone takes the typography rungs `size="heading"`/`size="display"` (themable token steps above title — section headings, hero stats, timer numerals) |
174
+ | `text`, `badge`, `tooltip` | text leaves | text content, `{}` interpolation allowed; `text` line policy via `wrap` (`"true"` word-wraps; `"false"`/unset paint one honest line, overflow eliding by default — `overflow="clip"` opts out), and `text` alone takes the typography rungs `size="heading"`/`size="display"` (themable token steps above title — section headings, hero stats, timer numerals). `tooltip` with `anchor="above\|below"` floats against its parent (the stack wrapping trigger + tooltip, the dropdown pattern) and the RUNTIME owns its visibility — hover intent on the trigger: shows after `tooltip-delay` ms (default 600; `"0"` = instant) and immediately on keyboard focus; hides on leave, focus departure, Escape, or a press of the trigger (a press also closes the warm window), and a shared 400ms warm window after a pointer-hovered tooltip hides on leave (the only hide that warms) shows the next trigger's tooltip instantly; the model never hears hover. These are shadcn/ui's defaults (Base UI). Without `anchor` it stays a static leaf that paints whenever the view renders it |
175
175
  | `text` > `span` | inline styled runs | mixed-style text in ONE wrapped paragraph: span children style runs with `weight="regular\|medium\|bold"`, `mono`, `italic`, `scale` (a positive multiplier on the paragraph's base size — inline headings, hero stats), `underline`, `foreground` (token name); `{bindings}` interpolate inside spans; whitespace between runs collapses to a single space (none = the runs abut); spans do not nest, take no events, and the paragraph announces as one text run — see "Rich text" |
176
176
  | `button`, `toggle-button`, `list-item`, `menu-item`, `toggle`, `switch`, `select`, `avatar` | text-bearing controls | label is the text content; `button`, `toggle-button`, `list-item`, and `menu-item` also take `icon="save"` — a vector icon drawn inline (buttons/toggle-buttons before the label, icon-only when the content is empty: add a `label`; list/menu items as a leading slot), ONE hit target whose icon follows the element's enabled/disabled tint (no overlay stacking, no duplicated `on-press`); tab strips are `toggle-button` children, so tabs get icons this way; `select` shows `placeholder` while empty and dispatches `on-press`; `avatar` renders initials, or a runtime image via `image="{binding}"` (see the Images section) |
177
177
  | `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); the checkbox/radio label rides `text="..."` — these are not text-bearing elements, so text content is a teaching error (`label=` alone names one for accessibility without a visible label); a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
@@ -180,6 +180,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
180
180
  | `separator`, `spacer` | separator, flexible space | `separator` is axis-aware: a horizontal rule in a `column`, a thin vertical divider in a `row`; give `spacer` a `grow` |
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
+ | `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 |
183
184
  | `markdown` | rendered markdown subtree | leaf; `source` is one `{binding}` — see "Markdown in markup" |
184
185
  | `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` |
185
186
  | `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 |
@@ -191,7 +192,7 @@ Not markup-expressible (deliberately — write these as Zig view functions with
191
192
 
192
193
  ## Attributes
193
194
 
194
- Layout: `gap` (flow containers only — stacking containers `stack`/`panel`/`card`/`alert`/`bubble`/`dialog`/`drawer`/`sheet`/`resizable` layer their children, so `gap` there is a validation error, not silence: wrap the children in a `column`/`row` inside; on `split` it sets the divider band thickness), `padding` (uniform), `grow`, `width`, `height` (definite: the element is exactly that size — intrinsic content neither shrinks nor silently overflows it; `resizable` treats `width` as the initial width), `min-width` (a floor WITHOUT `width`'s definite max — the element may grow past it but never shrink below; on split panes it bounds the divider drag), `wrap` (`text` only: `wrap="true"` word-wraps at the width the element receives and reserves the wrapped height in columns; `wrap="false"` and unset are honest single-line — one line whose overflow follows `overflow`), `overflow` (`text` only, a teaching error elsewhere: what a single line does with content that does not fit — `ellipsis`, the default, elides behind a trailing … measured with the same metrics paint uses, right for width-constrained list-row titles; `clip` hard-cuts at the frame for fixed-format content like a duration column where "1…" beats nothing; there is deliberately no overflow-visible), `text-alignment` (start|center|end — text leaves, status bars, surface titles; controls that own their label placement ignore it), `columns` (`grid` only: fixed column count, omit for the derived near-square grid; a teaching error elsewhere), `main` (start|center|end|space_between), `cross` (stretch|start|center|end), `virtualized`, `virtual-item-extent`, `anchor` (`dropdown-menu` only, literal `below`/`above`: floats the surface against its parent instead of the flow — auto-flips when the preferred side does not fit, height clamps to the chosen side, x clamps into the window), `anchor-alignment` (with `anchor`: `start`/`end`/`stretch` — stretch also widens the surface to at least the anchor's width, the select-menu look), `anchor-offset` (with `anchor`: literal gap in points, default 4), `overscroll` (`scroll` only, a teaching error elsewhere: `none` pins the region at its content edges — the shipped default via the `ScrollPhysics.overscroll` token — `rubber_band` lets it bounce past them on both the engine and native paths, `default` follows the token).
195
+ Layout: `gap` (flow containers only — stacking containers `stack`/`panel`/`card`/`alert`/`bubble`/`dialog`/`drawer`/`sheet`/`resizable` layer their children, so `gap` there is a validation error, not silence: wrap the children in a `column`/`row` inside; on `split` it sets the divider band thickness), `padding` (uniform), `grow`, `width`, `height` (definite: the element is exactly that size — intrinsic content neither shrinks nor silently overflows it; `resizable` treats `width` as the initial width), `min-width` (a floor WITHOUT `width`'s definite max — the element may grow past it but never shrink below; on split panes it bounds the divider drag), `wrap` (`text` only: `wrap="true"` word-wraps at the width the element receives and reserves the wrapped height in columns; `wrap="false"` and unset are honest single-line — one line whose overflow follows `overflow`), `overflow` (`text` only, a teaching error elsewhere: what a single line does with content that does not fit — `ellipsis`, the default, elides behind a trailing … measured with the same metrics paint uses, right for width-constrained list-row titles; `clip` hard-cuts at the frame for fixed-format content like a duration column where "1…" beats nothing; there is deliberately no overflow-visible), `text-alignment` (start|center|end — text leaves, status bars, surface titles; controls that own their label placement ignore it), `columns` (`grid` only: fixed column count, omit for the derived near-square grid; a teaching error elsewhere), `main` (start|center|end|space_between), `cross` (stretch|start|center|end), `virtualized`, `virtual-item-extent`, `anchor` (`dropdown-menu` and `tooltip`, literal `below`/`above`: floats the surface against its parent instead of the flow — auto-flips when the preferred side does not fit, height clamps to the chosen side, x clamps into the window; an anchored tooltip's visibility is runtime-owned hover intent, unlike the model-owned dropdown), `anchor-alignment` (with `anchor`: `start`/`end`/`stretch` — stretch also widens the surface to at least the anchor's width, the select-menu look), `anchor-offset` (with `anchor`: literal gap in points, default 4), `tooltip-delay` (`tooltip` only, beside `anchor` — a teaching error elsewhere or without it: hover-intent show delay in ms, default 600, `"0"` = instant; keyboard-focus reveals are always immediate), `overscroll` (`scroll` only, a teaching error elsewhere: `none` pins the region at its content edges — the shipped default via the `ScrollPhysics.overscroll` token — `rubber_band` lets it bounce past them on both the engine and native paths, `default` follows the token).
195
196
  Appearance/state: `variant` (default|primary|secondary|outline|ghost|destructive), `size` (the control scale default|sm|lg|icon on every sized element; on `text` also the typography rungs heading|display — named typography token steps (`heading_size` 28, `display_size` 48, themable like every token) for section headings and hero stats/timer numerals. The two axes stay apart: heading/display on a control is a teaching error naming text as their home, unknown values list the vocabulary, and numeric sizes are refused by design — retheme the typography tokens to move the whole scale), `disabled`, `checked`, `selected`, `value`, `placeholder`, `icon` (`button`, `toggle-button`, `list-item`, `menu-item`: vector icon drawn inline — buttons/toggle-buttons before the label, list/menu items as a leading slot; a teaching error anywhere else. A built-in name, `app:<name>`, or one `{binding}` resolving to such a name). **One size register per row**: every control class shares the control height at a given register (default 36, sm 31.5, lg 40.5 before density), so a toolbar/filter row reads as one height exactly when every control in it carries the SAME `size` — mixing `size="sm"` buttons with a default field renders two heights in one row, and hand-sized pressable panels (`height="30"`) never land on the scale; compose rows from real controls at one register.
196
197
  Focus: `autofocus` (focusable controls only — a teaching error elsewhere): moves keyboard focus to the element when it MOUNTS or when the bound value turns on, edge-triggered so holding it true never re-steals focus from the user. The TEA way to focus an editor on note-create (`<text-field autofocus="{editing}" ...>` or mount the field under an `<if>` with `autofocus="true"`; Zig views use `ElementOptions.autofocus`) and to give keyboard-first apps their first focus without a click.
197
198
  Semantics: `role` (listitem, treeitem, button, ...; `treeitem` also makes the row part of its tree's roving keyboard focus set), `label` (accessible name — it REPLACES the element's text content as the announced name, so snapshot greps and screen readers see the label, never the text; don't `label` an element whose visible text you grep for), `expanded` (tree rows: disclosure state, model-owned — omit on leaves). Accessible names are ENFORCED: an interactive control with no text content, no `text=`, and no `label=` is a validation error (icon-only controls need `label`; text-entry controls need `label` or `placeholder`), unknown/misused literal roles are errors (`role="tree"` on a text leaf can never hold rows), unnamed avatars and labels duplicating the text content are warnings (`label=""` marks an image decorative). Zig-built trees get the same discipline from `canvas.expectA11yAuditSweepClean` (missing names as the bridges would announce them, focusables clipped out of keyboard reach, identically labeled siblings) — adopt it next to the layout sweep.
@@ -428,6 +428,11 @@ fn runNull(app: native_sdk.App, options: RunOptions, init: std.process.Init) !vo
428
428
  // stack overflows on a stack instance, so construct it on the heap.
429
429
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
430
430
  defer std.heap.page_allocator.destroy(runtime);
431
+ // Fonts registered at startup and media-surface texture buffers
432
+ // adopted during the run are heap-owned by the runtime; return them
433
+ // (and disarm the producer wake bindings) before the runtime
434
+ // storage itself goes.
435
+ defer runtime.deinit();
431
436
  native_sdk.Runtime.initAt(runtime, .{
432
437
  .platform = null_platform.platform(),
433
438
  .trace_sink = runtime_trace_sink,
@@ -483,6 +488,11 @@ fn runMacos(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
483
488
  // stack overflows on a stack instance, so construct it on the heap.
484
489
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
485
490
  defer std.heap.page_allocator.destroy(runtime);
491
+ // Fonts registered at startup and media-surface texture buffers
492
+ // adopted during the run are heap-owned by the runtime; return them
493
+ // (and disarm the producer wake bindings) before the runtime
494
+ // storage itself goes.
495
+ defer runtime.deinit();
486
496
  native_sdk.Runtime.initAt(runtime, .{
487
497
  .platform = mac_platform.platform(),
488
498
  .trace_sink = runtime_trace_sink,
@@ -535,6 +545,11 @@ fn runLinux(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
535
545
  // stack overflows on a stack instance, so construct it on the heap.
536
546
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
537
547
  defer std.heap.page_allocator.destroy(runtime);
548
+ // Fonts registered at startup and media-surface texture buffers
549
+ // adopted during the run are heap-owned by the runtime; return them
550
+ // (and disarm the producer wake bindings) before the runtime
551
+ // storage itself goes.
552
+ defer runtime.deinit();
538
553
  native_sdk.Runtime.initAt(runtime, .{
539
554
  .platform = linux_platform.platform(),
540
555
  .trace_sink = runtime_trace_sink,
@@ -586,6 +601,11 @@ fn runWindows(app: native_sdk.App, options: RunOptions, init: std.process.Init)
586
601
  // stack overflows on a stack instance, so construct it on the heap.
587
602
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
588
603
  defer std.heap.page_allocator.destroy(runtime);
604
+ // Fonts registered at startup and media-surface texture buffers
605
+ // adopted during the run are heap-owned by the runtime; return them
606
+ // (and disarm the producer wake bindings) before the runtime
607
+ // storage itself goes.
608
+ defer runtime.deinit();
589
609
  native_sdk.Runtime.initAt(runtime, .{
590
610
  .platform = windows_platform.platform(),
591
611
  .trace_sink = runtime_trace_sink,
@@ -699,6 +719,11 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
699
719
  }
700
720
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
701
721
  defer std.heap.page_allocator.destroy(runtime);
722
+ // Fonts registered at startup and media-surface texture buffers
723
+ // adopted during the run are heap-owned by the runtime; return them
724
+ // (and disarm the producer wake bindings) before the runtime
725
+ // storage itself goes.
726
+ defer runtime.deinit();
702
727
  // Bridge policy and security must match what the recording ran
703
728
  // under (they gate replayed bridge_message dispatch); automation,
704
729
  // window-state restore, and tracing stay off — replay consumes only
@@ -34,7 +34,10 @@ pub const max_command_bytes: usize = 16 * 1024 + 64;
34
34
  /// never touches (same loud timeout) — and both directions are refused
35
35
  /// up front by this handshake whenever a live snapshot exists.
36
36
  /// Snapshots without a `protocol=` field predate the handshake entirely.
37
- pub const version: u32 = 6;
37
+ /// 7 = the `widget-pinch` verb (drive a trackpad pinch gesture as the
38
+ /// real begin/change/end platform input events, journaled like every
39
+ /// synthesized input).
40
+ pub const version: u32 = 7;
38
41
 
39
42
  /// How many commands may sit in the dropbox queue at once. Automation
40
43
  /// drivers are scripts, not firehoses: the app drains one command per
@@ -93,6 +96,14 @@ pub const Action = enum {
93
96
  widget_drag,
94
97
  widget_wheel,
95
98
  widget_key,
99
+ /// `widget-pinch <view-label> <scale> [<x> <y>]`: drive a trackpad
100
+ /// pinch gesture against a gpu-surface view — the real
101
+ /// `pinch_begin`/`pinch_change`/`pinch_end` platform events, with
102
+ /// one change carrying `scale - 1` so the cumulative gesture scale
103
+ /// (the product of `1 + delta`) lands exactly on `<scale>`, the
104
+ /// gesture's FINAL multiplicative zoom. The anchor point defaults
105
+ /// to the view center.
106
+ widget_pinch,
96
107
  menu_command,
97
108
  shortcut,
98
109
  tray_action,
@@ -133,6 +144,7 @@ pub const Command = struct {
133
144
  if (std.mem.eql(u8, action_text, "widget-drag") and value.len > 0) return .{ .action = .widget_drag, .value = value };
134
145
  if (std.mem.eql(u8, action_text, "widget-wheel") and value.len > 0) return .{ .action = .widget_wheel, .value = value };
135
146
  if (std.mem.eql(u8, action_text, "widget-key") and value.len > 0) return .{ .action = .widget_key, .value = value };
147
+ if (std.mem.eql(u8, action_text, "widget-pinch") and value.len > 0) return .{ .action = .widget_pinch, .value = value };
136
148
  if (std.mem.eql(u8, action_text, "menu-command") and value.len > 0) return .{ .action = .menu_command, .value = value };
137
149
  if (std.mem.eql(u8, action_text, "shortcut") and value.len > 0) return .{ .action = .shortcut, .value = value };
138
150
  if (std.mem.eql(u8, action_text, "tray-action") and value.len > 0) return .{ .action = .tray_action, .value = value };
@@ -226,6 +238,13 @@ test "commands parse reload and wait" {
226
238
  const widget_key = try Command.parse("widget-key canvas tab");
227
239
  try std.testing.expectEqual(Action.widget_key, widget_key.action);
228
240
  try std.testing.expectEqualStrings("canvas tab", widget_key.value);
241
+ const widget_pinch = try Command.parse("widget-pinch canvas 1.5");
242
+ try std.testing.expectEqual(Action.widget_pinch, widget_pinch.action);
243
+ try std.testing.expectEqualStrings("canvas 1.5", widget_pinch.value);
244
+ const widget_pinch_at = try Command.parse("widget-pinch canvas 0.5 120 80");
245
+ try std.testing.expectEqual(Action.widget_pinch, widget_pinch_at.action);
246
+ try std.testing.expectEqualStrings("canvas 0.5 120 80", widget_pinch_at.value);
247
+ try std.testing.expectError(error.InvalidCommand, Command.parse("widget-pinch"));
229
248
  const menu_command = try Command.parse("menu-command app.refresh");
230
249
  try std.testing.expectEqual(Action.menu_command, menu_command.action);
231
250
  const shortcut = try Command.parse("shortcut app.refresh");
@@ -436,6 +436,15 @@ pub fn deliverPresentedPixels(self: anytype, scale: f32, buffer: []u8, out: *typ
436
436
  return true;
437
437
  }
438
438
 
439
+ /// A runtime embedded in a host that owns the main loop (the mobile
440
+ /// shims, game engines, custom render loops, headless tests). Lifecycle:
441
+ /// `init`/`initInPlace`, `defer embedded.deinit()`, `start`, host-pumped
442
+ /// events and `frame`s, `stop` (dispatches app_shutdown), and finally
443
+ /// that deferred `deinit` — `stop` only tells the app it is shutting
444
+ /// down; `deinit` is what returns the embedded runtime's heap-owned
445
+ /// registrations (registered canvas font bytes), so a direct embedder
446
+ /// that creates and destroys apps in one process leaks a full font
447
+ /// registry per cycle without it.
439
448
  pub const EmbeddedApp = struct {
440
449
  app: runtime.App,
441
450
  runtime: runtime.Runtime,
@@ -451,6 +460,17 @@ pub const EmbeddedApp = struct {
451
460
  runtime.Runtime.initAt(&self.runtime, .{ .platform = platform_value });
452
461
  }
453
462
 
463
+ /// End of the embedded lifecycle, symmetric with `init`/`initInPlace`:
464
+ /// releases everything the embedded app owns on the heap — the
465
+ /// runtime's registered canvas font bytes (`Runtime.deinit`); `init`
466
+ /// itself allocates nothing else. Idempotent: a second call is a
467
+ /// no-op, so `defer embedded.deinit()` composes with early exits.
468
+ /// Everything borrowing the runtime (parsed faces, measure
469
+ /// providers, views) is invalid past this point.
470
+ pub fn deinit(self: *EmbeddedApp) void {
471
+ self.runtime.deinit();
472
+ }
473
+
454
474
  pub fn start(self: *EmbeddedApp) anyerror!void {
455
475
  try self.runtime.dispatchPlatformEvent(self.app, .app_start);
456
476
  }
@@ -757,6 +777,13 @@ pub const MobileHostApp = struct {
757
777
 
758
778
  pub fn destroy(self: *MobileHostApp) void {
759
779
  disableAutomation(self);
780
+ // One lifecycle owner: the embedded app's own deinit returns
781
+ // the runtime's heap-owned storage (registered canvas font
782
+ // bytes, lazily allocated media-surface texture buffers) AND
783
+ // disarms the producer wake bindings, so a media producer the
784
+ // embedding app keeps past destroy can never wake the freed
785
+ // host storage (the embedded null platform included).
786
+ self.embedded.deinit();
760
787
  std.heap.page_allocator.destroy(self);
761
788
  }
762
789