@native-sdk/cli 0.9.2 → 0.9.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 (65) hide show
  1. package/build/app.zig +273 -37
  2. package/build/ts_run.mjs +15 -18
  3. package/build.zig +141 -9
  4. package/package.json +13 -10
  5. package/packages/core/compile-surface/core.ts +1 -0
  6. package/packages/core/package-lock.json +16 -13
  7. package/packages/core/package.json +5 -2
  8. package/packages/core/scripts/compiler_command.mjs +71 -0
  9. package/packages/core/scripts/compiler_typecheck.mjs +4 -4
  10. package/packages/core/scripts/embed_markup_c.mjs +25 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +3 -3
  12. package/packages/core/scripts/run_external_core_compiler.mjs +4 -3
  13. package/packages/core/scripts/run_external_service_compiler.mjs +2 -1
  14. package/packages/core/sdk/core.ts +1 -0
  15. package/packages/core/sdk/events.d.ts +10 -0
  16. package/packages/core/sdk/events.ts +30 -5
  17. package/packages/core/sdk/text.d.ts +4 -0
  18. package/packages/core/sdk/text.ts +51 -0
  19. package/packages/core/src/checker.ts +61 -3
  20. package/packages/core/src/contract.ts +5 -4
  21. package/packages/core/src/devhost_journal.mjs +2 -2
  22. package/packages/core/src/diagnostics.ts +2 -2
  23. package/packages/core/src/service_contract.ts +10 -0
  24. package/packages/core/src/typed_ast.ts +9 -7
  25. package/packages/core/src/types.ts +28 -8
  26. package/skill-data/automation/SKILL.md +4 -3
  27. package/skill-data/native-ui/SKILL.md +5 -2
  28. package/skill-data/ts-core/SKILL.md +10 -4
  29. package/skill-data/ts-services/references/service-surface.md +1 -1
  30. package/src/app_runner/root.zig +208 -6
  31. package/src/app_runner/ts_core_main.zig +14 -4
  32. package/src/app_runner/ts_core_mobile.zig +6 -2
  33. package/src/automation/protocol.zig +5 -1
  34. package/src/automation/snapshot.zig +119 -0
  35. package/src/platform/macos/appkit_host.m +79 -12
  36. package/src/platform/macos/root.zig +68 -5
  37. package/src/primitives/canvas/events.zig +79 -1
  38. package/src/primitives/canvas/root.zig +1 -0
  39. package/src/primitives/canvas/text_interaction.zig +23 -0
  40. package/src/primitives/canvas/text_tests.zig +45 -0
  41. package/src/primitives/canvas/ui.zig +11 -8
  42. package/src/primitives/canvas/ui_markup_compiled_tests.zig +3 -0
  43. package/src/primitives/canvas/ui_markup_reflect.zig +6 -5
  44. package/src/primitives/canvas/ui_markup_view_tests.zig +18 -2
  45. package/src/primitives/canvas/ui_tests.zig +37 -0
  46. package/src/primitives/canvas/widget_builtin_tests.zig +13 -0
  47. package/src/runtime/automation_snapshot.zig +4 -0
  48. package/src/runtime/canvas_widget_control_tests.zig +2 -0
  49. package/src/runtime/canvas_widget_text_tests.zig +124 -0
  50. package/src/runtime/native_command_event_tests.zig +29 -0
  51. package/src/runtime/session_journal.zig +21 -2
  52. package/src/runtime/ts_ui_app.zig +184 -7
  53. package/src/runtime/ui_app.zig +98 -18
  54. package/src/runtime/ui_app_tests.zig +232 -13
  55. package/src/runtime/ui_app_window_tests.zig +23 -0
  56. package/src/runtime/view_widget_text.zig +1 -1
  57. package/src/tooling/templates.zig +6 -2
  58. package/src/tooling/ts_core.zig +1 -1
  59. package/src/tooling/verbs.zig +228 -0
  60. package/tools/corewire/emit.zig +31 -12
  61. package/tools/corewire/emit_facade.zig +57 -2
  62. package/tools/corewire/emit_profile.zig +20 -7
  63. package/tools/corewire/emit_service.zig +49 -24
  64. package/tools/corewire/main.zig +21 -2
  65. package/tools/corewire/shim_rt.zig +20 -0
