@native-sdk/cli 0.5.3 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/build/app.zig +41 -1
  2. package/build.zig +223 -3
  3. package/native-sdk.d.ts +17 -1
  4. package/package.json +9 -9
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/rt/rt.zig +138 -3
  8. package/packages/core/sdk/core.ts +225 -3
  9. package/packages/core/src/emitter.ts +2586 -259
  10. package/skill-data/native-ui/SKILL.md +3 -2
  11. package/skill-data/ts-core/SKILL.md +9 -1
  12. package/src/app_runner/root.zig +81 -1
  13. package/src/app_runner/ts_core_main.zig +4 -0
  14. package/src/embed/tests.zig +119 -1
  15. package/src/platform/linux/gtk_host.c +112 -3
  16. package/src/platform/linux/root.zig +71 -0
  17. package/src/platform/macos/appkit_host.h +48 -2
  18. package/src/platform/macos/appkit_host.m +533 -34
  19. package/src/platform/macos/cef_host.mm +262 -10
  20. package/src/platform/macos/root.zig +92 -4
  21. package/src/platform/null_platform.zig +298 -5
  22. package/src/platform/root.zig +33 -0
  23. package/src/platform/types.zig +138 -4
  24. package/src/platform/windows/root.zig +134 -0
  25. package/src/platform/windows/webview2_host.cpp +152 -40
  26. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  27. package/src/primitives/app_manifest/root.zig +1 -0
  28. package/src/primitives/app_manifest/types.zig +32 -0
  29. package/src/primitives/canvas/tests.zig +1 -0
  30. package/src/primitives/canvas/ui.zig +11 -7
  31. package/src/primitives/canvas/ui_markup.zig +58 -34
  32. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  33. package/src/primitives/canvas/ui_markup_compiled.zig +23 -8
  34. package/src/primitives/canvas/ui_markup_compiled_tests.zig +55 -0
  35. package/src/primitives/canvas/ui_markup_contract.zig +1 -1
  36. package/src/primitives/canvas/ui_markup_contract_tests.zig +26 -0
  37. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  38. package/src/primitives/canvas/ui_markup_tests.zig +29 -9
  39. package/src/primitives/canvas/ui_markup_view.zig +29 -11
  40. package/src/primitives/canvas/ui_markup_view_tests.zig +150 -9
  41. package/src/primitives/canvas/ui_schema.zig +13 -0
  42. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  43. package/src/root.zig +7 -0
  44. package/src/runtime/api.zig +6 -4
  45. package/src/runtime/bridge_payload.zig +7 -0
  46. package/src/runtime/bridge_responses.zig +5 -0
  47. package/src/runtime/builtin_bridge.zig +9 -4
  48. package/src/runtime/canvas_font_tests.zig +439 -2
  49. package/src/runtime/canvas_fonts.zig +61 -6
  50. package/src/runtime/canvas_image_tests.zig +195 -0
  51. package/src/runtime/canvas_images.zig +45 -12
  52. package/src/runtime/core.zig +58 -11
  53. package/src/runtime/effects.zig +1664 -43
  54. package/src/runtime/effects_fetch_tests.zig +89 -1
  55. package/src/runtime/effects_file_tests.zig +41 -1
  56. package/src/runtime/effects_image_tests.zig +1304 -0
  57. package/src/runtime/effects_tests.zig +153 -0
  58. package/src/runtime/flow.zig +17 -0
  59. package/src/runtime/root.zig +11 -0
  60. package/src/runtime/session_blobs.zig +689 -0
  61. package/src/runtime/session_journal.zig +85 -21
  62. package/src/runtime/session_record.zig +27 -2
  63. package/src/runtime/session_replay.zig +168 -16
  64. package/src/runtime/session_tests.zig +1992 -0
  65. package/src/runtime/shell_layout.zig +7 -0
  66. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  67. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  68. package/src/runtime/tests.zig +2 -0
  69. package/src/runtime/ts_core_host.zig +439 -4
  70. package/src/runtime/ts_core_host_tests.zig +41 -0
  71. package/src/runtime/ts_ui_app.zig +7 -0
  72. package/src/runtime/ui_app.zig +111 -6
  73. package/src/runtime/ui_app_window_tests.zig +468 -0
  74. package/src/runtime/window_command_bridge_tests.zig +117 -0
  75. package/src/runtime/window_storage.zig +32 -0
  76. package/src/runtime/window_views.zig +61 -1
  77. package/src/tooling/manifest.zig +75 -0
  78. package/src/tooling/raw_manifest.zig +2 -0
  79. package/src/tooling/templates.zig +219 -1
