@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
@@ -29,6 +29,7 @@
29
29
  //! false })` so the watch machinery compiles out too). Setting both keeps
30
30
  //! the compiled view until the watched file first changes on disk.
31
31
 
32
+ const authorization = @import("authorization_policy.zig");
32
33
  const std = @import("std");
33
34
  const builtin = @import("builtin");
34
35
  const geometry = @import("geometry");
@@ -40,10 +41,15 @@ const core = @import("core.zig");
40
41
  const canvas_frame = @import("canvas_frame.zig");
41
42
  const canvas_limits = @import("canvas_limits.zig");
42
43
  const canvas_widget_events = @import("canvas_widget_events.zig");
44
+ const drag_policy = @import("canvas_drag_policy.zig");
45
+ const dispatch_policy = @import("app_dispatch_policy.zig");
46
+ const component_policy = @import("component_policy.zig");
47
+ const hover_policy = @import("canvas_hover_policy.zig");
43
48
  const launch_timing = @import("launch_timing.zig");
44
49
  const runtime_effects = @import("effects.zig");
45
50
  const terminal_session = @import("terminal_session.zig");
46
51
  const ui_app_provenance = @import("ui_app_provenance.zig");
52
+ const markup_development = @import("markup_development_policy.zig");
47
53
 
48
54
  const Runtime = core.Runtime;
49
55
  const App = core.App;
@@ -96,6 +102,9 @@ pub const UiAppFeatures = struct {
96
102
  /// `canvas.CompiledMarkupView` so no parser code (or its diagnostics)
97
103
  /// ships in the binary; the markup machinery then compiles to nothing.
98
104
  runtime_markup: bool = true,
105
+ /// Generated TypeScript views observe compiled state directly. This
106
+ /// selects their stateless host handle instead of a decoded model mirror.
107
+ compiled_model: bool = false,
99
108
  };
100
109
 
101
110
  pub fn UiApp(comptime ModelT: type, comptime MsgT: type) type {
@@ -193,7 +202,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
193
202
  /// BUDGET instead: `build` may emit any count up to it.
194
203
  prefix_commands: usize,
195
204
  /// Number of chrome commands preserved after the
196
- /// widget-generated commands. Always exact.
205
+ /// widget-generated commands. Exact with the combined builder;
206
+ /// a budget when build_suffix supplies a separate derived layer.
197
207
  suffix_commands: usize = 0,
198
208
  /// The prefix length is whatever `build` emitted this
199
209
  /// rebuild (minus the fixed suffix) rather than an exact
@@ -209,6 +219,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
209
219
  /// commands (up to `prefix_commands` under
210
220
  /// `variable_prefix`).
211
221
  build: *const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void,
222
+ /// Optional independent suffix. The first builder supplies only
223
+ /// the prefix; both actual lengths are retained on every rebuild.
224
+ build_suffix: ?*const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void = null,
212
225
  };
213
226
 
214
227
  /// A live webview region hosted alongside the canvas — the "both
@@ -292,6 +305,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
292
305
  pack: ?canvas.ThemePack = null,
293
306
  color_scheme: ThemeColorScheme = .system,
294
307
  accent: ?canvas.Color = null,
308
+ /// Omission follows the OS; explicit values retain observed
309
+ /// accessibility appearance in the model during replay.
310
+ high_contrast: ?bool = null,
311
+ reduce_motion: ?bool = null,
295
312
  /// Adapter-only invalid declaration marker. Zig cores already
296
313
  /// pass a typed Color; the TS adapter retains malformed source
297
314
  /// text here so rebuild rejects it instead of silently inheriting.
@@ -479,8 +496,51 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
479
496
  };
480
497
 
481
498
  pub const Options = struct {
499
+ /// Resolve authored PTY names without exposing engine identities.
500
+ pty_key_resolver: ?*const fn ([]const u8) u64 = null,
482
501
  name: []const u8,
483
502
  scene: app_manifest.ShellConfig,
503
+ /// Portable dispatch/drain scheduling. Native owns messages,
504
+ /// queue boundaries, errors and capability execution; plans copy.
505
+ replay_policy: ?*const fn ([]const u8, []u8) usize = null,
506
+ recording_policy: ?*const fn ([]const u8, []u8) usize = null,
507
+ blob_policy: ?*const fn ([]const u8, []u8) usize = null,
508
+ app_dispatch_policy: dispatch_policy.Policy = null,
509
+ /// Portable context-menu and scroll coordination; native owns pins and latches.
510
+ component_policy: component_policy.Policy = null,
511
+ /// Portable construction is owned by the compiled app; the
512
+ /// builder copies descriptors into its existing generation arena.
513
+ composition_policy: ?canvas.ComponentCompositionPolicy.Policy = null,
514
+ code_content_policy: ?canvas.CodeContentPolicy.Policy = null,
515
+ paragraph_policy: ?*const fn ([]const u8, []u8) usize = null,
516
+ text_run_policy: ?*const fn ([]const u8, []u8) usize = null,
517
+ chart_content_policy: ?canvas.ChartContentPolicy.Policy = null,
518
+ markdown_content_policy: ?canvas.MarkdownContentPolicy.Policy = null,
519
+ construction_policy: ?canvas.ComponentConstructionPolicy.Policy = null,
520
+ shell_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
521
+ view_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
522
+ window_lifecycle_policy: ?*const fn ([]const u8, []u8) usize = null,
523
+ image_registry_policy: ?*const fn ([]const u8, []u8) usize = null,
524
+ font_registry_policy: ?*const fn ([]const u8, []u8) usize = null,
525
+ shell_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
526
+ shell_admission_policy: ?*const fn ([]const u8, []u8) usize = null,
527
+ system_admission_policy: ?*const fn ([]const u8, []u8) usize = null,
528
+ bridge_descriptor_policy: ?*const fn ([]const u8, []u8) usize = null,
529
+ authorization_policy: ?*const fn ([]const u8, []u8) usize = null,
530
+ builtin_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
531
+ automation_command_policy: ?*const fn ([]const u8, []u8) usize = null,
532
+ automation_interaction_policy: ?*const fn ([]const u8, []u8) usize = null,
533
+ snapshot_policy: ?*const fn ([]const u8, []u8) usize = null,
534
+ host_flow_policy: ?*const fn ([]const u8, []u8) usize = null,
535
+ /// Copied root/fragment reload and complete provenance programs.
536
+ markup_development_policy: markup_development.Policy = null,
537
+ /// Installed by TsUiApp for compiled command and status policy.
538
+ command_policy: ?*const fn ([]const u8, []u8) usize = null,
539
+ text_cache_policy: ?*const fn ([]const u8, []u8) usize = null,
540
+ render_cache_policy: ?*const fn ([]const u8, []u8) usize = null,
541
+ render_plan_policy: ?*const fn ([]const u8, []u8) usize = null,
542
+ render_override_policy: ?*const fn ([]const u8, []u8) usize = null,
543
+ render_damage_policy: ?*const fn ([]const u8, []u8) usize = null,
484
544
  canvas_label: []const u8,
485
545
  /// Fixed design tokens for an app that owns its look. Leave
486
546
  /// null (the default) and the stock tokens FOLLOW THE SYSTEM
@@ -495,6 +555,26 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
495
555
  /// scale afterwards: the model owns scheme/contrast/motion,
496
556
  /// the runtime owns the surface scale.
497
557
  tokens_fn: ?*const fn (model: *const ModelT) canvas.DesignTokens = null,
558
+ /// Portable surface placement over native measurements, independent of theme overrides.
559
+ surface_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
560
+ grid_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
561
+ container_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
562
+ measurement_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
563
+ flow_measurement_policy: ?*const fn ([]const u8, []u8) usize = null,
564
+ layout_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
565
+ render_coordination_policy: ?*const fn ([]const u8, []u8) usize = null,
566
+ control_command_policy: ?*const fn ([]const u8, []u8) usize = null,
567
+ intrinsic_layout_policy: ?*const fn ([]const u8, []u8) usize = null,
568
+ widget_motion_policy: ?*const fn ([]const u8, []u8) usize = null,
569
+ widget_audit_policy: ?*const fn ([]const u8, []u8) usize = null,
570
+ accessibility_policy: ?*const fn ([]const u8, []u8) usize = null,
571
+ widget_routing_policy: ?*const fn ([]const u8, []u8) usize = null,
572
+ widget_change_policy: ?*const fn ([]const u8, []u8) usize = null,
573
+ widget_paint_policy: ?*const fn ([]const u8, []u8) usize = null,
574
+ widget_presentation_policy: ?*const fn ([]const u8, []u8) usize = null,
575
+ terminal_paint_policy: ?*const fn ([]const u8, []u8) usize = null,
576
+ widget_paint_walk_policy: ?*const fn ([]const u8, []u8) usize = null,
577
+ control_geometry_policy: ?*const fn ([]const u8, []u8) usize = null,
498
578
  /// Which built-in theme pack the stock tokens resolve when
499
579
  /// the app claims neither `tokens` nor `tokens_fn`: the
500
580
  /// pack composes with the live system appearance (scheme,
@@ -517,6 +597,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
517
597
  /// is mutually exclusive with it. Explicit `tokens_fn`/`tokens`
518
598
  /// still own the complete register and take precedence.
519
599
  theme_state_fn: ?*const fn (model: *const ModelT) ThemeState = null,
600
+ /// Model-derived overrides over the resolved stock register.
601
+ /// Explicit complete tokens retain precedence; device scale and
602
+ /// native measurement capabilities remain runtime-owned.
603
+ token_overrides_fn: ?*const fn (model: *const ModelT) canvas.DesignTokenOverrides = null,
520
604
  /// The app's ONE-accent brand statement over the stock
521
605
  /// tokens: when set (and the app claims neither `tokens`
522
606
  /// nor `tokens_fn` — apps that own their tokens own their
@@ -529,6 +613,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
529
613
  /// this to app.zon's `theme_accent` field through
530
614
  /// `app_runner.manifestThemeAccent()`.
531
615
  theme_accent: ?canvas.Color = null,
616
+ /// Optional portable stock-theme policy. Inputs carry explicit
617
+ /// presence/appearance facts; copied results retain dispatch lifetime.
618
+ theme_policy: ?*const fn ([]const u8, []u8) usize = null,
532
619
  /// App font faces registered once, on the installing frame,
533
620
  /// BEFORE the first view build — so the very first layout
534
621
  /// already measures (and the first paint inks) with them.
@@ -605,6 +692,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
605
692
  /// Optional mapping from shell command events (menus, shortcuts,
606
693
  /// native controls) into messages.
607
694
  on_command: ?*const fn (name: []const u8) ?MsgT = null,
695
+ /// A source window's label is input context, reduced before its event.
696
+ on_window_context: ?*const fn (model: *const ModelT, label: []const u8) ?MsgT = null,
608
697
  /// Optional mapping from app lifecycle events into messages.
609
698
  /// A single-window app can use activate/deactivate as its
610
699
  /// keyboard-focus signal for custom canvas chrome whose
@@ -787,6 +876,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
787
876
  /// macOS-proven (`NSStatusItem`); platforms without a
788
877
  /// status-bar service log a warning and continue.
789
878
  status_item: ?StatusItemOptions = null,
879
+ /// Optional portable reconciliation. Requests borrow native facts;
880
+ /// results are copied without resetting the current dispatch frame.
881
+ status_policy: ?*const fn ([]const u8, []u8) usize = null,
790
882
  /// Model-derived status-item title and menu (e.g. an
791
883
  /// open-count badge in the menu bar, a latest-items
792
884
  /// dropdown), the `web_panes` pattern: consulted on install
@@ -819,6 +911,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
819
911
  /// no close Msg. Reconcile failures degrade to logged warnings
820
912
  /// — a failed create never takes the render loop down.
821
913
  windows_fn: ?*const fn (model: *const ModelT, scratch: *WindowsScratch) []const WindowDescriptor = null,
914
+ /// Optional portable reconciliation over native-owned window
915
+ /// facts. The callback copies its output; rebuild/view consumers
916
+ /// retain ownership of the compiler frame and descriptor storage.
917
+ window_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
918
+ /// Optional portable hold coordination; native retains timer
919
+ /// capabilities, armed identities and owned handler tables.
920
+ press_hold_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
921
+ /// Portable Tab order over retained-tree facts. Native keeps
922
+ /// identities, measured eligibility, reveal and OS focus.
923
+ tab_focus_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
924
+ /// Portable anchored-surface selection; native retains paint
925
+ /// facts, identities and dismissal/focus side effects.
926
+ surface_scope_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
927
+ /// Portable return-target selection for dismissed/unmounted surfaces.
928
+ focus_return_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
929
+ /// Portable tooltip ownership and adoption-time binding survival.
930
+ tooltip_policy: ?*const fn (request: []const u8, output: []u8) usize = null,
822
931
  /// Per-window view for declared secondary windows, keyed by
823
932
  /// the descriptor's window label — the `view` seam with the
824
933
  /// window identity alongside. Rebuilt for every open window
@@ -1344,6 +1453,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1344
1453
  return .{
1345
1454
  .model = model,
1346
1455
  .options = options,
1456
+ .provenance = if (comptime features.runtime_markup) .{ .policy = options.markup_development_policy, .allocator = backing } else {},
1457
+ .provenance_closure = if (comptime features.runtime_markup) .{ .policy = options.markup_development_policy } else {},
1347
1458
  .backing = backing,
1348
1459
  .arenas = .{
1349
1460
  std.heap.ArenaAllocator.init(backing),
@@ -1410,6 +1521,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1410
1521
  self.* = .{
1411
1522
  .model = undefined,
1412
1523
  .options = options,
1524
+ .provenance = if (comptime features.runtime_markup) .{ .policy = options.markup_development_policy, .allocator = backing } else {},
1525
+ .provenance_closure = if (comptime features.runtime_markup) .{ .policy = options.markup_development_policy } else {},
1413
1526
  .backing = backing,
1414
1527
  .arenas = .{
1415
1528
  std.heap.ArenaAllocator.init(backing),
@@ -1474,9 +1587,33 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1474
1587
  .context = self,
1475
1588
  .name = self.options.name,
1476
1589
  .scene_fn = sceneFn,
1590
+ .shell_layout_policy = self.options.shell_layout_policy,
1591
+ .view_coordination_policy = self.options.view_coordination_policy,
1592
+ .window_lifecycle_policy = self.options.window_lifecycle_policy,
1593
+ .image_registry_policy = self.options.image_registry_policy,
1594
+ .font_registry_policy = self.options.font_registry_policy,
1595
+ .shell_coordination_policy = self.options.shell_coordination_policy,
1596
+ .shell_admission_policy = self.options.shell_admission_policy,
1597
+ .system_admission_policy = self.options.system_admission_policy,
1598
+ .bridge_descriptor_policy = self.options.bridge_descriptor_policy,
1599
+ .authorization_policy = self.options.authorization_policy,
1600
+ .builtin_coordination_policy = self.options.builtin_coordination_policy,
1601
+ .automation_command_policy = self.options.automation_command_policy,
1602
+ .automation_interaction_policy = self.options.automation_interaction_policy,
1603
+ .snapshot_policy = self.options.snapshot_policy,
1604
+ .host_flow_policy = self.options.host_flow_policy,
1605
+ .command_policy = self.options.command_policy,
1606
+ .text_cache_policy = self.options.text_cache_policy,
1607
+ .render_cache_policy = self.options.render_cache_policy,
1608
+ .render_plan_policy = self.options.render_plan_policy,
1609
+ .render_override_policy = self.options.render_override_policy,
1610
+ .render_damage_policy = self.options.render_damage_policy,
1477
1611
  .event_fn = eventFn,
1478
1612
  .stop_fn = stopFn,
1479
1613
  .replay_fn = replayFn,
1614
+ .replay_policy = self.options.replay_policy,
1615
+ .recording_policy = self.options.recording_policy,
1616
+ .blob_policy = self.options.blob_policy,
1480
1617
  };
1481
1618
  }
1482
1619
 
@@ -1502,6 +1639,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1502
1639
  /// image registry, window verbs, and — while a session is being
1503
1640
  /// recorded — the recorder's result journal.
1504
1641
  fn bindEffectsChannel(self: *Self, runtime: *Runtime) void {
1642
+ self.effects.defer_desktop_capabilities = true;
1643
+ self.effects.system_admission_policy = self.options.system_admission_policy;
1505
1644
  self.effects.bindServices(&runtime.options.platform.services);
1506
1645
  self.effects.bindEnviron(runtime.options.environ);
1507
1646
  if (runtime.options.record_store) |binding| {
@@ -1514,7 +1653,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1514
1653
  .services = &runtime.options.platform.services,
1515
1654
  .service = runtime.options.platform.app_info.bundle_id,
1516
1655
  .permitted = runtime.options.credentials_enabled and
1517
- security.hasPermission(runtime.options.security.permissions, security.permission_credentials),
1656
+ authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_credentials),
1518
1657
  });
1519
1658
  if (runtime.options.file_access) |binding| {
1520
1659
  self.effects.bindFileAccess(binding);
@@ -1524,7 +1663,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1524
1663
  // fake file requests must park without consulting live paths.
1525
1664
  self.effects.bindFileAccess(.{
1526
1665
  .roots = &.{},
1527
- .permitted = security.hasPermission(runtime.options.security.permissions, security.permission_filesystem),
1666
+ .permitted = authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_filesystem),
1528
1667
  .enforce = true,
1529
1668
  });
1530
1669
  }
@@ -1544,8 +1683,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1544
1683
  .open_external_url_fn = effectsOpenExternalUrl,
1545
1684
  .reveal_path_fn = effectsRevealPath,
1546
1685
  .format_local_time_fn = effectsFormatLocalTime,
1686
+ .execute_capability_fn = effectsExecuteCapability,
1687
+ .replay_window_result_fn = effectsRestoreWindowResult,
1547
1688
  });
1548
1689
  if (runtime.options.session_recorder) |recorder| {
1690
+ if (self.options.recording_policy) |policy| recorder.recording_policy = policy;
1549
1691
  self.effects.bindJournal(recorder.effectJournal());
1550
1692
  }
1551
1693
  // The terminal-session seams (no-ops on stub builds): the
@@ -1593,7 +1735,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1593
1735
  .exit => {
1594
1736
  if (record.payload.len > 0) try self.effects.feedOutput(record.key, record.payload);
1595
1737
  if (record.stderr_tail.len > 0) try self.effects.feedStderr(record.key, record.stderr_tail);
1596
- try self.effects.feedExitReason(record.key, record.code, record.exit_reason);
1738
+ try self.effects.feedExitWithMetadata(record.key, record.code, record.exit_reason, .{
1739
+ .output_truncated = record.output_truncated,
1740
+ .stderr_truncated = record.stderr_truncated,
1741
+ .dropped_lines = record.dropped,
1742
+ });
1597
1743
  },
1598
1744
  .response => try self.effects.feedResponseOutcomeWithMetadata(
1599
1745
  record.key,
@@ -1619,6 +1765,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1619
1765
  // `.rejected` and regenerate from the same
1620
1766
  // deterministic validation, like `.timer` records.
1621
1767
  .host => try self.effects.feedHostResult(record.key, record.code == 0, record.payload),
1768
+ .window_execution => try self.effects.pushReplayWindowExecution(record),
1769
+ .channel_source => try self.effects.pushReplayChannelSource(record),
1622
1770
  .credentials => try self.effects.feedCredentialsResult(
1623
1771
  record.key,
1624
1772
  record.credentials_operation,
@@ -1700,13 +1848,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1700
1848
  // is still divergent input).
1701
1849
  .write => try self.effects.pushReplayPtyWriteVerdict(record.key, record.code == 1),
1702
1850
  },
1703
- // Spectrum records feed through the band-carrying
1704
- // helper so replay repaints identical bars; every
1705
- // other audio kind rides the plain shape.
1706
- .audio => if (record.audio_kind == .spectrum)
1707
- try self.effects.feedAudioSpectrum(record.audio_bands, record.audio_position_ms, record.audio_duration_ms)
1708
- else
1709
- try self.effects.feedAudioEventBuffering(record.audio_kind, record.audio_position_ms, record.audio_duration_ms, record.audio_playing, record.audio_buffering),
1851
+ .audio => try self.effects.feedAudioRecord(.{
1852
+ .key = record.key,
1853
+ .kind = record.audio_kind,
1854
+ .position_ms = record.audio_position_ms,
1855
+ .duration_ms = record.audio_duration_ms,
1856
+ .playing = record.audio_playing,
1857
+ .buffering = record.audio_buffering,
1858
+ .bands = record.audio_bands,
1859
+ }),
1710
1860
  // `.video` records feed the whole journaled shape —
1711
1861
  // dimensions included — routed by the journaled
1712
1862
  // load identity (`video_token`), so replay delivers
@@ -1746,120 +1896,110 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1746
1896
  /// widget state is synced into the model first so `update` sees
1747
1897
  /// current slider values and scroll offsets.
1748
1898
  pub fn dispatch(self: *Self, runtime: *Runtime, window_id: platform.WindowId, msg: MsgT) anyerror!void {
1749
- self.bindEffectsChannel(runtime);
1750
- self.syncModel(runtime, self.canvas_window_id);
1751
- self.applyMsg(msg);
1752
- self.publishAudioState(runtime);
1753
- // Before the installing frame there is nothing to render
1754
- // against: canvas size and scale arrive with the first frame
1755
- // event, and the installing rebuild renders whatever model
1756
- // state accumulated here. A pre-install rebuild is discarded
1757
- // work at a default surface size — and appearance/chrome
1758
- // events land before the first frame on every launch, so it
1759
- // used to cost a full view build on the launch path.
1760
- if (!self.installed) return;
1761
- // Hover edges the rebuilds produce (an unmounted hovered
1762
- // element's leave, an adoption re-hit-test's handoff)
1763
- // settle at this tail for DIRECT callers — command
1764
- // handlers, embedders, tests — without waiting for the
1765
- // next platform event, and on the REBUILD-ERROR path too:
1766
- // a failed secondary-window rebuild must not strand the
1767
- // leave the main rebuild already produced. Inside a runtime
1768
- // event the event's own tail drains instead, and the
1769
- // drain's own dispatches re-enter here guarded.
1770
- var rebuild_error: ?anyerror = null;
1771
- self.rebuild(runtime, self.canvas_window_id) catch |err| {
1772
- rebuild_error = err;
1773
- };
1774
- if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1775
- rebuild_error = err;
1776
- };
1777
- if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1778
- self.drainHoverMsgs(runtime) catch |err| {
1779
- if (rebuild_error == null) rebuild_error = err;
1780
- };
1899
+ for (self.dispatchPlan(.dispatch_begin, false, false)) |byte| {
1900
+ switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1901
+ .end => break,
1902
+ .bind => self.bindEffectsChannel(runtime),
1903
+ .sync => self.syncModel(runtime, self.canvas_window_id),
1904
+ .apply => self.applyMsg(msg),
1905
+ .audio => self.publishAudioState(runtime),
1906
+ else => @panic("unexpected dispatch preparation action"),
1907
+ }
1781
1908
  }
