@native-sdk/cli 0.10.1 → 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 (462) 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 +1796 -83
  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/native-ui/SKILL.md +76 -17
  130. package/skill-data/ts-core/SKILL.md +113 -9
  131. package/skill-data/ts-services/SKILL.md +1 -1
  132. package/skill-data/ts-services/references/service-surface.md +264 -144
  133. package/src/app_runner/root.zig +25 -12
  134. package/src/app_runner/ts_compiled_view.zig +1631 -0
  135. package/src/app_runner/ts_core_main.zig +143 -10
  136. package/src/app_runner/ts_core_mobile.zig +24 -12
  137. package/src/automation/server.zig +1 -3
  138. package/src/automation/snapshot.zig +9 -637
  139. package/src/automation/snapshot_reference.zig +656 -0
  140. package/src/automation/snapshot_serialization.zig +566 -0
  141. package/src/platform/linux/gtk_host.c +36 -24
  142. package/src/platform/linux/gtk_pixels.h +118 -0
  143. package/src/platform/linux/gtk_pixels_test.c +241 -0
  144. package/src/platform/linux/root.zig +2 -0
  145. package/src/platform/macos/appkit_host.m +188 -30
  146. package/src/platform/macos/pointer_motion_test.m +96 -0
  147. package/src/platform/macos/scroll_driver_test.m +105 -0
  148. package/src/platform/macos/spectrum_bins.h +34 -0
  149. package/src/platform/macos/spectrum_bins_test.c +56 -0
  150. package/src/platform/macos/text_keyboard_test.m +80 -0
  151. package/src/platform/macos/widget_focus_test.m +66 -0
  152. package/src/platform/null_platform.zig +26 -2
  153. package/src/platform/null_platform_tests.zig +13 -0
  154. package/src/platform/root.zig +1 -0
  155. package/src/platform/types.zig +13 -0
  156. package/src/platform/windows/root.zig +2 -0
  157. package/src/platform/windows/webview2_host.cpp +7 -2
  158. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  159. package/src/primitives/app_manifest/root.zig +2 -0
  160. package/src/primitives/app_manifest/tests.zig +4 -1
  161. package/src/primitives/app_manifest/validation.zig +2 -0
  162. package/src/primitives/canvas/a11y_audit.zig +3 -1
  163. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  164. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  165. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  166. package/src/primitives/canvas/code_content_policy.zig +162 -0
  167. package/src/primitives/canvas/commands.zig +29 -1
  168. package/src/primitives/canvas/component_composition.zig +125 -0
  169. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  170. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  171. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  172. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  173. package/src/primitives/canvas/control_command_policy.zig +75 -0
  174. package/src/primitives/canvas/control_content_policy.zig +90 -0
  175. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  176. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  177. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  178. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  179. package/src/primitives/canvas/events.zig +1027 -1
  180. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  181. package/src/primitives/canvas/frame.zig +92 -23
  182. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  183. package/src/primitives/canvas/gpu.zig +10 -0
  184. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  185. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  186. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  187. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  188. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  189. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  190. package/src/primitives/canvas/intrinsic_measure_policy.zig +128 -0
  191. package/src/primitives/canvas/layout_audit.zig +5 -2
  192. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  193. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  194. package/src/primitives/canvas/markdown.zig +13 -3
  195. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  196. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  197. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  198. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  199. package/src/primitives/canvas/reference.zig +12 -6
  200. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  201. package/src/primitives/canvas/render.zig +48 -0
  202. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  203. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  204. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  205. package/src/primitives/canvas/render_effects.zig +14 -0
  206. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  207. package/src/primitives/canvas/render_images.zig +14 -0
  208. package/src/primitives/canvas/render_layers.zig +14 -0
  209. package/src/primitives/canvas/render_override_policy.zig +119 -0
  210. package/src/primitives/canvas/render_paths.zig +14 -0
  211. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  212. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  213. package/src/primitives/canvas/root.zig +100 -0
  214. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  215. package/src/primitives/canvas/serialization.zig +8 -1
  216. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  217. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  218. package/src/primitives/canvas/terminal_grid.zig +10 -696
  219. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  220. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  221. package/src/primitives/canvas/text.zig +1 -0
  222. package/src/primitives/canvas/text_atlas.zig +113 -0
  223. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  224. package/src/primitives/canvas/text_document_policy.zig +120 -0
  225. package/src/primitives/canvas/text_layout.zig +51 -2
  226. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  227. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  228. package/src/primitives/canvas/text_layout_types.zig +3 -0
  229. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  230. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  231. package/src/primitives/canvas/text_metrics.zig +23 -0
  232. package/src/primitives/canvas/text_query_policy.zig +156 -0
  233. package/src/primitives/canvas/text_run_policy.zig +252 -0
  234. package/src/primitives/canvas/text_scalar_policy.zig +156 -0
  235. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  236. package/src/primitives/canvas/text_spans.zig +280 -8
  237. package/src/primitives/canvas/text_tests.zig +10 -0
  238. package/src/primitives/canvas/tokens.zig +38 -0
  239. package/src/primitives/canvas/ui.zig +250 -83
  240. package/src/primitives/canvas/ui_markup.zig +139 -33
  241. package/src/primitives/canvas/ui_markup_compiled.zig +319 -59
  242. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  243. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  244. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  245. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  246. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  247. package/src/primitives/canvas/ui_markup_view.zig +258 -32
  248. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  249. package/src/primitives/canvas/ui_schema.zig +13 -1
  250. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  251. package/src/primitives/canvas/ui_tests.zig +1 -0
  252. package/src/primitives/canvas/vector.zig +36 -2
  253. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  254. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  255. package/src/primitives/canvas/virtual_extent_policy.zig +292 -0
  256. package/src/primitives/canvas/virtual_extents.zig +99 -3
  257. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  258. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  259. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  260. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  261. package/src/primitives/canvas/widget_layout.zig +673 -128
  262. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  263. package/src/primitives/canvas/widget_metric_policy.zig +126 -0
  264. package/src/primitives/canvas/widget_metrics.zig +45 -6
  265. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  266. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  267. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  268. package/src/primitives/canvas/widget_render.zig +744 -74
  269. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  270. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  271. package/src/primitives/canvas/widget_render_style.zig +94 -0
  272. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  273. package/src/primitives/canvas/widget_routing.zig +75 -0
  274. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  275. package/src/primitives/canvas/widget_runtime.zig +20 -1
  276. package/src/primitives/canvas/widget_semantics.zig +25 -0
  277. package/src/primitives/canvas/widget_text_input.zig +86 -23
  278. package/src/primitives/canvas/widget_text_select.zig +1 -0
  279. package/src/primitives/canvas/widget_tree.zig +8 -1
  280. package/src/primitives/canvas/widgets.zig +42 -12
  281. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  282. package/src/root.zig +21 -0
  283. package/src/runtime/accessibility_policy.zig +122 -0
  284. package/src/runtime/api.zig +28 -0
  285. package/src/runtime/app_dispatch_policy.zig +68 -0
  286. package/src/runtime/authorization_policy.zig +150 -0
  287. package/src/runtime/automation_command_policy.zig +241 -0
  288. package/src/runtime/automation_interaction_policy.zig +107 -0
  289. package/src/runtime/automation_snapshot.zig +52 -22
  290. package/src/runtime/automation_snapshot_reference.zig +290 -0
  291. package/src/runtime/automation_widget_dispatch.zig +267 -355
  292. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  293. package/src/runtime/blob_policy.zig +58 -0
  294. package/src/runtime/blob_reference.zig +64 -0
  295. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  296. package/src/runtime/builtin_bridge.zig +180 -44
  297. package/src/runtime/builtin_coordination_policy.zig +121 -0
  298. package/src/runtime/callback_policy_test_reference.zig +97 -0
  299. package/src/runtime/canvas_drag_policy.zig +94 -0
  300. package/src/runtime/canvas_fonts.zig +38 -10
  301. package/src/runtime/canvas_frame.zig +590 -134
  302. package/src/runtime/canvas_frame_helpers.zig +1 -0
  303. package/src/runtime/canvas_hover_policy.zig +131 -0
  304. package/src/runtime/canvas_images.zig +59 -30
  305. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  306. package/src/runtime/canvas_limits.zig +1 -1
  307. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  308. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  309. package/src/runtime/canvas_widget_context_menu.zig +4 -4
  310. package/src/runtime/canvas_widget_display.zig +110 -9
  311. package/src/runtime/canvas_widget_events.zig +718 -328
  312. package/src/runtime/canvas_widget_runtime.zig +437 -81
  313. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  314. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  315. package/src/runtime/canvas_widget_state.zig +93 -56
  316. package/src/runtime/channel_sources.zig +80 -0
  317. package/src/runtime/command_policy.zig +161 -0
  318. package/src/runtime/component_policy.zig +83 -0
  319. package/src/runtime/core.zig +156 -6
  320. package/src/runtime/desktop_files.zig +189 -0
  321. package/src/runtime/effects.zig +466 -29
  322. package/src/runtime/effects_tests.zig +28 -0
  323. package/src/runtime/file_policy_test_reference.zig +113 -0
  324. package/src/runtime/flow.zig +418 -341
  325. package/src/runtime/flow_reference.zig +1426 -0
  326. package/src/runtime/font_registry_policy.zig +72 -0
  327. package/src/runtime/frame_profile.zig +24 -33
  328. package/src/runtime/gpu_surface_events.zig +97 -35
  329. package/src/runtime/host_event_pump.zig +303 -0
  330. package/src/runtime/host_event_pump_reference.zig +268 -0
  331. package/src/runtime/host_flow_policy.zig +155 -0
  332. package/src/runtime/host_input_regions_policy.zig +156 -0
  333. package/src/runtime/image_registry_policy.zig +94 -0
  334. package/src/runtime/input_composition_policy.zig +138 -0
  335. package/src/runtime/journal_policy.zig +66 -0
  336. package/src/runtime/journal_reference.zig +53 -0
  337. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  338. package/src/runtime/markup_development_policy.zig +91 -0
  339. package/src/runtime/media_surface.zig +40 -1
  340. package/src/runtime/motion_sampling_policy.zig +159 -0
  341. package/src/runtime/recording_policy.zig +42 -0
  342. package/src/runtime/render_animation_policy.zig +206 -0
  343. package/src/runtime/replay_policy.zig +66 -0
  344. package/src/runtime/replay_policy_reference.zig +326 -0
  345. package/src/runtime/replay_progress_policy.zig +64 -0
  346. package/src/runtime/replay_progress_reference.zig +34 -0
  347. package/src/runtime/request_policy_test_reference.zig +188 -0
  348. package/src/runtime/root.zig +13 -0
  349. package/src/runtime/session_blobs.zig +157 -58
  350. package/src/runtime/session_blobs_reference.zig +692 -0
  351. package/src/runtime/session_codec.zig +361 -0
  352. package/src/runtime/session_codec_reference.zig +1027 -0
  353. package/src/runtime/session_journal.zig +246 -983
  354. package/src/runtime/session_record.zig +224 -45
  355. package/src/runtime/session_replay.zig +157 -415
  356. package/src/runtime/session_tests.zig +552 -0
  357. package/src/runtime/shell_admission_policy.zig +225 -0
  358. package/src/runtime/shell_coordination_policy.zig +138 -0
  359. package/src/runtime/shell_layout.zig +126 -1
  360. package/src/runtime/snapshot_policy.zig +60 -0
  361. package/src/runtime/snapshot_reference.zig +64 -0
  362. package/src/runtime/state.zig +16 -0
  363. package/src/runtime/status_validation.zig +190 -0
  364. package/src/runtime/system_admission_policy.zig +140 -0
  365. package/src/runtime/system_services.zig +46 -36
  366. package/src/runtime/tests.zig +1 -0
  367. package/src/runtime/ts_canvas_hooks.zig +261 -0
  368. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  369. package/src/runtime/ts_canvas_icons.zig +234 -0
  370. package/src/runtime/ts_core_host.zig +2325 -411
  371. package/src/runtime/ts_core_host_tests.zig +1982 -0
  372. package/src/runtime/ts_test_host.zig +699 -0
  373. package/src/runtime/ts_ui_app.zig +1087 -45
  374. package/src/runtime/ui_app.zig +1117 -629
  375. package/src/runtime/ui_app_provenance.zig +147 -5
  376. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  377. package/src/runtime/ui_app_tests.zig +619 -9
  378. package/src/runtime/ui_app_window_tests.zig +89 -0
  379. package/src/runtime/view.zig +25 -0
  380. package/src/runtime/view_canvas.zig +30 -6
  381. package/src/runtime/view_coordination_policy.zig +147 -0
  382. package/src/runtime/view_widget_control.zig +51 -14
  383. package/src/runtime/view_widget_scroll.zig +16 -5
  384. package/src/runtime/view_widget_text.zig +153 -68
  385. package/src/runtime/view_widget_tree.zig +460 -56
  386. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  387. package/src/runtime/widget_motion_policy.zig +238 -0
  388. package/src/runtime/window_command_bridge_tests.zig +63 -0
  389. package/src/runtime/window_lifecycle_policy.zig +127 -0
  390. package/src/runtime/window_storage.zig +74 -8
  391. package/src/runtime/window_view_runtime.zig +148 -33
  392. package/src/runtime/window_views.zig +163 -10
  393. package/src/tooling/components/identity_tests.zig +62 -36
  394. package/src/tooling/components/stepper.native +24 -0
  395. package/src/tooling/components/stepper.zig +0 -19
  396. package/src/tooling/components/timeline-item.native +22 -0
  397. package/src/tooling/components/timeline.native +5 -3
  398. package/src/tooling/components/timeline_item.zig +0 -32
  399. package/src/tooling/eject_components.zig +76 -8
  400. package/src/tooling/ios.zig +66 -12
  401. package/src/tooling/manifest.zig +35 -0
  402. package/src/tooling/raw_manifest.zig +6 -0
  403. package/src/tooling/templates.zig +15 -3
  404. package/src/tooling/ts_core.zig +13 -3
  405. package/src/tooling/verbs.zig +22 -0
  406. package/tools/corewire/build_profile.mjs +54 -0
  407. package/tools/corewire/contract_intake.ts +303 -0
  408. package/tools/corewire/contract_intake.zig +82 -0
  409. package/tools/corewire/core.test.ts +166 -0
  410. package/tools/corewire/core_abi.zig +51 -0
  411. package/tools/corewire/core_cases.ts +233 -0
  412. package/tools/corewire/core_contract.ts +407 -0
  413. package/tools/corewire/core_emission.ts +136 -0
  414. package/tools/corewire/core_emission.zig +69 -0
  415. package/tools/corewire/core_goldens.json +3110 -0
  416. package/tools/corewire/core_policy.ts +14 -0
  417. package/tools/corewire/core_policy.zig +48 -0
  418. package/tools/corewire/core_projection.ts +360 -0
  419. package/tools/corewire/core_vocabulary.ts +6 -0
  420. package/tools/corewire/emit.zig +19 -1590
  421. package/tools/corewire/emit_facade.ts +714 -0
  422. package/tools/corewire/emit_facade.zig +10 -3752
  423. package/tools/corewire/emit_mirror.ts +290 -0
  424. package/tools/corewire/emit_profile.ts +50 -0
  425. package/tools/corewire/emit_service.ts +331 -0
  426. package/tools/corewire/emit_service.zig +23 -842
  427. package/tools/corewire/entry.test.ts +95 -0
  428. package/tools/corewire/entry_coordination.ts +127 -0
  429. package/tools/corewire/entry_coordination.zig +190 -0
  430. package/tools/corewire/facade_templates.ts +85 -0
  431. package/tools/corewire/filesystem.test.ts +166 -0
  432. package/tools/corewire/filesystem_coordination.ts +213 -0
  433. package/tools/corewire/filesystem_coordination.zig +245 -0
  434. package/tools/corewire/intake.test.ts +35 -0
  435. package/tools/corewire/intake_cases.ts +55 -0
  436. package/tools/corewire/intake_goldens.json +12237 -0
  437. package/tools/corewire/invocation.test.ts +24 -0
  438. package/tools/corewire/invocation.ts +175 -0
  439. package/tools/corewire/invocation.zig +136 -0
  440. package/tools/corewire/invocation_cases.ts +60 -0
  441. package/tools/corewire/invocation_fixture.ts +33 -0
  442. package/tools/corewire/invocation_goldens.json +1143 -0
  443. package/tools/corewire/invocation_tests.zig +111 -0
  444. package/tools/corewire/invocation_usage.ts +2 -0
  445. package/tools/corewire/lossless_projection.ts +96 -0
  446. package/tools/corewire/main.zig +7 -680
  447. package/tools/corewire/main_reference.zig +415 -0
  448. package/tools/corewire/mirror_templates.ts +55 -0
  449. package/tools/corewire/profile.test.ts +248 -0
  450. package/tools/corewire/profile.zig +56 -0
  451. package/tools/corewire/profile_emission.ts +202 -0
  452. package/tools/corewire/profile_library.json +29 -0
  453. package/tools/corewire/profile_tests.zig +136 -0
  454. package/tools/corewire/service.test.ts +75 -0
  455. package/tools/corewire/service_cases.ts +61 -0
  456. package/tools/corewire/service_contract.zig +40 -146
  457. package/tools/corewire/service_goldens.json +650 -0
  458. package/tools/corewire/service_projection.zig +52 -0
  459. package/tools/corewire/service_templates.ts +14 -0
  460. package/tools/corewire/shim_rt.zig +9 -0
  461. package/tools/corewire/sidecar.zig +267 -1438
  462. package/tools/corewire/emit_profile.zig +0 -521
