@native-sdk/cli 0.10.0 → 0.11.0

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 (465) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +320 -60
  4. package/build/corewire.zig +53 -0
  5. package/build/test_shards.zig +49 -0
  6. package/build/ts_run.mjs +3 -3
  7. package/build.zig +1818 -87
  8. package/package.json +19 -14
  9. package/packages/core/compile-surface/core.ts +134 -72
  10. package/packages/core/package-lock.json +75 -357
  11. package/packages/core/package.json +25 -4
  12. package/packages/core/scripts/compiler_command.mjs +17 -12
  13. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  14. package/packages/core/scripts/gen_declarations.mjs +3 -2
  15. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  16. package/packages/core/scripts/install_scriptc.mjs +182 -0
  17. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  18. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  19. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  20. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  21. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  22. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  23. package/packages/core/scripts/run_native_tests.mjs +22 -0
  24. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  25. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  26. package/packages/core/scripts/stage_external_core.mjs +57 -1
  27. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  28. package/packages/core/sdk/bytes.d.ts +2 -0
  29. package/packages/core/sdk/bytes.ts +86 -0
  30. package/packages/core/sdk/core.d.ts +308 -4
  31. package/packages/core/sdk/core.ts +320 -84
  32. package/packages/core/sdk/events.d.ts +247 -0
  33. package/packages/core/sdk/events.ts +230 -2
  34. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  35. package/packages/core/sdk/internal/image_identity.ts +71 -0
  36. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  37. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  38. package/packages/core/sdk/text.d.ts +27 -0
  39. package/packages/core/sdk/text.ts +206 -15
  40. package/packages/core/sdk/theme.d.ts +251 -0
  41. package/packages/core/sdk/theme.ts +267 -0
  42. package/packages/core/src/authorization.ts +137 -0
  43. package/packages/core/src/automation_commands.ts +201 -0
  44. package/packages/core/src/automation_interactions.ts +92 -0
  45. package/packages/core/src/bridge_descriptors.ts +104 -0
  46. package/packages/core/src/builtin_coordination.ts +172 -0
  47. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  48. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  49. package/packages/core/src/canvas_scene_observation.ts +145 -0
  50. package/packages/core/src/chart_content.ts +161 -0
  51. package/packages/core/src/chart_plans.ts +432 -0
  52. package/packages/core/src/checker.ts +166 -19
  53. package/packages/core/src/code_content.ts +580 -0
  54. package/packages/core/src/command_coordination.ts +140 -0
  55. package/packages/core/src/component_composition.ts +94 -0
  56. package/packages/core/src/component_construction.ts +149 -0
  57. package/packages/core/src/contract.ts +25 -7
  58. package/packages/core/src/control_appearance.ts +232 -0
  59. package/packages/core/src/control_commands.ts +115 -0
  60. package/packages/core/src/control_content.ts +105 -0
  61. package/packages/core/src/control_geometry.ts +107 -0
  62. package/packages/core/src/control_payloads.ts +119 -0
  63. package/packages/core/src/control_primitives.ts +134 -0
  64. package/packages/core/src/devhost.ts +82 -7
  65. package/packages/core/src/devhost_journal.mjs +30 -7
  66. package/packages/core/src/effect_plans.ts +71 -0
  67. package/packages/core/src/flow_measurement.ts +121 -0
  68. package/packages/core/src/font_registry.ts +37 -0
  69. package/packages/core/src/glyph_atlas.ts +86 -0
  70. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  71. package/packages/core/src/gpu_planning.ts +123 -0
  72. package/packages/core/src/gpu_presentation.ts +55 -0
  73. package/packages/core/src/host_flow.ts +89 -0
  74. package/packages/core/src/host_input_regions.ts +165 -0
  75. package/packages/core/src/image_registry.ts +66 -0
  76. package/packages/core/src/indicator_plans.ts +132 -0
  77. package/packages/core/src/infer.ts +150 -8
  78. package/packages/core/src/input_composition.ts +116 -0
  79. package/packages/core/src/intrinsic_measure.ts +100 -0
  80. package/packages/core/src/layout_coordination.ts +207 -0
  81. package/packages/core/src/leaf_plans.ts +134 -0
  82. package/packages/core/src/markup_development.ts +160 -0
  83. package/packages/core/src/measurement_coordination.ts +185 -0
  84. package/packages/core/src/modules.ts +1 -1
  85. package/packages/core/src/motion_sampling.ts +100 -0
  86. package/packages/core/src/paragraph_layout.ts +192 -0
  87. package/packages/core/src/portable_sources.json +74 -0
  88. package/packages/core/src/portable_sources.ts +17 -0
  89. package/packages/core/src/registered_font.ts +93 -0
  90. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  91. package/packages/core/src/render_coordination.ts +170 -0
  92. package/packages/core/src/render_resources.ts +234 -0
  93. package/packages/core/src/runtime_policy.ts +3930 -0
  94. package/packages/core/src/scalar_text.ts +84 -0
  95. package/packages/core/src/service_contract.ts +2 -1
  96. package/packages/core/src/session_codecs.ts +309 -0
  97. package/packages/core/src/shell_admission.ts +126 -0
  98. package/packages/core/src/shell_coordination.ts +93 -0
  99. package/packages/core/src/sqlite_cli.ts +11 -0
  100. package/packages/core/src/status_validation.ts +232 -0
  101. package/packages/core/src/stream_policy.ts +63 -0
  102. package/packages/core/src/surface_recipes.ts +136 -0
  103. package/packages/core/src/system_admission.ts +60 -0
  104. package/packages/core/src/terminal_paint.ts +436 -0
  105. package/packages/core/src/text_document_width.ts +81 -0
  106. package/packages/core/src/text_measurement_cache.ts +69 -0
  107. package/packages/core/src/text_query_layout.ts +179 -0
  108. package/packages/core/src/text_run_layout.ts +410 -0
  109. package/packages/core/src/text_span_queries.ts +355 -0
  110. package/packages/core/src/typed_ast.ts +18 -1
  111. package/packages/core/src/types.ts +7 -5
  112. package/packages/core/src/vector_effects.ts +98 -0
  113. package/packages/core/src/vector_raster.ts +243 -0
  114. package/packages/core/src/view_components.ts +2415 -0
  115. package/packages/core/src/view_coordination.ts +198 -0
  116. package/packages/core/src/view_frontend.ts +980 -0
  117. package/packages/core/src/widget_audits.ts +202 -0
  118. package/packages/core/src/widget_changes.ts +258 -0
  119. package/packages/core/src/widget_metrics.ts +139 -0
  120. package/packages/core/src/widget_motion.ts +171 -0
  121. package/packages/core/src/widget_paint.ts +272 -0
  122. package/packages/core/src/widget_paint_walk.ts +203 -0
  123. package/packages/core/src/widget_presentation.ts +141 -0
  124. package/packages/core/src/widget_routing.ts +262 -0
  125. package/packages/core/src/window_lifecycle.ts +92 -0
  126. package/packages/core/testing/index.ts +430 -0
  127. package/schemas/app.schema.json +13 -0
  128. package/skill-data/core/SKILL.md +2 -2
  129. package/skill-data/core/references/web-engines-packaging-debugging.md +2 -1
  130. package/skill-data/native-ui/SKILL.md +76 -17
  131. package/skill-data/ts-core/SKILL.md +113 -9
  132. package/skill-data/ts-services/SKILL.md +1 -1
  133. package/skill-data/ts-services/references/service-surface.md +264 -144
  134. package/src/app_runner/root.zig +25 -12
  135. package/src/app_runner/ts_compiled_view.zig +1631 -0
  136. package/src/app_runner/ts_core_main.zig +143 -10
  137. package/src/app_runner/ts_core_mobile.zig +24 -12
  138. package/src/automation/server.zig +1 -3
  139. package/src/automation/snapshot.zig +9 -637
  140. package/src/automation/snapshot_reference.zig +656 -0
  141. package/src/automation/snapshot_serialization.zig +566 -0
  142. package/src/platform/linux/gtk_host.c +36 -24
  143. package/src/platform/linux/gtk_pixels.h +118 -0
  144. package/src/platform/linux/gtk_pixels_test.c +241 -0
  145. package/src/platform/linux/root.zig +2 -0
  146. package/src/platform/macos/appkit_host.m +188 -30
  147. package/src/platform/macos/pointer_motion_test.m +96 -0
  148. package/src/platform/macos/scroll_driver_test.m +105 -0
  149. package/src/platform/macos/spectrum_bins.h +34 -0
  150. package/src/platform/macos/spectrum_bins_test.c +56 -0
  151. package/src/platform/macos/text_keyboard_test.m +80 -0
  152. package/src/platform/macos/widget_focus_test.m +66 -0
  153. package/src/platform/null_platform.zig +26 -2
  154. package/src/platform/null_platform_tests.zig +13 -0
  155. package/src/platform/root.zig +1 -0
  156. package/src/platform/types.zig +13 -0
  157. package/src/platform/windows/root.zig +2 -0
  158. package/src/platform/windows/webview2_host.cpp +7 -2
  159. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  160. package/src/primitives/app_manifest/root.zig +2 -0
  161. package/src/primitives/app_manifest/tests.zig +4 -1
  162. package/src/primitives/app_manifest/validation.zig +2 -0
  163. package/src/primitives/canvas/a11y_audit.zig +3 -1
  164. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  165. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  166. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  167. package/src/primitives/canvas/code_content_policy.zig +162 -0
  168. package/src/primitives/canvas/commands.zig +29 -1
  169. package/src/primitives/canvas/component_composition.zig +125 -0
  170. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  171. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  172. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  173. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  174. package/src/primitives/canvas/control_command_policy.zig +75 -0
  175. package/src/primitives/canvas/control_content_policy.zig +90 -0
  176. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  177. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  178. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  179. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  180. package/src/primitives/canvas/events.zig +1027 -1
  181. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  182. package/src/primitives/canvas/frame.zig +92 -23
  183. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  184. package/src/primitives/canvas/gpu.zig +10 -0
  185. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  186. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  187. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  188. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  189. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  190. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  191. package/src/primitives/canvas/intrinsic_measure_policy.zig +128 -0
  192. package/src/primitives/canvas/layout_audit.zig +5 -2
  193. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  194. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  195. package/src/primitives/canvas/markdown.zig +13 -3
  196. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  197. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  198. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  199. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  200. package/src/primitives/canvas/reference.zig +12 -6
  201. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  202. package/src/primitives/canvas/render.zig +48 -0
  203. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  204. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  205. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  206. package/src/primitives/canvas/render_effects.zig +14 -0
  207. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  208. package/src/primitives/canvas/render_images.zig +14 -0
  209. package/src/primitives/canvas/render_layers.zig +14 -0
  210. package/src/primitives/canvas/render_override_policy.zig +119 -0
  211. package/src/primitives/canvas/render_paths.zig +14 -0
  212. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  213. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  214. package/src/primitives/canvas/root.zig +100 -0
  215. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  216. package/src/primitives/canvas/serialization.zig +8 -1
  217. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  218. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  219. package/src/primitives/canvas/terminal_grid.zig +10 -696
  220. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  221. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  222. package/src/primitives/canvas/text.zig +1 -0
  223. package/src/primitives/canvas/text_atlas.zig +113 -0
  224. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  225. package/src/primitives/canvas/text_document_policy.zig +120 -0
  226. package/src/primitives/canvas/text_layout.zig +51 -2
  227. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  228. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  229. package/src/primitives/canvas/text_layout_types.zig +3 -0
  230. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  231. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  232. package/src/primitives/canvas/text_metrics.zig +23 -0
  233. package/src/primitives/canvas/text_query_policy.zig +156 -0
  234. package/src/primitives/canvas/text_run_policy.zig +252 -0
  235. package/src/primitives/canvas/text_scalar_policy.zig +156 -0
  236. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  237. package/src/primitives/canvas/text_spans.zig +280 -8
  238. package/src/primitives/canvas/text_tests.zig +10 -0
  239. package/src/primitives/canvas/tokens.zig +38 -0
  240. package/src/primitives/canvas/ui.zig +250 -83
  241. package/src/primitives/canvas/ui_markup.zig +139 -33
  242. package/src/primitives/canvas/ui_markup_compiled.zig +319 -59
  243. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  244. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  245. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  246. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  247. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  248. package/src/primitives/canvas/ui_markup_view.zig +258 -32
  249. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  250. package/src/primitives/canvas/ui_schema.zig +13 -1
  251. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  252. package/src/primitives/canvas/ui_tests.zig +1 -0
  253. package/src/primitives/canvas/vector.zig +36 -2
  254. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  255. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  256. package/src/primitives/canvas/virtual_extent_policy.zig +292 -0
  257. package/src/primitives/canvas/virtual_extents.zig +99 -3
  258. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  259. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  260. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  261. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  262. package/src/primitives/canvas/widget_layout.zig +673 -128
  263. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  264. package/src/primitives/canvas/widget_metric_policy.zig +126 -0
  265. package/src/primitives/canvas/widget_metrics.zig +45 -6
  266. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  267. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  268. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  269. package/src/primitives/canvas/widget_render.zig +744 -74
  270. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  271. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  272. package/src/primitives/canvas/widget_render_style.zig +94 -0
  273. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  274. package/src/primitives/canvas/widget_routing.zig +75 -0
  275. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  276. package/src/primitives/canvas/widget_runtime.zig +20 -1
  277. package/src/primitives/canvas/widget_semantics.zig +25 -0
  278. package/src/primitives/canvas/widget_text_input.zig +86 -23
  279. package/src/primitives/canvas/widget_text_select.zig +1 -0
  280. package/src/primitives/canvas/widget_tree.zig +8 -1
  281. package/src/primitives/canvas/widgets.zig +42 -12
  282. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  283. package/src/root.zig +21 -0
  284. package/src/runtime/accessibility_policy.zig +122 -0
  285. package/src/runtime/api.zig +28 -0
  286. package/src/runtime/app_dispatch_policy.zig +68 -0
  287. package/src/runtime/authorization_policy.zig +150 -0
  288. package/src/runtime/automation_command_policy.zig +241 -0
  289. package/src/runtime/automation_interaction_policy.zig +107 -0
  290. package/src/runtime/automation_snapshot.zig +52 -22
  291. package/src/runtime/automation_snapshot_reference.zig +290 -0
  292. package/src/runtime/automation_widget_dispatch.zig +267 -355
  293. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  294. package/src/runtime/blob_policy.zig +58 -0
  295. package/src/runtime/blob_reference.zig +64 -0
  296. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  297. package/src/runtime/builtin_bridge.zig +180 -44
  298. package/src/runtime/builtin_coordination_policy.zig +121 -0
  299. package/src/runtime/callback_policy_test_reference.zig +97 -0
  300. package/src/runtime/canvas_drag_policy.zig +94 -0
  301. package/src/runtime/canvas_fonts.zig +38 -10
  302. package/src/runtime/canvas_frame.zig +590 -134
  303. package/src/runtime/canvas_frame_helpers.zig +1 -0
  304. package/src/runtime/canvas_hover_policy.zig +131 -0
  305. package/src/runtime/canvas_images.zig +59 -30
  306. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  307. package/src/runtime/canvas_limits.zig +1 -1
  308. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  309. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  310. package/src/runtime/canvas_widget_context_menu.zig +4 -4
  311. package/src/runtime/canvas_widget_display.zig +110 -9
  312. package/src/runtime/canvas_widget_events.zig +718 -328
  313. package/src/runtime/canvas_widget_runtime.zig +437 -81
  314. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  315. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  316. package/src/runtime/canvas_widget_state.zig +93 -56
  317. package/src/runtime/channel_sources.zig +80 -0
  318. package/src/runtime/command_policy.zig +161 -0
  319. package/src/runtime/component_policy.zig +83 -0
  320. package/src/runtime/core.zig +156 -6
  321. package/src/runtime/desktop_files.zig +189 -0
  322. package/src/runtime/effects.zig +466 -29
  323. package/src/runtime/effects_tests.zig +28 -0
  324. package/src/runtime/file_policy_test_reference.zig +113 -0
  325. package/src/runtime/flow.zig +418 -341
  326. package/src/runtime/flow_reference.zig +1426 -0
  327. package/src/runtime/font_registry_policy.zig +72 -0
  328. package/src/runtime/frame_profile.zig +24 -33
  329. package/src/runtime/gpu_surface_events.zig +97 -35
  330. package/src/runtime/host_event_pump.zig +303 -0
  331. package/src/runtime/host_event_pump_reference.zig +268 -0
  332. package/src/runtime/host_flow_policy.zig +155 -0
  333. package/src/runtime/host_input_regions_policy.zig +156 -0
  334. package/src/runtime/image_registry_policy.zig +94 -0
  335. package/src/runtime/input_composition_policy.zig +138 -0
  336. package/src/runtime/journal_policy.zig +66 -0
  337. package/src/runtime/journal_reference.zig +53 -0
  338. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  339. package/src/runtime/markup_development_policy.zig +91 -0
  340. package/src/runtime/media_surface.zig +40 -1
  341. package/src/runtime/motion_sampling_policy.zig +159 -0
  342. package/src/runtime/recording_policy.zig +42 -0
  343. package/src/runtime/render_animation_policy.zig +206 -0
  344. package/src/runtime/replay_policy.zig +66 -0
  345. package/src/runtime/replay_policy_reference.zig +326 -0
  346. package/src/runtime/replay_progress_policy.zig +64 -0
  347. package/src/runtime/replay_progress_reference.zig +34 -0
  348. package/src/runtime/request_policy_test_reference.zig +188 -0
  349. package/src/runtime/root.zig +13 -0
  350. package/src/runtime/session_blobs.zig +157 -58
  351. package/src/runtime/session_blobs_reference.zig +692 -0
  352. package/src/runtime/session_codec.zig +361 -0
  353. package/src/runtime/session_codec_reference.zig +1027 -0
  354. package/src/runtime/session_journal.zig +246 -983
  355. package/src/runtime/session_record.zig +224 -45
  356. package/src/runtime/session_replay.zig +157 -415
  357. package/src/runtime/session_tests.zig +552 -0
  358. package/src/runtime/shell_admission_policy.zig +225 -0
  359. package/src/runtime/shell_coordination_policy.zig +138 -0
  360. package/src/runtime/shell_layout.zig +126 -1
  361. package/src/runtime/snapshot_policy.zig +60 -0
  362. package/src/runtime/snapshot_reference.zig +64 -0
  363. package/src/runtime/state.zig +16 -0
  364. package/src/runtime/status_validation.zig +190 -0
  365. package/src/runtime/system_admission_policy.zig +140 -0
  366. package/src/runtime/system_services.zig +46 -36
  367. package/src/runtime/tests.zig +1 -0
  368. package/src/runtime/ts_canvas_hooks.zig +261 -0
  369. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  370. package/src/runtime/ts_canvas_icons.zig +234 -0
  371. package/src/runtime/ts_core_host.zig +2325 -411
  372. package/src/runtime/ts_core_host_tests.zig +1982 -0
  373. package/src/runtime/ts_test_host.zig +699 -0
  374. package/src/runtime/ts_ui_app.zig +1087 -45
  375. package/src/runtime/ui_app.zig +1117 -629
  376. package/src/runtime/ui_app_provenance.zig +147 -5
  377. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  378. package/src/runtime/ui_app_tests.zig +619 -9
  379. package/src/runtime/ui_app_window_tests.zig +89 -0
  380. package/src/runtime/view.zig +25 -0
  381. package/src/runtime/view_canvas.zig +30 -6
  382. package/src/runtime/view_coordination_policy.zig +147 -0
  383. package/src/runtime/view_widget_control.zig +51 -14
  384. package/src/runtime/view_widget_scroll.zig +16 -5
  385. package/src/runtime/view_widget_text.zig +153 -68
  386. package/src/runtime/view_widget_tree.zig +460 -56
  387. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  388. package/src/runtime/widget_motion_policy.zig +238 -0
  389. package/src/runtime/window_command_bridge_tests.zig +63 -0
  390. package/src/runtime/window_lifecycle_policy.zig +127 -0
  391. package/src/runtime/window_storage.zig +74 -8
  392. package/src/runtime/window_view_runtime.zig +148 -33
  393. package/src/runtime/window_views.zig +163 -10
  394. package/src/tooling/codesign.zig +125 -74
  395. package/src/tooling/components/identity_tests.zig +62 -36
  396. package/src/tooling/components/stepper.native +24 -0
  397. package/src/tooling/components/stepper.zig +0 -19
  398. package/src/tooling/components/timeline-item.native +22 -0
  399. package/src/tooling/components/timeline.native +5 -3
  400. package/src/tooling/components/timeline_item.zig +0 -32
  401. package/src/tooling/eject_components.zig +76 -8
  402. package/src/tooling/ios.zig +66 -12
  403. package/src/tooling/manifest.zig +35 -0
  404. package/src/tooling/package.zig +85 -1
  405. package/src/tooling/raw_manifest.zig +6 -0
  406. package/src/tooling/templates.zig +15 -3
  407. package/src/tooling/ts_core.zig +13 -3
  408. package/src/tooling/verbs.zig +22 -0
  409. package/tools/corewire/build_profile.mjs +54 -0
  410. package/tools/corewire/contract_intake.ts +303 -0
  411. package/tools/corewire/contract_intake.zig +82 -0
  412. package/tools/corewire/core.test.ts +166 -0
  413. package/tools/corewire/core_abi.zig +51 -0
  414. package/tools/corewire/core_cases.ts +233 -0
  415. package/tools/corewire/core_contract.ts +407 -0
  416. package/tools/corewire/core_emission.ts +136 -0
  417. package/tools/corewire/core_emission.zig +69 -0
  418. package/tools/corewire/core_goldens.json +3110 -0
  419. package/tools/corewire/core_policy.ts +14 -0
  420. package/tools/corewire/core_policy.zig +48 -0
  421. package/tools/corewire/core_projection.ts +360 -0
  422. package/tools/corewire/core_vocabulary.ts +6 -0
  423. package/tools/corewire/emit.zig +19 -1590
  424. package/tools/corewire/emit_facade.ts +714 -0
  425. package/tools/corewire/emit_facade.zig +10 -3752
  426. package/tools/corewire/emit_mirror.ts +290 -0
  427. package/tools/corewire/emit_profile.ts +50 -0
  428. package/tools/corewire/emit_service.ts +331 -0
  429. package/tools/corewire/emit_service.zig +23 -842
  430. package/tools/corewire/entry.test.ts +95 -0
  431. package/tools/corewire/entry_coordination.ts +127 -0
  432. package/tools/corewire/entry_coordination.zig +190 -0
  433. package/tools/corewire/facade_templates.ts +85 -0
  434. package/tools/corewire/filesystem.test.ts +166 -0
  435. package/tools/corewire/filesystem_coordination.ts +213 -0
  436. package/tools/corewire/filesystem_coordination.zig +245 -0
  437. package/tools/corewire/intake.test.ts +35 -0
  438. package/tools/corewire/intake_cases.ts +55 -0
  439. package/tools/corewire/intake_goldens.json +12237 -0
  440. package/tools/corewire/invocation.test.ts +24 -0
  441. package/tools/corewire/invocation.ts +175 -0
  442. package/tools/corewire/invocation.zig +136 -0
  443. package/tools/corewire/invocation_cases.ts +60 -0
  444. package/tools/corewire/invocation_fixture.ts +33 -0
  445. package/tools/corewire/invocation_goldens.json +1143 -0
  446. package/tools/corewire/invocation_tests.zig +111 -0
  447. package/tools/corewire/invocation_usage.ts +2 -0
  448. package/tools/corewire/lossless_projection.ts +96 -0
  449. package/tools/corewire/main.zig +7 -680
  450. package/tools/corewire/main_reference.zig +415 -0
  451. package/tools/corewire/mirror_templates.ts +55 -0
  452. package/tools/corewire/profile.test.ts +248 -0
  453. package/tools/corewire/profile.zig +56 -0
  454. package/tools/corewire/profile_emission.ts +202 -0
  455. package/tools/corewire/profile_library.json +29 -0
  456. package/tools/corewire/profile_tests.zig +136 -0
  457. package/tools/corewire/service.test.ts +75 -0
  458. package/tools/corewire/service_cases.ts +61 -0
  459. package/tools/corewire/service_contract.zig +40 -146
  460. package/tools/corewire/service_goldens.json +650 -0
  461. package/tools/corewire/service_projection.zig +52 -0
  462. package/tools/corewire/service_templates.ts +14 -0
  463. package/tools/corewire/shim_rt.zig +9 -0
  464. package/tools/corewire/sidecar.zig +267 -1438
  465. package/tools/corewire/emit_profile.zig +0 -521
