synabun 2.4.0 → 2.4.1

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.
Files changed (72) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +25 -5
  4. package/browser-extension/engine.js +44 -13
  5. package/browser-extension/manifest.json +2 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +11 -5
  12. package/browser-extension/service-worker.js +8 -0
  13. package/docs/browser-extension-bridge.md +2 -2
  14. package/lib/data-home-files.js +45 -0
  15. package/lib/data-home-migration.js +34 -58
  16. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  17. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  18. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  19. package/mcp-server/dist/tools/agents.d.ts +3 -2
  20. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  21. package/mcp-server/dist/tools/agents.js +9 -7
  22. package/mcp-server/dist/tools/agents.js.map +1 -1
  23. package/mcp-server/package-lock.json +2 -2
  24. package/mcp-server/package.json +1 -1
  25. package/mcp-server/src/services/neural-interface.ts +1 -0
  26. package/mcp-server/src/tools/agents.ts +8 -6
  27. package/neural-interface/i18n/en.json +3 -1
  28. package/neural-interface/i18n/pt-BR.json +3 -1
  29. package/neural-interface/lib/agents/builtins.json +207 -0
  30. package/neural-interface/lib/agents/registry.js +60 -15
  31. package/neural-interface/lib/agents/resolve.js +69 -10
  32. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  33. package/neural-interface/lib/assistant-dispatch.js +127 -24
  34. package/neural-interface/lib/assistant-persona.js +1 -1
  35. package/neural-interface/lib/assistant-router.js +50 -7
  36. package/neural-interface/lib/assistant-runtime.js +9 -1
  37. package/neural-interface/lib/backup-service.js +64 -105
  38. package/neural-interface/lib/browser-extension-adapter.js +24 -15
  39. package/neural-interface/lib/browser-extension-bridge.js +27 -4
  40. package/neural-interface/lib/native-loop-runtime.js +6 -7
  41. package/neural-interface/lib/opencode-build-preflight.js +12 -7
  42. package/neural-interface/lib/peer-identity.js +13 -8
  43. package/neural-interface/lib/session-cache-builder.js +41 -3
  44. package/neural-interface/lib/teams/scheduler.js +2 -2
  45. package/neural-interface/lib/teams/schema.js +1 -1
  46. package/neural-interface/package-lock.json +2 -2
  47. package/neural-interface/package.json +1 -1
  48. package/neural-interface/public/index.html +51 -0
  49. package/neural-interface/public/offline.html +4 -3
  50. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  51. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  52. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  53. package/neural-interface/public/shared/api.js +2 -1
  54. package/neural-interface/public/shared/assistant/asst-render.js +1 -0
  55. package/neural-interface/public/shared/assistant/asst-route.js +3 -1
  56. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  57. package/neural-interface/public/shared/html-shell.js +1 -0
  58. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  59. package/neural-interface/public/shared/page-session.js +1 -1
  60. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  61. package/neural-interface/public/shared/start-bridge.js +2 -2
  62. package/neural-interface/public/shared/styles.css +13 -1
  63. package/neural-interface/public/shared/ui-loading.js +72 -19
  64. package/neural-interface/public/shared/ui-native-loop-router.js +49 -20
  65. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  66. package/neural-interface/public/shared/ui-settings.js +10 -2
  67. package/neural-interface/public/shared/ui-sync.js +1 -0
  68. package/neural-interface/public/sw.js +4 -3
  69. package/neural-interface/public/variant/3d/main.js +13 -4
  70. package/neural-interface/server.js +34 -25
  71. package/npm-shrinkwrap.json +2 -2
  72. package/package.json +2 -1
@@ -6,9 +6,8 @@
6
6
  // the connection (lib/peer-identity.js). When it cannot look that process up (netstat or ps missing, denied because
7
7
  // the server was started inside a sandbox, slow past its cap), it proves nothing about who is asking and pauses the
8
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
9
+ // /api/health says so (`ownerAuthority: { state: 'degraded', reason, retryable, since }`). A request refused with
10
+ // PEER_UNAVAILABLE prompts the page to check health. This module decides the words of the banner; ui-owner-authority.js asks the
12
11
  // server, listens and draws them. `unsupported` (Windows, Linux) and `off` (SYNABUN_PEER_IDENTITY=off) show nothing:
13
12
  // there the rules from before apply and nothing is paused.
14
13
  //
@@ -27,7 +26,7 @@ export const OWNER_AUTHORITY_NOTICE_COPY = Object.freeze({
27
26
  });
28
27
 
29
28
  /** The states GET /api/health can name (lib/peer-identity.js authorityState). */
30
- export const OWNER_AUTHORITY_STATES = Object.freeze(['ok', 'degraded', 'unsupported', 'off']);
29
+ export const OWNER_AUTHORITY_STATES = Object.freeze(['pending', 'ok', 'degraded', 'unsupported', 'off']);
31
30
  /** The longest reason the banner shows (the server's reasons are short; a longer one is cut). */
32
31
  export const REASON_MAX = 200;
33
32
 
@@ -58,13 +57,8 @@ export function readOwnerAuthority(health) {
58
57
  };
59
58
  }
