@xkwdstore/agent 2.0.4 → 2.0.6

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,7 @@ 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.6** (Tweet/Comment/Follow confirmation-safety fixes). It is
10
10
  > NOT claimed to be published unless the release workflow has published it — see
11
11
  > `reports/` for the authoritative publication state.
12
12
 
@@ -29,7 +29,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
29
29
  The generated launcher runs the pinned command:
30
30
 
31
31
  ```powershell
32
- npx --yes @xkwdstore/agent@2.0.4 start
32
+ npx --yes @xkwdstore/agent@2.0.6 start
33
33
  ```
34
34
 
35
35
  Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
@@ -177,10 +177,10 @@ The agent does NOT update itself. To use a newer version, change the version
177
177
  number in the command. The pinned command for this release is:
178
178
 
179
179
  ```powershell
180
- npx --yes @xkwdstore/agent@2.0.4 start
180
+ npx --yes @xkwdstore/agent@2.0.6 start
181
181
  ```
182
182
 
183
- > 2.0.4 is the current local agent version (same-device lease recovery fix).
183
+ > 2.0.6 is the current local agent version (Tweet/Comment/Follow confirmation-safety fixes).
184
184
  > 2.0.3 was the previous release.
185
185
  >
186
186
  > 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.6",
4
4
  "description": "XKWDStore Agent — terminal-only, cryptographically authenticated CLI for browser automation",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
@@ -118,12 +118,19 @@ async function comment(page, payload) {
118
118
  await page.keyboard.press('Control+Enter');
119
119
  }
120
120
 
121
- // Wait for dialog to close
121
+ // Wait for the compose surface to close. The comment editor detaching is the
122
+ // ONLY reliable success signal we have; if it never closes the comment may or
123
+ // may not have been submitted, so the outcome is UNKNOWN — never report
124
+ // success (and never auto-retry, since a comment is not idempotent).
125
+ let editorDetached = false;
122
126
  try {
123
- await page.waitForSelector('div[role="dialog"]', { state: 'detached', timeout: 15000 });
127
+ await page.waitForSelector('[data-testid="tweetTextarea_0"]', { state: 'detached', timeout: 15000 });
128
+ editorDetached = true;
124
129
  } catch {
125
130
  await page.keyboard.press('Control+Enter');
126
131
  await sleep(3000);
132
+ const stillVisible = await page.locator('[data-testid="tweetTextarea_0"]').first().isVisible({ timeout: 2000 }).catch(() => false);
133
+ editorDetached = !stillVisible;
127
134
  }
128
135
 
129
136
  // Check for failure
@@ -132,6 +139,15 @@ async function comment(page, payload) {
132
139
  throw new Error('Comment submit reported a failure');
133
140
  }
134
141
 
142
+ if (!editorDetached) {
143
+ return {
144
+ success: false,
145
+ code: 'UNKNOWN_OUTCOME',
146
+ outcome: 'unknown',
147
+ error: 'Comment submit could not be confirmed (editor is still open); outcome unknown',
148
+ };
149
+ }
150
+
135
151
  return { success: true, message: 'Comment posted' };
136
152
  }
137
153
 
@@ -19,6 +19,42 @@ const FOLLOWING_LABELS = [
19
19
  'unfollow', 'dejar de seguir', 'ne plus suivre', 'entfolgen', 'إلغاء المتابعة',
20
20
  ];
21
21
 
