@xkwdstore/agent 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,8 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
6
6
 
7
7
  > **@xkwdstore/agent 2.0.3 is the last version published on npm.**
8
8
  >
9
- > The current source version is **2.0.4** (lease same-device recovery fix). It is
9
+ > The current source version is **2.0.5** (window-truth visibility fix,
10
+ > lifecycle cause codes, cookie parity, stopped-frame dedupe). It is
10
11
  > NOT claimed to be published unless the release workflow has published it — see
11
12
  > `reports/` for the authoritative publication state.
12
13
 
@@ -29,7 +30,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
29
30
  The generated launcher runs the pinned command:
30
31
 
31
32
  ```powershell
32
- npx --yes @xkwdstore/agent@2.0.4 start
33
+ npx --yes @xkwdstore/agent@2.0.5 start
33
34
  ```
34
35
 
35
36
  Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
@@ -177,10 +178,11 @@ The agent does NOT update itself. To use a newer version, change the version
177
178
  number in the command. The pinned command for this release is:
178
179
 
179
180
  ```powershell
180
- npx --yes @xkwdstore/agent@2.0.4 start
181
+ npx --yes @xkwdstore/agent@2.0.5 start
181
182
  ```
182
183
 
183
- > 2.0.4 is the current local agent version (same-device lease recovery fix).
184
+ > 2.0.5 is the current local agent version (window-truth visibility fix,
185
+ > lifecycle cause codes, cookie parity, stopped-frame dedupe).
184
186
  > 2.0.3 was the previous release.
185
187
  >
186
188
  > The server checks compatibility at startup and displays a clear message if
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xkwdstore/agent",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "XKWDStore Agent — terminal-only, cryptographically authenticated CLI for browser automation",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -24,7 +24,7 @@ const crypto = require('crypto');
24
24
  const os = require('os');
25
25
  const path = require('path');
26
26
 
27
- const CLI_VERSION = '2.0.4';
27
+ const CLI_VERSION = '2.0.5';
28
28
  const PROTOCOL_VERSION = 2;
29
29
 
30
30
  // ── Command parsing ──────────────────────────────────────────────────────────
@@ -28,6 +28,34 @@ const { buildStealthScript } = require('./stealth');
28
28
  const leaseClient = require('./leaseClient');
29
29
  const { PROFILES_DIR } = require('./deviceKeyStore');
30
30
 
31
+ // ── Browser-lifecycle diagnostics ────────────────────────────────────────────
32
+ //
33
+ // A browser session that ends by itself previously left NO local trace: the
34
+ // only signal was the lease being released server-side, so "who closed this
35
+ // browser?" could not be answered from the agent. Every path that can end a
36
+ // session now emits one line with a CAUSE CODE. Records only the cause code,
37
+ // the account id and a monotonic timestamp — never cookie/token/credential
38
+ // values and never the profile directory contents.
39
+ //
40
+ // START_SESSION a session was created and registered
41
+ // STOP_COMMAND an explicit stopSession command closed it
42
+ // STOP_NOT_FOUND a stopSession command arrived with no active session
43
+ // STOP_CLOSE_FAILED a stopSession command could NOT confirm the close
44
+ // (fail-closed: no 'stopped' frame was sent, the session
45
+ // stays registered, the lease stays blocking/recoverable)
46
+ // CONTEXT_CLOSE the Playwright context closed (any cause)
47
+ // CONTEXT_CLOSE_DUP a second close event for an already-removed session
48
+ // PAGE_CLOSE a page closed
49
+ // PAGE_CRASH a page crashed
50
+ // BROWSER_DISCONNECTED the underlying browser disconnected
51
+ // CLOSE_ALL_SESSIONS closeAllSessions() ran (agent shutdown / WS loss)
52
+ function _logLifecycle(cause, accountId, extra) {
53
+ try {
54
+ const detail = extra ? ' ' + JSON.stringify(extra) : '';
55
+ process.stderr.write(`[session-lifecycle] ${new Date().toISOString()} ${cause} account=${accountId}${detail}\n`);
56
+ } catch {}
57
+ }
58
+
31
59
  // ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
32
60
  //
33
61
  // "activeSessions is empty" is NOT proof a browser stopped: an agent-process
