@native-sdk/cli 0.8.4 → 0.9.1

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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -40,11 +40,20 @@
40
40
  //!
41
41
  //! Everything else on `UiApp.Options` is the wiring's, unchanged: view
42
42
  //! or markup, scene, `on_command` maps command ids through the core's
43
- //! `commandMsg`, `tokens_fn`/`windows_fn`/`status_item_fn` derive from
43
+ //! `commandMsg`, `tokens_fn`/`windows_fn`/status-item callbacks derive from
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. The two seams the core owns — `update_fx` and
47
+ //! system appearance axes. An exported
48
+ //! `statusItem(model): StatusItemState` helper similarly owns one complete
49
+ //! menu-bar item through `status_item_fn`; `statusItems(model)` owns a keyed
50
+ //! collection through `status_items_fn`. Both keep shell, presentation, and
51
+ //! menu live. `windows(model): readonly WindowDescriptor[]` owns the
52
+ //! model-declared secondary-window set through `windows_fn`; the launcher or
53
+ //! hand wiring supplies the statically compiled `window_view` registry. In
54
+ //! hand wiring, empty singular shell fields inherit the static `status_item`
55
+ //! options. The two
56
+ //! seams the core owns — `update_fx` and
48
57
  //! `init_fx` — are stamped by this adapter and must be left null.
49
58
  //!
50
59
  //! `Options.sync` is deliberately unsupported: it mutates the model in
@@ -63,9 +72,14 @@
63
72
  const std = @import("std");
64
73
  const canvas = @import("canvas");
65
74
  const platform = @import("../platform/root.zig");
75
+ const runtime_core = @import("core.zig");
76
+ const runtime_effects = @import("effects.zig");
77
+ const persist_store = @import("persist_store.zig");
66
78
  const ui_app = @import("ui_app.zig");
67
79
  const ts_core_host = @import("ts_core_host.zig");
68
80
 
