@alumbwe/anvil 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (529) hide show
  1. package/README.md +84 -0
  2. package/bin/anvil +2 -0
  3. package/bin/tree-sitter.wasm +0 -0
  4. package/package.json +67 -0
  5. package/src/__tests__/README.md +256 -0
  6. package/src/__tests__/bash-mode.test.ts +442 -0
  7. package/src/__tests__/cli-args.test.ts +181 -0
  8. package/src/__tests__/cli-harness.test.ts +52 -0
  9. package/src/__tests__/e2e/first-time-login.test.ts +173 -0
  10. package/src/__tests__/e2e/logout-relogin-flow.test.ts +110 -0
  11. package/src/__tests__/e2e/returning-user-auth.test.ts +113 -0
  12. package/src/__tests__/e2e-cli.test.ts +183 -0
  13. package/src/__tests__/helpers/launcher-disconnect-fixture.cjs +176 -0
  14. package/src/__tests__/helpers/mock-api-client.ts +64 -0
  15. package/src/__tests__/helpers/renderer-cleanup-fixture.tsx +89 -0
  16. package/src/__tests__/helpers/terminal-watchdog-fixture.ts +75 -0
  17. package/src/__tests__/home-directory-detection.test.ts +213 -0
  18. package/src/__tests__/integration/api-integration.test.ts +288 -0
  19. package/src/__tests__/integration/credentials-storage.test.ts +486 -0
  20. package/src/__tests__/integration/local-agents.test.ts +1187 -0
  21. package/src/__tests__/integration/login-flow-instrumentation.test.ts +134 -0
  22. package/src/__tests__/integration/login-polling-working.test.ts +285 -0
  23. package/src/__tests__/integration/queue-editing.test.tsx +261 -0
  24. package/src/__tests__/integration/usage-refresh-on-completion.test.ts +168 -0
  25. package/src/__tests__/integration-tmux.test.ts +188 -0
  26. package/src/__tests__/launcher-avx2-fallback.test.ts +630 -0
  27. package/src/__tests__/launcher-disconnect.test.ts +104 -0
  28. package/src/__tests__/mocks/hover-toggle-controller.ts +71 -0
  29. package/src/__tests__/open-tui-native-bundle.test.ts +378 -0
  30. package/src/__tests__/path-completion.test.ts +243 -0
  31. package/src/__tests__/project-files-chat-id.test.ts +34 -0
  32. package/src/__tests__/release/proxy-http-get.test.ts +667 -0
  33. package/src/__tests__/release/wrapper-safety.test.ts +412 -0
  34. package/src/__tests__/renderer-cleanup.test.ts +174 -0
  35. package/src/__tests__/rerender-perf.integration.test.ts +283 -0
  36. package/src/__tests__/terminal-reset-sequences.test.ts +36 -0
  37. package/src/__tests__/terminal-watchdog.test.ts +388 -0
  38. package/src/__tests__/test-utils.ts +271 -0
  39. package/src/__tests__/tmux-poc.ts +150 -0
  40. package/src/__tests__/unit/agent-mode-toggle.test.ts +137 -0
  41. package/src/__tests__/unit/copy-button.test.ts +157 -0
  42. package/src/__tests__/unit/create-run-config.test.ts +66 -0
  43. package/src/__tests__/unit/publish-confirmation.test.ts +70 -0
  44. package/src/__tests__/unit/segmented-control.test.ts +152 -0
  45. package/src/__tests__/utils/env.test.ts +169 -0
  46. package/src/__tests__/utils/project-picker.test.ts +39 -0
  47. package/src/agents/bundled-agents.generated.d.ts +14 -0
  48. package/src/agents/bundled-agents.generated.ts +3692 -0
  49. package/src/app.tsx +399 -0
  50. package/src/chat.tsx +1698 -0
  51. package/src/cli-args.ts +134 -0
  52. package/src/commands/__tests__/bash-command.test.ts +445 -0
  53. package/src/commands/__tests__/command-args.test.ts +349 -0
  54. package/src/commands/__tests__/copy-conversation-clipboard.test.ts +108 -0
  55. package/src/commands/__tests__/copy-conversation.test.ts +226 -0
  56. package/src/commands/__tests__/diagnostics-command.test.ts +35 -0
  57. package/src/commands/__tests__/freebuff-command-aliases.test.ts +56 -0
  58. package/src/commands/__tests__/image.test.ts +99 -0
  59. package/src/commands/__tests__/init.test.ts +456 -0
  60. package/src/commands/__tests__/new-command-rotates-chat.test.ts +91 -0
  61. package/src/commands/__tests__/process-diagnostics.test.ts +54 -0
  62. package/src/commands/__tests__/prompt-builders.test.ts +28 -0
  63. package/src/commands/__tests__/router-input.test.ts +298 -0
  64. package/src/commands/ads.ts +44 -0
  65. package/src/commands/command-registry.ts +726 -0
  66. package/src/commands/copy-conversation.ts +392 -0
  67. package/src/commands/help.ts +13 -0
  68. package/src/commands/image.ts +20 -0
  69. package/src/commands/init.ts +121 -0
  70. package/src/commands/process-diagnostics.ts +120 -0
  71. package/src/commands/prompt-builders.ts +100 -0
  72. package/src/commands/publish.ts +203 -0
  73. package/src/commands/router-utils.ts +80 -0
  74. package/src/commands/router.ts +487 -0
  75. package/src/commands/usage.ts +26 -0
  76. package/src/components/__tests__/ad-banner.test.tsx +83 -0
  77. package/src/components/__tests__/chat-input-bar.test.tsx +130 -0
  78. package/src/components/__tests__/freebuff-landing-heading-row.test.tsx +91 -0
  79. package/src/components/__tests__/freebuff-model-selector.test.tsx +519 -0
  80. package/src/components/__tests__/freebuff-offer-invariants.test.ts +54 -0
  81. package/src/components/__tests__/freebuff-takeover-prompt.test.tsx +212 -0
  82. package/src/components/__tests__/grid-layout.integration.test.tsx +304 -0
  83. package/src/components/__tests__/grid-layout.test.tsx +1051 -0
  84. package/src/components/__tests__/message-block.completion.test.tsx +104 -0
  85. package/src/components/__tests__/message-block.streaming.test.tsx +78 -0
  86. package/src/components/__tests__/message-with-agents.test.tsx +579 -0
  87. package/src/components/__tests__/multiline-input.test.tsx +1132 -0
  88. package/src/components/__tests__/queue-panel.test.tsx +398 -0
  89. package/src/components/__tests__/selectable-list.test.ts +232 -0
  90. package/src/components/__tests__/status-bar.test.tsx +44 -0
  91. package/src/components/__tests__/status-indicator.test.tsx +204 -0
  92. package/src/components/__tests__/terminal-thinking-orb.test.tsx +111 -0
  93. package/src/components/__tests__/user-error-banner.test.tsx +102 -0
  94. package/src/components/ad-banner.tsx +323 -0
  95. package/src/components/agent-checklist.tsx +350 -0
  96. package/src/components/agent-mode-toggle.tsx +241 -0
  97. package/src/components/anvil-mark.tsx +52 -0
  98. package/src/components/ask-user/__tests__/multiple-choice-form.test.ts +432 -0
  99. package/src/components/ask-user/__tests__/validation.test.ts +213 -0
  100. package/src/components/ask-user/components/accordion-question.tsx +153 -0
  101. package/src/components/ask-user/components/custom-answer-input.tsx +66 -0
  102. package/src/components/ask-user/components/options-list.tsx +133 -0
  103. package/src/components/ask-user/components/question-header.tsx +80 -0
  104. package/src/components/ask-user/components/question-option.tsx +89 -0
  105. package/src/components/ask-user/constants.ts +38 -0
  106. package/src/components/ask-user/index.tsx +631 -0
  107. package/src/components/ask-user/utils/validation.ts +85 -0
  108. package/src/components/attachment-card.tsx +65 -0
  109. package/src/components/blocks/agent-block-grid.tsx +58 -0
  110. package/src/components/blocks/agent-branch-item.tsx +311 -0
  111. package/src/components/blocks/agent-branch-wrapper.tsx +493 -0
  112. package/src/components/blocks/agent-list-branch.tsx +77 -0
  113. package/src/components/blocks/ask-user-branch.tsx +81 -0
  114. package/src/components/blocks/block-helpers.ts +11 -0
  115. package/src/components/blocks/blocks-renderer.tsx +289 -0
  116. package/src/components/blocks/content-with-markdown.tsx +33 -0
  117. package/src/components/blocks/image-block.tsx +128 -0
  118. package/src/components/blocks/implementor-row.tsx +429 -0
  119. package/src/components/blocks/single-block.tsx +201 -0
  120. package/src/components/blocks/thinking-block.tsx +67 -0
  121. package/src/components/blocks/tool-block-group.tsx +57 -0
  122. package/src/components/blocks/tool-branch.tsx +206 -0
  123. package/src/components/blocks/user-content-copy.tsx +157 -0
  124. package/src/components/bottom-banner.tsx +136 -0
  125. package/src/components/build-mode-buttons.tsx +110 -0
  126. package/src/components/button.tsx +66 -0
  127. package/src/components/chat-header.tsx +77 -0
  128. package/src/components/chat-history-screen.tsx +413 -0
  129. package/src/components/chat-input-bar.tsx +523 -0
  130. package/src/components/clickable-title-box.tsx +66 -0
  131. package/src/components/clickable.tsx +119 -0
  132. package/src/components/collapse-button.tsx +34 -0
  133. package/src/components/copy-button.tsx +203 -0
  134. package/src/components/elapsed-timer.tsx +55 -0
  135. package/src/components/error-boundary.tsx +55 -0
  136. package/src/components/feedback-container.tsx +181 -0
  137. package/src/components/feedback-icon-button.tsx +89 -0
  138. package/src/components/feedback-input-mode.tsx +344 -0
  139. package/src/components/file-attachment-card.tsx +98 -0
  140. package/src/components/freebuff-active-session-summary.tsx +63 -0
  141. package/src/components/freebuff-landing-screen.tsx +865 -0
  142. package/src/components/freebuff-model-selector.tsx +1087 -0
  143. package/src/components/freebuff-referral-banner.tsx +604 -0
  144. package/src/components/freebuff-superseded-screen.tsx +62 -0
  145. package/src/components/grid-layout.tsx +80 -0
  146. package/src/components/help-banner.tsx +127 -0
  147. package/src/components/highlighted-text.tsx +52 -0
  148. package/src/components/image-card.tsx +167 -0
  149. package/src/components/image-thumbnail.tsx +114 -0
  150. package/src/components/input-cursor.tsx +77 -0
  151. package/src/components/input-mode-banner.tsx +57 -0
  152. package/src/components/load-previous-button.tsx +48 -0
  153. package/src/components/login-modal.tsx +475 -0
  154. package/src/components/message-block.tsx +346 -0
  155. package/src/components/message-footer.tsx +258 -0
  156. package/src/components/message-with-agents.tsx +506 -0
  157. package/src/components/mode-divider.tsx +43 -0
  158. package/src/components/multiline-input.tsx +1241 -0
  159. package/src/components/out-of-credits-banner.tsx +160 -0
  160. package/src/components/pending-attachments-banner.tsx +116 -0
  161. package/src/components/pending-bash-message.tsx +59 -0
  162. package/src/components/progress-bar.tsx +81 -0
  163. package/src/components/project-picker-screen.tsx +485 -0
  164. package/src/components/publish-confirmation.tsx +493 -0
  165. package/src/components/publish-container.tsx +687 -0
  166. package/src/components/queue-panel.tsx +310 -0
  167. package/src/components/raised-pill.tsx +95 -0
  168. package/src/components/renderers/plan-box.tsx +59 -0
  169. package/src/components/review-screen.tsx +112 -0
  170. package/src/components/scroll-to-bottom-button.tsx +34 -0
  171. package/src/components/segmented-control.tsx +187 -0
  172. package/src/components/selectable-list.tsx +248 -0
  173. package/src/components/selected-chips.tsx +80 -0
  174. package/src/components/separator.tsx +40 -0
  175. package/src/components/session-ended-banner.tsx +226 -0
  176. package/src/components/shimmer-text.tsx +248 -0
  177. package/src/components/status-bar.tsx +313 -0
  178. package/src/components/subscription-limit-banner.tsx +206 -0
  179. package/src/components/suggested-prompts.tsx +184 -0
  180. package/src/components/suggestion-menu.tsx +215 -0
  181. package/src/components/terminal-command-display.tsx +151 -0
  182. package/src/components/terminal-link.tsx +97 -0
  183. package/src/components/terminal-thinking-orb.tsx +95 -0
  184. package/src/components/text-attachment-card.tsx +77 -0
  185. package/src/components/thinking.tsx +109 -0
  186. package/src/components/tools/__tests__/apply-patch.test.tsx +84 -0
  187. package/src/components/tools/__tests__/code-search.test.tsx +45 -0
  188. package/src/components/tools/__tests__/gravity-index.test.ts +76 -0
  189. package/src/components/tools/__tests__/render-ui.test.tsx +92 -0
  190. package/src/components/tools/__tests__/run-terminal-command.test.ts +233 -0
  191. package/src/components/tools/apply-patch.tsx +95 -0
  192. package/src/components/tools/code-search.tsx +45 -0
  193. package/src/components/tools/composio.tsx +152 -0
  194. package/src/components/tools/diff-viewer.tsx +76 -0
  195. package/src/components/tools/glob.tsx +61 -0
  196. package/src/components/tools/gravity-index.tsx +77 -0
  197. package/src/components/tools/list-directory.tsx +61 -0
  198. package/src/components/tools/read-docs.tsx +37 -0
  199. package/src/components/tools/read-files.tsx +91 -0
  200. package/src/components/tools/read-subtree.tsx +44 -0
  201. package/src/components/tools/read-url.tsx +33 -0
  202. package/src/components/tools/registry.ts +126 -0
  203. package/src/components/tools/render-ui.tsx +122 -0
  204. package/src/components/tools/run-terminal-command.tsx +79 -0
  205. package/src/components/tools/skill.tsx +29 -0
  206. package/src/components/tools/str-replace.tsx +77 -0
  207. package/src/components/tools/suggest-followups.tsx +369 -0
  208. package/src/components/tools/task-completed.tsx +16 -0
  209. package/src/components/tools/tool-call-item.tsx +273 -0
  210. package/src/components/tools/types.ts +55 -0
  211. package/src/components/tools/web-search.tsx +33 -0
  212. package/src/components/tools/write-file.tsx +16 -0
  213. package/src/components/tools/write-todos.tsx +95 -0
  214. package/src/components/top-banner.tsx +178 -0
  215. package/src/components/usage-banner.tsx +244 -0
  216. package/src/components/user-error-banner.tsx +56 -0
  217. package/src/components/validation-error-popover.tsx +192 -0
  218. package/src/contexts/__tests__/chat-runtime-context.test.tsx +149 -0
  219. package/src/contexts/chat-runtime-context.tsx +240 -0
  220. package/src/data/slash-commands.test.ts +24 -0
  221. package/src/data/slash-commands.ts +249 -0
  222. package/src/entry.ts +12 -0
  223. package/src/hooks/__tests__/holds-live-freebuff-slot.test.ts +49 -0
  224. package/src/hooks/__tests__/session-fetch-signal.test.ts +63 -0
  225. package/src/hooks/__tests__/use-activity-query.test.ts +1000 -0
  226. package/src/hooks/__tests__/use-ask-user-bridge.test.ts +176 -0
  227. package/src/hooks/__tests__/use-auth-query.test.ts +21 -0
  228. package/src/hooks/__tests__/use-chat-input-remount.test.tsx +66 -0
  229. package/src/hooks/__tests__/use-clipboard.test.tsx +73 -0
  230. package/src/hooks/__tests__/use-connection-status.test.ts +112 -0
  231. package/src/hooks/__tests__/use-directory-browser.test.ts +203 -0
  232. package/src/hooks/__tests__/use-gravity-ad.test.ts +73 -0
  233. package/src/hooks/__tests__/use-grid-layout.test.ts +349 -0
  234. package/src/hooks/__tests__/use-input-history.test.ts +699 -0
  235. package/src/hooks/__tests__/use-message-queue-editing.test.tsx +209 -0
  236. package/src/hooks/__tests__/use-message-queue.test.tsx +71 -0
  237. package/src/hooks/__tests__/use-path-tab-completion.test.ts +315 -0
  238. package/src/hooks/__tests__/use-queue-controls.test.ts +68 -0
  239. package/src/hooks/__tests__/use-queue-ui.test.tsx +83 -0
  240. package/src/hooks/__tests__/use-searchable-list.test.ts +359 -0
  241. package/src/hooks/__tests__/use-send-message-timer.test.ts +146 -0
  242. package/src/hooks/__tests__/use-suggestion-engine-mention.test.ts +361 -0
  243. package/src/hooks/__tests__/use-suggestion-engine.test.ts +485 -0
  244. package/src/hooks/__tests__/use-terminal-focus.test.ts +66 -0
  245. package/src/hooks/__tests__/use-terminal-layout.test.ts +675 -0
  246. package/src/hooks/__tests__/use-timeout.test.ts +330 -0
  247. package/src/hooks/__tests__/use-usage-query.test.ts +502 -0
  248. package/src/hooks/__tests__/use-user-details-query.test.ts +195 -0
  249. package/src/hooks/helpers/__tests__/send-message.test.ts +1918 -0
  250. package/src/hooks/helpers/send-message.ts +654 -0
  251. package/src/hooks/stream-state.ts +83 -0
  252. package/src/hooks/use-activity-query.ts +668 -0
  253. package/src/hooks/use-agent-validation.ts +74 -0
  254. package/src/hooks/use-ask-user-bridge.ts +92 -0
  255. package/src/hooks/use-auth-query.ts +253 -0
  256. package/src/hooks/use-auth-state.ts +152 -0
  257. package/src/hooks/use-chat-input.ts +105 -0
  258. package/src/hooks/use-chat-keyboard.ts +321 -0
  259. package/src/hooks/use-chat-messages.ts +254 -0
  260. package/src/hooks/use-chat-state.ts +165 -0
  261. package/src/hooks/use-chat-streaming.ts +180 -0
  262. package/src/hooks/use-chat-ui.ts +131 -0
  263. package/src/hooks/use-clipboard.ts +151 -0
  264. package/src/hooks/use-connection-status.ts +142 -0
  265. package/src/hooks/use-directory-browser.ts +88 -0
  266. package/src/hooks/use-elapsed-time.ts +116 -0
  267. package/src/hooks/use-event.ts +34 -0
  268. package/src/hooks/use-exit-handler.ts +66 -0
  269. package/src/hooks/use-fetch-login-url.ts +65 -0
  270. package/src/hooks/use-fingerprint.ts +61 -0
  271. package/src/hooks/use-freebuff-ctrl-c-exit.ts +23 -0
  272. package/src/hooks/use-freebuff-session-progress.ts +34 -0
  273. package/src/hooks/use-freebuff-session.ts +806 -0
  274. package/src/hooks/use-freebuff-streak-query.ts +61 -0
  275. package/src/hooks/use-gravity-ad.ts +656 -0
  276. package/src/hooks/use-grid-layout.ts +73 -0
  277. package/src/hooks/use-input-history.ts +173 -0
  278. package/src/hooks/use-login-keyboard-handlers.ts +75 -0
  279. package/src/hooks/use-login-polling.ts +114 -0
  280. package/src/hooks/use-logo.tsx +161 -0
  281. package/src/hooks/use-message-queue.ts +387 -0
  282. package/src/hooks/use-now.ts +20 -0
  283. package/src/hooks/use-path-tab-completion.ts +88 -0
  284. package/src/hooks/use-publish-mutation.ts +60 -0
  285. package/src/hooks/use-queue-controls.ts +68 -0
  286. package/src/hooks/use-queue-ui.ts +74 -0
  287. package/src/hooks/use-scroll-management.ts +184 -0
  288. package/src/hooks/use-searchable-list.ts +98 -0
  289. package/src/hooks/use-send-message.ts +773 -0
  290. package/src/hooks/use-sheen-animation.tsx +88 -0
  291. package/src/hooks/use-subscription-query.ts +71 -0
  292. package/src/hooks/use-suggestion-engine.ts +783 -0
  293. package/src/hooks/use-terminal-breakpoints.ts +77 -0
  294. package/src/hooks/use-terminal-dimensions.ts +46 -0
  295. package/src/hooks/use-terminal-focus.ts +29 -0
  296. package/src/hooks/use-terminal-layout.ts +189 -0
  297. package/src/hooks/use-theme.tsx +140 -0
  298. package/src/hooks/use-timeout.ts +85 -0
  299. package/src/hooks/use-update-preference.ts +66 -0
  300. package/src/hooks/use-usage-monitor.ts +55 -0
  301. package/src/hooks/use-usage-query.ts +124 -0
  302. package/src/hooks/use-user-details-query.ts +93 -0
  303. package/src/hooks/use-why-did-you-update.ts +177 -0
  304. package/src/index.tsx +441 -0
  305. package/src/init/__tests__/init-direnv.test.ts +526 -0
  306. package/src/init/init-app.ts +34 -0
  307. package/src/init/init-direnv.ts +133 -0
  308. package/src/login/constants.ts +60 -0
  309. package/src/login/login-flow.ts +204 -0
  310. package/src/login/plain-login.ts +108 -0
  311. package/src/login/utils.ts +183 -0
  312. package/src/native/ripgrep.ts +80 -0
  313. package/src/polyfills/bun-strip-ansi.ts +12 -0
  314. package/src/pre-init/tree-sitter-wasm.ts +96 -0
  315. package/src/project-files.ts +102 -0
  316. package/src/smoke/terminal-command-broker.ts +439 -0
  317. package/src/state/__tests__/chat-store-focus.test.ts +22 -0
  318. package/src/state/__tests__/feedback-store.test.ts +257 -0
  319. package/src/state/chat-history-store.ts +30 -0
  320. package/src/state/chat-store.ts +544 -0
  321. package/src/state/feedback-store.ts +160 -0
  322. package/src/state/freebuff-model-store.ts +42 -0
  323. package/src/state/freebuff-session-store.ts +53 -0
  324. package/src/state/login-store.ts +150 -0
  325. package/src/state/message-block-store.ts +149 -0
  326. package/src/state/publish-store.ts +146 -0
  327. package/src/state/queue-panel-store.ts +26 -0
  328. package/src/state/review-store.ts +24 -0
  329. package/src/testing/env.ts +46 -0
  330. package/src/types/chat-state.ts +15 -0
  331. package/src/types/chat.ts +241 -0
  332. package/src/types/contracts/send-message.ts +12 -0
  333. package/src/types/env.ts +98 -0
  334. package/src/types/freebuff-session.ts +17 -0
  335. package/src/types/function-params.ts +28 -0
  336. package/src/types/react19-compat.d.ts +19 -0
  337. package/src/types/store.ts +111 -0
  338. package/src/types/theme-system.ts +144 -0
  339. package/src/types/utils.ts +3 -0
  340. package/src/utils/__tests__/active-run.test.ts +140 -0
  341. package/src/utils/__tests__/activity-tracker.test.ts +440 -0
  342. package/src/utils/__tests__/agent-display.test.ts +139 -0
  343. package/src/utils/__tests__/analytics-client.test.ts +262 -0
  344. package/src/utils/__tests__/anonymous-id.test.ts +74 -0
  345. package/src/utils/__tests__/anvil-api.test.ts +578 -0
  346. package/src/utils/__tests__/arrays.test.ts +264 -0
  347. package/src/utils/__tests__/bash-context-processor.test.ts +38 -0
  348. package/src/utils/__tests__/block-processor.test.ts +810 -0
  349. package/src/utils/__tests__/chat-history.test.ts +203 -0
  350. package/src/utils/__tests__/chat-input-key-intercept.test.ts +40 -0
  351. package/src/utils/__tests__/chat-meta.test.ts +130 -0
  352. package/src/utils/__tests__/clipboard-linux.test.ts +359 -0
  353. package/src/utils/__tests__/clipboard.test.ts +910 -0
  354. package/src/utils/__tests__/code-search-summary.test.ts +84 -0
  355. package/src/utils/__tests__/collapse-helpers.test.ts +1109 -0
  356. package/src/utils/__tests__/error-handling.test.ts +658 -0
  357. package/src/utils/__tests__/exit-cleanly.test.ts +110 -0
  358. package/src/utils/__tests__/feedback-helpers.test.ts +444 -0
  359. package/src/utils/__tests__/feedback-submission.test.ts +26 -0
  360. package/src/utils/__tests__/fetch-usage.test.ts +355 -0
  361. package/src/utils/__tests__/fingerprint.test.ts +144 -0
  362. package/src/utils/__tests__/fixtures/terminal-command-broker-child.ts +7 -0
  363. package/src/utils/__tests__/fixtures/terminal-command-broker-entry.ts +3 -0
  364. package/src/utils/__tests__/fixtures/terminal-command-broker-owner.ts +33 -0
  365. package/src/utils/__tests__/format-elapsed-time.test.ts +103 -0
  366. package/src/utils/__tests__/format-timeout.test.ts +87 -0
  367. package/src/utils/__tests__/freebuff-instance-owner.test.ts +69 -0
  368. package/src/utils/__tests__/freebuff-model-navigation.test.ts +102 -0
  369. package/src/utils/__tests__/freebuff-premium-reset.test.ts +79 -0
  370. package/src/utils/__tests__/freebuff-referral-cache.test.ts +116 -0
  371. package/src/utils/__tests__/freebuff-session-api.test.ts +215 -0
  372. package/src/utils/__tests__/freebuff-session-display.test.ts +23 -0
  373. package/src/utils/__tests__/freebuff-streak-line.test.ts +217 -0
  374. package/src/utils/__tests__/image-dimensions.test.ts +249 -0
  375. package/src/utils/__tests__/image-processor.test.ts +209 -0
  376. package/src/utils/__tests__/implementor-helpers.test.ts +1458 -0
  377. package/src/utils/__tests__/keyboard-actions.test.ts +660 -0
  378. package/src/utils/__tests__/layout-helpers.test.ts +36 -0
  379. package/src/utils/__tests__/lazy-response-ads.test.ts +167 -0
  380. package/src/utils/__tests__/log-shipper.test.ts +53 -0
  381. package/src/utils/__tests__/markdown-renderer.test.tsx +421 -0
  382. package/src/utils/__tests__/message-block-helpers.test.ts +1263 -0
  383. package/src/utils/__tests__/message-updater.test.ts +645 -0
  384. package/src/utils/__tests__/osc-timeout-scenarios.test.ts +172 -0
  385. package/src/utils/__tests__/pending-attachments.test.ts +277 -0
  386. package/src/utils/__tests__/polling-backoff.test.ts +51 -0
  387. package/src/utils/__tests__/queue-panel-actions.test.ts +148 -0
  388. package/src/utils/__tests__/run-state-storage.test.ts +919 -0
  389. package/src/utils/__tests__/safe-json.test.ts +77 -0
  390. package/src/utils/__tests__/sdk-event-handlers.test.ts +685 -0
  391. package/src/utils/__tests__/send-message-helpers.test.ts +1898 -0
  392. package/src/utils/__tests__/send-message-timer.test.ts +64 -0
  393. package/src/utils/__tests__/settings.test.ts +99 -0
  394. package/src/utils/__tests__/strings.test.ts +192 -0
  395. package/src/utils/__tests__/terminal-color-detection.test.ts +425 -0
  396. package/src/utils/__tests__/terminal-command-broker.test.ts +528 -0
  397. package/src/utils/__tests__/terminal-enter-detection.test.ts +77 -0
  398. package/src/utils/__tests__/terminal-io.test.ts +137 -0
  399. package/src/utils/__tests__/terminal-protocol-controller.test.ts +119 -0
  400. package/src/utils/__tests__/text-layout.test.ts +82 -0
  401. package/src/utils/__tests__/theme-platform-detection.test.ts +125 -0
  402. package/src/utils/__tests__/think-tag-parser.test.ts +159 -0
  403. package/src/utils/__tests__/trace-writer.test.ts +223 -0
  404. package/src/utils/__tests__/trim-chat-logs.test.ts +78 -0
  405. package/src/utils/__tests__/usage-banner-state.test.ts +298 -0
  406. package/src/utils/__tests__/validation-error-formatting.test.ts +126 -0
  407. package/src/utils/__tests__/windows-terminal-health.test.ts +101 -0
  408. package/src/utils/__tests__/write-file-atomic.test.ts +127 -0
  409. package/src/utils/active-run.ts +131 -0
  410. package/src/utils/activity-tracker.ts +66 -0
  411. package/src/utils/agent-display.ts +87 -0
  412. package/src/utils/agent-helpers.ts +27 -0
  413. package/src/utils/agent-id-utils.ts +14 -0
  414. package/src/utils/ai-message-id.ts +12 -0
  415. package/src/utils/analytics.ts +361 -0
  416. package/src/utils/anonymous-id.ts +87 -0
  417. package/src/utils/anvil-api.ts +612 -0
  418. package/src/utils/anvil-client.ts +217 -0
  419. package/src/utils/arrays.ts +117 -0
  420. package/src/utils/auth.ts +258 -0
  421. package/src/utils/bash-context-processor.ts +47 -0
  422. package/src/utils/bash-messages.ts +108 -0
  423. package/src/utils/block-margins.ts +35 -0
  424. package/src/utils/block-operations.ts +523 -0
  425. package/src/utils/block-processor.ts +213 -0
  426. package/src/utils/chat-history.ts +253 -0
  427. package/src/utils/chat-input-key-intercept.ts +52 -0
  428. package/src/utils/chat-meta.ts +90 -0
  429. package/src/utils/chat-scroll-accel.ts +151 -0
  430. package/src/utils/clipboard-image.ts +588 -0
  431. package/src/utils/clipboard.ts +397 -0
  432. package/src/utils/code-search-summary.ts +70 -0
  433. package/src/utils/collapse-helpers.ts +256 -0
  434. package/src/utils/config-dir.ts +24 -0
  435. package/src/utils/constants.ts +190 -0
  436. package/src/utils/create-event-handler-state.ts +73 -0
  437. package/src/utils/create-run-config.ts +121 -0
  438. package/src/utils/detect-shell.ts +116 -0
  439. package/src/utils/directory-browser.ts +72 -0
  440. package/src/utils/engagement.ts +55 -0
  441. package/src/utils/env.ts +92 -0
  442. package/src/utils/error-handling.ts +255 -0
  443. package/src/utils/error-messages.ts +62 -0
  444. package/src/utils/exit-cleanly.ts +86 -0
  445. package/src/utils/feedback-helpers.ts +103 -0
  446. package/src/utils/feedback-submission.ts +22 -0
  447. package/src/utils/fetch-usage.ts +76 -0
  448. package/src/utils/fingerprint.ts +245 -0
  449. package/src/utils/format-elapsed-time.ts +33 -0
  450. package/src/utils/format-session-units.ts +6 -0
  451. package/src/utils/format-timeout.ts +28 -0
  452. package/src/utils/format-validation-errors-for-message.ts +84 -0
  453. package/src/utils/freebuff-agent-selection.ts +33 -0
  454. package/src/utils/freebuff-instance-owner.ts +66 -0
  455. package/src/utils/freebuff-model-navigation.ts +50 -0
  456. package/src/utils/freebuff-premium-reset.ts +55 -0
  457. package/src/utils/freebuff-referral-cache.ts +51 -0
  458. package/src/utils/freebuff-session-api.ts +243 -0
  459. package/src/utils/freebuff-session-display.ts +21 -0
  460. package/src/utils/freebuff-streak-line.ts +93 -0
  461. package/src/utils/git.ts +17 -0
  462. package/src/utils/helpers.ts +47 -0
  463. package/src/utils/image-display.ts +67 -0
  464. package/src/utils/image-handler.ts +325 -0
  465. package/src/utils/image-processor.ts +133 -0
  466. package/src/utils/image-thumbnail.ts +78 -0
  467. package/src/utils/implementor-helpers.ts +787 -0
  468. package/src/utils/input-modes.ts +174 -0
  469. package/src/utils/keyboard-actions.ts +392 -0
  470. package/src/utils/keypad-keys.ts +47 -0
  471. package/src/utils/layout-helpers.ts +33 -0
  472. package/src/utils/lazy-response-ads.ts +1 -0
  473. package/src/utils/local-agent-registry.ts +474 -0
  474. package/src/utils/log-shipper.ts +126 -0
  475. package/src/utils/logger.ts +327 -0
  476. package/src/utils/markdown-renderer.tsx +1090 -0
  477. package/src/utils/math.ts +3 -0
  478. package/src/utils/message-block-helpers.ts +684 -0
  479. package/src/utils/message-history.ts +143 -0
  480. package/src/utils/message-tree-utils.ts +67 -0
  481. package/src/utils/message-updater.ts +279 -0
  482. package/src/utils/open-file.ts +146 -0
  483. package/src/utils/open-url.ts +63 -0
  484. package/src/utils/path-completion.ts +111 -0
  485. package/src/utils/path-helpers.ts +38 -0
  486. package/src/utils/pending-attachments.ts +360 -0
  487. package/src/utils/polling-backoff.ts +59 -0
  488. package/src/utils/project-picker.ts +12 -0
  489. package/src/utils/queue-panel-actions.ts +70 -0
  490. package/src/utils/recent-projects.ts +156 -0
  491. package/src/utils/renderer-cleanup.ts +233 -0
  492. package/src/utils/response-ad-positions.ts +1 -0
  493. package/src/utils/run-state-storage.ts +603 -0
  494. package/src/utils/safe-json.ts +153 -0
  495. package/src/utils/sdk-event-handlers.ts +571 -0
  496. package/src/utils/send-message-helpers.ts +210 -0
  497. package/src/utils/send-message-timer.ts +110 -0
  498. package/src/utils/settings.ts +226 -0
  499. package/src/utils/skill-registry.ts +94 -0
  500. package/src/utils/spawn-agent-matcher.ts +55 -0
  501. package/src/utils/status-indicator-state.ts +107 -0
  502. package/src/utils/stream-chunk-processor.ts +57 -0
  503. package/src/utils/strings.ts +271 -0
  504. package/src/utils/subscription.ts +31 -0
  505. package/src/utils/syntax-highlighter.tsx +19 -0
  506. package/src/utils/terminal-color-detection.ts +474 -0
  507. package/src/utils/terminal-command-broker.ts +467 -0
  508. package/src/utils/terminal-enter-detection.ts +63 -0
  509. package/src/utils/terminal-images.ts +229 -0
  510. package/src/utils/terminal-io.ts +85 -0
  511. package/src/utils/terminal-protocol-controller.ts +173 -0
  512. package/src/utils/terminal-reset-sequences.ts +33 -0
  513. package/src/utils/terminal-title.ts +84 -0
  514. package/src/utils/terminal-watchdog.ts +366 -0
  515. package/src/utils/text-layout.ts +149 -0
  516. package/src/utils/theme-config.ts +141 -0
  517. package/src/utils/theme-system.ts +1206 -0
  518. package/src/utils/think-tag-parser.ts +95 -0
  519. package/src/utils/time-format.ts +21 -0
  520. package/src/utils/trace-writer.ts +162 -0
  521. package/src/utils/ui-constants.ts +69 -0
  522. package/src/utils/update-checker.ts +110 -0
  523. package/src/utils/usage-banner-state.ts +146 -0
  524. package/src/utils/validation-error-formatting.ts +86 -0
  525. package/src/utils/validation-error-helpers.ts +19 -0
  526. package/src/utils/windows-terminal-health.ts +124 -0
  527. package/src/utils/word-wrap-utils.ts +53 -0
  528. package/src/utils/write-file-atomic.ts +54 -0
  529. package/src/utils/yield-to-event-loop.ts +9 -0
