Skip to content

Fix terminal activation WebGL cleanup and stale PTY recovery - #7080

Closed
Jinwoo-H wants to merge 1 commit into
mainfrom
bug-windows-apphangb1-when-opening-activating-te
Closed

Jinwoo-H wants to merge 1 commit into
mainfrom
bug-windows-apphangb1-when-opening-activating-te

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Summary

  • actively releases xterm WebGL contexts when terminal panes are disposed, instead of relying only on xterm/canvas removal
  • routes pane disposal through the shared WebGL teardown path
  • makes pty:kill synthesize a renderer pty:exit when provider shutdown is otherwise silent, with duplicate suppression for late provider exits
  • adds a Windows-only reproduction harness for issue [Bug]: Windows AppHangB1 when opening/activating terminal session #6874 that drives the real Electron app against real WSL UNC workspaces and terminal PTYs

Refs #6874

Why

Issue #6874 reports Windows AppHangB1 around opening or activating terminal/workspace sessions. This PR does not disable WebGL. Instead, it reproduces and fixes two concrete terminal-activation failures in the reported-style workflow: WebGL context accumulation and stale PTY reactivation.

The repro harness exercises the close user scenario: Windows Electron, WSL \\wsl.localhost\... git repo/worktrees, repeated sidebar worktree activation, real terminal panes/PTYs, high-volume terminal output, source-control sidebar open, and dead-PTY reactivation.

The harness exposed:

  1. WebGL context pressure. Repeated activation with WebGL enabled produced Chromium warnings:
    WARNING: Too many active WebGL contexts. Oldest context will be lost.

    Before-fix report: apphang-auto-webgl-enabled-rerun-report.json, webglContextWarningCount=5.

  2. Stale PTY reactivation. After killing terminal PTYs and revisiting worktrees, the renderer could keep writing to a dead PTY id or fail to recreate an active terminal.

This does not claim to prove the literal Windows WER AppHangB1 root cause from a crash dump. It does prove and fix reproducible WebGL resource pressure and stale terminal activation behavior in the same Windows/WSL workflow.

Reproduction Harness

