@zyro-sec/tui 0.0.0-stage → 1.0.2

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 (580) hide show
  1. package/AGENTS.md +6 -0
  2. package/bunfig.toml +4 -0
  3. package/package.json +79 -4
  4. package/src/app.tsx +1632 -0
  5. package/src/assets/backgrounds/anime.png +0 -0
  6. package/src/assets/backgrounds/circuit.jpg +0 -0
  7. package/src/assets/backgrounds/cyber-grid.jpg +0 -0
  8. package/src/assets/backgrounds/datacenter.jpg +0 -0
  9. package/src/assets/backgrounds/hacker-desk.jpg +0 -0
  10. package/src/assets/backgrounds/matrix-code.jpg +0 -0
  11. package/src/attention-sounds.bun.ts +8 -0
  12. package/src/attention-sounds.node.ts +16 -0
  13. package/src/attention.ts +189 -0
  14. package/src/audio.d.ts +9 -0
  15. package/src/audio.ts +49 -0
  16. package/src/clipboard.ts +68 -0
  17. package/src/component/background-image.tsx +26 -0
  18. package/src/component/command-palette.tsx +74 -0
  19. package/src/component/devtools-bar.tsx +611 -0
  20. package/src/component/dialog-agent.tsx +33 -0
  21. package/src/component/dialog-background.tsx +102 -0
  22. package/src/component/dialog-config.tsx +494 -0
  23. package/src/component/dialog-debug.tsx +90 -0
  24. package/src/component/dialog-error-details.tsx +130 -0
  25. package/src/component/dialog-experiments.tsx +101 -0
  26. package/src/component/dialog-go-upsell.tsx +448 -0
  27. package/src/component/dialog-highlights.tsx +88 -0
  28. package/src/component/dialog-image-preview.tsx +85 -0
  29. package/src/component/dialog-install-mcp.tsx +67 -0
  30. package/src/component/dialog-integration.tsx +1332 -0
  31. package/src/component/dialog-mcp.tsx +184 -0
  32. package/src/component/dialog-model-free.tsx +79 -0
  33. package/src/component/dialog-model.tsx +238 -0
  34. package/src/component/dialog-open.tsx +509 -0
  35. package/src/component/dialog-pair.tsx +123 -0
  36. package/src/component/dialog-session-list.tsx +328 -0
  37. package/src/component/dialog-session-rename.tsx +37 -0
  38. package/src/component/dialog-shell-output.tsx +194 -0
  39. package/src/component/dialog-skill.tsx +93 -0
  40. package/src/component/dialog-speed.tsx +48 -0
  41. package/src/component/dialog-stash.tsx +90 -0
  42. package/src/component/dialog-status.tsx +50 -0
  43. package/src/component/dialog-theme-list.tsx +56 -0
  44. package/src/component/dialog-update.tsx +144 -0
  45. package/src/component/dialog-variant.tsx +43 -0
  46. package/src/component/dialog-workspace-file-changes.tsx +187 -0
  47. package/src/component/dialog-workspaces.tsx +413 -0
  48. package/src/component/dialog-worktree-name.tsx +40 -0
  49. package/src/component/error-component.tsx +258 -0
  50. package/src/component/fade-in-text.tsx +113 -0
  51. package/src/component/go-upsell-art.ts +338 -0
  52. package/src/component/logo.tsx +79 -0
  53. package/src/component/masked-text.ts +59 -0
  54. package/src/component/media-source.ts +43 -0
  55. package/src/component/migration-overlay.tsx +73 -0
  56. package/src/component/model-options.tsx +121 -0
  57. package/src/component/one-cell-spinner.tsx +75 -0
  58. package/src/component/panel-host.tsx +64 -0
  59. package/src/component/patch-diff.tsx +211 -0
  60. package/src/component/plugin-route-missing.tsx +21 -0
  61. package/src/component/prompt/autocomplete.tsx +1005 -0
  62. package/src/component/prompt/draft-stash.ts +47 -0
  63. package/src/component/prompt/index.tsx +2080 -0
  64. package/src/component/prompt/local-attachment.ts +188 -0
  65. package/src/component/prompt/metadata.tsx +193 -0
  66. package/src/component/prompt/move.tsx +181 -0
  67. package/src/component/reconnecting.tsx +40 -0
  68. package/src/component/retry-provider.tsx +202 -0
  69. package/src/component/session-frame.tsx +408 -0
  70. package/src/component/session-tabs-rail.tsx +94 -0
  71. package/src/component/session-tabs.tsx +1789 -0
  72. package/src/component/shimmer-text.tsx +64 -0
  73. package/src/component/spinner-frames.ts +1 -0
  74. package/src/component/spinner-renderable.ts +126 -0
  75. package/src/component/spinner.tsx +50 -0
  76. package/src/component/startup-loading.tsx +63 -0
  77. package/src/component/tab-pulse.tsx +819 -0
  78. package/src/component/terminal-pane.tsx +377 -0
  79. package/src/component/theme-error-toast.tsx +20 -0
  80. package/src/component/title-shimmer.tsx +272 -0
  81. package/src/component/todo-item.tsx +27 -0
  82. package/src/component/usage.tsx +329 -0
  83. package/src/component/use-connected.tsx +14 -0
  84. package/src/config/index.tsx +438 -0
  85. package/src/config/keybind.ts +367 -0
  86. package/src/config/new-session-location.ts +16 -0
  87. package/src/config/v1/index.tsx +149 -0
  88. package/src/config/v1/keybind.ts +463 -0
  89. package/src/context/args.tsx +31 -0
  90. package/src/context/attention.tsx +23 -0
  91. package/src/context/client-mcp.tsx +119 -0
  92. package/src/context/client.tsx +76 -0
  93. package/src/context/clipboard.tsx +19 -0
  94. package/src/context/data.tsx +69 -0
  95. package/src/context/editor.ts +408 -0
  96. package/src/context/epilogue.tsx +14 -0
  97. package/src/context/event.ts +32 -0
  98. package/src/context/exit.tsx +8 -0
  99. package/src/context/helper.tsx +26 -0
  100. package/src/context/interactivity.tsx +20 -0
  101. package/src/context/keymap.tsx +515 -0
  102. package/src/context/local.tsx +723 -0
  103. package/src/context/location.tsx +80 -0
  104. package/src/context/log.tsx +24 -0
  105. package/src/context/panel.tsx +59 -0
  106. package/src/context/path-format.tsx +12 -0
  107. package/src/context/permission.tsx +18 -0
  108. package/src/context/program-status.ts +94 -0
  109. package/src/context/prompt.tsx +18 -0
  110. package/src/context/route.tsx +73 -0
  111. package/src/context/runtime.tsx +98 -0
  112. package/src/context/session-tabs-model.ts +263 -0
  113. package/src/context/session-tabs.tsx +508 -0
  114. package/src/context/session-terminals.tsx +136 -0
  115. package/src/context/storage.tsx +150 -0
  116. package/src/context/theme.tsx +447 -0
  117. package/src/context/thinking.ts +20 -0
  118. package/src/context/update-notification.tsx +158 -0
  119. package/src/devtools/index.ts +41 -0
  120. package/src/editor-zed-sqlite.bun.ts +1 -0
  121. package/src/editor-zed-sqlite.node.ts +21 -0
  122. package/src/editor-zed.ts +277 -0
  123. package/src/editor.ts +86 -0
  124. package/src/feature-plugins/home/footer.tsx +116 -0
  125. package/src/feature-plugins/prompt/btw.tsx +190 -0
  126. package/src/feature-plugins/prompt/footer.tsx +163 -0
  127. package/src/feature-plugins/prompt/goal.tsx +211 -0
  128. package/src/feature-plugins/sidebar/context.tsx +52 -0
  129. package/src/feature-plugins/sidebar/footer.tsx +126 -0
  130. package/src/feature-plugins/sidebar/limit.tsx +47 -0
  131. package/src/feature-plugins/sidebar/mcp.tsx +103 -0
  132. package/src/feature-plugins/sidebar/todo.tsx +58 -0
  133. package/src/feature-plugins/system/diff-viewer-file-menu.tsx +87 -0
  134. package/src/feature-plugins/system/diff-viewer-file-tree-utils.ts +174 -0
  135. package/src/feature-plugins/system/diff-viewer-file-tree.tsx +274 -0
  136. package/src/feature-plugins/system/diff-viewer-image.tsx +96 -0
  137. package/src/feature-plugins/system/diff-viewer.tsx +1380 -0
  138. package/src/feature-plugins/system/notifications.ts +102 -0
  139. package/src/feature-plugins/system/plugins.tsx +356 -0
  140. package/src/feature-plugins/system/stats-data.ts +18 -0
  141. package/src/feature-plugins/system/stats.tsx +217 -0
  142. package/src/feature-plugins/system/storybook/footer.tsx +51 -0
  143. package/src/feature-plugins/system/storybook/highlights.tsx +71 -0
  144. package/src/feature-plugins/system/storybook/index.tsx +153 -0
  145. package/src/feature-plugins/system/storybook/link-clicks.tsx +125 -0
  146. package/src/feature-plugins/system/storybook/merman-layouts.tsx +200 -0
  147. package/src/feature-plugins/system/storybook/one-cell-spinner.fixtures.ts +144 -0
  148. package/src/feature-plugins/system/storybook/one-cell-spinner.tsx +293 -0
  149. package/src/feature-plugins/system/storybook/session-location-missing.tsx +80 -0
  150. package/src/feature-plugins/system/storybook/session-tabs.tsx +571 -0
  151. package/src/feature-plugins/system/storybook/subcell-spinner.fixtures.ts +115 -0
  152. package/src/feature-plugins/system/storybook/todo.tsx +166 -0
  153. package/src/index.tsx +2 -0
  154. package/src/logo.ts +21 -0
  155. package/src/mini/catalog.shared.ts +116 -0
  156. package/src/mini/demo.ts +1086 -0
  157. package/src/mini/entry.body.ts +244 -0
  158. package/src/mini/footer.command.tsx +1205 -0
  159. package/src/mini/footer.form.tsx +647 -0
  160. package/src/mini/footer.menu.tsx +313 -0
  161. package/src/mini/footer.permission.tsx +562 -0
  162. package/src/mini/footer.prompt.tsx +1533 -0
  163. package/src/mini/footer.subagent.tsx +268 -0
  164. package/src/mini/footer.ts +1193 -0
  165. package/src/mini/footer.view.tsx +1022 -0
  166. package/src/mini/footer.width.ts +118 -0
  167. package/src/mini/form.shared.ts +241 -0
  168. package/src/mini/index.ts +7 -0
  169. package/src/mini/mono.ts +277 -0
  170. package/src/mini/permission.shared.ts +199 -0
  171. package/src/mini/prompt.editor.ts +74 -0
  172. package/src/mini/prompt.shared.ts +192 -0
  173. package/src/mini/runtime.boot.ts +98 -0
  174. package/src/mini/runtime.lifecycle.ts +393 -0
  175. package/src/mini/runtime.queue.ts +320 -0
  176. package/src/mini/runtime.ts +1117 -0
  177. package/src/mini/scrollback.shared.ts +82 -0
  178. package/src/mini/scrollback.surface.ts +548 -0
  179. package/src/mini/scrollback.writer.tsx +380 -0
  180. package/src/mini/session-data.ts +13 -0
  181. package/src/mini/session.shared.ts +113 -0
  182. package/src/mini/splash.ts +307 -0
  183. package/src/mini/stream-v2.fragment.ts +83 -0
  184. package/src/mini/stream-v2.image.ts +38 -0
  185. package/src/mini/stream-v2.subagent.ts +1130 -0
  186. package/src/mini/stream-v2.transport.ts +1916 -0
  187. package/src/mini/stream.ts +152 -0
  188. package/src/mini/theme.ts +328 -0
  189. package/src/mini/tool.public.ts +3 -0
  190. package/src/mini/tool.ts +1394 -0
  191. package/src/mini/turn-summary.ts +21 -0
  192. package/src/mini/types.ts +482 -0
  193. package/src/mini/variant.shared.ts +58 -0
  194. package/src/mini/verbosity.ts +84 -0
  195. package/src/model-preference.ts +206 -0
  196. package/src/parsers-config.ts +386 -0
  197. package/src/plugin/api.tsx +486 -0
  198. package/src/plugin/builtins.ts +35 -0
  199. package/src/plugin/context.tsx +757 -0
  200. package/src/plugin/discovery.ts +67 -0
  201. package/src/plugin/markdown.ts +18 -0
  202. package/src/plugin/render.tsx +116 -0
  203. package/src/plugin/runtime-plugin-support.bun.ts +11 -0
  204. package/src/plugin/runtime-plugin-support.node.ts +1 -0
  205. package/src/plugin/source.ts +1 -0
  206. package/src/plugin/structure.ts +159 -0
  207. package/src/plugin/watch.ts +113 -0
  208. package/src/prompt/attachment.ts +97 -0
  209. package/src/prompt/codec.ts +61 -0
  210. package/src/prompt/content.ts +22 -0
  211. package/src/prompt/directory-completion.ts +97 -0
  212. package/src/prompt/directory-recents.ts +36 -0
  213. package/src/prompt/display.ts +41 -0
  214. package/src/prompt/frecency.tsx +80 -0
  215. package/src/prompt/history.tsx +175 -0
  216. package/src/prompt/mention.ts +173 -0
  217. package/src/prompt/parse.ts +25 -0
  218. package/src/prompt/part.ts +35 -0
  219. package/src/prompt/restore.ts +39 -0
  220. package/src/prompt/stash.tsx +93 -0
  221. package/src/prompt/traits.ts +29 -0
  222. package/src/routes/home.tsx +180 -0
  223. package/src/routes/session/activity-summary.ts +101 -0
  224. package/src/routes/session/anchor-view.tsx +53 -0
  225. package/src/routes/session/anchors.ts +85 -0
  226. package/src/routes/session/composer/context.ts +24 -0
  227. package/src/routes/session/composer/index.tsx +143 -0
  228. package/src/routes/session/composer/scripts-tab.tsx +166 -0
  229. package/src/routes/session/composer/shell-tab.tsx +149 -0
  230. package/src/routes/session/composer/subagents-tab.tsx +264 -0
  231. package/src/routes/session/composer/tabs.ts +91 -0
  232. package/src/routes/session/composer/terminals-tab.tsx +114 -0
  233. package/src/routes/session/dialog-execute.tsx +276 -0
  234. package/src/routes/session/dialog-fork.tsx +87 -0
  235. package/src/routes/session/dialog-message.tsx +89 -0
  236. package/src/routes/session/dialog-timeline.tsx +43 -0
  237. package/src/routes/session/form.tsx +1177 -0
  238. package/src/routes/session/group-view.tsx +407 -0
  239. package/src/routes/session/grouping/session.ts +184 -0
  240. package/src/routes/session/grouping/tree.ts +111 -0
  241. package/src/routes/session/history.ts +59 -0
  242. package/src/routes/session/index.tsx +3922 -0
  243. package/src/routes/session/location-missing.tsx +81 -0
  244. package/src/routes/session/message-navigation.ts +48 -0
  245. package/src/routes/session/message-parts.tsx +322 -0
  246. package/src/routes/session/mount-budget.ts +38 -0
  247. package/src/routes/session/permission.tsx +622 -0
  248. package/src/routes/session/render-context.tsx +44 -0
  249. package/src/routes/session/rows.ts +493 -0
  250. package/src/routes/session/sidebar.tsx +80 -0
  251. package/src/routes/session/thinking-syntax.ts +8 -0
  252. package/src/runtime.tsx +1 -0
  253. package/src/simulation/semantics.ts +12 -0
  254. package/src/theme/assets/aura.json +69 -0
  255. package/src/theme/assets/ayu.json +80 -0
  256. package/src/theme/assets/carbonfox.json +248 -0
  257. package/src/theme/assets/catppuccin-frappe.json +230 -0
  258. package/src/theme/assets/catppuccin-macchiato.json +230 -0
  259. package/src/theme/assets/catppuccin.json +112 -0
  260. package/src/theme/assets/cobalt2.json +225 -0
  261. package/src/theme/assets/cursor.json +249 -0
  262. package/src/theme/assets/dracula.json +219 -0
  263. package/src/theme/assets/everforest.json +241 -0
  264. package/src/theme/assets/flexoki.json +237 -0
  265. package/src/theme/assets/github.json +233 -0
  266. package/src/theme/assets/gruvbox.json +242 -0
  267. package/src/theme/assets/kanagawa.json +77 -0
  268. package/src/theme/assets/lucent-orng.json +234 -0
  269. package/src/theme/assets/material.json +235 -0
  270. package/src/theme/assets/matrix.json +77 -0
  271. package/src/theme/assets/mercury.json +252 -0
  272. package/src/theme/assets/monokai.json +221 -0
  273. package/src/theme/assets/nightowl.json +221 -0
  274. package/src/theme/assets/nord.json +223 -0
  275. package/src/theme/assets/one-dark.json +84 -0
  276. package/src/theme/assets/opencode.json +245 -0
  277. package/src/theme/assets/orng.json +249 -0
  278. package/src/theme/assets/osaka-jade.json +93 -0
  279. package/src/theme/assets/palenight.json +222 -0
  280. package/src/theme/assets/rosepine.json +234 -0
  281. package/src/theme/assets/solarized.json +223 -0
  282. package/src/theme/assets/synthwave84.json +226 -0
  283. package/src/theme/assets/tokyonight.json +243 -0
  284. package/src/theme/assets/v2/opencode-classic.json +387 -0
  285. package/src/theme/assets/v2/opencode.json +395 -0
  286. package/src/theme/assets/vercel.json +245 -0
  287. package/src/theme/assets/vesper.json +218 -0
  288. package/src/theme/assets/zenburn.json +223 -0
  289. package/src/theme/color.ts +48 -0
  290. package/src/theme/component.ts +51 -0
  291. package/src/theme/discovery.ts +21 -0
  292. package/src/theme/index.ts +109 -0
  293. package/src/theme/resolve.ts +53 -0
  294. package/src/theme/system.ts +144 -0
  295. package/src/theme/v1.ts +70 -0
  296. package/src/ui/animation.ts +235 -0
  297. package/src/ui/border.ts +21 -0
  298. package/src/ui/dialog-alert.tsx +51 -0
  299. package/src/ui/dialog-confirm.tsx +62 -0
  300. package/src/ui/dialog-export-options.tsx +316 -0
  301. package/src/ui/dialog-export-result.tsx +84 -0
  302. package/src/ui/dialog-help.tsx +40 -0
  303. package/src/ui/dialog-prompt.tsx +180 -0
  304. package/src/ui/dialog-select.tsx +1006 -0
  305. package/src/ui/dialog.tsx +560 -0
  306. package/src/ui/file-path.tsx +112 -0
  307. package/src/ui/layout.ts +26 -0
  308. package/src/ui/link.tsx +51 -0
  309. package/src/ui/one-cell-motion.ts +111 -0
  310. package/src/ui/pane-resize-handle.tsx +33 -0
  311. package/src/ui/pane-resize.ts +76 -0
  312. package/src/ui/select-controller.ts +45 -0
  313. package/src/ui/session-link.ts +92 -0
  314. package/src/ui/spinner.ts +368 -0
  315. package/src/ui/subcell.ts +37 -0
  316. package/src/ui/toast.tsx +222 -0
  317. package/src/ui/working-directory-actions.tsx +66 -0
  318. package/src/util/collapse-tool-output.ts +95 -0
  319. package/src/util/config-directories.ts +53 -0
  320. package/src/util/connected-provider.ts +15 -0
  321. package/src/util/delayed-presence.ts +34 -0
  322. package/src/util/diff.ts +84 -0
  323. package/src/util/error-details.ts +21 -0
  324. package/src/util/error.ts +141 -0
  325. package/src/util/filetype.ts +135 -0
  326. package/src/util/form.ts +146 -0
  327. package/src/util/highlights.ts +51 -0
  328. package/src/util/locale.ts +81 -0
  329. package/src/util/marquee.ts +51 -0
  330. package/src/util/media.ts +43 -0
  331. package/src/util/model.ts +33 -0
  332. package/src/util/path-format.ts +37 -0
  333. package/src/util/path.ts +12 -0
  334. package/src/util/permission.ts +188 -0
  335. package/src/util/persistence.ts +42 -0
  336. package/src/util/presentation.ts +42 -0
  337. package/src/util/project.ts +7 -0
  338. package/src/util/record.ts +3 -0
  339. package/src/util/renderer.ts +15 -0
  340. package/src/util/scroll.ts +29 -0
  341. package/src/util/selection.ts +103 -0
  342. package/src/util/session.ts +103 -0
  343. package/src/util/signal.ts +49 -0
  344. package/src/util/single-flight.ts +12 -0
  345. package/src/util/string-width.bun.ts +1 -0
  346. package/src/util/string-width.node.ts +26 -0
  347. package/src/util/string-width.ts +1 -0
  348. package/src/util/system.ts +23 -0
  349. package/src/util/todo.ts +43 -0
  350. package/src/util/tool-display.ts +70 -0
  351. package/src/util/usage-limits.ts +152 -0
  352. package/src/util/watch.ts +24 -0
  353. package/test/app-lifecycle.test.tsx +2962 -0
  354. package/test/clear-session.test.tsx +67 -0
  355. package/test/cli/cmd/tui/integration-options.test.ts +98 -0
  356. package/test/cli/cmd/tui/model-options.test.ts +105 -0
  357. package/test/cli/cmd/tui/notifications.test.ts +356 -0
  358. package/test/cli/tui/__snapshots__/inline-tool-wrap-snapshot.test.tsx.snap +22 -0
  359. package/test/cli/tui/anchors.test.ts +77 -0
  360. package/test/cli/tui/collapse-tool-output.test.ts +14 -0
  361. package/test/cli/tui/command-palette.test.tsx +86 -0
  362. package/test/cli/tui/composer-keymap.test.tsx +346 -0
  363. package/test/cli/tui/data.test.tsx +3669 -0
  364. package/test/cli/tui/dialog-integration.test.tsx +588 -0
  365. package/test/cli/tui/dialog-mcp.test.tsx +197 -0
  366. package/test/cli/tui/dialog-open.test.tsx +1037 -0
  367. package/test/cli/tui/dialog-prompt.test.tsx +253 -0
  368. package/test/cli/tui/dialog-select.test.tsx +740 -0
  369. package/test/cli/tui/dialog-session-list.test.tsx +130 -0
  370. package/test/cli/tui/diff-viewer-file-tree.test.tsx +256 -0
  371. package/test/cli/tui/diff-viewer-image.test.tsx +172 -0
  372. package/test/cli/tui/diff-viewer.test.tsx +2510 -0
  373. package/test/cli/tui/form.test.tsx +950 -0
  374. package/test/cli/tui/group-boundary.test.ts +63 -0
  375. package/test/cli/tui/group-view.test.tsx +352 -0
  376. package/test/cli/tui/grouping-tree.test.ts +82 -0
  377. package/test/cli/tui/inline-tool-wrap-snapshot.test.tsx +248 -0
  378. package/test/cli/tui/input-scope.test.tsx +282 -0
  379. package/test/cli/tui/keymap-arguments.test.tsx +45 -0
  380. package/test/cli/tui/message-navigation.test.ts +164 -0
  381. package/test/cli/tui/mount-budget.test.ts +74 -0
  382. package/test/cli/tui/permission.test.ts +7 -0
  383. package/test/cli/tui/plugins-dialog.test.tsx +217 -0
  384. package/test/cli/tui/prompt-interrupt-status.test.tsx +25 -0
  385. package/test/cli/tui/prompt-move.test.tsx +446 -0
  386. package/test/cli/tui/reasoning-body.test.tsx +80 -0
  387. package/test/cli/tui/script-changes.test.ts +41 -0
  388. package/test/cli/tui/session-grouping.test.ts +21 -0
  389. package/test/cli/tui/session-history.test.ts +124 -0
  390. package/test/cli/tui/session-rows.test.ts +616 -0
  391. package/test/cli/tui/session-verbosity.test.ts +307 -0
  392. package/test/cli/tui/theme-mode.test.tsx +179 -0
  393. package/test/cli/tui/thinking.test.ts +36 -0
  394. package/test/cli/tui/toast.test.tsx +117 -0
  395. package/test/cli/tui/use-event.test.tsx +295 -0
  396. package/test/client-mcp.test.tsx +226 -0
  397. package/test/clipboard.test.ts +148 -0
  398. package/test/command-selection.test.tsx +123 -0
  399. package/test/compact-admission.test.tsx +251 -0
  400. package/test/completion-notices.test.tsx +197 -0
  401. package/test/component/animation-ticks.test.tsx +212 -0
  402. package/test/component/dialog-error-details.test.tsx +110 -0
  403. package/test/component/dialog-export-options.test.tsx +68 -0
  404. package/test/component/dialog-highlights.test.tsx +73 -0
  405. package/test/component/dialog-model.test.tsx +145 -0
  406. package/test/component/dialog-shell-output.test.tsx +255 -0
  407. package/test/component/dialog-speed.test.tsx +114 -0
  408. package/test/component/dialog-update.test.tsx +111 -0
  409. package/test/component/dialog-variant.test.tsx +24 -0
  410. package/test/component/go-upsell-art.test.tsx +110 -0
  411. package/test/component/retry-provider.test.tsx +288 -0
  412. package/test/component/session-tabs-marquee.test.tsx +100 -0
  413. package/test/component/session-tabs-mouse.test.tsx +216 -0
  414. package/test/component/session-tabs-rail.test.tsx +120 -0
  415. package/test/component/session-tabs-status.test.tsx +345 -0
  416. package/test/component/shimmer-text.test.tsx +37 -0
  417. package/test/component/spinner-renderable.test.tsx +133 -0
  418. package/test/component/tab-pulse.test.tsx +196 -0
  419. package/test/component/terminal-pane-theme.test.ts +68 -0
  420. package/test/config-v2.test.tsx +335 -0
  421. package/test/config.test.tsx +184 -0
  422. package/test/context/local-selection.test.tsx +204 -0
  423. package/test/context/local.test.ts +15 -0
  424. package/test/context/program-status.test.ts +73 -0
  425. package/test/context/session-retention.test.ts +234 -0
  426. package/test/context/session-tabs-model.test.ts +341 -0
  427. package/test/context/session-tabs.test.tsx +864 -0
  428. package/test/context/storage.test.ts +37 -0
  429. package/test/context/theme.test.tsx +183 -0
  430. package/test/copy-session-id.test.tsx +79 -0
  431. package/test/editor.test.ts +69 -0
  432. package/test/feature-plugins/diff-viewer-file-tree-utils.test.ts +234 -0
  433. package/test/feature-plugins/goal.test.tsx +126 -0
  434. package/test/feature-plugins/home-footer.test.ts +13 -0
  435. package/test/feature-plugins/prompt-footer.test.tsx +303 -0
  436. package/test/feature-plugins/sidebar-context.test.tsx +70 -0
  437. package/test/feature-plugins/sidebar-footer.test.tsx +139 -0
  438. package/test/fixture/animation-ticks.ts +19 -0
  439. package/test/fixture/app.ts +95 -0
  440. package/test/fixture/diff-image.ts +7 -0
  441. package/test/fixture/fixture.ts +27 -0
  442. package/test/fixture/frame.ts +25 -0
  443. package/test/fixture/local.tsx +158 -0
  444. package/test/fixture/plugin/client-reads/tui.tsx +9 -0
  445. package/test/fixture/plugin/dialog-throw/tui.tsx +11 -0
  446. package/test/fixture/plugin/native-resources/tui.tsx +26 -0
  447. package/test/fixture/plugin/setup-keymap/tui.tsx +72 -0
  448. package/test/fixture/plugin/slot-string/tui.tsx +10 -0
  449. package/test/fixture/tui-client.ts +186 -0
  450. package/test/fixture/tui-environment.tsx +47 -0
  451. package/test/fixture/tui-runtime.ts +21 -0
  452. package/test/highlights.test.ts +43 -0
  453. package/test/interactivity.test.tsx +46 -0
  454. package/test/keybind.test.ts +7 -0
  455. package/test/keymap-scope.test.tsx +271 -0
  456. package/test/keymap.test.tsx +244 -0
  457. package/test/markdown-streaming.test.tsx +49 -0
  458. package/test/mini/blocker.responsive.test.tsx +732 -0
  459. package/test/mini/catalog.shared.test.ts +76 -0
  460. package/test/mini/entry.body.test.ts +622 -0
  461. package/test/mini/fixture/catalog.ts +63 -0
  462. package/test/mini/fixture/footer-api.ts +69 -0
  463. package/test/mini/fixture/tool-part.ts +20 -0
  464. package/test/mini/footer-keymap.test.tsx +141 -0
  465. package/test/mini/footer.menu.test.ts +43 -0
  466. package/test/mini/footer.responsive.test.tsx +438 -0
  467. package/test/mini/footer.test.ts +446 -0
  468. package/test/mini/footer.view.test.tsx +2627 -0
  469. package/test/mini/footer.width.test.ts +120 -0
  470. package/test/mini/form.shared.test.ts +66 -0
  471. package/test/mini/permission.shared.test.ts +195 -0
  472. package/test/mini/prompt.editor.test.ts +118 -0
  473. package/test/mini/prompt.shared.test.ts +104 -0
  474. package/test/mini/runtime.boot.test.ts +118 -0
  475. package/test/mini/runtime.queue.test.ts +443 -0
  476. package/test/mini/runtime.test.ts +591 -0
  477. package/test/mini/scrollback.image.test.ts +213 -0
  478. package/test/mini/scrollback.surface.test.ts +1078 -0
  479. package/test/mini/session.shared.test.ts +267 -0
  480. package/test/mini/splash.test.ts +196 -0
  481. package/test/mini/stream-v2.transport.test.ts +4705 -0
  482. package/test/mini/stream.test.ts +52 -0
  483. package/test/mini/theme.test.ts +438 -0
  484. package/test/mini/tool.test.ts +134 -0
  485. package/test/mini/variant.shared.test.ts +58 -0
  486. package/test/mini/verbosity.test.ts +53 -0
  487. package/test/model-preference.test.ts +70 -0
  488. package/test/new-session-id.test.tsx +102 -0
  489. package/test/new-session-location.test.ts +30 -0
  490. package/test/panel.test.ts +71 -0
  491. package/test/plugin-discovery.test.ts +18 -0
  492. package/test/plugin-keymap.test.tsx +143 -0
  493. package/test/plugin-markdown.test.tsx +120 -0
  494. package/test/plugin-model.test.tsx +46 -0
  495. package/test/plugin-native-resources.test.tsx +11 -0
  496. package/test/plugin-select.test.tsx +391 -0
  497. package/test/plugin-slot-output.test.tsx +23 -0
  498. package/test/plugin-source.test.ts +871 -0
  499. package/test/plugin-toast.test.tsx +62 -0
  500. package/test/preload.ts +17 -0
  501. package/test/prompt/attachment.test.ts +138 -0
  502. package/test/prompt/autocomplete.test.ts +218 -0
  503. package/test/prompt/codec.test.ts +136 -0
  504. package/test/prompt/display.test.ts +72 -0
  505. package/test/prompt/draft-stash.test.ts +42 -0
  506. package/test/prompt/history-composer.test.tsx +52 -0
  507. package/test/prompt/history-provider.test.tsx +108 -0
  508. package/test/prompt/history.test.ts +94 -0
  509. package/test/prompt/jsonl.test.ts +24 -0
  510. package/test/prompt/local-attachment.test.ts +244 -0
  511. package/test/prompt/mention.test.ts +119 -0
  512. package/test/prompt/parse.test.ts +46 -0
  513. package/test/prompt/part.test.ts +40 -0
  514. package/test/prompt/persistence.test.ts +23 -0
  515. package/test/prompt/traits.test.ts +25 -0
  516. package/test/prompt-cursor.test.tsx +27 -0
  517. package/test/prompt-offset.test.tsx +58 -0
  518. package/test/prompt-paste.test.tsx +127 -0
  519. package/test/prompt-shell-failure.test.tsx +76 -0
  520. package/test/routes/composer-tabs.test.tsx +97 -0
  521. package/test/runtime.test.tsx +37 -0
  522. package/test/session-activity-anchor.test.tsx +180 -0
  523. package/test/session-backfill-disclosure.test.tsx +89 -0
  524. package/test/session-dialog-resync.test.tsx +122 -0
  525. package/test/session-fork-pending.test.tsx +60 -0
  526. package/test/session-group-navigation.test.tsx +252 -0
  527. package/test/session-history-interactions.test.tsx +305 -0
  528. package/test/session-history-reveal.test.tsx +108 -0
  529. package/test/session-home.test.tsx +401 -0
  530. package/test/session-interrupt-undo.test.tsx +98 -0
  531. package/test/session-media-refs.test.tsx +360 -0
  532. package/test/session-mount-budget.test.tsx +137 -0
  533. package/test/session-panel.test.tsx +721 -0
  534. package/test/session-shell-output.test.tsx +114 -0
  535. package/test/session-shell-stopped.test.tsx +107 -0
  536. package/test/session-subagent-navigation.test.tsx +44 -0
  537. package/test/session-submit-scroll.test.tsx +85 -0
  538. package/test/session-terminal-availability.test.tsx +80 -0
  539. package/test/session-wheel-focus.test.tsx +176 -0
  540. package/test/simulation/semantics.test.ts +23 -0
  541. package/test/stats.test.ts +33 -0
  542. package/test/stats.view.test.tsx +94 -0
  543. package/test/theme/v2/component.test.ts +87 -0
  544. package/test/theme/v2/resolve.test.ts +424 -0
  545. package/test/theme/v2/select.test.ts +25 -0
  546. package/test/theme/v2/types.typecheck.ts +57 -0
  547. package/test/theme/v2/v1-migrate.test.ts +397 -0
  548. package/test/theme.test.ts +150 -0
  549. package/test/ui/dialog-layout.test.tsx +56 -0
  550. package/test/ui/file-path.test.ts +61 -0
  551. package/test/ui/layout.test.ts +31 -0
  552. package/test/ui/link.test.tsx +60 -0
  553. package/test/ui/pane-resize-handle.test.tsx +134 -0
  554. package/test/ui/pane-resize.test.ts +258 -0
  555. package/test/ui/select-controller.test.ts +44 -0
  556. package/test/ui/session-link.test.tsx +325 -0
  557. package/test/usage-limits.test.tsx +162 -0
  558. package/test/util/added-patch.test.ts +44 -0
  559. package/test/util/connected-provider.test.ts +59 -0
  560. package/test/util/delayed-presence.test.ts +114 -0
  561. package/test/util/error-details.test.ts +26 -0
  562. package/test/util/error.test.ts +36 -0
  563. package/test/util/filetype.test.ts +23 -0
  564. package/test/util/form.test.ts +110 -0
  565. package/test/util/locale.test.ts +32 -0
  566. package/test/util/marquee.test.ts +45 -0
  567. package/test/util/media.test.ts +54 -0
  568. package/test/util/model.test.ts +70 -0
  569. package/test/util/path-format.test.ts +15 -0
  570. package/test/util/permission.test.ts +23 -0
  571. package/test/util/presentation.test.ts +30 -0
  572. package/test/util/renderer.test.ts +42 -0
  573. package/test/util/selection-copy-on-select.test.tsx +64 -0
  574. package/test/util/selection-keys.test.ts +172 -0
  575. package/test/util/selection.test.ts +115 -0
  576. package/test/util/session.test.ts +70 -0
  577. package/test/util/tool-display.test.ts +65 -0
  578. package/test/util/usage-limits.test.ts +154 -0
  579. package/tsconfig.json +13 -0
  580. package/README.md +0 -3
