Skip to content

fix: stop renderer heap leak from unhandled terminal teardown rejections (#8260) - #8279

Merged
brennanb2025 merged 1 commit into
stablyai:mainfrom
iridite:fix/renderer-crash-white-screen
Jul 15, 2026
Merged

brennanb2025 merged 1 commit into
stablyai:mainfrom
iridite:fix/renderer-crash-white-screen

Conversation

@iridite

@iridite iridite commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

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):

  1. Terminal file-link probe (SSH): createFilePathLinkProvider fired a void Promise.all(...) whose async mappers probe path existence over the runtime. On SSH teardown these reject with "Remote connection dropped/reconnecting" (the fs:pathExists flood in the reporter's trace). Added a .catch that resolves the link callback with no links so the rejection is handled.
  2. ResizeObserver noise: "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.

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 main independently 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 reached main:

  • Windows pty:kill signal handling (killPtyProcess / isPtyAlreadyGoneError) — already on main (v1.4.135).
  • The ResizeObserver loop itself is already broken at the source on main by the arePaneTitleOverlayRectsEqual bail-out (Fix terminal pane title focus handling #2756), so the double-rAF was dropped as redundant.
  • The renderer pty.kill .catch guards 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-session for 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

  • 85 renderer unit tests pass (terminal-link-handlers, crash-diagnostics), including the two new regression tests.
  • tsc (web config) clean; oxlint/oxfmt clean.
  • Note: the underlying symptom is a slow multi-hour heap leak that can't be observed live in a short session; verification here exercises the exact rejection/suppression mechanisms via unit tests rather than a live soak.

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.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Windows 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is off-template and omits the required Summary, Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes sections. Rewrite the PR description to follow the repository template with all required headings and fill in testing, review, security, screenshots, and notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches one real focus of the PR, but it is narrower than the broader terminal teardown and Windows patch changeset.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ee3c2194-caff-43a6-a3e8-f52c7a251d3b

📥 Commits

Reviewing files that changed from the base of the PR and between ff8192a and 82a7ff7.

📒 Files selected for processing (7)
  • src/main/ipc/pty.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-link-handlers.ts
  • src/renderer/src/lib/crash-diagnostics.ts
  • src/renderer/src/store/slices/repos.ts

Comment thread src/relay/pty-handler.ts Resolved
Comment thread src/relay/pty-handler.ts Outdated
throw new Error(`PTY "${id}" not found`)
}
managed.pty.kill(signal)
killPtyProcess(managed.pty, signal)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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 -C2

Repository: 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 2

Repository: 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 2

Repository: 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.

@AmethystLiang AmethystLiang self-assigned this Jul 11, 2026
@AmethystLiang
AmethystLiang self-requested a review July 11, 2026 16:47
@brennanb2025 brennanb2025 changed the title fix: prevent renderer heap leak and white-screen crash (3 root causes) fix: make terminal teardown failures safe and diagnosable Jul 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Unguarded killPtyForShutdown inside setTimeout fallback 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 a setTimeout callback. The PR's own tests show a native Windows kill() 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 (unlike shutdown()'s RPC entry points, which are intentionally left unguarded to support caller retries).
  • An uncaught exception inside a setTimeout callback is not scoped to a Promise; by default Node.js treats it as an uncaughtException, 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 win

