@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
@@ -20,6 +20,7 @@ import { spawnSync } from "node:child_process";
20
20
  import fs from "node:fs";
21
21
  import os from "node:os";
22
22
  import path from "node:path";
23
+ import { compilerArgv } from "./compiler_command.mjs";
23
24
 
24
25
  function parseArgs(argv) {
25
26
  const args = {};
@@ -56,10 +57,10 @@ for (const key of ["stage", "manifest", "frontend-sidecar", "out-archive", "out-
56
57
  if (key in args) args[key] = path.resolve(args[key]);
57
58
  }
58
59
  // --compiler is a COMMAND: a bare executable path (possibly containing
59
- // spaces) or an interpreter plus script ("node .../main.js"). A path
60
- // that exists is taken whole; anything else splits on whitespace.
60
+ // spaces) or an interpreter plus script ("node .../main.js"). The shared
61
+ // resolver also unwraps npm's Windows .cmd shim to its declared JS bin.
61
62
  const argv0 = args.compiler
62
- ? (fs.existsSync(args.compiler) ? [args.compiler] : args.compiler.split(/\s+/))
63
+ ? compilerArgv(args.compiler)
63
64
  : [process.execPath, args["compiler-js"]];
64
65
 
65
66
  // App and fixture build graphs state the host and target explicitly. A
@@ -17,6 +17,7 @@ import { spawnSync } from "node:child_process";
17
17
  import fs from "node:fs";
18
18
  import os from "node:os";
19
19
  import path from "node:path";
20
+ import { compilerArgv } from "./compiler_command.mjs";
20
21
 
21
22
  function parseArgs(argv) {
22
23
  const args = {};
@@ -143,7 +144,7 @@ for (const key of ["stage", "manifest", "contract", "out-exe", "out-archive", "c
143
144
  if (args[key]) args[key] = path.resolve(args[key]);
144
145
  }
145
146
  const argv0 = args.compiler
146
- ? (fs.existsSync(args.compiler) ? [args.compiler] : args.compiler.split(/\s+/))
147
+ ? compilerArgv(args.compiler)
147
148
  : [process.execPath, args["compiler-js"]];
148
149
 
149
150
  // Cross compiles hand the compiler its zig-cc lane: the target triple as
@@ -388,6 +388,7 @@ export function windowDescriptor(spec: WindowDescriptorSpec): WindowDescriptor {
388
388
  x: spec.x ?? null,
389
389
  y: spec.y ?? null,
390
390
  resizable: spec.resizable ?? true,
391
+ restorePolicy: spec.restorePolicy ?? "clamp_to_visible_screen",
391
392
  minWidth: spec.minWidth ?? 0,
392
393
  minHeight: spec.minHeight ?? 0,
393
394
  titlebar: spec.titlebar ?? "standard",
@@ -1,4 +1,11 @@
1
1
  export type { TextCaretDirection, TextCaretMove, TextSelection, TextInputEvent } from "./text.js";
2
+ export type ThemeStatePack = "house" | "geist";
3
+ export type ThemeStateColorScheme = "light" | "dark" | "system";
4
+ export type ThemeState = {
5
+ readonly pack?: ThemeStatePack;
6
+ readonly colorScheme?: ThemeStateColorScheme;
7
+ readonly accent?: string;
8
+ };
2
9
  export type StatusItemTone = "normal" | "warning" | "critical";
3
10
  export type StatusItemMenuRole = "command" | "info" | "header" | "hero" | "agent" | "context";
4
11
  export interface StatusItemModifiers {
@@ -48,6 +55,7 @@ export interface StatusItemDescriptor {
48
55
  }
49
56
  export type WindowClosePolicy = "quit" | "hide";
50
57
  export type WindowTitlebarStyle = "standard" | "hidden_inset" | "hidden_inset_tall" | "chromeless";
58
+ export type WindowRestorePolicy = "clamp_to_visible_screen" | "center_on_primary";
51
59
  export interface WindowDescriptorSpec {
52
60
  readonly label: Uint8Array;
53
61
  readonly canvasLabel: Uint8Array;
@@ -57,6 +65,7 @@ export interface WindowDescriptorSpec {
57
65
  readonly x?: number | null;
58
66
  readonly y?: number | null;
59
67
  readonly resizable?: boolean;
68
+ readonly restorePolicy?: WindowRestorePolicy;
60
69
  readonly minWidth?: number;
61
70
  readonly minHeight?: number;
62
71
  readonly titlebar?: WindowTitlebarStyle;
@@ -77,6 +86,7 @@ export interface WindowDescriptor {
77
86
  readonly x: number | null;
78
87
  readonly y: number | null;
79
88
  readonly resizable: boolean;
89
+ readonly restorePolicy: WindowRestorePolicy;
80
90
  readonly minWidth: number;
81
91
  readonly minHeight: number;
82
92
  readonly titlebar: WindowTitlebarStyle;
@@ -37,6 +37,8 @@
37
37
  // - `AppearanceEvent`, `ChromeEvent`, `AudioEvent`: the full arm
38
38
  // payload shapes, canonical and importable for helper signatures
39
39
  // (an arm value is structurally assignable to its event record).
40
+ // - `ThemeState`: the model-derived built-in theme axes returned by
41
+ // `themeState(model)`; omitted fields inherit the manifest/system.
40
42
  // - `StatusItemState`, `StatusItemDescriptor`, and their nested records:
41
43
  // the model-derived shell returned by `statusItem(model)` or keyed
42
44
  // `statusItems(model)`; the generated launcher refreshes shell,
@@ -44,6 +46,20 @@
44
46
 
45
47
  export type { TextCaretDirection, TextCaretMove, TextSelection, TextInputEvent } from "./text.ts";
46
48
 
49
+ /// The stock theme axes a TypeScript core may derive from committed model
50
+ /// state. Omit `pack`/`accent` to inherit app.zon; omit `colorScheme` (or
51
+ /// return `"system"`) to follow the OS. High contrast and reduced motion
52
+ /// remain system-owned, and high contrast suppresses accent overrides.
53
+ export type ThemeStatePack = "house" | "geist";
54
+
55
+ export type ThemeStateColorScheme = "light" | "dark" | "system";
56
+
57
+ export type ThemeState = {
58
+ readonly pack?: ThemeStatePack;
59
+ readonly colorScheme?: ThemeStateColorScheme;
60
+ readonly accent?: string;
61
+ };
62
+
47
63
  /// One row in a menu-bar status item's menu. Non-separator rows need a
48
64
  /// unique non-zero `id`, a non-empty `label`, and (when actionable) a
49
65
  /// command name accepted by `commandMsg`. Rich readout roles may carry
@@ -119,6 +135,8 @@ export type WindowClosePolicy = "quit" | "hide";
119
135
 
120
136
  export type WindowTitlebarStyle = "standard" | "hidden_inset" | "hidden_inset_tall" | "chromeless";
121
137
 
138
+ export type WindowRestorePolicy = "clamp_to_visible_screen" | "center_on_primary";
139
+
122
140
  /// Author-facing input to `windowDescriptor`; omitted fields receive the
123
141
  /// same defaults as UiApp.WindowDescriptor.
124
142
  export interface WindowDescriptorSpec {
@@ -130,6 +148,7 @@ export interface WindowDescriptorSpec {
130
148
  readonly x?: number | null;
131
149
  readonly y?: number | null;
132
150
  readonly resizable?: boolean;
151
+ readonly restorePolicy?: WindowRestorePolicy;
133
152
  readonly minWidth?: number;
134
153
  readonly minHeight?: number;
135
154
  readonly titlebar?: WindowTitlebarStyle;
@@ -156,6 +175,7 @@ export interface WindowDescriptor {
156
175
  readonly x: number | null;
157
176
  readonly y: number | null;
158
177
  readonly resizable: boolean;
178
+ readonly restorePolicy: WindowRestorePolicy;
159
179
  readonly minWidth: number;
160
180
  readonly minHeight: number;
161
181
  readonly titlebar: WindowTitlebarStyle;
@@ -247,8 +267,10 @@ export interface PinchEvent {
247
267
  readonly y: number;
248
268
  }
249
269
 
250
- /// A file drop's optional point in view-local canvas coordinates. Desktop
251
- /// hosts that only know the target window leave `FileDropEvent.point` null.
270
+ /// A file drop's optional point in top-left-origin local coordinates. A
271
+ /// non-empty `FileDropEvent.viewLabel` names its canvas or WebView coordinate
272
+ /// space; an empty label may carry window-content coordinates. Hosts that
273
+ /// cannot resolve local coordinates leave `FileDropEvent.point` null.
252
274
  export interface FileDropPoint {
253
275
  readonly x: number;
254
276
  readonly y: number;
@@ -256,9 +278,12 @@ export interface FileDropPoint {
256
278
 
257
279
  /// The app-level file-drop channel's record (`dropMsg(drop)`). `windowId`
258
280
  /// and `viewLabel` identify the source; `point` is present when the host can
259
- /// resolve view-local coordinates. Paths are byte text so arbitrary UTF-8
260
- /// filesystem names cross without becoming runtime JS strings. Return null
261
- /// from `dropMsg` to ignore a drop, or map it to an ordinary Msg.
281
+ /// resolve local coordinates. The macOS system host reports labeled canvas or
282
+ /// WebView coordinates and degrades unlabeled regions to window-content
283
+ /// coordinates; hosts without either leave `point` null. Paths are byte text
284
+ /// so arbitrary UTF-8 filesystem names cross without becoming runtime JS
285
+ /// strings. Return null from `dropMsg` to ignore a drop, or map it to an
286
+ /// ordinary Msg.
262
287
  export interface FileDropEvent {
263
288
  readonly windowId: number;
264
289
  readonly viewLabel: string;
@@ -22,6 +22,10 @@ export type TextInputEvent = {
22
22
  readonly kind: "delete_word_backward";
23
23
  } | {
24
24
  readonly kind: "delete_word_forward";
25
+ } | {
26
+ readonly kind: "delete_to_start";
27
+ } | {
28
+ readonly kind: "delete_to_line_start";
25
29
  } | {
26
30
  readonly kind: "clear";
27
31
  } | {
@@ -56,6 +56,8 @@ export type TextInputEvent =
56
56
  | { readonly kind: "delete_forward" }
57
57
  | { readonly kind: "delete_word_backward" }
58
58
  | { readonly kind: "delete_word_forward" }
59
+ | { readonly kind: "delete_to_start" }
60
+ | { readonly kind: "delete_to_line_start" }
59
61
  | { readonly kind: "clear" }
60
62
  | { readonly kind: "move_caret"; readonly move: TextCaretMove }
61
63
  | { readonly kind: "set_selection"; readonly selection: TextSelection }
@@ -417,6 +419,51 @@ function deleteWordForwardTextEdit(state: TextEditState, capacity: number): Text
417
419
  );
418
420
  }
419
421
 
422
+ function textLineStartOffset(text: Uint8Array, offset: number): number {
423
+ let cursor = snapTextOffset(text, offset);
424
+ while (cursor > 0 && text[cursor - 1] !== 0x0a) cursor -= 1;
425
+ return cursor;
426
+ }
427
+
428
+ function deleteToStartTextEdit(state: TextEditState, capacity: number): TextEditState | null {
429
+ const range = activeTextReplaceRange(state);
430
+ if (!rangeIsCollapsed(range, state.text.length)) {
431
+ return replaceTextEditRange(state, range, new Uint8Array(0), capacity, null, 0);
432
+ }
433
+ const caret = snapTextCaretOffset(state.text, state.selection.focus);
434
+ if (caret === 0) {
435
+ return { text: state.text, selection: caretSelectionAt(0, 0), composition: null };
436
+ }
437
+ return replaceTextEditRange(
438
+ state,
439
+ { start: 0, end: caret },
440
+ new Uint8Array(0),
441
+ capacity,
442
+ null,
443
+ 0,
444
+ );
445
+ }
446
+
447
+ function deleteToLineStartTextEdit(state: TextEditState, capacity: number): TextEditState | null {
448
+ const range = activeTextReplaceRange(state);
449
+ if (!rangeIsCollapsed(range, state.text.length)) {
450
+ return replaceTextEditRange(state, range, new Uint8Array(0), capacity, null, 0);
451
+ }
452
+ const caret = snapTextCaretOffset(state.text, state.selection.focus);
453
+ const lineStart = textLineStartOffset(state.text, caret);
454
+ if (lineStart === caret) {
455
+ return { text: state.text, selection: caretSelectionAt(caret, caret), composition: null };
456
+ }
457
+ return replaceTextEditRange(
458
+ state,
459
+ { start: lineStart, end: caret },
460
+ new Uint8Array(0),
461
+ capacity,
462
+ null,
463
+ 0,
464
+ );
465
+ }
466
+
420
467
  function moveTextCaret(state: TextEditState, move: TextCaretMove): TextEditState {
421
468
  const range = selectionRange(state.selection, state.text.length);
422
469
  const focus = snapTextCaretOffset(state.text, state.selection.focus);
@@ -472,6 +519,10 @@ export function applyTextInputEvent(
472
519
  return deleteWordBackwardTextEdit(normalized, capacity);
473
520
  case "delete_word_forward":
474
521
  return deleteWordForwardTextEdit(normalized, capacity);
522
+ case "delete_to_start":
523
+ return deleteToStartTextEdit(normalized, capacity);
524
+ case "delete_to_line_start":
525
+ return deleteToLineStartTextEdit(normalized, capacity);
475
526
  case "clear":
476
527
  return { text: new Uint8Array(0), selection: { anchor: 0, focus: 0 }, composition: null };
477
528
  case "move_caret":
@@ -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
@@ -1417,12 +1467,13 @@ export class SubsetChecker {
1417
1467
  return candidate?.type.k === "optional" && ["number", "i64", "f64", "numAlias"].includes(candidate.type.inner.k);
1418
1468
  };
1419
1469
  const valid =
1420
- names.join(",") === "activateOnShow,allowsFullscreen,alwaysOnTop,canvasLabel,clickThrough,closePolicy,height,label,minHeight,minWidth,onCloseCommand,resizable,title,titlebar,transparent,width,x,y" &&
1470
+ names.join(",") === "activateOnShow,allowsFullscreen,alwaysOnTop,canvasLabel,clickThrough,closePolicy,height,label,minHeight,minWidth,onCloseCommand,resizable,restorePolicy,title,titlebar,transparent,width,x,y" &&
1421
1471
  field("label")?.type.k === "bytes" &&
1422
1472
  field("canvasLabel")?.type.k === "bytes" &&
1423
1473
  field("title")?.type.k === "bytes" &&
1424
1474
  numeric("width") && numeric("height") && optionalNumeric("x") && optionalNumeric("y") &&
1425
- field("resizable")?.type.k === "bool" && numeric("minWidth") && numeric("minHeight") &&
1475
+ field("resizable")?.type.k === "bool" && enumMembersAre("restorePolicy", ["clamp_to_visible_screen", "center_on_primary"]) &&
1476
+ numeric("minWidth") && numeric("minHeight") &&
1426
1477
  enumMembersAre("titlebar", ["standard", "hidden_inset", "hidden_inset_tall", "chromeless"]) &&
1427
1478
  field("transparent")?.type.k === "bool" && field("alwaysOnTop")?.type.k === "bool" &&
1428
1479
  field("clickThrough")?.type.k === "bool" && field("activateOnShow")?.type.k === "bool" &&
@@ -1871,7 +1922,7 @@ export class SubsetChecker {
1871
1922
  /// entry points, but the exports themselves live in the entry module.
1872
1923
  private static readonly entryOnlyExports = new Set([
1873
1924
  "update", "initialModel", "subscriptions", "migrate",
1874
- "commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs", "themePack", "statusItem", "statusItems", "windows",
1925
+ "commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs", "themePack", "themeState", "statusItem", "statusItems", "windows",
1875
1926
  "viewUnbound", "modelUnbound", "msgUnbound",
1876
1927
  ]);
1877
1928
 
@@ -2039,6 +2090,13 @@ export class SubsetChecker {
2039
2090
  : this.table.unions.get(typeName)?.arms.flatMap((a) => [...a.fields]) ?? [];
2040
2091
  for (const f of fields) {
2041
2092
  const decl = f.decl;
2093
+ if (ts.isPropertySignature(decl) && decl.questionToken) {
2094
+ this.report(
2095
+ "NS1012",
2096
+ `Optional field \`${f.tsName}?\` in the ${typeName} tree has an implicit undefined state — spell the empty explicitly as \`${f.tsName}: T | null\`.`,
2097
+ decl,
2098
+ );
2099
+ }
2042
2100
  if (ts.isPropertySignature(decl) && decl.type && ts.isFunctionTypeNode(decl.type)) {
2043
2101
  this.report("NS1003", `\`${f.tsName}\` stores a function in the ${typeName} tree.`, decl);
2044
2102
  }
@@ -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
 
@@ -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
 
@@ -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
@@ -876,7 +878,7 @@ The `.wake` platform event is how live platforms marshal worker completions onto
876
878
 
877
879
  ## Secondary windows
878
880
 
879
- In the default TypeScript path, export `windows(model): readonly WindowDescriptor[]` and put each possible window's Native markup at `src/windows/<label>.native`. Spell each constructor identity as a literal `label: asciiBytes("<label>")`; `native check` and every build reject dynamic labels and missing roots. Those roots may import shared components nested under `src/windows/`; the generated launcher compiles and hot-reloads the full closure. Use `windowDescriptor` from `@native-sdk/core`; its `closePolicy` field accepts `"quit"` or `"hide"`, and `titlebar` includes `"chromeless"`. A `"quit"` user close routes `onCloseCommand` through `commandMsg`; a `"hide"` close preserves the window and view and dispatches no close command. The `ts-core` skill has the complete descriptor and example.
881
+ In the default TypeScript path, export `windows(model): readonly WindowDescriptor[]` and put each possible window's Native markup at `src/windows/<label>.native`. Spell each constructor identity as a literal `label: asciiBytes("<label>")`; `native check` and every build reject dynamic labels and missing roots. Those roots may import shared components nested under `src/windows/`; the generated launcher compiles and hot-reloads the full closure. Use `windowDescriptor` from `@native-sdk/core`; its `restorePolicy` field accepts `"clamp_to_visible_screen"` or `"center_on_primary"` (centering is currently macOS-only), `closePolicy` accepts `"quit"` or `"hide"`, and `titlebar` includes `"chromeless"`. A `"quit"` user close routes `onCloseCommand` through `commandMsg`; a `"hide"` close preserves the window and view and dispatches no close command. The `ts-core` skill has the complete descriptor and example.
880
882
 
881
883
  ### Zig cores: `windows_fn` + `window_view`
882
884
 
@@ -903,6 +905,7 @@ fn windowView(ui: *App.Ui, model: *const Model, window_label: []const u8) App.Ui
903
905
  Rules that matter:
904
906
  - **Every canvas label must be unique across the app** (main + declared windows); input routes back by it, and automation verbs (`widget-click <canvas-label> <id>`, `screenshot`) address any window's canvas the same way.
905
907
  - **Close policy**: `WindowDescriptor.close_policy` is `.quit` by default; a user close really closes and dispatches `on_close` (the dismissal precedent), so clear the open flag in `update` — or keep declaring the window and the next rebuild brings it back (source wins). `.hide` keeps the same window, slot, and views alive, dispatches no `on_close`, and `showWindow(label)` reveals it. A close the model itself initiated never echoes a Msg. Existing platform safeguards still apply: unsupported hosts refuse `.hide` rather than strand an unreachable window.
908
+ - **Restore policy**: `WindowDescriptor.restore_policy` is `.clamp_to_visible_screen` by default. On macOS, `.center_on_primary` centers a fresh descriptor with no authored `x`/`y`; Windows and Linux currently keep their native default placement. Model-declared windows deliberately do not restore persisted frames.
906
909
  - **Budget**: at most `UiApp.max_ui_windows` (4) declared windows; excess warns and is ignored. Every dispatched Msg rebuilds every open window's view.
907
910
  - **Present-before-show**: canvas windows (any `gpu_surface` view — startup, scene, and declared windows alike) are created ordered-out and become visible only after their first canvas frame presents, so opening one never flashes blank. Automatic (`WindowOptions.show = .on_first_present`, derived from the views); webview windows show immediately. The null platform records `window_show`, `window_visible`, and present/shown sequence numbers for ordering assertions; `NATIVE_SDK_WINDOW_TIMING=1` logs create→show latency on macOS.
908
911
  - **Markup binds ONE window's content** — there is no `window` element in the closed grammar. A markup-authored secondary window is a `canvas.CompiledMarkupView` whose `build` `window_view` calls for that label.