@@ -0,0 +1,2962 @@
1
+ import { expect, spyOn, test } from "bun:test"
2
+ import { EmbeddedTerminalRenderable, type Renderable } from "@opentui/core"
3
+ import { createTestRenderer } from "@opentui/core/testing"
4
+ import { Effect, FileSystem } from "effect"
5
+ import { Global } from "@zyro-sec/util/global"
6
+ import * as Open from "@zyro-sec/util/open"
7
+ import { waitForGoUpsellConnect } from "../src/component/dialog-go-upsell"
8
+ import { GoUpsellArtRenderable } from "../src/component/go-upsell-art"
9
+ import { SimulationRenderer } from "@zyro-sec/simulation/frontend/renderer"
10
+ import path from "node:path"
11
+ import { Writable } from "node:stream"
12
+ import { createEventStream, createFetch, directory, json } from "./fixture/tui-client"
13
+ import { tmpdir } from "./fixture/fixture"
14
+ import { createAppFixture } from "./fixture/app"
15
+ import { waitForHighlightedFrame } from "./fixture/frame"
16
+ import type { PluginInfo } from "@zyro-sec/client"
17
+
18
+ test.each([100, 44])("Ctrl-O is immediate, dismissible, and prunes cached deletions at width %s", async (width) => {
19
+ await using state = await tmpdir()
20
+ const requested = Promise.withResolvers<void>()
21
+ const response = Promise.withResolvers<Response>()
22
+ const projects = Promise.withResolvers<Response>()
23
+ const refresh = Promise.withResolvers<Response>()
24
+ const cachedSession = {
25
+ id: "ses_cached",
26
+ title: "Cached session",
27
+ projectID: "proj_fixture",
28
+ location: { directory: "/fixture" },
29
+ cost: 0,
30
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
31
+ time: { created: 1, updated: 2 },
32
+ }
33
+ let requests = 0
34
+ await using setup = await createAppFixture({
35
+ width,
36
+ state: state.path,
37
+ fetch: (url) => {
38
+ if (url.pathname === "/api/session") {
39
+ requests++
40
+ requested.resolve()
41
+ if (requests === 1) return response.promise
42
+ if (requests === 2 || requests === 4) return refresh.promise.then((response) => response.clone())
43
+ if (requests > 4) return new Response("Unavailable", { status: 503 })
44
+ return json({ data: [cachedSession], cursor: {} })
45
+ }
46
+ if (url.pathname === "/api/project") return projects.promise
47
+ return undefined
48
+ },
49
+ })
50
+ try {
51
+ await setup.ready
52
+ await setup.waitForFrame((frame) => frame.includes("commands"))
53
+ setup.mockInput.pressKey("o", { ctrl: true })
54
+ await requested.promise
55
+ await setup.renderOnce()
56
+ expect(setup.captureCharFrame()).toContain("Search sessions")
57
+ expect(setup.captureCharFrame()).toContain("Refreshing")
58
+ projects.resolve(
59
+ json([
60
+ {
61
+ id: "proj_fixture",
62
+ canonical: "/fixture",
63
+ name: "Fixture project",
64
+ time: { created: 1, updated: 2 },
65
+ sandboxes: [],
66
+ },
67
+ ]),
68
+ )
69
+ await setup.waitForFrame((frame) => frame.includes("Fixture project"))
70
+ setup.mockInput.pressKey("o", { ctrl: true })
71
+ expect(requests).toBe(1)
72
+ setup.mockInput.pressEscape()
73
+ await setup.waitForFrame((frame) => !frame.includes("Fixture project"))
74
+ response.resolve(json({ data: [{ ...cachedSession, id: "ses_disposed", title: "Disposed response" }], cursor: {} }))
75
+ await setup.renderOnce()
76
+ expect(setup.captureCharFrame()).not.toContain("Fixture project")
77
+ setup.mockInput.pressKey("o", { ctrl: true })
78
+ await setup.waitForFrame((frame) => frame.includes("Refreshing"))
79
+ expect(setup.captureCharFrame()).not.toContain("Disposed")
80
+ setup.mockInput.pressEscape()
81
+ await setup.waitForFrame((frame) => !frame.includes("Fixture project"))
82
+ setup.mockInput.pressKey("o", { ctrl: true })
83
+ await setup.waitForFrame((frame) => frame.includes("Cached"))
84
+ setup.mockInput.pressEscape()
85
+ await setup.waitForFrame((frame) => !frame.includes("Fixture project"))
86
+ setup.mockInput.pressKey("o", { ctrl: true })
87
+ await setup.waitForFrame((frame) => frame.includes("Cached") && frame.includes("Refreshing"))
88
+ setup.events.emit({
89
+ id: "evt_deleted",
90
+ created: 1,
91
+ type: "session.deleted",
92
+ durable: { aggregateID: "ses_cached", seq: 1, version: 2 },
93
+ data: { sessionID: "ses_cached" },
94
+ })
95
+ await setup.waitForFrame((frame) => !frame.includes("Cached"))
96
+ refresh.resolve(json({ data: [cachedSession], cursor: {} }))
97
+ await setup.waitForFrame((frame) => frame.includes("Fixture project") && !frame.includes("Refreshing"))
98
+ expect(setup.captureCharFrame()).not.toContain("Cached")
99
+ setup.mockInput.pressEscape()
100
+ await setup.waitForFrame((frame) => !frame.includes("Fixture project"))
101
+ setup.mockInput.pressKey("o", { ctrl: true })
102
+ await setup.waitForFrame((frame) => frame.includes("Could not refresh sessions"))
103
+ expect(setup.captureCharFrame()).not.toContain("Cached")
104
+ } finally {
105
+ response.resolve(json({ data: [], cursor: {} }))
106
+ projects.resolve(json([]))
107
+ refresh.resolve(json({ data: [], cursor: {} }))
108
+ }
109
+ })
110
+
111
+ test.each(["dismissed", "refreshing"])(
112
+ "Ctrl-O retains committed movement of a cached-only session while %s",
113
+ async (phase) => {
114
+ await using state = await tmpdir()
115
+ const refresh = Promise.withResolvers<Response>()
116
+ const metadata = Promise.withResolvers<Response>()
117
+ const destinationRequested = Promise.withResolvers<void>()
118
+ const cached = {
119
+ id: "ses_cached_move",
120
+ title: "Cached movement",
121
+ projectID: "proj_old",
122
+ location: { directory: "/fixture/old" },
123
+ cost: 0,
124
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
125
+ time: { created: 1, updated: 2 },
126
+ }
127
+ let requests = 0
128
+ const locations: string[] = []
129
+ await using setup = await createAppFixture({
130
+ state: state.path,
131
+ config: { animations: false, tabs: { mode: "off" } },
132
+ fetch: (url) => {
133
+ if (url.pathname === "/api/session") {
134
+ if (url.searchParams.has("parentID")) {
135
+ const parent = url.searchParams.get("parentID")
136
+ if (parent && parent !== "null") return json({ data: [], cursor: {} })
137
+ }
138
+ return requests++ === 0
139
+ ? json({ data: [cached], cursor: {} })
140
+ : refresh.promise.then((response) => response.clone())
141
+ }
142
+ if (url.pathname === `/api/session/${cached.id}`) return metadata.promise
143
+ if (url.pathname === `/api/session/${cached.id}/message`) return json({ data: [], cursor: {} })
144
+ if (
145
+ url.pathname === `/api/session/${cached.id}/inbox` ||
146
+ url.pathname === `/api/session/${cached.id}/permission`
147
+ )
148
+ return json({ data: [] })
149
+ if (url.pathname === "/api/project")
150
+ return json(
151
+ ["old", "new"].map((name) => ({
152
+ id: `proj_${name}`,
153
+ canonical: `/fixture/${name}`,
154
+ name: name === "old" ? "Old" : "New",
155
+ time: { created: 1, updated: 2 },
156
+ sandboxes: [],
157
+ })),
158
+ )
159
+ if (url.pathname === "/api/location") {
160
+ const query = url.searchParams.get("location[directory]") ?? ""
161
+ locations.push(query)
162
+ if (query.includes("/fixture/new")) {
163
+ destinationRequested.resolve()
164
+ return json({
165
+ directory: "/fixture/new",
166
+ project: { id: "proj_new", directory: "/fixture/new", canonical: "/fixture/new" },
167
+ })
168
+ }
169
+ }
170
+ return undefined
171
+ },
172
+ })
173
+ try {
174
+ await setup.ready
175
+ await setup.waitForFrame((frame) => frame.includes("commands"))
176
+ setup.mockInput.pressKey("o", { ctrl: true })
177
+ await setup.waitForFrame((frame) => frame.includes(cached.title) && !frame.includes("Refreshing"))
178
+ setup.mockInput.pressEscape()
179
+ await setup.waitForFrame((frame) => !frame.includes("Search sessions"))
180
+ if (phase === "refreshing") {
181
+ setup.mockInput.pressKey("o", { ctrl: true })
182
+ await setup.waitForFrame((frame) => frame.includes(cached.title) && frame.includes("Refreshing"))
183
+ }
184
+ setup.events.emit({
185
+ id: "evt_cached_moved",
186
+ created: 3,
187
+ type: "session.moved",
188
+ durable: { aggregateID: cached.id, seq: 1, version: 1 },
189
+ data: { sessionID: cached.id, location: { directory: "/fixture/new" }, projectID: "proj_new" },
190
+ })
191
+ if (phase === "dismissed") {
192
+ setup.mockInput.pressKey("o", { ctrl: true })
193
+ refresh.resolve(new Response("Unavailable", { status: 503 }))
194
+ await setup.waitForFrame((frame) => frame.includes("Could not refresh sessions"))
195
+ }
196
+ if (phase === "refreshing") {
197
+ await setup.waitForFrame((frame) =>
198
+ frame.split("\n").some((line) => line.includes(cached.title) && line.includes("New")),
199
+ )
200
+ refresh.resolve(json({ data: [cached], cursor: {} }))
201
+ await setup.waitForFrame((frame) => frame.includes(cached.title) && !frame.includes("Refreshing"))
202
+ }
203
+ await setup.waitForFrame((frame) =>
204
+ frame.split("\n").some((line) => line.includes(cached.title) && line.includes("New")),
205
+ )
206
+ expect(
207
+ setup
208
+ .captureCharFrame()
209
+ .split("\n")
210
+ .find((line) => line.includes(cached.title)),
211
+ ).toContain("New")
212
+ locations.length = 0
213
+ setup.mockInput.pressEnter()
214
+ await destinationRequested.promise
215
+ expect(locations.some((query) => query.includes("/fixture/old"))).toBe(false)
216
+ } finally {
217
+ refresh.resolve(json({ data: [], cursor: {} }))
218
+ metadata.resolve(json({ data: { ...cached, projectID: "proj_new", location: { directory: "/fixture/new" } } }))
219
+ }
220
+ },
221
+ )
222
+
223
+ test("boots on the simulation renderer with the terminal title enabled", async () => {
224
+ await Effect.runPromise(
225
+ Effect.scoped(
226
+ Effect.gen(function* () {
227
+ const setup = SimulationRenderer.setupFor(yield* SimulationRenderer.create({}))
228
+ yield* Effect.promise(async () => {
229
+ await using app = await createAppFixture({ setup })
230
+ await app.ready
231
+ await app.waitForFrame((frame) => frame.includes("commands"))
232
+ })
233
+ }),
234
+ ),
235
+ )
236
+ })
237
+
238
+ test("SIGHUP clears title and disposes scoped resources once", async () => {
239
+ await using state = await tmpdir()
240
+ const output: string[] = []
241
+ const setup = await createTestRenderer({
242
+ width: 80,
243
+ height: 24,
244
+ bufferedOutput: "stdout",
245
+ stdout: new Writable({
246
+ write(chunk, _encoding, callback) {
247
+ output.push(chunk.toString())
248
+ callback()
249
+ },
250
+ }) as NodeJS.WriteStream,
251
+ })
252
+ await setup.renderer.setupTerminal()
253
+ let started!: () => void
254
+ const ready = new Promise<void>((resolve) => {
255
+ started = resolve
256
+ })
257
+ const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer)
258
+ setup.renderer.setTerminalTitle = (title) => {
259
+ if (title === "OpenCode") started()
260
+ setTitle(title)
261
+ }
262
+ const listeners = new Set(process.listeners("SIGHUP"))
263
+ const events = createEventStream()
264
+ const calls = createFetch(undefined, events)
265
+ const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
266
+ try {
267
+ const { run } = await import("../src/app")
268
+ const task = Effect.runPromise(
269
+ run({
270
+ app: { name: "test", version: "test", channel: "test" },
271
+ server: { endpoint: { url: server.url.toString() } },
272
+ config: { get: async () => ({}), update: async () => ({}) },
273
+ packages: { prepare: async () => ({ directory: "" }) },
274
+ terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
275
+ args: {},
276
+ log: () => {},
277
+ }).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
278
+ )
279
+ await ready
280
+ process.emit("SIGHUP")
281
+ await task
282
+
283
+ expect(setup.renderer.isDestroyed).toBe(true)
284
+ expect(output.join("")).toContain("\x1b]0;\x07")
285
+ expect(process.listeners("SIGHUP").every((listener) => listeners.has(listener))).toBe(true)
286
+ } finally {
287
+ if (!setup.renderer.isDestroyed) setup.renderer.destroy()
288
+ await setup.renderer.closed
289
+ await server.stop()
290
+ }
291
+ })
292
+
293
+ test("session lifecycle updates the terminal title and prints the epilogue after cleanup", async () => {
294
+ await using state = await tmpdir()
295
+ const setup = await createTestRenderer({ width: 80, height: 24 })
296
+ await setup.renderer.setupTerminal()
297
+ let initialTitle!: () => void
298
+ const initialTitleSet = new Promise<void>((resolve) => {
299
+ initialTitle = resolve
300
+ })
301
+ let renamedTitle!: () => void
302
+ const renamedTitleSet = new Promise<void>((resolve) => {
303
+ renamedTitle = resolve
304
+ })
305
+ const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer)
306
+ setup.renderer.setTerminalTitle = (title) => {
307
+ if (title === "OC | Demo session") initialTitle()
308
+ if (title === "OC | Renamed session") renamedTitle()
309
+ setTitle(title)
310
+ }
311
+ const events = createEventStream()
312
+ let promptRequests = 0
313
+ const calls = createFetch((url) => {
314
+ const session = {
315
+ id: "dummy",
316
+ title: "Demo session",
317
+ projectID: "project",
318
+ location: { directory },
319
+ cost: 0,
320
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
321
+ time: { created: 0, updated: 0 },
322
+ }
323
+ if (url.pathname === "/api/session")
324
+ return json({
325
+ data: [session],
326
+ cursor: {},
327
+ })
328
+ if (url.pathname === "/api/session/dummy") return json({ data: session })
329
+ if (url.pathname === "/api/session/dummy/message") return json({ data: [], cursor: {} })
330
+ if (url.pathname === "/api/session/dummy/inbox") return json({ data: [] })
331
+ if (url.pathname === "/api/session/dummy/permission") return json({ data: [] })
332
+ if (url.pathname === "/api/session/dummy/prompt") {
333
+ promptRequests++
334
+ return json({ data: {} })
335
+ }
336
+ }, events)
337
+ const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
338
+ const originalWrite = process.stdout.write.bind(process.stdout)
339
+ let stdout = ""
340
+ process.stdout.write = ((chunk: string | Uint8Array) => {
341
+ stdout += String(chunk)
342
+ return true
343
+ }) as typeof process.stdout.write
344
+
345
+ try {
346
+ const { run } = await import("../src/app")
347
+ const task = Effect.runPromise(
348
+ run({
349
+ app: { name: "test", version: "test", channel: "test" },
350
+ server: { endpoint: { url: server.url.toString() } },
351
+ config: { get: async () => ({}), update: async () => ({}) },
352
+ packages: { prepare: async () => ({ directory: "" }) },
353
+ terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
354
+ args: { sessionID: "dummy" },
355
+ log: () => {},
356
+ }).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
357
+ )
358
+
359
+ await initialTitleSet
360
+ events.emit({
361
+ id: "evt_renamed",
362
+ created: 1,
363
+ type: "session.renamed",
364
+ durable: { aggregateID: "dummy", seq: 1, version: 1 },
365
+ data: { sessionID: "dummy", title: "Renamed session" },
366
+ })
367
+ await renamedTitleSet
368
+ setup.renderer.destroy()
369
+ await task
370
+
371
+ expect(stdout).toContain("Renamed session")
372
+ expect(stdout).toContain("opencode -s dummy")
373
+ expect(promptRequests).toBe(0)
374
+ } finally {
375
+ process.stdout.write = originalWrite
376
+ if (!setup.renderer.isDestroyed) setup.renderer.destroy()
377
+ await server.stop()
378
+ }
379
+ })
380
+
381
+ test("session title generated while an untitled session is loading remains visible", async () => {
382
+ await using state = await tmpdir()
383
+ const setup = await createTestRenderer({ width: 80, height: 24 })
384
+ await setup.renderer.setupTerminal()
385
+ const titles: string[] = []
386
+ const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer)
387
+ const generatedTitle = Promise.withResolvers<void>()
388
+ setup.renderer.setTerminalTitle = (title) => {
389
+ titles.push(title)
390
+ if (title === "OC | Generated title") generatedTitle.resolve()
391
+ setTitle(title)
392
+ }
393
+ const sessionRequested = Promise.withResolvers<void>()
394
+ const renameSyncRequested = Promise.withResolvers<void>()
395
+ const releaseSession = Promise.withResolvers<void>()
396
+ let sessionRequests = 0
397
+ const session = {
398
+ id: "dummy",
399
+ projectID: "project",
400
+ location: { directory },
401
+ cost: 0,
402
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
403
+ time: { created: 0, updated: 0 },
404
+ }
405
+ const events = createEventStream()
406
+ const calls = createFetch(async (url) => {
407
+ if (url.pathname === "/api/session") return json({ data: [], cursor: {} })
408
+ if (url.pathname === "/api/session/dummy") {
409
+ sessionRequests++
410
+ sessionRequested.resolve()
411
+ if (sessionRequests === 2) renameSyncRequested.resolve()
412
+ await releaseSession.promise
413
+ return json({ data: session })
414
+ }
415
+ if (url.pathname === "/api/session/dummy/message") return json({ data: [], cursor: {} })
416
+ if (url.pathname === "/api/session/dummy/inbox") return json({ data: [] })
417
+ if (url.pathname === "/api/session/dummy/permission") return json({ data: [] })
418
+ }, events)
419
+ const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
420
+
421
+ try {
422
+ const { run } = await import("../src/app")
423
+ const task = Effect.runPromise(
424
+ run({
425
+ app: { name: "test", version: "test", channel: "test" },
426
+ server: { endpoint: { url: server.url.toString() } },
427
+ config: { get: async () => ({}), update: async () => ({}) },
428
+ packages: { prepare: async () => ({ directory: "" }) },
429
+ terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
430
+ args: { sessionID: "dummy" },
431
+ log: () => {},
432
+ }).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
433
+ )
434
+
435
+ await sessionRequested.promise
436
+ events.emit({
437
+ id: "evt_renamed",
438
+ created: 1,
439
+ type: "session.renamed",
440
+ durable: { aggregateID: "dummy", seq: 1, version: 1 },
441
+ data: { sessionID: "dummy", title: "Generated title" },
442
+ })
443
+ await Promise.race([
444
+ renameSyncRequested.promise,
445
+ Bun.sleep(2_000).then(() => {
446
+ throw new Error("rename sync did not start")
447
+ }),
448
+ ])
449
+ releaseSession.resolve()
450
+ await Promise.race([
451
+ generatedTitle.promise,
452
+ Bun.sleep(2_000).then(() => {
453
+ throw new Error("generated title was not shown")
454
+ }),
455
+ ])
456
+ await Bun.sleep(20)
457
+
458
+ const generated = titles.lastIndexOf("OC | Generated title")
459
+ expect(generated).toBeGreaterThan(-1)
460
+ expect(titles.slice(generated + 1)).not.toContain("OpenCode")
461
+ setup.renderer.destroy()
462
+ await task
463
+ } finally {
464
+ if (!setup.renderer.isDestroyed) setup.renderer.destroy()
465
+ await server.stop()
466
+ }
467
+ })
468
+
469
+ test("vertical session tabs switch to horizontal below readable content width", async () => {
470
+ await using state = await tmpdir()
471
+ await Bun.write(path.join(state.path, "test", "tui", "layout.json"), JSON.stringify({ verticalTabsWidth: 42 }))
472
+ const session = {
473
+ id: "ses_resize",
474
+ title: "Resize fixture",
475
+ projectID: "project",
476
+ location: { directory },
477
+ cost: 0,
478
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
479
+ time: { created: 1, updated: 2 },
480
+ }
481
+ await using setup = await createAppFixture({
482
+ width: 120,
483
+ state: state.path,
484
+ config: {
485
+ animations: false,
486
+ tabs: { mode: "on", layout: "vertical", indicators: "status" },
487
+ session: { sidebar: "hide" },
488
+ },
489
+ args: { sessionID: session.id },
490
+ fetch: (url) => {
491
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
492
+ if (/^\/api\/session\/ses_resize\/(message|inbox|permission)$/.test(url.pathname))
493
+ return json({ data: [], cursor: {} })
494
+ return undefined
495
+ },
496
+ })
497
+ await setup.ready
498
+ await setup.waitForFrame((frame) => frame.split("\n")[1].slice(0, 42).includes(session.title))
499
+
500
+ setup.resize(100, 30)
501
+ await setup.waitForFrame((frame) => frame.split("\n")[0].includes(session.title))
502
+ expect(setup.captureCharFrame()).not.toContain("⌕")
503
+ setup.resize(120, 30)
504
+ await setup.waitForFrame((frame) => frame.split("\n")[1].slice(0, 42).includes(session.title))
505
+ })
506
+
507
+ test("narrow vertical session tabs collapse to a compact rail with the terminal", async () => {
508
+ await using state = await tmpdir()
509
+ await Bun.write(path.join(state.path, "test", "tui", "layout.json"), JSON.stringify({ verticalTabsWidth: 5 }))
510
+ const session = {
511
+ id: "ses_resize",
512
+ title: "Resize fixture",
513
+ projectID: "project",
514
+ location: { directory },
515
+ cost: 0,
516
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
517
+ time: { created: 1, updated: 2 },
518
+ }
519
+ await using setup = await createAppFixture({
520
+ width: 80,
521
+ state: state.path,
522
+ config: {
523
+ animations: false,
524
+ tabs: { mode: "on", layout: "vertical", indicators: "status" },
525
+ session: { sidebar: "hide" },
526
+ },
527
+ args: { sessionID: session.id },
528
+ fetch: (url) => {
529
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
530
+ if (/^\/api\/session\/ses_resize\/(message|inbox|permission)$/.test(url.pathname))
531
+ return json({ data: [], cursor: {} })
532
+ return undefined
533
+ },
534
+ })
535
+ await setup.ready
536
+ await setup.waitForFrame((frame) => frame.split("\n")[1].slice(0, 10).trim() === "⌕")
537
+
538
+ setup.resize(68, 30)
539
+ await setup.waitForFrame((frame) => frame.split("\n")[0].includes(session.title))
540
+ expect(setup.captureCharFrame()).not.toContain("⌕")
541
+ setup.resize(80, 30)
542
+ await setup.waitForFrame((frame) => frame.split("\n")[1].slice(0, 10).trim() === "⌕")
543
+ })
544
+
545
+ test("automatic rename refreshes the displayed title before settling, even without a renamed event", async () => {
546
+ await using state = await tmpdir()
547
+ const response = Promise.withResolvers<Response>()
548
+ const bodies: unknown[] = []
549
+ const location = { directory, project: { id: "project", directory, canonical: directory } }
550
+ const session = {
551
+ id: "ses_rename",
552
+ title: "Compiler cleanup",
553
+ projectID: "project",
554
+ location: { directory },
555
+ agent: "build",
556
+ model: { providerID: "provider", id: "model" },
557
+ cost: 0,
558
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
559
+ time: { created: 0, updated: 0 },
560
+ }
561
+ await using setup = await createAppFixture({
562
+ width: 110,
563
+ height: 20,
564
+ state: state.path,
565
+ config: { tabs: { mode: "on", layout: "vertical" }, session: { sidebar: "hide" } },
566
+ args: { sessionID: session.id },
567
+ fetch: async (url, request) => {
568
+ if (url.pathname === "/api/location") return json(location)
569
+ if (url.pathname === "/api/agent")
570
+ return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
571
+ if (url.pathname === "/api/model")
572
+ return json({ location, data: [{ id: "model", providerID: "provider", name: "Model", variants: [] }] })
573
+ if (url.pathname === "/api/provider") return json({ location, data: [{ id: "provider", name: "Provider" }] })
574
+ if (url.pathname === "/api/session") return json({ data: [], cursor: {} })
575
+ if (url.pathname === "/api/session/ses_rename" && request.method === "PATCH") {
576
+ bodies.push(await request.json())
577
+ return response.promise
578
+ }
579
+ if (url.pathname === "/api/session/ses_rename") return json({ data: session })
580
+ if (/^\/api\/session\/ses_rename\/(message|inbox|permission)$/.test(url.pathname))
581
+ return json({ data: [], cursor: {} })
582
+ return undefined
583
+ },
584
+ })
585
+
586
+ try {
587
+ await setup.waitForFrame((frame) => frame.includes(session.title) && frame.includes("Build · Model Provider"))
588
+ await setup.mockInput.typeText("/rename")
589
+ setup.mockInput.pressEscape()
590
+ setup.mockInput.pressEnter()
591
+ await setup.waitFor(() => bodies.length === 1)
592
+ await setup.renderOnce()
593
+ expect(bodies[0]).toEqual({ title: "" })
594
+ expect(setup.captureCharFrame()).toContain("Compiler cleanup")
595
+
596
+ session.title = "Simplify compiler parsing"
597
+ response.resolve(new Response(null, { status: 204 }))
598
+ await setup.waitForFrame((frame) => frame.includes(session.title), { maxPasses: 60 })
599
+ expect(setup.captureCharFrame()).not.toContain("Compiler cleanup")
600
+ } finally {
601
+ response.resolve(new Response(null, { status: 204 }))
602
+ }
603
+ })
604
+
605
+ test.each([80, 120])("completes custom Markdown and ordinary fences in a session at width %s", async (width) => {
606
+ await using state = await tmpdir()
607
+ const session = {
608
+ id: "ses_markdown",
609
+ title: "Markdown fixture",
610
+ projectID: "project",
611
+ location: { directory },
612
+ agent: "build",
613
+ model: { providerID: "fixture", id: "model" },
614
+ cost: 0,
615
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
616
+ time: { created: 1, updated: 2 },
617
+ }
618
+ const initial =
619
+ "```mermaid\ngraph LR\n A[DiagramStart] --> B[DiagramEnd]\n```\n\n```latex\nx^2\n```\n\n```text\ninitial"
620
+ await using setup = await createAppFixture({
621
+ width,
622
+ height: 55,
623
+ state: state.path,
624
+ config: { animations: false, tabs: { mode: "off" }, session: { sidebar: "hide" } },
625
+ args: { sessionID: session.id },
626
+ fetch: (url) => {
627
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
628
+ if (url.pathname === `/api/session/${session.id}/message`)
629
+ return json({
630
+ data: [
631
+ {
632
+ id: "msg_markdown",
633
+ type: "assistant",
634
+ agent: session.agent,
635
+ model: session.model,
636
+ time: { created: 2 },
637
+ content: [{ type: "text", text: initial }],
638
+ },
639
+ {
640
+ id: "msg_compaction",
641
+ type: "compaction",
642
+ time: { created: 1 },
643
+ status: "completed",
644
+ reason: "manual",
645
+ summary: "```latex\ny^2\n```",
646
+ recent: "msg_markdown",
647
+ },
648
+ ],
649
+ cursor: {},
650
+ })
651
+ if (
652
+ url.pathname === `/api/session/${session.id}/inbox` ||
653
+ url.pathname === `/api/session/${session.id}/permission`
654
+ )
655
+ return json({ data: [] })
656
+ return undefined
657
+ },
658
+ })
659
+ const streaming = await waitForHighlightedFrame(
660
+ setup,
661
+ (frame) =>
662
+ frame.includes("initial") &&
663
+ frame.includes("DiagramStart") &&
664
+ frame.includes("DiagramEnd") &&
665
+ frame.includes("x\u00b2") &&
666
+ frame.includes("y\u00b2"),
667
+ )
668
+ expect(streaming).toContain("Compaction")
669
+ expect(streaming).not.toContain("initial final")
670
+ expect(streaming).not.toContain("MARKDOWN_END")
671
+
672
+ // Queue final text and completion together to exercise TextPart's reactive property order.
673
+ setup.events.emit({
674
+ id: "evt_markdown_text_ended",
675
+ created: 3,
676
+ type: "session.text.ended",
677
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
678
+ data: {
679
+ sessionID: session.id,
680
+ assistantMessageID: "msg_markdown",
681
+ ordinal: 0,
682
+ text: `${initial} final\n\`\`\`\n\nMARKDOWN_END`,
683
+ },
684
+ })
685
+ setup.events.emit({
686
+ id: "evt_markdown_step_ended",
687
+ created: 4,
688
+ type: "session.step.ended",
689
+ durable: { aggregateID: session.id, seq: 2, version: 1 },
690
+ data: {
691
+ sessionID: session.id,
692
+ assistantMessageID: "msg_markdown",
693
+ finish: "stop",
694
+ cost: 0,
695
+ tokens: session.tokens,
696
+ },
697
+ })
698
+ const frame = await waitForHighlightedFrame(
699
+ setup,
700
+ (frame) => frame.includes("MARKDOWN_END") && frame.includes("initial final") && frame.includes("2ms"),
701
+ )
702
+ expect(frame).toContain("DiagramStart")
703
+ expect(frame).toContain("DiagramEnd")
704
+ expect(frame).toContain("x\u00b2")
705
+ expect(frame).toContain("y\u00b2")
706
+ expect(frame).toContain("initial final")
707
+ expect(frame).not.toContain("graph LR")
708
+ expect(frame).not.toContain("x^2")
709
+ expect(frame).not.toContain("y^2")
710
+ expect(frame).not.toContain("```")
711
+ })
712
+
713
+ test("a finished compaction summary shows a last line that streaming would hold back", async () => {
714
+ await using state = await tmpdir()
715
+ const session = {
716
+ id: "ses_compaction",
717
+ title: "Compaction fixture",
718
+ projectID: "project",
719
+ location: { directory },
720
+ agent: "build",
721
+ model: { providerID: "fixture", id: "model" },
722
+ cost: 0,
723
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
724
+ time: { created: 1, updated: 2 },
725
+ }
726
+ await using setup = await createAppFixture({
727
+ state: state.path,
728
+ config: { animations: false, tabs: { mode: "off" }, session: { sidebar: "hide" } },
729
+ args: { sessionID: session.id },
730
+ fetch: (url) => {
731
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
732
+ if (url.pathname === `/api/session/${session.id}/message`)
733
+ return json({
734
+ data: [
735
+ {
736
+ id: "msg_compaction",
737
+ type: "compaction",
738
+ time: { created: 1 },
739
+ status: "completed",
740
+ reason: "manual",
741
+ // A streaming document holds a last line that may still become a table's header.
742
+ summary: "SUMMARY_START\n\n| SUMMARY | END |",
743
+ },
744
+ ],
745
+ cursor: {},
746
+ })
747
+ if (
748
+ url.pathname === `/api/session/${session.id}/inbox` ||
749
+ url.pathname === `/api/session/${session.id}/permission`
750
+ )
751
+ return json({ data: [] })
752
+ return undefined
753
+ },
754
+ })
755
+ await setup.waitForFrame((frame) => frame.includes("SUMMARY_START"))
756
+ await setup.waitForFrame((frame) => frame.includes("SUMMARY | END"))
757
+ })
758
+
759
+ // Thinking "show" draws the thought as its own part; "hide" draws it in a thought group, opened with a click.
760
+ test.each(["show", "hide"] as const)(
761
+ "a finished thought shows a last line that streaming would hold back (thinking %s)",
762
+ async (thinking) => {
763
+ await using state = await tmpdir()
764
+ const session = {
765
+ id: "ses_thought",
766
+ title: "Thought fixture",
767
+ projectID: "project",
768
+ location: { directory },
769
+ agent: "build",
770
+ model: { providerID: "fixture", id: "model" },
771
+ cost: 0,
772
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
773
+ time: { created: 1, updated: 2 },
774
+ }
775
+ await using setup = await createAppFixture({
776
+ state: state.path,
777
+ config: {
778
+ animations: false,
779
+ tabs: { mode: "off" },
780
+ session: { sidebar: "hide", verbosity: "medium", thinking },
781
+ },
782
+ args: { sessionID: session.id },
783
+ fetch: (url) => {
784
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
785
+ if (url.pathname === `/api/session/${session.id}/message`)
786
+ return json({
787
+ data: [
788
+ {
789
+ id: "msg_thought",
790
+ type: "assistant",
791
+ agent: session.agent,
792
+ model: session.model,
793
+ finish: "stop",
794
+ time: { created: 2, completed: 4 },
795
+ content: [
796
+ {
797
+ type: "reasoning",
798
+ // A streaming document holds a last line that may still become a table's header.
799
+ text: "**Planning**\n\nTHOUGHT_START\n\n| THOUGHT | END |",
800
+ time: { created: 2, completed: 3 },
801
+ },
802
+ { type: "text", text: "Answer text" },
803
+ ],
804
+ },
805
+ { id: "msg_ask", type: "user", text: "Ask", time: { created: 1 } },
806
+ ],
807
+ cursor: {},
808
+ })
809
+ if (
810
+ url.pathname === `/api/session/${session.id}/inbox` ||
811
+ url.pathname === `/api/session/${session.id}/permission`
812
+ )
813
+ return json({ data: [] })
814
+ return undefined
815
+ },
816
+ })
817
+ await setup.waitForFrame((frame) => frame.includes("Answer text"))
818
+ if (thinking === "hide") {
819
+ const row = setup.captureCharFrame().split("\n").findIndex((line) => line.includes("+ Thought"))
820
+ await setup.mockMouse.click(6, row)
821
+ }
822
+ await setup.waitForFrame((frame) => frame.includes("THOUGHT_START"))
823
+ await setup.waitForFrame((frame) => frame.includes("THOUGHT | END"))
824
+ },
825
+ )
826
+
827
+ test("keeps assistant footer metrics current after prepend, refresh, and revert", async () => {
828
+ await using state = await tmpdir()
829
+ const session = {
830
+ id: "ses_footer",
831
+ title: "Footer fixture",
832
+ projectID: "project",
833
+ location: { directory },
834
+ agent: "build",
835
+ model: { providerID: "fixture", id: "model" },
836
+ cost: 0,
837
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
838
+ time: { created: 100, updated: 5000 },
839
+ }
840
+ let refresh = false
841
+ await using setup = await createAppFixture({
842
+ width: 100,
843
+ height: 40,
844
+ state: state.path,
845
+ config: { animations: false, tabs: { mode: "off" }, session: { sidebar: "hide", tps: true } },
846
+ args: { sessionID: session.id },
847
+ fetch: (url) => {
848
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
849
+ if (url.pathname === `/api/session/${session.id}/message`) {
850
+ if (url.searchParams.get("cursor") === "older")
851
+ return json({
852
+ data: [
853
+ {
854
+ id: "msg_0001",
855
+ type: "system",
856
+ text: "Earlier instructions",
857
+ description: "Prepended instructions",
858
+ time: { created: 200 },
859
+ },
860
+ { id: "msg_0000", type: "user", text: "Prepended input", time: { created: 100 } },
861
+ ],
862
+ cursor: {},
863
+ })
864
+ return json({
865
+ data: [
866
+ ...(refresh
867
+ ? [
868
+ {
869
+ id: "msg_0005",
870
+ type: "assistant",
871
+ agent: session.agent,
872
+ model: session.model,
873
+ time: { created: 7000, streamed: 8000, completed: 9000 },
874
+ finish: "stop",
875
+ cost: 0,
876
+ tokens: { ...session.tokens, output: 50 },
877
+ content: [{ type: "text", text: "Later answer" }],
878
+ },
879
+ { id: "msg_0004", type: "user", text: "Later input", time: { created: 6000 } },
880
+ ]
881
+ : []),
882
+ {
883
+ id: "msg_0003",
884
+ type: "assistant",
885
+ agent: session.agent,
886
+ model: session.model,
887
+ time: { created: 2000, firstToken: 2500, streamed: 3000, completed: 5000 },
888
+ finish: "stop",
889
+ cost: 0,
890
+ tokens: { ...session.tokens, output: 20 },
891
+ content: [{ type: "text", text: "Original answer" }],
892
+ },
893
+ { id: "msg_0002", type: "user", text: "Current input", time: { created: 1000 } },
894
+ ],
895
+ cursor: { next: "older" },
896
+ })
897
+ }
898
+ if (
899
+ url.pathname === `/api/session/${session.id}/inbox` ||
900
+ url.pathname === `/api/session/${session.id}/permission`
901
+ )
902
+ return json({ data: [] })
903
+ return undefined
904
+ },
905
+ })
906
+
907
+ const initial = await waitForHighlightedFrame(
908
+ setup,
909
+ (frame) => frame.includes("Original answer") && frame.includes("40.0 tok/s"),
910
+ )
911
+ expect(initial).toContain("Current input")
912
+ expect(initial).toContain("4.0s \u00b7 40.0 tok/s")
913
+ expect(initial).not.toContain("ttft")
914
+ expect(initial).not.toContain("Prepended input")
915
+
916
+ setup.mockInput.pressKey("g", { ctrl: true })
917
+ const prepended = await waitForHighlightedFrame(
918
+ setup,
919
+ (frame) =>
920
+ frame.includes("Prepended input") &&
921
+ frame.includes("Prepended instructions") &&
922
+ frame.includes("Original answer") &&
923
+ frame.includes("40.0 tok/s") &&
924
+ !frame.includes("Loading session history…"),
925
+ )
926
+ expect(prepended).toContain("Current input")
927
+ expect(prepended).toContain("Original answer")
928
+ expect(prepended).toContain("4.0s \u00b7 40.0 tok/s")
929
+
930
+ // Refresh the latest page: it brings a later turn and keeps the prepended history.
931
+ refresh = true
932
+ setup.events.disconnect()
933
+ const refreshed = await waitForHighlightedFrame(
934
+ setup,
935
+ (frame) => frame.includes("Later input") && frame.includes("Later answer"),
936
+ { maxPasses: 120 },
937
+ )
938
+ expect(refreshed).toContain("Prepended input")
939
+ expect(refreshed).toContain("Prepended instructions")
940
+ expect(refreshed).toContain("Current input")
941
+ expect(refreshed).toContain("Original answer")
942
+ expect(refreshed).toContain("4.0s \u00b7 40.0 tok/s")
943
+ expect(refreshed).toContain("3.0s \u00b7 50.0 tok/s")
944
+
945
+ setup.events.emit({
946
+ id: "evt_footer_reverted",
947
+ created: 10000,
948
+ type: "session.revert.committed",
949
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
950
+ data: { sessionID: session.id, to: "msg_0004" },
951
+ })
952
+ const reverted = await waitForHighlightedFrame(
953
+ setup,
954
+ (frame) => frame.includes("Original answer") && !frame.includes("Later input") && !frame.includes("Later answer"),
955
+ )
956
+ expect(reverted).toContain("Current input")
957
+ expect(reverted).toContain("4.0s \u00b7 40.0 tok/s")
958
+ expect(reverted).not.toContain("50.0 tok/s")
959
+ })
960
+
961
+ test("session startup prompt is submitted exactly once", async () => {
962
+ await using state = await tmpdir()
963
+ const setup = await createTestRenderer({ width: 80, height: 24 })
964
+ await setup.renderer.setupTerminal()
965
+ const events = createEventStream()
966
+ const cwd = process.cwd()
967
+ const location = { directory: cwd, project: { id: "project", directory: cwd } }
968
+ const session = {
969
+ id: "dummy",
970
+ title: "Demo session",
971
+ projectID: "project",
972
+ location: { directory: cwd },
973
+ agent: "build",
974
+ model: { providerID: "provider", id: "model" },
975
+ cost: 0,
976
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
977
+ time: { created: 0, updated: 0 },
978
+ }
979
+ const bodies: unknown[] = []
980
+ const promptSubmitted = Promise.withResolvers<void>()
981
+ const calls = createFetch(async (url, request) => {
982
+ if (url.pathname === "/api/location") return json(location)
983
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
984
+ if (url.pathname === "/api/session/dummy") return json({ data: session })
985
+ if (url.pathname === "/api/session/dummy/message") return json({ data: [], cursor: {} })
986
+ if (url.pathname === "/api/session/dummy/inbox") return json({ data: [] })
987
+ if (url.pathname === "/api/session/dummy/permission") return json({ data: [] })
988
+ if (url.pathname === "/api/agent")
989
+ return json({
990
+ location,
991
+ data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }],
992
+ })
993
+ if (url.pathname === "/api/model")
994
+ return json({
995
+ location,
996
+ data: [{ id: "model", providerID: "provider", name: "Model", variants: [] }],
997
+ })
998
+ if (url.pathname === "/api/session/dummy/prompt") {
999
+ bodies.push(await request.json())
1000
+ promptSubmitted.resolve()
1001
+ return json({ data: {} })
1002
+ }
1003
+ }, events)
1004
+ const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
1005
+
1006
+ try {
1007
+ const { run } = await import("../src/app")
1008
+ const task = Effect.runPromise(
1009
+ run({
1010
+ app: { name: "test", version: "test", channel: "test" },
1011
+ server: { endpoint: { url: server.url.toString() } },
1012
+ config: { get: async () => ({}), update: async () => ({}) },
1013
+ packages: { prepare: async () => ({ directory: "" }) },
1014
+ terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
1015
+ args: { sessionID: "dummy", prompt: "RESUME_READY" },
1016
+ log: () => {},
1017
+ }).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
1018
+ )
1019
+
1020
+ await Promise.race([
1021
+ promptSubmitted.promise,
1022
+ Bun.sleep(2000).then(() => {
1023
+ throw new Error("startup prompt was not submitted")
1024
+ }),
1025
+ ])
1026
+ await Bun.sleep(20)
1027
+ setup.renderer.destroy()
1028
+ await task
1029
+
1030
+ expect(bodies).toHaveLength(1)
1031
+ expect(bodies[0]).toMatchObject({ text: "RESUME_READY" })
1032
+ } finally {
1033
+ if (!setup.renderer.isDestroyed) setup.renderer.destroy()
1034
+ await server.stop()
1035
+ }
1036
+ })
1037
+
1038
+ test("home startup prompt is submitted exactly once", async () => {
1039
+ await using state = await tmpdir()
1040
+ const cwd = process.cwd()
1041
+ const location = { directory: cwd, project: { id: "project", directory: cwd, canonical: cwd } }
1042
+ const bodies: unknown[] = []
1043
+ const submitted = Promise.withResolvers<void>()
1044
+ let session: unknown
1045
+ await using setup = await createAppFixture({
1046
+ state: state.path,
1047
+ args: { prompt: "HOME_READY" },
1048
+ config: { animations: false, tabs: { mode: "off" } },
1049
+ fetch: async (url, request) => {
1050
+ if (url.pathname === "/api/location") return json(location)
1051
+ if (url.pathname === "/api/fs/list") return json({ location, data: [] })
1052
+ if (url.pathname === "/api/agent")
1053
+ return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
1054
+ if (url.pathname === "/api/model")
1055
+ return json({ location, data: [{ id: "model", providerID: "provider", name: "Model", variants: [] }] })
1056
+ if (url.pathname === "/api/provider") return json({ location, data: [{ id: "provider", name: "Provider" }] })
1057
+ if (url.pathname === "/api/session" && request.method === "POST") {
1058
+ const input: unknown = await request.json()
1059
+ if (typeof input !== "object" || input === null) throw new Error("Expected a session input")
1060
+ session = {
1061
+ ...input,
1062
+ projectID: "project",
1063
+ cost: 0,
1064
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1065
+ time: { created: 0, updated: 0 },
1066
+ }
1067
+ return json({ data: session })
1068
+ }
1069
+ if (/^\/api\/session\/[^/]+\/prompt$/.test(url.pathname)) {
1070
+ bodies.push(await request.json())
1071
+ submitted.resolve()
1072
+ return json({ data: {} })
1073
+ }
1074
+ if (/^\/api\/session\/[^/]+\/(message|inbox|permission)$/.test(url.pathname))
1075
+ return json({ data: [], cursor: {} })
1076
+ if (session && /^\/api\/session\/[^/]+$/.test(url.pathname)) return json({ data: session })
1077
+ return undefined
1078
+ },
1079
+ })
1080
+
1081
+ await setup.ready
1082
+ await Promise.race([
1083
+ submitted.promise,
1084
+ Bun.sleep(2000).then(() => {
1085
+ throw new Error("startup prompt was not submitted")
1086
+ }),
1087
+ ])
1088
+ await Bun.sleep(20)
1089
+ expect(bodies).toHaveLength(1)
1090
+ expect(bodies[0]).toMatchObject({ text: "HOME_READY" })
1091
+ })
1092
+
1093
+ test.each([false, true])("uses the resolved launch directory for new prompts (fallback: %s)", async (fallback) => {
1094
+ await using state = await tmpdir()
1095
+ const target = fallback ? directory : process.cwd()
1096
+ const location = { directory: target, project: { id: "project", directory: target, canonical: target } }
1097
+ const requests: URL[] = []
1098
+ const created = Promise.withResolvers<unknown>()
1099
+ const submitted = Promise.withResolvers<unknown>()
1100
+ let session: unknown
1101
+ await using setup = await createAppFixture({
1102
+ state: state.path,
1103
+ config: { animations: false, tabs: { mode: "off" }, keybinds: { "session.new": "f6" } },
1104
+ fetch: async (url, request) => {
1105
+ requests.push(url)
1106
+ if (url.searchParams.has("location[directory]") && url.searchParams.get("location[directory]") !== target)
1107
+ return json({ message: "Directory does not exist on the server" }, { status: 500 })
1108
+ if (url.pathname === "/api/fs/list") return json({ location, data: [] })
1109
+ if (url.pathname === "/api/location") return json(location)
1110
+ if (url.pathname === "/api/agent")
1111
+ return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
1112
+ if (url.pathname === "/api/model")
1113
+ return json({ location, data: [{ id: "model", providerID: "provider", name: "Remote Model", variants: [] }] })
1114
+ if (url.pathname === "/api/provider") return json({ location, data: [{ id: "provider", name: "Provider" }] })
1115
+ if (url.pathname === "/api/session" && request.method === "POST") {
1116
+ const input: unknown = await request.json()
1117
+ if (typeof input !== "object" || input === null) throw new Error("Expected a session input")
1118
+ created.resolve(input)
1119
+ session = {
1120
+ ...input,
1121
+ projectID: "project",
1122
+ cost: 0,
1123
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1124
+ time: { created: 0, updated: 0 },
1125
+ }
1126
+ return json({ data: session })
1127
+ }
1128
+ if (/^\/api\/session\/[^/]+\/prompt$/.test(url.pathname)) {
1129
+ submitted.resolve(await request.json())
1130
+ return json({ data: {} })
1131
+ }
1132
+ if (/^\/api\/session\/[^/]+\/(message|inbox|permission)$/.test(url.pathname))
1133
+ return json({ data: [], cursor: {} })
1134
+ if (session && /^\/api\/session\/[^/]+$/.test(url.pathname)) return json({ data: session })
1135
+ return undefined
1136
+ },
1137
+ })
1138
+
1139
+ await setup.ready
1140
+ await setup.waitForFrame((frame) => frame.includes("Build · Remote Model Provider"))
1141
+ setup.mockInput.pressKey("F6")
1142
+ await setup.renderOnce()
1143
+ await setup.mockInput.typeText("REMOTE_READY")
1144
+ await setup.waitForFrame((frame) => frame.includes("REMOTE_READY"))
1145
+ setup.mockInput.pressEnter()
1146
+ expect(
1147
+ await Promise.race([
1148
+ submitted.promise,
1149
+ Bun.sleep(2_000).then(() => {
1150
+ throw new Error("prompt was not submitted in the resolved server directory")
1151
+ }),
1152
+ ]),
1153
+ ).toMatchObject({ text: "REMOTE_READY" })
1154
+ expect(await created.promise).toMatchObject({ location: { directory: target } })
1155
+ expect(requests[0]?.pathname).toBe("/api/fs/list")
1156
+ expect(requests[0]?.searchParams.get("location[directory]")).toBe(process.cwd())
1157
+ expect(
1158
+ requests.filter((url) => url.pathname === "/api/location" && !url.searchParams.has("location[directory]")),
1159
+ ).toHaveLength(fallback ? 1 : 0)
1160
+ expect(
1161
+ requests
1162
+ .slice(1)
1163
+ .filter((url) => url.searchParams.has("location[directory]"))
1164
+ .every((url) => url.searchParams.get("location[directory]") === target),
1165
+ ).toBe(true)
1166
+ })
1167
+
1168
+ test("error investigations repeatedly seed editable home drafts without creating sessions", async () => {
1169
+ const cwd = process.cwd()
1170
+ const location = { directory: cwd, project: { id: "project", directory: cwd } }
1171
+ let created = 0
1172
+ await using setup = await createAppFixture({
1173
+ config: { animations: false, keybinds: { "mcp.list": "f6" } },
1174
+ fetch: (url, request) => {
1175
+ if (url.pathname === "/api/location") return json(location)
1176
+ if (url.pathname === "/api/mcp")
1177
+ return json({
1178
+ location,
1179
+ data: [
1180
+ { name: "alpha", status: { status: "failed", error: "Alpha connection refused" } },
1181
+ { name: "beta", status: { status: "failed", error: "Beta initialization failed" } },
1182
+ ],
1183
+ })
1184
+ if (url.pathname === "/api/session" && request.method === "POST") created++
1185
+ return undefined
1186
+ },
1187
+ })
1188
+ await setup.waitForFrame((frame) => frame.includes("commands"))
1189
+
1190
+ setup.mockInput.pressKey("F6")
1191
+ await setup.waitForFrame((frame) => frame.includes("MCP servers") && frame.includes("alpha"))
1192
+ setup.mockInput.pressEnter()
1193
+ await setup.waitForFrame((frame) => frame.includes("Alpha connection refused") && frame.includes("investigate i"))
1194
+ setup.mockInput.pressKey("i")
1195
+ await setup.waitForFrame((frame) => frame.includes("Alpha connection refused") && !frame.includes("investigate i"))
1196
+
1197
+ setup.mockInput.pressKey("F6")
1198
+ await setup.waitForFrame((frame) => frame.includes("MCP servers"))
1199
+ setup.mockInput.pressArrow("down")
1200
+ setup.mockInput.pressEnter()
1201
+ await setup.waitForFrame((frame) => frame.includes("Beta initialization failed") && frame.includes("investigate i"))
1202
+ setup.mockInput.pressKey("i")
1203
+ const draft = await setup.waitForFrame(
1204
+ (frame) => frame.includes("Beta initialization failed") && !frame.includes("investigate i"),
1205
+ )
1206
+
1207
+ expect(draft).not.toContain("Alpha connection refused")
1208
+ expect(created).toBe(0)
1209
+
1210
+ setup.mockInput.pressKey("c", { ctrl: true })
1211
+ await setup.waitForFrame((frame) => !frame.includes("Beta initialization failed"))
1212
+ })
1213
+
1214
+ test("completed user shell output replaces a partial live read when the final read fails", async () => {
1215
+ await using state = await tmpdir()
1216
+ const session = {
1217
+ id: "ses_shell_output",
1218
+ title: "Shell output fixture",
1219
+ projectID: "proj_test",
1220
+ location: { directory },
1221
+ cost: 0,
1222
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1223
+ time: { created: 0, updated: 0 },
1224
+ }
1225
+ const shell = {
1226
+ id: "sh_output",
1227
+ command: "echo shell-output-fixture",
1228
+ status: "running" as const,
1229
+ cwd: directory,
1230
+ shell: "/bin/sh",
1231
+ file: `${directory}/shell.out`,
1232
+ metadata: { sessionID: session.id, background: true },
1233
+ time: { started: 1 },
1234
+ }
1235
+ const partial = "first live output\n"
1236
+ const completed = `${partial}last persisted output\n`
1237
+ let finished = false
1238
+ let failedReads = 0
1239
+ await using setup = await createAppFixture({
1240
+ state: state.path,
1241
+ config: { animations: false, tabs: { mode: "off" }, session: { sidebar: "hide" } },
1242
+ args: { sessionID: session.id },
1243
+ fetch: (url) => {
1244
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
1245
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
1246
+ if (url.pathname === `/api/session/${session.id}/message`)
1247
+ return json({
1248
+ data: [
1249
+ {
1250
+ id: "msg_shell_output",
1251
+ type: "shell",
1252
+ shellID: shell.id,
1253
+ command: shell.command,
1254
+ status: "running",
1255
+ metadata: { background: true },
1256
+ time: { created: 1 },
1257
+ },
1258
+ ],
1259
+ cursor: {},
1260
+ })
1261
+ if (
1262
+ url.pathname === `/api/session/${session.id}/inbox` ||
1263
+ url.pathname === `/api/session/${session.id}/permission`
1264
+ )
1265
+ return json({ data: [] })
1266
+ if (url.pathname === "/api/shell") return json({ location: { directory }, data: finished ? [] : [shell] })
1267
+ if (url.pathname === `/api/shell/${shell.id}/output`) {
1268
+ if (finished) {
1269
+ failedReads++
1270
+ return json({ message: "Shell output unavailable" }, { status: 404 })
1271
+ }
1272
+ return json({
1273
+ location: { directory },
1274
+ data: {
1275
+ output: partial.slice(Number(url.searchParams.get("cursor") ?? 0)),
1276
+ cursor: partial.length,
1277
+ size: partial.length,
1278
+ truncated: false,
1279
+ },
1280
+ })
1281
+ }
1282
+ return undefined
1283
+ },
1284
+ })
1285
+
1286
+ const running = await setup.waitForFrame((frame) => frame.includes(partial.trim()))
1287
+ expect(running).toContain(shell.command)
1288
+ expect(running).not.toContain("Background")
1289
+
1290
+ finished = true
1291
+ setup.events.emit({
1292
+ id: "evt_shell_exited",
1293
+ created: 2,
1294
+ type: "shell.exited",
1295
+ location: { directory },
1296
+ data: { id: shell.id, status: "exited", exit: 0 },
1297
+ })
1298
+ await setup.waitFor(() => failedReads > 0)
1299
+ setup.events.emit({
1300
+ id: "evt_shell_ended",
1301
+ created: 3,
1302
+ type: "session.shell.ended",
1303
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
1304
+ data: {
1305
+ sessionID: session.id,
1306
+ shell: { ...shell, status: "exited", exit: 0, time: { started: 1, completed: 2 } },
1307
+ output: { output: completed, cursor: completed.length, size: completed.length, truncated: false },
1308
+ },
1309
+ })
1310
+ const terminal = await setup.waitForFrame((frame) => frame.includes("last persisted output"))
1311
+ expect(terminal).toContain(partial.trim())
1312
+ expect(terminal).toContain(`$ ${shell.command}`)
1313
+ expect(terminal).not.toContain("Background")
1314
+ })
1315
+
1316
+ test("new session inherits the active session model", async () => {
1317
+ const cwd = process.cwd()
1318
+ const location = { directory: cwd, project: { id: "project", directory: cwd } }
1319
+ const session = {
1320
+ id: "dummy",
1321
+ title: "Demo session",
1322
+ projectID: "project",
1323
+ location: { directory: cwd },
1324
+ agent: "build",
1325
+ model: { providerID: "provider", id: "session-model" },
1326
+ cost: 0,
1327
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1328
+ time: { created: 0, updated: 0 },
1329
+ }
1330
+ await using setup = await createAppFixture({
1331
+ width: 80,
1332
+ height: 24,
1333
+ args: { sessionID: "dummy" },
1334
+ fetch: (url) => {
1335
+ if (url.pathname === "/api/fs/list") return json({ location, data: [] })
1336
+ if (url.pathname === "/api/location") return json(location)
1337
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
1338
+ if (url.pathname === "/api/session/dummy") return json({ data: session })
1339
+ if (url.pathname === "/api/session/dummy/message") return json({ data: [], cursor: {} })
1340
+ if (url.pathname === "/api/session/dummy/inbox") return json({ data: [] })
1341
+ if (url.pathname === "/api/session/dummy/permission") return json({ data: [] })
1342
+ if (url.pathname === "/api/agent")
1343
+ return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
1344
+ if (url.pathname === "/api/provider") return json({ location, data: [{ id: "provider", name: "Provider" }] })
1345
+ if (url.pathname === "/api/model")
1346
+ return json({
1347
+ location,
1348
+ data: [
1349
+ { id: "home-model", providerID: "provider", name: "Home Model", variants: [] },
1350
+ { id: "session-model", providerID: "provider", name: "Session Model", variants: [] },
1351
+ ],
1352
+ })
1353
+ },
1354
+ })
1355
+
1356
+ await setup.waitForFrame((frame) => frame.includes("Session Model"))
1357
+ await setup.mockInput.typeText("/new")
1358
+ setup.mockInput.pressEnter()
1359
+ await Bun.sleep(50)
1360
+ await setup.renderOnce()
1361
+ const frame = setup.captureCharFrame()
1362
+ expect(frame).toContain("Session Model")
1363
+ })
1364
+
1365
+ test("keeps the prompt display stable while a new location catalog loads", async () => {
1366
+ const source = process.cwd()
1367
+ const target = path.join(path.parse(source).root, "opencode-target")
1368
+ const locationCatalog = Promise.withResolvers<void>()
1369
+ const catalog = Promise.withResolvers<void>()
1370
+ const providerCatalog = Promise.withResolvers<void>()
1371
+ const locationRequested = Promise.withResolvers<void>()
1372
+ const modelRequested = Promise.withResolvers<void>()
1373
+ await using setup = await createAppFixture({
1374
+ fetch: async (url) => {
1375
+ const requestedDirectory = url.searchParams.get("location[directory]") ?? source
1376
+ const location = {
1377
+ directory: requestedDirectory,
1378
+ project: {
1379
+ id: requestedDirectory === target ? "target" : "source",
1380
+ directory: requestedDirectory,
1381
+ canonical: requestedDirectory,
1382
+ },
1383
+ }
1384
+ if (url.pathname === "/api/location") {
1385
+ if (requestedDirectory === target) {
1386
+ locationRequested.resolve()
1387
+ await locationCatalog.promise
1388
+ }
1389
+ return json(location)
1390
+ }
1391
+ if (url.pathname === "/api/agent") {
1392
+ if (requestedDirectory === target) await catalog.promise
1393
+ return json({
1394
+ location,
1395
+ data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }],
1396
+ })
1397
+ }
1398
+ if (url.pathname === "/api/provider") {
1399
+ if (requestedDirectory === target) await providerCatalog.promise
1400
+ return json({ location, data: [{ id: "provider", name: "Provider" }] })
1401
+ }
1402
+ if (url.pathname === "/api/model") {
1403
+ if (requestedDirectory === target) {
1404
+ modelRequested.resolve()
1405
+ await catalog.promise
1406
+ }
1407
+ return json({
1408
+ location,
1409
+ data: [
1410
+ {
1411
+ id: requestedDirectory === target ? "target-model" : "source-model",
1412
+ providerID: "provider",
1413
+ name: requestedDirectory === target ? "Target Model" : "Source Model",
1414
+ variants: [],
1415
+ },
1416
+ ],
1417
+ })
1418
+ }
1419
+ return undefined
1420
+ },
1421
+ })
1422
+
1423
+ try {
1424
+ await setup.ready
1425
+ await setup.waitForFrame((frame) => frame.includes("Build · Source Model Provider"))
1426
+ const agentSpan = () =>
1427
+ setup
1428
+ .captureSpans()
1429
+ .lines.flatMap((line) => line.spans)
1430
+ .find((span) => span.text.trim() === "Build")
1431
+ const sourceAgentColor = agentSpan()?.fg.toInts()
1432
+ expect(sourceAgentColor).toBeDefined()
1433
+ await setup.mockInput.typeText(`/cd ${target}`)
1434
+ await setup.renderOnce()
1435
+ expect(setup.captureCharFrame()).toContain(`/cd ${target}`)
1436
+ setup.mockInput.pressEscape()
1437
+ setup.mockInput.pressEnter()
1438
+ await Promise.race([
1439
+ locationRequested.promise,
1440
+ Bun.sleep(2_000).then(() => {
1441
+ throw new Error("target location was not requested")
1442
+ }),
1443
+ ])
1444
+ await setup.renderOnce()
1445
+ expect(setup.captureCharFrame()).toContain(target)
1446
+
1447
+ locationCatalog.resolve()
1448
+ await Promise.race([
1449
+ modelRequested.promise,
1450
+ Bun.sleep(2_000).then(() => {
1451
+ throw new Error("target model catalog was not requested")
1452
+ }),
1453
+ ])
1454
+ await setup.renderOnce()
1455
+
1456
+ expect(setup.captureCharFrame()).toContain("Build · Source Model Provider")
1457
+ expect(agentSpan()?.fg.toInts()).toEqual(sourceAgentColor)
1458
+
1459
+ catalog.resolve()
1460
+ const resolved = await setup.waitForFrame((frame) => frame.includes("Build · Target Model provider"))
1461
+ expect(resolved).not.toContain("Source Model")
1462
+
1463
+ providerCatalog.resolve()
1464
+ await setup.waitForFrame((frame) => frame.includes("Build · Target Model Provider"))
1465
+ } finally {
1466
+ locationCatalog.resolve()
1467
+ catalog.resolve()
1468
+ providerCatalog.resolve()
1469
+ }
1470
+ })
1471
+
1472
+ test("configured app binding opens settings", async () => {
1473
+ await using setup = await createAppFixture({
1474
+ config: { animations: false, keybinds: { "opencode.settings": "f6" } },
1475
+ })
1476
+ await setup.ready
1477
+ await setup.waitForFrame((frame) => frame.includes("commands"))
1478
+
1479
+ setup.mockInput.pressKey("F6")
1480
+ const settings = await setup.waitForFrame((frame) => frame.includes("Settings"))
1481
+ expect(settings).toContain("Color mode")
1482
+ expect(settings).toContain("Animations")
1483
+ })
1484
+
1485
+ test("ctrl+c dismisses autocomplete and shell mode before exiting", async () => {
1486
+ await using setup = await createAppFixture()
1487
+ await setup.ready
1488
+ await setup.waitForFrame((frame) => frame.includes("commands"))
1489
+ await setup.mockInput.typeText("/theme")
1490
+ await setup.waitForFrame((frame) => frame.includes("Switch theme"))
1491
+
1492
+ setup.mockInput.pressKey("c", { ctrl: true })
1493
+ await setup.waitForFrame((frame) => !frame.includes("Switch theme"))
1494
+ expect(setup.renderer.isDestroyed).toBe(false)
1495
+
1496
+ await setup.mockInput.typeText("!")
1497
+ await setup.waitForFrame((frame) => frame.includes("Shell"))
1498
+ setup.mockInput.pressKey("c", { ctrl: true })
1499
+ await setup.waitForFrame((frame) => !frame.includes("Shell"))
1500
+ expect(setup.renderer.isDestroyed).toBe(false)
1501
+ })
1502
+
1503
+ test.skipIf(process.platform === "win32").each(["manual", "select"] as const)(
1504
+ "selection copy and pane management respect %s mode in the prompt and terminal pane",
1505
+ async (copy) => {
1506
+ await using state = await tmpdir()
1507
+ const setup = await createTestRenderer({ width: 100, height: 30, kittyKeyboard: true })
1508
+ await setup.renderer.setupTerminal()
1509
+ setup.renderer.start()
1510
+ const ready = Promise.withResolvers<void>()
1511
+ const session = {
1512
+ id: "dummy",
1513
+ title: "Selection fixture",
1514
+ projectID: "project",
1515
+ location: { directory },
1516
+ cost: 0,
1517
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1518
+ time: { created: 0, updated: 0 },
1519
+ }
1520
+ const pty = {
1521
+ id: "pty_fixture",
1522
+ sessionID: session.id,
1523
+ title: "Terminal",
1524
+ command: "/bin/sh",
1525
+ args: [],
1526
+ cwd: directory,
1527
+ status: "running",
1528
+ pid: 1,
1529
+ foregroundProcess: null,
1530
+ size: { cols: 48, rows: 24 },
1531
+ output: { head: 0, tail: 0 },
1532
+ }
1533
+ const input: string[] = []
1534
+ const calls = createFetch((url, request) => {
1535
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
1536
+ if (url.pathname === "/api/session/dummy") return json({ data: session })
1537
+ if (url.pathname === "/api/session/dummy/message") return json({ data: [], cursor: {} })
1538
+ if (url.pathname === "/api/session/dummy/inbox") return json({ data: [] })
1539
+ if (url.pathname === "/api/session/dummy/permission") return json({ data: [] })
1540
+ if (url.pathname === "/api/experimental/session/dummy/terminal")
1541
+ return json({ data: request.method === "POST" ? pty : [pty] })
1542
+ if (url.pathname === "/api/experimental/persistent-pty/pty_fixture/snapshot")
1543
+ return json({
1544
+ data: {
1545
+ info: pty,
1546
+ text: "alpha beta gamma",
1547
+ checkpoint: Buffer.from("alpha beta gamma").toString("base64"),
1548
+ cursor: { x: 16, y: 0 },
1549
+ },
1550
+ })
1551
+ if (url.pathname === "/api/experimental/persistent-pty/pty_fixture/connect-token")
1552
+ return json({ data: { ticket: "fixture" } })
1553
+ return undefined
1554
+ }, createEventStream())
1555
+ const server = Bun.serve({
1556
+ port: 0,
1557
+ fetch(request, server) {
1558
+ if (new URL(request.url).pathname.endsWith("/connect") && server.upgrade(request)) return undefined
1559
+ return calls.fetch(request)
1560
+ },
1561
+ websocket: {
1562
+ open(socket) {
1563
+ socket.send(JSON.stringify({ type: "attached", inputProtocol: 1, role: "controller", info: pty }))
1564
+ socket.send(JSON.stringify({ type: "replay_complete" }))
1565
+ },
1566
+ message(_socket, message) {
1567
+ const data = Buffer.from(message)
1568
+ if (data[0] === 1) input.push(data.subarray(5).toString())
1569
+ },
1570
+ },
1571
+ })
1572
+
1573
+ try {
1574
+ const { run } = await import("../src/app")
1575
+ const task = Effect.runPromise(
1576
+ run({
1577
+ app: { name: "test", version: "test", channel: "test" },
1578
+ server: { endpoint: { url: server.url.toString() } },
1579
+ config: {
1580
+ get: async () => ({
1581
+ animations: false,
1582
+ terminal: { copy },
1583
+ }),
1584
+ update: async () => ({}),
1585
+ },
1586
+ packages: { prepare: async () => ({ directory: "" }) },
1587
+ args: { sessionID: session.id },
1588
+ terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: ready.resolve }),
1589
+ log: () => {},
1590
+ }).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
1591
+ )
1592
+
1593
+ await ready.promise
1594
+ await setup.waitForFrame((frame) => frame.includes("commands"))
1595
+ await setup.mockInput.typeText("selection audit draft")
1596
+ setup.mockInput.pressKey("a", { ctrl: true, shift: true })
1597
+ expect(setup.renderer.getSelection()?.getSelectedText()).toBe("selection audit draft")
1598
+
1599
+ setup.mockInput.pressEscape()
1600
+ expect(setup.renderer.hasSelection).toBeFalse()
1601
+ expect(setup.renderer.currentFocusedEditor?.plainText).toBe("selection audit draft")
1602
+
1603
+ setup.mockInput.pressKey("c", { ctrl: true })
1604
+ await setup.waitForFrame((frame) => !frame.includes("selection audit draft"))
1605
+ expect(setup.renderer.currentFocusedEditor?.plainText).toBe("")
1606
+ expect(setup.renderer.hasSelection).toBeFalse()
1607
+ expect(setup.renderer.isDestroyed).toBeFalse()
1608
+
1609
+ await setup.mockInput.typeText("/terminal")
1610
+ await setup.waitForFrame((frame) => frame.includes("New terminal"))
1611
+ setup.mockInput.pressEnter()
1612
+ await setup.waitForFrame((frame) => frame.includes("alpha beta gamma"))
1613
+ setup.mockInput.pressKey("x", { ctrl: true })
1614
+ setup.mockInput.pressArrow("right")
1615
+ const terminal = setup.renderer.currentFocusedRenderable
1616
+ if (!(terminal instanceof EmbeddedTerminalRenderable)) throw new Error("Terminal was not focused")
1617
+ setup.renderer.startSelection(terminal, terminal.x + 6, terminal.y)
1618
+ setup.renderer.updateSelection(terminal, terminal.x + 9, terminal.y, { finishDragging: true })
1619
+ expect(setup.renderer.getSelection()?.getSelectedText()).toBe("beta")
1620
+
1621
+ setup.mockInput.pressEscape()
1622
+ expect(setup.renderer.hasSelection).toBeFalse()
1623
+ expect(terminal.hasSelection()).toBeFalse()
1624
+
1625
+ await setup.mockMouse.click(terminal.x + 6, terminal.y)
1626
+ if (copy === "select") {
1627
+ setup.renderer.updateSelection(terminal, terminal.x + 9, terminal.y, { finishDragging: true })
1628
+ expect(setup.renderer.getSelection()?.getSelectedText()).toBe("beta")
1629
+ }
1630
+ setup.mockInput.pressKey("c", { ctrl: true })
1631
+ await setup.waitFor(() => input.length > 0)
1632
+ expect(input).toEqual(["\x03"])
1633
+ expect(setup.renderer.hasSelection).toBeFalse()
1634
+ expect(setup.renderer.isDestroyed).toBeFalse()
1635
+
1636
+ setup.mockInput.pressKey("x", { ctrl: true })
1637
+ setup.mockInput.pressArrow("up")
1638
+ await setup.waitFor(() => terminal.isDestroyed)
1639
+ expect(setup.renderer.currentFocusedEditor?.plainText).toBe("")
1640
+ setup.mockInput.pressKey("x", { ctrl: true })
1641
+ setup.mockInput.pressKey("t")
1642
+ // The closed terminal can still be on the last frame, so the text alone does not mean it reopened.
1643
+ await setup.waitForFrame(
1644
+ (frame) =>
1645
+ frame.includes("alpha beta gamma") &&
1646
+ setup.renderer.currentFocusedRenderable instanceof EmbeddedTerminalRenderable,
1647
+ )
1648
+ setup.mockInput.pressKey("x", { ctrl: true })
1649
+ setup.mockInput.pressArrow("down")
1650
+ await setup.waitForFrame((frame) => frame.includes("Subagents") && frame.includes("Terminals"))
1651
+ // A failed toBeInstanceOf prints the whole renderable tree, millions of lines.
1652
+ expect(setup.renderer.currentFocusedRenderable instanceof EmbeddedTerminalRenderable).toBeFalse()
1653
+
1654
+ setup.renderer.destroy()
1655
+ await task
1656
+ } finally {
1657
+ if (!setup.renderer.isDestroyed) setup.renderer.destroy()
1658
+ await server.stop()
1659
+ }
1660
+ },
1661
+ )
1662
+
1663
+ test.each([100, 44])(
1664
+ "execution failure keeps the empty session composer and draft usable at width %s",
1665
+ async (width) => {
1666
+ await using state = await tmpdir()
1667
+ const session = {
1668
+ id: "ses_failure",
1669
+ projectID: "proj_test",
1670
+ location: { directory },
1671
+ title: "Failure fixture",
1672
+ cost: 0,
1673
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1674
+ time: { created: 1, updated: 1 },
1675
+ }
1676
+ await using setup = await createAppFixture({
1677
+ width,
1678
+ state: state.path,
1679
+ args: { sessionID: session.id },
1680
+ config: { animations: false, tabs: { mode: "off" } },
1681
+ fetch: (url) => {
1682
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
1683
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
1684
+ if (url.pathname === `/api/session/${session.id}/message`) return json({ data: [], cursor: {} })
1685
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
1686
+ return json({ data: [] })
1687
+ return undefined
1688
+ },
1689
+ })
1690
+ await setup.ready
1691
+ await setup.waitForFrame((frame) => frame.includes("commands"))
1692
+ setup.mockInput.pressKey("u", { ctrl: true })
1693
+ await setup.mockInput.typeText("Keep this draft")
1694
+ await setup.waitForFrame((frame) => frame.includes("Keep this draft"))
1695
+ setup.events.emit({
1696
+ id: "evt_execution_failed",
1697
+ created: 2,
1698
+ type: "session.execution.failed",
1699
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
1700
+ data: {
1701
+ sessionID: session.id,
1702
+ error: { type: "unknown", message: 'Plugin "broken-skills" failed during skill.transform.' },
1703
+ },
1704
+ })
1705
+ await setup.waitForFrame((frame) => frame.includes("Session failed"))
1706
+ expect(setup.captureCharFrame()).toContain("broken-skills")
1707
+ expect(setup.captureCharFrame()).toContain("skill.transform")
1708
+ expect(setup.captureCharFrame()).toContain("Keep this draft")
1709
+ expect(setup.captureCharFrame()).not.toContain("Select directory")
1710
+ await setup.mockInput.typeText(" intact")
1711
+ await setup.waitForFrame((frame) => frame.includes("Keep this draft intact"))
1712
+ },
1713
+ )
1714
+
1715
+ test.each([
1716
+ [100, true],
1717
+ [44, true],
1718
+ [100, false],
1719
+ [44, false],
1720
+ ] as const)("server plugin failures are visible at width %s (already failed: %s)", async (width, initial) => {
1721
+ await using state = await tmpdir()
1722
+ const failure: PluginInfo["state"] = {
1723
+ status: "failed",
1724
+ error: "Plugin disabled after command.transform failed. Check server logs for details.",
1725
+ ref: "err_fixture",
1726
+ }
1727
+ let inventory: PluginInfo[] = [
1728
+ {
1729
+ id: "broken",
1730
+ source: { type: "builtin" },
1731
+ features: { server: true },
1732
+ state: initial ? failure : { status: "active" },
1733
+ },
1734
+ { id: "healthy", source: { type: "builtin" }, features: { server: true }, state: { status: "active" } },
1735
+ ]
1736
+ let requests = 0
1737
+ await using setup = await createAppFixture({
1738
+ width,
1739
+ state: state.path,
1740
+ fetch: (url) => {
1741
+ if (url.pathname !== "/api/plugin") return undefined
1742
+ requests++
1743
+ return json({
1744
+ location: { directory, project: { id: "proj_test", directory, canonical: directory } },
1745
+ data: inventory,
1746
+ })
1747
+ },
1748
+ })
1749
+ await setup.ready
1750
+ await setup.waitForFrame((frame) => frame.includes("commands"))
1751
+ if (!initial) {
1752
+ expect(setup.captureCharFrame()).not.toContain("Plugin failed")
1753
+ inventory = inventory.map((plugin) => (plugin.id === "broken" ? { ...plugin, state: failure } : plugin))
1754
+ setup.events.emit({ id: "evt_failure", created: 1, type: "plugin.updated", data: {} })
1755
+ }
1756
+ await setup.waitForFrame((frame) => frame.includes("Plugin failed:") && frame.includes("broken"))
1757
+ expect(setup.captureCharFrame()).toContain("/plugins")
1758
+ expect(setup.captureCharFrame()).toContain("1 plugin failed")
1759
+
1760
+ const lines = setup.captureCharFrame().split("\n")
1761
+ const row = lines.findIndex((line) => line.includes("Open plugins"))
1762
+ expect(row).toBeGreaterThanOrEqual(0)
1763
+ const line = lines[row]
1764
+ if (!line) throw new Error("Open plugins action is missing")
1765
+ await setup.mockMouse.click(line.indexOf("Open plugins"), row)
1766
+ await setup.waitForFrame((frame) => frame.includes("ctrl+a") && frame.includes("broken"))
1767
+ expect(setup.captureCharFrame()).toContain("broken")
1768
+ expect(setup.captureCharFrame()).not.toContain("healthy")
1769
+ setup.mockInput.pressEnter()
1770
+ await setup.waitForFrame((frame) => frame.includes("Server plugin error") && frame.includes("transform failed"))
1771
+ expect(setup.captureCharFrame()).toContain("Plugin disabled")
1772
+ expect(setup.captureCharFrame()).toContain("transform failed")
1773
+ expect(setup.captureCharFrame()).toContain("err_fixture")
1774
+ setup.mockInput.pressEscape()
1775
+ await setup.waitForFrame((frame) => frame.includes("ctrl+a"))
1776
+ setup.mockInput.pressEscape()
1777
+ await setup.waitForFrame((frame) => !frame.includes("ctrl+a"))
1778
+ expect(setup.captureCharFrame()).toContain("1 plugin failed")
1779
+
1780
+ const seen = requests
1781
+ setup.events.emit({ id: "evt_repeat", created: 2, type: "plugin.updated", data: {} })
1782
+ setup.events.emit({ id: "evt_reconnect", type: "server.connected", data: {} })
1783
+ await setup.waitFor(() => requests >= seen + 2)
1784
+ await setup.flush()
1785
+ expect(setup.captureCharFrame()).not.toContain("Plugin failed:")
1786
+
1787
+ inventory = inventory.map((plugin) => ({ ...plugin, state: { status: "active" } }))
1788
+ setup.events.emit({ id: "evt_recovered", created: 3, type: "plugin.updated", data: {} })
1789
+ await setup.waitForFrame((frame) => !frame.includes("1 plugin failed"))
1790
+ inventory = inventory.map((plugin) => (plugin.id === "broken" ? { ...plugin, state: failure } : plugin))
1791
+ setup.events.emit({ id: "evt_failed_again", created: 4, type: "plugin.updated", data: {} })
1792
+ await setup.waitForFrame((frame) => frame.includes("Plugin failed:") && frame.includes("broken"))
1793
+ })
1794
+
1795
+ test("server plugin failures share one notice and use source names before an ID is known", async () => {
1796
+ await using state = await tmpdir()
1797
+ await using setup = await createAppFixture({
1798
+ state: state.path,
1799
+ fetch: (url) =>
1800
+ url.pathname === "/api/plugin"
1801
+ ? json({
1802
+ location: { directory, project: { id: "proj_test", directory, canonical: directory } },
1803
+ data: [
1804
+ {
1805
+ source: { type: "package", target: "missing-package" },
1806
+ features: {},
1807
+ state: { status: "failed", error: "Package missing" },
1808
+ },
1809
+ {
1810
+ source: { type: "local", path: "/fixture/broken.ts" },
1811
+ features: {},
1812
+ state: { status: "failed", error: "Invalid plugin" },
1813
+ },
1814
+ ],
1815
+ })
1816
+ : undefined,
1817
+ })
1818
+ await setup.ready
1819
+ await setup.waitForFrame((frame) => frame.includes("2 plugins failed"))
1820
+ expect(setup.captureCharFrame()).toContain("missing-package")
1821
+ expect(setup.captureCharFrame()).toContain("/fixture/broken.ts")
1822
+ expect(setup.captureCharFrame()).toContain("Open plugins")
1823
+ })
1824
+
1825
+ test("free usage limit offers OpenCode Go once per 24h, transitions Subscribe to Connect Go, and restores focus", async () => {
1826
+ await using state = await tmpdir()
1827
+ const baseNow = 1_700_000_000_000
1828
+ let currentNow = baseNow
1829
+ using _now = spyOn(Date, "now").mockImplementation(() => currentNow)
1830
+ const session = {
1831
+ id: "ses_free_limit",
1832
+ projectID: "proj_test",
1833
+ location: { directory },
1834
+ title: "Free limit",
1835
+ agent: "build",
1836
+ cost: 0,
1837
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1838
+ time: { created: 1, updated: 1 },
1839
+ }
1840
+ const model = { id: "big-pickle", providerID: "opencode" }
1841
+ const freeModel = {
1842
+ id: "big-pickle",
1843
+ providerID: "opencode",
1844
+ name: "Big Pickle",
1845
+ status: "active",
1846
+ cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
1847
+ capabilities: { input: ["text"], output: ["text"], reasoning: false, toolCall: true, attachment: false },
1848
+ limit: { context: 200_000, output: 8_192 },
1849
+ variants: [],
1850
+ time: { released: 1 },
1851
+ }
1852
+ const goModel = {
1853
+ id: "glm-5-go",
1854
+ providerID: "opencode-go",
1855
+ name: "GLM-5 Go",
1856
+ status: "active",
1857
+ cost: [{ input: 1, output: 2, cache: { read: 0, write: 0 } }],
1858
+ capabilities: { input: ["text"], output: ["text"], reasoning: false, toolCall: true, attachment: false },
1859
+ limit: { context: 200_000, output: 8_192 },
1860
+ variants: [],
1861
+ time: { released: 2 },
1862
+ }
1863
+ const error = {
1864
+ type: "provider.free-limit",
1865
+ message: "Free usage limit reached.",
1866
+ status: 429,
1867
+ retryAfterMs: 3_600_000,
1868
+ }
1869
+ let authorized = false
1870
+ let releaseOAuth!: () => void
1871
+ const oauthGate = new Promise<void>((resolve) => {
1872
+ releaseOAuth = resolve
1873
+ })
1874
+ const oauthRequests: unknown[] = []
1875
+ const switchedModels: unknown[] = []
1876
+ const resentPrompts: unknown[] = []
1877
+ const promptResent = Promise.withResolvers<void>()
1878
+ await using setup = await createAppFixture({
1879
+ width: 100,
1880
+ state: state.path,
1881
+ args: { sessionID: session.id },
1882
+ config: { animations: false, tabs: { mode: "off" } },
1883
+ fetch: async (url, request) => {
1884
+ const location = { directory, project: { id: "proj_test", directory, canonical: directory } }
1885
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
1886
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
1887
+ if (url.pathname === "/api/agent")
1888
+ return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
1889
+ if (url.pathname === "/api/provider")
1890
+ return json({
1891
+ location,
1892
+ data: [
1893
+ { id: "opencode", name: "OpenCode Zen" },
1894
+ ...(authorized ? [{ id: "opencode-go", integrationID: "opencode", name: "OpenCode Go" }] : []),
1895
+ ],
1896
+ })
1897
+ if (url.pathname === "/api/model")
1898
+ return json({
1899
+ location,
1900
+ data: authorized ? [goModel, freeModel] : [freeModel],
1901
+ })
1902
+ if (url.pathname === "/api/integration")
1903
+ return json({
1904
+ location,
1905
+ data: [
1906
+ {
1907
+ id: "opencode",
1908
+ name: "OpenCode Console",
1909
+ methods: [
1910
+ {
1911
+ id: "device",
1912
+ type: "oauth",
1913
+ label: "OpenCode Console account",
1914
+ form: [
1915
+ {
1916
+ key: "server",
1917
+ type: "string",
1918
+ format: "uri",
1919
+ hidden: true,
1920
+ default: "https://opencode.ai/console",
1921
+ },
1922
+ ],
1923
+ },
1924
+ { type: "key", label: "API key (service account)" },
1925
+ ],
1926
+ connections: authorized
1927
+ ? [{ type: "credential", method: "oauth", id: "cred_console", label: "Anomaly" }]
1928
+ : [],
1929
+ },
1930
+ {
1931
+ id: "opencode-go",
1932
+ name: "OpenCode Go",
1933
+ methods: [{ type: "key", label: "Enter Go API key" }],
1934
+ connections: [],
1935
+ },
1936
+ ],
1937
+ })
1938
+ if (url.pathname === "/api/integration/opencode/connect/oauth" && request.method === "POST") {
1939
+ oauthRequests.push(await request.json())
1940
+ return json({
1941
+ location,
1942
+ data: {
1943
+ attemptID: "attempt_go",
1944
+ mode: "auto",
1945
+ url: "https://opencode.ai/console/device?user_code=GOGO-1234",
1946
+ instructions: "Enter code: GOGO-1234",
1947
+ },
1948
+ })
1949
+ }
1950
+ if (url.pathname === "/api/integration/opencode/connect/oauth/attempt_go") {
1951
+ if (request.method === "DELETE") return new Response(null, { status: 204 })
1952
+ await oauthGate
1953
+ authorized = true
1954
+ return json({ location, data: { status: "complete" } })
1955
+ }
1956
+ if (url.pathname === `/api/session/${session.id}/model` && request.method === "POST") {
1957
+ switchedModels.push(await request.json())
1958
+ return new Response(null, { status: 204 })
1959
+ }
1960
+ if (url.pathname === `/api/session/${session.id}/prompt` && request.method === "POST") {
1961
+ resentPrompts.push(await request.json())
1962
+ promptResent.resolve()
1963
+ return json({ data: {} })
1964
+ }
1965
+ if (url.pathname === `/api/session/${session.id}/message`)
1966
+ return json({
1967
+ data: [
1968
+ {
1969
+ id: "msg_free_assistant",
1970
+ type: "assistant",
1971
+ agent: "build",
1972
+ model,
1973
+ content: [],
1974
+ time: { created: 2 },
1975
+ },
1976
+ { id: "msg_free_user", type: "user", text: "Refactor the parser", time: { created: 1 } },
1977
+ ],
1978
+ cursor: {},
1979
+ })
1980
+ if (url.pathname === `/api/session/${session.id}/inbox`)
1981
+ return json({
1982
+ data: [
1983
+ {
1984
+ id: "msg_queued_user",
1985
+ sessionID: session.id,
1986
+ type: "user",
1987
+ delivery: "queue",
1988
+ payload: { text: "Queued follow-up" },
1989
+ time: { created: 3 },
1990
+ },
1991
+ ],
1992
+ })
1993
+ if (url.pathname === `/api/session/${session.id}/permission`) return json({ data: [] })
1994
+ return undefined
1995
+ },
1996
+ })
1997
+ await setup.ready
1998
+ await setup.waitForFrame((frame) => frame.includes("Refactor the parser"))
1999
+ setup.events.emit({
2000
+ id: "evt_free_limit_1",
2001
+ created: baseNow,
2002
+ type: "session.step.failed",
2003
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2004
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant", error },
2005
+ })
2006
+ setup.events.emit({
2007
+ id: "evt_free_limit_exec",
2008
+ created: baseNow,
2009
+ type: "session.execution.failed",
2010
+ durable: { aggregateID: session.id, seq: 2, version: 1 },
2011
+ data: { sessionID: session.id, error },
2012
+ })
2013
+ using openSpy = spyOn(Open, "openUrl").mockResolvedValue(undefined as never)
2014
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2015
+ const upsell = setup.captureCharFrame()
2016
+ expect(upsell).toContain("OpenCode Go gives you reliable access")
2017
+ expect(upsell).toContain("▀▀▀▀ ▀▀▀▀")
2018
+ expect(upsell).toContain("opencode.ai/go")
2019
+ expect(upsell).toContain("don't show again")
2020
+ expect(upsell).toContain("dismiss")
2021
+ expect(upsell).toContain("subscribe")
2022
+ expect(upsell).not.toContain("Connect OpenCode Go")
2023
+ expect(upsell).not.toContain("Session failed")
2024
+ // Dismiss closes the modal, leaves the muted notice, and restores focus to the composer.
2025
+ setup.mockInput.pressArrow("left")
2026
+ setup.mockInput.pressEnter()
2027
+ await setup.waitForFrame((frame) => !frame.includes("Free limit reached"))
2028
+ const frame = setup.captureCharFrame()
2029
+ expect(frame).toContain("You've used today's free messages. They reset at")
2030
+ expect(frame).toContain("Upgrade to OpenCode Go → /connect · Switch model → /models")
2031
+ expect(frame).not.toContain("Error:")
2032
+ expect(frame).not.toContain("Session failed")
2033
+ // The delivered prompt (not the queued one) shows once in the transcript and once more back in the composer.
2034
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 3)
2035
+ expect(setup.captureCharFrame().split("Queued follow-up").length).toBe(2)
2036
+
2037
+ // Clear the composer (which also verifies composer focus was restored after Dismiss): a duplicate event does not re-restore.
2038
+ await Bun.sleep(10)
2039
+ setup.mockInput.pressKey("c", { ctrl: true })
2040
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 2)
2041
+ setup.events.emit({
2042
+ id: "evt_free_limit_dup",
2043
+ created: baseNow,
2044
+ type: "session.step.failed",
2045
+ durable: { aggregateID: session.id, seq: 3, version: 1 },
2046
+ data: {
2047
+ sessionID: session.id,
2048
+ assistantMessageID: "msg_free_assistant",
2049
+ error: { ...error, retryAfterMs: undefined },
2050
+ },
2051
+ })
2052
+ await setup.waitForFrame((frame) => !frame.includes("They reset at"))
2053
+ expect(setup.captureCharFrame().split("Refactor the parser").length).toBe(2)
2054
+
2055
+ // Just before 24h (86_400_000 - 1 ms) with an empty composer: recalls the next turn's prompt without reopening Free limit reached.
2056
+ currentNow = baseNow + 86_400_000 - 1
2057
+ setup.events.emit({
2058
+ id: "evt_free_limit_delivered",
2059
+ created: 4,
2060
+ type: "session.inbox.delivered",
2061
+ durable: { aggregateID: session.id, seq: 4, version: 1 },
2062
+ data: { sessionID: session.id, inboxID: "msg_queued_user" },
2063
+ })
2064
+ setup.events.emit({
2065
+ id: "evt_free_limit_2",
2066
+ created: 5,
2067
+ type: "session.step.started",
2068
+ durable: { aggregateID: session.id, seq: 5, version: 1 },
2069
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_2", agent: "build", model, started: 5 },
2070
+ })
2071
+ setup.events.emit({
2072
+ id: "evt_free_limit_3",
2073
+ created: currentNow,
2074
+ type: "session.step.failed",
2075
+ durable: { aggregateID: session.id, seq: 6, version: 1 },
2076
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_2", error },
2077
+ })
2078
+ await setup.waitForFrame(
2079
+ (frame) =>
2080
+ frame.split("You've used today's free messages").length === 3 && frame.split("Queued follow-up").length === 3,
2081
+ )
2082
+ expect(setup.captureCharFrame()).not.toContain("Free limit reached")
2083
+ expect(setup.captureCharFrame()).not.toContain("Connect OpenCode Go")
2084
+
2085
+ // Exactly at 24h (86_400_000 ms) with an empty composer: reopens Free limit reached, and Subscribe starts OpenCode device OAuth directly, selects Go, and resends the saved prompt.
2086
+ currentNow = baseNow + 86_400_000
2087
+ setup.mockInput.pressKey("c", { ctrl: true })
2088
+ await setup.waitForFrame((frame) => frame.split("Queued follow-up").length === 2)
2089
+ setup.events.emit({
2090
+ id: "evt_free_limit_4",
2091
+ created: 7,
2092
+ type: "session.step.started",
2093
+ durable: { aggregateID: session.id, seq: 7, version: 1 },
2094
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_3", agent: "build", model, started: 7 },
2095
+ })
2096
+ setup.events.emit({
2097
+ id: "evt_free_limit_5",
2098
+ created: currentNow,
2099
+ type: "session.step.failed",
2100
+ durable: { aggregateID: session.id, seq: 8, version: 1 },
2101
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_3", error },
2102
+ })
2103
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2104
+ setup.mockInput.pressEnter()
2105
+ await setup.waitForFrame((frame) => frame.includes("GOGO-1234"))
2106
+ expect(openSpy).toHaveBeenCalledWith("https://opencode.ai/go")
2107
+ expect(oauthRequests).toEqual([
2108
+ { methodID: "device", answer: { server: "https://opencode.ai/console" } },
2109
+ ])
2110
+ const connectFrame = setup.captureCharFrame()
2111
+ expect(connectFrame).toContain("OpenCode Console account")
2112
+ expect(connectFrame).not.toContain("Enter Go API key")
2113
+ expect(connectFrame).not.toContain("API key (service account)")
2114
+ releaseOAuth()
2115
+ await promptResent.promise
2116
+ await setup.waitForFrame((frame) => !frame.includes("GOGO-1234") && frame.includes("GLM-5 Go"))
2117
+ expect(switchedModels).toEqual([{ model: { providerID: "opencode-go", id: "glm-5-go" } }])
2118
+ expect(resentPrompts).toHaveLength(1)
2119
+ expect(resentPrompts[0]).toMatchObject({
2120
+ text: "Queued follow-up",
2121
+ })
2122
+ })
2123
+
2124
+ test("free usage limit Subscribe handles mid-auth/mid-sync Escape, sync failure, already-connected accounts, and Don't show again across restart", async () => {
2125
+ await using state = await tmpdir()
2126
+ const baseNow = 1_700_000_000_000
2127
+ let currentNow = baseNow
2128
+ using _now = spyOn(Date, "now").mockImplementation(() => currentNow)
2129
+ using openSpy = spyOn(Open, "openUrl").mockResolvedValue(undefined as never)
2130
+ const session = {
2131
+ id: "ses_free_limit_key",
2132
+ projectID: "proj_test",
2133
+ location: { directory },
2134
+ title: "Free limit no Go subscription",
2135
+ agent: "build",
2136
+ cost: 0,
2137
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
2138
+ time: { created: 1, updated: 1 },
2139
+ }
2140
+ const model = { id: "big-pickle", providerID: "opencode" }
2141
+ const freeModel = {
2142
+ id: "big-pickle",
2143
+ providerID: "opencode",
2144
+ name: "Big Pickle",
2145
+ status: "active",
2146
+ cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
2147
+ capabilities: { input: ["text"], output: ["text"], reasoning: false, toolCall: true, attachment: false },
2148
+ limit: { context: 200_000, output: 8_192 },
2149
+ variants: [],
2150
+ time: { released: 1 },
2151
+ }
2152
+ const goModel = {
2153
+ id: "glm-5-go",
2154
+ providerID: "opencode-go",
2155
+ name: "GLM-5 Go",
2156
+ status: "active",
2157
+ cost: [{ input: 1, output: 2, cache: { read: 0, write: 0 } }],
2158
+ capabilities: { input: ["text"], output: ["text"], reasoning: false, toolCall: true, attachment: false },
2159
+ limit: { context: 200_000, output: 8_192 },
2160
+ variants: [],
2161
+ time: { released: 2 },
2162
+ }
2163
+ const error = {
2164
+ type: "provider.free-limit",
2165
+ message: "Free usage limit reached.",
2166
+ status: 429,
2167
+ retryAfterMs: 3_600_000,
2168
+ }
2169
+ let releaseCatalog!: () => void
2170
+ const catalogGate = new Promise<void>((resolve) => {
2171
+ releaseCatalog = resolve
2172
+ })
2173
+ let oauthGate = Promise.resolve()
2174
+ let modelSyncGate = Promise.resolve()
2175
+ let onModelSyncRequest: (() => void) | undefined
2176
+ let failModelSync = false
2177
+ let connected = false
2178
+ let needsAuth = false
2179
+ let goEntitled = false
2180
+ let oauthConnectCalls = 0
2181
+ const switchedModels: unknown[] = []
2182
+ const resentPrompts: unknown[] = []
2183
+ const promptResent = Promise.withResolvers<void>()
2184
+ await using setup = await createAppFixture({
2185
+ width: 100,
2186
+ state: state.path,
2187
+ args: { sessionID: session.id },
2188
+ config: { animations: false, tabs: { mode: "off" } },
2189
+ fetch: async (url, request) => {
2190
+ const location = { directory, project: { id: "proj_test", directory, canonical: directory } }
2191
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
2192
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
2193
+ if (url.pathname === "/api/agent")
2194
+ return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
2195
+ if (url.pathname === "/api/provider")
2196
+ return json({
2197
+ location,
2198
+ data: [
2199
+ { id: "opencode", name: "OpenCode Zen" },
2200
+ ...(goEntitled ? [{ id: "opencode-go", integrationID: "opencode", name: "OpenCode Go" }] : []),
2201
+ ],
2202
+ })
2203
+ if (url.pathname === "/api/model") {
2204
+ onModelSyncRequest?.()
2205
+ await modelSyncGate
2206
+ if (failModelSync) return json({ message: "Model catalog sync failed" }, { status: 500 })
2207
+ return json({ location, data: goEntitled ? [goModel, freeModel] : [freeModel] })
2208
+ }
2209
+ if (url.pathname === "/api/integration") {
2210
+ await catalogGate
2211
+ return json({
2212
+ location,
2213
+ data: [
2214
+ {
2215
+ id: "opencode",
2216
+ name: "OpenCode Console",
2217
+ methods: [
2218
+ { id: "device", type: "oauth", label: "OpenCode Console account" },
2219
+ { type: "key", label: "API key (service account)" },
2220
+ ],
2221
+ connections: connected
2222
+ ? [
2223
+ {
2224
+ type: "credential",
2225
+ method: "oauth",
2226
+ id: "cred_console",
2227
+ label: "Personal",
2228
+ ...(needsAuth ? { status: { type: "needs_auth", message: "Session expired" } } : {}),
2229
+ },
2230
+ { type: "credential", method: "oauth", id: "cred_inactive", label: "Inactive backup" },
2231
+ ]
2232
+ : [],
2233
+ },
2234
+ ],
2235
+ })
2236
+ }
2237
+ if (url.pathname === "/api/integration/opencode/connect/oauth" && request.method === "POST") {
2238
+ oauthConnectCalls += 1
2239
+ return json({
2240
+ location,
2241
+ data: {
2242
+ attemptID: "attempt_no_go",
2243
+ mode: "auto",
2244
+ url: "https://opencode.ai/console/device?user_code=NOGO-5678",
2245
+ instructions: "Enter code: NOGO-5678",
2246
+ },
2247
+ })
2248
+ }
2249
+ if (url.pathname === "/api/integration/opencode/connect/oauth/attempt_no_go") {
2250
+ if (request.method === "DELETE") return new Response(null, { status: 204 })
2251
+ await oauthGate
2252
+ if (failModelSync) connected = true
2253
+ return json({ location, data: { status: "complete" } })
2254
+ }
2255
+ if (url.pathname === `/api/session/${session.id}/model` && request.method === "POST") {
2256
+ switchedModels.push(await request.json())
2257
+ return new Response(null, { status: 204 })
2258
+ }
2259
+ if (url.pathname === `/api/session/${session.id}/prompt` && request.method === "POST") {
2260
+ resentPrompts.push(await request.json())
2261
+ promptResent.resolve()
2262
+ return json({ data: {} })
2263
+ }
2264
+ if (url.pathname === `/api/session/${session.id}/message`)
2265
+ return json({
2266
+ data: [
2267
+ {
2268
+ id: "msg_free_assistant",
2269
+ type: "assistant",
2270
+ agent: "build",
2271
+ model,
2272
+ content: [],
2273
+ time: { created: 2 },
2274
+ },
2275
+ { id: "msg_free_user", type: "user", text: "Refactor the parser", time: { created: 1 } },
2276
+ ],
2277
+ cursor: {},
2278
+ })
2279
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
2280
+ return json({ data: [] })
2281
+ return undefined
2282
+ },
2283
+ })
2284
+ await setup.ready
2285
+ await setup.waitForFrame((frame) => frame.includes("Refactor the parser"))
2286
+
2287
+ // 1a. Escape mid-auth: cancelling while oauth.status is in flight must not select a model or resubmit the prompt.
2288
+ let releaseMidAuth!: () => void
2289
+ oauthGate = new Promise<void>((resolve) => {
2290
+ releaseMidAuth = resolve
2291
+ })
2292
+ goEntitled = true
2293
+ setup.events.emit({
2294
+ id: "evt_free_limit_mid_auth",
2295
+ created: baseNow,
2296
+ type: "session.step.failed",
2297
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2298
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant", error },
2299
+ })
2300
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2301
+ setup.mockInput.pressEnter()
2302
+ expect(openSpy).toHaveBeenCalledWith("https://opencode.ai/go")
2303
+ await setup.waitForFrame((frame) => frame.includes("Connect an integration"))
2304
+ releaseCatalog()
2305
+ await setup.waitForFrame((frame) => frame.includes("Waiting for authorization…"))
2306
+ setup.mockInput.pressEscape()
2307
+ await setup.waitForFrame((frame) => !frame.includes("Waiting for authorization…"))
2308
+ releaseMidAuth()
2309
+ await waitForGoUpsellConnect()
2310
+ expect(switchedModels).toHaveLength(0)
2311
+ expect(resentPrompts).toHaveLength(0)
2312
+ expect(setup.captureCharFrame().split("Refactor the parser").length).toBe(3)
2313
+
2314
+ // 1b. Escape mid-sync: cancelling while model sync is awaited must not select a model or resubmit the prompt.
2315
+ currentNow = baseNow + 86_400_000
2316
+ oauthGate = Promise.resolve()
2317
+ let releaseMidSync!: () => void
2318
+ const midSyncStarted = Promise.withResolvers<void>()
2319
+ onModelSyncRequest = () => midSyncStarted.resolve()
2320
+ modelSyncGate = new Promise<void>((resolve) => {
2321
+ releaseMidSync = resolve
2322
+ })
2323
+ await setup.mockInput.pressKey("c", { ctrl: true })
2324
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 2)
2325
+ setup.events.emit({
2326
+ id: "evt_free_limit_mid_sync_start",
2327
+ created: 3,
2328
+ type: "session.step.started",
2329
+ durable: { aggregateID: session.id, seq: 2, version: 1 },
2330
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_2", agent: "build", model, started: 3 },
2331
+ })
2332
+ setup.events.emit({
2333
+ id: "evt_free_limit_mid_sync_fail",
2334
+ created: currentNow,
2335
+ type: "session.step.failed",
2336
+ durable: { aggregateID: session.id, seq: 3, version: 1 },
2337
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_2", error },
2338
+ })
2339
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2340
+ setup.mockInput.pressEnter()
2341
+ await setup.waitForFrame((frame) => frame.includes("Waiting for authorization…"))
2342
+ await midSyncStarted.promise
2343
+ setup.mockInput.pressEscape()
2344
+ await setup.waitForFrame((frame) => !frame.includes("Waiting for authorization…"))
2345
+ releaseMidSync()
2346
+ await waitForGoUpsellConnect()
2347
+ onModelSyncRequest = undefined
2348
+ expect(switchedModels).toHaveLength(0)
2349
+ expect(resentPrompts).toHaveLength(0)
2350
+ expect(setup.captureCharFrame().split("Refactor the parser").length).toBe(3)
2351
+
2352
+ // 2. Model-sync rejection: catches the failure, closes "Waiting for authorization…", shows the error, and keeps the recalled prompt.
2353
+ currentNow = baseNow + 2 * 86_400_000
2354
+ modelSyncGate = Promise.resolve()
2355
+ failModelSync = true
2356
+ await setup.mockInput.pressKey("c", { ctrl: true })
2357
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 2)
2358
+ setup.events.emit({
2359
+ id: "evt_free_limit_sync_err_start",
2360
+ created: 5,
2361
+ type: "session.step.started",
2362
+ durable: { aggregateID: session.id, seq: 4, version: 1 },
2363
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_3", agent: "build", model, started: 5 },
2364
+ })
2365
+ setup.events.emit({
2366
+ id: "evt_free_limit_sync_err_fail",
2367
+ created: currentNow,
2368
+ type: "session.step.failed",
2369
+ durable: { aggregateID: session.id, seq: 5, version: 1 },
2370
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_3", error },
2371
+ })
2372
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2373
+ setup.mockInput.pressEnter()
2374
+ await setup.waitForFrame(
2375
+ (frame) => !frame.includes("Waiting for authorization…") && frame.includes("UnexpectedStatus: 500"),
2376
+ )
2377
+ expect(switchedModels).toHaveLength(0)
2378
+ expect(resentPrompts).toHaveLength(0)
2379
+ expect(setup.captureCharFrame().split("Refactor the parser").length).toBe(3)
2380
+
2381
+ // 3a. Expired/needs_auth active credential (even with a status-free inactive backup): refresh detects needs_auth and routes to device sign-in without submitting.
2382
+ failModelSync = false
2383
+ goEntitled = true
2384
+ connected = true
2385
+ needsAuth = true
2386
+ let releaseNeedsAuthOAuth!: () => void
2387
+ oauthGate = new Promise<void>((resolve) => {
2388
+ releaseNeedsAuthOAuth = resolve
2389
+ })
2390
+ currentNow = baseNow + 3 * 86_400_000
2391
+ await setup.mockInput.pressKey("c", { ctrl: true })
2392
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 2)
2393
+ setup.events.emit({
2394
+ id: "evt_free_limit_expired_start",
2395
+ created: 6,
2396
+ type: "session.step.started",
2397
+ durable: { aggregateID: session.id, seq: 6, version: 1 },
2398
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_expired", agent: "build", model, started: 6 },
2399
+ })
2400
+ setup.events.emit({
2401
+ id: "evt_free_limit_expired_fail",
2402
+ created: currentNow,
2403
+ type: "session.step.failed",
2404
+ durable: { aggregateID: session.id, seq: 7, version: 1 },
2405
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_expired", error },
2406
+ })
2407
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2408
+ const oauthCallsBeforeExpired = oauthConnectCalls
2409
+ setup.mockInput.pressEnter()
2410
+ await setup.waitForFrame((frame) => frame.includes("Waiting for authorization…") && frame.includes("NOGO-5678"))
2411
+ expect(oauthConnectCalls).toBe(oauthCallsBeforeExpired + 1)
2412
+ expect(switchedModels).toHaveLength(0)
2413
+ expect(resentPrompts).toHaveLength(0)
2414
+ // Complete sign-in so the refreshed active credential becomes valid again, then cancel before testing already-connected.
2415
+ setup.mockInput.pressEscape()
2416
+ await setup.waitForFrame((frame) => !frame.includes("Waiting for authorization…"))
2417
+ releaseNeedsAuthOAuth()
2418
+ await waitForGoUpsellConnect()
2419
+
2420
+ // 3b. Cached active credential with needs_auth (and status-free inactive backup): goes straight to device sign-in, then once re-authenticated without Go lands on /models.
2421
+ oauthGate = Promise.resolve()
2422
+ goEntitled = false
2423
+ currentNow = baseNow + 4 * 86_400_000
2424
+ await setup.mockInput.pressKey("c", { ctrl: true })
2425
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 2)
2426
+ setup.events.emit({
2427
+ id: "evt_free_limit_no_go_start",
2428
+ created: 7,
2429
+ type: "session.step.started",
2430
+ durable: { aggregateID: session.id, seq: 8, version: 1 },
2431
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_4", agent: "build", model, started: 7 },
2432
+ })
2433
+ setup.events.emit({
2434
+ id: "evt_free_limit_no_go_fail",
2435
+ created: currentNow,
2436
+ type: "session.step.failed",
2437
+ durable: { aggregateID: session.id, seq: 9, version: 1 },
2438
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_4", error },
2439
+ })
2440
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2441
+ needsAuth = false
2442
+ const oauthCallsBeforeCachedExpired = oauthConnectCalls
2443
+ setup.mockInput.pressEnter()
2444
+ await setup.waitForFrame((frame) => frame.includes("Select model") && frame.includes("Big Pickle"))
2445
+ expect(oauthConnectCalls).toBe(oauthCallsBeforeCachedExpired + 1)
2446
+ setup.mockInput.pressEscape()
2447
+ await setup.waitForFrame((frame) => !frame.includes("Select model"))
2448
+
2449
+ // 3c. Already-connected valid account with Go entitlement: skips device OAuth, refreshes catalog, selects Go, and resends the prompt.
2450
+ const oauthCallsBeforeAlreadyConnected = oauthConnectCalls
2451
+ goEntitled = true
2452
+ currentNow = baseNow + 5 * 86_400_000
2453
+ await setup.mockInput.pressKey("c", { ctrl: true })
2454
+ await setup.waitForFrame((frame) => frame.split("Refactor the parser").length === 2)
2455
+ setup.events.emit({
2456
+ id: "evt_free_limit_already_go_start",
2457
+ created: 9,
2458
+ type: "session.step.started",
2459
+ durable: { aggregateID: session.id, seq: 10, version: 1 },
2460
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_5", agent: "build", model, started: 9 },
2461
+ })
2462
+ setup.events.emit({
2463
+ id: "evt_free_limit_already_go_fail",
2464
+ created: currentNow,
2465
+ type: "session.step.failed",
2466
+ durable: { aggregateID: session.id, seq: 11, version: 1 },
2467
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_5", error },
2468
+ })
2469
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2470
+ setup.mockInput.pressEnter()
2471
+ await promptResent.promise
2472
+ await setup.waitForFrame((frame) => !frame.includes("Free limit reached") && frame.includes("GLM-5 Go"))
2473
+ expect(oauthConnectCalls).toBe(oauthCallsBeforeAlreadyConnected)
2474
+ expect(switchedModels).toEqual([{ model: { providerID: "opencode-go", id: "glm-5-go" } }])
2475
+ expect(resentPrompts).toHaveLength(1)
2476
+ expect(resentPrompts[0]).toMatchObject({ text: "Refactor the parser" })
2477
+
2478
+ // Advance past 24h, trigger again, and choose "don't show again".
2479
+ currentNow = baseNow + 6 * 86_400_000
2480
+ setup.events.emit({
2481
+ id: "evt_free_limit_key_2",
2482
+ created: 11,
2483
+ type: "session.step.started",
2484
+ durable: { aggregateID: session.id, seq: 12, version: 1 },
2485
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_6", agent: "build", model, started: 11 },
2486
+ })
2487
+ setup.events.emit({
2488
+ id: "evt_free_limit_key_3",
2489
+ created: currentNow,
2490
+ type: "session.step.failed",
2491
+ durable: { aggregateID: session.id, seq: 13, version: 1 },
2492
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_6", error },
2493
+ })
2494
+ await setup.waitForFrame((frame) => frame.includes("Free limit reached"))
2495
+ setup.mockInput.pressArrow("right")
2496
+ setup.mockInput.pressEnter()
2497
+ await setup.waitForFrame((frame) => !frame.includes("Free limit reached"))
2498
+ await Bun.sleep(30)
2499
+
2500
+ // Restart against the same state directory past another 48h: fresh in-memory store still respects persisted dontShow.
2501
+ currentNow = baseNow + 8 * 86_400_000
2502
+ await using restarted = await createAppFixture({
2503
+ width: 100,
2504
+ state: state.path,
2505
+ args: { sessionID: session.id },
2506
+ config: { animations: false, tabs: { mode: "off" } },
2507
+ fetch: (url) => {
2508
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
2509
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
2510
+ if (url.pathname === "/api/integration")
2511
+ return json({
2512
+ location: { directory, project: { id: "proj_test", directory, canonical: directory } },
2513
+ data: [{ id: "opencode-go", name: "OpenCode Go", methods: [{ type: "key" }], connections: [] }],
2514
+ })
2515
+ if (url.pathname === `/api/session/${session.id}/message`)
2516
+ return json({
2517
+ data: [
2518
+ {
2519
+ id: "msg_free_assistant_3",
2520
+ type: "assistant",
2521
+ agent: "build",
2522
+ model,
2523
+ content: [],
2524
+ time: { created: 8 },
2525
+ },
2526
+ { id: "msg_free_user", type: "user", text: "Refactor the parser", time: { created: 1 } },
2527
+ ],
2528
+ cursor: {},
2529
+ })
2530
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
2531
+ return json({ data: [] })
2532
+ return undefined
2533
+ },
2534
+ })
2535
+ await restarted.ready
2536
+ await restarted.waitForFrame((frame) => frame.includes("Refactor the parser"))
2537
+ restarted.events.emit({
2538
+ id: "evt_free_limit_key_restart",
2539
+ created: currentNow,
2540
+ type: "session.step.failed",
2541
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2542
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant_3", error },
2543
+ })
2544
+ await restarted.waitForFrame((frame) => frame.includes("You've used today's free messages. They reset at"))
2545
+ await Bun.sleep(30)
2546
+ await restarted.renderOnce()
2547
+ expect(restarted.captureCharFrame()).not.toContain("Free limit reached")
2548
+ })
2549
+
2550
+ test("free usage limit claims suppression atomically across two TUI instances and protects typing drafts", async () => {
2551
+ await using state = await tmpdir()
2552
+ const session = {
2553
+ id: "ses_free_limit_race",
2554
+ projectID: "proj_test",
2555
+ location: { directory },
2556
+ title: "Free limit race",
2557
+ cost: 0,
2558
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
2559
+ time: { created: 1, updated: 1 },
2560
+ }
2561
+ const model = { id: "big-pickle", providerID: "opencode" }
2562
+ const error = {
2563
+ type: "provider.free-limit",
2564
+ message: "Free usage limit reached.",
2565
+ status: 429,
2566
+ retryAfterMs: 3_600_000,
2567
+ }
2568
+ const fetch = (url: URL) => {
2569
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
2570
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
2571
+ if (url.pathname === "/api/integration")
2572
+ return json({
2573
+ location: { directory, project: { id: "proj_test", directory, canonical: directory } },
2574
+ data: [
2575
+ {
2576
+ id: "opencode-go",
2577
+ name: "OpenCode Go",
2578
+ methods: [{ id: "device", type: "oauth", label: "Sign in with your OpenCode account" }, { type: "key" }],
2579
+ connections: [],
2580
+ },
2581
+ ],
2582
+ })
2583
+ if (url.pathname === `/api/session/${session.id}/message`)
2584
+ return json({
2585
+ data: [
2586
+ {
2587
+ id: "msg_free_assistant",
2588
+ type: "assistant",
2589
+ agent: "build",
2590
+ model,
2591
+ content: [],
2592
+ time: { created: 2 },
2593
+ },
2594
+ { id: "msg_free_user", type: "user", text: "Refactor the parser", time: { created: 1 } },
2595
+ ],
2596
+ cursor: {},
2597
+ })
2598
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
2599
+ return json({ data: [] })
2600
+ return undefined
2601
+ }
2602
+ await using first = await createAppFixture({
2603
+ width: 100,
2604
+ state: state.path,
2605
+ args: { sessionID: session.id },
2606
+ config: { animations: false, tabs: { mode: "off" } },
2607
+ fetch,
2608
+ })
2609
+ await using second = await createAppFixture({
2610
+ width: 100,
2611
+ state: state.path,
2612
+ args: { sessionID: session.id },
2613
+ config: { animations: false, tabs: { mode: "off" } },
2614
+ fetch,
2615
+ })
2616
+ await Promise.all([first.ready, second.ready])
2617
+ await Promise.all([
2618
+ first.waitForFrame((frame) => frame.includes("Refactor the parser")),
2619
+ second.waitForFrame((frame) => frame.includes("Refactor the parser")),
2620
+ ])
2621
+ // Emit concurrently in both processes: only one claims the 24h window and opens the modal.
2622
+ const event = {
2623
+ id: "evt_free_limit_race_1",
2624
+ created: 3,
2625
+ type: "session.step.failed" as const,
2626
+ durable: { aggregateID: session.id, seq: 1, version: 1 as const },
2627
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant", error },
2628
+ }
2629
+ first.events.emit(event)
2630
+ second.events.emit(event)
2631
+ await Promise.all([
2632
+ first.waitForFrame((frame) => frame.includes("You've used today's free messages. They reset at")),
2633
+ second.waitForFrame((frame) => frame.includes("You've used today's free messages. They reset at")),
2634
+ ])
2635
+ await first.waitForFrame(
2636
+ () =>
2637
+ first.captureCharFrame().includes("Free limit reached") ||
2638
+ second.captureCharFrame().includes("Free limit reached"),
2639
+ )
2640
+ await Bun.sleep(30)
2641
+ await Promise.all([first.renderOnce(), second.renderOnce()])
2642
+ const opened = [first.captureCharFrame(), second.captureCharFrame()].filter((frame) =>
2643
+ frame.includes("Free limit reached"),
2644
+ )
2645
+ expect(opened).toHaveLength(1)
2646
+
2647
+ // Typing draft protection: does not overwrite a draft or open Free limit reached while typing.
2648
+ await using typingState = await tmpdir()
2649
+ await using typing = await createAppFixture({
2650
+ width: 100,
2651
+ state: typingState.path,
2652
+ args: { sessionID: session.id },
2653
+ config: { animations: false, tabs: { mode: "off" } },
2654
+ fetch,
2655
+ })
2656
+ await typing.ready
2657
+ await typing.waitForFrame((frame) => frame.includes("Refactor the parser"))
2658
+ await typing.mockInput.typeText("Draft in progress")
2659
+ await typing.waitForFrame((frame) => frame.includes("Draft in progress"))
2660
+ typing.events.emit(event)
2661
+ await typing.waitForFrame((frame) => frame.includes("You've used today's free messages. They reset at"))
2662
+ const frame = typing.captureCharFrame()
2663
+ expect(frame).toContain("Draft in progress")
2664
+ expect(frame.split("Refactor the parser").length).toBe(2)
2665
+ expect(frame).not.toContain("Free limit reached")
2666
+ expect(frame).not.toContain("Connect OpenCode Go")
2667
+ })
2668
+
2669
+ test("Go usage limit restores the prompt and explains the limit with its reset time instead of an error", async () => {
2670
+ await using state = await tmpdir()
2671
+ const session = {
2672
+ id: "ses_go_limit",
2673
+ projectID: "proj_test",
2674
+ location: { directory },
2675
+ title: "Go limit",
2676
+ cost: 0,
2677
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
2678
+ time: { created: 1, updated: 1 },
2679
+ }
2680
+ const error = {
2681
+ type: "provider.go-limit",
2682
+ message: "OpenCode Go 5 hour usage limit reached.",
2683
+ status: 429,
2684
+ response: {
2685
+ body: JSON.stringify({
2686
+ type: "error",
2687
+ error: { type: "GoUsageLimitError", message: "Go usage limit exceeded" },
2688
+ metadata: { workspace: "wrk_go_limit", limitName: "5 hour" },
2689
+ }),
2690
+ },
2691
+ retryAfterMs: 3_600_000,
2692
+ }
2693
+ await using setup = await createAppFixture({
2694
+ width: 100,
2695
+ state: state.path,
2696
+ args: { sessionID: session.id },
2697
+ config: { animations: false, tabs: { mode: "off" } },
2698
+ fetch: (url) => {
2699
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
2700
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
2701
+ if (url.pathname === `/api/session/${session.id}/message`)
2702
+ return json({
2703
+ data: [
2704
+ {
2705
+ id: "msg_go_assistant",
2706
+ type: "assistant",
2707
+ agent: "build",
2708
+ model: { id: "glm-5-go", providerID: "opencode-go" },
2709
+ content: [],
2710
+ time: { created: 2 },
2711
+ },
2712
+ { id: "msg_go_user", type: "user", text: "Refactor the parser", time: { created: 1 } },
2713
+ ],
2714
+ cursor: {},
2715
+ })
2716
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
2717
+ return json({ data: [] })
2718
+ return undefined
2719
+ },
2720
+ })
2721
+ await setup.ready
2722
+ await setup.waitForFrame((frame) => frame.includes("Refactor the parser"))
2723
+ setup.events.emit({
2724
+ id: "evt_go_limit_1",
2725
+ created: 3,
2726
+ type: "session.step.failed",
2727
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2728
+ data: { sessionID: session.id, assistantMessageID: "msg_go_assistant", error },
2729
+ })
2730
+ await setup.waitForFrame(
2731
+ (frame) =>
2732
+ frame.includes("OpenCode Go 5 hour usage limit reached") &&
2733
+ frame.includes("Resets ") &&
2734
+ frame.split("Refactor the parser").length === 3,
2735
+ )
2736
+ const frame = setup.captureCharFrame()
2737
+ expect(frame).toContain("Switch to a free model with")
2738
+ expect(frame).toContain("https://opencode.ai/console/wrk_go_limit/go")
2739
+ expect(frame).not.toContain("Error:")
2740
+ expect(frame).not.toContain("Free limit reached")
2741
+ })
2742
+
2743
+ test("free usage limit modal manages animation FPS and adapts to 44x24 and 60x12 terminals", async () => {
2744
+ const session = {
2745
+ id: "ses_free_limit_anim",
2746
+ projectID: "proj_test",
2747
+ location: { directory },
2748
+ title: "Free limit anim",
2749
+ cost: 0,
2750
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
2751
+ time: { created: 1, updated: 1 },
2752
+ }
2753
+ const model = { id: "big-pickle", providerID: "opencode" }
2754
+ const error = {
2755
+ type: "provider.free-limit",
2756
+ message: "Free usage limit reached.",
2757
+ status: 429,
2758
+ retryAfterMs: 3_600_000,
2759
+ }
2760
+ const fetch = (url: URL) => {
2761
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
2762
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
2763
+ if (url.pathname === `/api/session/${session.id}/message`)
2764
+ return json({
2765
+ data: [
2766
+ {
2767
+ id: "msg_free_assistant",
2768
+ type: "assistant",
2769
+ agent: "build",
2770
+ model,
2771
+ content: [],
2772
+ time: { created: 2 },
2773
+ },
2774
+ { id: "msg_free_user", type: "user", text: "Refactor the parser", time: { created: 1 } },
2775
+ ],
2776
+ cursor: {},
2777
+ })
2778
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
2779
+ return json({ data: [] })
2780
+ return undefined
2781
+ }
2782
+ const findArt = (node: Renderable): GoUpsellArtRenderable | undefined => {
2783
+ if (node instanceof GoUpsellArtRenderable) return node
2784
+ for (const child of node.getChildren()) {
2785
+ const found = findArt(child)
2786
+ if (found) return found
2787
+ }
2788
+ return undefined
2789
+ }
2790
+
2791
+ await using animState = await tmpdir()
2792
+ await using anim = await createAppFixture({
2793
+ width: 100,
2794
+ height: 30,
2795
+ state: animState.path,
2796
+ args: { sessionID: session.id },
2797
+ config: { animations: true, tabs: { mode: "off" } },
2798
+ fetch,
2799
+ })
2800
+ await anim.ready
2801
+ await anim.waitForFrame((frame) => frame.includes("Refactor the parser"))
2802
+ const initialTargetFps = anim.renderer.targetFps
2803
+ const initialMaxFps = anim.renderer.maxFps
2804
+ const initialLive = anim.renderer.liveRequestCount
2805
+ anim.events.emit({
2806
+ id: "evt_free_limit_anim_1",
2807
+ created: 3,
2808
+ type: "session.step.failed",
2809
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2810
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant", error },
2811
+ })
2812
+ await anim.waitForFrame((frame) => frame.includes("Free limit reached"))
2813
+ const art = findArt(anim.renderer.root)
2814
+ expect(art).toBeDefined()
2815
+ expect(art!.animationFps).toBe(30)
2816
+ expect(art!.isDestroyed).toBe(false)
2817
+ // The art ticks at 30 fps by itself; the rest of the screen keeps the renderer's rate.
2818
+ expect(anim.renderer.targetFps).toBe(initialTargetFps)
2819
+ expect(anim.renderer.maxFps).toBe(initialMaxFps)
2820
+ // Toggling animate off stops the art's ticks; toggling back on restarts them.
2821
+ art!.animate = false
2822
+ expect(art!.animationFps).toBeUndefined()
2823
+ art!.animate = true
2824
+ expect(art!.animationFps).toBe(30)
2825
+ // Closing the modal destroys the art renderable.
2826
+ anim.mockInput.pressEscape()
2827
+ await anim.waitForFrame((frame) => !frame.includes("Free limit reached"))
2828
+ expect(art!.isDestroyed).toBe(true)
2829
+ expect(findArt(anim.renderer.root)).toBeUndefined()
2830
+ expect(anim.renderer.liveRequestCount).toBe(initialLive)
2831
+
2832
+ // Compact sizes: 44x24 (narrow, stacked buttons) and 60x12 (short, scrollable body).
2833
+ for (const [width, height] of [
2834
+ [44, 24],
2835
+ [60, 12],
2836
+ ] as const) {
2837
+ await using compactState = await tmpdir()
2838
+ await using compact = await createAppFixture({
2839
+ width,
2840
+ height,
2841
+ state: compactState.path,
2842
+ args: { sessionID: session.id },
2843
+ config: { animations: true, tabs: { mode: "off" } },
2844
+ fetch,
2845
+ })
2846
+ await compact.ready
2847
+ await compact.waitForFrame((frame) => frame.includes("Refactor the parser"))
2848
+ compact.events.emit({
2849
+ id: `evt_free_limit_${width}x${height}`,
2850
+ created: 3,
2851
+ type: "session.step.failed",
2852
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2853
+ data: { sessionID: session.id, assistantMessageID: "msg_free_assistant", error },
2854
+ })
2855
+ await compact.waitForFrame((frame) => frame.includes("Free limit reached"))
2856
+ const frame = compact.captureCharFrame()
2857
+ expect(frame).toContain("Free limit reached")
2858
+ expect(frame).toContain("don't show again")
2859
+ expect(frame).toContain("dismiss")
2860
+ expect(frame).toContain("subscribe")
2861
+ expect(findArt(compact.renderer.root)).toBeUndefined()
2862
+ // Locate "dismiss" in the rendered frame and click it with the mouse.
2863
+ const lines = frame.split("\n")
2864
+ const row = lines.findIndex((line) => line.includes("dismiss"))
2865
+ expect(row).toBeGreaterThanOrEqual(0)
2866
+ const col = lines[row]!.indexOf("dismiss") + 2
2867
+ await compact.mockMouse.click(col, row)
2868
+ await compact.waitForFrame((next) => !next.includes("Free limit reached"))
2869
+ }
2870
+ })
2871
+
2872
+ test.each([44, 100])(
2873
+ "retry countdown updates and clears with the retry lifecycle at width %s",
2874
+ async (width) => {
2875
+ await using state = await tmpdir()
2876
+ const session = {
2877
+ id: "ses_countdown",
2878
+ projectID: "proj_test",
2879
+ location: { directory },
2880
+ title: "Retry countdown",
2881
+ cost: 0,
2882
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
2883
+ time: { created: 1, updated: 1 },
2884
+ }
2885
+ const model = { id: "model", providerID: "provider" }
2886
+ const error = { type: "provider.transport" as const, message: "Provider unavailable" }
2887
+ await using setup = await createAppFixture({
2888
+ width,
2889
+ state: state.path,
2890
+ args: { sessionID: session.id },
2891
+ config: { animations: false, tabs: { mode: "off" } },
2892
+ fetch: (url) => {
2893
+ if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
2894
+ if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
2895
+ if (url.pathname === `/api/session/${session.id}/message`)
2896
+ return json({
2897
+ data: [
2898
+ {
2899
+ id: "msg_countdown",
2900
+ type: "assistant",
2901
+ agent: "build",
2902
+ model,
2903
+ content: [],
2904
+ error,
2905
+ retry: { attempt: 2, at: Date.now() + 2_500, error },
2906
+ time: { created: 1 },
2907
+ },
2908
+ ],
2909
+ cursor: {},
2910
+ })
2911
+ if ([`/api/session/${session.id}/inbox`, `/api/session/${session.id}/permission`].includes(url.pathname))
2912
+ return json({ data: [] })
2913
+ return undefined
2914
+ },
2915
+ })
2916
+ await setup.ready
2917
+ await setup.waitForFrame((frame) => frame.includes("Retrying in 3s"))
2918
+ expect(setup.captureCharFrame()).toContain("attempt 2")
2919
+ expect(setup.captureCharFrame()).toContain("Provider unavailable")
2920
+ expect(setup.captureCharFrame()).not.toContain("Error:")
2921
+ await setup.waitForFrame((frame) => frame.includes("Retrying in 2s"), { maxPasses: 200 })
2922
+ await setup.waitForFrame((frame) => frame.includes("Retrying in 1s"), { maxPasses: 200 })
2923
+ await setup.waitForFrame((frame) => frame.includes("Retry due"), { maxPasses: 200 })
2924
+ expect(setup.captureCharFrame()).not.toContain("in 0s")
2925
+
2926
+ setup.events.emit({
2927
+ id: "evt_countdown_rescheduled",
2928
+ created: 2,
2929
+ type: "session.retry.scheduled",
2930
+ durable: { aggregateID: session.id, seq: 1, version: 1 },
2931
+ data: { sessionID: session.id, assistantMessageID: "msg_countdown", attempt: 3, at: Date.now() + 10_500, error },
2932
+ })
2933
+ await setup.waitForFrame((frame) => frame.includes("Retrying in 11s") && frame.includes("attempt 3"))
2934
+ setup.events.emit({
2935
+ id: "evt_countdown_started",
2936
+ created: 3,
2937
+ type: "session.step.started",
2938
+ durable: { aggregateID: session.id, seq: 2, version: 1 },
2939
+ data: { sessionID: session.id, assistantMessageID: "msg_countdown", agent: "build", model, started: 3 },
2940
+ })
2941
+ await setup.waitForFrame((frame) => !frame.includes("Retrying") && !frame.includes("Retry due"))
2942
+
2943
+ setup.events.emit({
2944
+ id: "evt_countdown_expired",
2945
+ created: 4,
2946
+ type: "session.retry.scheduled",
2947
+ durable: { aggregateID: session.id, seq: 3, version: 1 },
2948
+ data: { sessionID: session.id, assistantMessageID: "msg_countdown", attempt: 4, at: Date.now() - 1_000, error },
2949
+ })
2950
+ await setup.waitForFrame((frame) => frame.includes("Retry due") && frame.includes("attempt 4"))
2951
+ expect(setup.captureCharFrame()).not.toContain("in -")
2952
+ setup.events.emit({
2953
+ id: "evt_countdown_interrupted",
2954
+ created: 5,
2955
+ type: "session.execution.interrupted",
2956
+ durable: { aggregateID: session.id, seq: 4, version: 1 },
2957
+ data: { sessionID: session.id, reason: "shutdown" },
2958
+ })
2959
+ await setup.waitForFrame((frame) => !frame.includes("Retrying") && !frame.includes("Retry due"))
2960
+ },
2961
+ 15_000,
2962
+ )