test: remove low-value terminal transport and input cases

This commit is contained in:
OrcaWin
2026-11-09 16:10:56 -08:00
parent eae521a4cb
commit bae2db6d30
15 changed files with 26 additions and 2655 deletions
@@ -19,7 +19,6 @@ on:
# Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts;
# without these a rename lands green and only breaks the next nightly.
- 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts'
- 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts'
- 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts'
- 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts'
- 'src/main/runtime/rpc/methods/projects/repo.test.ts'
+1
View File
@@ -282,6 +282,7 @@
1 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts
1 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts
1 src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts
1 src/main/ipc/floating-workspace-directory.ts
1 src/main/ipc/macos-keyboard-layout-snapshot.ts
1 src/main/ipc/notification-authorization-status.ts
1 src/main/ipc/pty/spawn-pane-env.ts
File diff suppressed because one or more lines are too long
@@ -5897,7 +5897,6 @@
"src/renderer/src/components/terminal-pane/pty-connection/spawn/main-pane-start-wait.test.ts": 76,
"src/renderer/src/components/terminal-pane/pty-connection/serialization/pane-serializer-register.test.ts": 123,
"src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-kitty-file-reader.test.ts": 297,
"src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts": 1882,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/snapshot-covered-terminal-queries.test.ts": 150,
"src/renderer/src/components/terminal-pane/pty-connection/output/terminal-input-echo-delay.test.ts": 132,
"src/renderer/src/components/terminal-pane/pty-connection/host-ownership/unserved-ssh-pane-bridge.test.ts": 70,
@@ -5992,7 +5991,6 @@
"src/renderer/src/components/terminal-pane/emulation/terminal-capability-replies.test.ts": 131,
"src/renderer/src/components/terminal-pane/clipboard/terminal-clipboard-paste.test.ts": 76,
"src/renderer/src/components/terminal-pane/parking/retention/terminal-cold-park-timer-rearm.test.tsx": 701,
"src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.test.ts": 111,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts": 638,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-image-path.test.ts": 61,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts": 800,
-1
View File
@@ -6,7 +6,6 @@ import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-
const contracts = [
'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts',
'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts',
'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts',
'src/main/runtime/rpc/methods/projects/repo.test.ts',
@@ -1,546 +0,0 @@
import { bindBuildColdRestoreAgentResumeStartup } from './cold-restore-resume-startup'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types'
import type {
AgentLaunchConfigRegistryEntry,
AgentLaunchConfigRegistrationMetadata
} from '@/store/slices/agent-status/agent-status-contract'
import type { ColdRestoreAgentResumeStartup } from './fresh-spawn-types'
import type { ConnectPanePtySession } from '../connect-pane-pty-session'
import { bindPaneSerializerReadiness } from '../serialization/pane-serializer-readiness'
import { bindStartupDraftPaste } from './startup-draft-paste'
import { bindSessionRestoredBannerAdmission } from '../notifications/session-restored-banner-admission'
import { bindDeferredColdRestoreAndSnapshot } from '../deferred-cold-restore-and-snapshot'
import { installSleepingRecordAccess } from './sleeping-record-access'
import { createTestStore } from '@/store/testing/app-store-test-fixture'
import { makeTab } from '@/store/terminals/terminal-tab.test-fixture'
import { createStoreSessionMockApi } from '@/store/testing/app-store-session-api.test-fixture'
import {
applyTerminalLaunchResult,
captureTerminalLaunchContext
} from './terminal-launch-result-policy'
const fixture = vi.hoisted(() => ({
state: {},
setState: vi.fn(),
paste: vi.fn(),
parsed: vi.fn(async () => {})
}))
vi.mock('@/store/index', () => ({
useAppStore: { getState: () => fixture.state, setState: fixture.setState }
}))
vi.mock('@/lib/pane-manager/pane-terminal-output-scheduler', () => ({
waitForTerminalOutputParsed: fixture.parsed
}))
vi.mock('../../input/paste/terminal-startup-command-paste', () => ({
executeTerminalStartupCommandPaste: fixture.paste
}))
vi.mock('../../input/paste/terminal-paste-runtime', () => ({
resolveTerminalPasteRuntime: () => ({})
}))
vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' }))
vi.mock('../agent-identity/command-inferred-pane-agent', () => ({
installCommandInferredPaneAgent: vi.fn()
}))
afterEach(() => {
vi.useRealTimers()
vi.clearAllMocks()
fixture.setState.mockReset()
vi.unstubAllGlobals()
})
describe('a refused saved startup and its delayed paste', () => {
it.each(['original', 'same-C', 'different-D', 'unverifiable'] as const)(
'cancels only its captured source and keeps newer work (%s)',
async (kind) => {
vi.useFakeTimers()
const record = {
paneKey: 'tab:leaf',
tabId: 'tab',
worktreeId: 'wt',
agent: 'codex' as const,
providerSession: { key: 'session_id' as const, id: 'C' },
connectionId: null,
state: 'done' as const,
prompt: '',
capturedAt: 10,
updatedAt: 10,
origin: 'worktree-sleep' as const
}
const source = { cancelled: false, record }
const startup = {
command: 'codex resume C',
launchAgent: 'codex' as const,
resumeProviderSession: record.providerSession,
resumeOrigin: 'saved' as const,
resumeSource: source
}
const records = kind === 'unverifiable' ? {} : { [record.paneKey]: record }
const clear = vi.fn()
const remember = vi.fn()
fixture.state = {
sleepingAgentSessionsByPaneKey: records,
automaticAgentResumeClaimsByTabId: {},
agentLaunchConfigByPaneKey: {},
pendingStartupByTabId: {},
tabsByWorktree: {},
registerAgentLaunchConfig: vi.fn(),
clearAgentLaunchConfig: vi.fn(),
consumeTabStartupCommand: vi.fn(),
clearSleepingAgentSession: clear,
rememberSleepingAgentSession: remember
}
const sendInput = vi.fn(() => true)
const transport = { getPtyId: () => 'shell', sendInput }
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installers' accessed session members are supplied here.
const session = {
pane: { id: 1, leafId: 'leaf', terminal: {} },
manager: {},
transport,
deps: {
worktreeId: 'wt',
tabId: 'tab',
paneTransportsRef: { current: new Map([[1, transport]]) }
},
cacheKey: record.paneKey,
paneStartup: startup,
startupInjectTimer: null,
disposed: false,
transportStreamGeneration: 1,
shouldDeliverStartupViaTerminalPaste: true,
releaseUnattemptedStartupDraftPasteDelivery: vi.fn()
} as unknown as ConnectPanePtySession
installSleepingRecordAccess(session)
bindPaneSerializerReadiness(session)
bindStartupDraftPaste(session)
bindSessionRestoredBannerAdmission(session)
bindDeferredColdRestoreAndSnapshot(session)
let finishPaste: (() => void) | undefined
fixture.paste.mockImplementation(
() =>
new Promise((resolve) => {
finishPaste = () => resolve({ status: 'pasted' })
})
)
session.schedulePendingStartupCommandDelivery()
await vi.advanceTimersByTimeAsync(50)
expect(fixture.paste).toHaveBeenCalledOnce()
const newer = { command: kind === 'different-D' ? 'codex resume D' : 'codex resume C' }
session.pendingStartupCommand = newer
if (kind === 'same-C' || kind === 'different-D') {
Object.assign(records, {
[record.paneKey]: {
...record,
providerSession: { ...record.providerSession, id: kind === 'same-C' ? 'C' : 'D' },
updatedAt: 20
}
})
}
session.cancelSavedResumeStartup(startup, {
id: 'shell',
agentResumeRefused: kind === 'unverifiable' ? 'unverifiable' : 'chat-home'
})
expect(source.cancelled).toBe(true)
expect(session.pendingStartupCommand).toBe(newer)
finishPaste?.()
await vi.advanceTimersByTimeAsync(0)
expect(sendInput).not.toHaveBeenCalled()
expect(session.pendingStartupCommand).toBe(newer)
if (kind === 'unverifiable') {
expect(remember).toHaveBeenCalledWith(record)
} else if (kind === 'original') {
expect(clear).toHaveBeenCalledWith(record.paneKey)
} else {
expect(clear).not.toHaveBeenCalled()
}
}
)
})
it.each(['refused', 'same-C', 'different-D'] as const)(
'clears the real generated cold/wake registration and conditional tab identity only while owned (%s)',
(kind) => {
const cacheKey = 'tab:leaf'
const source = { cancelled: false }
const startup: ColdRestoreAgentResumeStartup = {
agent: 'codex',
command: 'codex resume C',
launchToken: 'saved-token',
launchConfig: { agentCommand: 'codex', agentArgs: 'resume C', agentEnv: {} },
resumeProviderSession: { key: 'session_id', id: 'C' },
resumeOrigin: 'saved',
resumeSource: source,
useLiveEntry: false,
hasSleepingRecord: false,
sleepingRecordEntry: null
}
const registry: Record<string, AgentLaunchConfigRegistryEntry> = {}
const pending: Record<string, object> = {}
const tab = { id: 'tab', title: 'Codex', launchAgent: 'codex', generation: 1 }
const clearTabLaunchAgent = vi.fn()
const registerAgentLaunchConfig = (
paneKey: string,
launchConfig: AgentLaunchConfigRegistryEntry['launchConfig'],
identity: AgentLaunchConfigRegistrationMetadata
) => {
registry[paneKey] = { launchConfig, identity, registeredAt: 1 }
}
fixture.state = {
agentLaunchConfigByPaneKey: registry,
pendingStartupByTabId: pending,
automaticAgentResumeClaimsByTabId: {},
sleepingAgentSessionsByPaneKey: {},
tabsByWorktree: { wt: [tab] },
registerAgentLaunchConfig,
clearAgentLaunchConfig: (key: string) => {
delete registry[key]
},
consumeTabStartupCommand: vi.fn(),
clearTabLaunchAgent
}
const updateTabTitle = vi.fn()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real installers/cancellation access only the supplied session members in this contract.
const session = {
cacheKey,
paneStartup: null,
pane: { id: 1, leafId: 'leaf' },
manager: { getActivePane: () => ({ id: 1 }) },
deps: { tabId: 'tab', worktreeId: 'wt', setRuntimePaneTitle: vi.fn(), updateTabTitle },
tabGeneration: 1,
startupInjectTimer: null,
transport: {},
shouldDeliverStartupViaTerminalPaste: false
} as unknown as ConnectPanePtySession
installSleepingRecordAccess(session)
bindDeferredColdRestoreAndSnapshot(session)
expect(session.applyColdRestoreAgentResumeStartup(startup)).toBe(true)
const saved = registry[cacheKey]
expect(saved?.identity.launchToken).toBe('saved-token')
if (kind !== 'refused') {
const command = kind === 'same-C' ? 'resume C' : 'resume D'
registerAgentLaunchConfig(
cacheKey,
{ ...startup.launchConfig, agentArgs: command },
{
agentType: 'codex',
launchToken: 'explicit-token'
}
)
pending.tab = { command }
}
const current = registry[cacheKey]
const newer = pending.tab
session.cancelSavedResumeStartup(startup, { id: 'shell', agentResumeRefused: 'chat-home' })
session.registerEffectiveLaunchConfig(undefined, {})
expect(source.cancelled).toBe(true)
expect(session.paneStartup).toBeNull()
if (kind === 'refused') {
expect(registry[cacheKey]).toBeUndefined()
expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab')
expect(updateTabTitle).toHaveBeenCalledWith('tab', 'Terminal')
} else {
expect(registry[cacheKey]).toBe(current)
expect(pending.tab).toBe(newer)
expect(clearTabLaunchAgent).not.toHaveBeenCalled()
expect(updateTabTitle).not.toHaveBeenCalled()
}
}
)
it.each([10, 100])('counts real saved-startup cancellation map work at %i entries', (size) => {
vi.stubGlobal('window', undefined)
createStoreSessionMockApi()
for (const newer of [true, false]) {
const store = createTestStore()
fixture.state = store.getState()
fixture.setState.mockImplementation(store.setState)
let notifications = 0
const unsubscribe = store.subscribe((state) => {
fixture.state = state
notifications += 1
})
const source = { cancelled: false }
const startup = {
command: 'codex resume C',
launchAgent: 'codex' as const,
launchToken: 'saved-token',
launchConfig: { agentCommand: 'codex', agentArgs: 'resume C', agentEnv: {} },
resumeProviderSession: { key: 'session_id' as const, id: 'C' },
resumeOrigin: 'saved' as const,
resumeSource: source
}
const claim = {
worktreeId: 'wt',
launchAgent: 'codex' as const,
providerSession: startup.resumeProviderSession
}
const status: AgentStatusEntry = {
paneKey: 'tab:leaf',
state: 'done',
prompt: '',
updatedAt: 1,
stateStartedAt: 1,
stateHistory: []
}
store.setState({ automaticAgentResumeClaimsByTabId: { tab: claim } })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the actual installers/result policy access only these supplied session members.
const session = {
cacheKey: 'tab:leaf',
pane: { id: 1, leafId: 'leaf' },
paneStartup: startup,
pendingStartupCommand: startup,
startupInjectTimer: null,
deps: { tabId: 'tab', worktreeId: 'wt' },
showSessionRestoredBanner: vi.fn()
} as unknown as ConnectPanePtySession
installSleepingRecordAccess(session)
const registration = store.getState().agentLaunchConfigByPaneKey['tab:leaf']!
session.savedStartupStatus = { source, entry: status }
let enumerated = 0
let copied = 0
const counted = <T extends object>(map: T): T =>
new Proxy(map, {
ownKeys(target) {
const keys = Reflect.ownKeys(target)
enumerated += keys.length
return keys
},
getOwnPropertyDescriptor(target, key) {
const descriptor = Object.getOwnPropertyDescriptor(target, key)
if (descriptor?.enumerable) {
copied += 1
}
return descriptor
}
})
const population = <T>(target: string, value: T) =>
Object.fromEntries(
Array.from({ length: size }, (_, index) => [
index === size - 1 ? target : `other-${index}`,
value
])
)
let tabVisits = 0
const tabs = Array.from({ length: size }, (_, index) =>
makeTab({
id: index === size - 1 ? 'tab' : `other-${index}`,
worktreeId: 'wt'
})
)
// Keep the real tab objects; count the actual find predicate's identity reads.
tabs.forEach((tab, index) =>
Object.defineProperty(tab, 'id', {
get: () => {
tabVisits += 1
return index === size - 1 ? 'tab' : `other-${index}`
}
})
)
store.setState({
pendingStartupByTabId: counted(population('tab', startup)),
automaticAgentResumeClaimsByTabId: counted(population('tab', claim)),
agentLaunchConfigByPaneKey: counted(population('tab:leaf', registration)),
agentStatusByPaneKey: counted(population('tab:leaf', status)),
tabsByWorktree: { wt: tabs }
})
const accepted = vi.fn()
const disposeAccepted = store.getState().subscribeAgentStatusChanges(accepted)
const context = captureTerminalLaunchContext(session, startup)
const successor = { ...startup, resumeSource: { cancelled: false } }
const successorRegistration = { ...registration, registeredAt: 2 }
if (newer) {
session.paneStartup = successor
session.pendingStartupCommand = successor
store.setState({
pendingStartupByTabId: counted(population('tab', successor)),
automaticAgentResumeClaimsByTabId: counted(population('tab', { ...claim })),
agentLaunchConfigByPaneKey: counted(population('tab:leaf', successorRegistration)),
agentStatusByPaneKey: counted(population('tab:leaf', { ...status, updatedAt: 2 }))
})
}
enumerated = 0
copied = 0
notifications = 0
tabVisits = 0
const result = {
agentResumeRefused: 'chat-home' as const,
savedResumeDecision: {
agent: 'codex',
providerSession: startup.resumeProviderSession,
verdict: 'chat-home' as const
}
}
try {
expect(applyTerminalLaunchResult(session, result, context, 'creator')).toBe(true)
expect(source.cancelled).toBe(true)
if (newer) {
expect(accepted).not.toHaveBeenCalled()
} else {
expect(accepted).toHaveBeenCalledExactlyOnceWith([
{ paneKey: 'tab:leaf', previous: status, current: undefined }
])
}
// Four independent whole-map spreads, once each; this is work per result, not a latency bound.
expect([enumerated, copied, notifications, tabVisits]).toEqual(
newer ? [0, 0, 0, 0] : [4 * size, 4 * size, 4, size]
)
const current = store.getState()
if (newer) {
expect(current.pendingStartupByTabId.tab).toBe(successor)
expect(current.agentLaunchConfigByPaneKey['tab:leaf']).toBe(successorRegistration)
expect(current.automaticAgentResumeClaimsByTabId.tab).not.toBe(claim)
expect(current.agentStatusByPaneKey['tab:leaf']?.updatedAt).toBe(2)
expect(session.paneStartup).toBe(successor)
expect(successor.resumeSource.cancelled).toBe(false)
} else {
expect(current.pendingStartupByTabId.tab).toBeUndefined()
expect(current.agentLaunchConfigByPaneKey['tab:leaf']).toBeUndefined()
expect(current.automaticAgentResumeClaimsByTabId.tab).toBeUndefined()
expect(current.agentStatusByPaneKey['tab:leaf']).toBeUndefined()
expect(current.pendingStartupByTabId['other-0']).toBe(startup)
expect(session.pendingStartupCommand).toBeNull()
}
enumerated = 0
copied = 0
notifications = 0
tabVisits = 0
applyTerminalLaunchResult(session, result, context, 'creator')
expect([enumerated, copied, notifications, tabVisits]).toEqual([0, 0, 0, 0])
} finally {
disposeAccepted()
unsubscribe()
}
}
})
it.each(['canonical', 'legacy', 'live'] as const)(
'does not recreate a confirmed-exited cold-restore source (%s)',
(kind) => {
const store = createTestStore()
fixture.state = store.getState()
const unsubscribe = store.subscribe((state) => {
fixture.state = state
})
const paneKey = 'tab:leaf'
const record = {
paneKey: kind === 'legacy' ? 'tab:1' : paneKey,
tabId: 'tab',
worktreeId: 'wt',
agent: 'codex' as const,
providerSession: { key: 'session_id' as const, id: 'C' },
prompt: '',
state: 'done' as const,
capturedAt: 1,
updatedAt: 1
}
store.getState().rememberSleepingAgentSession(record)
const startup: ColdRestoreAgentResumeStartup = {
agent: 'codex',
command: 'codex resume C',
launchToken: 'token',
launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} },
resumeProviderSession: record.providerSession,
resumeOrigin: 'saved',
resumeSource: {
cancelled: false,
record,
expectedStatus: { paneKey, receivedAt: 1, stateStartedAt: 1 }
},
useLiveEntry: kind === 'live',
hasSleepingRecord: kind !== 'live',
sleepingRecordEntry: kind === 'live' ? null : { paneKey: record.paneKey, record }
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only binding and retention run; all their accessed members are supplied.
const session = {
cacheKey: paneKey,
deps: { tabId: 'tab', worktreeId: 'wt' },
pane: { id: 1, leafId: 'leaf' },
manager: {},
paneStartup: null
} as unknown as ConnectPanePtySession
installSleepingRecordAccess(session)
bindDeferredColdRestoreAndSnapshot(session)
store.getState().clearSleepingAgentSession(record.paneKey)
session.keepResumeRecordAfterColdRestoreSpawn(startup)
expect(store.getState().sleepingAgentSessionsByPaneKey).toEqual({})
unsubscribe()
}
)
it.each([
{
liveId: 'C',
savedId: 'C',
savedHost: 'ssh-A',
liveHost: undefined,
expected: 'ssh-A',
host: 'ssh:ssh-A'
},
{
liveId: 'D',
savedId: 'C',
savedHost: 'ssh-A',
liveHost: undefined,
expected: undefined,
host: 'ssh:ssh-A'
},
{ liveId: 'C', savedId: 'C', savedHost: null, liveHost: null, expected: null, host: 'local' }
])('retains only matching captured host evidence ($liveId, $savedHost, $liveHost)', (testCase) => {
const store = createTestStore()
fixture.state = store.getState()
const unsubscribe = store.subscribe((state) => {
fixture.state = state
})
const paneKey = 'tab:leaf'
store.setState({
agentStatusByPaneKey: {
[paneKey]: {
paneKey,
agentType: 'codex',
state: 'working',
prompt: '',
updatedAt: 1,
stateStartedAt: 1,
stateHistory: [],
connectionId: testCase.liveHost,
providerSession: { key: 'session_id', id: testCase.liveId }
}
},
sleepingAgentSessionsByPaneKey: {
[paneKey]: {
paneKey,
worktreeId: 'wt',
agent: 'codex',
state: 'working',
prompt: '',
updatedAt: 1,
capturedAt: 1,
connectionId: testCase.savedHost,
providerSession: { key: 'session_id', id: testCase.savedId }
}
}
})
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only startup construction and retention run; all accessed session members are supplied.
const session = {
cacheKey: paneKey,
deps: { tabId: 'tab', worktreeId: 'wt' },
pane: { id: 1, leafId: 'leaf' },
manager: {},
paneStartup: null,
worktree: { path: '/tmp' },
executionHostId: testCase.host,
transport: { getRuntimeEnvironmentId: () => null }
} as unknown as ConnectPanePtySession
installSleepingRecordAccess(session)
bindBuildColdRestoreAgentResumeStartup(session)
bindDeferredColdRestoreAndSnapshot(session)
const startup = session.buildColdRestoreAgentResumeStartup()
expect(startup).not.toBeNull()
session.keepResumeRecordAfterColdRestoreSpawn(startup)
expect(store.getState().sleepingAgentSessionsByPaneKey[paneKey]?.connectionId).toBe(
testCase.expected
)
unsubscribe()
})
@@ -1,158 +0,0 @@
import { bindPtyConnectionTestMocks } from '../../test-fixtures/pty-connection-mocks.spec'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
POST_REPLAY_REATTACH_RESET,
PROCESS_BOUNDARY_GROUND
} from '../../../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles'
import { TerminalKittyKeyboardModeTracker } from '../../../../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker'
import { replayEpilogue } from '../../test-fixtures/pty-connection-test-replay-epilogue'
import { flushAsyncTicks } from '../../test-fixtures/pty-connection-test-async'
import {
LEAF_1,
createMockTransport,
createPane,
createManager,
type MockTransport
} from '../../test-fixtures/pty-connection-test-pane-fixtures'
import {
buildPaneConnectionDeps,
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../../test-fixtures/pty-connection-test-deps'
import { createInitialStoreState } from '../../test-fixtures/pty-connection-test-store-fixtures'
import type { StoreState } from '../../test-fixtures/pty-connection-test-store-state'
import {
installTerminalTestGlobals,
restoreTerminalTestGlobals
} from '../../test-fixtures/pty-connection-test-environment'
import { mockPanePtyArgs } from '../../test-fixtures/pty-connection-test-connect-mock-pane'
export function registerPtyConnectionKittyKeyboardRestoreTests(): void {
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
let createdTransportOptions: Record<string, unknown>[] = []
let storeSubscribers: ((state: StoreState) => void)[] = []
function createDeps(overrides: Record<string, unknown> = {}) {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
// Why: xterm and the pane mirror must end every restore on the same kitty flags.
describe('connectPanePty kitty keyboard restore', () => {
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
transportFactoryQueue = []
createdTransportOptions = []
storeSubscribers = []
mockStoreState = createInitialStoreState(() => mockStoreState)
bindPtyConnectionTestMocks({
getState: () => mockStoreState,
getTransportQueue: () => transportFactoryQueue,
getTransportOptions: () => createdTransportOptions,
getStoreSubscribers: () => storeSubscribers,
setStoreSubscribers: (subscribers) => {
storeSubscribers = subscribers
}
})
await installTerminalTestGlobals()
})
afterEach(async () => {
await restoreTerminalTestGlobals()
})
async function reattachWithSnapshotFlags(kittyKeyboard: boolean) {
const { connectPanePty } = await import('../../connect-pane-pty')
const agentTitleMocks = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('tab-pty')
transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) =>
sessionId
? {
id: sessionId,
snapshot: 'live app frame',
snapshotKittyKeyboardFlags: 31,
snapshotSeq: 7
}
: null
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
pane.terminal.options.vtExtensions.kittyKeyboard = kittyKeyboard
const deps = createDeps({
restoredLeafId: LEAF_1,
restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' }
})
connectPanePty(
...mockPanePtyArgs(pane, createManager(1), bindPaneAgentTitleMocks(deps, agentTitleMocks))
)
await flushAsyncTicks(20)
return { pane, mirror: deps.paneKittyKeyboardModesRef.current.get(pane.id) }
}
it("restores a live app's host-proven flags into xterm and the mirror on reattach", async () => {
const { pane, mirror } = await reattachWithSnapshotFlags(true)
expect(pane.terminal.write).toHaveBeenCalledWith(
`${POST_REPLAY_REATTACH_RESET}\x1b[<99u\x1b[=31u`,
expect.any(Function)
)
expect(mirror?.flags).toBe(31)
})
// Why: xterm ignores CSI u while the protocol is withheld (ConPTY), so its mirror must too.
it('keeps a withheld-protocol pane at 0 in both records despite host flags', async () => {
const { pane, mirror } = await reattachWithSnapshotFlags(false)
expect(pane.terminal.write).toHaveBeenCalledWith(
replayEpilogue(POST_REPLAY_REATTACH_RESET),
expect.any(Function)
)
expect(mirror?.flags).toBe(0)
})
it('grounds xterm and the mirror with one scanned write before a restart-in-place spawns', async () => {
const { connectPanePty } = await import('../../connect-pane-pty')
const agentTitleMocks2 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
transportFactoryQueue.push(createMockTransport())
const pane = createPane(91)
// Use a unique tab ID to avoid other tests’ pending-spawn entries and force fresh spawn.
const deps = createDeps({ tabId: 'tab-kitty-fresh-spawn' })
// The pane's previous occupant left the alternate screen and kitty flags on.
const mirror = new TerminalKittyKeyboardModeTracker()
mirror.scan('\x1b[?1049h\x1b[>5u')
deps.paneKittyKeyboardModesRef.current.set(pane.id, mirror)
connectPanePty(
...mockPanePtyArgs(pane, createManager(91), bindPaneAgentTitleMocks(deps, agentTitleMocks2))
)
await flushAsyncTicks(20)
expect(pane.terminal.write).toHaveBeenCalledWith(
PROCESS_BOUNDARY_GROUND,
expect.any(Function)
)
expect(mirror.snapshotFlags).toBe(0)
expect(mirror.isAlternateScreen).toBe(false)
})
it('grounds xterm and the mirror together on Reset Terminal and asks the host to ground', async () => {
const { pane, mirror } = await reattachWithSnapshotFlags(true)
expect(mirror?.flags).toBe(31)
const { resetTerminalInputModes } = await import('../../../input/terminal-input-mode-reset')
resetTerminalInputModes('tab-pty')
expect(pane.terminal.write).toHaveBeenLastCalledWith(
PROCESS_BOUNDARY_GROUND,
expect.any(Function)
)
expect(mirror?.flags).toBe(0)
expect(window.api.pty.resetInputModes).toHaveBeenCalledWith('tab-pty')
})
})
}
@@ -1,5 +1,4 @@
import { describe, vi } from 'vitest'
import { registerPtyConnectionKittyKeyboardRestoreTests } from './input-modes/pty-connection-kitty-keyboard-restore.spec'
import { registerPtyConnectionMode2031SubscriptionsTests } from '../emulation/pty-connection-mode-2031-subscriptions.spec'
import {
registerPtyConnectionDaemonPendingEscapeTailTests,
@@ -24,7 +23,6 @@ vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
describe('pty-connection-kitty-keyboard-restore', registerPtyConnectionKittyKeyboardRestoreTests)
describe('pty-connection-mode-2031-subscriptions', registerPtyConnectionMode2031SubscriptionsTests)
describe('pty-connection-reattach-mode-reset', () => {
registerPtyConnectionDaemonPendingEscapeTailTests()
@@ -1,17 +1,6 @@
// Why: reproduce the renderer Pi spinner pipeline (pty:data IPC → onTitleChange); electron verification showed frames arrive but the store never sees the canonicalized "⠋ π - cwd" working title.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const ESC = '\x1b'
const BEL = '\x07'
const workingFrame = (frame: string): string => `${ESC}]0;${frame} π - cwd${BEL}`
const idleTitle = (): string => `${ESC}]0;π - cwd${BEL}`
function flushPtySideEffects(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0))
}
describe('dispatcher → transport → onTitleChange for Pi spinner', () => {
describe('dispatcher delivery before attachment and during exit', () => {
const originalWindow = (globalThis as { window?: typeof window }).window
// The singleton dispatcher subscribes one global onData callback; we capture it to simulate main delivering IPC events directly.
@@ -72,175 +61,6 @@ describe('dispatcher → transport → onTitleChange for Pi spinner', () => {
}
})
it('ACKs PTY data after dispatcher consumers accept the chunk', async () => {
const { ensurePtyDispatcher } = await import('./pty-dispatcher')
const { ptyDataHandlers } = await import('../shutdown/pty-shutdown-data-suspension')
const handler = vi.fn()
ensurePtyDispatcher()
ptyDataHandlers.set('pty-pi', handler)
dispatcherCallback?.({ id: 'pty-pi', data: 'chunk', rawLength: 10, background: true } as never)
expect(handler).toHaveBeenCalledWith('chunk', { rawLength: 10, background: true })
expect(window.api.pty.ackData).toHaveBeenCalledWith('pty-pi', 10, 10)
ptyDataHandlers.delete('pty-pi')
})
it('signals main that the pty:data listener is live exactly once per page load', async () => {
// Why: main gates all pty sends on this handshake, so a silent no-op would stall delivery until the 10s watchdog; assert it fires exactly once.
const { ensurePtyDispatcher } = await import('./pty-dispatcher')
ensurePtyDispatcher()
ensurePtyDispatcher()
expect(window.api.pty.rendererDispatcherReady).toHaveBeenCalledTimes(1)
})
it('routes Pi OSC title frames from pty:data → onTitleChange via the dispatcher', async () => {
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
await transport.connect({ url: '', callbacks: {} })
expect(dispatcherCallback).not.toBeNull()
dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() })
dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠋') })
dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠙') })
dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() })
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
expect(seenTitles).toContain('⠋ π - cwd')
transport.disconnect()
})
it('pipeline survives a chunk carrying shell output interleaved with spinner frames', async () => {
// Why: node-pty's 8ms batching packs multiple OSC titles + body into one chunk; the handler takes the LAST title, which must still surface working frames.
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
await transport.connect({ url: '', callbacks: {} })
dispatcherCallback?.({
id: 'pty-pi',
data: `assistant output line 1\r\n${workingFrame('⠋')}more body text`
})
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
expect(seenTitles).toContain('⠋ π - cwd')
transport.disconnect()
})
it('attach()-flow pipeline delivers working frames to onTitleChange', async () => {
// Why: reattach uses attach() not connect(); if handler registration drifted between them, remounted Pi sessions would stop emitting spinner signals.
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
transport.attach({ existingPtyId: 'pty-pi', callbacks: {} })
// attach()'s eager-buffer replay can flush initial titles; only assert on frames pushed after attach resolves.
onTitleChange.mockClear()
dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠋') })
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
expect(seenTitles).toContain('⠋ π - cwd')
transport.disconnect()
})
it('reproduces "Pi is idle" state: after working→idle, onTitleChange ends on the idle title', async () => {
// Why: bug shows the store stuck at the idle title while working — assert both working and idle titles reach onTitleChange, in order.
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
await transport.connect({ url: '', callbacks: {} })
dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() })
dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠋') })
dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠙') })
dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() })
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
const workingIdx = seenTitles.indexOf('⠋ π - cwd')
const finalIdleIdx = seenTitles.lastIndexOf('π - cwd')
expect(workingIdx).toBeGreaterThanOrEqual(0)
expect(finalIdleIdx).toBeGreaterThan(workingIdx)
transport.disconnect()
})
// Cursor’s bare native redraw must not overwrite the synthesized working spinner mid-turn.
it('drops cursor-agent native "Cursor Agent" title so it cannot overwrite the synthesized spinner', async () => {
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
await transport.connect({ url: '', callbacks: {} })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠋ Cursor Agent${BEL}` })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠙ Cursor Agent${BEL}` })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` })
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
expect(seenTitles).not.toContain('Cursor Agent')
expect(seenTitles).toContain('⠋ Cursor Agent')
expect(seenTitles).toContain('⠙ Cursor Agent')
transport.disconnect()
})
it('still surfaces the synthesized "Cursor ready" idle title after working', async () => {
// Why: the bare-title drop must not also catch the decorated "Cursor ready" done frame Orca synthesizes on the stop hook.
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
await transport.connect({ url: '', callbacks: {} })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠋ Cursor Agent${BEL}` })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor ready${BEL}${BEL}` })
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
expect(seenTitles).toContain('⠋ Cursor Agent')
expect(seenTitles).toContain('Cursor ready')
transport.disconnect()
})
it('surfaces synthesized "Codex ready" idle titles after Codex spinner titles', async () => {
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
await transport.connect({ url: '', callbacks: {} })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;\u280b Codex${BEL}` })
dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Codex ready${BEL}` })
await flushPtySideEffects()
const seenTitles = onTitleChange.mock.calls.map((c) => c[0])
expect(seenTitles).toContain('\u280b Codex')
expect(seenTitles).toContain('Codex ready')
transport.disconnect()
})
it('replays PTY data that arrives before connect() registers the pane handler', async () => {
const { createIpcPtyTransport } = await import('../ipc/pty-transport')
const onData = vi.fn()
@@ -1,167 +0,0 @@
// Confirm dead push delivery over two silent ticks, then heal through invoke once per cooldown: reattach first and deliver pulled restore markers locally.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PtyRendererDeliveryHealthReply } from '../../../../../../shared/terminal/pty/diagnostics/pty-renderer-delivery-health'
vi.mock('@/lib/e2e-config', () => ({ e2eConfig: { exposeStore: false } }))
const INTERVAL_MS = 15_000
const HEALTHY: PtyRendererDeliveryHealthReply = {
inFlightTotalChars: 0,
inFlightPtyCount: 0,
msSinceLastAck: 1_000
}
const STALLED: PtyRendererDeliveryHealthReply = {
inFlightTotalChars: 512 * 1024,
inFlightPtyCount: 2,
msSinceLastAck: null
}
describe('terminal delivery watchdog', () => {
const originalWindow = (globalThis as { window?: typeof window }).window
const reportMock = vi.fn<(args: unknown) => Promise<PtyRendererDeliveryHealthReply>>()
const listenerCountMock = vi.fn(() => 1)
const reattachMock = vi.fn()
let warnSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.resetModules()
vi.useFakeTimers()
reportMock.mockReset()
listenerCountMock.mockClear()
reattachMock.mockClear()
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
;(globalThis as { window: typeof window }).window = {
...originalWindow,
api: {
...originalWindow?.api,
pty: {
...originalWindow?.api?.pty,
reportRendererDeliveryState: reportMock,
getPtyDataListenerCount: listenerCountMock
}
}
} as unknown as typeof window
})
afterEach(() => {
warnSpy.mockRestore()
vi.useRealTimers()
if (originalWindow) {
;(globalThis as { window: typeof window }).window = originalWindow
} else {
delete (globalThis as { window?: typeof window }).window
}
})
async function startWatchdog(): Promise<{
recordPtyDataReceived: (ptyId: string, chars: number) => void
registerRestoreHandler: (
ptyId: string,
handler: (event: { id: string; reason: string; markerSeq?: number }) => void
) => void
}> {
const watchdog = await import('./terminal-delivery-watchdog')
const restoreChannel = await import('./pty-model-restore-channel')
watchdog.startTerminalDeliveryWatchdog({
reattachPushListeners: reattachMock,
hasAttachedPtys: () => true
})
return {
recordPtyDataReceived: watchdog.recordPtyDataReceived,
registerRestoreHandler: (ptyId, handler) => {
restoreChannel.registerPtyModelRestoreNeededHandler(ptyId, handler)
}
}
}
it('does zero IPC while pty output is flowing', async () => {
const { recordPtyDataReceived } = await startWatchdog()
for (let tick = 0; tick < 8; tick++) {
recordPtyDataReceived('pty-1', 64)
await vi.advanceTimersByTimeAsync(INTERVAL_MS)
}
expect(reportMock).not.toHaveBeenCalled()
})
it('reports during silence but never heals a healthy-idle main', async () => {
reportMock.mockResolvedValue(HEALTHY)
await startWatchdog()
await vi.advanceTimersByTimeAsync(INTERVAL_MS * 4)
expect(reportMock).toHaveBeenCalledTimes(4)
for (const call of reportMock.mock.calls) {
expect((call[0] as { heal?: boolean }).heal).toBeUndefined()
}
expect(reattachMock).not.toHaveBeenCalled()
})
it('confirms a wedge across two silent ticks, re-attaches, and routes pulled restore markers', async () => {
reportMock.mockImplementation((args) =>
Promise.resolve(
(args as { heal?: boolean }).heal
? {
...STALLED,
inFlightTotalChars: 0,
inFlightPtyCount: 0,
writtenOff: [{ id: 'pty-1', markerSeq: 42, writtenOffChars: 512 * 1024 }]
}
: STALLED
)
)
const { recordPtyDataReceived, registerRestoreHandler } = await startWatchdog()
const restoreEvents: { id: string; reason: string; markerSeq?: number }[] = []
registerRestoreHandler('pty-1', (event) => restoreEvents.push(event))
// Bytes flowed once, then the push channel died: the field shape.
recordPtyDataReceived('pty-1', 128)
await vi.advanceTimersByTimeAsync(INTERVAL_MS)
expect(reportMock).not.toHaveBeenCalled()
// First silent tick: report only, no heal yet.
await vi.advanceTimersByTimeAsync(INTERVAL_MS)
expect(reportMock).toHaveBeenCalledTimes(1)
expect(reattachMock).not.toHaveBeenCalled()
// Require reattach before heal and local marker delivery without any push event; retain the prior listener count for diagnosis.
await vi.advanceTimersByTimeAsync(INTERVAL_MS)
expect(reattachMock).toHaveBeenCalledTimes(1)
const healCalls = reportMock.mock.calls.filter(
(call) => (call[0] as { heal?: boolean }).heal === true
)
expect(healCalls).toHaveLength(1)
expect(healCalls[0]![0]).toMatchObject({
heal: true,
rendererPtyDataListenerCount: 1,
receivedCharsByPty: { 'pty-1': 128 }
})
expect(restoreEvents).toEqual([{ id: 'pty-1', reason: 'delivery-heal', markerSeq: 42 }])
})
it('rate-limits heals to the cooldown while the wedge persists', async () => {
reportMock.mockImplementation((args) =>
Promise.resolve((args as { heal?: boolean }).heal ? { ...STALLED, writtenOff: [] } : STALLED)
)
await startWatchdog()
const countHeals = (): number =>
reportMock.mock.calls.filter((call) => (call[0] as { heal?: boolean }).heal === true).length
// Ticks at 15s/30s: confirm + first heal.
await vi.advanceTimersByTimeAsync(INTERVAL_MS * 2)
expect(countHeals()).toBe(1)
// 45s/60s/75s: streak rebuilds but the 60s cooldown holds.
await vi.advanceTimersByTimeAsync(INTERVAL_MS * 3)
expect(countHeals()).toBe(1)
// 90s: cooldown elapsed — one more heal, not one per tick.
await vi.advanceTimersByTimeAsync(INTERVAL_MS)
expect(countHeals()).toBe(2)
expect(reattachMock).toHaveBeenCalledTimes(2)
})
})
@@ -1,31 +1,12 @@
import { describe, expect, it, vi } from 'vitest'
import { Terminal } from '@xterm/headless'
import { createPtyInputWriteQueue } from './pty-input-write-queue'
import {
PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES,
PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS,
TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS
} from './pty-input-write-queue-contract'
import {
TERMINAL_INPUT_CHUNK_MAX_BYTES,
TERMINAL_INPUT_MAX_BYTES
} from '../../../../../../shared/terminal/input/terminal-input'
import { TERMINAL_INPUT_CHUNK_MAX_BYTES } from '../../../../../../shared/terminal/input/terminal-input'
import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../../../../../shared/clipboard-text'
import { mode2031SequenceFor } from '../../../../../../shared/terminal/protocol/queries/terminal-color-scheme-protocol'
import { PtyStartupIngress } from '../../../../../../shared/terminal/pty/ingress/pty-startup-ingress'
import type { PtyIngressEmission } from '../../../../../../shared/terminal/pty/ingress/pty-startup-ingress-contract'
import {
extractOnlyCookedEchoSafeQueryReplies,
needsCookedEchoSafeQueryReply
} from '../../../../../../shared/terminal/protocol/queries/terminal-query-reply'
import { installTerminalCapabilityReplyHandlers } from '../../emulation/terminal-capability-replies'
import {
createDeferred,
flushAsyncTicks
} from '../../pty-connection/test-fixtures/pty-connection-test-async'
const WHEEL_UP_REPORT = '\x1b[<64;60;20M'
type WriteRecord = { id: string; data: string }
function createRecordingQueue(options: { writable?: () => boolean } = {}): {
@@ -40,364 +21,7 @@ function createRecordingQueue(options: { writable?: () => boolean } = {}): {
return { writes, queue }
}
function createParkedQueue(): {
writes: WriteRecord[]
pendingYields: (() => void)[]
queue: ReturnType<typeof createPtyInputWriteQueue>
} {
const writes: WriteRecord[] = []
const pendingYields: (() => void)[] = []
const queue = createPtyInputWriteQueue({
isWritable: () => true,
write: (id, data) => writes.push({ id, data }),
yieldBetweenWrites: () =>
new Promise<void>((resolve) => {
pendingYields.push(resolve)
})
})
return { writes, pendingYields, queue }
}
async function releaseNextWrite(
writes: WriteRecord[],
pendingYields: (() => void)[]
): Promise<void> {
const before = writes.length
const release = pendingYields.shift()
expect(release).toBeDefined()
release?.()
await Promise.resolve()
expect(writes.length).toBeGreaterThan(before)
}
function writeTerminal(term: Terminal, data: string): Promise<void> {
return new Promise((resolve) => term.write(data, resolve))
}
function extractReplyWrites(writes: WriteRecord[]): string[] {
return writes.flatMap((write) => extractOnlyCookedEchoSafeQueryReplies(write.data) ?? [])
}
describe('pty input write queue', () => {
it('coalesces a dense burst of wheel reports instead of one write per macrotask turn', async () => {
const { writes, queue } = createRecordingQueue()
// Queue a 120Hz two-second gesture; the first report is immediate and the rest must coalesce without hundreds of timer turns.
for (let i = 0; i < 240; i += 1) {
expect(queue.enqueue('pty-1', WHEEL_UP_REPORT, 'driving')).toBe(true)
}
await queue.waitForDrain()
// First report flushes immediately (keystroke latency); everything queued
// behind it must drain as a single coalesced write, not 239 timer turns.
expect(writes.length).toBe(2)
expect(writes[0]?.data).toBe(WHEEL_UP_REPORT)
expect(writes[1]?.data).toBe(WHEEL_UP_REPORT.repeat(239))
expect(writes.map((write) => write.id)).toEqual(['pty-1', 'pty-1'])
})
it('preserves byte order and content across coalesced writes', async () => {
const { writes, queue } = createRecordingQueue()
const inputs = ['a', '\x1b[<65;1;1M', 'bc', '\x1b[A', 'd']
for (const input of inputs) {
queue.enqueue('pty-1', input, 'driving')
}
await queue.waitForDrain()
expect(writes.map((write) => write.data).join('')).toBe(inputs.join(''))
})
it('does not coalesce across different PTY ids', async () => {
const writes: WriteRecord[] = []
const queue = createPtyInputWriteQueue({
isWritable: () => true,
write: (id, data) => writes.push({ id, data })
})
queue.enqueue('pty-1', 'a', 'driving')
queue.enqueue('pty-1', 'b', 'driving')
queue.enqueue('pty-2', 'c', 'driving')
queue.enqueue('pty-1', 'd', 'driving')
await queue.waitForDrain()
expect(writes).toEqual([
{ id: 'pty-1', data: 'a' },
{ id: 'pty-1', data: 'b' },
{ id: 'pty-2', data: 'c' },
{ id: 'pty-1', data: 'd' }
])
})
it('keeps coalesced payloads under the input chunk byte cap', async () => {
const { writes, queue } = createRecordingQueue()
const piece = 'x'.repeat(1000)
for (let i = 0; i < 12; i += 1) {
queue.enqueue('pty-1', piece, 'driving')
}
await queue.waitForDrain()
expect(writes.map((write) => write.data).join('')).toBe(piece.repeat(12))
for (const write of writes) {
expect(write.data.length).toBeLessThanOrEqual(TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS)
}
expect(writes.length).toBeGreaterThan(1)
})
it('still chunks oversized items and keeps trailing input ordered behind them', async () => {
const { writes, queue } = createRecordingQueue()
const large = 'y'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES * 2 + 100)
queue.enqueue('pty-1', 'before', 'driving')
queue.enqueue('pty-1', large, 'driving')
queue.enqueue('pty-1', 'after', 'driving')
await queue.waitForDrain()
expect(writes.map((write) => write.data).join('')).toBe(`before${large}after`)
expect(writes.at(-1)?.data).toBe('after')
for (const write of writes) {
expect(write.data.length).toBeLessThanOrEqual(TERMINAL_INPUT_CHUNK_MAX_BYTES)
}
})
it('rejects input over the terminal input byte limit without writing', async () => {
const { writes, queue } = createRecordingQueue()
expect(queue.enqueue('pty-1', 'z'.repeat(TERMINAL_INPUT_MAX_BYTES + 1), 'driving')).toBe(false)
await queue.waitForDrain()
expect(writes).toEqual([])
})
it('drops queued input for PTYs that are no longer writable', async () => {
let writable = true
const { writes, queue } = createRecordingQueue({ writable: () => writable })
queue.enqueue('pty-1', 'a', 'driving')
writable = false
queue.enqueue('pty-1', 'b', 'driving')
await queue.waitForDrain()
expect(writes).toEqual([{ id: 'pty-1', data: 'a' }])
})
it('does not coalesce dual color-scheme replies into one host write (#13137)', async () => {
const { writes, queue } = createRecordingQueue()
const reply = mode2031SequenceFor('dark')
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
await queue.waitForDrain()
expect(writes).toEqual([
{ id: 'pty-1', data: reply },
{ id: 'pty-1', data: reply }
])
})
it('keeps all query replies atomic for host-side ordering (#13892)', async () => {
const { writes, queue } = createRecordingQueue()
const replies = ['\x1b[?1;2c', '\x1b[1;1R']
for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
await queue.waitForDrain()
expect(writes.map((write) => write.data)).toEqual(replies)
})
it('does not coalesce a color-scheme reply with a following keystroke', async () => {
const { writes, queue } = createRecordingQueue()
const reply = mode2031SequenceFor('dark')
queue.enqueueQueryReply('pty-1', reply)
queue.enqueue('pty-1', 'y', 'driving')
await queue.waitForDrain()
expect(writes).toEqual([
{ id: 'pty-1', data: reply },
{ id: 'pty-1', data: 'y' }
])
})
it('bounds an OSC 10/11 reply flood and drains a following keystroke', async () => {
const { writes, pendingYields, queue } = createParkedQueue()
const replies: string[] = []
let allAccepted = true
for (let index = 0; index < 10_000; index += 1) {
const color = index.toString(16).padStart(4, '0')
const reply = `\x1b]${index % 2 === 0 ? 10 : 11};rgb:${color}/0000/0000\x1b\\`
replies.push(reply)
allAccepted = queue.enqueueQueryReply('pty-1', reply) && allAccepted
}
expect(allAccepted).toBe(true)
expect(queue.enqueue('pty-1', 'k', 'driving')).toBe(true)
await Promise.resolve()
expect(pendingYields).toHaveLength(1)
for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
await queue.waitForDrain()
const replyWrites = writes.filter((write) => write.data.startsWith('\x1b]'))
expect(replyWrites.map((write) => write.data)).toEqual([
replies[0],
...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES)
])
expect(replyWrites.every((write) => needsCookedEchoSafeQueryReply(write.data))).toBe(true)
expect(writes.at(-1)?.data).toBe('k')
})
it('applies the same bound to DA1 replies kept atomic for ordering', async () => {
const { writes, pendingYields, queue } = createParkedQueue()
const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`)
for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
expect(queue.enqueue('pty-1', 'k', 'driving')).toBe(true)
await Promise.resolve()
for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
await queue.waitForDrain()
expect(writes.map((write) => write.data)).toEqual([
replies[0],
...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES),
'k'
])
})
it('drops the oldest reply-only payload when the reply text budget fills', async () => {
const reply = (slot: 10 | 11, marker: string): string =>
`\x1b]${slot};${marker.repeat(1_400)}\x1b\\`
const first = reply(10, '1')
const dropped = reply(11, '2')
const second = reply(10, '3')
const third = reply(11, '4')
const { writes, pendingYields, queue } = createParkedQueue()
expect(second.length * 2).toBeLessThanOrEqual(
PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS
)
expect(second.length * 3).toBeGreaterThan(PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS)
queue.enqueueQueryReply('pty-1', first)
queue.enqueueQueryReply('pty-1', dropped)
queue.enqueue('pty-1', 'x', 'driving')
queue.enqueueQueryReply('pty-1', second)
queue.enqueueQueryReply('pty-1', third)
queue.enqueue('pty-1', 'k', 'driving')
await Promise.resolve()
expect(pendingYields).toHaveLength(1)
for (let turn = 0; turn < 3; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
await queue.waitForDrain()
expect(writes).toEqual([
{ id: 'pty-1', data: first },
{ id: 'pty-1', data: 'x' },
{ id: 'pty-1', data: second },
{ id: 'pty-1', data: third },
{ id: 'pty-1', data: 'k' }
])
})
it('bounds replies generated by a real xterm OSC query flood', async () => {
const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true })
term.options.theme = { foreground: '#2e3434', background: '#ffffff' }
const { writes, queue } = createRecordingQueue()
const generated: string[] = []
const disposable = installTerminalCapabilityReplyHandlers({
terminal: {
cols: term.cols,
rows: term.rows,
element: undefined,
options: term.options
},
parser: term.parser,
sendInput: (data) => {
generated.push(data)
return queue.enqueueQueryReply('pty-1', data)
},
isReplaying: () => false
})
try {
await writeTerminal(term, '\x1b]10;?;?\x1b\\'.repeat(34))
await queue.waitForDrain()
const foreground = '\x1b]10;rgb:2e2e/3434/3434\x1b\\'
const background = '\x1b]11;rgb:ffff/ffff/ffff\x1b\\'
expect(generated).toEqual(Array.from({ length: 34 }, () => [foreground, background]).flat())
expect(extractReplyWrites(writes)).toEqual([
foreground,
...generated.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES)
])
} finally {
disposable.dispose()
term.dispose()
}
})
it('rejects one reply larger than the total reply retention budget', async () => {
const { writes, queue } = createRecordingQueue()
const prefix = '\x1b]10;'
const suffix = '\x1b\\'
const input = `${prefix}${'x'.repeat(
TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS + 1 - prefix.length - suffix.length
)}${suffix}`
expect(input).toHaveLength(TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS + 1)
expect(queue.enqueueQueryReply('pty-1', input)).toBe(false)
await queue.waitForDrain()
expect(writes).toEqual([])
})
it('preserves an ordinary backlog while bounding later replies', async () => {
const { writes, queue } = createRecordingQueue()
const ordinary = Array.from({ length: 10_000 }, (_, index) => String(index % 10))
const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};1n`)
for (const input of ordinary) {
expect(queue.enqueue('pty-1', input, 'driving')).toBe(true)
}
for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
await queue.waitForDrain()
expect(writes.map((write) => write.data).join('')).toBe(
[...ordinary, ...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES)].join('')
)
expect(extractReplyWrites(writes)).toEqual(
replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES)
)
})
it('never sheds reply-shaped bytes sent through the ordinary input path', async () => {
const { writes, queue } = createRecordingQueue()
const ordinary = '\x1b]10;user-ordinary-marker\x1b\\'
const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};1n`)
expect(queue.enqueueQueryReply('pty-1', '\x1b[?10000;1n')).toBe(true)
expect(queue.enqueue('pty-1', ordinary, 'driving')).toBe(true)
for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
await queue.waitForDrain()
expect(writes.map((write) => write.data).join('')).toContain(ordinary)
})
it('contains drain failures and rejects input until queue reuse', async () => {
const failure = new Error('write failed')
const writes: WriteRecord[] = []
@@ -554,42 +178,6 @@ describe('pty input write queue', () => {
expect(delivered).toEqual(['accepted:stale-active', 'ordinary:fresh'])
})
it('reports the pty id that failed so a rebound owner can ignore the drain failure', async () => {
const failure = new Error('yield failed')
const onDrainFailure = vi.fn()
let rejectYield: ((error: Error) => void) | undefined
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const queue = createPtyInputWriteQueue({
isWritable: () => true,
write: () => undefined,
yieldBetweenWrites: () =>
new Promise<void>((_resolve, reject) => {
rejectYield = reject
}),
onDrainFailure
})
try {
expect(
queue.enqueue('pty-1', 'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES * 2), 'driving')
).toBe(true)
expect(rejectYield).toBeDefined()
rejectYield?.(failure)
await queue.waitForDrain()
expect(onDrainFailure).toHaveBeenCalledExactlyOnceWith('pty-1')
} finally {
warn.mockRestore()
}
})
it('keeps a pending reply small enough that one drain step writes and removes it', () => {
// Larger replies would span chunks, so admitReply could evict a half-written entry.
expect(PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS * 3).toBeLessThanOrEqual(
TERMINAL_INPUT_CHUNK_MAX_BYTES
)
})
it('does not let a stale drain failure clear input queued after reuse', async () => {
const failure = new Error('stale yield failed')
const writes: WriteRecord[] = []
@@ -630,89 +218,6 @@ describe('pty input write queue', () => {
}
})
it('dual mode-2031 enqueues through the real queue never paint 997 under host echo-safe write', async () => {
// Mixed versions can coalesce late 997 replies; drive queue→host intercept→echo strip and require no literal leakage at confirmation prompts (#9993).
vi.useFakeTimers()
const reply = mode2031SequenceFor('dark')
// Model ECHOCTL for every control byte so this fixture stays aligned with the encoder.
const caretEcho = (data: string): string =>
[...data]
.map((ch) =>
ch.charCodeAt(0) < 0x20 ? `^${String.fromCharCode(ch.charCodeAt(0) + 0x40)}` : ch
)
.join('')
const masterWrites: string[] = []
const emissions: PtyIngressEmission[] = []
let ingress!: PtyStartupIngress
ingress = new PtyStartupIngress({
ownerBackend: 'posix-pty',
write: (data) => {
masterWrites.push(data)
ingress.accept(caretEcho(data))
},
onEmission: (emission) => emissions.push(emission)
})
// Same intercept shape as LocalPtyProvider.write / Session.write / relay writeData.
const hostWrite = (_id: string, data: string): void => {
if (ingress.answerLiveQueryReply(data)) {
return
}
masterWrites.push(`RAW:${data}`)
ingress.accept(caretEcho(data))
}
const queue = createPtyInputWriteQueue({
isWritable: () => true,
write: hostWrite
})
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
await queue.waitForDrain()
await vi.advanceTimersByTimeAsync(0)
expect(masterWrites).toEqual([reply, reply])
expect(masterWrites.some((write) => write.startsWith('RAW:'))).toBe(false)
const visible = emissions.map((emission) => emission.data).join('')
expect(visible).toBe('')
expect(visible).not.toContain('997')
ingress.accept('Ok to proceed? (y) ')
const afterPrompt = emissions.map((emission) => emission.data).join('')
expect(afterPrompt).toBe('Ok to proceed? (y) ')
expect(afterPrompt).not.toContain('997;1n')
expect(afterPrompt).not.toContain(reply)
ingress.drainAndClose()
vi.useRealTimers()
})
it('clear() drops pending input that has not been written yet', async () => {
const writes: WriteRecord[] = []
const pendingYields: (() => void)[] = []
const queue = createPtyInputWriteQueue({
isWritable: () => true,
write: (id, data) => writes.push({ id, data }),
yieldBetweenWrites: () =>
new Promise<void>((resolve) => {
pendingYields.push(resolve)
})
})
const large = 'y'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES * 3)
queue.enqueue('pty-1', large, 'driving')
queue.enqueue('pty-1', 'tail', 'driving')
// First chunk is written synchronously, then the drain parks on the yield.
expect(writes.length).toBe(1)
queue.clear()
pendingYields.shift()?.()
await queue.waitForDrain()
expect(writes.length).toBe(1)
expect(writes.map((write) => write.data).join('')).not.toContain('tail')
})
it('clear() fences an in-flight validation before queue reuse', async () => {
vi.useFakeTimers()
const { writes, queue } = createRecordingQueue()
@@ -731,37 +236,4 @@ describe('pty input write queue', () => {
vi.useRealTimers()
}
})
it('clear() resets reply capacity for later input', async () => {
const { writes, queue } = createRecordingQueue()
const reply = mode2031SequenceFor('dark')
for (let index = 0; index <= PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; index += 1) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
queue.clear()
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
await queue.waitForDrain()
expect(extractReplyWrites(writes)).toEqual([reply, reply])
})
it('does not retain a reaction record per acknowledged write', async () => {
// Queue-lifetime promise races retained a reaction per accepted write until teardown, leaking roughly 440 bytes each.
const queue = createPtyInputWriteQueue({
isWritable: () => true,
write: () => undefined,
writeAccepted: async () => true,
yieldBetweenWrites: async () => undefined
})
globalThis.gc?.()
const heapBefore = process.memoryUsage().heapUsed
for (let index = 0; index < 20_000; index += 1) {
await queue.enqueueAccepted('pty-1', 'x', 'driving')
}
await queue.waitForDrain()
globalThis.gc?.()
const growthMb = (process.memoryUsage().heapUsed - heapBefore) / 1024 / 1024
expect(growthMb).toBeLessThan(2)
})
})
@@ -3,11 +3,7 @@ import {
createDeferred,
flushAsyncTicks
} from '../../pty-connection/test-fixtures/pty-connection-test-async'
import {
createPtyPreconnectInputBuffer,
PTY_PRECONNECT_INPUT_MAX_CODE_UNITS,
PTY_PRECONNECT_INPUT_MAX_ENTRIES
} from './pty-preconnect-input-buffer'
import { createPtyPreconnectInputBuffer } from './pty-preconnect-input-buffer'
describe('createPtyPreconnectInputBuffer', () => {
it('shares one flush worker and preserves mixed input order', async () => {
@@ -88,116 +84,4 @@ describe('createPtyPreconnectInputBuffer', () => {
await expect(accepted).resolves.toBe(false)
}
)
it('counts an in-flight accepted write toward both retention caps', async () => {
const codeUnitWrite = createDeferred<boolean>()
const codeUnitWriteStarted = createDeferred<void>()
const codeUnitBuffer = createPtyPreconnectInputBuffer()
const codeUnitAccepted = codeUnitBuffer.enqueueAccepted(
'x'.repeat(PTY_PRECONNECT_INPUT_MAX_CODE_UNITS),
'driving'
)
const codeUnitFlush = codeUnitBuffer.flush({
isCurrent: () => true,
sendInput: () => true,
sendInputImmediate: () => true,
sendInputAccepted: async () => {
codeUnitWriteStarted.resolve()
return codeUnitWrite.promise
}
})
await codeUnitWriteStarted.promise
expect(codeUnitBuffer.enqueue('overflow', 'ordinary', 'driving')).toBe(false)
codeUnitBuffer.clear()
codeUnitWrite.resolve(true)
await expect(codeUnitAccepted).resolves.toBe(false)
await codeUnitFlush
const entryWrite = createDeferred<boolean>()
const entryWriteStarted = createDeferred<void>()
const entryBuffer = createPtyPreconnectInputBuffer()
const entryAccepted = entryBuffer.enqueueAccepted('first', 'driving')
for (let index = 1; index < PTY_PRECONNECT_INPUT_MAX_ENTRIES; index += 1) {
expect(entryBuffer.enqueue('', 'ordinary', 'driving')).toBe(true)
}
const entryFlush = entryBuffer.flush({
isCurrent: () => true,
sendInput: () => true,
sendInputImmediate: () => true,
sendInputAccepted: async () => {
entryWriteStarted.resolve()
return entryWrite.promise
}
})
await entryWriteStarted.promise
expect(entryBuffer.enqueue('', 'ordinary', 'driving')).toBe(false)
entryBuffer.clear()
entryWrite.resolve(true)
await expect(entryAccepted).resolves.toBe(false)
await entryFlush
})
it('applies entry and code-unit caps to seeded input', async () => {
const entryBuffer = createPtyPreconnectInputBuffer(
Array.from({ length: PTY_PRECONNECT_INPUT_MAX_ENTRIES + 1 }, () => ({
data: '',
kind: 'ordinary' as const,
inputKind: 'driving' as const
}))
)
let entryWrites = 0
expect(entryBuffer.enqueue('', 'ordinary', 'driving')).toBe(false)
await entryBuffer.flush({
isCurrent: () => true,
sendInput: () => {
entryWrites += 1
return true
},
sendInputImmediate: () => true
})
expect(entryWrites).toBe(PTY_PRECONNECT_INPUT_MAX_ENTRIES)
const codeUnitBuffer = createPtyPreconnectInputBuffer([
{
data: 'x'.repeat(PTY_PRECONNECT_INPUT_MAX_CODE_UNITS),
kind: 'ordinary',
inputKind: 'driving'
},
{ data: 'overflow', kind: 'ordinary', inputKind: 'driving' }
])
const codeUnitWrites: number[] = []
expect(codeUnitBuffer.enqueue('new', 'ordinary', 'driving')).toBe(false)
await codeUnitBuffer.flush({
isCurrent: () => true,
sendInput: (data) => {
codeUnitWrites.push(data.length)
return true
},
sendInputImmediate: () => true
})
expect(codeUnitWrites).toEqual([PTY_PRECONNECT_INPUT_MAX_CODE_UNITS])
})
it('settles retained acknowledged input when the spawn is abandoned before connect', async () => {
// Abandoned deferred spawns never connect; disposal must settle buffered accepted writes instead of hanging paste.
const buffer = createPtyPreconnectInputBuffer()
const pastePending = buffer.enqueueAccepted('pasted text', 'driving')
let settled = false
void pastePending.then(() => {
settled = true
})
await Promise.resolve()
expect(settled).toBe(false)
buffer.clear()
await expect(pastePending).resolves.toBe(false)
expect(buffer.isBuffering()).toBe(false)
})
})
@@ -1,10 +1,3 @@
import {
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../../pty-connection/test-fixtures/pty-connection-test-deps'
import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types'
import type { PtyConnectionDeps } from '../../pty-connection/pty-connection-deps'
import type { ConnectCallbacks } from '../../pty-connection/test-fixtures/pty-connection-test-pane-fixtures'
import { terminalAttachResult } from '../../../../../../shared/terminal/pty/lifecycle/terminal-attach-result'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness'
@@ -39,34 +32,6 @@ describe('createIpcPtyTransport', () => {
restorePtySpecWindow(originalWindow)
})
it('exposes explicit local or direct SSH ownership without inferring it from the workspace', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
for (const connectionId of [undefined, 'qa']) {
const transport = createIpcPtyTransport({ connectionId })
expect(transport.getExecutionHostId?.()).toBe(connectionId ? 'ssh:qa' : 'local')
expect(transport.getRuntimeEnvironmentId?.()).toBeNull()
transport.destroy?.()
}
})
it.each([0, 1, 420])(
'preserves snapshot sequence and keyboard proof %s across IPC reattach',
async (seq) => {
const { createIpcPtyTransport } = await import('./pty-transport')
vi.mocked(window.api.pty.spawn).mockResolvedValue({
id: 'existing',
isReattach: true,
snapshot: 'ready',
snapshotSeq: seq,
snapshotKittyKeyboardFlags: 0
})
const transport = createIpcPtyTransport({})
const result = await transport.connect({ url: '', sessionId: 'existing', callbacks: {} })
expect(result).toMatchObject({ snapshotSeq: seq, snapshotKittyKeyboardFlags: 0 })
transport.detach?.()
}
)
it('drains an exited join with pre-request output and preserves its snapshot projection', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { ensurePtyDispatcher } = await import('../delivery/pty-dispatcher')
@@ -112,284 +77,6 @@ describe('createIpcPtyTransport', () => {
snapshotView.detach?.()
})
it('leaves title tracking to the PTY data stream (no OpenCode IPC channel)', async () => {
// Why: the OpenCode status IPC channel is gone (now the agent-hooks server), so the transport has no per-agent status callback.
const { createIpcPtyTransport } = await import('./pty-transport')
const transport = createIpcPtyTransport({})
await transport.connect({ url: '', callbacks: {} })
expect(onData).not.toBeNull()
expect(onExit).not.toBeNull()
transport.disconnect()
})
// A pane drag waits out a spawn whose result would bind the leaf to its old tab.
it('reports a connect as pending only until its PTY id arrives', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
let resolveSpawn!: (value: { id: string }) => void
vi.mocked(window.api.pty.spawn).mockReturnValue(
new Promise((resolve) => {
resolveSpawn = resolve
})
)
const transport = createIpcPtyTransport({})
expect(transport.isConnectPending?.()).toBe(false)
const connecting = transport.connect({ url: '', callbacks: {} })
expect(transport.isConnectPending?.()).toBe(true)
resolveSpawn({ id: 'pty-late' })
await connecting
expect(transport.getPtyId()).toBe('pty-late')
expect(transport.isConnectPending?.()).toBe(false)
transport.disconnect()
})
it('does not create a PTY when the pane generation is stale', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
const transport = createIpcPtyTransport({})
await expect(
transport.connect({ url: '', shouldContinue: () => false, callbacks: {} })
).resolves.toBeUndefined()
expect(spawn).not.toHaveBeenCalled()
})
it("carries an AI button's launch in its pane's spawn, and says whether the agent started", async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { awaitAgentLaunchPaneStart } =
await import('@/lib/agent-session/launch/pane/agent-launch-pane-start')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
const agentLaunch = { launch: { agent: 'claude' } }
const pane = { worktreeId: 'wt', tabId: 'tab-launch', leafId: 'leaf-launch' }
const started = awaitAgentLaunchPaneStart(pane.tabId, pane.leafId)
spawn.mockResolvedValueOnce({ id: 'pty-launch' })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the transport forwards the request untouched; main validates it.
await createIpcPtyTransport({ ...pane, agentLaunch } as never).connect({
url: '',
callbacks: {}
})
expect(spawn).toHaveBeenCalledWith(
expect.objectContaining({ tabId: 'tab-launch', agentLaunch })
)
await expect(started).resolves.toBe('pty-launch')
spawn.mockRejectedValueOnce(new Error('agent_launch_pane_refused'))
const refused = awaitAgentLaunchPaneStart(pane.tabId, pane.leafId)
await createIpcPtyTransport(pane).connect({ url: '', callbacks: { onError: vi.fn() } })
await expect(refused).resolves.toBeNull()
})
it('keeps the recovery hint and raw diagnostic from a wrapped spawn error', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
vi.mocked(window.api.pty.spawn).mockRejectedValueOnce(
new Error(
"Error invoking remote method 'pty:spawn': Error: Close unused terminals, then try again.\nnode-pty: open_slave failed: EMFILE (errno 24)"
)
)
const onError = vi.fn()
await createIpcPtyTransport({}).connect({ url: '', callbacks: { onError } })
expect(onError).toHaveBeenCalledWith(
'Close unused terminals, then try again.\nnode-pty: open_slave failed: EMFILE (errno 24)'
)
})
it('threads provider command ownership through the spawn IPC', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const transport = createIpcPtyTransport({
command: 'printf ready',
commandDelivery: 'provider'
})
await transport.connect({ url: '', callbacks: {} })
expect(window.api.pty.spawn).toHaveBeenCalledWith(
expect.objectContaining({
command: 'printf ready',
commandDelivery: 'provider'
})
)
transport.disconnect()
})
it('forwards requested environment deletions to the PTY spawn', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
const transport = createIpcPtyTransport({
envToDelete: ['CODEX_HOME', 'ORCA_CODEX_HOME']
})
await transport.connect({ url: '', callbacks: {} })
expect(spawn).toHaveBeenCalledWith(
expect.objectContaining({ envToDelete: ['CODEX_HOME', 'ORCA_CODEX_HOME'] })
)
})
it('forwards automatic resume provenance to the PTY spawn', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
const resumeProviderSession = {
key: 'session_id' as const,
id: 'session-a',
transcriptPath: '/Users/example/.codex/sessions/2026/07/20/rollout-a.jsonl'
}
const transport = createIpcPtyTransport({ resumeProviderSession })
await transport.connect({ url: '', callbacks: {} })
expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ resumeProviderSession }))
})
it('exposes the connection identity captured at transport creation', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
expect(createIpcPtyTransport({}).getConnectionId?.()).toBeNull()
expect(createIpcPtyTransport({ connectionId: 'ssh-1' }).getConnectionId?.()).toBe('ssh-1')
})
it('exposes local session metadata only for local IPC PTYs', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const localTransport = createIpcPtyTransport({
cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo',
shellOverride: 'wsl.exe',
projectRuntime: {
status: 'resolved',
runtime: {
kind: 'wsl',
hostPlatform: 'wsl',
projectId: 'repo',
distro: 'Ubuntu-24.04',
reason: 'project-override',
cacheKey: 'repo:wsl'
}
}
})
const sshTransport = createIpcPtyTransport({
connectionId: 'ssh-1',
cwd: 'C:\\Users\\alice\\repo',
shellOverride: 'cmd.exe'
})
expect(localTransport.getLocalSessionMetadata?.()).toEqual({
cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo',
shellOverride: 'wsl.exe'
})
expect(sshTransport.getLocalSessionMetadata?.()).toBeNull()
})
it('keeps captured Windows and WSL metadata when existing PTYs reattach', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const currentWslForWindowsPty = createIpcPtyTransport({
cwd: 'C:\\repo',
shellOverride: 'pwsh.exe',
projectRuntime: {
status: 'resolved',
runtime: {
kind: 'wsl',
hostPlatform: 'wsl',
projectId: 'repo',
distro: 'Ubuntu-24.04',
reason: 'project-override',
cacheKey: 'repo:wsl'
}
}
})
const currentWindowsForWslPty = createIpcPtyTransport({
cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo',
shellOverride: 'wsl.exe',
projectRuntime: {
status: 'resolved',
runtime: {
kind: 'windows-host',
hostPlatform: 'win32',
projectId: 'repo',
reason: 'project-override',
cacheKey: 'repo:windows'
}
}
})
currentWslForWindowsPty.attach({ existingPtyId: 'windows-pty', callbacks: {} })
currentWindowsForWslPty.attach({ existingPtyId: 'wsl-pty', callbacks: {} })
expect(currentWslForWindowsPty.getLocalSessionMetadata?.()).toEqual({
cwd: 'C:\\repo',
shellOverride: 'pwsh.exe'
})
expect(currentWindowsForWslPty.getLocalSessionMetadata?.()).toEqual({
cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo',
shellOverride: 'wsl.exe'
})
})
it('sends placement on a fresh spawn but not on a session reattach', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
const placement = {
kind: 'split',
parentLeafId: '11111111-1111-4111-8111-111111111111',
direction: 'horizontal'
} as const
const fresh = createIpcPtyTransport({ placement })
await fresh.connect({ url: '', callbacks: {} })
expect(spawn).toHaveBeenLastCalledWith(expect.objectContaining({ placement }))
fresh.disconnect()
const reattach = createIpcPtyTransport({ placement })
await reattach.connect({ url: '', callbacks: {}, sessionId: 'session-1' })
expect(spawn).toHaveBeenLastCalledWith(expect.not.objectContaining({ placement }))
reattach.disconnect()
})
it('returns startup cwd fallback metadata to the connection layer', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
spawn.mockResolvedValueOnce({
id: 'pty-1',
startupCwdFallback: { kind: 'worktree', cwd: '/repo/app' }
})
const transport = createIpcPtyTransport({})
await expect(transport.connect({ url: '', callbacks: {} })).resolves.toEqual({
id: 'pty-1',
startupCwdFallback: { kind: 'worktree', cwd: '/repo/app' }
})
transport.disconnect()
})
it('forwards the declined-resume signal on fresh and cold-restore spawns alike', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
spawn.mockResolvedValueOnce({ id: 'pty-1', agentResumeUnavailable: true })
const freshTransport = createIpcPtyTransport({})
await expect(freshTransport.connect({ url: '', callbacks: {} })).resolves.toEqual({
id: 'pty-1',
agentResumeUnavailable: true
})
freshTransport.disconnect()
spawn.mockResolvedValueOnce({
id: 'pty-2',
coldRestore: { scrollback: 'recovered', cwd: '/repo/app' },
agentResumeUnavailable: true
})
const coldTransport = createIpcPtyTransport({})
await expect(coldTransport.connect({ url: '', callbacks: {} })).resolves.toEqual(
expect.objectContaining({ id: 'pty-2', agentResumeUnavailable: true })
)
coldTransport.disconnect()
})
it('stops gone-parking a session whose cold restore resolves after its transport was destroyed', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const gone = await import('../../../terminal/terminal-provider-gone-sessions')
@@ -427,201 +114,4 @@ describe('createIpcPtyTransport', () => {
// Live again without an authoritative snapshot, so it must stay mounted where its own watchers run.
expect(canWatcherCoverParkedTerminalTab('repo::/wt', tab)).toBe(false)
})
it('passes startup commands through PTY spawn instead of writing them after connect', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawnMock = vi.fn().mockResolvedValue({ id: 'pty-1' })
const writeMock = vi.fn()
;(globalThis as { window: typeof window }).window = {
...originalWindow,
api: {
...originalWindow?.api,
pty: {
...originalWindow?.api?.pty,
spawn: spawnMock,
write: writeMock,
resize: vi.fn(),
kill: vi.fn(),
onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => {
onData = callback
return () => {}
}),
onReplay: vi.fn(() => () => {}),
onExit: vi.fn((callback: (payload: { id: string; code: number }) => void) => {
onExit = callback
return () => {}
})
}
}
} as unknown as typeof window
const transport = createIpcPtyTransport({
cwd: '/tmp/worktree',
env: { FOO: 'bar' },
command: 'echo hello'
})
await transport.connect({
url: '',
cols: 120,
rows: 40,
callbacks: {}
})
expect(spawnMock).toHaveBeenCalledWith({
cols: 120,
rows: 40,
cwd: '/tmp/worktree',
env: { FOO: 'bar' },
command: 'echo hello'
})
expect(writeMock).not.toHaveBeenCalled()
})
it('paints an old image and delayed live bytes once without claiming their newer frontier', async () => {
const { provenSpawnResponse } =
await import('../../../../../../shared/terminal/pty/lifecycle/terminal-spawn-response')
const { bindPtyConnectionTestMocks } =
await import('../../pty-connection/test-fixtures/pty-connection-mocks.spec')
const { createInitialStoreState } =
await import('../../pty-connection/test-fixtures/pty-connection-test-store-fixtures')
const { buildPaneConnectionDeps } =
await import('../../pty-connection/test-fixtures/pty-connection-test-deps')
const { createMockTransport, createPaneContainer, LEAF_1 } =
await import('../../pty-connection/test-fixtures/pty-connection-test-pane-fixtures')
const { Terminal } = await import('@xterm/xterm')
const { FitAddon } = await import('@xterm/addon-fit')
const { SearchAddon } = await import('@xterm/addon-search')
const { SerializeAddon } = await import('@xterm/addon-serialize')
const { PaneManager } = await import('@/lib/pane-manager/pane-manager')
const { isTerminalLeafId } =
await import('../../../../../../shared/workspace-layout/stable-pane-id')
const { installTerminalTestGlobals, restoreTerminalTestGlobals } =
await import('../../pty-connection/test-fixtures/pty-connection-test-environment')
const { flushAsyncTicks } =
await import('../../pty-connection/test-fixtures/pty-connection-test-async')
let state = createInitialStoreState(() => state)
const transports: ReturnType<typeof createMockTransport>[] = []
bindPtyConnectionTestMocks({
getState: () => state,
getTransportQueue: () => transports,
getTransportOptions: () => [],
getStoreSubscribers: () => [],
setStoreSubscribers: () => {}
})
await installTerminalTestGlobals()
try {
const { connectPanePty } = await import('../../pty-connection/connect-pane-pty')
const agentTitleMocks = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
for (const proof of ['interleaved', 'covered', 'no-flags'] as const) {
state = createInitialStoreState(() => state)
const result = provenSpawnResponse(
{
id: 'tab-pty',
isReattach: true,
snapshot: 'OLD',
providerSequence: { value: 900, generation: 'continued' as const },
...(proof !== 'no-flags' ? { snapshotKittyKeyboardFlags: 0 } : {})
},
proof === 'covered' ? 900 : undefined
)
const transport = createMockTransport('tab-pty')
let callbacks: ConnectCallbacks | undefined
transport.connect.mockImplementation(async (options: { callbacks?: ConnectCallbacks }) => {
callbacks = options.callbacks
return result
})
transports.push(transport)
const leafId: string = LEAF_1
if (!isTerminalLeafId(leafId)) {
throw new Error('Expected a terminal leaf UUID')
}
const terminal = new Terminal({
cols: 120,
rows: 40,
scrollback: 5_000,
allowProposedApi: true,
theme: { foreground: '#eeeeee', background: '#111111' },
vtExtensions: { kittyKeyboard: true }
})
const writes: string[] = []
const parseCallbacks: (() => void)[] = []
vi.spyOn(terminal, 'write').mockImplementation((data, callback) => {
writes.push(typeof data === 'string' ? data : new TextDecoder().decode(data))
if (callback) {
parseCallbacks.push(callback)
}
})
const container = createPaneContainer()
Object.defineProperty(container, 'querySelectorAll', { value: () => [] })
const pane: ManagedPane = {
id: 1,
leafId,
stablePaneId: leafId,
terminal,
container,
linkTooltip: createPaneContainer(),
fitAddon: new FitAddon(),
searchAddon: new SearchAddon(),
serializeAddon: new SerializeAddon()
}
vi.spyOn(pane.fitAddon, 'fit').mockImplementation(() => {})
vi.spyOn(pane.fitAddon, 'proposeDimensions').mockReturnValue({ cols: 120, rows: 40 })
const manager = new PaneManager(container, { linkOpenHint: () => '' })
vi.spyOn(manager, 'getPanes').mockReturnValue([pane])
vi.spyOn(manager, 'getLeafId').mockReturnValue(leafId)
vi.spyOn(manager, 'getNumericIdForLeaf').mockReturnValue(1)
const fixtureDeps = buildPaneConnectionDeps(() => state, {
isVisibleRef: { current: true },
restoredLeafId: LEAF_1,
restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' }
})
const deps: PtyConnectionDeps = {
...fixtureDeps,
paneTransportsRef: { current: new Map() },
paneMode2031Ref: { current: new Map() },
paneLastThemeModeRef: { current: new Map() },
replayingPanesRef: { current: new Map() },
syncPanePtyLayoutBinding: (paneId, ptyId) => {
if (ptyId !== null) {
fixtureDeps.syncPanePtyLayoutBinding(paneId, ptyId)
}
}
}
const binding = connectPanePty(
pane,
manager,
bindPaneAgentTitleMocks(deps, agentTitleMocks)
)
try {
await flushAsyncTicks(20)
for (let step = 0; step < 40; step += 1) {
parseCallbacks.shift()?.()
await flushAsyncTicks(2)
}
// The stream reaches main at 903 before the control reply; its delivery to this view is delayed until after OLD paints.
expect(writes.join('')).toContain('OLD')
callbacks?.onData?.('NEW', { seq: 903, rawLength: 3 })
for (let step = 0; step < 40; step += 1) {
parseCallbacks.shift()?.()
await flushAsyncTicks(2)
}
expect(writes.join('').match(/OLD/g), proof).toHaveLength(1)
expect(writes.join('').match(/NEW/g), proof).toHaveLength(1)
expect(result.snapshotSeq).toBe(proof === 'covered' ? 900 : undefined)
} finally {
binding.dispose()
manager.destroy()
pane.fitAddon.dispose()
pane.searchAddon.dispose()
pane.serializeAddon.dispose()
terminal.dispose()
}
}
} finally {
await restoreTerminalTestGlobals()
}
})
})
@@ -36,54 +36,6 @@ describe('createIpcPtyTransport', () => {
restorePtySpecWindow(originalWindow)
})
it('does not create a second kill authority when a mounted pane detaches', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const kill = window.api.pty.kill as unknown as ReturnType<typeof vi.fn>
const transport = createIpcPtyTransport({})
await transport.connect({ url: '', callbacks: {} })
transport.detach?.()
expect(kill).not.toHaveBeenCalled()
})
// Why: retained gauges would inflate every later high-water profile.
it.each(['detach', 'destroy'] as const)(
'drops its side-effect gauge from the census on %s',
async (teardown) => {
await import('../output/pty-side-effect-pending-census')
const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile')
const { createIpcPtyTransport } = await import('./pty-transport')
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
const transport = createIpcPtyTransport({})
await transport.connect({ url: '', callbacks: {} })
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1)
transport[teardown]?.()
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
}
)
// Why: teardown that already failed is exactly when a stranded gauge would pin the processor.
it('drops its side-effect gauge even when destroy throws mid-disconnect', async () => {
await import('../output/pty-side-effect-pending-census')
const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile')
const { createIpcPtyTransport } = await import('./pty-transport')
const kill = window.api.pty.kill as unknown as ReturnType<typeof vi.fn>
const transport = createIpcPtyTransport({})
await transport.connect({ url: '', callbacks: {} })
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1)
kill.mockImplementationOnce(() => {
throw new Error('ipc channel closed')
})
expect(() => transport.destroy?.()).toThrow('ipc channel closed')
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
})
it('keeps the live handler when detach() runs after a newer transport attached to the same PTY', async () => {
// Why: a new pane can attach the same ptyId before the old detaches; unconditional unregister deletes the live handler (frozen-pane bug).
const { createIpcPtyTransport } = await import('./pty-transport')
@@ -1,9 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
flushPtySideEffects,
installIpcPtyWindow,
restorePtySpecWindow
} from './pty-transport-test-harness'
import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness'
describe('createIpcPtyTransport', () => {
const originalWindow = (globalThis as { window?: typeof window }).window
@@ -30,63 +26,6 @@ describe('createIpcPtyTransport', () => {
restorePtySpecWindow(originalWindow)
})
it('suppresses attention side effects when replaying eager-buffered data during attach', async () => {
// Why: replayed eager output must not raise fresh alerts — bell/idle suppressed, title still restores.
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const onTitleChange = vi.fn()
const onBell = vi.fn()
const onAgentBecameIdle = vi.fn()
const handle = registerEagerPtyBuffer('pty-restored', vi.fn())
onData?.({
id: 'pty-restored',
data: ']0;. Claude working]0;* Claude done'
})
const transport = createIpcPtyTransport({
onTitleChange,
onBell,
onAgentBecameIdle
})
transport.attach({
existingPtyId: 'pty-restored',
callbacks: {}
})
expect(handle.flush()).toBe('')
await flushPtySideEffects()
expect(onTitleChange).toHaveBeenCalledWith('* Claude done', '* Claude done')
expect(onBell).not.toHaveBeenCalled()
expect(onAgentBecameIdle).not.toHaveBeenCalled()
})
it('resets replay parser state after deferred side effects drain', async () => {
// Why: cleanup must await deferred replay side effects, else a partial OSC makes the first live BEL look like an OSC terminator.
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const onBell = vi.fn()
registerEagerPtyBuffer('pty-restored', vi.fn())
onData?.({
id: 'pty-restored',
data: '\x1b]0;partial-title'
})
const transport = createIpcPtyTransport({ onBell })
transport.attach({
existingPtyId: 'pty-restored',
callbacks: {}
})
await flushPtySideEffects()
onData?.({ id: 'pty-restored', data: '\x07' })
await flushPtySideEffects()
expect(onBell).toHaveBeenCalledTimes(1)
})
it('keeps exit sidecars after eager-buffered PTYs attach to a terminal', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer, subscribeToPtyExit } =
@@ -107,36 +46,6 @@ describe('createIpcPtyTransport', () => {
expect(sidecarExit).toHaveBeenCalledWith(0, { hadPrimary: true })
})
it('bounds the eager buffer to its cap and keeps the most recent output', async () => {
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const cap = 512 * 1024
const handle = registerEagerPtyBuffer('pty-restored', vi.fn())
// 800 KB of chunks exceeds the 512 KB cap; earliest chunks drop while the prompt-bearing tail is kept.
for (let i = 0; i < 8; i += 1) {
onData?.({ id: 'pty-restored', data: String.fromCharCode(65 + i).repeat(100 * 1024) })
}
onData?.({ id: 'pty-restored', data: 'PROMPT$' })
const flushed = handle.flush()
expect(flushed.length).toBeLessThanOrEqual(cap)
expect(flushed.endsWith('PROMPT$')).toBe(true)
expect(flushed).not.toContain('A')
})
it('caps a single oversized eager chunk to its most-recent tail', async () => {
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const cap = 512 * 1024
const handle = registerEagerPtyBuffer('pty-restored', vi.fn())
// One chunk larger than the cap must not be stored whole.
onData?.({ id: 'pty-restored', data: `${'x'.repeat(cap)}TAIL$` })
const flushed = handle.flush()
expect(flushed.length).toBeLessThanOrEqual(cap)
expect(flushed.endsWith('TAIL$')).toBe(true)
})
it('drains pre-handler data and exit into eager buffers for fast background PTYs', async () => {
const { ensurePtyDispatcher, registerEagerPtyBuffer } =
await import('../delivery/pty-dispatcher')
@@ -153,62 +62,6 @@ describe('createIpcPtyTransport', () => {
expect(onEagerExit).toHaveBeenCalledWith('pty-fast-setup', 1)
})
it('enforces the eager buffer cap in UTF-8 bytes for multi-byte output', async () => {
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const cap = 512 * 1024
const handle = registerEagerPtyBuffer('pty-restored', vi.fn())
const output = `${'界'.repeat(cap)}PROMPT$`
const encodeSpy = vi.spyOn(TextEncoder.prototype, 'encode')
onData?.({ id: 'pty-restored', data: output })
const flushed = handle.flush()
expect(new TextEncoder().encode(flushed).byteLength).toBeLessThanOrEqual(cap)
expect(flushed.endsWith('PROMPT$')).toBe(true)
expect(encodeSpy).not.toHaveBeenCalledWith(output)
encodeSpy.mockRestore()
})
it('preserves a BOM when it starts the retained oversized eager-buffer tail', async () => {
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const cap = 512 * 1024
const handle = registerEagerPtyBuffer('pty-restored', vi.fn())
onData?.({ id: 'pty-restored', data: `${'x'.repeat(16)}\uFEFF${'y'.repeat(cap - 3)}` })
const flushed = handle.flush()
expect(new TextEncoder().encode(flushed).byteLength).toBe(cap)
expect(flushed.startsWith('\uFEFF')).toBe(true)
})
it('does not use Array.shift while trimming many eager chunks', async () => {
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const handle = registerEagerPtyBuffer('pty-restored', vi.fn())
const originalShift = Array.prototype.shift
try {
// Why: Array.shift() per trim reindexed the buffer, making many small chunks quadratic.
Object.defineProperty(Array.prototype, 'shift', {
configurable: true,
writable: true,
value() {
throw new Error('Array.shift should not be used by the eager buffer')
}
})
for (let i = 0; i < 2048; i += 1) {
onData?.({ id: 'pty-restored', data: 'x'.repeat(1024) })
}
} finally {
Object.defineProperty(Array.prototype, 'shift', {
configurable: true,
writable: true,
value: originalShift
})
}
expect(handle.flush().length).toBeLessThanOrEqual(512 * 1024)
})
it('routes eager-buffered bytes through onReplayData so the renderer can engage the replay guard', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
@@ -239,85 +92,6 @@ describe('createIpcPtyTransport', () => {
expect(onDataCallback).not.toHaveBeenCalledWith(bufferedPayload)
})
it('replays display-bearing eager-buffered output with default clear semantics', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const bufferedPayload = '\x1b[?1049hAutomation agent is running'
registerEagerPtyBuffer('pty-automation', vi.fn())
onData?.({
id: 'pty-automation',
data: bufferedPayload
})
const transport = createIpcPtyTransport()
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-automation',
callbacks: {
onReplayData
}
})
expect(onReplayData.mock.calls).toEqual([[bufferedPayload]])
})
it('does not clear before replaying title-only eager-buffered output', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const bufferedPayload = '\x1b]0;Restored title\x07'
registerEagerPtyBuffer('pty-title-only', vi.fn())
onData?.({
id: 'pty-title-only',
data: bufferedPayload
})
const onTitleChange = vi.fn()
const transport = createIpcPtyTransport({ onTitleChange })
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-title-only',
callbacks: {
onReplayData
}
})
// Why: title/control frames restore metadata but don't redraw, so clearing before them would erase persisted scrollback.
const clear = '\x1b[2J\x1b[3J\x1b[H'
expect(onReplayData.mock.calls).toEqual([[bufferedPayload, { clearBeforeReplay: false }]])
expect(onReplayData).not.toHaveBeenCalledWith(clear)
expect(onTitleChange).toHaveBeenCalledWith('Restored title', 'Restored title')
})
it('does not write an unterminated title-only eager buffer into replay', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const bufferedPayload = '\x1b]0;partial restored title'
registerEagerPtyBuffer('pty-partial-title', vi.fn())
onData?.({
id: 'pty-partial-title',
data: bufferedPayload
})
const transport = createIpcPtyTransport()
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-partial-title',
callbacks: {
onReplayData
}
})
const clear = '\x1b[2J\x1b[3J\x1b[H'
expect(onReplayData.mock.calls).toEqual([['', { clearBeforeReplay: false }]])
expect(onReplayData).not.toHaveBeenCalledWith(clear)
})
it('does not let an unterminated OSC 9999 eager buffer swallow live output', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
@@ -349,103 +123,4 @@ describe('createIpcPtyTransport', () => {
expect(onDataCallback).toHaveBeenCalledWith('live output')
})
it('does not clear before replaying OSC 9999-only eager-buffered output', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
registerEagerPtyBuffer('pty-status-only', vi.fn())
onData?.({
id: 'pty-status-only',
data: '\x1b]9999;{"state":"working","prompt":"ship it","agentType":"codex"}\x07'
})
const transport = createIpcPtyTransport()
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-status-only',
callbacks: {
onReplayData
}
})
// Why: OSC 9999 is stripped before xterm; a raw status frame must not clear restored scrollback and replay nothing.
const clear = '\x1b[2J\x1b[3J\x1b[H'
expect(onReplayData.mock.calls).toEqual([['', { clearBeforeReplay: false }]])
expect(onReplayData).not.toHaveBeenCalledWith(clear)
})
it('does not clear on attach when there is no eager-buffered output', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const transport = createIpcPtyTransport()
const onDataCallback = vi.fn()
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-attached',
callbacks: {
onData: onDataCallback,
onReplayData
}
})
// Why: restored scrollback may already be in xterm before attach; an empty eager buffer must not erase it.
expect(onReplayData).not.toHaveBeenCalled()
expect(onDataCallback).not.toHaveBeenCalled()
})
it('does not clear on attach when the eager buffer is empty', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
registerEagerPtyBuffer('pty-attached', vi.fn())
const transport = createIpcPtyTransport()
const onDataCallback = vi.fn()
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-attached',
callbacks: {
onData: onDataCallback,
onReplayData
}
})
// Why: a live PTY can have an eager handle before any bytes arrive; clearing would destroy scrollback restored at mount.
expect(onReplayData).not.toHaveBeenCalled()
expect(onDataCallback).not.toHaveBeenCalled()
})
it('skips the attach-time clear sequence for alternate-screen sessions', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher')
const bufferedPayload = '\x1b[?1049hAlternate screen is already restored'
registerEagerPtyBuffer('pty-alt-screen', vi.fn())
onData?.({
id: 'pty-alt-screen',
data: bufferedPayload
})
const transport = createIpcPtyTransport()
const onDataCallback = vi.fn()
const onReplayData = vi.fn()
transport.attach({
existingPtyId: 'pty-alt-screen',
isAlternateScreen: true,
callbacks: {
onData: onDataCallback,
onReplayData
}
})
// Why: alternate-screen snapshots already fill the viewport, so emitting the clear would erase restored content.
const clear = '\x1b[2J\x1b[3J\x1b[H'
expect(onReplayData.mock.calls).toEqual([[bufferedPayload, { clearBeforeReplay: false }]])
expect(onReplayData).not.toHaveBeenCalledWith(clear)
expect(onDataCallback).not.toHaveBeenCalledWith(clear)
})
})