synabun 2.4.6 → 2.4.7

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.
@@ -53,6 +53,10 @@ import { AGENT_PROFILES_KEY, PROFILE_NOT_ALLOWED, normalizeAgentProfiles, agentP
53
53
  import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets, logIdOf } from './lib/terminal-tokens.js';
54
54
  import { knownSecretCount } from './lib/terminal-token-redaction.js';
55
55
  import { decideFailedTabRecovery } from './lib/browser-wedge-retire.js';
56
+ import { createOwnTargetRegistry, createOwnTabCloseWatch, ownTargetProfileKey, closeOwnTargets } from './lib/browser-own-targets.js';
57
+ import { createLaunchRecovery } from './lib/morelogin-launch-recovery.js';
58
+ import { createLaunchBlockApi, launchBlockNoticeOf } from './lib/launch-block-api.js';
59
+ import { connectGuardCdp } from './lib/browser-guard-cdp.js';
56
60
  import { createSocialWritePacer, socialPaceAccountKey, socialPaceRequest, socialPacingBlock, SOCIAL_PACE_LIMITS, SOCIAL_WRITE_GAPS } from './lib/social-write-pacing.js';
57
61
  import { describeLocatorMatches, healLocatorByText, validNthMatch, captureTargetIdentity, matchesTargetIdentity } from './lib/browser-targets.js';
58
62
  import { getInteractiveHints, collectSemanticContext, buildAssist, describeTargetFacts, verifyHealTarget, createAssistContextStore } from './lib/browser-semantic-context.js';
@@ -66,7 +70,7 @@ import { runBrowserExtraction, readBrowserContentHtml } from './lib/browser-extr
66
70
  import { attachConsoleBuffer, readConsoleBuffer, parseConsoleSince } from './lib/browser-console.js';
67
71
  import { resolveBrowserLanguage, validateBrowserLanguageConfig } from './lib/browser-language.js';
68
72
  import { parseScreenshotOptions, captureScreenshot, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './lib/browser-screenshot.js';
69
- import { openBackgroundPageStrict, backgroundTabsEnabled, newContextWithId, selectedTabReading } from './lib/browser-background-tab.js';
73
+ import { openBackgroundPageStrict, backgroundTabsEnabled, newContextWithId, selectedTabReading, pageTargetId } from './lib/browser-background-tab.js';
70
74
  import { withMemoryWrite } from '../mcp-server/dist/services/sqlite-write.js';
71
75
  import { memoryRevision } from '../mcp-server/dist/services/memory-maintenance.js';
72
76
  import { startGatedMemoryMaintenance, stopGatedMemoryMaintenance } from './lib/memory-timers.js';
@@ -16539,7 +16543,9 @@ async function launchScheduledLoop(schedule) {
16539
16543
  if (scheduledUsesBrowser) {
16540
16544
  // Same serialized shared-browser + dedicated-tab acquisition as manual loops. A new firing may start a profile
16541
16545
  // closed outside SynaBun (lib/morelogin-outside-close.js): that is what the schedule is for.
16542
- const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true });
16546
+ // `launch`: what the owner's notice names when launches keep failing on the profile (lib/morelogin-launch-recovery.js).
16547
+ const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true,
16548
+ launch: group?.name ? `${schedule.name} (${group.name})` : schedule.name });
16543
16549
  if (acq.error) {
16544
16550
  throw new Error(acq.error);
16545
16551
  }
@@ -21294,6 +21300,96 @@ const _runProfileFailures = createProfileFailureStore({
21294
21300
  log: (line) => console.warn(`[morelogin] ${line}`),
21295
21301
  });
21296
21302
 