@@ -0,0 +1,1426 @@
1
+ const builtin_coordination = @import("builtin_coordination_policy.zig");
2
+ const authorization = @import("authorization_policy.zig");
3
+ const std = @import("std");
4
+ const geometry = @import("geometry");
5
+ const trace = @import("trace");
6
+ const json = @import("json");
7
+ const validation = @import("validation.zig");
8
+ const command_policy = @import("command_policy.zig");
9
+ const runtime_api = @import("api.zig");
10
+ const runtime_async_bridge = @import("async_bridge.zig");
11
+ const runtime_automation_snapshot = @import("automation_snapshot.zig");
12
+ const runtime_automation_widget_dispatch = @import("automation_widget_dispatch.zig");
13
+ const automation_commands = @import("automation_command_policy.zig");
14
+ const launch_timing = @import("launch_timing.zig");
15
+ const runtime_clock = @import("clock.zig");
16
+ const runtime_state = @import("state.zig");
17
+ const shell_layout = @import("shell_layout.zig");
18
+ const runtime_builtin_bridge = @import("builtin_bridge.zig");
19
+ const runtime_canvas_widget_events = @import("canvas_widget_events.zig");
20
+ const runtime_canvas_widget_context_menu = @import("canvas_widget_context_menu.zig");
21
+ const runtime_canvas_widget_scroll_drivers = @import("canvas_widget_scroll_drivers.zig");
22
+ const runtime_gpu_surface_events = @import("gpu_surface_events.zig");
23
+ const runtime_system_services = @import("system_services.zig");
24
+ const runtime_window_views = @import("window_views.zig");
25
+ const widget_bridge = @import("widget_bridge.zig");
26
+ const automation = @import("../automation/root.zig");
27
+ const bridge = @import("../bridge/root.zig");
28
+ const extensions = @import("../extensions/root.zig");
29
+ const app_manifest = @import("app_manifest");
30
+ const platform = @import("../platform/root.zig");
31
+ const HostEventPump = @import("host_event_pump_reference.zig").HostEventPump;
32
+ const security = @import("../security/root.zig");
33
+
34
+ const validateCommandName = validation.validateCommandName;
35
+ const sceneNeedsMainWebView = shell_layout.sceneNeedsMainWebView;
36
+ const shellWindowNeedsMainWebView = shell_layout.shellWindowNeedsMainWebView;
37
+ const shellWindowUsesSourcelessCanvas = shell_layout.shellWindowUsesSourcelessCanvas;
38
+ const nowNanoseconds = runtime_clock.nowNanoseconds;
39
+ const canvasWidgetAccessibilityActionKindFromPlatform = widget_bridge.canvasWidgetAccessibilityActionKindFromPlatform;
40
+ const parseAutomationCommandName = automation_commands.parseAutomationCommandName;
41
+ const parseAutomationViewLabel = automation_commands.parseAutomationViewLabel;
42
+ const parseAutomationNativeCommand = automation_commands.parseAutomationNativeCommand;
43
+ const parseAutomationWidgetAction = automation_commands.parseAutomationWidgetAction;
44
+ const parseAutomationWidgetTarget = automation_commands.parseAutomationWidgetTarget;
45
+ const parseAutomationProvenanceTarget = automation_commands.parseAutomationProvenanceTarget;
46
+ const parseAutomationWidgetWheel = automation_commands.parseAutomationWidgetWheel;
47
+ const parseAutomationWidgetContextMenuItem = automation_commands.parseAutomationWidgetContextMenuItem;
48
+ const parseAutomationWidgetKey = automation_commands.parseAutomationWidgetKey;
49
+ const parseAutomationWidgetPinch = automation_commands.parseAutomationWidgetPinch;
50
+ const parseAutomationWidgetPointerDrag = automation_commands.parseAutomationWidgetPointerDrag;
51
+ const parseAutomationResizeCommand = automation_commands.parseAutomationResizeCommand;
52
+ const parseAutomationTrayTarget = automation_commands.parseAutomationTrayTarget;
53
+ const parseAutomationScreenshotCommand = automation_commands.parseAutomationScreenshotCommand;
54
+ const canvas = @import("canvas");
55
+
56
+ pub fn RuntimeFlow(comptime Runtime: type) type {
57
+ return struct {
58
+ const App = runtime_api.App(Runtime);
59
+ const Event = runtime_api.Event;
60
+ const CommandEvent = runtime_api.CommandEvent;
61
+ const FrameDiagnostics = runtime_api.FrameDiagnostics;
62
+ const AsyncBridgeResponseSlot = runtime_async_bridge.AsyncBridgeResponseSlot(Runtime);
63
+ const RunContext = struct {
64
+ runtime: *Runtime,
65
+ app: App,
66
+ host_events: HostEventPump,
67
+ };
68
+
69
+ fn WindowViewMethods() type {
70
+ return runtime_window_views.RuntimeWindowViews(Runtime);
71
+ }
72
+
73
+ fn SystemServiceMethods() type {
74
+ return runtime_system_services.RuntimeSystemServices(Runtime);
75
+ }
76
+
77
+ fn GpuSurfaceEventMethods() type {
78
+ return runtime_gpu_surface_events.RuntimeGpuSurfaceEvents(Runtime);
79
+ }
80
+
81
+ fn ScrollDriverMethods() type {
82
+ return runtime_canvas_widget_scroll_drivers.RuntimeCanvasWidgetScrollDrivers(Runtime);
83
+ }
84
+
85
+ fn ContextMenuMethods() type {
86
+ return runtime_canvas_widget_context_menu.RuntimeCanvasWidgetContextMenu(Runtime);
87
+ }
88
+
89
+ fn CanvasWidgetEventMethods() type {
90
+ return runtime_canvas_widget_events.RuntimeCanvasWidgetEvents(Runtime);
91
+ }
92
+
93
+ fn AutomationWidgetMethods() type {
94
+ return runtime_automation_widget_dispatch.RuntimeAutomationWidgetDispatch(Runtime);
95
+ }
96
+
97
+ pub fn run(self: *Runtime, app: App) anyerror!void {
98
+ var init_fields: [3]trace.Field = undefined;
99
+ init_fields[0] = trace.string("app", app.name);
100
+ init_fields[1] = trace.string("platform", self.options.platform.name);
101
+ var init_field_count: usize = 2;
102
+ if (self.options.log_path) |log_path| {
103
+ init_fields[init_field_count] = trace.string("log_path", log_path);
104
+ init_field_count += 1;
105
+ }
106
+ log(self, "runtime.init", "runtime initialized", init_fields[0..init_field_count]);
107
+ // Startup declaration admission runs before OS configuration and
108
+ // app_start installs the retained runtime policy callbacks.
109
+ if (app.command_policy) |policy| try command_policy.catalog(policy, self.options.commands) else try app_manifest.validateCommands(self.options.commands);
110
+ try self.options.platform.services.configureSecurityPolicy(self.options.security);
111
+ try self.options.platform.services.configureMenus(self.options.menus);
112
+ try self.options.platform.services.configureShortcuts(self.options.shortcuts);
113
+ // Automation liveness: the drain (`consumeAutomationCommand`,
114
+ // in `frame` below) runs at most once per frame_requested
115
+ // turn, and an idle app produces no frames — so a queued
116
+ // command must WAKE the loop the way user input does. The
117
+ // arrival watcher polls the dropbox slot on its own thread
118
+ // and asks the platform for one coalesced frame tick through
119
+ // its thread-safe `request_frame_fn` whenever a command is
120
+ // pending. Consumption itself stays on the frame boundary,
121
+ // so command order, one-command-per-frame, and session
122
+ // recording/replay (commands nest inside recorded
123
+ // frame_requested events) are unchanged; only the frame's
124
+ // ARRIVAL time moves. No automation server (any non-dev
125
+ // build) means no thread and no polls at all.
126
+ var command_watcher: automation.Watcher = undefined;
127
+ var command_watcher_running = false;
128
+ if (self.options.automation) |server| {
129
+ if (self.options.platform.services.request_frame_fn) |request_fn| {
130
+ command_watcher_running = command_watcher.start(server, .{
131
+ .context = self.options.platform.services.context,
132
+ .request_fn = request_fn,
133
+ });
134
+ if (!command_watcher_running) {
135
+ log(self, "automation.watcher_failed", "automation command watcher thread did not start; commands drain on the next unrelated frame", &.{});
136
+ }
137
+ } else {
138
+ // A platform without the cross-thread frame request
139
+ // keeps the old behavior (commands drain on whatever
140
+ // frame arrives next); say so once instead of wedging
141
+ // silently.
142
+ log(self, "automation.watcher_unsupported", "platform has no cross-thread frame request; automation commands drain on the next unrelated frame", &.{});
143
+ }
144
+ }
145
+ // Stopped (joined) before the platform loop's resources go
146
+ // away, so the watcher can never call into a dead host.
147
+ defer if (command_watcher_running) command_watcher.stop();
148
+
149
+ // Media-surface wake teardown: producers a slow app forgot
150
+ // to release may push (and try to wake this platform) at
151
+ // any later time from their own threads. Disarm their wake
152
+ // bindings before the caller's later-declared defers tear
153
+ // the host down — declared BEFORE the app-stop defer below
154
+ // so it runs AFTER the stop hook (LIFO), letting the hook
155
+ // join producer threads first. The same run-exit ordering
156
+ // that stops the automation arrival watcher.
157
+ defer self.disarmMediaSurfaceWakes();
158
+
159
+ // Teardown ordering contract: everything the app must do
160
+ // against the live platform — silencing an active audio
161
+ // player, disarming platform timers, joining effect workers
162
+ // that post through the platform's wake service — happens in
163
+ // the app's stop hook, and that hook is guaranteed to run
164
+ // before run() returns. The app's OWN deinit cannot serve
165
+ // this purpose: it is typically a `defer` in main that runs
166
+ // only after the runner's later-declared defers have already
167
+ // destroyed the platform host and freed the runtime, so any
168
+ // platform service call from there dereferences freed memory
169
+ // (the quit-while-audio-plays use-after-free). The platform's
170
+ // `.app_shutdown` event delivers the stop hook on the normal
171
+ // quit path; this defer delivers it when the loop exits any
172
+ // other way (an error unwind, a host that stops without a
173
+ // shutdown event) — exactly once either way, gated by
174
+ // `app_stop_delivered`.
175
+ defer if (!self.app_stop_delivered) {
176
+ self.app_stop_delivered = true;
177
+ app.stop(self) catch |err| log(self, "app.stop.failed", @errorName(err), &.{trace.string("app", app.name)});
178
+ };
179
+
180
+ var context: RunContext = .{ .runtime = self, .app = app, .host_events = .{ .allocator = self.owned_allocator } };
181
+ defer context.host_events.deinit();
182
+ try self.options.platform.run(handlePlatformEvent, &context);
183
+
184
+ log(self, "runtime.done", "runtime finished", &.{});
185
+ }
186
+
187
+ fn reservePrimaryStartupWindow(self: *Runtime) anyerror!void {
188
+ const app_info = self.options.platform.app_info;
189
+ if (app_info.startupWindowCount() == 0) return;
190
+ const window = app_info.resolvedStartupWindow(0);
191
+ if (WindowViewMethods().findWindowIndexById(self, window.id) != null) return;
192
+
193
+ const runtime_index = try WindowViewMethods().reserveWindow(self, window.id, window.label, window.resolvedTitle(app_info.app_name), null, true, .allow_source_less);
194
+ self.windows[runtime_index].activate_on_show = window.activate_on_show;
195
+ self.windows[runtime_index].info.focused = window.activate_on_show and window.show == .immediate;
196
+ self.windows[runtime_index].info.hidden = window.show == .hidden;
197
+ self.windows[runtime_index].main_focused = self.windows[runtime_index].info.focused;
198
+ self.windows[runtime_index].info.frame = window.default_frame;
199
+ self.windows[runtime_index].main_frame = geometry.RectF.init(0, 0, window.default_frame.width, window.default_frame.height);
200
+ self.next_window_id = @max(self.next_window_id, window.id + 1);
201
+ }
202
+
203
+ pub fn emitWindowEvent(self: *Runtime, window_id: platform.WindowId, name: []const u8, detail_json: []const u8) anyerror!void {
204
+ if (!json.isValidValue(detail_json)) return error.InvalidJsonEventDetail;
205
+ try self.options.platform.services.emitWindowEvent(window_id, name, detail_json);
206
+ }
207
+
208
+ pub fn respondToBridge(self: *Runtime, source: bridge.Source, response: []const u8) anyerror!void {
209
+ try completeBridgeResponse(self, source.window_id, source.webview_label, response);
210
+ }
211
+
212
+ pub fn dispatchPlatformEvent(self: *Runtime, app: App, event_value: platform.Event) anyerror!void {
213
+ // Session recording: stage the event on entry, commit it on
214
+ // exit — so effect results drained DURING dispatch precede
215
+ // the event record in the journal (replay feeds them before
216
+ // dispatching), and nested dispatches (automation commands
217
+ // inside frame_requested) commit innermost-first. One state
218
+ // fingerprint checkpoint follows each published frame.
219
+ if (self.options.session_recorder) |recorder| recorder.stageEvent(event_value);
220
+ defer if (self.options.session_recorder) |recorder| {
221
+ recorder.commitEvent();
222
+ if (recorder.wantsCheckpoint(self.frame_index)) {
223
+ recorder.recordCheckpoint(self.frame_index, self.sessionStateFingerprint());
224
+ }
225
+ // Seal on shutdown, here rather than only at run() exit:
226
+ // a host that terminates without unwinding the platform
227
+ // loop still leaves a whole journal behind.
228
+ if (event_value == .app_shutdown) recorder.finish();
229
+ };
230
+
231
+ if ((event_value != .frame_requested and event_value != .gpu_surface_frame) or self.invalidated) {
232
+ const event_fields = [_]trace.Field{trace.string("event", event_value.name())};
233
+ log(self, "platform.event", null, &event_fields);
234
+ }
235
+
236
+ switch (event_value) {
237
+ .app_start => {
238
+ self.shell_layout_policy = app.shell_layout_policy;
239
+ self.view_coordination_policy = app.view_coordination_policy;
240
+ self.window_lifecycle_policy = app.window_lifecycle_policy;
241
+ self.image_registry_policy = app.image_registry_policy;
242
+ self.font_registry_policy = app.font_registry_policy;
243
+ self.shell_coordination_policy = app.shell_coordination_policy;
244
+ self.shell_admission_policy = app.shell_admission_policy;
245
+ self.system_admission_policy = app.system_admission_policy;
246
+ self.bridge_descriptor_policy = app.bridge_descriptor_policy;
247
+ self.authorization_policy = app.authorization_policy;
248
+ self.builtin_coordination_policy = app.builtin_coordination_policy;
249
+ self.automation_command_policy = app.automation_command_policy;
250
+ self.automation_interaction_policy = app.automation_interaction_policy;
251
+ self.snapshot_policy = app.snapshot_policy;
252
+ self.frame_profile.policy = app.snapshot_policy;
253
+ self.command_policy = app.command_policy;
254
+ self.text_cache_policy = app.text_cache_policy;
255
+ self.render_cache_policy = app.render_cache_policy;
256
+ self.render_plan_policy = app.render_plan_policy;
257
+ self.render_override_policy = app.render_override_policy;
258
+ self.render_damage_policy = app.render_damage_policy;
259
+ // A startup failure must be loud and attributable.
260
+ // Without this record the error unwinds into the
261
+ // platform stop path and the only trace is a bare
262
+ // `app.stop` right after `start` — which reads like a
263
+ // clean exit while the main window sits blank.
264
+ errdefer |err| recordDispatchError(self, "app_start", err);
265
+ launch_timing.lap("app_start");
266
+ try reservePrimaryStartupWindow(self);
267
+ try app.start(self);
268
+ if (self.options.extensions) |registry| try registry.startAll(extensionContext(self));
269
+ try dispatchEvent(self, app, .{ .lifecycle = .start });
270
+ launch_timing.lap("app_started");
271
+ if (try app.scene()) |scene| {
272
+ try loadScene(self, app, scene);
273
+ } else {
274
+ try loadStartupWindows(self, app);
275
+ }
276
+ launch_timing.lap("scene_loaded");
277
+ self.invalidateFor(.startup, null);
278
+ log(self, "app.start", "app started", &.{trace.string("app", app.name)});
279
+ },
280
+ .app_activated => {
281
+ try WindowViewMethods().setAppActive(self, true);
282
+ try dispatchEvent(self, app, .{ .lifecycle = .activate });
283
+ emitAppLifecycleEvent(self, "app:activate") catch |err| log(self, "app.activate.emit_failed", @errorName(err), &.{});
284
+ },
285
+ .app_deactivated => {
286
+ // The app-active register flips FIRST — before the
287
+ // tooltip reset and before the app hears the
288
+ // lifecycle event — so a model that rebuilds FROM
289
+ // its deactivation callback adopts under a runtime
290
+ // that already knows the app is inactive: the
291
+ // adoption arm's reveal/arm paths are gated on this
292
+ // register and stay silent.
293
+ try WindowViewMethods().setAppActive(self, false);
294
+ // Deactivation drops every tooltip conversation in
295
+ // every window (see the seam's own rationale) BEFORE
296
+ // the app hears the lifecycle event, so a model that
297
+ // rebuilds on deactivate adopts against clean
298
+ // tooltip state instead of a stale shown slot.
299
+ try CanvasWidgetEventMethods().resetCanvasTooltipIntentForAppDeactivation(self);
300
+ try dispatchEvent(self, app, .{ .lifecycle = .deactivate });
301
+ emitAppLifecycleEvent(self, "app:deactivate") catch |err| log(self, "app.deactivate.emit_failed", @errorName(err), &.{});
302
+ },
303
+ .appearance_changed => |appearance| {
304
+ self.appearance = appearance;
305
+ // Appearance flips re-resolve theme typography (and a
306
+ // host may re-resolve its fonts with it): cached
307
+ // advance batches and retained wrap results must miss
308
+ // rather than serve metrics measured under the
309
+ // previous appearance.
310
+ canvas.bumpTextMeasureGeneration();
311
+ try dispatchEvent(self, app, .{ .appearance_changed = appearance });
312
+ },
313
+ .surface_resized => |surface_value| {
314
+ self.surface = surface_value;
315
+ if (WindowViewMethods().findWindowIndexById(self, surface_value.id)) |index| {
316
+ self.windows[index].info.frame.width = surface_value.size.width;
317
+ self.windows[index].info.frame.height = surface_value.size.height;
318
+ self.windows[index].info.scale_factor = surface_value.scale_factor;
319
+ }
320
+ WindowViewMethods().relayoutShellViews(self, surface_value.id) catch |err| log(self, "shell.relayout_failed", @errorName(err), &.{trace.uint("window_id", surface_value.id)});
321
+ var detail_buffer: [512]u8 = undefined;
322
+ var detail_writer = std.Io.Writer.fixed(&detail_buffer);
323
+ try detail_writer.print("{{\"width\":{d},\"height\":{d},\"scale\":{d},\"safeAreaInsets\":{{\"top\":{d},\"right\":{d},\"bottom\":{d},\"left\":{d}}},\"keyboardInsets\":{{\"top\":{d},\"right\":{d},\"bottom\":{d},\"left\":{d}}}}}", .{
324
+ surface_value.size.width,
325
+ surface_value.size.height,
326
+ surface_value.scale_factor,
327
+ surface_value.safe_area_insets.top,
328
+ surface_value.safe_area_insets.right,
329
+ surface_value.safe_area_insets.bottom,
330
+ surface_value.safe_area_insets.left,
331
+ surface_value.keyboard_insets.top,
332
+ surface_value.keyboard_insets.right,
333
+ surface_value.keyboard_insets.bottom,
334
+ surface_value.keyboard_insets.left,
335
+ });
336
+ emitWindowEvent(self, surface_value.id, "resize", detail_writer.buffered()) catch |err| log(self, "window.resize.emit_failed", @errorName(err), &.{});
337
+ self.invalidateFor(.surface_resize, geometry.RectF.fromSize(surface_value.size));
338
+ const fields = [_]trace.Field{
339
+ trace.float("width", surface_value.size.width),
340
+ trace.float("height", surface_value.size.height),
341
+ trace.float("scale", surface_value.scale_factor),
342
+ };
343
+ log(self, "surface.resize", "surface updated", &fields);
344
+ },
345
+ .window_frame_changed => |state| {
346
+ // A user (or host) close arrives as open=false on a
347
+ // window the runtime knew as open; a close the app
348
+ // itself made through `closeWindow` already flipped
349
+ // the flag, so the echo never re-fires. Capture the
350
+ // transition BEFORE the update.
351
+ const was_open = if (WindowViewMethods().findWindowIndexById(self, state.id)) |index| self.windows[index].info.open else false;
352
+ WindowViewMethods().updateWindowState(self, state) catch |err| log(self, "window.state.update_failed", @errorName(err), &.{trace.string("label", state.label)});
353
+ WindowViewMethods().relayoutShellViews(self, state.id) catch |err| log(self, "shell.relayout_failed", @errorName(err), &.{trace.uint("window_id", state.id)});
354
+ if (self.options.window_state_store) |store| {
355
+ store.saveWindow(WindowViewMethods().runtimeWindowStateForPersistence(self, state)) catch |err| log(self, "window.state.save_failed", @errorName(err), &.{trace.string("label", state.label)});
356
+ }
357
+ log(self, "window.frame", "window frame updated", &.{
358
+ trace.string("label", state.label),
359
+ trace.float("x", state.frame.x),
360
+ trace.float("y", state.frame.y),
361
+ trace.float("width", state.frame.width),
362
+ trace.float("height", state.frame.height),
363
+ });
364
+ if (was_open and !state.open) {
365
+ // The model owns the consequence (the dismissal
366
+ // precedent): the app maps this to a Msg and its
367
+ // next declared window set is truth. The label
368
+ // comes from runtime storage, which outlives the
369
+ // event's transient slices.
370
+ const label = if (WindowViewMethods().findWindowIndexById(self, state.id)) |index| self.windows[index].info.label else state.label;
371
+ try dispatchEvent(self, app, .{ .window_closed = .{ .window_id = state.id, .label = label } });
372
+ }
373
+ },
374
+ .window_focused => |window_id| {
375
+ // setFocusedIndex is the window-key seam: the
376
+ // window LOSING key here also drops its views'
377
+ // tooltip conversations there.
378
+ if (WindowViewMethods().findWindowIndexById(self, window_id)) |index| try WindowViewMethods().setFocusedIndex(self, index);
379
+ self.invalidated = true;
380
+ },
381
+ .view_focused => |focus| {
382
+ // Native children (notably embedded webviews) own
383
+ // their pointer stream, so the host reports the
384
+ // focus edge explicitly. Keep the canvas widget id
385
+ // as per-view focus memory while its view blurs:
386
+ // inactive terminal/text carets paint honestly, and
387
+ // clicking back into the canvas resumes its normal
388
+ // pointer-driven widget focus path.
389
+ try WindowViewMethods().setFocusedView(self, focus.window_id, focus.label);
390
+ self.invalidated = true;
391
+ },
392
+ .frame_requested => try frame(self, app),
393
+ .bridge_message => |message| try handleBridgeMessage(self, app, message),
394
+ .tray_action => |action| {
395
+ log(self, "tray.action", "tray item selected", &.{ trace.uint("status_item_id", action.status_item_id), trace.uint("item_id", action.item_id) });
396
+ try dispatchCommand(self, app, .{
397
+ .name = SystemServiceMethods().statusItemCommandNameForItem(self, action.status_item_id, action.item_id),
398
+ .source = .tray,
399
+ .status_item_id = action.status_item_id,
400
+ .tray_item_id = action.item_id,
401
+ });
402
+ },
403
+ .shortcut => |shortcut| {
404
+ try dispatchCommand(self, app, .{
405
+ .name = shortcut.id,
406
+ .source = .shortcut,
407
+ .window_id = shortcut.window_id,
408
+ });
409
+ try dispatchEvent(self, app, .{ .shortcut = shortcut });
410
+ emitShortcutEvent(self, shortcut) catch |err| log(self, "shortcut.emit_failed", @errorName(err), &.{trace.string("id", shortcut.id)});
411
+ self.invalidateFor(.command, null);
412
+ },
413
+ .native_command => |command| {
414
+ try dispatchCommand(self, app, .{
415
+ .name = command.name,
416
+ .source = WindowViewMethods().commandSourceForNativeView(self, command.window_id, command.view_label),
417
+ .window_id = command.window_id,
418
+ .view_label = command.view_label,
419
+ });
420
+ },
421
+ // The interactive-surface family below degrades on error
422
+ // instead of propagating: an error that escapes
423
+ // `dispatchPlatformEvent` reaches the platform callback,
424
+ // latches its failure flag, and exits the whole app — so a
425
+ // runtime-side capacity or render fault on a keystroke,
426
+ // click, scroll, resize, or frame tick must land in the
427
+ // dispatch-error ring (loud, queryable, traced at `.err`)
428
+ // while the app keeps running. The failing interaction is
429
+ // refused; the next one starts clean. The TestHarness's
430
+ // `.propagate` policy still returns the error so tests
431
+ // fail loud instead of leaving silent stale frames.
432
+ .gpu_surface_frame => |frame_event| GpuSurfaceEventMethods().dispatchGpuSurfaceFrame(self, app, frame_event) catch |err| {
433
+ recordDispatchError(self, "gpu_surface_frame", err);
434
+ if (self.dispatch_error_policy == .propagate) return err;
435
+ },
436
+ .gpu_surface_resized => |resize_event| {
437
+ GpuSurfaceEventMethods().dispatchGpuSurfaceResized(self, app, resize_event) catch |err| {
438
+ recordDispatchError(self, "gpu_surface_resized", err);
439
+ if (self.dispatch_error_policy == .propagate) return err;
440
+ };
441
+ log(self, "gpu_surface.resize", "gpu surface resized", &.{
442
+ trace.string("label", resize_event.label),
443
+ trace.float("width", resize_event.frame.width),
444
+ trace.float("height", resize_event.frame.height),
445
+ trace.float("scale", resize_event.scale_factor),
446
+ });
447
+ },
448
+ .gpu_surface_input => |input_event| GpuSurfaceEventMethods().dispatchGpuSurfaceInput(self, app, input_event) catch |err| {
449
+ recordDispatchError(self, "gpu_surface_input", err);
450
+ if (self.dispatch_error_policy == .propagate) return err;
451
+ },
452
+ .gpu_surface_scroll_driver => |driver_event| ScrollDriverMethods().dispatchGpuSurfaceScrollDriver(self, app, driver_event) catch |err| {
453
+ recordDispatchError(self, "gpu_surface_scroll_driver", err);
454
+ if (self.dispatch_error_policy == .propagate) return err;
455
+ },
456
+ .context_menu_action => |action_event| ContextMenuMethods().dispatchContextMenuAction(self, app, action_event) catch |err| {
457
+ recordDispatchError(self, "context_menu_action", err);
458
+ if (self.dispatch_error_policy == .propagate) return err;
459
+ },
460
+ .widget_context_menu_action => |action_event| AutomationWidgetMethods().dispatchWidgetContextMenuItem(self, app, action_event) catch |err| {
461
+ recordDispatchError(self, "widget_context_menu_action", err);
462
+ if (self.dispatch_error_policy == .propagate) return err;
463
+ },
464
+ .widget_accessibility_action => |action_event| {
465
+ _ = self.dispatchCanvasWidgetAccessibilityAction(app, action_event.window_id, action_event.label, .{
466
+ .id = action_event.id,
467
+ .action = canvasWidgetAccessibilityActionKindFromPlatform(action_event.action),
468
+ .text = action_event.text,
469
+ .selection = if (action_event.selection) |selection| .{ .anchor = selection.start, .focus = selection.end } else null,
470
+ }) catch |err| {
471
+ recordDispatchError(self, "widget_accessibility_action", err);
472
+ if (self.dispatch_error_policy == .propagate) return err;
473
+ };
474
+ },
475
+ .menu_command => |command| {
476
+ try dispatchCommand(self, app, .{
477
+ .name = command.name,
478
+ .source = .menu,
479
+ .window_id = command.window_id,
480
+ });
481
+ },
482
+ .tray_command => |command| {
483
+ try dispatchCommand(self, app, .{
484
+ .name = command.name,
485
+ .source = .tray,
486
+ .window_id = command.window_id,
487
+ .status_item_id = command.status_item_id,
488
+ });
489
+ },
490
+ .notification_command => |command| {
491
+ try dispatchCommand(self, app, .{
492
+ .name = command.name,
493
+ .source = .notification,
494
+ .window_id = command.window_id,
495
+ });
496
+ },
497
+ .timer => |timer_event| {
498
+ try dispatchEvent(self, app, .{ .timer = timer_event });
499
+ },
500
+ .audio => |audio_event| {
501
+ try dispatchEvent(self, app, .{ .audio = audio_event });
502
+ },
503
+ .video => |video_event| {
504
+ try dispatchEvent(self, app, .{ .video = video_event });
505
+ },
506
+ .wake => {
507
+ try dispatchEvent(self, app, .effects_wake);
508
+ },
509
+ .files_dropped => |drop| {
510
+ const widget_drop_event = self.routeCanvasWidgetFileDrop(drop, &self.widget_event_route_entries) catch |err| switch (err) {
511
+ error.WindowNotFound,
512
+ error.ViewNotFound,
513
+ error.InvalidViewOptions,
514
+ => null,
515
+ else => return err,
516
+ };
517
+ if (widget_drop_event) |drop_event| {
518
+ try dispatchEvent(self, app, .{ .canvas_widget_file_drop = drop_event });
519
+ }
520
+ try dispatchEvent(self, app, .{ .files_dropped = drop });
521
+ emitFileDropEvent(self, drop) catch |err| log(self, "drop.files.emit_failed", @errorName(err), &.{trace.uint("window_id", drop.window_id)});
522
+ self.invalidateFor(.command, null);
523
+ },
524
+ .app_shutdown => {
525
+ try dispatchEvent(self, app, .{ .lifecycle = .stop });
526
+ if (self.options.extensions) |registry| try registry.stopAll(extensionContext(self));
527
+ // Marked delivered BEFORE the call: if the hook itself
528
+ // errors, the run loop's exit path must not invoke it a
529
+ // second time (the hook contract is exactly-once).
530
+ self.app_stop_delivered = true;
531
+ try app.stop(self);
532
+ log(self, "app.stop", "app stopped", &.{trace.string("app", app.name)});
533
+ },
534
+ }
535
+ }
536
+
537
+ pub fn dispatchEvent(self: *Runtime, app: App, event_value: Event) anyerror!void {
538
+ const event_fields = [_]trace.Field{trace.string("event", event_value.name())};
539
+ log(self, "runtime.event", null, &event_fields);
540
+ // A handler/update error degrades — recorded and observable,
541
+ // never fatal. Propagating it would reach the platform
542
+ // callback, set `failed`, and exit the whole app. The tag
543
+ // name (not `Event.name()`, which for commands aliases
544
+ // transient command-name storage) keeps ring records static.
545
+ // Under the TestHarness's `.propagate` policy the recorded
546
+ // error additionally returns, so capacity errors fail tests
547
+ // instead of leaving silent stale frames.
548
+ app.event(self, event_value) catch |err| {
549
+ recordDispatchError(self, @tagName(event_value), err);
550
+ if (self.dispatch_error_policy == .propagate) return err;
551
+ };
552
+
553
+ switch (event_value) {
554
+ .command => {
555
+ if (self.options.extensions) |registry| {
556
+ registry.dispatchCommand(extensionContext(self), .{ .name = event_value.command.name }) catch |err| {
557
+ recordDispatchError(self, "extension.command", err);
558
+ };
559
+ }
560
+ self.invalidateFor(.command, null);
561
+ },
562
+ .shortcut => {
563
+ self.invalidateFor(.command, null);
564
+ },
565
+ .appearance_changed => {
566
+ self.invalidateFor(.state, null);
567
+ },
568
+ .timer => {},
569
+ .effects_wake => {},
570
+ .audio => {},
571
+ .video => {},
572
+ .files_dropped => {},
573
+ .gpu_surface_frame => {},
574
+ .gpu_surface_resized => {},
575
+ .gpu_surface_input => {},
576
+ .canvas_widget_pointer => {},
577
+ .canvas_widget_keyboard => {},
578
+ .canvas_widget_scroll => {},
579
+ .canvas_widget_file_drop => {},
580
+ .canvas_widget_drag => {},
581
+ .canvas_widget_context_menu => {
582
+ self.invalidateFor(.command, null);
583
+ },
584
+ // The shown notice only arms UiApp's selection snapshot:
585
+ // no visual change (the popover is an OS surface).
586
+ .canvas_widget_context_menu_shown => {},
587
+ // The dismissal notice only disarms UiApp's snapshot and
588
+ // pin: no visual change either.
589
+ .canvas_widget_context_menu_dismissed => {},
590
+ .canvas_widget_context_menu_request => {
591
+ // The app loop answers by mounting the anchored
592
+ // fallback surface: a visual change.
593
+ self.invalidateFor(.command, null);
594
+ },
595
+ .canvas_widget_dismiss => {},
596
+ .canvas_widget_context_press => {},
597
+ .canvas_widget_resize => {},
598
+ .canvas_widget_change => {},
599
+ .window_closed => {
600
+ self.invalidateFor(.state, null);
601
+ },
602
+ .automation_provenance => {},
603
+ .lifecycle => {},
604
+ }
605
+ }
606
+
607
+ pub fn dispatchCommand(self: *Runtime, app: App, command: CommandEvent) anyerror!void {
608
+ const plan: command_policy.Dispatch = if (self.command_policy) |policy| command_policy.dispatch(policy, command.name) else native: {
609
+ try validateCommandName(command.name);
610
+ break :native if (std.mem.eql(u8, command.name, platform.update_check_command)) .updater else .app;
611
+ };
612
+ if (plan == .invalid) return error.InvalidCommand;
613
+ if (plan == .updater) {
614
+ self.options.platform.services.checkForUpdates(true) catch |err| switch (err) {
615
+ error.UnsupportedService => return dispatchEvent(self, app, .{ .command = command }),
616
+ else => return err,
617
+ };
618
+ return;
619
+ }
620
+ try dispatchEvent(self, app, .{ .command = command });
621
+ }
622
+
623
+ pub fn frame(self: *Runtime, app: App) anyerror!void {
624
+ const start_ns = nowNanoseconds();
625
+ // A media-surface producer's wake arrives as THIS event (the
626
+ // platform's cross-thread frame request): adopt staged
627
+ // frames here so an idle app's push reaches the runtime —
628
+ // adoption's invalidation then arms the prompt gpu-surface
629
+ // frame that composites it (`noteCanvasImagesChanged` ->
630
+ // `requestCanvasFrameForView`). Runs before the invalidation
631
+ // check below because adoption IS an invalidation source; a
632
+ // busy app pays one fenced flag check per idle channel, and
633
+ // the gpu-surface frame dispatch's own adoption call keeps
634
+ // pacing consumption for hosts whose frame events do not
635
+ // pass through here.
636
+ self.adoptMediaSurfaceFrames();
637
+ try consumeAutomationCommand(self, app);
638
+ if (!self.invalidated) return;
639
+
640
+ try publishAutomation(self);
641
+ self.frame_index += 1;
642
+ self.last_diagnostics = .{
643
+ .frame_index = self.frame_index,
644
+ .command_count = self.command_count,
645
+ .dirty_region_count = self.dirty_region_count,
646
+ .resource_upload_count = 0,
647
+ .duration_ns = @intCast(@max(0, nowNanoseconds() - start_ns)),
648
+ };
649
+ self.command_count = 0;
650
+ self.dirty_region_count = 0;
651
+ self.invalidated = false;
652
+ log(self, "runtime.frame", "frame published", &.{
653
+ trace.uint("frame", self.frame_index),
654
+ trace.uint("dirty_regions", self.last_diagnostics.dirty_region_count),
655
+ });
656
+ app.event(self, .{ .lifecycle = .frame }) catch |err| {
657
+ recordDispatchError(self, "lifecycle", err);
658
+ if (self.dispatch_error_policy == .propagate) return err;
659
+ };
660
+ }
661
+
662
+ fn AutomationSnapshotMethods() type {
663
+ return runtime_automation_snapshot.RuntimeAutomationSnapshot(Runtime);
664
+ }
665
+
666
+ pub fn automationSnapshot(self: *Runtime, title: []const u8) automation.snapshot.Input {
667
+ return AutomationSnapshotMethods().automationSnapshot(self, title);
668
+ }
669
+
670
+ pub fn dispatchAutomationCommand(self: *Runtime, app: App, line: []const u8) anyerror!void {
671
+ try dispatchAutomationProtocolCommand(self, app, try automation.protocol.Command.parse(line));
672
+ }
673
+
674
+ pub fn frameDiagnostics(self: *Runtime) FrameDiagnostics {
675
+ return AutomationSnapshotMethods().frameDiagnostics(self);
676
+ }
677
+
678
+ pub fn supports(self: *const Runtime, feature: platform.PlatformFeature) bool {
679
+ return self.options.platform.supports(feature);
680
+ }
681
+
682
+ fn handlePlatformEvent(context: *anyopaque, event_value: platform.Event) anyerror!void {
683
+ const run_context: *RunContext = @ptrCast(@alignCast(context));
684
+ try run_context.host_events.dispatch(context, dispatchHostEvent, event_value);
685
+ }
686
+
687
+ fn dispatchHostEvent(context: *anyopaque, event_value: platform.Event) anyerror!void {
688
+ const run_context: *RunContext = @ptrCast(@alignCast(context));
689
+ try run_context.runtime.dispatchPlatformEvent(run_context.app, event_value);
690
+ }
691
+
692
+ fn loadStartupWindows(self: *Runtime, app: App) anyerror!void {
693
+ // Scene-less startup always materializes the app's webview
694
+ // source into the main window; a native-only build cannot.
695
+ if (!self.options.web_layer) return error.WebViewLayerNotBuilt;
696
+ const source = try WindowViewMethods().copyLoadedSource(self, try app.webViewSource());
697
+ self.loaded_source = source;
698
+ const app_info = self.options.platform.app_info;
699
+ const count = app_info.startupWindowCount();
700
+ var index: usize = 0;
701
+ while (index < count) : (index += 1) {
702
+ const window = app_info.resolvedStartupWindow(index);
703
+ const runtime_index = if (WindowViewMethods().findWindowIndexById(self, window.id)) |runtime_index| blk: {
704
+ self.windows[runtime_index].source = try WindowViewMethods().copySource(self, runtime_index, source);
705
+ self.windows[runtime_index].source_policy = .require_source;
706
+ break :blk runtime_index;
707
+ } else blk: {
708
+ const runtime_index = try WindowViewMethods().reserveWindow(self, window.id, window.label, window.resolvedTitle(app_info.app_name), source, true, .require_source);
709
+ self.windows[runtime_index].info.frame = window.default_frame;
710
+ self.windows[runtime_index].main_frame = geometry.RectF.init(0, 0, window.default_frame.width, window.default_frame.height);
711
+ break :blk runtime_index;
712
+ };
713
+ self.windows[runtime_index].source_reloads_from_app = true;
714
+ self.windows[runtime_index].activate_on_show = window.activate_on_show;
715
+ self.windows[runtime_index].info.focused = index == 0 and window.activate_on_show and window.show == .immediate;
716
+ self.windows[runtime_index].main_focused = self.windows[runtime_index].info.focused;
717
+ if (index > 0) {
718
+ // The same `.hide` gate as the runtime create path
719
+ // (window_storage): secondary startup windows reach
720
+ // the platform through this direct create, so the
721
+ // policy check must ride here too or a declared
722
+ // `.hide` is silently accepted on hosts that cannot
723
+ // re-show a closed window. `.hide` needs a host that
724
+ // can keep a closed-by-the-user window alive and
725
+ // re-show it; refusing here is the loud teaching
726
+ // (GTK: no status item exists to bring the window
727
+ // back, declare .quit — the default — instead).
728
+ // NEVER a silent no-op that strands a hidden window.
729
+ // The main window (index 0) is created by the host
730
+ // itself, which refuses the declaration at its own
731
+ // init.
732
+ if (window.close_policy == .hide and !self.options.platform.supports(.window_hide_on_close)) {
733
+ return error.UnsupportedWindowClosePolicy;
734
+ }
735
+ const native_info = try self.options.platform.services.createWindow(window);
736
+ try WindowViewMethods().applyNativeInfo(self, runtime_index, native_info);
737
+ }
738
+ try self.options.platform.services.loadWindowWebView(window.id, self.windows[runtime_index].source.?);
739
+ try applyMainWebViewState(self, window.id);
740
+ self.next_window_id = @max(self.next_window_id, window.id + 1);
741
+ }
742
+ log(self, "webview.load", "loaded webview source", &.{
743
+ trace.string("kind", @tagName(source.kind)),
744
+ trace.uint("bytes", source.bytes.len),
745
+ });
746
+ }
747
+
748
+ fn loadScene(self: *Runtime, app: App, scene: app_manifest.ShellConfig) anyerror!void {
749
+ if (self.shell_admission_policy) |policy|
750
+ try @import("shell_admission_policy.zig").scene(policy, scene, &.{})
751
+ else
752
+ try app_manifest.validateShell(scene, &.{});
753
+ if (scene.windows.len == 0) {
754
+ log(self, "scene.load", "loaded empty app scene", &.{trace.string("app", app.name)});
755
+ return;
756
+ }
757
+
758
+ const uses_default_empty_source = appUsesDefaultEmptyWebViewSource(App, app);
759
+ const source = if (if (self.shell_coordination_policy) |policy|
760
+ @import("shell_coordination_policy.zig").scene(policy, scene.windows, uses_default_empty_source).decisions != 0
761
+ else
762
+ sceneNeedsMainWebView(scene) or !uses_default_empty_source)
763
+ try WindowViewMethods().copyLoadedSource(self, try app.webViewSource())
764
+ else
765
+ null;
766
+ if (source != null and !self.options.web_layer) return error.WebViewLayerNotBuilt;
767
+ self.loaded_source = source;
768
+
769
+ const startup_uses_source = if (self.shell_coordination_policy) |policy|
770
+ @import("shell_coordination_policy.zig").scene(policy, scene.windows[0..1], uses_default_empty_source).choices[0] & 4 != 0
771
+ else
772
+ sceneWindowUsesAppSource(scene.windows[0], uses_default_empty_source);
773
+ try loadStartupSceneWindow(
774
+ self,
775
+ scene.windows[0],
776
+ if (startup_uses_source) source else null,
777
+ if (startup_uses_source) .allow_source_less else .never_source,
778
+ );
779
+ for (scene.windows[1..]) |window| {
780
+ if (if (self.shell_coordination_policy) |policy|
781
+ @import("shell_coordination_policy.zig").scene(policy, &.{window}, uses_default_empty_source).choices[0] & 4 != 0
782
+ else
783
+ sceneWindowUsesAppSource(window, uses_default_empty_source))
784
+ {
785
+ _ = try WindowViewMethods().createShellWindowWithSourceMode(self, window, source, source != null);
786
+ } else {
787
+ _ = try WindowViewMethods().createSourcelessShellWindow(self, window);
788
+ }
789
+ }
790
+
791
+ log(self, "scene.load", "loaded app scene", &.{
792
+ trace.string("app", app.name),
793
+ trace.uint("windows", scene.windows.len),
794
+ });
795
+ }
796
+
797
+ fn loadStartupSceneWindow(self: *Runtime, shell_window: app_manifest.ShellWindow, source: ?platform.WebViewSource, source_policy: runtime_state.WindowSourcePolicy) anyerror!void {
798
+ const app_info = self.options.platform.app_info;
799
+ const startup_window = app_info.resolvedStartupWindow(0);
800
+ const window_id = startup_window.id;
801
+ const manifest_frame = geometry.RectF.init(
802
+ shell_window.x orelse 0,
803
+ shell_window.y orelse 0,
804
+ shell_window.width,
805
+ shell_window.height,
806
+ );
807
+ const startup_frame = WindowViewMethods().startupWindowFrame(startup_window.default_frame, manifest_frame);
808
+
809
+ const runtime_index = if (WindowViewMethods().findWindowIndexById(self, window_id)) |index| index else try WindowViewMethods().reserveWindow(
810
+ self,
811
+ window_id,
812
+ shell_window.label,
813
+ shell_window.title orelse app_info.resolvedWindowTitle(),
814
+ null,
815
+ true,
816
+ source_policy,
817
+ );
818
+ if (WindowViewMethods().findWindowIndexByLabel(self, shell_window.label)) |label_index| {
819
+ if (label_index != runtime_index) return error.DuplicateWindowLabel;
820
+ }
821
+
822
+ self.windows[runtime_index].info.label = try copyInto(&self.windows[runtime_index].label_storage, shell_window.label);
823
+ self.windows[runtime_index].info.title = try copyInto(&self.windows[runtime_index].title_storage, shell_window.title orelse app_info.resolvedWindowTitle());
824
+ self.windows[runtime_index].info.frame = startup_frame;
825
+ self.windows[runtime_index].source = if (source) |source_value| try WindowViewMethods().copySource(self, runtime_index, source_value) else null;
826
+ self.windows[runtime_index].source_reloads_from_app = source != null;
827
+ self.windows[runtime_index].source_policy = source_policy;
828
+ // The host created this startup window from AppInfo before
829
+ // the scene loaded. Overlay presentation is immutable host
830
+ // state, so runtime bookkeeping must retain that same source
831
+ // of truth even when the scene descriptor differs.
832
+ self.windows[runtime_index].activate_on_show = startup_window.activate_on_show;
833
+ self.windows[runtime_index].info.focused = startup_window.activate_on_show and startup_window.show == .immediate;
834
+ self.windows[runtime_index].main_focused = self.windows[runtime_index].info.focused;
835
+ if (!self.windows[runtime_index].main_frame_set) {
836
+ self.windows[runtime_index].main_frame = geometry.RectF.init(0, 0, startup_frame.width, startup_frame.height);
837
+ }
838
+ self.next_window_id = @max(self.next_window_id, window_id + 1);
839
+
840
+ if (self.windows[runtime_index].source) |window_source| {
841
+ try self.options.platform.services.loadWindowWebView(window_id, window_source);
842
+ try applyMainWebViewState(self, window_id);
843
+ }
844
+ try WindowViewMethods().createShellViews(self, window_id, shell_window.views, WindowViewMethods().shellBoundsForWindow(self, window_id));
845
+ }
846
+
847
+ fn applyMainWebViewState(self: *Runtime, window_id: platform.WindowId) anyerror!void {
848
+ const window_index = WindowViewMethods().findWindowIndexById(self, window_id) orelse return error.WindowNotFound;
849
+ const window = self.windows[window_index];
850
+ if (window.main_frame_set) {
851
+ try self.options.platform.services.setWebViewFrame(window_id, "main", window.main_frame);
852
+ }
853
+ if (window.main_layer != 0) {
854
+ try self.options.platform.services.setWebViewLayer(window_id, "main", window.main_layer);
855
+ }
856
+ if (window.main_zoom != 1.0) {
857
+ try self.options.platform.services.setWebViewZoom(window_id, "main", window.main_zoom);
858
+ }
859
+ }
860
+
861
+ fn loadWebView(self: *Runtime, app: App) anyerror!void {
862
+ if (!self.options.web_layer) return error.WebViewLayerNotBuilt;
863
+ const source = try WindowViewMethods().copyLoadedSource(self, try app.webViewSource());
864
+ self.loaded_source = source;
865
+ try self.options.platform.services.loadWindowWebView(1, source);
866
+ }
867
+
868
+ pub fn reloadWindows(self: *Runtime, app: App) anyerror!void {
869
+ // Reload re-materializes webview sources; native-only builds
870
+ // have none to reload.
871
+ if (!self.options.web_layer) return error.WebViewLayerNotBuilt;
872
+ const source = try WindowViewMethods().copyLoadedSource(self, try app.webViewSource());
873
+ self.loaded_source = source;
874
+ if (self.window_count == 0) {
875
+ try self.options.platform.services.loadWindowWebView(1, source);
876
+ return;
877
+ }
878
+ for (self.windows[0..self.window_count], 0..) |*window, index| {
879
+ if (window.source_policy == .never_source) continue;
880
+ if (window.source == null or window.source_reloads_from_app) {
881
+ window.source = try WindowViewMethods().copySource(self, index, source);
882
+ }
883
+ const window_source = window.source orelse source;
884
+ try self.options.platform.services.loadWindowWebView(window.info.id, window_source);
885
+ }
886
+ }
887
+
888
+ fn handleBridgeMessage(self: *Runtime, app: App, message: platform.BridgeMessage) anyerror!void {
889
+ self.command_count += 1;
890
+ if (try handleBuiltinBridgeMessage(self, app, message)) return;
891
+ var dispatcher = self.options.bridge orelse bridge.Dispatcher{};
892
+ if (self.options.security.permissions.len > 0) dispatcher.policy.permissions = self.options.security.permissions;
893
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
894
+ if (try handleAsyncBridgeMessage(self, dispatcher, message)) {
895
+ self.invalidateFor(.command, null);
896
+ return;
897
+ }
898
+ const response = authorization.dispatch(self.authorization_policy, dispatcher, message.bytes, .{ .origin = message.origin, .window_id = message.window_id, .webview_label = message.webview_label }, &response_buffer);
899
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
900
+ self.invalidateFor(.command, null);
901
+ log(self, "bridge.dispatch", "bridge request handled", &.{
902
+ trace.uint("request_bytes", message.bytes.len),
903
+ trace.uint("response_bytes", response.len),
904
+ });
905
+ }
906
+
907
+ fn handleAsyncBridgeMessage(self: *Runtime, dispatcher: bridge.Dispatcher, message: platform.BridgeMessage) anyerror!bool {
908
+ const request = bridge.parseRequest(message.bytes) catch return false;
909
+ const handler = dispatcher.async_registry.find(request.command) orelse return false;
910
+ if (!authorization.bridgeAllows(self.authorization_policy, dispatcher.policy, request.command, message.origin)) {
911
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
912
+ const response = bridge.writeErrorResponse(&response_buffer, request.id, .permission_denied, "Bridge command is not permitted");
913
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
914
+ return true;
915
+ }
916
+ const source_slot = reserveAsyncBridgeResponse(self, .{
917
+ .origin = message.origin,
918
+ .window_id = message.window_id,
919
+ .webview_label = message.webview_label,
920
+ }) catch |err| {
921
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
922
+ const response = bridge.writeErrorResponse(&response_buffer, request.id, .internal_error, @errorName(err));
923
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
924
+ return true;
925
+ };
926
+ errdefer source_slot.release();
927
+ try handler.invoke_fn(handler.context, .{
928
+ .request = request,
929
+ .source = source_slot.source,
930
+ }, .{
931
+ .context = source_slot,
932
+ .source = source_slot.source,
933
+ .respond_fn = asyncBridgeRespond,
934
+ });
935
+ return true;
936
+ }
937
+
938
+ fn asyncBridgeRespond(context: *anyopaque, source: bridge.Source, response: []const u8) anyerror!void {
939
+ _ = source;
940
+ const slot: *AsyncBridgeResponseSlot = @ptrCast(@alignCast(context));
941
+ try slot.respond(response);
942
+ }
943
+
944
+ fn reserveAsyncBridgeResponse(self: *Runtime, source: bridge.Source) !*AsyncBridgeResponseSlot {
945
+ for (&self.async_bridge_responses) |*slot| {
946
+ if (slot.in_use) continue;
947
+ try slot.init(self, source);
948
+ return slot;
949
+ }
950
+ return error.AsyncBridgeResponseLimitReached;
951
+ }
952
+
953
+ fn publishAutomation(self: *Runtime) anyerror!void {
954
+ const server = self.options.automation orelse return;
955
+ try server.publish(automationSnapshot(self, server.title));
956
+ }
957
+
958
+ fn consumeAutomationCommand(self: *Runtime, app: App) anyerror!void {
959
+ const server = self.options.automation orelse return;
960
+ var buffer: [automation.protocol.max_command_bytes]u8 = undefined;
961
+ // Automation command errors ALWAYS degrade, regardless of
962
+ // `dispatch_error_policy`: a stale widget target or a
963
+ // malformed command is driver misuse, not an app fault —
964
+ // propagating would escape the frame_requested platform
965
+ // callback and kill the whole app under test, and the
966
+ // TestHarness's `.propagate` policy is for app errors. The
967
+ // record invalidates state, so the next published snapshot
968
+ // carries the error where the driver can see it.
969
+ const command = (server.takeCommand(&buffer) catch |err| {
970
+ recordDispatchError(self, "automation.command", err);
971
+ return;
972
+ }) orelse return;
973
+ dispatchAutomationProtocolCommand(self, app, command) catch |err| {
974
+ recordDispatchErrorDetail(self, automationCommandEventName(command.action), err, command.value);
975
+ };
976
+ }
977
+
978
+ /// Stable static event names for degraded automation command
979
+ /// errors — one per widget action, a generic fallback for
980
+ /// the rest (parse errors included).
981
+ fn automationCommandEventName(action: automation.protocol.Action) []const u8 {
982
+ return switch (action) {
983
+ .widget_click => "automation.widget_click",
984
+ .widget_hold => "automation.widget_hold",
985
+ .widget_context_press => "automation.widget_context_press",
986
+ .widget_context_menu => "automation.widget_context_menu",
987
+ .widget_action => "automation.widget_action",
988
+ .widget_drag => "automation.widget_drag",
989
+ .widget_wheel => "automation.widget_wheel",
990
+ .widget_key => "automation.widget_key",
991
+ .widget_pinch => "automation.widget_pinch",
992
+ .tray_action => "automation.tray_action",
993
+ .provenance => "automation.provenance",
994
+ else => "automation.command",
995
+ };
996
+ }
997
+
998
+ fn dispatchAutomationProtocolCommand(self: *Runtime, app: App, command: automation.protocol.Command) anyerror!void {
999
+ switch (command.action) {
1000
+ .reload => {
1001
+ self.command_count += 1;
1002
+ try reloadWindows(self, app);
1003
+ self.invalidateFor(.command, null);
1004
+ },
1005
+ .bridge => {
1006
+ try handleBridgeMessage(self, app, .{ .bytes = command.value, .origin = "zero://inline", .window_id = 1, .webview_label = "main" });
1007
+ },
1008
+ .resize => {
1009
+ const parsed = try parseAutomationResizeCommand(self.automation_command_policy, command.value);
1010
+ try dispatchPlatformEvent(self, app, .{ .surface_resized = .{
1011
+ .id = 1,
1012
+ .size = geometry.SizeF.init(parsed.width, parsed.height),
1013
+ .scale_factor = parsed.scale_factor,
1014
+ } });
1015
+ },
1016
+ .screenshot => {
1017
+ publishAutomationScreenshot(self, command.value) catch |err| {
1018
+ log(self, "automation.screenshot_failed", @errorName(err), &.{});
1019
+ };
1020
+ },
1021
+ .native_command => {
1022
+ const parsed = try parseAutomationNativeCommand(self.automation_command_policy, command.value);
1023
+ try dispatchPlatformEvent(self, app, .{ .native_command = .{
1024
+ .name = parsed.name,
1025
+ .window_id = 1,
1026
+ .view_label = parsed.view_label,
1027
+ } });
1028
+ },
1029
+ .widget_action => {
1030
+ try AutomationWidgetMethods().dispatchAutomationWidgetAction(self, app, try parseAutomationWidgetAction(self.automation_command_policy, command.value));
1031
+ },
1032
+ .widget_click => {
1033
+ try AutomationWidgetMethods().dispatchAutomationWidgetClick(self, app, try parseAutomationWidgetTarget(self.automation_command_policy, command.value));
1034
+ },
1035
+ .widget_hold => {
1036
+ try AutomationWidgetMethods().dispatchAutomationWidgetHold(self, app, try parseAutomationWidgetTarget(self.automation_command_policy, command.value));
1037
+ },
1038
+ .widget_context_press => {
1039
+ try AutomationWidgetMethods().dispatchAutomationWidgetContextPress(self, app, try parseAutomationWidgetTarget(self.automation_command_policy, command.value));
1040
+ },
1041
+ .widget_context_menu => {
1042
+ try AutomationWidgetMethods().dispatchAutomationWidgetContextMenuItem(self, app, try parseAutomationWidgetContextMenuItem(self.automation_command_policy, command.value));
1043
+ },
1044
+ .widget_drag => {
1045
+ try AutomationWidgetMethods().dispatchAutomationWidgetPointerDrag(self, app, try parseAutomationWidgetPointerDrag(self.automation_command_policy, command.value));
1046
+ },
1047
+ .widget_wheel => {
1048
+ try AutomationWidgetMethods().dispatchAutomationWidgetWheel(self, app, try parseAutomationWidgetWheel(self.automation_command_policy, command.value));
1049
+ },
1050
+ .widget_key => {
1051
+ try AutomationWidgetMethods().dispatchAutomationWidgetKeyInput(self, app, try parseAutomationWidgetKey(self.automation_command_policy, command.value));
1052
+ },
1053
+ .widget_pinch => {
1054
+ try AutomationWidgetMethods().dispatchAutomationWidgetPinch(self, app, try parseAutomationWidgetPinch(self.automation_command_policy, command.value));
1055
+ },
1056
+ .menu_command => {
1057
+ try dispatchPlatformEvent(self, app, .{ .menu_command = .{
1058
+ .name = try parseAutomationCommandName(self.automation_command_policy, command.value),
1059
+ .window_id = 1,
1060
+ } });
1061
+ },
1062
+ .shortcut => {
1063
+ try dispatchPlatformEvent(self, app, .{ .shortcut = .{
1064
+ .id = try parseAutomationCommandName(self.automation_command_policy, command.value),
1065
+ .key = "",
1066
+ .window_id = 1,
1067
+ } });
1068
+ },
1069
+ .tray_action => {
1070
+ // Drive a status-item dropdown row through the
1071
+ // SAME platform event a real NSStatusItem menu click
1072
+ // emits, so command resolution, `.tray` source, and
1073
+ // UiApp's window fallback are all the real path. A
1074
+ // stale or unknown item id is loud driver misuse,
1075
+ // like widget-click on an unmounted widget.
1076
+ const target = try parseAutomationTrayTarget(self.automation_command_policy, command.value);
1077
+ if (!SystemServiceMethods().statusItemMenuItemActionable(self, target.status_item_id, target.item_id)) return error.InvalidCommand;
1078
+ try dispatchPlatformEvent(self, app, .{ .tray_action = .{
1079
+ .status_item_id = target.status_item_id,
1080
+ .item_id = target.item_id,
1081
+ } });
1082
+ },
1083
+ .focus_view => {
1084
+ try WindowViewMethods().focusView(self, 1, try parseAutomationViewLabel(self.automation_command_policy, command.value));
1085
+ },
1086
+ .focus_next_view => {
1087
+ _ = try WindowViewMethods().focusNextView(self, 1);
1088
+ },
1089
+ .focus_previous_view => {
1090
+ _ = try WindowViewMethods().focusPreviousView(self, 1);
1091
+ },
1092
+ .profile => {
1093
+ // Toggle per-stage frame timing. Turning it on
1094
+ // starts a fresh window (stale samples from an
1095
+ // earlier session would skew the percentiles);
1096
+ // turning it off stops recording and drops the
1097
+ // snapshot's `frame_profile` line.
1098
+ self.command_count += 1;
1099
+ const enable = std.mem.eql(u8, command.value, "on");
1100
+ if (!enable and !std.mem.eql(u8, command.value, "off")) return error.InvalidCommand;
1101
+ if (enable and !self.frame_profile.enabled) {
1102
+ self.frame_profile.reset();
1103
+ for (self.views[0..self.view_count]) |*view| {
1104
+ view.gpu_frame_profile_timestamp_ns = 0;
1105
+ }
1106
+ }
1107
+ self.frame_profile.enabled = enable;
1108
+ self.invalidateFor(.command, null);
1109
+ },
1110
+ .provenance => {
1111
+ try AutomationWidgetMethods().dispatchAutomationProvenance(self, app, try parseAutomationProvenanceTarget(self.automation_command_policy, command.value));
1112
+ },
1113
+ .wait => {},
1114
+ }
1115
+ }
1116
+
1117
+ /// Render the named gpu_surface view's current canvas frame through
1118
+ /// the deterministic reference renderer and publish it as a PNG
1119
+ /// (`screenshot-<label>.png`) in the automation directory. The
1120
+ /// screenshot renders at scale 1 unless the command carries an
1121
+ /// explicit scale, so an unchanged scene produces byte-identical
1122
+ /// artifacts across captures.
1123
+ pub fn publishAutomationScreenshot(self: *Runtime, value: []const u8) anyerror!void {
1124
+ const server = self.options.automation orelse return;
1125
+ const parsed = try parseAutomationScreenshotCommand(self.automation_command_policy, value);
1126
+ // Screenshots address a gpu_surface view by label across ALL
1127
+ // open windows, like the widget verbs — a secondary window's
1128
+ // canvas captures the same way the main one does.
1129
+ const view_index = try AutomationWidgetMethods().automationGpuSurfaceViewIndexByLabel(self, parsed.view_label);
1130
+ const window_id = self.views[view_index].window_id;
1131
+ const allocator = std.heap.page_allocator;
1132
+ const pixel_size = try self.canvasScreenshotPixelSize(window_id, parsed.view_label, parsed.scale);
1133
+ const pixels = try allocator.alloc(u8, pixel_size.byte_len);
1134
+ defer allocator.free(pixels);
1135
+ const scratch = try allocator.alloc(u8, pixel_size.byte_len);
1136
+ defer allocator.free(scratch);
1137
+ const screenshot = try self.renderCanvasScreenshot(window_id, parsed.view_label, parsed.scale, pixels, scratch);
1138
+ var writer = try std.Io.Writer.Allocating.initCapacity(
1139
+ allocator,
1140
+ try canvas.png.encodedRgba8ByteLen(screenshot.width, screenshot.height),
1141
+ );
1142
+ defer writer.deinit();
1143
+ try canvas.png.writeRgba8(&writer.writer, screenshot.width, screenshot.height, screenshot.rgba8);
1144
+ try server.publishScreenshot(parsed.view_label, writer.written());
1145
+ // A screenshot taken during a recorded session marks a pixel
1146
+ // checkpoint: replay re-renders the same view at the same
1147
+ // scale through the same deterministic reference renderer
1148
+ // and compares hashes.
1149
+ if (self.options.session_recorder) |recorder| {
1150
+ recorder.recordScreenshot(
1151
+ parsed.view_label,
1152
+ parsed.scale orelse 1,
1153
+ std.hash.Wyhash.hash(0, writer.written()),
1154
+ writer.written().len,
1155
+ );
1156
+ }
1157
+ log(self, "automation.screenshot", "screenshot published", &.{
1158
+ trace.string("view", parsed.view_label),
1159
+ trace.uint("width", screenshot.width),
1160
+ trace.uint("height", screenshot.height),
1161
+ trace.uint("bytes", writer.written().len),
1162
+ });
1163
+ }
1164
+
1165
+ const BuiltinBridgeMethods = runtime_builtin_bridge.RuntimeBuiltinBridge(Runtime);
1166
+ const allowsBuiltinBridgeCommand = BuiltinBridgeMethods.allowsBuiltinBridgeCommand;
1167
+ const dispatchCommandBridgeCommand = BuiltinBridgeMethods.dispatchCommandBridgeCommand;
1168
+ const dispatchPlatformBridgeCommand = BuiltinBridgeMethods.dispatchPlatformBridgeCommand;
1169
+ const dispatchWindowBridgeCommand = BuiltinBridgeMethods.dispatchWindowBridgeCommand;
1170
+ const invokeCommandFromJson = BuiltinBridgeMethods.invokeCommandFromJson;
1171
+ const writeCommandListJson = BuiltinBridgeMethods.writeCommandListJson;
1172
+ const dispatchViewBridgeCommand = BuiltinBridgeMethods.dispatchViewBridgeCommand;
1173
+ const dispatchWebViewBridgeCommand = BuiltinBridgeMethods.dispatchWebViewBridgeCommand;
1174
+ const dispatchDialogBridgeCommand = BuiltinBridgeMethods.dispatchDialogBridgeCommand;
1175
+ const dispatchOsBridgeCommand = BuiltinBridgeMethods.dispatchOsBridgeCommand;
1176
+ const dispatchCredentialBridgeCommand = BuiltinBridgeMethods.dispatchCredentialBridgeCommand;
1177
+ const dispatchClipboardBridgeCommand = BuiltinBridgeMethods.dispatchClipboardBridgeCommand;
1178
+ const createWindowFromJson = BuiltinBridgeMethods.createWindowFromJson;
1179
+ const createViewFromJson = BuiltinBridgeMethods.createViewFromJson;
1180
+ const updateViewFromJson = BuiltinBridgeMethods.updateViewFromJson;
1181
+ const setViewFrameFromJson = BuiltinBridgeMethods.setViewFrameFromJson;
1182
+ const setViewVisibleFromJson = BuiltinBridgeMethods.setViewVisibleFromJson;
1183
+ const focusViewFromJson = BuiltinBridgeMethods.focusViewFromJson;
1184
+ const focusNextViewFromJson = BuiltinBridgeMethods.focusNextViewFromJson;
1185
+ const focusPreviousViewFromJson = BuiltinBridgeMethods.focusPreviousViewFromJson;
1186
+ const closeViewFromJson = BuiltinBridgeMethods.closeViewFromJson;
1187
+ const writeViewListJson = BuiltinBridgeMethods.writeViewListJson;
1188
+ const createWebViewFromJson = BuiltinBridgeMethods.createWebViewFromJson;
1189
+ const setWebViewFrameFromJson = BuiltinBridgeMethods.setWebViewFrameFromJson;
1190
+ const navigateWebViewFromJson = BuiltinBridgeMethods.navigateWebViewFromJson;
1191
+ const setWebViewZoomFromJson = BuiltinBridgeMethods.setWebViewZoomFromJson;
1192
+ const setWebViewLayerFromJson = BuiltinBridgeMethods.setWebViewLayerFromJson;
1193
+ const closeWebViewFromJson = BuiltinBridgeMethods.closeWebViewFromJson;
1194
+ const focusWindowFromJson = BuiltinBridgeMethods.focusWindowFromJson;
1195
+ const closeWindowFromJson = BuiltinBridgeMethods.closeWindowFromJson;
1196
+ const resolveWindowSelector = BuiltinBridgeMethods.resolveWindowSelector;
1197
+ const writeWindowListJson = BuiltinBridgeMethods.writeWindowListJson;
1198
+
1199
+ fn handleCompiledBuiltinBridgeMessage(self: *Runtime, app: App, message: platform.BridgeMessage) anyerror!bool {
1200
+ const request = bridge.parseRequest(message.bytes) catch return false;
1201
+ const plan = builtin_coordination.route(self.builtin_coordination_policy.?, .none, request.command);
1202
+ if (plan.family() == .none) return false;
1203
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
1204
+ var result_buffer: [bridge.max_result_bytes]u8 = undefined;
1205
+ if (!allowsBuiltinBridgeCommand(self, request.command, message.origin, plan.permission())) {
1206
+ const response = bridge.writeErrorResponse(&response_buffer, request.id, .permission_denied, plan.deniedMessage());
1207
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
1208
+ self.invalidateFor(.command, null);
1209
+ return true;
1210
+ }
1211
+ const response = switch (plan.family()) {
1212
+ .none => unreachable,
1213
+ .command => dispatchCommandBridgeCommand(self, app, request, message.window_id, message.webview_label, &result_buffer, &response_buffer),
1214
+ .window => dispatchWindowBridgeCommand(self, request, &result_buffer, &response_buffer),
1215
+ .view => dispatchViewBridgeCommand(self, request, message.window_id, &result_buffer, &response_buffer),
1216
+ .webview => dispatchWebViewBridgeCommand(self, request, message.window_id, &result_buffer, &response_buffer),
1217
+ .platform => dispatchPlatformBridgeCommand(self, request, &result_buffer, &response_buffer),
1218
+ .dialog => dispatchDialogBridgeCommand(self, request, &result_buffer, &response_buffer),
1219
+ .os => dispatchOsBridgeCommand(self, request, message.origin, &result_buffer, &response_buffer),
1220
+ .clipboard => dispatchClipboardBridgeCommand(self, request, &result_buffer, &response_buffer),
1221
+ .credentials => dispatchCredentialBridgeCommand(self, request, &result_buffer, &response_buffer),
1222
+ };
1223
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
1224
+ self.invalidateFor(.command, null);
1225
+ return true;
1226
+ }
1227
+
1228
+ fn handleBuiltinBridgeMessage(self: *Runtime, app: App, message: platform.BridgeMessage) anyerror!bool {
1229
+ if (self.builtin_coordination_policy != null) return handleCompiledBuiltinBridgeMessage(self, app, message);
1230
+ const request = bridge.parseRequest(message.bytes) catch return false;
1231
+ const is_command = std.mem.startsWith(u8, request.command, "native-sdk.command.");
1232
+ const is_window = std.mem.startsWith(u8, request.command, "native-sdk.window.");
1233
+ const is_view = std.mem.startsWith(u8, request.command, "native-sdk.view.");
1234
+ const is_webview = std.mem.startsWith(u8, request.command, "native-sdk.webview.");
1235
+ const is_platform = std.mem.startsWith(u8, request.command, "native-sdk.platform.");
1236
+ const is_dialog = std.mem.startsWith(u8, request.command, "native-sdk.dialog.");
1237
+ const is_os = std.mem.startsWith(u8, request.command, "native-sdk.os.");
1238
+ const is_clipboard = std.mem.startsWith(u8, request.command, "native-sdk.clipboard.");
1239
+ const is_credentials = std.mem.startsWith(u8, request.command, "native-sdk.credentials.");
1240
+ if (!is_command and !is_window and !is_view and !is_webview and !is_platform and !is_dialog and !is_os and !is_clipboard and !is_credentials) return false;
1241
+
1242
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
1243
+ var result_buffer: [bridge.max_result_bytes]u8 = undefined;
1244
+ const js_permission: ?[]const u8 = if (is_command)
1245
+ security.permission_command
1246
+ else if (is_view)
1247
+ security.permission_view
1248
+ else if (is_window or is_webview or is_platform)
1249
+ security.permission_window
1250
+ else
1251
+ null;
1252
+ if (!allowsBuiltinBridgeCommand(self, request.command, message.origin, js_permission)) {
1253
+ const message_text = if (is_view)
1254
+ "View API is not permitted"
1255
+ else if (is_webview)
1256
+ "WebView API is not permitted"
1257
+ else if (is_window)
1258
+ "Window API is not permitted"
1259
+ else if (is_command)
1260
+ "Command API is not permitted"
1261
+ else if (is_platform)
1262
+ "Platform API is not permitted"
1263
+ else if (is_os)
1264
+ "OS API is not permitted"
1265
+ else if (is_clipboard)
1266
+ "Clipboard API is not permitted"
1267
+ else if (is_credentials)
1268
+ "Credentials API is not permitted"
1269
+ else
1270
+ "Dialog API is not permitted";
1271
+ const result = bridge.writeErrorResponse(&response_buffer, request.id, .permission_denied, message_text);
1272
+ try completeBridgeResponse(self, message.window_id, message.webview_label, result);
1273
+ self.invalidateFor(.command, null);
1274
+ return true;
1275
+ }
1276
+ const result = if (is_command)
1277
+ dispatchCommandBridgeCommand(self, app, request, message.window_id, message.webview_label, &result_buffer, &response_buffer)
1278
+ else if (is_window)
1279
+ dispatchWindowBridgeCommand(self, request, &result_buffer, &response_buffer)
1280
+ else if (is_view)
1281
+ dispatchViewBridgeCommand(self, request, message.window_id, &result_buffer, &response_buffer)
1282
+ else if (is_webview)
1283
+ dispatchWebViewBridgeCommand(self, request, message.window_id, &result_buffer, &response_buffer)
1284
+ else if (is_platform)
1285
+ dispatchPlatformBridgeCommand(self, request, &result_buffer, &response_buffer)
1286
+ else if (is_dialog)
1287
+ dispatchDialogBridgeCommand(self, request, &result_buffer, &response_buffer)
1288
+ else if (is_clipboard)
1289
+ dispatchClipboardBridgeCommand(self, request, &result_buffer, &response_buffer)
1290
+ else if (is_credentials)
1291
+ dispatchCredentialBridgeCommand(self, request, &result_buffer, &response_buffer)
1292
+ else
1293
+ dispatchOsBridgeCommand(self, request, message.origin, &result_buffer, &response_buffer);
1294
+
1295
+ try completeBridgeResponse(self, message.window_id, message.webview_label, result);
1296
+ self.invalidateFor(.command, null);
1297
+ return true;
1298
+ }
1299
+
1300
+ fn completeBridgeResponse(self: *Runtime, window_id: platform.WindowId, webview_label: []const u8, response: []const u8) anyerror!void {
1301
+ try self.options.platform.services.completeWebViewBridge(window_id, webview_label, response);
1302
+ if (self.options.automation) |server| {
1303
+ server.publishBridgeResponse(response) catch |err| log(self, "automation.bridge_response_failed", @errorName(err), &.{});
1304
+ }
1305
+ }
1306
+
1307
+ fn emitShortcutEvent(self: *Runtime, shortcut: platform.ShortcutEvent) anyerror!void {
1308
+ var buffer: [512]u8 = undefined;
1309
+ var writer = std.Io.Writer.fixed(&buffer);
1310
+ try writer.writeAll("{\"id\":");
1311
+ try json.writeString(&writer, shortcut.id);
1312
+ try writer.writeAll(",\"command\":");
1313
+ try json.writeString(&writer, shortcut.id);
1314
+ try writer.writeAll(",\"key\":");
1315
+ try json.writeString(&writer, shortcut.key);
1316
+ try writer.print(",\"windowId\":{d},\"modifiers\":{{\"primary\":{},\"command\":{},\"control\":{},\"option\":{},\"shift\":{}}}}}", .{
1317
+ shortcut.window_id,
1318
+ shortcut.modifiers.primary,
1319
+ shortcut.modifiers.command,
1320
+ shortcut.modifiers.control,
1321
+ shortcut.modifiers.option,
1322
+ shortcut.modifiers.shift,
1323
+ });
1324
+ try emitWindowEvent(self, shortcut.window_id, "shortcut", writer.buffered());
1325
+ }
1326
+
1327
+ fn emitAppLifecycleEvent(self: *Runtime, name: []const u8) anyerror!void {
1328
+ for (self.windows[0..self.window_count]) |window| {
1329
+ if (window.info.open) try emitWindowEvent(self, window.info.id, name, "{}");
1330
+ }
1331
+ }
1332
+
1333
+ fn emitFileDropEvent(self: *Runtime, drop: platform.FileDropEvent) anyerror!void {
1334
+ var buffer: [platform.max_window_event_detail_bytes]u8 = undefined;
1335
+ var writer = std.Io.Writer.fixed(&buffer);
1336
+ try writer.print("{{\"windowId\":{d}", .{drop.window_id});
1337
+ if (drop.view_label.len > 0) {
1338
+ try writer.writeAll(",\"viewLabel\":");
1339
+ try json.writeString(&writer, drop.view_label);
1340
+ }
1341
+ if (drop.point) |point| {
1342
+ try writer.print(",\"x\":{d},\"y\":{d}", .{ point.x, point.y });
1343
+ }
1344
+ try writer.writeAll(",\"paths\":[");
1345
+ for (drop.paths, 0..) |path, index| {
1346
+ if (index > 0) try writer.writeByte(',');
1347
+ try json.writeString(&writer, path);
1348
+ }
1349
+ try writer.writeAll("]}");
1350
+ try emitWindowEvent(self, drop.window_id, "drop:files", writer.buffered());
1351
+ }
1352
+
1353
+ /// Trace logging never fails dispatch: a full or failing
1354
+ /// sink drops the record and counts the loss where snapshots can
1355
+ /// see it (`dropped_trace_records`).
1356
+ fn log(self: *Runtime, name_value: []const u8, message: ?[]const u8, fields: []const trace.Field) void {
1357
+ logAt(self, .info, name_value, message, fields);
1358
+ }
1359
+
1360
+ fn logAt(self: *Runtime, level: trace.Level, name_value: []const u8, message: ?[]const u8, fields: []const trace.Field) void {
1361
+ const sink = self.options.trace_sink orelse return;
1362
+ trace.writeRecord(sink, trace.event(nextTimestamp(self), level, name_value, message, fields)) catch {
1363
+ self.dropped_trace_records +%= 1;
1364
+ };
1365
+ }
1366
+
1367
+ /// A handler/update error must degrade, never terminate the
1368
+ /// app: record it in the bounded ring (queryable through
1369
+ /// `Runtime.dispatchErrors` and the automation snapshot), trace
1370
+ /// it at `.err`, and republish observable state.
1371
+ pub fn recordDispatchError(self: *Runtime, event_name: []const u8, err: anyerror) void {
1372
+ recordDispatchErrorDetail(self, event_name, err, "");
1373
+ }
1374
+
1375
+ /// `detail` is copied (truncated) into the record so the snapshot
1376
+ /// error line carries failure context — for automation commands,
1377
+ /// the command arguments, so a failed widget verb names its
1378
+ /// target.
1379
+ fn recordDispatchErrorDetail(self: *Runtime, event_name: []const u8, err: anyerror, detail: []const u8) void {
1380
+ self.dispatch_error_total +%= 1;
1381
+ var record: automation.snapshot.DispatchError = .{
1382
+ .timestamp_ns = runtime_clock.timestampToU64(nowNanoseconds()),
1383
+ .error_name = @errorName(err),
1384
+ };
1385
+ record.setEvent(event_name);
1386
+ record.setDetail(detail);
1387
+ if (self.dispatch_error_len == self.dispatch_errors.len) {
1388
+ std.mem.copyForwards(automation.snapshot.DispatchError, self.dispatch_errors[0 .. self.dispatch_errors.len - 1], self.dispatch_errors[1..]);
1389
+ self.dispatch_errors[self.dispatch_errors.len - 1] = record;
1390
+ } else {
1391
+ self.dispatch_errors[self.dispatch_error_len] = record;
1392
+ self.dispatch_error_len += 1;
1393
+ }
1394
+ logAt(self, .err, "dispatch.error", @errorName(err), &.{trace.string("event", event_name)});
1395
+ self.invalidateFor(.state, null);
1396
+ }
1397
+
1398
+ fn extensionContext(self: *Runtime) extensions.RuntimeContext {
1399
+ return .{ .platform_name = self.options.platform.name };
1400
+ }
1401
+
1402
+ fn nextTimestamp(self: *Runtime) trace.Timestamp {
1403
+ self.timestamp_ns = nowNanoseconds();
1404
+ return trace.Timestamp.fromNanoseconds(self.timestamp_ns);
1405
+ }
1406
+ };
1407
+ }
1408
+
1409
+ fn copyInto(buffer: []u8, value: []const u8) ![]const u8 {
1410
+ if (value.len > buffer.len) return error.NoSpaceLeft;
1411
+ @memcpy(buffer[0..value.len], value);
1412
+ return buffer[0..value.len];
1413
+ }
1414
+
1415
+ fn appUsesDefaultEmptyWebViewSource(comptime App: type, app: App) bool {
1416
+ return app.source_fn == null and
1417
+ app.source.kind == .html and
1418
+ app.source.bytes.len == 0 and
1419
+ app.source.asset_options == null;
1420
+ }
1421
+
1422
+ fn sceneWindowUsesAppSource(shell_window: app_manifest.ShellWindow, app_uses_default_empty_source: bool) bool {
1423
+ if (shellWindowNeedsMainWebView(shell_window)) return true;
1424
+ if (shellWindowUsesSourcelessCanvas(shell_window)) return false;
1425
+ return !app_uses_default_empty_source;
1426
+ }