@native-sdk/cli 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/build/app.zig +26 -9
  2. package/build.zig +124 -1
  3. package/package.json +9 -9
  4. package/packages/core/package-lock.json +2 -2
  5. package/packages/core/package.json +1 -1
  6. package/packages/core/sdk/core.ts +3 -1
  7. package/packages/core/sdk/events.d.ts +7 -0
  8. package/packages/core/sdk/events.ts +26 -5
  9. package/packages/core/sdk/text.d.ts +4 -0
  10. package/packages/core/sdk/text.ts +51 -0
  11. package/packages/core/src/checker.ts +58 -1
  12. package/packages/core/src/contract.ts +5 -4
  13. package/packages/core/src/devhost_journal.mjs +2 -2
  14. package/packages/core/src/diagnostics.ts +2 -2
  15. package/packages/core/src/service_contract.ts +10 -0
  16. package/packages/core/src/typed_ast.ts +9 -7
  17. package/packages/core/src/types.ts +28 -8
  18. package/skill-data/automation/SKILL.md +4 -3
  19. package/skill-data/native-ui/SKILL.md +10 -8
  20. package/skill-data/ts-core/SKILL.md +8 -5
  21. package/src/app_runner/root.zig +301 -12
  22. package/src/app_runner/ts_core_main.zig +6 -4
  23. package/src/app_runner/window_placement.zig +63 -0
  24. package/src/automation/protocol.zig +5 -1
  25. package/src/automation/snapshot.zig +119 -0
  26. package/src/embed/app_exports.zig +2 -1
  27. package/src/embed/conversions.zig +1 -0
  28. package/src/embed/host.zig +10 -3
  29. package/src/embed/root.zig +1 -0
  30. package/src/embed/tests.zig +13 -1
  31. package/src/embed/types.zig +2 -0
  32. package/src/embed/ui_host.zig +26 -2
  33. package/src/platform/android/NativeSdkActivity.java +49 -4
  34. package/src/platform/android/android_host.c +3 -3
  35. package/src/platform/android/native_sdk_app.h +1 -1
  36. package/src/platform/ios/apple_image_fit.h +38 -0
  37. package/src/platform/ios/files.zig +1 -0
  38. package/src/platform/ios/native_sdk_app.h +1 -1
  39. package/src/platform/ios/uikit_host.m +28 -5
  40. package/src/platform/linux/cef_host.cpp +10 -2
  41. package/src/platform/linux/gtk_host.c +43 -10
  42. package/src/platform/linux/gtk_host.h +3 -3
  43. package/src/platform/linux/root.zig +22 -7
  44. package/src/platform/macos/appkit_host.h +7 -4
  45. package/src/platform/macos/appkit_host.m +271 -52
  46. package/src/platform/macos/cef_host.mm +132 -34
  47. package/src/platform/macos/image_fit_test.m +44 -0
  48. package/src/platform/macos/root.zig +222 -14
  49. package/src/platform/null_platform.zig +17 -3
  50. package/src/platform/null_platform_tests.zig +58 -4
  51. package/src/platform/root.zig +2 -0
  52. package/src/platform/types.zig +69 -19
  53. package/src/platform/windows/root.zig +22 -7
  54. package/src/platform/windows/webview2_host.cpp +31 -6
  55. package/src/primitives/app_manifest/root.zig +3 -0
  56. package/src/primitives/app_manifest/tests.zig +24 -0
  57. package/src/primitives/app_manifest/types.zig +13 -0
  58. package/src/primitives/app_manifest/validation.zig +24 -0
  59. package/src/primitives/canvas/a11y_audit.zig +9 -7
  60. package/src/primitives/canvas/a11y_audit_tests.zig +24 -0
  61. package/src/primitives/canvas/events.zig +129 -1
  62. package/src/primitives/canvas/layout_audit.zig +6 -6
  63. package/src/primitives/canvas/markdown.zig +4 -0
  64. package/src/primitives/canvas/markdown_tests.zig +1 -0
  65. package/src/primitives/canvas/png.zig +138 -0
  66. package/src/primitives/canvas/root.zig +14 -2
  67. package/src/primitives/canvas/text_interaction.zig +23 -0
  68. package/src/primitives/canvas/text_span_tests.zig +5 -3
  69. package/src/primitives/canvas/text_spans.zig +2 -0
  70. package/src/primitives/canvas/text_tests.zig +65 -0
  71. package/src/primitives/canvas/ui.zig +66 -10
  72. package/src/primitives/canvas/ui_markup.zig +40 -13
  73. package/src/primitives/canvas/ui_markup_binary.zig +8 -6
  74. package/src/primitives/canvas/ui_markup_binary_tests.zig +14 -4
  75. package/src/primitives/canvas/ui_markup_compiled.zig +5 -1
  76. package/src/primitives/canvas/ui_markup_compiled_tests.zig +55 -0
  77. package/src/primitives/canvas/ui_markup_reflect.zig +6 -5
  78. package/src/primitives/canvas/ui_markup_tests.zig +11 -2
  79. package/src/primitives/canvas/ui_markup_view.zig +8 -2
  80. package/src/primitives/canvas/ui_markup_view_tests.zig +67 -6
  81. package/src/primitives/canvas/ui_schema.zig +17 -13
  82. package/src/primitives/canvas/ui_tests.zig +84 -0
  83. package/src/primitives/canvas/widget_access.zig +3 -3
  84. package/src/primitives/canvas/widget_anchored_tests.zig +106 -0
  85. package/src/primitives/canvas/widget_builtin_tests.zig +593 -32
  86. package/src/primitives/canvas/widget_invalidation.zig +33 -6
  87. package/src/primitives/canvas/widget_layout.zig +333 -126
  88. package/src/primitives/canvas/widget_layout_tests.zig +169 -0
  89. package/src/primitives/canvas/widget_metrics.zig +7 -8
  90. package/src/primitives/canvas/widget_render.zig +76 -44
  91. package/src/primitives/canvas/widget_render_controls.zig +110 -32
  92. package/src/primitives/canvas/widget_render_style.zig +58 -18
  93. package/src/primitives/canvas/widget_render_surfaces.zig +45 -14
  94. package/src/primitives/canvas/widget_routing.zig +40 -34
  95. package/src/primitives/canvas/widget_runtime.zig +11 -2
  96. package/src/primitives/canvas/widget_runtime_tests.zig +10 -14
  97. package/src/primitives/canvas/widget_semantics.zig +8 -3
  98. package/src/primitives/canvas/widget_semantics_tests.zig +6 -2
  99. package/src/primitives/canvas/widget_tree.zig +99 -5
  100. package/src/primitives/canvas/widgets.zig +20 -7
  101. package/src/root.zig +3 -0
  102. package/src/runtime/api.zig +6 -0
  103. package/src/runtime/automation_snapshot.zig +4 -0
  104. package/src/runtime/automation_widget_dispatch.zig +48 -6
  105. package/src/runtime/builtin_bridge.zig +5 -2
  106. package/src/runtime/canvas_frame_packet_tests.zig +22 -13
  107. package/src/runtime/canvas_image_tests.zig +146 -2
  108. package/src/runtime/canvas_images.zig +35 -16
  109. package/src/runtime/canvas_limits.zig +13 -3
  110. package/src/runtime/canvas_widget_accessibility_tests.zig +279 -4
  111. package/src/runtime/canvas_widget_anchored_tests.zig +54 -0
  112. package/src/runtime/canvas_widget_control_tests.zig +33 -1
  113. package/src/runtime/canvas_widget_events.zig +151 -26
  114. package/src/runtime/canvas_widget_floating_tests.zig +48 -0
  115. package/src/runtime/canvas_widget_runtime.zig +322 -102
  116. package/src/runtime/canvas_widget_scroll_driver_tests.zig +34 -0
  117. package/src/runtime/canvas_widget_scroll_drivers.zig +12 -10
  118. package/src/runtime/canvas_widget_scroll_tests.zig +193 -2
  119. package/src/runtime/canvas_widget_semantics_tests.zig +337 -3
  120. package/src/runtime/canvas_widget_split_tree_tests.zig +55 -0
  121. package/src/runtime/canvas_widget_state.zig +33 -7
  122. package/src/runtime/canvas_widget_text_tests.zig +124 -0
  123. package/src/runtime/core.zig +16 -0
  124. package/src/runtime/effects.zig +14 -14
  125. package/src/runtime/effects_image_tests.zig +91 -0
  126. package/src/runtime/gpu_surface_events.zig +25 -2
  127. package/src/runtime/native_command_event_tests.zig +29 -0
  128. package/src/runtime/root.zig +2 -0
  129. package/src/runtime/session_journal.zig +21 -2
  130. package/src/runtime/session_replay.zig +13 -8
  131. package/src/runtime/session_tests.zig +111 -4
  132. package/src/runtime/shell_layout_tests.zig +12 -0
  133. package/src/runtime/ts_core_host_tests.zig +47 -0
  134. package/src/runtime/ts_ui_app.zig +164 -1
  135. package/src/runtime/ui_app.zig +100 -21
  136. package/src/runtime/ui_app_tests.zig +351 -32
  137. package/src/runtime/ui_app_window_tests.zig +13 -1
  138. package/src/runtime/view.zig +3 -0
  139. package/src/runtime/view_widget_control.zig +18 -0
  140. package/src/runtime/view_widget_scroll.zig +112 -18
  141. package/src/runtime/view_widget_text.zig +1 -1
  142. package/src/runtime/view_widget_tree.zig +110 -13
  143. package/src/runtime/widget_bridge.zig +2 -0
  144. package/src/runtime/window_command_bridge_tests.zig +86 -0
  145. package/src/runtime/window_storage.zig +16 -1
  146. package/src/runtime/window_views.zig +1 -0
  147. package/src/tooling/ios.zig +3 -0
  148. package/src/tooling/manifest.zig +90 -2
  149. package/src/tooling/package.zig +67 -2
  150. package/src/tooling/raw_manifest.zig +10 -0
  151. package/src/tooling/templates.zig +128 -18
  152. package/src/tooling/verbs.zig +1 -0
  153. package/src/tooling/web_engine.zig +1 -1
  154. package/tools/corewire/emit.zig +31 -12
  155. package/tools/corewire/emit_facade.zig +57 -2
  156. package/tools/corewire/shim_rt.zig +20 -0
