message-part.tsx 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. import {
  2. Component,
  3. createEffect,
  4. createMemo,
  5. createSignal,
  6. For,
  7. Match,
  8. Show,
  9. Switch,
  10. onCleanup,
  11. type JSX,
  12. } from "solid-js"
  13. import stripAnsi from "strip-ansi"
  14. import { Dynamic } from "solid-js/web"
  15. import {
  16. AgentPart,
  17. AssistantMessage,
  18. FilePart,
  19. Message as MessageType,
  20. Part as PartType,
  21. ReasoningPart,
  22. TextPart,
  23. ToolPart,
  24. UserMessage,
  25. Todo,
  26. QuestionRequest,
  27. QuestionAnswer,
  28. QuestionInfo,
  29. } from "@opencode-ai/sdk/v2"
  30. import { createStore } from "solid-js/store"
  31. import { useData } from "../context"
  32. import { useDiffComponent } from "../context/diff"
  33. import { useCodeComponent } from "../context/code"
  34. import { useDialog } from "../context/dialog"
  35. import { useI18n } from "../context/i18n"
  36. import { BasicTool } from "./basic-tool"
  37. import { GenericTool } from "./basic-tool"
  38. import { Button } from "./button"
  39. import { Card } from "./card"
  40. import { Icon } from "./icon"
  41. import { Checkbox } from "./checkbox"
  42. import { DiffChanges } from "./diff-changes"
  43. import { Markdown } from "./markdown"
  44. import { ImagePreview } from "./image-preview"
  45. import { findLast } from "@opencode-ai/util/array"
  46. import { getDirectory as _getDirectory, getFilename } from "@opencode-ai/util/path"
  47. import { checksum } from "@opencode-ai/util/encode"
  48. import { Tooltip } from "./tooltip"
  49. import { IconButton } from "./icon-button"
  50. import { createAutoScroll } from "../hooks"
  51. import { createResizeObserver } from "@solid-primitives/resize-observer"
  52. interface Diagnostic {
  53. range: {
  54. start: { line: number; character: number }
  55. end: { line: number; character: number }
  56. }
  57. message: string
  58. severity?: number
  59. }
  60. function getDiagnostics(
  61. diagnosticsByFile: Record<string, Diagnostic[]> | undefined,
  62. filePath: string | undefined,
  63. ): Diagnostic[] {
  64. if (!diagnosticsByFile || !filePath) return []
  65. const diagnostics = diagnosticsByFile[filePath] ?? []
  66. return diagnostics.filter((d) => d.severity === 1).slice(0, 3)
  67. }
  68. function DiagnosticsDisplay(props: { diagnostics: Diagnostic[] }): JSX.Element {
  69. const i18n = useI18n()
  70. return (
  71. <Show when={props.diagnostics.length > 0}>
  72. <div data-component="diagnostics">
  73. <For each={props.diagnostics}>
  74. {(diagnostic) => (
  75. <div data-slot="diagnostic">
  76. <span data-slot="diagnostic-label">{i18n.t("ui.messagePart.diagnostic.error")}</span>
  77. <span data-slot="diagnostic-location">
  78. [{diagnostic.range.start.line + 1}:{diagnostic.range.start.character + 1}]
  79. </span>
  80. <span data-slot="diagnostic-message">{diagnostic.message}</span>
  81. </div>
  82. )}
  83. </For>
  84. </div>
  85. </Show>
  86. )
  87. }
  88. export interface MessageProps {
  89. message: MessageType
  90. parts: PartType[]
  91. }
  92. export interface MessagePartProps {
  93. part: PartType
  94. message: MessageType
  95. hideDetails?: boolean
  96. defaultOpen?: boolean
  97. }
  98. export type PartComponent = Component<MessagePartProps>
  99. export const PART_MAPPING: Record<string, PartComponent | undefined> = {}
  100. const TEXT_RENDER_THROTTLE_MS = 100
  101. function same<T>(a: readonly T[], b: readonly T[]) {
  102. if (a === b) return true
  103. if (a.length !== b.length) return false
  104. return a.every((x, i) => x === b[i])
  105. }
  106. function createThrottledValue(getValue: () => string) {
  107. const [value, setValue] = createSignal(getValue())
  108. let timeout: ReturnType<typeof setTimeout> | undefined
  109. let last = 0
  110. createEffect(() => {
  111. const next = getValue()
  112. const now = Date.now()
  113. const remaining = TEXT_RENDER_THROTTLE_MS - (now - last)
  114. if (remaining <= 0) {
  115. if (timeout) {
  116. clearTimeout(timeout)
  117. timeout = undefined
  118. }
  119. last = now
  120. setValue(next)
  121. return
  122. }
  123. if (timeout) clearTimeout(timeout)
  124. timeout = setTimeout(() => {
  125. last = Date.now()
  126. setValue(next)
  127. timeout = undefined
  128. }, remaining)
  129. })
  130. onCleanup(() => {
  131. if (timeout) clearTimeout(timeout)
  132. })
  133. return value
  134. }
  135. function relativizeProjectPaths(text: string, directory?: string) {
  136. if (!text) return ""
  137. if (!directory) return text
  138. return text.split(directory).join("")
  139. }
  140. function getDirectory(path: string | undefined) {
  141. const data = useData()
  142. return relativizeProjectPaths(_getDirectory(path), data.directory)
  143. }
  144. export function getSessionToolParts(store: ReturnType<typeof useData>["store"], sessionId: string): ToolPart[] {
  145. const messages = store.message[sessionId]?.filter((m) => m.role === "assistant")
  146. if (!messages) return []
  147. const parts: ToolPart[] = []
  148. for (const m of messages) {
  149. const msgParts = store.part[m.id]
  150. if (msgParts) {
  151. for (const p of msgParts) {
  152. if (p && p.type === "tool") parts.push(p as ToolPart)
  153. }
  154. }
  155. }
  156. return parts
  157. }
  158. import type { IconProps } from "./icon"
  159. export type ToolInfo = {
  160. icon: IconProps["name"]
  161. title: string
  162. subtitle?: string
  163. }
  164. export function getToolInfo(tool: string, input: any = {}): ToolInfo {
  165. const i18n = useI18n()
  166. switch (tool) {
  167. case "read":
  168. return {
  169. icon: "glasses",
  170. title: i18n.t("ui.tool.read"),
  171. subtitle: input.filePath ? getFilename(input.filePath) : undefined,
  172. }
  173. case "list":
  174. return {
  175. icon: "bullet-list",
  176. title: i18n.t("ui.tool.list"),
  177. subtitle: input.path ? getFilename(input.path) : undefined,
  178. }
  179. case "glob":
  180. return {
  181. icon: "magnifying-glass-menu",
  182. title: i18n.t("ui.tool.glob"),
  183. subtitle: input.pattern,
  184. }
  185. case "grep":
  186. return {
  187. icon: "magnifying-glass-menu",
  188. title: i18n.t("ui.tool.grep"),
  189. subtitle: input.pattern,
  190. }
  191. case "webfetch":
  192. return {
  193. icon: "window-cursor",
  194. title: i18n.t("ui.tool.webfetch"),
  195. subtitle: input.url,
  196. }
  197. case "task":
  198. return {
  199. icon: "task",
  200. title: i18n.t("ui.tool.agent", { type: input.subagent_type || "task" }),
  201. subtitle: input.description,
  202. }
  203. case "bash":
  204. return {
  205. icon: "console",
  206. title: i18n.t("ui.tool.shell"),
  207. subtitle: input.description,
  208. }
  209. case "edit":
  210. return {
  211. icon: "code-lines",
  212. title: i18n.t("ui.messagePart.title.edit"),
  213. subtitle: input.filePath ? getFilename(input.filePath) : undefined,
  214. }
  215. case "write":
  216. return {
  217. icon: "code-lines",
  218. title: i18n.t("ui.messagePart.title.write"),
  219. subtitle: input.filePath ? getFilename(input.filePath) : undefined,
  220. }
  221. case "apply_patch":
  222. return {
  223. icon: "code-lines",
  224. title: i18n.t("ui.tool.patch"),
  225. subtitle: input.files?.length
  226. ? `${input.files.length} ${i18n.t(input.files.length > 1 ? "ui.common.file.other" : "ui.common.file.one")}`
  227. : undefined,
  228. }
  229. case "todowrite":
  230. return {
  231. icon: "checklist",
  232. title: i18n.t("ui.tool.todos"),
  233. }
  234. case "todoread":
  235. return {
  236. icon: "checklist",
  237. title: i18n.t("ui.tool.todos.read"),
  238. }
  239. case "question":
  240. return {
  241. icon: "bubble-5",
  242. title: i18n.t("ui.tool.questions"),
  243. }
  244. default:
  245. return {
  246. icon: "mcp",
  247. title: tool,
  248. }
  249. }
  250. }
  251. export function registerPartComponent(type: string, component: PartComponent) {
  252. PART_MAPPING[type] = component
  253. }
  254. export function Message(props: MessageProps) {
  255. return (
  256. <Switch>
  257. <Match when={props.message.role === "user" && props.message}>
  258. {(userMessage) => <UserMessageDisplay message={userMessage() as UserMessage} parts={props.parts} />}
  259. </Match>
  260. <Match when={props.message.role === "assistant" && props.message}>
  261. {(assistantMessage) => (
  262. <AssistantMessageDisplay message={assistantMessage() as AssistantMessage} parts={props.parts} />
  263. )}
  264. </Match>
  265. </Switch>
  266. )
  267. }
  268. export function AssistantMessageDisplay(props: { message: AssistantMessage; parts: PartType[] }) {
  269. const emptyParts: PartType[] = []
  270. const filteredParts = createMemo(
  271. () =>
  272. props.parts.filter((x) => {
  273. return x.type !== "tool" || (x as ToolPart).tool !== "todoread"
  274. }),
  275. emptyParts,
  276. { equals: same },
  277. )
  278. return <For each={filteredParts()}>{(part) => <Part part={part} message={props.message} />}</For>
  279. }
  280. export function UserMessageDisplay(props: { message: UserMessage; parts: PartType[] }) {
  281. const dialog = useDialog()
  282. const i18n = useI18n()
  283. const [copied, setCopied] = createSignal(false)
  284. const [expanded, setExpanded] = createSignal(false)
  285. const [canExpand, setCanExpand] = createSignal(false)
  286. let textRef: HTMLDivElement | undefined
  287. const updateCanExpand = () => {
  288. const el = textRef
  289. if (!el) return
  290. if (expanded()) return
  291. setCanExpand(el.scrollHeight > el.clientHeight + 2)
  292. }
  293. createResizeObserver(
  294. () => textRef,
  295. () => {
  296. updateCanExpand()
  297. },
  298. )
  299. const textPart = createMemo(
  300. () => props.parts?.find((p) => p.type === "text" && !(p as TextPart).synthetic) as TextPart | undefined,
  301. )
  302. const text = createMemo(() => textPart()?.text || "")
  303. createEffect(() => {
  304. text()
  305. updateCanExpand()
  306. })
  307. const files = createMemo(() => (props.parts?.filter((p) => p.type === "file") as FilePart[]) ?? [])
  308. const attachments = createMemo(() =>
  309. files()?.filter((f) => {
  310. const mime = f.mime
  311. return mime.startsWith("image/") || mime === "application/pdf"
  312. }),
  313. )
  314. const inlineFiles = createMemo(() =>
  315. files().filter((f) => {
  316. const mime = f.mime
  317. return !mime.startsWith("image/") && mime !== "application/pdf" && f.source?.text?.start !== undefined
  318. }),
  319. )
  320. const agents = createMemo(() => (props.parts?.filter((p) => p.type === "agent") as AgentPart[]) ?? [])
  321. const openImagePreview = (url: string, alt?: string) => {
  322. dialog.show(() => <ImagePreview src={url} alt={alt} />)
  323. }
  324. const handleCopy = async () => {
  325. const content = text()
  326. if (!content) return
  327. await navigator.clipboard.writeText(content)
  328. setCopied(true)
  329. setTimeout(() => setCopied(false), 2000)
  330. }
  331. const toggleExpanded = () => {
  332. if (!canExpand()) return
  333. setExpanded((value) => !value)
  334. }
  335. return (
  336. <div data-component="user-message" data-expanded={expanded()} data-can-expand={canExpand()}>
  337. <Show when={attachments().length > 0}>
  338. <div data-slot="user-message-attachments">
  339. <For each={attachments()}>
  340. {(file) => (
  341. <div
  342. data-slot="user-message-attachment"
  343. data-type={file.mime.startsWith("image/") ? "image" : "file"}
  344. onClick={() => {
  345. if (file.mime.startsWith("image/") && file.url) {
  346. openImagePreview(file.url, file.filename)
  347. }
  348. }}
  349. >
  350. <Show
  351. when={file.mime.startsWith("image/") && file.url}
  352. fallback={
  353. <div data-slot="user-message-attachment-icon">
  354. <Icon name="folder" />
  355. </div>
  356. }
  357. >
  358. <img
  359. data-slot="user-message-attachment-image"
  360. src={file.url}
  361. alt={file.filename ?? i18n.t("ui.message.attachment.alt")}
  362. />
  363. </Show>
  364. </div>
  365. )}
  366. </For>
  367. </div>
  368. </Show>
  369. <Show when={text()}>
  370. <div data-slot="user-message-text" ref={(el) => (textRef = el)} onClick={toggleExpanded}>
  371. <HighlightedText text={text()} references={inlineFiles()} agents={agents()} />
  372. <button
  373. data-slot="user-message-expand"
  374. type="button"
  375. aria-label={expanded() ? i18n.t("ui.message.collapse") : i18n.t("ui.message.expand")}
  376. onClick={(event) => {
  377. event.stopPropagation()
  378. toggleExpanded()
  379. }}
  380. >
  381. <Icon name="chevron-down" size="small" />
  382. </button>
  383. <div data-slot="user-message-copy-wrapper">
  384. <Tooltip
  385. value={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
  386. placement="top"
  387. gutter={8}
  388. >
  389. <IconButton
  390. icon={copied() ? "check" : "copy"}
  391. size="small"
  392. variant="secondary"
  393. onMouseDown={(e) => e.preventDefault()}
  394. onClick={(event) => {
  395. event.stopPropagation()
  396. handleCopy()
  397. }}
  398. aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
  399. />
  400. </Tooltip>
  401. </div>
  402. </div>
  403. </Show>
  404. </div>
  405. )
  406. }
  407. type HighlightSegment = { text: string; type?: "file" | "agent" }
  408. function HighlightedText(props: { text: string; references: FilePart[]; agents: AgentPart[] }) {
  409. const segments = createMemo(() => {
  410. const text = props.text
  411. const allRefs: { start: number; end: number; type: "file" | "agent" }[] = [
  412. ...props.references
  413. .filter((r) => r.source?.text?.start !== undefined && r.source?.text?.end !== undefined)
  414. .map((r) => ({ start: r.source!.text!.start, end: r.source!.text!.end, type: "file" as const })),
  415. ...props.agents
  416. .filter((a) => a.source?.start !== undefined && a.source?.end !== undefined)
  417. .map((a) => ({ start: a.source!.start, end: a.source!.end, type: "agent" as const })),
  418. ].sort((a, b) => a.start - b.start)
  419. const result: HighlightSegment[] = []
  420. let lastIndex = 0
  421. for (const ref of allRefs) {
  422. if (ref.start < lastIndex) continue
  423. if (ref.start > lastIndex) {
  424. result.push({ text: text.slice(lastIndex, ref.start) })
  425. }
  426. result.push({ text: text.slice(ref.start, ref.end), type: ref.type })
  427. lastIndex = ref.end
  428. }
  429. if (lastIndex < text.length) {
  430. result.push({ text: text.slice(lastIndex) })
  431. }
  432. return result
  433. })
  434. return <For each={segments()}>{(segment) => <span data-highlight={segment.type}>{segment.text}</span>}</For>
  435. }
  436. export function Part(props: MessagePartProps) {
  437. const component = createMemo(() => PART_MAPPING[props.part.type])
  438. return (
  439. <Show when={component()}>
  440. <Dynamic
  441. component={component()}
  442. part={props.part}
  443. message={props.message}
  444. hideDetails={props.hideDetails}
  445. defaultOpen={props.defaultOpen}
  446. />
  447. </Show>
  448. )
  449. }
  450. export interface ToolProps {
  451. input: Record<string, any>
  452. metadata: Record<string, any>
  453. tool: string
  454. output?: string
  455. status?: string
  456. hideDetails?: boolean
  457. defaultOpen?: boolean
  458. forceOpen?: boolean
  459. locked?: boolean
  460. }
  461. export type ToolComponent = Component<ToolProps>
  462. const state: Record<
  463. string,
  464. {
  465. name: string
  466. render?: ToolComponent
  467. }
  468. > = {}
  469. export function registerTool(input: { name: string; render?: ToolComponent }) {
  470. state[input.name] = input
  471. return input
  472. }
  473. export function getTool(name: string) {
  474. return state[name]?.render
  475. }
  476. export const ToolRegistry = {
  477. register: registerTool,
  478. render: getTool,
  479. }
  480. PART_MAPPING["tool"] = function ToolPartDisplay(props) {
  481. const data = useData()
  482. const i18n = useI18n()
  483. const part = props.part as ToolPart
  484. const permission = createMemo(() => {
  485. const next = data.store.permission?.[props.message.sessionID]?.[0]
  486. if (!next || !next.tool) return undefined
  487. if (next.tool!.callID !== part.callID) return undefined
  488. return next
  489. })
  490. const questionRequest = createMemo(() => {
  491. const next = data.store.question?.[props.message.sessionID]?.[0]
  492. if (!next || !next.tool) return undefined
  493. if (next.tool!.callID !== part.callID) return undefined
  494. return next
  495. })
  496. const [showPermission, setShowPermission] = createSignal(false)
  497. const [showQuestion, setShowQuestion] = createSignal(false)
  498. createEffect(() => {
  499. const perm = permission()
  500. if (perm) {
  501. const timeout = setTimeout(() => setShowPermission(true), 50)
  502. onCleanup(() => clearTimeout(timeout))
  503. } else {
  504. setShowPermission(false)
  505. }
  506. })
  507. createEffect(() => {
  508. const question = questionRequest()
  509. if (question) {
  510. const timeout = setTimeout(() => setShowQuestion(true), 50)
  511. onCleanup(() => clearTimeout(timeout))
  512. } else {
  513. setShowQuestion(false)
  514. }
  515. })
  516. const [forceOpen, setForceOpen] = createSignal(false)
  517. createEffect(() => {
  518. if (permission() || questionRequest()) setForceOpen(true)
  519. })
  520. const respond = (response: "once" | "always" | "reject") => {
  521. const perm = permission()
  522. if (!perm || !data.respondToPermission) return
  523. data.respondToPermission({
  524. sessionID: perm.sessionID,
  525. permissionID: perm.id,
  526. response,
  527. })
  528. }
  529. const emptyInput: Record<string, any> = {}
  530. const emptyMetadata: Record<string, any> = {}
  531. const input = () => part.state?.input ?? emptyInput
  532. // @ts-expect-error
  533. const partMetadata = () => part.state?.metadata ?? emptyMetadata
  534. const metadata = () => {
  535. const perm = permission()
  536. if (perm?.metadata) return { ...perm.metadata, ...partMetadata() }
  537. return partMetadata()
  538. }
  539. const render = ToolRegistry.render(part.tool) ?? GenericTool
  540. return (
  541. <div data-component="tool-part-wrapper" data-permission={showPermission()} data-question={showQuestion()}>
  542. <Switch>
  543. <Match when={part.state.status === "error" && part.state.error}>
  544. {(error) => {
  545. const cleaned = error().replace("Error: ", "")
  546. const [title, ...rest] = cleaned.split(": ")
  547. return (
  548. <Card variant="error">
  549. <div data-component="tool-error">
  550. <Icon name="circle-ban-sign" size="small" />
  551. <Switch>
  552. <Match when={title && title.length < 30}>
  553. <div data-slot="message-part-tool-error-content">
  554. <div data-slot="message-part-tool-error-title">{title}</div>
  555. <span data-slot="message-part-tool-error-message">{rest.join(": ")}</span>
  556. </div>
  557. </Match>
  558. <Match when={true}>
  559. <span data-slot="message-part-tool-error-message">{cleaned}</span>
  560. </Match>
  561. </Switch>
  562. </div>
  563. </Card>
  564. )
  565. }}
  566. </Match>
  567. <Match when={true}>
  568. <Dynamic
  569. component={render}
  570. input={input()}
  571. tool={part.tool}
  572. metadata={metadata()}
  573. // @ts-expect-error
  574. output={part.state.output}
  575. status={part.state.status}
  576. hideDetails={props.hideDetails}
  577. forceOpen={forceOpen()}
  578. locked={showPermission() || showQuestion()}
  579. defaultOpen={props.defaultOpen}
  580. />
  581. </Match>
  582. </Switch>
  583. <Show when={showPermission() && permission()}>
  584. <div data-component="permission-prompt">
  585. <div data-slot="permission-actions">
  586. <Button variant="ghost" size="small" onClick={() => respond("reject")}>
  587. {i18n.t("ui.permission.deny")}
  588. </Button>
  589. <Button variant="secondary" size="small" onClick={() => respond("always")}>
  590. {i18n.t("ui.permission.allowAlways")}
  591. </Button>
  592. <Button variant="primary" size="small" onClick={() => respond("once")}>
  593. {i18n.t("ui.permission.allowOnce")}
  594. </Button>
  595. </div>
  596. </div>
  597. </Show>
  598. <Show when={showQuestion() && questionRequest()}>{(request) => <QuestionPrompt request={request()} />}</Show>
  599. </div>
  600. )
  601. }
  602. PART_MAPPING["text"] = function TextPartDisplay(props) {
  603. const data = useData()
  604. const i18n = useI18n()
  605. const part = props.part as TextPart
  606. const displayText = () => relativizeProjectPaths((part.text ?? "").trim(), data.directory)
  607. const throttledText = createThrottledValue(displayText)
  608. const [copied, setCopied] = createSignal(false)
  609. const handleCopy = async () => {
  610. const content = displayText()
  611. if (!content) return
  612. await navigator.clipboard.writeText(content)
  613. setCopied(true)
  614. setTimeout(() => setCopied(false), 2000)
  615. }
  616. return (
  617. <Show when={throttledText()}>
  618. <div data-component="text-part">
  619. <div data-slot="text-part-body">
  620. <Markdown text={throttledText()} cacheKey={part.id} />
  621. <div data-slot="text-part-copy-wrapper">
  622. <Tooltip
  623. value={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
  624. placement="top"
  625. gutter={8}
  626. >
  627. <IconButton
  628. icon={copied() ? "check" : "copy"}
  629. size="small"
  630. variant="secondary"
  631. onMouseDown={(e) => e.preventDefault()}
  632. onClick={handleCopy}
  633. aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
  634. />
  635. </Tooltip>
  636. </div>
  637. </div>
  638. </div>
  639. </Show>
  640. )
  641. }
  642. PART_MAPPING["reasoning"] = function ReasoningPartDisplay(props) {
  643. const part = props.part as ReasoningPart
  644. const text = () => part.text.trim()
  645. const throttledText = createThrottledValue(text)
  646. return (
  647. <Show when={throttledText()}>
  648. <div data-component="reasoning-part">
  649. <Markdown text={throttledText()} cacheKey={part.id} />
  650. </div>
  651. </Show>
  652. )
  653. }
  654. ToolRegistry.register({
  655. name: "read",
  656. render(props) {
  657. const data = useData()
  658. const i18n = useI18n()
  659. const args: string[] = []
  660. if (props.input.offset) args.push("offset=" + props.input.offset)
  661. if (props.input.limit) args.push("limit=" + props.input.limit)
  662. const loaded = createMemo(() => {
  663. if (props.status !== "completed") return []
  664. const value = props.metadata.loaded
  665. if (!value || !Array.isArray(value)) return []
  666. return value.filter((p): p is string => typeof p === "string")
  667. })
  668. return (
  669. <>
  670. <BasicTool
  671. {...props}
  672. icon="glasses"
  673. trigger={{
  674. title: i18n.t("ui.tool.read"),
  675. subtitle: props.input.filePath ? getFilename(props.input.filePath) : "",
  676. args,
  677. }}
  678. />
  679. <For each={loaded()}>
  680. {(filepath) => (
  681. <div data-component="tool-loaded-file">
  682. <Icon name="enter" size="small" />
  683. <span>
  684. {i18n.t("ui.tool.loaded")} {relativizeProjectPaths(filepath, data.directory)}
  685. </span>
  686. </div>
  687. )}
  688. </For>
  689. </>
  690. )
  691. },
  692. })
  693. ToolRegistry.register({
  694. name: "list",
  695. render(props) {
  696. const i18n = useI18n()
  697. return (
  698. <BasicTool
  699. {...props}
  700. icon="bullet-list"
  701. trigger={{ title: i18n.t("ui.tool.list"), subtitle: getDirectory(props.input.path || "/") }}
  702. >
  703. <Show when={props.output}>
  704. {(output) => (
  705. <div data-component="tool-output" data-scrollable>
  706. <Markdown text={output()} />
  707. </div>
  708. )}
  709. </Show>
  710. </BasicTool>
  711. )
  712. },
  713. })
  714. ToolRegistry.register({
  715. name: "glob",
  716. render(props) {
  717. const i18n = useI18n()
  718. return (
  719. <BasicTool
  720. {...props}
  721. icon="magnifying-glass-menu"
  722. trigger={{
  723. title: i18n.t("ui.tool.glob"),
  724. subtitle: getDirectory(props.input.path || "/"),
  725. args: props.input.pattern ? ["pattern=" + props.input.pattern] : [],
  726. }}
  727. >
  728. <Show when={props.output}>
  729. {(output) => (
  730. <div data-component="tool-output" data-scrollable>
  731. <Markdown text={output()} />
  732. </div>
  733. )}
  734. </Show>
  735. </BasicTool>
  736. )
  737. },
  738. })
  739. ToolRegistry.register({
  740. name: "grep",
  741. render(props) {
  742. const i18n = useI18n()
  743. const args: string[] = []
  744. if (props.input.pattern) args.push("pattern=" + props.input.pattern)
  745. if (props.input.include) args.push("include=" + props.input.include)
  746. return (
  747. <BasicTool
  748. {...props}
  749. icon="magnifying-glass-menu"
  750. trigger={{
  751. title: i18n.t("ui.tool.grep"),
  752. subtitle: getDirectory(props.input.path || "/"),
  753. args,
  754. }}
  755. >
  756. <Show when={props.output}>
  757. {(output) => (
  758. <div data-component="tool-output" data-scrollable>
  759. <Markdown text={output()} />
  760. </div>
  761. )}
  762. </Show>
  763. </BasicTool>
  764. )
  765. },
  766. })
  767. ToolRegistry.register({
  768. name: "webfetch",
  769. render(props) {
  770. const i18n = useI18n()
  771. return (
  772. <BasicTool
  773. {...props}
  774. icon="window-cursor"
  775. trigger={{
  776. title: i18n.t("ui.tool.webfetch"),
  777. subtitle: props.input.url || "",
  778. args: props.input.format ? ["format=" + props.input.format] : [],
  779. action: (
  780. <div data-component="tool-action">
  781. <Icon name="square-arrow-top-right" size="small" />
  782. </div>
  783. ),
  784. }}
  785. >
  786. <Show when={props.output}>
  787. {(output) => (
  788. <div data-component="tool-output" data-scrollable>
  789. <Markdown text={output()} />
  790. </div>
  791. )}
  792. </Show>
  793. </BasicTool>
  794. )
  795. },
  796. })
  797. ToolRegistry.register({
  798. name: "task",
  799. render(props) {
  800. const data = useData()
  801. const i18n = useI18n()
  802. const childSessionId = () => props.metadata.sessionId as string | undefined
  803. const href = createMemo(() => {
  804. const sessionId = childSessionId()
  805. if (!sessionId) return
  806. const direct = data.sessionHref?.(sessionId)
  807. if (direct) return direct
  808. if (typeof window === "undefined") return
  809. const path = window.location.pathname
  810. const idx = path.indexOf("/session")
  811. if (idx === -1) return
  812. return `${path.slice(0, idx)}/session/${sessionId}`
  813. })
  814. createEffect(() => {
  815. const sessionId = childSessionId()
  816. if (!sessionId) return
  817. const sync = data.syncSession
  818. if (!sync) return
  819. Promise.resolve(sync(sessionId)).catch(() => undefined)
  820. })
  821. const handleLinkClick = (e: MouseEvent) => {
  822. const sessionId = childSessionId()
  823. const url = href()
  824. if (!sessionId || !url) return
  825. e.stopPropagation()
  826. if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
  827. const nav = data.navigateToSession
  828. if (!nav || typeof window === "undefined") return
  829. e.preventDefault()
  830. const before = window.location.pathname + window.location.search + window.location.hash
  831. nav(sessionId)
  832. setTimeout(() => {
  833. const after = window.location.pathname + window.location.search + window.location.hash
  834. if (after === before) window.location.assign(url)
  835. }, 50)
  836. }
  837. const trigger = () => (
  838. <div data-slot="basic-tool-tool-info-structured">
  839. <div data-slot="basic-tool-tool-info-main">
  840. <span data-slot="basic-tool-tool-title" class="capitalize">
  841. {i18n.t("ui.tool.agent", { type: props.input.subagent_type || props.tool })}
  842. </span>
  843. <Show when={props.input.description}>
  844. <Switch>
  845. <Match when={href()}>
  846. {(url) => (
  847. <a data-slot="basic-tool-tool-subtitle" class="clickable" href={url()} onClick={handleLinkClick}>
  848. {props.input.description}
  849. </a>
  850. )}
  851. </Match>
  852. <Match when={true}>
  853. <span data-slot="basic-tool-tool-subtitle">{props.input.description}</span>
  854. </Match>
  855. </Switch>
  856. </Show>
  857. </div>
  858. </div>
  859. )
  860. const childToolParts = createMemo(() => {
  861. const sessionId = childSessionId()
  862. if (!sessionId) return []
  863. return getSessionToolParts(data.store, sessionId)
  864. })
  865. const autoScroll = createAutoScroll({
  866. working: () => true,
  867. overflowAnchor: "auto",
  868. })
  869. const childPermission = createMemo(() => {
  870. const sessionId = childSessionId()
  871. if (!sessionId) return undefined
  872. const permissions = data.store.permission?.[sessionId] ?? []
  873. return permissions[0]
  874. })
  875. const childToolPart = createMemo(() => {
  876. const perm = childPermission()
  877. if (!perm || !perm.tool) return undefined
  878. const sessionId = childSessionId()
  879. if (!sessionId) return undefined
  880. // Find the tool part that matches the permission's callID
  881. const messages = data.store.message[sessionId] ?? []
  882. const message = findLast(messages, (m) => m.id === perm.tool!.messageID)
  883. if (!message) return undefined
  884. const parts = data.store.part[message.id] ?? []
  885. for (const part of parts) {
  886. if (part.type === "tool" && (part as ToolPart).callID === perm.tool!.callID) {
  887. return { part: part as ToolPart, message }
  888. }
  889. }
  890. return undefined
  891. })
  892. const respond = (response: "once" | "always" | "reject") => {
  893. const perm = childPermission()
  894. if (!perm || !data.respondToPermission) return
  895. data.respondToPermission({
  896. sessionID: perm.sessionID,
  897. permissionID: perm.id,
  898. response,
  899. })
  900. }
  901. const renderChildToolPart = () => {
  902. const toolData = childToolPart()
  903. if (!toolData) return null
  904. const { part } = toolData
  905. const render = ToolRegistry.render(part.tool) ?? GenericTool
  906. // @ts-expect-error
  907. const metadata = part.state?.metadata ?? {}
  908. const input = part.state?.input ?? {}
  909. return (
  910. <Dynamic
  911. component={render}
  912. input={input}
  913. tool={part.tool}
  914. metadata={metadata}
  915. // @ts-expect-error
  916. output={part.state.output}
  917. status={part.state.status}
  918. defaultOpen={true}
  919. />
  920. )
  921. }
  922. return (
  923. <div data-component="tool-part-wrapper" data-permission={!!childPermission()}>
  924. <Switch>
  925. <Match when={childPermission()}>
  926. <>
  927. <Show when={childToolPart()} fallback={<BasicTool icon="task" defaultOpen={true} trigger={trigger()} />}>
  928. {renderChildToolPart()}
  929. </Show>
  930. <div data-component="permission-prompt">
  931. <div data-slot="permission-actions">
  932. <Button variant="ghost" size="small" onClick={() => respond("reject")}>
  933. {i18n.t("ui.permission.deny")}
  934. </Button>
  935. <Button variant="secondary" size="small" onClick={() => respond("always")}>
  936. {i18n.t("ui.permission.allowAlways")}
  937. </Button>
  938. <Button variant="primary" size="small" onClick={() => respond("once")}>
  939. {i18n.t("ui.permission.allowOnce")}
  940. </Button>
  941. </div>
  942. </div>
  943. </>
  944. </Match>
  945. <Match when={true}>
  946. <BasicTool icon="task" defaultOpen={true} trigger={trigger()}>
  947. <div
  948. ref={autoScroll.scrollRef}
  949. onScroll={autoScroll.handleScroll}
  950. data-component="tool-output"
  951. data-scrollable
  952. >
  953. <div ref={autoScroll.contentRef} data-component="task-tools">
  954. <For each={childToolParts()}>
  955. {(item) => {
  956. const info = createMemo(() => getToolInfo(item.tool, item.state.input))
  957. const subtitle = createMemo(() => {
  958. if (info().subtitle) return info().subtitle
  959. if (item.state.status === "completed" || item.state.status === "running") {
  960. return item.state.title
  961. }
  962. })
  963. return (
  964. <div data-slot="task-tool-item">
  965. <Icon name={info().icon} size="small" />
  966. <span data-slot="task-tool-title">{info().title}</span>
  967. <Show when={subtitle()}>
  968. <span data-slot="task-tool-subtitle">{subtitle()}</span>
  969. </Show>
  970. </div>
  971. )
  972. }}
  973. </For>
  974. </div>
  975. </div>
  976. </BasicTool>
  977. </Match>
  978. </Switch>
  979. </div>
  980. )
  981. },
  982. })
  983. ToolRegistry.register({
  984. name: "bash",
  985. render(props) {
  986. const i18n = useI18n()
  987. return (
  988. <BasicTool
  989. {...props}
  990. icon="console"
  991. trigger={{
  992. title: i18n.t("ui.tool.shell"),
  993. subtitle: props.input.description,
  994. }}
  995. >
  996. <div data-component="tool-output" data-scrollable>
  997. <Markdown
  998. text={`\`\`\`command\n$ ${props.input.command ?? props.metadata.command ?? ""}${props.output || props.metadata.output ? "\n\n" + stripAnsi(props.output || props.metadata.output) : ""}\n\`\`\``}
  999. />
  1000. </div>
  1001. </BasicTool>
  1002. )
  1003. },
  1004. })
  1005. ToolRegistry.register({
  1006. name: "edit",
  1007. render(props) {
  1008. const i18n = useI18n()
  1009. const diffComponent = useDiffComponent()
  1010. const diagnostics = createMemo(() => getDiagnostics(props.metadata.diagnostics, props.input.filePath))
  1011. const filename = () => getFilename(props.input.filePath ?? "")
  1012. return (
  1013. <BasicTool
  1014. {...props}
  1015. icon="code-lines"
  1016. trigger={
  1017. <div data-component="edit-trigger">
  1018. <div data-slot="message-part-title-area">
  1019. <div data-slot="message-part-title">
  1020. <span data-slot="message-part-title-text">{i18n.t("ui.messagePart.title.edit")}</span>
  1021. <span data-slot="message-part-title-filename">{filename()}</span>
  1022. </div>
  1023. <Show when={props.input.filePath?.includes("/")}>
  1024. <div data-slot="message-part-path">
  1025. <span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
  1026. </div>
  1027. </Show>
  1028. </div>
  1029. <div data-slot="message-part-actions">
  1030. <Show when={props.metadata.filediff}>
  1031. <DiffChanges changes={props.metadata.filediff} />
  1032. </Show>
  1033. </div>
  1034. </div>
  1035. }
  1036. >
  1037. <Show when={props.metadata.filediff?.path || props.input.filePath}>
  1038. <div data-component="edit-content">
  1039. <Dynamic
  1040. component={diffComponent}
  1041. before={{
  1042. name: props.metadata?.filediff?.file || props.input.filePath,
  1043. contents: props.metadata?.filediff?.before || props.input.oldString,
  1044. }}
  1045. after={{
  1046. name: props.metadata?.filediff?.file || props.input.filePath,
  1047. contents: props.metadata?.filediff?.after || props.input.newString,
  1048. }}
  1049. />
  1050. </div>
  1051. </Show>
  1052. <DiagnosticsDisplay diagnostics={diagnostics()} />
  1053. </BasicTool>
  1054. )
  1055. },
  1056. })
  1057. ToolRegistry.register({
  1058. name: "write",
  1059. render(props) {
  1060. const i18n = useI18n()
  1061. const codeComponent = useCodeComponent()
  1062. const diagnostics = createMemo(() => getDiagnostics(props.metadata.diagnostics, props.input.filePath))
  1063. const filename = () => getFilename(props.input.filePath ?? "")
  1064. return (
  1065. <BasicTool
  1066. {...props}
  1067. icon="code-lines"
  1068. trigger={
  1069. <div data-component="write-trigger">
  1070. <div data-slot="message-part-title-area">
  1071. <div data-slot="message-part-title">
  1072. <span data-slot="message-part-title-text">{i18n.t("ui.messagePart.title.write")}</span>
  1073. <span data-slot="message-part-title-filename">{filename()}</span>
  1074. </div>
  1075. <Show when={props.input.filePath?.includes("/")}>
  1076. <div data-slot="message-part-path">
  1077. <span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
  1078. </div>
  1079. </Show>
  1080. </div>
  1081. <div data-slot="message-part-actions">{/* <DiffChanges diff={diff} /> */}</div>
  1082. </div>
  1083. }
  1084. >
  1085. <Show when={props.input.content}>
  1086. <div data-component="write-content">
  1087. <Dynamic
  1088. component={codeComponent}
  1089. file={{
  1090. name: props.input.filePath,
  1091. contents: props.input.content,
  1092. cacheKey: checksum(props.input.content),
  1093. }}
  1094. overflow="scroll"
  1095. />
  1096. </div>
  1097. </Show>
  1098. <DiagnosticsDisplay diagnostics={diagnostics()} />
  1099. </BasicTool>
  1100. )
  1101. },
  1102. })
  1103. interface ApplyPatchFile {
  1104. filePath: string
  1105. relativePath: string
  1106. type: "add" | "update" | "delete" | "move"
  1107. diff: string
  1108. before: string
  1109. after: string
  1110. additions: number
  1111. deletions: number
  1112. movePath?: string
  1113. }
  1114. ToolRegistry.register({
  1115. name: "apply_patch",
  1116. render(props) {
  1117. const i18n = useI18n()
  1118. const diffComponent = useDiffComponent()
  1119. const files = createMemo(() => (props.metadata.files ?? []) as ApplyPatchFile[])
  1120. const subtitle = createMemo(() => {
  1121. const count = files().length
  1122. if (count === 0) return ""
  1123. return `${count} ${i18n.t(count > 1 ? "ui.common.file.other" : "ui.common.file.one")}`
  1124. })
  1125. return (
  1126. <BasicTool
  1127. {...props}
  1128. icon="code-lines"
  1129. trigger={{
  1130. title: i18n.t("ui.tool.patch"),
  1131. subtitle: subtitle(),
  1132. }}
  1133. >
  1134. <Show when={files().length > 0}>
  1135. <div data-component="apply-patch-files">
  1136. <For each={files()}>
  1137. {(file) => (
  1138. <div data-component="apply-patch-file">
  1139. <div data-slot="apply-patch-file-header">
  1140. <Switch>
  1141. <Match when={file.type === "delete"}>
  1142. <span data-slot="apply-patch-file-action" data-type="delete">
  1143. {i18n.t("ui.patch.action.deleted")}
  1144. </span>
  1145. </Match>
  1146. <Match when={file.type === "add"}>
  1147. <span data-slot="apply-patch-file-action" data-type="add">
  1148. {i18n.t("ui.patch.action.created")}
  1149. </span>
  1150. </Match>
  1151. <Match when={file.type === "move"}>
  1152. <span data-slot="apply-patch-file-action" data-type="move">
  1153. {i18n.t("ui.patch.action.moved")}
  1154. </span>
  1155. </Match>
  1156. <Match when={file.type === "update"}>
  1157. <span data-slot="apply-patch-file-action" data-type="update">
  1158. {i18n.t("ui.patch.action.patched")}
  1159. </span>
  1160. </Match>
  1161. </Switch>
  1162. <span data-slot="apply-patch-file-path">{file.relativePath}</span>
  1163. <Show when={file.type !== "delete"}>
  1164. <DiffChanges changes={{ additions: file.additions, deletions: file.deletions }} />
  1165. </Show>
  1166. <Show when={file.type === "delete"}>
  1167. <span data-slot="apply-patch-deletion-count">-{file.deletions}</span>
  1168. </Show>
  1169. </div>
  1170. <Show when={file.type !== "delete"}>
  1171. <div data-component="apply-patch-file-diff">
  1172. <Dynamic
  1173. component={diffComponent}
  1174. before={{ name: file.filePath, contents: file.before }}
  1175. after={{ name: file.filePath, contents: file.after }}
  1176. />
  1177. </div>
  1178. </Show>
  1179. </div>
  1180. )}
  1181. </For>
  1182. </div>
  1183. </Show>
  1184. </BasicTool>
  1185. )
  1186. },
  1187. })
  1188. ToolRegistry.register({
  1189. name: "todowrite",
  1190. render(props) {
  1191. const i18n = useI18n()
  1192. const todos = createMemo(() => {
  1193. const meta = props.metadata?.todos
  1194. if (Array.isArray(meta)) return meta
  1195. const input = props.input.todos
  1196. if (Array.isArray(input)) return input
  1197. return []
  1198. })
  1199. const subtitle = createMemo(() => {
  1200. const list = todos()
  1201. if (list.length === 0) return ""
  1202. return `${list.filter((t: Todo) => t.status === "completed").length}/${list.length}`
  1203. })
  1204. return (
  1205. <BasicTool
  1206. {...props}
  1207. defaultOpen
  1208. icon="checklist"
  1209. trigger={{
  1210. title: i18n.t("ui.tool.todos"),
  1211. subtitle: subtitle(),
  1212. }}
  1213. >
  1214. <Show when={todos().length}>
  1215. <div data-component="todos">
  1216. <For each={todos()}>
  1217. {(todo: Todo) => (
  1218. <Checkbox readOnly checked={todo.status === "completed"}>
  1219. <div data-slot="message-part-todo-content" data-completed={todo.status === "completed"}>
  1220. {todo.content}
  1221. </div>
  1222. </Checkbox>
  1223. )}
  1224. </For>
  1225. </div>
  1226. </Show>
  1227. </BasicTool>
  1228. )
  1229. },
  1230. })
  1231. ToolRegistry.register({
  1232. name: "question",
  1233. render(props) {
  1234. const i18n = useI18n()
  1235. const questions = createMemo(() => (props.input.questions ?? []) as QuestionInfo[])
  1236. const answers = createMemo(() => (props.metadata.answers ?? []) as QuestionAnswer[])
  1237. const completed = createMemo(() => answers().length > 0)
  1238. const subtitle = createMemo(() => {
  1239. const count = questions().length
  1240. if (count === 0) return ""
  1241. if (completed()) return i18n.t("ui.question.subtitle.answered", { count })
  1242. return `${count} ${i18n.t(count > 1 ? "ui.common.question.other" : "ui.common.question.one")}`
  1243. })
  1244. return (
  1245. <BasicTool
  1246. {...props}
  1247. defaultOpen={completed()}
  1248. icon="bubble-5"
  1249. trigger={{
  1250. title: i18n.t("ui.tool.questions"),
  1251. subtitle: subtitle(),
  1252. }}
  1253. >
  1254. <Show when={completed()}>
  1255. <div data-component="question-answers">
  1256. <For each={questions()}>
  1257. {(q, i) => {
  1258. const answer = () => answers()[i()] ?? []
  1259. return (
  1260. <div data-slot="question-answer-item">
  1261. <div data-slot="question-text">{q.question}</div>
  1262. <div data-slot="answer-text">{answer().join(", ") || i18n.t("ui.question.answer.none")}</div>
  1263. </div>
  1264. )
  1265. }}
  1266. </For>
  1267. </div>
  1268. </Show>
  1269. </BasicTool>
  1270. )
  1271. },
  1272. })
  1273. function QuestionPrompt(props: { request: QuestionRequest }) {
  1274. const data = useData()
  1275. const i18n = useI18n()
  1276. const questions = createMemo(() => props.request.questions)
  1277. const single = createMemo(() => questions().length === 1 && questions()[0]?.multiple !== true)
  1278. const [store, setStore] = createStore({
  1279. tab: 0,
  1280. answers: [] as QuestionAnswer[],
  1281. custom: [] as string[],
  1282. editing: false,
  1283. })
  1284. const question = createMemo(() => questions()[store.tab])
  1285. const confirm = createMemo(() => !single() && store.tab === questions().length)
  1286. const options = createMemo(() => question()?.options ?? [])
  1287. const input = createMemo(() => store.custom[store.tab] ?? "")
  1288. const multi = createMemo(() => question()?.multiple === true)
  1289. const customPicked = createMemo(() => {
  1290. const value = input()
  1291. if (!value) return false
  1292. return store.answers[store.tab]?.includes(value) ?? false
  1293. })
  1294. function submit() {
  1295. const answers = questions().map((_, i) => store.answers[i] ?? [])
  1296. data.replyToQuestion?.({
  1297. requestID: props.request.id,
  1298. answers,
  1299. })
  1300. }
  1301. function reject() {
  1302. data.rejectQuestion?.({
  1303. requestID: props.request.id,
  1304. })
  1305. }
  1306. function pick(answer: string, custom: boolean = false) {
  1307. const answers = [...store.answers]
  1308. answers[store.tab] = [answer]
  1309. setStore("answers", answers)
  1310. if (custom) {
  1311. const inputs = [...store.custom]
  1312. inputs[store.tab] = answer
  1313. setStore("custom", inputs)
  1314. }
  1315. if (single()) {
  1316. data.replyToQuestion?.({
  1317. requestID: props.request.id,
  1318. answers: [[answer]],
  1319. })
  1320. return
  1321. }
  1322. setStore("tab", store.tab + 1)
  1323. }
  1324. function toggle(answer: string) {
  1325. const existing = store.answers[store.tab] ?? []
  1326. const next = [...existing]
  1327. const index = next.indexOf(answer)
  1328. if (index === -1) next.push(answer)
  1329. if (index !== -1) next.splice(index, 1)
  1330. const answers = [...store.answers]
  1331. answers[store.tab] = next
  1332. setStore("answers", answers)
  1333. }
  1334. function selectTab(index: number) {
  1335. setStore("tab", index)
  1336. setStore("editing", false)
  1337. }
  1338. function selectOption(optIndex: number) {
  1339. if (optIndex === options().length) {
  1340. setStore("editing", true)
  1341. return
  1342. }
  1343. const opt = options()[optIndex]
  1344. if (!opt) return
  1345. if (multi()) {
  1346. toggle(opt.label)
  1347. return
  1348. }
  1349. pick(opt.label)
  1350. }
  1351. function handleCustomSubmit(e: Event) {
  1352. e.preventDefault()
  1353. const value = input().trim()
  1354. if (!value) {
  1355. setStore("editing", false)
  1356. return
  1357. }
  1358. if (multi()) {
  1359. const existing = store.answers[store.tab] ?? []
  1360. const next = [...existing]
  1361. if (!next.includes(value)) next.push(value)
  1362. const answers = [...store.answers]
  1363. answers[store.tab] = next
  1364. setStore("answers", answers)
  1365. setStore("editing", false)
  1366. return
  1367. }
  1368. pick(value, true)
  1369. setStore("editing", false)
  1370. }
  1371. return (
  1372. <div data-component="question-prompt">
  1373. <Show when={!single()}>
  1374. <div data-slot="question-tabs">
  1375. <For each={questions()}>
  1376. {(q, index) => {
  1377. const active = () => index() === store.tab
  1378. const answered = () => (store.answers[index()]?.length ?? 0) > 0
  1379. return (
  1380. <button
  1381. data-slot="question-tab"
  1382. data-active={active()}
  1383. data-answered={answered()}
  1384. onClick={() => selectTab(index())}
  1385. >
  1386. {q.header}
  1387. </button>
  1388. )
  1389. }}
  1390. </For>
  1391. <button data-slot="question-tab" data-active={confirm()} onClick={() => selectTab(questions().length)}>
  1392. {i18n.t("ui.common.confirm")}
  1393. </button>
  1394. </div>
  1395. </Show>
  1396. <Show when={!confirm()}>
  1397. <div data-slot="question-content">
  1398. <div data-slot="question-text">
  1399. {question()?.question}
  1400. {multi() ? " " + i18n.t("ui.question.multiHint") : ""}
  1401. </div>
  1402. <div data-slot="question-options">
  1403. <For each={options()}>
  1404. {(opt, i) => {
  1405. const picked = () => store.answers[store.tab]?.includes(opt.label) ?? false
  1406. return (
  1407. <button data-slot="question-option" data-picked={picked()} onClick={() => selectOption(i())}>
  1408. <span data-slot="option-label">{opt.label}</span>
  1409. <Show when={opt.description}>
  1410. <span data-slot="option-description">{opt.description}</span>
  1411. </Show>
  1412. <Show when={picked()}>
  1413. <Icon name="check-small" size="normal" />
  1414. </Show>
  1415. </button>
  1416. )
  1417. }}
  1418. </For>
  1419. <button
  1420. data-slot="question-option"
  1421. data-picked={customPicked()}
  1422. onClick={() => selectOption(options().length)}
  1423. >
  1424. <span data-slot="option-label">{i18n.t("ui.messagePart.option.typeOwnAnswer")}</span>
  1425. <Show when={!store.editing && input()}>
  1426. <span data-slot="option-description">{input()}</span>
  1427. </Show>
  1428. <Show when={customPicked()}>
  1429. <Icon name="check-small" size="normal" />
  1430. </Show>
  1431. </button>
  1432. <Show when={store.editing}>
  1433. <form data-slot="custom-input-form" onSubmit={handleCustomSubmit}>
  1434. <input
  1435. ref={(el) => setTimeout(() => el.focus(), 0)}
  1436. type="text"
  1437. data-slot="custom-input"
  1438. placeholder={i18n.t("ui.question.custom.placeholder")}
  1439. value={input()}
  1440. onInput={(e) => {
  1441. const inputs = [...store.custom]
  1442. inputs[store.tab] = e.currentTarget.value
  1443. setStore("custom", inputs)
  1444. }}
  1445. />
  1446. <Button type="submit" variant="primary" size="small">
  1447. {multi() ? i18n.t("ui.common.add") : i18n.t("ui.common.submit")}
  1448. </Button>
  1449. <Button type="button" variant="ghost" size="small" onClick={() => setStore("editing", false)}>
  1450. {i18n.t("ui.common.cancel")}
  1451. </Button>
  1452. </form>
  1453. </Show>
  1454. </div>
  1455. </div>
  1456. </Show>
  1457. <Show when={confirm()}>
  1458. <div data-slot="question-review">
  1459. <div data-slot="review-title">{i18n.t("ui.messagePart.review.title")}</div>
  1460. <For each={questions()}>
  1461. {(q, index) => {
  1462. const value = () => store.answers[index()]?.join(", ") ?? ""
  1463. const answered = () => Boolean(value())
  1464. return (
  1465. <div data-slot="review-item">
  1466. <span data-slot="review-label">{q.question}</span>
  1467. <span data-slot="review-value" data-answered={answered()}>
  1468. {answered() ? value() : i18n.t("ui.question.review.notAnswered")}
  1469. </span>
  1470. </div>
  1471. )
  1472. }}
  1473. </For>
  1474. </div>
  1475. </Show>
  1476. <div data-slot="question-actions">
  1477. <Button variant="ghost" size="small" onClick={reject}>
  1478. {i18n.t("ui.common.dismiss")}
  1479. </Button>
  1480. <Show when={!single()}>
  1481. <Show when={confirm()}>
  1482. <Button variant="primary" size="small" onClick={submit}>
  1483. {i18n.t("ui.common.submit")}
  1484. </Button>
  1485. </Show>
  1486. <Show when={!confirm() && multi()}>
  1487. <Button
  1488. variant="secondary"
  1489. size="small"
  1490. onClick={() => selectTab(store.tab + 1)}
  1491. disabled={(store.answers[store.tab]?.length ?? 0) === 0}
  1492. >
  1493. {i18n.t("ui.common.next")}
  1494. </Button>
  1495. </Show>
  1496. </Show>
  1497. </div>
  1498. </div>
  1499. )
  1500. }