← Commit history

Survive renderer crashes (issue #16): detect a crashed tab renderer (page error + Inspector.targetCrashed), fast-fail its verbs with a reload-to-recover hint instead of hanging the window, clear the flag when reload/navigate respawns it, and reap orphaned/crashed renderers scoped to the session profile on close

John Lauer ·d704de4f2e ·3mo ago ·parent de6ff2f
4 files changed +71−9
adom-bridge-puppeteer-manifest.json+4−4
@@ -1,10 +1,10 @@ {   "manifest_version": 1,   "name": "puppeteer",-  "version": "1.9.77",-  "url": "https://wiki.adom.inc/download/adom/adom-desktop-puppeteer-bridge/1.9.77/adom-bridge-puppeteer-v1.9.77.zip",-  "sha256": "ddf72a38c179d85552be2ec16c3d4721a5f625e639eddf2ee8e999e93211c81f",-  "size": 313835,+  "version": "1.9.78",+  "url": "https://wiki.adom.inc/download/adom/adom-desktop-puppeteer-bridge/1.9.78/adom-bridge-puppeteer-v1.9.78.zip",+  "sha256": "2e335e23ca5353d59971059a10bbe3c10971553050289d50cfb5863f9e3bbf74",+  "size": 315372,   "verbPrefixes": [     "browser_",     "desktop_recorder_",
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-1.9.77+1.9.78
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "puppeteer",   "displayName": "Puppeteer (Chrome for Testing + Native)",-  "version": "1.9.77",+  "version": "1.9.78",   "description": "Drives a browser ALREADY on the machine \u2014 installed Chrome, else Microsoft Edge (every Windows PC ships with Edge) \u2014 launched with a FRESH isolated profile, so the common case has NO ~150 MB Chrome-for-Testing download and it never touches the user's real tabs/logins. Binds its local server to LOOPBACK (127.0.0.1) only, so no Windows Firewall 'allow Node through the firewall' prompt ever pops. Chrome for Testing is fetched only as a LAST RESORT if the machine has no Chromium browser at all. SPAWN-VERIFIED fallback: pup tries each detected browser (Chrome \u2192 Edge \u2192 CfT) and actually launches it, falling through to the next if one won't start (and handling browsers like Edge that relaunch onto another PID), so a corrupt/partial install never hard-fails an open. The browser that launches is cached as the default (persisted across restarts) so it isn't re-probed each time. On spawn the bridge SELF-WARMS: detects browsers + disk, and only if the box has no Chrome/Edge and no cached CfT does it background-fetch CfT so the first open is instant. browser_use pins a specific browser (chrome | edge | cft | auto); {browser:'chrome',install:true} downloads & installs REAL Google Chrome (user-scoped, no admin) on an Edge-only box. browser_readiness (READ-ONLY) reports which browser will be used + the full candidate list + the default + free disk. Every failure returns a specific errorCode + _hint (chrome_install_no_disk, chrome_download_network, chrome_install_permission, chrome_stable_not_detected, \u2026). Launches with FULL browser permissions by default for full debug (strictPermissions:true opts out). Headful automation: open/close windows+tabs, navigate, screenshot, eval JS, record. pup is a GENERIC, non-profile browser only \u2014 every session is a fresh isolated Chrome/Edge process, never the user's real signed-in browser; profile defaults to sessionId. To drive the user's REAL Chrome/Edge (their profile, cookies, SSO), use the Adom browser EXTENSION's nbrowser_* verbs \u2014 a separate bridge, not pup's job.",   "homepage": "https://wiki.adom.inc/adom/adom-desktop",   "author": "Adom Inc.",
src/server.js+65−3
@@ -302,6 +302,29 @@ function attachTab(session, sessionId, page, { makeActive = true, opener = 'user   const tabId = nextTabId(session);   const errors = [];   setupErrorCollection(page, errors);+  // v1.9.78 — SURVIVE A RENDERER CRASH (wiki issue #16). Under many heavy-SPA tabs plus rapid+  // navigate/eval/screenshot churn, one tab's renderer can crash (Chrome's per-tab 'Aw, Snap').+  // puppeteer surfaces that as the page 'error' event; we mark the tab so every verb FAST-FAILS+  // with a clear 'reload this tab' instead of hanging for 20s and wedging the whole window. The+  // crash is isolated to the tab — the window and its other tabs stay drivable.+  const _markCrashed = (why) => {+    try {+      const t = (session.tabs || []).find(x => x.page === page);+      if (t && !t._crashed) {+        t._crashed = true; t._crashedAt = Date.now(); t._crashReason = why;+        console.log(`[crash] session "${sessionId}" tab ${t.tabId} renderer CRASHED (${why}) — verbs on it will fast-fail; reload the tab to recover`);+      }+    } catch (e) {}+  };+  try { page.on('error', (err) => _markCrashed((err && err.message) || 'Page crashed!')); } catch (e) {}+  try {+    // Belt-and-braces at the protocol level — Inspector.targetCrashed fires even when the higher+    // level 'error' event does not (e.g. an OOM-killed renderer).+    page.target().createCDPSession().then((cdp) => {+      try { cdp.on('Inspector.targetCrashed', () => _markCrashed('Inspector.targetCrashed')); } catch (e) {}+      try { cdp.send('Inspector.enable').catch(() => {}); } catch (e) {}+    }).catch(() => {});+  } catch (e) {}   // v1.8.17: PERSISTENT title-suffix injector. AD's browser_raise/lower_os_window   // (AD-core verbs, not this bridge — they shadow our fallback handlers) locate the   // OS window by its " (session: <id>)" title suffix. Post-goto page.evaluate re-adds@@ -572,7 +595,7 @@ function wirePopupTracking(browser, profileName) { // after it's gone used to get the active tab's response silently // (v1.4.8 and earlier had a quirk where some paths did this). We now error // loudly with the exact recipe to use instead.-function resolveTabOrError(session, sessionId, args) {+function resolveTabOrError(session, sessionId, args, { allowCrashed = false } = {}) {   if (args.tabId) {     const t = getTabById(session, args.tabId);     if (!t) {@@ -620,14 +643,32 @@ function resolveTabOrError(session, sessionId, args) {       err._isStructured = true;       throw err;     }+    if (!allowCrashed) _throwIfCrashed(t, sessionId);     return { tab: t, tabId: t.tabId };   }   const t = getActiveTab(session);   if (!t) {     throw new Error(`Session "${sessionId}" has no open tabs.`);   }+  if (!allowCrashed) _throwIfCrashed(t, sessionId);   return { tab: t, tabId: t.tabId }; }+// v1.9.78: a crashed-renderer tab cannot be screenshotted or evaluated — those operations hang+// until the verb times out (20s) and, on a busy window, that read-back wedge is what the user+// perceives as "pup crashed". Fail FAST and tell the caller exactly how to recover.+function _throwIfCrashed(t, sessionId) {+  if (!t || !t._crashed) return;+  const secs = Math.round((Date.now() - (t._crashedAt || Date.now())) / 1000);+  const payload = {+    error: `Tab "${t.tabId}" in session "${sessionId}" has a CRASHED renderer (${t._crashReason || 'crash'}, ${secs}s ago).`,+    errorCode: 'tab_renderer_crashed',+    tabId: t.tabId,+    _hint: `The tab's Chrome renderer process died (usually memory pressure from many heavy tabs, or a navigate racing an eval/screenshot on the same tab). The window and its OTHER tabs are fine. To recover THIS tab: browser_reload {sessionId:"${sessionId}", tabId:"${t.tabId}"} (or browser_navigate it to a URL) — that respawns the renderer and clears the crash flag. Then avoid driving a single tab with overlapping navigate/eval/screenshot calls; wait for one to return before the next.`,+  };+  const err = new Error(JSON.stringify(payload));+  err._isStructured = true;+  throw err;+}  // Send a structured-or-plain error from resolveTabOrError. If the error // message is the structured JSON we throw above, parse it back out and@@ -1396,6 +1437,25 @@ async function killBrowserProcess(browser, profileName) {     }   } +  // v1.9.78 (wiki issue #16) — REAP ORPHANED / CRASHED RENDERERS. taskkill /T kills the process+  // TREE, but a crashed renderer can be reparented (orphaned) and survive the tree kill, lingering+  // at 8-12 MB. They are unambiguous to find: any chrome/CfT process still launched with THIS+  // profile's --user-data-dir. Scoping the sweep to the profile dir makes it impossible to touch+  // the user's real browser or another session's window.+  if (process.platform === 'win32') {+    try {+      const dir = path.join(PROFILES_DIR, profileName);+      const needle = dir.replace(/\\/g, '\\\\');+      const ps = `Get-CimInstance Win32_Process | Where-Object { $_.Name -match 'chrome|msedge' -and $_.CommandLine -match 'user-data-dir' -and $_.CommandLine -like '*${dir.replace(/'/g, "''")}*' } | ForEach-Object { $_.ProcessId }`;+      const out = execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ps], { encoding: 'utf8', timeout: 8000, windowsHide: true });+      const pids = (out || '').split(/\r?\n/).map(x => parseInt(x, 10)).filter(Boolean);+      if (pids.length) {+        for (const rp of pids) { try { execSync(`taskkill /F /PID ${rp}`, { stdio: 'ignore' }); } catch (e) {} }+        console.log(`[reap] profile "${profileName}": swept ${pids.length} orphaned/crashed process(es) that survived the tree kill`);+      }+    } catch (e) { /* reap is best-effort; never block a close on it */ }+  }+   // Also check if Chrome is still locking the profile dir   const lockFile = path.join(PROFILES_DIR, profileName, 'SingletonLock');   try { fs.unlinkSync(lockFile); } catch { /* doesn't exist or can't remove */ }@@ -7481,13 +7541,14 @@ const server = http.createServer(async (req, res) => {           try { ({ session, resolvedId } = await recoverOrRelaunchSession(args)); }           catch (e) { sendSessionResolveError(res, e); return; }           let tab, tabId;-          try { ({ tab, tabId } = resolveTabOrError(session, resolvedId, args)); }+          try { ({ tab, tabId } = resolveTabOrError(session, resolvedId, args, { allowCrashed: true })); }           catch (e) { sendTabResolveError(res, e); return; }           tab.errors.length = 0;           await withTimeout(             tab.page.reload({ waitUntil: 'domcontentloaded', timeout: 25000 }),             30_000, 'page.reload'           );+          if (tab._crashed) { tab._crashed = false; delete tab._crashedAt; delete tab._crashReason; console.log(`[crash] session "${resolvedId}" tab ${tabId} recovered via reload`); }           // v1.8.26: the user is signalled by the auto-flash, NOT by raising the window.           // Only raise if this session is one the user is actively watching.           if (session._foreground) { try { await tab.page.bringToFront(); } catch {} }@@ -7505,7 +7566,7 @@ const server = http.createServer(async (req, res) => {           // v1.8.16: refuse a declared cross-owner navigate (window steal).           { const refusal = ownershipRefusal(session, resolvedId, args, 'browser_navigate'); if (refusal) { sendJSON(res, refusal); return; } }           let tab, tabId;-          try { ({ tab, tabId } = resolveTabOrError(session, resolvedId, args)); }+          try { ({ tab, tabId } = resolveTabOrError(session, resolvedId, args, { allowCrashed: true })); }           catch (e) { sendTabResolveError(res, e); return; }           // Apply stored basic-auth creds for the navigation target's host           // BEFORE goto, so the Chrome native auth dialog never appears@@ -7565,6 +7626,7 @@ const server = http.createServer(async (req, res) => {             // clears it when the window navigated off Adom).             setTimeout(() => { updateWikiJumplist(session, resolvedId).catch(() => {}); }, 1000);           }+          if (tab._crashed) { tab._crashed = false; delete tab._crashedAt; delete tab._crashReason; console.log(`[crash] session "${resolvedId}" tab ${tabId} recovered via navigate`); }           sendJSON(res, { success: true, output: JSON.stringify({ ok: true, url: args.url, sessionId: resolvedId, tabId, ...(authSteerHint(args.url) ? { _hint: authSteerHint(args.url).trim() } : {}) }) });           return;         }