22
+ /**
23
+ * Confirm a follow actually took effect. A click that did not throw is NOT
24
+ * evidence. We accept the standard post-follow signals (the unfollow testid or
25
+ * a Following/Unfollow control). Bounded wait; never throws.
26
+ */
27
+ const FOLLOW_CONFIRM_TIMEOUT_MS = parseInt(process.env.LOCAL_AGENT_FOLLOW_CONFIRM_TIMEOUT_MS || '8000', 10);
28
+
29
+ async function confirmFollow(page, cleanUsername) {
30
+ const deadline = Date.now() + FOLLOW_CONFIRM_TIMEOUT_MS;
31
+ while (Date.now() < deadline) {
32
+ const candidates = [
33
+ `[data-testid="${cleanUsername}-unfollow"]`,
34
+ '[data-testid="unfollow"]',
35
+ '[role="button"][aria-label*="Following"]',
36
+ '[role="button"][aria-label*="Unfollow"]',
37
+ 'button[aria-label*="Following"]',
38
+ 'button[aria-label*="Unfollow"]',
39
+ ];
40
+ for (const sel of candidates) {
41
+ const el = page.locator(sel).first();
42
+ if (await el.isVisible({ timeout: 500 }).catch(() => false)) return true;
43
+ }
44
+ await sleep(1000);
45
+ }
46
+ return false;
47
+ }
48
+
49
+ function unconfirmedFollow(cleanUsername) {
50
+ return {
51
+ success: false,
52
+ code: 'UNKNOWN_OUTCOME',
53
+ outcome: 'unknown',
54
+ error: `Follow click for @${cleanUsername} could not be confirmed; outcome unknown`,
55
+ };
56
+ }
57
+
22
58
  async function follow(page, payload) {
23
59
  const { username } = payload;
24
60
  if (!username) throw new Error('username required');
@@ -48,8 +84,10 @@ async function follow(page, payload) {
48
84
  const btn = page.locator(sel).first();
49
85
  if (await btn.isVisible({ timeout: 2000 }).catch(() => false)) {
50
86
  await humanClick(page, btn);
51
- await sleep(3000);
52
- return { success: true, message: `Following @${cleanUsername}` };
87
+ if (await confirmFollow(page, cleanUsername)) {
88
+ return { success: true, message: `Following @${cleanUsername}` };
89
+ }
90
+ return unconfirmedFollow(cleanUsername);
53
91
  }
54
92
  }
55
93
 
@@ -63,8 +101,10 @@ async function follow(page, payload) {
63
101
  // Check if it's actually "following" (already following)
64
102
  if (FOLLOWING_LABELS.some(label => text.includes(label))) continue;
65
103
  await humanClick(page, btn);
66
- await sleep(3000);
67
- return { success: true, message: `Following @${cleanUsername}` };
104
+ if (await confirmFollow(page, cleanUsername)) {
105
+ return { success: true, message: `Following @${cleanUsername}` };
106
+ }
107
+ return unconfirmedFollow(cleanUsername);
68
108
  }
69
109
  }
70
110
 
@@ -70,13 +70,20 @@ async function tweet(page, payload) {
70
70
  await page.keyboard.press('Control+Enter');
71
71
  }
72
72
 
73
- // Wait for compose box to close (success indicator)
73
+ // Wait for the compose surface to close. Detachment of the composer is the
74
+ // ONLY reliable success signal we have; if it never closes the tweet may or
75
+ // may not have been submitted, so the outcome is UNKNOWN — never report
76
+ // success (and never auto-retry, since a tweet is not idempotent).
77
+ let editorDetached = false;
74
78
  try {
75
79
  await page.waitForSelector(editorSelector, { state: 'detached', timeout: 15000 });
80
+ editorDetached = true;
76
81
  } catch {
77
82
  // Retry with Ctrl+Enter
78
83
  await page.keyboard.press('Control+Enter');
79
84
  await sleep(3000);
85
+ const stillVisible = await page.locator(editorSelector).first().isVisible({ timeout: 2000 }).catch(() => false);
86
+ editorDetached = !stillVisible;
80
87
  }
81
88
 
82
89
  // Check for failure toast
@@ -85,6 +92,15 @@ async function tweet(page, payload) {
85
92
  throw new Error('Tweet submit reported a failure toast');
86
93
  }
87
94
 
95
+ if (!editorDetached) {
96
+ return {
97
+ success: false,
98
+ code: 'UNKNOWN_OUTCOME',
99
+ outcome: 'unknown',
100
+ error: 'Tweet submit could not be confirmed (compose box is still open); outcome unknown',
101
+ };
102
+ }
103
+
88
104
  return { success: true, message: 'Tweet posted' };
89
105
  }
90
106
 
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.6';
28
28
  const PROTOCOL_VERSION = 2;
29
29
 
30
30
  // ── Command parsing ──────────────────────────────────────────────────────────
@@ -120,6 +120,11 @@ async function start(serverOrigin, flags) {
120
120
  console.error('The agent will not start enrollment until the server is compatible.');
121
121
  process.exit(1);
122
122
  }
