synabun 2.2.0 → 2.2.2
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 +45 -0
- package/README.md +1 -1
- package/hooks/claude-code/pre-websearch.mjs +4 -1
- package/hooks/claude-code/prompt-submit.mjs +7 -0
- package/lib/release-scan.mjs +23 -10
- package/lib/virustotal.mjs +143 -39
- package/mcp-server/dist/http.d.ts +19 -0
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +55 -13
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +14 -9
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.d.ts +118 -0
- package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
- package/mcp-server/dist/services/browser-route-flow.js +339 -0
- package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
- package/mcp-server/dist/services/desktop-client.js +2 -2
- package/mcp-server/dist/services/desktop-client.js.map +1 -1
- package/mcp-server/dist/services/identity.d.ts +66 -3
- package/mcp-server/dist/services/identity.d.ts.map +1 -1
- package/mcp-server/dist/services/identity.js +61 -4
- package/mcp-server/dist/services/identity.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +112 -1
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +555 -61
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/tools/bluesky.d.ts +20 -7
- package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
- package/mcp-server/dist/tools/bluesky.js +147 -45
- package/mcp-server/dist/tools/bluesky.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +11 -2
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +131 -18
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
- package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
- package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
- package/mcp-server/dist/tools/morelogin.js +4 -2
- package/mcp-server/dist/tools/morelogin.js.map +1 -1
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
- package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +58 -12
- package/mcp-server/src/index.ts +15 -9
- package/mcp-server/src/services/browser-route-flow.ts +402 -0
- package/mcp-server/src/services/desktop-client.ts +2 -2
- package/mcp-server/src/services/identity.ts +80 -4
- package/mcp-server/src/services/neural-interface.ts +572 -70
- package/mcp-server/src/tools/bluesky.ts +164 -51
- package/mcp-server/src/tools/browser-advanced.ts +121 -17
- package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
- package/mcp-server/src/tools/morelogin.ts +4 -2
- package/mcp-server/src/tools/youtube/helpers.ts +2 -2
- package/neural-interface/i18n/en.json +27 -0
- package/neural-interface/i18n/pt-BR.json +27 -0
- package/neural-interface/lib/assistant-api.js +64 -23
- package/neural-interface/lib/assistant-brains/codex.js +6 -1
- package/neural-interface/lib/assistant-catalog.js +20 -2
- package/neural-interface/lib/assistant-dispatch.js +31 -2
- package/neural-interface/lib/assistant-persona.js +1 -0
- package/neural-interface/lib/assistant-runtime.js +15 -1
- package/neural-interface/lib/assistant-tools.js +10 -1
- package/neural-interface/lib/browser-automation-routes.js +84 -0
- package/neural-interface/lib/browser-execution.js +16 -3
- package/neural-interface/lib/browser-owner.js +48 -0
- package/neural-interface/lib/browser-session-close.js +84 -0
- package/neural-interface/lib/browser-start-handoff.js +202 -0
- package/neural-interface/lib/browser-tool-policy.js +21 -4
- package/neural-interface/lib/browser-wedge-retire.js +64 -0
- package/neural-interface/lib/claude-agent-bridge.js +36 -1
- package/neural-interface/lib/claude-background-hold.js +239 -0
- package/neural-interface/lib/exec-loop-command.js +8 -0
- package/neural-interface/lib/http-guards.js +11 -6
- package/neural-interface/lib/loop-logger.js +6 -1
- package/neural-interface/lib/mcp-external-servers.js +64 -13
- package/neural-interface/lib/native-loop-providers.js +122 -10
- package/neural-interface/lib/native-loop-runtime.js +112 -11
- package/neural-interface/lib/opencode-native-boundary.js +155 -21
- package/neural-interface/lib/owner-authority.js +113 -37
- package/neural-interface/lib/page-session.js +81 -23
- package/neural-interface/lib/peer-identity.js +311 -47
- package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
- package/neural-interface/lib/pty-host/core.js +36 -0
- package/neural-interface/lib/pty-host/protocol.js +2 -0
- package/neural-interface/lib/skills/api-v2.js +13 -2
- package/neural-interface/lib/skills/creation-api.js +3 -1
- package/neural-interface/lib/skills/evals-api.js +5 -1
- package/neural-interface/lib/social-write-pacing.js +151 -0
- package/neural-interface/lib/terminal-token-redaction.js +293 -0
- package/neural-interface/lib/terminal-tokens.js +359 -0
- package/neural-interface/lib/worker-mcp-channel.js +45 -10
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/shared/agy/agy-render.js +41 -1
- package/neural-interface/public/shared/agy/agy-styles.js +5 -0
- package/neural-interface/public/shared/api.js +1 -0
- package/neural-interface/public/shared/assistant/asst-api.js +14 -2
- package/neural-interface/public/shared/assistant/asst-computer.js +73 -4
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +80 -0
- package/neural-interface/public/shared/assistant/asst-panel.js +8 -4
- package/neural-interface/public/shared/assistant/asst-render.js +72 -11
- package/neural-interface/public/shared/assistant/asst-scene-styles.js +55 -23
- package/neural-interface/public/shared/assistant/asst-scenes.js +225 -79
- package/neural-interface/public/shared/assistant/asst-sidepanel-styles.js +4 -4
- package/neural-interface/public/shared/assistant/asst-style-cache.js +44 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +26 -5
- package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
- package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
- package/neural-interface/public/shared/cp/cp-agents.js +8 -0
- package/neural-interface/public/shared/cp/cp-permissions.js +18 -2
- package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
- package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
- package/neural-interface/public/shared/judgments-log-origins.js +29 -0
- package/neural-interface/public/shared/loading-teardown.js +34 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +6 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +5 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +16 -86
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +6 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +88 -72
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
- package/neural-interface/public/shared/owner-access.js +134 -0
- package/neural-interface/public/shared/owner-authority-view.js +92 -0
- package/neural-interface/public/shared/page-session.js +143 -14
- package/neural-interface/public/shared/poll-backoff.js +59 -0
- package/neural-interface/public/shared/settings/settings-data.js +6 -1
- package/neural-interface/public/shared/settings/settings-kit.js +11 -3
- package/neural-interface/public/shared/settings/settings-shell.js +7 -0
- package/neural-interface/public/shared/shown-children.js +72 -0
- package/neural-interface/public/shared/static-bg-state.js +22 -0
- package/neural-interface/public/shared/storage-retry.js +47 -0
- package/neural-interface/public/shared/storage.js +25 -4
- package/neural-interface/public/shared/styles.css +109 -8
- package/neural-interface/public/shared/synabun-mascot.js +27 -8
- package/neural-interface/public/shared/synabun-ticker.js +147 -12
- package/neural-interface/public/shared/synabun-tools.js +173 -0
- package/neural-interface/public/shared/tool-heartbeat.js +43 -0
- package/neural-interface/public/shared/tool-list-picker.js +3 -1
- package/neural-interface/public/shared/tool-list-view.js +23 -4
- package/neural-interface/public/shared/ui-automation-studio.js +8 -1
- package/neural-interface/public/shared/ui-claude-panel.js +238 -90
- package/neural-interface/public/shared/ui-judgments.js +37 -10
- package/neural-interface/public/shared/ui-loading.js +5 -4
- package/neural-interface/public/shared/ui-navbar.js +6 -0
- package/neural-interface/public/shared/ui-owner-access.js +191 -0
- package/neural-interface/public/shared/ui-owner-authority.js +162 -0
- package/neural-interface/public/shared/ui-sessions.js +45 -16
- package/neural-interface/public/shared/ui-settings.js +86 -15
- package/neural-interface/public/shared/ui-terminal.js +15 -7
- package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
- package/neural-interface/public/shared/ui-update.js +3 -0
- package/neural-interface/public/shared/ui-whiteboard.js +4 -0
- package/neural-interface/public/shared/window-keys.js +38 -0
- package/neural-interface/server.js +1240 -238
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun Neural Interface — the banner of a degraded owner authority: what it says
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// On macOS the server tells the owner's own page from every other local program by the process at the other end of
|
|
6
|
+
// the connection (lib/peer-identity.js). When it cannot look that process up (netstat or ps missing, denied because
|
|
7
|
+
// the server was started inside a sandbox, slow past its cap), it proves nothing about who is asking and pauses the
|
|
8
|
+
// owner's actions: no page secret, and the owner's writes, reads and sockets answer 503 PEER_UNAVAILABLE. GET
|
|
9
|
+
// /api/health says so (`ownerAuthority: { state: 'degraded', reason, retryable, since }`), and so does every 503
|
|
10
|
+
// PEER_UNAVAILABLE a request of the page gets (public/shared/page-session.js turns it into the
|
|
11
|
+
// `synabun:peer-unavailable` event). This module decides the words of the banner; ui-owner-authority.js asks the
|
|
12
|
+
// server, listens and draws them. `unsupported` (Windows, Linux) and `off` (SYNABUN_PEER_IDENTITY=off) show nothing:
|
|
13
|
+
// there the rules from before apply and nothing is paused.
|
|
14
|
+
//
|
|
15
|
+
// No imports and no DOM: `node --test` loads this file as it is (tests/owner-authority-notice.test.mjs).
|
|
16
|
+
// OWNER_AUTHORITY_NOTICE_COPY is the English of every sentence; `ownerAuthorityNotice.*` in i18n/en.json must equal
|
|
17
|
+
// it and i18n/pt-BR.json must have the same keys.
|
|
18
|
+
|
|
19
|
+
export const OWNER_AUTHORITY_NOTICE_COPY = Object.freeze({
|
|
20
|
+
label: 'Owner actions paused',
|
|
21
|
+
title: 'SynaBun can\'t verify which program is calling it, so the owner\'s actions are paused.',
|
|
22
|
+
body: 'Settings, files, terminals, the agent panels and dispatching are refused until the check works again. Pages and memories still load.',
|
|
23
|
+
reason: 'Reason: {reason}',
|
|
24
|
+
hint: 'If this persists, start SynaBun outside any sandbox, or add SYNABUN_PEER_IDENTITY=off to ~/.synabun/.env and restart SynaBun (this turns the check off).',
|
|
25
|
+
reload: 'Reload to retry',
|
|
26
|
+
dismiss: 'Dismiss',
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
/** The states GET /api/health can name (lib/peer-identity.js authorityState). */
|
|
30
|
+
export const OWNER_AUTHORITY_STATES = Object.freeze(['ok', 'degraded', 'unsupported', 'off']);
|
|
31
|
+
/** The longest reason the banner shows (the server's reasons are short; a longer one is cut). */
|
|
32
|
+
export const REASON_MAX = 200;
|
|
33
|
+
|
|
34
|
+
/** A sentence of OWNER_AUTHORITY_NOTICE_COPY in English with its {values} filled; an unknown key is itself. */
|
|
35
|
+
export function ownerAuthorityText(key, params = {}) {
|
|
36
|
+
const template = OWNER_AUTHORITY_NOTICE_COPY[key];
|
|
37
|
+
if (typeof template !== 'string') return key;
|
|
38
|
+
return template.replace(/\{(\w+)\}/g, (whole, name) => (params[name] != null ? String(params[name]) : whole));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const cleanReason = (value) => {
|
|
42
|
+
const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
43
|
+
return text.length > REASON_MAX ? `${text.slice(0, REASON_MAX - 1)}…` : text;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The owner authority a GET /api/health answer reports, or null (an older server says nothing, a body that is not
|
|
48
|
+
* one): { state, reason, retryable, since }.
|
|
49
|
+
*/
|
|
50
|
+
export function readOwnerAuthority(health) {
|
|
51
|
+
const raw = health && typeof health === 'object' ? health.ownerAuthority : null;
|
|
52
|
+
if (!raw || typeof raw !== 'object' || !OWNER_AUTHORITY_STATES.includes(raw.state)) return null;
|
|
53
|
+
return {
|
|
54
|
+
state: raw.state,
|
|
55
|
+
reason: cleanReason(raw.reason) || null,
|
|
56
|
+
retryable: raw.retryable === true,
|
|
57
|
+
since: typeof raw.since === 'string' ? raw.since : null,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The state a 503 PEER_UNAVAILABLE answer stands for (the event's detail, or the answer's body). */
|
|
62
|
+
export function unavailableAuthority(detail) {
|
|
63
|
+
return { state: 'degraded', reason: cleanReason(detail?.reason) || null, retryable: detail?.retryable === true, since: null };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* What the banner shows for a state, or null when it shows nothing (ok, unsupported, off, nothing known).
|
|
68
|
+
* `t(key, params)` is the page's translator for `ownerAuthorityNotice.*` (English by default).
|
|
69
|
+
* → { key, label, title, body, reason, hint, actions: [{ id: 'reload'|'dismiss', label }] }. `key` is what a
|
|
70
|
+
* dismissal is remembered by: the same outage stays dismissed, a new reason shows again.
|
|
71
|
+
*/
|
|
72
|
+
export function ownerAuthorityNoticeView(authority, { t = ownerAuthorityText } = {}) {
|
|
73
|
+
if (!authority || authority.state !== 'degraded') return null;
|
|
74
|
+
// (a translator that does not know a key answers the key itself, short or as its whole path: English then)
|
|
75
|
+
const say = (key, params) => {
|
|
76
|
+
try {
|
|
77
|
+
const text = t(key, params);
|
|
78
|
+
return typeof text === 'string' && text && text !== key && !text.endsWith(`.${key}`) ? text : ownerAuthorityText(key, params);
|
|
79
|
+
} catch { return ownerAuthorityText(key, params); }
|
|
80
|
+
};
|
|
81
|
+
const reason = cleanReason(authority.reason);
|
|
82
|
+
return {
|
|
83
|
+
key: `degraded:${reason || 'unknown'}`,
|
|
84
|
+
label: say('label'),
|
|
85
|
+
title: say('title'),
|
|
86
|
+
body: say('body'),
|
|
87
|
+
reason: reason ? say('reason', { reason }) : '',
|
|
88
|
+
// A failure that may pass by itself (a timeout) is what a reload cures; one that does not needs the way out.
|
|
89
|
+
hint: authority.retryable ? '' : say('hint'),
|
|
90
|
+
actions: [{ id: 'reload', label: say('reload') }, { id: 'dismiss', label: say('dismiss') }],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -10,17 +10,51 @@
|
|
|
10
10
|
// page's fetch once: when a same-origin write is refused with one of those two codes, it asks GET /api/page-session
|
|
11
11
|
// (which sets this boot's cookie), then sends the very same request once more and hands back that answer. No
|
|
12
12
|
// reload, no toast (the toast fires on the error jsonFetch throws, and it throws only on the final answer), no lost
|
|
13
|
-
// action.
|
|
14
|
-
//
|
|
13
|
+
// action. A read is recovered the same way when it is refused 403 PAGE_SECRET_REQUIRED: since 2026-11-04 the browser
|
|
14
|
+
// routes (/api/browser/*) ask every request of the page for this boot's secret, reads included, so the browser panel
|
|
15
|
+
// and the browser settings keep working across a restart. Anything else (a read refused UI_ONLY, another 403, a refusal
|
|
16
|
+
// the refresh did not cure, a body that cannot be sent twice) is handed back as it came, so nothing changes for a
|
|
17
|
+
// request this is not about. refreshPageSession() asks for this boot's cookie by itself (one request at a time): the
|
|
18
|
+
// browser panel calls it before it opens its socket again, because a WebSocket refused for a stale cookie never says why.
|
|
15
19
|
//
|
|
16
20
|
// No imports and nothing done at load under Node: tests load it with node --test and a fake fetch. In a browser it
|
|
17
21
|
// installs itself on window.fetch when the page loads it (index.html, index2d.html and sidepanel-session.html load
|
|
18
22
|
// it as their first module script, before any module that writes), and once only.
|
|
23
|
+
//
|
|
24
|
+
// 503 PEER_UNAVAILABLE is something else: the server could not tell which program sent the request (macOS, its
|
|
25
|
+
// lookup of the calling process failed: lib/peer-identity.js), so it hands out no page secret and refuses the owner's
|
|
26
|
+
// actions until a lookup works again. Nothing here cures that, so nothing is retried: the answer goes back as it came,
|
|
27
|
+
// and the page is told once per answer (the `synabun:peer-unavailable` event on the window, which
|
|
28
|
+
// ui-owner-authority.js turns into its banner). A refresh that met it (GET /api/page-session answered 503) is not asked
|
|
29
|
+
// again for a few seconds: a burst of refused writes costs the server one lookup, not one each.
|
|
30
|
+
//
|
|
31
|
+
// A refusal nothing here cures (403 WORKER_BROWSER, OWNER_ROUTE, or PAGE_SECRET_REQUIRED the refresh did not cure) is
|
|
32
|
+
// the page not having the owner's access at all: SynaBun's automation browser opened it, by design. The answer still
|
|
33
|
+
// goes back as it came; the page is told (`synabun:owner-access-refused` on the window, which ui-owner-access.js turns
|
|
34
|
+
// into one banner and each panel into "No access" instead of an empty list or default values). A refresh that gets
|
|
35
|
+
// this boot's secret is told too (`synabun:owner-access-restored`).
|
|
19
36
|
|
|
20
37
|
/** The route that hands an open tab this boot's cookie (lib/page-session.js PAGE_SECRET_REFRESH_PATH). */
|
|
21
38
|
export const PAGE_SECRET_REFRESH_PATH = '/api/page-session';
|
|
22
39
|
/** The refusals that mean "the page secret is missing or stale", and nothing else. */
|
|
23
40
|
export const PAGE_SECRET_CODES = Object.freeze(['UI_ONLY', 'PAGE_SECRET_REQUIRED']);
|
|
41
|
+
/** The answer that means "the server could not identify the caller" (lib/owner-authority.js PEER_UNAVAILABLE). */
|
|
42
|
+
export const PEER_UNAVAILABLE_CODE = 'PEER_UNAVAILABLE';
|
|
43
|
+
/** The window event a 503 PEER_UNAVAILABLE becomes (detail: { reason, retryable, error, url, method }). */
|
|
44
|
+
export const PEER_UNAVAILABLE_EVENT = 'synabun:peer-unavailable';
|
|
45
|
+
/** How long a refresh that met 503 PEER_UNAVAILABLE is not asked again. */
|
|
46
|
+
export const REFRESH_COOLDOWN_MS = 5000;
|
|
47
|
+
/**
|
|
48
|
+
* The final refusals that mean "this page does not have the owner's access" (after any recovery here was tried):
|
|
49
|
+
* WORKER_BROWSER (SynaBun's automation browser: never the owner), PAGE_SECRET_REQUIRED (no secret, and the refresh
|
|
50
|
+
* did not cure it), OWNER_ROUTE (a route the owner's page only reaches). Told once per answer to `onRefused`, which
|
|
51
|
+
* the window turns into OWNER_ACCESS_REFUSED_EVENT (ui-owner-access.js: the banner and the panels' "No access").
|
|
52
|
+
*/
|
|
53
|
+
export const OWNER_ACCESS_CODES = Object.freeze(['WORKER_BROWSER', 'PAGE_SECRET_REQUIRED', 'OWNER_ROUTE']);
|
|
54
|
+
/** The window event a final owner refusal becomes (detail: { code, url, method, status }). */
|
|
55
|
+
export const OWNER_ACCESS_REFUSED_EVENT = 'synabun:owner-access-refused';
|
|
56
|
+
/** The window event a refresh that got this boot's page secret becomes (detail: {}): the page is the owner's again. */
|
|
57
|
+
export const OWNER_ACCESS_RESTORED_EVENT = 'synabun:owner-access-restored';
|
|
24
58
|
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
25
59
|
|
|
26
60
|
/** Whether an answer is the server refusing a write for want of this boot's page secret. */
|
|
@@ -28,6 +62,16 @@ export function isPageSecretRefusal(status, body) {
|
|
|
28
62
|
return Number(status) === 403 && !!body && typeof body === 'object' && PAGE_SECRET_CODES.includes(body.code);
|
|
29
63
|
}
|
|
30
64
|
|
|
65
|
+
/** Whether an answer is a final refusal of the owner's access (403 with one of OWNER_ACCESS_CODES). */
|
|
66
|
+
export function isOwnerAccessRefusal(status, body) {
|
|
67
|
+
return Number(status) === 403 && !!body && typeof body === 'object' && OWNER_ACCESS_CODES.includes(body.code);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Whether an answer is the server saying it could not identify the caller (never retried here). */
|
|
71
|
+
export function isPeerUnavailable(status, body) {
|
|
72
|
+
return Number(status) === 503 && !!body && typeof body === 'object' && body.code === PEER_UNAVAILABLE_CODE;
|
|
73
|
+
}
|
|
74
|
+
|
|
31
75
|
/**
|
|
32
76
|
* What a request is, for the retry: its method, whether it is same-origin, and the arguments that send it again,
|
|
33
77
|
* or null when it is not a write, goes elsewhere, or cannot be sent twice (a streamed body).
|
|
@@ -45,52 +89,137 @@ export function replayPlan(input, init, origin = null) {
|
|
|
45
89
|
return { method, url, args: init === undefined ? [again] : [again, init] };
|
|
46
90
|
}
|
|
47
91
|
|
|
92
|
+
/** The same for a read (GET / HEAD of this origin): sent again only when it was refused for the page secret. */
|
|
93
|
+
export function readReplayPlan(input, init, origin = null) {
|
|
94
|
+
const isRequest = typeof Request !== 'undefined' && input instanceof Request;
|
|
95
|
+
const method = String(init?.method || (isRequest ? input.method : '') || 'GET').toUpperCase();
|
|
96
|
+
if (method !== 'GET' && method !== 'HEAD') return null;
|
|
97
|
+
const url = isRequest ? input.url : (input instanceof URL ? input.href : String(input ?? ''));
|
|
98
|
+
if (!sameOrigin(url, origin)) return null;
|
|
99
|
+
const again = isRequest ? input.clone() : input;
|
|
100
|
+
return { method, url, read: true, args: init === undefined ? [again] : [again, init] };
|
|
101
|
+
}
|
|
102
|
+
|
|
48
103
|
function sameOrigin(url, origin) {
|
|
49
104
|
if (!/^[a-z][a-z0-9+.-]*:/i.test(url) && !url.startsWith('//')) return true; // a path of this page
|
|
50
105
|
if (!origin) return false;
|
|
51
106
|
try { return new URL(url).origin === new URL(origin).origin; } catch { return false; }
|
|
52
107
|
}
|
|
53
108
|
|
|
109
|
+
/** A request's URL and method as given to fetch (for the event's detail). */
|
|
110
|
+
function describeRequest(input, init) {
|
|
111
|
+
const isRequest = typeof Request !== 'undefined' && input instanceof Request;
|
|
112
|
+
const method = String(init?.method || (isRequest ? input.method : '') || 'GET').toUpperCase();
|
|
113
|
+
const url = isRequest ? input.url : (input instanceof URL ? input.href : String(input ?? ''));
|
|
114
|
+
return { method, url };
|
|
115
|
+
}
|
|
116
|
+
|
|
54
117
|
/**
|
|
55
118
|
* A fetch over `fetchImpl` that recovers the page secret once: the refresh is one request at a time (writes refused
|
|
56
119
|
* together share it), the refused request is sent again only when the refresh answered, and the second answer is
|
|
57
|
-
* final whatever it says.
|
|
120
|
+
* final whatever it says. A 503 PEER_UNAVAILABLE (a write's, a read's, or the refresh's) is never retried: it is handed
|
|
121
|
+
* back as it came and told to `onUnavailable` ({ reason, retryable, error, url, method }); after the refresh met one,
|
|
122
|
+
* refused writes are handed back without a refresh for `cooldownMs`.
|
|
58
123
|
*/
|
|
59
|
-
export function createPageSessionFetch(fetchImpl, { refreshPath = PAGE_SECRET_REFRESH_PATH, origin = null, onRecover = null } = {}) {
|
|
124
|
+
export function createPageSessionFetch(fetchImpl, { refreshPath = PAGE_SECRET_REFRESH_PATH, origin = null, onRecover = null, onUnavailable = null, onRefused = null, onRestored = null, cooldownMs = REFRESH_COOLDOWN_MS, now = () => Date.now() } = {}) {
|
|
60
125
|
if (typeof fetchImpl !== 'function') throw new TypeError('createPageSessionFetch needs a fetch');
|
|
61
126
|
let refreshing = null;
|
|
127
|
+
let quietUntil = 0;
|
|
128
|
+
const tell = (body, request) => {
|
|
129
|
+
try { onUnavailable?.({ reason: typeof body?.reason === 'string' ? body.reason : '', retryable: body?.retryable === true, error: typeof body?.error === 'string' ? body.error : '', url: request.url, method: request.method }); } catch { /* a listener's own error */ }
|
|
130
|
+
};
|
|
131
|
+
const tellRefused = (body, request, status = 403) => {
|
|
132
|
+
try { onRefused?.({ code: body.code, url: request.url, method: request.method, status }); } catch { /* a listener's own error */ }
|
|
133
|
+
};
|
|
134
|
+
/** Read a 403 answer's body and tell it when it is a final owner refusal (the answer itself is untouched). */
|
|
135
|
+
async function noteRefused(res, request) {
|
|
136
|
+
if (!onRefused || !res || res.status !== 403 || typeof res.clone !== 'function') return res;
|
|
137
|
+
let body = null;
|
|
138
|
+
try { body = await res.clone().json(); } catch { return res; }
|
|
139
|
+
if (isOwnerAccessRefusal(res.status, body)) tellRefused(body, request);
|
|
140
|
+
return res;
|
|
141
|
+
}
|
|
142
|
+
/** Read a 503 answer's body and tell it when it is PEER_UNAVAILABLE (the answer itself is untouched). */
|
|
143
|
+
async function noteUnavailable(res, request) {
|
|
144
|
+
if (!res || res.status !== 503 || typeof res.clone !== 'function') return false;
|
|
145
|
+
let body = null;
|
|
146
|
+
try { body = await res.clone().json(); } catch { return false; }
|
|
147
|
+
if (!isPeerUnavailable(res.status, body)) return false;
|
|
148
|
+
tell(body, request);
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
62
151
|
function refreshCookie() {
|
|
152
|
+
if (now() < quietUntil) return Promise.resolve(false);
|
|
63
153
|
if (!refreshing) {
|
|
64
154
|
refreshing = (async () => {
|
|
65
155
|
try {
|
|
66
156
|
const res = await fetchImpl(refreshPath, { method: 'GET', credentials: 'same-origin', cache: 'no-store', headers: { Accept: 'application/json' } });
|
|
67
|
-
|
|
157
|
+
if (await noteUnavailable(res, { url: refreshPath, method: 'GET' })) { quietUntil = now() + Math.max(0, Number(cooldownMs) || 0); return false; }
|
|
158
|
+
if (res && res.ok === true) { try { onRestored?.(); } catch { /* a listener's own error */ } return true; }
|
|
159
|
+
// The server refusing this page the secret itself (403 WORKER_BROWSER: the automation browser) is told too.
|
|
160
|
+
await noteRefused(res, { url: refreshPath, method: 'GET' });
|
|
161
|
+
return false;
|
|
68
162
|
} catch { return false; } finally { refreshing = null; }
|
|
69
163
|
})();
|
|
70
164
|
}
|
|
71
165
|
return refreshing;
|
|
72
166
|
}
|
|
73
|
-
|
|
74
|
-
const plan = replayPlan(input, init, origin);
|
|
167
|
+
async function pageSessionFetch(input, init) {
|
|
168
|
+
const plan = replayPlan(input, init, origin) || readReplayPlan(input, init, origin);
|
|
169
|
+
const request = describeRequest(input, init);
|
|
75
170
|
const res = await fetchImpl(input, init);
|
|
76
|
-
if (
|
|
171
|
+
if (res && res.status === 503) { await noteUnavailable(res, request); return res; }
|
|
172
|
+
if (!plan || !res || res.status !== 403 || typeof res.clone !== 'function') return noteRefused(res, request);
|
|
77
173
|
let body = null;
|
|
78
174
|
try { body = await res.clone().json(); } catch { return res; }
|
|
79
|
-
if (!isPageSecretRefusal(res.status, body)) return res;
|
|
80
|
-
|
|
175
|
+
if (!isPageSecretRefusal(res.status, body)) { if (isOwnerAccessRefusal(res.status, body)) tellRefused(body, request); return res; }
|
|
176
|
+
// A read is the page secret's business only when it says so (the browser routes): UI_ONLY on a read is handed back.
|
|
177
|
+
if (plan.read && body.code !== 'PAGE_SECRET_REQUIRED') return res;
|
|
178
|
+
if (!(await refreshCookie())) { if (isOwnerAccessRefusal(res.status, body)) tellRefused(body, request); return res; }
|
|
81
179
|
try { onRecover?.({ method: plan.method, url: plan.url, code: body.code }); } catch { /* a listener's own error */ }
|
|
82
|
-
|
|
83
|
-
|
|
180
|
+
const again = await fetchImpl(...plan.args);
|
|
181
|
+
if (again && again.status === 503) await noteUnavailable(again, { url: plan.url, method: plan.method });
|
|
182
|
+
return noteRefused(again, { url: plan.url, method: plan.method });
|
|
183
|
+
}
|
|
184
|
+
// The refresh by itself (one at a time, the same cooldown): true when the server handed this boot's cookie.
|
|
185
|
+
pageSessionFetch.refreshPageSession = () => refreshCookie();
|
|
186
|
+
return pageSessionFetch;
|
|
84
187
|
}
|
|
85
188
|
|
|
86
|
-
/** Wrap `target.fetch` (the window's) once; returns true when it did, false when it already had or there is none.
|
|
189
|
+
/** Wrap `target.fetch` (the window's) once; returns true when it did, false when it already had or there is none.
|
|
190
|
+
* A 503 PEER_UNAVAILABLE is dispatched on `target` as PEER_UNAVAILABLE_EVENT, a final owner refusal as
|
|
191
|
+
* OWNER_ACCESS_REFUSED_EVENT and a refresh that got the secret as OWNER_ACCESS_RESTORED_EVENT (when it can dispatch). */
|
|
87
192
|
export function installPageSessionRecovery(target = globalThis) {
|
|
88
193
|
if (!target || typeof target.fetch !== 'function' || target.__synabunPageSession) return false;
|
|
89
194
|
const original = target.fetch.bind(target);
|
|
90
195
|
const origin = target.location && typeof target.location.origin === 'string' ? target.location.origin : null;
|
|
91
|
-
|
|
196
|
+
const dispatch = (name, detail) => {
|
|
197
|
+
if (typeof target.dispatchEvent !== 'function' || typeof CustomEvent === 'undefined') return;
|
|
198
|
+
target.dispatchEvent(new CustomEvent(name, { detail }));
|
|
199
|
+
};
|
|
200
|
+
const onUnavailable = (detail) => dispatch(PEER_UNAVAILABLE_EVENT, detail);
|
|
201
|
+
// The last refusal is kept on the window too, for a module that listens only after it was told.
|
|
202
|
+
const onRefused = (detail) => { try { target.__synabunOwnerAccessRefused = detail; } catch { /* a frozen target */ } dispatch(OWNER_ACCESS_REFUSED_EVENT, detail); };
|
|
203
|
+
const onRestored = () => { try { delete target.__synabunOwnerAccessRefused; } catch { /* a frozen target */ } dispatch(OWNER_ACCESS_RESTORED_EVENT, {}); };
|
|
204
|
+
target.fetch = createPageSessionFetch(original, { origin, onUnavailable, onRefused, onRestored });
|
|
92
205
|
try { Object.defineProperty(target, '__synabunPageSession', { value: true, configurable: true }); } catch { target.__synabunPageSession = true; }
|
|
93
206
|
return true;
|
|
94
207
|
}
|
|
95
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Ask for this boot's page secret now (GET /api/page-session through the installed recovery: one request at a time,
|
|
211
|
+
* none during a cooldown after a 503). Resolves true when the server handed it, false otherwise; never rejects. For a
|
|
212
|
+
* socket the browser opens by itself (the browser panel's /ws/browser/:id), whose refusal for a stale cookie the page
|
|
213
|
+
* cannot read.
|
|
214
|
+
*/
|
|
215
|
+
export async function refreshPageSession(target = globalThis) {
|
|
216
|
+
try {
|
|
217
|
+
const refresh = target?.fetch?.refreshPageSession;
|
|
218
|
+
if (typeof refresh === 'function') return (await refresh()) === true;
|
|
219
|
+
if (typeof target?.fetch !== 'function') return false;
|
|
220
|
+
const res = await target.fetch(PAGE_SECRET_REFRESH_PATH, { method: 'GET', credentials: 'same-origin', cache: 'no-store', headers: { Accept: 'application/json' } });
|
|
221
|
+
return !!res && res.ok === true;
|
|
222
|
+
} catch { return false; }
|
|
223
|
+
}
|
|
224
|
+
|
|
96
225
|
if (typeof window !== 'undefined' && typeof document !== 'undefined') installPageSessionRecovery(window);
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun Neural Interface — one gate for a poller that several places share
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// A status poller (the Computer tray's GET /api/desktop/status, asst-computer.js) can run in every Assistant tab at
|
|
6
|
+
// once, each on its own timer. Through one gate they make at most one request at a time and one per interval, and a
|
|
7
|
+
// failure is not asked again at the same pace:
|
|
8
|
+
// • an answer: the next is due one interval later (less a little slack, so the timers that share it do not drift
|
|
9
|
+
// past each other);
|
|
10
|
+
// • a failure: the next is due after an exponential wait, capped (base · factor^failures, at most `maxMs`);
|
|
11
|
+
// • a refusal (the page has no owner access: owner-access.js): no more polling at all until `resume()`, which the
|
|
12
|
+
// page calls when something changed (it got the owner's page secret again, or it became visible again).
|
|
13
|
+
// A request the user asks for (Check again) does not ask the gate; its answer still counts.
|
|
14
|
+
//
|
|
15
|
+
// No DOM: `node --test` loads this file with a test clock (tests/poll-backoff.test.mjs).
|
|
16
|
+
|
|
17
|
+
export const POLL_BACKOFF_DEFAULTS = Object.freeze({ baseMs: 3000, maxMs: 5 * 60_000, factor: 2, slackMs: 250 });
|
|
18
|
+
|
|
19
|
+
/** The wait after `failures` failures in a row: the interval itself for none, then exponential, capped. */
|
|
20
|
+
export function backoffDelay(failures, { baseMs = POLL_BACKOFF_DEFAULTS.baseMs, maxMs = POLL_BACKOFF_DEFAULTS.maxMs, factor = POLL_BACKOFF_DEFAULTS.factor } = {}) {
|
|
21
|
+
const n = Math.max(0, Math.floor(Number(failures) || 0));
|
|
22
|
+
const base = Math.max(0, Number(baseMs) || 0);
|
|
23
|
+
const cap = Math.max(base, Number(maxMs) || 0);
|
|
24
|
+
if (n === 0) return base;
|
|
25
|
+
return Math.min(cap, base * Math.pow(Math.max(1, Number(factor) || 1), n));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createPollGate({ baseMs = POLL_BACKOFF_DEFAULTS.baseMs, maxMs = POLL_BACKOFF_DEFAULTS.maxMs, factor = POLL_BACKOFF_DEFAULTS.factor, slackMs = POLL_BACKOFF_DEFAULTS.slackMs, now = () => Date.now() } = {}) {
|
|
29
|
+
const opts = { baseMs, maxMs, factor };
|
|
30
|
+
let failures = 0;
|
|
31
|
+
let nextAt = 0;
|
|
32
|
+
let halted = null; // { code, reason } while a refusal stops the polling
|
|
33
|
+
let inFlight = false;
|
|
34
|
+
return {
|
|
35
|
+
/** Whether a timer's tick may send the request now. */
|
|
36
|
+
due() { return !halted && !inFlight && now() >= nextAt; },
|
|
37
|
+
/** A request leaves (timer or user). */
|
|
38
|
+
begin() { inFlight = true; },
|
|
39
|
+
/** It answered. */
|
|
40
|
+
succeed() {
|
|
41
|
+
inFlight = false;
|
|
42
|
+
failures = 0;
|
|
43
|
+
halted = null;
|
|
44
|
+
nextAt = now() + Math.max(0, baseMs - Math.max(0, slackMs));
|
|
45
|
+
},
|
|
46
|
+
/** It failed; `refusal` (owner-access.js) stops the polling until resume(). Returns the wait before the next. */
|
|
47
|
+
fail(refusal = null) {
|
|
48
|
+
inFlight = false;
|
|
49
|
+
failures += 1;
|
|
50
|
+
if (refusal) { halted = { code: refusal.code || null, reason: refusal.reason || null }; return Infinity; }
|
|
51
|
+
const wait = backoffDelay(failures, opts);
|
|
52
|
+
nextAt = now() + wait;
|
|
53
|
+
return wait;
|
|
54
|
+
},
|
|
55
|
+
/** Something changed (owner access back, the page visible again): due at once, from a clean slate. */
|
|
56
|
+
resume() { halted = null; failures = 0; nextAt = 0; },
|
|
57
|
+
snapshot() { return { failures, nextAt, halted, inFlight, waitMs: halted ? Infinity : Math.max(0, nextAt - now()) }; },
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -47,7 +47,12 @@ const caches = Object.fromEntries(Object.entries(SETTINGS_READS).map(([name, spe
|
|
|
47
47
|
load: async () => {
|
|
48
48
|
const res = await fetch(spec.url);
|
|
49
49
|
if (spec.raw) return { status: res.status, body: await res.json().catch(() => null) };
|
|
50
|
-
if (!res.ok)
|
|
50
|
+
if (!res.ok) {
|
|
51
|
+
// The status and the server's code stay with the error: a refusal of the owner's access (403 WORKER_BROWSER…)
|
|
52
|
+
// is "No access" in the modal, never an empty or default setting (owner-access.js refusalOfError).
|
|
53
|
+
const body = await res.json().catch(() => null);
|
|
54
|
+
throw Object.assign(new Error(`${spec.url}: HTTP ${res.status}`), { status: res.status, code: typeof body?.code === 'string' ? body.code : null });
|
|
55
|
+
}
|
|
51
56
|
return res.json();
|
|
52
57
|
},
|
|
53
58
|
accept: spec.raw ? (value) => value?.status >= 200 && value.status < 300 && !!value.body : spec.accept,
|
|
@@ -218,8 +218,14 @@ export function paneActive(overlay, paneId) {
|
|
|
218
218
|
* The status dot on a nav item. Several panes can share a page (WhatsApp and
|
|
219
219
|
* Discord on Messages), so each reports its own status and the page shows
|
|
220
220
|
* "connected" when any of them is. The word is also set for screen readers.
|
|
221
|
-
* @param {'connected'|'disconnected'|''} status
|
|
221
|
+
* @param {'connected'|'disconnected'|'refused'|''} status
|
|
222
222
|
*/
|
|
223
|
+
/** "No access" in the page's language (ownerAccess.navStatus; English when the key is missing). */
|
|
224
|
+
function noAccessWord() {
|
|
225
|
+
const text = t('ownerAccess.navStatus');
|
|
226
|
+
return typeof text === 'string' && text && text !== 'ownerAccess.navStatus' ? text : 'No access';
|
|
227
|
+
}
|
|
228
|
+
|
|
223
229
|
export function setNavStatus(overlay, paneId, status) {
|
|
224
230
|
const page = pageOfPane(paneId);
|
|
225
231
|
const nav = page && overlay.querySelector(`.settings-nav-item[data-tab="${page.id}"]`);
|
|
@@ -227,8 +233,10 @@ export function setNavStatus(overlay, paneId, status) {
|
|
|
227
233
|
const sources = nav._stgStatus || (nav._stgStatus = {});
|
|
228
234
|
if (status) sources[paneId] = status; else delete sources[paneId];
|
|
229
235
|
const values = Object.values(sources);
|
|
230
|
-
|
|
236
|
+
// 'refused': the page has no owner access, so the state is unknown (ui-owner-access.js): "No access", never "Off".
|
|
237
|
+
const next = values.includes('refused') ? 'refused' : values.includes('connected') ? 'connected' : values.includes('disconnected') ? 'disconnected' : '';
|
|
231
238
|
if (next) nav.dataset.status = next; else delete nav.dataset.status;
|
|
232
239
|
const word = nav.querySelector('.stg-nav-status-text');
|
|
233
|
-
|
|
240
|
+
const label = next === 'refused' ? noAccessWord() : next ? t(next === 'connected' ? 'settings.redesign.common.connected' : 'settings.redesign.common.off') : '';
|
|
241
|
+
if (word) word.textContent = label ? ` (${label})` : '';
|
|
234
242
|
}
|
|
@@ -15,11 +15,13 @@
|
|
|
15
15
|
import { sectionOpensByDefault } from './settings-ia.js';
|
|
16
16
|
import { searchSettings, runtimeSearchEntries, highlightParts, SEARCH_LIMIT, SEARCH_QUERY_MAX } from './settings-search.js';
|
|
17
17
|
import { tx, esc } from './settings-kit.js';
|
|
18
|
+
import { watchEmpty } from '../shown-children.js';
|
|
18
19
|
|
|
19
20
|
const TOGGLE_KEYS = new Set(['Enter', ' ']);
|
|
20
21
|
const KEY_ROLES = '[role="button"], [role="radio"], [role="switch"], [role="checkbox"], [role="tab"], [role="option"]';
|
|
21
22
|
const NATIVE_CONTROLS = 'button, a[href], input, select, textarea, summary';
|
|
22
23
|
const STATE_MIRRORS = '[data-stg-pressed], [data-stg-checked], [data-stg-selected]';
|
|
24
|
+
export const COLLAPSIBLE_BODY = '.stg-card[data-collapsible] > .stg-card-body';
|
|
23
25
|
|
|
24
26
|
// ── Sections: which ones the user left open ──
|
|
25
27
|
// One localStorage entry, { "<section id>": true | false }. A section the user never touched
|
|
@@ -217,6 +219,11 @@ export function wireSettingsShell(overlay, { activate }) {
|
|
|
217
219
|
observer.observe(content, { subtree: true, childList: true, attributes: true, attributeFilter: ['class'] });
|
|
218
220
|
overlay.addEventListener('settings-close', () => observer.disconnect());
|
|
219
221
|
|
|
222
|
+
// ── A collapsible card's body with nothing left to show says so (data-empty): styles.css drops its hairline
|
|
223
|
+
// and gap through that, never through a :has() (tests/css-has-performance.test.mjs) ──
|
|
224
|
+
const emptyBodies = watchEmpty(content, COLLAPSIBLE_BODY);
|
|
225
|
+
overlay.addEventListener('settings-close', () => emptyBodies.disconnect());
|
|
226
|
+
|
|
220
227
|
// ── A pane's save bar sits over the bottom of the scroll area: the scroller is told how tall it is,
|
|
221
228
|
// so a control that takes focus (or a deep link) never lands under the bar ──
|
|
222
229
|
const syncBarRoom = () => {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// A container that has nothing left to show says so: data-empty
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
// `data-empty` is on a container while none of its element children lacks the `hidden` attribute (no children at
|
|
5
|
+
// all included), and off as soon as one shows. CSS keys on it in place of `.x:not(:has(> :not([hidden])))`: that
|
|
6
|
+
// selector made Chromium re-check the page on every `hidden` toggle anywhere (~12 ms each on Windows), see
|
|
7
|
+
// tests/css-has-performance.test.mjs.
|
|
8
|
+
//
|
|
9
|
+
// syncEmpty(el) is for code that toggles the children itself (call it after the toggles); watchEmpty(root, selector)
|
|
10
|
+
// is for containers whose children many modules fill and toggle: one MutationObserver keeps every matching container
|
|
11
|
+
// true to its children. Mutation callbacks run before the next frame is drawn, so the page never shows a stale state.
|
|
12
|
+
// No imports: it runs under node --test with a stand-in DOM.
|
|
13
|
+
|
|
14
|
+
export const EMPTY_ATTR = 'data-empty';
|
|
15
|
+
|
|
16
|
+
/** Whether one of el's element children lacks the `hidden` attribute. */
|
|
17
|
+
export function hasShownChild(el) {
|
|
18
|
+
for (const child of el?.children || []) {
|
|
19
|
+
if (!child.hasAttribute('hidden')) return true;
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Puts data-empty on el, or takes it off, to match its children. Returns whether it is empty (false for no element). */
|
|
25
|
+
export function syncEmpty(el) {
|
|
26
|
+
if (!el || typeof el.hasAttribute !== 'function') return false;
|
|
27
|
+
const empty = !hasShownChild(el);
|
|
28
|
+
// Written only on a change: an observer of the attribute (or of the page's style) sees nothing otherwise.
|
|
29
|
+
if (el.hasAttribute(EMPTY_ATTR) !== empty) {
|
|
30
|
+
if (empty) el.setAttribute(EMPTY_ATTR, '');
|
|
31
|
+
else el.removeAttribute(EMPTY_ATTR);
|
|
32
|
+
}
|
|
33
|
+
return empty;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Keeps data-empty true on `root` (when it matches `selector`, or always when there is no selector) and on every
|
|
38
|
+
* descendant that matches `selector`, as children come, go and toggle `hidden`.
|
|
39
|
+
* @param {Element} root
|
|
40
|
+
* @param {string|null} [selector] the containers below root; null watches root alone
|
|
41
|
+
* @param {{ Observer?: typeof MutationObserver }} [opts]
|
|
42
|
+
* @returns {{ sync: () => void, disconnect: () => void }}
|
|
43
|
+
*/
|
|
44
|
+
export function watchEmpty(root, selector = null, { Observer = globalThis.MutationObserver } = {}) {
|
|
45
|
+
if (!root) return { sync() {}, disconnect() {} };
|
|
46
|
+
const isContainer = (el) => !!el && el.nodeType === 1
|
|
47
|
+
&& (el === root ? (!selector || el.matches(selector)) : (!!selector && el.matches(selector) && root.contains(el)));
|
|
48
|
+
const syncWithin = (node) => {
|
|
49
|
+
if (!node || node.nodeType !== 1) return;
|
|
50
|
+
if (isContainer(node)) syncEmpty(node);
|
|
51
|
+
if (selector) for (const el of node.querySelectorAll(selector)) syncEmpty(el);
|
|
52
|
+
};
|
|
53
|
+
const sync = () => syncWithin(root);
|
|
54
|
+
sync();
|
|
55
|
+
if (typeof Observer !== 'function') return { sync, disconnect() {} };
|
|
56
|
+
const observer = new Observer((records) => {
|
|
57
|
+
const touched = new Set();
|
|
58
|
+
for (const r of records) {
|
|
59
|
+
if (r.type === 'attributes') {
|
|
60
|
+
// A child's `hidden` changed: its parent is the container to check.
|
|
61
|
+
const parent = r.target.parentNode;
|
|
62
|
+
if (isContainer(parent)) touched.add(parent);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (isContainer(r.target)) touched.add(r.target);
|
|
66
|
+
if (selector) for (const node of r.addedNodes) syncWithin(node);
|
|
67
|
+
}
|
|
68
|
+
for (const el of touched) syncEmpty(el);
|
|
69
|
+
});
|
|
70
|
+
observer.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: ['hidden'] });
|
|
71
|
+
return { sync, disconnect: () => observer.disconnect() };
|
|
72
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Focus Mode's board (#static-bg) shown or hidden, with the same state on <html> as `static-bg-visible`.
|
|
2
|
+
//
|
|
3
|
+
// Rules outside the board need it (styles.css: the session pills keep clear of the whiteboard rail, the rail's show
|
|
4
|
+
// button exists only in Focus Mode). They used to read it with `:root:has(#static-bg.visible)` and
|
|
5
|
+
// `body:not(:has(#static-bg.visible))`; a :has() anchored on the root makes Chromium check the whole page again on
|
|
6
|
+
// every class change anywhere, which on the Windows desktop app cost tens of ms per change
|
|
7
|
+
// (tests/css-has-performance.test.mjs). No imports: tests/static-bg-state.test.mjs loads it under node.
|
|
8
|
+
|
|
9
|
+
export const STATIC_BG_ROOT_CLASS = 'static-bg-visible';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Show or hide the board and say so on the root. Without a board there is nothing showing, so the root class is
|
|
13
|
+
* cleared then too.
|
|
14
|
+
* @param {Element|null|undefined} staticBg #static-bg
|
|
15
|
+
* @param {boolean} visible
|
|
16
|
+
* @param {Element|null|undefined} [root] <html>
|
|
17
|
+
*/
|
|
18
|
+
export function setStaticBgVisible(staticBg, visible, root = globalThis.document?.documentElement) {
|
|
19
|
+
const on = !!staticBg && !!visible;
|
|
20
|
+
staticBg?.classList.toggle('visible', on);
|
|
21
|
+
root?.classList.toggle(STATIC_BG_ROOT_CLASS, on);
|
|
22
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// SynaBun — when storage.js tries a refused flush again. DOM-free (unit-tested under node --test).
|
|
2
|
+
//
|
|
3
|
+
// A failure that may pass by itself (network, 5xx, 408, 429) waits base·2^(attempt-1), capped, with full jitter in
|
|
4
|
+
// the upper half. A 401 / 403 is the server saying this client is not allowed: nothing is retried on a timer until
|
|
5
|
+
// something changes (a new write, the window regaining focus, the network coming back). Unsent values stay queued.
|
|
6
|
+
|
|
7
|
+
export const RETRY_BASE_MS = 1000;
|
|
8
|
+
export const RETRY_CAP_MS = 60_000;
|
|
9
|
+
|
|
10
|
+
/** Whether an HTTP status (or null for a network error) is a refusal that a timer will not fix. */
|
|
11
|
+
export function isAuthRefusal(status) {
|
|
12
|
+
return status === 401 || status === 403;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The wait before retry number `attempt` (1-based): between half and all of min(cap, base·2^(attempt-1)). */
|
|
16
|
+
export function retryDelay(attempt, { base = RETRY_BASE_MS, cap = RETRY_CAP_MS, random = Math.random } = {}) {
|
|
17
|
+
const n = Math.max(1, Math.floor(Number(attempt) || 1));
|
|
18
|
+
const ceiling = Math.min(cap, base * 2 ** Math.min(n - 1, 30));
|
|
19
|
+
const r = Math.min(1, Math.max(0, Number(random()) || 0));
|
|
20
|
+
return Math.round(ceiling / 2 + r * (ceiling / 2));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The retry state of one flusher. `fail(status)` → { blocked, delay } (delay null when blocked);
|
|
25
|
+
* `ok()` resets; `poke()` (a write or a reconnect) lifts a block and gives the wait the next try still owes.
|
|
26
|
+
*/
|
|
27
|
+
export function createRetryState({ base = RETRY_BASE_MS, cap = RETRY_CAP_MS, random = Math.random, now = () => Date.now() } = {}) {
|
|
28
|
+
let attempt = 0;
|
|
29
|
+
let blocked = false;
|
|
30
|
+
let notBefore = 0;
|
|
31
|
+
return {
|
|
32
|
+
get attempt() { return attempt; },
|
|
33
|
+
get blocked() { return blocked; },
|
|
34
|
+
fail(status) {
|
|
35
|
+
attempt++;
|
|
36
|
+
const delay = retryDelay(attempt, { base, cap, random });
|
|
37
|
+
notBefore = now() + delay;
|
|
38
|
+
blocked = isAuthRefusal(status);
|
|
39
|
+
return { blocked, delay: blocked ? null : delay };
|
|
40
|
+
},
|
|
41
|
+
ok() { attempt = 0; blocked = false; notBefore = 0; },
|
|
42
|
+
/** How long a flush asked for now must still wait (0 when none is owed). Lifts an auth block. */
|
|
43
|
+
poke() { blocked = false; return Math.max(0, notBefore - now()); },
|
|
44
|
+
/** How long a flush must still wait, without lifting a block (Infinity while blocked). */
|
|
45
|
+
wait() { return blocked ? Infinity : Math.max(0, notBefore - now()); },
|
|
46
|
+
};
|
|
47
|
+
}
|