fix: address review findings (#4690)
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
import type { ILink } from '@xterm/xterm'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createTerminalHandleLinkProvider,
|
||||
extractTerminalHandleLinks,
|
||||
findTerminalHandleTarget,
|
||||
focusRendererTerminalHandle
|
||||
} from './terminal-handle-links'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
activateTabAndFocusPane: vi.fn(),
|
||||
focusTerminalTabSurface: vi.fn(),
|
||||
storeState: {
|
||||
tabsByWorktree: {},
|
||||
ptyIdsByTabId: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
setActiveWorktree: vi.fn(),
|
||||
markWorktreeVisited: vi.fn(),
|
||||
setActiveView: vi.fn(),
|
||||
setActiveTabType: vi.fn(),
|
||||
revealWorktreeInSidebar: vi.fn(),
|
||||
setActiveTab: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: {
|
||||
getState: () => mocks.storeState
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/activate-tab-and-focus-pane', () => ({
|
||||
activateTabAndFocusPane: mocks.activateTabAndFocusPane
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/focus-terminal-tab-surface', () => ({
|
||||
focusTerminalTabSurface: mocks.focusTerminalTabSurface
|
||||
}))
|
||||
|
||||
type TestBufferLine = {
|
||||
isWrapped: boolean
|
||||
length: number
|
||||
translateToString: (
|
||||
trimRight?: boolean,
|
||||
startColumn?: number,
|
||||
endColumn?: number,
|
||||
outColumns?: number[]
|
||||
) => string
|
||||
}
|
||||
|
||||
function makeBufferLine(text: string, options: { isWrapped?: boolean } = {}): TestBufferLine {
|
||||
return {
|
||||
isWrapped: options.isWrapped ?? false,
|
||||
length: text.length,
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setPlatform(userAgent: string): void {
|
||||
vi.stubGlobal('navigator', { userAgent })
|
||||
}
|
||||
|
||||
async function collectLinks(rows: TestBufferLine[], bufferLineNumber = 1): Promise<ILink[]> {
|
||||
const terminal = {
|
||||
buffer: {
|
||||
active: {
|
||||
getLine: (y: number) => rows[y]
|
||||
}
|
||||
},
|
||||
clearSelection: vi.fn()
|
||||
}
|
||||
const provider = createTerminalHandleLinkProvider({
|
||||
getTerminal: () => terminal as never,
|
||||
getRuntimeEnvironmentId: () => null,
|
||||
linkTooltip: { textContent: '', style: { display: '' } } as unknown as HTMLElement
|
||||
})
|
||||
return await new Promise<ILink[]>((resolve) => {
|
||||
provider.provideLinks(bufferLineNumber, (links) => resolve(links ?? []))
|
||||
})
|
||||
}
|
||||
|
||||
describe('extractTerminalHandleLinks', () => {
|
||||
it('detects UUID terminal handles from orchestration output', () => {
|
||||
const line = '- Terminal: term_d422ff9f-42c8-4d70-bb6a-71762b21ab95'
|
||||
|
||||
expect(extractTerminalHandleLinks(line)).toEqual([
|
||||
{
|
||||
handle: 'term_d422ff9f-42c8-4d70-bb6a-71762b21ab95',
|
||||
startIndex: 12,
|
||||
endIndex: 53
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('trims sentence punctuation without matching inside longer tokens', () => {
|
||||
expect(extractTerminalHandleLinks('Open term_worker, not xterm_worker.')).toEqual([
|
||||
{ handle: 'term_worker', startIndex: 5, endIndex: 16 }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('findTerminalHandleTarget', () => {
|
||||
it('finds split-pane remote runtime handles from leaf PTY mappings', () => {
|
||||
expect(
|
||||
findTerminalHandleTarget('term_remote', {
|
||||
tabsByWorktree: {
|
||||
'wt-1': [
|
||||
{
|
||||
id: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
ptyId: null,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': ['remote:env-1@@term_remote'] },
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: { type: 'leaf', leafId: 'leaf-a' },
|
||||
activeLeafId: 'leaf-a',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { 'leaf-a': 'remote:env-1@@term_remote' }
|
||||
}
|
||||
}
|
||||
})
|
||||
).toEqual({ worktreeId: 'wt-1', tabId: 'tab-1', leafId: 'leaf-a' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('focusRendererTerminalHandle', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.storeState.tabsByWorktree = {
|
||||
'wt-1': [
|
||||
{
|
||||
id: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
ptyId: 'term_direct',
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
mocks.storeState.ptyIdsByTabId = { 'tab-1': ['term_direct'] }
|
||||
mocks.storeState.terminalLayoutsByTabId = {
|
||||
'tab-1': { root: null, activeLeafId: null, expandedLeafId: null }
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('activates a local renderer target without runtime lookup', () => {
|
||||
expect(focusRendererTerminalHandle('term_direct')).toBe(true)
|
||||
|
||||
expect(mocks.storeState.setActiveWorktree).toHaveBeenCalledWith('wt-1')
|
||||
expect(mocks.storeState.setActiveView).toHaveBeenCalledWith('terminal')
|
||||
expect(mocks.storeState.setActiveTabType).toHaveBeenCalledWith('terminal')
|
||||
expect(mocks.storeState.setActiveTab).toHaveBeenCalledWith('tab-1')
|
||||
expect(mocks.focusTerminalTabSurface).toHaveBeenCalledWith('tab-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createTerminalHandleLinkProvider', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setPlatform('Macintosh')
|
||||
mocks.storeState.tabsByWorktree = {}
|
||||
mocks.storeState.ptyIdsByTabId = {}
|
||||
mocks.storeState.terminalLayoutsByTabId = {}
|
||||
vi.stubGlobal('window', {
|
||||
api: {
|
||||
runtime: {
|
||||
call: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
result: { focus: { handle: 'term_worker', tabId: 'tab-1', worktreeId: 'wt-1' } }
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('provides wrapped terminal handle links and focuses through runtime on activation', async () => {
|
||||
const rows = [makeBufferLine('Worker: term_work'), makeBufferLine('er', { isWrapped: true })]
|
||||
const links = await collectLinks(rows, 1)
|
||||
|
||||
expect(links.map((link) => link.text)).toEqual(['term_worker'])
|
||||
links[0].activate(
|
||||
{
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
preventDefault: vi.fn()
|
||||
} as unknown as MouseEvent,
|
||||
links[0].text
|
||||
)
|
||||
await Promise.resolve()
|
||||
|
||||
expect(window.api.runtime.call).toHaveBeenCalledWith({
|
||||
method: 'terminal.focus',
|
||||
params: { terminal: 'term_worker' }
|
||||
})
|
||||
})
|
||||
|
||||
it('contains runtime focus failures for stale terminal handles', async () => {
|
||||
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
window.api.runtime.call = vi.fn().mockRejectedValue(new Error('terminal not found'))
|
||||
|
||||
try {
|
||||
const links = await collectLinks([makeBufferLine('Worker: term_gone')])
|
||||
links[0].activate(
|
||||
{
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
preventDefault: vi.fn()
|
||||
} as unknown as MouseEvent,
|
||||
links[0].text
|
||||
)
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
expect(consoleWarn).toHaveBeenCalledWith(
|
||||
'[terminal-handle-link] focus failed:',
|
||||
expect.any(Error)
|
||||
)
|
||||
} finally {
|
||||
consoleWarn.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { ILink, ILinkProvider, Terminal } from '@xterm/xterm'
|
||||
import type { AppState } from '@/store'
|
||||
import { useAppStore } from '@/store'
|
||||
import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane'
|
||||
import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface'
|
||||
import { callRuntimeRpc } from '@/runtime/runtime-rpc-client'
|
||||
import { getRemoteRuntimeTerminalHandle } from '@/runtime/runtime-terminal-stream'
|
||||
import { buildWrappedLogicalLine, rangeForParsedFileLink } from './wrapped-terminal-link-ranges'
|
||||
|
||||
export type ParsedTerminalHandleLink = {
|
||||
handle: string
|
||||
startIndex: number
|
||||
endIndex: number
|
||||
}
|
||||
|
||||
export type TerminalHandleTarget = {
|
||||
worktreeId: string
|
||||
tabId: string
|
||||
leafId: string | null
|
||||
}
|
||||
|
||||
export type TerminalHandleFocusState = Pick<
|
||||
AppState,
|
||||
'tabsByWorktree' | 'ptyIdsByTabId' | 'terminalLayoutsByTabId'
|
||||
>
|
||||
|
||||
type TerminalHandleLinkProviderDeps = {
|
||||
getTerminal: () => Terminal | null
|
||||
getRuntimeEnvironmentId: () => string | null
|
||||
linkTooltip: HTMLElement
|
||||
}
|
||||
|
||||
const TERMINAL_HANDLE_REGEX = /term_[A-Za-z0-9][A-Za-z0-9_-]{0,127}/g
|
||||
const TERMINAL_HANDLE_BOUNDARY_CHAR = /[A-Za-z0-9_-]/
|
||||
|
||||
export function extractTerminalHandleLinks(lineText: string): ParsedTerminalHandleLink[] {
|
||||
if (!lineText.includes('term_')) {
|
||||
return []
|
||||
}
|
||||
|
||||
const links: ParsedTerminalHandleLink[] = []
|
||||
for (const match of lineText.matchAll(TERMINAL_HANDLE_REGEX)) {
|
||||
const startIndex = match.index ?? 0
|
||||
const handle = match[0]
|
||||
const endIndex = startIndex + handle.length
|
||||
if (
|
||||
TERMINAL_HANDLE_BOUNDARY_CHAR.test(lineText[startIndex - 1] ?? '') ||
|
||||
TERMINAL_HANDLE_BOUNDARY_CHAR.test(lineText[endIndex] ?? '')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
links.push({ handle, startIndex, endIndex })
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
export function findTerminalHandleTarget(
|
||||
handle: string,
|
||||
state: TerminalHandleFocusState
|
||||
): TerminalHandleTarget | null {
|
||||
for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) {
|
||||
for (const tab of tabs) {
|
||||
const layout = state.terminalLayoutsByTabId[tab.id]
|
||||
for (const [leafId, ptyId] of Object.entries(layout?.ptyIdsByLeafId ?? {})) {
|
||||
if (ptyIdMatchesTerminalHandle(ptyId, handle)) {
|
||||
return { worktreeId, tabId: tab.id, leafId }
|
||||
}
|
||||
}
|
||||
|
||||
const tabPtyIds = [tab.ptyId, ...(state.ptyIdsByTabId[tab.id] ?? [])].filter(
|
||||
(ptyId): ptyId is string => Boolean(ptyId)
|
||||
)
|
||||
if (tabPtyIds.some((ptyId) => ptyIdMatchesTerminalHandle(ptyId, handle))) {
|
||||
return { worktreeId, tabId: tab.id, leafId: layout?.activeLeafId ?? null }
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function focusRendererTerminalHandle(handle: string): boolean {
|
||||
const store = useAppStore.getState()
|
||||
const target = findTerminalHandleTarget(handle, store)
|
||||
if (!target) {
|
||||
return false
|
||||
}
|
||||
|
||||
store.setActiveWorktree(target.worktreeId)
|
||||
store.markWorktreeVisited(target.worktreeId)
|
||||
store.setActiveView('terminal')
|
||||
store.setActiveTabType('terminal')
|
||||
store.revealWorktreeInSidebar(target.worktreeId)
|
||||
if (target.leafId) {
|
||||
activateTabAndFocusPane(target.tabId, target.leafId)
|
||||
} else {
|
||||
store.setActiveTab(target.tabId)
|
||||
focusTerminalTabSurface(target.tabId)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export function createTerminalHandleLinkProvider(
|
||||
deps: TerminalHandleLinkProviderDeps
|
||||
): ILinkProvider {
|
||||
return {
|
||||
provideLinks: (bufferLineNumber, callback) => {
|
||||
const terminal = deps.getTerminal()
|
||||
if (!terminal) {
|
||||
callback(undefined)
|
||||
return
|
||||
}
|
||||
const logicalLine = buildWrappedLogicalLine(terminal.buffer.active, bufferLineNumber)
|
||||
if (!logicalLine || !logicalLine.text.includes('term_')) {
|
||||
callback(undefined)
|
||||
return
|
||||
}
|
||||
|
||||
const links = extractTerminalHandleLinks(logicalLine.text)
|
||||
.map((parsed): ILink | null => {
|
||||
const range = rangeForParsedFileLink(logicalLine, parsed.startIndex, parsed.endIndex)
|
||||
if (!range) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
range,
|
||||
text: parsed.handle,
|
||||
activate: (event) => {
|
||||
if (!isTerminalHandleLinkActivation(event)) {
|
||||
return
|
||||
}
|
||||
event?.preventDefault()
|
||||
if (!focusRendererTerminalHandle(parsed.handle)) {
|
||||
void focusRuntimeTerminalHandle(
|
||||
parsed.handle,
|
||||
deps.getRuntimeEnvironmentId()
|
||||
).catch((error: unknown) => {
|
||||
console.warn('[terminal-handle-link] focus failed:', error)
|
||||
})
|
||||
}
|
||||
terminal.clearSelection()
|
||||
},
|
||||
hover: () => {
|
||||
deps.linkTooltip.textContent = `${parsed.handle} (${getTerminalHandleFocusHint()})`
|
||||
deps.linkTooltip.style.display = ''
|
||||
},
|
||||
leave: () => {
|
||||
deps.linkTooltip.style.display = 'none'
|
||||
}
|
||||
}
|
||||
})
|
||||
.filter((link): link is ILink => link !== null)
|
||||
|
||||
callback(links.length > 0 ? links : undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ptyIdMatchesTerminalHandle(ptyId: string, handle: string): boolean {
|
||||
return ptyId === handle || getRemoteRuntimeTerminalHandle(ptyId) === handle
|
||||
}
|
||||
|
||||
function getTerminalHandleFocusHint(): string {
|
||||
return navigator.userAgent.includes('Mac')
|
||||
? '⌘+click to switch terminal'
|
||||
: 'Ctrl+click to switch terminal'
|
||||
}
|
||||
|
||||
function isTerminalHandleLinkActivation(
|
||||
event: Pick<MouseEvent, 'metaKey' | 'ctrlKey'> | undefined
|
||||
): boolean {
|
||||
const isMac = navigator.userAgent.includes('Mac')
|
||||
return isMac ? Boolean(event?.metaKey) : Boolean(event?.ctrlKey)
|
||||
}
|
||||
|
||||
async function focusRuntimeTerminalHandle(
|
||||
handle: string,
|
||||
runtimeEnvironmentId: string | null
|
||||
): Promise<void> {
|
||||
const environmentId = runtimeEnvironmentId?.trim()
|
||||
const target = environmentId
|
||||
? ({ kind: 'environment', environmentId } as const)
|
||||
: ({ kind: 'local' } as const)
|
||||
// Why: main owns the `term_*` mapping. Defer to terminal.focus on click
|
||||
// instead of mirroring that state in renderer hover parsing.
|
||||
await callRuntimeRpc(target, 'terminal.focus', { terminal: handle })
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
getTerminalUrlOpenHint,
|
||||
installFilePathLinkClickFallback
|
||||
} from './terminal-link-handlers'
|
||||
import { createTerminalHandleLinkProvider } from './terminal-handle-links'
|
||||
import type { LinkHandlerDeps } from './terminal-link-handlers'
|
||||
import { handleOscLink } from './terminal-osc-link-routing'
|
||||
import { installHttpLinkClickFallback } from './terminal-url-link-hit-testing'
|
||||
@@ -353,6 +354,7 @@ export function useTerminalPaneLifecycle({
|
||||
const systemPrefersDarkRef = useRef(systemPrefersDark)
|
||||
systemPrefersDarkRef.current = systemPrefersDark
|
||||
const linkProviderDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
const terminalHandleLinkDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
const fileLinkClickFallbackDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
const httpLinkClickFallbackDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
// Why: read settingsRef at fire time so toggling "copy on select" takes
|
||||
@@ -422,6 +424,7 @@ export function useTerminalPaneLifecycle({
|
||||
const paneTransports = paneTransportsRef.current
|
||||
const panePtyBindings = panePtyBindingsRef.current
|
||||
const linkDisposables = linkProviderDisposablesRef.current
|
||||
const terminalHandleLinkDisposables = terminalHandleLinkDisposablesRef.current
|
||||
const fileLinkClickFallbackDisposables = fileLinkClickFallbackDisposablesRef.current
|
||||
const httpLinkClickFallbackDisposables = httpLinkClickFallbackDisposablesRef.current
|
||||
const selectionDisposables = selectionDisposablesRef.current
|
||||
@@ -663,6 +666,17 @@ export function useTerminalPaneLifecycle({
|
||||
createFilePathLinkProvider(pane.id, linkDeps, pane.linkTooltip, fileOpenLinkHint)
|
||||
)
|
||||
linkProviderDisposablesRef.current.set(pane.id, linkProviderDisposable)
|
||||
const terminalHandleLinkDisposable = pane.terminal.registerLinkProvider(
|
||||
createTerminalHandleLinkProvider({
|
||||
getTerminal: () =>
|
||||
managerRef.current?.getPanes().find((candidate) => candidate.id === pane.id)
|
||||
?.terminal ?? null,
|
||||
getRuntimeEnvironmentId: () =>
|
||||
linkDeps.getRuntimeEnvironmentIdForPane?.(pane.id) ?? null,
|
||||
linkTooltip: pane.linkTooltip
|
||||
})
|
||||
)
|
||||
terminalHandleLinkDisposablesRef.current.set(pane.id, terminalHandleLinkDisposable)
|
||||
const fileLinkClickFallbackDisposable = installFilePathLinkClickFallback(
|
||||
pane.id,
|
||||
pane.terminal,
|
||||
@@ -800,6 +814,11 @@ export function useTerminalPaneLifecycle({
|
||||
linkProviderDisposable.dispose()
|
||||
linkProviderDisposablesRef.current.delete(paneId)
|
||||
}
|
||||
const terminalHandleLinkDisposable = terminalHandleLinkDisposablesRef.current.get(paneId)
|
||||
if (terminalHandleLinkDisposable) {
|
||||
terminalHandleLinkDisposable.dispose()
|
||||
terminalHandleLinkDisposablesRef.current.delete(paneId)
|
||||
}
|
||||
const fileLinkClickFallbackDisposable =
|
||||
fileLinkClickFallbackDisposablesRef.current.get(paneId)
|
||||
if (fileLinkClickFallbackDisposable) {
|
||||
@@ -1241,6 +1260,10 @@ export function useTerminalPaneLifecycle({
|
||||
disposable.dispose()
|
||||
}
|
||||
linkDisposables.clear()
|
||||
for (const disposable of terminalHandleLinkDisposables.values()) {
|
||||
disposable.dispose()
|
||||
}
|
||||
terminalHandleLinkDisposables.clear()
|
||||
for (const disposable of fileLinkClickFallbackDisposables.values()) {
|
||||
disposable.dispose()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user