Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-local-process-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/ai-sandbox-local-process': patch
---

Fix local-process spawn handles hanging when the child exits before `wait()` is called.
13 changes: 8 additions & 5 deletions packages/ai-sandbox-local-process/src/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,13 @@ export class LocalProcessHandle implements SandboxHandle {
once: true,
})
}
const closed = new Promise<number>((resolve, reject) => {
child.once('error', reject)
child.once('close', (code) => resolve(code ?? 0))
})
// The child can close while stdout is still being drained. Keep the
// rejection handled until the caller asks for the result via wait().
closed.catch(() => {})
const handle: SpawnHandle = {
pid: child.pid ?? -1,
stdout: decodeStream(child.stdout),
Expand All @@ -354,11 +361,7 @@ export class LocalProcessHandle implements SandboxHandle {
child.stdin.end(() => resolve())
}),
},
wait: () =>
new Promise<number>((resolve, reject) => {
child.on('error', reject)
child.on('close', (code) => resolve(code ?? 0))
}),
wait: () => closed,
kill: (signal) => {
killTree(child, signal)
return Promise.resolve()
Expand Down
18 changes: 18 additions & 0 deletions packages/ai-sandbox-local-process/tests/local-process.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,24 @@ describe('local-process process', () => {
expect(code).toBe(0)
await sbx.destroy()
})

it('resolves wait() when the child closes before stdout is fully consumed', async () => {
const sbx = await fresh()
const proc = await sbx.process.spawn(
`node -e "for (let i = 0; i < 20; i++) console.log(i)"`,
)
let out = ''
for await (const chunk of proc.stdout) {
out += chunk
await new Promise((resolve) => setTimeout(resolve, 10))
}
await expect(proc.wait()).resolves.toBe(0)
const lines = out.trimEnd().split(/\r?\n/)
expect(lines).toEqual(
Array.from({ length: 20 }, (_, index) => String(index)),
)
await sbx.destroy()
})
})

describe('local-process + spawnNdjson (real agent-CLI streaming)', () => {
Expand Down