Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/agent-manager-terminal-render-performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Render Agent Manager terminal output with the WebGL renderer instead of the DOM renderer, and pause rendering for terminals hidden in the background
21 changes: 12 additions & 9 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/kilo-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1311,7 +1311,6 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^0.39.0",
"fuzzysort": "3.1.0",
"@kilocode/kilo-gateway": "workspace:*",
"@kilocode/kilo-i18n": "workspace:*",
"@kilocode/kilo-indexing": "workspace:*",
Expand All @@ -1328,10 +1327,12 @@
"@xterm/addon-fit": "0.11.0",
"@xterm/addon-unicode-graphemes": "0.4.0",
"@xterm/addon-web-links": "0.12.0",
"@xterm/addon-webgl": "0.19.0",
"@xterm/xterm": "6.0.0",
"diff": "8.0.4",
"fastest-levenshtein": "^1.0.16",
"friendly-words": "1.3.1",
"fuzzysort": "3.1.0",
"ignore": "^7.0.3",
"js-tiktoken": "^1.0.18",
"lru-cache": "^11.0.2",
Expand Down
119 changes: 118 additions & 1 deletion packages/kilo-vscode/tests/unit/agent-manager-terminal-replay.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,122 @@
import { describe, expect, it } from "bun:test"
import { createInputBuffer, createReplayGate } from "../../webview-ui/agent-manager/terminal/replay"
import { createInputBuffer, createReplayGate, createWriteBatcher } from "../../webview-ui/agent-manager/terminal/replay"

describe("Agent Manager terminal write batcher", () => {
const harness = (opts: { maxBytes?: number; stallFrames?: boolean } = {}) => {
const writes: Array<string | Uint8Array> = []
const cbs: Array<() => void> = []
const pending = new Map<number, () => void>()
const watchdog: Array<() => void> = []
let next = 0
const batcher = createWriteBatcher(
(data, callback) => {
writes.push(data)
cbs.push(callback ?? (() => undefined))
},
opts.stallFrames ? () => 0xffff : (callback) => {
const id = ++next
pending.set(id, callback)
return id
},
(id) => pending.delete(id),
(callback) => {
watchdog.push(callback)
return watchdog.length
},
() => undefined,
opts.maxBytes ?? 1024 * 1024,
)
return {
batcher,
writes,
cbs,
run: () => {
const frames = [...pending.values()]
pending.clear()
for (const frame of frames) frame()
},
triggerWatchdog: () => watchdog.splice(0).forEach((frame) => frame()),
}
}

it("joins one frame of text chunks into a single write", () => {
const h = harness()
h.batcher.write("a")
h.batcher.write("b")
h.batcher.write("c")
expect(h.writes).toEqual([])
h.run()
expect(h.writes).toEqual(["abc"])
})

it("coalesces many frames into separate writes", () => {
const h = harness()
h.batcher.write("1")
h.run()
h.batcher.write("2")
h.run()
expect(h.writes).toEqual(["1", "2"])
})

it("merges binary control frames with text into one byte write", () => {
const h = harness()
h.batcher.write("txt")
h.batcher.write(new Uint8Array([1, 2]))
h.run()
expect(h.writes).toHaveLength(1)
const merged = h.writes[0] as Uint8Array
expect(Array.from(merged)).toEqual([116, 120, 116, 1, 2])
})

it("fires chunk callbacks after the batch write completes", () => {
const h = harness()
let done: string | undefined
h.batcher.write("a", () => (done = "first"))
h.batcher.write("b", () => (done = "second"))
h.run()
expect(h.cbs).toHaveLength(1)
h.cbs[0]!()
expect(done).toBe("second")
})

it("keeps the replay boundary sentinel callback after batch parse", () => {
const h = harness()
let boundary = false
h.batcher.write("replay")
h.batcher.write("", () => (boundary = true))
h.run()
expect(h.writes).toEqual(["replay"])
h.cbs[0]!()
expect(boundary).toBe(true)
})

it("cancel drops pending chunks and stops the scheduled flush", () => {
const h = harness()
h.batcher.write("a")
h.batcher.cancel()
h.run()
expect(h.writes).toEqual([])
h.batcher.write("b")
h.run()
expect(h.writes).toEqual(["b"])
})

it("flushes immediately when the byte cap is exceeded", () => {
const h = harness({ maxBytes: 4 })
h.batcher.write("ab")
expect(h.writes).toEqual([])
h.batcher.write("cd")
expect(h.writes).toEqual(["abcd"])
})

it("watchdog drains the batch when animation frames stall", () => {
const h = harness({ stallFrames: true })
h.batcher.write("x")
expect(h.writes).toEqual([])
h.triggerWatchdog()
expect(h.writes).toEqual(["x"])
})
})