123
+ // NOTE: the server's declared `capabilities` are INFORMATIONAL. They are
124
+ // never a reason to refuse a server — a server that does not advertise the
125
+ // profile-identity capability may still supply the identity tuple, and every
126
+ // currently-deployed backend omits the field. A missing capability must not
127
+ // block startup (see validateCompatibilityResponse).
123
128
  // compat.ok — enforce minimum agent version
124
129
  const minVer = compat.body.minimumAgentVersion;
125
130
  const recVer = compat.body.recommendedAgentVersion;
@@ -299,6 +299,26 @@ function _isHtmlResponse(data, contentType) {
299
299
  return body.startsWith('<!doctype html>') || body.startsWith('<html');
300
300
  }
301
301
 
302
+ /**
303
+ * The server capability that indicates the backend can send the complete
304
+ * immutable profile-identity tuple inside startSession.options.
305
+ *
306
+ * THIS IS INFORMATIONAL ONLY — IT MUST NEVER GATE COMPATIBILITY.
307
+ * ------------------------------------------------------------
308
+ * An earlier revision made this a hard requirement of
309
+ * validateCompatibilityResponse. That was WRONG and would have been an outage:
310
+ * every currently-deployed server (including the live production backend) and
311
+ * every currently-published agent (2.0.4, 2.0.5) treat `capabilities` as an
312
+ * unknown/extra field, so requiring it would have REFUSED servers that in fact
313
+ * work correctly. Availability has to be able to report a capability that a
314
+ * server does not yet advertise without breaking that server.
315
+ *
316
+ * The field is therefore parsed and surfaced (see `capabilities` on the returned
317
+ * object) so operator tooling can DISPLAY the difference, but its absence never
318
+ * produces { ok: false }.
319
+ */
320
+ const PROFILE_IDENTITY_CAPABILITY = 'profile-identity-v1';
321
+
302
322
  /**
303
323
  * Shared strict compatibility validator (Protocol-v2 contract).
304
324
  *
@@ -311,12 +331,20 @@ function _isHtmlResponse(data, contentType) {
311
331
  * - non-empty minimumAgentVersion
312
332
  * - non-empty recommendedAgentVersion
313
333
  *
334
+ * OPTIONAL (never a failure condition):
335
+ * - capabilities[] — parsed and returned when present, so a caller can show
336
+ * whether the server advertises the profile-identity contract. A missing or
337
+ * ill-typed value is IGNORED, not rejected: the declared capability set is
338
+ * metadata about the server, and treating absent metadata as an
339
+ * incompatibility would break servers that are perfectly usable.
340
+ *
314
341
  * Never prints the HTML body or undefined values. For HTML/SPA responses it
315
342
  * returns { ok: false, html: true } and the caller prints the exact required
316
343
  * message.
317
344
  *
318
345
  * @param {object} resp — { status, body, contentType }
319
- * @returns {object} { ok: boolean, html?: boolean, reason?: string, body?: object }
346
+ * @returns {object} { ok: boolean, html?: boolean, reason?: string, body?: object,
347
+ * capabilities: string[], hasProfileIdentityCapability: boolean }
320
348
  */