60
59
 
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
60
  /**
67
- * What the banner shows for a state, or null when it shows nothing (ok, unsupported, off, nothing known).
61
+ * What the banner shows for a state, or null when it shows nothing (pending, ok, unsupported, off, nothing known).
68
62
  * `t(key, params)` is the page's translator for `ownerAuthorityNotice.*` (English by default).
69
63
  * → { key, label, title, body, reason, hint, actions: [{ id: 'reload'|'dismiss', label }] }. `key` is what a
70
64
  * dismissal is remembered by: the same outage stays dismissed, a new reason shows again.
@@ -25,7 +25,7 @@
25
25
  // lookup of the calling process failed: lib/peer-identity.js), so it hands out no page secret and refuses the owner's
26
26
  // actions until a lookup works again. Nothing here cures that, so nothing is retried: the answer goes back as it came,
27
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
28
+ // ui-owner-authority.js uses to recheck verifier health). A refresh that met it (GET /api/page-session answered 503) is not asked
29
29
  // again for a few seconds: a burst of refused writes costs the server one lookup, not one each.
30
30
  //
31
31
  // A refusal nothing here cures (403 WORKER_BROWSER, OWNER_ROUTE, or PAGE_SECRET_REQUIRED the refresh did not cure) is
@@ -11,10 +11,10 @@
11
11
  //
12
12
  // DOM-free and without imports: node --test and the page load the same file.
13
13
 
14
- /** The Connection modes of SynaBun's own local browser (the Browser tab's dropdown). */
15
- export const LOCAL_CONNECT_MODES = Object.freeze(['mirror', 'attach', 'extension']);
14
+ /** The modes offered in the Browser tab's Connection dropdown. */
15
+ export const LOCAL_CONNECT_OPTIONS = Object.freeze(['attach', 'extension']);
16
16
 
17
- /** The mode a MoreLogin switch-off goes back to (as POST /api/morelogin/use-default { clear: true } does). */
17
+ /** Deprecated in the menu. Still supported for saved configs and as the server's local default. */
18
18
  export const LOCAL_DEFAULT_MODE = 'mirror';
19
19
 
20
20
  const idOf = (value) => (value === undefined || value === null || value === '' ? null : String(value));
