session-turn.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import {
  2. AssistantMessage,
  3. FilePart,
  4. Message as MessageType,
  5. Part as PartType,
  6. type PermissionRequest,
  7. TextPart,
  8. ToolPart,
  9. } from "@opencode-ai/sdk/v2/client"
  10. import { useData } from "../context"
  11. import { useDiffComponent } from "../context/diff"
  12. import { getDirectory, getFilename } from "@opencode-ai/util/path"
  13. import { Binary } from "@opencode-ai/util/binary"
  14. import { createEffect, createMemo, createSignal, For, Match, on, onCleanup, ParentProps, Show, Switch } from "solid-js"
  15. import { DiffChanges } from "./diff-changes"
  16. import { Message, Part } from "./message-part"
  17. import { Markdown } from "./markdown"
  18. import { Accordion } from "./accordion"
  19. import { StickyAccordionHeader } from "./sticky-accordion-header"
  20. import { FileIcon } from "./file-icon"
  21. import { Icon } from "./icon"
  22. import { Card } from "./card"
  23. import { Dynamic } from "solid-js/web"
  24. import { Button } from "./button"
  25. import { Spinner } from "./spinner"
  26. import { createStore } from "solid-js/store"
  27. import { DateTime, DurationUnit, Interval } from "luxon"
  28. import { createAutoScroll } from "../hooks"
  29. import { createResizeObserver } from "@solid-primitives/resize-observer"
  30. function computeStatusFromPart(part: PartType | undefined): string | undefined {
  31. if (!part) return undefined
  32. if (part.type === "tool") {
  33. switch (part.tool) {
  34. case "task":
  35. return "Delegating work"
  36. case "todowrite":
  37. case "todoread":
  38. return "Planning next steps"
  39. case "read":
  40. return "Gathering context"
  41. case "list":
  42. case "grep":
  43. case "glob":
  44. return "Searching the codebase"
  45. case "webfetch":
  46. return "Searching the web"
  47. case "edit":
  48. case "write":
  49. return "Making edits"
  50. case "bash":
  51. return "Running commands"
  52. default:
  53. return undefined
  54. }
  55. }
  56. if (part.type === "reasoning") {
  57. const text = part.text ?? ""
  58. const match = text.trimStart().match(/^\*\*(.+?)\*\*/)
  59. if (match) return `Thinking · ${match[1].trim()}`
  60. return "Thinking"
  61. }
  62. if (part.type === "text") {
  63. return "Gathering thoughts"
  64. }
  65. return undefined
  66. }
  67. function same<T>(a: readonly T[], b: readonly T[]) {
  68. if (a === b) return true
  69. if (a.length !== b.length) return false
  70. return a.every((x, i) => x === b[i])
  71. }
  72. function isAttachment(part: PartType | undefined) {
  73. if (part?.type !== "file") return false
  74. const mime = (part as FilePart).mime ?? ""
  75. return mime.startsWith("image/") || mime === "application/pdf"
  76. }
  77. function AssistantMessageItem(props: {
  78. message: AssistantMessage
  79. responsePartId: string | undefined
  80. hideResponsePart: boolean
  81. hideReasoning: boolean
  82. }) {
  83. const data = useData()
  84. const emptyParts: PartType[] = []
  85. const msgParts = createMemo(() => data.store.part[props.message.id] ?? emptyParts)
  86. const lastTextPart = createMemo(() => {
  87. const parts = msgParts()
  88. for (let i = parts.length - 1; i >= 0; i--) {
  89. const part = parts[i]
  90. if (part?.type === "text") return part as TextPart
  91. }
  92. return undefined
  93. })
  94. const filteredParts = createMemo(() => {
  95. let parts = msgParts()
  96. if (props.hideReasoning) {
  97. parts = parts.filter((part) => part?.type !== "reasoning")
  98. }
  99. if (!props.hideResponsePart) return parts
  100. const responsePartId = props.responsePartId
  101. if (!responsePartId) return parts
  102. if (responsePartId !== lastTextPart()?.id) return parts
  103. return parts.filter((part) => part?.id !== responsePartId)
  104. })
  105. return <Message message={props.message} parts={filteredParts()} />
  106. }
  107. export function SessionTurn(
  108. props: ParentProps<{
  109. sessionID: string
  110. sessionTitle?: string
  111. messageID: string
  112. lastUserMessageID?: string
  113. stepsExpanded?: boolean
  114. onStepsExpandedToggle?: () => void
  115. onUserInteracted?: () => void
  116. classes?: {
  117. root?: string
  118. content?: string
  119. container?: string
  120. }
  121. }>,
  122. ) {
  123. const data = useData()
  124. const diffComponent = useDiffComponent()
  125. const emptyMessages: MessageType[] = []
  126. const emptyParts: PartType[] = []
  127. const emptyFiles: FilePart[] = []
  128. const emptyAssistant: AssistantMessage[] = []
  129. const emptyPermissions: PermissionRequest[] = []
  130. const emptyPermissionParts: { part: ToolPart; message: AssistantMessage }[] = []
  131. const idle = { type: "idle" as const }
  132. const allMessages = createMemo(() => data.store.message[props.sessionID] ?? emptyMessages)
  133. const messageIndex = createMemo(() => {
  134. const messages = allMessages()
  135. const result = Binary.search(messages, props.messageID, (m) => m.id)
  136. if (!result.found) return -1
  137. const msg = messages[result.index]
  138. if (msg.role !== "user") return -1
  139. return result.index
  140. })
  141. const message = createMemo(() => {
  142. const index = messageIndex()
  143. if (index < 0) return undefined
  144. const msg = allMessages()[index]
  145. if (!msg || msg.role !== "user") return undefined
  146. return msg
  147. })
  148. const lastUserMessageID = createMemo(() => {
  149. if (props.lastUserMessageID) return props.lastUserMessageID
  150. const messages = allMessages()
  151. for (let i = messages.length - 1; i >= 0; i--) {
  152. const msg = messages[i]
  153. if (msg?.role === "user") return msg.id
  154. }
  155. return undefined
  156. })
  157. const isLastUserMessage = createMemo(() => props.messageID === lastUserMessageID())
  158. const parts = createMemo(() => {
  159. const msg = message()
  160. if (!msg) return emptyParts
  161. return data.store.part[msg.id] ?? emptyParts
  162. })
  163. const attachmentParts = createMemo(() => {
  164. const msgParts = parts()
  165. if (msgParts.length === 0) return emptyFiles
  166. return msgParts.filter((part) => isAttachment(part)) as FilePart[]
  167. })
  168. const stickyParts = createMemo(() => {
  169. const msgParts = parts()
  170. if (msgParts.length === 0) return emptyParts
  171. if (attachmentParts().length === 0) return msgParts
  172. return msgParts.filter((part) => !isAttachment(part))
  173. })
  174. const assistantMessages = createMemo(
  175. () => {
  176. const msg = message()
  177. if (!msg) return emptyAssistant
  178. const messages = allMessages()
  179. const index = messageIndex()
  180. if (index < 0) return emptyAssistant
  181. const result: AssistantMessage[] = []
  182. for (let i = index + 1; i < messages.length; i++) {
  183. const item = messages[i]
  184. if (!item) continue
  185. if (item.role === "user") break
  186. if (item.role === "assistant" && item.parentID === msg.id) result.push(item as AssistantMessage)
  187. }
  188. return result
  189. },
  190. emptyAssistant,
  191. { equals: same },
  192. )
  193. const lastAssistantMessage = createMemo(() => assistantMessages().at(-1))
  194. const error = createMemo(() => assistantMessages().find((m) => m.error)?.error)
  195. const lastTextPart = createMemo(() => {
  196. const msgs = assistantMessages()
  197. for (let mi = msgs.length - 1; mi >= 0; mi--) {
  198. const msgParts = data.store.part[msgs[mi].id] ?? emptyParts
  199. for (let pi = msgParts.length - 1; pi >= 0; pi--) {
  200. const part = msgParts[pi]
  201. if (part?.type === "text") return part as TextPart
  202. }
  203. }
  204. return undefined
  205. })
  206. const hasSteps = createMemo(() => {
  207. for (const m of assistantMessages()) {
  208. const msgParts = data.store.part[m.id]
  209. if (!msgParts) continue
  210. for (const p of msgParts) {
  211. if (p?.type === "tool") return true
  212. }
  213. }
  214. return false
  215. })
  216. const permissions = createMemo(() => data.store.permission?.[props.sessionID] ?? emptyPermissions)
  217. const permissionCount = createMemo(() => permissions().length)
  218. const nextPermission = createMemo(() => permissions()[0])
  219. const permissionParts = createMemo(() => {
  220. if (props.stepsExpanded) return emptyPermissionParts
  221. const next = nextPermission()
  222. if (!next || !next.tool) return emptyPermissionParts
  223. const message = assistantMessages().findLast((m) => m.id === next.tool!.messageID)
  224. if (!message) return emptyPermissionParts
  225. const parts = data.store.part[message.id] ?? emptyParts
  226. for (const part of parts) {
  227. if (part?.type !== "tool") continue
  228. const tool = part as ToolPart
  229. if (tool.callID === next.tool?.callID) return [{ part: tool, message }]
  230. }
  231. return emptyPermissionParts
  232. })
  233. const shellModePart = createMemo(() => {
  234. const p = parts()
  235. if (!p.every((part) => part?.type === "text" && part?.synthetic)) return
  236. const msgs = assistantMessages()
  237. if (msgs.length !== 1) return
  238. const msgParts = data.store.part[msgs[0].id] ?? emptyParts
  239. if (msgParts.length !== 1) return
  240. const assistantPart = msgParts[0]
  241. if (assistantPart?.type === "tool" && assistantPart.tool === "bash") return assistantPart
  242. })
  243. const isShellMode = createMemo(() => !!shellModePart())
  244. const rawStatus = createMemo(() => {
  245. const msgs = assistantMessages()
  246. let last: PartType | undefined
  247. let currentTask: ToolPart | undefined
  248. for (let mi = msgs.length - 1; mi >= 0; mi--) {
  249. const msgParts = data.store.part[msgs[mi].id] ?? emptyParts
  250. for (let pi = msgParts.length - 1; pi >= 0; pi--) {
  251. const part = msgParts[pi]
  252. if (!part) continue
  253. if (!last) last = part
  254. if (
  255. part.type === "tool" &&
  256. part.tool === "task" &&
  257. part.state &&
  258. "metadata" in part.state &&
  259. part.state.metadata?.sessionId &&
  260. part.state.status === "running"
  261. ) {
  262. currentTask = part as ToolPart
  263. break
  264. }
  265. }
  266. if (currentTask) break
  267. }
  268. const taskSessionId =
  269. currentTask?.state && "metadata" in currentTask.state
  270. ? (currentTask.state.metadata?.sessionId as string | undefined)
  271. : undefined
  272. if (taskSessionId) {
  273. const taskMessages = data.store.message[taskSessionId] ?? emptyMessages
  274. for (let mi = taskMessages.length - 1; mi >= 0; mi--) {
  275. const msg = taskMessages[mi]
  276. if (!msg || msg.role !== "assistant") continue
  277. const msgParts = data.store.part[msg.id] ?? emptyParts
  278. for (let pi = msgParts.length - 1; pi >= 0; pi--) {
  279. const part = msgParts[pi]
  280. if (part) return computeStatusFromPart(part)
  281. }
  282. }
  283. }
  284. return computeStatusFromPart(last)
  285. })
  286. const status = createMemo(() => data.store.session_status[props.sessionID] ?? idle)
  287. const working = createMemo(() => status().type !== "idle" && isLastUserMessage())
  288. const retry = createMemo(() => {
  289. const s = status()
  290. if (s.type !== "retry") return
  291. return s
  292. })
  293. const response = createMemo(() => lastTextPart()?.text)
  294. const responsePartId = createMemo(() => lastTextPart()?.id)
  295. const hasDiffs = createMemo(() => (data.store.session_diff?.[props.sessionID]?.length ?? 0) > 0)
  296. const hideResponsePart = createMemo(() => !working() && !!responsePartId())
  297. const [rootRef, setRootRef] = createSignal<HTMLDivElement | undefined>()
  298. const [stickyRef, setStickyRef] = createSignal<HTMLDivElement | undefined>()
  299. const updateStickyHeight = (height: number) => {
  300. const root = rootRef()
  301. if (!root) return
  302. const next = Math.ceil(height)
  303. root.style.setProperty("--session-turn-sticky-height", `${next}px`)
  304. }
  305. function duration() {
  306. const msg = message()
  307. if (!msg) return ""
  308. const completed = lastAssistantMessage()?.time.completed
  309. const from = DateTime.fromMillis(msg.time.created)
  310. const to = completed ? DateTime.fromMillis(completed) : DateTime.now()
  311. const interval = Interval.fromDateTimes(from, to)
  312. const unit: DurationUnit[] = interval.length("seconds") > 60 ? ["minutes", "seconds"] : ["seconds"]
  313. return interval.toDuration(unit).normalize().toHuman({
  314. notation: "compact",
  315. unitDisplay: "narrow",
  316. compactDisplay: "short",
  317. showZeros: false,
  318. })
  319. }
  320. const autoScroll = createAutoScroll({
  321. working,
  322. onUserInteracted: props.onUserInteracted,
  323. overflowAnchor: "auto",
  324. })
  325. createResizeObserver(
  326. () => stickyRef(),
  327. ({ height }) => {
  328. updateStickyHeight(height)
  329. },
  330. )
  331. createEffect(() => {
  332. const root = rootRef()
  333. if (!root) return
  334. const sticky = stickyRef()
  335. if (!sticky) {
  336. root.style.setProperty("--session-turn-sticky-height", "0px")
  337. return
  338. }
  339. updateStickyHeight(sticky.getBoundingClientRect().height)
  340. })
  341. const diffInit = 20
  342. const diffBatch = 20
  343. const [store, setStore] = createStore({
  344. retrySeconds: 0,
  345. diffsOpen: [] as string[],
  346. diffLimit: diffInit,
  347. status: rawStatus(),
  348. duration: duration(),
  349. })
  350. createEffect(
  351. on(
  352. () => message()?.id,
  353. () => {
  354. setStore("diffsOpen", [])
  355. setStore("diffLimit", diffInit)
  356. },
  357. { defer: true },
  358. ),
  359. )
  360. createEffect(() => {
  361. const r = retry()
  362. if (!r) {
  363. setStore("retrySeconds", 0)
  364. return
  365. }
  366. const updateSeconds = () => {
  367. const next = r.next
  368. if (next) setStore("retrySeconds", Math.max(0, Math.round((next - Date.now()) / 1000)))
  369. }
  370. updateSeconds()
  371. const timer = setInterval(updateSeconds, 1000)
  372. onCleanup(() => clearInterval(timer))
  373. })
  374. createEffect(() => {
  375. const timer = setInterval(() => {
  376. setStore("duration", duration())
  377. }, 1000)
  378. onCleanup(() => clearInterval(timer))
  379. })
  380. createEffect(
  381. on(permissionCount, (count, prev) => {
  382. if (!count) return
  383. if (prev !== undefined && count <= prev) return
  384. autoScroll.forceScrollToBottom()
  385. }),
  386. )
  387. let lastStatusChange = Date.now()
  388. let statusTimeout: number | undefined
  389. createEffect(() => {
  390. const newStatus = rawStatus()
  391. if (newStatus === store.status || !newStatus) return
  392. const timeSinceLastChange = Date.now() - lastStatusChange
  393. if (timeSinceLastChange >= 2500) {
  394. setStore("status", newStatus)
  395. lastStatusChange = Date.now()
  396. if (statusTimeout) {
  397. clearTimeout(statusTimeout)
  398. statusTimeout = undefined
  399. }
  400. } else {
  401. if (statusTimeout) clearTimeout(statusTimeout)
  402. statusTimeout = setTimeout(() => {
  403. setStore("status", rawStatus())
  404. lastStatusChange = Date.now()
  405. statusTimeout = undefined
  406. }, 2500 - timeSinceLastChange) as unknown as number
  407. }
  408. })
  409. return (
  410. <div data-component="session-turn" class={props.classes?.root} ref={setRootRef}>
  411. <div
  412. ref={autoScroll.scrollRef}
  413. onScroll={autoScroll.handleScroll}
  414. data-slot="session-turn-content"
  415. class={props.classes?.content}
  416. >
  417. <div onClick={autoScroll.handleInteraction}>
  418. <Show when={message()}>
  419. {(msg) => (
  420. <div
  421. ref={autoScroll.contentRef}
  422. data-message={msg().id}
  423. data-slot="session-turn-message-container"
  424. class={props.classes?.container}
  425. >
  426. <Switch>
  427. <Match when={isShellMode()}>
  428. <Part part={shellModePart()!} message={msg()} defaultOpen />
  429. </Match>
  430. <Match when={true}>
  431. <Show when={attachmentParts().length > 0}>
  432. <div data-slot="session-turn-attachments">
  433. <Message message={msg()} parts={attachmentParts()} />
  434. </div>
  435. </Show>
  436. <div data-slot="session-turn-sticky" ref={setStickyRef}>
  437. {/* User Message */}
  438. <div data-slot="session-turn-message-content">
  439. <Message message={msg()} parts={stickyParts()} />
  440. </div>
  441. {/* Trigger (sticky) */}
  442. <Show when={working() || hasSteps()}>
  443. <div data-slot="session-turn-response-trigger">
  444. <Button
  445. data-expandable={assistantMessages().length > 0}
  446. data-slot="session-turn-collapsible-trigger-content"
  447. variant="ghost"
  448. size="small"
  449. onClick={props.onStepsExpandedToggle ?? (() => {})}
  450. >
  451. <Show when={working()}>
  452. <Spinner />
  453. </Show>
  454. <Switch>
  455. <Match when={retry()}>
  456. <span data-slot="session-turn-retry-message">
  457. {(() => {
  458. const r = retry()
  459. if (!r) return ""
  460. return r.message.length > 60 ? r.message.slice(0, 60) + "..." : r.message
  461. })()}
  462. </span>
  463. <span data-slot="session-turn-retry-seconds">
  464. · retrying {store.retrySeconds > 0 ? `in ${store.retrySeconds}s ` : ""}
  465. </span>
  466. <span data-slot="session-turn-retry-attempt">(#{retry()?.attempt})</span>
  467. </Match>
  468. <Match when={working()}>{store.status ?? "Considering next steps"}</Match>
  469. <Match when={props.stepsExpanded}>Hide steps</Match>
  470. <Match when={!props.stepsExpanded}>Show steps</Match>
  471. </Switch>
  472. <span>·</span>
  473. <span>{store.duration}</span>
  474. <Show when={assistantMessages().length > 0}>
  475. <Icon name="chevron-grabber-vertical" size="small" />
  476. </Show>
  477. </Button>
  478. </div>
  479. </Show>
  480. </div>
  481. {/* Response */}
  482. <Show when={props.stepsExpanded && assistantMessages().length > 0}>
  483. <div data-slot="session-turn-collapsible-content-inner">
  484. <For each={assistantMessages()}>
  485. {(assistantMessage) => (
  486. <AssistantMessageItem
  487. message={assistantMessage}
  488. responsePartId={responsePartId()}
  489. hideResponsePart={hideResponsePart()}
  490. hideReasoning={!working()}
  491. />
  492. )}
  493. </For>
  494. <Show when={error()}>
  495. <Card variant="error" class="error-card">
  496. {error()?.data?.message as string}
  497. </Card>
  498. </Show>
  499. </div>
  500. </Show>
  501. <Show when={!props.stepsExpanded && permissionParts().length > 0}>
  502. <div data-slot="session-turn-permission-parts">
  503. <For each={permissionParts()}>
  504. {({ part, message }) => <Part part={part} message={message} />}
  505. </For>
  506. </div>
  507. </Show>
  508. {/* Response */}
  509. <Show when={!working() && (response() || hasDiffs())}>
  510. <div data-slot="session-turn-summary-section">
  511. <div data-slot="session-turn-summary-header">
  512. <h2 data-slot="session-turn-summary-title">Response</h2>
  513. <Markdown
  514. data-slot="session-turn-markdown"
  515. data-diffs={hasDiffs()}
  516. text={response() ?? ""}
  517. cacheKey={responsePartId()}
  518. />
  519. </div>
  520. <Accordion
  521. data-slot="session-turn-accordion"
  522. multiple
  523. value={store.diffsOpen}
  524. onChange={(value) => {
  525. if (!Array.isArray(value)) return
  526. setStore("diffsOpen", value)
  527. }}
  528. >
  529. <For each={(data.store.session_diff?.[props.sessionID] ?? []).slice(0, store.diffLimit)}>
  530. {(diff) => (
  531. <Accordion.Item value={diff.file}>
  532. <StickyAccordionHeader>
  533. <Accordion.Trigger>
  534. <div data-slot="session-turn-accordion-trigger-content">
  535. <div data-slot="session-turn-file-info">
  536. <FileIcon
  537. node={{ path: diff.file, type: "file" }}
  538. data-slot="session-turn-file-icon"
  539. />
  540. <div data-slot="session-turn-file-path">
  541. <Show when={diff.file.includes("/")}>
  542. <span data-slot="session-turn-directory">
  543. {getDirectory(diff.file)}&lrm;
  544. </span>
  545. </Show>
  546. <span data-slot="session-turn-filename">{getFilename(diff.file)}</span>
  547. </div>
  548. </div>
  549. <div data-slot="session-turn-accordion-actions">
  550. <DiffChanges changes={diff} />
  551. <Icon name="chevron-grabber-vertical" size="small" />
  552. </div>
  553. </div>
  554. </Accordion.Trigger>
  555. </StickyAccordionHeader>
  556. <Accordion.Content data-slot="session-turn-accordion-content">
  557. <Show when={store.diffsOpen.includes(diff.file!)}>
  558. <Dynamic
  559. component={diffComponent}
  560. before={{
  561. name: diff.file!,
  562. contents: diff.before!,
  563. }}
  564. after={{
  565. name: diff.file!,
  566. contents: diff.after!,
  567. }}
  568. />
  569. </Show>
  570. </Accordion.Content>
  571. </Accordion.Item>
  572. )}
  573. </For>
  574. </Accordion>
  575. <Show when={(data.store.session_diff?.[props.sessionID]?.length ?? 0) > store.diffLimit}>
  576. <Button
  577. data-slot="session-turn-accordion-more"
  578. variant="ghost"
  579. size="small"
  580. onClick={() => {
  581. const total = data.store.session_diff?.[props.sessionID]?.length ?? 0
  582. setStore("diffLimit", (limit) => {
  583. const next = limit + diffBatch
  584. if (next > total) return total
  585. return next
  586. })
  587. }}
  588. >
  589. Show more changes (
  590. {(data.store.session_diff?.[props.sessionID]?.length ?? 0) - store.diffLimit})
  591. </Button>
  592. </Show>
  593. </div>
  594. </Show>
  595. <Show when={error() && !props.stepsExpanded}>
  596. <Card variant="error" class="error-card">
  597. {error()?.data?.message as string}
  598. </Card>
  599. </Show>
  600. </Match>
  601. </Switch>
  602. </div>
  603. )}
  604. </Show>
  605. {props.children}
  606. </div>
  607. </div>
  608. </div>
  609. )
  610. }