1782
- if (rebuild_error) |err| return err;
1783
- // A Msg dispatched FROM a secondary window still rebuilt the
1784
- // main canvas above (one model, every window's view derives
1785
- // from it); `window_id` names the dispatch origin for apps
1786
- // that inspect it, not the rebuild target.
1909
+ // Installation is sampled after update, as in the native loop.
1910
+ const render = self.dispatchPlan(.dispatch_render, self.installed, false);
1911
+ if (render[0] == 0) return;
1912
+ var first_error: ?anyerror = null;
1913
+ try self.executeRebuildPlan(runtime, render, &first_error);
1914
+ try self.settleDispatch(runtime, &first_error);
1787
1915
  _ = window_id;
1788
1916
  }
1789
1917
 
1790
- /// Run `update` through whichever form the app declared; the
1791
- /// effects channel rides along for the `update_fx` form.
1918
+ fn dispatchPlan(self: *Self, stage: dispatch_policy.Stage, a: bool, b: bool) dispatch_policy.Plan {
1919
+ return dispatch_policy.plan(self.options.app_dispatch_policy, stage, @intFromBool(a), @intFromBool(b));
1920
+ }
1921
+
1922
+ fn selectDispatchError(self: *Self, first: *?anyerror, next: ?anyerror) void {
1923
+ const plan = self.dispatchPlan(.error_selection, first.* != null, next != null);
1924
+ for (plan) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1925
+ .end => break,
1926
+ .take_error => first.* = next,
1927
+ else => @panic("unexpected dispatch error action"),
1928
+ };
1929
+ }
1930
+
1931
+ fn executeRebuildPlan(self: *Self, runtime: *Runtime, plan: dispatch_policy.Plan, first: *?anyerror) anyerror!void {
1932
+ for (plan) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1933
+ .end => break,
1934
+ .main => {
1935
+ self.rebuild(runtime, self.canvas_window_id) catch |err| self.selectDispatchError(first, err);
1936
+ const secondary = self.dispatchPlan(.secondary, first.* != null, false);
1937
+ for (secondary) |action| switch (@as(dispatch_policy.Action, @enumFromInt(action))) {
1938
+ .end => break,
1939
+ .secondary => self.rebuildWindowSlots(runtime) catch |err| self.selectDispatchError(first, err),
1940
+ else => @panic("unexpected secondary rebuild action"),
1941
+ };
1942
+ },
1943
+ .video_query => {
1944
+ const changed = !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot());
1945
+ try self.executeRebuildPlan(runtime, self.dispatchPlan(.video_rebuild, changed, false), first);
1946
+ },
1947
+ else => @panic("unexpected rebuild action"),
1948
+ };
1949
+ }
1950
+
1951
+ fn settleDispatch(self: *Self, runtime: *Runtime, first: *?anyerror) anyerror!void {
1952
+ const tail = self.dispatchPlan(.direct_tail, self.hover_msg_event_depth == 0, self.hover_msg_draining);
1953
+ for (tail) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1954
+ .end => break,
1955
+ .hover => self.drainHoverMsgs(runtime) catch |err| self.selectDispatchError(first, err),
1956
+ else => @panic("unexpected dispatch tail action"),
1957
+ };
1958
+ if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) self.effects.flushDesktopCapabilities();
1959
+ if (first.*) |err| return err;
1960
+ }
1961
+
1962
+ /// Execute a complete command batch before flushing relational reads.
1792
1963
  fn applyMsg(self: *Self, msg: MsgT) void {
1793
- if (self.options.update_fx) |update_fx| {
1794
- update_fx(&self.model, msg, &self.effects);
1795
- } else {
1796
- self.options.update.?(&self.model, msg);
1797
- }
1798
- // One update call is one complete command batch. Re-run live
1799
- // relational reads only after the batch has walked so several
1800
- // writes touching the same table still coalesce into one result.
1801
- self.effects.flushDbSubscriptions();
1964
+ for (self.dispatchPlan(.update, self.options.update_fx != null, false)) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1965
+ .end => break,
1966
+ .update_fx => self.options.update_fx.?(&self.model, msg, &self.effects),
1967
+ .update => self.options.update.?(&self.model, msg),
1968
+ .relational_flush => self.effects.flushDbSubscriptions(),
1969
+ else => @panic("unexpected update action"),
1970
+ };
1802
1971
  }
1803
1972
 
1804
- /// Drain the effect completion queue on the loop thread: every
1805
- /// queued line/exit becomes a Msg through its stored constructor
1806
- /// and runs through `update`; one rebuild follows. Called on
1807
- /// `.effects_wake` (the platform marshalled a worker's `wake_fn`
1808
- /// nudge) and each presented frame (host-pumped embeds have no
1809
- /// wake delivery; their frame pump drains naturally).
1973
+ /// Consume a captured causal boundary. Completions created by these
1974
+ /// updates remain queued for the next pass, with native-owned identities.
1810
1975
  pub fn drainEffects(self: *Self, runtime: *Runtime) anyerror!void {
1811
- if (!self.installed) return;
1812
- if (!self.effects.hasPending()) return;
1813
- self.bindEffectsChannel(runtime);
1814
- self.syncModel(runtime, self.canvas_window_id);
1976
+ const admission = self.dispatchPlan(.drain_installed, self.installed, false);
1977
+ var pending = false;
1978
+ for (admission) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1979
+ .end => break,
1980
+ .pending_query => pending = self.effects.hasPending(),
1981
+ else => @panic("unexpected effect admission action"),
1982
+ };
1983
+ const begin = self.dispatchPlan(.drain_pending, pending, false);
1984
+ if (begin[0] == 0) return;
1815
1985
  var dispatched = false;
1816
- // One pass consumes only completions that existed when it
1817
- // began: a load started by an update handler in THIS pass
1818
- // that finishes while the pass still runs waits for the wake
1819
- // its producer already nudged. That keeps the session
1820
- // journal's event boundaries causal — every result recorded
1821
- // ahead of this wake's event record answers a request from
1822
- // an earlier dispatch, so replay's file-order feed always
1823
- // finds the parked request (see Effects.DrainBoundary).
1824
- var boundary = self.effects.drainBoundary();
1825
- while (self.effects.takeMsgWithin(&boundary)) |msg| {
1826
- self.applyMsg(msg);
1827
- dispatched = true;
1828
- }
1829
- self.publishAudioState(runtime);
1830
- var rebuild_error: ?anyerror = null;
1831
- if (dispatched) {
1832
- self.rebuild(runtime, self.canvas_window_id) catch |err| {
1833
- rebuild_error = err;
1834
- };
1835
- if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1836
- rebuild_error = err;
1837
- };
1838
- } else if (self.installed and
1839
- !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot()))
1840
- {
1841
- // A drained Msg-less video terminal (a handler-less
1842
- // declarative playback's synchronous failure) moved
1843
- // the mirrors after the last build rendered them:
1844
- // re-render the chrome so its controls never keep
1845
- // advertising a playback that is gone.
1846
- self.rebuild(runtime, self.canvas_window_id) catch |err| {
1847
- rebuild_error = err;
1848
- };
1849
- if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1850
- rebuild_error = err;
1851
- };
1852
- }
1853
- // Same tail as `dispatch`, same error-path duty: effect-
1854
- // driven rebuilds settle the hover edges they produced
1855
- // (this path is also public — host-pumped embeds call it
1856
- // directly).
1857
- if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1858
- self.drainHoverMsgs(runtime) catch |err| {
1859
- if (rebuild_error == null) rebuild_error = err;
1860
- };
1861
- }
1862
- if (rebuild_error) |err| return err;
1986
+ for (begin) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
1987
+ .end => break,
1988
+ .bind => self.bindEffectsChannel(runtime),
1989
+ .sync => self.syncModel(runtime, self.canvas_window_id),
1990
+ .capture_drain => {
1991
+ var boundary = self.effects.drainBoundary();
1992
+ while (self.effects.takeMsgWithin(&boundary)) |msg| {
1993
+ self.applyMsg(msg);
1994
+ dispatched = true;
1995
+ }
1996
+ },
1997
+ .audio => self.publishAudioState(runtime),
1998
+ else => @panic("unexpected effect drain action"),
1999
+ };
2000
+ var first_error: ?anyerror = null;
2001
+ try self.executeRebuildPlan(runtime, self.dispatchPlan(.drain_rebuild, dispatched, self.installed), &first_error);
2002
+ try self.settleDispatch(runtime, &first_error);
1863
2003
  }
1864
2004
 
1865
2005
  /// Mirror the effects channel's audio playback state into the
@@ -1901,6 +2041,39 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1901
2041
  runtime.video_height = video.height;
1902
2042
  }
1903
2043
 
2044
+ const ThemeControl = struct { mode: u8, follows_system: bool, derives: bool };
2045
+
2046
+ fn themeControl(self: *const Self, scheme: ThemeColorScheme) ThemeControl {
2047
+ const full_tokens = self.options.tokens_fn != null or self.options.tokens != null;
2048
+ if (self.options.theme_policy) |policy| {
2049
+ const request = [_]u8{ 2, @intFromBool(self.options.tokens_fn != null), @intFromBool(self.options.tokens != null), @intFromBool(self.options.theme_state_fn != null), themeSchemeByte(scheme), @intFromBool(self.options.token_overrides_fn != null) };
2050
+ var result: [4]u8 = undefined;
2051
+ if (policy(&request, &result) != result.len or result[0] > 2 or result[1] > 1 or result[2] > 1) @panic("invalid compiled theme control result");
2052
+ return .{ .mode = result[0], .follows_system = result[1] == 1, .derives = result[2] == 1 };
2053
+ }
2054
+ const follows = !full_tokens and (self.options.theme_state_fn == null or scheme == .system);
2055
+ return .{
2056
+ .mode = if (self.options.tokens_fn != null) 1 else if (self.options.tokens != null) 2 else 0,
2057
+ .follows_system = follows,
2058
+ .derives = self.options.tokens_fn != null or self.options.theme_state_fn != null or self.options.token_overrides_fn != null or follows,
2059
+ };
2060
+ }
2061
+
2062
+ fn themeSchemeByte(scheme: ThemeColorScheme) u8 {
2063
+ return switch (scheme) {
2064
+ .system => 0,
2065
+ .light => 1,
2066
+ .dark => 2,
2067
+ };
2068
+ }
2069
+
2070
+ fn themePackByte(pack: canvas.ThemePack) u8 {
2071
+ return switch (pack) {
2072
+ .house => 1,
2073
+ .geist => 2,
2074
+ };
2075
+ }
2076
+
1904
2077
  /// The design tokens for the next rebuild: the model-derived
1905
2078
  /// `tokens_fn`, explicit static `tokens`, or — the default — the
1906
2079
  /// stock theme derived from the SYSTEM appearance the runtime
@@ -1910,42 +2083,105 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1910
2083
  /// appearance, the runtime owns the device scale — so static
1911
2084
  /// tokens snap hairlines against the real surface density too.
