refactor(tui): organize source by feature boundaries (#5975)

* refactor(tui): group source files by feature

* refactor(tui): split app and gateway responsibilities
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-29 16:57:36 +08:00
1 parent b7abbcd70b
commit f18423800e
73 files changed
+6401 -6006

No files matched your search

+158
View File
@@ -0,0 +1,158 @@
import { describe, expect, test } from "bun:test"
import { renderLatexAsUnicode } from "./latex"
describe("terminal LaTeX rendering", () => {
test("renders the cache-rate example as readable Unicode text", () => {
expect(renderLatexAsUnicode([
"实际公式是:",
"",
"\\[",
"\\text{缓存率}=\\frac{\\text{cached input tokens}}{\\text{total input tokens}}",
"\\]",
"",
"缓存命中:\\(66{,}000 \\times 94\\% \\approx 62{,}040\\) tokens",
].join("\n"))).toBe([
"实际公式是:",
"",
"缓存率 = cached input tokens / total input tokens",
"",
"缓存命中:66,000 × 94% ≈ 62,040 tokens",
].join("\n"))
})
test("converts common symbols, scripts, roots, fractions, and accents", () => {
const source = "$\\hat{f}(\\xi)=\\sum_{n=0}^{\\infty} \\frac{x^n}{n!}$ and \\(x_1=\\sqrt[3]{\\alpha+\\beta}\\)"
expect(renderLatexAsUnicode(source)).toBe(
"f̂(ξ) = ∑ₙ₌₀^(∞) xⁿ / n! and x₁ = ³√(α+β)",
)
})
test("preserves precedence for compound fraction sides", () => {
expect(renderLatexAsUnicode("\\(\\frac{a-b}{c} + \\frac{a}{b \\times c}\\)"))
.toBe("(a-b) / c + a / (b × c)")
})
test("keeps currency and price ranges literal while converting guarded dollar math", () => {
const source = [
"Costs are $24 today or $10-20 later; variables $x$ and $2^n$ are math.",
"Shipping costs $5+$10 and paths use $HOME/$USER.",
"Mixed currency and variables like $5+$x$ remain literal.",
"Commands and groups stay literal: $5+$\\alpha$, $5+${x}$, and $5+$(x)$.",
"Matrix $A$ maps $V$ to $W$.",
].join("\n")
expect(renderLatexAsUnicode(source)).toBe([
"Costs are $24 today or $10-20 later; variables x and 2ⁿ are math.",
"Shipping costs $5+$10 and paths use $HOME/$USER.",
"Mixed currency and variables like $5+$x$ remain literal.",
"Commands and groups stay literal: $5+$\\alpha$, $5+${x}$, and $5+$(x)$.",
"Matrix A maps V to W.",
].join("\n"))
})
test("supports display dollars and aligned line breaks", () => {
const source = "$$\\begin{aligned}a&=b+c\\\\d&\\le e\\end{aligned}$$"
expect(renderLatexAsUnicode(source)).toBe("a = b+c\nd ≤ e")
})
test("leaves inline and fenced code unchanged", () => {
const source = [
"Inline `\\(x^2\\)` stays literal, but \\(y^2\\) renders.",
"",
"```tex",
"\\[\\frac{a}{b}\\]",
"```",
].join("\n")
expect(renderLatexAsUnicode(source)).toBe([
"Inline `\\(x^2\\)` stays literal, but y² renders.",
"",
"```tex",
"\\[\\frac{a}{b}\\]",
"```",
].join("\n"))
expect(renderLatexAsUnicode("`$x$``")).toBe("`x``")
})
test("leaves fenced code inside block quotes and lists unchanged", () => {
const source = [
"> ~~~tex",
"> $x^2$",
"> ~~~",
"",
"- ```tex",
" \\(y_1\\)",
" ```",
"",
"1. item",
"",
" ~~~tex",
" $z^2$",
" ~~~",
].join("\n")
expect(renderLatexAsUnicode(source)).toBe(source)
})
test("leaves unmatched delimiters available during streaming", () => {
expect(renderLatexAsUnicode("Working on \\(x^2")).toBe("Working on \\(x^2")
expect(renderLatexAsUnicode("Working $$x$")).toBe("Working $$x$")
expect(renderLatexAsUnicode("An escaped \\$5 stays literal.")).toBe("An escaped \\$5 stays literal.")
})
test("handles many unmatched openers without changing them", () => {
const openers = "\\(".repeat(20_000)
const backslashes = "\\".repeat(20_000)
const backticks = `text ${"`".repeat(20_000)} then $x$`
const descendingBackticks = "text " + Array.from(
{ length: 500 },
(_, index) => "`".repeat(500 - index),
).join("x") + " $x$"
const linkDestinations = `${"](".repeat(20_000)} then $x$`
expect(renderLatexAsUnicode(openers)).toBe(openers)
expect(renderLatexAsUnicode(backslashes)).toBe(backslashes)
expect(renderLatexAsUnicode(backticks)).toBe(backticks.replace("$x$", "x"))
expect(renderLatexAsUnicode(descendingBackticks))
.toBe(descendingBackticks.replace("$x$", "x"))
expect(renderLatexAsUnicode(linkDestinations)).toBe(linkDestinations.replace("$x$", "x"))
})
test("leaves unsupported, malformed, and deeply nested math unchanged", () => {
const deep = `{`.repeat(100) + "x" + `}`.repeat(100)
const source = [
"$\\color{red}{x}$",
"$\\frac{a}$",
`\\(${deep}\\)`,
"\\(\\displaystyle x^2\\)",
].join(" ")
expect(renderLatexAsUnicode(source)).toBe([
"$\\color{red}{x}$",
"$\\frac{a}$",
`\\(${deep}\\)`,
"x²",
].join(" "))
})
test("does not rewrite Markdown link destinations or autolinks", () => {
const source = [
"[formula $x$](https://example.test/$x$/\\(raw\\))",
"<https://example.test/$y$>",
"bare https://example.test/$z$ remains intact",
"<span title=\"$raw$\">HTML</span>",
"if a < $x$ > b",
].join("\n")
expect(renderLatexAsUnicode(source)).toBe([
"[formula x](https://example.test/$x$/\\(raw\\))",
"<https://example.test/$y$>",
"bare https://example.test/$z$ remains intact",
"<span title=\"$raw$\">HTML</span>",
"if a < x > b",
].join("\n"))
})
})
+901
View File
@@ -0,0 +1,901 @@
const MATH_SYMBOLS: Readonly<Record<string, string>> = {
alpha: "α",
beta: "β",
gamma: "γ",
delta: "δ",
epsilon: "ε",
varepsilon: "ϵ",
zeta: "ζ",
eta: "η",
theta: "θ",
vartheta: "ϑ",
iota: "ι",
kappa: "κ",
lambda: "λ",
mu: "μ",
nu: "ν",
xi: "ξ",
omicron: "ο",
pi: "π",
varpi: "ϖ",
rho: "ρ",
varrho: "ϱ",
sigma: "σ",
varsigma: "ς",
tau: "τ",
upsilon: "υ",
phi: "φ",
varphi: "ϕ",
chi: "χ",
psi: "ψ",
omega: "ω",
Gamma: "Γ",
Delta: "Δ",
Theta: "Θ",
Lambda: "Λ",
Xi: "Ξ",
Pi: "Π",
Sigma: "Σ",
Upsilon: "Υ",
Phi: "Φ",
Psi: "Ψ",
Omega: "Ω",
times: " × ",
div: " ÷ ",
cdot: " · ",
ast: " ∗ ",
pm: " ± ",
mp: " ∓ ",
approx: " ≈ ",
sim: " ∼ ",
simeq: " ≃ ",
cong: " ≅ ",
equiv: " ≡ ",
ne: " ≠ ",
neq: " ≠ ",
le: " ≤ ",
leq: " ≤ ",
ge: " ≥ ",
geq: " ≥ ",
ll: " ≪ ",
gg: " ≫ ",
propto: " ∝ ",
to: " → ",
gets: " ← ",
rightarrow: " → ",
leftarrow: " ← ",
leftrightarrow: " ↔ ",
Rightarrow: " ⇒ ",
Leftarrow: " ⇐ ",
Leftrightarrow: " ⇔ ",
mapsto: " ↦ ",
in: " ∈ ",
ni: " ∋ ",
notin: " ∉ ",
subset: " ⊂ ",
supset: " ⊃ ",
subseteq: " ⊆ ",
supseteq: " ⊇ ",
cup: " ∪ ",
cap: " ∩ ",
setminus: " ∖ ",
emptyset: "∅",
varnothing: "∅",
forall: "∀",
exists: "∃",
neg: "¬",
land: " ∧ ",
lor: " ∨ ",
wedge: " ∧ ",
vee: " ∨ ",
sum: "∑",
prod: "∏",
coprod: "∐",
int: "∫",
iint: "∬",
iiint: "∭",
oint: "∮",
partial: "∂",
nabla: "∇",
infty: "∞",
ell: "ℓ",
hbar: "ℏ",
Re: "ℜ",
Im: "ℑ",
angle: "∠",
degree: "°",
prime: "′",
ldots: "…",
cdots: "⋯",
vdots: "⋮",
ddots: "⋱",
langle: "⟨",
rangle: "⟩",
lceil: "⌈",
rceil: "⌉",
lfloor: "⌊",
rfloor: "⌋",
vert: "|",
Vert: "‖",
}
const NAMED_FUNCTIONS = new Set([
"arccos",
"arcsin",
"arctan",
"cos",
"cosh",
"cot",
"coth",
"csc",
"deg",
"det",
"dim",
"exp",
"gcd",
"hom",
"inf",
"ker",
"lg",
"lim",
"liminf",
"limsup",
"ln",
"log",
"max",
"min",
"Pr",
"sec",
"sin",
"sinh",
"sup",
"tan",
"tanh",
])
const STYLE_COMMANDS = new Set([
"mathbf",
"mathbb",
"mathcal",
"mathfrak",
"mathit",
"mathrm",
"mathsf",
"mathtt",
"boldsymbol",
"bm",
])
const ACCENTS: Readonly<Record<string, string>> = {
acute: "\u0301",
bar: "\u0304",
breve: "\u0306",
check: "\u030c",
ddot: "\u0308",
dot: "\u0307",
grave: "\u0300",
hat: "\u0302",
overline: "\u0305",
tilde: "\u0303",
vec: "\u20d7",
}
const SUPER: Readonly<Record<string, string>> = {
"0": "⁰",
"1": "¹",
"2": "²",
"3": "³",
"4": "⁴",
"5": "⁵",
"6": "⁶",
"7": "⁷",
"8": "⁸",
"9": "⁹",
"+": "⁺",
"-": "⁻",
"=": "⁼",
"(": "⁽",
")": "⁾",
a: "ᵃ",
b: "ᵇ",
c: "ᶜ",
d: "ᵈ",
e: "ᵉ",
f: "ᶠ",
g: "ᵍ",
h: "ʰ",
i: "ⁱ",
j: "ʲ",
k: "ᵏ",
l: "ˡ",
m: "ᵐ",
n: "ⁿ",
o: "ᵒ",
p: "ᵖ",
r: "ʳ",
s: "ˢ",
t: "ᵗ",
u: "ᵘ",
v: "ᵛ",
w: "ʷ",
x: "ˣ",
y: "ʸ",
z: "ᶻ",
}
const SUB: Readonly<Record<string, string>> = {
"0": "₀",
"1": "₁",
"2": "₂",
"3": "₃",
"4": "₄",
"5": "₅",
"6": "₆",
"7": "₇",
"8": "₈",
"9": "₉",
"+": "₊",
"-": "₋",
"=": "₌",
"(": "₍",
")": "₎",
a: "ₐ",
e: "ₑ",
h: "ₕ",
i: "ᵢ",
j: "ⱼ",
k: "ₖ",
l: "ₗ",
m: "ₘ",
n: "ₙ",
o: "ₒ",
p: "ₚ",
r: "ᵣ",
s: "ₛ",
t: "ₜ",
u: "ᵤ",
v: "ᵥ",
x: "ₓ",
}
const MAX_MATH_LENGTH = 20_000
const MAX_GROUP_DEPTH = 64
/** Converts supported LaTeX math spans without changing the stored Markdown source. */
export function renderLatexAsUnicode(markdown: string): string {
if (!markdown.includes("$") && !markdown.includes("\\(") && !markdown.includes("\\[")) {
return markdown
}
let rendered = ""
let cursor = 0
const missingClosers = new Set<string>()
const inlineCodeEnds = markdown.includes("`") ? markdownInlineCodeEnds(markdown) : null
const linkDestinationEnds = markdown.includes("](")
? markdownLinkDestinationEnds(markdown)
: null
while (cursor < markdown.length) {
const fencedEnd = fencedCodeEnd(markdown, cursor)
if (fencedEnd !== null) {
rendered += markdown.slice(cursor, fencedEnd)
cursor = fencedEnd
continue
}
if (markdown[cursor] === "`") {
const delimiterLength = repeatedCharacterCount(markdown, cursor, "`")
const inlineEnd = inlineCodeEnds?.get(cursor)
if (inlineEnd !== undefined) {
rendered += markdown.slice(cursor, inlineEnd)
cursor = inlineEnd
continue
}
rendered += markdown.slice(cursor, cursor + delimiterLength)
cursor += delimiterLength
continue
}
const destinationEnd = markdownDestinationEnd(markdown, cursor, linkDestinationEnds)
if (destinationEnd !== null) {
rendered += markdown.slice(cursor, destinationEnd)
cursor = destinationEnd
continue
}
const explicitOpening = explicitMathOpeningAt(markdown, cursor)
const math = mathSpanAt(markdown, cursor, explicitOpening, missingClosers)
if (math) {
if (math.literal) {
rendered += markdown.slice(cursor, math.end)
cursor = math.end
continue
}
const converted = convertMath(math.content)
if (converted !== null) {
rendered += escapeMarkdown(converted)
cursor = math.end
continue
}
rendered += markdown.slice(cursor, math.end)
cursor = math.end
continue
}
if (explicitOpening) {
rendered += explicitOpening
cursor += explicitOpening.length
continue
}
rendered += markdown[cursor]
cursor += 1
}
return rendered
}
interface MathSpan {
content: string
end: number
literal?: boolean
}
interface ParseState {
valid: boolean
}
function convertMath(source: string): string | null {
if (!validMathStructure(source)) return null
const state: ParseState = { valid: true }
const converted = normalizeMath(new LatexParser(source, state).parse())
return state.valid && converted ? converted : null
}
function validMathStructure(source: string): boolean {
if (source.length > MAX_MATH_LENGTH) return false
let depth = 0
for (let cursor = 0; cursor < source.length; cursor += 1) {
const value = source[cursor]
if (value !== "{" && value !== "}") continue
if (isEscaped(source, cursor)) continue
if (value === "{") {
depth += 1
if (depth > MAX_GROUP_DEPTH) return false
} else if (source[cursor] === "}") {
depth -= 1
if (depth < 0) return false
}
}
return depth === 0
}
function explicitMathOpeningAt(markdown: string, start: number): string | null {
const opening = markdown.startsWith("\\[", start)
? "\\["
: markdown.startsWith("\\(", start)
? "\\("
: markdown.startsWith("$$", start)
? "$$"
: null
return opening && !isEscaped(markdown, start) ? opening : null
}
function mathSpanAt(
markdown: string,
start: number,
explicitOpening: string | null,
missingClosers: Set<string>,
): MathSpan | null {
if (explicitOpening === "\\[") {
return delimitedMath(markdown, start, "\\[", "\\]", false, missingClosers)
}
if (explicitOpening === "\\(") {
return delimitedMath(markdown, start, "\\(", "\\)", true, missingClosers)
}
if (explicitOpening === "$$") {
return delimitedMath(markdown, start, "$$", "$$", false, missingClosers)
}
if (
markdown[start] !== "$"
|| markdown[start + 1] === "$"
|| isWhitespace(markdown[start + 1])
|| isEscaped(markdown, start)
) {
return null
}
const span = delimitedMath(markdown, start, "$", "$", true, missingClosers)
if (!span || isWhitespace(span.content.at(-1))) return null
const first = span.content[0]
if (first && /[0-9]/u.test(first)) {
const following = markdown[span.end] ?? ""
if (!isWhitespace(following) && /[+\-*/]\s*$/u.test(span.content)) {
const adjacent = delimitedMath(
markdown,
span.end - 1,
"$",
"$",
true,
missingClosers,
)
if (adjacent && !isWhitespace(adjacent.content.at(-1))) {
return { content: "", end: adjacent.end, literal: true }
}
}
if (/[0-9]/u.test(following)) return null
}
if (first && /[0-9]/u.test(first) && !/[\\^_={}|+<>]/u.test(span.content)) return null
if (
/^[A-Z_][A-Z0-9_]*(?:\/|\s.*)$/u.test(span.content)
&& /[A-Z_]/u.test(markdown[span.end] ?? "")
&& !/[\\^_={}|+<>]/u.test(span.content)
) {
return null
}
return span
}
function delimitedMath(
source: string,
start: number,
opening: string,
closing: string,
singleLine: boolean,
missingClosers: Set<string>,
): MathSpan | null {
const contentStart = start + opening.length
const lineEnd = singleLine ? source.indexOf("\n", contentStart) : -1
const boundary = lineEnd < 0 ? source.length : lineEnd
const cacheKey = `${closing}:${boundary}`
if (missingClosers.has(cacheKey)) return null
for (let close = contentStart; close + closing.length <= boundary; close += 1) {
if (!source.startsWith(closing, close) || isEscaped(source, close)) continue
if (closing === "$" && (source[close - 1] === "$" || source[close + 1] === "$")) continue
const content = source.slice(start + opening.length, close)
return content ? { content, end: close + closing.length } : null
}
missingClosers.add(cacheKey)
return null
}
function fencedCodeEnd(source: string, start: number): number | null {
const marker = source[start]
if (marker !== "`" && marker !== "~") return null
const lineStart = source.lastIndexOf("\n", start - 1) + 1
const context = fenceContext(source.slice(lineStart, start))
if (!context) return null
const count = repeatedCharacterCount(source, start, marker)
if (count < 3) return null
const openingLineEnd = source.indexOf("\n", start + count)
if (openingLineEnd < 0) return source.length
let candidateStart = openingLineEnd + 1
while (candidateStart <= source.length) {
const candidateEnd = source.indexOf("\n", candidateStart)
const lineEnd = candidateEnd < 0 ? source.length : candidateEnd
const line = source.slice(candidateStart, lineEnd)
const markerOffset = closingFenceOffset(line, context)
if (markerOffset === null) {
if (candidateEnd < 0) break
candidateStart = candidateEnd + 1
continue
}
const markerStart = candidateStart + markerOffset
const closingCount = repeatedCharacterCount(source, markerStart, marker)
if (closingCount >= count && source.slice(markerStart + closingCount, lineEnd).trim() === "") {
return candidateEnd < 0 ? source.length : candidateEnd + 1
}
if (candidateEnd < 0) break
candidateStart = candidateEnd + 1
}
return source.length
}
interface FenceContext {
quoteDepth: number
maxIndent: number
}
function fenceContext(prefix: string): FenceContext | null {
let rest = prefix
let quoteDepth = 0
while (true) {
const quote = rest.match(/^[ \t]{0,3}>[ \t]?/u)?.[0]
if (!quote) break
quoteDepth += 1
rest = rest.slice(quote.length)
}
const list = rest.match(/^[ \t]*(?:[-+*]|[0-9]{1,9}[.)])[ \t]+/u)?.[0]
if (list) rest = rest.slice(list.length)
if (!/^[ \t]*$/u.test(rest)) return null
return { quoteDepth, maxIndent: Math.max(3, list?.length ?? 0, rest.length) }
}
function closingFenceOffset(line: string, context: FenceContext): number | null {
let offset = 0
for (let depth = 0; depth < context.quoteDepth; depth += 1) {
const quote = line.slice(offset).match(/^[ \t]{0,3}>[ \t]?/u)?.[0]
if (!quote) return null
offset += quote.length
}
const indent = line.slice(offset).match(new RegExp(`^[ \\t]{0,${context.maxIndent}}`, "u"))?.[0]
return indent === undefined ? null : offset + indent.length
}
function markdownInlineCodeEnds(source: string): ReadonlyMap<number, number> {
const ends = new Map<number, number>()
const previousRun = new Map<number, number>()
let cursor = 0
while (cursor < source.length) {
if (source[cursor] !== "`") {
cursor += 1
continue
}
const count = repeatedCharacterCount(source, cursor, "`")
const previous = previousRun.get(count)
if (previous !== undefined) ends.set(previous, cursor + count)
previousRun.set(count, cursor)
cursor += count
}
return ends
}
function markdownLinkDestinationEnds(source: string): ReadonlyMap<number, number> {
const ends = new Map<number, number>()
const openParentheses: number[] = []
let cursor = 0
while (cursor < source.length) {
const value = source[cursor]
if (value === "\\") {
cursor += Math.min(2, source.length - cursor)
continue
}
if (value === "\n") {
openParentheses.length = 0
} else if (value === "(") {
openParentheses.push(cursor)
} else if (value === ")") {
const opening = openParentheses.pop()
if (opening !== undefined && source[opening - 1] === "]" && !isEscaped(source, opening - 1)) {
ends.set(opening, cursor + 1)
}
}
cursor += 1
}
return ends
}
function markdownDestinationEnd(
source: string,
start: number,
linkDestinationEnds: ReadonlyMap<number, number> | null,
): number | null {
if (source[start] === "(" && source[start - 1] === "]" && !isEscaped(source, start - 1)) {
return linkDestinationEnds?.get(start) ?? null
}
if (source[start] === "<") {
const angle = source.slice(start).match(
/^<(?:[A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*|[^<>\s@]+@[^<>\s@]+|\/?[A-Za-z][^<>\n]*)>/u,
)?.[0]
if (angle) return start + angle.length
}
if (
source.startsWith("http://", start)
|| source.startsWith("https://", start)
|| source.startsWith("mailto:", start)
) {
let end = start
while (end < source.length && !/[\s<>]/u.test(source[end] ?? "")) end += 1
return end
}
return null
}
function repeatedCharacterCount(source: string, start: number, value: string): number {
let end = start
while (source[end] === value) end += 1
return end - start
}
function isEscaped(source: string, index: number): boolean {
let backslashes = 0
for (let cursor = index - 1; cursor >= 0 && source[cursor] === "\\"; cursor -= 1) {
backslashes += 1
}
return backslashes % 2 === 1
}
function isWhitespace(value: string | undefined): boolean {
return value === undefined || /\s/u.test(value)
}
class LatexParser {
private cursor = 0
constructor(
private readonly source: string,
private readonly state: ParseState,
) {}
parse(): string {
let result = ""
while (this.cursor < this.source.length) {
const value = this.source[this.cursor]
if (value === undefined) break
if (/\s/u.test(value)) {
result += " "
this.cursor += 1
} else if (value === "\\") {
result += this.command()
} else if (value === "{") {
const group = this.rawGroup()
result += group === null ? "{" : new LatexParser(group, this.state).parse()
} else if (value === "^" || value === "_") {
this.cursor += 1
const argument = this.argument()
result += script(argument ?? "", value === "^" ? SUPER : SUB, value)
} else if (value === "&" || value === "~") {
result += " "
this.cursor += 1
} else {
result += value
this.cursor += 1
}
}
return result
}
private command(): string {
this.cursor += 1
const first = this.source[this.cursor]
if (first === undefined) return ""
if (!/[A-Za-z]/u.test(first)) {
this.cursor += 1
if (first === "\\") return "\n"
if (",:;! ".includes(first)) return " "
return first
}
const start = this.cursor
while (/[A-Za-z]/u.test(this.source[this.cursor] ?? "")) this.cursor += 1
const name = this.source.slice(start, this.cursor)
if (this.source[this.cursor] === "*") this.cursor += 1
const symbol = MATH_SYMBOLS[name]
if (symbol !== undefined) return symbol
if (NAMED_FUNCTIONS.has(name)) return name
if ([
"left",
"right",
"limits",
"nolimits",
"displaystyle",
"textstyle",
"scriptstyle",
"scriptscriptstyle",
].includes(name)) return ""
if (["quad", "qquad", "enspace", "enskip"].includes(name)) return " "
if (["hspace", "vspace"].includes(name)) {
this.rawGroup()
return " "
}
if (["frac", "dfrac", "tfrac"].includes(name)) {
const numerator = this.argument()
const denominator = this.argument()
if (numerator !== null && denominator !== null) {
return `${fractionSide(numerator)} / ${fractionSide(denominator)}`
}
return "frac"
}
if (name === "sqrt") {
const root = this.optionalArgument()
const radicand = this.argument()
if (radicand === null) return "√"
const index = root ? script(root, SUPER, "^") : ""
return `${index}√(${radicand})`
}
if (["text", "textrm", "textsf", "texttt", "textnormal", "mbox"].includes(name)) {
const text = this.rawGroup()
return text === null ? name : plainText(text, this.state)
}
if (STYLE_COMMANDS.has(name)) return this.argument() ?? ""
if (name === "operatorname") {
const operator = this.rawGroup()
return operator === null ? "" : plainText(operator, this.state)
}
const accent = ACCENTS[name]
if (accent !== undefined) {
const argument = this.argument()
return argument === null ? "" : `${argument}${accent}`
}
if (name === "begin" || name === "end") {
const environment = this.rawGroup()
return name === "begin" && environment === "cases" ? "{\n" : ""
}
if (name === "not") return this.negatedSymbol()
if (name === "mod") return "mod"
if (name === "pmod") {
const value = this.argument()
return value === null ? "mod" : `(mod ${value})`
}
this.state.valid = false
return `\\${name}`
}
private negatedSymbol(): string {
while (/\s/u.test(this.source[this.cursor] ?? "")) this.cursor += 1
if (this.source[this.cursor] === "=") {
this.cursor += 1
return " ≠ "
}
if (this.source[this.cursor] !== "\\") return "¬"
const saved = this.cursor
this.cursor += 1
const start = this.cursor
while (/[A-Za-z]/u.test(this.source[this.cursor] ?? "")) this.cursor += 1
const name = this.source.slice(start, this.cursor)
const negated: Readonly<Record<string, string>> = {
in: " ∉ ",
ni: " ∌ ",
subset: " ⊄ ",
supset: " ⊅ ",
subseteq: " ⊈ ",
supseteq: " ⊉ ",
}
const symbol = negated[name]
if (symbol !== undefined) return symbol
this.cursor = saved
return "¬"
}
private argument(): string | null {
while (/\s/u.test(this.source[this.cursor] ?? "")) this.cursor += 1
if (this.source[this.cursor] === "{") {
const group = this.rawGroup()
return group === null ? null : new LatexParser(group, this.state).parse()
}
if (this.source[this.cursor] === "\\") return this.command()
const value = this.source[this.cursor]
if (value === undefined) {
this.state.valid = false
return null
}
this.cursor += 1
return value
}
private optionalArgument(): string | null {
while (/\s/u.test(this.source[this.cursor] ?? "")) this.cursor += 1
if (this.source[this.cursor] !== "[") return null
const start = this.cursor + 1
let depth = 1
this.cursor += 1
while (this.cursor < this.source.length) {
const value = this.source[this.cursor]
if (value === "[") depth += 1
else if (value === "]") {
depth -= 1
if (depth === 0) {
const content = this.source.slice(start, this.cursor)
this.cursor += 1
return new LatexParser(content, this.state).parse()
}
}
this.cursor += 1
}
this.state.valid = false
return null
}
private rawGroup(): string | null {
while (/\s/u.test(this.source[this.cursor] ?? "")) this.cursor += 1
if (this.source[this.cursor] !== "{") {
this.state.valid = false
return null
}
const start = this.cursor + 1
let depth = 1
this.cursor += 1
while (this.cursor < this.source.length) {
const value = this.source[this.cursor]
if (value === "\\") {
this.cursor += Math.min(2, this.source.length - this.cursor)
continue
}
if (value === "{") depth += 1
else if (value === "}") {
depth -= 1
if (depth === 0) {
const content = this.source.slice(start, this.cursor)
this.cursor += 1
return content
}
}
this.cursor += 1
}
this.state.valid = false
return null
}
}
function plainText(source: string, state: ParseState): string {
let text = ""
let cursor = 0
while (cursor < source.length) {
if (source[cursor] !== "\\") {
text += source[cursor]
cursor += 1
continue
}
const next = source[cursor + 1]
if (next === undefined) break
if (!/[A-Za-z]/u.test(next)) {
text += ",:;! ".includes(next) ? " " : next
cursor += 2
continue
}
let end = cursor + 1
while (/[A-Za-z]/u.test(source[end] ?? "")) end += 1
const name = source.slice(cursor + 1, end)
const symbol = MATH_SYMBOLS[name]
if (symbol !== undefined) text += symbol
else if (NAMED_FUNCTIONS.has(name)) text += name
else {
state.valid = false
text += `\\${name}`
}
cursor = end
}
return text.replace(/\s+/gu, " ").trim()
}
function script(value: string, alphabet: Readonly<Record<string, string>>, marker: string): string {
const normalized = normalizeMath(value).replace(/\s+/gu, "")
const converted = [...normalized].map((character) => alphabet[character])
if (converted.every((character) => character !== undefined)) return converted.join("")
return normalized ? `${marker}(${normalized})` : marker
}
function fractionSide(value: string): string {
const normalized = normalizeMath(value)
const compound = /[=+≈≠≤≥≪≫≃≅≡∝×÷·±∓→←↔⇒⇐⇔↦∈∉∋∌⊂⊄⊆⊈⊃⊅⊇⊉∪∩∧∨]/u.test(normalized)
|| /[-−]/u.test(normalized.slice(1))
|| /\s\/\s/u.test(normalized)
return compound ? `(${normalized})` : normalized
}
function normalizeMath(value: string): string {
return value
.split("\n")
.map((line) => line
.replace(/[ \t]+/gu, " ")
.trim()
.replace(/\s*([=≈≠≤≥≪≫≃≅≡∝×÷±∓→←↔⇒⇐⇔↦∈∉∋∌⊂⊄⊆⊈⊃⊅⊇⊉∪∩∧∨])\s*/gu, " $1 ")
.replace(/\s*\/\s*/gu, " / ")
.replace(/\(\s+/gu, "(")
.replace(/\s+\)/gu, ")")
.replace(/\s+([,;:%])/gu, "$1")
.replace(/[ \t]+/gu, " ")
.trim())
.filter(Boolean)
.join("\n")
}
function escapeMarkdown(value: string): string {
return value
.replace(/\\/gu, "\\\\")
.replace(/([`*_{}\[\]<>#|~])/gu, "\\$1")
}
+14
View File
@@ -0,0 +1,14 @@
import type { ScrollBoxRenderable } from "@opentui/core"
/** Keep scrolling functional without drawing terminal-dependent block glyphs. */
export function hideScrollbars(scrollBox: ScrollBoxRenderable): void {
for (const bar of [scrollBox.verticalScrollBar, scrollBox.horizontalScrollBar]) {
// ScrollBar can make itself visible again when content starts overflowing.
// Hiding its children as well keeps embedded terminals deterministic.
bar.visible = false
bar.showArrows = false
bar.slider.visible = false
bar.startArrow.visible = false
bar.endArrow.visible = false
}
}
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, test } from "bun:test"
import { mergeToolEvent, renderToolEvent } from "./tool-renderers"
describe("tool renderers", () => {
test("shows rg search phases and argument boundaries", () => {
const start = { name: "rg", phase: "start", arguments: { args: ["-n", "hello world", "src"] } }
expect(renderToolEvent(start)).toBe(' › Searching files -n "hello world" src')
expect(renderToolEvent(mergeToolEvent(start, { name: "rg", phase: "end", result: "src/a:1:hello world" })))
.toBe(' ✓ Searched files -n "hello world" src')
expect(renderToolEvent({ name: "rg", phase: "error", error: "invalid regex" }))
.toBe(" × Search failed invalid regex")
})
test("shows rg regex characters and empty arguments", () => {
expect(renderToolEvent({ name: "rg", phase: "end", arguments: { args: [String.raw`resolve\(`, ""] } }))
.toBe(' ✓ Searched files resolve\\( ""')
})
test("retains start arguments when an end frame only carries output", () => {
const event = mergeToolEvent(
{ call_id: "exec-1", phase: "start", name: "exec", arguments: { cmd: "git status" } },
{ call_id: "exec-1", phase: "end", name: "exec", result: { output: "clean" } },
)
expect(renderToolEvent(event)).toBe(" ✓ Ran git status")
})
test("uses stable task language for common file and web tools", () => {
expect(renderToolEvent({ phase: "end", name: "read_file", arguments: { path: "README.md" } }))
.toBe(" ✓ Read README.md")
expect(renderToolEvent({ phase: "start", name: "web_search", arguments: { query: "nanobot" } }))
.toBe(" › Search web nanobot")
expect(renderToolEvent({ phase: "error", name: "web_fetch", error: "timeout" }))
.toBe(" × Fetch timeout")
})
test("compresses verification and edits into outcome language", () => {
expect(renderToolEvent({ phase: "end", name: "exec", arguments: { cmd: "bun test" } }))
.toBe(" ✓ Testing bun test")
expect(renderToolEvent({ phase: "end", name: "apply_patch", arguments: { path: "app.ts" } }))
.toBe(" ✓ Edited app.ts")
})
test("shortens file paths relative to the workspace while preserving the useful tail", () => {
const workspace = String.raw`C:\workspace\nanobot`
expect(renderToolEvent({
phase: "end",
name: "read_file",
arguments: { path: String.raw`C:\workspace\nanobot\tui\src\app.ts` },
}, { workspace })).toBe(" ✓ Read tui/src/app.ts")
expect(renderToolEvent({
phase: "end",
name: "read_file",
arguments: {
path: String.raw`C:\workspace\nanobot\.worktrees\feature\nanobot\providers\fallback_provider.py`,
},
}, { workspace })).toBe(" ✓ Read …/feature/nanobot/providers/fallback_provider.py")
})
test("summarizes subagent delegation without exposing raw argument JSON", () => {
expect(renderToolEvent({
phase: "end",
name: "spawn",
arguments: { task: "Simplify the fallback provider implementation" },
})).toBe(" ✓ Delegated Simplify the fallback provider implementation")
})
})
+129
View File
@@ -0,0 +1,129 @@
import type { ToolProgressEvent } from "../client"
export interface ToolRenderOptions {
workspace?: string
}
const PATH_DETAIL_LIMIT = 52
export function mergeToolEvent(
previous: ToolProgressEvent | undefined,
next: ToolProgressEvent,
): ToolProgressEvent {
if (!previous) return next
return {
...previous,
...next,
arguments: next.arguments ?? previous.arguments,
result: next.result ?? previous.result,
error: next.error ?? previous.error,
}
}
export function renderToolEvent(
event: ToolProgressEvent,
options: ToolRenderOptions = {},
): string {
const phase = event.phase || "start"
const marker = phase === "error" ? "×" : phase === "end" ? "✓" : "›"
const name = (event.name || "tool").trim()
const args = record(event.arguments)
const result = record(event.result)
const detail = phase === "error"
? compact(event.error)
: toolDetail(name, args, result, options)
return ` ${marker} ${toolLabel(name, phase, args)}${detail ? ` ${detail}` : ""}`
}
function toolLabel(
name: string,
phase: string,
args: Record<string, unknown>,
): string {
if (/^(?:exec|exec_command|shell|run_command)$/u.test(name)) {
const command = compact(args.command ?? args.cmd)
if (/(?:^|\s)(?:pytest|ruff|pyright|basedpyright|cargo\s+test|go\s+test|(?:bun|npm|pnpm|yarn)(?:\s+run)?\s+test)(?:\s|$)/iu.test(command)) {
return "Testing"
}
return phase === "end" ? "Ran" : phase === "error" ? "Command failed" : "Running"
}
if (/^(?:read_file|read)$/u.test(name)) return "Read"
if (/^(?:write_file|write)$/u.test(name)) return phase === "end" ? "Edited" : "Editing"
if (/^(?:edit_file|apply_patch|edit)$/u.test(name)) return phase === "end" ? "Edited" : "Editing"
if (/^(?:spawn|spawn_agent)$/u.test(name)) {
return phase === "end" ? "Delegated" : phase === "error" ? "Delegation failed" : "Delegating"
}
if (name === "web_search") return "Search web"
if (name === "rg") return phase === "end" ? "Searched files" : phase === "error" ? "Search failed" : "Searching files"
if (name === "web_fetch") return "Fetch"
return name
}
function toolDetail(
name: string,
args: Record<string, unknown>,
result: Record<string, unknown>,
options: ToolRenderOptions,
): string {
if (/^(?:exec|exec_command|shell|run_command)$/u.test(name)) {
return compact(args.command ?? args.cmd ?? result.output)
}
if (/^(?:read_file|write_file|edit_file|apply_patch|read|write|edit)$/u.test(name)) {
return compactPath(args.path ?? args.file_path ?? result.path, options.workspace)
}
if (/^(?:spawn|spawn_agent)$/u.test(name)) return compact(args.label ?? args.task, 56)
if (name === "web_search") return compact(args.query ?? args.q)
if (name === "rg" && Array.isArray(args.args)) {
return compact(args.args.map((arg) =>
typeof arg === "string" && arg && !/[\s"']/u.test(arg) ? arg : JSON.stringify(arg),
).join(" "))
}
if (name === "web_fetch") return compact(args.url)
if (/session/u.test(name)) return compact(args.session_key ?? args.chat_id ?? args.query)
if (Object.keys(args).length) return compact(args)
return Object.keys(result).length ? compact(result) : ""
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: {}
}
function compact(value: unknown, limit = 88): string {
if (value == null || value === "") return ""
const serialized = typeof value === "string" ? value : JSON.stringify(value)
const text = (serialized || String(value)).replace(/\s+/gu, " ").trim()
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text
}
function compactPath(value: unknown, workspace?: string): string {
if (value == null || value === "") return ""
const normalized = String(value).replace(/\\/gu, "/").replace(/\/+$/u, "")
const relative = workspaceRelativePath(normalized, workspace)
if (relative.length <= PATH_DETAIL_LIMIT) return relative
const parts = relative.split("/").filter(Boolean)
let tail = parts.pop() || relative
if (tail.length + 1 >= PATH_DETAIL_LIMIT) {
return `…${tail.slice(-(PATH_DETAIL_LIMIT - 1))}`
}
while (parts.length) {
const candidate = `${parts.at(-1)}/${tail}`
if (`…/${candidate}`.length > PATH_DETAIL_LIMIT) break
tail = candidate
parts.pop()
}
return `…/${tail}`
}
function workspaceRelativePath(path: string, workspace?: string): string {
if (!workspace) return path
const base = workspace.replace(/\\/gu, "/").replace(/\/+$/u, "")
const caseInsensitive = /^[a-z]:\//iu.test(path) || /^[a-z]:\//iu.test(base)
const comparedPath = caseInsensitive ? path.toLowerCase() : path
const comparedBase = caseInsensitive ? base.toLowerCase() : base
if (comparedPath === comparedBase) return path.split("/").at(-1) || path
if (comparedPath.startsWith(`${comparedBase}/`)) return path.slice(base.length + 1)
return path
}
+783
View File
@@ -0,0 +1,783 @@
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications"
import {
BoxRenderable,
CodeRenderable,
MarkdownRenderable,
RGBA,
ScrollBoxRenderable,
StyledText,
SyntaxStyle,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
type TreeSitterClient,
} from "@opentui/core"
import type {
ContextCompaction,
FileEditEvent,
HistoryMessage,
MediaAttachment,
ToolProgressEvent,
} from "../client"
import { renderLatexAsUnicode } from "./latex"
import { hideScrollbars } from "./scrollbox"
import { mergeToolEvent, renderToolEvent } from "./tool-renderers"
export interface TranscriptTheme {
text: ColorInput
muted: ColorInput
error: ColorInput
user: ColorInput
userBackground: ColorInput | null
border: ColorInput
syntax: SyntaxStyle
}
export interface TranscriptHeader {
workspace: string
version: string
}
export interface TranscriptNavigation {
awayFromBottom: boolean
unseenOutput: boolean
}
interface Activity {
text: TextRenderable
lines: string[]
keys: Map<string, number>
expanded: boolean
events: Map<string, ToolProgressEvent>
}
interface ActivityPreviewItem {
text: string
steps: number
group?: string
}
const ACTIVITY_PREVIEW_LINES = 4
// OpenTUI renders at 30 FPS. Re-parsing the entire Markdown buffer for every
// provider token turns long answers into quadratic work without producing any
// additional visible frames. Paint the first token immediately, then coalesce
// subsequent deltas to the renderer cadence.
const STREAM_FLUSH_MS = 32
const CODE_RAIL_INDENT = 2
export interface UserMessageMedia {
kind?: MediaAttachment["kind"]
name?: string
}
interface UserMessageProjection {
imageLabels: string[]
attachmentNames: string[]
}
function projectUserMessage(media: readonly UserMessageMedia[]): UserMessageProjection {
const imageNames: Array<string | undefined> = []
const attachmentNames: string[] = []
for (const item of media) {
// Outbound TUI media has no explicit kind because this path currently only
// sends clipboard images. Gateway and history media carry the kind.
if (item.kind === undefined || item.kind === "image") imageNames.push(item.name)
else if (item.name) attachmentNames.push(item.name)
}
const used = new Set<number>()
let next = 1
const imageLabels = imageNames.map((name) => {
const match = name?.match(/^clipboard-image-(\d+)\.[^.]+$/iu)
const preferred = match ? Number(match[1]) : 0
let index = Number.isSafeInteger(preferred) && preferred > 0 && !used.has(preferred)
? preferred
: next
while (used.has(index)) index += 1
used.add(index)
while (used.has(next)) next += 1
return `[Image #${index}]`
})
return { imageLabels, attachmentNames }
}
/** Projects gateway events into retained, reflowable conversation cells. */
export class Transcript {
readonly root: ScrollBoxRenderable
private live: { row: BoxRenderable; markdown: MarkdownRenderable; content: string } | null = null
private activity: Activity | null = null
private readonly styledText: Array<{
renderable: TextRenderable
tone: "text" | "muted" | "error" | "user"
}> = []
private readonly markdown = new Set<MarkdownRenderable>()
private readonly activities = new Set<Activity>()
private readonly compactions = new Map<string, {
phase: ContextCompaction["phase"]
text: TextRenderable
}>()
private readonly frames = new Set<BoxRenderable>()
private readonly userRows = new Set<BoxRenderable>()
private readonly userMessages = new Set<{
renderable: TextRenderable
content: string
media: UserMessageMedia[]
displayContent?: string
}>()
private readonly userTurnIds = new Set<string>()
private wrote = false
private nextId = 0
private navigation: TranscriptNavigation = { awayFromBottom: false, unseenOutput: false }
private navigationTimer: ReturnType<typeof setTimeout> | null = null
private pendingStream = ""
private streamTimer: ReturnType<typeof setTimeout> | null = null
private codeRailColor: RGBA
constructor(
private readonly renderer: CliRenderer,
private theme: TranscriptTheme,
private readonly treeSitterClient: TreeSitterClient,
private readonly onNavigationChange?: (state: TranscriptNavigation) => void,
private readonly workspace = "",
) {
this.codeRailColor = parseColor(theme.border)
this.root = new ScrollBoxRenderable(renderer, {
id: "nanobot-tui-transcript",
width: "100%",
minHeight: 0,
flexGrow: 0,
scrollX: false,
scrollY: true,
stickyScroll: true,
stickyStart: "bottom",
viewportCulling: true,
contentOptions: {
flexDirection: "column",
minHeight: 0,
paddingTop: 1,
paddingBottom: 1,
paddingLeft: 1,
paddingRight: 1,
},
verticalScrollbarOptions: { visible: false },
horizontalScrollbarOptions: { visible: false },
onMouseScroll: () => this.scheduleNavigationUpdate(),
})
hideScrollbars(this.root)
}
setTheme(theme: TranscriptTheme): void {
const previousSyntax = this.theme.syntax
this.theme = theme
this.codeRailColor = parseColor(theme.border)
for (const { renderable, tone } of this.styledText) renderable.fg = theme[tone]
for (const { text, phase } of this.compactions.values()) {
text.fg = phase === "failed" ? theme.error : theme.muted
}
for (const message of this.userMessages) {
message.renderable.content = this.userMessageContent(
message.content,
message.media,
message.displayContent,
)
}
for (const renderable of this.markdown) {
renderable.fg = theme.text
renderable.syntaxStyle = theme.syntax
}
for (const frame of this.frames) frame.borderColor = theme.border
for (const row of this.userRows) {
row.backgroundColor = theme.userBackground
? parseColor(theme.userBackground)
: RGBA.defaultBackground()
}
// Markdown may still be rendering this frame. Release the prior native
// style only after the renderer reaches idle, matching OpenCode's retained
// theme lifecycle and avoiding both leaks and use-after-free transitions.
void this.renderer.idle().catch(() => {}).finally(() => previousSyntax.destroy())
}
header(options: TranscriptHeader): void {
const row = new BoxRenderable(this.renderer, {
id: this.id("header-row"),
width: "100%",
flexDirection: "column",
border: true,
borderStyle: "rounded",
borderColor: this.theme.border,
paddingLeft: 1,
paddingRight: 1,
})
const title = this.createText(`>_ nanobot v${options.version}`, "text", true)
const context = this.createText(["", options.workspace].join("\n"), "muted")
row.add(title)
row.add(context)
this.root.add(row)
this.frames.add(row)
this.wrote = true
}
reset(header: TranscriptHeader): void {
if (this.navigationTimer) clearTimeout(this.navigationTimer)
this.navigationTimer = null
this.clearStreamTimer()
this.pendingStream = ""
for (const child of [...this.root.getChildren()]) {
this.root.remove(child)
child.destroyRecursively()
}
this.live = null
this.activity = null
this.styledText.length = 0
this.markdown.clear()
this.activities.clear()
this.compactions.clear()
this.frames.clear()
this.userRows.clear()
this.userMessages.clear()
this.userTurnIds.clear()
this.wrote = false
this.nextId = 0
this.navigation = { awayFromBottom: false, unseenOutput: false }
hideScrollbars(this.root)
this.header(header)
this.emitNavigation()
}
history(messages: HistoryMessage[]): void {
for (const message of messages) {
if (message.compaction) this.compaction(message.compaction)
else if (message.role === "user") {
this.user(message.content, message.turnId, message.media)
}
else if (message.role === "assistant") this.assistant(message.content)
else if (message.fileEdits?.length) this.fileEdits(message.fileEdits)
else this.progress(message.content, message.toolEvents)
}
this.finishActivity()
}
async prependHistory(messages: HistoryMessage[]): Promise<void> {
if (messages.length === 0) return
const previousTop = this.root.scrollTop
const previousHeight = this.root.scrollHeight
let index = 1 // Keep the launch header first.
for (const message of messages) {
if (message.compaction) {
if (this.compaction(message.compaction, index)) index += 1
} else if (message.role === "user") {
if (message.turnId && this.userTurnIds.has(message.turnId)) continue
this.writeUser(message.content, message.media, index++)
if (message.turnId) this.userTurnIds.add(message.turnId)
} else if (message.role === "assistant") {
this.writeMarkdown(message.content, false, index++)
} else {
const activity = this.createActivity(index++)
const events: ToolProgressEvent[] = message.fileEdits?.length
? message.fileEdits.map((edit) => ({
call_id: `file:${edit.call_id || edit.path || "unknown"}`,
phase: edit.status === "error" ? "error" : edit.phase,
name: edit.tool || "edit_file",
arguments: { path: edit.path, stat: edit.error || formatDiffStat(edit) },
}))
: message.toolEvents || []
this.updateActivity(activity, message.content, events)
}
}
this.renderer.requestRender()
await this.renderer.idle()
this.root.scrollTop = previousTop + Math.max(0, this.root.scrollHeight - previousHeight)
}
get atTop(): boolean {
return this.root.scrollTop <= 0
}
user(
content: string,
turnId?: string,
media: readonly UserMessageMedia[] = [],
displayContent?: string,
): boolean {
if (turnId && this.userTurnIds.has(turnId)) return false
this.noteOutput()
this.finishActivity()
this.writeUser(content, media, undefined, displayContent)
if (turnId) this.userTurnIds.add(turnId)
return true
}
assistant(content: string): void {
if (!content.trim()) return
this.noteOutput()
this.finishActivity()
this.writeMarkdown(content, false)
}
notice(content: string, error = false): void {
this.noteOutput()
this.finishActivity()
this.writeRole(error ? "×" : "·", content, error ? "error" : "muted")
}
compaction(compaction: ContextCompaction, index?: number): boolean {
let entry = this.compactions.get(compaction.id)
// Hydration can replay a terminal state before an already queued start event.
if (!acceptsCompactionPhase(entry?.phase, compaction.phase)) return false
const added = !entry
if (index === undefined) {
this.noteOutput()
if (added) this.finishActivity()
}
if (!entry) {
const row = this.createRow("compaction")
const text = this.createText("", "muted", false, "compaction-status")
row.add(text)
this.root.add(row, index)
this.wrote = true
entry = { phase: compaction.phase, text }
this.compactions.set(compaction.id, entry)
}
entry.phase = compaction.phase
entry.text.content = compaction.phase === "started"
? " ≋ Compacting conversation…"
: compaction.phase === "succeeded"
? " ✓ Conversation compacted"
: compaction.phase === "cancelled"
? " · Conversation compaction cancelled"
: " × Could not compact conversation"
entry.text.fg = compaction.phase === "failed" ? this.theme.error : this.theme.muted
return added
}
stream(delta: string): void {
if (!delta) return
this.noteOutput()
if (!this.live) {
this.finishActivity()
const markdown = this.createMarkdown("", true, "assistant-stream")
const row = this.writeAssistant(markdown)
this.live = { row, markdown, content: "" }
}
if (!this.live.content && !this.pendingStream) {
this.live.content = delta
this.live.markdown.content = renderLatexAsUnicode(delta)
return
}
this.pendingStream += delta
if (this.streamTimer) return
this.streamTimer = setTimeout(() => this.flushStream(), STREAM_FLUSH_MS)
}
finishStream(fallback = ""): void {
this.flushStream()
if (this.live) {
const content = fallback || this.live.content
// Finalize the retained Markdown node in place. This preserves scroll
// anchors and avoids the one-frame jump caused by replacing the row.
this.live.markdown.content = renderLatexAsUnicode(content)
this.live.markdown.streaming = false
this.live = null
} else if (fallback.trim()) {
this.assistant(fallback)
}
}
reconcileStream(content: string): void {
if (!content || !this.live) return
this.clearStreamTimer()
this.pendingStream = ""
this.live.content = content
this.live.markdown.content = renderLatexAsUnicode(content)
}
progress(content: string, events: ToolProgressEvent[] = []): string {
if (events.length === 0 && !content.split("\n").some((line) => cleanProgress(line))) return ""
this.noteOutput()
if (!this.activity) this.activity = this.createActivity()
return this.updateActivity(this.activity, content, events)
}
fileEdits(edits: FileEditEvent[]): string {
return this.progress("", edits.map((edit) => ({
call_id: `file:${edit.call_id || edit.path || "unknown"}`,
phase: edit.status === "error" ? "error" : edit.phase,
name: edit.tool || "edit_file",
arguments: { path: edit.path, stat: edit.error || formatDiffStat(edit) },
})))
}
finishActivity(): void {
this.activity = null
}
toggleActivityDetails(): boolean | null {
const activity = [...this.activities]
.filter((item) => item.lines.length > ACTIVITY_PREVIEW_LINES)
.at(-1)
if (!activity) return null
activity.expanded = !activity.expanded
this.renderActivity(activity)
return activity.expanded
}
scrollByPage(direction: -1 | 1): void {
this.root.scrollBy(direction * Math.max(3, Math.floor(this.root.height * 0.7)))
this.scheduleNavigationUpdate()
}
scrollToEdge(edge: "top" | "bottom"): void {
this.root.scrollTo(edge === "top" ? 0 : this.root.scrollHeight)
if (edge === "bottom") this.updateNavigation(false, true)
else this.scheduleNavigationUpdate()
}
destroy(): void {
if (this.navigationTimer) clearTimeout(this.navigationTimer)
this.clearStreamTimer()
this.pendingStream = ""
this.live = null
this.activity = null
this.compactions.clear()
this.frames.clear()
this.userRows.clear()
this.userMessages.clear()
this.theme.syntax.destroy()
}
private flushStream(): void {
this.clearStreamTimer()
if (!this.live || !this.pendingStream) return
this.live.content += this.pendingStream
this.pendingStream = ""
this.live.markdown.content = renderLatexAsUnicode(this.live.content)
}
private clearStreamTimer(): void {
if (this.streamTimer) clearTimeout(this.streamTimer)
this.streamTimer = null
}
private noteOutput(): void {
this.updateNavigation(true)
}
private scheduleNavigationUpdate(): void {
if (this.navigationTimer) clearTimeout(this.navigationTimer)
this.navigationTimer = setTimeout(() => {
this.navigationTimer = null
this.updateNavigation(false)
}, 0)
}
private updateNavigation(output: boolean, forceBottom = false): void {
const awayFromBottom = forceBottom ? false : !this.isAtBottom()
const unseenOutput = awayFromBottom
? this.navigation.unseenOutput || output
: false
if (
awayFromBottom === this.navigation.awayFromBottom
&& unseenOutput === this.navigation.unseenOutput
) return
this.navigation = { awayFromBottom, unseenOutput }
this.emitNavigation()
}
private isAtBottom(): boolean {
const bottom = Math.max(0, this.root.scrollHeight - this.root.height)
return this.root.scrollTop >= bottom - 1
}
private emitNavigation(): void {
this.onNavigationChange?.({ ...this.navigation })
}
private id(prefix: string): string {
this.nextId += 1
return `${prefix}-${this.nextId}`
}
private createRow(kind = "row", direction: "column" | "row" = "column"): BoxRenderable {
return new BoxRenderable(this.renderer, {
id: this.id(`${kind}-row`),
width: "100%",
marginTop: this.wrote ? 1 : 0,
flexDirection: direction,
})
}
private createActivity(index?: number): Activity {
const row = this.createRow("activity")
const text = new TextRenderable(this.renderer, {
id: this.id("agent-activity"),
content: "",
width: "100%",
wrapMode: "word",
fg: this.theme.muted,
})
row.add(text)
this.root.add(row, index)
this.styledText.push({ renderable: text, tone: "muted" })
this.wrote = true
const activity = {
text,
lines: [],
keys: new Map<string, number>(),
expanded: false,
events: new Map<string, ToolProgressEvent>(),
}
this.activities.add(activity)
return activity
}
private updateActivity(
activity: Activity,
content: string,
events: ToolProgressEvent[] = [],
): string {
const projected = events.map((event) => {
const key = event.call_id ? `tool:${event.call_id}` : ""
const merged = key ? mergeToolEvent(activity.events.get(key), event) : event
if (key) activity.events.set(key, merged)
return { key, line: renderToolEvent(merged, { workspace: this.workspace }) }
})
const lines = events.length > 0
? projected.map(({ line }) => line).filter(Boolean)
: content.split("\n").map(cleanProgress).filter(Boolean)
for (const [index, line] of lines.entries()) {
const key = projected[index]?.key || undefined
const existing = key ? activity.keys.get(key) : undefined
if (existing !== undefined) {
activity.lines[existing] = line
} else if (line !== activity.lines.at(-1)) {
if (key) activity.keys.set(key, activity.lines.length)
activity.lines.push(line)
}
}
this.renderActivity(activity)
return lines.at(-1) || ""
}
private renderActivity(activity: Activity): void {
if (activity.expanded || activity.lines.length <= ACTIVITY_PREVIEW_LINES) {
activity.text.content = activity.lines.join("\n")
return
}
const visible = activityPreview(activity.lines).slice(-(ACTIVITY_PREVIEW_LINES - 1))
const visibleSteps = visible.reduce((total, item) => total + item.steps, 0)
const hidden = activity.lines.length - visibleSteps
const disclosure = hidden > 0 ? `${hidden} earlier steps` : `${activity.lines.length} steps`
activity.text.content = [
` … ${disclosure} · Ctrl+O expand`,
...visible.map((item) => item.text),
].join("\n")
}
private createText(
content: string | StyledText,
tone: "text" | "muted" | "error" | "user",
bold = false,
id = "text",
): TextRenderable {
const text = new TextRenderable(this.renderer, {
id: this.id(id),
content,
width: "100%",
wrapMode: "word",
fg: this.theme[tone],
attributes: bold ? TextAttributes.BOLD : 0,
})
this.styledText.push({ renderable: text, tone })
return text
}
private writeRole(
marker: string,
content: string | StyledText,
tone: "muted" | "error" | "user",
index?: number,
): TextRenderable {
const row = this.createRow(tone === "user" ? "user" : "notice", "row")
if (tone === "user") {
row.backgroundColor = this.theme.userBackground
? parseColor(this.theme.userBackground)
: RGBA.defaultBackground()
this.userRows.add(row)
}
const prefix = this.createText(marker, tone, true, "role-marker")
prefix.width = 2
prefix.flexShrink = 0
const text = this.createText(content, tone === "user" ? "text" : tone, false, "role-content")
text.width = "auto"
text.minWidth = 0
text.flexGrow = 1
row.add(prefix)
row.add(text)
this.root.add(row, index)
this.wrote = true
return text
}
private writeUser(
content: string,
media: readonly UserMessageMedia[] = [],
index?: number,
displayContent?: string,
): void {
const retainedMedia = [...media]
const renderable = this.writeRole(
"›",
this.userMessageContent(content, retainedMedia, displayContent),
"user",
index,
)
this.userMessages.add({ renderable, content, media: retainedMedia, displayContent })
}
private userMessageContent(
content: string,
media: readonly UserMessageMedia[],
displayContent?: string,
): StyledText {
const { imageLabels, attachmentNames } = projectUserMessage(media)
const chunks: TextChunk[] = []
const append = (text: string) => {
if (text) chunks.push({ __isChunk: true, text })
}
const nextLine = () => {
if (chunks.length) append("\n")
}
if (displayContent !== undefined) {
const ranges = imageLabels
.map((label) => ({ label, start: displayContent.indexOf(label) }))
.filter(({ start }) => start >= 0)
.sort((left, right) => left.start - right.start)
let cursor = 0
for (const { label, start } of ranges) {
append(displayContent.slice(cursor, start))
chunks.push({
__isChunk: true,
text: label,
fg: parseColor(this.theme.user),
attributes: TextAttributes.BOLD,
})
cursor = start + label.length
}
append(displayContent.slice(cursor))
} else {
append(content)
}
if (displayContent === undefined && imageLabels.length) {
if (chunks.length) append(" ")
for (const [index, label] of imageLabels.entries()) {
if (index > 0) append(" ")
chunks.push({
__isChunk: true,
text: label,
fg: parseColor(this.theme.user),
attributes: TextAttributes.BOLD,
})
}
}
if (attachmentNames.length) {
nextLine()
append(`Attachments: ${attachmentNames.join(", ")}`)
}
return new StyledText(chunks)
}
private decorateCodeBlock(code: CodeRenderable): CodeRenderable {
code.marginLeft = CODE_RAIL_INDENT
const render = code.render.bind(code)
code.render = (buffer, deltaTime) => {
render(buffer, deltaTime)
for (let row = 0; row < code.height; row += 1) {
buffer.drawText(
"│",
code.screenX - CODE_RAIL_INDENT,
code.screenY + row,
this.codeRailColor,
)
}
}
return code
}
private createMarkdown(content: string, streaming: boolean, id = "markdown"): MarkdownRenderable {
const markdown = new MarkdownRenderable(this.renderer, {
id: this.id(id),
content: renderLatexAsUnicode(content),
width: "auto",
minWidth: 0,
flexGrow: 1,
flexShrink: 1,
fg: this.theme.text,
syntaxStyle: this.theme.syntax,
streaming,
internalBlockMode: "top-level",
renderNode: (token, context) => {
if (token.type !== "code") return undefined
const code = context.defaultRender()
if (!(code instanceof CodeRenderable)) return code
return this.decorateCodeBlock(code)
},
tableOptions: {
style: "columns",
widthMode: "full",
columnFitter: "balanced",
wrapMode: "word",
},
treeSitterClient: this.treeSitterClient,
})
this.markdown.add(markdown)
return markdown
}
private writeMarkdown(content: string, streaming: boolean, index?: number): void {
this.writeAssistant(this.createMarkdown(content, streaming), index)
}
private writeAssistant(markdown: MarkdownRenderable, index?: number): BoxRenderable {
const row = this.createRow("assistant", "row")
const prefix = this.createText("•", "muted", false, "role-marker")
prefix.width = 2
prefix.flexShrink = 0
row.add(prefix)
row.add(markdown)
this.root.add(row, index)
this.wrote = true
return row
}
}
function cleanProgress(value: string): string {
const text = value.trim().replace(/^\*\*(.*?)\*\*$/u, "$1").replace(/\s+/gu, " ")
return text ? ` · ${text}` : ""
}
function activityPreview(lines: readonly string[]): ActivityPreviewItem[] {
const preview: ActivityPreviewItem[] = []
for (const line of lines) {
const match = line.match(/^ ([›✓]) (Read|Edited|Editing) /u)
const group = match ? `${match[1]}:${match[2]}` : undefined
const previous = preview.at(-1)
if (match && group && previous?.group === group) {
previous.steps += 1
previous.text = ` ${match[1]} ${match[2]} ${previous.steps} files`
continue
}
preview.push({ text: line, steps: 1, ...(group ? { group } : {}) })
}
return preview
}
function formatDiffStat(edit: FileEditEvent): string {
const added = typeof edit.added === "number" ? `+${edit.added}` : ""
const deleted = typeof edit.deleted === "number" ? `-${edit.deleted}` : ""
return [added, deleted].filter(Boolean).join(" ")
}