@native-sdk/cli 0.0.0 → 0.4.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 (367) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/bin/native.js +156 -0
  5. package/build/app.zig +716 -0
  6. package/build.zig +2593 -0
  7. package/build.zig.zon +24 -0
  8. package/native-sdk.d.ts +615 -0
  9. package/package.json +44 -8
  10. package/skill-data/automation/SKILL.md +248 -0
  11. package/skill-data/core/SKILL.md +249 -0
  12. package/skill-data/core/references/app-model-runtime.md +141 -0
  13. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  14. package/skill-data/core/references/frontend-assets.md +124 -0
  15. package/skill-data/core/references/project-anatomy.md +108 -0
  16. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  17. package/skill-data/native-ui/SKILL.md +1080 -0
  18. package/skills/native-sdk/SKILL.md +33 -0
  19. package/src/app_runner/root.zig +740 -0
  20. package/src/assets/root.zig +20 -0
  21. package/src/automation/protocol.zig +285 -0
  22. package/src/automation/root.zig +13 -0
  23. package/src/automation/server.zig +506 -0
  24. package/src/automation/snapshot.zig +1202 -0
  25. package/src/automation/watcher.zig +165 -0
  26. package/src/bridge/root.zig +507 -0
  27. package/src/debug/root.zig +246 -0
  28. package/src/embed/app_exports.zig +11 -0
  29. package/src/embed/c_api.zig +793 -0
  30. package/src/embed/c_exports.zig +10 -0
  31. package/src/embed/chrome.zig +168 -0
  32. package/src/embed/conversions.zig +359 -0
  33. package/src/embed/host.zig +960 -0
  34. package/src/embed/root.zig +81 -0
  35. package/src/embed/tests.zig +2552 -0
  36. package/src/embed/types.zig +382 -0
  37. package/src/embed/ui_host.zig +289 -0
  38. package/src/extensions/root.zig +197 -0
  39. package/src/frontend/root.zig +48 -0
  40. package/src/js/root.zig +65 -0
  41. package/src/platform/android/NativeSdkActivity.java +1370 -0
  42. package/src/platform/android/android_host.c +696 -0
  43. package/src/platform/android/files.zig +9 -0
  44. package/src/platform/android/native_sdk_app.h +237 -0
  45. package/src/platform/ios/files.zig +8 -0
  46. package/src/platform/ios/native_sdk_app.h +289 -0
  47. package/src/platform/ios/uikit_host.m +2739 -0
  48. package/src/platform/linux/cef_host.cpp +599 -0
  49. package/src/platform/linux/gtk_host.c +5362 -0
  50. package/src/platform/linux/gtk_host.h +265 -0
  51. package/src/platform/linux/root.zig +1519 -0
  52. package/src/platform/macos/appkit_host.h +604 -0
  53. package/src/platform/macos/appkit_host.m +10392 -0
  54. package/src/platform/macos/automation_host.h +14 -0
  55. package/src/platform/macos/automation_host.m +12 -0
  56. package/src/platform/macos/cef_host.mm +3028 -0
  57. package/src/platform/macos/root.zig +2260 -0
  58. package/src/platform/null_platform.zig +2232 -0
  59. package/src/platform/null_platform_tests.zig +670 -0
  60. package/src/platform/policy_values.zig +14 -0
  61. package/src/platform/root.zig +181 -0
  62. package/src/platform/types.zig +2681 -0
  63. package/src/platform/windows/cef_host.cpp +3 -0
  64. package/src/platform/windows/root.zig +1521 -0
  65. package/src/platform/windows/webview2_host.cpp +6230 -0
  66. package/src/primitives/app_dirs/root.zig +440 -0
  67. package/src/primitives/app_manifest/root.zig +109 -0
  68. package/src/primitives/app_manifest/tests.zig +758 -0
  69. package/src/primitives/app_manifest/types.zig +587 -0
  70. package/src/primitives/app_manifest/validation.zig +828 -0
  71. package/src/primitives/assets/root.zig +520 -0
  72. package/src/primitives/canvas/a11y_audit.zig +390 -0
  73. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  74. package/src/primitives/canvas/app_icon.zig +1590 -0
  75. package/src/primitives/canvas/chart.zig +392 -0
  76. package/src/primitives/canvas/chart_tests.zig +751 -0
  77. package/src/primitives/canvas/commands.zig +446 -0
  78. package/src/primitives/canvas/drawing.zig +309 -0
  79. package/src/primitives/canvas/equality.zig +316 -0
  80. package/src/primitives/canvas/events.zig +696 -0
  81. package/src/primitives/canvas/font_coverage.zig +118 -0
  82. package/src/primitives/canvas/font_ttf.zig +510 -0
  83. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  84. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  85. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  86. package/src/primitives/canvas/frame.zig +679 -0
  87. package/src/primitives/canvas/frame_metrics.zig +462 -0
  88. package/src/primitives/canvas/gpu.zig +639 -0
  89. package/src/primitives/canvas/hash.zig +112 -0
  90. package/src/primitives/canvas/icons/alert.svg +1 -0
  91. package/src/primitives/canvas/icons/archive.svg +1 -0
  92. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  93. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  94. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  95. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  96. package/src/primitives/canvas/icons/check.svg +1 -0
  97. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  98. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  99. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  100. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  101. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  102. package/src/primitives/canvas/icons/clock.svg +1 -0
  103. package/src/primitives/canvas/icons/copy.svg +1 -0
  104. package/src/primitives/canvas/icons/download.svg +1 -0
  105. package/src/primitives/canvas/icons/edit.svg +1 -0
  106. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  107. package/src/primitives/canvas/icons/external-link.svg +1 -0
  108. package/src/primitives/canvas/icons/eye.svg +1 -0
  109. package/src/primitives/canvas/icons/file-text.svg +1 -0
  110. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  111. package/src/primitives/canvas/icons/folder.svg +1 -0
  112. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  113. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  114. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  115. package/src/primitives/canvas/icons/info.svg +1 -0
  116. package/src/primitives/canvas/icons/menu.svg +1 -0
  117. package/src/primitives/canvas/icons/missing.svg +1 -0
  118. package/src/primitives/canvas/icons/moon.svg +1 -0
  119. package/src/primitives/canvas/icons/music.svg +1 -0
  120. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  121. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  122. package/src/primitives/canvas/icons/pause.svg +1 -0
  123. package/src/primitives/canvas/icons/play.svg +1 -0
  124. package/src/primitives/canvas/icons/plus.svg +1 -0
  125. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  126. package/src/primitives/canvas/icons/repeat.svg +1 -0
  127. package/src/primitives/canvas/icons/save.svg +1 -0
  128. package/src/primitives/canvas/icons/search.svg +1 -0
  129. package/src/primitives/canvas/icons/send.svg +1 -0
  130. package/src/primitives/canvas/icons/settings.svg +1 -0
  131. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  132. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  133. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  134. package/src/primitives/canvas/icons/sun.svg +1 -0
  135. package/src/primitives/canvas/icons/terminal.svg +1 -0
  136. package/src/primitives/canvas/icons/trash.svg +1 -0
  137. package/src/primitives/canvas/icons/volume.svg +1 -0
  138. package/src/primitives/canvas/icons/wrench.svg +1 -0
  139. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  140. package/src/primitives/canvas/icons/x.svg +1 -0
  141. package/src/primitives/canvas/icons.zig +249 -0
  142. package/src/primitives/canvas/layout_audit.zig +744 -0
  143. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  144. package/src/primitives/canvas/markdown.zig +1031 -0
  145. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  146. package/src/primitives/canvas/markdown_tests.zig +538 -0
  147. package/src/primitives/canvas/plan_key_index.zig +120 -0
  148. package/src/primitives/canvas/png.zig +355 -0
  149. package/src/primitives/canvas/reference.zig +1457 -0
  150. package/src/primitives/canvas/reference_blur.zig +104 -0
  151. package/src/primitives/canvas/reference_memo.zig +322 -0
  152. package/src/primitives/canvas/reference_paths.zig +184 -0
  153. package/src/primitives/canvas/reference_tests.zig +1650 -0
  154. package/src/primitives/canvas/render.zig +747 -0
  155. package/src/primitives/canvas/render_effects.zig +255 -0
  156. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  157. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  158. package/src/primitives/canvas/render_images.zig +247 -0
  159. package/src/primitives/canvas/render_layers.zig +260 -0
  160. package/src/primitives/canvas/render_paths.zig +347 -0
  161. package/src/primitives/canvas/render_resources.zig +51 -0
  162. package/src/primitives/canvas/render_tests.zig +3186 -0
  163. package/src/primitives/canvas/root.zig +744 -0
  164. package/src/primitives/canvas/serialization.zig +1528 -0
  165. package/src/primitives/canvas/svg_icon.zig +636 -0
  166. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  167. package/src/primitives/canvas/test_support.zig +422 -0
  168. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  169. package/src/primitives/canvas/tests.zig +30 -0
  170. package/src/primitives/canvas/text.zig +82 -0
  171. package/src/primitives/canvas/text_atlas.zig +408 -0
  172. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  173. package/src/primitives/canvas/text_interaction.zig +615 -0
  174. package/src/primitives/canvas/text_layout.zig +1069 -0
  175. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  176. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  177. package/src/primitives/canvas/text_layout_types.zig +128 -0
  178. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  179. package/src/primitives/canvas/text_metrics.zig +309 -0
  180. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  181. package/src/primitives/canvas/text_span_tests.zig +608 -0
  182. package/src/primitives/canvas/text_spans.zig +1010 -0
  183. package/src/primitives/canvas/text_tests.zig +1949 -0
  184. package/src/primitives/canvas/themes/geist.zig +470 -0
  185. package/src/primitives/canvas/tokens.zig +1522 -0
  186. package/src/primitives/canvas/ui.zig +2686 -0
  187. package/src/primitives/canvas/ui_markup.zig +3791 -0
  188. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  189. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  190. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  191. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  192. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  193. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  194. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  195. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  196. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  197. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  198. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  199. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  200. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  201. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  202. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  203. package/src/primitives/canvas/ui_provenance.zig +96 -0
  204. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  205. package/src/primitives/canvas/ui_schema.zig +825 -0
  206. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  207. package/src/primitives/canvas/ui_tests.zig +1432 -0
  208. package/src/primitives/canvas/vector.zig +919 -0
  209. package/src/primitives/canvas/vector_tests.zig +547 -0
  210. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  211. package/src/primitives/canvas/virtual_extents.zig +540 -0
  212. package/src/primitives/canvas/widget_access.zig +208 -0
  213. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  214. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  215. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  216. package/src/primitives/canvas/widget_layout.zig +2055 -0
  217. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  218. package/src/primitives/canvas/widget_metrics.zig +228 -0
  219. package/src/primitives/canvas/widget_render.zig +2534 -0
  220. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  221. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  222. package/src/primitives/canvas/widget_render_style.zig +626 -0
  223. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  224. package/src/primitives/canvas/widget_routing.zig +475 -0
  225. package/src/primitives/canvas/widget_runtime.zig +307 -0
  226. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  227. package/src/primitives/canvas/widget_semantics.zig +480 -0
  228. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  229. package/src/primitives/canvas/widget_tests.zig +8 -0
  230. package/src/primitives/canvas/widget_text_input.zig +351 -0
  231. package/src/primitives/canvas/widget_text_select.zig +147 -0
  232. package/src/primitives/canvas/widget_tree.zig +232 -0
  233. package/src/primitives/canvas/widgets.zig +1319 -0
  234. package/src/primitives/diagnostics/root.zig +445 -0
  235. package/src/primitives/geometry/root.zig +889 -0
  236. package/src/primitives/json/root.zig +272 -0
  237. package/src/primitives/platform_info/root.zig +450 -0
  238. package/src/primitives/trace/root.zig +569 -0
  239. package/src/root.zig +165 -0
  240. package/src/runtime/api.zig +431 -0
  241. package/src/runtime/async_bridge.zig +49 -0
  242. package/src/runtime/automation_commands.zig +686 -0
  243. package/src/runtime/automation_liveness_tests.zig +140 -0
  244. package/src/runtime/automation_snapshot.zig +246 -0
  245. package/src/runtime/automation_widget_dispatch.zig +617 -0
  246. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  247. package/src/runtime/bridge_payload.zig +194 -0
  248. package/src/runtime/bridge_permission_tests.zig +551 -0
  249. package/src/runtime/bridge_responses.zig +414 -0
  250. package/src/runtime/builtin_bridge.zig +554 -0
  251. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  252. package/src/runtime/canvas_font_tests.zig +410 -0
  253. package/src/runtime/canvas_fonts.zig +229 -0
  254. package/src/runtime/canvas_frame.zig +1734 -0
  255. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  256. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  257. package/src/runtime/canvas_frame_helpers.zig +414 -0
  258. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  259. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  260. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  261. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  262. package/src/runtime/canvas_frame_tests.zig +9 -0
  263. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  264. package/src/runtime/canvas_image_tests.zig +362 -0
  265. package/src/runtime/canvas_images.zig +224 -0
  266. package/src/runtime/canvas_limits.zig +317 -0
  267. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  268. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  269. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  270. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  271. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  272. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  273. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  274. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  275. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  276. package/src/runtime/canvas_widget_display.zig +677 -0
  277. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  278. package/src/runtime/canvas_widget_events.zig +1098 -0
  279. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  280. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  281. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  282. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  283. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  284. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  285. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  286. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  287. package/src/runtime/canvas_widget_state.zig +798 -0
  288. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  289. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  290. package/src/runtime/clock.zig +231 -0
  291. package/src/runtime/core.zig +927 -0
  292. package/src/runtime/effects.zig +4197 -0
  293. package/src/runtime/effects_audio_tests.zig +690 -0
  294. package/src/runtime/effects_clipboard_tests.zig +317 -0
  295. package/src/runtime/effects_fetch_tests.zig +1031 -0
  296. package/src/runtime/effects_file_tests.zig +407 -0
  297. package/src/runtime/effects_tests.zig +1251 -0
  298. package/src/runtime/flow.zig +1175 -0
  299. package/src/runtime/frame_profile.zig +221 -0
  300. package/src/runtime/gpu_surface_events.zig +639 -0
  301. package/src/runtime/launch_timing.zig +59 -0
  302. package/src/runtime/markdown_app_tests.zig +224 -0
  303. package/src/runtime/native_command_event_tests.zig +431 -0
  304. package/src/runtime/platform_bridge_tests.zig +8 -0
  305. package/src/runtime/platform_config_tests.zig +392 -0
  306. package/src/runtime/root.zig +150 -0
  307. package/src/runtime/runtime_event_tests.zig +1079 -0
  308. package/src/runtime/session_journal.zig +1522 -0
  309. package/src/runtime/session_record.zig +332 -0
  310. package/src/runtime/session_replay.zig +274 -0
  311. package/src/runtime/session_state.zig +30 -0
  312. package/src/runtime/session_tests.zig +399 -0
  313. package/src/runtime/shell_layout.zig +472 -0
  314. package/src/runtime/shell_layout_tests.zig +1246 -0
  315. package/src/runtime/shell_view_tests.zig +604 -0
  316. package/src/runtime/state.zig +110 -0
  317. package/src/runtime/system_services.zig +392 -0
  318. package/src/runtime/test_support.zig +79 -0
  319. package/src/runtime/tests.zig +30 -0
  320. package/src/runtime/ui_app.zig +3290 -0
  321. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  322. package/src/runtime/ui_app_provenance.zig +370 -0
  323. package/src/runtime/ui_app_tests.zig +3254 -0
  324. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  325. package/src/runtime/ui_app_window_tests.zig +442 -0
  326. package/src/runtime/validation.zig +206 -0
  327. package/src/runtime/view.zig +908 -0
  328. package/src/runtime/view_canvas.zig +850 -0
  329. package/src/runtime/view_widget_control.zig +433 -0
  330. package/src/runtime/view_widget_scroll.zig +360 -0
  331. package/src/runtime/view_widget_text.zig +275 -0
  332. package/src/runtime/view_widget_tree.zig +843 -0
  333. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  334. package/src/runtime/widget_bridge.zig +231 -0
  335. package/src/runtime/window_command_bridge_tests.zig +403 -0
  336. package/src/runtime/window_storage.zig +255 -0
  337. package/src/runtime/window_view_runtime.zig +727 -0
  338. package/src/runtime/window_views.zig +334 -0
  339. package/src/security/root.zig +118 -0
  340. package/src/tooling/android.zig +1172 -0
  341. package/src/tooling/assets.zig +128 -0
  342. package/src/tooling/buildgraph.zig +379 -0
  343. package/src/tooling/cef.zig +671 -0
  344. package/src/tooling/codesign.zig +172 -0
  345. package/src/tooling/components/identity_tests.zig +185 -0
  346. package/src/tooling/components/stepper.zig +113 -0
  347. package/src/tooling/components/timeline.native +27 -0
  348. package/src/tooling/components/timeline_item.zig +131 -0
  349. package/src/tooling/default_icon.icns +0 -0
  350. package/src/tooling/default_icon.png +0 -0
  351. package/src/tooling/dev.zig +172 -0
  352. package/src/tooling/doctor.zig +349 -0
  353. package/src/tooling/eject_components.zig +170 -0
  354. package/src/tooling/embedlib.zig +290 -0
  355. package/src/tooling/ios.zig +528 -0
  356. package/src/tooling/manifest.zig +1939 -0
  357. package/src/tooling/package.zig +2388 -0
  358. package/src/tooling/process_tree.zig +114 -0
  359. package/src/tooling/raw_manifest.zig +193 -0
  360. package/src/tooling/root.zig +22 -0
  361. package/src/tooling/templates.zig +3191 -0
  362. package/src/tooling/toolchain.zig +371 -0
  363. package/src/tooling/verbs.zig +204 -0
  364. package/src/tooling/web_engine.zig +135 -0
  365. package/src/tooling/xcodeproj.zig +462 -0
  366. package/src/window_state/root.zig +507 -0
  367. package/index.js +0 -2
