@adecore/agents-react 0.23.1 → 0.24.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 (341) hide show
  1. package/README.md +14 -11
  2. package/dist/agents/AccountDot.js +3 -1
  3. package/dist/agents/accounts.d.ts +3 -2
  4. package/dist/agents/accounts.js +5 -6
  5. package/dist/chat/actions.d.ts +2 -2
  6. package/dist/chat/actions.js +8 -5
  7. package/dist/chat/bookmarks.d.ts +5 -3
  8. package/dist/chat/bookmarks.js +13 -14
  9. package/dist/chat/chat-client.d.ts +1 -0
  10. package/dist/chat/chat-client.js +7 -0
  11. package/dist/chat/composer-send.d.ts +3 -0
  12. package/dist/chat/composer-send.js +22 -0
  13. package/dist/chat/forks.js +22 -5
  14. package/dist/chat/index.d.ts +31 -0
  15. package/dist/chat/index.js +28 -0
  16. package/dist/chat/logic/embedded-code.d.ts +8 -0
  17. package/dist/chat/logic/embedded-code.js +371 -0
  18. package/dist/chat/logic/fork.js +1 -0
  19. package/dist/chat/logic/goal.d.ts +6 -0
  20. package/dist/chat/logic/goal.js +26 -0
  21. package/dist/chat/logic/scrubber.d.ts +1 -1
  22. package/dist/chat/logic/scrubber.js +6 -5
  23. package/dist/chat/logic/thought.d.ts +3 -0
  24. package/dist/chat/logic/thought.js +35 -0
  25. package/dist/chat/logic/thread-cards.js +2 -0
  26. package/dist/chat/logic/timeline.d.ts +5 -0
  27. package/dist/chat/logic/timeline.js +22 -1
  28. package/dist/chat/logic/tool-catalog.d.ts +1 -0
  29. package/dist/chat/logic/tool-catalog.js +3 -1
  30. package/dist/chat/logic/tools.d.ts +14 -0
  31. package/dist/chat/logic/tools.js +57 -0
  32. package/dist/chat/preferences.d.ts +6 -0
  33. package/dist/chat/preferences.js +19 -3
  34. package/dist/chat/reading-width.d.ts +9 -0
  35. package/dist/chat/reading-width.js +27 -0
  36. package/dist/chat/send-key.d.ts +10 -0
  37. package/dist/chat/send-key.js +24 -0
  38. package/dist/chat/ui/BookmarkMarker.js +4 -2
  39. package/dist/chat/ui/BookmarkSubmenu.js +4 -3
  40. package/dist/chat/ui/ChatActivity.js +14 -10
  41. package/dist/chat/ui/ChatReferenceChip.js +3 -4
  42. package/dist/chat/ui/CodeBlock.d.ts +2 -1
  43. package/dist/chat/ui/CodeBlock.js +14 -96
  44. package/dist/chat/ui/Composer.d.ts +1 -1
  45. package/dist/chat/ui/Composer.js +117 -906
  46. package/dist/chat/ui/ComposerInput.js +5 -4
  47. package/dist/chat/ui/EditDiff.js +3 -2
  48. package/dist/chat/ui/GoalDock.d.ts +9 -0
  49. package/dist/chat/ui/GoalDock.js +63 -0
  50. package/dist/chat/ui/LimitState.js +5 -3
  51. package/dist/chat/ui/Markdown.d.ts +2 -1
  52. package/dist/chat/ui/Markdown.js +70 -31
  53. package/dist/chat/ui/MermaidBlock.d.ts +3 -0
  54. package/dist/chat/ui/MermaidBlock.js +73 -0
  55. package/dist/chat/ui/MessageActions.js +12 -7
  56. package/dist/chat/ui/Pickers.js +6 -5
  57. package/dist/chat/ui/PromptComposer.js +4 -3
  58. package/dist/chat/ui/RowTime.d.ts +3 -0
  59. package/dist/chat/ui/RowTime.js +12 -0
  60. package/dist/chat/ui/RunSettings.js +5 -4
  61. package/dist/chat/ui/ShellCommand.d.ts +3 -0
  62. package/dist/chat/ui/ShellCommand.js +110 -0
  63. package/dist/chat/ui/SubagentInfo.js +4 -3
  64. package/dist/chat/ui/SubagentStopButton.js +4 -3
  65. package/dist/chat/ui/SubagentTimeline.js +4 -1
  66. package/dist/chat/ui/Timeline.js +70 -40
  67. package/dist/chat/ui/TimelineMenu.d.ts +2 -1
  68. package/dist/chat/ui/TimelineMenu.js +18 -8
  69. package/dist/chat/ui/UnifiedDiff.js +3 -2
  70. package/dist/chat/ui/VisualFrame.js +6 -7
  71. package/dist/chat/ui/code-theme.d.ts +2 -1
  72. package/dist/chat/ui/code-theme.js +4 -4
  73. package/dist/chat/ui/composer/ComposerControls.d.ts +27 -0
  74. package/dist/chat/ui/composer/ComposerControls.js +34 -0
  75. package/dist/chat/ui/composer/ComposerMenu.d.ts +4 -0
  76. package/dist/chat/ui/composer/ComposerMenu.js +46 -0
  77. package/dist/chat/ui/composer/DraftParts.d.ts +18 -0
  78. package/dist/chat/ui/composer/DraftParts.js +25 -0
  79. package/dist/chat/ui/composer/QueuedMessages.d.ts +10 -0
  80. package/dist/chat/ui/composer/QueuedMessages.js +20 -0
  81. package/dist/chat/ui/composer/key-handler.d.ts +20 -0
  82. package/dist/chat/ui/composer/key-handler.js +150 -0
  83. package/dist/chat/ui/composer/keys.d.ts +7 -2
  84. package/dist/chat/ui/composer/keys.js +19 -9
  85. package/dist/chat/ui/composer/placeholder.d.ts +9 -0
  86. package/dist/chat/ui/composer/placeholder.js +38 -0
  87. package/dist/chat/ui/composer/use-chat-controls.d.ts +28 -0
  88. package/dist/chat/ui/composer/use-chat-controls.js +112 -0
  89. package/dist/chat/ui/composer/use-compaction-offer.d.ts +2 -0
  90. package/dist/chat/ui/composer/use-compaction-offer.js +23 -0
  91. package/dist/chat/ui/composer/use-composer-draft.d.ts +14 -0
  92. package/dist/chat/ui/composer/use-composer-draft.js +39 -0
  93. package/dist/chat/ui/composer/use-composer-menus.d.ts +52 -0
  94. package/dist/chat/ui/composer/use-composer-menus.js +232 -0
  95. package/dist/chat/ui/composer/use-composer-submit.d.ts +32 -0
  96. package/dist/chat/ui/composer/use-composer-submit.js +113 -0
  97. package/dist/chat/ui/composer/use-draft-files.d.ts +27 -0
  98. package/dist/chat/ui/composer/use-draft-files.js +111 -0
  99. package/dist/chat/ui/composer/use-notice.d.ts +6 -0
  100. package/dist/chat/ui/composer/use-notice.js +18 -0
  101. package/dist/chat/ui/composer/use-pending-requests.d.ts +2 -0
  102. package/dist/chat/ui/composer/use-pending-requests.js +22 -0
  103. package/dist/chat/ui/composer/use-prompt-history.d.ts +8 -0
  104. package/dist/chat/ui/composer/use-prompt-history.js +57 -0
  105. package/dist/chat/ui/composer/use-prompt-hold.d.ts +6 -0
  106. package/dist/chat/ui/composer/use-prompt-hold.js +48 -0
  107. package/dist/chat/ui/composer/use-take-back.d.ts +13 -0
  108. package/dist/chat/ui/composer/use-take-back.js +82 -0
  109. package/dist/chat/ui/diff/EditorEditDiff.js +4 -3
  110. package/dist/chat/ui/diff/LegacyDiffPool.js +3 -2
  111. package/dist/chat/ui/diff/LegacyEditDiff.js +3 -2
  112. package/dist/chat/ui/diff/LegacyUnifiedDiff.js +3 -2
  113. package/dist/chat/ui/diff/syntax-runtime.d.ts +2 -1
  114. package/dist/chat/ui/diff/syntax-runtime.js +9 -5
  115. package/dist/chat/ui/diff-syntax.d.ts +2 -2
  116. package/dist/chat/ui/diff-syntax.js +1 -2
  117. package/dist/chat/ui/diff-theme.js +10 -9
  118. package/dist/chat/ui/file-links.d.ts +1 -1
  119. package/dist/chat/ui/file-links.js +7 -5
  120. package/dist/chat/ui/highlighter.d.ts +27 -0
  121. package/dist/chat/ui/highlighter.js +151 -0
  122. package/dist/chat/ui/index.d.ts +67 -0
  123. package/dist/chat/ui/index.js +64 -0
  124. package/dist/chat/ui/intelligent-ui/UiReply.js +3 -2
  125. package/dist/chat/ui/intelligent-ui/renderers/content.js +3 -2
  126. package/dist/chat/ui/intelligent-ui/use-ui-links.js +2 -2
  127. package/dist/chat/ui/intelligent-ui/use-ui-queries.js +4 -3
  128. package/dist/chat/ui/markdown-blocks.d.ts +8 -0
  129. package/dist/chat/ui/markdown-blocks.js +260 -12
  130. package/dist/chat/ui/mermaid.d.ts +23 -0
  131. package/dist/chat/ui/mermaid.js +93 -0
  132. package/dist/chat/ui/rows/ForksRow.js +5 -3
  133. package/dist/chat/ui/rows/GeneratedImageRow.js +6 -4
  134. package/dist/chat/ui/rows/MessageRows.d.ts +4 -0
  135. package/dist/chat/ui/rows/MessageRows.js +36 -13
  136. package/dist/chat/ui/rows/Rows.js +3 -1
  137. package/dist/chat/ui/rows/SubagentRow.js +3 -2
  138. package/dist/chat/ui/rows/VisualRow.js +3 -2
  139. package/dist/chat/ui/rows/WorkRows.d.ts +6 -3
  140. package/dist/chat/ui/rows/WorkRows.js +57 -20
  141. package/dist/chat/ui/rows/WorkflowRow.js +3 -2
  142. package/dist/chat/ui/timestamp-format.d.ts +1 -0
  143. package/dist/chat/ui/timestamp-format.js +2 -0
  144. package/dist/chat/ui/use-diff-source-tokens.js +6 -3
  145. package/dist/chat/ui/visual-theme.js +3 -2
  146. package/dist/host.d.ts +9 -6
  147. package/dist/host.js +19 -8
  148. package/dist/index.d.ts +8 -0
  149. package/dist/index.js +9 -0
  150. package/dist/locales/en/agent-chat.d.ts +658 -0
  151. package/dist/locales/en/agent-chat.js +657 -0
  152. package/dist/locales/en/agent-prompts.d.ts +44 -0
  153. package/dist/locales/en/agent-prompts.js +43 -0
  154. package/dist/locales/en/agent-providers.d.ts +132 -0
  155. package/dist/locales/en/agent-providers.js +131 -0
  156. package/dist/locales/en/agent-usage.d.ts +132 -0
  157. package/dist/locales/en/agent-usage.js +131 -0
  158. package/dist/locales/nl/agent-chat.d.ts +658 -0
  159. package/dist/locales/nl/agent-chat.js +657 -0
  160. package/dist/locales/nl/agent-prompts.d.ts +44 -0
  161. package/dist/locales/nl/agent-prompts.js +43 -0
  162. package/dist/locales/nl/agent-providers.d.ts +132 -0
  163. package/dist/locales/nl/agent-providers.js +131 -0
  164. package/dist/locales/nl/agent-usage.d.ts +132 -0
  165. package/dist/locales/nl/agent-usage.js +131 -0
  166. package/dist/locales.js +9 -8
  167. package/dist/prompts/index.d.ts +11 -0
  168. package/dist/prompts/index.js +12 -0
  169. package/dist/prompts/logic/subjects.d.ts +2 -1
  170. package/dist/prompts/logic/subjects.js +6 -4
  171. package/dist/prompts/ui/ApprovalBody.js +6 -4
  172. package/dist/prompts/ui/PromptCard.js +5 -4
  173. package/dist/prompts/ui/PromptView.js +3 -2
  174. package/dist/prompts/ui/QuestionBody.js +3 -2
  175. package/dist/providers/AccountColors.js +2 -2
  176. package/dist/providers/AccountDetail.js +7 -6
  177. package/dist/providers/AccountVariables.js +3 -1
  178. package/dist/providers/AddAccountForm.js +3 -2
  179. package/dist/providers/ProvidersPane.js +4 -3
  180. package/dist/providers/account-actions.d.ts +4 -3
  181. package/dist/providers/account-actions.js +6 -7
  182. package/dist/providers/index.d.ts +16 -0
  183. package/dist/providers/index.js +17 -0
  184. package/dist/providers/provider-abilities.d.ts +2 -1
  185. package/dist/providers/provider-abilities.js +4 -0
  186. package/dist/state/chats.js +4 -2
  187. package/dist/state/index.d.ts +4 -0
  188. package/dist/state/index.js +5 -0
  189. package/dist/testing/index.d.ts +1 -0
  190. package/dist/testing/index.js +2 -0
  191. package/dist/{prompts/logic/prompts.fixtures.d.ts → testing/prompts.d.ts} +1 -1
  192. package/dist/theme.css +13 -3
  193. package/dist/usage/UsageBreakdown.js +3 -2
  194. package/dist/usage/UsageLimits.js +4 -3
  195. package/dist/usage/UsagePage.js +3 -2
  196. package/dist/usage/index.d.ts +15 -0
  197. package/dist/usage/index.js +15 -0
  198. package/package.json +53 -1031
  199. package/src/agents/AccountDot.tsx +3 -1
  200. package/src/agents/accounts.ts +6 -6
  201. package/src/chat/actions.ts +8 -5
  202. package/src/chat/bookmarks.ts +23 -14
  203. package/src/chat/chat-client.ts +8 -0
  204. package/src/chat/composer-send.ts +27 -0
  205. package/src/chat/forks.ts +27 -6
  206. package/src/chat/index.ts +98 -0
  207. package/src/chat/logic/embedded-code.ts +409 -0
  208. package/src/chat/logic/fork.ts +1 -0
  209. package/src/chat/logic/goal.ts +33 -0
  210. package/src/chat/logic/scrubber.ts +6 -5
  211. package/src/chat/logic/thought.ts +40 -0
  212. package/src/chat/logic/thread-cards.ts +2 -0
  213. package/src/chat/logic/timeline.ts +25 -1
  214. package/src/chat/logic/tool-catalog.ts +5 -1
  215. package/src/chat/logic/tools.ts +76 -0
  216. package/src/chat/preferences.ts +26 -3
  217. package/src/chat/reading-width.ts +39 -0
  218. package/src/chat/send-key.ts +38 -0
  219. package/src/chat/ui/BookmarkMarker.tsx +4 -2
  220. package/src/chat/ui/BookmarkSubmenu.tsx +4 -3
  221. package/src/chat/ui/ChatActivity.tsx +14 -10
  222. package/src/chat/ui/ChatReferenceChip.tsx +3 -4
  223. package/src/chat/ui/CodeBlock.tsx +33 -124
  224. package/src/chat/ui/Composer.tsx +162 -1324
  225. package/src/chat/ui/ComposerInput.tsx +5 -4
  226. package/src/chat/ui/EditDiff.tsx +3 -2
  227. package/src/chat/ui/GoalDock.tsx +104 -0
  228. package/src/chat/ui/LimitState.tsx +5 -3
  229. package/src/chat/ui/Markdown.tsx +113 -39
  230. package/src/chat/ui/MermaidBlock.tsx +119 -0
  231. package/src/chat/ui/MessageActions.tsx +13 -8
  232. package/src/chat/ui/Pickers.tsx +8 -7
  233. package/src/chat/ui/PromptComposer.tsx +4 -3
  234. package/src/chat/ui/RowTime.tsx +21 -0
  235. package/src/chat/ui/RunSettings.tsx +9 -4
  236. package/src/chat/ui/ShellCommand.tsx +134 -0
  237. package/src/chat/ui/SubagentInfo.tsx +4 -3
  238. package/src/chat/ui/SubagentStopButton.tsx +4 -3
  239. package/src/chat/ui/SubagentTimeline.tsx +5 -1
  240. package/src/chat/ui/Timeline.tsx +167 -105
  241. package/src/chat/ui/TimelineMenu.tsx +42 -7
  242. package/src/chat/ui/UnifiedDiff.tsx +3 -2
  243. package/src/chat/ui/VisualFrame.tsx +6 -7
  244. package/src/chat/ui/code-theme.ts +4 -4
  245. package/src/chat/ui/composer/ComposerControls.tsx +147 -0
  246. package/src/chat/ui/composer/ComposerMenu.tsx +138 -0
  247. package/src/chat/ui/composer/DraftParts.tsx +86 -0
  248. package/src/chat/ui/composer/QueuedMessages.tsx +64 -0
  249. package/src/chat/ui/composer/key-handler.ts +174 -0
  250. package/src/chat/ui/composer/keys.ts +32 -10
  251. package/src/chat/ui/composer/placeholder.ts +48 -0
  252. package/src/chat/ui/composer/use-chat-controls.ts +134 -0
  253. package/src/chat/ui/composer/use-compaction-offer.ts +25 -0
  254. package/src/chat/ui/composer/use-composer-draft.ts +71 -0
  255. package/src/chat/ui/composer/use-composer-menus.ts +289 -0
  256. package/src/chat/ui/composer/use-composer-submit.ts +163 -0
  257. package/src/chat/ui/composer/use-draft-files.ts +135 -0
  258. package/src/chat/ui/composer/use-notice.ts +28 -0
  259. package/src/chat/ui/composer/use-pending-requests.ts +23 -0
  260. package/src/chat/ui/composer/use-prompt-history.ts +76 -0
  261. package/src/chat/ui/composer/use-prompt-hold.ts +58 -0
  262. package/src/chat/ui/composer/use-take-back.ts +91 -0
  263. package/src/chat/ui/diff/DiffFallbackBoundary.tsx +2 -2
  264. package/src/chat/ui/diff/EditorEditDiff.tsx +4 -3
  265. package/src/chat/ui/diff/LegacyDiffPool.tsx +3 -2
  266. package/src/chat/ui/diff/LegacyEditDiff.tsx +3 -2
  267. package/src/chat/ui/diff/LegacyUnifiedDiff.tsx +3 -2
  268. package/src/chat/ui/diff/syntax-runtime.ts +10 -5
  269. package/src/chat/ui/diff-syntax.ts +2 -2
  270. package/src/chat/ui/diff-theme.ts +10 -9
  271. package/src/chat/ui/file-links.ts +7 -5
  272. package/src/chat/ui/highlighter.ts +185 -0
  273. package/src/chat/ui/index.ts +109 -0
  274. package/src/chat/ui/intelligent-ui/UiReply.tsx +5 -4
  275. package/src/chat/ui/intelligent-ui/renderers/content.tsx +3 -2
  276. package/src/chat/ui/intelligent-ui/use-ui-links.ts +2 -2
  277. package/src/chat/ui/intelligent-ui/use-ui-queries.ts +4 -3
  278. package/src/chat/ui/markdown-blocks.ts +300 -12
  279. package/src/chat/ui/mermaid.ts +118 -0
  280. package/src/chat/ui/rows/ForksRow.tsx +5 -3
  281. package/src/chat/ui/rows/GeneratedImageRow.tsx +6 -4
  282. package/src/chat/ui/rows/MessageRows.tsx +73 -18
  283. package/src/chat/ui/rows/Rows.tsx +14 -1
  284. package/src/chat/ui/rows/SubagentRow.tsx +3 -2
  285. package/src/chat/ui/rows/VisualRow.tsx +3 -2
  286. package/src/chat/ui/rows/WorkRows.tsx +148 -47
  287. package/src/chat/ui/rows/WorkflowRow.tsx +3 -2
  288. package/src/chat/ui/timestamp-format.ts +2 -0
  289. package/src/chat/ui/use-diff-source-tokens.ts +10 -4
  290. package/src/chat/ui/visual-theme.ts +3 -2
  291. package/src/host.ts +31 -15
  292. package/src/index.ts +49 -0
  293. package/src/locales/en/agent-chat.ts +657 -0
  294. package/src/locales/en/agent-prompts.ts +43 -0
  295. package/src/locales/en/agent-providers.ts +131 -0
  296. package/src/locales/en/agent-usage.ts +131 -0
  297. package/src/locales/nl/agent-chat.ts +657 -0
  298. package/src/locales/nl/agent-prompts.ts +43 -0
  299. package/src/locales/nl/agent-providers.ts +131 -0
  300. package/src/locales/nl/agent-usage.ts +132 -0
  301. package/src/locales.ts +9 -8
  302. package/src/prompts/index.ts +35 -0
  303. package/src/prompts/logic/subjects.ts +12 -4
  304. package/src/prompts/ui/ApprovalBody.tsx +6 -4
  305. package/src/prompts/ui/PromptCard.tsx +11 -4
  306. package/src/prompts/ui/PromptView.tsx +3 -2
  307. package/src/prompts/ui/QuestionBody.tsx +3 -2
  308. package/src/providers/AccountColors.tsx +2 -2
  309. package/src/providers/AccountDetail.tsx +13 -7
  310. package/src/providers/AccountVariables.tsx +3 -1
  311. package/src/providers/AddAccountForm.tsx +3 -2
  312. package/src/providers/ProvidersPane.tsx +4 -3
  313. package/src/providers/account-actions.ts +7 -7
  314. package/src/providers/index.ts +17 -0
  315. package/src/providers/provider-abilities.ts +6 -1
  316. package/src/state/chats.ts +4 -2
  317. package/src/state/index.ts +39 -0
  318. package/src/testing/index.ts +2 -0
  319. package/src/{prompts/logic/prompts.fixtures.ts → testing/prompts.ts} +1 -1
  320. package/src/theme.css +13 -3
  321. package/src/usage/UsageBreakdown.tsx +3 -2
  322. package/src/usage/UsageLimits.tsx +4 -3
  323. package/src/usage/UsagePage.tsx +3 -2
  324. package/src/usage/index.ts +16 -0
  325. package/dist/locales/en/agent-chat.json +0 -597
  326. package/dist/locales/en/agent-prompts.json +0 -43
  327. package/dist/locales/en/agent-providers.json +0 -131
  328. package/dist/locales/en/agent-usage.json +0 -131
  329. package/dist/locales/nl/agent-chat.json +0 -597
  330. package/dist/locales/nl/agent-prompts.json +0 -43
  331. package/dist/locales/nl/agent-providers.json +0 -131
  332. package/dist/locales/nl/agent-usage.json +0 -131
  333. package/src/locales/en/agent-chat.json +0 -597
  334. package/src/locales/en/agent-prompts.json +0 -43
  335. package/src/locales/en/agent-providers.json +0 -131
  336. package/src/locales/en/agent-usage.json +0 -131
  337. package/src/locales/nl/agent-chat.json +0 -597
  338. package/src/locales/nl/agent-prompts.json +0 -43
  339. package/src/locales/nl/agent-providers.json +0 -131
  340. package/src/locales/nl/agent-usage.json +0 -131
  341. /package/dist/{prompts/logic/prompts.fixtures.js → testing/prompts.js} +0 -0