@@ -61,6 +89,12 @@ function _chromeCommandLines() {
61
89
  let _chromeLinesProvider = _chromeCommandLines;
62
90
  function _setChromeLinesProvider(fn) { _chromeLinesProvider = typeof fn === 'function' ? fn : _chromeCommandLines; }
63
91
 
92
+ // Test-only injectable window-probe provider: tests inject synthetic probe
93
+ // output lines so the multi-process selection + visibility verdict are provable
94
+ // without spawning a real Windows session.
95
+ let _windowProbeProvider = null;
96
+ function _setWindowProbeProvider(fn) { _windowProbeProvider = typeof fn === 'function' ? fn : null; }
97
+
64
98
  /**
65
99
  * Return 'running' | 'stopped' | 'unknown' for whether a Chrome process still
66
100
  * owns the EXACT profile directory. Fails closed to 'unknown' on any error.
@@ -84,29 +118,68 @@ function _detectProfileChromeRunning(profileDir) {
84
118
  }
85
119
  }
86
120
 
87
- // ── Windows foreground helper ────────────────────────────────────────────────
121
+ // ── Windows window-visibility helper ─────────────────────────────────────────
88
122
  //
89
123
  // page.bringToFront() may be insufficient on real Windows to actually bring
90
124
  // the browser window to the foreground (Windows foreground lock rules).
91
- // This helper uses a narrow, safe PowerShell command to activate the EXACT
92
- // Chrome window associated with this session's persistent profile directory.
125
+ // This helper uses a narrow, safe PowerShell command to locate the EXACT
126
+ // Chrome window associated with this session's persistent profile directory,
127
+ // un-minimize it, attempt to activate it, and REPORT what it actually observed.
93
128
  //
94
- // Safety requirements:
129
+ // Two defects are fixed here (both produced a FALSE `visible: false`):
130
+ //
131
+ // (a) FIRST-MATCH PROCESS SELECTION. The previous script stopped at the
132
+ // FIRST chrome.exe whose command line contained the profile dir
133
+ // (`$target = $p; break`). Chromium is a multi-process tree — one root
134
+ // browser process plus renderer / gpu-process / utility / crashpad-handler
135
+ // children — and EVERY child carries the same `--user-data-dir`.
136
+ // Verified on the real Windows host: 10 processes matched the profile and
137
+ // 9 of them reported `MainWindowHandle = 0`; ONLY the root browser process
138
+ // owns a window. Whether the old code succeeded was therefore decided by
139
+ // CIM enumeration order rather than by window truth.
140
+ //
141
+ // (b) SetForegroundWindow AS THE VISIBILITY VERDICT. The old code derived
142
+ // `visible` from SetForegroundWindow()'s BOOL return value. That API is
143
+ // subject to the Windows foreground lock: it returns FALSE whenever the
144
+ // current foreground process refuses to yield, even though the Chrome
145
+ // window is genuinely present, un-minimized and on screen. The dashboard's
146
+ // `started === true && visible === true` gate then reported "did not
147
+ // appear visibly" for a browser that WAS visible.
148
+ //
149
+ // The fix separates the two questions:
150
+ // * PRESENCE/VISIBILITY — what `visible` now means: a real, non-minimized
151
+ // top-level window exists for THIS profile. Proven with IsWindowVisible()
152
+ // plus a sane window rect. A refused foreground switch no longer makes a
153
+ // genuinely visible browser report as invisible.
154
+ // * FOCUS — still best effort and still attempted (un-minimize via
155
+ // ShowWindowAsync SW_RESTORE, then SetForegroundWindow), but reported
156
+ // separately as `focused` instead of being conflated with visibility.
157
+ //
158
+ // Safety requirements (unchanged):
95
159
  // - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
96
160
  // - uses execFileSync argument arrays (no shell:true, no command interpolation)
97
161
  // - profileDir is passed via STDIN (never in command arguments)
98
- // - targets ONLY the Chrome process whose command line contains the exact
162
+ // - only ever considers Chrome processes whose command line contains the exact
99
163
  // profileDir (not "most recent Chrome" globally)
164
+ // - scans EVERY match but only ever selects a process that actually owns a
165
+ // window; it never guesses or fabricates a handle
100
166
  // - does NOT kill or focus unrelated windows
101
- // - Add-Type is defined BEFORE calling SetForegroundWindow (ordering fix)
102
- // - returns true only if the intended window was identified and foregrounded
167
+ // - Add-Type is defined BEFORE any user32 call (ordering fix)
103
168
  //
104
169
  // @param {string} profileDir — the persistent profile directory for this session
105
- // @returns {boolean} true if the window was identified and foregrounded
170
+ // @returns {{visible:boolean, focused:boolean, pid:number|null, hwnd:number, reason:string}}
106
171
 
107
- function _windowsForegroundChrome(profileDir) {
108
- if (os.platform() !== 'win32') return true; // non-Windows: no-op success
109
- if (!profileDir) return false;
172
+ function _windowsWindowState(profileDir) {
173
+ // Non-Windows: bringToFront() is sufficient, there is no foreground lock.
174
+ if (os.platform() !== 'win32') {
175
+ return { visible: true, focused: true, pid: null, hwnd: 0, reason: 'non_windows' };
176
+ }
177
+ if (!profileDir) {
178
+ return { visible: false, focused: false, pid: null, hwnd: 0, reason: 'no_profile' };
179
+ }
180
+ if (typeof _windowProbeProvider === 'function') {
181
+ return _parseWindowProbe(_windowProbeProvider(profileDir));
182
+ }
110
183
  try {
111
184
  const nodePath = require('path');
112
185
  const { execFileSync } = require('child_process');
@@ -115,47 +188,174 @@ function _windowsForegroundChrome(profileDir) {
115
188
 
116
189
  // Fixed PowerShell script — NO user data interpolation.
117
190
  // The profileDir is passed via STDIN and read by the script.
118
- // Add-Type is defined BEFORE any call to SetForegroundWindow.
119
- // The script:
120
- // 1. Reads the profileDir from stdin
121
- // 2. Finds chrome.exe processes whose command line contains that exact path
122
- // 3. Gets the MainWindowHandle of that specific process
123
- // 4. Uses SetForegroundWindow + ShowWindowAsync to restore+foreground it
124
- // 5. Outputs "OK" or "FAIL" so the caller knows whether it worked
125
- const script =
126
- "$ErrorActionPreference='Stop'; " +
127
- "Add-Type -Namespace Win32 -Name Native -MemberDefinition '" +
128
- "[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd); " +
129
- "[DllImport(\"user32.dll\")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); " +
130
- "[DllImport(\"user32.dll\")] public static extern bool IsIconic(IntPtr hWnd); " +
131
- "'; " +
132
- "$profileDir = [Console]::In.ReadToEnd().Trim(); " +
133
- "if (-not $profileDir) { Write-Output 'FAIL:no_profile'; exit 0 }; " +
134
- "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" -ErrorAction SilentlyContinue; " +
135
- "$target = $null; " +
136
- "foreach ($p in $procs) { " +
137
- " if ($p.CommandLine -and ($p.CommandLine -like \"*$profileDir*\")) { $target = $p; break } " +
138
- "}; " +
139
- "if (-not $target) { Write-Output 'FAIL:no_process'; exit 0 }; " +
140
- "$proc = Get-Process -Id $target.ProcessId -ErrorAction SilentlyContinue; " +
141
- "if (-not $proc -or $proc.MainWindowHandle -eq [IntPtr]::Zero) { Write-Output 'FAIL:no_window'; exit 0 }; " +
142
- "$handle = $proc.MainWindowHandle; " +
143
- "if ([Win32.Native]::IsIconic($handle)) { [void][Win32.Native]::ShowWindowAsync($handle, 9) }; " +
144
- "$result = [Win32.Native]::SetForegroundWindow($handle); " +
145
- "if ($result) { Write-Output 'OK' } else { Write-Output 'FAIL:foreground' }";
191
+ // Add-Type is defined BEFORE any user32 call.
192
+ //
193
+ // The script OBSERVES and ACTS, but does NOT decide which process is "the
194
+ // browser". It reports EVERY chrome.exe whose command line contains the
195
+ // exact profile path together with what Windows says about that process's
196
+ // window. The selection rule then lives in `_selectWindowOwner` in JS, where
197
+ // it is unit-testable — the previous version decided inside the script with
198
+ // a `break` on the FIRST match, which selected a windowless child whenever
199
+ // CIM happened to enumerate a renderer/gpu/utility process first.
200
+ //
201
+ // Output layout (one line, `|`-delimited, no user data):
202
+ // <status>|<focusedPostAttempt>|<cand>;<cand>;...
203
+ // <cand> = pid:hasWindow:isRoot:hwnd:shown:iconic:w:h
204
+ // Focus is attempted on the process JS would pick (same rule, computed
205
+ // in-script) so the attempt is not wasted on a windowless child.
206
+ const script = [
207
+ "$ErrorActionPreference='SilentlyContinue';",
208
+ 'Add-Type -Namespace Win32 -Name Native -MemberDefinition \'',
209
+ '[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); ',
210
+ '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); ',
211
+ '[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd); ',
212
+ '[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); ',
213
+ '[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); ',
214
+ '[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); ',
215
+ '[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }',
216
+ '\';',
217
+ '$profileDir = [Console]::In.ReadToEnd().Trim();',
218
+ "if (-not $profileDir) { Write-Output 'no_profile|False|'; exit 0 };",
219
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\";",
220
+ '$matched = @();',
221
+ 'foreach ($p in $procs) {',
222
+ ' if ($p.CommandLine -and ($p.CommandLine -like "*$profileDir*")) { $matched += $p }',
223
+ '};',
224
+ "if ($matched.Count -eq 0) { Write-Output 'no_process|False|'; exit 0 };",
225
+ // Observation pass: describe EVERY candidate, including windowless
226
+ // children (hasWindow=0). Nothing here short-circuits.
227
+ '$rows = @();',
228
+ 'foreach ($p in $matched) {',
229
+ ' $cand = Get-Process -Id $p.ProcessId;',
230
+ ' $isRoot = 0;',
231
+ ' if ($p.CommandLine -and ($p.CommandLine -notmatch "--type=")) { $isRoot = 1 };',
232
+ ' $hnd = [IntPtr]::Zero;',
233
+ ' if ($cand -and $cand.MainWindowHandle) { $hnd = $cand.MainWindowHandle };',
234
+ ' $hasWin = 0; $shown = $false; $iconic = $false; $w = 0; $h = 0;',
235
+ ' if ($hnd -ne [IntPtr]::Zero) {',
236
+ ' $hasWin = 1;',
237
+ ' $shown = [bool][Win32.Native]::IsWindowVisible($hnd);',
238
+ ' $iconic = [bool][Win32.Native]::IsIconic($hnd);',
239
+ ' $r = New-Object Win32.Native+RECT;',
240
+ ' if ([Win32.Native]::GetWindowRect($hnd, [ref]$r)) { $w = $r.Right - $r.Left; $h = $r.Bottom - $r.Top };',
241
+ ' };',
242
+ " $rows += ('{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}' -f $p.ProcessId, $hasWin, $isRoot, [int64]$hnd, $shown, $iconic, $w, $h)",
243
+ '};',
244
+ // Focus pass: target the root browser process that owns a window, else
245
+ // any window owner. Best effort — the result is reported, never treated
246
+ // as proof of visibility.
247
+ '$pick = $null;',
248
+ 'foreach ($row in $rows) { $f = $row.Split(":"); if ($f[1] -eq "1" -and $f[2] -eq "1") { $pick = $f[3]; break } };',
249
+ 'if (-not $pick) { foreach ($row in $rows) { $f = $row.Split(":"); if ($f[1] -eq "1") { $pick = $f[3]; break } } };',
250
+ '$focused = $false;',
251
+ 'if ($pick -and $pick -ne "0") {',
252
+ ' $h2 = [IntPtr][int64]$pick;',
253
+ ' if ([Win32.Native]::IsIconic($h2)) { [void][Win32.Native]::ShowWindowAsync($h2, 9) };',
254
+ ' [void][Win32.Native]::SetForegroundWindow($h2);',
255
+ ' Start-Sleep -Milliseconds 150;',
256
+ ' $focused = [bool]([Win32.Native]::GetForegroundWindow() -eq $h2)',
257
+ '};',
258
+ "Write-Output ('candidates|' + $focused + '|' + ($rows -join ';'))",
259
+ ].join(' ');
146
260
 
147
261
  const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
148
262
  windowsHide: true,
149
263
  encoding: 'utf8',
150
- timeout: 5000,
264
+ // The previous 5s budget silently swallowed the real reason for a
265
+ // `visible:false`: Add-Type compiles C#, then Get-CimInstance reads the
266
+ // command line of every chrome.exe (a Chromium tree is 40+ processes).
267
+ // A timeout aborted the probe and the bare `catch` turned it into
268
+ // "not visible". The budget is now generous and a timeout is reported
269
+ // explicitly instead of being indistinguishable from a missing window.
270
+ timeout: 20000,
151
271
  input: profileDir, // profileDir via STDIN — never in command arguments
152
272
  }).trim();
153
273
 
154
- return output === 'OK';
155
- } catch {
156
- // Foreground helper failed — return false so visible is not claimed
157
- return false;
274
+ return _parseWindowProbe(output);
275
+ } catch (err) {
276
+ // The probe failed — fail closed, but never claim a reason we did not prove.
277
+ const reason = err && err.killed ? 'probe_timeout' : 'probe_failed';
278
+ return { visible: false, focused: false, pid: null, hwnd: 0, reason };
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Select WHICH candidate process owns the browser window.
284
+ *
285
+ * A Chromium tree attaches the same `--user-data-dir` to every child process,
286
+ * but only the ROOT browser process owns a top-level window — verified on the
287
+ * real Windows host: of 10 processes matching one profile, 9 reported
288
+ * MainWindowHandle = 0. Selection rule:
289
+ *
290
+ * 1. a ROOT process (no `--type=`) that owns a window — the real browser
291
+ * 2. otherwise any process that owns a window — defensive fallback
292
+ * 3. otherwise nothing — never fabricate a window
293
+ *
294
+ * A windowless child is NEVER selected and never stops the scan.
295
+ *
296
+ * @param {Array<{pid:number,hasWindow:boolean,isRoot:boolean,hwnd:number,shown:boolean,iconic:boolean,w:number,h:number}>} candidates
297
+ * @returns {object|null} the selected candidate, or null when none owns a window
298
+ */
299
+ function _selectWindowOwner(candidates) {
300
+ if (!Array.isArray(candidates) || candidates.length === 0) return null;
301
+ const withWindow = candidates.filter((c) => c && c.hasWindow && c.hwnd);
302
+ if (withWindow.length === 0) return null;
303
+ return withWindow.find((c) => c.isRoot) || withWindow[0];
304
+ }
305
+
306
+ /**
307
+ * Parse the `|`-delimited window-probe output into a structured verdict.
308
+ *
309
+ * The ONE rule that matters: a window that EXISTS and is SHOWN is visible.
310
+ * SetForegroundWindow's refusal (the Windows foreground lock) is a FOCUS
311
+ * outcome and must never be reported as "the browser is not visible".
312
+ *
313
+ * @param {string} output — raw probe line (or injected test fixture)
314
+ * @returns {{visible:boolean, focused:boolean, pid:number|null, hwnd:number, reason:string}}
315
+ */
316
+ function _parseWindowProbe(output) {
317
+ const parts = String(output == null ? '' : output).trim().split('|');
318
+ const status = parts[0];
319
+
320
+ if (status !== 'candidates') {
321
+ // Transport-level outcome: no profile, no matching process, timeout, etc.
322
+ return { visible: false, focused: false, pid: null, hwnd: 0, reason: status || 'probe_failed' };
158
323
  }
324
+
325
+ const focused = parts[1] === 'True';
326
+ const raw = parts[2] || '';
327
+ const candidates = raw
328
+ .split(';')
329
+ .filter(Boolean)
330
+ .map((row) => {
331
+ const f = row.split(':');
332
+ return {
333
+ pid: parseInt(f[0], 10),
334
+ hasWindow: f[1] === '1',
335
+ isRoot: f[2] === '1',
336
+ hwnd: parseInt(f[3], 10) || 0,
337
+ shown: f[4] === 'True',
338
+ iconic: f[5] === 'True',
339
+ w: parseInt(f[6], 10) || 0,
340
+ h: parseInt(f[7], 10) || 0,
341
+ };
342
+ });
343
+
344
+ const owner = _selectWindowOwner(candidates);
345
+ if (!owner) {
346
+ // Processes matched but none owns a window: a real "not visible" finding.
347
+ return { visible: false, focused, pid: null, hwnd: 0, reason: 'no_window' };
348
+ }
349
+
350
+ // A real window: shown, not minimized, with a sane on-screen rect.
351
+ const hasRealWindow = owner.hwnd !== 0 && owner.shown && !owner.iconic && owner.w >= 100 && owner.h >= 100;
352
+ return {
353
+ visible: hasRealWindow,
354
+ focused,
355
+ pid: Number.isFinite(owner.pid) ? owner.pid : null,
356
+ hwnd: owner.hwnd,
357
+ reason: hasRealWindow ? 'window_visible' : 'window_not_visible',
358
+ };
159
359
  }
160
360
 
161
361
  // Active sessions: accountId -> { context, page, profileDir }
@@ -196,6 +396,10 @@ async function closeAllSessions() {
196
396
  if (!session) continue;
197
397
  // Delete BEFORE closing so a concurrent call does not double-close.
198
398
  sessions.delete(accountId);
399
+ // Deliberate close: the context close listener must not send its own
400
+ // 'stopped' frame for an agent-initiated shutdown.
401
+ session.stopping = true;
402
+ _logLifecycle('CLOSE_ALL_SESSIONS', accountId);
199
403
  try {
200
404
  if (session.context) await session.context.close().catch(() => {});
201
405
  } catch {}
@@ -596,11 +800,13 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
596
800
  await context.addInitScript(buildStealthScript(fingerprint));
597
801
 
598
802
  // The server sends cookies in options (options.cookies); accept the flat
599
- // params form too for robustness.
803
+ // params form too for robustness. The value is normally the JSON TEXT of a
804
+ // cookie array, so it MUST be normalized before injection — the previous
805
+ // `Array.isArray()` guard silently dropped every string payload and left the
806
+ // browser unauthenticated. Injection happens BEFORE the first navigation so
807
+ // the initial request already carries the account session.
600
808
  const cookiesToInject = launchOpts.cookies || params.cookies;
601
- if (cookiesToInject && Array.isArray(cookiesToInject)) {
602
- try { await context.addCookies(cookiesToInject); } catch {}
603
- }
809
+ const cookieDiag = await _injectCookies(context, cookiesToInject);
604
810
 
605
811
  const pages = context.pages();
606
812
  const page = pages[0] || await context.newPage();
@@ -632,14 +838,15 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
632
838
  };
633
839
  }
