From 45705b0a7a085ee1a2e809e38aeb1ef73c136ddd Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Thu, 4 Jun 2026 13:12:48 -0400 Subject: [PATCH] Fix terminal hover link CPU runaway (#4644) Co-authored-by: Orca --- ...terminal-hover-link-provider.repro.test.ts | 135 ++++++++++++++++++ .../terminal-pane/terminal-link-handlers.ts | 10 +- .../wrapped-terminal-link-ranges.test.ts | 67 +++++++++ .../wrapped-terminal-link-ranges.ts | 17 +++ src/renderer/src/lib/terminal-links.test.ts | 11 ++ src/renderer/src/lib/terminal-links.ts | 14 ++ 6 files changed, 249 insertions(+), 5 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/issue-4631-terminal-hover-link-provider.repro.test.ts create mode 100644 src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.test.ts diff --git a/src/renderer/src/components/terminal-pane/issue-4631-terminal-hover-link-provider.repro.test.ts b/src/renderer/src/components/terminal-pane/issue-4631-terminal-hover-link-provider.repro.test.ts new file mode 100644 index 000000000..1e293297b --- /dev/null +++ b/src/renderer/src/components/terminal-pane/issue-4631-terminal-hover-link-provider.repro.test.ts @@ -0,0 +1,135 @@ +import { performance } from 'node:perf_hooks' +import { Terminal } from '@xterm/headless' +import type { IDisposable } from '@xterm/xterm' +import { describe, expect, it, vi } from 'vitest' +import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import { extractTerminalFileLinks } from '@/lib/terminal-links' +import { createFilePathLinkProvider, getTerminalFileOpenHint } from './terminal-link-handlers' +import { buildWrappedLogicalLine } from './wrapped-terminal-link-ranges' + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => ({ + settings: undefined, + setActiveWorktree: vi.fn(), + createBrowserTab: vi.fn(), + openFile: vi.fn(), + setPendingEditorReveal: vi.fn() + }) + } +})) + +vi.mock('@/lib/language-detect', () => ({ + detectLanguage: () => 'plaintext' +})) + +vi.mock('@/lib/worktree-activation', () => ({ + activateAndRevealWorktree: vi.fn() +})) + +vi.mock('@/lib/connection-context', () => ({ + getConnectionId: () => null +})) + +async function writeTerminal(terminal: Terminal, data: string): Promise { + await new Promise((resolve) => terminal.write(data, resolve)) +} + +function configuredRowCount(): number { + const raw = process.env.ORCA_4631_WRAP_ROWS + if (!raw) { + return 50_000 + } + const parsed = Number.parseInt(raw, 10) + return Number.isFinite(parsed) && parsed > 0 ? parsed : 50_000 +} + +function logStage(stage: string, details: Record): void { + if (process.env.ORCA_LOG_4631_REPRO !== '1') { + return + } + process.stderr.write(`${JSON.stringify({ issue: 4631, stage, ...details })}\n`) +} + +describe('issue 4631 terminal hover link-provider repro', () => { + it('keeps hover link detection bounded for a huge soft-wrapped terminal line', async () => { + vi.stubGlobal('navigator', { userAgent: 'Macintosh' }) + vi.stubGlobal('window', { + api: { + shell: { + pathExists: vi.fn().mockResolvedValue(false) + } + } + }) + + const rowCount = configuredRowCount() + const terminal = new Terminal({ + allowProposedApi: true, + cols: 80, + rows: 24, + scrollback: rowCount + 100 + }) + const payload = `${'a'.repeat(79)}\r\n${'b'.repeat(80 * rowCount)}` + const writeStart = performance.now() + await writeTerminal(terminal, payload) + logStage('terminal.write', { + rowCount, + elapsedMs: Math.round(performance.now() - writeStart), + bufferBaseY: terminal.buffer.active.baseY + }) + + const targetBufferLine = 2 + const buildStart = performance.now() + const logicalLine = buildWrappedLogicalLine(terminal.buffer.active, targetBufferLine) + const buildElapsedMs = performance.now() - buildStart + logStage('buildWrappedLogicalLine', { + rowCount, + elapsedMs: Math.round(buildElapsedMs), + logicalTextLength: logicalLine?.text.length ?? null, + wrappedRows: logicalLine?.rows.length ?? null + }) + + const extractStart = performance.now() + const directLinks = logicalLine ? extractTerminalFileLinks(logicalLine.text) : [] + const extractElapsedMs = performance.now() - extractStart + logStage('extractTerminalFileLinks', { + rowCount, + elapsedMs: Math.round(extractElapsedMs), + directLinkCount: directLinks.length + }) + + const pane = { id: 1, terminal } + const managerRef = { + current: { getPanes: () => [pane] } as unknown as PaneManager + } + const provider = createFilePathLinkProvider( + 1, + { + worktreeId: 'wt-1', + worktreePath: '/repo', + startupCwd: '/repo', + managerRef, + linkProviderDisposablesRef: { current: new Map() }, + pathExistsCache: new Map() + }, + { textContent: '', style: { display: '' } } as unknown as HTMLElement, + getTerminalFileOpenHint() + ) + + const start = performance.now() + await new Promise((resolve) => { + provider.provideLinks(targetBufferLine, () => resolve()) + }) + const elapsedMs = performance.now() - start + + logStage('createFilePathLinkProvider.provideLinks', { + cols: terminal.cols, + rowCount, + elapsedMs: Math.round(elapsedMs), + bufferBaseY: terminal.buffer.active.baseY, + targetBufferLine + }) + + expect(buildElapsedMs + extractElapsedMs + elapsedMs).toBeLessThan(100) + }, 120_000) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-link-handlers.ts b/src/renderer/src/components/terminal-pane/terminal-link-handlers.ts index 3300b981a..a3c9424cb 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-handlers.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-handlers.ts @@ -121,15 +121,15 @@ export function createFilePathLinkProvider( const buffer = pane.terminal.buffer.active const softWrappedLogicalLine = buildWrappedLogicalLine(buffer, bufferLineNumber) - if (!softWrappedLogicalLine?.text) { + const logicalLines = dedupeLogicalLines([ + ...buildHardWrappedPathLogicalLineCandidates(buffer, bufferLineNumber), + ...(softWrappedLogicalLine ? [softWrappedLogicalLine] : []) + ]) + if (logicalLines.every((logicalLine) => !logicalLine.text)) { callback(undefined) return } - const logicalLines = dedupeLogicalLines([ - ...buildHardWrappedPathLogicalLineCandidates(buffer, bufferLineNumber), - softWrappedLogicalLine - ]) if ( logicalLines.every((logicalLine) => extractTerminalFileLinks(logicalLine.text).length === 0) ) { diff --git a/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.test.ts b/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.test.ts new file mode 100644 index 000000000..b39e73df1 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { buildWrappedLogicalLine } from './wrapped-terminal-link-ranges' + +type TestBufferLine = { + isWrapped: boolean + length: number + getCell: (_index: number) => undefined + translateToString: ( + trimRight?: boolean, + startColumn?: number, + endColumn?: number, + outColumns?: number[] + ) => string +} + +function makeBufferLine(text: string, isWrapped = false): TestBufferLine { + return { + isWrapped, + length: text.length, + getCell: () => undefined, + translateToString: ( + _trimRight?: boolean, + startColumn = 0, + endColumn = text.length, + outColumns?: number[] + ) => { + if (outColumns) { + outColumns.length = 0 + for (let index = startColumn; index <= endColumn; index++) { + outColumns.push(index) + } + } + return text.slice(startColumn, endColumn) + } + } +} + +describe('buildWrappedLogicalLine', () => { + it('joins ordinary soft-wrapped terminal rows', () => { + const rows = [makeBufferLine('src/'), makeBufferLine('file.ts', true)] + + const logicalLine = buildWrappedLogicalLine({ getLine: (y) => rows[y] }, 2) + + expect(logicalLine?.text).toBe('src/file.ts') + expect(logicalLine?.rows.map((row) => row.y)).toEqual([0, 1]) + }) + + it('caps pathological soft-wrapped lines before scanning the whole run', () => { + const rows = Array.from({ length: 1_000 }, (_value, index) => + makeBufferLine('b'.repeat(80), index > 0) + ) + const observedRows: number[] = [] + + const logicalLine = buildWrappedLogicalLine( + { + getLine: (y) => { + observedRows.push(y) + return rows[y] + } + }, + 1 + ) + + expect(logicalLine).toBeNull() + expect(Math.max(...observedRows)).toBeLessThan(250) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.ts b/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.ts index b6ac704fd..18be0543b 100644 --- a/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.ts +++ b/src/renderer/src/components/terminal-pane/wrapped-terminal-link-ranges.ts @@ -24,6 +24,9 @@ export type WrappedLogicalLine = { fingerprint: string } +const MAX_SOFT_WRAPPED_LINK_ROWS = 200 +const MAX_SOFT_WRAPPED_LINK_CHARS = 20_000 + function translateLineWithCells(line: IBufferLine): { text: string; columns: number[] } | null { let text = '' const columns: number[] = [] @@ -118,13 +121,22 @@ export function buildWrappedLogicalLine( } let startY = y + let rowCount = 1 while (startY > 0 && buffer.getLine(startY)?.isWrapped) { + if (rowCount >= MAX_SOFT_WRAPPED_LINK_ROWS) { + return null + } startY-- + rowCount++ } let endY = y while (buffer.getLine(endY + 1)?.isWrapped) { + if (rowCount >= MAX_SOFT_WRAPPED_LINK_ROWS) { + return null + } endY++ + rowCount++ } let text = '' @@ -135,6 +147,11 @@ export function buildWrappedLogicalLine( return null } const translated = translateLineWithColumns(line) + // Why: terminal hover runs on the renderer interaction path; enormous + // no-newline blobs are not useful file links and can freeze the window. + if (text.length + translated.text.length > MAX_SOFT_WRAPPED_LINK_CHARS) { + return null + } rows.push({ y: rowY, text: translated.text, diff --git a/src/renderer/src/lib/terminal-links.test.ts b/src/renderer/src/lib/terminal-links.test.ts index 897bac5d4..0efb43f46 100644 --- a/src/renderer/src/lib/terminal-links.test.ts +++ b/src/renderer/src/lib/terminal-links.test.ts @@ -1,3 +1,4 @@ +import { performance } from 'node:perf_hooks' import { describe, expect, it } from 'vitest' import { extractTerminalFileLinks, @@ -76,6 +77,16 @@ describe('terminal path helpers', () => { expect(links).toHaveLength(1) expect(links[0]).toMatchObject({ pathText: 'foo.ts', line: 12, column: 3 }) }) + + it('keeps huge no-separator terminal tokens off the hover hot path', () => { + const line = `${'b'.repeat(80 * 500)} package.json` + const startedAt = performance.now() + + const links = extractTerminalFileLinks(line) + + expect(performance.now() - startedAt).toBeLessThan(100) + expect(links.map((link) => link.displayText)).toEqual(['package.json']) + }) }) describe('extractTerminalFileLinks local path tokens', () => { diff --git a/src/renderer/src/lib/terminal-links.ts b/src/renderer/src/lib/terminal-links.ts index e9f34ec26..af6cbedb1 100644 --- a/src/renderer/src/lib/terminal-links.ts +++ b/src/renderer/src/lib/terminal-links.ts @@ -124,6 +124,11 @@ const EXTENSIONLESS_FILENAMES = new Set([ const BARE_FILENAME_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._+-]*$/ const URI_PREFIX_CHAR_PATTERN = /^[A-Za-z0-9+./:-]$/ +const MAX_BARE_FILENAME_TOKEN_LENGTH = 120 + +function hasPathSeparator(text: string): boolean { + return text.includes('/') || text.includes('\\') +} // Bare words are validated against the filesystem by the provider, so this // filter's job is to reject tokens that are obviously not filenames before @@ -290,6 +295,10 @@ function detectLocalPathLinks( lineText: string, includeLineEndingPrefixCandidates = false ): ParsedTerminalFileLink[] { + if (!hasPathSeparator(lineText)) { + return [] + } + const links: ParsedTerminalFileLink[] = [] const spacedLinks = detectSpacedLocalPathLinks(lineText, includeLineEndingPrefixCandidates) const spacedRanges = mergeRanges( @@ -359,6 +368,11 @@ function detectBareFilenameLinks( if (rangesOverlap(range, claimedRanges)) { continue } + // Why: huge terminal blobs can be one unbroken token; parse only bounded + // bare-filename candidates so hover link detection stays interactive. + if (range.text.length > MAX_BARE_FILENAME_TOKEN_LENGTH) { + continue + } const link = toParsedLink(range) if (!link) { continue