@@ -40,7 +40,7 @@ export function aiBrowserOfStatus(status) {
40
40
  /** The Connection dropdown's value for a loaded config: a local mode, never 'morelogin' (it has no such option). */
41
41
  export function localConnectModeOf(cfg) {
42
42
  const mode = cfg && typeof cfg === 'object' ? cfg.connectMode : null;
43
- return LOCAL_CONNECT_MODES.includes(mode) ? mode : LOCAL_DEFAULT_MODE;
43
+ return LOCAL_CONNECT_OPTIONS.includes(mode) ? mode : LOCAL_DEFAULT_MODE;
44
44
  }
45
45
 
46
46
  /**
@@ -54,7 +54,7 @@ export function browserSaveFields(formMode, current) {
54
54
  const now = current && typeof current === 'object' ? current : {};
55
55
  const envId = idOf(now.envId);
56
56
  if (now.moreLogin === true) return { connectMode: 'morelogin', moreloginEnvId: envId };
57
- return { connectMode: LOCAL_CONNECT_MODES.includes(formMode) ? formMode : LOCAL_DEFAULT_MODE, moreloginEnvId: envId };
57
+ return { connectMode: LOCAL_CONNECT_OPTIONS.includes(formMode) ? formMode : LOCAL_DEFAULT_MODE, moreloginEnvId: envId };
58
58
  }
59
59
 
60
60
  /**
@@ -266,7 +266,7 @@ export function fetchStartBeacon(target, { fetchImpl, timeoutMs = START_LIMITS.b
266
266
  * launch() → hand START_LINK to the OS
267
267
  * beacon() → Promise<object|null> the launch's raw report (optional)
268
268
  * port → the server's port (what a beacon must be about)
269
- * onState(state, detail) on every change of state
269
+ * onState(state, detail) on every change of state; online includes the answering server's boot id
270
270
  * onUpdate(snapshot) whenever what there is to show changed: the
271
271
  * state, what the launch reported, or the second
272
272
  *
@@ -456,7 +456,7 @@ export function createStartBridge({
456
456
  if (!up && !stopped && state !== 'refused') await listen();
457
457
  probing = false;
458
458
  if (stopped) return;
459
- if (up) { set('online'); update(); return; }
459
+ if (up) { set('online', { boot: seen.boot }); update(); return; }
460
460
  if (state === 'refused') { update(); return; }
461
461
  if (state === 'launching' || state === 'waiting') {
462
462
  const waited = now() - askedAt;
@@ -19126,6 +19126,8 @@
19126
19126
  /* The rig (shared/synabun-mascot.js) draws in currentColor. Asleep, the bob
19127
19127
  and the z below carry it; in every other state the rig plays its own pose. */
19128
19128
  #loading-mascot .synabun-mascot { color: #ffffff; }
19129
+ #loading-mascot .synabun-mascot:not(.art-ready) .syna-art { visibility: hidden; }
19130
+ #loading-mascot .synabun-mascot:not(.art-ready) :is(.syna-eye, .syna-mouth, .syna-props) { visibility: visible; }
19129
19131
  #loading-mascot:is([data-state="waking"], [data-state="working"], [data-state="ready"], [data-state="failed"], [data-state="stalled"]) { animation: none; }
19130
19132
  #loading-mascot:is([data-state="waking"], [data-state="working"], [data-state="ready"], [data-state="failed"], [data-state="stalled"]) #loading-zzz { display: none; }
19131
19133
  @media (prefers-reduced-motion: reduce) {
@@ -20871,7 +20873,17 @@
20871
20873
  .ax .ax-section-mark { display: inline-flex; }
20872
20874
  .ax .ax-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 16px; align-items: start; }
20873
20875
  .ax .ax-field--wide { grid-column: 1 / -1; }
20874
- .ax .ax-field .cc-dropdown { width: 100%; }
20876
+ .ax .ax-field .cc-dropdown { width: 100%; max-width: 32rem; }
20877
+ .ax .ax-field .cc-dropdown-trigger { width: 100%; min-width: 0; text-align: start; }
20878
+ .ax .ax-field .cc-dropdown-menu {
20879
+ --cc-menu-max-height: 18rem;
20880
+ box-sizing: border-box; overflow: hidden auto; overscroll-behavior: contain;
20881
+ background: var(--sx-menu); border-color: var(--b-hover); box-shadow: var(--shadow-md);
20882
+ }
20883
+ .ax .ax-field .cc-dropdown-item > span:last-child, .ax .ax-field .cc-dropdown-caption {
20884
+ display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
20885
+ }
20886
+ .ax .ax-field .cc-dropdown-item.highlight { background: var(--s-active); color: var(--t-bright); }
20875
20887
  .ax .ax-issues { display: grid; gap: 2px; }
20876
20888
  .ax .ax-issues:empty { display: none; }
20877
20889
  .ax .ax-issues .sx-field-note { display: flex; align-items: flex-start; gap: 6px; }
@@ -32,6 +32,9 @@ let _mascot = null;
32
32
  // held (sockets, terminals, panel sessions) was the old server's, so once the
33
33
  // server is back the page loads again instead of carrying on.
34
34
  let _restartShown = false;
35
+ let currentBoot = '';
36
+ let appWasVisible = false;
37
+ let reloadPending = false;
35
38
  // The tab's title from before the restart, for when it is refused.
36
39
  let _restartTitle = null;
37
40
 
@@ -128,7 +131,11 @@ export function showLoadingError(title, sub, canStart, serverOffline) {
128
131
  */
129
132
  export function hideLoading(delay = 400) {
130
133
  const $overlay = $('loading-overlay');
131
- if ($overlay) setTimeout(() => { markOnce(OVERLAY_HIDDEN_MARK); concealOverlay($overlay); }, delay);
134
+ if ($overlay) setTimeout(() => {
135
+ if (_offlineBridge) return;
136
+ markOnce(OVERLAY_HIDDEN_MARK);
137
+ concealOverlay($overlay);
138
+ }, delay);
132
139
  }
133
140
 
134
141
  /** The moment the overlay started to fade for the first time on this page (the time the user waited). */
@@ -165,11 +172,13 @@ function resetLoadingToConnecting() {
165
172
  const $sub = $('loading-sub');
166
173
  const $action = $('loading-action');
167
174
  const $actionStatus = $('loading-action-status');
175
+ const $retryStatus = $('loading-retry-status');
168
176
 
169
177
  if ($text) $text.textContent = t('loading.connecting');
170
178
  if ($sub) $sub.textContent = t('loading.initializingNeural');
171
179
  if ($action) $action.style.display = 'none';
172
180
  if ($actionStatus) $actionStatus.textContent = '';
181
+ if ($retryStatus) $retryStatus.textContent = '';
173
182
  clearStartStatus();
174
183
  clearRestartLook();
175
184
  if (_statusDot) _statusDot.classList.remove('error');
@@ -186,6 +195,7 @@ function resetLoadingToConnecting() {
186
195
  */
187
196
  export function rememberHealth(health) {
188
197
  if (!health) return;
198
+ if (!currentBoot && health.bootId) currentBoot = health.bootId;
189
199
  try {
190
200
  if (health.projectDir) {
191
201
  localStorage.setItem('synabun-project-dir', health.projectDir);
@@ -282,6 +292,12 @@ function mountMascot() {
282
292
  try {
283
293
  const still = host.querySelector('svg');
284
294
  _mascot = createMascot(host, { width: 160, height: 80, pose: 'sleep', active: false });
295
+ // The rig already paints a vector face for every pose. Show it until the
296
+ // current raster artwork loads, and again if the next pose cannot load.
297
+ const svg = _mascot.el;
298
+ const art = svg?.querySelector('.syna-art');
299
+ art?.addEventListener('load', () => svg.classList.add('art-ready'));
300
+ art?.addEventListener('error', () => svg.classList.remove('art-ready'));
285
301
  if (still && still !== _mascot.el) still.style.display = 'none';
286
302
  } catch {
287
303
  _mascot = null;
@@ -406,7 +422,7 @@ function watchForServer() {
406
422
  async function probeServer() {
407
423
  const health = await fetchHealth();
408
424
  return {
409
- up: !!health && health.ok !== false,
425
+ up: health?.ok === true,
410
426
  boot: typeof health?.bootId === 'string' ? health.bootId : '',
411
427
  stopping: health?.restarting === true,
412
428
  };
@@ -425,23 +441,35 @@ function openBridge() {
425
441
  if (_offlineBridge !== bridge) return;
426
442
  renderStart(snap);
427
443
  },
428
- onState(state) {
429
- if (_offlineBridge !== bridge) return;
430
- if (state !== 'online') return;
431
- // Back from a restart: the page loads again, after the frame that says so.
432
- if (_restartShown) {
433
- setTimeout(() => window.location.reload(), START_LIMITS.reloadDelayMs);
434
- return;
435
- }
436
- resetLoadingToConnecting();
437
- emit('loading:retried');
438
- if (_initCallback) _initCallback();
444
+ onState(state, { boot }) {
445
+ if (_offlineBridge === bridge && state === 'online') recoverConnection(boot);
439
446
  },
440
447
  });
441
448
  _offlineBridge = bridge;
442
449
  return bridge;
443
450
  }
444
451
 
452
+ /** Complete a healthy retry, whether the person pressed Retry or the bridge saw it first. */
453
+ function recoverConnection(boot) {
454
+ if (reloadPending) return;
455
+ // Older servers have no boot ID. A running page then needs a fresh session
456
+ // after an outage, while an unfinished first boot can retry initialization.
457
+ const needsReload = currentBoot && boot ? currentBoot !== boot : appWasVisible;
458
+ if (_restartShown || needsReload) {
459
+ reloadPending = true;
460
+ setTimeout(() => window.location.reload(), START_LIMITS.reloadDelayMs);
461
+ return;
462
+ }
463
+ resetLoadingToConnecting();
464
+ if (appWasVisible) {
465
+ appWasVisible = false;
466
+ concealOverlay($('loading-overlay'));
467
+ return;
468
+ }
469
+ emit('loading:retried');
470
+ if (_initCallback) _initCallback();
471
+ }
472
+
445
473
  // ═══════════════════════════════════════════
446
474
  // Restart Server
447
475
  // ═══════════════════════════════════════════
@@ -583,24 +611,23 @@ function handleCopyCommand() {
583
611
  * Pings /api/health and re-triggers init on success.
584
612
  */
585
613
  async function handleRetryConnection() {
614
+ const bridge = _offlineBridge;
586
615
  const $status = $('loading-retry-status');
587
616
  if ($status) $status.textContent = t('loading.checking');
588
617
 
589
618
  try {
590
619
  const health = await fetchHealth();
620
+ if (_offlineBridge !== bridge) return;
591
621
  // fetchHealth uses AbortSignal.timeout(3000) internally
592
- if (health && health.ok !== false) {
622
+ if (health?.ok === true && !health.restarting && !_restartShown) {
593
623
  if ($status) $status.textContent = t('loading.connectedLoading');
594
- // After a restart the page loads again (see openBridge).
595
- if (_restartShown) { window.location.reload(); return; }
596
- resetLoadingToConnecting();
597
- emit('loading:retried');
598
- if (_initCallback) _initCallback();
624
+ recoverConnection(health.bootId);
599
625
  } else {
600
626
  if ($status) $status.textContent = t('loading.notReadyYet');
601
627
  setTimeout(() => { if ($status) $status.textContent = ''; }, 3000);
602
628
  }
603
629
  } catch {
630
+ if (_offlineBridge !== bridge) return;
604
631
  if ($status) $status.textContent = t('loading.stillOffline');
605
632
  setTimeout(() => { if ($status) $status.textContent = ''; }, 3000);
606
633
  }
@@ -641,6 +668,32 @@ export function initLoading({ onInit } = {}) {
641
668
  const retryBtn = $('loading-retry-btn');
642
669
  if (retryBtn) retryBtn.addEventListener('click', handleRetryConnection);
643
670
 
671
+ let probing = false;
672
+ async function checkConnection() {
673
+ if (probing || _offlineBridge) return;
674
+ probing = true;
675
+ try {
676
+ let seen = await probeServer().catch(() => null);
677
+ // A close or a timed-out request after sleep can precede a healthy
678
+ // answer. Confirm the miss immediately, without waiting for another interval.
679
+ if (!seen && currentBoot && !_offlineBridge) seen = await probeServer().catch(() => null);
680
+ if (_offlineBridge) return;
681
+ if (seen?.up && !seen.stopping && !(currentBoot && seen.boot && currentBoot !== seen.boot)) {
682
+ currentBoot ||= seen.boot;
683
+ return;
684
+ }
685
+ // Preserve a specific startup database error until the app actually ran.
686
+ const overlay = $('loading-overlay');
687
+ if (!overlay || (seen && !seen.up && overlay.classList.contains('error') && !overlay.classList.contains('hidden'))) return;
688
+ appWasVisible = overlay.classList.contains('hidden');
689
+ revealOverlay(overlay);
690
+ showLoadingError(t('loading.serverOffline'), t('loading.serverNotRunning'), false, true);
691
+ if (appWasVisible) overlay.classList.add('over-app');
692
+ } finally { probing = false; }
693
+ }
694
+ setInterval(checkConnection, 3000);
695
+ on('sync:disconnected', checkConnection);
696
+
644
697
  // ── The server says it is restarting (ui-sync.js): every window shows it ──
645
698
  on('server:restarting', (msg) => beginRestart({ announced: true, boot: typeof msg?.bootId === 'string' ? msg.bootId : '' }));
646
699
  }
@@ -29,6 +29,8 @@ const _providerEventBuffers = new Map();
29
29
  const _localReleases = new LocalReleaseTracker();
30
30
  let _initialized = false;
31
31
  let _claimHeartbeat = null;
32
+ let _renewing = false;
33
+ let _retryClaimsAt = 0;
32
34
  let _suspended = false;
33
35
  let _suspendedClaims = new Map();
34
36
  let _reconcilePromise = null;
@@ -118,6 +120,7 @@ function trimLatestRuns() {
118
120
  }
119
121
 
120
122
  async function claim(run) {
123
+ if (Date.now() < _retryClaimsAt) return false;
121
124
  const claimToken = _claimToken;
122
125
  const claimEpoch = _claimEpoch;
123
126
  try {
@@ -126,7 +129,10 @@ async function claim(run) {
126
129
  headers: { 'Content-Type': 'application/json' },
127
130
  body: JSON.stringify({ windowId: _windowId, claimToken }),
128
131
  });
129
- if (!response.ok) return false;
132
+ if (!response.ok) {
133
+ if (response.status === 503) _retryClaimsAt = Date.now() + 2000;
134
+ return false;
135
+ }
130
136
  if (_suspended || claimEpoch !== _claimEpoch || claimToken !== _claimToken) {
131
137
  fetch(`/api/sidepanel-runs/${encodeURIComponent(run.runId)}/release`, {
132
138
  method: 'POST',
@@ -138,7 +144,7 @@ async function claim(run) {
138
144
  }
139
145
  const data = await response.json();
140
146
  const claimedRun = data?.run || run;
141
- _ownedClaims.set(run.runId, { provider: run.provider, status: claimedRun.status });
147
+ _ownedClaims.set(run.runId, { provider: run.provider, status: claimedRun.status, renewedAt: Date.now() });
142
148
  recordLatestRun(claimedRun);
143
149
  return claimedRun;
144
150
  } catch {
@@ -272,6 +278,7 @@ async function routeLatest(runId) {
272
278
  return false;
273
279
  }
274
280
  if (result?.ok) {
281
+ if (owned) owned.attachedVersion = run.version;
275
282
  _attached.set(run.runId, {
276
283
  provider: run.provider,
277
284
  iteration: run.currentIteration,
@@ -359,18 +366,26 @@ async function reconcileRuns() {
359
366
  if (!response.ok) return;
360
367
  const data = await response.json();
361
368
  const cutoff = Date.now() - 24 * 60 * 60 * 1000;
369
+ // Older servers moved updatedAt on a claim or release. A renewed lease
370
+ // does not make a finished conversation recent again.
371
+ const activityAt = (run) => run.completedAt || run.updatedAt || run.startedAt || '';
362
372
  const newestFirst = (data.runs || [])
363
373
  .filter(hasIdentity)
364
- .sort((a, b) => String(b.updatedAt || b.startedAt || '').localeCompare(String(a.updatedAt || a.startedAt || '')));
374
+ .sort((a, b) => activityAt(b).localeCompare(activityAt(a)));
365
375
  const activeRuns = newestFirst.filter((run) => LIVE_STATUSES.has(run.status));
366
376
  const terminalRuns = newestFirst.filter((run) => {
367
377
  if (!TERMINAL_STATUSES.has(run.status)) return false;
368
- if (new Date(run.updatedAt || run.startedAt || 0).getTime() < cutoff) return false;
378
+ if (!(Date.parse(activityAt(run)) >= cutoff)) return false;
369
379
  const claimAge = run.claimedAt ? Date.now() - new Date(run.claimedAt).getTime() : Infinity;
370
380
  return !run.claimedBy || run.claimedBy === _windowId || claimAge > CLAIM_TTL_MS;
371
381
  }).slice(0, TERMINAL_RESTORE_LIMIT);
372
- for (const run of activeRuns) await routeNativeLoopRun(run, { focus: false, retry: true });
373
- for (const run of terminalRuns) await routeNativeLoopRun(run, { focus: false, retry: true });
382
+ const restore = async (run) => {
383
+ const owned = _ownedClaims.get(run.runId);
384
+ if (run.claimedBy === _windowId && owned && Number.isFinite(run.version) && owned.attachedVersion === run.version) return;
385
+ await routeNativeLoopRun(run, { focus: false, retry: true });
386
+ };
387
+ for (const run of activeRuns) await restore(run);
388
+ for (const run of terminalRuns) await restore(run);
374
389
  } catch {}
375
390
  }
376
391
 
@@ -388,7 +403,7 @@ export function initNativeLoopRouter() {
388
403
  on('sync:sidepanel:run-created', route);
389
404
  on('sync:sidepanel:run-updated', (message) => {
390
405
  const run = descriptorFrom(message);
391
- if (message?.reason === 'claim-released' && run?.runId && _localReleases.consume(run.runId)) {
406
+ if (message?.reason === 'claim-released' && run?.runId && (_localReleases.consume(run.runId) || TERMINAL_STATUSES.has(run.status))) {
392
407
  recordLatestRun(run);
393
408
  return;
394
409
  }
@@ -500,19 +515,33 @@ export function initNativeLoopRouter() {
500
515
 
501
516
  function startClaimHeartbeat() {
502
517
  if (_claimHeartbeat) return;
503
- _claimHeartbeat = setInterval(() => {
504
- if (_suspended) return;
505
- for (const [runId, owned] of _ownedClaims) {
506
- fetch(`/api/sidepanel-runs/${encodeURIComponent(runId)}/claim`, {
507
- method: 'POST',
508
- headers: { 'Content-Type': 'application/json' },
509
- body: JSON.stringify({ windowId: _windowId, claimToken: _claimToken }),
510
- }).then((response) => {
511
- if (!response.ok) {
512
- loseClaim(runId, owned.provider);
518
+ _claimHeartbeat = setInterval(async () => {
519
+ if (_suspended || _renewing) return;
520
+ _renewing = true;
521
+ const epoch = _claimEpoch;
522
+ try {
523
+ for (const [runId, owned] of [..._ownedClaims]) {
524
+ if (_suspended || epoch !== _claimEpoch) return;
525
+ if (_ownedClaims.get(runId) !== owned) continue;
526
+ let response;
527
+ if (Date.now() >= _retryClaimsAt) {
528
+ try {
529
+ response = await fetch(`/api/sidepanel-runs/${encodeURIComponent(runId)}/claim`, {
530
+ method: 'POST',
531
+ headers: { 'Content-Type': 'application/json' },
532
+ body: JSON.stringify({ windowId: _windowId, claimToken: _claimToken }),
533
+ signal: AbortSignal.timeout(8000),
534
+ });
535
+ } catch { /* retry at the next heartbeat while the lease is valid */ }
536
+ if (_ownedClaims.get(runId) !== owned || epoch !== _claimEpoch) continue;
537
+ if (!response || response.status === 503) _retryClaimsAt = Date.now() + 2000;
513
538
  }
514
- }).catch(() => {});
515
- }
516
- scheduleReconcile();
539
+ if (response?.ok) owned.renewedAt = Date.now();
540
+ else if ((response && response.status !== 503) || Date.now() - owned.renewedAt >= CLAIM_TTL_MS) {
541
+ await loseClaim(runId, owned.provider);
542
+ }
543
+ }
544
+ if (_claimEpoch === epoch && Date.now() >= _retryClaimsAt) scheduleReconcile();
545
+ } finally { _renewing = false; }
517
546
  }, 30_000);
518
547
  }
@@ -5,12 +5,9 @@
5
5
  // When the server cannot identify the program calling it (macOS, lib/peer-identity.js: netstat or ps missing,
6
6
  // denied, slow past their cap), it pauses the owner's actions (503 PEER_UNAVAILABLE). This banner says so, with the
7
7
  // reason and Reload to retry, in the update toast's glass at the top centre of the page (styles.css .owner-authority-notice):
8
- // non-modal, nothing behind it is blocked. It shows when
9
- // • GET /api/health says `ownerAuthority.state: 'degraded'` (asked when the page starts and every time the sync
10
- // socket connects: a page that was open through a restart is not reloaded), or
11
- // • a request of the page got 503 PEER_UNAVAILABLE (public/shared/page-session.js dispatches
12
- // `synabun:peer-unavailable` on the window).
13
- // While it shows, /api/health is asked again now and then, and the banner goes once the state is ok again (the
8
+ // non-modal, nothing behind it is blocked. Only GET /api/health can report a degraded verifier. The page checks
9
+ // at startup, on sync reconnect and when any request gets 503 PEER_UNAVAILABLE (including socket-specific failures).
10
+ // While verification is pending or the banner shows, the page rechecks health. The banner goes on recovery (the
14
11
  // page's next write then gets this boot's page secret by itself). Dismiss hides it until another reason comes. Never
15
12
  // on an invite guest's page (the owner's authority is not a guest's concern). What it says is
16
13
  // owner-authority-view.js (DOM-free, tested under node).
@@ -19,11 +16,11 @@ import { on } from './state.js';
19
16
  import { t } from './i18n.js';
20
17
  import { isGuest } from './ui-sync.js';
21
18
  import { PEER_UNAVAILABLE_EVENT } from './page-session.js';
22
- import { ownerAuthorityNoticeView, readOwnerAuthority, unavailableAuthority } from './owner-authority-view.js';
19
+ import { ownerAuthorityNoticeView, readOwnerAuthority } from './owner-authority-view.js';
23
20
 
24
21
  const HEALTH_URL = '/api/health';
25
22
  const NOTICE_ID = 'owner-authority-notice';
26
- /** How often /api/health is asked again while the banner shows. */
23
+ /** How often to check pending verification or a visible outage. */
27
24
  export const RECHECK_MS = 15_000;
28
25
 
29
26
  const translate = (key, params) => t(`ownerAuthorityNotice.${key}`, params);
@@ -31,6 +28,8 @@ const translate = (key, params) => t(`ownerAuthorityNotice.${key}`, params);
31
28
  let _wired = false;
32
29
  let _guest = false;
33
30
  let _asking = null;
31
+ let _checkAgain = false;
32
+ let _loadingWatch = null;
34
33
  let _current = null; // { key, el }
35
34
  let _dismissed = null; // the key this page dismissed
36
35
  let _recheck = null;
@@ -52,6 +51,8 @@ function startRecheck() {
52
51
 
53
52
  function hide() {
54
53
  stopRecheck();
54
+ _loadingWatch?.disconnect();
55
+ _loadingWatch = null;
55
56
  const current = _current;
56
57
  _current = null;
57
58
  if (!current) return;
@@ -66,9 +67,11 @@ function whenPageShown(run) {
66
67
  const watch = new MutationObserver(() => {
67
68
  if (!overlay.classList.contains('hidden')) return;
68
69
  watch.disconnect();
70
+ _loadingWatch = null;
69
71
  run();
70
72
  });
71
73
  watch.observe(overlay, { attributes: true, attributeFilter: ['class'] });
74
+ _loadingWatch = watch;
72
75
  }
73
76
 
74
77
  function draw(view) {
@@ -98,9 +101,8 @@ function draw(view) {
98
101
  });
99
102
  });
100
103
  document.body.appendChild(el);
101
- requestAnimationFrame(() => el.classList.add('show'));
102
104
  _current = { key: view.key, el };
103
- startRecheck();
105
+ requestAnimationFrame(() => { if (_current?.el === el) el.classList.add('show'); });
104
106
  }
105
107
 
106
108
  /** Reload to retry: the page asks for everything again, the page secret included (a lookup that works hands it out). */
@@ -116,10 +118,18 @@ function dismiss(key) {
116
118
  /** Show the banner for this owner authority (or none): never on a guest's page, never one this page dismissed. */
117
119
  export function presentOwnerAuthority(authority) {
118
120
  const view = ownerAuthorityNoticeView(authority, { t: translate });
119
- if (!view || guestPage()) { hide(); if (!view) _dismissed = null; return null; }
121
+ if (!view || guestPage()) {
122
+ hide();
123
+ if (!view) _dismissed = null;
124
+ if (authority?.state === 'pending' && !guestPage()) startRecheck();
125
+ return null;
126
+ }
120
127
  // A banner something else took off the page is drawn again.
121
128
  if (_current && !_current.el.isConnected) _current = null;
122
- if (_dismissed === view.key) return null;
129
+ if (_dismissed === view.key) { hide(); return null; }
130
+ _loadingWatch?.disconnect();
131
+ _loadingWatch = null;
132
+ startRecheck();
123
133
  if (_current?.key === view.key) return view;
124
134
  whenPageShown(() => {
125
135
  if (guestPage() || _dismissed === view.key || _current?.key === view.key) return;
@@ -129,19 +139,30 @@ export function presentOwnerAuthority(authority) {
129
139
  }
130
140
 
131
141
  /** Ask GET /api/health; an older server (no `ownerAuthority`) or a failed request changes nothing. */
132
- export function checkOwnerAuthority() {
142
+ export function checkOwnerAuthority({ fresh = false } = {}) {
133
143
  if (guestPage()) return Promise.resolve(null);
134
- if (_asking) return _asking;
144
+ if (_asking) {
145
+ if (fresh) _checkAgain = true;
146
+ return _asking;
147
+ }
135
148
  _asking = (async () => {
136
- try {
137
- const res = await fetch(HEALTH_URL, { headers: { Accept: 'application/json' }, cache: 'no-store' });
138
- if (!res.ok) return null;
139
- const authority = readOwnerAuthority(await res.json());
140
- if (authority) presentOwnerAuthority(authority);
141
- return authority;
142
- } catch {
143
- return null;
144
- }
149
+ let authority;
150
+ let previousState;
151
+ do {
152
+ _checkAgain = false;
153
+ authority = null;
154
+ try {
155
+ const res = await fetch(HEALTH_URL, { headers: { Accept: 'application/json' }, cache: 'no-store' });
156
+ if (res.ok) authority = readOwnerAuthority(await res.json());
157
+ } catch { /* keep the last confirmed state */ }
158
+ // A refusal or reconnect during this read merits a fresh sample. Two matching
159
+ // samples can already be shown, even if refusals arrive faster than health replies.
160
+ if (authority && !guestPage() && (!_checkAgain || authority.state === previousState)) {
161
+ presentOwnerAuthority(authority);
162
+ }
163
+ previousState = authority?.state;
164
+ } while (_checkAgain && !guestPage());
165
+ return authority;
145
166
  })().finally(() => { _asking = null; });
146
167
  return _asking;
147
168
  }
@@ -153,10 +174,12 @@ export function initOwnerAuthorityNotice() {
153
174
  on('session:info', (info) => {
154
175
  _guest = !!info?.isGuest;
155
176
  if (_guest) hide();
156
- else checkOwnerAuthority();
177
+ else checkOwnerAuthority({ fresh: true });
157
178
  });
158
179
  if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
159
- window.addEventListener(PEER_UNAVAILABLE_EVENT, (event) => { presentOwnerAuthority(unavailableAuthority(event?.detail)); });
180
+ window.addEventListener(PEER_UNAVAILABLE_EVENT, (event) => {
181
+ if (event?.detail?.url !== HEALTH_URL) checkOwnerAuthority({ fresh: true });
182
+ });
160
183
  }
161
184
  checkOwnerAuthority();
162
185
  }
@@ -28,7 +28,7 @@ import { cliInstallText, setCliInstallTranslator } from './cli-install-view.js';
28
28
  import { dropdownHTML, wireDropdowns, setDropdownItems, setDropdownValue } from './cc-dropdown.js';
29
29
  import { PROXY_TYPES, isLocalProfile, proxySummary, defaultCreateWhere, isPlanLimit, formOfProfile, readLocalProfileForm, proxyOfForm, createAction, whereOptions, passwordNeededAgain } from './settings/settings-local-profiles.js';
30
30
  import { startLimitNotes, closedOutsideNotes } from './settings/settings-morelogin-cooldown.js';
31
- import { AI_BROWSER_EVENT, aiBrowserOf, aiBrowserOfStatus, localConnectModeOf, browserSaveFields, switchRequest, pickRequest, aiBrowserLine, profileOf, aiBrowserDetail } from './settings/settings-ai-browser.js';
31
+ import { AI_BROWSER_EVENT, LOCAL_CONNECT_OPTIONS, LOCAL_DEFAULT_MODE, aiBrowserOf, aiBrowserOfStatus, localConnectModeOf, browserSaveFields, switchRequest, pickRequest, aiBrowserLine, profileOf, aiBrowserDetail } from './settings/settings-ai-browser.js';
32
32
  import { IFACE_DEFAULTS, loadIfaceConfig, saveIfaceConfig, applyIfaceConfig, restoreInterfaceConfig, loadSkinStylesheet, removeSkinStylesheet, restoreSkin, setSkinsTabRefresher } from './iface-config.js';
33
33
  // The interface config and the skin, for the modules that import them from here.
34
34
  export { loadIfaceConfig, saveIfaceConfig, applyIfaceConfig, restoreInterfaceConfig, restoreSkin };
@@ -654,7 +654,7 @@ function buildBrowserTab(ownerAccess = null) {
654
654
  id: 'bcg-profiles', section: 'browser.browser_profiles',
655
655
  body: `
656
656
  <input type="hidden" id="bc-userDataDir" value="">
657
- ${kit.field('BRW011', `${dd('BRW011', 'bc-connectMode', 'connect', ['mirror', 'attach', 'extension'])}
657
+ ${kit.field('BRW011', `${dd('BRW011', 'bc-connectMode', 'connect', LOCAL_CONNECT_OPTIONS)}
658
658
  <div class="stg-help" id="bc-connectMode-ai-note" style="display:none">${b('aiBrowser.connectionNote')}</div>`)}
659
659
  ${extensionSettingsHTML(kit)}
660
660
  ${kit.field('BRW012', dd('BRW012', 'bc-attachSeed', 'seed', ['real', 'fresh']), { attrs: 'id="bc-attachSeed-row" style="display:none"' })}
@@ -6357,6 +6357,9 @@ async function openSettingsModalNow(options = {}) {
6357
6357
  const label = dd.querySelector('.cc-dropdown-value');
6358
6358
  const menu = dd.querySelector('.cc-dropdown-menu');
6359
6359
  if (!menu) return;
6360
+ if (label && hiddenId === 'bc-connectMode' && val === LOCAL_DEFAULT_MODE) {
6361
+ label.textContent = kit.tx('settings.redesign.browser.opt.connect.mirror');
6362
+ }
6360
6363
  menu.querySelectorAll('.cc-dropdown-item').forEach(item => {
6361
6364
  const isMatch = item.dataset.value === val;
6362
6365
  item.classList.toggle('active', isMatch);
@@ -7095,6 +7098,11 @@ async function openSettingsModalNow(options = {}) {
7095
7098
  }
7096
7099
  }
7097
7100
 
7101
+ // Keep the local default in the form until the saved config arrives.
7102
+ const connectModeInput = overlay.querySelector('#bc-connectMode');
7103
+ if (connectModeInput) connectModeInput.value = LOCAL_DEFAULT_MODE;
7104
+ syncBcDropdowns();
7105
+
7098
7106
  // Load config on open, then auto-detect profiles. A refused read (no owner access) is "No access", never defaults.
7099
7107
  fetch('/api/browser/config').then(async (r) => {
7100
7108
  if (markPaneRefused(overlay, 'browser', await refusalOfResponse(r))) return null;
@@ -283,6 +283,7 @@ function connect() {
283
283
  _ws.onclose = () => {
284
284
  console.log('[sync-ws] Disconnected, will reconnect in 5s');
285
285
  _ws = null;
286
+ emit('sync:disconnected');
286
287
  if (!_reconnectTimer) {
287
288
  _reconnectTimer = setInterval(connect, RECONNECT_INTERVAL);
288
289
  }