634
840
 
635
- // Windows-specific foreground: page.bringToFront() alone may not overcome
636
- // the Windows foreground lock. This helper targets the EXACT Chrome process
637
- // whose command line contains this session's profileDir (passed via stdin,
638
- // not interpolated). It returns true ONLY if the intended window was
639
- // identified and successfully foregrounded.
640
- let foregroundVerified = false;
841
+ // Windows-specific window verification: page.bringToFront() alone may not
842
+ // overcome the Windows foreground lock. The probe targets the EXACT Chrome
843
+ // process whose command line contains this session's profileDir (passed via
844
+ // stdin, not interpolated). It reports VISIBILITY (a real, non-minimized
845
+ // window exists for this profile) separately from FOCUS (the foreground
846
+ // switch was allowed). See _windowsWindowState for the two defects fixed.
847
+ let windowState = { visible: bringToFrontOk, focused: bringToFrontOk, pid: null, hwnd: 0, reason: 'not_probed' };
641
848
  if (bringToFrontOk) {
642
- foregroundVerified = _windowsForegroundChrome(profileDir);
849
+ windowState = _windowsWindowState(profileDir);
643
850
  }
644
851
 
645
852
  // Re-check after focus: the page may have closed in the meantime.
@@ -651,9 +858,10 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
651
858
  };