@@ -17,7 +17,7 @@ The markup compiles to the same widget tree a hand-written `canvas.Ui(Msg)` buil
17
17
 
18
18
  Editors highlight `.native` markup well in HTML mode — the default scaffold writes no editor config, so add `.vscode/settings.json` with `"files.associations": {"*.native": "html"}` yourself, or scaffold with `native init --full`, which writes it.
19
19
 
20
- Start a new app with `native init` (zero-config: `app.zon` + `src/core.ts` + `src/app.native` + assets; the CLI generates the build graph). Use `examples/chatbot`, `examples/soundboard-ts`, and `examples/system-monitor-ts` as substantial TypeScript references. The `native check|dev|test|build` verbs drive any app directory shaped this way.
20
+ Start a new app with `native init` (zero-config: `app.zon` + `src/core.ts` + `src/app.native` + assets; the CLI generates the build graph). Use `examples/chatbot`, `examples/soundboard`, and `examples/system-monitor` as substantial TypeScript references. The `native check|dev|test|build` verbs drive any app directory shaped this way.
21
21
 
22
22
  ## Menu-bar status items (TypeScript default)
23
23
 
@@ -64,8 +64,8 @@ pub fn main(init: std.process.Init) !void {
64
64
  .canvas_label = "habits-canvas", // must match the ShellView label
65
65
  .update = update,
66
66
  .markup = .{
67
- .source = @embedFile("habits.native"),
68
- .watch_path = "src/habits.native", // dev hot reload; omit in release
67
+ .source = @embedFile("app.native"),
68
+ .watch_path = "src/app.native", // dev hot reload; omit in release
69
69
  .io = init.io,
70
70
  },
71
71
  });
@@ -84,16 +84,26 @@ The runtime owns the loop: install on first GPU frame, presentation, resize, poi
84
84
  ```zig
85
85
  const dev = @import("builtin").mode == .Debug;
86
86
  const App = native_sdk.UiAppWithFeatures(Model, Msg, .{ .runtime_markup = dev });
87
- const CompiledView = canvas.CompiledMarkupView(Model, Msg, @embedFile("habits.native"));
87
+ const CompiledView = canvas.CompiledMarkupView(Model, Msg, @embedFile("app.native"));
88
88
  // options:
89
89
  .view = CompiledView.build,
90
- .markup = if (dev) .{ .source = ..., .watch_path = "src/habits.native", .io = init.io } else null,
90
+ .markup = if (dev) .{ .source = ..., .watch_path = "src/app.native", .io = init.io } else null,
91
91
  ```