@@ -0,0 +1,4197 @@
1
+ //! The effect system: TEA's `Cmd` half for `UiApp`.
2
+ //!
3
+ //! `Effects(Msg)` runs subprocesses, HTTP fetches, and whole-file
4
+ //! reads/writes on worker threads
5
+ //! owned by the app loop, streams subprocess stdout lines back as typed
6
+ //! `Msg` values (or, in `.collect` mode, accumulates whole stdout plus a
7
+ //! stderr tail and delivers both on the exit Msg), reports process exits
8
+ //! the same way, and delivers each fetch's terminal outcome as exactly
9
+ //! one `Msg` — with `.response = .stream` framing the response body into
10
+ //! `on_line` Msgs first (the spawn `.lines` contract over HTTP, for
11
+ //! NDJSON/SSE endpoints that hold the connection open). File effects
12
+ //! (`writeFile`/`readFile`) follow the fetch shape: one bounded
13
+ //! operation, one terminal Msg with an explicit outcome
14
+ //! (ok / not_found / io_failed / truncated / rejected / cancelled) —
15
+ //! TEA-friendly persistence without smuggling an `Io` handle into
16
+ //! `update`. Clipboard effects (`writeClipboard`/`readClipboard`) keep
17
+ //! the same shape over the platform pasteboard — the seam the
18
+ //! runtime's cmd+C copy uses — executed synchronously on the loop
19
+ //! thread (pasteboards are main-thread services), so apps stop
20
+ //! spawning `pbcopy`. The model is
21
+ //! never touched off-thread: workers post
22
+ //! fixed-size completion records into a bounded MPSC queue, nudge the
23
+ //! platform loop through `PlatformServices.wake_fn`, and the loop thread
24
+ //! drains the queue and dispatches Msgs through the app's `update`.
25
+ //!
26
+ //! Design points, mirroring the framework's fixed-capacity philosophy:
27
+ //!
28
+ //! - Caller-chosen `u64` keys identify effects (store them in the model);
29
+ //! there are no handles to leak. `cancel(key)` kills and reaps.
30
+ //! - Execution is thread-per-effect with a hard cap (`max_effects` slots
31
+ //! shared between spawns and fetches). Subprocess streaming and HTTP
32
+ //! exchanges are blocking-I/O-dominated, so a shared pool would need
33
+ //! multiplexing for zero gain at this scale; one thread whose lifetime
34
+ //! equals its effect keeps cancellation and reaping local to a slot.
35
+ //! A real fetch additionally borrows one `std.Io.Threaded` task thread
36
+ //! for the blocking HTTP exchange so the worker can interrupt it on
37
+ //! cancel or timeout.
38
+ //! - Overflow is NEVER silent: a spawn that cannot run surfaces as an
39
+ //! `on_exit` Msg with reason `.rejected` and a fetch that cannot run as
40
+ //! an `on_response` Msg with outcome `.rejected`; a line dropped on a
41
+ //! full queue is counted into the next delivered line's
42
+ //! `dropped_before` and the exit's `dropped_lines`; an over-long line
43
+ //! is delivered truncated with `truncated = true`; a response body over
44
+ //! `max_effect_body_bytes` arrives truncated with `truncated = true`;
45
+ //! collected stdout over `max_effect_collect_bytes` and a stderr tail
46
+ //! over `max_effect_stderr_tail_bytes` arrive cut with
47
+ //! `output_truncated`/`stderr_truncated` set.
48
+ //! - Spawned children inherit the host process environment (HOME, PATH,
49
+ //! ...): the app runner threads it from `std.process.Init` through
50
+ //! `Runtime.Options.environ` into `bindEnviron`; hosts without a
51
+ //! process `Init` (embed/mobile) get `fallbackEnviron()`.
52
+ //! - Cancel semantics: after `cancel(key)` returns, no further `on_line`
53
+ //! Msgs for that spawn are dispatched (already-queued lines are
54
+ //! discarded at drain), and exactly one `on_exit` Msg with reason
55
+ //! `.cancelled` follows once the process is reaped. No zombies: the
56
+ //! worker always waits on its child. A cancelled fetch keeps the same
57
+ //! promise: exactly one `on_response` Msg with outcome `.cancelled`,
58
+ //! and nothing for that fetch after it.
59
+ //!
60
+ //! Payload lifetime: `EffectLine.line`, `EffectResponse.body`,
61
+ //! `EffectExit.output`, and `EffectExit.stderr_tail` point into drain
62
+ //! scratch that is recycled on the next drained Msg — `update` must copy
63
+ //! what it keeps, exactly like `canvas.TextInputEvent` payloads.
64
+
65
+ const std = @import("std");
66
+ const builtin = @import("builtin");
67
+ const platform = @import("../platform/root.zig");
68
+ const runtime_clock = @import("clock.zig");
69
+
70
+ /// Maximum in-flight effects (spawn slots / worker threads).
71
+ pub const max_effects: usize = 16;
72
+ /// Maximum argv entries per spawn.
73
+ pub const max_effect_argv: usize = 16;
74
+ /// Maximum total bytes across all argv entries of one spawn.
75
+ pub const max_effect_argv_bytes: usize = 2048;
76
+ /// Maximum stdin payload per spawn (written once, then closed).
77
+ pub const max_effect_stdin_bytes: usize = 4096;
78
+ /// Default maximum bytes per delivered stdout line; longer lines are
79
+ /// truncated (delivered with `truncated = true`, the remainder
80
+ /// discarded). Applies to `.lines` spawns and `.stream` fetches only —
81
+ /// `.collect` spawns have no line framing. Override per effect with
82
+ /// `SpawnOptions.max_line_bytes` / `FetchOptions.max_line_bytes` (agent
83
+ /// CLIs emit whole NDJSON events as single lines far beyond 4 KiB).
84
+ pub const max_effect_line_bytes: usize = 4096;
85
+ /// Hard ceiling for per-effect `max_line_bytes` overrides. A request
86
+ /// above it is rejected (reason `.rejected` / outcome `.rejected`) —
87
+ /// never silently clamped. Lines beyond the granted bound still arrive
88
+ /// truncated and flagged. Overrides above the default heap-allocate one
89
+ /// line buffer per accepted effect plus one transfer buffer per
90
+ /// oversized line in flight — the ceiling only bounds what an app may
91
+ /// ask for; nothing is allocated until an effect opts in. Sized so an
92
+ /// envelope protocol (NDJSON wrapping another stream's lines as
93
+ /// JSON-escaped `data` fields, e.g. sandbox exec rechunking an agent's
94
+ /// stream-json) can carry a full 64 KiB inner line with escaping
95
+ /// overhead and framing to spare: the previous 64 KiB ceiling made a
96
+ /// near-ceiling inner line unrecoverable because the WRAPPED line blew
97
+ /// the same bound both layers individually fit in.
98
+ pub const max_effect_line_bytes_ceiling: usize = 256 * 1024;
99
+ /// Maximum collected stdout bytes per `.collect` spawn (whole-stdout
100
+ /// delivery for tools like `gh --json` that emit one giant line); the
101
+ /// overflow is discarded and the exit arrives with
102
+ /// `output_truncated = true`. Heap-allocated per accepted collect spawn,
103
+ /// like a fetch's body buffer.
104
+ pub const max_effect_collect_bytes: usize = 512 * 1024;
105
+ /// Stderr tail bytes kept per `.collect` spawn: the LAST bytes the child
106
+ /// wrote, delivered on the exit Msg (diagnose failures without an sh
107
+ /// re-route). Earlier bytes are discarded and flagged through
108
+ /// `stderr_truncated`. `.lines` spawns ignore stderr entirely.
109
+ pub const max_effect_stderr_tail_bytes: usize = 4096;
110
+
111
+ comptime {
112
+ // The stderr tail rides in a queue entry's line buffer.
113
+ std.debug.assert(max_effect_stderr_tail_bytes <= max_effect_line_bytes);
114
+ // File paths ride in a slot's URL storage.
115
+ std.debug.assert(max_effect_file_path_bytes <= max_effect_url_bytes);
116
+ }
117
+ /// Completion queue depth (lines + exits from all workers combined).
118
+ pub const max_effect_queue_entries: usize = 64;
119
+ /// Main-thread pending-exit ring (spawn rejections, fake-executor exits
120
+ /// that found the queue full). Sized above the slot count so a burst of
121
+ /// rejected spawns in one update still surfaces individually.
122
+ pub const max_effect_pending_exits: usize = 32;
123
+
124
+ /// Maximum bytes of one fetch's URL.
125
+ pub const max_effect_url_bytes: usize = 2048;
126
+ /// Maximum extra headers per fetch.
127
+ pub const max_effect_fetch_headers: usize = 8;
128
+ /// Maximum total bytes across all header names and values of one fetch.
129
+ pub const max_effect_fetch_header_bytes: usize = 1024;
130
+ /// Maximum request payload per fetch (the body sent to the server).
131
+ pub const max_effect_fetch_payload_bytes: usize = 64 * 1024;
132
+ /// Maximum response body bytes delivered per fetch; longer bodies arrive
133
+ /// truncated (delivered with `truncated = true`, the remainder
134
+ /// discarded). Generous next to `max_effect_line_bytes` because fetch
135
+ /// bodies are one-shot (JSON API responses, small images), not a stream;
136
+ /// full-size image fetches (I1) will revisit this with a per-fetch bound.
137
+ pub const max_effect_body_bytes: usize = 256 * 1024;
138
+ /// Default per-fetch timeout covering the whole exchange (DNS, connect,
139
+ /// TLS, headers, and body). Override per fetch with
140
+ /// `FetchOptions.timeout_ms`.
141
+ pub const default_effect_fetch_timeout_ms: u32 = 30_000;
142
+
143
+ /// Maximum bytes of one file effect's path.
144
+ pub const max_effect_file_path_bytes: usize = 1024;
145
+ /// Maximum file-effect payload: the bytes one `writeFile` writes, and
146
+ /// the most one `readFile` delivers (larger files arrive cut with
147
+ /// outcome `.truncated`). Sized for JSON session snapshots and app
148
+ /// state, not media. An over-bound WRITE is rejected outright — a cut
149
+ /// write would corrupt the file on disk, which truncation flags cannot
150
+ /// undo.
151
+ pub const max_effect_file_bytes: usize = 1024 * 1024;
152
+
153
+ /// Maximum clipboard-effect payload: what one `writeClipboard` writes
154
+ /// and the most one `readClipboard` delivers — the platform clipboard
155
+ /// bound (`platform.max_clipboard_data_bytes`). Over-bound writes are
156
+ /// rejected outright, mirroring `writeFile` (a cut clipboard string
157
+ /// must never pass for the whole one).
158
+ pub const max_effect_clipboard_bytes: usize = platform.max_clipboard_data_bytes;
159
+
160
+ /// The exit `code` reported for every non-`.exited` reason.
161
+ pub const effect_error_exit_code: i32 = -1;
162
+
163
+ /// Type-erased handle to the runtime's canvas image registry, bound onto
164
+ /// the effects channel (`bindImages`) so `update` can turn fetched bytes
165
+ /// into drawable ImageIds without reaching for the runtime. Constructed
166
+ /// by `Runtime.canvasImageRegistryBinding()`.
167
+ pub const ImageRegistryBinding = struct {
168
+ context: *anyopaque,
169
+ register_fn: *const fn (context: *anyopaque, id: u64, width: usize, height: usize, rgba8: []const u8) anyerror!void,
170
+ register_bytes_fn: *const fn (context: *anyopaque, id: u64, bytes: []const u8) anyerror!RegisteredImage,
171
+ unregister_fn: *const fn (context: *anyopaque, id: u64) bool,
172
+ };
173
+
174
+ /// Dimensions of a successfully registered image (what the platform
175
+ /// codec decoded).
176
+ pub const RegisteredImage = struct {
177
+ width: usize = 0,
178
+ height: usize = 0,
179
+ };
180
+
181
+ /// Type-erased handle to the runtime's window verbs, bound onto the
182
+ /// effects channel (`bindWindowActions`) so `update` can drive REAL OS
183
+ /// window actions — the seam behind app-drawn close/minimize controls
184
+ /// on chromeless windows. Label-addressed because labels are what apps
185
+ /// declare (`ShellWindow.label`, `WindowDescriptor.label`); the runtime
186
+ /// side resolves them to live window ids. Constructed by `UiApp`.
187
+ pub const WindowActionBinding = struct {
188
+ context: *anyopaque,
189
+ close_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
190
+ minimize_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
191
+ };
192
+
193
+ /// Window-action label capacity (`Effects.closeWindow`/`minimizeWindow`):
194
+ /// the mirror copies the last requested label so tests can pin it.
195
+ pub const max_window_action_label = 64;
196
+
197
+ /// The window-action mirror: observable state for every close/minimize
198
+ /// request made through the channel, recorded before the runtime call
199
+ /// (and INSTEAD of it under the fake executor — hermetic tests pin the
200
+ /// counts, live runs also perform the verb).
201
+ pub const WindowActionState = struct {
202
+ close_count: u32 = 0,
203
+ minimize_count: u32 = 0,
204
+ last_label_buffer: [max_window_action_label]u8 = @splat(0),
205
+ last_label_len: usize = 0,
206
+
207
+ pub fn lastLabel(self: *const WindowActionState) []const u8 {
208
+ return self.last_label_buffer[0..self.last_label_len];
209
+ }
210
+
211
+ fn record(self: *WindowActionState, label: []const u8) void {
212
+ const len = @min(label.len, max_window_action_label);
213
+ @memcpy(self.last_label_buffer[0..len], label[0..len]);
214
+ self.last_label_len = len;
215
+ }
216
+ };
217
+
218
+ /// How a spawn's stdout comes back. `.lines` streams each line as an
219
+ /// `on_line` Msg as it arrives (the default; long-running streams).
220
+ /// `.collect` accumulates whole stdout — single-line JSON far beyond the
221
+ /// line cap included — and delivers it once, on the exit Msg
222
+ /// (`EffectExit.output`), together with the child's stderr tail; collect
223
+ /// spawns dispatch no `on_line` Msgs. Both bounded, both flag truncation,
224
+ /// neither is ever silent.
225
+ pub const EffectOutputMode = enum { lines, collect };
226
+
227
+ /// How a fetch's response body comes back. `.buffered` (the default)
228
+ /// delivers the whole body once, on the terminal `on_response` Msg.
229
+ /// `.stream` frames the body into lines as they arrive — each line is
230
+ /// an `on_line` Msg (the spawn `.lines` contract over HTTP; NDJSON and
231
+ /// SSE endpoints that hold the connection open for a command's whole
232
+ /// lifetime are the driver) — and the terminal `on_response` Msg then
233
+ /// carries the status with an empty body. The fetch promise holds:
234
+ /// exactly one terminal Msg per fetch, and after `cancel(key)` no
235
+ /// further line Msgs are dispatched. The whole-exchange timeout applies
236
+ /// to the stream's full lifetime — long-lived streams should raise
237
+ /// `timeout_ms` accordingly.
238
+ pub const FetchResponseMode = enum { buffered, stream };
239
+
240
+ pub const EffectExitReason = enum {
241
+ /// The process exited on its own; `code` is its exit code.
242
+ exited,
243
+ /// The process died to a signal it was not sent by `cancel`.
244
+ signaled,
245
+ /// `cancel(key)` ended it (or it exited while the cancel was in
246
+ /// flight — after `cancel` the exit always reports `.cancelled`).
247
+ cancelled,
248
+ /// The spawn request never ran: all slots busy, a duplicate active
249
+ /// key, or argv/stdin over capacity.
250
+ rejected,
251
+ /// The process could not be started (missing binary, bad argv).
252
+ spawn_failed,
253
+ };
254
+
255
+ /// Payload for `on_line` Msg constructors. `line` is valid only during
256
+ /// the `update` call that receives it — copy what the model keeps.
257
+ pub const EffectLine = struct {
258
+ key: u64,
259
+ line: []const u8,
260
+ /// The source line exceeded the effect's line bound (the
261
+ /// `max_effect_line_bytes` default or its per-effect
262
+ /// `max_line_bytes` override); this is its first bound bytes and
263
+ /// the rest was discarded.
264
+ truncated: bool = false,
265
+ /// Whole lines dropped on a full completion queue immediately before
266
+ /// this one. Never silently zero when drops happened: undelivered
267
+ /// drops also accumulate into the exit's `dropped_lines`.
268
+ dropped_before: u32 = 0,
269
+ };
270
+
271
+ /// Payload for `on_exit` Msg constructors. Exactly one is delivered per
272
+ /// accepted spawn, and one per rejected spawn (reason `.rejected`).
273
+ /// `output` and `stderr_tail` are drain scratch, valid only during the
274
+ /// `update` call that receives them — copy what the model keeps (the
275
+ /// scalar fields are plain data and safe to store whole for `.lines`
276
+ /// spawns, whose slices are always empty).
277
+ pub const EffectExit = struct {
278
+ key: u64,
279
+ code: i32 = effect_error_exit_code,
280
+ reason: EffectExitReason = .exited,
281
+ /// Total stdout lines dropped over the effect's lifetime (full
282
+ /// completion queue). Zero means every line was delivered. Always
283
+ /// zero for `.collect` spawns (no line framing, nothing to drop).
284
+ dropped_lines: u32 = 0,
285
+ /// Whole collected stdout for `.collect` spawns; `""` for `.lines`
286
+ /// spawns and for cancelled/rejected exits.
287
+ output: []const u8 = "",
288
+ /// stdout exceeded `max_effect_collect_bytes`: `output` is its first
289
+ /// bytes and the rest was discarded. Never silent.
290
+ output_truncated: bool = false,
291
+ /// The last `max_effect_stderr_tail_bytes` of the child's stderr for
292
+ /// `.collect` spawns (`""` for `.lines`, whose stderr is ignored).
293
+ /// Delivered on every collect exit — check it when `code != 0`.
294
+ stderr_tail: []const u8 = "",
295
+ /// stderr exceeded the tail capacity: `stderr_tail` is its LAST
296
+ /// bytes and earlier output was discarded.
297
+ stderr_truncated: bool = false,
298
+ };
299
+
300
+ /// The terminal outcome of one fetch. Every started fetch delivers
301
+ /// exactly one `on_response` Msg carrying one of these — failure is
302
+ /// never silent.
303
+ pub const EffectFetchOutcome = enum {
304
+ /// A response arrived. `status` is the real HTTP status — including
305
+ /// non-2xx; an HTTP-level error is still a delivered response — and
306
+ /// `body` is its (possibly truncated) body.
307
+ ok,
308
+ /// The fetch never started: all slots busy, a duplicate active key,
309
+ /// a malformed URL or non-http(s) scheme, or URL/headers/payload
310
+ /// over capacity.
311
+ rejected,
312
+ /// DNS resolution or the TCP connect failed (unknown host,
313
+ /// connection refused, network unreachable).
314
+ connect_failed,
315
+ /// TLS setup or certificate validation failed.
316
+ tls_failed,
317
+ /// The connection was established but the exchange failed mid-flight
318
+ /// (reset, malformed response, redirect loop, send failure).
319
+ protocol_failed,
320
+ /// No complete response within the fetch's timeout.
321
+ timed_out,
322
+ /// `cancel(key)` ended it.
323
+ cancelled,
324
+ };
325
+
326
+ /// Payload for `on_response` Msg constructors. Exactly one is delivered
327
+ /// per fetch — terminal, nothing for that key after it. `body` is
328
+ /// binary-safe bytes (zeros and high bits round-trip) valid only during
329
+ /// the `update` call that receives it — copy what the model keeps.
330
+ pub const EffectResponse = struct {
331
+ key: u64,
332
+ outcome: EffectFetchOutcome = .ok,
333
+ /// The HTTP status code when `outcome == .ok`; 0 otherwise.
334
+ status: u16 = 0,
335
+ /// Response body bytes; empty for every non-`.ok` outcome.
336
+ body: []const u8 = "",
337
+ /// The response body exceeded `max_effect_body_bytes`: this is its
338
+ /// first `max_effect_body_bytes` bytes and the rest was discarded.
339
+ truncated: bool = false,
340
+ /// Loop-side terminal notices evicted from the pending ring to make
341
+ /// room before this one (only under extreme rejection bursts). For
342
+ /// `.stream` fetches this additionally carries stream lines dropped
343
+ /// on a full completion queue that no later line reported. Never
344
+ /// silently zero when something was lost.
345
+ dropped_before: u32 = 0,
346
+ };
347
+
348
+ /// Which file operation a file effect performs.
349
+ pub const EffectFileOp = enum { read, write };
350
+
351
+ /// The terminal outcome of one file effect. Every started file effect
352
+ /// delivers exactly one Msg carrying one of these — failure is never
353
+ /// silent. `truncated` is a full outcome rather than a flag on `.ok`:
354
+ /// a cut JSON snapshot must not be mistaken for a whole one.
355
+ pub const EffectFileOutcome = enum {
356
+ /// The operation completed. Reads carry the whole file in `bytes`;
357
+ /// writes wrote every byte (parent directories created as needed).
358
+ ok,
359
+ /// The file does not exist (reads only — writes create the path).
360
+ not_found,
361
+ /// The OS refused: permissions, the path names a directory, disk
362
+ /// errors, an unwritable parent — anything but absence.
363
+ io_failed,
364
+ /// The file exceeds `max_effect_file_bytes` (reads only): `bytes`
365
+ /// is its first bound bytes and the rest was NOT read.
366
+ truncated,
367
+ /// The request never ran: all slots busy, a duplicate active key,
368
+ /// an empty or over-long path, or write bytes over
369
+ /// `max_effect_file_bytes`.
370
+ rejected,
371
+ /// `cancel(key)` ended it before the result was delivered. The
372
+ /// operation itself may still have completed on disk.
373
+ cancelled,
374
+ };
375
+
376
+ /// Payload for file-effect Msg constructors. Exactly one is delivered
377
+ /// per `readFile`/`writeFile` — terminal, nothing for that key after
378
+ /// it. `bytes` is a read's content (binary-safe), valid only during
379
+ /// the `update` call that receives it — copy what the model keeps.
380
+ /// Writes always deliver empty `bytes`.
381
+ pub const EffectFileResult = struct {
382
+ key: u64,
383
+ op: EffectFileOp = .read,
384
+ outcome: EffectFileOutcome = .ok,
385
+ /// Read contents: the whole file for `.ok`, the first
386
+ /// `max_effect_file_bytes` for `.truncated`, `""` otherwise (and
387
+ /// always for writes).
388
+ bytes: []const u8 = "",
389
+ /// Loop-side terminal notices evicted from the pending ring to make
390
+ /// room before this one (only under extreme rejection bursts).
391
+ /// Never silently zero when something was lost.
392
+ dropped_before: u32 = 0,
393
+ };
394
+
395
+ /// Which clipboard operation a clipboard effect performs.
396
+ pub const EffectClipboardOp = enum { read, write };
397
+
398
+ /// The terminal outcome of one clipboard effect. Every started
399
+ /// clipboard effect delivers exactly one Msg carrying one of these —
400
+ /// failure is never silent. The taxonomy is deliberately small: the
401
+ /// pasteboard is one bounded synchronous platform call, so everything
402
+ /// the OS refuses (no clipboard service on the host, content over the
403
+ /// read bound, a pasteboard error) is one explicit `.failed`.
404
+ pub const EffectClipboardOutcome = enum {
405
+ /// The operation completed: a write's text is on the system
406
+ /// clipboard whole; a read's content is in `text`.
407
+ ok,
408
+ /// The platform clipboard refused or is absent: a host without a
409
+ /// clipboard service, clipboard content over
410
+ /// `max_effect_clipboard_bytes` on read, or a pasteboard error.
411
+ failed,
412
+ /// The request never ran: all slots busy, a duplicate active key,
413
+ /// write text over `max_effect_clipboard_bytes`, or no platform
414
+ /// services bound.
415
+ rejected,
416
+ /// `cancel(key)` ended it before the result was delivered. The
417
+ /// operation itself may still have completed (real clipboard ops
418
+ /// run synchronously at request time).
419
+ cancelled,
420
+ };
421
+
422
+ /// Payload for clipboard-effect Msg constructors. Exactly one is
423
+ /// delivered per `writeClipboard`/`readClipboard` — terminal, nothing
424
+ /// for that key after it. `text` is a read's clipboard content, valid
425
+ /// only during the `update` call that receives it — copy what the
426
+ /// model keeps. Writes always deliver empty `text`.
427
+ pub const EffectClipboardResult = struct {
428
+ key: u64,
429
+ op: EffectClipboardOp = .write,
430
+ outcome: EffectClipboardOutcome = .ok,
431
+ /// Read contents for `.ok`; `""` otherwise (and always for writes).
432
+ text: []const u8 = "",
433
+ /// Loop-side terminal notices evicted from the pending ring to make
434
+ /// room before this one (only under extreme rejection bursts).
435
+ /// Never silently zero when something was lost.
436
+ dropped_before: u32 = 0,
437
+ };
438
+
439
+ /// Maximum concurrently armed fx timers per app. Timers are their own
440
+ /// fixed table: they do NOT consume `max_effects` slots or worker
441
+ /// threads (a timer is a platform service arm, not a blocking effect),
442
+ /// and timer keys are their own namespace — an fx timer key never
443
+ /// collides with a spawn/fetch/file key.
444
+ pub const max_effect_timers: usize = 16;
445
+
446
+ /// Whether an fx timer fires once and retires or keeps firing until
447
+ /// `cancelTimer`.
448
+ pub const TimerMode = enum { one_shot, repeating };
449
+
450
+ /// How an fx timer Msg came to be. Rejection is never silent: a full
451
+ /// timer table, a zero interval, or a missing platform timer service
452
+ /// delivers exactly one Msg with outcome `.rejected`.
453
+ pub const EffectTimerOutcome = enum { fired, rejected };
454
+
455
+ /// Payload for `on_fire` Msg constructors of fx timers. `timestamp_ns`
456
+ /// is the platform's fire timestamp (0 from the fake executor's
457
+ /// `fireTimer`, which has no clock).
458
+ pub const EffectTimer = struct {
459
+ key: u64,
460
+ timestamp_ns: u64 = 0,
461
+ outcome: EffectTimerOutcome = .fired,
462
+ };
463
+
464
+ /// Longest audio file path `playAudio` accepts, mirroring the platform
465
+ /// bound. Longer paths deliver exactly one `.rejected` audio event Msg.
466
+ pub const max_effect_audio_path_bytes: usize = platform.max_audio_path_bytes;
467
+
468
+ /// How an audio event Msg came to be. `loaded` acknowledges a successful
469
+ /// `playAudio` load with the platform player's duration readout — the
470
+ /// player's own estimate, NOT a measured truth: a source without a seek
471
+ /// header is extrapolated from bitrate, and a progressive stream's
472
+ /// early readout can be minutes off (later ticks may revise it). An app
473
+ /// holding an authoritative duration of its own (a catalog manifest)
474
+ /// should prefer it for display; `position` ticks at
475
+ /// the platform's coarse honest cadence (~500ms) only while playing;
476
+ /// `completed` fires exactly once at the track's natural end; `failed`
477
+ /// reports a load/decode/device failure or a platform without audio
478
+ /// playback — always as a Msg, never a crash and never silence;
479
+ /// `rejected` reports a command the effects layer refused before the
480
+ /// platform was asked (an empty or oversized path); `spectrum` carries
481
+ /// the platform's real band-magnitude analysis of the playing audio
482
+ /// (see `EffectAudio.bands`) at a steady ~25 Hz while audio is audibly
483
+ /// playing — hosts that cannot analyze simply never send it (the
484
+ /// `audio_spectrum` platform feature names the difference).
485
+ pub const EffectAudioEventKind = enum(u8) {
486
+ loaded,
487
+ position,
488
+ completed,
489
+ failed,
490
+ rejected,
491
+ spectrum,
492
+ };
493
+
494
+ /// Payload for `on_event` Msg constructors of audio effects. Positions
495
+ /// and durations are milliseconds; `playing` is the player's honest
496
+ /// state when the event was produced; `buffering` is true while a
497
+ /// streamed URL source is stalled waiting for network bytes — distinct
498
+ /// from `playing` (the transport intent): a stream can be un-paused yet
499
+ /// silent until bytes arrive, and honest UI shows that difference.
500
+ /// Local files and verified cache hits never buffer. All fields are
501
+ /// plain data — safe to store in the model, unlike the borrowed byte
502
+ /// slices other effect families carry.
503
+ pub const EffectAudio = struct {
504
+ key: u64,
505
+ kind: EffectAudioEventKind,
506
+ position_ms: u64 = 0,
507
+ duration_ms: u64 = 0,
508
+ playing: bool = false,
509
+ buffering: bool = false,
510
+ /// `.spectrum` payload, verbatim from the platform event: 32 band
511
+ /// magnitudes, log-spaced 50 Hz..16 kHz, each byte linear-in-dB from
512
+ /// the -60 dBFS floor (0) to full scale (255) — divide by 255 for a
513
+ /// 0..1 level. All zeros on every other kind. Plain bytes like the
514
+ /// rest of this struct: safe to store in the model.
515
+ bands: [platform.audio_spectrum_band_count]u8 = @splat(0),
516
+ };
517
+
518
+ /// Where the active playback's bytes actually come from — the resolved
519
+ /// end of the `playAudio` source cascade (local file, then verified
520
+ /// cache entry, then network stream). Exposed in the snapshot and the
521
+ /// fake executor's request so tests and automation can pin the
522
+ /// resolution order, not just hear audio events.
523
+ pub const EffectAudioSource = enum(u8) {
524
+ local,
525
+ cache,
526
+ stream,
527
+ };
528
+
529
+ /// Derive the conventional cache file path for a URL audio source:
530
+ /// `<cache_dir>/audio/<hash>.<ext>`, where `<hash>` is the first 16
531
+ /// bytes of the URL's SHA-256 in lowercase hex and `<ext>` is the URL's
532
+ /// file extension (kept as a decoder hint; dropped when absent or
533
+ /// implausibly long). Keying by URL hash makes the cache content-
534
+ /// addressed by source: no name collisions, no path-escaping concerns,
535
+ /// and clearing it is deleting one directory — `cache_dir` should be
536
+ /// the platform caches directory (`app_dirs` kind `.cache`), so the OS
537
+ /// already treats it as reclaimable.
538
+ pub fn audioCachePath(buffer: []u8, cache_dir: []const u8, url: []const u8) ![]const u8 {
539
+ if (cache_dir.len == 0 or url.len == 0) return error.InvalidAudioOptions;
540
+ var digest: [32]u8 = undefined;
541
+ std.crypto.hash.sha2.Sha256.hash(url, &digest, .{});
542
+ const hex = std.fmt.bytesToHex(digest[0..16].*, .lower);
543
+ const tail = if (std.mem.lastIndexOfScalar(u8, url, '/')) |slash| url[slash + 1 ..] else url;
544
+ var extension: []const u8 = "";
545
+ if (std.mem.lastIndexOfScalar(u8, tail, '.')) |dot| {
546
+ const candidate = tail[dot..];
547
+ // A plausible extension only: short, and free of query/fragment
548
+ // syntax that would smuggle URL machinery into a file name.
549
+ if (candidate.len <= 8 and std.mem.indexOfAny(u8, candidate, "?#&") == null) {
550
+ extension = candidate;
551
+ }
552
+ }
553
+ return std.fmt.bufPrint(buffer, "{s}/audio/{s}{s}", .{ cache_dir, hex, extension });
554
+ }
555
+
556
+ /// Base platform timer id for fx timers: slot N arms the platform timer
557
+ /// `effect_timer_platform_id_base + N`. Lives in the framework-reserved
558
+ /// id range (`platform.reserved_timer_id_base`) with an `0x00f7_0000`
559
+ /// ("eff") offset, distinct from the ui-app markup watch id
560
+ /// (`0xffff_ffff_2e70_a11c`) — `UiApp.handleTimer` routes ids in this
561
+ /// range back through `Effects.takeTimerMsg` and they never reach the
562
+ /// app's `on_timer` callback.
563
+ pub const effect_timer_platform_id_base: u64 = platform.reserved_timer_id_base | 0x00f7_0000;
564
+
565
+ /// Executor selection: `.real` spawns processes on worker threads;
566
+ /// `.fake` records spawn requests for tests to inspect and answer with
567
+ /// `feedLine`/`feedExit` — fully deterministic, no processes, no threads.
568
+ pub const EffectExecutor = enum { real, fake };
569
+
570
+ /// Which effect channel a journaled result came from (the session
571
+ /// record/replay taxonomy — one value per drain-delivered Msg shape,
572
+ /// plus `.clock` for journaled wall-clock reads).
573
+ pub const EffectResultKind = enum(u8) {
574
+ line = 1,
575
+ exit = 2,
576
+ response = 3,
577
+ file = 4,
578
+ clipboard = 5,
579
+ timer = 6,
580
+ clock = 7,
581
+ audio = 8,
582
+ };
583
+
584
+ /// Journaled wall-clock reads buffered for replay (`Effects.wallMs`).
585
+ /// Bounded like everything else: more reads per drain window than this
586
+ /// is a runaway loop, not a session shape.
587
+ pub const max_effect_replay_clock_entries: usize = 64;
588
+
589
+ /// One drained effect result, flattened for the session journal: the
590
+ /// exact payload `update` received, Msg-type-erased so the recorder and
591
+ /// replayer need no knowledge of the app's Msg union. Only the fields
592
+ /// for `kind` are meaningful; the rest keep their defaults.
593
+ pub const EffectResultRecord = struct {
594
+ kind: EffectResultKind,
595
+ key: u64,
596
+ /// Line bytes / collected stdout / response body / file bytes /
597
+ /// clipboard text.
598
+ payload: []const u8 = "",
599
+ /// Collect-exit stderr tail.
600
+ stderr_tail: []const u8 = "",
601
+ truncated: bool = false,
602
+ /// `dropped_before` for lines/terminals, `dropped_lines` for exits.
603
+ dropped: u32 = 0,
604
+ code: i32 = 0,
605
+ exit_reason: EffectExitReason = .exited,
606
+ output_truncated: bool = false,
607
+ stderr_truncated: bool = false,
608
+ status: u16 = 0,
609
+ fetch_outcome: EffectFetchOutcome = .ok,
610
+ file_op: EffectFileOp = .read,
611
+ file_outcome: EffectFileOutcome = .ok,
612
+ clipboard_op: EffectClipboardOp = .write,
613
+ clipboard_outcome: EffectClipboardOutcome = .ok,
614
+ timer_timestamp_ns: u64 = 0,
615
+ timer_outcome: EffectTimerOutcome = .fired,
616
+ /// `.clock` records: the wall-clock value `Effects.wallMs` returned.
617
+ clock_wall_ms: i64 = 0,
618
+ /// `.audio` records: the delivered audio event, verbatim.
619
+ audio_kind: EffectAudioEventKind = .position,
620
+ audio_position_ms: u64 = 0,
621
+ audio_duration_ms: u64 = 0,
622
+ audio_playing: bool = false,
623
+ audio_buffering: bool = false,
624
+ /// `.spectrum` audio records: the delivered band bytes, verbatim —
625
+ /// the honest non-determinism (a real FFT of real audio) recorded at
626
+ /// the boundary so replay repaints identical bars.
627
+ audio_bands: [platform.audio_spectrum_band_count]u8 = @splat(0),
628
+ };
629
+
630
+ /// Type-erased sink the drain reports every delivered result to while a
631
+ /// session is being recorded (`bindJournal`). Called on the loop thread,
632
+ /// immediately before the Msg constructed from the same payload runs
633
+ /// through `update` — so the journal holds exactly what the app saw.
634
+ pub const EffectJournal = struct {
635
+ context: *anyopaque,
636
+ record_fn: *const fn (context: *anyopaque, record: EffectResultRecord) void,
637
+ };
638
+
639
+ /// Tiny spin lock over `std.atomic.Mutex` (0.16 has no blocking
640
+ /// thread mutex outside `Io`). Every guarded section here is a bounded
641
+ /// copy of at most one queue entry, so spinning is microseconds worst
642
+ /// case and never blocks on I/O.
643
+ const SpinMutex = struct {
644
+ inner: std.atomic.Mutex = .unlocked,
645
+
646
+ fn lock(self: *SpinMutex) void {
647
+ while (!self.inner.tryLock()) std.atomic.spinLoopHint();
648
+ }
649
+
650
+ fn unlock(self: *SpinMutex) void {
651
+ self.inner.unlock();
652
+ }
653
+ };
654
+
655
+ /// The spawned-child environment when the host never bound one through
656
+ /// `bindEnviron` (embed and mobile hosts have no `std.process.Init` to
657
+ /// take it from). Windows reads the live PEB block (`.global`); POSIX
658
+ /// hosts that link libc read `std.c.environ`; anything else falls back
659
+ /// to `.empty` — spawn and fetch still work, children just start with
660
+ /// a clean environment.
661
+ fn fallbackEnviron() std.process.Environ {
662
+ if (std.process.Environ.Block == std.process.Environ.GlobalBlock) {
663
+ return .{ .block = .global };
664
+ } else if (builtin.link_libc and std.process.Environ.Block == std.process.Environ.PosixBlock) {
665
+ const envp = std.c.environ;
666
+ var count: usize = 0;
667
+ while (envp[count] != null) : (count += 1) {}
668
+ return .{ .block = .{ .slice = envp[0..count :null] } };
669
+ } else {
670
+ return .empty;
671
+ }
672
+ }
673
+
674
+ /// `std.Io.Threaded` (the real executor's io) does not exist on
675
+ /// freestanding targets — the docs' live-preview wasm host compiles
676
+ /// this runtime to wasm32-freestanding. There the executor io compiles
677
+ /// away: `ensureIo` reports unsupported, which surfaces through the
678
+ /// standard `.rejected` outcome. Effects never actually run in that
679
+ /// host, so nothing is lost.
680
+ const io_threaded_supported = builtin.target.os.tag != .freestanding;
681
+ const IoThreaded = if (io_threaded_supported) std.Io.Threaded else void;
682
+
683
+ /// Map a fetch-side error onto the delivered failure taxonomy. The
684
+ /// worker refines `.cancelled` into `.timed_out` when the deadline (not
685
+ /// the app) interrupted the exchange.
686
+ fn classifyFetchError(err: anyerror) EffectFetchOutcome {
687
+ return switch (err) {
688
+ error.Canceled => .cancelled,
689
+ // DNS resolution.
690
+ error.UnknownHostName,
691
+ error.ResolvConfParseFailed,
692
+ error.InvalidDnsARecord,
693
+ error.InvalidDnsAAAARecord,
694
+ error.InvalidDnsCnameRecord,
695
+ error.NameServerFailure,
696
+ error.NoAddressReturned,
697
+ error.DetectingNetworkConfigurationFailed,
698
+ // TCP connect.
699
+ error.AddressUnavailable,
700
+ error.AddressFamilyUnsupported,
701
+ error.ConnectionPending,
702
+ error.ConnectionRefused,
703
+ error.HostUnreachable,
704
+ error.NetworkUnreachable,
705
+ error.NetworkDown,
706
+ error.Timeout,
707
+ // The worker's marker for an untyped failure while establishing
708
+ // the connection (see `runFetch`).
709
+ error.ConnectPhaseFailed,
710
+ => .connect_failed,
711
+ // TLS.
712
+ error.TlsInitializationFailed,
713
+ error.CertificateBundleLoadFailure,
714
+ => .tls_failed,
715
+ // Requests that could never be sent (pre-validated in `fetch`,
716
+ // so reaching these here still reports honestly).
717
+ error.UnsupportedUriScheme,
718
+ error.UriMissingHost,
719
+ => .rejected,
720
+ else => .protocol_failed,
721
+ };
722
+ }
723
+
724
+ pub fn Effects(comptime Msg: type) type {
725
+ return struct {
726
+ const Self = @This();
727
+
728
+ pub const LineMsgFn = *const fn (line: EffectLine) Msg;
729
+ pub const ExitMsgFn = *const fn (exit: EffectExit) Msg;
730
+ pub const ResponseMsgFn = *const fn (response: EffectResponse) Msg;
731
+ pub const FileMsgFn = *const fn (result: EffectFileResult) Msg;
732
+ pub const ClipboardMsgFn = *const fn (result: EffectClipboardResult) Msg;
733
+ pub const TimerMsgFn = *const fn (timer: EffectTimer) Msg;
734
+ pub const AudioMsgFn = *const fn (event: EffectAudio) Msg;
735
+
736
+ /// Comptime Msg constructor for `on_line`, following
737
+ /// `canvas.Ui(Msg).inputMsg`: `lineMsg(.agent_line)` builds
738
+ /// `Msg{ .agent_line = line }` — the variant's payload type must
739
+ /// be `native_sdk.EffectLine`.
740
+ pub fn lineMsg(comptime tag: std.meta.Tag(Msg)) LineMsgFn {
741
+ return struct {
742
+ fn make(line: EffectLine) Msg {
743
+ return @unionInit(Msg, @tagName(tag), line);
744
+ }
745
+ }.make;
746
+ }
747
+
748
+ /// Comptime Msg constructor for `on_exit`: `exitMsg(.agent_done)`
749
+ /// builds `Msg{ .agent_done = exit }` — the variant's payload
750
+ /// type must be `native_sdk.EffectExit`.
751
+ pub fn exitMsg(comptime tag: std.meta.Tag(Msg)) ExitMsgFn {
752
+ return struct {
753
+ fn make(exit: EffectExit) Msg {
754
+ return @unionInit(Msg, @tagName(tag), exit);
755
+ }
756
+ }.make;
757
+ }
758
+
759
+ /// Comptime Msg constructor for `on_response`:
760
+ /// `responseMsg(.issues_fetched)` builds
761
+ /// `Msg{ .issues_fetched = response }` — the variant's payload
762
+ /// type must be `native_sdk.EffectResponse`.
763
+ pub fn responseMsg(comptime tag: std.meta.Tag(Msg)) ResponseMsgFn {
764
+ return struct {
765
+ fn make(response: EffectResponse) Msg {
766
+ return @unionInit(Msg, @tagName(tag), response);
767
+ }
768
+ }.make;
769
+ }
770
+
771
+ /// Comptime Msg constructor for `on_result` of file effects:
772
+ /// `fileMsg(.snapshot_saved)` builds
773
+ /// `Msg{ .snapshot_saved = result }` — the variant's payload
774
+ /// type must be `native_sdk.EffectFileResult`.
775
+ pub fn fileMsg(comptime tag: std.meta.Tag(Msg)) FileMsgFn {
776
+ return struct {
777
+ fn make(result: EffectFileResult) Msg {
778
+ return @unionInit(Msg, @tagName(tag), result);
779
+ }
780
+ }.make;
781
+ }
782
+
783
+ /// Comptime Msg constructor for `on_result` of clipboard
784
+ /// effects: `clipboardMsg(.copied)` builds
785
+ /// `Msg{ .copied = result }` — the variant's payload type must
786
+ /// be `native_sdk.EffectClipboardResult`.
787
+ pub fn clipboardMsg(comptime tag: std.meta.Tag(Msg)) ClipboardMsgFn {
788
+ return struct {
789
+ fn make(result: EffectClipboardResult) Msg {
790
+ return @unionInit(Msg, @tagName(tag), result);
791
+ }
792
+ }.make;
793
+ }
794
+
795
+ /// Comptime Msg constructor for `on_fire` of fx timers:
796
+ /// `timerMsg(.refresh_tick)` builds
797
+ /// `Msg{ .refresh_tick = timer }` — the variant's payload type
798
+ /// must be `native_sdk.EffectTimer`.
799
+ pub fn timerMsg(comptime tag: std.meta.Tag(Msg)) TimerMsgFn {
800
+ return struct {
801
+ fn make(timer: EffectTimer) Msg {
802
+ return @unionInit(Msg, @tagName(tag), timer);
803
+ }
804
+ }.make;
805
+ }
806
+
807
+ /// Comptime Msg constructor for `on_event` of audio playback:
808
+ /// `audioMsg(.audio_event)` builds
809
+ /// `Msg{ .audio_event = event }` — the variant's payload type
810
+ /// must be `native_sdk.EffectAudio`.
811
+ pub fn audioMsg(comptime tag: std.meta.Tag(Msg)) AudioMsgFn {
812
+ return struct {
813
+ fn make(event: EffectAudio) Msg {
814
+ return @unionInit(Msg, @tagName(tag), event);
815
+ }
816
+ }.make;
817
+ }
818
+
819
+ pub const SpawnOptions = struct {
820
+ /// Caller-chosen identity, stored in the model. Must not
821
+ /// collide with another still-running effect.
822
+ key: u64,
823
+ argv: []const []const u8,
824
+ /// Written to the child's stdin once, then stdin closes.
825
+ stdin: ?[]const u8 = null,
826
+ /// `.lines` (default) streams stdout through `on_line`;
827
+ /// `.collect` accumulates whole stdout (up to
828
+ /// `max_effect_collect_bytes`) plus the stderr tail and
829
+ /// delivers both on the exit Msg — `on_line` is never called
830
+ /// for a collect spawn.
831
+ output: EffectOutputMode = .lines,
832
+ /// Per-spawn delivered-line bound for `.lines` output.
833
+ /// Line-oriented agent CLIs (`claude -p --output-format
834
+ /// stream-json`) emit whole events as single NDJSON lines
835
+ /// far beyond the 4 KiB default; raise this up to
836
+ /// `max_effect_line_bytes_ceiling` (256 KiB) to receive them
837
+ /// intact. Requests above the ceiling (or zero) are
838
+ /// rejected through `on_exit`, never silently clamped.
839
+ /// Bounds above the default heap-allocate the spawn's line
840
+ /// buffer. Ignored by `.collect` spawns.
841
+ max_line_bytes: usize = max_effect_line_bytes,
842
+ on_line: ?LineMsgFn = null,
843
+ on_exit: ?ExitMsgFn = null,
844
+ };
845
+
846
+ /// A recorded spawn request, exposed by the fake executor for
847
+ /// test assertions. Slices point into slot storage and stay
848
+ /// valid until the slot's effect exits.
849
+ pub const SpawnRequest = struct {
850
+ key: u64,
851
+ argv: []const []const u8,
852
+ stdin: []const u8,
853
+ output: EffectOutputMode = .lines,
854
+ max_line_bytes: usize = max_effect_line_bytes,
855
+ };
856
+
857
+ pub const FetchOptions = struct {
858
+ /// Caller-chosen identity, stored in the model. Must not
859
+ /// collide with another still-running effect (spawn or
860
+ /// fetch — they share the key space and the slots).
861
+ key: u64,
862
+ method: std.http.Method = .GET,
863
+ /// http:// or https:// URL, at most `max_effect_url_bytes`.
864
+ url: []const u8,
865
+ /// Extra request headers; names and values are copied into
866
+ /// slot storage at call time.
867
+ headers: []const std.http.Header = &.{},
868
+ /// Request payload (sent with a content-length). `null`
869
+ /// sends no body.
870
+ body: ?[]const u8 = null,
871
+ /// Whole-exchange timeout in milliseconds; expiry delivers
872
+ /// the terminal Msg with outcome `.timed_out`. For
873
+ /// `.stream` fetches this covers the stream's entire
874
+ /// lifetime — raise it for endpoints that hold the
875
+ /// connection open (sandbox exec, agent event streams).
876
+ timeout_ms: u32 = default_effect_fetch_timeout_ms,
877
+ /// `.buffered` (default) delivers the whole body on the
878
+ /// terminal Msg; `.stream` frames the body into `on_line`
879
+ /// Msgs as lines arrive (the spawn `.lines` contract over
880
+ /// HTTP) with the terminal Msg carrying only the status.
881
+ response: FetchResponseMode = .buffered,
882
+ /// Line Msg constructor for `.stream` fetches; unused (and
883
+ /// never called) in `.buffered` mode.
884
+ on_line: ?LineMsgFn = null,
885
+ /// Per-fetch delivered-line bound for `.stream` responses,
886
+ /// mirroring `SpawnOptions.max_line_bytes` (same ceiling,
887
+ /// same rejection of over-ceiling or zero requests).
888
+ /// Ignored by `.buffered` fetches.
889
+ max_line_bytes: usize = max_effect_line_bytes,
890
+ on_response: ?ResponseMsgFn = null,
891
+ };
892
+
893
+ /// A recorded fetch request, exposed by the fake executor for
894
+ /// test assertions. Slices point into slot storage and stay
895
+ /// valid until the fetch's response is drained.
896
+ pub const FetchRequest = struct {
897
+ key: u64,
898
+ method: std.http.Method,
899
+ url: []const u8,
900
+ headers: []const std.http.Header,
901
+ body: []const u8,
902
+ response: FetchResponseMode = .buffered,
903
+ max_line_bytes: usize = max_effect_line_bytes,
904
+ };
905
+
906
+ pub const WriteFileOptions = struct {
907
+ /// Caller-chosen identity, stored in the model. Shares the
908
+ /// key space and the `max_effects` slots with spawns and
909
+ /// fetches.
910
+ key: u64,
911
+ /// The file to write, at most `max_effect_file_path_bytes`.
912
+ /// Missing parent directories are created; an existing file
913
+ /// is replaced whole.
914
+ path: []const u8,
915
+ /// The whole file content, at most `max_effect_file_bytes`
916
+ /// — larger is rejected outright (a partial write would
917
+ /// corrupt the file; there is no write-side truncation).
918
+ /// Copied at call time; the caller's buffer may be reused
919
+ /// immediately.
920
+ bytes: []const u8,
921
+ on_result: ?FileMsgFn = null,
922
+ };
923
+
924
+ pub const ReadFileOptions = struct {
925
+ /// Caller-chosen identity, stored in the model. Shares the
926
+ /// key space and the `max_effects` slots with spawns and
927
+ /// fetches.
928
+ key: u64,
929
+ /// The file to read, at most `max_effect_file_path_bytes`.
930
+ path: []const u8,
931
+ on_result: ?FileMsgFn = null,
932
+ };
933
+
934
+ /// A recorded file request, exposed by the fake executor for
935
+ /// test assertions. Slices point into slot storage and stay
936
+ /// valid until the result is fed and drained.
937
+ pub const FileRequest = struct {
938
+ key: u64,
939
+ op: EffectFileOp,
940
+ path: []const u8,
941
+ /// The bytes a `writeFile` would write; `""` for reads.
942
+ bytes: []const u8 = "",
943
+ };
944
+
945
+ pub const WriteClipboardOptions = struct {
946
+ /// Caller-chosen identity, stored in the model. Shares the
947
+ /// key space and the `max_effects` slots with spawns,
948
+ /// fetches, and file effects.
949
+ key: u64,
950
+ /// The text to place on the system clipboard, at most
951
+ /// `max_effect_clipboard_bytes` — larger is rejected
952
+ /// outright (a cut clipboard string must never pass for the
953
+ /// whole one). Copied at call time; the caller's buffer may
954
+ /// be reused immediately.
955
+ text: []const u8,
956
+ on_result: ?ClipboardMsgFn = null,
957
+ };
958
+
959
+ pub const ReadClipboardOptions = struct {
960
+ /// Caller-chosen identity, stored in the model. Shares the
961
+ /// key space and the `max_effects` slots with spawns,
962
+ /// fetches, and file effects.
963
+ key: u64,
964
+ on_result: ?ClipboardMsgFn = null,
965
+ };
966
+
967
+ /// A recorded clipboard request, exposed by the fake executor
968
+ /// for test assertions. `text` points into slot storage and
969
+ /// stays valid until the result is fed and drained.
970
+ pub const ClipboardRequest = struct {
971
+ key: u64,
972
+ op: EffectClipboardOp,
973
+ /// The text a `writeClipboard` would write; `""` for reads.
974
+ text: []const u8 = "",
975
+ };
976
+
977
+ pub const StartTimerOptions = struct {
978
+ /// Caller-chosen identity, stored in the model. Timer keys
979
+ /// are their own namespace: they never collide with (and are
980
+ /// never checked against) spawn/fetch/file keys. Starting a
981
+ /// key that is already an active timer REPLACES it — the
982
+ /// interval, mode, and `on_fire` update in place and the
983
+ /// same platform timer re-arms, the friendly behavior for an
984
+ /// auto-refresh whose cadence the model changes.
985
+ key: u64,
986
+ /// Fire interval in milliseconds. Zero is rejected (one Msg
987
+ /// with outcome `.rejected`), never silently clamped.
988
+ interval_ms: u64,
989
+ /// `.one_shot` (default) fires once and retires the timer;
990
+ /// `.repeating` fires until `cancelTimer(key)`.
991
+ mode: TimerMode = .one_shot,
992
+ on_fire: ?TimerMsgFn = null,
993
+ };
994
+
995
+ pub const PlayAudioOptions = struct {
996
+ /// Caller-chosen identity, stored in the model and echoed in
997
+ /// every event for this playback. Audio keys are their own
998
+ /// namespace (like timer keys); a new `playAudio` replaces
999
+ /// the previous playback outright — one player is the whole
1000
+ /// surface.
1001
+ key: u64,
1002
+ /// Local file path, tried FIRST. May be empty when `url` is
1003
+ /// set (URL-only playback). A present-but-missing file falls
1004
+ /// through to `url` when one is given; with no `url` (or any
1005
+ /// other load failure) one `.failed` event reports it. Every
1006
+ /// string here is copied at call time — the caller's buffers
1007
+ /// may be reused immediately — and each is bounded by
1008
+ /// `max_effect_audio_path_bytes` (longer, or path AND url
1009
+ /// both empty, is rejected with one `.rejected` event).
1010
+ path: []const u8 = "",
1011
+ /// http(s) source, tried when the local path is absent or
1012
+ /// missing. The platform resolves it honestly: a verified
1013
+ /// cache entry at `cache_path` plays locally (no network);
1014
+ /// otherwise playback STREAMS progressively — audible before
1015
+ /// the download finishes — while the bytes fill the cache
1016
+ /// for next time. Empty means local-only (today's behavior).
1017
+ url: []const u8 = "",
1018
+ /// Where the URL's bytes are cached, and the cache policy in
1019
+ /// one field: empty disables caching (stream-only). The
1020
+ /// platform writes beside this path and atomically renames
1021
+ /// into place only after the size verifies, so a partial
1022
+ /// download never occupies the cache name.
1023
+ cache_path: []const u8 = "",
1024
+ /// The track's known byte size (from a manifest), the cache
1025
+ /// integrity gate: a cache entry whose size disagrees is
1026
+ /// discarded and re-streamed, and a finished download that
1027
+ /// disagrees is never installed. Zero means "unknown" —
1028
+ /// existence alone then qualifies a cache entry.
1029
+ expected_bytes: u64 = 0,
1030
+ /// Msg constructor every playback event flows through (see
1031
+ /// `audioMsg`). Without one, playback still runs; the app
1032
+ /// just hears nothing back.
1033
+ on_event: ?AudioMsgFn = null,
1034
+ };
1035
+
1036
+ /// A recorded fx timer, exposed by the fake executor for test
1037
+ /// assertions.
1038
+ pub const TimerRequest = struct {
1039
+ key: u64,
1040
+ interval_ms: u64,
1041
+ mode: TimerMode,
1042
+ };
1043
+
1044
+ const TimerSlot = struct {
1045
+ active: bool = false,
1046
+ fake: bool = false,
1047
+ key: u64 = 0,
1048
+ mode: TimerMode = .one_shot,
1049
+ interval_ms: u64 = 0,
1050
+ on_fire: ?TimerMsgFn = null,
1051
+ };
1052
+
1053
+ /// The single audio playback channel — one player is the whole
1054
+ /// platform surface, so the effects layer holds exactly one.
1055
+ /// Like timers it is a platform service arm, not a worker-thread
1056
+ /// effect: it consumes no `max_effects` slots and its key is its
1057
+ /// own namespace. The mirrors below track what the app has been
1058
+ /// told (commands optimistically, platform events authoritatively)
1059
+ /// so the automation snapshot can report playback state honestly.
1060
+ const AudioChannel = struct {
1061
+ active: bool = false,
1062
+ fake: bool = false,
1063
+ key: u64 = 0,
1064
+ on_event: ?AudioMsgFn = null,
1065
+ playing: bool = false,
1066
+ /// Where the resolved playback's bytes come from: `.local`
1067
+ /// until the URL branch of the cascade runs, then whatever
1068
+ /// the platform answered (`.cache` or `.stream`).
1069
+ source: EffectAudioSource = .local,
1070
+ /// True while a stream is stalled waiting for bytes. Set
1071
+ /// optimistically when a stream starts (nothing has arrived
1072
+ /// yet), cleared by the platform's `.loaded` acknowledgment
1073
+ /// and tracked from event flags after that.
1074
+ buffering: bool = false,
1075
+ position_ms: u64 = 0,
1076
+ duration_ms: u64 = 0,
1077
+ volume: f32 = 1.0,
1078
+ /// The latest `.spectrum` band bytes and a lifetime delivery
1079
+ /// count for THIS playback — snapshot evidence that analysis
1080
+ /// is flowing (the count moves) and freezing on pause (it
1081
+ /// holds). Reset with the channel on every new `playAudio`.
1082
+ spectrum_bands: [platform.audio_spectrum_band_count]u8 = @splat(0),
1083
+ spectrum_events: u64 = 0,
1084
+ path_buffer: [max_effect_audio_path_bytes]u8 = undefined,
1085
+ path_len: usize = 0,
1086
+ url_buffer: [max_effect_audio_path_bytes]u8 = undefined,
1087
+ url_len: usize = 0,
1088
+ cache_path_buffer: [max_effect_audio_path_bytes]u8 = undefined,
1089
+ cache_path_len: usize = 0,
1090
+ expected_bytes: u64 = 0,
1091
+
1092
+ fn path(channel: *const AudioChannel) []const u8 {
1093
+ return channel.path_buffer[0..channel.path_len];
1094
+ }
1095
+
1096
+ fn url(channel: *const AudioChannel) []const u8 {
1097
+ return channel.url_buffer[0..channel.url_len];
1098
+ }
1099
+
1100
+ fn cachePath(channel: *const AudioChannel) []const u8 {
1101
+ return channel.cache_path_buffer[0..channel.cache_path_len];
1102
+ }
1103
+ };
1104
+
1105
+ /// Playback state the automation snapshot exposes: honest — it
1106
+ /// reports what the platform has told us, not what the UI wishes.
1107
+ pub const AudioSnapshot = struct {
1108
+ active: bool = false,
1109
+ key: u64 = 0,
1110
+ playing: bool = false,
1111
+ buffering: bool = false,
1112
+ source: EffectAudioSource = .local,
1113
+ position_ms: u64 = 0,
1114
+ duration_ms: u64 = 0,
1115
+ /// Spectrum mirrors (see `AudioChannel`): zero events means
1116
+ /// no analysis has arrived for this playback — an honest
1117
+ /// "this host does not analyze" is visible right here.
1118
+ spectrum_bands: [platform.audio_spectrum_band_count]u8 = @splat(0),
1119
+ spectrum_events: u64 = 0,
1120
+ };
1121
+
1122
+ /// A recorded audio playback request, exposed by the fake
1123
+ /// executor for test assertions. The strings borrow the
1124
+ /// channel's storage — valid until the next `playAudio`.
1125
+ pub const AudioRequest = struct {
1126
+ key: u64,
1127
+ path: []const u8,
1128
+ url: []const u8,
1129
+ cache_path: []const u8,
1130
+ expected_bytes: u64,
1131
+ playing: bool,
1132
+ position_ms: u64,
1133
+ volume: f32,
1134
+ };
1135
+
1136
+ /// `draining`: the worker is done and the terminal entry is
1137
+ /// queued, but the slot still owns a heap buffer (a fetch's body
1138
+ /// or a collect spawn's stdout) until the drain delivers (and
1139
+ /// thereby retires) it.
1140
+ const SlotState = enum(u8) { idle, running, done, draining };
1141
+
1142
+ const SlotKind = enum(u8) { spawn, fetch, file, clipboard };
1143
+
1144
+ const EntryKind = enum(u8) { line, exit, response, file, clipboard };
1145
+
1146
+ const Entry = struct {
1147
+ kind: EntryKind = .line,
1148
+ slot_index: u16 = 0,
1149
+ generation: u32 = 0,
1150
+ key: u64 = 0,
1151
+ /// Line length for `.line` entries; body length for
1152
+ /// `.response` entries (the bytes live in the slot's fetch
1153
+ /// buffer, not here).
1154
+ line_len: u32 = 0,
1155
+ truncated: bool = false,
1156
+ dropped_before: u32 = 0,
1157
+ code: i32 = 0,
1158
+ reason: EffectExitReason = .exited,
1159
+ dropped_lines: u32 = 0,
1160
+ status: u16 = 0,
1161
+ outcome: EffectFetchOutcome = .ok,
1162
+ /// `.file` entries: the operation and its terminal outcome.
1163
+ /// A read's bytes stay in the slot's heap buffer (taken at
1164
+ /// drain, exactly like a fetch body) with their length in
1165
+ /// `line_len`.
1166
+ file_op: EffectFileOp = .read,
1167
+ file_outcome: EffectFileOutcome = .ok,
1168
+ /// `.clipboard` entries: the operation and its terminal
1169
+ /// outcome. A read's text stays in the slot's heap buffer
1170
+ /// (taken at drain, like a fetch body) with its length in
1171
+ /// `line_len`.
1172
+ clipboard_op: EffectClipboardOp = .write,
1173
+ clipboard_outcome: EffectClipboardOutcome = .ok,
1174
+ /// `.exit` entries of `.collect` spawns: the collected stdout
1175
+ /// stays in the slot's heap buffer (taken at drain, like a
1176
+ /// fetch body); the stderr tail rides in `line_bytes` with
1177
+ /// its length in `line_len`.
1178
+ collect: bool = false,
1179
+ collect_len: u32 = 0,
1180
+ collect_truncated: bool = false,
1181
+ stderr_truncated: bool = false,
1182
+ line_fn: ?LineMsgFn = null,
1183
+ exit_fn: ?ExitMsgFn = null,
1184
+ response_fn: ?ResponseMsgFn = null,
1185
+ file_fn: ?FileMsgFn = null,
1186
+ clipboard_fn: ?ClipboardMsgFn = null,
1187
+ /// `.line` entries whose payload exceeds the inline buffer
1188
+ /// (a raised `max_line_bytes` bound): the bytes ride in this
1189
+ /// heap allocation instead of `line_bytes`. Owned by the
1190
+ /// entry once enqueued — the drain takes it (freed when the
1191
+ /// next line drains) and every queue-clearing path frees it.
1192
+ heap_line: ?[]u8 = null,
1193
+ line_bytes: [max_effect_line_bytes]u8 = undefined,
1194
+ };
1195
+
1196
+ /// A loop-thread-produced terminal Msg awaiting drain: a spawn
1197
+ /// rejection or fake exit (`.exit`) or a fetch rejection or fake
1198
+ /// cancel (`.response`). Response bodies are always empty here.
1199
+ const PendingMsg = union(enum) {
1200
+ exit: struct { exit: EffectExit, exit_fn: ?ExitMsgFn },
1201
+ response: struct { response: EffectResponse, response_fn: ?ResponseMsgFn },
1202
+ file: struct { result: EffectFileResult, file_fn: ?FileMsgFn },
1203
+ clipboard: struct { result: EffectClipboardResult, clipboard_fn: ?ClipboardMsgFn },
1204
+ timer: struct { timer: EffectTimer, timer_fn: ?TimerMsgFn },
1205
+ /// `resolve`: a fed audio event (fake executor / replay)
1206
+ /// whose key and handler come from the live channel at
1207
+ /// delivery time — exactly how a platform event resolves in
1208
+ /// `takeAudioMsg`. Non-resolving entries (rejections and
1209
+ /// synchronous failures) are fully formed at enqueue.
1210
+ audio: struct { event: EffectAudio, audio_fn: ?AudioMsgFn, resolve: bool },
1211
+
1212
+ fn addDropped(pending: *PendingMsg, count: u32) void {
1213
+ switch (pending.*) {
1214
+ .exit => |*entry| entry.exit.dropped_lines +|= count,
1215
+ .response => |*entry| entry.response.dropped_before +|= count,
1216
+ .file => |*entry| entry.result.dropped_before +|= count,
1217
+ .clipboard => |*entry| entry.result.dropped_before +|= count,
1218
+ // EffectTimer carries no drop counter; a repeating
1219
+ // timer's next fire replaces the lost one anyway.
1220
+ .timer => {},
1221
+ // EffectAudio carries no drop counter either; the
1222
+ // next position tick supersedes a lost one.
1223
+ .audio => {},
1224
+ }
1225
+ }
1226
+
1227
+ fn droppedCount(pending: *const PendingMsg) u32 {
1228
+ return switch (pending.*) {
1229
+ .exit => |entry| entry.exit.dropped_lines,
1230
+ .response => |entry| entry.response.dropped_before,
1231
+ .file => |entry| entry.result.dropped_before,
1232
+ .clipboard => |entry| entry.result.dropped_before,
1233
+ .timer => 0,
1234
+ .audio => 0,
1235
+ };
1236
+ }
1237
+ };
1238
+
1239
+ const Slot = struct {
1240
+ state: std.atomic.Value(SlotState) = std.atomic.Value(SlotState).init(.idle),
1241
+ generation: u32 = 0,
1242
+ key: u64 = 0,
1243
+ kind: SlotKind = .spawn,
1244
+ fake: bool = false,
1245
+ on_line: ?LineMsgFn = null,
1246
+ on_exit: ?ExitMsgFn = null,
1247
+ on_response: ?ResponseMsgFn = null,
1248
+ on_file: ?FileMsgFn = null,
1249
+ on_clipboard: ?ClipboardMsgFn = null,
1250
+ /// Set by `cancel` before any kill attempt; read by the
1251
+ /// worker so a cancel that lands before the process spawns
1252
+ /// still kills it.
1253
+ cancel_requested: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
1254
+ /// Loop-thread bookkeeping: the generation whose queued
1255
+ /// lines the drain discards and whose exit reports
1256
+ /// `.cancelled`. Zero means none (generations start at 1).
1257
+ cancelled_generation: u32 = 0,
1258
+ /// Guards `child_id`/`reaping` between the worker and
1259
+ /// `cancel` on the loop thread: a kill is only sent while
1260
+ /// the worker has not started reaping, so the pid/handle is
1261
+ /// guaranteed un-reaped (alive or zombie) when signaled.
1262
+ child_mutex: SpinMutex = .{},
1263
+ child_id: ?std.process.Child.Id = null,
1264
+ reaping: bool = false,
1265
+ /// Producer-side drop accounting (worker in real mode, loop
1266
+ /// thread in fake mode; never both).
1267
+ dropped_pending: u32 = 0,
1268
+ dropped_total: u32 = 0,
1269
+ argv_slices: [max_effect_argv][]const u8 = undefined,
1270
+ argv_count: usize = 0,
1271
+ argv_storage: [max_effect_argv_bytes]u8 = undefined,
1272
+ stdin_storage: [max_effect_stdin_bytes]u8 = undefined,
1273
+ stdin_len: usize = 0,
1274
+ // ---- line-framing fields (.lines spawns, .stream fetches) ----
1275
+ /// Effective per-line bound: the default or the accepted
1276
+ /// `max_line_bytes` override.
1277
+ line_limit: usize = max_effect_line_bytes,
1278
+ /// Heap line-accumulation buffer, allocated per accepted
1279
+ /// effect whose `max_line_bytes` exceeds the default (the
1280
+ /// worker frames lines into it instead of its stack
1281
+ /// buffer). Owned by the slot; freed on reuse and deinit.
1282
+ line_buffer: ?[]u8 = null,
1283
+ // ---- collect-mode fields (kind == .spawn, output == .collect) ----
1284
+ output_mode: EffectOutputMode = .lines,
1285
+ /// Heap buffer per accepted `.collect` spawn
1286
+ /// (`max_effect_collect_bytes` of stdout space). Owned by the
1287
+ /// slot until the drain delivers the exit (taken into
1288
+ /// `drain_collect_output`) or `deinit` sweeps it.
1289
+ collect_buffer: ?[]u8 = null,
1290
+ collect_len: usize = 0,
1291
+ collect_truncated: bool = false,
1292
+ /// Ring of the child's most recent stderr bytes. Written by
1293
+ /// the stderr reader (worker-side thread in real mode, loop
1294
+ /// thread in fake mode); read only after the child is done.
1295
+ stderr_ring: [max_effect_stderr_tail_bytes]u8 = undefined,
1296
+ /// Total stderr bytes seen; beyond the ring capacity means
1297
+ /// the tail is truncated.
1298
+ stderr_total: usize = 0,
1299
+ // ---- file-only fields (kind == .file) ----
1300
+ file_op: EffectFileOp = .read,
1301
+ // ---- clipboard-only fields (kind == .clipboard) ----
1302
+ clipboard_op: EffectClipboardOp = .write,
1303
+ // ---- fetch/file fields ----
1304
+ /// `.stream` frames the response body into line entries;
1305
+ /// `.buffered` delivers it whole on the terminal entry.
1306
+ fetch_response_mode: FetchResponseMode = .buffered,
1307
+ method: std.http.Method = .GET,
1308
+ /// A fetch's URL — and a file effect's path (they never
1309
+ /// coexist in one slot; `max_effect_file_path_bytes` fits).
1310
+ url_storage: [max_effect_url_bytes]u8 = undefined,
1311
+ url_len: usize = 0,
1312
+ header_storage: [max_effect_fetch_header_bytes]u8 = undefined,
1313
+ header_slices: [max_effect_fetch_headers]std.http.Header = undefined,
1314
+ header_count: usize = 0,
1315
+ timeout_ms: u32 = default_effect_fetch_timeout_ms,
1316
+ /// Heap buffer per accepted fetch: request payload copy
1317
+ /// followed by `max_effect_body_bytes` of response space.
1318
+ /// File effects use it too: a write's payload copy, or a
1319
+ /// read's `max_effect_file_bytes + 1` of content space (the
1320
+ /// spare byte detects over-bound files). Owned by the slot
1321
+ /// until the drain delivers the terminal Msg (taken into
1322
+ /// `drain_fetch_body`) or `deinit` sweeps it.
1323
+ fetch_buffer: ?[]u8 = null,
1324
+ payload_len: usize = 0,
1325
+ /// Terminal fetch state, written by the fetch task before
1326
+ /// `fetch_done`, published to the loop thread by the queue.
1327
+ body_len: usize = 0,
1328
+ fetch_status: u16 = 0,
1329
+ fetch_outcome: EffectFetchOutcome = .protocol_failed,
1330
+ fetch_truncated: bool = false,
1331
+ /// Set by the fetch task after its final slot writes; the
1332
+ /// supervising worker distinguishes "completed" from
1333
+ /// "interrupted by cancel/timeout" through it.
1334
+ fetch_done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
1335
+
1336
+ fn argv(slot: *const Slot) []const []const u8 {
1337
+ return slot.argv_slices[0..slot.argv_count];
1338
+ }
1339
+
1340
+ fn stdinBytes(slot: *const Slot) []const u8 {
1341
+ return slot.stdin_storage[0..slot.stdin_len];
1342
+ }
1343
+
1344
+ fn fetchUrl(slot: *const Slot) []const u8 {
1345
+ return slot.url_storage[0..slot.url_len];
1346
+ }
1347
+
1348
+ fn fetchHeaders(slot: *const Slot) []const std.http.Header {
1349
+ return slot.header_slices[0..slot.header_count];
1350
+ }
1351
+
1352
+ fn fetchPayload(slot: *const Slot) []const u8 {
1353
+ const buffer = slot.fetch_buffer orelse return "";
1354
+ return buffer[0..slot.payload_len];
1355
+ }
1356
+
1357
+ fn filePath(slot: *const Slot) []const u8 {
1358
+ return slot.url_storage[0..slot.url_len];
1359
+ }
1360
+ };
1361
+
1362
+ allocator: std.mem.Allocator,
1363
+ executor: EffectExecutor = .real,
1364
+ /// Session-record sink: every drain-delivered result is reported
1365
+ /// here (loop thread, right before its Msg runs through
1366
+ /// `update`). Null outside recording.
1367
+ journal: ?EffectJournal = null,
1368
+ /// The clock behind `wallMs` — the swap seam tests use
1369
+ /// (`TestClock`), exactly like the fake executor. Session replay
1370
+ /// never consults it: journaled values win there.
1371
+ clock: runtime_clock.Clock = .system,
1372
+ /// Session replay: the executor is `.fake` AND terminal delivery
1373
+ /// comes exclusively from journaled results (`armReplay`). In
1374
+ /// this mode `cancel` never self-delivers a `.cancelled`
1375
+ /// terminal — the journaled terminal (recorded as `.cancelled`)
1376
+ /// is fed instead, so replay delivers exactly what the recorded
1377
+ /// session delivered, in the same order.
1378
+ replay: bool = false,
1379
+ /// Journaled wall-clock values queued for replay-mode `wallMs`
1380
+ /// reads (FIFO; fed from `.clock` records before the consuming
1381
+ /// event dispatches).
1382
+ replay_clock: [max_effect_replay_clock_entries]i64 = [_]i64{0} ** max_effect_replay_clock_entries,
1383
+ replay_clock_head: usize = 0,
1384
+ replay_clock_len: usize = 0,
1385
+ /// Replay `wallMs` reads that found no journaled value: a
1386
+ /// divergence signal (the replayed update read the clock more
1387
+ /// often than the recorded one). Reported loudly once.
1388
+ replay_clock_underflows: u64 = 0,
1389
+ /// Set once from the loop thread before the first dispatch;
1390
+ /// workers call `services.wake()` through it (the one
1391
+ /// thread-safe PlatformServices entry).
1392
+ services: ?*const platform.PlatformServices = null,
1393
+ /// The runtime's canvas image registry, bound by `UiApp`
1394
+ /// alongside the services so `update` can register fetched
1395
+ /// pixels synchronously (loop-thread only, not an effect).
1396
+ images: ?ImageRegistryBinding = null,
1397
+ /// The runtime's window verbs (close/minimize by label), bound
1398
+ /// by `UiApp` alongside the services — the seam behind
1399
+ /// app-drawn window controls (loop-thread only).
1400
+ window_actions: ?WindowActionBinding = null,
1401
+ /// Window-action mirror: counts and the last requested label,
1402
+ /// observable in tests (`windowActionState`).
1403
+ window_action_state: WindowActionState = .{},
1404
+ /// The environment spawned children inherit and fetch honors
1405
+ /// (PATH for `spawnPath`-style lookups, proxy variables).
1406
+ /// Bound once from the loop thread before the first real
1407
+ /// spawn/fetch; `null` means "resolve a fallback at first use"
1408
+ /// (see `fallbackEnviron`).
1409
+ environ: ?std.process.Environ = null,
1410
+ io_threaded: ?*IoThreaded = null,
1411
+ shutdown: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
1412
+ next_generation: u32 = 1,
1413
+ slots: [max_effects]Slot = [_]Slot{.{}} ** max_effects,
1414
+ /// Fixed fx timer table (see `max_effect_timers`): timers live
1415
+ /// beside the effect slots, never in them. Loop-thread only.
1416
+ timer_slots: [max_effect_timers]TimerSlot = [_]TimerSlot{.{}} ** max_effect_timers,
1417
+ /// The single audio playback channel (see `AudioChannel`).
1418
+ /// Loop-thread only, like the timer table.
1419
+ audio: AudioChannel = .{},
1420
+ queue_mutex: SpinMutex = .{},
1421
+ queue: [max_effect_queue_entries]Entry = undefined,
1422
+ queue_head: usize = 0,
1423
+ queue_len: usize = 0,
1424
+ /// Mirror of `queue_len` readable without the lock, so the frame
1425
+ /// path can skip idle drains cheaply.
1426
+ queue_count: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),
1427
+ /// Loop-thread-only ring: spawn/fetch rejections and fake-executor
1428
+ /// terminals that found the queue full. Drained before the queue.
1429
+ pending_exits: [max_effect_pending_exits]PendingMsg = undefined,
1430
+ pending_exit_head: usize = 0,
1431
+ pending_exit_len: usize = 0,
1432
+ /// Scratch the drained entry is copied into so its line slice
1433
+ /// stays valid while `update` runs (recycled per drained Msg).
1434
+ drain_scratch: Entry = .{},
1435
+ /// The heap payload of the most recently drained oversized line
1436
+ /// (raised `max_line_bytes`), keeping `EffectLine.line` valid
1437
+ /// while `update` runs (freed when the next line drains, or at
1438
+ /// `deinit`).
1439
+ drain_heap_line: ?[]u8 = null,
1440
+ /// The buffer of the most recently delivered fetch response or
1441
+ /// file result, keeping `EffectResponse.body` /
1442
+ /// `EffectFileResult.bytes` valid while `update` runs (freed
1443
+ /// when the next response or file result drains, or at
1444
+ /// `deinit`).
1445
+ drain_fetch_body: ?[]u8 = null,
1446
+ /// The collect buffer of the most recently delivered collect
1447
+ /// exit, keeping `EffectExit.output` valid while `update` runs
1448
+ /// (freed when the next collect exit drains, or at `deinit`).
1449
+ drain_collect_output: ?[]u8 = null,
1450
+
1451
+ pub fn init(allocator: std.mem.Allocator) Self {
1452
+ return .{ .allocator = allocator };
1453
+ }
1454
+
1455
+ /// Kill every running effect, wait for the workers to finish
1456
+ /// (draining their final queue posts), and release the executor
1457
+ /// io. Bounded: gives up waiting after ~5s.
1458
+ ///
1459
+ /// Idempotent, and only the FIRST call may touch platform
1460
+ /// services — it ends by severing the services binding, so a
1461
+ /// repeat call answers inert. That property carries the app
1462
+ /// teardown ordering contract: the UiApp stop hook runs this
1463
+ /// while the platform is still alive (the runtime guarantees the
1464
+ /// hook fires before its loop returns), and the app owner's own
1465
+ /// deinit — typically a main() defer that runs after the runner
1466
+ /// has destroyed platform and runtime — reaches this a second
1467
+ /// time, where any service call would dereference freed memory.
1468
+ pub fn deinit(self: *Self) void {
1469
+ self.shutdown.store(true, .release);
1470
+ // Disarm live platform timers (best effort) and clear the table.
1471
+ for (&self.timer_slots, 0..) |*timer_slot, index| {
1472
+ if (timer_slot.active and !timer_slot.fake) {
1473
+ if (self.services) |services| {
1474
+ services.cancelTimer(effectTimerPlatformId(index)) catch {};
1475
+ }
1476
+ }
1477
+ timer_slot.* = .{};
1478
+ }
1479
+ // Silence the platform audio player (best effort) and clear
1480
+ // the channel.
1481
+ if (self.audio.active and !self.audio.fake) {
1482
+ if (self.services) |services| services.audioStop() catch {};
1483
+ }
1484
+ self.audio = .{};
1485
+ for (&self.slots) |*slot| {
1486
+ if (slot.state.load(.acquire) == .running and !slot.fake) {
1487
+ slot.cancel_requested.store(true, .release);
1488
+ // Fetch workers poll `cancel_requested`/`shutdown`
1489
+ // and cancel their blocking task themselves.
1490
+ if (slot.kind == .spawn) self.killPublishedChild(slot);
1491
+ }
1492
+ }
1493
+ if (io_threaded_supported) {
1494
+ if (self.io_threaded) |threaded| {
1495
+ const io = threaded.io();
1496
+ var waited_ms: usize = 0;
1497
+ while (waited_ms < 5000) : (waited_ms += 1) {
1498
+ var running = false;
1499
+ for (&self.slots) |*slot| {
1500
+ if (slot.state.load(.acquire) == .running and !slot.fake) running = true;
1501
+ }
1502
+ if (!running) break;
1503
+ // Keep the queue drained so exit-post retries finish.
1504
+ self.clearQueue();
1505
+ std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake) catch break;
1506
+ }
1507
+ }
1508
+ if (self.io_threaded) |threaded| {
1509
+ threaded.deinit();
1510
+ self.allocator.destroy(threaded);
1511
+ self.io_threaded = null;
1512
+ }
1513
+ }
1514
+ self.clearQueue();
1515
+ for (&self.slots) |*slot| {
1516
+ if (slot.fetch_buffer) |buffer| {
1517
+ self.allocator.free(buffer);
1518
+ slot.fetch_buffer = null;
1519
+ }
1520
+ if (slot.collect_buffer) |buffer| {
1521
+ self.allocator.free(buffer);
1522
+ slot.collect_buffer = null;
1523
+ }
1524
+ if (slot.line_buffer) |buffer| {
1525
+ self.allocator.free(buffer);
1526
+ slot.line_buffer = null;
1527
+ }
1528
+ }
1529
+ if (self.drain_fetch_body) |buffer| {
1530
+ self.allocator.free(buffer);
1531
+ self.drain_fetch_body = null;
1532
+ }
1533
+ if (self.drain_collect_output) |buffer| {
1534
+ self.allocator.free(buffer);
1535
+ self.drain_collect_output = null;
1536
+ }
1537
+ if (self.drain_heap_line) |buffer| {
1538
+ self.allocator.free(buffer);
1539
+ self.drain_heap_line = null;
1540
+ }
1541
+ // Sever the services binding last: the platform this pointer
1542
+ // reaches into may be destroyed before the next call arrives
1543
+ // (main's deferred app deinit runs after the runner's platform
1544
+ // teardown), and a severed channel already answers every
1545
+ // transport command inert through its existing no-services
1546
+ // paths instead of dereferencing freed memory.
1547
+ self.services = null;
1548
+ }
1549
+
1550
+ /// Discard every queued completion, freeing heap line payloads
1551
+ /// (raised `max_line_bytes` lines own an allocation each).
1552
+ /// Shutdown-only; the drain path retires entries one by one.
1553
+ fn clearQueue(self: *Self) void {
1554
+ self.queue_mutex.lock();
1555
+ defer self.queue_mutex.unlock();
1556
+ while (self.queue_len > 0) {
1557
+ const entry = &self.queue[self.queue_head];
1558
+ if (entry.heap_line) |heap| {
1559
+ self.allocator.free(heap);
1560
+ entry.heap_line = null;
1561
+ }
1562
+ self.queue_head = (self.queue_head + 1) % max_effect_queue_entries;
1563
+ self.queue_len -= 1;
1564
+ }
1565
+ self.queue_head = 0;
1566
+ self.queue_count.store(0, .release);
1567
+ }
1568
+
1569
+ /// Point workers at the platform's wake service. Loop-thread
1570
+ /// only; the first bind sticks (the services value lives on the
1571
+ /// runtime and is stable for its lifetime).
1572
+ pub fn bindServices(self: *Self, services: *const platform.PlatformServices) void {
1573
+ if (self.services == null) self.services = services;
1574
+ }
1575
+
1576
+ /// Point spawned children at the host process environment (the
1577
+ /// runner takes it from `std.process.Init`). Loop-thread only;
1578
+ /// the first non-null bind sticks, and it must land before the
1579
+ /// first real spawn/fetch creates the executor io — after that
1580
+ /// the environment is frozen into `std.Io.Threaded`. Hosts that
1581
+ /// never bind (embed/mobile) get `fallbackEnviron()`.
1582
+ pub fn bindEnviron(self: *Self, environ: ?std.process.Environ) void {
1583
+ if (self.environ == null) self.environ = environ;
1584
+ }
1585
+
1586
+ /// Point image registration at the runtime's canvas image
1587
+ /// registry (`Runtime.canvasImageRegistryBinding()`). Loop-thread
1588
+ /// only; the first bind sticks.
1589
+ pub fn bindImages(self: *Self, binding: ImageRegistryBinding) void {
1590
+ if (self.images == null) self.images = binding;
1591
+ }
1592
+
1593
+ /// Point the drain's result reporting at a session recorder.
1594
+ /// Loop-thread only; the first bind sticks.
1595
+ pub fn bindJournal(self: *Self, binding: EffectJournal) void {
1596
+ if (self.journal == null) self.journal = binding;
1597
+ }
1598
+
1599
+ /// Point window actions at the runtime's window verbs (bound by
1600
+ /// `UiApp.bindEffectsChannel`, which resolves labels against the
1601
+ /// live window table). Loop-thread only; the first bind sticks.
1602
+ pub fn bindWindowActions(self: *Self, binding: WindowActionBinding) void {
1603
+ if (self.window_actions == null) self.window_actions = binding;
1604
+ }
1605
+
1606
+ /// Switch this channel into session-replay mode: the fake
1607
+ /// executor (no processes, no network, no file or pasteboard
1608
+ /// I/O — requests park in their slots) with journaled results as
1609
+ /// the only terminal source. Must run before the first
1610
+ /// spawn/fetch, i.e. before the replayed `app_start` dispatches.
1611
+ pub fn armReplay(self: *Self) void {
1612
+ self.executor = .fake;
1613
+ self.replay = true;
1614
+ }
1615
+
1616
+ /// Report one delivered result to the bound session recorder.
1617
+ fn journalNote(self: *Self, record: EffectResultRecord) void {
1618
+ const binding = self.journal orelse return;
1619
+ binding.record_fn(binding.context, record);
1620
+ }
1621
+
1622
+ /// Wall-clock milliseconds since the Unix epoch, AS AN EFFECT:
1623
+ /// the ledger-timestamp read for `update`/`init_fx` that stays
1624
+ /// deterministic under session replay. Recording journals every
1625
+ /// value returned; replay returns the journaled values in the
1626
+ /// same order instead of touching the OS clock — so "stamp the
1627
+ /// note's edited time" replays byte-identical. This is the one
1628
+ /// sanctioned wall-clock read inside update: a direct
1629
+ /// `Clock.system` read there is nondeterminism outside the
1630
+ /// effect boundary and will fail replay verification at the
1631
+ /// next checkpoint.
1632
+ pub fn wallMs(self: *Self) i64 {
1633
+ if (self.replay) {
1634
+ if (self.replay_clock_len == 0) {
1635
+ self.replay_clock_underflows += 1;
1636
+ if (self.replay_clock_underflows == 1) {
1637
+ std.debug.print(
1638
+ "session replay: a wallMs read found no journaled value - the replayed update reads the clock more often than the recording did (nondeterministic control flow); returning 0\n",
1639
+ .{},
1640
+ );
1641
+ }
1642
+ return 0;
1643
+ }
1644
+ const value = self.replay_clock[self.replay_clock_head];
1645
+ self.replay_clock_head = (self.replay_clock_head + 1) % max_effect_replay_clock_entries;
1646
+ self.replay_clock_len -= 1;
1647
+ return value;
1648
+ }
1649
+ const value = self.clock.wallMs();
1650
+ self.journalNote(.{ .kind = .clock, .key = 0, .clock_wall_ms = value });
1651
+ return value;
1652
+ }
1653
+
1654
+ /// Queue one journaled clock value for a replay-mode `wallMs`
1655
+ /// read (the `.clock` record feed).
1656
+ pub fn pushReplayClock(self: *Self, value: i64) error{EffectNotFound}!void {
1657
+ if (self.replay_clock_len >= max_effect_replay_clock_entries) return error.EffectNotFound;
1658
+ const index = (self.replay_clock_head + self.replay_clock_len) % max_effect_replay_clock_entries;
1659
+ self.replay_clock[index] = value;
1660
+ self.replay_clock_len += 1;
1661
+ }
1662
+
1663
+ // ------------------------------------------------------------- API
1664
+
1665
+ /// Register (or replace) decoded straight-alpha RGBA8 pixels
1666
+ /// under the caller-chosen ImageId `id`, so image/icon/avatar
1667
+ /// widgets referencing it draw them. Synchronous (the pixels are
1668
+ /// copied before this returns), not an effect: no Msg follows.
1669
+ /// Errors are the registry's (`error.InvalidImageId`,
1670
+ /// `error.InvalidImageDimensions`, `error.ImageTooLarge`,
1671
+ /// `error.ImageRegistryFull`) plus `error.UnsupportedService`
1672
+ /// when no registry is bound.
1673
+ pub fn registerImage(self: *Self, id: u64, width: usize, height: usize, rgba8: []const u8) anyerror!void {
1674
+ const binding = self.images orelse return error.UnsupportedService;
1675
+ return binding.register_fn(binding.context, id, width, height, rgba8);
1676
+ }
1677
+
1678
+ /// Decode encoded image bytes (PNG, JPEG, ... — whatever the
1679
+ /// platform codec supports) and register the pixels under `id` in
1680
+ /// one step: the fetch-avatar path. Call it from `update` on the
1681
+ /// `on_response` Msg with the delivered body; store `id` in the
1682
+ /// model only on success, so views fall back (avatar initials)
1683
+ /// while the image is loading or after it failed. On top of
1684
+ /// `registerImage`'s errors: `error.ImageDecodeFailed`
1685
+ /// (undecodable bytes) and `error.UnsupportedService` (platform
1686
+ /// without a codec or no registry bound).
1687
+ pub fn registerImageBytes(self: *Self, id: u64, bytes: []const u8) anyerror!RegisteredImage {
1688
+ const binding = self.images orelse return error.UnsupportedService;
1689
+ return binding.register_bytes_fn(binding.context, id, bytes);
1690
+ }
1691
+
1692
+ /// Remove `id` from the registry, freeing its slot. Returns
1693
+ /// whether the id was registered; widgets still referencing it
1694
+ /// draw their fallback (avatar initials) on the next frame.
1695
+ pub fn unregisterImage(self: *Self, id: u64) bool {
1696
+ const binding = self.images orelse return false;
1697
+ return binding.unregister_fn(binding.context, id);
1698
+ }
1699
+
1700
+ /// Run a subprocess and stream its stdout back as Msgs. Never
1701
+ /// fails from the caller's view: requests that cannot run are
1702
+ /// reported through `on_exit` with reason `.rejected` on the
1703
+ /// next drain.
1704
+ pub fn spawn(self: *Self, options: SpawnOptions) void {
1705
+ self.reclaimSlots();
1706
+ if (options.argv.len == 0 or options.argv.len > max_effect_argv) {
1707
+ return self.reject(options);
1708
+ }
1709
+ var total_bytes: usize = 0;
1710
+ for (options.argv) |arg| total_bytes += arg.len;
1711
+ if (total_bytes > max_effect_argv_bytes) return self.reject(options);
1712
+ const stdin_bytes = options.stdin orelse "";
1713
+ if (stdin_bytes.len > max_effect_stdin_bytes) return self.reject(options);
1714
+ if (options.max_line_bytes == 0 or options.max_line_bytes > max_effect_line_bytes_ceiling) {
1715
+ return self.reject(options);
1716
+ }
1717
+ if (self.findActiveSlot(options.key) != null) return self.reject(options);
1718
+ const slot_index = self.findIdleSlot() orelse return self.reject(options);
1719
+
1720
+ const slot = &self.slots[slot_index];
1721
+ slot.generation = self.next_generation;
1722
+ self.next_generation +%= 1;
1723
+ if (self.next_generation == 0) self.next_generation = 1;
1724
+ slot.key = options.key;
1725
+ slot.kind = .spawn;
1726
+ slot.on_line = options.on_line;
1727
+ slot.on_exit = options.on_exit;
1728
+ slot.on_response = null;
1729
+ slot.cancel_requested.store(false, .release);
1730
+ // `cancelled_generation` is deliberately NOT reset: entries
1731
+ // from a cancelled previous occupant may still sit in the
1732
+ // queue, and the sticky value keeps filtering them after the
1733
+ // slot is reused (the new generation never matches it).
1734
+ slot.child_id = null;
1735
+ slot.reaping = false;
1736
+ slot.dropped_pending = 0;
1737
+ slot.dropped_total = 0;
1738
+ slot.argv_count = options.argv.len;
1739
+ var offset: usize = 0;
1740
+ for (options.argv, 0..) |arg, index| {
1741
+ @memcpy(slot.argv_storage[offset .. offset + arg.len], arg);
1742
+ slot.argv_slices[index] = slot.argv_storage[offset .. offset + arg.len];
1743
+ offset += arg.len;
1744
+ }
1745
+ @memcpy(slot.stdin_storage[0..stdin_bytes.len], stdin_bytes);
1746
+ slot.stdin_len = stdin_bytes.len;
1747
+ slot.output_mode = options.output;
1748
+ slot.collect_len = 0;
1749
+ slot.collect_truncated = false;
1750
+ slot.stderr_total = 0;
1751
+ if (slot.collect_buffer) |old| {
1752
+ self.allocator.free(old);
1753
+ slot.collect_buffer = null;
1754
+ }
1755
+ if (slot.line_buffer) |old| {
1756
+ self.allocator.free(old);
1757
+ slot.line_buffer = null;
1758
+ }
1759
+ slot.line_limit = options.max_line_bytes;
1760
+ if (options.output == .collect) {
1761
+ slot.collect_buffer = self.allocator.alloc(u8, max_effect_collect_bytes) catch {
1762
+ return self.reject(options);
1763
+ };
1764
+ } else if (options.max_line_bytes > max_effect_line_bytes) {
1765
+ slot.line_buffer = self.allocator.alloc(u8, options.max_line_bytes) catch {
1766
+ return self.reject(options);
1767
+ };
1768
+ }
1769
+ slot.fake = self.executor == .fake;
1770
+ slot.state.store(.running, .release);
1771
+
1772
+ if (slot.fake) return;
1773
+
1774
+ const io = self.ensureIo() catch {
1775
+ self.releaseSpawnSlot(slot);
1776
+ return self.reject(options);
1777
+ };
1778
+ const thread = std.Thread.spawn(.{}, workerMain, .{ self, slot_index, slot.generation, io }) catch {
1779
+ self.releaseSpawnSlot(slot);
1780
+ return self.reject(options);
1781
+ };
1782
+ thread.detach();
1783
+ }
1784
+
1785
+ /// Run an HTTP(S) request on a worker thread and deliver its
1786
+ /// terminal outcome — response, failure, timeout, or cancel —
1787
+ /// as exactly one Msg. Never fails from the caller's view:
1788
+ /// requests that cannot run are reported through `on_response`
1789
+ /// with outcome `.rejected` on the next drain. Fetches share
1790
+ /// the spawn slots (`max_effects` in-flight effects combined)
1791
+ /// and the same key space.
1792
+ pub fn fetch(self: *Self, options: FetchOptions) void {
1793
+ self.reclaimSlots();
1794
+ if (options.url.len == 0 or options.url.len > max_effect_url_bytes) {
1795
+ return self.rejectFetch(options);
1796
+ }
1797
+ const uri = std.Uri.parse(options.url) catch return self.rejectFetch(options);
1798
+ const scheme_ok = std.ascii.eqlIgnoreCase(uri.scheme, "http") or
1799
+ std.ascii.eqlIgnoreCase(uri.scheme, "https");
1800
+ if (!scheme_ok) return self.rejectFetch(options);
1801
+ if (options.headers.len > max_effect_fetch_headers) return self.rejectFetch(options);
1802
+ var header_bytes: usize = 0;
1803
+ for (options.headers) |header| {
1804
+ header_bytes += header.name.len + header.value.len;
1805
+ // Names/values that would corrupt the request line are
1806
+ // rejected here rather than asserted on the worker.
1807
+ if (header.name.len == 0) return self.rejectFetch(options);
1808
+ if (std.mem.findScalar(u8, header.name, ':') != null) return self.rejectFetch(options);
1809
+ if (std.mem.findPosLinear(u8, header.name, 0, "\r\n") != null) return self.rejectFetch(options);
1810
+ if (std.mem.findPosLinear(u8, header.value, 0, "\r\n") != null) return self.rejectFetch(options);
1811
+ }
1812
+ if (header_bytes > max_effect_fetch_header_bytes) return self.rejectFetch(options);
1813
+ const payload = options.body orelse "";
1814
+ if (payload.len > max_effect_fetch_payload_bytes) return self.rejectFetch(options);
1815
+ if (options.max_line_bytes == 0 or options.max_line_bytes > max_effect_line_bytes_ceiling) {
1816
+ return self.rejectFetch(options);
1817
+ }
1818
+ if (self.findActiveSlot(options.key) != null) return self.rejectFetch(options);
1819
+ const slot_index = self.findIdleSlot() orelse return self.rejectFetch(options);
1820
+
1821
+ const slot = &self.slots[slot_index];
1822
+ // Stream fetches never buffer a body: the buffer holds only
1823
+ // the request payload copy.
1824
+ const body_space: usize = if (options.response == .stream) 0 else max_effect_body_bytes;
1825
+ const buffer = self.allocator.alloc(u8, payload.len + body_space) catch {
1826
+ return self.rejectFetch(options);
1827
+ };
1828
+ slot.generation = self.next_generation;
1829
+ self.next_generation +%= 1;
1830
+ if (self.next_generation == 0) self.next_generation = 1;
1831
+ slot.key = options.key;
1832
+ slot.kind = .fetch;
1833
+ slot.on_line = if (options.response == .stream) options.on_line else null;
1834
+ slot.on_exit = null;
1835
+ slot.on_response = options.on_response;
1836
+ slot.fetch_response_mode = options.response;
1837
+ slot.method = options.method;
1838
+ slot.timeout_ms = options.timeout_ms;
1839
+ slot.line_limit = options.max_line_bytes;
1840
+ if (slot.line_buffer) |old| {
1841
+ self.allocator.free(old);
1842
+ slot.line_buffer = null;
1843
+ }
1844
+ if (options.response == .stream and options.max_line_bytes > max_effect_line_bytes) {
1845
+ slot.line_buffer = self.allocator.alloc(u8, options.max_line_bytes) catch {
1846
+ self.allocator.free(buffer);
1847
+ return self.rejectFetch(options);
1848
+ };
1849
+ }
1850
+ slot.cancel_requested.store(false, .release);
1851
+ slot.fetch_done.store(false, .release);
1852
+ // `cancelled_generation` stays sticky, exactly as in `spawn`.
1853
+ slot.child_id = null;
1854
+ slot.reaping = false;
1855
+ slot.dropped_pending = 0;
1856
+ slot.dropped_total = 0;
1857
+ @memcpy(slot.url_storage[0..options.url.len], options.url);
1858
+ slot.url_len = options.url.len;
1859
+ var offset: usize = 0;
1860
+ for (options.headers, 0..) |header, index| {
1861
+ @memcpy(slot.header_storage[offset .. offset + header.name.len], header.name);
1862
+ const name = slot.header_storage[offset .. offset + header.name.len];
1863
+ offset += header.name.len;
1864
+ @memcpy(slot.header_storage[offset .. offset + header.value.len], header.value);
1865
+ const value = slot.header_storage[offset .. offset + header.value.len];
1866
+ offset += header.value.len;
1867
+ slot.header_slices[index] = .{ .name = name, .value = value };
1868
+ }
1869
+ slot.header_count = options.headers.len;
1870
+ if (slot.fetch_buffer) |old| self.allocator.free(old);
1871
+ slot.fetch_buffer = buffer;
1872
+ @memcpy(buffer[0..payload.len], payload);
1873
+ slot.payload_len = payload.len;
1874
+ slot.body_len = 0;
1875
+ slot.fetch_status = 0;
1876
+ slot.fetch_outcome = .protocol_failed;
1877
+ slot.fetch_truncated = false;
1878
+ slot.fake = self.executor == .fake;
1879
+ slot.state.store(.running, .release);
1880
+
1881
+ if (slot.fake) return;
1882
+
1883
+ const io = self.ensureIo() catch {
1884
+ self.releaseFetchSlot(slot);
1885
+ return self.rejectFetch(options);
1886
+ };
1887
+ const thread = std.Thread.spawn(.{}, fetchWorkerMain, .{ self, slot_index, slot.generation, io }) catch {
1888
+ self.releaseFetchSlot(slot);
1889
+ return self.rejectFetch(options);
1890
+ };
1891
+ thread.detach();
1892
+ }
1893
+
1894
+ /// Write a whole file on a worker thread — TEA-friendly
1895
+ /// persistence (session snapshots, app state) without smuggling
1896
+ /// an `Io` handle into `update`. Missing parent directories are
1897
+ /// created; an existing file is replaced whole. Exactly one
1898
+ /// terminal Msg follows through `on_result` — `.ok` means every
1899
+ /// byte is on disk; failure is never silent. Never fails from
1900
+ /// the caller's view: requests that cannot run are reported with
1901
+ /// outcome `.rejected` on the next drain. File effects share the
1902
+ /// `max_effects` slots and the key space with spawns and fetches.
1903
+ pub fn writeFile(self: *Self, options: WriteFileOptions) void {
1904
+ if (options.bytes.len > max_effect_file_bytes) {
1905
+ return self.rejectFile(options.key, .write, options.on_result);
1906
+ }
1907
+ self.startFile(options.key, .write, options.path, options.bytes, options.on_result);
1908
+ }
1909
+
1910
+ /// Read a whole file on a worker thread and deliver it as
1911
+ /// exactly one terminal Msg: `.ok` with the content in
1912
+ /// `EffectFileResult.bytes`, `.not_found`, `.io_failed`, or
1913
+ /// `.truncated` with the first `max_effect_file_bytes` when the
1914
+ /// file is bigger (its own outcome, not a flag — a cut JSON
1915
+ /// snapshot must not parse as whole). The bytes are drain
1916
+ /// scratch: copy what the model keeps.
1917
+ pub fn readFile(self: *Self, options: ReadFileOptions) void {
1918
+ self.startFile(options.key, .read, options.path, "", options.on_result);
1919
+ }
1920
+
1921
+ fn startFile(self: *Self, key: u64, op: EffectFileOp, file_path: []const u8, bytes: []const u8, on_result: ?FileMsgFn) void {
1922
+ self.reclaimSlots();
1923
+ if (file_path.len == 0 or file_path.len > max_effect_file_path_bytes) {
1924
+ return self.rejectFile(key, op, on_result);
1925
+ }
1926
+ if (self.findActiveSlot(key) != null) return self.rejectFile(key, op, on_result);
1927
+ const slot_index = self.findIdleSlot() orelse return self.rejectFile(key, op, on_result);
1928
+
1929
+ const slot = &self.slots[slot_index];
1930
+ // A write's buffer holds its payload copy; a read's holds
1931
+ // the content space plus one spare byte that detects
1932
+ // over-bound files without a stat round trip.
1933
+ const buffer_len = if (op == .write) bytes.len else max_effect_file_bytes + 1;
1934
+ const buffer = self.allocator.alloc(u8, buffer_len) catch {
1935
+ return self.rejectFile(key, op, on_result);
1936
+ };
1937
+ slot.generation = self.next_generation;
1938
+ self.next_generation +%= 1;
1939
+ if (self.next_generation == 0) self.next_generation = 1;
1940
+ slot.key = key;
1941
+ slot.kind = .file;
1942
+ slot.file_op = op;
1943
+ slot.on_line = null;
1944
+ slot.on_exit = null;
1945
+ slot.on_response = null;
1946
+ slot.on_file = on_result;
1947
+ slot.cancel_requested.store(false, .release);
1948
+ // `cancelled_generation` stays sticky, exactly as in `spawn`.
1949
+ slot.child_id = null;
1950
+ slot.reaping = false;
1951
+ slot.dropped_pending = 0;
1952
+ slot.dropped_total = 0;
1953
+ @memcpy(slot.url_storage[0..file_path.len], file_path);
1954
+ slot.url_len = file_path.len;
1955
+ if (slot.line_buffer) |old| {
1956
+ self.allocator.free(old);
1957
+ slot.line_buffer = null;
1958
+ }
1959
+ if (slot.fetch_buffer) |old| self.allocator.free(old);
1960
+ slot.fetch_buffer = buffer;
1961
+ if (op == .write) {
1962
+ @memcpy(buffer[0..bytes.len], bytes);
1963
+ slot.payload_len = bytes.len;
1964
+ } else {
1965
+ slot.payload_len = 0;
1966
+ }
1967
+ slot.body_len = 0;
1968
+ slot.fake = self.executor == .fake;
1969
+ slot.state.store(.running, .release);
1970
+
1971
+ if (slot.fake) return;
1972
+
1973
+ const io = self.ensureIo() catch {
1974
+ self.releaseFetchSlot(slot);
1975
+ return self.rejectFile(key, op, on_result);
1976
+ };
1977
+ const thread = std.Thread.spawn(.{}, fileWorkerMain, .{ self, slot_index, slot.generation, io }) catch {
1978
+ self.releaseFetchSlot(slot);
1979
+ return self.rejectFile(key, op, on_result);
1980
+ };
1981
+ thread.detach();
1982
+ }
1983
+
1984
+ /// Put text on the system clipboard through the platform
1985
+ /// pasteboard — the same seam the runtime's cmd+C copy uses —
1986
+ /// and deliver exactly one terminal Msg with an explicit
1987
+ /// outcome (`.ok` / `.failed` / `.rejected`). TEA apps stop
1988
+ /// spawning `pbcopy`: the write is one bounded synchronous
1989
+ /// platform call on the loop thread (pasteboards are
1990
+ /// main-thread services), so no worker thread is involved; the
1991
+ /// Msg still arrives through the ordinary drain, keeping the
1992
+ /// effect contract uniform. Never fails from the caller's view:
1993
+ /// requests that cannot run (slots busy, duplicate active key,
1994
+ /// text over `max_effect_clipboard_bytes`) are reported with
1995
+ /// outcome `.rejected` on the next drain. Clipboard effects
1996
+ /// share the `max_effects` slots and the key space with spawns,
1997
+ /// fetches, and file effects.
1998
+ pub fn writeClipboard(self: *Self, options: WriteClipboardOptions) void {
1999
+ if (options.text.len > max_effect_clipboard_bytes) {
2000
+ return self.rejectClipboard(options.key, .write, options.on_result);
2001
+ }
2002
+ self.startClipboard(options.key, .write, options.text, options.on_result);
2003
+ }
2004
+
2005
+ /// Read the system clipboard's text and deliver it as exactly
2006
+ /// one terminal Msg: `.ok` with the content in
2007
+ /// `EffectClipboardResult.text` (drain scratch — copy what the
2008
+ /// model keeps), or `.failed` when the platform refuses (no
2009
+ /// clipboard service, content over
2010
+ /// `max_effect_clipboard_bytes`, pasteboard error). Synchronous
2011
+ /// like `writeClipboard`; same slots, same key space.
2012
+ pub fn readClipboard(self: *Self, options: ReadClipboardOptions) void {
2013
+ self.startClipboard(options.key, .read, "", options.on_result);
2014
+ }
2015
+
2016
+ fn startClipboard(self: *Self, key: u64, op: EffectClipboardOp, text: []const u8, on_result: ?ClipboardMsgFn) void {
2017
+ self.reclaimSlots();
2018
+ const fake = self.executor == .fake;
2019
+ // Services are bound before init_fx/update ever run; a null
2020
+ // here means a host without the platform clipboard arm.
2021
+ if (!fake and self.services == null) return self.rejectClipboard(key, op, on_result);
2022
+ if (self.findActiveSlot(key) != null) return self.rejectClipboard(key, op, on_result);
2023
+ const slot_index = self.findIdleSlot() orelse return self.rejectClipboard(key, op, on_result);
2024
+
2025
+ const slot = &self.slots[slot_index];
2026
+ // A write's buffer holds its text copy; a read's holds the
2027
+ // clipboard content space.
2028
+ const buffer_len = if (op == .write) text.len else max_effect_clipboard_bytes;
2029
+ const buffer = self.allocator.alloc(u8, buffer_len) catch {
2030
+ return self.rejectClipboard(key, op, on_result);
2031
+ };
2032
+ slot.generation = self.next_generation;
2033
+ self.next_generation +%= 1;
2034
+ if (self.next_generation == 0) self.next_generation = 1;
2035
+ slot.key = key;
2036
+ slot.kind = .clipboard;
2037
+ slot.clipboard_op = op;
2038
+ slot.on_line = null;
2039
+ slot.on_exit = null;
2040
+ slot.on_response = null;
2041
+ slot.on_file = null;
2042
+ slot.on_clipboard = on_result;
2043
+ slot.cancel_requested.store(false, .release);
2044
+ // `cancelled_generation` stays sticky, exactly as in `spawn`.
2045
+ slot.child_id = null;
2046
+ slot.reaping = false;
2047
+ slot.dropped_pending = 0;
2048
+ slot.dropped_total = 0;
2049
+ slot.url_len = 0;
2050
+ if (slot.line_buffer) |old| {
2051
+ self.allocator.free(old);
2052
+ slot.line_buffer = null;
2053
+ }
2054
+ if (slot.fetch_buffer) |old| self.allocator.free(old);
2055
+ slot.fetch_buffer = buffer;
2056
+ if (op == .write) {
2057
+ @memcpy(buffer[0..text.len], text);
2058
+ slot.payload_len = text.len;
2059
+ } else {
2060
+ slot.payload_len = 0;
2061
+ }
2062
+ slot.body_len = 0;
2063
+ slot.fake = fake;
2064
+ slot.state.store(.running, .release);
2065
+
2066
+ if (fake) return;
2067
+
2068
+ // Real mode: one bounded synchronous pasteboard call, right
2069
+ // here on the loop thread (the platform clipboard is a
2070
+ // loop-thread service — the cmd+C seam). The terminal entry
2071
+ // still rides the queue so delivery, cancel rewriting, and
2072
+ // payload lifetime are uniform with every other effect.
2073
+ const services = self.services.?;
2074
+ var outcome: EffectClipboardOutcome = .ok;
2075
+ var read_len: usize = 0;
2076
+ switch (op) {
2077
+ .write => services.writeClipboard(slot.fetchPayload()) catch {
2078
+ outcome = .failed;
2079
+ },
2080
+ .read => {
2081
+ if (services.readClipboard(buffer)) |content| {
2082
+ read_len = content.len;
2083
+ } else |_| {
2084
+ outcome = .failed;
2085
+ }
2086
+ },
2087
+ }
2088
+ slot.body_len = read_len;
2089
+ var entry: Entry = .{
2090
+ .kind = .clipboard,
2091
+ .slot_index = @intCast(slot_index),
2092
+ .generation = slot.generation,
2093
+ .key = key,
2094
+ .line_len = @intCast(read_len),
2095
+ .clipboard_op = op,
2096
+ .clipboard_outcome = outcome,
2097
+ .clipboard_fn = on_result,
2098
+ };
2099
+ slot.state.store(.draining, .release);
2100
+ if (!self.enqueue(&entry)) {
2101
+ // A read whose bytes were lost to a full queue reports
2102
+ // `.failed`, never a silent empty `.ok`.
2103
+ self.releaseFetchSlot(slot);
2104
+ self.deliverLoopClipboard(.{
2105
+ .key = key,
2106
+ .op = op,
2107
+ .outcome = if (op == .read and outcome == .ok and read_len > 0) .failed else outcome,
2108
+ }, on_result);
2109
+ }
2110
+ self.wakeHost();
2111
+ }
2112
+
2113
+ /// Cancel a running effect by key. After this returns, no
2114
+ /// further `on_line` Msgs for that spawn are dispatched; one
2115
+ /// `on_exit` Msg with reason `.cancelled` follows once the
2116
+ /// process is reaped. A cancel that races the natural exit
2117
+ /// (worker finished, completions still queued) keeps the same
2118
+ /// promise: queued lines are discarded and the queued exit is
2119
+ /// reported as `.cancelled`. Unknown keys are a no-op.
2120
+ pub fn cancel(self: *Self, key: u64) void {
2121
+ const slot_index = self.findActiveSlot(key) orelse {
2122
+ // The worker may have finished with its exit still in
2123
+ // the queue: mark the finished generation cancelled so
2124
+ // the drain filters its lines and rewrites its exit.
2125
+ if (self.findFinishedSlot(key)) |finished_index| {
2126
+ const finished = &self.slots[finished_index];
2127
+ finished.cancelled_generation = finished.generation;
2128
+ }
2129
+ return;
2130
+ };
2131
+ const slot = &self.slots[slot_index];
2132
+ slot.cancelled_generation = slot.generation;
2133
+ slot.cancel_requested.store(true, .release);
2134
+ if (slot.fake) {
2135
+ // Replay mode: never self-deliver — the recorded session
2136
+ // already journaled this effect's terminal (as
2137
+ // `.cancelled`, the drain rewrite the marked generation
2138
+ // guarantees), and feeding that record is the one
2139
+ // delivery. The slot stays parked until the feed.
2140
+ if (self.replay) return;
2141
+ if (slot.kind == .fetch) {
2142
+ // No exchange: retire the slot and surface the
2143
+ // terminal response now.
2144
+ const response_fn = slot.on_response;
2145
+ const key_copy = slot.key;
2146
+ self.releaseFetchSlot(slot);
2147
+ self.deliverLoopResponse(.{ .key = key_copy, .outcome = .cancelled }, response_fn);
2148
+ return;
2149
+ }
2150
+ if (slot.kind == .file) {
2151
+ // No IO: retire the slot and surface the terminal
2152
+ // result now.
2153
+ const file_fn = slot.on_file;
2154
+ const op = slot.file_op;
2155
+ const key_copy = slot.key;
2156
+ self.releaseFetchSlot(slot);
2157
+ self.deliverLoopFile(.{ .key = key_copy, .op = op, .outcome = .cancelled }, file_fn);
2158
+ return;
2159
+ }
2160
+ if (slot.kind == .clipboard) {
2161
+ // No pasteboard call happened: retire the slot and
2162
+ // surface the terminal result now.
2163
+ const clipboard_fn = slot.on_clipboard;
2164
+ const op = slot.clipboard_op;
2165
+ const key_copy = slot.key;
2166
+ self.releaseFetchSlot(slot);
2167
+ self.deliverLoopClipboard(.{ .key = key_copy, .op = op, .outcome = .cancelled }, clipboard_fn);
2168
+ return;
2169
+ }
2170
+ // No process: retire the slot and surface the exit now.
2171
+ const exit_fn = slot.on_exit;
2172
+ const exit: EffectExit = .{
2173
+ .key = slot.key,
2174
+ .code = effect_error_exit_code,
2175
+ .reason = .cancelled,
2176
+ .dropped_lines = slot.dropped_total,
2177
+ };
2178
+ self.releaseSpawnSlot(slot);
2179
+ self.deliverLoopExit(exit, exit_fn);
2180
+ return;
2181
+ }
2182
+ // A real fetch is interrupted by its supervising worker,
2183
+ // which polls `cancel_requested`; a real file op is quick
2184
+ // and simply finishes (the drain rewrites its terminal to
2185
+ // `.cancelled`). Neither has a child to kill.
2186
+ if (slot.kind == .spawn) self.killPublishedChild(slot);
2187
+ }
2188
+
2189
+ /// Start (or replace) a key-based timer on the effects channel:
2190
+ /// TEA's way to tick — an auto-refresh, a poll, a debounce —
2191
+ /// without reaching for the runtime. Each fire is delivered as
2192
+ /// one `on_fire` Msg through the ordinary update path. Key
2193
+ /// discipline mirrors `PlatformServices.startTimer`: starting a
2194
+ /// key that is already an active timer REPLACES it (interval,
2195
+ /// mode, and `on_fire` update; the same platform timer re-arms).
2196
+ /// Timer keys are their own namespace and never collide with
2197
+ /// spawn/fetch/file keys; timers consume none of the
2198
+ /// `max_effects` slots and no worker threads. Never fails from
2199
+ /// the caller's view — rejection is never silent: a full timer
2200
+ /// table (`max_effect_timers`), a zero `interval_ms`, or a
2201
+ /// platform without a timer service delivers exactly one Msg
2202
+ /// with outcome `.rejected` on the next drain.
2203
+ pub fn startTimer(self: *Self, options: StartTimerOptions) void {
2204
+ if (options.interval_ms == 0) return self.rejectTimer(options);
2205
+ const fake = self.executor == .fake;
2206
+ // Services are bound before init_fx/update ever run; a null
2207
+ // here means a host without the platform timer arm.
2208
+ if (!fake and self.services == null) return self.rejectTimer(options);
2209
+ const index = self.findActiveTimerIndex(options.key) orelse
2210
+ (self.findIdleTimerIndex() orelse return self.rejectTimer(options));
2211
+ const slot = &self.timer_slots[index];
2212
+ slot.key = options.key;
2213
+ slot.mode = options.mode;
2214
+ slot.interval_ms = options.interval_ms;
2215
+ slot.on_fire = options.on_fire;
2216
+ slot.fake = fake;
2217
+ slot.active = true;
2218
+ if (fake) return;
2219
+ self.services.?.startTimer(
2220
+ effectTimerPlatformId(index),
2221
+ options.interval_ms * std.time.ns_per_ms,
2222
+ options.mode == .repeating,
2223
+ ) catch {
2224
+ slot.active = false;
2225
+ return self.rejectTimer(options);
2226
+ };
2227
+ }
2228
+
2229
+ /// Cancel the fx timer with `key`: no further `on_fire` Msgs for
2230
+ /// it are dispatched. Unknown keys are a no-op (a one-shot that
2231
+ /// already fired counts as unknown).
2232
+ pub fn cancelTimer(self: *Self, key: u64) void {
2233
+ const index = self.findActiveTimerIndex(key) orelse return;
2234
+ const slot = &self.timer_slots[index];
2235
+ slot.active = false;
2236
+ if (slot.fake) return;
2237
+ const services = self.services orelse return;
2238
+ services.cancelTimer(effectTimerPlatformId(index)) catch {};
2239
+ }
2240
+
2241
+ /// Route a fired platform timer back into an fx-timer Msg: the
2242
+ /// on_fire Msg for the slot the reserved `platform_id` maps to,
2243
+ /// or null when the id is not an fx timer (or its slot has no
2244
+ /// `on_fire`). One-shot slots retire here — platform one-shot
2245
+ /// timers self-stop (macOS invalidates its NSTimer, the null
2246
+ /// platform deactivates on fire), so no cancel round trip is
2247
+ /// needed. Loop-thread only; called by `UiApp.handleTimer`.
2248
+ pub fn takeTimerMsg(self: *Self, platform_id: u64, timestamp_ns: u64) ?Msg {
2249
+ const index = timerIndexForPlatformId(platform_id) orelse return null;
2250
+ const slot = &self.timer_slots[index];
2251
+ if (!slot.active) return null;
2252
+ const on_fire = slot.on_fire;
2253
+ const key = slot.key;
2254
+ if (slot.mode == .one_shot) slot.active = false;
2255
+ const fire_fn = on_fire orelse return null;
2256
+ return fire_fn(.{ .key = key, .timestamp_ns = timestamp_ns, .outcome = .fired });
2257
+ }
2258
+
2259
+ /// Load a track into the app's single audio player and start
2260
+ /// playing it, replacing whatever played before. Sources resolve
2261
+ /// in a fixed, honest order: the LOCAL `path` first; when it is
2262
+ /// absent (or the file is missing) the `url` — where the
2263
+ /// platform plays a verified cache entry locally, or STREAMS
2264
+ /// progressively (audible before the download finishes) while
2265
+ /// the bytes fill the cache for next time. TEA all the way down:
2266
+ /// every report — the load acknowledgment with the real
2267
+ /// duration, coarse position ticks while playing (carrying the
2268
+ /// stream's honest `buffering` flag), the one completion at
2269
+ /// natural end, failures — arrives as an `on_event` Msg (payload
2270
+ /// `EffectAudio`) through the ordinary update path. Never fails
2271
+ /// from the caller's view: an oversized string (or path and url
2272
+ /// both empty) delivers one `.rejected` event; a platform
2273
+ /// without audio playback (a Linux host missing GStreamer at
2274
+ /// runtime), an unreadable
2275
+ /// file with no url fallback, or a network failure delivers one
2276
+ /// `.failed` event — never a crash, never silence. The audio key
2277
+ /// is its own namespace (like timer keys) and identifies the
2278
+ /// playback in every event; it consumes no `max_effects` slots.
2279
+ pub fn playAudio(self: *Self, options: PlayAudioOptions) void {
2280
+ const rejected = (options.path.len == 0 and options.url.len == 0) or
2281
+ options.path.len > max_effect_audio_path_bytes or
2282
+ options.url.len > max_effect_audio_path_bytes or
2283
+ options.cache_path.len > max_effect_audio_path_bytes;
2284
+ if (rejected) {
2285
+ self.deliverLoopAudio(.{ .key = options.key, .kind = .rejected }, options.on_event);
2286
+ return;
2287
+ }
2288
+ const volume = self.audio.volume;
2289
+ self.audio = .{
2290
+ .active = true,
2291
+ .fake = self.executor == .fake,
2292
+ .key = options.key,
2293
+ .on_event = options.on_event,
2294
+ // Optimistic command mirror; the platform's events are
2295
+ // the authority from the `.loaded` acknowledgment on.
2296
+ .playing = true,
2297
+ // The fake executor cannot resolve the cascade, so it
2298
+ // records the requested shape: URL-only requests read as
2299
+ // streams, anything with a local path as local.
2300
+ .source = if (options.path.len == 0) .stream else .local,
2301
+ .volume = volume,
2302
+ .expected_bytes = options.expected_bytes,
2303
+ };
2304
+ @memcpy(self.audio.path_buffer[0..options.path.len], options.path);
2305
+ self.audio.path_len = options.path.len;
2306
+ @memcpy(self.audio.url_buffer[0..options.url.len], options.url);
2307
+ self.audio.url_len = options.url.len;
2308
+ @memcpy(self.audio.cache_path_buffer[0..options.cache_path.len], options.cache_path);
2309
+ self.audio.cache_path_len = options.cache_path.len;
2310
+ if (self.audio.fake) return;
2311
+ const services = self.services orelse return self.failAudioChannel();
2312
+ // The source cascade. A missing local file is the ONE local
2313
+ // failure that falls through to the url — everything else
2314
+ // (no player, decode failure) is terminal, because retrying
2315
+ // a different source would mask the real problem.
2316
+ resolve: {
2317
+ if (options.path.len > 0) {
2318
+ if (services.audioLoad(options.path)) |_| {
2319
+ self.audio.source = .local;
2320
+ break :resolve;
2321
+ } else |err| {
2322
+ if (err != error.AudioSourceNotFound or options.url.len == 0) {
2323
+ return self.failAudioChannel();
2324
+ }
2325
+ }
2326
+ }
2327
+ const resolution = services.audioLoadUrl(options.url, options.cache_path, options.expected_bytes) catch
2328
+ return self.failAudioChannel();
2329
+ self.audio.source = switch (resolution) {
2330
+ .cache => .cache,
2331
+ .stream => .stream,
2332
+ };
2333
+ // A fresh stream has no bytes yet: buffering starts true
2334
+ // optimistically and the platform's `.loaded`
2335
+ // acknowledgment (and every event after) is the
2336
+ // authority from there.
2337
+ self.audio.buffering = resolution == .stream;
2338
+ }
2339
+ services.audioPlay() catch return self.failAudioChannel();
2340
+ if (volume != 1.0) services.audioSetVolume(volume) catch {};
2341
+ }
2342
+
2343
+ /// Pause the current playback in place. Idle channels no-op; no
2344
+ /// event echoes — the caller commanded it, so the caller knows.
2345
+ pub fn pauseAudio(self: *Self) void {
2346
+ if (!self.audio.active) return;
2347
+ self.audio.playing = false;
2348
+ if (self.audio.fake) return;
2349
+ const services = self.services orelse return;
2350
+ services.audioPause() catch {};
2351
+ }
2352
+
2353
+ /// Resume paused playback. Idle channels no-op; a player the
2354
+ /// platform can no longer resume (or a platform without audio)
2355
+ /// delivers one `.failed` event instead of silence.
2356
+ pub fn resumeAudio(self: *Self) void {
2357
+ if (!self.audio.active) return;
2358
+ self.audio.playing = true;
2359
+ if (self.audio.fake) return;
2360
+ const services = self.services orelse return self.failAudioChannel();
2361
+ services.audioPlay() catch return self.failAudioChannel();
2362
+ }
2363
+
2364
+ /// Stop playback and release the player. No event echoes; the
2365
+ /// channel goes idle and later platform stragglers are swallowed.
2366
+ pub fn stopAudio(self: *Self) void {
2367
+ if (!self.audio.active) return;
2368
+ const fake = self.audio.fake;
2369
+ const volume = self.audio.volume;
2370
+ self.audio = .{ .volume = volume };
2371
+ if (fake) return;
2372
+ const services = self.services orelse return;
2373
+ services.audioStop() catch {};
2374
+ }
2375
+
2376
+ /// Jump the current playback to `position_ms` (the platform
2377
+ /// clamps to the duration). Idle channels no-op; no event echoes
2378
+ /// — the next position tick reports from the new position.
2379
+ pub fn seekAudio(self: *Self, position_ms: u64) void {
2380
+ if (!self.audio.active) return;
2381
+ self.audio.position_ms = if (self.audio.duration_ms > 0)
2382
+ @min(position_ms, self.audio.duration_ms)
2383
+ else
2384
+ position_ms;
2385
+ if (self.audio.fake) return;
2386
+ const services = self.services orelse return;
2387
+ services.audioSeek(position_ms) catch {};
2388
+ }
2389
+
2390
+ /// Close a window by its declared label — the REAL OS close,
2391
+ /// with the platform's full close semantics (closing the last
2392
+ /// window follows the app's existing exit behavior). The seam
2393
+ /// behind app-drawn close controls on chromeless windows;
2394
+ /// model-declared secondary windows should usually close
2395
+ /// DECLARATIVELY instead (stop declaring them in `windows_fn`).
2396
+ /// Fire-and-forget: no event echoes, an unknown label is a
2397
+ /// no-op, and the fake executor only records the request in the
2398
+ /// mirror (`windowActionState`).
2399
+ pub fn closeWindow(self: *Self, window_label: []const u8) void {
2400
+ self.window_action_state.close_count += 1;
2401
+ self.window_action_state.record(window_label);
2402
+ if (self.executor == .fake) return;
2403
+ const binding = self.window_actions orelse return;
2404
+ _ = binding.close_fn(binding.context, window_label);
2405
+ }
2406
+
2407
+ /// Minimize a window by its declared label — the REAL OS verb
2408
+ /// (macOS genies into the Dock, Windows animates to the
2409
+ /// taskbar, GTK minimizes). The seam behind app-drawn minimize
2410
+ /// controls on chromeless windows. Fire-and-forget, same
2411
+ /// contract as `closeWindow`.
2412
+ pub fn minimizeWindow(self: *Self, window_label: []const u8) void {
2413
+ self.window_action_state.minimize_count += 1;
2414
+ self.window_action_state.record(window_label);
2415
+ if (self.executor == .fake) return;
2416
+ const binding = self.window_actions orelse return;
2417
+ _ = binding.minimize_fn(binding.context, window_label);
2418
+ }
2419
+
2420
+ /// The window-action mirror, for tests: how many close/minimize
2421
+ /// requests rode the channel and the last label requested.
2422
+ pub fn windowActionState(self: *const Self) WindowActionState {
2423
+ return self.window_action_state;
2424
+ }
2425
+
2426
+ /// Set playback volume, clamped to 0.0—1.0. Remembered across
2427
+ /// tracks: the next `playAudio` re-applies it.
2428
+ pub fn setAudioVolume(self: *Self, volume: f32) void {
2429
+ const clamped = std.math.clamp(volume, 0.0, 1.0);
2430
+ self.audio.volume = clamped;
2431
+ if (!self.audio.active or self.audio.fake) return;
2432
+ const services = self.services orelse return;
2433
+ services.audioSetVolume(clamped) catch {};
2434
+ }
2435
+
2436
+ /// Route a platform audio event back into an `on_event` Msg for
2437
+ /// the active channel, updating the playback mirrors on the way.
2438
+ /// Null when the channel is idle (a straggler after `stopAudio`)
2439
+ /// or has no handler. Loop-thread only; called by
2440
+ /// `UiApp.handleEvent` for `.audio` platform events.
2441
+ pub fn takeAudioMsg(self: *Self, platform_event: platform.AudioEvent) ?Msg {
2442
+ // Under replay the journaled effect records are the ONLY
2443
+ // Msg source (fed through `feedAudioEvent`); the replayed
2444
+ // platform `.audio` events would double-deliver.
2445
+ if (self.replay) return null;
2446
+ const kind: EffectAudioEventKind = switch (platform_event.kind) {
2447
+ .loaded => .loaded,
2448
+ .position => .position,
2449
+ .completed => .completed,
2450
+ .failed => .failed,
2451
+ .spectrum => .spectrum,
2452
+ };
2453
+ const audio_fn = self.audio.on_event;
2454
+ const event = self.applyAudioEvent(.{
2455
+ .key = 0,
2456
+ .kind = kind,
2457
+ .position_ms = platform_event.position_ms,
2458
+ .duration_ms = platform_event.duration_ms,
2459
+ .playing = platform_event.playing,
2460
+ .buffering = platform_event.buffering,
2461
+ .bands = platform_event.bands,
2462
+ }) orelse return null;
2463
+ const event_fn = audio_fn orelse return null;
2464
+ self.journalNote(.{
2465
+ .kind = .audio,
2466
+ .key = event.key,
2467
+ .audio_kind = event.kind,
2468
+ .audio_position_ms = event.position_ms,
2469
+ .audio_duration_ms = event.duration_ms,
2470
+ .audio_playing = event.playing,
2471
+ .audio_buffering = event.buffering,
2472
+ .audio_bands = event.bands,
2473
+ });
2474
+ return event_fn(event);
2475
+ }
2476
+
2477
+ /// The playback state mirrors, for the automation snapshot.
2478
+ pub fn audioSnapshot(self: *const Self) AudioSnapshot {
2479
+ return .{
2480
+ .active = self.audio.active,
2481
+ .key = self.audio.key,
2482
+ .playing = self.audio.playing,
2483
+ .buffering = self.audio.buffering,
2484
+ .source = self.audio.source,
2485
+ .position_ms = self.audio.position_ms,
2486
+ .duration_ms = self.audio.duration_ms,
2487
+ .spectrum_bands = self.audio.spectrum_bands,
2488
+ .spectrum_events = self.audio.spectrum_events,
2489
+ };
2490
+ }
2491
+
2492
+ /// Fake executor: the recorded playback request on the single
2493
+ /// audio channel, or null when nothing was asked to play.
2494
+ pub fn pendingAudio(self: *const Self) ?AudioRequest {
2495
+ if (!self.audio.active) return null;
2496
+ return .{
2497
+ .key = self.audio.key,
2498
+ .path = self.audio.path(),
2499
+ .url = self.audio.url(),
2500
+ .cache_path = self.audio.cachePath(),
2501
+ .expected_bytes = self.audio.expected_bytes,
2502
+ .playing = self.audio.playing,
2503
+ .position_ms = self.audio.position_ms,
2504
+ .volume = self.audio.volume,
2505
+ };
2506
+ }
2507
+
2508
+ /// Fake executor / replay: feed one audio event as the platform
2509
+ /// would deliver it. The event resolves against the live channel
2510
+ /// at drain time (key and handler from the channel, mirrors
2511
+ /// updated), mirroring `takeAudioMsg` exactly. Fails when no
2512
+ /// playback is active to receive it.
2513
+ pub fn feedAudioEvent(self: *Self, kind: EffectAudioEventKind, position_ms: u64, duration_ms: u64, playing: bool) !void {
2514
+ return self.feedAudioEventBuffering(kind, position_ms, duration_ms, playing, false);
2515
+ }
2516
+
2517
+ /// `feedAudioEvent` with the stream-stall flag — the shape the
2518
+ /// replayer feeds (journal records carry buffering) and stream
2519
+ /// suites use; the plain feed keeps local-file tests terse.
2520
+ pub fn feedAudioEventBuffering(self: *Self, kind: EffectAudioEventKind, position_ms: u64, duration_ms: u64, playing: bool, buffering: bool) !void {
2521
+ if (!self.audio.active) return error.EffectNotFound;
2522
+ self.deliverPending(.{ .audio = .{
2523
+ .event = .{
2524
+ .key = self.audio.key,
2525
+ .kind = kind,
2526
+ .position_ms = position_ms,
2527
+ .duration_ms = duration_ms,
2528
+ .playing = playing,
2529
+ .buffering = buffering,
2530
+ },
2531
+ .audio_fn = null,
2532
+ .resolve = true,
2533
+ } });
2534
+ }
2535
+
2536
+ /// Fake executor / replay: feed one `.spectrum` band report as
2537
+ /// the platform would deliver it — the band bytes ride the same
2538
+ /// resolve-at-drain path as every other fed audio event, so the
2539
+ /// journal and the channel mirrors see exactly what a live
2540
+ /// analysis tap produces.
2541
+ pub fn feedAudioSpectrum(self: *Self, bands: [platform.audio_spectrum_band_count]u8, position_ms: u64, duration_ms: u64) !void {
2542
+ if (!self.audio.active) return error.EffectNotFound;
2543
+ self.deliverPending(.{ .audio = .{
2544
+ .event = .{
2545
+ .key = self.audio.key,
2546
+ .kind = .spectrum,
2547
+ .position_ms = position_ms,
2548
+ .duration_ms = duration_ms,
2549
+ .playing = true,
2550
+ .bands = bands,
2551
+ },
2552
+ .audio_fn = null,
2553
+ .resolve = true,
2554
+ } });
2555
+ }
2556
+
2557
+ /// Number of effects currently in flight (running slots).
2558
+ pub fn activeCount(self: *Self) usize {
2559
+ self.reclaimSlots();
2560
+ var count: usize = 0;
2561
+ for (&self.slots) |*slot| {
2562
+ if (slot.state.load(.acquire) == .running) count += 1;
2563
+ }
2564
+ return count;
2565
+ }
2566
+
2567
+ /// True when a drain would dispatch at least one Msg.
2568
+ pub fn hasPending(self: *const Self) bool {
2569
+ return self.pending_exit_len > 0 or self.queue_count.load(.acquire) > 0;
2570
+ }
2571
+
2572
+ /// Pop the next completion as a Msg. Loop-thread only. The
2573
+ /// returned Msg's line payload stays valid until the next call.
2574
+ pub fn takeMsg(self: *Self) ?Msg {
2575
+ self.reclaimSlots();
2576
+ while (true) {
2577
+ if (self.takePendingMsg()) |pending| {
2578
+ switch (pending) {
2579
+ .exit => |entry| {
2580
+ const exit_fn = entry.exit_fn orelse continue;
2581
+ self.journalNote(.{
2582
+ .kind = .exit,
2583
+ .key = entry.exit.key,
2584
+ .payload = entry.exit.output,
2585
+ .stderr_tail = entry.exit.stderr_tail,
2586
+ .dropped = entry.exit.dropped_lines,
2587
+ .code = entry.exit.code,
2588
+ .exit_reason = entry.exit.reason,
2589
+ .output_truncated = entry.exit.output_truncated,
2590
+ .stderr_truncated = entry.exit.stderr_truncated,
2591
+ });
2592
+ return exit_fn(entry.exit);
2593
+ },
2594
+ .response => |entry| {
2595
+ const response_fn = entry.response_fn orelse continue;
2596
+ self.journalNote(.{
2597
+ .kind = .response,
2598
+ .key = entry.response.key,
2599
+ .payload = entry.response.body,
2600
+ .truncated = entry.response.truncated,
2601
+ .dropped = entry.response.dropped_before,
2602
+ .status = entry.response.status,
2603
+ .fetch_outcome = entry.response.outcome,
2604
+ });
2605
+ return response_fn(entry.response);
2606
+ },
2607
+ .file => |entry| {
2608
+ const file_fn = entry.file_fn orelse continue;
2609
+ self.journalNote(.{
2610
+ .kind = .file,
2611
+ .key = entry.result.key,
2612
+ .payload = entry.result.bytes,
2613
+ .dropped = entry.result.dropped_before,
2614
+ .file_op = entry.result.op,
2615
+ .file_outcome = entry.result.outcome,
2616
+ });
2617
+ return file_fn(entry.result);
2618
+ },
2619
+ .clipboard => |entry| {
2620
+ const clipboard_fn = entry.clipboard_fn orelse continue;
2621
+ self.journalNote(.{
2622
+ .kind = .clipboard,
2623
+ .key = entry.result.key,
2624
+ .payload = entry.result.text,
2625
+ .dropped = entry.result.dropped_before,
2626
+ .clipboard_op = entry.result.op,
2627
+ .clipboard_outcome = entry.result.outcome,
2628
+ });
2629
+ return clipboard_fn(entry.result);
2630
+ },
2631
+ .timer => |entry| {
2632
+ const timer_fn = entry.timer_fn orelse continue;
2633
+ self.journalNote(.{
2634
+ .kind = .timer,
2635
+ .key = entry.timer.key,
2636
+ .timer_timestamp_ns = entry.timer.timestamp_ns,
2637
+ .timer_outcome = entry.timer.outcome,
2638
+ });
2639
+ return timer_fn(entry.timer);
2640
+ },
2641
+ .audio => |entry| {
2642
+ var event = entry.event;
2643
+ var audio_fn = entry.audio_fn;
2644
+ if (entry.resolve) {
2645
+ // Fed events resolve against the live
2646
+ // channel exactly like a platform event:
2647
+ // mirrors update, key and handler come
2648
+ // from the channel, a stopped channel
2649
+ // swallows the event. Capture the handler
2650
+ // first — a `.failed` apply resets it.
2651
+ audio_fn = self.audio.on_event;
2652
+ event = self.applyAudioEvent(event) orelse continue;
2653
+ }
2654
+ const event_fn = audio_fn orelse continue;
2655
+ self.journalNote(.{
2656
+ .kind = .audio,
2657
+ .key = event.key,
2658
+ .audio_kind = event.kind,
2659
+ .audio_position_ms = event.position_ms,
2660
+ .audio_duration_ms = event.duration_ms,
2661
+ .audio_playing = event.playing,
2662
+ .audio_buffering = event.buffering,
2663
+ .audio_bands = event.bands,
2664
+ });
2665
+ return event_fn(event);
2666
+ },
2667
+ }
2668
+ }
2669
+ if (!self.dequeueInto(&self.drain_scratch)) return null;
2670
+ const entry = &self.drain_scratch;
2671
+ const slot = &self.slots[entry.slot_index];
2672
+ const cancelled = slot.cancelled_generation == entry.generation and entry.generation != 0;
2673
+ switch (entry.kind) {
2674
+ .line => {
2675
+ // Oversized lines (raised `max_line_bytes`) own a
2676
+ // heap payload: take it before any early-out so
2677
+ // skipped entries still free (retired when the
2678
+ // next line drains, like `drain_fetch_body`).
2679
+ if (self.drain_heap_line) |old| {
2680
+ self.allocator.free(old);
2681
+ self.drain_heap_line = null;
2682
+ }
2683
+ if (entry.heap_line) |heap| {
2684
+ self.drain_heap_line = heap;
2685
+ entry.heap_line = null;
2686
+ }
2687
+ if (cancelled) continue;
2688
+ const line_fn = entry.line_fn orelse continue;
2689
+ const line_bytes: []const u8 = if (self.drain_heap_line) |heap|
2690
+ heap[0..entry.line_len]
2691
+ else
2692
+ entry.line_bytes[0..entry.line_len];
2693
+ const line: EffectLine = .{
2694
+ .key = entry.key,
2695
+ .line = line_bytes,
2696
+ .truncated = entry.truncated,
2697
+ .dropped_before = entry.dropped_before,
2698
+ };
2699
+ self.journalNote(.{
2700
+ .kind = .line,
2701
+ .key = line.key,
2702
+ .payload = line.line,
2703
+ .truncated = line.truncated,
2704
+ .dropped = line.dropped_before,
2705
+ });
2706
+ return line_fn(line);
2707
+ },
2708
+ .exit => {
2709
+ // Collect exits own a heap stdout buffer: take it
2710
+ // before any early-out so the slot retires even
2711
+ // when the handler is absent. A mismatched
2712
+ // generation means the occupant was already
2713
+ // retired (and its buffer freed on slot reuse).
2714
+ var output: []const u8 = "";
2715
+ if (entry.collect and entry.generation == slot.generation) {
2716
+ if (self.drain_collect_output) |old| self.allocator.free(old);
2717
+ self.drain_collect_output = slot.collect_buffer;
2718
+ slot.collect_buffer = null;
2719
+ if (!cancelled) {
2720
+ if (self.drain_collect_output) |buffer| output = buffer[0..entry.collect_len];
2721
+ }
2722
+ }
2723
+ const exit_fn = entry.exit_fn orelse continue;
2724
+ const exit: EffectExit = if (cancelled)
2725
+ // Cancelled exits mirror cancelled fetches:
2726
+ // no payload, just the terminal notice.
2727
+ .{
2728
+ .key = entry.key,
2729
+ .code = effect_error_exit_code,
2730
+ .reason = .cancelled,
2731
+ .dropped_lines = entry.dropped_lines,
2732
+ }
2733
+ else
2734
+ .{
2735
+ .key = entry.key,
2736
+ .code = entry.code,
2737
+ .reason = entry.reason,
2738
+ .dropped_lines = entry.dropped_lines,
2739
+ .output = output,
2740
+ .output_truncated = entry.collect_truncated,
2741
+ .stderr_tail = if (entry.collect) entry.line_bytes[0..entry.line_len] else "",
2742
+ .stderr_truncated = entry.stderr_truncated,
2743
+ };
2744
+ self.journalNote(.{
2745
+ .kind = .exit,
2746
+ .key = exit.key,
2747
+ .payload = exit.output,
2748
+ .stderr_tail = exit.stderr_tail,
2749
+ .dropped = exit.dropped_lines,
2750
+ .code = exit.code,
2751
+ .exit_reason = exit.reason,
2752
+ .output_truncated = exit.output_truncated,
2753
+ .stderr_truncated = exit.stderr_truncated,
2754
+ });
2755
+ return exit_fn(exit);
2756
+ },
2757
+ .response => {
2758
+ // One response per fetch occupancy: a mismatched
2759
+ // generation means the occupant was already
2760
+ // retired with its own terminal Msg.
2761
+ if (entry.generation != slot.generation) continue;
2762
+ // Take body ownership so the slot can be reused
2763
+ // while `update` still reads the slice; the
2764
+ // buffer is freed when the next response drains.
2765
+ if (self.drain_fetch_body) |old| self.allocator.free(old);
2766
+ self.drain_fetch_body = slot.fetch_buffer;
2767
+ slot.fetch_buffer = null;
2768
+ const payload_len = slot.payload_len;
2769
+ const response_fn = entry.response_fn orelse continue;
2770
+ const body: []const u8 = if (self.drain_fetch_body) |buffer|
2771
+ buffer[payload_len .. payload_len + entry.line_len]
2772
+ else
2773
+ "";
2774
+ const response: EffectResponse = if (cancelled)
2775
+ .{ .key = entry.key, .outcome = .cancelled }
2776
+ else
2777
+ .{
2778
+ .key = entry.key,
2779
+ .outcome = entry.outcome,
2780
+ .status = entry.status,
2781
+ .body = body,
2782
+ .truncated = entry.truncated,
2783
+ .dropped_before = entry.dropped_before,
2784
+ };
2785
+ self.journalNote(.{
2786
+ .kind = .response,
2787
+ .key = response.key,
2788
+ .payload = response.body,
2789
+ .truncated = response.truncated,
2790
+ .dropped = response.dropped_before,
2791
+ .status = response.status,
2792
+ .fetch_outcome = response.outcome,
2793
+ });
2794
+ return response_fn(response);
2795
+ },
2796
+ .file => {
2797
+ // One terminal per file occupancy, mirroring
2798
+ // `.response`: a mismatched generation means the
2799
+ // occupant was already retired.
2800
+ if (entry.generation != slot.generation) continue;
2801
+ // Take buffer ownership so the slot can be
2802
+ // reused while `update` still reads the bytes.
2803
+ if (self.drain_fetch_body) |old| self.allocator.free(old);
2804
+ self.drain_fetch_body = slot.fetch_buffer;
2805
+ slot.fetch_buffer = null;
2806
+ const payload_len = slot.payload_len;
2807
+ const file_fn = entry.file_fn orelse continue;
2808
+ const bytes: []const u8 = if (self.drain_fetch_body) |buffer|
2809
+ buffer[payload_len .. payload_len + entry.line_len]
2810
+ else
2811
+ "";
2812
+ const result: EffectFileResult = if (cancelled)
2813
+ .{ .key = entry.key, .op = entry.file_op, .outcome = .cancelled }
2814
+ else
2815
+ .{
2816
+ .key = entry.key,
2817
+ .op = entry.file_op,
2818
+ .outcome = entry.file_outcome,
2819
+ .bytes = bytes,
2820
+ .dropped_before = entry.dropped_before,
2821
+ };
2822
+ self.journalNote(.{
2823
+ .kind = .file,
2824
+ .key = result.key,
2825
+ .payload = result.bytes,
2826
+ .dropped = result.dropped_before,
2827
+ .file_op = result.op,
2828
+ .file_outcome = result.outcome,
2829
+ });
2830
+ return file_fn(result);
2831
+ },
2832
+ .clipboard => {
2833
+ // One terminal per clipboard occupancy, mirroring
2834
+ // `.file`: a mismatched generation means the
2835
+ // occupant was already retired.
2836
+ if (entry.generation != slot.generation) continue;
2837
+ // Take buffer ownership so the slot can be
2838
+ // reused while `update` still reads the text.
2839
+ if (self.drain_fetch_body) |old| self.allocator.free(old);
2840
+ self.drain_fetch_body = slot.fetch_buffer;
2841
+ slot.fetch_buffer = null;
2842
+ const payload_len = slot.payload_len;
2843
+ const clipboard_fn = entry.clipboard_fn orelse continue;
2844
+ const text: []const u8 = if (self.drain_fetch_body) |buffer|
2845
+ buffer[payload_len .. payload_len + entry.line_len]
2846
+ else
2847
+ "";
2848
+ const result: EffectClipboardResult = if (cancelled)
2849
+ .{ .key = entry.key, .op = entry.clipboard_op, .outcome = .cancelled }
2850
+ else
2851
+ .{
2852
+ .key = entry.key,
2853
+ .op = entry.clipboard_op,
2854
+ .outcome = entry.clipboard_outcome,
2855
+ .text = text,
2856
+ .dropped_before = entry.dropped_before,
2857
+ };
2858
+ self.journalNote(.{
2859
+ .kind = .clipboard,
2860
+ .key = result.key,
2861
+ .payload = result.text,
2862
+ .dropped = result.dropped_before,
2863
+ .clipboard_op = result.op,
2864
+ .clipboard_outcome = result.outcome,
2865
+ });
2866
+ return clipboard_fn(result);
2867
+ },
2868
+ }
2869
+ }
2870
+ }
2871
+
2872
+ // --------------------------------------------------- fake executor
2873
+
2874
+ /// Number of recorded (still-active) fake spawn requests.
2875
+ pub fn pendingSpawnCount(self: *Self) usize {
2876
+ var count: usize = 0;
2877
+ for (&self.slots) |*slot| {
2878
+ if (slot.fake and slot.kind == .spawn and slot.state.load(.acquire) == .running) count += 1;
2879
+ }
2880
+ return count;
2881
+ }
2882
+
2883
+ /// The `index`-th recorded fake spawn request (slot order).
2884
+ pub fn pendingSpawnAt(self: *Self, index: usize) ?SpawnRequest {
2885
+ var seen: usize = 0;
2886
+ for (&self.slots) |*slot| {
2887
+ if (!(slot.fake and slot.kind == .spawn and slot.state.load(.acquire) == .running)) continue;
2888
+ if (seen == index) {
2889
+ return .{
2890
+ .key = slot.key,
2891
+ .argv = slot.argv(),
2892
+ .stdin = slot.stdinBytes(),
2893
+ .output = slot.output_mode,
2894
+ .max_line_bytes = slot.line_limit,
2895
+ };
2896
+ }
2897
+ seen += 1;
2898
+ }
2899
+ return null;
2900
+ }
2901
+
2902
+ /// Number of recorded (still-active) fake fetch requests.
2903
+ pub fn pendingFetchCount(self: *Self) usize {
2904
+ var count: usize = 0;
2905
+ for (&self.slots) |*slot| {
2906
+ if (slot.fake and slot.kind == .fetch and slot.state.load(.acquire) == .running) count += 1;
2907
+ }
2908
+ return count;
2909
+ }
2910
+
2911
+ /// The `index`-th recorded fake fetch request (slot order).
2912
+ pub fn pendingFetchAt(self: *Self, index: usize) ?FetchRequest {
2913
+ var seen: usize = 0;
2914
+ for (&self.slots) |*slot| {
2915
+ if (!(slot.fake and slot.kind == .fetch and slot.state.load(.acquire) == .running)) continue;
2916
+ if (seen == index) {
2917
+ return .{
2918
+ .key = slot.key,
2919
+ .method = slot.method,
2920
+ .url = slot.fetchUrl(),
2921
+ .headers = slot.fetchHeaders(),
2922
+ .body = slot.fetchPayload(),
2923
+ .response = slot.fetch_response_mode,
2924
+ .max_line_bytes = slot.line_limit,
2925
+ };
2926
+ }
2927
+ seen += 1;
2928
+ }
2929
+ return null;
2930
+ }
2931
+
2932
+ /// Feed one synthetic stdout line to the fake effect with `key`.
2933
+ /// Mirrors the real executor per output mode: a `.lines` spawn
2934
+ /// (or `.stream` fetch) queues one `on_line` Msg (a full queue
2935
+ /// counts a drop instead of delivering); a `.collect` spawn
2936
+ /// accumulates the bytes plus their newline into the collected
2937
+ /// output (truncating over the collect bound with the flag set,
2938
+ /// exactly like a real child that printed that line).
2939
+ pub fn feedLine(self: *Self, key: u64, bytes: []const u8) error{EffectNotFound}!void {
2940
+ const slot_index = self.findActiveFakeSlot(key, .spawn) orelse blk: {
2941
+ const fetch_index = self.findActiveFakeSlot(key, .fetch) orelse return error.EffectNotFound;
2942
+ if (self.slots[fetch_index].fetch_response_mode != .stream) return error.EffectNotFound;
2943
+ break :blk fetch_index;
2944
+ };
2945
+ const slot = &self.slots[slot_index];
2946
+ if (slot.kind == .spawn and slot.output_mode == .collect) {
2947
+ appendCollected(slot, bytes);
2948
+ appendCollected(slot, "\n");
2949
+ return;
2950
+ }
2951
+ self.produceLine(slot, @intCast(slot_index), slot.generation, bytes, false);
2952
+ }
2953
+
2954
+ /// Feed synthetic stderr bytes to the fake `.collect` effect with
2955
+ /// `key`. Mirrors the real tail: only the last
2956
+ /// `max_effect_stderr_tail_bytes` are kept and earlier bytes are
2957
+ /// flagged through `stderr_truncated`. `.lines` spawns ignore
2958
+ /// stderr, so feeding one reports EffectNotFound.
2959
+ pub fn feedStderr(self: *Self, key: u64, bytes: []const u8) error{EffectNotFound}!void {
2960
+ const slot_index = self.findActiveFakeSlot(key, .spawn) orelse return error.EffectNotFound;
2961
+ const slot = &self.slots[slot_index];
2962
+ if (slot.output_mode != .collect) return error.EffectNotFound;
2963
+ appendStderrTail(slot, bytes);
2964
+ }
2965
+
2966
+ /// Feed the synthetic exit for the fake effect with `key`,
2967
+ /// retiring its slot. A `.collect` exit carries the accumulated
2968
+ /// output and stderr tail, exactly like a real collect exit; if
2969
+ /// the completion queue is somehow full, the terminal still lands
2970
+ /// through the pending ring — with empty payloads and the
2971
+ /// truncation flags set, never silently.
2972
+ pub fn feedExit(self: *Self, key: u64, code: i32) error{EffectNotFound}!void {
2973
+ return self.feedExitReason(key, code, .exited);
2974
+ }
2975
+
2976
+ /// `feedExit` with an explicit exit reason — the session-replay
2977
+ /// feed, which must deliver exactly the reason the recorded
2978
+ /// session delivered (`.signaled`, `.cancelled`, ...).
2979
+ pub fn feedExitReason(self: *Self, key: u64, code: i32, reason: EffectExitReason) error{EffectNotFound}!void {
2980
+ const slot_index = self.findActiveFakeSlot(key, .spawn) orelse return error.EffectNotFound;
2981
+ const slot = &self.slots[slot_index];
2982
+ var entry: Entry = .{
2983
+ .kind = .exit,
2984
+ .slot_index = @intCast(slot_index),
2985
+ .generation = slot.generation,
2986
+ .key = slot.key,
2987
+ .code = code,
2988
+ .reason = reason,
2989
+ .dropped_lines = slot.dropped_total,
2990
+ .exit_fn = slot.on_exit,
2991
+ };
2992
+ const exit_fn = slot.on_exit;
2993
+ if (slot.output_mode == .collect) {
2994
+ stampCollectExit(slot, &entry);
2995
+ slot.state.store(.draining, .release);
2996
+ if (!self.enqueue(&entry)) {
2997
+ self.releaseSpawnSlot(slot);
2998
+ self.deliverLoopExit(.{
2999
+ .key = entry.key,
3000
+ .code = code,
3001
+ .reason = reason,
3002
+ .dropped_lines = entry.dropped_lines,
3003
+ .output_truncated = true,
3004
+ .stderr_truncated = true,
3005
+ }, exit_fn);
3006
+ }
3007
+ self.wakeHost();
3008
+ return;
3009
+ }
3010
+ const delivered = self.enqueue(&entry);
3011
+ slot.state.store(.idle, .release);
3012
+ if (!delivered) {
3013
+ self.deliverLoopExit(.{
3014
+ .key = entry.key,
3015
+ .code = code,
3016
+ .reason = reason,
3017
+ .dropped_lines = entry.dropped_lines,
3018
+ }, exit_fn);
3019
+ }
3020
+ self.wakeHost();
3021
+ }
3022
+
3023
+ /// Feed the synthetic response for the fake fetch with `key`,
3024
+ /// retiring its slot. Mirrors real truncation: bodies over
3025
+ /// `max_effect_body_bytes` are cut with `truncated = true`. A
3026
+ /// `.stream` fetch's terminal carries no body (feed its lines
3027
+ /// through `feedLine` first); any body bytes passed here are
3028
+ /// ignored, exactly like the real stream terminal. If the
3029
+ /// completion queue is somehow full, the terminal still lands
3030
+ /// through the pending ring — with an empty body and
3031
+ /// `truncated = true`, never silently.
3032
+ pub fn feedResponse(self: *Self, key: u64, status: u16, body: []const u8) error{EffectNotFound}!void {
3033
+ return self.feedResponseOutcome(key, .ok, status, body);
3034
+ }
3035
+
3036
+ /// `feedResponse` with an explicit terminal outcome — the
3037
+ /// session-replay feed, which must deliver exactly the outcome
3038
+ /// the recorded session delivered (`.timed_out`,
3039
+ /// `.connect_failed`, ...). Non-`.ok` outcomes carry no body,
3040
+ /// mirroring the real executor.
3041
+ pub fn feedResponseOutcome(self: *Self, key: u64, outcome: EffectFetchOutcome, status: u16, body: []const u8) error{EffectNotFound}!void {
3042
+ const slot_index = self.findActiveFakeSlot(key, .fetch) orelse return error.EffectNotFound;
3043
+ const slot = &self.slots[slot_index];
3044
+ const buffer = slot.fetch_buffer orelse return error.EffectNotFound;
3045
+ if (slot.fetch_response_mode == .stream or outcome != .ok) {
3046
+ slot.body_len = 0;
3047
+ slot.fetch_truncated = false;
3048
+ } else {
3049
+ const capacity = buffer.len - slot.payload_len;
3050
+ const len = @min(body.len, capacity);
3051
+ @memcpy(buffer[slot.payload_len..][0..len], body[0..len]);
3052
+ slot.body_len = len;
3053
+ slot.fetch_truncated = body.len > capacity;
3054
+ }
3055
+ slot.fetch_status = status;
3056
+ slot.fetch_outcome = outcome;
3057
+ var entry: Entry = .{
3058
+ .kind = .response,
3059
+ .slot_index = @intCast(slot_index),
3060
+ .generation = slot.generation,
3061
+ .key = slot.key,
3062
+ .line_len = @intCast(slot.body_len),
3063
+ .truncated = slot.fetch_truncated,
3064
+ .dropped_before = slot.dropped_pending,
3065
+ .status = status,
3066
+ .outcome = outcome,
3067
+ .response_fn = slot.on_response,
3068
+ };
3069
+ slot.state.store(.draining, .release);
3070
+ if (!self.enqueue(&entry)) {
3071
+ const response_fn = slot.on_response;
3072
+ self.releaseFetchSlot(slot);
3073
+ self.deliverLoopResponse(.{
3074
+ .key = entry.key,
3075
+ .outcome = outcome,
3076
+ .status = status,
3077
+ .truncated = true,
3078
+ }, response_fn);
3079
+ }
3080
+ self.wakeHost();
3081
+ }
3082
+
3083
+ /// Append raw bytes to a fake `.collect` spawn's accumulated
3084
+ /// stdout WITHOUT line framing — the session-replay feed for a
3085
+ /// recorded collect exit's whole `output` payload (whose
3086
+ /// original line structure is already baked into the bytes).
3087
+ pub fn feedOutput(self: *Self, key: u64, bytes: []const u8) error{EffectNotFound}!void {
3088
+ const slot_index = self.findActiveFakeSlot(key, .spawn) orelse return error.EffectNotFound;
3089
+ const slot = &self.slots[slot_index];
3090
+ if (slot.output_mode != .collect) return error.EffectNotFound;
3091
+ appendCollected(slot, bytes);
3092
+ }
3093
+
3094
+ /// Number of recorded (still-active) fake file requests.
3095
+ pub fn pendingFileCount(self: *Self) usize {
3096
+ var count: usize = 0;
3097
+ for (&self.slots) |*slot| {
3098
+ if (slot.fake and slot.kind == .file and slot.state.load(.acquire) == .running) count += 1;
3099
+ }
3100
+ return count;
3101
+ }
3102
+
3103
+ /// The `index`-th recorded fake file request (slot order).
3104
+ pub fn pendingFileAt(self: *Self, index: usize) ?FileRequest {
3105
+ var seen: usize = 0;
3106
+ for (&self.slots) |*slot| {
3107
+ if (!(slot.fake and slot.kind == .file and slot.state.load(.acquire) == .running)) continue;
3108
+ if (seen == index) {
3109
+ return .{
3110
+ .key = slot.key,
3111
+ .op = slot.file_op,
3112
+ .path = slot.filePath(),
3113
+ .bytes = if (slot.file_op == .write) slot.fetchPayload() else "",
3114
+ };
3115
+ }
3116
+ seen += 1;
3117
+ }
3118
+ return null;
3119
+ }
3120
+
3121
+ /// Feed the synthetic terminal for the fake file effect with
3122
+ /// `key`, retiring its slot. `bytes` is a read's content,
3123
+ /// delivered with outcome `.ok` or `.truncated` (over-bound
3124
+ /// content is cut at `max_effect_file_bytes` and the outcome
3125
+ /// rewritten to `.truncated`, mirroring the real reader);
3126
+ /// `bytes` is ignored for writes and for failure outcomes. If
3127
+ /// the completion queue is somehow full, the terminal still
3128
+ /// lands through the pending ring — a read whose bytes were
3129
+ /// lost that way reports `.truncated`, never silently.
3130
+ pub fn feedFileResult(self: *Self, key: u64, outcome: EffectFileOutcome, bytes: []const u8) error{EffectNotFound}!void {
3131
+ const slot_index = self.findActiveFakeSlot(key, .file) orelse return error.EffectNotFound;
3132
+ const slot = &self.slots[slot_index];
3133
+ const buffer = slot.fetch_buffer orelse return error.EffectNotFound;
3134
+ var delivered_len: usize = 0;
3135
+ var delivered_outcome = outcome;
3136
+ if (slot.file_op == .read and (outcome == .ok or outcome == .truncated)) {
3137
+ const capacity = @min(buffer.len, max_effect_file_bytes);
3138
+ delivered_len = @min(bytes.len, capacity);
3139
+ @memcpy(buffer[0..delivered_len], bytes[0..delivered_len]);
3140
+ if (bytes.len > capacity) delivered_outcome = .truncated;
3141
+ }
3142
+ slot.body_len = delivered_len;
3143
+ var entry: Entry = .{
3144
+ .kind = .file,
3145
+ .slot_index = @intCast(slot_index),
3146
+ .generation = slot.generation,
3147
+ .key = slot.key,
3148
+ .line_len = @intCast(delivered_len),
3149
+ .file_op = slot.file_op,
3150
+ .file_outcome = delivered_outcome,
3151
+ .file_fn = slot.on_file,
3152
+ };
3153
+ slot.state.store(.draining, .release);
3154
+ if (!self.enqueue(&entry)) {
3155
+ const file_fn = slot.on_file;
3156
+ const op = slot.file_op;
3157
+ self.releaseFetchSlot(slot);
3158
+ self.deliverLoopFile(.{
3159
+ .key = entry.key,
3160
+ .op = op,
3161
+ .outcome = if (op == .read and delivered_len > 0) .truncated else delivered_outcome,
3162
+ }, file_fn);
3163
+ }
3164
+ self.wakeHost();
3165
+ }
3166
+
3167
+ /// Number of recorded (still-active) fake clipboard requests.
3168
+ pub fn pendingClipboardCount(self: *Self) usize {
3169
+ var count: usize = 0;
3170
+ for (&self.slots) |*slot| {
3171
+ if (slot.fake and slot.kind == .clipboard and slot.state.load(.acquire) == .running) count += 1;
3172
+ }
3173
+ return count;
3174
+ }
3175
+
3176
+ /// The `index`-th recorded fake clipboard request (slot order).
3177
+ pub fn pendingClipboardAt(self: *Self, index: usize) ?ClipboardRequest {
3178
+ var seen: usize = 0;
3179
+ for (&self.slots) |*slot| {
3180
+ if (!(slot.fake and slot.kind == .clipboard and slot.state.load(.acquire) == .running)) continue;
3181
+ if (seen == index) {
3182
+ return .{
3183
+ .key = slot.key,
3184
+ .op = slot.clipboard_op,
3185
+ .text = if (slot.clipboard_op == .write) slot.fetchPayload() else "",
3186
+ };
3187
+ }
3188
+ seen += 1;
3189
+ }
3190
+ return null;
3191
+ }
3192
+
3193
+ /// Feed the synthetic terminal for the fake clipboard effect
3194
+ /// with `key`, retiring its slot. `text` is a read's clipboard
3195
+ /// content, delivered with outcome `.ok`; content over
3196
+ /// `max_effect_clipboard_bytes` rewrites the outcome to
3197
+ /// `.failed` with empty text, mirroring the real reader (which
3198
+ /// fails whole rather than cutting — a cut clipboard string
3199
+ /// must never pass for the clipboard). `text` is ignored for
3200
+ /// writes and for failure outcomes. If the completion queue is
3201
+ /// somehow full, the terminal still lands through the pending
3202
+ /// ring — a read whose bytes were lost that way reports
3203
+ /// `.failed`, never silently.
3204
+ pub fn feedClipboardResult(self: *Self, key: u64, outcome: EffectClipboardOutcome, text: []const u8) error{EffectNotFound}!void {
3205
+ const slot_index = self.findActiveFakeSlot(key, .clipboard) orelse return error.EffectNotFound;
3206
+ const slot = &self.slots[slot_index];
3207
+ const buffer = slot.fetch_buffer orelse return error.EffectNotFound;
3208
+ var delivered_len: usize = 0;
3209
+ var delivered_outcome = outcome;
3210
+ if (slot.clipboard_op == .read and outcome == .ok) {
3211
+ const capacity = @min(buffer.len, max_effect_clipboard_bytes);
3212
+ if (text.len > capacity) {
3213
+ delivered_outcome = .failed;
3214
+ } else {
3215
+ delivered_len = text.len;
3216
+ @memcpy(buffer[0..delivered_len], text[0..delivered_len]);
3217
+ }
3218
+ }
3219
+ slot.body_len = delivered_len;
3220
+ var entry: Entry = .{
3221
+ .kind = .clipboard,
3222
+ .slot_index = @intCast(slot_index),
3223
+ .generation = slot.generation,
3224
+ .key = slot.key,
3225
+ .line_len = @intCast(delivered_len),
3226
+ .clipboard_op = slot.clipboard_op,
3227
+ .clipboard_outcome = delivered_outcome,
3228
+ .clipboard_fn = slot.on_clipboard,
3229
+ };
3230
+ slot.state.store(.draining, .release);
3231
+ if (!self.enqueue(&entry)) {
3232
+ const clipboard_fn = slot.on_clipboard;
3233
+ const op = slot.clipboard_op;
3234
+ self.releaseFetchSlot(slot);
3235
+ self.deliverLoopClipboard(.{
3236
+ .key = entry.key,
3237
+ .op = op,
3238
+ .outcome = if (op == .read and delivered_len > 0) .failed else delivered_outcome,
3239
+ }, clipboard_fn);
3240
+ }
3241
+ self.wakeHost();
3242
+ }
3243
+
3244
+ /// Number of recorded (still-armed) fake fx timers.
3245
+ pub fn pendingTimerCount(self: *Self) usize {
3246
+ var count: usize = 0;
3247
+ for (&self.timer_slots) |*slot| {
3248
+ if (slot.active and slot.fake) count += 1;
3249
+ }
3250
+ return count;
3251
+ }
3252
+
3253
+ /// The `index`-th recorded fake fx timer (slot order).
3254
+ pub fn pendingTimerAt(self: *Self, index: usize) ?TimerRequest {
3255
+ var seen: usize = 0;
3256
+ for (&self.timer_slots) |*slot| {
3257
+ if (!(slot.active and slot.fake)) continue;
3258
+ if (seen == index) {
3259
+ return .{
3260
+ .key = slot.key,
3261
+ .interval_ms = slot.interval_ms,
3262
+ .mode = slot.mode,
3263
+ };
3264
+ }
3265
+ seen += 1;
3266
+ }
3267
+ return null;
3268
+ }
3269
+
3270
+ /// Fire the fake fx timer with `key` by hand: its `on_fire` Msg
3271
+ /// (timestamp 0 — the fake executor has no clock) lands through
3272
+ /// the pending ring and drains on the next `.effects_wake`
3273
+ /// dispatch or frame pump, exactly like `feedExit`. One-shot
3274
+ /// timers retire after the fire; repeating timers stay armed.
3275
+ pub fn fireTimer(self: *Self, key: u64) error{EffectNotFound}!void {
3276
+ const index = self.findActiveTimerIndex(key) orelse return error.EffectNotFound;
3277
+ const slot = &self.timer_slots[index];
3278
+ if (!slot.fake) return error.EffectNotFound;
3279
+ const on_fire = slot.on_fire;
3280
+ const key_copy = slot.key;
3281
+ if (slot.mode == .one_shot) slot.active = false;
3282
+ self.deliverLoopTimer(.{ .key = key_copy, .timestamp_ns = 0 }, on_fire);
3283
+ self.wakeHost();
3284
+ }
3285
+
3286
+ // ---------------------------------------------------------- internals
3287
+
3288
+ fn ensureIo(self: *Self) !std.Io {
3289
+ if (io_threaded_supported) {
3290
+ if (self.io_threaded == null) {
3291
+ const threaded = try self.allocator.create(IoThreaded);
3292
+ // `environ` defaults to `.empty` in `InitOptions`, which
3293
+ // would hand every spawned child a blank environment (no
3294
+ // HOME, no PATH) — always pass the host environment.
3295
+ threaded.* = IoThreaded.init(self.allocator, .{
3296
+ .environ = self.environ orelse fallbackEnviron(),
3297
+ });
3298
+ self.io_threaded = threaded;
3299
+ }
3300
+ return self.io_threaded.?.io();
3301
+ } else {
3302
+ return error.IoUnsupported;
3303
+ }
3304
+ }
3305
+
3306
+ fn wakeHost(self: *Self) void {
3307
+ const services = self.services orelse return;
3308
+ services.wake() catch {};
3309
+ }
3310
+
3311
+ fn reject(self: *Self, options: SpawnOptions) void {
3312
+ self.deliverLoopExit(.{
3313
+ .key = options.key,
3314
+ .code = effect_error_exit_code,
3315
+ .reason = .rejected,
3316
+ }, options.on_exit);
3317
+ }
3318
+
3319
+ fn rejectFetch(self: *Self, options: FetchOptions) void {
3320
+ self.deliverLoopResponse(.{
3321
+ .key = options.key,
3322
+ .outcome = .rejected,
3323
+ }, options.on_response);
3324
+ }
3325
+
3326
+ fn rejectFile(self: *Self, key: u64, op: EffectFileOp, file_fn: ?FileMsgFn) void {
3327
+ self.deliverLoopFile(.{
3328
+ .key = key,
3329
+ .op = op,
3330
+ .outcome = .rejected,
3331
+ }, file_fn);
3332
+ }
3333
+
3334
+ fn rejectClipboard(self: *Self, key: u64, op: EffectClipboardOp, clipboard_fn: ?ClipboardMsgFn) void {
3335
+ self.deliverLoopClipboard(.{
3336
+ .key = key,
3337
+ .op = op,
3338
+ .outcome = .rejected,
3339
+ }, clipboard_fn);
3340
+ }
3341
+
3342
+ /// Queue a terminal clipboard result produced on the loop
3343
+ /// thread (rejections, fake cancels, feed fallbacks) for the
3344
+ /// next drain. Text here is always empty.
3345
+ fn deliverLoopClipboard(self: *Self, result: EffectClipboardResult, clipboard_fn: ?ClipboardMsgFn) void {
3346
+ if (clipboard_fn == null) return;
3347
+ self.deliverPending(.{ .clipboard = .{ .result = result, .clipboard_fn = clipboard_fn } });
3348
+ }
3349
+
3350
+ fn rejectTimer(self: *Self, options: StartTimerOptions) void {
3351
+ self.deliverLoopTimer(.{
3352
+ .key = options.key,
3353
+ .outcome = .rejected,
3354
+ }, options.on_fire);
3355
+ }
3356
+
3357
+ /// Queue an fx-timer Msg produced on the loop thread (rejections
3358
+ /// and fake-executor fires) for the next drain.
3359
+ fn deliverLoopTimer(self: *Self, timer: EffectTimer, timer_fn: ?TimerMsgFn) void {
3360
+ if (timer_fn == null) return;
3361
+ self.deliverPending(.{ .timer = .{ .timer = timer, .timer_fn = timer_fn } });
3362
+ }
3363
+
3364
+ /// Update the channel mirrors from one audio event and stamp the
3365
+ /// channel's key into it. Null when the channel is idle — a
3366
+ /// platform straggler after `stopAudio` (or a fed event racing a
3367
+ /// stop) is swallowed rather than misattributed. Position and
3368
+ /// duration are the platform's readout, taken verbatim;
3369
+ /// `.completed` pins position to the duration and `.failed`
3370
+ /// resets the channel (nothing is left to resume).
3371
+ fn applyAudioEvent(self: *Self, event: EffectAudio) ?EffectAudio {
3372
+ if (!self.audio.active) return null;
3373
+ var resolved = event;
3374
+ resolved.key = self.audio.key;
3375
+ switch (resolved.kind) {
3376
+ .loaded, .position => {
3377
+ self.audio.position_ms = resolved.position_ms;
3378
+ if (resolved.duration_ms > 0) self.audio.duration_ms = resolved.duration_ms;
3379
+ self.audio.playing = resolved.playing;
3380
+ // The platform is the buffering authority from its
3381
+ // first report on: `.loaded` means bytes decoded
3382
+ // (stream underway), so the optimistic start-of-
3383
+ // stream flag clears here unless the event holds it.
3384
+ self.audio.buffering = resolved.buffering;
3385
+ },
3386
+ .completed => {
3387
+ if (resolved.duration_ms > 0) self.audio.duration_ms = resolved.duration_ms;
3388
+ resolved.position_ms = self.audio.duration_ms;
3389
+ resolved.playing = false;
3390
+ resolved.buffering = false;
3391
+ self.audio.position_ms = self.audio.duration_ms;
3392
+ self.audio.playing = false;
3393
+ self.audio.buffering = false;
3394
+ },
3395
+ .failed, .rejected => {
3396
+ resolved.playing = false;
3397
+ resolved.buffering = false;
3398
+ self.audio = .{ .volume = self.audio.volume };
3399
+ },
3400
+ // Band reports never steer the transport mirrors — the
3401
+ // position ticks stay the clock authority; the channel
3402
+ // only mirrors the latest bands (and counts deliveries)
3403
+ // for the automation snapshot's live evidence.
3404
+ .spectrum => {
3405
+ self.audio.spectrum_bands = resolved.bands;
3406
+ self.audio.spectrum_events +%= 1;
3407
+ },
3408
+ }
3409
+ return resolved;
3410
+ }
3411
+
3412
+ /// A synchronous platform refusal (`audioLoad`/`audioPlay`
3413
+ /// errored, or no services are bound): reset the channel and
3414
+ /// deliver one `.failed` event on the next drain — the honest
3415
+ /// degrade for hosts without audio playback.
3416
+ fn failAudioChannel(self: *Self) void {
3417
+ const key = self.audio.key;
3418
+ const on_event = self.audio.on_event;
3419
+ self.audio = .{ .volume = self.audio.volume };
3420
+ self.deliverLoopAudio(.{ .key = key, .kind = .failed }, on_event);
3421
+ }
3422
+
3423
+ /// Queue an audio event Msg produced on the loop thread
3424
+ /// (rejections and synchronous failures) for the next drain.
3425
+ fn deliverLoopAudio(self: *Self, event: EffectAudio, audio_fn: ?AudioMsgFn) void {
3426
+ if (audio_fn == null) return;
3427
+ self.deliverPending(.{ .audio = .{ .event = event, .audio_fn = audio_fn, .resolve = false } });
3428
+ }
3429
+
3430
+ fn effectTimerPlatformId(slot_index: usize) u64 {
3431
+ return effect_timer_platform_id_base + @as(u64, slot_index);
3432
+ }
3433
+
3434
+ fn timerIndexForPlatformId(platform_id: u64) ?usize {
3435
+ if (platform_id < effect_timer_platform_id_base) return null;
3436
+ const index = platform_id - effect_timer_platform_id_base;
3437
+ if (index >= max_effect_timers) return null;
3438
+ return @intCast(index);
3439
+ }
3440
+
3441
+ fn findActiveTimerIndex(self: *Self, key: u64) ?usize {
3442
+ for (&self.timer_slots, 0..) |*slot, index| {
3443
+ if (slot.active and slot.key == key) return index;
3444
+ }
3445
+ return null;
3446
+ }
3447
+
3448
+ fn findIdleTimerIndex(self: *Self) ?usize {
3449
+ for (&self.timer_slots, 0..) |*slot, index| {
3450
+ if (!slot.active) return index;
3451
+ }
3452
+ return null;
3453
+ }
3454
+
3455
+ /// Free a fetch slot's body and line buffers and return it to
3456
+ /// `.idle` (spawn-time failures and fake cancels). Loop-thread
3457
+ /// only.
3458
+ fn releaseFetchSlot(self: *Self, slot: *Slot) void {
3459
+ if (slot.fetch_buffer) |buffer| {
3460
+ self.allocator.free(buffer);
3461
+ slot.fetch_buffer = null;
3462
+ }
3463
+ if (slot.line_buffer) |buffer| {
3464
+ self.allocator.free(buffer);
3465
+ slot.line_buffer = null;
3466
+ }
3467
+ slot.state.store(.idle, .release);
3468
+ }
3469
+
3470
+ /// Free a spawn slot's collect and line buffers (if any) and
3471
+ /// return it to `.idle` (spawn-time failures, fake cancels, and
3472
+ /// feed fallbacks). Loop-thread only.
3473
+ fn releaseSpawnSlot(self: *Self, slot: *Slot) void {
3474
+ if (slot.collect_buffer) |buffer| {
3475
+ self.allocator.free(buffer);
3476
+ slot.collect_buffer = null;
3477
+ }
3478
+ if (slot.line_buffer) |buffer| {
3479
+ self.allocator.free(buffer);
3480
+ slot.line_buffer = null;
3481
+ }
3482
+ slot.state.store(.idle, .release);
3483
+ }
3484
+
3485
+ /// Queue an exit produced on the loop thread (rejections, fake
3486
+ /// cancel/exit fallbacks) for the next drain.
3487
+ fn deliverLoopExit(self: *Self, exit: EffectExit, exit_fn: ?ExitMsgFn) void {
3488
+ if (exit_fn == null) return;
3489
+ self.deliverPending(.{ .exit = .{ .exit = exit, .exit_fn = exit_fn } });
3490
+ }
3491
+
3492
+ /// Queue a terminal response produced on the loop thread (fetch
3493
+ /// rejections, fake cancels) for the next drain. Bodies here are
3494
+ /// always empty.
3495
+ fn deliverLoopResponse(self: *Self, response: EffectResponse, response_fn: ?ResponseMsgFn) void {
3496
+ if (response_fn == null) return;
3497
+ self.deliverPending(.{ .response = .{ .response = response, .response_fn = response_fn } });
3498
+ }
3499
+
3500
+ /// Queue a terminal file result produced on the loop thread
3501
+ /// (file rejections, fake cancels, feed fallbacks) for the next
3502
+ /// drain. Bytes here are always empty.
3503
+ fn deliverLoopFile(self: *Self, result: EffectFileResult, file_fn: ?FileMsgFn) void {
3504
+ if (file_fn == null) return;
3505
+ self.deliverPending(.{ .file = .{ .result = result, .file_fn = file_fn } });
3506
+ }
3507
+
3508
+ /// Push onto the loop-side pending ring. When the ring is full
3509
+ /// the oldest entry is replaced and the replacement carries the
3510
+ /// loss in its drop counter — overflow stays visible.
3511
+ fn deliverPending(self: *Self, pending: PendingMsg) void {
3512
+ if (self.pending_exit_len == max_effect_pending_exits) {
3513
+ const oldest = &self.pending_exits[self.pending_exit_head];
3514
+ self.pending_exit_head = (self.pending_exit_head + 1) % max_effect_pending_exits;
3515
+ self.pending_exit_len -= 1;
3516
+ var replacement = pending;
3517
+ replacement.addDropped(oldest.droppedCount() +| 1);
3518
+ const tail = (self.pending_exit_head + self.pending_exit_len) % max_effect_pending_exits;
3519
+ self.pending_exits[tail] = replacement;
3520
+ self.pending_exit_len += 1;
3521
+ } else {
3522
+ const tail = (self.pending_exit_head + self.pending_exit_len) % max_effect_pending_exits;
3523
+ self.pending_exits[tail] = pending;
3524
+ self.pending_exit_len += 1;
3525
+ }
3526
+ self.wakeHost();
3527
+ }
3528
+
3529
+ fn takePendingMsg(self: *Self) ?PendingMsg {
3530
+ if (self.pending_exit_len == 0) return null;
3531
+ const pending = self.pending_exits[self.pending_exit_head];
3532
+ self.pending_exit_head = (self.pending_exit_head + 1) % max_effect_pending_exits;
3533
+ self.pending_exit_len -= 1;
3534
+ return pending;
3535
+ }
3536
+
3537
+ fn findIdleSlot(self: *Self) ?usize {
3538
+ for (&self.slots, 0..) |*slot, index| {
3539
+ if (slot.state.load(.acquire) == .idle) return index;
3540
+ }
3541
+ return null;
3542
+ }
3543
+
3544
+ fn findActiveSlot(self: *Self, key: u64) ?usize {
3545
+ for (&self.slots, 0..) |*slot, index| {
3546
+ if (slot.state.load(.acquire) == .running and slot.key == key) return index;
3547
+ }
3548
+ return null;
3549
+ }
3550
+
3551
+ /// The most recent no-longer-running occupant with `key` (done
3552
+ /// or already reclaimed to idle) — the spawn a racing cancel is
3553
+ /// aimed at.
3554
+ fn findFinishedSlot(self: *Self, key: u64) ?usize {
3555
+ var best: ?usize = null;
3556
+ for (&self.slots, 0..) |*slot, index| {
3557
+ if (slot.state.load(.acquire) == .running) continue;
3558
+ if (slot.generation == 0 or slot.key != key) continue;
3559
+ if (best == null or self.slots[best.?].generation < slot.generation) best = index;
3560
+ }
3561
+ return best;
3562
+ }
3563
+
3564
+ fn findActiveFakeSlot(self: *Self, key: u64, kind: SlotKind) ?usize {
3565
+ const index = self.findActiveSlot(key) orelse return null;
3566
+ if (!self.slots[index].fake) return null;
3567
+ if (self.slots[index].kind != kind) return null;
3568
+ return index;
3569
+ }
3570
+
3571
+ fn reclaimSlots(self: *Self) void {
3572
+ for (&self.slots) |*slot| {
3573
+ switch (slot.state.load(.acquire)) {
3574
+ .done => slot.state.store(.idle, .release),
3575
+ // A draining slot is reusable once the drain took its
3576
+ // heap buffer (fetch body or collected stdout — the
3577
+ // terminal Msg was delivered).
3578
+ .draining => if (slot.fetch_buffer == null and slot.collect_buffer == null) slot.state.store(.idle, .release),
3579
+ else => {},
3580
+ }
3581
+ }
3582
+ }
3583
+
3584
+ fn enqueue(self: *Self, entry: *const Entry) bool {
3585
+ self.queue_mutex.lock();
3586
+ defer self.queue_mutex.unlock();
3587
+ if (self.queue_len == max_effect_queue_entries) return false;
3588
+ const tail = (self.queue_head + self.queue_len) % max_effect_queue_entries;
3589
+ self.queue[tail] = entry.*;
3590
+ self.queue_len += 1;
3591
+ self.queue_count.store(self.queue_len, .release);
3592
+ return true;
3593
+ }
3594
+
3595
+ fn dequeueInto(self: *Self, out: *Entry) bool {
3596
+ self.queue_mutex.lock();
3597
+ defer self.queue_mutex.unlock();
3598
+ if (self.queue_len == 0) return false;
3599
+ out.* = self.queue[self.queue_head];
3600
+ self.queue_head = (self.queue_head + 1) % max_effect_queue_entries;
3601
+ self.queue_len -= 1;
3602
+ self.queue_count.store(self.queue_len, .release);
3603
+ return true;
3604
+ }
3605
+
3606
+ /// Append stdout bytes to a collect spawn's buffer, truncating at
3607
+ /// the collect bound with the flag set. Single-writer: the worker
3608
+ /// in real mode, the loop thread (feedLine) in fake mode.
3609
+ fn appendCollected(slot: *Slot, bytes: []const u8) void {
3610
+ const buffer = slot.collect_buffer orelse return;
3611
+ const remaining = buffer.len - slot.collect_len;
3612
+ const take = @min(bytes.len, remaining);
3613
+ @memcpy(buffer[slot.collect_len..][0..take], bytes[0..take]);
3614
+ slot.collect_len += take;
3615
+ if (take < bytes.len) slot.collect_truncated = true;
3616
+ }
3617
+
3618
+ /// Append stderr bytes to a collect spawn's tail ring (the last
3619
+ /// `max_effect_stderr_tail_bytes` win). Single-writer, like
3620
+ /// `appendCollected`.
3621
+ fn appendStderrTail(slot: *Slot, bytes: []const u8) void {
3622
+ for (bytes) |byte| {
3623
+ slot.stderr_ring[slot.stderr_total % max_effect_stderr_tail_bytes] = byte;
3624
+ slot.stderr_total += 1;
3625
+ }
3626
+ }
3627
+
3628
+ /// Stamp a collect spawn's terminal payload onto its exit entry:
3629
+ /// the output length/flag (bytes stay in the slot buffer until
3630
+ /// the drain takes them) and the linearized stderr tail (oldest
3631
+ /// kept byte first) into the entry's line buffer.
3632
+ fn stampCollectExit(slot: *const Slot, entry: *Entry) void {
3633
+ entry.collect = true;
3634
+ entry.collect_len = @intCast(slot.collect_len);
3635
+ entry.collect_truncated = slot.collect_truncated;
3636
+ const tail_len = @min(slot.stderr_total, max_effect_stderr_tail_bytes);
3637
+ entry.stderr_truncated = slot.stderr_total > max_effect_stderr_tail_bytes;
3638
+ const start = if (slot.stderr_total > max_effect_stderr_tail_bytes)
3639
+ slot.stderr_total % max_effect_stderr_tail_bytes
3640
+ else
3641
+ 0;
3642
+ var index: usize = 0;
3643
+ while (index < tail_len) : (index += 1) {
3644
+ entry.line_bytes[index] = slot.stderr_ring[(start + index) % max_effect_stderr_tail_bytes];
3645
+ }
3646
+ entry.line_len = @intCast(tail_len);
3647
+ }
3648
+
3649
+ /// Producer-side line delivery with drop accounting, bounded by
3650
+ /// the slot's `line_limit`. Lines beyond the inline entry buffer
3651
+ /// (a raised `max_line_bytes`) ride a per-line heap allocation
3652
+ /// the drain retires; if that allocation fails the line degrades
3653
+ /// to the inline bound, truncated and flagged — never silent.
3654
+ fn produceLine(self: *Self, slot: *Slot, slot_index: u16, generation: u32, bytes: []const u8, truncated: bool) void {
3655
+ var len = @min(bytes.len, slot.line_limit);
3656
+ var entry: Entry = .{
3657
+ .kind = .line,
3658
+ .slot_index = slot_index,
3659
+ .generation = generation,
3660
+ .key = slot.key,
3661
+ .truncated = truncated or bytes.len > slot.line_limit,
3662
+ .dropped_before = slot.dropped_pending,
3663
+ .line_fn = slot.on_line,
3664
+ };
3665
+ if (len <= max_effect_line_bytes) {
3666
+ @memcpy(entry.line_bytes[0..len], bytes[0..len]);
3667
+ } else if (self.allocator.alloc(u8, len)) |heap| {
3668
+ @memcpy(heap, bytes[0..len]);
3669
+ entry.heap_line = heap;
3670
+ } else |_| {
3671
+ len = max_effect_line_bytes;
3672
+ entry.truncated = true;
3673
+ @memcpy(entry.line_bytes[0..len], bytes[0..len]);
3674
+ }
3675
+ entry.line_len = @intCast(len);
3676
+ if (self.enqueue(&entry)) {
3677
+ slot.dropped_pending = 0;
3678
+ } else {
3679
+ if (entry.heap_line) |heap| self.allocator.free(heap);
3680
+ slot.dropped_pending +|= 1;
3681
+ slot.dropped_total +|= 1;
3682
+ }
3683
+ self.wakeHost();
3684
+ }
3685
+
3686
+ /// Send a kill to the published child id, but only while the
3687
+ /// worker has not begun reaping (guarded by the slot mutex), so
3688
+ /// the pid/handle is guaranteed to still name this process.
3689
+ fn killPublishedChild(self: *Self, slot: *Slot) void {
3690
+ _ = self;
3691
+ slot.child_mutex.lock();
3692
+ defer slot.child_mutex.unlock();
3693
+ if (slot.reaping) return;
3694
+ const id = slot.child_id orelse return;
3695
+ if (builtin.os.tag == .windows) {
3696
+ _ = std.os.windows.ntdll.NtTerminateProcess(id, @enumFromInt(1));
3697
+ } else {
3698
+ std.posix.kill(id, .KILL) catch {};
3699
+ }
3700
+ }
3701
+
3702
+ // ------------------------------------------------------------ worker
3703
+
3704
+ fn workerMain(self: *Self, slot_index: usize, generation: u32, io: std.Io) void {
3705
+ const slot = &self.slots[slot_index];
3706
+ var exit: EffectExit = .{
3707
+ .key = slot.key,
3708
+ .code = effect_error_exit_code,
3709
+ .reason = .spawn_failed,
3710
+ };
3711
+ self.runChild(slot, @intCast(slot_index), generation, io, &exit);
3712
+ exit.dropped_lines = slot.dropped_total;
3713
+ self.postExit(slot, @intCast(slot_index), generation, io, exit);
3714
+ // A collect slot still owns its stdout buffer; park it in
3715
+ // `.draining` until the drain takes the buffer (fetch-style).
3716
+ slot.state.store(if (slot.output_mode == .collect) .draining else .done, .release);
3717
+ self.wakeHost();
3718
+ }
3719
+
3720
+ fn runChild(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io, exit: *EffectExit) void {
3721
+ var child = std.process.spawn(io, .{
3722
+ .argv = slot.argv(),
3723
+ .stdin = if (slot.stdin_len > 0) .pipe else .ignore,
3724
+ .stdout = .pipe,
3725
+ .stderr = if (slot.output_mode == .collect) .pipe else .ignore,
3726
+ }) catch return;
3727
+
3728
+ slot.child_mutex.lock();
3729
+ slot.child_id = child.id;
3730
+ slot.child_mutex.unlock();
3731
+ // A cancel that raced the spawn still lands.
3732
+ if (slot.cancel_requested.load(.acquire)) self.killPublishedChild(slot);
3733
+
3734
+ // Collect mode drains stderr concurrently so a chatty child
3735
+ // can never deadlock against a full stderr pipe while we read
3736
+ // stdout. The reader ends at stderr EOF (the child exiting),
3737
+ // and the join below runs before the exit is assembled, so
3738
+ // the tail ring is complete and single-threaded again by the
3739
+ // time it is read.
3740
+ var stderr_thread: ?std.Thread = null;
3741
+ defer if (stderr_thread) |thread| thread.join();
3742
+ if (child.stderr) |stderr_file| {
3743
+ stderr_thread = std.Thread.spawn(.{}, stderrTailMain, .{ slot, io, stderr_file }) catch null;
3744
+ }
3745
+
3746
+ if (child.stdin) |stdin_file| {
3747
+ stdin_file.writeStreamingAll(io, slot.stdinBytes()) catch {};
3748
+ stdin_file.close(io);
3749
+ child.stdin = null;
3750
+ }
3751
+
3752
+ if (child.stdout) |stdout_file| {
3753
+ if (slot.output_mode == .collect) {
3754
+ collectStdout(slot, io, stdout_file);
3755
+ } else {
3756
+ self.streamLines(slot, slot_index, generation, io, stdout_file);
3757
+ }
3758
+ }
3759
+
3760
+ // Thread-spawn failure fallback: drain stderr inline after
3761
+ // stdout closed (before reaping, so a child blocked on a full
3762
+ // stderr pipe still finishes).
3763
+ if (stderr_thread == null) {
3764
+ if (child.stderr) |stderr_file| collectStderrTail(slot, io, stderr_file);
3765
+ }
3766
+
3767
+ // Join the stderr reader BEFORE reaping: `child.wait` closes
3768
+ // the child's pipe files unconditionally, and a reader still
3769
+ // in flight races that close and loses the tail (it reads a
3770
+ // dead — or worse, recycled — descriptor). The join is safe
3771
+ // here: stdout already hit EOF, and stderr EOF arrives when
3772
+ // the child dies whether or not it has been reaped.
3773
+ if (stderr_thread) |thread| {
3774
+ thread.join();
3775
+ stderr_thread = null;
3776
+ }
3777
+
3778
+ slot.child_mutex.lock();
3779
+ slot.reaping = true;
3780
+ slot.child_mutex.unlock();
3781
+ const term = child.wait(io) catch {
3782
+ exit.* = .{ .key = slot.key, .code = effect_error_exit_code, .reason = .signaled };
3783
+ return;
3784
+ };
3785
+ exit.* = switch (term) {
3786
+ .exited => |code| .{ .key = slot.key, .code = code, .reason = .exited },
3787
+ else => .{ .key = slot.key, .code = effect_error_exit_code, .reason = .signaled },
3788
+ };
3789
+ if (slot.cancel_requested.load(.acquire)) {
3790
+ exit.reason = .cancelled;
3791
+ exit.code = effect_error_exit_code;
3792
+ }
3793
+ }
3794
+
3795
+ fn streamLines(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io, stdout_file: std.Io.File) void {
3796
+ var read_buffer: [1024]u8 = undefined;
3797
+ // Spawns with a raised `max_line_bytes` frame into their
3798
+ // slot's heap buffer; everyone else uses the stack.
3799
+ var stack_buffer: [max_effect_line_bytes]u8 = undefined;
3800
+ const line_buffer: []u8 = slot.line_buffer orelse &stack_buffer;
3801
+ const limit = @min(slot.line_limit, line_buffer.len);
3802
+ var line_len: usize = 0;
3803
+ var truncated = false;
3804
+ while (true) {
3805
+ const read_slices: [1][]u8 = .{&read_buffer};
3806
+ const count = stdout_file.readStreaming(io, &read_slices) catch break;
3807
+ for (read_buffer[0..count]) |byte| {
3808
+ if (byte == '\n') {
3809
+ self.produceLine(slot, slot_index, generation, line_buffer[0..line_len], truncated);
3810
+ line_len = 0;
3811
+ truncated = false;
3812
+ } else if (line_len < limit) {
3813
+ line_buffer[line_len] = byte;
3814
+ line_len += 1;
3815
+ } else {
3816
+ truncated = true;
3817
+ }
3818
+ }
3819
+ }
3820
+ if (line_len > 0 or truncated) {
3821
+ self.produceLine(slot, slot_index, generation, line_buffer[0..line_len], truncated);
3822
+ }
3823
+ }
3824
+
3825
+ /// Collect-mode stdout: raw bytes into the slot's heap buffer,
3826
+ /// no line framing, bounded by `max_effect_collect_bytes`.
3827
+ fn collectStdout(slot: *Slot, io: std.Io, stdout_file: std.Io.File) void {
3828
+ var read_buffer: [4096]u8 = undefined;
3829
+ while (true) {
3830
+ const read_slices: [1][]u8 = .{&read_buffer};
3831
+ const count = stdout_file.readStreaming(io, &read_slices) catch break;
3832
+ if (count == 0) break;
3833
+ appendCollected(slot, read_buffer[0..count]);
3834
+ }
3835
+ }
3836
+
3837
+ fn stderrTailMain(slot: *Slot, io: std.Io, stderr_file: std.Io.File) void {
3838
+ collectStderrTail(slot, io, stderr_file);
3839
+ }
3840
+
3841
+ /// Collect-mode stderr: keep the last
3842
+ /// `max_effect_stderr_tail_bytes` bytes in the slot's tail ring.
3843
+ fn collectStderrTail(slot: *Slot, io: std.Io, stderr_file: std.Io.File) void {
3844
+ var read_buffer: [1024]u8 = undefined;
3845
+ while (true) {
3846
+ const read_slices: [1][]u8 = .{&read_buffer};
3847
+ const count = stderr_file.readStreaming(io, &read_slices) catch break;
3848
+ if (count == 0) break;
3849
+ appendStderrTail(slot, read_buffer[0..count]);
3850
+ }
3851
+ }
3852
+
3853
+ // ------------------------------------------------------ fetch worker
3854
+
3855
+ /// Supervises one fetch: runs the blocking HTTP exchange as a
3856
+ /// cancelable `Io` task and polls for completion, cancel, and
3857
+ /// the timeout deadline. Ends by posting exactly one `.response`
3858
+ /// entry and parking the slot in `.draining` (the drain retires
3859
+ /// it after taking the body buffer).
3860
+ fn fetchWorkerMain(self: *Self, slot_index: usize, generation: u32, io: std.Io) void {
3861
+ const slot = &self.slots[slot_index];
3862
+ supervise: {
3863
+ var future = std.Io.concurrent(io, fetchTask, .{ self, slot, @as(u16, @intCast(slot_index)), generation, io }) catch {
3864
+ // No concurrent capacity: run the exchange inline.
3865
+ // Cancels can no longer interrupt mid-transfer and
3866
+ // the timeout is not enforced, but the terminal Msg
3867
+ // still lands (a raced cancel is rewritten at drain).
3868
+ fetchTask(self, slot, @intCast(slot_index), generation, io);
3869
+ break :supervise;
3870
+ };
3871
+ const poll_ms: u64 = 5;
3872
+ var waited_ms: u64 = 0;
3873
+ var timed_out = false;
3874
+ while (true) {
3875
+ if (slot.fetch_done.load(.acquire)) break;
3876
+ if (self.shutdown.load(.acquire) or slot.cancel_requested.load(.acquire)) {
3877
+ future.cancel(io);
3878
+ break;
3879
+ }
3880
+ if (waited_ms >= slot.timeout_ms) {
3881
+ timed_out = true;
3882
+ future.cancel(io);
3883
+ break;
3884
+ }
3885
+ std.Io.sleep(io, std.Io.Duration.fromMilliseconds(poll_ms), .awake) catch {};
3886
+ waited_ms += poll_ms;
3887
+ }
3888
+ future.await(io);
3889
+ if (!slot.fetch_done.load(.acquire)) {
3890
+ // Interrupted before the task recorded a terminal
3891
+ // state (never expected — the task always records).
3892
+ slot.fetch_status = 0;
3893
+ slot.body_len = 0;
3894
+ slot.fetch_truncated = false;
3895
+ slot.fetch_outcome = if (timed_out) .timed_out else .cancelled;
3896
+ } else if (timed_out and slot.fetch_outcome != .ok) {
3897
+ // The interruption was the deadline, not the app.
3898
+ // The interrupted exchange may have surfaced as any
3899
+ // I/O error (a cancelled blocking read reports
3900
+ // ReadFailed, not Canceled), so every non-ok
3901
+ // outcome here is the timeout's doing. A response
3902
+ // that completed before the deadline fired stays a
3903
+ // delivered `.ok`.
3904
+ slot.fetch_outcome = .timed_out;
3905
+ slot.fetch_status = 0;
3906
+ slot.body_len = 0;
3907
+ slot.fetch_truncated = false;
3908
+ }
3909
+ }
3910
+ self.postResponse(slot, @intCast(slot_index), generation, io);
3911
+ slot.state.store(.draining, .release);
3912
+ self.wakeHost();
3913
+ }
3914
+
3915
+ /// The blocking exchange, run as a cancelable task. Always
3916
+ /// records a terminal state in the slot before `fetch_done`.
3917
+ fn fetchTask(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io) void {
3918
+ defer slot.fetch_done.store(true, .release);
3919
+ self.runFetch(slot, slot_index, generation, io) catch |err| {
3920
+ slot.fetch_status = 0;
3921
+ slot.body_len = 0;
3922
+ slot.fetch_truncated = false;
3923
+ slot.fetch_outcome = classifyFetchError(err);
3924
+ };
3925
+ }
3926
+
3927
+ fn runFetch(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io) !void {
3928
+ const uri = try std.Uri.parse(slot.fetchUrl());
3929
+ var client: std.http.Client = .{ .allocator = self.allocator, .io = io };
3930
+ defer client.deinit();
3931
+ var request = client.request(slot.method, uri, .{
3932
+ .keep_alive = false,
3933
+ .extra_headers = slot.fetchHeaders(),
3934
+ // Mirrors `std.http.Client.fetch`: payloads cannot be
3935
+ // replayed across redirects.
3936
+ .redirect_behavior = if (slot.payload_len > 0) .unhandled else @enumFromInt(3),
3937
+ }) catch |err| {
3938
+ // Establishing the connection is what `request` does, so
3939
+ // an UNTYPED failure here is a connect failure. (The
3940
+ // Windows net layer surfaces refused/unreachable connects
3941
+ // as NTSTATUS codes it does not translate into typed
3942
+ // errors; without this, those reported `.protocol_failed`
3943
+ // even though no protocol exchange ever began.)
3944
+ if (err == error.Unexpected) return error.ConnectPhaseFailed;
3945
+ return err;
3946
+ };
3947
+ defer request.deinit();
3948
+ if (slot.payload_len > 0) {
3949
+ request.transfer_encoding = .{ .content_length = slot.payload_len };
3950
+ var body = try request.sendBodyUnflushed(&.{});
3951
+ try body.writer.writeAll(slot.fetchPayload());
3952
+ try body.end();
3953
+ try request.connection.?.flush();
3954
+ } else {
3955
+ try request.sendBodiless();
3956
+ }
3957
+ var redirect_buffer: [8 * 1024]u8 = undefined;
3958
+ var response = try request.receiveHead(&redirect_buffer);
3959
+ slot.fetch_status = @intFromEnum(response.head.status);
3960
+
3961
+ const decompress_buffer: []u8 = switch (response.head.content_encoding) {
3962
+ .identity => &.{},
3963
+ .zstd => try self.allocator.alloc(u8, std.compress.zstd.default_window_len),
3964
+ .deflate, .gzip => try self.allocator.alloc(u8, std.compress.flate.max_window_len),
3965
+ .compress => return error.UnsupportedCompressionMethod,
3966
+ };
3967
+ defer if (decompress_buffer.len > 0) self.allocator.free(decompress_buffer);
3968
+ var transfer_buffer: [4096]u8 = undefined;
3969
+ var decompress: std.http.Decompress = undefined;
3970
+ const reader = response.readerDecompressing(&transfer_buffer, &decompress, decompress_buffer);
3971
+
3972
+ if (slot.fetch_response_mode == .stream) {
3973
+ // Frame the body into on_line entries as bytes arrive —
3974
+ // the spawn `.lines` contract over HTTP. A broken stream
3975
+ // surfaces through the terminal outcome; lines delivered
3976
+ // before the break stand.
3977
+ try self.streamFetchLines(slot, slot_index, generation, reader, &response);
3978
+ slot.body_len = 0;
3979
+ slot.fetch_truncated = false;
3980
+ slot.fetch_outcome = .ok;
3981
+ return;
3982
+ }
3983
+
3984
+ const buffer = slot.fetch_buffer.?;
3985
+ var body_writer = std.Io.Writer.fixed(buffer[slot.payload_len..]);
3986
+ _ = reader.streamRemaining(&body_writer) catch |err| switch (err) {
3987
+ // The bounded body space filled: deliver the first
3988
+ // `max_effect_body_bytes` bytes with the flag set.
3989
+ error.WriteFailed => slot.fetch_truncated = true,
3990
+ error.ReadFailed => return response.bodyErr() orelse error.ReadFailed,
3991
+ };
3992
+ slot.body_len = body_writer.end;
3993
+ slot.fetch_outcome = .ok;
3994
+ }
3995
+
3996
+ /// Line-frame a streaming fetch's body, mirroring `streamLines`:
3997
+ /// every '\n'-terminated line becomes one queued `on_line`
3998
+ /// entry, bounded by the slot's `line_limit` with truncation
3999
+ /// flagged; a trailing unterminated line is delivered at end of
4000
+ /// stream. Read failures propagate so the terminal outcome
4001
+ /// reports the break (cancel interruptions included — the drain
4002
+ /// rewrites those to `.cancelled` and filters queued lines).
4003
+ fn streamFetchLines(
4004
+ self: *Self,
4005
+ slot: *Slot,
4006
+ slot_index: u16,
4007
+ generation: u32,
4008
+ reader: *std.Io.Reader,
4009
+ response: *std.http.Client.Response,
4010
+ ) !void {
4011
+ var stack_buffer: [max_effect_line_bytes]u8 = undefined;
4012
+ const line_buffer: []u8 = slot.line_buffer orelse &stack_buffer;
4013
+ const limit = @min(slot.line_limit, line_buffer.len);
4014
+ var line_len: usize = 0;
4015
+ var truncated = false;
4016
+ while (true) {
4017
+ const byte = reader.takeByte() catch |err| switch (err) {
4018
+ error.EndOfStream => break,
4019
+ error.ReadFailed => return response.bodyErr() orelse error.ReadFailed,
4020
+ };
4021
+ if (byte == '\n') {
4022
+ self.produceLine(slot, slot_index, generation, line_buffer[0..line_len], truncated);
4023
+ line_len = 0;
4024
+ truncated = false;
4025
+ } else if (line_len < limit) {
4026
+ line_buffer[line_len] = byte;
4027
+ line_len += 1;
4028
+ } else {
4029
+ truncated = true;
4030
+ }
4031
+ }
4032
+ if (line_len > 0 or truncated) {
4033
+ self.produceLine(slot, slot_index, generation, line_buffer[0..line_len], truncated);
4034
+ }
4035
+ }
4036
+
4037
+ /// The terminal response must never be dropped: retry until the
4038
+ /// loop thread drains space, giving up only on shutdown.
4039
+ fn postResponse(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io) void {
4040
+ var entry: Entry = .{
4041
+ .kind = .response,
4042
+ .slot_index = slot_index,
4043
+ .generation = generation,
4044
+ .key = slot.key,
4045
+ .line_len = @intCast(slot.body_len),
4046
+ .truncated = slot.fetch_truncated,
4047
+ // Stream-mode lines dropped on a full queue that no
4048
+ // later line reported land on the terminal instead.
4049
+ .dropped_before = slot.dropped_pending,
4050
+ .status = slot.fetch_status,
4051
+ .outcome = slot.fetch_outcome,
4052
+ .response_fn = slot.on_response,
4053
+ };
4054
+ while (!self.enqueue(&entry)) {
4055
+ if (self.shutdown.load(.acquire)) return;
4056
+ self.wakeHost();
4057
+ std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake) catch {};
4058
+ }
4059
+ }
4060
+
4061
+ /// Exits must never be dropped: retry until the loop thread
4062
+ /// drains space, giving up only on shutdown.
4063
+ fn postExit(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io, exit: EffectExit) void {
4064
+ var entry: Entry = .{
4065
+ .kind = .exit,
4066
+ .slot_index = slot_index,
4067
+ .generation = generation,
4068
+ .key = exit.key,
4069
+ .code = exit.code,
4070
+ .reason = exit.reason,
4071
+ .dropped_lines = exit.dropped_lines,
4072
+ .exit_fn = slot.on_exit,
4073
+ };
4074
+ if (slot.output_mode == .collect) stampCollectExit(slot, &entry);
4075
+ while (!self.enqueue(&entry)) {
4076
+ if (self.shutdown.load(.acquire)) return;
4077
+ self.wakeHost();
4078
+ std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake) catch {};
4079
+ }
4080
+ }
4081
+
4082
+ // ------------------------------------------------------- file worker
4083
+
4084
+ /// Runs one file effect: the blocking read/write happens right
4085
+ /// here on the worker thread (local file IO is quick — no
4086
+ /// timeout supervision), then exactly one `.file` terminal
4087
+ /// entry posts and the slot parks in `.draining` until the
4088
+ /// drain takes its buffer. `cancel` does not interrupt the OS
4089
+ /// call: it marks the generation and the drain rewrites the
4090
+ /// terminal to `.cancelled` (the operation itself may still
4091
+ /// have completed on disk, as `EffectFileOutcome.cancelled`
4092
+ /// documents).
4093
+ fn fileWorkerMain(self: *Self, slot_index: usize, generation: u32, io: std.Io) void {
4094
+ const slot = &self.slots[slot_index];
4095
+ var read_len: usize = 0;
4096
+ const outcome = runFileOp(slot, io, &read_len);
4097
+ slot.body_len = read_len;
4098
+ self.postFile(slot, @intCast(slot_index), generation, io, outcome, read_len);
4099
+ slot.state.store(.draining, .release);
4100
+ self.wakeHost();
4101
+ }
4102
+
4103
+ fn runFileOp(slot: *Slot, io: std.Io, read_len: *usize) EffectFileOutcome {
4104
+ const cwd = std.Io.Dir.cwd();
4105
+ const file_path = slot.filePath();
4106
+ switch (slot.file_op) {
4107
+ .write => {
4108
+ if (std.fs.path.dirname(file_path)) |parent| {
4109
+ cwd.createDirPath(io, parent) catch return .io_failed;
4110
+ }
4111
+ cwd.writeFile(io, .{
4112
+ .sub_path = file_path,
4113
+ .data = slot.fetchPayload(),
4114
+ }) catch return .io_failed;
4115
+ return .ok;
4116
+ },
4117
+ .read => {
4118
+ var file = cwd.openFile(io, file_path, .{}) catch |err| {
4119
+ return if (err == error.FileNotFound) .not_found else .io_failed;
4120
+ };
4121
+ defer file.close(io);
4122
+ // The buffer has one byte past the delivery bound:
4123
+ // filling it proves the file is over-bound.
4124
+ const buffer = slot.fetch_buffer.?;
4125
+ const len = file.readPositionalAll(io, buffer, 0) catch return .io_failed;
4126
+ if (len > max_effect_file_bytes) {
4127
+ read_len.* = max_effect_file_bytes;
4128
+ return .truncated;
4129
+ }
4130
+ read_len.* = len;
4131
+ return .ok;
4132
+ },
4133
+ }
4134
+ }
4135
+
4136
+ /// The terminal file result must never be dropped: retry until
4137
+ /// the loop thread drains space, giving up only on shutdown.
4138
+ fn postFile(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io, outcome: EffectFileOutcome, read_len: usize) void {
4139
+ var entry: Entry = .{
4140
+ .kind = .file,
4141
+ .slot_index = slot_index,
4142
+ .generation = generation,
4143
+ .key = slot.key,
4144
+ .line_len = @intCast(read_len),
4145
+ .file_op = slot.file_op,
4146
+ .file_outcome = outcome,
4147
+ .file_fn = slot.on_file,
4148
+ };
4149
+ while (!self.enqueue(&entry)) {
4150
+ if (self.shutdown.load(.acquire)) return;
4151
+ self.wakeHost();
4152
+ std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake) catch {};
4153
+ }
4154
+ }
4155
+ };
4156
+ }
4157
+
4158
+ test "effect payload types have documented defaults" {
4159
+ const line: EffectLine = .{ .key = 7, .line = "hello" };
4160
+ try std.testing.expect(!line.truncated);
4161
+ try std.testing.expectEqual(@as(u32, 0), line.dropped_before);
4162
+ const exit: EffectExit = .{ .key = 7 };
4163
+ try std.testing.expectEqual(EffectExitReason.exited, exit.reason);
4164
+ try std.testing.expectEqual(@as(u32, 0), exit.dropped_lines);
4165
+ try std.testing.expectEqualStrings("", exit.output);
4166
+ try std.testing.expect(!exit.output_truncated);
4167
+ try std.testing.expectEqualStrings("", exit.stderr_tail);
4168
+ try std.testing.expect(!exit.stderr_truncated);
4169
+ const response: EffectResponse = .{ .key = 7 };
4170
+ try std.testing.expectEqual(EffectFetchOutcome.ok, response.outcome);
4171
+ try std.testing.expectEqual(@as(u16, 0), response.status);
4172
+ try std.testing.expectEqualStrings("", response.body);
4173
+ try std.testing.expect(!response.truncated);
4174
+ try std.testing.expectEqual(@as(u32, 0), response.dropped_before);
4175
+ const file_result: EffectFileResult = .{ .key = 7 };
4176
+ try std.testing.expectEqual(EffectFileOp.read, file_result.op);
4177
+ try std.testing.expectEqual(EffectFileOutcome.ok, file_result.outcome);
4178
+ try std.testing.expectEqualStrings("", file_result.bytes);
4179
+ try std.testing.expectEqual(@as(u32, 0), file_result.dropped_before);
4180
+ const timer: EffectTimer = .{ .key = 7 };
4181
+ try std.testing.expectEqual(@as(u64, 0), timer.timestamp_ns);
4182
+ try std.testing.expectEqual(EffectTimerOutcome.fired, timer.outcome);
4183
+ }
4184
+
4185
+ test "fx timer platform ids stay inside the reserved range and clear of the markup watch id" {
4186
+ try std.testing.expect(effect_timer_platform_id_base >= platform.reserved_timer_id_base);
4187
+ try std.testing.expect(effect_timer_platform_id_base + max_effect_timers - 1 < 0xffff_ffff_2e70_a11c);
4188
+ }
4189
+
4190
+ test "fetch errors map onto the documented taxonomy" {
4191
+ try std.testing.expectEqual(EffectFetchOutcome.cancelled, classifyFetchError(error.Canceled));
4192
+ try std.testing.expectEqual(EffectFetchOutcome.connect_failed, classifyFetchError(error.ConnectionRefused));
4193
+ try std.testing.expectEqual(EffectFetchOutcome.connect_failed, classifyFetchError(error.UnknownHostName));
4194
+ try std.testing.expectEqual(EffectFetchOutcome.tls_failed, classifyFetchError(error.TlsInitializationFailed));
4195
+ try std.testing.expectEqual(EffectFetchOutcome.rejected, classifyFetchError(error.UnsupportedUriScheme));
4196
+ try std.testing.expectEqual(EffectFetchOutcome.protocol_failed, classifyFetchError(error.HttpHeadersInvalid));
4197
+ }