Repository navigation
fix: stop renderer heap leak from unhandled terminal teardown rejections (#8260) - #8279
Conversation
📝 WalkthroughWalkthroughWindows node-pty shutdown now executes immediately before readiness, with packaging, deployment checks, patch application, and relay lifecycle coverage. Relay PTY termination uses centralized Windows-specific no-argument kills and avoids subsequent destruction. Daemon PTY sessions now use generation-aware exit proof, serialized admissions, route reconciliation, identity validation, and bounded shutdown draining. Renderer PTY cleanup and project removal swallow kill failures while logging warnings. Terminal file-link probing uses settled promises, preserves successful candidates, and records a breadcrumb for rejected probes. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: ee3c2194-caff-43a6-a3e8-f52c7a251d3b
📒 Files selected for processing (7)
src/main/ipc/pty.tssrc/relay/pty-handler.tssrc/renderer/src/components/terminal-pane/TerminalPane.tsxsrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/terminal-link-handlers.tssrc/renderer/src/lib/crash-diagnostics.tssrc/renderer/src/store/slices/repos.ts
| throw new Error(`PTY "${id}" not found`) | ||
| } | ||
| managed.pty.kill(signal) | ||
| killPtyProcess(managed.pty, signal) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect ALLOWED_SIGNALS to confirm non-terminating signals flow through sendSignal
rg -nP "ALLOWED_SIGNALS" src/relay/pty-handler.ts -C2Repository: stablyai/orca
Length of output: 527
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the signal allowlist and the PTY kill helper around the reported lines
sed -n '145,220p' src/relay/pty-handler.ts
printf '\n---\n'
sed -n '880,960p' src/relay/pty-handler.ts
# Find tests and call sites for sendSignal / killPtyProcess
rg -n "sendSignal|killPtyProcess|SIGWINCH|ALLOWED_SIGNALS" src test . -C 2Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Read the PTY kill helper and nearby Windows-specific logic without dumping the whole file
sed -n '1,60p' src/relay/pty-handler.ts
printf '\n---\n'
rg -n "win32|signals not supported|pty\.kill\(|killPtyProcess\(" src/relay/pty-handler.ts -C 2
# Look for tests that distinguish SIGWINCH from terminating signals on Windows or in the relay path
rg -n "SIGWINCH|SIGTERM|SIGKILL|signals not supported|windows" src/relay/pty-handler.test.ts src/main/providers/local-pty-provider.test.ts -C 2Repository: stablyai/orca
Length of output: 12889
Non-terminating signals should not hit the Windows kill fallback. sendSignal() routes every allowed signal through killPtyProcess(), but that helper falls back to pty.kill() when signals aren’t supported. On Windows, SIGWINCH will then terminate the PTY instead of behaving like a repaint signal. Split the fallback so only shutdown paths can degrade to kill(), or bypass it for non-terminating signals.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/relay/pty-handler.ts (2)
731-744: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winUnguarded
killPtyForShutdowninsidesetTimeoutfallback callbacks can leak the PTY or crash the relay.In both the stale-spawn cleanup fallback (line 735) and the graceful-shutdown SIGKILL fallback (line 893),
killPtyForShutdown(still, 'SIGKILL')is called with no try/catch, inside asetTimeoutcallback. The PR's own tests show a native Windowskill()throw is a real, anticipated failure ('invalid ConPTY handle'). If that throw happens here:
- Everything after it in the callback (
notifyExitListener,disposeManagedPty,this.ptys.delete(id),clearPtyFlowState) never runs, so the managed entry and its slot leak permanently — and for the stale-spawn path there is no retry mechanism at all (unlikeshutdown()'s RPC entry points, which are intentionally left unguarded to support caller retries).- An uncaught exception inside a
setTimeoutcallback is not scoped to a Promise; by default Node.js treats it as anuncaughtException, which can terminate the entire relay process — taking down every other active PTY session, not just this one.
dispose()already wraps the equivalent call in try/catch (line 1161) — apply the same pattern here.🛡️ Proposed fix: guard both fallback-timer kill calls
managed.killTimer = setTimeout(() => { const still = this.ptys.get(id) if (still && !still.disposed) { - killPtyForShutdown(still, 'SIGKILL') + try { + killPtyForShutdown(still, 'SIGKILL') + } catch { + /* child may already be dead */ + } // Why: stale-spawn cleanup has no client who will ever attach. ... this.notifyExitListener(still) disposeManagedPty(still) this.ptys.delete(id) } }, 5000)managed.killTimer = setTimeout(() => { const still = this.ptys.get(id) if (still && !still.disposed) { - killPtyForShutdown(still, 'SIGKILL') + try { + killPtyForShutdown(still, 'SIGKILL') + } catch { + /* child may already be dead */ + } this.flushPtyOutput(id) this.dispatcher.notify('pty.exit', { id, code: -1 }) ...Also applies to: 890-911
915-929: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winHandle Windows signals separately
pty.sendSignalis still exposed on the relay, and the Windows path is exercised withSIGWINCH. Sincenode-pty’s Windowskill(signal)throws for any signal, non-terminating signals likeSIGWINCHwill reject on Windows relays instead of being a no-op. Split resize/repaint signals from termination signals, or gate the Windows path, so ConPTY updates keep working.
🧹 Nitpick comments (2)
src/relay/pty-handler.ts (1)
1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift
oxlint-disable max-linesconflicts with the coding guideline; file keeps growing.This PR adds more lines (new helper, new field, new guard) to a file that already suppresses the
max-linesrule. As per coding guidelines,**/*.{js,jsx,ts,tsx}should "Never disablemax-linesvia ESLint or oxlint, including line-specific variants." Consider splittingpty-handler.tsinto smaller cohesive modules (e.g. extract shutdown/kill handling, output batching, spawn/revive) rather than continuing to suppress the check.Source: Coding guidelines
src/relay/pty-handler.test.ts (1)
1084-1211: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGood coverage, but the fallback-timer throw path is untested.
These tests thoroughly cover the initial
killPtyForShutdowncall throwing and being retried, but none simulate the fallback SIGKILL timer (shutdown()'s 5s graceful fallback, orspawn()'s stale-cleanup fallback) itself throwing. That's precisely the unguarded path flagged inpty-handler.ts(lines 890-911 / 731-744) — a test exercisingmockKillthrowing on the fallback-timer invocation would have caught it.Also applies to: 1906-1932
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 39e1e6f0-8bbf-4efa-a6c0-f6de07ae230d
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (17)
config/patches/[email protected]config/reliability-gates.jsoncconfig/scripts/build-relay-windows-node-pty-patch.test.mjsconfig/scripts/build-relay.mjsconfig/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjssrc/main/ssh/ssh-relay-deploy.tssrc/main/ssh/ssh-relay-native-deps-install.test.tssrc/relay/node-pty-windows-pre-ready-shutdown.test.tssrc/relay/pty-handler.test.tssrc/relay/pty-handler.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/terminal-link-handlers.test.tssrc/renderer/src/components/terminal-pane/terminal-link-handlers.tssrc/renderer/src/components/terminal-pane/terminal-link-probe-results.tssrc/renderer/src/store/slices/repos-remove-project-purge-leak.test.tssrc/renderer/src/store/slices/repos.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/renderer/src/store/slices/repos.ts
- src/renderer/src/components/terminal-pane/pty-transport.ts
| function checkNativeDeps(rootDir = process.cwd()) { | ||
| const target = join(rootDir, 'node_modules', 'node-pty', 'lib', 'windowsTerminal.js') | ||
| const source = readFileSync(target, 'utf8') | ||
| if (!source.includes(PATCHED_DESTROY) || !source.includes(PATCHED_KILL)) { | ||
| throw new Error('node-pty Windows pre-ready shutdown patch is missing') | ||
| } | ||
| require.resolve('@parcel/watcher', { paths: [rootDir] }) | ||
| return target | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== Relevant file ==\n'
git ls-files 'config/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjs' 'package.json' 'pnpm-lock.yaml' 'package-lock.json' 'yarn.lock' 2>/dev/null || true
printf '\n== File excerpt ==\n'
cat -n config/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjs | sed -n '1,180p'
printf '\n== Search for `@parcel/watcher` references ==\n'
rg -n "`@parcel/watcher`|parcel/watcher" -S .
printf '\n== Package versions (if any) ==\n'
python3 - <<'PY'
import json, pathlib, re
for p in [pathlib.Path('package.json'), pathlib.Path('pnpm-lock.yaml'), pathlib.Path('package-lock.json'), pathlib.Path('yarn.lock')]:
if p.exists():
print(f'-- {p} exists')
if p.name == 'package.json':
data = json.loads(p.read_text())
for sec in ('dependencies','devDependencies','optionalDependencies','peerDependencies'):
if sec in data and '`@parcel/watcher`' in data[sec]:
print(sec, data[sec]['`@parcel/watcher`'])
elif p.name.endswith('.lock'):
txt = p.read_text(errors='ignore')
m = re.search(r'`@parcel/watcher`@([^:\n]+)', txt)
if m: print('lock hint:', m.group(0)[:200])
PYRepository: stablyai/orca
Length of output: 17415
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect `@parcel/watcher` package metadata from installed/system source if present in repo cache references.
# This does not execute repository code.
python3 - <<'PY'
import os, json, pathlib, re, sys
candidates = []
for root, dirs, files in os.walk('.'):
if 'package.json' in files and '`@parcel/watcher`' in open(os.path.join(root,'package.json'), encoding='utf-8', errors='ignore').read():
candidates.append(os.path.join(root,'package.json'))
print('\n'.join(candidates[:20]))
PYRepository: stablyai/orca
Length of output: 921
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== Relevant file ==\n'
cat -n config/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjs | sed -n '1,180p'
printf '\n== Search for `@parcel/watcher` references ==\n'
rg -n "`@parcel/watcher`|parcel/watcher" -S .
printf '\n== Package versions (if any) ==\n'
python3 - <<'PY'
import json, pathlib
for p in [pathlib.Path('package.json'), pathlib.Path('pnpm-lock.yaml'), pathlib.Path('package-lock.json'), pathlib.Path('yarn.lock')]:
if not p.exists():
continue
print(f'-- {p}')
if p.name == 'package.json':
data = json.loads(p.read_text())
for sec in ('dependencies','devDependencies','optionalDependencies','peerDependencies'):
if sec in data and '`@parcel/watcher`' in data[sec]:
print(sec, data[sec]['`@parcel/watcher`'])
PYRepository: stablyai/orca
Length of output: 17286
🌐 Web query:
@parcel/watcher require missing native binary error load optional dependency package main entrypoint
💡 Result:
The error "No prebuild or local build of @parcel/watcher found" occurs because @parcel/watcher uses a pattern of platform-specific native binaries published as optional dependencies [1]. When these dependencies fail to install correctly, the main package cannot locate the required binary for your architecture [2][3]. Common causes and solutions include: 1. Installation Flags: Ensure you are not using flags like --no-optional during installation [3][4]. The package manager must be able to install the optional dependency corresponding to your specific platform (e.g., @parcel/watcher-linux-x64-musl) [4][1]. 2. Packaging and Bundling: If you are encountering this in a bundled environment (like Electron or a Docker build), the bundler may fail to include the platform-specific optional dependency because it is not explicitly referenced in the main dependency graph [5][6]. To resolve this, you may need to manually ensure the specific platform-native subpackage is included in your build output [6]. 3. Unsupported Platforms or Missing Binaries: If the package does not support your specific platform/architecture combination, it will fail to find a prebuild [3][7]. Ensure your environment matches a supported architecture [3]. 4. Build from Source: If prebuilds are unavailable, the package attempts to build from source [8]. If your environment lacks the necessary build tools (like C++ compilers or Python), this step will fail [8]. Troubleshooting Steps: - Check your installation logs to see if optional dependencies were skipped [3][4]. - If using tools that prune dependencies or package applications, verify that the platform-specific @parcel/watcher-* package is being explicitly collected [6]. - If you are in a constrained environment (e.g., WebContainers), note that native addons may be disabled, and you may need to implement a try/catch block or conditional exports to gracefully handle the failure to load the binary [9].
Citations:
- 1: Separate packages for precompiled binaries parcel-bundler/watcher#143
- 2: npm ci cannot locate a prebuild for any given architecture parcel-bundler/watcher#151
- 3: Error: No prebuild or local build of @parcel/watcher found. Tried @parcel/watcher-linux-arm64-musl. parcel-bundler/watcher#152
- 4: @parcel/watcher not working with Docker node:alpine image parcel-bundler/watcher#147
- 5: No prebuild or local build of @parcel/watcher found parcel-bundler/watcher#204
- 6: fix(packaging): include @parcel/watcher native addon in packaged runtime #4860
- 7: Error building parcel watcher on m1 parcel-bundler/watcher#182
- 8: npm RFC #868 will block this package's install script by default parcel-bundler/watcher#251
- 9: Does not work in stackblitz parcel-bundler/watcher#99
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== `@parcel/watcher` package entrypoint ==\n'
node - <<'JS'
const fs = require('fs')
const path = require('path')
const pkgPath = path.resolve('node_modules/.pnpm/@[email protected]/node_modules/@parcel/watcher/package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
console.log('package.json path:', pkgPath)
console.log('main:', pkg.main)
console.log('exports:', JSON.stringify(pkg.exports, null, 2))
console.log('optionalDependencies keys:', Object.keys(pkg.optionalDependencies || {}).join(', '))
JS
printf '\n== entrypoint file excerpt ==\n'
ENTRY=$(node - <<'JS'
const fs = require('fs')
const path = require('path')
const pkg = JSON.parse(fs.readFileSync('node_modules/.pnpm/@[email protected]/node_modules/@parcel/watcher/package.json','utf8'))
console.log(path.join('node_modules/.pnpm/@[email protected]/node_modules/@parcel/watcher', pkg.main))
JS
)
cat -n "$ENTRY" | sed -n '1,220p'
printf '\n== relay deployment check excerpt ==\n'
cat -n src/main/ssh/ssh-relay-deploy.ts | sed -n '446,472p'
printf '\n== packaged runtime node module handling excerpt ==\n'
cat -n config/packaged-runtime-node-modules.cjs | sed -n '158,172p'Repository: stablyai/orca
Length of output: 4384
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
import os, pathlib, json
pkgdir = pathlib.Path('node_modules/.pnpm/@[email protected]/node_modules/@parcel/watcher')
print('exists', pkgdir.exists())
print('files:')
for p in sorted(pkgdir.iterdir()):
print(p.name)
PYRepository: stablyai/orca
Length of output: 270
Load @parcel/watcher here instead of only resolving it. @parcel/watcher’s index.js immediately require()s the platform-specific optional package and throws if the native addon is missing, so require.resolve() can still report ORCA-NATIVE-DEPS-OK when the binary won’t actually load.
| } | ||
|
|
||
| void Promise.all( | ||
| void Promise.allSettled( |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Add .catch() to handle errors thrown within the .then() callback.
The old Promise.all(...).then(...).catch(() => callback(undefined)) chain caught both probe rejections and synchronous errors thrown inside .then(). Switching to Promise.allSettled correctly prevents probe rejections from reaching .then(), but removing .catch() eliminates the safety net for callback-internal errors. If buildCandidateLogicalLinesForBufferPosition accesses a disposed terminal buffer or preferLongestNonOverlappingLinks encounters unexpected input, the rejection is unhandled — the same class of issue this PR targets.
🛡️ Proposed fix
).then((results) => {
const resolvedLinks = collectProbeResults(results)
const latestFingerprints = new Set(
buildCandidateLogicalLinesForBufferPosition(buffer, bufferLineNumber).map(
(logicalLine) => logicalLine.fingerprint
)
)
const providedLinks = resolvedLinks.filter(
(link): link is ProvidedFileLink => link !== null
)
const links = preferLongestNonOverlappingLinks(providedLinks)
.filter(({ logicalLine }) => latestFingerprints.has(logicalLine.fingerprint))
.map(({ link }) => link)
if (providedLinks.length > 0 && links.length === 0) {
return
}
callback(links.length > 0 ? links : undefined)
- })
+ }).catch(() => {
+ callback(undefined)
+ })Also applies to: 219-236
|
Taking a look! |
brennanb2025
left a comment
There was a problem hiding this comment.
Validated the narrowed teardown/retry-ownership scope against latest main. Exact-head unit, mobile, Electron, perf/leak, packaging, and two independent review lanes are clean; #8260 remains open for the unproved white-screen/heap investigation.
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 5258b621-a198-4a44-af35-6246daa99790
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (36)
config/reliability-gates.jsoncconfig/scripts/build-relay-windows-node-pty-patch.test.mjsconfig/scripts/build-relay.mjsconfig/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjssrc/main/daemon/daemon-entry.tssrc/main/daemon/daemon-foreground-confirmation-protocol.test.tssrc/main/daemon/daemon-main.test.tssrc/main/daemon/daemon-main.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-provider.test.tssrc/main/daemon/daemon-pty-provider.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/daemon-server.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/daemon-session-exit-fence.test.tssrc/main/daemon/daemon-session-exit-fence.tssrc/main/daemon/daemon-spawner.test.tssrc/main/daemon/daemon-stream-events.tssrc/main/daemon/degraded-daemon-fallback-shutdown.tssrc/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/daemon/pty-provider-route-reconciliation.test.tssrc/main/daemon/pty-provider-route-reconciliation.tssrc/main/daemon/pty-subprocess.test.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/daemon/slow-daemon-session-verification.test.tssrc/main/daemon/terminal-host-create-contract.tssrc/main/daemon/terminal-host-session-reaping-leak.test.tssrc/main/daemon/terminal-host-shutdown-drain.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/daemon/types.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- config/scripts/build-relay-windows-node-pty-patch.test.mjs
👮 Files not reviewed due to content moderation or server errors (6)
- src/main/daemon/daemon-server.test.ts
- src/main/daemon/daemon-pty-adapter.test.ts
- src/main/daemon/terminal-host.ts
- src/main/daemon/degraded-daemon-pty-provider.ts
- src/main/daemon/daemon-pty-router.ts
- src/main/daemon/daemon-pty-adapter.ts
| "providers": ["local", "daemon", "ssh", "remote-runtime"], | ||
| "coveredPlatforms": ["macos"], | ||
| "coveredProviders": ["local", "ssh"], | ||
| "coverageNotes": "A macOS unit harness loads the installed patched node-pty WindowsTerminal prototype without constructing native state, proving pre-ready kill/destroy dispatch immediately. A relay artifact harness reproduces vanilla npm node-pty retaining one deferred kill with zero native close calls, then proves both Windows relay artifacts hash, ship, apply, include the local ConPTY console-list fallback, and idempotently verify the fix. Relay tests simulate win32 shutdown, persistent single-timer stale-spawn and graceful fallback ownership, retry after native failure without deleting the only handle before close is proven, and accept OS process-death proof even when native close throws without onExit. Relay boot UUIDs scope recycled pty-N counters through initial spawn, durable-lease persistence, reattach, and SSH target-id migration; mismatched generations expire before raw attach and release their exact in-memory retry owner, while pane identity protects legacy leases. Main-process retry owners persist local daemon and remote-runtime teardown intent across renderer and app restarts, coalesce by exact provider identity, use one shared one-shot timer per owner, and fence SSH relay plus remote-runtime generation reuse before close. Local and daemon providers retain pane/tab identity and reject stale teardown before native or daemon kill; daemon native failures propagate and accepted kills remain listed until onExit or conservative OS proof. Protocol v22 carries pane identity across process boundaries, v23 carries immutable daemon-session generations through create/list/size/exit, and admission revisions protect preserved legacy daemons while replacement creation is in flight. Lease-less SSH retry owners survive transport replacement and re-drive the replacement provider. Local Windows shutdown retains provider records and listeners after native throw unless onExit independently proves death. A disconnected SSH provider rejects shutdown without tombstoning its attachable lease. Paired/mobile headless close refuses to depersist a terminal until the controller accepts durable retry ownership. Project removal keeps local or remote ownership until provider-verified shutdown and successful VM cleanup; runtime repo removal drains pre-spawn trust/team/command preparation plus create-first worktree creation, headless, renderer-backed mobile, renderer split, and selector-less renderer terminal admissions before fresh ownership/liveness snapshots, stop, and metadata mutation. Desktop and duplicate-host repo removal route through the same transaction; unresolved terminal creation may continue for an unrelated host while the removed host remains fenced. Legacy worktree creation, renderer PTY spawn, and every local/SSH/folder worktree removal outcome—including Windows stale registration and orphan-compatible fallback—are fenced and verified before destructive mutation or metadata purge. Hidden local/SSH and remote-runtime background-launch cleanup retain exact PTY/handle retry ownership with bounded one-shot scheduling. Crash-durable teardown intent uses an O(1) revisioned append journal with exact SSH set/remove records, compacted to one checkpoint after a successful full-state save, instead of synchronously serializing every retained owner for each mutation. Targeted terminal.stop probes skip unrelated sessions. The same relay contract serves paired web/mobile clients; no live Windows ConPTY or Windows-over-SSH run is recorded yet.", |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
coveredProviders omits "daemon" despite this gate's own evidence.
The gate's coverageNotes, oracle, and assertionRefs extensively document daemon-provider coverage (protocol v22/v23 generation fencing, daemon-pty-adapter.test.ts, daemon-server.test.ts, daemon-session-exit-fence.test.ts, session.test.ts, terminal-host.test.ts, pty-subprocess.test.ts, daemon-pty-router.test.ts, degraded-daemon-pty-provider.test.ts), yet coveredProviders lists only ["local", "ssh"]. This is an internal inconsistency in the manifest's own claims.
📝 Suggested fix
- "coveredProviders": ["local", "ssh"],
+ "coveredProviders": ["local", "daemon", "ssh"],📝 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.
| "providers": ["local", "daemon", "ssh", "remote-runtime"], | |
| "coveredPlatforms": ["macos"], | |
| "coveredProviders": ["local", "ssh"], | |
| "coverageNotes": "A macOS unit harness loads the installed patched node-pty WindowsTerminal prototype without constructing native state, proving pre-ready kill/destroy dispatch immediately. A relay artifact harness reproduces vanilla npm node-pty retaining one deferred kill with zero native close calls, then proves both Windows relay artifacts hash, ship, apply, include the local ConPTY console-list fallback, and idempotently verify the fix. Relay tests simulate win32 shutdown, persistent single-timer stale-spawn and graceful fallback ownership, retry after native failure without deleting the only handle before close is proven, and accept OS process-death proof even when native close throws without onExit. Relay boot UUIDs scope recycled pty-N counters through initial spawn, durable-lease persistence, reattach, and SSH target-id migration; mismatched generations expire before raw attach and release their exact in-memory retry owner, while pane identity protects legacy leases. Main-process retry owners persist local daemon and remote-runtime teardown intent across renderer and app restarts, coalesce by exact provider identity, use one shared one-shot timer per owner, and fence SSH relay plus remote-runtime generation reuse before close. Local and daemon providers retain pane/tab identity and reject stale teardown before native or daemon kill; daemon native failures propagate and accepted kills remain listed until onExit or conservative OS proof. Protocol v22 carries pane identity across process boundaries, v23 carries immutable daemon-session generations through create/list/size/exit, and admission revisions protect preserved legacy daemons while replacement creation is in flight. Lease-less SSH retry owners survive transport replacement and re-drive the replacement provider. Local Windows shutdown retains provider records and listeners after native throw unless onExit independently proves death. A disconnected SSH provider rejects shutdown without tombstoning its attachable lease. Paired/mobile headless close refuses to depersist a terminal until the controller accepts durable retry ownership. Project removal keeps local or remote ownership until provider-verified shutdown and successful VM cleanup; runtime repo removal drains pre-spawn trust/team/command preparation plus create-first worktree creation, headless, renderer-backed mobile, renderer split, and selector-less renderer terminal admissions before fresh ownership/liveness snapshots, stop, and metadata mutation. Desktop and duplicate-host repo removal route through the same transaction; unresolved terminal creation may continue for an unrelated host while the removed host remains fenced. Legacy worktree creation, renderer PTY spawn, and every local/SSH/folder worktree removal outcome—including Windows stale registration and orphan-compatible fallback—are fenced and verified before destructive mutation or metadata purge. Hidden local/SSH and remote-runtime background-launch cleanup retain exact PTY/handle retry ownership with bounded one-shot scheduling. Crash-durable teardown intent uses an O(1) revisioned append journal with exact SSH set/remove records, compacted to one checkpoint after a successful full-state save, instead of synchronously serializing every retained owner for each mutation. Targeted terminal.stop probes skip unrelated sessions. The same relay contract serves paired web/mobile clients; no live Windows ConPTY or Windows-over-SSH run is recorded yet.", | |
| "coveredProviders": ["local", "daemon", "ssh"], |
| hasExited() { | ||
| return killed | ||
| }, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Track exit proof separately from whether a kill was requested.
forceKill() sets killed, so this mock reports hasExited() === true before simulateExit(). That can let the new shutdown tests pass even if the session incorrectly treats an accepted kill as OS exit proof.
Proposed fix
function createMockSubprocess() {
+ let exited = false
let killed = false
kill() {
killed = true
// Simulate async exit
- setTimeout(() => onExit?.(0), 5)
+ setTimeout(() => {
+ exited = true
+ onExit?.(0)
+ }, 5)
},
forceKill() {
killed = true
},
hasExited() {
- return killed
+ return exited
},
simulateExit(code: number) {
+ exited = true
onExit?.(code)
}📝 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.
| hasExited() { | |
| return killed | |
| }, | |
| function createMockSubprocess() { | |
| let exited = false | |
| let killed = false | |
| return { | |
| kill() { | |
| killed = true | |
| // Simulate async exit | |
| setTimeout(() => { | |
| exited = true | |
| onExit?.(0) | |
| }, 5) | |
| }, | |
| forceKill() { | |
| killed = true | |
| }, | |
| hasExited() { | |
| return exited | |
| }, | |
| simulateExit(code: number) { | |
| exited = true | |
| onExit?.(code) | |
| } | |
| } | |
| } |
| /** Conservative OS/onExit proof; false includes unknown and still alive. */ | ||
| hasExited?(): boolean | ||
| /** Windows ConPTY may accept a pre-ready close before it can act on it. */ | ||
| signal(sig: string): void | ||
| onData(cb: (data: string) => void): void | ||
| onExit(cb: (code: number) => void): void | ||
| /** Release the native PTY handle via node-pty's own destroy() path. | ||
| * Idempotent. Safe to call after exit. Called by Session on every teardown | ||
| * path (natural exit, kill, force-kill, native throw, session dispose). */ | ||
| * path after physical exit proof, or during whole-session disposal. */ | ||
| dispose(): void | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Misplaced doc comment on SubprocessHandle.signal().
"Windows ConPTY may accept a pre-ready close before it can act on it." describes pre-ready shutdown/close semantics (relevant to kill()/forceKill()/hasExited), not signal(). The actual rationale for signal() — matching its own implementation comment in pty-subprocess.ts ("same recycled-pid hazard as forceKill... silently drop the signal") — is unrelated. This looks like a comment left in the wrong spot during the interface reorder for this PR.
📝 Suggested fix
/** Conservative OS/onExit proof; false includes unknown and still alive. */
hasExited?(): boolean
- /** Windows ConPTY may accept a pre-ready close before it can act on it. */
signal(sig: string): void📝 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.
| /** Conservative OS/onExit proof; false includes unknown and still alive. */ | |
| hasExited?(): boolean | |
| /** Windows ConPTY may accept a pre-ready close before it can act on it. */ | |
| signal(sig: string): void | |
| onData(cb: (data: string) => void): void | |
| onExit(cb: (code: number) => void): void | |
| /** Release the native PTY handle via node-pty's own destroy() path. | |
| * Idempotent. Safe to call after exit. Called by Session on every teardown | |
| * path (natural exit, kill, force-kill, native throw, session dispose). */ | |
| * path after physical exit proof, or during whole-session disposal. */ | |
| dispose(): void | |
| } | |
| /** Conservative OS/onExit proof; false includes unknown and still alive. */ | |
| hasExited?(): boolean | |
| signal(sig: string): void | |
| onData(cb: (data: string) => void): void | |
| onExit(cb: (code: number) => void): void | |
| /** Release the native PTY handle via node-pty's own destroy() path. | |
| * Idempotent. Safe to call after exit. Called by Session on every teardown | |
| * path after physical exit proof, or during whole-session disposal. */ | |
| dispose(): void | |
| } |
| /** Request immediate shutdown while retaining the session until exit proof. */ | ||
| requestImmediateShutdown(): void { | ||
| if (this._state === 'exited' || this.forceKillAccepted) { | ||
| return | ||
| } | ||
| this._isTerminating = true | ||
| this.releaseProducerPause({ resume: true }) | ||
| try { | ||
| this.issueForceShutdown() | ||
| } catch (error) { | ||
| this._isTerminating = false | ||
| throw error | ||
| } | ||
| this.scheduleForceShutdownCheck(this.nextForceShutdownCheckDelay()) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== session.ts outline ==\n'
ast-grep outline src/main/daemon/session.ts --view expanded || true
printf '\n== terminal-host.ts search ==\n'
rg -n "requestImmediateShutdown|beginShutdownDrain|scheduleForceShutdownCheck|kill\\(" src/main -g '!**/dist/**' -g '!**/build/**' || true
printf '\n== pty-subprocess.ts search ==\n'
rg -n "signal\\(|forceKill|recycled-pid|ConPTY|pre-ready" src/main -g '!**/dist/**' -g '!**/build/**' || trueRepository: stablyai/orca
Length of output: 46599
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== session.ts relevant slice ==\n'
sed -n '280,360p' src/main/daemon/session.ts | cat -n
printf '\n== scheduleForceShutdownCheck slice ==\n'
sed -n '760,820p' src/main/daemon/session.ts | cat -n
printf '\n== terminal-host.ts relevant slice ==\n'
sed -n '1,260p' src/main/daemon/terminal-host.ts | cat -nRepository: stablyai/orca
Length of output: 17369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== session.ts line-numbered slices around the shutdown paths ==\n'
sed -n '300,360p' src/main/daemon/session.ts | cat -n
printf '\n---\n'
sed -n '760,815p' src/main/daemon/session.ts | cat -n
printf '\n== terminal-host.ts line-numbered slices around kill() ==\n'
sed -n '1,260p' src/main/daemon/terminal-host.ts | cat -nRepository: stablyai/orca
Length of output: 16779
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== terminal-host tests around immediate kill ==\n'
sed -n '120,220p' src/main/daemon/terminal-host-session-reaping-leak.test.ts | cat -n
printf '\n== terminal-host tests around kill() ==\n'
sed -n '440,540p' src/main/daemon/terminal-host.test.ts | cat -n
printf '\n== session tests around signal() and force shutdown comments ==\n'
sed -n '500,590p' src/main/daemon/session.test.ts | cat -nRepository: stablyai/orca
Length of output: 11715
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== getAliveSession and related state checks ==\n'
sed -n '260,340p' src/main/daemon/terminal-host.ts | cat -n
printf '\n== isTerminating usages ==\n'
rg -n "isTerminating|_isTerminating" src/main/daemon -g '!**/dist/**' -g '!**/build/**' | sed -n '1,200p'
printf '\n== session exit/proof disposal slice ==\n'
sed -n '500,620p' src/main/daemon/session.ts | cat -nRepository: stablyai/orca
Length of output: 10925
Clear the pending kill timer before escalating to force-kill
requestImmediateShutdown() is called directly from TerminalHost.kill(..., { immediate: true }), so if a graceful kill already left killTimer armed, the follow-up re-poll is blocked by scheduleForceShutdownCheck() and stays on the old ~5s cadence until that timer expires.
- Clear
killTimerhere beforeissueForceShutdown(), or make the slower cadence explicit. - The
signal()doc comment also looks misplaced; the recycled-pid warning belongs on the signal passthrough, not the ConPTY pre-ready-close note.
Two renderer paths let Promise rejections escape unhandled, where the crash-breadcrumb system retains them and grows the heap until the renderer white-screens (#8260): - The terminal file-link provider fires a `void Promise.all(...)` whose async mappers probe path existence over SSH. On disconnect these reject with "Remote connection dropped/reconnecting"; add a `.catch` that resolves the callback with no links so the rejection is handled. - "ResizeObserver loop completed" is a benign Chromium quirk; suppress it in crash-diagnostics so it stops filling the breadcrumb buffer and inflating the renderer error count. Scope note: the original fix for #8260 also proposed Windows pty:kill signal handling (killPtyProcess / isPtyAlreadyGoneError) and a ResizeObserver double-rAF. Those landed on main independently (Windows kill handling by v1.4.135; the pane-title-overlay rect-equality guard from #2756 already breaks the loop at the source), so this change carries only the two guards still missing upstream. Co-Authored-By: Claude <[email protected]>
ba9e0b4 to
bd0a0a8
Compare
Dismissing: this approval was for the earlier 122-commit revision (ba9e0b4), which bundled a large terminal-teardown refactor now known to be largely redundant with main (#8628/#8630/#8673). The PR has been reset to the true residual of #8260 — two renderer rejection/leak guards — and needs a fresh independent review of that clean diff. Prior revision archived at branch archive/pr-8279-review-session.
|
Thanks for the PR! Sorry about the review weirdness, my agent got stuck in a review loop. But the core fix is much appreciated! |
|
@iridite The next release build will be out in <24 hours - I'll ping you again here when it's released. When that happens, could you let us know whether the white-screen cadence drops (and if you can, whether renderer heap still climbs over a long session)? Since the leak takes hours to build, your real-world usage is the verification we can't do quickly ourselves. Keeping this open until then - if crashes persist on the new build, the remaining leak is somewhere else and your next trace will tell us where. Thanks again! |
|
Thanks for merging and for asking for follow-up data — here's the full picture from the local telemetry logs (77 renderer sessions across 4 days, Jul 12–15, macOS desktop connecting to a Windows machine exclusively via SSH, typically 5–8 SSH terminal tabs open across multiple repos). Baseline: sessions and heap growth
Average heap growth rate across 23 sessions ≥ 30 min: 61.5 MB/hr (range 5–135 MB/hr). Renderer starts at ~23 MB fresh. Rejection type breakdown
Interesting shift on Jul 14: the Windows PTY signal rejections disappeared entirely (likely an upstream ORCA fix landed), but a new rejection class appeared — SSH multiplexer teardown during reconnect. These aren't covered by this PR. I've filed a separate fix in PR #8655. Critical: heap grows even with zero rejectionsThis is the most important data point. 12 sessions show ≥ 80 MB peak heap with 0 unhandled rejections, some reaching 169 MB: The rejection-plus-heap sessions were only 4 out of all affected sessions. Unhandled rejection accumulation is a contributing factor, but not the dominant one. Root cause hypothesis for the rejection-free leakAll repos in this setup connect via SSH ( At the user's configured scrollback limit (changed from 5 000 → 1 000 rows mid-observation period), each SSH terminal occupies roughly 3–5 MB of cell data in the xterm buffer. With 5–8 SSH tabs and extended agent runs that fill the buffer, the heap climbs steadily even when nothing throws. I've submitted PR #8655 to address this with a deferred scrollback trim (matching the 30 s cold-park delay) for hidden SSH panes, restoring the full limit on reveal. What to look for in the new buildWhen the build ships, I'll update here with:
Thanks again for the quick review and merge. |
Post-build comparison: v1.4.142 (with PR #8279) vs baselineUpdated after running v1.4.143 for most of today (Jul 16). Same environment: macOS → Windows SSH, 5–8 SSH terminal tabs across multiple repos. Sessions per day
What improved
What persists
This confirms the original analysis: the rejection accumulation was a contributing factor, but the primary leak is the SSH PTY scrollback buffers that can't be parked. The fix here stopped the crash loop, but the underlying heap growth path was never rejection-driven. Next step: PR #8655 / PR #7448PR #8655 (my scrollback-trim approach for SSH hidden panes) is still open. Separately, community member @Zaradacht just commented on #8652 linking PR #7448, which appears to be the comprehensive solution — full terminal pane eviction with a mirror-replay restore, covering both SSH and remote-runtime PTYs. That PR has been marked READY since July 7. Given that today's session already hit 215 MB in ~2.5 hours, enabling even the opt-in flag in Settings would meaningfully help users with long-lived SSH workflows. |
Follow-up: v1.4.144, Jul 17Updated after one day on v1.4.144 (released today). Same environment: macOS → Windows SSH, 5–8 SSH terminal tabs open. Heap growth: still present, roughly same rate
Growth rate in the 11:17 session: ~26 MB/hr (lower than the 62 MB/hr from Jul 16, but PR #8655 and PR #7448 are not yet merged and SSH panes are still excluded from parking). Rejections remain at 0 across all sessions. ✅ Separate issue discovered: unexpected Electron subprocess crashesI've been seeing a pattern where the app exits unexpectedly — not an auto-update restart, not triggered by memory pressure or SSH disconnect. Electron Utility subprocesses (Audio Service, Network Service, GPU) are being killed with SIGTERM but with Full history across 6 days:
The Jul 17 crashes are particularly clear because the heap telemetry is available: both sessions started at 25 MB (fresh restart), had 0 heap growth, and crashed at exactly 13 minutes. Memory pressure is ruled out. Raw log entry for reference (Jul 17 17:13:02): The two Jul 17 crashes followed a cluster of 6 rapid auto-update restarts between 15:19 and 16:43 — it's possible the SSH relay or reconnection state gets into a bad state after rapid sequential restarts, and the next full session crashes when it tries to use it. This pattern predates v1.4.144 (9 events across Jul 12–17), so it's not something introduced by the recent change. Is this a known issue or something Sentry would catch separately? Happy to provide more log context if useful — I have the full OpenTelemetry trace for each of these sessions. |
Update: crash storm on Jul 17 — 6 unexpected crashes totalCorrection to my earlier comment today (which only reflected the first two crashes at 17:13 and 17:28): the crash continued, for a total of 6 consecutive unexpected crashes between 17:13 and 20:50 before the app finally stabilized. Full crash timeline today
All crashes: exit=15 (SIGTERM), New clue: crashes happen even with zero user interactionSessions at 19:39, 20:04, 20:24, and 20:36 had zero Possible connection to PR #8403PR #8403 ("reconnect persisted PTYs after shutdown races") shipped in v1.4.144 today. Previous versions (Jul 12-15) had 7 total unexpected crashes across 5 days. Today alone had 6. If #8403 introduced a background timer that fires ~10-15 minutes after startup to attempt PTY reconnection, and that reconnection path has an error that kills a utility subprocess, it would explain both the increased frequency and the background crash timing. Secondary finding: terminal_replay_guard_wedged_release (Jul 13-16 only)A different pattern worth separate investigation: 49 Also seen: lazy chunk reload with syntax errorOne Let me know if a crash minidump or the full OTel trace for one of these sessions would help narrow it down. |
|
Cross-posting a related finding: opened #9191 specifically for the SIGTERM crash pattern, which appears separate from the heap growth issue tracked here. Summary: Electron Utility subprocesses (Network/Audio/GPU) receive unexpected SIGTERM with |
…ons (stablyai#8279) Two renderer paths let Promise rejections escape unhandled, where the crash-breadcrumb system retains them and grows the heap until the renderer white-screens (stablyai#8260): - The terminal file-link provider fires a `void Promise.all(...)` whose async mappers probe path existence over SSH. On disconnect these reject with "Remote connection dropped/reconnecting"; add a `.catch` that resolves the callback with no links so the rejection is handled. - "ResizeObserver loop completed" is a benign Chromium quirk; suppress it in crash-diagnostics so it stops filling the breadcrumb buffer and inflating the renderer error count. Scope note: the original fix for stablyai#8260 also proposed Windows pty:kill signal handling (killPtyProcess / isPtyAlreadyGoneError) and a ResizeObserver double-rAF. Those landed on main independently (Windows kill handling by v1.4.135; the pane-title-overlay rect-equality guard from stablyai#2756 already breaks the loop at the source), so this change carries only the two guards still missing upstream. Co-authored-by: Yixian HU <[email protected]> Co-authored-by: Claude <[email protected]>
What this fixes
Two renderer paths let Promise rejections escape unhandled, where the crash-breadcrumb system retains them and grows the renderer heap until it white-screens (#8260):
createFilePathLinkProviderfired avoid Promise.all(...)whose async mappers probe path existence over the runtime. On SSH teardown these reject with "Remote connection dropped/reconnecting" (thefs:pathExistsflood in the reporter's trace). Added a.catchthat resolves the link callback with no links so the rejection is handled.crash-diagnosticsso it stops filling the breadcrumb buffer and inflating the renderer error count.Both are covered by new regression tests.
Scope note
This PR was reset from an earlier 122-commit revision that bundled a large terminal-teardown/retry-ownership refactor. That work turned out to be largely redundant with fixes that landed on
mainindependently during the same window (session retirement #8628, pane self-heal #8630, recovery-behind-stuck-connect #8673), and much of the original #8260 fix had also already reachedmain:pty:killsignal handling (killPtyProcess/isPtyAlreadyGoneError) — already onmain(v1.4.135).mainby thearePaneTitleOverlayRectsEqualbail-out (Fix terminal pane title focus handling #2756), so the double-rAF was dropped as redundant.pty.kill.catchguards were dropped because the main-side kill handler now swallows those rejections itself.So this PR carries only the two guards still genuinely missing upstream.
The prior 122-commit revision is preserved at
archive/pr-8279-review-sessionfor reference; the Windows node-pty pre-ready-shutdown patch and the SSH lease-generation fencing from it are the only pieces worth potentially extracting as separate, independently-reviewed PRs.Verification
terminal-link-handlers,crash-diagnostics), including the two new regression tests.tsc(web config) clean; oxlint/oxfmt clean.Not claimed
This does not by itself close the broader #8260 white-screen / OOM / ResizeObserver investigation; it removes two confirmed unhandled-rejection leak sources. #8260 stays open.