prompt-input.tsx 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. import { useFilteredList } from "@opencode-ai/ui/hooks"
  2. import { createEffect, on, Component, Show, For, onCleanup, Switch, Match, createMemo, createSignal } from "solid-js"
  3. import { createStore } from "solid-js/store"
  4. import { createFocusSignal } from "@solid-primitives/active-element"
  5. import { useLocal } from "@/context/local"
  6. import { useFile } from "@/context/file"
  7. import {
  8. ContentPart,
  9. DEFAULT_PROMPT,
  10. isPromptEqual,
  11. Prompt,
  12. usePrompt,
  13. ImageAttachmentPart,
  14. AgentPart,
  15. FileAttachmentPart,
  16. } from "@/context/prompt"
  17. import { useLayout } from "@/context/layout"
  18. import { useSDK } from "@/context/sdk"
  19. import { useParams } from "@solidjs/router"
  20. import { useSync } from "@/context/sync"
  21. import { useComments } from "@/context/comments"
  22. import { Button } from "@opencode-ai/ui/button"
  23. import { Icon } from "@opencode-ai/ui/icon"
  24. import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
  25. import type { IconName } from "@opencode-ai/ui/icons/provider"
  26. import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
  27. import { IconButton } from "@opencode-ai/ui/icon-button"
  28. import { Select } from "@opencode-ai/ui/select"
  29. import { useDialog } from "@opencode-ai/ui/context/dialog"
  30. import { ModelSelectorPopover } from "@/components/dialog-select-model"
  31. import { DialogSelectModelUnpaid } from "@/components/dialog-select-model-unpaid"
  32. import { useProviders } from "@/hooks/use-providers"
  33. import { useCommand } from "@/context/command"
  34. import { Persist, persisted } from "@/utils/persist"
  35. import { SessionContextUsage } from "@/components/session-context-usage"
  36. import { usePermission } from "@/context/permission"
  37. import { useLanguage } from "@/context/language"
  38. import { createTextFragment, getCursorPosition, setCursorPosition, setRangeEdge } from "./prompt-input/editor-dom"
  39. import { createPromptAttachments, ACCEPTED_FILE_TYPES } from "./prompt-input/attachments"
  40. import { navigatePromptHistory, prependHistoryEntry, promptLength } from "./prompt-input/history"
  41. import { createPromptSubmit } from "./prompt-input/submit"
  42. import { PromptPopover, type AtOption, type SlashCommand } from "./prompt-input/slash-popover"
  43. import { PromptContextItems } from "./prompt-input/context-items"
  44. import { PromptImageAttachments } from "./prompt-input/image-attachments"
  45. import { PromptDragOverlay } from "./prompt-input/drag-overlay"
  46. import { promptPlaceholder } from "./prompt-input/placeholder"
  47. import { ImagePreview } from "@opencode-ai/ui/image-preview"
  48. interface PromptInputProps {
  49. class?: string
  50. ref?: (el: HTMLDivElement) => void
  51. newSessionWorktree?: string
  52. onNewSessionWorktreeReset?: () => void
  53. onSubmit?: () => void
  54. }
  55. const EXAMPLES = [
  56. "prompt.example.1",
  57. "prompt.example.2",
  58. "prompt.example.3",
  59. "prompt.example.4",
  60. "prompt.example.5",
  61. "prompt.example.6",
  62. "prompt.example.7",
  63. "prompt.example.8",
  64. "prompt.example.9",
  65. "prompt.example.10",
  66. "prompt.example.11",
  67. "prompt.example.12",
  68. "prompt.example.13",
  69. "prompt.example.14",
  70. "prompt.example.15",
  71. "prompt.example.16",
  72. "prompt.example.17",
  73. "prompt.example.18",
  74. "prompt.example.19",
  75. "prompt.example.20",
  76. "prompt.example.21",
  77. "prompt.example.22",
  78. "prompt.example.23",
  79. "prompt.example.24",
  80. "prompt.example.25",
  81. ] as const
  82. export const PromptInput: Component<PromptInputProps> = (props) => {
  83. const sdk = useSDK()
  84. const sync = useSync()
  85. const local = useLocal()
  86. const files = useFile()
  87. const prompt = usePrompt()
  88. const commentCount = createMemo(() => prompt.context.items().filter((item) => !!item.comment?.trim()).length)
  89. const layout = useLayout()
  90. const comments = useComments()
  91. const params = useParams()
  92. const dialog = useDialog()
  93. const providers = useProviders()
  94. const command = useCommand()
  95. const permission = usePermission()
  96. const language = useLanguage()
  97. let editorRef!: HTMLDivElement
  98. let fileInputRef!: HTMLInputElement
  99. let scrollRef!: HTMLDivElement
  100. let slashPopoverRef!: HTMLDivElement
  101. const mirror = { input: false }
  102. const scrollCursorIntoView = () => {
  103. const container = scrollRef
  104. const selection = window.getSelection()
  105. if (!container || !selection || selection.rangeCount === 0) return
  106. const range = selection.getRangeAt(0)
  107. if (!editorRef.contains(range.startContainer)) return
  108. const rect = range.getBoundingClientRect()
  109. if (!rect.height) return
  110. const containerRect = container.getBoundingClientRect()
  111. const top = rect.top - containerRect.top + container.scrollTop
  112. const bottom = rect.bottom - containerRect.top + container.scrollTop
  113. const padding = 12
  114. if (top < container.scrollTop + padding) {
  115. container.scrollTop = Math.max(0, top - padding)
  116. return
  117. }
  118. if (bottom > container.scrollTop + container.clientHeight - padding) {
  119. container.scrollTop = bottom - container.clientHeight + padding
  120. }
  121. }
  122. const queueScroll = () => {
  123. requestAnimationFrame(scrollCursorIntoView)
  124. }
  125. const sessionKey = createMemo(() => `${params.dir}${params.id ? "/" + params.id : ""}`)
  126. const tabs = createMemo(() => layout.tabs(sessionKey))
  127. const view = createMemo(() => layout.view(sessionKey))
  128. const commentInReview = (path: string) => {
  129. const sessionID = params.id
  130. if (!sessionID) return false
  131. const diffs = sync.data.session_diff[sessionID]
  132. if (!diffs) return false
  133. return diffs.some((diff) => diff.file === path)
  134. }
  135. const openComment = (item: { path: string; commentID?: string; commentOrigin?: "review" | "file" }) => {
  136. if (!item.commentID) return
  137. const focus = { file: item.path, id: item.commentID }
  138. comments.setActive(focus)
  139. const wantsReview = item.commentOrigin === "review" || (item.commentOrigin !== "file" && commentInReview(item.path))
  140. if (wantsReview) {
  141. if (!view().reviewPanel.opened()) view().reviewPanel.open()
  142. layout.fileTree.open()
  143. layout.fileTree.setTab("changes")
  144. requestAnimationFrame(() => comments.setFocus(focus))
  145. return
  146. }
  147. if (!view().reviewPanel.opened()) view().reviewPanel.open()
  148. layout.fileTree.open()
  149. layout.fileTree.setTab("all")
  150. const tab = files.tab(item.path)
  151. tabs().open(tab)
  152. files.load(item.path)
  153. requestAnimationFrame(() => comments.setFocus(focus))
  154. }
  155. const recent = createMemo(() => {
  156. const all = tabs().all()
  157. const active = tabs().active()
  158. const order = active ? [active, ...all.filter((x) => x !== active)] : all
  159. const seen = new Set<string>()
  160. const paths: string[] = []
  161. for (const tab of order) {
  162. const path = files.pathFromTab(tab)
  163. if (!path) continue
  164. if (seen.has(path)) continue
  165. seen.add(path)
  166. paths.push(path)
  167. }
  168. return paths
  169. })
  170. const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined))
  171. const status = createMemo(
  172. () =>
  173. sync.data.session_status[params.id ?? ""] ?? {
  174. type: "idle",
  175. },
  176. )
  177. const working = createMemo(() => status()?.type !== "idle")
  178. const imageAttachments = createMemo(() =>
  179. prompt.current().filter((part): part is ImageAttachmentPart => part.type === "image"),
  180. )
  181. const [store, setStore] = createStore<{
  182. popover: "at" | "slash" | null
  183. historyIndex: number
  184. savedPrompt: Prompt | null
  185. placeholder: number
  186. draggingType: "image" | "@mention" | null
  187. mode: "normal" | "shell"
  188. applyingHistory: boolean
  189. }>({
  190. popover: null,
  191. historyIndex: -1,
  192. savedPrompt: null,
  193. placeholder: Math.floor(Math.random() * EXAMPLES.length),
  194. draggingType: null,
  195. mode: "normal",
  196. applyingHistory: false,
  197. })
  198. const placeholder = createMemo(() =>
  199. promptPlaceholder({
  200. mode: store.mode,
  201. commentCount: commentCount(),
  202. example: language.t(EXAMPLES[store.placeholder]),
  203. t: (key, params) => language.t(key as Parameters<typeof language.t>[0], params as never),
  204. }),
  205. )
  206. const MAX_HISTORY = 100
  207. const [history, setHistory] = persisted(
  208. Persist.global("prompt-history", ["prompt-history.v1"]),
  209. createStore<{
  210. entries: Prompt[]
  211. }>({
  212. entries: [],
  213. }),
  214. )
  215. const [shellHistory, setShellHistory] = persisted(
  216. Persist.global("prompt-history-shell", ["prompt-history-shell.v1"]),
  217. createStore<{
  218. entries: Prompt[]
  219. }>({
  220. entries: [],
  221. }),
  222. )
  223. const applyHistoryPrompt = (p: Prompt, position: "start" | "end") => {
  224. const length = position === "start" ? 0 : promptLength(p)
  225. setStore("applyingHistory", true)
  226. prompt.set(p, length)
  227. requestAnimationFrame(() => {
  228. editorRef.focus()
  229. setCursorPosition(editorRef, length)
  230. setStore("applyingHistory", false)
  231. queueScroll()
  232. })
  233. }
  234. const getCaretState = () => {
  235. const selection = window.getSelection()
  236. const textLength = promptLength(prompt.current())
  237. if (!selection || selection.rangeCount === 0) {
  238. return { collapsed: false, cursorPosition: 0, textLength }
  239. }
  240. const anchorNode = selection.anchorNode
  241. if (!anchorNode || !editorRef.contains(anchorNode)) {
  242. return { collapsed: false, cursorPosition: 0, textLength }
  243. }
  244. return {
  245. collapsed: selection.isCollapsed,
  246. cursorPosition: getCursorPosition(editorRef),
  247. textLength,
  248. }
  249. }
  250. const isFocused = createFocusSignal(() => editorRef)
  251. createEffect(() => {
  252. params.id
  253. if (params.id) return
  254. const interval = setInterval(() => {
  255. setStore("placeholder", (prev) => (prev + 1) % EXAMPLES.length)
  256. }, 6500)
  257. onCleanup(() => clearInterval(interval))
  258. })
  259. const [composing, setComposing] = createSignal(false)
  260. const isImeComposing = (event: KeyboardEvent) => event.isComposing || composing() || event.keyCode === 229
  261. createEffect(() => {
  262. if (!isFocused()) setStore("popover", null)
  263. })
  264. // Safety: reset composing state on focus change to prevent stuck state
  265. // This handles edge cases where compositionend event may not fire
  266. createEffect(() => {
  267. if (!isFocused()) setComposing(false)
  268. })
  269. const agentList = createMemo(() =>
  270. sync.data.agent
  271. .filter((agent) => !agent.hidden && agent.mode !== "primary")
  272. .map((agent): AtOption => ({ type: "agent", name: agent.name, display: agent.name })),
  273. )
  274. const handleAtSelect = (option: AtOption | undefined) => {
  275. if (!option) return
  276. if (option.type === "agent") {
  277. addPart({ type: "agent", name: option.name, content: "@" + option.name, start: 0, end: 0 })
  278. } else {
  279. addPart({ type: "file", path: option.path, content: "@" + option.path, start: 0, end: 0 })
  280. }
  281. }
  282. const atKey = (x: AtOption | undefined) => {
  283. if (!x) return ""
  284. return x.type === "agent" ? `agent:${x.name}` : `file:${x.path}`
  285. }
  286. const {
  287. flat: atFlat,
  288. active: atActive,
  289. setActive: setAtActive,
  290. onInput: atOnInput,
  291. onKeyDown: atOnKeyDown,
  292. } = useFilteredList<AtOption>({
  293. items: async (query) => {
  294. const agents = agentList()
  295. const open = recent()
  296. const seen = new Set(open)
  297. const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true }))
  298. const paths = await files.searchFilesAndDirectories(query)
  299. const fileOptions: AtOption[] = paths
  300. .filter((path) => !seen.has(path))
  301. .map((path) => ({ type: "file", path, display: path }))
  302. return [...agents, ...pinned, ...fileOptions]
  303. },
  304. key: atKey,
  305. filterKeys: ["display"],
  306. groupBy: (item) => {
  307. if (item.type === "agent") return "agent"
  308. if (item.recent) return "recent"
  309. return "file"
  310. },
  311. sortGroupsBy: (a, b) => {
  312. const rank = (category: string) => {
  313. if (category === "agent") return 0
  314. if (category === "recent") return 1
  315. return 2
  316. }
  317. return rank(a.category) - rank(b.category)
  318. },
  319. onSelect: handleAtSelect,
  320. })
  321. const slashCommands = createMemo<SlashCommand[]>(() => {
  322. const builtin = command.options
  323. .filter((opt) => !opt.disabled && !opt.id.startsWith("suggested.") && opt.slash)
  324. .map((opt) => ({
  325. id: opt.id,
  326. trigger: opt.slash!,
  327. title: opt.title,
  328. description: opt.description,
  329. keybind: opt.keybind,
  330. type: "builtin" as const,
  331. }))
  332. const custom = sync.data.command.map((cmd) => ({
  333. id: `custom.${cmd.name}`,
  334. trigger: cmd.name,
  335. title: cmd.name,
  336. description: cmd.description,
  337. type: "custom" as const,
  338. source: cmd.source,
  339. }))
  340. return [...custom, ...builtin]
  341. })
  342. const handleSlashSelect = (cmd: SlashCommand | undefined) => {
  343. if (!cmd) return
  344. setStore("popover", null)
  345. if (cmd.type === "custom") {
  346. const text = `/${cmd.trigger} `
  347. editorRef.innerHTML = ""
  348. editorRef.textContent = text
  349. prompt.set([{ type: "text", content: text, start: 0, end: text.length }], text.length)
  350. requestAnimationFrame(() => {
  351. editorRef.focus()
  352. const range = document.createRange()
  353. const sel = window.getSelection()
  354. range.selectNodeContents(editorRef)
  355. range.collapse(false)
  356. sel?.removeAllRanges()
  357. sel?.addRange(range)
  358. })
  359. return
  360. }
  361. editorRef.innerHTML = ""
  362. prompt.set([{ type: "text", content: "", start: 0, end: 0 }], 0)
  363. command.trigger(cmd.id, "slash")
  364. }
  365. const {
  366. flat: slashFlat,
  367. active: slashActive,
  368. setActive: setSlashActive,
  369. onInput: slashOnInput,
  370. onKeyDown: slashOnKeyDown,
  371. refetch: slashRefetch,
  372. } = useFilteredList<SlashCommand>({
  373. items: slashCommands,
  374. key: (x) => x?.id,
  375. filterKeys: ["trigger", "title", "description"],
  376. onSelect: handleSlashSelect,
  377. })
  378. const createPill = (part: FileAttachmentPart | AgentPart) => {
  379. const pill = document.createElement("span")
  380. pill.textContent = part.content
  381. pill.setAttribute("data-type", part.type)
  382. if (part.type === "file") pill.setAttribute("data-path", part.path)
  383. if (part.type === "agent") pill.setAttribute("data-name", part.name)
  384. pill.setAttribute("contenteditable", "false")
  385. pill.style.userSelect = "text"
  386. pill.style.cursor = "default"
  387. return pill
  388. }
  389. const isNormalizedEditor = () =>
  390. Array.from(editorRef.childNodes).every((node) => {
  391. if (node.nodeType === Node.TEXT_NODE) {
  392. const text = node.textContent ?? ""
  393. if (!text.includes("\u200B")) return true
  394. if (text !== "\u200B") return false
  395. const prev = node.previousSibling
  396. const next = node.nextSibling
  397. const prevIsBr = prev?.nodeType === Node.ELEMENT_NODE && (prev as HTMLElement).tagName === "BR"
  398. const nextIsBr = next?.nodeType === Node.ELEMENT_NODE && (next as HTMLElement).tagName === "BR"
  399. if (!prevIsBr && !nextIsBr) return false
  400. if (nextIsBr && !prevIsBr && prev) return false
  401. return true
  402. }
  403. if (node.nodeType !== Node.ELEMENT_NODE) return false
  404. const el = node as HTMLElement
  405. if (el.dataset.type === "file") return true
  406. if (el.dataset.type === "agent") return true
  407. return el.tagName === "BR"
  408. })
  409. const renderEditor = (parts: Prompt) => {
  410. editorRef.innerHTML = ""
  411. for (const part of parts) {
  412. if (part.type === "text") {
  413. editorRef.appendChild(createTextFragment(part.content))
  414. continue
  415. }
  416. if (part.type === "file" || part.type === "agent") {
  417. editorRef.appendChild(createPill(part))
  418. }
  419. }
  420. }
  421. createEffect(
  422. on(
  423. () => sync.data.command,
  424. () => slashRefetch(),
  425. { defer: true },
  426. ),
  427. )
  428. // Auto-scroll active command into view when navigating with keyboard
  429. createEffect(() => {
  430. const activeId = slashActive()
  431. if (!activeId || !slashPopoverRef) return
  432. requestAnimationFrame(() => {
  433. const element = slashPopoverRef.querySelector(`[data-slash-id="${activeId}"]`)
  434. element?.scrollIntoView({ block: "nearest", behavior: "smooth" })
  435. })
  436. })
  437. const selectPopoverActive = () => {
  438. if (store.popover === "at") {
  439. const items = atFlat()
  440. if (items.length === 0) return
  441. const active = atActive()
  442. const item = items.find((entry) => atKey(entry) === active) ?? items[0]
  443. handleAtSelect(item)
  444. return
  445. }
  446. if (store.popover === "slash") {
  447. const items = slashFlat()
  448. if (items.length === 0) return
  449. const active = slashActive()
  450. const item = items.find((entry) => entry.id === active) ?? items[0]
  451. handleSlashSelect(item)
  452. }
  453. }
  454. createEffect(
  455. on(
  456. () => prompt.current(),
  457. (currentParts) => {
  458. const inputParts = currentParts.filter((part) => part.type !== "image")
  459. if (mirror.input) {
  460. mirror.input = false
  461. if (isNormalizedEditor()) return
  462. const selection = window.getSelection()
  463. let cursorPosition: number | null = null
  464. if (selection && selection.rangeCount > 0 && editorRef.contains(selection.anchorNode)) {
  465. cursorPosition = getCursorPosition(editorRef)
  466. }
  467. renderEditor(inputParts)
  468. if (cursorPosition !== null) {
  469. setCursorPosition(editorRef, cursorPosition)
  470. }
  471. return
  472. }
  473. const domParts = parseFromDOM()
  474. if (isNormalizedEditor() && isPromptEqual(inputParts, domParts)) return
  475. const selection = window.getSelection()
  476. let cursorPosition: number | null = null
  477. if (selection && selection.rangeCount > 0 && editorRef.contains(selection.anchorNode)) {
  478. cursorPosition = getCursorPosition(editorRef)
  479. }
  480. renderEditor(inputParts)
  481. if (cursorPosition !== null) {
  482. setCursorPosition(editorRef, cursorPosition)
  483. }
  484. },
  485. ),
  486. )
  487. const parseFromDOM = (): Prompt => {
  488. const parts: Prompt = []
  489. let position = 0
  490. let buffer = ""
  491. const flushText = () => {
  492. const content = buffer.replace(/\r\n?/g, "\n").replace(/\u200B/g, "")
  493. buffer = ""
  494. if (!content) return
  495. parts.push({ type: "text", content, start: position, end: position + content.length })
  496. position += content.length
  497. }
  498. const pushFile = (file: HTMLElement) => {
  499. const content = file.textContent ?? ""
  500. parts.push({
  501. type: "file",
  502. path: file.dataset.path!,
  503. content,
  504. start: position,
  505. end: position + content.length,
  506. })
  507. position += content.length
  508. }
  509. const pushAgent = (agent: HTMLElement) => {
  510. const content = agent.textContent ?? ""
  511. parts.push({
  512. type: "agent",
  513. name: agent.dataset.name!,
  514. content,
  515. start: position,
  516. end: position + content.length,
  517. })
  518. position += content.length
  519. }
  520. const visit = (node: Node) => {
  521. if (node.nodeType === Node.TEXT_NODE) {
  522. buffer += node.textContent ?? ""
  523. return
  524. }
  525. if (node.nodeType !== Node.ELEMENT_NODE) return
  526. const el = node as HTMLElement
  527. if (el.dataset.type === "file") {
  528. flushText()
  529. pushFile(el)
  530. return
  531. }
  532. if (el.dataset.type === "agent") {
  533. flushText()
  534. pushAgent(el)
  535. return
  536. }
  537. if (el.tagName === "BR") {
  538. buffer += "\n"
  539. return
  540. }
  541. for (const child of Array.from(el.childNodes)) {
  542. visit(child)
  543. }
  544. }
  545. const children = Array.from(editorRef.childNodes)
  546. children.forEach((child, index) => {
  547. const isBlock = child.nodeType === Node.ELEMENT_NODE && ["DIV", "P"].includes((child as HTMLElement).tagName)
  548. visit(child)
  549. if (isBlock && index < children.length - 1) {
  550. buffer += "\n"
  551. }
  552. })
  553. flushText()
  554. if (parts.length === 0) parts.push(...DEFAULT_PROMPT)
  555. return parts
  556. }
  557. const handleInput = () => {
  558. const rawParts = parseFromDOM()
  559. const images = imageAttachments()
  560. const cursorPosition = getCursorPosition(editorRef)
  561. const rawText = rawParts.map((p) => ("content" in p ? p.content : "")).join("")
  562. const trimmed = rawText.replace(/\u200B/g, "").trim()
  563. const hasNonText = rawParts.some((part) => part.type !== "text")
  564. const shouldReset = trimmed.length === 0 && !hasNonText && images.length === 0
  565. if (shouldReset) {
  566. setStore("popover", null)
  567. if (store.historyIndex >= 0 && !store.applyingHistory) {
  568. setStore("historyIndex", -1)
  569. setStore("savedPrompt", null)
  570. }
  571. if (prompt.dirty()) {
  572. mirror.input = true
  573. prompt.set(DEFAULT_PROMPT, 0)
  574. }
  575. queueScroll()
  576. return
  577. }
  578. const shellMode = store.mode === "shell"
  579. if (!shellMode) {
  580. const atMatch = rawText.substring(0, cursorPosition).match(/@(\S*)$/)
  581. const slashMatch = rawText.match(/^\/(\S*)$/)
  582. if (atMatch) {
  583. atOnInput(atMatch[1])
  584. setStore("popover", "at")
  585. } else if (slashMatch) {
  586. slashOnInput(slashMatch[1])
  587. setStore("popover", "slash")
  588. } else {
  589. setStore("popover", null)
  590. }
  591. } else {
  592. setStore("popover", null)
  593. }
  594. if (store.historyIndex >= 0 && !store.applyingHistory) {
  595. setStore("historyIndex", -1)
  596. setStore("savedPrompt", null)
  597. }
  598. mirror.input = true
  599. prompt.set([...rawParts, ...images], cursorPosition)
  600. queueScroll()
  601. }
  602. const addPart = (part: ContentPart) => {
  603. const selection = window.getSelection()
  604. if (!selection || selection.rangeCount === 0) return
  605. const cursorPosition = getCursorPosition(editorRef)
  606. const currentPrompt = prompt.current()
  607. const rawText = currentPrompt.map((p) => ("content" in p ? p.content : "")).join("")
  608. const textBeforeCursor = rawText.substring(0, cursorPosition)
  609. const atMatch = textBeforeCursor.match(/@(\S*)$/)
  610. if (part.type === "file" || part.type === "agent") {
  611. const pill = createPill(part)
  612. const gap = document.createTextNode(" ")
  613. const range = selection.getRangeAt(0)
  614. if (atMatch) {
  615. const start = atMatch.index ?? cursorPosition - atMatch[0].length
  616. setRangeEdge(editorRef, range, "start", start)
  617. setRangeEdge(editorRef, range, "end", cursorPosition)
  618. }
  619. range.deleteContents()
  620. range.insertNode(gap)
  621. range.insertNode(pill)
  622. range.setStartAfter(gap)
  623. range.collapse(true)
  624. selection.removeAllRanges()
  625. selection.addRange(range)
  626. } else if (part.type === "text") {
  627. const range = selection.getRangeAt(0)
  628. const fragment = createTextFragment(part.content)
  629. const last = fragment.lastChild
  630. range.deleteContents()
  631. range.insertNode(fragment)
  632. if (last) {
  633. if (last.nodeType === Node.TEXT_NODE) {
  634. const text = last.textContent ?? ""
  635. if (text === "\u200B") {
  636. range.setStart(last, 0)
  637. }
  638. if (text !== "\u200B") {
  639. range.setStart(last, text.length)
  640. }
  641. }
  642. if (last.nodeType !== Node.TEXT_NODE) {
  643. range.setStartAfter(last)
  644. }
  645. }
  646. range.collapse(true)
  647. selection.removeAllRanges()
  648. selection.addRange(range)
  649. }
  650. handleInput()
  651. setStore("popover", null)
  652. }
  653. const addToHistory = (prompt: Prompt, mode: "normal" | "shell") => {
  654. const currentHistory = mode === "shell" ? shellHistory : history
  655. const setCurrentHistory = mode === "shell" ? setShellHistory : setHistory
  656. const next = prependHistoryEntry(currentHistory.entries, prompt)
  657. if (next === currentHistory.entries) return
  658. setCurrentHistory("entries", next)
  659. }
  660. const navigateHistory = (direction: "up" | "down") => {
  661. const result = navigatePromptHistory({
  662. direction,
  663. entries: store.mode === "shell" ? shellHistory.entries : history.entries,
  664. historyIndex: store.historyIndex,
  665. currentPrompt: prompt.current(),
  666. savedPrompt: store.savedPrompt,
  667. })
  668. if (!result.handled) return false
  669. setStore("historyIndex", result.historyIndex)
  670. setStore("savedPrompt", result.savedPrompt)
  671. applyHistoryPrompt(result.prompt, result.cursor)
  672. return true
  673. }
  674. const { addImageAttachment, removeImageAttachment, handlePaste } = createPromptAttachments({
  675. editor: () => editorRef,
  676. isFocused,
  677. isDialogActive: () => !!dialog.active,
  678. setDraggingType: (type) => setStore("draggingType", type),
  679. focusEditor: () => {
  680. editorRef.focus()
  681. setCursorPosition(editorRef, promptLength(prompt.current()))
  682. },
  683. addPart,
  684. })
  685. const { abort, handleSubmit } = createPromptSubmit({
  686. info,
  687. imageAttachments,
  688. commentCount,
  689. mode: () => store.mode,
  690. working,
  691. editor: () => editorRef,
  692. queueScroll,
  693. promptLength,
  694. addToHistory,
  695. resetHistoryNavigation: () => {
  696. setStore("historyIndex", -1)
  697. setStore("savedPrompt", null)
  698. },
  699. setMode: (mode) => setStore("mode", mode),
  700. setPopover: (popover) => setStore("popover", popover),
  701. newSessionWorktree: props.newSessionWorktree,
  702. onNewSessionWorktreeReset: props.onNewSessionWorktreeReset,
  703. onSubmit: props.onSubmit,
  704. })
  705. const handleKeyDown = (event: KeyboardEvent) => {
  706. if (event.key === "Backspace") {
  707. const selection = window.getSelection()
  708. if (selection && selection.isCollapsed) {
  709. const node = selection.anchorNode
  710. const offset = selection.anchorOffset
  711. if (node && node.nodeType === Node.TEXT_NODE) {
  712. const text = node.textContent ?? ""
  713. if (/^\u200B+$/.test(text) && offset > 0) {
  714. const range = document.createRange()
  715. range.setStart(node, 0)
  716. range.collapse(true)
  717. selection.removeAllRanges()
  718. selection.addRange(range)
  719. }
  720. }
  721. }
  722. }
  723. if (event.key === "!" && store.mode === "normal") {
  724. const cursorPosition = getCursorPosition(editorRef)
  725. if (cursorPosition === 0) {
  726. setStore("mode", "shell")
  727. setStore("popover", null)
  728. event.preventDefault()
  729. return
  730. }
  731. }
  732. if (store.mode === "shell") {
  733. const { collapsed, cursorPosition, textLength } = getCaretState()
  734. if (event.key === "Escape") {
  735. setStore("mode", "normal")
  736. event.preventDefault()
  737. return
  738. }
  739. if (event.key === "Backspace" && collapsed && cursorPosition === 0 && textLength === 0) {
  740. setStore("mode", "normal")
  741. event.preventDefault()
  742. return
  743. }
  744. }
  745. // Handle Shift+Enter BEFORE IME check - Shift+Enter is never used for IME input
  746. // and should always insert a newline regardless of composition state
  747. if (event.key === "Enter" && event.shiftKey) {
  748. addPart({ type: "text", content: "\n", start: 0, end: 0 })
  749. event.preventDefault()
  750. return
  751. }
  752. if (event.key === "Enter" && isImeComposing(event)) {
  753. return
  754. }
  755. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  756. if (store.popover) {
  757. if (event.key === "Tab") {
  758. selectPopoverActive()
  759. event.preventDefault()
  760. return
  761. }
  762. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  763. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  764. if (nav || ctrlNav) {
  765. if (store.popover === "at") {
  766. atOnKeyDown(event)
  767. event.preventDefault()
  768. return
  769. }
  770. if (store.popover === "slash") {
  771. slashOnKeyDown(event)
  772. }
  773. event.preventDefault()
  774. return
  775. }
  776. }
  777. if (ctrl && event.code === "KeyG") {
  778. if (store.popover) {
  779. setStore("popover", null)
  780. event.preventDefault()
  781. return
  782. }
  783. if (working()) {
  784. abort()
  785. event.preventDefault()
  786. }
  787. return
  788. }
  789. if (event.key === "ArrowUp" || event.key === "ArrowDown") {
  790. if (event.altKey || event.ctrlKey || event.metaKey) return
  791. const { collapsed } = getCaretState()
  792. if (!collapsed) return
  793. const cursorPosition = getCursorPosition(editorRef)
  794. const textLength = promptLength(prompt.current())
  795. const textContent = prompt
  796. .current()
  797. .map((part) => ("content" in part ? part.content : ""))
  798. .join("")
  799. const isEmpty = textContent.trim() === "" || textLength <= 1
  800. const hasNewlines = textContent.includes("\n")
  801. const inHistory = store.historyIndex >= 0
  802. const atStart = cursorPosition <= (isEmpty ? 1 : 0)
  803. const atEnd = cursorPosition >= (isEmpty ? textLength - 1 : textLength)
  804. const allowUp = isEmpty || atStart || (!hasNewlines && !inHistory) || (inHistory && atEnd)
  805. const allowDown = isEmpty || atEnd || (!hasNewlines && !inHistory) || (inHistory && atStart)
  806. if (event.key === "ArrowUp") {
  807. if (!allowUp) return
  808. if (navigateHistory("up")) {
  809. event.preventDefault()
  810. }
  811. return
  812. }
  813. if (!allowDown) return
  814. if (navigateHistory("down")) {
  815. event.preventDefault()
  816. }
  817. return
  818. }
  819. // Note: Shift+Enter is handled earlier, before IME check
  820. if (event.key === "Enter" && !event.shiftKey) {
  821. handleSubmit(event)
  822. }
  823. if (event.key === "Escape") {
  824. if (store.popover) {
  825. setStore("popover", null)
  826. } else if (working()) {
  827. abort()
  828. }
  829. }
  830. }
  831. return (
  832. <div class="relative size-full _max-h-[320px] flex flex-col gap-3">
  833. <PromptPopover
  834. popover={store.popover}
  835. setSlashPopoverRef={(el) => (slashPopoverRef = el)}
  836. atFlat={atFlat()}
  837. atActive={atActive() ?? undefined}
  838. atKey={atKey}
  839. setAtActive={setAtActive}
  840. onAtSelect={handleAtSelect}
  841. slashFlat={slashFlat()}
  842. slashActive={slashActive() ?? undefined}
  843. setSlashActive={setSlashActive}
  844. onSlashSelect={handleSlashSelect}
  845. commandKeybind={command.keybind}
  846. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  847. />
  848. <form
  849. onSubmit={handleSubmit}
  850. classList={{
  851. "group/prompt-input": true,
  852. "bg-surface-raised-stronger-non-alpha shadow-xs-border relative": true,
  853. "rounded-[14px] overflow-clip focus-within:shadow-xs-border": true,
  854. "border-icon-info-active border-dashed": store.draggingType !== null,
  855. [props.class ?? ""]: !!props.class,
  856. }}
  857. >
  858. <PromptDragOverlay
  859. type={store.draggingType}
  860. label={language.t(store.draggingType === "@mention" ? "prompt.dropzone.file.label" : "prompt.dropzone.label")}
  861. />
  862. <PromptContextItems
  863. items={prompt.context.items()}
  864. active={(item) => {
  865. const active = comments.active()
  866. return !!item.commentID && item.commentID === active?.id && item.path === active?.file
  867. }}
  868. openComment={openComment}
  869. remove={(item) => {
  870. if (item.commentID) comments.remove(item.path, item.commentID)
  871. prompt.context.remove(item.key)
  872. }}
  873. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  874. />
  875. <PromptImageAttachments
  876. attachments={imageAttachments()}
  877. onOpen={(attachment) =>
  878. dialog.show(() => <ImagePreview src={attachment.dataUrl} alt={attachment.filename} />)
  879. }
  880. onRemove={removeImageAttachment}
  881. removeLabel={language.t("prompt.attachment.remove")}
  882. />
  883. <div class="relative max-h-[240px] overflow-y-auto" ref={(el) => (scrollRef = el)}>
  884. <div
  885. data-component="prompt-input"
  886. ref={(el) => {
  887. editorRef = el
  888. props.ref?.(el)
  889. }}
  890. role="textbox"
  891. aria-multiline="true"
  892. aria-label={placeholder()}
  893. contenteditable="true"
  894. autocapitalize="off"
  895. autocorrect="off"
  896. spellcheck={false}
  897. onInput={handleInput}
  898. onPaste={handlePaste}
  899. onCompositionStart={() => setComposing(true)}
  900. onCompositionEnd={() => setComposing(false)}
  901. onKeyDown={handleKeyDown}
  902. classList={{
  903. "select-text": true,
  904. "w-full p-3 pr-12 text-14-regular text-text-strong focus:outline-none whitespace-pre-wrap": true,
  905. "[&_[data-type=file]]:text-syntax-property": true,
  906. "[&_[data-type=agent]]:text-syntax-type": true,
  907. "font-mono!": store.mode === "shell",
  908. }}
  909. />
  910. <Show when={!prompt.dirty()}>
  911. <div class="absolute top-0 inset-x-0 p-3 pr-12 text-14-regular text-text-weak pointer-events-none whitespace-nowrap truncate">
  912. {placeholder()}
  913. </div>
  914. </Show>
  915. </div>
  916. <div class="relative p-3 flex items-center justify-between gap-2">
  917. <div class="flex items-center gap-2 min-w-0 flex-1">
  918. <Switch>
  919. <Match when={store.mode === "shell"}>
  920. <div class="flex items-center gap-2 px-2 h-6">
  921. <Icon name="console" size="small" class="text-icon-primary" />
  922. <span class="text-12-regular text-text-primary">{language.t("prompt.mode.shell")}</span>
  923. <span class="text-12-regular text-text-weak">{language.t("prompt.mode.shell.exit")}</span>
  924. </div>
  925. </Match>
  926. <Match when={store.mode === "normal"}>
  927. <TooltipKeybind
  928. placement="top"
  929. gutter={8}
  930. title={language.t("command.agent.cycle")}
  931. keybind={command.keybind("agent.cycle")}
  932. >
  933. <Select
  934. options={local.agent.list().map((agent) => agent.name)}
  935. current={local.agent.current()?.name ?? ""}
  936. onSelect={local.agent.set}
  937. class={`capitalize ${local.model.variant.list().length > 0 ? "max-w-full" : "max-w-[120px]"}`}
  938. valueClass="truncate"
  939. variant="ghost"
  940. />
  941. </TooltipKeybind>
  942. <Show
  943. when={providers.paid().length > 0}
  944. fallback={
  945. <TooltipKeybind
  946. placement="top"
  947. gutter={8}
  948. title={language.t("command.model.choose")}
  949. keybind={command.keybind("model.choose")}
  950. >
  951. <Button
  952. as="div"
  953. variant="ghost"
  954. class="px-2 min-w-0 max-w-[240px]"
  955. onClick={() => dialog.show(() => <DialogSelectModelUnpaid />)}
  956. >
  957. <Show when={local.model.current()?.provider?.id}>
  958. <ProviderIcon id={local.model.current()!.provider.id as IconName} class="size-4 shrink-0" />
  959. </Show>
  960. <span class="truncate">
  961. {local.model.current()?.name ?? language.t("dialog.model.select.title")}
  962. </span>
  963. <Icon name="chevron-down" size="small" class="shrink-0" />
  964. </Button>
  965. </TooltipKeybind>
  966. }
  967. >
  968. <TooltipKeybind
  969. placement="top"
  970. gutter={8}
  971. title={language.t("command.model.choose")}
  972. keybind={command.keybind("model.choose")}
  973. >
  974. <ModelSelectorPopover
  975. triggerAs={Button}
  976. triggerProps={{ variant: "ghost", class: "min-w-0 max-w-[240px]" }}
  977. >
  978. <Show when={local.model.current()?.provider?.id}>
  979. <ProviderIcon id={local.model.current()!.provider.id as IconName} class="size-4 shrink-0" />
  980. </Show>
  981. <span class="truncate">
  982. {local.model.current()?.name ?? language.t("dialog.model.select.title")}
  983. </span>
  984. <Icon name="chevron-down" size="small" class="shrink-0" />
  985. </ModelSelectorPopover>
  986. </TooltipKeybind>
  987. </Show>
  988. <Show when={local.model.variant.list().length > 0}>
  989. <TooltipKeybind
  990. placement="top"
  991. gutter={8}
  992. title={language.t("command.model.variant.cycle")}
  993. keybind={command.keybind("model.variant.cycle")}
  994. >
  995. <Button
  996. data-action="model-variant-cycle"
  997. variant="ghost"
  998. class="text-text-base _hidden group-hover/prompt-input:inline-block capitalize text-12-regular"
  999. onClick={() => local.model.variant.cycle()}
  1000. >
  1001. {local.model.variant.current() ?? language.t("common.default")}
  1002. </Button>
  1003. </TooltipKeybind>
  1004. </Show>
  1005. <Show when={permission.permissionsEnabled() && params.id}>
  1006. <TooltipKeybind
  1007. placement="top"
  1008. gutter={8}
  1009. title={language.t("command.permissions.autoaccept.enable")}
  1010. keybind={command.keybind("permissions.autoaccept")}
  1011. >
  1012. <Button
  1013. variant="ghost"
  1014. onClick={() => permission.toggleAutoAccept(params.id!, sdk.directory)}
  1015. classList={{
  1016. "_hidden group-hover/prompt-input:flex size-6 items-center justify-center": true,
  1017. "text-text-base": !permission.isAutoAccepting(params.id!, sdk.directory),
  1018. "hover:bg-surface-success-base": permission.isAutoAccepting(params.id!, sdk.directory),
  1019. }}
  1020. aria-label={
  1021. permission.isAutoAccepting(params.id!, sdk.directory)
  1022. ? language.t("command.permissions.autoaccept.disable")
  1023. : language.t("command.permissions.autoaccept.enable")
  1024. }
  1025. aria-pressed={permission.isAutoAccepting(params.id!, sdk.directory)}
  1026. >
  1027. <Icon
  1028. name="chevron-double-right"
  1029. size="small"
  1030. classList={{ "text-icon-success-base": permission.isAutoAccepting(params.id!, sdk.directory) }}
  1031. />
  1032. </Button>
  1033. </TooltipKeybind>
  1034. </Show>
  1035. </Match>
  1036. </Switch>
  1037. </div>
  1038. <div class="flex items-center gap-1 shrink-0">
  1039. <input
  1040. ref={fileInputRef}
  1041. type="file"
  1042. accept={ACCEPTED_FILE_TYPES.join(",")}
  1043. class="hidden"
  1044. onChange={(e) => {
  1045. const file = e.currentTarget.files?.[0]
  1046. if (file) addImageAttachment(file)
  1047. e.currentTarget.value = ""
  1048. }}
  1049. />
  1050. <div class="flex items-center gap-1 mr-1">
  1051. <SessionContextUsage />
  1052. <Show when={store.mode === "normal"}>
  1053. <Tooltip placement="top" value={language.t("prompt.action.attachFile")}>
  1054. <Button
  1055. type="button"
  1056. variant="ghost"
  1057. class="size-6 px-1"
  1058. onClick={() => fileInputRef.click()}
  1059. aria-label={language.t("prompt.action.attachFile")}
  1060. >
  1061. <Icon name="photo" class="size-4.5" />
  1062. </Button>
  1063. </Tooltip>
  1064. </Show>
  1065. </div>
  1066. <Tooltip
  1067. placement="top"
  1068. inactive={!prompt.dirty() && !working()}
  1069. value={
  1070. <Switch>
  1071. <Match when={working()}>
  1072. <div class="flex items-center gap-2">
  1073. <span>{language.t("prompt.action.stop")}</span>
  1074. <span class="text-icon-base text-12-medium text-[10px]!">{language.t("common.key.esc")}</span>
  1075. </div>
  1076. </Match>
  1077. <Match when={true}>
  1078. <div class="flex items-center gap-2">
  1079. <span>{language.t("prompt.action.send")}</span>
  1080. <Icon name="enter" size="small" class="text-icon-base" />
  1081. </div>
  1082. </Match>
  1083. </Switch>
  1084. }
  1085. >
  1086. <IconButton
  1087. type="submit"
  1088. disabled={!prompt.dirty() && !working() && commentCount() === 0}
  1089. icon={working() ? "stop" : "arrow-up"}
  1090. variant="primary"
  1091. class="h-6 w-4.5"
  1092. aria-label={working() ? language.t("prompt.action.stop") : language.t("prompt.action.send")}
  1093. />
  1094. </Tooltip>
  1095. </div>
  1096. </div>
  1097. </form>
  1098. </div>
  1099. )
  1100. }