21303
+ // ── A launch that fails on its profile's browser: one restart, one retry, one notice (lib/morelogin-launch-recovery.js) ──
21304
+ // The server's own recovery for the run it is launching (acquireWithProfileRecovery), never an agent's tool: what an
21305
+ // agent may stop or start is unchanged (POST /api/morelogin/stop, /start). Outcomes go to the profile's row of
21306
+ // morelogin-profile-failures.json and to this log; the owner's pages are told once per streak (`schedule:launch-blocked`,
21307
+ // GET /api/system/launch-blocks).
21308
+ /**
21309
+ * The automations other than `ownerKey` that work in profile `envId` now: the owners of a tab or a hold in a live
21310
+ * session on it (lib/browser-session-close.js otherSessionOwners), and the runs that started it themselves and are
21311
+ * still running. While there is one, the profile is not restarted under it. A starter the server no longer knows as
21312
+ * a running run (it ended, or it was a session that left) holds nothing: its entry stays until the profile is stopped,
21313
+ * and must not keep the profile from ever being restarted.
21314
+ */
21315
+ function otherProfileHolders(envId, ownerKey) {
21316
+ const others = new Set();
21317
+ for (const session of browserSessions.values()) {
21318
+ if (!sessionServesMoreLoginEnv(session, envId)) continue;
21319
+ for (const owner of otherSessionOwners(session, ownerKey)) others.add(owner);
21320
+ }
21321
+ for (const starter of _moreLoginStartedBy.get(String(envId)) || []) {
21322
+ if (starter !== ownerKey && automationRunState(browserOwnerId(starter) || starter, { files: true }) === 'live') others.add(starter);
21323
+ }
21324
+ return [...others];
21325
+ }
21326
+ /**
21327
+ * The sessions of profile `envId` that the owner has open in SynaBun: a page watches them (`clients`: a Browser panel,
21328
+ * a terminal's browser card) and no automation other than `ownerKey` works in them. A session the owner opened from the
21329
+ * page has no owner key, so otherProfileHolders never sees it; a restart would close the tabs the owner works in
21330
+ * (review of 2026-11-29, finding 1). closeUnclaimedBrowserStart reads a watched session as in use the same way. Such a
21331
+ * session is never restarted under the owner, and nothing of it is closed on the way to that refusal: the release of a
21332
+ * session that opens no tab (acquireSharedBrowserTab `release`) runs only after the recovery decided to restart.
21333
+ */
21334
+ function ownerPageSessionsOn(envId, ownerKey) {
21335
+ const watched = [];
21336
+ for (const [id, session] of browserSessions) {
21337
+ if (!sessionServesMoreLoginEnv(session, envId)) continue;
21338
+ if ((session.clients?.size || 0) > 0 && otherSessionOwners(session, ownerKey).length === 0) watched.push(id);
21339
+ }
21340
+ return watched;
21341
+ }
21342
+ const _launchRecovery = createLaunchRecovery({
21343
+ store: _runProfileFailures,
21344
+ holders: otherProfileHolders,
21345
+ ownerSessions: ownerPageSessionsOn,
21346
+ // SynaBun's own tabs in the profile are closed right before the stop: MoreLogin would reopen a frozen one.
21347
+ closeOwnTabs: (envId) => closeRecordedTabsBeforeRestart(envId),
21348
+ startLimit: (envId) => moreLogin.listStartCooldowns().find((held) => String(held.envId) === String(envId)) || null,
21349
+ closedOutside: (envId) => moreLogin.outsideCloseFor(String(envId)),
21350
+ running: async (envId) => !!moreLogin.runningDebugPort(await moreLogin.profileStatus(envId, { ..._moreLoginOpts(), timeout: 3000 })),
21351
+ stop: (envId) => moreLogin.stopProfile(envId, _moreLoginOpts()),
21352
+ // A new scheduled firing may start a profile closed outside SynaBun (lib/morelogin-outside-close.js); nothing else may.
21353
+ start: (envId, { scheduled = false } = {}) => moreLogin.startProfile(envId, { ..._moreLoginOpts(), requireCdp: true, profileLabel: moreLoginProfileLabel,
21354
+ ...(scheduled ? { allowAfterOutsideClose: 'schedule' } : {}) }),
21355
+ // SynaBun's own stop: no session there reads it as a close by someone else, and nobody "started" what is restarted.
21356
+ stopping: (envId) => { _moreLoginStoppedBySynaBun.set(String(envId), Date.now()); _moreLoginStartedBy.delete(String(envId)); },
21357
+ describe: (envId, name) => describeProfile(String(envId), name || _moreLoginEnvNames.get(String(envId)) || null),
21358
+ // `schedule:` messages go to the owner's pages only (broadcastSync keeps them from invite guests).
21359
+ announce: (notices) => broadcastSync({ type: 'schedule:launch-blocked', notices: notices.map(launchBlockNoticeOf).filter(Boolean) }),
21360
+ log: (line) => console.warn(`[morelogin] launch recovery: ${line}`),
21361
+ newId: () => randomBytes(8).toString('hex'),
21362
+ });
21363
+ /**
21364
+ * An attachment to profile `envId` from outside its acquisition queue (createBrowserSession: an agent's
21365
+ * browser_session create, POST /api/browser/sessions, the owner's page) while the launch recovery restarts it: it waits
21366
+ * for the restart (RESTART_ATTACH_WAIT_MS at most) and goes on, or is refused with MORELOGIN_PROFILE_RESTARTING. The
21367
+ * recovery's own retry comes after the restart and never waits here. Review of e8937e79, N1.
21368
+ */
21369
+ async function waitOutProfileRestart(envId) {
21370
+ const id = envId === null || envId === undefined ? '' : String(envId);
21371
+ if (!id || !_launchRecovery.restarting?.(id)) return;
21372
+ console.warn(`[morelogin] ${describeProfile(id, _moreLoginEnvNames.get(id) || null)} is being restarted by SynaBun: an attachment to it waits for the restart`);
21373
+ const started = Date.now();
21374
+ if (await _launchRecovery.whenRestarted(id)) return;
21375
+ throw _launchRecovery.restartingError(id, { name: _moreLoginEnvNames.get(id) || null, waitedMs: Date.now() - started });
21376
+ }
21377
+ /** A new tab in a session of a profile the launch recovery restarts is refused at once: the stop ends that session. */
21378
+ function profileRestartRefusal(session) {
21379
+ const id = session?._profileMode === 'morelogin' && session._mlEnvId ? String(session._mlEnvId) : '';
21380
+ return id && _launchRecovery.restarting?.(id) ? _launchRecovery.restartingError(id, { name: _moreLoginEnvNames.get(id) || null }) : null;
21381
+ }
21382
+
21383
+ // The notice the owner's pages show when launches keep failing on a profile (lib/launch-block-api.js,
21384
+ // public/shared/ui-launch-block-notice.js): asked when a page loads and when its sync socket connects.
21385
+ app.use('/api/system/launch-blocks', createLaunchBlockApi({
21386
+ recovery: () => _launchRecovery,
21387
+ guard: ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true }),
21388
+ // The dismissal carries this boot's page secret, as the crash notice's does (lib/page-session.js).
21389
+ pageSession: _pageSession,
21390
+ log: (line) => console.log(line),
21391
+ }));
21392
+
21297
21393
  /**
21298
21394
  * The owners of the saved choices are retired when the server starts (called once, as it starts listening, before any
21299
21395
  * request is answered): their ids are refused until their owner registers again (a side panel's new token, a brain's
@@ -33958,7 +34054,7 @@ async function findReusableBrowserSession(opts = {}) {
33958
34054
  return { id, session };
33959
34055
  } catch (error) {
33960
34056
  console.warn(`[browser] Existing session ${id} context is dead — destroying (${error.message})`);
33961
- await destroyBrowserSession(id).catch(() => {});
34057
+ await destroyBrowserSession(id, { retireOwnTabs: true }).catch(() => {});
33962
34058
  }
33963
34059
  }
33964
34060
  return null;
@@ -34047,17 +34143,20 @@ function loopBrowserLockKey(ownerKey, requestedBrowserSessionId, cfg) {
34047
34143
  *
34048
34144
  * Returns { browserSessionId, browserTabId } on success, or { error } on failure.
34049
34145
  */
34050
- async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
34146
+ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false, launch = null }) {
34051
34147
  if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
34052
34148
  // takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
34053
34149
  try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
34054
34150
  catch (error) { return extensionAdapter.describeError(error); }
34055
34151
  }
34056
34152
  const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