652
859
  }
653
860
 
654
- const session = { context, page, profileDir, accountId, lease: null };
861
+ const session = { context, page, profileDir, accountId, lease: null, stopping: false };
655
862
  if (lease) leaseClient.bind(session, lease);
656
863
  activeSessions.set(accountId, session);
864
+ _logLifecycle('START_SESSION', accountId, { visible: windowState.visible, focused: windowState.focused, reason: windowState.reason });
657
865
 
658
866
  // ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
659
867
  // The server's session cache (`agent.sessions`) and the durable lease TTL
@@ -670,12 +878,41 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
670
878
  // A browser context closed outside our control (user closed the window,
671
879
  // crash): report the verified stop so the server releases the lease — a
672
880
  // dead local browser must not keep the account locked.
881
+ //
882
+ // 'stopping' is set by _stopSession / closeAllSessions so a deliberate close
883
+ // does NOT send a second 'stopped' frame: the command path already acks it,
884
+ // and two identical lease-bound stops for one stop were a duplicate.
673
885
  context.on('close', () => {
674
886
  const closed = activeSessions.get(accountId);
675
- if (closed === session) activeSessions.delete(accountId);
887
+ if (session.stopping) {
888
+ _logLifecycle('CONTEXT_CLOSE', accountId, { duplicate: true, reason: 'command_initiated' });
889
+ return;
890
+ }
891
+ if (closed !== session) {
892
+ // The session was already replaced/removed — never report a stop for a
893
+ // session that is no longer the active one.
894
+ _logLifecycle('CONTEXT_CLOSE_DUP', accountId);
895
+ return;
896
+ }
897
+ _logLifecycle('CONTEXT_CLOSE', accountId);
898
+ activeSessions.delete(accountId);
676
899
  try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(closed || session, accountId, 'stopped'))); } catch {}