@@ -231,6 +231,7 @@ export function windows(model: Model): readonly WindowDescriptor[] {
231
231
  title: asciiBytes("Settings"),
232
232
  width: 420,
233
233
  height: 240,
234
+ restorePolicy: "center_on_primary",
234
235
  resizable: false,
235
236
  closePolicy: "quit",
236
237
  onCloseCommand: asciiBytes("app.settings-closed"),
@@ -240,6 +241,8 @@ export function windows(model: Model): readonly WindowDescriptor[] {
240
241
 
241
242
  `closePolicy` is `"quit"` by default. Under `"quit"`, a user close really closes the window and routes `onCloseCommand` through `commandMsg`; map it to the Msg that clears the model's open flag. If the model keeps declaring the label, source wins and the next reconciliation recreates it. Under `"hide"`, the same native window and view stay alive, no close command fires, and `Cmd.showWindow("settings")` reveals it. Stopping the declaration always performs a real reconcile close. The platform safeguards for `hide` are the same as manifest windows. Model-declared secondary windows are desktop-only.
242
243
 
244
+ `restorePolicy` accepts `"clamp_to_visible_screen"` (the default) or `"center_on_primary"`. Model-declared windows do not restore persisted frames. On macOS, the latter centers a fresh descriptor with no `x`/`y` directly at native creation time; Windows and Linux currently keep their native default placement.
245
+
243
246
  `titlebar` accepts `"standard"`, `"hidden_inset"`, `"hidden_inset_tall"`, and `"chromeless"`. The last removes all OS chrome and is required when a transparent model-declared window targets Windows; provide working app-drawn close/minimize controls for that fully skinned shape.
244
247
 
245
248
  ### The init command
@@ -291,7 +294,7 @@ One caveat for node-side pokes: the build resolves the `@native-sdk/core*` speci
291
294
  - **`src/` is the boundary**: `../` escapes and absolute paths are taught (NS1034); bare npm specifiers are taught (NS1035 - vendor the code under `src/` or make the import `import type`). Only `@native-sdk/core` (the intrinsic Cmd/Sub/asciiBytes/utf8Bytes surface) and the SDK library modules below carry runtime meaning from outside.
292
295
  - **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the compile uniques them per module).
293
296
  - **No runtime import cycles** (NS1036). `import type` back-edges are legal and idiomatic: a helper module type-imports `Model` from `./core.ts` while `core.ts` runtime-imports the helpers - that is the expected shape, not a smell.
294
- - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), the model-derived launcher helpers (`themePack`/`statusItem`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
297
+ - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), the model-derived launcher helpers (`themeState`/`themePack`/`statusItem`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
295
298
  - **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`, `AudioCaptureState`/`AudioCaptureSource`/`AudioCaptureEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
296
299
 
297
300
  The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/chatbot` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
@@ -355,6 +358,8 @@ export type TextInputEvent =
355
358
  | { readonly kind: "delete_forward" }
356
359
  | { readonly kind: "delete_word_backward" }
357
360
  | { readonly kind: "delete_word_forward" }
361
+ | { readonly kind: "delete_to_start" }
362
+ | { readonly kind: "delete_to_line_start" }
358
363
  | { readonly kind: "clear" }
359
364
  | { readonly kind: "move_caret"; readonly move: TextCaretMove }
360
365
  | { readonly kind: "set_selection"; readonly selection: TextSelection }
@@ -392,6 +397,7 @@ The generated wiring detects each channel from an export (export exists → wire
392
397
 
393
398
  - **`commandMsg(name: string): Msg | null`** — menus, shortcuts, and chrome tabs, by command id (string equality works on `string` values).
394
399
  - **`statusItem(model: Model): StatusItemState` / `statusItems(model: Model): readonly StatusItemDescriptor[]`** — one complete menu-bar item, or a stable-id collection: live icon/tooltip/visibility/click hooks, presentation, and dropdown. The generated launcher reconciles after committed updates; import the exact records from `@native-sdk/core/events`.
400
+ - **`themeState(model: Model): ThemeState`** — the stock theme's model-owned pack, color scheme, and accent. Import `ThemeState` from `@native-sdk/core/events`; each field is optional (`pack`, `colorScheme`, `accent`). Omit a field to inherit app.zon, use `colorScheme: "system"` (or omit it) to follow the OS, and spell accents exactly `#rrggbb`. High contrast/reduced motion remain system-owned and high contrast suppresses accents. `themePack(model)` remains the pack-only compatibility helper; export one or the other, never both. Complete `tokens_fn`/`tokens` wiring takes precedence. Forced scheme applies to canvas tokens in v1; native chrome and WebViews remain OS-themed.
395
401
  - **`windows(model: Model): readonly WindowDescriptor[]`** — the model-declared secondary-window set. The launcher compiles `src/windows/<label>.native`, reconciles descriptor presence after committed updates, projects `closePolicy`, and routes a `.quit` `onCloseCommand` through `commandMsg`.
396
402
  - **`frameMsg(model: Model, frame: FrameEvent): Msg | null`** — presented frames. `FrameEvent` is exactly `{ width, height, timestampMs, intervalMs }` numbers (canvas points; fractional milliseconds). Return null for frames that change nothing — the idle law holds exactly when an idle app dispatches nothing (a frame arm that always returns a Msg would spin the loop at full frame rate). The installing frame is excluded; the first PRESENTED frame corrects any seeded value.
397
403
  - **`keyMsg(key: KeyEvent): Msg | null`** — the app-level key FALLBACK (a focused widget's own keys and editable text always win first). `KeyEvent` is exactly `{ key: string; shift: boolean; control: boolean; alt: boolean; super: boolean }`; the key NAME arrives lowercased (`key.key === "space"`).
@@ -441,7 +447,7 @@ Every diagnostic carries one of these IDs plus the fix and the why, and every ru
441
447
  - **NS1031 exported model helpers join the model's binding surface.** An exported single-Model-parameter helper becomes a Model declaration markup binds (`doneCount` → `{doneCount}`); two members with one binding name would be ambiguous — rename one.
442
448
  - **NS1032 viewUnbound names update-only model state.** `export const viewUnbound = [...] as const` entries must be string literals naming Model fields, exported model helpers, or Msg kinds — by their TypeScript spellings (`"nextId"`); anything else would silence nothing and hide a typo.
443
449
  - **NS1030 effect arguments respect the engine's limits.** A compile-time-knowable value outside an engine bound (a path literal over 1024 bytes, a URL literal over 2 KiB, more than 8 headers, a header block over 1 KiB, a delay literal outside 1ms..one year) stops the build instead of shipping a guaranteed runtime rejection. Dynamic values stay the engine's to validate — they surface through the `err` arm.
444
- - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm; `themePack`, `statusItem`, `statusItems`, and `windows` return their exact model-derived shell shapes. The generated wiring builds these host values structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
450
+ - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm; `themeState`, `themePack`, `statusItem`, `statusItems`, and `windows` return their exact model-derived shell shapes. The generated wiring builds these host values structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
445
451
  - **NS1034 core imports stay inside src/.** `../` escapes and absolute paths are rejected: the entry module's directory is the core's whole world - the build ships exactly that tree.
446
452
  - **NS1035 npm packages do not run inside a core.** No JS engine ships in the binary; vendor the logic under `src/` or make the import type-only.
447
453
  - **NS1036 core modules do not import in a cycle.** Runtime cycles only work through JS live-binding indirection; hoist shared declarations, or make the back-edge `import type` (which is exempt and idiomatic).
@@ -547,7 +553,7 @@ export function update(model: Model, msg: Msg): Model {
547
553
 
548
554
  ## Running a core as an app
549
555
 
550
- A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut/status-item/window-close command events as Msgs). A core can also export `themePack(model: Model): ThemePack`, either status-item helper, and `windows(model): readonly WindowDescriptor[]`; the adapter wires the matching UiApp seams, while the generated launcher supplies secondary views from `src/windows/<label>.native`. The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
556
+ A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut/status-item/window-close command events as Msgs). A core can also export `themeState(model: Model): ThemeState` (or legacy pack-only `themePack`), either status-item helper, and `windows(model): readonly WindowDescriptor[]`; the adapter wires the matching UiApp seams, while the generated launcher supplies secondary views from `src/windows/<label>.native`. The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
551
557
 
552
558
  The compiled core runs as a full desktop app through `native_sdk.TsUiApp(core)` — the committed TS model IS the app model, no shim, no glue:
553
559
 
@@ -567,7 +573,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
567
573
  });