92
92
 
93
- With both set (dev), the compiled view renders until the watched file first changes, then the interpreter hot-reloads it. See `examples/habits` for the full pattern.
93
+ With both set (dev), the compiled view renders until the watched file first changes, then the interpreter hot-reloads it. See the native reference fixture in `tests/ts-core/habits_reference.zig` for this Zig wiring pattern.
94
94
 
95
95
  ### Webview panes: canvas + live web content in one window
96
96
 
97
+ For TypeScript apps, export `webPanes(model: Model): readonly WebViewPane[]` from `core.ts`. Import the descriptor from `@native-sdk/core/events`; return `label`, nullable `anchor`, `url`, `x`, `y`, `width`, `height`, and `reloadToken`. The label identifies an existing manifest WebView; the anchor identifies a widget label such as `<panel label="preview-pane" grow="1"/>`. See `examples/canvas-preview` for pane, frame, and tray coordination in one compiled core. The native adapter copies bytes and validates finite geometry and safe integer tokens; the OS owns WebView hosting and navigation policy.
98
+
99
+ For all u64 reload states, return `readonly ExactWebViewPane[]` instead. Its `reloadToken` is decimal ASCII bytes; the host validates the full u64 range without rounding. `WebViewPane` retains its existing safe-number token.
100
+
101
+ ### TypeScript terminal panes
102
+
103
+ Bind `<terminal pty="{shellKey}" scrollback="{scrollback}" on-terminal="terminalChanged" label="Shell" autofocus="true" grow="1"/>` to a `Uint8Array` helper or field naming the same key as `Cmd.ptySpawn`. Import `TerminalState` from `@native-sdk/core/events` for the message payload. The native host resolves the name to its PTY capability; engine identities never cross through a JavaScript number. Both view backends preserve the complete four-field state report. A bound slot remains reserved through exit until app teardown, keeping the ended screen stable across rebuilds. Restarting the same name reuses its slot; the existing four-slot budget applies. Keep `.terminal_sessions = true` and the lazy Ghostty pin in the app's owned build, as in `examples/workbench`. Native integer PTY bindings remain supported.
104
+
105
+ For Zig cores and extensions:
106
+
97
107
  Declare the webview in the scene next to the gpu_surface (parent it to the canvas view), reserve its region with an empty panel carrying a semantics label, and let `Options.web_panes` snap the webview to that widget's layout frame while the model drives navigation:
98
108
 
99
109
  ```zig
@@ -143,6 +153,25 @@ fn statusItem(model: *const Model, scratch: *App.StatusItemScratch) App.StatusIt
143
153
 
144
154
  Title updates retitle the live `NSStatusItem` button without re-creating it; platforms without a tray-title seam keep menu updates and log the title gap once.
145
155
 
156
+ ### Windowed lists in markup
157
+
158
+ Use `<virtual-window>` to resolve one retained range before rendering, then `<virtual-list>` to request only its rendered rows. The window declares a stable literal `id`, an `as` range name, an `item-count`, and either `item-extent` or an exported Model-first `extent-estimate` helper. Optional `gap`, `overscan`, `viewport-fallback`, `index-base`, and `anchor="leading|trailing"` describe the complete content geometry.
159
+
160
+ ```html
161
+ <virtual-window id="records" as="range" item-count="{loaded}" item-extent="48" overscan="4">
162
+ <column>
163
+ <virtual-list window="range" each="rows" as="row" grow="1" label="Records">
164
+ <list-item key="{row.id}" focusable="true" on-press="select:{row.id}">{row.title}</list-item>
165
+ </virtual-list>
166
+ <status-bar>{range.first_visible_index}–{range.last_visible_index}</status-bar>
167
+ </column>
168
+ </virtual-window>
169
+ ```
170
+
171
+ In a TypeScript core, `rows(model: Model, range: VirtualListRange): readonly Row[]` takes the complete SDK range from `@native-sdk/core/events` and returns exactly `range.end_index - range.start_index` rows in rendered-index order. An extent estimator has shape `rowExtent(model: Model, index: number): number`; its retained identity survives rebuilds. Each row has one keyed root. Ordinary scroll styling, `on-scroll`, and reach-start/end messages belong on `virtual-list`.
172
+
173
+ Each window has one root and exactly one consuming list; windows cannot nest. A range can pass through a template argument, and secondary window views have their own retained descriptors. The full range exposes visible and rendered bounds, content extent, row extent, and offset; use it for footer text without copying scroll state into the model. See `examples/feed` for variable-height estimates, stable row queries, and retained selection.
174
+
146
175
  ### Native scrolling (macOS)
147
176
 
148
177
  Zero app code: on macOS every non-virtualized `scroll` region — and every windowed virtual list (`ui.virtualList`), whose driver content size is the full virtual extent — is driven by an invisible `NSScrollView` — OS momentum and the system overlay scrollbar — while the engine renders the content. `widget.value` stays the offset of record, so the rebuild reconcile rule ("user offset survives rebuilds until the source offset changes"), automation snapshot offsets (`scroll=[offset=..]`), and `Options.sync` all work exactly as before; the engine-drawn scrollbar simply stops painting for natively driven regions. Programmatic scrolls still work: change the source offset (or scroll via keyboard/automation) and the runtime pushes it into the native scroller. GTK/Win32 and mobile embeds keep the engine's wheel physics unchanged. Nested-scroll saturation handoff (inner region exhausted, outer continues) is per-region native today: the inner region stops at its edge like a standalone scroller.
@@ -171,6 +200,8 @@ Markup declares the menu as a `<context-menu>` element — a DIRECT child of the
171
200
  </list-item>
172
201
  ```
173
202
 
203
+ The compiled TypeScript view supports one direct menu with at most 32 labeled `menu-item` leaves and bare separators. Items require `on-press` and may bind `disabled`; structure tags inside menus currently remain on the native markup backend. The menu is copied into the native tree arena before the compiled result expires.
204
+
174
205
  The Zig builder's mirror is `ElementOptions.context_menu` — per-widget items in the chrome-menu shape with typed messages:
175
206
 
176
207
  ```zig
@@ -186,7 +217,7 @@ ui.listItem(.{
186
217
 
187
218
  The deepest declaring widget on the hit route wins; disabled items and separators are fine (`enabled = false`, `.separator = true`). Zero-code defaults need no declaration: editable text fields present the standard Cut / Copy / Paste / Select All menu wired to the existing clipboard actions, and a selected static text presents Copy (these defaults are presenter-only — without an OS menu they degrade to the keyboard clipboard paths). Touch long-press is design-noted for the mobile embeds: the iOS host's under-slop `Pending` touch state is the timer seam, pending a secondary-button leg in the embed ABI and `UIEditMenuInteraction` presentation.
188
219
 
189
- Automation drives the native path honestly: snapshots list every widget's declared items in invocation order (`context_menu=["Rename","Delete"]`, separators keep their slots, disabled items say so), `widget-context-press <view> <id>` performs the real secondary click (presenting the menu), and `widget-context-menu <view> <id> <item-index>` invokes an item — the selection dispatches as the same `context_menu_action` platform event a real pick produces (so it journals and replays), because the OS menu's tracking loop cannot be driven programmatically. Dead invocations fail by name (undeclared menu, index out of range, separator slot, disabled item). `examples/notes` row menus and `examples/gpu-dashboard` nav rows carry live menus; `zig build test-example-notes`, `test-example-gpu-dashboard`, and the runtime context-menu suite verify dispatch, the fallback surface, and the verb.
220
+ Automation drives the native path honestly: snapshots list every widget's declared items in invocation order (`context_menu=["Rename","Delete"]`, separators keep their slots, disabled items say so), `widget-context-press <view> <id>` performs the real secondary click (presenting the menu), and `widget-context-menu <view> <id> <item-index>` invokes an item — the selection dispatches as the same `context_menu_action` platform event a real pick produces; the journal records the complete widget invocation so replay reconstructs its pending request before selection, because the OS menu's tracking loop cannot be driven programmatically. Dead invocations fail by name (undeclared menu, index out of range, separator slot, disabled item). `examples/notes` row menus and `examples/gpu-dashboard` nav rows carry live menus; `zig build test-example-notes`, `test-example-gpu-dashboard`, and the runtime context-menu suite verify dispatch, the fallback surface, and the verb.
190
221
 
191
222
  ## Elements
192
223
 
@@ -208,12 +239,13 @@ Automation drives the native path honestly: snapshots list every widget's declar
208
239
  | `text`, `badge`, `tooltip` | text leaves | text content, `{}` interpolation allowed; `text` line policy via `wrap` (`"true"` word-wraps; `"false"`/unset paint one honest line, overflow eliding by default — `overflow="clip"` opts out), and `text` alone takes the typography rungs `size="heading"`/`size="display"` (themable token steps above title — section headings, hero stats, timer numerals). `tooltip` with `anchor="above\|below"` floats against its parent (the stack wrapping trigger + tooltip, the dropdown pattern) and the RUNTIME owns its visibility — hover intent on the trigger: shows after `tooltip-delay` ms (default 600; `"0"` = instant) and immediately on keyboard focus; hides on leave, focus departure, Escape, or a press of the trigger (a press also closes the warm window), and a shared 400ms warm window after a pointer-hovered tooltip hides on leave (the only hide that warms) shows the next trigger's tooltip instantly; the model never hears hover. These are shadcn/ui's defaults (Base UI). Without `anchor` it stays a static leaf that paints whenever the view renders it |
209
240
  | `text` > `span` | inline styled runs | mixed-style text in ONE wrapped paragraph: span children style runs with `weight="regular\|medium\|bold"`, `mono`, `italic`, `scale` (a positive multiplier on the paragraph's base size — inline headings, hero stats), `underline`, `foreground` (token name); `{bindings}` interpolate inside spans; whitespace between runs collapses to a single space (none = the runs abut); spans do not nest, take no events, and the paragraph announces as one text run — see "Rich text" |
210
241
  | `button`, `toggle-button`, `list-item`, `menu-item`, `toggle`, `switch`, `select`, `avatar` | text-bearing controls | label is the text content; `button`, `toggle-button`, `list-item`, and `menu-item` also take `icon="save"` — a vector icon drawn inline (buttons/toggle-buttons before the label, icon-only when the content is empty: add a `label`; list/menu items as a leading slot), ONE hit target whose icon follows the element's enabled/disabled tint (no overlay stacking, no duplicated `on-press`); tab strips are `toggle-button` children, so tabs get icons this way; `select` shows `placeholder` while empty and dispatches `on-press`; `avatar` renders initials, or a runtime image via `image="{binding}"` (see the Images section) |
242
+ | `segmented-control` | exclusive-choice control | standalone text-bearing segment; bind `selected`, dispatch `on-press`, and optionally add a vector `icon`; compose several in a row, or use `tabs` for the strip-and-panel pattern |
211
243
  | `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); checkbox/radio visible labels are text content (`<checkbox>Done</checkbox>`), with `text="..."` as the equivalent binding-friendly form and `label=` alone naming one for accessibility without drawing a label; a radio selection TRANSITION (pointer, Space/Enter, grouped navigation, or accessibility selection) dispatches `on-change` when bound, then `on-toggle`, then `on-press` for compatibility — reactivating the already-checked radio has no new `on-change` edge, though a legacy fallback still receives the activation; a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
212
244
  | `text-field`, `input`, `search-field`, `combobox`, `textarea` | text entry | `placeholder`; edits via `on-input`, enter via `on-submit` on single-line kinds; in a default `textarea`, Enter (and Shift+Enter) inserts a newline and `on-submit` dispatches on primary+Enter (cmd on macOS, ctrl elsewhere). A chat composer opts into `submit-on-enter="true"`: plain Enter submits, Shift+Enter remains a newline, and the primary chord still submits. `search-field` carries a built-in trailing clear affordance whenever it holds text (press the x, or Escape while focused — both clear through the text-edit path, so `on-input` hears it; no attribute, no external Clear button needed) |
213
245
  | `status-bar` | status bar | text leaf: content only, no children |
214
246
  | `separator`, `spacer` | separator, flexible space | `separator` is axis-aware: a horizontal rule in a `column`, a thin vertical divider in a `row`; give `spacer` a `grow` |
215
247
  | `skeleton`, `spinner` | loading leaves | size `skeleton` with `width`/`height` |
216
- | `icon` | vector icon leaf | `name` picks the icon: a bare literal is a curated built-in stroke icon (compile-checked; 49 names: search, plus, x, x-circle, check, check-circle, chevron-up/down/left/right, arrow-up/down/right, menu, panel-left, panel-right, settings, terminal, wrench, trash, edit, copy, external-link, play, pause, skip-back/forward, shuffle, repeat, music, volume, info, alert, download, save, folder, folder-open, file-text, sun, moon, eye, clock, git-pull-request, git-merge, git-branch, circle-dot, archive, refresh-cw, send); `app:<name>` reaches an icon the app registered at boot with `canvas.icons.registerAppIcons` (declare the table as `pub const app_icons` on the app root so `native check` verifies the name against the model contract), and one `{binding}` defers the choice to model data - an unknown resolved name draws the missing-icon fallback (a slashed circle) with a Debug warning naming the value, never a silent gap; tint with `foreground`, size with `width`/`height` |
248
+ | `icon` | vector icon leaf | `name` picks the icon: a bare literal is a curated built-in stroke icon (compile-checked; 49 names: search, plus, x, x-circle, check, check-circle, chevron-up/down/left/right, arrow-up/down/right, menu, panel-left, panel-right, settings, terminal, wrench, trash, edit, copy, external-link, play, pause, skip-back/forward, shuffle, repeat, music, volume, info, alert, download, save, folder, folder-open, file-text, sun, moon, eye, clock, git-pull-request, git-merge, git-branch, circle-dot, archive, refresh-cw, send); `app:<name>` reaches an icon the app registered at boot with `canvas.icons.registerAppIcons` (declare the table as `pub const app_icons` on the app root so `native check` verifies the name against the model contract), and one `{binding}` defers the choice to model data - an unknown resolved name draws the missing-icon fallback (a slashed circle) with a Debug warning naming the value; tint with `foreground`, size with `width`/`height` |
217
249
  | `media-surface` | media surface leaf | composites a texture produced OUTSIDE the widget tree (video decoder, camera, an external renderer like mpv) into the layout like any widget — clipped, z-ordered, rounded. `surface="{binding}"` (required) binds the model-owned u64 surface id a Zig-tier producer targets (`runtime.acquireMediaSurfaceProducer` pushes RGBA8 frames, latest-wins, paced by the presented-frame clock; 0 = unbound, draws nothing; usable ids are nonzero values below the reserved bit 63). No intrinsic size — give it `width`/`height` or `grow`; display-only (presses fall through); `label` it (pictorial content). Texture contents are presentation chrome: goldens, reference screenshots, and session replay show the deterministic id-derived placeholder, never producer frames |
