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