@zyro-sec/tui 1.0.2 → 1.0.3

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 (573) hide show
  1. package/AGENTS.md +6 -6
  2. package/bunfig.toml +4 -4
  3. package/package.json +11 -11
  4. package/src/app.tsx +1632 -1632
  5. package/src/attention-sounds.bun.ts +8 -8
  6. package/src/attention-sounds.node.ts +16 -16
  7. package/src/attention.ts +189 -189
  8. package/src/audio.d.ts +9 -9
  9. package/src/audio.ts +49 -49
  10. package/src/clipboard.ts +68 -68
  11. package/src/component/background-image.tsx +26 -26
  12. package/src/component/command-palette.tsx +74 -74
  13. package/src/component/devtools-bar.tsx +611 -611
  14. package/src/component/dialog-agent.tsx +33 -33
  15. package/src/component/dialog-background.tsx +102 -102
  16. package/src/component/dialog-config.tsx +494 -494
  17. package/src/component/dialog-debug.tsx +90 -90
  18. package/src/component/dialog-error-details.tsx +130 -130
  19. package/src/component/dialog-experiments.tsx +101 -101
  20. package/src/component/dialog-go-upsell.tsx +448 -448
  21. package/src/component/dialog-highlights.tsx +88 -88
  22. package/src/component/dialog-image-preview.tsx +85 -85
  23. package/src/component/dialog-install-mcp.tsx +25 -3
  24. package/src/component/dialog-integration.tsx +1332 -1332
  25. package/src/component/dialog-mcp.tsx +184 -184
  26. package/src/component/dialog-model-free.tsx +79 -79
  27. package/src/component/dialog-model.tsx +238 -238
  28. package/src/component/dialog-open.tsx +509 -509
  29. package/src/component/dialog-pair.tsx +123 -123
  30. package/src/component/dialog-session-list.tsx +328 -328
  31. package/src/component/dialog-session-rename.tsx +37 -37
  32. package/src/component/dialog-shell-output.tsx +194 -194
  33. package/src/component/dialog-skill.tsx +93 -93
  34. package/src/component/dialog-speed.tsx +48 -48
  35. package/src/component/dialog-stash.tsx +90 -90
  36. package/src/component/dialog-status.tsx +50 -50
  37. package/src/component/dialog-theme-list.tsx +56 -56
  38. package/src/component/dialog-update.tsx +144 -144
  39. package/src/component/dialog-variant.tsx +43 -43
  40. package/src/component/dialog-workspace-file-changes.tsx +187 -187
  41. package/src/component/dialog-workspaces.tsx +413 -413
  42. package/src/component/dialog-worktree-name.tsx +40 -40
  43. package/src/component/error-component.tsx +258 -258
  44. package/src/component/fade-in-text.tsx +113 -113
  45. package/src/component/go-upsell-art.ts +338 -338
  46. package/src/component/logo.tsx +79 -79
  47. package/src/component/masked-text.ts +59 -59
  48. package/src/component/media-source.ts +43 -43
  49. package/src/component/migration-overlay.tsx +73 -73
  50. package/src/component/model-options.tsx +121 -121
  51. package/src/component/one-cell-spinner.tsx +75 -75
  52. package/src/component/panel-host.tsx +64 -64
  53. package/src/component/patch-diff.tsx +211 -211
  54. package/src/component/plugin-route-missing.tsx +21 -21
  55. package/src/component/prompt/autocomplete.tsx +1005 -1005
  56. package/src/component/prompt/draft-stash.ts +47 -47
  57. package/src/component/prompt/index.tsx +2080 -2080
  58. package/src/component/prompt/local-attachment.ts +188 -188
  59. package/src/component/prompt/metadata.tsx +193 -193
  60. package/src/component/prompt/move.tsx +181 -181
  61. package/src/component/reconnecting.tsx +40 -40
  62. package/src/component/retry-provider.tsx +202 -202
  63. package/src/component/session-frame.tsx +408 -408
  64. package/src/component/session-tabs-rail.tsx +94 -94
  65. package/src/component/session-tabs.tsx +1789 -1789
  66. package/src/component/shimmer-text.tsx +64 -64
  67. package/src/component/spinner-frames.ts +1 -1
  68. package/src/component/spinner-renderable.ts +126 -126
  69. package/src/component/spinner.tsx +50 -50
  70. package/src/component/startup-loading.tsx +63 -63
  71. package/src/component/tab-pulse.tsx +819 -819
  72. package/src/component/terminal-pane.tsx +377 -377
  73. package/src/component/theme-error-toast.tsx +20 -20
  74. package/src/component/title-shimmer.tsx +272 -272
  75. package/src/component/todo-item.tsx +27 -27
  76. package/src/component/usage.tsx +329 -329
  77. package/src/component/use-connected.tsx +14 -14
  78. package/src/config/index.tsx +438 -438
  79. package/src/config/keybind.ts +367 -367
  80. package/src/config/new-session-location.ts +16 -16
  81. package/src/config/v1/index.tsx +149 -149
  82. package/src/config/v1/keybind.ts +463 -463
  83. package/src/context/args.tsx +31 -31
  84. package/src/context/attention.tsx +23 -23
  85. package/src/context/client-mcp.tsx +119 -119
  86. package/src/context/client.tsx +76 -76
  87. package/src/context/clipboard.tsx +19 -19
  88. package/src/context/data.tsx +69 -69
  89. package/src/context/editor.ts +408 -408
  90. package/src/context/epilogue.tsx +14 -14
  91. package/src/context/event.ts +32 -32
  92. package/src/context/exit.tsx +8 -8
  93. package/src/context/helper.tsx +26 -26
  94. package/src/context/interactivity.tsx +20 -20
  95. package/src/context/keymap.tsx +515 -515
  96. package/src/context/local.tsx +723 -723
  97. package/src/context/location.tsx +80 -80
  98. package/src/context/log.tsx +24 -24
  99. package/src/context/panel.tsx +59 -59
  100. package/src/context/path-format.tsx +12 -12
  101. package/src/context/permission.tsx +18 -18
  102. package/src/context/program-status.ts +94 -94
  103. package/src/context/prompt.tsx +18 -18
  104. package/src/context/route.tsx +73 -73
  105. package/src/context/runtime.tsx +98 -98
  106. package/src/context/session-tabs-model.ts +263 -263
  107. package/src/context/session-tabs.tsx +508 -508
  108. package/src/context/session-terminals.tsx +136 -136
  109. package/src/context/storage.tsx +150 -150
  110. package/src/context/theme.tsx +447 -447
  111. package/src/context/thinking.ts +20 -20
  112. package/src/context/update-notification.tsx +158 -158
  113. package/src/devtools/index.ts +41 -41
  114. package/src/editor-zed-sqlite.bun.ts +1 -1
  115. package/src/editor-zed-sqlite.node.ts +21 -21
  116. package/src/editor-zed.ts +277 -277
  117. package/src/editor.ts +86 -86
  118. package/src/feature-plugins/home/footer.tsx +116 -116
  119. package/src/feature-plugins/prompt/btw.tsx +190 -190
  120. package/src/feature-plugins/prompt/footer.tsx +163 -163
  121. package/src/feature-plugins/prompt/goal.tsx +211 -211
  122. package/src/feature-plugins/sidebar/context.tsx +52 -52
  123. package/src/feature-plugins/sidebar/footer.tsx +126 -126
  124. package/src/feature-plugins/sidebar/limit.tsx +47 -47
  125. package/src/feature-plugins/sidebar/mcp.tsx +103 -103
  126. package/src/feature-plugins/sidebar/todo.tsx +58 -58
  127. package/src/feature-plugins/system/diff-viewer-file-menu.tsx +87 -87
  128. package/src/feature-plugins/system/diff-viewer-file-tree-utils.ts +174 -174
  129. package/src/feature-plugins/system/diff-viewer-file-tree.tsx +274 -274
  130. package/src/feature-plugins/system/diff-viewer-image.tsx +96 -96
  131. package/src/feature-plugins/system/diff-viewer.tsx +1380 -1380
  132. package/src/feature-plugins/system/notifications.ts +102 -102
  133. package/src/feature-plugins/system/plugins.tsx +356 -356
  134. package/src/feature-plugins/system/stats-data.ts +18 -18
  135. package/src/feature-plugins/system/stats.tsx +217 -217
  136. package/src/feature-plugins/system/storybook/footer.tsx +51 -51
  137. package/src/feature-plugins/system/storybook/highlights.tsx +71 -71
  138. package/src/feature-plugins/system/storybook/index.tsx +153 -153
  139. package/src/feature-plugins/system/storybook/link-clicks.tsx +125 -125
  140. package/src/feature-plugins/system/storybook/merman-layouts.tsx +200 -200
  141. package/src/feature-plugins/system/storybook/one-cell-spinner.fixtures.ts +144 -144
  142. package/src/feature-plugins/system/storybook/one-cell-spinner.tsx +293 -293
  143. package/src/feature-plugins/system/storybook/session-location-missing.tsx +80 -80
  144. package/src/feature-plugins/system/storybook/session-tabs.tsx +571 -571
  145. package/src/feature-plugins/system/storybook/subcell-spinner.fixtures.ts +115 -115
  146. package/src/feature-plugins/system/storybook/todo.tsx +166 -166
  147. package/src/index.tsx +2 -2
  148. package/src/logo.ts +21 -21
  149. package/src/mini/catalog.shared.ts +116 -116
  150. package/src/mini/demo.ts +1086 -1086
  151. package/src/mini/entry.body.ts +244 -244
  152. package/src/mini/footer.command.tsx +1205 -1205
  153. package/src/mini/footer.form.tsx +647 -647
  154. package/src/mini/footer.menu.tsx +313 -313
  155. package/src/mini/footer.permission.tsx +562 -562
  156. package/src/mini/footer.prompt.tsx +1533 -1533
  157. package/src/mini/footer.subagent.tsx +268 -268
  158. package/src/mini/footer.ts +1193 -1193
  159. package/src/mini/footer.view.tsx +1022 -1022
  160. package/src/mini/footer.width.ts +118 -118
  161. package/src/mini/form.shared.ts +241 -241
  162. package/src/mini/index.ts +7 -7
  163. package/src/mini/mono.ts +277 -277
  164. package/src/mini/permission.shared.ts +199 -199
  165. package/src/mini/prompt.editor.ts +74 -74
  166. package/src/mini/prompt.shared.ts +192 -192
  167. package/src/mini/runtime.boot.ts +98 -98
  168. package/src/mini/runtime.lifecycle.ts +393 -393
  169. package/src/mini/runtime.queue.ts +320 -320
  170. package/src/mini/runtime.ts +1117 -1117
  171. package/src/mini/scrollback.shared.ts +82 -82
  172. package/src/mini/scrollback.surface.ts +548 -548
  173. package/src/mini/scrollback.writer.tsx +380 -380
  174. package/src/mini/session-data.ts +13 -13
  175. package/src/mini/session.shared.ts +113 -113
  176. package/src/mini/splash.ts +307 -307
  177. package/src/mini/stream-v2.fragment.ts +83 -83
  178. package/src/mini/stream-v2.image.ts +38 -38
  179. package/src/mini/stream-v2.subagent.ts +1130 -1130
  180. package/src/mini/stream-v2.transport.ts +1916 -1916
  181. package/src/mini/stream.ts +152 -152
  182. package/src/mini/theme.ts +328 -328
  183. package/src/mini/tool.public.ts +3 -3
  184. package/src/mini/tool.ts +1394 -1394
  185. package/src/mini/turn-summary.ts +21 -21
  186. package/src/mini/types.ts +482 -482
  187. package/src/mini/variant.shared.ts +58 -58
  188. package/src/mini/verbosity.ts +84 -84
  189. package/src/model-preference.ts +206 -206
  190. package/src/parsers-config.ts +386 -386
  191. package/src/plugin/api.tsx +486 -486
  192. package/src/plugin/builtins.ts +35 -35
  193. package/src/plugin/context.tsx +757 -757
  194. package/src/plugin/discovery.ts +67 -67
  195. package/src/plugin/markdown.ts +18 -18
  196. package/src/plugin/render.tsx +116 -116
  197. package/src/plugin/runtime-plugin-support.bun.ts +11 -11
  198. package/src/plugin/runtime-plugin-support.node.ts +1 -1
  199. package/src/plugin/source.ts +1 -1
  200. package/src/plugin/structure.ts +159 -159
  201. package/src/plugin/watch.ts +113 -113
  202. package/src/prompt/attachment.ts +97 -97
  203. package/src/prompt/codec.ts +61 -61
  204. package/src/prompt/content.ts +22 -22
  205. package/src/prompt/directory-completion.ts +97 -97
  206. package/src/prompt/directory-recents.ts +36 -36
  207. package/src/prompt/display.ts +41 -41
  208. package/src/prompt/frecency.tsx +80 -80
  209. package/src/prompt/history.tsx +175 -175
  210. package/src/prompt/mention.ts +173 -173
  211. package/src/prompt/parse.ts +25 -25
  212. package/src/prompt/part.ts +35 -35
  213. package/src/prompt/restore.ts +39 -39
  214. package/src/prompt/stash.tsx +93 -93
  215. package/src/prompt/traits.ts +29 -29
  216. package/src/routes/home.tsx +180 -180
  217. package/src/routes/session/activity-summary.ts +101 -101
  218. package/src/routes/session/anchor-view.tsx +53 -53
  219. package/src/routes/session/anchors.ts +85 -85
  220. package/src/routes/session/composer/context.ts +24 -24
  221. package/src/routes/session/composer/index.tsx +143 -143
  222. package/src/routes/session/composer/scripts-tab.tsx +166 -166
  223. package/src/routes/session/composer/shell-tab.tsx +149 -149
  224. package/src/routes/session/composer/subagents-tab.tsx +264 -264
  225. package/src/routes/session/composer/tabs.ts +91 -91
  226. package/src/routes/session/composer/terminals-tab.tsx +114 -114
  227. package/src/routes/session/dialog-execute.tsx +276 -276
  228. package/src/routes/session/dialog-fork.tsx +87 -87
  229. package/src/routes/session/dialog-message.tsx +89 -89
  230. package/src/routes/session/dialog-timeline.tsx +43 -43
  231. package/src/routes/session/form.tsx +1177 -1177
  232. package/src/routes/session/group-view.tsx +407 -407
  233. package/src/routes/session/grouping/session.ts +184 -184
  234. package/src/routes/session/grouping/tree.ts +111 -111
  235. package/src/routes/session/history.ts +59 -59
  236. package/src/routes/session/index.tsx +3922 -3922
  237. package/src/routes/session/location-missing.tsx +81 -81
  238. package/src/routes/session/message-navigation.ts +48 -48
  239. package/src/routes/session/message-parts.tsx +322 -322
  240. package/src/routes/session/mount-budget.ts +38 -38
  241. package/src/routes/session/permission.tsx +622 -622
  242. package/src/routes/session/render-context.tsx +44 -44
  243. package/src/routes/session/rows.ts +493 -493
  244. package/src/routes/session/sidebar.tsx +80 -80
  245. package/src/routes/session/thinking-syntax.ts +8 -8
  246. package/src/runtime.tsx +1 -1
  247. package/src/simulation/semantics.ts +12 -12
  248. package/src/theme/assets/aura.json +69 -69
  249. package/src/theme/assets/ayu.json +80 -80
  250. package/src/theme/assets/carbonfox.json +248 -248
  251. package/src/theme/assets/catppuccin-frappe.json +230 -230
  252. package/src/theme/assets/catppuccin-macchiato.json +230 -230
  253. package/src/theme/assets/catppuccin.json +112 -112
  254. package/src/theme/assets/cobalt2.json +225 -225
  255. package/src/theme/assets/cursor.json +249 -249
  256. package/src/theme/assets/dracula.json +219 -219
  257. package/src/theme/assets/everforest.json +241 -241
  258. package/src/theme/assets/flexoki.json +237 -237
  259. package/src/theme/assets/github.json +233 -233
  260. package/src/theme/assets/gruvbox.json +242 -242
  261. package/src/theme/assets/kanagawa.json +77 -77
  262. package/src/theme/assets/lucent-orng.json +234 -234
  263. package/src/theme/assets/material.json +235 -235
  264. package/src/theme/assets/matrix.json +77 -77
  265. package/src/theme/assets/mercury.json +252 -252
  266. package/src/theme/assets/monokai.json +221 -221
  267. package/src/theme/assets/nightowl.json +221 -221
  268. package/src/theme/assets/nord.json +223 -223
  269. package/src/theme/assets/one-dark.json +84 -84
  270. package/src/theme/assets/opencode.json +245 -245
  271. package/src/theme/assets/orng.json +249 -249
  272. package/src/theme/assets/osaka-jade.json +93 -93
  273. package/src/theme/assets/palenight.json +222 -222
  274. package/src/theme/assets/rosepine.json +234 -234
  275. package/src/theme/assets/solarized.json +223 -223
  276. package/src/theme/assets/synthwave84.json +226 -226
  277. package/src/theme/assets/tokyonight.json +243 -243
  278. package/src/theme/assets/v2/opencode-classic.json +387 -387
  279. package/src/theme/assets/v2/opencode.json +395 -395
  280. package/src/theme/assets/vercel.json +245 -245
  281. package/src/theme/assets/vesper.json +218 -218
  282. package/src/theme/assets/zenburn.json +223 -223
  283. package/src/theme/color.ts +48 -48
  284. package/src/theme/component.ts +51 -51
  285. package/src/theme/discovery.ts +21 -21
  286. package/src/theme/index.ts +109 -109
  287. package/src/theme/resolve.ts +53 -53
  288. package/src/theme/system.ts +144 -144
  289. package/src/theme/v1.ts +70 -70
  290. package/src/ui/animation.ts +235 -235
  291. package/src/ui/border.ts +21 -21
  292. package/src/ui/dialog-alert.tsx +51 -51
  293. package/src/ui/dialog-confirm.tsx +62 -62
  294. package/src/ui/dialog-export-options.tsx +316 -316
  295. package/src/ui/dialog-export-result.tsx +84 -84
  296. package/src/ui/dialog-help.tsx +40 -40
  297. package/src/ui/dialog-prompt.tsx +180 -180
  298. package/src/ui/dialog-select.tsx +1006 -1006
  299. package/src/ui/dialog.tsx +560 -560
  300. package/src/ui/file-path.tsx +112 -112
  301. package/src/ui/layout.ts +26 -26
  302. package/src/ui/link.tsx +51 -51
  303. package/src/ui/one-cell-motion.ts +111 -111
  304. package/src/ui/pane-resize-handle.tsx +33 -33
  305. package/src/ui/pane-resize.ts +76 -76
  306. package/src/ui/select-controller.ts +45 -45
  307. package/src/ui/session-link.ts +92 -92
  308. package/src/ui/spinner.ts +368 -368
  309. package/src/ui/subcell.ts +37 -37
  310. package/src/ui/toast.tsx +222 -222
  311. package/src/ui/working-directory-actions.tsx +66 -66
  312. package/src/util/collapse-tool-output.ts +95 -95
  313. package/src/util/config-directories.ts +53 -53
  314. package/src/util/connected-provider.ts +15 -15
  315. package/src/util/delayed-presence.ts +34 -34
  316. package/src/util/diff.ts +84 -84
  317. package/src/util/error-details.ts +21 -21
  318. package/src/util/error.ts +141 -141
  319. package/src/util/filetype.ts +135 -135
  320. package/src/util/form.ts +146 -146
  321. package/src/util/highlights.ts +51 -51
  322. package/src/util/locale.ts +81 -81
  323. package/src/util/marquee.ts +51 -51
  324. package/src/util/media.ts +43 -43
  325. package/src/util/model.ts +33 -33
  326. package/src/util/path-format.ts +37 -37
  327. package/src/util/path.ts +12 -12
  328. package/src/util/permission.ts +188 -188
  329. package/src/util/persistence.ts +42 -42
  330. package/src/util/presentation.ts +42 -42
  331. package/src/util/project.ts +7 -7
  332. package/src/util/record.ts +3 -3
  333. package/src/util/renderer.ts +15 -15
  334. package/src/util/scroll.ts +29 -29
  335. package/src/util/selection.ts +103 -103
  336. package/src/util/session.ts +103 -103
  337. package/src/util/signal.ts +49 -49
  338. package/src/util/single-flight.ts +12 -12
  339. package/src/util/string-width.bun.ts +1 -1
  340. package/src/util/string-width.node.ts +26 -26
  341. package/src/util/string-width.ts +1 -1
  342. package/src/util/system.ts +23 -23
  343. package/src/util/todo.ts +43 -43
  344. package/src/util/tool-display.ts +70 -70
  345. package/src/util/usage-limits.ts +152 -152
  346. package/src/util/watch.ts +24 -24
  347. package/test/app-lifecycle.test.tsx +2962 -2962
  348. package/test/clear-session.test.tsx +67 -67
  349. package/test/cli/tui/__snapshots__/inline-tool-wrap-snapshot.test.tsx.snap +22 -22
  350. package/test/cli/tui/command-palette.test.tsx +86 -86
  351. package/test/cli/tui/composer-keymap.test.tsx +346 -346
  352. package/test/cli/tui/data.test.tsx +3669 -3669
  353. package/test/cli/tui/dialog-integration.test.tsx +588 -588
  354. package/test/cli/tui/dialog-mcp.test.tsx +197 -197
  355. package/test/cli/tui/dialog-open.test.tsx +1037 -1037
  356. package/test/cli/tui/dialog-prompt.test.tsx +253 -253
  357. package/test/cli/tui/dialog-select.test.tsx +740 -740
  358. package/test/cli/tui/dialog-session-list.test.tsx +130 -130
  359. package/test/cli/tui/diff-viewer-file-tree.test.tsx +256 -256
  360. package/test/cli/tui/diff-viewer-image.test.tsx +172 -172
  361. package/test/cli/tui/diff-viewer.test.tsx +2510 -2510
  362. package/test/cli/tui/form.test.tsx +950 -950
  363. package/test/cli/tui/group-view.test.tsx +352 -352
  364. package/test/cli/tui/inline-tool-wrap-snapshot.test.tsx +248 -248
  365. package/test/cli/tui/input-scope.test.tsx +282 -282
  366. package/test/cli/tui/keymap-arguments.test.tsx +45 -45
  367. package/test/cli/tui/plugins-dialog.test.tsx +217 -217
  368. package/test/cli/tui/prompt-interrupt-status.test.tsx +25 -25
  369. package/test/cli/tui/prompt-move.test.tsx +446 -446
  370. package/test/cli/tui/reasoning-body.test.tsx +80 -80
  371. package/test/cli/tui/theme-mode.test.tsx +179 -179
  372. package/test/cli/tui/toast.test.tsx +117 -117
  373. package/test/cli/tui/use-event.test.tsx +295 -295
  374. package/test/client-mcp.test.tsx +226 -226
  375. package/test/command-selection.test.tsx +123 -123
  376. package/test/compact-admission.test.tsx +251 -251
  377. package/test/completion-notices.test.tsx +197 -197
  378. package/test/component/animation-ticks.test.tsx +212 -212
  379. package/test/component/dialog-error-details.test.tsx +110 -110
  380. package/test/component/dialog-export-options.test.tsx +68 -68
  381. package/test/component/dialog-highlights.test.tsx +73 -73
  382. package/test/component/dialog-model.test.tsx +145 -145
  383. package/test/component/dialog-shell-output.test.tsx +255 -255
  384. package/test/component/dialog-speed.test.tsx +114 -114
  385. package/test/component/dialog-update.test.tsx +111 -111
  386. package/test/component/dialog-variant.test.tsx +24 -24
  387. package/test/component/go-upsell-art.test.tsx +110 -110
  388. package/test/component/retry-provider.test.tsx +288 -288
  389. package/test/component/session-tabs-marquee.test.tsx +100 -100
  390. package/test/component/session-tabs-mouse.test.tsx +216 -216
  391. package/test/component/session-tabs-rail.test.tsx +120 -120
  392. package/test/component/session-tabs-status.test.tsx +345 -345
  393. package/test/component/shimmer-text.test.tsx +37 -37
  394. package/test/component/spinner-renderable.test.tsx +133 -133
  395. package/test/component/tab-pulse.test.tsx +196 -196
  396. package/test/config-v2.test.tsx +335 -335
  397. package/test/config.test.tsx +184 -184
  398. package/test/context/local-selection.test.tsx +204 -204
  399. package/test/context/session-tabs.test.tsx +864 -864
  400. package/test/context/theme.test.tsx +183 -183
  401. package/test/copy-session-id.test.tsx +79 -79
  402. package/test/feature-plugins/goal.test.tsx +126 -126
  403. package/test/feature-plugins/prompt-footer.test.tsx +303 -303
  404. package/test/feature-plugins/sidebar-context.test.tsx +70 -70
  405. package/test/feature-plugins/sidebar-footer.test.tsx +139 -139
  406. package/test/fixture/animation-ticks.ts +19 -19
  407. package/test/fixture/app.ts +95 -95
  408. package/test/fixture/diff-image.ts +7 -7
  409. package/test/fixture/fixture.ts +27 -27
  410. package/test/fixture/frame.ts +25 -25
  411. package/test/fixture/local.tsx +158 -158
  412. package/test/fixture/plugin/client-reads/tui.tsx +9 -9
  413. package/test/fixture/plugin/dialog-throw/tui.tsx +11 -11
  414. package/test/fixture/plugin/native-resources/tui.tsx +26 -26
  415. package/test/fixture/plugin/setup-keymap/tui.tsx +72 -72
  416. package/test/fixture/plugin/slot-string/tui.tsx +10 -10
  417. package/test/fixture/tui-client.ts +186 -186
  418. package/test/fixture/tui-environment.tsx +47 -47
  419. package/test/fixture/tui-runtime.ts +21 -21
  420. package/test/interactivity.test.tsx +46 -46
  421. package/test/keymap-scope.test.tsx +271 -271
  422. package/test/keymap.test.tsx +244 -244
  423. package/test/markdown-streaming.test.tsx +49 -49
  424. package/test/mini/blocker.responsive.test.tsx +732 -732
  425. package/test/mini/fixture/catalog.ts +63 -63
  426. package/test/mini/fixture/footer-api.ts +69 -69
  427. package/test/mini/fixture/tool-part.ts +20 -20
  428. package/test/mini/footer-keymap.test.tsx +141 -141
  429. package/test/mini/footer.responsive.test.tsx +438 -438
  430. package/test/mini/footer.view.test.tsx +2627 -2627
  431. package/test/new-session-id.test.tsx +102 -102
  432. package/test/plugin-keymap.test.tsx +143 -143
  433. package/test/plugin-markdown.test.tsx +120 -120
  434. package/test/plugin-model.test.tsx +46 -46
  435. package/test/plugin-native-resources.test.tsx +11 -11
  436. package/test/plugin-select.test.tsx +391 -391
  437. package/test/plugin-slot-output.test.tsx +23 -23
  438. package/test/plugin-toast.test.tsx +62 -62
  439. package/test/preload.ts +17 -17
  440. package/test/prompt/history-composer.test.tsx +52 -52
  441. package/test/prompt/history-provider.test.tsx +108 -108
  442. package/test/prompt-cursor.test.tsx +27 -27
  443. package/test/prompt-offset.test.tsx +58 -58
  444. package/test/prompt-paste.test.tsx +127 -127
  445. package/test/prompt-shell-failure.test.tsx +76 -76
  446. package/test/routes/composer-tabs.test.tsx +97 -97
  447. package/test/runtime.test.tsx +37 -37
  448. package/test/session-activity-anchor.test.tsx +180 -180
  449. package/test/session-backfill-disclosure.test.tsx +89 -89
  450. package/test/session-dialog-resync.test.tsx +122 -122
  451. package/test/session-fork-pending.test.tsx +60 -60
  452. package/test/session-group-navigation.test.tsx +252 -252
  453. package/test/session-history-interactions.test.tsx +305 -305
  454. package/test/session-history-reveal.test.tsx +108 -108
  455. package/test/session-home.test.tsx +401 -401
  456. package/test/session-interrupt-undo.test.tsx +98 -98
  457. package/test/session-media-refs.test.tsx +360 -360
  458. package/test/session-mount-budget.test.tsx +137 -137
  459. package/test/session-panel.test.tsx +721 -721
  460. package/test/session-shell-output.test.tsx +114 -114
  461. package/test/session-shell-stopped.test.tsx +107 -107
  462. package/test/session-subagent-navigation.test.tsx +44 -44
  463. package/test/session-submit-scroll.test.tsx +85 -85
  464. package/test/session-terminal-availability.test.tsx +80 -80
  465. package/test/session-wheel-focus.test.tsx +176 -176
  466. package/test/stats.view.test.tsx +94 -94
  467. package/test/theme/v2/types.typecheck.ts +57 -57
  468. package/test/ui/dialog-layout.test.tsx +56 -56
  469. package/test/ui/link.test.tsx +60 -60
  470. package/test/ui/pane-resize-handle.test.tsx +134 -134
  471. package/test/ui/session-link.test.tsx +325 -325
  472. package/test/usage-limits.test.tsx +162 -162
  473. package/test/util/selection-copy-on-select.test.tsx +64 -64
  474. package/tsconfig.json +13 -13
  475. package/test/cli/cmd/tui/integration-options.test.ts +0 -98
  476. package/test/cli/cmd/tui/model-options.test.ts +0 -105
  477. package/test/cli/cmd/tui/notifications.test.ts +0 -356
  478. package/test/cli/tui/anchors.test.ts +0 -77
  479. package/test/cli/tui/collapse-tool-output.test.ts +0 -14
  480. package/test/cli/tui/group-boundary.test.ts +0 -63
  481. package/test/cli/tui/grouping-tree.test.ts +0 -82
  482. package/test/cli/tui/message-navigation.test.ts +0 -164
  483. package/test/cli/tui/mount-budget.test.ts +0 -74
  484. package/test/cli/tui/permission.test.ts +0 -7
  485. package/test/cli/tui/script-changes.test.ts +0 -41
  486. package/test/cli/tui/session-grouping.test.ts +0 -21
  487. package/test/cli/tui/session-history.test.ts +0 -124
  488. package/test/cli/tui/session-rows.test.ts +0 -616
  489. package/test/cli/tui/session-verbosity.test.ts +0 -307
  490. package/test/cli/tui/thinking.test.ts +0 -36
  491. package/test/clipboard.test.ts +0 -148
  492. package/test/component/terminal-pane-theme.test.ts +0 -68
  493. package/test/context/local.test.ts +0 -15
  494. package/test/context/program-status.test.ts +0 -73
  495. package/test/context/session-retention.test.ts +0 -234
  496. package/test/context/session-tabs-model.test.ts +0 -341
  497. package/test/context/storage.test.ts +0 -37
  498. package/test/editor.test.ts +0 -69
  499. package/test/feature-plugins/diff-viewer-file-tree-utils.test.ts +0 -234
  500. package/test/feature-plugins/home-footer.test.ts +0 -13
  501. package/test/highlights.test.ts +0 -43
  502. package/test/keybind.test.ts +0 -7
  503. package/test/mini/catalog.shared.test.ts +0 -76
  504. package/test/mini/entry.body.test.ts +0 -622
  505. package/test/mini/footer.menu.test.ts +0 -43
  506. package/test/mini/footer.test.ts +0 -446
  507. package/test/mini/footer.width.test.ts +0 -120
  508. package/test/mini/form.shared.test.ts +0 -66
  509. package/test/mini/permission.shared.test.ts +0 -195
  510. package/test/mini/prompt.editor.test.ts +0 -118
  511. package/test/mini/prompt.shared.test.ts +0 -104
  512. package/test/mini/runtime.boot.test.ts +0 -118
  513. package/test/mini/runtime.queue.test.ts +0 -443
  514. package/test/mini/runtime.test.ts +0 -591
  515. package/test/mini/scrollback.image.test.ts +0 -213
  516. package/test/mini/scrollback.surface.test.ts +0 -1078
  517. package/test/mini/session.shared.test.ts +0 -267
  518. package/test/mini/splash.test.ts +0 -196
  519. package/test/mini/stream-v2.transport.test.ts +0 -4705
  520. package/test/mini/stream.test.ts +0 -52
  521. package/test/mini/theme.test.ts +0 -438
  522. package/test/mini/tool.test.ts +0 -134
  523. package/test/mini/variant.shared.test.ts +0 -58
  524. package/test/mini/verbosity.test.ts +0 -53
  525. package/test/model-preference.test.ts +0 -70
  526. package/test/new-session-location.test.ts +0 -30
  527. package/test/panel.test.ts +0 -71
  528. package/test/plugin-discovery.test.ts +0 -18
  529. package/test/plugin-source.test.ts +0 -871
  530. package/test/prompt/attachment.test.ts +0 -138
  531. package/test/prompt/autocomplete.test.ts +0 -218
  532. package/test/prompt/codec.test.ts +0 -136
  533. package/test/prompt/display.test.ts +0 -72
  534. package/test/prompt/draft-stash.test.ts +0 -42
  535. package/test/prompt/history.test.ts +0 -94
  536. package/test/prompt/jsonl.test.ts +0 -24
  537. package/test/prompt/local-attachment.test.ts +0 -244
  538. package/test/prompt/mention.test.ts +0 -119
  539. package/test/prompt/parse.test.ts +0 -46
  540. package/test/prompt/part.test.ts +0 -40
  541. package/test/prompt/persistence.test.ts +0 -23
  542. package/test/prompt/traits.test.ts +0 -25
  543. package/test/simulation/semantics.test.ts +0 -23
  544. package/test/stats.test.ts +0 -33
  545. package/test/theme/v2/component.test.ts +0 -87
  546. package/test/theme/v2/resolve.test.ts +0 -424
  547. package/test/theme/v2/select.test.ts +0 -25
  548. package/test/theme/v2/v1-migrate.test.ts +0 -397
  549. package/test/theme.test.ts +0 -150
  550. package/test/ui/file-path.test.ts +0 -61
  551. package/test/ui/layout.test.ts +0 -31
  552. package/test/ui/pane-resize.test.ts +0 -258
  553. package/test/ui/select-controller.test.ts +0 -44
  554. package/test/util/added-patch.test.ts +0 -44
  555. package/test/util/connected-provider.test.ts +0 -59
  556. package/test/util/delayed-presence.test.ts +0 -114
  557. package/test/util/error-details.test.ts +0 -26
  558. package/test/util/error.test.ts +0 -36
  559. package/test/util/filetype.test.ts +0 -23
  560. package/test/util/form.test.ts +0 -110
  561. package/test/util/locale.test.ts +0 -32
  562. package/test/util/marquee.test.ts +0 -45
  563. package/test/util/media.test.ts +0 -54
  564. package/test/util/model.test.ts +0 -70
  565. package/test/util/path-format.test.ts +0 -15
  566. package/test/util/permission.test.ts +0 -23
  567. package/test/util/presentation.test.ts +0 -30
  568. package/test/util/renderer.test.ts +0 -42
  569. package/test/util/selection-keys.test.ts +0 -172
  570. package/test/util/selection.test.ts +0 -115
  571. package/test/util/session.test.ts +0 -70
  572. package/test/util/tool-display.test.ts +0 -65
  573. package/test/util/usage-limits.test.ts +0 -154
