prompt-input.tsx 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189
  1. import { useFilteredList } from "@opencode-ai/ui/hooks"
  2. import {
  3. createEffect,
  4. on,
  5. Component,
  6. Show,
  7. For,
  8. onMount,
  9. onCleanup,
  10. Switch,
  11. Match,
  12. createMemo,
  13. createSignal,
  14. } from "solid-js"
  15. import { createStore, produce } from "solid-js/store"
  16. import { createFocusSignal } from "@solid-primitives/active-element"
  17. import { useLocal } from "@/context/local"
  18. import { useFile, type FileSelection } from "@/context/file"
  19. import {
  20. ContentPart,
  21. DEFAULT_PROMPT,
  22. isPromptEqual,
  23. Prompt,
  24. usePrompt,
  25. ImageAttachmentPart,
  26. AgentPart,
  27. FileAttachmentPart,
  28. } from "@/context/prompt"
  29. import { useLayout } from "@/context/layout"
  30. import { useSDK } from "@/context/sdk"
  31. import { useNavigate, useParams } from "@solidjs/router"
  32. import { useSync } from "@/context/sync"
  33. import { useComments } from "@/context/comments"
  34. import { FileIcon } from "@opencode-ai/ui/file-icon"
  35. import { Button } from "@opencode-ai/ui/button"
  36. import { Icon } from "@opencode-ai/ui/icon"
  37. import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
  38. import type { IconName } from "@opencode-ai/ui/icons/provider"
  39. import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
  40. import { IconButton } from "@opencode-ai/ui/icon-button"
  41. import { Select } from "@opencode-ai/ui/select"
  42. import { getDirectory, getFilename, getFilenameTruncated } from "@opencode-ai/util/path"
  43. import { useDialog } from "@opencode-ai/ui/context/dialog"
  44. import { ImagePreview } from "@opencode-ai/ui/image-preview"
  45. import { ModelSelectorPopover } from "@/components/dialog-select-model"
  46. import { DialogSelectModelUnpaid } from "@/components/dialog-select-model-unpaid"
  47. import { useProviders } from "@/hooks/use-providers"
  48. import { useCommand } from "@/context/command"
  49. import { Persist, persisted } from "@/utils/persist"
  50. import { Identifier } from "@/utils/id"
  51. import { Worktree as WorktreeState } from "@/utils/worktree"
  52. import { SessionContextUsage } from "@/components/session-context-usage"
  53. import { usePermission } from "@/context/permission"
  54. import { useLanguage } from "@/context/language"
  55. import { useGlobalSync } from "@/context/global-sync"
  56. import { usePlatform } from "@/context/platform"
  57. import { createOpencodeClient, type Message, type Part } from "@opencode-ai/sdk/v2/client"
  58. import { Binary } from "@opencode-ai/util/binary"
  59. import { showToast } from "@opencode-ai/ui/toast"
  60. import { base64Encode } from "@opencode-ai/util/encode"
  61. const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"]
  62. const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"]
  63. type PendingPrompt = {
  64. abort: AbortController
  65. cleanup: VoidFunction
  66. }
  67. const pending = new Map<string, PendingPrompt>()
  68. interface PromptInputProps {
  69. class?: string
  70. ref?: (el: HTMLDivElement) => void
  71. newSessionWorktree?: string
  72. onNewSessionWorktreeReset?: () => void
  73. onSubmit?: () => void
  74. }
  75. const EXAMPLES = [
  76. "prompt.example.1",
  77. "prompt.example.2",
  78. "prompt.example.3",
  79. "prompt.example.4",
  80. "prompt.example.5",
  81. "prompt.example.6",
  82. "prompt.example.7",
  83. "prompt.example.8",
  84. "prompt.example.9",
  85. "prompt.example.10",
  86. "prompt.example.11",
  87. "prompt.example.12",
  88. "prompt.example.13",
  89. "prompt.example.14",
  90. "prompt.example.15",
  91. "prompt.example.16",
  92. "prompt.example.17",
  93. "prompt.example.18",
  94. "prompt.example.19",
  95. "prompt.example.20",
  96. "prompt.example.21",
  97. "prompt.example.22",
  98. "prompt.example.23",
  99. "prompt.example.24",
  100. "prompt.example.25",
  101. ] as const
  102. interface SlashCommand {
  103. id: string
  104. trigger: string
  105. title: string
  106. description?: string
  107. keybind?: string
  108. type: "builtin" | "custom"
  109. source?: "command" | "mcp" | "skill"
  110. }
  111. export const PromptInput: Component<PromptInputProps> = (props) => {
  112. const navigate = useNavigate()
  113. const sdk = useSDK()
  114. const sync = useSync()
  115. const globalSync = useGlobalSync()
  116. const platform = usePlatform()
  117. const local = useLocal()
  118. const files = useFile()
  119. const prompt = usePrompt()
  120. const commentCount = createMemo(() => prompt.context.items().filter((item) => !!item.comment?.trim()).length)
  121. const layout = useLayout()
  122. const comments = useComments()
  123. const params = useParams()
  124. const dialog = useDialog()
  125. const providers = useProviders()
  126. const command = useCommand()
  127. const permission = usePermission()
  128. const language = useLanguage()
  129. let editorRef!: HTMLDivElement
  130. let fileInputRef!: HTMLInputElement
  131. let scrollRef!: HTMLDivElement
  132. let slashPopoverRef!: HTMLDivElement
  133. const mirror = { input: false }
  134. const scrollCursorIntoView = () => {
  135. const container = scrollRef
  136. const selection = window.getSelection()
  137. if (!container || !selection || selection.rangeCount === 0) return
  138. const range = selection.getRangeAt(0)
  139. if (!editorRef.contains(range.startContainer)) return
  140. const rect = range.getBoundingClientRect()
  141. if (!rect.height) return
  142. const containerRect = container.getBoundingClientRect()
  143. const top = rect.top - containerRect.top + container.scrollTop
  144. const bottom = rect.bottom - containerRect.top + container.scrollTop
  145. const padding = 12
  146. if (top < container.scrollTop + padding) {
  147. container.scrollTop = Math.max(0, top - padding)
  148. return
  149. }
  150. if (bottom > container.scrollTop + container.clientHeight - padding) {
  151. container.scrollTop = bottom - container.clientHeight + padding
  152. }
  153. }
  154. const queueScroll = () => {
  155. requestAnimationFrame(scrollCursorIntoView)
  156. }
  157. const sessionKey = createMemo(() => `${params.dir}${params.id ? "/" + params.id : ""}`)
  158. const tabs = createMemo(() => layout.tabs(sessionKey))
  159. const commentInReview = (path: string) => {
  160. const sessionID = params.id
  161. if (!sessionID) return false
  162. const diffs = sync.data.session_diff[sessionID]
  163. if (!diffs) return false
  164. return diffs.some((diff) => diff.file === path)
  165. }
  166. const openComment = (item: { path: string; commentID?: string; commentOrigin?: "review" | "file" }) => {
  167. if (!item.commentID) return
  168. const focus = { file: item.path, id: item.commentID }
  169. comments.setActive(focus)
  170. const wantsReview = item.commentOrigin === "review" || (item.commentOrigin !== "file" && commentInReview(item.path))
  171. if (wantsReview) {
  172. layout.fileTree.open()
  173. layout.fileTree.setTab("changes")
  174. requestAnimationFrame(() => comments.setFocus(focus))
  175. return
  176. }
  177. layout.fileTree.open()
  178. layout.fileTree.setTab("all")
  179. const tab = files.tab(item.path)
  180. tabs().open(tab)
  181. files.load(item.path)
  182. requestAnimationFrame(() => comments.setFocus(focus))
  183. }
  184. const recent = createMemo(() => {
  185. const all = tabs().all()
  186. const active = tabs().active()
  187. const order = active ? [active, ...all.filter((x) => x !== active)] : all
  188. const seen = new Set<string>()
  189. const paths: string[] = []
  190. for (const tab of order) {
  191. const path = files.pathFromTab(tab)
  192. if (!path) continue
  193. if (seen.has(path)) continue
  194. seen.add(path)
  195. paths.push(path)
  196. }
  197. return paths
  198. })
  199. const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined))
  200. const status = createMemo(
  201. () =>
  202. sync.data.session_status[params.id ?? ""] ?? {
  203. type: "idle",
  204. },
  205. )
  206. const working = createMemo(() => status()?.type !== "idle")
  207. const imageAttachments = createMemo(
  208. () => prompt.current().filter((part) => part.type === "image") as ImageAttachmentPart[],
  209. )
  210. const [store, setStore] = createStore<{
  211. popover: "at" | "slash" | null
  212. historyIndex: number
  213. savedPrompt: Prompt | null
  214. placeholder: number
  215. dragging: boolean
  216. mode: "normal" | "shell"
  217. applyingHistory: boolean
  218. }>({
  219. popover: null,
  220. historyIndex: -1,
  221. savedPrompt: null,
  222. placeholder: Math.floor(Math.random() * EXAMPLES.length),
  223. dragging: false,
  224. mode: "normal",
  225. applyingHistory: false,
  226. })
  227. const MAX_HISTORY = 100
  228. const [history, setHistory] = persisted(
  229. Persist.global("prompt-history", ["prompt-history.v1"]),
  230. createStore<{
  231. entries: Prompt[]
  232. }>({
  233. entries: [],
  234. }),
  235. )
  236. const [shellHistory, setShellHistory] = persisted(
  237. Persist.global("prompt-history-shell", ["prompt-history-shell.v1"]),
  238. createStore<{
  239. entries: Prompt[]
  240. }>({
  241. entries: [],
  242. }),
  243. )
  244. const clonePromptParts = (prompt: Prompt): Prompt =>
  245. prompt.map((part) => {
  246. if (part.type === "text") return { ...part }
  247. if (part.type === "image") return { ...part }
  248. if (part.type === "agent") return { ...part }
  249. return {
  250. ...part,
  251. selection: part.selection ? { ...part.selection } : undefined,
  252. }
  253. })
  254. const promptLength = (prompt: Prompt) =>
  255. prompt.reduce((len, part) => len + ("content" in part ? part.content.length : 0), 0)
  256. const applyHistoryPrompt = (p: Prompt, position: "start" | "end") => {
  257. const length = position === "start" ? 0 : promptLength(p)
  258. setStore("applyingHistory", true)
  259. prompt.set(p, length)
  260. requestAnimationFrame(() => {
  261. editorRef.focus()
  262. setCursorPosition(editorRef, length)
  263. setStore("applyingHistory", false)
  264. queueScroll()
  265. })
  266. }
  267. const getCaretState = () => {
  268. const selection = window.getSelection()
  269. const textLength = promptLength(prompt.current())
  270. if (!selection || selection.rangeCount === 0) {
  271. return { collapsed: false, cursorPosition: 0, textLength }
  272. }
  273. const anchorNode = selection.anchorNode
  274. if (!anchorNode || !editorRef.contains(anchorNode)) {
  275. return { collapsed: false, cursorPosition: 0, textLength }
  276. }
  277. return {
  278. collapsed: selection.isCollapsed,
  279. cursorPosition: getCursorPosition(editorRef),
  280. textLength,
  281. }
  282. }
  283. const isFocused = createFocusSignal(() => editorRef)
  284. createEffect(() => {
  285. params.id
  286. if (params.id) return
  287. const interval = setInterval(() => {
  288. setStore("placeholder", (prev) => (prev + 1) % EXAMPLES.length)
  289. }, 6500)
  290. onCleanup(() => clearInterval(interval))
  291. })
  292. const [composing, setComposing] = createSignal(false)
  293. const isImeComposing = (event: KeyboardEvent) => event.isComposing || composing() || event.keyCode === 229
  294. const addImageAttachment = async (file: File) => {
  295. if (!ACCEPTED_FILE_TYPES.includes(file.type)) return
  296. const reader = new FileReader()
  297. reader.onload = () => {
  298. const dataUrl = reader.result as string
  299. const attachment: ImageAttachmentPart = {
  300. type: "image",
  301. id: crypto.randomUUID(),
  302. filename: file.name,
  303. mime: file.type,
  304. dataUrl,
  305. }
  306. const cursorPosition = prompt.cursor() ?? getCursorPosition(editorRef)
  307. prompt.set([...prompt.current(), attachment], cursorPosition)
  308. }
  309. reader.readAsDataURL(file)
  310. }
  311. const removeImageAttachment = (id: string) => {
  312. const current = prompt.current()
  313. const next = current.filter((part) => part.type !== "image" || part.id !== id)
  314. prompt.set(next, prompt.cursor())
  315. }
  316. const handlePaste = async (event: ClipboardEvent) => {
  317. if (!isFocused()) return
  318. const clipboardData = event.clipboardData
  319. if (!clipboardData) return
  320. event.preventDefault()
  321. event.stopPropagation()
  322. const items = Array.from(clipboardData.items)
  323. const fileItems = items.filter((item) => item.kind === "file")
  324. const imageItems = fileItems.filter((item) => ACCEPTED_FILE_TYPES.includes(item.type))
  325. if (imageItems.length > 0) {
  326. for (const item of imageItems) {
  327. const file = item.getAsFile()
  328. if (file) await addImageAttachment(file)
  329. }
  330. return
  331. }
  332. if (fileItems.length > 0) {
  333. showToast({
  334. title: language.t("prompt.toast.pasteUnsupported.title"),
  335. description: language.t("prompt.toast.pasteUnsupported.description"),
  336. })
  337. return
  338. }
  339. const plainText = clipboardData.getData("text/plain") ?? ""
  340. if (!plainText) return
  341. addPart({ type: "text", content: plainText, start: 0, end: 0 })
  342. }
  343. const handleGlobalDragOver = (event: DragEvent) => {
  344. if (dialog.active) return
  345. event.preventDefault()
  346. const hasFiles = event.dataTransfer?.types.includes("Files")
  347. if (hasFiles) {
  348. setStore("dragging", true)
  349. }
  350. }
  351. const handleGlobalDragLeave = (event: DragEvent) => {
  352. if (dialog.active) return
  353. // relatedTarget is null when leaving the document window
  354. if (!event.relatedTarget) {
  355. setStore("dragging", false)
  356. }
  357. }
  358. const handleGlobalDrop = async (event: DragEvent) => {
  359. if (dialog.active) return
  360. event.preventDefault()
  361. setStore("dragging", false)
  362. const dropped = event.dataTransfer?.files
  363. if (!dropped) return
  364. for (const file of Array.from(dropped)) {
  365. if (ACCEPTED_FILE_TYPES.includes(file.type)) {
  366. await addImageAttachment(file)
  367. }
  368. }
  369. }
  370. onMount(() => {
  371. document.addEventListener("dragover", handleGlobalDragOver)
  372. document.addEventListener("dragleave", handleGlobalDragLeave)
  373. document.addEventListener("drop", handleGlobalDrop)
  374. })
  375. onCleanup(() => {
  376. document.removeEventListener("dragover", handleGlobalDragOver)
  377. document.removeEventListener("dragleave", handleGlobalDragLeave)
  378. document.removeEventListener("drop", handleGlobalDrop)
  379. })
  380. createEffect(() => {
  381. if (!isFocused()) setStore("popover", null)
  382. })
  383. // Safety: reset composing state on focus change to prevent stuck state
  384. // This handles edge cases where compositionend event may not fire
  385. createEffect(() => {
  386. if (!isFocused()) setComposing(false)
  387. })
  388. type AtOption =
  389. | { type: "agent"; name: string; display: string }
  390. | { type: "file"; path: string; display: string; recent?: boolean }
  391. const agentList = createMemo(() =>
  392. sync.data.agent
  393. .filter((agent) => !agent.hidden && agent.mode !== "primary")
  394. .map((agent): AtOption => ({ type: "agent", name: agent.name, display: agent.name })),
  395. )
  396. const handleAtSelect = (option: AtOption | undefined) => {
  397. if (!option) return
  398. if (option.type === "agent") {
  399. addPart({ type: "agent", name: option.name, content: "@" + option.name, start: 0, end: 0 })
  400. } else {
  401. addPart({ type: "file", path: option.path, content: "@" + option.path, start: 0, end: 0 })
  402. }
  403. }
  404. const atKey = (x: AtOption | undefined) => {
  405. if (!x) return ""
  406. return x.type === "agent" ? `agent:${x.name}` : `file:${x.path}`
  407. }
  408. const {
  409. flat: atFlat,
  410. active: atActive,
  411. setActive: setAtActive,
  412. onInput: atOnInput,
  413. onKeyDown: atOnKeyDown,
  414. } = useFilteredList<AtOption>({
  415. items: async (query) => {
  416. const agents = agentList()
  417. const open = recent()
  418. const seen = new Set(open)
  419. const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true }))
  420. const paths = await files.searchFilesAndDirectories(query)
  421. const fileOptions: AtOption[] = paths
  422. .filter((path) => !seen.has(path))
  423. .map((path) => ({ type: "file", path, display: path }))
  424. return [...agents, ...pinned, ...fileOptions]
  425. },
  426. key: atKey,
  427. filterKeys: ["display"],
  428. groupBy: (item) => {
  429. if (item.type === "agent") return "agent"
  430. if (item.recent) return "recent"
  431. return "file"
  432. },
  433. sortGroupsBy: (a, b) => {
  434. const rank = (category: string) => {
  435. if (category === "agent") return 0
  436. if (category === "recent") return 1
  437. return 2
  438. }
  439. return rank(a.category) - rank(b.category)
  440. },
  441. onSelect: handleAtSelect,
  442. })
  443. const slashCommands = createMemo<SlashCommand[]>(() => {
  444. const builtin = command.options
  445. .filter((opt) => !opt.disabled && !opt.id.startsWith("suggested.") && opt.slash)
  446. .map((opt) => ({
  447. id: opt.id,
  448. trigger: opt.slash!,
  449. title: opt.title,
  450. description: opt.description,
  451. keybind: opt.keybind,
  452. type: "builtin" as const,
  453. }))
  454. const custom = sync.data.command.map((cmd) => ({
  455. id: `custom.${cmd.name}`,
  456. trigger: cmd.name,
  457. title: cmd.name,
  458. description: cmd.description,
  459. type: "custom" as const,
  460. source: cmd.source,
  461. }))
  462. return [...custom, ...builtin]
  463. })
  464. const handleSlashSelect = (cmd: SlashCommand | undefined) => {
  465. if (!cmd) return
  466. setStore("popover", null)
  467. if (cmd.type === "custom") {
  468. const text = `/${cmd.trigger} `
  469. editorRef.innerHTML = ""
  470. editorRef.textContent = text
  471. prompt.set([{ type: "text", content: text, start: 0, end: text.length }], text.length)
  472. requestAnimationFrame(() => {
  473. editorRef.focus()
  474. const range = document.createRange()
  475. const sel = window.getSelection()
  476. range.selectNodeContents(editorRef)
  477. range.collapse(false)
  478. sel?.removeAllRanges()
  479. sel?.addRange(range)
  480. })
  481. return
  482. }
  483. editorRef.innerHTML = ""
  484. prompt.set([{ type: "text", content: "", start: 0, end: 0 }], 0)
  485. command.trigger(cmd.id, "slash")
  486. }
  487. const {
  488. flat: slashFlat,
  489. active: slashActive,
  490. setActive: setSlashActive,
  491. onInput: slashOnInput,
  492. onKeyDown: slashOnKeyDown,
  493. refetch: slashRefetch,
  494. } = useFilteredList<SlashCommand>({
  495. items: slashCommands,
  496. key: (x) => x?.id,
  497. filterKeys: ["trigger", "title", "description"],
  498. onSelect: handleSlashSelect,
  499. })
  500. const createPill = (part: FileAttachmentPart | AgentPart) => {
  501. const pill = document.createElement("span")
  502. pill.textContent = part.content
  503. pill.setAttribute("data-type", part.type)
  504. if (part.type === "file") pill.setAttribute("data-path", part.path)
  505. if (part.type === "agent") pill.setAttribute("data-name", part.name)
  506. pill.setAttribute("contenteditable", "false")
  507. pill.style.userSelect = "text"
  508. pill.style.cursor = "default"
  509. return pill
  510. }
  511. const isNormalizedEditor = () =>
  512. Array.from(editorRef.childNodes).every((node) => {
  513. if (node.nodeType === Node.TEXT_NODE) {
  514. const text = node.textContent ?? ""
  515. if (!text.includes("\u200B")) return true
  516. if (text !== "\u200B") return false
  517. const prev = node.previousSibling
  518. const next = node.nextSibling
  519. const prevIsBr = prev?.nodeType === Node.ELEMENT_NODE && (prev as HTMLElement).tagName === "BR"
  520. const nextIsBr = next?.nodeType === Node.ELEMENT_NODE && (next as HTMLElement).tagName === "BR"
  521. if (!prevIsBr && !nextIsBr) return false
  522. if (nextIsBr && !prevIsBr && prev) return false
  523. return true
  524. }
  525. if (node.nodeType !== Node.ELEMENT_NODE) return false
  526. const el = node as HTMLElement
  527. if (el.dataset.type === "file") return true
  528. if (el.dataset.type === "agent") return true
  529. return el.tagName === "BR"
  530. })
  531. const renderEditor = (parts: Prompt) => {
  532. editorRef.innerHTML = ""
  533. for (const part of parts) {
  534. if (part.type === "text") {
  535. editorRef.appendChild(createTextFragment(part.content))
  536. continue
  537. }
  538. if (part.type === "file" || part.type === "agent") {
  539. editorRef.appendChild(createPill(part))
  540. }
  541. }
  542. }
  543. createEffect(
  544. on(
  545. () => sync.data.command,
  546. () => slashRefetch(),
  547. { defer: true },
  548. ),
  549. )
  550. // Auto-scroll active command into view when navigating with keyboard
  551. createEffect(() => {
  552. const activeId = slashActive()
  553. if (!activeId || !slashPopoverRef) return
  554. requestAnimationFrame(() => {
  555. const element = slashPopoverRef.querySelector(`[data-slash-id="${activeId}"]`)
  556. element?.scrollIntoView({ block: "nearest", behavior: "smooth" })
  557. })
  558. })
  559. const selectPopoverActive = () => {
  560. if (store.popover === "at") {
  561. const items = atFlat()
  562. if (items.length === 0) return
  563. const active = atActive()
  564. const item = items.find((entry) => atKey(entry) === active) ?? items[0]
  565. handleAtSelect(item)
  566. return
  567. }
  568. if (store.popover === "slash") {
  569. const items = slashFlat()
  570. if (items.length === 0) return
  571. const active = slashActive()
  572. const item = items.find((entry) => entry.id === active) ?? items[0]
  573. handleSlashSelect(item)
  574. }
  575. }
  576. createEffect(
  577. on(
  578. () => prompt.current(),
  579. (currentParts) => {
  580. const inputParts = currentParts.filter((part) => part.type !== "image") as Prompt
  581. if (mirror.input) {
  582. mirror.input = false
  583. if (isNormalizedEditor()) return
  584. const selection = window.getSelection()
  585. let cursorPosition: number | null = null
  586. if (selection && selection.rangeCount > 0 && editorRef.contains(selection.anchorNode)) {
  587. cursorPosition = getCursorPosition(editorRef)
  588. }
  589. renderEditor(inputParts)
  590. if (cursorPosition !== null) {
  591. setCursorPosition(editorRef, cursorPosition)
  592. }
  593. return
  594. }
  595. const domParts = parseFromDOM()
  596. if (isNormalizedEditor() && isPromptEqual(inputParts, domParts)) return
  597. const selection = window.getSelection()
  598. let cursorPosition: number | null = null
  599. if (selection && selection.rangeCount > 0 && editorRef.contains(selection.anchorNode)) {
  600. cursorPosition = getCursorPosition(editorRef)
  601. }
  602. renderEditor(inputParts)
  603. if (cursorPosition !== null) {
  604. setCursorPosition(editorRef, cursorPosition)
  605. }
  606. },
  607. ),
  608. )
  609. const parseFromDOM = (): Prompt => {
  610. const parts: Prompt = []
  611. let position = 0
  612. let buffer = ""
  613. const flushText = () => {
  614. const content = buffer.replace(/\r\n?/g, "\n").replace(/\u200B/g, "")
  615. buffer = ""
  616. if (!content) return
  617. parts.push({ type: "text", content, start: position, end: position + content.length })
  618. position += content.length
  619. }
  620. const pushFile = (file: HTMLElement) => {
  621. const content = file.textContent ?? ""
  622. parts.push({
  623. type: "file",
  624. path: file.dataset.path!,
  625. content,
  626. start: position,
  627. end: position + content.length,
  628. })
  629. position += content.length
  630. }
  631. const pushAgent = (agent: HTMLElement) => {
  632. const content = agent.textContent ?? ""
  633. parts.push({
  634. type: "agent",
  635. name: agent.dataset.name!,
  636. content,
  637. start: position,
  638. end: position + content.length,
  639. })
  640. position += content.length
  641. }
  642. const visit = (node: Node) => {
  643. if (node.nodeType === Node.TEXT_NODE) {
  644. buffer += node.textContent ?? ""
  645. return
  646. }
  647. if (node.nodeType !== Node.ELEMENT_NODE) return
  648. const el = node as HTMLElement
  649. if (el.dataset.type === "file") {
  650. flushText()
  651. pushFile(el)
  652. return
  653. }
  654. if (el.dataset.type === "agent") {
  655. flushText()
  656. pushAgent(el)
  657. return
  658. }
  659. if (el.tagName === "BR") {
  660. buffer += "\n"
  661. return
  662. }
  663. for (const child of Array.from(el.childNodes)) {
  664. visit(child)
  665. }
  666. }
  667. const children = Array.from(editorRef.childNodes)
  668. children.forEach((child, index) => {
  669. const isBlock = child.nodeType === Node.ELEMENT_NODE && ["DIV", "P"].includes((child as HTMLElement).tagName)
  670. visit(child)
  671. if (isBlock && index < children.length - 1) {
  672. buffer += "\n"
  673. }
  674. })
  675. flushText()
  676. if (parts.length === 0) parts.push(...DEFAULT_PROMPT)
  677. return parts
  678. }
  679. const handleInput = () => {
  680. const rawParts = parseFromDOM()
  681. const images = imageAttachments()
  682. const cursorPosition = getCursorPosition(editorRef)
  683. const rawText = rawParts.map((p) => ("content" in p ? p.content : "")).join("")
  684. const trimmed = rawText.replace(/\u200B/g, "").trim()
  685. const hasNonText = rawParts.some((part) => part.type !== "text")
  686. const shouldReset = trimmed.length === 0 && !hasNonText && images.length === 0
  687. if (shouldReset) {
  688. setStore("popover", null)
  689. if (store.historyIndex >= 0 && !store.applyingHistory) {
  690. setStore("historyIndex", -1)
  691. setStore("savedPrompt", null)
  692. }
  693. if (prompt.dirty()) {
  694. mirror.input = true
  695. prompt.set(DEFAULT_PROMPT, 0)
  696. }
  697. queueScroll()
  698. return
  699. }
  700. const shellMode = store.mode === "shell"
  701. if (!shellMode) {
  702. const atMatch = rawText.substring(0, cursorPosition).match(/@(\S*)$/)
  703. const slashMatch = rawText.match(/^\/(\S*)$/)
  704. if (atMatch) {
  705. atOnInput(atMatch[1])
  706. setStore("popover", "at")
  707. } else if (slashMatch) {
  708. slashOnInput(slashMatch[1])
  709. setStore("popover", "slash")
  710. } else {
  711. setStore("popover", null)
  712. }
  713. } else {
  714. setStore("popover", null)
  715. }
  716. if (store.historyIndex >= 0 && !store.applyingHistory) {
  717. setStore("historyIndex", -1)
  718. setStore("savedPrompt", null)
  719. }
  720. mirror.input = true
  721. prompt.set([...rawParts, ...images], cursorPosition)
  722. queueScroll()
  723. }
  724. const setRangeEdge = (range: Range, edge: "start" | "end", offset: number) => {
  725. let remaining = offset
  726. const nodes = Array.from(editorRef.childNodes)
  727. for (const node of nodes) {
  728. const length = getNodeLength(node)
  729. const isText = node.nodeType === Node.TEXT_NODE
  730. const isPill =
  731. node.nodeType === Node.ELEMENT_NODE &&
  732. ((node as HTMLElement).dataset.type === "file" || (node as HTMLElement).dataset.type === "agent")
  733. const isBreak = node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR"
  734. if (isText && remaining <= length) {
  735. if (edge === "start") range.setStart(node, remaining)
  736. if (edge === "end") range.setEnd(node, remaining)
  737. return
  738. }
  739. if ((isPill || isBreak) && remaining <= length) {
  740. if (edge === "start" && remaining === 0) range.setStartBefore(node)
  741. if (edge === "start" && remaining > 0) range.setStartAfter(node)
  742. if (edge === "end" && remaining === 0) range.setEndBefore(node)
  743. if (edge === "end" && remaining > 0) range.setEndAfter(node)
  744. return
  745. }
  746. remaining -= length
  747. }
  748. }
  749. const addPart = (part: ContentPart) => {
  750. const selection = window.getSelection()
  751. if (!selection || selection.rangeCount === 0) return
  752. const cursorPosition = getCursorPosition(editorRef)
  753. const currentPrompt = prompt.current()
  754. const rawText = currentPrompt.map((p) => ("content" in p ? p.content : "")).join("")
  755. const textBeforeCursor = rawText.substring(0, cursorPosition)
  756. const atMatch = textBeforeCursor.match(/@(\S*)$/)
  757. if (part.type === "file" || part.type === "agent") {
  758. const pill = createPill(part)
  759. const gap = document.createTextNode(" ")
  760. const range = selection.getRangeAt(0)
  761. if (atMatch) {
  762. const start = atMatch.index ?? cursorPosition - atMatch[0].length
  763. setRangeEdge(range, "start", start)
  764. setRangeEdge(range, "end", cursorPosition)
  765. }
  766. range.deleteContents()
  767. range.insertNode(gap)
  768. range.insertNode(pill)
  769. range.setStartAfter(gap)
  770. range.collapse(true)
  771. selection.removeAllRanges()
  772. selection.addRange(range)
  773. } else if (part.type === "text") {
  774. const range = selection.getRangeAt(0)
  775. const fragment = createTextFragment(part.content)
  776. const last = fragment.lastChild
  777. range.deleteContents()
  778. range.insertNode(fragment)
  779. if (last) {
  780. if (last.nodeType === Node.TEXT_NODE) {
  781. const text = last.textContent ?? ""
  782. if (text === "\u200B") {
  783. range.setStart(last, 0)
  784. }
  785. if (text !== "\u200B") {
  786. range.setStart(last, text.length)
  787. }
  788. }
  789. if (last.nodeType !== Node.TEXT_NODE) {
  790. range.setStartAfter(last)
  791. }
  792. }
  793. range.collapse(true)
  794. selection.removeAllRanges()
  795. selection.addRange(range)
  796. }
  797. handleInput()
  798. setStore("popover", null)
  799. }
  800. const abort = async () => {
  801. const sessionID = params.id
  802. if (!sessionID) return Promise.resolve()
  803. const queued = pending.get(sessionID)
  804. if (queued) {
  805. queued.abort.abort()
  806. queued.cleanup()
  807. pending.delete(sessionID)
  808. return Promise.resolve()
  809. }
  810. return sdk.client.session
  811. .abort({
  812. sessionID,
  813. })
  814. .catch(() => {})
  815. }
  816. const addToHistory = (prompt: Prompt, mode: "normal" | "shell") => {
  817. const text = prompt
  818. .map((p) => ("content" in p ? p.content : ""))
  819. .join("")
  820. .trim()
  821. const hasImages = prompt.some((part) => part.type === "image")
  822. if (!text && !hasImages) return
  823. const entry = clonePromptParts(prompt)
  824. const currentHistory = mode === "shell" ? shellHistory : history
  825. const setCurrentHistory = mode === "shell" ? setShellHistory : setHistory
  826. const lastEntry = currentHistory.entries[0]
  827. if (lastEntry && isPromptEqual(lastEntry, entry)) return
  828. setCurrentHistory("entries", (entries) => [entry, ...entries].slice(0, MAX_HISTORY))
  829. }
  830. const navigateHistory = (direction: "up" | "down") => {
  831. const entries = store.mode === "shell" ? shellHistory.entries : history.entries
  832. const current = store.historyIndex
  833. if (direction === "up") {
  834. if (entries.length === 0) return false
  835. if (current === -1) {
  836. setStore("savedPrompt", clonePromptParts(prompt.current()))
  837. setStore("historyIndex", 0)
  838. applyHistoryPrompt(entries[0], "start")
  839. return true
  840. }
  841. if (current < entries.length - 1) {
  842. const next = current + 1
  843. setStore("historyIndex", next)
  844. applyHistoryPrompt(entries[next], "start")
  845. return true
  846. }
  847. return false
  848. }
  849. if (current > 0) {
  850. const next = current - 1
  851. setStore("historyIndex", next)
  852. applyHistoryPrompt(entries[next], "end")
  853. return true
  854. }
  855. if (current === 0) {
  856. setStore("historyIndex", -1)
  857. const saved = store.savedPrompt
  858. if (saved) {
  859. applyHistoryPrompt(saved, "end")
  860. setStore("savedPrompt", null)
  861. return true
  862. }
  863. applyHistoryPrompt(DEFAULT_PROMPT, "end")
  864. return true
  865. }
  866. return false
  867. }
  868. const handleKeyDown = (event: KeyboardEvent) => {
  869. if (event.key === "Backspace") {
  870. const selection = window.getSelection()
  871. if (selection && selection.isCollapsed) {
  872. const node = selection.anchorNode
  873. const offset = selection.anchorOffset
  874. if (node && node.nodeType === Node.TEXT_NODE) {
  875. const text = node.textContent ?? ""
  876. if (/^\u200B+$/.test(text) && offset > 0) {
  877. const range = document.createRange()
  878. range.setStart(node, 0)
  879. range.collapse(true)
  880. selection.removeAllRanges()
  881. selection.addRange(range)
  882. }
  883. }
  884. }
  885. }
  886. if (event.key === "!" && store.mode === "normal") {
  887. const cursorPosition = getCursorPosition(editorRef)
  888. if (cursorPosition === 0) {
  889. setStore("mode", "shell")
  890. setStore("popover", null)
  891. event.preventDefault()
  892. return
  893. }
  894. }
  895. if (store.mode === "shell") {
  896. const { collapsed, cursorPosition, textLength } = getCaretState()
  897. if (event.key === "Escape") {
  898. setStore("mode", "normal")
  899. event.preventDefault()
  900. return
  901. }
  902. if (event.key === "Backspace" && collapsed && cursorPosition === 0 && textLength === 0) {
  903. setStore("mode", "normal")
  904. event.preventDefault()
  905. return
  906. }
  907. }
  908. // Handle Shift+Enter BEFORE IME check - Shift+Enter is never used for IME input
  909. // and should always insert a newline regardless of composition state
  910. if (event.key === "Enter" && event.shiftKey) {
  911. addPart({ type: "text", content: "\n", start: 0, end: 0 })
  912. event.preventDefault()
  913. return
  914. }
  915. if (event.key === "Enter" && isImeComposing(event)) {
  916. return
  917. }
  918. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  919. if (store.popover) {
  920. if (event.key === "Tab") {
  921. selectPopoverActive()
  922. event.preventDefault()
  923. return
  924. }
  925. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  926. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  927. if (nav || ctrlNav) {
  928. if (store.popover === "at") {
  929. atOnKeyDown(event)
  930. event.preventDefault()
  931. return
  932. }
  933. if (store.popover === "slash") {
  934. slashOnKeyDown(event)
  935. }
  936. event.preventDefault()
  937. return
  938. }
  939. }
  940. if (ctrl && event.code === "KeyG") {
  941. if (store.popover) {
  942. setStore("popover", null)
  943. event.preventDefault()
  944. return
  945. }
  946. if (working()) {
  947. abort()
  948. event.preventDefault()
  949. }
  950. return
  951. }
  952. if (event.key === "ArrowUp" || event.key === "ArrowDown") {
  953. if (event.altKey || event.ctrlKey || event.metaKey) return
  954. const { collapsed } = getCaretState()
  955. if (!collapsed) return
  956. const cursorPosition = getCursorPosition(editorRef)
  957. const textLength = promptLength(prompt.current())
  958. const textContent = prompt
  959. .current()
  960. .map((part) => ("content" in part ? part.content : ""))
  961. .join("")
  962. const isEmpty = textContent.trim() === "" || textLength <= 1
  963. const hasNewlines = textContent.includes("\n")
  964. const inHistory = store.historyIndex >= 0
  965. const atStart = cursorPosition <= (isEmpty ? 1 : 0)
  966. const atEnd = cursorPosition >= (isEmpty ? textLength - 1 : textLength)
  967. const allowUp = isEmpty || atStart || (!hasNewlines && !inHistory) || (inHistory && atEnd)
  968. const allowDown = isEmpty || atEnd || (!hasNewlines && !inHistory) || (inHistory && atStart)
  969. if (event.key === "ArrowUp") {
  970. if (!allowUp) return
  971. if (navigateHistory("up")) {
  972. event.preventDefault()
  973. }
  974. return
  975. }
  976. if (!allowDown) return
  977. if (navigateHistory("down")) {
  978. event.preventDefault()
  979. }
  980. return
  981. }
  982. // Note: Shift+Enter is handled earlier, before IME check
  983. if (event.key === "Enter" && !event.shiftKey) {
  984. handleSubmit(event)
  985. }
  986. if (event.key === "Escape") {
  987. if (store.popover) {
  988. setStore("popover", null)
  989. } else if (working()) {
  990. abort()
  991. }
  992. }
  993. }
  994. const handleSubmit = async (event: Event) => {
  995. event.preventDefault()
  996. const currentPrompt = prompt.current()
  997. const text = currentPrompt.map((part) => ("content" in part ? part.content : "")).join("")
  998. const images = imageAttachments().slice()
  999. const mode = store.mode
  1000. if (text.trim().length === 0 && images.length === 0 && commentCount() === 0) {
  1001. if (working()) abort()
  1002. return
  1003. }
  1004. const currentModel = local.model.current()
  1005. const currentAgent = local.agent.current()
  1006. if (!currentModel || !currentAgent) {
  1007. showToast({
  1008. title: language.t("prompt.toast.modelAgentRequired.title"),
  1009. description: language.t("prompt.toast.modelAgentRequired.description"),
  1010. })
  1011. return
  1012. }
  1013. const errorMessage = (err: unknown) => {
  1014. if (err && typeof err === "object" && "data" in err) {
  1015. const data = (err as { data?: { message?: string } }).data
  1016. if (data?.message) return data.message
  1017. }
  1018. if (err instanceof Error) return err.message
  1019. return language.t("common.requestFailed")
  1020. }
  1021. addToHistory(currentPrompt, mode)
  1022. setStore("historyIndex", -1)
  1023. setStore("savedPrompt", null)
  1024. const projectDirectory = sdk.directory
  1025. const isNewSession = !params.id
  1026. const worktreeSelection = props.newSessionWorktree ?? "main"
  1027. let sessionDirectory = projectDirectory
  1028. let client = sdk.client
  1029. if (isNewSession) {
  1030. if (worktreeSelection === "create") {
  1031. const createdWorktree = await client.worktree
  1032. .create({ directory: projectDirectory })
  1033. .then((x) => x.data)
  1034. .catch((err) => {
  1035. showToast({
  1036. title: language.t("prompt.toast.worktreeCreateFailed.title"),
  1037. description: errorMessage(err),
  1038. })
  1039. return undefined
  1040. })
  1041. if (!createdWorktree?.directory) {
  1042. showToast({
  1043. title: language.t("prompt.toast.worktreeCreateFailed.title"),
  1044. description: language.t("common.requestFailed"),
  1045. })
  1046. return
  1047. }
  1048. WorktreeState.pending(createdWorktree.directory)
  1049. sessionDirectory = createdWorktree.directory
  1050. }
  1051. if (worktreeSelection !== "main" && worktreeSelection !== "create") {
  1052. sessionDirectory = worktreeSelection
  1053. }
  1054. if (sessionDirectory !== projectDirectory) {
  1055. client = createOpencodeClient({
  1056. baseUrl: sdk.url,
  1057. fetch: platform.fetch,
  1058. directory: sessionDirectory,
  1059. throwOnError: true,
  1060. })
  1061. globalSync.child(sessionDirectory)
  1062. }
  1063. props.onNewSessionWorktreeReset?.()
  1064. }
  1065. let session = info()
  1066. if (!session && isNewSession) {
  1067. session = await client.session
  1068. .create()
  1069. .then((x) => x.data ?? undefined)
  1070. .catch((err) => {
  1071. showToast({
  1072. title: language.t("prompt.toast.sessionCreateFailed.title"),
  1073. description: errorMessage(err),
  1074. })
  1075. return undefined
  1076. })
  1077. if (session) navigate(`/${base64Encode(sessionDirectory)}/session/${session.id}`)
  1078. }
  1079. if (!session) return
  1080. props.onSubmit?.()
  1081. const model = {
  1082. modelID: currentModel.id,
  1083. providerID: currentModel.provider.id,
  1084. }
  1085. const agent = currentAgent.name
  1086. const variant = local.model.variant.current()
  1087. const clearInput = () => {
  1088. prompt.reset()
  1089. setStore("mode", "normal")
  1090. setStore("popover", null)
  1091. }
  1092. const restoreInput = () => {
  1093. prompt.set(currentPrompt, promptLength(currentPrompt))
  1094. setStore("mode", mode)
  1095. setStore("popover", null)
  1096. requestAnimationFrame(() => {
  1097. editorRef.focus()
  1098. setCursorPosition(editorRef, promptLength(currentPrompt))
  1099. queueScroll()
  1100. })
  1101. }
  1102. if (mode === "shell") {
  1103. clearInput()
  1104. client.session
  1105. .shell({
  1106. sessionID: session.id,
  1107. agent,
  1108. model,
  1109. command: text,
  1110. })
  1111. .catch((err) => {
  1112. showToast({
  1113. title: language.t("prompt.toast.shellSendFailed.title"),
  1114. description: errorMessage(err),
  1115. })
  1116. restoreInput()
  1117. })
  1118. return
  1119. }
  1120. if (text.startsWith("/")) {
  1121. const [cmdName, ...args] = text.split(" ")
  1122. const commandName = cmdName.slice(1)
  1123. const customCommand = sync.data.command.find((c) => c.name === commandName)
  1124. if (customCommand) {
  1125. clearInput()
  1126. client.session
  1127. .command({
  1128. sessionID: session.id,
  1129. command: commandName,
  1130. arguments: args.join(" "),
  1131. agent,
  1132. model: `${model.providerID}/${model.modelID}`,
  1133. variant,
  1134. parts: images.map((attachment) => ({
  1135. id: Identifier.ascending("part"),
  1136. type: "file" as const,
  1137. mime: attachment.mime,
  1138. url: attachment.dataUrl,
  1139. filename: attachment.filename,
  1140. })),
  1141. })
  1142. .catch((err) => {
  1143. showToast({
  1144. title: language.t("prompt.toast.commandSendFailed.title"),
  1145. description: errorMessage(err),
  1146. })
  1147. restoreInput()
  1148. })
  1149. return
  1150. }
  1151. }
  1152. const toAbsolutePath = (path: string) =>
  1153. path.startsWith("/") ? path : (sessionDirectory + "/" + path).replace("//", "/")
  1154. const fileAttachments = currentPrompt.filter((part) => part.type === "file") as FileAttachmentPart[]
  1155. const agentAttachments = currentPrompt.filter((part) => part.type === "agent") as AgentPart[]
  1156. const fileAttachmentParts = fileAttachments.map((attachment) => {
  1157. const absolute = toAbsolutePath(attachment.path)
  1158. const query = attachment.selection
  1159. ? `?start=${attachment.selection.startLine}&end=${attachment.selection.endLine}`
  1160. : ""
  1161. return {
  1162. id: Identifier.ascending("part"),
  1163. type: "file" as const,
  1164. mime: "text/plain",
  1165. url: `file://${absolute}${query}`,
  1166. filename: getFilename(attachment.path),
  1167. source: {
  1168. type: "file" as const,
  1169. text: {
  1170. value: attachment.content,
  1171. start: attachment.start,
  1172. end: attachment.end,
  1173. },
  1174. path: absolute,
  1175. },
  1176. }
  1177. })
  1178. const agentAttachmentParts = agentAttachments.map((attachment) => ({
  1179. id: Identifier.ascending("part"),
  1180. type: "agent" as const,
  1181. name: attachment.name,
  1182. source: {
  1183. value: attachment.content,
  1184. start: attachment.start,
  1185. end: attachment.end,
  1186. },
  1187. }))
  1188. const usedUrls = new Set(fileAttachmentParts.map((part) => part.url))
  1189. const context = prompt.context.items().slice()
  1190. const commentItems = context.filter((item) => item.type === "file" && !!item.comment?.trim())
  1191. const contextParts: Array<
  1192. | {
  1193. id: string
  1194. type: "text"
  1195. text: string
  1196. synthetic?: boolean
  1197. }
  1198. | {
  1199. id: string
  1200. type: "file"
  1201. mime: string
  1202. url: string
  1203. filename?: string
  1204. }
  1205. > = []
  1206. const commentNote = (path: string, selection: FileSelection | undefined, comment: string) => {
  1207. const start = selection ? Math.min(selection.startLine, selection.endLine) : undefined
  1208. const end = selection ? Math.max(selection.startLine, selection.endLine) : undefined
  1209. const range =
  1210. start === undefined || end === undefined
  1211. ? "this file"
  1212. : start === end
  1213. ? `line ${start}`
  1214. : `lines ${start} through ${end}`
  1215. return `The user made the following comment regarding ${range} of ${path}: ${comment}`
  1216. }
  1217. const addContextFile = (input: { path: string; selection?: FileSelection; comment?: string }) => {
  1218. const absolute = toAbsolutePath(input.path)
  1219. const query = input.selection ? `?start=${input.selection.startLine}&end=${input.selection.endLine}` : ""
  1220. const url = `file://${absolute}${query}`
  1221. const comment = input.comment?.trim()
  1222. if (!comment && usedUrls.has(url)) return
  1223. usedUrls.add(url)
  1224. if (comment) {
  1225. contextParts.push({
  1226. id: Identifier.ascending("part"),
  1227. type: "text",
  1228. text: commentNote(input.path, input.selection, comment),
  1229. synthetic: true,
  1230. })
  1231. }
  1232. contextParts.push({
  1233. id: Identifier.ascending("part"),
  1234. type: "file",
  1235. mime: "text/plain",
  1236. url,
  1237. filename: getFilename(input.path),
  1238. })
  1239. }
  1240. for (const item of context) {
  1241. if (item.type !== "file") continue
  1242. addContextFile({ path: item.path, selection: item.selection, comment: item.comment })
  1243. }
  1244. const imageAttachmentParts = images.map((attachment) => ({
  1245. id: Identifier.ascending("part"),
  1246. type: "file" as const,
  1247. mime: attachment.mime,
  1248. url: attachment.dataUrl,
  1249. filename: attachment.filename,
  1250. }))
  1251. const messageID = Identifier.ascending("message")
  1252. const textPart = {
  1253. id: Identifier.ascending("part"),
  1254. type: "text" as const,
  1255. text,
  1256. }
  1257. const requestParts = [
  1258. textPart,
  1259. ...fileAttachmentParts,
  1260. ...contextParts,
  1261. ...agentAttachmentParts,
  1262. ...imageAttachmentParts,
  1263. ]
  1264. const optimisticParts = requestParts.map((part) => ({
  1265. ...part,
  1266. sessionID: session.id,
  1267. messageID,
  1268. })) as unknown as Part[]
  1269. const optimisticMessage: Message = {
  1270. id: messageID,
  1271. sessionID: session.id,
  1272. role: "user",
  1273. time: { created: Date.now() },
  1274. agent,
  1275. model,
  1276. }
  1277. const addOptimisticMessage = () => {
  1278. if (sessionDirectory === projectDirectory) {
  1279. sync.set(
  1280. produce((draft) => {
  1281. const messages = draft.message[session.id]
  1282. if (!messages) {
  1283. draft.message[session.id] = [optimisticMessage]
  1284. } else {
  1285. const result = Binary.search(messages, messageID, (m) => m.id)
  1286. messages.splice(result.index, 0, optimisticMessage)
  1287. }
  1288. draft.part[messageID] = optimisticParts
  1289. .filter((p) => !!p?.id)
  1290. .slice()
  1291. .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
  1292. }),
  1293. )
  1294. return
  1295. }
  1296. globalSync.child(sessionDirectory)[1](
  1297. produce((draft) => {
  1298. const messages = draft.message[session.id]
  1299. if (!messages) {
  1300. draft.message[session.id] = [optimisticMessage]
  1301. } else {
  1302. const result = Binary.search(messages, messageID, (m) => m.id)
  1303. messages.splice(result.index, 0, optimisticMessage)
  1304. }
  1305. draft.part[messageID] = optimisticParts
  1306. .filter((p) => !!p?.id)
  1307. .slice()
  1308. .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
  1309. }),
  1310. )
  1311. }
  1312. const removeOptimisticMessage = () => {
  1313. if (sessionDirectory === projectDirectory) {
  1314. sync.set(
  1315. produce((draft) => {
  1316. const messages = draft.message[session.id]
  1317. if (messages) {
  1318. const result = Binary.search(messages, messageID, (m) => m.id)
  1319. if (result.found) messages.splice(result.index, 1)
  1320. }
  1321. delete draft.part[messageID]
  1322. }),
  1323. )
  1324. return
  1325. }
  1326. globalSync.child(sessionDirectory)[1](
  1327. produce((draft) => {
  1328. const messages = draft.message[session.id]
  1329. if (messages) {
  1330. const result = Binary.search(messages, messageID, (m) => m.id)
  1331. if (result.found) messages.splice(result.index, 1)
  1332. }
  1333. delete draft.part[messageID]
  1334. }),
  1335. )
  1336. }
  1337. for (const item of commentItems) {
  1338. prompt.context.remove(item.key)
  1339. }
  1340. clearInput()
  1341. addOptimisticMessage()
  1342. const waitForWorktree = async () => {
  1343. const worktree = WorktreeState.get(sessionDirectory)
  1344. if (!worktree || worktree.status !== "pending") return true
  1345. if (sessionDirectory === projectDirectory) {
  1346. sync.set("session_status", session.id, { type: "busy" })
  1347. }
  1348. const controller = new AbortController()
  1349. const cleanup = () => {
  1350. if (sessionDirectory === projectDirectory) {
  1351. sync.set("session_status", session.id, { type: "idle" })
  1352. }
  1353. removeOptimisticMessage()
  1354. for (const item of commentItems) {
  1355. prompt.context.add({
  1356. type: "file",
  1357. path: item.path,
  1358. selection: item.selection,
  1359. comment: item.comment,
  1360. commentID: item.commentID,
  1361. commentOrigin: item.commentOrigin,
  1362. preview: item.preview,
  1363. })
  1364. }
  1365. restoreInput()
  1366. }
  1367. pending.set(session.id, { abort: controller, cleanup })
  1368. const abort = new Promise<Awaited<ReturnType<typeof WorktreeState.wait>>>((resolve) => {
  1369. if (controller.signal.aborted) {
  1370. resolve({ status: "failed", message: "aborted" })
  1371. return
  1372. }
  1373. controller.signal.addEventListener(
  1374. "abort",
  1375. () => {
  1376. resolve({ status: "failed", message: "aborted" })
  1377. },
  1378. { once: true },
  1379. )
  1380. })
  1381. const timeoutMs = 5 * 60 * 1000
  1382. const timer = { id: undefined as number | undefined }
  1383. const timeout = new Promise<Awaited<ReturnType<typeof WorktreeState.wait>>>((resolve) => {
  1384. timer.id = window.setTimeout(() => {
  1385. resolve({ status: "failed", message: language.t("workspace.error.stillPreparing") })
  1386. }, timeoutMs)
  1387. })
  1388. const result = await Promise.race([WorktreeState.wait(sessionDirectory), abort, timeout]).finally(() => {
  1389. if (timer.id === undefined) return
  1390. clearTimeout(timer.id)
  1391. })
  1392. pending.delete(session.id)
  1393. if (controller.signal.aborted) return false
  1394. if (result.status === "failed") throw new Error(result.message)
  1395. return true
  1396. }
  1397. const send = async () => {
  1398. const ok = await waitForWorktree()
  1399. if (!ok) return
  1400. await client.session.prompt({
  1401. sessionID: session.id,
  1402. agent,
  1403. model,
  1404. messageID,
  1405. parts: requestParts,
  1406. variant,
  1407. })
  1408. }
  1409. void send().catch((err) => {
  1410. pending.delete(session.id)
  1411. if (sessionDirectory === projectDirectory) {
  1412. sync.set("session_status", session.id, { type: "idle" })
  1413. }
  1414. showToast({
  1415. title: language.t("prompt.toast.promptSendFailed.title"),
  1416. description: errorMessage(err),
  1417. })
  1418. removeOptimisticMessage()
  1419. for (const item of commentItems) {
  1420. prompt.context.add({
  1421. type: "file",
  1422. path: item.path,
  1423. selection: item.selection,
  1424. comment: item.comment,
  1425. commentID: item.commentID,
  1426. commentOrigin: item.commentOrigin,
  1427. preview: item.preview,
  1428. })
  1429. }
  1430. restoreInput()
  1431. })
  1432. }
  1433. return (
  1434. <div class="relative size-full _max-h-[320px] flex flex-col gap-3">
  1435. <Show when={store.popover}>
  1436. <div
  1437. ref={(el) => {
  1438. if (store.popover === "slash") slashPopoverRef = el
  1439. }}
  1440. class="absolute inset-x-0 -top-3 -translate-y-full origin-bottom-left max-h-80 min-h-10
  1441. overflow-auto no-scrollbar flex flex-col p-2 rounded-md
  1442. border border-border-base bg-surface-raised-stronger-non-alpha shadow-md"
  1443. onMouseDown={(e) => e.preventDefault()}
  1444. >
  1445. <Switch>
  1446. <Match when={store.popover === "at"}>
  1447. <Show
  1448. when={atFlat().length > 0}
  1449. fallback={<div class="text-text-weak px-2 py-1">{language.t("prompt.popover.emptyResults")}</div>}
  1450. >
  1451. <For each={atFlat().slice(0, 10)}>
  1452. {(item) => (
  1453. <button
  1454. classList={{
  1455. "w-full flex items-center gap-x-2 rounded-md px-2 py-0.5": true,
  1456. "bg-surface-raised-base-hover": atActive() === atKey(item),
  1457. }}
  1458. onClick={() => handleAtSelect(item)}
  1459. onMouseEnter={() => setAtActive(atKey(item))}
  1460. >
  1461. <Show
  1462. when={item.type === "agent"}
  1463. fallback={
  1464. <>
  1465. <FileIcon
  1466. node={{ path: (item as { type: "file"; path: string }).path, type: "file" }}
  1467. class="shrink-0 size-4"
  1468. />
  1469. <div class="flex items-center text-14-regular min-w-0">
  1470. <span class="text-text-weak whitespace-nowrap truncate min-w-0">
  1471. {(() => {
  1472. const path = (item as { type: "file"; path: string }).path
  1473. return path.endsWith("/") ? path : getDirectory(path)
  1474. })()}
  1475. </span>
  1476. <Show when={!(item as { type: "file"; path: string }).path.endsWith("/")}>
  1477. <span class="text-text-strong whitespace-nowrap">
  1478. {getFilename((item as { type: "file"; path: string }).path)}
  1479. </span>
  1480. </Show>
  1481. </div>
  1482. </>
  1483. }
  1484. >
  1485. <Icon name="brain" size="small" class="text-icon-info-active shrink-0" />
  1486. <span class="text-14-regular text-text-strong whitespace-nowrap">
  1487. @{(item as { type: "agent"; name: string }).name}
  1488. </span>
  1489. </Show>
  1490. </button>
  1491. )}
  1492. </For>
  1493. </Show>
  1494. </Match>
  1495. <Match when={store.popover === "slash"}>
  1496. <Show
  1497. when={slashFlat().length > 0}
  1498. fallback={<div class="text-text-weak px-2 py-1">{language.t("prompt.popover.emptyCommands")}</div>}
  1499. >
  1500. <For each={slashFlat()}>
  1501. {(cmd) => (
  1502. <button
  1503. data-slash-id={cmd.id}
  1504. classList={{
  1505. "w-full flex items-center justify-between gap-4 rounded-md px-2 py-1": true,
  1506. "bg-surface-raised-base-hover": slashActive() === cmd.id,
  1507. }}
  1508. onClick={() => handleSlashSelect(cmd)}
  1509. onMouseEnter={() => setSlashActive(cmd.id)}
  1510. >
  1511. <div class="flex items-center gap-2 min-w-0">
  1512. <span class="text-14-regular text-text-strong whitespace-nowrap">/{cmd.trigger}</span>
  1513. <Show when={cmd.description}>
  1514. <span class="text-14-regular text-text-weak truncate">{cmd.description}</span>
  1515. </Show>
  1516. </div>
  1517. <div class="flex items-center gap-2 shrink-0">
  1518. <Show when={cmd.type === "custom" && cmd.source !== "command"}>
  1519. <span class="text-11-regular text-text-subtle px-1.5 py-0.5 bg-surface-base rounded">
  1520. {cmd.source === "skill"
  1521. ? language.t("prompt.slash.badge.skill")
  1522. : cmd.source === "mcp"
  1523. ? language.t("prompt.slash.badge.mcp")
  1524. : language.t("prompt.slash.badge.custom")}
  1525. </span>
  1526. </Show>
  1527. <Show when={command.keybind(cmd.id)}>
  1528. <span class="text-12-regular text-text-subtle">{command.keybind(cmd.id)}</span>
  1529. </Show>
  1530. </div>
  1531. </button>
  1532. )}
  1533. </For>
  1534. </Show>
  1535. </Match>
  1536. </Switch>
  1537. </div>
  1538. </Show>
  1539. <form
  1540. onSubmit={handleSubmit}
  1541. classList={{
  1542. "group/prompt-input": true,
  1543. "bg-surface-raised-stronger-non-alpha shadow-xs-border relative": true,
  1544. "rounded-[14px] overflow-clip focus-within:shadow-xs-border": true,
  1545. "border-icon-info-active border-dashed": store.dragging,
  1546. [props.class ?? ""]: !!props.class,
  1547. }}
  1548. >
  1549. <Show when={store.dragging}>
  1550. <div class="absolute inset-0 z-10 flex items-center justify-center bg-surface-raised-stronger-non-alpha/90 pointer-events-none">
  1551. <div class="flex flex-col items-center gap-2 text-text-weak">
  1552. <Icon name="photo" class="size-8" />
  1553. <span class="text-14-regular">{language.t("prompt.dropzone.label")}</span>
  1554. </div>
  1555. </div>
  1556. </Show>
  1557. <Show when={prompt.context.items().length > 0}>
  1558. <div class="flex flex-nowrap items-start gap-2 p-2 overflow-x-auto no-scrollbar">
  1559. <For each={prompt.context.items()}>
  1560. {(item) => {
  1561. const active = () => {
  1562. const a = comments.active()
  1563. return !!item.commentID && item.commentID === a?.id && item.path === a?.file
  1564. }
  1565. return (
  1566. <Tooltip
  1567. value={
  1568. <span class="flex max-w-[300px]">
  1569. <span class="text-text-invert-base truncate-start [unicode-bidi:plaintext] min-w-0">
  1570. {getDirectory(item.path)}
  1571. </span>
  1572. <span class="shrink-0">{getFilename(item.path)}</span>
  1573. </span>
  1574. }
  1575. placement="top"
  1576. openDelay={2000}
  1577. >
  1578. <div
  1579. classList={{
  1580. "group shrink-0 flex flex-col rounded-[6px] pl-2 pr-1 py-1 max-w-[200px] h-12 transition-all transition-transform shadow-xs-border hover:shadow-xs-border-hover": true,
  1581. "cursor-pointer hover:bg-surface-interactive-weak": !!item.commentID && !active(),
  1582. "cursor-pointer bg-surface-interactive-hover hover:bg-surface-interactive-hover shadow-xs-border-hover":
  1583. active(),
  1584. "bg-background-stronger": !active(),
  1585. }}
  1586. onClick={() => {
  1587. openComment(item)
  1588. }}
  1589. >
  1590. <div class="flex items-center gap-1.5">
  1591. <FileIcon node={{ path: item.path, type: "file" }} class="shrink-0 size-3.5" />
  1592. <div class="flex items-center text-11-regular min-w-0 font-medium">
  1593. <span class="text-text-strong whitespace-nowrap">{getFilenameTruncated(item.path, 14)}</span>
  1594. <Show when={item.selection}>
  1595. {(sel) => (
  1596. <span class="text-text-weak whitespace-nowrap shrink-0">
  1597. {sel().startLine === sel().endLine
  1598. ? `:${sel().startLine}`
  1599. : `:${sel().startLine}-${sel().endLine}`}
  1600. </span>
  1601. )}
  1602. </Show>
  1603. </div>
  1604. <IconButton
  1605. type="button"
  1606. icon="close-small"
  1607. variant="ghost"
  1608. class="ml-auto size-3.5 opacity-0 group-hover:opacity-100 transition-all"
  1609. onClick={(e) => {
  1610. e.stopPropagation()
  1611. if (item.commentID) comments.remove(item.path, item.commentID)
  1612. prompt.context.remove(item.key)
  1613. }}
  1614. aria-label={language.t("prompt.context.removeFile")}
  1615. />
  1616. </div>
  1617. <Show when={item.comment}>
  1618. {(comment) => (
  1619. <div class="text-12-regular text-text-strong ml-5 pr-1 truncate">{comment()}</div>
  1620. )}
  1621. </Show>
  1622. </div>
  1623. </Tooltip>
  1624. )
  1625. }}
  1626. </For>
  1627. </div>
  1628. </Show>
  1629. <Show when={imageAttachments().length > 0}>
  1630. <div class="flex flex-wrap gap-2 px-3 pt-3">
  1631. <For each={imageAttachments()}>
  1632. {(attachment) => (
  1633. <div class="relative group">
  1634. <Show
  1635. when={attachment.mime.startsWith("image/")}
  1636. fallback={
  1637. <div class="size-16 rounded-md bg-surface-base flex items-center justify-center border border-border-base">
  1638. <Icon name="folder" class="size-6 text-text-weak" />
  1639. </div>
  1640. }
  1641. >
  1642. <img
  1643. src={attachment.dataUrl}
  1644. alt={attachment.filename}
  1645. class="size-16 rounded-md object-cover border border-border-base hover:border-border-strong-base transition-colors"
  1646. onClick={() =>
  1647. dialog.show(() => <ImagePreview src={attachment.dataUrl} alt={attachment.filename} />)
  1648. }
  1649. />
  1650. </Show>
  1651. <button
  1652. type="button"
  1653. onClick={() => removeImageAttachment(attachment.id)}
  1654. class="absolute -top-1.5 -right-1.5 size-5 rounded-full bg-surface-raised-stronger-non-alpha border border-border-base flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-surface-raised-base-hover"
  1655. aria-label={language.t("prompt.attachment.remove")}
  1656. >
  1657. <Icon name="close" class="size-3 text-text-weak" />
  1658. </button>
  1659. <div class="absolute bottom-0 left-0 right-0 px-1 py-0.5 bg-black/50 rounded-b-md">
  1660. <span class="text-10-regular text-white truncate block">{attachment.filename}</span>
  1661. </div>
  1662. </div>
  1663. )}
  1664. </For>
  1665. </div>
  1666. </Show>
  1667. <div class="relative max-h-[240px] overflow-y-auto" ref={(el) => (scrollRef = el)}>
  1668. <div
  1669. data-component="prompt-input"
  1670. ref={(el) => {
  1671. editorRef = el
  1672. props.ref?.(el)
  1673. }}
  1674. role="textbox"
  1675. aria-multiline="true"
  1676. aria-label={
  1677. store.mode === "shell"
  1678. ? language.t("prompt.placeholder.shell")
  1679. : commentCount() > 1
  1680. ? language.t("prompt.placeholder.summarizeComments")
  1681. : commentCount() === 1
  1682. ? language.t("prompt.placeholder.summarizeComment")
  1683. : language.t("prompt.placeholder.normal", { example: language.t(EXAMPLES[store.placeholder]) })
  1684. }
  1685. contenteditable="true"
  1686. onInput={handleInput}
  1687. onPaste={handlePaste}
  1688. onCompositionStart={() => setComposing(true)}
  1689. onCompositionEnd={() => setComposing(false)}
  1690. onKeyDown={handleKeyDown}
  1691. classList={{
  1692. "select-text": true,
  1693. "w-full p-3 pr-12 text-14-regular text-text-strong focus:outline-none whitespace-pre-wrap": true,
  1694. "[&_[data-type=file]]:text-syntax-property": true,
  1695. "[&_[data-type=agent]]:text-syntax-type": true,
  1696. "font-mono!": store.mode === "shell",
  1697. }}
  1698. />
  1699. <Show when={!prompt.dirty()}>
  1700. <div class="absolute top-0 inset-x-0 p-3 pr-12 text-14-regular text-text-weak pointer-events-none whitespace-nowrap truncate">
  1701. {store.mode === "shell"
  1702. ? language.t("prompt.placeholder.shell")
  1703. : commentCount() > 1
  1704. ? language.t("prompt.placeholder.summarizeComments")
  1705. : commentCount() === 1
  1706. ? language.t("prompt.placeholder.summarizeComment")
  1707. : language.t("prompt.placeholder.normal", { example: language.t(EXAMPLES[store.placeholder]) })}
  1708. </div>
  1709. </Show>
  1710. </div>
  1711. <div class="relative p-3 flex items-center justify-between gap-2">
  1712. <div class="flex items-center gap-2 min-w-0 flex-1">
  1713. <Switch>
  1714. <Match when={store.mode === "shell"}>
  1715. <div class="flex items-center gap-2 px-2 h-6">
  1716. <Icon name="console" size="small" class="text-icon-primary" />
  1717. <span class="text-12-regular text-text-primary">{language.t("prompt.mode.shell")}</span>
  1718. <span class="text-12-regular text-text-weak">{language.t("prompt.mode.shell.exit")}</span>
  1719. </div>
  1720. </Match>
  1721. <Match when={store.mode === "normal"}>
  1722. <TooltipKeybind
  1723. placement="top"
  1724. gutter={8}
  1725. title={language.t("command.agent.cycle")}
  1726. keybind={command.keybind("agent.cycle")}
  1727. >
  1728. <Select
  1729. options={local.agent.list().map((agent) => agent.name)}
  1730. current={local.agent.current()?.name ?? ""}
  1731. onSelect={local.agent.set}
  1732. class={`capitalize ${local.model.variant.list().length > 0 ? "max-w-[80px]" : "max-w-[120px]"}`}
  1733. valueClass="truncate"
  1734. variant="ghost"
  1735. />
  1736. </TooltipKeybind>
  1737. <Show
  1738. when={providers.paid().length > 0}
  1739. fallback={
  1740. <TooltipKeybind
  1741. placement="top"
  1742. gutter={8}
  1743. title={language.t("command.model.choose")}
  1744. keybind={command.keybind("model.choose")}
  1745. >
  1746. <Button
  1747. as="div"
  1748. variant="ghost"
  1749. class="px-2 min-w-0 max-w-[240px]"
  1750. onClick={() => dialog.show(() => <DialogSelectModelUnpaid />)}
  1751. >
  1752. <Show when={local.model.current()?.provider?.id}>
  1753. <ProviderIcon id={local.model.current()!.provider.id as IconName} class="size-4 shrink-0" />
  1754. </Show>
  1755. <span class="truncate">
  1756. {local.model.current()?.name ?? language.t("dialog.model.select.title")}
  1757. </span>
  1758. <Icon name="chevron-down" size="small" class="shrink-0" />
  1759. </Button>
  1760. </TooltipKeybind>
  1761. }
  1762. >
  1763. <TooltipKeybind
  1764. placement="top"
  1765. gutter={8}
  1766. title={language.t("command.model.choose")}
  1767. keybind={command.keybind("model.choose")}
  1768. >
  1769. <ModelSelectorPopover
  1770. triggerAs={Button}
  1771. triggerProps={{ variant: "ghost", class: "min-w-0 max-w-[240px]" }}
  1772. >
  1773. <Show when={local.model.current()?.provider?.id}>
  1774. <ProviderIcon id={local.model.current()!.provider.id as IconName} class="size-4 shrink-0" />
  1775. </Show>
  1776. <span class="truncate">
  1777. {local.model.current()?.name ?? language.t("dialog.model.select.title")}
  1778. </span>
  1779. <Icon name="chevron-down" size="small" class="shrink-0" />
  1780. </ModelSelectorPopover>
  1781. </TooltipKeybind>
  1782. </Show>
  1783. <Show when={local.model.variant.list().length > 0}>
  1784. <TooltipKeybind
  1785. placement="top"
  1786. gutter={8}
  1787. title={language.t("command.model.variant.cycle")}
  1788. keybind={command.keybind("model.variant.cycle")}
  1789. >
  1790. <Button
  1791. data-action="model-variant-cycle"
  1792. variant="ghost"
  1793. class="text-text-base _hidden group-hover/prompt-input:inline-block capitalize text-12-regular"
  1794. onClick={() => local.model.variant.cycle()}
  1795. >
  1796. {local.model.variant.current() ?? language.t("common.default")}
  1797. </Button>
  1798. </TooltipKeybind>
  1799. </Show>
  1800. <Show when={permission.permissionsEnabled() && params.id}>
  1801. <TooltipKeybind
  1802. placement="top"
  1803. gutter={8}
  1804. title={language.t("command.permissions.autoaccept.enable")}
  1805. keybind={command.keybind("permissions.autoaccept")}
  1806. >
  1807. <Button
  1808. variant="ghost"
  1809. onClick={() => permission.toggleAutoAccept(params.id!, sdk.directory)}
  1810. classList={{
  1811. "_hidden group-hover/prompt-input:flex size-6 items-center justify-center": true,
  1812. "text-text-base": !permission.isAutoAccepting(params.id!, sdk.directory),
  1813. "hover:bg-surface-success-base": permission.isAutoAccepting(params.id!, sdk.directory),
  1814. }}
  1815. aria-label={
  1816. permission.isAutoAccepting(params.id!, sdk.directory)
  1817. ? language.t("command.permissions.autoaccept.disable")
  1818. : language.t("command.permissions.autoaccept.enable")
  1819. }
  1820. aria-pressed={permission.isAutoAccepting(params.id!, sdk.directory)}
  1821. >
  1822. <Icon
  1823. name="chevron-double-right"
  1824. size="small"
  1825. classList={{ "text-icon-success-base": permission.isAutoAccepting(params.id!, sdk.directory) }}
  1826. />
  1827. </Button>
  1828. </TooltipKeybind>
  1829. </Show>
  1830. </Match>
  1831. </Switch>
  1832. </div>
  1833. <div class="flex items-center gap-1 shrink-0">
  1834. <input
  1835. ref={fileInputRef}
  1836. type="file"
  1837. accept={ACCEPTED_FILE_TYPES.join(",")}
  1838. class="hidden"
  1839. onChange={(e) => {
  1840. const file = e.currentTarget.files?.[0]
  1841. if (file) addImageAttachment(file)
  1842. e.currentTarget.value = ""
  1843. }}
  1844. />
  1845. <div class="flex items-center gap-1 mr-1">
  1846. <SessionContextUsage />
  1847. <Show when={store.mode === "normal"}>
  1848. <Tooltip placement="top" value={language.t("prompt.action.attachFile")}>
  1849. <Button
  1850. type="button"
  1851. variant="ghost"
  1852. class="size-6 px-1"
  1853. onClick={() => fileInputRef.click()}
  1854. aria-label={language.t("prompt.action.attachFile")}
  1855. >
  1856. <Icon name="photo" class="size-4.5" />
  1857. </Button>
  1858. </Tooltip>
  1859. </Show>
  1860. </div>
  1861. <Tooltip
  1862. placement="top"
  1863. inactive={!prompt.dirty() && !working()}
  1864. value={
  1865. <Switch>
  1866. <Match when={working()}>
  1867. <div class="flex items-center gap-2">
  1868. <span>{language.t("prompt.action.stop")}</span>
  1869. <span class="text-icon-base text-12-medium text-[10px]!">{language.t("common.key.esc")}</span>
  1870. </div>
  1871. </Match>
  1872. <Match when={true}>
  1873. <div class="flex items-center gap-2">
  1874. <span>{language.t("prompt.action.send")}</span>
  1875. <Icon name="enter" size="small" class="text-icon-base" />
  1876. </div>
  1877. </Match>
  1878. </Switch>
  1879. }
  1880. >
  1881. <IconButton
  1882. type="submit"
  1883. disabled={!prompt.dirty() && !working() && commentCount() === 0}
  1884. icon={working() ? "stop" : "arrow-up"}
  1885. variant="primary"
  1886. class="h-6 w-4.5"
  1887. aria-label={working() ? language.t("prompt.action.stop") : language.t("prompt.action.send")}
  1888. />
  1889. </Tooltip>
  1890. </div>
  1891. </div>
  1892. </form>
  1893. </div>
  1894. )
  1895. }
  1896. function createTextFragment(content: string): DocumentFragment {
  1897. const fragment = document.createDocumentFragment()
  1898. const segments = content.split("\n")
  1899. segments.forEach((segment, index) => {
  1900. if (segment) {
  1901. fragment.appendChild(document.createTextNode(segment))
  1902. } else if (segments.length > 1) {
  1903. fragment.appendChild(document.createTextNode("\u200B"))
  1904. }
  1905. if (index < segments.length - 1) {
  1906. fragment.appendChild(document.createElement("br"))
  1907. }
  1908. })
  1909. return fragment
  1910. }
  1911. function getNodeLength(node: Node): number {
  1912. if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR") return 1
  1913. return (node.textContent ?? "").replace(/\u200B/g, "").length
  1914. }
  1915. function getTextLength(node: Node): number {
  1916. if (node.nodeType === Node.TEXT_NODE) return (node.textContent ?? "").replace(/\u200B/g, "").length
  1917. if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR") return 1
  1918. let length = 0
  1919. for (const child of Array.from(node.childNodes)) {
  1920. length += getTextLength(child)
  1921. }
  1922. return length
  1923. }
  1924. function getCursorPosition(parent: HTMLElement): number {
  1925. const selection = window.getSelection()
  1926. if (!selection || selection.rangeCount === 0) return 0
  1927. const range = selection.getRangeAt(0)
  1928. if (!parent.contains(range.startContainer)) return 0
  1929. const preCaretRange = range.cloneRange()
  1930. preCaretRange.selectNodeContents(parent)
  1931. preCaretRange.setEnd(range.startContainer, range.startOffset)
  1932. return getTextLength(preCaretRange.cloneContents())
  1933. }
  1934. function setCursorPosition(parent: HTMLElement, position: number) {
  1935. let remaining = position
  1936. let node = parent.firstChild
  1937. while (node) {
  1938. const length = getNodeLength(node)
  1939. const isText = node.nodeType === Node.TEXT_NODE
  1940. const isPill =
  1941. node.nodeType === Node.ELEMENT_NODE &&
  1942. ((node as HTMLElement).dataset.type === "file" || (node as HTMLElement).dataset.type === "agent")
  1943. const isBreak = node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR"
  1944. if (isText && remaining <= length) {
  1945. const range = document.createRange()
  1946. const selection = window.getSelection()
  1947. range.setStart(node, remaining)
  1948. range.collapse(true)
  1949. selection?.removeAllRanges()
  1950. selection?.addRange(range)
  1951. return
  1952. }
  1953. if ((isPill || isBreak) && remaining <= length) {
  1954. const range = document.createRange()
  1955. const selection = window.getSelection()
  1956. if (remaining === 0) {
  1957. range.setStartBefore(node)
  1958. }
  1959. if (remaining > 0 && isPill) {
  1960. range.setStartAfter(node)
  1961. }
  1962. if (remaining > 0 && isBreak) {
  1963. const next = node.nextSibling
  1964. if (next && next.nodeType === Node.TEXT_NODE) {
  1965. range.setStart(next, 0)
  1966. }
  1967. if (!next || next.nodeType !== Node.TEXT_NODE) {
  1968. range.setStartAfter(node)
  1969. }
  1970. }
  1971. range.collapse(true)
  1972. selection?.removeAllRanges()
  1973. selection?.addRange(range)
  1974. return
  1975. }
  1976. remaining -= length
  1977. node = node.nextSibling
  1978. }
  1979. const fallbackRange = document.createRange()
  1980. const fallbackSelection = window.getSelection()
  1981. const last = parent.lastChild
  1982. if (last && last.nodeType === Node.TEXT_NODE) {
  1983. const len = last.textContent ? last.textContent.length : 0
  1984. fallbackRange.setStart(last, len)
  1985. }
  1986. if (!last || last.nodeType !== Node.TEXT_NODE) {
  1987. fallbackRange.selectNodeContents(parent)
  1988. }
  1989. fallbackRange.collapse(false)
  1990. fallbackSelection?.removeAllRanges()
  1991. fallbackSelection?.addRange(fallbackRange)
  1992. }