321
349
  function validateCompatibilityResponse(resp) {
322
350
  if (!resp || typeof resp !== 'object') {
@@ -348,7 +376,19 @@ function validateCompatibilityResponse(resp) {
348
376
  if (!body.recommendedAgentVersion || typeof body.recommendedAgentVersion !== 'string') {
349
377
  return { ok: false, reason: 'missing recommendedAgentVersion' };
350
378
  }
351
- return { ok: true, body };
379
+ // OPTIONAL capabilities: read for DISPLAY only. An absent, empty, or
380
+ // ill-typed value must NOT fail compatibility — a server that does not
381
+ // advertise capabilities can still be fully usable (every deployed server
382
+ // today omits it). Only well-formed string entries are surfaced.
383
+ const capabilities = Array.isArray(body.capabilities)
384
+ ? body.capabilities.filter((c) => typeof c === 'string' && c.trim()).map((c) => c.trim())
385
+ : [];
386
+ return {
387
+ ok: true,
388
+ body,
389
+ capabilities,
390
+ hasProfileIdentityCapability: capabilities.includes(PROFILE_IDENTITY_CAPABILITY),
391
+ };
352
392
  }
353
393
 
354
394
  /**
@@ -586,4 +626,5 @@ module.exports = {
586
626
  _isHtmlResponse,
587
627
  validateCompatibilityResponse,
588
628
  COMPAT_HTML_MESSAGE,
629
+ PROFILE_IDENTITY_CAPABILITY,
589
630
  };
@@ -161,6 +161,19 @@ function _windowsForegroundChrome(profileDir) {
161
161
  // Active sessions: accountId -> { context, page, profileDir }
162
162
  const activeSessions = new Map();
163
163
 
164
+ // Accounts currently LAUNCHING on this agent (String(accountId)).
165
+ //
166
+ // WHY: a startSession must never create a SECOND persistent Chrome context for
167
+ // the same profile dir. Two overlapping /start requests for one account (e.g. a
168
+ // retry fired while a slow launch is still in flight) would otherwise both pass
169
+ // the "no active session yet" check and race `launchPersistentContext` on the
170
+ // same profile — producing a profile-lock error for one of them, or two windows
171
+ // where only one is lease-bound. The server serializes start attempts per
172
+ // (account, device) in browserProviderFactory, but that guard is per-process
173
+ // state on the server and does not cover two distinct server-side attempts
174
+ // reaching the agent; the invariant belongs on the device that owns the profile.
175
+ const _startInProgress = new Set();
176
+
164
177
  // Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
165
178
  // runtime object so a newly initialized handler starts connected and does
166
179
  // NOT inherit stale state from a prior handler lifecycle. The module-level
@@ -378,6 +391,22 @@ async function _handleCommandEnvelope(ws, msg, opts) {
378
391
 
379
392
  const { type, ...rest } = command;
380
393
 
394
+ // CONTRACT: `options` must ALWAYS be a real object on the params we hand to
395
+ // the executors. It is the ONLY carrier of the immutable profile-identity
396
+ // tuple (serverUuid/tenantUuid/accountUuid/deviceUuid) and of the proxy
397
+ // policy, so a command that simply OMITS `options` must not silently degrade
398
+ // into "no options at all". Previously the executors fell back to the params
399
+ // object itself (`params.options || params`), and because `rest` spreads the
400
+ // command MINUS `type`, that fallback object can never contain serverUuid —
401
+ // so such a command failed closed with PROFILE_IDENTITY_INCOMPLETE and no
402
+ // browser ever opened, with no diagnostic pointing at the envelope. Making the
403
+ // shape unconditional keeps every executor's contract identical and makes the
404
+ // failure explicit instead of accidental. Identity is still validated
405
+ // downstream and NEVER defaulted here.
406
+ if (!rest.options || typeof rest.options !== 'object' || Array.isArray(rest.options)) {
407
+ rest.options = {};
408
+ }
409
+
381
410
  // Build the echo object from the envelope (nonce, leaseId, accountUuid).
382
411
  const echo = _extractEcho(msg);
383
412
 
@@ -442,7 +471,11 @@ async function _executeCommand(type, params, msg, opts, ws) {
442
471
  case 'runAction':
443
472
  return _runAction(accountId, params.action, params.payload || params.args);
444
473
  case 'getStatus':
445
- return _getStatus();
474
+ // Account-scoped status contract (parity with the hardened index.js path).
475
+ // Job readiness on the server uses getSessionStatus (registry), but any
476
+ // caller of the getStatus command must receive a truthful per-account
477
+ // { status:'running'|'stopped' } — never a bare sessions list.
478
+ return _getStatus(accountId);
446
479
  case 'importLegacyProfile':
447
480
  return _importLegacyProfile(accountId, accountUuid, opts);
448
481
  case 'discoverLegacyProfiles':
@@ -456,6 +489,7 @@ async function _executeCommand(type, params, msg, opts, ws) {
456
489
 
457
490
  async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
458
491
  if (!accountId) return { success: false, error: 'Missing accountId' };
492
+ const accountKey = String(accountId);
459
493
 
460
494
  // Lease-bound error reporter: a FAILED start sends a lease-bound
461
495
  // session-status 'error' so the server releases the lease it acquired for
@@ -470,46 +504,144 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
470
504
  } catch {}
471
505
  };
472
506
 
507
+ // ── ONE launch per account/profile ─────────────────────────────────────────
508
+ // A launch is already in flight for this account → refuse a SECOND concurrent
509
+ // launch (no duplicate context, no profile-lock race). Placed BEFORE any
510
+ // identity work because it mutates nothing and can answer immediately; the
511
+ // "already running" case below is checked AFTER the identity contract so a
512
+ // malformed envelope still fails closed.
513
+ //
514
+ // CRITICAL: do NOT emit a lease-bound `session-status: error` here. The server
515
+ // treats a verified lease-bound error frame as a STOP ACK and RELEASES the
516
+ // durable lease — but two server-side start attempts for one account SHARE a
517
+ // single reservation (same leaseId + credential, by design). Releasing on this
518
+ // refusal would free the reservation the FIRST, still-launching attempt owns;
519
+ // that attempt then positively starts a browser whose lease can no longer be
520
+ // activated, which is exactly the SESSION_START_LEASE_LOST inconsistency. The
521
+ // refusal is reported ONLY through the command response, leaving the durable
522
+ // lease to the attempt that owns it (its own failure path releases it, under
523
+ // the server's lifecycle-ownership guard).
524
+ if (_startInProgress.has(accountKey)) {
525
+ return {
526
+ success: false,
527
+ code: 'START_ALREADY_IN_PROGRESS',
528
+ error: 'A browser launch for this account is already in progress on this device; a second launch was not started.',
529
+ };
530
+ }
531
+ _startInProgress.add(accountKey);
532
+ try {
533
+ return await _startSessionLocked(params, opts, accountKey, accountId, accountUuid, lease, ws);
534
+ } finally {
535
+ _startInProgress.delete(accountKey);
536
+ }
537
+ }
538
+
539
+ /**
540
+ * The actual launch. Called only while this account holds the per-agent launch
541
+ * guard (see _startSession), so exactly one persistent context can be created
542
+ * for the account/profile at a time.
543
+ */
544
+ async function _startSessionLocked(params, opts, accountKey, accountId, accountUuid, lease, ws) {
545
+ // Lease-bound error reporter (see _startSession).
546
+ const _sendStartError = (error) => {
547
+ if (!ws || !lease) return;
548
+ try {
549
+ const tmp = {};
550
+ leaseClient.bind(tmp, lease);
551
+ ws.send(JSON.stringify(leaseClient.boundStatusMessage(tmp, accountId, 'error', { error })));
552
+ } catch {}
553
+ };
554
+
473
555
  const deviceMeta = opts.deviceMeta;
474
556
  // Phase 14 / schema-4: the profile identity requires ALL FOUR UUIDs
475
557
  // (server/tenant/account/device). The command's options carry the
476
558
  // server-assigned serverUuid + tenantUuid; the device UUID comes from this
477
559
  // device's metadata. Without all four, resolveProfileDir throws
478
560
  // PROFILE_IDENTITY_INCOMPLETE and no browser can ever launch.
479
- const identity = params.options || params;
480
- const serverUuid = identity.serverUuid || null;
481
- const tenantUuid = identity.tenantUuid || null;
482
- const resolvedAccountUuid = identity.accountUuid || accountUuid || null;
561
+ //
562
+ // The identity is read from `params.options` ONLY (the envelope guarantees it
563
+ // is an object). The previous `|| params` fallback was a silent trap: `params`
564
+ // spreads the command MINUS `type`, so it can never hold serverUuid, and a
565
+ // command missing `options` therefore failed closed with an error that pointed
566
+ // at the identity instead of at the malformed envelope. There is still NO
567
+ // identity fallback: absent UUIDs fail closed exactly as before.
568
+ const launchParams = (params.options && typeof params.options === 'object') ? params.options : {};
569
+ const serverUuid = launchParams.serverUuid || null;
570
+ const tenantUuid = launchParams.tenantUuid || null;
571
+ const resolvedAccountUuid = launchParams.accountUuid || accountUuid || null;
483
572
 
484
573
  // Fail closed with a clear, actionable error if the server did not send the
485
574
  // complete immutable tuple (a profile is never opened with a partial
486
- // identity).
575
+ // identity). The error carries the TYPED code so the server/UI can classify it
576
+ // as an identity-contract failure (never as a lease conflict).
487
577
  if (!serverUuid || !tenantUuid || !resolvedAccountUuid || !deviceMeta.deviceId) {
488
578
  _sendStartError('PROFILE_IDENTITY_INCOMPLETE');
489
579
  return {
490
580
  success: false,
581
+ code: 'PROFILE_IDENTITY_INCOMPLETE',
491
582
  error: 'PROFILE_IDENTITY_INCOMPLETE: the server did not provide the full profile identity (serverUuid/tenantUuid/accountUuid). Cannot open a browser profile.',
492
583
  };
493
584
  }
494
585
 
495
- const profileDir = resolveProfileDir({
496
- profilesDir: PROFILES_DIR,
497
- serverUuid,
498
- tenantUuid,
499
- accountUuid: resolvedAccountUuid,
500
- deviceUuid: deviceMeta.deviceId,
501
- }).dir;
502
-
586
+ // Phase 14 / schema-4: resolve the device-bound profile slot. The resolver is
587
+ // FAIL-CLOSED and also enforces UUID SHAPE, path containment, marker integrity
588
+ // and quarantine — so its rejection must be classified as an identity problem
589
+ // too. Previously the raw throw escaped to the generic error handler, so a
590
+ // malformed UUID surfaced as a bare message with no typed code and the server
591
+ // could not tell it apart from an ordinary failure.
592
+ let profileDir;
593
+ try {
594
+ profileDir = resolveProfileDir({
595
+ profilesDir: PROFILES_DIR,
596
+ serverUuid,
597
+ tenantUuid,
598
+ accountUuid: resolvedAccountUuid,
599
+ deviceUuid: deviceMeta.deviceId,
600
+ }).dir;
601
+ } catch (err) {
602
+ const isIdentity = err && err.code === 'PROFILE_IDENTITY_INCOMPLETE';
603
+ if (!isIdentity) throw err; // containment/marker/quarantine failures keep their own handling
604
+ _sendStartError('PROFILE_IDENTITY_INCOMPLETE');
605
+ return {
606
+ success: false,
607
+ code: 'PROFILE_IDENTITY_INCOMPLETE',
608
+ error: `PROFILE_IDENTITY_INCOMPLETE: ${(_safeError(err))}`,
609
+ };
610
+ }
503
611
  const fs = require('fs');
504
612
  if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
505
613
 
614
+ // ── Already RUNNING for this exact account/profile → adopt, do not relaunch ─
615
+ // A second `launchPersistentContext` on the same profile dir cannot succeed
616
+ // (Chrome locks it) and would race the live window. The identity contract has
617
+ // been satisfied above, so this is a well-formed start for a profile that is
618
+ // ALREADY open: report the live session truthfully and REBIND it to the lease
619
+ // this start carries, so every subsequent command/status for the account is
620
+ // verified against the CURRENT authoritative credential rather than a stale
621
+ // in-memory one from a previous reservation.
622
+ const existingSession = activeSessions.get(accountKey);
623
+ if (existingSession && existingSession.context) {
624
+ if (lease) leaseClient.bind(existingSession, lease);
625
+ // (The in-flight guard is released by _startSession's finally on return.)
626
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(existingSession, accountId, 'running'))); } catch {}
627
+ return {
628
+ success: true,
629
+ accountId,
630
+ started: true,
631
+ visible: true,
632
+ sessionId: accountKey,
633
+ alreadyRunning: true,
634
+ status: 'running',
635
+ };
636
+ }
637
+
506
638
  // fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
