synabun 2.4.5 → 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.
- package/CHANGELOG.md +38 -0
- package/README.md +1 -1
- package/docs/whatsapp.md +17 -1
- package/hooks/claude-code/session-start.mjs +21 -18
- package/lib/claude-global-config.js +214 -0
- package/lib/client-config-repair.js +17 -3
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +6 -1
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.js +1 -1
- package/mcp-server/dist/services/tool-catalog.js.map +1 -1
- package/mcp-server/dist/tools/agents.d.ts +2 -0
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +11 -5
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
- package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
- package/mcp-server/dist/tools/skill-tools.js +88 -8
- package/mcp-server/dist/tools/skill-tools.js.map +1 -1
- package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
- package/mcp-server/dist/tools/tool-groups.js +19 -4
- package/mcp-server/dist/tools/tool-groups.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/index.ts +6 -1
- package/mcp-server/src/services/tool-catalog.ts +1 -1
- package/mcp-server/src/tools/agents.ts +11 -5
- package/mcp-server/src/tools/skill-tools.ts +82 -9
- package/mcp-server/src/tools/tool-groups.ts +19 -4
- package/neural-interface/i18n/en.json +153 -10
- package/neural-interface/i18n/pt-BR.json +153 -10
- package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
- package/neural-interface/lib/assistant-dispatch.js +15 -1
- package/neural-interface/lib/assistant-runtime.js +79 -8
- package/neural-interface/lib/assistant-user-context.js +7 -3
- package/neural-interface/lib/browser-background-tab.js +12 -0
- package/neural-interface/lib/browser-guard-cdp.js +2 -1
- package/neural-interface/lib/browser-network-guard.js +140 -3
- package/neural-interface/lib/browser-own-targets.js +350 -0
- package/neural-interface/lib/claude-agent-bridge.js +13 -2
- package/neural-interface/lib/codex-thread-history.js +144 -7
- package/neural-interface/lib/codex-worker-app-server.js +84 -30
- package/neural-interface/lib/db.js +26 -0
- package/neural-interface/lib/greeting/sources.js +7 -3
- package/neural-interface/lib/jsonl-lines.js +10 -11
- package/neural-interface/lib/launch-block-api.js +86 -0
- package/neural-interface/lib/line-buffer.js +88 -0
- package/neural-interface/lib/loop-stall.js +15 -1
- package/neural-interface/lib/memory-list-read.js +105 -0
- package/neural-interface/lib/memory-timers.js +4 -1
- package/neural-interface/lib/morelogin-launch-recovery.js +506 -0
- package/neural-interface/lib/morelogin-profile-failures.js +48 -1
- package/neural-interface/lib/morelogin.js +16 -2
- package/neural-interface/lib/native-loop-runtime.js +7 -3
- package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
- package/neural-interface/lib/skills/api-v2.js +18 -3
- package/neural-interface/lib/skills/bundle.js +2 -2
- package/neural-interface/lib/skills/deploy.js +169 -34
- package/neural-interface/lib/skills/digest.js +57 -3
- package/neural-interface/lib/skills/health.js +55 -1
- package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
- package/neural-interface/lib/skills/runtime-checks.js +7 -4
- package/neural-interface/lib/skills/scan-shell.js +56 -7
- package/neural-interface/lib/skills/scan.js +13 -12
- package/neural-interface/lib/skills/service.js +7 -2
- package/neural-interface/lib/skills/telemetry.js +2 -2
- package/neural-interface/lib/teams/README.md +12 -5
- package/neural-interface/lib/teams/api.js +15 -4
- package/neural-interface/lib/teams/index.js +2 -0
- package/neural-interface/lib/teams/landing.js +195 -75
- package/neural-interface/lib/teams/scheduler.js +31 -32
- package/neural-interface/lib/terminal-token-redaction.js +228 -58
- package/neural-interface/lib/terminal-tokens.js +18 -0
- package/neural-interface/lib/whatsapp/brain.js +21 -0
- package/neural-interface/lib/whatsapp/bridge.js +40 -4
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +117 -37
- package/neural-interface/public/shared/agents/studio/ax-api.js +11 -0
- package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
- package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
- package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
- package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
- package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
- package/neural-interface/public/shared/agents/studio/ax-teams-view.js +137 -39
- package/neural-interface/public/shared/agents/studio/ax-teams.js +219 -4
- package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
- package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
- package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
- package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
- package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
- package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
- package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
- package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
- package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
- package/neural-interface/public/shared/launch-block-view.js +124 -0
- package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
- package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
- package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
- package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
- package/neural-interface/public/shared/styles.css +17 -0
- package/neural-interface/public/shared/ui-launch-block-notice.js +155 -0
- package/neural-interface/public/shared/ui-navbar.js +11 -0
- package/neural-interface/public/shared/ui-sync.js +2 -0
- package/neural-interface/server.js +745 -270
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/skills/skill-forge/SKILL.md +7 -3
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A launch that fails on its profile's browser: one restart of the profile, one retry, and one notice (2026-11-29).
|
|
3
|
+
*
|
|
4
|
+
* On 2026-11-28 a frozen tab left in MoreLogin profile P-1 by a retired session made every scheduled launch on that
|
|
5
|
+
* profile fail for 40 hours ("Network guard: Target.setAutoAttach timed out", lib/browser-network-guard.js). The
|
|
6
|
+
* launcher refused each run, correctly (never another profile, never Chrome), and did nothing else: the same tab
|
|
7
|
+
* failed the next launch, agents may not stop a profile they hold nothing in, and nobody was told.
|
|
8
|
+
*
|
|
9
|
+
* Now, when a run's browser acquisition (server.js acquireSharedBrowserTab: a scheduled launch, a loop launch, a
|
|
10
|
+
* run's recovery) fails because the guard timed out or the profile's browser does not answer (`launchFailureKind`),
|
|
11
|
+
* the server itself stops and starts the profile through MoreLogin's local API (a local profile through its own
|
|
12
|
+
* launcher) and the acquisition is tried once more. This is the server's recovery for the run being launched, not a
|
|
13
|
+
* tool: what an agent may stop or start is unchanged (lib/browser-session-close.js profileStopDecision).
|
|
14
|
+
*
|
|
15
|
+
* It does not restart when (`restartRefusal`):
|
|
16
|
+
* - the owner has a session of that profile open in SynaBun (a page watches it) that no other automation works in:
|
|
17
|
+
* a restart would close the owner's tabs under them (review of 2026-11-29, finding 1);
|
|
18
|
+
* - another automation holds a tab or a hold in that profile, or started it: a restart would close their tabs;
|
|
19
|
+
* - MoreLogin holds the profile's start for its plan's daily limit: a stop could not be followed by a start;
|
|
20
|
+
* - the profile was closed outside SynaBun and this is not a new scheduled firing (which alone may start it);
|
|
21
|
+
* - it restarted the profile recently: every start of a MoreLogin profile spends one of the plan's daily launches,
|
|
22
|
+
* so a restart that helped is not repeated for RESTART_OK_INTERVAL_MS and one that did not for
|
|
23
|
+
* RESTART_FAILED_INTERVAL_MS, and none goes past RESTARTS_PER_DAY in RESTART_CAP_WINDOW_MS (`daily-cap`: a tab that
|
|
24
|
+
* froze again after each restart that helped would restart the profile every 15 minutes).
|
|
25
|
+
*
|
|
26
|
+
* A restart that is decided is under way for that profile until its start ended (`restarting`): an attachment to it
|
|
27
|
+
* from outside its acquisition queue (an agent's browser_session create, POST /api/browser/sessions, the owner's page,
|
|
28
|
+
* a new tab in a session of it) waits for it (`whenRestarted`, RESTART_ATTACH_WAIT_MS at most) or is refused with
|
|
29
|
+
* MORELOGIN_PROFILE_RESTARTING, because the stop would cut it off. Who holds the profile is asked again before
|
|
30
|
+
* SynaBun's tabs are closed and right before the stop; one that appeared meanwhile cancels the restart with the usual
|
|
31
|
+
* refusal (review of e8937e79, N1).
|
|
32
|
+
* A refusal, a failed stop or start and a failed retry all fail the run with the reason; the run never moves to
|
|
33
|
+
* another profile or browser, and nothing loops (one restart and one retry per acquisition).
|
|
34
|
+
*
|
|
35
|
+
* Right before the stop, the tabs SynaBun recorded as its own in that profile (lib/browser-own-targets.js) are closed
|
|
36
|
+
* with the browser-level Target.closeTarget (`closeOwnTabs`; review of 2026-11-29, finding 2): MoreLogin reopens a
|
|
37
|
+
* profile's tabs at its next start under new target ids, which nothing knows as SynaBun's, so a frozen tab left open
|
|
38
|
+
* would come straight back with the restart. Only recorded tabs, never the owner's; bounded (CLOSE_TABS_WAIT_MS): a
|
|
39
|
+
* browser that does not answer the close does not hold the restart up, and the stop follows.
|
|
40
|
+
*
|
|
41
|
+
* Each outcome is kept in the profile's row of DATA_HOME/data/morelogin-profile-failures.json
|
|
42
|
+
* (lib/morelogin-profile-failures.js `profiles`) and logged. The same row counts the launches that failed on the
|
|
43
|
+
* profile in a row; at LAUNCH_NOTICE_AFTER the owner gets ONE notice (profile, error, fix), not one per run. It
|
|
44
|
+
* goes when a launch on the profile works again, or when the owner dismisses it; a new streak raises a new one.
|
|
45
|
+
*
|
|
46
|
+
* No imports and no DOM: everything it touches is handed in.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/** A restart that was followed by a working launch is not repeated before this. */
|
|
50
|
+
export const RESTART_OK_INTERVAL_MS = 15 * 60_000;
|
|
51
|
+
/** A restart that did not help (or could not be completed) is not repeated before this. */
|
|
52
|
+
export const RESTART_FAILED_INTERVAL_MS = 6 * 60 * 60_000;
|
|
53
|
+
/** Launches failing in a row on one profile before the owner is told. */
|
|
54
|
+
export const LAUNCH_NOTICE_AFTER = 2;
|
|
55
|
+
/** How long a stopped profile may take to leave MoreLogin's list of running profiles. */
|
|
56
|
+
export const STOP_WAIT_MS = 30_000;
|
|
57
|
+
/** How long the close of SynaBun's own tabs before the stop may take; the stop follows whatever it got done. */
|
|
58
|
+
export const CLOSE_TABS_WAIT_MS = 10_000;
|
|
59
|
+
/**
|
|
60
|
+
* Recovery restarts of one profile in RESTART_CAP_WINDOW_MS at most. With RESTART_OK_INTERVAL_MS alone, a tab that
|
|
61
|
+
* freezes again after each restart that helped could restart the profile every 15 minutes, each start spending one of
|
|
62
|
+
* MoreLogin's 20 daily launches. Counted in the profile's row of morelogin-profile-failures.json (`restarts`), so a
|
|
63
|
+
* restart of the server does not reset it.
|
|
64
|
+
*/
|
|
65
|
+
export const RESTARTS_PER_DAY = 3;
|
|
66
|
+
/** The rolling window RESTARTS_PER_DAY counts in. */
|
|
67
|
+
export const RESTART_CAP_WINDOW_MS = 24 * 60 * 60_000;
|
|
68
|
+
/** The longest an attachment to a profile waits for SynaBun's restart of it (`whenRestarted`) before it is refused. */
|
|
69
|
+
export const RESTART_ATTACH_WAIT_MS = 90_000;
|
|
70
|
+
|
|
71
|
+
// What a failed start says when the user has to act, or SynaBun chose not to start: never a reason to restart.
|
|
72
|
+
const NEVER_RESTART_CODES = new Set([
|
|
73
|
+
'MORELOGIN_START_REFUSED', 'MORELOGIN_CLOSED_OUTSIDE', 'MORELOGIN_PROFILE_WINDOWLESS', 'MORELOGIN_NOT_CHROMIUM',
|
|
74
|
+
'MORELOGIN_NOT_DEVTOOLS', 'MORELOGIN_PROFILE_NOT_ALLOWED', 'NATIVE_SERVE_UNVERIFIED', 'PROFILE_PINS_FULL',
|
|
75
|
+
'MORELOGIN_PROFILE_RESTARTING', 'PROFILE_CHANGED_DURING_RESTART',
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
/** The error of an attachment to profile `label` refused while SynaBun restarts it (code MORELOGIN_PROFILE_RESTARTING). */
|
|
79
|
+
export function restartingError(label, { since = null, owner = null, waitedMs = null, now = Date.now() } = {}) {
|
|
80
|
+
const waited = Number.isFinite(waitedMs) && waitedMs > 0 ? ` and did not finish within ${Math.round(waitedMs / 1000)} s` : '';
|
|
81
|
+
const started = Number.isFinite(Number(since)) ? ` at ${recoveryTime(Number(since), now)}` : '';
|
|
82
|
+
return Object.assign(new Error(`${label} is being restarted by SynaBun to clear a launch that failed on it (started${started}${owner ? ` for ${String(owner).slice(0, 64)}` : ''})${waited}: nothing attaches to it until the restart is over, because the stop would cut that attachment off. Try again in a minute.`), {
|
|
83
|
+
code: 'MORELOGIN_PROFILE_RESTARTING', status: 409,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* What kind of failure a failed browser start is, for the restart: 'guard-timeout' (the network guard waited for a
|
|
89
|
+
* target that never answered), 'browser-unresponsive' (the profile's browser is listed running and does not answer:
|
|
90
|
+
* no tab could be opened, DevTools did not answer in time, the connection dropped while attaching), or null (anything
|
|
91
|
+
* else: MoreLogin itself is unreachable, the start was refused, the profile cannot be driven, a policy refusal).
|
|
92
|
+
* `failure`: { error, code } as server.js browserStartFailure gives it, or an Error.
|
|
93
|
+
*/
|
|
94
|
+
export function launchFailureKind(failure) {
|
|
95
|
+
if (!failure || failure.sharedPreflight) return null;
|
|
96
|
+
if (failure.code && NEVER_RESTART_CODES.has(String(failure.code))) return null;
|
|
97
|
+
const text = String(failure.error || failure.message || '');
|
|
98
|
+
if (!text) return null;
|
|
99
|
+
// MoreLogin's app or local API is what does not answer: the profile cannot be stopped or started through it.
|
|
100
|
+
if (/MoreLogin app is not reachable|MoreLogin desktop app was not found|local API does not answer/i.test(text)) return null;
|
|
101
|
+
if (/Network guard: [A-Za-z.]+ timed out/.test(text)) return 'guard-timeout';
|
|
102
|
+
if (failure.code === 'BACKGROUND_TAB_FAILED' || /Could not open the browser tab in the background/i.test(text)) return 'browser-unresponsive';
|
|
103
|
+
if (/Network guard CDP disconnected|Network guard: DevTools endpoint answered|Network guard: no DevTools WebSocket endpoint/i.test(text)) return 'browser-unresponsive';
|
|
104
|
+
if (/connectOverCDP[^\n]*(?:Timeout|timed out)|Timeout \d+ms exceeded|Opening handshake has timed out|WebSocket error|socket hang up/i.test(text)) return 'browser-unresponsive';
|
|
105
|
+
if (/ECONNREFUSED|ECONNRESET|ETIMEDOUT/.test(text) && /127\.0\.0\.1|localhost|DevTools|CDP/i.test(text)) return 'browser-unresponsive';
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const KIND_WORDS = {
|
|
110
|
+
'guard-timeout': 'a tab in it does not answer',
|
|
111
|
+
'browser-unresponsive': 'its browser does not answer',
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/** "14:05" today, else "2026-11-28 14:05": a moment as a reason names it, in the server's own time. */
|
|
115
|
+
export function recoveryTime(ms, now = Date.now()) {
|
|
116
|
+
const d = new Date(ms);
|
|
117
|
+
if (Number.isNaN(d.getTime())) return 'an earlier moment';
|
|
118
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
119
|
+
const time = `${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
120
|
+
const today = new Date(now);
|
|
121
|
+
const same = d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate();
|
|
122
|
+
return same ? time : `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${time}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The recovery restarts of `restarts` (a row's list of times) inside the window that ends `now`, oldest first. */
|
|
126
|
+
export function recentRestarts(restarts, now = Date.now(), windowMs = RESTART_CAP_WINDOW_MS) {
|
|
127
|
+
return (Array.isArray(restarts) ? restarts : []).map(Number).filter((at) => Number.isFinite(at) && at <= now && now - at < windowMs).sort((a, b) => a - b);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Why the profile is not restarted now, or null (it may be). Pure.
|
|
132
|
+
* → { reason: 'owner-session' | 'in-use' | 'start-limit' | 'closed-outside' | 'daily-cap' | 'recently-restarted', sentence, ...details }
|
|
133
|
+
* `restarts`: the times of the recovery restarts kept in the profile's row.
|
|
134
|
+
*/
|
|
135
|
+
export function restartRefusal({ label = 'the profile', others = [], ownerSessions = [], startLimit = null, closedOutside = null, scheduled = false, last = null, restarts = [], now = Date.now(),
|
|
136
|
+
okIntervalMs = RESTART_OK_INTERVAL_MS, failedIntervalMs = RESTART_FAILED_INTERVAL_MS, perDay = RESTARTS_PER_DAY, capWindowMs = RESTART_CAP_WINDOW_MS } = {}) {
|
|
137
|
+
if (ownerSessions.length) {
|
|
138
|
+
const one = ownerSessions.length === 1;
|
|
139
|
+
const named = ownerSessions.slice(0, 3).map((id) => text(String(id), 64)).filter(Boolean).join(', ');
|
|
140
|
+
return {
|
|
141
|
+
reason: 'owner-session', sessions: ownerSessions.length,
|
|
142
|
+
sentence: `SynaBun did not restart ${label} to clear it: the owner has ${one ? 'a session' : `${ownerSessions.length} sessions`} of that profile open in SynaBun (${one ? 'session' : 'sessions'} ${named}${ownerSessions.length > 3 ? ', …' : ''}, watched in a browser view), and a restart would close ${one ? 'its tabs' : 'their tabs'} under them. Nothing was stopped or closed. To clear it, close that browser view and launch again, or stop and start the profile in MoreLogin or in SynaBun → Settings → Connected tools → MoreLogin.`,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
if (others.length) {
|
|
146
|
+
return {
|
|
147
|
+
reason: 'in-use', others: others.length,
|
|
148
|
+
sentence: `SynaBun did not restart ${label} to clear it: ${others.length} other automation${others.length === 1 ? ' holds' : 's hold'} a tab in that profile, and a restart would close ${others.length === 1 ? 'its tab' : 'their tabs'}. When ${others.length === 1 ? 'that run ends' : 'those runs end'} the next launch restarts it; to clear it now, stop and start the profile in MoreLogin or in SynaBun → Settings → Connected tools → MoreLogin.`,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (startLimit) {
|
|
152
|
+
return {
|
|
153
|
+
reason: 'start-limit', resetAt: startLimit.resetAt || null,
|
|
154
|
+
sentence: `SynaBun did not restart ${label} to clear it: MoreLogin's daily start limit is reached for it${startLimit.resetAt ? ` until ${recoveryTime(Date.parse(startLimit.resetAt), now)}` : ''}, so a stopped profile could not be started again.`,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
if (closedOutside && !scheduled) {
|
|
158
|
+
return {
|
|
159
|
+
reason: 'closed-outside',
|
|
160
|
+
sentence: `SynaBun did not restart ${label} to clear it: the profile was closed outside SynaBun, and only the owner or a new scheduled run starts it again.`,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
const recent = recentRestarts(restarts, now, capWindowMs);
|
|
164
|
+
if (perDay > 0 && recent.length >= perDay) {
|
|
165
|
+
// The next restart is allowed once enough of these have left the window.
|
|
166
|
+
const next = recent[recent.length - perDay] + capWindowMs;
|
|
167
|
+
return {
|
|
168
|
+
reason: 'daily-cap', count: recent.length, until: next,
|
|
169
|
+
sentence: `SynaBun did not restart ${label} again: it restarted it ${recent.length} times in the last ${Math.round(capWindowMs / 3_600_000)} hours to clear failed launches, the most it does in that time (each start of a MoreLogin profile spends one of the plan's daily launches). The next restart is allowed at ${recoveryTime(next, now)}. To clear it now, stop and start the profile in MoreLogin or in SynaBun → Settings → Connected tools → MoreLogin, and close the tab the error names if it keeps coming back.`,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
if (last && Number.isFinite(Number(last.at)) && last.outcome && last.outcome !== 'refused') {
|
|
173
|
+
const worked = last.outcome === 'restarted-ok';
|
|
174
|
+
const until = Number(last.at) + (worked ? okIntervalMs : failedIntervalMs);
|
|
175
|
+
if (now < until) {
|
|
176
|
+
return {
|
|
177
|
+
reason: 'recently-restarted', until,
|
|
178
|
+
sentence: `SynaBun did not restart ${label} again: it restarted it at ${recoveryTime(Number(last.at), now)}${worked ? '' : ' and that did not clear it'}, and does not restart it again before ${recoveryTime(until, now)} (each start of a MoreLogin profile spends one of the plan's daily launches). To clear it now, stop and start the profile in MoreLogin or in SynaBun → Settings → Connected tools → MoreLogin${worked ? '' : ', and close the tab the error names if it comes back'}.`,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** What fixes a profile whose launches keep failing, as the notice names it: 'restart' | 'start-limit' | 'check'. */
|
|
186
|
+
export function launchFixOf({ kind = null, code = null } = {}) {
|
|
187
|
+
if (kind) return 'restart';
|
|
188
|
+
if (code === 'MORELOGIN_START_REFUSED') return 'start-limit';
|
|
189
|
+
return 'check';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const text = (value, max) => (typeof value === 'string' ? value.replace(/[\u0000-\u001f]+/g, ' ').trim().slice(0, max) : '');
|
|
193
|
+
const sleep = (ms) => new Promise((resolve) => { const timer = setTimeout(resolve, ms); timer.unref?.(); });
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param {object} deps
|
|
197
|
+
* @param {{ profile(envId): object|null, setProfile(envId, row): object|null, profileEntries(): Array }} deps.store
|
|
198
|
+
* lib/morelogin-profile-failures.js createProfileFailureStore
|
|
199
|
+
* @param {(envId: string, ownerKey: string) => string[]} deps.holders the OTHER automations that hold a tab or a
|
|
200
|
+
* hold in a session on that profile, or started it
|
|
201
|
+
* @param {(envId: string, ownerKey: string) => string[]} [deps.ownerSessions] the sessions of that profile the owner
|
|
202
|
+
* has open in SynaBun (a page watches them) and no other automation works in
|
|
203
|
+
* @param {(envId: string) => Promise<{ asked?: number, closed?: string[], pending?: string[], kept?: string|null, error?: string|null }>} [deps.closeOwnTabs]
|
|
204
|
+
* close the tabs recorded as SynaBun's own in that profile, right before the stop (only those, never the owner's)
|
|
205
|
+
* @param {(envId: string) => ({ resetAt?: string }|null)} [deps.startLimit] MoreLogin's daily start limit held for it
|
|
206
|
+
* @param {(envId: string) => (object|null)} [deps.closedOutside] the mark of a close outside SynaBun
|
|
207
|
+
* @param {(envId: string) => Promise<boolean>} deps.running whether the profile's browser is listed as running
|
|
208
|
+
* @param {(envId: string) => Promise<unknown>} deps.stop stop it (MoreLogin's local API, or the local launcher)
|
|
209
|
+
* @param {(envId: string, how: { scheduled: boolean }) => Promise<unknown>} deps.start start it (`scheduled`: for
|
|
210
|
+
* a new scheduled firing, which alone may start a profile closed outside SynaBun)
|
|
211
|
+
* @param {(envId: string) => void} [deps.stopping] told right before the stop: it is SynaBun's own, not an outside close
|
|
212
|
+
* @param {(envId: string, name: string|null) => string} [deps.describe] how a profile is named
|
|
213
|
+
* @param {(notices: object[], change: object) => void} [deps.announce] the notices changed (raised, cleared, dismissed)
|
|
214
|
+
*/
|
|
215
|
+
export function createLaunchRecovery({
|
|
216
|
+
store, holders, ownerSessions = () => [], closeOwnTabs = null, startLimit = () => null, closedOutside = () => null, running, stop, start, stopping = () => {},
|
|
217
|
+
describe = (envId, name) => (name ? `profile "${name}" (${envId})` : `profile ${envId}`),
|
|
218
|
+
announce = () => {}, log = () => {}, now = Date.now, newId = () => Math.random().toString(16).slice(2, 18).padEnd(16, '0'),
|
|
219
|
+
noticeAfter = LAUNCH_NOTICE_AFTER, stopWaitMs = STOP_WAIT_MS, pollMs = 500, closeTabsWaitMs = CLOSE_TABS_WAIT_MS,
|
|
220
|
+
okIntervalMs = RESTART_OK_INTERVAL_MS, failedIntervalMs = RESTART_FAILED_INTERVAL_MS,
|
|
221
|
+
perDay = RESTARTS_PER_DAY, capWindowMs = RESTART_CAP_WINDOW_MS, attachWaitMs = RESTART_ATTACH_WAIT_MS,
|
|
222
|
+
} = {}) {
|
|
223
|
+
if (!store || typeof holders !== 'function' || typeof running !== 'function' || typeof stop !== 'function' || typeof start !== 'function') {
|
|
224
|
+
throw new Error('createLaunchRecovery needs the store, the holders and the profile\'s running, stop and start');
|
|
225
|
+
}
|
|
226
|
+
const rowOf = (envId) => { try { return store.profile(String(envId)) || {}; } catch { return {}; } };
|
|
227
|
+
const keep = (envId, row) => { try { return store.setProfile(String(envId), row); } catch { return null; } };
|
|
228
|
+
const record = (envId, name, recovery) => {
|
|
229
|
+
const row = rowOf(envId);
|
|
230
|
+
keep(envId, { ...row, name: name || row.name || null, recovery: { at: now(), ...recovery } });
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* The restarts under way: envId → { since, owner, done, finish }. From the moment a restart is decided (in the same
|
|
234
|
+
* step as the check of who holds the profile) until its start ended, an attachment to that profile from outside its
|
|
235
|
+
* acquisition queue (an agent's browser_session create, POST /api/browser/sessions, the owner's page, a new tab in a
|
|
236
|
+
* session of it) waits for it (`whenRestarted`) or is refused (`restartingError`): the stop would cut it off.
|
|
237
|
+
*/
|
|
238
|
+
const underWay = new Map();
|
|
239
|
+
/** Who holds the profile now: { others, watched } (a doubt is a holder: nothing restarts on it). */
|
|
240
|
+
const holdersOf = (id, ownerKey) => {
|
|
241
|
+
let others = [];
|
|
242
|
+
try { others = [...new Set(holders(id, ownerKey) || [])]; } catch { others = ['unknown']; }
|
|
243
|
+
let watched = [];
|
|
244
|
+
try { watched = [...new Set((ownerSessions(id, ownerKey) || []).map(String))]; } catch { others = [...others, 'unknown']; }
|
|
245
|
+
return { others, watched };
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The tabs recorded as SynaBun's own in profile `id` are closed before its stop (`closeOwnTabs`). Bounded by
|
|
250
|
+
* `closeTabsWaitMs`, never throws: whatever it got done, the stop follows. → what the outcome keeps, or null when
|
|
251
|
+
* nothing was recorded there: { asked, closed, pending, kept, error } (counts; `kept`: one stays for the window).
|
|
252
|
+
*/
|
|
253
|
+
async function closeRecordedTabs(id, label) {
|
|
254
|
+
if (typeof closeOwnTabs !== 'function') return null;
|
|
255
|
+
let timer = null;
|
|
256
|
+
let result = null;
|
|
257
|
+
let gaveUp = null;
|
|
258
|
+
try {
|
|
259
|
+
result = await Promise.race([
|
|
260
|
+
Promise.resolve().then(() => closeOwnTabs(id)),
|
|
261
|
+
new Promise((_, fail) => { timer = setTimeout(() => fail(new Error(`no answer within ${closeTabsWaitMs >= 1000 ? `${Math.round(closeTabsWaitMs / 1000)} s` : `${closeTabsWaitMs} ms`}`)), closeTabsWaitMs); timer.unref?.(); }),
|
|
262
|
+
]);
|
|
263
|
+
} catch (failure) { gaveUp = text(failure?.message || String(failure), 200) || 'it failed'; } finally { clearTimeout(timer); }
|
|
264
|
+
const count = (list) => (Array.isArray(list) ? list.length : 0);
|
|
265
|
+
const asked = Number.isFinite(Number(result?.asked)) ? Number(result.asked) : count(result?.closed) + count(result?.pending) + (result?.kept ? 1 : 0);
|
|
266
|
+
if (!gaveUp && !asked) return null;
|
|
267
|
+
const summary = {
|
|
268
|
+
asked: gaveUp && !result ? null : asked, closed: count(result?.closed), pending: count(result?.pending), kept: !!result?.kept,
|
|
269
|
+
error: gaveUp || (result?.error ? text(String(result.error), 200) : null),
|
|
270
|
+
};
|
|
271
|
+
log(`${label}: closed ${summary.closed} of the ${summary.asked ?? 'recorded'} tab(s) SynaBun had opened in it, before the stop`
|
|
272
|
+
+ `${summary.pending ? `; ${summary.pending} not seen closed` : ''}${summary.kept ? '; one stays open so the browser keeps its window' : ''}`
|
|
273
|
+
+ `${summary.error ? `; ${gaveUp ? 'the close was given up' : 'the browser answered'}: ${summary.error}` : ''}; the stop follows`);
|
|
274
|
+
return summary;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The notice of a row as the owner's page is shown it, or null (none raised, or dismissed). */
|
|
278
|
+
function noticeOf(envId, row) {
|
|
279
|
+
if (!row?.notice?.id || row.notice.dismissedAt || !row.streak) return null;
|
|
280
|
+
return {
|
|
281
|
+
id: row.notice.id, envId: String(envId), name: row.name || null, raisedAt: row.notice.at,
|
|
282
|
+
count: row.streak.count, firstAt: row.streak.firstAt, lastAt: row.streak.lastAt,
|
|
283
|
+
error: row.streak.error || '', code: row.streak.code || null, kind: row.streak.kind || null,
|
|
284
|
+
fix: launchFixOf(row.streak), launches: row.streak.launches || [],
|
|
285
|
+
recovery: row.recovery ? { at: row.recovery.at, outcome: row.recovery.outcome, reason: row.recovery.reason || null } : null,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function notices() {
|
|
289
|
+
try { return store.profileEntries().map(([envId, row]) => noticeOf(envId, row)).filter(Boolean); } catch { return []; }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* The restart itself, once decided (`attempt` holds the profile's mark around it). Who holds the profile is asked
|
|
294
|
+
* again before SynaBun's tabs are closed and right before the stop: an attachment that began before the mark (and so
|
|
295
|
+
* neither waited nor was refused) cancels the restart with the usual refusal, before anything of it is closed.
|
|
296
|
+
*/
|
|
297
|
+
async function restartNow({ id, label, kind, name, ownerKey, scheduled, beforeStop, refuse }) {
|
|
298
|
+
const heldNow = () => {
|
|
299
|
+
const { others, watched } = holdersOf(id, ownerKey);
|
|
300
|
+
return others.length || watched.length ? restartRefusal({ label, others, ownerSessions: watched, now: now() }) : null;
|
|
301
|
+
};
|
|
302
|
+
log(`restarting ${label} for ${ownerKey || 'a run'}: ${KIND_WORDS[kind]} and no other automation holds a tab in it; the launch is then tried once more`);
|
|
303
|
+
// What the caller still holds of that browser (a session that cannot open a tab) goes first.
|
|
304
|
+
if (typeof beforeStop === 'function') { try { await beforeStop(); } catch { /* the restart ends it anyway */ } }
|
|
305
|
+
// What the outcome keeps of the close of SynaBun's own tabs before the stop (null: nothing was recorded there).
|
|
306
|
+
let tabs = null;
|
|
307
|
+
const withTabs = (outcome) => (tabs ? { ...outcome, tabs } : outcome);
|
|
308
|
+
try {
|
|
309
|
+
let up = false;
|
|
310
|
+
try { up = await running(id); } catch { up = true; }
|
|
311
|
+
if (up) {
|
|
312
|
+
const appeared = heldNow();
|
|
313
|
+
if (appeared) return refuse(appeared);
|
|
314
|
+
// SynaBun's own tabs go first: MoreLogin reopens what is open at the stop, under ids nobody knows as SynaBun's.
|
|
315
|
+
tabs = await closeRecordedTabs(id, label);
|
|
316
|
+
const appearedLate = heldNow();
|
|
317
|
+
if (appearedLate) return refuse(appearedLate);
|
|
318
|
+
try { stopping(id); } catch { /* the stop goes on */ }
|
|
319
|
+
await stop(id);
|
|
320
|
+
// Real elapsed time, whatever clock the records use: this wait must end.
|
|
321
|
+
const until = Date.now() + stopWaitMs;
|
|
322
|
+
for (;;) {
|
|
323
|
+
let still = true;
|
|
324
|
+
try { still = await running(id); } catch { still = true; }
|
|
325
|
+
if (!still) break;
|
|
326
|
+
if (Date.now() >= until) throw Object.assign(new Error(`it is still listed as running ${Math.round(stopWaitMs / 1000)} s after it was stopped`), { step: 'stop' });
|
|
327
|
+
await sleep(pollMs);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
} catch (error) {
|
|
331
|
+
const why = text(error?.message || String(error), 300) || 'no reason was given';
|
|
332
|
+
log(`${label} could not be stopped for the restart: ${why}`);
|
|
333
|
+
record(id, name, withTabs({ outcome: 'stop-failed', kind, reason: why, owner: ownerKey || null }));
|
|
334
|
+
return { restarted: false, kind, reason: 'stop-failed', sentence: `SynaBun tried to restart ${label} to clear it and could not stop it: ${why}. Stop and start the profile in MoreLogin.` };
|
|
335
|
+
}
|
|
336
|
+
// Each start spends one of MoreLogin's daily launches: counted for the daily cap before it is asked for.
|
|
337
|
+
const row = rowOf(id);
|
|
338
|
+
keep(id, { ...row, restarts: [...recentRestarts(row.restarts, now(), capWindowMs), now()] });
|
|
339
|
+
try { await start(id, { scheduled: scheduled === true }); } catch (error) {
|
|
340
|
+
const why = text(error?.message || String(error), 300) || 'no reason was given';
|
|
341
|
+
log(`${label} was stopped for the restart and could not be started again: ${why}`);
|
|
342
|
+
record(id, name, withTabs({ outcome: 'start-failed', kind, reason: why, owner: ownerKey || null, ...(error?.code ? { code: String(error.code).slice(0, 64) } : {}) }));
|
|
343
|
+
return { restarted: false, kind, reason: 'start-failed', needsUser: true, sentence: `SynaBun stopped ${label} to clear it and could not start it again: ${why}. The profile is stopped now; start it in MoreLogin or in SynaBun → Settings → Connected tools → MoreLogin.` };
|
|
344
|
+
}
|
|
345
|
+
record(id, name, withTabs({ outcome: 'restarted', kind, reason: null, owner: ownerKey || null }));
|
|
346
|
+
log(`${label} was stopped and started again; retrying the launch once`);
|
|
347
|
+
return { restarted: true, kind, ...(tabs ? { tabs } : {}) };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
kindOf: launchFailureKind,
|
|
352
|
+
notices,
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* A run's acquisition failed with `failure` on profile `envId`: restart the profile when that can clear it.
|
|
356
|
+
* → { restarted: true, kind } (stopped and started: try the acquisition once more), or
|
|
357
|
+
* { restarted: false, kind, reason, sentence, needsUser? } (nothing to restart for, refused, or the stop or the
|
|
358
|
+
* start failed: the run fails, and `sentence` is added to its error). Never throws.
|
|
359
|
+
*/
|
|
360
|
+
async attempt({ ownerKey, envId, name = null, failure, scheduled = false, beforeStop = null } = {}) {
|
|
361
|
+
const kind = launchFailureKind(failure);
|
|
362
|
+
const id = String(envId || '');
|
|
363
|
+
if (!kind || !id) return { restarted: false, kind: null, reason: null, sentence: '' };
|
|
364
|
+
const label = describe(id, name);
|
|
365
|
+
// Another restart of this profile is under way (one launch's recovery waits in the profile's queue, so this is
|
|
366
|
+
// a caller outside it): it is not started twice.
|
|
367
|
+
if (underWay.has(id)) {
|
|
368
|
+
const busy = underWay.get(id);
|
|
369
|
+
log(`${label} is not restarted for ${ownerKey || 'a run'} (${KIND_WORDS[kind]}): a restart of it is under way`);
|
|
370
|
+
return { restarted: false, kind, reason: 'restart-under-way', sentence: restartingError(label, { since: busy.since, owner: busy.owner, now: now() }).message };
|
|
371
|
+
}
|
|
372
|
+
const refuse = (refusal) => {
|
|
373
|
+
log(`${label} is not restarted for ${ownerKey || 'a run'} (${KIND_WORDS[kind]}): ${refusal.reason}`);
|
|
374
|
+
// A refusal is no restart: the last real one stays what the next decision reads.
|
|
375
|
+
const row = rowOf(id);
|
|
376
|
+
keep(id, { ...row, name: name || row.name || null, refused: { at: now(), reason: refusal.reason, kind, owner: ownerKey || null } });
|
|
377
|
+
return { restarted: false, kind, reason: refusal.reason, sentence: refusal.sentence };
|
|
378
|
+
};
|
|
379
|
+
const { others, watched } = holdersOf(id, ownerKey);
|
|
380
|
+
let limit = null;
|
|
381
|
+
let outside = null;
|
|
382
|
+
try { limit = startLimit(id) || null; } catch { limit = null; }
|
|
383
|
+
try { outside = closedOutside(id) || null; } catch { outside = null; }
|
|
384
|
+
const before = rowOf(id);
|
|
385
|
+
const refusal = restartRefusal({ label, others, ownerSessions: watched, startLimit: limit, closedOutside: outside, scheduled, last: before.recovery || null, restarts: before.restarts, now: now(), okIntervalMs, failedIntervalMs, perDay, capWindowMs });
|
|
386
|
+
if (refusal) return refuse(refusal);
|
|
387
|
+
// Decided, in the same step as the check of who holds the profile: from now until its start ended, attachments
|
|
388
|
+
// to it from outside the queue wait or are refused (`restarting`, `whenRestarted`).
|
|
389
|
+
let finish = () => {};
|
|
390
|
+
const done = new Promise((resolve) => { finish = resolve; });
|
|
391
|
+
underWay.set(id, { since: now(), owner: ownerKey || null, name: name || null, done, finish });
|
|
392
|
+
try {
|
|
393
|
+
return await restartNow({ id, label, kind, name, ownerKey, scheduled, beforeStop, refuse });
|
|
394
|
+
} finally {
|
|
395
|
+
underWay.delete(id);
|
|
396
|
+
finish();
|
|
397
|
+
}
|
|
398
|
+
},
|
|
399
|
+
|
|
400
|
+
/** The restart of profile `envId` under way, or null: { since, owner }. */
|
|
401
|
+
restarting(envId) {
|
|
402
|
+
const busy = underWay.get(String(envId || ''));
|
|
403
|
+
return busy ? { since: busy.since, owner: busy.owner } : null;
|
|
404
|
+
},
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Wait for the restart of profile `envId` under way, `timeoutMs` at most. → true when none is under way (any
|
|
408
|
+
* more), false when it was still under way at the end of the wait. Never rejects.
|
|
409
|
+
*/
|
|
410
|
+
async whenRestarted(envId, { timeoutMs = attachWaitMs } = {}) {
|
|
411
|
+
const busy = underWay.get(String(envId || ''));
|
|
412
|
+
if (!busy) return true;
|
|
413
|
+
let timer = null;
|
|
414
|
+
const over = await Promise.race([
|
|
415
|
+
busy.done.then(() => true),
|
|
416
|
+
new Promise((resolve) => { timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs)); timer.unref?.(); }),
|
|
417
|
+
]).finally(() => clearTimeout(timer));
|
|
418
|
+
return over || !underWay.has(String(envId || ''));
|
|
419
|
+
},
|
|
420
|
+
|
|
421
|
+
/** The error an attachment to a profile under restart is refused with (MORELOGIN_PROFILE_RESTARTING). */
|
|
422
|
+
restartingError: (envId, { name = null, waitedMs = null } = {}) => {
|
|
423
|
+
const busy = underWay.get(String(envId || ''));
|
|
424
|
+
return restartingError(describe(String(envId || ''), name || busy?.name || null), { since: busy?.since ?? null, owner: busy?.owner ?? null, waitedMs, now: now() });
|
|
425
|
+
},
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* The retry after a restart ended (`ok`, else `error`). Returns the sentence a failed retry adds to the run's
|
|
429
|
+
* error ('' when it worked).
|
|
430
|
+
*/
|
|
431
|
+
settled({ envId, name = null, ownerKey = null, ok, error = null } = {}) {
|
|
432
|
+
const id = String(envId || '');
|
|
433
|
+
if (!id) return '';
|
|
434
|
+
const row = rowOf(id);
|
|
435
|
+
const kind = row.recovery?.kind || null;
|
|
436
|
+
const label = describe(id, name || row.name || null);
|
|
437
|
+
// What was closed before the stop stays with the outcome of the restart it belongs to.
|
|
438
|
+
const tabs = row.recovery?.tabs ? { tabs: row.recovery.tabs } : {};
|
|
439
|
+
if (ok) {
|
|
440
|
+
record(id, name, { outcome: 'restarted-ok', kind, reason: null, owner: ownerKey, ...tabs });
|
|
441
|
+
log(`${label}: the launch works again after the restart`);
|
|
442
|
+
return '';
|
|
443
|
+
}
|
|
444
|
+
const why = text(String(error || ''), 300) || 'no reason was given';
|
|
445
|
+
record(id, name, { outcome: 'restarted-retry-failed', kind, reason: why, owner: ownerKey, ...tabs });
|
|
446
|
+
log(`${label}: the launch failed again after the restart (${why}); it is not restarted again for this launch`);
|
|
447
|
+
return `SynaBun restarted ${label} once to clear it and the retry failed too; it does not restart it again for this launch, nor before ${recoveryTime(now() + failedIntervalMs, now())}.`;
|
|
448
|
+
},
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* A launch failed on profile `envId` (after whatever recovery was tried). Counts it; at `noticeAfter` in a row
|
|
452
|
+
* the owner is told, once for the streak. → { count, raised: notice|null }
|
|
453
|
+
*/
|
|
454
|
+
launchFailed({ envId, name = null, failure = null, launch = null } = {}) {
|
|
455
|
+
const id = String(envId || '');
|
|
456
|
+
if (!id) return { count: 0, raised: null };
|
|
457
|
+
const row = rowOf(id);
|
|
458
|
+
const at = now();
|
|
459
|
+
const previous = row.streak && Number.isFinite(Number(row.streak.count)) ? row.streak : null;
|
|
460
|
+
const launches = [...new Set([...(previous?.launches || []), text(launch || '', 120)].filter(Boolean))].slice(-5);
|
|
461
|
+
const streak = {
|
|
462
|
+
count: (previous?.count || 0) + 1, firstAt: previous?.firstAt || at, lastAt: at,
|
|
463
|
+
error: text(String(failure?.error || failure?.message || ''), 600) || 'no reason was given',
|
|
464
|
+
code: failure?.code ? String(failure.code).slice(0, 64) : null, kind: launchFailureKind(failure), launches,
|
|
465
|
+
};
|
|
466
|
+
let notice = row.notice || null;
|
|
467
|
+
let raised = null;
|
|
468
|
+
if (!notice && streak.count >= noticeAfter) notice = { id: String(newId()).slice(0, 32), at, dismissedAt: null };
|
|
469
|
+
const kept = keep(id, { ...row, name: name || row.name || null, streak, notice });
|
|
470
|
+
if (notice && !row.notice) {
|
|
471
|
+
raised = noticeOf(id, kept || { ...row, name, streak, notice });
|
|
472
|
+
log(`${describe(id, name || row.name || null)}: ${streak.count} launches in a row failed on it (${streak.error}); the owner is told once`);
|
|
473
|
+
try { announce(notices(), { raised }); } catch { /* the page asks when it loads */ }
|
|
474
|
+
}
|
|
475
|
+
return { count: streak.count, raised };
|
|
476
|
+
},
|
|
477
|
+
|
|
478
|
+
/** A launch works on profile `envId` again: its streak and its notice are over. → whether a notice was cleared. */
|
|
479
|
+
launchSucceeded(envId) {
|
|
480
|
+
const id = String(envId || '');
|
|
481
|
+
if (!id) return false;
|
|
482
|
+
const row = rowOf(id);
|
|
483
|
+
if (!row.streak && !row.notice) return false;
|
|
484
|
+
const shown = !!noticeOf(id, row);
|
|
485
|
+
keep(id, { ...row, streak: null, notice: null, refused: null });
|
|
486
|
+
if (row.streak) log(`${describe(id, row.name || null)}: a launch works again after ${row.streak.count} failed in a row`);
|
|
487
|
+
if (shown) { try { announce(notices(), { cleared: id }); } catch { /* the page asks when it loads */ } }
|
|
488
|
+
return shown;
|
|
489
|
+
},
|
|
490
|
+
|
|
491
|
+
/** The owner dismissed notice `noticeId`: not shown again for this streak. → whether one was dismissed. */
|
|
492
|
+
dismiss(noticeId) {
|
|
493
|
+
const wanted = String(noticeId || '');
|
|
494
|
+
if (!wanted) return false;
|
|
495
|
+
let entries = [];
|
|
496
|
+
try { entries = store.profileEntries(); } catch { return false; }
|
|
497
|
+
for (const [envId, row] of entries) {
|
|
498
|
+
if (row?.notice?.id !== wanted || row.notice.dismissedAt) continue;
|
|
499
|
+
keep(envId, { ...row, notice: { ...row.notice, dismissedAt: now() } });
|
|
500
|
+
try { announce(notices(), { dismissed: wanted }); } catch { /* the page asks when it loads */ }
|
|
501
|
+
return true;
|
|
502
|
+
}
|
|
503
|
+
return false;
|
|
504
|
+
},
|
|
505
|
+
};
|
|
506
|
+
}
|
|
@@ -29,6 +29,10 @@
|
|
|
29
29
|
*
|
|
30
30
|
* State: in memory and in DATA_HOME/data/morelogin-profile-failures.json (a restart resumes runs: a barred run must stay
|
|
31
31
|
* barred), like the sessions' profile choices (lib/browser-profile-choices.js). Never throws.
|
|
32
|
+
*
|
|
33
|
+
* The same file also keeps one row per PROFILE (`profiles`, 2026-11-29): what lib/morelogin-launch-recovery.js records
|
|
34
|
+
* of the launches that failed on it in a row, of the restart SynaBun made to clear it and of the notice the owner was
|
|
35
|
+
* shown. One store writes the file, so neither part overwrites the other; a file from before has no `profiles`.
|
|
32
36
|
*/
|
|
33
37
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
34
38
|
import { dirname } from 'node:path';
|
|
@@ -124,14 +128,23 @@ export function profileSwitchBarError(failure, { label = null, targetLabel = nul
|
|
|
124
128
|
export function createProfileFailureStore({ file = null, now = Date.now, log = () => {}, max = PROFILE_FAILURES_MAX, maxAgeMs = PROFILE_FAILURE_MAX_AGE_MS } = {}) {
|
|
125
129
|
/** ownerKey → { envId, name, at, code, reason }, oldest first. */
|
|
126
130
|
let rows = null;
|
|
131
|
+
/** envId → the profile's own row (lib/morelogin-launch-recovery.js decides what is in it; `at` is when it last changed). */
|
|
132
|
+
let profiles = new Map();
|
|
127
133
|
|
|
128
134
|
const fresh = (row) => row && Number.isFinite(Number(row.at)) && now() - Number(row.at) < maxAgeMs;
|
|
129
135
|
|
|
130
136
|
function read() {
|
|
131
137
|
const out = new Map();
|
|
138
|
+
profiles = new Map();
|
|
132
139
|
try {
|
|
133
140
|
if (!file || !existsSync(file)) return out;
|
|
134
141
|
const data = JSON.parse(readFileSync(file, 'utf-8'));
|
|
142
|
+
const perProfile = data && typeof data === 'object' && data.profiles && typeof data.profiles === 'object' && !Array.isArray(data.profiles) ? Object.entries(data.profiles) : [];
|
|
143
|
+
for (const [envId, row] of perProfile) {
|
|
144
|
+
if (cleanId(envId) !== envId || !row || typeof row !== 'object' || Array.isArray(row) || !fresh(row)) continue;
|
|
145
|
+
profiles.set(envId, JSON.parse(JSON.stringify(row)));
|
|
146
|
+
if (profiles.size >= max) break;
|
|
147
|
+
}
|
|
135
148
|
const list = data && typeof data === 'object' && data.failures && typeof data.failures === 'object' ? Object.entries(data.failures) : [];
|
|
136
149
|
for (const [owner, row] of list.filter(([owner, row]) => OWNER_RE.test(owner) && fresh(row)).sort((a, b) => Number(a[1].at) - Number(b[1].at))) {
|
|
137
150
|
const envId = cleanId(row.envId);
|
|
@@ -149,7 +162,7 @@ export function createProfileFailureStore({ file = null, now = Date.now, log = (
|
|
|
149
162
|
try {
|
|
150
163
|
mkdirSync(dirname(file), { recursive: true });
|
|
151
164
|
const temp = `${file}.${process.pid}.tmp`;
|
|
152
|
-
writeFileSync(temp, JSON.stringify({ version: 1, failures: Object.fromEntries(rows) }, null, 2), { mode: 0o600 });
|
|
165
|
+
writeFileSync(temp, JSON.stringify({ version: 1, failures: Object.fromEntries(rows), ...(profiles.size ? { profiles: Object.fromEntries(profiles) } : {}) }, null, 2), { mode: 0o600 });
|
|
153
166
|
renameSync(temp, file);
|
|
154
167
|
} catch (error) {
|
|
155
168
|
log(`a run's failed browser profile was not saved (${error?.message || error}): it bars the run until the server restarts`);
|
|
@@ -202,5 +215,39 @@ export function createProfileFailureStore({ file = null, now = Date.now, log = (
|
|
|
202
215
|
entries() {
|
|
203
216
|
return [...loaded()].filter(([, row]) => fresh(row)).map(([owner, row]) => [owner, copy(row)]);
|
|
204
217
|
},
|
|
218
|
+
/** The row kept for profile `envId` (a copy), or null. An expired one is dropped. */
|
|
219
|
+
profile(envId) {
|
|
220
|
+
loaded();
|
|
221
|
+
const id = cleanId(envId);
|
|
222
|
+
const row = id ? profiles.get(id) : null;
|
|
223
|
+
if (!row) return null;
|
|
224
|
+
if (!fresh(row)) { profiles.delete(id); write(); return null; }
|
|
225
|
+
return JSON.parse(JSON.stringify(row));
|
|
226
|
+
},
|
|
227
|
+
/**
|
|
228
|
+
* Keep `row` (a plain JSON object) for profile `envId`, stamped with the time of this change; null removes it.
|
|
229
|
+
* Returns what is kept now (a copy), or null.
|
|
230
|
+
*/
|
|
231
|
+
setProfile(envId, row) {
|
|
232
|
+
loaded();
|
|
233
|
+
const id = cleanId(envId);
|
|
234
|
+
if (!id) return null;
|
|
235
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) {
|
|
236
|
+
if (profiles.delete(id)) write();
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
let kept;
|
|
240
|
+
try { kept = { ...JSON.parse(JSON.stringify(row)), at: now() }; } catch { return null; }
|
|
241
|
+
profiles.delete(id); // newest last
|
|
242
|
+
profiles.set(id, kept);
|
|
243
|
+
while (profiles.size > max) profiles.delete(profiles.keys().next().value);
|
|
244
|
+
write();
|
|
245
|
+
return JSON.parse(JSON.stringify(kept));
|
|
246
|
+
},
|
|
247
|
+
/** Every profile row held now: [envId, row], oldest first. */
|
|
248
|
+
profileEntries() {
|
|
249
|
+
loaded();
|
|
250
|
+
return [...profiles].filter(([, row]) => fresh(row)).map(([envId, row]) => [envId, JSON.parse(JSON.stringify(row))]);
|
|
251
|
+
},
|
|
205
252
|
};
|
|
206
253
|
}
|
|
@@ -686,6 +686,15 @@ function runningWithPort(row) {
|
|
|
686
686
|
return !/stop|clos|fail|error/i.test(state);
|
|
687
687
|
}
|
|
688
688
|
|
|
689
|
+
/**
|
|
690
|
+
* The DevTools port of a profile a status answer (profileStatus, MoreLogin's or a local profile's) lists as running,
|
|
691
|
+
* or null: not running, no port, or no answer.
|
|
692
|
+
*/
|
|
693
|
+
export function runningDebugPort(status) {
|
|
694
|
+
const row = statusRow(status);
|
|
695
|
+
return runningWithPort(row) ? extractDebugPort(row) : null;
|
|
696
|
+
}
|
|
697
|
+
|
|
689
698
|
// One start per profile at a time: a second caller waits for the first and then looks again (it then finds the
|
|
690
699
|
// profile running and attaches, or finds the refusal held), so two runs never spend two launches on one profile.
|
|
691
700
|
const _startsInFlight = new Map(); // envId → promise
|
|
@@ -810,8 +819,10 @@ async function launchProfile(envId, { knownStatus, ...opts }) {
|
|
|
810
819
|
* cookies/fingerprint, even though it belongs to the same Chromium process.
|
|
811
820
|
* Never substitute one when the profile context is missing. On setup failure,
|
|
812
821
|
* close only this connectOverCDP transport; MoreLogin owns the running browser.
|
|
822
|
+
* `guardOptions` ({ pageOwner, onOrphanClosed }) go to the profile's network guard as they are
|
|
823
|
+
* (lib/browser-network-guard.js registerBrowserNetworkEndpoint): whose a tab is that never answers it.
|
|
813
824
|
*/
|
|
814
|
-
export async function attachProfileBrowser(chromium, endpoint, openPage) {
|
|
825
|
+
export async function attachProfileBrowser(chromium, endpoint, openPage, guardOptions = {}) {
|
|
815
826
|
let browser;
|
|
816
827
|
try { browser = await chromium.connectOverCDP(endpoint); } catch (error) {
|
|
817
828
|
// The DevTools port answers but the browser holds no profile (its window was closed and its process lives on):
|
|
@@ -825,7 +836,10 @@ export async function attachProfileBrowser(chromium, endpoint, openPage) {
|
|
|
825
836
|
throw new Error('MoreLogin did not expose its profile context over CDP; refusing to create an isolated context with different cookies and fingerprint settings');
|
|
826
837
|
}
|
|
827
838
|
const page = await openPage(browser, context);
|
|
828
|
-
registerBrowserNetworkEndpoint(context, endpoint
|
|
839
|
+
registerBrowserNetworkEndpoint(context, endpoint, {
|
|
840
|
+
...(typeof guardOptions?.pageOwner === 'function' ? { pageOwner: guardOptions.pageOwner } : {}),
|
|
841
|
+
...(typeof guardOptions?.onOrphanClosed === 'function' ? { onOrphanClosed: guardOptions.onOrphanClosed } : {}),
|
|
842
|
+
});
|
|
829
843
|
return { browser, context, page };
|
|
830
844
|
} catch (error) {
|
|
831
845
|
// Browser.close on a connectOverCDP browser disconnects this client. Do not
|