34057
- const acquired = await withLoopBrowserLock(lockKey, async () => {
34153
+ const acquired = await withLoopBrowserLock(lockKey, () => {
34058
34154
  // The browser this owner gets changed while it waited (the owner's settings, a requested session that went away):
34059
34155
  // it queues again for the right one, outside this turn.
34060
34156
  if (loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig()) !== lockKey) return { requeue: true };
34157
+ // One attempt: strategies 0 to 2 and the owner's tab. A failure on the profile's own browser carries `_launch`
34158
+ // (the profile and what failed), which acquireWithProfileRecovery reads to restart the profile and try once more.
34159
+ const attempt = async ({ onlyEnvId = null } = {}) => {
34061
34160
  let browserSessionId = null;
34062
34161
  let browserTabId = null;
34063
34162
  const ownerProp = ownerType === 'interactive' ? '_interactiveOwned' : '_loopOwned';
@@ -34077,6 +34176,19 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34077
34176
  loopLog(ownerKey, logTag, 'ABORT: the run\'s MoreLogin profile is not on the owner\'s list of profiles agents may choose', { envId: pin.envId });
34078
34177
  return { error: pinRefused.error, code: pinRefused.code };
34079
34178
  }
34179
+ // The retry after a restart (acquireWithProfileRecovery `onlyEnvId`) runs in the profile that was restarted and in
34180
+ // no other: when the owner moved the run, or changed the default profile, during the restart, it is not tried again
34181
+ // at all (never another profile), and the launch that failed stays counted on the profile it ran on.
34182
+ if (onlyEnvId) {
34183
+ const runsOn = pin ? String(pin.envId) : (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? String(moreLoginDefaultEnvId(policyCfg)) : null);
34184
+ if (runsOn !== String(onlyEnvId)) {
34185
+ loopLog(ownerKey, logTag, 'ABORT: the run\'s profile changed during the restart: the launch is not tried again in another profile', { restarted: String(onlyEnvId), now: runsOn });
34186
+ return {
34187
+ error: `The run's browser profile changed while SynaBun restarted ${describeProfile(String(onlyEnvId), _moreLoginEnvNames.get(String(onlyEnvId)) || null)} for it${runsOn ? ` (it is ${describeProfile(runsOn, _moreLoginEnvNames.get(runsOn) || null)} now)` : ''}: the launch was not tried again, because a retry runs only in the profile that was restarted. Its next launch runs in its profile as it is now.`,
34188
+ code: 'PROFILE_CHANGED_DURING_RESTART', _launch: { envId: String(onlyEnvId), profileChanged: true },
34189
+ };
34190
+ }
34191
+ }
34080
34192
  if (requestedBrowserSessionId) {
34081
34193
  const requested = browserSessions.get(requestedBrowserSessionId);
34082
34194
  const unfit = requested && !sessionServesRun(requested, policyCfg, ownerKey);
@@ -34092,7 +34204,10 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34092
34204
  loopLog(ownerKey, logTag, 'strategy 0: pinned to requested browser', { browserSessionId });
34093
34205
  } catch (err) {
34094
34206
  loopLog(ownerKey, logTag, 'strategy 0 failed: requested browser unhealthy — destroying', { requestedBrowserSessionId, err: err.message });
34095
- await destroyBrowserSession(requestedBrowserSessionId).catch(() => {});
34207
+ // Only its current tab was asked: other runs' tabs may still be working (an upload under way), so only this
34208
+ // caller's tabs and the ones nobody owns are closed (retireFor); the others stay open, as before 2026-11-29
34209
+ // (review of 2026-11-29, finding 3).
34210
+ await destroyBrowserSession(requestedBrowserSessionId, { retireOwnTabs: true, retireFor: ownerKey }).catch(() => {});
34096
34211
  }
34097
34212
  } else {
34098
34213
  loopLog(ownerKey, logTag, 'strategy 0 skipped: requested browser not in registry', { requestedBrowserSessionId });
@@ -34155,8 +34270,11 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34155
34270
  // it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
34156
34271
  // profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
34157
34272
  let profileAdvice = '';
34273
+ // What acquireWithProfileRecovery reads: the profile that failed and how.
34274
+ let _launch = null;
34158
34275
  if (createError) {
34159
34276
  const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
34277
+ if (own) _launch = { envId: String(own.envId), name: own.name || _moreLoginEnvNames.get(String(own.envId)) || null, failure: createError };
34160
34278
  noteRunProfileFailure(ownerKey, own, createError);
34161
34279
  if (own && !createError.code) {
34162
34280
  profileAdvice = await stoppedProfileAdvice(own.envId, own.name || _moreLoginEnvNames.get(own.envId),
@@ -34188,6 +34306,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34188
34306
  ...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
34189
34307
  ...(createError?.needsUser ? { needsUser: true } : {}),
34190
34308
  ...(createError?.resetAt ? { resetAt: createError.resetAt } : {}),
34309
+ ...(_launch ? { _launch } : {}),
34191
34310
  };
34192
34311
  }
34193
34312
 
@@ -34252,7 +34371,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34252
34371
  } catch (err) {
34253
34372
  claimedSession?.[ownerProp]?.delete(ownerKey);
34254
34373
  loopLog(ownerKey, logTag, 'ABORT: could not create tab', { err: err.message, browserSessionId });
34255
- return { error: `Could not create a new browser tab: ${err.message}` };
34374
+ // A profile's browser that opens no tab: the recovery may restart it, after this session (which nobody else
34375
+ // works in then) has let go of it.
34376
+ const tabless = claimedSession._profileMode === 'morelogin' && claimedSession._mlEnvId ? {
34377
+ envId: String(claimedSession._mlEnvId), name: pin?.name || _moreLoginEnvNames.get(String(claimedSession._mlEnvId)) || null,
34378
+ failure: { error: err.message, ...(err.code ? { code: err.code } : {}) },
34379
+ release: () => destroyBrowserSession(browserSessionId, { retireOwnTabs: true }),
34380
+ } : null;
34381
+ return { error: `Could not create a new browser tab: ${err.message}`, ...(tabless ? { _launch: tabless } : {}) };
34256
34382
  }
34257
34383
 
34258
34384
  // Record ownerKey → tabId so getTargetPage() can route a tab-less call from this
@@ -34284,9 +34410,65 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
34284
34410
 
34285
34411
  // Connected to its profile: a failure of that profile noted earlier in this run is over (it may switch again).
34286
34412
  if (claimedSession._mlEnvId) noteRunProfileConnected(ownerKey, claimedSession._mlEnvId);
34287
- return { browserSessionId, browserTabId };
34413
+ return { browserSessionId, browserTabId, ...(claimedSession._mlEnvId ? { _launch: { envId: String(claimedSession._mlEnvId) } } : {}) };
34414
+ };
34415
+ return acquireWithProfileRecovery({ attempt, ownerKey, ownerType, logTag, scheduledFiring, launch, lockKey });
34288
34416
  });