@@ -507,6 +507,7 @@ export class SubsetChecker {
507
507
  this.checkModelBindingSurface();
508
508
  this.checkMigrationHook();
509
509
  this.checkThemePackHelper();
510
+ this.checkThemeStateHelper();
510
511
  this.checkStatusItemHelper();
511
512
  this.checkStatusItemsHelper();
512
513
  this.checkWindowsHelper();
@@ -843,6 +844,55 @@ export class SubsetChecker {
843
844
  }
844
845
  }
845
846
 
847
+ /// `themeState(model)` subsumes themePack with one exact, projection-safe
848
+ /// record. Optional properties are intentional: omission is the manifest /
849
+ /// system inheritance signal that crosses the helper ABI as null.
850
+ private checkThemeStateHelper(): void {
851
+ const decl = this.entryExportedFunction("themeState");
852
+ if (decl === null) return;
853
+
854
+ if (this.table.modelHelperDecls().some((candidate) => candidate.name === "themePack")) {
855
+ this.report("NS1033", "Export either `themePack` or `themeState`, not both.", decl.name ?? decl);
856
+ }
857
+
858
+ const helper = this.table.modelHelperDecls().find(
859
+ (candidate) => candidate.name === "themeState" && candidate.decl === decl,
860
+ );
861
+ if (helper === undefined || decl.type === undefined) {
862
+ this.report(
863
+ "NS1033",
864
+ "`themeState` is not a single-Model-parameter helper with an explicit return type.",
865
+ decl.name ?? decl,
866
+ );
867
+ return;
868
+ }
869
+
870
+ const returns = this.table.resolveTypeNode(decl.type);
871
+ const state = returns.k === "struct" ? this.table.structs.get(returns.name) : undefined;
872
+ const names = state?.fields.map((field) => field.tsName).sort() ?? [];
873
+ const field = (name: string) => state?.fields.find((candidate) => candidate.tsName === name);
874
+ const pack = field("pack");
875
+ const colorScheme = field("colorScheme");
876
+ const accent = field("accent");
877
+ const optionalEnumMembersAre = (candidate: typeof pack, expected: readonly string[]): boolean => {
878
+ if (candidate?.type.k !== "optional" || candidate.type.inner.k !== "enum") return false;
879
+ const found = this.table.enums.get(candidate.type.inner.name)?.members.slice().sort() ?? [];
880
+ return found.join(",") === expected.slice().sort().join(",");
881
+ };
882
+ const valid =
883
+ names.join(",") === "accent,colorScheme,pack" &&
884
+ optionalEnumMembersAre(pack, ["house", "geist"]) &&
885
+ optionalEnumMembersAre(colorScheme, ["light", "dark", "system"]) &&
886
+ accent?.type.k === "optional" && accent.type.inner.k === "string";
887
+ if (!valid) {
888
+ this.report(
889
+ "NS1033",
890
+ "`themeState` must return the exact canonical `ThemeState` record (`pack?`, `colorScheme?`, `accent?`); import it from `@native-sdk/core/events`.",
891
+ decl.type,
892
+ );
893
+ }
894
+ }
895
+
846
896
  /// Persistence migration is a pure entry hook, not a model helper. It
847
897
  /// receives the previous canonical snapshot and monotonic schema version;
848
898
  /// returning the current Model succeeds, while throwing closes as