describe("Agent Manager terminal input buffer", () => {
it("sends parser replies first while preserving user input order", () => {
Expand Down
36 changes: 25 additions & 11 deletions packages/kilo-vscode/webview-ui/agent-manager/agent-manager.css
Original file line number Diff line number Diff line change
Expand Up @@ -4878,20 +4878,25 @@ body.vscode-high-contrast-light {
/*
* Stacking layout for xterm terminal tabs.
*
* The hydration invariant (see the render helpers under `terminal/`) requires that
* xterm canvases never leave the paint tree. Both the layer and each
* terminal slot therefore use absolute-positioning + opacity for
* visibility — NEVER `display: none`, because that would detach the
* subtree and stop xterm's internal rAF render loop, causing the
* "press Enter to see content" bug on worktree switches.
* Terminals are never unmounted once mounted; inactive slots are hidden
* with `display: none`. xterm 6's render service observes the screen
* element and pauses hidden terminals' render loops (rAF, model
* updates, GPU draws), then replays a full refresh when a slot becomes
* visible again — the activation fit + refresh in the TerminalTab
* component is insurance on top of that. The historical `display: none`
* avoidance was for the "press Enter to see content" bug, caused by older
* xterm versions not resuming after a paint-tree detach; opacity-only hiding
* instead kept the render loop running at full rate for output no one
* sees (such as background setup scripts), which is measurable on the
* main thread.
*
* Stack: position:relative container hosting the main pane, review,
* and side panel. Sits below the tab bar inside `.am-detail`.
* Layer: absolute-positioned overlay covering the main pane.
* `pointer-events: none` when no terminal is active, letting
* clicks fall through to the chat behind it.
* Slots: absolute-positioned and stacked inside the layer; only the
* active one is opaque and receives pointer events.
* active one is displayed and receives pointer events.
*/

.am-detail-stack {
Expand Down Expand Up @@ -4921,9 +4926,17 @@ body.vscode-high-contrast-light {
}

.am-terminal-slot {
/* Hidden slots are display:none, not opacity:0. xterm 6's render
service observes the screen element and pauses its render loop for
non-intersecting terminals (rAF loop, model updates, WebGL draws),
then replays a full refresh when the slot becomes visible again.
Opacity-only hiding kept the loop running at full rate for output
no one sees, such as background setup scripts streaming while the
user works in another context's terminal. */
position: absolute;
inset: 0;
display: flex;
display: none;
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
flex-direction: column;
min-height: 0;
min-width: 0;
opacity: 0;
Expand All @@ -4932,16 +4945,17 @@ body.vscode-high-contrast-light {
}

.am-terminal-slot-visible {
display: flex;
opacity: 1;
pointer-events: auto;
z-index: 1;
}

/* Side terminal panel — lives inside .am-diff-panel-wrapper next to the
diff and PR panels. Header reuses .am-diff-header metrics so the
chrome does not shift when switching inspector modes. Visibility is
opacity-only: the xterm render loop dies if the subtree leaves the
paint tree. */
chrome does not shift when switching inspector modes. The panel is
opacity-toggled, its terminal slots flip display (per-slot render
pause, see .am-terminal-slot above). */
.am-side-terminal {
position: absolute;
inset: 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
* panels, so every mode uses the same persisted resize width. The tab row is
* the shared inspector strip used by subagents as well.
*
* Visibility is opacity-based, never unmount: the xterm render loop dies when
* its subtree leaves the paint tree (see `render.tsx`).
* Visibility toggles between none and flex, never unmount: xterm keeps its
* buffer, socket, and parser alive, while xterm's own render observer
* (IntersectionObserver on the screen element) pauses the render loop for
* hidden slots and replays a full refresh when a slot becomes visible
* again. `TerminalTab` still does an explicit fit + refresh on activation
* as insurance (see `render.tsx`).
*/

import type { Accessor, Component } from "solid-js"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import { Component, createEffect, onCleanup, onMount } from "solid-js"
import { Terminal } from "@xterm/xterm"
import { FitAddon } from "@xterm/addon-fit"
import { WebglAddon } from "@xterm/addon-webgl"
import { WebLinksAddon } from "@xterm/addon-web-links"
import { ClipboardAddon } from "@xterm/addon-clipboard"
import { UnicodeGraphemesAddon } from "@xterm/addon-unicode-graphemes"
Expand All @@ -21,7 +22,7 @@ import { useVSCode } from "../../src/context/vscode"
import { useLanguage } from "../../src/context/language"
import { formatReviewCommentsMarkdown } from "../../src/utils/review-comment-markdown"
import type { ScriptTerminalStatus, TerminalFont } from "./state"
import { createInputBuffer, createReplayGate } from "./replay"
import { createInputBuffer, createReplayGate, createWriteBatcher } from "./replay"
import { registerTerminalOutput, unregisterTerminalOutput } from "./output"

interface Props {
Expand All @@ -32,13 +33,12 @@ interface Props {
font: TerminalFont
/** Whether this terminal is currently the focused tab.
*
* The xterm subtree always stays in the paint tree (see the layer /
* slot CSS in `terminal/render.tsx` and `agent-manager.css`), so we
* do NOT rely on this prop to rescue the canvas after a hypothetical
* `display: none` detach — the layout is designed so that never
* happens. It's used only to auto-focus on activation and to force
* an xterm re-paint when the slot transitions back to visible after
* sitting behind an occluding layer. */
* Inactive slots are `display: none` (see the layer / slot CSS in
* `terminal/render.tsx` and `agent-manager.css`): xterm's render
* observer pauses invisible terminals and resumes them with a full
* refresh on activation. This prop drives that activation repaint
* plus auto-focus on activation — xterm's own resume is primary, the
* explicit fit + refresh here is insurance. */
active: boolean
/** Side terminals only repaint on activation; focus is restored explicitly
* when that context's remembered focus owner is the terminal. */
Expand Down Expand Up @@ -168,6 +168,16 @@ export const TerminalTab: Component<Props> = (props) => {
const fit = new FitAddon()
term.loadAddon(fit)
term.open(host)
// GPU renderer: the DOM renderer creates one element per cell per row,
// which dominates CPU under sustained PTY output (see profiling of
// streaming script output). WebGL paints the whole viewport in one
// draw batched by first glyph. Falls back to the DOM renderer when
// WebGL2 is unavailable; the catch logs without breaking the session.
try {
term.loadAddon(new WebglAddon())
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
} catch (err) {
log("webgl renderer unavailable, using DOM renderer", err)
}
registerTerminalOutput(props.terminalId, () => {
const buffer = term.buffer.active
return Array.from(
Expand Down Expand Up @@ -296,8 +306,9 @@ export const TerminalTab: Component<Props> = (props) => {
flush()
}, 100)
}
const batcher = createWriteBatcher((data, callback) => term.write(data, callback))
const replay = createReplayGate({
write: (data, callback) => term.write(data, callback),
write: (data, callback) => batcher.write(data, callback),
flush: () => flush(true),
})
const disposeKey = term.onKey(markUser)
Expand Down Expand Up @@ -443,16 +454,14 @@ export const TerminalTab: Component<Props> = (props) => {

// ---- Repaint recovery ----
//
// Every xterm canvas stays mounted in the paint tree (stacking CSS
// guarantees this), but browsers still deprioritise canvases that
// aren't visibly contributing pixels: after another terminal is
// opened on top, or after the window loses focus, the canvas keeps
// its last painted bitmap frozen while xterm's internal buffer goes
// on updating. When we flip the slot back to opacity:1 the canvas
// shows that stale frame until something kicks xterm's render loop
// — historically "press Enter to wake it up". Forcing a
// `fit + refresh(0, rows-1)` once per activation reclaims the paint
// priority; from then on the browser keeps the canvas live.
// Inactive xterm slots are display:none, so their canvases are not
// composed while hidden. xterm's render observer pauses hidden
// terminals and replays a full refresh when they re-enter the tree,
// but browsers still defer some canvas/render work: forcing a
// `fit + refresh(0, rows-1)` once per activation reclaims paint
// priority immediately; from then on the renderer keeps the canvas
// live. Historically the missing insurance step here was "press
// Enter to wake it up".
//
// Focus is opt-in per repaint (`shouldFocus`): repaints triggered by
// resizes or font changes must not yank the cursor out of the chat
Expand Down Expand Up @@ -590,6 +599,7 @@ export const TerminalTab: Component<Props> = (props) => {

onCleanup(() => {
closed = true
batcher.cancel()
unregisterTerminalOutput(props.terminalId)
if (pendingFrame !== null) cancelAnimationFrame(pendingFrame)
if (frame !== undefined) cancelAnimationFrame(frame)
Expand Down
Loading
Loading