507
639
  // options, generator }) — matching the hardened v1 runtime call. The
508
640
  // positional form threw "paths[0] must be of type string" and aborted every
509
641
  // launch. Live operator options (mobileView/locale/userAgent/timezone) are
510
642
  // re-applied on every launch; the randomized hardware identity is persisted
511
643
  // inside the profile dir and stays stable across launches.
512
- const launchOpts = params.options || {};
644
+ const launchOpts = launchParams;
513
645
  const fingerprint = fingerprintStore.loadOrGenerate({
514
646
  profileDir,
515
647
  accountId: String(accountId),
@@ -651,9 +783,9 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
651
783
  };
652
784
  }
653
785
 
654
- const session = { context, page, profileDir, accountId, lease: null };
786
+ const session = { context, page, profileDir, accountId: accountKey, lease: null };
655
787
  if (lease) leaseClient.bind(session, lease);
656
- activeSessions.set(accountId, session);
788
+ activeSessions.set(accountKey, session);
657
789
 
658
790
  // ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
659
791
  // The server's session cache (`agent.sessions`) and the durable lease TTL
@@ -669,12 +801,10 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
669
801
 
670
802
  // A browser context closed outside our control (user closed the window,
671
803
  // crash): report the verified stop so the server releases the lease — a
672
- // dead local browser must not keep the account locked.
673
- context.on('close', () => {
674
- const closed = activeSessions.get(accountId);
675
- if (closed === session) activeSessions.delete(accountId);
676
- try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(closed || session, accountId, 'stopped'))); } catch {}
677
- });
804
+ // dead local browser must not keep the account locked. Wired through the
805
+ // shared reporter so the API stop and the context close collapse to ONE
806
+ // authoritative report per session.
807
+ _attachContextCloseReporter(context, session, accountKey, accountId, ws);
678
808
 