@@ -1,938 +1,149 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useContext, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';
2
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
3
3
  import { useTranslation } from 'react-i18next';
4
- import { indentLess, indentMore, insertNewline } from '@codemirror/commands';
5
- import { ensureSyntaxTree, syntaxTree } from '@codemirror/language';
6
- import { EditorView } from '@codemirror/view';
7
4
  import clsx from 'clsx';
8
- import { ArrowUp, ChevronDown, Clock, Copy, FastForward, MessageSquare, Paperclip, Pencil, Plus, Square, SquareSlash, X, Zap } from 'lucide-react';
9
- import { chatHost } from '../../host.js';
5
+ import { ChevronDown } from 'lucide-react';
6
+ import { Icon, PromptDialog, Surface, Tooltip } from '@adecore/ui';
7
+ import { formatNumber } from '@adecore/ui/format';
8
+ import { useChatHost } from '../../host.js';
9
+ import { canSteer } from '../../providers/provider-abilities.js';
10
10
  import { useChatScope } from '../../scope.js';
11
- import { errorCode } from '../../transport.js';
12
- import { useAccountChoice } from '../account-choice.js';
13
- import { useChatActions } from '../actions.js';
14
- import { checkAttachmentLimits, filesOf, formatBytes, isImageAttachment, readAttachments, readStoredAttachments, uploadBytes } from '../attachments.js';
15
- import { chatSuggestions } from '../chat-references.js';
16
- import { EMPTY_DRAFT, isEmptyDraft, joinDraftText, readDraft, takeBackIntoDraft, takeDraftOffers, writeDraft } from '../drafts.js';
17
- import { carriesMentions, droppedMentions, NO_MENTION_SEARCH, dropQuery, findMentionQuery, findSkillQuery, insertMention, insertSkill, mentionPick, pastedMentions, presentMentions, presentSkills } from '../mentions.js';
18
- import { RESUME_COMPACTION_TOKENS, resumeCompactionOffer } from '../logic/resume-compaction.js';
19
- import { dismissResumeCompaction, useResumeCompactionDismissal } from '../resume-compaction-dismissals.js';
20
- import { composerStopLabel, composerStopOf } from '../subagent-list.js';
21
- import { PROMPT_MAX_CHARS, pasteBecomesAttachment, pastedTextName, promptGuard, usableSlashCommands } from '../guards.js';
11
+ import { useProviders } from '../../state/providers.js';
12
+ import { isEmptyDraft } from '../drafts.js';
13
+ import { PROMPT_MAX_CHARS, promptGuard } from '../guards.js';
14
+ import { useChatPreferences } from '../preferences.js';
22
15
  import { withQuote } from '../quote.js';