677
900
  });
678
901
 
902
+ // Page-level causes: a closed/crashed page is the leading hypothesis for a
903
+ // browser that appears to quit on its own (closing the LAST page ends a
904
+ // persistent context). Recorded so the next occurrence is identifiable.
905
+ try {
906
+ page.on('close', () => _logLifecycle('PAGE_CLOSE', accountId, { pagesLeft: context.pages().length }));
907
+ page.on('crash', () => _logLifecycle('PAGE_CRASH', accountId));
908
+ } catch {}
909
+ try {
910
+ const browser = typeof context.browser === 'function' ? context.browser() : null;
911
+ if (browser && typeof browser.on === 'function') {
912
+ browser.on('disconnected', () => _logLifecycle('BROWSER_DISCONNECTED', accountId));
913
+ }
914
+ } catch {}
915
+
679
916
  // Return confirmed success metadata. The backend/frontend uses this to
680
917
  // show a green toast ONLY when the browser is genuinely started and visible.
681
918
  //
@@ -683,41 +920,83 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
683
920
  // - launchPersistentContext succeeded
684
921
  // - page exists and is not closed
685
922
  // - page.bringToFront() succeeded
686
- // - on Windows: the intended Chrome process was identified and
687
- // SetForegroundWindow succeeded (or on non-Windows: bringToFront is
688
- // sufficient)
923
+ // - on Windows: a real, non-minimized top-level Chrome window was found for
924
+ // THIS exact profile (IsWindowVisible + sane window rect). A refused
925
+ // SetForegroundWindow is a FOCUS outcome and does NOT mean invisible —
926
+ // reporting it as visible:false was the false negative fixed here.
927
+ // (on non-Windows: bringToFront is sufficient)
689
928
  //