218
250
  | `image` | runtime image leaf | draws a RUNTIME-REGISTERED image by its model-owned u64 ImageId — the id `Cmd.imageLoad` (TS) or `fx.loadImage`/`fx.registerImageBytes` (Zig) registered pixels under. `image="{binding}"` (required) binds a model field/fn; ids are model data, never markup literals, and 0 draws nothing (store the id only when the load reports loaded — see the Images section). `source-x`/`source-y`/`source-width`/`source-height` select one atlas region in decoded-image pixel coordinates (declare all four). No intrinsic size — give it `width`/`height` or `grow`; display-only (presses fall through); `label` it (pictorial content) |
219
251
  | `code` | bare highlighted source/editor | `source="{binding}"` (required) provides source text and `language="tsx"` selects a literal lexer name; the component supplies no background, border, radius, shadow, or padding, so wrap it in a panel/card when chrome is wanted. It is read-only by default; `editable on-input="edit"` opts into multiline editing while retaining highlighting. It wraps by default, `line-numbers` opts into logical line numbers, `added-lines="5"` / `removed-lines="2-4"` add Geist-style diff rows without changing copied source, and `wrap="false"` preserves lines inside one horizontal scroll region. HTML-family highlighting distinguishes HTML/XML/SVG and JSX/TSX tags, attributes, strings, comments, and embedded expressions. Zig builder: `ui.code(CodeOptions, source)` |
@@ -224,7 +256,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
224
256
  | `context-menu` | consumed by its parent | right-click menu on its DIRECT parent (a hit-target kind or an element with `on-press`/`on-double-press`/`on-toggle`/`on-hold`/`on-drag`); metadata, never a flow child. Children: `menu-item`s (`on-press` required, `disabled` optional, no `icon`) and bare `separator`s, with `if`/`else`/`for` around them. Attribute-less; presents natively where the host has a menu presenter, as an anchored surface elsewhere — see "Context menus" |
225
257
  | `input-group` > `textarea` + `input-group-actions` | composite grouped input | the composer shape: ONE bordered field wrapping exactly one `textarea` (first — document order is focus order) plus an optional `input-group-actions` row of controls inside the same border. The group wears the focus ring for its focused descendant and the textarea's own chrome dissolves automatically, so the whole group reads as one field; the textarea keeps its full behavior (`text`, `placeholder`, `on-input`, `on-submit`, `autofocus`, and optional `submit-on-enter`). Group takes `label`, `width`, `height`, `min-width`, `grow`, `key`, `global-key`; the actions row takes `gap` and holds ordinary elements (`if`/`else`/`for` work — swap send for stop while streaming) — put a `<spacer grow="1"/>` between leading and trailing controls (`Ui.inputGroup`/`Ui.inputGroupActions` are the Zig-view equivalents) |
226
258
 
227
- Not markup-expressible (deliberately — write these as Zig view functions with `canvas.Ui`): `icon_button` (`<button icon="...">` with empty content is the declarative icon button), `data_grid` (per-column cell templates), `popover`/`menu_surface` (anchored to runtime geometry), `segmented_control` (use `tabs`/`toggle-group`: `<button>` children of `<tabs>` lower to segmented triggers automatically, so the active tab lifts per the house treatment). Charts ARE expressible: `<chart>` with `<series values="{binding}">` children binding model f32 iterables — see the Charts section (`.band` series and dynamic series composition stay with `ui.chart`). Built-in vector icons ARE expressible: `<icon name="search"/>` (closed, compile-checked name set; `Ui.icon` is the Zig-view equivalent). App-authored icons: `canvas.svg_icon.parseComptime(@embedFile("icons/logo.svg"))` parses any SVG in the common 24x24 stroke-icon dialect at comptime; register the parsed table once at boot with `canvas.icons.registerAppIcons(&table)` and draw by name via `ui.appIcon(.{...}, "logo")` or `ElementOptions.icon` — registered names render exactly like built-ins on every draw path. Markup `<icon>`/`<button icon>` stay built-in-only (the compiled engine validates names at comptime, where runtime registrations cannot exist — engine parity). Runtime images ARE expressible: `<image image="{cover}" width="120" height="80" label="Cover art"/>` and `<avatar image="{user_image}">CT</avatar>` bind a `u64` ImageId model field/fn (the id is just model data; 0 draws nothing / keeps the initials fallback) — see the Images section; the `image` binding is required on the leaf (an unbound `<image>` is dead markup) and stays avatar+image scoped. Add all four `source-x`/`source-y`/`source-width`/`source-height` attributes to draw one decoded-pixel sub-rectangle from a shared atlas.
259
+ Capabilities still awaiting a separate admission or ruling are image-backed `icon_button` content, `data_grid` per-column cell templates, and `popover`/`menu_surface` anchoring. `segmented-control` is a first-class markup leaf, and vector icon buttons use `<button size="icon" icon="..." label="..." on-press="..." />`. Charts ARE expressible: `<chart>` with `<series values="{binding}">` children binding model f32 iterables — see the Charts section (`.band` series and dynamic series composition stay with `ui.chart`). Built-in vector icons ARE expressible: `<icon name="search"/>` (closed, compile-checked name set; `Ui.icon` is the Zig-view equivalent). App-authored icons: `canvas.svg_icon.parseComptime(@embedFile("icons/logo.svg"))` parses any SVG in the common 24x24 stroke-icon dialect at comptime; register the parsed table once at boot with `canvas.icons.registerAppIcons(&table)` and draw by name via `ui.appIcon(.{...}, "logo")` or `ElementOptions.icon` — registered names render exactly like built-ins on every draw path. Markup `<icon>`/`<button icon>` stay built-in-only (the compiled engine validates names at comptime, where runtime registrations cannot exist — engine parity). Runtime images ARE expressible: `<image image="{cover}" width="120" height="80" label="Cover art"/>` and `<avatar image="{user_image}">CT</avatar>` bind a `u64` ImageId model field/fn (the id is just model data; 0 draws nothing / keeps the initials fallback) — see the Images section; the `image` binding is required on the leaf (an unbound `<image>` is dead markup) and stays avatar+image scoped. Add all four `source-x`/`source-y`/`source-width`/`source-height` attributes to draw one decoded-pixel sub-rectangle from a shared atlas.
228
260
 
229
261
  ## Attributes
230
262
 
@@ -277,10 +309,10 @@ How the pieces fit, all model-owned (TEA):
277
309
  - **`anchor` floats the menu.** The dropdown positions against its PARENT's frame (the `stack`, sized by the trigger): below it by default, flipping above when it doesn't fit and the other side has more room, height clamped to the chosen side, x clamped into the window. It consumes NO space in the flow (siblings never reflow), paints in a late z-pass above the whole tree, and escapes every ancestor scroll/clip region — window-clipped, not pane-clipped. `anchor-alignment="stretch"` widens it to at least the trigger's width (the select look).
278
310
  - **`on-dismiss` closes it model-side.** Escape and a click outside the menu dismiss the surface and dispatch the Msg; `close_repo_picker` clears the bool. Escape works even when the trigger took no focus (a plain-text crumb): with no relevant focus chain it dismisses the topmost mounted anchored surface. The engine hides the surface immediately (the optimistic echo), and the next rebuild's source tree is truth — a model that keeps `open` true gets it back. Clicking the TRIGGER while open never double-fires: the anchor region owns its surface's toggling, so only `toggle_repo_picker` dispatches.
279
311
  - **Items close on pick.** `pick_repo` sets the value AND clears the open flag — a click inside the surface never dismisses.
280
- - **Keyboard**: once focus is in the menu (tab into it), tab wraps inside the surface (the floating focus scope) and Enter/Space activate items; Escape dismisses from the trigger or the menu.
312
+ - **Keyboard**: ArrowDown/Up on a trigger with a mounted menu enters its selected visible row, or the first/last eligible row. Arrows move without wrapping; Home/End choose the visible edges. Enter/Space activate items. Tab/Shift+Tab dismiss without committing and return focus to the trigger; the next Tab continues through ordinary controls. Escape also dismisses from the trigger or menu and returns focus.
281
313
  - **Automation sees everything**: the floating menu and its items appear in widget snapshots at their real frames and `widget-click <item-id>` works while it is open.
282
314
 
283
- `combobox` composes the same way (the model filters the `for` source as the user types via `on-input`). The Zig mirror is `ElementOptions.anchor`/`anchor_alignment`/`anchor_offset` + `on_dismiss` on a `dropdown_menu` (or `popover`/`menu_surface`, which stay Zig-only) built with `ui.eachCtx` for the options. Budget: at most 16 anchored surfaces may be mounted per view (`max_canvas_widget_anchored_per_view`, loud `error.WidgetAnchoredSurfaceLimitReached`) — an `anchor` inside a `<for>` body is almost always a mistake.
315
+ `combobox` composes the same way (the model filters the `for` source as the user types via `on-input`). Markup also supports `<popover>` and `<menu-surface>` with the same anchor and dismissal attributes. The Zig mirror is `ElementOptions.anchor`/`anchor_alignment`/`anchor_offset` + `on_dismiss` on `dropdown_menu`, `popover`, or `menu_surface`, built with `ui.eachCtx` for the options. Budget: at most 16 anchored surfaces may be mounted per view (`max_canvas_widget_anchored_per_view`, loud `error.WidgetAnchoredSurfaceLimitReached`) — an `anchor` inside a `<for>` body is almost always a mistake.
284
316
 
285
317
  ### Splitters: split panes with a model-owned fraction
286
318
 
@@ -389,7 +421,7 @@ The `examples/feed` app is the reference: a 100,000-post deterministic MIXED-HEI
389
421
  Color and radius come from the design tokens, referenced by token NAME — literals only, no bindings, no raw colors (dynamic styling stays in Zig via `ElementOptions.style`):
390
422
 
391
423
  - Color attributes: `background`, `foreground`, `accent`, `accent-foreground`, `border-color`, `focus-ring`. Values are `canvas.ColorTokens` field names — the complete list: `background`, `surface`, `surface_subtle`, `surface_pressed`, `text`, `text_muted`, `syntax_plain`, `syntax_comment`, `syntax_keyword`, `syntax_literal`, `syntax_function`, `syntax_property`, `syntax_constant`, `border`, `accent`, `accent_text`, `destructive`, `destructive_text`, `success`, `success_text`, `warning`, `warning_text`, `info`, `info_text`, `focus_ring`, `shadow`, `scrim`, `disabled`. The `syntax_*` roles are the Geist Code Block palette used automatically by `ui.code` and Markdown fences in both built-in packs. `info` is the violet identity hue beside the status trio (merged PR badges, "new" chips). (`border-color`, not bare `border` — that name is reserved for a future width shorthand.)
392
- - `radius` — `canvas.RadiusTokens` field names: `sm`, `md`, `lg`, `xl`.
424
+ - `radius` — `canvas.RadiusTokens` field names: `sm`, `md`, `lg`, `xl`, `none`; `none` renders square corners.
393
425
 
394
426
  ```html
395
427
  <row background="surface" radius="md" padding="8">
@@ -397,7 +429,7 @@ Color and radius come from the design tokens, referenced by token NAME — liter
397
429
  </row>
398
430
  ```
399
431
 
400
- References resolve against the app's LIVE tokens on every rebuild (`finalizeWithTokens`), so a themed app (`tokens`/`tokens_fn`) re-resolves them when the theme changes — dark mode flips `surface` automatically. The DEFAULT theme follows the system appearance: an app that sets neither `tokens` nor `tokens_fn` derives the stock tokens from the OS light/dark setting (plus high-contrast and reduce-motion) and re-themes live when the user flips it. A TypeScript core may export `themeState(model: Model): ThemeState` (from `@native-sdk/core/events`) to derive optional `pack`, `colorScheme` (`light`/`dark`/`system`), and `accent` (`#rrggbb`) from model state. Omitted fields inherit app.zon, and omitted/system scheme follows the OS; high contrast still suppresses accents. `themePack(model)` remains supported for pack-only apps, but never export both. Pass explicit `tokens` for a fixed look, or `tokens_fn` for a fully model-owned custom palette; those complete-token paths take precedence over themeState. Forced scheme is canvas-token scope in v1 — native title bars and WebViews continue following the OS. An explicit `style` value set in Zig always wins over a token ref on the same field. Unknown token names and malformed model accents are validation errors.
432
+ References resolve against the app's LIVE tokens on every rebuild (`finalizeWithTokens`), so a themed app (`tokens`/`tokens_fn`) re-resolves them when the theme changes — dark mode flips `surface` automatically. The DEFAULT theme follows the system appearance: an app that sets neither `tokens` nor `tokens_fn` derives the stock tokens from the OS light/dark setting (plus high-contrast and reduce-motion) and re-themes live when the user flips it. A TypeScript core may export `themeState(model: Model): ThemeState` (from `@native-sdk/core/events`) to derive optional `pack`, `colorScheme` (`light`/`dark`/`system`), `accent` (`#rrggbb`), `highContrast`, and `reduceMotion` from model state. Omitted fields inherit app.zon, and omitted/system scheme follows the OS. Omitted accessibility flags follow the OS; explicit flags retain model appearance during replay. Effective high contrast suppresses accents. `themePack(model)` remains supported for pack-only apps, but never export both. Pass explicit `tokens` for a fixed look, or `tokens_fn` for a fully model-owned custom palette; those complete-token paths take precedence over themeState. Forced scheme is canvas-token scope in v1 — native title bars and WebViews continue following the OS. An explicit `style` value set in Zig always wins over a token ref on the same field. Unknown token names and malformed model accents are validation errors.
401
433
 
