prompt-input.tsx 80 KB

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