81
+ const ts_ui_app_log = std.log.scoped(.zero_ts_ui_app);
82
+
69
83
  pub fn TsUiApp(comptime core: type) type {
70
84
  return struct {
71
85
  /// The effect bridge — shared with any direct `TsCoreHost(core)`
@@ -79,6 +93,10 @@ pub fn TsUiApp(comptime core: type) type {
79
93
  pub const Effects = App.Effects;
80
94
  pub const Ui = App.Ui;
81
95
 
96
+ /// Internal keyed-channel namespace for persistence write failures
97
+ /// ("TSPR"). It never shares an app-authored TS bridge index.
98
+ const persist_outcome_channel_key: u64 = 0x5453_5052_0000_0001;
99
+
82
100
  /// One boot-registered image: the wiring reads the encoded bytes
83
101
  /// (app.zon's `.assets.images` paths) and the adapter registers
84
102
  /// them on the installing frame — `fx.registerImageBytes`, the
@@ -102,6 +120,132 @@ pub fn TsUiApp(comptime core: type) type {
102
120
  value: []const u8,
103
121
  };
104
122
 
123
+ pub const PersistRoutes = struct {
124
+ ok: []const u8,
125
+ none: []const u8,
126
+ err: []const u8,
127
+ };
128
+
129
+ pub const PersistRestore = struct {
130
+ outcome: persist_store.Outcome,
131
+ bytes: []const u8 = "",
132
+ migration_from_version: ?u64 = null,
133
+ };
134
+
135
+ pub const PersistOptions = struct {
136
+ binding: runtime_effects.HostCallBinding,
137
+ routes: PersistRoutes,
138
+ restore: PersistRestore,
139
+ /// Runner-owned slot populated during install. The store worker
140
+ /// posts failed writes through it, gaining ordinary effect wake,
141
+ /// ordering, journaling, and replay semantics.
142
+ outcome_handle: ?*runtime_effects.ChannelHandle = null,
143
+ };
144
+
145
+ /// One effects host binding must carry both app services and the
146
+ /// framework-owned persistence verbs when an app enables both. The
147
+ /// reserved persistence names route to that binding; every other
148
+ /// command and the worker completion lifecycle stay with the app
149
+ /// service carrier.
150
+ const HostCallMux = struct {
151
+ primary: runtime_effects.HostCallBinding,
152
+ persist: runtime_effects.HostCallBinding,
153
+
154
+ fn binding(self: *HostCallMux) runtime_effects.HostCallBinding {
155
+ return .{
156
+ .context = self,
157
+ .send_fn = send,
158
+ .request_fn = request,
159
+ .cancel_fn = cancel,
160
+ .reject_duplicate_keys = self.primary.reject_duplicate_keys,
161
+ .poll_fn = poll,
162
+ .pending_fn = pending,
163
+ .bind_services_fn = bindServices,
164
+ .bind_channels_fn = bindChannels,
165
+ .shutdown_fn = shutdown,
166
+ };
167
+ }
168
+
169
+ fn persistenceName(name: []const u8) bool {
170
+ return std.mem.eql(u8, name, "core.persist") or std.mem.eql(u8, name, "core.persist.flush");
171
+ }
172
+
173
+ fn send(context: *anyopaque, name: []const u8, payload: []const u8) void {
174
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
175
+ const target = if (persistenceName(name)) self.persist else self.primary;
176
+ target.send_fn(target.context, name, payload);
177
+ }
178
+
179
+ fn request(context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void {
180
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
181
+ const target = if (persistenceName(name)) self.persist else self.primary;
182
+ target.request_fn(target.context, name, key, payload);
183
+ }
184
+
185
+ fn cancel(context: *anyopaque, key: u64) void {
186
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
187
+ if (self.primary.cancel_fn) |cancel_fn| cancel_fn(self.primary.context, key);
188
+ }
189
+
190
+ fn poll(context: *anyopaque) ?runtime_effects.HostCallCompletion {
191
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
192
+ const poll_fn = self.primary.poll_fn orelse return null;
193
+ return poll_fn(self.primary.context);
194
+ }
195
+
196
+ fn pending(context: *anyopaque) bool {
197
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
198
+ const pending_fn = self.primary.pending_fn orelse return false;
199
+ return pending_fn(self.primary.context);
200
+ }
201
+
202
+ fn bindServices(context: *anyopaque, services: *const platform.PlatformServices) void {
203
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
204
+ if (self.primary.bind_services_fn) |bind_fn| bind_fn(self.primary.context, services);
205
+ if (self.persist.bind_services_fn) |bind_fn| bind_fn(self.persist.context, services);
206
+ }
207
+
208
+ fn bindChannels(context: *anyopaque, channels: runtime_effects.HostChannelBinding) void {
209
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
210
+ if (self.primary.bind_channels_fn) |bind_fn| bind_fn(self.primary.context, channels);
211
+ if (self.persist.bind_channels_fn) |bind_fn| bind_fn(self.persist.context, channels);
212
+ }
213
+
214
+ fn shutdown(context: *anyopaque) void {
215
+ const self: *HostCallMux = @ptrCast(@alignCast(context));
216
+ if (self.primary.shutdown_fn) |shutdown_fn| shutdown_fn(self.primary.context);
217
+ if (self.persist.shutdown_fn) |shutdown_fn| shutdown_fn(self.persist.context);
218
+ }
219
+ };
220
+
221
+ /// Build-time manifest/wire fence for the three persistence routes.
222
+ /// The generated runner calls this with app.zon's comptime strings so
223
+ /// a typo or payload mismatch fails during `native build`, before a
224
+ /// first boot can reach the dynamic dispatch path below.
225
+ pub fn validatePersistRoutes(comptime routes: PersistRoutes) void {
226
+ validatePersistRoute(routes.ok, void, "ok");
227
+ validatePersistRoute(routes.none, void, "none");
228
+ validatePersistRoute(routes.err, []const u8, "err");
229
+ }
230
+
231
+ fn validatePersistRoute(comptime route: []const u8, comptime Payload: type, comptime role: []const u8) void {
232
+ inline for (@typeInfo(Msg).@"union".fields) |arm| {
233
+ if (comptime std.mem.eql(u8, arm.name, route)) {
234
+ if (arm.type != Payload) {
235
+ @compileError(std.fmt.comptimePrint(
236
+ "persistence restore route `{s}` ({s}) has the wrong Msg payload; ok/none must be void and err must carry one Uint8Array field",
237
+ .{ route, role },
238
+ ));
239
+ }
240
+ return;
241
+ }
242
+ }
243
+ @compileError(std.fmt.comptimePrint(
244
+ "persistence restore route `{s}` ({s}) names no Msg arm",
245
+ .{ route, role },
246
+ ));
247
+ }
248
+
105
249
  /// Adapter-owned configuration — the knobs that exist because
106
250
  /// the core is TypeScript, kept separate from `App.Options` so
107
251
  /// the wiring surface reads as ordinary UiApp wiring.
@@ -128,6 +272,14 @@ pub fn TsUiApp(comptime core: type) type {
128
272
  /// meaningful for cores exporting `envMsgs`. The slices must
129
273
  /// outlive install.
130
274
  env_values: []const EnvValue = &.{},
275
+ /// Generated service registry/carrier for Cmd.host/request. Null
276
+ /// preserves the existing embedding-host behavior.
277
+ host_calls: ?runtime_effects.HostCallBinding = null,
278
+ /// Typed service result projection generated from the same
279
+ /// sidecar as `host_calls`. Null keeps raw Cmd.request byte
280
+ /// routing for embedders and apps without services.
281
+ service_results: ?Host.ServiceResultBinding = null,
282
+ persist: ?PersistOptions = null,
131
283
  };
132
284
 
133
285
  /// Construct the UiApp over the committed TS model. `options`
@@ -141,6 +293,20 @@ pub fn TsUiApp(comptime core: type) type {
141
293
  return App.init(backing, Host.model().*, stamped);
142
294
  }
143
295
 
296
+ /// Mobile counterpart of `init`/`create`: the embed host
297
+ /// (`native_sdk.embed.UiAppHost`) owns App construction, so this
298
+ /// resolves the adapter's stamped options and applies the core
299
+ /// options — the boot model commits here, and the generated mobile
300
+ /// wiring's `initModel` reads `Host.model()` afterwards. The embed
301
+ /// host then drives the same stamped `init_fx`/`update_fx` seams
302
+ /// the desktop wiring gets.
303
+ pub fn mobileOptions(core_options: CoreOptions, options: Options) Options {
304
+ const stamped = stampOptions(options);
305
+ Host.boot();
306
+ applyCoreOptions(core_options);
307
+ return stamped;
308
+ }
309
+
144
310
  /// Heap counterpart of `init`, mirroring `UiApp.create`: the app
145
311
  /// struct (and any real model) is multi-MB, so construct it in
146
312
  /// place on the heap — the shape generated wiring and `main`
@@ -162,15 +328,31 @@ pub fn TsUiApp(comptime core: type) type {
162
328
  /// installing frame.
163
329
  var boot_images_store: []const BootImage = &.{};
164
330
  var env_values_store: []const EnvValue = &.{};
331
+ var host_calls_store: ?runtime_effects.HostCallBinding = null;
332
+ var persist_options_store: ?PersistOptions = null;
333
+ var host_call_mux_store: ?HostCallMux = null;
334
+ var lifecycle_store: ?*const fn (event: runtime_core.LifecycleEvent) ?Msg = null;
335
+ var command_store: ?*const fn (name: []const u8) ?Msg = null;
336
+ var lifecycle_flush_after_update = false;
165
337
 
166
338
  fn applyCoreOptions(core_options: CoreOptions) void {
167
339
  Host.setAudioCacheDir(core_options.audio_cache_dir);
168
340
  Host.setImageCacheDir(core_options.image_cache_dir);
341
+ Host.bindServiceResults(core_options.service_results);
169
342
  boot_images_store = core_options.boot_images;
170
343
  env_values_store = core_options.env_values;
344
+ host_calls_store = core_options.host_calls;
345
+ persist_options_store = core_options.persist;
346
+ host_call_mux_store = if (core_options.host_calls != null and core_options.persist != null) .{
347
+ .primary = core_options.host_calls.?,
348
+ .persist = core_options.persist.?.binding,
349
+ } else null;
171
350
  if (core_options.env_values.len > 0 and comptime !@hasDecl(core, "envMsgs")) {
172
351
  @panic("TsUiApp received env_values but the core exports no envMsgs channel - declare `export const envMsgs = [{ env: \"NAME\", msg: \"<arm>\" }] as const` in core.ts");
173
352
  }
353
+ if (core_options.persist != null and comptime !@hasDecl(core, "restoreModel")) {
354
+ @panic("TsUiApp received persistence wiring but the generated core exposes no restoreModel entry - rebuild with core ABI version 2");
355
+ }
174
356
  }
175
357
 
176
358
  fn stampOptions(options: Options) Options {
@@ -184,6 +366,10 @@ pub fn TsUiApp(comptime core: type) type {
184
366
  @panic("TsUiApp does not support Options.sync: a committed model cannot be mutated in place - echo widget state through on-change/on-scroll Msgs instead");
185
367
  }
186
368
  var stamped = options;
369
+ command_store = stamped.on_command;
370
+ lifecycle_store = stamped.on_lifecycle;
371
+ lifecycle_flush_after_update = false;
372
+ stamped.on_lifecycle = lifecycleAdapter;
187
373
  stamped.init_fx = initFx;
188
374
  stamped.update_fx = updateFx;
189
375
  // A TypeScript core can select a built-in pack from ordinary
@@ -199,6 +385,38 @@ pub fn TsUiApp(comptime core: type) type {
199
385
  comptime validateThemePackHelper();
200
386
  stamped.theme_fn = themePackAdapter;
201
387
  }
388
+ // A statusItem helper is the TS app's model-derived shell
389
+ // declaration. UiApp installs it on the first frame and
390
+ // independently patches shell/presentation/menu after each
391
+ // committed rebuild; empty fields inherit custom static
392
+ // status_item options in hand wiring.
393
+ if (comptime @hasDecl(Model, "statusItem")) {
394
+ if (options.status_item_fn != null) {
395
+ @panic("TsUiApp wires status_item_fn from the core's statusItem helper - remove the wiring's status_item_fn");
396
+ }
397
+ comptime validateStatusItemHelper();
398
+ stamped.status_item_fn = statusItemAdapter;
399
+ }
400
+ if (comptime @hasDecl(Model, "statusItems")) {
401
+ if (comptime @hasDecl(Model, "statusItem")) {
402
+ @compileError("TsUiApp: export either statusItem or statusItems, not both");
403
+ }
404
+ if (options.status_items_fn != null or options.status_item != null or options.status_item_fn != null) {
405
+ @panic("TsUiApp wires status_items_fn from the core's statusItems helper - remove singular/custom status-item wiring");
406
+ }
407
+ comptime validateStatusItemsHelper();
408
+ stamped.status_items_fn = statusItemsAdapter;
409
+ }
410
+ if (comptime @hasDecl(Model, "windows")) {
411
+ if (options.windows_fn != null) {
412
+ @panic("TsUiApp wires windows_fn from the core's windows helper - remove the wiring's windows_fn");
413
+ }
414
+ if (options.window_view == null) {
415
+ @panic("TsUiApp windows(model) requires a window_view registry - default apps provide src/windows/<label>.native; hand wiring must set Options.window_view");
416
+ }
417
+ comptime validateWindowsHelper();
418
+ stamped.windows_fn = windowsAdapter;
419
+ }
202
420
  // The core's host-event channels, comptime-detected from its
203
421
  // exports (export exists -> wired; every shape mismatch is a
204
422
  // teaching compile error in the adapter below). A wiring that
@@ -243,6 +461,26 @@ pub fn TsUiApp(comptime core: type) type {
243
461
  return stamped;
244
462
  }
245
463
 
464
+ fn lifecycleAdapter(event: runtime_core.LifecycleEvent) ?Msg {
465
+ const mapped = if (lifecycle_store) |map| map(event) else null;
466
+ if (event != .deactivate and event != .stop) return mapped;
467
+ if (mapped != null) {
468
+ // UiApp dispatches the mapped Msg after this callback returns.
469
+ // Delay the flush until updateFx has committed that cycle, so
470
+ // a Cmd.persist issued by the lifecycle update is included.
471
+ lifecycle_flush_after_update = true;
472
+ } else {
473
+ flushPersistence();
474
+ }
475
+ return mapped;
476
+ }
477
+
478
+ fn flushPersistence() void {
479
+ if (persist_options_store) |persist| {
480
+ persist.binding.send_fn(persist.binding.context, "core.persist.flush", "");
481
+ }
482
+ }
483
+
246
484
  fn themePackAdapter(model: *const Model) canvas.ThemePack {
247
485
  const pack = model.themePack();
248
486
  return canvas.ThemePack.fromName(@tagName(pack)).?;
@@ -265,23 +503,572 @@ pub fn TsUiApp(comptime core: type) type {
265
503
  }
266
504
  }
267
505
 
506
+ /// Convert the compiled core's canonical status-item records into
507
+ /// the platform rows UiApp already knows how to validate, copy,
508
+ /// hash, install, and patch. Interface records cross the core ABI
509
+ /// by pointer; value records are accepted too so hand-assembled
510
+ /// compiler fixtures exercise the same seam.
511
+ fn statusItemAdapter(model: *const Model, scratch: *App.StatusItemScratch) App.StatusItemState {
512
+ const params = @typeInfo(@TypeOf(Model.statusItem)).@"fn".params;
513
+ const raw_state = if (comptime params.len == 1)
514
+ model.statusItem()
515
+ else
516
+ model.statusItem(core.rt.frameAllocator());
517
+ const state = if (comptime @typeInfo(@TypeOf(raw_state)) == .pointer) raw_state.* else raw_state;
518
+ if (state.items.len > scratch.items.len) {
519
+ // The callback cannot return an error. Feed UiApp one
520
+ // deliberately invalid actionable row so the ordinary
521
+ // tray validator rejects the over-capacity declaration
522
+ // loudly instead of silently truncating it.
523
+ scratch.items[0] = .{ .id = 0, .label = "status item has more than 32 rows", .command = "status-item-overflow" };
524
+ return statusItemState(state, scratch.items[0..1]);
525
+ }
526
+ for (state.items, 0..) |raw_item, index| {
527
+ const item = if (comptime @typeInfo(@TypeOf(raw_item)) == .pointer) raw_item.* else raw_item;
528
+ scratch.items[index] = .{
529
+ .id = statusItemId(item.id),
530
+ .label = item.label,
531
+ .command = item.command,
532
+ .separator = item.separator,
533
+ .enabled = item.enabled,
534
+ .detail = item.detail,
535
+ .role = statusItemRole(item.role),
536
+ .key = item.key,
537
+ .modifiers = .{
538
+ .primary = item.modifiers.primary,
539
+ .command = item.modifiers.command,
540
+ .control = item.modifiers.control,
541
+ .option = item.modifiers.option,
542
+ .shift = item.modifiers.shift,
543
+ },
544
+ };
545
+ }
546
+ return statusItemState(state, scratch.items[0..state.items.len]);
547
+ }
548
+
549
+ fn statusItemsAdapter(model: *const Model, scratch: *App.StatusItemsScratch) []const App.StatusItemDescriptor {
550
+ const params = @typeInfo(@TypeOf(Model.statusItems)).@"fn".params;
551
+ const raw_states = if (comptime params.len == 1)
552
+ model.statusItems()
553
+ else
554
+ model.statusItems(core.rt.frameAllocator());
555
+ if (raw_states.len > scratch.status_items.len) {
556
+ scratch.status_items[0] = .{ .id = 0 };
557
+ return scratch.status_items[0..1];
558
+ }
559
+ for (raw_states, 0..) |raw_state, status_index| {
560
+ const state = if (comptime @typeInfo(@TypeOf(raw_state)) == .pointer) raw_state.* else raw_state;
561
+ const row_start = status_index * platform.max_tray_items;
562
+ const row_storage = scratch.items[row_start .. row_start + platform.max_tray_items];
563
+ if (state.items.len > row_storage.len) {
564
+ row_storage[0] = .{ .id = 0, .label = "status item has more than 32 rows", .command = "status-item-overflow" };
565
+ scratch.status_items[status_index] = .{
566
+ .id = statusItemId(state.id),
567
+ .visible = state.visible,
568
+ .state = statusItemState(state, row_storage[0..1]),
569
+ };
570
+ continue;
571
+ }
572
+ for (state.items, 0..) |raw_item, item_index| {
573
+ const item = if (comptime @typeInfo(@TypeOf(raw_item)) == .pointer) raw_item.* else raw_item;
574
+ row_storage[item_index] = statusItemMenuItem(item);
575
+ }
576
+ scratch.status_items[status_index] = .{
577
+ .id = statusItemId(state.id),
578
+ .visible = state.visible,
579
+ .state = statusItemState(state, row_storage[0..state.items.len]),
580
+ };
581
+ }
582
+ return scratch.status_items[0..raw_states.len];
583
+ }
584
+
585
+ fn windowsAdapter(model: *const Model, scratch: *App.WindowsScratch) []const App.WindowDescriptor {
586
+ const params = @typeInfo(@TypeOf(Model.windows)).@"fn".params;
587
+ const raw_windows = if (comptime params.len == 1)
588
+ model.windows()
589
+ else
590
+ model.windows(core.rt.frameAllocator());
591
+ if (raw_windows.len > scratch.windows.len) {
592
+ ts_ui_app_log.warn(
593
+ "windows(model) declared {d} windows; the budget is {d} (canvas_limits.max_ui_app_windows) - the excess is ignored",
594
+ .{ raw_windows.len, scratch.windows.len },
595
+ );
596
+ }
597
+ const kept = raw_windows[0..@min(raw_windows.len, scratch.windows.len)];
598
+ for (kept, 0..) |raw_window, index| {
599
+ const window = if (comptime @typeInfo(@TypeOf(raw_window)) == .pointer) raw_window.* else raw_window;
600
+ const close_policy = windowClosePolicy(window.closePolicy);
601
+ scratch.windows[index] = .{
602
+ .label = window.label,
603
+ .canvas_label = window.canvasLabel,
604
+ .title = window.title,
605
+ .width = statusItemFloat(window.width),
606
+ .height = statusItemFloat(window.height),
607
+ .x = optionalWindowFloat(window.x),
608
+ .y = optionalWindowFloat(window.y),
609
+ .resizable = window.resizable,
610
+ .min_width = statusItemFloat(window.minWidth),
611
+ .min_height = statusItemFloat(window.minHeight),
612
+ .titlebar = windowTitlebar(window.titlebar),
613
+ .transparent = window.transparent,
614
+ .always_on_top = window.alwaysOnTop,
615
+ .click_through = window.clickThrough,
616
+ .activate_on_show = window.activateOnShow,
617
+ .allows_fullscreen = window.allowsFullscreen,
618
+ .close_policy = close_policy,
619
+ // A hide never closes and therefore never routes its
620
+ // command. A real close must map a non-empty command
621
+ // now, before the window is created, so the adapter
622
+ // cannot install a dead callback that lets the model
623
+ // resurrect the just-closed window later.
624
+ .on_close = if (close_policy == .quit) requireWindowCloseMsg(window.onCloseCommand) else null,
625
+ };
626
+ }
627
+ return scratch.windows[0..kept.len];
628
+ }
629
+
630
+ fn optionalWindowFloat(value: anytype) ?f32 {
631
+ return if (value) |present| statusItemFloat(present) else null;
632
+ }
633
+
634
+ fn windowTitlebar(value: anytype) @import("app_manifest").WindowTitlebarStyle {
635
+ const Target = @import("app_manifest").WindowTitlebarStyle;
636
+ inline for (std.meta.fields(Target)) |field| {
637
+ if (std.mem.eql(u8, @tagName(value), field.name)) return @enumFromInt(field.value);
638
+ }
639
+ unreachable;
640
+ }
641
+
642
+ fn windowClosePolicy(value: anytype) @import("app_manifest").WindowClosePolicy {
643
+ const Target = @import("app_manifest").WindowClosePolicy;
644
+ inline for (std.meta.fields(Target)) |field| {
645
+ if (std.mem.eql(u8, @tagName(value), field.name)) return @enumFromInt(field.value);
646
+ }
647
+ unreachable;
648
+ }
649
+
650
+ const WindowCloseCommandError = error{
651
+ MissingCommandMapper,
652
+ UnmappedCommand,
653
+ };
654
+
655
+ fn windowCloseMsg(command: []const u8) WindowCloseCommandError!?Msg {
656
+ if (command.len == 0) return null;
657
+ const map = command_store orelse return error.MissingCommandMapper;
658
+ return map(command) orelse error.UnmappedCommand;
659
+ }
660
+
661
+ fn requireWindowCloseMsg(command: []const u8) ?Msg {
662
+ return windowCloseMsg(command) catch |err| {
663
+ ts_ui_app_log.err(
664
+ "window onCloseCommand '{s}' cannot be installed: {s}; map every quit-close command through Options.on_command (the default launcher wires exported commandMsg)",
665
+ .{ command, @errorName(err) },
666
+ );
667
+ @panic("TsUiApp: a non-empty quit-close onCloseCommand must map through Options.on_command");
668
+ };
669
+ }
670
+
671
+ fn statusItemMenuItem(item: anytype) platform.TrayMenuItem {
672
+ return .{
673
+ .id = statusItemId(item.id),
674
+ .label = item.label,
675
+ .command = item.command,
676
+ .separator = item.separator,
677
+ .enabled = item.enabled,
678
+ .detail = item.detail,
679
+ .role = statusItemRole(item.role),
680
+ .key = item.key,
681
+ .modifiers = .{
682
+ .primary = item.modifiers.primary,
683
+ .command = item.modifiers.command,
684
+ .control = item.modifiers.control,
685
+ .option = item.modifiers.option,
686
+ .shift = item.modifiers.shift,
687
+ },
688
+ };
689
+ }
690
+
691
+ fn statusItemState(state: anytype, items: []const platform.TrayMenuItem) App.StatusItemState {
692
+ const presentation = if (comptime @typeInfo(@TypeOf(state.presentation)) == .pointer) state.presentation.* else state.presentation;
693
+ return .{
694
+ .presentation = .{
695
+ .title = presentation.title,
696
+ .width = statusItemFloat(presentation.width),
697
+ .tone = statusItemTone(presentation.tone),
698
+ .icon_opacity = statusItemFloat(presentation.iconOpacity),
699
+ .monospaced = presentation.monospaced,
700
+ },
701
+ .icon_path = state.iconPath,
702
+ .tooltip = state.tooltip,
703
+ .activation_command = state.activationCommand,
704
+ .alternate_activation_command = state.alternateActivationCommand,
705
+ .open_command = state.openCommand,
706
+ .items = items,
707
+ };
708
+ }
709
+
710
+ /// JavaScript `number` slots may infer as integer or float in the
711
+ /// compiled core. Tray ids are u32; a negative, fractional,
712
+ /// non-finite, or overflowing value maps to zero so the runtime's
713
+ /// existing actionable-row validation produces the rejection.
714
+ fn statusItemId(value: anytype) u32 {
715
+ const number: f64 = switch (@typeInfo(@TypeOf(value))) {
716
+ .int => @floatFromInt(value),
717
+ .float => @floatCast(value),
718
+ else => unreachable,
719
+ };
720
+ if (!std.math.isFinite(number) or number < 0 or number > @as(f64, @floatFromInt(std.math.maxInt(u32))) or @floor(number) != number) return 0;
721
+ return @intFromFloat(number);
722
+ }
723
+
724
+ fn statusItemFloat(value: anytype) f32 {
725
+ return switch (@typeInfo(@TypeOf(value))) {
726
+ .int => @floatFromInt(value),
727
+ .float => @floatCast(value),
728
+ else => unreachable,
729
+ };
730
+ }
731
+
732
+ fn statusItemTone(value: anytype) platform.TrayTone {
733
+ const name = @tagName(value);
734
+ inline for (std.meta.fields(platform.TrayTone)) |field| {
735
+ if (std.mem.eql(u8, name, field.name)) return @enumFromInt(field.value);
736
+ }
737
+ unreachable;
738
+ }
739
+
740
+ fn statusItemRole(value: anytype) platform.TrayItemRole {
741
+ const name = @tagName(value);
742
+ inline for (std.meta.fields(platform.TrayItemRole)) |field| {
743
+ if (std.mem.eql(u8, name, field.name)) return @enumFromInt(field.value);
744
+ }
745
+ unreachable;
746
+ }
747
+
748
+ /// Teaching re-derivation of frontend NS1033 for hand-assembled
749
+ /// cores. The nested records stay flat and exact so their ABI
750
+ /// projection is deterministic and arrays need no tagged union.
751
+ fn validateStatusItemHelper() void {
752
+ const teaching = "TsUiApp: statusItem must be exported from core.ts as statusItem(model: Model): StatusItemState; import StatusItemState from @native-sdk/core/events";
753
+ const helper_info = @typeInfo(@TypeOf(Model.statusItem));
754
+ if (helper_info != .@"fn") @compileError(teaching);
755
+ const function = helper_info.@"fn";
756
+ if ((function.params.len != 1 and function.params.len != 2) or function.params[0].type == null or function.params[0].type.? != *const Model) {
757
+ @compileError(teaching);
758
+ }
759
+ if (function.params.len == 2) {
760
+ if (function.params[1].type == null or function.params[1].type.? != std.mem.Allocator or
761
+ !@hasDecl(core, "rt") or !@hasDecl(core.rt, "frameAllocator"))
762
+ {
763
+ @compileError(teaching);
764
+ }
765
+ }
766
+ const RawState = function.return_type orelse @compileError(teaching);
767
+ const State = statusItemRecordType(RawState, teaching);
768
+ const state_info = @typeInfo(State).@"struct";
769
+ if (state_info.fields.len != 7 or !@hasField(State, "iconPath") or !@hasField(State, "tooltip") or
770
+ !@hasField(State, "activationCommand") or !@hasField(State, "alternateActivationCommand") or
771
+ !@hasField(State, "openCommand") or !@hasField(State, "presentation") or !@hasField(State, "items"))
772
+ {
773
+ @compileError(teaching);
774
+ }
775
+ if (@FieldType(State, "iconPath") != []const u8 or @FieldType(State, "tooltip") != []const u8 or
776
+ @FieldType(State, "activationCommand") != []const u8 or @FieldType(State, "alternateActivationCommand") != []const u8 or
777
+ @FieldType(State, "openCommand") != []const u8)
778
+ {
779
+ @compileError(teaching);
780
+ }
781
+ const Presentation = statusItemRecordType(@FieldType(State, "presentation"), teaching);
782
+ const presentation_info = @typeInfo(Presentation).@"struct";
783
+ if (presentation_info.fields.len != 5 or !@hasField(Presentation, "title") or !@hasField(Presentation, "width") or
784
+ !@hasField(Presentation, "tone") or !@hasField(Presentation, "iconOpacity") or !@hasField(Presentation, "monospaced"))
785
+ {
786
+ @compileError(teaching);
787
+ }
788
+ if (@FieldType(Presentation, "title") != []const u8 or !statusItemNumericType(@FieldType(Presentation, "width")) or
789
+ !statusItemEnumType(@FieldType(Presentation, "tone"), &.{ "normal", "warning", "critical" }) or
790
+ !statusItemNumericType(@FieldType(Presentation, "iconOpacity")) or @FieldType(Presentation, "monospaced") != bool)
791
+ {
792
+ @compileError(teaching);
793
+ }
794
+ const items_info = @typeInfo(@FieldType(State, "items"));
795
+ if (items_info != .pointer or items_info.pointer.size != .slice or !items_info.pointer.is_const) @compileError(teaching);
796
+ const Item = statusItemRecordType(items_info.pointer.child, teaching);
797
+ const item_info = @typeInfo(Item).@"struct";
798
+ if (item_info.fields.len != 9 or !@hasField(Item, "id") or !@hasField(Item, "label") or
799
+ !@hasField(Item, "command") or !@hasField(Item, "separator") or !@hasField(Item, "enabled") or
800
+ !@hasField(Item, "detail") or !@hasField(Item, "role") or !@hasField(Item, "key") or !@hasField(Item, "modifiers"))
801
+ {
802
+ @compileError(teaching);
803
+ }
804
+ if (!statusItemNumericType(@FieldType(Item, "id"))) @compileError(teaching);
805
+ if (@FieldType(Item, "label") != []const u8 or @FieldType(Item, "command") != []const u8 or
806
+ @FieldType(Item, "separator") != bool or @FieldType(Item, "enabled") != bool or
807
+ @FieldType(Item, "detail") != []const u8 or
808
+ !statusItemEnumType(@FieldType(Item, "role"), &.{ "command", "info", "header", "hero", "agent", "context" }) or
809
+ @FieldType(Item, "key") != []const u8)
810
+ {
811
+ @compileError(teaching);
812
+ }
813
+ const Modifiers = statusItemRecordType(@FieldType(Item, "modifiers"), teaching);
814
+ const modifiers_info = @typeInfo(Modifiers).@"struct";
815
+ if (modifiers_info.fields.len != 5 or !@hasField(Modifiers, "primary") or !@hasField(Modifiers, "command") or
816
+ !@hasField(Modifiers, "control") or !@hasField(Modifiers, "option") or !@hasField(Modifiers, "shift") or
817
+ @FieldType(Modifiers, "primary") != bool or @FieldType(Modifiers, "command") != bool or
818
+ @FieldType(Modifiers, "control") != bool or @FieldType(Modifiers, "option") != bool or @FieldType(Modifiers, "shift") != bool)
819
+ {
820
+ @compileError(teaching);
821
+ }
822
+ }
823
+
824
+ fn validateStatusItemsHelper() void {
825
+ const teaching = "TsUiApp: statusItems must be exported from core.ts as statusItems(model: Model): readonly StatusItemDescriptor[]; import StatusItemDescriptor from @native-sdk/core/events";
826
+ const helper_info = @typeInfo(@TypeOf(Model.statusItems));
827
+ if (helper_info != .@"fn") @compileError(teaching);
828
+ const function = helper_info.@"fn";
829
+ if ((function.params.len != 1 and function.params.len != 2) or function.params[0].type == null or function.params[0].type.? != *const Model) {
830
+ @compileError(teaching);
831
+ }
832
+ if (function.params.len == 2) {
833
+ if (function.params[1].type == null or function.params[1].type.? != std.mem.Allocator or
834
+ !@hasDecl(core, "rt") or !@hasDecl(core.rt, "frameAllocator"))
835
+ {
836
+ @compileError(teaching);
837
+ }
838
+ }
839
+ const Return = function.return_type orelse @compileError(teaching);
840
+ const return_info = @typeInfo(Return);
841
+ if (return_info != .pointer or return_info.pointer.size != .slice or !return_info.pointer.is_const) @compileError(teaching);
842
+ const State = statusItemRecordType(return_info.pointer.child, teaching);
843
+ const info = @typeInfo(State).@"struct";
844
+ if (info.fields.len != 9 or !@hasField(State, "id") or !@hasField(State, "visible") or
845
+ !@hasField(State, "iconPath") or !@hasField(State, "tooltip") or !@hasField(State, "activationCommand") or
846
+ !@hasField(State, "alternateActivationCommand") or !@hasField(State, "openCommand") or
847
+ !@hasField(State, "presentation") or !@hasField(State, "items") or
848
+ !statusItemNumericType(@FieldType(State, "id")) or @FieldType(State, "visible") != bool or
849
+ @FieldType(State, "iconPath") != []const u8 or @FieldType(State, "tooltip") != []const u8 or
850
+ @FieldType(State, "activationCommand") != []const u8 or @FieldType(State, "alternateActivationCommand") != []const u8 or
851
+ @FieldType(State, "openCommand") != []const u8)
852
+ {
853
+ @compileError(teaching);
854
+ }
855
+ const Presentation = statusItemRecordType(@FieldType(State, "presentation"), teaching);
856
+ const presentation_info = @typeInfo(Presentation).@"struct";
857
+ if (presentation_info.fields.len != 5 or !@hasField(Presentation, "title") or !@hasField(Presentation, "width") or
858
+ !@hasField(Presentation, "tone") or !@hasField(Presentation, "iconOpacity") or !@hasField(Presentation, "monospaced") or
859
+ @FieldType(Presentation, "title") != []const u8 or !statusItemNumericType(@FieldType(Presentation, "width")) or
860
+ !statusItemEnumType(@FieldType(Presentation, "tone"), &.{ "normal", "warning", "critical" }) or
861
+ !statusItemNumericType(@FieldType(Presentation, "iconOpacity")) or @FieldType(Presentation, "monospaced") != bool)
862
+ {
863
+ @compileError(teaching);
864
+ }
865
+ const items_info = @typeInfo(@FieldType(State, "items"));
866
+ if (items_info != .pointer or items_info.pointer.size != .slice or !items_info.pointer.is_const) @compileError(teaching);
867
+ const Item = statusItemRecordType(items_info.pointer.child, teaching);
868
+ const item_info = @typeInfo(Item).@"struct";
869
+ if (item_info.fields.len != 9 or !@hasField(Item, "id") or !@hasField(Item, "label") or
870
+ !@hasField(Item, "command") or !@hasField(Item, "separator") or !@hasField(Item, "enabled") or
871
+ !@hasField(Item, "detail") or !@hasField(Item, "role") or !@hasField(Item, "key") or
872
+ !@hasField(Item, "modifiers") or !statusItemNumericType(@FieldType(Item, "id")) or
873
+ @FieldType(Item, "label") != []const u8 or @FieldType(Item, "command") != []const u8 or
874
+ @FieldType(Item, "separator") != bool or @FieldType(Item, "enabled") != bool or
875
+ @FieldType(Item, "detail") != []const u8 or
876
+ !statusItemEnumType(@FieldType(Item, "role"), &.{ "command", "info", "header", "hero", "agent", "context" }) or
877
+ @FieldType(Item, "key") != []const u8)
878
+ {
879
+ @compileError(teaching);
880
+ }
881
+ const Modifiers = statusItemRecordType(@FieldType(Item, "modifiers"), teaching);
882
+ const modifiers_info = @typeInfo(Modifiers).@"struct";
883
+ if (modifiers_info.fields.len != 5 or !@hasField(Modifiers, "primary") or !@hasField(Modifiers, "command") or
884
+ !@hasField(Modifiers, "control") or !@hasField(Modifiers, "option") or !@hasField(Modifiers, "shift") or
885
+ @FieldType(Modifiers, "primary") != bool or @FieldType(Modifiers, "command") != bool or
886
+ @FieldType(Modifiers, "control") != bool or @FieldType(Modifiers, "option") != bool or
887
+ @FieldType(Modifiers, "shift") != bool)
888
+ {
889
+ @compileError(teaching);
890
+ }
891
+ }
892
+
893
+ fn validateWindowsHelper() void {
894
+ const teaching = "TsUiApp: windows must be exported from core.ts as windows(model: Model): readonly WindowDescriptor[]; import WindowDescriptor from @native-sdk/core/events and construct entries with windowDescriptor(...)";
895
+ const helper_info = @typeInfo(@TypeOf(Model.windows));
896
+ if (helper_info != .@"fn") @compileError(teaching);
897
+ const function = helper_info.@"fn";
898
+ if ((function.params.len != 1 and function.params.len != 2) or function.params[0].type == null or function.params[0].type.? != *const Model) @compileError(teaching);
899
+ if (function.params.len == 2) {
900
+ if (function.params[1].type == null or function.params[1].type.? != std.mem.Allocator or
901
+ !@hasDecl(core, "rt") or !@hasDecl(core.rt, "frameAllocator")) @compileError(teaching);
902
+ }
903
+ const Return = function.return_type orelse @compileError(teaching);
904
+ const return_info = @typeInfo(Return);
905
+ if (return_info != .pointer or return_info.pointer.size != .slice or !return_info.pointer.is_const) @compileError(teaching);
906
+ const Window = statusItemRecordType(return_info.pointer.child, teaching);
907
+ const info = @typeInfo(Window).@"struct";
908
+ if (info.fields.len != 18 or !@hasField(Window, "label") or !@hasField(Window, "canvasLabel") or
909
+ !@hasField(Window, "title") or !@hasField(Window, "width") or !@hasField(Window, "height") or
910
+ !@hasField(Window, "x") or !@hasField(Window, "y") or !@hasField(Window, "resizable") or
911
+ !@hasField(Window, "minWidth") or !@hasField(Window, "minHeight") or !@hasField(Window, "titlebar") or
912
+ !@hasField(Window, "transparent") or !@hasField(Window, "alwaysOnTop") or !@hasField(Window, "clickThrough") or
913
+ !@hasField(Window, "activateOnShow") or !@hasField(Window, "allowsFullscreen") or
914
+ !@hasField(Window, "closePolicy") or !@hasField(Window, "onCloseCommand")) @compileError(teaching);
915
+ if (@FieldType(Window, "label") != []const u8 or @FieldType(Window, "canvasLabel") != []const u8 or
916
+ @FieldType(Window, "title") != []const u8 or !statusItemNumericType(@FieldType(Window, "width")) or
917
+ !statusItemNumericType(@FieldType(Window, "height")) or !optionalNumericType(@FieldType(Window, "x")) or
918
+ !optionalNumericType(@FieldType(Window, "y")) or @FieldType(Window, "resizable") != bool or
919
+ !statusItemNumericType(@FieldType(Window, "minWidth")) or !statusItemNumericType(@FieldType(Window, "minHeight")) or
920
+ !statusItemEnumType(@FieldType(Window, "titlebar"), &.{ "standard", "hidden_inset", "hidden_inset_tall", "chromeless" }) or
921
+ @FieldType(Window, "transparent") != bool or @FieldType(Window, "alwaysOnTop") != bool or
922
+ @FieldType(Window, "clickThrough") != bool or @FieldType(Window, "activateOnShow") != bool or
923
+ @FieldType(Window, "allowsFullscreen") != bool or
924
+ !statusItemEnumType(@FieldType(Window, "closePolicy"), &.{ "quit", "hide" }) or
925
+ @FieldType(Window, "onCloseCommand") != []const u8) @compileError(teaching);
926
+ }
927
+
928
+ fn optionalNumericType(comptime T: type) bool {
929
+ const info = @typeInfo(T);
930
+ return info == .optional and statusItemNumericType(info.optional.child);
931
+ }
932
+
933
+ fn statusItemNumericType(comptime T: type) bool {
934
+ return @typeInfo(T) == .int or @typeInfo(T) == .float;
935
+ }
936
+
937
+ fn statusItemEnumType(comptime T: type, comptime expected: []const []const u8) bool {
938
+ const info = @typeInfo(T);
939
+ if (info != .@"enum" or info.@"enum".fields.len != expected.len) return false;
940
+ inline for (expected) |name| {
941
+ var found = false;
942
+ inline for (info.@"enum".fields) |field| {
943
+ if (std.mem.eql(u8, name, field.name)) found = true;
944
+ }
945
+ if (!found) return false;
946
+ }
947
+ return true;
948
+ }
949
+
950
+ fn statusItemRecordType(comptime Raw: type, comptime teaching: []const u8) type {
951
+ const Record = switch (@typeInfo(Raw)) {
952
+ .pointer => |pointer| if (pointer.size == .one and pointer.is_const) pointer.child else @compileError(teaching),
953
+ else => Raw,
954
+ };
955
+ if (@typeInfo(Record) != .@"struct") @compileError(teaching);
956
+ return Record;
957
+ }
958
+
268
959
  /// `Options.init_fx`: register the wiring's boot images, perform
269
960
  /// the boot command and initial subscriptions on the installing
270
961
  /// frame (the boot model itself committed in `init`), dispatch
271
962
  /// the launch environment overrides as ordinary journaled Msgs,
272
963
  /// then refresh the app-held root.
273
964
  fn initFx(model: *Model, fx: *Effects) void {
965
+ if (host_call_mux_store) |*mux| {
966
+ fx.bindHostCalls(mux.binding());
967
+ } else if (host_calls_store) |binding| {
968
+ fx.bindHostCalls(binding);
969
+ } else if (persist_options_store) |persist| {
970
+ fx.bindHostCalls(persist.binding);
971
+ }
274
972
  for (boot_images_store) |image| {
275
973
  // Registration is synchronous; a failed decode leaves the
276
974
  // views on their fallback (avatar initials) — a bad asset
277
975
  // never breaks presentation (the Zig apps' convention).
278
976
  _ = fx.registerImageBytes(image.id, image.bytes) catch continue;
279
977
  }
978
+ if (persist_options_store) |persist| {
979
+ if (persist.outcome_handle) |handle| {
980
+ handle.* = fx.openChannel(.{
981
+ .key = persist_outcome_channel_key,
982
+ .on_event = persistOutcomeMsg,
983
+ .max_pending = 8,
984
+ });
985
+ }
986
+ }
987
+ const persist_outcome = preparePersistRestore(fx);
280
988
  Host.performBoot(fx);
989
+ if (persist_outcome) |outcome| dispatchPersistOutcome(fx, outcome);
281
990
  dispatchEnvValues(fx);
282
991
  model.* = Host.model().*;
283
992
  }
284
993
 
994
+ /// Resolve the boot snapshot entirely at the effect boundary. Live
995
+ /// launches journal the runner-provided result; replay consumes the
996
+ /// recorded result and never consults the current app-data directory.
997
+ fn preparePersistRestore(fx: *Effects) ?persist_store.Outcome {
998
+ const persist = persist_options_store orelse return null;
999
+ const restore = if (fx.replay) fx.takeReplayPersist() orelse return null else blk: {
1000
+ if (persist.restore.migration_from_version) |from_version| {
1001
+ if (Host.migrateSnapshot(persist.restore.bytes, from_version, std.heap.page_allocator)) |migrated| {
1002
+ defer std.heap.page_allocator.free(migrated);
1003
+ if (migrated.len > persist_store.max_snapshot_bytes) {
1004
+ fx.journalPersistRestore(.rejected, "");
1005
+ return .rejected;
1006
+ }
1007
+ Host.restoreSnapshot(migrated);
1008
+ persist.binding.send_fn(persist.binding.context, "core.persist", migrated);
1009
+ fx.journalPersistRestore(.ok, migrated);
1010
+ return .ok;
1011
+ }
1012
+ fx.journalPersistRestore(.migrate_failed, "");
1013
+ return .migrate_failed;
1014
+ }
1015
+ fx.journalPersistRestore(persist.restore.outcome, persist.restore.bytes);
1016
+ break :blk runtime_effects.ReplayPersistEntry{ .outcome = persist.restore.outcome, .bytes = persist.restore.bytes };
1017
+ };
1018
+ if (restore.outcome == .ok) Host.restoreSnapshot(restore.bytes);
1019
+ return restore.outcome;
1020
+ }
1021
+
1022
+ fn dispatchPersistOutcome(fx: *Effects, outcome: persist_store.Outcome) void {
1023
+ const routes = persist_options_store.?.routes;
1024
+ switch (outcome) {
1025
+ .ok => dispatchPersistVoid(fx, routes.ok),
1026
+ .none => dispatchPersistVoid(fx, routes.none),
1027
+ .corrupt, .version_unknown, .migrate_failed, .io_failed, .rejected => dispatchPersistError(fx, routes.err, @tagName(outcome)),
1028
+ }
1029
+ }
1030
+
1031
+ fn persistOutcomeMsg(event: runtime_effects.EffectChannelEvent) Msg {
1032
+ const reason: []const u8 = switch (event.kind) {
1033
+ .data => event.bytes,
1034
+ .rejected => "rejected",
1035
+ .closed => "io_failed",
1036
+ };
1037
+ const route = persist_options_store.?.routes.err;
1038
+ inline for (@typeInfo(Msg).@"union".fields) |arm| {
1039
+ if (comptime arm.type == []const u8) {
1040
+ if (std.mem.eql(u8, arm.name, route)) return @unionInit(Msg, arm.name, reason);
1041
+ }
1042
+ }
1043
+ @panic("TsUiApp persistence err route does not name a one-Uint8Array-field Msg arm");
1044
+ }
1045
+
1046
+ fn dispatchPersistVoid(fx: *Effects, route: []const u8) void {
1047
+ inline for (@typeInfo(Msg).@"union".fields) |arm| {
1048
+ if (comptime arm.type == void) {
1049
+ if (std.mem.eql(u8, arm.name, route)) {
1050
+ Host.dispatch(fx, @unionInit(Msg, arm.name, {}));
1051
+ return;
1052
+ }
1053
+ }
1054
+ }
1055
+ @panic("TsUiApp persistence route does not name a void Msg arm");
1056
+ }
1057
+
1058
+ fn dispatchPersistError(fx: *Effects, route: []const u8, reason: []const u8) void {
1059
+ inline for (@typeInfo(Msg).@"union".fields) |arm| {
1060
+ if (comptime arm.type == []const u8) {
1061
+ if (std.mem.eql(u8, arm.name, route)) {
1062
+ const copy = core.rt.frameAlloc(u8, reason.len);
1063
+ @memcpy(copy, reason);
1064
+ Host.dispatch(fx, @unionInit(Msg, arm.name, copy));
1065
+ return;
1066
+ }
1067
+ }
1068
+ }
1069
+ @panic("TsUiApp persistence err route does not name a one-Uint8Array-field Msg arm");
1070
+ }
1071
+
285
1072
  /// The `envMsgs` channel's delivery: each launch-resolved value
286
1073
  /// dispatches its named one-bytes-field arm — a full core cycle
287
1074
  /// per value, in declaration order, right after the boot command.
@@ -629,6 +1416,170 @@ pub fn TsUiApp(comptime core: type) type {
629
1416
  fn updateFx(model: *Model, msg: Msg, fx: *Effects) void {
630
1417
  Host.dispatch(fx, msg);
631
1418
  model.* = Host.model().*;
1419
+ if (lifecycle_flush_after_update) {
1420
+ lifecycle_flush_after_update = false;
1421
+ flushPersistence();
1422
+ }
632
1423
  }
633
1424
  };
634
1425
  }
1426
+
1427
+ const StatusItemsAdapterTestCore = struct {
1428
+ const Tone = enum { normal, warning, critical };
1429
+ const Role = enum { command, info, header, hero, agent, context };
1430
+ const Modifiers = struct {
1431
+ primary: bool,
1432
+ command: bool,
1433
+ control: bool,
1434
+ option: bool,
1435
+ shift: bool,
1436
+ };
1437
+ const Presentation = struct {
1438
+ title: []const u8,
1439
+ width: f64,
1440
+ tone: Tone,
1441
+ iconOpacity: f64,
1442
+ monospaced: bool,
1443
+ };
1444
+ const Item = struct {
1445
+ id: f64,
1446
+ label: []const u8,
1447
+ command: []const u8,
1448
+ separator: bool,
1449
+ enabled: bool,
1450
+ detail: []const u8,
1451
+ role: Role,
1452
+ key: []const u8,
1453
+ modifiers: Modifiers,
1454
+ };
1455
+ const Descriptor = struct {
1456
+ id: f64,
1457
+ visible: bool,
1458
+ iconPath: []const u8,
1459
+ tooltip: []const u8,
1460
+ activationCommand: []const u8,
1461
+ alternateActivationCommand: []const u8,
1462
+ openCommand: []const u8,
1463
+ presentation: Presentation,
1464
+ items: []const Item,
1465
+ };
1466
+
1467
+ const rows = [_]Item{.{
1468
+ .id = 3,
1469
+ .label = "Refresh",
1470
+ .command = "spend.refresh",
1471
+ .separator = false,
1472
+ .enabled = true,
1473
+ .detail = "$7",
1474
+ .role = .command,
1475
+ .key = "r",
1476
+ .modifiers = .{ .primary = true, .command = false, .control = false, .option = false, .shift = false },
1477
+ }};
1478
+ const descriptors = [_]Descriptor{.{
1479
+ .id = 7,
1480
+ .visible = false,
1481
+ .iconPath = "spend.png",
1482
+ .tooltip = "Vercel spend",
1483
+ .activationCommand = "spend.open",
1484
+ .alternateActivationCommand = "",
1485
+ .openCommand = "spend.refresh",
1486
+ .presentation = .{ .title = "$7", .width = 52, .tone = .warning, .iconOpacity = 0.75, .monospaced = true },
1487
+ .items = &rows,
1488
+ }};
1489
+
1490
+ pub const Msg = union(enum) { noop };
1491
+ pub const Model = struct {
1492
+ pub fn statusItems(_: *const Model) []const Descriptor {
1493
+ return &descriptors;
1494
+ }
1495
+ };
1496
+ };
1497
+
1498
+ test "TypeScript statusItems adapter validates and projects canonical descriptors" {
1499
+ const Adapter = TsUiApp(StatusItemsAdapterTestCore);
1500
+ comptime Adapter.validateStatusItemsHelper();
1501
+ var model = StatusItemsAdapterTestCore.Model{};
1502
+ var scratch = Adapter.App.StatusItemsScratch{};
1503
+ const descriptors = Adapter.statusItemsAdapter(&model, &scratch);
1504
+ try std.testing.expectEqual(@as(usize, 1), descriptors.len);
1505
+ try std.testing.expectEqual(@as(platform.StatusItemId, 7), descriptors[0].id);
1506
+ try std.testing.expect(!descriptors[0].visible);
1507
+ try std.testing.expectEqualStrings("$7", descriptors[0].state.presentation.title);
1508
+ try std.testing.expectEqualStrings("spend.png", descriptors[0].state.icon_path);
1509
+ try std.testing.expectEqual(@as(usize, 1), descriptors[0].state.items.len);
1510
+ try std.testing.expectEqual(@as(platform.TrayItemId, 3), descriptors[0].state.items[0].id);
1511
+ try std.testing.expect(descriptors[0].state.items[0].modifiers.primary);
1512
+ }
1513
+
1514
+ const WindowsAdapterTestCore = struct {
1515
+ const Titlebar = enum { standard, hidden_inset, hidden_inset_tall, chromeless };
1516
+ const ClosePolicy = enum { quit, hide };
1517
+ const Descriptor = struct {
1518
+ label: []const u8,
1519
+ canvasLabel: []const u8,
1520
+ title: []const u8,
1521
+ width: f64,
1522
+ height: f64,
1523
+ x: ?f64,
1524
+ y: ?f64,
1525
+ resizable: bool,
1526
+ minWidth: f64,
1527
+ minHeight: f64,
1528
+ titlebar: Titlebar,
1529
+ transparent: bool,
1530
+ alwaysOnTop: bool,
1531
+ clickThrough: bool,
1532
+ activateOnShow: bool,
1533
+ allowsFullscreen: bool,
1534
+ closePolicy: ClosePolicy,
1535
+ onCloseCommand: []const u8,
1536
+ };
1537
+
1538
+ 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 = "" },
1544
+ };
1545
+
1546
+ pub const Msg = union(enum) { noop };
1547
+ pub const Model = struct {
1548
+ pub fn windows(_: *const Model) []const Descriptor {
1549
+ return &descriptors;
1550
+ }
1551
+ };
1552
+ };
1553
+
1554
+ test "TypeScript windows adapter keeps the declared prefix on overflow and projects chromeless" {
1555
+ const Adapter = TsUiApp(WindowsAdapterTestCore);
1556
+ comptime Adapter.validateWindowsHelper();
1557
+ var model = WindowsAdapterTestCore.Model{};
1558
+ var scratch = Adapter.App.WindowsScratch{};
1559
+ const descriptors = Adapter.windowsAdapter(&model, &scratch);
1560
+ try std.testing.expectEqual(Adapter.App.max_ui_windows, descriptors.len);
1561
+ try std.testing.expectEqualStrings("one", descriptors[0].label);
1562
+ try std.testing.expectEqual(@import("app_manifest").WindowTitlebarStyle.chromeless, descriptors[0].titlebar);
1563
+ try std.testing.expect(descriptors[0].transparent);
1564
+ try std.testing.expectEqualStrings("four", descriptors[3].label);
1565
+ }
1566
+
1567
+ const WindowCloseCommandTestCore = struct {
1568
+ pub const Msg = union(enum) { closed, noop };
1569
+ pub const Model = struct {};
1570
+ };
1571
+
1572
+ fn mappedWindowCloseCommand(name: []const u8) ?WindowCloseCommandTestCore.Msg {
1573
+ return if (std.mem.eql(u8, name, "settings.closed")) .closed else null;
1574
+ }
1575
+
1576
+ test "TypeScript window close commands refuse missing and unmapped command callbacks" {
1577
+ const Adapter = TsUiApp(WindowCloseCommandTestCore);
1578
+ Adapter.command_store = null;
1579
+ try std.testing.expectError(error.MissingCommandMapper, Adapter.windowCloseMsg("settings.closed"));
1580
+ try std.testing.expect((try Adapter.windowCloseMsg("")) == null);
1581
+
1582
+ Adapter.command_store = mappedWindowCloseCommand;
1583
+ try std.testing.expectError(error.UnmappedCommand, Adapter.windowCloseMsg("settings.missing"));
1584
+ try std.testing.expectEqual(WindowCloseCommandTestCore.Msg.closed, (try Adapter.windowCloseMsg("settings.closed")).?);
1585
+ }