23
- import { rememberChatAccount, rememberChatPreferences, rememberChatSelection } from '../preferences.js';
24
- import { STASH_SHORTCUT, stashDraft, useStash } from '../stash.js';
25
- import { jumpToTimelineItem, pageTimeline, scrollTimelineToEnd, subscribeTimelineEnd, timelineAtEnd } from '../timeline-scroll.js';
16
+ import { dismissResumeCompaction } from '../resume-compaction-dismissals.js';
17
+ import { sendShortcut } from '../send-key.js';
18
+ import { scrollTimelineToEnd, subscribeTimelineEnd, timelineAtEnd } from '../timeline-scroll.js';
26
19
  import { ChatActivity } from './ChatActivity.js';
27
- import { ChatReferenceChip } from './ChatReferenceChip.js';
28
- import { chipDecorations } from './composer/chips.js';
29
- import { clampMenuIndex, composerMenuAria, optionIdOf } from './composer/menu-aria.js';
30
- import { enterAction, inCode, inFenceBody, inOpenFence, listItemAt, recallDirection, tabSpaces } from './composer/keys.js';
31
20
  import { ComposerInput } from './ComposerInput.js';
32
- import { holdLiftsIn } from '../prompt-hold.js';
33
- import { PromptComposer } from './PromptComposer.js';
34
- import { QuoteTakerContext } from './quote-selection.js';
21
+ import { GoalDock } from './GoalDock.js';
35
22
  import { LimitDock } from './LimitState.js';
23
+ import { PromptComposer } from './PromptComposer.js';
36
24
  import { ResumeCompactionDock } from './ResumeCompactionDock.js';