690
- // If the Windows foreground helper cannot prove the window is visible
691
- // (foregroundVerified = false), we return started:true but visible:false
929
+ // If no real window can be proven, we return started:true but visible:false
692
930
  // with an actionable error so the frontend does NOT show a green toast.
693
- if (os.platform() === 'win32' && !foregroundVerified) {
694
- // The browser launched and bringToFront succeeded, but we could not
695
- // positively verify the window is in the foreground. Return a safe
696
- // actionable message — NOT a green toast.
931
+ if (os.platform() === 'win32' && !windowState.visible) {
932
+ // The browser launched and bringToFront succeeded, but we could not find a
933
+ // real on-screen window for this profile. Return a safe actionable message
934
+ // — NOT a green toast. `reason` says which evidence was missing.
697
935
  return {
698
936
  success: true,
699
937
  accountId,
700
938
  started: true,
701
939
  visible: false,
702
940
  sessionId: accountId,
703
- error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
941
+ reason: windowState.reason,
942
+ error: 'Browser launched but no visible window could be confirmed. Check the taskbar for the Chrome window.',
943
+ cookieDiagnostics: cookieDiag,
704
944
  };
705
945
  }
706
946
 
947
+ // The window is proven present. `focused` is reported for diagnostics only —
948
+ // a window that exists on screen is visible whether or not it holds focus.
707
949
  return {
708
950
  success: true,
709
951
  accountId,
710
952
  started: true,
711
953
  visible: true,
712
954
  sessionId: accountId,
955
+ cookieDiagnostics: cookieDiag,
713
956
  };
714
957
  }
715
958
 
