@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
@@ -44,7 +44,8 @@
44
44
  //! the committed model. One model-helper convention joins that wiring:
45
45
  //! an exported `themePack(model): "house" | "geist"` helper selects the
46
46
  //! stock pack live through `theme_fn`, without taking ownership of the
47
- //! system appearance axes. An exported
47
+ //! system appearance axes; `themeState(model)` subsumes it with scheme and
48
+ //! accent axes through `theme_state_fn`. An exported
48
49
  //! `statusItem(model): StatusItemState` helper similarly owns one complete
49
50
  //! menu-bar item through `status_item_fn`; `statusItems(model)` owns a keyed
50
51
  //! collection through `status_items_fn`. Both keep shell, presentation, and
@@ -80,6 +81,27 @@ const ts_core_host = @import("ts_core_host.zig");
80
81
 
81
82
  const ts_ui_app_log = std.log.scoped(.zero_ts_ui_app);
82
83
 
84
+ /// Quota for a comptime scan of an app-authored type. TS `Msg` unions may
85
+ /// legally carry 256 arms; include total identifier bytes because
86
+ /// `std.mem.eql`'s comptime scalar path scales with the compared names.
87
+ fn typeScanQuota(comptime T: type) u32 {
88
+ const fields = switch (@typeInfo(T)) {
89
+ .@"struct" => |info| info.fields,
90
+ .@"union" => |info| info.fields,
91
+ .@"enum" => |info| info.fields,
92
+ else => return 2_000,
93
+ };
94
+ var name_bytes: u64 = 0;
95
+ for (fields) |field| name_bytes += field.name.len;
96
+ const quota: u64 = 100_000 + @as(u64, fields.len) * 1_024 + name_bytes * 256;
97
+ return @intCast(@min(quota, std.math.maxInt(u32)));
98
+ }
99
+
100
+ fn scaledTypeScanQuota(comptime T: type, comptime scans: usize) u32 {
101
+ const quota = @as(u64, typeScanQuota(T)) * @max(scans, 1);
102
+ return @intCast(@min(quota, std.math.maxInt(u32)));
103
+ }
104
+
83
105
  pub fn TsUiApp(comptime core: type) type {
84
106
  return struct {
85
107
  /// The effect bridge — shared with any direct `TsCoreHost(core)`
@@ -92,6 +114,9 @@ pub fn TsUiApp(comptime core: type) type {
92
114
  pub const Options = App.Options;
93
115
  pub const Effects = App.Effects;
94
116
  pub const Ui = App.Ui;
117
+ /// Shared with generated launchers that perform their own Msg scans.
118
+ pub const msg_scan_quota = typeScanQuota(Msg);
119
+ pub const persist_route_scan_quota = scaledTypeScanQuota(Msg, 3);
95
120
 
96
121
  /// Internal keyed-channel namespace for persistence write failures
97
122
  /// ("TSPR"). It never shares an app-authored TS bridge index.
@@ -223,12 +248,14 @@ pub fn TsUiApp(comptime core: type) type {
223
248
  /// a typo or payload mismatch fails during `native build`, before a
224
249
  /// first boot can reach the dynamic dispatch path below.
225
250
  pub fn validatePersistRoutes(comptime routes: PersistRoutes) void {
251
+ @setEvalBranchQuota(persist_route_scan_quota);
226
252
  validatePersistRoute(routes.ok, void, "ok");
227
253
  validatePersistRoute(routes.none, void, "none");
228
254
  validatePersistRoute(routes.err, []const u8, "err");
229
255
  }
230
256
 
231
257
  fn validatePersistRoute(comptime route: []const u8, comptime Payload: type, comptime role: []const u8) void {
258
+ @setEvalBranchQuota(msg_scan_quota);
232
259
  inline for (@typeInfo(Msg).@"union".fields) |arm| {
233
260
  if (comptime std.mem.eql(u8, arm.name, route)) {
234
261
  if (arm.type != Payload) {
@@ -379,12 +406,22 @@ pub fn TsUiApp(comptime core: type) type {
379
406
  // external-core mirror. The app owns only the pack; UiApp's
380
407
  // stock-token path keeps following the OS appearance.
381
408
  if (comptime @hasDecl(Model, "themePack")) {
409
+ if (comptime @hasDecl(Model, "themeState")) {
410
+ @compileError("TsUiApp: export either themePack or themeState, not both");
411
+ }
382
412
  if (options.theme_fn != null) {
383
413
  @panic("TsUiApp wires theme_fn from the core's themePack helper - remove the wiring's theme_fn");
384
414
  }
385
415
  comptime validateThemePackHelper();
386
416
  stamped.theme_fn = themePackAdapter;
387
417
  }
418
+ if (comptime @hasDecl(Model, "themeState")) {
419
+ if (options.theme_state_fn != null or options.theme_fn != null) {
420
+ @panic("TsUiApp wires theme_state_fn from the core's themeState helper - remove the wiring's theme_state_fn/theme_fn");
421
+ }
422
+ comptime validateThemeStateHelper();
423
+ stamped.theme_state_fn = themeStateAdapter;
424
+ }
388
425
  // A statusItem helper is the TS app's model-derived shell
389
426
  // declaration. UiApp installs it on the first frame and
390
427
  // independently patches shell/presentation/menu after each
@@ -503,6 +540,82 @@ pub fn TsUiApp(comptime core: type) type {
503
540
  }
504
541
  }
505
542
 
543
+ fn themeStateAdapter(model: *const Model) App.ThemeState {
544
+ const params = @typeInfo(@TypeOf(Model.themeState)).@"fn".params;
545
+ const raw_state = if (comptime params.len == 1)
546
+ model.themeState()
547
+ else
548
+ model.themeState(core.rt.frameAllocator());
549
+ const state = if (comptime @typeInfo(@TypeOf(raw_state)) == .pointer) raw_state.* else raw_state;
550
+ const accent = if (state.accent) |value| parseThemeAccent(value) else null;
551
+ return .{
552
+ .pack = if (state.pack) |pack| canvas.ThemePack.fromName(@tagName(pack)).? else null,
553
+ .color_scheme = if (state.colorScheme) |scheme| themeColorScheme(scheme) else .system,
554
+ .accent = accent,
555
+ .invalid_accent = if (state.accent != null and accent == null) state.accent else null,
556
+ };
557
+ }
558
+
559
+ fn themeColorScheme(value: anytype) App.ThemeColorScheme {
560
+ const name = @tagName(value);
561
+ inline for (std.meta.fields(App.ThemeColorScheme)) |field| {
562
+ if (std.mem.eql(u8, name, field.name)) return @enumFromInt(field.value);
563
+ }
564
+ unreachable;
565
+ }
566
+
567
+ fn parseThemeAccent(value: []const u8) ?canvas.Color {
568
+ if (value.len != 7 or value[0] != '#') return null;
569
+ const r = themeHexByte(value[1], value[2]) orelse return null;
570
+ const g = themeHexByte(value[3], value[4]) orelse return null;
571
+ const b = themeHexByte(value[5], value[6]) orelse return null;
572
+ return canvas.Color.rgb8(r, g, b);
573
+ }
574
+
575
+ fn themeHexByte(hi: u8, lo: u8) ?u8 {
576
+ const h = themeHexNibble(hi) orelse return null;
577
+ const l = themeHexNibble(lo) orelse return null;
578
+ return h * 16 + l;
579
+ }
580
+
581
+ fn themeHexNibble(byte: u8) ?u8 {
582
+ return switch (byte) {
583
+ '0'...'9' => byte - '0',
584
+ 'a'...'f' => byte - 'a' + 10,
585
+ 'A'...'F' => byte - 'A' + 10,
586
+ else => null,
587
+ };
588
+ }
589
+
590
+ fn validateThemeStateHelper() void {
591
+ const teaching = "TsUiApp: themeState must be exported from core.ts as themeState(model: Model): ThemeState; import ThemeState from @native-sdk/core/events";
592
+ const helper_info = @typeInfo(@TypeOf(Model.themeState));
593
+ if (helper_info != .@"fn") @compileError(teaching);
594
+ const function = helper_info.@"fn";
595
+ if ((function.params.len != 1 and function.params.len != 2) or function.params[0].type == null or function.params[0].type.? != *const Model) {
596
+ @compileError(teaching);
597
+ }
598
+ if (function.params.len == 2) {
599
+ if (function.params[1].type == null or function.params[1].type.? != std.mem.Allocator or
600
+ !@hasDecl(core, "rt") or !@hasDecl(core.rt, "frameAllocator"))
601
+ {
602
+ @compileError(teaching);
603
+ }
604
+ }
605
+ const RawState = function.return_type orelse @compileError(teaching);
606
+ const State = statusItemRecordType(RawState, teaching);
607
+ const info = @typeInfo(State).@"struct";
608
+ if (info.fields.len != 3 or !@hasField(State, "pack") or !@hasField(State, "colorScheme") or !@hasField(State, "accent")) {
609
+ @compileError(teaching);
610
+ }
611
+ if (!optionalEnumType(@FieldType(State, "pack"), &.{ "house", "geist" }) or
612
+ !optionalEnumType(@FieldType(State, "colorScheme"), &.{ "light", "dark", "system" }) or
613
+ @FieldType(State, "accent") != ?[]const u8)
614
+ {
615
+ @compileError(teaching);
616
+ }
617
+ }
618
+
506
619
  /// Convert the compiled core's canonical status-item records into
507
620
  /// the platform rows UiApp already knows how to validate, copy,
508
621
  /// hash, install, and patch. Interface records cross the core ABI
@@ -607,6 +720,7 @@ pub fn TsUiApp(comptime core: type) type {
607
720
  .x = optionalWindowFloat(window.x),
608
721
  .y = optionalWindowFloat(window.y),
609
722
  .resizable = window.resizable,
723
+ .restore_policy = windowRestorePolicy(window.restorePolicy),
610
724
  .min_width = statusItemFloat(window.minWidth),
611
725
  .min_height = statusItemFloat(window.minHeight),
612
726
  .titlebar = windowTitlebar(window.titlebar),
@@ -639,6 +753,14 @@ pub fn TsUiApp(comptime core: type) type {
639
753
  unreachable;
640
754
  }
641
755
 
756
+ fn windowRestorePolicy(value: anytype) @import("app_manifest").WindowRestorePolicy {
757
+ const Target = @import("app_manifest").WindowRestorePolicy;
758
+ inline for (std.meta.fields(Target)) |field| {
759
+ if (std.mem.eql(u8, @tagName(value), field.name)) return @enumFromInt(field.value);
760
+ }
761
+ unreachable;
762
+ }
763
+
642
764
  fn windowClosePolicy(value: anytype) @import("app_manifest").WindowClosePolicy {
643
765
  const Target = @import("app_manifest").WindowClosePolicy;
644
766
  inline for (std.meta.fields(Target)) |field| {
@@ -905,9 +1027,10 @@ pub fn TsUiApp(comptime core: type) type {
905
1027
  if (return_info != .pointer or return_info.pointer.size != .slice or !return_info.pointer.is_const) @compileError(teaching);
906
1028
  const Window = statusItemRecordType(return_info.pointer.child, teaching);
907
1029
  const info = @typeInfo(Window).@"struct";
908
- if (info.fields.len != 18 or !@hasField(Window, "label") or !@hasField(Window, "canvasLabel") or
1030
+ if (info.fields.len != 19 or !@hasField(Window, "label") or !@hasField(Window, "canvasLabel") or
909
1031
  !@hasField(Window, "title") or !@hasField(Window, "width") or !@hasField(Window, "height") or
910
1032
  !@hasField(Window, "x") or !@hasField(Window, "y") or !@hasField(Window, "resizable") or
1033
+ !@hasField(Window, "restorePolicy") or
911
1034
  !@hasField(Window, "minWidth") or !@hasField(Window, "minHeight") or !@hasField(Window, "titlebar") or
912
1035
  !@hasField(Window, "transparent") or !@hasField(Window, "alwaysOnTop") or !@hasField(Window, "clickThrough") or
913
1036
  !@hasField(Window, "activateOnShow") or !@hasField(Window, "allowsFullscreen") or
@@ -916,6 +1039,7 @@ pub fn TsUiApp(comptime core: type) type {
916
1039
  @FieldType(Window, "title") != []const u8 or !statusItemNumericType(@FieldType(Window, "width")) or
917
1040
  !statusItemNumericType(@FieldType(Window, "height")) or !optionalNumericType(@FieldType(Window, "x")) or
918
1041
  !optionalNumericType(@FieldType(Window, "y")) or @FieldType(Window, "resizable") != bool or
1042
+ !statusItemEnumType(@FieldType(Window, "restorePolicy"), &.{ "clamp_to_visible_screen", "center_on_primary" }) or
919
1043
  !statusItemNumericType(@FieldType(Window, "minWidth")) or !statusItemNumericType(@FieldType(Window, "minHeight")) or
920
1044
  !statusItemEnumType(@FieldType(Window, "titlebar"), &.{ "standard", "hidden_inset", "hidden_inset_tall", "chromeless" }) or
921
1045
  @FieldType(Window, "transparent") != bool or @FieldType(Window, "alwaysOnTop") != bool or
@@ -930,6 +1054,11 @@ pub fn TsUiApp(comptime core: type) type {
930
1054
  return info == .optional and statusItemNumericType(info.optional.child);
931
1055
  }
932
1056
 
1057
+ fn optionalEnumType(comptime T: type, comptime expected: []const []const u8) bool {
1058
+ const info = @typeInfo(T);
1059
+ return info == .optional and statusItemEnumType(info.optional.child, expected);
1060
+ }
1061
+
933
1062
  fn statusItemNumericType(comptime T: type) bool {
934
1063
  return @typeInfo(T) == .int or @typeInfo(T) == .float;
935
1064
  }
@@ -1029,6 +1158,7 @@ pub fn TsUiApp(comptime core: type) type {
1029
1158
  }
1030
1159
 
1031
1160
  fn persistOutcomeMsg(event: runtime_effects.EffectChannelEvent) Msg {
1161
+ @setEvalBranchQuota(msg_scan_quota);
1032
1162
  const reason: []const u8 = switch (event.kind) {
1033
1163
  .data => event.bytes,
1034
1164
  .rejected => "rejected",
@@ -1044,6 +1174,7 @@ pub fn TsUiApp(comptime core: type) type {
1044
1174
  }
1045
1175
 
1046
1176
  fn dispatchPersistVoid(fx: *Effects, route: []const u8) void {
1177
+ @setEvalBranchQuota(msg_scan_quota);
1047
1178
  inline for (@typeInfo(Msg).@"union".fields) |arm| {
1048
1179
  if (comptime arm.type == void) {
1049
1180
  if (std.mem.eql(u8, arm.name, route)) {
@@ -1056,6 +1187,7 @@ pub fn TsUiApp(comptime core: type) type {
1056
1187
  }
1057
1188
 
1058
1189
  fn dispatchPersistError(fx: *Effects, route: []const u8, reason: []const u8) void {
1190
+ @setEvalBranchQuota(msg_scan_quota);
1059
1191
  inline for (@typeInfo(Msg).@"union".fields) |arm| {
1060
1192
  if (comptime arm.type == []const u8) {
1061
1193
  if (std.mem.eql(u8, arm.name, route)) {
@@ -1098,6 +1230,7 @@ pub fn TsUiApp(comptime core: type) type {
1098
1230
  /// One env delivery: resolve the arm by name and dispatch the
1099
1231
  /// value through a full core cycle.
1100
1232
  fn dispatchOneEnvValue(fx: *Effects, msg: []const u8, value: []const u8) void {
1233
+ @setEvalBranchQuota(msg_scan_quota);
1101
1234
  inline for (@typeInfo(Msg).@"union".fields) |arm| {
1102
1235
  if (comptime arm.type == []const u8) {
1103
1236
  if (std.mem.eql(u8, arm.name, msg)) {
@@ -1117,6 +1250,7 @@ pub fn TsUiApp(comptime core: type) type {
1117
1250
  /// hand-assembled cores: every `envMsgs` entry must name a Msg
1118
1251
  /// arm carrying exactly one bytes payload.
1119
1252
  fn validateEnvMsgs() void {
1253
+ @setEvalBranchQuota(scaledTypeScanQuota(Msg, core.envMsgs.len));
1120
1254
  for (core.envMsgs) |entry| {
1121
1255
  var found = false;
1122
1256
  for (@typeInfo(Msg).@"union".fields) |arm| {
@@ -1333,6 +1467,7 @@ pub fn TsUiApp(comptime core: type) type {
1333
1467
  /// error the frontend's NS1033 re-derives for hand-written
1334
1468
  /// cores.
1335
1469
  fn channelArmIndex(comptime tag: []const u8, comptime channel: []const u8) usize {
1470
+ @setEvalBranchQuota(msg_scan_quota);
1336
1471
  for (@typeInfo(Msg).@"union".fields, 0..) |arm, index| {
1337
1472
  if (std.mem.eql(u8, arm.name, tag)) return index;
1338
1473
  }
@@ -1513,6 +1648,7 @@ test "TypeScript statusItems adapter validates and projects canonical descriptor
1513
1648
 
1514
1649
  const WindowsAdapterTestCore = struct {
1515
1650
  const Titlebar = enum { standard, hidden_inset, hidden_inset_tall, chromeless };
1651
+ const RestorePolicy = enum { clamp_to_visible_screen, center_on_primary };
1516
1652
  const ClosePolicy = enum { quit, hide };
1517
1653
  const Descriptor = struct {
1518
1654
  label: []const u8,
@@ -1523,6 +1659,7 @@ const WindowsAdapterTestCore = struct {
1523
1659
  x: ?f64,
1524
1660
  y: ?f64,
1525
1661
  resizable: bool,
1662
+ restorePolicy: RestorePolicy,
1526
1663
  minWidth: f64,
1527
1664
  minHeight: f64,
1528
1665
  titlebar: Titlebar,
@@ -1536,11 +1673,11 @@ const WindowsAdapterTestCore = struct {
1536
1673
  };
1537
1674
 
1538
1675
  const descriptors = [_]Descriptor{
1539
- .{ .label = "one", .canvasLabel = "one-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .minWidth = 0, .minHeight = 0, .titlebar = .chromeless, .transparent = true, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1540
- .{ .label = "two", .canvasLabel = "two-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1541
- .{ .label = "three", .canvasLabel = "three-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1542
- .{ .label = "four", .canvasLabel = "four-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1543
- .{ .label = "excess", .canvasLabel = "excess-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1676
+ .{ .label = "one", .canvasLabel = "one-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .restorePolicy = .center_on_primary, .minWidth = 0, .minHeight = 0, .titlebar = .chromeless, .transparent = true, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1677
+ .{ .label = "two", .canvasLabel = "two-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .restorePolicy = .clamp_to_visible_screen, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1678
+ .{ .label = "three", .canvasLabel = "three-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .restorePolicy = .clamp_to_visible_screen, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1679
+ .{ .label = "four", .canvasLabel = "four-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .restorePolicy = .clamp_to_visible_screen, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1680
+ .{ .label = "excess", .canvasLabel = "excess-canvas", .title = "", .width = 100, .height = 100, .x = null, .y = null, .resizable = true, .restorePolicy = .clamp_to_visible_screen, .minWidth = 0, .minHeight = 0, .titlebar = .standard, .transparent = false, .alwaysOnTop = false, .clickThrough = false, .activateOnShow = true, .allowsFullscreen = true, .closePolicy = .quit, .onCloseCommand = "" },
1544
1681
  };
1545
1682
 
1546
1683
  pub const Msg = union(enum) { noop };
@@ -1551,6 +1688,45 @@ const WindowsAdapterTestCore = struct {
1551
1688
  };
1552
1689
  };
1553
1690
 
1691
+ const ThemeStateAdapterTestCore = struct {
1692
+ const Pack = enum { house, geist };
1693
+ const Scheme = enum { light, dark, system };
1694
+ const State = struct {
1695
+ pack: ?Pack,
1696
+ colorScheme: ?Scheme,
1697
+ accent: ?[]const u8,
1698
+ };
1699
+
1700
+ pub const Msg = union(enum) { noop };
1701
+ pub const Model = struct {
1702
+ bad: bool = false,
1703
+
1704
+ pub fn themeState(self: *const Model) State {
1705
+ return .{
1706
+ .pack = .geist,
1707
+ .colorScheme = .dark,
1708
+ .accent = if (self.bad) "hot-pink" else "#Df2670",
1709
+ };
1710
+ }
1711
+ };
1712
+ };
1713
+
1714
+ test "TypeScript themeState adapter validates, parses hex, and preserves malformed accent teaching" {
1715
+ const Adapter = TsUiApp(ThemeStateAdapterTestCore);
1716
+ comptime Adapter.validateThemeStateHelper();
1717
+ var model = ThemeStateAdapterTestCore.Model{};
1718
+ var state = Adapter.themeStateAdapter(&model);
1719
+ try std.testing.expectEqual(canvas.ThemePack.geist, state.pack.?);
1720
+ try std.testing.expectEqual(Adapter.App.ThemeColorScheme.dark, state.color_scheme);
1721
+ try std.testing.expectEqual(canvas.Color.rgb8(0xdf, 0x26, 0x70), state.accent.?);
1722
+ try std.testing.expect(state.invalid_accent == null);
1723
+
1724
+ model.bad = true;
1725
+ state = Adapter.themeStateAdapter(&model);
1726
+ try std.testing.expect(state.accent == null);
1727
+ try std.testing.expectEqualStrings("hot-pink", state.invalid_accent.?);
1728
+ }
1729
+
1554
1730
  test "TypeScript windows adapter keeps the declared prefix on overflow and projects chromeless" {
1555
1731
  const Adapter = TsUiApp(WindowsAdapterTestCore);
1556
1732
  comptime Adapter.validateWindowsHelper();
@@ -1560,6 +1736,7 @@ test "TypeScript windows adapter keeps the declared prefix on overflow and proje
1560
1736
  try std.testing.expectEqual(Adapter.App.max_ui_windows, descriptors.len);
1561
1737
  try std.testing.expectEqualStrings("one", descriptors[0].label);
1562
1738
  try std.testing.expectEqual(@import("app_manifest").WindowTitlebarStyle.chromeless, descriptors[0].titlebar);
1739
+ try std.testing.expectEqual(@import("app_manifest").WindowRestorePolicy.center_on_primary, descriptors[0].restore_policy);
1563
1740
  try std.testing.expect(descriptors[0].transparent);
1564
1741
  try std.testing.expectEqualStrings("four", descriptors[3].label);
1565
1742
  }
@@ -281,6 +281,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
281
281
  items: []const platform.TrayMenuItem = &.{},
282
282
  };
283
283
 
284
+ /// The stock-theme axes a model may own without replacing the full
285
+ /// DesignTokens register. `system` follows the platform's live color
286
+ /// scheme; null pack/accent values inherit the manifest-backed
287
+ /// Options fields. Native chrome and WebViews remain OS-themed — this
288
+ /// state controls canvas tokens only.
289
+ pub const ThemeColorScheme = enum { system, light, dark };
290
+
291
+ pub const ThemeState = struct {
292
+ pack: ?canvas.ThemePack = null,
293
+ color_scheme: ThemeColorScheme = .system,
294
+ accent: ?canvas.Color = null,
295
+ /// Adapter-only invalid declaration marker. Zig cores already
296
+ /// pass a typed Color; the TS adapter retains malformed source
297
+ /// text here so rebuild rejects it instead of silently inheriting.
298
+ invalid_accent: ?[]const u8 = null,
299
+ };
300
+
284
301
  /// One entry in the model-declared status-item collection.
285
302
  /// `id` is stable identity; dropping the entry removes that
286
303
  /// native status item, while every other field patches in place.
@@ -353,6 +370,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
353
370
  x: ?f32 = null,
354
371
  y: ?f32 = null,
355
372
  resizable: bool = true,
373
+ /// Placement policy passed to the host when creating this
374
+ /// fresh, non-restored window. On macOS,
375
+ /// `.center_on_primary` centers a descriptor without an authored
376
+ /// origin on the primary screen; other hosts currently retain
377
+ /// their native default placement.
378
+ restore_policy: app_manifest.WindowRestorePolicy = .clamp_to_visible_screen,
356
379
  /// Content min-size floor the WINDOW enforces (macOS
357
380
  /// `contentMinSize`): the user's resize stops at the floor
358
381
  /// instead of the layout clamping/clipping panes below
@@ -485,6 +508,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
485
508
  /// `tokens_fn` still take precedence because those paths own
486
509
  /// the complete token register.
487
510
  theme_fn: ?*const fn (model: *const ModelT) canvas.ThemePack = null,
511
+ /// Cohesive model-derived stock-theme state: built-in pack,
512
+ /// canvas color scheme, and accent. This subsumes `theme_fn` and
513
+ /// is mutually exclusive with it. Explicit `tokens_fn`/`tokens`
514
+ /// still own the complete register and take precedence.
515
+ theme_state_fn: ?*const fn (model: *const ModelT) ThemeState = null,
488
516
  /// The app's ONE-accent brand statement over the stock
489
517
  /// tokens: when set (and the app claims neither `tokens`
490
518
  /// nor `tokens_fn` — apps that own their tokens own their
@@ -962,6 +990,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
962
990
  /// light/dark setting live. Test/null platforms never emit it,
963
991
  /// so deterministic runs stay on the default light theme.
964
992
  system_appearance: platform.Appearance = .{},
993
+ /// Last valid model-derived state. Re-derived before each rebuild;
994
+ /// equality is a handful of scalar/optional fields.
995
+ theme_state: ThemeState = .{},
996
+ theme_state_known: bool = false,
965
997
  pixel_snap_scale: f32 = 1,
966
998
  frame_timestamp_ns: u64 = 0,
967
999
  markup_arenas: [2]std.heap.ArenaAllocator,
@@ -1397,6 +1429,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1397
1429
  std.debug.assert((options.update != null) != (options.update_fx != null));
1398
1430
  // Declared windows need the per-window view to build them.
1399
1431
  std.debug.assert(options.windows_fn == null or options.window_view != null);
1432
+ std.debug.assert(options.theme_fn == null or options.theme_state_fn == null);
1400
1433
  if (comptime !features.runtime_markup) std.debug.assert(options.markup == null);
1401
1434
  }
1402
1435
 
@@ -1883,32 +1916,66 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1883
1916
  tokens.pixel_snap.scale = self.pixel_snap_scale;
1884
1917
  return tokens;
1885
1918
  }
1886
- var tokens = canvas.DesignTokens.theme(.{
1887
- .color_scheme = switch (self.system_appearance.color_scheme) {
1919
+ const state = self.currentThemeState();
1920
+ const color_scheme: canvas.ColorScheme = switch (state.color_scheme) {
1921
+ .system => switch (self.system_appearance.color_scheme) {
1888
1922
  .light => .light,
1889
1923
  .dark => .dark,
1890
1924
  },
1925
+ .light => .light,
1926
+ .dark => .dark,
1927
+ };
1928
+ var tokens = canvas.DesignTokens.theme(.{
1929
+ .color_scheme = color_scheme,
1891
1930
  .contrast = if (self.system_appearance.high_contrast) .high else .standard,
1892
1931
  .reduce_motion = self.system_appearance.reduce_motion,
1893
- .pack = if (self.options.theme_fn) |theme_fn| theme_fn(&self.model) else self.options.theme,
1932
+ .pack = state.pack orelse if (self.options.theme_fn) |theme_fn| theme_fn(&self.model) else self.options.theme,
1894
1933
  });
1895
- if (self.options.theme_accent) |accent| {
1934
+ if (state.accent orelse self.options.theme_accent) |accent| {
1896
1935
  // The manifest accent layers over the resolved pack —
1897
1936
  // except under high contrast, where the pack's own loud
1898
1937
  // register wins untouched (accessibility beats brand).
1899
1938
  // The bundle takes the resolved scheme: the dark ring
1900
1939
  // derives desaturated (canvas.accentFocusRing).
1901
1940
  if (!self.system_appearance.high_contrast) {
1902
- tokens = tokens.withOverrides(canvas.accentOverrides(accent, switch (self.system_appearance.color_scheme) {
1903
- .light => .light,
1904
- .dark => .dark,
1905
- }));
1941
+ tokens = tokens.withOverrides(canvas.accentOverrides(accent, color_scheme));
1906
1942
  }
1907
1943
  }
1908
1944
  tokens.pixel_snap.scale = self.pixel_snap_scale;
1909
1945
  return tokens;
1910
1946
  }
1911
1947
 
1948
+ fn currentThemeState(self: *const Self) ThemeState {
1949
+ if (self.theme_state_known) return self.theme_state;
1950
+ return if (self.options.theme_state_fn) |theme_state_fn| theme_state_fn(&self.model) else .{};
1951
+ }
1952
+
1953
+ /// Re-derive once per rebuild and reject malformed adapter input at
1954
+ /// the declaration boundary. A valid retained state contains no
1955
+ /// borrowed accent text, so it remains safe between dispatches.
1956
+ fn refreshThemeState(self: *Self) error{InvalidThemeAccent}!void {
1957
+ // Complete-token paths outrank the stock-theme helper entirely.
1958
+ // Do not even validate an unused model accent: the app has
1959
+ // explicitly claimed the whole DesignTokens register.
1960
+ if (self.options.tokens_fn != null or self.options.tokens != null) {
1961
+ self.theme_state = .{};
1962
+ self.theme_state_known = true;
1963
+ return;
1964
+ }
1965
+ const next = if (self.options.theme_state_fn) |theme_state_fn| theme_state_fn(&self.model) else ThemeState{};
1966
+ if (next.invalid_accent) |accent| {
1967
+ ui_app_log.warn(
1968
+ "themeState(model) returned accent '{s}'; expected exactly #rrggbb (six hexadecimal digits)",
1969
+ .{accent},
1970
+ );
1971
+ return error.InvalidThemeAccent;
1972
+ }
1973
+ if (!self.theme_state_known or !std.meta.eql(self.theme_state, next)) {
1974
+ self.theme_state = next;
1975
+ self.theme_state_known = true;
1976
+ }
1977
+ }
1978
+
1912
1979
  /// The design tokens for a secondary window's rebuild: the same
1913
1980
  /// app-owned appearance as `effectiveTokens`, restamped with the
1914
1981
  /// SLOT's device scale. Each window snaps hairlines against its
@@ -1924,13 +1991,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1924
1991
  /// true only when the app claims neither token override, so an
1925
1992
  /// appearance flip must re-derive and re-render.
1926
1993
  fn followsSystemAppearance(self: *const Self) bool {
1927
- return self.options.tokens_fn == null and self.options.tokens == null;
1994
+ if (self.options.tokens_fn != null or self.options.tokens != null) return false;
1995
+ if (self.options.theme_state_fn == null) return true;
1996
+ return self.currentThemeState().color_scheme == .system;
1928
1997
  }
1929
1998
 
1930
1999
  /// Whether tokens are derived per rebuild (model-owned or
1931
2000
  /// system-followed) rather than a fixed set.
1932
2001
  fn derivesTokens(self: *const Self) bool {
1933
- return self.options.tokens_fn != null or self.followsSystemAppearance();
2002
+ return self.options.tokens_fn != null or self.options.theme_state_fn != null or self.followsSystemAppearance();
1934
2003
  }
1935
2004
 
1936
2005
  /// Whether a rebuild must push its tokens into the runtime's
@@ -1947,8 +2016,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1947
2016
  /// pre-registration metrics). Ordinary rebuilds keep skipping
1948
2017
  /// the redundant emission.
1949
2018
  fn rebuildEmitsTokens(self: *const Self, runtime: *Runtime, window_id: platform.WindowId, canvas_label: []const u8, tokens: canvas.DesignTokens) bool {
1950
- if (self.derivesTokens()) return true;
1951
2019
  const stored = runtime.canvasWidgetDesignTokens(window_id, canvas_label) catch return true;
2020
+ if (self.derivesTokens()) return !std.meta.eql(stored, tokens);
1952
2021
  if (!std.meta.eql(stored.text_measure, tokens.text_measure)) return true;
1953
2022
  return stored.pixel_snap.scale != tokens.pixel_snap.scale;
1954
2023
  }
@@ -1981,6 +2050,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1981
2050
  /// for the next Msg.
1982
2051
  pub fn rebuild(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1983
2052
  self.syncModel(runtime, window_id);
2053
+ try self.refreshThemeState();
1984
2054
  if (comptime features.runtime_markup) {
1985
2055
  // Under automation, drive the interpreter from the first
1986
2056
  // frame even when a compiled view is present: provenance
@@ -2816,6 +2886,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2816
2886
  .x = descriptor.x,
2817
2887
  .y = descriptor.y,
2818
2888
  .resizable = descriptor.resizable,
2889
+ .restore_policy = descriptor.restore_policy,
2819
2890
  .titlebar = descriptor.titlebar,
2820
2891
  .transparent = descriptor.transparent,
2821
2892
  .always_on_top = descriptor.always_on_top,
@@ -2953,6 +3024,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2953
3024
 
2954
3025
  fn rebuildWindowSlot(self: *Self, runtime: *Runtime, slot: *WindowSlot) anyerror!void {
2955
3026
  if (self.options.window_view == null) return;
3027
+ try self.refreshThemeState();
2956
3028
  var tokens = runtime.tokensWithTextMeasure(self.slotEffectiveTokens(slot));
2957
3029
  const next_index = self.contextMenuRebuildIndex(slot.window_id, slot.arena_index);
2958
3030
  const bounds = geometry.RectF.fromSize(slot.canvas_size).deflate(runtime.viewportInsetsForWindow(slot.window_id));
@@ -4249,7 +4321,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4249
4321
  }
4250
4322
  },
4251
4323
  .appearance_changed => |appearance| {
4252
- const changed = !std.meta.eql(self.system_appearance, appearance);
4324
+ const previous = self.system_appearance;
4253
4325
  self.system_appearance = appearance;
4254
4326
  if (self.options.on_appearance) |map| {
4255
4327
  if (map(appearance)) |msg| {
@@ -4257,14 +4329,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4257
4329
  return;
4258
4330
  }
4259
4331
  }
4260
- // No app mapping consumed the change: when the stock
4261
- // tokens follow the system, re-derive and re-render
4262
- // live — flipping the OS appearance re-themes the
4263
- // running app without a restart. Before install the
4264
- // stored appearance alone is enough: the first build
4332
+ // No app mapping consumed the change. High contrast and
4333
+ // reduced motion remain live system axes even when the
4334
+ // model forces light/dark; only a scheme-only flip may
4335
+ // skip repaint while themeState is forced. Before install
4336
+ // the stored appearance alone is enough: the first build
4265
4337
  // reads it.
4266
- if (changed and self.installed and self.followsSystemAppearance()) {
4338
+ const accessibility_changed =
4339
+ previous.high_contrast != appearance.high_contrast or
4340
+ previous.reduce_motion != appearance.reduce_motion;
4341
+ const followed_scheme_changed =
4342
+ previous.color_scheme != appearance.color_scheme and self.followsSystemAppearance();
4343
+ if (self.installed and self.options.tokens_fn == null and self.options.tokens == null and
4344
+ (accessibility_changed or followed_scheme_changed))
4345
+ {
4267
4346
  try self.rebuild(runtime, self.canvas_window_id);
4347
+ try self.rebuildWindowSlots(runtime);
4268
4348
  if (self.options.chrome == null) {
4269
4349
  _ = try runtime.emitCanvasWidgetDisplayList(self.canvas_window_id, self.options.canvas_label, runtime.tokensWithTextMeasure(self.effectiveTokens()));
4270
4350
  }