@native-sdk/cli 0.0.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/assets/icon.icns +0 -0
  5. package/assets/icon.ico +0 -0
  6. package/assets/icon.png +0 -0
  7. package/assets/icon.svg +15 -0
  8. package/assets/native-sdk.entitlements +10 -0
  9. package/assets/native-sdk.manifest +12 -0
  10. package/bin/native.js +156 -0
  11. package/build/app.zig +716 -0
  12. package/build.zig +2593 -0
  13. package/build.zig.zon +24 -0
  14. package/native-sdk.d.ts +615 -0
  15. package/package.json +45 -8
  16. package/skill-data/automation/SKILL.md +248 -0
  17. package/skill-data/core/SKILL.md +249 -0
  18. package/skill-data/core/references/app-model-runtime.md +141 -0
  19. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  20. package/skill-data/core/references/frontend-assets.md +124 -0
  21. package/skill-data/core/references/project-anatomy.md +108 -0
  22. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  23. package/skill-data/native-ui/SKILL.md +1080 -0
  24. package/skills/native-sdk/SKILL.md +33 -0
  25. package/src/app_runner/root.zig +740 -0
  26. package/src/assets/root.zig +20 -0
  27. package/src/automation/protocol.zig +285 -0
  28. package/src/automation/root.zig +13 -0
  29. package/src/automation/server.zig +506 -0
  30. package/src/automation/snapshot.zig +1202 -0
  31. package/src/automation/watcher.zig +165 -0
  32. package/src/bridge/root.zig +507 -0
  33. package/src/debug/root.zig +246 -0
  34. package/src/embed/app_exports.zig +11 -0
  35. package/src/embed/c_api.zig +793 -0
  36. package/src/embed/c_exports.zig +10 -0
  37. package/src/embed/chrome.zig +168 -0
  38. package/src/embed/conversions.zig +359 -0
  39. package/src/embed/host.zig +960 -0
  40. package/src/embed/root.zig +81 -0
  41. package/src/embed/tests.zig +2552 -0
  42. package/src/embed/types.zig +382 -0
  43. package/src/embed/ui_host.zig +289 -0
  44. package/src/extensions/root.zig +197 -0
  45. package/src/frontend/root.zig +48 -0
  46. package/src/js/root.zig +65 -0
  47. package/src/platform/android/NativeSdkActivity.java +1370 -0
  48. package/src/platform/android/android_host.c +696 -0
  49. package/src/platform/android/files.zig +9 -0
  50. package/src/platform/android/native_sdk_app.h +237 -0
  51. package/src/platform/ios/files.zig +8 -0
  52. package/src/platform/ios/native_sdk_app.h +289 -0
  53. package/src/platform/ios/uikit_host.m +2739 -0
  54. package/src/platform/linux/cef_host.cpp +599 -0
  55. package/src/platform/linux/gtk_host.c +5362 -0
  56. package/src/platform/linux/gtk_host.h +265 -0
  57. package/src/platform/linux/root.zig +1519 -0
  58. package/src/platform/macos/appkit_host.h +604 -0
  59. package/src/platform/macos/appkit_host.m +10392 -0
  60. package/src/platform/macos/automation_host.h +14 -0
  61. package/src/platform/macos/automation_host.m +12 -0
  62. package/src/platform/macos/cef_host.mm +3028 -0
  63. package/src/platform/macos/root.zig +2260 -0
  64. package/src/platform/null_platform.zig +2232 -0
  65. package/src/platform/null_platform_tests.zig +670 -0
  66. package/src/platform/policy_values.zig +14 -0
  67. package/src/platform/root.zig +181 -0
  68. package/src/platform/types.zig +2681 -0
  69. package/src/platform/windows/cef_host.cpp +3 -0
  70. package/src/platform/windows/root.zig +1521 -0
  71. package/src/platform/windows/webview2_host.cpp +6230 -0
  72. package/src/primitives/app_dirs/root.zig +440 -0
  73. package/src/primitives/app_manifest/root.zig +109 -0
  74. package/src/primitives/app_manifest/tests.zig +758 -0
  75. package/src/primitives/app_manifest/types.zig +587 -0
  76. package/src/primitives/app_manifest/validation.zig +828 -0
  77. package/src/primitives/assets/root.zig +520 -0
  78. package/src/primitives/canvas/a11y_audit.zig +390 -0
  79. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  80. package/src/primitives/canvas/app_icon.zig +1590 -0
  81. package/src/primitives/canvas/chart.zig +392 -0
  82. package/src/primitives/canvas/chart_tests.zig +751 -0
  83. package/src/primitives/canvas/commands.zig +446 -0
  84. package/src/primitives/canvas/drawing.zig +309 -0
  85. package/src/primitives/canvas/equality.zig +316 -0
  86. package/src/primitives/canvas/events.zig +696 -0
  87. package/src/primitives/canvas/font_coverage.zig +118 -0
  88. package/src/primitives/canvas/font_ttf.zig +510 -0
  89. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  90. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  91. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  92. package/src/primitives/canvas/frame.zig +679 -0
  93. package/src/primitives/canvas/frame_metrics.zig +462 -0
  94. package/src/primitives/canvas/gpu.zig +639 -0
  95. package/src/primitives/canvas/hash.zig +112 -0
  96. package/src/primitives/canvas/icons/alert.svg +1 -0
  97. package/src/primitives/canvas/icons/archive.svg +1 -0
  98. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  99. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  100. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  101. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  102. package/src/primitives/canvas/icons/check.svg +1 -0
  103. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  104. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  105. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  106. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  107. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  108. package/src/primitives/canvas/icons/clock.svg +1 -0
  109. package/src/primitives/canvas/icons/copy.svg +1 -0
  110. package/src/primitives/canvas/icons/download.svg +1 -0
  111. package/src/primitives/canvas/icons/edit.svg +1 -0
  112. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  113. package/src/primitives/canvas/icons/external-link.svg +1 -0
  114. package/src/primitives/canvas/icons/eye.svg +1 -0
  115. package/src/primitives/canvas/icons/file-text.svg +1 -0
  116. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  117. package/src/primitives/canvas/icons/folder.svg +1 -0
  118. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  119. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  120. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  121. package/src/primitives/canvas/icons/info.svg +1 -0
  122. package/src/primitives/canvas/icons/menu.svg +1 -0
  123. package/src/primitives/canvas/icons/missing.svg +1 -0
  124. package/src/primitives/canvas/icons/moon.svg +1 -0
  125. package/src/primitives/canvas/icons/music.svg +1 -0
  126. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  127. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  128. package/src/primitives/canvas/icons/pause.svg +1 -0
  129. package/src/primitives/canvas/icons/play.svg +1 -0
  130. package/src/primitives/canvas/icons/plus.svg +1 -0
  131. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  132. package/src/primitives/canvas/icons/repeat.svg +1 -0
  133. package/src/primitives/canvas/icons/save.svg +1 -0
  134. package/src/primitives/canvas/icons/search.svg +1 -0
  135. package/src/primitives/canvas/icons/send.svg +1 -0
  136. package/src/primitives/canvas/icons/settings.svg +1 -0
  137. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  138. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  139. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  140. package/src/primitives/canvas/icons/sun.svg +1 -0
  141. package/src/primitives/canvas/icons/terminal.svg +1 -0
  142. package/src/primitives/canvas/icons/trash.svg +1 -0
  143. package/src/primitives/canvas/icons/volume.svg +1 -0
  144. package/src/primitives/canvas/icons/wrench.svg +1 -0
  145. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  146. package/src/primitives/canvas/icons/x.svg +1 -0
  147. package/src/primitives/canvas/icons.zig +249 -0
  148. package/src/primitives/canvas/layout_audit.zig +744 -0
  149. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  150. package/src/primitives/canvas/markdown.zig +1031 -0
  151. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  152. package/src/primitives/canvas/markdown_tests.zig +538 -0
  153. package/src/primitives/canvas/plan_key_index.zig +120 -0
  154. package/src/primitives/canvas/png.zig +355 -0
  155. package/src/primitives/canvas/reference.zig +1457 -0
  156. package/src/primitives/canvas/reference_blur.zig +104 -0
  157. package/src/primitives/canvas/reference_memo.zig +322 -0
  158. package/src/primitives/canvas/reference_paths.zig +184 -0
  159. package/src/primitives/canvas/reference_tests.zig +1650 -0
  160. package/src/primitives/canvas/render.zig +747 -0
  161. package/src/primitives/canvas/render_effects.zig +255 -0
  162. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  163. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  164. package/src/primitives/canvas/render_images.zig +247 -0
  165. package/src/primitives/canvas/render_layers.zig +260 -0
  166. package/src/primitives/canvas/render_paths.zig +347 -0
  167. package/src/primitives/canvas/render_resources.zig +51 -0
  168. package/src/primitives/canvas/render_tests.zig +3186 -0
  169. package/src/primitives/canvas/root.zig +744 -0
  170. package/src/primitives/canvas/serialization.zig +1528 -0
  171. package/src/primitives/canvas/svg_icon.zig +636 -0
  172. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  173. package/src/primitives/canvas/test_support.zig +422 -0
  174. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  175. package/src/primitives/canvas/tests.zig +30 -0
  176. package/src/primitives/canvas/text.zig +82 -0
  177. package/src/primitives/canvas/text_atlas.zig +408 -0
  178. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  179. package/src/primitives/canvas/text_interaction.zig +615 -0
  180. package/src/primitives/canvas/text_layout.zig +1069 -0
  181. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  182. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  183. package/src/primitives/canvas/text_layout_types.zig +128 -0
  184. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  185. package/src/primitives/canvas/text_metrics.zig +309 -0
  186. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  187. package/src/primitives/canvas/text_span_tests.zig +608 -0
  188. package/src/primitives/canvas/text_spans.zig +1010 -0
  189. package/src/primitives/canvas/text_tests.zig +1949 -0
  190. package/src/primitives/canvas/themes/geist.zig +470 -0
  191. package/src/primitives/canvas/tokens.zig +1522 -0
  192. package/src/primitives/canvas/ui.zig +2686 -0
  193. package/src/primitives/canvas/ui_markup.zig +3791 -0
  194. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  195. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  196. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  197. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  198. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  199. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  200. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  201. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  202. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  203. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  204. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  205. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  206. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  207. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  208. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  209. package/src/primitives/canvas/ui_provenance.zig +96 -0
  210. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  211. package/src/primitives/canvas/ui_schema.zig +825 -0
  212. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  213. package/src/primitives/canvas/ui_tests.zig +1432 -0
  214. package/src/primitives/canvas/vector.zig +919 -0
  215. package/src/primitives/canvas/vector_tests.zig +547 -0
  216. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  217. package/src/primitives/canvas/virtual_extents.zig +540 -0
  218. package/src/primitives/canvas/widget_access.zig +208 -0
  219. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  220. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  221. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  222. package/src/primitives/canvas/widget_layout.zig +2055 -0
  223. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  224. package/src/primitives/canvas/widget_metrics.zig +228 -0
  225. package/src/primitives/canvas/widget_render.zig +2534 -0
  226. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  227. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  228. package/src/primitives/canvas/widget_render_style.zig +626 -0
  229. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  230. package/src/primitives/canvas/widget_routing.zig +475 -0
  231. package/src/primitives/canvas/widget_runtime.zig +307 -0
  232. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  233. package/src/primitives/canvas/widget_semantics.zig +480 -0
  234. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  235. package/src/primitives/canvas/widget_tests.zig +8 -0
  236. package/src/primitives/canvas/widget_text_input.zig +351 -0
  237. package/src/primitives/canvas/widget_text_select.zig +147 -0
  238. package/src/primitives/canvas/widget_tree.zig +232 -0
  239. package/src/primitives/canvas/widgets.zig +1319 -0
  240. package/src/primitives/diagnostics/root.zig +445 -0
  241. package/src/primitives/geometry/root.zig +889 -0
  242. package/src/primitives/json/root.zig +272 -0
  243. package/src/primitives/platform_info/root.zig +450 -0
  244. package/src/primitives/trace/root.zig +569 -0
  245. package/src/root.zig +165 -0
  246. package/src/runtime/api.zig +431 -0
  247. package/src/runtime/async_bridge.zig +49 -0
  248. package/src/runtime/automation_commands.zig +686 -0
  249. package/src/runtime/automation_liveness_tests.zig +140 -0
  250. package/src/runtime/automation_snapshot.zig +246 -0
  251. package/src/runtime/automation_widget_dispatch.zig +617 -0
  252. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  253. package/src/runtime/bridge_payload.zig +194 -0
  254. package/src/runtime/bridge_permission_tests.zig +551 -0
  255. package/src/runtime/bridge_responses.zig +414 -0
  256. package/src/runtime/builtin_bridge.zig +554 -0
  257. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  258. package/src/runtime/canvas_font_tests.zig +410 -0
  259. package/src/runtime/canvas_fonts.zig +229 -0
  260. package/src/runtime/canvas_frame.zig +1734 -0
  261. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  262. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  263. package/src/runtime/canvas_frame_helpers.zig +414 -0
  264. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  265. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  266. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  267. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  268. package/src/runtime/canvas_frame_tests.zig +9 -0
  269. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  270. package/src/runtime/canvas_image_tests.zig +362 -0
  271. package/src/runtime/canvas_images.zig +224 -0
  272. package/src/runtime/canvas_limits.zig +317 -0
  273. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  274. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  275. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  276. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  277. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  278. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  279. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  280. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  281. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  282. package/src/runtime/canvas_widget_display.zig +677 -0
  283. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  284. package/src/runtime/canvas_widget_events.zig +1098 -0
  285. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  286. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  287. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  288. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  289. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  290. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  291. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  292. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  293. package/src/runtime/canvas_widget_state.zig +798 -0
  294. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  295. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  296. package/src/runtime/clock.zig +231 -0
  297. package/src/runtime/core.zig +927 -0
  298. package/src/runtime/effects.zig +4197 -0
  299. package/src/runtime/effects_audio_tests.zig +690 -0
  300. package/src/runtime/effects_clipboard_tests.zig +317 -0
  301. package/src/runtime/effects_fetch_tests.zig +1031 -0
  302. package/src/runtime/effects_file_tests.zig +407 -0
  303. package/src/runtime/effects_tests.zig +1251 -0
  304. package/src/runtime/flow.zig +1175 -0
  305. package/src/runtime/frame_profile.zig +221 -0
  306. package/src/runtime/gpu_surface_events.zig +639 -0
  307. package/src/runtime/launch_timing.zig +59 -0
  308. package/src/runtime/markdown_app_tests.zig +224 -0
  309. package/src/runtime/native_command_event_tests.zig +431 -0
  310. package/src/runtime/platform_bridge_tests.zig +8 -0
  311. package/src/runtime/platform_config_tests.zig +392 -0
  312. package/src/runtime/root.zig +150 -0
  313. package/src/runtime/runtime_event_tests.zig +1079 -0
  314. package/src/runtime/session_journal.zig +1522 -0
  315. package/src/runtime/session_record.zig +332 -0
  316. package/src/runtime/session_replay.zig +274 -0
  317. package/src/runtime/session_state.zig +30 -0
  318. package/src/runtime/session_tests.zig +399 -0
  319. package/src/runtime/shell_layout.zig +472 -0
  320. package/src/runtime/shell_layout_tests.zig +1246 -0
  321. package/src/runtime/shell_view_tests.zig +604 -0
  322. package/src/runtime/state.zig +110 -0
  323. package/src/runtime/system_services.zig +392 -0
  324. package/src/runtime/test_support.zig +79 -0
  325. package/src/runtime/tests.zig +30 -0
  326. package/src/runtime/ui_app.zig +3290 -0
  327. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  328. package/src/runtime/ui_app_provenance.zig +370 -0
  329. package/src/runtime/ui_app_tests.zig +3254 -0
  330. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  331. package/src/runtime/ui_app_window_tests.zig +442 -0
  332. package/src/runtime/validation.zig +206 -0
  333. package/src/runtime/view.zig +908 -0
  334. package/src/runtime/view_canvas.zig +850 -0
  335. package/src/runtime/view_widget_control.zig +433 -0
  336. package/src/runtime/view_widget_scroll.zig +360 -0
  337. package/src/runtime/view_widget_text.zig +275 -0
  338. package/src/runtime/view_widget_tree.zig +843 -0
  339. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  340. package/src/runtime/widget_bridge.zig +231 -0
  341. package/src/runtime/window_command_bridge_tests.zig +403 -0
  342. package/src/runtime/window_storage.zig +255 -0
  343. package/src/runtime/window_view_runtime.zig +727 -0
  344. package/src/runtime/window_views.zig +334 -0
  345. package/src/security/root.zig +118 -0
  346. package/src/tooling/android.zig +1172 -0
  347. package/src/tooling/assets.zig +128 -0
  348. package/src/tooling/buildgraph.zig +379 -0
  349. package/src/tooling/cef.zig +671 -0
  350. package/src/tooling/codesign.zig +172 -0
  351. package/src/tooling/components/identity_tests.zig +185 -0
  352. package/src/tooling/components/stepper.zig +113 -0
  353. package/src/tooling/components/timeline.native +27 -0
  354. package/src/tooling/components/timeline_item.zig +131 -0
  355. package/src/tooling/default_icon.icns +0 -0
  356. package/src/tooling/default_icon.png +0 -0
  357. package/src/tooling/dev.zig +172 -0
  358. package/src/tooling/doctor.zig +349 -0
  359. package/src/tooling/eject_components.zig +170 -0
  360. package/src/tooling/embedlib.zig +290 -0
  361. package/src/tooling/ios.zig +528 -0
  362. package/src/tooling/manifest.zig +1939 -0
  363. package/src/tooling/package.zig +2388 -0
  364. package/src/tooling/process_tree.zig +114 -0
  365. package/src/tooling/raw_manifest.zig +193 -0
  366. package/src/tooling/root.zig +22 -0
  367. package/src/tooling/templates.zig +3191 -0
  368. package/src/tooling/toolchain.zig +371 -0
  369. package/src/tooling/verbs.zig +204 -0
  370. package/src/tooling/web_engine.zig +135 -0
  371. package/src/tooling/xcodeproj.zig +462 -0
  372. package/src/window_state/root.zig +507 -0
  373. package/index.js +0 -2
