Fix terminal hover link CPU runaway (#4644)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
+135
@@ -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<void> {
|
||||
await new Promise<void>((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<string, unknown>): 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<number, IDisposable>() },
|
||||
pathExistsCache: new Map()
|
||||
},
|
||||
{ textContent: '', style: { display: '' } } as unknown as HTMLElement,
|
||||
getTerminalFileOpenHint()
|
||||
)
|
||||
|
||||
const start = performance.now()
|
||||
await new Promise<void>((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)
|
||||
})
|
||||
@@ -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)
|
||||
) {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user