679
809
  // Return confirmed success metadata. The backend/frontend uses this to
680
810
  // show a green toast ONLY when the browser is genuinely started and visible.
@@ -713,75 +843,140 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
713
843
  };
714
844
  }
715
845
 
846
+ /**
847
+ * Wire the single authoritative stop reporter onto a browser context.
848
+ *
849
+ * A context 'close' happens for a manual Chrome X close, a crash, and for the
850
+ * context.close() issued by _stopSession. This listener is the ONLY report path
851
+ * for those events; _stopSession also calls _reportStoppedOnce directly so an
852
+ * API close reports even if no 'close' event arrives. Both converge on the same
853
+ * idempotent reporter, so one stop is always exactly one frame.
854
+ *
855
+ * The slot-ownership check is what makes a LATE frame safe: if the account was
856
+ * closed and reopened, the old context must not report a stop carrying the NEW
857
+ * session's credential (that would release a lease still protecting a live
858
+ * browser).
859
+ */
860
+ function _attachContextCloseReporter(context, session, accountKey, accountId, ws) {
861
+ context.on('close', () => {
862
+ const closed = activeSessions.get(accountKey);
863
+ if (closed && closed !== session) return;
864
+ if (closed === session) activeSessions.delete(accountKey);
865
+ _reportStoppedOnce(session, accountId, ws);
866
+ });
867
+ }
868
+
869
+ /**
870
+ * Report ONE verified, lease-bound `stopped` frame for a session.
871
+ *
872
+ * Both stop paths converge here: the context's own 'close' event (a manual
873
+ * Chrome X close, a crash, or the context.close() issued by _stopSession) and
874
+ * the explicit API stop. Without this guard the API path emitted TWO frames for
875
+ * one stop (the close event plus the explicit send), doubling the lifecycle
876
+ * event — and a late duplicate could land AFTER the account was reopened and
877
+ * release the NEW lease that protects a running browser.
878
+ *
879
+ * The credential is whatever the session was bound to at launch; the server
880
+ * verifies it in constant time and releases only the matching durable lease.
881
+ * Idempotent by construction: the flag lives on the session object itself, so a
882
+ * NEW session for the same account is never suppressed by a previous stop.
883
+ */
884
+ function _reportStoppedOnce(session, accountId, ws) {
885
+ if (!session || session._stopReported) return false;
886
+ session._stopReported = true;
887
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
888
+ return true;
889
+ }
890
+
716
891
  async function _stopSession(accountId, lease, ws) {
717
- const session = activeSessions.get(accountId);
892
+ // Account keys are stored as String(accountId) — normalize every lookup so a
893
+ // number/string mismatch can never make a LIVE session invisible (which would
894
+ // make a stop silently no-op and leave the browser running past its lease).
895
+ const accountKey = String(accountId);
896
+ const session = activeSessions.get(accountKey);
718
897
  if (!session) return { success: false, error: 'Session not found' };
719
898
  try { await session.context.close(); } catch {}
720
- activeSessions.delete(accountId);
899
+ activeSessions.delete(accountKey);
721
900
  // Lease-bound stop ack: the server verifies the credential and releases the
722
901
  // durable lease. This is the only thing that completes a takeover.
723
- if (ws) {
724
- try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
725
- }
902
+ //
903
+ // EXACTLY ONE logically effective stop report per session. `context.close()`
904
+ // fires the context's own 'close' handler above, and this path used to send a
905
+ // SECOND stopped frame. Both carry the same credential, and the server's
906
+ // `releaseLeaseByNumericId` is idempotent for an already-released lease — but
907
+ // two frames are two lifecycle events for one stop (and, ordered against a
908
+ // reopen, the late duplicate would hit the NEW lease). `_reportStoppedOnce`
909
+ // makes the pair collapse to exactly one authoritative report while keeping
910
+ // BOTH paths intact: a manual Chrome X close (handler above) and an API close
911
+ // both still report their stop.
912
+ if (ws) _reportStoppedOnce(session, accountId, ws);
726
913
  return { success: true, accountId, stopped: true };
727
914
  }