@@ -0,0 +1,1175 @@
1
+ const std = @import("std");
2
+ const geometry = @import("geometry");
3
+ const trace = @import("trace");
4
+ const json = @import("json");
5
+ const validation = @import("validation.zig");
6
+ const runtime_api = @import("api.zig");
7
+ const runtime_async_bridge = @import("async_bridge.zig");
8
+ const runtime_automation_snapshot = @import("automation_snapshot.zig");
9
+ const runtime_automation_widget_dispatch = @import("automation_widget_dispatch.zig");
10
+ const automation_commands = @import("automation_commands.zig");
11
+ const launch_timing = @import("launch_timing.zig");
12
+ const runtime_clock = @import("clock.zig");
13
+ const shell_layout = @import("shell_layout.zig");
14
+ const runtime_builtin_bridge = @import("builtin_bridge.zig");
15
+ const runtime_canvas_widget_context_menu = @import("canvas_widget_context_menu.zig");
16
+ const runtime_canvas_widget_scroll_drivers = @import("canvas_widget_scroll_drivers.zig");
17
+ const runtime_gpu_surface_events = @import("gpu_surface_events.zig");
18
+ const runtime_system_services = @import("system_services.zig");
19
+ const runtime_window_views = @import("window_views.zig");
20
+ const widget_bridge = @import("widget_bridge.zig");
21
+ const automation = @import("../automation/root.zig");
22
+ const bridge = @import("../bridge/root.zig");
23
+ const extensions = @import("../extensions/root.zig");
24
+ const app_manifest = @import("app_manifest");
25
+ const platform = @import("../platform/root.zig");
26
+ const security = @import("../security/root.zig");
27
+
28
+ const validateCommandName = validation.validateCommandName;
29
+ const sceneNeedsMainWebView = shell_layout.sceneNeedsMainWebView;
30
+ const nowNanoseconds = runtime_clock.nowNanoseconds;
31
+ const canvasWidgetAccessibilityActionKindFromPlatform = widget_bridge.canvasWidgetAccessibilityActionKindFromPlatform;
32
+ const parseAutomationCommandName = automation_commands.parseAutomationCommandName;
33
+ const parseAutomationViewLabel = automation_commands.parseAutomationViewLabel;
34
+ const parseAutomationNativeCommand = automation_commands.parseAutomationNativeCommand;
35
+ const parseAutomationWidgetAction = automation_commands.parseAutomationWidgetAction;
36
+ const parseAutomationWidgetTarget = automation_commands.parseAutomationWidgetTarget;
37
+ const parseAutomationProvenanceTarget = automation_commands.parseAutomationProvenanceTarget;
38
+ const parseAutomationWidgetWheel = automation_commands.parseAutomationWidgetWheel;
39
+ const parseAutomationWidgetContextMenuItem = automation_commands.parseAutomationWidgetContextMenuItem;
40
+ const parseAutomationWidgetKey = automation_commands.parseAutomationWidgetKey;
41
+ const parseAutomationWidgetPointerDrag = automation_commands.parseAutomationWidgetPointerDrag;
42
+ const parseAutomationResizeCommand = automation_commands.parseAutomationResizeCommand;
43
+ const parseAutomationTrayItemId = automation_commands.parseAutomationTrayItemId;
44
+ const parseAutomationScreenshotCommand = automation_commands.parseAutomationScreenshotCommand;
45
+ const canvas = @import("canvas");
46
+
47
+ pub fn RuntimeFlow(comptime Runtime: type) type {
48
+ return struct {
49
+ const App = runtime_api.App(Runtime);
50
+ const Event = runtime_api.Event;
51
+ const CommandEvent = runtime_api.CommandEvent;
52
+ const FrameDiagnostics = runtime_api.FrameDiagnostics;
53
+ const AsyncBridgeResponseSlot = runtime_async_bridge.AsyncBridgeResponseSlot(Runtime);
54
+ const RunContext = struct {
55
+ runtime: *Runtime,
56
+ app: App,
57
+ };
58
+
59
+ fn WindowViewMethods() type {
60
+ return runtime_window_views.RuntimeWindowViews(Runtime);
61
+ }
62
+
63
+ fn SystemServiceMethods() type {
64
+ return runtime_system_services.RuntimeSystemServices(Runtime);
65
+ }
66
+
67
+ fn GpuSurfaceEventMethods() type {
68
+ return runtime_gpu_surface_events.RuntimeGpuSurfaceEvents(Runtime);
69
+ }
70
+
71
+ fn ScrollDriverMethods() type {
72
+ return runtime_canvas_widget_scroll_drivers.RuntimeCanvasWidgetScrollDrivers(Runtime);
73
+ }
74
+
75
+ fn ContextMenuMethods() type {
76
+ return runtime_canvas_widget_context_menu.RuntimeCanvasWidgetContextMenu(Runtime);
77
+ }
78
+
79
+ fn AutomationWidgetMethods() type {
80
+ return runtime_automation_widget_dispatch.RuntimeAutomationWidgetDispatch(Runtime);
81
+ }
82
+
83
+ pub fn run(self: *Runtime, app: App) anyerror!void {
84
+ var init_fields: [3]trace.Field = undefined;
85
+ init_fields[0] = trace.string("app", app.name);
86
+ init_fields[1] = trace.string("platform", self.options.platform.name);
87
+ var init_field_count: usize = 2;
88
+ if (self.options.log_path) |log_path| {
89
+ init_fields[init_field_count] = trace.string("log_path", log_path);
90
+ init_field_count += 1;
91
+ }
92
+ log(self, "runtime.init", "runtime initialized", init_fields[0..init_field_count]);
93
+ try app_manifest.validateCommands(self.options.commands);
94
+ try self.options.platform.services.configureSecurityPolicy(self.options.security);
95
+ try self.options.platform.services.configureMenus(self.options.menus);
96
+ try self.options.platform.services.configureShortcuts(self.options.shortcuts);
97
+ // Automation liveness: the drain (`consumeAutomationCommand`,
98
+ // in `frame` below) runs at most once per frame_requested
99
+ // turn, and an idle app produces no frames — so a queued
100
+ // command must WAKE the loop the way user input does. The
101
+ // arrival watcher polls the dropbox slot on its own thread
102
+ // and asks the platform for one coalesced frame tick through
103
+ // its thread-safe `request_frame_fn` whenever a command is
104
+ // pending. Consumption itself stays on the frame boundary,
105
+ // so command order, one-command-per-frame, and session
106
+ // recording/replay (commands nest inside recorded
107
+ // frame_requested events) are unchanged; only the frame's
108
+ // ARRIVAL time moves. No automation server (any non-dev
109
+ // build) means no thread and no polls at all.
110
+ var command_watcher: automation.Watcher = undefined;
111
+ var command_watcher_running = false;
112
+ if (self.options.automation) |server| {
113
+ if (self.options.platform.services.request_frame_fn) |request_fn| {
114
+ command_watcher_running = command_watcher.start(server, .{
115
+ .context = self.options.platform.services.context,
116
+ .request_fn = request_fn,
117
+ });
118
+ if (!command_watcher_running) {
119
+ log(self, "automation.watcher_failed", "automation command watcher thread did not start; commands drain on the next unrelated frame", &.{});
120
+ }
121
+ } else {
122
+ // A platform without the cross-thread frame request
123
+ // keeps the old behavior (commands drain on whatever
124
+ // frame arrives next); say so once instead of wedging
125
+ // silently.
126
+ log(self, "automation.watcher_unsupported", "platform has no cross-thread frame request; automation commands drain on the next unrelated frame", &.{});
127
+ }
128
+ }
129
+ // Stopped (joined) before the platform loop's resources go
130
+ // away, so the watcher can never call into a dead host.
131
+ defer if (command_watcher_running) command_watcher.stop();
132
+
133
+ // Teardown ordering contract: everything the app must do
134
+ // against the live platform — silencing an active audio
135
+ // player, disarming platform timers, joining effect workers
136
+ // that post through the platform's wake service — happens in
137
+ // the app's stop hook, and that hook is guaranteed to run
138
+ // before run() returns. The app's OWN deinit cannot serve
139
+ // this purpose: it is typically a `defer` in main that runs
140
+ // only after the runner's later-declared defers have already
141
+ // destroyed the platform host and freed the runtime, so any
142
+ // platform service call from there dereferences freed memory
143
+ // (the quit-while-audio-plays use-after-free). The platform's
144
+ // `.app_shutdown` event delivers the stop hook on the normal
145
+ // quit path; this defer delivers it when the loop exits any
146
+ // other way (an error unwind, a host that stops without a
147
+ // shutdown event) — exactly once either way, gated by
148
+ // `app_stop_delivered`.
149
+ defer if (!self.app_stop_delivered) {
150
+ self.app_stop_delivered = true;
151
+ app.stop(self) catch |err| log(self, "app.stop.failed", @errorName(err), &.{trace.string("app", app.name)});
152
+ };
153
+
154
+ var context: RunContext = .{ .runtime = self, .app = app };
155
+ try self.options.platform.run(handlePlatformEvent, &context);
156
+
157
+ log(self, "runtime.done", "runtime finished", &.{});
158
+ }
159
+
160
+ fn reservePrimaryStartupWindow(self: *Runtime) anyerror!void {
161
+ const app_info = self.options.platform.app_info;
162
+ if (app_info.startupWindowCount() == 0) return;
163
+ const window = app_info.resolvedStartupWindow(0);
164
+ if (WindowViewMethods().findWindowIndexById(self, window.id) != null) return;
165
+
166
+ const runtime_index = try WindowViewMethods().reserveWindow(self, window.id, window.label, window.resolvedTitle(app_info.app_name), null, true);
167
+ self.windows[runtime_index].info.frame = window.default_frame;
168
+ self.windows[runtime_index].main_frame = geometry.RectF.init(0, 0, window.default_frame.width, window.default_frame.height);
169
+ self.next_window_id = @max(self.next_window_id, window.id + 1);
170
+ }
171
+
172
+ pub fn emitWindowEvent(self: *Runtime, window_id: platform.WindowId, name: []const u8, detail_json: []const u8) anyerror!void {
173
+ if (!json.isValidValue(detail_json)) return error.InvalidJsonEventDetail;
174
+ try self.options.platform.services.emitWindowEvent(window_id, name, detail_json);
175
+ }
176
+
177
+ pub fn respondToBridge(self: *Runtime, source: bridge.Source, response: []const u8) anyerror!void {
178
+ try completeBridgeResponse(self, source.window_id, source.webview_label, response);
179
+ }
180
+
181
+ pub fn dispatchPlatformEvent(self: *Runtime, app: App, event_value: platform.Event) anyerror!void {
182
+ // Session recording: stage the event on entry, commit it on
183
+ // exit — so effect results drained DURING dispatch precede
184
+ // the event record in the journal (replay feeds them before
185
+ // dispatching), and nested dispatches (automation commands
186
+ // inside frame_requested) commit innermost-first. One state
187
+ // fingerprint checkpoint follows each published frame.
188
+ if (self.options.session_recorder) |recorder| recorder.stageEvent(event_value);
189
+ defer if (self.options.session_recorder) |recorder| {
190
+ recorder.commitEvent();
191
+ if (recorder.wantsCheckpoint(self.frame_index)) {
192
+ recorder.recordCheckpoint(self.frame_index, self.sessionStateFingerprint());
193
+ }
194
+ // Seal on shutdown, here rather than only at run() exit:
195
+ // a host that terminates without unwinding the platform
196
+ // loop still leaves a whole journal behind.
197
+ if (event_value == .app_shutdown) recorder.finish();
198
+ };
199
+
200
+ if ((event_value != .frame_requested and event_value != .gpu_surface_frame) or self.invalidated) {
201
+ const event_fields = [_]trace.Field{trace.string("event", event_value.name())};
202
+ log(self, "platform.event", null, &event_fields);
203
+ }
204
+
205
+ switch (event_value) {
206
+ .app_start => {
207
+ // A startup failure must be loud and attributable.
208
+ // Without this record the error unwinds into the
209
+ // platform stop path and the only trace is a bare
210
+ // `app.stop` right after `start` — which reads like a
211
+ // clean exit while the main window sits blank.
212
+ errdefer |err| recordDispatchError(self, "app_start", err);
213
+ launch_timing.lap("app_start");
214
+ try reservePrimaryStartupWindow(self);
215
+ try app.start(self);
216
+ if (self.options.extensions) |registry| try registry.startAll(extensionContext(self));
217
+ try dispatchEvent(self, app, .{ .lifecycle = .start });
218
+ launch_timing.lap("app_started");
219
+ if (try app.scene()) |scene| {
220
+ try loadScene(self, app, scene);
221
+ } else {
222
+ try loadStartupWindows(self, app);
223
+ }
224
+ launch_timing.lap("scene_loaded");
225
+ self.invalidateFor(.startup, null);
226
+ log(self, "app.start", "app started", &.{trace.string("app", app.name)});
227
+ },
228
+ .app_activated => {
229
+ try dispatchEvent(self, app, .{ .lifecycle = .activate });
230
+ emitAppLifecycleEvent(self, "app:activate") catch |err| log(self, "app.activate.emit_failed", @errorName(err), &.{});
231
+ },
232
+ .app_deactivated => {
233
+ try dispatchEvent(self, app, .{ .lifecycle = .deactivate });
234
+ emitAppLifecycleEvent(self, "app:deactivate") catch |err| log(self, "app.deactivate.emit_failed", @errorName(err), &.{});
235
+ },
236
+ .appearance_changed => |appearance| {
237
+ self.appearance = appearance;
238
+ // Appearance flips re-resolve theme typography (and a
239
+ // host may re-resolve its fonts with it): cached
240
+ // advance batches and retained wrap results must miss
241
+ // rather than serve metrics measured under the
242
+ // previous appearance.
243
+ canvas.bumpTextMeasureGeneration();
244
+ try dispatchEvent(self, app, .{ .appearance_changed = appearance });
245
+ },
246
+ .surface_resized => |surface_value| {
247
+ self.surface = surface_value;
248
+ if (WindowViewMethods().findWindowIndexById(self, surface_value.id)) |index| {
249
+ self.windows[index].info.frame.width = surface_value.size.width;
250
+ self.windows[index].info.frame.height = surface_value.size.height;
251
+ self.windows[index].info.scale_factor = surface_value.scale_factor;
252
+ }
253
+ WindowViewMethods().relayoutShellViews(self, surface_value.id) catch |err| log(self, "shell.relayout_failed", @errorName(err), &.{trace.uint("window_id", surface_value.id)});
254
+ var detail_buffer: [512]u8 = undefined;
255
+ var detail_writer = std.Io.Writer.fixed(&detail_buffer);
256
+ 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}}}}}", .{
257
+ surface_value.size.width,
258
+ surface_value.size.height,
259
+ surface_value.scale_factor,
260
+ surface_value.safe_area_insets.top,
261
+ surface_value.safe_area_insets.right,
262
+ surface_value.safe_area_insets.bottom,
263
+ surface_value.safe_area_insets.left,
264
+ surface_value.keyboard_insets.top,
265
+ surface_value.keyboard_insets.right,
266
+ surface_value.keyboard_insets.bottom,
267
+ surface_value.keyboard_insets.left,
268
+ });
269
+ emitWindowEvent(self, surface_value.id, "resize", detail_writer.buffered()) catch |err| log(self, "window.resize.emit_failed", @errorName(err), &.{});
270
+ self.invalidateFor(.surface_resize, geometry.RectF.fromSize(surface_value.size));
271
+ const fields = [_]trace.Field{
272
+ trace.float("width", surface_value.size.width),
273
+ trace.float("height", surface_value.size.height),
274
+ trace.float("scale", surface_value.scale_factor),
275
+ };
276
+ log(self, "surface.resize", "surface updated", &fields);
277
+ },
278
+ .window_frame_changed => |state| {
279
+ // A user (or host) close arrives as open=false on a
280
+ // window the runtime knew as open; a close the app
281
+ // itself made through `closeWindow` already flipped
282
+ // the flag, so the echo never re-fires. Capture the
283
+ // transition BEFORE the update.
284
+ const was_open = if (WindowViewMethods().findWindowIndexById(self, state.id)) |index| self.windows[index].info.open else false;
285
+ WindowViewMethods().updateWindowState(self, state) catch |err| log(self, "window.state.update_failed", @errorName(err), &.{trace.string("label", state.label)});
286
+ WindowViewMethods().relayoutShellViews(self, state.id) catch |err| log(self, "shell.relayout_failed", @errorName(err), &.{trace.uint("window_id", state.id)});
287
+ if (self.options.window_state_store) |store| {
288
+ store.saveWindow(WindowViewMethods().runtimeWindowStateForPersistence(self, state)) catch |err| log(self, "window.state.save_failed", @errorName(err), &.{trace.string("label", state.label)});
289
+ }
290
+ log(self, "window.frame", "window frame updated", &.{
291
+ trace.string("label", state.label),
292
+ trace.float("x", state.frame.x),
293
+ trace.float("y", state.frame.y),
294
+ trace.float("width", state.frame.width),
295
+ trace.float("height", state.frame.height),
296
+ });
297
+ if (was_open and !state.open) {
298
+ // The model owns the consequence (the dismissal
299
+ // precedent): the app maps this to a Msg and its
300
+ // next declared window set is truth. The label
301
+ // comes from runtime storage, which outlives the
302
+ // event's transient slices.
303
+ const label = if (WindowViewMethods().findWindowIndexById(self, state.id)) |index| self.windows[index].info.label else state.label;
304
+ try dispatchEvent(self, app, .{ .window_closed = .{ .window_id = state.id, .label = label } });
305
+ }
306
+ },
307
+ .window_focused => |window_id| {
308
+ if (WindowViewMethods().findWindowIndexById(self, window_id)) |index| WindowViewMethods().setFocusedIndex(self, index);
309
+ self.invalidated = true;
310
+ },
311
+ .frame_requested => try frame(self, app),
312
+ .bridge_message => |message| try handleBridgeMessage(self, app, message),
313
+ .tray_action => |item_id| {
314
+ log(self, "tray.action", "tray item selected", &.{trace.uint("item_id", item_id)});
315
+ try dispatchCommand(self, app, .{
316
+ .name = SystemServiceMethods().trayCommandNameForItem(self, item_id),
317
+ .source = .tray,
318
+ .tray_item_id = item_id,
319
+ });
320
+ },
321
+ .shortcut => |shortcut| {
322
+ try dispatchCommand(self, app, .{
323
+ .name = shortcut.id,
324
+ .source = .shortcut,
325
+ .window_id = shortcut.window_id,
326
+ });
327
+ try dispatchEvent(self, app, .{ .shortcut = shortcut });
328
+ emitShortcutEvent(self, shortcut) catch |err| log(self, "shortcut.emit_failed", @errorName(err), &.{trace.string("id", shortcut.id)});
329
+ self.invalidateFor(.command, null);
330
+ },
331
+ .native_command => |command| {
332
+ try dispatchCommand(self, app, .{
333
+ .name = command.name,
334
+ .source = WindowViewMethods().commandSourceForNativeView(self, command.window_id, command.view_label),
335
+ .window_id = command.window_id,
336
+ .view_label = command.view_label,
337
+ });
338
+ },
339
+ // The interactive-surface family below degrades on error
340
+ // instead of propagating: an error that escapes
341
+ // `dispatchPlatformEvent` reaches the platform callback,
342
+ // latches its failure flag, and exits the whole app — so a
343
+ // runtime-side capacity or render fault on a keystroke,
344
+ // click, scroll, resize, or frame tick must land in the
345
+ // dispatch-error ring (loud, queryable, traced at `.err`)
346
+ // while the app keeps running. The failing interaction is
347
+ // refused; the next one starts clean. The TestHarness's
348
+ // `.propagate` policy still returns the error so tests
349
+ // fail loud instead of leaving silent stale frames.
350
+ .gpu_surface_frame => |frame_event| GpuSurfaceEventMethods().dispatchGpuSurfaceFrame(self, app, frame_event) catch |err| {
351
+ recordDispatchError(self, "gpu_surface_frame", err);
352
+ if (self.dispatch_error_policy == .propagate) return err;
353
+ },
354
+ .gpu_surface_resized => |resize_event| {
355
+ GpuSurfaceEventMethods().dispatchGpuSurfaceResized(self, app, resize_event) catch |err| {
356
+ recordDispatchError(self, "gpu_surface_resized", err);
357
+ if (self.dispatch_error_policy == .propagate) return err;
358
+ };
359
+ log(self, "gpu_surface.resize", "gpu surface resized", &.{
360
+ trace.string("label", resize_event.label),
361
+ trace.float("width", resize_event.frame.width),
362
+ trace.float("height", resize_event.frame.height),
363
+ trace.float("scale", resize_event.scale_factor),
364
+ });
365
+ },
366
+ .gpu_surface_input => |input_event| GpuSurfaceEventMethods().dispatchGpuSurfaceInput(self, app, input_event) catch |err| {
367
+ recordDispatchError(self, "gpu_surface_input", err);
368
+ if (self.dispatch_error_policy == .propagate) return err;
369
+ },
370
+ .gpu_surface_scroll_driver => |driver_event| ScrollDriverMethods().dispatchGpuSurfaceScrollDriver(self, app, driver_event) catch |err| {
371
+ recordDispatchError(self, "gpu_surface_scroll_driver", err);
372
+ if (self.dispatch_error_policy == .propagate) return err;
373
+ },
374
+ .context_menu_action => |action_event| ContextMenuMethods().dispatchContextMenuAction(self, app, action_event) catch |err| {
375
+ recordDispatchError(self, "context_menu_action", err);
376
+ if (self.dispatch_error_policy == .propagate) return err;
377
+ },
378
+ .widget_accessibility_action => |action_event| {
379
+ _ = self.dispatchCanvasWidgetAccessibilityAction(app, action_event.window_id, action_event.label, .{
380
+ .id = action_event.id,
381
+ .action = canvasWidgetAccessibilityActionKindFromPlatform(action_event.action),
382
+ .text = action_event.text,
383
+ .selection = if (action_event.selection) |selection| .{ .anchor = selection.start, .focus = selection.end } else null,
384
+ }) catch |err| {
385
+ recordDispatchError(self, "widget_accessibility_action", err);
386
+ if (self.dispatch_error_policy == .propagate) return err;
387
+ };
388
+ },
389
+ .menu_command => |command| {
390
+ try dispatchCommand(self, app, .{
391
+ .name = command.name,
392
+ .source = .menu,
393
+ .window_id = command.window_id,
394
+ });
395
+ },
396
+ .timer => |timer_event| {
397
+ try dispatchEvent(self, app, .{ .timer = timer_event });
398
+ },
399
+ .audio => |audio_event| {
400
+ try dispatchEvent(self, app, .{ .audio = audio_event });
401
+ },
402
+ .wake => {
403
+ try dispatchEvent(self, app, .effects_wake);
404
+ },
405
+ .files_dropped => |drop| {
406
+ const widget_drop_event = self.routeCanvasWidgetFileDrop(drop, &self.widget_event_route_entries) catch |err| switch (err) {
407
+ error.WindowNotFound,
408
+ error.ViewNotFound,
409
+ error.InvalidViewOptions,
410
+ => null,
411
+ else => return err,
412
+ };
413
+ if (widget_drop_event) |drop_event| {
414
+ try dispatchEvent(self, app, .{ .canvas_widget_file_drop = drop_event });
415
+ }
416
+ try dispatchEvent(self, app, .{ .files_dropped = drop });
417
+ emitFileDropEvent(self, drop) catch |err| log(self, "drop.files.emit_failed", @errorName(err), &.{trace.uint("window_id", drop.window_id)});
418
+ self.invalidateFor(.command, null);
419
+ },
420
+ .app_shutdown => {
421
+ try dispatchEvent(self, app, .{ .lifecycle = .stop });
422
+ if (self.options.extensions) |registry| try registry.stopAll(extensionContext(self));
423
+ // Marked delivered BEFORE the call: if the hook itself
424
+ // errors, the run loop's exit path must not invoke it a
425
+ // second time (the hook contract is exactly-once).
426
+ self.app_stop_delivered = true;
427
+ try app.stop(self);
428
+ log(self, "app.stop", "app stopped", &.{trace.string("app", app.name)});
429
+ },
430
+ }
431
+ }
432
+
433
+ pub fn dispatchEvent(self: *Runtime, app: App, event_value: Event) anyerror!void {
434
+ const event_fields = [_]trace.Field{trace.string("event", event_value.name())};
435
+ log(self, "runtime.event", null, &event_fields);
436
+ // A handler/update error degrades — recorded and observable,
437
+ // never fatal. Propagating it would reach the platform
438
+ // callback, set `failed`, and exit the whole app. The tag
439
+ // name (not `Event.name()`, which for commands aliases
440
+ // transient command-name storage) keeps ring records static.
441
+ // Under the TestHarness's `.propagate` policy the recorded
442
+ // error additionally returns, so capacity errors fail tests
443
+ // instead of leaving silent stale frames.
444
+ app.event(self, event_value) catch |err| {
445
+ recordDispatchError(self, @tagName(event_value), err);
446
+ if (self.dispatch_error_policy == .propagate) return err;
447
+ };
448
+
449
+ switch (event_value) {
450
+ .command => {
451
+ if (self.options.extensions) |registry| {
452
+ registry.dispatchCommand(extensionContext(self), .{ .name = event_value.command.name }) catch |err| {
453
+ recordDispatchError(self, "extension.command", err);
454
+ };
455
+ }
456
+ self.invalidateFor(.command, null);
457
+ },
458
+ .shortcut => {
459
+ self.invalidateFor(.command, null);
460
+ },
461
+ .appearance_changed => {
462
+ self.invalidateFor(.state, null);
463
+ },
464
+ .timer => {},
465
+ .effects_wake => {},
466
+ .audio => {},
467
+ .files_dropped => {},
468
+ .gpu_surface_frame => {},
469
+ .gpu_surface_resized => {},
470
+ .gpu_surface_input => {},
471
+ .canvas_widget_pointer => {},
472
+ .canvas_widget_keyboard => {},
473
+ .canvas_widget_scroll => {},
474
+ .canvas_widget_file_drop => {},
475
+ .canvas_widget_drag => {},
476
+ .canvas_widget_context_menu => {
477
+ self.invalidateFor(.command, null);
478
+ },
479
+ .canvas_widget_context_menu_request => {
480
+ // The app loop answers by mounting the anchored
481
+ // fallback surface: a visual change.
482
+ self.invalidateFor(.command, null);
483
+ },
484
+ .canvas_widget_dismiss => {},
485
+ .canvas_widget_context_press => {},
486
+ .canvas_widget_resize => {},
487
+ .canvas_widget_change => {},
488
+ .window_closed => {
489
+ self.invalidateFor(.state, null);
490
+ },
491
+ .automation_provenance => {},
492
+ .lifecycle => {},
493
+ }
494
+ }
495
+
496
+ pub fn dispatchCommand(self: *Runtime, app: App, command: CommandEvent) anyerror!void {
497
+ try validateCommandName(command.name);
498
+ try dispatchEvent(self, app, .{ .command = command });
499
+ }
500
+
501
+ pub fn frame(self: *Runtime, app: App) anyerror!void {
502
+ const start_ns = nowNanoseconds();
503
+ try consumeAutomationCommand(self, app);
504
+ if (!self.invalidated) return;
505
+
506
+ try publishAutomation(self);
507
+ self.frame_index += 1;
508
+ self.last_diagnostics = .{
509
+ .frame_index = self.frame_index,
510
+ .command_count = self.command_count,
511
+ .dirty_region_count = self.dirty_region_count,
512
+ .resource_upload_count = 0,
513
+ .duration_ns = @intCast(@max(0, nowNanoseconds() - start_ns)),
514
+ };
515
+ self.command_count = 0;
516
+ self.dirty_region_count = 0;
517
+ self.invalidated = false;
518
+ log(self, "runtime.frame", "frame published", &.{
519
+ trace.uint("frame", self.frame_index),
520
+ trace.uint("dirty_regions", self.last_diagnostics.dirty_region_count),
521
+ });
522
+ app.event(self, .{ .lifecycle = .frame }) catch |err| {
523
+ recordDispatchError(self, "lifecycle", err);
524
+ if (self.dispatch_error_policy == .propagate) return err;
525
+ };
526
+ }
527
+
528
+ fn AutomationSnapshotMethods() type {
529
+ return runtime_automation_snapshot.RuntimeAutomationSnapshot(Runtime);
530
+ }
531
+
532
+ pub fn automationSnapshot(self: *Runtime, title: []const u8) automation.snapshot.Input {
533
+ return AutomationSnapshotMethods().automationSnapshot(self, title);
534
+ }
535
+
536
+ pub fn dispatchAutomationCommand(self: *Runtime, app: App, line: []const u8) anyerror!void {
537
+ try dispatchAutomationProtocolCommand(self, app, try automation.protocol.Command.parse(line));
538
+ }
539
+
540
+ pub fn frameDiagnostics(self: *Runtime) FrameDiagnostics {
541
+ return AutomationSnapshotMethods().frameDiagnostics(self);
542
+ }
543
+
544
+ pub fn supports(self: *const Runtime, feature: platform.PlatformFeature) bool {
545
+ return self.options.platform.supports(feature);
546
+ }
547
+
548
+ fn handlePlatformEvent(context: *anyopaque, event_value: platform.Event) anyerror!void {
549
+ const run_context: *RunContext = @ptrCast(@alignCast(context));
550
+ try run_context.runtime.dispatchPlatformEvent(run_context.app, event_value);
551
+ }
552
+
553
+ fn loadStartupWindows(self: *Runtime, app: App) anyerror!void {
554
+ const source = try WindowViewMethods().copyLoadedSource(self, try app.webViewSource());
555
+ self.loaded_source = source;
556
+ const app_info = self.options.platform.app_info;
557
+ const count = app_info.startupWindowCount();
558
+ var index: usize = 0;
559
+ while (index < count) : (index += 1) {
560
+ const window = app_info.resolvedStartupWindow(index);
561
+ const runtime_index = if (WindowViewMethods().findWindowIndexById(self, window.id)) |runtime_index| blk: {
562
+ self.windows[runtime_index].source = try WindowViewMethods().copySource(self, runtime_index, source);
563
+ break :blk runtime_index;
564
+ } else blk: {
565
+ const runtime_index = try WindowViewMethods().reserveWindow(self, window.id, window.label, window.resolvedTitle(app_info.app_name), source, true);
566
+ self.windows[runtime_index].info.frame = window.default_frame;
567
+ self.windows[runtime_index].main_frame = geometry.RectF.init(0, 0, window.default_frame.width, window.default_frame.height);
568
+ break :blk runtime_index;
569
+ };
570
+ self.windows[runtime_index].source_reloads_from_app = true;
571
+ if (index > 0) {
572
+ _ = try self.options.platform.services.createWindow(window);
573
+ }
574
+ try self.options.platform.services.loadWindowWebView(window.id, self.windows[runtime_index].source.?);
575
+ try applyMainWebViewState(self, window.id);
576
+ self.next_window_id = @max(self.next_window_id, window.id + 1);
577
+ }
578
+ log(self, "webview.load", "loaded webview source", &.{
579
+ trace.string("kind", @tagName(source.kind)),
580
+ trace.uint("bytes", source.bytes.len),
581
+ });
582
+ }
583
+
584
+ fn loadScene(self: *Runtime, app: App, scene: app_manifest.ShellConfig) anyerror!void {
585
+ try app_manifest.validateShell(scene, &.{});
586
+ if (scene.windows.len == 0) {
587
+ log(self, "scene.load", "loaded empty app scene", &.{trace.string("app", app.name)});
588
+ return;
589
+ }
590
+
591
+ const source = if (sceneNeedsMainWebView(scene) or !appUsesDefaultEmptyWebViewSource(App, app))
592
+ try WindowViewMethods().copyLoadedSource(self, try app.webViewSource())
593
+ else
594
+ null;
595
+ self.loaded_source = source;
596
+
597
+ try loadStartupSceneWindow(self, scene.windows[0], source);
598
+ for (scene.windows[1..]) |window| {
599
+ _ = try WindowViewMethods().createShellWindowWithSourceMode(self, window, source, source != null);
600
+ }
601
+
602
+ log(self, "scene.load", "loaded app scene", &.{
603
+ trace.string("app", app.name),
604
+ trace.uint("windows", scene.windows.len),
605
+ });
606
+ }
607
+
608
+ fn loadStartupSceneWindow(self: *Runtime, shell_window: app_manifest.ShellWindow, source: ?platform.WebViewSource) anyerror!void {
609
+ const app_info = self.options.platform.app_info;
610
+ const startup_window = app_info.resolvedStartupWindow(0);
611
+ const window_id = startup_window.id;
612
+ const manifest_frame = geometry.RectF.init(
613
+ shell_window.x orelse 0,
614
+ shell_window.y orelse 0,
615
+ shell_window.width,
616
+ shell_window.height,
617
+ );
618
+ const startup_frame = WindowViewMethods().startupWindowFrame(startup_window.default_frame, manifest_frame);
619
+
620
+ const runtime_index = if (WindowViewMethods().findWindowIndexById(self, window_id)) |index| index else try WindowViewMethods().reserveWindow(
621
+ self,
622
+ window_id,
623
+ shell_window.label,
624
+ shell_window.title orelse app_info.resolvedWindowTitle(),
625
+ null,
626
+ true,
627
+ );
628
+ if (WindowViewMethods().findWindowIndexByLabel(self, shell_window.label)) |label_index| {
629
+ if (label_index != runtime_index) return error.DuplicateWindowLabel;
630
+ }
631
+
632
+ self.windows[runtime_index].info.label = try copyInto(&self.windows[runtime_index].label_storage, shell_window.label);
633
+ self.windows[runtime_index].info.title = try copyInto(&self.windows[runtime_index].title_storage, shell_window.title orelse app_info.resolvedWindowTitle());
634
+ self.windows[runtime_index].info.frame = startup_frame;
635
+ self.windows[runtime_index].source = if (source) |source_value| try WindowViewMethods().copySource(self, runtime_index, source_value) else null;
636
+ self.windows[runtime_index].source_reloads_from_app = source != null;
637
+ if (!self.windows[runtime_index].main_frame_set) {
638
+ self.windows[runtime_index].main_frame = geometry.RectF.init(0, 0, startup_frame.width, startup_frame.height);
639
+ }
640
+ self.next_window_id = @max(self.next_window_id, window_id + 1);
641
+
642
+ if (self.windows[runtime_index].source) |window_source| {
643
+ try self.options.platform.services.loadWindowWebView(window_id, window_source);
644
+ try applyMainWebViewState(self, window_id);
645
+ }
646
+ try WindowViewMethods().createShellViews(self, window_id, shell_window.views, WindowViewMethods().shellBoundsForWindow(self, window_id));
647
+ }
648
+
649
+ fn applyMainWebViewState(self: *Runtime, window_id: platform.WindowId) anyerror!void {
650
+ const window_index = WindowViewMethods().findWindowIndexById(self, window_id) orelse return error.WindowNotFound;
651
+ const window = self.windows[window_index];
652
+ if (window.main_frame_set) {
653
+ try self.options.platform.services.setWebViewFrame(window_id, "main", window.main_frame);
654
+ }
655
+ if (window.main_layer != 0) {
656
+ try self.options.platform.services.setWebViewLayer(window_id, "main", window.main_layer);
657
+ }
658
+ if (window.main_zoom != 1.0) {
659
+ try self.options.platform.services.setWebViewZoom(window_id, "main", window.main_zoom);
660
+ }
661
+ }
662
+
663
+ fn loadWebView(self: *Runtime, app: App) anyerror!void {
664
+ const source = try WindowViewMethods().copyLoadedSource(self, try app.webViewSource());
665
+ self.loaded_source = source;
666
+ try self.options.platform.services.loadWindowWebView(1, source);
667
+ }
668
+
669
+ pub fn reloadWindows(self: *Runtime, app: App) anyerror!void {
670
+ const source = try WindowViewMethods().copyLoadedSource(self, try app.webViewSource());
671
+ self.loaded_source = source;
672
+ if (self.window_count == 0) {
673
+ try self.options.platform.services.loadWindowWebView(1, source);
674
+ return;
675
+ }
676
+ for (self.windows[0..self.window_count], 0..) |*window, index| {
677
+ if (window.source == null or window.source_reloads_from_app) {
678
+ window.source = try WindowViewMethods().copySource(self, index, source);
679
+ }
680
+ const window_source = window.source orelse source;
681
+ try self.options.platform.services.loadWindowWebView(window.info.id, window_source);
682
+ }
683
+ }
684
+
685
+ fn handleBridgeMessage(self: *Runtime, app: App, message: platform.BridgeMessage) anyerror!void {
686
+ self.command_count += 1;
687
+ if (try handleBuiltinBridgeMessage(self, app, message)) return;
688
+ var dispatcher = self.options.bridge orelse bridge.Dispatcher{};
689
+ if (self.options.security.permissions.len > 0) dispatcher.policy.permissions = self.options.security.permissions;
690
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
691
+ if (try handleAsyncBridgeMessage(self, dispatcher, message)) {
692
+ self.invalidateFor(.command, null);
693
+ return;
694
+ }
695
+ const response = dispatcher.dispatch(message.bytes, .{ .origin = message.origin, .window_id = message.window_id, .webview_label = message.webview_label }, &response_buffer);
696
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
697
+ self.invalidateFor(.command, null);
698
+ log(self, "bridge.dispatch", "bridge request handled", &.{
699
+ trace.uint("request_bytes", message.bytes.len),
700
+ trace.uint("response_bytes", response.len),
701
+ });
702
+ }
703
+
704
+ fn handleAsyncBridgeMessage(self: *Runtime, dispatcher: bridge.Dispatcher, message: platform.BridgeMessage) anyerror!bool {
705
+ const request = bridge.parseRequest(message.bytes) catch return false;
706
+ const handler = dispatcher.async_registry.find(request.command) orelse return false;
707
+ if (!dispatcher.policy.allows(request.command, message.origin)) {
708
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
709
+ const response = bridge.writeErrorResponse(&response_buffer, request.id, .permission_denied, "Bridge command is not permitted");
710
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
711
+ return true;
712
+ }
713
+ const source_slot = reserveAsyncBridgeResponse(self, .{
714
+ .origin = message.origin,
715
+ .window_id = message.window_id,
716
+ .webview_label = message.webview_label,
717
+ }) catch |err| {
718
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
719
+ const response = bridge.writeErrorResponse(&response_buffer, request.id, .internal_error, @errorName(err));
720
+ try completeBridgeResponse(self, message.window_id, message.webview_label, response);
721
+ return true;
722
+ };
723
+ errdefer source_slot.release();
724
+ try handler.invoke_fn(handler.context, .{
725
+ .request = request,
726
+ .source = source_slot.source,
727
+ }, .{
728
+ .context = source_slot,
729
+ .source = source_slot.source,
730
+ .respond_fn = asyncBridgeRespond,
731
+ });
732
+ return true;
733
+ }
734
+
735
+ fn asyncBridgeRespond(context: *anyopaque, source: bridge.Source, response: []const u8) anyerror!void {
736
+ _ = source;
737
+ const slot: *AsyncBridgeResponseSlot = @ptrCast(@alignCast(context));
738
+ try slot.respond(response);
739
+ }
740
+
741
+ fn reserveAsyncBridgeResponse(self: *Runtime, source: bridge.Source) !*AsyncBridgeResponseSlot {
742
+ for (&self.async_bridge_responses) |*slot| {
743
+ if (slot.in_use) continue;
744
+ try slot.init(self, source);
745
+ return slot;
746
+ }
747
+ return error.AsyncBridgeResponseLimitReached;
748
+ }
749
+
750
+ fn publishAutomation(self: *Runtime) anyerror!void {
751
+ const server = self.options.automation orelse return;
752
+ try server.publish(automationSnapshot(self, server.title));
753
+ }
754
+
755
+ fn consumeAutomationCommand(self: *Runtime, app: App) anyerror!void {
756
+ const server = self.options.automation orelse return;
757
+ var buffer: [automation.protocol.max_command_bytes]u8 = undefined;
758
+ // Automation command errors ALWAYS degrade, regardless of
759
+ // `dispatch_error_policy`: a stale widget target or a
760
+ // malformed command is driver misuse, not an app fault —
761
+ // propagating would escape the frame_requested platform
762
+ // callback and kill the whole app under test, and the
763
+ // TestHarness's `.propagate` policy is for app errors. The
764
+ // record invalidates state, so the next published snapshot
765
+ // carries the error where the driver can see it.
766
+ const command = (server.takeCommand(&buffer) catch |err| {
767
+ recordDispatchError(self, "automation.command", err);
768
+ return;
769
+ }) orelse return;
770
+ dispatchAutomationProtocolCommand(self, app, command) catch |err| {
771
+ recordDispatchErrorDetail(self, automationCommandEventName(command.action), err, command.value);
772
+ };
773
+ }
774
+
775
+ /// Stable static event names for degraded automation command
776
+ /// errors — one per widget action, a generic fallback for
777
+ /// the rest (parse errors included).
778
+ fn automationCommandEventName(action: automation.protocol.Action) []const u8 {
779
+ return switch (action) {
780
+ .widget_click => "automation.widget_click",
781
+ .widget_hold => "automation.widget_hold",
782
+ .widget_context_press => "automation.widget_context_press",
783
+ .widget_context_menu => "automation.widget_context_menu",
784
+ .widget_action => "automation.widget_action",
785
+ .widget_drag => "automation.widget_drag",
786
+ .widget_wheel => "automation.widget_wheel",
787
+ .widget_key => "automation.widget_key",
788
+ .tray_action => "automation.tray_action",
789
+ .provenance => "automation.provenance",
790
+ else => "automation.command",
791
+ };
792
+ }
793
+
794
+ fn dispatchAutomationProtocolCommand(self: *Runtime, app: App, command: automation.protocol.Command) anyerror!void {
795
+ switch (command.action) {
796
+ .reload => {
797
+ self.command_count += 1;
798
+ try reloadWindows(self, app);
799
+ self.invalidateFor(.command, null);
800
+ },
801
+ .bridge => {
802
+ try handleBridgeMessage(self, app, .{ .bytes = command.value, .origin = "zero://inline", .window_id = 1, .webview_label = "main" });
803
+ },
804
+ .resize => {
805
+ const parsed = try parseAutomationResizeCommand(command.value);
806
+ try dispatchPlatformEvent(self, app, .{ .surface_resized = .{
807
+ .id = 1,
808
+ .size = geometry.SizeF.init(parsed.width, parsed.height),
809
+ .scale_factor = parsed.scale_factor,
810
+ } });
811
+ },
812
+ .screenshot => {
813
+ publishAutomationScreenshot(self, command.value) catch |err| {
814
+ log(self, "automation.screenshot_failed", @errorName(err), &.{});
815
+ };
816
+ },
817
+ .native_command => {
818
+ const parsed = try parseAutomationNativeCommand(command.value);
819
+ try dispatchPlatformEvent(self, app, .{ .native_command = .{
820
+ .name = parsed.name,
821
+ .window_id = 1,
822
+ .view_label = parsed.view_label,
823
+ } });
824
+ },
825
+ .widget_action => {
826
+ try AutomationWidgetMethods().dispatchAutomationWidgetAction(self, app, try parseAutomationWidgetAction(command.value));
827
+ },
828
+ .widget_click => {
829
+ try AutomationWidgetMethods().dispatchAutomationWidgetClick(self, app, try parseAutomationWidgetTarget(command.value));
830
+ },
831
+ .widget_hold => {
832
+ try AutomationWidgetMethods().dispatchAutomationWidgetHold(self, app, try parseAutomationWidgetTarget(command.value));
833
+ },
834
+ .widget_context_press => {
835
+ try AutomationWidgetMethods().dispatchAutomationWidgetContextPress(self, app, try parseAutomationWidgetTarget(command.value));
836
+ },
837
+ .widget_context_menu => {
838
+ try AutomationWidgetMethods().dispatchAutomationWidgetContextMenuItem(self, app, try parseAutomationWidgetContextMenuItem(command.value));
839
+ },
840
+ .widget_drag => {
841
+ try AutomationWidgetMethods().dispatchAutomationWidgetPointerDrag(self, app, try parseAutomationWidgetPointerDrag(command.value));
842
+ },
843
+ .widget_wheel => {
844
+ try AutomationWidgetMethods().dispatchAutomationWidgetWheel(self, app, try parseAutomationWidgetWheel(command.value));
845
+ },
846
+ .widget_key => {
847
+ try AutomationWidgetMethods().dispatchAutomationWidgetKeyInput(self, app, try parseAutomationWidgetKey(command.value));
848
+ },
849
+ .menu_command => {
850
+ try dispatchPlatformEvent(self, app, .{ .menu_command = .{
851
+ .name = try parseAutomationCommandName(command.value),
852
+ .window_id = 1,
853
+ } });
854
+ },
855
+ .shortcut => {
856
+ try dispatchPlatformEvent(self, app, .{ .shortcut = .{
857
+ .id = try parseAutomationCommandName(command.value),
858
+ .key = "",
859
+ .window_id = 1,
860
+ } });
861
+ },
862
+ .tray_action => {
863
+ // Drive a status-item dropdown row through the
864
+ // SAME platform event a real NSStatusItem menu click
865
+ // emits, so command resolution, `.tray` source, and
866
+ // UiApp's window fallback are all the real path. A
867
+ // stale or unknown item id is loud driver misuse,
868
+ // like widget-click on an unmounted widget.
869
+ const item_id = try parseAutomationTrayItemId(command.value);
870
+ if (!self.tray_created or !SystemServiceMethods().trayItemExists(self, item_id)) return error.InvalidCommand;
871
+ try dispatchPlatformEvent(self, app, .{ .tray_action = item_id });
872
+ },
873
+ .focus_view => {
874
+ try WindowViewMethods().focusView(self, 1, try parseAutomationViewLabel(command.value));
875
+ },
876
+ .focus_next_view => {
877
+ _ = try WindowViewMethods().focusNextView(self, 1);
878
+ },
879
+ .focus_previous_view => {
880
+ _ = try WindowViewMethods().focusPreviousView(self, 1);
881
+ },
882
+ .profile => {
883
+ // Toggle per-stage frame timing. Turning it on
884
+ // starts a fresh window (stale samples from an
885
+ // earlier session would skew the percentiles);
886
+ // turning it off stops recording and drops the
887
+ // snapshot's `frame_profile` line.
888
+ self.command_count += 1;
889
+ const enable = std.mem.eql(u8, command.value, "on");
890
+ if (!enable and !std.mem.eql(u8, command.value, "off")) return error.InvalidCommand;
891
+ if (enable and !self.frame_profile.enabled) self.frame_profile.reset();
892
+ self.frame_profile.enabled = enable;
893
+ self.invalidateFor(.command, null);
894
+ },
895
+ .provenance => {
896
+ try AutomationWidgetMethods().dispatchAutomationProvenance(self, app, try parseAutomationProvenanceTarget(command.value));
897
+ },
898
+ .wait => {},
899
+ }
900
+ }
901
+
902
+ /// Render the named gpu_surface view's current canvas frame through
903
+ /// the deterministic reference renderer and publish it as a PNG
904
+ /// (`screenshot-<label>.png`) in the automation directory. The
905
+ /// screenshot renders at scale 1 unless the command carries an
906
+ /// explicit scale, so an unchanged scene produces byte-identical
907
+ /// artifacts across captures.
908
+ pub fn publishAutomationScreenshot(self: *Runtime, value: []const u8) anyerror!void {
909
+ const server = self.options.automation orelse return;
910
+ const parsed = try parseAutomationScreenshotCommand(value);
911
+ // Screenshots address a gpu_surface view by label across ALL
912
+ // open windows, like the widget verbs — a secondary window's
913
+ // canvas captures the same way the main one does.
914
+ const view_index = try AutomationWidgetMethods().automationGpuSurfaceViewIndexByLabel(self, parsed.view_label);
915
+ const window_id = self.views[view_index].window_id;
916
+ const allocator = std.heap.page_allocator;
917
+ const pixel_size = try self.canvasScreenshotPixelSize(window_id, parsed.view_label, parsed.scale);
918
+ const pixels = try allocator.alloc(u8, pixel_size.byte_len);
919
+ defer allocator.free(pixels);
920
+ const scratch = try allocator.alloc(u8, pixel_size.byte_len);
921
+ defer allocator.free(scratch);
922
+ const screenshot = try self.renderCanvasScreenshot(window_id, parsed.view_label, parsed.scale, pixels, scratch);
923
+ var writer = try std.Io.Writer.Allocating.initCapacity(
924
+ allocator,
925
+ try canvas.png.encodedRgba8ByteLen(screenshot.width, screenshot.height),
926
+ );
927
+ defer writer.deinit();
928
+ try canvas.png.writeRgba8(&writer.writer, screenshot.width, screenshot.height, screenshot.rgba8);
929
+ try server.publishScreenshot(parsed.view_label, writer.written());
930
+ // A screenshot taken during a recorded session marks a pixel
931
+ // checkpoint: replay re-renders the same view at the same
932
+ // scale through the same deterministic reference renderer
933
+ // and compares hashes.
934
+ if (self.options.session_recorder) |recorder| {
935
+ recorder.recordScreenshot(
936
+ parsed.view_label,
937
+ parsed.scale orelse 1,
938
+ std.hash.Wyhash.hash(0, writer.written()),
939
+ writer.written().len,
940
+ );
941
+ }
942
+ log(self, "automation.screenshot", "screenshot published", &.{
943
+ trace.string("view", parsed.view_label),
944
+ trace.uint("width", screenshot.width),
945
+ trace.uint("height", screenshot.height),
946
+ trace.uint("bytes", writer.written().len),
947
+ });
948
+ }
949
+
950
+ const BuiltinBridgeMethods = runtime_builtin_bridge.RuntimeBuiltinBridge(Runtime);
951
+ const allowsBuiltinBridgeCommand = BuiltinBridgeMethods.allowsBuiltinBridgeCommand;
952
+ const dispatchCommandBridgeCommand = BuiltinBridgeMethods.dispatchCommandBridgeCommand;
953
+ const dispatchPlatformBridgeCommand = BuiltinBridgeMethods.dispatchPlatformBridgeCommand;
954
+ const dispatchWindowBridgeCommand = BuiltinBridgeMethods.dispatchWindowBridgeCommand;
955
+ const invokeCommandFromJson = BuiltinBridgeMethods.invokeCommandFromJson;
956
+ const writeCommandListJson = BuiltinBridgeMethods.writeCommandListJson;
957
+ const dispatchViewBridgeCommand = BuiltinBridgeMethods.dispatchViewBridgeCommand;
958
+ const dispatchWebViewBridgeCommand = BuiltinBridgeMethods.dispatchWebViewBridgeCommand;
959
+ const dispatchDialogBridgeCommand = BuiltinBridgeMethods.dispatchDialogBridgeCommand;
960
+ const dispatchOsBridgeCommand = BuiltinBridgeMethods.dispatchOsBridgeCommand;
961
+ const dispatchCredentialBridgeCommand = BuiltinBridgeMethods.dispatchCredentialBridgeCommand;
962
+ const dispatchClipboardBridgeCommand = BuiltinBridgeMethods.dispatchClipboardBridgeCommand;
963
+ const createWindowFromJson = BuiltinBridgeMethods.createWindowFromJson;
964
+ const createViewFromJson = BuiltinBridgeMethods.createViewFromJson;
965
+ const updateViewFromJson = BuiltinBridgeMethods.updateViewFromJson;
966
+ const setViewFrameFromJson = BuiltinBridgeMethods.setViewFrameFromJson;
967
+ const setViewVisibleFromJson = BuiltinBridgeMethods.setViewVisibleFromJson;
968
+ const focusViewFromJson = BuiltinBridgeMethods.focusViewFromJson;
969
+ const focusNextViewFromJson = BuiltinBridgeMethods.focusNextViewFromJson;
970
+ const focusPreviousViewFromJson = BuiltinBridgeMethods.focusPreviousViewFromJson;
971
+ const closeViewFromJson = BuiltinBridgeMethods.closeViewFromJson;
972
+ const writeViewListJson = BuiltinBridgeMethods.writeViewListJson;
973
+ const createWebViewFromJson = BuiltinBridgeMethods.createWebViewFromJson;
974
+ const setWebViewFrameFromJson = BuiltinBridgeMethods.setWebViewFrameFromJson;
975
+ const navigateWebViewFromJson = BuiltinBridgeMethods.navigateWebViewFromJson;
976
+ const setWebViewZoomFromJson = BuiltinBridgeMethods.setWebViewZoomFromJson;
977
+ const setWebViewLayerFromJson = BuiltinBridgeMethods.setWebViewLayerFromJson;
978
+ const closeWebViewFromJson = BuiltinBridgeMethods.closeWebViewFromJson;
979
+ const focusWindowFromJson = BuiltinBridgeMethods.focusWindowFromJson;
980
+ const closeWindowFromJson = BuiltinBridgeMethods.closeWindowFromJson;
981
+ const resolveWindowSelector = BuiltinBridgeMethods.resolveWindowSelector;
982
+ const writeWindowListJson = BuiltinBridgeMethods.writeWindowListJson;
983
+
984
+ fn handleBuiltinBridgeMessage(self: *Runtime, app: App, message: platform.BridgeMessage) anyerror!bool {
985
+ const request = bridge.parseRequest(message.bytes) catch return false;
986
+ const is_command = std.mem.startsWith(u8, request.command, "native-sdk.command.");
987
+ const is_window = std.mem.startsWith(u8, request.command, "native-sdk.window.");
988
+ const is_view = std.mem.startsWith(u8, request.command, "native-sdk.view.");
989
+ const is_webview = std.mem.startsWith(u8, request.command, "native-sdk.webview.");
990
+ const is_platform = std.mem.startsWith(u8, request.command, "native-sdk.platform.");
991
+ const is_dialog = std.mem.startsWith(u8, request.command, "native-sdk.dialog.");
992
+ const is_os = std.mem.startsWith(u8, request.command, "native-sdk.os.");
993
+ const is_clipboard = std.mem.startsWith(u8, request.command, "native-sdk.clipboard.");
994
+ const is_credentials = std.mem.startsWith(u8, request.command, "native-sdk.credentials.");
995
+ 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;
996
+
997
+ var response_buffer: [bridge.max_response_bytes]u8 = undefined;
998
+ var result_buffer: [bridge.max_result_bytes]u8 = undefined;
999
+ const js_permission: ?[]const u8 = if (is_command)
1000
+ security.permission_command
1001
+ else if (is_view)
1002
+ security.permission_view
1003
+ else if (is_window or is_webview or is_platform)
1004
+ security.permission_window
1005
+ else
1006
+ null;
1007
+ if (!allowsBuiltinBridgeCommand(self, request.command, message.origin, js_permission)) {
1008
+ const message_text = if (is_view)
1009
+ "View API is not permitted"
1010
+ else if (is_webview)
1011
+ "WebView API is not permitted"
1012
+ else if (is_window)
1013
+ "Window API is not permitted"
1014
+ else if (is_command)
1015
+ "Command API is not permitted"
1016
+ else if (is_platform)
1017
+ "Platform API is not permitted"
1018
+ else if (is_os)
1019
+ "OS API is not permitted"
1020
+ else if (is_clipboard)
1021
+ "Clipboard API is not permitted"
1022
+ else if (is_credentials)
1023
+ "Credentials API is not permitted"
1024
+ else
1025
+ "Dialog API is not permitted";
1026
+ const result = bridge.writeErrorResponse(&response_buffer, request.id, .permission_denied, message_text);
1027
+ try completeBridgeResponse(self, message.window_id, message.webview_label, result);
1028
+ self.invalidateFor(.command, null);
1029
+ return true;
1030
+ }
1031
+ const result = if (is_command)
1032
+ dispatchCommandBridgeCommand(self, app, request, message.window_id, message.webview_label, &result_buffer, &response_buffer)
1033
+ else if (is_window)
1034
+ dispatchWindowBridgeCommand(self, request, &result_buffer, &response_buffer)
1035
+ else if (is_view)
1036
+ dispatchViewBridgeCommand(self, request, message.window_id, &result_buffer, &response_buffer)
1037
+ else if (is_webview)
1038
+ dispatchWebViewBridgeCommand(self, request, message.window_id, &result_buffer, &response_buffer)
1039
+ else if (is_platform)
1040
+ dispatchPlatformBridgeCommand(self, request, &result_buffer, &response_buffer)
1041
+ else if (is_dialog)
1042
+ dispatchDialogBridgeCommand(self, request, &result_buffer, &response_buffer)
1043
+ else if (is_clipboard)
1044
+ dispatchClipboardBridgeCommand(self, request, &result_buffer, &response_buffer)
1045
+ else if (is_credentials)
1046
+ dispatchCredentialBridgeCommand(self, request, &result_buffer, &response_buffer)
1047
+ else
1048
+ dispatchOsBridgeCommand(self, request, &result_buffer, &response_buffer);
1049
+
1050
+ try completeBridgeResponse(self, message.window_id, message.webview_label, result);
1051
+ self.invalidateFor(.command, null);
1052
+ return true;
1053
+ }
1054
+
1055
+ fn completeBridgeResponse(self: *Runtime, window_id: platform.WindowId, webview_label: []const u8, response: []const u8) anyerror!void {
1056
+ try self.options.platform.services.completeWebViewBridge(window_id, webview_label, response);
1057
+ if (self.options.automation) |server| {
1058
+ server.publishBridgeResponse(response) catch |err| log(self, "automation.bridge_response_failed", @errorName(err), &.{});
1059
+ }
1060
+ }
1061
+
1062
+ fn emitShortcutEvent(self: *Runtime, shortcut: platform.ShortcutEvent) anyerror!void {
1063
+ var buffer: [512]u8 = undefined;
1064
+ var writer = std.Io.Writer.fixed(&buffer);
1065
+ try writer.writeAll("{\"id\":");
1066
+ try json.writeString(&writer, shortcut.id);
1067
+ try writer.writeAll(",\"command\":");
1068
+ try json.writeString(&writer, shortcut.id);
1069
+ try writer.writeAll(",\"key\":");
1070
+ try json.writeString(&writer, shortcut.key);
1071
+ try writer.print(",\"windowId\":{d},\"modifiers\":{{\"primary\":{},\"command\":{},\"control\":{},\"option\":{},\"shift\":{}}}}}", .{
1072
+ shortcut.window_id,
1073
+ shortcut.modifiers.primary,
1074
+ shortcut.modifiers.command,
1075
+ shortcut.modifiers.control,
1076
+ shortcut.modifiers.option,
1077
+ shortcut.modifiers.shift,
1078
+ });
1079
+ try emitWindowEvent(self, shortcut.window_id, "shortcut", writer.buffered());
1080
+ }
1081
+
1082
+ fn emitAppLifecycleEvent(self: *Runtime, name: []const u8) anyerror!void {
1083
+ for (self.windows[0..self.window_count]) |window| {
1084
+ if (window.info.open) try emitWindowEvent(self, window.info.id, name, "{}");
1085
+ }
1086
+ }
1087
+
1088
+ fn emitFileDropEvent(self: *Runtime, drop: platform.FileDropEvent) anyerror!void {
1089
+ var buffer: [platform.max_window_event_detail_bytes]u8 = undefined;
1090
+ var writer = std.Io.Writer.fixed(&buffer);
1091
+ try writer.print("{{\"windowId\":{d}", .{drop.window_id});
1092
+ if (drop.view_label.len > 0) {
1093
+ try writer.writeAll(",\"viewLabel\":");
1094
+ try json.writeString(&writer, drop.view_label);
1095
+ }
1096
+ if (drop.point) |point| {
1097
+ try writer.print(",\"x\":{d},\"y\":{d}", .{ point.x, point.y });
1098
+ }
1099
+ try writer.writeAll(",\"paths\":[");
1100
+ for (drop.paths, 0..) |path, index| {
1101
+ if (index > 0) try writer.writeByte(',');
1102
+ try json.writeString(&writer, path);
1103
+ }
1104
+ try writer.writeAll("]}");
1105
+ try emitWindowEvent(self, drop.window_id, "drop:files", writer.buffered());
1106
+ }
1107
+
1108
+ /// Trace logging never fails dispatch: a full or failing
1109
+ /// sink drops the record and counts the loss where snapshots can
1110
+ /// see it (`dropped_trace_records`).
1111
+ fn log(self: *Runtime, name_value: []const u8, message: ?[]const u8, fields: []const trace.Field) void {
1112
+ logAt(self, .info, name_value, message, fields);
1113
+ }
1114
+
1115
+ fn logAt(self: *Runtime, level: trace.Level, name_value: []const u8, message: ?[]const u8, fields: []const trace.Field) void {
1116
+ const sink = self.options.trace_sink orelse return;
1117
+ trace.writeRecord(sink, trace.event(nextTimestamp(self), level, name_value, message, fields)) catch {
1118
+ self.dropped_trace_records +%= 1;
1119
+ };
1120
+ }
1121
+
1122
+ /// A handler/update error must degrade, never terminate the
1123
+ /// app: record it in the bounded ring (queryable through
1124
+ /// `Runtime.dispatchErrors` and the automation snapshot), trace
1125
+ /// it at `.err`, and republish observable state.
1126
+ fn recordDispatchError(self: *Runtime, event_name: []const u8, err: anyerror) void {
1127
+ recordDispatchErrorDetail(self, event_name, err, "");
1128
+ }
1129
+
1130
+ /// `detail` is copied (truncated) into the record so the snapshot
1131
+ /// error line carries failure context — for automation commands,
1132
+ /// the command arguments, so a failed widget verb names its
1133
+ /// target.
1134
+ fn recordDispatchErrorDetail(self: *Runtime, event_name: []const u8, err: anyerror, detail: []const u8) void {
1135
+ self.dispatch_error_total +%= 1;
1136
+ var record: automation.snapshot.DispatchError = .{
1137
+ .timestamp_ns = runtime_clock.timestampToU64(nowNanoseconds()),
1138
+ .event = event_name,
1139
+ .error_name = @errorName(err),
1140
+ };
1141
+ record.setDetail(detail);
1142
+ if (self.dispatch_error_len == self.dispatch_errors.len) {
1143
+ std.mem.copyForwards(automation.snapshot.DispatchError, self.dispatch_errors[0 .. self.dispatch_errors.len - 1], self.dispatch_errors[1..]);
1144
+ self.dispatch_errors[self.dispatch_errors.len - 1] = record;
1145
+ } else {
1146
+ self.dispatch_errors[self.dispatch_error_len] = record;
1147
+ self.dispatch_error_len += 1;
1148
+ }
1149
+ logAt(self, .err, "dispatch.error", @errorName(err), &.{trace.string("event", event_name)});
1150
+ self.invalidateFor(.state, null);
1151
+ }
1152
+
1153
+ fn extensionContext(self: *Runtime) extensions.RuntimeContext {
1154
+ return .{ .platform_name = self.options.platform.name };
1155
+ }
1156
+
1157
+ fn nextTimestamp(self: *Runtime) trace.Timestamp {
1158
+ self.timestamp_ns = nowNanoseconds();
1159
+ return trace.Timestamp.fromNanoseconds(self.timestamp_ns);
1160
+ }
1161
+ };
1162
+ }
1163
+
1164
+ fn copyInto(buffer: []u8, value: []const u8) ![]const u8 {
1165
+ if (value.len > buffer.len) return error.NoSpaceLeft;
1166
+ @memcpy(buffer[0..value.len], value);
1167
+ return buffer[0..value.len];
1168
+ }
1169
+
1170
+ fn appUsesDefaultEmptyWebViewSource(comptime App: type, app: App) bool {
1171
+ return app.source_fn == null and
1172
+ app.source.kind == .html and
1173
+ app.source.bytes.len == 0 and
1174
+ app.source.asset_options == null;
1175
+ }