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.
- package/CHANGELOG.md +13 -0
- package/README.md +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/neural-interface/i18n/en.json +18 -0
- package/neural-interface/i18n/pt-BR.json +18 -0
- 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/launch-block-api.js +86 -0
- 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/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/shared/launch-block-view.js +124 -0
- 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 +429 -18
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// ── The tabs SynaBun opened in a browser the user owns, by DevTools target id ──
|
|
2
|
+
//
|
|
3
|
+
// In a MoreLogin profile (or the user's Chrome over CDP) the browser outlives every SynaBun session: closing a
|
|
4
|
+
// session only disconnects, and each tab stays. A tab SynaBun opened is its own to close; every other tab is the
|
|
5
|
+
// owner's and is never touched. server.js knew its own tabs by their Playwright page (synabunOpenedPages), which
|
|
6
|
+
// is gone the moment the session's connection is: on 2026-11-28 a session was retired because nothing in it
|
|
7
|
+
// answered, its frozen TikTok Studio tab stayed in MoreLogin profile P-1, and nothing could tell later that the tab
|
|
8
|
+
// was SynaBun's. Every scheduled launch on that profile then failed for 40 hours on that tab's workers
|
|
9
|
+
// (lib/browser-network-guard.js).
|
|
10
|
+
//
|
|
11
|
+
// This registry keeps the DevTools target id of every tab SynaBun opens, per profile, in memory and in
|
|
12
|
+
// DATA_HOME/data/browser-own-targets.json (a tab outlives a server restart too). A target id is the browser's own
|
|
13
|
+
// name for a tab and lasts as long as that browser runs; a profile that was stopped and started gives every tab a
|
|
14
|
+
// new one, so a tab the browser restored is never mistaken for SynaBun's. Two things read it:
|
|
15
|
+
// - the network guard, for a page whose target never answers (`classify`): 'orphan' (SynaBun's tab, no live
|
|
16
|
+
// session works in it: closed), 'live' (a live session's tab: left alone) or 'foreign' (not SynaBun's: left
|
|
17
|
+
// alone);
|
|
18
|
+
// - the retirement of a session that stopped answering (`closeOwnTargets`), which closes the session's own tabs
|
|
19
|
+
// with the browser-level Target.closeTarget, the one close a frozen renderer cannot hold up.
|
|
20
|
+
// Nothing here ever closes a target that is not recorded as SynaBun's.
|
|
21
|
+
//
|
|
22
|
+
// An entry goes when its tab is seen gone: SynaBun closed it, or its page reported its close, and the browser no
|
|
23
|
+
// longer lists its target (`createOwnTabCloseWatch`); the guard closed it as an orphan; a new attachment finds it gone
|
|
24
|
+
// (`prune`). A close event alone never forgets an entry: a page also reports a close when the connection to its
|
|
25
|
+
// browser ends, and its tab stays open. The file is written behind (`OWN_TARGETS_WRITE_DELAY_MS`) and flushed at a
|
|
26
|
+
// stop: what a crash loses is an entry (that tab is then the owner's as far as SynaBun can tell, the safe side),
|
|
27
|
+
// never a wrong one.
|
|
28
|
+
|
|
29
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
30
|
+
import { dirname } from 'node:path';
|
|
31
|
+
|
|
32
|
+
/** Entries kept at most (the oldest go first: such a tab is then the owner's as far as SynaBun can tell). */
|
|
33
|
+
export const OWN_TARGETS_MAX = 1000;
|
|
34
|
+
/** An entry older than this is dropped: no browser keeps a target that long without a restart of the profile. */
|
|
35
|
+
export const OWN_TARGET_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
|
|
36
|
+
/** A tab opened this recently counts as in use: it may not be in its session's registry yet. */
|
|
37
|
+
export const OWN_TARGET_SETUP_GRACE_MS = 2 * 60_000;
|
|
38
|
+
/** How long a change waits before the file is written: tabs opened together are one write, not one each. */
|
|
39
|
+
export const OWN_TARGETS_WRITE_DELAY_MS = 250;
|
|
40
|
+
/** When a recorded tab's page closed, the browser is asked after these delays whether its target is gone. */
|
|
41
|
+
export const OWN_TAB_CLOSE_CHECKS_MS = Object.freeze([250, 1_000, 5_000]);
|
|
42
|
+
|
|
43
|
+
const ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
44
|
+
const KEY_RE = /^[A-Za-z0-9_:.-]{1,160}$/;
|
|
45
|
+
|
|
46
|
+
/** The registry key of a browser: a MoreLogin (or local) profile by its id, else the one attached Chrome. */
|
|
47
|
+
export function ownTargetProfileKey({ profileMode = null, envId = null } = {}) {
|
|
48
|
+
if (envId !== null && envId !== undefined && String(envId)) return `ml:${String(envId)}`;
|
|
49
|
+
return profileMode === 'cdp' ? 'cdp' : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {object} [opts]
|
|
54
|
+
* @param {string|null} [opts.file] where the registry is kept (none: memory only)
|
|
55
|
+
* @param {(page: object) => boolean} [opts.inUse] whether a live session works in this Playwright page now
|
|
56
|
+
*/
|
|
57
|
+
export function createOwnTargetRegistry({ file = null, now = Date.now, log = () => {}, inUse = () => false, max = OWN_TARGETS_MAX, maxAgeMs = OWN_TARGET_MAX_AGE_MS, setupGraceMs = OWN_TARGET_SETUP_GRACE_MS, writeDelayMs = OWN_TARGETS_WRITE_DELAY_MS } = {}) {
|
|
58
|
+
/** targetId → { profile, at }, oldest first. */
|
|
59
|
+
let rows = null;
|
|
60
|
+
/** The pages this process opened: targetId → page, and back. */
|
|
61
|
+
const pages = new Map();
|
|
62
|
+
const ids = new WeakMap();
|
|
63
|
+
|
|
64
|
+
const fresh = (row) => row && Number.isFinite(Number(row.at)) && now() - Number(row.at) < maxAgeMs;
|
|
65
|
+
|
|
66
|
+
function read() {
|
|
67
|
+
const out = new Map();
|
|
68
|
+
try {
|
|
69
|
+
if (!file || !existsSync(file)) return out;
|
|
70
|
+
const data = JSON.parse(readFileSync(file, 'utf-8'));
|
|
71
|
+
const list = data && typeof data === 'object' && data.targets && typeof data.targets === 'object' ? Object.entries(data.targets) : [];
|
|
72
|
+
for (const [id, row] of list.filter(([id, row]) => ID_RE.test(id) && fresh(row) && KEY_RE.test(String(row.profile || ''))).sort((a, b) => Number(a[1].at) - Number(b[1].at))) {
|
|
73
|
+
out.set(id, { profile: String(row.profile), at: Number(row.at) });
|
|
74
|
+
}
|
|
75
|
+
} catch (error) {
|
|
76
|
+
log(`the tabs SynaBun opened could not be read (${error?.message || error}): none is known as its own, so none is closed`);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Written behind: one write for the changes of `writeDelayMs`, through a temporary file and a rename (a reader never
|
|
82
|
+
// sees half a file). The file is always the registry as it was at one moment, so a crash before a write loses the
|
|
83
|
+
// latest entries (safe: such a tab is never closed by its id) and never adds one.
|
|
84
|
+
let writeTimer = null;
|
|
85
|
+
function writeNow() {
|
|
86
|
+
if (writeTimer) { clearTimeout(writeTimer); writeTimer = null; }
|
|
87
|
+
if (!file || !rows) return;
|
|
88
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
89
|
+
try {
|
|
90
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
91
|
+
writeFileSync(temp, JSON.stringify({ version: 1, targets: Object.fromEntries(rows) }), { mode: 0o600 });
|
|
92
|
+
renameSync(temp, file);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
try { rmSync(temp, { force: true }); } catch { /* nothing to clean */ }
|
|
95
|
+
log(`a tab SynaBun opened was not saved (${error?.message || error}): it is known as its own until the server restarts`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function write() {
|
|
99
|
+
if (!file) return;
|
|
100
|
+
if (!(writeDelayMs > 0)) { writeNow(); return; }
|
|
101
|
+
if (writeTimer) return;
|
|
102
|
+
writeTimer = setTimeout(writeNow, writeDelayMs);
|
|
103
|
+
writeTimer.unref?.();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const loaded = () => (rows ||= read());
|
|
107
|
+
const drop = (id) => { const page = pages.get(id); pages.delete(id); if (page) ids.delete(page); return loaded().delete(id); };
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
/** SynaBun opened the tab `targetId` in the browser `profileKey` (its Playwright `page`, when this process has it). */
|
|
111
|
+
note(profileKey, targetId, { page = null } = {}) {
|
|
112
|
+
const key = String(profileKey || '');
|
|
113
|
+
const id = String(targetId || '');
|
|
114
|
+
if (!KEY_RE.test(key) || !ID_RE.test(id)) return false;
|
|
115
|
+
const map = loaded();
|
|
116
|
+
map.delete(id); // newest last
|
|
117
|
+
map.set(id, { profile: key, at: now() });
|
|
118
|
+
while (map.size > max) drop(map.keys().next().value);
|
|
119
|
+
if (page && typeof page === 'object') { pages.set(id, page); ids.set(page, id); }
|
|
120
|
+
write();
|
|
121
|
+
return true;
|
|
122
|
+
},
|
|
123
|
+
/** The target id noted for a page this process opened, or null. */
|
|
124
|
+
targetIdOf(page) {
|
|
125
|
+
return (page && typeof page === 'object' && ids.get(page)) || null;
|
|
126
|
+
},
|
|
127
|
+
/** Whether `targetId` is recorded as a tab SynaBun opened in `profileKey`. */
|
|
128
|
+
owns(profileKey, targetId) {
|
|
129
|
+
const row = loaded().get(String(targetId || ''));
|
|
130
|
+
return !!row && fresh(row) && row.profile === String(profileKey || '');
|
|
131
|
+
},
|
|
132
|
+
/**
|
|
133
|
+
* Whose the tab is: 'foreign' (not recorded as SynaBun's in this browser), 'live' (a live session works in its
|
|
134
|
+
* page, or it was opened moments ago and may not be registered yet) or 'orphan' (SynaBun's, and nothing works in
|
|
135
|
+
* it: its session was retired, or it is left from before a restart of the server).
|
|
136
|
+
*/
|
|
137
|
+
classify(profileKey, targetId) {
|
|
138
|
+
const id = String(targetId || '');
|
|
139
|
+
const row = loaded().get(id);
|
|
140
|
+
if (!row || !fresh(row) || row.profile !== String(profileKey || '')) return 'foreign';
|
|
141
|
+
const page = pages.get(id);
|
|
142
|
+
if (!page) return 'orphan';
|
|
143
|
+
let used = false;
|
|
144
|
+
try { used = inUse(page) === true; } catch { used = true; } // a doubt keeps the tab
|
|
145
|
+
return used || now() - row.at < setupGraceMs ? 'live' : 'orphan';
|
|
146
|
+
},
|
|
147
|
+
/** The tab is gone (closed, and seen closed): forgotten. Returns whether it was known. */
|
|
148
|
+
forget(targetId) {
|
|
149
|
+
const known = drop(String(targetId || ''));
|
|
150
|
+
if (known) write();
|
|
151
|
+
return known;
|
|
152
|
+
},
|
|
153
|
+
/**
|
|
154
|
+
* The browser `profileKey` holds exactly the targets `present` now: entries of that browser it no longer has
|
|
155
|
+
* are dropped (the profile was restarted, or the tabs were closed). Returns how many went.
|
|
156
|
+
*/
|
|
157
|
+
prune(profileKey, present) {
|
|
158
|
+
const key = String(profileKey || '');
|
|
159
|
+
const have = new Set([...(present || [])].map(String));
|
|
160
|
+
let gone = 0;
|
|
161
|
+
for (const [id, row] of [...loaded()]) {
|
|
162
|
+
if (row.profile === key && !have.has(id)) { drop(id); gone += 1; }
|
|
163
|
+
}
|
|
164
|
+
if (gone) write();
|
|
165
|
+
return gone;
|
|
166
|
+
},
|
|
167
|
+
/** Every tab recorded for `profileKey`: [targetId], oldest first. */
|
|
168
|
+
list(profileKey) {
|
|
169
|
+
const key = String(profileKey || '');
|
|
170
|
+
return [...loaded()].filter(([, row]) => row.profile === key && fresh(row)).map(([id]) => id);
|
|
171
|
+
},
|
|
172
|
+
/** A write that is still waiting is done now (the server stops). Never throws. */
|
|
173
|
+
flush() {
|
|
174
|
+
if (writeTimer) writeNow();
|
|
175
|
+
},
|
|
176
|
+
/** Whether a write is waiting (tests). */
|
|
177
|
+
get writePending() { return writeTimer !== null; },
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Forgets a recorded tab once it is seen gone. `seen(profileKey, targetId, browser)` is called when SynaBun closed the
|
|
183
|
+
* tab, or its page reported its close; `list(browser)` asks that browser, over the session's own connection (so it is
|
|
184
|
+
* the browser the tab was opened in), which targets it has now, and answers null when it cannot be asked (the
|
|
185
|
+
* connection ended, it did not answer). An entry is forgotten only when the browser answered and no longer lists the
|
|
186
|
+
* target: a page reports a close too when the connection to its browser ends, and the tab is then still open. A target
|
|
187
|
+
* still listed is asked about again after each delay of `checksMs`, then kept (the next attachment to that browser
|
|
188
|
+
* prunes what is gone). The checks of one browser are made together. Never throws.
|
|
189
|
+
*/
|
|
190
|
+
export function createOwnTabCloseWatch({ registry, list, checksMs = OWN_TAB_CLOSE_CHECKS_MS, log = () => {} } = {}) {
|
|
191
|
+
if (!registry || typeof list !== 'function') throw new Error('createOwnTabCloseWatch needs the registry and a way to list the targets of a browser');
|
|
192
|
+
/** browser → { ids: Map<targetId, { key, step }>, timer } */
|
|
193
|
+
const waiting = new Map();
|
|
194
|
+
const delays = (Array.isArray(checksMs) && checksMs.length ? checksMs : OWN_TAB_CLOSE_CHECKS_MS).map((ms) => Math.max(0, Number(ms) || 0));
|
|
195
|
+
|
|
196
|
+
function schedule(browser, batch) {
|
|
197
|
+
if (batch.timer) return;
|
|
198
|
+
const next = Math.min(...[...batch.ids.values()].map((entry) => delays[Math.min(entry.step, delays.length - 1)]));
|
|
199
|
+
batch.timer = setTimeout(() => { batch.timer = null; void check(browser); }, next);
|
|
200
|
+
batch.timer.unref?.();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function check(browser) {
|
|
204
|
+
const batch = waiting.get(browser);
|
|
205
|
+
if (!batch) return 0;
|
|
206
|
+
if (batch.timer) { clearTimeout(batch.timer); batch.timer = null; }
|
|
207
|
+
waiting.delete(browser);
|
|
208
|
+
let present = null;
|
|
209
|
+
try { present = await list(browser); } catch { present = null; }
|
|
210
|
+
// The browser could not be asked: nothing is known to be gone, so nothing is forgotten.
|
|
211
|
+
if (!Array.isArray(present)) return 0;
|
|
212
|
+
const have = new Set(present.map(String));
|
|
213
|
+
let gone = 0;
|
|
214
|
+
const again = new Map();
|
|
215
|
+
for (const [id, entry] of batch.ids) {
|
|
216
|
+
if (!registry.owns(entry.key, id)) continue; // forgotten meanwhile
|
|
217
|
+
if (!have.has(id)) { if (registry.forget(id)) gone += 1; continue; }
|
|
218
|
+
if (entry.step + 1 < delays.length) again.set(id, { key: entry.key, step: entry.step + 1 });
|
|
219
|
+
else log(`tab ${id} reported its close and its browser still lists it: it stays known as SynaBun's`);
|
|
220
|
+
}
|
|
221
|
+
if (again.size) {
|
|
222
|
+
const merged = waiting.get(browser) || { ids: new Map(), timer: null };
|
|
223
|
+
for (const [id, entry] of again) if (!merged.ids.has(id)) merged.ids.set(id, entry);
|
|
224
|
+
waiting.set(browser, merged);
|
|
225
|
+
schedule(browser, merged);
|
|
226
|
+
}
|
|
227
|
+
return gone;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
/** The tab `targetId` of `profileKey` was closed, or its page said so: checked against `browser` shortly. */
|
|
232
|
+
seen(profileKey, targetId, browser) {
|
|
233
|
+
const key = String(profileKey || '');
|
|
234
|
+
const id = String(targetId || '');
|
|
235
|
+
if (!browser || !key || !id || !registry.owns(key, id)) return false;
|
|
236
|
+
const batch = waiting.get(browser) || { ids: new Map(), timer: null };
|
|
237
|
+
if (!batch.ids.has(id)) batch.ids.set(id, { key, step: 0 });
|
|
238
|
+
waiting.set(browser, batch);
|
|
239
|
+
schedule(browser, batch);
|
|
240
|
+
return true;
|
|
241
|
+
},
|
|
242
|
+
/** Check `browser`'s closed tabs now (before its connection ends). → how many were forgotten. */
|
|
243
|
+
confirm(browser) {
|
|
244
|
+
return waiting.has(browser) ? check(browser) : Promise.resolve(0);
|
|
245
|
+
},
|
|
246
|
+
/** How many closed tabs wait for their check (tests). */
|
|
247
|
+
pending() { return [...waiting.values()].reduce((sum, batch) => sum + batch.ids.size, 0); },
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// The browser's own pages that do not count as a tab that keeps its window open: extension and DevTools pages and
|
|
252
|
+
// the browser's own UI (server.js otherOpenPageCount reads the same way).
|
|
253
|
+
const windowTab = (target) => target?.type === 'page' && !target.subtype
|
|
254
|
+
&& !/^(?:chrome-extension|devtools):|^chrome(?:-untrusted)?:\/\/[^/]*\.top-chrome\b/i.test(target.url || '');
|
|
255
|
+
|
|
256
|
+
const within = (promise, ms, what) => {
|
|
257
|
+
let timer;
|
|
258
|
+
return Promise.race([
|
|
259
|
+
Promise.resolve(promise),
|
|
260
|
+
new Promise((_, fail) => { timer = setTimeout(() => fail(new Error(`${what} timed out`)), ms); timer.unref?.(); }),
|
|
261
|
+
]).finally(() => clearTimeout(timer));
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Close the tabs `targetIds` of one browser with the browser-level Target.closeTarget (it asks nothing of a tab's
|
|
266
|
+
* renderer, so a frozen tab closes too). `openers`: ways to a browser-level CDP client ({ send(method, params),
|
|
267
|
+
* detach() }), tried in order until one lists the browser's targets; a session that stopped answering is given a
|
|
268
|
+
* fresh connection first and its own second.
|
|
269
|
+
*
|
|
270
|
+
* The browser keeps a window: when the tabs to close are its only ones, an empty tab is opened first (in the
|
|
271
|
+
* background); when that fails, the last of them stays open and is reported as `kept`. A tab the browser no longer
|
|
272
|
+
* has counts as closed, but only on the word of a browser shown to be the one the tabs were opened in: an opener
|
|
273
|
+
* marked `{ open, sameBrowser: true }` (the session's own connection), or one whose browser lists at least one of
|
|
274
|
+
* `targetIds` or of `known` (other tabs recorded for that browser). A DevTools port can belong to another browser
|
|
275
|
+
* by now (the profile was restarted on another port, another program took it): there SynaBun's ids are all absent,
|
|
276
|
+
* and that says nothing. Such an opener is passed over, and when no opener can be trusted the ids are reported as
|
|
277
|
+
* `unverified`, neither closed nor forgotten. Bounded (`timeoutMs` per step) and never throws.
|
|
278
|
+
* → { closed: [id], pending: [id] (asked, not seen gone), unverified: [id] (no browser shown to be theirs answered),
|
|
279
|
+
* kept: id|null, placeholder: id|null, via: index|null, error }
|
|
280
|
+
*/
|
|
281
|
+
export async function closeOwnTargets(openers, targetIds, { timeoutMs = 3000, keepWindow = true, known = [], log = () => {} } = {}) {
|
|
282
|
+
const wanted = [...new Set((targetIds || []).map(String).filter((id) => ID_RE.test(id)))];
|
|
283
|
+
const out = { closed: [], pending: [], unverified: [], kept: null, placeholder: null, via: null, error: null };
|
|
284
|
+
if (wanted.length === 0) return out;
|
|
285
|
+
const evidence = new Set([...wanted, ...(known || []).map(String)]);
|
|
286
|
+
const list = async (cdp) => (await within(cdp.send('Target.getTargets'), timeoutMs, 'listing the tabs of the browser')).targetInfos || [];
|
|
287
|
+
let untrusted = false;
|
|
288
|
+
for (const [index, opener] of (openers || []).entries()) {
|
|
289
|
+
const open = typeof opener === 'function' ? opener : opener?.open;
|
|
290
|
+
const sameBrowser = typeof opener === 'object' && opener?.sameBrowser === true;
|
|
291
|
+
if (typeof open !== 'function') continue;
|
|
292
|
+
let cdp = null;
|
|
293
|
+
try {
|
|
294
|
+
let late = null;
|
|
295
|
+
const opening = Promise.resolve().then(open);
|
|
296
|
+
opening.then((client) => { if (late) Promise.resolve().then(() => client?.detach?.()).catch(() => {}); }, () => {});
|
|
297
|
+
try { cdp = await within(opening, timeoutMs, 'connecting to the browser'); } catch (error) { late = true; throw error; }
|
|
298
|
+
if (!cdp || typeof cdp.send !== 'function') throw new Error('no browser-level connection');
|
|
299
|
+
const before = await list(cdp);
|
|
300
|
+
const present = new Set(before.map((target) => target.targetId));
|
|
301
|
+
if (!sameBrowser && ![...evidence].some((id) => present.has(id))) {
|
|
302
|
+
// None of SynaBun's tabs of this browser is there: another browser answers, or every one is gone. In doubt the
|
|
303
|
+
// entries stay (a new attachment to the profile prunes them on its own connection).
|
|
304
|
+
untrusted = true;
|
|
305
|
+
log(`the browser reached by connection ${index + 1} lists none of the ${evidence.size} tab(s) SynaBun recorded for it: it may be another browser, so nothing is taken as closed on its word`);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
out.via = index;
|
|
309
|
+
const stillOpen = wanted.filter((id) => present.has(id));
|
|
310
|
+
out.closed.push(...wanted.filter((id) => !present.has(id)));
|
|
311
|
+
let closing = stillOpen;
|
|
312
|
+
if (keepWindow && stillOpen.length && before.filter((target) => windowTab(target) && !stillOpen.includes(target.targetId)).length === 0) {
|
|
313
|
+
try {
|
|
314
|
+
const made = await within(cdp.send('Target.createTarget', { url: 'about:blank', background: true }), timeoutMs, 'opening an empty tab');
|
|
315
|
+
out.placeholder = made?.targetId || null;
|
|
316
|
+
} catch (error) { log(`no empty tab could be opened to keep the window (${error?.message || error})`); }
|
|
317
|
+
if (!out.placeholder) { out.kept = stillOpen.at(-1); closing = stillOpen.slice(0, -1); }
|
|
318
|
+
}
|
|
319
|
+
await Promise.all(closing.map((targetId) => within(cdp.send('Target.closeTarget', { targetId }), timeoutMs, 'closing a tab').catch((error) => {
|
|
320
|
+
if (!/No target with given id/i.test(error?.protocolMessage || error?.message || '')) log(`tab ${targetId} was not confirmed closed (${error?.message || error})`);
|
|
321
|
+
})));
|
|
322
|
+
// Gone when the browser no longer lists it: a close is asynchronous, and a frozen tab takes a moment.
|
|
323
|
+
let left = closing;
|
|
324
|
+
const until = Date.now() + timeoutMs;
|
|
325
|
+
while (left.length) {
|
|
326
|
+
let after = null;
|
|
327
|
+
try { after = new Set((await list(cdp)).map((target) => target.targetId)); } catch { break; }
|
|
328
|
+
left = left.filter((id) => after.has(id));
|
|
329
|
+
if (!left.length || Date.now() >= until) break;
|
|
330
|
+
await new Promise((resolve) => { const timer = setTimeout(resolve, 100); timer.unref?.(); });
|
|
331
|
+
}
|
|
332
|
+
out.closed.push(...closing.filter((id) => !left.includes(id)));
|
|
333
|
+
out.pending = left;
|
|
334
|
+
out.error = null;
|
|
335
|
+
return out;
|
|
336
|
+
} catch (error) {
|
|
337
|
+
out.error = error?.message || String(error);
|
|
338
|
+
if (out.via !== null) { out.pending = wanted.filter((id) => !out.closed.includes(id) && id !== out.kept); return out; }
|
|
339
|
+
} finally {
|
|
340
|
+
if (cdp) Promise.resolve().then(() => cdp.detach?.()).catch(() => {});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (untrusted) {
|
|
344
|
+
out.unverified = wanted;
|
|
345
|
+
out.error = 'no browser that answered could be shown to be the one these tabs were opened in';
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
out.pending = wanted;
|
|
349
|
+
return out;
|
|
350
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — /api/system/launch-blocks: the notice that launches keep failing on a browser profile
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// GET /api/system/launch-blocks { ok, notices } the profiles whose launches failed in a row
|
|
6
|
+
// POST /api/system/launch-blocks/dismiss { id } { ok, notices }: what is left
|
|
7
|
+
//
|
|
8
|
+
// When the launches of one browser profile fail several times in a row (lib/morelogin-launch-recovery.js: two, after
|
|
9
|
+
// whatever restart SynaBun tried), the owner is told once: which profile, the error, what SynaBun did and what fixes
|
|
10
|
+
// it. Before 2026-11-29 nothing said so: on 2026-11-28 every schedule of one group failed for 40 hours, each with its
|
|
11
|
+
// own "Schedule failed" toast on a page nobody had open. The owner's pages ask when they load and every time their
|
|
12
|
+
// sync socket connects (public/shared/ui-launch-block-notice.js) and are told of a change at once
|
|
13
|
+
// (`schedule:launch-blocked` on the sync socket, which invite guests never get). A notice goes when a launch on the
|
|
14
|
+
// profile works again, or when the owner dismisses it (not shown again for that streak of failures).
|
|
15
|
+
//
|
|
16
|
+
// The owner's only, like the crash notice (lib/crash-notice-api.js): /api/system is admin-only
|
|
17
|
+
// (lib/request-gate.js), every route takes the owner's guard by itself and refuses an agent's request (uiOnly), and
|
|
18
|
+
// the dismissal is the owner's write from SynaBun's own page (X-SynaBun-UI: 1, a JSON body, this boot's page secret).
|
|
19
|
+
// A request names a notice's id, never a profile or a path.
|
|
20
|
+
|
|
21
|
+
import { Router } from 'express';
|
|
22
|
+
import { sendGuardError, uiOnly } from './http-guards.js';
|
|
23
|
+
|
|
24
|
+
const ID = /^[0-9a-f]{16,32}$/;
|
|
25
|
+
const KINDS = new Set(['guard-timeout', 'browser-unresponsive']);
|
|
26
|
+
const FIXES = new Set(['restart', 'start-limit', 'check']);
|
|
27
|
+
const OUTCOMES = new Set(['restarted', 'restarted-ok', 'restarted-retry-failed', 'stop-failed', 'start-failed']);
|
|
28
|
+
const line = (value, max) => (typeof value === 'string' ? value.replace(/[\u0000-\u001f]+/g, ' ').trim().slice(0, max) : '');
|
|
29
|
+
const time = (value) => (Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : null);
|
|
30
|
+
|
|
31
|
+
/** A notice as a page is shown it, field by field; null for anything that is not one. */
|
|
32
|
+
export function launchBlockNoticeOf(notice) {
|
|
33
|
+
if (!notice || typeof notice !== 'object' || typeof notice.id !== 'string' || !ID.test(notice.id)) return null;
|
|
34
|
+
const envId = line(String(notice.envId ?? ''), 128);
|
|
35
|
+
if (!envId) return null;
|
|
36
|
+
const recovery = notice.recovery && typeof notice.recovery === 'object' && OUTCOMES.has(notice.recovery.outcome) && time(notice.recovery.at)
|
|
37
|
+
? { at: time(notice.recovery.at), outcome: notice.recovery.outcome } : null;
|
|
38
|
+
return {
|
|
39
|
+
id: notice.id, envId, name: line(notice.name, 200) || null,
|
|
40
|
+
count: Number.isInteger(notice.count) && notice.count > 0 ? Math.min(notice.count, 9999) : 1,
|
|
41
|
+
firstAt: time(notice.firstAt), lastAt: time(notice.lastAt),
|
|
42
|
+
error: line(notice.error, 600), code: line(notice.code, 64) || null,
|
|
43
|
+
kind: KINDS.has(notice.kind) ? notice.kind : null,
|
|
44
|
+
fix: FIXES.has(notice.fix) ? notice.fix : 'check',
|
|
45
|
+
launches: (Array.isArray(notice.launches) ? notice.launches : []).map((name) => line(name, 120)).filter(Boolean).slice(0, 5),
|
|
46
|
+
recovery,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {object} deps
|
|
52
|
+
* @param {() => { notices(): object[], dismiss(id: string): boolean }} deps.recovery lib/morelogin-launch-recovery.js
|
|
53
|
+
* (read at each request: server.js makes it after the first routes are mounted)
|
|
54
|
+
* @param {import('express').RequestHandler} deps.guard the owner's guard (lib/http-guards.js ownerRouteGuard)
|
|
55
|
+
* @param {{ verify(req): boolean, require: import('express').RequestHandler }} [deps.pageSession] lib/page-session.js:
|
|
56
|
+
* the page secret a dismissal carries (without one, as in a unit test, none is asked)
|
|
57
|
+
*/
|
|
58
|
+
export function createLaunchBlockApi({ recovery, guard, pageSession = null, log = () => {} } = {}) {
|
|
59
|
+
if (typeof recovery !== 'function' || typeof guard !== 'function') throw new Error('createLaunchBlockApi needs the launch recovery and the owner\'s guard');
|
|
60
|
+
const router = Router();
|
|
61
|
+
const current = () => {
|
|
62
|
+
try { return (recovery()?.notices?.() || []).map(launchBlockNoticeOf).filter(Boolean); } catch { return []; }
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
router.use(guard, uiOnly, (req, res, next) => { res.set('Cache-Control', 'no-store'); next(); });
|
|
66
|
+
|
|
67
|
+
router.get('/', (req, res) => { res.json({ ok: true, notices: current() }); });
|
|
68
|
+
|
|
69
|
+
router.post('/dismiss', (req, res, next) => {
|
|
70
|
+
if (req.get('x-synabun-ui') !== '1') return sendGuardError(res, 403, 'UI_HEADER_REQUIRED', 'A notice is dismissed from SynaBun\'s own page.');
|
|
71
|
+
// The page secret: what a local process that merely sends the page's headers lacks.
|
|
72
|
+
if (pageSession && !pageSession.verify(req)) return pageSession.require(req, res, next);
|
|
73
|
+
next();
|
|
74
|
+
}, (req, res) => {
|
|
75
|
+
if (!req.is('application/json')) return res.status(415).json({ ok: false, code: 'JSON_REQUIRED', error: 'Send JSON.' });
|
|
76
|
+
const id = req.body?.id;
|
|
77
|
+
if (typeof id !== 'string' || !ID.test(id)) return res.status(400).json({ ok: false, code: 'BAD_REQUEST', error: 'Send { id } of the notice.' });
|
|
78
|
+
let dismissed = false;
|
|
79
|
+
try { dismissed = recovery()?.dismiss?.(id) === true; } catch { dismissed = false; }
|
|
80
|
+
if (dismissed) log(`[launch-block] dismissed ${id}`);
|
|
81
|
+
// The recovery announces the change itself (`schedule:launch-blocked`); every other window drops it then.
|
|
82
|
+
res.json({ ok: true, notices: current() });
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return router;
|
|
86
|
+
}
|