728
915
 
729
916
  async function _refreshSession(accountId) {
730
- const session = activeSessions.get(accountId);
917
+ const session = activeSessions.get(String(accountId));
731
918
  if (!session) return { success: false, error: 'Session not found' };
732
919
  await session.page.reload();
733
920
  return { success: true };
734
921
  }
735
922
 
736
923
  async function _navigate(accountId, url) {
737
- const session = activeSessions.get(accountId);
924
+ const session = activeSessions.get(String(accountId));
738
925
  if (!session) return { success: false, error: 'Session not found' };
739
926
  await session.page.goto(url, { waitUntil: 'domcontentloaded' });
740
927
  return { success: true };
741
928
  }
742
929
 
743
930
  async function _typeText(accountId, selector, text) {
744
- const session = activeSessions.get(accountId);
931
+ const session = activeSessions.get(String(accountId));
745
932
  if (!session) return { success: false, error: 'Session not found' };
746
933
  await session.page.locator(selector).fill(text);
747
934
  return { success: true };
748
935
  }
749
936
 
750
937
  async function _pressKey(accountId, key) {
751
- const session = activeSessions.get(accountId);
938
+ const session = activeSessions.get(String(accountId));
752
939
  if (!session) return { success: false, error: 'Session not found' };
753
940
  await session.page.keyboard.press(key);
754
941
  return { success: true };
755
942
  }