716
959
  async function _stopSession(accountId, lease, ws) {
717
960
  const session = activeSessions.get(accountId);
718
961
  if (!session) return { success: false, error: 'Session not found' };
719
- try { await session.context.close(); } catch {}
720
- activeSessions.delete(accountId);
962
+ // Mark BEFORE closing: context.close() fires the session's `close` listener,
963
+ // which would otherwise send its own 'stopped' frame and produce TWO
964
+ // identical lease-bound stops for one stop command (a duplicate ack the
965
+ // server had to absorb). The explicit ack below is now the single one.
966
+ session.stopping = true;
967
+ _logLifecycle('STOP_COMMAND', accountId);
968
+
969
+ // ── FAIL-CLOSED stop ───────────────────────────────────────────────────────
970
+ // A lease-bound `status: 'stopped'` means, and must ONLY ever mean, that the
971
+ // local browser context close was POSITIVELY CONFIRMED. The previous shape
972
+ // swallowed a close failure (`catch {}`) and then sent `stopped` anyway, so a
973
+ // failed close could make the backend release the durable lease while the
974
+ // browser was still alive — fail-OPEN, and the account could then be acquired
975
+ // by another device while two live browsers existed for it.
976
+ //
977
+ // Now: if the close cannot be confirmed we send NO stopped frame, keep the
978
+ // session registered, and report an explicit failure. The lease stays
979
+ // blocking/recoverable (a human/operator or recovery path resolves it), which
980
+ // is strictly safer than claiming a stop we did not observe.
981
+ try {
982
+ await session.context.close();
983
+ } catch {
984
+ // Close was NOT confirmed. Revert the deliberate-close marking so a later
985
+ // real context close (user closes the window, crash, browser disconnect) is
986
+ // reported normally by the context close listener instead of being
987
+ // suppressed as a duplicate.
988
+ session.stopping = false;
989
+ // NEVER delete an entry here. If this session is still the registered one it
990
+ // must stay (it may still be live — never erase evidence). If the map has
991
+ // been REPLACED by a newer session for this account, that replacement must
992
+ // not be evicted either. A failed close therefore touches no map state.
993
+ _logLifecycle('STOP_CLOSE_FAILED', accountId);
994
+ // Safe, generic failure: no credentials, no token, no raw driver text.
995
+ return { success: false, accountId, error: 'Browser close could not be confirmed' };
996
+ }
997
+
998
+ // Only after a confirmed close.
999
+ if (activeSessions.get(accountId) === session) activeSessions.delete(accountId);
721
1000
  // Lease-bound stop ack: the server verifies the credential and releases the
722
1001
  // durable lease. This is the only thing that completes a takeover.
723
1002
  if (ws) {
@@ -799,6 +1078,199 @@ function _discoverLegacyProfiles() {
799
1078
  return { success: true, profiles };
800
1079
  }
801
1080
 
1081
+ // ── Account cookie restoration ───────────────────────────────────────────────
1082
+ //
1083
+ // The backend stores an account's cookies as the JSON TEXT of a Playwright
1084
+ // cookie array (accounts.db.json `cookies`) and forwards that value verbatim in
1085
+ // the startSession command options — so it arrives here as a STRING.
1086
+ //
1087
+ // The original hardened runtime (index.js) parsed BOTH shapes: a JSON string
1088
+ // (with a base64-wrapped fallback) and an already-parsed array. This runtime
1089
+ // only accepted an array (`Array.isArray`) and swallowed everything else in a
1090
+ // bare `catch {}`, so every string payload was dropped silently: the browser
1091
+ // opened with no account session at all (X saw an anonymous visitor even though
1092
+ // auth_token/ct0/twid were present in the account record). Restoring the
1093
+ // hardened runtime's normalization makes both runtimes accept the same
1094
+ // payloads.
1095
+ //
1096
+ // Payloads are normalized EXACTLY as stored — domain, sameSite and every other
1097
+ // stored field are never rewritten; only fields Playwright requires are filled
1098
+ // in when absent. Injection happens BEFORE the first navigation so the very
1099
+ // first request is already authenticated.
1100
+
1101
+ /**
1102
+ * Canonicalize a sameSite value. Returns 'Strict' | 'Lax' | 'None' when the
1103
+ * value is recognized (case-insensitively), otherwise null so the caller can
1104
+ * OMIT it. Returning 'None' for an unknown value would silently relax the
1105
+ * cookie's cross-site posture AND is rejected by Playwright, whose `sameSite`
1106
+ * is an optional enum of exactly those three values.
1107
+ */
1108
+ function _canonSameSite(value) {
1109
+ if (value == null) return null;
1110
+ switch (String(value).trim().toLowerCase()) {
1111
+ case 'strict': return 'Strict';
1112
+ case 'lax': return 'Lax';
1113
+ case 'none': return 'None';
1114
+ default: return null;
1115
+ }
1116
+ }
1117
+
1118
+ // Playwright: only -1 or a positive unix timestamp up to this bound is allowed.
1119
+ const MAX_COOKIE_EXPIRES_SECONDS = 253402300799;
1120
+
1121
+ /** Playwright's expires constraint: -1, or a positive value within its bound. */
1122
+ function _validExpires(value) {
1123
+ if (value == null || value === '') return null;
1124
+ const n = Number(value);
1125
+ if (!Number.isFinite(n)) return null;
1126
+ if (n === -1) return -1;
1127
+ if (n <= 0 || n > MAX_COOKIE_EXPIRES_SECONDS) return null;
1128
+ return n;
1129
+ }
1130
+
1131
+ /** A `url` scope Playwright will accept (not about:blank, not a data: URL). */
1132
+ function _usableUrl(value) {
1133
+ if (typeof value !== 'string' || !value) return null;
1134
+ if (value === 'about:blank' || value.startsWith('data:')) return null;
1135
+ try {
1136
+ const u = new URL(value);
1137
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
1138
+ return value;
1139
+ } catch {
1140
+ return null;
1141
+ }
1142
+ }
1143
+
1144
+ /**
1145
+ * Normalize any supported cookie payload into a Playwright cookie array.
1146
+ * Supported (pre-existing) formats: a JS array, or a string containing a JSON
1147
+ * array either directly or base64-wrapped. Returns { cookies, source }.
1148
+ */
1149
+ function _normalizeCookiePayload(cookiesData) {
1150
+ let raw = null;
1151
+ let source = null;
1152
+
1153
+ if (Array.isArray(cookiesData)) {
1154
+ raw = cookiesData;
1155
+ source = 'array';
1156
+ } else if (typeof cookiesData === 'string') {
1157
+ const text = cookiesData.trim();
1158
+ if (!text) return { cookies: [], source: 'empty_string' };
1159
+ try {
1160
+ raw = JSON.parse(text);
1161
+ source = 'json_string';
1162
+ } catch {
1163
+ try {
1164
+ raw = JSON.parse(Buffer.from(text, 'base64').toString());
1165
+ source = 'base64_json';
1166
+ } catch { raw = null; }
1167
+ }
1168
+ } else if (cookiesData && typeof cookiesData === 'object') {
1169
+ // A wrapper object is NOT itself a cookie. Only an explicit `cookies`
1170
+ // array is accepted, so arbitrary objects can never become cookies.
1171
+ if (Array.isArray(cookiesData.cookies)) {
1172
+ raw = cookiesData.cookies;
1173
+ source = 'object.cookies';
1174
+ }
1175
+ }
1176
+
1177
+ if (!Array.isArray(raw)) return { cookies: [], source: source || 'unsupported' };
1178
+
1179
+ const cookies = [];
1180
+ let unrecognizedSameSite = 0;
1181
+ for (const c of raw) {
1182
+ if (!c || typeof c !== 'object') continue;
1183
+ if (typeof c.name !== 'string' || !c.name) continue;
1184
+ if (c.value == null) continue;
1185
+ const out = { name: c.name, value: String(c.value) };
1186
+
1187
+ // ── Scope: Playwright requires url XOR (domain + path) ──
1188
+ // The explicit domain/path pair wins when a record carries both (a shape
1189
+ // Playwright rejects outright).
1190
+ const hasDomain = typeof c.domain === 'string' && c.domain;
1191
+ if (hasDomain) {
1192
+ out.domain = c.domain;
1193
+ // The ONLY field this normalizer defaults, because Playwright mandates a
1194
+ // path whenever a domain is used.
1195
+ out.path = (typeof c.path === 'string' && c.path) ? c.path : '/';
1196
+ } else {
1197
+ const url = _usableUrl(c.url);
1198
+ if (!url) continue;
1199
+ out.url = url;
1200
+ }
1201
+
1202
+ // ── Optional fields: included ONLY when the stored record supplied them ──
1203
+ // Inventing secure/sameSite/httpOnly/expires would silently change how the
1204
+ // browser treats the cookie.
1205
+ const expires = _validExpires(c.expires);
1206
+ if (expires !== null) out.expires = expires;
1207
+ if (typeof c.httpOnly === 'boolean') out.httpOnly = c.httpOnly;
1208
+ if (typeof c.secure === 'boolean') out.secure = c.secure;
1209
+ if (c.sameSite != null) {
1210
+ const raw = String(c.sameSite).trim();
1211
+ if (raw) {
1212
+ const sameSite = _canonSameSite(raw);
1213
+ if (sameSite) out.sameSite = sameSite;
1214
+ else unrecognizedSameSite += 1; // omitted, never reinterpreted
1215
+ }
1216
+ }
1217
+
1218
+ cookies.push(out);
1219
+ }
1220
+ return { cookies, source: source || 'array', unrecognizedSameSite };
1221
+ }
1222
+
1223
+ /**
1224
+ * Restore account cookies into the persistent context. Never throws (a cookie
1225
+ * problem must not abort a launch), and NEVER fails silently: counts and any
1226
+ * error are returned for diagnostics and logged. Cookie VALUES are never
1227
+ * logged — only names/counts.
1228
+ */
1229
+ async function _injectCookies(context, cookiesData) {
1230
+ const diag = {
1231
+ cookiesProvided: false,
1232
+ cookieSource: null,
1233
+ cookiesParsed: 0,
1234
+ cookiesInjected: 0,
1235
+ cookieError: null,
1236
+ };
1237
+ if (cookiesData == null || cookiesData === '') return diag;
1238
+ diag.cookiesProvided = true;
1239
+
1240
+ const { cookies, source } = _normalizeCookiePayload(cookiesData);
1241
+ diag.cookieSource = source;
1242
+ diag.cookiesParsed = cookies.length;
1243
+
1244
+ if (cookies.length === 0) {
1245
+ console.log(`[session] No cookies to inject (source=${source})`);
1246
+ return diag;
1247
+ }
1248
+
1249
+ const names = cookies.map((c) => c.name);
1250
+ const authCookiePresent = names.includes('auth_token');
1251
+ const csrfCookiePresent = names.includes('ct0');
1252
+
1253
+ try {
1254
+ await context.addCookies(cookies);
1255
+ diag.cookiesInjected = cookies.length;
1256
+ console.log(`[session] Injected ${cookies.length} cookies (source=${source}) authCookiePresent=${authCookiePresent} csrfCookiePresent=${csrfCookiePresent}`);
1257
+ return diag;
1258
+ } catch (err) {
1259
+ diag.cookieError = _safeError(err);
1260
+ console.error(`[session] Cookie injection failed for ${cookies.length} cookies: ${diag.cookieError}`);
1261
+ // One malformed entry must not discard the whole set: retry individually
1262
+ // and keep every cookie Playwright does accept.
1263
+ for (const c of cookies) {
1264
+ try {
1265
+ await context.addCookies([c]);
1266
+ diag.cookiesInjected += 1;
1267
+ } catch { /* this single entry is unusable — the rest are kept */ }
1268
+ }
1269
+ console.log(`[session] Injected ${diag.cookiesInjected}/${cookies.length} cookies after per-cookie retry (authCookiePresent=${authCookiePresent})`);
1270
+ return diag;
1271
+ }
1272
+ }
1273
+
802
1274
  // ── Helpers ──────────────────────────────────────────────────────────────────
803
1275
 
804
1276
  /**
@@ -871,4 +1343,4 @@ function _safeError(err) {
871
1343
  .slice(0, 500);
872
1344
  }
873
1345
 
874
- module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider };
1346
+ module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider, _setWindowProbeProvider, _windowsWindowState, _parseWindowProbe, _selectWindowOwner, _logLifecycle };