Added:

  • config/scripts/repro-windows-apphang-terminal-activation.mjs
  • config/scripts/windows-apphang-repro/*.mjs

The harness:

  • creates a disposable WSL fixture with a git repo, 4 external worktrees, and a plain folder
  • launches the real Orca dev Electron app with CDP and an isolated user data dir
  • registers WSL UNC paths in Orca
  • clicks real worktree cards in the sidebar
  • waits for the real terminal tab, pane manager, and PTY binding
  • writes high-volume output to the PTY and waits for completion markers
  • optionally kills PTYs and reactivates worktrees to test stale-session recovery
  • records renderer/main diagnostics, WebGL context warning counts, WebGL counts, timing, and log tails

Verification

Post-rebase full harness:

node config\scripts\repro-windows-apphang-terminal-activation.mjs --gpu=auto --cycles=14 --output-lines=1600 --expect=pass --report=.\previews\apphang-auto-full-post-rebase-report.json

Result:

  • reproduced=false
  • sampleCount=26
  • webglContextWarningCount=0
  • final WebGL contexts: attachedWebglCount=1, deferredWebglCount=5, managerCount=6, paneCount=6
  • maxMainIpcMs=44

Focused tests and checks:

pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts src/renderer/src/lib/pane-manager/pane-lifecycle.test.ts src/renderer/src/lib/pane-manager/terminal-webgl-auto-policy.test.ts
pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts -t "daemon-backed pty kill|duplicate renderer exit|late provider exit"
pnpm exec oxlint src/main/ipc/pty.ts src/main/ipc/pty.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts src/renderer/src/lib/pane-manager/pane-lifecycle.ts src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts config/scripts/repro-windows-apphang-terminal-activation.mjs config/scripts/windows-apphang-repro --quiet
node --check config\scripts\repro-windows-apphang-terminal-activation.mjs
node --check config\scripts\windows-apphang-repro\apphang-report-summary.mjs
node --check config\scripts\windows-apphang-repro\electron-dev-session.mjs
node --check config\scripts\windows-apphang-repro\repro-timing.mjs
node --check config\scripts\windows-apphang-repro\terminal-activation-scenario.mjs
node --check config\scripts\windows-apphang-repro\wsl-workspace-fixture.mjs

Additional before/after evidence from the same harness:

  • Before WebGL cleanup: webglContextWarningCount=5
  • After WebGL cleanup: webglContextWarningCount=0
  • Forced WebGL after cleanup: webglContextWarningCount=0
  • Full workflow after PTY fix: passed 14 cycles plus dead-PTY reactivation with webglContextWarningCount=0

Risk

  • WebGL teardown reaches into xterm WebGL internals to call WEBGL_lose_context; this is guarded and normal addon disposal still runs.
  • PTY kill handling now fills in missing renderer exit events; tests cover no-provider-exit, provider-exit, and late-provider-exit cases to avoid double close.
  • SSH/remote PTY behavior is kept behind provider/connection checks and idempotent cleanup.

@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

This PR adds a new Windows-only reproduction harness (CLI script plus supporting modules) that automates a WSL-backed Electron app to stress terminal activation, measure timing signals, capture renderer/WebGL diagnostics, and report reproduction evidence. Separately, it fixes pty:kill IPC handling in the main process to guarantee exactly one pty:exit renderer notification via a new synthetic-kill tracking mechanism, with expanded tests. Additionally, pane WebGL disposal now explicitly releases the xterm WebGL GPU context and resets canvas dimensions before disposing the addon, wired through pane lifecycle teardown.

Sequence Diagram(s)

Diagrams included in the hidden review stack artifact illustrate the repro scenario execution flow and the pty:kill exit delivery flow.

Related PRs: None found.

Suggested labels: enhancement, bug fix, tooling

Suggested reviewers: None specified.

🐰 A hare-brained script hunts a Windows hang,
Through WSL worktrees it does gang,
One clean exit for every kill,
WebGL contexts released with skill,
The terminal stress test rings its bang!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning It covers summary, rationale, harness, verification, and risk, but misses required template sections like Screenshots, Testing, AI Review Report, Security Audit, and Notes. Add the missing template sections and include screenshots status, testing checklist results, AI review report, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main changes: terminal activation cleanup, PTY recovery, and WebGL cleanup.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (5)
config/scripts/windows-apphang-repro/electron-dev-session.mjs (2)

63-63: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Build the script path with Node path utilities.

Avoid the slash-delimited script path in spawn. As per coding guidelines, use path.join or Electron/Node path utilities for file paths — never assume / or \ for cross-platform compatibility.

Proposed fix
-  const child = spawn(process.execPath, ['config/scripts/run-electron-vite-dev.mjs'], {
+  const child = spawn(process.execPath, [path.join('config', 'scripts', 'run-electron-vite-dev.mjs')], {

Source: Coding guidelines


211-239: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the throwaway WebGL context cleanup.

This probe intentionally creates and immediately loses a WebGL context; add a short rationale so future changes do not skew the context-pressure measurement. As per coding guidelines, non-obvious constraints should have a short comment explaining why.

Proposed fix
           const readWebglIdentity = () => {
+            // This probe creates a throwaway context; lose it immediately so
+            // diagnostics do not add WebGL pressure to the repro.
             const canvas = document.createElement('canvas')

Source: Coding guidelines

src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts (1)

68-90: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Good coverage; consider also asserting the extension name.

Test correctly verifies loseContext is invoked, dispose runs once, canvas is zeroed, and webglAddon becomes null. One small gap: getExtension is mocked to return the stub regardless of the argument, so a typo in the extension name ('WEBGL_lose_context') at the call site wouldn't be caught.

🧪 Optional strengthening
     const pane = createPane({
       webglAddon: {
         dispose,
         _renderer: {
           _gl: {
             getExtension: vi.fn(() => ({ loseContext }))
           },
           _canvas: canvas
         }
       } as never
     })

     disposeWebgl(pane)

     expect(loseContext).toHaveBeenCalledTimes(1)
+    expect(pane.webglAddon).toBeNull() // already asserted below, kept for context

Add an assertion on the mocked getExtension call args, e.g. expect(pane.webglAddon._renderer._gl.getExtension).toHaveBeenCalledWith('WEBGL_lose_context') before it's nulled out, or capture the mock reference beforehand.

src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts (1)

86-101: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a warning when WebGL internals are missing
This reaches into private @xterm/addon-webgl fields, so a future addon bump could turn the teardown into a silent no-op. Add a dev-only warning or telemetry when _renderer, _gl, or _canvas are absent so the fallback path stays visible.

config/scripts/windows-apphang-repro/terminal-activation-scenario.mjs (1)

197-200: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a short why-comment for the POSIX shell command.

This Windows-only harness sends POSIX shell syntax because the fixture targets WSL UNC workspaces; that constraint is non-obvious at the call site.

As per coding guidelines, “When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does.”

Proposed comment
 function makeOutputCommand(marker, outputLines) {
   const payload = 'x'.repeat(180)
+  // WSL UNC workspaces open a POSIX shell, even though the harness runs from Windows.
   return `printf '${marker}_START\\n'; i=1; while [ "$i" -le ${outputLines} ]; do printf '${marker}_%05d ${payload}\\n' "$i"; i=$((i+1)); done; printf '${marker}_DONE\\n'\r`
 }

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: eac4323a-83e5-4f31-b4fe-cecae9d551e1

📥 Commits

Reviewing files that changed from the base of the PR and between c29bf6f and b9b5f1a.

📒 Files selected for processing (11)
  • config/scripts/repro-windows-apphang-terminal-activation.mjs
  • config/scripts/windows-apphang-repro/apphang-report-summary.mjs
  • config/scripts/windows-apphang-repro/electron-dev-session.mjs
  • config/scripts/windows-apphang-repro/repro-timing.mjs
  • config/scripts/windows-apphang-repro/terminal-activation-scenario.mjs
  • config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/renderer/src/lib/pane-manager/pane-lifecycle.ts
  • src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts
  • src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts

Comment on lines +127 to +130
const page =
pages.find((candidate) =>
/^https?:\/\/127\.0\.0\.1:|^https?:\/\/localhost:/.test(candidate.url())
) ?? pages[0]

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 | 🟡 Minor | ⚡ Quick win

Wait for the actual renderer page instead of falling back immediately.

pages[0] can be an auxiliary/blank CDP target; returning it makes waitForStoreReady() poll the wrong page. Keep polling until the localhost renderer appears.

Proposed fix
-      const page =
-        pages.find((candidate) =>
-          /^https?:\/\/127\.0\.0\.1:|^https?:\/\/localhost:/.test(candidate.url())
-        ) ?? pages[0]
+      const page = pages.find((candidate) =>
+        /^https?:\/\/127\.0\.0\.1:|^https?:\/\/localhost:/.test(candidate.url())
+      )
📝 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
const page =
pages.find((candidate) =>
/^https?:\/\/127\.0\.0\.1:|^https?:\/\/localhost:/.test(candidate.url())
) ?? pages[0]
const page = pages.find((candidate) =>
/^https?:\/\/127\.0\.0\.1:|^https?:\/\/localhost:/.test(candidate.url())
)

Comment on lines +201 to +210
const timed = (label, promise) =>
Promise.race([
Promise.resolve(promise).then(
(value) => ({ value }),
(error) => ({ error: error instanceof Error ? error.message : String(error) })
),
new Promise((resolve) =>
setTimeout(() => resolve({ error: `Timed out collecting ${label}` }), 1_000)
)
])

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

Wrap diagnostic API calls in thunks.

timed(label, promise) only catches promise rejection; a synchronous throw while creating the promise aborts the whole diagnostics payload. Pass a callback so each diagnostic remains isolated.

Proposed fix
-          const timed = (label, promise) =>
+          const timed = (label, read) =>
             Promise.race([
-              Promise.resolve(promise).then(
+              Promise.resolve().then(read).then(
                 (value) => ({ value }),
                 (error) => ({ error: error instanceof Error ? error.message : String(error) })
               ),
-            ptySessions: await timed('PTY sessions', window.api?.pty?.listSessions?.()),
+            ptySessions: await timed('PTY sessions', () => window.api?.pty?.listSessions?.()),
             rendererDeliveryDebug: await timed(
               'renderer delivery debug',
-              window.api?.pty?.getRendererDeliveryDebugSnapshot?.()
+              () => window.api?.pty?.getRendererDeliveryDebugSnapshot?.()
             )

Also applies to: 315-319

Comment on lines +336 to +350
async function runDeadPtyReactivation(page, targets, args) {
const samples = []
for (const target of targets) {
await clickWorktreeCard(page, target.id)
await waitForActiveWorktree(page, target.id)
await waitForActivePty(page, target.id)
const killedPtyId = await killActivePty(page)
samples.push({ worktreeId: target.id, killedPtyId })
}
for (const target of targets) {
samples.push(
await runActivationCycle(page, { ...target, kind: `${target.kind}:dead-pty` }, args)
)
}
return samples

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep dead-PTY setup records out of samples.

runDeadPtyReactivation pushes { worktreeId, killedPtyId } into result.samples, but summarizeResult counts every object in samples as a measured activation sample. This inflates sampleCount and mixes schemas in the evidence payload.

Proposed schema split
 async function runDeadPtyReactivation(page, targets, args) {
+  const killedPtys = []
   const samples = []
   for (const target of targets) {
     await clickWorktreeCard(page, target.id)
     await waitForActiveWorktree(page, target.id)
     await waitForActivePty(page, target.id)
     const killedPtyId = await killActivePty(page)
-    samples.push({ worktreeId: target.id, killedPtyId })
+    killedPtys.push({ worktreeId: target.id, killedPtyId })
   }
   for (const target of targets) {
     samples.push(
       await runActivationCycle(page, { ...target, kind: `${target.kind}:dead-pty` }, args)
     )
   }
-  return samples
+  return { killedPtys, samples }
 }
     setup: null,
     samples: [],
+    deadPtyKills: [],
     finalDiagnostics: null,
       }
       console.log(`[apphang-repro] dead-pty-reactivation gpu=${gpuMode}`)
-      result.samples.push(...(await runDeadPtyReactivation(page, uniqueTargets, args)))
+      const deadPtyRun = await runDeadPtyReactivation(page, uniqueTargets, args)
+      result.deadPtyKills.push(...deadPtyRun.killedPtys)
+      result.samples.push(...deadPtyRun.samples)
     }

Also applies to: 380-395, 423-433

Comment on lines +435 to +444
} catch (error) {
if (error instanceof ReproductionObservedError) {
result.reproduced = true
result.reproductionReason = error.message
result.samples.push(error.evidence)
} else {
result.reproduced = true
result.reproductionReason =
error instanceof Error ? error.stack || error.message : String(error)
}

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

Don’t classify setup/infrastructure failures as reproductions.

The generic catch marks every error as reproduced. If app connection or fixture registration fails before the stress scenario starts, --expect=repro can pass without observing hang evidence.

Proposed guard
   let browser = null
   let page = null
+  let scenarioStarted = false
   const startedAt = Date.now()
     )
     for (const target of targets) {
       console.log(`[apphang-repro] cycle=${target.index} gpu=${gpuMode} kind=${target.kind}`)
+      scenarioStarted = true
       result.samples.push(await runActivationCycle(page, target, args))
     }
     if (error instanceof ReproductionObservedError) {
       result.reproduced = true
       result.reproductionReason = error.message
       result.samples.push(error.evidence)
-    } else {
+    } else if (scenarioStarted) {
       result.reproduced = true
       result.reproductionReason =
         error instanceof Error ? error.stack || error.message : String(error)
+    } else {
+      throw error
     }
📝 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
} catch (error) {
if (error instanceof ReproductionObservedError) {
result.reproduced = true
result.reproductionReason = error.message
result.samples.push(error.evidence)
} else {
result.reproduced = true
result.reproductionReason =
error instanceof Error ? error.stack || error.message : String(error)
}
let browser = null
let page = null
let scenarioStarted = false
const startedAt = Date.now()
Suggested change
} catch (error) {
if (error instanceof ReproductionObservedError) {
result.reproduced = true
result.reproductionReason = error.message
result.samples.push(error.evidence)
} else {
result.reproduced = true
result.reproductionReason =
error instanceof Error ? error.stack || error.message : String(error)
}
)
for (const target of targets) {
console.log(`[apphang-repro] cycle=${target.index} gpu=${gpuMode} kind=${target.kind}`)
scenarioStarted = true
result.samples.push(await runActivationCycle(page, target, args))
}
Suggested change
} catch (error) {
if (error instanceof ReproductionObservedError) {
result.reproduced = true
result.reproductionReason = error.message
result.samples.push(error.evidence)
} else {
result.reproduced = true
result.reproductionReason =
error instanceof Error ? error.stack || error.message : String(error)
}
} catch (error) {
if (error instanceof ReproductionObservedError) {
result.reproduced = true
result.reproductionReason = error.message
result.samples.push(error.evidence)
} else if (scenarioStarted) {
result.reproduced = true
result.reproductionReason =
error instanceof Error ? error.stack || error.message : String(error)
} else {
throw error
}

Comment on lines +8 to +23
function runWsl(distro, script, options = {}) {
return execFileSync('wsl.exe', ['-d', distro, '--', 'bash', '-se'], {
cwd: rootDir,
encoding: 'utf8',
input: script,
timeout: options.timeoutMs ?? 120_000,
stdio: ['pipe', 'pipe', 'pipe']
})
}

export function listWslDistros() {
const output = execFileSync('wsl.exe', ['--list', '--quiet'], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 10_000
})

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

Guard WSL-only execution in this module.

These helpers directly invoke wsl.exe; add a local process.platform === 'win32' check so direct imports fail with the intended Windows-only message instead of ENOENT. As per coding guidelines, keep all platform-dependent behavior behind runtime checks.

Proposed fix
+function assertWindowsHost() {
+  if (process.platform !== 'win32') {
+    throw new Error('This repro harness requires Windows with WSL installed.')
+  }
+}
+
 function runWsl(distro, script, options = {}) {
+  assertWindowsHost()
   return execFileSync('wsl.exe', ['-d', distro, '--', 'bash', '-se'], {
 export function listWslDistros() {
+  assertWindowsHost()
   const output = execFileSync('wsl.exe', ['--list', '--quiet'], {
📝 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
function runWsl(distro, script, options = {}) {
return execFileSync('wsl.exe', ['-d', distro, '--', 'bash', '-se'], {
cwd: rootDir,
encoding: 'utf8',
input: script,
timeout: options.timeoutMs ?? 120_000,
stdio: ['pipe', 'pipe', 'pipe']
})
}
export function listWslDistros() {
const output = execFileSync('wsl.exe', ['--list', '--quiet'], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 10_000
})
function assertWindowsHost() {
if (process.platform !== 'win32') {
throw new Error('This repro harness requires Windows with WSL installed.')
}
}
function runWsl(distro, script, options = {}) {
assertWindowsHost()
return execFileSync('wsl.exe', ['-d', distro, '--', 'bash', '-se'], {
cwd: rootDir,
encoding: 'utf8',
input: script,
timeout: options.timeoutMs ?? 120_000,
stdio: ['pipe', 'pipe', 'pipe']
})
}
export function listWslDistros() {
assertWindowsHost()
const output = execFileSync('wsl.exe', ['--list', '--quiet'], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 10_000
})

Source: Coding guidelines

Comment on lines +93 to +123
export function createCompletedOnboardingProfile(userDataDir) {
mkdirSync(userDataDir, { recursive: true })
const profile = {
settings: {
telemetry: {
optedIn: true,
installId: '00000000-0000-4000-8000-000000000000',
existedBeforeTelemetryRelease: false
}
},
onboarding: {
flowVersion: 4,
closedAt: 1,
outcome: 'completed',
lastCompletedStep: 5
},
ui: {
contextualToursAutoEligible: false,
contextualToursSeenIds: [
'workspace-board',
'browser',
'tasks',
'automations',
'workspace-creation'
],
featureTipsSeenIds: [],
featureInteractions: {},
projectOrderManualDefaultNoticeDismissed: true
}
}
writeFileSync(path.join(userDataDir, 'orca-data.json'), `${JSON.stringify(profile, null, 2)}\n`)

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not opt repro runs into telemetry.

The harness marks onboarding complete but also sets telemetry.optedIn: true; running the real app can pollute telemetry with repro data. Prefer false unless this scenario explicitly needs telemetry enabled.

Proposed fix
       telemetry: {
-        optedIn: true,
+        optedIn: false,
         installId: '00000000-0000-4000-8000-000000000000',
📝 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
export function createCompletedOnboardingProfile(userDataDir) {
mkdirSync(userDataDir, { recursive: true })
const profile = {
settings: {
telemetry: {
optedIn: true,
installId: '00000000-0000-4000-8000-000000000000',
existedBeforeTelemetryRelease: false
}
},
onboarding: {
flowVersion: 4,
closedAt: 1,
outcome: 'completed',
lastCompletedStep: 5
},
ui: {
contextualToursAutoEligible: false,
contextualToursSeenIds: [
'workspace-board',
'browser',
'tasks',
'automations',
'workspace-creation'
],
featureTipsSeenIds: [],
featureInteractions: {},
projectOrderManualDefaultNoticeDismissed: true
}
}
writeFileSync(path.join(userDataDir, 'orca-data.json'), `${JSON.stringify(profile, null, 2)}\n`)
export function createCompletedOnboardingProfile(userDataDir) {
mkdirSync(userDataDir, { recursive: true })
const profile = {
settings: {
telemetry: {
optedIn: false,
installId: '00000000-0000-4000-8000-000000000000',
existedBeforeTelemetryRelease: false
}
},
onboarding: {
flowVersion: 4,
closedAt: 1,
outcome: 'completed',
lastCompletedStep: 5
},
ui: {
contextualToursAutoEligible: false,
contextualToursSeenIds: [
'workspace-board',
'browser',
'tasks',
'automations',
'workspace-creation'
],
featureTipsSeenIds: [],
featureInteractions: {},
projectOrderManualDefaultNoticeDismissed: true
}
}
writeFileSync(path.join(userDataDir, 'orca-data.json'), `${JSON.stringify(profile, null, 2)}\n`)

Comment thread src/main/ipc/pty.ts
Comment on lines +1686 to +1705
function sendPtyExitToRenderer(payload: { id: string; code: number }): void {
if (mainWindow.isDestroyed()) {
return
}
// Why: flush any batched data for this PTY before sending the exit event,
// otherwise the last <=8ms of output is silently lost because the renderer
// tears down the terminal on pty:exit before the batch timer fires.
const remaining = pendingData.get(payload.id)
if (remaining) {
sendPtyDataToRenderer(
payload.id,
makePtyDataPayload(
payload.id,
remaining.data,
remaining.startSeq,
remaining.containsBackgroundOutput
)
)
pendingData.delete(payload.id)
}

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

Preserve the PTY batch chunking limit when flushing before exit.

Line 1699 sends the entire pending buffer in one pty:data IPC payload. If a high-output PTY is killed while ACK-gated or backgrounded, pendingData can be much larger than PTY_BATCH_FLUSH_CHUNK_CHARS, reintroducing a large synchronous IPC/serialization spike right before pty:exit.

Suggested fix
     const remaining = pendingData.get(payload.id)
     if (remaining) {
-      sendPtyDataToRenderer(
-        payload.id,
-        makePtyDataPayload(
-          payload.id,
-          remaining.data,
-          remaining.startSeq,
-          remaining.containsBackgroundOutput
-        )
-      )
       pendingData.delete(payload.id)
+      for (let offset = 0; offset < remaining.data.length; offset += PTY_BATCH_FLUSH_CHUNK_CHARS) {
+        const chunk = remaining.data.slice(offset, offset + PTY_BATCH_FLUSH_CHUNK_CHARS)
+        const startSeq =
+          typeof remaining.startSeq === 'number' ? remaining.startSeq + offset : undefined
+        sendPtyDataToRenderer(
+          payload.id,
+          makePtyDataPayload(
+            payload.id,
+            chunk,
+            startSeq,
+            remaining.containsBackgroundOutput
+          )
+        )
+      }
     }
📝 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
function sendPtyExitToRenderer(payload: { id: string; code: number }): void {
if (mainWindow.isDestroyed()) {
return
}
// Why: flush any batched data for this PTY before sending the exit event,
// otherwise the last <=8ms of output is silently lost because the renderer
// tears down the terminal on pty:exit before the batch timer fires.
const remaining = pendingData.get(payload.id)
if (remaining) {
sendPtyDataToRenderer(
payload.id,
makePtyDataPayload(
payload.id,
remaining.data,
remaining.startSeq,
remaining.containsBackgroundOutput
)
)
pendingData.delete(payload.id)
}
function sendPtyExitToRenderer(payload: { id: string; code: number }): void {
if (mainWindow.isDestroyed()) {
return
}
// Why: flush any batched data for this PTY before sending the exit event,
// otherwise the last <=8ms of output is silently lost because the renderer
// tears down the terminal on pty:exit before the batch timer fires.
const remaining = pendingData.get(payload.id)
if (remaining) {
pendingData.delete(payload.id)
for (let offset = 0; offset < remaining.data.length; offset += PTY_BATCH_FLUSH_CHUNK_CHARS) {
const chunk = remaining.data.slice(offset, offset + PTY_BATCH_FLUSH_CHUNK_CHARS)
const startSeq =
typeof remaining.startSeq === 'number' ? remaining.startSeq + offset : undefined
sendPtyDataToRenderer(
payload.id,
makePtyDataPayload(
payload.id,
chunk,
startSeq,
remaining.containsBackgroundOutput
)
)
}
}

@brennanb2025

Copy link
Copy Markdown
Contributor

Superseded by #7085 (merged 2026-07-02), which landed a superset of this. The WebGL release-on-dispose (releaseXtermWebglContext → WEBGL_lose_context.loseContext(), kept through the #7169 revert) and the synthetic kill-exit recovery (rememberSyntheticKillExit / consumeSyntheticKillExit / sendPtyExitToRenderer) are both in main now, extended to additional kill paths. Nothing to rebase here — closing this stale one. #6874 tracks the underlying AppHangB1 hang.

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.

2 participants