34289
- return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring }) : acquired;
34417
+ return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring, launch }) : acquired;
34418
+ }
34419
+
34420
+ /**
34421
+ * One acquisition of a run's browser tab with the profile's own recovery (lib/morelogin-launch-recovery.js), inside
34422
+ * the profile's acquisition queue. `attempt()` is the acquisition itself; what it answers carries `_launch` (never
34423
+ * returned): the profile it ran in ({ envId }), and for a failure on that profile's browser also its name, what
34424
+ * failed (`failure`) and what must let go of the browser before a restart (`release`).
34425
+ *
34426
+ * A loop's acquisition (a scheduled launch, a loop launch, a run's recovery or create) that failed because the
34427
+ * network guard timed out or the profile's browser does not answer: the profile is stopped and started through
34428
+ * MoreLogin's local API (a local profile through its launcher) and the acquisition is tried ONCE more, unless another
34429
+ * automation holds a tab there, MoreLogin holds its start, or it was restarted recently; then the run fails with that
34430
+ * reason. A second failure fails the run. Never another profile, never Chrome, never the extension: both attempts are
34431
+ * the same acquisition, for the same profile. Every failed launch on a profile counts towards the owner's one notice;
34432
+ * a launch that works ends the count.
34433
+ */
34434
+ async function acquireWithProfileRecovery({ attempt, ownerKey, ownerType = 'loop', logTag = 'launch:browser', scheduledFiring = false, launch = null, lockKey = null }) {
34435
+ const bare = (result) => { if (result && typeof result === 'object') delete result._launch; return result; };
34436
+ let result = await attempt();
34437
+ let info = result?._launch || null;
34438
+ if (!result || result.requeue || !info?.envId) return bare(result);
34439
+ // The restart and the retry happen in the queue of the profile that failed (or the whole registry's): a failure of
34440
+ // another profile than the one whose queue this acquisition holds is never restarted from here.
34441
+ const inItsQueue = lockKey === null || lockKey === `ml:${info.envId}`;
34442
+ if (ownerType === 'loop' && result.error && info.failure && inItsQueue) {
34443
+ const recovery = await _launchRecovery.attempt({ ownerKey, envId: info.envId, name: info.name || null, failure: info.failure, scheduled: scheduledFiring === true, beforeStop: info.release || null });
34444
+ if (recovery.restarted) {
34445
+ loopLog(ownerKey, logTag, 'the profile was restarted to clear the failure: trying the acquisition once more', { envId: info.envId, kind: recovery.kind });
34446
+ // Only in the profile that was restarted (`onlyEnvId`): the owner may have changed the run's profile meanwhile.
34447
+ const retried = await attempt({ onlyEnvId: info.envId });
34448
+ if (!retried || retried.requeue) return bare(retried);
34449
+ if (retried._launch?.profileChanged) {
34450
+ // Not tried: the restart's own outcome stays as it is, and the failed launch counts on the profile it ran on.
34451
+ result.error = `${result.error} ${retried.error}`;
34452
+ result.code = retried.code;
34453
+ loopLog(ownerKey, logTag, 'the run\'s profile changed during the restart: no retry, the run fails', { envId: info.envId });
34454
+ } else {
34455
+ // Where the retry ran (its session's profile, which the attempt holds to `onlyEnvId`).
34456
+ const ranOn = retried._launch?.envId ? String(retried._launch.envId) : info.envId;
34457
+ const sentence = _launchRecovery.settled({ envId: info.envId, name: info.name || null, ownerKey, ok: !retried.error && ranOn === info.envId, error: retried._launch?.failure?.error || retried.error || null });
34458
+ if (retried.error && sentence) retried.error = `${retried.error} ${sentence}`;
34459
+ loopLog(ownerKey, logTag, retried.error ? 'the acquisition failed again after the restart: the run fails (no second restart)' : 'the acquisition works after the restart', { envId: ranOn });
34460
+ result = retried;
34461
+ info = { ...info, ...(retried._launch || {}), envId: ranOn };
34462
+ }
34463
+ } else if (recovery.kind) {
34464
+ loopLog(ownerKey, logTag, `the profile was not restarted (${recovery.reason})`, { envId: info.envId, kind: recovery.kind });
34465
+ if (recovery.sentence) result.error = `${result.error} ${recovery.sentence}`;
34466
+ if (recovery.needsUser) result.needsUser = true;
34467
+ }
34468
+ }
34469
+ if (!result.error) _launchRecovery.launchSucceeded(info.envId);
34470
+ else if (ownerType === 'loop' && info.failure) _launchRecovery.launchFailed({ envId: info.envId, name: info.name || null, failure: info.failure, launch });
34471
+ return bare(result);
34290
34472
  }
34291
34473
 
34292
34474
  /**
@@ -34330,8 +34512,8 @@ function moreLoginProfileLabel(envId, name = null) {
34330
34512
  * Backward-compatible loop wrapper around acquireSharedBrowserTab. Existing callers
34331
34513
  * pass { terminalSessionId } and expect loop-owned semantics.
34332
34514
  */
34333
- async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
34334
- return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring });
34515
+ async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false, launch = null }) {
34516
+ return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring, launch });
34335
34517
  }
34336
34518
 
