Improve Windows terminal performance: retain WebGL contexts, warm first ConPTY (#7085)
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { mkdirSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import process from 'node:process'
|
||||
import {
|
||||
createWslFixture,
|
||||
listWslDistros,
|
||||
removeWslFixture
|
||||
} from './windows-apphang-repro/wsl-workspace-fixture.mjs'
|
||||
import { runGpuMode } from './windows-apphang-repro/terminal-activation-scenario.mjs'
|
||||
import { summarizeResult } from './windows-apphang-repro/apphang-report-summary.mjs'
|
||||
|
||||
const defaultCycles = 14
|
||||
const defaultOutputLines = 1_600
|
||||
|
||||
function parseArgs() {
|
||||
const args = {
|
||||
cycles: defaultCycles,
|
||||
distro: null,
|
||||
expect: 'none',
|
||||
gpuModes: ['on'],
|
||||
keep: false,
|
||||
outputLines: defaultOutputLines,
|
||||
reportPath: null,
|
||||
sourceControl: true,
|
||||
deadPtyReactivate: true
|
||||
}
|
||||
|
||||
for (const arg of process.argv.slice(2)) {
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
printHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
if (arg === '--keep') {
|
||||
args.keep = true
|
||||
continue
|
||||
}
|
||||
if (arg === '--no-source-control') {
|
||||
args.sourceControl = false
|
||||
continue
|
||||
}
|
||||
if (arg === '--no-dead-pty-reactivate') {
|
||||
args.deadPtyReactivate = false
|
||||
continue
|
||||
}
|
||||
const [name, value] = arg.split('=', 2)
|
||||
if (name === '--cycles') {
|
||||
args.cycles = parsePositiveInt(name, value)
|
||||
continue
|
||||
}
|
||||
if (name === '--distro') {
|
||||
args.distro = value?.trim() || null
|
||||
continue
|
||||
}
|
||||
if (name === '--expect') {
|
||||
if (!['none', 'repro', 'pass'].includes(value)) {
|
||||
throw new Error(`Unsupported --expect=${value}. Use none, repro, or pass.`)
|
||||
}
|
||||
args.expect = value
|
||||
continue
|
||||
}
|
||||
if (name === '--gpu') {
|
||||
const modes = (value ?? '')
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean)
|
||||
if (modes.length === 0 || modes.some((mode) => !['on', 'off', 'auto'].includes(mode))) {
|
||||
throw new Error(`Unsupported --gpu=${value}. Use on, off, auto, or a comma-list.`)
|
||||
}
|
||||
args.gpuModes = modes
|
||||
continue
|
||||
}
|
||||
if (name === '--output-lines') {
|
||||
args.outputLines = parsePositiveInt(name, value)
|
||||
continue
|
||||
}
|
||||
if (name === '--report') {
|
||||
args.reportPath = value?.trim() || null
|
||||
if (!args.reportPath) {
|
||||
throw new Error('--report requires a file path.')
|
||||
}
|
||||
continue
|
||||
}
|
||||
throw new Error(`Unknown argument: ${arg}`)
|
||||
}
|
||||
|
||||
return args
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage:
|
||||
node config/scripts/repro-windows-apphang-terminal-activation.mjs [options]
|
||||
|
||||
Options:
|
||||
--expect=none|repro|pass none prints measurements, repro exits 0 only when hang evidence is observed,
|
||||
pass exits 1 if hang evidence is observed. Default: none.
|
||||
--gpu=on|off|auto[,mode...] Terminal GPU setting(s) to run. Default: on.
|
||||
--cycles=N Activation/output cycles per GPU mode. Default: ${defaultCycles}.
|
||||
--output-lines=N Lines emitted by each terminal stress command. Default: ${defaultOutputLines}.
|
||||
--report=PATH Write full JSON evidence to PATH and print a compact summary to stdout.
|
||||
--distro=NAME WSL distro to use. Default: first non docker-desktop distro.
|
||||
--no-source-control Do not open Source Control during the stress loop.
|
||||
--no-dead-pty-reactivate Do not kill PTYs and revisit workspaces after initial activation.
|
||||
--keep Keep disposable WSL/userData fixtures after the run.`)
|
||||
}
|
||||
|
||||
function parsePositiveInt(name, value) {
|
||||
const parsed = Number.parseInt(value ?? '', 10)
|
||||
if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== value) {
|
||||
throw new Error(`${name} requires a positive integer.`)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (process.platform !== 'win32') {
|
||||
throw new Error('This repro harness is intentionally Windows-only.')
|
||||
}
|
||||
const args = parseArgs()
|
||||
const distros = listWslDistros()
|
||||
const distro = args.distro ?? distros[0]
|
||||
if (!distro) {
|
||||
throw new Error('No user WSL distro found. Install/enable WSL or pass --distro=NAME.')
|
||||
}
|
||||
console.log(
|
||||
`[apphang-repro] issue=https://github.com/stablyai/orca/issues/6874 distro=${distro} gpuModes=${args.gpuModes.join(',')} cycles=${args.cycles}`
|
||||
)
|
||||
const fixture = createWslFixture(distro)
|
||||
console.log(
|
||||
`[apphang-repro] fixture repo=${fixture.repoUncPath} plain=${fixture.plainUncPath} base=${fixture.baseLinuxPath}`
|
||||
)
|
||||
|
||||
const results = []
|
||||
try {
|
||||
for (const gpuMode of args.gpuModes) {
|
||||
results.push(await runGpuMode(gpuMode, args, fixture))
|
||||
if (args.expect === 'repro' && results.at(-1)?.reproduced) {
|
||||
break
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (!args.keep) {
|
||||
removeWslFixture(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
const payload = {
|
||||
issue: 'https://github.com/stablyai/orca/issues/6874',
|
||||
expect: args.expect,
|
||||
distro,
|
||||
fixture: args.keep ? fixture : { removed: true, baseLinuxPath: fixture.baseLinuxPath },
|
||||
summary: results.map(summarizeResult),
|
||||
results
|
||||
}
|
||||
if (args.reportPath) {
|
||||
const reportPath = path.resolve(args.reportPath)
|
||||
mkdirSync(path.dirname(reportPath), { recursive: true })
|
||||
writeFileSync(reportPath, `${JSON.stringify(payload, null, 2)}\n`)
|
||||
console.log(JSON.stringify({ reportPath, summary: payload.summary }, null, 2))
|
||||
} else {
|
||||
console.log(JSON.stringify(payload, null, 2))
|
||||
}
|
||||
|
||||
// Why: a broken harness run (CDP/setup/selector failure) proves nothing —
|
||||
// it must fail both --expect=repro and --expect=pass rather than being
|
||||
// miscounted as hang evidence or as a clean pass.
|
||||
const harnessErrors = results.filter((result) => result.harnessError)
|
||||
if (harnessErrors.length > 0) {
|
||||
const harnessErrorLines = harnessErrors
|
||||
.map((result) => ` gpu=${result.gpuMode}: ${result.harnessError}`)
|
||||
.join('\n')
|
||||
console.error(
|
||||
`[apphang-repro] Harness failed in ${harnessErrors.length} run(s); result inconclusive:\n${harnessErrorLines}`
|
||||
)
|
||||
if (args.expect !== 'none') {
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
const reproduced = results.some((result) => result.reproduced)
|
||||
if (args.expect === 'repro' && !reproduced) {
|
||||
console.error(
|
||||
'[apphang-repro] Expected to reproduce the hang, but no hang evidence was observed.'
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (args.expect === 'pass' && reproduced) {
|
||||
console.error('[apphang-repro] Expected a clean pass, but hang evidence was observed.')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.stack || error.message : String(error))
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export function summarizeTrace(userDataDir) {
|
||||
const tracePath = path.join(userDataDir, 'logs', 'main.trace.ndjson')
|
||||
if (!existsSync(tracePath)) {
|
||||
return { tracePath, exists: false }
|
||||
}
|
||||
const lines = readFileSync(tracePath, 'utf8').trim().split(/\r?\n/).filter(Boolean)
|
||||
const parsed = []
|
||||
for (const line of lines.slice(-400)) {
|
||||
try {
|
||||
parsed.push(JSON.parse(line))
|
||||
} catch {
|
||||
parsed.push({ raw: line })
|
||||
}
|
||||
}
|
||||
const interesting = parsed.filter((entry) => {
|
||||
const name = String(entry.name ?? entry.event ?? entry.type ?? '')
|
||||
const text = JSON.stringify(entry)
|
||||
return (
|
||||
name.includes('git.exec') ||
|
||||
name.includes('renderer_memory') ||
|
||||
name.includes('sidebar_worktree_activate') ||
|
||||
text.includes('git.exec remote') ||
|
||||
text.includes('git.exec worktree') ||
|
||||
text.includes('sidebar_worktree_activate')
|
||||
)
|
||||
})
|
||||
return {
|
||||
tracePath,
|
||||
exists: true,
|
||||
totalLines: lines.length,
|
||||
interestingTail: interesting.slice(-40)
|
||||
}
|
||||
}
|
||||
|
||||
export function summarizeAppLogs(logs) {
|
||||
const webglContextWarnings = logs.filter((entry) =>
|
||||
entry.line.includes('Too many active WebGL contexts')
|
||||
)
|
||||
const webglContextLosses = logs.filter((entry) =>
|
||||
entry.line.toLowerCase().includes('webgl context lost')
|
||||
)
|
||||
const gpuProcessEvents = logs.filter((entry) => /gpu|d3d|angle/i.test(entry.line))
|
||||
return {
|
||||
lineCount: logs.length,
|
||||
webglContextWarningCount: webglContextWarnings.length,
|
||||
webglContextWarningsTail: webglContextWarnings.slice(-10),
|
||||
webglContextLossCount: webglContextLosses.length,
|
||||
webglContextLossesTail: webglContextLosses.slice(-10),
|
||||
gpuProcessEventCount: gpuProcessEvents.length,
|
||||
gpuProcessEventsTail: gpuProcessEvents.slice(-20)
|
||||
}
|
||||
}
|
||||
|
||||
export function summarizeResult(result) {
|
||||
const samples = result.samples.filter((sample) => sample && typeof sample === 'object')
|
||||
const maxActivationMs = Math.max(0, ...samples.map((sample) => sample.activationMs ?? 0))
|
||||
const maxPtyWaitMs = Math.max(0, ...samples.map((sample) => sample.ptyWaitMs ?? 0))
|
||||
const maxMainIpcMs = Math.max(0, ...samples.map((sample) => sample.mainIpcMs ?? 0))
|
||||
const maxRendererDriftMs = Math.max(0, ...samples.map((sample) => sample.rendererMaxDriftMs ?? 0))
|
||||
return {
|
||||
gpuMode: result.gpuMode,
|
||||
reproduced: result.reproduced,
|
||||
reproductionReason: result.reproductionReason,
|
||||
harnessError: result.harnessError ?? null,
|
||||
elapsedMs: result.elapsedMs,
|
||||
sampleCount: samples.length,
|
||||
maxActivationMs,
|
||||
maxPtyWaitMs,
|
||||
maxMainIpcMs,
|
||||
maxRendererDriftMs,
|
||||
finalWebglContextCounts: result.finalDiagnostics?.webglContextCounts ?? null,
|
||||
appLogSummary: result.appLogSummary
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import { chromium } from '@playwright/test'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import net from 'node:net'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import process from 'node:process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
appShutdownTimeoutMs,
|
||||
cdpPollTimeoutMs,
|
||||
delay,
|
||||
pollUntil,
|
||||
rendererActionTimeoutMs,
|
||||
runWithTimeout
|
||||
} from './repro-timing.mjs'
|
||||
import { createCompletedOnboardingProfile } from './wsl-workspace-fixture.mjs'
|
||||
|
||||
const rootDir = path.resolve(fileURLToPath(new URL('../../..', import.meta.url)))
|
||||
|
||||
function isPortFree(port) {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer()
|
||||
server.once('error', () => {
|
||||
try {
|
||||
server.close()
|
||||
} catch {}
|
||||
resolve(false)
|
||||
})
|
||||
server.once('listening', () => server.close(() => resolve(true)))
|
||||
server.listen(port, '127.0.0.1')
|
||||
})
|
||||
}
|
||||
|
||||
export async function pickFreePort() {
|
||||
for (let port = 9533; port < 9633; port += 1) {
|
||||
if (await isPortFree(port)) {
|
||||
return port
|
||||
}
|
||||
}
|
||||
throw new Error('Could not find a free CDP port in 9533..9632.')
|
||||
}
|
||||
|
||||
export function createGpuUserDataDirectory(gpuMode) {
|
||||
const userDataDir = mkdtempSync(path.join(os.tmpdir(), `orca-apphang-${gpuMode}-userdata-`))
|
||||
createCompletedOnboardingProfile(userDataDir)
|
||||
return userDataDir
|
||||
}
|
||||
|
||||
export function launchDevApp({ cdpPort, userDataDir }) {
|
||||
const env = { ...process.env }
|
||||
delete env.ELECTRON_RUN_AS_NODE
|
||||
Object.assign(env, {
|
||||
ELECTRON_ENABLE_LOGGING: '1',
|
||||
ELECTRON_ENABLE_STACK_DUMPING: '1',
|
||||
NODE_ENV: 'development',
|
||||
ORCA_DEV_USER_DATA_PATH: userDataDir,
|
||||
ORCA_SKIP_DEV_WEB_PREPARE: '1',
|
||||
ORCA_STARTUP_DIAGNOSTICS: '1',
|
||||
REMOTE_DEBUGGING_PORT: String(cdpPort),
|
||||
VITE_EXPOSE_STORE: 'true'
|
||||
})
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[path.join('config', 'scripts', 'run-electron-vite-dev.mjs')],
|
||||
{
|
||||
cwd: rootDir,
|
||||
env,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
windowsHide: true
|
||||
}
|
||||
)
|
||||
const logs = []
|
||||
const collect = (source) => (chunk) => {
|
||||
const text = chunk.toString()
|
||||
for (const line of text.split(/\r?\n/).filter(Boolean)) {
|
||||
logs.push({ source, line, at: Date.now() })
|
||||
console.log(`[apphang-repro:${source}] ${line}`)
|
||||
}
|
||||
}
|
||||
child.stdout?.on('data', collect('stdout'))
|
||||
child.stderr?.on('data', collect('stderr'))
|
||||
return { child, logs }
|
||||
}
|
||||
|
||||
export async function stopDevApp(child) {
|
||||
if (!child?.pid || child.exitCode !== null || child.signalCode !== null) {
|
||||
return
|
||||
}
|
||||
await new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, appShutdownTimeoutMs)
|
||||
child.once('exit', () => {
|
||||
clearTimeout(timer)
|
||||
resolve()
|
||||
})
|
||||
if (process.platform === 'win32') {
|
||||
const killer = spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
|
||||
stdio: 'ignore',
|
||||
windowsHide: true
|
||||
})
|
||||
killer.once('exit', () => undefined)
|
||||
return
|
||||
}
|
||||
child.kill('SIGTERM')
|
||||
})
|
||||
}
|
||||
|
||||
async function waitForCdp(port) {
|
||||
const url = `http://127.0.0.1:${port}/json`
|
||||
const startedAt = Date.now()
|
||||
while (Date.now() - startedAt < cdpPollTimeoutMs) {
|
||||
try {
|
||||
const response = await fetch(url)
|
||||
if (response.ok) {
|
||||
const targets = await response.json()
|
||||
if (Array.isArray(targets) && targets.some((target) => target.type)) {
|
||||
return targets
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
await delay(500)
|
||||
}
|
||||
throw new Error(`Timed out waiting for CDP targets on ${url}`)
|
||||
}
|
||||
|
||||
async function getMainPage(browser) {
|
||||
const startedAt = Date.now()
|
||||
while (Date.now() - startedAt < cdpPollTimeoutMs) {
|
||||
for (const context of browser.contexts()) {
|
||||
const pages = context.pages()
|
||||
const page =
|
||||
pages.find((candidate) =>
|
||||
/^https?:\/\/127\.0\.0\.1:|^https?:\/\/localhost:/.test(candidate.url())
|
||||
) ?? pages[0]
|
||||
if (page) {
|
||||
return page
|
||||
}
|
||||
}
|
||||
await delay(250)
|
||||
}
|
||||
throw new Error('Timed out waiting for the Electron renderer page.')
|
||||
}
|
||||
|
||||
export async function connectToApp(cdpPort) {
|
||||
await waitForCdp(cdpPort)
|
||||
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`)
|
||||
const page = await getMainPage(browser)
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 })
|
||||
return { browser, page }
|
||||
}
|
||||
|
||||
export async function installRendererProbe(page) {
|
||||
await page.evaluate(() => {
|
||||
if (globalThis.__orcaApphangProbe) {
|
||||
return
|
||||
}
|
||||
const probe = {
|
||||
intervalMs: 50,
|
||||
last: performance.now(),
|
||||
maxDriftMs: 0,
|
||||
samples: 0,
|
||||
startedAt: performance.now(),
|
||||
lastTickAt: performance.now()
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
const now = performance.now()
|
||||
const drift = Math.max(0, now - probe.last - probe.intervalMs)
|
||||
probe.maxDriftMs = Math.max(probe.maxDriftMs, drift)
|
||||
probe.last = now
|
||||
probe.lastTickAt = now
|
||||
probe.samples += 1
|
||||
}, probe.intervalMs)
|
||||
globalThis.__orcaApphangProbe = { probe, timer }
|
||||
})
|
||||
}
|
||||
|
||||
export async function waitForStoreReady(page) {
|
||||
await pollUntil(
|
||||
'renderer store exposure',
|
||||
() => page.evaluate(() => Boolean(window.__store && window.api)),
|
||||
Boolean,
|
||||
30_000
|
||||
)
|
||||
await pollUntil(
|
||||
'workspace session hydration',
|
||||
() =>
|
||||
page.evaluate(() => {
|
||||
const state = window.__store?.getState?.()
|
||||
return Boolean(state?.workspaceSessionReady && state?.hydrationSucceeded)
|
||||
}),
|
||||
Boolean,
|
||||
45_000
|
||||
)
|
||||
}
|
||||
|
||||
export async function collectRendererDiagnostics(page) {
|
||||
if (!page) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return await runWithTimeout(
|
||||
'renderer diagnostics',
|
||||
() =>
|
||||
page.evaluate(async () => {
|
||||
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)
|
||||
)
|
||||
])
|
||||
const readWebglIdentity = () => {
|
||||
const canvas = document.createElement('canvas')
|
||||
let gl = null
|
||||
try {
|
||||
gl = canvas.getContext('webgl2') ?? canvas.getContext('webgl')
|
||||
if (!gl) {
|
||||
return { available: false, vendor: null, renderer: null }
|
||||
}
|
||||
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
|
||||
if (!debugInfo) {
|
||||
return { available: true, vendor: null, renderer: null }
|
||||
}
|
||||
return {
|
||||
available: true,
|
||||
vendor: String(gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) ?? '') || null,
|
||||
renderer: String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) ?? '') || null
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
gl?.getExtension('WEBGL_lose_context')?.loseContext()
|
||||
} catch {}
|
||||
canvas.width = 0
|
||||
canvas.height = 0
|
||||
}
|
||||
}
|
||||
const allPaneManagersDiagnostics = Array.from(
|
||||
window.__paneManagers?.entries?.() ?? []
|
||||
).map(([managerTabId, paneManager]) => ({
|
||||
tabId: managerTabId,
|
||||
diagnostics: paneManager?.getRenderingDiagnostics?.() ?? []
|
||||
}))
|
||||
const webglContextCounts = allPaneManagersDiagnostics.reduce(
|
||||
(acc, entry) => {
|
||||
acc.managerCount += 1
|
||||
acc.paneCount += entry.diagnostics.length
|
||||
for (const diagnostic of entry.diagnostics) {
|
||||
if (diagnostic.hasWebgl) {
|
||||
acc.attachedWebglCount += 1
|
||||
}
|
||||
if (diagnostic.webglAttachmentDeferred) {
|
||||
acc.deferredWebglCount += 1
|
||||
}
|
||||
}
|
||||
return acc
|
||||
},
|
||||
{ attachedWebglCount: 0, deferredWebglCount: 0, managerCount: 0, paneCount: 0 }
|
||||
)
|
||||
const state = window.__store?.getState?.()
|
||||
const worktreeId = state?.activeWorktreeId ?? null
|
||||
const tabId =
|
||||
state?.activeTabType === 'terminal'
|
||||
? state.activeTabId
|
||||
: worktreeId
|
||||
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
|
||||
: null
|
||||
const manager = tabId ? window.__paneManagers?.get(tabId) : null
|
||||
const activePane = manager?.getActivePane?.() ?? manager?.getPanes?.()?.[0] ?? null
|
||||
const buffer = activePane?.terminal?.buffer?.active ?? null
|
||||
return {
|
||||
hasStore: Boolean(window.__store),
|
||||
workspaceSessionReady: state?.workspaceSessionReady ?? null,
|
||||
hydrationSucceeded: state?.hydrationSucceeded ?? null,
|
||||
activeView: state?.activeView ?? null,
|
||||
activeRepoId: state?.activeRepoId ?? null,
|
||||
activeWorktreeId: worktreeId,
|
||||
activeTabType: state?.activeTabType ?? null,
|
||||
activeTabId: tabId,
|
||||
terminalGpuAcceleration: state?.settings?.terminalGpuAcceleration ?? null,
|
||||
repoCount: state?.repos?.length ?? null,
|
||||
worktreeCountsByRepo: Object.fromEntries(
|
||||
Object.entries(state?.worktreesByRepo ?? {}).map(([repoId, worktrees]) => [
|
||||
repoId,
|
||||
worktrees.length
|
||||
])
|
||||
),
|
||||
ptyIdsByTabId: tabId ? (state?.ptyIdsByTabId?.[tabId] ?? []) : [],
|
||||
paneManagerCount: window.__paneManagers?.size ?? null,
|
||||
activePane: activePane
|
||||
? {
|
||||
id: activePane.id ?? null,
|
||||
leafId: activePane.leafId ?? null,
|
||||
ptyId: activePane.container?.dataset?.ptyId ?? null,
|
||||
cols: activePane.terminal?.cols ?? null,
|
||||
rows: activePane.terminal?.rows ?? null,
|
||||
buffer: buffer
|
||||
? {
|
||||
baseY: buffer.baseY,
|
||||
viewportY: buffer.viewportY,
|
||||
cursorY: buffer.cursorY,
|
||||
length: buffer.length
|
||||
}
|
||||
: null
|
||||
}
|
||||
: null,
|
||||
renderingDiagnostics: manager?.getRenderingDiagnostics?.() ?? null,
|
||||
allPaneManagersDiagnostics,
|
||||
webglContextCounts,
|
||||
webglIdentity: readWebglIdentity(),
|
||||
rendererProbe: globalThis.__orcaApphangProbe?.probe ?? null,
|
||||
ptySessions: await timed('PTY sessions', window.api?.pty?.listSessions?.()),
|
||||
rendererDeliveryDebug: await timed(
|
||||
'renderer delivery debug',
|
||||
window.api?.pty?.getRendererDeliveryDebugSnapshot?.()
|
||||
)
|
||||
}
|
||||
}),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
} catch (error) {
|
||||
return { error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
export const cdpPollTimeoutMs = 90_000
|
||||
export const rendererActionTimeoutMs = 5_000
|
||||
export const activationTimeoutMs = 15_000
|
||||
export const ptyWaitTimeoutMs = 20_000
|
||||
export const terminalMarkerTimeoutMs = 45_000
|
||||
export const setupTimeoutMs = 90_000
|
||||
export const appShutdownTimeoutMs = 8_000
|
||||
export const severeRendererDriftMs = 2_000
|
||||
export const severeActivationMs = 5_000
|
||||
export const severeMainIpcMs = 2_000
|
||||
export const severePtyWaitMs = 10_000
|
||||
|
||||
export function delay(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
export async function runWithTimeout(label, action, timeoutMs) {
|
||||
const actionPromise = Promise.resolve().then(action)
|
||||
actionPromise.catch(() => undefined)
|
||||
const result = await Promise.race([
|
||||
actionPromise.then(
|
||||
(value) => ({ timedOut: false, value }),
|
||||
(error) => ({ timedOut: false, error })
|
||||
),
|
||||
delay(timeoutMs).then(() => ({ timedOut: true }))
|
||||
])
|
||||
if (result.timedOut) {
|
||||
throw new Error(`Timed out during ${label} after ${timeoutMs}ms.`)
|
||||
}
|
||||
if ('error' in result) {
|
||||
throw result.error
|
||||
}
|
||||
return result.value
|
||||
}
|
||||
|
||||
export async function pollUntil(label, read, predicate, timeoutMs, intervalMs = 100) {
|
||||
const startedAt = Date.now()
|
||||
let lastValue = null
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
lastValue = await runWithTimeout(label, read, rendererActionTimeoutMs)
|
||||
if (predicate(lastValue)) {
|
||||
return lastValue
|
||||
}
|
||||
await delay(intervalMs)
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${label}; last value: ${JSON.stringify(lastValue)}`)
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
import {
|
||||
collectRendererDiagnostics,
|
||||
connectToApp,
|
||||
createGpuUserDataDirectory,
|
||||
installRendererProbe,
|
||||
launchDevApp,
|
||||
pickFreePort,
|
||||
stopDevApp,
|
||||
waitForStoreReady
|
||||
} from './electron-dev-session.mjs'
|
||||
import { summarizeAppLogs, summarizeTrace } from './apphang-report-summary.mjs'
|
||||
import {
|
||||
activationTimeoutMs,
|
||||
pollUntil,
|
||||
ptyWaitTimeoutMs,
|
||||
rendererActionTimeoutMs,
|
||||
runWithTimeout,
|
||||
setupTimeoutMs,
|
||||
severeActivationMs,
|
||||
severeMainIpcMs,
|
||||
severePtyWaitMs,
|
||||
severeRendererDriftMs,
|
||||
terminalMarkerTimeoutMs
|
||||
} from './repro-timing.mjs'
|
||||
import { safeRemoveLocalDirectory } from './wsl-workspace-fixture.mjs'
|
||||
|
||||
class ReproductionObservedError extends Error {
|
||||
constructor(message, evidence) {
|
||||
super(message)
|
||||
this.name = 'ReproductionObservedError'
|
||||
this.evidence = evidence
|
||||
}
|
||||
}
|
||||
|
||||
async function setupAppFixture(page, fixture, gpuMode, sourceControl) {
|
||||
return await runWithTimeout(
|
||||
'fixture registration in Orca',
|
||||
() =>
|
||||
page.evaluate(
|
||||
async ({ repoPath, plainPath, importedWorktreePaths, mode, openSourceControl }) => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
throw new Error('window.__store is unavailable.')
|
||||
}
|
||||
const state = store.getState()
|
||||
await state.fetchSettings?.()
|
||||
await store.getState().updateSettings({ terminalGpuAcceleration: mode })
|
||||
|
||||
const addResult = await window.api.repos.add({ path: repoPath, kind: 'git' })
|
||||
if ('error' in addResult) {
|
||||
throw new Error(addResult.error)
|
||||
}
|
||||
await store.getState().fetchRepos()
|
||||
let nextState = store.getState()
|
||||
const repo =
|
||||
nextState.repos.find((candidate) => candidate.path === repoPath) ?? addResult.repo
|
||||
await nextState.updateRepo(repo.id, {
|
||||
externalWorktreeVisibility: 'show',
|
||||
externalWorktreeVisibilityPromptDismissedAt: Date.now(),
|
||||
importedExternalWorktreePaths: importedWorktreePaths,
|
||||
externalWorktreeInboxBaselinePaths: importedWorktreePaths
|
||||
})
|
||||
await store.getState().fetchWorktrees(repo.id, { requireAuthoritative: true })
|
||||
|
||||
const plainRepo = await store.getState().addNonGitFolder(plainPath)
|
||||
if (!plainRepo) {
|
||||
throw new Error('addNonGitFolder returned null.')
|
||||
}
|
||||
await store.getState().fetchWorktrees(plainRepo.id, { requireAuthoritative: true })
|
||||
|
||||
nextState = store.getState()
|
||||
nextState.setSidebarOpen(true)
|
||||
nextState.setGroupBy('none')
|
||||
nextState.setSortBy('recent')
|
||||
nextState.setShowActiveOnly(false)
|
||||
nextState.setActiveView('terminal')
|
||||
if (openSourceControl) {
|
||||
nextState.setRightSidebarOpen(true)
|
||||
nextState.setRightSidebarTab('source-control')
|
||||
}
|
||||
|
||||
const gitWorktrees = nextState.worktreesByRepo[repo.id] ?? []
|
||||
const plainWorktrees = nextState.worktreesByRepo[plainRepo.id] ?? []
|
||||
return {
|
||||
repoId: repo.id,
|
||||
repoPath: repo.path,
|
||||
plainRepoId: plainRepo.id,
|
||||
gitWorktrees: gitWorktrees.map((worktree) => ({
|
||||
id: worktree.id,
|
||||
path: worktree.path,
|
||||
displayName: worktree.displayName,
|
||||
branch: worktree.branch,
|
||||
isMainWorktree: worktree.isMainWorktree
|
||||
})),
|
||||
plainWorktrees: plainWorktrees.map((worktree) => ({
|
||||
id: worktree.id,
|
||||
path: worktree.path,
|
||||
displayName: worktree.displayName,
|
||||
branch: worktree.branch,
|
||||
isMainWorktree: worktree.isMainWorktree
|
||||
}))
|
||||
}
|
||||
},
|
||||
{
|
||||
repoPath: fixture.repoUncPath,
|
||||
plainPath: fixture.plainUncPath,
|
||||
importedWorktreePaths: fixture.worktreeUncPaths,
|
||||
mode: gpuMode,
|
||||
openSourceControl: sourceControl
|
||||
}
|
||||
),
|
||||
setupTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function clickWorktreeCard(page, worktreeId) {
|
||||
const rect = await runWithTimeout(
|
||||
`locate worktree card ${worktreeId}`,
|
||||
() =>
|
||||
page.evaluate((id) => {
|
||||
const rows = Array.from(document.querySelectorAll('[data-worktree-id]'))
|
||||
const row = rows.find((candidate) => candidate.getAttribute('data-worktree-id') === id)
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
row.scrollIntoView({ block: 'center', inline: 'nearest' })
|
||||
const surface = row.querySelector('[data-worktree-card-surface="true"]') ?? row
|
||||
const bounds = surface.getBoundingClientRect()
|
||||
if (bounds.width <= 0 || bounds.height <= 0) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
x: bounds.left + bounds.width / 2,
|
||||
y: bounds.top + bounds.height / 2,
|
||||
width: bounds.width,
|
||||
height: bounds.height
|
||||
}
|
||||
}, worktreeId),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
if (!rect) {
|
||||
throw new Error(`Could not find rendered worktree card for ${worktreeId}`)
|
||||
}
|
||||
await runWithTimeout(
|
||||
`click worktree card ${worktreeId}`,
|
||||
() => page.mouse.click(rect.x, rect.y),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function waitForActiveWorktree(page, worktreeId) {
|
||||
return await pollUntil(
|
||||
`active worktree ${worktreeId}`,
|
||||
() =>
|
||||
page.evaluate((id) => {
|
||||
const state = window.__store?.getState?.()
|
||||
return {
|
||||
activeWorktreeId: state?.activeWorktreeId ?? null,
|
||||
activeTabId: state?.activeTabId ?? null,
|
||||
activeTabType: state?.activeTabType ?? null,
|
||||
tabs: state?.tabsByWorktree?.[id]?.map((tab) => tab.id) ?? []
|
||||
}
|
||||
}, worktreeId),
|
||||
(value) => value?.activeWorktreeId === worktreeId && value.activeTabType === 'terminal',
|
||||
activationTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function waitForActivePty(page, worktreeId) {
|
||||
const startedAt = Date.now()
|
||||
const value = await pollUntil(
|
||||
`active PTY for ${worktreeId}`,
|
||||
() =>
|
||||
page.evaluate((id) => {
|
||||
const state = window.__store?.getState?.()
|
||||
const tabId =
|
||||
state?.activeWorktreeId === id && state.activeTabType === 'terminal'
|
||||
? state.activeTabId
|
||||
: (state?.activeTabIdByWorktree?.[id] ?? null)
|
||||
const manager = tabId ? window.__paneManagers?.get(tabId) : null
|
||||
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()?.[0] ?? null
|
||||
const ptyId = pane?.container?.dataset?.ptyId ?? null
|
||||
return {
|
||||
tabId,
|
||||
ptyId,
|
||||
hasManager: Boolean(manager),
|
||||
paneCount: manager?.getPanes?.()?.length ?? 0,
|
||||
ptyIdsByTab: tabId ? (state?.ptyIdsByTabId?.[tabId] ?? []) : []
|
||||
}
|
||||
}, worktreeId),
|
||||
(value) => Boolean(value?.ptyId),
|
||||
ptyWaitTimeoutMs
|
||||
)
|
||||
return { ...value, waitMs: Date.now() - startedAt }
|
||||
}
|
||||
|
||||
function makeOutputCommand(marker, outputLines) {
|
||||
const payload = 'x'.repeat(180)
|
||||
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`
|
||||
}
|
||||
|
||||
async function getTerminalContent(page, charLimit = 20_000) {
|
||||
return await runWithTimeout(
|
||||
'terminal content',
|
||||
() =>
|
||||
page.evaluate((limit) => {
|
||||
const state = window.__store?.getState?.()
|
||||
const worktreeId = state?.activeWorktreeId
|
||||
const tabId =
|
||||
state?.activeTabType === 'terminal'
|
||||
? state.activeTabId
|
||||
: worktreeId
|
||||
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
|
||||
: null
|
||||
const manager = tabId ? window.__paneManagers?.get(tabId) : null
|
||||
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()?.[0] ?? null
|
||||
return (pane?.serializeAddon?.serialize?.() ?? '').slice(-limit)
|
||||
}, charLimit),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function sendOutputStress(page, ptyId, marker, outputLines) {
|
||||
await runWithTimeout(
|
||||
`write terminal stress ${marker}`,
|
||||
() =>
|
||||
page.evaluate(
|
||||
({ id, command }) => {
|
||||
window.api.pty.write(id, command)
|
||||
},
|
||||
{ id: ptyId, command: makeOutputCommand(marker, outputLines) }
|
||||
),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
await pollUntil(
|
||||
`terminal stress marker ${marker}`,
|
||||
async () => (await getTerminalContent(page)).includes(`${marker}_DONE`),
|
||||
Boolean,
|
||||
terminalMarkerTimeoutMs,
|
||||
200
|
||||
)
|
||||
}
|
||||
|
||||
async function pingMainIpc(page) {
|
||||
const startedAt = Date.now()
|
||||
await runWithTimeout(
|
||||
'main IPC ping',
|
||||
() => page.evaluate(() => window.api.pty.listSessions()),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
return Date.now() - startedAt
|
||||
}
|
||||
|
||||
async function readRendererProbe(page) {
|
||||
return await runWithTimeout(
|
||||
'renderer probe read',
|
||||
() => page.evaluate(() => globalThis.__orcaApphangProbe?.probe ?? null),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function killActivePty(page) {
|
||||
return await runWithTimeout(
|
||||
'kill active PTY',
|
||||
() =>
|
||||
page.evaluate(async () => {
|
||||
const state = window.__store?.getState?.()
|
||||
const tabId = state?.activeTabId ?? null
|
||||
const ptyIds = tabId ? (state?.ptyIdsByTabId?.[tabId] ?? []) : []
|
||||
const ptyId = ptyIds[0] ?? null
|
||||
if (!ptyId) {
|
||||
return null
|
||||
}
|
||||
await window.api.pty.kill(ptyId)
|
||||
return ptyId
|
||||
}),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function resetRendererProbe(page) {
|
||||
// Why: probe drift is cumulative since installation; without a per-cycle
|
||||
// reset, one startup/setup stall gets re-reported as a hang in every
|
||||
// later cycle's rendererMaxDriftMs check.
|
||||
await runWithTimeout(
|
||||
'renderer probe reset',
|
||||
() =>
|
||||
page.evaluate(() => {
|
||||
const probe = globalThis.__orcaApphangProbe?.probe
|
||||
if (!probe) {
|
||||
return
|
||||
}
|
||||
const now = performance.now()
|
||||
probe.last = now
|
||||
probe.lastTickAt = now
|
||||
probe.startedAt = now
|
||||
probe.maxDriftMs = 0
|
||||
probe.samples = 0
|
||||
}),
|
||||
rendererActionTimeoutMs
|
||||
)
|
||||
}
|
||||
|
||||
async function runActivationCycle(page, target, args) {
|
||||
await resetRendererProbe(page)
|
||||
const marker = `ORCA_APPHANG_${target.index}_${Date.now()}`
|
||||
const cycleStartedAt = Date.now()
|
||||
const activationStartedAt = Date.now()
|
||||
await clickWorktreeCard(page, target.id)
|
||||
const activation = await waitForActiveWorktree(page, target.id)
|
||||
const activationMs = Date.now() - activationStartedAt
|
||||
const activePty = await waitForActivePty(page, target.id)
|
||||
const diagnosticsBeforeOutput = await collectRendererDiagnostics(page)
|
||||
const outputStartedAt = Date.now()
|
||||
await sendOutputStress(page, activePty.ptyId, marker, args.outputLines)
|
||||
const outputMs = Date.now() - outputStartedAt
|
||||
const mainIpcMs = await pingMainIpc(page)
|
||||
const rendererProbe = await readRendererProbe(page)
|
||||
const diagnosticsAfterOutput = await collectRendererDiagnostics(page)
|
||||
const elapsedMs = Date.now() - cycleStartedAt
|
||||
const sample = {
|
||||
index: target.index,
|
||||
kind: target.kind,
|
||||
worktreeId: target.id,
|
||||
displayName: target.displayName,
|
||||
elapsedMs,
|
||||
activationMs,
|
||||
outputMs,
|
||||
activation,
|
||||
ptyWaitMs: activePty.waitMs,
|
||||
ptyId: activePty.ptyId,
|
||||
tabId: activePty.tabId,
|
||||
mainIpcMs,
|
||||
rendererMaxDriftMs: rendererProbe?.maxDriftMs ?? null,
|
||||
renderingDiagnostics: diagnosticsAfterOutput?.renderingDiagnostics ?? null,
|
||||
webglIdentity: diagnosticsAfterOutput?.webglIdentity ?? null,
|
||||
diagnosticsBeforeOutput,
|
||||
diagnosticsAfterOutput
|
||||
}
|
||||
|
||||
const reproducedReasons = []
|
||||
if (activationMs > severeActivationMs) {
|
||||
reproducedReasons.push(`worktree activation took ${activationMs}ms`)
|
||||
}
|
||||
if (activePty.waitMs > severePtyWaitMs) {
|
||||
reproducedReasons.push(`PTY binding took ${activePty.waitMs}ms`)
|
||||
}
|
||||
if (mainIpcMs > severeMainIpcMs) {
|
||||
reproducedReasons.push(`main IPC ping took ${mainIpcMs}ms`)
|
||||
}
|
||||
if ((rendererProbe?.maxDriftMs ?? 0) > severeRendererDriftMs) {
|
||||
reproducedReasons.push(`renderer timer drift reached ${Math.round(rendererProbe.maxDriftMs)}ms`)
|
||||
}
|
||||
if (reproducedReasons.length > 0) {
|
||||
throw new ReproductionObservedError(reproducedReasons.join('; '), sample)
|
||||
}
|
||||
return sample
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
function selectTargets(setupResult, cycles) {
|
||||
const gitWorktrees = setupResult.gitWorktrees
|
||||
.filter((worktree) => worktree.path)
|
||||
.sort((a, b) => Number(b.isMainWorktree) - Number(a.isMainWorktree))
|
||||
.slice(0, 5)
|
||||
.map((worktree) => ({ ...worktree, kind: 'git-wsl' }))
|
||||
const plainWorktrees = setupResult.plainWorktrees.map((worktree) => ({
|
||||
...worktree,
|
||||
kind: 'plain-folder-wsl'
|
||||
}))
|
||||
const baseTargets = [...gitWorktrees, ...plainWorktrees]
|
||||
if (baseTargets.length === 0) {
|
||||
throw new Error('No worktrees were discovered for the repro fixture.')
|
||||
}
|
||||
return Array.from({ length: cycles }, (_, index) => ({
|
||||
...baseTargets[index % baseTargets.length],
|
||||
index: index + 1
|
||||
}))
|
||||
}
|
||||
|
||||
export async function runGpuMode(gpuMode, args, fixture) {
|
||||
const cdpPort = await pickFreePort()
|
||||
const userDataDir = createGpuUserDataDirectory(gpuMode)
|
||||
const launched = launchDevApp({ cdpPort, userDataDir })
|
||||
let browser = null
|
||||
let page = null
|
||||
const startedAt = Date.now()
|
||||
const result = {
|
||||
gpuMode,
|
||||
reproduced: false,
|
||||
reproductionReason: null,
|
||||
harnessError: null,
|
||||
startedAt,
|
||||
elapsedMs: null,
|
||||
cdpPort,
|
||||
userDataDir,
|
||||
appPid: launched.child.pid ?? null,
|
||||
setup: null,
|
||||
samples: [],
|
||||
finalDiagnostics: null,
|
||||
trace: null,
|
||||
appLogSummary: null,
|
||||
appLogsTail: null,
|
||||
cleanupErrors: []
|
||||
}
|
||||
|
||||
try {
|
||||
const connected = await connectToApp(cdpPort)
|
||||
browser = connected.browser
|
||||
page = connected.page
|
||||
await waitForStoreReady(page)
|
||||
await installRendererProbe(page)
|
||||
const identity = await runWithTimeout(
|
||||
'app identity',
|
||||
() => page.evaluate(() => window.api.app.getIdentity?.()),
|
||||
rendererActionTimeoutMs
|
||||
).catch(() => null)
|
||||
console.log(
|
||||
`[apphang-repro] connected gpu=${gpuMode} pid=${result.appPid} identity=${JSON.stringify(identity)}`
|
||||
)
|
||||
result.setup = await setupAppFixture(page, fixture, gpuMode, args.sourceControl)
|
||||
const targets = selectTargets(result.setup, args.cycles)
|
||||
console.log(
|
||||
`[apphang-repro] targets gpu=${gpuMode}: ${targets
|
||||
.map((target) => `${target.kind}:${target.displayName}`)
|
||||
.join(', ')}`
|
||||
)
|
||||
for (const target of targets) {
|
||||
console.log(`[apphang-repro] cycle=${target.index} gpu=${gpuMode} kind=${target.kind}`)
|
||||
result.samples.push(await runActivationCycle(page, target, args))
|
||||
}
|
||||
if (args.deadPtyReactivate) {
|
||||
const uniqueTargets = []
|
||||
const seen = new Set()
|
||||
for (const target of targets) {
|
||||
if (!seen.has(target.id)) {
|
||||
seen.add(target.id)
|
||||
uniqueTargets.push(target)
|
||||
}
|
||||
}
|
||||
console.log(`[apphang-repro] dead-pty-reactivation gpu=${gpuMode}`)
|
||||
result.samples.push(...(await runDeadPtyReactivation(page, uniqueTargets, args)))
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ReproductionObservedError) {
|
||||
result.reproduced = true
|
||||
result.reproductionReason = error.message
|
||||
result.samples.push(error.evidence)
|
||||
} else {
|
||||
// Why: setup/CDP/selector failures are inconclusive, not hang evidence.
|
||||
// Conflating them with `reproduced` lets --expect=repro pass on a broken
|
||||
// harness; callers treat harnessError as a hard failure instead.
|
||||
result.harnessError = error instanceof Error ? error.stack || error.message : String(error)
|
||||
}
|
||||
} finally {
|
||||
result.elapsedMs = Date.now() - startedAt
|
||||
result.finalDiagnostics = await collectRendererDiagnostics(page)
|
||||
result.trace = summarizeTrace(userDataDir)
|
||||
result.appLogSummary = summarizeAppLogs(launched.logs)
|
||||
result.appLogsTail = launched.logs.slice(-120)
|
||||
if (browser) {
|
||||
await browser.close().catch(() => undefined)
|
||||
}
|
||||
await stopDevApp(launched.child)
|
||||
if (!args.keep) {
|
||||
safeRemoveLocalDirectory(userDataDir, result.cleanupErrors)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const rootDir = path.resolve(fileURLToPath(new URL('../../..', import.meta.url)))
|
||||
|
||||
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
|
||||
})
|
||||
return output
|
||||
.replaceAll(String.fromCharCode(0), '')
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim().replace(/^\*\s*/, ''))
|
||||
.filter((line) => line && !line.toLowerCase().startsWith('docker-desktop'))
|
||||
}
|
||||
|
||||
function linuxPathToWslUnc(distro, linuxPath) {
|
||||
if (!linuxPath.startsWith('/')) {
|
||||
throw new Error(`Expected absolute Linux path, got ${linuxPath}`)
|
||||
}
|
||||
return `\\\\wsl.localhost\\${distro}${linuxPath.replace(/\//g, '\\')}`
|
||||
}
|
||||
|
||||
export function createWslFixture(distro) {
|
||||
const script = String.raw`
|
||||
set -euo pipefail
|
||||
base="$(mktemp -d /tmp/orca-apphang-repro.XXXXXX)"
|
||||
repo="$base/repo"
|
||||
mkdir -p "$repo"
|
||||
cd "$repo"
|
||||
git init -q
|
||||
git config user.email apphang-repro@test.local
|
||||
git config user.name "AppHang Repro"
|
||||
mkdir -p src docs
|
||||
printf '# Orca Windows AppHang repro\n' > README.md
|
||||
for n in $(seq 1 25); do
|
||||
printf 'line %03d %s\n' "$n" "abcdefghijklmnopqrstuvwxyz0123456789" >> src/payload.txt
|
||||
done
|
||||
git add -A
|
||||
git commit -q -m "Initial repro fixture"
|
||||
for n in 1 2 3 4; do
|
||||
git branch "repro-wt-$n"
|
||||
git worktree add -q "$base/wt-$n" "repro-wt-$n"
|
||||
mkdir -p "$base/wt-$n/docs"
|
||||
printf 'worktree %s\n' "$n" > "$base/wt-$n/docs/wt.txt"
|
||||
done
|
||||
plain="$base/plain-folder"
|
||||
mkdir -p "$plain/subdir"
|
||||
printf 'plain folder for Orca AppHang repro\n' > "$plain/README.txt"
|
||||
printf '%s\n' "$base" "$repo" "$base/wt-1" "$base/wt-2" "$base/wt-3" "$base/wt-4" "$plain"
|
||||
`
|
||||
const lines = runWsl(distro, script, { timeoutMs: 120_000 }).trim().split(/\r?\n/).filter(Boolean)
|
||||
if (lines.length < 7) {
|
||||
throw new Error(`WSL fixture creation returned unexpected output: ${JSON.stringify(lines)}`)
|
||||
}
|
||||
const [base, repo, ...rest] = lines
|
||||
const plain = rest.at(-1)
|
||||
const worktrees = rest.slice(0, -1)
|
||||
return {
|
||||
distro,
|
||||
baseLinuxPath: base,
|
||||
repoLinuxPath: repo,
|
||||
plainLinuxPath: plain,
|
||||
worktreeLinuxPaths: worktrees,
|
||||
repoUncPath: linuxPathToWslUnc(distro, repo),
|
||||
plainUncPath: linuxPathToWslUnc(distro, plain),
|
||||
worktreeUncPaths: worktrees.map((entry) => linuxPathToWslUnc(distro, entry))
|
||||
}
|
||||
}
|
||||
|
||||
export function removeWslFixture(fixture) {
|
||||
if (!fixture?.baseLinuxPath) {
|
||||
return
|
||||
}
|
||||
const quoted = fixture.baseLinuxPath.replaceAll("'", "'\\''")
|
||||
runWsl(fixture.distro, `rm -rf '${quoted}'`, { timeoutMs: 30_000 })
|
||||
}
|
||||
|
||||
export function createCompletedOnboardingProfile(userDataDir) {
|
||||
mkdirSync(userDataDir, { recursive: true })
|
||||
const profile = {
|
||||
settings: {
|
||||
telemetry: {
|
||||
// Why: synthetic harness/benchmark activity must not send telemetry.
|
||||
// Explicit false with existedBeforeTelemetryRelease=false also keeps
|
||||
// the first-launch consent surface from blocking automation.
|
||||
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`)
|
||||
}
|
||||
|
||||
export function safeRemoveLocalDirectory(dir, cleanupErrors) {
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 })
|
||||
} catch (error) {
|
||||
cleanupErrors.push(error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user