prompt-input.tsx 52 KB

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