568
574
  ```
569
575
 
570
- - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically. It likewise wires `theme_fn` from `themePack(model)` and the singular `status_item_fn` or collection `status_items_fn` from the matching helper. A wiring that also sets one of those seams is a teaching panic. Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
576
+ - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically. It likewise wires `theme_state_fn` from `themeState(model)` or `theme_fn` from legacy `themePack(model)`, and the singular `status_item_fn` or collection `status_items_fn` from the matching helper. A wiring that also sets one of those seams is a teaching panic. Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
571
577
  - Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the core's model keeps the TS spellings). Record arrays iterate with `<for each="tasks" as="t" key="id">` and items bind their fields (`{t.title}`); optional scalars gate with `<if test="{selected}">` (null is falsy); string-literal unions bind as their member name (`{filter}` renders `all` — compare against a quoted literal, `selected="{sortKey == 'cpu'}"`); exported single-model helpers bind as derived values (`{doneCount}`) and slice-returning ones drive `for each`. Markup `<chart>` series bind number arrays too — `<series kind="bar" values="{cpuSpark}" />` over a field or helper returning `readonly number[]` (f64, narrowed per sample into the chart pipeline); pad a filling window's leading gap with `NaN` samples, which draw nothing.
572
578
  - `Options.sync` does not exist for TS apps (a committed model cannot be mutated in place): keep continuous controls model-driven — bind the widget's value and echo `on-change`/`on-scroll` Msgs back into the model.
573
579
  - One live app per core module per process: two apps over the SAME core would share one committed root — and a process carries ONE compiled core (the archive owns a fixed-prefix C ABI symbol set).
@@ -6,7 +6,7 @@
6
6
  Verify without writing:
7
7
  node packages/core/scripts/gen_service_surface.mjs --check -->
8
8
 
9
- # Service compile surface — scriptc 0.0.31
9
+ # Service compile surface — scriptc 0.0.33
10
10
 
11
11
  What TypeScript under `src/services/` can use, as stated by the pinned
12
12
  compiler itself (surface manifest schema 1, 527 entries:
@@ -4,7 +4,9 @@ const native_sdk = @import("native_sdk");
4
4
  const app_manifest = @import("app_manifest_zon");
5
5
  const built_relational_migrations = @import("relational_migrations");
6
6
  const window_placement = @import("window_placement.zig");
7
+ const manifest_commands = if (@hasField(@TypeOf(app_manifest), "commands")) app_manifest.commands else .{};
7
8
  const manifest_shortcuts = if (@hasField(@TypeOf(app_manifest), "shortcuts")) app_manifest.shortcuts else .{};
9
+ const manifest_menus = if (@hasField(@TypeOf(app_manifest), "menus")) app_manifest.menus else .{};
8
10
  const manifest_windows = if (@hasField(@TypeOf(app_manifest), "windows")) app_manifest.windows else .{};
9
11
 
10
12
  fn manifestImagePixelBudget() usize {
@@ -62,7 +64,8 @@ pub const RunOptions = struct {
62
64
  builtin_bridge: native_sdk.BridgePolicy = .{},
63
65
  js_window_api: bool = false,
64
66
  security: native_sdk.SecurityPolicy = .{},
65
- menus: []const native_sdk.Menu = &.{},
67
+ commands: ?[]const native_sdk.Command = null,
68
+ menus: ?[]const native_sdk.Menu = null,
66
69
  shortcuts: ?[]const native_sdk.Shortcut = null,
67
70
  /// Filled by `runWithOptions` from the manifest capability. App entry
68
71
  /// points do not set this themselves; the field only carries the owned
@@ -142,6 +145,72 @@ pub const RunOptions = struct {
142
145
  fn resolvedShortcuts(self: RunOptions, storage: *ShortcutStorage) []const native_sdk.Shortcut {
143
146
  return self.shortcuts orelse storage.fromManifest();
144
147
  }
148
+
149
+ fn resolvedCommands(self: RunOptions, storage: *CommandStorage) []const native_sdk.Command {
150
+ return self.commands orelse storage.fromManifest();
151
+ }
152
+
153
+ fn resolvedMenus(self: RunOptions, storage: *MenuStorage) []const native_sdk.Menu {
154
+ return self.menus orelse storage.fromManifest();
155
+ }
156
+ };
157
+
158
+ const CommandStorage = struct {
159
+ commands: [native_sdk.app_manifest.max_commands]native_sdk.Command = undefined,
160
+
161
+ fn fromManifest(self: *CommandStorage) []const native_sdk.Command {
162
+ comptime {
163
+ if (manifest_commands.len > native_sdk.app_manifest.max_commands) {
164
+ @compileError("app.zon defines too many commands");
165
+ }
166
+ }
167
+
168
+ inline for (manifest_commands, 0..) |command, index| {
169
+ self.commands[index] = .{
170
+ .id = command.id,
171
+ .title = if (@hasField(@TypeOf(command), "title")) command.title else "",
172
+ .enabled = if (@hasField(@TypeOf(command), "enabled")) command.enabled else true,
173
+ .checked = if (@hasField(@TypeOf(command), "checked")) command.checked else false,
174
+ };
175
+ }
176
+ return self.commands[0..manifest_commands.len];
177
+ }
178
+ };
179
+
180
+ const MenuStorage = struct {
181
+ menus: [native_sdk.platform.max_menus]native_sdk.Menu = undefined,
182
+ items: [native_sdk.platform.max_menu_items]native_sdk.MenuItem = undefined,
183
+
184
+ fn fromManifest(self: *MenuStorage) []const native_sdk.Menu {
185
+ comptime {
186
+ if (manifest_menus.len > native_sdk.platform.max_menus) {
187
+ @compileError("app.zon defines too many menus");
188
+ }
189
+ var item_count: usize = 0;
190
+ for (manifest_menus) |menu| {
191
+ const items = if (@hasField(@TypeOf(menu), "items")) menu.items else .{};
192
+ item_count += items.len;
193
+ }
194
+ if (item_count > native_sdk.platform.max_menu_items) {
195
+ @compileError("app.zon defines too many menu items");
196
+ }
197
+ }
198
+
199
+ var item_index: usize = 0;
200
+ inline for (manifest_menus, 0..) |menu, menu_index| {
201
+ const items = if (@hasField(@TypeOf(menu), "items")) menu.items else .{};
202
+ const first_item = item_index;
203
+ inline for (items) |item| {
204
+ self.items[item_index] = menuItem(item);
205
+ item_index += 1;
206
+ }
207
+ self.menus[menu_index] = .{
208
+ .title = menu.title,
209
+ .items = self.items[first_item..item_index],
210
+ };
211
+ }
212
+ return self.menus[0..manifest_menus.len];
213
+ }
145
214
  };
146
215
 
147
216
  const ShortcutStorage = struct {
@@ -558,6 +627,18 @@ fn manifestDeclaresCredentials() bool {
558
627
  return false;
559
628
  }
560
629
 
630
+ fn menuItem(comptime item: anytype) native_sdk.MenuItem {
631
+ return .{
632
+ .label = if (@hasField(@TypeOf(item), "label")) item.label else "",
633
+ .command = if (@hasField(@TypeOf(item), "command")) item.command else "",
634
+ .key = if (@hasField(@TypeOf(item), "key")) item.key else "",
635
+ .modifiers = shortcutModifiers(item),
636
+ .separator = if (@hasField(@TypeOf(item), "separator")) item.separator else false,
637
+ .enabled = if (@hasField(@TypeOf(item), "enabled")) item.enabled else true,
638
+ .checked = if (@hasField(@TypeOf(item), "checked")) item.checked else false,
639
+ };
640
+ }
641
+
561
642
  fn shortcutModifiers(comptime shortcut: anytype) native_sdk.ShortcutModifiers {
562
643
  const values = if (@hasField(@TypeOf(shortcut), "modifiers")) shortcut.modifiers else .{};
563
644
  var modifiers: native_sdk.ShortcutModifiers = .{};
@@ -697,6 +778,10 @@ fn runNull(app: native_sdk.App, options: RunOptions, init: std.process.Init) !vo
697
778
  runtime_trace_sink = filtered_trace_sink.sink();
698
779
  var shortcut_storage: ShortcutStorage = .{};
699
780
  const shortcuts = options.resolvedShortcuts(&shortcut_storage);
781
+ var menu_storage: MenuStorage = .{};
782
+ const menus = options.resolvedMenus(&menu_storage);
783
+ var command_storage: CommandStorage = .{};
784
+ const commands = options.resolvedCommands(&command_storage);
700
785
  // The Runtime is multi-megabyte; Linux's default 8 MB main-thread
701
786
  // stack overflows on a stack instance, so construct it on the heap.
702
787
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
@@ -717,7 +802,8 @@ fn runNull(app: native_sdk.App, options: RunOptions, init: std.process.Init) !vo
717
802
  .web_layer = webLayerEnabled(),
718
803
  .gpu_surface_frame_diagnostics = false,
719
804
  .security = options.security,
720
- .menus = options.menus,
805
+ .commands = commands,
806
+ .menus = menus,
721
807
  .shortcuts = shortcuts,
722
808
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
723
809
  .window_state_store = store,
@@ -766,6 +852,10 @@ fn runMacos(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
766
852
  runtime_trace_sink = filtered_trace_sink.sink();
767
853
  var shortcut_storage: ShortcutStorage = .{};
768
854
  const shortcuts = options.resolvedShortcuts(&shortcut_storage);
855
+ var menu_storage: MenuStorage = .{};
856
+ const menus = options.resolvedMenus(&menu_storage);
857
+ var command_storage: CommandStorage = .{};
858
+ const commands = options.resolvedCommands(&command_storage);
769
859
  // The Runtime is multi-megabyte; Linux's default 8 MB main-thread
770
860
  // stack overflows on a stack instance, so construct it on the heap.
771
861
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
@@ -786,7 +876,8 @@ fn runMacos(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
786
876
  .web_layer = webLayerEnabled(),
787
877
  .gpu_surface_frame_diagnostics = false,
788
878
  .security = options.security,
789
- .menus = options.menus,
879
+ .commands = commands,
880
+ .menus = menus,
790
881
  .shortcuts = shortcuts,
791
882
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
792
883
  .window_state_store = store,
@@ -832,6 +923,10 @@ fn runLinux(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
832
923
  runtime_trace_sink = filtered_trace_sink.sink();
833
924
  var shortcut_storage: ShortcutStorage = .{};
834
925
  const shortcuts = options.resolvedShortcuts(&shortcut_storage);
926
+ var menu_storage: MenuStorage = .{};
927
+ const menus = options.resolvedMenus(&menu_storage);
928
+ var command_storage: CommandStorage = .{};
929
+ const commands = options.resolvedCommands(&command_storage);
835
930
  // The Runtime is multi-megabyte; Linux's default 8 MB main-thread
836
931
  // stack overflows on a stack instance, so construct it on the heap.
837
932
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
@@ -852,7 +947,8 @@ fn runLinux(app: native_sdk.App, options: RunOptions, init: std.process.Init) !v
852
947
  .web_layer = webLayerEnabled(),
853
948
  .gpu_surface_frame_diagnostics = false,
854
949
  .security = options.security,
855
- .menus = options.menus,
950
+ .commands = commands,
951
+ .menus = menus,
856
952
  .shortcuts = shortcuts,
857
953
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
858
954
  .window_state_store = store,
@@ -897,6 +993,10 @@ fn runWindows(app: native_sdk.App, options: RunOptions, init: std.process.Init)
897
993
  runtime_trace_sink = filtered_trace_sink.sink();
898
994
  var shortcut_storage: ShortcutStorage = .{};
899
995
  const shortcuts = options.resolvedShortcuts(&shortcut_storage);
996
+ var menu_storage: MenuStorage = .{};
997
+ const menus = options.resolvedMenus(&menu_storage);
998
+ var command_storage: CommandStorage = .{};
999
+ const commands = options.resolvedCommands(&command_storage);
900
1000
  // The Runtime is multi-megabyte; Linux's default 8 MB main-thread
901
1001
  // stack overflows on a stack instance, so construct it on the heap.
902
1002
  const runtime = try std.heap.page_allocator.create(native_sdk.Runtime);
@@ -917,7 +1017,8 @@ fn runWindows(app: native_sdk.App, options: RunOptions, init: std.process.Init)
917
1017
  .web_layer = webLayerEnabled(),
918
1018
  .gpu_surface_frame_diagnostics = false,
919
1019
  .security = options.security,
920
- .menus = options.menus,
1020
+ .commands = commands,
1021
+ .menus = menus,
921
1022
  .shortcuts = shortcuts,
922
1023
  .automation = if (build_options.automation) native_sdk.automation.Server.init(init.io, ".zig-cache/native-sdk-automation", app_info.resolvedWindowTitle()) else null,
923
1024
  .window_state_store = store,
@@ -1058,6 +1159,12 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
1058
1159
  // (and disarm the producer wake bindings) before the runtime
1059
1160
  // storage itself goes.
1060
1161
  defer runtime.deinit();
1162
+ var shortcut_storage: ShortcutStorage = .{};
1163
+ const shortcuts = options.resolvedShortcuts(&shortcut_storage);
1164
+ var menu_storage: MenuStorage = .{};
1165
+ const menus = options.resolvedMenus(&menu_storage);
1166
+ var command_storage: CommandStorage = .{};
1167
+ const commands = options.resolvedCommands(&command_storage);
1061
1168
  // Bridge policy and security must match what the recording ran
1062
1169
  // under (they gate replayed bridge_message dispatch); automation,
1063
1170
  // window-state restore, and tracing stay off — replay consumes only
@@ -1070,7 +1177,9 @@ fn runSessionReplay(app: native_sdk.App, options: RunOptions, init: std.process.
1070
1177
  .js_window_api = options.js_window_api,
1071
1178
  .web_layer = webLayerEnabled(),
1072
1179
  .security = options.security,
1073
- .menus = options.menus,
1180
+ .commands = commands,
1181
+ .menus = menus,
1182
+ .shortcuts = shortcuts,
1074
1183
  });
1075
1184
 
1076
1185
  const verify = if (init.environ_map.get("NATIVE_SDK_SESSION_VERIFY")) |value|
@@ -1142,6 +1251,99 @@ fn webEngine() native_sdk.WebEngine {
1142
1251
  return .system;
1143
1252
  }
1144
1253
 
1254
+ test "RunOptions resolves manifest commands menus and shortcuts" {
1255
+ const options: RunOptions = .{
1256
+ .app_name = "runner-fixture",
1257
+ .bundle_id = "dev.native_sdk.runner_fixture",
1258
+ };
1259
+
1260
+ var command_storage: CommandStorage = .{};
1261
+ const commands = options.resolvedCommands(&command_storage);
1262
+ try std.testing.expectEqual(@as(usize, 2), commands.len);
1263
+ try std.testing.expectEqualStrings("app.refresh", commands[0].id);
1264
+ try std.testing.expectEqualStrings("Refresh", commands[0].title);
1265
+ try std.testing.expect(!commands[0].enabled);
1266
+ try std.testing.expect(commands[0].checked);
1267
+ try std.testing.expectEqualStrings("app.defaults", commands[1].id);
1268
+ try std.testing.expectEqualStrings("", commands[1].title);
1269
+ try std.testing.expect(commands[1].enabled);
1270
+ try std.testing.expect(!commands[1].checked);
1271
+
1272
+ var menu_storage: MenuStorage = .{};
1273
+ const menus = options.resolvedMenus(&menu_storage);
1274
+ try std.testing.expectEqual(@as(usize, 2), menus.len);
1275
+ try std.testing.expectEqualStrings("View", menus[0].title);
1276
+ try std.testing.expectEqual(@as(usize, 3), menus[0].items.len);
1277
+ try std.testing.expectEqualStrings("Refresh", menus[0].items[0].label);
1278
+ try std.testing.expectEqualStrings("app.refresh", menus[0].items[0].command);
1279
+ try std.testing.expectEqualStrings("r", menus[0].items[0].key);
1280
+ try std.testing.expect(menus[0].items[0].modifiers.option);
1281
+ try std.testing.expect(menus[0].items[0].modifiers.shift);
1282
+ try std.testing.expect(!menus[0].items[0].enabled);
1283
+ try std.testing.expect(menus[0].items[0].checked);
1284
+ try std.testing.expect(menus[0].items[1].separator);
1285
+ try std.testing.expectEqualStrings("Defaults", menus[0].items[2].label);
1286
+ try std.testing.expect(menus[0].items[2].enabled);
1287
+ try std.testing.expect(!menus[0].items[2].checked);
1288
+ try std.testing.expectEqualStrings("Help", menus[1].title);
1289
+ try std.testing.expectEqual(@as(usize, 0), menus[1].items.len);
1290
+
1291
+ var shortcut_storage: ShortcutStorage = .{};
1292
+ const shortcuts = options.resolvedShortcuts(&shortcut_storage);
1293
+ try std.testing.expectEqual(@as(usize, 1), shortcuts.len);
1294
+ try std.testing.expectEqualStrings("app.refresh", shortcuts[0].id);
1295
+ try std.testing.expectEqualStrings("r", shortcuts[0].key);
1296
+ try std.testing.expect(shortcuts[0].modifiers.primary);
1297
+ }
1298
+
1299
+ test "RunOptions explicit command menu and shortcut slices override manifest values" {
1300
+ const override_commands = [_]native_sdk.Command{
1301
+ .{ .id = "override.command", .title = "Override Command" },
1302
+ };
1303
+ const override_items = [_]native_sdk.MenuItem{
1304
+ .{ .label = "Override Item", .command = "override.command" },
1305
+ };
1306
+ const override_menus = [_]native_sdk.Menu{
1307
+ .{ .title = "Override Menu", .items = &override_items },
1308
+ };
1309
+ const override_shortcuts = [_]native_sdk.Shortcut{
1310
+ .{ .id = "override.command", .key = "o", .modifiers = .{ .primary = true } },
1311
+ };
1312
+ const options: RunOptions = .{
1313
+ .app_name = "runner-fixture",
1314
+ .bundle_id = "dev.native_sdk.runner_fixture",
1315
+ .commands = &override_commands,
1316
+ .menus = &override_menus,
1317
+ .shortcuts = &override_shortcuts,
1318
+ };
1319
+
1320
+ var command_storage: CommandStorage = .{};
1321
+ const commands = options.resolvedCommands(&command_storage);
1322
+ try std.testing.expectEqual(@as(usize, 1), commands.len);
1323
+ try std.testing.expectEqualStrings("override.command", commands[0].id);
1324
+
1325
+ var menu_storage: MenuStorage = .{};
1326
+ const menus = options.resolvedMenus(&menu_storage);
1327
+ try std.testing.expectEqual(@as(usize, 1), menus.len);
1328
+ try std.testing.expectEqualStrings("Override Menu", menus[0].title);
1329
+
1330
+ var shortcut_storage: ShortcutStorage = .{};
1331
+ const shortcuts = options.resolvedShortcuts(&shortcut_storage);
1332
+ try std.testing.expectEqual(@as(usize, 1), shortcuts.len);
1333
+ try std.testing.expectEqualStrings("override.command", shortcuts[0].id);
1334
+
1335
+ const empty_options: RunOptions = .{
1336
+ .app_name = "runner-fixture",
1337
+ .bundle_id = "dev.native_sdk.runner_fixture",
1338
+ .commands = &.{},
1339
+ .menus = &.{},
1340
+ .shortcuts = &.{},
1341
+ };
1342
+ try std.testing.expectEqual(@as(usize, 0), empty_options.resolvedCommands(&command_storage).len);
1343
+ try std.testing.expectEqual(@as(usize, 0), empty_options.resolvedMenus(&menu_storage).len);
1344
+ try std.testing.expectEqual(@as(usize, 0), empty_options.resolvedShortcuts(&shortcut_storage).len);
1345
+ }
1346
+
1145
1347
  const StateBuffers = struct {
1146
1348
  state_dir: [1024]u8 = undefined,
1147
1349
  file_path: [1200]u8 = undefined,
@@ -1,7 +1,8 @@
1
1
  //! The generated wiring for a TypeScript app core — staged (never written
2
2
  //! into the app) by the framework build when the tree carries src/core.ts:
3
- //! the build transpiles the core beside this file as core.zig, copies the
4
- //! app's src/app.native beside it too, and roots the app module here. The
3
+ //! the build transpiles the core beside this file as core.zig, links the
4
+ //! app's src/app.native as an isolated data object, and roots the app module
5
+ //! here. The
5
6
  //! app tree stays three files of truth — core.ts (logic), app.native
6
7
  //! (view), app.zon (manifest) — and every value below derives from them at
7
8
  //! comptime:
@@ -79,7 +80,14 @@ const App = Adapter.App;
79
80
 
80
81
  const shell_scene = native_sdk.app_manifest.shellConfigFrom(manifest);
81
82
  const canvas_label = native_sdk.app_manifest.firstGpuSurfaceLabel(shell_scene);
82
- pub const app_markup = @embedFile("app.native");
83
+ extern const native_sdk_app_markup: u8;
84
+ extern const native_sdk_app_markup_len: usize;
85
+
86
+ /// Primary markup is linked as a data object so changing it does not dirty
87
+ /// this Zig module's already-compiled SDK/app graph.
88
+ pub fn appMarkup() []const u8 {
89
+ return @as([*]const u8, @ptrCast(&native_sdk_app_markup))[0..native_sdk_app_markup_len];
90
+ }
83
91
 
84
92
  const app_permissions = manifestStringList(manifest, "permissions");
85
93
  const allowed_origins = manifestAllowedOrigins();
@@ -90,7 +98,7 @@ pub fn main(init: std.process.Init) !void {
90
98
  .name = manifest.name,
91
99
  .scene = shell_scene,
92
100
  .canvas_label = canvas_label,
93
- .markup = .{ .source = app_markup, .watch_path = "src/app.native", .io = init.io },
101
+ .markup = .{ .source = appMarkup(), .watch_path = "src/app.native", .io = init.io },
94
102
  // app.zon's theme pack; unthemed manifests get the house register.
95
103
  // The stock tokens compose the pack with the LIVE system
96
104
  // appearance, so TS apps follow the OS light/dark flip with no
@@ -477,6 +485,7 @@ fn manifestPersistDebounce(comptime config: anytype) u32 {
477
485
  }
478
486
 
479
487
  fn validatePersistRoutes(comptime routes: anytype) void {
488
+ @setEvalBranchQuota(Adapter.persist_route_scan_quota);
480
489
  if (!persistRouteMatches(routes.ok, void)) {
481
490
  @compileError("app.zon .persist.restore.ok must name a void Msg arm in src/core.ts");
482
491
  }
@@ -489,6 +498,7 @@ fn validatePersistRoutes(comptime routes: anytype) void {
489
498
  }
490
499
 
491
500
  fn persistRouteMatches(comptime name: []const u8, comptime Payload: type) bool {
501
+ @setEvalBranchQuota(Adapter.msg_scan_quota);
492
502
  const info = @typeInfo(core.Msg);
493
503
  if (info != .@"union") return false;
494
504
  inline for (info.@"union".fields) |field| {
@@ -46,7 +46,11 @@ const Adapter = native_sdk.TsUiApp(core);
46
46
  pub const Model = core.Model;
47
47
  pub const Msg = core.Msg;
48
48
 
49
- pub const app_markup = @embedFile("app.native");
49
+ extern const native_sdk_app_markup: u8;
50
+ extern const native_sdk_app_markup_len: usize;
51
+ pub fn appMarkup() []const u8 {
52
+ return @as([*]const u8, @ptrCast(&native_sdk_app_markup))[0..native_sdk_app_markup_len];
53
+ }
50
54
 
51
55
  comptime {
52
56
  // The build graph resolves the carrier before staging this file; a
@@ -97,7 +101,7 @@ pub fn mobileOptions() Adapter.Options {
97
101
  .name = manifest.name,
98
102
  .scene = mobile_scene,
99
103
  .canvas_label = native_sdk.embed.mobile_gpu_surface_label,
100
- .markup = .{ .source = app_markup },
104
+ .markup = .{ .source = appMarkup() },
101
105
  // app.zon's theme pack and one-accent override, same as desktop.
102
106
  .theme = comptime manifestThemePack(),
103
107
  .theme_accent = comptime manifestThemeAccent(),
@@ -55,7 +55,11 @@ pub const fingerprint: u64 = layout_fingerprint.hash(layoutDescription(semantic_
55
55
  /// visibility, and `tray-action` gained the explicit
56
56
  /// `<status-item-id> <menu-item-id>` form (the old one-id primary-item
57
57
  /// shorthand remains valid).
58
- pub const semantic_epoch: u32 = 2;
58
+ /// Epoch 3: automation snapshots expose the app menus configured on the
59
+ /// runtime, including command ids and enabled/checked/key state.
60
+ /// Epoch 4: command and app-menu catalog strings in snapshots use
61
+ /// JSON-style escapes so every catalog entry remains exactly one line.
62
+ pub const semantic_epoch: u32 = 4;
59
63
 
60
64
  /// The canonical description the protocol fingerprint hashes: the
61
65
  /// command vocabulary (the `Action` enum, reflected — names and values,
@@ -1,5 +1,6 @@
1
1
  const std = @import("std");
2
2
  const geometry = @import("geometry");
3
+ const app_manifest = @import("app_manifest");
3
4
  const platform = @import("../platform/root.zig");
4
5
  const protocol = @import("protocol.zig");
5
6
 
@@ -290,6 +291,12 @@ pub const Input = struct {
290
291
  windows: []const Window,
291
292
  views: []const platform.ViewInfo = &.{},
292
293
  widgets: []const Widget = &.{},
294
+ /// Static command and app-menu catalogs configured on the runtime.
295
+ /// These receipts let automation prove generated/ejected runners
296
+ /// loaded their manifest declarations before injecting command-source
297
+ /// events that cannot drive an OS menu tracking loop directly.
298
+ commands: []const app_manifest.Command = &.{},
299
+ menus: []const platform.Menu = &.{},
293
300
  diagnostics: Diagnostics = .{},
294
301
  /// Per-stage frame timing, non-null while `profile on` is active —
295
302
  /// printed as the `frame_profile` line right after the header.
@@ -595,6 +602,40 @@ pub fn writeText(input: Input, writer: anytype) !void {
595
602
  try writeWidgetContextMenu(widget, writer);
596
603
  try writer.writeByte('\n');
597
604
  }
605
+ for (input.commands) |command| {
606
+ try writer.writeAll("command id=");
607
+ try writeQuotedSnapshotText(command.id, writer);
608
+ try writer.writeAll(" title=");
609
+ try writeQuotedSnapshotText(command.title, writer);
610
+ try writer.print(" enabled={any} checked={any}\n", .{ command.enabled, command.checked });
611
+ }
612
+ for (input.menus) |menu| {
613
+ try writer.writeAll("app-menu title=");
614
+ try writeQuotedSnapshotText(menu.title, writer);
615
+ try writer.print(" items={d}\n", .{menu.items.len});
616
+ for (menu.items) |item| {
617
+ if (item.separator) {
618
+ try writer.writeAll(" app-menu-item separator\n");
619
+ continue;
620
+ }
621
+ try writer.writeAll(" app-menu-item label=");
622
+ try writeQuotedSnapshotText(item.label, writer);
623
+ try writer.writeAll(" command=");
624
+ try writeQuotedSnapshotText(item.command, writer);
625
+ try writer.print(" enabled={any} checked={any} key=", .{
626
+ item.enabled,
627
+ item.checked,
628
+ });
629
+ try writeQuotedSnapshotText(item.key, writer);
630
+ try writer.print(" modifiers=(primary={any},command={any},control={any},option={any},shift={any})\n", .{
631
+ item.modifiers.primary,
632
+ item.modifiers.command,
633
+ item.modifiers.control,
634
+ item.modifiers.option,
635
+ item.modifiers.shift,
636
+ });
637
+ }
638
+ }
598
639
  for (input.trays) |tray| {
599
640
  try writer.print("tray #{d} title=\"{s}\" visible={any} items={d}\n", .{ tray.id, tray.title, tray.visible, tray.items.len });
600
641
  for (tray.items) |item| {
@@ -726,6 +767,31 @@ pub fn writeA11yText(input: Input, writer: anytype) !void {
726
767
  }
727
768
  }
728
769
 
770
+ /// Catalog values are user-authored but snapshots are line-oriented. Keep
771
+ /// each configured command/menu record on exactly one line and preserve its
772
+ /// byte identity with JSON-style escapes for delimiters and control bytes.
773
+ fn writeQuotedSnapshotText(value: []const u8, writer: anytype) !void {
774
+ const hex = "0123456789abcdef";
775
+ try writer.writeByte('"');
776
+ for (value) |byte| {
777
+ switch (byte) {
778
+ '"' => try writer.writeAll("\\\""),
779
+ '\\' => try writer.writeAll("\\\\"),
780
+ '\n' => try writer.writeAll("\\n"),
781
+ '\r' => try writer.writeAll("\\r"),
782
+ '\t' => try writer.writeAll("\\t"),
783
+ else => if (byte < 0x20 or byte == 0x7f) {
784
+ try writer.writeAll("\\u00");
785
+ try writer.writeByte(hex[byte >> 4]);
786
+ try writer.writeByte(hex[byte & 0x0f]);
787
+ } else {
788
+ try writer.writeByte(byte);
789
+ },
790
+ }
791
+ }
792
+ try writer.writeByte('"');
793
+ }
794
+
729
795
  fn writeWidgetParent(widget: Widget, writer: anytype) !void {
730
796
  if (widget.parent_id) |parent_id| try writer.print(" parent=#{d}", .{parent_id});
731
797
  }
@@ -942,6 +1008,59 @@ test "snapshot emits tray title and dropdown items" {
942
1008
  try std.testing.expect(std.mem.indexOf(u8, empty_writer.buffered(), "tray") == null);
943
1009
  }
944
1010
 
1011
+ test "snapshot emits configured command and app-menu catalogs" {
1012
+ var buffer: [2048]u8 = undefined;
1013
+ var writer = std.Io.Writer.fixed(&buffer);
1014
+ const windows = [_]Window{.{ .title = "Test", .bounds = geometry.RectF.init(0, 0, 100, 100) }};
1015
+ const commands = [_]app_manifest.Command{
1016
+ .{ .id = "app.refresh", .title = "Refresh" },
1017
+ };
1018
+ const items = [_]platform.MenuItem{
1019
+ .{ .label = "Refresh", .command = "app.refresh", .key = "r", .modifiers = .{ .primary = true } },
1020
+ .{ .separator = true },
1021
+ };
1022
+ const menus = [_]platform.Menu{
1023
+ .{ .title = "View", .items = &items },
1024
+ };
1025
+ try writeText(.{
1026
+ .windows = &windows,
1027
+ .commands = &commands,
1028
+ .menus = &menus,
1029
+ }, &writer);
1030
+ const text = writer.buffered();
1031
+ try std.testing.expect(std.mem.indexOf(u8, text, "\ncommand id=\"app.refresh\" title=\"Refresh\" enabled=true checked=false\n") != null);
1032
+ try std.testing.expect(std.mem.indexOf(u8, text, "app-menu title=\"View\" items=2\n") != null);
1033
+ try std.testing.expect(std.mem.indexOf(u8, text, " app-menu-item label=\"Refresh\" command=\"app.refresh\" enabled=true checked=false key=\"r\" modifiers=(primary=true,command=false,control=false,option=false,shift=false)\n") != null);
1034
+ try std.testing.expect(std.mem.indexOf(u8, text, " app-menu-item separator\n") != null);
1035
+ }
1036
+
1037
+ test "snapshot escapes hostile command and app-menu catalog text" {
1038
+ var buffer: [2048]u8 = undefined;
1039
+ var writer = std.Io.Writer.fixed(&buffer);
1040
+ const windows = [_]Window{.{ .title = "Test", .bounds = geometry.RectF.init(0, 0, 100, 100) }};
1041
+ const commands = [_]app_manifest.Command{
1042
+ .{ .id = "app.\"quoted", .title = "Line 1\nLine 2\\tail\t\x01\x7f Café" },
1043
+ };
1044
+ const items = [_]platform.MenuItem{
1045
+ .{ .label = "Open \"now\"\rnext\\", .command = "app.\"run", .key = "r\t" },
1046
+ };
1047
+ const menus = [_]platform.Menu{
1048
+ .{ .title = "Tools\"\nInjected", .items = &items },
1049
+ };
1050
+ try writeText(.{
1051
+ .windows = &windows,
1052
+ .commands = &commands,
1053
+ .menus = &menus,
1054
+ }, &writer);
1055
+ const text = writer.buffered();
1056
+ try std.testing.expect(std.mem.indexOf(u8, text, "\ncommand id=\"app.\\\"quoted\" title=\"Line 1\\nLine 2\\\\tail\\t\\u0001\\u007f Café\" enabled=true checked=false\n") != null);
1057
+ try std.testing.expect(std.mem.indexOf(u8, text, "app-menu title=\"Tools\\\"\\nInjected\" items=1\n") != null);
1058
+ try std.testing.expect(std.mem.indexOf(u8, text, " app-menu-item label=\"Open \\\"now\\\"\\rnext\\\\\" command=\"app.\\\"run\" enabled=true checked=false key=\"r\\t\" modifiers=(primary=false,command=false,control=false,option=false,shift=false)\n") != null);
1059
+ // Header, window, command, menu, and item: hostile values inject no
1060
+ // additional records into the line-oriented snapshot.
1061
+ try std.testing.expectEqual(@as(usize, 5), std.mem.count(u8, text, "\n"));
1062
+ }
1063
+
945
1064
  test "accessibility snapshot uses visible view text as name" {
946
1065
  var buffer: [512]u8 = undefined;
947
1066
  var writer = std.Io.Writer.fixed(&buffer);