← Commit history

Birth-time handle resolution: each new window is born at a unique off-screen position and its OS handle captured while off-screen and small (before park maximizes it), the only unambiguous moment for a same-profile window; the resolver trusts this birth handle ahead of all geometry heuristics. Finally resolves multi-window profiles the width-wiggle never could

John Lauer ·d8f96da53d ·3mo ago ·parent b1b0e20
4 files changed +89−9
adom-bridge-puppeteer-manifest.json+4−4
@@ -1,10 +1,10 @@ {   "manifest_version": 1,   "name": "puppeteer",-  "version": "1.9.303",-  "url": "https://wiki.adom.inc/download/adom/adom-desktop-puppeteer-bridge/1.9.303/adom-bridge-puppeteer-v1.9.303.zip",-  "sha256": "91038fe7735245505470b1615ec0ce72e7ea3c4dc07949abfbaf5c89ffc32ecf",-  "size": 726129,+  "version": "1.9.304",+  "url": "https://wiki.adom.inc/download/adom/adom-desktop-puppeteer-bridge/1.9.304/adom-bridge-puppeteer-v1.9.304.zip",+  "sha256": "209ab37f2842054ad177fed445e2981ba31add5dc8a004a980f5ac844d706a94",+  "size": 727271,   "verbPrefixes": [     "browser_",     "desktop_recorder_",
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-1.9.303+1.9.304
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "puppeteer",   "displayName": "Puppeteer (Chrome for Testing + Native)",-  "version": "1.9.303",+  "version": "1.9.304",   "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. macOS (v1.9.74+): full parity with mac-native mechanics \u2014 background-by-default is the app-level hide (windows stay drivable/screenshottable while hidden), raise/lower map to unhide+activate/hide, browser_alert_window posts a native toast whose click focuses the window, browser_use {browser:'chrome',install:true} installs Chrome from the official dmg, and taskbar identity/badging remains Windows-only.",   "homepage": "https://wiki.adom.inc/adom/adom-desktop",   "author": "Adom Inc.",
src/server.js+83−3
@@ -312,6 +312,7 @@ const _launchInFlight = new Map(); // a fleet of AI threads opening default windows simultaneously is the 10,000-user case. const _profileOpenChain = new Map(); // profileName -> tail promise let _tabClaimSeq = 0; // monotonic per-call marker for in-window tab adoption (see addTabToSession)+let _birthSeq = 0;    // monotonic counter for unique off-screen birth positions (birth-time hwnd resolution) let _regenBusy = false;   // a dashboard "regenerate all overlays" sweep is in flight let _lastRegen = null;    // { at, done, swept, painted, changed, results[] } from the last sweep const _overlayRefreshTimers = new Map(); // per-session debounce for the centralized post-verb overlay re-sync@@ -4883,6 +4884,50 @@ async function hwndBelongsToPup(hwnd, session) {   } catch (e) {}   return false; }+// v1.9.304: enumerate every visible top-level Chrome browser frame with its owner pid + rect. Shared+// by birth-time resolution (createPageInNewWindow) and the resolver. Returns [{h,pid,L,T,W,H}].+async function enumChromeWidgetWindows() {+  if (process.platform !== 'win32') return [];+  try {+    const scriptPath = path.join(require('os').tmpdir(), `_adom_enumcw_${process.pid}.ps1`);+    const ps = [+      'Add-Type @"',+      'using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic;',+      'public class WEnum2 {',+      '  public delegate bool Proc(IntPtr h, IntPtr l);',+      '  [DllImport("user32.dll")] public static extern bool EnumWindows(Proc p, IntPtr l);',+      '  [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);',+      '  [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);',+      '  [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);',+      '  [DllImport("user32.dll")] public static extern int GetClassName(IntPtr h, StringBuilder s, int n);',+      '  public struct RECT { public int L, T, R, B; }',+      '  public static List<string> Find() {',+      '    var outp = new List<string>();',+      '    EnumWindows((h, l) => {',+      '      if (!IsWindowVisible(h)) return true;',+      '      uint pid; GetWindowThreadProcessId(h, out pid);',+      '      var cn = new StringBuilder(128); GetClassName(h, cn, 128);',+      '      if (cn.ToString() != "Chrome_WidgetWin_1") return true;',+      '      RECT r; GetWindowRect(h, out r);',+      '      outp.Add(((long)h).ToString() + "," + pid + "," + r.L + "," + r.T + "," + (r.R - r.L) + "," + (r.B - r.T));',+      '      return true;',+      '    }, IntPtr.Zero);',+      '    return outp;',+      '  } }',+      '"@',+      '[WEnum2]::Find() | ForEach-Object { Write-Output $_ }',+    ].join('\r\n');+    fs.writeFileSync(scriptPath, ps);+    const out = (await runPsHiddenPromise(scriptPath, { timeout: 9000 }) || '').trim();+    if (!out) return [];+    const rows = [];+    for (const line of out.split(/\r?\n/)) {+      const p = line.split(',').map(Number);+      if (p[0] && Number.isFinite(p[4])) rows.push({ h: p[0], pid: p[1], L: p[2], T: p[3], W: p[4], H: p[5] });+    }+    return rows;+  } catch (e) { return []; }+} async function resolveSessionHwndByBounds(session, sessionId) {   if (process.platform !== 'win32' || !session) return null;   let _releaseWiggle = null;   // v1.9.291: hoisted so the outer catch can always release the lock@@ -4894,6 +4939,18 @@ async function resolveSessionHwndByBounds(session, sessionId) {       console.log(`[hwnd] "${sessionId}" cached hwnd ${session._hwnd} is stale/foreign — discarding and re-resolving`);       session._hwnd = null;     }+    // v1.9.304: BIRTH-TIME handle — captured while this window was off-screen at creation, the only+    // unambiguous moment for a same-profile window. Trust it (validated) ahead of every geometry+    // heuristic; this is what finally resolves multi-window profiles the wiggle never could.+    try {+      const p0 = (session.tabs || [])[0] && (session.tabs || [])[0].page;+      const bh = p0 && p0.__pupHwnd;+      if (bh && await hwndBelongsToPup(Number(bh), session)) {+        session._hwnd = Number(bh); persistSessionHwnd(sessionId, Number(bh));+        console.log(`[hwnd] "${sessionId}" resolved OS handle ${bh} — birth-time capture (off-screen at creation)`);+        return Number(bh);+      }+    } catch (e) {}     // v1.9.274 (John's dashboard showed 3 'untracked' windows that WERE the real session windows):     // every parked window shares the IDENTICAL rect (work-area minus insets), so pure geometry     // matching cannot distinguish windows after a restart and misassigns hwnds. The title tag is@@ -7245,8 +7302,14 @@ async function getOrLaunchBrowser(profileName, { freshProfile = false, strictPer // always makes a tab; only CDP Target.createTarget accepts newWindow. Page identity is resolved by // diffing browser.pages() before/after rather than matching internal target ids, so this stays // correct across puppeteer versions. Returns null if the window never materialises.-async function createPageInNewWindow(browser) {+async function createPageInNewWindow(browser, profileName) {   let cdp = null;+  // v1.9.304 BIRTH-TIME hwnd: give each new window a UNIQUE off-screen birth position so we can+  // resolve its exact OS handle while it is still off-screen AND small (1280x800) — the ONLY moment a+  // same-profile window is unambiguous. After park it is maximized + shares the parked rect with its+  // siblings, which is why the width-wiggle could never tell them apart. Captured here, stashed on the+  // page, trusted by resolveSessionHwndByBounds. This is the fix for multi-window profiles (adom-you).+  const birthLeft = -32000 - ((_birthSeq++ % 300) * 40);   try {     const before = new Set(await browser.pages());     cdp = await browser.target().createCDPSession();@@ -7263,12 +7326,29 @@ async function createPageInNewWindow(browser) {     // their screen. This is the at-the-source fix; parks and re-asserts then act on an unfocused     // window (osBottomUnlessForeground no longer mistakes the creation-grab for user intent).     const prevFg = osGetForegroundWindow();-    await cdp.send('Target.createTarget', { url: 'about:blank', newWindow: true, left: -32000, top: -32000, width: 1280, height: 800 });+    await cdp.send('Target.createTarget', { url: 'about:blank', newWindow: true, left: birthLeft, top: -32000, width: 1280, height: 800 });     let fresh = null;     for (let i = 0; i < 50 && !fresh; i++) {       fresh = (await browser.pages()).find(p => !before.has(p));       if (!fresh) await new Promise(r => setTimeout(r, 100));     }+    // Resolve the OS handle NOW, by the unique off-screen birth position, before park moves it on-+    // screen. Parked siblings are at positive L; only newborns sit far off-screen, so "the off-screen+    // window of this profile at ~birthLeft" is unambiguous. Stash it on the page for the resolver.+    if (fresh && process.platform === 'win32' && profileName) {+      try {+        const pids = pupBrowserPidSet(profileName);+        let picked = null;+        for (let i = 0; i < 12 && !picked; i++) {+          const rows = await enumChromeWidgetWindows();+          const off = rows.filter(r => pids.has(r.pid) && r.L < -10000);+          if (off.length === 1) picked = off[0].h;+          else if (off.length > 1) { for (const sc of [1, 1.25, 1.5, 1.75, 2]) { const m = off.find(r => Math.abs(r.L - Math.round(birthLeft * sc)) <= 40); if (m) { picked = m.h; break; } } }+          if (!picked) await new Promise(r => setTimeout(r, 150));+        }+        if (picked) { fresh.__pupHwnd = picked; console.log(`[hwnd] birth-resolved new window on "${profileName}" -> ${picked} (off-screen L≈${birthLeft})`); }+      } catch (e) {}+    }     try {       const nowFg = osGetForegroundWindow();       // Diagnostic only. The playbook (dev-skills/pup-bridge-dev, SOLVED PLAYBOOK) says this can@@ -7399,7 +7479,7 @@ async function launchSession(sessionId, url, { freshProfile = false, profile, st   if (page) {     console.log(`Reusing existing blank tab (${page.url()}) for session "${sessionId}"`);   } else if (profileAlreadyInUse) {-    page = await createPageInNewWindow(browser);+    page = await createPageInNewWindow(browser, profileName);     if (page) page._pupCreated = true;   // v1.9.142: never a 'restored leftover' — see closeRestoredLeftoverTabs     if (page) console.log(`Session "${sessionId}" opened in its OWN window on shared profile "${profileName}"`);     else { console.log(`[window] newWindow target failed for "${sessionId}" -- falling back to a tab`); page = await browser.newPage(); page._pupCreated = true; }