Skip to content

The agent that grows with you

perf(desktop): isolate right pane layout work

Johnny105143432523
diff --git a/apps/desktop/e2e/right-pane.spec.ts b/apps/desktop/e2e/right-pane.spec.ts
new file mode 100644
index 00000000000..5447955f452
--- /dev/null
+++ b/apps/desktop/e2e/right-pane.spec.ts
@@ -0,0 +1,138 @@
+import { test, expect } from './test'
+
+import {
+ type MockBackendFixture,
+ setupMockBackend,
+ waitForAppReady,
+} from './fixtures'
+
+let fixture: MockBackendFixture | null = null
+
+test.beforeAll(async () => {
+ fixture = await setupMockBackend()
+ await waitForAppReady(fixture, 120_000)
+})
+
+test.afterAll(async () => {
+ await fixture?.cleanup()
+ fixture = null
+})
+
+test('persistent terminal overlay follows the pane after split dragging', async () => {
+ const page = fixture!.page
+
+ await page.keyboard.press('Control+`')
+ await page.locator('[data-terminal-slot]').waitFor({ state: 'visible', timeout: 30_000 })
+ await page.locator('[data-persistent-terminal] .xterm').waitFor({ state: 'visible', timeout: 30_000 })
+
+ const result = await page.evaluate(async () => {
+ const slot = document.querySelector('[data-terminal-slot]')
+ const overlay = document.querySelector('[data-persistent-terminal]')
+
+ if (!slot || !overlay) {
+ return { drift: -1, moved: 0, target: false }
+ }
+
+ const before = slot.getBoundingClientRect()
+ const target = [...document.querySelectorAll<HTMLElement>('[role="separator"]')]
+ .map(element => {
+ const box = element.getBoundingClientRect()
+ const horizontal = box.width > box.height
+ const center = horizontal
+ ? (box.top + box.bottom) / 2
+ : (box.left + box.right) / 2
+ const sides = horizontal
+ ? [before.top, before.bottom]
+ : [before.left, before.right]
+
+ return {
+ element,
+ box,
+ horizontal,
+ score: Math.min(...sides.map(side => Math.abs(center - side))),
+ }
+ })
+ .filter(item => item.box.width > 0 && item.box.height > 0)
+ .sort((a, b) => a.score - b.score)[0]
+
+ if (!target) {
+ return { drift: -1, moved: 0, target: false }
+ }
+
+ const x = target.box.left + target.box.width / 2
+ const y0 = target.box.top + target.box.height / 2
+ const nearestSide = target.horizontal
+ ? Math.abs(y0 - before.top) < Math.abs(y0 - before.bottom)
+ ? 'top'
+ : 'bottom'
+ : Math.abs(x - before.left) < Math.abs(x - before.right)
+ ? 'left'
+ : 'right'
+ const deltaX = nearestSide === 'left' ? -1 : nearestSide === 'right' ? 1 : 0
+ const deltaY = nearestSide === 'top' ? -1 : nearestSide === 'bottom' ? 1 : 0
+ let currentX = x
+ let y = y0
+ const pointer = {
+ bubbles: true,
+ cancelable: true,
+ pointerId: 71,
+ pointerType: 'mouse',
+ isPrimary: true,
+ button: 0,
+ buttons: 1,
+ }
+
+ target.element.dispatchEvent(
+ new PointerEvent('pointerdown', { ...pointer, clientX: x, clientY: y }),
+ )
+
+ for (let index = 0; index < 24; index += 1) {
+ currentX += deltaX
+ y += deltaY
+ window.dispatchEvent(
+ new PointerEvent('pointermove', {
+ ...pointer,
+ clientX: currentX,
+ clientY: y,
+ }),
+ )
+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()))
+ }
+
+ window.dispatchEvent(
+ new PointerEvent('pointerup', {
+ ...pointer,
+ buttons: 0,
+ clientX: currentX,
+ clientY: y,
+ }),
+ )
+ await new Promise<void>(resolve => setTimeout(resolve, 350))
+ await new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ )
+
+ const next = slot.getBoundingClientRect()
+ const fixed = overlay.getBoundingClientRect()
+
+ return {
+ drift: Math.max(
+ Math.abs(next.top - fixed.top),
+ Math.abs(next.left - fixed.left),
+ Math.abs(next.width - fixed.width),
+ Math.abs(next.height - fixed.height),
+ ),
+ moved: Math.max(
+ Math.abs(next.top - before.top),
+ Math.abs(next.left - before.left),
+ Math.abs(next.width - before.width),
+ Math.abs(next.height - before.height),
+ ),
+ target: true,
+ }
+ })
+
+ expect(result.target).toBe(true)
+ expect(result.moved).toBeGreaterThan(10)
+ expect(result.drift).toBeLessThanOrEqual(1)
+})
diff --git a/apps/desktop/scripts/perf/README.md b/apps/desktop/scripts/perf/README.md
index 986595f8b2c..58c1ca5bc17 100644
--- a/apps/desktop/scripts/perf/README.md
+++ b/apps/desktop/scripts/perf/README.md
@@ -53,6 +53,7 @@ directly via `window.__PERF_DRIVE__`, so no LLM credits are spent.
| `transcript` | ci | large-transcript mount + paint cost | (new) |
| `render-churn` | ci | per-component render attribution + store churn while N tabs stream | (new) |
| `idle-cost` | report | busy-but-silent tiles: idle commit rate, + fps while resizing / typing | (new) |
+| `right-pane` | report | file tree + persistent xterm tabs under chat/terminal output and split dragging | (new) |
| `cold-start` | cold | launch → CDP → driver → first paint (fresh spawn/run) | (new) |
| `first-token` | backend | Enter → first assistant token painted (TTFT) | (new) |
| `submit` | backend | Enter → cleared → user msg painted, scroll jump | measure-submit, measure-jump |
diff --git a/apps/desktop/scripts/perf/scenarios/index.mjs b/apps/desktop/scripts/perf/scenarios/index.mjs
index d03ad457fde..01ca3be3841 100644
--- a/apps/desktop/scripts/perf/scenarios/index.mjs
+++ b/apps/desktop/scripts/perf/scenarios/index.mjs
@@ -8,6 +8,7 @@ import keystroke from './keystroke.mjs'
import multitab from './multitab.mjs'
import profileSwitch from './profile-switch.mjs'
import renderChurn from './render-churn.mjs'
+import rightPane from './right-pane.mjs'
import sessionLoad from './session-load.mjs'
import sessionSwitch from './session-switch.mjs'
import stream from './stream.mjs'
@@ -22,6 +23,7 @@ export const SCENARIOS = {
[transcript.name]: transcript,
[multitab.name]: multitab,
[renderChurn.name]: renderChurn,
+ [rightPane.name]: rightPane,
[idleCost.name]: idleCost,
[coldStart.name]: coldStart,
[firstToken.name]: firstToken,
diff --git a/apps/desktop/scripts/perf/scenarios/right-pane.mjs b/apps/desktop/scripts/perf/scenarios/right-pane.mjs
new file mode 100644
index 00000000000..411b283c9ad
--- /dev/null
+++ b/apps/desktop/scripts/perf/scenarios/right-pane.mjs
@@ -0,0 +1,315 @@
+// File-tree + terminal workspace stress. This is the regression scene for the
+// desktop symptom where opening the project tree/terminal made the whole page
+// hitch while chat and PTY output continued.
+//
+// It mounts a real project tree, one PTY plus multiple persistent xterm tabs,
+// streams chat and terminal output together, mutates Git decoration state, and
+// drags the terminal split. The debug probe records the specific work we care
+// about rather than inferring it from CPU alone:
+// - fixed-overlay measurements
+// - active/hidden xterm fits
+// - ProjectTree + per-path row renders
+// - frame pacing / slow frames
+//
+// npm run perf -- right-pane --spawn --prod --runs 3
+
+import { dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { sleep } from '../lib/cdp.mjs'
+import { frameHistogram, percentile } from '../lib/stats.mjs'
+
+const DEFAULT_CWD = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
+
+const RECORDERS = `
+ (() => {
+ window.__RP_FRAME_GEN__ = (window.__RP_FRAME_GEN__ || 0) + 1
+ const generation = window.__RP_FRAME_GEN__
+ window.__RP_FRAMES__ = { times: [], stop: false }
+ let last = performance.now()
+ const tick = () => {
+ if (window.__RP_FRAME_GEN__ !== generation || window.__RP_FRAMES__.stop) return
+ const now = performance.now()
+ window.__RP_FRAMES__.times.push(now - last)
+ last = now
+ requestAnimationFrame(tick)
+ }
+ requestAnimationFrame(tick)
+
+ window.__RP_LONG__ = { entries: [], stop: false }
+ try {
+ const observer = new PerformanceObserver(list => {
+ if (window.__RP_LONG__.stop) return
+ for (const entry of list.getEntries()) {
+ window.__RP_LONG__.entries.push({ duration: entry.duration, startTime: entry.startTime })
+ }
+ })
+ observer.observe({ entryTypes: ['longtask'] })
+ window.__RP_LONG__.observer = observer
+ } catch {}
+ return 'armed'
+ })()
+`
+
+const COLLECT_RECORDERS = `
+ (() => {
+ window.__RP_FRAMES__.stop = true
+ window.__RP_LONG__.stop = true
+ try { window.__RP_LONG__.observer && window.__RP_LONG__.observer.disconnect() } catch {}
+ return JSON.stringify({ frames: window.__RP_FRAMES__.times, longtasks: window.__RP_LONG__.entries })
+ })()
+`
+
+const START_COUNTERS = `window.__RIGHT_PANE_PERF__.start(); 'recording'`
+const SNAPSHOT_COUNTERS = `
+ (() => {
+ window.__RIGHT_PANE_PERF__.stop()
+ return JSON.stringify(window.__RIGHT_PANE_PERF__.snapshot())
+ })()
+`
+
+const DRAG_TERMINAL_SPLIT = `
+ (async () => {
+ const slot = document.querySelector('[data-terminal-slot]')
+ const overlay = document.querySelector('[data-persistent-terminal]')
+ if (!slot || !overlay) return JSON.stringify({ target: 'none', drift: -1, moved: 0 })
+
+ const slotBox = slot.getBoundingClientRect()
+ const candidates = [...document.querySelectorAll('[role="separator"]')]
+ .map(element => ({ element, box: element.getBoundingClientRect() }))
+ .filter(item => item.box.width > item.box.height * 3)
+ .sort((a, b) =>
+ Math.abs((a.box.top + a.box.bottom) / 2 - slotBox.top) -
+ Math.abs((b.box.top + b.box.bottom) / 2 - slotBox.top)
+ )
+ const target = candidates[0]
+ if (!target) return JSON.stringify({ target: 'none', drift: -1, moved: 0 })
+
+ const x = target.box.left + target.box.width / 2
+ const y0 = target.box.top + target.box.height / 2
+ let y = y0
+ const pointer = {
+ bubbles: true, cancelable: true, pointerId: 91, pointerType: 'mouse',
+ isPrimary: true, button: 0, buttons: 1
+ }
+ target.element.dispatchEvent(new PointerEvent('pointerdown', { ...pointer, clientX: x, clientY: y }))
+
+ for (let i = 0; i < 24; i += 1) {
+ y -= 1
+ window.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: x, clientY: y }))
+ await new Promise(resolve => requestAnimationFrame(resolve))
+ }
+ for (let i = 0; i < 24; i += 1) {
+ y += 1
+ window.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: x, clientY: y }))
+ await new Promise(resolve => requestAnimationFrame(resolve))
+ }
+ window.dispatchEvent(new PointerEvent('pointerup', { ...pointer, buttons: 0, clientX: x, clientY: y }))
+ // Track-size transitions continue briefly after pointerup. Wait through
+ // that animation, then give the overlay its normal two-frame calibration.
+ await new Promise(resolve => setTimeout(resolve, 350))
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))
+
+ const a = slot.getBoundingClientRect()
+ const b = overlay.getBoundingClientRect()
+ const drift = Math.max(
+ Math.abs(a.top - b.top),
+ Math.abs(a.left - b.left),
+ Math.abs(a.width - b.width),
+ Math.abs(a.height - b.height)
+ )
+ return JSON.stringify({ target: 'horizontal-separator', drift, moved: 24 })
+ })()
+`
+
+async function waitFor(cdp, expression, label, timeoutMs = 20000) {
+ const deadline = Date.now() + timeoutMs
+
+ while (Date.now() < deadline) {
+ if (await cdp.eval(expression)) {
+ return
+ }
+
+ await sleep(100)
+ }
+
+ throw new Error(`right-pane timed out waiting for ${label}`)
+}
+
+const trimWarmup = (frames, warmupMs = 300) => {
+ const kept = []
+ let elapsed = 0
+
+ for (const frame of frames) {
+ elapsed += frame
+
+ if (elapsed >= warmupMs) {
+ kept.push(frame)
+ }
+ }
+
+ return kept
+}
+
+export default {
+ name: 'right-pane',
+ tier: 'report',
+ description: 'Project tree + persistent terminal tabs under chat/terminal output and split dragging.',
+ async run(cdp, opts = {}) {
+ const cwd = resolve(String(opts.cwd ?? DEFAULT_CWD))
+ const terminalCount = Math.max(2, Number(opts.terminals ?? 3))
+ const tokens = Number(opts.tokens ?? 90)
+ const outputChunks = Number(opts.outputChunks ?? 160)
+
+ await cdp.send('Runtime.enable')
+
+ const ready = await cdp.eval(
+ `!!(window.__PERF_DRIVE__?.rightPaneSetup && window.__RIGHT_PANE_PERF__ && window.__HERMES_LAYOUT_TREE__)`
+ )
+
+ if (!ready) {
+ throw new Error('right-pane needs a dev renderer or a production build with VITE_PERF_PROBE=1.')
+ }
+
+ let setup
+
+ try {
+ setup = await cdp.eval(
+ `window.__PERF_DRIVE__.rightPaneSetup(${JSON.stringify({ cwd, terminals: terminalCount })})`
+ )
+ await cdp.eval(`window.__HERMES_LAYOUT_TREE__.reveal('files'); window.__HERMES_LAYOUT_TREE__.reveal('terminal')`)
+ await waitFor(cdp, `!!document.querySelector('[data-project-tree]')`, 'project tree')
+ await waitFor(
+ cdp,
+ `!!document.querySelector('[data-terminal-slot]') && !!document.querySelector('[data-persistent-terminal]')`,
+ 'persistent terminal'
+ )
+ await waitFor(
+ cdp,
+ `document.querySelectorAll('[data-terminal] .xterm').length >= ${terminalCount}`,
+ `${terminalCount} mounted xterms`,
+ 30000
+ )
+ await sleep(1200)
+
+ // Activate every keep-alive tab once, then return to the output tab.
+ // Each activation should restore exactly one fit; inactive tabs must stay
+ // at zero even while another tab resizes or writes output.
+ await cdp.eval(START_COUNTERS)
+
+ for (const id of setup.terminalIds) {
+ await cdp.eval(`window.__PERF_DRIVE__.rightPaneSelect(${JSON.stringify(id)})`)
+ await sleep(180)
+ }
+
+ const activation = JSON.parse(await cdp.eval(SNAPSHOT_COUNTERS))
+
+ await cdp.eval(RECORDERS)
+
+ // Chat DOM churn is deliberately measured in its own counter window:
+ // terminal positioning should receive no wakeups from transcript changes.
+ await cdp.eval(START_COUNTERS)
+ await cdp.eval(
+ `window.__PERF_DRIVE__.stream({
+ chunk: 'Right pane streaming sentence with **bold** and \`code\`.\\n\\n',
+ intervalMs: 16,
+ totalTokens: ${tokens},
+ flushMinMs: 33
+ })`
+ )
+ await cdp.eval(`
+ (() => {
+ let n = 0
+ window.__RP_OUTPUT_TIMER__ = setInterval(() => {
+ window.__PERF_DRIVE__.rightPaneWrite(
+ ${JSON.stringify(setup.procId)},
+ 'terminal output line ' + n + ' ........................................\\r\\n'
+ )
+ n += 1
+ if (n >= ${outputChunks}) clearInterval(window.__RP_OUTPUT_TIMER__)
+ }, 16)
+ return 'writing'
+ })()
+ `)
+ await sleep(Math.max(tokens, outputChunks) * 16 + 900)
+ const stream = JSON.parse(await cdp.eval(SNAPSHOT_COUNTERS))
+
+ // An unrelated Git status publication should render neither the tree root
+ // nor any visible row. A status for one visible path should touch only it.
+ await cdp.eval(START_COUNTERS)
+ await cdp.eval(`window.__PERF_DRIVE__.rightPaneGit('__right_pane_unrelated__.txt', 'modified')`)
+ await sleep(250)
+ const unrelatedGit = JSON.parse(await cdp.eval(SNAPSHOT_COUNTERS))
+
+ const visiblePath = await cdp.eval(
+ `document.querySelector('[data-project-tree] [title]')?.getAttribute('title') || ''`
+ )
+ let affectedGit = { counts: { 'project-tree-render': 0, 'project-tree-row-render': 0 }, rows: {} }
+
+ if (visiblePath) {
+ const relative = String(visiblePath).startsWith(`${cwd}/`)
+ ? String(visiblePath).slice(cwd.length + 1)
+ : String(visiblePath)
+ await cdp.eval(START_COUNTERS)
+ await cdp.eval(`window.__PERF_DRIVE__.rightPaneGit(${JSON.stringify(relative)}, 'modified')`)
+ await sleep(250)
+ affectedGit = JSON.parse(await cdp.eval(SNAPSHOT_COUNTERS))
+ }
+
+ await cdp.eval(START_COUNTERS)
+ const drag = JSON.parse(await cdp.eval(DRAG_TERMINAL_SPLIT))
+ const dragCounters = JSON.parse(await cdp.eval(SNAPSHOT_COUNTERS))
+ const recorded = JSON.parse(await cdp.eval(COLLECT_RECORDERS))
+ const frames = trimWarmup(recorded.frames)
+ const longtasks = recorded.longtasks.map(entry => entry.duration)
+ const streamCounts = stream.counts
+ const activationCounts = activation.counts
+ const unrelatedCounts = unrelatedGit.counts
+ const affectedRows = Object.values(affectedGit.rows).reduce((sum, count) => sum + count, 0)
+ const affectedPaths = Object.keys(affectedGit.rows).length
+
+ if (drag.target === 'none') {
+ throw new Error('right-pane found no horizontal terminal split separator.')
+ }
+
+ return {
+ metrics: {
+ chat_terminal_measures: streamCounts['terminal-measure'],
+ hidden_terminal_fits: activationCounts['terminal-fit-hidden'] + streamCounts['terminal-fit-hidden'],
+ activation_fit_mismatch: Math.abs(activationCounts['terminal-fit-active'] - setup.terminalIds.length),
+ unrelated_tree_renders: unrelatedCounts['project-tree-render'],
+ unrelated_row_renders: unrelatedCounts['project-tree-row-render'],
+ affected_tree_renders: affectedGit.counts['project-tree-render'],
+ affected_row_path_excess: Math.max(0, affectedPaths - 1),
+ terminal_drift_px: Math.round(drag.drift * 10) / 10,
+ frame_p95_ms: Math.round(percentile(frames, 0.95) * 10) / 10,
+ frame_p99_ms: Math.round(percentile(frames, 0.99) * 10) / 10,
+ slow_frames_33: frames.filter(frame => frame > 33).length,
+ longtask_max_ms: Math.round((longtasks.length ? Math.max(...longtasks) : 0) * 10) / 10
+ },
+ detail: {
+ cwd,
+ terminals: setup.terminalIds.length,
+ activation,
+ stream,
+ unrelatedGit,
+ affectedGit,
+ affectedRows,
+ drag,
+ dragCounters,
+ frameHistogram: frameHistogram(frames),
+ frames: frames.length
+ }
+ }
+ } finally {
+ await cdp.eval(`
+ (() => {
+ clearInterval(window.__RP_OUTPUT_TIMER__)
+ window.__RIGHT_PANE_PERF__?.stop()
+ window.__PERF_DRIVE__?.reset()
+ return 'cleaned'
+ })()
+ `)
+ }
+ }
+}
diff --git a/apps/desktop/src/app/chat/perf-probe.tsx b/apps/desktop/src/app/chat/perf-probe.tsx
index 987d89fb428..e61e1d52a5b 100644
--- a/apps/desktop/src/app/chat/perf-probe.tsx
+++ b/apps/desktop/src/app/chat/perf-probe.tsx
@@ -1,7 +1,19 @@
import { Profiler, type ProfilerOnRenderCallback, type ReactNode } from 'react'
+import { $terminalTakeover, setTerminalTakeover } from '@/app/right-sidebar/store'
+import { writeAgentTerminalChunk } from '@/app/right-sidebar/terminal/agent-terminal-stream'
+import {
+ $activeTerminalId,
+ $terminals,
+ createTerminal,
+ ensureAgentTerminal,
+ selectTerminal,
+ type TerminalEntry
+} from '@/app/right-sidebar/terminal/terminals'
+import type { HermesRepoStatus } from '@/global'
+import { $repoStatus } from '@/store/coding-status'
import { $gateway } from '@/store/gateway'
-import { $messages, setBusy, setMessages } from '@/store/session'
+import { $currentCwd, $messages, setBusy, setCurrentCwdTransient, setMessages } from '@/store/session'
type Sample = {
id: string
@@ -38,6 +50,12 @@ declare global {
* backend) doesn't contaminate frame-pacing numbers.
*/
connected: () => boolean
+ /** Mount files + multiple xterms for the synthetic right-pane scenario. */
+ rightPaneSetup: (opts: { cwd: string; terminals?: number }) => { procId: string; terminalIds: string[] }
+ rightPaneGit: (path: string, kind?: 'added' | 'conflicted' | 'modified') => void
+ rightPaneReset: () => void
+ rightPaneSelect: (id: string) => void
+ rightPaneWrite: (procId: string, chunk: string) => void
reset: () => void
snapshotMsgs: () => number
}
@@ -102,11 +120,34 @@ if (typeof window !== 'undefined' && !window.__PERF_DRIVE__) {
let baseline: ReturnType<typeof $messages.get> | null = null
let activeHandle: SyntheticDriverHandle | null = null
+ let rightPaneBaseline:
+ | null
+ | {
+ activeTerminalId: null | string
+ cwd: string
+ repoStatus: HermesRepoStatus | null
+ takeover: boolean
+ terminals: readonly TerminalEntry[]
+ } = null
+
const stop = () => {
activeHandle = null
setBusy(false)
}
+ const resetRightPane = () => {
+ if (!rightPaneBaseline) {
+ return
+ }
+
+ setTerminalTakeover(rightPaneBaseline.takeover)
+ $terminals.set(rightPaneBaseline.terminals)
+ $activeTerminalId.set(rightPaneBaseline.activeTerminalId)
+ $repoStatus.set(rightPaneBaseline.repoStatus)
+ setCurrentCwdTransient(rightPaneBaseline.cwd)
+ rightPaneBaseline = null
+ }
+
// One synthetic turn's worth of mixed markdown — prose, a list, a fenced
// code block, inline code, a link, and a short table — so a loaded transcript
// exercises the same render cost (Streamdown blocks, code cards) a real one
@@ -166,6 +207,65 @@ if (typeof window !== 'undefined' && !window.__PERF_DRIVE__) {
return false
}
},
+ rightPaneGit: (path, kind = 'modified') => {
+ const file = {
+ conflicted: kind === 'conflicted',
+ path,
+ staged: false,
+ unstaged: kind === 'modified',
+ untracked: kind === 'added'
+ }
+
+ $repoStatus.set({
+ added: 0,
+ ahead: 0,
+ behind: 0,
+ branch: 'perf',
+ changed: 1,
+ conflicted: kind === 'conflicted' ? 1 : 0,
+ defaultBranch: 'main',
+ detached: false,
+ files: [file],
+ removed: 0,
+ staged: 0,
+ unstaged: kind === 'modified' ? 1 : 0,
+ untracked: kind === 'added' ? 1 : 0
+ })
+ },
+ rightPaneReset: resetRightPane,
+ rightPaneSelect: selectTerminal,
+ rightPaneSetup: ({ cwd, terminals = 3 }) => {
+ resetRightPane()
+ rightPaneBaseline = {
+ activeTerminalId: $activeTerminalId.get(),
+ cwd: $currentCwd.get(),
+ repoStatus: $repoStatus.get(),
+ takeover: $terminalTakeover.get(),
+ terminals: $terminals.get()
+ }
+
+ setCurrentCwdTransient(cwd)
+ const terminalIds = [createTerminal(cwd)]
+ let procId = ''
+
+ for (let index = 1; index < Math.max(1, terminals); index += 1) {
+ procId = `right-pane-perf-${Date.now()}-${index}`
+ const id = ensureAgentTerminal(procId, `perf output ${index}`)
+
+ if (id) {
+ terminalIds.push(id)
+ }
+ }
+
+ if (procId) {
+ selectTerminal(terminalIds.at(-1) ?? terminalIds[0])
+ }
+
+ setTerminalTakeover(true)
+
+ return { procId, terminalIds }
+ },
+ rightPaneWrite: (procId, chunk) => writeAgentTerminalChunk(procId, chunk),
loadTranscript: (turns = 200) => {
if (!baseline) {
baseline = $messages.get()
@@ -190,6 +290,7 @@ if (typeof window !== 'undefined' && !window.__PERF_DRIVE__) {
},
reset: () => {
activeHandle?.stop()
+ resetRightPane()
if (baseline) {
setMessages(baseline)
diff --git a/apps/desktop/src/app/right-sidebar/files/tree-sizing.test.ts b/apps/desktop/src/app/right-sidebar/files/tree-sizing.test.ts
new file mode 100644
index 00000000000..04e8a8bb47f
--- /dev/null
+++ b/apps/desktop/src/app/right-sidebar/files/tree-sizing.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { projectTreeViewportSize } from './tree'
+
+describe('projectTreeViewportSize', () => {
+ it('uses ResizeObserver contentRect without forcing another layout read', () => {
+ const element = document.createElement('div')
+ const getBoundingClientRect = vi.spyOn(element, 'getBoundingClientRect')
+ const contentRect = { height: 480, width: 320 } as DOMRectReadOnly
+
+ expect(
+ projectTreeViewportSize([{ contentRect, target: element } as unknown as ResizeObserverEntry], element)
+ ).toEqual({
+ height: 480,
+ width: 320
+ })
+ expect(getBoundingClientRect).not.toHaveBeenCalled()
+ })
+
+ it('falls back to a rect when ResizeObserver is unavailable', () => {
+ const element = document.createElement('div')
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
+ height: 240,
+ width: 160
+ } as DOMRect)
+
+ expect(projectTreeViewportSize([], element)).toEqual({ height: 240, width: 160 })
+ })
+})
diff --git a/apps/desktop/src/app/right-sidebar/files/tree.tsx b/apps/desktop/src/app/right-sidebar/files/tree.tsx
index 97d96f267b9..b20bfcaf4b1 100644
--- a/apps/desktop/src/app/right-sidebar/files/tree.tsx
+++ b/apps/desktop/src/app/right-sidebar/files/tree.tsx
@@ -1,12 +1,14 @@
import { useStore } from '@nanostores/react'
import { type KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect, useRef, useState } from 'react'
+import { useMemo } from 'react'
import { type NodeApi, type NodeRendererProps, type RowRendererProps, Tree, type TreeApi } from 'react-arborist'
import { TreeSkeleton } from '@/components/chat/skeletons'
import { Codicon } from '@/components/ui/codicon'
+import { markRightPanePerf } from '@/debug/right-pane-events'
import { useResizeObserver } from '@/hooks/use-resize-observer'
import { cn } from '@/lib/utils'
-import { $repoChangeByPath, type RepoChangeKind } from '@/store/coding-status'
+import { type RepoChangeKind, repoChangeKindForPath } from '@/store/coding-status'
import { $renamingPath, beginInlineRename } from '@/store/file-actions'
import { $revealInTreeRequest } from '@/store/layout'
@@ -55,19 +57,20 @@ export function ProjectTree({
onPreviewFile,
openState
}: ProjectTreeProps) {
+ markRightPanePerf('project-tree-render')
+
const containerRef = useRef<HTMLDivElement | null>(null)
const treeRef = useRef<TreeApi<TreeNode> | null>(null)
const [size, setSize] = useState({ height: 0, width: 0 })
- const changeByPath = useStore($repoChangeByPath)
- const syncTreeSize = useCallback(() => {
+ const syncTreeSize = useCallback((entries: readonly ResizeObserverEntry[]) => {
const el = containerRef.current
if (!el) {
return
}
- const { height, width } = el.getBoundingClientRect()
+ const { height, width } = projectTreeViewportSize(entries, el)
setSize(prev => {
if (prev.height === height && prev.width === width) {
@@ -175,7 +178,12 @@ export function ProjectTree({
}, [])
return (
- <div className="min-h-0 flex-1 overflow-hidden" onKeyDownCapture={handleRenameShortcut} ref={containerRef}>
+ <div
+ className="min-h-0 flex-1 overflow-hidden"
+ data-project-tree=""
+ onKeyDownCapture={handleRenameShortcut}
+ ref={containerRef}
+ >
{size.height > 0 && size.width > 0 ? (
<Tree<TreeNode>
childrenAccessor={node => (node?.isDirectory ? (node.children ?? []) : null)}
@@ -200,7 +208,6 @@ export function ProjectTree({
{props => (
<ProjectTreeRow
{...props}
- changeKind={props.node.data ? changeByPath.get(props.node.data.id) : undefined}
onAttachFile={onActivateFile}
onAttachFolder={onActivateFolder}
onPreviewFile={onPreviewFile}
@@ -215,6 +222,16 @@ export function ProjectTree({
)
}
+export function projectTreeViewportSize(
+ entries: readonly ResizeObserverEntry[],
+ element: HTMLElement
+): { height: number; width: number } {
+ const entry = entries.find(item => item.target === element)
+ const box = entry?.contentRect ?? element.getBoundingClientRect()
+
+ return { height: box.height, width: box.width }
+}
+
function TreeSizingState() {
return <TreeSkeleton />
}
@@ -244,7 +261,6 @@ const CHANGE_TINT: Record<RepoChangeKind, string> = {
}
function ProjectTreeRow({
- changeKind,
dragHandle,
node,
onAttachFile,
@@ -253,13 +269,17 @@ function ProjectTreeRow({
relativeTo,
style
}: NodeRendererProps<TreeNode> & {
- changeKind?: RepoChangeKind
onAttachFile: (path: string) => void
onAttachFolder: (path: string) => void
onPreviewFile?: (path: string) => void
relativeTo?: null | string
}) {
const renamingPath = useStore($renamingPath)
+ const path = node.data?.id ?? ''
+ const changeStore = useMemo(() => repoChangeKindForPath(path), [path])
+ const changeKind: RepoChangeKind | undefined = useStore(changeStore)
+
+ markRightPanePerf('project-tree-row-render', path)
if (!node.data) {
return <div style={style} />
diff --git a/apps/desktop/src/app/right-sidebar/terminal/active-resize.test.ts b/apps/desktop/src/app/right-sidebar/terminal/active-resize.test.ts
new file mode 100644
index 00000000000..27909c2cb03
--- /dev/null
+++ b/apps/desktop/src/app/right-sidebar/terminal/active-resize.test.ts
@@ -0,0 +1,159 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { observeActiveTerminalResize } from './active-resize'
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+function installRaf() {
+ let nextId = 1
+ const frames = new Map<number, FrameRequestCallback>()
+
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ const id = nextId++
+ frames.set(id, callback)
+
+ return id
+ })
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id))
+
+ return {
+ flush() {
+ const pending = [...frames.entries()]
+ frames.clear()
+ pending.forEach(([, callback]) => callback(0))
+ },
+ pending: () => frames.size
+ }
+}
+
+describe('observeActiveTerminalResize', () => {
+ it('fits once on activation and coalesces later resize bursts', () => {
+ const raf = installRaf()
+ const resize = { current: null as ResizeObserverCallback | null }
+ const disconnect = vi.fn()
+
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ resize.current = callback
+ }
+
+ disconnect = disconnect
+ observe = vi.fn((target: Element) => {
+ resize.current?.([{ target } as ResizeObserverEntry], this as unknown as ResizeObserver)
+ })
+ unobserve = vi.fn()
+ } as unknown as typeof ResizeObserver
+ )
+
+ const onFit = vi.fn()
+ const onActivate = vi.fn()
+ const host = document.createElement('div')
+ const dispose = observeActiveTerminalResize(host, { onActivate, onFit })
+
+ // ResizeObserver's initial delivery is absorbed by the activation frame.
+ expect(raf.pending()).toBe(1)
+ raf.flush()
+ expect(onFit).toHaveBeenCalledTimes(1)
+ expect(onActivate).toHaveBeenCalledTimes(1)
+
+ resize.current?.([], {} as ResizeObserver)
+ resize.current?.([], {} as ResizeObserver)
+ resize.current?.([], {} as ResizeObserver)
+ expect(raf.pending()).toBe(1)
+ raf.flush()
+ expect(onFit).toHaveBeenCalledTimes(2)
+
+ dispose()
+ expect(disconnect).toHaveBeenCalledTimes(1)
+ })
+
+ it('cancels activation without fitting when hidden before the first frame', () => {
+ const raf = installRaf()
+
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ disconnect = vi.fn()
+ observe = vi.fn()
+ unobserve = vi.fn()
+ } as unknown as typeof ResizeObserver
+ )
+
+ const onFit = vi.fn()
+
+ const dispose = observeActiveTerminalResize(document.createElement('div'), {
+ onActivate: vi.fn(),
+ onFit
+ })
+
+ dispose()
+
+ raf.flush()
+ expect(onFit).not.toHaveBeenCalled()
+ })
+
+ it('absorbs a real browser-style initial resize delivered after activation', () => {
+ const raf = installRaf()
+ const resize = { current: null as ResizeObserverCallback | null }
+
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ resize.current = callback
+ }
+
+ disconnect = vi.fn()
+ observe = vi.fn()
+ unobserve = vi.fn()
+ } as unknown as typeof ResizeObserver
+ )
+
+ const onFit = vi.fn()
+ observeActiveTerminalResize(document.createElement('div'), { onActivate: vi.fn(), onFit })
+
+ raf.flush()
+ expect(onFit).toHaveBeenCalledTimes(1)
+
+ // Browser initial delivery: the activation fit already covered this size.
+ resize.current?.([], {} as ResizeObserver)
+ expect(raf.pending()).toBe(0)
+
+ // A later real resize schedules exactly one fit.
+ resize.current?.([], {} as ResizeObserver)
+ expect(raf.pending()).toBe(1)
+ raf.flush()
+ expect(onFit).toHaveBeenCalledTimes(2)
+ })
+
+ it('reuses a first-mount fit without fitting again on activation', () => {
+ const raf = installRaf()
+
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ disconnect = vi.fn()
+ observe = vi.fn()
+ unobserve = vi.fn()
+ } as unknown as typeof ResizeObserver
+ )
+
+ const onActivate = vi.fn()
+ const onFit = vi.fn()
+
+ observeActiveTerminalResize(document.createElement('div'), {
+ fitOnActivate: false,
+ onActivate,
+ onFit
+ })
+
+ raf.flush()
+
+ expect(onActivate).toHaveBeenCalledOnce()
+ expect(onFit).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/right-sidebar/terminal/active-resize.ts b/apps/desktop/src/app/right-sidebar/terminal/active-resize.ts
new file mode 100644
index 00000000000..ea68ceda1dc
--- /dev/null
+++ b/apps/desktop/src/app/right-sidebar/terminal/active-resize.ts
@@ -0,0 +1,78 @@
+interface ActiveTerminalResizeOptions {
+ fitOnActivate?: boolean
+ onActivate: () => void
+ onFit: () => void
+}
+
+/**
+ * Observe one visible xterm host.
+ *
+ * Inactive terminals never call this helper, so their preserved DOM/PTY stays
+ * mounted without paying for ResizeObserver delivery or FitAddon work. The
+ * first frame owns activation and ignores the observer's initial delivery;
+ * later resize bursts are coalesced to one fit per animation frame.
+ */
+export function observeActiveTerminalResize(
+ host: HTMLElement,
+ { fitOnActivate = true, onActivate, onFit }: ActiveTerminalResizeOptions
+): () => void {
+ let activated = false
+ let frame = 0
+ let initialResizeDelivered = false
+ let stopped = false
+
+ const scheduleFit = () => {
+ if (!activated || stopped || frame !== 0) {
+ return
+ }
+
+ frame = window.requestAnimationFrame(() => {
+ frame = 0
+
+ if (!stopped) {
+ onFit()
+ }
+ })
+ }
+
+ const observer = new ResizeObserver(() => {
+ // ResizeObserver's initial delivery is asynchronous in browsers and may
+ // arrive before OR after the activation rAF. Activation already fits the
+ // current box, so absorb that first delivery in either ordering.
+ if (!initialResizeDelivered) {
+ initialResizeDelivered = true
+
+ return
+ }
+
+ scheduleFit()
+ })
+
+ observer.observe(host)
+
+ frame = window.requestAnimationFrame(() => {
+ frame = 0
+
+ if (stopped) {
+ return
+ }
+
+ activated = true
+
+ if (fitOnActivate) {
+ onFit()
+ }
+
+ onActivate()
+ })
+
+ return () => {
+ stopped = true
+ observer.disconnect()
+
+ if (frame !== 0) {
+ window.cancelAnimationFrame(frame)
+ frame = 0
+ }
+ }
+}
diff --git a/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx
index c0f718e546c..77eeb480d63 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx
+++ b/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx
@@ -2,6 +2,8 @@ import { act, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { $paneStates } from '@/store/panes'
+
import { PersistentTerminal, TerminalSlot } from './persistent'
vi.mock('./terminals', () => ({
@@ -212,7 +214,8 @@ describe('PersistentTerminal rect tracking', () => {
render(<Harness />)
- expect(mutationObserveCalls.some(call => call.options?.subtree === true)).toBe(true)
+ expect(mutationObserveCalls.length).toBeGreaterThan(0)
+ expect(mutationObserveCalls.every(call => call.options?.subtree === false)).toBe(true)
act(() => {
raf.runNext()
@@ -244,6 +247,27 @@ describe('PersistentTerminal rect tracking', () => {
expect(raf.pending()).toBe(0)
})
+ it('remeasures from an explicit pane-layout state change', () => {
+ const raf = installRaf()
+ const before = $paneStates.get()
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))
+
+ render(<Harness />)
+ raf.runNext()
+ expect(raf.pending()).toBe(0)
+
+ act(() => {
+ $paneStates.set({ ...before, __terminal_rect_test__: { open: true } })
+ })
+
+ expect(raf.pending()).toBe(1)
+
+ act(() => {
+ raf.runNext()
+ $paneStates.set(before)
+ })
+ })
+
it('does not schedule rect RAFs while the Electron window is paused, then resumes when visible', () => {
const raf = installRaf()
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))
diff --git a/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx b/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx
index b5e75978b02..d3a7b0c8290 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx
+++ b/apps/desktop/src/app/right-sidebar/terminal/persistent.tsx
@@ -2,7 +2,10 @@ import { useStore } from '@nanostores/react'
import { atom } from 'nanostores'
import { type CSSProperties, useEffect, useLayoutEffect, useRef, useState } from 'react'
+import { $layoutTree } from '@/components/pane-shell/tree/store'
+import { markRightPanePerf } from '@/debug/right-pane-events'
import { createRendererLoopPauseController } from '@/lib/renderer-loop-pause'
+import { $paneStates } from '@/store/panes'
import { $terminalTakeover } from '../store'
@@ -39,7 +42,7 @@ export function TerminalSlot({ className = SLOT_CLASS }: { className?: string })
}
}, [])
- return <div className={className} ref={ref} />
+ return <div className={className} data-terminal-slot="" ref={ref} />
}
interface PersistentTerminalProps {
@@ -86,6 +89,7 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
let prev: Rect | null = null
let frame = 0
let stopped = false
+ let pendingReason = 'initial'
let pauseController: ReturnType<typeof createRendererLoopPauseController> | null = null
const rendererPaused = () => pauseController?.isPaused() ?? document.visibilityState === 'hidden'
@@ -97,11 +101,12 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
}
}
- const measure = (): boolean => {
+ const measure = (reason: string): boolean => {
if (rendererPaused()) {
return false
}
+ markRightPanePerf('terminal-measure', reason)
const r = slot.getBoundingClientRect()
// floor top/left + ceil right/bottom: overlay always covers the slot's
// full pixel footprint, so half-pixel rects can't leak page bg through.
@@ -123,16 +128,18 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
return false
}
- const scheduleMeasure = () => {
+ const scheduleMeasure = (reason = 'unknown') => {
if (stopped || rendererPaused() || frame !== 0) {
return
}
+ pendingReason = reason
frame = window.requestAnimationFrame(() => {
frame = 0
+ const reason = pendingReason
- if (measure()) {
- scheduleMeasure()
+ if (measure(reason)) {
+ scheduleMeasure('settle')
}
})
}
@@ -144,50 +151,69 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
return
}
- scheduleMeasure()
+ scheduleMeasure('visibility')
}
const observer =
typeof ResizeObserver === 'undefined'
? null
: new ResizeObserver(() => {
- scheduleMeasure()
+ scheduleMeasure('resize-observer')
})
const positionObserver =
typeof MutationObserver === 'undefined'
? null
: new MutationObserver(() => {
- scheduleMeasure()
+ scheduleMeasure('ancestor-mutation')
})
pauseController = createRendererLoopPauseController(handleVisibilityChange)
- if (measure()) {
- scheduleMeasure()
+ if (measure('initial')) {
+ scheduleMeasure('settle')
}
observer?.observe(slot)
+ const handleScroll = () => scheduleMeasure('scroll')
+ const scrollTargets: Array<HTMLElement | Window> = [window]
+ window.addEventListener('scroll', handleScroll)
+
for (let node: HTMLElement | null = slot; node; node = node.parentElement) {
positionObserver?.observe(node, {
attributeFilter: ['class', 'style', 'hidden', 'aria-hidden', 'data-state'],
attributes: true,
childList: true,
- subtree: true
+ subtree: false
})
+ // Scroll does not bubble. Listen only on the slot's own ancestor chain,
+ // so a transcript/file-tree/xterm viewport scroll elsewhere cannot wake
+ // terminal positioning.
+ node.addEventListener('scroll', handleScroll)
+ scrollTargets.push(node)
}
- window.addEventListener('resize', scheduleMeasure)
- window.addEventListener('scroll', scheduleMeasure, true)
+ // Nested layout-tree and pane-state commits can move the slot without
+ // changing its own size. Subscribe to the actual layout authorities instead
+ // of observing every descendant mutation under every ancestor (chat stream
+ // and file-tree updates are unrelated and used to wake this tracker).
+ const unsubscribeLayout = $layoutTree.listen(() => scheduleMeasure('layout-tree'))
+ const unsubscribePanes = $paneStates.listen(() => scheduleMeasure('pane-state'))
+
+ const handleResize = () => scheduleMeasure('window-resize')
+
+ window.addEventListener('resize', handleResize)
return () => {
stopped = true
cancelFrame()
observer?.disconnect()
positionObserver?.disconnect()
- window.removeEventListener('resize', scheduleMeasure)
- window.removeEventListener('scroll', scheduleMeasure, true)
+ unsubscribeLayout()
+ unsubscribePanes()
+ window.removeEventListener('resize', handleResize)
+ scrollTargets.forEach(target => target.removeEventListener('scroll', handleScroll))
pauseController?.dispose()
}
}, [slot])
@@ -215,7 +241,7 @@ export function PersistentTerminal({ onAddSelectionToChat }: PersistentTerminalP
// booting xterm/node-pty at 0×0 starts the shell at 80×24 and spawns a visible
// conhost on Windows. After that `mounted` latches: shells persist while hidden.
return (
- <div aria-hidden={!visible} style={style}>
+ <div aria-hidden={!visible} data-persistent-terminal="" style={style}>
{mounted && <TerminalWorkspace onAddSelectionToChat={onAddSelectionToChat} />}
</div>
)
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
index c0947eb0d9f..339d70144be 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
@@ -5,9 +5,11 @@ import { Terminal } from '@xterm/xterm'
import { useEffect, useRef } from 'react'
import { writeClipboardText } from '@/components/ui/copy-button'
+import { markRightPanePerf } from '@/debug/right-pane-events'
import { triggerHaptic } from '@/lib/haptics'
import { useTheme } from '@/themes/context'
+import { observeActiveTerminalResize } from './active-resize'
import { registerAgentTerminalWriter } from './agent-terminal-stream'
import { makeTerminalReader, registerTerminalReader } from './buffer'
import { mirrorSelection, terminalClipboardIntent } from './clipboard'
@@ -24,7 +26,8 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
const hostRef = useRef<HTMLDivElement | null>(null)
const termRef = useRef<Terminal | null>(null)
const webglRef = useRef<WebglAddon | null>(null)
- const fitRef = useRef<(() => void) | null>(null)
+ const fitRef = useRef<((visible: boolean) => void) | null>(null)
+ const initialActiveFitRef = useRef(false)
const { latestFontFamilyRef, mountedRef } = useTerminalFontController({ fitRef, termRef, webglRef })
const surfaceTheme = () => {
@@ -47,7 +50,6 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
}
let disposed = false
- let observer: ResizeObserver | null = null
let unregister = () => {}
@@ -101,10 +103,11 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
return false
})
- fitRef.current = () => {
+ fitRef.current = visible => {
if (host.clientWidth > 0 && host.clientHeight > 0) {
try {
fit.fit()
+ markRightPanePerf(visible ? 'terminal-fit-active' : 'terminal-fit-hidden', id)
} catch {
// Mid-transition layout — the next observer tick refits.
}
@@ -132,9 +135,8 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
// No WebGL — xterm falls back to the DOM renderer.
}
- fitRef.current?.()
- observer = new ResizeObserver(() => fitRef.current?.())
- observer.observe(host)
+ fitRef.current?.(active)
+ initialActiveFitRef.current = active
// Stream live output straight into the terminal (replays backlog on attach).
unregister = registerAgentTerminalWriter(procId, chunk => term.write(chunk))
@@ -159,7 +161,6 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
unregister()
unregisterReader()
selectionDisposable.dispose()
- observer?.disconnect()
fitRef.current = null
term.dispose()
termRef.current = null
@@ -184,25 +185,39 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [renderedMode, themeName])
- // A visibility:hidden xterm doesn't paint — refit + redraw on re-activation.
+ // Keep inactive agent terminals mounted for their backlog, but do not observe
+ // or fit them until they become the visible tab.
+ // eslint-disable-next-line no-restricted-syntax -- lifecycle flag prevents a duplicate first-mount fit
useEffect(() => {
if (!active) {
+ initialActiveFitRef.current = false
+
return
}
- const frame = requestAnimationFrame(() => {
- const term = termRef.current
+ const host = hostRef.current
- fitRef.current?.()
- webglRef.current?.clearTextureAtlas()
- term?.refresh(0, term.rows - 1)
- // Take focus on activation (parity with the user terminal) so the active
- // agent tab holds focus and ⌘W's isFocusWithin('[data-terminal]') routes
- // the close to this tab rather than to a preview.
- term?.focus()
- })
+ if (!host) {
+ return
+ }
- return () => cancelAnimationFrame(frame)
+ const fitOnActivate = !initialActiveFitRef.current
+ initialActiveFitRef.current = false
+
+ return observeActiveTerminalResize(host, {
+ fitOnActivate,
+ onFit: () => fitRef.current?.(true),
+ onActivate: () => {
+ const term = termRef.current
+
+ webglRef.current?.clearTextureAtlas()
+ term?.refresh(0, term.rows - 1)
+ // Take focus on activation (parity with the user terminal) so the active
+ // agent tab holds focus and ⌘W's isFocusWithin('[data-terminal]') routes
+ // the close to this tab rather than to a preview.
+ term?.focus()
+ }
+ })
}, [active])
return { hostRef }
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts
index 656968071f0..8bcf76426e2 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts
@@ -7,7 +7,7 @@ import type { RefObject } from 'react'
import { $terminalFontFamily, applyTerminalFontFamily, resolveTerminalFontFamily } from './terminal-font'
interface TerminalFontControllerOptions {
- fitRef: RefObject<(() => void) | null>
+ fitRef: RefObject<((visible: boolean) => void) | null>
termRef: RefObject<Terminal | null>
webglRef: RefObject<WebglAddon | null>
}
@@ -38,7 +38,7 @@ export function useTerminalFontController({ fitRef, termRef, webglRef }: Termina
void applyTerminalFontFamily({
clearTextureAtlas: () => webglRef.current?.clearTextureAtlas(),
- fit: () => fitRef.current?.(),
+ fit: () => fitRef.current?.(true),
fontFamily,
isCurrent: () => !cancelled && generationRef.current === generation,
term
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
index e4e80fd3a42..24531cabe26 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
@@ -7,12 +7,14 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { CSSProperties } from 'react'
import { writeClipboardText } from '@/components/ui/copy-button'
+import { markRightPanePerf } from '@/debug/right-pane-events'
import { triggerHaptic } from '@/lib/haptics'
import { $previewTarget } from '@/store/preview'
import { useTheme } from '@/themes/context'
import { $terminalInjection } from '../store'
+import { observeActiveTerminalResize } from './active-resize'
import { makeTerminalReader, registerTerminalReader } from './buffer'
import { mirrorSelection, terminalClipboardIntent } from './clipboard'
import { terminalLinkHandler, terminalWebLinksAddon } from './links'
@@ -413,6 +415,7 @@ export function useTerminalSession({
// drag-and-drop paths, or an injected command). Gates idle-buffer handling in
// persistSnapshot so an untouched tab never re-saves an accumulating snapshot.
const hasSessionActivityRef = useRef(false)
+ const initialActiveRef = useRef(active)
const shellNameRef = useRef('shell')
const selectionLabelRef = useRef('')
const selectionRef = useRef('')
@@ -420,7 +423,8 @@ export function useTerminalSession({
const onShellRef = useRef(onShell)
// Re-fit on activation: a tab hidden via display:none has a 0×0 host, so its
// last fit is stale by the time it's shown again.
- const fitRef = useRef<(() => void) | null>(null)
+ const fitRef = useRef<((visible: boolean) => void) | null>(null)
+ const initialActiveFitRef = useRef(false)
const { latestFontFamilyRef, mountedRef } = useTerminalFontController({ fitRef, termRef, webglRef })
const [status, setStatus] = useState<TerminalStatus>('starting')
const [selection, setSelection] = useState('')
@@ -742,56 +746,28 @@ export function useTerminalSession({
term.write(next)
}
- const fitAndResize = () => {
+ const fitAndResize = (visible: boolean) => {
if (disposed || !host.isConnected || host.clientWidth <= 0 || host.clientHeight <= 0) {
return
}
try {
fit.fit()
+ markRightPanePerf(visible ? 'terminal-fit-active' : 'terminal-fit-hidden', id)
} catch {
return
}
- const id = sessionIdRef.current
+ const sessionId = sessionIdRef.current
- if (id && (lastSentSize?.cols !== term.cols || lastSentSize?.rows !== term.rows)) {
+ if (sessionId && (lastSentSize?.cols !== term.cols || lastSentSize?.rows !== term.rows)) {
lastSentSize = { cols: term.cols, rows: term.rows }
- void terminalApi.resize(id, { cols: term.cols, rows: term.rows })
+ void terminalApi.resize(sessionId, { cols: term.cols, rows: term.rows })
}
}
fitRef.current = fitAndResize
- // Coalesce ResizeObserver bursts through rAF — running fit.fit()
- // synchronously while sibling panes are mid-transition (e.g. file browser
- // collapsing to 0px) crashes the WebGL renderer mid texture-atlas rebuild.
- let pendingFrame = 0
-
- const scheduleResize = () => {
- if (pendingFrame) {
- return
- }
-
- pendingFrame = window.requestAnimationFrame(() => {
- pendingFrame = 0
-
- if (!disposed) {
- fitAndResize()
- }
- })
- }
-
- const resizeObserver = new ResizeObserver(scheduleResize)
- resizeObserver.observe(host)
- cleanup.push(() => {
- resizeObserver.disconnect()
-
- if (pendingFrame) {
- window.cancelAnimationFrame(pendingFrame)
- }
- })
-
const dataDisposable = term.onData(data => {
hasSessionActivityRef.current = true
const id = sessionIdRef.current
@@ -901,9 +877,7 @@ export function useTerminalSession({
)
window.requestAnimationFrame(() => {
- fitAndResize()
term.clearSelection() // drop any selection painted over transient boot rows
- term.focus()
})
})
.catch(error => {
@@ -938,7 +912,8 @@ export function useTerminalSession({
console.warn('[hermes-terminal] WebGL unavailable; falling back to DOM', err)
}
- fitAndResize()
+ fitAndResize(initialActiveRef.current)
+ initialActiveFitRef.current = initialActiveRef.current
startSession()
}
@@ -1013,24 +988,39 @@ export function useTerminalSession({
return term ? registerTerminalReader(id, makeTerminalReader(term)) : undefined
}, [id, status])
- // On (re)activation: a WebGL terminal doesn't paint while visibility:hidden, so
- // it reveals a stale/garbled frame. Refit, rebuild the glyph atlas, and force a
- // full redraw against the live buffer, then focus.
+ // Only the active terminal observes its host. Every terminal stays mounted
+ // (PTY + scrollback preserved), but hidden tabs do no FitAddon/layout work.
+ // Re-activation owns one fit + atlas rebuild + redraw.
+ // eslint-disable-next-line no-restricted-syntax -- lifecycle flag prevents a duplicate first-mount fit
useEffect(() => {
if (!active || status !== 'open') {
+ if (!active) {
+ initialActiveFitRef.current = false
+ }
+
return
}
- const frame = requestAnimationFrame(() => {
- const term = termRef.current
+ const host = hostRef.current
- fitRef.current?.()
- webglRef.current?.clearTextureAtlas()
- term?.refresh(0, term.rows - 1)
- term?.focus()
- })
+ if (!host) {
+ return
+ }
+
+ const fitOnActivate = !initialActiveFitRef.current
+ initialActiveFitRef.current = false
- return () => cancelAnimationFrame(frame)
+ return observeActiveTerminalResize(host, {
+ fitOnActivate,
+ onFit: () => fitRef.current?.(true),
+ onActivate: () => {
+ const term = termRef.current
+
+ webglRef.current?.clearTextureAtlas()
+ term?.refresh(0, term.rows - 1)
+ term?.focus()
+ }
+ })
}, [active, status])
// Flush a queued command (e.g. a provider-disconnect) into the live session.
diff --git a/apps/desktop/src/components/pane-shell/tree/store.ts b/apps/desktop/src/components/pane-shell/tree/store.ts
index 105fdb0df96..8399eb36ef5 100644
--- a/apps/desktop/src/components/pane-shell/tree/store.ts
+++ b/apps/desktop/src/components/pane-shell/tree/store.ts
@@ -1593,7 +1593,7 @@ export function resetLayoutTree() {
}
// Dev hook for automation.
-if (import.meta.env.DEV && typeof window !== 'undefined') {
+if ((import.meta.env.DEV || import.meta.env.VITE_PERF_PROBE === '1') && typeof window !== 'undefined') {
;(window as unknown as Record<string, unknown>).__HERMES_LAYOUT_TREE__ = {
close: closeTreePane,
dismissed: () => $dismissedPanes.get(),
diff --git a/apps/desktop/src/debug/index.ts b/apps/desktop/src/debug/index.ts
index e5eb37b55b2..a796085847c 100644
--- a/apps/desktop/src/debug/index.ts
+++ b/apps/desktop/src/debug/index.ts
@@ -29,6 +29,7 @@ import './render-counter'
// app under REAL sessions instead of a synthetic scenario's toy transcripts.
// window.__PERF_LIVE__.on() in the console, then just use the app.
import './perf-live'
+import './right-pane-probe'
import { watchSessionAtoms } from './watched-atoms'
diff --git a/apps/desktop/src/debug/right-pane-events.ts b/apps/desktop/src/debug/right-pane-events.ts
new file mode 100644
index 00000000000..9d76f3475f5
--- /dev/null
+++ b/apps/desktop/src/debug/right-pane-events.ts
@@ -0,0 +1,29 @@
+export type RightPanePerfEvent =
+ | 'project-tree-render'
+ | 'project-tree-row-render'
+ | 'terminal-fit-active'
+ | 'terminal-fit-hidden'
+ | 'terminal-measure'
+
+export interface RightPanePerfSnapshot {
+ counts: Record<RightPanePerfEvent, number>
+ details: Partial<Record<RightPanePerfEvent, Record<string, number>>>
+ rows: Record<string, number>
+}
+
+declare global {
+ interface Window {
+ __RIGHT_PANE_PERF__?: {
+ clear: () => void
+ mark: (event: RightPanePerfEvent, detail?: string) => void
+ snapshot: () => RightPanePerfSnapshot
+ start: () => void
+ stop: () => void
+ }
+ }
+}
+
+/** Tiny production-safe callsite; the recorder exists only in dev/perf builds. */
+export function markRightPanePerf(event: RightPanePerfEvent, detail?: string): void {
+ window.__RIGHT_PANE_PERF__?.mark(event, detail)
+}
diff --git a/apps/desktop/src/debug/right-pane-probe.ts b/apps/desktop/src/debug/right-pane-probe.ts
new file mode 100644
index 00000000000..d9e660078b8
--- /dev/null
+++ b/apps/desktop/src/debug/right-pane-probe.ts
@@ -0,0 +1,60 @@
+import type { RightPanePerfEvent, RightPanePerfSnapshot } from './right-pane-events'
+
+const eventNames: RightPanePerfEvent[] = [
+ 'project-tree-render',
+ 'project-tree-row-render',
+ 'terminal-fit-active',
+ 'terminal-fit-hidden',
+ 'terminal-measure'
+]
+
+const blankCounts = (): Record<RightPanePerfEvent, number> =>
+ Object.fromEntries(eventNames.map(name => [name, 0])) as Record<RightPanePerfEvent, number>
+
+if (typeof window !== 'undefined' && !window.__RIGHT_PANE_PERF__) {
+ let recording = false
+ let counts = blankCounts()
+ let details: RightPanePerfSnapshot['details'] = {}
+ let rows: Record<string, number> = {}
+
+ window.__RIGHT_PANE_PERF__ = {
+ clear: () => {
+ counts = blankCounts()
+ details = {}
+ rows = {}
+ },
+ mark: (event, detail) => {
+ if (!recording) {
+ return
+ }
+
+ counts[event] += 1
+
+ if (detail) {
+ const eventDetails = details[event] ?? {}
+ eventDetails[detail] = (eventDetails[detail] ?? 0) + 1
+ details[event] = eventDetails
+
+ if (event === 'project-tree-row-render') {
+ rows[detail] = (rows[detail] ?? 0) + 1
+ }
+ }
+ },
+ snapshot: (): RightPanePerfSnapshot => ({
+ counts: { ...counts },
+ details: Object.fromEntries(
+ Object.entries(details).map(([event, eventDetails]) => [event, { ...eventDetails }])
+ ),
+ rows: { ...rows }
+ }),
+ start: () => {
+ counts = blankCounts()
+ details = {}
+ rows = {}
+ recording = true
+ },
+ stop: () => {
+ recording = false
+ }
+ }
+}
diff --git a/apps/desktop/src/store/coding-status.test.ts b/apps/desktop/src/store/coding-status.test.ts
index aa731c5b253..6eb5cefd545 100644
--- a/apps/desktop/src/store/coding-status.test.ts
+++ b/apps/desktop/src/store/coding-status.test.ts
@@ -10,6 +10,7 @@ import {
refreshAllRepoStatuses,
refreshRepoStatus,
registerRepoStatusCwd,
+ repoChangeKindForPath,
repoStatusForCwd
} from './coding-status'
import { $currentCwd, $selectedStoredSessionId } from './session'
@@ -255,3 +256,28 @@ describe('refreshRepoStatus', () => {
release?.()
})
})
+
+describe('repoChangeKindForPath', () => {
+ it('does not notify a row when only another path changes', () => {
+ $currentCwd.set('/repo')
+ $repoStatus.set({ ...sampleStatus, files: [] })
+ const row = repoChangeKindForPath('/repo/a.ts')
+ const listener = vi.fn()
+ const unsubscribe = row.subscribe(listener)
+
+ $repoStatus.set({
+ ...sampleStatus,
+ files: [{ path: 'b.ts', untracked: true } as HermesRepoStatus['files'][number]]
+ })
+ expect(listener).toHaveBeenCalledTimes(1)
+
+ $repoStatus.set({
+ ...sampleStatus,
+ files: [{ path: 'a.ts', untracked: true } as HermesRepoStatus['files'][number]]
+ })
+ expect(listener).toHaveBeenCalledTimes(2)
+ expect(listener.mock.calls.at(-1)?.[0]).toBe('added')
+
+ unsubscribe()
+ })
+})
diff --git a/apps/desktop/src/store/coding-status.ts b/apps/desktop/src/store/coding-status.ts
index 4a1ea97b0c1..5e434e0744d 100644
--- a/apps/desktop/src/store/coding-status.ts
+++ b/apps/desktop/src/store/coding-status.ts
@@ -112,6 +112,14 @@ export const $repoChangeByPath = computed([$repoStatus, $currentCwd], (status, c
return map
})
+/**
+ * Per-row Git decoration subscription. A visible file row reads one scalar, so
+ * a fresh repo-status map only re-renders that row when its own kind changed.
+ */
+export function repoChangeKindForPath(path: string): ReadableAtom<RepoChangeKind | undefined> {
+ return computed($repoChangeByPath, changes => changes.get(path))
+}
+
// Cwds whose rails are on screen right now (refcounted — two tiles in one
// worktree register it twice). Every refresh edge re-probes each registered
// cwd plus the primary workspace, so a tile's rail moves when ITS agent
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index ebf58f9819c..8c6811bf6ef 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -799,7 +799,7 @@ $selectedStoredSessionId.listen(selected => {
})
// Dev hook for automation (mirrors __HERMES_LAYOUT_TREE__).
-if (import.meta.env.DEV && typeof window !== 'undefined') {
+if ((import.meta.env.DEV || import.meta.env.VITE_PERF_PROBE === '1') && typeof window !== 'undefined') {
;(window as unknown as Record<string, unknown>).__HERMES_SESSION_TILES__ = {
close: closeSessionTile,
open: openSessionTile,