scrollback.surface.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Retained streaming append logic for direct-mode scrollback.
  2. //
  3. // Static entries are rendered through `scrollback.writer.tsx`. This file only
  4. // keeps the retained-surface machinery needed for streaming assistant,
  5. // reasoning, and tool progress entries that need stable markdown/code layout
  6. // while content is still arriving.
  7. import {
  8. CodeRenderable,
  9. MarkdownRenderable,
  10. TextRenderable,
  11. getTreeSitterClient,
  12. type TreeSitterClient,
  13. type CliRenderer,
  14. type ScrollbackSurface,
  15. } from "@opentui/core"
  16. import { entryBody, entryCanStream, entryDone, entryFlags } from "./entry.body"
  17. import { entryColor, entryLook, entrySyntax } from "./scrollback.shared"
  18. import { turnSummaryCommit } from "./turn-summary"
  19. import { entryWriter, sameEntryGroup, separatorRows, spacerWriter, turnSummaryWriter } from "./scrollback.writer"
  20. import { type RunTheme } from "./theme"
  21. import type { RunDiffStyle, RunEntryBody, StreamCommit } from "./types"
  22. type ActiveBody = Exclude<RunEntryBody, { type: "none" | "structured" }>
  23. type ActiveEntry = {
  24. body: ActiveBody
  25. commit: StreamCommit
  26. surface: ScrollbackSurface
  27. renderable: TextRenderable | CodeRenderable | MarkdownRenderable
  28. content: string
  29. committedRows: number
  30. committedBlocks: number
  31. pendingSpacerRows: number
  32. rendered: boolean
  33. }
  34. function commitMarkdownBlocks(input: {
  35. surface: ScrollbackSurface
  36. renderable: MarkdownRenderable
  37. startBlock: number
  38. endBlockExclusive: number
  39. trailingNewline: boolean
  40. beforeCommit?: () => void
  41. }) {
  42. if (input.endBlockExclusive <= input.startBlock) {
  43. return false
  44. }
  45. const first = input.renderable._blockStates[input.startBlock]
  46. const last = input.renderable._blockStates[input.endBlockExclusive - 1]
  47. if (!first || !last) {
  48. return false
  49. }
  50. const next = input.renderable._blockStates[input.endBlockExclusive]
  51. const start = first.renderable.y
  52. const end = next ? next.renderable.y : last.renderable.y + last.renderable.height
  53. input.beforeCommit?.()
  54. input.surface.commitRows(start, end, {
  55. trailingNewline: input.trailingNewline,
  56. })
  57. return true
  58. }
  59. function staticBody(commit: StreamCommit, body: RunEntryBody, spaced: number): RunEntryBody {
  60. if (spaced === 0 || body.type !== "text") {
  61. return body
  62. }
  63. if (commit.kind !== "tool" || commit.phase !== "progress" || commit.toolState !== "completed") {
  64. return body
  65. }
  66. if (!body.content.startsWith("\n")) {
  67. return body
  68. }
  69. return {
  70. ...body,
  71. content: body.content.replace(/^\n/, ""),
  72. }
  73. }
  74. export class RunScrollbackStream {
  75. private tail: StreamCommit | undefined
  76. private rendered: StreamCommit | undefined
  77. private active: ActiveEntry | undefined
  78. private diffStyle: RunDiffStyle | undefined
  79. private sessionID?: () => string | undefined
  80. private treeSitterClient: TreeSitterClient | undefined
  81. private wrote: boolean
  82. private pendingThemes: RunTheme[] = []
  83. constructor(
  84. private renderer: CliRenderer,
  85. private theme: RunTheme,
  86. options: {
  87. wrote?: boolean
  88. diffStyle?: RunDiffStyle
  89. sessionID?: () => string | undefined
  90. treeSitterClient?: TreeSitterClient
  91. onThemeRelease?: (theme: RunTheme) => void
  92. } = {},
  93. ) {
  94. this.diffStyle = options.diffStyle
  95. this.sessionID = options.sessionID
  96. this.treeSitterClient = options.treeSitterClient
  97. this.wrote = options.wrote ?? false
  98. this.onThemeRelease = options.onThemeRelease
  99. }
  100. private onThemeRelease: ((theme: RunTheme) => void) | undefined
  101. private releasePendingThemes(): void {
  102. if (this.pendingThemes.length === 0) {
  103. return
  104. }
  105. for (const theme of this.pendingThemes.splice(0)) this.onThemeRelease?.(theme)
  106. }
  107. public setTheme(theme: RunTheme): void {
  108. if (this.theme === theme) {
  109. return
  110. }
  111. const previous = this.theme
  112. this.theme = theme
  113. const active = this.active
  114. if (!active) {
  115. this.onThemeRelease?.(previous)
  116. return
  117. }
  118. this.pendingThemes.push(previous)
  119. const style = entryLook(active.commit, theme.entry)
  120. if (active.renderable instanceof TextRenderable) {
  121. active.renderable.fg = style.fg
  122. active.renderable.attributes = style.attrs ?? 0
  123. return
  124. }
  125. active.renderable.fg = entryColor(active.commit, theme)
  126. active.renderable.syntaxStyle = entrySyntax(active.commit, theme)
  127. }
  128. private createEntry(commit: StreamCommit, body: ActiveBody): ActiveEntry {
  129. const surface = this.renderer.createScrollbackSurface({
  130. startOnNewLine: entryFlags(commit).startOnNewLine,
  131. })
  132. const style = entryLook(commit, this.theme.entry)
  133. const treeSitterClient = body.type === "text" ? undefined : (this.treeSitterClient ??= getTreeSitterClient())
  134. const renderable =
  135. body.type === "text"
  136. ? new TextRenderable(surface.renderContext, {
  137. content: "",
  138. width: "100%",
  139. wrapMode: "word",
  140. fg: style.fg,
  141. attributes: style.attrs,
  142. })
  143. : body.type === "code"
  144. ? new CodeRenderable(surface.renderContext, {
  145. content: "",
  146. filetype: body.filetype,
  147. syntaxStyle: entrySyntax(commit, this.theme),
  148. width: "100%",
  149. wrapMode: "word",
  150. drawUnstyledText: false,
  151. streaming: true,
  152. fg: entryColor(commit, this.theme),
  153. treeSitterClient,
  154. })
  155. : new MarkdownRenderable(surface.renderContext, {
  156. content: "",
  157. syntaxStyle: entrySyntax(commit, this.theme),
  158. width: "100%",
  159. streaming: true,
  160. internalBlockMode: "top-level",
  161. tableOptions: { widthMode: "content" },
  162. fg: entryColor(commit, this.theme),
  163. treeSitterClient,
  164. })
  165. surface.root.add(renderable)
  166. const rows = separatorRows(this.rendered, commit, body)
  167. return {
  168. body,
  169. commit,
  170. surface,
  171. renderable,
  172. content: "",
  173. committedRows: 0,
  174. committedBlocks: 0,
  175. pendingSpacerRows: rows || (!this.rendered && this.wrote ? 1 : 0),
  176. rendered: false,
  177. }
  178. }
  179. private markRendered(commit: StreamCommit | undefined): void {
  180. if (!commit) {
  181. return
  182. }
  183. this.rendered = commit
  184. }
  185. private writeSpacer(rows: number): void {
  186. if (rows === 0) {
  187. return
  188. }
  189. this.renderer.writeToScrollback(spacerWriter())
  190. this.wrote = false
  191. }
  192. private flushPendingSpacer(active: ActiveEntry): void {
  193. this.writeSpacer(active.pendingSpacerRows)
  194. active.pendingSpacerRows = 0
  195. }
  196. private async flushActive(done: boolean, trailingNewline: boolean): Promise<boolean> {
  197. const active = this.active
  198. if (!active) {
  199. return false
  200. }
  201. if (active.body.type === "text") {
  202. if (!(active.renderable instanceof TextRenderable)) {
  203. return false
  204. }
  205. const renderable = active.renderable
  206. renderable.content = active.content
  207. active.surface.render()
  208. this.releasePendingThemes()
  209. const targetRows = done ? active.surface.height : Math.max(active.committedRows, active.surface.height - 1)
  210. if (targetRows <= active.committedRows) {
  211. return false
  212. }
  213. this.flushPendingSpacer(active)
  214. active.surface.commitRows(active.committedRows, targetRows, {
  215. trailingNewline: done && targetRows === active.surface.height ? trailingNewline : false,
  216. })
  217. active.committedRows = targetRows
  218. active.rendered = true
  219. return true
  220. }
  221. if (active.body.type === "code") {
  222. if (!(active.renderable instanceof CodeRenderable)) {
  223. return false
  224. }
  225. const renderable = active.renderable
  226. renderable.content = active.content
  227. renderable.streaming = !done
  228. await active.surface.settle()
  229. this.releasePendingThemes()
  230. const targetRows = done ? active.surface.height : Math.max(active.committedRows, active.surface.height - 1)
  231. if (targetRows <= active.committedRows) {
  232. return false
  233. }
  234. this.flushPendingSpacer(active)
  235. active.surface.commitRows(active.committedRows, targetRows, {
  236. trailingNewline: done && targetRows === active.surface.height ? trailingNewline : false,
  237. })
  238. active.committedRows = targetRows
  239. active.rendered = true
  240. return true
  241. }
  242. if (!(active.renderable instanceof MarkdownRenderable)) {
  243. return false
  244. }
  245. const renderable = active.renderable
  246. renderable.content = active.content
  247. renderable.streaming = !done
  248. await active.surface.settle()
  249. this.releasePendingThemes()
  250. const targetBlockCount = done ? renderable._blockStates.length : renderable._stableBlockCount
  251. if (targetBlockCount <= active.committedBlocks) {
  252. return false
  253. }
  254. if (
  255. commitMarkdownBlocks({
  256. surface: active.surface,
  257. renderable,
  258. startBlock: active.committedBlocks,
  259. endBlockExclusive: targetBlockCount,
  260. trailingNewline: done && targetBlockCount === renderable._blockStates.length ? trailingNewline : false,
  261. beforeCommit: () => this.flushPendingSpacer(active),
  262. })
  263. ) {
  264. active.committedBlocks = targetBlockCount
  265. active.rendered = true
  266. return true
  267. }
  268. return false
  269. }
  270. private async finishActive(trailingNewline: boolean): Promise<StreamCommit | undefined> {
  271. if (!this.active) {
  272. return undefined
  273. }
  274. const active = this.active
  275. try {
  276. await this.flushActive(true, trailingNewline)
  277. } finally {
  278. if (this.active === active) {
  279. this.active = undefined
  280. }
  281. if (!active.surface.isDestroyed) {
  282. active.surface.destroy()
  283. }
  284. this.releasePendingThemes()
  285. }
  286. return active.rendered ? active.commit : undefined
  287. }
  288. private async writeStreaming(commit: StreamCommit, body: ActiveBody): Promise<void> {
  289. if (!this.active || !sameEntryGroup(this.active.commit, commit) || this.active.body.type !== body.type) {
  290. this.markRendered(await this.finishActive(false))
  291. this.active = this.createEntry(commit, body)
  292. }
  293. this.active.body = body
  294. this.active.commit = commit
  295. this.active.content += body.content
  296. await this.flushActive(false, false)
  297. if (this.active.rendered) {
  298. this.markRendered(this.active.commit)
  299. }
  300. }
  301. public async append(commit: StreamCommit): Promise<void> {
  302. const same = sameEntryGroup(this.tail, commit)
  303. if (!same) {
  304. this.markRendered(await this.finishActive(false))
  305. }
  306. if (commit.summary) {
  307. this.writeSpacer(1)
  308. this.renderer.writeToScrollback(turnSummaryWriter({ ...commit.summary, theme: this.theme }))
  309. this.markRendered(commit)
  310. this.tail = commit
  311. return
  312. }
  313. const body = entryBody(commit)
  314. if (body.type === "none") {
  315. if (entryDone(commit)) {
  316. this.markRendered(await this.finishActive(false))
  317. }
  318. this.tail = commit
  319. return
  320. }
  321. if (
  322. body.type !== "structured" &&
  323. (entryCanStream(commit, body) || (commit.kind === "tool" && commit.phase === "final" && body.type === "markdown"))
  324. ) {
  325. await this.writeStreaming(commit, body)
  326. if (entryDone(commit)) {
  327. this.markRendered(await this.finishActive(false))
  328. }
  329. this.tail = commit
  330. return
  331. }
  332. if (same) {
  333. this.markRendered(await this.finishActive(false))
  334. }
  335. const rows = separatorRows(this.rendered, commit, body)
  336. const spaced = rows || (!this.rendered && this.wrote ? 1 : 0)
  337. this.writeSpacer(spaced)
  338. this.renderer.writeToScrollback(
  339. entryWriter({
  340. commit,
  341. body: staticBody(commit, body, spaced),
  342. theme: this.theme,
  343. opts: {
  344. diffStyle: this.diffStyle,
  345. },
  346. }),
  347. )
  348. this.markRendered(commit)
  349. this.tail = commit
  350. }
  351. private resetActive(): void {
  352. if (!this.active) {
  353. return
  354. }
  355. if (!this.active.surface.isDestroyed) {
  356. this.active.surface.destroy()
  357. }
  358. this.active = undefined
  359. this.releasePendingThemes()
  360. }
  361. public async complete(trailingNewline = false): Promise<void> {
  362. this.markRendered(await this.finishActive(trailingNewline))
  363. }
  364. public async writeTurnSummary(input: { agent: string; model: string; duration: string }): Promise<void> {
  365. await this.append(turnSummaryCommit(input))
  366. }
  367. public destroy(): void {
  368. this.resetActive()
  369. this.releasePendingThemes()
  370. }
  371. }