756
943
 
757
944
  async function _click(accountId, selector) {
758
- const session = activeSessions.get(accountId);
945
+ const session = activeSessions.get(String(accountId));
759
946
  if (!session) return { success: false, error: 'Session not found' };
760
947
  await session.page.locator(selector).click();
761
948
  return { success: true };
762
949
  }
763
950
 
764
951
  async function _focusSession(accountId) {
765
- const session = activeSessions.get(accountId);
952
+ const session = activeSessions.get(String(accountId));
766
953
  if (!session) return { success: false, error: 'Session not found' };
767
954
  await session.page.bringToFront();
768
955
  return { success: true };
769
956
  }
770
957
 
771
958
  async function _runAction(accountId, action, payload) {
772
- const session = activeSessions.get(accountId);
959
+ const session = activeSessions.get(String(accountId));
773
960
  if (!session) return { success: false, error: 'Session not found' };
774
961
  const { runAction } = require('./actions');
775
- const result = await runAction(session.page, action, payload || {});
776
- return { success: true, result };
962
+ // Return the ACTION result at the TOP level. The server places this value in
963
+ // the command-response `result` field and reads success/code/outcome/
964
+ // failureStage there (JobRuntime, browserProviderFactory, browser.js). Wrapping
965
+ // it as { success: true, result } made a RETURNED typed failure (notably the
966
+ // non-idempotent tweet/comment/follow UNKNOWN_OUTCOME) look like a clean
967
+ // success, because the outer `success` shadowed the inner one. Do NOT re-wrap.
968
+ return await runAction(session.page, action, payload || {});
777
969
  }
778
970
 
779
- function _getStatus() {
780
- const sessions = [];
781
- for (const [accountId, session] of activeSessions) {
782
- sessions.push({ accountId, url: session.page ? session.page.url() : null });
971
+ function _getStatus(accountId) {
972
+ const key = String(accountId || '');
973
+ const session = key ? activeSessions.get(key) : null;
974
+ if (session && session.context) {
975
+ let url = null;
976
+ try { url = session.page && !session.page.isClosed() ? session.page.url() : null; } catch { url = null; }
977
+ return { success: true, status: 'running', accountId: key, url };
783
978
  }
784
- return { success: true, sessions, count: sessions.length };
979
+ return { success: true, status: 'stopped', accountId: key || null, url: null };
785
980
  }
786
981
 
787
982
  function _importLegacyProfile(accountId, accountUuid, opts) {
@@ -871,4 +1066,4 @@ function _safeError(err) {
871
1066
  .slice(0, 500);
872
1067
  }
873
1068
 
874
- module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider };
1069
+ module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider, _attachContextCloseReporter };