@@ -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
 
@@ -1064,7 +1065,7 @@ Tests that touch files or clocks get their `Io` from `std.testing.io`. The full
1064
1065
 
1065
1066
  ## Validate without building
1066
1067
 
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).
1068
+ `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
1069
 
1069
1070
  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
1071
 
@@ -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.
@@ -154,6 +154,14 @@ 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.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the decoded dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). Decode limits are the registered-image limits (16 slots, 1 MiB decoded pixels — avatar/cover scale, not photo scale); the encoded source bound is 1.25 MiB, and over-bound sources fail whole with `"too_large"`, never cut. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
158
+
159
+ ### The window verbs
160
+
161
+ The menu-bar lifecycle pair — fire-and-forget, no routing and no result Msg (the window's own frame event carries the resulting state):
162
+
163
+ - `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.
164
+ - `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
165
 
158
166
  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
167
 
@@ -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 = .{};
@@ -649,6 +701,22 @@ const SessionRecordContext = struct {
649
701
  }
650
702
  };
651
703
 
704
+ /// The blob directory beside a session journal: `blobs/` in the
705
+ /// journal's directory — large effect payloads (an image load's source
706
+ /// bytes) live there content-addressed, referenced from journal
707
+ /// records by hash + length (see session_blobs.zig).
708
+ fn sessionBlobStore(io: std.Io, journal_path: []const u8) ?*native_sdk.runtime.SessionBlobDirStore {
709
+ var dir_buffer: [1024]u8 = undefined;
710
+ const parent = std.fs.path.dirname(journal_path) orelse ".";
711
+ const blob_dir = std.fmt.bufPrint(&dir_buffer, "{s}/blobs", .{parent}) catch return null;
712
+ const store = std.heap.page_allocator.create(native_sdk.runtime.SessionBlobDirStore) catch return null;
713
+ store.* = native_sdk.runtime.SessionBlobDirStore.init(io, blob_dir) catch {
714
+ std.heap.page_allocator.destroy(store);
715
+ return null;
716
+ };
717
+ return store;
718
+ }
719
+
652
720
  /// `NATIVE_SDK_SESSION_RECORD=<path>`: create the journal file and a
653
721
  /// recorder that streams the session into it from the very first
654
722
  /// dispatched event (init determinism needs init-time effect results).
@@ -663,6 +731,7 @@ fn setupSessionRecorder(init: std.process.Init, app_info: native_sdk.AppInfo) ?*
663
731
  context.* = .{ .io = init.io, .file = file };
664
732
  const recorder = std.heap.page_allocator.create(native_sdk.runtime.SessionRecorder) catch return null;
665
733
  recorder.* = native_sdk.runtime.SessionRecorder.init(context.sink());
734
+ if (sessionBlobStore(init.io, path)) |store| recorder.blob_sink = store.sink();
666
735
  recorder.begin(native_sdk.runtime.sessionHeaderNow(
667
736
  native_sdk.runtime.sessionPlatformName(),
668
737
  app_info.app_name,
@@ -717,6 +786,13 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
717
786
  native_sdk.platform.macos.installHeadlessTextServices(&replay_platform.services);
718
787
  null_platform.gpu_surface_scroll_drivers = true;
719
788
  }
789
+ // Replayed image loads decode too: successful `.image` records feed
790
+ // their journaled blob-store bytes back through decode+register, so
791
+ // the codec must be the recording host's own or every replayed load
792
+ // (and every replayed screenshot with an image in it) drops its
793
+ // pixels. Journaled bytes stay the only input — the codec is a pure
794
+ // bytes-to-pixels call and the network stays absent.
795
+ native_sdk.platform.installHeadlessImageCodec(build_options.platform, &null_platform, &replay_platform.services);
720
796
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
721
797
  defer std.heap.page_allocator.destroy(runtime);
722
798
  // Fonts registered at startup and media-surface texture buffers
@@ -742,7 +818,11 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
742
818
  !std.mem.eql(u8, value, "0")
743
819
  else
744
820
  true;
745
- const report = native_sdk.runtime.replaySession(runtime, app, journal_bytes, .{ .verify = verify }) catch |err| {
821
+ const blob_store = sessionBlobStore(init.io, journal_path);
822
+ const report = native_sdk.runtime.replaySession(runtime, app, journal_bytes, .{
823
+ .verify = verify,
824
+ .blobs = if (blob_store) |store| store.source() else null,
825
+ }) catch |err| {
746
826
  switch (err) {
747
827
  error.JournalBadMagic,
748
828
  error.JournalUnsupportedVersion,
@@ -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);
@@ -109,9 +109,91 @@ test "embedded app deinit returns registered font bytes across create-destroy cy
109
109
  try embedded.runtime.registerCanvasFont(canvas.min_registered_font_id, canvas.font_ttf.geist_mono_bytes);
110
110
  try std.testing.expectEqual(@as(usize, 1), embedded.runtime.registeredCanvasFontCount());
111
111
  try embedded.stop();
112
+
113
+ // Deinit returns BOTH sides of the registration: the Zig-side
114
+ // bytes (the leak-checking allocator above) and the host-side
115
+ // registration — the runtime must call the platform's
116
+ // font-unregister seam per registered id, the call a macOS host
117
+ // answers by dropping its CoreText descriptor and caches. The
118
+ // null platform records that call; the deferred second deinit
119
+ // stays the idempotence backstop.
120
+ embedded.deinit();
121
+ try std.testing.expectEqual(@as(usize, 1), null_platform.gpu_surface_font_unregister_count);
122
+ try std.testing.expectEqual(@as(u64, canvas.min_registered_font_id), null_platform.gpu_surface_font_unregister_id);
123
+ // The null platform's register seam is off by default, so the
124
+ // runtime captured ownership token 0 (nothing installed
125
+ // host-side) and the teardown call must carry exactly that.
126
+ try std.testing.expectEqual(@as(u64, 0), null_platform.gpu_surface_font_unregister_token);
112
127
  }
113
128
  }
114
129
 
130
+ test "embedded app deinit leaves a newer runtime's re-registration of the same font id intact" {
131
+ // Host font state is per-process while font ids are only permanent
132
+ // per-runtime, so two live runtimes can pass the same id through one
133
+ // host: the later registration wins (the documented lifecycle), and
134
+ // the OLDER runtime's deinit must return only its own already-
135
+ // replaced registration — never the newer runtime's live face,
136
+ // which that runtime's engine still holds and draws through. The
137
+ // null platform's host-font mirror models the stateful host (the
138
+ // shape of macOS's descriptor and token tables): one instance
139
+ // stands in for the process, both runtimes register through it, and
140
+ // the per-registration ownership token is what the unregister guard
141
+ // matches. An id-keyed removal is exactly the regression this test
142
+ // catches — it would empty the mirror at A's deinit and fail the
143
+ // survives assertion below.
144
+ var host_platform = platform.NullPlatform.init(.{});
145
+ host_platform.gpu_surface_font_registrations = true;
146
+ var state_a: u8 = 0;
147
+ var state_b: u8 = 0;
148
+ const embedded_a = try std.testing.allocator.create(EmbeddedApp);
149
+ defer std.testing.allocator.destroy(embedded_a);
150
+ const embedded_b = try std.testing.allocator.create(EmbeddedApp);
151
+ defer std.testing.allocator.destroy(embedded_b);
152
+ embedded_a.initInPlace(.{
153
+ .context = &state_a,
154
+ .name = "embedded-font-owner-a",
155
+ .source = platform.WebViewSource.html("<p>A</p>"),
156
+ }, host_platform.platform());
157
+ defer embedded_a.deinit();
158
+ embedded_b.initInPlace(.{
159
+ .context = &state_b,
160
+ .name = "embedded-font-owner-b",
161
+ .source = platform.WebViewSource.html("<p>B</p>"),
162
+ }, host_platform.platform());
163
+ defer embedded_b.deinit();
164
+ embedded_a.runtime.owned_allocator = std.testing.allocator;
165
+ embedded_b.runtime.owned_allocator = std.testing.allocator;
166
+
167
+ // A registers first, B re-registers the same id: last wins, each
168
+ // runtime captured its own never-repeating ownership token.
169
+ try embedded_a.runtime.registerCanvasFont(canvas.min_registered_font_id, canvas.font_ttf.geist_mono_bytes);
170
+ const token_a = embedded_a.runtime.canvas_font_entries[0].host_registration_token;
171
+ try embedded_b.runtime.registerCanvasFont(canvas.min_registered_font_id, canvas.font_ttf.geist_mono_bytes);
172
+ const token_b = embedded_b.runtime.canvas_font_entries[0].host_registration_token;
173
+ try std.testing.expect(token_a != 0);
174
+ try std.testing.expect(token_b != 0);
175
+ try std.testing.expect(token_a != token_b);
176
+ const live = host_platform.gpuSurfaceFont(canvas.min_registered_font_id) orelse return error.TestUnexpectedResult;
177
+ try std.testing.expectEqual(token_b, live.token);
178
+
179
+ // A's deinit presents its stale token: recorded and accepted (the
180
+ // registration it owned is already gone), and provably removing
181
+ // nothing — B's registration is still the one the host resolves.
182
+ embedded_a.deinit();
183
+ try std.testing.expectEqual(@as(usize, 1), host_platform.gpu_surface_font_unregister_count);
184
+ try std.testing.expectEqual(@as(u64, canvas.min_registered_font_id), host_platform.gpu_surface_font_unregister_id);
185
+ try std.testing.expectEqual(token_a, host_platform.gpu_surface_font_unregister_token);
186
+ const survivor = host_platform.gpuSurfaceFont(canvas.min_registered_font_id) orelse return error.TestUnexpectedResult;
187
+ try std.testing.expectEqual(token_b, survivor.token);
188
+
189
+ // B's deinit presents the live token and the host state comes out —
190
+ // the guard blocks the wrong owner, not teardown itself.
191
+ embedded_b.deinit();
192
+ try std.testing.expectEqual(@as(usize, 2), host_platform.gpu_surface_font_unregister_count);
193
+ try std.testing.expectEqual(token_b, host_platform.gpu_surface_font_unregister_token);
194
+ try std.testing.expect(host_platform.gpuSurfaceFont(canvas.min_registered_font_id) == null);
195
+ }
196
+
115
197
  test "embedded app deinit is idempotent" {
116
198
  var null_platform = platform.NullPlatform.init(.{});
117
199
  var state: u8 = 0;
@@ -127,10 +209,46 @@ test "embedded app deinit is idempotent" {
127
209
 
128
210
  // The documented idiom is `defer embedded.deinit()`, which must
129
211
  // compose with an explicit early teardown: the second call is a
130
- // no-op, never a double free.
212
+ // no-op, never a double free — and never a double host unregister
213
+ // (the first deinit already returned the host-side registration).
131
214
  embedded.deinit();
132
215
  try std.testing.expectEqual(@as(usize, 0), embedded.runtime.registeredCanvasFontCount());
216
+ try std.testing.expectEqual(@as(usize, 1), null_platform.gpu_surface_font_unregister_count);
217
+ embedded.deinit();
218
+ try std.testing.expectEqual(@as(usize, 1), null_platform.gpu_surface_font_unregister_count);
219
+ }
220
+
221
+ test "embedded app deinit returns the font registration to the platform that received it" {
222
+ // `Runtime.options` is public and mutable, and embedders genuinely
223
+ // swap the platform on a live runtime (tests in this repo do it
224
+ // constantly). The host-side registration must still come back to
225
+ // the host that RECEIVED it: each font entry captures its
226
+ // unregistration owner at registration time (the allocator-identity
227
+ // freeze, applied to the host seam), so a swap between registration
228
+ // and teardown retargets nothing. A deinit reading the live options
229
+ // instead would unregister against the swapped-in platform — the
230
+ // wrong host, or a null seam — and strand the original host's
231
+ // descriptor and caches for the process lifetime.
232
+ var platform_a = platform.NullPlatform.init(.{});
233
+ var platform_b = platform.NullPlatform.init(.{});
234
+ var state: u8 = 0;
235
+ const embedded = try std.testing.allocator.create(EmbeddedApp);
236
+ defer std.testing.allocator.destroy(embedded);
237
+ embedded.initInPlace(.{
238
+ .context = &state,
239
+ .name = "embedded-font-platform-swap",
240
+ .source = platform.WebViewSource.html("<p>Fonts</p>"),
241
+ }, platform_a.platform());
242
+ embedded.runtime.owned_allocator = std.testing.allocator;
243
+ try embedded.runtime.registerCanvasFont(canvas.min_registered_font_id, canvas.font_ttf.geist_mono_bytes);
244
+
245
+ // The swap under test: platform B holds the option by teardown time,
246
+ // but it never saw the registration.
247
+ embedded.runtime.options.platform = platform_b.platform();
133
248
  embedded.deinit();
249
+ try std.testing.expectEqual(@as(usize, 1), platform_a.gpu_surface_font_unregister_count);
250
+ try std.testing.expectEqual(@as(u64, canvas.min_registered_font_id), platform_a.gpu_surface_font_unregister_id);
251
+ try std.testing.expectEqual(@as(usize, 0), platform_b.gpu_surface_font_unregister_count);
134
252
  }
135
253
 
136
254
  test "mobile C ABI destroy returns registered font bytes through the embedded deinit" {
@@ -24,8 +24,17 @@
24
24
  * NATIVE_SDK_ALLOW_WEBVIEW2_STUB. */
25
25
  #if defined(NATIVE_SDK_ALLOW_WEBKITGTK_STUB)
26
26
  #define NATIVE_SDK_HAS_WEBKITGTK 0
27
- #pragma message("Embedded web layer excluded by the build configuration: building the GTK host without WebKitGTK (canvas apps unaffected; WebView loads will report WebViewNotFound)")
28
- /* The stubbed web layer keeps the window/webview bookkeeping SHAPE so
27
+ /* Deliberately NO compiler diagnostic in this branch — not even an
28
+ * informational #pragma message. The stub is the expected, configured
29
+ * state of every native-only Linux build, and zig renders every clang
30
+ * diagnostic of a failing translation unit as `error:` (its serialized
31
+ * clang diagnostics carry no severity into the error bundle), so an
32
+ * informational note here masquerades as the build-killing error the
33
+ * moment any unrelated real error appears anywhere in this file. The
34
+ * teaching lives where it is actionable instead: a stubbed host
35
+ * reports WebViewNotFound the moment an app actually uses a WebView.
36
+ *
37
+ * The stubbed web layer keeps the window/webview bookkeeping SHAPE so
29
38
  * every GTK-only path (overlay reordering, focus lookups, window
30
39
  * teardown) compiles unchanged: the web-view pointers below are opaque
31
40
  * and permanently NULL — every path that could create one is compiled
@@ -43,6 +52,18 @@ typedef struct native_sdk_absent_content_manager WebKitUserContentManager;
43
52
  #error "webkit/webkit.h not found: install the WebKitGTK 6.0 development package (libwebkitgtk-6.0-dev on Debian/Ubuntu), or define NATIVE_SDK_ALLOW_WEBKITGTK_STUB to build without the embedded web layer"
44
53
  #endif
45
54
 
55
+ /* G_APPLICATION_DEFAULT_FLAGS arrived in GLib 2.74 as the
56
+ * non-deprecated spelling of "no flags". This host's GTK floor is 4.10
57
+ * (the GtkFileDialog family below), and GTK 4.10's own GLib floor is
58
+ * 2.72 — distros that backport GTK 4.10 onto a GLib 2.72 base (Ubuntu
59
+ * 22.04 derivatives) must still compile this file. Same value, gated to
60
+ * older GLib only; the pre-2.74 name G_APPLICATION_FLAGS_NONE is not
61
+ * used because it is deprecated from 2.74 on and would emit a warning
62
+ * exactly where the newer name exists. */
63
+ #if !GLIB_CHECK_VERSION(2, 74, 0)
64
+ #define G_APPLICATION_DEFAULT_FLAGS ((GApplicationFlags) 0)
65
+ #endif
66
+
46
67
  #define NATIVE_SDK_MAX_WINDOWS 16
47
68
  #define NATIVE_SDK_MAX_WEBVIEWS 16
48
69
  #define NATIVE_SDK_MAX_TIMERS 64
@@ -326,6 +347,13 @@ struct native_sdk_gtk_host {
326
347
  int did_shutdown;
327
348
  int app_active;
328
349
  guint frame_timer;
350
+ /* The quit verb's queued stop turn (native_sdk_gtk_stop), tracked
351
+ * like frame_timer so it can be coalesced while pending and
352
+ * removed at destroy — a bare g_idle_add would leave a second stop
353
+ * request (the shutdown handler's error path can make one) holding
354
+ * a freed host after the loop quits. Zero while none is queued;
355
+ * the idle clears it as its first act. */
356
+ guint stop_idle_source;
329
357
 
330
358
  char **allowed_origins;
331
359
  int allowed_origins_count;
@@ -523,6 +551,39 @@ static int native_sdk_valid_native_view_frame(double x, double y, double width,
523
551
  return x >= 0 && y >= 0 && width >= 0 && height >= 0;
524
552
  }
525
553
 
554
+ /* String-parameter byte caps for the native-view calls, mirroring the
555
+ * runtime's platform limits (types.zig: max_view_label_bytes 64,
556
+ * max_view_role_bytes 64, max_view_accessibility_label_bytes 256,
557
+ * max_view_text_bytes 1024, and the command-id cap 128). The runtime
558
+ * validates the same bounds before ever calling in, so a length past
559
+ * them at THIS boundary means the arguments were corrupted in transit —
560
+ * a caller compiled with a broken C ABI hands over shifted stack slots
561
+ * where a pointer poses as a length. Refuse loudly and name the field
562
+ * instead of memcpy-ing from a garbage pointer and faulting. */
563
+ #define NATIVE_SDK_MAX_VIEW_LABEL_BYTES 64
564
+ #define NATIVE_SDK_MAX_VIEW_ROLE_BYTES 64
565
+ #define NATIVE_SDK_MAX_VIEW_ACCESSIBILITY_LABEL_BYTES 256
566
+ #define NATIVE_SDK_MAX_VIEW_TEXT_BYTES 1024
567
+ #define NATIVE_SDK_MAX_VIEW_COMMAND_BYTES 128
568
+
569
+ static int native_sdk_valid_native_view_string(const char *what, size_t len, size_t max_len) {
570
+ if (len <= max_len) return 1;
571
+ g_warning("native view %s length %zu exceeds the platform cap %zu; refusing the call - "
572
+ "the runtime never sends this, so the arguments likely arrived corrupted "
573
+ "(a miscompiled C-ABI boundary hands the host shifted stack slots)",
574
+ what, len, max_len);
575
+ return 0;
576
+ }
577
+
578
+ static int native_sdk_valid_native_view_strings(size_t label_len, size_t parent_len, size_t role_len, size_t accessibility_label_len, size_t text_len, size_t command_len) {
579
+ return native_sdk_valid_native_view_string("label", label_len, NATIVE_SDK_MAX_VIEW_LABEL_BYTES) &&
580
+ native_sdk_valid_native_view_string("parent", parent_len, NATIVE_SDK_MAX_VIEW_LABEL_BYTES) &&
581
+ native_sdk_valid_native_view_string("role", role_len, NATIVE_SDK_MAX_VIEW_ROLE_BYTES) &&
582
+ native_sdk_valid_native_view_string("accessibility_label", accessibility_label_len, NATIVE_SDK_MAX_VIEW_ACCESSIBILITY_LABEL_BYTES) &&
583
+ native_sdk_valid_native_view_string("text", text_len, NATIVE_SDK_MAX_VIEW_TEXT_BYTES) &&
584
+ native_sdk_valid_native_view_string("command", command_len, NATIVE_SDK_MAX_VIEW_COMMAND_BYTES);
585
+ }
586
+
526
587
  static int native_sdk_native_extent(double value) {
527
588
  return value > 0 ? (int)(value + 0.5) : 0;
528
589
  }
@@ -2791,6 +2852,12 @@ void native_sdk_gtk_destroy(native_sdk_gtk_host_t *host) {
2791
2852
  * anything else goes away; everything runs on this thread. */
2792
2853
  native_sdk_audio_release(host, 1);
2793
2854
  if (host->frame_timer) g_source_remove(host->frame_timer);
2855
+ /* A stop turn still queued at teardown (the loop quit before the
2856
+ * idle ran) must not fire into freed memory. */
2857
+ if (host->stop_idle_source) {
2858
+ g_source_remove(host->stop_idle_source);
2859
+ host->stop_idle_source = 0;
2860
+ }
2794
2861
  for (int i = 0; i < NATIVE_SDK_MAX_TIMERS; i++) {
2795
2862
  if (host->timers[i].in_use && host->timers[i].source) g_source_remove(host->timers[i].source);
2796
2863
  host->timers[i].in_use = 0;
@@ -2819,7 +2886,15 @@ void native_sdk_gtk_run(native_sdk_gtk_host_t *host, native_sdk_gtk_event_callba
2819
2886
  g_application_run(G_APPLICATION(host->app), 0, NULL);
2820
2887
  }
2821
2888
 
2822
- void native_sdk_gtk_stop(native_sdk_gtk_host_t *host) {
2889
+ /* Runs on the GLib main loop: the quit verb's deferred stop turn. The
2890
+ * same emitShutdown-then-quit the last window's close-request runs,
2891
+ * just one loop turn later (see native_sdk_gtk_stop). */
2892
+ static gboolean native_sdk_stop_idle(gpointer data) {
2893
+ native_sdk_gtk_host_t *host = data;
2894
+ /* This turn is running: clear the tracked id FIRST, so the source
2895
+ * cannot be double-removed (destroy) or wrongly treated as still
2896
+ * pending (a re-quit during the shutdown dispatch below). */
2897
+ host->stop_idle_source = 0;
2823
2898
  if (!host->did_shutdown) {
2824
2899
  host->did_shutdown = 1;
2825
2900
  native_sdk_emit(host, (native_sdk_gtk_event_t){ .kind = NATIVE_SDK_GTK_EVENT_SHUTDOWN });
@@ -2829,6 +2904,33 @@ void native_sdk_gtk_stop(native_sdk_gtk_host_t *host) {
2829
2904
  host->frame_timer = 0;
2830
2905
  }
2831
2906
  g_application_quit(G_APPLICATION(host->app));
2907
+ return G_SOURCE_REMOVE;
2908
+ }
2909
+
2910
+ void native_sdk_gtk_stop(native_sdk_gtk_host_t *host) {
2911
+ /* Queued, never synchronous: this stop is the quit verb's landing
2912
+ * point, and the verb arrives MID DISPATCH (a menu command's
2913
+ * update returned it), so a synchronous SHUTDOWN emit would nest
2914
+ * the shutdown dispatch inside the requesting command's — the
2915
+ * session recorder commits nested events innermost-first and seals
2916
+ * the journal on shutdown, so the nested seal drops the command
2917
+ * record and replay diverges. The idle hop (the same seam the wake
2918
+ * and frame-request paths ride) emits the identical
2919
+ * emitShutdown + quit on the next loop turn, after the requesting
2920
+ * dispatch has committed; g_application_run keeps pumping until
2921
+ * the queued g_application_quit lands, so a quit that is the last
2922
+ * thing an app ever does still exits promptly.
2923
+ *
2924
+ * Exactly-once hygiene: once the shutdown has emitted there is
2925
+ * nothing left to stop, and while a stop turn is already queued a
2926
+ * second request coalesces into it — a second bare g_idle_add
2927
+ * (the shutdown handler's error path can request one) would leave
2928
+ * an untracked source holding this host after the loop quits and
2929
+ * the host is freed. The pending source id is tracked on the host
2930
+ * (stop_idle_source, cleared by the idle itself) and removed at
2931
+ * native_sdk_gtk_destroy. */
2932
+ if (host->did_shutdown || host->stop_idle_source) return;
2933
+ host->stop_idle_source = g_idle_add(native_sdk_stop_idle, host);
2832
2934
  }
2833
2935
 
2834
2936
  /* Runs on the GLib main loop: emit the wake event there, so the runtime
@@ -3433,6 +3535,7 @@ int native_sdk_gtk_create_view(native_sdk_gtk_host_t *host, uint64_t window_id,
3433
3535
  native_sdk_gtk_window_t *win = native_sdk_find_window(host, window_id);
3434
3536
  if (!win || !win->stack_root || label_len == 0 || !native_sdk_valid_native_view_frame(x, y, width, height)) return 0;
3435
3537
  if (!native_sdk_is_supported_native_view_kind(kind)) return 0;
3538
+ if (!native_sdk_valid_native_view_strings(label_len, parent_len, role_len, accessibility_label_len, text_len, command_len)) return 0;
3436
3539
  if (win->native_view_count >= NATIVE_SDK_MAX_NATIVE_VIEWS) return 0;
3437
3540
 
3438
3541
  char *label_copy = native_sdk_strndup(label, label_len);
@@ -3620,6 +3723,12 @@ int native_sdk_gtk_present_gpu_surface_pixels(native_sdk_gtk_host_t *host, uint6
3620
3723
  }
3621
3724
 
3622
3725
  int native_sdk_gtk_update_view(native_sdk_gtk_host_t *host, uint64_t window_id, const char *label, size_t label_len, int has_frame, double x, double y, double width, double height, int has_layer, int layer, int has_visible, int visible, int has_enabled, int enabled, int has_role, const char *role, size_t role_len, int has_accessibility_label, const char *accessibility_label, size_t accessibility_label_len, int has_text, const char *text, size_t text_len, int has_command, const char *command, size_t command_len) {
3726
+ if (!native_sdk_valid_native_view_strings(label_len,
3727
+ 0,
3728
+ has_role ? role_len : 0,
3729
+ has_accessibility_label ? accessibility_label_len : 0,
3730
+ has_text ? text_len : 0,
3731
+ has_command ? command_len : 0)) return 0;
3623
3732
  native_sdk_gtk_window_t *win = native_sdk_find_window(host, window_id);
3624
3733
  char *label_copy = label_len > 0 ? native_sdk_strndup(label, label_len) : NULL;
3625
3734
  native_sdk_gtk_native_view_t *view = native_sdk_find_native_view(win, label_copy);