message-part.tsx 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. import {
  2. Component,
  3. createEffect,
  4. createMemo,
  5. createSignal,
  6. For,
  7. Match,
  8. onMount,
  9. Show,
  10. Switch,
  11. onCleanup,
  12. Index,
  13. type JSX,
  14. } from "solid-js"
  15. import stripAnsi from "strip-ansi"
  16. import { Dynamic } from "solid-js/web"
  17. import {
  18. AgentPart,
  19. AssistantMessage,
  20. FilePart,
  21. Message as MessageType,
  22. Part as PartType,
  23. ReasoningPart,
  24. TextPart,
  25. ToolPart,
  26. UserMessage,
  27. Todo,
  28. QuestionAnswer,
  29. QuestionInfo,
  30. } from "@opencode-ai/sdk/v2"
  31. import { useData } from "../context"
  32. import { useFileComponent } from "../context/file"
  33. import { useDialog } from "../context/dialog"
  34. import { type UiI18n, useI18n } from "../context/i18n"
  35. import { BasicTool, GenericTool } from "./basic-tool"
  36. import { Accordion } from "./accordion"
  37. import { StickyAccordionHeader } from "./sticky-accordion-header"
  38. import { Card } from "./card"
  39. import { Collapsible } from "./collapsible"
  40. import { FileIcon } from "./file-icon"
  41. import { Icon } from "./icon"
  42. import { ToolErrorCard } from "./tool-error-card"
  43. import { Checkbox } from "./checkbox"
  44. import { DiffChanges } from "./diff-changes"
  45. import { Markdown } from "./markdown"
  46. import { ImagePreview } from "./image-preview"
  47. import { getDirectory as _getDirectory, getFilename } from "@opencode-ai/util/path"
  48. import { checksum } from "@opencode-ai/util/encode"
  49. import { Tooltip } from "./tooltip"
  50. import { IconButton } from "./icon-button"
  51. import { TextShimmer } from "./text-shimmer"
  52. import { AnimatedCountList } from "./tool-count-summary"
  53. import { ToolStatusTitle } from "./tool-status-title"
  54. import { animate } from "motion"
  55. import { useLocation } from "@solidjs/router"
  56. function ShellSubmessage(props: { text: string; animate?: boolean }) {
  57. let widthRef: HTMLSpanElement | undefined
  58. let valueRef: HTMLSpanElement | undefined
  59. onMount(() => {
  60. if (!props.animate) return
  61. requestAnimationFrame(() => {
  62. if (widthRef) {
  63. animate(widthRef, { width: "auto" }, { type: "spring", visualDuration: 0.25, bounce: 0 })
  64. }
  65. if (valueRef) {
  66. animate(valueRef, { opacity: 1, filter: "blur(0px)" }, { duration: 0.32, ease: [0.16, 1, 0.3, 1] })
  67. }
  68. })
  69. })
  70. return (
  71. <span data-component="shell-submessage">
  72. <span ref={widthRef} data-slot="shell-submessage-width" style={{ width: props.animate ? "0px" : undefined }}>
  73. <span data-slot="basic-tool-tool-subtitle">
  74. <span
  75. ref={valueRef}
  76. data-slot="shell-submessage-value"
  77. style={props.animate ? { opacity: 0, filter: "blur(2px)" } : undefined}
  78. >
  79. {props.text}
  80. </span>
  81. </span>
  82. </span>
  83. </span>
  84. )
  85. }
  86. interface Diagnostic {
  87. range: {
  88. start: { line: number; character: number }
  89. end: { line: number; character: number }
  90. }
  91. message: string
  92. severity?: number
  93. }
  94. function getDiagnostics(
  95. diagnosticsByFile: Record<string, Diagnostic[]> | undefined,
  96. filePath: string | undefined,
  97. ): Diagnostic[] {
  98. if (!diagnosticsByFile || !filePath) return []
  99. const diagnostics = diagnosticsByFile[filePath] ?? []
  100. return diagnostics.filter((d) => d.severity === 1).slice(0, 3)
  101. }
  102. function DiagnosticsDisplay(props: { diagnostics: Diagnostic[] }): JSX.Element {
  103. const i18n = useI18n()
  104. return (
  105. <Show when={props.diagnostics.length > 0}>
  106. <div data-component="diagnostics">
  107. <For each={props.diagnostics}>
  108. {(diagnostic) => (
  109. <div data-slot="diagnostic">
  110. <span data-slot="diagnostic-label">{i18n.t("ui.messagePart.diagnostic.error")}</span>
  111. <span data-slot="diagnostic-location">
  112. [{diagnostic.range.start.line + 1}:{diagnostic.range.start.character + 1}]
  113. </span>
  114. <span data-slot="diagnostic-message">{diagnostic.message}</span>
  115. </div>
  116. )}
  117. </For>
  118. </div>
  119. </Show>
  120. )
  121. }
  122. export interface MessageProps {
  123. message: MessageType
  124. parts: PartType[]
  125. actions?: UserActions
  126. showAssistantCopyPartID?: string | null
  127. interrupted?: boolean
  128. queued?: boolean
  129. showReasoningSummaries?: boolean
  130. }
  131. export type SessionAction = (input: { sessionID: string; messageID: string }) => Promise<void> | void
  132. export type UserActions = {
  133. fork?: SessionAction
  134. revert?: SessionAction
  135. }
  136. export interface MessagePartProps {
  137. part: PartType
  138. message: MessageType
  139. hideDetails?: boolean
  140. defaultOpen?: boolean
  141. showAssistantCopyPartID?: string | null
  142. turnDurationMs?: number
  143. }
  144. export type PartComponent = Component<MessagePartProps>
  145. export const PART_MAPPING: Record<string, PartComponent | undefined> = {}
  146. const TEXT_RENDER_THROTTLE_MS = 100
  147. function createThrottledValue(getValue: () => string) {
  148. const [value, setValue] = createSignal(getValue())
  149. let timeout: ReturnType<typeof setTimeout> | undefined
  150. let last = 0
  151. createEffect(() => {
  152. const next = getValue()
  153. const now = Date.now()
  154. const remaining = TEXT_RENDER_THROTTLE_MS - (now - last)
  155. if (remaining <= 0) {
  156. if (timeout) {
  157. clearTimeout(timeout)
  158. timeout = undefined
  159. }
  160. last = now
  161. setValue(next)
  162. return
  163. }
  164. if (timeout) clearTimeout(timeout)
  165. timeout = setTimeout(() => {
  166. last = Date.now()
  167. setValue(next)
  168. timeout = undefined
  169. }, remaining)
  170. })
  171. onCleanup(() => {
  172. if (timeout) clearTimeout(timeout)
  173. })
  174. return value
  175. }
  176. function relativizeProjectPath(path: string, directory?: string) {
  177. if (!path) return ""
  178. if (!directory) return path
  179. if (directory === "/") return path
  180. if (directory === "\\") return path
  181. if (path === directory) return ""
  182. const separator = directory.includes("\\") ? "\\" : "/"
  183. const prefix = directory.endsWith(separator) ? directory : directory + separator
  184. if (!path.startsWith(prefix)) return path
  185. return path.slice(directory.length)
  186. }
  187. function getDirectory(path: string | undefined) {
  188. const data = useData()
  189. return relativizeProjectPath(_getDirectory(path), data.directory)
  190. }
  191. import type { IconProps } from "./icon"
  192. export type ToolInfo = {
  193. icon: IconProps["name"]
  194. title: string
  195. subtitle?: string
  196. }
  197. function agentTitle(i18n: UiI18n, type?: string) {
  198. if (!type) return i18n.t("ui.tool.agent.default")
  199. return i18n.t("ui.tool.agent", { type })
  200. }
  201. export function getToolInfo(tool: string, input: any = {}): ToolInfo {
  202. const i18n = useI18n()
  203. switch (tool) {
  204. case "read":
  205. return {
  206. icon: "glasses",
  207. title: i18n.t("ui.tool.read"),
  208. subtitle: input.filePath ? getFilename(input.filePath) : undefined,
  209. }
  210. case "list":
  211. return {
  212. icon: "bullet-list",
  213. title: i18n.t("ui.tool.list"),
  214. subtitle: input.path ? getFilename(input.path) : undefined,
  215. }
  216. case "glob":
  217. return {
  218. icon: "magnifying-glass-menu",
  219. title: i18n.t("ui.tool.glob"),
  220. subtitle: input.pattern,
  221. }
  222. case "grep":
  223. return {
  224. icon: "magnifying-glass-menu",
  225. title: i18n.t("ui.tool.grep"),
  226. subtitle: input.pattern,
  227. }
  228. case "webfetch":
  229. return {
  230. icon: "window-cursor",
  231. title: i18n.t("ui.tool.webfetch"),
  232. subtitle: input.url,
  233. }
  234. case "websearch":
  235. return {
  236. icon: "window-cursor",
  237. title: i18n.t("ui.tool.websearch"),
  238. subtitle: input.query,
  239. }
  240. case "codesearch":
  241. return {
  242. icon: "code",
  243. title: i18n.t("ui.tool.codesearch"),
  244. subtitle: input.query,
  245. }
  246. case "task": {
  247. const type =
  248. typeof input.subagent_type === "string" && input.subagent_type
  249. ? input.subagent_type[0]!.toUpperCase() + input.subagent_type.slice(1)
  250. : undefined
  251. return {
  252. icon: "task",
  253. title: agentTitle(i18n, type),
  254. subtitle: input.description,
  255. }
  256. }
  257. case "bash":
  258. return {
  259. icon: "console",
  260. title: i18n.t("ui.tool.shell"),
  261. subtitle: input.description,
  262. }
  263. case "edit":
  264. return {
  265. icon: "code-lines",
  266. title: i18n.t("ui.messagePart.title.edit"),
  267. subtitle: input.filePath ? getFilename(input.filePath) : undefined,
  268. }
  269. case "write":
  270. return {
  271. icon: "code-lines",
  272. title: i18n.t("ui.messagePart.title.write"),
  273. subtitle: input.filePath ? getFilename(input.filePath) : undefined,
  274. }
  275. case "apply_patch":
  276. return {
  277. icon: "code-lines",
  278. title: i18n.t("ui.tool.patch"),
  279. subtitle: input.files?.length
  280. ? `${input.files.length} ${i18n.t(input.files.length > 1 ? "ui.common.file.other" : "ui.common.file.one")}`
  281. : undefined,
  282. }
  283. case "todowrite":
  284. return {
  285. icon: "checklist",
  286. title: i18n.t("ui.tool.todos"),
  287. }
  288. case "todoread":
  289. return {
  290. icon: "checklist",
  291. title: i18n.t("ui.tool.todos.read"),
  292. }
  293. case "question":
  294. return {
  295. icon: "bubble-5",
  296. title: i18n.t("ui.tool.questions"),
  297. }
  298. case "skill":
  299. return {
  300. icon: "brain",
  301. title: input.name || "skill",
  302. }
  303. default:
  304. return {
  305. icon: "mcp",
  306. title: tool,
  307. }
  308. }
  309. }
  310. function urls(text: string | undefined) {
  311. if (!text) return []
  312. const seen = new Set<string>()
  313. return [...text.matchAll(/https?:\/\/[^\s<>"'`)\]]+/g)]
  314. .map((item) => item[0].replace(/[),.;:!?]+$/g, ""))
  315. .filter((item) => {
  316. if (seen.has(item)) return false
  317. seen.add(item)
  318. return true
  319. })
  320. }
  321. const CONTEXT_GROUP_TOOLS = new Set(["read", "glob", "grep", "list"])
  322. const HIDDEN_TOOLS = new Set(["todowrite", "todoread"])
  323. function list<T>(value: T[] | undefined | null, fallback: T[]) {
  324. if (Array.isArray(value)) return value
  325. return fallback
  326. }
  327. function same<T>(a: readonly T[] | undefined, b: readonly T[] | undefined) {
  328. if (a === b) return true
  329. if (!a || !b) return false
  330. if (a.length !== b.length) return false
  331. return a.every((x, i) => x === b[i])
  332. }
  333. type PartRef = {
  334. messageID: string
  335. partID: string
  336. }
  337. type PartGroup =
  338. | {
  339. key: string
  340. type: "part"
  341. ref: PartRef
  342. }
  343. | {
  344. key: string
  345. type: "context"
  346. refs: PartRef[]
  347. }
  348. function sameRef(a: PartRef, b: PartRef) {
  349. return a.messageID === b.messageID && a.partID === b.partID
  350. }
  351. function sameGroup(a: PartGroup, b: PartGroup) {
  352. if (a === b) return true
  353. if (a.key !== b.key) return false
  354. if (a.type !== b.type) return false
  355. if (a.type === "part") {
  356. if (b.type !== "part") return false
  357. return sameRef(a.ref, b.ref)
  358. }
  359. if (b.type !== "context") return false
  360. if (a.refs.length !== b.refs.length) return false
  361. return a.refs.every((ref, i) => sameRef(ref, b.refs[i]!))
  362. }
  363. function sameGroups(a: readonly PartGroup[] | undefined, b: readonly PartGroup[] | undefined) {
  364. if (a === b) return true
  365. if (!a || !b) return false
  366. if (a.length !== b.length) return false
  367. return a.every((item, i) => sameGroup(item, b[i]!))
  368. }
  369. function groupParts(parts: { messageID: string; part: PartType }[]) {
  370. const result: PartGroup[] = []
  371. let start = -1
  372. const flush = (end: number) => {
  373. if (start < 0) return
  374. const first = parts[start]
  375. const last = parts[end]
  376. if (!first || !last) {
  377. start = -1
  378. return
  379. }
  380. result.push({
  381. key: `context:${first.part.id}`,
  382. type: "context",
  383. refs: parts.slice(start, end + 1).map((item) => ({
  384. messageID: item.messageID,
  385. partID: item.part.id,
  386. })),
  387. })
  388. start = -1
  389. }
  390. parts.forEach((item, index) => {
  391. if (isContextGroupTool(item.part)) {
  392. if (start < 0) start = index
  393. return
  394. }
  395. flush(index - 1)
  396. result.push({
  397. key: `part:${item.messageID}:${item.part.id}`,
  398. type: "part",
  399. ref: {
  400. messageID: item.messageID,
  401. partID: item.part.id,
  402. },
  403. })
  404. })
  405. flush(parts.length - 1)
  406. return result
  407. }
  408. function index<T extends { id: string }>(items: readonly T[]) {
  409. return new Map(items.map((item) => [item.id, item] as const))
  410. }
  411. function renderable(part: PartType, showReasoningSummaries = true) {
  412. if (part.type === "tool") {
  413. if (HIDDEN_TOOLS.has(part.tool)) return false
  414. if (part.tool === "question") return part.state.status !== "pending" && part.state.status !== "running"
  415. return true
  416. }
  417. if (part.type === "text") return !!part.text?.trim()
  418. if (part.type === "reasoning") return showReasoningSummaries && !!part.text?.trim()
  419. return !!PART_MAPPING[part.type]
  420. }
  421. function toolDefaultOpen(tool: string, shell = false, edit = false) {
  422. if (tool === "bash") return shell
  423. if (tool === "edit" || tool === "write" || tool === "apply_patch") return edit
  424. }
  425. function partDefaultOpen(part: PartType, shell = false, edit = false) {
  426. if (part.type !== "tool") return
  427. return toolDefaultOpen(part.tool, shell, edit)
  428. }
  429. export function AssistantParts(props: {
  430. messages: AssistantMessage[]
  431. showAssistantCopyPartID?: string | null
  432. turnDurationMs?: number
  433. working?: boolean
  434. showReasoningSummaries?: boolean
  435. shellToolDefaultOpen?: boolean
  436. editToolDefaultOpen?: boolean
  437. }) {
  438. const data = useData()
  439. const emptyParts: PartType[] = []
  440. const emptyTools: ToolPart[] = []
  441. const msgs = createMemo(() => index(props.messages))
  442. const part = createMemo(
  443. () =>
  444. new Map(
  445. props.messages.map((message) => [message.id, index(list(data.store.part?.[message.id], emptyParts))] as const),
  446. ),
  447. )
  448. const grouped = createMemo(
  449. () =>
  450. groupParts(
  451. props.messages.flatMap((message) =>
  452. list(data.store.part?.[message.id], emptyParts)
  453. .filter((part) => renderable(part, props.showReasoningSummaries ?? true))
  454. .map((part) => ({
  455. messageID: message.id,
  456. part,
  457. })),
  458. ),
  459. ),
  460. [] as PartGroup[],
  461. { equals: sameGroups },
  462. )
  463. const last = createMemo(() => grouped().at(-1)?.key)
  464. return (
  465. <Index each={grouped()}>
  466. {(entryAccessor) => {
  467. const entryType = createMemo(() => entryAccessor().type)
  468. return (
  469. <Switch>
  470. <Match when={entryType() === "context"}>
  471. {(() => {
  472. const parts = createMemo(
  473. () => {
  474. const entry = entryAccessor()
  475. if (entry.type !== "context") return emptyTools
  476. return entry.refs
  477. .map((ref) => part().get(ref.messageID)?.get(ref.partID))
  478. .filter((part): part is ToolPart => !!part && isContextGroupTool(part))
  479. },
  480. emptyTools,
  481. { equals: same },
  482. )
  483. const busy = createMemo(() => props.working && last() === entryAccessor().key)
  484. return (
  485. <Show when={parts().length > 0}>
  486. <ContextToolGroup parts={parts()} busy={busy()} />
  487. </Show>
  488. )
  489. })()}
  490. </Match>
  491. <Match when={entryType() === "part"}>
  492. {(() => {
  493. const message = createMemo(() => {
  494. const entry = entryAccessor()
  495. if (entry.type !== "part") return
  496. return msgs().get(entry.ref.messageID)
  497. })
  498. const item = createMemo(() => {
  499. const entry = entryAccessor()
  500. if (entry.type !== "part") return
  501. return part().get(entry.ref.messageID)?.get(entry.ref.partID)
  502. })
  503. return (
  504. <Show when={message()}>
  505. <Show when={item()}>
  506. <Part
  507. part={item()!}
  508. message={message()!}
  509. showAssistantCopyPartID={props.showAssistantCopyPartID}
  510. turnDurationMs={props.turnDurationMs}
  511. defaultOpen={partDefaultOpen(item()!, props.shellToolDefaultOpen, props.editToolDefaultOpen)}
  512. />
  513. </Show>
  514. </Show>
  515. )
  516. })()}
  517. </Match>
  518. </Switch>
  519. )
  520. }}
  521. </Index>
  522. )
  523. }
  524. function isContextGroupTool(part: PartType): part is ToolPart {
  525. return part.type === "tool" && CONTEXT_GROUP_TOOLS.has(part.tool)
  526. }
  527. function contextToolDetail(part: ToolPart): string | undefined {
  528. const info = getToolInfo(part.tool, part.state.input ?? {})
  529. if (info.subtitle) return info.subtitle
  530. if (part.state.status === "error") return part.state.error
  531. if ((part.state.status === "running" || part.state.status === "completed") && part.state.title)
  532. return part.state.title
  533. const description = part.state.input?.description
  534. if (typeof description === "string") return description
  535. return undefined
  536. }
  537. function contextToolTrigger(part: ToolPart, i18n: ReturnType<typeof useI18n>) {
  538. const input = (part.state.input ?? {}) as Record<string, unknown>
  539. const path = typeof input.path === "string" ? input.path : "/"
  540. const filePath = typeof input.filePath === "string" ? input.filePath : undefined
  541. const pattern = typeof input.pattern === "string" ? input.pattern : undefined
  542. const include = typeof input.include === "string" ? input.include : undefined
  543. const offset = typeof input.offset === "number" ? input.offset : undefined
  544. const limit = typeof input.limit === "number" ? input.limit : undefined
  545. switch (part.tool) {
  546. case "read": {
  547. const args: string[] = []
  548. if (offset !== undefined) args.push("offset=" + offset)
  549. if (limit !== undefined) args.push("limit=" + limit)
  550. return {
  551. title: i18n.t("ui.tool.read"),
  552. subtitle: filePath ? getFilename(filePath) : "",
  553. args,
  554. }
  555. }
  556. case "list":
  557. return {
  558. title: i18n.t("ui.tool.list"),
  559. subtitle: getDirectory(path),
  560. }
  561. case "glob":
  562. return {
  563. title: i18n.t("ui.tool.glob"),
  564. subtitle: getDirectory(path),
  565. args: pattern ? ["pattern=" + pattern] : [],
  566. }
  567. case "grep": {
  568. const args: string[] = []
  569. if (pattern) args.push("pattern=" + pattern)
  570. if (include) args.push("include=" + include)
  571. return {
  572. title: i18n.t("ui.tool.grep"),
  573. subtitle: getDirectory(path),
  574. args,
  575. }
  576. }
  577. default: {
  578. const info = getToolInfo(part.tool, input)
  579. return {
  580. title: info.title,
  581. subtitle: info.subtitle || contextToolDetail(part),
  582. args: [],
  583. }
  584. }
  585. }
  586. }
  587. function contextToolSummary(parts: ToolPart[]) {
  588. const read = parts.filter((part) => part.tool === "read").length
  589. const search = parts.filter((part) => part.tool === "glob" || part.tool === "grep").length
  590. const list = parts.filter((part) => part.tool === "list").length
  591. return { read, search, list }
  592. }
  593. function ExaOutput(props: { output?: string }) {
  594. const links = createMemo(() => urls(props.output))
  595. return (
  596. <Show when={links().length > 0}>
  597. <div data-component="exa-tool-output">
  598. <div data-slot="exa-tool-links">
  599. <For each={links()}>
  600. {(url) => (
  601. <a
  602. data-slot="exa-tool-link"
  603. href={url}
  604. target="_blank"
  605. rel="noopener noreferrer"
  606. onClick={(event) => event.stopPropagation()}
  607. >
  608. {url}
  609. </a>
  610. )}
  611. </For>
  612. </div>
  613. </div>
  614. </Show>
  615. )
  616. }
  617. export function registerPartComponent(type: string, component: PartComponent) {
  618. PART_MAPPING[type] = component
  619. }
  620. export function Message(props: MessageProps) {
  621. return (
  622. <Switch>
  623. <Match when={props.message.role === "user" && props.message}>
  624. {(userMessage) => (
  625. <UserMessageDisplay
  626. message={userMessage() as UserMessage}
  627. parts={props.parts}
  628. actions={props.actions}
  629. interrupted={props.interrupted}
  630. queued={props.queued}
  631. />
  632. )}
  633. </Match>
  634. <Match when={props.message.role === "assistant" && props.message}>
  635. {(assistantMessage) => (
  636. <AssistantMessageDisplay
  637. message={assistantMessage() as AssistantMessage}
  638. parts={props.parts}
  639. showAssistantCopyPartID={props.showAssistantCopyPartID}
  640. showReasoningSummaries={props.showReasoningSummaries}
  641. />
  642. )}
  643. </Match>
  644. </Switch>
  645. )
  646. }
  647. export function AssistantMessageDisplay(props: {
  648. message: AssistantMessage
  649. parts: PartType[]
  650. showAssistantCopyPartID?: string | null
  651. showReasoningSummaries?: boolean
  652. }) {
  653. const emptyTools: ToolPart[] = []
  654. const part = createMemo(() => index(props.parts))
  655. const grouped = createMemo(
  656. () =>
  657. groupParts(
  658. props.parts
  659. .filter((part) => renderable(part, props.showReasoningSummaries ?? true))
  660. .map((part) => ({
  661. messageID: props.message.id,
  662. part,
  663. })),
  664. ),
  665. [] as PartGroup[],
  666. { equals: sameGroups },
  667. )
  668. return (
  669. <Index each={grouped()}>
  670. {(entryAccessor) => {
  671. const entryType = createMemo(() => entryAccessor().type)
  672. return (
  673. <Switch>
  674. <Match when={entryType() === "context"}>
  675. {(() => {
  676. const parts = createMemo(
  677. () => {
  678. const entry = entryAccessor()
  679. if (entry.type !== "context") return emptyTools
  680. return entry.refs
  681. .map((ref) => part().get(ref.partID))
  682. .filter((part): part is ToolPart => !!part && isContextGroupTool(part))
  683. },
  684. emptyTools,
  685. { equals: same },
  686. )
  687. return (
  688. <Show when={parts().length > 0}>
  689. <ContextToolGroup parts={parts()} />
  690. </Show>
  691. )
  692. })()}
  693. </Match>
  694. <Match when={entryType() === "part"}>
  695. {(() => {
  696. const item = createMemo(() => {
  697. const entry = entryAccessor()
  698. if (entry.type !== "part") return
  699. return part().get(entry.ref.partID)
  700. })
  701. return (
  702. <Show when={item()}>
  703. <Part
  704. part={item()!}
  705. message={props.message}
  706. showAssistantCopyPartID={props.showAssistantCopyPartID}
  707. />
  708. </Show>
  709. )
  710. })()}
  711. </Match>
  712. </Switch>
  713. )
  714. }}
  715. </Index>
  716. )
  717. }
  718. function ContextToolGroup(props: { parts: ToolPart[]; busy?: boolean }) {
  719. const i18n = useI18n()
  720. const [open, setOpen] = createSignal(false)
  721. const pending = createMemo(
  722. () =>
  723. !!props.busy || props.parts.some((part) => part.state.status === "pending" || part.state.status === "running"),
  724. )
  725. const summary = createMemo(() => contextToolSummary(props.parts))
  726. return (
  727. <Collapsible open={open()} onOpenChange={setOpen} variant="ghost">
  728. <Collapsible.Trigger>
  729. <div data-component="context-tool-group-trigger">
  730. <span
  731. data-slot="context-tool-group-title"
  732. class="min-w-0 flex items-center gap-2 text-14-medium text-text-strong"
  733. >
  734. <span data-slot="context-tool-group-label" class="shrink-0">
  735. <ToolStatusTitle
  736. active={pending()}
  737. activeText={i18n.t("ui.sessionTurn.status.gatheringContext")}
  738. doneText={i18n.t("ui.sessionTurn.status.gatheredContext")}
  739. split={false}
  740. />
  741. </span>
  742. <span
  743. data-slot="context-tool-group-summary"
  744. class="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap font-normal text-text-base"
  745. >
  746. <AnimatedCountList
  747. items={[
  748. {
  749. key: "read",
  750. count: summary().read,
  751. one: i18n.t("ui.messagePart.context.read.one"),
  752. other: i18n.t("ui.messagePart.context.read.other"),
  753. },
  754. {
  755. key: "search",
  756. count: summary().search,
  757. one: i18n.t("ui.messagePart.context.search.one"),
  758. other: i18n.t("ui.messagePart.context.search.other"),
  759. },
  760. {
  761. key: "list",
  762. count: summary().list,
  763. one: i18n.t("ui.messagePart.context.list.one"),
  764. other: i18n.t("ui.messagePart.context.list.other"),
  765. },
  766. ]}
  767. fallback=""
  768. />
  769. </span>
  770. </span>
  771. <Collapsible.Arrow />
  772. </div>
  773. </Collapsible.Trigger>
  774. <Collapsible.Content>
  775. <div data-component="context-tool-group-list">
  776. <Index each={props.parts}>
  777. {(partAccessor) => {
  778. const trigger = createMemo(() => contextToolTrigger(partAccessor(), i18n))
  779. const running = createMemo(
  780. () => partAccessor().state.status === "pending" || partAccessor().state.status === "running",
  781. )
  782. return (
  783. <div data-slot="context-tool-group-item">
  784. <div data-component="tool-trigger">
  785. <div data-slot="basic-tool-tool-trigger-content">
  786. <div data-slot="basic-tool-tool-info">
  787. <div data-slot="basic-tool-tool-info-structured">
  788. <div data-slot="basic-tool-tool-info-main">
  789. <span data-slot="basic-tool-tool-title">
  790. <TextShimmer text={trigger().title} active={running()} />
  791. </span>
  792. <Show when={!running() && trigger().subtitle}>
  793. <span data-slot="basic-tool-tool-subtitle">{trigger().subtitle}</span>
  794. </Show>
  795. <Show when={!running() && trigger().args?.length}>
  796. <For each={trigger().args}>
  797. {(arg) => <span data-slot="basic-tool-tool-arg">{arg}</span>}
  798. </For>
  799. </Show>
  800. </div>
  801. </div>
  802. </div>
  803. </div>
  804. </div>
  805. </div>
  806. )
  807. }}
  808. </Index>
  809. </div>
  810. </Collapsible.Content>
  811. </Collapsible>
  812. )
  813. }
  814. export function UserMessageDisplay(props: {
  815. message: UserMessage
  816. parts: PartType[]
  817. actions?: UserActions
  818. interrupted?: boolean
  819. queued?: boolean
  820. }) {
  821. const data = useData()
  822. const dialog = useDialog()
  823. const i18n = useI18n()
  824. const [copied, setCopied] = createSignal(false)
  825. const [busy, setBusy] = createSignal<"fork" | "revert" | undefined>()
  826. const textPart = createMemo(
  827. () => props.parts?.find((p) => p.type === "text" && !(p as TextPart).synthetic) as TextPart | undefined,
  828. )
  829. const text = createMemo(() => textPart()?.text || "")
  830. const files = createMemo(() => (props.parts?.filter((p) => p.type === "file") as FilePart[]) ?? [])
  831. const attachments = createMemo(() =>
  832. files()?.filter((f) => {
  833. const mime = f.mime
  834. return mime.startsWith("image/") || mime === "application/pdf"
  835. }),
  836. )
  837. const inlineFiles = createMemo(() =>
  838. files().filter((f) => {
  839. const mime = f.mime
  840. return !mime.startsWith("image/") && mime !== "application/pdf" && f.source?.text?.start !== undefined
  841. }),
  842. )
  843. const agents = createMemo(() => (props.parts?.filter((p) => p.type === "agent") as AgentPart[]) ?? [])
  844. const model = createMemo(() => {
  845. const providerID = props.message.model?.providerID
  846. const modelID = props.message.model?.modelID
  847. if (!providerID || !modelID) return ""
  848. const match = data.store.provider?.all?.find((p) => p.id === providerID)
  849. return match?.models?.[modelID]?.name ?? modelID
  850. })
  851. const stamp = createMemo(() => {
  852. const created = props.message.time?.created
  853. if (typeof created !== "number") return ""
  854. const date = new Date(created)
  855. const hours = date.getHours()
  856. const hour12 = hours % 12 || 12
  857. const minute = String(date.getMinutes()).padStart(2, "0")
  858. return `${hour12}:${minute} ${hours < 12 ? "AM" : "PM"}`
  859. })
  860. const metaHead = createMemo(() => {
  861. const agent = props.message.agent
  862. const items = [agent ? agent[0]?.toUpperCase() + agent.slice(1) : "", model()]
  863. return items.filter((x) => !!x).join("\u00A0\u00B7\u00A0")
  864. })
  865. const metaTail = createMemo(() => {
  866. const items = [stamp(), props.interrupted ? i18n.t("ui.message.interrupted") : ""]
  867. return items.filter((x) => !!x).join("\u00A0\u00B7\u00A0")
  868. })
  869. const openImagePreview = (url: string, alt?: string) => {
  870. dialog.show(() => <ImagePreview src={url} alt={alt} />)
  871. }
  872. const handleCopy = async () => {
  873. const content = text()
  874. if (!content) return
  875. await navigator.clipboard.writeText(content)
  876. setCopied(true)
  877. setTimeout(() => setCopied(false), 2000)
  878. }
  879. const run = (kind: "fork" | "revert") => {
  880. const act = kind === "fork" ? props.actions?.fork : props.actions?.revert
  881. if (!act || busy()) return
  882. setBusy(kind)
  883. void Promise.resolve()
  884. .then(() =>
  885. act({
  886. sessionID: props.message.sessionID,
  887. messageID: props.message.id,
  888. }),
  889. )
  890. .finally(() => {
  891. if (busy() === kind) setBusy(undefined)
  892. })
  893. }
  894. return (
  895. <div data-component="user-message" data-interrupted={props.interrupted ? "" : undefined}>
  896. <Show when={attachments().length > 0}>
  897. <div data-slot="user-message-attachments">
  898. <For each={attachments()}>
  899. {(file) => (
  900. <div
  901. data-slot="user-message-attachment"
  902. data-type={file.mime.startsWith("image/") ? "image" : "file"}
  903. data-queued={props.queued ? "" : undefined}
  904. onClick={() => {
  905. if (file.mime.startsWith("image/") && file.url) {
  906. openImagePreview(file.url, file.filename)
  907. }
  908. }}
  909. >
  910. <Show
  911. when={file.mime.startsWith("image/") && file.url}
  912. fallback={
  913. <div data-slot="user-message-attachment-icon">
  914. <Icon name="folder" />
  915. </div>
  916. }
  917. >
  918. <img
  919. data-slot="user-message-attachment-image"
  920. src={file.url}
  921. alt={file.filename ?? i18n.t("ui.message.attachment.alt")}
  922. />
  923. </Show>
  924. </div>
  925. )}
  926. </For>
  927. </div>
  928. </Show>
  929. <Show when={text()}>
  930. <>
  931. <div data-slot="user-message-body">
  932. <div data-slot="user-message-text" data-queued={props.queued ? "" : undefined}>
  933. <HighlightedText text={text()} references={inlineFiles()} agents={agents()} />
  934. </div>
  935. <Show when={props.queued}>
  936. <div data-slot="user-message-queued-indicator">
  937. <TextShimmer text={i18n.t("ui.message.queued")} />
  938. </div>
  939. </Show>
  940. </div>
  941. <div data-slot="user-message-copy-wrapper" data-interrupted={props.interrupted ? "" : undefined}>
  942. <Show when={metaHead() || metaTail()}>
  943. <span data-slot="user-message-meta-wrap">
  944. <Show when={metaHead()}>
  945. <span data-slot="user-message-meta" class="text-12-regular text-text-weak cursor-default">
  946. {metaHead()}
  947. </span>
  948. </Show>
  949. <Show when={metaHead() && metaTail()}>
  950. <span data-slot="user-message-meta-sep" class="text-12-regular text-text-weak cursor-default">
  951. {"\u00A0\u00B7\u00A0"}
  952. </span>
  953. </Show>
  954. <Show when={metaTail()}>
  955. <span data-slot="user-message-meta-tail" class="text-12-regular text-text-weak cursor-default">
  956. {metaTail()}
  957. </span>
  958. </Show>
  959. </span>
  960. </Show>
  961. <Show when={props.actions?.fork}>
  962. <Tooltip value={i18n.t("ui.message.forkMessage")} placement="top" gutter={4}>
  963. <IconButton
  964. icon="fork"
  965. size="normal"
  966. variant="ghost"
  967. disabled={!!busy()}
  968. onMouseDown={(e) => e.preventDefault()}
  969. onClick={(event) => {
  970. event.stopPropagation()
  971. run("fork")
  972. }}
  973. aria-label={i18n.t("ui.message.forkMessage")}
  974. />
  975. </Tooltip>
  976. </Show>
  977. <Show when={props.actions?.revert}>
  978. <Tooltip value={i18n.t("ui.message.revertMessage")} placement="top" gutter={4}>
  979. <IconButton
  980. icon="reset"
  981. size="normal"
  982. variant="ghost"
  983. disabled={!!busy()}
  984. onMouseDown={(e) => e.preventDefault()}
  985. onClick={(event) => {
  986. event.stopPropagation()
  987. run("revert")
  988. }}
  989. aria-label={i18n.t("ui.message.revertMessage")}
  990. />
  991. </Tooltip>
  992. </Show>
  993. <Tooltip
  994. value={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyMessage")}
  995. placement="top"
  996. gutter={4}
  997. >
  998. <IconButton
  999. icon={copied() ? "check" : "copy"}
  1000. size="normal"
  1001. variant="ghost"
  1002. onMouseDown={(e) => e.preventDefault()}
  1003. onClick={(event) => {
  1004. event.stopPropagation()
  1005. handleCopy()
  1006. }}
  1007. aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyMessage")}
  1008. />
  1009. </Tooltip>
  1010. </div>
  1011. </>
  1012. </Show>
  1013. </div>
  1014. )
  1015. }
  1016. type HighlightSegment = { text: string; type?: "file" | "agent" }
  1017. function HighlightedText(props: { text: string; references: FilePart[]; agents: AgentPart[] }) {
  1018. const segments = createMemo(() => {
  1019. const text = props.text
  1020. const allRefs: { start: number; end: number; type: "file" | "agent" }[] = [
  1021. ...props.references
  1022. .filter((r) => r.source?.text?.start !== undefined && r.source?.text?.end !== undefined)
  1023. .map((r) => ({ start: r.source!.text!.start, end: r.source!.text!.end, type: "file" as const })),
  1024. ...props.agents
  1025. .filter((a) => a.source?.start !== undefined && a.source?.end !== undefined)
  1026. .map((a) => ({ start: a.source!.start, end: a.source!.end, type: "agent" as const })),
  1027. ].sort((a, b) => a.start - b.start)
  1028. const result: HighlightSegment[] = []
  1029. let lastIndex = 0
  1030. for (const ref of allRefs) {
  1031. if (ref.start < lastIndex) continue
  1032. if (ref.start > lastIndex) {
  1033. result.push({ text: text.slice(lastIndex, ref.start) })
  1034. }
  1035. result.push({ text: text.slice(ref.start, ref.end), type: ref.type })
  1036. lastIndex = ref.end
  1037. }
  1038. if (lastIndex < text.length) {
  1039. result.push({ text: text.slice(lastIndex) })
  1040. }
  1041. return result
  1042. })
  1043. return <For each={segments()}>{(segment) => <span data-highlight={segment.type}>{segment.text}</span>}</For>
  1044. }
  1045. export function Part(props: MessagePartProps) {
  1046. const component = createMemo(() => PART_MAPPING[props.part.type])
  1047. return (
  1048. <Show when={component()}>
  1049. <Dynamic
  1050. component={component()}
  1051. part={props.part}
  1052. message={props.message}
  1053. hideDetails={props.hideDetails}
  1054. defaultOpen={props.defaultOpen}
  1055. showAssistantCopyPartID={props.showAssistantCopyPartID}
  1056. turnDurationMs={props.turnDurationMs}
  1057. />
  1058. </Show>
  1059. )
  1060. }
  1061. export interface ToolProps {
  1062. input: Record<string, any>
  1063. metadata: Record<string, any>
  1064. tool: string
  1065. output?: string
  1066. status?: string
  1067. hideDetails?: boolean
  1068. defaultOpen?: boolean
  1069. forceOpen?: boolean
  1070. locked?: boolean
  1071. }
  1072. export type ToolComponent = Component<ToolProps>
  1073. const state: Record<
  1074. string,
  1075. {
  1076. name: string
  1077. render?: ToolComponent
  1078. }
  1079. > = {}
  1080. export function registerTool(input: { name: string; render?: ToolComponent }) {
  1081. state[input.name] = input
  1082. return input
  1083. }
  1084. export function getTool(name: string) {
  1085. return state[name]?.render
  1086. }
  1087. export const ToolRegistry = {
  1088. register: registerTool,
  1089. render: getTool,
  1090. }
  1091. function ToolFileAccordion(props: { path: string; actions?: JSX.Element; children: JSX.Element }) {
  1092. const value = createMemo(() => props.path || "tool-file")
  1093. return (
  1094. <Accordion
  1095. multiple
  1096. data-scope="apply-patch"
  1097. style={{ "--sticky-accordion-offset": "40px" }}
  1098. defaultValue={[value()]}
  1099. >
  1100. <Accordion.Item value={value()}>
  1101. <StickyAccordionHeader>
  1102. <Accordion.Trigger>
  1103. <div data-slot="apply-patch-trigger-content">
  1104. <div data-slot="apply-patch-file-info">
  1105. <FileIcon node={{ path: props.path, type: "file" }} />
  1106. <div data-slot="apply-patch-file-name-container">
  1107. <Show when={props.path.includes("/")}>
  1108. <span data-slot="apply-patch-directory">{`\u202A${getDirectory(props.path)}\u202C`}</span>
  1109. </Show>
  1110. <span data-slot="apply-patch-filename">{getFilename(props.path)}</span>
  1111. </div>
  1112. </div>
  1113. <div data-slot="apply-patch-trigger-actions">
  1114. {props.actions}
  1115. <Icon name="chevron-grabber-vertical" size="small" />
  1116. </div>
  1117. </div>
  1118. </Accordion.Trigger>
  1119. </StickyAccordionHeader>
  1120. <Accordion.Content>{props.children}</Accordion.Content>
  1121. </Accordion.Item>
  1122. </Accordion>
  1123. )
  1124. }
  1125. PART_MAPPING["tool"] = function ToolPartDisplay(props) {
  1126. const i18n = useI18n()
  1127. const part = () => props.part as ToolPart
  1128. if (part().tool === "todowrite" || part().tool === "todoread") return null
  1129. const hideQuestion = createMemo(
  1130. () => part().tool === "question" && (part().state.status === "pending" || part().state.status === "running"),
  1131. )
  1132. const emptyInput: Record<string, any> = {}
  1133. const emptyMetadata: Record<string, any> = {}
  1134. const input = () => part().state?.input ?? emptyInput
  1135. // @ts-expect-error
  1136. const partMetadata = () => part().state?.metadata ?? emptyMetadata
  1137. const render = createMemo(() => ToolRegistry.render(part().tool) ?? GenericTool)
  1138. return (
  1139. <Show when={!hideQuestion()}>
  1140. <div data-component="tool-part-wrapper">
  1141. <Switch>
  1142. <Match when={part().state.status === "error" && (part().state as any).error}>
  1143. {(error) => {
  1144. const cleaned = error().replace("Error: ", "")
  1145. if (part().tool === "question" && cleaned.includes("dismissed this question")) {
  1146. return (
  1147. <div style="width: 100%; display: flex; justify-content: flex-end;">
  1148. <span class="text-13-regular text-text-weak cursor-default">
  1149. {i18n.t("ui.messagePart.questions.dismissed")}
  1150. </span>
  1151. </div>
  1152. )
  1153. }
  1154. return <ToolErrorCard tool={part().tool} error={error()} defaultOpen={props.defaultOpen} />
  1155. }}
  1156. </Match>
  1157. <Match when={true}>
  1158. <Dynamic
  1159. component={render()}
  1160. input={input()}
  1161. tool={part().tool}
  1162. metadata={partMetadata()}
  1163. // @ts-expect-error
  1164. output={part().state.output}
  1165. status={part().state.status}
  1166. hideDetails={props.hideDetails}
  1167. defaultOpen={props.defaultOpen}
  1168. />
  1169. </Match>
  1170. </Switch>
  1171. </div>
  1172. </Show>
  1173. )
  1174. }
  1175. PART_MAPPING["compaction"] = function CompactionPartDisplay() {
  1176. const i18n = useI18n()
  1177. return (
  1178. <div data-component="compaction-part">
  1179. <div data-slot="compaction-part-divider">
  1180. <span data-slot="compaction-part-line" />
  1181. <span data-slot="compaction-part-label" class="text-12-regular text-text-weak">
  1182. {i18n.t("ui.messagePart.compaction")}
  1183. </span>
  1184. <span data-slot="compaction-part-line" />
  1185. </div>
  1186. </div>
  1187. )
  1188. }
  1189. PART_MAPPING["text"] = function TextPartDisplay(props) {
  1190. const data = useData()
  1191. const i18n = useI18n()
  1192. const part = () => props.part as TextPart
  1193. const interrupted = createMemo(
  1194. () =>
  1195. props.message.role === "assistant" && (props.message as AssistantMessage).error?.name === "MessageAbortedError",
  1196. )
  1197. const model = createMemo(() => {
  1198. if (props.message.role !== "assistant") return ""
  1199. const message = props.message as AssistantMessage
  1200. const match = data.store.provider?.all?.find((p) => p.id === message.providerID)
  1201. return match?.models?.[message.modelID]?.name ?? message.modelID
  1202. })
  1203. const duration = createMemo(() => {
  1204. if (props.message.role !== "assistant") return ""
  1205. const message = props.message as AssistantMessage
  1206. const completed = message.time.completed
  1207. const ms =
  1208. typeof props.turnDurationMs === "number"
  1209. ? props.turnDurationMs
  1210. : typeof completed === "number"
  1211. ? completed - message.time.created
  1212. : -1
  1213. if (!(ms >= 0)) return ""
  1214. const total = Math.round(ms / 1000)
  1215. if (total < 60) return `${total}s`
  1216. const minutes = Math.floor(total / 60)
  1217. const seconds = total % 60
  1218. return `${minutes}m ${seconds}s`
  1219. })
  1220. const meta = createMemo(() => {
  1221. if (props.message.role !== "assistant") return ""
  1222. const agent = (props.message as AssistantMessage).agent
  1223. const items = [
  1224. agent ? agent[0]?.toUpperCase() + agent.slice(1) : "",
  1225. model(),
  1226. duration(),
  1227. interrupted() ? i18n.t("ui.message.interrupted") : "",
  1228. ]
  1229. return items.filter((x) => !!x).join(" \u00B7 ")
  1230. })
  1231. const displayText = () => (part().text ?? "").trim()
  1232. const throttledText = createThrottledValue(displayText)
  1233. const isLastTextPart = createMemo(() => {
  1234. const last = (data.store.part?.[props.message.id] ?? [])
  1235. .filter((item): item is TextPart => item?.type === "text" && !!item.text?.trim())
  1236. .at(-1)
  1237. return last?.id === part().id
  1238. })
  1239. const showCopy = createMemo(() => {
  1240. if (props.message.role !== "assistant") return isLastTextPart()
  1241. if (props.showAssistantCopyPartID === null) return false
  1242. if (typeof props.showAssistantCopyPartID === "string") return props.showAssistantCopyPartID === part().id
  1243. return isLastTextPart()
  1244. })
  1245. const [copied, setCopied] = createSignal(false)
  1246. const handleCopy = async () => {
  1247. const content = displayText()
  1248. if (!content) return
  1249. await navigator.clipboard.writeText(content)
  1250. setCopied(true)
  1251. setTimeout(() => setCopied(false), 2000)
  1252. }
  1253. return (
  1254. <Show when={throttledText()}>
  1255. <div data-component="text-part">
  1256. <div data-slot="text-part-body">
  1257. <Markdown text={throttledText()} cacheKey={part().id} />
  1258. </div>
  1259. <Show when={showCopy()}>
  1260. <div data-slot="text-part-copy-wrapper" data-interrupted={interrupted() ? "" : undefined}>
  1261. <Tooltip
  1262. value={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
  1263. placement="top"
  1264. gutter={4}
  1265. >
  1266. <IconButton
  1267. icon={copied() ? "check" : "copy"}
  1268. size="normal"
  1269. variant="ghost"
  1270. onMouseDown={(e) => e.preventDefault()}
  1271. onClick={handleCopy}
  1272. aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
  1273. />
  1274. </Tooltip>
  1275. <Show when={meta()}>
  1276. <span data-slot="text-part-meta" class="text-12-regular text-text-weak cursor-default">
  1277. {meta()}
  1278. </span>
  1279. </Show>
  1280. </div>
  1281. </Show>
  1282. </div>
  1283. </Show>
  1284. )
  1285. }
  1286. PART_MAPPING["reasoning"] = function ReasoningPartDisplay(props) {
  1287. const part = () => props.part as ReasoningPart
  1288. const text = () => part().text.trim()
  1289. const throttledText = createThrottledValue(text)
  1290. return (
  1291. <Show when={throttledText()}>
  1292. <div data-component="reasoning-part">
  1293. <Markdown text={throttledText()} cacheKey={part().id} />
  1294. </div>
  1295. </Show>
  1296. )
  1297. }
  1298. ToolRegistry.register({
  1299. name: "read",
  1300. render(props) {
  1301. const data = useData()
  1302. const i18n = useI18n()
  1303. const args: string[] = []
  1304. if (props.input.offset) args.push("offset=" + props.input.offset)
  1305. if (props.input.limit) args.push("limit=" + props.input.limit)
  1306. const loaded = createMemo(() => {
  1307. if (props.status !== "completed") return []
  1308. const value = props.metadata.loaded
  1309. if (!value || !Array.isArray(value)) return []
  1310. return value.filter((p): p is string => typeof p === "string")
  1311. })
  1312. return (
  1313. <>
  1314. <BasicTool
  1315. {...props}
  1316. icon="glasses"
  1317. trigger={{
  1318. title: i18n.t("ui.tool.read"),
  1319. subtitle: props.input.filePath ? getFilename(props.input.filePath) : "",
  1320. args,
  1321. }}
  1322. />
  1323. <For each={loaded()}>
  1324. {(filepath) => (
  1325. <div data-component="tool-loaded-file">
  1326. <Icon name="enter" size="small" />
  1327. <span>
  1328. {i18n.t("ui.tool.loaded")} {relativizeProjectPath(filepath, data.directory)}
  1329. </span>
  1330. </div>
  1331. )}
  1332. </For>
  1333. </>
  1334. )
  1335. },
  1336. })
  1337. ToolRegistry.register({
  1338. name: "list",
  1339. render(props) {
  1340. const i18n = useI18n()
  1341. return (
  1342. <BasicTool
  1343. {...props}
  1344. icon="bullet-list"
  1345. trigger={{ title: i18n.t("ui.tool.list"), subtitle: getDirectory(props.input.path || "/") }}
  1346. >
  1347. <Show when={props.output}>
  1348. <div data-component="tool-output" data-scrollable>
  1349. <Markdown text={props.output!} />
  1350. </div>
  1351. </Show>
  1352. </BasicTool>
  1353. )
  1354. },
  1355. })
  1356. ToolRegistry.register({
  1357. name: "glob",
  1358. render(props) {
  1359. const i18n = useI18n()
  1360. return (
  1361. <BasicTool
  1362. {...props}
  1363. icon="magnifying-glass-menu"
  1364. trigger={{
  1365. title: i18n.t("ui.tool.glob"),
  1366. subtitle: getDirectory(props.input.path || "/"),
  1367. args: props.input.pattern ? ["pattern=" + props.input.pattern] : [],
  1368. }}
  1369. >
  1370. <Show when={props.output}>
  1371. <div data-component="tool-output" data-scrollable>
  1372. <Markdown text={props.output!} />
  1373. </div>
  1374. </Show>
  1375. </BasicTool>
  1376. )
  1377. },
  1378. })
  1379. ToolRegistry.register({
  1380. name: "grep",
  1381. render(props) {
  1382. const i18n = useI18n()
  1383. const args: string[] = []
  1384. if (props.input.pattern) args.push("pattern=" + props.input.pattern)
  1385. if (props.input.include) args.push("include=" + props.input.include)
  1386. return (
  1387. <BasicTool
  1388. {...props}
  1389. icon="magnifying-glass-menu"
  1390. trigger={{
  1391. title: i18n.t("ui.tool.grep"),
  1392. subtitle: getDirectory(props.input.path || "/"),
  1393. args,
  1394. }}
  1395. >
  1396. <Show when={props.output}>
  1397. <div data-component="tool-output" data-scrollable>
  1398. <Markdown text={props.output!} />
  1399. </div>
  1400. </Show>
  1401. </BasicTool>
  1402. )
  1403. },
  1404. })
  1405. ToolRegistry.register({
  1406. name: "webfetch",
  1407. render(props) {
  1408. const i18n = useI18n()
  1409. const pending = createMemo(() => props.status === "pending" || props.status === "running")
  1410. const url = createMemo(() => {
  1411. const value = props.input.url
  1412. if (typeof value !== "string") return ""
  1413. return value
  1414. })
  1415. return (
  1416. <BasicTool
  1417. {...props}
  1418. hideDetails
  1419. icon="window-cursor"
  1420. trigger={
  1421. <div data-slot="basic-tool-tool-info-structured">
  1422. <div data-slot="basic-tool-tool-info-main">
  1423. <span data-slot="basic-tool-tool-title">
  1424. <TextShimmer text={i18n.t("ui.tool.webfetch")} active={pending()} />
  1425. </span>
  1426. <Show when={!pending() && url()}>
  1427. <a
  1428. data-slot="basic-tool-tool-subtitle"
  1429. class="clickable subagent-link"
  1430. href={url()}
  1431. target="_blank"
  1432. rel="noopener noreferrer"
  1433. onClick={(event) => event.stopPropagation()}
  1434. >
  1435. {url()}
  1436. </a>
  1437. </Show>
  1438. </div>
  1439. <Show when={!pending() && url()}>
  1440. <div data-component="tool-action">
  1441. <Icon name="square-arrow-top-right" size="small" />
  1442. </div>
  1443. </Show>
  1444. </div>
  1445. }
  1446. />
  1447. )
  1448. },
  1449. })
  1450. ToolRegistry.register({
  1451. name: "websearch",
  1452. render(props) {
  1453. const i18n = useI18n()
  1454. const query = createMemo(() => {
  1455. const value = props.input.query
  1456. if (typeof value !== "string") return ""
  1457. return value
  1458. })
  1459. return (
  1460. <BasicTool
  1461. {...props}
  1462. icon="window-cursor"
  1463. trigger={{
  1464. title: i18n.t("ui.tool.websearch"),
  1465. subtitle: query(),
  1466. subtitleClass: "exa-tool-query",
  1467. }}
  1468. >
  1469. <ExaOutput output={props.output} />
  1470. </BasicTool>
  1471. )
  1472. },
  1473. })
  1474. ToolRegistry.register({
  1475. name: "codesearch",
  1476. render(props) {
  1477. const i18n = useI18n()
  1478. const query = createMemo(() => {
  1479. const value = props.input.query
  1480. if (typeof value !== "string") return ""
  1481. return value
  1482. })
  1483. return (
  1484. <BasicTool
  1485. {...props}
  1486. icon="code"
  1487. trigger={{
  1488. title: i18n.t("ui.tool.codesearch"),
  1489. subtitle: query(),
  1490. subtitleClass: "exa-tool-query",
  1491. }}
  1492. >
  1493. <ExaOutput output={props.output} />
  1494. </BasicTool>
  1495. )
  1496. },
  1497. })
  1498. ToolRegistry.register({
  1499. name: "task",
  1500. render(props) {
  1501. const data = useData()
  1502. const i18n = useI18n()
  1503. const location = useLocation()
  1504. const childSessionId = () => props.metadata.sessionId as string | undefined
  1505. const type = createMemo(() => {
  1506. const raw = props.input.subagent_type
  1507. if (typeof raw !== "string" || !raw) return undefined
  1508. return raw[0]!.toUpperCase() + raw.slice(1)
  1509. })
  1510. const title = createMemo(() => agentTitle(i18n, type()))
  1511. const description = createMemo(() => {
  1512. const value = props.input.description
  1513. if (typeof value === "string") return value
  1514. return undefined
  1515. })
  1516. const running = createMemo(() => props.status === "pending" || props.status === "running")
  1517. const href = createMemo(() => {
  1518. const sessionId = childSessionId()
  1519. if (!sessionId) return
  1520. const direct = data.sessionHref?.(sessionId)
  1521. if (direct) return direct
  1522. const path = location.pathname
  1523. const idx = path.indexOf("/session")
  1524. if (idx === -1) return
  1525. return `${path.slice(0, idx)}/session/${sessionId}`
  1526. })
  1527. const titleContent = () => <TextShimmer text={title()} active={running()} />
  1528. const trigger = () => (
  1529. <div data-slot="basic-tool-tool-info-structured">
  1530. <div data-slot="basic-tool-tool-info-main">
  1531. <span data-slot="basic-tool-tool-title" class="capitalize agent-title">
  1532. {titleContent()}
  1533. </span>
  1534. <Show when={description()}>
  1535. <Switch>
  1536. <Match when={href()}>
  1537. <a
  1538. data-slot="basic-tool-tool-subtitle"
  1539. class="clickable subagent-link"
  1540. href={href()!}
  1541. onClick={(e) => e.stopPropagation()}
  1542. >
  1543. {description()}
  1544. </a>
  1545. </Match>
  1546. <Match when={true}>
  1547. <span data-slot="basic-tool-tool-subtitle">{description()}</span>
  1548. </Match>
  1549. </Switch>
  1550. </Show>
  1551. </div>
  1552. </div>
  1553. )
  1554. return <BasicTool icon="task" status={props.status} trigger={trigger()} hideDetails />
  1555. },
  1556. })
  1557. ToolRegistry.register({
  1558. name: "bash",
  1559. render(props) {
  1560. const i18n = useI18n()
  1561. const pending = () => props.status === "pending" || props.status === "running"
  1562. const sawPending = pending()
  1563. const text = createMemo(() => {
  1564. const cmd = props.input.command ?? props.metadata.command ?? ""
  1565. const out = stripAnsi(props.output || props.metadata.output || "")
  1566. return `$ ${cmd}${out ? "\n\n" + out : ""}`
  1567. })
  1568. const [copied, setCopied] = createSignal(false)
  1569. const handleCopy = async () => {
  1570. const content = text()
  1571. if (!content) return
  1572. await navigator.clipboard.writeText(content)
  1573. setCopied(true)
  1574. setTimeout(() => setCopied(false), 2000)
  1575. }
  1576. return (
  1577. <BasicTool
  1578. {...props}
  1579. icon="console"
  1580. trigger={
  1581. <div data-slot="basic-tool-tool-info-structured">
  1582. <div data-slot="basic-tool-tool-info-main">
  1583. <span data-slot="basic-tool-tool-title">
  1584. <TextShimmer text={i18n.t("ui.tool.shell")} active={pending()} />
  1585. </span>
  1586. <Show when={!pending() && props.input.description}>
  1587. <ShellSubmessage text={props.input.description} animate={sawPending} />
  1588. </Show>
  1589. </div>
  1590. </div>
  1591. }
  1592. >
  1593. <div data-component="bash-output">
  1594. <div data-slot="bash-copy">
  1595. <Tooltip
  1596. value={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
  1597. placement="top"
  1598. gutter={4}
  1599. >
  1600. <IconButton
  1601. icon={copied() ? "check" : "copy"}
  1602. size="small"
  1603. variant="secondary"
  1604. onMouseDown={(e) => e.preventDefault()}
  1605. onClick={handleCopy}
  1606. aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
  1607. />
  1608. </Tooltip>
  1609. </div>
  1610. <div data-slot="bash-scroll" data-scrollable>
  1611. <pre data-slot="bash-pre">
  1612. <code>{text()}</code>
  1613. </pre>
  1614. </div>
  1615. </div>
  1616. </BasicTool>
  1617. )
  1618. },
  1619. })
  1620. ToolRegistry.register({
  1621. name: "edit",
  1622. render(props) {
  1623. const i18n = useI18n()
  1624. const fileComponent = useFileComponent()
  1625. const diagnostics = createMemo(() => getDiagnostics(props.metadata.diagnostics, props.input.filePath))
  1626. const path = createMemo(() => props.metadata?.filediff?.file || props.input.filePath || "")
  1627. const filename = () => getFilename(props.input.filePath ?? "")
  1628. const pending = () => props.status === "pending" || props.status === "running"
  1629. return (
  1630. <div data-component="edit-tool">
  1631. <BasicTool
  1632. {...props}
  1633. icon="code-lines"
  1634. defer
  1635. trigger={
  1636. <div data-component="edit-trigger">
  1637. <div data-slot="message-part-title-area">
  1638. <div data-slot="message-part-title">
  1639. <span data-slot="message-part-title-text">
  1640. <TextShimmer text={i18n.t("ui.messagePart.title.edit")} active={pending()} />
  1641. </span>
  1642. <Show when={!pending()}>
  1643. <span data-slot="message-part-title-filename">{filename()}</span>
  1644. </Show>
  1645. </div>
  1646. <Show when={!pending() && props.input.filePath?.includes("/")}>
  1647. <div data-slot="message-part-path">
  1648. <span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
  1649. </div>
  1650. </Show>
  1651. </div>
  1652. <div data-slot="message-part-actions">
  1653. <Show when={!pending() && props.metadata.filediff}>
  1654. <DiffChanges changes={props.metadata.filediff} />
  1655. </Show>
  1656. </div>
  1657. </div>
  1658. }
  1659. >
  1660. <Show when={path()}>
  1661. <ToolFileAccordion
  1662. path={path()}
  1663. actions={
  1664. <Show when={!pending() && props.metadata.filediff}>
  1665. <DiffChanges changes={props.metadata.filediff!} />
  1666. </Show>
  1667. }
  1668. >
  1669. <div data-component="edit-content">
  1670. <Dynamic
  1671. component={fileComponent}
  1672. mode="diff"
  1673. before={{
  1674. name: props.metadata?.filediff?.file || props.input.filePath,
  1675. contents: props.metadata?.filediff?.before || props.input.oldString,
  1676. }}
  1677. after={{
  1678. name: props.metadata?.filediff?.file || props.input.filePath,
  1679. contents: props.metadata?.filediff?.after || props.input.newString,
  1680. }}
  1681. />
  1682. </div>
  1683. </ToolFileAccordion>
  1684. </Show>
  1685. <DiagnosticsDisplay diagnostics={diagnostics()} />
  1686. </BasicTool>
  1687. </div>
  1688. )
  1689. },
  1690. })
  1691. ToolRegistry.register({
  1692. name: "write",
  1693. render(props) {
  1694. const i18n = useI18n()
  1695. const fileComponent = useFileComponent()
  1696. const diagnostics = createMemo(() => getDiagnostics(props.metadata.diagnostics, props.input.filePath))
  1697. const path = createMemo(() => props.input.filePath || "")
  1698. const filename = () => getFilename(props.input.filePath ?? "")
  1699. const pending = () => props.status === "pending" || props.status === "running"
  1700. return (
  1701. <div data-component="write-tool">
  1702. <BasicTool
  1703. {...props}
  1704. icon="code-lines"
  1705. defer
  1706. trigger={
  1707. <div data-component="write-trigger">
  1708. <div data-slot="message-part-title-area">
  1709. <div data-slot="message-part-title">
  1710. <span data-slot="message-part-title-text">
  1711. <TextShimmer text={i18n.t("ui.messagePart.title.write")} active={pending()} />
  1712. </span>
  1713. <Show when={!pending()}>
  1714. <span data-slot="message-part-title-filename">{filename()}</span>
  1715. </Show>
  1716. </div>
  1717. <Show when={!pending() && props.input.filePath?.includes("/")}>
  1718. <div data-slot="message-part-path">
  1719. <span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
  1720. </div>
  1721. </Show>
  1722. </div>
  1723. <div data-slot="message-part-actions">{/* <DiffChanges diff={diff} /> */}</div>
  1724. </div>
  1725. }
  1726. >
  1727. <Show when={props.input.content && path()}>
  1728. <ToolFileAccordion path={path()}>
  1729. <div data-component="write-content">
  1730. <Dynamic
  1731. component={fileComponent}
  1732. mode="text"
  1733. file={{
  1734. name: props.input.filePath,
  1735. contents: props.input.content,
  1736. cacheKey: checksum(props.input.content),
  1737. }}
  1738. overflow="scroll"
  1739. />
  1740. </div>
  1741. </ToolFileAccordion>
  1742. </Show>
  1743. <DiagnosticsDisplay diagnostics={diagnostics()} />
  1744. </BasicTool>
  1745. </div>
  1746. )
  1747. },
  1748. })
  1749. interface ApplyPatchFile {
  1750. filePath: string
  1751. relativePath: string
  1752. type: "add" | "update" | "delete" | "move"
  1753. diff: string
  1754. before: string
  1755. after: string
  1756. additions: number
  1757. deletions: number
  1758. movePath?: string
  1759. }
  1760. ToolRegistry.register({
  1761. name: "apply_patch",
  1762. render(props) {
  1763. const i18n = useI18n()
  1764. const fileComponent = useFileComponent()
  1765. const files = createMemo(() => (props.metadata.files ?? []) as ApplyPatchFile[])
  1766. const pending = createMemo(() => props.status === "pending" || props.status === "running")
  1767. const single = createMemo(() => {
  1768. const list = files()
  1769. if (list.length !== 1) return
  1770. return list[0]
  1771. })
  1772. const [expanded, setExpanded] = createSignal<string[]>([])
  1773. let seeded = false
  1774. createEffect(() => {
  1775. const list = files()
  1776. if (list.length === 0) return
  1777. if (seeded) return
  1778. seeded = true
  1779. setExpanded(list.filter((f) => f.type !== "delete").map((f) => f.filePath))
  1780. })
  1781. const subtitle = createMemo(() => {
  1782. const count = files().length
  1783. if (count === 0) return ""
  1784. return `${count} ${i18n.t(count > 1 ? "ui.common.file.other" : "ui.common.file.one")}`
  1785. })
  1786. return (
  1787. <Show
  1788. when={single()}
  1789. fallback={
  1790. <div data-component="apply-patch-tool">
  1791. <BasicTool
  1792. {...props}
  1793. icon="code-lines"
  1794. defer
  1795. trigger={{
  1796. title: i18n.t("ui.tool.patch"),
  1797. subtitle: subtitle(),
  1798. }}
  1799. >
  1800. <Show when={files().length > 0}>
  1801. <Accordion
  1802. multiple
  1803. data-scope="apply-patch"
  1804. style={{ "--sticky-accordion-offset": "40px" }}
  1805. value={expanded()}
  1806. onChange={(value) => setExpanded(Array.isArray(value) ? value : value ? [value] : [])}
  1807. >
  1808. <For each={files()}>
  1809. {(file) => {
  1810. const active = createMemo(() => expanded().includes(file.filePath))
  1811. const [visible, setVisible] = createSignal(false)
  1812. createEffect(() => {
  1813. if (!active()) {
  1814. setVisible(false)
  1815. return
  1816. }
  1817. requestAnimationFrame(() => {
  1818. if (!active()) return
  1819. setVisible(true)
  1820. })
  1821. })
  1822. return (
  1823. <Accordion.Item value={file.filePath} data-type={file.type}>
  1824. <StickyAccordionHeader>
  1825. <Accordion.Trigger>
  1826. <div data-slot="apply-patch-trigger-content">
  1827. <div data-slot="apply-patch-file-info">
  1828. <FileIcon node={{ path: file.relativePath, type: "file" }} />
  1829. <div data-slot="apply-patch-file-name-container">
  1830. <Show when={file.relativePath.includes("/")}>
  1831. <span data-slot="apply-patch-directory">{`\u202A${getDirectory(file.relativePath)}\u202C`}</span>
  1832. </Show>
  1833. <span data-slot="apply-patch-filename">{getFilename(file.relativePath)}</span>
  1834. </div>
  1835. </div>
  1836. <div data-slot="apply-patch-trigger-actions">
  1837. <Switch>
  1838. <Match when={file.type === "add"}>
  1839. <span data-slot="apply-patch-change" data-type="added">
  1840. {i18n.t("ui.patch.action.created")}
  1841. </span>
  1842. </Match>
  1843. <Match when={file.type === "delete"}>
  1844. <span data-slot="apply-patch-change" data-type="removed">
  1845. {i18n.t("ui.patch.action.deleted")}
  1846. </span>
  1847. </Match>
  1848. <Match when={file.type === "move"}>
  1849. <span data-slot="apply-patch-change" data-type="modified">
  1850. {i18n.t("ui.patch.action.moved")}
  1851. </span>
  1852. </Match>
  1853. <Match when={true}>
  1854. <DiffChanges changes={{ additions: file.additions, deletions: file.deletions }} />
  1855. </Match>
  1856. </Switch>
  1857. <Icon name="chevron-grabber-vertical" size="small" />
  1858. </div>
  1859. </div>
  1860. </Accordion.Trigger>
  1861. </StickyAccordionHeader>
  1862. <Accordion.Content>
  1863. <Show when={visible()}>
  1864. <div data-component="apply-patch-file-diff">
  1865. <Dynamic
  1866. component={fileComponent}
  1867. mode="diff"
  1868. before={{ name: file.filePath, contents: file.before }}
  1869. after={{ name: file.movePath ?? file.filePath, contents: file.after }}
  1870. />
  1871. </div>
  1872. </Show>
  1873. </Accordion.Content>
  1874. </Accordion.Item>
  1875. )
  1876. }}
  1877. </For>
  1878. </Accordion>
  1879. </Show>
  1880. </BasicTool>
  1881. </div>
  1882. }
  1883. >
  1884. <div data-component="apply-patch-tool">
  1885. <BasicTool
  1886. {...props}
  1887. icon="code-lines"
  1888. defer
  1889. trigger={
  1890. <div data-component="edit-trigger">
  1891. <div data-slot="message-part-title-area">
  1892. <div data-slot="message-part-title">
  1893. <span data-slot="message-part-title-text">
  1894. <TextShimmer text={i18n.t("ui.tool.patch")} active={pending()} />
  1895. </span>
  1896. <Show when={!pending()}>
  1897. <span data-slot="message-part-title-filename">{getFilename(single()!.relativePath)}</span>
  1898. </Show>
  1899. </div>
  1900. <Show when={!pending() && single()!.relativePath.includes("/")}>
  1901. <div data-slot="message-part-path">
  1902. <span data-slot="message-part-directory">{getDirectory(single()!.relativePath)}</span>
  1903. </div>
  1904. </Show>
  1905. </div>
  1906. <div data-slot="message-part-actions">
  1907. <Show when={!pending()}>
  1908. <DiffChanges changes={{ additions: single()!.additions, deletions: single()!.deletions }} />
  1909. </Show>
  1910. </div>
  1911. </div>
  1912. }
  1913. >
  1914. <ToolFileAccordion
  1915. path={single()!.relativePath}
  1916. actions={
  1917. <Switch>
  1918. <Match when={single()!.type === "add"}>
  1919. <span data-slot="apply-patch-change" data-type="added">
  1920. {i18n.t("ui.patch.action.created")}
  1921. </span>
  1922. </Match>
  1923. <Match when={single()!.type === "delete"}>
  1924. <span data-slot="apply-patch-change" data-type="removed">
  1925. {i18n.t("ui.patch.action.deleted")}
  1926. </span>
  1927. </Match>
  1928. <Match when={single()!.type === "move"}>
  1929. <span data-slot="apply-patch-change" data-type="modified">
  1930. {i18n.t("ui.patch.action.moved")}
  1931. </span>
  1932. </Match>
  1933. <Match when={true}>
  1934. <DiffChanges changes={{ additions: single()!.additions, deletions: single()!.deletions }} />
  1935. </Match>
  1936. </Switch>
  1937. }
  1938. >
  1939. <div data-component="apply-patch-file-diff">
  1940. <Dynamic
  1941. component={fileComponent}
  1942. mode="diff"
  1943. before={{ name: single()!.filePath, contents: single()!.before }}
  1944. after={{ name: single()!.movePath ?? single()!.filePath, contents: single()!.after }}
  1945. />
  1946. </div>
  1947. </ToolFileAccordion>
  1948. </BasicTool>
  1949. </div>
  1950. </Show>
  1951. )
  1952. },
  1953. })
  1954. ToolRegistry.register({
  1955. name: "todowrite",
  1956. render(props) {
  1957. const i18n = useI18n()
  1958. const todos = createMemo(() => {
  1959. const meta = props.metadata?.todos
  1960. if (Array.isArray(meta)) return meta
  1961. const input = props.input.todos
  1962. if (Array.isArray(input)) return input
  1963. return []
  1964. })
  1965. const subtitle = createMemo(() => {
  1966. const list = todos()
  1967. if (list.length === 0) return ""
  1968. return `${list.filter((t: Todo) => t.status === "completed").length}/${list.length}`
  1969. })
  1970. return (
  1971. <BasicTool
  1972. {...props}
  1973. defaultOpen
  1974. icon="checklist"
  1975. trigger={{
  1976. title: i18n.t("ui.tool.todos"),
  1977. subtitle: subtitle(),
  1978. }}
  1979. >
  1980. <Show when={todos().length}>
  1981. <div data-component="todos">
  1982. <For each={todos()}>
  1983. {(todo: Todo) => (
  1984. <Checkbox readOnly checked={todo.status === "completed"}>
  1985. <span
  1986. data-slot="message-part-todo-content"
  1987. data-completed={todo.status === "completed" ? "completed" : undefined}
  1988. >
  1989. {todo.content}
  1990. </span>
  1991. </Checkbox>
  1992. )}
  1993. </For>
  1994. </div>
  1995. </Show>
  1996. </BasicTool>
  1997. )
  1998. },
  1999. })
  2000. ToolRegistry.register({
  2001. name: "question",
  2002. render(props) {
  2003. const i18n = useI18n()
  2004. const questions = createMemo(() => (props.input.questions ?? []) as QuestionInfo[])
  2005. const answers = createMemo(() => (props.metadata.answers ?? []) as QuestionAnswer[])
  2006. const completed = createMemo(() => answers().length > 0)
  2007. const subtitle = createMemo(() => {
  2008. const count = questions().length
  2009. if (count === 0) return ""
  2010. if (completed()) return i18n.t("ui.question.subtitle.answered", { count })
  2011. return `${count} ${i18n.t(count > 1 ? "ui.common.question.other" : "ui.common.question.one")}`
  2012. })
  2013. return (
  2014. <BasicTool
  2015. {...props}
  2016. defaultOpen={completed()}
  2017. icon="bubble-5"
  2018. trigger={{
  2019. title: i18n.t("ui.tool.questions"),
  2020. subtitle: subtitle(),
  2021. }}
  2022. >
  2023. <Show when={completed()}>
  2024. <div data-component="question-answers">
  2025. <For each={questions()}>
  2026. {(q, i) => {
  2027. const answer = () => answers()[i()] ?? []
  2028. return (
  2029. <div data-slot="question-answer-item">
  2030. <div data-slot="question-text">{q.question}</div>
  2031. <div data-slot="answer-text">{answer().join(", ") || i18n.t("ui.question.answer.none")}</div>
  2032. </div>
  2033. )
  2034. }}
  2035. </For>
  2036. </div>
  2037. </Show>
  2038. </BasicTool>
  2039. )
  2040. },
  2041. })
  2042. ToolRegistry.register({
  2043. name: "skill",
  2044. render(props) {
  2045. const title = createMemo(() => props.input.name || "skill")
  2046. const running = createMemo(() => props.status === "pending" || props.status === "running")
  2047. const titleContent = () => <TextShimmer text={title()} active={running()} />
  2048. const trigger = () => (
  2049. <div data-slot="basic-tool-tool-info-structured">
  2050. <div data-slot="basic-tool-tool-info-main">
  2051. <span data-slot="basic-tool-tool-title" class="capitalize agent-title">
  2052. {titleContent()}
  2053. </span>
  2054. </div>
  2055. </div>
  2056. )
  2057. return <BasicTool icon="brain" status={props.status} trigger={trigger()} hideDetails />
  2058. },
  2059. })