session-turn.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. import {
  2. AssistantMessage,
  3. type SnapshotFileDiff,
  4. Message as MessageType,
  5. Part as PartType,
  6. } from "@opencode-ai/sdk/v2/client"
  7. import type { SessionStatus } from "@opencode-ai/sdk/v2"
  8. import { useData } from "../context"
  9. import { useFileComponent } from "../context/file"
  10. import { Binary } from "@opencode-ai/shared/util/binary"
  11. import { getDirectory, getFilename } from "@opencode-ai/shared/util/path"
  12. import { createEffect, createMemo, createSignal, For, on, ParentProps, Show } from "solid-js"
  13. import { createStore } from "solid-js/store"
  14. import { Dynamic } from "solid-js/web"
  15. import { AssistantParts, Message, MessageDivider, PART_MAPPING, type UserActions } from "./message-part"
  16. import { Card } from "./card"
  17. import { Accordion } from "./accordion"
  18. import { StickyAccordionHeader } from "./sticky-accordion-header"
  19. import { DiffChanges } from "./diff-changes"
  20. import { Icon } from "./icon"
  21. import { TextShimmer } from "./text-shimmer"
  22. import { SessionRetry } from "./session-retry"
  23. import { TextReveal } from "./text-reveal"
  24. import { createAutoScroll } from "../hooks"
  25. import { useI18n } from "../context/i18n"
  26. import { normalize } from "./session-diff"
  27. function record(value: unknown): value is Record<string, unknown> {
  28. return !!value && typeof value === "object" && !Array.isArray(value)
  29. }
  30. function unwrap(message: string) {
  31. const text = message.replace(/^Error:\s*/, "").trim()
  32. const parse = (value: string) => {
  33. try {
  34. return JSON.parse(value) as unknown
  35. } catch {
  36. return undefined
  37. }
  38. }
  39. const read = (value: string) => {
  40. const first = parse(value)
  41. if (typeof first !== "string") return first
  42. return parse(first.trim())
  43. }
  44. let json = read(text)
  45. if (json === undefined) {
  46. const start = text.indexOf("{")
  47. const end = text.lastIndexOf("}")
  48. if (start !== -1 && end > start) {
  49. json = read(text.slice(start, end + 1))
  50. }
  51. }
  52. if (!record(json)) return message
  53. const err = record(json.error) ? json.error : undefined
  54. if (err) {
  55. const type = typeof err.type === "string" ? err.type : undefined
  56. const msg = typeof err.message === "string" ? err.message : undefined
  57. if (type && msg) return `${type}: ${msg}`
  58. if (msg) return msg
  59. if (type) return type
  60. const code = typeof err.code === "string" ? err.code : undefined
  61. if (code) return code
  62. }
  63. const msg = typeof json.message === "string" ? json.message : undefined
  64. if (msg) return msg
  65. const reason = typeof json.error === "string" ? json.error : undefined
  66. if (reason) return reason
  67. return message
  68. }
  69. function same<T>(a: readonly T[], b: readonly T[]) {
  70. if (a === b) return true
  71. if (a.length !== b.length) return false
  72. return a.every((x, i) => x === b[i])
  73. }
  74. function list<T>(value: T[] | undefined | null, fallback: T[]) {
  75. if (Array.isArray(value)) return value
  76. return fallback
  77. }
  78. const hidden = new Set(["todowrite"])
  79. function partState(part: PartType, showReasoningSummaries: boolean) {
  80. if (part.type === "tool") {
  81. if (hidden.has(part.tool)) return
  82. if (part.tool === "question" && (part.state.status === "pending" || part.state.status === "running")) return
  83. return "visible" as const
  84. }
  85. if (part.type === "text") return part.text?.trim() ? ("visible" as const) : undefined
  86. if (part.type === "reasoning") {
  87. if (showReasoningSummaries && part.text?.trim()) return "visible" as const
  88. return
  89. }
  90. if (PART_MAPPING[part.type]) return "visible" as const
  91. return
  92. }
  93. function clean(value: string) {
  94. return value
  95. .replace(/`([^`]+)`/g, "$1")
  96. .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
  97. .replace(/[*_~]+/g, "")
  98. .trim()
  99. }
  100. function heading(text: string) {
  101. const markdown = text.replace(/\r\n?/g, "\n")
  102. const html = markdown.match(/<h[1-6][^>]*>([\s\S]*?)<\/h[1-6]>/i)
  103. if (html?.[1]) {
  104. const value = clean(html[1].replace(/<[^>]+>/g, " "))
  105. if (value) return value
  106. }
  107. const atx = markdown.match(/^\s{0,3}#{1,6}[ \t]+(.+?)(?:[ \t]+#+[ \t]*)?$/m)
  108. if (atx?.[1]) {
  109. const value = clean(atx[1])
  110. if (value) return value
  111. }
  112. const setext = markdown.match(/^([^\n]+)\n(?:=+|-+)\s*$/m)
  113. if (setext?.[1]) {
  114. const value = clean(setext[1])
  115. if (value) return value
  116. }
  117. const strong = markdown.match(/^\s*(?:\*\*|__)(.+?)(?:\*\*|__)\s*$/m)
  118. if (strong?.[1]) {
  119. const value = clean(strong[1])
  120. if (value) return value
  121. }
  122. }
  123. export function SessionTurn(
  124. props: ParentProps<{
  125. sessionID: string
  126. messageID: string
  127. messages?: MessageType[]
  128. actions?: UserActions
  129. showReasoningSummaries?: boolean
  130. shellToolDefaultOpen?: boolean
  131. editToolDefaultOpen?: boolean
  132. active?: boolean
  133. status?: SessionStatus
  134. onUserInteracted?: () => void
  135. classes?: {
  136. root?: string
  137. content?: string
  138. container?: string
  139. }
  140. }>,
  141. ) {
  142. const data = useData()
  143. const i18n = useI18n()
  144. const fileComponent = useFileComponent()
  145. const emptyMessages: MessageType[] = []
  146. const emptyParts: PartType[] = []
  147. const emptyAssistant: AssistantMessage[] = []
  148. const emptyDiffs: SnapshotFileDiff[] = []
  149. const idle = { type: "idle" as const }
  150. const allMessages = createMemo(() => props.messages ?? list(data.store.message?.[props.sessionID], emptyMessages))
  151. const messageIndex = createMemo(() => {
  152. const messages = allMessages() ?? emptyMessages
  153. const result = Binary.search(messages, props.messageID, (m) => m.id)
  154. const index = result.found ? result.index : messages.findIndex((m) => m.id === props.messageID)
  155. if (index < 0) return -1
  156. const msg = messages[index]
  157. if (!msg || msg.role !== "user") return -1
  158. return index
  159. })
  160. const message = createMemo(() => {
  161. const index = messageIndex()
  162. if (index < 0) return undefined
  163. const messages = allMessages() ?? emptyMessages
  164. const msg = messages[index]
  165. if (!msg || msg.role !== "user") return undefined
  166. return msg
  167. })
  168. const pending = createMemo(() => {
  169. if (typeof props.active === "boolean") return
  170. const messages = allMessages() ?? emptyMessages
  171. return messages.findLast(
  172. (item): item is AssistantMessage => item.role === "assistant" && typeof item.time.completed !== "number",
  173. )
  174. })
  175. const pendingUser = createMemo(() => {
  176. const item = pending()
  177. if (!item?.parentID) return
  178. const messages = allMessages() ?? emptyMessages
  179. const result = Binary.search(messages, item.parentID, (m) => m.id)
  180. const msg = result.found ? messages[result.index] : messages.find((m) => m.id === item.parentID)
  181. if (!msg || msg.role !== "user") return
  182. return msg
  183. })
  184. const active = createMemo(() => {
  185. if (typeof props.active === "boolean") return props.active
  186. const msg = message()
  187. const parent = pendingUser()
  188. if (!msg || !parent) return false
  189. return parent.id === msg.id
  190. })
  191. const parts = createMemo(() => {
  192. const msg = message()
  193. if (!msg) return emptyParts
  194. return list(data.store.part?.[msg.id], emptyParts)
  195. })
  196. const compaction = createMemo(() => parts().find((part) => part.type === "compaction"))
  197. const diffs = createMemo(() => {
  198. const files = message()?.summary?.diffs
  199. if (!files?.length) return emptyDiffs
  200. const seen = new Set<string>()
  201. return files
  202. .reduceRight<SnapshotFileDiff[]>((result, diff) => {
  203. if (seen.has(diff.file)) return result
  204. seen.add(diff.file)
  205. result.push(diff)
  206. return result
  207. }, [])
  208. .reverse()
  209. })
  210. const MAX_FILES = 10
  211. const edited = createMemo(() => diffs().length)
  212. const [state, setState] = createStore({
  213. showAll: false,
  214. expanded: [] as string[],
  215. })
  216. const showAll = () => state.showAll
  217. const expanded = () => state.expanded
  218. const overflow = createMemo(() => Math.max(0, edited() - MAX_FILES))
  219. const visible = createMemo(() => (showAll() ? diffs() : diffs().slice(0, MAX_FILES)))
  220. const toggleAll = () => {
  221. autoScroll.pause()
  222. setState("showAll", !showAll())
  223. }
  224. const assistantMessages = createMemo(
  225. () => {
  226. const msg = message()
  227. if (!msg) return emptyAssistant
  228. const messages = allMessages() ?? emptyMessages
  229. const index = messageIndex()
  230. if (index < 0) return emptyAssistant
  231. const result: AssistantMessage[] = []
  232. for (let i = index + 1; i < messages.length; i++) {
  233. const item = messages[i]
  234. if (!item) continue
  235. if (item.role === "user") break
  236. if (item.role === "assistant" && item.parentID === msg.id) result.push(item as AssistantMessage)
  237. }
  238. return result
  239. },
  240. emptyAssistant,
  241. { equals: same },
  242. )
  243. const interrupted = createMemo(() => assistantMessages().some((m) => m.error?.name === "MessageAbortedError"))
  244. const divider = createMemo(() => {
  245. if (compaction()) return i18n.t("ui.messagePart.compaction")
  246. if (interrupted()) return i18n.t("ui.message.interrupted")
  247. return ""
  248. })
  249. const error = createMemo(
  250. () => assistantMessages().find((m) => m.error && m.error.name !== "MessageAbortedError")?.error,
  251. )
  252. const showAssistantCopyPartID = createMemo(() => {
  253. const messages = assistantMessages()
  254. for (let i = messages.length - 1; i >= 0; i--) {
  255. const message = messages[i]
  256. if (!message) continue
  257. const parts = list(data.store.part?.[message.id], emptyParts)
  258. for (let j = parts.length - 1; j >= 0; j--) {
  259. const part = parts[j]
  260. if (!part || part.type !== "text" || !part.text?.trim()) continue
  261. return part.id
  262. }
  263. }
  264. return undefined
  265. })
  266. const errorText = createMemo(() => {
  267. const msg = error()?.data?.message
  268. if (typeof msg === "string") return unwrap(msg)
  269. if (msg === undefined || msg === null) return ""
  270. // oxlint-disable-next-line no-base-to-string -- msg is unknown from error data, coercion is intentional
  271. return unwrap(String(msg))
  272. })
  273. const status = createMemo(() => {
  274. if (props.status !== undefined) return props.status
  275. if (typeof props.active === "boolean" && !props.active) return idle
  276. return data.store.session_status[props.sessionID] ?? idle
  277. })
  278. const working = createMemo(() => status().type !== "idle" && active())
  279. const showReasoningSummaries = createMemo(() => props.showReasoningSummaries ?? true)
  280. const assistantCopyPartID = createMemo(() => {
  281. if (working()) return null
  282. return showAssistantCopyPartID() ?? null
  283. })
  284. const turnDurationMs = createMemo(() => {
  285. const start = message()?.time.created
  286. if (typeof start !== "number") return undefined
  287. const end = assistantMessages().reduce<number | undefined>((max, item) => {
  288. const completed = item.time.completed
  289. if (typeof completed !== "number") return max
  290. if (max === undefined) return completed
  291. return Math.max(max, completed)
  292. }, undefined)
  293. if (typeof end !== "number") return undefined
  294. if (end < start) return undefined
  295. return end - start
  296. })
  297. const assistantDerived = createMemo(() => {
  298. let visible = 0
  299. let reason: string | undefined
  300. const show = showReasoningSummaries()
  301. for (const message of assistantMessages()) {
  302. for (const part of list(data.store.part?.[message.id], emptyParts)) {
  303. if (partState(part, show) === "visible") {
  304. visible++
  305. }
  306. if (part.type === "reasoning" && part.text) {
  307. const h = heading(part.text)
  308. if (h) reason = h
  309. }
  310. }
  311. }
  312. return { visible, reason }
  313. })
  314. const assistantVisible = createMemo(() => assistantDerived().visible)
  315. const reasoningHeading = createMemo(() => assistantDerived().reason)
  316. const showThinking = createMemo(() => {
  317. if (!working() || !!error()) return false
  318. if (status().type === "retry") return false
  319. if (showReasoningSummaries()) return assistantVisible() === 0
  320. return true
  321. })
  322. const autoScroll = createAutoScroll({
  323. working,
  324. onUserInteracted: props.onUserInteracted,
  325. overflowAnchor: "dynamic",
  326. })
  327. return (
  328. <div data-component="session-turn" class={props.classes?.root}>
  329. <div
  330. ref={autoScroll.scrollRef}
  331. onScroll={autoScroll.handleScroll}
  332. data-slot="session-turn-content"
  333. class={props.classes?.content}
  334. >
  335. <div onClick={autoScroll.handleInteraction}>
  336. <Show when={message()}>
  337. <div
  338. ref={autoScroll.contentRef}
  339. data-message={message()!.id}
  340. data-slot="session-turn-message-container"
  341. class={props.classes?.container}
  342. >
  343. <div data-slot="session-turn-message-content" aria-live="off">
  344. <Message message={message()!} parts={parts()} actions={props.actions} />
  345. </div>
  346. <Show when={divider()}>
  347. <div data-slot="session-turn-compaction">
  348. <MessageDivider label={divider()} />
  349. </div>
  350. </Show>
  351. <Show when={assistantMessages().length > 0}>
  352. <div data-slot="session-turn-assistant-content" aria-hidden={working()}>
  353. <AssistantParts
  354. messages={assistantMessages()}
  355. showAssistantCopyPartID={assistantCopyPartID()}
  356. turnDurationMs={turnDurationMs()}
  357. working={working()}
  358. showReasoningSummaries={showReasoningSummaries()}
  359. shellToolDefaultOpen={props.shellToolDefaultOpen}
  360. editToolDefaultOpen={props.editToolDefaultOpen}
  361. />
  362. </div>
  363. </Show>
  364. <Show when={showThinking()}>
  365. <div data-slot="session-turn-thinking">
  366. <TextShimmer text={i18n.t("ui.sessionTurn.status.thinking")} />
  367. <Show when={!showReasoningSummaries()}>
  368. <TextReveal
  369. text={reasoningHeading()}
  370. class="session-turn-thinking-heading"
  371. travel={25}
  372. duration={700}
  373. />
  374. </Show>
  375. </div>
  376. </Show>
  377. <SessionRetry status={status()} show={active()} />
  378. <Show when={edited() > 0 && !working()}>
  379. <div
  380. data-slot="session-turn-diffs"
  381. data-component="session-turn-diffs-group"
  382. data-show-all={showAll() || undefined}
  383. >
  384. <div data-slot="session-turn-diffs-header">
  385. <span data-slot="session-turn-diffs-label">
  386. {edited()} {i18n.t("ui.sessionTurn.diffs.changed")}{" "}
  387. {i18n.t(edited() === 1 ? "ui.common.file.one" : "ui.common.file.other")}
  388. </span>
  389. <DiffChanges changes={diffs()} />
  390. <Show when={overflow() > 0}>
  391. <span data-slot="session-turn-diffs-toggle" onClick={toggleAll}>
  392. {showAll() ? i18n.t("ui.sessionTurn.diffs.showLess") : i18n.t("ui.sessionTurn.diffs.showAll")}
  393. </span>
  394. </Show>
  395. </div>
  396. <div data-component="session-turn-diffs-content">
  397. <Accordion
  398. multiple
  399. style={{ "--sticky-accordion-offset": "44px" }}
  400. value={expanded()}
  401. onChange={(value) => setState("expanded", Array.isArray(value) ? value : value ? [value] : [])}
  402. >
  403. <For each={visible()}>
  404. {(diff) => {
  405. const view = normalize(diff)
  406. const active = createMemo(() => expanded().includes(diff.file))
  407. const [shown, setShown] = createSignal(false)
  408. createEffect(
  409. on(
  410. active,
  411. (value) => {
  412. if (!value) {
  413. setShown(false)
  414. return
  415. }
  416. requestAnimationFrame(() => {
  417. if (!active()) return
  418. setShown(true)
  419. })
  420. },
  421. { defer: true },
  422. ),
  423. )
  424. return (
  425. <Accordion.Item value={diff.file}>
  426. <StickyAccordionHeader>
  427. <Accordion.Trigger>
  428. <div data-slot="session-turn-diff-trigger">
  429. <span data-slot="session-turn-diff-path">
  430. <Show when={diff.file.includes("/")}>
  431. <span data-slot="session-turn-diff-directory">
  432. {`\u202A${getDirectory(diff.file)}\u202C`}
  433. </span>
  434. </Show>
  435. <span data-slot="session-turn-diff-filename">{getFilename(diff.file)}</span>
  436. </span>
  437. <div data-slot="session-turn-diff-meta">
  438. <span data-slot="session-turn-diff-changes">
  439. <DiffChanges changes={diff} />
  440. </span>
  441. <span data-slot="session-turn-diff-chevron">
  442. <Icon name="chevron-down" size="small" />
  443. </span>
  444. </div>
  445. </div>
  446. </Accordion.Trigger>
  447. </StickyAccordionHeader>
  448. <Accordion.Content>
  449. <Show when={shown()}>
  450. <div data-slot="session-turn-diff-view" data-scrollable>
  451. <Dynamic component={fileComponent} mode="diff" fileDiff={view.fileDiff} />
  452. </div>
  453. </Show>
  454. </Accordion.Content>
  455. </Accordion.Item>
  456. )
  457. }}
  458. </For>
  459. </Accordion>
  460. <Show when={!showAll() && overflow() > 0}>
  461. <div data-slot="session-turn-diffs-more" onClick={toggleAll}>
  462. {i18n.t("ui.sessionTurn.diffs.more", { count: String(overflow()) })}
  463. </div>
  464. </Show>
  465. </div>
  466. </div>
  467. </Show>
  468. <Show when={error()}>
  469. <Card variant="error" class="error-card">
  470. {errorText()}
  471. </Card>
  472. </Show>
  473. </div>
  474. </Show>
  475. {props.children}
  476. </div>
  477. </div>
  478. </div>
  479. )
  480. }