Handle Windows signals separately
pty.sendSignal is still exposed on the relay, and the Windows path is exercised with SIGWINCH. Since node-pty’s Windows kill(signal) throws for any signal, non-terminating signals like SIGWINCH will 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-lines conflicts 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-lines rule. As per coding guidelines, **/*.{js,jsx,ts,tsx} should "Never disable max-lines via ESLint or oxlint, including line-specific variants." Consider splitting pty-handler.ts into 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 win

Good coverage, but the fallback-timer throw path is untested.

These tests thoroughly cover the initial killPtyForShutdown call throwing and being retried, but none simulate the fallback SIGKILL timer (shutdown()'s 5s graceful fallback, or spawn()'s stale-cleanup fallback) itself throwing. That's precisely the unguarded path flagged in pty-handler.ts (lines 890-911 / 731-744) — a test exercising mockKill throwing 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

📥 Commits

Reviewing files that changed from the base of the PR and between 82a7ff7 and 4be8dd3.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (17)
  • config/patches/[email protected]
  • config/reliability-gates.jsonc
  • config/scripts/build-relay-windows-node-pty-patch.test.mjs
  • config/scripts/build-relay.mjs
  • config/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjs
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-native-deps-install.test.ts
  • src/relay/node-pty-windows-pre-ready-shutdown.test.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-link-handlers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-link-handlers.ts
  • src/renderer/src/components/terminal-pane/terminal-link-probe-results.ts
  • src/renderer/src/store/slices/repos-remove-project-purge-leak.test.ts
  • src/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

Comment on lines +70 to +78
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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])
PY

Repository: 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]))
PY

Repository: 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`'])
PY

Repository: 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:


🏁 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)
PY

Repository: 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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

@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

brennanb2025
brennanb2025 previously approved these changes Jul 14, 2026

@brennanb2025 brennanb2025 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5258b621-a198-4a44-af35-6246daa99790

📥 Commits

Reviewing files that changed from the base of the PR and between 4be8dd3 and ba9e0b4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (36)
  • config/reliability-gates.jsonc
  • config/scripts/build-relay-windows-node-pty-patch.test.mjs
  • config/scripts/build-relay.mjs
  • config/scripts/relay-node-pty-windows-pre-ready-shutdown-patch.cjs
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-main.test.ts
  • src/main/daemon/daemon-main.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-provider.test.ts
  • src/main/daemon/daemon-pty-provider.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/daemon-session-exit-fence.test.ts
  • src/main/daemon/daemon-session-exit-fence.ts
  • src/main/daemon/daemon-spawner.test.ts
  • src/main/daemon/daemon-stream-events.ts
  • src/main/daemon/degraded-daemon-fallback-shutdown.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/daemon/pty-provider-route-reconciliation.test.ts
  • src/main/daemon/pty-provider-route-reconciliation.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/slow-daemon-session-verification.test.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/terminal-host-session-reaping-leak.test.ts
  • src/main/daemon/terminal-host-shutdown-drain.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/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

Comment thread config/reliability-gates.jsonc Outdated
Comment on lines +3779 to +3782
"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.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
"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"],

Comment thread src/main/daemon/session.test.ts Outdated
Comment on lines +60 to +62
hasExited() {
return killed
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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)
}
}
}

Comment thread src/main/daemon/session.ts Outdated
Comment on lines 71 to 81
/** 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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
/** 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
}

Comment thread src/main/daemon/session.ts Outdated
Comment on lines +319 to +333
/** 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())
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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/**' || true

Repository: 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 -n

Repository: 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 -n

Repository: 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 -n

Repository: 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 -n

Repository: 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 killTimer here before issueForceShutdown(), 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]>
@brennanb2025
brennanb2025 force-pushed the fix/renderer-crash-white-screen branch from ba9e0b4 to bd0a0a8 Compare July 14, 2026 23:40
@brennanb2025
brennanb2025 dismissed their stale review July 14, 2026 23:41

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.

@brennanb2025 brennanb2025 changed the title fix: make terminal teardown failures safe and diagnosable fix: stop renderer heap leak from unhandled terminal teardown rejections (#8260) Jul 14, 2026
@brennanb2025
brennanb2025 merged commit 70e16cb into stablyai:main Jul 15, 2026
1 check passed
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the PR! Sorry about the review weirdness, my agent got stuck in a review loop. But the core fix is much appreciated!

@brennanb2025

Copy link
Copy Markdown
Contributor

@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!

@iridite

iridite commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

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

Date Sessions Short (<15 min) Max peak heap Total rejections
Jul 12 16 6 169 MB 0
Jul 13 20 9 169 MB 11
Jul 14 33 16 159 MB 21
Jul 15 (today, pre-build) 8 5 179 MB 0

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

Date Type Count
Jul 13 "Signals not supported on windows" (fixed by this PR) 11
Jul 14 Error invoking remote method 'pty:kill': Error: SSH connection lost, reconnecting... 9
Jul 14 Error invoking remote method 'fs:pathExists': Error: Multiplexer disposed 9
Jul 14 Other 3

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 rejections

This is the most important data point. 12 sessions show ≥ 80 MB peak heap with 0 unhandled rejections, some reaching 169 MB:

07-12  15:11   35 min   23 → 87 MB   (+64 MB)   0 rejections
07-12  15:46  110 min   23 → 98 MB   (+75 MB)   0 rejections
07-12  17:37   98 min   23 → 169 MB  (+146 MB)  0 rejections
07-12  20:22  126 min   23 → 98 MB   (+75 MB)   0 rejections
07-13  10:55   45 min   23 → 98 MB   (+75 MB)   0 rejections
07-14  13:44   50 min   23 → 133 MB  (+110 MB)  0 rejections
07-14  15:08   70 min   23 → 125 MB  (+102 MB)  0 rejections
07-15  08:44  160 min   23 → 78 MB   (+55 MB)   0 rejections
07-15  12:13  111 min   23 → 179 MB  (+156 MB)  0 rejections  ← today, pre-build

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 leak

All repos in this setup connect via SSH (ssh:<id>@@pty-<n> IDs). SSH PTYs are excluded from canParkTerminalTabRenderer() because they have no daemon snapshot. With terminalHiddenViewParking: true, local panes get parked and their xterm instances freed after 30 s, but SSH panes stay mounted indefinitely with full scrollback buffers.

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 build

When the build ships, I'll update here with:

Thanks again for the quick review and merge.

@iridite

iridite commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

Post-build comparison: v1.4.142 (with PR #8279) vs baseline

Updated 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

Date Version Sessions Short (<15 min) Max heap Rejections
Jul 12 pre-fix 16 6 169 MB 0
Jul 13 pre-fix 20 9 169 MB 11
Jul 14 pre-fix 33 16 159 MB 21
Jul 15 pre-fix 8 5 179 MB 0
Jul 16 v1.4.143 (this PR) 9 2 215 MB 0

What improved

  • ✅ Unhandled rejections: 0 — completely gone (was 11–21/day when the Windows PTY signal path was active)
  • ✅ Short sessions dropped from 6–16 to 2 — fewer white-screen crashes forcing manual restarts
  • ✅ Total daily restarts down from 20–33 to 9

What persists

  • ❌ Heap still grows — and now grows further because sessions run longer without crashing first. Today's peak was 215 MB in a 143-minute session (23 → 215 MB, 0 rejections). The 61.5 MB/hr average growth rate is unchanged.

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 #7448

PR #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.

@iridite

iridite commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: v1.4.144, Jul 17

Updated 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

Session start Duration Peak heap Rejections
11:17 198 min 111 MB 0
14:35 43 min 104 MB 0
15:51 51 min 54 MB 0

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 crashes

I'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 expectedTeardown: 'none', indicating the main process was not the one requesting the shutdown.

Full history across 6 days:

Date Session start Elapsed at crash Processes killed Heap at crash
Jul 12 12:34 +7m36s Audio Service —
Jul 12 15:46 +106m Audio + Network Service —
Jul 13 08:50 +6m15s Audio + Network + GPU —
Jul 14 09:34 +15m Audio Service —
Jul 14 18:09 +62m Network + Audio Service —
Jul 14 19:59 +93m Audio + GPU —
Jul 15 17:43 +19m50s Audio + Network Service —
Jul 17 16:59 +13m07s Audio + Network Service 25 MB
Jul 17 17:14 +13m13s Network Service + GPU 25 MB

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):

{"breadcrumb.name":"process_gone_suppressed","breadcrumb.data":{"source":"child","processType":"Utility","reason":"killed","exitCode":15,"expectedTeardown":"none","name":"Network Service"}}

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.

@iridite

iridite commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

Update: crash storm on Jul 17 — 6 unexpected crashes total

Correction 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

Session start Elapsed → crash Processes Heap SSH activations
16:59 +13m07s → 17:13 Audio + Network 25 MB 3
17:14 +13m13s → 17:28 Network + GPU 25 MB 4
19:39 +11m31s → 19:51 Network + GPU 25 MB 0
20:04 +20m28s → 20:24 Network + GPU 61 MB 0
20:24 +10m59s → 20:35 Network + Audio 25 MB 0
20:36 +14m34s → 20:50 Audio + Network 25 MB 0
20:51 no crash — 179 MB 0

All crashes: exit=15 (SIGTERM), expectedTeardown: 'none'. After 6 cycles the app stabilized on its own.

New clue: crashes happen even with zero user interaction

Sessions at 19:39, 20:04, 20:24, and 20:36 had zero sidebar_worktree_activate events — the user did not switch to any worktree or trigger any visible SSH activity. The crashes happened at 10-20 minutes purely in the background, without any user action. This rules out user-triggered SSH activity as the cause.

Possible connection to PR #8403

PR #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 terminal_replay_guard_wedged_release events across Jul 13-16, always on paneId: 1 (the first terminal pane), in bursts of 4-9. These stopped completely after upgrading to v1.4.144 today. Each burst triggered the replay-guard watchdog 4-9 times in the same second, suggesting the first SSH terminal pane's replay state was repeatedly getting wedged. This appears to be a different issue that #8403 may have incidentally fixed — or it may have shifted the failure mode from wedge to crash.

Also seen: lazy chunk reload with syntax error

One lazy_chunk_reload event on Jul 17 at 14:35 with message: 'Illegal return statement' — a JS bundle chunk triggered a reload due to a syntax error. Timing aligns with the v1.4.144 update download.

Let me know if a crash minidump or the full OTel trace for one of these sessions would help narrow it down.

@iridite

iridite commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

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 expectedTeardown: 'none' — 13 crashes across Jul 12-17, escalating from ~1/day to 6 on Jul 17 (the same day v1.4.144 shipped with PR #8403). The crashes happen in the background with zero user SSH activity and at consistent ~10-20 min intervals, suggesting a background reconnection timer. The terminal_replay_guard_wedged_release events that appeared on Jul 13-16 also disappeared after upgrading to v1.4.144, suggesting the SSH reconnect path changed significantly.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants