Share.tsx 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082
  1. import { type JSX } from "solid-js"
  2. import {
  3. For,
  4. Show,
  5. Match,
  6. Switch,
  7. onMount,
  8. Suspense,
  9. onCleanup,
  10. splitProps,
  11. createMemo,
  12. createEffect,
  13. createSignal,
  14. SuspenseList,
  15. } from "solid-js"
  16. import map from "lang-map"
  17. import { DateTime } from "luxon"
  18. import { createStore, reconcile } from "solid-js/store"
  19. import type { Diagnostic } from "vscode-languageserver-types"
  20. import {
  21. IconOpenAI,
  22. IconGemini,
  23. IconOpencode,
  24. IconAnthropic,
  25. } from "./icons/custom"
  26. import {
  27. IconHashtag,
  28. IconSparkles,
  29. IconGlobeAlt,
  30. IconDocument,
  31. IconQueueList,
  32. IconUserCircle,
  33. IconCheckCircle,
  34. IconChevronDown,
  35. IconCommandLine,
  36. IconChevronRight,
  37. IconDocumentPlus,
  38. IconPencilSquare,
  39. IconRectangleStack,
  40. IconMagnifyingGlass,
  41. IconWrenchScrewdriver,
  42. IconDocumentMagnifyingGlass,
  43. IconArrowDown,
  44. } from "./icons"
  45. import DiffView from "./DiffView"
  46. import CodeBlock from "./CodeBlock"
  47. import MarkdownView from "./MarkdownView"
  48. import styles from "./share.module.css"
  49. import type { Message } from "opencode/session/message"
  50. import type { Session } from "opencode/session/index"
  51. const MIN_DURATION = 2
  52. type Status =
  53. | "disconnected"
  54. | "connecting"
  55. | "connected"
  56. | "error"
  57. | "reconnecting"
  58. type TodoStatus = "pending" | "in_progress" | "completed"
  59. interface Todo {
  60. id: string
  61. content: string
  62. status: TodoStatus
  63. priority: "low" | "medium" | "high"
  64. }
  65. function sortTodosByStatus(todos: Todo[]) {
  66. const statusPriority: Record<TodoStatus, number> = {
  67. in_progress: 0,
  68. pending: 1,
  69. completed: 2,
  70. }
  71. return todos
  72. .slice()
  73. .sort((a, b) => statusPriority[a.status] - statusPriority[b.status])
  74. }
  75. function scrollToAnchor(id: string) {
  76. const el = document.getElementById(id)
  77. if (!el) return
  78. el.scrollIntoView({ behavior: "smooth" })
  79. }
  80. function stripWorkingDirectory(filePath?: string, workingDir?: string) {
  81. if (filePath === undefined || workingDir === undefined) return filePath
  82. const prefix = workingDir.endsWith("/") ? workingDir : workingDir + "/"
  83. if (filePath === workingDir) {
  84. return ""
  85. }
  86. if (filePath.startsWith(prefix)) {
  87. return filePath.slice(prefix.length)
  88. }
  89. return filePath
  90. }
  91. function getShikiLang(filename: string) {
  92. const ext = filename.split(".").pop()?.toLowerCase() ?? ""
  93. // map.languages(ext) returns an array of matching Linguist language names (e.g. ['TypeScript'])
  94. const langs = map.languages(ext)
  95. const type = langs?.[0]?.toLowerCase()
  96. // Overrride any specific language mappings
  97. const overrides: Record<string, string> = {
  98. conf: "shellscript",
  99. }
  100. return type ? (overrides[type] ?? type) : "plaintext"
  101. }
  102. function formatDuration(ms: number): string {
  103. const ONE_SECOND = 1000
  104. const ONE_MINUTE = 60 * ONE_SECOND
  105. if (ms >= ONE_MINUTE) {
  106. const minutes = Math.floor(ms / ONE_MINUTE)
  107. return minutes === 1 ? `1min` : `${minutes}mins`
  108. }
  109. if (ms >= ONE_SECOND) {
  110. const seconds = Math.floor(ms / ONE_SECOND)
  111. return `${seconds}s`
  112. }
  113. return `${ms}ms`
  114. }
  115. // Converts nested objects/arrays into [path, value] pairs.
  116. // E.g. {a:{b:{c:1}}, d:[{e:2}, 3]} => [["a.b.c",1], ["d[0].e",2], ["d[1]",3]]
  117. function flattenToolArgs(obj: any, prefix: string = ""): Array<[string, any]> {
  118. const entries: Array<[string, any]> = []
  119. for (const [key, value] of Object.entries(obj)) {
  120. const path = prefix ? `${prefix}.${key}` : key
  121. if (value !== null && typeof value === "object") {
  122. if (Array.isArray(value)) {
  123. value.forEach((item, index) => {
  124. const arrayPath = `${path}[${index}]`
  125. if (item !== null && typeof item === "object") {
  126. entries.push(...flattenToolArgs(item, arrayPath))
  127. } else {
  128. entries.push([arrayPath, item])
  129. }
  130. })
  131. } else {
  132. entries.push(...flattenToolArgs(value, path))
  133. }
  134. } else {
  135. entries.push([path, value])
  136. }
  137. }
  138. return entries
  139. }
  140. function formatErrorString(error: string): JSX.Element {
  141. const errorMarker = "Error: "
  142. const startsWithError = error.startsWith(errorMarker)
  143. return startsWithError ? (
  144. <pre>
  145. <span data-color="red" data-marker="label" data-separator>
  146. Error
  147. </span>
  148. <span>{error.slice(errorMarker.length)}</span>
  149. </pre>
  150. ) : (
  151. <pre>
  152. <span data-color="dimmed">{error}</span>
  153. </pre>
  154. )
  155. }
  156. function getDiagnostics(
  157. diagnosticsByFile: Record<string, Diagnostic[]>,
  158. currentFile: string,
  159. ): JSX.Element[] {
  160. // Return a flat array of error diagnostics, in the format:
  161. // "Error [65:20] Property 'x' does not exist on type 'Y'"
  162. const result: JSX.Element[] = []
  163. if (
  164. diagnosticsByFile === undefined ||
  165. diagnosticsByFile[currentFile] === undefined
  166. )
  167. return result
  168. for (const diags of Object.values(diagnosticsByFile)) {
  169. for (const d of diags) {
  170. // Only keep diagnostics explicitly marked as Error (severity === 1)
  171. if (d.severity !== 1) continue
  172. const line = d.range.start.line + 1 // 1-based
  173. const column = d.range.start.character + 1 // 1-based
  174. result.push(
  175. <pre>
  176. <span data-color="red" data-marker="label">
  177. Error
  178. </span>
  179. <span data-color="dimmed" data-separator>
  180. [{line}:{column}]
  181. </span>
  182. <span>{d.message}</span>
  183. </pre>,
  184. )
  185. }
  186. }
  187. return result
  188. }
  189. function stripEnclosingTag(text: string): string {
  190. const wrappedRe = /^\s*<([A-Za-z]\w*)>\s*([\s\S]*?)\s*<\/\1>\s*$/
  191. const match = text.match(wrappedRe)
  192. return match ? match[2] : text
  193. }
  194. function getStatusText(status: [Status, string?]): string {
  195. switch (status[0]) {
  196. case "connected":
  197. return "Connected, waiting for messages..."
  198. case "connecting":
  199. return "Connecting..."
  200. case "disconnected":
  201. return "Disconnected"
  202. case "reconnecting":
  203. return "Reconnecting..."
  204. case "error":
  205. return status[1] || "Error"
  206. default:
  207. return "Unknown"
  208. }
  209. }
  210. function ProviderIcon(props: { provider: string; size?: number }) {
  211. const size = props.size || 16
  212. return (
  213. <Switch fallback={<IconSparkles width={size} height={size} />}>
  214. <Match when={props.provider === "openai"}>
  215. <IconOpenAI width={size} height={size} />
  216. </Match>
  217. <Match when={props.provider === "anthropic"}>
  218. <IconAnthropic width={size} height={size} />
  219. </Match>
  220. <Match when={props.provider === "gemini"}>
  221. <IconGemini width={size} height={size} />
  222. </Match>
  223. </Switch>
  224. )
  225. }
  226. interface ResultsButtonProps extends JSX.HTMLAttributes<HTMLButtonElement> {
  227. showCopy?: string
  228. hideCopy?: string
  229. results: boolean
  230. }
  231. function ResultsButton(props: ResultsButtonProps) {
  232. const [local, rest] = splitProps(props, ["results", "showCopy", "hideCopy"])
  233. return (
  234. <button
  235. type="button"
  236. data-element-button-text
  237. data-element-button-more
  238. {...rest}
  239. >
  240. <span>
  241. {local.results
  242. ? local.hideCopy || "Hide results"
  243. : local.showCopy || "Show results"}
  244. </span>
  245. <span data-button-icon>
  246. <Show
  247. when={local.results}
  248. fallback={<IconChevronRight width={11} height={11} />}
  249. >
  250. <IconChevronDown width={11} height={11} />
  251. </Show>
  252. </span>
  253. </button>
  254. )
  255. }
  256. interface TextPartProps extends JSX.HTMLAttributes<HTMLDivElement> {
  257. text: string
  258. expand?: boolean
  259. invert?: boolean
  260. highlight?: boolean
  261. }
  262. function TextPart(props: TextPartProps) {
  263. const [local, rest] = splitProps(props, [
  264. "text",
  265. "expand",
  266. "invert",
  267. "highlight",
  268. ])
  269. const [expanded, setExpanded] = createSignal(false)
  270. const [overflowed, setOverflowed] = createSignal(false)
  271. let preEl: HTMLPreElement | undefined
  272. function checkOverflow() {
  273. if (preEl && !local.expand) {
  274. setOverflowed(preEl.scrollHeight > preEl.clientHeight + 1)
  275. }
  276. }
  277. onMount(() => {
  278. checkOverflow()
  279. window.addEventListener("resize", checkOverflow)
  280. })
  281. createEffect(() => {
  282. local.text
  283. local.expand
  284. setTimeout(checkOverflow, 0)
  285. })
  286. onCleanup(() => {
  287. window.removeEventListener("resize", checkOverflow)
  288. })
  289. return (
  290. <div
  291. class={styles["message-text"]}
  292. data-invert={local.invert}
  293. data-highlight={local.highlight}
  294. data-expanded={expanded() || local.expand === true}
  295. {...rest}
  296. >
  297. <pre ref={(el) => (preEl = el)}>{local.text}</pre>
  298. {((!local.expand && overflowed()) || expanded()) && (
  299. <button
  300. type="button"
  301. data-element-button-text
  302. onClick={() => setExpanded((e) => !e)}
  303. >
  304. {expanded() ? "Show less" : "Show more"}
  305. </button>
  306. )}
  307. </div>
  308. )
  309. }
  310. interface ErrorPartProps extends JSX.HTMLAttributes<HTMLDivElement> {
  311. expand?: boolean
  312. }
  313. function ErrorPart(props: ErrorPartProps) {
  314. const [local, rest] = splitProps(props, ["expand", "children"])
  315. const [expanded, setExpanded] = createSignal(false)
  316. const [overflowed, setOverflowed] = createSignal(false)
  317. let preEl: HTMLElement | undefined
  318. function checkOverflow() {
  319. if (preEl && !local.expand) {
  320. setOverflowed(preEl.scrollHeight > preEl.clientHeight + 1)
  321. }
  322. }
  323. onMount(() => {
  324. checkOverflow()
  325. window.addEventListener("resize", checkOverflow)
  326. })
  327. createEffect(() => {
  328. local.children
  329. local.expand
  330. setTimeout(checkOverflow, 0)
  331. })
  332. onCleanup(() => {
  333. window.removeEventListener("resize", checkOverflow)
  334. })
  335. return (
  336. <div
  337. class={styles["message-error"]}
  338. data-expanded={expanded() || local.expand === true}
  339. {...rest}
  340. >
  341. <div data-section="content" ref={(el) => (preEl = el)}>
  342. {local.children}
  343. </div>
  344. {((!local.expand && overflowed()) || expanded()) && (
  345. <button
  346. type="button"
  347. data-element-button-text
  348. onClick={() => setExpanded((e) => !e)}
  349. >
  350. {expanded() ? "Show less" : "Show more"}
  351. </button>
  352. )}
  353. </div>
  354. )
  355. }
  356. interface MarkdownPartProps extends JSX.HTMLAttributes<HTMLDivElement> {
  357. text: string
  358. expand?: boolean
  359. highlight?: boolean
  360. }
  361. function MarkdownPart(props: MarkdownPartProps) {
  362. const [local, rest] = splitProps(props, ["text", "expand", "highlight"])
  363. const [expanded, setExpanded] = createSignal(false)
  364. const [overflowed, setOverflowed] = createSignal(false)
  365. let divEl: HTMLDivElement | undefined
  366. function checkOverflow() {
  367. if (divEl && !local.expand) {
  368. setOverflowed(divEl.scrollHeight > divEl.clientHeight + 1)
  369. }
  370. }
  371. onMount(() => {
  372. checkOverflow()
  373. window.addEventListener("resize", checkOverflow)
  374. })
  375. createEffect(() => {
  376. local.text
  377. local.expand
  378. setTimeout(checkOverflow, 0)
  379. })
  380. onCleanup(() => {
  381. window.removeEventListener("resize", checkOverflow)
  382. })
  383. return (
  384. <div
  385. class={styles["message-markdown"]}
  386. data-highlight={local.highlight}
  387. data-expanded={expanded() || local.expand === true}
  388. {...rest}
  389. >
  390. <MarkdownView
  391. data-element-markdown
  392. markdown={local.text}
  393. ref={(el) => (divEl = el)}
  394. />
  395. {((!local.expand && overflowed()) || expanded()) && (
  396. <button
  397. type="button"
  398. data-element-button-text
  399. onClick={() => setExpanded((e) => !e)}
  400. >
  401. {expanded() ? "Show less" : "Show more"}
  402. </button>
  403. )}
  404. </div>
  405. )
  406. }
  407. interface TerminalPartProps extends JSX.HTMLAttributes<HTMLDivElement> {
  408. command: string
  409. error?: string
  410. result?: string
  411. desc?: string
  412. expand?: boolean
  413. }
  414. function TerminalPart(props: TerminalPartProps) {
  415. const [local, rest] = splitProps(props, [
  416. "command",
  417. "error",
  418. "result",
  419. "desc",
  420. "expand",
  421. ])
  422. const [expanded, setExpanded] = createSignal(false)
  423. const [overflowed, setOverflowed] = createSignal(false)
  424. let preEl: HTMLElement | undefined
  425. function checkOverflow() {
  426. if (!preEl) return
  427. const code = preEl.getElementsByTagName("code")[0]
  428. if (code && !local.expand) {
  429. setOverflowed(preEl.clientHeight < code.offsetHeight)
  430. }
  431. }
  432. createEffect(() => {
  433. local.command
  434. local.result
  435. local.error
  436. local.expand
  437. setTimeout(checkOverflow, 0)
  438. })
  439. onMount(() => {
  440. checkOverflow()
  441. window.addEventListener("resize", checkOverflow)
  442. })
  443. onCleanup(() => {
  444. window.removeEventListener("resize", checkOverflow)
  445. })
  446. return (
  447. <div
  448. class={styles["message-terminal"]}
  449. data-expanded={expanded() || local.expand === true}
  450. {...rest}
  451. >
  452. <div data-section="body">
  453. <div data-section="header">
  454. <span>{local.desc}</span>
  455. </div>
  456. <div data-section="content">
  457. <CodeBlock lang="bash" code={local.command} />
  458. <Switch>
  459. <Match when={local.error}>
  460. <CodeBlock
  461. data-section="error"
  462. lang="text"
  463. ref={(el) => (preEl = el)}
  464. code={local.error || ""}
  465. />
  466. </Match>
  467. <Match when={local.result}>
  468. <CodeBlock
  469. lang="console"
  470. ref={(el) => (preEl = el)}
  471. code={local.result || ""}
  472. />
  473. </Match>
  474. </Switch>
  475. </div>
  476. </div>
  477. {((!local.expand && overflowed()) || expanded()) && (
  478. <button
  479. type="button"
  480. data-element-button-text
  481. onClick={() => setExpanded((e) => !e)}
  482. >
  483. {expanded() ? "Show less" : "Show more"}
  484. </button>
  485. )}
  486. </div>
  487. )
  488. }
  489. function ToolFooter(props: { time: number }) {
  490. return props.time > MIN_DURATION ? (
  491. <span data-part-footer title={`${props.time}ms`}>
  492. {formatDuration(props.time)}
  493. </span>
  494. ) : (
  495. <div data-part-footer="spacer"></div>
  496. )
  497. }
  498. interface AnchorProps extends JSX.HTMLAttributes<HTMLDivElement> {
  499. id: string
  500. }
  501. function AnchorIcon(props: AnchorProps) {
  502. const [local, rest] = splitProps(props, ["id", "children"])
  503. const [copied, setCopied] = createSignal(false)
  504. return (
  505. <div
  506. {...rest}
  507. data-element-anchor
  508. title="Link to this message"
  509. data-status={copied() ? "copied" : ""}
  510. >
  511. <a
  512. href={`#${local.id}`}
  513. onClick={(e) => {
  514. e.preventDefault()
  515. const anchor = e.currentTarget
  516. const hash = anchor.getAttribute("href") || ""
  517. const { origin, pathname, search } = window.location
  518. navigator.clipboard
  519. .writeText(`${origin}${pathname}${search}${hash}`)
  520. .catch((err) => console.error("Copy failed", err))
  521. setCopied(true)
  522. setTimeout(() => setCopied(false), 3000)
  523. }}
  524. >
  525. {local.children}
  526. <IconHashtag width={18} height={18} />
  527. <IconCheckCircle width={18} height={18} />
  528. </a>
  529. <span data-element-tooltip>Copied!</span>
  530. </div>
  531. )
  532. }
  533. export default function Share(props: {
  534. id: string
  535. api: string
  536. info: Session.Info
  537. messages: Record<string, Message.Info>
  538. }) {
  539. let lastScrollY = 0
  540. let scrollTimeout: number | undefined
  541. let scrollSentinel: HTMLElement | undefined
  542. let scrollObserver: IntersectionObserver | undefined
  543. const id = props.id
  544. const params = new URLSearchParams(window.location.search)
  545. const debug = params.get("debug") === "true"
  546. const [showScrollButton, setShowScrollButton] = createSignal(false)
  547. const [isButtonHovered, setIsButtonHovered] = createSignal(false)
  548. const [isNearBottom, setIsNearBottom] = createSignal(false)
  549. const [store, setStore] = createStore<{
  550. info?: Session.Info
  551. messages: Record<string, Message.Info>
  552. }>({ info: props.info, messages: props.messages })
  553. const messages = createMemo(() =>
  554. Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)),
  555. )
  556. const [connectionStatus, setConnectionStatus] = createSignal<
  557. [Status, string?]
  558. >(["disconnected", "Disconnected"])
  559. onMount(() => {
  560. const apiUrl = props.api
  561. if (!id) {
  562. setConnectionStatus(["error", "id not found"])
  563. return
  564. }
  565. if (!apiUrl) {
  566. console.error("API URL not found in environment variables")
  567. setConnectionStatus(["error", "API URL not found"])
  568. return
  569. }
  570. let reconnectTimer: number | undefined
  571. let socket: WebSocket | null = null
  572. // Function to create and set up WebSocket with auto-reconnect
  573. const setupWebSocket = () => {
  574. // Close any existing connection
  575. if (socket) {
  576. socket.close()
  577. }
  578. setConnectionStatus(["connecting"])
  579. // Always use secure WebSocket protocol (wss)
  580. const wsBaseUrl = apiUrl.replace(/^https?:\/\//, "wss://")
  581. const wsUrl = `${wsBaseUrl}/share_poll?id=${id}`
  582. console.log("Connecting to WebSocket URL:", wsUrl)
  583. // Create WebSocket connection
  584. socket = new WebSocket(wsUrl)
  585. // Handle connection opening
  586. socket.onopen = () => {
  587. setConnectionStatus(["connected"])
  588. console.log("WebSocket connection established")
  589. }
  590. // Handle incoming messages
  591. socket.onmessage = (event) => {
  592. console.log("WebSocket message received")
  593. try {
  594. const d = JSON.parse(event.data)
  595. const [root, type, ...splits] = d.key.split("/")
  596. if (root !== "session") return
  597. if (type === "info") {
  598. setStore("info", reconcile(d.content))
  599. return
  600. }
  601. if (type === "message") {
  602. const [, messageID] = splits
  603. setStore("messages", messageID, reconcile(d.content))
  604. }
  605. } catch (error) {
  606. console.error("Error parsing WebSocket message:", error)
  607. }
  608. }
  609. // Handle errors
  610. socket.onerror = (error) => {
  611. console.error("WebSocket error:", error)
  612. setConnectionStatus(["error", "Connection failed"])
  613. }
  614. // Handle connection close and reconnection
  615. socket.onclose = (event) => {
  616. console.log(`WebSocket closed: ${event.code} ${event.reason}`)
  617. setConnectionStatus(["reconnecting"])
  618. // Try to reconnect after 2 seconds
  619. clearTimeout(reconnectTimer)
  620. reconnectTimer = window.setTimeout(
  621. setupWebSocket,
  622. 2000,
  623. ) as unknown as number
  624. }
  625. }
  626. // Initial connection
  627. setupWebSocket()
  628. // Clean up on component unmount
  629. onCleanup(() => {
  630. console.log("Cleaning up WebSocket connection")
  631. if (socket) {
  632. socket.close()
  633. }
  634. clearTimeout(reconnectTimer)
  635. })
  636. })
  637. function checkScrollNeed() {
  638. const currentScrollY = window.scrollY
  639. const isScrollingDown = currentScrollY > lastScrollY
  640. const scrolled = currentScrollY > 200 // Show after scrolling 200px
  641. // Only show when scrolling down, scrolled enough, and not near bottom
  642. const shouldShow = isScrollingDown && scrolled && !isNearBottom()
  643. // Update last scroll position
  644. lastScrollY = currentScrollY
  645. if (shouldShow) {
  646. setShowScrollButton(true)
  647. // Clear existing timeout
  648. if (scrollTimeout) {
  649. clearTimeout(scrollTimeout)
  650. }
  651. // Hide button after 3 seconds of no scrolling (unless hovered)
  652. scrollTimeout = window.setTimeout(() => {
  653. if (!isButtonHovered()) {
  654. setShowScrollButton(false)
  655. }
  656. }, 1500)
  657. } else if (!isButtonHovered()) {
  658. // Only hide if not hovered (to prevent disappearing while user is about to click)
  659. setShowScrollButton(false)
  660. if (scrollTimeout) {
  661. clearTimeout(scrollTimeout)
  662. }
  663. }
  664. }
  665. onMount(() => {
  666. lastScrollY = window.scrollY // Initialize scroll position
  667. // Create sentinel element
  668. const sentinel = document.createElement("div")
  669. sentinel.style.height = "1px"
  670. sentinel.style.position = "absolute"
  671. sentinel.style.bottom = "100px"
  672. sentinel.style.width = "100%"
  673. sentinel.style.pointerEvents = "none"
  674. document.body.appendChild(sentinel)
  675. // Create intersection observer
  676. const observer = new IntersectionObserver((entries) => {
  677. setIsNearBottom(entries[0].isIntersecting)
  678. })
  679. observer.observe(sentinel)
  680. // Store references for cleanup
  681. scrollSentinel = sentinel
  682. scrollObserver = observer
  683. checkScrollNeed()
  684. window.addEventListener("scroll", checkScrollNeed)
  685. window.addEventListener("resize", checkScrollNeed)
  686. })
  687. onCleanup(() => {
  688. window.removeEventListener("scroll", checkScrollNeed)
  689. window.removeEventListener("resize", checkScrollNeed)
  690. // Clean up observer and sentinel
  691. if (scrollObserver) {
  692. scrollObserver.disconnect()
  693. }
  694. if (scrollSentinel) {
  695. document.body.removeChild(scrollSentinel)
  696. }
  697. if (scrollTimeout) {
  698. clearTimeout(scrollTimeout)
  699. }
  700. })
  701. const data = createMemo(() => {
  702. const result = {
  703. rootDir: undefined as string | undefined,
  704. created: undefined as number | undefined,
  705. completed: undefined as number | undefined,
  706. messages: [] as Message.Info[],
  707. models: {} as Record<string, string[]>,
  708. cost: 0,
  709. tokens: {
  710. input: 0,
  711. output: 0,
  712. reasoning: 0,
  713. },
  714. }
  715. result.created = props.info.time.created
  716. for (let i = 0; i < messages().length; i++) {
  717. const msg = messages()[i]
  718. const assistant = msg.metadata?.assistant
  719. result.messages.push(msg)
  720. if (assistant) {
  721. result.cost += assistant.cost
  722. result.tokens.input += assistant.tokens.input
  723. result.tokens.output += assistant.tokens.output
  724. result.tokens.reasoning += assistant.tokens.reasoning
  725. result.models[`${assistant.providerID} ${assistant.modelID}`] = [
  726. assistant.providerID,
  727. assistant.modelID,
  728. ]
  729. if (assistant.path?.root) {
  730. result.rootDir = assistant.path.root
  731. }
  732. if (msg.metadata?.time.completed) {
  733. result.completed = msg.metadata?.time.completed
  734. }
  735. }
  736. }
  737. return result
  738. })
  739. return (
  740. <main class={`${styles.root} not-content`}>
  741. <div class={styles.header}>
  742. <div data-section="title">
  743. <h1>{store.info?.title}</h1>
  744. </div>
  745. <div data-section="row">
  746. <ul data-section="stats" data-section-models>
  747. <li title="opencode version">
  748. <div data-stat-icon title="opencode">
  749. <IconOpencode width={16} height={16} />
  750. </div>
  751. <Show when={store.info?.version} fallback="v0.0.1">
  752. <span>v{store.info?.version}</span>
  753. </Show>
  754. </li>
  755. {Object.values(data().models).length > 0 ? (
  756. <For each={Object.values(data().models)}>
  757. {([provider, model]) => (
  758. <li>
  759. <div data-stat-icon title={provider}>
  760. <ProviderIcon provider={provider} />
  761. </div>
  762. <span data-stat-model>{model}</span>
  763. </li>
  764. )}
  765. </For>
  766. ) : (
  767. <li>
  768. <span data-element-label>Models</span>
  769. <span data-placeholder>&mdash;</span>
  770. </li>
  771. )}
  772. </ul>
  773. <div data-section="time">
  774. {data().created ? (
  775. <span
  776. title={DateTime.fromMillis(data().created || 0).toLocaleString(
  777. DateTime.DATETIME_FULL_WITH_SECONDS,
  778. )}
  779. >
  780. {DateTime.fromMillis(data().created || 0).toLocaleString(
  781. DateTime.DATETIME_MED,
  782. )}
  783. </span>
  784. ) : (
  785. <span data-element-label data-placeholder>
  786. Started at &mdash;
  787. </span>
  788. )}
  789. </div>
  790. </div>
  791. </div>
  792. <div>
  793. <Show
  794. when={data().messages.length > 0}
  795. fallback={<p>Waiting for messages...</p>}
  796. >
  797. <div class={styles.parts}>
  798. <SuspenseList revealOrder="forwards">
  799. <For each={data().messages}>
  800. {(msg, msgIndex) => (
  801. <Suspense>
  802. <For each={msg.parts}>
  803. {(part, partIndex) => {
  804. if (
  805. (part.type === "step-start" &&
  806. (partIndex() > 0 || !msg.metadata?.assistant)) ||
  807. (msg.role === "assistant" &&
  808. part.type === "tool-invocation" &&
  809. part.toolInvocation.toolName === "todoread")
  810. )
  811. return null
  812. const anchor = createMemo(
  813. () => `${msg.id}-${partIndex()}`,
  814. )
  815. const [showResults, setShowResults] =
  816. createSignal(false)
  817. const isLastPart = createMemo(
  818. () =>
  819. data().messages.length === msgIndex() + 1 &&
  820. msg.parts.length === partIndex() + 1,
  821. )
  822. const toolData = createMemo(() => {
  823. if (
  824. msg.role !== "assistant" ||
  825. part.type !== "tool-invocation"
  826. )
  827. return {}
  828. const metadata =
  829. msg.metadata?.tool[part.toolInvocation.toolCallId]
  830. const args = part.toolInvocation.args
  831. const result =
  832. part.toolInvocation.state === "result" &&
  833. part.toolInvocation.result
  834. const duration = DateTime.fromMillis(
  835. metadata?.time.end || 0,
  836. )
  837. .diff(
  838. DateTime.fromMillis(metadata?.time.start || 0),
  839. )
  840. .toMillis()
  841. return { metadata, args, result, duration }
  842. })
  843. onMount(() => {
  844. const hash = window.location.hash.slice(1)
  845. // Wait till all parts are loaded
  846. if (
  847. hash !== ""
  848. && msg.parts.length === partIndex() + 1
  849. && data().messages.length === msgIndex() + 1
  850. ) {
  851. scrollToAnchor(hash)
  852. }
  853. })
  854. return (
  855. <Switch>
  856. {/* User text */}
  857. <Match
  858. when={
  859. msg.role === "user" &&
  860. part.type === "text" &&
  861. part
  862. }
  863. >
  864. {(part) => (
  865. <div
  866. id={anchor()}
  867. data-section="part"
  868. data-part-type="user-text"
  869. >
  870. <div data-section="decoration">
  871. <AnchorIcon id={anchor()}>
  872. <IconUserCircle width={18} height={18} />
  873. </AnchorIcon>
  874. <div></div>
  875. </div>
  876. <div data-section="content">
  877. <TextPart
  878. invert
  879. text={part().text}
  880. expand={isLastPart()}
  881. />
  882. </div>
  883. </div>
  884. )}
  885. </Match>
  886. {/* AI text */}
  887. <Match
  888. when={
  889. msg.role === "assistant" &&
  890. part.type === "text" &&
  891. part
  892. }
  893. >
  894. {(part) => (
  895. <div
  896. id={anchor()}
  897. data-section="part"
  898. data-part-type="ai-text"
  899. >
  900. <div data-section="decoration">
  901. <AnchorIcon id={anchor()}>
  902. <IconSparkles width={18} height={18} />
  903. </AnchorIcon>
  904. <div></div>
  905. </div>
  906. <div data-section="content">
  907. <MarkdownPart
  908. highlight
  909. expand={isLastPart()}
  910. text={stripEnclosingTag(part().text)}
  911. />
  912. <Show
  913. when={isLastPart() && data().completed}
  914. >
  915. <span
  916. data-part-footer
  917. title={DateTime.fromMillis(
  918. data().completed || 0,
  919. ).toLocaleString(
  920. DateTime.DATETIME_FULL_WITH_SECONDS,
  921. )}
  922. >
  923. {DateTime.fromMillis(
  924. data().completed || 0,
  925. ).toLocaleString(DateTime.DATETIME_MED)}
  926. </span>
  927. </Show>
  928. </div>
  929. </div>
  930. )}
  931. </Match>
  932. {/* AI model */}
  933. <Match
  934. when={
  935. msg.role === "assistant" &&
  936. part.type === "step-start" &&
  937. msg.metadata?.assistant
  938. }
  939. >
  940. {(assistant) => {
  941. return (
  942. <div
  943. id={anchor()}
  944. data-section="part"
  945. data-part-type="ai-model"
  946. >
  947. <div data-section="decoration">
  948. <AnchorIcon id={anchor()}>
  949. <ProviderIcon
  950. size={18}
  951. provider={assistant().providerID}
  952. />
  953. </AnchorIcon>
  954. <div></div>
  955. </div>
  956. <div data-section="content">
  957. <div data-part-tool-body>
  958. <div data-part-title>
  959. <span data-element-label>
  960. {assistant().providerID}
  961. </span>
  962. </div>
  963. <span data-part-model>
  964. {assistant().modelID}
  965. </span>
  966. </div>
  967. </div>
  968. </div>
  969. )
  970. }}
  971. </Match>
  972. {/* Grep tool */}
  973. <Match
  974. when={
  975. msg.role === "assistant" &&
  976. part.type === "tool-invocation" &&
  977. part.toolInvocation.toolName === "grep" &&
  978. part
  979. }
  980. >
  981. {(_part) => {
  982. const matches = () =>
  983. toolData()?.metadata?.matches
  984. const splitArgs = () => {
  985. const { pattern, ...rest } = toolData()?.args
  986. return { pattern, rest }
  987. }
  988. return (
  989. <div
  990. id={anchor()}
  991. data-section="part"
  992. data-part-type="tool-grep"
  993. >
  994. <div data-section="decoration">
  995. <AnchorIcon id={anchor()}>
  996. <IconDocumentMagnifyingGlass
  997. width={18}
  998. height={18}
  999. />
  1000. </AnchorIcon>
  1001. <div></div>
  1002. </div>
  1003. <div data-section="content">
  1004. <div data-part-tool-body>
  1005. <div data-part-title>
  1006. <span data-element-label>Grep</span>
  1007. <b>
  1008. &ldquo;{splitArgs().pattern}&rdquo;
  1009. </b>
  1010. </div>
  1011. <Show
  1012. when={
  1013. Object.keys(splitArgs().rest)
  1014. .length > 0
  1015. }
  1016. >
  1017. <div data-part-tool-args>
  1018. <For
  1019. each={flattenToolArgs(
  1020. splitArgs().rest,
  1021. )}
  1022. >
  1023. {([name, value]) => (
  1024. <>
  1025. <div></div>
  1026. <div>{name}</div>
  1027. <div>{value}</div>
  1028. </>
  1029. )}
  1030. </For>
  1031. </div>
  1032. </Show>
  1033. <Switch>
  1034. <Match when={matches() > 0}>
  1035. <div data-part-tool-result>
  1036. <ResultsButton
  1037. showCopy={
  1038. matches() === 1
  1039. ? "1 match"
  1040. : `${matches()} matches`
  1041. }
  1042. hideCopy="Hide matches"
  1043. results={showResults()}
  1044. onClick={() =>
  1045. setShowResults((e) => !e)
  1046. }
  1047. />
  1048. <Show when={showResults()}>
  1049. <TextPart
  1050. expand
  1051. data-size="sm"
  1052. data-color="dimmed"
  1053. text={toolData()?.result}
  1054. />
  1055. </Show>
  1056. </div>
  1057. </Match>
  1058. <Match when={toolData()?.result}>
  1059. <div data-part-tool-result>
  1060. <TextPart
  1061. expand
  1062. data-size="sm"
  1063. data-color="dimmed"
  1064. text={toolData()?.result}
  1065. />
  1066. </div>
  1067. </Match>
  1068. </Switch>
  1069. </div>
  1070. <ToolFooter
  1071. time={toolData()?.duration || 0}
  1072. />
  1073. </div>
  1074. </div>
  1075. )
  1076. }}
  1077. </Match>
  1078. {/* Glob tool */}
  1079. <Match
  1080. when={
  1081. msg.role === "assistant" &&
  1082. part.type === "tool-invocation" &&
  1083. part.toolInvocation.toolName === "glob" &&
  1084. part
  1085. }
  1086. >
  1087. {(_part) => {
  1088. const count = () => toolData()?.metadata?.count
  1089. const pattern = () => toolData()?.args.pattern
  1090. return (
  1091. <div
  1092. id={anchor()}
  1093. data-section="part"
  1094. data-part-type="tool-glob"
  1095. >
  1096. <div data-section="decoration">
  1097. <AnchorIcon id={anchor()}>
  1098. <IconMagnifyingGlass
  1099. width={18}
  1100. height={18}
  1101. />
  1102. </AnchorIcon>
  1103. <div></div>
  1104. </div>
  1105. <div data-section="content">
  1106. <div data-part-tool-body>
  1107. <div data-part-title>
  1108. <span data-element-label>Glob</span>
  1109. <b>&ldquo;{pattern()}&rdquo;</b>
  1110. </div>
  1111. <Switch>
  1112. <Match when={count() > 0}>
  1113. <div data-part-tool-result>
  1114. <ResultsButton
  1115. showCopy={
  1116. count() === 1
  1117. ? "1 result"
  1118. : `${count()} results`
  1119. }
  1120. results={showResults()}
  1121. onClick={() =>
  1122. setShowResults((e) => !e)
  1123. }
  1124. />
  1125. <Show when={showResults()}>
  1126. <TextPart
  1127. expand
  1128. text={toolData()?.result}
  1129. data-size="sm"
  1130. data-color="dimmed"
  1131. />
  1132. </Show>
  1133. </div>
  1134. </Match>
  1135. <Match when={toolData()?.result}>
  1136. <div data-part-tool-result>
  1137. <TextPart
  1138. expand
  1139. text={toolData()?.result}
  1140. data-size="sm"
  1141. data-color="dimmed"
  1142. />
  1143. </div>
  1144. </Match>
  1145. </Switch>
  1146. </div>
  1147. <ToolFooter
  1148. time={toolData()?.duration || 0}
  1149. />
  1150. </div>
  1151. </div>
  1152. )
  1153. }}
  1154. </Match>
  1155. {/* LS tool */}
  1156. <Match
  1157. when={
  1158. msg.role === "assistant" &&
  1159. part.type === "tool-invocation" &&
  1160. part.toolInvocation.toolName === "list" &&
  1161. part
  1162. }
  1163. >
  1164. {(_part) => {
  1165. const path = createMemo(() =>
  1166. toolData()?.args?.path !== data().rootDir
  1167. ? stripWorkingDirectory(
  1168. toolData()?.args?.path,
  1169. data().rootDir,
  1170. )
  1171. : toolData()?.args?.path,
  1172. )
  1173. return (
  1174. <div
  1175. id={anchor()}
  1176. data-section="part"
  1177. data-part-type="tool-list"
  1178. >
  1179. <div data-section="decoration">
  1180. <AnchorIcon id={anchor()}>
  1181. <IconRectangleStack
  1182. width={18}
  1183. height={18}
  1184. />
  1185. </AnchorIcon>
  1186. <div></div>
  1187. </div>
  1188. <div data-section="content">
  1189. <div data-part-tool-body>
  1190. <div data-part-title>
  1191. <span data-element-label>LS</span>
  1192. <b title={toolData()?.args?.path}>
  1193. {path()}
  1194. </b>
  1195. </div>
  1196. <Switch>
  1197. <Match when={toolData()?.result}>
  1198. <div data-part-tool-result>
  1199. <ResultsButton
  1200. results={showResults()}
  1201. onClick={() =>
  1202. setShowResults((e) => !e)
  1203. }
  1204. />
  1205. <Show when={showResults()}>
  1206. <TextPart
  1207. expand
  1208. data-size="sm"
  1209. data-color="dimmed"
  1210. text={toolData()?.result}
  1211. />
  1212. </Show>
  1213. </div>
  1214. </Match>
  1215. </Switch>
  1216. </div>
  1217. <ToolFooter
  1218. time={toolData()?.duration || 0}
  1219. />
  1220. </div>
  1221. </div>
  1222. )
  1223. }}
  1224. </Match>
  1225. {/* Read tool */}
  1226. <Match
  1227. when={
  1228. msg.role === "assistant" &&
  1229. part.type === "tool-invocation" &&
  1230. part.toolInvocation.toolName === "read" &&
  1231. part
  1232. }
  1233. >
  1234. {(_part) => {
  1235. const filePath = createMemo(() =>
  1236. stripWorkingDirectory(
  1237. toolData()?.args?.filePath,
  1238. data().rootDir,
  1239. ),
  1240. )
  1241. const hasError = () =>
  1242. toolData()?.metadata?.error
  1243. const preview = () =>
  1244. toolData()?.metadata?.preview
  1245. return (
  1246. <div
  1247. id={anchor()}
  1248. data-section="part"
  1249. data-part-type="tool-read"
  1250. >
  1251. <div data-section="decoration">
  1252. <AnchorIcon id={anchor()}>
  1253. <IconDocument width={18} height={18} />
  1254. </AnchorIcon>
  1255. <div></div>
  1256. </div>
  1257. <div data-section="content">
  1258. <div data-part-tool-body>
  1259. <div data-part-title>
  1260. <span data-element-label>Read</span>
  1261. <b title={toolData()?.args?.filePath}>
  1262. {filePath()}
  1263. </b>
  1264. </div>
  1265. <Switch>
  1266. <Match when={hasError()}>
  1267. <div data-part-tool-result>
  1268. <ErrorPart>
  1269. {formatErrorString(
  1270. toolData()?.result,
  1271. )}
  1272. </ErrorPart>
  1273. </div>
  1274. </Match>
  1275. {/* Always try to show CodeBlock if preview is available (even if empty string) */}
  1276. <Match
  1277. when={typeof preview() === "string"}
  1278. >
  1279. <div data-part-tool-result>
  1280. <ResultsButton
  1281. showCopy="Show preview"
  1282. hideCopy="Hide preview"
  1283. results={showResults()}
  1284. onClick={() =>
  1285. setShowResults((e) => !e)
  1286. }
  1287. />
  1288. <Show when={showResults()}>
  1289. <div data-part-tool-code>
  1290. <CodeBlock
  1291. lang={getShikiLang(
  1292. filePath(),
  1293. )}
  1294. code={preview()}
  1295. />
  1296. </div>
  1297. </Show>
  1298. </div>
  1299. </Match>
  1300. {/* Fallback to TextPart if preview is not a string (e.g. undefined) AND result exists */}
  1301. <Match
  1302. when={
  1303. typeof preview() !== "string" &&
  1304. toolData()?.result
  1305. }
  1306. >
  1307. <div data-part-tool-result>
  1308. <ResultsButton
  1309. results={showResults()}
  1310. onClick={() =>
  1311. setShowResults((e) => !e)
  1312. }
  1313. />
  1314. <Show when={showResults()}>
  1315. <TextPart
  1316. expand
  1317. text={toolData()?.result}
  1318. data-size="sm"
  1319. data-color="dimmed"
  1320. />
  1321. </Show>
  1322. </div>
  1323. </Match>
  1324. </Switch>
  1325. </div>
  1326. <ToolFooter
  1327. time={toolData()?.duration || 0}
  1328. />
  1329. </div>
  1330. </div>
  1331. )
  1332. }}
  1333. </Match>
  1334. {/* Write tool */}
  1335. <Match
  1336. when={
  1337. msg.role === "assistant" &&
  1338. part.type === "tool-invocation" &&
  1339. part.toolInvocation.toolName === "write" &&
  1340. part
  1341. }
  1342. >
  1343. {(_part) => {
  1344. const filePath = createMemo(() =>
  1345. stripWorkingDirectory(
  1346. toolData()?.args?.filePath,
  1347. data().rootDir,
  1348. ),
  1349. )
  1350. const hasError = () =>
  1351. toolData()?.metadata?.error
  1352. const content = () => toolData()?.args?.content
  1353. const diagnostics = createMemo(() =>
  1354. getDiagnostics(
  1355. toolData()?.metadata?.diagnostics,
  1356. toolData()?.args.filePath,
  1357. ),
  1358. )
  1359. return (
  1360. <div
  1361. id={anchor()}
  1362. data-section="part"
  1363. data-part-type="tool-write"
  1364. >
  1365. <div data-section="decoration">
  1366. <AnchorIcon id={anchor()}>
  1367. <IconDocumentPlus
  1368. width={18}
  1369. height={18}
  1370. />
  1371. </AnchorIcon>
  1372. <div></div>
  1373. </div>
  1374. <div data-section="content">
  1375. <div data-part-tool-body>
  1376. <div data-part-title>
  1377. <span data-element-label>Write</span>
  1378. <b title={toolData()?.args?.filePath}>
  1379. {filePath()}
  1380. </b>
  1381. </div>
  1382. <Show when={diagnostics().length > 0}>
  1383. <ErrorPart>{diagnostics()}</ErrorPart>
  1384. </Show>
  1385. <Switch>
  1386. <Match when={hasError()}>
  1387. <div data-part-tool-result>
  1388. <ErrorPart>
  1389. {formatErrorString(
  1390. toolData()?.result,
  1391. )}
  1392. </ErrorPart>
  1393. </div>
  1394. </Match>
  1395. <Match when={content()}>
  1396. <div data-part-tool-result>
  1397. <ResultsButton
  1398. showCopy="Show contents"
  1399. hideCopy="Hide contents"
  1400. results={showResults()}
  1401. onClick={() =>
  1402. setShowResults((e) => !e)
  1403. }
  1404. />
  1405. <Show when={showResults()}>
  1406. <div data-part-tool-code>
  1407. <CodeBlock
  1408. lang={getShikiLang(
  1409. filePath(),
  1410. )}
  1411. code={
  1412. toolData()?.args?.content
  1413. }
  1414. />
  1415. </div>
  1416. </Show>
  1417. </div>
  1418. </Match>
  1419. </Switch>
  1420. </div>
  1421. <ToolFooter
  1422. time={toolData()?.duration || 0}
  1423. />
  1424. </div>
  1425. </div>
  1426. )
  1427. }}
  1428. </Match>
  1429. {/* Edit tool */}
  1430. <Match
  1431. when={
  1432. msg.role === "assistant" &&
  1433. part.type === "tool-invocation" &&
  1434. part.toolInvocation.toolName === "edit" &&
  1435. part
  1436. }
  1437. >
  1438. {(_part) => {
  1439. const diff = () => toolData()?.metadata?.diff
  1440. const message = () =>
  1441. toolData()?.metadata?.message
  1442. const hasError = () =>
  1443. toolData()?.metadata?.error
  1444. const filePath = createMemo(() =>
  1445. stripWorkingDirectory(
  1446. toolData()?.args.filePath,
  1447. data().rootDir,
  1448. ),
  1449. )
  1450. const diagnostics = createMemo(() =>
  1451. getDiagnostics(
  1452. toolData()?.metadata?.diagnostics,
  1453. toolData()?.args.filePath,
  1454. ),
  1455. )
  1456. return (
  1457. <div
  1458. id={anchor()}
  1459. data-section="part"
  1460. data-part-type="tool-edit"
  1461. >
  1462. <div data-section="decoration">
  1463. <AnchorIcon id={anchor()}>
  1464. <IconPencilSquare
  1465. width={18}
  1466. height={18}
  1467. />
  1468. </AnchorIcon>
  1469. <div></div>
  1470. </div>
  1471. <div data-section="content">
  1472. <div data-part-tool-body>
  1473. <div data-part-title>
  1474. <span data-element-label>Edit</span>
  1475. <b title={toolData()?.args?.filePath}>
  1476. {filePath()}
  1477. </b>
  1478. </div>
  1479. <Switch>
  1480. <Match when={hasError()}>
  1481. <div data-part-tool-result>
  1482. <ErrorPart>
  1483. {formatErrorString(message())}
  1484. </ErrorPart>
  1485. </div>
  1486. </Match>
  1487. <Match when={diff()}>
  1488. <div data-part-tool-edit>
  1489. <DiffView
  1490. class={
  1491. styles["diff-code-block"]
  1492. }
  1493. diff={diff()}
  1494. lang={getShikiLang(filePath())}
  1495. />
  1496. </div>
  1497. </Match>
  1498. </Switch>
  1499. <Show when={diagnostics().length > 0}>
  1500. <ErrorPart>{diagnostics()}</ErrorPart>
  1501. </Show>
  1502. </div>
  1503. <ToolFooter
  1504. time={toolData()?.duration || 0}
  1505. />
  1506. </div>
  1507. </div>
  1508. )
  1509. }}
  1510. </Match>
  1511. {/* Bash tool */}
  1512. <Match
  1513. when={
  1514. msg.role === "assistant" &&
  1515. part.type === "tool-invocation" &&
  1516. part.toolInvocation.toolName === "bash" &&
  1517. part
  1518. }
  1519. >
  1520. {(_part) => {
  1521. const command = () =>
  1522. toolData()?.metadata?.title
  1523. const desc = () =>
  1524. toolData()?.metadata?.description
  1525. const result = () =>
  1526. toolData()?.metadata?.stdout
  1527. const error = () => toolData()?.metadata?.stderr
  1528. return (
  1529. <div
  1530. id={anchor()}
  1531. data-section="part"
  1532. data-part-type="tool-bash"
  1533. >
  1534. <div data-section="decoration">
  1535. <AnchorIcon id={anchor()}>
  1536. <IconCommandLine
  1537. width={18}
  1538. height={18}
  1539. />
  1540. </AnchorIcon>
  1541. <div></div>
  1542. </div>
  1543. <div data-section="content">
  1544. {command() && (
  1545. <div data-part-tool-body>
  1546. <TerminalPart
  1547. desc={desc()}
  1548. data-size="sm"
  1549. command={command()!}
  1550. result={result()}
  1551. error={error()}
  1552. />
  1553. </div>
  1554. )}
  1555. <ToolFooter
  1556. time={toolData()?.duration || 0}
  1557. />
  1558. </div>
  1559. </div>
  1560. )
  1561. }}
  1562. </Match>
  1563. {/* Todo write */}
  1564. <Match
  1565. when={
  1566. msg.role === "assistant" &&
  1567. part.type === "tool-invocation" &&
  1568. part.toolInvocation.toolName === "todowrite" &&
  1569. part
  1570. }
  1571. >
  1572. {(_part) => {
  1573. const todos = createMemo(() =>
  1574. sortTodosByStatus(
  1575. toolData()?.args?.todos ?? [],
  1576. ),
  1577. )
  1578. const starting = () =>
  1579. todos().every((t) => t.status === "pending")
  1580. const finished = () =>
  1581. todos().every((t) => t.status === "completed")
  1582. return (
  1583. <div
  1584. id={anchor()}
  1585. data-section="part"
  1586. data-part-type="tool-todo"
  1587. >
  1588. <div data-section="decoration">
  1589. <AnchorIcon id={anchor()}>
  1590. <IconQueueList width={18} height={18} />
  1591. </AnchorIcon>
  1592. <div></div>
  1593. </div>
  1594. <div data-section="content">
  1595. <div data-part-tool-body>
  1596. <div data-part-title>
  1597. <span data-element-label>
  1598. <Switch fallback="Updating plan">
  1599. <Match when={starting()}>
  1600. Creating plan
  1601. </Match>
  1602. <Match when={finished()}>
  1603. Completing plan
  1604. </Match>
  1605. </Switch>
  1606. </span>
  1607. </div>
  1608. <Show when={todos().length > 0}>
  1609. <ul class={styles.todos}>
  1610. <For each={todos()}>
  1611. {(todo) => (
  1612. <li data-status={todo.status}>
  1613. <span></span>
  1614. {todo.content}
  1615. </li>
  1616. )}
  1617. </For>
  1618. </ul>
  1619. </Show>
  1620. </div>
  1621. <ToolFooter
  1622. time={toolData()?.duration || 0}
  1623. />
  1624. </div>
  1625. </div>
  1626. )
  1627. }}
  1628. </Match>
  1629. {/* Fetch tool */}
  1630. <Match
  1631. when={
  1632. msg.role === "assistant" &&
  1633. part.type === "tool-invocation" &&
  1634. part.toolInvocation.toolName === "webfetch" &&
  1635. part
  1636. }
  1637. >
  1638. {(_part) => {
  1639. const url = () => toolData()?.args.url
  1640. const format = () => toolData()?.args.format
  1641. const hasError = () =>
  1642. toolData()?.metadata?.error
  1643. return (
  1644. <div
  1645. id={anchor()}
  1646. data-section="part"
  1647. data-part-type="tool-fetch"
  1648. >
  1649. <div data-section="decoration">
  1650. <AnchorIcon id={anchor()}>
  1651. <IconGlobeAlt width={18} height={18} />
  1652. </AnchorIcon>
  1653. <div></div>
  1654. </div>
  1655. <div data-section="content">
  1656. <div data-part-tool-body>
  1657. <div data-part-title>
  1658. <span data-element-label>Fetch</span>
  1659. <b>{url()}</b>
  1660. </div>
  1661. <Switch>
  1662. <Match when={hasError()}>
  1663. <div data-part-tool-result>
  1664. <ErrorPart>
  1665. {formatErrorString(
  1666. toolData()?.result,
  1667. )}
  1668. </ErrorPart>
  1669. </div>
  1670. </Match>
  1671. <Match when={toolData()?.result}>
  1672. <div data-part-tool-result>
  1673. <ResultsButton
  1674. results={showResults()}
  1675. onClick={() =>
  1676. setShowResults((e) => !e)
  1677. }
  1678. />
  1679. <Show when={showResults()}>
  1680. <div data-part-tool-code>
  1681. <CodeBlock
  1682. lang={format() || "text"}
  1683. code={toolData()?.result}
  1684. />
  1685. </div>
  1686. </Show>
  1687. </div>
  1688. </Match>
  1689. </Switch>
  1690. </div>
  1691. <ToolFooter
  1692. time={toolData()?.duration || 0}
  1693. />
  1694. </div>
  1695. </div>
  1696. )
  1697. }}
  1698. </Match>
  1699. {/* Tool call */}
  1700. <Match
  1701. when={
  1702. msg.role === "assistant" &&
  1703. part.type === "tool-invocation" &&
  1704. part
  1705. }
  1706. >
  1707. {(part) => {
  1708. return (
  1709. <div
  1710. id={anchor()}
  1711. data-section="part"
  1712. data-part-type="tool-fallback"
  1713. >
  1714. <div data-section="decoration">
  1715. <AnchorIcon id={anchor()}>
  1716. <IconWrenchScrewdriver
  1717. width={18}
  1718. height={18}
  1719. />
  1720. </AnchorIcon>
  1721. <div></div>
  1722. </div>
  1723. <div data-section="content">
  1724. <div data-part-tool-body>
  1725. <div data-part-title>
  1726. {part().toolInvocation.toolName}
  1727. </div>
  1728. <div data-part-tool-args>
  1729. <For
  1730. each={flattenToolArgs(
  1731. part().toolInvocation.args,
  1732. )}
  1733. >
  1734. {(arg) => (
  1735. <>
  1736. <div></div>
  1737. <div>{arg[0]}</div>
  1738. <div>{arg[1]}</div>
  1739. </>
  1740. )}
  1741. </For>
  1742. </div>
  1743. <Switch>
  1744. <Match when={toolData()?.result}>
  1745. <div data-part-tool-result>
  1746. <ResultsButton
  1747. results={showResults()}
  1748. onClick={() =>
  1749. setShowResults((e) => !e)
  1750. }
  1751. />
  1752. <Show when={showResults()}>
  1753. <TextPart
  1754. expand
  1755. data-size="sm"
  1756. data-color="dimmed"
  1757. text={toolData()?.result}
  1758. />
  1759. </Show>
  1760. </div>
  1761. </Match>
  1762. <Match
  1763. when={
  1764. part().toolInvocation.state ===
  1765. "call"
  1766. }
  1767. >
  1768. <TextPart
  1769. data-size="sm"
  1770. data-color="dimmed"
  1771. text="Calling..."
  1772. />
  1773. </Match>
  1774. </Switch>
  1775. </div>
  1776. <ToolFooter
  1777. time={toolData()?.duration || 0}
  1778. />
  1779. </div>
  1780. </div>
  1781. )
  1782. }}
  1783. </Match>
  1784. {/* Fallback */}
  1785. <Match when={true}>
  1786. <div
  1787. id={anchor()}
  1788. data-section="part"
  1789. data-part-type="fallback"
  1790. >
  1791. <div data-section="decoration">
  1792. <AnchorIcon id={anchor()}>
  1793. <Switch
  1794. fallback={
  1795. <IconWrenchScrewdriver
  1796. width={16}
  1797. height={16}
  1798. />
  1799. }
  1800. >
  1801. <Match
  1802. when={
  1803. msg.role === "assistant" &&
  1804. part.type !== "tool-invocation"
  1805. }
  1806. >
  1807. <IconSparkles width={18} height={18} />
  1808. </Match>
  1809. <Match when={msg.role === "user"}>
  1810. <IconUserCircle
  1811. width={18}
  1812. height={18}
  1813. />
  1814. </Match>
  1815. </Switch>
  1816. </AnchorIcon>
  1817. <div></div>
  1818. </div>
  1819. <div data-section="content">
  1820. <div data-part-tool-body>
  1821. <div data-part-title>
  1822. <span data-element-label>
  1823. {part.type}
  1824. </span>
  1825. </div>
  1826. <TextPart
  1827. text={JSON.stringify(part, null, 2)}
  1828. />
  1829. </div>
  1830. </div>
  1831. </div>
  1832. </Match>
  1833. </Switch>
  1834. )
  1835. }}
  1836. </For>
  1837. </Suspense>
  1838. )}
  1839. </For>
  1840. </SuspenseList>
  1841. <div data-section="part" data-part-type="summary">
  1842. <div data-section="decoration">
  1843. <span data-status={connectionStatus()[0]}></span>
  1844. <div></div>
  1845. </div>
  1846. <div data-section="content">
  1847. <p data-section="copy">{getStatusText(connectionStatus())}</p>
  1848. <ul data-section="stats">
  1849. <li>
  1850. <span data-element-label>Cost</span>
  1851. {data().cost !== undefined ? (
  1852. <span>${data().cost.toFixed(2)}</span>
  1853. ) : (
  1854. <span data-placeholder>&mdash;</span>
  1855. )}
  1856. </li>
  1857. <li>
  1858. <span data-element-label>Input Tokens</span>
  1859. {data().tokens.input ? (
  1860. <span>{data().tokens.input}</span>
  1861. ) : (
  1862. <span data-placeholder>&mdash;</span>
  1863. )}
  1864. </li>
  1865. <li>
  1866. <span data-element-label>Output Tokens</span>
  1867. {data().tokens.output ? (
  1868. <span>{data().tokens.output}</span>
  1869. ) : (
  1870. <span data-placeholder>&mdash;</span>
  1871. )}
  1872. </li>
  1873. <li>
  1874. <span data-element-label>Reasoning Tokens</span>
  1875. {data().tokens.reasoning ? (
  1876. <span>{data().tokens.reasoning}</span>
  1877. ) : (
  1878. <span data-placeholder>&mdash;</span>
  1879. )}
  1880. </li>
  1881. </ul>
  1882. </div>
  1883. </div>
  1884. </div>
  1885. </Show>
  1886. </div>
  1887. <Show when={debug}>
  1888. <div style={{ margin: "2rem 0" }}>
  1889. <div
  1890. style={{
  1891. border: "1px solid #ccc",
  1892. padding: "1rem",
  1893. "overflow-y": "auto",
  1894. }}
  1895. >
  1896. <Show
  1897. when={data().messages.length > 0}
  1898. fallback={<p>Waiting for messages...</p>}
  1899. >
  1900. <ul style={{ "list-style-type": "none", padding: 0 }}>
  1901. <For each={data().messages}>
  1902. {(msg) => (
  1903. <li
  1904. style={{
  1905. padding: "0.75rem",
  1906. margin: "0.75rem 0",
  1907. "box-shadow": "0 1px 3px rgba(0,0,0,0.1)",
  1908. }}
  1909. >
  1910. <div>
  1911. <strong>Key:</strong> {msg.id}
  1912. </div>
  1913. <pre>{JSON.stringify(msg, null, 2)}</pre>
  1914. </li>
  1915. )}
  1916. </For>
  1917. </ul>
  1918. </Show>
  1919. </div>
  1920. </div>
  1921. </Show>
  1922. <Show when={showScrollButton()}>
  1923. <button
  1924. type="button"
  1925. class={styles["scroll-button"]}
  1926. onClick={() =>
  1927. document.body.scrollIntoView({ behavior: "smooth", block: "end" })
  1928. }
  1929. onMouseEnter={() => {
  1930. setIsButtonHovered(true)
  1931. if (scrollTimeout) {
  1932. clearTimeout(scrollTimeout)
  1933. }
  1934. }}
  1935. onMouseLeave={() => {
  1936. setIsButtonHovered(false)
  1937. if (showScrollButton()) {
  1938. scrollTimeout = window.setTimeout(() => {
  1939. if (!isButtonHovered()) {
  1940. setShowScrollButton(false)
  1941. }
  1942. }, 3000)
  1943. }
  1944. }}
  1945. title="Scroll to bottom"
  1946. aria-label="Scroll to bottom"
  1947. >
  1948. <IconArrowDown width={20} height={20} />
  1949. </button>
  1950. </Show>
  1951. </main>
  1952. )
  1953. }