@@ -1871,7 +1921,7 @@ export class SubsetChecker {
1871
1921
  /// entry points, but the exports themselves live in the entry module.
1872
1922
  private static readonly entryOnlyExports = new Set([
1873
1923
  "update", "initialModel", "subscriptions", "migrate",
1874
- "commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs", "themePack", "statusItem", "statusItems", "windows",
1924
+ "commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs", "themePack", "themeState", "statusItem", "statusItems", "windows",
1875
1925
  "viewUnbound", "modelUnbound", "msgUnbound",
1876
1926
  ]);
1877
1927
 
@@ -2039,6 +2089,13 @@ export class SubsetChecker {
2039
2089
  : this.table.unions.get(typeName)?.arms.flatMap((a) => [...a.fields]) ?? [];
2040
2090
  for (const f of fields) {
2041
2091
  const decl = f.decl;
2092
+ if (ts.isPropertySignature(decl) && decl.questionToken) {
2093
+ this.report(
2094
+ "NS1012",
2095
+ `Optional field \`${f.tsName}?\` in the ${typeName} tree has an implicit undefined state — spell the empty explicitly as \`${f.tsName}: T | null\`.`,
2096
+ decl,
2097
+ );
2098
+ }
2042
2099
  if (ts.isPropertySignature(decl) && decl.type && ts.isFunctionTypeNode(decl.type)) {
2043
2100
  this.report("NS1003", `\`${f.tsName}\` stores a function in the ${typeName} tree.`, decl);
2044
2101
  }
@@ -457,10 +457,11 @@ class ContractEmitter {
457
457
  }
458
458
  }
459
459
  }
460
- // `statusItem` is consumed by the generated launcher, not markup. It
461
- // is still an ordinary Model helper in the core ABI, so teach native
462
- // check that this one helper is intentionally shell-bound without
463
- // making every app repeat it in `viewUnbound`.
460
+ // These helpers are consumed by the generated launcher, not markup.
461
+ // They remain ordinary Model helpers in the core ABI, so teach native
462
+ // check that they are intentionally shell-bound without making every
463
+ // app repeat them in `viewUnbound`.
464
+ if (helperNames.includes("themeState") && !model.includes("themeState")) model.push("themeState");
464
465
  if (helperNames.includes("statusItem") && !model.includes("statusItem")) model.push("statusItem");
465
466
  if (helperNames.includes("statusItems") && !model.includes("statusItems")) model.push("statusItems");
466
467
  if (helperNames.includes("windows") && !model.includes("windows")) model.push("windows");
@@ -5,8 +5,8 @@ import fs from "node:fs";
5
5
  // recordings.
6
6
  // EffectFileOp appended `delete`; the reflected journal layout fingerprint
7
7
  // moves so older recordings refuse cleanly instead of decoding op 8 wrongly.
8
- export const journalFormatFingerprint = 0xb3bd2e83971de44dn;
9
- export const automationProtocolFingerprint = 0x59d66f39803fd602n;
8
+ export const journalFormatFingerprint = 0xc510d4b0292ac71an;
9
+ export const automationProtocolFingerprint = 0x51f7889bbe3305e7n;
10
10
 
11
11
  const requestKeyBase = 0x5453525100000000n;
12
12
  const textEncoder = new TextEncoder();
@@ -125,7 +125,7 @@ export const rules = {
125
125
  id: "NS1014",
126
126
  title: "the core's entry points live in core.ts",
127
127
  fix: "Move this export into src/core.ts (imported modules may hold the helpers it calls and the types it uses).",
128
- why: "The build wires `update`, `initialModel`, `subscriptions`, the host-event channels, `themePack`, and `viewUnbound` from the entry module only, so an entry export in an imported file would be silently ignored.",
128
+ why: "The build wires `update`, `initialModel`, `subscriptions`, the host-event channels, `themeState` / `themePack`, and `viewUnbound` from the entry module only, so an entry export in an imported file would be silently ignored.",
129
129
  class: "guarantee",
130
130
  },
131
131
  NS1015: {
@@ -257,7 +257,7 @@ export const rules = {
257
257
  NS1033: {
258
258
  id: "NS1033",
259
259
  title: "wiring exports match their runtime shapes",
260
- fix: "Declare the channel exactly: `commandMsg(name: string)` / `keyMsg(key: KeyEvent)` / `frameMsg(model: Model, frame: FrameEvent)` / `pinchMsg(pinch: PinchEvent)` / `dropMsg(drop: FileDropEvent)` returning `Msg | null`; `themePack(model: Model): ThemePack`; singular `statusItem(model: Model): StatusItemState` or collection `statusItems(model: Model): readonly StatusItemDescriptor[]`; `windows(model: Model): readonly WindowDescriptor[]`, with each entry constructed by `windowDescriptor` and a literal `label: asciiBytes(\"name\")` matching `src/windows/name.native`; `appearanceMsg` / `chromeMsg` naming an arm with that channel's record shape; `envMsgs` entries targeting one-`Uint8Array`-field arms; and persistence ok/none routes naming void arms while err names a one-`Uint8Array`-field arm. Import canonical records from the SDK modules.",
260
+ fix: "Declare the channel exactly: `commandMsg(name: string)` / `keyMsg(key: KeyEvent)` / `frameMsg(model: Model, frame: FrameEvent)` / `pinchMsg(pinch: PinchEvent)` / `dropMsg(drop: FileDropEvent)` returning `Msg | null`; `themePack(model: Model): ThemePack` or `themeState(model: Model): ThemeState` (not both); singular `statusItem(model: Model): StatusItemState` or collection `statusItems(model: Model): readonly StatusItemDescriptor[]`; `windows(model: Model): readonly WindowDescriptor[]`, with each entry constructed by `windowDescriptor` and a literal `label: asciiBytes(\"name\")` matching `src/windows/name.native`; `appearanceMsg` / `chromeMsg` naming an arm with that channel's record shape; `envMsgs` entries targeting one-`Uint8Array`-field arms; and persistence ok/none routes naming void arms while err names a one-`Uint8Array`-field arm. Import canonical records from the SDK modules.",
261
261
  why: "The generated wiring builds host events, persistence restore results, model-derived theme/status/window declarations, and their typed callbacks structurally at build time; a wrong shape would otherwise surface as a Zig compile error inside generated code instead of a teaching diagnostic here.",
262
262
  class: "guarantee",
263
263
  },
@@ -258,6 +258,16 @@ class ServiceShapeTable {
258
258
  if (this.listed.has(name)) return;
259
259
  const info = this.table.structs.get(name);
260
260
  if (!info) throw new ServiceShapeError(`The shared type table has no record named \`${name}\``, this.fallbackSite);
261
+ const optionalField = info.fields.find((field) =>
262
+ (ts.isPropertySignature(field.decl) || ts.isPropertyDeclaration(field.decl)) &&
263
+ field.decl.questionToken !== undefined
264
+ );
265
+ if (optionalField) {
266
+ throw new ServiceShapeError(
267
+ `Service boundary record \`${name}\` has optional property \`${optionalField.tsName}?\`; spell absence explicitly as \`${optionalField.tsName}: T | null\` so both service codecs encode the same state`,
268
+ optionalField.decl,
269
+ );
270
+ }
261
271
  this.listed.add(name);
262
272
  const record: ServiceRecordType = {
263
273
  name,
@@ -340,18 +340,20 @@ export class TypedAst {
340
340
 
341
341
  /// Properties of an object-literal type alias body, in declaration
342
342
  /// order — null unless every member is a plain record property (an
343
- /// identifier-named, annotated, non-optional property signature), so
343
+ /// identifier-named, annotated property signature), so
344
344
  /// a shape this walk cannot carry whole refuses as an unsupported
345
- /// alias instead of registering a struct with silently missing
346
- /// fields.
347
- propsOfTypeLiteral(node: tsImpl.TypeLiteralNode): PropInfo[] | null {
345
+ /// alias instead of registering a struct with silently missing fields.
346
+ /// The one omission-carrying value record is the SDK-owned ThemeState;
347
+ /// its caller opts in explicitly so authored/service records keep the
348
+ /// fixed-shape rule.
349
+ propsOfTypeLiteral(node: tsImpl.TypeLiteralNode, allowOptional = false): PropInfo[] | null {
348
350
  const out: PropInfo[] = [];
349
351
  for (const member of node.members) {
350
- if (!tsImpl.isPropertySignature(member) || !member.name || !tsImpl.isIdentifier(member.name)) return null;
351
- if (member.questionToken || !member.type) return null;
352
+ if (!tsImpl.isPropertySignature(member) || !member.name || !tsImpl.isIdentifier(member.name) || !member.type) return null;
353
+ if (member.questionToken && !allowOptional) return null;
352
354
  out.push({
353
355
  name: member.name.text,
354
- optional: false,
356
+ optional: member.questionToken !== undefined,
355
357
  readonly: hasReadonlyModifier(member),
356
358
  typeNode: member.type,
357
359
  declaration: member,
@@ -12,7 +12,8 @@
12
12
  // T | null/undefined -> ?T (R7)
13
13
  // Uint8Array -> []const u8 (R3)
14
14
 
15
- import { ts, TypedAst, hasExportModifier, exportListBindings, type PropInfo } from "./typed_ast.ts";
15
+ import path from "node:path";
16
+ import { ts, TypedAst, hasExportModifier, exportListBindings, sdkLibraryModules, type PropInfo } from "./typed_ast.ts";
16
17
  import { mutatingMethodNames } from "./ownership.ts";
17
18
 
18
19
  export type ZType =
@@ -265,14 +266,17 @@ export class TypeTable {
265
266
  this.declOrder.push(name);
266
267
  continue;
267
268
  }
268
- if (ts.isTypeLiteralNode(stmt.type) && this.tast.propsOfTypeLiteral(stmt.type) !== null) {
269
+ const projectOptional = this.isCanonicalThemeState(stmt);
270
+ if (ts.isTypeLiteralNode(stmt.type) && this.tast.propsOfTypeLiteral(stmt.type, projectOptional) !== null) {
269
271
  // A plain-record object-literal alias is a struct exactly like
270
272
  // an interface; the alias FORM is how a contract projection
271
273
  // spells a value-stored record (interfaces spell node
272
274
  // storage), and the storage itself still comes from the
273
275
  // promotion walk. Shapes the plain-record walk cannot carry
274
276
  // whole (quoted or optional properties) stay unclassified and
275
- // refuse at emission instead of losing fields silently.
277
+ // refuse at emission instead of losing fields silently. The
278
+ // canonical SDK ThemeState is the sole optional-property record:
279
+ // omission is its manifest/system inheritance signal.
276
280
  this.structs.set(name, {
277
281
  name,
278
282
  decl: stmt,
@@ -319,18 +323,32 @@ export class TypeTable {
319
323
  }
320
324
  const structInfo = this.structs.get(stmt.name.text);
321
325
  if (structInfo && structInfo.decl === stmt && ts.isTypeLiteralNode(stmt.type)) {
322
- const props = this.tast.propsOfTypeLiteral(stmt.type);
323
- if (props) structInfo.fields = props.map((p) => this.fieldOf(p));
326
+ const projectOptional = this.isCanonicalThemeState(stmt);
327
+ const props = this.tast.propsOfTypeLiteral(stmt.type, projectOptional);
328
+ if (props) structInfo.fields = props.map((p) => this.fieldOf(p, projectOptional));
324
329
  }
325
330
  }
326
331
  }
327
332
  }
328
333
 
329
- private fieldOf(p: PropInfo): ZField {
334
+ private isCanonicalThemeState(decl: ts.TypeAliasDeclaration): boolean {
335
+ const events = sdkLibraryModules.get("@native-sdk/core/events");
336
+ return decl.name.text === "ThemeState" && events !== undefined &&
337
+ path.resolve(decl.getSourceFile().fileName) === path.resolve(events);
338
+ }
339
+
340
+ private fieldOf(p: PropInfo, projectOptional = false): ZField {
341
+ const resolved = p.typeNode ? this.resolveTypeNode(p.typeNode) : { k: "void" } as ZType;
330
342
  return {
331
343
  tsName: p.name,
332
344
  zigName: zigDeclName(p.name),
333
- type: p.typeNode ? this.resolveTypeNode(p.typeNode) : { k: "void" },
345
+ // Only the canonical ThemeState projects JS `undefined` omission onto
346
+ // the contract's ordinary optional slot. Applying this globally would
347
+ // let service records acquire an absent state while their generated
348
+ // codecs still accept only explicit null.
349
+ type: projectOptional && p.optional && resolved.k !== "void" && resolved.k !== "optional"
350
+ ? { k: "optional", inner: resolved }
351
+ : resolved,
334
352
  decl: p.declaration,
335
353
  };
336
354
  }
@@ -748,7 +766,7 @@ export class TypeTable {
748
766
  }
749
767
 
750
768
  /// The canvas text-input event vocabulary — a union carrying exactly these
751
- /// eleven tags is the declared mirror the markup engines resolve `on-input`
769
+ /// thirteen tags is the declared mirror the markup engines resolve `on-input`
752
770
  /// through (matched structurally on the Zig side; see
753
771
  /// ui_markup_reflect.declaredTextInputUnion).
754
772
  const textInputMirrorTags = [
@@ -757,6 +775,8 @@ const textInputMirrorTags = [
757
775
  "delete_forward",
758
776
  "delete_word_backward",
759
777
  "delete_word_forward",
778
+ "delete_to_start",
779
+ "delete_to_line_start",
760
780
  "clear",
761
781
  "move_caret",
762
782
  "set_selection",
@@ -117,9 +117,10 @@ Semantics:
117
117
  10. Use `native automate widget-key <view-label> <key> [text]` for focused retained widget keyboard input. The key accepts modifier chords — `cmd+a`, `cmd+c`, `cmd+v`, `cmd+x`, `ctrl+shift+arrowleft` (`cmd` sets the primary shortcut modifier on every platform) — so select-all/copy/cut/paste and shift-extended selection are drivable; after a copy, widget lines in the snapshot show the live selection as `selection=a..b`, and the copied text lands on the real system clipboard (`pbpaste` on macOS).
118
118
  11. Use `native automate widget-pinch <view-label> <scale> [x y]` for trackpad pinch gestures against a gpu-surface view: the runtime dispatches the real `pinch_begin`/`pinch_change`/`pinch_end` platform events, with one change carrying `scale - 1`. `<scale>` is the FINAL multiplicative zoom for the gesture — the cumulative gesture scale (the product of `1 + delta`) lands exactly on it — `1.5` zooms in 50%, `0.5` zooms out to half. The optional anchor point is view-local points, defaulting to the view center. Apps hear it through the pinch channel (`Options.on_pinch` / the TS core's `pinchMsg`).
119
119
  12. Use `native automate screenshot <view-label> [scale]` to capture the named `gpu_surface` view's canvas as `screenshot-<view-label>.png` (the CLI prints the artifact path and waits for the file).
120
- 13. Use `native automate tray-action <item-id>` for the primary status item, or `native automate tray-action <status-item-id> <item-id>` for an explicit item. Both select a dropdown row through the same platform event a real menu-bar click emits (command dispatch with source `.tray`). Live items appear in `snapshot.txt` as `tray #status-id title="..." visible=... items=N` followed by ` tray-item #item-id ...` rows — the menu bar is outside every window capture, so this is the automation evidence for every model-driven item. Unknown id pairs degrade into the dispatch-error ring as `automation.tray_action`.
121
- 14. Use `native automate reload` to request a WebView reload.
122
- 15. Use `native automate profile on` to enable per-stage frame timing: while on, `snapshot.txt` carries a `frame_profile` line with rolling p50/p90/max microseconds per pipeline stage (`rebuild`, `layout`, `reconcile`, `emit`, `a11y`, `plan`, `patch`, `encode`, `present`, `host_decode`, `host_draw`), each with a lifetime sample count (`<stage>_n=`). Drive some interactions, then `native automate snapshot | grep -o 'frame_profile.*'` to read where frame time goes; `profile off` stops recording and drops the line. Turning it on starts a fresh sample window.
120
+ 13. Before driving an app-menu command, inspect the snapshot's `command id="..."` catalog and `app-menu` / `app-menu-item` rows to prove the running app loaded the expected `app.zon` or runner declarations. Then use `native automate menu-command <id>` to dispatch the same `.menu_command` platform event a real selection emits; the verb remains a raw event injector, so the snapshot receipt is what validates registration.
121
+ 14. Use `native automate tray-action <item-id>` for the primary status item, or `native automate tray-action <status-item-id> <item-id>` for an explicit item. Both select a dropdown row through the same platform event a real menu-bar click emits (command dispatch with source `.tray`). Live items appear in `snapshot.txt` as `tray #status-id title="..." visible=... items=N` followed by ` tray-item #item-id ...` rows — the menu bar is outside every window capture, so this is the automation evidence for every model-driven item. Unknown id pairs degrade into the dispatch-error ring as `automation.tray_action`.
122
+ 15. Use `native automate reload` to request a WebView reload.
123
+ 16. Use `native automate profile on` to enable per-stage frame timing: while on, `snapshot.txt` carries a `frame_profile` line with rolling p50/p90/max microseconds per pipeline stage (`rebuild`, `layout`, `reconcile`, `emit`, `a11y`, `plan`, `patch`, `encode`, `present`, `host_decode`, `host_draw`), each with a lifetime sample count (`<stage>_n=`). Drive some interactions, then `native automate snapshot | grep -o 'frame_profile.*'` to read where frame time goes; `profile off` stops recording and drops the line. Turning it on starts a fresh sample window.
123
124
 
124
125
  ## Screenshots
125
126
 
@@ -153,7 +153,7 @@ Zero app code: on macOS every non-virtualized `scroll` region — and every wind
153
153
 
154
154
  Authors write ONE menu; the platform decides how it presents. The default is the real OS context menu at the pointer — `NSMenu` on macOS, `TrackPopupMenu` on Windows, `GtkPopoverMenu` on Linux — and the selection dispatches the item's typed `Msg`. On hosts without a native menu presenter (the mobile toolkit hosts and embed hosts today), the SAME declared items present automatically as an anchored canvas surface at the click point, with the standard anchored-surface behavior (Escape and outside-click dismiss, late z-pass, window clipping). Never two authored menus, never a canvas imitation where the OS menu exists.
155
155
 
156
- Markup declares the menu as a `<context-menu>` element — a DIRECT child of the pressable element whose right-click it answers (a hit target, or an element with a bound `on-press`/`on-hold`). It is metadata, not content: it renders nothing in the row's flow. Children are `menu-item`s (`on-press` required, `disabled` optional, the text content is the label) and bare `<separator/>`s, with `if`/`else`/`for` around them to swap or repeat items — a menu whose items all evaporate at runtime simply declares no menu (the All Notes row pattern). Conditional MENUS are spelled as conditional ITEMS: the `<context-menu>` itself takes no attributes and cannot sit behind a structure tag. No submenus: the platform channel carries flat items (label, enabled, separator) only.
156
+ Markup declares the menu as a `<context-menu>` element — a DIRECT child of the interactive element whose right-click it answers (a hit-target kind, or an element made interactive by `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`). It is metadata, not content: it renders nothing in the row's flow. Children are `menu-item`s (`on-press` required, `disabled` optional, the text content is the label) and bare `<separator/>`s, with `if`/`else`/`for` around them to swap or repeat items — a menu whose items all evaporate at runtime simply declares no menu (the All Notes row pattern). Conditional MENUS are spelled as conditional ITEMS: the `<context-menu>` itself takes no attributes and cannot sit behind a structure tag. No submenus: the platform channel carries flat items (label, enabled, separator) only.
157
157
 
158
158
  ```html
159
159
  <list-item on-press="open_note:{n.id}" label="{n.title}">
@@ -196,19 +196,19 @@ Automation drives the native path honestly: snapshots list every widget's declar
196
196
  | `stack`, `panel`, `card` | overlay containers | children stack on top of each other — `gap` can never space them and is a validation error (put a `column`/`row` inside for flow) |
197
197
  | `scroll` | scroll_view | wrap multiple children in a `column` inside it |
198
198
  | `list`, `grid` | list, grid | vertical stack / cell grid |
199
- | `tabs`, `toggle-group`, `button-group`, `radio-group`, `breadcrumb`, `pagination` | row containers | children flow horizontally (tab buttons, toggle-buttons, radios, ...) |
199
+ | `tabs`, `toggle-group`, `button-group`, `radio-group`, `breadcrumb`, `pagination` | row containers | children flow horizontally. Give every `radio-group` an accessible `label`; it is one logical `radiogroup`: descendant radios at any nesting depth share one Tab stop; arrows wrap while Home/End move to the edges, focus and selection move together, and selecting one clears the rest of the nearest group scope |
200
200
  | `table` > `table-row` > `table-cell` | table, data_row, data_cell | rows only inside a table, cells only inside a row (for/if wrappers are fine); cells are text leaves, dispatch with `on-press` |
201
201
  | `dropdown-menu` | dropdown_menu | vertical menu surface; children are `menu-item`s. `anchor="below\|above"` floats it against its PARENT's frame (see Pickers): late z-pass above the whole tree, window-clipped, auto-flipping at the window edges, zero flow space. Pair with `on-dismiss` |
202
202
  | `accordion` | accordion | header via `text` attr; children show while `selected`, dispatch `on-toggle` |
203
203
  | `alert`, `bubble` | surfaces | `alert` title via `text` attr; children stack inside. `bubble` hugs its message up to 80% of the thread (`ghost` exempt; explicit `width` wins) and takes one `<reactions>` child — the reaction pill straddling its bottom edge, one text run, dock via `text-alignment` (default `end`); `text=` on bubble itself is a teaching error (that channel belongs to the pill). Grouped runs are spacing, not vocabulary: 8 gap within a sender's run, 32 between turns |
204
- | `dialog`, `drawer`, `sheet` | modal surfaces | rendered in place — title via `text` attr, wrap in `<if>` to show conditionally |
204
+ | `dialog`, `drawer`, `sheet` | modal surfaces | root-relative and unaffected by ancestor scroll or clipping: dialogs center in the viewport, drawers span its width and dock to the bottom, and sheets span its height and dock to the right — title via `text` attr, wrap in `<if>` to show conditionally |
205
205
  | `resizable` | resizable | engine-managed drag handle; `width` sets the initial width |
206
206
  | `split` | split | two-pane horizontal splitter: exactly two element children (nest splits for more panes), the engine synthesizes the draggable divider between them. `value` binds the model-owned first-pane fraction (0 lays out at 0.5), `on-resize` names an f32 Msg variant dispatched with every applied fraction (echo it back through `value` — see Splitters), `min-width` on the panes bounds the drag, `gap` sets the divider band thickness. The divider is focusable: Left/Right (Shift for bigger steps) adjust, Home/End jump to the clamp edges |
207
207
  | `tree` | tree | disclosure-tree container (vertical flow): descendant rows carrying `role="treeitem"` — at ANY nesting depth — form one roving keyboard focus set with the ARIA tree keymap. Up/Down walk visible rows (selection follows focus through each row's `on-press`), Left collapses an expanded row or moves to the parent row, Right expands a collapsed row or moves to the first child row, Home/End jump to the edges, Enter/Space activate. Expandable rows bind `expanded` and `on-toggle`; the model owns selection and expansion (collapsed children are simply not rendered) |
208
208
  | `text`, `badge`, `tooltip` | text leaves | text content, `{}` interpolation allowed; `text` line policy via `wrap` (`"true"` word-wraps; `"false"`/unset paint one honest line, overflow eliding by default — `overflow="clip"` opts out), and `text` alone takes the typography rungs `size="heading"`/`size="display"` (themable token steps above title — section headings, hero stats, timer numerals). `tooltip` with `anchor="above\|below"` floats against its parent (the stack wrapping trigger + tooltip, the dropdown pattern) and the RUNTIME owns its visibility — hover intent on the trigger: shows after `tooltip-delay` ms (default 600; `"0"` = instant) and immediately on keyboard focus; hides on leave, focus departure, Escape, or a press of the trigger (a press also closes the warm window), and a shared 400ms warm window after a pointer-hovered tooltip hides on leave (the only hide that warms) shows the next trigger's tooltip instantly; the model never hears hover. These are shadcn/ui's defaults (Base UI). Without `anchor` it stays a static leaf that paints whenever the view renders it |
209
209
  | `text` > `span` | inline styled runs | mixed-style text in ONE wrapped paragraph: span children style runs with `weight="regular\|medium\|bold"`, `mono`, `italic`, `scale` (a positive multiplier on the paragraph's base size — inline headings, hero stats), `underline`, `foreground` (token name); `{bindings}` interpolate inside spans; whitespace between runs collapses to a single space (none = the runs abut); spans do not nest, take no events, and the paragraph announces as one text run — see "Rich text" |
210
210
  | `button`, `toggle-button`, `list-item`, `menu-item`, `toggle`, `switch`, `select`, `avatar` | text-bearing controls | label is the text content; `button`, `toggle-button`, `list-item`, and `menu-item` also take `icon="save"` — a vector icon drawn inline (buttons/toggle-buttons before the label, icon-only when the content is empty: add a `label`; list/menu items as a leading slot), ONE hit target whose icon follows the element's enabled/disabled tint (no overlay stacking, no duplicated `on-press`); tab strips are `toggle-button` children, so tabs get icons this way; `select` shows `placeholder` while empty and dispatches `on-press`; `avatar` renders initials, or a runtime image via `image="{binding}"` (see the Images section) |
211
- | `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); the checkbox/radio label rides `text="..."` — these are not text-bearing elements, so text content is a teaching error (`label=` alone names one for accessibility without a visible label); a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
211
+ | `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); checkbox/radio visible labels are text content (`<checkbox>Done</checkbox>`), with `text="..."` as the equivalent binding-friendly form and `label=` alone naming one for accessibility without drawing a label; a radio selection TRANSITION (pointer, Space/Enter, grouped navigation, or accessibility selection) dispatches `on-change` when bound, then `on-toggle`, then `on-press` for compatibility — reactivating the already-checked radio has no new `on-change` edge, though a legacy fallback still receives the activation; a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
212
212
  | `text-field`, `input`, `search-field`, `combobox`, `textarea` | text entry | `placeholder`; edits via `on-input`, enter via `on-submit` on single-line kinds; in a default `textarea`, Enter (and Shift+Enter) inserts a newline and `on-submit` dispatches on primary+Enter (cmd on macOS, ctrl elsewhere). A chat composer opts into `submit-on-enter="true"`: plain Enter submits, Shift+Enter remains a newline, and the primary chord still submits. `search-field` carries a built-in trailing clear affordance whenever it holds text (press the x, or Escape while focused — both clear through the text-edit path, so `on-input` hears it; no attribute, no external Clear button needed) |
213
213
  | `status-bar` | status bar | text leaf: content only, no children |
214
214
  | `separator`, `spacer` | separator, flexible space | `separator` is axis-aware: a horizontal rule in a `column`, a thin vertical divider in a `row`; give `spacer` a `grow` |
@@ -221,7 +221,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
221
221
  | `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` |
222
222
  | `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 |
223
223
  | `chart` > `series` | composite data chart | series only inside a chart, and only series (the set is static — data varies through bindings); each series is a leaf — `values="{binding}"` (required) names a model `[]const f32` iterable, `kind` is `line`/`area`/`bar` (literal), `color` a token name, `label` the semantics name; chart takes `y-min`, `y-max`, `grid-lines`, `baseline`, `x-labels`, `y-labels`, `hover-details`, `stroke-width`, box options, `label` — see "Charts" |
224
- | `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" |
224
+ | `context-menu` | consumed by its parent | right-click menu on its DIRECT parent (a hit-target kind or an element with `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`); 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" |
225
225
  | `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`, and optional `submit-on-enter`). 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) |
226
226
 
227
227
  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.
@@ -397,7 +397,7 @@ Color and radius come from the design tokens, referenced by token NAME — liter
397
397
  </row>
398
398
  ```
399
399
 
400
- References resolve against the app's LIVE tokens on every rebuild (`finalizeWithTokens`), so a themed app (`tokens`/`tokens_fn`) re-resolves them when the theme changes — dark mode flips `surface` automatically. The DEFAULT theme follows the system appearance: an app that sets neither `tokens` nor `tokens_fn` derives the stock tokens from the OS light/dark setting (plus high-contrast and reduce-motion) and re-themes live when the user flips it. A TypeScript core may export `themePack(model: Model): ThemePack` (`ThemePack = "house" | "geist"`) for a model-owned built-in pack toggle; the generated adapter changes only the pack and preserves those live system axes, manifest accent, and surface scale. Pass explicit `tokens` for a fixed look, or `tokens_fn` for a fully model-owned custom palette (usually still following the system scheme through `on_appearance`). An explicit `style` value set in Zig always wins over a token ref on the same field. Unknown token names are validation/compile errors.
400
+ References resolve against the app's LIVE tokens on every rebuild (`finalizeWithTokens`), so a themed app (`tokens`/`tokens_fn`) re-resolves them when the theme changes — dark mode flips `surface` automatically. The DEFAULT theme follows the system appearance: an app that sets neither `tokens` nor `tokens_fn` derives the stock tokens from the OS light/dark setting (plus high-contrast and reduce-motion) and re-themes live when the user flips it. A TypeScript core may export `themeState(model: Model): ThemeState` (from `@native-sdk/core/events`) to derive optional `pack`, `colorScheme` (`light`/`dark`/`system`), and `accent` (`#rrggbb`) from model state. Omitted fields inherit app.zon, and omitted/system scheme follows the OS; high contrast still suppresses accents. `themePack(model)` remains supported for pack-only apps, but never export both. Pass explicit `tokens` for a fixed look, or `tokens_fn` for a fully model-owned custom palette; those complete-token paths take precedence over themeState. Forced scheme is canvas-token scope in v1 — native title bars and WebViews continue following the OS. An explicit `style` value set in Zig always wins over a token ref on the same field. Unknown token names and malformed model accents are validation errors.
401
401
 
402
402
  One Zig-only style knob rides beside the tokens: `ElementOptions.style = .{ .quiet_hover = true }` silences a pressable surface's pointer HOVER wash only — press and selection fills, the focus ring, cursor intent, and hit testing stay — for image-forward content tiles (cover art, photo cards) where the pointer rests on content rather than a control register. Acting controls (list rows, menu items, buttons, tab triggers) keep their washes: there the hover fill IS the affordance.
403
403
 
@@ -521,7 +521,7 @@ Scroll offsets follow the same mirror discipline as text: the Msg carries the of
521
521
 
522
522
  A handler or update error DEGRADES, it does not exit the app: dispatch catches it, records it in a bounded ring (`runtime.dispatchErrors()`, the `error event=... name=...` lines and `dispatch_errors=` count in automation snapshots, and a `dispatch.error` trace record at error level), and the app keeps running. Trace-sink capacity failures likewise never fail dispatch — dropped records are counted (`dropped_trace_records=`), not fatal. Design for it: an arm that can fail should still surface its own status in the model; the error ring is the safety net, not the UX.
523
523
 
524
- Presses follow ONE rule: a click lands on the nearest pressable widget under the pointer — plain text, icons, images, badges, and layout containers let it fall through to their closest pressable ancestor, and dragging still selects text. "Pressable" means an interactive kind (button, checkbox, list-item, ...) or ANY element with a bound `on-press`/`on-double-press`/`on-toggle` — the handler itself makes the element a hit target, so a pressable row is just `<panel on-press="open:{id}">` (or `<row on-press=...>`, `ui.row(.{ .on_press = ... })`) with plain text children: no empty-text overlays, no duplicating the handler onto every text leaf. Nested pressables resolve to the deepest one (a button inside a pressable row wins over the row); editable text fields, scroll containers, and modal surfaces (dialog, drawer, sheet, popover, menus) always claim their own presses, so a click in a field inside a pressable row places the caret instead of activating the row. The value/text handlers (`on-change`, `on-submit`, `on-input`) still only belong on controls — both engines and `markup check` reject them on layout/decoration elements with a teaching error.
524
+ Presses follow ONE rule: a click lands on the nearest press-claiming widget under the pointer — plain text, icons, images, badges, and layout containers let it fall through to their closest interactive ancestor, and dragging still selects text. An interactive element is a control kind (button, checkbox, list-item, ...) or ANY element with a bound `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`; these handlers make the element a hit target and press claimer. Thus a row can bind `on-press` for clicks or `on-drag` for spatial dragging, and child text still resolves to that row without overlays or duplicated handlers. Nested claimers resolve to the deepest one; editable text fields, scroll containers, and modal surfaces (dialog, drawer, sheet, popover, menus) always claim their own presses. The value/text handlers (`on-change`, `on-submit`, `on-input`) still only belong on controls — both engines and `markup check` reject them on layout/decoration elements with a teaching error.
525
525
 
526
526
  ### Keys: quiet list rows and the app-level fallback
527
527
 
@@ -565,6 +565,8 @@ The markup binds the FN (`text="{draft}"`), never the buffer: binding a `TextBuf
565
565
 
566
566
  The runtime owns cmd/ctrl+C/X/V in editable text: copy writes the current selection to the system clipboard, cut copies then delivers the removal to your `on-input` handler as an `insert_text ""` edit, and paste arrives as an ordinary `insert_text` edit — the TEA mirror above stays consistent with zero extra code. Paste is clamped to the view's text capacity: when bytes were dropped, the keyboard event carries `edit_truncated = true` and your `TextBuffer` mirror sets its own `truncated` flag (check it if lost paste bytes matter to your UX; `TextBuffer` clamps oversized insertions at a UTF-8 boundary rather than dropping the edit). Shift+arrows/home/end extend the selection from the keyboard.
567
567
 
568
+ Deletion is platform-correct and semantic: Backspace/Delete remove one caret unit, Option+Backspace/Delete on macOS (Ctrl+Backspace/Delete elsewhere) remove one word, and Command+Backspace on macOS (with or without Shift) emits `delete_to_start` for single-line fields or `delete_to_line_start` for a textarea. Either event removes the active selection when non-empty; otherwise the former removes caret-to-offset-0 and the latter removes caret-to-hard-line-start (with CRLF atomic). Soft-wrapped textarea lines intentionally use the hard line start in v1. Apply the event through the same `TextBuffer` / TypeScript `applyTextInputEvent` mirror — it is one edit and therefore one undo step.
569
+
568
570
  Static text is selectable too: click-drag inside one `text` leaf or `paragraph` (markdown bodies included) selects with a highlight, cmd/ctrl+C copies it, and pressing anywhere else clears it. Selection and pressing coexist inside pressable rows — dragging selects (and presses nothing), a plain click collapses the selection and lands on the row's `on-press`. Selection is per-widget by design — there is no document model ordering text across widgets, so a drag cannot span two paragraphs (copy per paragraph). The selection survives rebuilds while that widget's text bytes are unchanged, and shows up in semantics/automation snapshots as `selection=a..b` on the widget line. Clipboard access from `update` is `fx.writeClipboard` / `fx.readClipboard` on the effects channel (see Effects) — never a `pbcopy` spawn; `runtime.readClipboard(&buffer)` / `runtime.writeClipboard(text)` remain for code that holds the runtime.
569
571
 
570
572
  ## Effects in Zig cores: subprocesses and HTTP from update
@@ -1003,7 +1005,7 @@ Rules:
1003
1005
 
1004
1006
  - `fx.registerImage(id, w, h, rgba8)` takes already-decoded straight-alpha RGBA8 (exactly `w*h*4` bytes; the runtime copies — your buffer is free on return). `fx.registerImageBytes(id, bytes)` decodes first. `fx.unregisterImage(id)` frees the slot. Outside UiApp: `Runtime.registerCanvasImage` / `registerCanvasImageBytes` / `unregisterCanvasImage`.
1005
1007
  - Re-registering an id replaces the pixels; every view repaints and GPU caches re-upload off the changed content fingerprint — no invalidation calls. For caches, mint fresh ids (effect-key style, monotonically increasing) and `unregisterImage` the evictee — never re-key different content onto a live id.
1006
- - Bounded and loud (`canvas_limits`): 16 slots (`max_registered_canvas_images`), 1 MiB per image (`max_registered_canvas_image_pixel_bytes`, 512×512 RGBA8 — avatar/icon scale). Errors: `error.ImageRegistryFull`, `error.ImageTooLarge`, `error.ImageDecodeFailed`, `error.InvalidImageId`/`InvalidImageDimensions`, `error.UnsupportedService` (codec-less platform).
1008
+ - Bounded and loud (`canvas_limits`): 16 slots, a 1 MiB decoded-pixel TARGET by default. Encoded images decode aspect-preservingly to fit, so real photos load and the reported dimensions are the registered geometry; raw-pixel `registerImage` remains strict. Image-centric apps may declare app.zon `.images = .{ .max_image_pixel_bytes = 8388608 }` (accepted range 1–8 MiB). Allocation is lazy per used slot, but 16 fully used 8 MiB slots are a declared 128 MiB high-water. Every encoded entry point, including direct `fx.registerImageBytes`, shares the separate flat 8 MiB source bound. Editors needing source-resolution pixels, 1:1 zoom, or tiles own that pipeline through a `gpu_surface` or media-surface producer, not this registry. Errors: `error.ImageRegistryFull`, `error.ImageTooLarge` (encoded source, raw pixels, or a codec-contract violation), `error.ImageDecodeFailed`, `error.InvalidImageId`/`InvalidImageDimensions`, `error.UnsupportedService`.
1007
1009
  - A draw referencing an unregistered id skips — a transient loading state can never fail presentation. `ui.avatar` clips a set image to the circle (`cover` fit) and renders the initials argument otherwise.
1008
1010
  - Registered images render in live presentation AND `renderCanvasScreenshot`/automation screenshots, so goldens can assert on them.
1009
1011
  - Deterministic tests: `harness.null_platform.image_decode = true` enables a strict decoder for the exact PNG subset `canvas.png.writeRgba8` emits — encode a raw RGBA fixture with the canvas PNG writer and drive the full decode→register→draw path with no bundled codec (`src/runtime/canvas_image_tests.zig` is the reference).
@@ -169,7 +169,7 @@ Four effect families deliver MANY results from one command — a keyed stream th
169
169
  - `Cmd.channelClose(key)` — close the open channel under the key, if any: staged posts flush, exactly one `"closed"` event (final drop totals aboard) dispatches the event arm, and the key frees. A key with no open channel no-ops.
170
170
  - `Cmd.audioCaptureStart(key, { source, sampleRate?, channels? }, { event })` — start a native `"microphone"` or `"system"` audio stream. The host converts into interleaved signed-16 little-endian PCM at 16/24/48 kHz and mono/stereo (default 48 kHz mono), in chunks no larger than 20 ms. The ten-field event arm is matched by NAME: `key`, `state` (exactly `"started" | "data" | "failed" | "stopped" | "rejected"`), `source` (exactly `"microphone" | "system"`), `sampleRate`, `channels`, `timestampMs`, `frames`, `pcm`, `droppedPending`, and `droppedTotal`. PCM is dispatch-lifetime bytes; the commit walker copies it when stored in the model. The bounded queue, wake behavior, drop accounting, journaling, and offline replay are the channel transport's. Microphone and system may run concurrently; a second start for one source replaces that source's prior key.
171
171
  - `Cmd.audioCaptureStop(key)` — synchronously quiesce native callbacks, flush already accepted chunks, deliver exactly one `"stopped"` terminal, and free the key. The key remains occupied until that terminal is delivered, so wait for `"stopped"` before reusing it; an earlier restart is rejected. A missing key no-ops. Declare `"microphone"` and/or `"system_audio"` in `app.zon` permissions so macOS dev executables and packaged apps carry the required usage descriptions.
172
- - `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.
172
+ - `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 actual registered 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`). The default registry has 16 slots and a 1 MiB decoded-pixel target per slot: platform codecs downscale photo-size sources at decode time, preserving aspect, instead of rejecting them. Image-centric apps may declare `.images = .{ .max_image_pixel_bytes = 8388608 }` in app.zon (1–8 MiB accepted); allocation stays lazy per used slot, but filling 16 ceiling-sized slots is a declared 128 MiB high-water. Encoded sources have their own flat 8 MiB bound; only over-bound source bytes report `"too_large"` in normal operation, never a cut decode. `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.
173
173
 
174
174
  ### The window verbs
175
175
 
@@ -291,7 +291,7 @@ One caveat for node-side pokes: the build resolves the `@native-sdk/core*` speci
291
291
  - **`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
292
  - **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
293
  - **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.
294
+ - **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
295
  - **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
296
 
297
297
  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 +355,8 @@ export type TextInputEvent =
355
355
  | { readonly kind: "delete_forward" }
356
356
  | { readonly kind: "delete_word_backward" }
357
357
  | { readonly kind: "delete_word_forward" }
358
+ | { readonly kind: "delete_to_start" }
359
+ | { readonly kind: "delete_to_line_start" }
358
360
  | { readonly kind: "clear" }
359
361
  | { readonly kind: "move_caret"; readonly move: TextCaretMove }
360
362
  | { readonly kind: "set_selection"; readonly selection: TextSelection }
@@ -392,6 +394,7 @@ The generated wiring detects each channel from an export (export exists → wire
392
394
 
393
395
  - **`commandMsg(name: string): Msg | null`** — menus, shortcuts, and chrome tabs, by command id (string equality works on `string` values).
394
396
  - **`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`.
397
+ - **`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
398
  - **`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
399
  - **`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
400
  - **`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 +444,7 @@ Every diagnostic carries one of these IDs plus the fix and the why, and every ru
441
444
  - **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
445
  - **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
446
  - **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.
447
+ - **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
448
  - **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
449
  - **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
450
  - **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 +550,7 @@ export function update(model: Model, msg: Msg): Model {
547
550
 
548
551
  ## Running a core as an app
549
552
 
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.
553
+ 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
554
 
552
555
  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
556
 
@@ -567,7 +570,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
567
570
  });
568
571
  ```
569
572
 
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`).
573
+ - `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
574
  - 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
575
  - `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
576
  - 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).