index.tsx 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. import { BoxRenderable, TextareaRenderable, MouseEvent, PasteEvent, t, dim, fg, type KeyBinding } from "@opentui/core"
  2. import { createEffect, createMemo, type JSX, onMount, createSignal, onCleanup, Show, Switch, Match } from "solid-js"
  3. import "opentui-spinner/solid"
  4. import { useLocal } from "@tui/context/local"
  5. import { useTheme } from "@tui/context/theme"
  6. import { EmptyBorder } from "@tui/component/border"
  7. import { useSDK } from "@tui/context/sdk"
  8. import { useRoute } from "@tui/context/route"
  9. import { useSync } from "@tui/context/sync"
  10. import { Identifier } from "@/id/id"
  11. import { createStore, produce } from "solid-js/store"
  12. import { useKeybind } from "@tui/context/keybind"
  13. import { Keybind } from "@/util/keybind"
  14. import { usePromptHistory, type PromptInfo } from "./history"
  15. import { type AutocompleteRef, Autocomplete } from "./autocomplete"
  16. import { useCommandDialog } from "../dialog-command"
  17. import { useRenderer } from "@opentui/solid"
  18. import { Editor } from "@tui/util/editor"
  19. import { useExit } from "../../context/exit"
  20. import { Clipboard } from "../../util/clipboard"
  21. import type { FilePart } from "@opencode-ai/sdk/v2"
  22. import { TuiEvent } from "../../event"
  23. import { iife } from "@/util/iife"
  24. import { Locale } from "@/util/locale"
  25. import { createColors, createFrames } from "../../ui/spinner.ts"
  26. import { useDialog } from "@tui/ui/dialog"
  27. import { DialogProvider as DialogProviderConnect } from "../dialog-provider"
  28. import { DialogAlert } from "../../ui/dialog-alert"
  29. import { useToast } from "../../ui/toast"
  30. export type PromptProps = {
  31. sessionID?: string
  32. disabled?: boolean
  33. onSubmit?: () => void
  34. ref?: (ref: PromptRef) => void
  35. hint?: JSX.Element
  36. showPlaceholder?: boolean
  37. }
  38. export type PromptRef = {
  39. focused: boolean
  40. current: PromptInfo
  41. set(prompt: PromptInfo): void
  42. reset(): void
  43. blur(): void
  44. focus(): void
  45. submit(): void
  46. }
  47. const PLACEHOLDERS = ["Fix a TODO in the codebase", "What is the tech stack of this project?", "Fix broken tests"]
  48. const TEXTAREA_ACTIONS = [
  49. "submit",
  50. "newline",
  51. "move-left",
  52. "move-right",
  53. "move-up",
  54. "move-down",
  55. "select-left",
  56. "select-right",
  57. "select-up",
  58. "select-down",
  59. "line-home",
  60. "line-end",
  61. "select-line-home",
  62. "select-line-end",
  63. "visual-line-home",
  64. "visual-line-end",
  65. "select-visual-line-home",
  66. "select-visual-line-end",
  67. "buffer-home",
  68. "buffer-end",
  69. "select-buffer-home",
  70. "select-buffer-end",
  71. "delete-line",
  72. "delete-to-line-end",
  73. "delete-to-line-start",
  74. "backspace",
  75. "delete",
  76. "undo",
  77. "redo",
  78. "word-forward",
  79. "word-backward",
  80. "select-word-forward",
  81. "select-word-backward",
  82. "delete-word-forward",
  83. "delete-word-backward",
  84. ] as const
  85. function mapTextareaKeybindings(
  86. keybinds: Record<string, Keybind.Info[]>,
  87. action: (typeof TEXTAREA_ACTIONS)[number],
  88. ): KeyBinding[] {
  89. const configKey = `input_${action.replace(/-/g, "_")}`
  90. const bindings = keybinds[configKey]
  91. if (!bindings) return []
  92. return bindings.map((binding) => ({
  93. name: binding.name,
  94. ctrl: binding.ctrl || undefined,
  95. meta: binding.meta || undefined,
  96. shift: binding.shift || undefined,
  97. super: binding.super || undefined,
  98. action,
  99. }))
  100. }
  101. export function Prompt(props: PromptProps) {
  102. let input: TextareaRenderable
  103. let anchor: BoxRenderable
  104. let autocomplete: AutocompleteRef
  105. const keybind = useKeybind()
  106. const local = useLocal()
  107. const sdk = useSDK()
  108. const route = useRoute()
  109. const sync = useSync()
  110. const dialog = useDialog()
  111. const toast = useToast()
  112. const status = createMemo(() => sync.data.session_status?.[props.sessionID ?? ""] ?? { type: "idle" })
  113. const history = usePromptHistory()
  114. const command = useCommandDialog()
  115. const renderer = useRenderer()
  116. const { theme, syntax } = useTheme()
  117. function promptModelWarning() {
  118. toast.show({
  119. variant: "warning",
  120. message: "Connect a provider to send prompts",
  121. duration: 3000,
  122. })
  123. if (sync.data.provider.length === 0) {
  124. dialog.replace(() => <DialogProviderConnect />)
  125. }
  126. }
  127. const textareaKeybindings = createMemo(() => {
  128. const keybinds = keybind.all
  129. return [
  130. { name: "return", action: "submit" },
  131. { name: "return", meta: true, action: "newline" },
  132. ...TEXTAREA_ACTIONS.flatMap((action) => mapTextareaKeybindings(keybinds, action)),
  133. ] satisfies KeyBinding[]
  134. })
  135. const fileStyleId = syntax().getStyleId("extmark.file")!
  136. const agentStyleId = syntax().getStyleId("extmark.agent")!
  137. const pasteStyleId = syntax().getStyleId("extmark.paste")!
  138. let promptPartTypeId: number
  139. command.register(() => {
  140. return [
  141. {
  142. title: "Clear prompt",
  143. value: "prompt.clear",
  144. category: "Prompt",
  145. disabled: true,
  146. onSelect: (dialog) => {
  147. input.extmarks.clear()
  148. input.clear()
  149. dialog.clear()
  150. },
  151. },
  152. {
  153. title: "Submit prompt",
  154. value: "prompt.submit",
  155. disabled: true,
  156. keybind: "input_submit",
  157. category: "Prompt",
  158. onSelect: (dialog) => {
  159. if (!input.focused) return
  160. submit()
  161. dialog.clear()
  162. },
  163. },
  164. {
  165. title: "Paste",
  166. value: "prompt.paste",
  167. disabled: true,
  168. keybind: "input_paste",
  169. category: "Prompt",
  170. onSelect: async () => {
  171. const content = await Clipboard.read()
  172. if (content?.mime.startsWith("image/")) {
  173. await pasteImage({
  174. filename: "clipboard",
  175. mime: content.mime,
  176. content: content.data,
  177. })
  178. }
  179. },
  180. },
  181. {
  182. title: "Interrupt session",
  183. value: "session.interrupt",
  184. keybind: "session_interrupt",
  185. disabled: status().type === "idle",
  186. category: "Session",
  187. onSelect: (dialog) => {
  188. if (autocomplete.visible) return
  189. if (!input.focused) return
  190. // TODO: this should be its own command
  191. if (store.mode === "shell") {
  192. setStore("mode", "normal")
  193. return
  194. }
  195. if (!props.sessionID) return
  196. setStore("interrupt", store.interrupt + 1)
  197. setTimeout(() => {
  198. setStore("interrupt", 0)
  199. }, 5000)
  200. if (store.interrupt >= 2) {
  201. sdk.client.session.abort({
  202. sessionID: props.sessionID,
  203. })
  204. setStore("interrupt", 0)
  205. }
  206. dialog.clear()
  207. },
  208. },
  209. {
  210. title: "Open editor",
  211. category: "Session",
  212. keybind: "editor_open",
  213. value: "prompt.editor",
  214. onSelect: async (dialog, trigger) => {
  215. dialog.clear()
  216. // replace summarized text parts with the actual text
  217. const text = store.prompt.parts
  218. .filter((p) => p.type === "text")
  219. .reduce((acc, p) => {
  220. if (!p.source) return acc
  221. return acc.replace(p.source.text.value, p.text)
  222. }, store.prompt.input)
  223. const nonTextParts = store.prompt.parts.filter((p) => p.type !== "text")
  224. const value = trigger === "prompt" ? "" : text
  225. const content = await Editor.open({ value, renderer })
  226. if (!content) return
  227. input.setText(content)
  228. // Update positions for nonTextParts based on their location in new content
  229. // Filter out parts whose virtual text was deleted
  230. // this handles a case where the user edits the text in the editor
  231. // such that the virtual text moves around or is deleted
  232. const updatedNonTextParts = nonTextParts
  233. .map((part) => {
  234. let virtualText = ""
  235. if (part.type === "file" && part.source?.text) {
  236. virtualText = part.source.text.value
  237. } else if (part.type === "agent" && part.source) {
  238. virtualText = part.source.value
  239. }
  240. if (!virtualText) return part
  241. const newStart = content.indexOf(virtualText)
  242. // if the virtual text is deleted, remove the part
  243. if (newStart === -1) return null
  244. const newEnd = newStart + virtualText.length
  245. if (part.type === "file" && part.source?.text) {
  246. return {
  247. ...part,
  248. source: {
  249. ...part.source,
  250. text: {
  251. ...part.source.text,
  252. start: newStart,
  253. end: newEnd,
  254. },
  255. },
  256. }
  257. }
  258. if (part.type === "agent" && part.source) {
  259. return {
  260. ...part,
  261. source: {
  262. ...part.source,
  263. start: newStart,
  264. end: newEnd,
  265. },
  266. }
  267. }
  268. return part
  269. })
  270. .filter((part) => part !== null)
  271. setStore("prompt", {
  272. input: content,
  273. // keep only the non-text parts because the text parts were
  274. // already expanded inline
  275. parts: updatedNonTextParts,
  276. })
  277. restoreExtmarksFromParts(updatedNonTextParts)
  278. input.cursorOffset = Bun.stringWidth(content)
  279. },
  280. },
  281. ]
  282. })
  283. sdk.event.on(TuiEvent.PromptAppend.type, (evt) => {
  284. input.insertText(evt.properties.text)
  285. setTimeout(() => {
  286. input.getLayoutNode().markDirty()
  287. input.gotoBufferEnd()
  288. renderer.requestRender()
  289. }, 0)
  290. })
  291. createEffect(() => {
  292. if (props.disabled) input.cursorColor = theme.backgroundElement
  293. if (!props.disabled) input.cursorColor = theme.text
  294. })
  295. const [store, setStore] = createStore<{
  296. prompt: PromptInfo
  297. mode: "normal" | "shell"
  298. extmarkToPartIndex: Map<number, number>
  299. interrupt: number
  300. placeholder: number
  301. }>({
  302. placeholder: Math.floor(Math.random() * PLACEHOLDERS.length),
  303. prompt: {
  304. input: "",
  305. parts: [],
  306. },
  307. mode: "normal",
  308. extmarkToPartIndex: new Map(),
  309. interrupt: 0,
  310. })
  311. createEffect(() => {
  312. input.focus()
  313. })
  314. onMount(() => {
  315. promptPartTypeId = input.extmarks.registerType("prompt-part")
  316. })
  317. function restoreExtmarksFromParts(parts: PromptInfo["parts"]) {
  318. input.extmarks.clear()
  319. setStore("extmarkToPartIndex", new Map())
  320. parts.forEach((part, partIndex) => {
  321. let start = 0
  322. let end = 0
  323. let virtualText = ""
  324. let styleId: number | undefined
  325. if (part.type === "file" && part.source?.text) {
  326. start = part.source.text.start
  327. end = part.source.text.end
  328. virtualText = part.source.text.value
  329. styleId = fileStyleId
  330. } else if (part.type === "agent" && part.source) {
  331. start = part.source.start
  332. end = part.source.end
  333. virtualText = part.source.value
  334. styleId = agentStyleId
  335. } else if (part.type === "text" && part.source?.text) {
  336. start = part.source.text.start
  337. end = part.source.text.end
  338. virtualText = part.source.text.value
  339. styleId = pasteStyleId
  340. }
  341. if (virtualText) {
  342. const extmarkId = input.extmarks.create({
  343. start,
  344. end,
  345. virtual: true,
  346. styleId,
  347. typeId: promptPartTypeId,
  348. })
  349. setStore("extmarkToPartIndex", (map: Map<number, number>) => {
  350. const newMap = new Map(map)
  351. newMap.set(extmarkId, partIndex)
  352. return newMap
  353. })
  354. }
  355. })
  356. }
  357. function syncExtmarksWithPromptParts() {
  358. const allExtmarks = input.extmarks.getAllForTypeId(promptPartTypeId)
  359. setStore(
  360. produce((draft) => {
  361. const newMap = new Map<number, number>()
  362. const newParts: typeof draft.prompt.parts = []
  363. for (const extmark of allExtmarks) {
  364. const partIndex = draft.extmarkToPartIndex.get(extmark.id)
  365. if (partIndex !== undefined) {
  366. const part = draft.prompt.parts[partIndex]
  367. if (part) {
  368. if (part.type === "agent" && part.source) {
  369. part.source.start = extmark.start
  370. part.source.end = extmark.end
  371. } else if (part.type === "file" && part.source?.text) {
  372. part.source.text.start = extmark.start
  373. part.source.text.end = extmark.end
  374. } else if (part.type === "text" && part.source?.text) {
  375. part.source.text.start = extmark.start
  376. part.source.text.end = extmark.end
  377. }
  378. newMap.set(extmark.id, newParts.length)
  379. newParts.push(part)
  380. }
  381. }
  382. }
  383. draft.extmarkToPartIndex = newMap
  384. draft.prompt.parts = newParts
  385. }),
  386. )
  387. }
  388. props.ref?.({
  389. get focused() {
  390. return input.focused
  391. },
  392. get current() {
  393. return store.prompt
  394. },
  395. focus() {
  396. input.focus()
  397. },
  398. blur() {
  399. input.blur()
  400. },
  401. set(prompt) {
  402. input.setText(prompt.input)
  403. setStore("prompt", prompt)
  404. restoreExtmarksFromParts(prompt.parts)
  405. input.gotoBufferEnd()
  406. },
  407. reset() {
  408. input.clear()
  409. input.extmarks.clear()
  410. setStore("prompt", {
  411. input: "",
  412. parts: [],
  413. })
  414. setStore("extmarkToPartIndex", new Map())
  415. },
  416. submit() {
  417. submit()
  418. },
  419. })
  420. async function submit() {
  421. if (props.disabled) return
  422. if (autocomplete?.visible) return
  423. if (!store.prompt.input) return
  424. const trimmed = store.prompt.input.trim()
  425. if (trimmed === "exit" || trimmed === "quit" || trimmed === ":q") {
  426. exit()
  427. return
  428. }
  429. const selectedModel = local.model.current()
  430. if (!selectedModel) {
  431. promptModelWarning()
  432. return
  433. }
  434. const sessionID = props.sessionID
  435. ? props.sessionID
  436. : await (async () => {
  437. const sessionID = await sdk.client.session.create({}).then((x) => x.data!.id)
  438. return sessionID
  439. })()
  440. const messageID = Identifier.ascending("message")
  441. let inputText = store.prompt.input
  442. // Expand pasted text inline before submitting
  443. const allExtmarks = input.extmarks.getAllForTypeId(promptPartTypeId)
  444. const sortedExtmarks = allExtmarks.sort((a: { start: number }, b: { start: number }) => b.start - a.start)
  445. for (const extmark of sortedExtmarks) {
  446. const partIndex = store.extmarkToPartIndex.get(extmark.id)
  447. if (partIndex !== undefined) {
  448. const part = store.prompt.parts[partIndex]
  449. if (part?.type === "text" && part.text) {
  450. const before = inputText.slice(0, extmark.start)
  451. const after = inputText.slice(extmark.end)
  452. inputText = before + part.text + after
  453. }
  454. }
  455. }
  456. // Filter out text parts (pasted content) since they're now expanded inline
  457. const nonTextParts = store.prompt.parts.filter((part) => part.type !== "text")
  458. // Capture mode before it gets reset
  459. const currentMode = store.mode
  460. if (store.mode === "shell") {
  461. sdk.client.session.shell({
  462. sessionID,
  463. agent: local.agent.current().name,
  464. model: {
  465. providerID: selectedModel.providerID,
  466. modelID: selectedModel.modelID,
  467. },
  468. command: inputText,
  469. })
  470. setStore("mode", "normal")
  471. } else if (
  472. inputText.startsWith("/") &&
  473. iife(() => {
  474. const command = inputText.split(" ")[0].slice(1)
  475. console.log(command)
  476. return sync.data.command.some((x) => x.name === command)
  477. })
  478. ) {
  479. let [command, ...args] = inputText.split(" ")
  480. sdk.client.session.command({
  481. sessionID,
  482. command: command.slice(1),
  483. arguments: args.join(" "),
  484. agent: local.agent.current().name,
  485. model: `${selectedModel.providerID}/${selectedModel.modelID}`,
  486. messageID,
  487. })
  488. } else {
  489. sdk.client.session.prompt({
  490. sessionID,
  491. ...selectedModel,
  492. messageID,
  493. agent: local.agent.current().name,
  494. model: selectedModel,
  495. parts: [
  496. {
  497. id: Identifier.ascending("part"),
  498. type: "text",
  499. text: inputText,
  500. },
  501. ...nonTextParts.map((x) => ({
  502. id: Identifier.ascending("part"),
  503. ...x,
  504. })),
  505. ],
  506. })
  507. }
  508. history.append({
  509. ...store.prompt,
  510. mode: currentMode,
  511. })
  512. input.extmarks.clear()
  513. setStore("prompt", {
  514. input: "",
  515. parts: [],
  516. })
  517. setStore("extmarkToPartIndex", new Map())
  518. props.onSubmit?.()
  519. // temporary hack to make sure the message is sent
  520. if (!props.sessionID)
  521. setTimeout(() => {
  522. route.navigate({
  523. type: "session",
  524. sessionID,
  525. })
  526. }, 50)
  527. input.clear()
  528. }
  529. const exit = useExit()
  530. function pasteText(text: string, virtualText: string) {
  531. const currentOffset = input.visualCursor.offset
  532. const extmarkStart = currentOffset
  533. const extmarkEnd = extmarkStart + virtualText.length
  534. input.insertText(virtualText + " ")
  535. const extmarkId = input.extmarks.create({
  536. start: extmarkStart,
  537. end: extmarkEnd,
  538. virtual: true,
  539. styleId: pasteStyleId,
  540. typeId: promptPartTypeId,
  541. })
  542. setStore(
  543. produce((draft) => {
  544. const partIndex = draft.prompt.parts.length
  545. draft.prompt.parts.push({
  546. type: "text" as const,
  547. text,
  548. source: {
  549. text: {
  550. start: extmarkStart,
  551. end: extmarkEnd,
  552. value: virtualText,
  553. },
  554. },
  555. })
  556. draft.extmarkToPartIndex.set(extmarkId, partIndex)
  557. }),
  558. )
  559. }
  560. async function pasteImage(file: { filename?: string; content: string; mime: string }) {
  561. const currentOffset = input.visualCursor.offset
  562. const extmarkStart = currentOffset
  563. const count = store.prompt.parts.filter((x) => x.type === "file").length
  564. const virtualText = `[Image ${count + 1}]`
  565. const extmarkEnd = extmarkStart + virtualText.length
  566. const textToInsert = virtualText + " "
  567. input.insertText(textToInsert)
  568. const extmarkId = input.extmarks.create({
  569. start: extmarkStart,
  570. end: extmarkEnd,
  571. virtual: true,
  572. styleId: pasteStyleId,
  573. typeId: promptPartTypeId,
  574. })
  575. const part: Omit<FilePart, "id" | "messageID" | "sessionID"> = {
  576. type: "file" as const,
  577. mime: file.mime,
  578. filename: file.filename,
  579. url: `data:${file.mime};base64,${file.content}`,
  580. source: {
  581. type: "file",
  582. path: file.filename ?? "",
  583. text: {
  584. start: extmarkStart,
  585. end: extmarkEnd,
  586. value: virtualText,
  587. },
  588. },
  589. }
  590. setStore(
  591. produce((draft) => {
  592. const partIndex = draft.prompt.parts.length
  593. draft.prompt.parts.push(part)
  594. draft.extmarkToPartIndex.set(extmarkId, partIndex)
  595. }),
  596. )
  597. return
  598. }
  599. const highlight = createMemo(() => {
  600. if (keybind.leader) return theme.border
  601. if (store.mode === "shell") return theme.primary
  602. return local.agent.color(local.agent.current().name)
  603. })
  604. const spinnerDef = createMemo(() => {
  605. const color = local.agent.color(local.agent.current().name)
  606. return {
  607. frames: createFrames({
  608. color,
  609. style: "blocks",
  610. inactiveFactor: 0.6,
  611. // enableFading: false,
  612. minAlpha: 0.3,
  613. }),
  614. color: createColors({
  615. color,
  616. style: "blocks",
  617. inactiveFactor: 0.6,
  618. // enableFading: false,
  619. minAlpha: 0.3,
  620. }),
  621. }
  622. })
  623. return (
  624. <>
  625. <Autocomplete
  626. sessionID={props.sessionID}
  627. ref={(r) => (autocomplete = r)}
  628. anchor={() => anchor}
  629. input={() => input}
  630. setPrompt={(cb) => {
  631. setStore("prompt", produce(cb))
  632. }}
  633. setExtmark={(partIndex, extmarkId) => {
  634. setStore("extmarkToPartIndex", (map: Map<number, number>) => {
  635. const newMap = new Map(map)
  636. newMap.set(extmarkId, partIndex)
  637. return newMap
  638. })
  639. }}
  640. value={store.prompt.input}
  641. fileStyleId={fileStyleId}
  642. agentStyleId={agentStyleId}
  643. promptPartTypeId={() => promptPartTypeId}
  644. />
  645. <box ref={(r) => (anchor = r)}>
  646. <box
  647. border={["left"]}
  648. borderColor={highlight()}
  649. customBorderChars={{
  650. ...EmptyBorder,
  651. vertical: "┃",
  652. bottomLeft: "╹",
  653. }}
  654. >
  655. <box
  656. paddingLeft={2}
  657. paddingRight={1}
  658. paddingTop={1}
  659. flexShrink={0}
  660. backgroundColor={theme.backgroundElement}
  661. flexGrow={1}
  662. >
  663. <textarea
  664. placeholder={props.sessionID ? undefined : `Ask anything... "${PLACEHOLDERS[store.placeholder]}"`}
  665. textColor={keybind.leader ? theme.textMuted : theme.text}
  666. focusedTextColor={keybind.leader ? theme.textMuted : theme.text}
  667. minHeight={1}
  668. maxHeight={6}
  669. onContentChange={() => {
  670. const value = input.plainText
  671. setStore("prompt", "input", value)
  672. autocomplete.onInput(value)
  673. syncExtmarksWithPromptParts()
  674. }}
  675. keyBindings={textareaKeybindings()}
  676. onKeyDown={async (e) => {
  677. if (props.disabled) {
  678. e.preventDefault()
  679. return
  680. }
  681. // Handle clipboard paste (Ctrl+V) - check for images first on Windows
  682. // This is needed because Windows terminal doesn't properly send image data
  683. // through bracketed paste, so we need to intercept the keypress and
  684. // directly read from clipboard before the terminal handles it
  685. if (keybind.match("input_paste", e)) {
  686. const content = await Clipboard.read()
  687. if (content?.mime.startsWith("image/")) {
  688. e.preventDefault()
  689. await pasteImage({
  690. filename: "clipboard",
  691. mime: content.mime,
  692. content: content.data,
  693. })
  694. return
  695. }
  696. // If no image, let the default paste behavior continue
  697. }
  698. if (keybind.match("input_clear", e) && store.prompt.input !== "") {
  699. input.clear()
  700. input.extmarks.clear()
  701. setStore("prompt", {
  702. input: "",
  703. parts: [],
  704. })
  705. setStore("extmarkToPartIndex", new Map())
  706. return
  707. }
  708. if (keybind.match("app_exit", e)) {
  709. if (store.prompt.input === "") {
  710. await exit()
  711. // Don't preventDefault - let textarea potentially handle the event
  712. e.preventDefault()
  713. return
  714. }
  715. }
  716. if (e.name === "!" && input.visualCursor.offset === 0) {
  717. setStore("mode", "shell")
  718. e.preventDefault()
  719. return
  720. }
  721. if (store.mode === "shell") {
  722. if ((e.name === "backspace" && input.visualCursor.offset === 0) || e.name === "escape") {
  723. setStore("mode", "normal")
  724. e.preventDefault()
  725. return
  726. }
  727. }
  728. if (store.mode === "normal") autocomplete.onKeyDown(e)
  729. if (!autocomplete.visible) {
  730. if (
  731. (keybind.match("history_previous", e) && input.cursorOffset === 0) ||
  732. (keybind.match("history_next", e) && input.cursorOffset === input.plainText.length)
  733. ) {
  734. const direction = keybind.match("history_previous", e) ? -1 : 1
  735. const item = history.move(direction, input.plainText)
  736. if (item) {
  737. input.setText(item.input)
  738. setStore("prompt", item)
  739. setStore("mode", item.mode ?? "normal")
  740. restoreExtmarksFromParts(item.parts)
  741. e.preventDefault()
  742. if (direction === -1) input.cursorOffset = 0
  743. if (direction === 1) input.cursorOffset = input.plainText.length
  744. }
  745. return
  746. }
  747. if (keybind.match("history_previous", e) && input.visualCursor.visualRow === 0) input.cursorOffset = 0
  748. if (keybind.match("history_next", e) && input.visualCursor.visualRow === input.height - 1)
  749. input.cursorOffset = input.plainText.length
  750. }
  751. }}
  752. onSubmit={submit}
  753. onPaste={async (event: PasteEvent) => {
  754. if (props.disabled) {
  755. event.preventDefault()
  756. return
  757. }
  758. // Normalize line endings at the boundary
  759. // Windows ConPTY/Terminal often sends CR-only newlines in bracketed paste
  760. // Replace CRLF first, then any remaining CR
  761. const normalizedText = event.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
  762. const pastedContent = normalizedText.trim()
  763. if (!pastedContent) {
  764. command.trigger("prompt.paste")
  765. return
  766. }
  767. // trim ' from the beginning and end of the pasted content. just
  768. // ' and nothing else
  769. const filepath = pastedContent.replace(/^'+|'+$/g, "").replace(/\\ /g, " ")
  770. const isUrl = /^(https?):\/\//.test(filepath)
  771. if (!isUrl) {
  772. try {
  773. const file = Bun.file(filepath)
  774. // Handle SVG as raw text content, not as base64 image
  775. if (file.type === "image/svg+xml") {
  776. event.preventDefault()
  777. const content = await file.text().catch(() => {})
  778. if (content) {
  779. pasteText(content, `[SVG: ${file.name ?? "image"}]`)
  780. return
  781. }
  782. }
  783. if (file.type.startsWith("image/")) {
  784. event.preventDefault()
  785. const content = await file
  786. .arrayBuffer()
  787. .then((buffer) => Buffer.from(buffer).toString("base64"))
  788. .catch(() => {})
  789. if (content) {
  790. await pasteImage({
  791. filename: file.name,
  792. mime: file.type,
  793. content,
  794. })
  795. return
  796. }
  797. }
  798. } catch {}
  799. }
  800. const lineCount = (pastedContent.match(/\n/g)?.length ?? 0) + 1
  801. if (
  802. (lineCount >= 3 || pastedContent.length > 150) &&
  803. !sync.data.config.experimental?.disable_paste_summary
  804. ) {
  805. event.preventDefault()
  806. pasteText(pastedContent, `[Pasted ~${lineCount} lines]`)
  807. return
  808. }
  809. }}
  810. ref={(r: TextareaRenderable) => {
  811. input = r
  812. setTimeout(() => {
  813. input.cursorColor = theme.text
  814. }, 0)
  815. }}
  816. onMouseDown={(r: MouseEvent) => r.target?.focus()}
  817. focusedBackgroundColor={theme.backgroundElement}
  818. cursorColor={theme.text}
  819. syntaxStyle={syntax()}
  820. />
  821. <box flexDirection="row" flexShrink={0} paddingTop={1} gap={1}>
  822. <text fg={highlight()}>
  823. {store.mode === "shell" ? "Shell" : Locale.titlecase(local.agent.current().name)}{" "}
  824. </text>
  825. <Show when={store.mode === "normal"}>
  826. <box flexDirection="row" gap={1}>
  827. <text flexShrink={0} fg={keybind.leader ? theme.textMuted : theme.text}>
  828. {local.model.parsed().model}
  829. </text>
  830. <text fg={theme.textMuted}>{local.model.parsed().provider}</text>
  831. </box>
  832. </Show>
  833. </box>
  834. </box>
  835. </box>
  836. <box
  837. height={1}
  838. border={["left"]}
  839. borderColor={highlight()}
  840. customBorderChars={{
  841. ...EmptyBorder,
  842. vertical: theme.backgroundElement.a !== 0 ? "╹" : " ",
  843. }}
  844. >
  845. <box
  846. height={1}
  847. border={["bottom"]}
  848. borderColor={theme.backgroundElement}
  849. customBorderChars={
  850. theme.backgroundElement.a !== 0
  851. ? {
  852. ...EmptyBorder,
  853. horizontal: "▀",
  854. }
  855. : {
  856. ...EmptyBorder,
  857. horizontal: " ",
  858. }
  859. }
  860. />
  861. </box>
  862. <box flexDirection="row" justifyContent="space-between">
  863. <Show when={status().type !== "idle"} fallback={<text />}>
  864. <box
  865. flexDirection="row"
  866. gap={1}
  867. flexGrow={1}
  868. justifyContent={status().type === "retry" ? "space-between" : "flex-start"}
  869. >
  870. <box flexShrink={0} flexDirection="row" gap={1}>
  871. {/* @ts-ignore // SpinnerOptions doesn't support marginLeft */}
  872. <spinner marginLeft={1} color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
  873. <box flexDirection="row" gap={1} flexShrink={0}>
  874. {(() => {
  875. const retry = createMemo(() => {
  876. const s = status()
  877. if (s.type !== "retry") return
  878. return s
  879. })
  880. const message = createMemo(() => {
  881. const r = retry()
  882. if (!r) return
  883. if (r.message.includes("exceeded your current quota") && r.message.includes("gemini"))
  884. return "gemini is way too hot right now"
  885. if (r.message.length > 80) return r.message.slice(0, 80) + "..."
  886. return r.message
  887. })
  888. const isTruncated = createMemo(() => {
  889. const r = retry()
  890. if (!r) return false
  891. return r.message.length > 120
  892. })
  893. const [seconds, setSeconds] = createSignal(0)
  894. onMount(() => {
  895. const timer = setInterval(() => {
  896. const next = retry()?.next
  897. if (next) setSeconds(Math.round((next - Date.now()) / 1000))
  898. }, 1000)
  899. onCleanup(() => {
  900. clearInterval(timer)
  901. })
  902. })
  903. const handleMessageClick = () => {
  904. const r = retry()
  905. if (!r) return
  906. if (isTruncated()) {
  907. DialogAlert.show(dialog, "Retry Error", r.message)
  908. }
  909. }
  910. const retryText = () => {
  911. const r = retry()
  912. if (!r) return ""
  913. const baseMessage = message()
  914. const truncatedHint = isTruncated() ? " (click to expand)" : ""
  915. const retryInfo = ` [retrying ${seconds() > 0 ? `in ${seconds()}s ` : ""}attempt #${r.attempt}]`
  916. return baseMessage + truncatedHint + retryInfo
  917. }
  918. return (
  919. <Show when={retry()}>
  920. <box onMouseUp={handleMessageClick}>
  921. <text fg={theme.error}>{retryText()}</text>
  922. </box>
  923. </Show>
  924. )
  925. })()}
  926. </box>
  927. </box>
  928. <text fg={store.interrupt > 0 ? theme.primary : theme.text}>
  929. esc{" "}
  930. <span style={{ fg: store.interrupt > 0 ? theme.primary : theme.textMuted }}>
  931. {store.interrupt > 0 ? "again to interrupt" : "interrupt"}
  932. </span>
  933. </text>
  934. </box>
  935. </Show>
  936. <Show when={status().type !== "retry"}>
  937. <box gap={2} flexDirection="row">
  938. <Switch>
  939. <Match when={store.mode === "normal"}>
  940. <text fg={theme.text}>
  941. {keybind.print("agent_cycle")} <span style={{ fg: theme.textMuted }}>switch agent</span>
  942. </text>
  943. <text fg={theme.text}>
  944. {keybind.print("command_list")} <span style={{ fg: theme.textMuted }}>commands</span>
  945. </text>
  946. </Match>
  947. <Match when={store.mode === "shell"}>
  948. <text fg={theme.text}>
  949. esc <span style={{ fg: theme.textMuted }}>exit shell mode</span>
  950. </text>
  951. </Match>
  952. </Switch>
  953. </box>
  954. </Show>
  955. </box>
  956. </box>
  957. </>
  958. )
  959. }