34337
34519
  /**
@@ -36137,6 +36319,9 @@ async function createBrowserSession(options = {}) {
36137
36319
  const def = await moreLogin.ensureDefaultProfile(mlOpts);
36138
36320
  envId = def.id;
36139
36321
  }
36322
+ // SynaBun is restarting this profile to clear a launch that failed on it: its stop would cut this attachment
36323
+ // off. It waits for the restart, then goes on (or is refused with MORELOGIN_PROFILE_RESTARTING).
36324
+ await waitOutProfileRestart(envId);
36140
36325
  // requireCdp: a Firefox-type profile has no DevTools endpoint and is refused, before it is started when
36141
36326
  // MoreLogin says what it is up front.
36142
36327
  nativePreflightProfiles.add(String(envId));
@@ -36168,6 +36353,9 @@ async function createBrowserSession(options = {}) {
36168
36353
  attached = await moreLogin.attachProfileBrowser(
36169
36354
  chromium, endpoint,
36170
36355
  (cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
36356
+ // Whose a tab is, for a page of this profile that never answers the network guard (an orphan tab of
36357
+ // SynaBun's is closed, every other one fails the session closed).
36358
+ ownTargetGuardOptions(envId),
36171
36359
  ); // fresh tab in the real profile; never substitute an incognito context
36172
36360
  } catch (attachError) {
36173
36361
  // MoreLogin lists the profile running, but its browser holds no profile (its window was closed and the
@@ -36182,6 +36370,8 @@ async function createBrowserSession(options = {}) {
36182
36370
  }
36183
36371
  }
36184
36372
  const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = attached;
36373
+ // This first tab is SynaBun's own in that profile's browser, known by its target id from now on.
36374
+ await adoptProfileBrowser(envId, cdpBrowser, cdpContext, cdpPage);
36185
36375
  // A local profile's timezone on this first tab (every later tab gets it in newSessionPage, from the session).
36186
36376
  if (_localProfileInfo?.timezone) await applyPageTimezone(cdpContext, cdpPage, _localProfileInfo.timezone);
36187
36377
 
@@ -36884,6 +37074,8 @@ async function newSessionPage(session, { timeoutMs } = {}) {
36884
37074
  page = await session.context.newPage();
36885
37075
  }
36886
37076
  synabunOpenedPages.add(page);
37077
+ // Its DevTools target id is kept too, for a browser that outlives the session (noteOwnTab).
37078
+ await noteOwnTab(session, page);
36887
37079
  // A local profile's timezone (lib/local-profiles.js). Its Chrome is started with TZ, which Chrome on Windows does
36888
37080
  // not read: the tabs SynaBun opens there are told over DevTools too. The CDP session stays with the page (the
36889
37081
  // override ends when it detaches). Best effort: a tab without it still has the timezone of the profile's start.
@@ -36913,6 +37105,9 @@ const synabunOpenedPages = new WeakSet();
36913
37105
  * Returns { tabId, url, title }.
36914
37106
  */
