prompt-input.tsx 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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. dragging: boolean
  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. dragging: false,
  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. setDragging: (value) => setStore("dragging", value),
  679. addPart,
  680. })
  681. const { abort, handleSubmit } = createPromptSubmit({
  682. info,
  683. imageAttachments,
  684. commentCount,
  685. mode: () => store.mode,
  686. working,
  687. editor: () => editorRef,
  688. queueScroll,
  689. promptLength,
  690. addToHistory,
  691. resetHistoryNavigation: () => {
  692. setStore("historyIndex", -1)
  693. setStore("savedPrompt", null)
  694. },
  695. setMode: (mode) => setStore("mode", mode),
  696. setPopover: (popover) => setStore("popover", popover),
  697. newSessionWorktree: props.newSessionWorktree,
  698. onNewSessionWorktreeReset: props.onNewSessionWorktreeReset,
  699. onSubmit: props.onSubmit,
  700. })
  701. const handleKeyDown = (event: KeyboardEvent) => {
  702. if (event.key === "Backspace") {
  703. const selection = window.getSelection()
  704. if (selection && selection.isCollapsed) {
  705. const node = selection.anchorNode
  706. const offset = selection.anchorOffset
  707. if (node && node.nodeType === Node.TEXT_NODE) {
  708. const text = node.textContent ?? ""
  709. if (/^\u200B+$/.test(text) && offset > 0) {
  710. const range = document.createRange()
  711. range.setStart(node, 0)
  712. range.collapse(true)
  713. selection.removeAllRanges()
  714. selection.addRange(range)
  715. }
  716. }
  717. }
  718. }
  719. if (event.key === "!" && store.mode === "normal") {
  720. const cursorPosition = getCursorPosition(editorRef)
  721. if (cursorPosition === 0) {
  722. setStore("mode", "shell")
  723. setStore("popover", null)
  724. event.preventDefault()
  725. return
  726. }
  727. }
  728. if (store.mode === "shell") {
  729. const { collapsed, cursorPosition, textLength } = getCaretState()
  730. if (event.key === "Escape") {
  731. setStore("mode", "normal")
  732. event.preventDefault()
  733. return
  734. }
  735. if (event.key === "Backspace" && collapsed && cursorPosition === 0 && textLength === 0) {
  736. setStore("mode", "normal")
  737. event.preventDefault()
  738. return
  739. }
  740. }
  741. // Handle Shift+Enter BEFORE IME check - Shift+Enter is never used for IME input
  742. // and should always insert a newline regardless of composition state
  743. if (event.key === "Enter" && event.shiftKey) {
  744. addPart({ type: "text", content: "\n", start: 0, end: 0 })
  745. event.preventDefault()
  746. return
  747. }
  748. if (event.key === "Enter" && isImeComposing(event)) {
  749. return
  750. }
  751. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  752. if (store.popover) {
  753. if (event.key === "Tab") {
  754. selectPopoverActive()
  755. event.preventDefault()
  756. return
  757. }
  758. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  759. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  760. if (nav || ctrlNav) {
  761. if (store.popover === "at") {
  762. atOnKeyDown(event)
  763. event.preventDefault()
  764. return
  765. }
  766. if (store.popover === "slash") {
  767. slashOnKeyDown(event)
  768. }
  769. event.preventDefault()
  770. return
  771. }
  772. }
  773. if (ctrl && event.code === "KeyG") {
  774. if (store.popover) {
  775. setStore("popover", null)
  776. event.preventDefault()
  777. return
  778. }
  779. if (working()) {
  780. abort()
  781. event.preventDefault()
  782. }
  783. return
  784. }
  785. if (event.key === "ArrowUp" || event.key === "ArrowDown") {
  786. if (event.altKey || event.ctrlKey || event.metaKey) return
  787. const { collapsed } = getCaretState()
  788. if (!collapsed) return
  789. const cursorPosition = getCursorPosition(editorRef)
  790. const textLength = promptLength(prompt.current())
  791. const textContent = prompt
  792. .current()
  793. .map((part) => ("content" in part ? part.content : ""))
  794. .join("")
  795. const isEmpty = textContent.trim() === "" || textLength <= 1
  796. const hasNewlines = textContent.includes("\n")
  797. const inHistory = store.historyIndex >= 0
  798. const atStart = cursorPosition <= (isEmpty ? 1 : 0)
  799. const atEnd = cursorPosition >= (isEmpty ? textLength - 1 : textLength)
  800. const allowUp = isEmpty || atStart || (!hasNewlines && !inHistory) || (inHistory && atEnd)
  801. const allowDown = isEmpty || atEnd || (!hasNewlines && !inHistory) || (inHistory && atStart)
  802. if (event.key === "ArrowUp") {
  803. if (!allowUp) return
  804. if (navigateHistory("up")) {
  805. event.preventDefault()
  806. }
  807. return
  808. }
  809. if (!allowDown) return
  810. if (navigateHistory("down")) {
  811. event.preventDefault()
  812. }
  813. return
  814. }
  815. // Note: Shift+Enter is handled earlier, before IME check
  816. if (event.key === "Enter" && !event.shiftKey) {
  817. handleSubmit(event)
  818. }
  819. if (event.key === "Escape") {
  820. if (store.popover) {
  821. setStore("popover", null)
  822. } else if (working()) {
  823. abort()
  824. }
  825. }
  826. }
  827. return (
  828. <div class="relative size-full _max-h-[320px] flex flex-col gap-3">
  829. <PromptPopover
  830. popover={store.popover}
  831. setSlashPopoverRef={(el) => (slashPopoverRef = el)}
  832. atFlat={atFlat()}
  833. atActive={atActive() ?? undefined}
  834. atKey={atKey}
  835. setAtActive={setAtActive}
  836. onAtSelect={handleAtSelect}
  837. slashFlat={slashFlat()}
  838. slashActive={slashActive() ?? undefined}
  839. setSlashActive={setSlashActive}
  840. onSlashSelect={handleSlashSelect}
  841. commandKeybind={command.keybind}
  842. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  843. />
  844. <form
  845. onSubmit={handleSubmit}
  846. classList={{
  847. "group/prompt-input": true,
  848. "bg-surface-raised-stronger-non-alpha shadow-xs-border relative": true,
  849. "rounded-[14px] overflow-clip focus-within:shadow-xs-border": true,
  850. "border-icon-info-active border-dashed": store.dragging,
  851. [props.class ?? ""]: !!props.class,
  852. }}
  853. >
  854. <PromptDragOverlay dragging={store.dragging} label={language.t("prompt.dropzone.label")} />
  855. <PromptContextItems
  856. items={prompt.context.items()}
  857. active={(item) => {
  858. const active = comments.active()
  859. return !!item.commentID && item.commentID === active?.id && item.path === active?.file
  860. }}
  861. openComment={openComment}
  862. remove={(item) => {
  863. if (item.commentID) comments.remove(item.path, item.commentID)
  864. prompt.context.remove(item.key)
  865. }}
  866. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  867. />
  868. <PromptImageAttachments
  869. attachments={imageAttachments()}
  870. onOpen={(attachment) =>
  871. dialog.show(() => <ImagePreview src={attachment.dataUrl} alt={attachment.filename} />)
  872. }
  873. onRemove={removeImageAttachment}
  874. removeLabel={language.t("prompt.attachment.remove")}
  875. />
  876. <div class="relative max-h-[240px] overflow-y-auto" ref={(el) => (scrollRef = el)}>
  877. <div
  878. data-component="prompt-input"
  879. ref={(el) => {
  880. editorRef = el
  881. props.ref?.(el)
  882. }}
  883. role="textbox"
  884. aria-multiline="true"
  885. aria-label={placeholder()}
  886. contenteditable="true"
  887. onInput={handleInput}
  888. onPaste={handlePaste}
  889. onCompositionStart={() => setComposing(true)}
  890. onCompositionEnd={() => setComposing(false)}
  891. onKeyDown={handleKeyDown}
  892. classList={{
  893. "select-text": true,
  894. "w-full p-3 pr-12 text-14-regular text-text-strong focus:outline-none whitespace-pre-wrap": true,
  895. "[&_[data-type=file]]:text-syntax-property": true,
  896. "[&_[data-type=agent]]:text-syntax-type": true,
  897. "font-mono!": store.mode === "shell",
  898. }}
  899. />
  900. <Show when={!prompt.dirty()}>
  901. <div class="absolute top-0 inset-x-0 p-3 pr-12 text-14-regular text-text-weak pointer-events-none whitespace-nowrap truncate">
  902. {placeholder()}
  903. </div>
  904. </Show>
  905. </div>
  906. <div class="relative p-3 flex items-center justify-between gap-2">
  907. <div class="flex items-center gap-2 min-w-0 flex-1">
  908. <Switch>
  909. <Match when={store.mode === "shell"}>
  910. <div class="flex items-center gap-2 px-2 h-6">
  911. <Icon name="console" size="small" class="text-icon-primary" />
  912. <span class="text-12-regular text-text-primary">{language.t("prompt.mode.shell")}</span>
  913. <span class="text-12-regular text-text-weak">{language.t("prompt.mode.shell.exit")}</span>
  914. </div>
  915. </Match>
  916. <Match when={store.mode === "normal"}>
  917. <TooltipKeybind
  918. placement="top"
  919. gutter={8}
  920. title={language.t("command.agent.cycle")}
  921. keybind={command.keybind("agent.cycle")}
  922. >
  923. <Select
  924. options={local.agent.list().map((agent) => agent.name)}
  925. current={local.agent.current()?.name ?? ""}
  926. onSelect={local.agent.set}
  927. class={`capitalize ${local.model.variant.list().length > 0 ? "max-w-full" : "max-w-[120px]"}`}
  928. valueClass="truncate"
  929. variant="ghost"
  930. />
  931. </TooltipKeybind>
  932. <Show
  933. when={providers.paid().length > 0}
  934. fallback={
  935. <TooltipKeybind
  936. placement="top"
  937. gutter={8}
  938. title={language.t("command.model.choose")}
  939. keybind={command.keybind("model.choose")}
  940. >
  941. <Button
  942. as="div"
  943. variant="ghost"
  944. class="px-2 min-w-0 max-w-[240px]"
  945. onClick={() => dialog.show(() => <DialogSelectModelUnpaid />)}
  946. >
  947. <Show when={local.model.current()?.provider?.id}>
  948. <ProviderIcon id={local.model.current()!.provider.id as IconName} class="size-4 shrink-0" />
  949. </Show>
  950. <span class="truncate">
  951. {local.model.current()?.name ?? language.t("dialog.model.select.title")}
  952. </span>
  953. <Icon name="chevron-down" size="small" class="shrink-0" />
  954. </Button>
  955. </TooltipKeybind>
  956. }
  957. >
  958. <TooltipKeybind
  959. placement="top"
  960. gutter={8}
  961. title={language.t("command.model.choose")}
  962. keybind={command.keybind("model.choose")}
  963. >
  964. <ModelSelectorPopover
  965. triggerAs={Button}
  966. triggerProps={{ variant: "ghost", class: "min-w-0 max-w-[240px]" }}
  967. >
  968. <Show when={local.model.current()?.provider?.id}>
  969. <ProviderIcon id={local.model.current()!.provider.id as IconName} class="size-4 shrink-0" />
  970. </Show>
  971. <span class="truncate">
  972. {local.model.current()?.name ?? language.t("dialog.model.select.title")}
  973. </span>
  974. <Icon name="chevron-down" size="small" class="shrink-0" />
  975. </ModelSelectorPopover>
  976. </TooltipKeybind>
  977. </Show>
  978. <Show when={local.model.variant.list().length > 0}>
  979. <TooltipKeybind
  980. placement="top"
  981. gutter={8}
  982. title={language.t("command.model.variant.cycle")}
  983. keybind={command.keybind("model.variant.cycle")}
  984. >
  985. <Button
  986. data-action="model-variant-cycle"
  987. variant="ghost"
  988. class="text-text-base _hidden group-hover/prompt-input:inline-block capitalize text-12-regular"
  989. onClick={() => local.model.variant.cycle()}
  990. >
  991. {local.model.variant.current() ?? language.t("common.default")}
  992. </Button>
  993. </TooltipKeybind>
  994. </Show>
  995. <Show when={permission.permissionsEnabled() && params.id}>
  996. <TooltipKeybind
  997. placement="top"
  998. gutter={8}
  999. title={language.t("command.permissions.autoaccept.enable")}
  1000. keybind={command.keybind("permissions.autoaccept")}
  1001. >
  1002. <Button
  1003. variant="ghost"
  1004. onClick={() => permission.toggleAutoAccept(params.id!, sdk.directory)}
  1005. classList={{
  1006. "_hidden group-hover/prompt-input:flex size-6 items-center justify-center": true,
  1007. "text-text-base": !permission.isAutoAccepting(params.id!, sdk.directory),
  1008. "hover:bg-surface-success-base": permission.isAutoAccepting(params.id!, sdk.directory),
  1009. }}
  1010. aria-label={
  1011. permission.isAutoAccepting(params.id!, sdk.directory)
  1012. ? language.t("command.permissions.autoaccept.disable")
  1013. : language.t("command.permissions.autoaccept.enable")
  1014. }
  1015. aria-pressed={permission.isAutoAccepting(params.id!, sdk.directory)}
  1016. >
  1017. <Icon
  1018. name="chevron-double-right"
  1019. size="small"
  1020. classList={{ "text-icon-success-base": permission.isAutoAccepting(params.id!, sdk.directory) }}
  1021. />
  1022. </Button>
  1023. </TooltipKeybind>
  1024. </Show>
  1025. </Match>
  1026. </Switch>
  1027. </div>
  1028. <div class="flex items-center gap-1 shrink-0">
  1029. <input
  1030. ref={fileInputRef}
  1031. type="file"
  1032. accept={ACCEPTED_FILE_TYPES.join(",")}
  1033. class="hidden"
  1034. onChange={(e) => {
  1035. const file = e.currentTarget.files?.[0]
  1036. if (file) addImageAttachment(file)
  1037. e.currentTarget.value = ""
  1038. }}
  1039. />
  1040. <div class="flex items-center gap-1 mr-1">
  1041. <SessionContextUsage />
  1042. <Show when={store.mode === "normal"}>
  1043. <Tooltip placement="top" value={language.t("prompt.action.attachFile")}>
  1044. <Button
  1045. type="button"
  1046. variant="ghost"
  1047. class="size-6 px-1"
  1048. onClick={() => fileInputRef.click()}
  1049. aria-label={language.t("prompt.action.attachFile")}
  1050. >
  1051. <Icon name="photo" class="size-4.5" />
  1052. </Button>
  1053. </Tooltip>
  1054. </Show>
  1055. </div>
  1056. <Tooltip
  1057. placement="top"
  1058. inactive={!prompt.dirty() && !working()}
  1059. value={
  1060. <Switch>
  1061. <Match when={working()}>
  1062. <div class="flex items-center gap-2">
  1063. <span>{language.t("prompt.action.stop")}</span>
  1064. <span class="text-icon-base text-12-medium text-[10px]!">{language.t("common.key.esc")}</span>
  1065. </div>
  1066. </Match>
  1067. <Match when={true}>
  1068. <div class="flex items-center gap-2">
  1069. <span>{language.t("prompt.action.send")}</span>
  1070. <Icon name="enter" size="small" class="text-icon-base" />
  1071. </div>
  1072. </Match>
  1073. </Switch>
  1074. }
  1075. >
  1076. <IconButton
  1077. type="submit"
  1078. disabled={!prompt.dirty() && !working() && commentCount() === 0}
  1079. icon={working() ? "stop" : "arrow-up"}
  1080. variant="primary"
  1081. class="h-6 w-4.5"
  1082. aria-label={working() ? language.t("prompt.action.stop") : language.t("prompt.action.send")}
  1083. />
  1084. </Tooltip>
  1085. </div>
  1086. </div>
  1087. </form>
  1088. </div>
  1089. )
  1090. }