37
- import { StashPicker } from './Pickers.js';
38
- import { RunSettings } from './RunSettings.js';
39
- import { UploadThumb } from './UploadThumb.js';
40
- import { formatNumber } from '@adecore/ui/format';
41
- import { ButtonGroup, ContextMenu, copyText, ErrorBoundary, FileIcon, Icon, IconButton, isModHeld, KEY_SHORTCUTS, matchesShortcut, Menu, PromptDialog, Surface, Tooltip, useNow } from '@adecore/ui';
42
- import { useChatRow, waitingRequestsOf } from '../../state/chats.js';
43
- import { useProviders } from '../../state/providers.js';
44
- const SEARCH_DEBOUNCE_MS = 80;
45
- // What fits above the composer without turning the picker into a file tree.
46
- const MENTION_RESULTS = 8;
47
- // The chats go above the files, so a few leave the files in view.
48
- const CHAT_RESULTS = 4;
49
- const NOTICE_MS = 4000;
50
- // How many sent prompts the arrow keys walk back through, per chat.
51
- const PROMPT_HISTORY = 50;
52
- // Commands the composer handles itself; the CLI's own ones are sent through as text.
53
- const LOCAL_COMMANDS = ['model', 'compact', 'clear'];
54
- /* The card turns dropped files and paths into attachments and chips; CodeMirror would also paste their text at the drop point. */
55
- const LEAVE_DROPS_TO_THE_CARD = EditorView.domEventHandlers({
56
- drop: (event) => event.dataTransfer !== null && (event.dataTransfer.types.includes('Files') || carriesMentions(event.dataTransfer.types))
57
- });
58
- function usePendingRequests(chatId) {
59
- // The structure, which a delta leaves alone. The prompts and the requests are items of their own.
60
- const structure = useChatRow(chatId, (row) => row?.structure);
61
- const order = useChatRow(chatId, (row) => row?.order);
62
- const waitingBefore = useChatRow(chatId, (row) => row?.waitingBefore);
63
- return useMemo(() => {
64
- const approvals = [];
65
- const questions = [];
66
- for (const item of waitingRequestsOf(structure && order ? { structure, order, waitingBefore } : undefined)) {
67
- if (item.kind === 'approval') {
68
- approvals.push(item);
69
- }
70
- else {
71
- questions.push(item);
72
- }
73
- }
74
- return { approvals, questions };
75
- }, [structure, order, waitingBefore]);
76
- }
77
- /* The empty box names its sigils as key caps, so they read as keys to press rather than as punctuation. */
78
- function hintedPlaceholder(lead, joiner, hints) {
79
- const root = document.createElement('span');
80
- root.className = 'composer-hints';
81
- const extra = document.createElement('span');
82
- extra.className = 'composer-hints-extra';
83
- extra.append(joiner);
84
- for (const hint of hints) {
85
- const cap = document.createElement('kbd');
86
- cap.textContent = hint.key;
87
- extra.append(cap, hint.label);
88
- }
89
- root.append(lead, extra);
90
- return root;
91
- }
92
- function sendLabelKey(busy, canSteer, delivery) {
25
+ import { chipDecorations } from './composer/chips.js';
26
+ import { ComposerControls } from './composer/ComposerControls.js';
27
+ import { ComposerMenu } from './composer/ComposerMenu.js';
28
+ import { DraftAttachments, DraftChats, DraftQuote } from './composer/DraftParts.js';
29
+ import { composerKeyHandler } from './composer/key-handler.js';
30
+ import { useHintedPlaceholder } from './composer/placeholder.js';
31
+ import { QueuedMessages } from './composer/QueuedMessages.js';
32
+ import { useChatControls } from './composer/use-chat-controls.js';
33
+ import { useCompactionOffer } from './composer/use-compaction-offer.js';
34
+ import { useComposerDraft } from './composer/use-composer-draft.js';
35
+ import { useComposerMenus } from './composer/use-composer-menus.js';
36
+ import { useComposerSubmit } from './composer/use-composer-submit.js';
37
+ import { LEAVE_DROPS_TO_THE_CARD, useDraftFiles } from './composer/use-draft-files.js';
38
+ import { useNotice } from './composer/use-notice.js';
39
+ import { usePendingRequests } from './composer/use-pending-requests.js';
40
+ import { usePromptHistory } from './composer/use-prompt-history.js';
41
+ import { usePromptHold } from './composer/use-prompt-hold.js';
42
+ import { useTakeBack } from './composer/use-take-back.js';
43
+ function sendLabelKey(busy, steerable, delivery) {
93
44
  if (!busy) {
94
45
  return 'composer.send';
95
46
  }
96
- if (!canSteer) {
47
+ if (!steerable) {
97
48
  return 'composer.queueButton';
98
49
  }
99
50
  return delivery === 'steer' ? 'composer.steerButton' : 'composer.queueWithSteerButton';
100
51
  }
101
- function sameQuery(left, right) {
102
- return left?.start === right?.start && left?.query === right?.query;
103
- }
104
- function splitPath(path) {
105
- const slash = path.lastIndexOf('/');
106
- return slash < 0 ? { name: path, dir: '' } : { name: path.slice(slash + 1), dir: path.slice(0, slash) };
107
- }
108
- // Keep the editor mounted while a pending request takes over, so its selection and draft survive.
109
- /*
110
- * Keeps a waiting prompt card behind the draft while the person types. Typing, pasting and dictating
111
- * all change the draft, so `noteInput` is called from its change handler; the hold lifts after a pause.
112
- */
113
- function usePromptHold() {
114
- const typedAt = useRef(null);
115
- const composing = useRef(false);
116
- const timer = useRef(null);
117
- const [state, setState] = useState({ held: false, releasedBy: null });
118
- const clearTimer = () => {
119
- if (timer.current !== null) {
120
- clearTimeout(timer.current);
121
- timer.current = null;
122
- }
123
- };
124
- const release = (reason) => {
125
- clearTimer();
126
- typedAt.current = null;
127
- composing.current = false;
128
- setState((current) => (current.held ? { held: false, releasedBy: reason } : current));
129
- };
130
- const schedule = () => {
131
- clearTimer();
132
- const wait = holdLiftsIn({ typedAt: typedAt.current, composing: composing.current }, Date.now());
133
- if (wait !== null) {
134
- timer.current = setTimeout(() => release('pause'), wait);
135
- }
136
- };
137
- const noteInput = () => {
138
- typedAt.current = Date.now();
139
- setState({ held: true, releasedBy: null });
140
- schedule();
141
- };
142
- const setComposing = (next) => {
143
- composing.current = next;
144
- if (next) {
145
- setState({ held: true, releasedBy: null });
146
- }
147
- else {
148
- typedAt.current = Date.now();
149
- }
150
- schedule();
151
- };
152
- useEffect(() => clearTimer, []);
153
- return { held: state.held, releasedBy: state.releasedBy, release, noteInput, setComposing };
154
- }
155
52
  export function Composer({ chatId, info, focused, answerPromptsElsewhere, disabled, readOnly = false, providerFixed, onSend, onRetarget }) {
156
53
  const { t } = useTranslation('agent-chat');
157
- const sendDelivery = chatHost().useSendDelivery();
158
- const canSteer = info.provider === 'claude' || info.provider === 'codex';
159
- const [draft, setDraft] = useState(() => readDraft(chatId));
160
- const [historyIndex, setHistoryIndex] = useState(null);
161
- const [menuIndex, setMenuIndex] = useState(0);
162
- const [mention, setMention] = useState(null);
163
- const [skillQuery, setSkillQuery] = useState(null);
164
- const [skills, setSkills] = useState([]);
165
- const [searched, setSearched] = useState(NO_MENTION_SEARCH);
166
- const configuring = useRef(false);
167
- const [configurationPending, setConfigurationPending] = useState(false);
168
- const [notice, setNotice] = useState(null);
169
- const [dragging, setDragging] = useState(false);
170
- const [modelPickerOpen, setModelPickerOpen] = useState(false);
171
- const [confirmClear, setConfirmClear] = useState(false);
172
- const [takingBack, setTakingBack] = useState(null);
54
+ const host = useChatHost();
173
55
  const scope = useChatScope();
174
- const actions = useChatActions();
175
- const { isApplePlatform, notify } = chatHost();
176
- const registerQuoteTaker = useContext(QuoteTakerContext);
177
- const inputRef = useRef(null);
178
- const hold = usePromptHold();
179
- // Taking a queued message back waits on the machine, and what was typed meanwhile is what it merges with.
180
- const draftRef = useRef(draft);
181
- const fileInputRef = useRef(null);
182
- const [dictationToolbar, setDictationToolbar] = useState(null);
183
- // A paste event says nothing about the keys behind it, so the key that asked for text inline is remembered here.
184
- const pasteInlineRef = useRef(false);
185
- const providers = useProviders((s) => s.providers);
186
- const { approvals, questions } = usePendingRequests(chatId);
187
- const order = useChatRow(chatId, (row) => row?.order);
188
- const items = useChatRow(chatId, (row) => row?.structure);
189
- const chats = chatHost().useReferableChats();
190
- const placeholderLead = chatHost().useComposerPlaceholder(scope.id, chatId);
191
- const pending = useMemo(() => [...approvals, ...questions], [approvals, questions]);
192
- const writable = !disabled && !readOnly;
193
- const provider = providers.find((entry) => entry.kind === info.provider);
56
+ const sendDelivery = host.useSendDelivery();
57
+ const sendKey = useChatPreferences((preferences) => preferences.sendKey);
58
+ const provider = useProviders((row) => row.providers.find((entry) => entry.kind === info.provider));
194
59
  // Absent until the host answered `provider.list`, so only an explicit false hides anything.
195
60
  const capabilities = provider?.capabilities;
196
- const compaction = capabilities?.compaction;
197
- const dismissedTurnId = useResumeCompactionDismissal(chatId);
198
- // The cheap half of the offer, so a chat that can never make one keeps no timer.
199
- const couldOfferCompaction = compaction !== undefined && compaction !== 'none' && info.usage.contextTokens >= RESUME_COMPACTION_TOKENS;
200
- const now = useNow(60_000, couldOfferCompaction);
201
- const compactionOffer = !couldOfferCompaction
202
- ? null
203
- : resumeCompactionOffer({
204
- info,
205
- compaction,
206
- items: (order ?? []).map((id) => items?.[id]).filter((item) => item !== undefined),
207
- dismissedTurnId,
208
- now
209
- });
210
- const models = provider?.models ?? [];
211
- const model = models.find((entry) => entry.slug === info.selection.model);
61
+ const steerable = canSteer(capabilities);
62
+ const writable = !disabled && !readOnly;
212
63
  const busy = info.activeTurnId !== null;
213
- const queue = info.queue ?? [];
214
- const text = draft.text;
215
- const quote = draft.quote;
216
- const quoteSource = draft.quoteSource;
217
- // The CLI announces its session on the first message, so anything before that is still a blank chat.
218
- const started = info.agentSessionId !== null || info.usage.turns > 0;
219
- const accountChoice = useAccountChoice(info.provider, info.account);
220
- // A chat that has started keeps its provider (the CLI holds the thread), and so does one opened for a
221
- // named CLI; its models stay switchable, since the CLI takes a new one on the restart the next send does.
222
- const pickable = started || providerFixed
223
- ? providers.filter((entry) => entry.kind === info.provider)
224
- : providers.filter((entry) => entry.installed && entry.capabilities.chat);
225
- useEffect(() => {
226
- if (focused) {
64
+ const inputRef = useRef(null);
65
+ const [dictationToolbar, setDictationToolbar] = useState(null);
66
+ const hold = usePromptHold();
67
+ const box = useComposerDraft(chatId, inputRef);
68
+ const { draft } = box;
69
+ const notice = useNotice();
70
+ const history = usePromptHistory(chatId, box.setText);
71
+ const menus = useComposerMenus({ chatId, info, capabilities, providerName: provider?.name, draft: box, inputRef });
72
+ const files = useDraftFiles({ capabilities, providerName: provider?.name, writable, draft: box, inputRef, setNotice: notice.setNotice });
73
+ const controls = useChatControls({ chatId, info, notice, onRetarget });
74
+ const guard = promptGuard(withQuote(draft.quote, draft.text));
75
+ const { submit, restoreStashed, toggleStash } = useComposerSubmit({
76
+ chatId,
77
+ writable,
78
+ guard,
79
+ steerable,
80
+ sendDelivery,
81
+ draft: box,
82
+ menus,
83
+ controls,
84
+ history,
85
+ hold,
86
+ inputRef,
87
+ setNotice: notice.setNotice,
88
+ onSend
89
+ });
90
+ const { takingBack, takeBack } = useTakeBack({
91
+ chatId,
92
+ draft: box,
93
+ setNotice: notice.setNotice,
94
+ onTaken: () => {
95
+ history.forget();
227
96
  inputRef.current?.focus();
228
97
  }
229
- }, [focused]);
230
- useEffect(() => {
231
- draftRef.current = draft;
232
- writeDraft(chatId, draft);
233
- }, [chatId, draft]);
234
- useEffect(() => takeDraftOffers(chatId, (offered) => {
235
- setDraft((current) => ({ ...current, text: joinDraftText(current.text, offered) }));
236
- inputRef.current?.focus();
237
- }), [chatId]);
238
- useEffect(() => registerQuoteTaker?.((selected, itemId) => {
239
- setDraft((current) => ({ ...current, quote: selected, quoteSource: itemId }));
240
- inputRef.current?.focus();
241
- }), [registerQuoteTaker]);
242
- useEffect(() => {
243
- if (!notice) {
244
- return;
245
- }
246
- const timer = setTimeout(() => setNotice(null), NOTICE_MS);
247
- return () => clearTimeout(timer);
248
- }, [notice]);
249
- // Every keystroke inside an `@word` searches again; a slow answer must not overwrite a newer one.
250
- useEffect(() => {
251
- if (mention === null) {
252
- return;
253
- }
254
- let stale = false;
255
- const search = () => {
256
- const searchFiles = chatHost().searchFiles;
257
- if (searchFiles === null) {
258
- return;
259
- }
260
- searchFiles(scope.id, info.cwd, mention.query, MENTION_RESULTS)
261
- .then((files) => {
262
- if (!stale) {
263
- setSearched({ query: mention.query, files });
264
- setMenuIndex(0);
265
- }
266
- })
267
- .catch(() => undefined);
268
- };
269
- // A bare `@` is not a keystroke in a query. It opens the list of what is there, at once.
270
- if (mention.query === '') {
271
- search();
272
- return () => {
273
- stale = true;
274
- };
275
- }
276
- const timer = setTimeout(search, SEARCH_DEBOUNCE_MS);
277
- return () => {
278
- stale = true;
279
- clearTimeout(timer);
280
- };
281
- }, [scope, info.cwd, mention]);
282
- /* The host's skill list, once per chat and again once the CLI announced its own after the first message. */
283
- useEffect(() => {
284
- let stale = false;
285
- scope.chats
286
- .listSkills(chatId)
287
- .then((found) => {
288
- if (!stale) {
289
- setSkills(found);
290
- }
291
- })
292
- .catch(() => undefined);
293
- return () => {
294
- stale = true;
295
- };
296
- }, [scope, chatId, info.skills]);
297
- const history = useMemo(() => {
298
- const prompts = [];
299
- for (const id of order ?? []) {
300
- const item = items?.[id];
301
- if (item?.kind === 'user') {
302
- prompts.push({ text: item.text, mentions: item.mentions ?? [] });
303
- }
304
- }
305
- // Walking back further than this is faster with the timeline than with the arrow key.
306
- return prompts.slice(-PROMPT_HISTORY);
307
- }, [order, items]);
308
- const commandQuery = text.startsWith('/') && !text.includes('\n') ? text.slice(1).trim().toLowerCase() : null;
309
- const commands = useMemo(() => {
310
- if (commandQuery === null) {
311
- return [];
312
- }
313
- const known = new Set(skills.map((skill) => skill.name));
314
- const own = LOCAL_COMMANDS.map((name) => ({ name, hint: t(`composer.commands.${name}`), local: true, skill: false }));
315
- const cli = usableSlashCommands(info.slashCommands)
316
- .filter((name) => !LOCAL_COMMANDS.includes(name))
317
- .map((name) => ({
318
- name,
319
- hint: known.has(name) ? t('composer.commands.skill') : t('composer.commands.cli', { cli: provider?.name ?? t('composer.commands.anyCli') }),
320
- local: false,
321
- skill: known.has(name)
322
- }));
323
- return [...own, ...cli].filter((command) => command.name.startsWith(commandQuery)).slice(0, 8);
324
- }, [commandQuery, info.slashCommands, provider?.name, skills, t]);
325
- const skillMatches = useMemo(() => {
326
- if (skillQuery === null) {
327
- return [];
328
- }
329
- const query = skillQuery.query.toLowerCase();
330
- return skills.filter((skill) => skill.name.toLowerCase().includes(query)).slice(0, 8);
331
- }, [skillQuery, skills]);
332
- const commandMenuOpen = commandQuery !== null && commands.length > 0;
333
- const skillMenuOpen = !commandMenuOpen && skillQuery !== null && skillMatches.length > 0;
334
- const mentionMenuOpen = !commandMenuOpen && !skillMenuOpen && mention !== null;
335
- // Results belong to the query that asked for them; a closed picker shows none while the next answer is on its way.
336
- const files = mention === null ? [] : searched.files;
337
- const chatMatches = useMemo(() => (mention === null ? [] : chatSuggestions(chats, mention.query, [chatId, ...draft.chats], CHAT_RESULTS)), [chatId, chats, draft.chats, mention]);
338
- const mentionCount = chatMatches.length + files.length;
339
- // One menu is open at a time, so they share an id.
340
- const listId = useId();
341
- const mentionsLabelId = `${listId}-chats`;
342
- const filesLabelId = `${listId}-files`;
343
- const filesLabelShown = mention !== null && (mention.query === '' || chatMatches.length > 0);
344
- const menuOpen = commandMenuOpen || skillMenuOpen || mentionMenuOpen;
345
- const menuCount = commandMenuOpen ? commands.length : skillMenuOpen ? skillMatches.length : mentionCount;
346
- // The list can shrink under a stale index; every reader takes the one that still points at an option.
347
- const activeIndex = clampMenuIndex(menuIndex, menuCount);
348
- const inputAria = useMemo(() => composerMenuAria({
349
- label: t('composer.inputLabel'),
350
- listId,
351
- open: menuOpen,
352
- activeIndex,
353
- count: menuCount
354
- }), [t, listId, menuOpen, activeIndex, menuCount]);
98
+ });
99
+ const pending = usePendingRequests(chatId);
100
+ const compactionOffer = useCompactionOffer(chatId, info, capabilities?.compaction);
101
+ const placeholder = useHintedPlaceholder({ chatId, disabled, readOnly, mentionable: capabilities?.mentions !== false, hasSkills: menus.hasSkills });
355
102
  const editorExtensions = useMemo(() => [chipDecorations({ mentions: draft.mentions, skills: draft.skills }), LEAVE_DROPS_TO_THE_CARD], [draft.mentions, draft.skills]);
356
- const guard = promptGuard(withQuote(quote, text));
357
- const setText = (next, mentions = draft.mentions, chosen = draft.skills) => {
358
- setDraft((current) => ({ ...current, text: next, mentions, skills: chosen }));
359
- };
360
- const clearDraft = () => {
361
- setDraft(EMPTY_DRAFT);
362
- };
363
- const removeQuote = () => {
364
- setDraft((current) => ({ ...current, quote: '', quoteSource: null }));
365
- inputRef.current?.focus();
366
- };
367
- const showError = (error) => {
368
- setNotice(error instanceof Error ? error.message : String(error));
369
- };
370
- /* One configuration at a time; a second pick while one is on its way is dropped. */
371
- const runConfiguration = (work) => {
372
- if (configuring.current) {
373
- return;
374
- }
375
- configuring.current = true;
376
- setConfigurationPending(true);
377
- void work()
378
- .catch(showError)
379
- .finally(() => {
380
- configuring.current = false;
381
- setConfigurationPending(false);
382
- });
383
- };
384
- const configure = (patch) => {
385
- runConfiguration(() => actions.configure(chatId, patch).then(() => {
386
- if (patch.selection) {
387
- rememberChatSelection(info.provider, patch.selection);
388
- }
389
- if (patch.runtimeMode) {
390
- rememberChatPreferences({ runtimeMode: patch.runtimeMode });
391
- }
392
- if (patch.account) {
393
- rememberChatAccount(scope.id, info.provider, patch.account);
394
- }
395
- }));
396
- };
397
- const chooseAccount = (account) => configure({ account });
398
- /* A model of another CLI re-points the whole chat; one of this CLI's own is a configure. */
399
- const chooseModel = (provider, slug) => {
400
- const selection = { model: slug, options: {} };
401
- if (provider !== info.provider) {
402
- runConfiguration(() => onRetarget(provider, selection).then(() => rememberChatSelection(provider, selection)));
403
- return;
404
- }
405
- configure({ selection });
406
- };
407
- const stop = (shiftKey) => {
408
- if (composerStopOf(shiftKey) === 'turn') {
409
- void actions.stopTurn(chatId, false).catch(showError);
410
- return;
411
- }
412
- chatHost().confirm.stopSubagents(scope.id, chatId, () => void actions.stopTurn(chatId, true).catch(showError));
413
- };
414
- /* The host decides whether a turn is in the way; only its refusal asks the person first. */
415
- const clearThread = async () => {
416
- try {
417
- await actions.clear(chatId, false);
418
- }
419
- catch (e) {
420
- if (errorCode(e) === 'chat-busy') {
421
- setConfirmClear(true);
422
- return;
423
- }
424
- setNotice(t('composer.notice.clearFailed'));
425
- }
426
- };
427
- const forceClearThread = async () => {
428
- await actions.clear(chatId, true);
429
- setConfirmClear(false);
430
- };
431
- const compact = () => {
432
- void actions.compact(chatId).catch(() => setNotice(t('composer.notice.compactFailed')));
433
- };
434
- const runCommand = (name) => {
435
- switch (name) {
436
- case 'model':
437
- setModelPickerOpen(true);
438
- return true;
439
- case 'compact':
440
- void actions.compact(chatId).catch(() => undefined);
441
- return true;
442
- case 'clear':
443
- void clearThread();
444
- return true;
445
- default:
446
- return false;
447
- }
448
- };
449
- /* Which picker the caret opens: `@` for a file, `$` for a skill, or neither. In code a sigil is just text. */
450
- const trackTriggers = (value, selection, state) => {
451
- const empty = selection.from === selection.to;
452
- const tree = empty ? (ensureSyntaxTree(state, selection.from, 50) ?? syntaxTree(state)) : null;
453
- const caret = tree !== null && !inCode(tree, value, selection.from) ? selection.from : null;
454
- const skill = caret === null ? null : findSkillQuery(value, caret);
455
- setSkillQuery((current) => (sameQuery(current, skill) ? current : skill));
456
- // A CLI that does not expand `@path` gets the text as it is, so the picker stays out of the way.
457
- const next = caret === null || capabilities?.mentions === false ? null : findMentionQuery(value, caret);
458
- setMention((current) => (sameQuery(current, next) ? current : next));
459
- };
460
- // The inserted text reaches the editor with the render it causes, so the caret waits a frame for it.
461
- const moveCaret = (caret) => {
462
- requestAnimationFrame(() => inputRef.current?.setCaret(caret));
463
- };
464
- const chooseMention = (path) => {
465
- if (!mention) {
466
- return;
467
- }
468
- const result = insertMention(text, mention, path);
469
- setText(result.text, draft.mentions.includes(path) ? draft.mentions : [...draft.mentions, path]);
470
- setMention(null);
471
- moveCaret(result.caret);
472
- };
473
- /* A picked chat sits beside the text as a chip, so the `@query` that found it goes. */
474
- const chooseChat = (id) => {
475
- if (!mention) {
476
- return;
477
- }
478
- const result = dropQuery(text, mention);
479
- setDraft((current) => ({ ...current, text: result.text, chats: current.chats.includes(id) ? current.chats : [...current.chats, id] }));
480
- setMention(null);
481
- moveCaret(result.caret);
482
- };
483
- const chooseMentionAt = (index) => {
484
- const pick = mention === null ? null : mentionPick(index, chatMatches, searched, mention.query);
485
- if (pick?.kind === 'chat') {
486
- chooseChat(pick.chat.id);
487
- }
488
- else if (pick?.kind === 'file') {
489
- chooseMention(pick.path);
490
- }
491
- };
492
- const removeChat = (id) => {
493
- setDraft((current) => ({ ...current, chats: current.chats.filter((entry) => entry !== id) }));
494
- inputRef.current?.focus();
495
- };
496
- /*
497
- * A picked skill becomes a `$name` chip in the text and a name on the send, which is what
498
- * dispatches it. The `/` menu lands here too, so both spellings end up on the same path.
499
- */
500
- const chooseSkill = (name) => {
501
- const result = skillQuery ? insertSkill(text, skillQuery, name) : { text: `$${name} `, caret: name.length + 2 };
502
- setText(result.text, draft.mentions, draft.skills.includes(name) ? draft.skills : [...draft.skills, name]);
503
- setSkillQuery(null);
504
- moveCaret(result.caret);
505
- };
506
- /* Paths dragged in from a list of files. With no mention query to insert into, they land at the end of the prompt. */
507
- const addMentions = (paths) => {
508
- const fresh = paths.filter((path) => path !== '');
509
- if (fresh.length === 0 || capabilities?.mentions === false) {
510
- return;
511
- }
512
- const appended = fresh.map((path) => `@${path}`).join(' ');
513
- const before = text.replace(/\s+$/, '');
514
- setText(before === '' ? `${appended} ` : `${before} ${appended} `, [...draft.mentions, ...fresh.filter((path) => !draft.mentions.includes(path))]);
515
- };
516
- const addFiles = (incoming) => {
517
- if (incoming.length === 0) {
518
- return;
519
- }
520
- if (capabilities?.attachments === false) {
521
- setNotice(t('composer.notice.noAttachments', { agent: provider?.name ?? t('composer.notice.thisAgent') }));
522
- return;
523
- }
524
- const checked = checkAttachmentLimits(draft.attachments.length, incoming.map((file) => ({ name: file.name, mime: file.type, bytes: file.size, file })), draft.attachments.reduce((bytes, attachment) => bytes + uploadBytes(attachment), 0));
525
- if (checked.rejected[0]) {
526
- setNotice(t('composer.notice.rejected', { name: checked.rejected[0].name || t('composer.notice.thatFile'), reason: checked.rejected[0].reason }));
527
- }
528
- if (checked.accepted.length === 0) {
529
- return;
530
- }
531
- readAttachments(checked.accepted.map((entry) => entry.file))
532
- .then((attachments) => setDraft((current) => ({ ...current, attachments: [...current.attachments, ...attachments] })))
533
- .catch(() => setNotice(t('composer.notice.unreadable')));
534
- };
535
- const insertIntoDraft = (added) => {
536
- if (writable) {
537
- inputRef.current?.insert(added);
538
- }
539
- };
540
- const removeAttachment = (index) => {
541
- setDraft((current) => ({ ...current, attachments: current.attachments.filter((_, i) => i !== index) }));
542
- };
543
- const submit = (alternate = false) => {
544
- const delivery = canSteer && (alternate ? sendDelivery === 'queue' : sendDelivery === 'steer') ? 'steer' : 'queue';
545
- const trimmed = text.trim();
546
- if (isEmptyDraft(draft) || !writable || guard.tooLong) {
547
- return;
548
- }
549
- // Recheck restored drafts and files that finished reading concurrently.
550
- const rejected = checkAttachmentLimits(0, draft.attachments.map((attachment) => ({ ...attachment, bytes: uploadBytes(attachment) }))).rejected[0];
551
- if (rejected) {
552
- setNotice(`${rejected.name}: ${rejected.reason}`);
553
- return;
554
- }
555
- hold.release('send');
556
- const chosen = commands[activeIndex];
557
- if (commandQuery !== null && chosen?.local && runCommand(chosen.name)) {
558
- clearDraft();
559
- return;
560
- }
561
- if (commandQuery !== null && chosen?.skill) {
562
- chooseSkill(chosen.name);
563
- return;
564
- }
565
- // Whoever sends wants to see what comes back, wherever they were reading.
566
- scrollTimelineToEnd(chatId, 'instant');
567
- if (commandQuery !== null && chosen && !chosen.local) {
568
- onSend(`/${chosen.name}`, {});
569
- clearDraft();
570
- return;
571
- }
572
- onSend(withQuote(quote, trimmed), {
573
- delivery,
574
- mentions: presentMentions(trimmed, draft.mentions),
575
- skills: presentSkills(trimmed, draft.skills),
576
- chats: draft.chats,
577
- quoteSource: quote !== '' && quoteSource !== null ? { itemId: quoteSource } : undefined,
578
- attachments: draft.attachments
579
- });
580
- clearDraft();
581
- setMention(null);
582
- setSkillQuery(null);
583
- setHistoryIndex(null);
584
- };
585
- /*
586
- * A stashed prompt comes back as text, mentions and skills; its files were never kept. Its quote
587
- * keeps leading to its reply in the chat it came from, and is plain text in any other.
588
- */
589
- const restoreStashed = (prompt) => {
590
- const stashedQuote = prompt.quote;
591
- const here = stashedQuote !== undefined && stashedQuote.chatId === chatId;
592
- setDraft((current) => ({
593
- ...current,
594
- text: stashedQuote === undefined || here ? prompt.text : withQuote(stashedQuote.text, prompt.text),
595
- mentions: [...prompt.mentions],
596
- skills: [...prompt.skills],
597
- ...(here ? { quote: stashedQuote.text, quoteSource: stashedQuote.itemId } : {})
598
- }));
599
- setHistoryIndex(null);
600
- inputRef.current?.focus();
601
- };
602
- /*
603
- * The files come back from the machine before the message leaves the queue, since the machine only
604
- * serves a file some message still holds. The machine's refusal is what says it already went out.
605
- */
606
- const takeBack = async (message) => {
607
- if (takingBack !== null) {
608
- return;
609
- }
610
- const failed = (e) => {
611
- notify({ kind: 'error', title: t('composer.queue.editFailed'), description: e instanceof Error ? e.message : String(e) });
612
- };
613
- const readFiles = async () => {
614
- const stored = message.attachments ?? [];
615
- if (stored.length === 0) {
616
- return [];
617
- }
618
- const files = chatHost().attachments;
619
- return readStoredAttachments((attachment) => files.read(scope.id, chatId, attachment.id), stored);
620
- };
621
- setTakingBack(message.id);
622
- try {
623
- let uploads;
624
- try {
625
- uploads = await readFiles();
626
- }
627
- catch (e) {
628
- failed(e);
629
- return;
630
- }
631
- const taken = {
632
- text: message.text,
633
- mentions: message.mentions ?? [],
634
- skills: message.skills ?? [],
635
- chats: message.chats ?? [],
636
- attachments: uploads
637
- };
638
- // A file that would not fit is refused here, while the message still holds it on the machine.
639
- const wouldReject = takeBackIntoDraft(draftRef.current, taken).rejected[0];
640
- if (wouldReject) {
641
- setNotice(t('composer.notice.queuedDoesNotFit', { name: wouldReject.name || t('composer.notice.thatFile'), reason: wouldReject.reason }));
642
- return;
643
- }
644
- try {
645
- await actions.unqueue(chatId, message.id);
646
- }
647
- catch (e) {
648
- if (errorCode(e) === 'request-not-found') {
649
- notify({ kind: 'error', title: t('composer.queue.alreadySent') });
650
- }
651
- else {
652
- failed(e);
653
- }
654
- return;
655
- }
656
- const merged = takeBackIntoDraft(draftRef.current, taken);
657
- setDraft(merged.draft);
658
- if (merged.rejected[0]) {
659
- setNotice(t('composer.notice.rejected', { name: merged.rejected[0].name, reason: merged.rejected[0].reason }));
660
- }
661
- setHistoryIndex(null);
662
- inputRef.current?.focus();
663
- }
664
- finally {
665
- setTakingBack(null);
666
- }
667
- };
668
- /* Cmd+S puts the draft away and clears the box; on an empty box the same key takes the last one back. */
669
- const toggleStash = () => {
670
- if (isEmptyDraft(draft)) {
671
- const newest = useStash.getState().prompts[0];
672
- if (newest) {
673
- restoreStashed(newest);
674
- }
675
- return;
676
- }
677
- if (stashDraft(draft, chatId)) {
678
- clearDraft();
679
- setMention(null);
680
- setSkillQuery(null);
681
- }
682
- };
683
- const recall = (direction) => {
684
- if (history.length === 0) {
685
- return false;
686
- }
687
- const next = historyIndex === null ? (direction === -1 ? history.length - 1 : null) : historyIndex + direction;
688
- if (next === null || next >= history.length) {
689
- setHistoryIndex(null);
690
- setText('', [], []);
691
- return true;
692
- }
693
- if (next < 0) {
694
- return true;
695
- }
696
- setHistoryIndex(next);
697
- setText(history[next].text, history[next].mentions);
698
- return true;
699
- };
700
- /* The arrows walk an open picker round; true when the key was one of them. */
701
- const moveInMenu = (key, count) => {
702
- if (key === 'ArrowDown') {
703
- setMenuIndex((i) => (i + 1) % count);
704
- return true;
705
- }
706
- if (key === 'ArrowUp') {
707
- setMenuIndex((i) => (i - 1 + count) % count);
708
- return true;
709
- }
710
- return false;
711
- };
712
- /* Runs before the editor's own keymap; true means the key is handled and its default prevented. */
713
- const onKeyDown = (e, view) => {
714
- // Shift with the paste shortcut pastes a large text inline after all; any other key forgets it.
715
- pasteInlineRef.current = e.shiftKey && e.key.toLowerCase() === 'v' && (isApplePlatform() ? e.metaKey : e.ctrlKey);
716
- // Escape leaves the node, unless it first has a recalled prompt to put back.
717
- if (e.key === 'Escape' && !e.isComposing) {
718
- if (historyIndex === null) {
719
- return false;
720
- }
721
- e.stopPropagation();
722
- setHistoryIndex(null);
723
- setText('', [], []);
724
- return true;
725
- }
726
- // The app's own shortcuts stay the app's while you type: Mod+Shift+Enter would otherwise send as well.
727
- if (chatHost().isAppShortcut(e)) {
728
- return false;
729
- }
730
- e.stopPropagation();
731
- // A key inside an IME composition belongs to the composition, Enter and the arrows included.
732
- if (e.isComposing) {
733
- return false;
734
- }
735
- // Reading back through a long answer should not mean leaving the box you are typing in.
736
- if (e.key === 'PageUp' || e.key === 'PageDown') {
737
- return pageTimeline(chatId, e.key === 'PageUp' ? -1 : 1);
738
- }
739
- if (matchesShortcut(STASH_SHORTCUT, e, isApplePlatform())) {
740
- toggleStash();
741
- return true;
742
- }
743
- if (commandMenuOpen) {
744
- if (moveInMenu(e.key, commands.length)) {
745
- return true;
746
- }
747
- if (e.key === 'Tab') {
748
- const chosen = commands[activeIndex];
749
- if (chosen.skill) {
750
- chooseSkill(chosen.name);
751
- }
752
- else {
753
- setText(`/${chosen.name} `);
754
- }
755
- return true;
756
- }
757
- }
758
- if (skillMenuOpen) {
759
- if (moveInMenu(e.key, skillMatches.length)) {
760
- return true;
761
- }
762
- if (e.key === 'Tab' || e.key === 'Enter') {
763
- chooseSkill((skillMatches[activeIndex] ?? skillMatches[0]).name);
764
- return true;
765
- }
766
- }
767
- if (mentionMenuOpen && mentionCount > 0) {
768
- if (moveInMenu(e.key, mentionCount)) {
769
- return true;
770
- }
771
- if (e.key === 'Tab' || e.key === 'Enter') {
772
- chooseMentionAt(activeIndex);
773
- return true;
774
- }
775
- }
776
- // In a fence Tab indents like a code editor; anywhere else it keeps moving the focus.
777
- if (e.key === 'Tab' && !e.altKey && !e.metaKey && !e.ctrlKey) {
778
- const { state } = view;
779
- const { from, to, head } = state.selection.main;
780
- const tree = ensureSyntaxTree(state, state.doc.length, 50) ?? syntaxTree(state);
781
- if (inFenceBody(tree, state.doc.toString(), head)) {
782
- // Handled even when there is nothing to outdent, so Shift+Tab never throws the focus out of a block.
783
- if (e.shiftKey) {
784
- indentLess(view);
785
- }
786
- else if (from !== to) {
787
- indentMore(view);
788
- }
789
- else {
790
- view.dispatch(state.replaceSelection(tabSpaces(head - state.doc.lineAt(head).from)), { scrollIntoView: true, userEvent: 'input' });
791
- }
792
- return true;
793
- }
794
- }
795
- if (e.key === 'Enter') {
796
- const { state } = view;
797
- const { from, to, head } = state.selection.main;
798
- // Parsed to the end, since the fence that closes the block can sit after the caret.
799
- const tree = ensureSyntaxTree(state, state.doc.length, 50) ?? syntaxTree(state);
800
- const line = state.doc.lineAt(head);
801
- const list = from === to && !inCode(tree, state.doc.toString(), head) ? listItemAt(line.text) : null;
802
- const action = enterAction({ shift: e.shiftKey, mod: isModHeld(e, isApplePlatform()) }, { inOpenFence: inOpenFence(tree, head), list, column: head - line.from });
803
- if (action === 'newline') {
804
- return insertNewline(view);
805
- }
806
- if (action === 'continue-list' && list) {
807
- view.dispatch({
808
- changes: { from: head, insert: `\n${list.next}` },
809
- selection: { anchor: head + 1 + list.next.length },
810
- scrollIntoView: true,
811
- userEvent: 'input'
812
- });
813
- return true;
814
- }
815
- if (action === 'leave-list') {
816
- view.dispatch({ changes: { from: line.from, to: line.to }, selection: { anchor: line.from }, userEvent: 'delete' });
817
- return true;
818
- }
819
- submit(e.altKey);
820
- return true;
821
- }
822
- const { from, to } = view.state.selection.main;
823
- const recalled = historyIndex !== null && text === history[historyIndex]?.text;
824
- const direction = recallDirection({ key: e.key, text, from, to, recalled });
825
- return direction !== null && recall(direction);
826
- };
827
- /* Files become attachments and a long text a file of its own; anything else the editor pastes as plain text. */
828
- const onPaste = (e, view) => {
829
- const data = e.clipboardData;
830
- if (!data) {
831
- return false;
832
- }
833
- const pasted = filesOf(data);
834
- if (pasted.length > 0) {
835
- addFiles(pasted);
836
- return true;
837
- }
838
- const inline = pasteInlineRef.current;
839
- pasteInlineRef.current = false;
840
- const clip = data.getData('text/plain');
841
- const mentions = capabilities?.mentions === false ? [] : pastedMentions(clip);
842
- if (mentions.length > 0) {
843
- // The editor's own change reads the draft as it was rendered, so the mentions join it after that change.
844
- view.dispatch(view.state.replaceSelection(clip), { scrollIntoView: true, userEvent: 'input.paste' });
845
- setDraft((current) => ({ ...current, mentions: [...current.mentions, ...mentions.filter((path) => !current.mentions.includes(path))] }));
846
- return true;
847
- }
848
- // Without attachments there is nowhere else for the text to go, so it pastes as it always did.
849
- if (inline || capabilities?.attachments === false || !pasteBecomesAttachment(clip)) {
850
- return false;
851
- }
852
- // The paste still replaces what was selected; it just puts nothing in its place.
853
- const { from, to } = view.state.selection.main;
854
- if (from !== to) {
855
- view.dispatch({ changes: { from, to }, userEvent: 'delete' });
856
- }
857
- const name = pastedTextName(draft.attachments.map((attachment) => attachment.name));
858
- addFiles([new File([clip], name, { type: 'text/plain' })]);
859
- return true;
860
- };
861
103
  /* The timeline owns the scroller; this is the one bit of it the composer needs to know. */
862
104
  const atEnd = useSyncExternalStore(subscribeTimelineEnd, () => timelineAtEnd(chatId), () => true);
863
- const mentionable = capabilities?.mentions !== false;
864
- const hasSkills = skills.length > 0;
865
- const placeholder = useMemo(() => {
866
- if (disabled) {
867
- return t('composer.placeholder.disconnected');
868
- }
869
- if (readOnly) {
870
- return t('composer.placeholder.readOnly');
105
+ const queue = info.queue ?? [];
106
+ const empty = isEmptyDraft(draft);
107
+ useEffect(() => {
108
+ if (focused) {
109
+ inputRef.current?.focus();
871
110
  }
872
- return hintedPlaceholder(placeholderLead ?? t('composer.placeholder.lead'), t('composer.placeholder.joiner'), [
873
- { key: '/', label: t('composer.placeholder.commands') },
874
- ...(mentionable ? [{ key: '@', label: t('composer.placeholder.files') }] : []),
875
- ...(hasSkills ? [{ key: '$', label: t('composer.placeholder.skills') }] : [])
876
- ]);
877
- }, [disabled, readOnly, placeholderLead, mentionable, hasSkills, t]);
878
- const attachable = capabilities?.attachments !== false;
879
- const Slot = chatHost().ComposerSlot;
880
- return (_jsxs("div", { className: "chat-composer-content pointer-events-none relative z-10 w-full", children: [!atEnd && !readOnly && (_jsx("div", { className: "absolute inset-x-0 bottom-full mb-2 flex justify-center", children: _jsx(Tooltip, { label: t('composer.jumpToEnd'), name: true, children: _jsx(Surface, { render: _jsx("button", { onClick: () => scrollTimelineToEnd(chatId) }), className: "pointer-events-auto grid h-8 w-8 place-items-center rounded-full text-text-muted hover:text-text", children: _jsx(Icon, { icon: ChevronDown, size: 16 }) }) }) })), _jsx(ChatActivity, { chatId: chatId }), _jsx("div", { className: clsx('@container/composer pointer-events-auto flex flex-col overflow-hidden rounded-2xl border shadow-float backdrop-blur-[14px] focus-ring-within', dragging
111
+ }, [focused]);
112
+ const onKeyDown = composerKeyHandler({
113
+ chatId,
114
+ host,
115
+ sendKey,
116
+ text: draft.text,
117
+ menus,
118
+ history,
119
+ noteKey: files.noteKey,
120
+ toggleStash,
121
+ setText: (next) => box.setText(next),
122
+ submit
123
+ });
124
+ return (_jsxs("div", { className: "chat-composer-content pointer-events-none relative z-10 w-full", children: [!atEnd && !readOnly && (_jsx("div", { className: "absolute inset-x-0 bottom-full mb-2 flex justify-center", children: _jsx(Tooltip, { label: t('composer.jumpToEnd'), name: true, children: _jsx(Surface, { render: _jsx("button", { onClick: () => scrollTimelineToEnd(chatId) }), className: "pointer-events-auto grid h-8 w-8 place-items-center rounded-full text-text-muted hover:text-text", children: _jsx(Icon, { icon: ChevronDown, size: 16 }) }) }) })), _jsx(ChatActivity, { chatId: chatId }), _jsx("div", { className: clsx('@container/composer pointer-events-auto flex flex-col overflow-hidden rounded-2xl border shadow-float backdrop-blur-[14px] focus-ring-within', files.dragging
881
125
  ? 'border-accent bg-[color-mix(in_srgb,var(--accent-soft)_60%,var(--surface-raised))]'
882
- : 'border-border bg-[color-mix(in_srgb,var(--surface-raised)_92%,transparent)]'), "data-takes-drop": "all", onDragOver: (e) => {
883
- if (writable && (e.dataTransfer.types.includes('Files') || carriesMentions(e.dataTransfer.types))) {
884
- e.preventDefault();
885
- e.stopPropagation();
886
- setDragging(true);
887
- }
888
- }, onDragLeave: (e) => {
889
- if (!e.currentTarget.contains(e.relatedTarget)) {
890
- setDragging(false);
891
- }
892
- }, onDrop: (e) => {
893
- e.preventDefault();
894
- e.stopPropagation();
895
- setDragging(false);
896
- addMentions(droppedMentions(e.dataTransfer));
897
- addFiles(filesOf(e.dataTransfer));
898
- inputRef.current?.focus();
899
- }, children: _jsxs(PromptComposer, { chatId: chatId, pending: pending, focused: focused, onShowElsewhere: answerPromptsElsewhere, disabled: disabled, hasDraft: !isEmptyDraft(draft), denyReason: capabilities?.denyReason === true, onAllAnswered: () => inputRef.current?.focus(), hold: hold, children: [_jsx(LimitDock, { chatId: chatId, info: info }), compactionOffer && (_jsx(ResumeCompactionDock, { tokens: compactionOffer.tokens, onCompact: compact, onDismiss: () => dismissResumeCompaction(scope, chatId, compactionOffer.turnId) })), commandMenuOpen && (_jsx("div", { id: listId, role: "listbox", "aria-label": t('composer.menu.commands'), className: "border-b border-border px-1.5 py-1.5", children: commands.map((command, index) => (_jsxs("button", { id: optionIdOf(listId, index), role: "option", "aria-selected": index === activeIndex, tabIndex: -1, "data-active": index === activeIndex, className: "cursor-row flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-xs text-text-muted", onMouseEnter: () => setMenuIndex(index), onMouseDown: (e) => e.preventDefault(), onClick: () => {
900
- setMenuIndex(index);
901
- if (command.skill) {
902
- chooseSkill(command.name);
903
- return;
904
- }
905
- setText(`/${command.name}`);
906
- inputRef.current?.focus();
907
- }, children: [_jsx(Icon, { icon: command.skill ? Zap : SquareSlash, size: 12, className: clsx('shrink-0', command.skill ? 'text-skill' : 'text-text-faint') }), _jsxs("span", { className: "font-mono text-text", children: ["/", command.name] }), _jsx("span", { className: "text-text-faint", children: command.hint })] }, command.name))) })), skillMenuOpen && (_jsx("div", { id: listId, role: "listbox", "aria-label": t('composer.menu.skills'), className: "border-b border-border px-1.5 py-1.5", children: skillMatches.map((skill, index) => (_jsxs("button", { id: optionIdOf(listId, index), role: "option", "aria-selected": index === activeIndex, tabIndex: -1, "data-active": index === activeIndex, className: "cursor-row flex w-full items-start gap-2 rounded-md px-2 py-1 text-left text-xs text-text-muted", onMouseEnter: () => setMenuIndex(index), onMouseDown: (e) => e.preventDefault(), onClick: () => chooseSkill(skill.name), children: [_jsx(Icon, { icon: Zap, size: 12, className: "mt-0.5 shrink-0 text-skill" }), _jsxs("span", { className: "flex min-w-0 flex-col", children: [_jsxs("span", { className: "truncate font-mono text-text", children: ["$", skill.name] }), skill.description !== '' && _jsx("span", { className: "line-clamp-1 text-text-faint", children: skill.description })] })] }, skill.name))) })), mentionMenuOpen && (_jsxs("div", { className: "border-b border-border px-1.5 py-1.5", children: [mentionCount > 0 && (_jsxs("div", { id: listId, role: "listbox", "aria-label": t('composer.menu.mentions'), children: [chatMatches.length > 0 && (_jsxs("div", { role: "group", "aria-labelledby": mentionsLabelId, children: [_jsx(Menu.Label, { id: mentionsLabelId, children: t('composer.mentions.chats') }), chatMatches.map((chat, index) => (_jsxs("button", { id: optionIdOf(listId, index), role: "option", "aria-selected": index === activeIndex, tabIndex: -1, "data-active": index === activeIndex, className: "cursor-row flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-xs text-text-muted", onMouseEnter: () => setMenuIndex(index), onMouseDown: (e) => e.preventDefault(), onClick: () => chooseChat(chat.id), children: [_jsx(Icon, { icon: MessageSquare, size: 14, className: "shrink-0 text-text-faint" }), _jsx("span", { className: "truncate text-text", children: chat.title || t('chatReference.untitled') })] }, chat.id)))] })), files.length > 0 && (_jsxs("div", { role: "group", ...(filesLabelShown ? { 'aria-labelledby': filesLabelId } : { 'aria-label': t('composer.mentions.files') }), children: [filesLabelShown && (_jsx(Menu.Label, { id: filesLabelId, children: mention.query === '' ? t('composer.mentions.here') : t('composer.mentions.files') })), files.map((path, index) => {
908
- const { name, dir } = splitPath(path);
909
- return (_jsxs("button", { id: optionIdOf(listId, chatMatches.length + index), role: "option", "aria-selected": chatMatches.length + index === activeIndex, tabIndex: -1, "data-active": chatMatches.length + index === activeIndex, className: "cursor-row flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-xs text-text-muted", onMouseEnter: () => setMenuIndex(chatMatches.length + index), onMouseDown: (e) => e.preventDefault(), onClick: () => chooseMention(path), children: [_jsx(FileIcon, { path: path, size: 14 }), _jsx("span", { className: "truncate font-mono text-text", children: name }), dir && _jsx("span", { className: "min-w-0 truncate text-text-faint", children: dir })] }, path));
910
- })] }))] })), mentionCount === 0 && (_jsx("div", { className: "px-2 py-1 text-xs text-text-faint", children: mention.query ? t('composer.mentions.noMatch') : t('composer.mentions.empty') }))] })), queue.length > 0 && (_jsxs("div", { className: "flex flex-col gap-1 border-b border-border px-2 py-1.5", children: [info.queuePaused === true && _jsx("p", { className: "px-1.5 text-xs text-text-muted", children: t('composer.queue.paused') }), queue.map((message) => {
911
- const sendNow = () => {
912
- scrollTimelineToEnd(chatId, 'instant');
913
- void actions.sendNow(chatId, message.id).catch(() => undefined);
914
- };
915
- const unqueue = () => void actions.unqueue(chatId, message.id).catch(() => undefined);
916
- const edit = () => void takeBack(message);
917
- return (_jsxs(ContextMenu.Root, { children: [_jsxs(ContextMenu.Trigger, { className: "group/queued flex items-center gap-2 rounded-md px-1.5 py-1 text-xs text-text-muted", children: [_jsx(Icon, { icon: Clock, size: 12, className: "shrink-0 text-text-faint" }), _jsx("span", { className: "min-w-0 grow truncate", children: message.text || t('composer.queue.attachments', { count: message.attachments?.length ?? 0 }) }), _jsxs(ButtonGroup, { render: _jsx("span", {}), className: "opacity-0 transition-opacity group-hover/queued:opacity-100 focus-within:opacity-100", children: [_jsx(IconButton, { icon: FastForward, size: "2xs", label: t('composer.queue.sendNow'), onClick: sendNow }), _jsx(IconButton, { icon: Pencil, size: "2xs", label: t('common.action.edit'), disabled: takingBack !== null, onClick: edit }), _jsx(IconButton, { icon: X, size: "2xs", label: t('common.action.remove'), onClick: unqueue })] })] }), _jsxs(ContextMenu.Popup, { children: [_jsxs(ContextMenu.Item, { onClick: sendNow, children: [_jsx(Icon, { icon: FastForward, size: 14 }), " ", t('composer.queue.sendNow')] }), _jsxs(ContextMenu.Item, { disabled: takingBack !== null, onClick: edit, children: [_jsx(Icon, { icon: Pencil, size: 14 }), " ", t('common.action.edit')] }), _jsxs(ContextMenu.Item, { disabled: message.text === '', onClick: () => copyText(message.text), children: [_jsx(Icon, { icon: Copy, size: 14 }), " ", t('common.action.copy')] }), _jsx(ContextMenu.Separator, {}), _jsxs(ContextMenu.Item, { className: "text-status-error", onClick: unqueue, children: [_jsx(Icon, { icon: X, size: 14 }), " ", t('common.action.remove')] })] })] }, message.id));
918
- })] })), quote !== '' && (_jsxs("div", { className: "flex items-center gap-2 px-5 pt-4 @max-md/composer:px-3.5 @max-md/composer:pt-3", children: [quoteSource === null ? (_jsx("span", { className: "min-w-0 grow truncate border-l-2 border-border-strong pl-2.5 text-xs text-text-muted", children: quote })) : (_jsx(Tooltip, { label: t('composer.quote.goToSource'), children: _jsx("button", { type: "button", className: "min-w-0 grow truncate border-l-2 border-border-strong pl-2.5 text-left text-xs text-text-muted hover:text-text", onClick: () => jumpToTimelineItem(scope.keyOf(chatId), quoteSource, {
919
- flash: true,
920
- onMissing: () => setNotice(t('rows.user.quoteGone'))
921
- }), children: quote }) })), _jsx(IconButton, { icon: X, size: "2xs", label: t('composer.quote.remove'), onClick: removeQuote })] })), draft.chats.length > 0 && (_jsx("div", { className: "flex flex-wrap gap-1.5 px-5 pt-4 @max-md/composer:px-3.5 @max-md/composer:pt-3", children: draft.chats.map((id) => (_jsx(ChatReferenceChip, { chatId: id, onRemove: () => removeChat(id) }, id))) })), draft.attachments.length > 0 && (_jsx("div", { className: "flex flex-wrap gap-2 px-5 pt-4 @max-md/composer:px-3.5 @max-md/composer:pt-3", children: draft.attachments.map((attachment, index) => (_jsxs("div", { className: "group/thumb relative", children: [isImageAttachment(attachment.mime) ? (_jsx(UploadThumb, { upload: attachment })) : (_jsxs("span", { className: "flex h-14 w-36 flex-col justify-center gap-0.5 rounded-lg border border-border bg-surface-sunken px-2.5", children: [_jsxs("span", { className: "flex items-center gap-1.5 text-xs text-text", children: [_jsx(Icon, { icon: Paperclip, size: 12, className: "shrink-0 text-text-faint" }), _jsx("span", { className: "truncate", children: attachment.name })] }), _jsx("span", { className: "pl-5 text-xs text-text-faint", children: formatBytes(uploadBytes(attachment)) })] })), _jsx(IconButton, { icon: X, size: "2xs", label: t('composer.removeAttachment', { name: attachment.name }), className: "absolute -top-1.5 -right-1.5 border border-border bg-surface-raised opacity-0 transition-opacity group-hover/thumb:opacity-100 focus-visible:opacity-100", onClick: () => removeAttachment(index) })] }, `${attachment.name}-${index}`))) })), _jsx(ComposerInput, { ref: inputRef, dictationToolbar: dictationToolbar, className: "composer-input select-text text-sm leading-normal text-text", value: text, placeholder: placeholder, disabled: !writable, tabbable: focused, extensions: editorExtensions, aria: inputAria, onChange: (value, selection, state) => {
126
+ : 'border-border bg-[color-mix(in_srgb,var(--surface-raised)_92%,transparent)]'), ...files.dropTarget, children: _jsxs(PromptComposer, { chatId: chatId, pending: pending, focused: focused, onShowElsewhere: answerPromptsElsewhere, disabled: disabled, hasDraft: !empty, denyReason: capabilities?.denyReason === true, onAllAnswered: () => inputRef.current?.focus(), hold: hold, children: [_jsx(LimitDock, { chatId: chatId, info: info }), _jsx(GoalDock, { chatId: chatId, info: info, goals: capabilities?.goals }), compactionOffer && (_jsx(ResumeCompactionDock, { tokens: compactionOffer.tokens, onCompact: controls.compact, onDismiss: () => dismissResumeCompaction(scope, chatId, compactionOffer.turnId) })), _jsx(ComposerMenu, { menus: menus }), queue.length > 0 && (_jsx(QueuedMessages, { chatId: chatId, queue: queue, paused: info.queuePaused === true, takingBack: takingBack !== null, onEdit: (message) => void takeBack(message) })), draft.quote !== '' && (_jsx(DraftQuote, { chatId: chatId, quote: draft.quote, source: draft.quoteSource, onRemove: box.removeQuote, onSourceGone: () => notice.setNotice(t('rows.user.quoteGone')) })), draft.chats.length > 0 && _jsx(DraftChats, { chats: draft.chats, onRemove: box.removeChat }), draft.attachments.length > 0 && _jsx(DraftAttachments, { attachments: draft.attachments, onRemove: box.removeAttachment }), _jsx(ComposerInput, { ref: inputRef, dictationToolbar: dictationToolbar, className: "composer-input select-text text-sm leading-normal text-text", value: draft.text, placeholder: placeholder, disabled: !writable, tabbable: focused, extensions: editorExtensions, aria: menus.inputAria, onChange: (value, selection, state) => {
922
127
  hold.noteInput();
923
- setText(value);
924
- setMenuIndex(0);
925
- trackTriggers(value, selection, state);
926
- if (historyIndex !== null && value !== history[historyIndex]?.text) {
927
- setHistoryIndex(null);
928
- }
929
- }, onSelectionChange: trackTriggers, onBlur: () => {
930
- setMention(null);
931
- setSkillQuery(null);
128
+ box.setText(value);
129
+ menus.setMenuIndex(0);
130
+ menus.trackTriggers(value, selection, state);
131
+ history.edited(value);
132
+ }, onSelectionChange: menus.trackTriggers, onBlur: () => {
133
+ menus.close();
932
134
  hold.release('blur');
933
- }, onComposing: hold.setComposing, onKeyDown: onKeyDown, onPaste: onPaste }), notice && (_jsx("div", { className: "px-5 pb-1 text-xs text-status-error @max-md/composer:px-3.5", role: "alert", children: notice })), guard.visible && (_jsxs("div", { className: clsx('px-5 pb-1 text-right text-xs tabular-nums @max-md/composer:px-3.5', guard.tooLong ? 'text-status-error' : 'text-text-faint'), children: [formatNumber(guard.count), " / ", formatNumber(PROMPT_MAX_CHARS), guard.tooLong && ` ${t('composer.tooLong')}`] })), _jsxs("div", { className: "flex items-center gap-2 pt-3 pr-3.5 pb-3.5 pl-5 @max-md/composer:gap-1.5 @max-md/composer:p-3 @max-md/composer:pt-2.5", children: [attachable && (_jsx(Tooltip, { label: t('composer.attach'), name: true, children: _jsx("button", { type: "button", className: "grid h-8 w-8 shrink-0 place-items-center rounded-full border border-border text-text-muted hover:bg-surface-hover hover:text-text disabled:opacity-50", disabled: !writable, onClick: () => fileInputRef.current?.click(), children: _jsx(Icon, { icon: Plus, size: 16 }) }) })), _jsx("input", { ref: fileInputRef, type: "file", multiple: true, hidden: true, onChange: (e) => {
934
- addFiles(Array.from(e.target.files ?? []));
935
- e.target.value = '';
936
- inputRef.current?.focus();
937
- } }), _jsx(RunSettings, { disabled: configurationPending || !writable, providers: pickable, provider: info.provider, selection: info.selection, model: model, runtimeMode: info.runtimeMode, effectiveRuntimeMode: info.effectiveRuntimeMode, permissionMode: info.permissionMode, open: modelPickerOpen, onOpenChange: setModelPickerOpen, onModel: chooseModel, onOption: (id, value) => configure({ selection: { ...info.selection, options: { ...info.selection.options, [id]: value } } }), onMode: (runtimeMode) => configure({ runtimeMode }), usage: info.usage, compactDisabled: busy || !writable, onCompact: compact, account: accountChoice === null ? null : { choice: accountChoice, started, onPick: chooseAccount } }), _jsx(StashPicker, { onRestore: restoreStashed }), Slot !== null && (_jsx(ErrorBoundary, { label: t('composer.slotFailed'), resetKeys: [chatId], compact: true, className: "relative rounded-lg", children: _jsx(Slot, { scopeId: scope.id, chatId: chatId, disabled: !writable, insert: insertIntoDraft }) })), _jsx("span", { className: "grow" }), _jsxs("div", { className: "flex h-9 shrink-0 items-center gap-0.5 rounded-full bg-surface-hover", children: [_jsx("div", { ref: setDictationToolbar, className: "flex items-center pl-1 empty:hidden [&_.icon-btn]:rounded-full" }), busy && (_jsx(Tooltip, { label: composerStopLabel(), name: true, children: _jsx("button", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-status-error text-accent-text", onClick: (event) => stop(event.shiftKey), children: _jsx(Icon, { icon: Square, size: 16 }) }) })), (!busy || !isEmptyDraft(draft)) && (_jsx(Tooltip, { label: t(sendLabelKey(busy, canSteer, sendDelivery)), kbd: KEY_SHORTCUTS.modEnter, name: true, children: _jsx("button", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-accent text-accent-text hover:brightness-90 disabled:opacity-50 disabled:hover:brightness-100", disabled: isEmptyDraft(draft) || !writable || guard.tooLong, onClick: (event) => submit(event.altKey), children: _jsx(Icon, { icon: ArrowUp, size: 16 }) }) }))] })] })] }) }), _jsx(PromptDialog, { open: confirmClear, title: t('composer.clear.title'), description: t('composer.clear.description'), confirmLabel: t('composer.clear.confirm'), danger: true, fallbackMessage: t('composer.notice.clearFailed'), onConfirm: forceClearThread, onOpenChange: () => setConfirmClear(false) })] }));
135
+ }, onComposing: hold.setComposing, onKeyDown: onKeyDown, onPaste: files.onPaste }), notice.notice && (_jsx("div", { className: "px-5 pb-1 text-xs text-status-error @max-md/composer:px-3.5", role: "alert", children: notice.notice })), guard.visible && (_jsxs("div", { className: clsx('px-5 pb-1 text-right text-xs tabular-nums @max-md/composer:px-3.5', guard.tooLong ? 'text-status-error' : 'text-text-faint'), children: [formatNumber(guard.count), " / ", formatNumber(PROMPT_MAX_CHARS), guard.tooLong && ` ${t('composer.tooLong')}`] })), _jsx(ComposerControls, { chatId: chatId, info: info, providerFixed: providerFixed, writable: writable, attachable: capabilities?.attachments !== false, controls: controls, send: {
136
+ visible: !busy || !empty,
137
+ disabled: empty || !writable || guard.tooLong,
138
+ label: t(sendLabelKey(busy, steerable, sendDelivery)),
139
+ kbd: sendShortcut(sendKey, draft.text.includes('\n')),
140
+ onSend: (alternate) => submit(alternate ? 'alternate' : 'default')
141
+ }, dictationToolbar: setDictationToolbar, onFiles: (picked) => {
142
+ files.addFiles(picked);
143
+ inputRef.current?.focus();
144
+ }, onRestore: restoreStashed, insert: (added) => {
145
+ if (writable) {
146
+ inputRef.current?.insert(added);
147
+ }
148
+ } })] }) }), _jsx(PromptDialog, { open: controls.confirmClear, title: t('composer.clear.title'), description: t('composer.clear.description'), confirmLabel: t('composer.clear.confirm'), danger: true, fallbackMessage: t('composer.notice.clearFailed'), onConfirm: controls.forceClearThread, onOpenChange: controls.cancelClear })] }));
938
149
  }