1912
2085
  pub fn effectiveTokens(self: *const Self) canvas.DesignTokens {
1913
- if (self.options.tokens_fn) |tokens_fn| {
1914
- var tokens = tokens_fn(&self.model);
1915
- tokens.pixel_snap.scale = self.pixel_snap_scale;
1916
- return tokens;
1917
- }
1918
- if (self.options.tokens) |static_tokens| {
1919
- var tokens = static_tokens;
2086
+ const control = self.themeControl(.system);
2087
+ if (control.mode != 0) {
2088
+ var tokens = switch (control.mode) {
2089
+ 1 => self.options.tokens_fn.?(&self.model),
2090
+ 2 => self.options.tokens.?,
2091
+ else => unreachable,
2092
+ };
1920
2093
  tokens.pixel_snap.scale = self.pixel_snap_scale;
2094
+ tokens.surface_layout_policy = self.options.surface_layout_policy;
2095
+ tokens.grid_layout_policy = self.options.grid_layout_policy;
2096
+ tokens.container_layout_policy = self.options.container_layout_policy;
2097
+ tokens.intrinsic_layout_policy = self.options.intrinsic_layout_policy;
2098
+ tokens.measurement_coordination_policy = self.options.measurement_coordination_policy;
2099
+ tokens.flow_measurement_policy = self.options.flow_measurement_policy;
2100
+ tokens.layout_coordination_policy = self.options.layout_coordination_policy;
2101
+ tokens.render_coordination_policy = self.options.render_coordination_policy;
2102
+ tokens.control_command_policy = self.options.control_command_policy;
2103
+ tokens.widget_motion_policy = self.options.widget_motion_policy;
2104
+ tokens.widget_audit_policy = self.options.widget_audit_policy;
2105
+ tokens.accessibility_policy = self.options.accessibility_policy;
2106
+ tokens.widget_routing_policy = self.options.widget_routing_policy;
2107
+ tokens.widget_change_policy = self.options.widget_change_policy;
2108
+ tokens.widget_paint_policy = self.options.widget_paint_policy;
2109
+ tokens.widget_presentation_policy = self.options.widget_presentation_policy;
2110
+ tokens.widget_paint_walk_policy = self.options.widget_paint_walk_policy;
2111
+ tokens.terminal_paint_policy = self.options.terminal_paint_policy;
2112
+ tokens.control_geometry_policy = self.options.control_geometry_policy;
2113
+ tokens.code_content_policy = self.options.code_content_policy;
2114
+ tokens.paragraph_policy = self.options.paragraph_policy;
2115
+ tokens.text_run_policy = self.options.text_run_policy;
1921
2116
  return tokens;
1922
2117
  }
1923
2118
  const state = self.currentThemeState();
1924
- const color_scheme: canvas.ColorScheme = switch (state.color_scheme) {
1925
- .system => switch (self.system_appearance.color_scheme) {
2119
+ const high_contrast = state.high_contrast orelse self.system_appearance.high_contrast;
2120
+ const reduce_motion = state.reduce_motion orelse self.system_appearance.reduce_motion;
2121
+ // Preserve lazy legacy helper evaluation when a model pack exists.
2122
+ const fallback_pack = if (state.pack == null and self.options.theme_fn != null) self.options.theme_fn.?(&self.model) else self.options.theme;
2123
+ var pack: canvas.ThemePack = undefined;
2124
+ var color_scheme: canvas.ColorScheme = undefined;
2125
+ var accent: ?canvas.Color = undefined;
2126
+ if (self.options.theme_policy) |policy| {
2127
+ const request = [_]u8{
2128
+ 1, if (state.pack) |value| themePackByte(value) else 0, themePackByte(fallback_pack),
2129
+ themeSchemeByte(state.color_scheme), @intFromBool(self.system_appearance.color_scheme == .dark), @intFromBool(high_contrast),
2130
+ @intFromBool(state.accent != null), @intFromBool(self.options.theme_accent != null),
2131
+ };
2132
+ var result: [4]u8 = undefined;
2133
+ if (policy(&request, &result) != result.len or result[0] < 1 or result[0] > 2 or result[1] > 1 or result[2] > 2) @panic("invalid compiled stock theme result");
2134
+ pack = if (result[0] == 1) .house else .geist;
2135
+ color_scheme = if (result[1] == 0) .light else .dark;
2136
+ accent = switch (result[2]) {
2137
+ 0 => null,
2138
+ 1 => state.accent.?,
2139
+ 2 => self.options.theme_accent.?,
2140
+ else => unreachable,
2141
+ };
2142
+ } else {
2143
+ pack = state.pack orelse fallback_pack;
2144
+ color_scheme = switch (state.color_scheme) {
2145
+ .system => switch (self.system_appearance.color_scheme) {
2146
+ .light => .light,
2147
+ .dark => .dark,
2148
+ },
1926
2149
  .light => .light,
1927
2150
  .dark => .dark,
1928
- },
1929
- .light => .light,
1930
- .dark => .dark,
1931
- };
2151
+ };
2152
+ accent = if (high_contrast) null else state.accent orelse self.options.theme_accent;
2153
+ }
1932
2154
  var tokens = canvas.DesignTokens.theme(.{
1933
2155
  .color_scheme = color_scheme,
1934
- .contrast = if (self.system_appearance.high_contrast) .high else .standard,
1935
- .reduce_motion = self.system_appearance.reduce_motion,
1936
- .pack = state.pack orelse if (self.options.theme_fn) |theme_fn| theme_fn(&self.model) else self.options.theme,
2156
+ .contrast = if (high_contrast) .high else .standard,
2157
+ .reduce_motion = reduce_motion,
2158
+ .pack = pack,
1937
2159
  });
1938
- if (state.accent orelse self.options.theme_accent) |accent| {
1939
- // The manifest accent layers over the resolved pack —
1940
- // except under high contrast, where the pack's own loud
1941
- // register wins untouched (accessibility beats brand).
1942
- // The bundle takes the resolved scheme: the dark ring
1943
- // derives desaturated (canvas.accentFocusRing).
1944
- if (!self.system_appearance.high_contrast) {
1945
- tokens = tokens.withOverrides(canvas.accentOverrides(accent, color_scheme));
1946
- }
1947
- }
2160
+ if (accent) |value| tokens = tokens.withOverrides(canvas.accentOverrides(value, color_scheme));
2161
+ if (self.options.token_overrides_fn) |overrides| tokens = tokens.withOverrides(overrides(&self.model));
1948
2162
  tokens.pixel_snap.scale = self.pixel_snap_scale;
2163
+ tokens.surface_layout_policy = self.options.surface_layout_policy;
2164
+ tokens.grid_layout_policy = self.options.grid_layout_policy;
2165
+ tokens.container_layout_policy = self.options.container_layout_policy;
2166
+ tokens.intrinsic_layout_policy = self.options.intrinsic_layout_policy;
2167
+ tokens.measurement_coordination_policy = self.options.measurement_coordination_policy;
2168
+ tokens.flow_measurement_policy = self.options.flow_measurement_policy;
2169
+ tokens.layout_coordination_policy = self.options.layout_coordination_policy;
2170
+ tokens.render_coordination_policy = self.options.render_coordination_policy;
2171
+ tokens.control_command_policy = self.options.control_command_policy;
2172
+ tokens.widget_motion_policy = self.options.widget_motion_policy;
2173
+ tokens.widget_audit_policy = self.options.widget_audit_policy;
2174
+ tokens.accessibility_policy = self.options.accessibility_policy;
2175
+ tokens.widget_routing_policy = self.options.widget_routing_policy;
2176
+ tokens.widget_change_policy = self.options.widget_change_policy;
2177
+ tokens.widget_paint_policy = self.options.widget_paint_policy;
2178
+ tokens.widget_presentation_policy = self.options.widget_presentation_policy;
2179
+ tokens.widget_paint_walk_policy = self.options.widget_paint_walk_policy;
2180
+ tokens.terminal_paint_policy = self.options.terminal_paint_policy;
2181
+ tokens.control_geometry_policy = self.options.control_geometry_policy;
2182
+ tokens.code_content_policy = self.options.code_content_policy;
2183
+ tokens.paragraph_policy = self.options.paragraph_policy;
2184
+ tokens.text_run_policy = self.options.text_run_policy;
1949
2185
  return tokens;
1950
2186
  }
1951
2187
 
@@ -1961,7 +2197,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1961
2197
  // Complete-token paths outrank the stock-theme helper entirely.
1962
2198
  // Do not even validate an unused model accent: the app has
1963
2199
  // explicitly claimed the whole DesignTokens register.
1964
- if (self.options.tokens_fn != null or self.options.tokens != null) {
2200
+ if (self.themeControl(.system).mode != 0) {
1965
2201
  self.theme_state = .{};
1966
2202
  self.theme_state_known = true;
1967
2203
  return;
@@ -1995,15 +2231,18 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1995
2231
  /// true only when the app claims neither token override, so an
1996
2232
  /// appearance flip must re-derive and re-render.
1997
2233
  fn followsSystemAppearance(self: *const Self) bool {
1998
- if (self.options.tokens_fn != null or self.options.tokens != null) return false;
1999
- if (self.options.theme_state_fn == null) return true;
2000
- return self.currentThemeState().color_scheme == .system;
2234
+ // Preserve the reference helper's lazy evaluation and call count.
2235
+ const scheme = if (self.options.tokens_fn == null and self.options.tokens == null and self.options.theme_state_fn != null)
2236
+ self.currentThemeState().color_scheme
2237
+ else
2238
+ ThemeColorScheme.system;
2239
+ return self.themeControl(scheme).follows_system;
2001
2240
  }
2002
2241
 
2003
2242
  /// Whether tokens are derived per rebuild (model-owned or
2004
2243
  /// system-followed) rather than a fixed set.
2005
2244
  fn derivesTokens(self: *const Self) bool {
2006
- return self.options.tokens_fn != null or self.options.theme_state_fn != null or self.followsSystemAppearance();
2245
+ return self.themeControl(.system).derives;
2007
2246
  }
2008
2247
 
2009
2248
  /// Whether a rebuild must push its tokens into the runtime's
@@ -2053,6 +2292,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2053
2292
  /// window converges within the same rebuild instead of waiting
2054
2293
  /// for the next Msg.
2055
2294
  pub fn rebuild(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
2295
+ for (runtime.windows[0..runtime.window_count]) |window| {
2296
+ if (window.info.id == window_id and !window.info.open) {
2297
+ // The app and secondary windows survive a closed primary
2298
+ // canvas. Continue declaration reconciliation without
2299
+ // installing a tree into the removed native surface.
2300
+ self.tree = null;
2301
+ self.main_tree_current = false;
2302
+ self.releaseContextMenuSnapshotForWindow(window_id);
2303
+ try self.refreshThemeState();
2304
+ self.applyStatusItem(runtime);
2305
+ self.applyWindows(runtime);
2306
+ return;
2307
+ }
2308
+ }
2056
2309
  self.syncModel(runtime, window_id);
2057
2310
  try self.refreshThemeState();
2058
2311
  if (comptime features.runtime_markup) {
@@ -2107,7 +2360,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2107
2360
  // Apps whose headers already pad through the chrome
2108
2361
  // channel's insets never collide, never retry, and keep a
2109
2362
  // byte-identical layout.
2110
- if (windowControlsReservation(runtime, window_id, self.options.canvas_label, built.layout, tokens)) |controls| {
2363
+ if (try windowControlsReservation(runtime, window_id, self.options.canvas_label, built.layout, tokens)) |controls| {
2111
2364
  tokens.window_controls = controls;
2112
2365
  built = try self.buildLayoutPass(runtime, window_id, bounds, tokens, next_index);
2113
2366
  }
@@ -2155,7 +2408,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2155
2408
  // The fallback menu's target vanished from this build (the
2156
2409
  // model dropped the row, or its menu emptied): the open state
2157
2410
  // has nothing to present, so it closes.
2158
- if (self.contextMenuFallbackTargetForLabel(self.options.canvas_label) != 0 and tree.context_menu_fallback == null) {
2411
+ if (self.componentDecision(.fallback_vanished, self.contextMenuFallbackTargetForLabel(self.options.canvas_label) != 0, tree.context_menu_fallback != null, false) != 0) {
2159
2412
  self.clearContextMenuFallback();
2160
2413
  }
2161
2414
  try self.scheduleAnimations(runtime, window_id);
@@ -2220,9 +2473,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2220
2473
  const content_height = @max(0, frame.height - inset.top - inset.bottom);
2221
2474
  const metrics = canvas.terminalCellMetrics(tokens);
2222
2475
  if (metrics.width <= 0 or metrics.height <= 0) continue;
2223
- const proposed = canvas.clampTerminalGrid(
2476
+ const proposed = canvas.terminal_grid.clampGridWithPolicy(
2224
2477
  @intFromFloat(@max(2, @floor(content_width / metrics.width))),
2225
2478
  @intFromFloat(@max(2, @floor(content_height / metrics.height))),
2479
+ tokens.terminal_paint_policy,
2226
2480
  );
2227
2481
  const state = self.terminal_sessions.reconcile(
2228
2482
  pty,
@@ -2329,6 +2583,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2329
2583
  std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != null or pin.arena_index != next_index else true);
2330
2584
  _ = self.arenas[next_index].reset(.retain_capacity);
2331
2585
  var ui = Ui.init(self.arenas[next_index].allocator());
2586
+ ui.composition_policy = self.options.composition_policy;
2587
+ ui.code_content_policy = self.options.code_content_policy;
2588
+ ui.chart_content_policy = self.options.chart_content_policy;
2589
+ ui.markdown_content_policy = self.options.markdown_content_policy;
2590
+ ui.construction_policy = self.options.construction_policy;
2332
2591
  // The house video chrome renders the channel's honest
2333
2592
  // snapshot, stamped before the view fn runs — the model
2334
2593
  // carries none of it.
@@ -2339,10 +2598,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2339
2598
  // driving the palette's theme mapping.
2340
2599
  self.terminal_sessions.beginBuild(tokens);
2341
2600
  ui.terminal_lookup = self.terminal_sessions.lookup();
2601
+ ui.pty_key_resolver = self.options.pty_key_resolver;
2342
2602
  ui.virtual_window_context = @ptrCast(&window_source);
2343
2603
  ui.virtual_window_source = VirtualWindowResolver.resolve;
2344
2604
  ui.virtual_extent_context = @ptrCast(self);
2345
2605
  ui.virtual_extent_source = virtualExtentResolve;
2606
+ ui.virtual_extent_policy = self.options.intrinsic_layout_policy;
2346
2607
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(self.options.canvas_label);
2347
2608
  if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
2348
2609
  self.armUiFragmentHost(&ui);
@@ -2426,7 +2687,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2426
2687
  /// cluster. `tokens` must be the tokens the layout was built
2427
2688
  /// with: the scan re-measures text through the same seam to
2428
2689
  /// judge painted bounds, not frames.
2429
- fn windowControlsReservation(runtime: *Runtime, window_id: platform.WindowId, canvas_label: []const u8, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) ?geometry.RectF {
2690
+ fn windowControlsReservation(runtime: *Runtime, window_id: platform.WindowId, canvas_label: []const u8, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) !?geometry.RectF {
2430
2691
  var has_drag_region = false;
2431
2692
  for (layout.nodes) |node| {
2432
2693
  if (canvas.widgetIsWindowDragRegion(node.widget)) {
@@ -2435,7 +2696,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2435
2696
  }
2436
2697
  }
2437
2698
  if (!has_drag_region) return null;
2438
- const controls = runtime.windowControlsForView(window_id, canvas_label);
2699
+ const controls = try runtime.windowControlsForView(window_id, canvas_label);
2439
2700
  if (controls.width <= 0 or controls.height <= 0) return null;
2440
2701
  if (!canvas.windowDragContentUnderWindowControls(layout.nodes, controls, tokens)) return null;
2441
2702
  return controls;
@@ -2548,7 +2809,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2548
2809
  if (record.item_count == 0) continue;
2549
2810
  const offset = @max(0, node.widget.value);
2550
2811
  const first_visible = table.indexAtOffset(offset);
2551
- const visible_end = @min(record.item_count, table.indexAtOffset(offset + viewport.height) + 1);
2812
+ const end_probe = table.indexAtOffset(offset + viewport.height);
2813
+ if (self.options.intrinsic_layout_policy) |policy| {
2814
+ if (canvas.virtual_extent_policy.undercovered(policy, record.item_count, first_visible, end_probe, record.overscan, record.start_index, record.end_index)) return true;
2815
+ continue;
2816
+ }
2817
+ const visible_end = @min(record.item_count, end_probe + 1);
2552
2818
  const start = if (first_visible > record.overscan) first_visible - record.overscan else 0;
2553
2819
  const end = @min(record.item_count, visible_end + record.overscan);
2554
2820
  if (start < record.start_index or end > record.end_index) return true;
@@ -2590,6 +2856,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2590
2856
  }
2591
2857
 
2592
2858
  fn claimVirtualExtentTable(self: *Self, id: canvas.ObjectId) ?*canvas.VirtualExtentTable {
2859
+ if (self.options.intrinsic_layout_policy) |policy| {
2860
+ const decision = canvas.virtual_extent_policy.slot(policy, id, &self.virtual_extent_tables, self.virtual_windows[0..self.virtual_window_count]);
2861
+ if (decision) |plan| {
2862
+ const table = &self.virtual_extent_tables[plan.index];
2863
+ if (plan.recycle) table.reset();
2864
+ table.policy = policy;
2865
+ return table;
2866
+ }
2867
+ if (id != 0) ui_app_log.warn("variable-extent virtual list table budget exhausted; using estimates without measured corrections", .{});
2868
+ return null;
2869
+ }
2593
2870
  if (id == 0) return null;
2594
2871
  for (&self.virtual_extent_tables) |*table| {
2595
2872
  if (table.id == id) return table;
@@ -2646,15 +2923,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2646
2923
  // the pending offset by however much the batch moves
2647
2924
  // that edge, and the anchored row stays under the
2648
2925
  // user's eyes.
2649
- table.beginCorrections(list_node.widget.layout.virtual_anchor_index, null);
2926
+ var measurements: std.ArrayList(canvas.VirtualExtentMeasurement) = .empty;
2927
+ defer measurements.deinit(std.heap.page_allocator);
2650
2928
  for (layout.nodes) |node| {
2651
2929
  const parent = node.parent_index orelse continue;
2652
2930
  if (parent != list_index) continue;
2653
2931
  if (node.widget.layout.anchor != null) continue;
2654
2932
  const physical = node.widget.semantics.list_item_index orelse continue;
2655
- table.recordMeasured(@intCast(physical), node.frame.normalized().height);
2933
+ measurements.append(std.heap.page_allocator, .{ .physical = @intCast(physical), .extent = node.frame.normalized().height }) catch @panic("virtual row measurement allocation failed");
2656
2934
  }
2657
- table.endCorrections();
2935
+ table.applyMeasurements(list_node.widget.layout.virtual_anchor_index, null, measurements.items);
2658
2936
  if (@abs(table.pending_offset_delta) > virtual_correction_retry_threshold) corrected = true;
2659
2937
  }
2660
2938
  return corrected;
@@ -2679,25 +2957,6 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2679
2957
  axis: canvas.ScrollAxis = .vertical,
2680
2958
  };
2681
2959
 
2682
- const ReachAxis = struct {
2683
- state: canvas.ScrollAxisState,
2684
- axis: canvas.ScrollAxis,
2685
- };
2686
-
2687
- /// The axis reach-end/reach-start measure: the vertical axis
2688
- /// wherever it has scrollable range (every pre-axis region, so
2689
- /// existing apps see identical behavior), otherwise the
2690
- /// horizontal one — a horizontal timeline's `on-reach-end` is
2691
- /// its right edge. One rule for both signals so "the end" and
2692
- /// "the start" always name the same axis.
2693
- fn reachAxisState(scroll_state: canvas.ScrollState) ReachAxis {
2694
- const vertical = scroll_state.axis(.vertical);
2695
- if (vertical.maxOffset() > 0) return .{ .state = vertical, .axis = .vertical };
2696
- const horizontal = scroll_state.axis(.horizontal);
2697
- if (horizontal.maxOffset() > 0) return .{ .state = horizontal, .axis = .horizontal };
2698
- return .{ .state = vertical, .axis = .vertical };
2699
- }
2700
-
2701
2960
  /// Approach-end hysteresis (`on_reach_end`): fire when a scroll
2702
2961
  /// lands within `reach_end_fire_ratio` viewports of the content
2703
2962
  /// end and the region is armed; re-arm once the offset sits more
@@ -2705,22 +2964,24 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2705
2964
  /// appending a batch causes on its own, since the extent grows
2706
2965
  /// under the unchanged offset. One Msg per approach, never a
2707
2966
  /// fetch storm from a user riding the end of the list.
2708
- fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
2709
- const reach = reachAxisState(scroll_state);
2710
- const axis_state = reach.state;
2711
- if (id == 0 or axis_state.viewport_extent <= 0) return false;
2712
- const remaining = axis_state.content_extent - axis_state.viewport_extent - axis_state.offset;
2713
- if (remaining > axis_state.viewport_extent * reach_end_rearm_ratio) {
2714
- self.clearReachEndFired(id, reach.axis);
2715
- return false;
2967
+ fn applyReachPlan(self: *Self, start: bool, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
2968
+ const vertical_fired = if (start) self.reachStartFired(id, .vertical) else self.reachEndFired(id, .vertical);
2969
+ const horizontal_fired = if (start) self.reachStartFired(id, .horizontal) else self.reachEndFired(id, .horizontal);
2970
+ const plan = component_policy.reach(self.options.component_policy, start, id != 0, scroll_state, vertical_fired, horizontal_fired);
2971
+ const axis: canvas.ScrollAxis = if (plan.horizontal) .horizontal else .vertical;
2972
+ switch (plan.action) {
2973
+ .none => return false,
2974
+ .clear => {
2975
+ if (start) self.clearReachStartFired(id, axis) else self.clearReachEndFired(id, axis);
2976
+ return false;
2977
+ },
2978
+ // Dispatch only after a native latch slot was actually stored.
2979
+ .store => return if (start) self.markReachStartFired(id, axis) else self.markReachEndFired(id, axis),
2716
2980
  }
2717
- if (remaining > axis_state.viewport_extent * reach_end_fire_ratio) return false;
2718
- if (self.reachEndFired(id, reach.axis)) return false;
2719
- // Fire only when the latch STORES: an unstorable latch
2720
- // (table full — a degenerate tree) would otherwise fire on
2721
- // every observation, the exact storm the hysteresis exists
2722
- // to prevent. Silence is the safer failure.
2723
- return self.markReachEndFired(id, reach.axis);
2981
+ }
2982
+
2983
+ fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
2984
+ return self.applyReachPlan(false, id, scroll_state);
2724
2985
  }
2725
2986
 
2726
2987
  fn reachEndFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
@@ -2757,18 +3018,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2757
3018
  /// only moves on scroll OBSERVATIONS, so a programmatic jump out
2758
3019
  /// of the band re-arms on the next user scroll, not instantly.
2759
3020
  fn reachStartShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
2760
- const reach = reachAxisState(scroll_state);
2761
- const axis_state = reach.state;
2762
- if (id == 0 or axis_state.viewport_extent <= 0) return false;
2763
- const remaining = axis_state.offset;
2764
- if (remaining > axis_state.viewport_extent * reach_start_rearm_ratio) {
2765
- self.clearReachStartFired(id, reach.axis);
2766
- return false;
2767
- }
2768
- if (remaining > axis_state.viewport_extent * reach_start_fire_ratio) return false;
2769
- if (self.reachStartFired(id, reach.axis)) return false;
2770
- // Fire only when the latch stores (the reach-end rule).
2771
- return self.markReachStartFired(id, reach.axis);
3021
+ return self.applyReachPlan(true, id, scroll_state);
2772
3022
  }
2773
3023
 
2774
3024
  fn reachStartFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
@@ -2810,6 +3060,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2810
3060
  declared = declared[0..max_ui_windows];
2811
3061
  }
2812
3062
 
3063
+ if (self.options.window_policy != null) {
3064
+ self.applyCompiledWindows(runtime, declared) catch |err| {
3065
+ ui_app_log.warn("window reconciliation failed: {s}", .{@errorName(err)});
3066
+ };
3067
+ return;
3068
+ }
3069
+
2813
3070
  // Close first: a label leaving the declared set frees its
2814
3071
  // slot (and its runtime window label) before creations run.
2815
3072
  var index: usize = 0;
@@ -2831,6 +3088,77 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2831
3088
  }
2832
3089
  }
2833
3090
 
3091
+ fn writeWindowPolicyLabel(writer: *std.Io.Writer, label: []const u8) !void {
3092
+ if (label.len > std.math.maxInt(u32)) return error.WindowPolicyLabelTooLong;
3093
+ try writer.writeInt(u32, @intCast(label.len), .little);
3094
+ try writer.writeAll(label);
3095
+ }
3096
+
3097
+ /// Each decision sees the current ordered slots, including the swap
3098
+ /// after a close and only successful OS creates. Copy the complete
3099
+ /// request before entering scriptc; keep all descriptor bytes alive.
3100
+ fn windowPolicyDecision(self: *Self, declared: []const WindowDescriptor, descriptor: ?WindowDescriptor) ![2]u8 {
3101
+ comptime {
3102
+ std.debug.assert(max_ui_windows == 4);
3103
+ std.debug.assert(platform.max_window_label_bytes == 64);
3104
+ std.debug.assert(app_manifest.max_view_label_bytes == 64);
3105
+ }
3106
+ var request = std.Io.Writer.Allocating.init(self.backing);
3107
+ defer request.deinit();
3108
+ const writer = &request.writer;
3109
+ try writer.writeByte(@intFromBool(descriptor != null));
3110
+ if (descriptor) |value| {
3111
+ try writeWindowPolicyLabel(writer, self.options.canvas_label);
3112
+ try writeWindowPolicyLabel(writer, value.label);
3113
+ try writeWindowPolicyLabel(writer, value.canvas_label);
3114
+ } else {
3115
+ try writer.writeByte(@intCast(declared.len));
3116
+ for (declared) |value| try writeWindowPolicyLabel(writer, value.label);
3117
+ }
3118
+ try writer.writeByte(@intCast(self.window_slot_count));
3119
+ for (self.window_slots[0..self.window_slot_count]) |*slot| {
3120
+ try writeWindowPolicyLabel(writer, slot.label());
3121
+ try writeWindowPolicyLabel(writer, slot.canvasLabel());
3122
+ }
3123
+ var result: [2]u8 = undefined;
3124
+ if (self.options.window_policy.?(request.written(), &result) != result.len or
3125
+ result[0] > 4 or (result[1] != 255 and result[1] >= self.window_slot_count))
3126
+ @panic("invalid compiled window policy result");
3127
+ if (descriptor == null) {
3128
+ if (result[0] != 0) @panic("invalid compiled window retirement result");
3129
+ } else if ((result[0] == 1) == (result[1] == 255)) {
3130
+ @panic("invalid compiled window declaration result");
3131
+ }
3132
+ return result;
3133
+ }
3134
+
3135
+ fn applyCompiledWindows(self: *Self, runtime: *Runtime, declared: []const WindowDescriptor) !void {
3136
+ while (true) {
3137
+ const plan = try self.windowPolicyDecision(declared, null);
3138
+ if (plan[1] == 255) break;
3139
+ self.closeWindowSlot(runtime, plan[1]);
3140
+ }
3141
+ for (declared) |descriptor| {
3142
+ const plan = try self.windowPolicyDecision(&.{}, descriptor);
3143
+ switch (plan[0]) {
3144
+ 0 => {
3145
+ // Bound native copies even if a custom callback violates
3146
+ // the ABI. Lookup/collision decisions belong to policy.
3147
+ if (self.window_slot_count >= max_ui_windows or
3148
+ descriptor.label.len == 0 or descriptor.label.len > platform.max_window_label_bytes or
3149
+ descriptor.canvas_label.len == 0 or descriptor.canvas_label.len > app_manifest.max_view_label_bytes)
3150
+ @panic("invalid compiled window creation result");
3151
+ self.openWindowSlot(runtime, descriptor);
3152
+ },
3153
+ 1 => self.setWindowSlotOnClose(&self.window_slots[plan[1]], descriptor.on_close),
3154
+ 2 => ui_app_log.warn("declared window '{s}' ignored: more than {d} secondary windows (canvas_limits.max_ui_app_windows)", .{ descriptor.label, max_ui_windows }),
3155
+ 3 => ui_app_log.warn("declared window '{s}' ignored: window and canvas labels must be non-empty and fit the platform label budgets", .{descriptor.label}),
3156
+ 4 => ui_app_log.warn("declared window '{s}' ignored: canvas label '{s}' is already bound - every window's canvas label must be unique", .{ descriptor.label, descriptor.canvas_label }),
3157
+ else => unreachable,
3158
+ }
3159
+ }
3160
+ }
3161
+
2834
3162
  fn declaredWindowIndex(declared: []const WindowDescriptor, label: []const u8) ?usize {
2835
3163
  for (declared, 0..) |descriptor, index| {
2836
3164
  if (std.mem.eql(u8, descriptor.label, label)) return index;
@@ -2881,6 +3209,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2881
3209
  return;
2882
3210
  }
2883
3211
 
3212
+ self.openWindowSlot(runtime, descriptor);
3213
+ }
3214
+
3215
+ /// Native capability boundary: create the shell, then retain its
3216
+ /// labels, close message, tree arenas and GPU state only on success.
3217
+ fn openWindowSlot(self: *Self, runtime: *Runtime, descriptor: WindowDescriptor) void {
2884
3218
  const shell_views = [_]app_manifest.ShellView{self.secondaryShellView(descriptor)};
2885
3219
  const info = runtime.createSourcelessShellWindow(.{
2886
3220
  .label = descriptor.label,
@@ -3047,7 +3381,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3047
3381
  // exactly like the main window's, so a proven collision
3048
3382
  // stamps the cluster into THIS slot's tokens (a local copy —
3049
3383
  // other windows keep their own layout) for one more pass.
3050
- if (windowControlsReservation(runtime, slot.window_id, slot.canvasLabel(), built.layout, tokens)) |controls| {
3384
+ if (try windowControlsReservation(runtime, slot.window_id, slot.canvasLabel(), built.layout, tokens)) |controls| {
3051
3385
  tokens.window_controls = controls;
3052
3386
  built = try self.buildWindowSlotPass(slot, bounds, tokens, next_index);
3053
3387
  }
@@ -3075,7 +3409,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3075
3409
  runtime.recordDispatchError("hover_leave_capture", refresh_err);
3076
3410
  }
3077
3411
  // Same close-on-vanish rule as the main canvas rebuild.
3078
- if (self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0 and tree.context_menu_fallback == null) {
3412
+ if (self.componentDecision(.fallback_vanished, self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0, tree.context_menu_fallback != null, false) != 0) {
3079
3413
  self.clearContextMenuFallback();
3080
3414
  }
3081
3415
  // Reconcile the video declaration THIS build recorded or
@@ -3170,6 +3504,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3170
3504
  std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != slot.window_id or pin.arena_index != next_index else true);
3171
3505
  _ = slot.arenas[next_index].reset(.retain_capacity);
3172
3506
  var ui = Ui.init(slot.arenas[next_index].allocator());
3507
+ ui.composition_policy = self.options.composition_policy;
3508
+ ui.code_content_policy = self.options.code_content_policy;
3509
+ ui.chart_content_policy = self.options.chart_content_policy;
3510
+ ui.markdown_content_policy = self.options.markdown_content_policy;
3511
+ ui.construction_policy = self.options.construction_policy;
3173
3512
  // Window views render the same honest video chrome state,
3174
3513
  // and their `<video src>` declarations reconcile the channel
3175
3514
  // too — `Ui.video` promises that declaring the element IS
@@ -3182,6 +3521,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3182
3521
  // key, whichever tree binds it.
3183
3522
  self.terminal_sessions.beginBuild(tokens);
3184
3523
  ui.terminal_lookup = self.terminal_sessions.lookup();
3524
+ ui.pty_key_resolver = self.options.pty_key_resolver;
3185
3525
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(slot.canvasLabel());
3186
3526
  if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
3187
3527
  self.armUiFragmentHost(&ui);
@@ -3308,21 +3648,37 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3308
3648
  /// runtime then regenerates the widget span on internal state
3309
3649
  /// changes while preserving the chrome via
3310
3650
  /// `emitCanvasWidgetDisplayListWithChrome`.
3651
+ // Zig-core compatibility for the original combined chrome callback.
3652
+ // Compiled cores always install the TypeScript composition owner.
3653
+ fn nativeChromePlan(chrome: ChromeOptions, count: usize, before: ?usize) error{InvalidChromeCommandCount}!canvas.render_coordination_policy.ChromePlan {
3654
+ const prefix = before orelse blk: {
3655
+ if (count < chrome.suffix_commands) return error.InvalidChromeCommandCount;
3656
+ break :blk count - chrome.suffix_commands;
3657
+ };
3658
+ if (prefix > count or (chrome.variable_prefix and prefix > chrome.prefix_commands) or
3659
+ (!chrome.variable_prefix and prefix != chrome.prefix_commands)) return error.InvalidChromeCommandCount;
3660
+ const suffix = count - prefix;
3661
+ if (before != null and suffix > chrome.suffix_commands) return error.InvalidChromeCommandCount;
3662
+ return .{ .prefix = prefix, .suffix = suffix };
3663
+ }
3664
+
3311
3665
  fn installChromeDisplayList(self: *Self, runtime: *Runtime, window_id: platform.WindowId, chrome: ChromeOptions, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) anyerror!void {
3312
3666
  var chrome_commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
3313
3667
  var chrome_builder = canvas.Builder.init(&chrome_commands);
3314
3668
  try chrome.build(&self.model, &chrome_builder, self.canvas_size, tokens);
3669
+ var before_suffix: ?usize = null;
3670
+ if (chrome.build_suffix) |build_suffix| {
3671
+ before_suffix = chrome_builder.displayList().commands.len;
3672
+ try build_suffix(&self.model, &chrome_builder, self.canvas_size, tokens);
3673
+ }
3674
+ const count = chrome_builder.displayList().commands.len;
3675
+ const plan = if (self.options.render_coordination_policy) |policy|
3676
+ try canvas.render_coordination_policy.ChromePlan.init(policy, chrome.prefix_commands, chrome.suffix_commands, count, before_suffix, chrome.variable_prefix)
3677
+ else
3678
+ try nativeChromePlan(chrome, count, before_suffix);
3679
+ const prefix_len = plan.prefix;
3680
+ const suffix_len = plan.suffix;
3315
3681
  const chrome_list = chrome_builder.displayList();
3316
- if (chrome.variable_prefix) {
3317
- if (chrome_list.commands.len < chrome.suffix_commands or
3318
- chrome_list.commands.len - chrome.suffix_commands > chrome.prefix_commands)
3319
- {
3320
- return error.InvalidChromeCommandCount;
3321
- }
3322
- } else if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
3323
- return error.InvalidChromeCommandCount;
3324
- }
3325
- const prefix_len = chrome_list.commands.len - chrome.suffix_commands;
3326
3682
 
3327
3683
  var commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
3328
3684
  var builder = canvas.Builder.init(&commands);
@@ -3338,7 +3694,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3338
3694
  try self.publishWidgetLayoutTracked(runtime, window_id, self.options.canvas_label, layout, &self.main_tree_current);
3339
3695
  _ = try runtime.emitCanvasWidgetDisplayListWithChrome(window_id, self.options.canvas_label, tokens, .{
3340
3696
  .prefix_command_count = prefix_len,
3341
- .suffix_command_count = chrome.suffix_commands,
3697
+ .suffix_command_count = suffix_len,
3342
3698
  });
3343
3699
  }
3344
3700
 
@@ -3407,6 +3763,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3407
3763
  const sources: []const canvas.ui_markup.SourceFile = if (self.options.markup) |markup_options| markup_options.sources else &.{};
3408
3764
  var set_loader = canvas.ui_markup.SourceSetLoader{ .set = sources };
3409
3765
  var hashing = HashingLoader.init(set_loader.loader(), source, "");
3766
+ hashing.policy = self.options.markup_development_policy;
3410
3767
  if (comptime features.runtime_markup) {
3411
3768
  self.provenance_closure.reset();
3412
3769
  hashing.closure = &self.provenance_closure;
@@ -3417,11 +3774,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3417
3774
  const owned_source = try arena.dupe(u8, source);
3418
3775
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3419
3776
  const document = canvas.ui_markup.resolveImports(arena, "", owned_source, hashing.loader(), &diagnostic) catch |err| {
3420
- if (err == error.MarkupSyntax or err == error.MarkupImport) self.recordMarkupDiagnostic(diagnostic);
3777
+ if (self.options.markup_development_policy) |callback| {
3778
+ const program = markup_development.reload(callback, 0, true, true, err == error.MarkupSyntax or err == error.MarkupImport, false, self.installed);
3779
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
3780
+ .end => break,
3781
+ .diagnostic => self.recordMarkupDiagnostic(diagnostic),
3782
+ else => unreachable,
3783
+ };
3784
+ } else if (err == error.MarkupSyntax or err == error.MarkupImport) self.recordMarkupDiagnostic(diagnostic);
3421
3785
  return err;
3422
3786
  };
3423
3787
  // The typed-document pass: attribute expressions parse once
3424
3788
  // here instead of on every frame's build.
3789
+ if (self.options.markup_development_policy) |callback| {
3790
+ try self.applyRootMarkupProgram(callback, 0, document, arena, next_index, hashing.hasher.final(), "", owned_source, null, 0);
3791
+ return;
3792
+ }
3425
3793
  const canonical = try canvas.ui_markup.canonicalize(arena, document);
3426
3794
  self.adoptMarkupDocument(canonical, next_index, hashing.hasher.final());
3427
3795
  // Embedded resolve: root nodes carry an empty src_path, and
@@ -3430,6 +3798,21 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3430
3798
  self.commitProvenanceFiles("", owned_source, false);
3431
3799
  }
3432
3800
 
3801
+ fn applyRootMarkupProgram(self: *Self, callback: *const fn ([]const u8, []u8) usize, kind: u8, document: canvas.ui_markup.MarkupDocument, arena: std.mem.Allocator, next_index: usize, hash: u64, path: []const u8, source: []const u8, runtime: ?*Runtime, window_id: platform.WindowId) anyerror!void {
3802
+ const program = markup_development.reload(callback, kind, kind == 0 or hash != self.markup_source_hash, false, false, false, self.installed);
3803
+ var canonical = document;
3804
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
3805
+ .end => break,
3806
+ .canonicalize => canonical = if (kind == 0) try canvas.ui_markup.canonicalize(arena, document) else canvas.ui_markup.canonicalize(arena, document) catch document,
3807
+ .adopt_root => self.adoptMarkupDocument(canonical, next_index, hash),
3808
+ .provenance => self.commitProvenanceFiles(path, source, kind == 1),
3809
+ .rebuild_root => if (runtime) |value| {
3810
+ self.rebuild(value, window_id) catch {};
3811
+ },
3812
+ else => unreachable,
3813
+ };
3814
+ }
3815
+
3433
3816
  /// Activate a resolved document built into `arena_index`'s arena.
3434
3817
  fn adoptMarkupDocument(self: *Self, document: canvas.ui_markup.MarkupDocument, arena_index: usize, closure_hash: u64) void {
3435
3818
  self.markup_view = MarkupView.fromDocument(document);
@@ -3454,6 +3837,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3454
3837
  /// resolver-relative path and content hash is recorded so the
3455
3838
  /// adopt step can commit them as write-back anchors.
3456
3839
  closure: ?*ui_app_provenance.ClosureFiles = null,
3840
+ policy: markup_development.Policy = null,
3457
3841
 
3458
3842
  fn init(inner: canvas.ui_markup.ImportLoader, root_source: []const u8, strip_prefix: []const u8) HashingLoader {
3459
3843
  var hasher = std.hash.Wyhash.init(0);
@@ -3469,7 +3853,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3469
3853
  const self: *HashingLoader = @ptrCast(@alignCast(@constCast(context)));
3470
3854
  const source = self.inner.load(self.inner.context, arena, path) orelse return null;
3471
3855
  var hashed_path = path;
3472
- if (self.strip_prefix.len > 0 and path.len > self.strip_prefix.len and
3856
+ if (self.policy) |callback| {
3857
+ hashed_path = markup_development.stripPrefix(callback, self.strip_prefix, path);
3858
+ } else if (self.strip_prefix.len > 0 and path.len > self.strip_prefix.len and
3473
3859
  std.mem.startsWith(u8, path, self.strip_prefix) and path[self.strip_prefix.len] == '/')
3474
3860
  {
3475
3861
  hashed_path = path[self.strip_prefix.len + 1 ..];
@@ -3501,7 +3887,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3501
3887
  for (self.provenance_closure.entries[0..self.provenance_closure.len]) |*entry| {
3502
3888
  const stamped = entry.path[0..entry.path_len];
3503
3889
  var disk_buffer: [ui_app_provenance.max_path_bytes]u8 = undefined;
3504
- const disk: []const u8 = if (entries_are_disk_paths)
3890
+ const disk: []const u8 = if (self.options.markup_development_policy) |callback| blk: {
3891
+ var input: [2 * ui_app_provenance.max_path_bytes + 16]u8 = undefined;
3892
+ var writer = std.Io.Writer.fixed(&input);
3893
+ const r = markup_development.Request.begin(&writer, 10) catch unreachable;
3894
+ r.byte(@intFromBool(entries_are_disk_paths)) catch unreachable;
3895
+ r.byte(@intFromBool(watch_path != null)) catch unreachable;
3896
+ r.blob(disk_prefix[0..@min(disk_prefix.len, ui_app_provenance.max_path_bytes + 1)]) catch unreachable;
3897
+ r.blob(stamped) catch unreachable;
3898
+ break :blk markup_development.evaluate(callback, writer.buffered(), &disk_buffer);
3899
+ } else if (entries_are_disk_paths)
3505
3900
  stamped
3506
3901
  else if (watch_path == null)
3507
3902
  ""
@@ -3536,12 +3931,37 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3536
3931
  /// sites) and the arena resets on the next reload attempt, so the
3537
3932
  /// stored copy owns its bytes.
3538
3933
  fn recordMarkupDiagnostic(self: *Self, info: canvas.ui_markup.MarkupErrorInfo) void {
3539
- const already_reported = if (self.markup_diagnostic) |current|
3540
- current.line == info.line and current.column == info.column and
3541
- std.mem.eql(u8, current.message, info.message) and std.mem.eql(u8, current.path, info.path)
3542
- else
3543
- false;
3544
- if (!already_reported) {
3934
+ var should_report: bool = undefined;
3935
+ var message_len: usize = @min(info.message.len, self.markup_diagnostic_message_storage.len);
3936
+ var path_len: usize = @min(info.path.len, self.markup_diagnostic_path_storage.len);
3937
+ if (self.options.markup_development_policy) |callback| {
3938
+ var input: [8192]u8 = undefined;
3939
+ var writer = std.Io.Writer.fixed(&input);
3940
+ const r = markup_development.Request.begin(&writer, 2) catch unreachable;
3941
+ const current = self.markup_diagnostic;
3942
+ r.byte(@intFromBool(current != null)) catch unreachable;
3943
+ r.byte(@intFromBool(if (current) |value| value.line == info.line else false)) catch unreachable;
3944
+ r.byte(@intFromBool(if (current) |value| value.column == info.column else false)) catch unreachable;
3945
+ r.blob(if (current) |value| value.message else "") catch unreachable;
3946
+ r.blob(info.message[0..@min(info.message.len, self.markup_diagnostic_message_storage.len + 1)]) catch unreachable;
3947
+ r.blob(if (current) |value| value.path else "") catch unreachable;
3948
+ r.blob(info.path[0..@min(info.path.len, self.markup_diagnostic_path_storage.len + 1)]) catch unreachable;
3949
+ r.word(self.markup_diagnostic_message_storage.len) catch unreachable;
3950
+ r.word(self.markup_diagnostic_path_storage.len) catch unreachable;
3951
+ var output: [12]u8 = undefined;
3952
+ const result = markup_development.evaluate(callback, writer.buffered(), &output);
3953
+ if (result.len != 12 or markup_development.word(result, 0) > 1 or markup_development.word(result, 4) > message_len or markup_development.word(result, 8) > path_len) @panic("invalid markup diagnostic extent");
3954
+ should_report = markup_development.word(result, 0) != 0;
3955
+ message_len = markup_development.word(result, 4);
3956
+ path_len = markup_development.word(result, 8);
3957
+ } else {
3958
+ should_report = if (self.markup_diagnostic) |current|
3959
+ !(current.line == info.line and current.column == info.column and
3960
+ std.mem.eql(u8, current.message, info.message) and std.mem.eql(u8, current.path, info.path))
3961
+ else
3962
+ true;
3963
+ }
3964
+ if (should_report) {
3545
3965
  // std.debug.print, not std.log: the default scaffold app is
3546
3966
  // ReleaseFast (std.log only passes .err there), while
3547
3967
  // logged errors fail test suites that exercise bad markup
@@ -3552,9 +3972,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3552
3972
  std.debug.print("markup view failed to build ({d}:{d}): {s}\n", .{ info.line, info.column, info.message });
3553
3973
  }
3554
3974
  }
3555
- const message_len = @min(info.message.len, self.markup_diagnostic_message_storage.len);
3556
3975
  @memcpy(self.markup_diagnostic_message_storage[0..message_len], info.message[0..message_len]);
3557
- const path_len = @min(info.path.len, self.markup_diagnostic_path_storage.len);
3558
3976
  @memcpy(self.markup_diagnostic_path_storage[0..path_len], info.path[0..path_len]);
3559
3977
  self.markup_diagnostic = .{
3560
3978
  .line = info.line,
@@ -3574,7 +3992,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3574
3992
  markup_options.watch_path != null and markup_options.io != null
3575
3993
  else
3576
3994
  false;
3577
- if (root_armed) {
3995
+ const count = if (comptime fragment_watch_enabled) (if (self.options.fragment_watch) |watch| watch.fragments.len else 0) else 0;
3996
+ const plan = if (self.options.markup_development_policy) |callback| markup_development.watch(callback, root_armed, self.options.view != null, self.markup_source_hash == 0, fragment_watch_enabled and self.options.fragment_watch != null, count, max_watched_fragments) else null;
3997
+ if (if (plan) |value| value[0] != 0 else root_armed and self.options.view != null and self.markup_source_hash == 0) {
3578
3998
  const markup_options = self.options.markup.?;
3579
3999
  // With a compiled `view` also set, the embedded sources are
3580
4000
  // the baseline: the interpreter only takes over once the
@@ -3582,12 +4002,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3582
4002
  // be computed the way the poll computes it — over the whole
3583
4003
  // resolved import closure — or the first poll would flag a
3584
4004
  // phantom change.
3585
- if (self.options.view != null and self.markup_source_hash == 0) {
3586
- self.markup_source_hash = self.embeddedMarkupClosureHash(markup_options);
3587
- }
4005
+ self.markup_source_hash = self.embeddedMarkupClosureHash(markup_options);
3588
4006
  }
3589
4007
  const fragments_armed = self.armFragmentWatch();
3590
- if (!root_armed and !fragments_armed) return;
4008
+ if (if (plan) |value| value[1] == 0 else !root_armed and !fragments_armed) return;
3591
4009
  runtime.startTimer(markup_watch_timer_id, markup_watch_interval_ns, true) catch {};
3592
4010
  // Make the armed watch observable: the automation snapshot
3593
4011
  // header reports `markup_watch=armed|off`, so a dev loop can
@@ -3608,19 +4026,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3608
4026
  fn armFragmentWatch(self: *Self) bool {
3609
4027
  if (comptime !fragment_watch_enabled) return false;
3610
4028
  const fragment_watch = self.options.fragment_watch orelse return false;
3611
- if (fragment_watch.fragments.len > max_watched_fragments) {
4029
+ const plan = if (self.options.markup_development_policy) |callback| markup_development.watch(callback, false, false, false, true, fragment_watch.fragments.len, max_watched_fragments) else null;
4030
+ if (if (plan) |value| value[3] != 0 else fragment_watch.fragments.len > max_watched_fragments) {
3612
4031
  ui_app_log.warn(
3613
4032
  "fragment watch: {d} fragments registered but the watch budget is {d} (max_watched_fragments) - the rest stay compiled-only; consolidate fragments or raise the budget",
3614
4033
  .{ fragment_watch.fragments.len, max_watched_fragments },
3615
4034
  );
3616
4035
  }
3617
- const count = @min(fragment_watch.fragments.len, max_watched_fragments);
4036
+ const count: usize = if (plan) |value| value[2] else @min(fragment_watch.fragments.len, max_watched_fragments);
3618
4037
  for (fragment_watch.fragments[0..count], self.markup_fragment_slots[0..count]) |spec, *slot| {
3619
4038
  // Baseline into the slot's inactive arena — reset on the
3620
4039
  // next reload attempt, so this costs nothing durable.
3621
4040
  const scratch_index = slot.arena_index ^ 1;
3622
4041
  _ = slot.arenas[scratch_index].reset(.retain_capacity);
3623
- slot.baseline_hash = embeddedClosureHash(slot.arenas[scratch_index].allocator(), spec.source, spec.sources);
4042
+ slot.baseline_hash = embeddedClosureHash(slot.arenas[scratch_index].allocator(), spec.source, spec.sources, self.options.markup_development_policy);
3624
4043
  slot.hash = slot.baseline_hash;
3625
4044
  }
3626
4045
  return count > 0;
@@ -3631,18 +4050,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3631
4050
  // hashing side effect; the arena resets on the next reload.
3632
4051
  const scratch_index = self.markup_arena_index ^ 1;
3633
4052
  _ = self.markup_arenas[scratch_index].reset(.retain_capacity);
3634
- return embeddedClosureHash(self.markup_arenas[scratch_index].allocator(), markup_options.source, markup_options.sources);
4053
+ return embeddedClosureHash(self.markup_arenas[scratch_index].allocator(), markup_options.source, markup_options.sources, self.options.markup_development_policy);
3635
4054
  }
3636
4055
 
3637
4056
  /// Hash an embedded source closure exactly like the disk poll
3638
4057
  /// hashes the on-disk one: root bytes plus every loaded file's
3639
4058
  /// root-relative path and bytes, in resolution order.
3640
- fn embeddedClosureHash(arena: std.mem.Allocator, source: []const u8, sources: []const canvas.ui_markup.SourceFile) u64 {
4059
+ fn embeddedClosureHash(arena: std.mem.Allocator, source: []const u8, sources: []const canvas.ui_markup.SourceFile, policy: markup_development.Policy) u64 {
3641
4060
  if (sources.len == 0) {
3642
4061
  return std.hash.Wyhash.hash(0, source);
3643
4062
  }
3644
4063
  var set_loader = canvas.ui_markup.SourceSetLoader{ .set = sources };
3645
4064
  var hashing = HashingLoader.init(set_loader.loader(), source, "");
4065
+ hashing.policy = policy;
3646
4066
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3647
4067
  _ = canvas.ui_markup.resolveImports(
3648
4068
  arena,
@@ -3673,6 +4093,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3673
4093
  var disk_loader = DiskImportLoader{ .io = io };
3674
4094
  const watch_dir = std.fs.path.dirname(watch_path) orelse "";
3675
4095
  var hashing = HashingLoader.init(disk_loader.loader(), source, watch_dir);
4096
+ hashing.policy = self.options.markup_development_policy;
3676
4097
  if (comptime features.runtime_markup) {
3677
4098
  self.provenance_closure.reset();
3678
4099
  hashing.closure = &self.provenance_closure;
@@ -3680,6 +4101,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3680
4101
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3681
4102
  const document = canvas.ui_markup.resolveImports(arena, watch_path, source, hashing.loader(), &diagnostic) catch |err| {
3682
4103
  const hash = hashing.hasher.final();
4104
+ if (self.options.markup_development_policy) |callback| {
4105
+ const program = markup_development.reload(callback, 1, hash != self.markup_source_hash, true, err == error.MarkupSyntax or err == error.MarkupImport, false, self.installed);
4106
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
4107
+ .end => break,
4108
+ .observed_hash => self.markup_source_hash = hash,
4109
+ .diagnostic => self.recordMarkupDiagnostic(diagnostic),
4110
+ else => unreachable,
4111
+ };
4112
+ return;
4113
+ }
3683
4114
  if (hash == self.markup_source_hash) return;
3684
4115
  self.markup_source_hash = hash;
3685
4116
  if (err == error.MarkupSyntax or err == error.MarkupImport) {
@@ -3688,6 +4119,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3688
4119
  return;
3689
4120
  };
3690
4121
  const hash = hashing.hasher.final();
4122
+ if (self.options.markup_development_policy) |callback| {
4123
+ self.applyRootMarkupProgram(callback, 1, document, arena, next_index, hash, watch_path, source, runtime, window_id) catch {};
4124
+ return;
4125
+ }
3691
4126
  if (hash == self.markup_source_hash) return;
3692
4127
  // Canonicalize for per-frame cost only; on OOM the raw
3693
4128
  // document builds identically through attrTyped's fallback.
@@ -3721,9 +4156,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3721
4156
  var disk_loader = DiskImportLoader{ .io = fragment_watch.io };
3722
4157
  const watch_dir = std.fs.path.dirname(spec.path) orelse "";
3723
4158
  var hashing = HashingLoader.init(disk_loader.loader(), source, watch_dir);
4159
+ hashing.policy = self.options.markup_development_policy;
3724
4160
  var diagnostic: canvas.ui_markup.MarkupErrorInfo = .{};
3725
4161
  const document = canvas.ui_markup.resolveImports(arena, spec.path, source, hashing.loader(), &diagnostic) catch |err| {
3726
4162
  const hash = hashing.hasher.final();
4163
+ if (self.options.markup_development_policy) |callback| {
4164
+ const program = markup_development.reload(callback, 2, hash != slot.hash, true, err == error.MarkupSyntax or err == error.MarkupImport, false, self.installed);
4165
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
4166
+ .end => break,
4167
+ .observed_hash => slot.hash = hash,
4168
+ .diagnostic => self.recordMarkupDiagnostic(diagnostic),
4169
+ else => unreachable,
4170
+ };
4171
+ continue;
4172
+ }
3727
4173
  if (hash == slot.hash) continue;
3728
4174
  slot.hash = hash;
3729
4175
  if (err == error.MarkupSyntax or err == error.MarkupImport) {
@@ -3732,6 +4178,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3732
4178
  continue;
3733
4179
  };
3734
4180
  const hash = hashing.hasher.final();
4181
+ if (self.options.markup_development_policy) |callback| {
4182
+ const program = markup_development.reload(callback, 2, hash != slot.hash, false, false, hash == slot.baseline_hash, self.installed);
4183
+ var canonical = document;
4184
+ for (program) |byte| switch (@as(markup_development.Action, @enumFromInt(byte))) {
4185
+ .end => break,
4186
+ .observed_hash => slot.hash = hash,
4187
+ .canonicalize => canonical = canvas.ui_markup.canonicalize(arena, document) catch document,
4188
+ .restore_fragment => slot.document = null,
4189
+ .adopt_fragment => slot.document = canonical,
4190
+ .switch_arena => slot.arena_index = next_index,
4191
+ .clear_diagnostic => self.markup_diagnostic = null,
4192
+ .adopted_fragment => any_adopted = true,
4193
+ else => unreachable,
4194
+ };
4195
+ continue;
4196
+ }
3735
4197
  if (hash == slot.hash) continue;
3736
4198
  slot.hash = hash;
3737
4199
  if (hash == slot.baseline_hash) {
@@ -3755,7 +4217,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3755
4217
  // Fragments build wherever the app's views embed them — the
3756
4218
  // main canvas and declared windows — so a reload re-derives
3757
4219
  // every open view.
3758
- if (any_adopted and self.installed) self.rebuildAllViews(runtime) catch {};
4220
+ const should_rebuild = if (self.options.markup_development_policy) |callback| blk: {
4221
+ const input = [_]u8{ 32, 1, 11, 0, @intFromBool(any_adopted), @intFromBool(self.installed) };
4222
+ var output: [4]u8 = undefined;
4223
+ const result = markup_development.evaluate(callback, &input, &output);
4224
+ if (result.len != 4 or markup_development.word(result, 0) > 1) @panic("invalid markup rebuild result");
4225
+ break :blk markup_development.word(result, 0) != 0;
4226
+ } else any_adopted and self.installed;
4227
+ if (should_rebuild) self.rebuildAllViews(runtime) catch {};
3759
4228
  }
3760
4229
 
3761
4230
  /// The `override` half of the fragment hot-reload seam (see
@@ -3902,14 +4371,50 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3902
4371
  return self.status_items_scratch.status_items[0..1];
3903
4372
  }
3904
4373
 
4374
+ fn statusItemPolicyDecision(self: *Self, desired: []const StatusItemDescriptor, index: ?usize) [2]u8 {
4375
+ comptime std.debug.assert(platform.max_status_items == 8);
4376
+ var request: [4 + 8 * 4 + 8 * 5]u8 = undefined;
4377
+ request[0] = @intFromBool(index != null);
4378
+ request[1] = if (index) |i| @intCast(i) else 255;
4379
+ request[2] = @intCast(desired.len);
4380
+ request[3] = @intCast(self.applied_status_item_count);
4381
+ var at: usize = 4;
4382
+ for (desired) |descriptor| {
4383
+ std.mem.writeInt(u32, request[at..][0..4], descriptor.id, .little);
4384
+ at += 4;
4385
+ }
4386
+ for (self.applied_status_items) |applied| {
4387
+ request[at] = @intFromBool(applied.active);
4388
+ std.mem.writeInt(u32, request[at + 1 ..][0..4], applied.id, .little);
4389
+ at += 5;
4390
+ }
4391
+ var result: [2]u8 = undefined;
4392
+ if (self.options.status_policy.?(request[0..at], &result) != result.len) @panic("invalid compiled status policy result");
4393
+ if (index != null and (result[0] > 3 or (result[0] >= 2 and result[1] >= platform.max_status_items))) @panic("invalid compiled status admission");
4394
+ return result;
4395
+ }
4396
+
4397
+ fn statusItemPatchDecision(self: *Self, applied: *const AppliedStatusItem, shell: u64, presentation: u64, menu: u64) u8 {
4398
+ var request: [49]u8 = undefined;
4399
+ request[0] = 2;
4400
+ const hashes = [_]u64{ shell, presentation, menu, applied.shell_hash, applied.presentation_hash, applied.menu_hash };
4401
+ for (hashes, 0..) |hash, index| std.mem.writeInt(u64, request[1 + index * 8 ..][0..8], hash, .little);
4402
+ var result: [2]u8 = undefined;
4403
+ if (self.options.status_policy.?(&request, &result) != result.len or result[0] > 7) @panic("invalid compiled status patch result");
4404
+ return result[0];
4405
+ }
4406
+
3905
4407
  fn reconcileStatusItems(self: *Self, runtime: *Runtime, declared: []const StatusItemDescriptor) void {
3906
4408
  if (declared.len > platform.max_status_items) {
3907
4409
  ui_app_log.warn("status item collection has {d} entries; at most {d} are supported", .{ declared.len, platform.max_status_items });
3908
4410
  }
3909
4411
  const desired = declared[0..@min(declared.len, platform.max_status_items)];
3910
4412
 
3911
- for (&self.applied_status_items) |*applied| {
3912
- if (!applied.active or statusItemDeclared(desired, applied.id)) continue;
4413
+ const compiled = self.options.status_policy != null;
4414
+ const retirement = if (compiled) self.statusItemPolicyDecision(desired, null)[0] else 0;
4415
+ for (&self.applied_status_items, 0..) |*applied, slot| {
4416
+ const remove = if (compiled) retirement & (@as(u8, 1) << @intCast(slot)) != 0 else applied.active and !statusItemDeclared(desired, applied.id);
4417
+ if (!remove) continue;
3913
4418
  runtime.removeStatusItem(applied.id) catch |err| {
3914
4419
  ui_app_log.warn("status item #{d} remove failed: {s}", .{ applied.id, @errorName(err) });
3915
4420
  continue;
@@ -3919,10 +4424,18 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3919
4424
  }
3920
4425
 
3921
4426
  for (desired, 0..) |raw_descriptor, index| {
3922
- if (raw_descriptor.id == 0 or statusItemIdAppearedEarlier(desired, index, raw_descriptor.id)) {
4427
+ // Requery the owned table after every successful or failed OS
4428
+ // operation. Failed removals retain slots; failed creates do not.
4429
+ const plan = if (compiled) self.statusItemPolicyDecision(desired, index) else [2]u8{ 0, 255 };
4430
+ const invalid = if (compiled) plan[0] == 0 else raw_descriptor.id == 0 or statusItemIdAppearedEarlier(desired, index, raw_descriptor.id);
4431
+ if (invalid) {
3923
4432
  ui_app_log.warn("status item declaration ignored: identifiers must be unique and non-zero (got {d})", .{raw_descriptor.id});
3924
4433
  continue;
3925
4434
  }
4435
+ if (compiled and plan[0] == 1) {
4436
+ ui_app_log.warn("status item #{d} ignored: status-item capacity is full", .{raw_descriptor.id});
4437
+ continue;
4438
+ }
3926
4439
  var descriptor = raw_descriptor;
3927
4440
  if (descriptor.state.presentation.title.len == 0) descriptor.state.presentation.title = descriptor.state.title;
3928
4441
  const shell = platform.TrayShell{
@@ -3937,11 +4450,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3937
4450
  const presentation_hash = hashTrayPresentation(descriptor.state.presentation);
3938
4451
  const menu_hash = hashTrayMenu(descriptor.state.items);
3939
4452
 
3940
- const applied = self.findAppliedStatusItem(descriptor.id) orelse self.emptyAppliedStatusItem() orelse {
4453
+ const applied = if (compiled) &self.applied_status_items[plan[1]] else self.findAppliedStatusItem(descriptor.id) orelse self.emptyAppliedStatusItem() orelse {
3941
4454
  ui_app_log.warn("status item #{d} ignored: status-item capacity is full", .{descriptor.id});
3942
4455
  continue;
3943
4456
  };
3944
- if (!applied.active) {
4457
+ const creating = if (compiled) plan[0] == 2 else !applied.active;
4458
+ if (creating) {
3945
4459
  runtime.createStatusItem(descriptor.id, .{
3946
4460
  .title = descriptor.state.presentation.title,
3947
4461
  .icon_path = shell.icon_path,
@@ -3967,7 +4481,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3967
4481
  continue;
3968
4482
  }
3969
4483
 
3970
- if (shell_hash != applied.shell_hash) {
4484
+ const changes = if (compiled) self.statusItemPatchDecision(applied, shell_hash, presentation_hash, menu_hash) else @as(u8, @intFromBool(shell_hash != applied.shell_hash)) |
4485
+ (@as(u8, @intFromBool(presentation_hash != applied.presentation_hash)) << 1) |
4486
+ (@as(u8, @intFromBool(menu_hash != applied.menu_hash)) << 2);
4487
+ if (changes & 1 != 0) {
3971
4488
  applied.shell_hash = shell_hash;
3972
4489
  if (!applied.shell_unsupported) {
3973
4490
  runtime.updateStatusItemShell(descriptor.id, shell) catch |err| {
@@ -3976,7 +4493,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3976
4493
  };
3977
4494
  }
3978
4495
  }
3979
- if (presentation_hash != applied.presentation_hash) {
4496
+ if (changes & 2 != 0) {
3980
4497
  applied.presentation_hash = presentation_hash;
3981
4498
  if (!applied.presentation_unsupported) {
3982
4499
  runtime.updateStatusItemPresentation(descriptor.id, descriptor.state.presentation) catch |err| {
@@ -3985,7 +4502,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3985
4502
  };
3986
4503
  }
3987
4504
  }
3988
- if (menu_hash != applied.menu_hash) {
4505
+ if (changes & 4 != 0) {
3989
4506
  applied.menu_hash = menu_hash;
3990
4507
  runtime.updateStatusItemMenu(descriptor.id, descriptor.state.items) catch |err| {
3991
4508
  ui_app_log.warn("status item #{d} menu update failed: {s}", .{ descriptor.id, @errorName(err) });
@@ -4247,65 +4764,45 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4247
4764
 
4248
4765
  fn eventFn(context: *anyopaque, runtime: *Runtime, event_value: Event) anyerror!void {
4249
4766
  const self: *Self = @ptrCast(@alignCast(context));
4767
+ if (self.options.on_window_context) |map| {
4768
+ const source_id: ?platform.WindowId = switch (event_value) {
4769
+ inline .command, .shortcut, .canvas_widget_pointer, .canvas_widget_keyboard, .canvas_widget_scroll, .canvas_widget_file_drop, .canvas_widget_drag, .canvas_widget_context_menu, .canvas_widget_context_menu_shown, .canvas_widget_context_menu_dismissed, .canvas_widget_context_menu_request, .canvas_widget_dismiss, .canvas_widget_context_press, .canvas_widget_resize, .canvas_widget_change, .window_closed, .automation_provenance => |event| event.window_id,
4770
+ else => null,
4771
+ };
4772
+ if (source_id) |id| {
4773
+ var storage: [platform.max_windows]platform.WindowInfo = undefined;
4774
+ for (runtime.listWindows(&storage)) |window| {
4775
+ if (window.id != id) continue;
4776
+ if (map(&self.model, window.label)) |msg| self.applyMsg(msg);
4777
+ break;
4778
+ }
4779
+ }
4780
+ }
4250
4781
  self.hover_msg_event_depth += 1;
4251
4782
  defer self.hover_msg_event_depth -= 1;
4252
- // Hover enter/leave delivery rides the tail of runtime
4253
- // events: the standing chain moves during pointer routing,
4254
- // scroll reconciles (wheel, kinetic, drivers, keyboard),
4255
- // dismissals, and any rebuild the dispatches above
4256
- // performed — the drain seam catches them all, and replay
4257
- // re-runs the same events through the same seam. The drain
4258
- // runs on the handler's ERROR path too (the degraded-error
4259
- // doctrine): a failing handler must not strand edges the
4260
- // event already produced — a closed window's leave, a
4261
- // failed rebuild's prune — until some later event happens
4262
- // by. Mid-cycle DERIVED widget events skip the drain (see
4263
- // `hoverDrainsAfterEvent`): their input cycle's terminal
4264
- // `gpu_surface_input` dispatch drains after the cycle's
4265
- // pending scroll/resize/change observations were delivered,
4266
- // so a hover Msg's rebuild can never unmount a view whose
4267
- // promised observation is still queued.
4783
+ var first_error: ?anyerror = null;
4268
4784
  handleRuntimeEvent(self, runtime, event_value) catch |err| {
4269
- if (hoverDrainsAfterEvent(event_value)) self.drainHoverMsgs(runtime) catch {};
4270
- return err;
4785
+ first_error = err;
4786
+ };
4787
+ // Event classification describes the native input envelope; the
4788
+ // portable policy chooses settlement, including error paths.
4789
+ const kind: u8 = switch (event_value) {
4790
+ .canvas_widget_keyboard => 2,
4791
+ .canvas_widget_pointer, .canvas_widget_drag, .canvas_widget_file_drop, .canvas_widget_context_press, .canvas_widget_context_menu_request, .canvas_widget_context_menu_shown, .canvas_widget_scroll, .canvas_widget_resize, .canvas_widget_change => 1,
4792
+ else => 0,
4271
4793
  };
4272
- if (hoverDrainsAfterEvent(event_value)) try self.drainHoverMsgs(runtime);
4273
- }
4274
-
4275
- /// Whether the hover drain runs at this event's tail. Derived
4276
- /// widget events that only occur INSIDE a gpu-surface input
4277
- /// cycle defer to the cycle's terminal `gpu_surface_input`
4278
- /// dispatch — which always follows them, after the pending
4279
- /// scroll/resize/change drains. Scroll/resize/change events also
4280
- /// arrive standalone from the native-driver and kinetic paths;
4281
- /// those defer at most one frame (both paths run under an
4282
- /// actively pumping frame channel), which is the price of never
4283
- /// rebuilding mid-cycle. Dismiss events DO drain: the
4284
- /// automation/accessibility dismiss verb dispatches one
4285
- /// standalone, and a dismissal's own Msg rebuild already runs
4286
- /// before the cycle's pending drains, so draining here adds no
4287
- /// new hazard class. Everything else — commands, timers, wakes,
4288
- /// frames, the terminal input dispatch, native menu selections —
4289
- /// drains immediately.
4290
- fn hoverDrainsAfterEvent(event_value: Event) bool {
4291
- return switch (event_value) {
4292
- // Keyboard events usually ride an input cycle (their
4293
- // terminal dispatch drains); the standalone ones —
4294
- // accessibility selection edits, context-menu
4295
- // cut/paste/select-all — have no cycle and drain here.
4296
- .canvas_widget_keyboard => |keyboard_event| keyboard_event.standalone,
4297
- .canvas_widget_pointer,
4298
- .canvas_widget_drag,
4299
- .canvas_widget_file_drop,
4300
- .canvas_widget_context_press,
4301
- .canvas_widget_context_menu_request,
4302
- .canvas_widget_context_menu_shown,
4303
- .canvas_widget_scroll,
4304
- .canvas_widget_resize,
4305
- .canvas_widget_change,
4306
- => false,
4307
- else => true,
4794
+ const standalone = switch (event_value) {
4795
+ .canvas_widget_keyboard => |keyboard| keyboard.standalone,
4796
+ else => false,
4308
4797
  };
4798
+ const tail = dispatch_policy.plan(self.options.app_dispatch_policy, .event_tail, kind, @intFromBool(standalone));
4799
+ for (tail) |byte| switch (@as(dispatch_policy.Action, @enumFromInt(byte))) {
4800
+ .end => break,
4801
+ .hover => self.drainHoverMsgs(runtime) catch |err| self.selectDispatchError(&first_error, err),
4802
+ else => @panic("unexpected event tail action"),
4803
+ };
4804
+ if (self.hover_msg_event_depth == 1) self.effects.flushDesktopCapabilities();
4805
+ if (first_error) |err| return err;
4309
4806
  }
4310
4807
 
4311
4808
  fn handleRuntimeEvent(self: *Self, runtime: *Runtime, event_value: Event) anyerror!void {
@@ -4524,15 +5021,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4524
5021
  }
4525
5022
 
4526
5023
  fn handleFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent) anyerror!void {
5024
+ // A secondary surface can be the only surviving frame source.
5025
+ try self.drainEffects(runtime);
5026
+ for (runtime.windows[0..runtime.window_count]) |window| {
5027
+ if (window.info.id == frame_event.window_id and !window.info.open) return;
5028
+ }
4527
5029
  if (!std.mem.eql(u8, frame_event.label, self.options.canvas_label)) {
4528
5030
  return self.handleWindowSlotFrame(runtime, frame_event);
4529
5031
  }
4530
5032
  // Host-pumped embeds deliver no `.wake`; drain pending effect
4531
5033
  // results with the frame tick so this frame presents them.
4532
- try self.drainEffects(runtime);
4533
5034
  self.canvas_window_id = frame_event.window_id;
4534
5035
  self.frame_timestamp_ns = frame_event.timestamp_ns;
4535
- const scale = normalizedSurfaceScale(frame_event.scale_factor);
5036
+ const scale = self.normalizedSurfaceScale(frame_event.scale_factor);
4536
5037
  var installing = false;
4537
5038
  if (!self.installed) {
4538
5039
  installing = true;
@@ -4568,7 +5069,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4568
5069
  // rebuild below is the one that renders it), so a
4569
5070
  // hidden-titlebar header is padded in the very first
4570
5071
  // paint.
4571
- if (self.chromeInsetsMsg(runtime, frame_event.window_id)) |msg| {
5072
+ if (try self.chromeInsetsMsg(runtime, frame_event.window_id)) |msg| {
4572
5073
  self.applyMsg(msg);
4573
5074
  }
4574
5075
  try self.rebuild(runtime, frame_event.window_id);
@@ -4610,7 +5111,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4610
5111
  // job.
4611
5112
  self.canvas_size = frame_event.size;
4612
5113
  try self.rebuild(runtime, frame_event.window_id);
4613
- } else if (runtime.registeredCanvasFontCount() != self.fonts_built_count) {
5114
+ } else if (if (self.options.font_registry_policy) |policy|
5115
+ @import("font_registry_policy.zig").plan(policy, .refresh, &.{}, runtime.registeredCanvasFontCount(), .{ .built_count = self.fonts_built_count }).action != 0
5116
+ else
5117
+ runtime.registeredCanvasFontCount() != self.fonts_built_count)
5118
+ {
4614
5119
  // A face joined the registry after install (late
4615
5120
  // registration through the runtime seam). The runtime
4616
5121
  // already invalidated measurement caches and requested
@@ -4621,14 +5126,6 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4621
5126
  // rebuilding so layout and the re-emitted display lists
4622
5127
  // charge the registered face's advances.
4623
5128
  try self.rebuildForRegisteredFonts(runtime);
4624
- } else if (self.options.web_panes != null) {
4625
- // Re-snap the webview panes each presented frame: a shell
4626
- // relayout that stomped a pane frame also invalidated the
4627
- // canvas, so the reconciliation ride-along here converges
4628
- // without a dedicated event.
4629
- if (runtime.canvasWidgetLayout(frame_event.window_id, self.options.canvas_label)) |layout| {
4630
- self.applyWebPanes(runtime, frame_event.window_id, layout);
4631
- } else |_| {}
4632
5129
  }
4633
5130
  // Terminal outbound pacing: a child that read without
4634
5131
  // echoing freed stdin-FIFO room no output event announces,
@@ -4646,6 +5143,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4646
5143
  installing,
4647
5144
  self.effectiveTokens().colors.background,
4648
5145
  );
5146
+ // The first native present can show the window and synchronously
5147
+ // report its frame. Shell relayout then resets child WebViews to
5148
+ // their manifest frames after rebuild applied the model's panes.
5149
+ // Restore pane ownership before this event commits, so recording
5150
+ // and flat replay observe the same anchored first-frame state.
5151
+ if (self.options.web_panes != null) {
5152
+ if (runtime.canvasWidgetLayout(frame_event.window_id, self.options.canvas_label)) |layout| {
5153
+ self.applyWebPanes(runtime, frame_event.window_id, layout);
5154
+ } else |_| {}
5155
+ }
4649
5156
  if (installing) return;
4650
5157
  const on_frame = self.options.on_frame orelse return;
4651
5158
  const gpu_frame = runtime.gpuSurfaceFrame(frame_event.window_id, self.options.canvas_label) catch return;
@@ -4662,7 +5169,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4662
5169
  fn handleWindowSlotFrame(self: *Self, runtime: *Runtime, frame_event: platform.GpuSurfaceFrameEvent) anyerror!void {
4663
5170
  const slot = self.windowSlotByCanvasLabel(frame_event.label) orelse return;
4664
5171
  slot.window_id = frame_event.window_id;
4665
- const scale = normalizedSurfaceScale(frame_event.scale_factor);
5172
+ const scale = self.normalizedSurfaceScale(frame_event.scale_factor);
4666
5173
  var installing = false;
4667
5174
  if (!slot.installed) {
4668
5175
  installing = true;
@@ -4690,7 +5197,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4690
5197
  // stale bounds.
4691
5198
  slot.canvas_size = frame_event.size;
4692
5199
  try self.rebuildWindowSlot(runtime, slot);
4693
- } else if (runtime.registeredCanvasFontCount() != self.fonts_built_count) {
5200
+ } else if (if (self.options.font_registry_policy) |policy|
5201
+ @import("font_registry_policy.zig").plan(policy, .refresh, &.{}, runtime.registeredCanvasFontCount(), .{ .built_count = self.fonts_built_count }).action != 0
5202
+ else
5203
+ runtime.registeredCanvasFontCount() != self.fonts_built_count)
5204
+ {
4694
5205
  // Late registration, first observed on a secondary
4695
5206
  // window's frame (registration requests frames for every
4696
5207
  // open surface, and arrival order is the platform's):
@@ -4803,7 +5314,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4803
5314
  /// Grow the heap pixel buffers to hold the surface at the given
4804
5315
  /// scale. No-op when they are already large enough.
4805
5316
  fn ensurePixelBuffers(self: *Self, surface_size: geometry.SizeF, scale_factor: f32) anyerror!void {
4806
- const pixel_size = try canvas_frame.canvasSurfacePixelSize(surface_size, scale_factor);
5317
+ const pixel_size = try canvas_frame.canvasSurfacePixelSizeWithPolicy(surface_size, scale_factor, self.options.render_cache_policy);
4807
5318
  if (self.pixel_buffer.len < pixel_size.byte_len) {
4808
5319
  self.pixel_buffer_window_id = null;
4809
5320
  if (self.pixel_buffer.len > 0) self.backing.free(self.pixel_buffer);
@@ -4817,9 +5328,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4817
5328
  }
4818
5329
  }
4819
5330
 
4820
- fn normalizedSurfaceScale(scale_factor: f32) f32 {
4821
- if (!std.math.isFinite(scale_factor) or scale_factor <= 0) return 1;
4822
- return scale_factor;
5331
+ fn normalizedSurfaceScale(self: *Self, scale_factor: f32) f32 {
5332
+ return canvas_frame.normalizedCanvasPresentationScaleWithPolicy(scale_factor, 1, self.options.render_cache_policy);
4823
5333
  }
4824
5334
 
4825
5335
  /// Change-detection hashes for the model-derived tray state:
@@ -4917,19 +5427,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4917
5427
  if (!std.mem.eql(u8, resize_event.label, self.options.canvas_label)) {
4918
5428
  const slot = self.windowSlotByCanvasLabel(resize_event.label) orelse return;
4919
5429
  slot.canvas_size = .{ .width = resize_event.frame.width, .height = resize_event.frame.height };
4920
- slot.pixel_snap_scale = normalizedSurfaceScale(resize_event.scale_factor);
5430
+ slot.pixel_snap_scale = self.normalizedSurfaceScale(resize_event.scale_factor);
4921
5431
  if (slot.installed) try self.rebuildWindowSlot(runtime, slot);
4922
5432
  return;
4923
5433
  }
4924
5434
  self.canvas_size = .{ .width = resize_event.frame.width, .height = resize_event.frame.height };
4925
- self.pixel_snap_scale = normalizedSurfaceScale(resize_event.scale_factor);
5435
+ self.pixel_snap_scale = self.normalizedSurfaceScale(resize_event.scale_factor);
4926
5436
  if (!self.installed) return;
4927
5437
  // Fullscreen transitions resize the canvas AND flip the
4928
5438
  // chrome overlay insets (macOS hides the titlebar band and
4929
5439
  // traffic lights); re-query on every resize and dispatch
4930
5440
  // only on change — `dispatch` already rebuilds, so the
4931
5441
  // plain-resize rebuild is the else arm.
4932
- if (self.chromeInsetsMsg(runtime, resize_event.window_id)) |msg| {
5442
+ if (try self.chromeInsetsMsg(runtime, resize_event.window_id)) |msg| {
4933
5443
  try self.dispatch(runtime, resize_event.window_id, msg);
4934
5444
  return;
4935
5445
  }
@@ -4961,9 +5471,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
4961
5471
  /// The `on_chrome` delivery gate: query the platform's chrome
4962
5472
  /// overlay geometry for the canvas window and map it to a Msg
4963
5473
  /// when the app subscribed AND the geometry actually changed.
4964
- fn chromeInsetsMsg(self: *Self, runtime: *Runtime, window_id: platform.WindowId) ?MsgT {
5474
+ fn chromeInsetsMsg(self: *Self, runtime: *Runtime, window_id: platform.WindowId) !?MsgT {
4965
5475
  const map = self.options.on_chrome orelse return null;
4966
- const chrome = runtime.options.platform.services.windowChrome(window_id);
5476
+ const chrome = try runtime.windowChrome(window_id);
4967
5477
  if (self.window_chrome_known and std.meta.eql(chrome, self.window_chrome)) return null;
4968
5478
  self.window_chrome = chrome;
4969
5479
  self.window_chrome_known = true;
@@ -5032,9 +5542,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5032
5542
  const terminal_selected = try self.handleTerminalPointer(runtime, pointer_event);
5033
5543
  switch (pointer_event.pointer.phase) {
5034
5544
  .down => {
5035
- self.disarmHold(runtime);
5545
+ const has_hold = if (pointer_event.press_target) |target| tree.hasHoldHandler(target.id) else false;
5546
+ const plan = self.pressHoldPlan(0, has_hold, true);
5547
+ self.applyHoldReset(runtime, plan);
5036
5548
  if (pointer_event.press_target) |target| {
5037
- if (tree.hasHoldHandler(target.id)) {
5549
+ if (plan & 4 != 0) {
5038
5550
  self.hold_armed_id = target.id;
5039
5551
  self.hold_fired = false;
5040
5552
  // One pointer, one gesture — but it can be
@@ -5050,9 +5562,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5050
5562
  }
5051
5563
  },
5052
5564
  .up, .cancel => {
5053
- const suppressed = self.hold_fired;
5054
- self.disarmHold(runtime);
5055
- if (suppressed) return;
5565
+ const plan = self.pressHoldPlan(1, false, true);
5566
+ self.applyHoldReset(runtime, plan);
5567
+ if (plan & 8 != 0) return;
5056
5568
  },
5057
5569
  else => {},
5058
5570
  }
@@ -5100,19 +5612,6 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5100
5612
  }
5101
5613
  }
5102
5614
 
5103
- /// Cap on hover-Msg drain passes per runtime event: each pass
5104
- /// delivers one coalesced containment transition, and the Msgs
5105
- /// it dispatches can rebuild the tree and move the standing
5106
- /// chain again (an enter handler that unmounts the hovered
5107
- /// element owes an immediate leave — the second pass delivers
5108
- /// it). The cap exists ONLY as a flap guard (an app whose enter
5109
- /// mounts and whose leave unmounts, forever), sized far past
5110
- /// any honest cascade — even one where every enter replaces the
5111
- /// listener under a stationary pointer — so a finite sequence
5112
- /// always settles within one drain; residue past the cap
5113
- /// delivers on the next event's drain.
5114
- const hover_msg_drain_passes: usize = 64;
5115
-
5116
5615
  /// Refresh every standing capture from the mirror view's live
5117
5616
  /// tree when the trees moved underneath: called at EVERY
5118
5617
  /// rebuild commit — two dispatches in one cycle (payload A to
@@ -5123,66 +5622,56 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5123
5622
  /// (allocation) after attempting every entry, leaving the
5124
5623
  /// generation behind so the next commit or drain retries.
5125
5624
  fn refreshHoverLeaveCaptures(self: *Self) ?anyerror {
5126
- if (self.hover_msg_chain_len == 0) return null;
5127
- if (self.hover_msg_captured_generation == self.build_generation) return null;
5128
- if (!self.hoverTreeCurrentFor(self.hover_msg_window_id, self.hoverMsgViewLabel())) return null;
5129
- const mirror_tree = self.hoverTreeFor(self.hover_msg_window_id, self.hoverMsgViewLabel()) orelse return null;
5625
+ const mirror_tree = self.hoverTreeFor(self.hover_msg_window_id, self.hoverMsgViewLabel());
5626
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .refresh, .facts = @as(u8, if (self.hover_msg_chain_len != 0) 1 else 0) | @as(u8, if (self.hover_msg_captured_generation == self.build_generation) 2 else 0) |
5627
+ @as(u8, if (self.hoverTreeCurrentFor(self.hover_msg_window_id, self.hoverMsgViewLabel())) 4 else 0) | @as(u8, if (mirror_tree != null) 8 else 0) }) == 0) return null;
5130
5628
  var first_error: ?anyerror = null;
5131
5629
  var refreshed = true;
5132
5630
  for (0..self.hover_msg_chain_len) |position| {
5133
5631
  // A refused entry's pair is disabled (its enter never
5134
5632
  // dispatched); a rebind only takes effect on re-entry.
5135
- if (self.hover_msg_slots[position] == hover_msg_slot_refused) continue;
5136
- const leave_msg = mirror_tree.msgFor(self.hover_msg_chain[position], .hover_leave) orelse continue;
5633
+ const leave_msg = if (mirror_tree) |tree| tree.msgFor(self.hover_msg_chain[position], .hover_leave) else null;
5634
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .refresh_entry, .facts = @as(u8, if (self.hover_msg_slots[position] == hover_msg_slot_refused) 1 else 0) | @as(u8, if (leave_msg != null) 2 else 0) }) == 0) continue;
5137
5635
  // Copy-then-swap: the replacement lands in a FRESH slot
5138
5636
  // (the pool sizing guarantees one is free) and the old
5139
5637
  // capture releases only after it succeeded — a failed
5140
5638
  // allocation must never destroy the still-valid capture
5141
5639
  // it was refreshing.
5142
5640
  const fresh = self.claimHoverSlot() orelse {
5143
- refreshed = false;
5144
- ui_app_log.warn("hover-leave capture refresh failed: no free capture slot - retrying at the next rebuild or drain", .{});
5145
- if (first_error == null) first_error = error.OutOfMemory;
5641
+ if (self.hoverCaptureDecision(0, 0, self.hover_msg_slots[position]) == 1) {
5642
+ refreshed = false;
5643
+ ui_app_log.warn("hover-leave capture refresh failed: no free capture slot - retrying at the next rebuild or drain", .{});
5644
+ if (first_error == null) first_error = error.OutOfMemory;
5645
+ }
5146
5646
  continue;
5147
5647
  };
5148
- self.captureHoverLeave(fresh, leave_msg) catch |err| {
5648
+ self.captureHoverLeave(fresh, leave_msg.?) catch |err| {
5149
5649
  self.releaseHoverSlot(fresh);
5150
- switch (err) {
5151
- error.OutOfMemory => {
5152
- // Transient: keep the old capture, retry at
5153
- // the next commit or drain — the generation
5154
- // stays behind — and surface the failure
5155
- // LOUD: if the element unmounts before a
5156
- // retry lands, its refreshed leave is lost,
5157
- // and that must never be silent.
5158
- refreshed = false;
5159
- ui_app_log.warn("hover-leave capture refresh failed: {t} - retrying at the next rebuild or drain; an unmount before a successful retry loses the newly bound leave", .{err});
5160
- if (first_error == null) first_error = err;
5161
- },
5162
- error.HoverCapturePayloadUnsupported => {
5163
- // A rebind to an unownable payload. An
5164
- // entry with a standing capture keeps it
5165
- // quietly (the promise the enter earned);
5166
- // an entry that never had one — entered
5167
- // with no leave bound, then given one no
5168
- // copy can own — is marked so the
5169
- // degradation is WARNED once, not silent,
5170
- // and not re-warned every generation.
5171
- if (self.hover_msg_slots[position] == hover_msg_slot_none) {
5172
- self.hover_msg_slots[position] = hover_msg_slot_unowned;
5173
- ui_app_log.warn("on_hover_leave rebind cannot be owned (a single-item pointer): the standing element's leave degrades to live-tree resolution, and an unmount loses it - bind a slice or scalar payload instead", .{});
5174
- }
5175
- },
5650
+ const action = self.hoverCaptureDecision(0, if (err == error.OutOfMemory) 0 else 1, self.hover_msg_slots[position]);
5651
+ if (action == 1) {
5652
+ refreshed = false;
5653
+ ui_app_log.warn("hover-leave capture refresh failed: {t} - retrying at the next rebuild or drain; an unmount before a successful retry loses the newly bound leave", .{err});
5654
+ if (first_error == null) first_error = err;
5655
+ } else if (action == 3) {
5656
+ self.hover_msg_slots[position] = hover_msg_slot_unowned;
5657
+ ui_app_log.warn("on_hover_leave rebind cannot be owned (a single-item pointer): the standing element's leave degrades to live-tree resolution, and an unmount loses it - bind a slice or scalar payload instead", .{});
5176
5658
  }
5177
5659
  continue;
5178
5660
  };
5179
- self.releaseHoverSlot(self.hover_msg_slots[position]);
5180
- self.hover_msg_slots[position] = fresh;
5661
+ if (self.hoverCaptureDecision(0, 2, self.hover_msg_slots[position]) == 4) {
5662
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5663
+ self.hover_msg_slots[position] = fresh;
5664
+ } else self.releaseHoverSlot(fresh);
5181
5665
  }
5182
5666
  if (refreshed) self.hover_msg_captured_generation = self.build_generation;
5183
5667
  return first_error;
5184
5668
  }
5185
5669
 
5670
+ fn hoverCaptureDecision(self: *const Self, context: u8, outcome: u8, slot: u8) u8 {
5671
+ const kind: u8 = if (slot == hover_msg_slot_none) 0 else if (slot == hover_msg_slot_refused) 1 else if (slot == hover_msg_slot_unowned) 2 else 3;
5672
+ return hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .capture, .a = context, .b = outcome, .facts = kind });
5673
+ }
5674
+
5186
5675
  /// The mirror-view adoption count for the tracked publication
5187
5676
  /// below (0 when the view is not found — then no adoption can
5188
5677
  /// have happened either).
@@ -5201,8 +5690,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5201
5690
  /// still mark the pair stale, while a pre-adoption rejection
5202
5691
  /// must not. The view's adoption counter is the witness.
5203
5692
  fn publishWidgetLayoutTracked(self: *Self, runtime: *Runtime, window_id: platform.WindowId, label: []const u8, layout: canvas.WidgetLayoutTree, current_flag: *bool) anyerror!void {
5204
- _ = self;
5205
5693
  const adoptions_before = canvasWidgetLayoutAdoptions(runtime, window_id, label);
5694
+ defer {
5695
+ // Adoption precedes fallible host synchronization. Stamp
5696
+ // the policy even when those later operations fail, while
5697
+ // leaving a rejected publication's retained policy intact.
5698
+ if (canvasWidgetLayoutAdoptions(runtime, window_id, label) != adoptions_before) {
5699
+ for (runtime.views[0..runtime.view_count]) |*view| {
5700
+ if (view.window_id == window_id and std.mem.eql(u8, view.label, label)) {
5701
+ view.canvas_widget_tab_focus_policy = self.options.tab_focus_policy;
5702
+ view.canvas_widget_surface_scope_policy = self.options.surface_scope_policy;
5703
+ view.canvas_widget_focus_return_policy = self.options.focus_return_policy;
5704
+ view.canvas_widget_tooltip_policy = self.options.tooltip_policy;
5705
+ break;
5706
+ }
5707
+ }
5708
+ }
5709
+ }
5206
5710
  _ = runtime.setCanvasWidgetLayout(window_id, label, layout) catch |err| {
5207
5711
  if (canvasWidgetLayoutAdoptions(runtime, window_id, label) != adoptions_before) current_flag.* = false;
5208
5712
  return err;
@@ -5397,8 +5901,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5397
5901
  /// dispatches, which is what "discrete edges, never per-move"
5398
5902
  /// means under a fast pointer.
5399
5903
  fn drainHoverMsgs(self: *Self, runtime: *Runtime) anyerror!void {
5400
- if (!self.installed) return;
5401
- if (self.hover_msg_draining) return;
5904
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .drain, .facts = @as(u8, if (self.installed) 1 else 0) | @as(u8, if (self.hover_msg_draining) 2 else 0) }) == 0) return;
5402
5905
  self.hover_msg_draining = true;
5403
5906
  defer self.hover_msg_draining = false;
5404
5907
  // A pass's error degrades WITHOUT aborting the drain: its
@@ -5409,12 +5912,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5409
5912
  // degraded handling every event handler gets.
5410
5913
  var first_error: ?anyerror = null;
5411
5914
  var passes: usize = 0;
5412
- while (passes < hover_msg_drain_passes) : (passes += 1) {
5915
+ while (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .continuation, .a = @intCast(passes), .facts = 1 }) != 0) : (passes += 1) {
5413
5916
  const progressed = self.stepHoverMsgs(runtime) catch |err| blk: {
5414
5917
  if (first_error == null) first_error = err;
5415
5918
  break :blk true;
5416
5919
  };
5417
- if (!progressed) break;
5920
+ if (hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .continuation, .a = @intCast(passes + 1), .facts = @intFromBool(progressed) }) == 0) break;
5418
5921
  }
5419
5922
  if (first_error) |err| return err;
5420
5923
  }
@@ -5432,15 +5935,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5432
5935
  fn stepHoverMsgs(self: *Self, runtime: *Runtime) anyerror!bool {
5433
5936
  var standing_index: ?usize = null;
5434
5937
  for (runtime.views[0..runtime.view_count], 0..) |*view, index| {
5435
- if (view.kind != .gpu_surface) continue;
5436
- if (view.canvas_widget_hover_msg_chain_len == 0) continue;
5437
- const is_mirror = view.window_id == self.hover_msg_window_id and
5438
- std.mem.eql(u8, view.label, self.hoverMsgViewLabel());
5439
- if (is_mirror) {
5440
- standing_index = index;
5441
- break;
5442
- }
5443
- if (standing_index == null) standing_index = index;
5938
+ const is_mirror = view.window_id == self.hover_msg_window_id and std.mem.eql(u8, view.label, self.hoverMsgViewLabel());
5939
+ const action = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .view, .facts = @as(u8, if (view.kind == .gpu_surface) 1 else 0) | @as(u8, if (view.canvas_widget_hover_msg_chain_len != 0) 2 else 0) |
5940
+ @as(u8, if (is_mirror) 4 else 0) | @as(u8, if (standing_index != null) 8 else 0) });
5941
+ if (action != 0) standing_index = index;
5942
+ if (action == 2) break;
5444
5943
  }
5445
5944
 
5446
5945
  // The standing chain and the view identity it belongs to
@@ -5491,28 +5990,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5491
5990
  // A view change retains nothing (one pointer, one view).
5492
5991
  var retained_slots: [canvas.max_widget_depth]u8 = undefined;
5493
5992
  var entering_at: [canvas.max_widget_depth]bool = undefined;
5494
- var entering_any = false;
5495
- var identical = same_view and standing_len == mirror_len;
5496
- for (standing_chain[0..standing_len], 0..) |id, position| {
5497
- var slot: u8 = hover_msg_slot_none;
5498
- var retained = false;
5499
- if (same_view) {
5500
- for (self.hover_msg_chain[0..mirror_len], 0..) |mirror_id, mirror_position| {
5501
- if (mirror_id != id) continue;
5502
- slot = self.hover_msg_slots[mirror_position];
5503
- retained = true;
5504
- if (mirror_position != position) identical = false;
5505
- break;
5506
- }
5507
- }
5508
- retained_slots[position] = slot;
5509
- entering_at[position] = !retained;
5510
- if (!retained) {
5511
- entering_any = true;
5512
- identical = false;
5513
- }
5993
+ const plan = hover_policy.plan(self.options.surface_scope_policy, same_view, self.hover_msg_chain[0..mirror_len], standing_chain[0..standing_len]);
5994
+ for (0..standing_len) |position| {
5995
+ const retained = plan.retained[position];
5996
+ retained_slots[position] = if (retained == 255) hover_msg_slot_none else self.hover_msg_slots[retained];
5997
+ entering_at[position] = retained == 255;
5514
5998
  }
5515
- if (identical) {
5999
+ if (plan.identical) {
5516
6000
  if (first_error) |err| return err;
5517
6001
  return false;
5518
6002
  }
@@ -5528,26 +6012,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5528
6012
  // while the leaves this transition owes still dispatch
5529
6013
  // below — their Msgs are owned captures, not tree lookups,
5530
6014
  // and a broken destination must never withhold them.
5531
- const destination_ready = !entering_any or
5532
- (self.hoverTreeCurrentFor(standing_window, standing_label) and self.hoverTreeFor(standing_window, standing_label) != null);
5533
- if (!destination_ready) {
5534
- var any_leaving = false;
5535
- for (self.hover_msg_chain[0..mirror_len]) |id| {
5536
- const still_standing = same_view and blk: {
5537
- for (standing_chain[0..standing_len]) |candidate| {
5538
- if (candidate == id) break :blk true;
5539
- }
5540
- break :blk false;
5541
- };
5542
- if (!still_standing) {
5543
- any_leaving = true;
5544
- break;
5545
- }
5546
- }
5547
- // Nothing deliverable now: enters wait for a current
5548
- // tree, retained entries stay put.
5549
- if (!any_leaving) return false;
5550
- }
6015
+ const destination_ready = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .enter, .facts = 1 |
6016
+ @as(u8, if (plan.entering) 2 else 0) | @as(u8, if (self.hoverTreeCurrentFor(standing_window, standing_label)) 4 else 0) |
6017
+ @as(u8, if (self.hoverTreeFor(standing_window, standing_label) != null) 8 else 0) }) != 2;
6018
+ // Deferred enters stay outside the mirror, but owned leaves still deliver.
6019
+ if (!destination_ready and plan.leave_count == 0) return false;
5551
6020
 
5552
6021
  // The leaves this pass owes — mirror ids absent from the
5553
6022
  // standing chain — innermost-first. Their captured Msgs own
@@ -5562,21 +6031,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5562
6031
  @memcpy(leave_label_storage[0..leave_label_len], self.hover_msg_view_label_storage[0..leave_label_len]);
5563
6032
  var leave_ids: [canvas.max_widget_depth]canvas.ObjectId = undefined;
5564
6033
  var leave_slots: [canvas.max_widget_depth]u8 = undefined;
5565
- var leave_count: usize = 0;
5566
- var index = mirror_len;
5567
- while (index > 0) {
5568
- index -= 1;
5569
- const id = self.hover_msg_chain[index];
5570
- const still_standing = same_view and blk: {
5571
- for (standing_chain[0..standing_len]) |candidate| {
5572
- if (candidate == id) break :blk true;
5573
- }
5574
- break :blk false;
5575
- };
5576
- if (still_standing) continue;
5577
- leave_ids[leave_count] = id;
5578
- leave_slots[leave_count] = self.hover_msg_slots[index];
5579
- leave_count += 1;
6034
+ const leave_count = plan.leave_count;
6035
+ for (plan.leaving[0..leave_count], 0..) |index, position| {
6036
+ leave_ids[position] = self.hover_msg_chain[index];
6037
+ leave_slots[position] = self.hover_msg_slots[index];
5580
6038
  }
5581
6039
 
5582
6040
  // Commit the mirror before dispatching so a mid-dispatch
@@ -5610,18 +6068,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5610
6068
  // — and the first error propagates after the batch, into
5611
6069
  // the same degraded handling every event handler gets.
5612
6070
  for (leave_ids[0..leave_count], leave_slots[0..leave_count]) |id, slot| {
5613
- // A refused entry never entered: it owes nothing on
5614
- // exit.
5615
- if (slot == hover_msg_slot_refused) continue;
5616
- // The capture wins (leave answers what enter announced);
5617
- // an unowned capture falls back to the live tree while
5618
- // its element still stands there.
5619
6071
  const captured: ?MsgT = if (slot >= hover_msg_slot_count) null else self.hover_msg_leave_msgs[slot];
5620
- const msg = captured orelse blk: {
5621
- if (!self.hoverTreeCurrentFor(leave_window, leave_label_storage[0..leave_label_len])) break :blk null;
5622
- const live = self.hoverTreeFor(leave_window, leave_label_storage[0..leave_label_len]) orelse break :blk null;
5623
- break :blk live.msgFor(id, .hover_leave);
5624
- } orelse {
6072
+ const live = self.hoverTreeFor(leave_window, leave_label_storage[0..leave_label_len]);
6073
+ const resolution = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .leave, .facts = @as(u8, if (slot == hover_msg_slot_refused) 1 else 0) | @as(u8, if (captured != null) 2 else 0) |
6074
+ @as(u8, if (self.hoverTreeCurrentFor(leave_window, leave_label_storage[0..leave_label_len])) 4 else 0) | @as(u8, if (live != null) 8 else 0) });
6075
+ if (resolution == 0) continue;
6076
+ const msg = (if (resolution == 1) captured else if (resolution == 2) live.?.msgFor(id, .hover_leave) else null) orelse {
5625
6077
  self.releaseHoverSlot(slot);
5626
6078
  continue;
5627
6079
  };
@@ -5634,69 +6086,47 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5634
6086
  self.releaseHoverSlot(slot);
5635
6087
  }
5636
6088
  for (standing_chain[0..standing_len], 0..) |id, position| {
5637
- if (!destination_ready) break;
5638
- if (!entering_at[position]) continue;
5639
- if (!self.hoverTreeCurrentFor(standing_window, standing_label)) {
5640
- // An earlier edge's failed rebuild left this tree
5641
- // stale mid-batch: the same deferral as above — drop
5642
- // the unentered tail from the mirror and retry after
5643
- // a rebuild lands.
6089
+ const live = self.hoverTreeFor(standing_window, standing_label);
6090
+ const admission = hover_policy.decide(self.options.surface_scope_policy, .{ .stage = .enter, .facts = @as(u8, if (destination_ready) 1 else 0) | @as(u8, if (entering_at[position]) 2 else 0) |
6091
+ @as(u8, if (self.hoverTreeCurrentFor(standing_window, standing_label)) 4 else 0) | @as(u8, if (live != null) 8 else 0) });
6092
+ if (admission == 0) break;
6093
+ if (admission == 1) continue;
6094
+ if (admission == 2) {
5644
6095
  self.unwindHoverEnters(&entering_at, position);
5645
6096
  break;
5646
6097
  }
5647
- // Resolve from the LIVE tree per edge: an earlier edge
5648
- // in this batch may have rebuilt the view (payload
5649
- // bytes are only promised for their own dispatch), and
5650
- // its update may even have unmounted this element — a
5651
- // vanished handler then dispatches no enter and owes no
5652
- // leave. The paired leave is captured BEFORE the enter
5653
- // dispatches, from the same tree that resolved it, so
5654
- // an enter whose own handler unmounts the element still
5655
- // has its leave to deliver.
5656
- const live = self.hoverTreeFor(standing_window, standing_label) orelse {
5657
- // A failed rebuild cleared the tree mid-batch: drop
5658
- // the not-yet-entered ids from the mirror so the
5659
- // next drain retries them once the tree returns (the
5660
- // entering-with-no-tree deferral above then holds
5661
- // the line instead of consuming enters as silence).
5662
- self.unwindHoverEnters(&entering_at, position);
5663
- break;
5664
- };
5665
- const enter_msg = live.msgFor(id, .hover_enter);
5666
- if (live.msgFor(id, .hover_leave)) |leave_msg| {
6098
+ // Resolve each edge from the current tree; own its paired leave before dispatch.
6099
+ const enter_msg = live.?.msgFor(id, .hover_enter);
6100
+ if (live.?.msgFor(id, .hover_leave)) |leave_msg| {
5667
6101
  const slot = self.claimHoverSlot() orelse {
5668
6102
  // Pool pressure degrades like allocation
5669
6103
  // pressure: defer this id and the entering tail
5670
6104
  // to the next drain.
5671
- self.unwindHoverEnters(&entering_at, position);
5672
- if (first_error == null) first_error = error.OutOfMemory;
6105
+ if (self.hoverCaptureDecision(1, 0, self.hover_msg_slots[position]) == 1) {
6106
+ self.unwindHoverEnters(&entering_at, position);
6107
+ if (first_error == null) first_error = error.OutOfMemory;
6108
+ }
5673
6109
  break;
5674
6110
  };
5675
- self.captureHoverLeave(slot, leave_msg) catch |err| switch (err) {
5676
- error.OutOfMemory => {
5677
- // Transient: an enter whose paired leave
5678
- // cannot be owned must not dispatch — defer
5679
- // this id and the rest of the entering tail
5680
- // to the next drain instead of breaking the
5681
- // pairing guarantee.
5682
- self.releaseHoverSlot(slot);
6111
+ self.captureHoverLeave(slot, leave_msg) catch |err| {
6112
+ self.releaseHoverSlot(slot);
6113
+ const action = self.hoverCaptureDecision(1, if (err == error.OutOfMemory) 0 else 1, self.hover_msg_slots[position]);
6114
+ if (action == 1) {
5683
6115
  self.unwindHoverEnters(&entering_at, position);
5684
6116
  if (first_error == null) first_error = error.OutOfMemory;
5685
6117
  break;
5686
- },
5687
- error.HoverCapturePayloadUnsupported => {
5688
- // Permanent: no copy can own this payload
5689
- // (a single-item pointer), so the PAIR is
5690
- // disabled — the enter is refused too,
5691
- // once, loudly, and the entry settles as
5692
- // refused instead of retrying every drain.
5693
- self.releaseHoverSlot(slot);
6118
+ }
6119
+ if (action == 2) {
5694
6120
  self.releaseHoverSlot(self.hover_msg_slots[position]);
5695
6121
  self.hover_msg_slots[position] = hover_msg_slot_refused;
5696
6122
  ui_app_log.warn("on_hover_leave payload cannot be owned (a single-item pointer): the hover pair is disabled for this element - bind a slice or scalar payload instead", .{});
5697
- continue;
5698
- },
6123
+ }
6124
+ continue;
5699
6125
  };
6126
+ if (self.hoverCaptureDecision(1, 2, self.hover_msg_slots[position]) != 4) {
6127
+ self.releaseHoverSlot(slot);
6128
+ continue;
6129
+ }
5700
6130
  // A mid-batch rebuild's capture refresh can have
5701
6131
  // filled this position's slot already (an earlier
5702
6132
  // edge's dispatch rebuilt): release it before the
@@ -5724,20 +6154,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5724
6154
  /// sees them as entering again and retries. Their positions hold
5725
6155
  /// no capture slots yet, so nothing needs releasing.
5726
6156
  fn unwindHoverEnters(self: *Self, entering_at: *const [canvas.max_widget_depth]bool, from: usize) void {
5727
- var kept: usize = 0;
6157
+ const compaction = hover_policy.unwind(self.options.surface_scope_policy, entering_at[0..self.hover_msg_chain_len], from);
6158
+ // Release discarded claims before compacting the native id/slot storage.
6159
+ var kept_position: usize = 0;
5728
6160
  for (0..self.hover_msg_chain_len) |position| {
5729
- if (position >= from and entering_at[position]) {
5730
- // A mid-batch capture refresh can have filled this
5731
- // never-entered position's slot: release it so an
5732
- // unwound enter never leaks its claim.
5733
- self.releaseHoverSlot(self.hover_msg_slots[position]);
5734
- continue;
5735
- }
6161
+ if (kept_position < compaction.len and compaction.kept[kept_position] == position) kept_position += 1 else self.releaseHoverSlot(self.hover_msg_slots[position]);
6162
+ }
6163
+ for (compaction.kept[0..compaction.len], 0..) |position, kept| {
5736
6164
  self.hover_msg_chain[kept] = self.hover_msg_chain[position];
5737
6165
  self.hover_msg_slots[kept] = self.hover_msg_slots[position];
5738
- kept += 1;
5739
6166
  }
5740
- self.hover_msg_chain_len = kept;
6167
+ self.hover_msg_chain_len = compaction.len;
5741
6168
  }
5742
6169
 
5743
6170
  /// Re-render the house video chrome from the moved channel
@@ -5782,10 +6209,44 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5782
6209
  try self.rebuildVideoChrome(runtime);
5783
6210
  }
5784
6211
 
6212
+ fn pressHoldPlan(self: *const Self, operation: u8, has_hold: bool, tree_available: bool) u8 {
6213
+ const armed = self.hold_armed_id != 0;
6214
+ if (self.options.press_hold_policy) |policy| {
6215
+ const facts = @as(u8, @intFromBool(armed)) |
6216
+ (@as(u8, @intFromBool(self.hold_fired)) << 1) |
6217
+ (@as(u8, @intFromBool(has_hold)) << 2) |
6218
+ (@as(u8, @intFromBool(tree_available)) << 3);
6219
+ const request = [_]u8{ 19, operation, facts };
6220
+ var result: [1]u8 = undefined;
6221
+ const allowed: u8 = switch (operation) {
6222
+ 0 => 7,
6223
+ 1 => 11,
6224
+ 2 => 16,
6225
+ 3 => 3,
6226
+ else => unreachable,
6227
+ };
6228
+ if (policy(&request, &result) != result.len or result[0] & ~allowed != 0 or
6229
+ (result[0] & 4 != 0 and !has_hold) or
6230
+ (result[0] & 16 != 0 and (!armed or self.hold_fired or !tree_available)))
6231
+ @panic("invalid compiled press hold result");
6232
+ return result[0];
6233
+ }
6234
+ if (operation == 2) return if (armed and !self.hold_fired and tree_available) 16 else 0;
6235
+ const reset: u8 = 2 | @as(u8, @intFromBool(armed and !self.hold_fired));
6236
+ return reset | (if (operation == 0 and has_hold) @as(u8, 4) else 0) |
6237
+ (if (operation == 1 and self.hold_fired) @as(u8, 8) else 0);
6238
+ }
6239
+
6240
+ fn applyHoldReset(self: *Self, runtime: *Runtime, plan: u8) void {
6241
+ if (plan & 1 != 0) runtime.cancelTimer(press_hold_timer_id) catch {};
6242
+ if (plan & 2 != 0) {
6243
+ self.hold_armed_id = 0;
6244
+ self.hold_fired = false;
6245
+ }
6246
+ }
6247
+
5785
6248
  fn disarmHold(self: *Self, runtime: *Runtime) void {
5786
- if (self.hold_armed_id != 0 and !self.hold_fired) runtime.cancelTimer(press_hold_timer_id) catch {};
5787
- self.hold_armed_id = 0;
5788
- self.hold_fired = false;
6249
+ self.applyHoldReset(runtime, self.pressHoldPlan(3, false, false));
5789
6250
  }
5790
6251
 
5791
6252
  /// The hold timer fired while the press is still down: dispatch
@@ -5794,11 +6255,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5794
6255
  /// that this gesture consumed its press.
5795
6256
  fn firePressHold(self: *Self, runtime: *Runtime) anyerror!void {
5796
6257
  const armed_id = self.hold_armed_id;
5797
- if (armed_id == 0 or self.hold_fired) return;
5798
6258
  const hold_label = self.hold_view_label_storage[0..self.hold_view_label_len];
5799
- const tree = self.treeForViewLabel(hold_label) orelse return;
6259
+ const tree = if (armed_id != 0 and !self.hold_fired) self.treeForViewLabel(hold_label) else null;
6260
+ if (self.pressHoldPlan(2, false, tree != null) & 16 == 0) return;
5800
6261
  self.hold_fired = true;
5801
- if (tree.msgForHold(armed_id)) |msg| {
6262
+ if (tree.?.msgForHold(armed_id)) |msg| {
5802
6263
  try self.dispatch(runtime, self.hold_window_id, msg);
5803
6264
  }
5804
6265
  }
@@ -5815,14 +6276,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
5815
6276
  // on_dismiss (its open state lives here, not in the model):
5816
6277
  // close the state and rebuild, agreeing with the engine's
5817
6278
  // optimistic hide.
5818
- if (self.context_menu_fallback_target != 0) {
5819
- if (tree.context_menu_fallback) |fallback| {
5820
- if (fallback.surface_id == dismiss_event.id) {
5821
- self.clearContextMenuFallback();
5822
- try self.rebuildAllViews(runtime);
5823
- return;
5824
- }
5825
- }
6279
+ const fallback = tree.context_menu_fallback;
6280
+ const matches = if (fallback) |value| value.surface_id == dismiss_event.id else false;
6281
+ if (self.componentDecision(.fallback_dismiss, self.context_menu_fallback_target != 0, fallback != null, matches) != 0) {
6282
+ self.clearContextMenuFallback();
6283
+ try self.rebuildAllViews(runtime);
6284
+ return;
5826
6285
  }
5827
6286
  if (tree.msgForDismiss(dismiss_event.id)) |msg| {
5828
6287
  try self.dispatch(runtime, dismiss_event.window_id, msg);
@@ -6124,19 +6583,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6124
6583
  /// point, and view dimensions so it can preview a semantic insertion
6125
6584
  /// during motion, commit it on release, or restore it on cancel.
6126
6585
  fn handleWidgetDrag(self: *Self, runtime: *Runtime, drag_event: core.CanvasWidgetDragEvent) anyerror!void {
6127
- // The runtime promotes a source only after this slop, so terminal
6128
- // phases are always real drags and must dispatch even when the
6129
- // pointer returned near its origin before release. Change events
6130
- // below slop remain on the low-level channel to own text motion,
6131
- // but declarative apps do not hear them.
6132
- if (drag_event.drag.phase == .change and
6133
- !canvas_widget_events.canvasWidgetDragCrossedSlop(drag_event.drag.delta)) return;
6134
- const source = drag_event.source orelse return;
6135
- // Once drag wins the pointer gesture it also owns its delayed
6136
- // interpretation. An element may declare both on-hold and on-drag;
6137
- // leaving the down-armed timer live would dispatch the hold Msg in
6138
- // the middle of a stationary drag and then dispatch drag end too.
6139
- if (drag_event.drag.phase == .change) self.disarmHold(runtime);
6586
+ const policy = self.options.surface_scope_policy;
6587
+ const phase = drag_policy.dragPhase(drag_event.drag.phase);
6588
+ const admission = drag_policy.decide(policy, .{ .stage = .delivery, .phase = phase, .facts = @intFromBool(drag_event.source != null), .delta = drag_event.drag.delta });
6589
+ if (admission == 0) return;
6590
+ const source = drag_event.source.?;
6591
+ if (admission == 1) self.disarmHold(runtime);
6140
6592
  const tree = self.treeForViewLabel(drag_event.view_label);
6141
6593
  const live_template = if (tree) |value| value.msgFor(source.id, .drag) else null;
6142
6594
  const layout: ?canvas.WidgetLayoutTree = runtime.canvasWidgetLayout(drag_event.window_id, drag_event.view_label) catch null;
@@ -6144,31 +6596,23 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6144
6596
  const root = root_value.normalized();
6145
6597
  break :blk geometry.SizeF.init(root.width, root.height);
6146
6598
  } else null else null;
6147
-
6148
- if (drag_event.drag.phase == .change) {
6149
- const template = live_template orelse return;
6150
- const view_size = live_view_size orelse return;
6151
- const msg = Ui.Tree.msgForDragTemplate(template, drag_event.drag, view_size) orelse return;
6152
- // Capture before dispatch: this very Msg may rebuild the tree
6153
- // without its source or handler.
6154
- try self.captureWidgetDragMsg(drag_event, template, view_size);
6155
- try self.dispatch(runtime, drag_event.window_id, msg);
6599
+ const captured = if (admission == 2) self.widgetDragCaptureMatches(drag_event.window_id, drag_event.view_label, source.id) else false;
6600
+ const resolve = drag_policy.decide(policy, .{ .stage = .resolve, .phase = phase, .facts = @as(u8, if (live_template != null) 1 else 0) | @as(u8, if (live_view_size != null) 2 else 0) |
6601
+ @as(u8, if (captured) 4 else 0) | @as(u8, if (self.drag_msg_template != null) 8 else 0) });
6602
+ if (resolve == 32) {
6603
+ self.clearWidgetDragMsgCapture();
6156
6604
  return;
6157
6605
  }
6158
-
6159
- const captured = self.widgetDragCaptureMatches(drag_event.window_id, drag_event.view_label, source.id);
6160
- const maybe_template: ?MsgT = live_template orelse if (captured) self.drag_msg_template else null;
6161
- const template = maybe_template orelse {
6162
- if (captured) self.clearWidgetDragMsgCapture();
6163
- return;
6164
- };
6165
- const view_size = live_view_size orelse if (captured) self.drag_msg_view_size else return;
6166
- const msg = Ui.Tree.msgForDragTemplate(template, drag_event.drag, view_size) orelse {
6167
- if (captured) self.clearWidgetDragMsgCapture();
6168
- return;
6169
- };
6170
- defer if (captured) self.clearWidgetDragMsgCapture();
6171
- try self.dispatch(runtime, drag_event.window_id, msg);
6606
+ if (resolve == 0) return;
6607
+ const template = if (resolve & 1 != 0) live_template.? else self.drag_msg_template.?;
6608
+ const view_size = if (resolve & 4 != 0) live_view_size.? else self.drag_msg_view_size;
6609
+ const msg = Ui.Tree.msgForDragTemplate(template, drag_event.drag, view_size);
6610
+ const action = drag_policy.decide(policy, .{ .stage = .message, .phase = phase, .facts = @as(u8, if (msg != null) 1 else 0) | @as(u8, if (captured) 2 else 0) });
6611
+ defer if (action & 4 != 0) self.clearWidgetDragMsgCapture();
6612
+ if (action & 1 == 0) return;
6613
+ // Copy before dispatch: the resulting Msg may remove its source.
6614
+ if (action & 2 != 0) try self.captureWidgetDragMsg(drag_event, template, view_size);
6615
+ try self.dispatch(runtime, drag_event.window_id, msg.?);
6172
6616
  }
6173
6617
 
6174
6618
  fn captureWidgetDragMsg(self: *Self, drag_event: core.CanvasWidgetDragEvent, template: MsgT, view_size: geometry.SizeF) anyerror!void {
@@ -6189,10 +6633,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6189
6633
  }
6190
6634
 
6191
6635
  fn widgetDragCaptureMatches(self: *const Self, window_id: platform.WindowId, view_label: []const u8, source_id: canvas.ObjectId) bool {
6192
- return self.drag_msg_template != null and
6193
- self.drag_msg_window_id == window_id and
6194
- self.drag_msg_source_id == source_id and
6195
- std.mem.eql(u8, self.drag_msg_view_label_storage[0..self.drag_msg_view_label_len], view_label);
6636
+ return drag_policy.decide(self.options.surface_scope_policy, .{ .stage = .capture_match, .facts = @as(u8, if (self.drag_msg_template != null) 1 else 0) | @as(u8, if (self.drag_msg_window_id == window_id) 2 else 0) |
6637
+ @as(u8, if (self.drag_msg_source_id == source_id) 4 else 0) |
6638
+ @as(u8, if (std.mem.eql(u8, self.drag_msg_view_label_storage[0..self.drag_msg_view_label_len], view_label)) 8 else 0) }) != 0;
6196
6639
  }
6197
6640
 
6198
6641
  fn clearWidgetDragMsgCapture(self: *Self) void {
@@ -6264,10 +6707,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6264
6707
  rebuilt = true;
6265
6708
  }
6266
6709
  }
6267
- if (!rebuilt and self.installed and
6268
- std.mem.eql(u8, scroll_event.view_label, self.options.canvas_label) and
6269
- self.isVirtualWindowId(scroll_event.id))
6270
- {
6710
+ const rebuild_plan = component_policy.plan(self.options.component_policy, .scroll_rebuild, rebuilt, self.installed, std.mem.eql(u8, scroll_event.view_label, self.options.canvas_label), @intFromBool(self.isVirtualWindowId(scroll_event.id)), 0);
6711
+ if (rebuild_plan[0] != 0) {
6271
6712
  try self.rebuild(runtime, scroll_event.window_id);
6272
6713
  }
6273
6714
  }
@@ -6288,20 +6729,26 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6288
6729
  // the tree first — silently arming nothing would leave the
6289
6730
  // presented menu's selection to fall through a null tree
6290
6731
  // and dispatch no message.
6291
- if (self.treeForViewLabel(shown_event.view_label) == null) try self.restoreMissingTree(runtime);
6732
+ if (self.componentDecision(.missing_tree, self.treeForViewLabel(shown_event.view_label) == null, false, false) != 0) try self.restoreMissingTree(runtime);
6292
6733
  const tree = self.treeForViewLabel(shown_event.view_label) orelse return;
6293
- const count = @min(shown_event.item_count, self.context_menu_shown_msgs.len);
6734
+ const count_plan = component_policy.plan(self.options.component_policy, .shown_count, false, false, false, shown_event.item_count, self.context_menu_shown_msgs.len);
6735
+ const count: usize = @intCast(std.mem.readInt(u64, count_plan[8..16], .little));
6294
6736
  for (0..count) |item_index| {
6295
6737
  self.context_menu_shown_msgs[item_index] = tree.msgForContextMenu(shown_event.target_id, item_index);
6296
6738
  }
6297
6739
  self.context_menu_shown_token = shown_event.token;
6298
6740
  self.context_menu_shown_count = count;
6299
- self.context_menu_pin = if (std.mem.eql(u8, shown_event.view_label, self.options.canvas_label))
6300
- .{ .window_id = null, .arena_index = self.arena_index }
6301
- else if (self.windowSlotByCanvasLabel(shown_event.view_label)) |slot|
6302
- .{ .window_id = slot.window_id, .arena_index = slot.arena_index }
6303
- else
6304
- null;
6741
+ const slot = self.windowSlotByCanvasLabel(shown_event.view_label);
6742
+ const owner = self.componentDecision(.pin_owner, std.mem.eql(u8, shown_event.view_label, self.options.canvas_label), slot != null, false);
6743
+ self.context_menu_pin = switch (owner) {
6744
+ 1 => .{ .window_id = null, .arena_index = self.arena_index },
6745
+ 2 => .{ .window_id = slot.?.window_id, .arena_index = slot.?.arena_index },
6746
+ else => null,
6747
+ };
6748
+ }
6749
+
6750
+ fn componentDecision(self: *const Self, stage: component_policy.Stage, a: bool, b: bool, c: bool) u8 {
6751
+ return component_policy.plan(self.options.component_policy, stage, a, b, c, 0, 0)[0];
6305
6752
  }
6306
6753
 
6307
6754
  /// The arena index this canvas's next rebuild must use:
@@ -6315,13 +6762,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6315
6762
  /// therefore bounded at two trees, however many rebuilds occur.
6316
6763
  fn contextMenuRebuildIndex(self: *const Self, window_id: ?platform.WindowId, current_index: usize) usize {
6317
6764
  const natural = current_index ^ 1;
6318
- const pin = self.context_menu_pin orelse return natural;
6319
- if (pin.arena_index != natural) return natural;
6320
- const matches = if (pin.window_id) |pin_window|
6321
- (window_id orelse return natural) == pin_window
6322
- else
6323
- window_id == null;
6324
- return if (matches) natural ^ 1 else natural;
6765
+ const pin = self.context_menu_pin;
6766
+ const matches = if (pin) |value| value.window_id == window_id else false;
6767
+ const pinned = if (pin) |value| value.arena_index == natural else false;
6768
+ return natural ^ self.componentDecision(.rebuild_arena, pin != null, pinned, matches);
6325
6769
  }
6326
6770
 
6327
6771
  /// Window teardown for the pin's owner: the slot's arenas are
@@ -6330,9 +6774,10 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6330
6774
  /// a stale pin would otherwise keep steering the reused slot's
6331
6775
  /// rebuild cadence around a generation that no longer exists.
6332
6776
  fn releaseContextMenuSnapshotForWindow(self: *Self, window_id: platform.WindowId) void {
6333
- const pin = self.context_menu_pin orelse return;
6334
- const pin_window = pin.window_id orelse return;
6335
- if (pin_window == window_id) self.releaseContextMenuSnapshot();
6777
+ const pin = self.context_menu_pin;
6778
+ const has_window = if (pin) |value| value.window_id != null else false;
6779
+ const matches = if (pin) |value| value.window_id == window_id else false;
6780
+ if (self.componentDecision(.release_window, pin != null, has_window, matches) != 0) self.releaseContextMenuSnapshot();
6336
6781
  }
6337
6782
 
6338
6783
  /// Disarm the presented-menu snapshot and release the pinned
@@ -6350,7 +6795,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6350
6795
  /// token's notice is ignored (a superseding presentation
6351
6796
  /// already replaced the snapshot and the pin).
6352
6797
  fn handleContextMenuDismissed(self: *Self, runtime: *Runtime, dismissed_event: core.CanvasWidgetContextMenuDismissedEvent) anyerror!void {
6353
- if (dismissed_event.token == 0 or dismissed_event.token != self.context_menu_shown_token) return;
6798
+ if (self.componentDecision(.dismiss_token, dismissed_event.token != 0, dismissed_event.token == self.context_menu_shown_token, false) == 0) return;
6354
6799
  self.releaseContextMenuSnapshot();
6355
6800
  try self.restoreMissingTree(runtime);
6356
6801
  }
@@ -6364,12 +6809,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6364
6809
  /// no-ops until an unrelated resize, timer, or effect happens
6365
6810
  /// to rebuild.
6366
6811
  fn restoreMissingTree(self: *Self, runtime: *Runtime) anyerror!void {
6367
- if (!self.installed) return;
6368
- var missing = self.tree == null;
6812
+ var secondary_missing = false;
6369
6813
  for (self.window_slots[0..self.window_slot_count]) |*slot| {
6370
- if (slot.installed and slot.tree == null) missing = true;
6814
+ if (slot.installed and slot.tree == null) secondary_missing = true;
6371
6815
  }
6372
- if (missing) try self.rebuildAllViews(runtime);
6816
+ if (self.componentDecision(.restore_tree, self.installed, self.tree == null, secondary_missing) != 0) try self.rebuildAllViews(runtime);
6373
6817
  }
6374
6818
 
6375
6819
  /// A native context-menu selection: resolve the selected item's
@@ -6382,32 +6826,30 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6382
6826
  // A selection on this menu closes it whatever the source: an
6383
6827
  // automation-invoked selection while the fallback surface is
6384
6828
  // open must not leave the surface mounted.
6385
- if (self.context_menu_fallback_target == menu_event.target_id) {
6386
- self.clearContextMenuFallback();
6387
- }
6388
- if (menu_event.token != 0 and menu_event.token == self.context_menu_shown_token) {
6829
+ const begin = self.componentDecision(.selection_begin, self.context_menu_fallback_target == menu_event.target_id, menu_event.token != 0, menu_event.token == self.context_menu_shown_token);
6830
+ if (begin & 1 != 0) self.clearContextMenuFallback();
6831
+ if (begin & 2 != 0) {
6389
6832
  const count = self.context_menu_shown_count;
6390
6833
  // The request is consumed on every path out of this
6391
6834
  // block — resolved, out-of-range, or a failed dispatch.
6392
6835
  defer self.releaseContextMenuSnapshot();
6393
- if (menu_event.item_index < count) {
6394
- if (self.context_menu_shown_msgs[menu_event.item_index]) |msg| {
6395
- // The Msg is stored by value and its pinned-arena
6396
- // payload slices are consumed by `update` itself;
6397
- // the rebuild that follows reads only the model.
6398
- // Release the pin BEFORE the dispatch: nothing
6399
- // resets the pinned arena until the rebuild, and
6400
- // the rebuild then routes into the partner arena
6401
- // naturally — so a Msg whose update pushes the
6402
- // model past a build budget fails the rebuild
6403
- // WITHOUT resetting the live arena underneath it.
6404
- // Input keeps working on the previous tree, and
6405
- // the app's controls can recover the model —
6406
- // production's degraded-error contract.
6407
- self.releaseContextMenuSnapshot();
6408
- try self.dispatch(runtime, menu_event.window_id, msg);
6409
- return;
6410
- }
6836
+ const msg = if (menu_event.item_index < count) self.context_menu_shown_msgs[menu_event.item_index] else null;
6837
+ if (self.componentDecision(.selection_item, menu_event.item_index < count, msg != null, false) == 1) {
6838
+ // The Msg is stored by value and its pinned-arena
6839
+ // payload slices are consumed by `update` itself;
6840
+ // the rebuild that follows reads only the model.
6841
+ // Release the pin BEFORE the dispatch: nothing
6842
+ // resets the pinned arena until the rebuild, and
6843
+ // the rebuild then routes into the partner arena
6844
+ // naturally — so a Msg whose update pushes the
6845
+ // model past a build budget fails the rebuild
6846
+ // WITHOUT resetting the live arena underneath it.
6847
+ // Input keeps working on the previous tree, and
6848
+ // the app's controls can recover the model —
6849
+ // production's degraded-error contract.
6850
+ self.releaseContextMenuSnapshot();
6851
+ try self.dispatch(runtime, menu_event.window_id, msg.?);
6852
+ return;
6411
6853
  }
6412
6854
  // Swallowed without a Msg (out of range, or an item the
6413
6855
  // presented tree never mapped): no dispatch rebuilds, so
@@ -6420,7 +6862,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6420
6862
  // failed while the model was unbuildable): the model may
6421
6863
  // have recovered since, so restore a dropped tree before
6422
6864
  // resolving rather than silently dispatching nothing.
6423
- if (self.treeForViewLabel(menu_event.view_label) == null) try self.restoreMissingTree(runtime);
6865
+ if (self.componentDecision(.missing_tree, self.treeForViewLabel(menu_event.view_label) == null, false, false) != 0) try self.restoreMissingTree(runtime);
6424
6866
  const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
6425
6867
  if (tree.msgForContextMenu(menu_event.target_id, menu_event.item_index)) |msg| {
6426
6868
  try self.dispatch(runtime, menu_event.window_id, msg);
@@ -6450,9 +6892,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6450
6892
  /// being rebuilt, or 0 when the open fallback (if any) belongs to
6451
6893
  /// a different view.
6452
6894
  fn contextMenuFallbackTargetForLabel(self: *const Self, view_label: []const u8) canvas.ObjectId {
6453
- if (self.context_menu_fallback_target == 0) return 0;
6454
- if (!std.mem.eql(u8, view_label, self.contextMenuFallbackLabel())) return 0;
6455
- return self.context_menu_fallback_target;
6895
+ return if (self.componentDecision(.fallback_label, self.context_menu_fallback_target != 0, std.mem.eql(u8, view_label, self.contextMenuFallbackLabel()), false) != 0) self.context_menu_fallback_target else 0;
6456
6896
  }
6457
6897
 
6458
6898
  fn clearContextMenuFallback(self: *Self) void {
@@ -6464,7 +6904,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6464
6904
  /// menu's open state lives here, not in the model, so opening and
6465
6905
  /// closing it re-derives the views directly.
6466
6906
  fn rebuildAllViews(self: *Self, runtime: *Runtime) anyerror!void {
6467
- if (!self.installed) return;
6907
+ if (self.componentDecision(.rebuild_views, self.installed, false, false) == 0) return;
6468
6908
  try self.rebuild(runtime, self.canvas_window_id);
6469
6909
  try self.rebuildWindowSlots(runtime);
6470
6910
  }
@@ -6475,12 +6915,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
6475
6915
  /// a native selection resolves. Returns true when the id was a
6476
6916
  /// fallback item (consumed either way).
6477
6917
  fn dispatchContextMenuFallbackItem(self: *Self, runtime: *Runtime, tree: *const Ui.Tree, window_id: platform.WindowId, id: canvas.ObjectId) anyerror!bool {
6478
- if (self.context_menu_fallback_target == 0) return false;
6479
- const fallback = tree.context_menu_fallback orelse return false;
6480
- const item_index = fallback.itemIndex(id) orelse return false;
6918
+ const fallback = tree.context_menu_fallback;
6919
+ const item_index = if (fallback) |value| value.itemIndex(id) else null;
6920
+ if (self.componentDecision(.fallback_item, self.context_menu_fallback_target != 0, fallback != null, item_index != null) == 0) return false;
6481
6921
  self.clearContextMenuFallback();
6482
- if (tree.msgForContextMenu(fallback.target_id, item_index)) |msg| {
6483
- try self.dispatch(runtime, window_id, msg);
6922
+ const msg = tree.msgForContextMenu(fallback.?.target_id, item_index.?);
6923
+ if (self.componentDecision(.fallback_dispatch, msg != null, false, false) == 1) {
6924
+ try self.dispatch(runtime, window_id, msg.?);
6484
6925
  } else {
6485
6926
  try self.rebuildAllViews(runtime);
6486
6927
  }
@@ -6578,3 +7019,50 @@ const ContextMenuPin = struct {
6578
7019
  window_id: ?platform.WindowId,
6579
7020
  arena_index: usize,
6580
7021
  };
7022
+
7023
+ fn effectsRestoreWindowResult(context: *anyopaque, label: []const u8, closed: bool) void {
7024
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7025
+ runtime.restoreWindowCapabilityResult(label, closed);
7026
+ }
7027
+
7028
+ fn effectsExecuteCapability(context: *anyopaque, name: []const u8, payload: []const u8, output: []u8) anyerror![]const u8 {
7029
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
7030
+ const desktop_files = @import("desktop_files.zig");
7031
+ var reader = try desktop_files.request(payload);
7032
+ if (std.mem.eql(u8, name, "native-sdk.window.focusResult") or std.mem.eql(u8, name, "native-sdk.window.closeResult")) {
7033
+ const label = try reader.field();
7034
+ try reader.finish();
7035
+ if (label.len == 0 or label.len > 255 or std.mem.indexOfScalar(u8, label, 0) != null) return error.InvalidRequest;
7036
+ const window_id = effectsWindowIdByLabel(runtime, label) orelse
7037
+ return output[0..try desktop_files.replyHeaderFor(output, payload, "WindowNotFound")];
7038
+ if (std.mem.eql(u8, name, "native-sdk.window.focusResult")) {
7039
+ runtime.focusWindow(window_id) catch |err| return output[0..try desktop_files.replyHeaderFor(output, payload, @errorName(err))];
7040
+ } else {
7041
+ runtime.closeWindow(window_id) catch |err| return output[0..try desktop_files.replyHeaderFor(output, payload, @errorName(err))];
7042
+ }
7043
+ return output[0..try desktop_files.replyHeaderFor(output, payload, "")];
7044
+ }
7045
+ if (std.mem.eql(u8, name, "native-sdk.dialog.openDirectory")) {
7046
+ if (!authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_dialog)) return error.PermissionDenied;
7047
+ const title = try reader.field();
7048
+ const path = try reader.field();
7049
+ try reader.finish();
7050
+ if (title.len > 255 or path.len > desktop_files.max_path_bytes or std.mem.indexOfScalar(u8, path, 0) != null) return error.InvalidRequest;
7051
+ var storage: [platform.max_dialog_paths_bytes]u8 = undefined;
7052
+ const result = runtime.showOpenDialog(.{ .title = title, .default_path = path, .allow_directories = true, .allow_multiple = false }, &storage) catch |err| {
7053
+ return output[0..try desktop_files.replyHeaderFor(output, payload, @errorName(err))];
7054
+ };
7055
+ const selected = if (result.count == 0) "" else result.paths;
7056
+ const header = try desktop_files.replyHeaderFor(output, payload, "");
7057
+ if (selected.len > 65535 or output.len - header < 2 or selected.len > output.len - header - 2) return error.OverBound;
7058
+ std.mem.writeInt(u16, output[header..][0..2], @intCast(selected.len), .little);
7059
+ @memcpy(output[header + 2 ..][0..selected.len], selected);
7060
+ return output[0 .. header + 2 + selected.len];
7061
+ }
7062
+ if (!authorization.hasPermission(runtime.authorization_policy, runtime.options.security.permissions, security.permission_filesystem)) return error.PermissionDenied;
7063
+ if (comptime builtin.os.tag == .macos or builtin.os.tag == .linux or builtin.os.tag == .windows) {
7064
+ var threaded = std.Io.Threaded.init(runtime.owned_allocator, .{});
7065
+ defer threaded.deinit();
7066
+ return desktop_files.execute(threaded.io(), name, payload, output);
7067
+ } else return error.Unsupported;
7068
+ }