test: remove low-value snapshot and recovery cases (#40563)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-09 17:03:06 -08:00
committed by GitHub
co-authored by OrcaWin
parent e96ee25c73
commit 08c0ffdec0
8 changed files with 27 additions and 1463 deletions
File diff suppressed because one or more lines are too long
@@ -5802,8 +5802,6 @@
"src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx": 2303,
"src/renderer/src/components/terminal-pane/session-fork/TerminalAgentSessionForkDialog.test.tsx": 266,
"src/renderer/src/components/terminal-pane/titles/TerminalPaneHeaderOverlay.test.tsx": 1104,
"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/TerminalPaneRecoveryPortals.test.tsx": 670,
"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/TerminalRemoteRuntimeReconnectBanner.test.tsx": 812,
"src/renderer/src/components/terminal-pane/account-restart/detached/account-restart-queue-progress.test.ts": 1988,
"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-attention-dispatch.test.ts": 301,
"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-completion-replay-guard.test.ts": 318,
@@ -1,226 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
CALM_STATUS_MIN_VISIBLE_MS,
CALM_STATUS_REVEAL_DELAY_MS
} from '../../../../../../../shared/calm-status-reveal'
import type { TerminalPaneController } from '../../../controller/use-terminal-pane-controller'
import { resetRemoteServerNoticeClaimsForTests } from '../../recovery/server-outage/remote-server-notice-claims'
const outage = vi.hoisted((): { environmentId: string | null } => ({ environmentId: 'env-1' }))
const wslHostStatuses = vi.hoisted((): Record<string, { state: string; distro: string }> => ({}))
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, options?: Record<string, string>) =>
fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? ''),
getIntlLocale: () => 'en-US'
}))
vi.mock('@/store/index', () => ({
useAppStore: (selector: (state: unknown) => unknown) => selector({ wslHostStatuses })
}))
vi.mock('../../../../../runtime/hosts/wsl/wsl-host-availability', () => ({
useWslHostUnavailableReason: () => null
}))
vi.mock('./use-managed-pairing-refused', () => ({
useManagedPairingRefusedEnvironmentId: () => null,
useManagedServerReplaced: () => false
}))
vi.mock('@/lib/workspace/ownership/workspace-runtime-environment', () => ({
useWorkspaceRuntimeEnvironmentId: () => 'env-1'
}))
vi.mock('../../recovery/server-outage/remote-server-outage', () => ({
useRetryingOutageEnvironmentId: () => outage.environmentId,
selectRuntimeServerName: () => 'Desk',
selectRuntimeServerTailscaleHost: () => null,
selectRemoteServerOutageCause: () => 'connection-lost'
}))
afterEach(() => {
outage.environmentId = 'env-1'
delete wslHostStatuses['env-1']
cleanup()
resetRemoteServerNoticeClaimsForTests()
document.body.innerHTML = ''
vi.useRealTimers()
})
function controllerFor(
panes: HTMLElement[],
transport: { getRuntimeEnvironmentId: () => string | null } = {
getRuntimeEnvironmentId: () => 'env-1'
}
): TerminalPaneController {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recovery portals read only these fields of the pane controller.
return {
managedPanes: panes.map((container, index) => ({ id: index + 1, container })),
ptyRecoveryStatesByPaneId: Object.fromEntries(
panes.map((_, index) => [index + 1, { phase: 'backoff', epoch: 1, attempt: 1 }])
),
paneTransportsRef: { current: new Map(panes.map((_, index) => [index + 1, transport])) },
showSshReconnectOverlay: false,
worktreeId: 'wt-1',
isVisible: true,
isolatedPaneKey: null
} as unknown as TerminalPaneController
}
describe('TerminalPaneRecoveryPortals', () => {
it('offers Start on every pane of a stopped WSL distro instead of "retrying automatically"', async () => {
vi.useFakeTimers()
wslHostStatuses['env-1'] = { state: 'distro-stopped', distro: 'Ubuntu' }
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const panes = [document.createElement('div'), document.createElement('div')]
panes.forEach((pane) => document.body.appendChild(pane))
const view = render(<TerminalPaneRecoveryPortals controller={controllerFor(panes)} />)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS))
expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(0)
expect(
document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner]')
).toHaveLength(0)
const cards = document.querySelectorAll('[data-terminal-wsl-host-stopped="env-1"]')
expect(cards).toHaveLength(2)
expect(cards[0]).toHaveTextContent('Ubuntu is stopped')
expect(cards[0].querySelector('button')).toHaveTextContent('Start')
})
it('offers Start on a pane whose create failed before it reached the stopped host', async () => {
vi.useFakeTimers()
wslHostStatuses['env-1'] = { state: 'distro-stopped', distro: 'Ubuntu' }
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const pane = document.createElement('div')
document.body.appendChild(pane)
render(
<TerminalPaneRecoveryPortals
controller={controllerFor([pane], { getRuntimeEnvironmentId: () => null })}
/>
)
expect(document.querySelectorAll('[data-terminal-wsl-host-stopped="env-1"]')).toHaveLength(1)
})
it('says a server-wide drop once for the tab and keeps every split pane quiet', async () => {
vi.useFakeTimers()
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const panes = [document.createElement('div'), document.createElement('div')]
panes.forEach((pane) => document.body.appendChild(pane))
const view = render(<TerminalPaneRecoveryPortals controller={controllerFor(panes)} />)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS))
expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(1)
expect(
document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner]')
).toHaveLength(0)
})
it('keeps every surface on the server quiet through the notice hold, then lets a still-down pane speak', async () => {
vi.useFakeTimers()
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const leftPane = document.createElement('div')
const rightPane = document.createElement('div')
document.body.append(leftPane, rightPane)
const left = controllerFor([leftPane])
const right = controllerFor([rightPane])
const surfaces = (l: TerminalPaneController, r: TerminalPaneController) => (
<>
<TerminalPaneRecoveryPortals controller={l} />
<TerminalPaneRecoveryPortals controller={r} />
</>
)
const view = render(surfaces(left, right))
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2))
const notices = () => view.container.querySelectorAll('[data-remote-server-outage-notice]')
const paneBanners = () =>
document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner]')
expect(notices()).toHaveLength(1)
outage.environmentId = null
view.rerender(surfaces({ ...left }, { ...right }))
expect(notices()).toHaveLength(1)
expect(paneBanners()).toHaveLength(0)
act(() => vi.advanceTimersByTime(CALM_STATUS_MIN_VISIBLE_MS))
expect(notices()).toHaveLength(0)
expect(paneBanners()).toHaveLength(2)
})
it('lets a pane waiting for SSH sign-in say so at once instead of a server notice', async () => {
vi.useFakeTimers()
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const pane = document.createElement('div')
document.body.append(pane)
const base = controllerFor([pane])
const controller = {
...base,
ptyRecoveryStatesByPaneId: {
1: { phase: 'backoff' as const, epoch: 1, attempt: 1, reason: 'ssh-sign-in' as const }
}
}
const view = render(<TerminalPaneRecoveryPortals controller={controller} />)
expect(
document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner="ssh-sign-in"]')
).toHaveLength(1)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2))
expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(0)
})
it('drops a visible notice at once when a pane starts waiting for SSH sign-in', async () => {
vi.useFakeTimers()
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const pane = document.createElement('div')
document.body.append(pane)
const controller = controllerFor([pane])
const view = render(<TerminalPaneRecoveryPortals controller={controller} />)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2))
expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(1)
view.rerender(
<TerminalPaneRecoveryPortals
controller={{
...controller,
ptyRecoveryStatesByPaneId: {
1: { phase: 'backoff' as const, epoch: 1, attempt: 1, reason: 'ssh-sign-in' as const }
}
}}
/>
)
expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(0)
expect(
document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner="ssh-sign-in"]')
).toHaveLength(1)
})
it('never shows two notices when the speaker hides and returns during an ongoing outage', async () => {
vi.useFakeTimers()
const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals')
const leftPane = document.createElement('div')
const rightPane = document.createElement('div')
document.body.append(leftPane, rightPane)
const left = controllerFor([leftPane])
const right = controllerFor([rightPane])
const surfaces = (l: TerminalPaneController) => (
<>
<TerminalPaneRecoveryPortals controller={l} />
<TerminalPaneRecoveryPortals controller={right} />
</>
)
const view = render(surfaces(left))
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2))
const notices = () => view.container.querySelectorAll('[data-remote-server-outage-notice]')
view.rerender(surfaces({ ...left, isVisible: false }))
view.rerender(surfaces({ ...left, isVisible: true }))
expect(notices()).toHaveLength(1)
outage.environmentId = null
view.rerender(surfaces({ ...left, isVisible: true }))
expect(notices()).toHaveLength(1)
})
})
@@ -1,284 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
CalmRemoteRuntimeReconnectBanner,
TerminalRemoteRuntimeReconnectBanner
} from './TerminalRemoteRuntimeReconnectBanner'
import {
CALM_STATUS_MIN_VISIBLE_MS,
CALM_STATUS_REVEAL_DELAY_MS
} from '../../../../../../../shared/calm-status-reveal'
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, options?: Record<string, string>) =>
fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? ''),
getIntlLocale: () => 'en-US'
}))
vi.mock('@/store/index', () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
settings: {},
runtimeEnvironments: [
{
id: 'env-1',
name: 'Desk',
preferredEndpointId: 'ws',
endpoints: [{ id: 'ws', endpoint: 'ws://100.101.102.103:6768' }]
}
]
})
}))
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('TerminalRemoteRuntimeReconnectBanner', () => {
it('names the server and the cause while retrying, without a manual action', () => {
render(
<TerminalRemoteRuntimeReconnectBanner
recovery={{ phase: 'backoff', cause: 'stream-stalled' }}
serverName="Desk"
onReconnect={vi.fn()}
/>
)
expect(screen.getByText('Terminal stopped responding')).toBeInTheDocument()
expect(screen.getByText(/Desk stopped sending/)).toBeInTheDocument()
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
it('stays neutral when nothing shows the connection dropped, such as a capacity refusal', () => {
render(
<TerminalRemoteRuntimeReconnectBanner
recovery={{ phase: 'backoff' }}
serverName="Desk"
tailscaleHost="100.101.102.103"
onReconnect={vi.fn()}
/>
)
expect(screen.getByText('Reattaching terminal')).toBeInTheDocument()
expect(screen.queryByText(/connection to the server dropped/)).not.toBeInTheDocument()
expect(screen.queryByText(/tailscale ping/)).not.toBeInTheDocument()
})
it('never claims a parked pane is retrying, and offers to try now', async () => {
const onReconnect = vi.fn()
const user = userEvent.setup()
render(
<TerminalRemoteRuntimeReconnectBanner
recovery={{ phase: 'recovering', cause: 'stream-ended', waiting: true }}
serverName="Desk"
onReconnect={onReconnect}
/>
)
expect(screen.getByText('Waiting for Desk')).toBeInTheDocument()
expect(screen.queryByText(/retrying/i)).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Reconnect' }))
expect(onReconnect).toHaveBeenCalledOnce()
})
it('offers one explicit reconnect action after automatic recovery stops', async () => {
const onReconnect = vi.fn()
const user = userEvent.setup()
render(
<TerminalRemoteRuntimeReconnectBanner
recovery={{ phase: 'disconnected' }}
serverName="Desk"
onReconnect={onReconnect}
/>
)
expect(screen.getByText('Remote runtime disconnected')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Reconnect' }))
expect(onReconnect).toHaveBeenCalledOnce()
})
it('says the host refused this computer instead of spinning, even mid-recovery', () => {
render(
<TerminalRemoteRuntimeReconnectBanner
recovery={{ phase: 'backoff' }}
serverName="Desk"
onReconnect={vi.fn()}
pairingRefused
/>
)
expect(screen.getByText('This host no longer accepts this computer')).toBeInTheDocument()
expect(screen.queryByText('Reconnecting to Desk')).not.toBeInTheDocument()
})
it('sends a replaced server to Settings instead of an ineffective Reconnect (#37766)', async () => {
const onReconnect = vi.fn()
const openSettings = vi.fn()
const user = userEvent.setup()
render(
<TerminalRemoteRuntimeReconnectBanner
recovery={{ phase: 'backoff' }}
serverName="Desk"
onReconnect={onReconnect}
pairingRefused
onOpenReplacedServerSettings={openSettings}
/>
)
expect(screen.getByText('This host runs a different Orca server')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Reconnect' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Open server settings' }))
expect(openSettings).toHaveBeenCalledOnce()
expect(onReconnect).not.toHaveBeenCalled()
})
})
describe('SSH sign-in wait', () => {
it.each(['backoff', 'disconnected'] as const)(
'shows the sign-in wait at once during %s, never the runtime-lost copy',
async (phase) => {
const onReconnect = vi.fn()
const user = userEvent.setup()
render(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase }}
environmentId="env-1"
heldByServer={false}
onReconnect={onReconnect}
awaitingSignIn
/>
)
expect(screen.getByText('Waiting for SSH sign-in')).toBeInTheDocument()
expect(screen.queryByText(/Remote runtime disconnected|Reconnecting/)).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Sign in' }))
expect(onReconnect).toHaveBeenCalledOnce()
}
)
})
describe('CalmRemoteRuntimeReconnectBanner', () => {
it('drops a resolved sign-in card at once instead of holding stale copy', () => {
vi.useFakeTimers()
const props = { environmentId: 'env-1', heldByServer: false, onReconnect: vi.fn() }
const { rerender } = render(
<CalmRemoteRuntimeReconnectBanner
{...props}
recovery={{ phase: 'disconnected' }}
awaitingSignIn
/>
)
expect(screen.getByText('Waiting for SSH sign-in')).toBeInTheDocument()
rerender(<CalmRemoteRuntimeReconnectBanner {...props} recovery={null} />)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('stays quiet through a reconnect a 400 ms relay finishes, then says it with a Tailscale hint', () => {
vi.useFakeTimers()
const { rerender } = render(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase: 'backoff', cause: 'connection' }}
environmentId="env-1"
heldByServer={false}
onReconnect={vi.fn()}
/>
)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS - 1))
rerender(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase: 'recovering', cause: 'connection' }}
environmentId="env-1"
heldByServer={false}
onReconnect={vi.fn()}
/>
)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
act(() => vi.advanceTimersByTime(1))
expect(screen.getByText('Reconnecting to Desk')).toBeInTheDocument()
expect(screen.getByText('tailscale ping 100.101.102.103')).toBeInTheDocument()
})
it('shows a stopped recovery at once', () => {
vi.useFakeTimers()
render(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase: 'disconnected' }}
environmentId="env-1"
heldByServer={false}
onReconnect={vi.fn()}
/>
)
expect(screen.getByText('Remote runtime disconnected')).toBeInTheDocument()
})
it('keeps a manual Reconnect from hiding the banner it was clicked on', () => {
vi.useFakeTimers()
const { rerender } = render(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase: 'disconnected' }}
environmentId="env-1"
heldByServer={false}
onReconnect={vi.fn()}
/>
)
rerender(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase: 'recovering', cause: 'connection' }}
environmentId="env-1"
heldByServer={false}
onReconnect={vi.fn()}
/>
)
expect(screen.getByText('Reconnecting to Desk')).toBeInTheDocument()
})
it('holds a banner that just appeared long enough to read, then lets it go', () => {
vi.useFakeTimers()
const props = { environmentId: 'env-1', heldByServer: false, onReconnect: vi.fn() }
const { rerender } = render(
<CalmRemoteRuntimeReconnectBanner {...props} recovery={{ phase: 'backoff' }} />
)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS + 100))
rerender(<CalmRemoteRuntimeReconnectBanner {...props} recovery={null} />)
expect(screen.getByRole('status')).toBeInTheDocument()
act(() => vi.advanceTimersByTime(CALM_STATUS_MIN_VISIBLE_MS))
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('leaves a server-wide drop to the server notice', () => {
vi.useFakeTimers()
render(
<CalmRemoteRuntimeReconnectBanner
recovery={{ phase: 'disconnected' }}
environmentId="env-1"
heldByServer
onReconnect={vi.fn()}
/>
)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2))
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('speaks at once for a pane still down when the server notice ends', () => {
vi.useFakeTimers()
const props = { environmentId: 'env-1', onReconnect: vi.fn() }
const recovery = { phase: 'backoff' as const, cause: 'stream-stalled' as const }
const { rerender } = render(
<CalmRemoteRuntimeReconnectBanner {...props} recovery={recovery} heldByServer />
)
act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2))
rerender(
<CalmRemoteRuntimeReconnectBanner {...props} recovery={recovery} heldByServer={false} />
)
expect(screen.getByText('Terminal stopped responding')).toBeInTheDocument()
})
})
@@ -3,96 +3,13 @@ import {
RemoteRuntimePtyRecoveryState,
retryAllRemoteRuntimePtyRecoveriesNow
} from './remote-runtime-pty-recovery-state'
import {
REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS,
REMOTE_RUNTIME_RECOVERY_ATTEMPT_BUDGET_MS,
REMOTE_RUNTIME_RECOVERY_DELAYS_MS
} from './remote-runtime-pty-recovery-limits'
import { REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS } from './remote-runtime-pty-recovery-limits'
afterEach(() => {
vi.useRealTimers()
})
describe('RemoteRuntimePtyRecoveryState', () => {
it('cancels stale retry timers when a pane detaches', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const epoch = state.begin()
state.schedule(epoch, retry)
state.cancel()
await vi.runAllTimersAsync()
expect(retry).not.toHaveBeenCalled()
expect(state.isCurrent(epoch)).toBe(false)
expect(state.isActive).toBe(false)
})
it('keeps one epoch across retries and rejects it after disposal', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const epoch = state.begin()
state.schedule(epoch, retry)
await vi.advanceTimersByTimeAsync(250)
expect(retry).toHaveBeenCalledWith(epoch)
expect(state.begin()).toBe(epoch)
state.dispose()
expect(state.isCurrent(epoch)).toBe(false)
expect(state.isActive).toBe(false)
})
it('rejects a stale retry after a newer attachment becomes healthy', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const epoch = state.begin()
state.markHealthy()
expect(state.isCurrent(epoch)).toBe(false)
expect(state.schedule(epoch, retry)).toBe(false)
await vi.runAllTimersAsync()
expect(retry).not.toHaveBeenCalled()
})
it('stops automatic recovery after the bounded recovery window', async () => {
vi.useFakeTimers()
const onChange = vi.fn()
const state = new RemoteRuntimePtyRecoveryState(onChange)
const retry = vi.fn()
const epoch = state.begin()
state.schedule(epoch, retry)
await vi.advanceTimersByTimeAsync(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS)
expect(state.currentPhase).toBe('disconnected')
expect(state.isActive).toBe(false)
expect(state.isCurrent(epoch)).toBe(false)
expect(onChange).toHaveBeenCalled()
state.dispose()
})
it('advances a pending backoff immediately via retryNow and the active registry', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const epoch = state.begin()
state.schedule(epoch, retry)
expect(retryAllRemoteRuntimePtyRecoveriesNow()).toBe(1)
expect(retryAllRemoteRuntimePtyRecoveriesNow()).toBe(0)
expect(retry).toHaveBeenCalledWith(epoch)
expect(state.currentPhase).toBe('recovering')
await vi.advanceTimersByTimeAsync(30_000)
expect(retry).toHaveBeenCalledTimes(1)
state.dispose()
})
it('does not leave a timer armed when onChange forces the retry synchronously', async () => {
vi.useFakeTimers()
const retry = vi.fn()
@@ -111,57 +28,6 @@ describe('RemoteRuntimePtyRecoveryState', () => {
state.dispose()
})
it('starts a newly fenced recovery epoch after a manual retry', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const firstEpoch = state.begin()
await vi.advanceTimersByTimeAsync(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS)
const manualEpoch = state.begin()
expect(manualEpoch).toBe(firstEpoch + 1)
expect(state.currentPhase).toBe('recovering')
expect(state.isCurrent(firstEpoch)).toBe(false)
expect(state.isCurrent(manualEpoch)).toBe(true)
state.dispose()
})
it('cancels scheduled work when a caller reaches its own recovery cutoff', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const epoch = state.begin()
state.schedule(epoch, retry)
state.markDisconnected()
await vi.runAllTimersAsync()
expect(state.currentPhase).toBe('disconnected')
expect(state.isCurrent(epoch)).toBe(false)
expect(retry).not.toHaveBeenCalled()
state.dispose()
})
it('keeps a markDisconnected pane as revivable as the deadline it imitates', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const epoch = state.begin()
state.schedule(epoch, retry)
state.markDisconnected()
// Why: the latch stops self-initiated retries only; it must not un-register the pane.
await vi.advanceTimersByTimeAsync(300_000)
expect(retry).not.toHaveBeenCalled()
expect(state.currentPhase).toBe('disconnected')
expect(retryAllRemoteRuntimePtyRecoveriesNow()).toBe(1)
expect(retry).toHaveBeenCalledWith(epoch + 1)
expect(state.currentPhase).toBe('recovering')
state.dispose()
})
it.each(['healthy', 'cancelled', 'disposed', 'deadline', 'exhausted', 'contact loss'] as const)(
'settles the owner caller once and retains only the allowance owned by %s',
async (finish) => {
@@ -223,24 +89,6 @@ describe('RemoteRuntimePtyRecoveryState', () => {
state.dispose()
})
it('revives a parked retry that never armed a backoff timer', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
const firstEpoch = state.begin()
expect(state.parkRetryForExternalTrigger(firstEpoch, retry)).toBe(true)
// Why: parking must not fire on its own, so the pane still latches at the cutoff.
await vi.advanceTimersByTimeAsync(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS + 300_000)
expect(state.currentPhase).toBe('disconnected')
expect(retry).not.toHaveBeenCalled()
expect(retryAllRemoteRuntimePtyRecoveriesNow()).toBe(1)
expect(retry).toHaveBeenCalledWith(firstEpoch + 1)
expect(state.currentPhase).toBe('recovering')
state.dispose()
})
it('fires a parked retry while still recovering, in the same epoch', () => {
const state = new RemoteRuntimePtyRecoveryState()
const retry = vi.fn()
@@ -254,75 +102,6 @@ describe('RemoteRuntimePtyRecoveryState', () => {
state.dispose()
})
it('reports a parked retry as waiting, not retrying, until a trigger fires it', () => {
const onChange = vi.fn()
const state = new RemoteRuntimePtyRecoveryState(onChange)
const epoch = state.begin()
onChange.mockClear()
expect(state.parkRetryForExternalTrigger(epoch, vi.fn())).toBe(true)
expect(state.awaitingExternalTrigger).toBe(true)
expect(onChange).toHaveBeenCalledOnce()
state.retryNow()
expect(state.awaitingExternalTrigger).toBe(false)
state.dispose()
})
it('refuses to park over an armed backoff or a stale epoch', () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const epoch = state.begin()
state.schedule(epoch, vi.fn())
expect(state.parkRetryForExternalTrigger(epoch, vi.fn())).toBe(false)
state.cancel()
expect(state.parkRetryForExternalTrigger(epoch, vi.fn())).toBe(false)
expect(retryAllRemoteRuntimePtyRecoveriesNow()).toBe(0)
state.dispose()
})
// #11305: the schedule and the deadline lived as two independent literals and drifted apart.
it('keeps the backoff schedule inside the auto-recovery budget it arms', () => {
const scheduleSumMs = REMOTE_RUNTIME_RECOVERY_DELAYS_MS.reduce(
(total, delayMs) => total + delayMs,
0
)
expect(scheduleSumMs).toBeLessThanOrEqual(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS)
// Every step also needs room for the attempt it leads into, or the tail is dead code
// whenever a half-open link makes each attempt burn its full RPC timeout.
expect(
scheduleSumMs +
REMOTE_RUNTIME_RECOVERY_DELAYS_MS.length * REMOTE_RUNTIME_RECOVERY_ATTEMPT_BUDGET_MS
).toBeLessThanOrEqual(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS)
})
it('reaches every backoff step when each attempt burns a full RPC timeout', async () => {
vi.useFakeTimers()
const state = new RemoteRuntimePtyRecoveryState()
const attemptStartsMs: number[] = []
const epoch = state.begin()
const startedAt = Date.now()
const failSlowly = (currentEpoch: number): void => {
attemptStartsMs.push(Date.now() - startedAt)
// Silent-drop reconnects do not fail instantly; they time out.
setTimeout(() => {
if (state.isCurrent(currentEpoch)) {
state.schedule(currentEpoch, failSlowly)
}
}, REMOTE_RUNTIME_RECOVERY_ATTEMPT_BUDGET_MS)
}
state.schedule(epoch, failSlowly)
await vi.advanceTimersByTimeAsync(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS)
expect(attemptStartsMs.length).toBeGreaterThanOrEqual(REMOTE_RUNTIME_RECOVERY_DELAYS_MS.length)
expect(state.currentPhase).toBe('disconnected')
state.dispose()
})
// #12683: markDisconnected() is a UI latch, not proof the window ran out.
it('only reports the auto-recovery window spent when the deadline actually fired', async () => {
vi.useFakeTimers()
@@ -47,14 +47,4 @@ describe('restoreScrollbackBuffers over a parked live TUI', () => {
terminal.dispose()
}
})
it('still leaves alt for a pane whose TUI did not survive', async () => {
const terminal = await restoreInto()
try {
expect(terminal.buffer.active.type).toBe('normal')
expect(visibleRows(terminal)[0]).toBe(LAUNCH)
} finally {
terminal.dispose()
}
})
})
@@ -1,4 +1,3 @@
import { SerializeAddon } from '@xterm/addon-serialize'
import { Terminal } from '@xterm/headless'
import { afterEach, describe, expect, it } from 'vitest'
import { restoreScrollbackBuffers } from './saved-terminal-output-replay'
@@ -52,13 +51,6 @@ async function restoreBuffer(
return terminal
}
function serialize(data: string): { terminal: Terminal; addon: SerializeAddon; data: string } {
const terminal = createTerminal()
const addon = new SerializeAddon()
terminal.loadAddon(addon)
return { terminal, addon, data }
}
afterEach(() => {
for (const terminal of terminals.splice(0)) {
terminal.dispose()
@@ -86,14 +78,4 @@ describe('fresh-shell terminal restore SGR state', () => {
expect(bottomLine?.getCell(20)?.getBgColor()).toBe(-1)
})
it('restores alt-screen scrollback without leaking its bold frame', async () => {
const source = serialize('shell-history\x1b[?1049h\x1b[1mBOLD-TUI')
await writeTerminal(source.terminal, source.data)
const restored = await restoreBuffer(source.addon.serialize())
expect(boldAtText(restored, 'shell-history')).toBe(0)
expect(boldAtText(restored, 'fresh-shell')).toBe(0)
})
})
@@ -1,22 +1,7 @@
import { describe, expect, it } from 'vitest'
import { Terminal } from '@xterm/headless'
import {
ABORT_TRUNCATED_CONTROL_STRING,
buildSnapshotReplayPrologue,
RESET_AFTER_BYTE_GAP
} from '../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles'
import {
buildParityMainBufferSnapshot,
createRendererParityTerminal,
cursorPosition,
normalBufferRowsTrimmed,
visibleRowStyles,
writeToTerminal
} from '../../../../../shared/terminal/replay/testing/terminal-restore-parity-fixture'
import {
buildMainModelSnapshotReplayWrites,
hasPositiveTerminalDimensions,
resolvePositiveTerminalDimensions,
shouldSkipAltFrameForWidthMismatch
} from './terminal-snapshot-replay-paint'
@@ -24,161 +9,7 @@ function writeTerminal(terminal: Terminal, data: string): Promise<void> {
return new Promise((resolve) => terminal.write(data, resolve))
}
const NORMAL_BUFFER_PROLOGUE_FROM_ALT = `${ABORT_TRUNCATED_CONTROL_STRING}${buildSnapshotReplayPrologue({ targetAlternateScreen: false, paneOnAlternateScreen: true })}`
const NORMAL_BUFFER_PROLOGUE = `${ABORT_TRUNCATED_CONTROL_STRING}${buildSnapshotReplayPrologue({ targetAlternateScreen: false, paneOnAlternateScreen: false })}`
const ALT_BUFFER_PROLOGUE = `${ABORT_TRUNCATED_CONTROL_STRING}${buildSnapshotReplayPrologue({ targetAlternateScreen: true, paneOnAlternateScreen: false })}`
// Already-alt snapshots must work without incidental ?1049h side effects.
const ALT_BUFFER_PROLOGUE_FROM_ALT = `${ABORT_TRUNCATED_CONTROL_STRING}${buildSnapshotReplayPrologue({ targetAlternateScreen: true, paneOnAlternateScreen: true })}`
function readRows(terminal: Terminal, count: number): (string | undefined)[] {
return Array.from({ length: count }, (_, row) =>
terminal.buffer.active.getLine(row)?.translateToString(true)
)
}
describe('RESET_AFTER_BYTE_GAP', () => {
// Use the real emulator to prove post-gap cells cannot inherit a stranded pen (STA-4042).
it('grounds the SGR pen so post-gap cells are not bold', async () => {
const terminal = new Terminal({ cols: 40, rows: 2, allowProposedApi: true })
try {
// Bold opened and never closed — exactly what a dropped `ESC[22m` leaves.
await writeTerminal(terminal, '\x1b[1mBOLD')
await writeTerminal(terminal, `${RESET_AFTER_BYTE_GAP}after`)
const line = terminal.buffer.active.getLine(0)
expect(line?.translateToString(true)).toBe('BOLDafter')
// The pre-gap run keeps its bold; only what follows the reset is grounded.
expect(line?.getCell(0)?.isBold()).not.toBe(0)
expect(line?.getCell(4)?.isBold()).toBe(0)
expect(line?.getCell(8)?.isBold()).toBe(0)
} finally {
terminal.dispose()
}
})
// CAN aborts truncated OSC/DCS/APC; bare ESC would commit a partial title or clipboard write instead.
it('discards a control string the gap truncated instead of committing it', async () => {
const terminal = new Terminal({ cols: 40, rows: 2, allowProposedApi: true })
let title = ''
terminal.onTitleChange((next) => {
title = next
})
try {
await writeTerminal(terminal, '\x1b]0;real-title-TRUNCA')
await writeTerminal(terminal, `${RESET_AFTER_BYTE_GAP}after`)
expect(title).toBe('')
// Still resynchronised: the bytes after the reset render as text.
expect(terminal.buffer.active.getLine(0)?.translateToString(true)).toBe('after')
} finally {
terminal.dispose()
}
})
})
// Use production-shaped snapshot composition so dirty and clean renderers converge, including split history/alt payloads and absolute-cursor epilogues.
describe('replay convergence with a production-composed snapshot', () => {
const strandedByTheGap: Record<string, string> = {
'bold pen': '\x1b[1m',
'G0 line drawing': '\x1b(0',
'scroll margins': '\x1b[2;3r',
'origin mode': '\x1b[2;3r\x1b[?6h',
'autowrap off': '\x1b[?7l',
'insert mode': '\x1b[4h',
'reverse wraparound': '\x1b[?45h',
'saved-cursor register': '\x1b7',
'truncated OSC': '\x1b]0;TRUNCATED',
'all of them at once':
'\x1b[1m\x1b(0\x1b)0\x1b[2;3r\x1b[?6h\x1b[?7l\x1b[?45h\x1b[4h\x1b7\x1b]0;TRUNCATED'
}
function describeFrame(terminal: Terminal): string {
return JSON.stringify({
buffer: terminal.buffer.active.type,
rows: readRows(terminal, terminal.rows),
normal: readRows(terminal, terminal.rows).length > 0 ? normalBufferRowsTrimmed(terminal) : [],
styles: visibleRowStyles(terminal),
cursor: cursorPosition(terminal)
})
}
for (const alternateScreen of [true, false]) {
const branch = alternateScreen ? 'alt-screen' : 'normal-buffer'
it(`lands on the same ${branch} frame from any stranded state`, async () => {
const model = createRendererParityTerminal({ cols: 20, rows: 5 })
try {
const enterAlt = alternateScreen ? '\x1b[?1049h' : ''
// Seed saved cursor so snapshot generation actually exercises its absolute-cursor epilogue.
await writeToTerminal(
model.terminal,
`${enterAlt}\x1b[2;5H\x1b7\x1b[33mONE\r\nplain two\r\n\x1b[1mbold three`
)
const snapshot = buildParityMainBufferSnapshot(model, 1)
expect(snapshot.alternateScreen).toBe(alternateScreen)
// Require production split-alt shape and cursor epilogue to avoid vacuous branch coverage.
expect(snapshot.scrollbackAnsi === undefined).toBe(!alternateScreen)
expect(snapshot.data).toContain('\x1b7')
const replay = async (terminal: Terminal): Promise<void> => {
for (const write of buildMainModelSnapshotReplayWrites(snapshot, {
paneOnAlternateScreen: alternateScreen
})) {
await writeTerminal(terminal, write)
}
}
const clean = createRendererParityTerminal({ cols: 20, rows: 5 })
let expected: string
try {
await writeToTerminal(clean.terminal, enterAlt)
await replay(clean.terminal)
expected = describeFrame(clean.terminal)
} finally {
clean.terminal.dispose()
}
for (const [label, stranded] of Object.entries(strandedByTheGap)) {
const dirty = createRendererParityTerminal({ cols: 20, rows: 5 })
try {
await writeToTerminal(dirty.terminal, enterAlt)
await writeToTerminal(dirty.terminal, stranded)
await replay(dirty.terminal)
expect(`${label}: ${describeFrame(dirty.terminal)}`).toBe(`${label}: ${expected}`)
} finally {
dirty.terminal.dispose()
}
}
} finally {
model.terminal.dispose()
}
})
}
})
// SerializeAddon assumes default cells and emits no charset; stranded state would silently rewrite replayed content.
describe('replay baseline grounding', () => {
const strandedState: Record<string, string> = {
'bold pen': '\x1b[1m',
'DEC line-drawing charset': '\x1b(0',
'scroll region': '\x1b[2;3r',
'origin mode': '\x1b[2;3r\x1b[?6h'
}
for (const [label, stranded] of Object.entries(strandedState)) {
it(`replays a normal-buffer snapshot unchanged despite a stranded ${label}`, async () => {
const terminal = new Terminal({ cols: 10, rows: 6, allowProposedApi: true })
try {
await writeTerminal(terminal, stranded)
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE}qqq\r\nB\r\nC\r\nD\r\nE\r\nF`)
expect(readRows(terminal, 6)).toEqual(['qqq', 'B', 'C', 'D', 'E', 'F'])
expect(terminal.buffer.active.getLine(0)?.getCell(0)?.isBold()).toBe(0)
} finally {
terminal.dispose()
}
})
}
// Exercise production split-alt snapshot output, the reported STA-4042 branch.
it('replays a split alt-screen snapshot clean when the TUI entered alt with a pen set', async () => {
const terminal = new Terminal({ cols: 24, rows: 4, allowProposedApi: true })
@@ -203,421 +34,6 @@ describe('replay baseline grounding', () => {
terminal.dispose()
}
})
// ?1049l restores saved pen/charsets/modes; grounding before the switch alone would be undone and restore bold bleed.
it('grounds after the buffer switch, not before, so ?1049l cannot restore the stale pen', async () => {
const terminal = new Terminal({ cols: 20, rows: 3, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[1m\x1b(0\x1b[?7l')
// ?1049h saves that pen, charset and wraparound into the restore register.
await writeTerminal(terminal, '\x1b[?1049hTUI FRAME')
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE_FROM_ALT}qqq restored`)
const line = terminal.buffer.active.getLine(0)
expect(line?.translateToString(true)).toBe('qqq restored')
expect(line?.getCell(0)?.isBold()).toBe(0)
} finally {
terminal.dispose()
}
})
// Poison the saved register’s pen, G-sets, GL, origin, wrap and cursor; post-switch grounding must neutralize all restored state.
it('neutralises every field ?1049l restores, even with the saved register poisoned', async () => {
const terminal = new Terminal({ cols: 20, rows: 6, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[1;31;44m') // pen: bold + fg + bg
await writeTerminal(terminal, '\x1b(0\x1b)0\x1b*0\x1b+0') // G0..G3 -> line drawing
await writeTerminal(terminal, '\x0e') // LS1: GL -> G1
await writeTerminal(terminal, '\x1b[2;5r\x1b[?6h\x1b[?7l\x1b[4h') // margins, origin, no wrap, insert
await writeTerminal(terminal, '\x1b[3;7H') // non-home cursor
await writeTerminal(terminal, '\x1b[?1049hTUI FRAME') // saveCursor() captures all of it
// 24 columns of `q` into a 20-column grid: only autowrap on, GL=G0 and
// G0=ASCII produce this, and only a homed cursor starts it on row 0.
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE_FROM_ALT}${'q'.repeat(24)}`)
expect(terminal.buffer.active.type).toBe('normal')
expect(readRows(terminal, 2)).toEqual(['q'.repeat(20), 'qqqq'])
const cell = terminal.buffer.active.getLine(0)?.getCell(0)
expect(cell?.isBold()).toBe(0)
expect(cell?.isFgDefault()).toBe(true)
expect(cell?.isBgDefault()).toBe(true)
} finally {
terminal.dispose()
}
})
// Replay must adopt model buffer state or missed alt exit leaves Kitty flags leaking into an unnegotiated shell.
it('converges on the model kitty keyboard state when the gap ate the alt-screen exit', async () => {
const options = {
cols: 20,
rows: 4,
allowProposedApi: true,
vtExtensions: { kittyKeyboard: true }
}
const readKittyFlags = (term: Terminal): unknown => {
const flags = (term as unknown as { _core: { coreService: { kittyKeyboard: unknown } } })
._core.coreService.kittyKeyboard
// Without this the assertion passes vacuously if xterm renames the field.
expect(flags).toBeDefined()
return flags
}
// The model ingested every byte: agent entered alt, negotiated kitty, exited.
const model = new Terminal(options)
// The renderer missed the exit and is still on alt with the agent's flags.
const renderer = new Terminal(options)
try {
await writeTerminal(model, '\x1b[?1049h\x1b[>1u')
await writeTerminal(model, '\x1b[?1049l')
await writeTerminal(renderer, '\x1b[?1049h\x1b[>1u')
for (const write of buildMainModelSnapshotReplayWrites(
{ data: 'shell prompt $' },
{ paneOnAlternateScreen: true }
)) {
await writeTerminal(renderer, write)
}
expect(renderer.buffer.active.type).toBe(model.buffer.active.type)
expect(readKittyFlags(renderer)).toEqual(readKittyFlags(model))
} finally {
model.dispose()
renderer.dispose()
}
})
// Ground before ?1049h too: otherwise it banks stale pen/charsets that only reappear when the TUI later exits.
it('grounds before the switch too, so the alt-exit later cannot restore the gap state', async () => {
const terminal = new Terminal({ cols: 20, rows: 3, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[1m\x1b(0\x1b[?7l')
await writeTerminal(terminal, `${ALT_BUFFER_PROLOGUE}alt frame`)
// The agent exits the alt screen some time after the repaint.
await writeTerminal(terminal, '\x1b[?1049l')
await writeTerminal(terminal, 'qqq shell prompt')
const line = terminal.buffer.active.getLine(0)
expect(line?.translateToString(true)).toBe('qqq shell prompt')
expect(line?.getCell(0)?.isBold()).toBe(0)
} finally {
terminal.dispose()
}
})
// Avoid same-buffer ?1049: xterm still swaps Kitty registers even without a buffer swap, confiscating a live agent’s flags.
it('leaves kitty flags alone when the pane is already on the target buffer', async () => {
const options = {
cols: 20,
rows: 3,
allowProposedApi: true,
vtExtensions: { kittyKeyboard: true }
}
const readKittyFlags = (term: Terminal): unknown => {
const flags = (term as unknown as { _core: { coreService: { kittyKeyboard: unknown } } })
._core.coreService.kittyKeyboard
// Without this the assertion passes vacuously if xterm renames the field.
expect(flags).toBeDefined()
return flags
}
const model = new Terminal(options)
const renderer = new Terminal(options)
try {
await writeTerminal(model, '\x1b[>1u')
await writeTerminal(renderer, '\x1b[>1u')
const writes = buildMainModelSnapshotReplayWrites(
{ data: 'restored' },
{ paneOnAlternateScreen: false }
)
for (const write of writes) {
await writeTerminal(renderer, write)
}
expect(writes[0]).not.toContain('\x1b[?1049')
expect(readKittyFlags(renderer)).toEqual(readKittyFlags(model))
} finally {
model.dispose()
renderer.dispose()
}
})
// Snapshot only re-emits enabled reverse wrap; explicitly clear stranded on state before later backspace crosses a soft wrap.
it('leaves reverse wraparound off so a later backspace cannot chew the row above', async () => {
const terminal = new Terminal({ cols: 8, rows: 3, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[?45h')
// 12 columns into 8 makes row 1 a SOFT wrap of row 0 — the only kind
// reverse wraparound reverses.
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE}AAAAAAAABBBB`)
await writeTerminal(terminal, '\b\b\b\b\bX')
expect(readRows(terminal, 2)).toEqual(['AAAAAAAA', 'XBBB'])
} finally {
terminal.dispose()
}
})
// Production alt payloads contain their own ?1049h and can bank Kitty flags; this checks only that the prologue adds no unnecessary switch.
it('adds no buffer switch of its own when the pane is already on the alt screen', async () => {
const options = {
cols: 20,
rows: 3,
allowProposedApi: true,
vtExtensions: { kittyKeyboard: true }
}
const readKittyFlags = (term: Terminal): unknown => {
const flags = (term as unknown as { _core: { coreService: { kittyKeyboard: unknown } } })
._core.coreService.kittyKeyboard
// Without this the assertion passes vacuously if xterm renames the field.
expect(flags).toBeDefined()
return flags
}
const renderer = new Terminal(options)
try {
await writeTerminal(renderer, '\x1b[?1049h\x1b[>1u')
const before = JSON.stringify(readKittyFlags(renderer))
const writes = buildMainModelSnapshotReplayWrites(
{ data: 'alt-frame', alternateScreen: true },
{ paneOnAlternateScreen: true }
)
expect(writes[0]).not.toContain('\x1b[?1049')
for (const write of writes) {
await writeTerminal(renderer, write)
}
// Nothing in the prologue moved them; only a payload `?1049h` could.
expect(JSON.stringify(readKittyFlags(renderer))).toBe(before)
} finally {
renderer.dispose()
}
})
// Ground outgoing normal-buffer margins too; buffer-local stale regions otherwise return when the TUI exits alt.
it('grounds the source buffer margins when switching to the alt screen', async () => {
const terminal = new Terminal({ cols: 20, rows: 6, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[2;3r')
for (const write of buildMainModelSnapshotReplayWrites(
{ data: 'alt-frame', alternateScreen: true },
{ paneOnAlternateScreen: false }
)) {
await writeTerminal(terminal, write)
}
await writeTerminal(terminal, '\x1b[?1049l')
await writeTerminal(terminal, 'AAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF')
expect(readRows(terminal, 6)).toEqual(['AAAA', 'BBBB', 'CCCC', 'DDDD', 'EEEE', 'FFFF'])
} finally {
terminal.dispose()
}
})
// Preserve G1–G3: SO/SI terminfo designates G1 once at initialization and snapshot replay never redeclares it, so resetting breaks live box drawing.
it('leaves an app-designated G1 intact so its later shift-out still draws boxes', async () => {
const terminal = new Terminal({ cols: 20, rows: 3, allowProposedApi: true })
try {
// enacs: G0 = ASCII, G1 = DEC line drawing. Runs once, at init.
await writeTerminal(terminal, '\x1b(B\x1b)0')
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE}restored`)
// smacs / box / rmacs, the way the app draws for the rest of the session.
await writeTerminal(terminal, '\r\n\x0elqqqk\x0f')
expect(terminal.buffer.active.getLine(1)?.translateToString(true)).toBe('┌───┐')
} finally {
terminal.dispose()
}
})
// Trailing DECSC overwrites a stale saved cursor register before a live TUI’s later ESC 8 can restore gap state.
it('grounds the saved-cursor register so a later ESC 8 cannot restore the stale pen', async () => {
const terminal = new Terminal({ cols: 20, rows: 3, allowProposedApi: true })
try {
// The gap strands a DECSC taken while bold + line-drawing were set.
await writeTerminal(terminal, '\x1b[1m\x1b(0\x1b7')
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE}restored`)
// The live TUI restores its cursor, then draws.
await writeTerminal(terminal, '\x1b8qqq')
const line = terminal.buffer.active.getLine(0)
expect(line?.translateToString(true)).toBe('qqqtored')
expect(line?.getCell(0)?.isBold()).toBe(0)
} finally {
terminal.dispose()
}
})
// Serialized exact-width rows need autowrap; stranded-off mode overwrites the margin and loses history.
it('replays a row wider than the grid instead of dropping it at the margin', async () => {
const terminal = new Terminal({ cols: 10, rows: 4, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[?7l')
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE}ABCDEFGHIJKLMNO`)
expect(readRows(terminal, 2)).toEqual(['ABCDEFGHIJ', 'KLMNO'])
} finally {
terminal.dispose()
}
})
// Origin mode can look correct during replay with reset margins yet break later TUI cursor addressing; explicitly clear it.
it('leaves origin mode off so later cursor addressing stays absolute', async () => {
const terminal = new Terminal({ cols: 10, rows: 6, allowProposedApi: true })
try {
// Already-alt replay has no buffer restore to repair state incidentally; only baseline reset can do it.
await writeTerminal(terminal, '\x1b[?1049h')
await writeTerminal(terminal, '\x1b[2;3r\x1b[?6h')
await writeTerminal(terminal, `${ALT_BUFFER_PROLOGUE_FROM_ALT}restored`)
// The live TUI re-establishes its own region and homes the cursor.
await writeTerminal(terminal, '\x1b[4;6r\x1b[1;1HTOP')
expect(terminal.buffer.active.getLine(0)?.translateToString(true)).toBe('TOPtored')
} finally {
terminal.dispose()
}
})
// Cleared frames hide stranded insert mode; later in-place repaint exposes shifts unless explicitly grounded.
it('leaves insert mode off so later repaints overwrite rather than shift', async () => {
const terminal = new Terminal({ cols: 10, rows: 4, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[4h')
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE}OLDTEXT`)
// A live in-place repaint after the replay, exactly as a TUI would send it.
await writeTerminal(terminal, '\x1b[1;1HNEW')
expect(readRows(terminal, 1)).toEqual(['NEWTEXT'])
} finally {
terminal.dispose()
}
})
// Cover already-alt separately: no normal-buffer restore incidentally clears saved origin/autowrap state.
for (const [label, stranded, replayed, expected] of [
['autowrap off', '\x1b[?7l', 'ABCDEFGHIJKLMNO', ['ABCDEFGHIJ', 'KLMNO']],
['origin mode', '\x1b[2;3r\x1b[?6h', 'A\r\nB\r\nC', ['A', 'B', 'C']],
['DEC line-drawing charset', '\x1b(0', 'qqq', ['qqq', '']]
] as const) {
it(`grounds a stranded ${label} on the alt-screen branch`, async () => {
const terminal = new Terminal({ cols: 10, rows: 4, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[?1049h')
await writeTerminal(terminal, stranded)
await writeTerminal(terminal, `${ALT_BUFFER_PROLOGUE_FROM_ALT}${replayed}`)
expect(readRows(terminal, expected.length)).toEqual([...expected])
} finally {
terminal.dispose()
}
})
}
// Already-alt ?1049h keeps buffer-local margins; explicit reset must clear them.
it('grounds the alt buffer margins even when already on the alt screen', async () => {
const terminal = new Terminal({ cols: 10, rows: 6, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[?1049h')
await writeTerminal(terminal, '\x1b[2;3r')
await writeTerminal(terminal, `${ALT_BUFFER_PROLOGUE_FROM_ALT}A\r\nB\r\nC\r\nD\r\nE\r\nF`)
expect(readRows(terminal, 6)).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])
} finally {
terminal.dispose()
}
})
// A missed TUI exit leaves renderer on alt; restore onto normal so history stays scrollable and survives later switches.
it('returns to the normal buffer before replaying a normal-buffer snapshot', async () => {
const terminal = new Terminal({ cols: 20, rows: 3, allowProposedApi: true })
try {
await writeTerminal(terminal, '\x1b[?1049hSTALE TUI FRAME')
await writeTerminal(terminal, `${NORMAL_BUFFER_PROLOGUE_FROM_ALT}shell prompt $`)
expect(terminal.buffer.active.type).toBe('normal')
expect(terminal.buffer.normal.getLine(0)?.translateToString(true)).toBe('shell prompt $')
} finally {
terminal.dispose()
}
})
})
describe('hasPositiveTerminalDimensions', () => {
it('accepts only finite positive numeric pairs', () => {
expect(hasPositiveTerminalDimensions(80, 24)).toBe(true)
expect(hasPositiveTerminalDimensions(1, 1)).toBe(true)
})
// Infinity passes a simple > 0 check; malformed dimensions must never reach terminal.resize.
it('rejects non-finite, non-positive, and non-numeric values', () => {
expect(hasPositiveTerminalDimensions(Infinity, 24)).toBe(false)
expect(hasPositiveTerminalDimensions(80, Infinity)).toBe(false)
expect(hasPositiveTerminalDimensions(Number.NaN, 24)).toBe(false)
expect(hasPositiveTerminalDimensions(0, 24)).toBe(false)
expect(hasPositiveTerminalDimensions(80, -1)).toBe(false)
expect(hasPositiveTerminalDimensions(undefined, 24)).toBe(false)
expect(hasPositiveTerminalDimensions('80', 24)).toBe(false)
expect(hasPositiveTerminalDimensions(null, null)).toBe(false)
})
})
describe('resolvePositiveTerminalDimensions', () => {
it('returns the numeric pair only when valid', () => {
expect(resolvePositiveTerminalDimensions(80, 24)).toEqual({ cols: 80, rows: 24 })
expect(resolvePositiveTerminalDimensions(Infinity, 24)).toBeNull()
expect(resolvePositiveTerminalDimensions(undefined, undefined)).toBeNull()
})
})
describe('buildMainModelSnapshotReplayWrites', () => {
it('clears normal buffer + scrollback before a normal-buffer snapshot', () => {
expect(
buildMainModelSnapshotReplayWrites({ data: 'shell-output' }, { paneOnAlternateScreen: false })
).toEqual([NORMAL_BUFFER_PROLOGUE, 'shell-output'])
})
// Main strips alt entry from split payloads; the restorer must rebuild normal history then return to alt before painting the frame.
it('rebuilds normal buffer then paints a clean alt frame for alt-screen snapshots', () => {
expect(
buildMainModelSnapshotReplayWrites(
{ data: 'alt-frame', alternateScreen: true, scrollbackAnsi: 'normal-history' },
{ paneOnAlternateScreen: false }
)
).toEqual([
NORMAL_BUFFER_PROLOGUE,
'normal-history',
buildSnapshotReplayPrologue({ targetAlternateScreen: true, paneOnAlternateScreen: false }),
'alt-frame'
])
})
it('enters a cleared alt screen when no split scrollback is available', () => {
expect(
buildMainModelSnapshotReplayWrites(
{ data: 'alt-frame', alternateScreen: true },
{ paneOnAlternateScreen: false }
)
).toEqual([ALT_BUFFER_PROLOGUE, 'alt-frame'])
})
})
describe('shouldSkipAltFrameForWidthMismatch', () => {
it('skips only when the snapshot is WIDER than the target', () => {
expect(shouldSkipAltFrameForWidthMismatch(135, 128)).toBe(true)
expect(shouldSkipAltFrameForWidthMismatch(129, 128)).toBe(true)
expect(shouldSkipAltFrameForWidthMismatch(128, 128)).toBe(false)
expect(shouldSkipAltFrameForWidthMismatch(100, 120)).toBe(false)
})
it('never skips when a width is missing or nonsensical', () => {
// Why: an unknown width must not cost the user their restored frame.
expect(shouldSkipAltFrameForWidthMismatch(undefined, 128)).toBe(false)
expect(shouldSkipAltFrameForWidthMismatch(135, undefined)).toBe(false)
expect(shouldSkipAltFrameForWidthMismatch(0, 128)).toBe(false)
expect(shouldSkipAltFrameForWidthMismatch(Number.NaN, 128)).toBe(false)
expect(shouldSkipAltFrameForWidthMismatch(Number.POSITIVE_INFINITY, 128)).toBe(false)
})
})
describe('buildMainModelSnapshotReplayWrites alt-frame skip', () => {
@@ -675,91 +91,4 @@ describe('buildMainModelSnapshotReplayWrites alt-frame skip', () => {
terminal.dispose()
}
})
it('drops only the frame paint, keeping scrollback and the alt-buffer choreography', () => {
expect(
buildMainModelSnapshotReplayWrites(
{
data: 'mode-prefixalt-frame',
frameRestoreAnsi: 'complete-live-state',
alternateScreen: true,
scrollbackAnsi: 'normal-history'
},
{ skipAltFrame: true, paneOnAlternateScreen: false }
)
).toEqual([
NORMAL_BUFFER_PROLOGUE,
'normal-history',
buildSnapshotReplayPrologue({ targetAlternateScreen: true, paneOnAlternateScreen: false }),
'complete-live-state'
])
})
it('still enters a cleared alt screen when skipping without split scrollback', () => {
// Still clear before SIGWINCH so application repaint cannot inherit the pre-park frame.
expect(
buildMainModelSnapshotReplayWrites(
{
data: 'mode-prefixalt-frame',
frameRestoreAnsi: 'complete-live-state',
alternateScreen: true
},
{ skipAltFrame: true, paneOnAlternateScreen: false }
)
).toEqual([ALT_BUFFER_PROLOGUE, 'complete-live-state'])
})
it('keeps composed data when an older producer omits the mode boundary', () => {
expect(
buildMainModelSnapshotReplayWrites(
{ data: 'legacy-modes-and-frame', alternateScreen: true },
{ skipAltFrame: true, paneOnAlternateScreen: false }
)
).toEqual([ALT_BUFFER_PROLOGUE, 'legacy-modes-and-frame'])
})
it('never drops a normal-buffer snapshot, whose rows reflow correctly', () => {
expect(
buildMainModelSnapshotReplayWrites(
{ data: 'shell-output' },
{ skipAltFrame: true, paneOnAlternateScreen: false }
)
).toEqual([NORMAL_BUFFER_PROLOGUE, 'shell-output'])
})
// Unknown gap state must be grounded before any replay branch paints content (STA-4042).
it('clears the SGR pen before any replayed content in every branch', () => {
// Use genuine buffer transitions so baseline ordering around switch/restore is exercised.
const branches = [
buildMainModelSnapshotReplayWrites(
{ data: 'normal-buffer' },
{ paneOnAlternateScreen: true }
),
buildMainModelSnapshotReplayWrites(
{ data: 'alt-frame', alternateScreen: true, scrollbackAnsi: 'scrollback' },
{ paneOnAlternateScreen: true }
),
buildMainModelSnapshotReplayWrites(
{ data: 'alt-frame', alternateScreen: true },
{ paneOnAlternateScreen: false }
)
]
for (const writes of branches) {
// Leading CAN aborts a truncated control string instead of committing it on the next ESC.
expect(writes[0].startsWith('\x18')).toBe(true)
// Assert literal protocol bytes so a broken imported constant cannot satisfy its own test.
const prologue = writes[0]
expect(prologue).toContain('\x1b[0m') // SGR
expect(prologue).toContain('\x0f\x1b(B') // GL -> G0, G0 -> ASCII
expect(prologue).toContain('\x1b[r') // margins
expect(prologue.endsWith('\x1b7')).toBe(true) // saved-cursor floor, last
// Ground before switching to save clean state and after switching to override restored stale state.
const switchAt = prologue.indexOf('\x1b[?1049')
expect(switchAt).toBeGreaterThanOrEqual(0)
expect(prologue.indexOf('\x1b[0m')).toBeLessThan(switchAt)
expect(prologue.lastIndexOf('\x1b[0m')).toBeGreaterThan(switchAt)
// Nothing may be replayed ahead of the first prologue.
expect(writes.indexOf('scrollback')).not.toBe(0)
}
})
})