prompt-input.tsx 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. import { useFilteredList } from "@opencode-ai/ui/hooks"
  2. import { useSpring } from "@opencode-ai/ui/motion-spring"
  3. import {
  4. createEffect,
  5. on,
  6. Component,
  7. Show,
  8. onCleanup,
  9. createMemo,
  10. createSignal,
  11. createResource,
  12. Switch,
  13. Match,
  14. type JSX,
  15. } from "solid-js"
  16. import { selectionFromLines, type SelectedLineRange, useFile } from "@/context/file"
  17. import {
  18. ContentPart,
  19. DEFAULT_PROMPT,
  20. isCommentItem,
  21. isPromptEqual,
  22. Prompt,
  23. usePrompt,
  24. ImageAttachmentPart,
  25. AgentPart,
  26. FileAttachmentPart,
  27. } from "@/context/prompt"
  28. import { useLayout } from "@/context/layout"
  29. import { useSDK } from "@/context/sdk"
  30. import { useSync } from "@/context/sync"
  31. import { useComments } from "@/context/comments"
  32. import { Button } from "@opencode-ai/ui/button"
  33. import { DockShellForm, DockTray } from "@opencode-ai/ui/dock-surface"
  34. import { Icon } from "@opencode-ai/ui/icon"
  35. import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
  36. import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
  37. import { ButtonV2 } from "@opencode-ai/ui/v2/button-v2"
  38. import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
  39. import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
  40. import { KeybindV2 } from "@opencode-ai/ui/v2/keybind-v2"
  41. import { MenuV2 } from "@opencode-ai/ui/v2/menu-v2"
  42. import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
  43. import { IconButton } from "@opencode-ai/ui/icon-button"
  44. import { Select } from "@opencode-ai/ui/select"
  45. import { useDialog } from "@opencode-ai/ui/context/dialog"
  46. import { ModelSelectorPopover, ModelSelectorPopoverV2 } from "@/components/dialog-select-model"
  47. import { DialogSelectModelUnpaid } from "@/components/dialog-select-model-unpaid"
  48. import { DialogSelectModelUnpaidV2 } from "@/components/dialog-select-model-unpaid-v2"
  49. import { useCommand } from "@/context/command"
  50. import { usePermission } from "@/context/permission"
  51. import { useLanguage } from "@/context/language"
  52. import { usePlatform } from "@/context/platform"
  53. import { createSessionTabs } from "@/pages/session/helpers"
  54. import { createTextFragment, getCursorPosition, setCursorPosition, setRangeEdge } from "./prompt-input/editor-dom"
  55. import { createPromptAttachments } from "./prompt-input/attachments"
  56. import { ACCEPTED_FILE_TYPES, pickAttachmentFiles } from "./prompt-input/files"
  57. import {
  58. canNavigateHistoryAtCursor,
  59. navigatePromptHistory,
  60. type PromptHistoryComment,
  61. type PromptHistoryEntry,
  62. promptLength,
  63. } from "./prompt-input/history"
  64. import {
  65. createPersistedPromptInputHistory,
  66. createPromptInputHistory,
  67. type PromptInputHistory,
  68. } from "./prompt-input/history-store"
  69. import {
  70. type PromptInputControls,
  71. type PromptInputProps,
  72. type PromptInputState,
  73. type PromptInputSubmission,
  74. } from "./prompt-input/contracts"
  75. import { createPromptSubmit } from "./prompt-input/submit"
  76. import { PromptPopover, type AtOption, type SlashCommand } from "./prompt-input/slash-popover"
  77. import { PromptContextItems } from "./prompt-input/context-items"
  78. import { PromptImageAttachments } from "./prompt-input/image-attachments"
  79. import { PromptDragOverlay } from "./prompt-input/drag-overlay"
  80. import { promptPlaceholder } from "./prompt-input/placeholder"
  81. import { createPromptInputTransientState } from "./prompt-input/transient-state"
  82. import { showToast } from "@/utils/toast"
  83. import { ImagePreview } from "@opencode-ai/ui/image-preview"
  84. import type { ReferenceInfo } from "@opencode-ai/sdk/v2/client"
  85. export { createPromptInputHistory }
  86. export type { PromptInputControls, PromptInputHistory, PromptInputProps, PromptInputState, PromptInputSubmission }
  87. const EXAMPLES = [
  88. "prompt.example.1",
  89. "prompt.example.2",
  90. "prompt.example.3",
  91. "prompt.example.4",
  92. "prompt.example.5",
  93. "prompt.example.6",
  94. "prompt.example.7",
  95. "prompt.example.8",
  96. "prompt.example.9",
  97. "prompt.example.10",
  98. "prompt.example.11",
  99. "prompt.example.12",
  100. "prompt.example.13",
  101. "prompt.example.14",
  102. "prompt.example.15",
  103. "prompt.example.16",
  104. "prompt.example.17",
  105. "prompt.example.18",
  106. "prompt.example.19",
  107. "prompt.example.20",
  108. "prompt.example.21",
  109. "prompt.example.22",
  110. "prompt.example.23",
  111. "prompt.example.24",
  112. "prompt.example.25",
  113. ] as const
  114. export const PromptInput: Component<PromptInputProps> = (props) => {
  115. const sdk = useSDK()
  116. const sync = useSync()
  117. const files = useFile()
  118. const prompt = props.state ?? usePrompt()
  119. const layout = useLayout()
  120. const comments = useComments()
  121. const dialog = useDialog()
  122. const command = useCommand()
  123. const permission = usePermission()
  124. const language = useLanguage()
  125. const platform = usePlatform()
  126. const tabs = () => props.controls.session.tabs
  127. let editorRef!: HTMLDivElement
  128. let fileInputRef: HTMLInputElement | undefined
  129. let scrollRef!: HTMLDivElement
  130. let slashPopoverRef!: HTMLDivElement
  131. let restoreEndOnFocus = true
  132. let savedCursor: number | null = null
  133. const mirror = { input: false }
  134. const inset = 56
  135. const space = `${inset}px`
  136. const scrollCursorIntoView = () => {
  137. const container = scrollRef
  138. const selection = window.getSelection()
  139. if (!container || !selection || selection.rangeCount === 0) return
  140. const range = selection.getRangeAt(0)
  141. if (!editorRef.contains(range.startContainer)) return
  142. const cursor = getCursorPosition(editorRef)
  143. const length = promptLength(prompt.current().filter((part) => part.type !== "image"))
  144. if (cursor >= length) {
  145. container.scrollTop = container.scrollHeight
  146. return
  147. }
  148. const rect = range.getClientRects().item(0) ?? range.getBoundingClientRect()
  149. if (!rect.height) return
  150. const containerRect = container.getBoundingClientRect()
  151. const top = rect.top - containerRect.top + container.scrollTop
  152. const bottom = rect.bottom - containerRect.top + container.scrollTop
  153. const padding = 12
  154. if (top < container.scrollTop + padding) {
  155. container.scrollTop = Math.max(0, top - padding)
  156. return
  157. }
  158. if (bottom > container.scrollTop + container.clientHeight - inset) {
  159. container.scrollTop = bottom - container.clientHeight + inset
  160. }
  161. }
  162. const queueScroll = (count = 2) => {
  163. requestAnimationFrame(() => {
  164. scrollCursorIntoView()
  165. if (count > 1) queueScroll(count - 1)
  166. })
  167. }
  168. const activeFileTab = createSessionTabs({
  169. tabs,
  170. pathFromTab: files.pathFromTab,
  171. normalizeTab: (tab) => (tab.startsWith("file://") ? files.tab(tab) : tab),
  172. }).activeFileTab
  173. const commentInReview = (path: string) => {
  174. const sessionID = props.controls.session.id
  175. if (!sessionID) return false
  176. const diffs = sync().data.session_diff[sessionID]
  177. if (!diffs) return false
  178. return diffs.some((diff) => diff.file === path)
  179. }
  180. const openComment = (item: { path: string; commentID?: string; commentOrigin?: "review" | "file" }) => {
  181. if (!item.commentID) return
  182. const focus = { file: item.path, id: item.commentID }
  183. comments.setActive(focus)
  184. const queueCommentFocus = (attempts = 6) => {
  185. const schedule = (left: number) => {
  186. requestAnimationFrame(() => {
  187. comments.setFocus({ ...focus })
  188. if (left <= 0) return
  189. requestAnimationFrame(() => {
  190. const current = comments.focus()
  191. if (!current) return
  192. if (current.file !== focus.file || current.id !== focus.id) return
  193. schedule(left - 1)
  194. })
  195. })
  196. }
  197. schedule(attempts)
  198. }
  199. const wantsReview = item.commentOrigin === "review" || (item.commentOrigin !== "file" && commentInReview(item.path))
  200. if (wantsReview) {
  201. if (!props.controls.session.reviewPanel.opened()) props.controls.session.reviewPanel.open()
  202. layout.fileTree.setTab("changes")
  203. tabs().setActive("review")
  204. queueCommentFocus()
  205. return
  206. }
  207. if (!props.controls.session.reviewPanel.opened()) props.controls.session.reviewPanel.open()
  208. layout.fileTree.setTab("all")
  209. const tab = files.tab(item.path)
  210. void tabs().open(tab)
  211. tabs().setActive(tab)
  212. void Promise.resolve(files.load(item.path)).finally(() => queueCommentFocus())
  213. }
  214. const recent = createMemo(() => {
  215. const all = tabs().all()
  216. const active = activeFileTab()
  217. const order = active ? [active, ...all.filter((x) => x !== active)] : all
  218. const seen = new Set<string>()
  219. const paths: string[] = []
  220. for (const tab of order) {
  221. const path = files.pathFromTab(tab)
  222. if (!path) continue
  223. if (seen.has(path)) continue
  224. seen.add(path)
  225. paths.push(path)
  226. }
  227. return paths
  228. })
  229. const info = createMemo(() => (props.controls.session.id ? sync().session.get(props.controls.session.id) : undefined))
  230. const working = createMemo(() => sync().data.session_working(props.controls.session.id ?? ""))
  231. const imageAttachments = createMemo(() =>
  232. prompt.current().filter((part): part is ImageAttachmentPart => part.type === "image"),
  233. )
  234. const [store, setStore] = createPromptInputTransientState(
  235. () => prompt.capture(),
  236. Math.floor(Math.random() * EXAMPLES.length),
  237. )
  238. const buttonsSpring = useSpring(() => (store.mode === "normal" ? 1 : 0), { visualDuration: 0.2, bounce: 0 })
  239. const motion = (value: number) => ({
  240. opacity: value,
  241. transform: `scale(${0.98 + value * 0.02})`,
  242. filter: `blur(${(1 - value) * 2}px)`,
  243. "pointer-events": value > 0.5 ? ("auto" as const) : ("none" as const),
  244. })
  245. const buttons = createMemo(() => motion(buttonsSpring()))
  246. const shell = createMemo(() => motion(1 - buttonsSpring()))
  247. const control = createMemo(() => ({ height: "28px", ...buttons() }))
  248. const commentCount = createMemo(() => {
  249. if (store.mode === "shell") return 0
  250. return prompt.context.items().filter((item) => !!item.comment?.trim()).length
  251. })
  252. const blank = createMemo(() => {
  253. const text = prompt
  254. .current()
  255. .map((part) => ("content" in part ? part.content : ""))
  256. .join("")
  257. return text.trim().length === 0 && imageAttachments().length === 0 && commentCount() === 0
  258. })
  259. const stopping = createMemo(() => working() && blank())
  260. const tip = () => {
  261. if (stopping()) {
  262. return (
  263. <div class="flex items-center gap-2">
  264. <span>{language.t("prompt.action.stop")}</span>
  265. <span class="text-icon-base text-12-medium text-[10px]!">{language.t("common.key.esc")}</span>
  266. </div>
  267. )
  268. }
  269. return (
  270. <div class="flex items-center gap-2">
  271. <span>{language.t("prompt.action.send")}</span>
  272. <Icon name="enter" size="small" class="text-icon-base" />
  273. </div>
  274. )
  275. }
  276. const contextItems = createMemo(() => {
  277. const items = prompt.context.items()
  278. if (store.mode !== "shell") return items
  279. return items.filter((item) => !item.comment?.trim())
  280. })
  281. const hasUserPrompt = createMemo(() => {
  282. const sessionID = props.controls.session.id
  283. if (!sessionID) return false
  284. const messages = sync().data.message[sessionID]
  285. if (!messages) return false
  286. return messages.some((m) => m.role === "user")
  287. })
  288. const history = props.history ?? createPersistedPromptInputHistory()
  289. const suggest = createMemo(() => !hasUserPrompt())
  290. const placeholder = createMemo(() =>
  291. promptPlaceholder({
  292. mode: store.mode,
  293. commentCount: commentCount(),
  294. example: suggest() ? (store.mode === "shell" ? "git status" : language.t(EXAMPLES[store.placeholder])) : "",
  295. suggest: suggest(),
  296. t: (key, params) => language.t(key as Parameters<typeof language.t>[0], params as never),
  297. }),
  298. )
  299. const historyComments = () => {
  300. const byID = new Map(comments.all().map((item) => [`${item.file}\n${item.id}`, item] as const))
  301. return prompt.context.items().flatMap((item) => {
  302. if (item.type !== "file") return []
  303. const comment = item.comment?.trim()
  304. if (!comment) return []
  305. const selection = item.commentID ? byID.get(`${item.path}\n${item.commentID}`)?.selection : undefined
  306. const nextSelection =
  307. selection ??
  308. (item.selection
  309. ? ({
  310. start: item.selection.startLine,
  311. end: item.selection.endLine,
  312. } satisfies SelectedLineRange)
  313. : undefined)
  314. if (!nextSelection) return []
  315. return [
  316. {
  317. id: item.commentID ?? item.key,
  318. path: item.path,
  319. selection: { ...nextSelection },
  320. comment,
  321. time: item.commentID ? (byID.get(`${item.path}\n${item.commentID}`)?.time ?? Date.now()) : Date.now(),
  322. origin: item.commentOrigin,
  323. preview: item.preview,
  324. } satisfies PromptHistoryComment,
  325. ]
  326. })
  327. }
  328. const applyHistoryComments = (items: PromptHistoryComment[]) => {
  329. comments.replace(
  330. items.map((item) => ({
  331. id: item.id,
  332. file: item.path,
  333. selection: { ...item.selection },
  334. comment: item.comment,
  335. time: item.time,
  336. })),
  337. )
  338. prompt.context.replaceComments(
  339. items.map((item) => ({
  340. type: "file" as const,
  341. path: item.path,
  342. selection: selectionFromLines(item.selection),
  343. comment: item.comment,
  344. commentID: item.id,
  345. commentOrigin: item.origin,
  346. preview: item.preview,
  347. })),
  348. )
  349. }
  350. const applyHistoryPrompt = (entry: PromptHistoryEntry, position: "start" | "end") => {
  351. const p = entry.prompt
  352. const length = position === "start" ? 0 : promptLength(p)
  353. setStore("applyingHistory", true)
  354. applyHistoryComments(entry.comments)
  355. prompt.set(p, length)
  356. requestAnimationFrame(() => {
  357. editorRef.focus()
  358. setCursorPosition(editorRef, length)
  359. setStore("applyingHistory", false)
  360. queueScroll()
  361. })
  362. }
  363. const getCaretState = () => {
  364. const selection = window.getSelection()
  365. const textLength = promptLength(prompt.current())
  366. if (!selection || selection.rangeCount === 0) {
  367. return { collapsed: false, cursorPosition: 0, textLength }
  368. }
  369. const anchorNode = selection.anchorNode
  370. if (!anchorNode || !editorRef.contains(anchorNode)) {
  371. return { collapsed: false, cursorPosition: 0, textLength }
  372. }
  373. return {
  374. collapsed: selection.isCollapsed,
  375. cursorPosition: getCursorPosition(editorRef),
  376. textLength,
  377. }
  378. }
  379. const escBlur = () => platform.platform === "desktop" && platform.os === "macos"
  380. const pick = () => {
  381. pickAttachmentFiles({
  382. picker: platform.openAttachmentPickerDialog,
  383. directory: () => sdk().directory,
  384. fallback: () => fileInputRef?.click(),
  385. onFile: addAttachment,
  386. onError: (error) =>
  387. showToast({
  388. variant: "error",
  389. title: language.t("common.requestFailed"),
  390. description: error instanceof Error ? error.message : String(error),
  391. }),
  392. })
  393. }
  394. const setMode = (mode: "normal" | "shell") => {
  395. setStore("mode", mode)
  396. setStore({ popover: null, slashMenu: false, slashMenuQuery: "" })
  397. requestAnimationFrame(() => editorRef?.focus())
  398. }
  399. const shellModeKey = "mod+shift+x"
  400. const normalModeKey = "mod+shift+e"
  401. command.register("prompt-input", () => [
  402. {
  403. id: "file.attach",
  404. title: language.t("prompt.action.attachFile"),
  405. category: language.t("command.category.file"),
  406. keybind: "mod+u",
  407. disabled: store.mode !== "normal",
  408. onSelect: pick,
  409. },
  410. {
  411. id: "prompt.mode.shell",
  412. title: language.t("command.prompt.mode.shell"),
  413. category: language.t("command.category.session"),
  414. keybind: shellModeKey,
  415. disabled: store.mode === "shell",
  416. onSelect: () => setMode("shell"),
  417. },
  418. {
  419. id: "prompt.mode.normal",
  420. title: language.t("command.prompt.mode.normal"),
  421. category: language.t("command.category.session"),
  422. keybind: normalModeKey,
  423. disabled: store.mode === "normal",
  424. onSelect: () => setMode("normal"),
  425. },
  426. ])
  427. const closePopover = () => setStore({ popover: null, slashMenu: false, slashMenuQuery: "" })
  428. const resetHistoryNavigation = (force = false) => {
  429. if (!force && (store.historyIndex < 0 || store.applyingHistory)) return
  430. setStore("historyIndex", -1)
  431. setStore("savedPrompt", null)
  432. }
  433. const clearEditor = () => {
  434. editorRef.innerHTML = ""
  435. }
  436. const setEditorText = (text: string) => {
  437. clearEditor()
  438. editorRef.textContent = text
  439. }
  440. const focusEditorEnd = () => {
  441. requestAnimationFrame(() => {
  442. editorRef.focus()
  443. const range = document.createRange()
  444. const selection = window.getSelection()
  445. range.selectNodeContents(editorRef)
  446. range.collapse(false)
  447. selection?.removeAllRanges()
  448. selection?.addRange(range)
  449. })
  450. }
  451. const currentCursor = () => {
  452. const selection = window.getSelection()
  453. if (!selection || selection.rangeCount === 0 || !editorRef.contains(selection.anchorNode)) return null
  454. return getCursorPosition(editorRef)
  455. }
  456. const restoreFocus = () => {
  457. requestAnimationFrame(() => {
  458. const cursor = savedCursor ?? prompt.cursor() ?? promptLength(prompt.current())
  459. editorRef.focus()
  460. setCursorPosition(editorRef, cursor)
  461. queueScroll()
  462. })
  463. }
  464. const handleFocus = () => {
  465. if (!restoreEndOnFocus) return
  466. restoreEndOnFocus = false
  467. requestAnimationFrame(() => {
  468. if (document.activeElement !== editorRef) return
  469. setCursorPosition(editorRef, prompt.cursor() ?? promptLength(prompt.current()))
  470. queueScroll()
  471. })
  472. }
  473. const renderEditorWithCursor = (parts: Prompt) => {
  474. const cursor = currentCursor()
  475. renderEditor(parts)
  476. if (cursor !== null) setCursorPosition(editorRef, cursor)
  477. }
  478. createEffect(() => {
  479. props.controls.session.id
  480. if (props.controls.session.id) return
  481. if (!suggest()) return
  482. const interval = setInterval(() => {
  483. setStore("placeholder", (prev) => (prev + 1) % EXAMPLES.length)
  484. }, 6500)
  485. onCleanup(() => clearInterval(interval))
  486. })
  487. const [composing, setComposing] = createSignal(false)
  488. const isImeComposing = (event: KeyboardEvent) => event.isComposing || composing() || event.keyCode === 229
  489. const handleBlur = () => {
  490. const cursor = currentCursor()
  491. savedCursor = cursor
  492. if (cursor !== null && cursor !== prompt.cursor()) prompt.set(prompt.current(), cursor)
  493. closePopover()
  494. setComposing(false)
  495. }
  496. const handleCompositionStart = () => {
  497. setComposing(true)
  498. }
  499. const handleCompositionEnd = () => {
  500. setComposing(false)
  501. requestAnimationFrame(() => {
  502. if (composing()) return
  503. reconcile(prompt.current().filter((part) => part.type !== "image"))
  504. })
  505. }
  506. const referenceDescription = (reference: ReferenceInfo) =>
  507. reference.source.type === "git" ? reference.source.repository : reference.source.path
  508. const referenceList = createMemo(() =>
  509. sync()
  510. .data.reference.filter((reference) => !reference.hidden)
  511. .map(
  512. (reference): AtOption => ({
  513. type: "reference",
  514. name: reference.name,
  515. path: reference.path,
  516. display: reference.name,
  517. description: reference.description ?? referenceDescription(reference),
  518. }),
  519. ),
  520. )
  521. const agentList = createMemo(() =>
  522. props.controls.agents.available
  523. .filter((agent) => !agent.hidden && agent.mode !== "primary")
  524. .map((agent): AtOption => ({ type: "agent", name: agent.name, display: agent.name })),
  525. )
  526. const mcpResourceList = createMemo(() =>
  527. Object.values(sync().data.mcp_resource).map(
  528. (resource): AtOption => ({
  529. type: "resource",
  530. name: resource.name,
  531. uri: resource.uri,
  532. client: resource.server,
  533. display: resource.name,
  534. description: resource.description,
  535. mime: resource.mimeType,
  536. }),
  537. ),
  538. )
  539. const handleAtSelect = (option: AtOption | undefined) => {
  540. if (!option) return
  541. if (option.type === "agent") {
  542. addPart({ type: "agent", name: option.name, content: "@" + option.name, start: 0, end: 0 })
  543. return
  544. }
  545. if (option.type === "reference") {
  546. addPart({
  547. type: "file",
  548. path: option.path,
  549. content: "@" + option.name,
  550. start: 0,
  551. end: 0,
  552. mime: "application/x-directory",
  553. filename: option.name,
  554. })
  555. return
  556. }
  557. if (option.type === "resource") {
  558. addPart({
  559. type: "file",
  560. path: option.uri,
  561. content: "@" + option.name,
  562. start: 0,
  563. end: 0,
  564. mime: option.mime ?? "text/plain",
  565. filename: option.name,
  566. url: option.uri,
  567. source: {
  568. type: "resource",
  569. text: { value: "@" + option.name, start: 0, end: 0 },
  570. clientName: option.client,
  571. uri: option.uri,
  572. },
  573. })
  574. return
  575. }
  576. addPart({ type: "file", path: option.path, content: "@" + option.path, start: 0, end: 0 })
  577. }
  578. const atKey = (x: AtOption | undefined) => {
  579. if (!x) return ""
  580. if (x.type === "agent") return `agent:${x.name}`
  581. if (x.type === "reference") return `reference:${x.name}`
  582. if (x.type === "resource") return `resource:${x.client}:${x.uri}`
  583. return `file:${x.path}`
  584. }
  585. const {
  586. flat: atFlat,
  587. active: atActive,
  588. setActive: setAtActive,
  589. onInput: atOnInput,
  590. onKeyDown: atOnKeyDown,
  591. } = useFilteredList<AtOption>({
  592. items: async (query) => {
  593. const references = referenceList()
  594. const agents = agentList()
  595. const mcpResources = mcpResourceList()
  596. const open = recent()
  597. const seen = new Set(open)
  598. const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true }))
  599. if (!query.trim()) return [...references, ...agents, ...mcpResources, ...pinned]
  600. const paths = await files.searchFilesAndDirectories(query)
  601. const fileOptions: AtOption[] = paths
  602. .filter((path) => !seen.has(path))
  603. .map((path) => ({ type: "file", path, display: path }))
  604. return [...references, ...agents, ...mcpResources, ...pinned, ...fileOptions]
  605. },
  606. key: atKey,
  607. filterKeys: ["display"],
  608. skipFilter: (item) => item.type === "file" && !item.recent,
  609. groupBy: (item) => {
  610. if (item.type === "reference") return "reference"
  611. if (item.type === "agent") return "agent"
  612. if (item.type === "resource") return "resource"
  613. if (item.recent) return "recent"
  614. return "file"
  615. },
  616. sortGroupsBy: (a, b) => {
  617. const rank = (category: string) => {
  618. if (category === "reference") return 0
  619. if (category === "agent") return 1
  620. if (category === "resource") return 2
  621. if (category === "recent") return 3
  622. return 4
  623. }
  624. return rank(a.category) - rank(b.category)
  625. },
  626. onSelect: handleAtSelect,
  627. })
  628. const slashCommands = createMemo<SlashCommand[]>(() => {
  629. const builtin = command.options
  630. .filter((opt) => !opt.disabled && !opt.id.startsWith("suggested.") && opt.slash)
  631. .map((opt) => ({
  632. id: opt.id,
  633. trigger: opt.slash!,
  634. title: opt.title,
  635. description: opt.description,
  636. keybind: opt.keybind,
  637. type: "builtin" as const,
  638. }))
  639. const custom = sync().data.command.map((cmd) => ({
  640. id: `custom.${cmd.name}`,
  641. trigger: cmd.name,
  642. title: cmd.name,
  643. description: cmd.description,
  644. type: "custom" as const,
  645. // source: cmd.source,
  646. }))
  647. return [...custom, ...builtin]
  648. })
  649. const handleSlashSelect = (cmd: SlashCommand | undefined) => {
  650. if (!cmd) return
  651. const menu = store.slashMenu
  652. closePopover()
  653. const images = imageAttachments()
  654. if (cmd.type === "custom") {
  655. const text = `/${cmd.trigger} `
  656. if (menu) {
  657. editorRef.focus()
  658. setCursorPosition(editorRef, 0)
  659. addPart({ type: "text", content: text, start: 0, end: text.length })
  660. focusEditorEnd()
  661. return
  662. }
  663. setEditorText(text)
  664. prompt.set([{ type: "text", content: text, start: 0, end: text.length }, ...images], text.length)
  665. focusEditorEnd()
  666. return
  667. }
  668. if (menu) {
  669. command.trigger(cmd.id, "slash")
  670. return
  671. }
  672. clearEditor()
  673. prompt.set([...DEFAULT_PROMPT, ...images], 0)
  674. command.trigger(cmd.id, "slash")
  675. }
  676. const {
  677. flat: slashFlat,
  678. active: slashActive,
  679. setActive: setSlashActive,
  680. onInput: slashOnInput,
  681. onKeyDown: slashOnKeyDown,
  682. } = useFilteredList<SlashCommand>({
  683. items: slashCommands,
  684. key: (x) => x?.id,
  685. filterKeys: ["trigger", "title"],
  686. onSelect: handleSlashSelect,
  687. })
  688. const createPill = (part: FileAttachmentPart | AgentPart) => {
  689. const pill = document.createElement("span")
  690. pill.textContent = part.content
  691. pill.setAttribute("data-type", part.type)
  692. if (part.type === "file") {
  693. pill.setAttribute("data-path", part.path)
  694. if (part.mime) pill.setAttribute("data-mime", part.mime)
  695. if (part.filename) pill.setAttribute("data-filename", part.filename)
  696. if (part.url) pill.setAttribute("data-url", part.url)
  697. if (part.source?.type === "resource") {
  698. pill.setAttribute("data-source-type", part.source.type)
  699. pill.setAttribute("data-source-client-name", part.source.clientName)
  700. pill.setAttribute("data-source-uri", part.source.uri)
  701. }
  702. }
  703. if (part.type === "agent") pill.setAttribute("data-name", part.name)
  704. pill.setAttribute("contenteditable", "false")
  705. pill.style.userSelect = "text"
  706. pill.style.cursor = "default"
  707. return pill
  708. }
  709. const isNormalizedEditor = () =>
  710. Array.from(editorRef.childNodes).every((node) => {
  711. if (node.nodeType === Node.TEXT_NODE) {
  712. const text = node.textContent ?? ""
  713. if (!text.includes("\u200B")) return true
  714. if (text !== "\u200B") return false
  715. const prev = node.previousSibling
  716. const next = node.nextSibling
  717. const prevIsBr = prev?.nodeType === Node.ELEMENT_NODE && (prev as HTMLElement).tagName === "BR"
  718. return !!prevIsBr && !next
  719. }
  720. if (node.nodeType !== Node.ELEMENT_NODE) return false
  721. const el = node as HTMLElement
  722. if (el.dataset.type === "file") return true
  723. if (el.dataset.type === "agent") return true
  724. return el.tagName === "BR"
  725. })
  726. const renderEditor = (parts: Prompt) => {
  727. clearEditor()
  728. for (const part of parts) {
  729. if (part.type === "text") {
  730. editorRef.appendChild(createTextFragment(part.content))
  731. continue
  732. }
  733. if (part.type === "file" || part.type === "agent") {
  734. editorRef.appendChild(createPill(part))
  735. }
  736. }
  737. const last = editorRef.lastChild
  738. if (last?.nodeType === Node.ELEMENT_NODE && (last as HTMLElement).tagName === "BR") {
  739. editorRef.appendChild(document.createTextNode("\u200B"))
  740. }
  741. }
  742. const scrollSlashActiveIntoView = () => {
  743. const activeId = slashActive()
  744. if (!activeId || !slashPopoverRef) return
  745. requestAnimationFrame(() => {
  746. const element = slashPopoverRef.querySelector(`[data-slash-id="${activeId}"]`)
  747. element?.scrollIntoView({ block: "nearest", behavior: "smooth" })
  748. })
  749. }
  750. const selectPopoverActive = () => {
  751. if (store.popover === "at") {
  752. const items = atFlat()
  753. if (items.length === 0) return
  754. const active = atActive()
  755. const item = items.find((entry) => atKey(entry) === active) ?? items[0]
  756. handleAtSelect(item)
  757. return
  758. }
  759. if (store.popover === "slash") {
  760. const items = slashFlat()
  761. if (items.length === 0) return
  762. const active = slashActive()
  763. const item = items.find((entry) => entry.id === active) ?? items[0]
  764. handleSlashSelect(item)
  765. }
  766. }
  767. const reconcile = (input: Prompt) => {
  768. if (mirror.input) {
  769. mirror.input = false
  770. if (isNormalizedEditor()) return
  771. renderEditorWithCursor(input)
  772. return
  773. }
  774. const dom = parseFromDOM()
  775. if (isNormalizedEditor() && isPromptEqual(input, dom)) return
  776. renderEditorWithCursor(input)
  777. }
  778. createEffect(
  779. on(
  780. () => prompt.current(),
  781. (parts) => {
  782. if (composing()) return
  783. reconcile(parts.filter((part) => part.type !== "image"))
  784. },
  785. ),
  786. )
  787. const parseFromDOM = (): Prompt => {
  788. const parts: Prompt = []
  789. let position = 0
  790. let buffer = ""
  791. const flushText = () => {
  792. let content = buffer
  793. if (content.includes("\r")) content = content.replace(/\r\n?/g, "\n")
  794. if (content.includes("\u200B")) content = content.replace(/\u200B/g, "")
  795. buffer = ""
  796. if (!content) return
  797. parts.push({ type: "text", content, start: position, end: position + content.length })
  798. position += content.length
  799. }
  800. const pushFile = (file: HTMLElement) => {
  801. const content = file.textContent ?? ""
  802. const source =
  803. file.dataset.sourceType === "resource" && file.dataset.sourceClientName && file.dataset.sourceUri
  804. ? {
  805. type: "resource" as const,
  806. text: {
  807. value: content,
  808. start: position,
  809. end: position + content.length,
  810. },
  811. clientName: file.dataset.sourceClientName,
  812. uri: file.dataset.sourceUri,
  813. }
  814. : undefined
  815. parts.push({
  816. type: "file",
  817. path: file.dataset.path!,
  818. content,
  819. start: position,
  820. end: position + content.length,
  821. ...(file.dataset.mime ? { mime: file.dataset.mime } : {}),
  822. ...(file.dataset.filename ? { filename: file.dataset.filename } : {}),
  823. ...(file.dataset.url ? { url: file.dataset.url } : {}),
  824. ...(source ? { source } : {}),
  825. })
  826. position += content.length
  827. }
  828. const pushAgent = (agent: HTMLElement) => {
  829. const content = agent.textContent ?? ""
  830. parts.push({
  831. type: "agent",
  832. name: agent.dataset.name!,
  833. content,
  834. start: position,
  835. end: position + content.length,
  836. })
  837. position += content.length
  838. }
  839. const visit = (node: Node) => {
  840. if (node.nodeType === Node.TEXT_NODE) {
  841. buffer += node.textContent ?? ""
  842. return
  843. }
  844. if (node.nodeType !== Node.ELEMENT_NODE) return
  845. const el = node as HTMLElement
  846. if (el.dataset.type === "file") {
  847. flushText()
  848. pushFile(el)
  849. return
  850. }
  851. if (el.dataset.type === "agent") {
  852. flushText()
  853. pushAgent(el)
  854. return
  855. }
  856. if (el.tagName === "BR") {
  857. buffer += "\n"
  858. return
  859. }
  860. for (const child of Array.from(el.childNodes)) {
  861. visit(child)
  862. }
  863. }
  864. const children = Array.from(editorRef.childNodes)
  865. children.forEach((child, index) => {
  866. const isBlock = child.nodeType === Node.ELEMENT_NODE && ["DIV", "P"].includes((child as HTMLElement).tagName)
  867. visit(child)
  868. if (isBlock && index < children.length - 1) {
  869. buffer += "\n"
  870. }
  871. })
  872. flushText()
  873. if (parts.length === 0) parts.push(...DEFAULT_PROMPT)
  874. return parts
  875. }
  876. const handleInput = () => {
  877. const rawParts = parseFromDOM()
  878. const images = imageAttachments()
  879. const cursorPosition = getCursorPosition(editorRef)
  880. const rawText =
  881. rawParts.length === 1 && rawParts[0]?.type === "text"
  882. ? rawParts[0].content
  883. : rawParts.map((p) => ("content" in p ? p.content : "")).join("")
  884. const hasNonText = rawParts.some((part) => part.type !== "text")
  885. const textContent = (editorRef.textContent ?? "").replace(/\u200B/g, "")
  886. const shouldReset =
  887. textContent.length === 0 && rawText.replace(/\n/g, "").length === 0 && !hasNonText && images.length === 0
  888. if (shouldReset) {
  889. closePopover()
  890. resetHistoryNavigation()
  891. if (prompt.dirty()) {
  892. mirror.input = true
  893. prompt.set(DEFAULT_PROMPT, 0)
  894. }
  895. queueScroll()
  896. return
  897. }
  898. const shellMode = store.mode === "shell"
  899. if (!shellMode) {
  900. const atMatch = rawText.substring(0, cursorPosition).match(/@(\S*)$/)
  901. const slashMatch = rawText.match(/^\/(\S*)$/)
  902. if (atMatch) {
  903. atOnInput(atMatch[1])
  904. setStore({ popover: "at", slashMenu: false, slashMenuQuery: "" })
  905. } else if (slashMatch) {
  906. slashOnInput(slashMatch[1])
  907. setStore({ popover: "slash", slashMenu: false, slashMenuQuery: "" })
  908. } else {
  909. closePopover()
  910. }
  911. } else {
  912. closePopover()
  913. }
  914. resetHistoryNavigation()
  915. mirror.input = true
  916. prompt.set([...rawParts, ...images], cursorPosition)
  917. queueScroll()
  918. }
  919. const addPart = (part: ContentPart) => {
  920. if (part.type === "image") return false
  921. const selection = window.getSelection()
  922. if (!selection) return false
  923. if (selection.rangeCount === 0 || !editorRef.contains(selection.anchorNode)) {
  924. editorRef.focus()
  925. const cursor = prompt.cursor() ?? promptLength(prompt.current())
  926. setCursorPosition(editorRef, cursor)
  927. }
  928. if (selection.rangeCount === 0) return false
  929. const range = selection.getRangeAt(0)
  930. if (!editorRef.contains(range.startContainer)) return false
  931. if (part.type === "file" || part.type === "agent") {
  932. const cursorPosition = getCursorPosition(editorRef)
  933. const rawText = prompt
  934. .current()
  935. .map((p) => ("content" in p ? p.content : ""))
  936. .join("")
  937. const textBeforeCursor = rawText.substring(0, cursorPosition)
  938. const atMatch = textBeforeCursor.match(/@(\S*)$/)
  939. const pill = createPill(part)
  940. const gap = document.createTextNode(" ")
  941. if (atMatch) {
  942. const start = atMatch.index ?? cursorPosition - atMatch[0].length
  943. setRangeEdge(editorRef, range, "start", start)
  944. setRangeEdge(editorRef, range, "end", cursorPosition)
  945. }
  946. range.deleteContents()
  947. range.insertNode(gap)
  948. range.insertNode(pill)
  949. range.setStartAfter(gap)
  950. range.collapse(true)
  951. selection.removeAllRanges()
  952. selection.addRange(range)
  953. }
  954. if (part.type === "text") {
  955. const fragment = createTextFragment(part.content)
  956. const last = fragment.lastChild
  957. range.deleteContents()
  958. range.insertNode(fragment)
  959. if (last) {
  960. if (last.nodeType === Node.TEXT_NODE) {
  961. const text = last.textContent ?? ""
  962. if (text === "\u200B") {
  963. range.setStart(last, 0)
  964. }
  965. if (text !== "\u200B") {
  966. range.setStart(last, text.length)
  967. }
  968. }
  969. if (last.nodeType !== Node.TEXT_NODE) {
  970. const isBreak = last.nodeType === Node.ELEMENT_NODE && (last as HTMLElement).tagName === "BR"
  971. const next = last.nextSibling
  972. const emptyText = next?.nodeType === Node.TEXT_NODE && (next.textContent ?? "") === ""
  973. if (isBreak && (!next || emptyText)) {
  974. const placeholder = next && emptyText ? next : document.createTextNode("\u200B")
  975. if (!next) last.parentNode?.insertBefore(placeholder, null)
  976. placeholder.textContent = "\u200B"
  977. range.setStart(placeholder, 0)
  978. } else {
  979. range.setStartAfter(last)
  980. }
  981. }
  982. }
  983. range.collapse(true)
  984. selection.removeAllRanges()
  985. selection.addRange(range)
  986. }
  987. handleInput()
  988. closePopover()
  989. return true
  990. }
  991. const addToHistory = (prompt: Prompt, mode: "normal" | "shell") => {
  992. history.add(prompt, mode, mode === "shell" ? [] : historyComments())
  993. }
  994. createEffect(
  995. on(
  996. () => props.edit?.id,
  997. (id) => {
  998. const edit = props.edit
  999. if (!id || !edit) return
  1000. for (const item of prompt.context.items()) {
  1001. prompt.context.remove(item.key)
  1002. }
  1003. for (const item of edit.context) {
  1004. prompt.context.add({
  1005. type: item.type,
  1006. path: item.path,
  1007. selection: item.selection,
  1008. comment: item.comment,
  1009. commentID: item.commentID,
  1010. commentOrigin: item.commentOrigin,
  1011. preview: item.preview,
  1012. })
  1013. }
  1014. setStore("mode", "normal")
  1015. closePopover()
  1016. setStore("historyIndex", -1)
  1017. setStore("savedPrompt", null)
  1018. prompt.set(edit.prompt, promptLength(edit.prompt))
  1019. requestAnimationFrame(() => {
  1020. editorRef.focus()
  1021. setCursorPosition(editorRef, promptLength(edit.prompt))
  1022. queueScroll()
  1023. })
  1024. props.onEditLoaded?.()
  1025. },
  1026. { defer: true },
  1027. ),
  1028. )
  1029. const navigateHistory = (direction: "up" | "down") => {
  1030. const result = navigatePromptHistory({
  1031. direction,
  1032. entries: history.entries(store.mode),
  1033. historyIndex: store.historyIndex,
  1034. currentPrompt: prompt.current(),
  1035. currentComments: historyComments(),
  1036. savedPrompt: store.savedPrompt,
  1037. })
  1038. if (!result.handled) return false
  1039. setStore("historyIndex", result.historyIndex)
  1040. setStore("savedPrompt", result.savedPrompt)
  1041. applyHistoryPrompt(result.entry, result.cursor)
  1042. return true
  1043. }
  1044. const { addAttachment, addAttachments, removeAttachment, handlePaste } = createPromptAttachments({
  1045. prompt,
  1046. editor: () => editorRef,
  1047. isDialogActive: () => !!dialog.active,
  1048. setDraggingType: (type) => setStore("draggingType", type),
  1049. focusEditor: () => {
  1050. editorRef.focus()
  1051. setCursorPosition(editorRef, promptLength(prompt.current()))
  1052. },
  1053. addPart,
  1054. readClipboardImage: platform.readClipboardImage,
  1055. getPathForFile: platform.getPathForFile,
  1056. })
  1057. const fileAttachmentInput = () => (
  1058. <input
  1059. ref={(el) => (fileInputRef = el)}
  1060. type="file"
  1061. multiple
  1062. accept={ACCEPTED_FILE_TYPES.join(",")}
  1063. class="hidden"
  1064. onChange={(e) => {
  1065. const list = e.currentTarget.files
  1066. if (list) void addAttachments(Array.from(list))
  1067. e.currentTarget.value = ""
  1068. }}
  1069. />
  1070. )
  1071. const variants = createMemo(() => ["default", ...props.controls.model.selection.variant.list()])
  1072. // Check provider variants directly: `variants` also includes the UI-only default option.
  1073. const showVariantControl = createMemo(() => props.controls.model.selection.variant.list().length > 0)
  1074. const accepting = createMemo(() => {
  1075. const id = props.controls.session.id
  1076. if (!id) return permission.isAutoAcceptingDirectory(sdk().directory)
  1077. return permission.isAutoAccepting(id, sdk().directory)
  1078. })
  1079. const { abort, handleSubmit } =
  1080. props.submission ??
  1081. createPromptSubmit({
  1082. prompt,
  1083. info,
  1084. imageAttachments,
  1085. commentCount,
  1086. autoAccept: () => accepting(),
  1087. mode: () => store.mode,
  1088. working,
  1089. editor: () => editorRef,
  1090. queueScroll,
  1091. promptLength,
  1092. addToHistory,
  1093. resetHistoryNavigation: () => {
  1094. resetHistoryNavigation(true)
  1095. },
  1096. setMode: (mode) => setStore("mode", mode),
  1097. setPopover: (popover) => {
  1098. if (!popover) return closePopover()
  1099. setStore({ popover, slashMenu: false, slashMenuQuery: "" })
  1100. },
  1101. newSessionWorktree: () => props.newSessionWorktree,
  1102. onNewSessionWorktreeReset: props.onNewSessionWorktreeReset,
  1103. shouldQueue: props.shouldQueue,
  1104. onQueue: props.onQueue,
  1105. onAbort: props.onAbort,
  1106. onSubmit: props.onSubmit,
  1107. model: props.controls.model.selection,
  1108. })
  1109. const handleKeyDown = (event: KeyboardEvent) => {
  1110. if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "u") {
  1111. event.preventDefault()
  1112. if (store.mode !== "normal") return
  1113. pick()
  1114. return
  1115. }
  1116. if (event.key === "Backspace") {
  1117. const selection = window.getSelection()
  1118. if (selection && selection.isCollapsed) {
  1119. const node = selection.anchorNode
  1120. const offset = selection.anchorOffset
  1121. if (node && node.nodeType === Node.TEXT_NODE) {
  1122. const text = node.textContent ?? ""
  1123. if (/^\u200B+$/.test(text) && offset > 0) {
  1124. const range = document.createRange()
  1125. range.setStart(node, 0)
  1126. range.collapse(true)
  1127. selection.removeAllRanges()
  1128. selection.addRange(range)
  1129. }
  1130. }
  1131. }
  1132. }
  1133. if (event.key === "!" && store.mode === "normal") {
  1134. const cursorPosition = getCursorPosition(editorRef)
  1135. if (cursorPosition === 0) {
  1136. setStore("mode", "shell")
  1137. closePopover()
  1138. event.preventDefault()
  1139. return
  1140. }
  1141. }
  1142. if (event.key === "Escape") {
  1143. if (store.popover) {
  1144. closePopover()
  1145. event.preventDefault()
  1146. event.stopPropagation()
  1147. return
  1148. }
  1149. if (store.mode === "shell") {
  1150. setStore("mode", "normal")
  1151. event.preventDefault()
  1152. event.stopPropagation()
  1153. return
  1154. }
  1155. if (working()) {
  1156. void abort()
  1157. event.preventDefault()
  1158. event.stopPropagation()
  1159. return
  1160. }
  1161. if (escBlur()) {
  1162. editorRef.blur()
  1163. event.preventDefault()
  1164. event.stopPropagation()
  1165. return
  1166. }
  1167. }
  1168. if (store.mode === "shell") {
  1169. const { collapsed, cursorPosition, textLength } = getCaretState()
  1170. if (event.key === "Backspace" && collapsed && cursorPosition === 0 && textLength === 0) {
  1171. setStore("mode", "normal")
  1172. event.preventDefault()
  1173. return
  1174. }
  1175. }
  1176. // Handle Shift+Enter BEFORE IME check - Shift+Enter is never used for IME input
  1177. // and should always insert a newline regardless of composition state
  1178. if (event.key === "Enter" && event.shiftKey) {
  1179. addPart({ type: "text", content: "\n", start: 0, end: 0 })
  1180. event.preventDefault()
  1181. return
  1182. }
  1183. if (event.key === "Enter" && isImeComposing(event)) {
  1184. return
  1185. }
  1186. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  1187. if (store.popover) {
  1188. if (event.key === "Tab") {
  1189. selectPopoverActive()
  1190. event.preventDefault()
  1191. return
  1192. }
  1193. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  1194. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  1195. if (nav || ctrlNav) {
  1196. if (store.popover === "at") {
  1197. atOnKeyDown(event)
  1198. event.preventDefault()
  1199. return
  1200. }
  1201. if (store.popover === "slash") {
  1202. slashOnKeyDown(event)
  1203. if (event.key === "ArrowUp" || event.key === "ArrowDown" || ctrlNav) {
  1204. scrollSlashActiveIntoView()
  1205. }
  1206. }
  1207. event.preventDefault()
  1208. return
  1209. }
  1210. }
  1211. if (ctrl && event.code === "KeyG") {
  1212. if (store.popover) {
  1213. closePopover()
  1214. event.preventDefault()
  1215. return
  1216. }
  1217. if (working()) {
  1218. void abort()
  1219. event.preventDefault()
  1220. }
  1221. return
  1222. }
  1223. if (event.key === "ArrowUp" || event.key === "ArrowDown") {
  1224. if (event.altKey || event.ctrlKey || event.metaKey) return
  1225. const { collapsed } = getCaretState()
  1226. if (!collapsed) return
  1227. const cursorPosition = getCursorPosition(editorRef)
  1228. const textContent = prompt
  1229. .current()
  1230. .map((part) => ("content" in part ? part.content : ""))
  1231. .join("")
  1232. const direction = event.key === "ArrowUp" ? "up" : "down"
  1233. if (!canNavigateHistoryAtCursor(direction, textContent, cursorPosition, store.historyIndex >= 0)) return
  1234. if (navigateHistory(direction)) {
  1235. event.preventDefault()
  1236. }
  1237. return
  1238. }
  1239. // Note: Shift+Enter is handled earlier, before IME check
  1240. if (event.key === "Enter" && !event.shiftKey) {
  1241. event.preventDefault()
  1242. if (event.repeat) return
  1243. if (
  1244. working() &&
  1245. prompt
  1246. .current()
  1247. .map((part) => ("content" in part ? part.content : ""))
  1248. .join("")
  1249. .trim().length === 0 &&
  1250. imageAttachments().length === 0 &&
  1251. commentCount() === 0
  1252. ) {
  1253. return
  1254. }
  1255. void handleSubmit(event)
  1256. }
  1257. }
  1258. const handleSlashMenuKeyDown = (event: KeyboardEvent) => {
  1259. if (event.key === "Escape") {
  1260. closePopover()
  1261. requestAnimationFrame(() => editorRef.focus())
  1262. event.preventDefault()
  1263. return
  1264. }
  1265. if (event.key === "Tab") {
  1266. selectPopoverActive()
  1267. event.preventDefault()
  1268. return
  1269. }
  1270. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  1271. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  1272. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  1273. if (!nav && !ctrlNav) return
  1274. slashOnKeyDown(event)
  1275. if (event.key === "ArrowUp" || event.key === "ArrowDown" || ctrlNav) scrollSlashActiveIntoView()
  1276. event.preventDefault()
  1277. }
  1278. const agentsLoading = () => props.controls.agents.loading
  1279. const agentsShouldFadeIn = createMemo<boolean>((prev) => prev ?? agentsLoading())
  1280. const providersLoading = () => props.controls.model.loading
  1281. const providersShouldFadeIn = createMemo<boolean>((prev) => prev ?? providersLoading())
  1282. const [promptReady] = createResource(
  1283. () => prompt.ready.promise,
  1284. (p) => p,
  1285. )
  1286. const bindEditorRef = (el: HTMLDivElement) => {
  1287. editorRef = el
  1288. restoreEndOnFocus = true
  1289. props.ref?.(el)
  1290. }
  1291. return (
  1292. <div class="relative size-full flex flex-col gap-0">
  1293. {(promptReady(), null)}
  1294. <PromptPopover
  1295. popover={store.popover}
  1296. setSlashPopoverRef={(el) => (slashPopoverRef = el)}
  1297. atFlat={atFlat()}
  1298. atActive={atActive() ?? undefined}
  1299. atKey={atKey}
  1300. setAtActive={setAtActive}
  1301. onAtSelect={handleAtSelect}
  1302. slashFlat={slashFlat()}
  1303. slashActive={slashActive() ?? undefined}
  1304. setSlashActive={setSlashActive}
  1305. onSlashSelect={handleSlashSelect}
  1306. slashMenu={store.slashMenu}
  1307. slashMenuQuery={store.slashMenuQuery}
  1308. onSlashMenuInput={(value) => {
  1309. setStore("slashMenuQuery", value)
  1310. slashOnInput(value)
  1311. }}
  1312. onSlashMenuKeyDown={handleSlashMenuKeyDown}
  1313. commandKeybind={command.keybind}
  1314. commandKeybindParts={command.keybindParts}
  1315. newLayoutDesigns={false}
  1316. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  1317. />
  1318. <DockShellForm
  1319. data-dock-border-underlay="legacy"
  1320. onSubmit={handleSubmit}
  1321. classList={{
  1322. "group/prompt-input": true,
  1323. "border-icon-info-active border-dashed": store.draggingType !== null,
  1324. [props.class ?? ""]: !!props.class,
  1325. }}
  1326. >
  1327. <PromptDragOverlay
  1328. type={store.draggingType}
  1329. label={language.t(store.draggingType === "@mention" ? "prompt.dropzone.file.label" : "prompt.dropzone.label")}
  1330. />
  1331. <PromptContextItems
  1332. items={contextItems()}
  1333. active={(item) => {
  1334. const active = comments.active()
  1335. return !!item.commentID && item.commentID === active?.id && item.path === active?.file
  1336. }}
  1337. openComment={openComment}
  1338. remove={(item) => {
  1339. if (item.commentID) comments.remove(item.path, item.commentID)
  1340. prompt.context.remove(item.key)
  1341. }}
  1342. newLayoutDesigns={false}
  1343. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  1344. />
  1345. <PromptImageAttachments
  1346. attachments={imageAttachments()}
  1347. onOpen={(attachment) =>
  1348. dialog.show(() => <ImagePreview src={attachment.dataUrl} alt={attachment.filename} />)
  1349. }
  1350. onRemove={removeAttachment}
  1351. removeLabel={language.t("prompt.attachment.remove")}
  1352. newLayoutDesigns={false}
  1353. />
  1354. <div
  1355. class="relative"
  1356. onMouseDown={(e) => {
  1357. const target = e.target
  1358. if (!(target instanceof HTMLElement)) return
  1359. if (target.closest('[data-action="prompt-attach"], [data-action="prompt-submit"]')) {
  1360. return
  1361. }
  1362. editorRef?.focus()
  1363. }}
  1364. >
  1365. <div
  1366. class="relative max-h-[240px] overflow-y-auto no-scrollbar"
  1367. ref={(el) => (scrollRef = el)}
  1368. style={{ "scroll-padding-bottom": space }}
  1369. >
  1370. <div
  1371. data-component="prompt-input"
  1372. ref={bindEditorRef}
  1373. role="textbox"
  1374. aria-multiline="true"
  1375. aria-label={placeholder()}
  1376. contenteditable="true"
  1377. autocapitalize={store.mode === "normal" ? "sentences" : "off"}
  1378. autocorrect={store.mode === "normal" ? "on" : "off"}
  1379. spellcheck={store.mode === "normal"}
  1380. inputMode="text"
  1381. // @ts-expect-error
  1382. autocomplete="off"
  1383. onInput={handleInput}
  1384. onPaste={handlePaste}
  1385. onCompositionStart={handleCompositionStart}
  1386. onCompositionEnd={handleCompositionEnd}
  1387. onFocus={handleFocus}
  1388. onBlur={handleBlur}
  1389. onKeyDown={handleKeyDown}
  1390. classList={{
  1391. "select-text": true,
  1392. "w-full pl-3 pr-2 pt-2 text-14-regular text-text-strong focus:outline-none whitespace-pre-wrap": true,
  1393. "[&_[data-type=file]]:text-syntax-property": true,
  1394. "[&_[data-type=agent]]:text-syntax-type": true,
  1395. "font-mono!": store.mode === "shell",
  1396. }}
  1397. style={{ "padding-bottom": space }}
  1398. />
  1399. <div
  1400. class="absolute top-0 inset-x-0 pl-3 pr-2 pt-2 text-14-regular text-text-weak pointer-events-none whitespace-nowrap truncate"
  1401. classList={{ "font-mono!": store.mode === "shell" }}
  1402. style={{ "padding-bottom": space, display: prompt.dirty() ? "none" : undefined }}
  1403. >
  1404. {placeholder()}
  1405. </div>
  1406. </div>
  1407. <div
  1408. aria-hidden="true"
  1409. class="pointer-events-none absolute inset-x-0 bottom-0"
  1410. style={{
  1411. height: space,
  1412. background:
  1413. "linear-gradient(to top, var(--surface-raised-stronger-non-alpha) calc(100% - 20px), transparent)",
  1414. }}
  1415. />
  1416. <div class="pointer-events-none absolute bottom-2 right-2 flex items-center gap-2">
  1417. <input
  1418. ref={fileInputRef}
  1419. type="file"
  1420. multiple
  1421. accept={ACCEPTED_FILE_TYPES.join(",")}
  1422. class="hidden"
  1423. onChange={(e) => {
  1424. const list = e.currentTarget.files
  1425. if (list) void addAttachments(Array.from(list))
  1426. e.currentTarget.value = ""
  1427. }}
  1428. />
  1429. <div class="flex items-center gap-1 pointer-events-auto">
  1430. <Tooltip placement="top" inactive={!working() && blank()} value={tip()}>
  1431. <IconButton
  1432. data-action="prompt-submit"
  1433. type="submit"
  1434. disabled={!working() && blank()}
  1435. tabIndex={store.mode === "normal" ? undefined : -1}
  1436. icon={stopping() ? "stop" : store.mode === "shell" ? "arrow-undo-down" : "arrow-up"}
  1437. variant="primary"
  1438. class="size-8"
  1439. aria-label={stopping() ? language.t("prompt.action.stop") : language.t("prompt.action.send")}
  1440. />
  1441. </Tooltip>
  1442. </div>
  1443. </div>
  1444. <div class="pointer-events-none absolute bottom-2 left-2">
  1445. <div
  1446. aria-hidden={store.mode !== "normal"}
  1447. class="pointer-events-auto"
  1448. style={{
  1449. "pointer-events": buttonsSpring() > 0.5 ? "auto" : "none",
  1450. }}
  1451. >
  1452. <TooltipKeybind
  1453. placement="top"
  1454. title={language.t("prompt.action.attachFile")}
  1455. keybind={command.keybind("file.attach")}
  1456. >
  1457. <Button
  1458. data-action="prompt-attach"
  1459. type="button"
  1460. variant="ghost"
  1461. class="size-8 p-0"
  1462. style={buttons()}
  1463. onClick={pick}
  1464. disabled={store.mode !== "normal"}
  1465. tabIndex={store.mode === "normal" ? undefined : -1}
  1466. aria-label={language.t("prompt.action.attachFile")}
  1467. >
  1468. <Icon name="plus" class="size-4.5" />
  1469. </Button>
  1470. </TooltipKeybind>
  1471. </div>
  1472. </div>
  1473. </div>
  1474. </DockShellForm>
  1475. <Show when={store.mode === "normal" || store.mode === "shell"}>
  1476. <DockTray attach="top">
  1477. <div class="px-1.75 pt-5.5 pb-2 flex items-center gap-2 min-w-0">
  1478. <div class="flex items-center gap-1.5 min-w-0 flex-1 relative">
  1479. <div
  1480. class="h-7 flex items-center gap-1.5 min-w-0 absolute inset-0"
  1481. style={{
  1482. padding: "0 0px 0 8px",
  1483. ...shell(),
  1484. }}
  1485. >
  1486. <Icon name="console" />
  1487. <span class="truncate text-13-medium text-text-base">{language.t("prompt.mode.shell")}</span>
  1488. <div class="flex-1" />
  1489. <Button
  1490. variant="ghost"
  1491. class="text-text-base"
  1492. onClick={() => {
  1493. setStore("mode", "normal")
  1494. }}
  1495. >
  1496. {language.t("common.cancel")}
  1497. </Button>
  1498. </div>
  1499. <div class="flex items-center gap-1.5 min-w-0 flex-1 h-7">
  1500. <Show when={!agentsLoading()}>
  1501. <div
  1502. data-component="prompt-agent-control"
  1503. classList={{ "animate-in fade-in duration-300": agentsShouldFadeIn() }}
  1504. >
  1505. <TooltipKeybind
  1506. placement="top"
  1507. gutter={4}
  1508. title={language.t("command.agent.cycle")}
  1509. keybind={command.keybind("agent.cycle")}
  1510. >
  1511. <Select
  1512. size="normal"
  1513. options={props.controls.agents.options}
  1514. current={props.controls.agents.current}
  1515. onSelect={(value) => {
  1516. props.controls.agents.select(value)
  1517. restoreFocus()
  1518. }}
  1519. class="capitalize max-w-[160px] text-text-base"
  1520. valueClass="truncate text-13-regular text-text-base"
  1521. triggerStyle={control()}
  1522. triggerProps={{ "data-action": "prompt-agent" }}
  1523. variant="ghost"
  1524. />
  1525. </TooltipKeybind>
  1526. </div>
  1527. </Show>
  1528. <Show when={!providersLoading()}>
  1529. <Show when={store.mode !== "shell"}>
  1530. <div
  1531. data-component="prompt-model-control"
  1532. classList={{ "animate-in fade-in duration-300": providersShouldFadeIn() }}
  1533. >
  1534. <Show
  1535. when={props.controls.model.paid}
  1536. fallback={
  1537. <TooltipKeybind
  1538. placement="top"
  1539. gutter={4}
  1540. title={language.t("command.model.choose")}
  1541. keybind={command.keybind("model.choose")}
  1542. >
  1543. <Button
  1544. data-action="prompt-model"
  1545. as="div"
  1546. variant="ghost"
  1547. size="normal"
  1548. class="min-w-0 max-w-[320px] text-13-regular text-text-base group"
  1549. style={control()}
  1550. onClick={() => {
  1551. dialog.show(() => <DialogSelectModelUnpaid model={props.controls.model.selection} />)
  1552. }}
  1553. >
  1554. <Show when={props.controls.model.selection.current()?.provider?.id}>
  1555. <ProviderIcon
  1556. id={props.controls.model.selection.current()?.provider?.id ?? ""}
  1557. class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
  1558. style={{ "will-change": "opacity", transform: "translateZ(0)" }}
  1559. />
  1560. </Show>
  1561. <span class="truncate">
  1562. {props.controls.model.selection.current()?.name ??
  1563. language.t("dialog.model.select.title")}
  1564. </span>
  1565. <Icon name="chevron-down" size="small" class="shrink-0" />
  1566. </Button>
  1567. </TooltipKeybind>
  1568. }
  1569. >
  1570. <TooltipKeybind
  1571. placement="top"
  1572. gutter={4}
  1573. title={language.t("command.model.choose")}
  1574. keybind={command.keybind("model.choose")}
  1575. >
  1576. <ModelSelectorPopover
  1577. model={props.controls.model.selection}
  1578. trigger={(triggerProps) => (
  1579. <Button
  1580. {...triggerProps}
  1581. variant="ghost"
  1582. size="normal"
  1583. style={control()}
  1584. class="min-w-0 max-w-[320px] text-13-regular text-text-base group"
  1585. data-action="prompt-model"
  1586. >
  1587. <Show when={props.controls.model.selection.current()?.provider?.id}>
  1588. <ProviderIcon
  1589. id={props.controls.model.selection.current()?.provider?.id ?? ""}
  1590. class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
  1591. style={{ "will-change": "opacity", transform: "translateZ(0)" }}
  1592. />
  1593. </Show>
  1594. <span class="truncate">
  1595. {props.controls.model.selection.current()?.name ??
  1596. language.t("dialog.model.select.title")}
  1597. </span>
  1598. <Icon name="chevron-down" size="small" class="shrink-0" />
  1599. </Button>
  1600. )}
  1601. onClose={restoreFocus}
  1602. />
  1603. </TooltipKeybind>
  1604. </Show>
  1605. </div>
  1606. <Show when={showVariantControl()}>
  1607. <div
  1608. data-component="prompt-variant-control"
  1609. classList={{ "animate-in fade-in duration-300": providersShouldFadeIn() }}
  1610. >
  1611. <TooltipKeybind
  1612. placement="top"
  1613. gutter={4}
  1614. title={language.t("command.model.variant.cycle")}
  1615. keybind={command.keybind("model.variant.cycle")}
  1616. >
  1617. <Select
  1618. size="normal"
  1619. options={variants()}
  1620. current={props.controls.model.selection.variant.current() ?? "default"}
  1621. label={(x) => (x === "default" ? language.t("common.default") : x)}
  1622. onSelect={(value) => {
  1623. props.controls.model.selection.variant.set(value === "default" ? undefined : value)
  1624. restoreFocus()
  1625. }}
  1626. class="capitalize max-w-[160px] text-text-base"
  1627. valueClass="truncate text-13-regular text-text-base"
  1628. triggerStyle={control()}
  1629. triggerProps={{ "data-action": "prompt-model-variant" }}
  1630. variant="ghost"
  1631. />
  1632. </TooltipKeybind>
  1633. </div>
  1634. </Show>
  1635. </Show>
  1636. </Show>
  1637. </div>
  1638. </div>
  1639. </div>
  1640. </DockTray>
  1641. </Show>
  1642. </div>
  1643. )
  1644. }