Prevent duplicate startup command echoes (#6023)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-21 18:51:44 -07:00
committed by GitHub
co-authored by Orca
parent 8228155e4d
commit 36bdd06aa8
16 changed files with 671 additions and 143 deletions
@@ -795,6 +795,27 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => {
expect(existsSync(join(historyDir, getHistorySessionDirName(id)))).toBe(true)
})
it('persists final take records that are not represented in the snapshot', async () => {
historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir })
const { id } = await historyAdapter.spawn({
cols: 80,
rows: 24,
cwd: '/home/user',
command: 'printf ready',
env: { SHELL: '/bin/zsh' },
sessionId: 'sleep-checkpoint-tail'
})
const appendSpy = vi.spyOn(historyAdapter.getHistoryManager()!, 'appendIncrements')
lastSubprocess._simulateData('\x1b]777;orca-shell-ready')
await historyAdapter.shutdown(id, { immediate: true, keepHistory: true })
expect(appendSpy).toHaveBeenCalledWith(id, expect.any(Number), [
{ kind: 'output', data: '\x1b]777;orca-shell-ready' }
])
})
it('returns cold restore data when disk history has unclean shutdown', async () => {
// Simulate a previous daemon crash: write history files without endedAt
const sessionId = 'cold-restore-test'
+30 -11
View File
@@ -297,7 +297,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
// Why: sleep/exact-stop must preserve restorable terminal history,
// so force a final checkpoint before killing the daemon session.
if (opts.keepHistory) {
await this.checkpointSessions([id], { final: true })
await this.checkpointSessions([id], { final: true, teardown: true })
}
await this.client.request('kill', { sessionId: id, immediate: opts.immediate ?? false })
this.activeSessionIds.delete(id)
@@ -675,7 +675,9 @@ export class DaemonPtyAdapter implements IPtyProvider {
// socket per session. Returns a promise that resolves when all checkpoint
// writes complete (callers that don't need to wait can void it).
// Why final=true here: this runs on clean disconnect, where the full-depth
// snapshot (not the increment log) must be the restore source.
// snapshot (not the increment log) must be the restore source. It is not a
// teardown snapshot: the detached daemon and its PTYs keep running for warm
// reattach, so shell-ready scanner state must remain intact.
private async checkpointAllSessions(): Promise<void> {
const completed = await this.checkpointSessions(this.activeSessionIds, { final: true })
for (const sessionId of completed) {
@@ -685,7 +687,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
private async checkpointSessions(
sessionIds: Iterable<string>,
opts?: { final?: boolean }
opts?: { final?: boolean; teardown?: boolean }
): Promise<Set<string>> {
const completed = new Set<string>()
if (!this.historyManager) {
@@ -702,7 +704,10 @@ export class DaemonPtyAdapter implements IPtyProvider {
return
}
const sessionId = ids[index]
await this.checkpointSession(sessionId, opts?.final === true)
await this.checkpointSession(sessionId, {
final: opts?.final === true,
teardown: opts?.teardown === true
})
.then(() => {
completed.add(sessionId)
})
@@ -719,7 +724,10 @@ export class DaemonPtyAdapter implements IPtyProvider {
return completed
}
private async checkpointSession(sessionId: string, final: boolean): Promise<void> {
private async checkpointSession(
sessionId: string,
opts: { final: boolean; teardown: boolean }
): Promise<void> {
if (!this.supportsIncrementalCheckpoints) {
const result = await this.client.request<GetSnapshotResult>('getSnapshot', { sessionId })
if (result.snapshot && this.historyManager) {
@@ -727,14 +735,14 @@ export class DaemonPtyAdapter implements IPtyProvider {
}
return
}
if (final || this.sessionsNeedingFullCheckpoint.has(sessionId)) {
if (opts.final || this.sessionsNeedingFullCheckpoint.has(sessionId)) {
// Why take-with-snapshot instead of plain getSnapshot: the take clears
// the daemon's pending records in the same synchronous turn as the
// serialize. A plain snapshot would leave pre-snapshot records pending;
// a later warm reattach would append them to the fresh log and cold
// restore would replay them on top of a checkpoint that already
// contains them.
await this.takeSnapshotAndCheckpoint(sessionId)
await this.takeSnapshotAndCheckpoint(sessionId, { teardown: opts.teardown })
this.sessionsNeedingFullCheckpoint.delete(sessionId)
return
}
@@ -747,7 +755,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
if (take.overflowed) {
// Why: overflow dropped records, so the log has a hole — only a full
// snapshot (which reflects everything ever written) can re-anchor it.
await this.takeSnapshotAndCheckpoint(sessionId)
await this.takeSnapshotAndCheckpoint(sessionId, { teardown: false })
return
}
if (take.records.length === 0) {
@@ -764,17 +772,28 @@ export class DaemonPtyAdapter implements IPtyProvider {
if (appendResult === 'needs-checkpoint') {
// Why dropping take.records is lossless: they were applied to the live
// emulator before the take, so the snapshot below contains them.
await this.takeSnapshotAndCheckpoint(sessionId)
await this.takeSnapshotAndCheckpoint(sessionId, { teardown: false })
}
}
private async takeSnapshotAndCheckpoint(sessionId: string): Promise<void> {
private async takeSnapshotAndCheckpoint(
sessionId: string,
opts: { teardown: boolean }
): Promise<void> {
const take = await this.client.request<TakePendingOutputResult | null>('takePendingOutput', {
sessionId,
includeSnapshot: true
includeSnapshot: true,
teardownSnapshot: opts.teardown
})
if (take?.snapshot && this.historyManager) {
await this.historyManager.checkpoint(sessionId, take.snapshot)
if (take.records.length > 0) {
// Why: take-with-snapshot usually returns no records because the
// snapshot subsumes them. Held parser-state bytes, such as an
// incomplete shell-ready marker prefix, are not representable in the
// snapshot and must remain as a post-checkpoint log tail.
await this.historyManager.appendIncrements(sessionId, take.seq, take.records)
}
}
}
+2 -1
View File
@@ -384,7 +384,8 @@ export class DaemonServer {
// those bytes on top of a snapshot that already contains them.
return this.host.takePendingOutput(
request.payload.sessionId,
request.payload.includeSnapshot === true
request.payload.includeSnapshot === true,
{ teardownSnapshot: request.payload.teardownSnapshot === true }
)
case 'ping':
@@ -34,6 +34,15 @@ describe('PostReadyFlushGate', () => {
expect(onFlush).toHaveBeenCalledTimes(1)
})
it('flushes via short delay when arm receives post-marker bytes evidence', () => {
gate.arm(true)
vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS - 1)
expect(onFlush).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(onFlush).toHaveBeenCalledTimes(1)
})
it('flushes via wall-clock fallback when no notifyData arrives', () => {
gate.arm()
@@ -41,6 +50,14 @@ describe('PostReadyFlushGate', () => {
expect(onFlush).toHaveBeenCalledTimes(1)
})
it('does not fallback at the old duplicate-echo race window', () => {
gate.arm()
vi.advanceTimersByTime(50)
expect(onFlush).not.toHaveBeenCalled()
})
it('ignores notifyData before arm()', () => {
gate.notifyData()
vi.advanceTimersByTime(1000)
+12 -8
View File
@@ -9,17 +9,17 @@
* redraws it under the prompt — producing a visible duplicate (e.g. "claude"
* appears twice on agent launch).
*
* Strategy: after arm() is called, wait for the next PTY data chunk (the
* prompt draw) plus a short delay for the tcsetattr() that enables raw mode.
* A wall-clock fallback covers the case where the prompt arrives in the same
* chunk as the marker, so no follow-up notifyData() ever fires.
* Strategy: after arm() is called, wait for prompt bytes plus a short delay
* for the tcsetattr() that enables raw mode. If the marker-completing scan
* already saw post-marker bytes, use that same short path immediately.
* A conservative wall-clock fallback covers ambiguous marker-only cases.
*
* Mirrors the gate in local-pty-shell-ready.ts::writeStartupCommandWhenShellReady,
* which solves the same race on the non-daemon path.
*/
export const POST_READY_FLUSH_DELAY_MS = 30
export const POST_READY_FLUSH_FALLBACK_MS = 50
export const POST_READY_FLUSH_FALLBACK_MS = 200
export class PostReadyFlushGate {
private awaitingPromptDraw = false
@@ -35,10 +35,14 @@ export class PostReadyFlushGate {
}
/** Arm the gate after observing the shell-ready marker. Starts the
* wall-clock fallback; the flush fires when the fallback elapses or when
* notifyData() observes a subsequent PTY data chunk. */
arm(): void {
* wall-clock fallback unless the marker scan already observed post-marker
* bytes, in which case the short post-data settle path is enough. */
arm(postMarkerBytesObserved = false): void {
this.awaitingPromptDraw = true
if (postMarkerBytesObserved) {
this.notifyData()
return
}
this.fallbackTimer = setTimeout(() => {
this.fallbackTimer = null
this.awaitingPromptDraw = false
+119
View File
@@ -207,6 +207,125 @@ describe('Session', () => {
expect(subprocess.written).toEqual(['first\n', 'second\n'])
})
it('uses the short settle path when marker and prompt bytes arrive together', () => {
createSession({ shellReadySupported: true })
session.write('codex\n')
subprocess.simulateData('\x1b]777;orca-shell-ready\x07\r\nuser@host $ ')
expect(session.shellState).toBe('ready' satisfies ShellReadyState)
vi.advanceTimersByTime(29)
expect(subprocess.written).toEqual([])
vi.advanceTimersByTime(1)
expect(subprocess.written).toEqual(['codex\n'])
})
it('does not treat bytes before the marker as post-marker prompt output', () => {
createSession({ shellReadySupported: true })
session.write('codex\n')
subprocess.simulateData('last login\r\n\x1b]777;orca-shell-ready\x07')
expect(session.shellState).toBe('ready' satisfies ShellReadyState)
vi.advanceTimersByTime(30)
expect(subprocess.written).toEqual([])
subprocess.simulateData('\r\nuser@host $ ')
vi.advanceTimersByTime(30)
expect(subprocess.written).toEqual(['codex\n'])
})
it('strips shell-ready marker bytes before client and pending-output fan-out', () => {
createSession({ shellReadySupported: true })
const received: string[] = []
session.attachClient({
onData: (data) => received.push(data),
onExit: () => {}
})
subprocess.simulateData('hello \x1b]777;orca-shell-ready\x07% ')
expect(received).toEqual(['hello % '])
expect(session.takePendingOutput(false)?.records).toEqual([
{ kind: 'output', data: 'hello % ' }
])
expect(session.getSnapshot()?.snapshotAnsi).toContain('hello % ')
expect(session.getSnapshot()?.snapshotAnsi).not.toContain('orca-shell-ready')
})
it('releases held marker-prefix bytes before flushing queued input on timeout', () => {
createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 })
const received: string[] = []
session.attachClient({
onData: (data) => received.push(data),
onExit: () => {}
})
subprocess.simulateData('\x1b]777;orca-shell-ready')
session.write('codex\n')
vi.advanceTimersByTime(100)
expect(session.shellState).toBe('timed_out' satisfies ShellReadyState)
expect(received).toEqual(['\x1b]777;orca-shell-ready'])
expect(session.takePendingOutput(false)?.records).toEqual([
{ kind: 'output', data: '\x1b]777;orca-shell-ready' }
])
expect(subprocess.written).toEqual(['codex\n'])
})
it('releases held marker-prefix bytes when the subprocess exits before readiness', () => {
createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 })
const received: string[] = []
session.attachClient({
onData: (data) => received.push(data),
onExit: () => {}
})
subprocess.simulateData('\x1b]777;orca-shell-ready')
subprocess.simulateExit(0)
expect(received).toEqual(['\x1b]777;orca-shell-ready'])
expect(session.takePendingOutput(false)?.records).toEqual([
{ kind: 'output', data: '\x1b]777;orca-shell-ready' }
])
})
it('keeps held marker-prefix bytes during live take-with-snapshot', () => {
createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 })
session.write('codex\n')
subprocess.simulateData('\x1b]777;orca-shell-ready')
const taken = session.takePendingOutput(true)
subprocess.simulateData('\x07\r\nuser@host $ ')
vi.advanceTimersByTime(30)
expect(taken?.records).toEqual([])
expect(taken?.snapshot).toBeTruthy()
expect(session.shellState).toBe('ready' satisfies ShellReadyState)
expect(subprocess.written).toEqual(['codex\n'])
})
it('releases held marker-prefix bytes before final take-with-snapshot', () => {
createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 })
subprocess.simulateData('\x1b]777;orca-shell-ready')
const taken = session.takePendingOutput(true, { teardownSnapshot: true })
expect(taken?.records).toEqual([{ kind: 'output', data: '\x1b]777;orca-shell-ready' }])
expect(taken?.snapshot).toBeTruthy()
})
it('cancels the post-ready flush gate when force-disposing the subprocess', () => {
createSession({ shellReadySupported: true })
session.write('codex\n')
subprocess.simulateData('\x1b]777;orca-shell-ready\x07')
expect(session.shellState).toBe('ready' satisfies ShellReadyState)
session.forceKillAndDisposeSubprocess()
vi.advanceTimersByTime(500)
expect(subprocess.written).toEqual([])
})
it('transitions to timed_out after 15 seconds', () => {
createSession({ shellReadySupported: true })
session.write('waiting input')
+60 -26
View File
@@ -2,6 +2,12 @@
import { HeadlessEmulator } from './headless-emulator'
import { isValidPtySize, normalizePtySize } from './daemon-pty-size'
import { PostReadyFlushGate } from './post-ready-flush-gate'
import {
createShellReadyScanState,
drainShellReadyHeldBytes,
scanForShellReady,
type ShellReadyScanState
} from '../shell-ready-marker-scanner'
import type {
PendingOutputRecord,
SessionState,
@@ -15,7 +21,6 @@ const SHELL_READY_TIMEOUT_MS = 15_000
// older daemon/local paths that still report shell-ready support for Codex.
export const CODEX_SHELL_READY_TIMEOUT_MS = 300
const KILL_TIMEOUT_MS = 5_000
const SHELL_READY_MARKER = '\x1b]777;orca-shell-ready\x07'
// Why: pending records exist so the 5s checkpoint can persist increments
// instead of re-serializing the whole buffer. If no client drains them (main
// process gone, history disabled), memory must stay bounded — past the cap we
@@ -81,7 +86,7 @@ export class Session {
private readonly onSessionExit?: (code: number) => void
private attachedClients: AttachedClient[] = []
private preReadyStdinQueue: string[] = []
private markerBuffer = ''
private shellReadyScanState: ShellReadyScanState | null = null
private shellReadyTimer: ReturnType<typeof setTimeout> | null = null
private killTimer: ReturnType<typeof setTimeout> | null = null
private postReadyFlushGate: PostReadyFlushGate
@@ -107,6 +112,7 @@ export class Session {
if (opts.shellReadySupported) {
this._shellState = 'pending'
this.shellReadyScanState = createShellReadyScanState()
this.shellReadyTimer = setTimeout(() => {
this.onShellReadyTimeout()
}, opts.shellReadyTimeoutMs ?? SHELL_READY_TIMEOUT_MS)
@@ -224,10 +230,15 @@ export class Session {
* when includeSnapshot is set, the serialize happens in the same turn so no
* PTY data can land between the drain and the snapshot (which would later
* be replayed twice on cold restore). */
takePendingOutput(includeSnapshot: boolean): TakePendingOutputResult | null {
takePendingOutput(
includeSnapshot: boolean,
opts: { teardownSnapshot?: boolean } = {}
): TakePendingOutputResult | null {
if (this._disposed) {
return null
}
const releasedHeldBytes =
includeSnapshot && opts.teardownSnapshot === true ? this.prepareForFinalSnapshot() : ''
const records = this.pendingOutputRecords
const overflowed = this.pendingOutputOverflowed
this.pendingOutputRecords = []
@@ -235,7 +246,11 @@ export class Session {
this.pendingOutputOverflowed = false
this.pendingOutputSeq += 1
return {
records: includeSnapshot ? [] : records,
records: includeSnapshot
? releasedHeldBytes
? [{ kind: 'output', data: releasedHeldBytes }]
: []
: records,
seq: this.pendingOutputSeq,
overflowed,
snapshot: includeSnapshot ? this.emulator.getSnapshot() : null
@@ -258,6 +273,10 @@ export class Session {
this.recordPendingOutput({ kind: 'clear' })
}
prepareForFinalSnapshot(): string {
return this.releaseHeldShellReadyBytes()
}
dispose(): void {
if (this._disposed) {
return
@@ -355,6 +374,9 @@ export class Session {
clearTimeout(this.shellReadyTimer)
this.shellReadyTimer = null
}
this.shellReadyScanState = null
this.preReadyStdinQueue = []
this.postReadyFlushGate.clear()
try {
this.subprocess.dispose()
} catch (err) {
@@ -392,16 +414,28 @@ export class Session {
return
}
// Feed data to headless emulator for state tracking
this.emulator.write(data)
this.recordPendingOutput({ kind: 'output', data })
if (this._shellState === 'pending') {
this.scanForShellMarker(data)
if (this._shellState === 'pending' && this.shellReadyScanState) {
const scanned = scanForShellReady(this.shellReadyScanState, data)
data = scanned.output
if (scanned.matched) {
this.transitionToReady(scanned.postMarkerBytesObserved)
}
} else {
this.postReadyFlushGate.notifyData()
}
this.emitSubprocessOutput(data)
}
private emitSubprocessOutput(data: string): void {
if (data.length === 0) {
return
}
// Feed data to headless emulator for state tracking
this.emulator.write(data)
this.recordPendingOutput({ kind: 'output', data })
// Broadcast to attached clients
for (const client of this.attachedClients) {
client.onData(data)
@@ -415,6 +449,7 @@ export class Session {
this._exitCode = code
this._state = 'exited'
this.releaseHeldShellReadyBytes()
if (this.killTimer) {
clearTimeout(this.killTimer)
@@ -448,25 +483,23 @@ export class Session {
this.onSessionExit?.(code)
}
private scanForShellMarker(data: string): void {
this.markerBuffer += data
const markerIdx = this.markerBuffer.indexOf(SHELL_READY_MARKER)
if (markerIdx !== -1) {
this.markerBuffer = ''
this.transitionToReady()
return
}
// Keep only the tail that could be the start of a partial marker match
const maxPartial = SHELL_READY_MARKER.length - 1
if (this.markerBuffer.length > maxPartial) {
this.markerBuffer = this.markerBuffer.slice(-maxPartial)
private releaseHeldShellReadyBytes(): string {
if (!this.shellReadyScanState) {
return ''
}
const heldBytes = drainShellReadyHeldBytes(this.shellReadyScanState)
this.shellReadyScanState = null
// Why: daemon scanning now runs before emulator/client fan-out so marker
// bytes can be stripped. If readiness never completes, preserve the
// previous behavior by releasing any held prefix before timeout or exit
// state changes discard it.
this.emitSubprocessOutput(heldBytes)
return heldBytes
}
private transitionToReady(): void {
private transitionToReady(postMarkerBytesObserved = false): void {
this._shellState = 'ready'
this.shellReadyScanState = null
if (this.shellReadyTimer) {
clearTimeout(this.shellReadyTimer)
this.shellReadyTimer = null
@@ -474,7 +507,7 @@ export class Session {
if (this.preReadyStdinQueue.length === 0) {
return
}
this.postReadyFlushGate.arm()
this.postReadyFlushGate.arm(postMarkerBytesObserved)
}
private onShellReadyTimeout(): void {
@@ -483,6 +516,7 @@ export class Session {
return
}
this._shellState = 'timed_out'
this.releaseHeldShellReadyBytes()
this.flushPreReadyQueue()
}
+48
View File
@@ -169,6 +169,31 @@ describe('TerminalHost', () => {
)
})
it('uses the short daemon settle path when marker and prompt arrive together', async () => {
vi.useFakeTimers()
try {
await host.createOrAttach({
sessionId: 'session-1',
cols: 80,
rows: 24,
command: 'echo hello',
shellReadySupported: true,
streamClient: { onData: vi.fn(), onExit: vi.fn() }
})
lastSubprocess._onDataCb?.('\x1b]777;orca-shell-ready\x07\r\nuser@host $ ')
vi.advanceTimersByTime(29)
expect(lastSubprocess.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(lastSubprocess.write).toHaveBeenCalledWith(
process.platform === 'win32' ? 'echo hello\r' : 'echo hello\n'
)
} finally {
vi.useRealTimers()
}
})
it('does not write startup commands already embedded in shell args', async () => {
spawnFn = vi.fn(() => {
const sub = createMockSubprocess({
@@ -386,6 +411,29 @@ describe('TerminalHost', () => {
expect(lastSubprocess.dispose).toHaveBeenCalled()
})
it('releases held shell-ready marker prefixes before final checkpoint', async () => {
host.dispose()
const onFinalCheckpoint = vi.fn()
host = new TerminalHost({
spawnSubprocess: spawnFn as MockSpawnFn,
onFinalCheckpoint
})
await host.createOrAttach({
sessionId: 'session-1',
cols: 80,
rows: 24,
shellReadySupported: true,
streamClient: { onData: vi.fn(), onExit: vi.fn() }
})
lastSubprocess._onDataCb?.('\x1b]777;orca-shell-ready')
host.dispose()
expect(onFinalCheckpoint).toHaveBeenCalledWith('session-1', expect.any(Object), [
{ kind: 'output', data: '\x1b]777;orca-shell-ready' }
])
})
it('does not list exited sessions', async () => {
await host.createOrAttach({
sessionId: 'session-1',
+14 -6
View File
@@ -58,7 +58,11 @@ export type TerminalHostOptions = {
// Why: on graceful shutdown, the host writes final checkpoints for all live
// sessions before killing them. This bypasses the RPC round-trip — the daemon
// writes checkpoints in-process, guaranteeing completion before teardown.
onFinalCheckpoint?: (sessionId: string, snapshot: TerminalSnapshot) => void
onFinalCheckpoint?: (
sessionId: string,
snapshot: TerminalSnapshot,
records: TakePendingOutputResult['records']
) => void
// Why: production keeps a large cap, but tests need a small deterministic cap
// without spawning thousands of full terminal sessions.
maxTombstones?: number
@@ -258,12 +262,16 @@ export class TerminalHost {
// Why: same null-not-throw semantics as getSnapshot — incremental
// checkpoints are best-effort against sessions that may have just exited.
takePendingOutput(sessionId: string, includeSnapshot: boolean): TakePendingOutputResult | null {
takePendingOutput(
sessionId: string,
includeSnapshot: boolean,
opts: { teardownSnapshot?: boolean } = {}
): TakePendingOutputResult | null {
const session = this.sessions.get(sessionId)
if (!session || !session.isAlive) {
return null
}
return session.takePendingOutput(includeSnapshot)
return session.takePendingOutput(includeSnapshot, opts)
}
isKilled(sessionId: string): boolean {
@@ -300,10 +308,10 @@ export class TerminalHost {
if (!session.isAlive) {
continue
}
const snapshot = session.getSnapshot()
if (snapshot) {
const take = session.takePendingOutput(true, { teardownSnapshot: true })
if (take?.snapshot) {
try {
this.onFinalCheckpoint(sessionId, snapshot)
this.onFinalCheckpoint(sessionId, take.snapshot, take.records)
} catch {
// Best-effort — don't block shutdown
}
+7 -2
View File
@@ -7,9 +7,9 @@ import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery
// when daemon-baked behavior cannot be delivered by on-disk wrapper refresh.
// Why: bump when adding daemon wire behavior so same-version old daemons do
// not silently accept the handshake and then reject new RPCs.
export const PROTOCOL_VERSION = 17
export const PROTOCOL_VERSION = 18
export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17
] as const
// ─── Session State Machine ──────────────────────────────────────────
@@ -246,6 +246,11 @@ export type TakePendingOutputRequest = {
* snapshot taken in a separate request could include bytes that a later
* take would replay again, duplicating content on cold restore. */
includeSnapshot?: boolean
/** True only for final checkpoints taken immediately before PTY teardown.
* This lets the daemon release pending parser-state bytes that should be
* preserved before the backing PTY is destroyed, without disturbing live
* full checkpoints or warm-reconnect checkpoints. */
teardownSnapshot?: boolean
}
}
+34 -2
View File
@@ -5055,11 +5055,11 @@ describe('registerPtyHandlers', () => {
mockProc.emitData('\x1b]777;orca-shell-ready\x07')
await Promise.resolve()
vi.advanceTimersByTime(49)
vi.advanceTimersByTime(50)
await Promise.resolve()
expect(mockProc.proc.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(mockProc.proc.write).toHaveBeenCalledWith("codex 'linked issue context'\n")
} finally {
@@ -5067,6 +5067,38 @@ describe('registerPtyHandlers', () => {
}
})
posixOnlyIt(
'uses the short settle path for delivery-hinted Codex when prompt follows the marker',
async () => {
vi.useFakeTimers()
const mockProc = createMockProc()
spawnMock.mockReturnValue(mockProc.proc)
try {
registerPtyHandlers(mainWindow as never)
await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp',
command: "codex 'linked issue context'",
startupCommandDelivery: 'shell-ready'
})
mockProc.emitData('\x1b]777;orca-shell-ready\x07\r\nuser@host % ')
await Promise.resolve()
vi.advanceTimersByTime(29)
await Promise.resolve()
expect(mockProc.proc.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
await Promise.resolve()
expect(mockProc.proc.write).toHaveBeenCalledWith("codex 'linked issue context'\n")
} finally {
vi.useRealTimers()
}
}
)
posixOnlyIt('waits for shell-ready when Codex uses the native prefill flag', async () => {
vi.useFakeTimers()
const mockProc = createMockProc()
+75 -2
View File
@@ -95,9 +95,16 @@ describe('LocalPtyProvider', () => {
exitCb = undefined
mockProc = {
onData: vi.fn(),
onData: vi.fn(() => ({ dispose: vi.fn() })),
onExit: vi.fn((cb: (info: { exitCode: number }) => void) => {
exitCb = cb
return {
dispose: () => {
if (exitCb === cb) {
exitCb = undefined
}
}
}
}),
write: vi.fn(),
resize: vi.fn(),
@@ -211,15 +218,66 @@ describe('LocalPtyProvider', () => {
const dataCallback = mockProc.onData.mock.calls[0]?.[0] as (data: string) => void
dataCallback('\x1b]777;orca-shell-ready\x07user@host % ')
await Promise.resolve()
vi.advanceTimersByTime(50)
vi.advanceTimersByTime(29)
await Promise.resolve()
expect(mockProc.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
await Promise.resolve()
expect(mockProc.write).toHaveBeenCalledWith("printf 'linked issue context'\n")
} finally {
vi.useRealTimers()
}
})
it('releases held marker-prefix bytes when local shell readiness times out', async () => {
vi.useFakeTimers()
const onData = vi.fn()
provider.configure({ onData })
try {
await provider.spawn({ cols: 80, rows: 24, command: 'printf ready' })
const dataCallback = mockProc.onData.mock.calls[0]?.[0] as (data: string) => void
dataCallback('\x1b]777;orca-shell-ready')
expect(onData).not.toHaveBeenCalled()
vi.advanceTimersByTime(1500)
await Promise.resolve()
expect(onData).toHaveBeenCalledWith(
expect.any(String),
'\x1b]777;orca-shell-ready',
expect.any(Number)
)
expect(mockProc.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(200)
await Promise.resolve()
expect(mockProc.write).toHaveBeenCalledWith('printf ready\n')
} finally {
vi.useRealTimers()
}
})
it('releases held marker-prefix bytes when local shell exits before readiness', async () => {
const onData = vi.fn()
provider.configure({ onData })
await provider.spawn({ cols: 80, rows: 24, command: 'printf ready' })
const dataCallback = mockProc.onData.mock.calls[0]?.[0] as (data: string) => void
dataCallback('\x1b]777;orca-shell-ready')
expect(onData).not.toHaveBeenCalled()
exitCb?.({ exitCode: 0 })
expect(onData).toHaveBeenCalledWith(
expect.any(String),
'\x1b]777;orca-shell-ready',
expect.any(Number)
)
})
it('honors explicit terminal env overrides after deleting requested defaults', async () => {
provider.configure({
buildSpawnEnv: (_id, env) => {
@@ -662,6 +720,21 @@ describe('LocalPtyProvider', () => {
expect(destroySpy).not.toHaveBeenCalled()
})
it('cancels pending shell-ready startup delivery on forced shutdown', async () => {
vi.useFakeTimers()
try {
const { id } = await provider.spawn({ cols: 80, rows: 24, command: 'printf ready' })
await provider.shutdown(id, { immediate: true })
vi.advanceTimersByTime(2000)
await Promise.resolve()
expect(mockProc.write).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('is a no-op for unknown PTY ids', async () => {
await provider.shutdown('nonexistent', { immediate: true })
expect(mockProc.kill).not.toHaveBeenCalled()
+52 -14
View File
@@ -26,10 +26,12 @@ import {
getAttributionShellLaunchConfig,
getShellReadyLaunchConfig,
createShellReadyScanState,
drainShellReadyHeldBytes,
scanForShellReady,
writeStartupCommandWhenShellReady,
STARTUP_COMMAND_READY_MAX_WAIT_MS
} from './local-pty-shell-ready'
import type { ShellReadySignal } from './local-pty-shell-ready'
import { removeInheritedNoColor } from '../pty/terminal-color-env'
import { isHostCodexHomeForWsl, isWslCodexHomeForHost } from '../pty/codex-home-wsl-env'
import { addWslEnvKeys } from '../wsl-env'
@@ -60,6 +62,7 @@ const ptyAgentForegroundContextPaths = new Map<string, string[]>()
// stale callbacks survive into node::FreeEnvironment() where NAPI attempts
// to invoke/clean them up on a destroyed environment, triggering a SIGABRT.
const ptyDisposables = new Map<string, { dispose: () => void }[]>()
const ptyCleanupCallbacks = new Map<string, () => void>()
let loadGeneration = 0
const ptyLoadGeneration = new Map<string, number>()
@@ -135,6 +138,15 @@ function disposePtyListeners(id: string): void {
}
}
function runPtyCleanup(id: string): void {
const cleanup = ptyCleanupCallbacks.get(id)
if (!cleanup) {
return
}
ptyCleanupCallbacks.delete(id)
cleanup()
}
/**
* Resolves a WSL context from a worktree id whose path is already a WSL path.
*/
@@ -160,6 +172,7 @@ function getWslContextFromPreferredDistro(
* Removes all local tracking state for a PTY id after teardown.
*/
function clearPtyState(id: string): void {
runPtyCleanup(id)
disposePtyListeners(id)
ptyProcesses.delete(id)
ptyShellName.delete(id)
@@ -249,6 +262,7 @@ function destroyPtyProcess(proc: pty.IPty, options: { alreadyKilled?: boolean }
* Kills a local PTY and clears all associated local provider state.
*/
function safeKillAndClean(id: string, proc: pty.IPty): void {
runPtyCleanup(id)
disposePtyListeners(id)
try {
proc.kill()
@@ -618,17 +632,17 @@ export class LocalPtyProvider implements IPtyProvider {
this.opts.onSpawned?.(id)
// Shell-ready startup command support
let resolveShellReady: (() => void) | null = null
let resolveShellReady: ((signal: ShellReadySignal) => void) | null = null
let shellReadyTimeout: ReturnType<typeof setTimeout> | null = null
const shellReadyScanState = shellReadyLaunch?.supportsReadyMarker
? createShellReadyScanState()
: null
const shellReadyPromise = args.command
? new Promise<void>((resolve) => {
? new Promise<ShellReadySignal>((resolve) => {
resolveShellReady = resolve
})
: Promise.resolve()
const finishShellReady = (): void => {
: Promise.resolve({ postMarkerBytesObserved: false })
const finishShellReady = (signal: ShellReadySignal): void => {
if (!resolveShellReady) {
return
}
@@ -638,18 +652,44 @@ export class LocalPtyProvider implements IPtyProvider {
}
const resolve = resolveShellReady
resolveShellReady = null
resolve()
resolve(signal)
}
const releaseHeldShellReadyBytes = (): void => {
if (!shellReadyScanState) {
return
}
const heldBytes = drainShellReadyHeldBytes(shellReadyScanState)
if (heldBytes.length === 0) {
return
}
this.opts.onData?.(id, heldBytes, Date.now())
for (const cb of dataListeners) {
cb({ id, data: heldBytes })
}
}
if (args.command) {
if (shellReadyLaunch?.supportsReadyMarker) {
shellReadyTimeout = setTimeout(() => {
finishShellReady()
releaseHeldShellReadyBytes()
finishShellReady({ postMarkerBytesObserved: false })
}, STARTUP_COMMAND_READY_MAX_WAIT_MS)
} else {
finishShellReady()
finishShellReady({ postMarkerBytesObserved: false })
}
}
let startupCommandCleanup: (() => void) | null = null
if (args.command) {
ptyCleanupCallbacks.set(id, () => {
if (shellReadyTimeout) {
clearTimeout(shellReadyTimeout)
shellReadyTimeout = null
}
releaseHeldShellReadyBytes()
startupCommandCleanup?.()
startupCommandCleanup = null
resolveShellReady = null
})
}
const disposables: { dispose: () => void }[] = []
const onDataDisposable = proc.onData((rawData) => {
@@ -658,7 +698,7 @@ export class LocalPtyProvider implements IPtyProvider {
const scanned = scanForShellReady(shellReadyScanState, rawData)
data = scanned.output
if (scanned.matched) {
finishShellReady()
finishShellReady({ postMarkerBytesObserved: scanned.postMarkerBytesObserved })
}
}
if (data.length === 0) {
@@ -740,8 +780,9 @@ export class LocalPtyProvider implements IPtyProvider {
// Why: disposePtyListeners removes the onExit callback, so the natural
// exit cleanup path from node-pty won't fire. Cleanup and notification
// must happen unconditionally after the try/catch.
// Note: clearPtyState calls disposePtyListeners internally, so we only
// need to call it once via clearPtyState after killing the process.
// Timer/writer cleanup must happen here too: disposing listeners prevents
// the natural onExit callback from running the usual clearPtyState path.
runPtyCleanup(id)
disposePtyListeners(id)
try {
proc.kill()
@@ -749,10 +790,7 @@ export class LocalPtyProvider implements IPtyProvider {
/* Process may already be dead */
}
destroyPtyProcess(proc, { alreadyKilled: true })
ptyProcesses.delete(id)
ptyShellName.delete(id)
ptyAgentForegroundContextPaths.delete(id)
ptyLoadGeneration.delete(id)
clearPtyState(id)
this.opts.onExit?.(id, -1)
for (const cb of exitListeners) {
cb({ id, code: -1 })
@@ -97,9 +97,8 @@ describe('writeStartupCommandWhenShellReady', () => {
writeStartupCommandWhenShellReady(ready, proc, 'claude', () => {})
await ready
// flush path waits for a post-ready data chunk (prompt draw) then 30ms,
// or falls back after 50ms if no data arrives.
vi.advanceTimersByTime(50)
proc._emitData('\r\nuser@host % ')
vi.advanceTimersByTime(30)
await Promise.resolve()
expect(proc._writes).toEqual(['claude\n'])
@@ -112,7 +111,8 @@ describe('writeStartupCommandWhenShellReady', () => {
writeStartupCommandWhenShellReady(ready, proc, 'claude', () => {})
await ready
vi.advanceTimersByTime(50)
proc._emitData('\r\nPS> ')
vi.advanceTimersByTime(30)
await Promise.resolve()
expect(proc._writes).toEqual(['claude\r'])
@@ -125,11 +125,46 @@ describe('writeStartupCommandWhenShellReady', () => {
writeStartupCommandWhenShellReady(ready, proc, 'claude\n', () => {})
await ready
vi.advanceTimersByTime(50)
proc._emitData('\r\nPS> ')
vi.advanceTimersByTime(30)
await Promise.resolve()
expect(proc._writes).toEqual(['claude\n'])
})
it('keeps the no-prompt fallback conservative to avoid duplicate shell echo', async () => {
Object.defineProperty(process, 'platform', { value: 'darwin' })
const proc = createMockProc()
const ready = Promise.resolve()
writeStartupCommandWhenShellReady(ready, proc, 'codex', () => {})
await ready
vi.advanceTimersByTime(50)
await Promise.resolve()
expect(proc._writes).toEqual([])
vi.advanceTimersByTime(150)
await Promise.resolve()
expect(proc._writes).toEqual(['codex\n'])
})
it('uses the short settle delay when marker scan already observed post-marker bytes', async () => {
Object.defineProperty(process, 'platform', { value: 'darwin' })
const proc = createMockProc()
const ready = Promise.resolve({ postMarkerBytesObserved: true })
writeStartupCommandWhenShellReady(ready, proc, 'codex', () => {})
await ready
vi.advanceTimersByTime(29)
await Promise.resolve()
expect(proc._writes).toEqual([])
vi.advanceTimersByTime(1)
await Promise.resolve()
expect(proc._writes).toEqual(['codex\n'])
})
})
describe('scanForShellReady', () => {
@@ -138,11 +173,53 @@ describe('scanForShellReady', () => {
expect(scanForShellReady(state, 'before \x1b]777;orca-shell-readyx')).toEqual({
output: 'before \x1b]777;orca-shell-readyx',
matched: false
matched: false,
postMarkerBytesObserved: false
})
expect(scanForShellReady(state, ' after')).toEqual({
output: ' after',
matched: false
matched: false,
postMarkerBytesObserved: false
})
})
it('reports post-marker bytes only when bytes follow the BEL terminator in the matching call', () => {
let state = createShellReadyScanState()
expect(scanForShellReady(state, 'before \x1b]777;orca-shell-ready\x07')).toEqual({
output: 'before ',
matched: true,
postMarkerBytesObserved: false
})
state = createShellReadyScanState()
expect(scanForShellReady(state, 'before \x1b]777;orca-shell-ready\x07% ')).toEqual({
output: 'before % ',
matched: true,
postMarkerBytesObserved: true
})
state = createShellReadyScanState()
expect(scanForShellReady(state, 'before \x1b]777;orca-shell-ready')).toEqual({
output: 'before ',
matched: false,
postMarkerBytesObserved: false
})
expect(scanForShellReady(state, '\x07')).toEqual({
output: '',
matched: true,
postMarkerBytesObserved: false
})
state = createShellReadyScanState()
expect(scanForShellReady(state, '\x1b]777;orca-shell-ready')).toEqual({
output: '',
matched: false,
postMarkerBytesObserved: false
})
expect(scanForShellReady(state, '\x07% ')).toEqual({
output: '% ',
matched: true,
postMarkerBytesObserved: true
})
})
})
+27 -64
View File
@@ -27,66 +27,23 @@ import {
getZshShellReadyMarkerRegistrationBlock,
getZshStartupFileSourceBlock
} from '../shell-templates'
export {
createShellReadyScanState,
drainShellReadyHeldBytes,
scanForShellReady,
SHELL_READY_MARKER_PREFIX
} from '../shell-ready-marker-scanner'
export type { ShellReadyScanResult, ShellReadyScanState } from '../shell-ready-marker-scanner'
let didEnsureShellReadyWrappers = false
const STARTUP_COMMAND_READY_MAX_WAIT_MS = 1500
const SHELL_READY_MARKER = '\x1b]777;orca-shell-ready'
const POST_SHELL_READY_STARTUP_COMMAND_DELAY_MS = 30
const POST_SHELL_READY_STARTUP_COMMAND_FALLBACK_MS = 200
const SHELL_READY_MARKER_ESCAPED = '\\033]777;orca-shell-ready\\007'
// ── OSC 777 shell-ready scanner ─────────────────────────────────────
export type ShellReadyScanState = {
matchPos: number
heldBytes: string
}
export function createShellReadyScanState(): ShellReadyScanState {
return { matchPos: 0, heldBytes: '' }
}
export function scanForShellReady(
state: ShellReadyScanState,
data: string
): { output: string; matched: boolean } {
let output = ''
for (let i = 0; i < data.length; i += 1) {
const ch = data[i] as string
if (state.matchPos < SHELL_READY_MARKER.length) {
if (ch === SHELL_READY_MARKER[state.matchPos]) {
state.heldBytes += ch
state.matchPos += 1
} else {
output += state.heldBytes
state.heldBytes = ''
state.matchPos = 0
if (ch === SHELL_READY_MARKER[0]) {
state.heldBytes = ch
state.matchPos = 1
} else {
output += ch
}
}
} else if (ch === '\x07') {
const remaining = data.slice(i + 1)
state.heldBytes = ''
state.matchPos = 0
return { output: output + remaining, matched: true }
} else {
output += state.heldBytes
state.heldBytes = ''
state.matchPos = 0
if (ch === SHELL_READY_MARKER[0]) {
state.heldBytes = ch
state.matchPos = 1
} else {
output += ch
}
}
}
return { output, matched: false }
export type ShellReadySignal = {
postMarkerBytesObserved: boolean
}
// ── Shell wrapper files ─────────────────────────────────────────────
@@ -469,7 +426,7 @@ export function getAttributionShellLaunchConfig(shellPath: string): ShellReadyLa
// ── Startup command writer ──────────────────────────────────────────
export function writeStartupCommandWhenShellReady(
readyPromise: Promise<void>,
readyPromise: Promise<void | ShellReadySignal>,
proc: pty.IPty,
startupCommand: string,
onExit: (cleanup: () => void) => void
@@ -518,7 +475,11 @@ export function writeStartupCommandWhenShellReady(
proc.write(payload)
}
readyPromise.then(() => {
const schedulePostReadyFlush = (): void => {
postReadyTimer = setTimeout(flush, POST_SHELL_READY_STARTUP_COMMAND_DELAY_MS)
}
readyPromise.then((signal) => {
if (sent) {
return
}
@@ -528,26 +489,28 @@ export function writeStartupCommandWhenShellReady(
// causes the characters to be echoed once by the kernel and then redisplayed
// by the line editor after the prompt — producing a visible duplicate.
//
// Strategy: wait for the next PTY data event after the ready marker. That
// data is the shell drawing its prompt, which means the shell is about to
// (or has already) switched to raw mode. A brief follow-up delay covers the
// gap between the last prompt write() and the tcsetattr() that enables raw
// mode. The 50ms fallback timeout handles the case where the prompt data
// arrived in the same chunk as the ready marker (no subsequent onData).
// Strategy: if the marker-completing scan already observed post-marker
// bytes, use the short settle delay directly. Otherwise, wait for the next
// PTY data event after the ready marker, with a conservative fallback for
// ambiguous marker-only or markerless cases.
if (signal?.postMarkerBytesObserved === true) {
schedulePostReadyFlush()
return
}
postReadyDataDisposable = proc.onData(() => {
postReadyDataDisposable?.dispose()
postReadyDataDisposable = null
if (postReadyTimer !== null) {
clearTimeout(postReadyTimer)
}
postReadyTimer = setTimeout(flush, 30)
schedulePostReadyFlush()
})
postReadyTimer = setTimeout(() => {
postReadyDataDisposable?.dispose()
postReadyDataDisposable = null
postReadyTimer = null
flush()
}, 50)
}, POST_SHELL_READY_STARTUP_COMMAND_FALLBACK_MS)
})
onExit(cleanup)
}
+69
View File
@@ -0,0 +1,69 @@
export const SHELL_READY_MARKER_PREFIX = '\x1b]777;orca-shell-ready'
export const SHELL_READY_MARKER = `${SHELL_READY_MARKER_PREFIX}\x07`
export type ShellReadyScanState = {
matchPos: number
heldBytes: string
}
export type ShellReadyScanResult = {
output: string
matched: boolean
postMarkerBytesObserved: boolean
}
export function createShellReadyScanState(): ShellReadyScanState {
return { matchPos: 0, heldBytes: '' }
}
export function drainShellReadyHeldBytes(state: ShellReadyScanState): string {
const heldBytes = state.heldBytes
state.heldBytes = ''
state.matchPos = 0
return heldBytes
}
export function scanForShellReady(state: ShellReadyScanState, data: string): ShellReadyScanResult {
let output = ''
for (let i = 0; i < data.length; i += 1) {
const ch = data[i] as string
if (state.matchPos < SHELL_READY_MARKER_PREFIX.length) {
if (ch === SHELL_READY_MARKER_PREFIX[state.matchPos]) {
state.heldBytes += ch
state.matchPos += 1
} else {
output += state.heldBytes
state.heldBytes = ''
state.matchPos = 0
if (ch === SHELL_READY_MARKER_PREFIX[0]) {
state.heldBytes = ch
state.matchPos = 1
} else {
output += ch
}
}
} else if (ch === '\x07') {
const remaining = data.slice(i + 1)
state.heldBytes = ''
state.matchPos = 0
return {
output: output + remaining,
matched: true,
postMarkerBytesObserved: remaining.length > 0
}
} else {
output += state.heldBytes
state.heldBytes = ''
state.matchPos = 0
if (ch === SHELL_READY_MARKER_PREFIX[0]) {
state.heldBytes = ch
state.matchPos = 1
} else {
output += ch
}
}
}
return { output, matched: false, postMarkerBytesObserved: false }
}