36915
37107
  async function createSessionTab(session, sessionId, url = 'about:blank') {
37108
+ // A session of a profile SynaBun is restarting ends with the stop: no new tab is opened in it meanwhile.
37109
+ const restarting = profileRestartRefusal(session);
37110
+ if (restarting) throw restarting;
36916
37111
  const tabId = randomBytes(4).toString('hex');
36917
37112
  const activeEntry = session.tabs?.get(session.activeTabId);
36918
37113
  const shouldAdoptAsActive = !activeEntry || activeEntry.page?.isClosed?.();
@@ -37075,8 +37270,13 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
37075
37270
  console.warn(`[browser] Failed during ${recoveryStage} for tab ${tabId} in session ${sessionId}: ${error.message}`);
37076
37271
  // One slow tab does not end the other runs' tabs (lib/browser-wedge-retire.js): while the session's other
37077
37272
  // tabs still answer, only this tab is retired; its owner's next call gets "Tab not found" and a new tab.
37273
+ // Its tabs are closed with the session only when that probe found nothing in it that answers: a session retired
37274
+ // without the probe (the tab changed meanwhile) or after a probe that found tabs answering only disconnects, as
37275
+ // before 2026-11-29, so another run's working tab is never closed (review of 2026-11-29).
37276
+ let nothingAnswers = false;
37078
37277
  if (!session._invalidating && browserSessions.get(sessionId) === session && session.tabs.get(tabId)?.page === oldPage) {
37079
37278
  const verdict = await decideFailedTabRecovery(session, tabId);
37279
+ nothingAnswers = verdict.action === 'retire-session';
37080
37280
  if (verdict.action === 'retire-tab' && !session._invalidating && browserSessions.get(sessionId) === session
37081
37281
  && session.tabs.get(tabId)?.page === oldPage) {
37082
37282
  unrouteScreenshotTab(session, sessionId, tabId, oldPage);
@@ -37096,7 +37296,9 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
37096
37296
  // destroyBrowserSession removes the registry entry synchronously before
37097
37297
  // its first await. The next pinned MCP call will therefore use the
37098
37298
  // existing /api/loop/recover-browser path instead of reusing this context.
37099
- void destroyBrowserSession(sessionId).catch((destroyError) => {
37299
+ // Its own tabs go with it when nothing in it answers (retireOwnTabs): a tab that froze is closed, not left in
37300
+ // the browser.
37301
+ void destroyBrowserSession(sessionId, { retireOwnTabs: nothingAnswers }).catch((destroyError) => {
37100
37302
  console.warn(`[browser] Failed to retire invalidated session ${sessionId}: ${destroyError.message}`);
37101
37303
  });
37102
37304
  }
@@ -37271,6 +37473,8 @@ async function closeSessionTab(session, sessionId, tabId) {
37271
37473
 
37272
37474
  // Close the page, whatever the switch did: the tab has left the registry already
37273
37475
  try { await tabEntry.page.close(); } catch {}
37476
+ // A tab SynaBun recorded as its own leaves that record once its browser no longer lists it (noteOwnTabClosed).
37477
+ noteOwnTabClosed(session, tabEntry.page);
37274
37478
  console.log(`[browser] Tab ${tabId} closed in session ${sessionId} (remaining: ${session.tabs.size})`);
37275
37479
  if (switchError) throw switchError;
37276
37480
  }
@@ -37282,10 +37486,18 @@ async function closeSessionTab(session, sessionId, tabId) {
37282
37486
  * their Chrome over CDP) the tabs SynaBun opened for the session are closed
37283
37487
  * before the disconnect, `closingPage` (a last tab that has left the registry
37284
37488
  * already) included. Every other connect mode closes its whole browser anyway
37285
- * and is unchanged, and so is every other teardown (a dead or invalidated
37286
- * session, an idle or grace reap).
37489
+ * and is unchanged, and so is every other teardown (an idle or grace reap).
37490
+ * `retireOwnTabs` marks a session retired because it stopped answering (a
37491
+ * wedged tab whose session has nothing left that answers, a requested or
37492
+ * reusable session found dead): in a browser the user owns its own tabs are
37493
+ * closed by their DevTools target id, over a browser-level connection
37494
+ * (retireSessionOwnTabs), so a frozen tab is not left behind for the next
37495
+ * launch on that browser to trip over. `retireFor` (an owner key, or null for
37496
+ * the owner's page) narrows that to the tabs of that owner and the ones nobody
37497
+ * owns, for a retirement decided on one tab alone: another run's tabs stay
37498
+ * open, as they did before 2026-11-29 (retireSessionOwnTabs).
37287
37499
  */
37288
- async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null } = {}) {
37500
+ async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null, retireOwnTabs = false, retireFor = undefined } = {}) {
37289
37501
  const session = browserSessions.get(sessionId);
37290
37502
  if (session?._profileMode === 'extension') return extensionAdapter.destroy(sessionId);
37291
37503
  if (!session) return;
@@ -37297,7 +37509,10 @@ async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingP
37297
37509
  engagementScheduler.clear(sessionId);
37298
37510
  // From here on the tabs this close takes leave quietly: their close handlers switch to no
37299
37511
  // other tab and announce nothing, and a call that fails on one of them opens no replacement.
37300
- if (closeOwnTabs && (session._profileMode === 'cdp' || session._profileMode === 'morelogin') && !session._chromeProcess) {
37512
+ const userOwnedBrowser = (session._profileMode === 'cdp' || session._profileMode === 'morelogin') && !session._chromeProcess;
37513
+ // A retired session's own tabs are closed by target id (below); they leave as quietly as an explicit close's.
37514
+ const retiring = !closeOwnTabs && retireOwnTabs && userOwnedBrowser;
37515
+ if ((closeOwnTabs || retiring) && userOwnedBrowser) {
37301
37516
  session._tearingDown = true;
37302
37517
  }
37303
37518
 
@@ -37325,7 +37540,8 @@ async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingP
37325
37540
  // transport; it does not terminate the externally-owned Chromium process, and
37326
37541
  // every tab stays open (MoreLogin reopens them all at the profile's next start).
37327
37542
  // An explicit close therefore first closes the tabs SynaBun opened for the session.
37328
- if (session._tearingDown) await closeOwnTabsBeforeDisconnect(session, sessionId, closingPage);
37543
+ if (retiring) await retireSessionOwnTabs(session, sessionId, retireFor === undefined ? {} : { forOwner: retireFor });
37544
+ else if (session._tearingDown) await closeOwnTabsBeforeDisconnect(session, sessionId, closingPage);
37329
37545
  try { await session.browser.close(); } catch {}
37330
37546
  } else if (session._chromeProcess) {
37331
37547
  // Spawned Chrome process: disconnect Playwright, then kill Chrome
@@ -37399,8 +37615,14 @@ function closeOwnTabsBeforeDisconnect(session, sessionId, closingPage = null) {
37399
37615
  3_000,
37400
37616
  page === keep ? 'Emptying the last tab of the browser' : 'Closing a tab SynaBun opened',
37401
37617
  ).catch(() => {})));
37402
- const closed = own.filter((page) => page !== keep && page.isClosed?.()).length;
37618
+ const closedPages = own.filter((page) => page !== keep && page.isClosed?.());
37619
+ const closed = closedPages.length;
37403
37620
  const open = own.length - closed - (keep ? 1 : 0);
37621
+ // The records of the closed ones go now, while this connection can still ask the browser (bounded; what it
37622
+ // cannot confirm stays until the next attachment to that browser prunes it).
37623
+ if (closedPages.map((page) => noteOwnTabClosed(session, page)).some(Boolean)) {
37624
+ await withBrowserOperationDeadline(_ownTabCloses.confirm(ownTabBrowserOf(session, closedPages[0])), 2_500, 'Confirming the closed tabs').catch(() => {});
37625
+ }
37404
37626
  console.log(`[browser] Closed ${closed} tab(s) SynaBun opened in session ${sessionId} before disconnecting`
37405
37627
  + `${keep ? '; the last page of the browser was emptied (about:blank) instead' : ''}`
37406
37628
  + `${open ? `; ${open} not confirmed closed, may still be open` : ''}`);
@@ -37442,6 +37664,192 @@ async function otherOpenPageCount(session, own) {
37442
37664
  }
37443
37665
  }
37444
37666
 
37667
+ // ── The tabs SynaBun opened (synabunOpenedPages), by DevTools target id (lib/browser-own-targets.js) ──
37668
+ // For a browser that outlives its session. A Playwright page is gone with its session's connection; the tab is not.
37669
+ // The target id is what tells later, on a new connection or after a restart of the server, that a tab is SynaBun's
37670
+ // own: the network guard closes such a tab when it froze and no live session works in it (ownTargetGuardOptions), and
37671
+ // a session retired because it stopped answering closes its own tabs by it (retireSessionOwnTabs). Never a tab that
37672
+ // is not in here.
37673
+ const _ownTargets = createOwnTargetRegistry({
37674
+ file: resolve(LOOP_DATA_DIR, 'browser-own-targets.json'),
37675
+ log: (line) => console.warn(`[browser] ${line}`),
37676
+ // In use: a tab of a session that is still registered (a retired session left the registry before anything else).
37677
+ inUse: (page) => {
37678
+ for (const session of browserSessions.values()) {
37679
+ for (const entry of session.tabs?.values?.() || []) if (entry?.page === page) return true;
37680
+ }
37681
+ return false;
37682
+ },
37683
+ });
37684
+
37685
+ /**
37686
+ * Records the tab `page` as SynaBun's own in the browser `session` drives (a MoreLogin or local profile by its id,
37687
+ * the attached Chrome), by its DevTools target id. Best effort and bounded: a tab whose id could not be read is
37688
+ * never closed by its id later. Launched browsers end with their session and are not recorded.
37689
+ */
37690
+ async function noteOwnTab(session, page) {
37691
+ const key = ownTargetProfileKey({ profileMode: session?._profileMode, envId: session?._mlEnvId });
37692
+ if (!key || !page) return null;
37693
+ try {
37694
+ const targetId = await pageTargetId(session.context, page);
37695
+ if (targetId) {
37696
+ _ownTargets.note(key, targetId, { page });
37697
+ // Closed by anyone (the owner, the page itself, a close of SynaBun's): forgotten once its browser no longer lists
37698
+ // it. The page's close event alone is not enough: it also comes when the connection to the browser ends.
37699
+ const browser = ownTabBrowserOf(session, page);
37700
+ if (typeof page.once === 'function') page.once('close', () => { _ownTabCloses.seen(key, targetId, browser); });
37701
+ }
37702
+ return targetId || null;
37703
+ } catch { return null; }
37704
+ }
37705
+
37706
+ /** The Playwright browser a session's tab lives in: the connection its close is checked over. */
37707
+ function ownTabBrowserOf(session, page) {
37708
+ try { return session?.browser || session?.context?.browser?.() || page?.context?.()?.browser?.() || null; } catch { return null; }
37709
+ }
37710
+
37711
+ /**
37712
+ * The targets the browser `browser` has now, asked over its own Playwright connection (it is the browser the tab was
37713
+ * opened in), or null when it cannot be asked: disconnected, or no answer within `timeoutMs` per step.
37714
+ */
37715
+ async function listBrowserTargetIds(browser, { timeoutMs = 2_000 } = {}) {
37716
+ if (!browser || typeof browser.newBrowserCDPSession !== 'function' || browser.isConnected?.() === false) return null;
37717
+ let cdp = null;
37718
+ try {
37719
+ cdp = await withBrowserOperationDeadline(browser.newBrowserCDPSession(), timeoutMs, 'Opening a browser CDP session', { onLateResolve: (late) => late?.detach?.() });
37720
+ const { targetInfos = [] } = await withBrowserOperationDeadline(cdp.send('Target.getTargets'), timeoutMs, 'Listing the tabs of the browser');
37721
+ return targetInfos.map((target) => target.targetId);
37722
+ } catch { return null; } finally { if (cdp) cdp.detach().catch(() => {}); }
37723
+ }
37724
+
37725
+ // A recorded tab that was closed leaves the registry once its browser confirms it (lib/browser-own-targets.js
37726
+ // createOwnTabCloseWatch). A MoreLogin session is never reaped for idleness and lives for hours while loops open and
37727
+ // close tabs in it: without this, each closed tab stayed in browser-own-targets.json and in the page map until the
37728
+ // next new attachment to the profile, and a restart's close asked for tabs long gone.
37729
+ const _ownTabCloses = createOwnTabCloseWatch({
37730
+ registry: _ownTargets,
37731
+ list: (browser) => listBrowserTargetIds(browser),
37732
+ log: (line) => console.warn(`[browser] ${line}`),
37733
+ });
37734
+
37735
+ /** SynaBun closed the tab `page` of `session`: its entry goes once the browser no longer lists it. */
37736
+ function noteOwnTabClosed(session, page) {
37737
+ const key = ownTargetProfileKey({ profileMode: session?._profileMode, envId: session?._mlEnvId });
37738
+ const targetId = key && page ? _ownTargets.targetIdOf(page) : null;
37739
+ return targetId ? _ownTabCloses.seen(key, targetId, ownTabBrowserOf(session, page)) : false;
37740
+ }
37741
+
37742
+ /**
37743
+ * What the network guard of profile `envId` is told about a page whose target never answers
37744
+ * (lib/browser-network-guard.js registerBrowserNetworkEndpoint): whose tab it is, and that an orphan was closed.
37745
+ */
37746
+ function ownTargetGuardOptions(envId) {
37747
+ const key = ownTargetProfileKey({ profileMode: 'morelogin', envId });
37748
+ return {
37749
+ pageOwner: (targetInfo) => _ownTargets.classify(key, targetInfo?.targetId),
37750
+ onOrphanClosed: (targetInfo) => {
37751
+ _ownTargets.forget(targetInfo?.targetId);
37752
+ console.warn(`[browser] ${describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || null)}: closed a frozen tab SynaBun had opened for a session that ended (target ${targetInfo?.targetId}); the profile's network protection could not be installed while it was open`);
37753
+ },
37754
+ };
37755
+ }
37756
+
37757
+ /**
37758
+ * SynaBun attached to the browser of profile `envId`: its first tab there is recorded as its own, and the tabs
37759
+ * recorded for that profile that its browser no longer has are forgotten (the profile was restarted since, or they
37760
+ * were closed). The second part runs on its own and never holds the session up.
37761
+ */
37762
+ async function adoptProfileBrowser(envId, browser, context, page) {
37763
+ const key = ownTargetProfileKey({ profileMode: 'morelogin', envId });
37764
+ await noteOwnTab({ context, _profileMode: 'morelogin', _mlEnvId: String(envId) }, page);
37765
+ void (async () => {
37766
+ let cdp = null;
37767
+ try {
37768
+ cdp = await withBrowserOperationDeadline(browser.newBrowserCDPSession(), 2_000, 'Opening a browser CDP session', { onLateResolve: (late) => late?.detach?.() });
37769
+ const { targetInfos = [] } = await withBrowserOperationDeadline(cdp.send('Target.getTargets'), 2_000, 'Listing the tabs of the browser');
37770
+ _ownTargets.prune(key, targetInfos.map((target) => target.targetId));
37771
+ } catch { /* kept until they expire */ } finally { if (cdp) cdp.detach().catch(() => {}); }
37772
+ })();
37773
+ }
37774
+
37775
+ /**
37776
+ * A session that is retired because it stopped answering (its browser stays open: a MoreLogin profile, the user's
37777
+ * Chrome): the tabs SynaBun opened for it are closed with the browser-level Target.closeTarget, which a frozen tab
37778
+ * cannot hold up, over a fresh connection first (the session's own may be what is stuck). Before 2026-11-29 such a
37779
+ * session only disconnected and its tabs stayed; a frozen one then failed every later launch on the profile. Only
37780
+ * tabs recorded as SynaBun's own, never the owner's; the browser keeps a window (closeOwnTargets). Bounded, never throws.
37781
+ */
37782
+ async function retireSessionOwnTabs(session, sessionId, { forOwner } = {}) {
37783
+ try {
37784
+ const key = ownTargetProfileKey({ profileMode: session._profileMode, envId: session._mlEnvId });
37785
+ if (!key) return null;
37786
+ // `forOwner` (a key, or null for the owner's page): a retirement decided on one tab alone closes only that caller's
37787
+ // tabs and the ones nobody owns, never another run's, which may still be working (review of 2026-11-29, finding 3).
37788
+ // An unowned tab of a session a page watches is the owner's working tab: it stays too.
37789
+ const owned = new Map();
37790
+ for (const [owner, tabId] of session._tabOwners || []) owned.set(tabId, [...(owned.get(tabId) || []), owner]);
37791
+ const closable = ([tabId]) => {
37792
+ if (forOwner === undefined) return true;
37793
+ const owners = owned.get(tabId) || [];
37794
+ if (owners.length === 0) return (session.clients?.size || 0) === 0;
37795
+ return owners.every((owner) => owner === forOwner);
37796
+ };
37797
+ const entries = [...(session.tabs?.entries() || [])].filter(closable);
37798
+ const pages = [...new Set(entries.map(([, entry]) => entry?.page))].filter((page) => page && synabunOpenedPages.has(page));
37799
+ const targetIds = pages.map((page) => _ownTargets.targetIdOf(page)).filter((id) => id && _ownTargets.owns(key, id));
37800
+ if (targetIds.length === 0) return null;
37801
+ const openers = [];
37802
+ // The port the session remembered may belong to another browser by now: what that one lists is trusted only when
37803
+ // it holds a tab recorded for this profile (closeOwnTargets `known`). The session's own connection is that browser.
37804
+ if (session._mlDebugPort) openers.push(() => connectGuardCdp(`http://127.0.0.1:${session._mlDebugPort}`, { timeoutMs: 3_000 }));
37805
+ openers.push({ open: () => session.browser.newBrowserCDPSession(), sameBrowser: true });
37806
+ const result = await closeOwnTargets(openers, targetIds, { known: _ownTargets.list(key), log: (line) => console.warn(`[browser] retiring session ${sessionId}: ${line}`) });
37807
+ for (const id of result.closed) _ownTargets.forget(id);
37808
+ // The empty tab that keeps the window is SynaBun's too: nothing works in it.
37809
+ if (result.placeholder) _ownTargets.note(key, result.placeholder);
37810
+ console.warn(`[browser] Retired session ${sessionId}: closed ${result.closed.length} of the ${targetIds.length} tab(s) SynaBun had opened in it`
37811
+ + `${result.placeholder ? '; an empty tab was opened first so the browser keeps its window' : ''}`
37812
+ + `${result.kept ? '; one stays open so the browser keeps its window' : ''}`
37813
+ + `${result.pending.length ? `; ${result.pending.length} not seen closed (the next launch on this browser closes a frozen one)` : ''}`
37814
+ + `${result.unverified?.length ? `; ${result.unverified.length} kept as SynaBun's: no browser that answered could be shown to be theirs` : ''}`
37815
+ + `${result.via === null && !result.unverified?.length ? `; the browser could not be reached (${result.error || 'no connection'})` : ''}`);
37816
+ return result;
37817
+ } catch (error) {
37818
+ console.warn(`[browser] Closing the tabs of retired session ${sessionId} failed: ${error.message}`);
37819
+ return null;
37820
+ }
37821
+ }
37822
+
37823
+ /**
37824
+ * The launch recovery restarts profile `envId` (lib/morelogin-launch-recovery.js `closeOwnTabs`): right before the
37825
+ * stop, every tab recorded as SynaBun's own in that profile is closed with the browser-level Target.closeTarget over
37826
+ * the profile's DevTools port. MoreLogin reopens a profile's tabs at its next start, under new target ids that nothing
37827
+ * knows as SynaBun's, so a frozen tab left open at the stop came straight back (review of 2026-11-29, finding 2). It
37828
+ * runs only after the recovery found no other automation and no page of the owner's in the profile; only recorded
37829
+ * tabs, never the owner's. The browser keeps a window (closeOwnTargets opens an empty tab first when SynaBun's are
37830
+ * its only ones): a browser left with no window closes itself on Windows, before SynaBun's stop is marked as its own,
37831
+ * and could be read as a close outside SynaBun. Bounded per step; the recovery bounds the whole and never waits on it.
37832
+ */
37833
+ async function closeRecordedTabsBeforeRestart(envId) {
37834
+ const key = ownTargetProfileKey({ profileMode: 'morelogin', envId });
37835
+ const targetIds = key ? _ownTargets.list(key) : [];
37836
+ if (targetIds.length === 0) return { asked: 0, closed: [], pending: [], kept: null, placeholder: null, error: null };
37837
+ let port = null;
37838
+ try { port = moreLogin.runningDebugPort(await moreLogin.profileStatus(envId, { ..._moreLoginOpts(), timeout: 3000 })); } catch { port = null; }
37839
+ if (!port) {
37840
+ for (const session of browserSessions.values()) if (sessionServesMoreLoginEnv(session, envId) && session._mlDebugPort) { port = session._mlDebugPort; break; }
37841
+ }
37842
+ if (!port) return { asked: targetIds.length, closed: [], pending: targetIds, kept: null, placeholder: null, error: 'the profile\'s DevTools port is not known' };
37843
+ // Only on the word of a browser that holds one of the tabs recorded there (closeOwnTargets `known`): a port that
37844
+ // belongs to another browser by now lists none of them, and nothing is then taken as closed or forgotten.
37845
+ const result = await closeOwnTargets([() => connectGuardCdp(`http://127.0.0.1:${port}`, { timeoutMs: 2_000 })], targetIds, {
37846
+ timeoutMs: 2_000, known: targetIds, log: (line) => console.warn(`[morelogin] launch recovery: ${describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || null)}: ${line}`),
37847
+ });
37848
+ for (const id of result.closed) _ownTargets.forget(id);
37849
+ if (result.placeholder) _ownTargets.note(key, result.placeholder);
37850
+ return { asked: targetIds.length, ...result };
37851
+ }
37852
+
37445
37853
  // ── Who a browser request is (lib/terminal-tokens.js) ──
37446
37854
  // A run's X-Synabun-Terminal counts only with that run's terminal token (X-Synabun-Terminal-Token): a request that
37447
37855
  // names a run SynaBun gave a token to without it, with another one, or after the run ended is refused before any
@@ -41481,6 +41889,9 @@ process.on('exit', () => {
41481
41889
  try { flushWhiteboardSync(); } catch {}
41482
41890
  try { flushCostDataSync(); } catch {}
41483
41891
  try { memoryMap.flushSync(); } catch {}
41892
+ // The tabs SynaBun opened, by target id (lib/browser-own-targets.js): written behind, so a write still waiting is
41893
+ // done now. A crash that skips this loses only entries, never adds a wrong one.
41894
+ try { _ownTargets.flush(); } catch {}
41484
41895
  // The Assistant's session records (a rename among them): this handler runs before the Assistant's own
41485
41896
  // exit handler, which the SIGKILL below never lets run.
41486
41897
  try { _assistantRuntime?.flushIndex?.(); } catch {}