fix(pty): close the exit race between send settlement and the next poll in both persistent shell tools
This commit is contained in:
1 parent
db208953b1
commit
974c340bb1
4 files changed
+146
-20
No files matched your search
@@ -197,6 +197,36 @@ function renderShellExitStatus(
|
||||
return appendStatusMarker(content, marker)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the exited-session result, reset the owner's shell, and reset the
|
||||
* message that tells the model the next call starts fresh.
|
||||
* @param shells - the owner-scoped registry to reset.
|
||||
* @param status - the exited session status (exit code and signal).
|
||||
* @returns the complete model-facing result.
|
||||
*/
|
||||
async function respondToSessionExit(
|
||||
ctx: Context,
|
||||
shells: PersistentShells,
|
||||
owner: Agent,
|
||||
id: PtySessionId,
|
||||
status: { exitCode: number | null; signal: NodeJS.Signals | null },
|
||||
marker: CommandMarkers,
|
||||
fallback: string,
|
||||
fallbackTruncated: boolean,
|
||||
config: ResolvedConfig,
|
||||
): Promise<string> {
|
||||
const snapshot = retainedScrollback(ctx, owner, id)
|
||||
await shells.reset(owner, 'persistent bash shell exited')
|
||||
return [
|
||||
renderShellExitStatus(
|
||||
renderCaptured(partialOutput(snapshot, marker, fallback, fallbackTruncated), config.maxOutputChars),
|
||||
status.exitCode,
|
||||
status.signal,
|
||||
),
|
||||
SHELL_RESET_MESSAGE,
|
||||
].filter(part => part.length > 0).join('\n')
|
||||
}
|
||||
|
||||
function persistentShells(ctx: Context, config: ResolvedConfig): PersistentShells {
|
||||
const pending = new WeakMap<Agent, Promise<PtySessionId>>()
|
||||
const live = new Map<Agent, PtySessionId>()
|
||||
@@ -286,6 +316,15 @@ async function executeCommand(
|
||||
let fallbackTruncated = false
|
||||
|
||||
while (true) {
|
||||
// The shell may flip to exited between iterations (a fast `exit` can
|
||||
// settle the previous send while its exit event is still in flight);
|
||||
// re-observing status before the next send closes that gap.
|
||||
const status = ctx.pty.list(owner).find(session => session.sessionId === id)?.status
|
||||
if (status?.kind === 'exited') {
|
||||
return await respondToSessionExit(
|
||||
ctx, shells, owner, id, status, marker, fallback, fallbackTruncated, config,
|
||||
)
|
||||
}
|
||||
let operation
|
||||
let result
|
||||
try {
|
||||
@@ -328,16 +367,9 @@ async function executeCommand(
|
||||
if (complete !== undefined) return renderCaptured(complete, config.maxOutputChars)
|
||||
}
|
||||
if (result.sessionStatus.kind === 'exited') {
|
||||
const snapshot = retainedScrollback(ctx, owner, id, latest)
|
||||
await shells.reset(owner, 'persistent bash shell exited')
|
||||
return [
|
||||
renderShellExitStatus(
|
||||
renderCaptured(partialOutput(snapshot, marker, fallback, fallbackTruncated), config.maxOutputChars),
|
||||
result.sessionStatus.exitCode,
|
||||
result.sessionStatus.signal,
|
||||
),
|
||||
SHELL_RESET_MESSAGE,
|
||||
].filter(part => part.length > 0).join('\n')
|
||||
return await respondToSessionExit(
|
||||
ctx, shells, owner, id, result.sessionStatus, marker, fallback, fallbackTruncated, config,
|
||||
)
|
||||
}
|
||||
if (promptCompleted(result)) {
|
||||
const snapshot = retainedScrollback(ctx, owner, id, latest)
|
||||
|
||||
@@ -98,6 +98,7 @@ type StubMode =
|
||||
| 'incremental-fallback'
|
||||
| 'empty-page-after-latest'
|
||||
| 'paged-scrollback'
|
||||
| 'exit-after-send'
|
||||
|
||||
class StubPtySession implements PtyBackendSession {
|
||||
readonly motd = '__DSH_PERSISTENT_BASH_PROMPT__ '
|
||||
@@ -109,6 +110,7 @@ class StubPtySession implements PtyBackendSession {
|
||||
sends = 0
|
||||
pendingText = ''
|
||||
historyTruncated = false
|
||||
throwOnSend = false
|
||||
|
||||
constructor(mode: StubMode) {
|
||||
this.mode = mode
|
||||
@@ -127,6 +129,7 @@ class StubPtySession implements PtyBackendSession {
|
||||
return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')))
|
||||
}
|
||||
if (this.mode === 'send-error') throw new Error('stub send failed')
|
||||
if (this.throwOnSend) throw new Error('PTY session has exited')
|
||||
if (this.mode === 'wait-for-abort' || this.mode === 'end-on-abort') {
|
||||
const done = new Promise<ReturnType<StubPtySession['result']>>((resolve) => {
|
||||
request.signal?.addEventListener('abort', () => {
|
||||
@@ -171,6 +174,18 @@ class StubPtySession implements PtyBackendSession {
|
||||
const incremental = `${start ?? ''}\nincrement\n${this.motd}`
|
||||
return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')), incremental)
|
||||
}
|
||||
if (this.mode === 'exit-after-send') {
|
||||
// A fast `exit` settles the send while the exit event is still in
|
||||
// flight; the shell flips to exited before the tool's next poll,
|
||||
// exactly like the real backend. The tool must re-observe status
|
||||
// instead of sending.
|
||||
const output = `${start ?? ''}\n`
|
||||
this.scrollback += output
|
||||
const settled = this.result(output, 'inferred_idle')
|
||||
this.statusValue = { kind: 'exited', exitCode: 9, signal: null }
|
||||
this.throwOnSend = true
|
||||
return this.operation(Promise.resolve(settled))
|
||||
}
|
||||
if (this.mode === 'torn-status') {
|
||||
const output = `${start ?? ''}\nhello from stub\n${end ?? ''}`
|
||||
this.scrollback += output
|
||||
@@ -397,6 +412,21 @@ describe('tool-bash-persistent', () => {
|
||||
expect(text(await call(ctx, owner, 'torn status'))).toBe('hello from stub\n[exit code: 7]')
|
||||
})
|
||||
|
||||
it('reports the exit path when the shell exits between send settlement and the next poll', async () => {
|
||||
const { ctx, owner, stub } = await setup({ backendType: 'stub' })
|
||||
await call(ctx, owner, 'warm up')
|
||||
const session = stub.sessions[0]!
|
||||
session.mode = 'exit-after-send'
|
||||
|
||||
const result = text(await call(ctx, owner, 'exit'))
|
||||
expect(result).toContain('[shell exited: code 9]')
|
||||
expect(result).toContain('next bash call starts from the workspace')
|
||||
expect(session.closed).toContain('persistent bash shell exited')
|
||||
|
||||
expect(text(await call(ctx, owner, 'echo "$PWD"'))).toBe('hello from stub')
|
||||
expect(stub.sessions).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('reports a shell exit when the backend has no code or signal', async () => {
|
||||
const { ctx, owner, stub } = await setup({ backendType: 'stub' })
|
||||
await call(ctx, owner, 'warm up')
|
||||
|
||||
@@ -219,6 +219,37 @@ function renderShellExitStatus(
|
||||
return appendStatusMarker(content, marker)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the exited-session result, reset the owner's shell, and reset the
|
||||
* message that tells the model the next call starts fresh.
|
||||
* @param shells - the owner-scoped registry to reset.
|
||||
* @param status - the exited session status (exit code and signal).
|
||||
* @returns the complete model-facing result.
|
||||
*/
|
||||
async function respondToSessionExit(
|
||||
ctx: Context,
|
||||
shells: PersistentShells,
|
||||
owner: Agent,
|
||||
id: PtySessionId,
|
||||
status: { exitCode: number | null; signal: NodeJS.Signals | null },
|
||||
marker: CommandMarkers,
|
||||
wrapped: string,
|
||||
fallback: string,
|
||||
fallbackTruncated: boolean,
|
||||
config: ResolvedConfig,
|
||||
): Promise<string> {
|
||||
const snapshot = retainedScrollback(ctx, owner, id)
|
||||
await shells.reset(owner, 'persistent pwsh shell exited')
|
||||
return [
|
||||
renderShellExitStatus(
|
||||
renderCaptured(partialOutput(snapshot, marker, wrapped, fallback, fallbackTruncated), config.maxOutputChars),
|
||||
status.exitCode,
|
||||
status.signal,
|
||||
),
|
||||
SHELL_RESET_MESSAGE,
|
||||
].filter(part => part.length > 0).join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* The pwsh prompt function that overrides the backend bootstrap value with
|
||||
* this tool's own prompt. `[char]27`/`[char]7` build the OSC bytes at runtime
|
||||
@@ -317,6 +348,16 @@ async function executeCommand(
|
||||
let fallbackTruncated = false
|
||||
|
||||
while (true) {
|
||||
// The shell may flip to exited between iterations (a fast `exit` can
|
||||
// settle the previous send while its exit event is still in flight, and
|
||||
// the echoed wrapper can then carry a marker end without status digits);
|
||||
// re-observing status before the next send closes that gap.
|
||||
const status = ctx.pty.list(owner).find(session => session.sessionId === id)?.status
|
||||
if (status?.kind === 'exited') {
|
||||
return await respondToSessionExit(
|
||||
ctx, shells, owner, id, status, marker, wrapped, fallback, fallbackTruncated, config,
|
||||
)
|
||||
}
|
||||
let operation
|
||||
let result
|
||||
try {
|
||||
@@ -359,16 +400,9 @@ async function executeCommand(
|
||||
if (complete !== undefined) return renderCaptured(complete, config.maxOutputChars)
|
||||
}
|
||||
if (result.sessionStatus.kind === 'exited') {
|
||||
const snapshot = retainedScrollback(ctx, owner, id, latest)
|
||||
await shells.reset(owner, 'persistent pwsh shell exited')
|
||||
return [
|
||||
renderShellExitStatus(
|
||||
renderCaptured(partialOutput(snapshot, marker, wrapped, fallback, fallbackTruncated), config.maxOutputChars),
|
||||
result.sessionStatus.exitCode,
|
||||
result.sessionStatus.signal,
|
||||
),
|
||||
SHELL_RESET_MESSAGE,
|
||||
].filter(part => part.length > 0).join('\n')
|
||||
return await respondToSessionExit(
|
||||
ctx, shells, owner, id, result.sessionStatus, marker, wrapped, fallback, fallbackTruncated, config,
|
||||
)
|
||||
}
|
||||
if (promptCompleted(result)) {
|
||||
const snapshot = retainedScrollback(ctx, owner, id, latest)
|
||||
|
||||
@@ -99,6 +99,7 @@ type StubMode =
|
||||
| 'empty-page-after-latest'
|
||||
| 'paged-scrollback'
|
||||
| 'with-echo'
|
||||
| 'exit-after-send'
|
||||
|
||||
const START_PATTERN = /__DSH_PERSISTENT_PWSH_START_[^_]+(?:-[^_]+)*__/
|
||||
const END_PATTERN = /__DSH_PERSISTENT_PWSH_END_[^:]+:/
|
||||
@@ -113,6 +114,7 @@ class StubPtySession implements PtyBackendSession {
|
||||
sends = 0
|
||||
pendingText = ''
|
||||
historyTruncated = false
|
||||
throwOnSend = false
|
||||
|
||||
constructor(mode: StubMode) {
|
||||
this.mode = mode
|
||||
@@ -131,6 +133,7 @@ class StubPtySession implements PtyBackendSession {
|
||||
return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')))
|
||||
}
|
||||
if (this.mode === 'send-error') throw new Error('stub send failed')
|
||||
if (this.throwOnSend) throw new Error('PTY session has exited')
|
||||
if (this.mode === 'wait-for-abort' || this.mode === 'end-on-abort') {
|
||||
const done = new Promise<ReturnType<StubPtySession['result']>>((resolve) => {
|
||||
request.signal?.addEventListener('abort', () => {
|
||||
@@ -178,6 +181,18 @@ class StubPtySession implements PtyBackendSession {
|
||||
this.scrollback += output
|
||||
return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
|
||||
}
|
||||
if (this.mode === 'exit-after-send') {
|
||||
// A fast `exit` settles the send with an echoed wrapper (marker end,
|
||||
// no status digits) while the exit event is still in flight; the shell
|
||||
// flips to exited before the tool's next poll, exactly like the real
|
||||
// ConPTY backend. The tool must re-observe status instead of sending.
|
||||
const output = `${sent}\n${start ?? ''}\n`
|
||||
this.scrollback += output
|
||||
const settled = this.result(output, 'inferred_idle')
|
||||
this.statusValue = { kind: 'exited', exitCode: 9, signal: null }
|
||||
this.throwOnSend = true
|
||||
return this.operation(Promise.resolve(settled))
|
||||
}
|
||||
if (this.mode === 'incremental-fallback') {
|
||||
const incremental = `${start ?? ''}\nincrement\n${this.motd}`
|
||||
return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')), incremental)
|
||||
@@ -347,6 +362,21 @@ describe('tool-pwsh-persistent', () => {
|
||||
expect(result).not.toContain('Invoke-Expression')
|
||||
})
|
||||
|
||||
it('reports the exit path when the shell exits between send settlement and the next poll', async () => {
|
||||
const { ctx, owner, stub } = await setup({ backendType: 'stub' })
|
||||
await call(ctx, owner, 'warm up')
|
||||
const session = stub.sessions[0]!
|
||||
session.mode = 'exit-after-send'
|
||||
|
||||
const result = text(await call(ctx, owner, 'exit'))
|
||||
expect(result).toContain('[shell exited: code 9]')
|
||||
expect(result).toContain('next pwsh call starts from the workspace')
|
||||
expect(session.closed).toContain('persistent pwsh shell exited')
|
||||
|
||||
expect(text(await call(ctx, owner, 'Write-Output "$PWD"'))).toBe('hello from stub')
|
||||
expect(stub.sessions).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('handles inferred idle, prompt fallback, shell exit, clipping, and cleanup', async () => {
|
||||
const { ctx, owner, stub, fiber } = await setup({
|
||||
backendType: 'stub',
|
||||
|
||||
Reference in new issue
Block a user