@@ -0,0 +1,1898 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+
3
+ import {
4
+ appendTextToRootStream,
5
+ appendTextToAgentBlock,
6
+ appendToolToAgentBlock,
7
+ isNativeReasoningBlock,
8
+ closeNativeReasoningBlock,
9
+ closeNativeReasoningInAgent,
10
+ markAgentComplete,
11
+ markRunningAgentsAsCancelled,
12
+ } from '../block-operations'
13
+ import {
14
+ updateBlocksRecursively,
15
+ scrubPlanTags,
16
+ scrubPlanTagsInBlocks,
17
+ extractPlanFromBuffer,
18
+ createAgentBlock,
19
+ getAgentBaseName,
20
+ autoCollapseBlocks,
21
+ updateToolBlockWithOutput,
22
+ transformAskUserBlocks,
23
+ appendInterruptionNotice,
24
+ extractSpawnAgentResultContent,
25
+ } from '../message-block-helpers'
26
+ import {
27
+ createModeDividerMessage,
28
+ createAiMessageShell,
29
+ createErrorMessage,
30
+ generateAiMessageId,
31
+ autoCollapsePreviousMessages,
32
+ createSpawnAgentBlocks,
33
+ isSpawnAgentsResult,
34
+ markMessageComplete,
35
+ sanitizeRestoredMessages,
36
+ setMessageError,
37
+ } from '../send-message-helpers'
38
+
39
+ import type {
40
+ ContentBlock,
41
+ AgentContentBlock,
42
+ AskUserContentBlock,
43
+ ChatMessage,
44
+ ModeDividerContentBlock,
45
+ TextContentBlock,
46
+ ToolContentBlock,
47
+ } from '../../types/chat'
48
+
49
+ // ============================================================================
50
+ // Block Manipulation Helpers Tests (from message-block-helpers)
51
+ // ============================================================================
52
+
53
+ describe('updateBlocksRecursively', () => {
54
+ test('updates a top-level agent block', () => {
55
+ const blocks: ContentBlock[] = [
56
+ {
57
+ type: 'agent',
58
+ agentId: 'agent-1',
59
+ agentName: 'Test',
60
+ agentType: 'test',
61
+ content: '',
62
+ status: 'running',
63
+ },
64
+ ]
65
+
66
+ const result = updateBlocksRecursively(blocks, 'agent-1', (block) => ({
67
+ ...block,
68
+ status: 'complete' as const,
69
+ }))
70
+
71
+ expect(result[0].type).toBe('agent')
72
+ expect((result[0] as AgentContentBlock).status).toBe('complete')
73
+ })
74
+
75
+ test('updates a nested agent block', () => {
76
+ const blocks: ContentBlock[] = [
77
+ {
78
+ type: 'agent',
79
+ agentId: 'parent',
80
+ agentName: 'Parent',
81
+ agentType: 'parent',
82
+ content: '',
83
+ status: 'running',
84
+ blocks: [
85
+ {
86
+ type: 'agent',
87
+ agentId: 'child',
88
+ agentName: 'Child',
89
+ agentType: 'child',
90
+ content: '',
91
+ status: 'running',
92
+ },
93
+ ],
94
+ },
95
+ ]
96
+
97
+ const result = updateBlocksRecursively(blocks, 'child', (block) => ({
98
+ ...block,
99
+ status: 'complete' as const,
100
+ }))
101
+
102
+ const parent = result[0] as AgentContentBlock
103
+ const child = parent.blocks![0] as AgentContentBlock
104
+ expect(child.status).toBe('complete')
105
+ })
106
+
107
+ test('returns original array if no match found', () => {
108
+ const blocks: ContentBlock[] = [{ type: 'text', content: 'Hello' }]
109
+
110
+ const result = updateBlocksRecursively(blocks, 'nonexistent', (block) => ({
111
+ ...block,
112
+ }))
113
+
114
+ expect(result).toBe(blocks) // Same reference
115
+ })
116
+
117
+ test('does not create new blocks for unchanged nested structures', () => {
118
+ const blocks: ContentBlock[] = [
119
+ {
120
+ type: 'agent',
121
+ agentId: 'agent-1',
122
+ agentName: 'Test',
123
+ agentType: 'test',
124
+ content: '',
125
+ status: 'running',
126
+ blocks: [{ type: 'text', content: 'Nested text' }],
127
+ },
128
+ ]
129
+
130
+ const result = updateBlocksRecursively(blocks, 'nonexistent', (block) => ({
131
+ ...block,
132
+ }))
133
+
134
+ expect(result).toBe(blocks)
135
+ })
136
+ })
137
+
138
+ describe('scrubPlanTags', () => {
139
+ test('removes complete PLAN tags', () => {
140
+ const input = 'Before <PLAN>plan content</cb_plan> After'
141
+ expect(scrubPlanTags(input)).toBe('Before After')
142
+ })
143
+
144
+ test('removes incomplete trailing PLAN tags', () => {
145
+ const input = 'Content <PLAN>incomplete plan'
146
+ expect(scrubPlanTags(input)).toBe('Content ')
147
+ })
148
+
149
+ test('handles string with no PLAN tags', () => {
150
+ const input = 'Just regular content'
151
+ expect(scrubPlanTags(input)).toBe('Just regular content')
152
+ })
153
+
154
+ test('handles empty string', () => {
155
+ expect(scrubPlanTags('')).toBe('')
156
+ })
157
+ })
158
+
159
+ describe('scrubPlanTagsInBlocks', () => {
160
+ test('removes plan tags from text blocks', () => {
161
+ const blocks: ContentBlock[] = [
162
+ { type: 'text', content: 'Hello <PLAN>plan</cb_plan> World' },
163
+ ]
164
+
165
+ const result = scrubPlanTagsInBlocks(blocks)
166
+ expect((result[0] as TextContentBlock).content).toBe('Hello World')
167
+ })
168
+
169
+ test('filters out empty text blocks after scrubbing', () => {
170
+ const blocks: ContentBlock[] = [
171
+ { type: 'text', content: '<PLAN>only plan</cb_plan>' },
172
+ { type: 'text', content: 'Keep this' },
173
+ ]
174
+
175
+ const result = scrubPlanTagsInBlocks(blocks)
176
+ expect(result).toHaveLength(1)
177
+ expect((result[0] as TextContentBlock).content).toBe('Keep this')
178
+ })
179
+
180
+ test('preserves non-text blocks', () => {
181
+ const blocks: ContentBlock[] = [
182
+ {
183
+ type: 'agent',
184
+ agentId: '1',
185
+ agentName: 'Test',
186
+ agentType: 'test',
187
+ content: '',
188
+ status: 'running',
189
+ },
190
+ ]
191
+
192
+ const result = scrubPlanTagsInBlocks(blocks)
193
+ expect(result).toEqual(blocks)
194
+ })
195
+ })
196
+
197
+ // ============================================================================
198
+ // Message Creation Helpers Tests (from send-message-helpers)
199
+ // ============================================================================
200
+
201
+ describe('createModeDividerMessage', () => {
202
+ test('creates a mode divider message', () => {
203
+ const message = createModeDividerMessage('MAX')
204
+
205
+ expect(message.variant).toBe('ai')
206
+ expect(message.content).toBe('')
207
+ expect(message.blocks).toHaveLength(1)
208
+ expect(message.blocks![0].type).toBe('mode-divider')
209
+ expect((message.blocks![0] as ModeDividerContentBlock).mode).toBe('MAX')
210
+ expect(message.id).toMatch(/^divider-/)
211
+ })
212
+ })
213
+
214
+ describe('createAiMessageShell', () => {
215
+ test('creates an empty AI message shell', () => {
216
+ const message = createAiMessageShell('ai-123')
217
+
218
+ expect(message.id).toBe('ai-123')
219
+ expect(message.variant).toBe('ai')
220
+ expect(message.content).toBe('')
221
+ expect(message.blocks).toEqual([])
222
+ expect(message.metadata?.allowInlineAds).toBe(true)
223
+ })
224
+ })
225
+
226
+ describe('createErrorMessage', () => {
227
+ test('creates an error message', () => {
228
+ const message = createErrorMessage('Something went wrong')
229
+
230
+ expect(message.variant).toBe('error')
231
+ expect(message.content).toBe('Something went wrong')
232
+ expect(message.id).toMatch(/^error-/)
233
+ })
234
+ })
235
+
236
+ describe('generateAiMessageId', () => {
237
+ test('generates unique IDs', () => {
238
+ const id1 = generateAiMessageId()
239
+ const id2 = generateAiMessageId()
240
+
241
+ expect(id1).toMatch(/^ai-\d+-[a-f0-9]+$/)
242
+ expect(id1).not.toBe(id2)
243
+ })
244
+ })
245
+
246
+ // ============================================================================
247
+ // Auto-Collapse Logic Tests
248
+ // ============================================================================
249
+
250
+ describe('autoCollapseBlocks', () => {
251
+ test('collapses text blocks with thinkingId', () => {
252
+ const blocks: ContentBlock[] = [
253
+ { type: 'text', content: 'thinking', thinkingId: 'think-1' },
254
+ ]
255
+
256
+ const result = autoCollapseBlocks(blocks)
257
+ expect((result[0] as TextContentBlock).thinkingCollapseState).toBe('hidden')
258
+ })
259
+
260
+ test('does not collapse user-opened blocks', () => {
261
+ const blocks: ContentBlock[] = [
262
+ {
263
+ type: 'text',
264
+ content: 'thinking',
265
+ thinkingId: 'think-1',
266
+ userOpened: true,
267
+ },
268
+ ]
269
+
270
+ const result = autoCollapseBlocks(blocks)
271
+ expect((result[0] as TextContentBlock).isCollapsed).toBeUndefined()
272
+ })
273
+
274
+ test('collapses agent blocks', () => {
275
+ const blocks: ContentBlock[] = [
276
+ {
277
+ type: 'agent',
278
+ agentId: '1',
279
+ agentName: 'Test',
280
+ agentType: 'test',
281
+ content: '',
282
+ status: 'running',
283
+ },
284
+ ]
285
+
286
+ const result = autoCollapseBlocks(blocks)
287
+ expect((result[0] as AgentContentBlock).isCollapsed).toBe(true)
288
+ })
289
+
290
+ test('collapses tool blocks', () => {
291
+ const blocks: ContentBlock[] = [
292
+ {
293
+ type: 'tool',
294
+ toolCallId: 'tool-1',
295
+ toolName: 'read_files',
296
+ input: {},
297
+ },
298
+ ]
299
+
300
+ const result = autoCollapseBlocks(blocks)
301
+ expect((result[0] as ToolContentBlock).isCollapsed).toBe(true)
302
+ })
303
+
304
+ test('recursively collapses nested agent blocks', () => {
305
+ const blocks: ContentBlock[] = [
306
+ {
307
+ type: 'agent',
308
+ agentId: 'parent',
309
+ agentName: 'Parent',
310
+ agentType: 'parent',
311
+ content: '',
312
+ status: 'running',
313
+ blocks: [
314
+ {
315
+ type: 'agent',
316
+ agentId: 'child',
317
+ agentName: 'Child',
318
+ agentType: 'child',
319
+ content: '',
320
+ status: 'running',
321
+ },
322
+ ],
323
+ },
324
+ ]
325
+
326
+ const result = autoCollapseBlocks(blocks)
327
+ const parent = result[0] as AgentContentBlock
328
+ const child = parent.blocks![0] as AgentContentBlock
329
+
330
+ expect(parent.isCollapsed).toBe(true)
331
+ expect(child.isCollapsed).toBe(true)
332
+ })
333
+ })
334
+
335
+ describe('autoCollapsePreviousMessages', () => {
336
+ test('does not collapse the current AI message', () => {
337
+ const messages: ChatMessage[] = [
338
+ {
339
+ id: 'ai-123',
340
+ variant: 'ai',
341
+ content: '',
342
+ blocks: [
343
+ {
344
+ type: 'agent',
345
+ agentId: '1',
346
+ agentName: 'Test',
347
+ agentType: 'test',
348
+ content: '',
349
+ status: 'running',
350
+ },
351
+ ],
352
+ timestamp: '',
353
+ },
354
+ ]
355
+
356
+ const result = autoCollapsePreviousMessages(messages, 'ai-123')
357
+ expect(
358
+ (result[0].blocks![0] as AgentContentBlock).isCollapsed,
359
+ ).toBeUndefined()
360
+ })
361
+
362
+ test('collapses previous messages', () => {
363
+ const messages: ChatMessage[] = [
364
+ {
365
+ id: 'ai-old',
366
+ variant: 'ai',
367
+ content: '',
368
+ blocks: [
369
+ {
370
+ type: 'agent',
371
+ agentId: '1',
372
+ agentName: 'Test',
373
+ agentType: 'test',
374
+ content: '',
375
+ status: 'running',
376
+ },
377
+ ],
378
+ timestamp: '',
379
+ },
380
+ {
381
+ id: 'ai-new',
382
+ variant: 'ai',
383
+ content: '',
384
+ blocks: [],
385
+ timestamp: '',
386
+ },
387
+ ]
388
+
389
+ const result = autoCollapsePreviousMessages(messages, 'ai-new')
390
+ expect((result[0].blocks![0] as AgentContentBlock).isCollapsed).toBe(true)
391
+ })
392
+
393
+ test('respects user-opened agent messages', () => {
394
+ const messages: ChatMessage[] = [
395
+ {
396
+ id: 'agent-msg',
397
+ variant: 'agent',
398
+ content: '',
399
+ timestamp: '',
400
+ metadata: { userOpened: true },
401
+ },
402
+ ]
403
+
404
+ const result = autoCollapsePreviousMessages(messages, 'ai-new')
405
+ expect(result[0].metadata?.isCollapsed).toBeUndefined()
406
+ })
407
+ })
408
+
409
+ // ============================================================================
410
+ // Stream Chunk Processing Tests (from block-operations)
411
+ // ============================================================================
412
+
413
+ describe('appendTextToRootStream', () => {
414
+ test('creates new text block for empty blocks array', () => {
415
+ const result = appendTextToRootStream([], { type: 'text', text: 'Hello' })
416
+
417
+ expect(result).toHaveLength(1)
418
+ expect(result[0].type).toBe('text')
419
+ expect((result[0] as TextContentBlock).content).toBe('Hello')
420
+ })
421
+
422
+ test('appends to existing text block of same type', () => {
423
+ const blocks: ContentBlock[] = [
424
+ { type: 'text', content: 'Hello', textType: 'text' },
425
+ ]
426
+
427
+ const result = appendTextToRootStream(blocks, {
428
+ type: 'text',
429
+ text: ' World',
430
+ })
431
+
432
+ expect(result).toHaveLength(1)
433
+ expect((result[0] as TextContentBlock).content).toBe('Hello World')
434
+ })
435
+
436
+ test('creates new block for different text type', () => {
437
+ const blocks: ContentBlock[] = [
438
+ { type: 'text', content: 'Hello', textType: 'text' },
439
+ ]
440
+
441
+ const result = appendTextToRootStream(blocks, {
442
+ type: 'reasoning',
443
+ text: 'Thinking...',
444
+ })
445
+
446
+ expect(result).toHaveLength(2)
447
+ expect((result[1] as TextContentBlock).textType).toBe('reasoning')
448
+ expect((result[1] as TextContentBlock).thinkingCollapseState).toBe(
449
+ 'preview',
450
+ )
451
+ })
452
+
453
+ test('returns original blocks for empty text', () => {
454
+ const blocks: ContentBlock[] = [{ type: 'text', content: 'Hello' }]
455
+
456
+ const result = appendTextToRootStream(blocks, { type: 'text', text: '' })
457
+
458
+ expect(result).toBe(blocks)
459
+ })
460
+
461
+ // Think tag parsing tests
462
+ test('handles unclosed think tag', () => {
463
+ const result = appendTextToRootStream([], {
464
+ type: 'text',
465
+ text: 'Before <think>unclosed thoughts',
466
+ })
467
+
468
+ expect(result).toHaveLength(2)
469
+ expect((result[0] as TextContentBlock).content).toBe('Before ')
470
+ expect((result[1] as TextContentBlock).content).toBe('unclosed thoughts')
471
+ expect((result[1] as TextContentBlock).textType).toBe('reasoning')
472
+ expect((result[1] as TextContentBlock).thinkingOpen).toBe(true)
473
+ })
474
+
475
+ test('continues appending to open thinking block', () => {
476
+ const blocks: ContentBlock[] = [
477
+ {
478
+ type: 'text',
479
+ content: 'initial thoughts',
480
+ textType: 'reasoning',
481
+ isCollapsed: true,
482
+ thinkingOpen: true,
483
+ },
484
+ ]
485
+
486
+ const result = appendTextToRootStream(blocks, {
487
+ type: 'text',
488
+ text: ' more thoughts',
489
+ })
490
+
491
+ expect(result).toHaveLength(1)
492
+ expect((result[0] as TextContentBlock).content).toBe(
493
+ 'initial thoughts more thoughts',
494
+ )
495
+ expect((result[0] as TextContentBlock).textType).toBe('reasoning')
496
+ })
497
+
498
+ test('closes thinking block when close tag received', () => {
499
+ const blocks: ContentBlock[] = [
500
+ {
501
+ type: 'text',
502
+ content: 'initial thoughts',
503
+ textType: 'reasoning',
504
+ isCollapsed: true,
505
+ thinkingOpen: true,
506
+ },
507
+ ]
508
+
509
+ const result = appendTextToRootStream(blocks, {
510
+ type: 'text',
511
+ text: ' final</think> regular text',
512
+ })
513
+
514
+ expect(result).toHaveLength(2)
515
+ expect((result[0] as TextContentBlock).content).toBe(
516
+ 'initial thoughts final',
517
+ )
518
+ expect((result[0] as TextContentBlock).textType).toBe('reasoning')
519
+ expect((result[0] as TextContentBlock).thinkingOpen).toBe(false)
520
+ expect((result[1] as TextContentBlock).content).toBe(' regular text')
521
+ expect((result[1] as TextContentBlock).textType).toBe('text')
522
+ })
523
+
524
+ test('text without think tags works normally', () => {
525
+ const result = appendTextToRootStream([], {
526
+ type: 'text',
527
+ text: 'Just regular text without tags',
528
+ })
529
+
530
+ expect(result).toHaveLength(1)
531
+ expect((result[0] as TextContentBlock).content).toBe(
532
+ 'Just regular text without tags',
533
+ )
534
+ expect((result[0] as TextContentBlock).textType).toBe('text')
535
+ })
536
+
537
+ test('closes thinking block when receiving just </think> tag', () => {
538
+ const blocks: ContentBlock[] = [
539
+ {
540
+ type: 'text',
541
+ content: 'thoughts',
542
+ textType: 'reasoning',
543
+ isCollapsed: true,
544
+ thinkingOpen: true,
545
+ },
546
+ ]
547
+
548
+ const result = appendTextToRootStream(blocks, {
549
+ type: 'text',
550
+ text: '</think>',
551
+ })
552
+
553
+ expect(result).toHaveLength(1)
554
+ expect((result[0] as TextContentBlock).content).toBe('thoughts')
555
+ expect((result[0] as TextContentBlock).textType).toBe('reasoning')
556
+ expect((result[0] as TextContentBlock).thinkingOpen).toBe(false)
557
+ })
558
+
559
+ test('closes thinking block and adds text after </think>', () => {
560
+ const blocks: ContentBlock[] = [
561
+ {
562
+ type: 'text',
563
+ content: 'thoughts',
564
+ textType: 'reasoning',
565
+ isCollapsed: true,
566
+ thinkingOpen: true,
567
+ },
568
+ ]
569
+
570
+ const result = appendTextToRootStream(blocks, {
571
+ type: 'text',
572
+ text: '</think>after',
573
+ })
574
+
575
+ expect(result).toHaveLength(2)
576
+ expect((result[0] as TextContentBlock).content).toBe('thoughts')
577
+ expect((result[0] as TextContentBlock).textType).toBe('reasoning')
578
+ expect((result[0] as TextContentBlock).thinkingOpen).toBe(false)
579
+ expect((result[1] as TextContentBlock).content).toBe('after')
580
+ expect((result[1] as TextContentBlock).textType).toBe('text')
581
+ })
582
+
583
+ // Streaming simulation tests
584
+ test('streaming: does not create duplicate block when closing existing thinking block', () => {
585
+ // Simulate streaming: first chunk opens thinking, second chunk closes it
586
+ // First chunk: '<think>My thoughts' creates open thinking block
587
+ const afterFirstChunk = appendTextToRootStream([], {
588
+ type: 'text',
589
+ text: '<think>My thoughts',
590
+ })
591
+
592
+ expect(afterFirstChunk).toHaveLength(1)
593
+ expect((afterFirstChunk[0] as TextContentBlock).textType).toBe('reasoning')
594
+ expect((afterFirstChunk[0] as TextContentBlock).content).toBe('My thoughts')
595
+ expect((afterFirstChunk[0] as TextContentBlock).thinkingOpen).toBe(true)
596
+
597
+ // Second chunk: '</think> after' should close the block, not create a duplicate
598
+ const afterSecondChunk = appendTextToRootStream(afterFirstChunk, {
599
+ type: 'text',
600
+ text: '</think> after',
601
+ })
602
+
603
+ expect(afterSecondChunk).toHaveLength(2)
604
+ expect((afterSecondChunk[0] as TextContentBlock).textType).toBe('reasoning')
605
+ expect((afterSecondChunk[0] as TextContentBlock).content).toBe(
606
+ 'My thoughts',
607
+ )
608
+ expect((afterSecondChunk[0] as TextContentBlock).thinkingOpen).toBe(false)
609
+ expect((afterSecondChunk[1] as TextContentBlock).textType).toBe('text')
610
+ expect((afterSecondChunk[1] as TextContentBlock).content).toBe(' after')
611
+ })
612
+
613
+ // Native reasoning tests
614
+ test('closes native reasoning block when text arrives', () => {
615
+ // Native reasoning block (thinkingOpen === undefined)
616
+ const blocks: ContentBlock[] = [
617
+ {
618
+ type: 'text',
619
+ content: 'Thinking...',
620
+ textType: 'reasoning',
621
+ isCollapsed: true,
622
+ thinkingId: 'think-1',
623
+ // Note: thinkingOpen is undefined for native reasoning
624
+ },
625
+ ]
626
+
627
+ const result = appendTextToRootStream(blocks, {
628
+ type: 'text',
629
+ text: 'Regular text',
630
+ })
631
+
632
+ expect(result).toHaveLength(2)
633
+ // Native reasoning block should be closed
634
+ expect((result[0] as TextContentBlock).thinkingOpen).toBe(false)
635
+ // New text block added
636
+ expect((result[1] as TextContentBlock).content).toBe('Regular text')
637
+ expect((result[1] as TextContentBlock).textType).toBe('text')
638
+ })
639
+
640
+ test('appends to existing native reasoning block', () => {
641
+ const blocks: ContentBlock[] = [
642
+ {
643
+ type: 'text',
644
+ content: 'First thought',
645
+ textType: 'reasoning',
646
+ isCollapsed: true,
647
+ thinkingId: 'think-1',
648
+ // thinkingOpen is undefined for native reasoning
649
+ },
650
+ ]
651
+
652
+ const result = appendTextToRootStream(blocks, {
653
+ type: 'reasoning',
654
+ text: ' second thought',
655
+ })
656
+
657
+ expect(result).toHaveLength(1)
658
+ expect((result[0] as TextContentBlock).content).toBe(
659
+ 'First thought second thought',
660
+ )
661
+ expect((result[0] as TextContentBlock).textType).toBe('reasoning')
662
+ })
663
+ })
664
+
665
+ // ============================================================================
666
+ // Native Reasoning Block Tests (from block-operations)
667
+ // ============================================================================
668
+
669
+ describe('isNativeReasoningBlock', () => {
670
+ test('returns true for native reasoning block (thinkingOpen undefined)', () => {
671
+ const block: ContentBlock = {
672
+ type: 'text',
673
+ content: 'Thinking...',
674
+ textType: 'reasoning',
675
+ isCollapsed: true,
676
+ thinkingId: 'think-1',
677
+ }
678
+
679
+ expect(isNativeReasoningBlock(block)).toBe(true)
680
+ })
681
+
682
+ test('returns false for closed native reasoning block (thinkingOpen false)', () => {
683
+ const block: ContentBlock = {
684
+ type: 'text',
685
+ content: 'Thinking...',
686
+ textType: 'reasoning',
687
+ isCollapsed: true,
688
+ thinkingOpen: false,
689
+ thinkingId: 'think-1',
690
+ }
691
+
692
+ expect(isNativeReasoningBlock(block)).toBe(false)
693
+ })
694
+
695
+ test('returns false for <think> tag block (thinkingOpen true)', () => {
696
+ const block: ContentBlock = {
697
+ type: 'text',
698
+ content: 'Thinking...',
699
+ textType: 'reasoning',
700
+ isCollapsed: true,
701
+ thinkingOpen: true,
702
+ thinkingId: 'think-1',
703
+ }
704
+
705
+ expect(isNativeReasoningBlock(block)).toBe(false)
706
+ })
707
+
708
+ test('returns false for regular text block', () => {
709
+ const block: ContentBlock = {
710
+ type: 'text',
711
+ content: 'Hello',
712
+ textType: 'text',
713
+ }
714
+
715
+ expect(isNativeReasoningBlock(block)).toBe(false)
716
+ })
717
+
718
+ test('returns false for non-text blocks', () => {
719
+ const agentBlock: ContentBlock = {
720
+ type: 'agent',
721
+ agentId: 'agent-1',
722
+ agentName: 'Test',
723
+ agentType: 'test',
724
+ content: '',
725
+ status: 'running',
726
+ }
727
+
728
+ expect(isNativeReasoningBlock(agentBlock)).toBe(false)
729
+ })
730
+
731
+ test('returns false for undefined', () => {
732
+ expect(isNativeReasoningBlock(undefined)).toBe(false)
733
+ })
734
+ })
735
+
736
+ describe('closeNativeReasoningBlock', () => {
737
+ test('closes native reasoning block by setting thinkingOpen to false', () => {
738
+ const blocks: ContentBlock[] = [
739
+ {
740
+ type: 'text',
741
+ content: 'Thinking...',
742
+ textType: 'reasoning',
743
+ isCollapsed: true,
744
+ thinkingId: 'think-1',
745
+ },
746
+ ]
747
+
748
+ const result = closeNativeReasoningBlock(blocks)
749
+
750
+ expect(result).toHaveLength(1)
751
+ expect((result[0] as TextContentBlock).thinkingOpen).toBe(false)
752
+ expect((result[0] as TextContentBlock).content).toBe('Thinking...')
753
+ })
754
+
755
+ test('returns original blocks if no native reasoning block exists', () => {
756
+ const blocks: ContentBlock[] = [
757
+ { type: 'text', content: 'Hello', textType: 'text' },
758
+ ]
759
+
760
+ const result = closeNativeReasoningBlock(blocks)
761
+
762
+ expect(result).toBe(blocks) // Same reference
763
+ })
764
+
765
+ test('does not close already-closed reasoning blocks', () => {
766
+ const blocks: ContentBlock[] = [
767
+ {
768
+ type: 'text',
769
+ content: 'Already closed',
770
+ textType: 'reasoning',
771
+ isCollapsed: true,
772
+ thinkingOpen: false,
773
+ thinkingId: 'think-1',
774
+ },
775
+ ]
776
+
777
+ const result = closeNativeReasoningBlock(blocks)
778
+
779
+ expect(result).toBe(blocks) // Same reference, no change
780
+ })
781
+
782
+ test('does not close <think> tag blocks (thinkingOpen true)', () => {
783
+ const blocks: ContentBlock[] = [
784
+ {
785
+ type: 'text',
786
+ content: 'Think tag block',
787
+ textType: 'reasoning',
788
+ isCollapsed: true,
789
+ thinkingOpen: true,
790
+ thinkingId: 'think-1',
791
+ },
792
+ ]
793
+
794
+ const result = closeNativeReasoningBlock(blocks)
795
+
796
+ expect(result).toBe(blocks) // Same reference, no change
797
+ })
798
+
799
+ test('finds native reasoning block even when not at end', () => {
800
+ const blocks: ContentBlock[] = [
801
+ {
802
+ type: 'text',
803
+ content: 'Native reasoning',
804
+ textType: 'reasoning',
805
+ isCollapsed: true,
806
+ thinkingId: 'think-1',
807
+ },
808
+ {
809
+ type: 'agent',
810
+ agentId: 'agent-1',
811
+ agentName: 'Test',
812
+ agentType: 'test',
813
+ content: '',
814
+ status: 'running',
815
+ },
816
+ ]
817
+
818
+ const result = closeNativeReasoningBlock(blocks)
819
+
820
+ expect((result[0] as TextContentBlock).thinkingOpen).toBe(false)
821
+ expect(result[1]).toEqual(blocks[1]) // Agent block unchanged
822
+ })
823
+ })
824
+
825
+ describe('closeNativeReasoningInAgent', () => {
826
+ test('closes native reasoning in specific agent', () => {
827
+ const blocks: ContentBlock[] = [
828
+ {
829
+ type: 'agent',
830
+ agentId: 'agent-1',
831
+ agentName: 'Test',
832
+ agentType: 'test',
833
+ content: '',
834
+ status: 'running',
835
+ blocks: [
836
+ {
837
+ type: 'text',
838
+ content: 'Agent thinking...',
839
+ textType: 'reasoning',
840
+ isCollapsed: true,
841
+ thinkingId: 'think-1',
842
+ },
843
+ ],
844
+ },
845
+ ]
846
+
847
+ const result = closeNativeReasoningInAgent(blocks, 'agent-1')
848
+
849
+ const agentBlock = result[0] as AgentContentBlock
850
+ expect((agentBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
851
+ })
852
+
853
+ test('does not modify other agents', () => {
854
+ const blocks: ContentBlock[] = [
855
+ {
856
+ type: 'agent',
857
+ agentId: 'agent-1',
858
+ agentName: 'Test 1',
859
+ agentType: 'test',
860
+ content: '',
861
+ status: 'running',
862
+ blocks: [
863
+ {
864
+ type: 'text',
865
+ content: 'Agent 1 thinking...',
866
+ textType: 'reasoning',
867
+ isCollapsed: true,
868
+ thinkingId: 'think-1',
869
+ },
870
+ ],
871
+ },
872
+ {
873
+ type: 'agent',
874
+ agentId: 'agent-2',
875
+ agentName: 'Test 2',
876
+ agentType: 'test',
877
+ content: '',
878
+ status: 'running',
879
+ blocks: [
880
+ {
881
+ type: 'text',
882
+ content: 'Agent 2 thinking...',
883
+ textType: 'reasoning',
884
+ isCollapsed: true,
885
+ thinkingId: 'think-2',
886
+ },
887
+ ],
888
+ },
889
+ ]
890
+
891
+ const result = closeNativeReasoningInAgent(blocks, 'agent-1')
892
+
893
+ const agent1 = result[0] as AgentContentBlock
894
+ const agent2 = result[1] as AgentContentBlock
895
+ expect((agent1.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
896
+ // Agent 2 should still have undefined thinkingOpen
897
+ expect((agent2.blocks![0] as TextContentBlock).thinkingOpen).toBeUndefined()
898
+ })
899
+
900
+ test('returns original blocks if agent not found', () => {
901
+ const blocks: ContentBlock[] = [{ type: 'text', content: 'Hello' }]
902
+
903
+ const result = closeNativeReasoningInAgent(blocks, 'nonexistent')
904
+
905
+ expect(result).toBe(blocks)
906
+ })
907
+ })
908
+
909
+ describe('appendTextToAgentBlock with native reasoning', () => {
910
+ test('creates native reasoning block when textType is reasoning', () => {
911
+ const blocks: ContentBlock[] = [
912
+ {
913
+ type: 'agent',
914
+ agentId: 'agent-1',
915
+ agentName: 'Test',
916
+ agentType: 'test',
917
+ content: '',
918
+ status: 'running',
919
+ blocks: [],
920
+ },
921
+ ]
922
+
923
+ const result = appendTextToAgentBlock(
924
+ blocks,
925
+ 'agent-1',
926
+ 'Thinking...',
927
+ 'reasoning',
928
+ )
929
+
930
+ const agentBlock = result[0] as AgentContentBlock
931
+ expect(agentBlock.blocks).toHaveLength(1)
932
+ expect((agentBlock.blocks![0] as TextContentBlock).textType).toBe(
933
+ 'reasoning',
934
+ )
935
+ expect((agentBlock.blocks![0] as TextContentBlock).content).toBe(
936
+ 'Thinking...',
937
+ )
938
+ expect(
939
+ (agentBlock.blocks![0] as TextContentBlock).thinkingCollapseState,
940
+ ).toBe('preview')
941
+ // Native reasoning has thinkingOpen undefined
942
+ expect(
943
+ (agentBlock.blocks![0] as TextContentBlock).thinkingOpen,
944
+ ).toBeUndefined()
945
+ })
946
+
947
+ test('appends to existing open native reasoning block', () => {
948
+ const blocks: ContentBlock[] = [
949
+ {
950
+ type: 'agent',
951
+ agentId: 'agent-1',
952
+ agentName: 'Test',
953
+ agentType: 'test',
954
+ content: 'First',
955
+ status: 'running',
956
+ blocks: [
957
+ {
958
+ type: 'text',
959
+ content: 'First',
960
+ textType: 'reasoning',
961
+ isCollapsed: true,
962
+ thinkingId: 'think-1',
963
+ },
964
+ ],
965
+ },
966
+ ]
967
+
968
+ const result = appendTextToAgentBlock(
969
+ blocks,
970
+ 'agent-1',
971
+ ' second',
972
+ 'reasoning',
973
+ )
974
+
975
+ const agentBlock = result[0] as AgentContentBlock
976
+ expect(agentBlock.blocks).toHaveLength(1)
977
+ expect((agentBlock.blocks![0] as TextContentBlock).content).toBe(
978
+ 'First second',
979
+ )
980
+ })
981
+
982
+ test('does NOT append to closed native reasoning block', () => {
983
+ const blocks: ContentBlock[] = [
984
+ {
985
+ type: 'agent',
986
+ agentId: 'agent-1',
987
+ agentName: 'Test',
988
+ agentType: 'test',
989
+ content: 'Closed',
990
+ status: 'running',
991
+ blocks: [
992
+ {
993
+ type: 'text',
994
+ content: 'Closed',
995
+ textType: 'reasoning',
996
+ isCollapsed: true,
997
+ thinkingOpen: false, // Already closed
998
+ thinkingId: 'think-1',
999
+ },
1000
+ ],
1001
+ },
1002
+ ]
1003
+
1004
+ const result = appendTextToAgentBlock(
1005
+ blocks,
1006
+ 'agent-1',
1007
+ 'New thought',
1008
+ 'reasoning',
1009
+ )
1010
+
1011
+ const agentBlock = result[0] as AgentContentBlock
1012
+ // Should create a NEW reasoning block, not append to closed one
1013
+ expect(agentBlock.blocks).toHaveLength(2)
1014
+ expect((agentBlock.blocks![0] as TextContentBlock).content).toBe('Closed')
1015
+ expect((agentBlock.blocks![1] as TextContentBlock).content).toBe(
1016
+ 'New thought',
1017
+ )
1018
+ })
1019
+
1020
+ test('does NOT append to <think> tag block', () => {
1021
+ const blocks: ContentBlock[] = [
1022
+ {
1023
+ type: 'agent',
1024
+ agentId: 'agent-1',
1025
+ agentName: 'Test',
1026
+ agentType: 'test',
1027
+ content: 'Think tag',
1028
+ status: 'running',
1029
+ blocks: [
1030
+ {
1031
+ type: 'text',
1032
+ content: 'Think tag',
1033
+ textType: 'reasoning',
1034
+ isCollapsed: true,
1035
+ thinkingOpen: true, // <think> tag block
1036
+ thinkingId: 'think-1',
1037
+ },
1038
+ ],
1039
+ },
1040
+ ]
1041
+
1042
+ const result = appendTextToAgentBlock(
1043
+ blocks,
1044
+ 'agent-1',
1045
+ 'Native thought',
1046
+ 'reasoning',
1047
+ )
1048
+
1049
+ const agentBlock = result[0] as AgentContentBlock
1050
+ // Should create a NEW native reasoning block, not append to <think> block
1051
+ expect(agentBlock.blocks).toHaveLength(2)
1052
+ expect((agentBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(true)
1053
+ expect(
1054
+ (agentBlock.blocks![1] as TextContentBlock).thinkingOpen,
1055
+ ).toBeUndefined()
1056
+ })
1057
+
1058
+ test('closes native reasoning when regular text arrives', () => {
1059
+ const blocks: ContentBlock[] = [
1060
+ {
1061
+ type: 'agent',
1062
+ agentId: 'agent-1',
1063
+ agentName: 'Test',
1064
+ agentType: 'test',
1065
+ content: 'Thinking',
1066
+ status: 'running',
1067
+ blocks: [
1068
+ {
1069
+ type: 'text',
1070
+ content: 'Thinking',
1071
+ textType: 'reasoning',
1072
+ isCollapsed: true,
1073
+ thinkingId: 'think-1',
1074
+ },
1075
+ ],
1076
+ },
1077
+ ]
1078
+
1079
+ const result = appendTextToAgentBlock(
1080
+ blocks,
1081
+ 'agent-1',
1082
+ 'Regular text',
1083
+ 'text',
1084
+ )
1085
+
1086
+ const agentBlock = result[0] as AgentContentBlock
1087
+ expect(agentBlock.blocks).toHaveLength(2)
1088
+ // Native reasoning should be closed
1089
+ expect((agentBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
1090
+ // New text block added
1091
+ expect((agentBlock.blocks![1] as TextContentBlock).content).toBe(
1092
+ 'Regular text',
1093
+ )
1094
+ expect((agentBlock.blocks![1] as TextContentBlock).textType).toBe('text')
1095
+ })
1096
+ })
1097
+
1098
+ describe('appendToolToAgentBlock closes native reasoning', () => {
1099
+ test('closes native reasoning when tool is appended', () => {
1100
+ const blocks: ContentBlock[] = [
1101
+ {
1102
+ type: 'agent',
1103
+ agentId: 'agent-1',
1104
+ agentName: 'Test',
1105
+ agentType: 'test',
1106
+ content: 'Thinking',
1107
+ status: 'running',
1108
+ blocks: [
1109
+ {
1110
+ type: 'text',
1111
+ content: 'Thinking',
1112
+ textType: 'reasoning',
1113
+ isCollapsed: true,
1114
+ thinkingId: 'think-1',
1115
+ },
1116
+ ],
1117
+ },
1118
+ ]
1119
+
1120
+ const toolBlock: ToolContentBlock = {
1121
+ type: 'tool',
1122
+ toolCallId: 'tool-1',
1123
+ toolName: 'read_files',
1124
+ input: { paths: ['test.ts'] },
1125
+ }
1126
+
1127
+ const result = appendToolToAgentBlock(blocks, 'agent-1', toolBlock)
1128
+
1129
+ const agentBlock = result[0] as AgentContentBlock
1130
+ expect(agentBlock.blocks).toHaveLength(2)
1131
+ // Native reasoning should be closed
1132
+ expect((agentBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
1133
+ // Tool block added
1134
+ expect(agentBlock.blocks![1].type).toBe('tool')
1135
+ })
1136
+ })
1137
+
1138
+ describe('markAgentComplete closes native reasoning', () => {
1139
+ test('closes native reasoning when agent completes', () => {
1140
+ const blocks: ContentBlock[] = [
1141
+ {
1142
+ type: 'agent',
1143
+ agentId: 'agent-1',
1144
+ agentName: 'Test',
1145
+ agentType: 'test',
1146
+ content: 'Thinking',
1147
+ status: 'running',
1148
+ blocks: [
1149
+ {
1150
+ type: 'text',
1151
+ content: 'Thinking',
1152
+ textType: 'reasoning',
1153
+ isCollapsed: true,
1154
+ thinkingId: 'think-1',
1155
+ },
1156
+ ],
1157
+ },
1158
+ ]
1159
+
1160
+ const result = markAgentComplete(blocks, 'agent-1')
1161
+
1162
+ const agentBlock = result[0] as AgentContentBlock
1163
+ expect(agentBlock.status).toBe('complete')
1164
+ expect((agentBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
1165
+ })
1166
+ })
1167
+
1168
+ describe('markRunningAgentsAsCancelled closes native reasoning', () => {
1169
+ test('closes native reasoning in cancelled agents', () => {
1170
+ const blocks: ContentBlock[] = [
1171
+ {
1172
+ type: 'agent',
1173
+ agentId: 'agent-1',
1174
+ agentName: 'Test',
1175
+ agentType: 'test',
1176
+ content: 'Thinking',
1177
+ status: 'running',
1178
+ blocks: [
1179
+ {
1180
+ type: 'text',
1181
+ content: 'Thinking',
1182
+ textType: 'reasoning',
1183
+ isCollapsed: true,
1184
+ thinkingId: 'think-1',
1185
+ },
1186
+ ],
1187
+ },
1188
+ ]
1189
+
1190
+ const result = markRunningAgentsAsCancelled(blocks)
1191
+
1192
+ const agentBlock = result[0] as AgentContentBlock
1193
+ expect(agentBlock.status).toBe('cancelled')
1194
+ expect((agentBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
1195
+ })
1196
+
1197
+ test('closes native reasoning in nested cancelled agents', () => {
1198
+ const blocks: ContentBlock[] = [
1199
+ {
1200
+ type: 'agent',
1201
+ agentId: 'parent',
1202
+ agentName: 'Parent',
1203
+ agentType: 'parent',
1204
+ content: '',
1205
+ status: 'running',
1206
+ blocks: [
1207
+ {
1208
+ type: 'agent',
1209
+ agentId: 'child',
1210
+ agentName: 'Child',
1211
+ agentType: 'child',
1212
+ content: 'Child thinking',
1213
+ status: 'running',
1214
+ blocks: [
1215
+ {
1216
+ type: 'text',
1217
+ content: 'Child thinking',
1218
+ textType: 'reasoning',
1219
+ isCollapsed: true,
1220
+ thinkingId: 'think-child',
1221
+ },
1222
+ ],
1223
+ },
1224
+ ],
1225
+ },
1226
+ ]
1227
+
1228
+ const result = markRunningAgentsAsCancelled(blocks)
1229
+
1230
+ const parentBlock = result[0] as AgentContentBlock
1231
+ const childBlock = parentBlock.blocks![0] as AgentContentBlock
1232
+
1233
+ expect(parentBlock.status).toBe('cancelled')
1234
+ expect(childBlock.status).toBe('cancelled')
1235
+ expect((childBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
1236
+ })
1237
+
1238
+ test('closes native reasoning even in non-running agents during cancellation', () => {
1239
+ const blocks: ContentBlock[] = [
1240
+ {
1241
+ type: 'agent',
1242
+ agentId: 'agent-1',
1243
+ agentName: 'Test',
1244
+ agentType: 'test',
1245
+ content: '',
1246
+ status: 'complete', // Already complete
1247
+ blocks: [
1248
+ {
1249
+ type: 'agent',
1250
+ agentId: 'child',
1251
+ agentName: 'Child',
1252
+ agentType: 'child',
1253
+ content: 'Thinking',
1254
+ status: 'running',
1255
+ blocks: [
1256
+ {
1257
+ type: 'text',
1258
+ content: 'Thinking',
1259
+ textType: 'reasoning',
1260
+ isCollapsed: true,
1261
+ thinkingId: 'think-1',
1262
+ },
1263
+ ],
1264
+ },
1265
+ ],
1266
+ },
1267
+ ]
1268
+
1269
+ const result = markRunningAgentsAsCancelled(blocks)
1270
+
1271
+ const parentBlock = result[0] as AgentContentBlock
1272
+ const childBlock = parentBlock.blocks![0] as AgentContentBlock
1273
+
1274
+ // Parent stays complete
1275
+ expect(parentBlock.status).toBe('complete')
1276
+ // Child is cancelled
1277
+ expect(childBlock.status).toBe('cancelled')
1278
+ // Child's reasoning is closed
1279
+ expect((childBlock.blocks![0] as TextContentBlock).thinkingOpen).toBe(false)
1280
+ })
1281
+
1282
+ test('does not modify agents without native reasoning blocks', () => {
1283
+ const blocks: ContentBlock[] = [
1284
+ {
1285
+ type: 'agent',
1286
+ agentId: 'agent-1',
1287
+ agentName: 'Test',
1288
+ agentType: 'test',
1289
+ content: 'Hello',
1290
+ status: 'running',
1291
+ blocks: [{ type: 'text', content: 'Hello', textType: 'text' }],
1292
+ },
1293
+ ]
1294
+
1295
+ const result = markRunningAgentsAsCancelled(blocks)
1296
+
1297
+ const agentBlock = result[0] as AgentContentBlock
1298
+ expect(agentBlock.status).toBe('cancelled')
1299
+ // Text block should be unchanged
1300
+ expect(
1301
+ (agentBlock.blocks![0] as TextContentBlock).thinkingOpen,
1302
+ ).toBeUndefined()
1303
+ })
1304
+ })
1305
+
1306
+ describe('extractPlanFromBuffer', () => {
1307
+ test('extracts plan content from complete tags', () => {
1308
+ const buffer = 'Some text <PLAN>This is the plan</PLAN> more text'
1309
+
1310
+ const result = extractPlanFromBuffer(buffer)
1311
+
1312
+ expect(result).toBe('This is the plan')
1313
+ })
1314
+
1315
+ test('returns null for incomplete plan', () => {
1316
+ const buffer = 'Some text <PLAN>Incomplete plan'
1317
+
1318
+ expect(extractPlanFromBuffer(buffer)).toBeNull()
1319
+ })
1320
+
1321
+ test('returns null when no plan tags exist', () => {
1322
+ expect(extractPlanFromBuffer('No plan here')).toBeNull()
1323
+ })
1324
+
1325
+ test('trims whitespace from extracted plan', () => {
1326
+ const buffer = '<PLAN> Trimmed plan </PLAN>'
1327
+
1328
+ expect(extractPlanFromBuffer(buffer)).toBe('Trimmed plan')
1329
+ })
1330
+ })
1331
+
1332
+ // ============================================================================
1333
+ // Agent Block Helpers Tests (from message-block-helpers)
1334
+ // ============================================================================
1335
+
1336
+ describe('createAgentBlock', () => {
1337
+ test('creates an agent block with required fields', () => {
1338
+ const block = createAgentBlock({
1339
+ agentId: 'agent-1',
1340
+ agentType: 'file-picker',
1341
+ })
1342
+
1343
+ expect(block.type).toBe('agent')
1344
+ expect(block.agentId).toBe('agent-1')
1345
+ expect(block.agentType).toBe('file-picker')
1346
+ expect(block.status).toBe('running')
1347
+ expect(block.content).toBe('')
1348
+ })
1349
+
1350
+ test('includes optional prompt', () => {
1351
+ const block = createAgentBlock({
1352
+ agentId: 'agent-1',
1353
+ agentType: 'file-picker',
1354
+ prompt: 'Find files',
1355
+ })
1356
+
1357
+ expect(block.initialPrompt).toBe('Find files')
1358
+ })
1359
+
1360
+ test('includes optional params', () => {
1361
+ const block = createAgentBlock({
1362
+ agentId: 'agent-1',
1363
+ agentType: 'file-picker',
1364
+ params: { path: '/src' },
1365
+ })
1366
+
1367
+ expect(block.params).toEqual({ path: '/src' })
1368
+ })
1369
+ })
1370
+
1371
+ describe('getAgentBaseName', () => {
1372
+ test('extracts base name from scoped versioned name', () => {
1373
+ expect(getAgentBaseName('anvil/file-picker@0.0.2')).toBe('file-picker')
1374
+ })
1375
+
1376
+ test('extracts base name from simple versioned name', () => {
1377
+ expect(getAgentBaseName('file-picker@1.0.0')).toBe('file-picker')
1378
+ })
1379
+
1380
+ test('returns simple name unchanged', () => {
1381
+ expect(getAgentBaseName('file-picker')).toBe('file-picker')
1382
+ })
1383
+
1384
+ test('normalizes direct tool aliases to canonical agent names', () => {
1385
+ expect(getAgentBaseName('code_reviewer_lite')).toBe('code-reviewer-lite')
1386
+ })
1387
+ })
1388
+
1389
+ describe('agentTypesMatch', () => {
1390
+ test('matches same base names with different versions', () => {
1391
+ expect(
1392
+ getAgentBaseName('anvil/file-picker@0.0.2') ===
1393
+ getAgentBaseName('file-picker@1.0.0'),
1394
+ ).toBe(true)
1395
+ })
1396
+
1397
+ test('matches same simple names', () => {
1398
+ expect(
1399
+ getAgentBaseName('file-picker') === getAgentBaseName('file-picker'),
1400
+ ).toBe(true)
1401
+ })
1402
+
1403
+ test('does not match different base names', () => {
1404
+ expect(
1405
+ getAgentBaseName('file-picker') === getAgentBaseName('code-searcher'),
1406
+ ).toBe(false)
1407
+ })
1408
+ })
1409
+
1410
+ // ============================================================================
1411
+ // Tool Block Helpers Tests (from message-block-helpers)
1412
+ // ============================================================================
1413
+
1414
+ describe('updateToolBlockWithOutput', () => {
1415
+ test('updates tool block with output', () => {
1416
+ const blocks: ContentBlock[] = [
1417
+ {
1418
+ type: 'tool',
1419
+ toolCallId: 'tool-1',
1420
+ toolName: 'read_files',
1421
+ input: {},
1422
+ },
1423
+ ]
1424
+
1425
+ const result = updateToolBlockWithOutput(blocks, {
1426
+ toolCallId: 'tool-1',
1427
+ toolOutput: ['File contents'],
1428
+ })
1429
+
1430
+ expect((result[0] as ToolContentBlock).output).toBe('File contents')
1431
+ })
1432
+
1433
+ test('updates nested tool block', () => {
1434
+ const blocks: ContentBlock[] = [
1435
+ {
1436
+ type: 'agent',
1437
+ agentId: 'agent-1',
1438
+ agentName: 'Test',
1439
+ agentType: 'test',
1440
+ content: '',
1441
+ status: 'running',
1442
+ blocks: [
1443
+ {
1444
+ type: 'tool',
1445
+ toolCallId: 'tool-1',
1446
+ toolName: 'read_files',
1447
+ input: {},
1448
+ },
1449
+ ],
1450
+ },
1451
+ ]
1452
+
1453
+ const result = updateToolBlockWithOutput(blocks, {
1454
+ toolCallId: 'tool-1',
1455
+ toolOutput: ['File contents'],
1456
+ })
1457
+ const agent = result[0] as AgentContentBlock
1458
+ expect((agent.blocks![0] as ToolContentBlock).output).toBe('File contents')
1459
+ })
1460
+
1461
+ test('returns same reference if no match', () => {
1462
+ const blocks: ContentBlock[] = [{ type: 'text', content: 'Hello' }]
1463
+
1464
+ const result = updateToolBlockWithOutput(blocks, {
1465
+ toolCallId: 'tool-1',
1466
+ toolOutput: ['Output'],
1467
+ })
1468
+
1469
+ expect(result).toEqual(blocks)
1470
+ })
1471
+ })
1472
+
1473
+ // ============================================================================
1474
+ // Ask User Transformation Tests (from message-block-helpers)
1475
+ // ============================================================================
1476
+
1477
+ describe('transformAskUserBlocks', () => {
1478
+ test('transforms ask_user tool block to ask-user block', () => {
1479
+ const blocks: ContentBlock[] = [
1480
+ {
1481
+ type: 'tool',
1482
+ toolCallId: 'tool-1',
1483
+ toolName: 'ask_user',
1484
+ input: { questions: [{ question: 'Choose?', options: ['A', 'B'] }] },
1485
+ },
1486
+ ]
1487
+
1488
+ const result = transformAskUserBlocks(blocks, {
1489
+ toolCallId: 'tool-1',
1490
+ resultValue: { answers: [{ questionIndex: 0, selectedOption: 'A' }] },
1491
+ })
1492
+
1493
+ expect(result[0].type).toBe('ask-user')
1494
+ expect((result[0] as AskUserContentBlock).answers).toEqual([
1495
+ { questionIndex: 0, selectedOption: 'A' },
1496
+ ])
1497
+ })
1498
+
1499
+ test('keeps tool block if no answers or skipped', () => {
1500
+ const blocks: ContentBlock[] = [
1501
+ {
1502
+ type: 'tool',
1503
+ toolCallId: 'tool-1',
1504
+ toolName: 'ask_user',
1505
+ input: { questions: [] },
1506
+ },
1507
+ ]
1508
+
1509
+ const result = transformAskUserBlocks(blocks, {
1510
+ toolCallId: 'tool-1',
1511
+ resultValue: {},
1512
+ })
1513
+
1514
+ expect(result[0].type).toBe('tool')
1515
+ })
1516
+
1517
+ test('handles skipped state', () => {
1518
+ const blocks: ContentBlock[] = [
1519
+ {
1520
+ type: 'tool',
1521
+ toolCallId: 'tool-1',
1522
+ toolName: 'ask_user',
1523
+ input: { questions: [] },
1524
+ },
1525
+ ]
1526
+
1527
+ const result = transformAskUserBlocks(blocks, {
1528
+ toolCallId: 'tool-1',
1529
+ resultValue: { skipped: true },
1530
+ })
1531
+
1532
+ expect(result[0].type).toBe('ask-user')
1533
+ expect((result[0] as AskUserContentBlock).skipped).toBe(true)
1534
+ })
1535
+ })
1536
+
1537
+ // ============================================================================
1538
+ // Interruption Handling Tests (from message-block-helpers)
1539
+ // ============================================================================
1540
+
1541
+ describe('appendInterruptionNotice', () => {
1542
+ test('appends to existing text block', () => {
1543
+ const blocks: ContentBlock[] = [
1544
+ { type: 'text', content: 'Partial response' },
1545
+ ]
1546
+
1547
+ const result = appendInterruptionNotice(blocks)
1548
+
1549
+ expect((result[0] as TextContentBlock).content).toBe(
1550
+ 'Partial response\n\n[response interrupted]',
1551
+ )
1552
+ })
1553
+
1554
+ test('creates new text block if no existing text', () => {
1555
+ const blocks: ContentBlock[] = []
1556
+
1557
+ const result = appendInterruptionNotice(blocks)
1558
+
1559
+ expect(result).toHaveLength(1)
1560
+ expect((result[0] as TextContentBlock).content).toBe(
1561
+ '[response interrupted]',
1562
+ )
1563
+ })
1564
+
1565
+ test('creates new block if last block is not text', () => {
1566
+ const blocks: ContentBlock[] = [
1567
+ {
1568
+ type: 'tool',
1569
+ toolCallId: 'tool-1',
1570
+ toolName: 'read_files',
1571
+ input: {},
1572
+ },
1573
+ ]
1574
+
1575
+ const result = appendInterruptionNotice(blocks)
1576
+
1577
+ expect(result).toHaveLength(2)
1578
+ expect(result[1].type).toBe('text')
1579
+ })
1580
+ })
1581
+
1582
+ // ============================================================================
1583
+ // Spawn Agents Helpers Tests (from send-message-helpers)
1584
+ // ============================================================================
1585
+
1586
+ describe('createSpawnAgentBlocks', () => {
1587
+ test('creates agent blocks from spawn_agents input', () => {
1588
+ const agents = [
1589
+ { agent_type: 'file-picker', prompt: 'Find files' },
1590
+ { agent_type: 'code-searcher', prompt: 'Search code' },
1591
+ ]
1592
+
1593
+ const result = createSpawnAgentBlocks('tool-1', agents)
1594
+
1595
+ expect(result).toHaveLength(2)
1596
+ expect(result[0].type).toBe('agent')
1597
+ expect((result[0] as AgentContentBlock).agentId).toBe('tool-1-0')
1598
+ expect((result[1] as AgentContentBlock).agentId).toBe('tool-1-1')
1599
+ })
1600
+
1601
+ test('filters out hidden agents', () => {
1602
+ const agents = [
1603
+ { agent_type: 'file-picker' },
1604
+ { agent_type: 'context-pruner' }, // bundled id — hidden
1605
+ { agent_type: 'anvil/context-pruner' }, // publisher-qualified — hidden
1606
+ ]
1607
+
1608
+ const result = createSpawnAgentBlocks('tool-1', agents)
1609
+
1610
+ expect(result).toHaveLength(1)
1611
+ expect((result[0] as AgentContentBlock).agentType).toBe('file-picker')
1612
+ })
1613
+ })
1614
+
1615
+ describe('isSpawnAgentsResult', () => {
1616
+ test('returns true for spawn_agents result structure', () => {
1617
+ const output = [{ agentName: 'file-picker', value: 'result' }]
1618
+
1619
+ expect(isSpawnAgentsResult(output)).toBe(true)
1620
+ })
1621
+
1622
+ test('returns false for non-array', () => {
1623
+ expect(isSpawnAgentsResult('string')).toBe(false)
1624
+ expect(isSpawnAgentsResult(null)).toBe(false)
1625
+ })
1626
+
1627
+ test('returns false for array without agent properties', () => {
1628
+ expect(isSpawnAgentsResult([{ foo: 'bar' }])).toBe(false)
1629
+ })
1630
+ })
1631
+
1632
+ describe('extractSpawnAgentResultContent', () => {
1633
+ test('extracts string value directly', () => {
1634
+ const result = extractSpawnAgentResultContent('Simple result')
1635
+
1636
+ expect(result.content).toBe('Simple result')
1637
+ expect(result.hasError).toBe(false)
1638
+ })
1639
+
1640
+ test('extracts string from value property', () => {
1641
+ const result = extractSpawnAgentResultContent({ value: 'Nested string' })
1642
+
1643
+ expect(result.content).toBe('Nested string')
1644
+ expect(result.hasError).toBe(false)
1645
+ })
1646
+
1647
+ test('extracts error message', () => {
1648
+ const result = extractSpawnAgentResultContent({ errorMessage: 'Failed!' })
1649
+
1650
+ expect(result.content).toBe('Failed!')
1651
+ expect(result.hasError).toBe(true)
1652
+ })
1653
+
1654
+ test('extracts nested error message', () => {
1655
+ const result = extractSpawnAgentResultContent({
1656
+ value: { errorMessage: 'Nested error!' },
1657
+ })
1658
+
1659
+ expect(result.content).toBe('Nested error!')
1660
+ expect(result.hasError).toBe(true)
1661
+ })
1662
+
1663
+ test('extracts message property', () => {
1664
+ const result = extractSpawnAgentResultContent({
1665
+ message: 'Message content',
1666
+ })
1667
+
1668
+ expect(result.content).toBe('Message content')
1669
+ expect(result.hasError).toBe(false)
1670
+ })
1671
+
1672
+ test('extracts nested message property', () => {
1673
+ const result = extractSpawnAgentResultContent({
1674
+ value: { message: 'Nested message' },
1675
+ })
1676
+
1677
+ expect(result.content).toBe('Nested message')
1678
+ expect(result.hasError).toBe(false)
1679
+ })
1680
+
1681
+ test('returns empty for null/undefined', () => {
1682
+ const result = extractSpawnAgentResultContent(null)
1683
+
1684
+ expect(result.content).toBe('')
1685
+ expect(result.hasError).toBe(false)
1686
+ })
1687
+
1688
+ test('returns empty for empty object', () => {
1689
+ const result = extractSpawnAgentResultContent({})
1690
+
1691
+ expect(result.content).toBe('')
1692
+ expect(result.hasError).toBe(false)
1693
+ })
1694
+ })
1695
+
1696
+ // ============================================================================
1697
+ // Message Completion Helpers Tests (from send-message-helpers)
1698
+ // ============================================================================
1699
+
1700
+ describe('markMessageComplete', () => {
1701
+ const baseMessage: ChatMessage = {
1702
+ id: 'msg-1',
1703
+ variant: 'ai',
1704
+ content: 'Hello',
1705
+ timestamp: '',
1706
+ }
1707
+
1708
+ test('marks message as complete', () => {
1709
+ const result = markMessageComplete(baseMessage)
1710
+
1711
+ expect(result.isComplete).toBe(true)
1712
+ })
1713
+
1714
+ test('adds completion time', () => {
1715
+ const result = markMessageComplete(baseMessage, { completionTime: '5s' })
1716
+
1717
+ expect(result.completionTime).toBe('5s')
1718
+ })
1719
+
1720
+ test('adds credits', () => {
1721
+ const result = markMessageComplete(baseMessage, { credits: 100 })
1722
+
1723
+ expect(result.credits).toBe(100)
1724
+ })
1725
+
1726
+ test('adds runState to metadata', () => {
1727
+ const runState = { output: { type: 'text', text: 'Done' } }
1728
+ const result = markMessageComplete(baseMessage, { runState })
1729
+
1730
+ expect(result.metadata?.runState).toEqual(runState)
1731
+ })
1732
+
1733
+ test('preserves existing metadata', () => {
1734
+ const message: ChatMessage = {
1735
+ ...baseMessage,
1736
+ metadata: { userOpened: true },
1737
+ }
1738
+
1739
+ const result = markMessageComplete(message, { credits: 50 })
1740
+
1741
+ expect(result.metadata?.userOpened).toBe(true)
1742
+ })
1743
+ })
1744
+
1745
+ describe('setMessageError', () => {
1746
+ test('sets error content and clears blocks', () => {
1747
+ const message: ChatMessage = {
1748
+ id: 'msg-1',
1749
+ variant: 'ai',
1750
+ content: '',
1751
+ blocks: [{ type: 'text', content: 'Old content' }],
1752
+ timestamp: '',
1753
+ }
1754
+
1755
+ const result = setMessageError(message, 'Error occurred')
1756
+
1757
+ expect(result.content).toBe('Error occurred')
1758
+ expect(result.blocks).toBeUndefined()
1759
+ expect(result.isComplete).toBe(true)
1760
+ })
1761
+ })
1762
+
1763
+ // ============================================================================
1764
+ // sanitizeRestoredMessages Tests
1765
+ // ============================================================================
1766
+
1767
+ describe('sanitizeRestoredMessages', () => {
1768
+ const streamedShell = (
1769
+ overrides: Partial<ChatMessage> = {},
1770
+ ): ChatMessage => ({
1771
+ id: 'ai-1750000000000-abc123',
1772
+ variant: 'ai',
1773
+ content: '',
1774
+ timestamp: new Date().toISOString(),
1775
+ blocks: [{ type: 'text', content: 'partial answer' }],
1776
+ ...overrides,
1777
+ })
1778
+
1779
+ test('marks an interrupted AI response complete with an interruption notice', () => {
1780
+ const [result] = sanitizeRestoredMessages([streamedShell()])
1781
+
1782
+ expect(result.isComplete).toBe(true)
1783
+ const lastBlock = result.blocks![result.blocks!.length - 1]
1784
+ expect(lastBlock.type).toBe('text')
1785
+ expect((lastBlock as TextContentBlock).content).toContain(
1786
+ '[response interrupted]',
1787
+ )
1788
+ })
1789
+
1790
+ test('cancels running agent blocks in an interrupted AI response', () => {
1791
+ const [result] = sanitizeRestoredMessages([
1792
+ streamedShell({
1793
+ blocks: [
1794
+ {
1795
+ type: 'agent',
1796
+ agentId: 'agent-1',
1797
+ agentName: 'TestAgent',
1798
+ agentType: 'inline',
1799
+ content: '',
1800
+ status: 'running',
1801
+ blocks: [],
1802
+ },
1803
+ ],
1804
+ }),
1805
+ ])
1806
+
1807
+ const agentBlock = result.blocks![0] as AgentContentBlock
1808
+ expect(agentBlock.status).toBe('cancelled')
1809
+ })
1810
+
1811
+ test('adds a notice to an interrupted AI response with no blocks yet', () => {
1812
+ const [result] = sanitizeRestoredMessages([streamedShell({ blocks: [] })])
1813
+
1814
+ expect(result.isComplete).toBe(true)
1815
+ expect(result.blocks).toHaveLength(1)
1816
+ expect((result.blocks![0] as TextContentBlock).content).toBe(
1817
+ '[response interrupted]',
1818
+ )
1819
+ })
1820
+
1821
+ test('leaves completed AI responses untouched', () => {
1822
+ const message = streamedShell({ isComplete: true })
1823
+ const [result] = sanitizeRestoredMessages([message])
1824
+
1825
+ expect(result).toBe(message)
1826
+ })
1827
+
1828
+ test('strips the live inline-ad marker from restored responses', () => {
1829
+ const [result] = sanitizeRestoredMessages([
1830
+ streamedShell({
1831
+ isComplete: true,
1832
+ metadata: { allowInlineAds: true, userOpened: true },
1833
+ }),
1834
+ ])
1835
+
1836
+ expect(result.metadata).toEqual({ userOpened: true })
1837
+ })
1838
+
1839
+ test('drops persisted hidden agent blocks (context-pruner)', () => {
1840
+ const [result] = sanitizeRestoredMessages([
1841
+ streamedShell({
1842
+ isComplete: true,
1843
+ blocks: [
1844
+ {
1845
+ type: 'agent',
1846
+ agentId: 'agent-1',
1847
+ agentName: 'context-pruner',
1848
+ agentType: 'context-pruner',
1849
+ content: '',
1850
+ status: 'complete',
1851
+ },
1852
+ { type: 'text', content: 'answer' },
1853
+ ],
1854
+ }),
1855
+ ])
1856
+
1857
+ expect(result.blocks).toHaveLength(1)
1858
+ expect(result.blocks![0].type).toBe('text')
1859
+ })
1860
+
1861
+ test('leaves mode dividers, system messages, and user messages untouched', () => {
1862
+ const divider = createModeDividerMessage('DEFAULT' as any)
1863
+ const system: ChatMessage = {
1864
+ id: 'sys-123',
1865
+ variant: 'ai',
1866
+ content: 'system notice',
1867
+ timestamp: new Date().toISOString(),
1868
+ }
1869
+ const user: ChatMessage = {
1870
+ id: 'user-123',
1871
+ variant: 'user',
1872
+ content: 'hello',
1873
+ timestamp: new Date().toISOString(),
1874
+ }
1875
+
1876
+ const results = sanitizeRestoredMessages([divider, system, user])
1877
+
1878
+ expect(results[0]).toBe(divider)
1879
+ expect(results[1]).toBe(system)
1880
+ expect(results[2]).toBe(user)
1881
+ })
1882
+ })
1883
+
1884
+ describe('sanitizeRestoredMessages corruption tolerance', () => {
1885
+ test('does not throw on null entries in a restored blocks array', () => {
1886
+ const corrupted: ChatMessage = {
1887
+ id: 'ai-1750000000000-abc123',
1888
+ variant: 'ai',
1889
+ content: '',
1890
+ timestamp: new Date().toISOString(),
1891
+ blocks: [null as unknown as ContentBlock, { type: 'text', content: 'x' }],
1892
+ }
1893
+
1894
+ const [result] = sanitizeRestoredMessages([corrupted])
1895
+
1896
+ expect(result.isComplete).toBe(true)
1897
+ })
1898
+ })