prompt-input.tsx 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350
  1. import { useFilteredList } from "@opencode-ai/ui/hooks"
  2. import { useSpring } from "@opencode-ai/ui/motion-spring"
  3. import {
  4. createEffect,
  5. on,
  6. Component,
  7. Show,
  8. onCleanup,
  9. createMemo,
  10. createSignal,
  11. createResource,
  12. Switch,
  13. Match,
  14. type JSX,
  15. } from "solid-js"
  16. import { createStore, type SetStoreFunction, type Store } from "solid-js/store"
  17. import type { useLocal } from "@/context/local"
  18. import { selectionFromLines, type SelectedLineRange, useFile } 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 { useSync } from "@/context/sync"
  32. import { useComments } from "@/context/comments"
  33. import { Button } from "@opencode-ai/ui/button"
  34. import { DockShellForm, DockTray } from "@opencode-ai/ui/dock-surface"
  35. import { Icon } from "@opencode-ai/ui/icon"
  36. import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
  37. import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
  38. import { ButtonV2 } from "@opencode-ai/ui/v2/button-v2"
  39. import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
  40. import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
  41. import { KeybindV2 } from "@opencode-ai/ui/v2/keybind-v2"
  42. import { MenuV2 } from "@opencode-ai/ui/v2/menu-v2"
  43. import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
  44. import { IconButton } from "@opencode-ai/ui/icon-button"
  45. import { Select } from "@opencode-ai/ui/select"
  46. import { useDialog } from "@opencode-ai/ui/context/dialog"
  47. import { ModelSelectorPopover, ModelSelectorPopoverV2 } from "@/components/dialog-select-model"
  48. import { DialogSelectModelUnpaid } from "@/components/dialog-select-model-unpaid"
  49. import { DialogSelectModelUnpaidV2 } from "@/components/dialog-select-model-unpaid-v2"
  50. import { useCommand } from "@/context/command"
  51. import { Persist, persisted } from "@/utils/persist"
  52. import { usePermission } from "@/context/permission"
  53. import { useLanguage } from "@/context/language"
  54. import { usePlatform } from "@/context/platform"
  55. import { createSessionTabs } from "@/pages/session/helpers"
  56. import { createTextFragment, getCursorPosition, setCursorPosition, setRangeEdge } from "./prompt-input/editor-dom"
  57. import { createPromptAttachments } from "./prompt-input/attachments"
  58. import { ACCEPTED_FILE_TYPES, pickAttachmentFiles } from "./prompt-input/files"
  59. import {
  60. canNavigateHistoryAtCursor,
  61. navigatePromptHistory,
  62. prependHistoryEntry,
  63. type PromptHistoryComment,
  64. type PromptHistoryEntry,
  65. type PromptHistoryStoredEntry,
  66. promptLength,
  67. } from "./prompt-input/history"
  68. import { createPromptSubmit, type FollowupDraft } from "./prompt-input/submit"
  69. import { PromptPopover, type AtOption, type SlashCommand } from "./prompt-input/slash-popover"
  70. import { PromptContextItems } from "./prompt-input/context-items"
  71. import { PromptImageAttachments } from "./prompt-input/image-attachments"
  72. import { PromptDragOverlay } from "./prompt-input/drag-overlay"
  73. import { promptPlaceholder } from "./prompt-input/placeholder"
  74. import { createPromptInputTransientState } from "./prompt-input/transient-state"
  75. import { showToast } from "@/utils/toast"
  76. import { ImagePreview } from "@opencode-ai/ui/image-preview"
  77. import type { ReferenceInfo } from "@opencode-ai/sdk/v2/client"
  78. export type PromptInputState = ReturnType<typeof usePrompt>
  79. export type PromptInputHistory = {
  80. entries: (mode: "normal" | "shell") => PromptHistoryStoredEntry[]
  81. add: (prompt: Prompt, mode: "normal" | "shell", comments: PromptHistoryComment[]) => void
  82. }
  83. export type PromptInputSubmission = {
  84. abort: () => Promise<void> | void
  85. handleSubmit: (event: Event) => Promise<void> | void
  86. }
  87. export type PromptInputControls = {
  88. agents: {
  89. available: { name: string; hidden?: boolean; mode: string }[]
  90. options: string[]
  91. current: string
  92. loading: boolean
  93. visible: boolean
  94. select: (name: string | undefined) => void
  95. }
  96. model: {
  97. selection: ReturnType<typeof useLocal>["model"]
  98. paid: boolean
  99. loading: boolean
  100. }
  101. session: {
  102. id?: string
  103. tabs: {
  104. active: () => string | undefined
  105. all: () => string[]
  106. open: (tab: string) => void | Promise<void>
  107. setActive: (tab: string) => void
  108. }
  109. reviewPanel: {
  110. opened: () => boolean
  111. open: () => void
  112. }
  113. }
  114. newLayoutDesigns: boolean
  115. }
  116. export function createPromptInputHistory(): PromptInputHistory {
  117. const [normal, setNormal] = createStore<PromptHistoryState>({ entries: [] })
  118. const [shell, setShell] = createStore<PromptHistoryState>({ entries: [] })
  119. return createPromptInputHistoryStore(normal, setNormal, shell, setShell)
  120. }
  121. type PromptHistoryState = { entries: PromptHistoryStoredEntry[] }
  122. function createPromptInputHistoryStore(
  123. normal: Store<PromptHistoryState>,
  124. setNormal: SetStoreFunction<PromptHistoryState>,
  125. shell: Store<PromptHistoryState>,
  126. setShell: SetStoreFunction<PromptHistoryState>,
  127. ): PromptInputHistory {
  128. return {
  129. entries: (mode) => (mode === "shell" ? shell.entries : normal.entries),
  130. add(prompt, mode, comments) {
  131. const current = mode === "shell" ? shell : normal
  132. const setCurrent = mode === "shell" ? setShell : setNormal
  133. const next = prependHistoryEntry(current.entries, prompt, comments)
  134. if (next === current.entries) return
  135. setCurrent("entries", next)
  136. },
  137. }
  138. }
  139. function createPersistedPromptInputHistory() {
  140. const [normal, setNormal] = persisted(
  141. Persist.global("prompt-history", ["prompt-history.v1"]),
  142. createStore<PromptHistoryState>({ entries: [] }),
  143. )
  144. const [shell, setShell] = persisted(
  145. Persist.global("prompt-history-shell", ["prompt-history-shell.v1"]),
  146. createStore<PromptHistoryState>({ entries: [] }),
  147. )
  148. return createPromptInputHistoryStore(normal, setNormal, shell, setShell)
  149. }
  150. export interface PromptInputProps {
  151. class?: string
  152. variant?: "dock" | "new-session"
  153. state?: PromptInputState
  154. history?: PromptInputHistory
  155. submission?: PromptInputSubmission
  156. controls: PromptInputControls
  157. ref?: (el: HTMLDivElement) => void
  158. newSessionWorktree?: string
  159. onNewSessionWorktreeReset?: () => void
  160. edit?: { id: string; prompt: Prompt; context: FollowupDraft["context"] }
  161. onEditLoaded?: () => void
  162. shouldQueue?: () => boolean
  163. onQueue?: (draft: FollowupDraft) => void
  164. onAbort?: () => void
  165. onSubmit?: () => void
  166. toolbar?: JSX.Element
  167. }
  168. const EXAMPLES = [
  169. "prompt.example.1",
  170. "prompt.example.2",
  171. "prompt.example.3",
  172. "prompt.example.4",
  173. "prompt.example.5",
  174. "prompt.example.6",
  175. "prompt.example.7",
  176. "prompt.example.8",
  177. "prompt.example.9",
  178. "prompt.example.10",
  179. "prompt.example.11",
  180. "prompt.example.12",
  181. "prompt.example.13",
  182. "prompt.example.14",
  183. "prompt.example.15",
  184. "prompt.example.16",
  185. "prompt.example.17",
  186. "prompt.example.18",
  187. "prompt.example.19",
  188. "prompt.example.20",
  189. "prompt.example.21",
  190. "prompt.example.22",
  191. "prompt.example.23",
  192. "prompt.example.24",
  193. "prompt.example.25",
  194. ] as const
  195. export const PromptInput: Component<PromptInputProps> = (props) => {
  196. const sdk = useSDK()
  197. const sync = useSync()
  198. const files = useFile()
  199. const prompt = props.state ?? usePrompt()
  200. const layout = useLayout()
  201. const comments = useComments()
  202. const dialog = useDialog()
  203. const command = useCommand()
  204. const permission = usePermission()
  205. const language = useLanguage()
  206. const platform = usePlatform()
  207. const tabs = () => props.controls.session.tabs
  208. let editorRef!: HTMLDivElement
  209. let fileInputRef: HTMLInputElement | undefined
  210. let scrollRef!: HTMLDivElement
  211. let slashPopoverRef!: HTMLDivElement
  212. let restoreEndOnFocus = true
  213. let savedCursor: number | null = null
  214. const mirror = { input: false }
  215. const inset = 56
  216. const space = `${inset}px`
  217. const scrollCursorIntoView = () => {
  218. const container = scrollRef
  219. const selection = window.getSelection()
  220. if (!container || !selection || selection.rangeCount === 0) return
  221. const range = selection.getRangeAt(0)
  222. if (!editorRef.contains(range.startContainer)) return
  223. const cursor = getCursorPosition(editorRef)
  224. const length = promptLength(prompt.current().filter((part) => part.type !== "image"))
  225. if (cursor >= length) {
  226. container.scrollTop = container.scrollHeight
  227. return
  228. }
  229. const rect = range.getClientRects().item(0) ?? range.getBoundingClientRect()
  230. if (!rect.height) return
  231. const containerRect = container.getBoundingClientRect()
  232. const top = rect.top - containerRect.top + container.scrollTop
  233. const bottom = rect.bottom - containerRect.top + container.scrollTop
  234. const padding = 12
  235. if (top < container.scrollTop + padding) {
  236. container.scrollTop = Math.max(0, top - padding)
  237. return
  238. }
  239. if (bottom > container.scrollTop + container.clientHeight - inset) {
  240. container.scrollTop = bottom - container.clientHeight + inset
  241. }
  242. }
  243. const queueScroll = (count = 2) => {
  244. requestAnimationFrame(() => {
  245. scrollCursorIntoView()
  246. if (count > 1) queueScroll(count - 1)
  247. })
  248. }
  249. const activeFileTab = createSessionTabs({
  250. tabs,
  251. pathFromTab: files.pathFromTab,
  252. normalizeTab: (tab) => (tab.startsWith("file://") ? files.tab(tab) : tab),
  253. }).activeFileTab
  254. const commentInReview = (path: string) => {
  255. const sessionID = props.controls.session.id
  256. if (!sessionID) return false
  257. const diffs = sync().data.session_diff[sessionID]
  258. if (!diffs) return false
  259. return diffs.some((diff) => diff.file === path)
  260. }
  261. const openComment = (item: { path: string; commentID?: string; commentOrigin?: "review" | "file" }) => {
  262. if (!item.commentID) return
  263. const focus = { file: item.path, id: item.commentID }
  264. comments.setActive(focus)
  265. const queueCommentFocus = (attempts = 6) => {
  266. const schedule = (left: number) => {
  267. requestAnimationFrame(() => {
  268. comments.setFocus({ ...focus })
  269. if (left <= 0) return
  270. requestAnimationFrame(() => {
  271. const current = comments.focus()
  272. if (!current) return
  273. if (current.file !== focus.file || current.id !== focus.id) return
  274. schedule(left - 1)
  275. })
  276. })
  277. }
  278. schedule(attempts)
  279. }
  280. const wantsReview = item.commentOrigin === "review" || (item.commentOrigin !== "file" && commentInReview(item.path))
  281. if (wantsReview) {
  282. if (!props.controls.session.reviewPanel.opened()) props.controls.session.reviewPanel.open()
  283. layout.fileTree.setTab("changes")
  284. tabs().setActive("review")
  285. queueCommentFocus()
  286. return
  287. }
  288. if (!props.controls.session.reviewPanel.opened()) props.controls.session.reviewPanel.open()
  289. layout.fileTree.setTab("all")
  290. const tab = files.tab(item.path)
  291. void tabs().open(tab)
  292. tabs().setActive(tab)
  293. void Promise.resolve(files.load(item.path)).finally(() => queueCommentFocus())
  294. }
  295. const recent = createMemo(() => {
  296. const all = tabs().all()
  297. const active = activeFileTab()
  298. const order = active ? [active, ...all.filter((x) => x !== active)] : all
  299. const seen = new Set<string>()
  300. const paths: string[] = []
  301. for (const tab of order) {
  302. const path = files.pathFromTab(tab)
  303. if (!path) continue
  304. if (seen.has(path)) continue
  305. seen.add(path)
  306. paths.push(path)
  307. }
  308. return paths
  309. })
  310. const info = createMemo(() => (props.controls.session.id ? sync().session.get(props.controls.session.id) : undefined))
  311. const working = createMemo(() => sync().data.session_working(props.controls.session.id ?? ""))
  312. const imageAttachments = createMemo(() =>
  313. prompt.current().filter((part): part is ImageAttachmentPart => part.type === "image"),
  314. )
  315. const [store, setStore] = createPromptInputTransientState(
  316. () => prompt.capture(),
  317. Math.floor(Math.random() * EXAMPLES.length),
  318. )
  319. const buttonsSpring = useSpring(() => (store.mode === "normal" ? 1 : 0), { visualDuration: 0.2, bounce: 0 })
  320. const motion = (value: number) => ({
  321. opacity: value,
  322. transform: `scale(${0.98 + value * 0.02})`,
  323. filter: `blur(${(1 - value) * 2}px)`,
  324. "pointer-events": value > 0.5 ? ("auto" as const) : ("none" as const),
  325. })
  326. const buttons = createMemo(() => motion(buttonsSpring()))
  327. const shell = createMemo(() => motion(1 - buttonsSpring()))
  328. const control = createMemo(() => ({ height: "28px", ...buttons() }))
  329. const commentCount = createMemo(() => {
  330. if (store.mode === "shell") return 0
  331. return prompt.context.items().filter((item) => !!item.comment?.trim()).length
  332. })
  333. const blank = createMemo(() => {
  334. const text = prompt
  335. .current()
  336. .map((part) => ("content" in part ? part.content : ""))
  337. .join("")
  338. return text.trim().length === 0 && imageAttachments().length === 0 && commentCount() === 0
  339. })
  340. const stopping = createMemo(() => working() && blank())
  341. const tip = () => {
  342. if (stopping()) {
  343. return (
  344. <div class="flex items-center gap-2">
  345. <span>{language.t("prompt.action.stop")}</span>
  346. <span class="text-icon-base text-12-medium text-[10px]!">{language.t("common.key.esc")}</span>
  347. </div>
  348. )
  349. }
  350. return (
  351. <div class="flex items-center gap-2">
  352. <span>{language.t("prompt.action.send")}</span>
  353. <Icon name="enter" size="small" class="text-icon-base" />
  354. </div>
  355. )
  356. }
  357. const contextItems = createMemo(() => {
  358. const items = prompt.context.items()
  359. if (store.mode !== "shell") return items
  360. return items.filter((item) => !item.comment?.trim())
  361. })
  362. const hasUserPrompt = createMemo(() => {
  363. const sessionID = props.controls.session.id
  364. if (!sessionID) return false
  365. const messages = sync().data.message[sessionID]
  366. if (!messages) return false
  367. return messages.some((m) => m.role === "user")
  368. })
  369. const history = props.history ?? createPersistedPromptInputHistory()
  370. const suggest = createMemo(() => !hasUserPrompt())
  371. const placeholder = createMemo(() =>
  372. promptPlaceholder({
  373. mode: store.mode,
  374. commentCount: commentCount(),
  375. example: suggest() ? (store.mode === "shell" ? "git status" : language.t(EXAMPLES[store.placeholder])) : "",
  376. suggest: suggest(),
  377. t: (key, params) => language.t(key as Parameters<typeof language.t>[0], params as never),
  378. }),
  379. )
  380. const historyComments = () => {
  381. const byID = new Map(comments.all().map((item) => [`${item.file}\n${item.id}`, item] as const))
  382. return prompt.context.items().flatMap((item) => {
  383. if (item.type !== "file") return []
  384. const comment = item.comment?.trim()
  385. if (!comment) return []
  386. const selection = item.commentID ? byID.get(`${item.path}\n${item.commentID}`)?.selection : undefined
  387. const nextSelection =
  388. selection ??
  389. (item.selection
  390. ? ({
  391. start: item.selection.startLine,
  392. end: item.selection.endLine,
  393. } satisfies SelectedLineRange)
  394. : undefined)
  395. if (!nextSelection) return []
  396. return [
  397. {
  398. id: item.commentID ?? item.key,
  399. path: item.path,
  400. selection: { ...nextSelection },
  401. comment,
  402. time: item.commentID ? (byID.get(`${item.path}\n${item.commentID}`)?.time ?? Date.now()) : Date.now(),
  403. origin: item.commentOrigin,
  404. preview: item.preview,
  405. } satisfies PromptHistoryComment,
  406. ]
  407. })
  408. }
  409. const applyHistoryComments = (items: PromptHistoryComment[]) => {
  410. comments.replace(
  411. items.map((item) => ({
  412. id: item.id,
  413. file: item.path,
  414. selection: { ...item.selection },
  415. comment: item.comment,
  416. time: item.time,
  417. })),
  418. )
  419. prompt.context.replaceComments(
  420. items.map((item) => ({
  421. type: "file" as const,
  422. path: item.path,
  423. selection: selectionFromLines(item.selection),
  424. comment: item.comment,
  425. commentID: item.id,
  426. commentOrigin: item.origin,
  427. preview: item.preview,
  428. })),
  429. )
  430. }
  431. const applyHistoryPrompt = (entry: PromptHistoryEntry, position: "start" | "end") => {
  432. const p = entry.prompt
  433. const length = position === "start" ? 0 : promptLength(p)
  434. setStore("applyingHistory", true)
  435. applyHistoryComments(entry.comments)
  436. prompt.set(p, length)
  437. requestAnimationFrame(() => {
  438. editorRef.focus()
  439. setCursorPosition(editorRef, length)
  440. setStore("applyingHistory", false)
  441. queueScroll()
  442. })
  443. }
  444. const getCaretState = () => {
  445. const selection = window.getSelection()
  446. const textLength = promptLength(prompt.current())
  447. if (!selection || selection.rangeCount === 0) {
  448. return { collapsed: false, cursorPosition: 0, textLength }
  449. }
  450. const anchorNode = selection.anchorNode
  451. if (!anchorNode || !editorRef.contains(anchorNode)) {
  452. return { collapsed: false, cursorPosition: 0, textLength }
  453. }
  454. return {
  455. collapsed: selection.isCollapsed,
  456. cursorPosition: getCursorPosition(editorRef),
  457. textLength,
  458. }
  459. }
  460. const escBlur = () => platform.platform === "desktop" && platform.os === "macos"
  461. const pick = () => {
  462. pickAttachmentFiles({
  463. picker: platform.openAttachmentPickerDialog,
  464. directory: () => sdk().directory,
  465. fallback: () => fileInputRef?.click(),
  466. onFile: addAttachment,
  467. onError: (error) =>
  468. showToast({
  469. variant: "error",
  470. title: language.t("common.requestFailed"),
  471. description: error instanceof Error ? error.message : String(error),
  472. }),
  473. })
  474. }
  475. const setMode = (mode: "normal" | "shell") => {
  476. setStore("mode", mode)
  477. setStore({ popover: null, slashMenu: false, slashMenuQuery: "" })
  478. requestAnimationFrame(() => editorRef?.focus())
  479. }
  480. const shellModeKey = "mod+shift+x"
  481. const normalModeKey = "mod+shift+e"
  482. command.register("prompt-input", () => [
  483. {
  484. id: "file.attach",
  485. title: language.t("prompt.action.attachFile"),
  486. category: language.t("command.category.file"),
  487. keybind: "mod+u",
  488. disabled: store.mode !== "normal",
  489. onSelect: pick,
  490. },
  491. {
  492. id: "prompt.mode.shell",
  493. title: language.t("command.prompt.mode.shell"),
  494. category: language.t("command.category.session"),
  495. keybind: shellModeKey,
  496. disabled: store.mode === "shell",
  497. onSelect: () => setMode("shell"),
  498. },
  499. {
  500. id: "prompt.mode.normal",
  501. title: language.t("command.prompt.mode.normal"),
  502. category: language.t("command.category.session"),
  503. keybind: normalModeKey,
  504. disabled: store.mode === "normal",
  505. onSelect: () => setMode("normal"),
  506. },
  507. ])
  508. const closePopover = () => setStore({ popover: null, slashMenu: false, slashMenuQuery: "" })
  509. const resetHistoryNavigation = (force = false) => {
  510. if (!force && (store.historyIndex < 0 || store.applyingHistory)) return
  511. setStore("historyIndex", -1)
  512. setStore("savedPrompt", null)
  513. }
  514. const clearEditor = () => {
  515. editorRef.innerHTML = ""
  516. }
  517. const setEditorText = (text: string) => {
  518. clearEditor()
  519. editorRef.textContent = text
  520. }
  521. const focusEditorEnd = () => {
  522. requestAnimationFrame(() => {
  523. editorRef.focus()
  524. const range = document.createRange()
  525. const selection = window.getSelection()
  526. range.selectNodeContents(editorRef)
  527. range.collapse(false)
  528. selection?.removeAllRanges()
  529. selection?.addRange(range)
  530. })
  531. }
  532. const currentCursor = () => {
  533. const selection = window.getSelection()
  534. if (!selection || selection.rangeCount === 0 || !editorRef.contains(selection.anchorNode)) return null
  535. return getCursorPosition(editorRef)
  536. }
  537. const restoreFocus = () => {
  538. requestAnimationFrame(() => {
  539. const cursor = savedCursor ?? prompt.cursor() ?? promptLength(prompt.current())
  540. editorRef.focus()
  541. setCursorPosition(editorRef, cursor)
  542. queueScroll()
  543. })
  544. }
  545. const handleFocus = () => {
  546. if (!restoreEndOnFocus) return
  547. restoreEndOnFocus = false
  548. requestAnimationFrame(() => {
  549. if (document.activeElement !== editorRef) return
  550. setCursorPosition(editorRef, prompt.cursor() ?? promptLength(prompt.current()))
  551. queueScroll()
  552. })
  553. }
  554. const renderEditorWithCursor = (parts: Prompt) => {
  555. const cursor = currentCursor()
  556. renderEditor(parts)
  557. if (cursor !== null) setCursorPosition(editorRef, cursor)
  558. }
  559. createEffect(() => {
  560. props.controls.session.id
  561. if (props.controls.session.id) return
  562. if (!suggest()) return
  563. const interval = setInterval(() => {
  564. setStore("placeholder", (prev) => (prev + 1) % EXAMPLES.length)
  565. }, 6500)
  566. onCleanup(() => clearInterval(interval))
  567. })
  568. const [composing, setComposing] = createSignal(false)
  569. const isImeComposing = (event: KeyboardEvent) => event.isComposing || composing() || event.keyCode === 229
  570. const handleBlur = () => {
  571. savedCursor = currentCursor()
  572. closePopover()
  573. setComposing(false)
  574. }
  575. const handleCompositionStart = () => {
  576. setComposing(true)
  577. }
  578. const handleCompositionEnd = () => {
  579. setComposing(false)
  580. requestAnimationFrame(() => {
  581. if (composing()) return
  582. reconcile(prompt.current().filter((part) => part.type !== "image"))
  583. })
  584. }
  585. const referenceDescription = (reference: ReferenceInfo) =>
  586. reference.source.type === "git" ? reference.source.repository : reference.source.path
  587. const referenceList = createMemo(() =>
  588. sync()
  589. .data.reference.filter((reference) => !reference.hidden)
  590. .map(
  591. (reference): AtOption => ({
  592. type: "reference",
  593. name: reference.name,
  594. path: reference.path,
  595. display: reference.name,
  596. description: reference.description ?? referenceDescription(reference),
  597. }),
  598. ),
  599. )
  600. const agentList = createMemo(() =>
  601. props.controls.agents.available
  602. .filter((agent) => !agent.hidden && agent.mode !== "primary")
  603. .map((agent): AtOption => ({ type: "agent", name: agent.name, display: agent.name })),
  604. )
  605. const mcpResourceList = createMemo(() =>
  606. Object.values(sync().data.mcp_resource).map(
  607. (resource): AtOption => ({
  608. type: "resource",
  609. name: resource.name,
  610. uri: resource.uri,
  611. client: resource.client,
  612. display: resource.name,
  613. description: resource.description,
  614. mime: resource.mimeType,
  615. }),
  616. ),
  617. )
  618. const handleAtSelect = (option: AtOption | undefined) => {
  619. if (!option) return
  620. if (option.type === "agent") {
  621. addPart({ type: "agent", name: option.name, content: "@" + option.name, start: 0, end: 0 })
  622. return
  623. }
  624. if (option.type === "reference") {
  625. addPart({
  626. type: "file",
  627. path: option.path,
  628. content: "@" + option.name,
  629. start: 0,
  630. end: 0,
  631. mime: "application/x-directory",
  632. filename: option.name,
  633. })
  634. return
  635. }
  636. if (option.type === "resource") {
  637. addPart({
  638. type: "file",
  639. path: option.uri,
  640. content: "@" + option.name,
  641. start: 0,
  642. end: 0,
  643. mime: option.mime ?? "text/plain",
  644. filename: option.name,
  645. url: option.uri,
  646. source: {
  647. type: "resource",
  648. text: { value: "@" + option.name, start: 0, end: 0 },
  649. clientName: option.client,
  650. uri: option.uri,
  651. },
  652. })
  653. return
  654. }
  655. addPart({ type: "file", path: option.path, content: "@" + option.path, start: 0, end: 0 })
  656. }
  657. const atKey = (x: AtOption | undefined) => {
  658. if (!x) return ""
  659. if (x.type === "agent") return `agent:${x.name}`
  660. if (x.type === "reference") return `reference:${x.name}`
  661. if (x.type === "resource") return `resource:${x.client}:${x.uri}`
  662. return `file:${x.path}`
  663. }
  664. const {
  665. flat: atFlat,
  666. active: atActive,
  667. setActive: setAtActive,
  668. onInput: atOnInput,
  669. onKeyDown: atOnKeyDown,
  670. } = useFilteredList<AtOption>({
  671. items: async (query) => {
  672. const references = referenceList()
  673. const agents = agentList()
  674. const mcpResources = mcpResourceList()
  675. const open = recent()
  676. const seen = new Set(open)
  677. const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true }))
  678. if (!query.trim()) return [...references, ...agents, ...mcpResources, ...pinned]
  679. const paths = await files.searchFilesAndDirectories(query)
  680. const fileOptions: AtOption[] = paths
  681. .filter((path) => !seen.has(path))
  682. .map((path) => ({ type: "file", path, display: path }))
  683. return [...references, ...agents, ...mcpResources, ...pinned, ...fileOptions]
  684. },
  685. key: atKey,
  686. filterKeys: ["display"],
  687. skipFilter: (item) => item.type === "file" && !item.recent,
  688. groupBy: (item) => {
  689. if (item.type === "reference") return "reference"
  690. if (item.type === "agent") return "agent"
  691. if (item.type === "resource") return "resource"
  692. if (item.recent) return "recent"
  693. return "file"
  694. },
  695. sortGroupsBy: (a, b) => {
  696. const rank = (category: string) => {
  697. if (category === "reference") return 0
  698. if (category === "agent") return 1
  699. if (category === "resource") return 2
  700. if (category === "recent") return 3
  701. return 4
  702. }
  703. return rank(a.category) - rank(b.category)
  704. },
  705. onSelect: handleAtSelect,
  706. })
  707. const slashCommands = createMemo<SlashCommand[]>(() => {
  708. const builtin = command.options
  709. .filter((opt) => !opt.disabled && !opt.id.startsWith("suggested.") && opt.slash)
  710. .map((opt) => ({
  711. id: opt.id,
  712. trigger: opt.slash!,
  713. title: opt.title,
  714. description: opt.description,
  715. keybind: opt.keybind,
  716. type: "builtin" as const,
  717. }))
  718. const custom = sync().data.command.map((cmd) => ({
  719. id: `custom.${cmd.name}`,
  720. trigger: cmd.name,
  721. title: cmd.name,
  722. description: cmd.description,
  723. type: "custom" as const,
  724. source: cmd.source,
  725. }))
  726. return [...custom, ...builtin]
  727. })
  728. const handleSlashSelect = (cmd: SlashCommand | undefined) => {
  729. if (!cmd) return
  730. const menu = store.slashMenu
  731. closePopover()
  732. const images = imageAttachments()
  733. if (cmd.type === "custom") {
  734. const text = `/${cmd.trigger} `
  735. if (menu) {
  736. editorRef.focus()
  737. setCursorPosition(editorRef, 0)
  738. addPart({ type: "text", content: text, start: 0, end: text.length })
  739. focusEditorEnd()
  740. return
  741. }
  742. setEditorText(text)
  743. prompt.set([{ type: "text", content: text, start: 0, end: text.length }, ...images], text.length)
  744. focusEditorEnd()
  745. return
  746. }
  747. if (menu) {
  748. command.trigger(cmd.id, "slash")
  749. return
  750. }
  751. clearEditor()
  752. prompt.set([...DEFAULT_PROMPT, ...images], 0)
  753. command.trigger(cmd.id, "slash")
  754. }
  755. const {
  756. flat: slashFlat,
  757. active: slashActive,
  758. setActive: setSlashActive,
  759. onInput: slashOnInput,
  760. onKeyDown: slashOnKeyDown,
  761. } = useFilteredList<SlashCommand>({
  762. items: slashCommands,
  763. key: (x) => x?.id,
  764. filterKeys: ["trigger", "title"],
  765. onSelect: handleSlashSelect,
  766. })
  767. const createPill = (part: FileAttachmentPart | AgentPart) => {
  768. const pill = document.createElement("span")
  769. pill.textContent = part.content
  770. pill.setAttribute("data-type", part.type)
  771. if (part.type === "file") {
  772. pill.setAttribute("data-path", part.path)
  773. if (part.mime) pill.setAttribute("data-mime", part.mime)
  774. if (part.filename) pill.setAttribute("data-filename", part.filename)
  775. if (part.url) pill.setAttribute("data-url", part.url)
  776. if (part.source?.type === "resource") {
  777. pill.setAttribute("data-source-type", part.source.type)
  778. pill.setAttribute("data-source-client-name", part.source.clientName)
  779. pill.setAttribute("data-source-uri", part.source.uri)
  780. }
  781. }
  782. if (part.type === "agent") pill.setAttribute("data-name", part.name)
  783. pill.setAttribute("contenteditable", "false")
  784. pill.style.userSelect = "text"
  785. pill.style.cursor = "default"
  786. return pill
  787. }
  788. const isNormalizedEditor = () =>
  789. Array.from(editorRef.childNodes).every((node) => {
  790. if (node.nodeType === Node.TEXT_NODE) {
  791. const text = node.textContent ?? ""
  792. if (!text.includes("\u200B")) return true
  793. if (text !== "\u200B") return false
  794. const prev = node.previousSibling
  795. const next = node.nextSibling
  796. const prevIsBr = prev?.nodeType === Node.ELEMENT_NODE && (prev as HTMLElement).tagName === "BR"
  797. return !!prevIsBr && !next
  798. }
  799. if (node.nodeType !== Node.ELEMENT_NODE) return false
  800. const el = node as HTMLElement
  801. if (el.dataset.type === "file") return true
  802. if (el.dataset.type === "agent") return true
  803. return el.tagName === "BR"
  804. })
  805. const renderEditor = (parts: Prompt) => {
  806. clearEditor()
  807. for (const part of parts) {
  808. if (part.type === "text") {
  809. editorRef.appendChild(createTextFragment(part.content))
  810. continue
  811. }
  812. if (part.type === "file" || part.type === "agent") {
  813. editorRef.appendChild(createPill(part))
  814. }
  815. }
  816. const last = editorRef.lastChild
  817. if (last?.nodeType === Node.ELEMENT_NODE && (last as HTMLElement).tagName === "BR") {
  818. editorRef.appendChild(document.createTextNode("\u200B"))
  819. }
  820. }
  821. const scrollSlashActiveIntoView = () => {
  822. const activeId = slashActive()
  823. if (!activeId || !slashPopoverRef) return
  824. requestAnimationFrame(() => {
  825. const element = slashPopoverRef.querySelector(`[data-slash-id="${activeId}"]`)
  826. element?.scrollIntoView({ block: "nearest", behavior: "smooth" })
  827. })
  828. }
  829. const selectPopoverActive = () => {
  830. if (store.popover === "at") {
  831. const items = atFlat()
  832. if (items.length === 0) return
  833. const active = atActive()
  834. const item = items.find((entry) => atKey(entry) === active) ?? items[0]
  835. handleAtSelect(item)
  836. return
  837. }
  838. if (store.popover === "slash") {
  839. const items = slashFlat()
  840. if (items.length === 0) return
  841. const active = slashActive()
  842. const item = items.find((entry) => entry.id === active) ?? items[0]
  843. handleSlashSelect(item)
  844. }
  845. }
  846. const reconcile = (input: Prompt) => {
  847. if (mirror.input) {
  848. mirror.input = false
  849. if (isNormalizedEditor()) return
  850. renderEditorWithCursor(input)
  851. return
  852. }
  853. const dom = parseFromDOM()
  854. if (isNormalizedEditor() && isPromptEqual(input, dom)) return
  855. renderEditorWithCursor(input)
  856. }
  857. createEffect(
  858. on(
  859. () => prompt.current(),
  860. (parts) => {
  861. if (composing()) return
  862. reconcile(parts.filter((part) => part.type !== "image"))
  863. },
  864. ),
  865. )
  866. const parseFromDOM = (): Prompt => {
  867. const parts: Prompt = []
  868. let position = 0
  869. let buffer = ""
  870. const flushText = () => {
  871. let content = buffer
  872. if (content.includes("\r")) content = content.replace(/\r\n?/g, "\n")
  873. if (content.includes("\u200B")) content = content.replace(/\u200B/g, "")
  874. buffer = ""
  875. if (!content) return
  876. parts.push({ type: "text", content, start: position, end: position + content.length })
  877. position += content.length
  878. }
  879. const pushFile = (file: HTMLElement) => {
  880. const content = file.textContent ?? ""
  881. const source =
  882. file.dataset.sourceType === "resource" && file.dataset.sourceClientName && file.dataset.sourceUri
  883. ? {
  884. type: "resource" as const,
  885. text: {
  886. value: content,
  887. start: position,
  888. end: position + content.length,
  889. },
  890. clientName: file.dataset.sourceClientName,
  891. uri: file.dataset.sourceUri,
  892. }
  893. : undefined
  894. parts.push({
  895. type: "file",
  896. path: file.dataset.path!,
  897. content,
  898. start: position,
  899. end: position + content.length,
  900. ...(file.dataset.mime ? { mime: file.dataset.mime } : {}),
  901. ...(file.dataset.filename ? { filename: file.dataset.filename } : {}),
  902. ...(file.dataset.url ? { url: file.dataset.url } : {}),
  903. ...(source ? { source } : {}),
  904. })
  905. position += content.length
  906. }
  907. const pushAgent = (agent: HTMLElement) => {
  908. const content = agent.textContent ?? ""
  909. parts.push({
  910. type: "agent",
  911. name: agent.dataset.name!,
  912. content,
  913. start: position,
  914. end: position + content.length,
  915. })
  916. position += content.length
  917. }
  918. const visit = (node: Node) => {
  919. if (node.nodeType === Node.TEXT_NODE) {
  920. buffer += node.textContent ?? ""
  921. return
  922. }
  923. if (node.nodeType !== Node.ELEMENT_NODE) return
  924. const el = node as HTMLElement
  925. if (el.dataset.type === "file") {
  926. flushText()
  927. pushFile(el)
  928. return
  929. }
  930. if (el.dataset.type === "agent") {
  931. flushText()
  932. pushAgent(el)
  933. return
  934. }
  935. if (el.tagName === "BR") {
  936. buffer += "\n"
  937. return
  938. }
  939. for (const child of Array.from(el.childNodes)) {
  940. visit(child)
  941. }
  942. }
  943. const children = Array.from(editorRef.childNodes)
  944. children.forEach((child, index) => {
  945. const isBlock = child.nodeType === Node.ELEMENT_NODE && ["DIV", "P"].includes((child as HTMLElement).tagName)
  946. visit(child)
  947. if (isBlock && index < children.length - 1) {
  948. buffer += "\n"
  949. }
  950. })
  951. flushText()
  952. if (parts.length === 0) parts.push(...DEFAULT_PROMPT)
  953. return parts
  954. }
  955. const handleInput = () => {
  956. const rawParts = parseFromDOM()
  957. const images = imageAttachments()
  958. const cursorPosition = getCursorPosition(editorRef)
  959. const rawText =
  960. rawParts.length === 1 && rawParts[0]?.type === "text"
  961. ? rawParts[0].content
  962. : rawParts.map((p) => ("content" in p ? p.content : "")).join("")
  963. const hasNonText = rawParts.some((part) => part.type !== "text")
  964. const textContent = (editorRef.textContent ?? "").replace(/\u200B/g, "")
  965. const shouldReset =
  966. textContent.length === 0 && rawText.replace(/\n/g, "").length === 0 && !hasNonText && images.length === 0
  967. if (shouldReset) {
  968. closePopover()
  969. resetHistoryNavigation()
  970. if (prompt.dirty()) {
  971. mirror.input = true
  972. prompt.set(DEFAULT_PROMPT, 0)
  973. }
  974. queueScroll()
  975. return
  976. }
  977. const shellMode = store.mode === "shell"
  978. if (!shellMode) {
  979. const atMatch = rawText.substring(0, cursorPosition).match(/@(\S*)$/)
  980. const slashMatch = rawText.match(/^\/(\S*)$/)
  981. if (atMatch) {
  982. atOnInput(atMatch[1])
  983. setStore({ popover: "at", slashMenu: false, slashMenuQuery: "" })
  984. } else if (slashMatch) {
  985. slashOnInput(slashMatch[1])
  986. setStore({ popover: "slash", slashMenu: false, slashMenuQuery: "" })
  987. } else {
  988. closePopover()
  989. }
  990. } else {
  991. closePopover()
  992. }
  993. resetHistoryNavigation()
  994. mirror.input = true
  995. prompt.set([...rawParts, ...images], cursorPosition)
  996. queueScroll()
  997. }
  998. const addPart = (part: ContentPart) => {
  999. if (part.type === "image") return false
  1000. const selection = window.getSelection()
  1001. if (!selection) return false
  1002. if (selection.rangeCount === 0 || !editorRef.contains(selection.anchorNode)) {
  1003. editorRef.focus()
  1004. const cursor = prompt.cursor() ?? promptLength(prompt.current())
  1005. setCursorPosition(editorRef, cursor)
  1006. }
  1007. if (selection.rangeCount === 0) return false
  1008. const range = selection.getRangeAt(0)
  1009. if (!editorRef.contains(range.startContainer)) return false
  1010. if (part.type === "file" || part.type === "agent") {
  1011. const cursorPosition = getCursorPosition(editorRef)
  1012. const rawText = prompt
  1013. .current()
  1014. .map((p) => ("content" in p ? p.content : ""))
  1015. .join("")
  1016. const textBeforeCursor = rawText.substring(0, cursorPosition)
  1017. const atMatch = textBeforeCursor.match(/@(\S*)$/)
  1018. const pill = createPill(part)
  1019. const gap = document.createTextNode(" ")
  1020. if (atMatch) {
  1021. const start = atMatch.index ?? cursorPosition - atMatch[0].length
  1022. setRangeEdge(editorRef, range, "start", start)
  1023. setRangeEdge(editorRef, range, "end", cursorPosition)
  1024. }
  1025. range.deleteContents()
  1026. range.insertNode(gap)
  1027. range.insertNode(pill)
  1028. range.setStartAfter(gap)
  1029. range.collapse(true)
  1030. selection.removeAllRanges()
  1031. selection.addRange(range)
  1032. }
  1033. if (part.type === "text") {
  1034. const fragment = createTextFragment(part.content)
  1035. const last = fragment.lastChild
  1036. range.deleteContents()
  1037. range.insertNode(fragment)
  1038. if (last) {
  1039. if (last.nodeType === Node.TEXT_NODE) {
  1040. const text = last.textContent ?? ""
  1041. if (text === "\u200B") {
  1042. range.setStart(last, 0)
  1043. }
  1044. if (text !== "\u200B") {
  1045. range.setStart(last, text.length)
  1046. }
  1047. }
  1048. if (last.nodeType !== Node.TEXT_NODE) {
  1049. const isBreak = last.nodeType === Node.ELEMENT_NODE && (last as HTMLElement).tagName === "BR"
  1050. const next = last.nextSibling
  1051. const emptyText = next?.nodeType === Node.TEXT_NODE && (next.textContent ?? "") === ""
  1052. if (isBreak && (!next || emptyText)) {
  1053. const placeholder = next && emptyText ? next : document.createTextNode("\u200B")
  1054. if (!next) last.parentNode?.insertBefore(placeholder, null)
  1055. placeholder.textContent = "\u200B"
  1056. range.setStart(placeholder, 0)
  1057. } else {
  1058. range.setStartAfter(last)
  1059. }
  1060. }
  1061. }
  1062. range.collapse(true)
  1063. selection.removeAllRanges()
  1064. selection.addRange(range)
  1065. }
  1066. handleInput()
  1067. closePopover()
  1068. return true
  1069. }
  1070. const openCommands = () => {
  1071. const populated = prompt.dirty() || commentCount() > 0
  1072. requestAnimationFrame(() => {
  1073. if (!populated) {
  1074. if (!addPart({ type: "text", content: "/", start: 0, end: 0 })) return
  1075. slashOnInput("")
  1076. setStore({ popover: "slash", slashMenu: false, slashMenuQuery: "" })
  1077. return
  1078. }
  1079. slashOnInput("")
  1080. setStore({ popover: "slash", slashMenu: true, slashMenuQuery: "" })
  1081. })
  1082. }
  1083. const openContext = () => {
  1084. requestAnimationFrame(() => {
  1085. if (!addPart({ type: "text", content: "@", start: 0, end: 0 })) return
  1086. atOnInput("")
  1087. setStore({ popover: "at", slashMenu: false, slashMenuQuery: "" })
  1088. })
  1089. }
  1090. const addToHistory = (prompt: Prompt, mode: "normal" | "shell") => {
  1091. history.add(prompt, mode, mode === "shell" ? [] : historyComments())
  1092. }
  1093. createEffect(
  1094. on(
  1095. () => props.edit?.id,
  1096. (id) => {
  1097. const edit = props.edit
  1098. if (!id || !edit) return
  1099. for (const item of prompt.context.items()) {
  1100. prompt.context.remove(item.key)
  1101. }
  1102. for (const item of edit.context) {
  1103. prompt.context.add({
  1104. type: item.type,
  1105. path: item.path,
  1106. selection: item.selection,
  1107. comment: item.comment,
  1108. commentID: item.commentID,
  1109. commentOrigin: item.commentOrigin,
  1110. preview: item.preview,
  1111. })
  1112. }
  1113. setStore("mode", "normal")
  1114. closePopover()
  1115. setStore("historyIndex", -1)
  1116. setStore("savedPrompt", null)
  1117. prompt.set(edit.prompt, promptLength(edit.prompt))
  1118. requestAnimationFrame(() => {
  1119. editorRef.focus()
  1120. setCursorPosition(editorRef, promptLength(edit.prompt))
  1121. queueScroll()
  1122. })
  1123. props.onEditLoaded?.()
  1124. },
  1125. { defer: true },
  1126. ),
  1127. )
  1128. const navigateHistory = (direction: "up" | "down") => {
  1129. const result = navigatePromptHistory({
  1130. direction,
  1131. entries: history.entries(store.mode),
  1132. historyIndex: store.historyIndex,
  1133. currentPrompt: prompt.current(),
  1134. currentComments: historyComments(),
  1135. savedPrompt: store.savedPrompt,
  1136. })
  1137. if (!result.handled) return false
  1138. setStore("historyIndex", result.historyIndex)
  1139. setStore("savedPrompt", result.savedPrompt)
  1140. applyHistoryPrompt(result.entry, result.cursor)
  1141. return true
  1142. }
  1143. const { addAttachment, addAttachments, removeAttachment, handlePaste } = createPromptAttachments({
  1144. prompt,
  1145. editor: () => editorRef,
  1146. isDialogActive: () => !!dialog.active,
  1147. setDraggingType: (type) => setStore("draggingType", type),
  1148. focusEditor: () => {
  1149. editorRef.focus()
  1150. setCursorPosition(editorRef, promptLength(prompt.current()))
  1151. },
  1152. addPart,
  1153. readClipboardImage: platform.readClipboardImage,
  1154. getPathForFile: platform.getPathForFile,
  1155. })
  1156. const fileAttachmentInput = () => (
  1157. <input
  1158. ref={(el) => (fileInputRef = el)}
  1159. type="file"
  1160. multiple
  1161. accept={ACCEPTED_FILE_TYPES.join(",")}
  1162. class="hidden"
  1163. onChange={(e) => {
  1164. const list = e.currentTarget.files
  1165. if (list) void addAttachments(Array.from(list))
  1166. e.currentTarget.value = ""
  1167. }}
  1168. />
  1169. )
  1170. const variants = createMemo(() => ["default", ...props.controls.model.selection.variant.list()])
  1171. // Check provider variants directly: `variants` also includes the UI-only default option.
  1172. const showVariantControl = createMemo(() => props.controls.model.selection.variant.list().length > 0)
  1173. const accepting = createMemo(() => {
  1174. const id = props.controls.session.id
  1175. if (!id) return permission.isAutoAcceptingDirectory(sdk().directory)
  1176. return permission.isAutoAccepting(id, sdk().directory)
  1177. })
  1178. const { abort, handleSubmit } =
  1179. props.submission ??
  1180. createPromptSubmit({
  1181. prompt,
  1182. info,
  1183. imageAttachments,
  1184. commentCount,
  1185. autoAccept: () => accepting(),
  1186. mode: () => store.mode,
  1187. working,
  1188. editor: () => editorRef,
  1189. queueScroll,
  1190. promptLength,
  1191. addToHistory,
  1192. resetHistoryNavigation: () => {
  1193. resetHistoryNavigation(true)
  1194. },
  1195. setMode: (mode) => setStore("mode", mode),
  1196. setPopover: (popover) => {
  1197. if (!popover) return closePopover()
  1198. setStore({ popover, slashMenu: false, slashMenuQuery: "" })
  1199. },
  1200. newSessionWorktree: () => props.newSessionWorktree,
  1201. onNewSessionWorktreeReset: props.onNewSessionWorktreeReset,
  1202. shouldQueue: props.shouldQueue,
  1203. onQueue: props.onQueue,
  1204. onAbort: props.onAbort,
  1205. onSubmit: props.onSubmit,
  1206. model: props.controls.model.selection,
  1207. })
  1208. const handleKeyDown = (event: KeyboardEvent) => {
  1209. if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "u") {
  1210. event.preventDefault()
  1211. if (store.mode !== "normal") return
  1212. pick()
  1213. return
  1214. }
  1215. if (event.key === "Backspace") {
  1216. const selection = window.getSelection()
  1217. if (selection && selection.isCollapsed) {
  1218. const node = selection.anchorNode
  1219. const offset = selection.anchorOffset
  1220. if (node && node.nodeType === Node.TEXT_NODE) {
  1221. const text = node.textContent ?? ""
  1222. if (/^\u200B+$/.test(text) && offset > 0) {
  1223. const range = document.createRange()
  1224. range.setStart(node, 0)
  1225. range.collapse(true)
  1226. selection.removeAllRanges()
  1227. selection.addRange(range)
  1228. }
  1229. }
  1230. }
  1231. }
  1232. if (event.key === "!" && store.mode === "normal") {
  1233. const cursorPosition = getCursorPosition(editorRef)
  1234. if (cursorPosition === 0) {
  1235. setStore("mode", "shell")
  1236. closePopover()
  1237. event.preventDefault()
  1238. return
  1239. }
  1240. }
  1241. if (event.key === "Escape") {
  1242. if (store.popover) {
  1243. closePopover()
  1244. event.preventDefault()
  1245. event.stopPropagation()
  1246. return
  1247. }
  1248. if (store.mode === "shell") {
  1249. setStore("mode", "normal")
  1250. event.preventDefault()
  1251. event.stopPropagation()
  1252. return
  1253. }
  1254. if (working()) {
  1255. void abort()
  1256. event.preventDefault()
  1257. event.stopPropagation()
  1258. return
  1259. }
  1260. if (escBlur()) {
  1261. editorRef.blur()
  1262. event.preventDefault()
  1263. event.stopPropagation()
  1264. return
  1265. }
  1266. }
  1267. if (store.mode === "shell") {
  1268. const { collapsed, cursorPosition, textLength } = getCaretState()
  1269. if (event.key === "Backspace" && collapsed && cursorPosition === 0 && textLength === 0) {
  1270. setStore("mode", "normal")
  1271. event.preventDefault()
  1272. return
  1273. }
  1274. }
  1275. // Handle Shift+Enter BEFORE IME check - Shift+Enter is never used for IME input
  1276. // and should always insert a newline regardless of composition state
  1277. if (event.key === "Enter" && event.shiftKey) {
  1278. addPart({ type: "text", content: "\n", start: 0, end: 0 })
  1279. event.preventDefault()
  1280. return
  1281. }
  1282. if (event.key === "Enter" && isImeComposing(event)) {
  1283. return
  1284. }
  1285. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  1286. if (store.popover) {
  1287. if (event.key === "Tab") {
  1288. selectPopoverActive()
  1289. event.preventDefault()
  1290. return
  1291. }
  1292. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  1293. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  1294. if (nav || ctrlNav) {
  1295. if (store.popover === "at") {
  1296. atOnKeyDown(event)
  1297. event.preventDefault()
  1298. return
  1299. }
  1300. if (store.popover === "slash") {
  1301. slashOnKeyDown(event)
  1302. if (event.key === "ArrowUp" || event.key === "ArrowDown" || ctrlNav) {
  1303. scrollSlashActiveIntoView()
  1304. }
  1305. }
  1306. event.preventDefault()
  1307. return
  1308. }
  1309. }
  1310. if (ctrl && event.code === "KeyG") {
  1311. if (store.popover) {
  1312. closePopover()
  1313. event.preventDefault()
  1314. return
  1315. }
  1316. if (working()) {
  1317. void abort()
  1318. event.preventDefault()
  1319. }
  1320. return
  1321. }
  1322. if (event.key === "ArrowUp" || event.key === "ArrowDown") {
  1323. if (event.altKey || event.ctrlKey || event.metaKey) return
  1324. const { collapsed } = getCaretState()
  1325. if (!collapsed) return
  1326. const cursorPosition = getCursorPosition(editorRef)
  1327. const textContent = prompt
  1328. .current()
  1329. .map((part) => ("content" in part ? part.content : ""))
  1330. .join("")
  1331. const direction = event.key === "ArrowUp" ? "up" : "down"
  1332. if (!canNavigateHistoryAtCursor(direction, textContent, cursorPosition, store.historyIndex >= 0)) return
  1333. if (navigateHistory(direction)) {
  1334. event.preventDefault()
  1335. }
  1336. return
  1337. }
  1338. // Note: Shift+Enter is handled earlier, before IME check
  1339. if (event.key === "Enter" && !event.shiftKey) {
  1340. event.preventDefault()
  1341. if (event.repeat) return
  1342. if (
  1343. working() &&
  1344. prompt
  1345. .current()
  1346. .map((part) => ("content" in part ? part.content : ""))
  1347. .join("")
  1348. .trim().length === 0 &&
  1349. imageAttachments().length === 0 &&
  1350. commentCount() === 0
  1351. ) {
  1352. return
  1353. }
  1354. void handleSubmit(event)
  1355. }
  1356. }
  1357. const handleSlashMenuKeyDown = (event: KeyboardEvent) => {
  1358. if (event.key === "Escape") {
  1359. closePopover()
  1360. requestAnimationFrame(() => editorRef.focus())
  1361. event.preventDefault()
  1362. return
  1363. }
  1364. if (event.key === "Tab") {
  1365. selectPopoverActive()
  1366. event.preventDefault()
  1367. return
  1368. }
  1369. const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
  1370. const nav = event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"
  1371. const ctrlNav = ctrl && (event.key === "n" || event.key === "p")
  1372. if (!nav && !ctrlNav) return
  1373. slashOnKeyDown(event)
  1374. if (event.key === "ArrowUp" || event.key === "ArrowDown" || ctrlNav) scrollSlashActiveIntoView()
  1375. event.preventDefault()
  1376. }
  1377. const agentsLoading = () => props.controls.agents.loading
  1378. const agentsShouldFadeIn = createMemo<boolean>((prev) => prev ?? agentsLoading())
  1379. const providersLoading = () => props.controls.model.loading
  1380. const providersShouldFadeIn = createMemo<boolean>((prev) => prev ?? providersLoading())
  1381. const [promptReady] = createResource(
  1382. () => prompt.ready.promise,
  1383. (p) => p,
  1384. )
  1385. const designPlaceholder = () => {
  1386. if (store.mode === "shell") return placeholder()
  1387. return "Ask anything, / for commands, @ for context..."
  1388. }
  1389. const modelControlState = createMemo<ComposerModelControlState>(() => ({
  1390. loading: providersLoading(),
  1391. shouldAnimate: providersShouldFadeIn(),
  1392. paid: props.controls.model.paid,
  1393. title: language.t("command.model.choose"),
  1394. keybind: command.keybindParts("model.choose"),
  1395. model: props.controls.model.selection,
  1396. providerID: props.controls.model.selection.current()?.provider?.id,
  1397. modelName: props.controls.model.selection.current()?.name ?? language.t("dialog.model.select.title"),
  1398. newLayoutDesigns: props.controls.newLayoutDesigns,
  1399. style: control(),
  1400. onClose: restoreFocus,
  1401. onUnpaidClick: () => {
  1402. if (props.controls.newLayoutDesigns) {
  1403. dialog.show(() => <DialogSelectModelUnpaidV2 model={props.controls.model.selection} />)
  1404. return
  1405. }
  1406. dialog.show(() => <DialogSelectModelUnpaid model={props.controls.model.selection} />)
  1407. },
  1408. }))
  1409. const newSession = () => props.variant === "new-session"
  1410. const bindEditorRef = (el: HTMLDivElement) => {
  1411. editorRef = el
  1412. restoreEndOnFocus = true
  1413. props.ref?.(el)
  1414. }
  1415. const showAgentControl = createMemo(() => props.controls.agents.visible && props.controls.agents.options.length > 0)
  1416. const agentControlState = createMemo<ComposerAgentControlState>(() => ({
  1417. title: language.t("command.agent.cycle"),
  1418. keybind: command.keybindParts("agent.cycle"),
  1419. options: props.controls.agents.options,
  1420. current: props.controls.agents.current,
  1421. style: control(),
  1422. onSelect: (value) => {
  1423. props.controls.agents.select(value)
  1424. restoreFocus()
  1425. },
  1426. }))
  1427. return (
  1428. <div class="relative size-full flex flex-col gap-0">
  1429. {(promptReady(), null)}
  1430. <PromptPopover
  1431. popover={store.popover}
  1432. setSlashPopoverRef={(el) => (slashPopoverRef = el)}
  1433. atFlat={atFlat()}
  1434. atActive={atActive() ?? undefined}
  1435. atKey={atKey}
  1436. setAtActive={setAtActive}
  1437. onAtSelect={handleAtSelect}
  1438. slashFlat={slashFlat()}
  1439. slashActive={slashActive() ?? undefined}
  1440. setSlashActive={setSlashActive}
  1441. onSlashSelect={handleSlashSelect}
  1442. slashMenu={store.slashMenu}
  1443. slashMenuQuery={store.slashMenuQuery}
  1444. onSlashMenuInput={(value) => {
  1445. setStore("slashMenuQuery", value)
  1446. slashOnInput(value)
  1447. }}
  1448. onSlashMenuKeyDown={handleSlashMenuKeyDown}
  1449. commandKeybind={command.keybind}
  1450. commandKeybindParts={command.keybindParts}
  1451. newLayoutDesigns={props.controls.newLayoutDesigns}
  1452. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  1453. />
  1454. <Switch>
  1455. <Match when={props.controls.newLayoutDesigns}>
  1456. <div class="flex flex-col gap-3">
  1457. <DockShellForm
  1458. data-component={newSession() ? "session-new-composer" : "session-composer"}
  1459. onSubmit={handleSubmit}
  1460. classList={{
  1461. "group/prompt-input min-h-[96px] w-full rounded-xl bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)]": true,
  1462. "border-icon-info-active border-dashed": store.draggingType !== null,
  1463. [props.class ?? ""]: !!props.class,
  1464. }}
  1465. >
  1466. <PromptDragOverlay
  1467. type={store.draggingType}
  1468. label={language.t(
  1469. store.draggingType === "@mention" ? "prompt.dropzone.file.label" : "prompt.dropzone.label",
  1470. )}
  1471. />
  1472. <PromptContextItems
  1473. items={contextItems()}
  1474. active={(item) => {
  1475. const active = comments.active()
  1476. return !!item.commentID && item.commentID === active?.id && item.path === active?.file
  1477. }}
  1478. openComment={openComment}
  1479. remove={(item) => {
  1480. if (item.commentID) comments.remove(item.path, item.commentID)
  1481. prompt.context.remove(item.key)
  1482. }}
  1483. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  1484. />
  1485. <PromptImageAttachments
  1486. attachments={imageAttachments()}
  1487. onOpen={(attachment) =>
  1488. dialog.show(() => <ImagePreview src={attachment.dataUrl} alt={attachment.filename} />)
  1489. }
  1490. onRemove={removeAttachment}
  1491. removeLabel={language.t("prompt.attachment.remove")}
  1492. />
  1493. <div
  1494. class="relative min-h-[52px]"
  1495. onMouseDown={(e) => {
  1496. const target = e.target
  1497. if (!(target instanceof HTMLElement)) return
  1498. if (target.closest('[data-action^="prompt-"]')) return
  1499. editorRef?.focus()
  1500. }}
  1501. >
  1502. <div class="relative max-h-[180px] overflow-y-auto no-scrollbar" ref={(el) => (scrollRef = el)}>
  1503. <div
  1504. data-component="prompt-input"
  1505. ref={bindEditorRef}
  1506. role="textbox"
  1507. aria-multiline="true"
  1508. aria-label={designPlaceholder()}
  1509. contenteditable="true"
  1510. autocapitalize={store.mode === "normal" ? "sentences" : "off"}
  1511. autocorrect={store.mode === "normal" ? "on" : "off"}
  1512. spellcheck={store.mode === "normal"}
  1513. inputMode="text"
  1514. // @ts-expect-error
  1515. autocomplete="off"
  1516. onInput={handleInput}
  1517. onPaste={handlePaste}
  1518. onCompositionStart={handleCompositionStart}
  1519. onCompositionEnd={handleCompositionEnd}
  1520. onFocus={handleFocus}
  1521. onBlur={handleBlur}
  1522. onKeyDown={handleKeyDown}
  1523. classList={{
  1524. "select-text": true,
  1525. "min-h-[52px] w-full px-4 pt-4 pb-2 focus:outline-none whitespace-pre-wrap leading-5 text-[13px] font-[440] text-v2-text-text-base": true,
  1526. "[&_[data-type=file]]:text-syntax-property": true,
  1527. "[&_[data-type=agent]]:text-syntax-type": true,
  1528. "font-mono!": store.mode === "shell",
  1529. }}
  1530. />
  1531. <div
  1532. data-component={newSession() ? "session-new-design-text" : "session-composer-text"}
  1533. class="absolute top-0 inset-x-0 px-4 pt-4 pointer-events-none whitespace-nowrap truncate leading-5 text-[13px] font-[440] text-v2-text-text-faint [font-family:Inter,var(--font-family-sans)]"
  1534. classList={{ "font-mono!": store.mode === "shell", hidden: prompt.dirty() }}
  1535. >
  1536. {designPlaceholder()}
  1537. </div>
  1538. </div>
  1539. </div>
  1540. <div class="flex h-11 items-center px-2">
  1541. <div class="flex min-w-0 flex-1 items-center gap-1">
  1542. {fileAttachmentInput()}
  1543. <TooltipV2
  1544. placement="top"
  1545. value={
  1546. <>
  1547. {language.t("prompt.menu.addImagesAndFiles")}
  1548. <KeybindV2 keys={command.keybindParts("file.attach")} variant="neutral" />
  1549. </>
  1550. }
  1551. >
  1552. <MenuV2 gutter={6} modal={false} placement="top-start">
  1553. <MenuV2.Trigger
  1554. as={IconButtonV2}
  1555. data-action="prompt-attach"
  1556. type="button"
  1557. icon={<IconV2 name="plus" />}
  1558. variant="ghost-muted"
  1559. size="large"
  1560. style={buttons()}
  1561. disabled={store.mode !== "normal"}
  1562. tabIndex={store.mode === "normal" ? undefined : -1}
  1563. aria-label={language.t("prompt.menu.addImagesAndFiles")}
  1564. />
  1565. <MenuV2.Portal>
  1566. <MenuV2.Content style={{ "min-width": "180px" }}>
  1567. <MenuV2.Item onSelect={pick} shortcut={command.keybind("file.attach")}>
  1568. {language.t("prompt.menu.imagesAndFiles")}
  1569. </MenuV2.Item>
  1570. <MenuV2.Separator />
  1571. <MenuV2.Item onSelect={openCommands} shortcut="/">
  1572. {language.t("prompt.menu.commands")}
  1573. </MenuV2.Item>
  1574. <MenuV2.Item onSelect={openContext} shortcut="@">
  1575. {language.t("prompt.menu.context")}
  1576. </MenuV2.Item>
  1577. <MenuV2.Item onSelect={() => setMode("shell")} shortcut="!">
  1578. {language.t("prompt.menu.shellCommand")}
  1579. </MenuV2.Item>
  1580. </MenuV2.Content>
  1581. </MenuV2.Portal>
  1582. </MenuV2>
  1583. </TooltipV2>
  1584. <Show when={showAgentControl()}>
  1585. <ComposerAgentControl state={agentControlState()} />
  1586. </Show>
  1587. {props.toolbar}
  1588. <ComposerModelControl state={modelControlState()} />
  1589. <Show when={!providersLoading() && store.mode !== "shell" && showVariantControl()}>
  1590. <div
  1591. data-component="prompt-variant-control"
  1592. class="[&_[data-action=prompt-model-variant]]:![font-weight:440]"
  1593. classList={{
  1594. "animate-in fade-in": providersShouldFadeIn(),
  1595. "hidden group-hover/prompt-input:block group-focus-within/prompt-input:block":
  1596. !props.controls.model.selection.variant.current() && !store.variantOpen,
  1597. }}
  1598. >
  1599. <TooltipV2
  1600. placement="top"
  1601. gutter={4}
  1602. value={
  1603. <>
  1604. {language.t("command.model.variant.cycle")}
  1605. <KeybindV2 keys={command.keybindParts("model.variant.cycle")} variant="neutral" />
  1606. </>
  1607. }
  1608. >
  1609. <MenuV2
  1610. gutter={6}
  1611. modal={false}
  1612. placement="top-start"
  1613. onOpenChange={(open) => setStore("variantOpen", open)}
  1614. >
  1615. <MenuV2.Trigger
  1616. as={ButtonV2}
  1617. data-action="prompt-model-variant"
  1618. variant="ghost-muted"
  1619. size="normal"
  1620. class="max-w-[160px] justify-start capitalize"
  1621. style={control()}
  1622. >
  1623. <span class="truncate leading-5">
  1624. {props.controls.model.selection.variant.current() ?? language.t("common.default")}
  1625. </span>
  1626. <span class="-ml-0.5 -mr-1 flex shrink-0">
  1627. <Icon name="chevron-down" size="small" />
  1628. </span>
  1629. </MenuV2.Trigger>
  1630. <MenuV2.Portal>
  1631. <MenuV2.Content>
  1632. <MenuV2.RadioGroup
  1633. value={props.controls.model.selection.variant.current() ?? "default"}
  1634. onChange={(value) => {
  1635. props.controls.model.selection.variant.set(value === "default" ? undefined : value)
  1636. restoreFocus()
  1637. }}
  1638. >
  1639. {variants().map((value) => (
  1640. <MenuV2.RadioItem value={value} class="capitalize">
  1641. {value === "default" ? language.t("common.default") : value}
  1642. </MenuV2.RadioItem>
  1643. ))}
  1644. </MenuV2.RadioGroup>
  1645. </MenuV2.Content>
  1646. </MenuV2.Portal>
  1647. </MenuV2>
  1648. </TooltipV2>
  1649. </div>
  1650. </Show>
  1651. </div>
  1652. <TooltipV2 placement="top" inactive={!working() && blank()} value={tip()}>
  1653. <IconButton
  1654. data-action="prompt-submit"
  1655. type="submit"
  1656. disabled={!working() && blank()}
  1657. tabIndex={store.mode === "normal" ? undefined : -1}
  1658. icon={stopping() ? "stop" : store.mode === "shell" ? "arrow-undo-down" : "arrow-up"}
  1659. variant="primary"
  1660. class="size-7 rounded-md p-[6px] text-v2-icon-icon-muted shadow-[var(--v2-elevation-button-contrast)] disabled:opacity-50"
  1661. style={{
  1662. "background-image":
  1663. "linear-gradient(180deg,var(--v2-alpha-light-20) 0%,var(--v2-alpha-light-0) 100%),linear-gradient(90deg,var(--v2-background-bg-contrast) 0%,var(--v2-background-bg-contrast) 100%)",
  1664. }}
  1665. aria-label={stopping() ? language.t("prompt.action.stop") : language.t("prompt.action.send")}
  1666. />
  1667. </TooltipV2>
  1668. </div>
  1669. </DockShellForm>
  1670. </div>
  1671. </Match>
  1672. <Match when>
  1673. <DockShellForm
  1674. onSubmit={handleSubmit}
  1675. classList={{
  1676. "group/prompt-input": true,
  1677. "focus-within:shadow-xs-border": true,
  1678. "border-icon-info-active border-dashed": store.draggingType !== null,
  1679. [props.class ?? ""]: !!props.class,
  1680. }}
  1681. >
  1682. <PromptDragOverlay
  1683. type={store.draggingType}
  1684. label={language.t(
  1685. store.draggingType === "@mention" ? "prompt.dropzone.file.label" : "prompt.dropzone.label",
  1686. )}
  1687. />
  1688. <PromptContextItems
  1689. items={contextItems()}
  1690. active={(item) => {
  1691. const active = comments.active()
  1692. return !!item.commentID && item.commentID === active?.id && item.path === active?.file
  1693. }}
  1694. openComment={openComment}
  1695. remove={(item) => {
  1696. if (item.commentID) comments.remove(item.path, item.commentID)
  1697. prompt.context.remove(item.key)
  1698. }}
  1699. t={(key) => language.t(key as Parameters<typeof language.t>[0])}
  1700. />
  1701. <PromptImageAttachments
  1702. attachments={imageAttachments()}
  1703. onOpen={(attachment) =>
  1704. dialog.show(() => <ImagePreview src={attachment.dataUrl} alt={attachment.filename} />)
  1705. }
  1706. onRemove={removeAttachment}
  1707. removeLabel={language.t("prompt.attachment.remove")}
  1708. />
  1709. <div
  1710. class="relative"
  1711. onMouseDown={(e) => {
  1712. const target = e.target
  1713. if (!(target instanceof HTMLElement)) return
  1714. if (target.closest('[data-action="prompt-attach"], [data-action="prompt-submit"]')) {
  1715. return
  1716. }
  1717. editorRef?.focus()
  1718. }}
  1719. >
  1720. <div
  1721. class="relative max-h-[240px] overflow-y-auto no-scrollbar"
  1722. ref={(el) => (scrollRef = el)}
  1723. style={{ "scroll-padding-bottom": space }}
  1724. >
  1725. <div
  1726. data-component="prompt-input"
  1727. ref={bindEditorRef}
  1728. role="textbox"
  1729. aria-multiline="true"
  1730. aria-label={placeholder()}
  1731. contenteditable="true"
  1732. autocapitalize={store.mode === "normal" ? "sentences" : "off"}
  1733. autocorrect={store.mode === "normal" ? "on" : "off"}
  1734. spellcheck={store.mode === "normal"}
  1735. inputMode="text"
  1736. // @ts-expect-error
  1737. autocomplete="off"
  1738. onInput={handleInput}
  1739. onPaste={handlePaste}
  1740. onCompositionStart={handleCompositionStart}
  1741. onCompositionEnd={handleCompositionEnd}
  1742. onFocus={handleFocus}
  1743. onBlur={handleBlur}
  1744. onKeyDown={handleKeyDown}
  1745. classList={{
  1746. "select-text": true,
  1747. "w-full pl-3 pr-2 pt-2 text-14-regular text-text-strong focus:outline-none whitespace-pre-wrap": true,
  1748. "[&_[data-type=file]]:text-syntax-property": true,
  1749. "[&_[data-type=agent]]:text-syntax-type": true,
  1750. "font-mono!": store.mode === "shell",
  1751. }}
  1752. style={{ "padding-bottom": space }}
  1753. />
  1754. <div
  1755. class="absolute top-0 inset-x-0 pl-3 pr-2 pt-2 text-14-regular text-text-weak pointer-events-none whitespace-nowrap truncate"
  1756. classList={{ "font-mono!": store.mode === "shell" }}
  1757. style={{ "padding-bottom": space, display: prompt.dirty() ? "none" : undefined }}
  1758. >
  1759. {placeholder()}
  1760. </div>
  1761. </div>
  1762. <div
  1763. aria-hidden="true"
  1764. class="pointer-events-none absolute inset-x-0 bottom-0"
  1765. style={{
  1766. height: space,
  1767. background:
  1768. "linear-gradient(to top, var(--surface-raised-stronger-non-alpha) calc(100% - 20px), transparent)",
  1769. }}
  1770. />
  1771. <div class="pointer-events-none absolute bottom-2 right-2 flex items-center gap-2">
  1772. <input
  1773. ref={fileInputRef}
  1774. type="file"
  1775. multiple
  1776. accept={ACCEPTED_FILE_TYPES.join(",")}
  1777. class="hidden"
  1778. onChange={(e) => {
  1779. const list = e.currentTarget.files
  1780. if (list) void addAttachments(Array.from(list))
  1781. e.currentTarget.value = ""
  1782. }}
  1783. />
  1784. <div class="flex items-center gap-1 pointer-events-auto">
  1785. <Tooltip placement="top" inactive={!working() && blank()} value={tip()}>
  1786. <IconButton
  1787. data-action="prompt-submit"
  1788. type="submit"
  1789. disabled={!working() && blank()}
  1790. tabIndex={store.mode === "normal" ? undefined : -1}
  1791. icon={stopping() ? "stop" : store.mode === "shell" ? "arrow-undo-down" : "arrow-up"}
  1792. variant="primary"
  1793. class="size-8"
  1794. aria-label={stopping() ? language.t("prompt.action.stop") : language.t("prompt.action.send")}
  1795. />
  1796. </Tooltip>
  1797. </div>
  1798. </div>
  1799. <div class="pointer-events-none absolute bottom-2 left-2">
  1800. <div
  1801. aria-hidden={store.mode !== "normal"}
  1802. class="pointer-events-auto"
  1803. style={{
  1804. "pointer-events": buttonsSpring() > 0.5 ? "auto" : "none",
  1805. }}
  1806. >
  1807. <TooltipKeybind
  1808. placement="top"
  1809. title={language.t("prompt.action.attachFile")}
  1810. keybind={command.keybind("file.attach")}
  1811. >
  1812. <Button
  1813. data-action="prompt-attach"
  1814. type="button"
  1815. variant="ghost"
  1816. class="size-8 p-0"
  1817. style={buttons()}
  1818. onClick={pick}
  1819. disabled={store.mode !== "normal"}
  1820. tabIndex={store.mode === "normal" ? undefined : -1}
  1821. aria-label={language.t("prompt.action.attachFile")}
  1822. >
  1823. <Icon name="plus" class="size-4.5" />
  1824. </Button>
  1825. </TooltipKeybind>
  1826. </div>
  1827. </div>
  1828. </div>
  1829. </DockShellForm>
  1830. <Show when={store.mode === "normal" || store.mode === "shell"}>
  1831. <DockTray attach="top">
  1832. <div class="px-1.75 pt-5.5 pb-2 flex items-center gap-2 min-w-0">
  1833. <div class="flex items-center gap-1.5 min-w-0 flex-1 relative">
  1834. <div
  1835. class="h-7 flex items-center gap-1.5 min-w-0 absolute inset-0"
  1836. style={{
  1837. padding: "0 0px 0 8px",
  1838. ...shell(),
  1839. }}
  1840. >
  1841. <Icon name="console" />
  1842. <span class="truncate text-13-medium text-text-base">{language.t("prompt.mode.shell")}</span>
  1843. <div class="flex-1" />
  1844. <Button
  1845. variant="ghost"
  1846. class="text-text-base"
  1847. onClick={() => {
  1848. setStore("mode", "normal")
  1849. }}
  1850. >
  1851. {language.t("common.cancel")}
  1852. </Button>
  1853. </div>
  1854. <div class="flex items-center gap-1.5 min-w-0 flex-1 h-7">
  1855. <Show when={!agentsLoading()}>
  1856. <div
  1857. data-component="prompt-agent-control"
  1858. classList={{ "animate-in fade-in duration-300": agentsShouldFadeIn() }}
  1859. >
  1860. <TooltipKeybind
  1861. placement="top"
  1862. gutter={4}
  1863. title={language.t("command.agent.cycle")}
  1864. keybind={command.keybind("agent.cycle")}
  1865. >
  1866. <Select
  1867. size="normal"
  1868. options={props.controls.agents.options}
  1869. current={props.controls.agents.current}
  1870. onSelect={(value) => {
  1871. props.controls.agents.select(value)
  1872. restoreFocus()
  1873. }}
  1874. class="capitalize max-w-[160px] text-text-base"
  1875. valueClass="truncate text-13-regular text-text-base"
  1876. triggerStyle={control()}
  1877. triggerProps={{ "data-action": "prompt-agent" }}
  1878. variant="ghost"
  1879. />
  1880. </TooltipKeybind>
  1881. </div>
  1882. </Show>
  1883. <Show when={!providersLoading()}>
  1884. <Show when={store.mode !== "shell"}>
  1885. <div
  1886. data-component="prompt-model-control"
  1887. classList={{ "animate-in fade-in duration-300": providersShouldFadeIn() }}
  1888. >
  1889. <Show
  1890. when={props.controls.model.paid}
  1891. fallback={
  1892. <TooltipKeybind
  1893. placement="top"
  1894. gutter={4}
  1895. title={language.t("command.model.choose")}
  1896. keybind={command.keybind("model.choose")}
  1897. >
  1898. <Button
  1899. data-action="prompt-model"
  1900. as="div"
  1901. variant="ghost"
  1902. size="normal"
  1903. class="min-w-0 max-w-[320px] text-13-regular text-text-base group"
  1904. style={control()}
  1905. onClick={() => {
  1906. dialog.show(() => (
  1907. <DialogSelectModelUnpaid model={props.controls.model.selection} />
  1908. ))
  1909. }}
  1910. >
  1911. <Show when={props.controls.model.selection.current()?.provider?.id}>
  1912. <ProviderIcon
  1913. id={props.controls.model.selection.current()?.provider?.id ?? ""}
  1914. class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
  1915. style={{ "will-change": "opacity", transform: "translateZ(0)" }}
  1916. />
  1917. </Show>
  1918. <span class="truncate">
  1919. {props.controls.model.selection.current()?.name ??
  1920. language.t("dialog.model.select.title")}
  1921. </span>
  1922. <Icon name="chevron-down" size="small" class="shrink-0" />
  1923. </Button>
  1924. </TooltipKeybind>
  1925. }
  1926. >
  1927. <TooltipKeybind
  1928. placement="top"
  1929. gutter={4}
  1930. title={language.t("command.model.choose")}
  1931. keybind={command.keybind("model.choose")}
  1932. >
  1933. <ModelSelectorPopover
  1934. model={props.controls.model.selection}
  1935. triggerAs={Button}
  1936. triggerProps={{
  1937. variant: "ghost",
  1938. size: "normal",
  1939. style: control(),
  1940. class: "min-w-0 max-w-[320px] text-13-regular text-text-base group",
  1941. "data-action": "prompt-model",
  1942. }}
  1943. onClose={restoreFocus}
  1944. >
  1945. <Show when={props.controls.model.selection.current()?.provider?.id}>
  1946. <ProviderIcon
  1947. id={props.controls.model.selection.current()?.provider?.id ?? ""}
  1948. class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
  1949. style={{ "will-change": "opacity", transform: "translateZ(0)" }}
  1950. />
  1951. </Show>
  1952. <span class="truncate">
  1953. {props.controls.model.selection.current()?.name ??
  1954. language.t("dialog.model.select.title")}
  1955. </span>
  1956. <Icon name="chevron-down" size="small" class="shrink-0" />
  1957. </ModelSelectorPopover>
  1958. </TooltipKeybind>
  1959. </Show>
  1960. </div>
  1961. <Show when={showVariantControl()}>
  1962. <div
  1963. data-component="prompt-variant-control"
  1964. classList={{ "animate-in fade-in duration-300": providersShouldFadeIn() }}
  1965. >
  1966. <TooltipKeybind
  1967. placement="top"
  1968. gutter={4}
  1969. title={language.t("command.model.variant.cycle")}
  1970. keybind={command.keybind("model.variant.cycle")}
  1971. >
  1972. <Select
  1973. size="normal"
  1974. options={variants()}
  1975. current={props.controls.model.selection.variant.current() ?? "default"}
  1976. label={(x) => (x === "default" ? language.t("common.default") : x)}
  1977. onSelect={(value) => {
  1978. props.controls.model.selection.variant.set(value === "default" ? undefined : value)
  1979. restoreFocus()
  1980. }}
  1981. class="capitalize max-w-[160px] text-text-base"
  1982. valueClass="truncate text-13-regular text-text-base"
  1983. triggerStyle={control()}
  1984. triggerProps={{ "data-action": "prompt-model-variant" }}
  1985. variant="ghost"
  1986. />
  1987. </TooltipKeybind>
  1988. </div>
  1989. </Show>
  1990. </Show>
  1991. </Show>
  1992. </div>
  1993. </div>
  1994. </div>
  1995. </DockTray>
  1996. </Show>
  1997. </Match>
  1998. </Switch>
  1999. </div>
  2000. )
  2001. }
  2002. type ComposerAgentControlState = {
  2003. title: string
  2004. keybind: string[]
  2005. options: string[]
  2006. current: string
  2007. style: JSX.CSSProperties | undefined
  2008. onSelect: (value: string | undefined) => void
  2009. }
  2010. type ComposerModelControlState = {
  2011. loading: boolean
  2012. shouldAnimate: boolean
  2013. paid: boolean
  2014. title: string
  2015. keybind: string[]
  2016. model: ReturnType<typeof useLocal>["model"]
  2017. providerID?: string
  2018. modelName: string
  2019. newLayoutDesigns: boolean
  2020. style: JSX.CSSProperties | undefined
  2021. onClose: () => void
  2022. onUnpaidClick: () => void
  2023. }
  2024. function ComposerAgentControl(props: { state: ComposerAgentControlState }) {
  2025. return (
  2026. <div class="relative">
  2027. <div class="pointer-events-none absolute left-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-v2-icon-icon-muted">
  2028. <Icon name="sliders" size="small" />
  2029. </div>
  2030. <TooltipV2
  2031. placement="top"
  2032. gutter={4}
  2033. value={
  2034. <>
  2035. {props.state.title}
  2036. <KeybindV2 keys={props.state.keybind} variant="neutral" />
  2037. </>
  2038. }
  2039. >
  2040. <Select
  2041. size="normal"
  2042. options={props.state.options}
  2043. current={props.state.current}
  2044. onSelect={props.state.onSelect}
  2045. class="max-w-[175px] justify-start text-v2-text-text-faint [&_[data-component=icon]]:text-v2-icon-icon-muted"
  2046. valueClass="truncate pl-5 text-[13px] font-[440] leading-5 text-v2-text-text-faint"
  2047. triggerStyle={props.state.style}
  2048. triggerProps={{ "data-action": "prompt-agent" }}
  2049. variant="ghost"
  2050. />
  2051. </TooltipV2>
  2052. </div>
  2053. )
  2054. }
  2055. function ComposerModelControl(props: { state: ComposerModelControlState }) {
  2056. return (
  2057. <Show when={!props.state.loading}>
  2058. <Show
  2059. when={props.state.paid}
  2060. fallback={
  2061. <TooltipV2
  2062. placement="top"
  2063. gutter={4}
  2064. value={
  2065. <>
  2066. {props.state.title}
  2067. <KeybindV2 keys={props.state.keybind} variant="neutral" />
  2068. </>
  2069. }
  2070. >
  2071. <Show
  2072. when={props.state.newLayoutDesigns}
  2073. fallback={
  2074. <Button
  2075. data-action="prompt-model"
  2076. as="div"
  2077. variant="ghost"
  2078. size="normal"
  2079. class="min-w-0 max-w-[220px] justify-start text-[13px] font-[440] leading-5 text-v2-text-text-faint group"
  2080. classList={{ "animate-in fade-in": props.state.shouldAnimate }}
  2081. style={props.state.style}
  2082. onClick={props.state.onUnpaidClick}
  2083. >
  2084. <Show when={props.state.providerID}>
  2085. {(providerID) => (
  2086. <ProviderIcon
  2087. id={providerID()}
  2088. class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
  2089. style={{ "will-change": "opacity", transform: "translateZ(0)" }}
  2090. />
  2091. )}
  2092. </Show>
  2093. <span class="truncate">{props.state.modelName}</span>
  2094. <span class="-ml-1 shrink-0 flex size-fit">
  2095. <Icon name="chevron-down" size="small" class="text-v2-icon-icon-muted" />
  2096. </span>
  2097. </Button>
  2098. }
  2099. >
  2100. <ButtonV2
  2101. data-action="prompt-model"
  2102. variant="ghost-muted"
  2103. size="normal"
  2104. class="min-w-0 max-w-[220px] justify-start ![font-weight:440] group"
  2105. classList={{ "animate-in fade-in": props.state.shouldAnimate }}
  2106. style={props.state.style}
  2107. onClick={props.state.onUnpaidClick}
  2108. >
  2109. <ModelControlContent state={props.state} v2 />
  2110. </ButtonV2>
  2111. </Show>
  2112. </TooltipV2>
  2113. }
  2114. >
  2115. <TooltipV2
  2116. placement="top"
  2117. gutter={4}
  2118. value={
  2119. <>
  2120. {props.state.title}
  2121. <KeybindV2 keys={props.state.keybind} variant="neutral" />
  2122. </>
  2123. }
  2124. >
  2125. <Show
  2126. when={props.state.newLayoutDesigns}
  2127. fallback={
  2128. <ModelSelectorPopover
  2129. model={props.state.model}
  2130. triggerAs={Button}
  2131. triggerProps={{
  2132. variant: "ghost",
  2133. size: "normal",
  2134. style: props.state.style,
  2135. class:
  2136. "min-w-0 max-w-[220px] justify-start text-[13px] font-[440] leading-5 text-v2-text-text-faint group",
  2137. classList: { "animate-in fade-in": props.state.shouldAnimate },
  2138. "data-action": "prompt-model",
  2139. }}
  2140. onClose={props.state.onClose}
  2141. >
  2142. <ModelControlContent state={props.state} />
  2143. </ModelSelectorPopover>
  2144. }
  2145. >
  2146. <ModelSelectorPopoverV2
  2147. model={props.state.model}
  2148. triggerAs={ButtonV2}
  2149. triggerProps={{
  2150. variant: "ghost-muted",
  2151. size: "normal",
  2152. style: props.state.style,
  2153. class: "min-w-0 max-w-[220px] justify-start ![font-weight:440] group",
  2154. classList: { "animate-in fade-in": props.state.shouldAnimate },
  2155. "data-action": "prompt-model",
  2156. }}
  2157. onClose={props.state.onClose}
  2158. >
  2159. <ModelControlContent state={props.state} v2 />
  2160. </ModelSelectorPopoverV2>
  2161. </Show>
  2162. </TooltipV2>
  2163. </Show>
  2164. </Show>
  2165. )
  2166. }
  2167. function ModelControlContent(props: { state: ComposerModelControlState; v2?: boolean }) {
  2168. return (
  2169. <>
  2170. <Show when={props.state.providerID}>
  2171. {(providerID) => (
  2172. <ProviderIcon
  2173. id={providerID()}
  2174. class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
  2175. style={{ "will-change": "opacity", transform: "translateZ(0)" }}
  2176. />
  2177. )}
  2178. </Show>
  2179. <span class="truncate leading-4">{props.state.modelName}</span>
  2180. <span class={props.v2 ? "-ml-0.5 -mr-1 flex shrink-0" : "-ml-1 shrink-0 flex size-fit"}>
  2181. <Icon name="chevron-down" size="small" class="text-v2-icon-icon-muted" />
  2182. </span>
  2183. </>
  2184. )
  2185. }