Repository navigation
fix(daemon): validate spawn cwd asynchronously so one dead share cannot freeze every terminal - #14848
Conversation
…ot freeze every terminal createOrAttach validated the working directory synchronously on the daemon's only thread. Measured on Windows 11 + Ubuntu-24.04: existsSync on an unreachable UNC share 21,022 ms wsl.exe probe, cold distro 1,266 ms wsl.exe probe, warm distro 59 ms existsSync/statSync on healthy \\wsl.localhost 4 ms / 1 ms A single unreachable share therefore blocks the whole RPC loop past the client's 30s request ceiling, so every other terminal stalls behind it and reports `DaemonProtocolError: Request createOrAttach timed out after 30000ms`. The main process already validates asynchronously and passes prevalidatedCwd (ipc/pty.ts); the daemon never got the same treatment. Add validateWorkingDirectoryAsync (one stat, not exists-then-stat, so an unreachable share is not paid for twice) and await it from the daemon spawn preflights. spawnSubprocess now returns SubprocessHandle | Promise<...>, which existing sync stubs still satisfy. Deliberately not bounding the stat with a timeout: the 30s ceiling comes from blocking the shared loop, not from the duration. A timeout cannot tell "slow share" from "gone share", so it would fail spawns that succeed today at 3-8s on a cold VPN mount, and trade an accurate "working directory does not exist" for a guess. The new await opened a race: it sits between the "already exists?" check and the sessions.set that publishes the session, so two concurrent creates for one session id both spawned. Gate creation per session id; distinct ids still spawn in parallel. STA-4470
📝 WalkthroughWalkthroughPTY working-directory validation now uses asynchronous filesystem and WSL checks. PTY preflight and creation return promises. Terminal session creation accepts asynchronous subprocess handles and serializes concurrent creation attempts for the same session ID. Daemon RPC requests now support abort signals, request-scoped cancellation, bounded cancellation, and cleanup. PTY, daemon, terminal session, protocol, and end-to-end tests cover asynchronous creation, cancellation, concurrency, and protocol version 35. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/providers/local-pty-utils.ts (1)
153-163: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten this rationale comment.
Keep the durable reason in one brief comment. Move measurements and incident detail to PR or issue documentation.
As per coding guidelines, comments must be concise, non-obvious, and brief; prefer one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4cf45caa-b089-4104-a80c-02bd773114a8
📒 Files selected for processing (19)
src/main/daemon/daemon-server.tssrc/main/daemon/pty-subprocess-env-inheritance.test.tssrc/main/daemon/pty-subprocess-foreground-degraded-scan.test.tssrc/main/daemon/pty-subprocess-foreground-identity.test.tssrc/main/daemon/pty-subprocess-foreground-scan-cadence.test.tssrc/main/daemon/pty-subprocess-git-credential-guard.test.tssrc/main/daemon/pty-subprocess-handle-lifecycle.test.tssrc/main/daemon/pty-subprocess-managed-agent-env.test.tssrc/main/daemon/pty-subprocess-windows-shell-launch.test.tssrc/main/daemon/pty-subprocess-wsl-launch.test.tssrc/main/daemon/pty-subprocess.test.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.tssrc/main/daemon/terminal-host-concurrent-create.test.tssrc/main/daemon/terminal-host-options.tssrc/main/daemon/terminal-host-session-create.tssrc/main/daemon/terminal-host.tssrc/main/providers/local-pty-utils.tssrc/main/providers/working-directory-validation.test.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 1 remains after this review.
| let settleCreation: () => void = () => {} | ||
| deps.pendingCreations.set( | ||
| opts.sessionId, | ||
| new Promise<void>((resolve) => { | ||
| settleCreation = resolve | ||
| }) | ||
| ) | ||
| try { | ||
| return await spawnAndPublishSession(opts, deps, { size, wslDistro }) | ||
| } finally { | ||
| deps.pendingCreations.delete(opts.sessionId) | ||
| settleCreation() | ||
| } | ||
| } | ||
|
|
||
| async function spawnAndPublishSession( | ||
| opts: InternalCreateOrAttachOptions, | ||
| deps: TerminalHostSessionCreateDependencies, | ||
| ctx: { size: { cols: number; rows: number }; wslDistro: string | undefined } | ||
| ): Promise<CreateOrAttachResult> { | ||
| const { size, wslDistro } = ctx | ||
| const subprocess = await deps.spawnSubprocess({ |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Stop in-flight creation during shutdown.
creationFenced is captured before await deps.spawnSubprocess(...). If shutdown starts during that await, this flow can still publish a new Session after disposeSessions() has completed. That PTY is not included in shutdown cleanup.
Pass a live fence predicate. Recheck it after spawning. If shutdown started, terminate and dispose the handle before sessions.set. Make shutdown wait for pending creations to settle.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/daemon/terminal-host-concurrent-create.test.ts (1)
128-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePre-attach a rejection handler to
spawnGate.
rejectSpawn()on Line 145 runs in the same synchronous block as the twocreateOrAttachcalls. At that moment the mock has not yet reachedawait spawnGate, so the rejected promise has no handler. Node checks for unhandled rejections after the microtask queue drains, and the handler attaches during that drain, so the test passes today. If the path fromcreateOrAttachtodeps.spawnSubprocessever gains a macrotask boundary, this becomes an unhandled rejection and can fail the suite.♻️ Proposed hardening
const spawnGate = new Promise<void>((_resolve, reject) => { rejectSpawn = () => reject(new Error('spawn failed')) }) + // Keep the gate handled before the mock awaits it. + spawnGate.catch(() => {})
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 481cbe47-f732-4f4a-8a09-352e1684868d
📒 Files selected for processing (26)
src/main/daemon/client.tssrc/main/daemon/daemon-client-rpc-request.test.tssrc/main/daemon/daemon-client-rpc-request.tssrc/main/daemon/daemon-foreground-confirmation-protocol.test.tssrc/main/daemon/daemon-protocol-version.test.tssrc/main/daemon/daemon-protocol-version.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-server-async-spawn-cancellation.test.tssrc/main/daemon/daemon-server.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/pty-subprocess.test.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/terminal-host-agent-session-claim.tssrc/main/daemon/terminal-host-agent-session.test.tssrc/main/daemon/terminal-host-concurrent-create.test.tssrc/main/daemon/terminal-host-options.tssrc/main/daemon/terminal-host-session-create.tssrc/main/daemon/terminal-host.tssrc/main/daemon/types.tssrc/main/providers/local-pty-utils.tssrc/main/providers/working-directory-validation.test.tssrc/shared/local-build-compatibility-contract.jsonsrc/shared/local-build-compatibility-contract.tstests/e2e/fixtures/daemon-generation-entry.tstests/e2e/terminal-foreground-confirmation.unit.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/daemon/terminal-host-options.ts
- src/main/providers/working-directory-validation.test.ts
- src/main/daemon/pty-subprocess.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.
| const cancelCreate = (error: Error): void => { | ||
| if (cancellationStarted) { | ||
| return | ||
| } | ||
| cancellationStarted = true | ||
| clearTimeout(timer) | ||
| if (!sent || typeof createSessionId !== 'string') { | ||
| rejectAndDrop(error) | ||
| return | ||
| } | ||
| void opts | ||
| .settleCreateCancellation(createSessionId, opts.id) | ||
| .then((result) => { | ||
| if (result.canceled) { | ||
| rejectAndDrop(error) | ||
| } | ||
| }) | ||
| .catch(() => { | ||
| if (!settled) { | ||
| opts.onCreateCancellationFailure() | ||
| } | ||
| }) | ||
| } | ||
| const timer = setTimeout(() => { | ||
| const error = new DaemonProtocolError(`Request ${type} timed out after ${opts.timeoutMs}ms`) | ||
| if (typeof createSessionId === 'string') { | ||
| cancelCreate(error) | ||
| } else { | ||
| rejectAndDrop(error) | ||
| } | ||
| }, opts.timeoutMs) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Bound the wait after a cancellation reports canceled: false.
cancelCreate clears timer at Line 54 before it asks the daemon to cancel. If settleCreateCancellation resolves with canceled: false, the code neither rejects nor re-arms a timer. The pending request then has no deadline. If the matching createOrAttach reply never arrives, the caller's promise never settles.
The canceled: false case is expected when the daemon already finished the preparation, so a reply is usually in flight. It is not guaranteed: the daemon can fail the create between the preparation window and the reply write, or the reply can be lost on a half-open socket. In that case spawn() hangs and the pane never resolves.
Re-arm a bounded fallback timer so the request always settles.
🛡️ Proposed fallback deadline
const cancelCreate = (error: Error): void => {
if (cancellationStarted) {
return
}
cancellationStarted = true
clearTimeout(timer)
if (!sent || typeof createSessionId !== 'string') {
rejectAndDrop(error)
return
}
+ // The daemon may still answer the original create; do not wait forever for it.
+ const fallbackTimer = setTimeout(() => rejectAndDrop(error), CREATE_CANCELLATION_GRACE_MS)
+ fallbackTimer.unref?.()
void opts
.settleCreateCancellation(createSessionId, opts.id)
.then((result) => {
if (result.canceled) {
+ clearTimeout(fallbackTimer)
rejectAndDrop(error)
}
})
.catch(() => {
+ clearTimeout(fallbackTimer)
if (!settled) {
opts.onCreateCancellationFailure()
}
})
}Note that rejectAndDrop calls clearTimeout(timer) on the stale handle, which is harmless.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const cancelCreate = (error: Error): void => { | |
| if (cancellationStarted) { | |
| return | |
| } | |
| cancellationStarted = true | |
| clearTimeout(timer) | |
| if (!sent || typeof createSessionId !== 'string') { | |
| rejectAndDrop(error) | |
| return | |
| } | |
| void opts | |
| .settleCreateCancellation(createSessionId, opts.id) | |
| .then((result) => { | |
| if (result.canceled) { | |
| rejectAndDrop(error) | |
| } | |
| }) | |
| .catch(() => { | |
| if (!settled) { | |
| opts.onCreateCancellationFailure() | |
| } | |
| }) | |
| } | |
| const timer = setTimeout(() => { | |
| const error = new DaemonProtocolError(`Request ${type} timed out after ${opts.timeoutMs}ms`) | |
| if (typeof createSessionId === 'string') { | |
| cancelCreate(error) | |
| } else { | |
| rejectAndDrop(error) | |
| } | |
| }, opts.timeoutMs) | |
| const cancelCreate = (error: Error): void => { | |
| if (cancellationStarted) { | |
| return | |
| } | |
| cancellationStarted = true | |
| clearTimeout(timer) | |
| if (!sent || typeof createSessionId !== 'string') { | |
| rejectAndDrop(error) | |
| return | |
| } | |
| // The daemon may still answer the original create; do not wait forever for it. | |
| const fallbackTimer = setTimeout(() => rejectAndDrop(error), CREATE_CANCELLATION_GRACE_MS) | |
| fallbackTimer.unref?.() | |
| void opts | |
| .settleCreateCancellation(createSessionId, opts.id) | |
| .then((result) => { | |
| if (result.canceled) { | |
| clearTimeout(fallbackTimer) | |
| rejectAndDrop(error) | |
| } | |
| }) | |
| .catch(() => { | |
| clearTimeout(fallbackTimer) | |
| if (!settled) { | |
| opts.onCreateCancellationFailure() | |
| } | |
| }) | |
| } | |
| const timer = setTimeout(() => { | |
| const error = new DaemonProtocolError(`Request ${type} timed out after ${opts.timeoutMs}ms`) | |
| if (typeof createSessionId === 'string') { | |
| cancelCreate(error) | |
| } else { | |
| rejectAndDrop(error) | |
| } | |
| }, opts.timeoutMs) |
Async cwd validation dedupes by exact path but had no concurrency bound, and a dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs threads. Four distinct paths on one unreachable server therefore starved every other async fs read in the daemon — including the cold-restore history replay running alongside them — which moves the head-of-line stall #14848 removed from the event loop into the thread pool. Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one share fold into one lane. Local-disk paths bypass the lane entirely: a global cap would queue a healthy local spawn behind a dead share. The lane also bounds a same-path case: the dedupe eviction added alongside it re-probes a path whose previous probe is still in flight, so that a recovered mount is noticed rather than pinned to a promise that can never settle. Without a cap each eviction wave would add another overlapping probe against the same dead share. Moves PrioritySemaphore to src/shared. It has no imports, and reaching into src/main/daemon from src/main/providers inverted the dependency direction that already runs daemon -> providers. Note this bounds pool occupancy, which cancellation cannot: an aborted `stat` still holds its libuv thread until the OS returns. STA-4543
Review follow-ups on this PR. The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat` is uninterruptible, so that freed no libuv thread — it only let the next caller pin another. A few retries against one dead mount exhaust the default pool of 4 and stall every other async fs read in the daemon, which is the cross-session freeze #14848 set out to remove. Drop the timer and clear on settle only: the AbortSignal added here already lets callers escape a shared hung probe, so sharing one no longer strands them, and a mount whose stat eventually returns still re-probes on the next call. The abort also introduced a second cancellation identity on the wire. WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as the request's error, and the client's mapping only recognizes the attach-cancel message — so a canceled create could reach the rollback branch that closes a terminal the user still has (#7718). Translate it at the daemon boundary so the wire carries one identity.
…share (#14966) * fix(daemon): bound cwd validation and attach-only requests on a dead share #14848 made cwd validation async so one dead share could not freeze every terminal, but left two ways for a single unreachable path to strand work. Canceling a create did not abort the probe: `isCanceled` is only polled between spawn steps, so `fs.stat` on a dead SMB/NFS/UNC path ran to completion. The create stayed in flight, later creates for that session queued behind it, and shutdown/idle waited on it. Carry an AbortSignal next to the existing poll so a canceled caller abandons the probe, and make the per-session queue wait abortable so a canceled queued request stops waiting too. The shared probe is left running for whoever still wants it, and the dedupe entry is evicted on a hard cap so a never-settling mount cannot poison that path across sessions forever. Attach-only requests registered no cancellable preparation, so the daemon could not match the client's cancel and the client had already cleared its timer — neither side bounded the request. Register the preparation for every createOrAttach and run spawn preflight only when it is not attach-only, and give the client a bounded grace window when the daemon reports an unmatched cancel. The cancellation reason now wins over a racing daemon rejection: callers key recovery off `client_disconnected`, and letting the race pick would roll back terminals it should keep (#7718). Splits working-directory validation out of local-pty-utils to stay under the line cap. STA-4541 * fix(daemon): keep a hung cwd probe to one thread and one cancel identity Review follow-ups on this PR. The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat` is uninterruptible, so that freed no libuv thread — it only let the next caller pin another. A few retries against one dead mount exhaust the default pool of 4 and stall every other async fs read in the daemon, which is the cross-session freeze #14848 set out to remove. Drop the timer and clear on settle only: the AbortSignal added here already lets callers escape a shared hung probe, so sharing one no longer strands them, and a mount whose stat eventually returns still re-probes on the next call. The abort also introduced a second cancellation identity on the wire. WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as the request's error, and the client's mapping only recognizes the attach-cancel message — so a canceled create could reach the rollback branch that closes a terminal the user still has (#7718). Translate it at the daemon boundary so the wire carries one identity.
Async cwd validation dedupes by exact path but had no concurrency bound, and a dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs threads. Four distinct paths on one unreachable server therefore starved every other async fs read in the daemon — including the cold-restore history replay running alongside them — which moves the head-of-line stall #14848 removed from the event loop into the thread pool. Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one share fold into one lane. Local-disk paths bypass the lane entirely: a global cap would queue a healthy local spawn behind a dead share. Moves PrioritySemaphore to src/shared. It has no imports, and reaching into src/main/daemon from src/main/providers inverted the dependency direction that already runs daemon -> providers. Note this bounds pool occupancy, which cancellation cannot: an aborted `stat` still holds its libuv thread until the OS returns. STA-4543
Async cwd validation dedupes by exact path but had no concurrency bound, and a dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs threads. Four distinct paths on one unreachable server therefore starved every other async fs read in the daemon — including the cold-restore history replay running alongside them — which moves the head-of-line stall #14848 removed from the event loop into the thread pool. Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one share fold into one lane. Local-disk paths bypass the lane entirely: a global cap would queue a healthy local spawn behind a dead share. Moves PrioritySemaphore to src/shared. It has no imports, and reaching into src/main/daemon from src/main/providers inverted the dependency direction that already runs daemon -> providers. Note this bounds pool occupancy, which cancellation cannot: an aborted `stat` still holds its libuv thread until the OS returns. STA-4543
…ot freeze every terminal (#14848) * fix(daemon): validate spawn cwd asynchronously so one dead share cannot freeze every terminal createOrAttach validated the working directory synchronously on the daemon's only thread. Measured on Windows 11 + Ubuntu-24.04: existsSync on an unreachable UNC share 21,022 ms wsl.exe probe, cold distro 1,266 ms wsl.exe probe, warm distro 59 ms existsSync/statSync on healthy \\wsl.localhost 4 ms / 1 ms A single unreachable share therefore blocks the whole RPC loop past the client's 30s request ceiling, so every other terminal stalls behind it and reports `DaemonProtocolError: Request createOrAttach timed out after 30000ms`. The main process already validates asynchronously and passes prevalidatedCwd (ipc/pty.ts); the daemon never got the same treatment. Add validateWorkingDirectoryAsync (one stat, not exists-then-stat, so an unreachable share is not paid for twice) and await it from the daemon spawn preflights. spawnSubprocess now returns SubprocessHandle | Promise<...>, which existing sync stubs still satisfy. Deliberately not bounding the stat with a timeout: the 30s ceiling comes from blocking the shared loop, not from the duration. A timeout cannot tell "slow share" from "gone share", so it would fail spawns that succeed today at 3-8s on a cold VPN mount, and trade an accurate "working directory does not exist" for a guess. The new await opened a race: it sits between the "already exists?" check and the sessions.set that publishes the session, so two concurrent creates for one session id both spawned. Gate creation per session id; distinct ids still spawn in parallel. STA-4470 * fix(daemon): fence async spawn lifecycle
…share (#14966) * fix(daemon): bound cwd validation and attach-only requests on a dead share #14848 made cwd validation async so one dead share could not freeze every terminal, but left two ways for a single unreachable path to strand work. Canceling a create did not abort the probe: `isCanceled` is only polled between spawn steps, so `fs.stat` on a dead SMB/NFS/UNC path ran to completion. The create stayed in flight, later creates for that session queued behind it, and shutdown/idle waited on it. Carry an AbortSignal next to the existing poll so a canceled caller abandons the probe, and make the per-session queue wait abortable so a canceled queued request stops waiting too. The shared probe is left running for whoever still wants it, and the dedupe entry is evicted on a hard cap so a never-settling mount cannot poison that path across sessions forever. Attach-only requests registered no cancellable preparation, so the daemon could not match the client's cancel and the client had already cleared its timer — neither side bounded the request. Register the preparation for every createOrAttach and run spawn preflight only when it is not attach-only, and give the client a bounded grace window when the daemon reports an unmatched cancel. The cancellation reason now wins over a racing daemon rejection: callers key recovery off `client_disconnected`, and letting the race pick would roll back terminals it should keep (#7718). Splits working-directory validation out of local-pty-utils to stay under the line cap. STA-4541 * fix(daemon): keep a hung cwd probe to one thread and one cancel identity Review follow-ups on this PR. The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat` is uninterruptible, so that freed no libuv thread — it only let the next caller pin another. A few retries against one dead mount exhaust the default pool of 4 and stall every other async fs read in the daemon, which is the cross-session freeze #14848 set out to remove. Drop the timer and clear on settle only: the AbortSignal added here already lets callers escape a shared hung probe, so sharing one no longer strands them, and a mount whose stat eventually returns still re-probes on the next call. The abort also introduced a second cancellation identity on the wire. WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as the request's error, and the client's mapping only recognizes the attach-cancel message — so a canceled create could reach the rollback branch that closes a terminal the user still has (#7718). Translate it at the daemon boundary so the wire carries one identity.
Async cwd validation dedupes by exact path but had no concurrency bound, and a dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs threads. Four distinct paths on one unreachable server therefore starved every other async fs read in the daemon — including the cold-restore history replay running alongside them — which moves the head-of-line stall #14848 removed from the event loop into the thread pool. Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one share fold into one lane. Local-disk paths bypass the lane entirely: a global cap would queue a healthy local spawn behind a dead share. Moves PrioritySemaphore to src/shared. It has no imports, and reaching into src/main/daemon from src/main/providers inverted the dependency direction that already runs daemon -> providers. Note this bounds pool occupancy, which cancellation cannot: an aborted `stat` still holds its libuv thread until the OS returns. STA-4543
…ot freeze every terminal (stablyai#14848) * fix(daemon): validate spawn cwd asynchronously so one dead share cannot freeze every terminal createOrAttach validated the working directory synchronously on the daemon's only thread. Measured on Windows 11 + Ubuntu-24.04: existsSync on an unreachable UNC share 21,022 ms wsl.exe probe, cold distro 1,266 ms wsl.exe probe, warm distro 59 ms existsSync/statSync on healthy \\wsl.localhost 4 ms / 1 ms A single unreachable share therefore blocks the whole RPC loop past the client's 30s request ceiling, so every other terminal stalls behind it and reports `DaemonProtocolError: Request createOrAttach timed out after 30000ms`. The main process already validates asynchronously and passes prevalidatedCwd (ipc/pty.ts); the daemon never got the same treatment. Add validateWorkingDirectoryAsync (one stat, not exists-then-stat, so an unreachable share is not paid for twice) and await it from the daemon spawn preflights. spawnSubprocess now returns SubprocessHandle | Promise<...>, which existing sync stubs still satisfy. Deliberately not bounding the stat with a timeout: the 30s ceiling comes from blocking the shared loop, not from the duration. A timeout cannot tell "slow share" from "gone share", so it would fail spawns that succeed today at 3-8s on a cold VPN mount, and trade an accurate "working directory does not exist" for a guess. The new await opened a race: it sits between the "already exists?" check and the sessions.set that publishes the session, so two concurrent creates for one session id both spawned. Gate creation per session id; distinct ids still spawn in parallel. STA-4470 * fix(daemon): fence async spawn lifecycle
…share (stablyai#14966) * fix(daemon): bound cwd validation and attach-only requests on a dead share stablyai#14848 made cwd validation async so one dead share could not freeze every terminal, but left two ways for a single unreachable path to strand work. Canceling a create did not abort the probe: `isCanceled` is only polled between spawn steps, so `fs.stat` on a dead SMB/NFS/UNC path ran to completion. The create stayed in flight, later creates for that session queued behind it, and shutdown/idle waited on it. Carry an AbortSignal next to the existing poll so a canceled caller abandons the probe, and make the per-session queue wait abortable so a canceled queued request stops waiting too. The shared probe is left running for whoever still wants it, and the dedupe entry is evicted on a hard cap so a never-settling mount cannot poison that path across sessions forever. Attach-only requests registered no cancellable preparation, so the daemon could not match the client's cancel and the client had already cleared its timer — neither side bounded the request. Register the preparation for every createOrAttach and run spawn preflight only when it is not attach-only, and give the client a bounded grace window when the daemon reports an unmatched cancel. The cancellation reason now wins over a racing daemon rejection: callers key recovery off `client_disconnected`, and letting the race pick would roll back terminals it should keep (stablyai#7718). Splits working-directory validation out of local-pty-utils to stay under the line cap. STA-4541 * fix(daemon): keep a hung cwd probe to one thread and one cancel identity Review follow-ups on this PR. The 30s dedupe eviction retired an entry whose probe was still running. `fs.stat` is uninterruptible, so that freed no libuv thread — it only let the next caller pin another. A few retries against one dead mount exhaust the default pool of 4 and stall every other async fs read in the daemon, which is the cross-session freeze stablyai#14848 set out to remove. Drop the timer and clear on settle only: the AbortSignal added here already lets callers escape a shared hung probe, so sharing one no longer strands them, and a mount whose stat eventually returns still re-probes on the next call. The abort also introduced a second cancellation identity on the wire. WorkingDirectoryValidationAbortedError propagated out of createPtySubprocess as the request's error, and the client's mapping only recognizes the attach-cancel message — so a canceled create could reach the rollback branch that closes a terminal the user still has (stablyai#7718). Translate it at the daemon boundary so the wire carries one identity.
Async cwd validation dedupes by exact path but had no concurrency bound, and a dead UNC share answers `stat` in ~21s while holding one of libuv's 4 default fs threads. Four distinct paths on one unreachable server therefore starved every other async fs read in the daemon — including the cold-restore history replay running alongside them — which moves the head-of-line stall stablyai#14848 removed from the event loop into the thread pool. Adds a per-route lane of 2, reusing PrioritySemaphore and matching the per-distro lane in rate-limits/auth-filesystem-operation.ts. Keyed by the host that has to answer (WSL distro, or the `\\server` prefix) so many dead subdirectories of one share fold into one lane. Local-disk paths bypass the lane entirely: a global cap would queue a healthy local spawn behind a dead share. Moves PrioritySemaphore to src/shared. It has no imports, and reaching into src/main/daemon from src/main/providers inverted the dependency direction that already runs daemon -> providers. Note this bounds pool occupancy, which cancellation cannot: an aborted `stat` still holds its libuv thread until the OS returns. STA-4543
Closes STA-4470.
Problem
createOrAttachvalidated the working directory synchronously on the daemon's shared event loop. On Windows 11,existsSyncagainst an unreachable UNC share blocked for about 21 seconds; a coldwsl.exeprobe took about 1.3 seconds. One dead workspace could therefore stall every terminal RPC and push unrelated creates past the client's 30-second request ceiling.Change
statinstead ofexistsfollowed bystat.The affected tab may still wait for the filesystem's accurate answer. The fix removes daemon-wide head-of-line blocking without guessing that a slow VPN mount is missing.
Reliability contract
daemon-pty.spawn-admission-cleanup): a slow cwd probe cannot block unrelated daemon RPCs, and no canceled, disconnected, timed-out, or shutdown-fenced create can publish an unowned PTY.working-directory-validation.test.ts,terminal-host-concurrent-create.test.ts,daemon-server-async-spawn-cancellation.test.ts, anddaemon-client-rpc-request.test.ts. The absence of a dedicated STA-4470 entry inreliability-gates.jsoncis an accepted residual gap for this PR.Verification
pnpm run typecheckpnpm lint(including reliability manifest and max-lines ratchet)worktree-base-directory-poller.test.tstimeout under parallel load; that exact 23-test file passed three consecutive isolated runssessions=1,preparations=0,canceled=false, original create resolved, tracked sessions remained 1, pending requests returned to 0Residual gaps