mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
perf: restore terminal history without synchronous IPC (#41660)
* perf: restore terminal history without synchronous IPC * fix: follow moved terminal topology imports * Consume queued terminal commands when startup dispatches
This commit is contained in:
@@ -175,7 +175,6 @@
|
||||
2 src/renderer/src/components/task-page/use-task-page-source-availability.ts
|
||||
2 src/renderer/src/components/task-page/use-task-page-store-bindings.ts
|
||||
1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-controller.ts
|
||||
1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-lifecycle.ts
|
||||
1 src/renderer/src/components/terminal-pane/layout/close/retire-unbound-runtime-terminal-pane.ts
|
||||
2 src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-admission.ts
|
||||
2 src/renderer/src/components/terminal-pane/layout/close/use-terminal-pane-close-actions.ts
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
# Only explicit worker/utility entry files are exempt; their imports remain guarded.
|
||||
3 src/main/host/native-chat-visual-guest-theme.ts
|
||||
1 src/main/ipc/renderer-shutdown-checkpoint.ts
|
||||
2 src/main/ipc/session.ts
|
||||
1 src/main/ipc/settings.ts
|
||||
1 src/preload/api/app-bridge.ts
|
||||
1 src/preload/api/native-chat-bridge.ts
|
||||
2 src/preload/api/session-bridge.ts
|
||||
1 src/preload/api/settings-bridge.ts
|
||||
1 src/preload/native-chat-visual-guest-theme.ts
|
||||
|
||||
@@ -451,8 +451,7 @@
|
||||
5 src/main/pty/history/terminal-history.ts
|
||||
1 src/main/pty/process-retirement/posix-pty-process-table.ts
|
||||
12 src/main/pty/scrollback/overlay-mirror.ts
|
||||
1 src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts
|
||||
11 src/main/pty/scrollback/terminal-scrollback-snapshots.ts
|
||||
7 src/main/pty/scrollback/terminal-scrollback-snapshots.ts
|
||||
2 src/main/pty/shell-startup/codex-shell-launch-preflight.ts
|
||||
7 src/main/pty/shell-startup/git-bash.ts
|
||||
3 src/main/pty/shell-startup/legacy-terminal-posix-tombstone.ts
|
||||
|
||||
@@ -633,7 +633,7 @@
|
||||
1 src/renderer/src/components/terminal-pane/controller/TerminalPaneCodexRestartPortals.tsx
|
||||
1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-context-actions.ts
|
||||
3 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-foundation.ts
|
||||
10 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-projection.ts
|
||||
2 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-projection.ts
|
||||
3 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-startup-actions.ts
|
||||
1 src/renderer/src/components/terminal-pane/controller/use-terminal-pane-store-actions.ts
|
||||
1 src/renderer/src/components/terminal-pane/errors/TerminalErrorToast.tsx
|
||||
|
||||
+4
-15
@@ -95,20 +95,9 @@ export function registerSessionHandlers(store: Store, runtime: OrcaRuntimeServic
|
||||
return store.flushPendingOrThrowAsync()
|
||||
})
|
||||
|
||||
ipcMain.on(
|
||||
'session:read-terminal-scrollback-sync',
|
||||
(event, args: { ref?: unknown } | undefined) => {
|
||||
event.returnValue =
|
||||
typeof args?.ref === 'string' ? store.readTerminalScrollbackSnapshot(args.ref) : null
|
||||
}
|
||||
)
|
||||
|
||||
// Why: render-time planning only needs to know a local copy exists; a stat never reads bytes.
|
||||
ipcMain.on(
|
||||
'session:has-terminal-scrollback-sync',
|
||||
(event, args: { ref?: unknown } | undefined) => {
|
||||
event.returnValue =
|
||||
typeof args?.ref === 'string' ? store.hasTerminalScrollbackSnapshot(args.ref) : false
|
||||
}
|
||||
ipcMain.handle(
|
||||
'session:read-terminal-scrollback',
|
||||
(_event, args: { ref?: unknown } | undefined) =>
|
||||
typeof args?.ref === 'string' ? store.readTerminalScrollbackSnapshotAsync(args.ref) : null
|
||||
)
|
||||
}
|
||||
|
||||
+1
-1
@@ -133,7 +133,7 @@ describe('Store', () => {
|
||||
[TEST_LEAF_1]: expect.stringMatching(/^v1-[0-9a-f]{32}$/)
|
||||
})
|
||||
const ref = layout.scrollbackRefsByLeafId?.[TEST_LEAF_1]
|
||||
expect(ref ? store.readTerminalScrollbackSnapshot(ref) : null).toBe('Current buffer')
|
||||
expect(ref ? await store.readTerminalScrollbackSnapshotAsync(ref) : null).toBe('Current buffer')
|
||||
expect(layout.titlesByLeafId).toEqual({ [TEST_LEAF_1]: 'Current' })
|
||||
expect(session.tabsByWorktree.wt1[0].ptyId).toBe('daemon-pty')
|
||||
})
|
||||
|
||||
@@ -13,9 +13,7 @@ import { pruneLocalTerminalScrollbackBuffers } from '../../../../shared/workspac
|
||||
import { pruneWorkspaceSessionBrowserHistory } from '../../../../shared/workspace-session/workspace-session-browser-history'
|
||||
import { withoutRedundantGlobalFields } from '../../../../shared/workspace-session/workspace-session-host-field-ownership'
|
||||
import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id'
|
||||
import { readTerminalScrollbackSnapshotSync } from '../../../pty/scrollback/terminal-scrollback-snapshots'
|
||||
import {
|
||||
hasTerminalScrollbackSnapshotSync,
|
||||
readTerminalScrollbackSnapshot,
|
||||
statTerminalScrollbackSnapshotSize
|
||||
} from '../../../pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads'
|
||||
@@ -114,20 +112,6 @@ export class SessionHostPartitionOperations {
|
||||
)
|
||||
}
|
||||
|
||||
readTerminalScrollbackSnapshot(ref: string): string | null {
|
||||
return readTerminalScrollbackSnapshotSync(
|
||||
ref,
|
||||
this[sessionHostPartitionOperationsContext].runtime.terminalScrollbackSnapshotStorage
|
||||
)
|
||||
}
|
||||
|
||||
hasTerminalScrollbackSnapshot(ref: string): boolean {
|
||||
return hasTerminalScrollbackSnapshotSync(
|
||||
ref,
|
||||
this[sessionHostPartitionOperationsContext].runtime.terminalScrollbackSnapshotStorage
|
||||
)
|
||||
}
|
||||
|
||||
readTerminalScrollbackSnapshotAsync(ref: string): Promise<string | null> {
|
||||
return readTerminalScrollbackSnapshot(
|
||||
ref,
|
||||
|
||||
+1
-1
@@ -106,6 +106,6 @@ describe('Store', () => {
|
||||
initDataPath()
|
||||
const store = createSqliteTestStore(Store, { dataFile: profileDataFile })
|
||||
|
||||
expect(store.readTerminalScrollbackSnapshot(ref)).toBe('legacy-scrollback')
|
||||
expect(await store.readTerminalScrollbackSnapshotAsync(ref)).toBe('legacy-scrollback')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type * as FsPromises from 'node:fs/promises'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
|
||||
const counts = vi.hoisted(() => ({ open: 0, peak: 0 }))
|
||||
vi.mock('node:fs/promises', async (importOriginal) => {
|
||||
const fs = await importOriginal<typeof FsPromises>()
|
||||
return {
|
||||
...fs,
|
||||
open: async (...args: Parameters<typeof fs.open>) => {
|
||||
const handle = await fs.open(...args)
|
||||
counts.open++
|
||||
counts.peak = Math.max(counts.peak, counts.open)
|
||||
return {
|
||||
stat: () => handle.stat(),
|
||||
read: handle.read.bind(handle),
|
||||
close: async () => {
|
||||
try {
|
||||
await handle.close()
|
||||
} finally {
|
||||
counts.open--
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
import { readTerminalScrollbackSnapshot } from './terminal-scrollback-snapshot-nonblocking-reads'
|
||||
|
||||
// 3,300 serialized real filesystem reads need a wider timeout on slow CI disks.
|
||||
it('bounds simultaneous snapshot handles and delivers every queued frame after a missing read at N and 10N', async () => {
|
||||
const scratch = await mkdtemp(join(tmpdir(), 'orca-scrollback-reader-'))
|
||||
const snapshotRoot = join(scratch, 'terminal-scrollback')
|
||||
await mkdir(snapshotRoot)
|
||||
const ref = `v1-${'d'.repeat(32)}`
|
||||
await writeFile(join(snapshotRoot, `${ref}.bin`), 'saved frame 👩💻\n')
|
||||
try {
|
||||
for (const count of [300, 3_000]) {
|
||||
counts.peak = 0
|
||||
const outputs = await Promise.all([
|
||||
readTerminalScrollbackSnapshot(`v1-${'e'.repeat(32)}`, { snapshotRoot }),
|
||||
...Array.from({ length: count }, () =>
|
||||
readTerminalScrollbackSnapshot(ref, { snapshotRoot })
|
||||
)
|
||||
])
|
||||
expect(outputs[0]).toBeNull()
|
||||
expect(outputs.slice(1).every((text) => text === 'saved frame 👩💻\n')).toBe(true)
|
||||
expect(counts.peak).toBe(1)
|
||||
expect(counts.open).toBe(0)
|
||||
}
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true })
|
||||
}
|
||||
}, 10_000)
|
||||
@@ -1,5 +1,5 @@
|
||||
import { statSync } from 'node:fs'
|
||||
import { open, stat } from 'node:fs/promises'
|
||||
import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations'
|
||||
import { TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT } from '../../../shared/terminal/replay/terminal-scrollback-limits'
|
||||
import {
|
||||
decodeFromFirstUtf8Boundary,
|
||||
@@ -7,23 +7,6 @@ import {
|
||||
type TerminalScrollbackSnapshotStorage
|
||||
} from './terminal-scrollback-snapshots'
|
||||
|
||||
/** Whether a non-empty snapshot exists for `ref`; a stat only, so it never reads bytes. */
|
||||
export function hasTerminalScrollbackSnapshotSync(
|
||||
ref: string,
|
||||
storage?: TerminalScrollbackSnapshotStorage
|
||||
): boolean {
|
||||
for (const path of snapshotReadPaths(ref, storage)) {
|
||||
try {
|
||||
if (statSync(path).size > 0) {
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
// Try the legacy/global fallback when a profile-local snapshot is absent.
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Byte size of the snapshot `readTerminalScrollbackSnapshot` would read; `null` when absent. */
|
||||
export async function statTerminalScrollbackSnapshotSize(
|
||||
ref: string,
|
||||
@@ -55,17 +38,22 @@ async function readTrailingUtf8Async(path: string, maxBytes: number): Promise<st
|
||||
}
|
||||
}
|
||||
|
||||
/** Async twin of `readTerminalScrollbackSnapshotSync` for request paths that must not block. */
|
||||
const snapshotReads = new Map<string, Promise<void>>()
|
||||
|
||||
/** Read the bounded replay tail without blocking the request owner on disk I/O. */
|
||||
export async function readTerminalScrollbackSnapshot(
|
||||
ref: string,
|
||||
storage?: TerminalScrollbackSnapshotStorage
|
||||
): Promise<string | null> {
|
||||
for (const path of snapshotReadPaths(ref, storage)) {
|
||||
try {
|
||||
return await readTrailingUtf8Async(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT)
|
||||
} catch {
|
||||
// Try the legacy/global fallback when a profile-local snapshot is absent.
|
||||
// Async requests share the old single-reader resource bound without blocking the event loop.
|
||||
return runKeyedSerializedOperation(snapshotReads, 'snapshot-read', async () => {
|
||||
for (const path of snapshotReadPaths(ref, storage)) {
|
||||
try {
|
||||
return await readTrailingUtf8Async(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT)
|
||||
} catch {
|
||||
// Try the legacy/global fallback when a profile-local snapshot is absent.
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
return null
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,23 +1,10 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
closeSync,
|
||||
mkdirSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
readSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
||||
import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { getAppEnvironment } from '../../../shared/app-environment'
|
||||
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
|
||||
import {
|
||||
TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT,
|
||||
TERMINAL_SCROLLBACK_STORE_BYTE_LIMIT
|
||||
} from '../../../shared/terminal/replay/terminal-scrollback-limits'
|
||||
import { TERMINAL_SCROLLBACK_STORE_BYTE_LIMIT } from '../../../shared/terminal/replay/terminal-scrollback-limits'
|
||||
import { errorMessage } from '../../../shared/error-message'
|
||||
|
||||
const SNAPSHOT_DIR_NAME = 'terminal-scrollback'
|
||||
@@ -122,22 +109,6 @@ function trailingUtf8Bytes(value: string, maxBytes: number): Buffer {
|
||||
return bytes.subarray(start)
|
||||
}
|
||||
|
||||
function readTrailingUtf8(path: string, maxBytes: number): string {
|
||||
const size = statSync(path).size
|
||||
const length = Math.min(size, maxBytes)
|
||||
if (length <= 0) {
|
||||
return ''
|
||||
}
|
||||
const bytes = Buffer.allocUnsafe(length)
|
||||
const fd = openSync(path, 'r')
|
||||
try {
|
||||
readSync(fd, bytes, 0, length, size - length)
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
return decodeFromFirstUtf8Boundary(bytes)
|
||||
}
|
||||
|
||||
/** Decodes a tail slice, skipping continuation bytes of a character the slice cut in half. */
|
||||
export function decodeFromFirstUtf8Boundary(bytes: Buffer): string {
|
||||
let start = 0
|
||||
@@ -217,20 +188,6 @@ export async function writeTerminalScrollbackSnapshot(args: {
|
||||
}
|
||||
}
|
||||
|
||||
export function readTerminalScrollbackSnapshotSync(
|
||||
ref: string,
|
||||
storage?: TerminalScrollbackSnapshotStorage
|
||||
): string | null {
|
||||
for (const path of snapshotReadPaths(ref, storage)) {
|
||||
try {
|
||||
return readTrailingUtf8(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT)
|
||||
} catch {
|
||||
// Try the next snapshot root when this read fails.
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function deleteTerminalScrollbackSnapshotSync(
|
||||
ref: string,
|
||||
storage?: TerminalScrollbackSnapshotStorage
|
||||
|
||||
@@ -8,8 +8,5 @@ export const sessionApi = {
|
||||
patch: (args, hostId) => ipcRenderer.invoke('session:patch', args, hostId),
|
||||
closeTerminalSurface: (args) => ipcRenderer.invoke('session:close-terminal-surface', args),
|
||||
flush: () => ipcRenderer.invoke('session:flush'),
|
||||
readTerminalScrollback: (args) =>
|
||||
ipcRenderer.sendSync('session:read-terminal-scrollback-sync', args),
|
||||
hasTerminalScrollback: (args) =>
|
||||
ipcRenderer.sendSync('session:has-terminal-scrollback-sync', args)
|
||||
readTerminalScrollback: (args) => ipcRenderer.invoke('session:read-terminal-scrollback', args)
|
||||
} satisfies PreloadApi['session']
|
||||
|
||||
@@ -21,9 +21,7 @@ export type WorkspaceSessionApi = {
|
||||
reason?: 'user' | 'cleanup'
|
||||
}) => Promise<void>
|
||||
flush: () => Promise<void>
|
||||
readTerminalScrollback: (args: { ref: string }) => string | null
|
||||
/** Stat-only: whether this machine's snapshot store holds `ref`. */
|
||||
hasTerminalScrollback: (args: { ref: string }) => boolean
|
||||
readTerminalScrollback: (args: { ref: string }) => Promise<string | null>
|
||||
}
|
||||
cache: {
|
||||
getGitHub: () => Promise<{
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
import { TerminalPaneSurface } from './controller/TerminalPaneSurface'
|
||||
import { TerminalRestoringPlaceholder } from './mounting/TerminalRestoringPlaceholder'
|
||||
import { useTerminalPaneController } from './controller/use-terminal-pane-controller'
|
||||
import { useHostTerminalScrollbackHold } from './snapshots/use-host-terminal-scrollback-hold'
|
||||
import type { TerminalPaneProps } from './controller/terminal-pane-types'
|
||||
|
||||
function MountedTerminalPane(props: TerminalPaneProps): React.JSX.Element {
|
||||
export default function TerminalPane(props: TerminalPaneProps): React.JSX.Element {
|
||||
return <TerminalPaneSurface controller={useTerminalPaneController(props)} />
|
||||
}
|
||||
|
||||
export default function TerminalPane(props: TerminalPaneProps): React.JSX.Element {
|
||||
const holdForHostScrollback = useHostTerminalScrollbackHold(props.tabId, props.worktreeId)
|
||||
return holdForHostScrollback ? (
|
||||
<TerminalRestoringPlaceholder />
|
||||
) : (
|
||||
<MountedTerminalPane {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
+10
-3
@@ -2,12 +2,13 @@ import { useEffect } from 'react'
|
||||
import { applyTerminalAppearance } from './terminal-appearance'
|
||||
import { useThemeBackgroundStore } from '@/store/appearance/theme-background'
|
||||
import { usePluginFontReady } from '@/store/plugins/appearance/plugin-fonts'
|
||||
import type { UseTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types'
|
||||
import type { MountedTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types'
|
||||
import type { TerminalPaneLifecycleRefs } from '../mounting/use-terminal-pane-lifecycle-refs'
|
||||
|
||||
export function useMountedTerminalAppearance(
|
||||
deps: Pick<
|
||||
UseTerminalPaneLifecycleDeps,
|
||||
MountedTerminalPaneLifecycleDeps,
|
||||
| 'mountedManager'
|
||||
| 'managerRef'
|
||||
| 'settingsRef'
|
||||
| 'settings'
|
||||
@@ -27,7 +28,12 @@ export function useMountedTerminalAppearance(
|
||||
useEffect(() => {
|
||||
const manager = deps.managerRef.current
|
||||
const currentSettings = deps.settingsRef.current
|
||||
if (!manager || !deps.settings || !currentSettings) {
|
||||
if (
|
||||
!deps.mountedManager ||
|
||||
manager !== deps.mountedManager ||
|
||||
!deps.settings ||
|
||||
!currentSettings
|
||||
) {
|
||||
return
|
||||
}
|
||||
applyTerminalAppearance(
|
||||
@@ -40,6 +46,7 @@ export function useMountedTerminalAppearance(
|
||||
deps.paneLastThemeModeRef.current
|
||||
)
|
||||
}, [
|
||||
deps.mountedManager,
|
||||
deps.settings,
|
||||
themeBackgroundActive,
|
||||
terminalFontReady,
|
||||
|
||||
+4
-4
@@ -1,16 +1,16 @@
|
||||
import { useEffect } from 'react'
|
||||
import { applyTerminalScrollbackRowsToMountedPanes } from './mounted-terminal-scrollback'
|
||||
import type { UseTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types'
|
||||
import type { MountedTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types'
|
||||
|
||||
export function useMountedTerminalScrollback(
|
||||
deps: Pick<UseTerminalPaneLifecycleDeps, 'managerRef'>,
|
||||
deps: Pick<MountedTerminalPaneLifecycleDeps, 'mountedManager' | 'managerRef'>,
|
||||
terminalScrollbackRows: number
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const manager = deps.managerRef.current
|
||||
if (!manager) {
|
||||
if (!deps.mountedManager || manager !== deps.mountedManager) {
|
||||
return
|
||||
}
|
||||
applyTerminalScrollbackRowsToMountedPanes(manager, terminalScrollbackRows)
|
||||
}, [deps.managerRef, terminalScrollbackRows])
|
||||
}, [deps.mountedManager, deps.managerRef, terminalScrollbackRows])
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { useEffect } from 'react'
|
||||
import type { UseTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types'
|
||||
import type { MountedTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lifecycle-types'
|
||||
|
||||
export function useTerminalGpuPreference(
|
||||
deps: Pick<UseTerminalPaneLifecycleDeps, 'managerRef' | 'settings'>
|
||||
deps: Pick<MountedTerminalPaneLifecycleDeps, 'mountedManager' | 'managerRef' | 'settings'>
|
||||
): void {
|
||||
useEffect(() => {
|
||||
deps.managerRef.current?.setTerminalGpuAcceleration(
|
||||
if (!deps.mountedManager || deps.managerRef.current !== deps.mountedManager) {
|
||||
return
|
||||
}
|
||||
deps.managerRef.current.setTerminalGpuAcceleration(
|
||||
deps.settings?.terminalGpuAcceleration ?? 'auto'
|
||||
)
|
||||
}, [deps.settings?.terminalGpuAcceleration, deps.managerRef])
|
||||
}, [deps.mountedManager, deps.settings?.terminalGpuAcceleration, deps.managerRef])
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { TerminalRestoringPlaceholder } from '../mounting/TerminalRestoringPlaceholder'
|
||||
import { TerminalCrewPortals } from '../../orchestration-crew/TerminalCrewPortals'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { TerminalPaneFileDropOwner } from '../input/file-drop/TerminalPaneFileDropOwner'
|
||||
import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import { TerminalPaneFileDropOwners } from '../input/file-drop/TerminalPaneFileDropOwner'
|
||||
import TerminalSearch from '@/components/TerminalSearch'
|
||||
import { DaemonActionDialog } from '@/components/shared/useDaemonActions'
|
||||
import { AgentSessionContinuationDialog } from '@/components/agent-session-continuation/AgentSessionContinuationDialog'
|
||||
@@ -120,6 +120,8 @@ export function TerminalPaneSurface({
|
||||
showSshReconnectOverlay,
|
||||
splitTerminalPaneFromHeader,
|
||||
tabId,
|
||||
terminalMountPhase,
|
||||
terminalManager,
|
||||
terminalContainerStyle,
|
||||
terminalContentVisible,
|
||||
terminalLinkActionRequest,
|
||||
@@ -148,7 +150,12 @@ export function TerminalPaneSurface({
|
||||
data-terminal-chat-pane={effectiveChatViewMode && chatPane ? '' : undefined}
|
||||
data-terminal-layout-leaf-ids={expectedLayoutLeafIdsAttr}
|
||||
data-pane-title-surface={titleUsesLightSurface ? 'light' : 'dark'}
|
||||
style={terminalContainerStyle}
|
||||
inert={!terminalManager}
|
||||
style={
|
||||
terminalManager
|
||||
? terminalContainerStyle
|
||||
: { ...terminalContainerStyle, visibility: 'hidden' }
|
||||
}
|
||||
onContextMenuCapture={contextMenu.onContextMenuCapture}
|
||||
onMouseDownCapture={(event) => {
|
||||
contextMenu.onMouseDownCapture(event)
|
||||
@@ -182,17 +189,8 @@ export function TerminalPaneSurface({
|
||||
})
|
||||
}}
|
||||
/>
|
||||
{managedPanes.map((pane) => (
|
||||
<TerminalPaneFileDropOwner
|
||||
key={makePaneKey(tabId, pane.leafId)}
|
||||
pane={pane}
|
||||
tabId={tabId}
|
||||
worktreeId={worktreeId}
|
||||
cwd={cwd}
|
||||
managerRef={managerRef}
|
||||
paneTransportsRef={paneTransportsRef}
|
||||
/>
|
||||
))}
|
||||
{terminalMountPhase === 'host' && <TerminalRestoringPlaceholder />}
|
||||
<TerminalPaneFileDropOwners controller={controller} />
|
||||
<TerminalCrewPortals controller={controller} />
|
||||
<TerminalPaneCodexRestartPortals controller={controller} />
|
||||
<AgentLaunchPaneNoticePortal
|
||||
@@ -256,7 +254,7 @@ export function TerminalPaneSurface({
|
||||
<SessionRestoredBannerPortals panes={managedPanes} paneIds={sessionRestoredBannerPaneIds} />
|
||||
<TerminalPaneNativeChatPortal controller={controller} />
|
||||
<TerminalContextMenu
|
||||
open={contextMenu.open}
|
||||
open={Boolean(terminalManager) && contextMenu.open}
|
||||
onOpenChange={contextMenu.setOpen}
|
||||
onRestoreTerminalFocus={contextMenu.onRestoreTerminalFocus}
|
||||
menuPoint={contextMenu.point}
|
||||
@@ -313,7 +311,10 @@ export function TerminalPaneSurface({
|
||||
canCopyAgentSessionId={menuAgentSessionId !== null}
|
||||
onCopyAgentSessionId={() => void contextMenu.onCopyAgentSessionId()}
|
||||
/>
|
||||
<LinkActionPopover request={terminalLinkActionRequest} onClose={closeTerminalLinkActions} />
|
||||
<LinkActionPopover
|
||||
request={terminalManager ? terminalLinkActionRequest : null}
|
||||
onClose={closeTerminalLinkActions}
|
||||
/>
|
||||
{quickCommandEditorOpen ? (
|
||||
<TerminalQuickCommandEditorDialog
|
||||
command={quickCommandDraft}
|
||||
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
import { usePaneTitleRenameActions } from '../titles/use-pane-title-rename-actions'
|
||||
import { useCallback, useEffect } from 'react'
|
||||
import { useTerminalPaneContextMenu } from '../context-menu/use-terminal-pane-context-menu'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
import { useTerminalQuickCommandHosts } from '@/hooks/use-terminal-quick-command-hosts'
|
||||
import { useVisibleTerminalQuickCommandHosts } from '@/hooks/use-visible-terminal-quick-command-hosts'
|
||||
|
||||
export function useTerminalPaneContextActions(controller: TerminalPaneCloseController) {
|
||||
export function useTerminalPaneContextActions(controller: TerminalPaneMountedController) {
|
||||
const {
|
||||
cancelPendingRenameFrames,
|
||||
clearPaneScrollback,
|
||||
@@ -128,5 +128,5 @@ export function useTerminalPaneContextActions(controller: TerminalPaneCloseContr
|
||||
}
|
||||
}
|
||||
|
||||
export type TerminalPaneContextController = TerminalPaneCloseController &
|
||||
export type TerminalPaneContextController = TerminalPaneMountedController &
|
||||
ReturnType<typeof useTerminalPaneContextActions>
|
||||
|
||||
+4
-4
@@ -32,16 +32,16 @@ export function useTerminalPaneController(props: TerminalPaneProps) {
|
||||
const store = Object.assign(chat, useTerminalPaneStoreBindings(chat))
|
||||
const startup = Object.assign(store, useTerminalPaneStartupActions(store))
|
||||
const layout = Object.assign(startup, useTerminalPaneLayoutPersistence(startup))
|
||||
useHostPaneTitleSync(layout)
|
||||
const bindings = Object.assign(layout, useTerminalPaneLayoutBindings(layout))
|
||||
const close = Object.assign(
|
||||
bindings,
|
||||
useTerminalPaneCloseActions(bindings),
|
||||
useTerminalPaneTabDetachActions(bindings)
|
||||
)
|
||||
useTerminalPaneLifecycleStage(close)
|
||||
const reconciliation = Object.assign(close, useTerminalPaneReconciliation(close))
|
||||
useLayoutOwnerPaneTreeWhenMain(close)
|
||||
const mounted = Object.assign(close, useTerminalPaneLifecycleStage(close))
|
||||
useHostPaneTitleSync(mounted)
|
||||
const reconciliation = Object.assign(mounted, useTerminalPaneReconciliation(mounted))
|
||||
useLayoutOwnerPaneTreeWhenMain(mounted)
|
||||
useTerminalPaneGlobalListeners(reconciliation)
|
||||
useTerminalPanePasteListeners(reconciliation)
|
||||
useTerminalPaneTitleEffects(reconciliation)
|
||||
|
||||
+12
-4
@@ -3,9 +3,9 @@ import { useRegularTerminalInputFocus } from '../input/focus/use-regular-termina
|
||||
import { useTerminalFontZoom } from '../appearance/useTerminalFontZoom'
|
||||
import { useTerminalKeyboardShortcuts } from '../input/keyboard/terminal-keyboard-hook'
|
||||
import { useTerminalPaneGlobalEffects } from '../viewport/visibility/use-terminal-pane-global-effects'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useTerminalPaneGlobalListeners(controller: TerminalPaneCloseController): void {
|
||||
export function useTerminalPaneGlobalListeners(controller: TerminalPaneMountedController): void {
|
||||
const {
|
||||
clearPaneScrollback,
|
||||
containerRef,
|
||||
@@ -25,6 +25,7 @@ export function useTerminalPaneGlobalListeners(controller: TerminalPaneCloseCont
|
||||
keybindings,
|
||||
macOptionAsAltRef,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
paneCwdRef,
|
||||
paneKittyKeyboardModesRef,
|
||||
@@ -51,7 +52,7 @@ export function useTerminalPaneGlobalListeners(controller: TerminalPaneCloseCont
|
||||
useTerminalKeyboardShortcuts({
|
||||
tabId,
|
||||
worktreeId,
|
||||
isActive,
|
||||
isActive: isActive && Boolean(terminalManager),
|
||||
keyboardScopeRef: containerRef,
|
||||
managerRef,
|
||||
paneTransportsRef,
|
||||
@@ -79,6 +80,7 @@ export function useTerminalPaneGlobalListeners(controller: TerminalPaneCloseCont
|
||||
terminalShortcutPolicy: settings?.terminalShortcutPolicy ?? 'orca-first'
|
||||
})
|
||||
useTerminalPaneGlobalEffects({
|
||||
terminalManager,
|
||||
tabId,
|
||||
cwd,
|
||||
isActive,
|
||||
@@ -97,7 +99,13 @@ export function useTerminalPaneGlobalListeners(controller: TerminalPaneCloseCont
|
||||
toggleExpandPane
|
||||
})
|
||||
|
||||
useWebClientTerminalResize({ isActive, isVisible, managerRef, paneTransportsRef })
|
||||
useWebClientTerminalResize({
|
||||
terminalManager,
|
||||
isActive,
|
||||
isVisible,
|
||||
managerRef,
|
||||
paneTransportsRef
|
||||
})
|
||||
|
||||
useRegularTerminalInputFocus({ containerRef })
|
||||
}
|
||||
|
||||
@@ -11,9 +11,10 @@ import type { UseTerminalPaneLifecycleDeps } from '../mounting/terminal-pane-lif
|
||||
import { useTerminalPaneMountLifecycle } from '../mounting/use-terminal-pane-mount-lifecycle'
|
||||
import { useTerminalPaneLifecycleRefs } from '../mounting/use-terminal-pane-lifecycle-refs'
|
||||
|
||||
export function useTerminalPaneLifecycle(deps: UseTerminalPaneLifecycleDeps): void {
|
||||
export function useTerminalPaneLifecycle(deps: UseTerminalPaneLifecycleDeps) {
|
||||
const refs = useTerminalPaneLifecycleRefs()
|
||||
useTerminalPaneMountLifecycle(deps, refs)
|
||||
const mount = useTerminalPaneMountLifecycle(deps, refs)
|
||||
const mountedDeps = { ...deps, mountedManager: mount.manager }
|
||||
|
||||
const terminalScrollbackRows = normalizeDesktopTerminalScrollbackRows(
|
||||
deps.settings?.terminalScrollbackRows
|
||||
@@ -27,15 +28,16 @@ export function useTerminalPaneLifecycle(deps: UseTerminalPaneLifecycleDeps): vo
|
||||
|
||||
useTerminalPaneHibernationWake(deps)
|
||||
|
||||
useTerminalPaneProcessVisibility(deps, refs)
|
||||
useTerminalPaneProcessVisibility(mountedDeps, refs)
|
||||
|
||||
useTerminalForegroundAgentSampling(deps)
|
||||
|
||||
useMountedTerminalAppearance(deps, systemPrefersDarkRef)
|
||||
useMountedTerminalAppearance(mountedDeps, systemPrefersDarkRef)
|
||||
|
||||
useTerminalGpuPreference(deps)
|
||||
useTerminalGpuPreference(mountedDeps)
|
||||
|
||||
useMountedTerminalScrollback(deps, terminalScrollbackRows)
|
||||
useMountedTerminalScrollback(mountedDeps, terminalScrollbackRows)
|
||||
|
||||
useTerminalMouseHidePreference(deps, refs)
|
||||
useTerminalMouseHidePreference(mountedDeps, refs)
|
||||
return mount
|
||||
}
|
||||
|
||||
+2
@@ -16,6 +16,7 @@ export function useTerminalPaneProcessExitActions(controller: TerminalPaneCloseC
|
||||
cwd,
|
||||
dispatchNotification,
|
||||
executeClosePane,
|
||||
initialLayoutRef,
|
||||
isActiveRef,
|
||||
isVisibleRef,
|
||||
markTerminalBell,
|
||||
@@ -56,6 +57,7 @@ export function useTerminalPaneProcessExitActions(controller: TerminalPaneCloseC
|
||||
clearTabPtyId,
|
||||
cwd,
|
||||
dispatchNotification,
|
||||
initialLayoutRef,
|
||||
isActiveRef,
|
||||
isVisibleRef,
|
||||
markTerminalBell,
|
||||
|
||||
+3
-3
@@ -22,7 +22,7 @@ export function useTerminalPaneProjection(controller: TerminalPaneMobileControll
|
||||
isChatEligibleForLeaf,
|
||||
isChatViewMode,
|
||||
isVisible,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
toggleNativeChatForLeaf,
|
||||
paneTitles,
|
||||
paneTransportsRef,
|
||||
@@ -55,8 +55,8 @@ export function useTerminalPaneProjection(controller: TerminalPaneMobileControll
|
||||
shouldMeasureHiddenStartup,
|
||||
systemPrefersDark
|
||||
})
|
||||
const activePane = managerRef.current?.getActivePane()
|
||||
const managedPanes = managerRef.current?.getPanes() ?? []
|
||||
const activePane = terminalManager?.getActivePane()
|
||||
const managedPanes = terminalManager?.getPanes() ?? []
|
||||
const activePaneRuntimeEnvironmentId = activePane
|
||||
? (paneTransportsRef.current.get(activePane.id)?.getRuntimeEnvironmentId?.() ?? null)
|
||||
: undefined
|
||||
|
||||
+5
-2
@@ -3,9 +3,9 @@ import { useHostTerminalLayoutReconciliation } from '../layout/reconciliation/us
|
||||
import { useTerminalPaneActivityIsolation } from '../layout/isolation/use-terminal-pane-activity-isolation'
|
||||
import { useRef } from 'react'
|
||||
import { useTerminalPaneProcessExitActions } from './use-terminal-pane-process-exit-actions'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useTerminalPaneReconciliation(controller: TerminalPaneCloseController) {
|
||||
export function useTerminalPaneReconciliation(controller: TerminalPaneMountedController) {
|
||||
const {
|
||||
activityIsolationSnapshotRef,
|
||||
closeTerminalLinkActions,
|
||||
@@ -16,6 +16,7 @@ export function useTerminalPaneReconciliation(controller: TerminalPaneCloseContr
|
||||
isRendererVisible,
|
||||
isolatedPaneKey,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
paneLayoutRevision,
|
||||
paneTransportsRef,
|
||||
@@ -36,6 +37,7 @@ export function useTerminalPaneReconciliation(controller: TerminalPaneCloseContr
|
||||
})
|
||||
|
||||
useHostTerminalLayoutReconciliation({
|
||||
terminalManager,
|
||||
executeClosePane,
|
||||
hostRetiredLeafIdsRef,
|
||||
isActive,
|
||||
@@ -49,6 +51,7 @@ export function useTerminalPaneReconciliation(controller: TerminalPaneCloseContr
|
||||
})
|
||||
|
||||
useTerminalPaneActivityIsolation({
|
||||
terminalManager,
|
||||
activityIsolationSnapshotRef,
|
||||
containerRef,
|
||||
isolatedPaneKey,
|
||||
|
||||
-5
@@ -1,6 +1,5 @@
|
||||
import { useQueuedTabStartupAcknowledgement } from '../mounting/use-queued-tab-startup-acknowledgement'
|
||||
import { useVisibleTerminalMeasurement } from '../viewport/use-visible-terminal-measurement'
|
||||
import { useIssueCommandSplitSettlement } from '../layout/split/use-issue-command-split-settlement'
|
||||
import { useRestoredSessionBannerActions } from '../session-restore/use-restored-session-banner-actions'
|
||||
import { useTerminalSessionSaveRecovery } from '../errors/use-terminal-session-save-recovery'
|
||||
import { useTerminalQuickCommandEditor } from '../quick-commands/use-terminal-quick-command-editor'
|
||||
@@ -16,10 +15,8 @@ import type { TerminalPaneStoreController } from './use-terminal-pane-store-bind
|
||||
|
||||
export function useTerminalPaneStartupActions(controller: TerminalPaneStoreController) {
|
||||
const {
|
||||
consumeTabIssueCommandSplit,
|
||||
consumeTabStartupCommand,
|
||||
containerRef,
|
||||
issueCommandSplit,
|
||||
isVisible,
|
||||
managerRef,
|
||||
onPtyExit,
|
||||
@@ -87,8 +84,6 @@ export function useTerminalPaneStartupActions(controller: TerminalPaneStoreContr
|
||||
quickCommandEditorHostId
|
||||
})
|
||||
|
||||
useIssueCommandSplitSettlement({ consumeTabIssueCommandSplit, issueCommandSplit, tabId })
|
||||
|
||||
const settingsRef = useRef(settings)
|
||||
// Startup callbacks can run before the next effect commit.
|
||||
// react-doctor-disable-next-line react-doctor/no-ref-current-in-render
|
||||
|
||||
+12
-4
@@ -4,9 +4,9 @@ import { usePaneTitleOverlayGeometry } from '../titles/use-pane-title-overlay-ge
|
||||
import { useRestoredBannerPanePruning } from '../session-restore/use-restored-banner-pane-pruning'
|
||||
import { useTerminalShutdownBufferCapture } from '../snapshots/use-terminal-shutdown-buffer-capture'
|
||||
import { usePaneTitleRenameBlurIntent } from '../titles/use-pane-title-rename-blur-intent'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useTerminalPaneTitleEffects(controller: TerminalPaneCloseController): void {
|
||||
export function useTerminalPaneTitleEffects(controller: TerminalPaneMountedController): void {
|
||||
const {
|
||||
clearedScrollbackLeafIdsRef,
|
||||
containerRef,
|
||||
@@ -14,6 +14,7 @@ export function useTerminalPaneTitleEffects(controller: TerminalPaneCloseControl
|
||||
isolatedPaneKey,
|
||||
isVisible,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
paneLayoutRevision,
|
||||
paneTitles,
|
||||
@@ -31,9 +32,10 @@ export function useTerminalPaneTitleEffects(controller: TerminalPaneCloseControl
|
||||
worktreeId
|
||||
} = controller
|
||||
|
||||
useTerminalPaneAttention({ managerRef, paneCount, tabId })
|
||||
useTerminalPaneAttention({ terminalManager, managerRef, paneCount, tabId })
|
||||
|
||||
useRestoredBannerTitleSpace({
|
||||
terminalManager,
|
||||
isVisible,
|
||||
managerRef,
|
||||
paneCount,
|
||||
@@ -45,6 +47,7 @@ export function useTerminalPaneTitleEffects(controller: TerminalPaneCloseControl
|
||||
})
|
||||
|
||||
usePaneTitleOverlayGeometry({
|
||||
terminalManager,
|
||||
containerRef,
|
||||
expandedPaneId,
|
||||
isolatedPaneKey,
|
||||
@@ -59,7 +62,12 @@ export function useTerminalPaneTitleEffects(controller: TerminalPaneCloseControl
|
||||
shouldMeasureHiddenStartup
|
||||
})
|
||||
|
||||
useRestoredBannerPanePruning({ managerRef, paneCount, setSessionRestoredBannerPaneIds })
|
||||
useRestoredBannerPanePruning({
|
||||
terminalManager,
|
||||
managerRef,
|
||||
paneCount,
|
||||
setSessionRestoredBannerPaneIds
|
||||
})
|
||||
|
||||
useTerminalShutdownBufferCapture({
|
||||
clearedScrollbackLeafIdsRef,
|
||||
|
||||
+25
@@ -1,3 +1,5 @@
|
||||
import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import type { TerminalPaneController } from '../../controller/use-terminal-pane-controller'
|
||||
import { useLayoutEffect } from 'react'
|
||||
import {
|
||||
useTerminalPaneFileDropOwner,
|
||||
@@ -13,3 +15,26 @@ export function TerminalPaneFileDropOwner(args: TerminalPaneFileDropOwnerArgs):
|
||||
}, [attach, args.pane.container])
|
||||
return null
|
||||
}
|
||||
|
||||
export function TerminalPaneFileDropOwners({
|
||||
controller
|
||||
}: {
|
||||
controller: TerminalPaneController
|
||||
}): React.JSX.Element {
|
||||
const { managedPanes, tabId, worktreeId, cwd, managerRef, paneTransportsRef } = controller
|
||||
return (
|
||||
<>
|
||||
{managedPanes.map((pane) => (
|
||||
<TerminalPaneFileDropOwner
|
||||
key={makePaneKey(tabId, pane.leafId)}
|
||||
pane={pane}
|
||||
tabId={tabId}
|
||||
worktreeId={worktreeId}
|
||||
cwd={cwd}
|
||||
managerRef={managerRef}
|
||||
paneTransportsRef={paneTransportsRef}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
+5
-4
@@ -1,10 +1,11 @@
|
||||
import { useEffect } from 'react'
|
||||
import { createTerminalPanePasteExecution } from './terminal-pane-paste-execution'
|
||||
import { registerTerminalPanePasteListeners } from './terminal-pane-paste-listeners'
|
||||
import type { TerminalPaneCloseController } from '../../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useTerminalPanePasteListeners(controller: TerminalPaneCloseController): void {
|
||||
export function useTerminalPanePasteListeners(controller: TerminalPaneMountedController): void {
|
||||
const {
|
||||
terminalManager,
|
||||
containerRef,
|
||||
forceBracketedMultilineTextPaste,
|
||||
isActive,
|
||||
@@ -14,7 +15,7 @@ export function useTerminalPanePasteListeners(controller: TerminalPaneCloseContr
|
||||
} = controller
|
||||
|
||||
useEffect(() => {
|
||||
if (!isActive) {
|
||||
if (!isActive || !terminalManager) {
|
||||
return
|
||||
}
|
||||
const container = containerRef.current
|
||||
@@ -36,5 +37,5 @@ export function useTerminalPanePasteListeners(controller: TerminalPaneCloseContr
|
||||
shortcutPlatform
|
||||
})
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- Preserve the pre-split dependency contract.
|
||||
}, [isActive, worktreeId, keybindings, forceBracketedMultilineTextPaste, tabId])
|
||||
}, [terminalManager, isActive, worktreeId, keybindings, forceBracketedMultilineTextPaste, tabId])
|
||||
}
|
||||
|
||||
+9
-4
@@ -1,15 +1,15 @@
|
||||
import { useEffect } from 'react'
|
||||
import { installMouseHideWhileTyping } from './mouse-hide-while-typing'
|
||||
import type { UseTerminalPaneLifecycleDeps } from '../../mounting/terminal-pane-lifecycle-types'
|
||||
import type { MountedTerminalPaneLifecycleDeps } from '../../mounting/terminal-pane-lifecycle-types'
|
||||
import type { TerminalPaneLifecycleRefs } from '../../mounting/use-terminal-pane-lifecycle-refs'
|
||||
|
||||
export function useTerminalMouseHidePreference(
|
||||
deps: Pick<UseTerminalPaneLifecycleDeps, 'managerRef' | 'settings'>,
|
||||
deps: Pick<MountedTerminalPaneLifecycleDeps, 'mountedManager' | 'managerRef' | 'settings'>,
|
||||
refs: Pick<TerminalPaneLifecycleRefs, 'mouseHideDisposablesRef'>
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const manager = deps.managerRef.current
|
||||
if (!manager) {
|
||||
if (!deps.mountedManager || manager !== deps.mountedManager) {
|
||||
return
|
||||
}
|
||||
const hide = deps.settings?.terminalMouseHideWhileTyping ?? false
|
||||
@@ -25,5 +25,10 @@ export function useTerminalMouseHidePreference(
|
||||
refs.mouseHideDisposablesRef.current.delete(pane.id)
|
||||
}
|
||||
}
|
||||
}, [deps.settings?.terminalMouseHideWhileTyping, deps.managerRef, refs.mouseHideDisposablesRef])
|
||||
}, [
|
||||
deps.mountedManager,
|
||||
deps.settings?.terminalMouseHideWhileTyping,
|
||||
deps.managerRef,
|
||||
refs.mouseHideDisposablesRef
|
||||
])
|
||||
}
|
||||
|
||||
+16
-3
@@ -6,27 +6,32 @@ import {
|
||||
} from '../expand/expanded-pane-layout'
|
||||
import { safeFit } from '@/lib/pane-manager/terminal-fit/pane-fit'
|
||||
import { resolvePaneKeyForManager } from '@/lib/pane-manager/pane-key-resolution'
|
||||
import type { TerminalPaneCloseController } from '../close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useTerminalPaneActivityIsolation({
|
||||
activityIsolationSnapshotRef,
|
||||
containerRef,
|
||||
isolatedPaneKey,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
pendingPaneSizeRefreshFrameIdsRef,
|
||||
tabId
|
||||
}: Pick<
|
||||
TerminalPaneCloseController,
|
||||
TerminalPaneMountedController,
|
||||
| 'activityIsolationSnapshotRef'
|
||||
| 'containerRef'
|
||||
| 'isolatedPaneKey'
|
||||
| 'managerRef'
|
||||
| 'terminalManager'
|
||||
| 'paneCount'
|
||||
| 'pendingPaneSizeRefreshFrameIdsRef'
|
||||
| 'tabId'
|
||||
>): void {
|
||||
useLayoutEffect(() => {
|
||||
if (!terminalManager || managerRef.current !== terminalManager) {
|
||||
return
|
||||
}
|
||||
const snapshots = activityIsolationSnapshotRef.current
|
||||
const scheduleRefit = (): number =>
|
||||
requestAnimationFrame(() => {
|
||||
@@ -66,7 +71,15 @@ export function useTerminalPaneActivityIsolation({
|
||||
}
|
||||
const frame = scheduleRefit()
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [isolatedPaneKey, paneCount, tabId, activityIsolationSnapshotRef, containerRef, managerRef])
|
||||
}, [
|
||||
isolatedPaneKey,
|
||||
paneCount,
|
||||
tabId,
|
||||
activityIsolationSnapshotRef,
|
||||
containerRef,
|
||||
managerRef,
|
||||
terminalManager
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
const snapshots = activityIsolationSnapshotRef.current
|
||||
|
||||
+15
-4
@@ -9,15 +9,16 @@ import {
|
||||
} from '@/runtime/workspace-layout/intents/layout-owner-pane-tree-holds'
|
||||
import { isHostAuthoritativeLayout } from '../reconciliation/terminal-live-layout-reconciliation'
|
||||
import { reconcileMountedPanesToLayout } from '../reconciliation/terminal-pane-frame-reconciliation'
|
||||
import type { TerminalPaneCloseController } from '../close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
/** Local tabs follow main’s framed tree; paired tabs use host reconciliation, and pending local commands hold their tab until answered. */
|
||||
export function useLayoutOwnerPaneTree(controller: TerminalPaneCloseController): void {
|
||||
export function useLayoutOwnerPaneTree(controller: TerminalPaneMountedController): void {
|
||||
const {
|
||||
closePaneLocally,
|
||||
expandedPaneIdRef,
|
||||
isolatedPaneKey,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
persistLayoutSnapshot,
|
||||
restoredLayout,
|
||||
tabId,
|
||||
@@ -45,7 +46,8 @@ export function useLayoutOwnerPaneTree(controller: TerminalPaneCloseController):
|
||||
useEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (
|
||||
!manager ||
|
||||
!terminalManager ||
|
||||
manager !== terminalManager ||
|
||||
isTabPaneTreeHeld(tabId) ||
|
||||
// By host kind, as frames decide it: a paired-server tab may not have bound a remote PTY yet.
|
||||
pairedServerMirrors(useAppStore.getState())(worktreeId) ||
|
||||
@@ -74,5 +76,14 @@ export function useLayoutOwnerPaneTree(controller: TerminalPaneCloseController):
|
||||
persistLayoutSnapshot()
|
||||
}
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- closePaneLocally/persistLayoutSnapshot change with tab callbacks; re-reconciling on that would replay layout writes.
|
||||
}, [restoredLayout, redraws, zoomed, tabId, worktreeId, managerRef, expandedPaneIdRef])
|
||||
}, [
|
||||
restoredLayout,
|
||||
redraws,
|
||||
zoomed,
|
||||
tabId,
|
||||
worktreeId,
|
||||
terminalManager,
|
||||
managerRef,
|
||||
expandedPaneIdRef
|
||||
])
|
||||
}
|
||||
|
||||
+2
@@ -22,6 +22,7 @@ export function useTerminalPaneLayoutPersistence(controller: TerminalPaneStartup
|
||||
clearedScrollbackLeafIdsRef,
|
||||
chatLeafId,
|
||||
containerRef,
|
||||
initialLayoutRef,
|
||||
isChatViewMode,
|
||||
expandedPaneIdRef,
|
||||
managerRef,
|
||||
@@ -144,6 +145,7 @@ export function useTerminalPaneLayoutPersistence(controller: TerminalPaneStartup
|
||||
}, [chatLeafId, isChatViewMode, persistLayoutSnapshot])
|
||||
|
||||
const { clearPaneScrollback } = usePaneScrollbackClear({
|
||||
initialLayoutRef,
|
||||
clearedScrollbackLeafIdsRef,
|
||||
paneTransportsRef,
|
||||
persistLayoutSnapshot
|
||||
|
||||
+6
-3
@@ -7,13 +7,14 @@ import {
|
||||
trackRetiredLeafIds
|
||||
} from './terminal-live-layout-reconciliation'
|
||||
import { collectLeafIds } from '../../../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree'
|
||||
import type { TerminalPaneCloseController } from '../close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useHostTerminalLayoutReconciliation({
|
||||
executeClosePane,
|
||||
hostRetiredLeafIdsRef,
|
||||
isActive,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
paneTransportsRef,
|
||||
persistLayoutSnapshot,
|
||||
@@ -21,11 +22,12 @@ export function useHostTerminalLayoutReconciliation({
|
||||
restoredLayout,
|
||||
hostLayoutLeafIdsRef
|
||||
}: Pick<
|
||||
TerminalPaneCloseController,
|
||||
TerminalPaneMountedController,
|
||||
| 'executeClosePane'
|
||||
| 'hostRetiredLeafIdsRef'
|
||||
| 'isActive'
|
||||
| 'managerRef'
|
||||
| 'terminalManager'
|
||||
| 'paneCount'
|
||||
| 'paneTransportsRef'
|
||||
| 'persistLayoutSnapshot'
|
||||
@@ -34,7 +36,7 @@ export function useHostTerminalLayoutReconciliation({
|
||||
> & { hostLayoutLeafIdsRef: React.RefObject<ReadonlySet<string>> }): void {
|
||||
useEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (!manager || !restoredLayout.root) {
|
||||
if (!terminalManager || manager !== terminalManager || !restoredLayout.root) {
|
||||
return
|
||||
}
|
||||
// Why the retired check: dropping a retired leaf can drop the layout's only remote PTY id.
|
||||
@@ -128,6 +130,7 @@ export function useHostTerminalLayoutReconciliation({
|
||||
restoredLayout,
|
||||
hostRetiredLeafIdsRef,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneTransportsRef
|
||||
])
|
||||
}
|
||||
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { useEffect } from 'react'
|
||||
import type { TerminalPaneStoreController } from '../../controller/use-terminal-pane-store-bindings'
|
||||
|
||||
export function useIssueCommandSplitSettlement({
|
||||
consumeTabIssueCommandSplit,
|
||||
issueCommandSplit,
|
||||
tabId
|
||||
}: Pick<
|
||||
TerminalPaneStoreController,
|
||||
'consumeTabIssueCommandSplit' | 'issueCommandSplit' | 'tabId'
|
||||
>) {
|
||||
useEffect(() => {
|
||||
if (issueCommandSplit) {
|
||||
consumeTabIssueCommandSplit(tabId)
|
||||
}
|
||||
}, [issueCommandSplit, tabId, consumeTabIssueCommandSplit])
|
||||
}
|
||||
@@ -59,9 +59,18 @@ export function restoreTerminalPaneLayout(args: {
|
||||
) {
|
||||
const layoutWithoutRestoredBuffers = { ...initialLayoutRef.current }
|
||||
delete layoutWithoutRestoredBuffers.buffersByLeafId
|
||||
if (hasScrollbackRefs) {
|
||||
initialLayoutRef.current = layoutWithoutRestoredBuffers
|
||||
}
|
||||
const retainedInline = Object.fromEntries(
|
||||
Object.entries(restoredBuffers).filter(
|
||||
([leafId]) =>
|
||||
restoredPaneByLeafId.has(leafId) &&
|
||||
initialLayoutRef.current.scrollbackRefsByLeafId?.[leafId] === undefined &&
|
||||
!deps.clearedScrollbackLeafIdsRef?.current.has(leafId)
|
||||
)
|
||||
)
|
||||
initialLayoutRef.current =
|
||||
Object.keys(retainedInline).length > 0
|
||||
? { ...layoutWithoutRestoredBuffers, buffersByLeafId: retainedInline }
|
||||
: layoutWithoutRestoredBuffers
|
||||
if (initialLayoutHadBuffers) {
|
||||
useAppStore.getState().setTabLayout(tabId, layoutWithoutRestoredBuffers)
|
||||
}
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import { Terminal } from '@xterm/headless'
|
||||
import { vi, type Mock } from 'vitest'
|
||||
import type {
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalTab
|
||||
} from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { mintStablePaneId } from '@/lib/pane-manager/pane-layout/mint-stable-pane-id'
|
||||
import type { UseTerminalPaneLifecycleDeps } from './terminal-pane-lifecycle-types'
|
||||
import type { PtyConnectionDeps } from '../pty-connection/pty-connection-deps'
|
||||
import type { ConnectPanePtySession } from '../pty-connection/connect-pane-pty-session'
|
||||
import { bindRegisterPaneSerializer } from '../pty-connection/serialization/pane-serializer-register'
|
||||
|
||||
export const FIRST_LEAF = '11111111-1111-4111-8111-111111111111'
|
||||
export const SECOND_LEAF = '22222222-2222-4222-8222-222222222222'
|
||||
export const FIRST_REF = `v1-${'a'.repeat(32)}`
|
||||
export const SECOND_REF = `v1-${'b'.repeat(32)}`
|
||||
export const NEW_REF = `v1-${'c'.repeat(32)}`
|
||||
|
||||
export class HeadlessMountManager {
|
||||
static instances: HeadlessMountManager[] = []
|
||||
panes: { id: number; leafId: string; terminal: Terminal; container: HTMLDivElement }[] = []
|
||||
activeId = 1
|
||||
destroyed = false
|
||||
gpu: string | undefined
|
||||
splitStartups: unknown[] = []
|
||||
constructor(
|
||||
readonly container: HTMLDivElement,
|
||||
readonly options: { getStartup?: () => unknown; ptyDeps?: PtyConnectionDeps } = {}
|
||||
) {
|
||||
HeadlessMountManager.instances.push(this)
|
||||
}
|
||||
createInitialPane({ leafId }: { leafId: string }) {
|
||||
const pane = {
|
||||
id: this.panes.length + 1,
|
||||
leafId,
|
||||
terminal: new Terminal({ cols: 80, rows: 6, allowProposedApi: true }),
|
||||
container: document.createElement('div')
|
||||
}
|
||||
pane.container.className = 'pane'
|
||||
pane.container.dataset.leafId = leafId
|
||||
this.panes.push(pane)
|
||||
this.container.append(pane.container)
|
||||
return pane
|
||||
}
|
||||
splitPane(id: number, direction: string, options?: { leafId: string }) {
|
||||
this.splitStartups.push(this.options.getStartup?.())
|
||||
const existing = this.panes.find((pane) => pane.id === id)!
|
||||
const split = document.createElement('div')
|
||||
split.className = `pane-split ${direction === 'horizontal' ? 'is-horizontal' : ''}`
|
||||
existing.container.replaceWith(split)
|
||||
const next = this.createInitialPane({ leafId: options?.leafId ?? mintStablePaneId() })
|
||||
split.append(existing.container, next.container)
|
||||
return next
|
||||
}
|
||||
getLeafIdMap() {
|
||||
return new Map(this.panes.map((pane) => [pane.id, pane.leafId]))
|
||||
}
|
||||
getPanes() {
|
||||
return this.panes
|
||||
}
|
||||
getActivePane() {
|
||||
return this.panes.find((pane) => pane.id === this.activeId)
|
||||
}
|
||||
getNumericIdForLeaf(leafId: string) {
|
||||
return this.panes.find((pane) => pane.leafId === leafId)?.id ?? null
|
||||
}
|
||||
setActivePane(id: number) {
|
||||
this.activeId = id
|
||||
}
|
||||
hasWebglRenderer() {
|
||||
return true
|
||||
}
|
||||
setTerminalGpuAcceleration(value: string) {
|
||||
this.gpu = value
|
||||
}
|
||||
fitAllPanes() {}
|
||||
destroy() {
|
||||
this.destroyed = true
|
||||
for (const pane of this.panes) {
|
||||
pane.terminal.dispose()
|
||||
pane.container.remove()
|
||||
}
|
||||
this.container.replaceChildren()
|
||||
}
|
||||
}
|
||||
|
||||
export function registerRuntimeClear(manager: HeadlessMountManager, ptyId: string) {
|
||||
const originalApi = window.api
|
||||
const onClearBufferRequest = vi.fn<typeof window.api.pty.onClearBufferRequest>(() => () => {})
|
||||
Object.defineProperty(window, 'api', {
|
||||
configurable: true,
|
||||
value: {
|
||||
...originalApi,
|
||||
pty: {
|
||||
...originalApi?.pty,
|
||||
onClearBufferRequest,
|
||||
onResetInputModesRequest: () => () => {},
|
||||
onSerializeBufferRequest: () => () => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
const adapter = {
|
||||
pane: manager.panes[0],
|
||||
manager,
|
||||
deps: manager.options.ptyDeps,
|
||||
disposed: false,
|
||||
clearHiddenOutputRestoreState: () => {},
|
||||
onDataDisposable: { dispose: () => {} }
|
||||
}
|
||||
const session =
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the production clear/title registration reads these fields and real factory deps; serialization and transport are excluded.
|
||||
adapter as unknown as ConnectPanePtySession
|
||||
bindRegisterPaneSerializer(session)
|
||||
session.registerPaneSerializerFor(ptyId)
|
||||
return {
|
||||
clear: () => onClearBufferRequest.mock.calls[0][0]({ ptyId }),
|
||||
dispose: () => {
|
||||
session.onDataDisposable.dispose()
|
||||
Object.defineProperty(window, 'api', { configurable: true, value: originalApi })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function mountDeps(): UseTerminalPaneLifecycleDeps {
|
||||
return {
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
cwd: '/first',
|
||||
consumeTabIssueCommandSplit: vi.fn(),
|
||||
isActive: false,
|
||||
isVisible: true,
|
||||
settings: null,
|
||||
settingsRef: { current: null },
|
||||
systemPrefersDark: false,
|
||||
requestOpenLinksInAppPreference: vi.fn(),
|
||||
requestTerminalLinkAction: vi.fn(),
|
||||
effectiveMacOptionAsAlt: 'false',
|
||||
effectiveMacOptionAsAltRef: { current: 'false' },
|
||||
clearedScrollbackLeafIdsRef: { current: new Set() },
|
||||
initialLayoutRef: { current: { root: null, activeLeafId: null, expandedLeafId: null } },
|
||||
managerRef: { current: null },
|
||||
containerRef: { current: document.createElement('div') },
|
||||
getTabWideAgentHintLeafId: () => null,
|
||||
expandedStyleSnapshotRef: { current: new Map() },
|
||||
paneTransportsRef: { current: new Map() },
|
||||
panePtyBindingsRef: { current: new Map() },
|
||||
paneCwdRef: { current: new Map() },
|
||||
paneMode2031Ref: { current: new Map() },
|
||||
paneKittyKeyboardModesRef: { current: new Map() },
|
||||
paneLastThemeModeRef: { current: new Map() },
|
||||
replayingPanesRef: { current: new Map() },
|
||||
isActiveRef: { current: false },
|
||||
isVisibleRef: { current: true },
|
||||
onPtyExitRef: { current: vi.fn() },
|
||||
onAgentExitedRef: { current: vi.fn() },
|
||||
clearTabPtyId: vi.fn(),
|
||||
consumeSuppressedPtyExit: () => false,
|
||||
isPtyShutdownPending: () => false,
|
||||
updateTabTitle: vi.fn(),
|
||||
setRuntimePaneTitle: vi.fn(),
|
||||
clearRuntimePaneTitle: vi.fn(),
|
||||
updateTabPtyId: vi.fn(),
|
||||
markTerminalBell: vi.fn(),
|
||||
onShowSessionRestoredBanner: vi.fn(),
|
||||
dispatchNotification: vi.fn(),
|
||||
setCacheTimerStartedAt: vi.fn(),
|
||||
syncPanePtyLayoutBinding: vi.fn(),
|
||||
clearExitedPanePtyLayoutBinding: vi.fn(),
|
||||
setTabPaneExpanded: vi.fn(),
|
||||
setTabCanExpandPane: vi.fn(),
|
||||
setExpandedPane: vi.fn(),
|
||||
syncExpandedLayout: vi.fn(),
|
||||
persistLayoutSnapshot: vi.fn(),
|
||||
showPaneTitle: vi.fn(),
|
||||
setPaneTitles: vi.fn(),
|
||||
paneTitlesRef: { current: {} },
|
||||
setRenamingPaneId: vi.fn(),
|
||||
setPaneCount: vi.fn(),
|
||||
setPaneLayoutRevision: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
export async function parsedRows(manager: HeadlessMountManager): Promise<string[]> {
|
||||
return Promise.all(
|
||||
manager.panes.map(async ({ terminal }) => {
|
||||
await new Promise<void>((resolve) => terminal.write('', resolve))
|
||||
const buffer = terminal.buffer.active
|
||||
return Array.from(
|
||||
{ length: buffer.length },
|
||||
(_, row) => buffer.getLine(row)?.translateToString(true) ?? ''
|
||||
).join('\n')
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
export type TerminalPaneHydrationFixtureState = {
|
||||
deps: UseTerminalPaneLifecycleDeps | null
|
||||
reads: Mock<(ref: string) => Promise<string | null>>
|
||||
parked: boolean
|
||||
consumeIssue: Mock
|
||||
depsByTab: Record<string, UseTerminalPaneLifecycleDeps>
|
||||
renders: Map<string, number>
|
||||
store: {
|
||||
tabsByWorktree: Record<string, TerminalTab[]>
|
||||
terminalLayoutsByTabId: Record<string, TerminalLayoutSnapshot>
|
||||
localOnlyScrollbackByTabId: Record<string, Record<string, string>>
|
||||
repos: never[]
|
||||
allWorktrees: () => never[]
|
||||
consumeTabInitialCwd: () => null
|
||||
setTabLayout: Mock<(tabId: string, layout: TerminalLayoutSnapshot) => void>
|
||||
setTabLocalOnlyScrollback: Mock
|
||||
consumeSuppressedPtyExit: () => boolean
|
||||
isPtyShutdownPending: () => boolean
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ export type UseTerminalPaneLifecycleDeps = {
|
||||
startup?: TerminalPaneStartup | null
|
||||
/** Split pane runs the repo's issue-automation command with the issue number interpolated. */
|
||||
issueCommandSplit?: TerminalPaneIssueCommandSplit | null
|
||||
consumeTabIssueCommandSplit: (tabId: string) => void
|
||||
isActive: boolean
|
||||
isVisible: boolean
|
||||
systemPrefersDark: boolean
|
||||
@@ -48,6 +49,7 @@ export type UseTerminalPaneLifecycleDeps = {
|
||||
effectiveMacOptionAsAlt: EffectiveMacOptionAsAlt
|
||||
effectiveMacOptionAsAltRef: React.RefObject<EffectiveMacOptionAsAlt>
|
||||
initialLayoutRef: React.RefObject<TerminalLayoutSnapshot>
|
||||
clearedScrollbackLeafIdsRef?: React.RefObject<Set<string>>
|
||||
managerRef: React.RefObject<PaneManager | null>
|
||||
getTabWideAgentHintLeafId: () => string | null
|
||||
containerRef: React.RefObject<HTMLDivElement | null>
|
||||
@@ -121,3 +123,7 @@ export type UseTerminalPaneLifecycleDeps = {
|
||||
onExternalPaneDrop?: PaneExternalDropHandler
|
||||
detachPaneToNewTab?: DetachTerminalPaneToNewTab
|
||||
}
|
||||
|
||||
export type MountedTerminalPaneLifecycleDeps = UseTerminalPaneLifecycleDeps & {
|
||||
mountedManager: PaneManager | null
|
||||
}
|
||||
|
||||
+1
@@ -32,6 +32,7 @@ export function createPaneManagerOptionsTestContext(
|
||||
current: new Map<number, PanePtyBinding>(binding ? [[1, binding]] : [])
|
||||
},
|
||||
dispatchNotification: vi.fn(),
|
||||
consumeTabIssueCommandSplit: vi.fn(),
|
||||
setTabPaneExpanded: vi.fn(),
|
||||
setTabCanExpandPane: vi.fn(),
|
||||
setExpandedPane: vi.fn(),
|
||||
|
||||
+10
-13
@@ -1,3 +1,4 @@
|
||||
import type { LocalScrollbackSnapshots } from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration'
|
||||
import type { HttpLinkActionDestinations as TerminalHttpLinkActionDestinations } from '@/lib/browser/navigation/http-link-destinations'
|
||||
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import { useAppStore } from '@/store/index'
|
||||
@@ -28,12 +29,11 @@ import type { UseTerminalPaneLifecycleDeps } from './terminal-pane-lifecycle-typ
|
||||
import type { TerminalPaneLifecycleRefs } from './use-terminal-pane-lifecycle-refs'
|
||||
import { fitAndFocusPanes, fitPanes } from '../viewport/mounted-pane-fit'
|
||||
import { registerRuntimeTerminalTab } from '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
|
||||
import { normalizeTerminalLayoutSnapshot } from '../layout/terminal-layout-normalization'
|
||||
import { applyTerminalAppearance } from '../appearance/terminal-appearance'
|
||||
import { terminalLinkClickBehaviorFor } from '../links/gestures/terminal-link-click-behavior'
|
||||
import { createTerminalPanePtyDeps } from './terminal-pane-pty-deps'
|
||||
import type { DeferredSplitPaneHandoffHandle } from '../layout/split/deferred-split-pane-handoff'
|
||||
import { hydrateTerminalScrollbackRefs } from '../snapshots/terminal-scrollback-ref-hydration'
|
||||
import { prepareTerminalPaneScrollback } from './terminal-pane-mount-scrollback'
|
||||
import { resolvePaneLinkCwd } from '../links/pane-link-cwd'
|
||||
import { resolveQueuedInitialCwd } from './queued-initial-cwd'
|
||||
import { resolveTerminalHomePathFromEnv } from './terminal-home-path'
|
||||
@@ -75,7 +75,9 @@ export type TerminalPaneMountPreparation = {
|
||||
export function prepareTerminalPaneMount(
|
||||
deps: UseTerminalPaneLifecycleDeps,
|
||||
refs: TerminalPaneLifecycleRefs,
|
||||
mountFollowsTerminalPark: boolean
|
||||
mountFollowsTerminalPark: boolean,
|
||||
snapshots: LocalScrollbackSnapshots = {},
|
||||
retainedInlineLayout?: UseTerminalPaneLifecycleDeps['initialLayoutRef']['current']
|
||||
): TerminalPaneMountPreparation | null {
|
||||
const { containerRef, expandedStyleSnapshotRef, paneTransportsRef, panePtyBindingsRef } = deps
|
||||
const container = containerRef.current
|
||||
@@ -212,16 +214,11 @@ export function prepareTerminalPaneMount(
|
||||
const syncPaneLayoutRevision = (): void => {
|
||||
deps.setPaneLayoutRevision((revision) => revision + 1)
|
||||
}
|
||||
const normalizedInitialLayout = normalizeTerminalLayoutSnapshot(deps.initialLayoutRef.current)
|
||||
if (normalizedInitialLayout.changed) {
|
||||
deps.initialLayoutRef.current = normalizedInitialLayout.snapshot
|
||||
useAppStore.getState().setTabLayout(deps.tabId, normalizedInitialLayout.snapshot)
|
||||
}
|
||||
const initialLayoutHadBuffers = Boolean(deps.initialLayoutRef.current.buffersByLeafId)
|
||||
const hydratedInitialScrollback = hydrateTerminalScrollbackRefs(deps.initialLayoutRef.current)
|
||||
if (hydratedInitialScrollback.hydrated) {
|
||||
deps.initialLayoutRef.current = hydratedInitialScrollback.layout
|
||||
}
|
||||
const initialLayoutHadBuffers = prepareTerminalPaneScrollback(
|
||||
deps,
|
||||
snapshots,
|
||||
retainedInlineLayout
|
||||
)
|
||||
// Numeric IDs die with the mount; durable tab/leaf keys let remounts reclaim deferred handles.
|
||||
const deferredSplitHandoffs = new Map<number, DeferredSplitPaneHandoffHandle>()
|
||||
const ptyDeps = createTerminalPanePtyDeps({
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { normalizeTerminalLayoutSnapshot } from '../layout/terminal-layout-normalization'
|
||||
import {
|
||||
hydrateTerminalScrollbackRefs,
|
||||
restoreRetainedInlineScrollback
|
||||
} from '../snapshots/terminal-scrollback-ref-hydration'
|
||||
import type { LocalScrollbackSnapshots } from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration'
|
||||
import type { UseTerminalPaneLifecycleDeps } from './terminal-pane-lifecycle-types'
|
||||
|
||||
export function prepareTerminalPaneScrollback(
|
||||
deps: UseTerminalPaneLifecycleDeps,
|
||||
snapshots: LocalScrollbackSnapshots,
|
||||
retainedInlineLayout: UseTerminalPaneLifecycleDeps['initialLayoutRef']['current'] | undefined
|
||||
): boolean {
|
||||
const normalizedInitialLayout = normalizeTerminalLayoutSnapshot(deps.initialLayoutRef.current)
|
||||
if (normalizedInitialLayout.changed) {
|
||||
deps.initialLayoutRef.current = normalizedInitialLayout.snapshot
|
||||
useAppStore.getState().setTabLayout(deps.tabId, normalizedInitialLayout.snapshot)
|
||||
}
|
||||
const initialLayoutHadBuffers = Boolean(deps.initialLayoutRef.current.buffersByLeafId)
|
||||
deps.initialLayoutRef.current = restoreRetainedInlineScrollback(
|
||||
deps.initialLayoutRef.current,
|
||||
retainedInlineLayout,
|
||||
useAppStore.getState().localOnlyScrollbackByTabId[deps.tabId],
|
||||
deps.clearedScrollbackLeafIdsRef?.current
|
||||
)
|
||||
const hydratedInitialScrollback = hydrateTerminalScrollbackRefs(
|
||||
deps.initialLayoutRef.current,
|
||||
snapshots
|
||||
)
|
||||
if (hydratedInitialScrollback.hydrated) {
|
||||
deps.initialLayoutRef.current = hydratedInitialScrollback.layout
|
||||
}
|
||||
return initialLayoutHadBuffers
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
import type { PtyConnectionDeps } from '../pty-connection/pty-connection-deps'
|
||||
import type { UseTerminalPaneLifecycleDeps } from './terminal-pane-lifecycle-types'
|
||||
import type { TerminalPaneLifecycleRefs } from './use-terminal-pane-lifecycle-refs'
|
||||
import { clearRetainedInlineScrollback } from '../snapshots/terminal-scrollback-ref-hydration'
|
||||
|
||||
export function createTerminalPanePtyDeps(args: {
|
||||
deps: UseTerminalPaneLifecycleDeps
|
||||
@@ -34,6 +35,12 @@ export function createTerminalPanePtyDeps(args: {
|
||||
cwd: startupCwd,
|
||||
startup: deps.startup,
|
||||
mountFollowsTerminalPark,
|
||||
invalidateRetainedInlineScrollback: (leafId) => {
|
||||
deps.initialLayoutRef.current = clearRetainedInlineScrollback(
|
||||
deps.initialLayoutRef.current,
|
||||
leafId
|
||||
)
|
||||
},
|
||||
paneTransportsRef: deps.paneTransportsRef,
|
||||
paneMode2031Ref: deps.paneMode2031Ref,
|
||||
paneKittyKeyboardModesRef: deps.paneKittyKeyboardModesRef,
|
||||
|
||||
+10
-2
@@ -2,12 +2,14 @@ import { useTerminalPaneStoreActions } from '../controller/use-terminal-pane-sto
|
||||
import { useTerminalPaneLifecycle } from '../controller/use-terminal-pane-lifecycle'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
|
||||
export function useTerminalPaneLifecycleStage(controller: TerminalPaneCloseController): void {
|
||||
export function useTerminalPaneLifecycleStage(controller: TerminalPaneCloseController) {
|
||||
const {
|
||||
consumeTabIssueCommandSplit,
|
||||
clearExitedPanePtyLayoutBinding,
|
||||
clearExitedPanePtyLayoutBindingForLeaf,
|
||||
clearRuntimePaneTitle,
|
||||
clearTabPtyId,
|
||||
clearedScrollbackLeafIdsRef,
|
||||
containerRef,
|
||||
cwd,
|
||||
dispatchNotification,
|
||||
@@ -70,12 +72,13 @@ export function useTerminalPaneLifecycleStage(controller: TerminalPaneCloseContr
|
||||
} = controller
|
||||
const { consumeSuppressedPtyExit, isPtyShutdownPending } = useTerminalPaneStoreActions()
|
||||
|
||||
useTerminalPaneLifecycle({
|
||||
const mount = useTerminalPaneLifecycle({
|
||||
tabId,
|
||||
worktreeId,
|
||||
cwd,
|
||||
startup,
|
||||
issueCommandSplit,
|
||||
consumeTabIssueCommandSplit,
|
||||
isActive,
|
||||
isVisible: isRendererVisible,
|
||||
systemPrefersDark,
|
||||
@@ -86,6 +89,7 @@ export function useTerminalPaneLifecycleStage(controller: TerminalPaneCloseContr
|
||||
effectiveMacOptionAsAlt,
|
||||
effectiveMacOptionAsAltRef: macOptionAsAltRef,
|
||||
initialLayoutRef,
|
||||
clearedScrollbackLeafIdsRef,
|
||||
managerRef,
|
||||
getTabWideAgentHintLeafId: () => getTabWideAgentHintLeafIdRef.current(),
|
||||
containerRef,
|
||||
@@ -137,4 +141,8 @@ export function useTerminalPaneLifecycleStage(controller: TerminalPaneCloseContr
|
||||
onExternalPaneDrop: handleExternalPaneDrop,
|
||||
detachPaneToNewTab
|
||||
})
|
||||
return { terminalMountPhase: mount.phase, terminalManager: mount.manager }
|
||||
}
|
||||
|
||||
export type TerminalPaneMountedController = TerminalPaneCloseController &
|
||||
ReturnType<typeof useTerminalPaneLifecycleStage>
|
||||
|
||||
+634
@@ -0,0 +1,634 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type * as ScrollbackReadsModule from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-reads'
|
||||
import { StrictMode, useRef, useState } from 'react'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalTab
|
||||
} from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { UseTerminalPaneLifecycleDeps } from './terminal-pane-lifecycle-types'
|
||||
import type { TerminalPaneProps } from '../controller/terminal-pane-types'
|
||||
import type { PtyConnectionDeps } from '../pty-connection/pty-connection-deps'
|
||||
import {
|
||||
type TerminalPaneHydrationFixtureState,
|
||||
FIRST_LEAF,
|
||||
SECOND_LEAF,
|
||||
FIRST_REF,
|
||||
SECOND_REF,
|
||||
NEW_REF,
|
||||
HeadlessMountManager,
|
||||
mountDeps,
|
||||
parsedRows,
|
||||
registerRuntimeClear
|
||||
} from './terminal-pane-hydration-test-fixture'
|
||||
|
||||
const state = vi.hoisted((): TerminalPaneHydrationFixtureState => ({
|
||||
deps: null,
|
||||
reads: vi.fn<(ref: string) => Promise<string | null>>(),
|
||||
parked: true,
|
||||
consumeIssue: vi.fn(),
|
||||
depsByTab: {},
|
||||
renders: new Map<string, number>(),
|
||||
store: {
|
||||
tabsByWorktree: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
localOnlyScrollbackByTabId: {},
|
||||
repos: [],
|
||||
allWorktrees: () => [],
|
||||
consumeTabInitialCwd: () => null,
|
||||
setTabLayout: vi.fn(),
|
||||
setTabLocalOnlyScrollback: vi.fn(),
|
||||
consumeSuppressedPtyExit: () => false,
|
||||
isPtyShutdownPending: () => false
|
||||
}
|
||||
}))
|
||||
vi.mock('@/store/index', () => ({ useAppStore: { getState: () => state.store } }))
|
||||
vi.mock('@/lib/pane-manager/pane-manager', async () => ({
|
||||
PaneManager: (await import('./terminal-pane-hydration-test-fixture')).HeadlessMountManager
|
||||
}))
|
||||
vi.mock('./terminal-pane-manager-options', () => ({
|
||||
createTerminalPaneManagerOptions: (context: { ptyDeps: PtyConnectionDeps }) => ({
|
||||
getStartup: () => context.ptyDeps.startup,
|
||||
ptyDeps: context.ptyDeps
|
||||
})
|
||||
}))
|
||||
vi.mock('./terminal-pane-mount-events', () => ({ installTerminalPaneMountEvents: () => () => {} }))
|
||||
vi.mock('@/runtime/sync-runtime-graph/graph-sync-scheduler', () => ({
|
||||
scheduleRuntimeGraphSync: () => {}
|
||||
}))
|
||||
vi.mock('@/app-shell/startup/e2e-config', () => ({ e2eConfig: { exposeStore: false } }))
|
||||
vi.mock('@/diagnostics/crash-reporting/crash-breadcrumb-recorder', () => ({
|
||||
recordRendererCrashBreadcrumb: vi.fn()
|
||||
}))
|
||||
vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: () => null }))
|
||||
vi.mock('@/lib/browser/workspace/workspace-browser-tab-open', () => ({}))
|
||||
vi.mock('../host-state/terminal-pane-wsl-distro', () => ({ resolvePaneWslDistro: () => null }))
|
||||
vi.mock('../links/terminal-link-open-hints', () => ({
|
||||
getTerminalFileOpenHint: () => '',
|
||||
getTerminalUrlOpenHint: () => '',
|
||||
terminalUrlOpenHintOptionsFor: () => ({})
|
||||
}))
|
||||
vi.mock('../appearance/terminal-appearance', () => ({ applyTerminalAppearance: () => {} }))
|
||||
vi.mock('@/store/appearance/theme-background', () => ({ useThemeBackgroundStore: () => false }))
|
||||
vi.mock('@/store/plugins/appearance/plugin-fonts', () => ({ usePluginFontReady: () => false }))
|
||||
vi.mock('../parking/output-watchers/terminal-parked-tab-watchers', () => ({}))
|
||||
vi.mock('../parking/output-watchers/terminal-parked-watcher-registry', () => ({
|
||||
isTerminalTabParked: () => state.parked,
|
||||
captureParkedTerminalPaneCandidates: () => {}
|
||||
}))
|
||||
vi.mock('@/web/preload-api/web-runtime-session', () => ({
|
||||
requireActiveEnvironmentOrNull: () => null
|
||||
}))
|
||||
vi.mock(
|
||||
'@/runtime/hosted-terminals/hydration/host-terminal-scrollback-reads',
|
||||
async (importOriginal) => {
|
||||
const original = await importOriginal<typeof ScrollbackReadsModule>()
|
||||
return {
|
||||
...original,
|
||||
defaultDeps: {
|
||||
...original.defaultDeps,
|
||||
readLocalSnapshot: (ref: string) => state.reads(ref),
|
||||
resolveEnvironmentId: () => null
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
// Keep the actual pane boundary and production mount pipeline; isolate unrelated controller/UI services.
|
||||
vi.mock('../controller/use-terminal-pane-controller', async () => {
|
||||
const { useTerminalPaneLifecycleStage } = await import('./use-terminal-pane-lifecycle-stage')
|
||||
const { useTerminalPaneLayoutPersistence } =
|
||||
await import('../layout/persistence/use-terminal-pane-layout-persistence')
|
||||
return {
|
||||
useTerminalPaneController: (props: TerminalPaneProps) => {
|
||||
const [draft, setDraft] = useState('')
|
||||
const deps = state.depsByTab[props.tabId] ?? state.deps!
|
||||
const [issueCommandSplit] = useState(() => deps.issueCommandSplit)
|
||||
const lifecycleController = {
|
||||
...deps,
|
||||
...props,
|
||||
issueCommandSplit,
|
||||
isRendererVisible: props.isVisible ?? true,
|
||||
expandedPaneIdRef: useRef(null),
|
||||
removedTitleLeafIdsRef: useRef(new Set<string>()),
|
||||
remotePaneLayoutPusherRef: useRef(null),
|
||||
chatLeafId: null,
|
||||
isChatViewMode: false,
|
||||
paneCount: 0,
|
||||
paneTitles: {},
|
||||
setTabLayout: state.store.setTabLayout,
|
||||
macOptionAsAltRef: deps.effectiveMacOptionAsAltRef,
|
||||
getTabWideAgentHintLeafIdRef: { current: deps.getTabWideAgentHintLeafId },
|
||||
showRestoredSessionBanner: deps.onShowSessionRestoredBanner,
|
||||
consumeTabIssueCommandSplit: state.consumeIssue
|
||||
}
|
||||
const controller =
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture provides the lifecycle/persistence fields; unrelated controller UI is excluded.
|
||||
lifecycleController as unknown as Parameters<typeof useTerminalPaneLifecycleStage>[0]
|
||||
const persistence = useTerminalPaneLayoutPersistence(controller)
|
||||
const mount = useTerminalPaneLifecycleStage({ ...controller, ...persistence })
|
||||
return {
|
||||
...mount,
|
||||
draft,
|
||||
setDraft,
|
||||
tabId: props.tabId,
|
||||
clearFirst: () => {
|
||||
const pane = deps.managerRef.current?.getPanes()[0]
|
||||
if (pane) {
|
||||
persistence.clearPaneScrollback(pane)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
vi.mock('../controller/TerminalPaneSurface', () => ({
|
||||
TerminalPaneSurface: ({
|
||||
controller
|
||||
}: {
|
||||
controller: {
|
||||
tabId: string
|
||||
draft: string
|
||||
setDraft: (value: string) => void
|
||||
clearFirst: () => void
|
||||
}
|
||||
}) => {
|
||||
state.renders.set(controller.tabId, (state.renders.get(controller.tabId) ?? 0) + 1)
|
||||
return (
|
||||
<>
|
||||
<button onClick={controller.clearFirst}>Clear history</button>
|
||||
<input
|
||||
aria-label="Search draft"
|
||||
value={controller.draft}
|
||||
onChange={(event) => controller.setDraft(event.target.value)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}))
|
||||
import TerminalPane from '../TerminalPane'
|
||||
import { resetHostTerminalScrollbackHydrationForTests } from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration'
|
||||
|
||||
function terminalTab(id: string, worktreeId = 'wt-1'): TerminalTab {
|
||||
return {
|
||||
id,
|
||||
worktreeId,
|
||||
ptyId: null,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
const props = {
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
cwd: '/first',
|
||||
isActive: false,
|
||||
isVisible: true,
|
||||
onPtyExit: vi.fn(),
|
||||
onCloseTab: vi.fn()
|
||||
}
|
||||
function savedLayout(): TerminalLayoutSnapshot {
|
||||
return {
|
||||
root: {
|
||||
type: 'split',
|
||||
direction: 'horizontal',
|
||||
first: { type: 'leaf', leafId: FIRST_LEAF },
|
||||
second: { type: 'leaf', leafId: SECOND_LEAF }
|
||||
},
|
||||
activeLeafId: FIRST_LEAF,
|
||||
expandedLeafId: null,
|
||||
scrollbackRefsByLeafId: { [FIRST_LEAF]: FIRST_REF, [SECOND_LEAF]: SECOND_REF },
|
||||
ptyIdsByLeafId: { [SECOND_LEAF]: 'remote:live-tui' }
|
||||
}
|
||||
}
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
beforeEach(() => {
|
||||
state.deps = mountDeps()
|
||||
state.depsByTab = {}
|
||||
state.renders.clear()
|
||||
state.consumeIssue.mockReset()
|
||||
state.store.tabsByWorktree = { 'wt-1': [terminalTab('tab-1')] }
|
||||
state.store.terminalLayoutsByTabId = { 'tab-1': savedLayout() }
|
||||
state.store.localOnlyScrollbackByTabId = {}
|
||||
state.store.setTabLayout.mockReset()
|
||||
state.store.setTabLocalOnlyScrollback.mockReset()
|
||||
state.reads
|
||||
.mockReset()
|
||||
.mockImplementation(async (ref) =>
|
||||
ref === FIRST_REF ? 'saved shell history' : 'launch line\r\n\x1b[?1049h\x1b[Hsaved live TUI'
|
||||
)
|
||||
HeadlessMountManager.instances = []
|
||||
resetHostTerminalScrollbackHydrationForTests()
|
||||
})
|
||||
afterEach(() => cleanup())
|
||||
|
||||
describe('manager-owned saved history', () => {
|
||||
it('replays both saved panes after a cwd replacement while preserving the open draft', async () => {
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[0])).toEqual([
|
||||
'saved shell history\n\n\n\n\n',
|
||||
'saved live TUI\n\n\n\n\n'
|
||||
])
|
||||
fireEvent.change(screen.getByLabelText('Search draft'), { target: { value: 'unsaved query' } })
|
||||
expect(state.deps!.initialLayoutRef.current.buffersByLeafId).toBeUndefined()
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
state.reads.mockImplementation(async (ref) =>
|
||||
ref === FIRST_REF
|
||||
? 'new saved shell history'
|
||||
: 'launch line\r\n\x1b[?1049h\x1b[Hnew saved live TUI'
|
||||
)
|
||||
view.rerender(<TerminalPane {...props} cwd="/second" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'new saved shell history\n\n\n\n\n',
|
||||
'new saved live TUI\n\n\n\n\n'
|
||||
])
|
||||
expect(HeadlessMountManager.instances[0].destroyed).toBe(true)
|
||||
expect(screen.getByLabelText<HTMLInputElement>('Search draft').value).toBe('unsaved query')
|
||||
expect(state.store.setTabLocalOnlyScrollback).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('retires a pending cwd and StrictMode setup, then restores current park bytes and changed refs', async () => {
|
||||
const old = deferred<string>()
|
||||
const newer = deferred<string>()
|
||||
state.reads.mockImplementation((ref) => (ref === NEW_REF ? newer.promise : old.promise))
|
||||
const view = render(
|
||||
<StrictMode>
|
||||
<TerminalPane {...props} />
|
||||
</StrictMode>
|
||||
)
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledWith(FIRST_REF))
|
||||
view.rerender(
|
||||
<StrictMode>
|
||||
<TerminalPane {...props} cwd="/second" isVisible={false} />
|
||||
</StrictMode>
|
||||
)
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = {
|
||||
...savedLayout(),
|
||||
scrollbackRefsByLeafId: { [FIRST_LEAF]: FIRST_REF, [SECOND_LEAF]: NEW_REF }
|
||||
}
|
||||
state.store.localOnlyScrollbackByTabId['tab-1'] = { [FIRST_LEAF]: 'newer parked history' }
|
||||
await act(async () => {
|
||||
old.resolve('obsolete disk bytes')
|
||||
})
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledWith(NEW_REF))
|
||||
expect(HeadlessMountManager.instances).toHaveLength(0)
|
||||
await act(async () => {
|
||||
newer.resolve('current second pane')
|
||||
})
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[0])).toEqual([
|
||||
'newer parked history\n\n\n\n\n',
|
||||
'current second pane\n\n\n\n\n'
|
||||
])
|
||||
expect(state.deps!.isVisibleRef.current).toBe(false)
|
||||
expect(HeadlessMountManager.instances[0].gpu).toBe('auto')
|
||||
view.unmount()
|
||||
expect(HeadlessMountManager.instances[0].destroyed).toBe(true)
|
||||
})
|
||||
it('replays released inline history on a cwd-only replacement without a saved ref', async () => {
|
||||
const inline = savedLayout()
|
||||
delete inline.scrollbackRefsByLeafId
|
||||
inline.buffersByLeafId = {
|
||||
[FIRST_LEAF]: 'remote inline shell history',
|
||||
[SECOND_LEAF]: 'remote inline TUI frame'
|
||||
}
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = inline
|
||||
state.store.setTabLayout.mockImplementation((tabId: string, layout: TerminalLayoutSnapshot) => {
|
||||
state.store.terminalLayoutsByTabId[tabId] = layout
|
||||
})
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[0])).toEqual([
|
||||
'remote inline shell history\n\n\n\n\n',
|
||||
'remote inline TUI frame\n\n\n\n\n'
|
||||
])
|
||||
expect(state.store.terminalLayoutsByTabId['tab-1'].buffersByLeafId).toBeUndefined()
|
||||
state.store.setTabLayout.mockClear()
|
||||
view.rerender(<TerminalPane {...props} cwd="/second" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'remote inline shell history\n\n\n\n\n',
|
||||
'remote inline TUI frame\n\n\n\n\n'
|
||||
])
|
||||
for (const [, layout] of state.store.setTabLayout.mock.calls) {
|
||||
expect(layout.buffersByLeafId).toBeUndefined()
|
||||
}
|
||||
view.rerender(<TerminalPane {...props} cwd="/third" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(3))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[2])).toEqual([
|
||||
'remote inline shell history\n\n\n\n\n',
|
||||
'remote inline TUI frame\n\n\n\n\n'
|
||||
])
|
||||
for (const [, layout] of state.store.setTabLayout.mock.calls) {
|
||||
expect(layout.buffersByLeafId).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('retains only current no-ref winners through mixed replay, empty bytes and leaf removal', async () => {
|
||||
const initial = savedLayout()
|
||||
delete initial.scrollbackRefsByLeafId
|
||||
initial.buffersByLeafId = {
|
||||
[FIRST_LEAF]: 'old first history',
|
||||
[SECOND_LEAF]: 'old second history'
|
||||
}
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = initial
|
||||
state.store.setTabLayout.mockImplementation((tabId: string, layout: TerminalLayoutSnapshot) => {
|
||||
state.store.terminalLayoutsByTabId[tabId] = layout
|
||||
})
|
||||
state.store.setTabLocalOnlyScrollback.mockImplementation(
|
||||
(tabId: string, buffers: Record<string, string> | null) => {
|
||||
if (buffers) {
|
||||
state.store.localOnlyScrollbackByTabId[tabId] = buffers
|
||||
} else {
|
||||
delete state.store.localOnlyScrollbackByTabId[tabId]
|
||||
}
|
||||
}
|
||||
)
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = {
|
||||
...savedLayout(),
|
||||
scrollbackRefsByLeafId: { [SECOND_LEAF]: SECOND_REF },
|
||||
buffersByLeafId: { [FIRST_LEAF]: 'new inline winner' }
|
||||
}
|
||||
state.store.localOnlyScrollbackByTabId['tab-1'] = { [SECOND_LEAF]: 'new parked ref history' }
|
||||
view.rerender(<TerminalPane {...props} cwd="/mixed" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'new inline winner\n\n\n\n\n',
|
||||
'new parked ref history\n\n\n\n\n'
|
||||
])
|
||||
expect(state.store.localOnlyScrollbackByTabId['tab-1']).toBeUndefined()
|
||||
state.reads.mockResolvedValue('ref-backed replacement')
|
||||
view.rerender(<TerminalPane {...props} cwd="/mixed-again" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(3))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[2])).toEqual([
|
||||
'new inline winner\n\n\n\n\n',
|
||||
'ref-backed replacement\n\n\n\n\n'
|
||||
])
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = {
|
||||
root: { type: 'leaf', leafId: FIRST_LEAF },
|
||||
activeLeafId: FIRST_LEAF,
|
||||
expandedLeafId: null,
|
||||
buffersByLeafId: { [FIRST_LEAF]: '' },
|
||||
titlesByLeafId: { [FIRST_LEAF]: 'current title' }
|
||||
}
|
||||
view.rerender(<TerminalPane {...props} cwd="/removed" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(4))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[3])).toEqual(['\n\n\n\n\n'])
|
||||
expect(HeadlessMountManager.instances[3].getPanes().map((pane) => pane.leafId)).toEqual([
|
||||
FIRST_LEAF
|
||||
])
|
||||
const reintroduced = savedLayout()
|
||||
delete reintroduced.scrollbackRefsByLeafId
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = reintroduced
|
||||
view.rerender(<TerminalPane {...props} cwd="/reintroduced" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(5))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[4])).toEqual([
|
||||
'\n\n\n\n\n',
|
||||
'\n\n\n\n\n'
|
||||
])
|
||||
})
|
||||
|
||||
it('drops inline fallback across committed owner changes even if the intervening read is pending', async () => {
|
||||
const inline = savedLayout()
|
||||
delete inline.scrollbackRefsByLeafId
|
||||
inline.buffersByLeafId = { [FIRST_LEAF]: 'owner A history' }
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = inline
|
||||
state.store.setTabLayout.mockImplementation((tabId: string, layout: TerminalLayoutSnapshot) => {
|
||||
state.store.terminalLayoutsByTabId[tabId] = layout
|
||||
})
|
||||
state.store.tabsByWorktree['wt-2'] = [terminalTab('tab-2', 'wt-2')]
|
||||
state.store.terminalLayoutsByTabId['tab-2'] = savedLayout()
|
||||
const pending = deferred<string>()
|
||||
state.reads.mockReturnValue(pending.promise)
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
view.rerender(<TerminalPane {...props} tabId="tab-2" worktreeId="wt-2" />)
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledWith(FIRST_REF))
|
||||
view.rerender(<TerminalPane {...props} cwd="/returned" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'\n\n\n\n\n',
|
||||
'\n\n\n\n\n'
|
||||
])
|
||||
await act(async () => pending.resolve('retired owner B history'))
|
||||
expect(HeadlessMountManager.instances).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps cleared inline history gone across cwd replacements while its saved-ref sibling restores', async () => {
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = {
|
||||
...savedLayout(),
|
||||
buffersByLeafId: { [FIRST_LEAF]: 'cleared inline history must not return\r\ncurrent prompt' },
|
||||
scrollbackRefsByLeafId: { [SECOND_LEAF]: SECOND_REF }
|
||||
}
|
||||
state.store.setTabLayout.mockImplementation((tabId: string, layout: TerminalLayoutSnapshot) => {
|
||||
state.store.terminalLayoutsByTabId[tabId] = layout
|
||||
})
|
||||
state.reads.mockResolvedValue('saved sibling history')
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[0])).toEqual([
|
||||
'cleared inline history must not return\ncurrent prompt\n\n\n\n',
|
||||
'saved sibling history\n\n\n\n\n'
|
||||
])
|
||||
fireEvent.click(screen.getByText('Clear history'))
|
||||
expect(state.deps!.clearedScrollbackLeafIdsRef!.current.size).toBe(0)
|
||||
expect(state.store.terminalLayoutsByTabId['tab-1'].scrollbackRefsByLeafId).toEqual({
|
||||
[SECOND_LEAF]: SECOND_REF
|
||||
})
|
||||
view.rerender(<TerminalPane {...props} cwd="/after-clear" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'\n\n\n\n\n',
|
||||
'saved sibling history\n\n\n\n\n'
|
||||
])
|
||||
view.rerender(<TerminalPane {...props} cwd="/after-clear-again" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(3))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[2])).toEqual([
|
||||
'\n\n\n\n\n',
|
||||
'saved sibling history\n\n\n\n\n'
|
||||
])
|
||||
})
|
||||
|
||||
it('applies a runtime clear to the current replay owner before another cwd replacement', async () => {
|
||||
state.store.terminalLayoutsByTabId['tab-1'] = {
|
||||
...savedLayout(),
|
||||
buffersByLeafId: { [FIRST_LEAF]: 'runtime-cleared history\r\ncurrent prompt' },
|
||||
scrollbackRefsByLeafId: { [SECOND_LEAF]: SECOND_REF },
|
||||
ptyIdsByLeafId: { [FIRST_LEAF]: 'pty-runtime-clear' }
|
||||
}
|
||||
state.store.setTabLayout.mockImplementation((tabId: string, layout: TerminalLayoutSnapshot) => {
|
||||
state.store.terminalLayoutsByTabId[tabId] = layout
|
||||
})
|
||||
state.reads.mockResolvedValue('saved sibling history')
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
view.rerender(<TerminalPane {...props} cwd="/before-runtime-clear" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'runtime-cleared history\ncurrent prompt\n\n\n\n',
|
||||
'saved sibling history\n\n\n\n\n'
|
||||
])
|
||||
const registration = registerRuntimeClear(
|
||||
HeadlessMountManager.instances[1],
|
||||
'pty-runtime-clear'
|
||||
)
|
||||
try {
|
||||
registration.clear()
|
||||
view.rerender(<TerminalPane {...props} cwd="/after-runtime-clear" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(3))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[2])).toEqual([
|
||||
'\n\n\n\n\n',
|
||||
'saved sibling history\n\n\n\n\n'
|
||||
])
|
||||
} finally {
|
||||
registration.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not repeat a dispatched issue command when persistence replaces its surface before readiness', async () => {
|
||||
const pending = deferred<string>()
|
||||
state.reads.mockReturnValue(pending.promise)
|
||||
state.deps!.issueCommandSplit = { command: 'issue runner', env: { ISSUE: '42' } }
|
||||
state.consumeIssue.mockImplementation(() => {
|
||||
state.deps!.issueCommandSplit = null
|
||||
})
|
||||
function ReplacedPane() {
|
||||
const [generation, setGeneration] = useState(0)
|
||||
state.store.setTabLayout.mockImplementationOnce((tabId, layout) => {
|
||||
state.store.terminalLayoutsByTabId[tabId] = layout
|
||||
setGeneration(1)
|
||||
})
|
||||
return <TerminalPane key={generation} {...props} />
|
||||
}
|
||||
render(<ReplacedPane />)
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledWith(FIRST_REF))
|
||||
await act(async () => pending.resolve('saved history'))
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
const commands = HeadlessMountManager.instances.flatMap((manager) =>
|
||||
manager.splitStartups.filter(Boolean)
|
||||
)
|
||||
expect(commands).toEqual([{ command: 'issue runner', env: { ISSUE: '42' } }])
|
||||
expect(HeadlessMountManager.instances[0].destroyed).toBe(true)
|
||||
})
|
||||
|
||||
it('retains a queued split across a retired mount until its successor dispatches the startup', async () => {
|
||||
const pending = deferred<string>()
|
||||
state.reads.mockReturnValue(pending.promise)
|
||||
state.deps!.issueCommandSplit = { command: 'issue runner', env: { ISSUE: '42' } }
|
||||
let queued: UseTerminalPaneLifecycleDeps['issueCommandSplit'] = state.deps!.issueCommandSplit
|
||||
state.consumeIssue.mockImplementation(() => {
|
||||
expect(HeadlessMountManager.instances[0].splitStartups).toEqual([
|
||||
undefined,
|
||||
{ command: 'issue runner', env: { ISSUE: '42' } }
|
||||
])
|
||||
queued = null
|
||||
})
|
||||
const view = render(<TerminalPane {...props} />)
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledWith(FIRST_REF))
|
||||
view.rerender(<TerminalPane {...props} cwd="/successor" />)
|
||||
expect(queued).toEqual({ command: 'issue runner', env: { ISSUE: '42' } })
|
||||
expect(state.consumeIssue).not.toHaveBeenCalled()
|
||||
expect(HeadlessMountManager.instances).toHaveLength(0)
|
||||
await act(async () => pending.resolve('saved history'))
|
||||
await waitFor(() => expect(queued).toBeNull())
|
||||
expect(HeadlessMountManager.instances).toHaveLength(1)
|
||||
expect(await parsedRows(HeadlessMountManager.instances[0])).toEqual([
|
||||
'saved history\n\n\n\n\n',
|
||||
'saved history\n\n\n\n\n',
|
||||
'\n\n\n\n\n'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps readiness local to one pane and releases retired reads before a later mount', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
state.depsByTab['tab-2'] = mountDeps()
|
||||
state.store.tabsByWorktree['wt-1'] = [terminalTab('tab-1'), terminalTab('tab-2')]
|
||||
state.store.terminalLayoutsByTabId['tab-2'] = {
|
||||
...savedLayout(),
|
||||
scrollbackRefsByLeafId: { [FIRST_LEAF]: NEW_REF, [SECOND_LEAF]: NEW_REF }
|
||||
}
|
||||
state.reads.mockImplementation((ref) => (ref === NEW_REF ? second.promise : first.promise))
|
||||
const view = render(
|
||||
<>
|
||||
<TerminalPane {...props} />
|
||||
<TerminalPane {...props} tabId="tab-2" />
|
||||
</>
|
||||
)
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledTimes(2))
|
||||
const siblingRenders = state.renders.get('tab-2')
|
||||
await act(async () => {
|
||||
first.resolve('first pane history')
|
||||
})
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(1))
|
||||
expect(state.renders.get('tab-2')).toBe(siblingRenders)
|
||||
view.unmount()
|
||||
await act(async () => {
|
||||
second.resolve('retired read history')
|
||||
})
|
||||
state.reads.mockResolvedValue('fresh retry history')
|
||||
const retry = render(<TerminalPane {...props} tabId="tab-2" />)
|
||||
await waitFor(() => expect(HeadlessMountManager.instances).toHaveLength(2))
|
||||
expect(await parsedRows(HeadlessMountManager.instances[1])).toEqual([
|
||||
'fresh retry history\n\n\n\n\n',
|
||||
'fresh retry history\n\n\n\n\n'
|
||||
])
|
||||
retry.unmount()
|
||||
})
|
||||
|
||||
// One bucket index visit per tab is sufficient to prove current ownership for every mount.
|
||||
// Ten times as many owners must not multiply that work by every owner's validity checks.
|
||||
it('indexes a shared tab bucket once through the production mount validity path at N and 10N', async () => {
|
||||
const { useTerminalPaneMountLifecycle } = await import('./use-terminal-pane-mount-lifecycle')
|
||||
const { useTerminalPaneLifecycleRefs } = await import('./use-terminal-pane-lifecycle-refs')
|
||||
for (const count of [300, 3_000]) {
|
||||
let entryVisits = 0
|
||||
const base = mountDeps()
|
||||
base.containerRef.current = null
|
||||
const tabs = Array.from({ length: count }, (_, index) => ({
|
||||
...terminalTab(`scale-${index}`),
|
||||
get id() {
|
||||
entryVisits++
|
||||
return `scale-${index}`
|
||||
},
|
||||
ptyId: null
|
||||
}))
|
||||
state.store.tabsByWorktree = { 'wt-1': tabs }
|
||||
state.store.terminalLayoutsByTabId = Object.fromEntries(
|
||||
Array.from({ length: count }, (_, index) => [`scale-${index}`, savedLayout()])
|
||||
)
|
||||
state.reads.mockReset().mockResolvedValue(null)
|
||||
function PendingMount({ tabId }: { tabId: string }) {
|
||||
useTerminalPaneMountLifecycle({ ...base, tabId }, useTerminalPaneLifecycleRefs())
|
||||
return null
|
||||
}
|
||||
const view = render(
|
||||
<>
|
||||
{Array.from({ length: count }, (_, index) => (
|
||||
<PendingMount key={index} tabId={`scale-${index}`} />
|
||||
))}
|
||||
</>
|
||||
)
|
||||
await waitFor(() => expect(state.reads).toHaveBeenCalledTimes(count * 2), { timeout: 10_000 })
|
||||
expect(entryVisits).toBeLessThanOrEqual(count)
|
||||
expect(HeadlessMountManager.instances).toHaveLength(0)
|
||||
view.unmount()
|
||||
}
|
||||
})
|
||||
+229
-115
@@ -1,4 +1,12 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { getCachedTerminalTabForWorktree } from '../controller/tab-state/terminal-tab-lookup'
|
||||
import { sanitizeTerminalLayoutPaneTitles } from '../../../../../shared/workspace-layout/terminal-topology/terminal-pane-title-sanitization'
|
||||
import { EMPTY_LAYOUT } from '../layout/empty-terminal-layout'
|
||||
import {
|
||||
startHostTerminalScrollbackHydration,
|
||||
type LocalScrollbackSnapshots
|
||||
} from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration'
|
||||
import { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import { configureTerminalOutputBacklogCap } from '@/lib/pane-manager/terminal-output/pane-terminal-output-queue-registry'
|
||||
import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph/graph-sync-scheduler'
|
||||
@@ -18,126 +26,232 @@ import type { TerminalPaneLifecycleRefs } from './use-terminal-pane-lifecycle-re
|
||||
export function useTerminalPaneMountLifecycle(
|
||||
deps: UseTerminalPaneLifecycleDeps,
|
||||
refs: TerminalPaneLifecycleRefs
|
||||
): void {
|
||||
) {
|
||||
// Read park intent during render before watcher disposal; instance caching becomes stale on cwd changes.
|
||||
const mountFollowsTerminalPark = isTerminalTabParked(deps.tabId)
|
||||
configureTerminalOutputBacklogCap(deps.settings?.terminalScrollbackRows)
|
||||
|
||||
useEffect(() => {
|
||||
const preparation = prepareTerminalPaneMount(deps, refs, mountFollowsTerminalPark)
|
||||
if (!preparation) {
|
||||
return
|
||||
const latest = useRef(deps)
|
||||
const [mount, setMount] = useState<{
|
||||
tabId: string
|
||||
worktreeId: string
|
||||
cwd: typeof deps.cwd
|
||||
manager: PaneManager | null
|
||||
phase: 'local' | 'host' | 'ready'
|
||||
failure?: { error: unknown }
|
||||
} | null>(null)
|
||||
const matches =
|
||||
mount?.tabId === deps.tabId && mount.worktreeId === deps.worktreeId && mount.cwd === deps.cwd
|
||||
const manager = matches && mount.manager === deps.managerRef.current ? mount.manager : null
|
||||
const phase = manager ? 'ready' : matches && mount.phase === 'host' ? 'host' : 'local'
|
||||
useLayoutEffect(() => {
|
||||
if (latest.current.tabId !== deps.tabId || latest.current.worktreeId !== deps.worktreeId) {
|
||||
deps.initialLayoutRef.current = EMPTY_LAYOUT
|
||||
}
|
||||
const {
|
||||
container,
|
||||
latest.current = deps
|
||||
})
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
let dispose: (() => void) | undefined
|
||||
const { tabId, worktreeId, cwd } = deps
|
||||
const isCurrent = (): boolean =>
|
||||
live &&
|
||||
latest.current.tabId === tabId &&
|
||||
latest.current.worktreeId === worktreeId &&
|
||||
latest.current.cwd === cwd &&
|
||||
Boolean(
|
||||
getCachedTerminalTabForWorktree(useAppStore.getState().tabsByWorktree, worktreeId, tabId)
|
||||
)
|
||||
const commit = (snapshots: LocalScrollbackSnapshots): void => {
|
||||
const current = latest.current
|
||||
const state = useAppStore.getState()
|
||||
if (!isCurrent()) {
|
||||
return
|
||||
}
|
||||
const tab = getCachedTerminalTabForWorktree(state.tabsByWorktree, worktreeId, tabId)
|
||||
const layout = state.terminalLayoutsByTabId[tabId] ?? EMPTY_LAYOUT
|
||||
const retainedInlineLayout = current.initialLayoutRef.current
|
||||
current.initialLayoutRef.current = tab
|
||||
? sanitizeTerminalLayoutPaneTitles(layout, tab)
|
||||
: layout
|
||||
dispose = mountTerminalPane(
|
||||
current,
|
||||
refs,
|
||||
mountFollowsTerminalPark,
|
||||
snapshots,
|
||||
retainedInlineLayout
|
||||
)
|
||||
if (current.managerRef.current) {
|
||||
setMount({ tabId, worktreeId, cwd, manager: current.managerRef.current, phase: 'ready' })
|
||||
}
|
||||
}
|
||||
const pending = startHostTerminalScrollbackHydration(
|
||||
tabId,
|
||||
worktreeId,
|
||||
undefined,
|
||||
isCurrent,
|
||||
commit
|
||||
)
|
||||
const retire = pending?.retire
|
||||
if (pending) {
|
||||
setMount({ tabId, worktreeId, cwd, manager: null, phase: 'local' })
|
||||
void pending.ready.catch((error) => {
|
||||
if (isCurrent()) {
|
||||
setMount({ tabId, worktreeId, cwd, manager: null, phase: 'local', failure: { error } })
|
||||
}
|
||||
})
|
||||
void pending.local.then(
|
||||
(needsHost) => {
|
||||
if (isCurrent() && needsHost) {
|
||||
setMount({ tabId, worktreeId, cwd, manager: null, phase: 'host' })
|
||||
}
|
||||
},
|
||||
() => {}
|
||||
)
|
||||
} else {
|
||||
commit({})
|
||||
}
|
||||
return () => {
|
||||
live = false
|
||||
retire?.()
|
||||
dispose?.()
|
||||
}
|
||||
// Each resource transaction follows the manager identity; the commit reads live preferences.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [deps.tabId, deps.worktreeId, deps.cwd])
|
||||
if (matches && mount.failure) {
|
||||
throw mount.failure.error
|
||||
}
|
||||
return { manager, phase }
|
||||
}
|
||||
|
||||
function mountTerminalPane(
|
||||
deps: UseTerminalPaneLifecycleDeps,
|
||||
refs: TerminalPaneLifecycleRefs,
|
||||
mountFollowsTerminalPark: boolean,
|
||||
snapshots: LocalScrollbackSnapshots,
|
||||
retainedInlineLayout: UseTerminalPaneLifecycleDeps['initialLayoutRef']['current']
|
||||
): (() => void) | undefined {
|
||||
const preparation = prepareTerminalPaneMount(
|
||||
deps,
|
||||
refs,
|
||||
mountFollowsTerminalPark,
|
||||
snapshots,
|
||||
retainedInlineLayout
|
||||
)
|
||||
if (!preparation) {
|
||||
return
|
||||
}
|
||||
const {
|
||||
container,
|
||||
deferredSplitHandoffs,
|
||||
expandedStyleSnapshots,
|
||||
ptyDeps,
|
||||
unregisterRuntimeTab
|
||||
} = preparation
|
||||
let shouldPersistLayout = false
|
||||
const releaseWebviewDragPassthrough: { current: (() => void) | null } = {
|
||||
current: null
|
||||
}
|
||||
const queueResizeAll = preparation.queueResizeAll
|
||||
const managerContext = {
|
||||
deps,
|
||||
refs,
|
||||
ptyDeps,
|
||||
deferredSplitHandoffs,
|
||||
// Preserve startup identity before bootstrap mutates ptyDeps.startup, so ownership checks compare the queued object.
|
||||
startup: deps.startup,
|
||||
defaultTabCwd: preparation.defaultTabCwd,
|
||||
startupCwd: preparation.startupCwd,
|
||||
worktreePath: preparation.worktreePath,
|
||||
terminalHomePath: preparation.terminalHomePath,
|
||||
wslDistro: preparation.wslDistro,
|
||||
linkDeps: preparation.linkDeps,
|
||||
fileOpenLinkHint: preparation.fileOpenLinkHint,
|
||||
getPaneLinkCwd: preparation.getPaneLinkCwd,
|
||||
getUrlOpenLinkHint: preparation.getUrlOpenLinkHint,
|
||||
getHttpLinkSourceOwnerForPane: preparation.getHttpLinkSourceOwnerForPane,
|
||||
getHttpLinkActionDestinations: preparation.getHttpLinkActionDestinations,
|
||||
getLinkActionContext: preparation.getLinkActionContext,
|
||||
canOpenOwnedBrowserForPane: preparation.canOpenOwnedBrowserForPane,
|
||||
queueResizeAll,
|
||||
syncPaneCount: preparation.syncPaneCount,
|
||||
syncPaneLayoutRevision: preparation.syncPaneLayoutRevision,
|
||||
syncCanExpandState: preparation.syncCanExpandState,
|
||||
applyAppearance: preparation.applyAppearance,
|
||||
requestOpenLinksInAppPreference: deps.requestOpenLinksInAppPreference,
|
||||
onShowSessionRestoredBanner: deps.onShowSessionRestoredBanner,
|
||||
releaseWebviewDragPassthrough: releaseWebviewDragPassthrough,
|
||||
shouldPersistLayout: () => shouldPersistLayout,
|
||||
osc7UncHost: preparation.osc7UncHost
|
||||
}
|
||||
const manager = new PaneManager(container, createTerminalPaneManagerOptions(managerContext))
|
||||
deps.managerRef.current = manager
|
||||
if (e2eConfig.exposeStore) {
|
||||
window.__paneManagers = window.__paneManagers ?? new Map()
|
||||
window.__paneManagers.set(deps.tabId, manager)
|
||||
}
|
||||
restoreTerminalPaneLayout({
|
||||
manager,
|
||||
deps,
|
||||
refs,
|
||||
ptyDeps,
|
||||
initialLayoutHadBuffers: preparation.initialLayoutHadBuffers
|
||||
})
|
||||
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
|
||||
runBootstrapSplitInMain({
|
||||
manager,
|
||||
worktreeId: deps.worktreeId,
|
||||
tabId: deps.tabId,
|
||||
ptyDeps,
|
||||
issueCommandSplit: deps.issueCommandSplit,
|
||||
isActive: deps.isActive
|
||||
})
|
||||
} else {
|
||||
runTerminalPaneBootstrapSplits({
|
||||
manager,
|
||||
ptyDeps,
|
||||
issueCommandSplit: deps.issueCommandSplit,
|
||||
isActive: deps.isActive
|
||||
})
|
||||
}
|
||||
if (deps.issueCommandSplit) {
|
||||
deps.consumeTabIssueCommandSplit(deps.tabId)
|
||||
}
|
||||
shouldPersistLayout = true
|
||||
preparation.syncCanExpandState()
|
||||
preparation.syncPaneCount()
|
||||
preparation.applyAppearance(manager)
|
||||
queueResizeAll(deps.isActive)
|
||||
deps.persistLayoutSnapshot()
|
||||
scheduleRuntimeGraphSync()
|
||||
const removeMountEvents = installTerminalPaneMountEvents({
|
||||
manager,
|
||||
deps: {
|
||||
tabId: deps.tabId,
|
||||
worktreeId: deps.worktreeId,
|
||||
isActive: deps.isActive,
|
||||
managerRef: deps.managerRef,
|
||||
showPaneTitle: deps.showPaneTitle,
|
||||
persistLayoutSnapshot: deps.persistLayoutSnapshot,
|
||||
syncCanExpandState: preparation.syncCanExpandState,
|
||||
queueResizeAll,
|
||||
detachPaneToNewTab: deps.detachPaneToNewTab
|
||||
},
|
||||
ptyDeps
|
||||
})
|
||||
return () => {
|
||||
removeMountEvents()
|
||||
cleanupTerminalPaneMount({
|
||||
manager,
|
||||
deps,
|
||||
refs,
|
||||
deferredSplitHandoffs,
|
||||
expandedStyleSnapshots,
|
||||
ptyDeps,
|
||||
unregisterRuntimeTab
|
||||
} = preparation
|
||||
let shouldPersistLayout = false
|
||||
const releaseWebviewDragPassthrough: { current: (() => void) | null } = {
|
||||
current: null
|
||||
}
|
||||
const queueResizeAll = preparation.queueResizeAll
|
||||
const managerContext = {
|
||||
deps,
|
||||
refs,
|
||||
ptyDeps,
|
||||
deferredSplitHandoffs,
|
||||
// Preserve startup identity before bootstrap mutates ptyDeps.startup, so ownership checks compare the queued object.
|
||||
startup: deps.startup,
|
||||
defaultTabCwd: preparation.defaultTabCwd,
|
||||
startupCwd: preparation.startupCwd,
|
||||
worktreePath: preparation.worktreePath,
|
||||
terminalHomePath: preparation.terminalHomePath,
|
||||
wslDistro: preparation.wslDistro,
|
||||
linkDeps: preparation.linkDeps,
|
||||
fileOpenLinkHint: preparation.fileOpenLinkHint,
|
||||
getPaneLinkCwd: preparation.getPaneLinkCwd,
|
||||
getUrlOpenLinkHint: preparation.getUrlOpenLinkHint,
|
||||
getHttpLinkSourceOwnerForPane: preparation.getHttpLinkSourceOwnerForPane,
|
||||
getHttpLinkActionDestinations: preparation.getHttpLinkActionDestinations,
|
||||
getLinkActionContext: preparation.getLinkActionContext,
|
||||
canOpenOwnedBrowserForPane: preparation.canOpenOwnedBrowserForPane,
|
||||
queueResizeAll,
|
||||
syncPaneCount: preparation.syncPaneCount,
|
||||
syncPaneLayoutRevision: preparation.syncPaneLayoutRevision,
|
||||
syncCanExpandState: preparation.syncCanExpandState,
|
||||
applyAppearance: preparation.applyAppearance,
|
||||
requestOpenLinksInAppPreference: deps.requestOpenLinksInAppPreference,
|
||||
onShowSessionRestoredBanner: deps.onShowSessionRestoredBanner,
|
||||
releaseWebviewDragPassthrough: releaseWebviewDragPassthrough,
|
||||
shouldPersistLayout: () => shouldPersistLayout,
|
||||
osc7UncHost: preparation.osc7UncHost
|
||||
}
|
||||
const manager = new PaneManager(container, createTerminalPaneManagerOptions(managerContext))
|
||||
deps.managerRef.current = manager
|
||||
if (e2eConfig.exposeStore) {
|
||||
window.__paneManagers = window.__paneManagers ?? new Map()
|
||||
window.__paneManagers.set(deps.tabId, manager)
|
||||
}
|
||||
restoreTerminalPaneLayout({
|
||||
manager,
|
||||
deps,
|
||||
refs,
|
||||
ptyDeps,
|
||||
initialLayoutHadBuffers: preparation.initialLayoutHadBuffers
|
||||
unregisterRuntimeTab,
|
||||
cancelResize: preparation.cancelResizeAll
|
||||
})
|
||||
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
|
||||
runBootstrapSplitInMain({
|
||||
manager,
|
||||
worktreeId: deps.worktreeId,
|
||||
tabId: deps.tabId,
|
||||
ptyDeps,
|
||||
issueCommandSplit: deps.issueCommandSplit,
|
||||
isActive: deps.isActive
|
||||
})
|
||||
} else {
|
||||
runTerminalPaneBootstrapSplits({
|
||||
manager,
|
||||
ptyDeps,
|
||||
issueCommandSplit: deps.issueCommandSplit,
|
||||
isActive: deps.isActive
|
||||
})
|
||||
}
|
||||
shouldPersistLayout = true
|
||||
preparation.syncCanExpandState()
|
||||
preparation.syncPaneCount()
|
||||
preparation.applyAppearance(manager)
|
||||
queueResizeAll(deps.isActive)
|
||||
deps.persistLayoutSnapshot()
|
||||
scheduleRuntimeGraphSync()
|
||||
const removeMountEvents = installTerminalPaneMountEvents({
|
||||
manager,
|
||||
deps: {
|
||||
tabId: deps.tabId,
|
||||
worktreeId: deps.worktreeId,
|
||||
isActive: deps.isActive,
|
||||
managerRef: deps.managerRef,
|
||||
showPaneTitle: deps.showPaneTitle,
|
||||
persistLayoutSnapshot: deps.persistLayoutSnapshot,
|
||||
syncCanExpandState: preparation.syncCanExpandState,
|
||||
queueResizeAll,
|
||||
detachPaneToNewTab: deps.detachPaneToNewTab
|
||||
},
|
||||
ptyDeps
|
||||
})
|
||||
return () => {
|
||||
removeMountEvents()
|
||||
cleanupTerminalPaneMount({
|
||||
manager,
|
||||
deps,
|
||||
refs,
|
||||
deferredSplitHandoffs,
|
||||
expandedStyleSnapshots,
|
||||
unregisterRuntimeTab,
|
||||
cancelResize: preparation.cancelResizeAll
|
||||
})
|
||||
releaseWebviewDragPassthrough.current?.()
|
||||
releaseWebviewDragPassthrough.current = null
|
||||
}
|
||||
// The manager follows tab/cwd identity; live settings are handled by sibling effects.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [deps.tabId, deps.cwd])
|
||||
releaseWebviewDragPassthrough.current?.()
|
||||
releaseWebviewDragPassthrough.current = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { releasePaneTransportForRestart } from './pane-restart-transport-handoff
|
||||
import { clearPaneTerminalError } from '../errors/terminal-error-accumulation'
|
||||
import type { PtyConnectionDeps } from '../pty-connection/pty-connection-deps'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import { clearRetainedInlineScrollback } from '../snapshots/terminal-scrollback-ref-hydration'
|
||||
|
||||
export function usePaneProcessRestart({
|
||||
clearCodexRestartNotice,
|
||||
@@ -14,6 +15,7 @@ export function usePaneProcessRestart({
|
||||
clearTabPtyId,
|
||||
cwd,
|
||||
dispatchNotification,
|
||||
initialLayoutRef,
|
||||
isActiveRef,
|
||||
isVisibleRef,
|
||||
markTerminalBell,
|
||||
@@ -49,6 +51,7 @@ export function usePaneProcessRestart({
|
||||
| 'clearTabPtyId'
|
||||
| 'cwd'
|
||||
| 'dispatchNotification'
|
||||
| 'initialLayoutRef'
|
||||
| 'isActiveRef'
|
||||
| 'isVisibleRef'
|
||||
| 'markTerminalBell'
|
||||
@@ -107,6 +110,9 @@ export function usePaneProcessRestart({
|
||||
startup,
|
||||
...(replacesPtyId ? { replacesPtyId } : {}),
|
||||
mountFollowsTerminalPark: false,
|
||||
invalidateRetainedInlineScrollback: (leafId) => {
|
||||
initialLayoutRef.current = clearRetainedInlineScrollback(initialLayoutRef.current, leafId)
|
||||
},
|
||||
paneTransportsRef,
|
||||
paneMode2031Ref,
|
||||
paneKittyKeyboardModesRef,
|
||||
@@ -147,6 +153,7 @@ export function usePaneProcessRestart({
|
||||
cwd,
|
||||
dispatchNotification,
|
||||
handlePaneProcessDied,
|
||||
initialLayoutRef,
|
||||
isActiveRef,
|
||||
isVisibleRef,
|
||||
markTerminalBell,
|
||||
|
||||
@@ -40,6 +40,7 @@ export type PtyConnectionDeps = {
|
||||
restoredPtyIdByLeafId?: Record<string, string>
|
||||
/** Render-time park intent survives watcher disposal and is consumed once after layout replay. */
|
||||
mountFollowsTerminalPark: boolean
|
||||
invalidateRetainedInlineScrollback: (leafId: string) => void
|
||||
paneTransportsRef: React.RefObject<Map<number, PtyTransport>>
|
||||
paneMode2031Ref: React.RefObject<Map<number, boolean>>
|
||||
/** Mirror xterm’s negotiated Kitty flags for keyboard policy. */
|
||||
|
||||
+1
@@ -63,6 +63,7 @@ export function bindRegisterPaneSerializer(session: ConnectPanePtySession): void
|
||||
},
|
||||
{
|
||||
clear: () => {
|
||||
session.deps.invalidateRetainedInlineScrollback(session.pane.leafId)
|
||||
session.clearHiddenOutputRestoreState()
|
||||
discardTerminalOutput(session.pane.terminal)
|
||||
clearTerminalScrollbackAndFollowOutput(session.pane.terminal)
|
||||
|
||||
+9
-2
@@ -1,4 +1,5 @@
|
||||
import { isRemoteRuntimePtyId } from '../../../../../../shared/remote-runtime/remote-runtime-pty-id'
|
||||
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import { useEffect } from 'react'
|
||||
import type { PtyTransport } from '../pty-transport-types'
|
||||
import {
|
||||
@@ -22,18 +23,24 @@ function reportRendererPtyVisibility(
|
||||
|
||||
export function useRendererPtyVisibilityClaims({
|
||||
paneTransportsRef,
|
||||
terminalManager,
|
||||
rendererVisible
|
||||
}: {
|
||||
paneTransportsRef: React.RefObject<Map<number, PtyTransport>>
|
||||
terminalManager: PaneManager | null
|
||||
rendererVisible: boolean
|
||||
}): void {
|
||||
useEffect(() => {
|
||||
if (!terminalManager) {
|
||||
return
|
||||
}
|
||||
const paneTransports = paneTransportsRef.current
|
||||
reportRendererPtyVisibility(paneTransports, rendererVisible)
|
||||
const claimedTransports = Array.from(paneTransports.values())
|
||||
return () => {
|
||||
for (const transport of paneTransports.values()) {
|
||||
for (const transport of claimedTransports) {
|
||||
releaseRendererPtyVisibilityClaim(transport)
|
||||
}
|
||||
}
|
||||
}, [rendererVisible, paneTransportsRef])
|
||||
}, [terminalManager, rendererVisible, paneTransportsRef])
|
||||
}
|
||||
|
||||
+6
-5
@@ -1,23 +1,24 @@
|
||||
import { useEffect } from 'react'
|
||||
import { pruneSessionRestoredBannerPaneIds } from './session-restored-banner-pane-state'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useRestoredBannerPanePruning({
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
setSessionRestoredBannerPaneIds
|
||||
}: Pick<
|
||||
TerminalPaneCloseController,
|
||||
'managerRef' | 'paneCount' | 'setSessionRestoredBannerPaneIds'
|
||||
TerminalPaneMountedController,
|
||||
'managerRef' | 'terminalManager' | 'paneCount' | 'setSessionRestoredBannerPaneIds'
|
||||
>): void {
|
||||
useEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (!manager) {
|
||||
if (!terminalManager || manager !== terminalManager) {
|
||||
return
|
||||
}
|
||||
setSessionRestoredBannerPaneIds((previous) => {
|
||||
const next = pruneSessionRestoredBannerPaneIds(previous, manager.getPanes())
|
||||
return next === previous ? previous : next
|
||||
})
|
||||
}, [paneCount, managerRef, setSessionRestoredBannerPaneIds])
|
||||
}, [terminalManager, paneCount, managerRef, setSessionRestoredBannerPaneIds])
|
||||
}
|
||||
|
||||
+7
-4
@@ -1,11 +1,12 @@
|
||||
import { useLayoutEffect } from 'react'
|
||||
import { syncSessionRestoredBannerTitleSpace } from './session-restored-banner-pane-state'
|
||||
import { fitPanes } from '../viewport/mounted-pane-fit'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useRestoredBannerTitleSpace({
|
||||
isVisible,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
paneLayoutRevision,
|
||||
paneTitles,
|
||||
@@ -13,9 +14,10 @@ export function useRestoredBannerTitleSpace({
|
||||
sessionRestoredBannerPaneIds,
|
||||
shouldMeasureHiddenStartup
|
||||
}: Pick<
|
||||
TerminalPaneCloseController,
|
||||
TerminalPaneMountedController,
|
||||
| 'isVisible'
|
||||
| 'managerRef'
|
||||
| 'terminalManager'
|
||||
| 'paneCount'
|
||||
| 'paneLayoutRevision'
|
||||
| 'paneTitles'
|
||||
@@ -25,7 +27,7 @@ export function useRestoredBannerTitleSpace({
|
||||
>): void {
|
||||
useLayoutEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (!manager) {
|
||||
if (!terminalManager || manager !== terminalManager) {
|
||||
return
|
||||
}
|
||||
const needsFit = syncSessionRestoredBannerTitleSpace({
|
||||
@@ -45,6 +47,7 @@ export function useRestoredBannerTitleSpace({
|
||||
sessionRestoredBannerPaneIds,
|
||||
isVisible,
|
||||
shouldMeasureHiddenStartup,
|
||||
managerRef
|
||||
managerRef,
|
||||
terminalManager
|
||||
])
|
||||
}
|
||||
|
||||
+62
-9
@@ -1,6 +1,30 @@
|
||||
import { collectLeafIds } from '../../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree'
|
||||
import { resolveRootlessTerminalLayoutLeafId } from '../../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree'
|
||||
import type { LocalScrollbackSnapshots } from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration'
|
||||
import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
|
||||
export function hydrateTerminalScrollbackRefs(layout: TerminalLayoutSnapshot): {
|
||||
export function clearRetainedInlineScrollback(
|
||||
layout: TerminalLayoutSnapshot,
|
||||
leafId: string
|
||||
): TerminalLayoutSnapshot {
|
||||
if (!layout.buffersByLeafId || !Object.hasOwn(layout.buffersByLeafId, leafId)) {
|
||||
return layout
|
||||
}
|
||||
const buffersByLeafId = { ...layout.buffersByLeafId }
|
||||
delete buffersByLeafId[leafId]
|
||||
const nextLayout = { ...layout }
|
||||
if (Object.keys(buffersByLeafId).length > 0) {
|
||||
nextLayout.buffersByLeafId = buffersByLeafId
|
||||
} else {
|
||||
delete nextLayout.buffersByLeafId
|
||||
}
|
||||
return nextLayout
|
||||
}
|
||||
|
||||
export function hydrateTerminalScrollbackRefs(
|
||||
layout: TerminalLayoutSnapshot,
|
||||
snapshots: LocalScrollbackSnapshots
|
||||
): {
|
||||
layout: TerminalLayoutSnapshot
|
||||
hydrated: boolean
|
||||
} {
|
||||
@@ -15,14 +39,10 @@ export function hydrateTerminalScrollbackRefs(layout: TerminalLayoutSnapshot): {
|
||||
if (buffers[leafId] !== undefined) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const buffer = window.api.session.readTerminalScrollback({ ref })
|
||||
if (buffer) {
|
||||
buffers[leafId] = buffer
|
||||
hydrated = true
|
||||
}
|
||||
} catch {
|
||||
// Best-effort restore; failed snapshot reads should not block terminal mount.
|
||||
const snapshot = snapshots[leafId]
|
||||
if (snapshot?.ref === ref) {
|
||||
buffers[leafId] = snapshot.buffer
|
||||
hydrated = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,3 +50,36 @@ export function hydrateTerminalScrollbackRefs(layout: TerminalLayoutSnapshot): {
|
||||
? { layout: { ...layout, buffersByLeafId: buffers }, hydrated }
|
||||
: { layout, hydrated }
|
||||
}
|
||||
|
||||
/** A replacement manager can reuse inline bytes whose only surviving owner is this component. */
|
||||
export function restoreRetainedInlineScrollback(
|
||||
layout: TerminalLayoutSnapshot,
|
||||
retained: TerminalLayoutSnapshot | undefined,
|
||||
localOnly: Record<string, string> | undefined,
|
||||
cleared: ReadonlySet<string> | undefined
|
||||
): TerminalLayoutSnapshot {
|
||||
if (!retained?.buffersByLeafId) {
|
||||
return layout
|
||||
}
|
||||
const leaves = layout.root
|
||||
? collectLeafIds(layout.root)
|
||||
: [resolveRootlessTerminalLayoutLeafId(layout)].filter(
|
||||
(leafId): leafId is string => leafId !== null
|
||||
)
|
||||
let buffers: Record<string, string> | undefined
|
||||
for (const leafId of leaves) {
|
||||
const buffer = retained.buffersByLeafId[leafId]
|
||||
if (
|
||||
buffer !== undefined &&
|
||||
retained.scrollbackRefsByLeafId?.[leafId] === undefined &&
|
||||
layout.buffersByLeafId?.[leafId] === undefined &&
|
||||
layout.scrollbackRefsByLeafId?.[leafId] === undefined &&
|
||||
localOnly?.[leafId] === undefined &&
|
||||
!cleared?.has(leafId)
|
||||
) {
|
||||
buffers ??= { ...layout.buffersByLeafId }
|
||||
buffers[leafId] = buffer
|
||||
}
|
||||
}
|
||||
return buffers ? { ...layout, buffersByLeafId: buffers } : layout
|
||||
}
|
||||
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
HOST_TERMINAL_SCROLLBACK_HOLD_MS,
|
||||
startHostTerminalScrollbackHydration
|
||||
} from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration'
|
||||
|
||||
/**
|
||||
* True while this tab's scrollback is being read from its host. The pane mounts once, and mount
|
||||
* is the only point that replays stored scrollback, so it waits for the bytes instead of racing them.
|
||||
*/
|
||||
export function useHostTerminalScrollbackHold(tabId: string, worktreeId: string): boolean {
|
||||
// Why in the initializer: the hold must be known on the first render, before the pane mounts;
|
||||
// the start is synchronous and deduplicated per tab, so a repeated render does not refetch.
|
||||
const [pending] = useState(() => startHostTerminalScrollbackHydration(tabId, worktreeId))
|
||||
const [held, setHeld] = useState(pending !== null)
|
||||
useEffect(() => {
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
let live = true
|
||||
const release = (): void => {
|
||||
if (live) {
|
||||
setHeld(false)
|
||||
}
|
||||
}
|
||||
// Why: the read aborts at the same bound; this only guards a dependency that ignores abort.
|
||||
const timer = setTimeout(release, HOST_TERMINAL_SCROLLBACK_HOLD_MS)
|
||||
void pending.then(release)
|
||||
return () => {
|
||||
live = false
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [pending])
|
||||
return held
|
||||
}
|
||||
@@ -3,16 +3,25 @@ import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types'
|
||||
import { clearTerminalScrollbackAndFollowOutput } from '@/lib/pane-manager/terminal-scroll/terminal-scrollback-clear'
|
||||
import { clearWebRuntimeTerminalBuffer } from '@/runtime/hosted-terminals/actions/web-runtime-terminal-buffer-actions'
|
||||
import type { TerminalPaneStartupController } from '../controller/use-terminal-pane-startup-actions'
|
||||
import { clearRetainedInlineScrollback } from './terminal-scrollback-ref-hydration'
|
||||
|
||||
export function usePaneScrollbackClear({
|
||||
initialLayoutRef,
|
||||
clearedScrollbackLeafIdsRef,
|
||||
paneTransportsRef,
|
||||
persistLayoutSnapshot
|
||||
}: Pick<TerminalPaneStartupController, 'clearedScrollbackLeafIdsRef' | 'paneTransportsRef'> & {
|
||||
}: Pick<
|
||||
TerminalPaneStartupController,
|
||||
'initialLayoutRef' | 'clearedScrollbackLeafIdsRef' | 'paneTransportsRef'
|
||||
> & {
|
||||
persistLayoutSnapshot: () => void
|
||||
}) {
|
||||
const clearPaneScrollback = useCallback(
|
||||
(pane: ManagedPane): void => {
|
||||
initialLayoutRef.current = clearRetainedInlineScrollback(
|
||||
initialLayoutRef.current,
|
||||
pane.leafId
|
||||
)
|
||||
clearedScrollbackLeafIdsRef.current.add(pane.leafId)
|
||||
clearTerminalScrollbackAndFollowOutput(pane.terminal)
|
||||
const ptyId = paneTransportsRef.current.get(pane.id)?.getPtyId() ?? null
|
||||
@@ -22,7 +31,7 @@ export function usePaneScrollbackClear({
|
||||
}
|
||||
persistLayoutSnapshot()
|
||||
},
|
||||
[paneTransportsRef, persistLayoutSnapshot, clearedScrollbackLeafIdsRef]
|
||||
[initialLayoutRef, paneTransportsRef, persistLayoutSnapshot, clearedScrollbackLeafIdsRef]
|
||||
)
|
||||
return { clearPaneScrollback }
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-sw
|
||||
import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import '../layout/terminal-layout-leaf-traversal'
|
||||
import { collectLayoutLeafIdsInOrder } from '../../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree'
|
||||
import type { TerminalPaneLayoutController } from '../layout/persistence/use-terminal-pane-layout-persistence'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
/** Sync owner-published pane titles while retaining pending local renames until host echo. */
|
||||
export function hostPaneTitleUpdates(args: {
|
||||
@@ -32,11 +32,18 @@ export function hostPaneTitleUpdates(args: {
|
||||
}
|
||||
|
||||
/** Open panes follow pane names the host publishes, not only the ones they opened with. */
|
||||
export function useHostPaneTitleSync(controller: TerminalPaneLayoutController): void {
|
||||
const { managerRef, paneLayoutRevision, paneTitlesRef, savedLayout, setPaneTitles } = controller
|
||||
export function useHostPaneTitleSync(controller: TerminalPaneMountedController): void {
|
||||
const {
|
||||
terminalManager,
|
||||
managerRef,
|
||||
paneLayoutRevision,
|
||||
paneTitlesRef,
|
||||
savedLayout,
|
||||
setPaneTitles
|
||||
} = controller
|
||||
useEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (!manager) {
|
||||
if (!terminalManager || manager !== terminalManager) {
|
||||
return
|
||||
}
|
||||
const updates = hostPaneTitleUpdates({
|
||||
@@ -61,5 +68,5 @@ export function useHostPaneTitleSync(controller: TerminalPaneLayoutController):
|
||||
// The store already holds the owner's layout, so nothing is persisted or pushed back.
|
||||
paneTitlesRef.current = apply(paneTitlesRef.current)
|
||||
setPaneTitles(apply)
|
||||
}, [managerRef, paneLayoutRevision, paneTitlesRef, savedLayout, setPaneTitles])
|
||||
}, [terminalManager, managerRef, paneLayoutRevision, paneTitlesRef, savedLayout, setPaneTitles])
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
clearPaneTitleOverlayRects
|
||||
} from './pane-title-overlay-rects'
|
||||
import type { PaneTitleOverlayRect } from './pane-title-overlay-rects'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function usePaneTitleOverlayGeometry({
|
||||
containerRef,
|
||||
@@ -12,6 +12,7 @@ export function usePaneTitleOverlayGeometry({
|
||||
isolatedPaneKey,
|
||||
isVisible,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
paneLayoutRevision,
|
||||
paneTitles,
|
||||
@@ -20,12 +21,13 @@ export function usePaneTitleOverlayGeometry({
|
||||
setPaneTitleOverlayRects,
|
||||
shouldMeasureHiddenStartup
|
||||
}: Pick<
|
||||
TerminalPaneCloseController,
|
||||
TerminalPaneMountedController,
|
||||
| 'containerRef'
|
||||
| 'expandedPaneId'
|
||||
| 'isolatedPaneKey'
|
||||
| 'isVisible'
|
||||
| 'managerRef'
|
||||
| 'terminalManager'
|
||||
| 'paneCount'
|
||||
| 'paneLayoutRevision'
|
||||
| 'paneTitles'
|
||||
@@ -37,7 +39,7 @@ export function usePaneTitleOverlayGeometry({
|
||||
const syncPaneTitleOverlayRects = useCallback((): void => {
|
||||
const manager = managerRef.current
|
||||
const container = containerRef.current
|
||||
if (!manager || !container) {
|
||||
if (!terminalManager || manager !== terminalManager || !container) {
|
||||
setPaneTitleOverlayRects(clearPaneTitleOverlayRects)
|
||||
return
|
||||
}
|
||||
@@ -57,12 +59,12 @@ export function usePaneTitleOverlayGeometry({
|
||||
setPaneTitleOverlayRects((previous) =>
|
||||
arePaneTitleOverlayRectsEqual(previous, nextRects) ? previous : nextRects
|
||||
)
|
||||
}, [containerRef, managerRef, setPaneTitleOverlayRects])
|
||||
}, [terminalManager, containerRef, managerRef, setPaneTitleOverlayRects])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const manager = managerRef.current
|
||||
const container = containerRef.current
|
||||
if (!manager || !container) {
|
||||
if (!terminalManager || manager !== terminalManager || !container) {
|
||||
setPaneTitleOverlayRects(clearPaneTitleOverlayRects)
|
||||
return
|
||||
}
|
||||
@@ -105,6 +107,7 @@ export function usePaneTitleOverlayGeometry({
|
||||
syncPaneTitleOverlayRects,
|
||||
containerRef,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
setPaneTitleOverlayRects
|
||||
])
|
||||
}
|
||||
|
||||
@@ -3,19 +3,23 @@ import {
|
||||
applyTerminalPaneAttentionToManager,
|
||||
subscribeTerminalPaneAttention
|
||||
} from './terminal-pane-attention-subscriptions'
|
||||
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
|
||||
import type { TerminalPaneMountedController } from '../mounting/use-terminal-pane-lifecycle-stage'
|
||||
|
||||
export function useTerminalPaneAttention({
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneCount,
|
||||
tabId
|
||||
}: Pick<TerminalPaneCloseController, 'managerRef' | 'paneCount' | 'tabId'>): void {
|
||||
}: Pick<
|
||||
TerminalPaneMountedController,
|
||||
'managerRef' | 'terminalManager' | 'paneCount' | 'tabId'
|
||||
>): void {
|
||||
const applyTerminalPaneAttention = useCallback(() => {
|
||||
const manager = managerRef.current
|
||||
if (manager) {
|
||||
if (terminalManager && manager === terminalManager) {
|
||||
applyTerminalPaneAttentionToManager(manager, tabId)
|
||||
}
|
||||
}, [tabId, managerRef])
|
||||
}, [tabId, managerRef, terminalManager])
|
||||
useLayoutEffect(() => {
|
||||
applyTerminalPaneAttention()
|
||||
return subscribeTerminalPaneAttention(tabId, applyTerminalPaneAttention)
|
||||
|
||||
+5
-2
@@ -9,16 +9,19 @@ export function useWebClientTerminalResize({
|
||||
isActive,
|
||||
isVisible,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
paneTransportsRef
|
||||
}: {
|
||||
isActive: boolean
|
||||
isVisible: boolean
|
||||
terminalManager: PaneManager | null
|
||||
managerRef: React.RefObject<PaneManager | null>
|
||||
paneTransportsRef: React.RefObject<Map<number, PtyTransport>>
|
||||
}): void {
|
||||
useEffect(() => {
|
||||
if (
|
||||
!(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ ||
|
||||
!terminalManager ||
|
||||
!isVisible ||
|
||||
!isActive
|
||||
) {
|
||||
@@ -27,7 +30,7 @@ export function useWebClientTerminalResize({
|
||||
const cleanupCallbacks: (() => void)[] = []
|
||||
const fitAndForward = (): void => {
|
||||
const manager = managerRef.current
|
||||
if (!manager) {
|
||||
if (manager !== terminalManager) {
|
||||
return
|
||||
}
|
||||
for (const pane of manager.getPanes()) {
|
||||
@@ -65,5 +68,5 @@ export function useWebClientTerminalResize({
|
||||
cleanup()
|
||||
}
|
||||
}
|
||||
}, [isActive, isVisible, managerRef, paneTransportsRef])
|
||||
}, [terminalManager, isActive, isVisible, managerRef, paneTransportsRef])
|
||||
}
|
||||
|
||||
+18
-4
@@ -31,6 +31,7 @@ type UseTerminalPaneGlobalEffectsArgs = {
|
||||
/** Keep WebGL attached in a laid-out hidden host so a likely reveal skips context and atlas setup. */
|
||||
warmRendererWhileHidden?: boolean
|
||||
paneCount: number
|
||||
terminalManager: PaneManager | null
|
||||
managerRef: React.RefObject<PaneManager | null>
|
||||
containerRef: React.RefObject<HTMLDivElement | null>
|
||||
paneTransportsRef: React.RefObject<Map<number, PtyTransport>>
|
||||
@@ -50,6 +51,7 @@ export function useTerminalPaneGlobalEffects({
|
||||
warmRendererWhileHidden = false,
|
||||
paneCount,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
containerRef,
|
||||
paneTransportsRef,
|
||||
panePtyBindingsRef,
|
||||
@@ -58,6 +60,7 @@ export function useTerminalPaneGlobalEffects({
|
||||
toggleExpandPane
|
||||
}: UseTerminalPaneGlobalEffectsArgs): void {
|
||||
// Start true so initially hidden panes suspend the WebGL context openTerminal creates instead of exhausting Chromium’s context budget.
|
||||
const previousManagerRef = useRef<PaneManager | null>(null)
|
||||
const wasVisibleRef = useRef(true)
|
||||
const wasWorktreeActiveRef = useRef(isWorktreeActive)
|
||||
const hasCompletedVisibleResumeRef = useRef(false)
|
||||
@@ -77,6 +80,7 @@ export function useTerminalPaneGlobalEffects({
|
||||
applyPendingFollowOutputRequests,
|
||||
scheduleFollowOutputIfNeeded
|
||||
} = useTerminalScrollVisibilityMemory({
|
||||
terminalManager,
|
||||
managerRef,
|
||||
isVisibleRef,
|
||||
visibleResumeCompleteRef: wasVisibleRef,
|
||||
@@ -97,13 +101,22 @@ export function useTerminalPaneGlobalEffects({
|
||||
panePtyBindingsRef
|
||||
})
|
||||
|
||||
useRendererPtyVisibilityClaims({ paneTransportsRef, rendererVisible })
|
||||
useRendererPtyVisibilityClaims({ terminalManager, paneTransportsRef, rendererVisible })
|
||||
|
||||
useEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (!manager) {
|
||||
if (!terminalManager || manager !== terminalManager) {
|
||||
return
|
||||
}
|
||||
if (previousManagerRef.current !== manager) {
|
||||
previousManagerRef.current = manager
|
||||
wasVisibleRef.current = true
|
||||
wasWorktreeActiveRef.current = isWorktreeActive
|
||||
hasCompletedVisibleResumeRef.current = false
|
||||
renderingSuspendedByVisibilityRef.current = false
|
||||
hiddenReasonRef.current = null
|
||||
warmedWhileHiddenRef.current = false
|
||||
}
|
||||
manager.setAtlasRecoveryVisible?.(rendererVisible)
|
||||
// Why: hidden-worktree panes keep their WebGL backing; tab-hidden ones may release it (pane-webgl-renderer).
|
||||
containerRef.current?.toggleAttribute('data-worktree-surface-hidden', !isWorktreeActive)
|
||||
@@ -183,14 +196,15 @@ export function useTerminalPaneGlobalEffects({
|
||||
isActiveRef,
|
||||
isVisibleRef,
|
||||
managerRef,
|
||||
terminalManager,
|
||||
withSuppressedScrollTracking
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (panePtyBindingsRef) {
|
||||
if (terminalManager && managerRef.current === terminalManager && panePtyBindingsRef) {
|
||||
syncPaneOutputCadences(panePtyBindingsRef.current)
|
||||
}
|
||||
}, [isActive, panePtyBindingsRef])
|
||||
}, [terminalManager, managerRef, isActive, panePtyBindingsRef])
|
||||
|
||||
useActiveRendererPty({ isActive, isVisible, isWorktreeActive, activeLeafPtyId })
|
||||
|
||||
|
||||
+14
-3
@@ -8,7 +8,7 @@ import {
|
||||
reconcileMissingSessions,
|
||||
type ReconcilableBinding
|
||||
} from '../../pty-connection/lifecycle/terminal-dead-session-reconcile'
|
||||
import type { UseTerminalPaneLifecycleDeps } from '../../mounting/terminal-pane-lifecycle-types'
|
||||
import type { MountedTerminalPaneLifecycleDeps } from '../../mounting/terminal-pane-lifecycle-types'
|
||||
import type { TerminalPaneLifecycleRefs } from '../../mounting/use-terminal-pane-lifecycle-refs'
|
||||
|
||||
type IDisposableWithVisibility = IDisposable & {
|
||||
@@ -18,12 +18,21 @@ type IDisposableWithVisibility = IDisposable & {
|
||||
|
||||
export function useTerminalPaneProcessVisibility(
|
||||
deps: Pick<
|
||||
UseTerminalPaneLifecycleDeps,
|
||||
'tabId' | 'cwd' | 'isVisible' | 'isVisibleRef' | 'panePtyBindingsRef'
|
||||
MountedTerminalPaneLifecycleDeps,
|
||||
| 'managerRef'
|
||||
| 'mountedManager'
|
||||
| 'tabId'
|
||||
| 'cwd'
|
||||
| 'isVisible'
|
||||
| 'isVisibleRef'
|
||||
| 'panePtyBindingsRef'
|
||||
>,
|
||||
refs: Pick<TerminalPaneLifecycleRefs, 'previousVisibleForReconcileRef'>
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (!deps.mountedManager || deps.managerRef.current !== deps.mountedManager) {
|
||||
return
|
||||
}
|
||||
const previousIsVisible = getPreviousVisibleForTerminalPane({
|
||||
previous: refs.previousVisibleForReconcileRef.current,
|
||||
tabId: deps.tabId,
|
||||
@@ -55,6 +64,8 @@ export function useTerminalPaneProcessVisibility(
|
||||
})
|
||||
}
|
||||
}, [
|
||||
deps.mountedManager,
|
||||
deps.managerRef,
|
||||
deps.cwd,
|
||||
deps.isVisible,
|
||||
deps.isVisibleRef,
|
||||
|
||||
+12
-3
@@ -21,6 +21,7 @@ type VisibleScrollSnapshot = {
|
||||
}
|
||||
|
||||
type UseTerminalScrollVisibilityMemoryArgs = {
|
||||
terminalManager: PaneManager | null
|
||||
managerRef: React.RefObject<PaneManager | null>
|
||||
isVisibleRef: React.RefObject<boolean>
|
||||
visibleResumeCompleteRef: React.RefObject<boolean>
|
||||
@@ -38,6 +39,7 @@ const FOLLOW_OUTPUT_FLUSH_CHARS = 256 * 1024
|
||||
|
||||
export function useTerminalScrollVisibilityMemory({
|
||||
managerRef,
|
||||
terminalManager,
|
||||
isVisibleRef,
|
||||
visibleResumeCompleteRef,
|
||||
paneCount
|
||||
@@ -163,11 +165,18 @@ export function useTerminalScrollVisibilityMemory({
|
||||
[applyPendingFollowOutputRequests]
|
||||
)
|
||||
|
||||
useEffect(() => cancelPendingFollowOutputFrames, [cancelPendingFollowOutputFrames])
|
||||
useEffect(
|
||||
() => () => {
|
||||
cancelPendingFollowOutputFrames()
|
||||
visibleScrollSnapshotsRef.current.clear()
|
||||
pendingFollowOutputPaneIdsRef.current.clear()
|
||||
},
|
||||
[terminalManager, cancelPendingFollowOutputFrames]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const manager = managerRef.current
|
||||
if (!manager) {
|
||||
if (!terminalManager || manager !== terminalManager) {
|
||||
return
|
||||
}
|
||||
const panes = manager.getPanes()
|
||||
@@ -178,7 +187,7 @@ export function useTerminalScrollVisibilityMemory({
|
||||
pendingFollowOutputPaneIdsRef.current.delete(paneId)
|
||||
}
|
||||
}
|
||||
}, [managerRef, paneCount])
|
||||
}, [terminalManager, managerRef, paneCount])
|
||||
|
||||
return {
|
||||
captureViewportPositions,
|
||||
|
||||
+124
-3
@@ -1,4 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { hydrateTerminalScrollbackRefs } from '../../../components/terminal-pane/snapshots/terminal-scrollback-ref-hydration'
|
||||
import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import {
|
||||
HOST_TERMINAL_SCROLLBACK_HOLD_MS,
|
||||
@@ -33,7 +34,7 @@ function harness(overrides: Partial<HostTerminalScrollbackHydrationDeps> = {}) {
|
||||
const deps = {
|
||||
getTabState: vi.fn(() => tabState),
|
||||
resolveEnvironmentId: vi.fn((_worktreeId: string): string | null => 'env-wsl'),
|
||||
hasLocalSnapshot: vi.fn((_ref: string) => false),
|
||||
readLocalSnapshot: vi.fn(async (_ref: string): Promise<string | null> => null),
|
||||
peekHostSupportsRead: vi.fn((_environmentId: string): boolean | undefined => true),
|
||||
warmHostSupportsRead: vi.fn(async (_environmentId: string): Promise<unknown> => true),
|
||||
readHostSnapshot: vi.fn(
|
||||
@@ -59,6 +60,126 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('startHostTerminalScrollbackHydration', () => {
|
||||
it('restores slow local history while the replaced pane is still mounted without writing a session', async () => {
|
||||
vi.useFakeTimers()
|
||||
let finish!: (buffer: string) => void
|
||||
const { deps, tabState } = harness({
|
||||
resolveEnvironmentId: () => null,
|
||||
isTabMounted: () => true,
|
||||
readLocalSnapshot: () =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
})
|
||||
tabState.layout = layout({ ptyIdsByLeafId: { 'leaf-1': 'daemon-pty' } })
|
||||
const pending = startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)!
|
||||
await vi.advanceTimersByTimeAsync(HOST_TERMINAL_SCROLLBACK_HOLD_MS + 1)
|
||||
finish('saved full-screen frame')
|
||||
const captured = await pending.ready
|
||||
expect(
|
||||
hydrateTerminalScrollbackRefs(tabState.layout!, captured).layout.buffersByLeafId
|
||||
).toEqual({ 'leaf-1': 'saved full-screen frame' })
|
||||
expect(deps.storeLocalOnly).not.toHaveBeenCalled()
|
||||
expect(deps.readHostSnapshot).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses local bytes even when the host has no snapshot capability and preserves newer park bytes', async () => {
|
||||
let finish!: (buffer: string) => void
|
||||
const { deps, tabState } = harness({
|
||||
peekHostSupportsRead: () => false,
|
||||
readLocalSnapshot: () =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
})
|
||||
const pending = startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)!
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
finish('local history')
|
||||
const captured = await pending.ready
|
||||
expect(
|
||||
hydrateTerminalScrollbackRefs(tabState.layout!, captured).layout.buffersByLeafId
|
||||
).toEqual({ 'leaf-1': 'local history' })
|
||||
const changed = layout({ scrollbackRefsByLeafId: { 'leaf-1': 'new-ref' } })
|
||||
expect(hydrateTerminalScrollbackRefs(changed, captured).layout.buffersByLeafId).toBeUndefined()
|
||||
const parked = layout({ buffersByLeafId: { 'leaf-1': 'newer park history' } })
|
||||
expect(hydrateTerminalScrollbackRefs(parked, captured).layout.buffersByLeafId).toEqual({
|
||||
'leaf-1': 'newer park history'
|
||||
})
|
||||
expect(deps.readHostSnapshot).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('commits validated bytes before a later queued ref update can invalidate their handoff', async () => {
|
||||
const { deps, tabState } = harness({
|
||||
resolveEnvironmentId: () => null,
|
||||
readLocalSnapshot: async () => 'history at the commit boundary'
|
||||
})
|
||||
let mountedBuffers: Record<string, string> | undefined
|
||||
const pending = startHostTerminalScrollbackHydration(
|
||||
'tab-1',
|
||||
'repo::/wt',
|
||||
deps,
|
||||
() => true,
|
||||
(snapshots) => {
|
||||
mountedBuffers = hydrateTerminalScrollbackRefs(tabState.layout!, snapshots).layout
|
||||
.buffersByLeafId
|
||||
}
|
||||
)!
|
||||
void pending.local.then(() => {
|
||||
queueMicrotask(() => {
|
||||
tabState.layout = layout({ scrollbackRefsByLeafId: { 'leaf-1': 'later-ref' } })
|
||||
})
|
||||
})
|
||||
await pending.ready
|
||||
expect(tabState.layout?.scrollbackRefsByLeafId).toEqual({ 'leaf-1': 'later-ref' })
|
||||
expect(mountedBuffers).toEqual({ 'leaf-1': 'history at the commit boundary' })
|
||||
})
|
||||
|
||||
it('restores host history after a failed local read', async () => {
|
||||
const { deps, tabState } = harness({
|
||||
readLocalSnapshot: async () => {
|
||||
throw new Error('unreadable')
|
||||
}
|
||||
})
|
||||
await startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)?.ready
|
||||
expect(tabState.localOnly).toEqual({ 'leaf-1': 'host history' })
|
||||
})
|
||||
|
||||
it('releases the host deadline when its mount retires', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { deps } = harness({ readHostSnapshot: () => new Promise<string>(() => {}) })
|
||||
const pending = startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)!
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
pending.retire()
|
||||
await pending.ready
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
expect(deps.storeLocalOnly).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps one host deadline when the saved ref changes during fallback', async () => {
|
||||
vi.useFakeTimers()
|
||||
const replies = new Map<string, (buffer: string) => void>()
|
||||
const signals: AbortSignal[] = []
|
||||
const { deps, tabState } = harness({
|
||||
readHostSnapshot: (_environment, _worktree, ref, signal) => {
|
||||
signals.push(signal)
|
||||
return new Promise<string>((resolve) => replies.set(ref, resolve))
|
||||
}
|
||||
})
|
||||
const pending = startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)!
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
tabState.layout = layout({ scrollbackRefsByLeafId: { 'leaf-1': 'changed-ref' } })
|
||||
replies.get(REF)!('obsolete host history')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(replies.has('changed-ref')).toBe(true)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
await pending.ready
|
||||
expect(signals[1].aborted).toBe(true)
|
||||
replies.get('changed-ref')!('late changed history')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(deps.storeLocalOnly).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('aborts the read when the hold bound passes and drops late bytes', async () => {
|
||||
vi.useFakeTimers()
|
||||
let observed: AbortSignal | undefined
|
||||
@@ -76,11 +197,11 @@ describe('startHostTerminalScrollbackHydration', () => {
|
||||
})
|
||||
const pending = startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)
|
||||
await vi.advanceTimersByTimeAsync(HOST_TERMINAL_SCROLLBACK_HOLD_MS)
|
||||
await pending
|
||||
await pending?.ready
|
||||
expect(observed?.aborted).toBe(true)
|
||||
expect(deps.storeLocalOnly).not.toHaveBeenCalled()
|
||||
vi.mocked(deps.readHostSnapshot).mockResolvedValueOnce('retry history')
|
||||
await startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)
|
||||
await startHostTerminalScrollbackHydration('tab-1', 'repo::/wt', deps)?.ready
|
||||
expect(deps.storeLocalOnly).toHaveBeenCalledWith('tab-1', {
|
||||
'leaf-1': 'retry history'
|
||||
})
|
||||
|
||||
+138
-281
@@ -1,302 +1,159 @@
|
||||
import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { SessionReadTerminalScrollbackResult } from '../../../../../shared/rpc-contract/session-terminal-scrollback-params'
|
||||
import { SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import {
|
||||
runtimeEnvironmentIdForWorkspaceOwner,
|
||||
type RuntimeEnvironmentOwnerMatch
|
||||
} from '@/lib/workspace/ownership/resolve-owner'
|
||||
import type { OrcadDeploymentLink } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments'
|
||||
import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call'
|
||||
import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof'
|
||||
import { peekRuntimeEnvironmentCapability } from '../../rpc/compatibility/runtime-compatibility-cache'
|
||||
import { hasRuntimeRpcErrorCode } from '../../../../../shared/runtime-rpc-error-code'
|
||||
import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector'
|
||||
import { hasRegisteredRuntimeTerminalTab } from '../mounted-surfaces/mounted-terminal-tab-registry'
|
||||
defaultDeps,
|
||||
planHostScrollbackHydration,
|
||||
fetchHostScrollback,
|
||||
HOST_TERMINAL_SCROLLBACK_HOLD_MS,
|
||||
resetHostTerminalScrollbackReadsForTests,
|
||||
type HostTerminalScrollbackHydrationDeps,
|
||||
type LocalScrollbackSnapshots
|
||||
} from './host-terminal-scrollback-reads'
|
||||
|
||||
// Why bounded: a slow or unreachable host must never keep a terminal from mounting.
|
||||
export const HOST_TERMINAL_SCROLLBACK_HOLD_MS = 3_000
|
||||
export {
|
||||
HOST_TERMINAL_SCROLLBACK_HOLD_MS,
|
||||
hostScrollbackEnvironmentId
|
||||
} from './host-terminal-scrollback-reads'
|
||||
export type {
|
||||
HostTerminalScrollbackHydrationDeps,
|
||||
HostTerminalScrollbackTabState,
|
||||
LocalScrollbackSnapshots
|
||||
} from './host-terminal-scrollback-reads'
|
||||
|
||||
// Answers that will not change on retry; anything else (transport, timeout, abort) may.
|
||||
const DEFINITE_READ_FAILURE_CODES = [
|
||||
'terminal_scrollback_not_found',
|
||||
'terminal_scrollback_too_large'
|
||||
]
|
||||
|
||||
export type HostTerminalScrollbackTabState = {
|
||||
layout: TerminalLayoutSnapshot | undefined
|
||||
localOnly: Record<string, string> | undefined
|
||||
export type TerminalScrollbackHydrationAttempt = {
|
||||
local: Promise<boolean>
|
||||
ready: Promise<LocalScrollbackSnapshots>
|
||||
retire: () => void
|
||||
}
|
||||
|
||||
export type HostTerminalScrollbackHydrationDeps = {
|
||||
getTabState: (tabId: string) => HostTerminalScrollbackTabState
|
||||
/** Null for a pane this machine runs; such panes never ask a host. */
|
||||
resolveEnvironmentId: (worktreeId: string) => string | null
|
||||
/** Stat-only check of this client's own snapshot store; web clients have none. */
|
||||
hasLocalSnapshot: (ref: string) => boolean
|
||||
/** Cached verdict only; undefined when this client has no fresh status for the host. */
|
||||
peekHostSupportsRead: (environmentId: string) => boolean | undefined
|
||||
/** Fetches the host's status so a later peek answers. */
|
||||
warmHostSupportsRead: (environmentId: string) => Promise<unknown>
|
||||
readHostSnapshot: (
|
||||
environmentId: string,
|
||||
worktreeId: string,
|
||||
ref: string,
|
||||
signal: AbortSignal
|
||||
) => Promise<string>
|
||||
isTabMounted: (tabId: string) => boolean
|
||||
storeLocalOnly: (tabId: string, buffersByLeafId: Record<string, string>) => void
|
||||
}
|
||||
const localReads = new Map<string, Promise<string | null>>()
|
||||
|
||||
type HostScrollbackLeaf = { leafId: string; ref: string }
|
||||
type HostScrollbackPlan = {
|
||||
environmentId: string
|
||||
leaves: HostScrollbackLeaf[]
|
||||
/** Undefined until this client has a fresh status for the host; the read waits for one. */
|
||||
supported: boolean | undefined
|
||||
}
|
||||
type FetchedHostScrollbackLeaf = HostScrollbackLeaf & { buffer: string | null }
|
||||
|
||||
const defaultDeps: HostTerminalScrollbackHydrationDeps = {
|
||||
getTabState: (tabId) => {
|
||||
const state = useAppStore.getState()
|
||||
return {
|
||||
layout: state.terminalLayoutsByTabId[tabId],
|
||||
localOnly: state.localOnlyScrollbackByTabId[tabId]
|
||||
}
|
||||
},
|
||||
resolveEnvironmentId: (worktreeId) => {
|
||||
const state = useAppStore.getState()
|
||||
return hostScrollbackEnvironmentId(
|
||||
runtimeEnvironmentIdForWorkspaceOwner(state, { workspaceId: worktreeId }),
|
||||
state.runtimeEnvironments
|
||||
)
|
||||
},
|
||||
hasLocalSnapshot: (ref) => {
|
||||
try {
|
||||
return window.api.session.hasTerminalScrollback({ ref })
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
peekHostSupportsRead: (environmentId) =>
|
||||
peekRuntimeEnvironmentCapability(
|
||||
environmentId,
|
||||
SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY
|
||||
),
|
||||
warmHostSupportsRead: (environmentId) =>
|
||||
runtimeEnvironmentSupportsCapability(
|
||||
environmentId,
|
||||
SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY
|
||||
),
|
||||
readHostSnapshot: async (environmentId, worktreeId, ref, signal) =>
|
||||
(
|
||||
await callRuntimeRpc<SessionReadTerminalScrollbackResult>(
|
||||
{ kind: 'environment', environmentId },
|
||||
'session.readTerminalScrollback',
|
||||
{ worktree: toRuntimeWorktreeSelector(worktreeId), ref },
|
||||
{ timeoutMs: HOST_TERMINAL_SCROLLBACK_HOLD_MS, signal }
|
||||
)
|
||||
).buffer,
|
||||
isTabMounted: (tabId) => hasRegisteredRuntimeTerminalTab(tabId),
|
||||
storeLocalOnly: (tabId, buffersByLeafId) =>
|
||||
useAppStore.getState().setTabLocalOnlyScrollback(tabId, buffersByLeafId)
|
||||
}
|
||||
|
||||
// Why: a pane snapshot with a definite answer is never asked for again, so it never holds a mount twice.
|
||||
const settledKeys = new Set<string>()
|
||||
// Why: a known local copy needs no further stat IPC on remount.
|
||||
const localSnapshotRefs = new Set<string>()
|
||||
const inFlightByTabId = new Map<string, Promise<void>>()
|
||||
const warmingByEnvironmentId = new Map<string, Promise<void>>()
|
||||
|
||||
function attemptKey(environmentId: string, tabId: string, ref: string): string {
|
||||
return `${environmentId}\0${tabId}\0${ref}`
|
||||
}
|
||||
|
||||
function hasLocalSnapshotCached(ref: string, deps: HostTerminalScrollbackHydrationDeps): boolean {
|
||||
if (localSnapshotRefs.has(ref)) {
|
||||
return true
|
||||
}
|
||||
if (!deps.hasLocalSnapshot(ref)) {
|
||||
return false
|
||||
}
|
||||
localSnapshotRefs.add(ref)
|
||||
return true
|
||||
}
|
||||
|
||||
function warmCapability(
|
||||
environmentId: string,
|
||||
function readLocal(
|
||||
key: string,
|
||||
ref: string,
|
||||
deps: HostTerminalScrollbackHydrationDeps
|
||||
): Promise<void> {
|
||||
const warming = warmingByEnvironmentId.get(environmentId)
|
||||
if (warming) {
|
||||
return warming
|
||||
): Promise<string | null> {
|
||||
const pending = localReads.get(key)
|
||||
if (pending) {
|
||||
return pending
|
||||
}
|
||||
const pending = Promise.resolve()
|
||||
.then(() => deps.warmHostSupportsRead(environmentId))
|
||||
.then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
.finally(() => warmingByEnvironmentId.delete(environmentId))
|
||||
warmingByEnvironmentId.set(environmentId, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
function planHostScrollbackHydration(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
deps: HostTerminalScrollbackHydrationDeps
|
||||
): HostScrollbackPlan | null {
|
||||
const { layout, localOnly } = deps.getTabState(tabId)
|
||||
const refs = Object.entries(layout?.scrollbackRefsByLeafId ?? {}).filter(
|
||||
([leafId]) =>
|
||||
// Why: a live PTY repaints its own screen, which replaces restored history anyway.
|
||||
layout?.ptyIdsByLeafId?.[leafId] === undefined &&
|
||||
layout?.buffersByLeafId?.[leafId] === undefined &&
|
||||
localOnly?.[leafId] === undefined
|
||||
)
|
||||
if (refs.length === 0) {
|
||||
return null
|
||||
}
|
||||
const environmentId = deps.resolveEnvironmentId(worktreeId)
|
||||
if (!environmentId) {
|
||||
return null
|
||||
}
|
||||
const leaves = refs
|
||||
.filter(
|
||||
([, ref]) =>
|
||||
!settledKeys.has(attemptKey(environmentId, tabId, ref)) &&
|
||||
!hasLocalSnapshotCached(ref, deps)
|
||||
)
|
||||
.map(([leafId, ref]) => ({ leafId, ref }))
|
||||
if (leaves.length === 0) {
|
||||
return null
|
||||
}
|
||||
// Why hold on an unknown host too: mount is the only replay, so a pane that mounts before the
|
||||
// status answers (a moved tab opened a minute after the last probe) opens empty for good.
|
||||
// Only a pane with a ref and no local copy gets here, and a definite answer settles it.
|
||||
const supported = deps.peekHostSupportsRead(environmentId)
|
||||
return supported === false ? null : { environmentId, leaves, supported }
|
||||
}
|
||||
|
||||
async function readLeaf(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
environmentId: string,
|
||||
leaf: HostScrollbackLeaf,
|
||||
signal: AbortSignal,
|
||||
deps: HostTerminalScrollbackHydrationDeps
|
||||
): Promise<FetchedHostScrollbackLeaf> {
|
||||
try {
|
||||
const buffer = await deps.readHostSnapshot(environmentId, worktreeId, leaf.ref, signal)
|
||||
return { ...leaf, buffer }
|
||||
} catch (error) {
|
||||
if (DEFINITE_READ_FAILURE_CODES.some((code) => hasRuntimeRpcErrorCode(error, code))) {
|
||||
settledKeys.add(attemptKey(environmentId, tabId, leaf.ref))
|
||||
}
|
||||
return { ...leaf, buffer: null }
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchHostScrollback(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
plan: HostScrollbackPlan,
|
||||
deps: HostTerminalScrollbackHydrationDeps
|
||||
): Promise<void> {
|
||||
const controller = new AbortController()
|
||||
// Why: the hold releases at this bound; bytes after it would land behind a mounted pane.
|
||||
const deadline = setTimeout(() => controller.abort(), HOST_TERMINAL_SCROLLBACK_HOLD_MS)
|
||||
let fetched: FetchedHostScrollbackLeaf[]
|
||||
try {
|
||||
if (plan.supported === undefined) {
|
||||
await warmCapability(plan.environmentId, deps)
|
||||
if (controller.signal.aborted || deps.peekHostSupportsRead(plan.environmentId) !== true) {
|
||||
return
|
||||
const read = Promise.resolve()
|
||||
.then(() => deps.readLocalSnapshot(ref))
|
||||
.catch(() => null)
|
||||
.finally(() => {
|
||||
if (localReads.get(key) === read) {
|
||||
localReads.delete(key)
|
||||
}
|
||||
}
|
||||
fetched = await Promise.all(
|
||||
plan.leaves.map((leaf) =>
|
||||
readLeaf(tabId, worktreeId, plan.environmentId, leaf, controller.signal, deps)
|
||||
)
|
||||
)
|
||||
} finally {
|
||||
clearTimeout(deadline)
|
||||
}
|
||||
// Why: a mounted pane's xterm already owns its bytes; its next park captures them instead.
|
||||
if (controller.signal.aborted || deps.isTabMounted(tabId)) {
|
||||
return
|
||||
}
|
||||
const { layout, localOnly } = deps.getTabState(tabId)
|
||||
const next = { ...localOnly }
|
||||
const stored: HostScrollbackLeaf[] = []
|
||||
for (const { leafId, ref, buffer } of fetched) {
|
||||
if (
|
||||
buffer &&
|
||||
layout?.scrollbackRefsByLeafId?.[leafId] === ref &&
|
||||
layout.buffersByLeafId?.[leafId] === undefined &&
|
||||
next[leafId] === undefined
|
||||
) {
|
||||
next[leafId] = buffer
|
||||
stored.push({ leafId, ref })
|
||||
}
|
||||
}
|
||||
if (stored.length > 0) {
|
||||
deps.storeLocalOnly(tabId, next)
|
||||
for (const { ref } of stored) {
|
||||
settledKeys.add(attemptKey(plan.environmentId, tabId, ref))
|
||||
}
|
||||
}
|
||||
})
|
||||
localReads.set(key, read)
|
||||
return read
|
||||
}
|
||||
|
||||
/**
|
||||
* The host to read a pane's stored scrollback from: only a WSL host, whose moved panes keep their
|
||||
* history as host snapshots. SSH and paired-server panes paint as before, with no hold or read.
|
||||
* Null for a twin too: no single host owns the stored scrollback, so the pane paints locally.
|
||||
*/
|
||||
export function hostScrollbackEnvironmentId(
|
||||
owner: RuntimeEnvironmentOwnerMatch,
|
||||
environments: readonly { id: string; orcadDeployment?: OrcadDeploymentLink | null }[] | undefined
|
||||
): string | null {
|
||||
if (owner.kind !== 'resolved' || owner.environmentId === null) {
|
||||
return null
|
||||
}
|
||||
const environmentId = owner.environmentId
|
||||
const environment = environments?.find((candidate) => candidate.id === environmentId)
|
||||
return environment?.orcadDeployment?.kind === 'wsl' ? environmentId : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts reading a host-run tab's stored scrollback from its host when this client has no copy,
|
||||
* so the pane paints its history after a move deleted (or a web client never had) the local one.
|
||||
* Decides synchronously and holds unless the host is known not to serve the read; returns null
|
||||
* when there is nothing to fetch. The promise never rejects and settles by the hold bound.
|
||||
*/
|
||||
/** Each manager mount acquires current bytes; retiring a consumer never drains another's result. */
|
||||
export function startHostTerminalScrollbackHydration(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
deps: HostTerminalScrollbackHydrationDeps = defaultDeps
|
||||
): Promise<void> | null {
|
||||
const inFlight = inFlightByTabId.get(tabId)
|
||||
if (inFlight) {
|
||||
return inFlight
|
||||
deps: HostTerminalScrollbackHydrationDeps = defaultDeps,
|
||||
isCurrent: () => boolean = () => true,
|
||||
commit?: (snapshots: LocalScrollbackSnapshots) => void
|
||||
): TerminalScrollbackHydrationAttempt | null {
|
||||
const missingLeaves = () => {
|
||||
const { layout, localOnly } = deps.getTabState(tabId)
|
||||
return Object.entries(layout?.scrollbackRefsByLeafId ?? {}).filter(
|
||||
([leafId]) =>
|
||||
layout?.buffersByLeafId?.[leafId] === undefined && localOnly?.[leafId] === undefined
|
||||
)
|
||||
}
|
||||
const plan = planHostScrollbackHydration(tabId, worktreeId, deps)
|
||||
if (!plan) {
|
||||
if (missingLeaves().length === 0) {
|
||||
return null
|
||||
}
|
||||
const pending = fetchHostScrollback(tabId, worktreeId, plan, deps)
|
||||
.catch(() => {})
|
||||
.finally(() => inFlightByTabId.delete(tabId))
|
||||
inFlightByTabId.set(tabId, pending)
|
||||
return pending
|
||||
const retirement = new AbortController()
|
||||
const current = (): boolean => !retirement.signal.aborted && isCurrent()
|
||||
let snapshots: LocalScrollbackSnapshots = {}
|
||||
const attempted = new Map<string, string>()
|
||||
let hostDeadline: number | undefined
|
||||
const unattemptedLeaves = () =>
|
||||
missingLeaves().filter(([leafId, ref]) => attempted.get(leafId) !== ref)
|
||||
const readCurrentLocal = async (): Promise<void> => {
|
||||
while (current()) {
|
||||
const leaves = unattemptedLeaves()
|
||||
if (leaves.length === 0) {
|
||||
return
|
||||
}
|
||||
for (const [leafId, ref] of leaves) {
|
||||
if (!current()) {
|
||||
return
|
||||
}
|
||||
const state = deps.getTabState(tabId)
|
||||
if (
|
||||
state.layout?.scrollbackRefsByLeafId?.[leafId] !== ref ||
|
||||
state.layout.buffersByLeafId?.[leafId] !== undefined ||
|
||||
state.localOnly?.[leafId] !== undefined
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const buffer = await readLocal(`${worktreeId}\0${tabId}\0${ref}`, ref, deps)
|
||||
if (!current()) {
|
||||
return
|
||||
}
|
||||
attempted.set(leafId, ref)
|
||||
if (buffer) {
|
||||
snapshots[leafId] = { ref, buffer }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const local = Promise.resolve().then(async () => {
|
||||
await readCurrentLocal()
|
||||
return current() && planHostScrollbackHydration(tabId, worktreeId, deps, snapshots) !== null
|
||||
})
|
||||
const ready = local.then(async () => {
|
||||
while (current()) {
|
||||
await readCurrentLocal()
|
||||
if (!current()) {
|
||||
break
|
||||
}
|
||||
const plan = planHostScrollbackHydration(tabId, worktreeId, deps, snapshots)
|
||||
if (plan) {
|
||||
hostDeadline ??= Date.now() + HOST_TERMINAL_SCROLLBACK_HOLD_MS
|
||||
const remaining = hostDeadline - Date.now()
|
||||
if (remaining > 0) {
|
||||
await fetchHostScrollback(
|
||||
tabId,
|
||||
worktreeId,
|
||||
plan,
|
||||
deps,
|
||||
current,
|
||||
retirement.signal,
|
||||
remaining
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!current()) {
|
||||
break
|
||||
}
|
||||
if (unattemptedLeaves().length > 0) {
|
||||
continue
|
||||
}
|
||||
// No promise gap between the final ref validation and synchronous mount preparation.
|
||||
if (commit) {
|
||||
commit(snapshots)
|
||||
snapshots = {}
|
||||
}
|
||||
return snapshots
|
||||
}
|
||||
snapshots = {}
|
||||
return {}
|
||||
})
|
||||
return {
|
||||
local,
|
||||
ready,
|
||||
retire: () => {
|
||||
retirement.abort()
|
||||
snapshots = {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function resetHostTerminalScrollbackHydrationForTests(): void {
|
||||
settledKeys.clear()
|
||||
localSnapshotRefs.clear()
|
||||
inFlightByTabId.clear()
|
||||
warmingByEnvironmentId.clear()
|
||||
localReads.clear()
|
||||
resetHostTerminalScrollbackReadsForTests()
|
||||
}
|
||||
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { SessionReadTerminalScrollbackResult } from '../../../../../shared/rpc-contract/session-terminal-scrollback-params'
|
||||
import { SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import {
|
||||
runtimeEnvironmentIdForWorkspaceOwner,
|
||||
type RuntimeEnvironmentOwnerMatch
|
||||
} from '@/lib/workspace/ownership/resolve-owner'
|
||||
import type { OrcadDeploymentLink } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments'
|
||||
import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call'
|
||||
import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof'
|
||||
import { peekRuntimeEnvironmentCapability } from '../../rpc/compatibility/runtime-compatibility-cache'
|
||||
import { hasRuntimeRpcErrorCode } from '../../../../../shared/runtime-rpc-error-code'
|
||||
import { toRuntimeWorktreeSelector } from '../../rpc/targets/runtime-worktree-selector'
|
||||
import { hasRegisteredRuntimeTerminalTab } from '../mounted-surfaces/mounted-terminal-tab-registry'
|
||||
|
||||
// Why bounded: a slow or unreachable host must never keep a terminal from mounting.
|
||||
export const HOST_TERMINAL_SCROLLBACK_HOLD_MS = 3_000
|
||||
|
||||
// Answers that will not change on retry; anything else (transport, timeout, abort) may.
|
||||
const DEFINITE_READ_FAILURE_CODES = [
|
||||
'terminal_scrollback_not_found',
|
||||
'terminal_scrollback_too_large'
|
||||
]
|
||||
|
||||
export type HostTerminalScrollbackTabState = {
|
||||
layout: TerminalLayoutSnapshot | undefined
|
||||
localOnly: Record<string, string> | undefined
|
||||
}
|
||||
|
||||
export type HostTerminalScrollbackHydrationDeps = {
|
||||
getTabState: (tabId: string) => HostTerminalScrollbackTabState
|
||||
/** Null for a pane this machine runs; such panes never ask a host. */
|
||||
resolveEnvironmentId: (worktreeId: string) => string | null
|
||||
readLocalSnapshot: (ref: string) => Promise<string | null>
|
||||
/** Cached verdict only; undefined when this client has no fresh status for the host. */
|
||||
peekHostSupportsRead: (environmentId: string) => boolean | undefined
|
||||
/** Fetches the host's status so a later peek answers. */
|
||||
warmHostSupportsRead: (environmentId: string) => Promise<unknown>
|
||||
readHostSnapshot: (
|
||||
environmentId: string,
|
||||
worktreeId: string,
|
||||
ref: string,
|
||||
signal: AbortSignal
|
||||
) => Promise<string>
|
||||
isTabMounted: (tabId: string) => boolean
|
||||
storeLocalOnly: (tabId: string, buffersByLeafId: Record<string, string>) => void
|
||||
}
|
||||
|
||||
type HostScrollbackLeaf = { leafId: string; ref: string }
|
||||
export type HostScrollbackPlan = {
|
||||
environmentId: string
|
||||
leaves: HostScrollbackLeaf[]
|
||||
/** Undefined until this client has a fresh status for the host; the read waits for one. */
|
||||
supported: boolean | undefined
|
||||
}
|
||||
|
||||
export const defaultDeps: HostTerminalScrollbackHydrationDeps = {
|
||||
getTabState: (tabId) => {
|
||||
const state = useAppStore.getState()
|
||||
return {
|
||||
layout: state.terminalLayoutsByTabId[tabId],
|
||||
localOnly: state.localOnlyScrollbackByTabId[tabId]
|
||||
}
|
||||
},
|
||||
resolveEnvironmentId: (worktreeId) => {
|
||||
const state = useAppStore.getState()
|
||||
return hostScrollbackEnvironmentId(
|
||||
runtimeEnvironmentIdForWorkspaceOwner(state, { workspaceId: worktreeId }),
|
||||
state.runtimeEnvironments
|
||||
)
|
||||
},
|
||||
readLocalSnapshot: (ref) => window.api.session.readTerminalScrollback({ ref }),
|
||||
peekHostSupportsRead: (environmentId) =>
|
||||
peekRuntimeEnvironmentCapability(
|
||||
environmentId,
|
||||
SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY
|
||||
),
|
||||
warmHostSupportsRead: (environmentId) =>
|
||||
runtimeEnvironmentSupportsCapability(
|
||||
environmentId,
|
||||
SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY
|
||||
),
|
||||
readHostSnapshot: async (environmentId, worktreeId, ref, signal) =>
|
||||
(
|
||||
await callRuntimeRpc<SessionReadTerminalScrollbackResult>(
|
||||
{ kind: 'environment', environmentId },
|
||||
'session.readTerminalScrollback',
|
||||
{ worktree: toRuntimeWorktreeSelector(worktreeId), ref },
|
||||
{ timeoutMs: HOST_TERMINAL_SCROLLBACK_HOLD_MS, signal }
|
||||
)
|
||||
).buffer,
|
||||
isTabMounted: (tabId) => hasRegisteredRuntimeTerminalTab(tabId),
|
||||
storeLocalOnly: (tabId, buffersByLeafId) =>
|
||||
useAppStore.getState().setTabLocalOnlyScrollback(tabId, buffersByLeafId)
|
||||
}
|
||||
|
||||
// Why: a pane snapshot with a definite answer is never asked for again, so it never holds a mount twice.
|
||||
const settledKeys = new Set<string>()
|
||||
export type LocalScrollbackSnapshots = Record<string, { ref: string; buffer: string }>
|
||||
|
||||
const warmingByEnvironmentId = new Map<string, Promise<void>>()
|
||||
|
||||
function attemptKey(environmentId: string, tabId: string, ref: string): string {
|
||||
return `${environmentId}\0${tabId}\0${ref}`
|
||||
}
|
||||
|
||||
function warmCapability(
|
||||
environmentId: string,
|
||||
deps: HostTerminalScrollbackHydrationDeps
|
||||
): Promise<void> {
|
||||
const warming = warmingByEnvironmentId.get(environmentId)
|
||||
if (warming) {
|
||||
return warming
|
||||
}
|
||||
const pending = Promise.resolve()
|
||||
.then(() => deps.warmHostSupportsRead(environmentId))
|
||||
.then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
.finally(() => warmingByEnvironmentId.delete(environmentId))
|
||||
warmingByEnvironmentId.set(environmentId, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
export function planHostScrollbackHydration(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
deps: HostTerminalScrollbackHydrationDeps,
|
||||
local: LocalScrollbackSnapshots
|
||||
): HostScrollbackPlan | null {
|
||||
const { layout, localOnly } = deps.getTabState(tabId)
|
||||
const refs = Object.entries(layout?.scrollbackRefsByLeafId ?? {}).filter(
|
||||
([leafId]) =>
|
||||
// Why: a live PTY repaints its own screen, which replaces restored history anyway.
|
||||
layout?.ptyIdsByLeafId?.[leafId] === undefined &&
|
||||
layout?.buffersByLeafId?.[leafId] === undefined &&
|
||||
localOnly?.[leafId] === undefined
|
||||
)
|
||||
if (refs.length === 0) {
|
||||
return null
|
||||
}
|
||||
const environmentId = deps.resolveEnvironmentId(worktreeId)
|
||||
if (!environmentId) {
|
||||
return null
|
||||
}
|
||||
const leaves = refs
|
||||
.filter(
|
||||
([leafId, ref]) =>
|
||||
!settledKeys.has(attemptKey(environmentId, tabId, ref)) && local[leafId]?.ref !== ref
|
||||
)
|
||||
.map(([leafId, ref]) => ({ leafId, ref }))
|
||||
if (leaves.length === 0) {
|
||||
return null
|
||||
}
|
||||
// Why hold on an unknown host too: mount is the only replay, so a pane that mounts before the
|
||||
// status answers (a moved tab opened a minute after the last probe) opens empty for good.
|
||||
// Only a pane with a ref and no local copy gets here, and a definite answer settles it.
|
||||
const supported = deps.peekHostSupportsRead(environmentId)
|
||||
return supported === false ? null : { environmentId, leaves, supported }
|
||||
}
|
||||
|
||||
async function readLeaf(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
environmentId: string,
|
||||
leaf: HostScrollbackLeaf,
|
||||
signal: AbortSignal,
|
||||
deps: HostTerminalScrollbackHydrationDeps
|
||||
): Promise<HostScrollbackLeaf & { buffer: string | null }> {
|
||||
try {
|
||||
const buffer = await deps.readHostSnapshot(environmentId, worktreeId, leaf.ref, signal)
|
||||
return { ...leaf, buffer }
|
||||
} catch (error) {
|
||||
if (DEFINITE_READ_FAILURE_CODES.some((code) => hasRuntimeRpcErrorCode(error, code))) {
|
||||
settledKeys.add(attemptKey(environmentId, tabId, leaf.ref))
|
||||
}
|
||||
return { ...leaf, buffer: null }
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchHostScrollback(
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
plan: HostScrollbackPlan,
|
||||
deps: HostTerminalScrollbackHydrationDeps,
|
||||
isCurrent: () => boolean,
|
||||
signal: AbortSignal,
|
||||
remainingMs: number
|
||||
): Promise<void> {
|
||||
const controller = new AbortController()
|
||||
const retire = (): void => controller.abort()
|
||||
signal.addEventListener('abort', retire, { once: true })
|
||||
let deadline: ReturnType<typeof setTimeout>
|
||||
const expired = new Promise<void>((resolve) => {
|
||||
controller.signal.addEventListener('abort', () => resolve(), { once: true })
|
||||
deadline = setTimeout(() => controller.abort(), remainingMs)
|
||||
if (signal.aborted) {
|
||||
controller.abort()
|
||||
}
|
||||
})
|
||||
const fetch = async (): Promise<void> => {
|
||||
if (!isCurrent() || controller.signal.aborted) {
|
||||
return
|
||||
}
|
||||
if (plan.supported === undefined) {
|
||||
await warmCapability(plan.environmentId, deps)
|
||||
if (
|
||||
!isCurrent() ||
|
||||
controller.signal.aborted ||
|
||||
deps.peekHostSupportsRead(plan.environmentId) !== true
|
||||
) {
|
||||
return
|
||||
}
|
||||
}
|
||||
const fetched = await Promise.all(
|
||||
plan.leaves.map((leaf) =>
|
||||
readLeaf(tabId, worktreeId, plan.environmentId, leaf, controller.signal, deps)
|
||||
)
|
||||
)
|
||||
if (
|
||||
!isCurrent() ||
|
||||
controller.signal.aborted ||
|
||||
deps.isTabMounted(tabId) ||
|
||||
deps.resolveEnvironmentId(worktreeId) !== plan.environmentId
|
||||
) {
|
||||
return
|
||||
}
|
||||
const { layout, localOnly } = deps.getTabState(tabId)
|
||||
const next = { ...localOnly }
|
||||
const stored: HostScrollbackLeaf[] = []
|
||||
for (const { leafId, ref, buffer } of fetched) {
|
||||
if (
|
||||
buffer &&
|
||||
layout?.scrollbackRefsByLeafId?.[leafId] === ref &&
|
||||
layout.buffersByLeafId?.[leafId] === undefined &&
|
||||
next[leafId] === undefined
|
||||
) {
|
||||
next[leafId] = buffer
|
||||
stored.push({ leafId, ref })
|
||||
}
|
||||
}
|
||||
if (stored.length > 0) {
|
||||
deps.storeLocalOnly(tabId, next)
|
||||
for (const { ref } of stored) {
|
||||
settledKeys.add(attemptKey(plan.environmentId, tabId, ref))
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await Promise.race([fetch().catch(() => {}), expired])
|
||||
} finally {
|
||||
clearTimeout(deadline!)
|
||||
signal.removeEventListener('abort', retire)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The host to read a pane's stored scrollback from: only a WSL host, whose moved panes keep their
|
||||
* history as host snapshots. SSH and paired-server panes paint as before, with no hold or read.
|
||||
* Null for a twin too: no single host owns the stored scrollback, so the pane paints locally.
|
||||
*/
|
||||
export function hostScrollbackEnvironmentId(
|
||||
owner: RuntimeEnvironmentOwnerMatch,
|
||||
environments: readonly { id: string; orcadDeployment?: OrcadDeploymentLink | null }[] | undefined
|
||||
): string | null {
|
||||
if (owner.kind !== 'resolved' || owner.environmentId === null) {
|
||||
return null
|
||||
}
|
||||
const environmentId = owner.environmentId
|
||||
const environment = environments?.find((candidate) => candidate.id === environmentId)
|
||||
return environment?.orcadDeployment?.kind === 'wsl' ? environmentId : null
|
||||
}
|
||||
|
||||
export function resetHostTerminalScrollbackReadsForTests(): void {
|
||||
settledKeys.clear()
|
||||
warmingByEnvironmentId.clear()
|
||||
}
|
||||
@@ -84,8 +84,7 @@ export function createWebWorkspaceSessionApi(): Partial<PreloadApi> {
|
||||
// localStorage writes synchronously, so there is no deferred web flush.
|
||||
flush: async () => {},
|
||||
// No local snapshot store: host-run panes read theirs from the host (host-terminal-scrollback-hydration).
|
||||
readTerminalScrollback: () => null,
|
||||
hasTerminalScrollback: () => false
|
||||
readTerminalScrollback: async () => null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user