402
434
  One Zig-only style knob rides beside the tokens: `ElementOptions.style = .{ .quiet_hover = true }` silences a pressable surface's pointer HOVER wash only — press and selection fills, the focus ring, cursor intent, and hit testing stay — for image-forward content tiles (cover art, photo cards) where the pointer rests on content rather than a control register. Acting controls (list rows, menu items, buttons, tab triggers) keep their washes: there the hover fill IS the affordance.
403
435
 
@@ -936,7 +968,7 @@ export type Msg = /* ... */ | {
936
968
  export const chromeMsg = "chrome_changed";
937
969
  ```
938
970
 
939
- Handle that arm by storing `msg.insets.left` and `Math.max(headerNaturalHeight, msg.insets.top)` in fields such as `chromeLeading`/`headerHeight`; markup binds those exact TypeScript spellings (`<spacer width="{chromeLeading}" />`). `examples/system-monitor-ts` is the complete reference. In a Zig core, the equivalent hook is `Options.on_chrome: fn (platform.WindowChrome) ?Msg`, with snake-case bindings such as `{chrome_leading}` when the Zig model uses those names.
971
+ Handle that arm by storing `msg.insets.left` and `Math.max(headerNaturalHeight, msg.insets.top)` in fields such as `chromeLeading`/`headerHeight`; markup binds those exact TypeScript spellings (`<spacer width="{chromeLeading}" />`). `examples/system-monitor` is the complete reference. In a Zig core, the equivalent hook is `Options.on_chrome: fn (platform.WindowChrome) ?Msg`, with snake-case bindings such as `{chrome_leading}` when the Zig model uses those names.
940
972
 
941
973
  macOS-first like `resizable = false`: GTK/Win32 keep standard chrome and the whole channel is harmless there. Full retrofit: `examples/markdown-viewer` (tall band; toolbar row is the drag region and tracks the band height). Tests: the null platform records `startWindowDrag` calls (`window_drag_starts`), per-window `window_titlebar`, and serves settable `window_chrome` (insets + buttons frame).
942
974
 
@@ -979,6 +1011,16 @@ The view binds that model-owned id in either tier; `0` is the no-image sentinel
979
1011
  <avatar image="{avatar}" label="Octocat">OC</avatar>
980
1012
  ```
981
1013
 
1014
+ Compiled TypeScript views also accept canonical unsigned decimal `Uint8Array`
1015
+ identity bytes, through max-u64. Keep exact restored/native identities in that
1016
+ representation instead of converting them to `number`. The view validates the
1017
+ bytes and sends two exact u32 words to native storage. An image leaf accepts
1018
+ `fit="stretch|contain|cover"`; the default is stretch and avatars use cover.
1019
+ Compiled views support per-side `padding-top`, `padding-bottom`, `padding-left`
1020
+ and `padding-right` over the uniform `padding` value. Color-token and radius
1021
+ attributes may bind a closed string-literal union of their supported tokens;
1022
+ the compiler rejects arbitrary text and unsupported members.
1023
+
982
1024
  One registered image can be a texture atlas. The source rectangle uses
983
1025
  decoded-image pixel coordinates; declare all four markup attributes, or set
984
1026
  the equivalent `ElementOptions.image_src` `geometry.RectF` in a Zig view.
@@ -1074,7 +1116,7 @@ When the same subtree repeats with different data (board columns, dashboard sect
1074
1116
 
1075
1117
  Rules and semantics:
1076
1118
 
1077
- - A template takes `name` (kebab-case), optional `args` (space-separated names, each optionally `name=default`), and exactly one element child. `<use template="name">` is allowed anywhere an element is (including as a `for` child or the view root); its other attributes must match the template's `args` exactly — missing args without a default and extra args are errors.
1119
+ - A template takes `name` (kebab-case), optional `args` (space-separated names, each optionally `name=default`), and exactly one element child. `<use template="name">` is allowed anywhere an element is (including as a `for` child or the view root); its value attributes must match the template's `args` exactly — missing args without a default and extra args are errors. A use may additionally carry `on-press`, which forwards one typed message (including a use-site payload binding) to the expanded root.
1078
1120
  - Arg defaults are LITERALS only (`args="title trend=flat count=0"`): a default evaluates in no scope, so `{binding}` defaults are errors. A use site may omit any defaulted arg. `args="name="` declares an EMPTY-STRING default; defaults are unquoted — quotes in a default would be literal characters, so a quoted default (`name='x'`) is a teaching error.
1079
1121
  - The template body is built IN PLACE of the `<use>`: structural widget ids hash through the parent chain at the expansion site, exactly as if you had written the body inline. Two uses at different sites get different ids; the same site is stable across rebuilds. Rewriting copy-pasted markup as a template does not change any widget id.
1080
1122
  - Args bind like `for` variables: an arg whose value is a `{binding}` naming an iterable (model slice/array field, pub decl, or model fn — the same set `for each` accepts) is iterable inside the template (`<for each="cards" ...>`); any other arg (literal or scalar binding) is a value usable in bindings, interpolation, and equality (`{title}`, `label="{title}"`). Args are evaluated at the use site; inside the body only the args, the model, and the body's own loop variables are in scope. Value args are scalars — `{arg.field}` is an error.
@@ -1082,7 +1124,7 @@ Rules and semantics:
1082
1124
  - SLOTS: a template body may contain one `<slot/>` (attribute-less, childless; named slots do not exist). The `<use>` site's children build IN THE CONSUMER'S SCOPE — they see the model paths and loop variables where the use is written — and land at the slot's position; ids hash as if inlined. A use with no children renders the slot empty; children on a slotless template are an error; a `<slot/>` inside use-site children (forwarding) is an error.
1083
1125
  - IMPORTS: `<import src="components/cards.native"/>` lines go at the very top of a file, before its templates. Paths are relative to the importing file (subdirectories and transitive imports fine, always under the root view file's directory — absolute paths and escapes are errors). An imported file defines templates ONLY (a component file; a view root inside one is an error, and a component file checks standalone). Importing splices the file's templates (transitively) BEFORE yours, in import order — as if pasted at the import site — so define-before-use stays the only ordering rule. Cycles are reported with the cycle path; duplicate template names are an error naming both definition sites.
1084
1126
 
1085
- Both engines implement templates, defaults, slots, and imports: the interpreter expands at build time (hot reload re-resolves imports from disk, so edits to imported files reload), and the compiled engine inlines at comptime with the identical result. A document with imports compiles through `canvas.CompiledMarkupImports(Model, Msg, "root.native", &sources)` where `sources` is a `canvas.ui_markup.SourceFile` set (`.{ .path = "components/cards.native", .source = @embedFile("components/cards.native") }`, paths relative to the root file's directory); pass the same set on `MarkupOptions.sources` for the runtime engine. See `examples/kanban/src/board.native` + `examples/kanban/src/components/board-column.native`.
1127
+ Both engines implement templates, defaults, slots, and imports: the interpreter expands at build time (hot reload re-resolves imports from disk, so edits to imported files reload), and the compiled engine inlines at comptime with the identical result. A default TypeScript app's generated launcher discovers every component `.native` file under `src/`, embeds the same source set for both engines, and wires it on desktop and mobile. The main view can import anywhere under `src/`; secondary-window roots remain under `src/windows/`. Lower-level wiring compiles an imported document through `canvas.CompiledMarkupImports(Model, Msg, "root.native", &sources)` and passes the same `canvas.ui_markup.SourceFile` set on `MarkupOptions.sources`. See `examples/kanban/src/app.native` + `examples/kanban/src/components/board-column.native`.
1086
1128
 
1087
1129
  ## Code in markup: `<code>`
1088
1130
 
@@ -1140,7 +1182,7 @@ Three composites for pipeline/run UIs — pure compositions of existing widgets
1140
1182
 
1141
1183
  ## Charts
1142
1184
 
1143
- `<chart>` is the data-visualization composite: `<series>` children bind model `[]const f32` iterables and draw through the vector path pipeline with token colors — charts retheme with the palette, repaint exactly when their data changes (value equality, not identity), and report series semantics to automation. Both engines lower it through `ui.chart`, so markup charts and Zig charts are pixel- and semantics-identical.
1185
+ `<chart>` is the data-visualization composite: `<series>` children bind model `[]const f32` iterables and draw through the vector path pipeline with token colors — charts retheme with the palette, repaint exactly when their data changes (value equality, not identity), and report series semantics to automation. The interpreted, native-compiled and scriptc-compiled markup paths preserve the same chart data, pixels and semantics as `ui.chart`.
1144
1186
 
1145
1187
  ```html
1146
1188
  <!-- Star-history: cumulative stars per repo. 10k-point series are fine —
@@ -1285,3 +1327,20 @@ For scripted checks (and the CI workflow `native init --full` scaffolds), replac
1285
1327
  native automate assert 'gpu_nonblank=true' 'role=button name="Reset"' 'count: 0'
1286
1328
  native automate assert --absent 'error event='
1287
1329
  ```
1330
+
1331
+ ## Compiled inline typography
1332
+
1333
+ A text paragraph can contain ordered `span` leaves. Each leaf supports `weight="regular|medium|bold"`, `mono`, `italic`, `underline`, a positive `scale`, and a foreground color token. Use `text-alignment="start|center|end"` on the paragraph. Layout, keys, semantics, and events belong on the enclosing text element. The compiler preserves one separating space between whitespace-separated runs and keeps punctuation adjacent. Spans cannot contain nested elements or several comment-separated text runs.
1334
+
1335
+ ```xml
1336
+ <text size="display" text-alignment="end" label="{readout}">
1337
+ <span mono="true" weight="medium">{readout}</span>
1338
+ </text>
1339
+ ```
1340
+
1341
+ Text-entry controls also accept `border-color` tokens, including `background` for a field that blends into the surrounding surface.
1342
+
1343
+
1344
+ ## Compiled playback views
1345
+
1346
+ TypeScript apps support `<video src="{opened}" controls="true" grow="1" label="Clip"/>` for house transport chrome and `<media-surface surface="{surface}" grow="1" label="Frames"/>` for app-owned controls. The scriptc view receives explicit playback state for each build, including secondary windows; it composes the transport widgets without mutable global view context. Native code supplies decoded textures and the current playback capability. Dynamic icons bind a closed string-literal union such as `"play" | "pause"`. The Video Player example demonstrates both playback styles.
@@ -19,7 +19,7 @@ native check # subset-check core.ts + validate markup + app.json/app.zon
19
19
  native build # ReleaseFast binary; native test runs the app's tests
20
20
  ```
21
21
 
22
- The complete reference app in this idiom is `examples/soundboard-ts` in the SDK repo: the soundboard music library as three files and zero Zig — const catalog tables, REAL audio through the `Cmd.audioPlay` stream, scrub-to-seek on a markup slider, a motion-gated `Sub.timer` playback clock, the full text-edit engine on a search field, controlled scroll, registered cover assets, the width-adaptive grid through the frame channel, clipboard, and context menus, with an end-to-end suite driving the shipping markup.
22
+ The complete reference app in this idiom is `examples/soundboard` in the SDK repo: the soundboard music library as three files and zero Zig — const catalog tables, REAL audio through the `Cmd.audioPlay` stream, scrub-to-seek on a markup slider, a motion-gated `Sub.timer` playback clock, the full text-edit engine on a search field, controlled scroll, registered cover assets, the width-adaptive grid through the frame channel, clipboard, and context menus, with an end-to-end suite driving the shipping markup.
23
23
 
24
24
  ## The contract
25
25
 
@@ -46,6 +46,10 @@ export function update(model: Model, msg: Msg): Model {
46
46
  - Update-only state (fields, helpers, or Msg kinds nothing in markup binds or dispatches — host-fired timer arms, persistence bookkeeping) is declared once: `export const viewUnbound = ["nextId", "tick"] as const;`. It emits as the `view_unbound` opt-out `native check`'s unbound-state lint reads; a name outside the model surface is a taught NS1032. Entries are the TypeScript names exactly as declared (`"nextId"`) and Msg kinds as their `kind` tags — the same names markup binds, because there are no other names.
47
47
  - Names: your names are your names — fields, helpers, and locals emit into Zig with their TS spellings (`doneToday` stays `doneToday`), and markup binds them verbatim. String-literal unions emit as native enums.
48
48
 
49
+ ## Tests against the compiled app
50
+
51
+ Put Node test files directly in `tests/*.test.ts` and run `native test`. Import `NativeApp` and `findWidget` from `@native-sdk/core/testing` **only in tests**, never in `src/core.ts`. Each `NativeApp.start()` launches a separate headless native process with the real scriptc-compiled core and markup. Drive `click`/`action`/`menu`, assert returned model and accessibility snapshots, inspect and answer fake requests with `respond`, and fire declared timers with `fireTimer`. Supply explicit declared launch values with `NativeApp.start({ environment: [{ name: "APP_MODE", value: "manual" }] })`; they are journaled and replay does not read ambient environment. Framework app directories still use `appDataDirectory`. Always `close()` in `finally` or use `await using`. `verifyReplay()` verifies checkpoints and the final model in a fresh runtime; afterward only snapshot/close are allowed. Model bytes are JSON number arrays; native identities are decimal strings. The host uses a fixed clock and fake effects, without production persistence/services/app-data startup. See https://native-sdk.dev/docs/testing for the complete API and limits.
52
+
49
53
  ## The arena mental model
50
54
 
51
55
  Everything `update` builds lives in a per-dispatch bump arena that is freed wholesale after the returned model is committed, so spreads, `map`, and `filter` are cheap by construction. At commit, only nodes your update actually created are copied into the persistent model heap — everything you spread through unchanged is shared with the previous model for free.
@@ -167,16 +171,38 @@ Four effect families deliver MANY results from one command — a keyed stream th
167
171
  - `Cmd.audioPause(key)` / `Cmd.audioResume(key)` / `Cmd.audioStop(key)` / `Cmd.audioSeek(key, ms)` / `Cmd.audioSetVolume(key, volume)` — fire-and-forget control verbs: no result of their own; their consequences arrive on the event stream (`audioResume` on a dead player reports one `"failed"` event, never silence). A verb whose key names no open stream is a no-op. `audioStop` is the audio stream's close — no events for the key after it (`Cmd.cancel` does not apply to audio). Volume is clamped 0..1 and remembered across tracks; a literal outside 0..1 (or a negative seek literal) stops the build (NS1030).
168
172
  - `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb — compiled cores are single-threaded, so the core opens, closes, and receives while the posting handle lives on the native side (`Effects.channelHandle(key)`). `key` may be any number expression, a positive integer below 2^53 (a certain-to-be-refused literal stops the build, NS1030). The `event` arm is a five-field record matched by NAME: `key` (the channel key echoed verbatim, so concurrent channels sharing one arm stay distinguishable; a key the wire cannot carry exactly echoes 0), `state` (the `ChannelState` union — import it from `@native-sdk/core` or declare an alias with exactly the three members `"data" | "closed" | "rejected"` in any order; checked BOTH directions, since a narrower union would silently drop states the host emits), `bytes` (`Uint8Array` — the post's payload on `"data"` events, empty otherwise), and `droppedPending`/`droppedTotal` (numbers — the honest back-pressure counters: posts the native handle refused since the previous delivered event, and over the channel's whole life; refused posts count, never silence). One channel per key at a time — a duplicate live key dispatches `"rejected"` — and the key shares the engine's effect-key space (a same-key fetch is blocked while the channel lives). No timer polling anywhere: the source wakes the loop itself. Channel events journal at the effect boundary, so recorded sessions replay the whole stream from the journal — the native posting side is never needed at replay (a native producer that consults `ChannelHandle.live()` before launching keeps replay fully offline; one that launches unconditionally is stopped at its first post, which answers `.closed`).
169
173
  - `Cmd.channelClose(key)` — close the open channel under the key, if any: staged posts flush, exactly one `"closed"` event (final drop totals aboard) dispatches the event arm, and the key frees. A key with no open channel no-ops.
174
+ - `Cmd.channelOpenSource(key, source, payload, { event, started })` opens a channel and starts an explicit native producer only for that newly accepted occupancy. The `started` arm has exactly `key: number`, `state: "started" | "skipped" | "failed"`, and `bytes: Uint8Array`; it runs in command order before the settled view. A refused open skips startup and still delivers the ordinary channel rejection. Startup failure carries the native error name; close that channel with `Cmd.channelClose`. Source names are 1–255 UTF-8 bytes and arguments at most 4096 bytes. The built-in `"native-sdk.process.samples"` source takes empty arguments and posts process readings every 500 ms. Native embedders can inject `Effects.channel_sources`; starters copy borrowed arguments before returning and must be quick and nonreentrant. Native recording journals startup results and replay never invokes the producer. The fake and virtual hosts report `UnsupportedChannelSource` unless a native test injects a starter; virtual-host recording of external producers requires the native runtime. See `examples/channel-monitor`.
170
175
  - `Cmd.audioCaptureStart(key, { source, sampleRate?, channels? }, { event })` — start a native `"microphone"` or `"system"` audio stream. The host converts into interleaved signed-16 little-endian PCM at 16/24/48 kHz and mono/stereo (default 48 kHz mono), in chunks no larger than 20 ms. The ten-field event arm is matched by NAME: `key`, `state` (exactly `"started" | "data" | "failed" | "stopped" | "rejected"`), `source` (exactly `"microphone" | "system"`), `sampleRate`, `channels`, `timestampMs`, `frames`, `pcm`, `droppedPending`, and `droppedTotal`. PCM is dispatch-lifetime bytes; the commit walker copies it when stored in the model. The bounded queue, wake behavior, drop accounting, journaling, and offline replay are the channel transport's. Microphone and system may run concurrently; a second start for one source replaces that source's prior key.
171
176
  - `Cmd.audioCaptureStop(key)` — synchronously quiesce native callbacks, flush already accepted chunks, deliver exactly one `"stopped"` terminal, and free the key. The key remains occupied until that terminal is delivered, so wait for `"stopped"` before reusing it; an earlier restart is rejected. A missing key no-ops. Declare `"microphone"` and/or `"system_audio"` in `app.zon` permissions so macOS dev executables and packaged apps carry the required usage descriptions.
172
177
  - `Cmd.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the actual registered dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). The default registry has 16 slots and a 1 MiB decoded-pixel target per slot: platform codecs downscale photo-size sources at decode time, preserving aspect, instead of rejecting them. Image-centric apps may declare `.images = .{ .max_image_pixel_bytes = 8388608 }` in app.zon (1–8 MiB accepted); allocation stays lazy per used slot, but filling 16 ceiling-sized slots is a declared 128 MiB high-water. Encoded sources have their own flat 8 MiB bound; only over-bound source bytes report `"too_large"` in normal operation, never a cut decode. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
173
178
 
179
+ ### Complete capability results and playback snapshots
180
+
181
+ `Cmd.spawnEvents(argv, { key?, stdin?, collect?, line?, exit })` routes every native subprocess field. Its line arm has `key: Uint8Array`, `line: Uint8Array`, `truncated: boolean`, and `droppedBefore: number`. Its exit arm has `key`, `code`, `reason` (`"exited" | "signaled" | "cancelled" | "rejected" | "spawn_failed"`), `droppedLines`, `output`, `outputTruncated`, `stderrTail`, and `stderrTruncated`. Bytes and booleans retain their ordinary types; counts and code are numbers. Duplicate pending keys reject without cancelling the original stream. Cancellation supplies the complete cancelled terminal.
182
+
183
+ `Cmd.spawnEventsExact(key, argv, { stdin?, collect?, line?, exit })` uses the same complete result arms with an exact native identity: `key` is canonical unsigned decimal ASCII bytes, from `"0"` through `"18446744073709551615"`. The native engine owns request copying, duplicate-key refusal, cancellation and terminal delivery; each refused request retains its own route while the original child continues. Empty argv, more than 16 arguments, over-bound argument bytes or stdin produce the ordinary rejected terminal. The command wire carries at most 255 argument entries. `Cmd.cancelExact(key)` cancels by that exact native identity and retains the ordinary terminal route. Malformed identities trap before an engine call.
184
+
185
+ `Cmd.clipboardWriteResult(bytes, { key?, result })` routes a complete arm with `key`, `operation` (`"read" | "write"`), `outcome` (`"ok" | "failed" | "rejected" | "cancelled"`), `text`, and `droppedBefore`. It preserves rejection and cancellation rather than dropping completion. `Cmd.clipboardWrite` remains the fire-and-forget form.
186
+
187
+ `Cmd.videoSnapshot({ snapshot })` captures current playback state when the command is issued and replies within the same dispatch, in command order like `Cmd.now`. Its arm carries `key: Uint8Array`, `active`, `surface`, `playing`, `buffering`, `completed`, `looping`, `muted`, `source` (`"local" | "stream"`), `positionMs`, `durationMs`, `width`, `height`, and `volume`. Flags are booleans and numeric mirrors are numbers. The key is empty when the playback belongs to another owner. `Cmd.videoRestart(key)` restarts completed playback and retains ownership for later keyed commands. See `examples/effects-probe` and `examples/video-player` for complete cores and views.
188
+
189
+ `Cmd.wallTime(msgKind)` supplies the journaled signed-i64 wall clock as canonical decimal bytes, preserving values outside the exact JavaScript-number range. Use a single-byte-payload arm.
190
+
191
+ `Cmd.readFileResult(path, { key?, result })` and `Cmd.writeFileResult(path, bytes, { key?, result })` supply the full file terminal: `key`, `operation`, `event`, `outcome`, `bytes`, `totalBytes`, `mtimeMs`, `exists`, and `droppedBefore`. Import `FileResultArm` for the complete shape. Totals and signed modification times are canonical decimal bytes. Named requests replace earlier requests and cancel silently; unrelated live capability owners and full tables return a complete `"rejected"` record. The virtual host returns explicit refusals because it performs no ambient filesystem IO.
192
+
193
+ `Cmd.host("native-sdk.debug.log", bytes)` writes up to 4096 raw bytes to native stderr for cadence diagnostics. The fake executor and replay suppress the send; it adds no effect journal record.
194
+
195
+ `Cmd.timerResult(key, afterMs, "one_shot" | "repeating", { result })` supplies `key: Uint8Array`, `timestampNs: Uint8Array`, and `outcome: "fired" | "rejected"`. `Cmd.timerResultExact` accepts canonical unsigned decimal ASCII bytes for the interval, through `18446744073709` ms (the native nanosecond conversion limit). Zero, malformed values, and larger intervals deliver the rejected terminal. Ordinary number timers retain their one-year bound. Repeating timers stay armed after a fire; rearming replaces the same key; cancellation is silent. Rejection includes the requested key. See `examples/notes` for persistence coalescing and relative-time refresh.
196
+
197
+ `commandMsg` may accept a `string` or `Uint8Array`; the checked contract selects the matching command ABI. Byte input preserves the command spelling without an ASCII conversion.
198
+
174
199
  ### The window verbs
175
200
 
176
201
  The menu-bar lifecycle verbs are fire-and-forget, with no result Msg (the window's own frame event carries visibility state):
177
202
 
178
203
  - `Cmd.showWindow(label)` — un-hide + activate the window with the declared label (a string literal — window labels are declarations, in `app.zon` or a `windows_fn` descriptor): the counterpart to a `close_policy = "hide"` close and the tray "Open" consequence; also restores a minimized window. An unknown label is a no-op.
179
204
  - `Cmd.hideWindow(label)` — order a live window out without closing it; native identity and views remain, and `showWindow` is the inverse.
205
+ - `Cmd.closeWindow(label)` / `Cmd.minimizeWindow(label)` — perform the native close or minimize action for an app-drawn window control. Close follows the window's ordinary policy, including normal shutdown when the last window closes. Unknown labels no-op; the fake executor retains complete request counters and copied labels. Model-declared secondary windows usually close by removing their descriptor.
180
206
  - `Cmd.setDockPresence(visible)` — on macOS, switch between a regular Dock/app-switcher app and accessory/headless behavior; unsupported hosts ignore it.
181
207
  - `Cmd.quitApp()` — the graceful terminate, and the tray "Quit" consequence: the host quits through the SAME shutdown path a last-window close takes, so the stop hook runs exactly once and a recording session seals its journal.
182
208
 
@@ -217,7 +243,7 @@ Commands are constructed inline in the return path and nowhere else (NS1017): ne
217
243
 
218
244
  Export `windows(model): readonly WindowDescriptor[]` to derive the secondary windows that should exist from committed model state. Import `WindowDescriptor` from `@native-sdk/core/events`, and construct entries with `windowDescriptor` from `@native-sdk/core` so omitted fields receive the canonical defaults. Presence is liveness: adding a descriptor creates the window, removing it closes the window and releases its retained view.
219
245
 
220
- Each possible label has a statically compiled Native markup view at `src/windows/<label>.native`; for example descriptor label `settings` uses `src/windows/settings.native`. Spell that identity directly inside the canonical constructor as `label: asciiBytes("settings")`: window labels are static declarations, and `native check`/every build reject a dynamic label or one whose root file is missing. Window roots may import shared components nested under `src/windows/` with the ordinary `<import>` syntax; the generated launcher embeds and hot-reloads the full import closure. The descriptor's `canvasLabel` must be unique across the whole app. Both the main view and every open window view rebuild from the same model after a Msg.
246
+ Each possible label has a statically compiled Native markup view at `src/windows/<label>.native`; for example descriptor label `settings` uses `src/windows/settings.native`. Spell that identity directly inside the canonical constructor as `label: asciiBytes("settings")`: window labels are static declarations, and `native check`/every build reject a dynamic label or one whose root file is missing. Window roots may import components nested under `src/windows/` with the ordinary `<import>` syntax. The main `src/app.native` view can import component files anywhere under `src/`; the generated launcher embeds both source sets and hot-reloads each imported closure. The descriptor's `canvasLabel` must be unique across the whole app. Both the main view and every open window view rebuild from the same model after a Msg.
221
247
 
222
248
  ```ts
223
249
  import { asciiBytes, windowDescriptor } from "@native-sdk/core";
@@ -245,6 +271,12 @@ export function windows(model: Model): readonly WindowDescriptor[] {
245
271
 
246
272
  `titlebar` accepts `"standard"`, `"hidden_inset"`, `"hidden_inset_tall"`, and `"chromeless"`. The last removes all OS chrome and is required when a transparent model-declared window targets Windows; provide working app-drawn close/minimize controls for that fully skinned shape.
247
273
 
274
+ ### Model-declared WebView panes
275
+
276
+ Export `webPanes(model: Model): readonly WebViewPane[]` from `core.ts`, importing `WebViewPane` from `@native-sdk/core/events`. Each descriptor supplies byte `label` and `url`, nullable byte `anchor`, numeric `x`, `y`, `width`, `height`, and `reloadToken`. The label names an existing manifest WebView parented to the canvas. An anchor names a canvas widget's semantics label and uses its measured bounds; `anchor: null` uses the explicit frame. A URL change navigates, and a token change reloads.
277
+
278
+ The adapter copies helper-result bytes into native-owned storage before OS reconciliation. It consumes the first four descriptors in declaration order. Labels are bounded to 64 bytes, anchors to 256 bytes, and URLs to the platform's URL budget. Geometry must fit finite f32 canvas points; dimensions are nonnegative. Reload tokens are nonnegative safe integers. Navigation still obeys manifest origin policy. Panes reconcile after rebuild and presentation; they do not create WebViews or bypass OS policy.
279
+
248
280
  ### The init command
249
281
 
250
282
  `initialModel` may return the same pair to run a boot effect once at install, before the first view build — loading a store is the canonical use:
@@ -294,10 +326,33 @@ One caveat for node-side pokes: the build resolves the `@native-sdk/core*` speci
294
326
  - **`src/` is the boundary**: `../` escapes and absolute paths are taught (NS1034); bare npm specifiers are taught (NS1035 - vendor the code under `src/` or make the import `import type`). Only `@native-sdk/core` (the intrinsic Cmd/Sub/asciiBytes/utf8Bytes surface) and the SDK library modules below carry runtime meaning from outside.
295
327
  - **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the compile uniques them per module).
296
328
  - **No runtime import cycles** (NS1036). `import type` back-edges are legal and idiomatic: a helper module type-imports `Model` from `./core.ts` while `core.ts` runtime-imports the helpers - that is the expected shape, not a smell.
297
- - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), the model-derived launcher helpers (`themeState`/`themePack`/`statusItem`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
329
+ - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), the model-derived launcher helpers (`themeState`/`themePack`/`statusItem`/`webPanes`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
298
330
  - **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`, `AudioCaptureState`/`AudioCaptureSource`/`AudioCaptureEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
299
331
 
300
- The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/chatbot` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
332
+ The reference splits are `examples/soundboard` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/chatbot` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
333
+
334
+ ## Windowed lists
335
+
336
+ Use `VirtualListRange` from `@native-sdk/core/events` for a Model-first row query. Export `rows(model: Model, range: VirtualListRange): readonly Row[]`; return exactly the rows from `start_index` through the exclusive `end_index`. Every row needs one keyed root. The range also includes first/last visible indices, item extent/gap, scroll/layout offsets, total content extent, before/after extents, and anchor extent. Geometry remains fractional.
337
+
338
+ ```html
339
+ <virtual-window id="items" as="window" item-count="{count}"
340
+ item-extent="40" overscan="4" viewport-fallback="600">
341
+ <column>
342
+ <virtual-list window="window" each="rows" as="row" grow="1"
343
+ label="Items" on-reach-end="load_more">
344
+ <list-item key="{row.id}">{row.title}</list-item>
345
+ </virtual-list>
346
+ <status-bar>{window.first_visible_index}–{window.last_visible_index}</status-bar>
347
+ </column>
348
+ </virtual-window>
349
+ ```
350
+
351
+ For variable row heights, replace `item-extent` with `extent-estimate="estimate"`, where `estimate(model: Model, index: number): number` returns a nonnegative finite estimate. The native capability owns measurement, scrolling, retained corrections, and viewport resolution; compiled TypeScript owns row selection and markup composition. Estimates retain only a stable helper identity. They never hold a model pointer or result-arena memory. Supply cheap estimates without constructing rows.
352
+
353
+ Each window requires exactly one list, declarations cannot nest, and a view supports eight windows. A template may receive a complete window binding and forward it to another template. Counts and logical indices are nonnegative safe integers; extent values must fit finite f32 points. Return no rows for an empty range. See `examples/feed` for variable-height authoring and persistent row interaction state.
354
+
355
+ Exported Model-first helpers may take additional explicitly typed, fixed-arity parameters. Their complete parameter tuples cross the canonical helper ABI, including nested records, optionals, slices, integer obligations, and fractional fields. Ordinary `{helper}` bindings continue to use helpers with only the Model parameter; windowed row queries receive their range through `<virtual-list>`. Shell conventions such as `windows`, `statusItem`, and `webPanes` retain their documented single-Model signature.
301
356
 
302
357
  ## Text is bytes
303
358
 
@@ -396,10 +451,17 @@ export type Msg = /* ... */ | { readonly kind: "library_scrolled"; readonly scro
396
451
  The generated wiring detects each channel from an export (export exists → wired; a wrong shape is a taught NS1033). Event records are matched by field name, STRUCTURALLY: import them from `@native-sdk/core/events` (`FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`, `ChromeInsets`/`ChromeButtons`) or declare the same shapes in your core — both emit as your module's types and match identically. The `appearanceMsg`/`chromeMsg` arms themselves stay inline union members (`kind` plus the event's fields — the subset has no intersection arms); the SDK's `AppearanceEvent`/`ChromeEvent` records are those arms' canonical payload shapes, importable for helper signatures.
397
452
 
398
453
  - **`commandMsg(name: string): Msg | null`** — menus, shortcuts, and chrome tabs, by command id (string equality works on `string` values).
454
+ - **`windowContext(model: Model, label: Uint8Array): WindowContextMsg | null`** — source-window identity before a window's input or command message. The label is the exact live window label; GPU frames do not change input ownership. Return a dedicated kind-discriminated subset of `Msg` with matching payloads, or null when the owner already matches. Handle this context message without effects so the corresponding input owns one command batch.
399
455
  - **`statusItem(model: Model): StatusItemState` / `statusItems(model: Model): readonly StatusItemDescriptor[]`** — one complete menu-bar item, or a stable-id collection. Presentation includes generic title typography. Dropdown rows include a typed `metric` block, typed segmented options, and bounded chart data; never encode these as text conventions. The generated launcher reconciles after committed updates.
400
- - **`themeState(model: Model): ThemeState`** — the stock theme's model-owned pack, color scheme, and accent. Import `ThemeState` from `@native-sdk/core/events`; each field is optional (`pack`, `colorScheme`, `accent`). Omit a field to inherit app.zon, use `colorScheme: "system"` (or omit it) to follow the OS, and spell accents exactly `#rrggbb`. High contrast/reduced motion remain system-owned and high contrast suppresses accents. `themePack(model)` remains the pack-only compatibility helper; export one or the other, never both. Complete `tokens_fn`/`tokens` wiring takes precedence. Forced scheme applies to canvas tokens in v1; native chrome and WebViews remain OS-themed.
456
+ - **`tokenOverrides(model: Model): ThemeDesignTokenOverrides`** — model-derived colors, typography, spacing, geometry, controls, and motion over the selected stock theme. Import the complete optional record from `@native-sdk/core/theme`; omitted members inherit the resolved stock register. Colors use normalized RGBA. Numbers cross the helper ABI as f64; native registration validates font ids and ranges and explicitly converts GPU values to f32. The runtime stamps device scale and installs its layout policies after applying the overrides. Full native `tokens`/`tokens_fn` configurations retain precedence.
457
+ - **`assets.fonts` in the manifest** — declare bundled TrueType faces as `{ "id": 64, "path": "assets/mono.ttf" }`. Ids start at 64 and remain permanent; at most eight faces register before the first layout. Reference their ids through `tokenOverrides` typography. Missing, oversized, or invalid files fail startup. The same asset tree is included in packaging.
458
+ - **`themeState(model: Model): ThemeState`** — the stock theme's model-owned pack, color scheme, and accent. Import `ThemeState` from `@native-sdk/core/events`; each field is optional (`pack`, `colorScheme`, `accent`, `highContrast`, `reduceMotion`). Omit a field to inherit app.zon, use `colorScheme: "system"` (or omit it) to follow the OS, and spell accents exactly `#rrggbb`. Omitted `highContrast`/`reduceMotion` follow the OS; explicit values retain model-owned appearance during replay. Effective high contrast suppresses accents. `themePack(model)` remains the pack-only compatibility helper; export one or the other, never both. Complete `tokens_fn`/`tokens` wiring takes precedence. Forced scheme applies to canvas tokens in v1; native chrome and WebViews remain OS-themed.
459
+ - **`webPanes(model: Model): readonly WebViewPane[]`** — model-declared geometry, URL, and reload state for existing scene WebViews; see Model-declared WebView panes.
401
460
  - **`windows(model: Model): readonly WindowDescriptor[]`** — the model-declared secondary-window set. The launcher compiles `src/windows/<label>.native`, reconciles descriptor presence after committed updates, projects `closePolicy`, and routes a `.quit` `onCloseCommand` through `commandMsg`.
402
- - **`frameMsg(model: Model, frame: FrameEvent): Msg | null`** — presented frames. `FrameEvent` is exactly `{ width, height, timestampMs, intervalMs }` numbers (canvas points; fractional milliseconds). Return null for frames that change nothing — the idle law holds exactly when an idle app dispatches nothing (a frame arm that always returns a Msg would spin the loop at full frame rate). The installing frame is excluded; the first PRESENTED frame corrects any seeded value.
461
+ - **`frameMsg(model: Model, frame: FrameEvent): Msg | null`** — presented frames. `FrameEvent` carries `{ width, height, timestampMs, intervalMs }` numbers (canvas points; fractional milliseconds) plus `timestampNs` and `intervalNs` as exact decimal ASCII bytes. Use the byte clocks for nanosecond-sensitive animation; converting the fractional-millisecond number back loses large-u64 precision. Existing structural four-number events remain supported. Return null for frames that change nothing — the idle law holds exactly when an idle app dispatches nothing. The installing frame is excluded.
462
+
463
+ For native audio identity parity, return `Cmd.audioPlayExact(key, source, { event: "audio_event" })` from `update`. The key is canonical unsigned decimal bytes through max-u64. Its event arm has exactly `key`, `state`, `positionMs`, `durationMs`, `playing`, `buffering`, and `bands`; the key and both counters are bytes, the flags are booleans, and `state` uses all six `AudioState` members. Import `ExactAudioEvent` from `@native-sdk/core/events` for helper signatures. Native copies every report into the dispatch arena, and committed model storage owns retained data. Deferred rejections/failures retain their original route and key across replacement; source rejection preserves the prior player. Existing native event admission bounds apply. `cacheDir` derives a content-addressed URL cache path when `cachePath` is empty; omitting both disables caching. `Cmd.audioTransport` controls the single player with `pause`, `play` (resume), `stop`, `seek` (decimal-byte `positionMs`), or `volume` (numeric `value`); volume is remembered even while idle. Commands remain inline in `update`'s return.
464
+ - **`layoutTweens(model: Model): readonly LayoutTween[]`** — runtime-driven split animation targets. Import `LayoutTween` from `@native-sdk/core/events`; provide nullable byte `label`, zero-based split occurrence `index`, target fraction `to`, integer `durationMs`, and `easing` (`linear`, `standard`, `emphasized`, `spring`). `label: null` selects among all splits; otherwise `index` selects among exact matching labels in tree order. Native resolves widget identities and retains animation storage; the core derives targets. Invalid descriptors are ignored, the first declaration for an id wins, and output respects the runtime tween budget. Reduced motion snaps through the existing runtime primitive.
403
465
  - **`keyMsg(key: KeyEvent): Msg | null`** — the app-level key FALLBACK (a focused widget's own keys and editable text always win first). `KeyEvent` is exactly `{ key: string; shift: boolean; control: boolean; alt: boolean; super: boolean }`; the key NAME arrives lowercased (`key.key === "space"`).
404
466
  - **`pinchMsg(pinch: PinchEvent): Msg | null`** — the view-global trackpad pinch channel. `PinchEvent` carries `windowId`, `label`, begin/change/end `phase`, multiplicative `scale` delta, and the view-local `x`/`y` anchor.
405
467
  - **`dropMsg(drop: FileDropEvent): Msg | null`** — native file drops after widget routing. `FileDropEvent` is exactly `{ windowId; viewLabel; point; paths }`: `point` is `{ x; y } | null`, and `paths` is `readonly Uint8Array[]` so arbitrary UTF-8 filesystem names remain byte text. Return null to ignore the drop or map it to any ordinary Msg.
@@ -408,6 +470,39 @@ The generated wiring detects each channel from an export (export exists → wire
408
470
  - **`export const envMsgs = [{ env: "NAME", msg: "<arm>" }] as const`** — each named environment variable present at launch dispatches its value through the arm (exactly one `Uint8Array` field, `BytesKind` — annotate with `readonly EnvMsg<Msg>[]` from the SDK for tsc checking) as one journaled Msg right after the boot command. The generated runner also synthesizes the reserved `NATIVE_SDK_APP_DATA_DIR` value from `native_sdk.app_dirs` when requested here; use it as the root for durable `Cmd.writeFile`/`Cmd.readFile` paths instead of relying on the package's process working directory. The core never reads the environment (NS1005), and neither does replay: the deliveries are journaled at record time and fed back from the journal, so a recording replays byte-identically even when ambient variables are unset or changed at replay launch.
409
471
  - **`app.zon .assets.images`** — `.assets = .{ .images = .{ .{ .id = 1, .path = "assets/art/cover.jpg" }, ... } }`: each file is read once at launch and registered on the installing frame; the `id` is the `ImageId` markup avatar bindings reference (`<avatar image="{coverId}">`), and a missing file or failed decode keeps the initials fallback.
410
472
 
473
+ ## Synchronous boot image results
474
+
475
+ Declare encoded images in the manifest's image assets. Native code decodes and
476
+ registers them on the installing frame. Export
477
+ `bootImageMsg(model: Model, result: BootImageResult): ImageMsg | null` to choose
478
+ which successful registrations enter the model and which failures keep a
479
+ fallback. Import `BootImageResult` from `@native-sdk/core/events`; it contains
480
+ exact decimal `id` bytes, `registered`, `width`, `height`, and complete native
481
+ `errorName` bytes. Failure has zero dimensions; success has an empty error.
482
+
483
+ `ImageMsg` is a dedicated subset union of `Msg`, with identical payload fields.
484
+ Returning `null` ignores the report without undoing registration. Results arrive
485
+ in asset declaration order before the initial command and first view. Images
486
+ retain native registry and pixel ownership; registration follows the existing
487
+ synchronous native boot convention and does not add an effect journal record.
488
+ A replay installs the same declared assets through the same codec capability.
489
+ Cores without this hook retain automatic registration without result delivery.
490
+
491
+ Like other transient value records, keep the callback record out of the retained
492
+ model tree: copy its fields into an interface-backed model record. Carry its
493
+ byte fields inline in message arms so the complete dispatch ABI stays explicit.
494
+
495
+ ## Canvas declarations
496
+
497
+ Import the canonical records from `@native-sdk/core/events` and declare these helpers in `core.ts`:
498
+
499
+ - `canvasIcons(model): readonly CanvasIconDefinition[]` declares the app's vector glyphs, installed once before boot images, commands and the first view. Each record carries its raw name bytes, view box, complete path elements and shape ranges with fill/stroke paints, stroke width, cap and join. Paints are `none`, `current_color`, or an explicit RGBA `color`. Native copies all data into stable drawing storage; another helper call cannot change the registered glyphs. There may be 64 icons with names of 1–128 bytes, 48 shapes and 512 path elements per icon. Names must be unique, view-box dimensions positive, ranges within the element array, geometry finite, stroke widths nonnegative and RGBA channels within 0–1. A refused batch leaves the previous registry intact and fails installation. Use `app:<name>` in markup. Glyph definitions are pure data and replay reinstalls the same definitions without file IO.
500
+ - `canvasChrome(model, context: CanvasChromeContext): readonly CanvasChromeCommand[]` derives up to 256 commands before the widget display list. `canvasChromeSuffix` has the same signature and derives an independent layer after widgets; either layer may be empty or omitted. Native supplies viewport dimensions and resolved background/surface/border colors. The compiled core owns the split, and native preserves both actual layer lengths during widget-only regeneration. Commands support filled rectangles, uniform rounded rectangles, stroked rectangles with four corner radii, lines, filled paths, and stroked paths with butt/round caps. IDs are canonical unsigned decimal bytes through max-u64; nonzero IDs must be unique across both layers, while zero is anonymous. Each gradient has at most 16 stops and each path at most 64 elements. Import `CanvasPathElement` and carry its verb plus all three point slots explicitly, including unused points, to keep declarations lossless. Native copies gradients and paths into disjoint layer storage before another helper call, then into the retained display list. Geometry and all path points must be finite, dimensions/radii/stroke widths nonnegative, and RGBA channels within 0–1. The native view's aggregate command, path, and gradient capacities still apply. Invalid or over-capacity declarations fail the whole install.
501
+ - `canvasAnimations(model): readonly CanvasAnimation[]` targets an exact accessibility label and zero-based occurrence, with `part: "fill" | "text"`. Native resolves retained command IDs and stamps the presentation clock. Indices and durations are u32-range integers; transforms are finite and opacity stays within 0–1. An invalid, duplicate, or oversized batch clears declarations.
502
+ - `canvasFrameMsg(model, frame: CanvasFrameEvent)` receives copied renderer facts with exact decimal-byte clocks/counters, risk, packet representability and dirty ratio. Return a dedicated subset union of `Msg` or `null`; share the exact payload types with `Msg`. Export this helper instead of `frameMsg`.
503
+
504
+ GPU Dashboard demonstrates these hooks together with model-owned appearance, token overrides, retained controls, and replay. Native retains rendering, submission and resource lifetime.
505
+
411
506
  ## The rules the checker enforces
412
507
 
413
508
  Every diagnostic carries one of these IDs plus the fix and the why, and every rule carries a class: `guarantee` rules protect a core invariant (determinism and replay, fixed shapes, immutability of shared data, the one text representation) and are permanent; `deferred` rules (NS1011, NS1019, NS1040, NS1042, NS1044) wait on a deliberate easing decision and say so in their output. Write to them up front:
@@ -444,10 +539,10 @@ Every diagnostic carries one of these IDs plus the fix and the why, and every ru
444
539
  - **NS1070 relational SQLite and capability disagree (warning).** Raw `Cmd.db.*`, generated `Cmd.q<Name>`, and generated `Sub.q<Name>` require `"sqlite"`; declaring the capability without using any of them produces the inverse warning.
445
540
  - **NS14xx SQL diagnostics come from the real schema.** Fix the migration or named statement at the reported `.sql` line. Migration versions are append-only and contiguous; ordinary generated-query tables are `STRICT`; raw query literals receive the non-fatal NS1420 escape-hatch nudge; identifier-like INTEGER fields receive NS1422's exact-number warning.
446
541
  - **NS1029 effect op arguments have a fixed shape.** Paths/URLs/bodies are bytes, `Cmd.fetch`'s spec is an inline object with a closed verb literal, a number-literal timeout, and an inline flat record of headers whose NAMES are compile-time ASCII and whose VALUES are string literals or runtime bytes (`Uint8Array`). The record's shape encodes at build time; a runtime header value rides its length-prefixed wire field at dispatch time exactly like `url`/`body` — but a smuggled string (a ternary of literals, a template) has no encoding: make it bytes.
447
- - **NS1031 exported model helpers join the model's binding surface.** An exported single-Model-parameter helper becomes a Model declaration markup binds (`doneCount` → `{doneCount}`); two members with one binding name would be ambiguous — rename one.
542
+ - **NS1031 exported model helpers join the model's binding surface.** An exported Model-first helper becomes a Model declaration; only a single-Model-parameter helper is a scalar markup binding (`doneCount` → `{doneCount}`); two members with one binding name would be ambiguous — rename one.
448
543
  - **NS1032 viewUnbound names update-only model state.** `export const viewUnbound = [...] as const` entries must be string literals naming Model fields, exported model helpers, or Msg kinds — by their TypeScript spellings (`"nextId"`); anything else would silence nothing and hide a typo.
449
544
  - **NS1030 effect arguments respect the engine's limits.** A compile-time-knowable value outside an engine bound (a path literal over 1024 bytes, a URL literal over 2 KiB, more than 8 headers, a header block over 1 KiB, a delay literal outside 1ms..one year) stops the build instead of shipping a guaranteed runtime rejection. Dynamic values stay the engine's to validate — they surface through the `err` arm.
450
- - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm; `themeState`, `themePack`, `statusItem`, `statusItems`, and `windows` return their exact model-derived shell shapes. The generated wiring builds these host values structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
545
+ - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm; `themeState`, `themePack`, `statusItem`, `statusItems`, `windows`, and `webPanes` return their exact model-derived shell shapes. The generated wiring builds these host values structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
451
546
  - **NS1034 core imports stay inside src/.** `../` escapes and absolute paths are rejected: the entry module's directory is the core's whole world - the build ships exactly that tree.
452
547
  - **NS1035 npm packages do not run inside a core.** No JS engine ships in the binary; vendor the logic under `src/` or make the import type-only.
453
548
  - **NS1036 core modules do not import in a cycle.** Runtime cycles only work through JS live-binding indirection; hoist shared declarations, or make the back-edge `import type` (which is exempt and idiomatic).
@@ -575,7 +670,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
575
670
 
576
671
  - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically. It likewise wires `theme_state_fn` from `themeState(model)` or `theme_fn` from legacy `themePack(model)`, and the singular `status_item_fn` or collection `status_items_fn` from the matching helper. A wiring that also sets one of those seams is a teaching panic. Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
577
672
  - Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the core's model keeps the TS spellings). Record arrays iterate with `<for each="tasks" as="t" key="id">` and items bind their fields (`{t.title}`); optional scalars gate with `<if test="{selected}">` (null is falsy); string-literal unions bind as their member name (`{filter}` renders `all` — compare against a quoted literal, `selected="{sortKey == 'cpu'}"`); exported single-model helpers bind as derived values (`{doneCount}`) and slice-returning ones drive `for each`. Markup `<chart>` series bind number arrays too — `<series kind="bar" values="{cpuSpark}" />` over a field or helper returning `readonly number[]` (f64, narrowed per sample into the chart pipeline); pad a filling window's leading gap with `NaN` samples, which draw nothing.
578
- - `Options.sync` does not exist for TS apps (a committed model cannot be mutated in place): keep continuous controls model-driven — bind the widget's value and echo `on-change`/`on-scroll` Msgs back into the model.
673
+ - Keep continuous controls model-driven: bind the widget's value and echo `on-change`/`on-scroll` messages back into the model. For passive sampling of retained main-canvas sliders, export `sliderStateMsg(model: Model, sliders: readonly SliderState[]): SliderMsg | null` with `SliderState` from `@native-sdk/core/events`. The adapter supplies each slider's exact decimal `id`, byte `label`, and applied native f32 `value` before updates, effect drains, and rebuilds. Return a dedicated Msg subset union with identical payloads, or null; its update must return `Cmd.none` (commands fail the sync boundary). The ordinary commit walker retains the complete result before scratch reset. Sampling emits no extra journal event and follows the same retained state during replay. Custom `Options.sync` remains unsupported because it mutates a committed graph in place.
579
674
  - One live app per core module per process: two apps over the SAME core would share one committed root — and a process carries ONE compiled core (the archive owns a fixed-prefix C ABI symbol set).
580
675
  - Record/replay, the automation verbs, and screenshot fingerprints work unchanged — the adapter rides the standard UiApp dispatch path.
581
676
 
@@ -597,3 +692,12 @@ node <sdk-repo>/packages/core/src/cli.ts src/core.ts
597
692
  ```
598
693
 
599
694
  Exit 0 means the module typechecked (real tsc semantics) and passed every subset rule — the exact pass every build runs before the external core compiler takes the graph. Because the subset is erasable TypeScript, `node` can import your core directly for quick behavioral checks (`node --input-type=module -e "..."` or a small `node --test` file) — the native build has the same semantics. If the core imports `@native-sdk/core` (for `Cmd`, `asciiBytes`, or `utf8Bytes`), map that one specifier for node first: copy the SDK module file next to the core and rewrite the import, or run through a loader that resolves it.
695
+
696
+ For a migration that already stores files under the app's short name, `envMsgs` may request `NATIVE_SDK_APP_LEGACY_DATA_DIR`. The launcher resolves that name and explicitly grants its data directory as an additional file root. The ordinary `NATIVE_SDK_APP_DATA_DIR` remains the bundle-ID directory; raw ambient path overrides are never used for either capability.
697
+
698
+ `envMsgs` may also request `NATIVE_SDK_APP_CACHE_DIR`. On desktop it supplies
699
+ the OS-resolved cache root under the app's short name, matching the launcher’s
700
+ URL media cache. Resolution failure supplies empty bytes, which disables
701
+ caching. The mobile launcher supplies empty bytes until a cache-root capability
702
+ is available. An ambient variable cannot override either result. Deliveries use
703
+ the same journaled launch channel and replay ownership as other `envMsgs`.
@@ -79,7 +79,7 @@ native vendor . escape-string-regexp@5.0.0
79
79
 
80
80
  The command installs with lifecycle scripts disabled in a temporary directory, copies the flattened package graph into `src/services/vendor/`, retains package/license files, computes canonical tree hashes, and rewrites app.zon's `service_packages` with exact names, `X.Y.Z` versions, and hashes. Check those bytes and manifest facts into source control.
81
81
 
82
- Builds never run npm or use the network. They verify package identity and every vendored byte, stage only declared packages, and invoke scriptc with `--npm-static <explicit-list>`. `auto`, dynamic-island fallback, and `--dynamic` are refused. Anything below 100% static coverage fails: `native check` preserves the coverage note verbatim and names the three options—choose another exact package, port/vendor a suitable implementation, or wait for compiler support. The checked-in package spike (`tests/ts-services/npm-static-spike.json`) passed three of five deliberately small candidates and refused `nanoid` and `micromark`; npm support is selective.
82
+ Builds never run npm or use the network. They verify package identity and every vendored byte, stage only declared packages, and invoke scriptc with `--npm-static <explicit-list>`. `auto`, dynamic-island fallback, and `--dynamic` are refused. Anything below 100% static coverage fails: `native check` preserves the coverage note verbatim and names the three options—choose another exact package, port/vendor a suitable implementation, or wait for compiler support. The checked-in package spike (`tests/ts-services/npm-static-spike.json`) passed four of five deliberately small candidates and refused `micromark`; npm support is selective.
83
83
 
84
84
  ## Streaming, cancellation, and deadlines
85
85