@@ -1,757 +1,757 @@
1
- import type { PluginInfo } from "@zyro-sec/client"
2
- import type { Plugin } from "@zyro-sec/plugin/tui"
3
- import type { MarkdownCodeBlockRenderer, MarkdownOptions } from "@opentui/core"
4
- import {
5
- batch,
6
- createContext,
7
- createEffect,
8
- createMemo,
9
- createSignal,
10
- on,
11
- onCleanup,
12
- onMount,
13
- useContext,
14
- type ParentProps,
15
- } from "solid-js"
16
- import path from "path"
17
- import { stat } from "fs/promises"
18
- import { fileURLToPath } from "url"
19
- import type { Page } from "@zyro-sec/plugin/tui/context"
20
- import { Host } from "@zyro-sec/plugin/host"
21
- import { resolveSlots, type Claim } from "./structure"
22
- import { createStore, produce, reconcile as reconcileStore, unwrap } from "solid-js/store"
23
- import { isDeepEqual } from "remeda"
24
- import "#runtime-plugin-support"
25
- import { useConfig } from "../config"
26
- import { useTuiLifecycle } from "../context/runtime"
27
- import { useClient } from "../context/client"
28
- import { useData } from "../context/data"
29
- import { errorMessage } from "../util/error"
30
- import { createPluginContext, usePluginHost, type Dispose, type RegisteredSlot, type SlotRender } from "./api"
31
- import { createSourceWatcher } from "./watch"
32
- import { discoverPluginTargets, localSource, mergePluginTargets } from "./discovery"
33
- import { createPluginSources } from "./source"
34
- import { isMissingPath } from "../util/config-directories"
35
- import { createMarkdownRenderer } from "./markdown"
36
- import { useLog, type LogTags } from "../context/log"
37
-
38
- export interface PackageSource {
39
- readonly prepare: (spec: string, install?: boolean) => Promise<Host.Target>
40
- }
41
-
42
- type State =
43
- | { readonly target: string; readonly id: string; readonly status: "active" | "inactive" }
44
- | { readonly target: string; readonly status: "unsupported" }
45
- | { readonly target: string; readonly id?: string; readonly status: "failed"; readonly error: string }
46
-
47
- type RegisteredPlugin = {
48
- readonly id: string
49
- readonly source: "builtin" | "external"
50
- readonly active: boolean
51
- }
52
-
53
- type Value = {
54
- readonly ready: () => boolean
55
- readonly list: () => ReadonlyArray<State>
56
- readonly server: () => readonly PluginInfo[]
57
- readonly registered: () => ReadonlyArray<RegisteredPlugin>
58
- readonly route: (id: string, name: string) => Page["render"] | undefined
59
- readonly slots: {
60
- // A mounted <Slot> instance registers its path; the disposer unregisters.
61
- readonly register: (path: string) => () => void
62
- readonly resolved: () => ReturnType<typeof resolveSlots<SlotRender>>
63
- }
64
- readonly markdown: () => MarkdownOptions["renderBlock"]
65
- readonly activate: (id: string) => Promise<boolean>
66
- readonly deactivate: (id: string) => Promise<boolean>
67
- }
68
-
69
- type Registration = {
70
- plugin: Plugin.Definition
71
- source: RegisteredPlugin["source"]
72
- target?: string
73
- version: string
74
- options?: Readonly<Record<string, any>>
75
- active: boolean
76
- routes: Record<string, Page>
77
- slots: Record<string, RegisteredSlot>
78
- markdown: Record<string, MarkdownCodeBlockRenderer>
79
- cleanups: Dispose[]
80
- }
81
-
82
- // One entry of the desired plugin generation produced by the resolve phase.
83
- type Desired = Pick<Registration, "plugin" | "source" | "target" | "version" | "options"> & { enabled: boolean }
84
- type Trace = <T>(stage: string, tags: LogTags, task: () => Promise<T>) => Promise<T>
85
-
86
- const PluginContext = createContext<Value>()
87
-
88
- export function PluginProvider(props: ParentProps<{ packages: PackageSource; directories: string[] }>) {
89
- const host = usePluginHost()
90
- const log = useLog({ component: "plugin" })
91
- const config = useConfig()
92
- const lifecycle = useTuiLifecycle()
93
- const client = useClient()
94
- const data = useData()
95
- const [serverPlugins, setServerPlugins] = createSignal<readonly PluginInfo[]>([])
96
- const serverTuiPlugins = createMemo(() =>
97
- serverPlugins().filter(
98
- (plugin): plugin is PluginInfo & { readonly source: { readonly type: "package" } | { readonly type: "local" } } =>
99
- plugin.state.status === "active" &&
100
- plugin.features.tui === true &&
101
- (plugin.source.type === "package" || plugin.source.type === "local"),
102
- ),
103
- )
104
- const directory = config.path ? path.dirname(config.path) : process.cwd()
105
- const [store, setStore] = createStore({
106
- ready: false,
107
- states: [] as ReadonlyArray<State>,
108
- registrations: {} as Record<string, Registration>,
109
- })
110
- // One save can emit several watch events. Remember setup failures so those
111
- // events do not repeatedly tear down and restore the last good generation.
112
- const setupFailures = new Map<string, { version: string; options: Registration["options"]; error: string }>()
113
- let operationID = 0
114
- const trace: Trace = (stage, tags, task) => {
115
- const id = ++operationID
116
- const started = Date.now()
117
- log.debug("plugin operation started", { id, stage, ...tags })
118
- const stalled = setTimeout(
119
- () => log.warn("plugin operation stalled", { id, stage, elapsedMs: Date.now() - started, ...tags }),
120
- 5_000,
121
- )
122
- return task()
123
- .then(
124
- (value) => {
125
- log.debug("plugin operation completed", { id, stage, durationMs: Date.now() - started, ...tags })
126
- return value
127
- },
128
- (error) => {
129
- log.warn("plugin operation failed", {
130
- id,
131
- stage,
132
- durationMs: Date.now() - started,
133
- error: errorMessage(error),
134
- ...tags,
135
- })
136
- throw error
137
- },
138
- )
139
- .finally(() => clearTimeout(stalled))
140
- }
141
- const markdown = createMarkdownRenderer(() =>
142
- Object.values(store.registrations).flatMap((registration) => (registration.active ? [registration.markdown] : [])),
143
- )
144
- const clearContributions = (id: string) => {
145
- setStore("registrations", id, "routes", reconcileStore({}))
146
- setStore("registrations", id, "slots", reconcileStore({}))
147
- setStore("registrations", id, "markdown", reconcileStore({}))
148
- }
149
-
150
- const activate = async (id: string) => {
151
- const item = store.registrations[id]
152
- if (!item) return false
153
- await deactivate(id)
154
- batch(() => {
155
- clearContributions(id)
156
- setStore("registrations", id, "cleanups", [])
157
- })
158
- const owned: Dispose[] = []
159
- const context = createPluginContext({
160
- host,
161
- id,
162
- options: item.options,
163
- owned,
164
- registry: {
165
- has: (kind, name) => Boolean(store.registrations[id]?.[kind][name]),
166
- set: (
167
- kind: "routes" | "slots" | "markdown",
168
- name: string,
169
- value: Page | RegisteredSlot | MarkdownCodeBlockRenderer,
170
- ) => setStore("registrations", id, kind, name, () => value),
171
- remove: (kind, name) =>
172
- setStore(
173
- "registrations",
174
- produce((registrations) => {
175
- if (!registrations[id]) return
176
- delete registrations[id][kind][name]
177
- }),
178
- ),
179
- active: () => Boolean(store.registrations[id]?.active),
180
- },
181
- })
182
- const cleanup = await trace("setup", { plugin: id, target: item.target }, () =>
183
- setup(item.plugin, context, owned),
184
- ).catch((error) => {
185
- clearContributions(id)
186
- if (item.target)
187
- setupFailures.set(item.target, {
188
- version: item.version,
189
- options: snapshotOptions(item.options),
190
- error: errorMessage(error),
191
- })
192
- throw error
193
- })
194
- if (cleanup) owned.push(async () => cleanup())
195
- if (item.target && sameGeneration(setupFailures.get(item.target), item)) setupFailures.delete(item.target)
196
- batch(() => {
197
- setStore("registrations", id, "cleanups", owned)
198
- setStore("registrations", id, "active", true)
199
- setStore("states", (items) =>
200
- items.map((state) =>
201
- "id" in state && state.id === id ? { target: state.target, id, status: "active" } : state,
202
- ),
203
- )
204
- })
205
- return true
206
- }
207
-
208
- const deactivate = async (id: string) => {
209
- const item = store.registrations[id]
210
- if (!item?.active) return false
211
- const cleanups = [...item.cleanups]
212
- batch(() => {
213
- setStore("registrations", id, "active", false)
214
- setStore("registrations", id, "cleanups", [])
215
- })
216
- await trace("cleanup", { plugin: id, target: item.target, cleanups: cleanups.length }, () =>
217
- disposeAll(cleanups),
218
- ).finally(() =>
219
- batch(() => {
220
- if (store.registrations[id]) {
221
- clearContributions(id)
222
- }
223
- setStore("states", (items) =>
224
- items.map((state) =>
225
- "id" in state && state.id === id ? { target: state.target, id, status: "inactive" } : state,
226
- ),
227
- )
228
- }),
229
- )
230
- return true
231
- }
232
-
233
- // Cleanup failures must not stop a swap or teardown, but they should not
234
- // vanish either: the old generation may still own listeners or intervals.
235
- const deactivateNoisily = (id: string) =>
236
- deactivate(id).catch((error) =>
237
- host.toast.show({ variant: "error", title: "Plugin", message: `${id}: cleanup failed: ${errorMessage(error)}` }),
238
- )
239
-
240
- // Every lifecycle mutation — reconciles, manual dialog toggles, shutdown —
241
- // is serialized through one chain so generations can never interleave.
242
- let loading = Promise.resolve()
243
- const enqueue = <T,>(task: () => Promise<T>) => {
244
- const result = loading.catch(() => undefined).then(task)
245
- loading = result.then(
246
- () => undefined,
247
- () => undefined,
248
- )
249
- return result
250
- }
251
-
252
- // Hot-reload local plugin sources: watch the discovery directory and any
253
- // local entrypoints (see watch.ts for the mechanics), debounced into a
254
- // serialized reconcile so bursts of events rebuild the generation once.
255
- let pending: ReturnType<typeof setTimeout> | undefined
256
- const watcher = createSourceWatcher(() => {
257
- clearTimeout(pending)
258
- pending = setTimeout(() => {
259
- // Observe failures immediately: a plugin cleanup that throws would
260
- // otherwise surface as an unhandled rejection until the next trigger.
261
- void enqueue(reconcile).catch(() => undefined)
262
- }, 100)
263
- })
264
- const stopWatching = () => {
265
- clearTimeout(pending)
266
- watcher.dispose()
267
- }
268
- const sources = createPluginSources(watcher.wait)
269
- onCleanup(stopWatching)
270
-
271
- // Rebuild the plugin generation as resolve → compare → swap, mirroring the
272
- // core plugin registry: fold the ordered entries into a desired end state
273
- // (importing only new or changed sources, before anything running is
274
- // touched), no-op when the generation is unchanged, and restart only the
275
- // plugins that differ. Membership or order changes rebuild the whole
276
- // generation to preserve slot-order semantics.
277
- // Package resolution failures would otherwise retry a full npm install on
278
- // every watch event; remember them until the configuration changes.
279
- const npmFailures = new Map<string, string>()
280
- let reconciliationID = 0
281
- const reconcile = async () => {
282
- const id = ++reconciliationID
283
- const started = Date.now()
284
- log.info("plugin reconciliation started", { id })
285
- await trace("watch", { reconciliation: id, directories: props.directories }, () =>
286
- Promise.all(props.directories.map(watcher.wait)).then(() => undefined),
287
- )
288
- // Discovery admits TUI-only plugins while server inventory carries combined plugins.
289
- // Their overlap is intentional; explicit configuration remains the final authority.
290
- const entries = mergePluginTargets(
291
- [
292
- ...(
293
- await trace("discover", { reconciliation: id, directories: props.directories }, () =>
294
- discoverPluginTargets(props.directories),
295
- )
296
- ).map((entry) => ({
297
- entry,
298
- install: true,
299
- optional: true,
300
- })),
301
- ...serverTuiPlugins().map((plugin) => ({
302
- entry: plugin.source.type === "package" ? plugin.source.target : plugin.source.path,
303
- install: false,
304
- optional: true,
305
- })),
306
- ...(config.data.plugins ?? []).map((entry) => ({ entry, install: true, optional: false })),
307
- ],
308
- directory,
309
- )
310
-
311
- // Resolve: fold entries into one desired generation. A source that fails
312
- // to import keeps its running previous version and only reports failure.
313
- const { builtins } = await import("./builtins")
314
- const desired = new Map<string, Desired>()
315
- for (const plugin of builtins)
316
- desired.set(plugin.id, { plugin, source: "builtin", version: "builtin", enabled: true })
317
- const failures: State[] = []
318
- for (const source of entries) {
319
- const entry = source.entry
320
- const target = typeof entry === "string" ? entry : entry.package
321
- if (target.startsWith("-")) {
322
- for (const item of desired.values()) if (matches(target.slice(1), item.plugin.id)) item.enabled = false
323
- continue
324
- }
325
-
326
- const selected = [...desired.values()].filter((item) => matches(target, item.plugin.id))
327
- if (selected.length || target === "*" || target.endsWith(".*") || target.startsWith("opencode.")) {
328
- for (const item of selected) item.enabled = true
329
- continue
330
- }
331
-
332
- const options = typeof entry === "string" ? undefined : entry.options
333
- const local = localSource(target, directory)
334
- if (
335
- local &&
336
- (await stat(local).then(
337
- (info) => info.isFile(),
338
- (error) => (isMissingPath(error) ? false : Promise.reject(error)),
339
- ))
340
- )
341
- continue
342
- // Watch even when the resolve below fails so fixing a broken plugin reloads it.
343
- if (local) await watcher.add(fileURLToPath(local))
344
- const previous = Object.values(store.registrations).find((registration) => registration.target === target)
345
- const memo = local ? undefined : npmFailures.get(target)
346
- const resolved = memo
347
- ? { status: "failed" as const, error: memo }
348
- : await resolvePlugin(
349
- target,
350
- local,
351
- options,
352
- previous,
353
- props.packages,
354
- source.install,
355
- sources.read,
356
- trace,
357
- id,
358
- ).catch((error) => ({
359
- status: "failed" as const,
360
- error: errorMessage(error),
361
- }))
362
- if (resolved.status === "unsupported") {
363
- if (source.optional) continue
364
- failures.push({ target, status: "unsupported" })
365
- continue
366
- }
367
- if (resolved.status === "failed") {
368
- if (!local && !previous) npmFailures.set(target, resolved.error)
369
- failures.push({
370
- target,
371
- id: previous?.plugin.id,
372
- status: "failed",
373
- error: previous?.active ? `${resolved.error} (previous version still active)` : resolved.error,
374
- })
375
- if (previous) desired.set(previous.plugin.id, toDesired(previous))
376
- continue
377
- }
378
- const setupFailure = setupFailures.get(target)
379
- if (setupFailure && sameGeneration(setupFailure, { version: resolved.version, options }) && previous) {
380
- failures.push({
381
- target,
382
- id: previous.plugin.id,
383
- status: "failed",
384
- error: previous.active ? `${setupFailure.error} (previous version still active)` : setupFailure.error,
385
- })
386
- desired.set(previous.plugin.id, toDesired(previous))
387
- continue
388
- }
389
- setupFailures.delete(target)
390
- desired.set(resolved.plugin.id, {
391
- plugin: resolved.plugin,
392
- source: "external",
393
- target,
394
- version: resolved.version,
395
- options,
396
- enabled: true,
397
- })
398
- }
399
-
400
- // Compare: unchanged plugins are never touched, and a fully unchanged
401
- // generation is a no-op, so spurious watch events cost nothing.
402
- const currentIds = Object.keys(store.registrations)
403
- const desiredIds = [...desired.keys()]
404
- const structural =
405
- currentIds.length !== desiredIds.length || currentIds.some((id, index) => desiredIds[index] !== id)
406
- if (structural) {
407
- await Promise.all(
408
- Object.entries(store.registrations)
409
- .filter(([, registration]) => registration.active)
410
- .map(([id]) => deactivateNoisily(id)),
411
- )
412
- setStore("registrations", reconcileStore({}))
413
- }
414
- const changed = structural
415
- ? desiredIds
416
- : desiredIds.filter((id) => {
417
- const registration = store.registrations[id]!
418
- const item = desired.get(id)!
419
- // enabled derives from config directives alone, so config wins over
420
- // manual dialog toggles on every reconcile — the same semantics
421
- // config saves had before hot reload existed, just more frequent.
422
- return !sameGeneration(registration, item) || registration.active !== item.enabled
423
- })
424
-
425
- // Swap: cleanup failures surface as a toast, never propagate, so one
426
- // broken plugin cannot take the rest of the generation down.
427
- const errors = new Map<string, string>()
428
- for (const id of changed) {
429
- const item = desired.get(id)!
430
- const registration = store.registrations[id]
431
- const replaced = !registration || !sameGeneration(registration, item)
432
- // Snapshot the running version before it is overwritten: an import
433
- // failure keeps last-good in the resolve phase, and a setup failure
434
- // must not cost the previous version either.
435
- const fallback = replaced && registration ? toDesired(registration) : undefined
436
- if (replaced) {
437
- if (registration) await deactivateNoisily(id)
438
- // In-place replacement keeps the registration's key position, which
439
- // slot ordering (mode "replace" takes the last one) depends on.
440
- setStore("registrations", id, toRegistration(item))
441
- }
442
- if (!item.enabled) {
443
- await deactivateNoisily(id)
444
- continue
445
- }
446
- const error = await activate(id).then(() => undefined, errorMessage)
447
- if (!error) continue
448
- errors.set(id, error)
449
- if (!fallback) continue
450
- setStore("registrations", id, toRegistration(fallback))
451
- if (!fallback.enabled) continue
452
- const restored = await activate(id).then(
453
- () => true,
454
- () => false,
455
- )
456
- if (restored) errors.set(id, `${error} (previous version still active)`)
457
- }
458
-
459
- const failedTargets = new Set(failures.map((failure) => failure.target))
460
- const states: State[] = [
461
- ...[...desired.values()].flatMap((item): State[] => {
462
- if (item.target === undefined) return []
463
- // A failed reload keeps this item running; the failure entry covers it.
464
- if (failedTargets.has(item.target)) return []
465
- const error = errors.get(item.plugin.id)
466
- if (error) return [{ target: item.target, id: item.plugin.id, status: "failed", error }]
467
- const status = store.registrations[item.plugin.id]?.active ? "active" : "inactive"
468
- return [{ target: item.target, id: item.plugin.id, status }]
469
- }),
470
- ...failures,
471
- ]
472
- // Surface newly failing plugins; repeated reconciles stay silent.
473
- for (const state of states)
474
- if (
475
- state.status === "failed" &&
476
- !store.states.some(
477
- (prev) => prev.status === "failed" && prev.target === state.target && prev.error === state.error,
478
- )
479
- )
480
- host.toast.show({
481
- variant: "error",
482
- title: `Plugin failed: ${state.target}`,
483
- message: "Run /plugins to view details.",
484
- action: { label: "Open plugins", run: () => host.keymap.dispatch("plugins.list") },
485
- })
486
- setStore("states", reconcileStore(states))
487
- log.info("plugin reconciliation completed", { id, durationMs: Date.now() - started, plugins: desired.size })
488
- }
489
- const slotItems = new WeakMap<SlotRender, Claim<SlotRender>>()
490
- // The mounted slot tree: path -> live <Slot> instance count. Reference
491
- // counted because the same path can be mounted several times (one composer
492
- // footer per session tab); a path exists while any instance is mounted.
493
- const [mounted, setMounted] = createStore<Record<string, number>>({})
494
- const registerSlot = (slotPath: string) => {
495
- setMounted(slotPath, (count) => (count ?? 0) + 1)
496
- return () =>
497
- setMounted(
498
- produce((counts) => {
499
- const count = counts[slotPath]
500
- if (count && count > 1) counts[slotPath] = count - 1
501
- else delete counts[slotPath]
502
- }),
503
- )
504
- }
505
- // Claims come back in enable order: registration-store key order across
506
- // plugins (generations preserve key positions in place), then registration
507
- // order within one plugin. The resolver's last-wins rules depend on it.
508
- const claims = createMemo(() =>
509
- Object.entries(store.registrations).flatMap(([id, registration]) =>
510
- Object.entries(registration.active ? registration.slots : {}).map(([key, slot]) => {
511
- // Rows downstream diff by reference; a stable claim per render
512
- // function keeps untouched plugins' slot rows (and their state)
513
- // alive across other plugins' reloads.
514
- const cached = slotItems.get(slot.render)
515
- if (cached) return cached
516
- // Placements are immutable once registered; unwrap the store proxy
517
- // so resolver reads don't subscribe tracked scopes.
518
- const item = { key: `${id}/${key}`, plugin: id, placement: unwrap(slot.placement), render: slot.render }
519
- slotItems.set(slot.render, item)
520
- return item
521
- }),
522
- ),
523
- )
524
- // Object.keys tracks the store's keys node only: refcount changes on an
525
- // already-mounted path (a second tab's composer) skip re-resolution.
526
- const resolved = createMemo(() => resolveSlots({ paths: new Set(Object.keys(mounted)), claims: claims() }))
527
- createEffect(
528
- on(
529
- () => JSON.stringify([serverTuiPlugins(), config.data.plugins ?? []]),
530
- () => {
531
- npmFailures.clear()
532
- void enqueue(reconcile).then(
533
- () => setStore("ready", true),
534
- () => setStore("ready", true),
535
- )
536
- },
537
- ),
538
- )
539
- const syncServerPlugins = () =>
540
- client.api.plugin
541
- .list({ location: data.location.default() })
542
- .then((response) => {
543
- const failed = response.data.filter(
544
- (plugin) =>
545
- plugin.state.status === "failed" &&
546
- !serverPlugins().some(
547
- (previous) =>
548
- serverPluginName(previous) === serverPluginName(plugin) && isDeepEqual(previous.state, plugin.state),
549
- ),
550
- )
551
- setServerPlugins(response.data)
552
- const first = failed[0]
553
- if (!first) return
554
- host.toast.show({
555
- variant: "error",
556
- title: failed.length === 1 ? `Plugin failed: ${serverPluginName(first)}` : `${failed.length} plugins failed`,
557
- message:
558
- (failed.length > 1 ? `${failed.map(serverPluginName).join(", ")}\n` : "") + "Run /plugins to view details.",
559
- action: { label: "Open plugins", run: () => host.keymap.dispatch("plugins.list") },
560
- })
561
- })
562
- .catch(() => undefined)
563
- createEffect(
564
- on(
565
- () => JSON.stringify(data.location.default()),
566
- () => void syncServerPlugins(),
567
- ),
568
- )
569
- onCleanup(client.event.on("plugin.updated", syncServerPlugins))
570
- onCleanup(client.event.on("server.connected", syncServerPlugins))
571
- onMount(() => {
572
- let disposing: Promise<void> | undefined
573
- const dispose = () => {
574
- if (disposing) return disposing
575
- stopWatching()
576
- disposing = loading
577
- .catch(() => undefined)
578
- .then(() =>
579
- Promise.all(
580
- Object.entries(store.registrations)
581
- .filter(([, registration]) => registration.active)
582
- .map(([id]) => deactivate(id).catch(() => undefined)),
583
- ),
584
- )
585
- .then(() => setStore("registrations", reconcileStore({})))
586
- .finally(sources.dispose)
587
- return disposing
588
- }
589
- const unregister = lifecycle.add(dispose)
590
- onCleanup(() => {
591
- unregister()
592
- void dispose()
593
- })
594
- })
595
-
596
- return (
597
- <PluginContext.Provider
598
- value={{
599
- ready: () => store.ready,
600
- list: () => store.states,
601
- server: serverPlugins,
602
- registered: () =>
603
- Object.entries(store.registrations).map(([id, plugin]) => ({
604
- id,
605
- source: plugin.source,
606
- active: plugin.active,
607
- })),
608
- route: (id, name) => store.registrations[id]?.routes[name]?.render,
609
- slots: { register: registerSlot, resolved },
610
- markdown,
611
- // Manual dialog toggles join the same chain as reconciles so a
612
- // toggle mid-reload cannot mix registrations across generations.
613
- activate: (id) => enqueue(() => activate(id)),
614
- deactivate: (id) => enqueue(() => deactivate(id)),
615
- }}
616
- >
617
- {props.children}
618
- </PluginContext.Provider>
619
- )
620
- }
621
-
622
- function serverPluginName(plugin: PluginInfo) {
623
- return (
624
- plugin.id ??
625
- (plugin.source.type === "package"
626
- ? plugin.source.target
627
- : plugin.source.type === "local"
628
- ? plugin.source.path
629
- : plugin.source.type)
630
- )
631
- }
632
-
633
- async function disposeAll(cleanups: Dispose[]) {
634
- const failures: unknown[] = []
635
- for (const cleanup of cleanups.splice(0).reverse()) await cleanup().catch((error) => failures.push(error))
636
- if (failures.length) throw failures[0]
637
- }
638
-
639
- async function setup(plugin: Plugin.Definition, context: Plugin.Context, owned: Dispose[]) {
640
- try {
641
- return await plugin.setup(context)
642
- } catch (error) {
643
- await disposeAll(owned).catch(() => undefined)
644
- throw error
645
- }
646
- }
647
-
648
- function matches(selector: string, id: string) {
649
- return selector === "*" || selector === id || (selector.endsWith(".*") && id.startsWith(selector.slice(0, -1)))
650
- }
651
-
652
- async function resolvePlugin(
653
- spec: string,
654
- local: URL | undefined,
655
- options: Readonly<Record<string, any>> | undefined,
656
- previous: Registration | undefined,
657
- packages: PackageSource,
658
- install: boolean,
659
- readSource: ReturnType<typeof createPluginSources>["read"],
660
- trace: Trace,
661
- reconciliation: number,
662
- ) {
663
- // Package entrypoints never change within a session, so a loaded previous
664
- // version needs no re-resolution (which could otherwise hit npm).
665
- if (!local && previous && sameOptions(previous.options, options))
666
- return { status: "unchanged" as const, plugin: previous.plugin, version: previous.version }
667
- const target = local
668
- ? { directory: fileURLToPath(local) }
669
- : await trace("prepare", { reconciliation, target: spec, install }, () => packages.prepare(spec, install))
670
- const entrypoint = Host.resolve(target).tui
671
- if (!entrypoint) return { status: "unsupported" as const }
672
- // Content remains stable across the several mtimes one save may expose to
673
- // filesystem watchers, while the generation keeps reverted modules fresh.
674
- let source = local
675
- ? await trace("read", { reconciliation, target: spec, entrypoint }, () => readSource(entrypoint))
676
- : {
677
- version: entrypoint,
678
- module: await trace("load", { reconciliation, target: spec, entrypoint }, () => Host.load(entrypoint)),
679
- }
680
- while (true) {
681
- const version = source.version
682
- if (previous && previous.version === version && sameOptions(previous.options, options))
683
- return { status: "unchanged" as const, plugin: previous.plugin, version }
684
- const mod = source.module
685
- if (local) {
686
- const observed = await readSource(entrypoint)
687
- // In-place saves can change the file between hashing and import. Retry
688
- // so setup always runs under the generation of the imported bytes.
689
- if (version !== observed.version) {
690
- source = observed
691
- continue
692
- }
693
- }
694
- if (typeof mod !== "object" || mod === null || !("default" in mod) || !isPlugin(mod.default))
695
- throw new Error(`Invalid V2 TUI plugin module: ${spec}`)
696
- return { status: "loaded" as const, plugin: mod.default, version }
697
- }
698
- }
699
-
700
- function toRegistration(item: Desired): Registration {
701
- return {
702
- plugin: item.plugin,
703
- source: item.source,
704
- target: item.target,
705
- version: item.version,
706
- options: snapshotOptions(item.options),
707
- active: false,
708
- routes: {},
709
- slots: {},
710
- markdown: {},
711
- cleanups: [],
712
- }
713
- }
714
-
715
- function toDesired(item: Registration): Desired {
716
- return {
717
- plugin: item.plugin,
718
- source: item.source,
719
- target: item.target,
720
- version: item.version,
721
- options: item.options,
722
- enabled: item.active,
723
- }
724
- }
725
-
726
- function sameOptions(a: Registration["options"], b: Registration["options"]) {
727
- return isDeepEqual(a ?? null, b ?? null)
728
- }
729
-
730
- function sameGeneration(
731
- a: Pick<Registration, "version" | "options"> | undefined,
732
- b: Pick<Registration, "version" | "options">,
733
- ) {
734
- return a?.version === b.version && sameOptions(a.options, b.options)
735
- }
736
-
737
- function snapshotOptions(options: Registration["options"]) {
738
- return options ? structuredClone(unwrap(options)) : undefined
739
- }
740
-
741
- function isPlugin(value: unknown): value is Plugin.Definition {
742
- return (
743
- typeof value === "object" &&
744
- value !== null &&
745
- "id" in value &&
746
- typeof value.id === "string" &&
747
- value.id.length > 0 &&
748
- "setup" in value &&
749
- typeof value.setup === "function"
750
- )
751
- }
752
-
753
- export function usePlugin() {
754
- const value = useContext(PluginContext)
755
- if (!value) throw new Error("PluginProvider is missing")
756
- return value
757
- }
1
+ import type { PluginInfo } from "@zyro-sec/client"
2
+ import type { Plugin } from "@zyro-sec/plugin/tui"
3
+ import type { MarkdownCodeBlockRenderer, MarkdownOptions } from "@opentui/core"
4
+ import {
5
+ batch,
6
+ createContext,
7
+ createEffect,
8
+ createMemo,
9
+ createSignal,
10
+ on,
11
+ onCleanup,
12
+ onMount,
13
+ useContext,
14
+ type ParentProps,
15
+ } from "solid-js"
16
+ import path from "path"
17
+ import { stat } from "fs/promises"
18
+ import { fileURLToPath } from "url"
19
+ import type { Page } from "@zyro-sec/plugin/tui/context"
20
+ import { Host } from "@zyro-sec/plugin/host"
21
+ import { resolveSlots, type Claim } from "./structure"
22
+ import { createStore, produce, reconcile as reconcileStore, unwrap } from "solid-js/store"
23
+ import { isDeepEqual } from "remeda"
24
+ import "#runtime-plugin-support"
25
+ import { useConfig } from "../config"
26
+ import { useTuiLifecycle } from "../context/runtime"
27
+ import { useClient } from "../context/client"
28
+ import { useData } from "../context/data"
29
+ import { errorMessage } from "../util/error"
30
+ import { createPluginContext, usePluginHost, type Dispose, type RegisteredSlot, type SlotRender } from "./api"
31
+ import { createSourceWatcher } from "./watch"
32
+ import { discoverPluginTargets, localSource, mergePluginTargets } from "./discovery"
33
+ import { createPluginSources } from "./source"
34
+ import { isMissingPath } from "../util/config-directories"
35
+ import { createMarkdownRenderer } from "./markdown"
36
+ import { useLog, type LogTags } from "../context/log"
37
+
38
+ export interface PackageSource {
39
+ readonly prepare: (spec: string, install?: boolean) => Promise<Host.Target>
40
+ }
41
+
42
+ type State =
43
+ | { readonly target: string; readonly id: string; readonly status: "active" | "inactive" }
44
+ | { readonly target: string; readonly status: "unsupported" }
45
+ | { readonly target: string; readonly id?: string; readonly status: "failed"; readonly error: string }
46
+
47
+ type RegisteredPlugin = {
48
+ readonly id: string
49
+ readonly source: "builtin" | "external"
50
+ readonly active: boolean
51
+ }
52
+
53
+ type Value = {
54
+ readonly ready: () => boolean
55
+ readonly list: () => ReadonlyArray<State>
56
+ readonly server: () => readonly PluginInfo[]
57
+ readonly registered: () => ReadonlyArray<RegisteredPlugin>
58
+ readonly route: (id: string, name: string) => Page["render"] | undefined
59
+ readonly slots: {
60
+ // A mounted <Slot> instance registers its path; the disposer unregisters.
61
+ readonly register: (path: string) => () => void
62
+ readonly resolved: () => ReturnType<typeof resolveSlots<SlotRender>>
63
+ }
64
+ readonly markdown: () => MarkdownOptions["renderBlock"]
65
+ readonly activate: (id: string) => Promise<boolean>
66
+ readonly deactivate: (id: string) => Promise<boolean>
67
+ }
68
+
69
+ type Registration = {
70
+ plugin: Plugin.Definition
71
+ source: RegisteredPlugin["source"]
72
+ target?: string
73
+ version: string
74
+ options?: Readonly<Record<string, any>>
75
+ active: boolean
76
+ routes: Record<string, Page>
77
+ slots: Record<string, RegisteredSlot>
78
+ markdown: Record<string, MarkdownCodeBlockRenderer>
79
+ cleanups: Dispose[]
80
+ }
81
+
82
+ // One entry of the desired plugin generation produced by the resolve phase.
83
+ type Desired = Pick<Registration, "plugin" | "source" | "target" | "version" | "options"> & { enabled: boolean }
84
+ type Trace = <T>(stage: string, tags: LogTags, task: () => Promise<T>) => Promise<T>
85
+
86
+ const PluginContext = createContext<Value>()
87
+
88
+ export function PluginProvider(props: ParentProps<{ packages: PackageSource; directories: string[] }>) {
89
+ const host = usePluginHost()
90
+ const log = useLog({ component: "plugin" })
91
+ const config = useConfig()
92
+ const lifecycle = useTuiLifecycle()
93
+ const client = useClient()
94
+ const data = useData()
95
+ const [serverPlugins, setServerPlugins] = createSignal<readonly PluginInfo[]>([])
96
+ const serverTuiPlugins = createMemo(() =>
97
+ serverPlugins().filter(
98
+ (plugin): plugin is PluginInfo & { readonly source: { readonly type: "package" } | { readonly type: "local" } } =>
99
+ plugin.state.status === "active" &&
100
+ plugin.features.tui === true &&
101
+ (plugin.source.type === "package" || plugin.source.type === "local"),
102
+ ),
103
+ )
104
+ const directory = config.path ? path.dirname(config.path) : process.cwd()
105
+ const [store, setStore] = createStore({
106
+ ready: false,
107
+ states: [] as ReadonlyArray<State>,
108
+ registrations: {} as Record<string, Registration>,
109
+ })
110
+ // One save can emit several watch events. Remember setup failures so those
111
+ // events do not repeatedly tear down and restore the last good generation.
112
+ const setupFailures = new Map<string, { version: string; options: Registration["options"]; error: string }>()
113
+ let operationID = 0
114
+ const trace: Trace = (stage, tags, task) => {
115
+ const id = ++operationID
116
+ const started = Date.now()
117
+ log.debug("plugin operation started", { id, stage, ...tags })
118
+ const stalled = setTimeout(
119
+ () => log.warn("plugin operation stalled", { id, stage, elapsedMs: Date.now() - started, ...tags }),
120
+ 5_000,
121
+ )
122
+ return task()
123
+ .then(
124
+ (value) => {
125
+ log.debug("plugin operation completed", { id, stage, durationMs: Date.now() - started, ...tags })
126
+ return value
127
+ },
128
+ (error) => {
129
+ log.warn("plugin operation failed", {
130
+ id,
131
+ stage,
132
+ durationMs: Date.now() - started,
133
+ error: errorMessage(error),
134
+ ...tags,
135
+ })
136
+ throw error
137
+ },
138
+ )
139
+ .finally(() => clearTimeout(stalled))
140
+ }
141
+ const markdown = createMarkdownRenderer(() =>
142
+ Object.values(store.registrations).flatMap((registration) => (registration.active ? [registration.markdown] : [])),
143
+ )
144
+ const clearContributions = (id: string) => {
145
+ setStore("registrations", id, "routes", reconcileStore({}))
146
+ setStore("registrations", id, "slots", reconcileStore({}))
147
+ setStore("registrations", id, "markdown", reconcileStore({}))
148
+ }
149
+
150
+ const activate = async (id: string) => {
151
+ const item = store.registrations[id]
152
+ if (!item) return false
153
+ await deactivate(id)
154
+ batch(() => {
155
+ clearContributions(id)
156
+ setStore("registrations", id, "cleanups", [])
157
+ })
158
+ const owned: Dispose[] = []
159
+ const context = createPluginContext({
160
+ host,
161
+ id,
162
+ options: item.options,
163
+ owned,
164
+ registry: {
165
+ has: (kind, name) => Boolean(store.registrations[id]?.[kind][name]),
166
+ set: (
167
+ kind: "routes" | "slots" | "markdown",
168
+ name: string,
169
+ value: Page | RegisteredSlot | MarkdownCodeBlockRenderer,
170
+ ) => setStore("registrations", id, kind, name, () => value),
171
+ remove: (kind, name) =>
172
+ setStore(
173
+ "registrations",
174
+ produce((registrations) => {
175
+ if (!registrations[id]) return
176
+ delete registrations[id][kind][name]
177
+ }),
178
+ ),
179
+ active: () => Boolean(store.registrations[id]?.active),
180
+ },
181
+ })
182
+ const cleanup = await trace("setup", { plugin: id, target: item.target }, () =>
183
+ setup(item.plugin, context, owned),
184
+ ).catch((error) => {
185
+ clearContributions(id)
186
+ if (item.target)
187
+ setupFailures.set(item.target, {
188
+ version: item.version,
189
+ options: snapshotOptions(item.options),
190
+ error: errorMessage(error),
191
+ })
192
+ throw error
193
+ })
194
+ if (cleanup) owned.push(async () => cleanup())
195
+ if (item.target && sameGeneration(setupFailures.get(item.target), item)) setupFailures.delete(item.target)
196
+ batch(() => {
197
+ setStore("registrations", id, "cleanups", owned)
198
+ setStore("registrations", id, "active", true)
199
+ setStore("states", (items) =>
200
+ items.map((state) =>
201
+ "id" in state && state.id === id ? { target: state.target, id, status: "active" } : state,
202
+ ),
203
+ )
204
+ })
205
+ return true
206
+ }
207
+
208
+ const deactivate = async (id: string) => {
209
+ const item = store.registrations[id]
210
+ if (!item?.active) return false
211
+ const cleanups = [...item.cleanups]
212
+ batch(() => {
213
+ setStore("registrations", id, "active", false)
214
+ setStore("registrations", id, "cleanups", [])
215
+ })
216
+ await trace("cleanup", { plugin: id, target: item.target, cleanups: cleanups.length }, () =>
217
+ disposeAll(cleanups),
218
+ ).finally(() =>
219
+ batch(() => {
220
+ if (store.registrations[id]) {
221
+ clearContributions(id)
222
+ }
223
+ setStore("states", (items) =>
224
+ items.map((state) =>
225
+ "id" in state && state.id === id ? { target: state.target, id, status: "inactive" } : state,
226
+ ),
227
+ )
228
+ }),
229
+ )
230
+ return true
231
+ }
232
+
233
+ // Cleanup failures must not stop a swap or teardown, but they should not
234
+ // vanish either: the old generation may still own listeners or intervals.
235
+ const deactivateNoisily = (id: string) =>
236
+ deactivate(id).catch((error) =>
237
+ host.toast.show({ variant: "error", title: "Plugin", message: `${id}: cleanup failed: ${errorMessage(error)}` }),
238
+ )
239
+
240
+ // Every lifecycle mutation — reconciles, manual dialog toggles, shutdown —
241
+ // is serialized through one chain so generations can never interleave.
242
+ let loading = Promise.resolve()
243
+ const enqueue = <T,>(task: () => Promise<T>) => {
244
+ const result = loading.catch(() => undefined).then(task)
245
+ loading = result.then(
246
+ () => undefined,
247
+ () => undefined,
248
+ )
249
+ return result
250
+ }
251
+
252
+ // Hot-reload local plugin sources: watch the discovery directory and any
253
+ // local entrypoints (see watch.ts for the mechanics), debounced into a
254
+ // serialized reconcile so bursts of events rebuild the generation once.
255
+ let pending: ReturnType<typeof setTimeout> | undefined
256
+ const watcher = createSourceWatcher(() => {
257
+ clearTimeout(pending)
258
+ pending = setTimeout(() => {
259
+ // Observe failures immediately: a plugin cleanup that throws would
260
+ // otherwise surface as an unhandled rejection until the next trigger.
261
+ void enqueue(reconcile).catch(() => undefined)
262
+ }, 100)
263
+ })
264
+ const stopWatching = () => {
265
+ clearTimeout(pending)
266
+ watcher.dispose()
267
+ }
268
+ const sources = createPluginSources(watcher.wait)
269
+ onCleanup(stopWatching)
270
+
271
+ // Rebuild the plugin generation as resolve → compare → swap, mirroring the
272
+ // core plugin registry: fold the ordered entries into a desired end state
273
+ // (importing only new or changed sources, before anything running is
274
+ // touched), no-op when the generation is unchanged, and restart only the
275
+ // plugins that differ. Membership or order changes rebuild the whole
276
+ // generation to preserve slot-order semantics.
277
+ // Package resolution failures would otherwise retry a full npm install on
278
+ // every watch event; remember them until the configuration changes.
279
+ const npmFailures = new Map<string, string>()
280
+ let reconciliationID = 0
281
+ const reconcile = async () => {
282
+ const id = ++reconciliationID
283
+ const started = Date.now()
284
+ log.info("plugin reconciliation started", { id })
285
+ await trace("watch", { reconciliation: id, directories: props.directories }, () =>
286
+ Promise.all(props.directories.map(watcher.wait)).then(() => undefined),
287
+ )
288
+ // Discovery admits TUI-only plugins while server inventory carries combined plugins.
289
+ // Their overlap is intentional; explicit configuration remains the final authority.
290
+ const entries = mergePluginTargets(
291
+ [
292
+ ...(
293
+ await trace("discover", { reconciliation: id, directories: props.directories }, () =>
294
+ discoverPluginTargets(props.directories),
295
+ )
296
+ ).map((entry) => ({
297
+ entry,
298
+ install: true,
299
+ optional: true,
300
+ })),
301
+ ...serverTuiPlugins().map((plugin) => ({
302
+ entry: plugin.source.type === "package" ? plugin.source.target : plugin.source.path,
303
+ install: false,
304
+ optional: true,
305
+ })),
306
+ ...(config.data.plugins ?? []).map((entry) => ({ entry, install: true, optional: false })),
307
+ ],
308
+ directory,
309
+ )
310
+
311
+ // Resolve: fold entries into one desired generation. A source that fails
312
+ // to import keeps its running previous version and only reports failure.
313
+ const { builtins } = await import("./builtins")
314
+ const desired = new Map<string, Desired>()
315
+ for (const plugin of builtins)
316
+ desired.set(plugin.id, { plugin, source: "builtin", version: "builtin", enabled: true })
317
+ const failures: State[] = []
318
+ for (const source of entries) {
319
+ const entry = source.entry
320
+ const target = typeof entry === "string" ? entry : entry.package
321
+ if (target.startsWith("-")) {
322
+ for (const item of desired.values()) if (matches(target.slice(1), item.plugin.id)) item.enabled = false
323
+ continue
324
+ }
325
+
326
+ const selected = [...desired.values()].filter((item) => matches(target, item.plugin.id))
327
+ if (selected.length || target === "*" || target.endsWith(".*") || target.startsWith("opencode.")) {
328
+ for (const item of selected) item.enabled = true
329
+ continue
330
+ }
331
+
332
+ const options = typeof entry === "string" ? undefined : entry.options
333
+ const local = localSource(target, directory)
334
+ if (
335
+ local &&
336
+ (await stat(local).then(
337
+ (info) => info.isFile(),
338
+ (error) => (isMissingPath(error) ? false : Promise.reject(error)),
339
+ ))
340
+ )
341
+ continue
342
+ // Watch even when the resolve below fails so fixing a broken plugin reloads it.
343
+ if (local) await watcher.add(fileURLToPath(local))
344
+ const previous = Object.values(store.registrations).find((registration) => registration.target === target)
345
+ const memo = local ? undefined : npmFailures.get(target)
346
+ const resolved = memo
347
+ ? { status: "failed" as const, error: memo }
348
+ : await resolvePlugin(
349
+ target,
350
+ local,
351
+ options,
352
+ previous,
353
+ props.packages,
354
+ source.install,
355
+ sources.read,
356
+ trace,
357
+ id,
358
+ ).catch((error) => ({
359
+ status: "failed" as const,
360
+ error: errorMessage(error),
361
+ }))
362
+ if (resolved.status === "unsupported") {
363
+ if (source.optional) continue
364
+ failures.push({ target, status: "unsupported" })
365
+ continue
366
+ }
367
+ if (resolved.status === "failed") {
368
+ if (!local && !previous) npmFailures.set(target, resolved.error)
369
+ failures.push({
370
+ target,
371
+ id: previous?.plugin.id,
372
+ status: "failed",
373
+ error: previous?.active ? `${resolved.error} (previous version still active)` : resolved.error,
374
+ })
375
+ if (previous) desired.set(previous.plugin.id, toDesired(previous))
376
+ continue
377
+ }
378
+ const setupFailure = setupFailures.get(target)
379
+ if (setupFailure && sameGeneration(setupFailure, { version: resolved.version, options }) && previous) {
380
+ failures.push({
381
+ target,
382
+ id: previous.plugin.id,
383
+ status: "failed",
384
+ error: previous.active ? `${setupFailure.error} (previous version still active)` : setupFailure.error,
385
+ })
386
+ desired.set(previous.plugin.id, toDesired(previous))
387
+ continue
388
+ }
389
+ setupFailures.delete(target)
390
+ desired.set(resolved.plugin.id, {
391
+ plugin: resolved.plugin,
392
+ source: "external",
393
+ target,
394
+ version: resolved.version,
395
+ options,
396
+ enabled: true,
397
+ })
398
+ }
399
+
400
+ // Compare: unchanged plugins are never touched, and a fully unchanged
401
+ // generation is a no-op, so spurious watch events cost nothing.
402
+ const currentIds = Object.keys(store.registrations)
403
+ const desiredIds = [...desired.keys()]
404
+ const structural =
405
+ currentIds.length !== desiredIds.length || currentIds.some((id, index) => desiredIds[index] !== id)
406
+ if (structural) {
407
+ await Promise.all(
408
+ Object.entries(store.registrations)
409
+ .filter(([, registration]) => registration.active)
410
+ .map(([id]) => deactivateNoisily(id)),
411
+ )
412
+ setStore("registrations", reconcileStore({}))
413
+ }
414
+ const changed = structural
415
+ ? desiredIds
416
+ : desiredIds.filter((id) => {
417
+ const registration = store.registrations[id]!
418
+ const item = desired.get(id)!
419
+ // enabled derives from config directives alone, so config wins over
420
+ // manual dialog toggles on every reconcile — the same semantics
421
+ // config saves had before hot reload existed, just more frequent.
422
+ return !sameGeneration(registration, item) || registration.active !== item.enabled
423
+ })
424
+
425
+ // Swap: cleanup failures surface as a toast, never propagate, so one
426
+ // broken plugin cannot take the rest of the generation down.
427
+ const errors = new Map<string, string>()
428
+ for (const id of changed) {
429
+ const item = desired.get(id)!
430
+ const registration = store.registrations[id]
431
+ const replaced = !registration || !sameGeneration(registration, item)
432
+ // Snapshot the running version before it is overwritten: an import
433
+ // failure keeps last-good in the resolve phase, and a setup failure
434
+ // must not cost the previous version either.
435
+ const fallback = replaced && registration ? toDesired(registration) : undefined
436
+ if (replaced) {
437
+ if (registration) await deactivateNoisily(id)
438
+ // In-place replacement keeps the registration's key position, which
439
+ // slot ordering (mode "replace" takes the last one) depends on.
440
+ setStore("registrations", id, toRegistration(item))
441
+ }
442
+ if (!item.enabled) {
443
+ await deactivateNoisily(id)
444
+ continue
445
+ }
446
+ const error = await activate(id).then(() => undefined, errorMessage)
447
+ if (!error) continue
448
+ errors.set(id, error)
449
+ if (!fallback) continue
450
+ setStore("registrations", id, toRegistration(fallback))
451
+ if (!fallback.enabled) continue
452
+ const restored = await activate(id).then(
453
+ () => true,
454
+ () => false,
455
+ )
456
+ if (restored) errors.set(id, `${error} (previous version still active)`)
457
+ }
458
+
459
+ const failedTargets = new Set(failures.map((failure) => failure.target))
460
+ const states: State[] = [
461
+ ...[...desired.values()].flatMap((item): State[] => {
462
+ if (item.target === undefined) return []
463
+ // A failed reload keeps this item running; the failure entry covers it.
464
+ if (failedTargets.has(item.target)) return []
465
+ const error = errors.get(item.plugin.id)
466
+ if (error) return [{ target: item.target, id: item.plugin.id, status: "failed", error }]
467
+ const status = store.registrations[item.plugin.id]?.active ? "active" : "inactive"
468
+ return [{ target: item.target, id: item.plugin.id, status }]
469
+ }),
470
+ ...failures,
471
+ ]
472
+ // Surface newly failing plugins; repeated reconciles stay silent.
473
+ for (const state of states)
474
+ if (
475
+ state.status === "failed" &&
476
+ !store.states.some(
477
+ (prev) => prev.status === "failed" && prev.target === state.target && prev.error === state.error,
478
+ )
479
+ )
480
+ host.toast.show({
481
+ variant: "error",
482
+ title: `Plugin failed: ${state.target}`,
483
+ message: "Run /plugins to view details.",
484
+ action: { label: "Open plugins", run: () => host.keymap.dispatch("plugins.list") },
485
+ })
486
+ setStore("states", reconcileStore(states))
487
+ log.info("plugin reconciliation completed", { id, durationMs: Date.now() - started, plugins: desired.size })
488
+ }
489
+ const slotItems = new WeakMap<SlotRender, Claim<SlotRender>>()
490
+ // The mounted slot tree: path -> live <Slot> instance count. Reference
491
+ // counted because the same path can be mounted several times (one composer
492
+ // footer per session tab); a path exists while any instance is mounted.
493
+ const [mounted, setMounted] = createStore<Record<string, number>>({})
494
+ const registerSlot = (slotPath: string) => {
495
+ setMounted(slotPath, (count) => (count ?? 0) + 1)
496
+ return () =>
497
+ setMounted(
498
+ produce((counts) => {
499
+ const count = counts[slotPath]
500
+ if (count && count > 1) counts[slotPath] = count - 1
501
+ else delete counts[slotPath]
502
+ }),
503
+ )
504
+ }
505
+ // Claims come back in enable order: registration-store key order across
506
+ // plugins (generations preserve key positions in place), then registration
507
+ // order within one plugin. The resolver's last-wins rules depend on it.
508
+ const claims = createMemo(() =>
509
+ Object.entries(store.registrations).flatMap(([id, registration]) =>
510
+ Object.entries(registration.active ? registration.slots : {}).map(([key, slot]) => {
511
+ // Rows downstream diff by reference; a stable claim per render
512
+ // function keeps untouched plugins' slot rows (and their state)
513
+ // alive across other plugins' reloads.
514
+ const cached = slotItems.get(slot.render)
515
+ if (cached) return cached
516
+ // Placements are immutable once registered; unwrap the store proxy
517
+ // so resolver reads don't subscribe tracked scopes.
518
+ const item = { key: `${id}/${key}`, plugin: id, placement: unwrap(slot.placement), render: slot.render }
519
+ slotItems.set(slot.render, item)
520
+ return item
521
+ }),
522
+ ),
523
+ )
524
+ // Object.keys tracks the store's keys node only: refcount changes on an
525
+ // already-mounted path (a second tab's composer) skip re-resolution.
526
+ const resolved = createMemo(() => resolveSlots({ paths: new Set(Object.keys(mounted)), claims: claims() }))
527
+ createEffect(
528
+ on(
529
+ () => JSON.stringify([serverTuiPlugins(), config.data.plugins ?? []]),
530
+ () => {
531
+ npmFailures.clear()
532
+ void enqueue(reconcile).then(
533
+ () => setStore("ready", true),
534
+ () => setStore("ready", true),
535
+ )
536
+ },
537
+ ),
538
+ )
539
+ const syncServerPlugins = () =>
540
+ client.api.plugin
541
+ .list({ location: data.location.default() })
542
+ .then((response) => {
543
+ const failed = response.data.filter(
544
+ (plugin) =>
545
+ plugin.state.status === "failed" &&
546
+ !serverPlugins().some(
547
+ (previous) =>
548
+ serverPluginName(previous) === serverPluginName(plugin) && isDeepEqual(previous.state, plugin.state),
549
+ ),
550
+ )
551
+ setServerPlugins(response.data)
552
+ const first = failed[0]
553
+ if (!first) return
554
+ host.toast.show({
555
+ variant: "error",
556
+ title: failed.length === 1 ? `Plugin failed: ${serverPluginName(first)}` : `${failed.length} plugins failed`,
557
+ message:
558
+ (failed.length > 1 ? `${failed.map(serverPluginName).join(", ")}\n` : "") + "Run /plugins to view details.",
559
+ action: { label: "Open plugins", run: () => host.keymap.dispatch("plugins.list") },
560
+ })
561
+ })
562
+ .catch(() => undefined)
563
+ createEffect(
564
+ on(
565
+ () => JSON.stringify(data.location.default()),
566
+ () => void syncServerPlugins(),
567
+ ),
568
+ )
569
+ onCleanup(client.event.on("plugin.updated", syncServerPlugins))
570
+ onCleanup(client.event.on("server.connected", syncServerPlugins))
571
+ onMount(() => {
572
+ let disposing: Promise<void> | undefined
573
+ const dispose = () => {
574
+ if (disposing) return disposing
575
+ stopWatching()
576
+ disposing = loading
577
+ .catch(() => undefined)
578
+ .then(() =>
579
+ Promise.all(
580
+ Object.entries(store.registrations)
581
+ .filter(([, registration]) => registration.active)
582
+ .map(([id]) => deactivate(id).catch(() => undefined)),
583
+ ),
584
+ )
585
+ .then(() => setStore("registrations", reconcileStore({})))
586
+ .finally(sources.dispose)
587
+ return disposing
588
+ }
589
+ const unregister = lifecycle.add(dispose)
590
+ onCleanup(() => {
591
+ unregister()
592
+ void dispose()
593
+ })
594
+ })
595
+
596
+ return (
597
+ <PluginContext.Provider
598
+ value={{
599
+ ready: () => store.ready,
600
+ list: () => store.states,
601
+ server: serverPlugins,
602
+ registered: () =>
603
+ Object.entries(store.registrations).map(([id, plugin]) => ({
604
+ id,
605
+ source: plugin.source,
606
+ active: plugin.active,
607
+ })),
608
+ route: (id, name) => store.registrations[id]?.routes[name]?.render,
609
+ slots: { register: registerSlot, resolved },
610
+ markdown,
611
+ // Manual dialog toggles join the same chain as reconciles so a
612
+ // toggle mid-reload cannot mix registrations across generations.
613
+ activate: (id) => enqueue(() => activate(id)),
614
+ deactivate: (id) => enqueue(() => deactivate(id)),
615
+ }}
616
+ >
617
+ {props.children}
618
+ </PluginContext.Provider>
619
+ )
620
+ }
621
+
622
+ function serverPluginName(plugin: PluginInfo) {
623
+ return (
624
+ plugin.id ??
625
+ (plugin.source.type === "package"
626
+ ? plugin.source.target
627
+ : plugin.source.type === "local"
628
+ ? plugin.source.path
629
+ : plugin.source.type)
630
+ )
631
+ }
632
+
633
+ async function disposeAll(cleanups: Dispose[]) {
634
+ const failures: unknown[] = []
635
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup().catch((error) => failures.push(error))
636
+ if (failures.length) throw failures[0]
637
+ }
638
+
639
+ async function setup(plugin: Plugin.Definition, context: Plugin.Context, owned: Dispose[]) {
640
+ try {
641
+ return await plugin.setup(context)
642
+ } catch (error) {
643
+ await disposeAll(owned).catch(() => undefined)
644
+ throw error
645
+ }
646
+ }
647
+
648
+ function matches(selector: string, id: string) {
649
+ return selector === "*" || selector === id || (selector.endsWith(".*") && id.startsWith(selector.slice(0, -1)))
650
+ }
651
+
652
+ async function resolvePlugin(
653
+ spec: string,
654
+ local: URL | undefined,
655
+ options: Readonly<Record<string, any>> | undefined,
656
+ previous: Registration | undefined,
657
+ packages: PackageSource,
658
+ install: boolean,
659
+ readSource: ReturnType<typeof createPluginSources>["read"],
660
+ trace: Trace,
661
+ reconciliation: number,
662
+ ) {
663
+ // Package entrypoints never change within a session, so a loaded previous
664
+ // version needs no re-resolution (which could otherwise hit npm).
665
+ if (!local && previous && sameOptions(previous.options, options))
666
+ return { status: "unchanged" as const, plugin: previous.plugin, version: previous.version }
667
+ const target = local
668
+ ? { directory: fileURLToPath(local) }
669
+ : await trace("prepare", { reconciliation, target: spec, install }, () => packages.prepare(spec, install))
670
+ const entrypoint = Host.resolve(target).tui
671
+ if (!entrypoint) return { status: "unsupported" as const }
672
+ // Content remains stable across the several mtimes one save may expose to
673
+ // filesystem watchers, while the generation keeps reverted modules fresh.
674
+ let source = local
675
+ ? await trace("read", { reconciliation, target: spec, entrypoint }, () => readSource(entrypoint))
676
+ : {
677
+ version: entrypoint,
678
+ module: await trace("load", { reconciliation, target: spec, entrypoint }, () => Host.load(entrypoint)),
679
+ }
680
+ while (true) {
681
+ const version = source.version
682
+ if (previous && previous.version === version && sameOptions(previous.options, options))
683
+ return { status: "unchanged" as const, plugin: previous.plugin, version }
684
+ const mod = source.module
685
+ if (local) {
686
+ const observed = await readSource(entrypoint)
687
+ // In-place saves can change the file between hashing and import. Retry
688
+ // so setup always runs under the generation of the imported bytes.
689
+ if (version !== observed.version) {
690
+ source = observed
691
+ continue
692
+ }
693
+ }
694
+ if (typeof mod !== "object" || mod === null || !("default" in mod) || !isPlugin(mod.default))
695
+ throw new Error(`Invalid V2 TUI plugin module: ${spec}`)
696
+ return { status: "loaded" as const, plugin: mod.default, version }
697
+ }
698
+ }
699
+
700
+ function toRegistration(item: Desired): Registration {
701
+ return {
702
+ plugin: item.plugin,
703
+ source: item.source,
704
+ target: item.target,
705
+ version: item.version,
706
+ options: snapshotOptions(item.options),
707
+ active: false,
708
+ routes: {},
709
+ slots: {},
710
+ markdown: {},
711
+ cleanups: [],
712
+ }
713
+ }
714
+
715
+ function toDesired(item: Registration): Desired {
716
+ return {
717
+ plugin: item.plugin,
718
+ source: item.source,
719
+ target: item.target,
720
+ version: item.version,
721
+ options: item.options,
722
+ enabled: item.active,
723
+ }
724
+ }
725
+
726
+ function sameOptions(a: Registration["options"], b: Registration["options"]) {
727
+ return isDeepEqual(a ?? null, b ?? null)
728
+ }
729
+
730
+ function sameGeneration(
731
+ a: Pick<Registration, "version" | "options"> | undefined,
732
+ b: Pick<Registration, "version" | "options">,
733
+ ) {
734
+ return a?.version === b.version && sameOptions(a.options, b.options)
735
+ }
736
+
737
+ function snapshotOptions(options: Registration["options"]) {
738
+ return options ? structuredClone(unwrap(options)) : undefined
739
+ }
740
+
741
+ function isPlugin(value: unknown): value is Plugin.Definition {
742
+ return (
743
+ typeof value === "object" &&
744
+ value !== null &&
745
+ "id" in value &&
746
+ typeof value.id === "string" &&
747
+ value.id.length > 0 &&
748
+ "setup" in value &&
749
+ typeof value.setup === "function"
750
+ )
751
+ }
752
+
753
+ export function usePlugin() {
754
+ const value = useContext(PluginContext)
755
+ if (!value) throw new Error("PluginProvider is missing")
756
+ return value
757
+ }