synabun 2.4.2 → 2.4.3

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 (103) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +23 -3
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/services/neural-interface.js +1 -1
  6. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  7. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  8. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  9. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  10. package/mcp-server/package-lock.json +5 -5
  11. package/mcp-server/package.json +1 -1
  12. package/mcp-server/src/services/neural-interface.ts +1 -1
  13. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  14. package/neural-interface/i18n/en.json +50 -1
  15. package/neural-interface/i18n/pt-BR.json +57 -8
  16. package/neural-interface/lib/assistant-api.js +33 -0
  17. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  18. package/neural-interface/lib/assistant-dispatch.js +26 -2
  19. package/neural-interface/lib/assistant-envelope.js +40 -0
  20. package/neural-interface/lib/assistant-runtime.js +95 -10
  21. package/neural-interface/lib/browser-extension-adapter.js +1 -3
  22. package/neural-interface/lib/browser-extension-archive.js +149 -0
  23. package/neural-interface/lib/browser-extension-bridge.js +7 -4
  24. package/neural-interface/lib/browser-extension-folder.js +596 -76
  25. package/neural-interface/lib/browser-extension-package.js +200 -0
  26. package/neural-interface/lib/browser-extension-pin.js +84 -0
  27. package/neural-interface/lib/browser-extension-pin.json +33 -0
  28. package/neural-interface/lib/browser-extension-setup.js +105 -18
  29. package/neural-interface/lib/cli-install.js +23 -3
  30. package/neural-interface/lib/cli-update-planner.js +67 -4
  31. package/neural-interface/lib/native-loop-providers.js +10 -1
  32. package/neural-interface/lib/native-loop-runtime.js +20 -2
  33. package/neural-interface/lib/opencode-shell-read.js +107 -0
  34. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  35. package/neural-interface/lib/opencode-turn-release.js +173 -0
  36. package/neural-interface/lib/opencode-v2-client.js +4 -1
  37. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  38. package/neural-interface/lib/opencode2-client.js +341 -6
  39. package/neural-interface/lib/opencode2-translate.js +161 -4
  40. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  41. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  42. package/neural-interface/package-lock.json +5 -5
  43. package/neural-interface/package.json +1 -1
  44. package/neural-interface/public/extension-setup.html +5 -2
  45. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  46. package/neural-interface/public/shared/assistant/asst-api.js +25 -0
  47. package/neural-interface/public/shared/assistant/asst-panel.js +69 -1
  48. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  49. package/neural-interface/public/shared/assistant/asst-render.js +138 -6
  50. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  51. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  52. package/neural-interface/public/shared/assistant/asst-styles.js +1 -0
  53. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  54. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  55. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  56. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  57. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  58. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  59. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  60. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  61. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  62. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  63. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  64. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  65. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  66. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  67. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  68. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  69. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  70. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  71. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  72. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  73. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  74. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  75. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  76. package/neural-interface/public/shared/ui-claude-panel.js +20 -0
  77. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  78. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  79. package/neural-interface/server.js +249 -35
  80. package/npm-shrinkwrap.json +5 -5
  81. package/package.json +1 -2
  82. package/browser-extension/content.js +0 -231
  83. package/browser-extension/engine.js +0 -658
  84. package/browser-extension/icons/icon-128.png +0 -0
  85. package/browser-extension/icons/icon-16.png +0 -0
  86. package/browser-extension/icons/icon-32.png +0 -0
  87. package/browser-extension/icons/icon-48.png +0 -0
  88. package/browser-extension/icons/status-off-16.png +0 -0
  89. package/browser-extension/icons/status-off-32.png +0 -0
  90. package/browser-extension/icons/status-off-48.png +0 -0
  91. package/browser-extension/icons/status-on-16.png +0 -0
  92. package/browser-extension/icons/status-on-32.png +0 -0
  93. package/browser-extension/icons/status-on-48.png +0 -0
  94. package/browser-extension/manifest.json +0 -58
  95. package/browser-extension/popup-strings.js +0 -250
  96. package/browser-extension/popup-view.js +0 -151
  97. package/browser-extension/popup.css +0 -166
  98. package/browser-extension/popup.html +0 -108
  99. package/browser-extension/popup.js +0 -359
  100. package/browser-extension/service-worker.js +0 -283
  101. package/browser-extension/setup-content.js +0 -36
  102. package/browser-extension/tokens.css +0 -326
  103. /package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +0 -0
@@ -0,0 +1,111 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // SynaBun Assistant — a shell call's live terminal block
3
+ //
4
+ // The block itself is the OpenCode panel's (ocp-v2-shell-block.js) in the rack's
5
+ // classes and words; the command's state and output come from the tracker
6
+ // (asst-shell-logic.js). A long test run must not cost the conversation
7
+ // anything: drawing is coalesced to one frame, and a block that is off screen or
8
+ // in a closed panel does no DOM work at all until it is seen again.
9
+ // ─────────────────────────────────────────────────────────────────────────────
10
+
11
+ import { createTerminalBlock } from '../ocp-v2/ocp-v2-shell-block.js';
12
+ import { shellNoteText } from './asst-shell-logic.js';
13
+
14
+ const SHOW_EVENT = 'asst-term-show';
15
+
16
+ const CLASSES = Object.freeze({
17
+ wrap: 'asst-term',
18
+ note: 'asst-term-note',
19
+ noteText: 'asst-term-note-text',
20
+ load: 'asst-tool-more asst-term-load',
21
+ out: 'asst-tool-section asst-term-out',
22
+ foot: 'asst-term-foot',
23
+ state: 'asst-term-state',
24
+ jump: 'asst-tool-more asst-term-jump',
25
+ copy: 'asst-copy asst-term-copy',
26
+ });
27
+
28
+ /**
29
+ * mountShellTerminal(tracker, shellId, { t, onDraw, onGone }) → { el, show(), dispose() }
30
+ * `onDraw`: the block was drawn (its height may have changed); `onGone`: OpenCode no longer has this output.
31
+ */
32
+ export function mountShellTerminal(tracker, shellId, { t, onDraw = () => {}, onGone = () => {} } = {}) {
33
+ let drawBlock = null;
34
+ let frame = 0;
35
+ let dirty = false;
36
+ let seen = true;
37
+ let disposed = false;
38
+ let wasGone = !!tracker.view(shellId)?.gone;
39
+ let wrap = null;
40
+
41
+ const flush = () => {
42
+ frame = 0;
43
+ if (disposed || !dirty || !seen || !wrap?.isConnected) return;
44
+ dirty = false;
45
+ drawBlock?.();
46
+ onDraw();
47
+ const gone = !!tracker.view(shellId)?.gone;
48
+ if (gone && !wasGone) { wasGone = true; onGone(); }
49
+ };
50
+ const request = () => {
51
+ dirty = true;
52
+ if (frame || !seen) return;
53
+ frame = requestAnimationFrame(flush);
54
+ };
55
+
56
+ tracker.open(shellId);
57
+ wrap = createTerminalBlock({
58
+ shellId,
59
+ place: tracker.placeOf(shellId),
60
+ showEvent: SHOW_EVENT,
61
+ read: () => ({ view: tracker.view(shellId), shell: tracker.shell(shellId) }),
62
+ // Told through `request` below, for as long as this mount lives (dispose ends it).
63
+ subscribe: (draw) => {
64
+ drawBlock = draw;
65
+ return () => {};
66
+ },
67
+ loadAll: () => tracker.loadAll(shellId),
68
+ classes: CLASSES,
69
+ words: {
70
+ load: t('assistant.rack.shell.loadFull', 'Load full output'),
71
+ loading: t('assistant.rack.shell.loading', 'Loading…'),
72
+ jump: t('assistant.rack.shell.jump', 'Jump to latest'),
73
+ copy: t('assistant.rack.shell.copy', 'Copy output'),
74
+ copied: t('assistant.rack.shell.copied', 'Copied'),
75
+ label: t('assistant.rack.shell.label', 'Command output'),
76
+ noOutputYet: t('assistant.rack.shell.noOutputYet', 'No output yet'),
77
+ noOutput: t('assistant.rack.shell.noOutput', 'No output'),
78
+ reading: t('assistant.rack.shell.reading', 'Reading the output…'),
79
+ running: t('assistant.rack.shell.runningNow', 'Running'),
80
+ note: (view) => shellNoteText(view, t),
81
+ },
82
+ });
83
+
84
+ // Not tied to being in the page: a row can be out of it for a moment while it is rebuilt.
85
+ const release = tracker.subscribe(shellId, request);
86
+ const watcher = typeof IntersectionObserver === 'function'
87
+ ? new IntersectionObserver((entries) => {
88
+ seen = entries[entries.length - 1].isIntersecting;
89
+ if (seen && dirty && !frame) frame = requestAnimationFrame(flush);
90
+ })
91
+ : null;
92
+ watcher?.observe(wrap);
93
+
94
+ return {
95
+ el: wrap,
96
+ /** The block is in the page again (a body rebuilt, a row opened): it measures itself and catches up. */
97
+ show() {
98
+ wrap.dispatchEvent(new Event(SHOW_EVENT));
99
+ request();
100
+ },
101
+ dispose() {
102
+ if (disposed) return;
103
+ disposed = true;
104
+ if (frame) cancelAnimationFrame(frame);
105
+ frame = 0;
106
+ watcher?.disconnect();
107
+ release();
108
+ wrap.remove();
109
+ },
110
+ };
111
+ }
@@ -469,6 +469,7 @@ export function injectAssistantStyles() {
469
469
  .asst-status { color: var(--asst-text-3); font-size: 12px; }
470
470
  .asst-status.info { color: var(--asst-text-2); }
471
471
  .asst-status.error { color: var(--asst-live); }
472
+ .asst-status .asst-stop-anyway { margin-left: 8px; vertical-align: baseline; }
472
473
  .asst-divider { display: flex; align-items: center; gap: 10px; color: var(--asst-text-3); font-size: 11px; }
473
474
  .asst-divider::before, .asst-divider::after { content: ''; flex: 1; height: 1px; background: var(--asst-line); }
474
475
 
@@ -45,6 +45,7 @@ import { isFarRowStyleRecord, stripFarRowStyles, watchTranscriptRows } from '../
45
45
  import { requestGeneratedSessionTitle } from '../session-title.js';
46
46
  import { fileLinkText } from '../ui-file-links.js';
47
47
  import { WORKER_END_CLASS, buildWorkerEndCard, endWorkerRunOnClose, forgetWorkerEnd, leaveWorkerTab } from '../ui-worker-end.js';
48
+ import { composerHoldsDraft, markAutoCloseKeep } from '../tray-auto-close.js';
48
49
  import {
49
50
  CODEX_COMMANDS, CODEX_COMMAND_BY_NAME, parseCodexCommand, codexCommandHints,
50
51
  capabilityAvailability, latestCompletedCodexText, configValue,
@@ -2685,6 +2686,24 @@ function hasMeaningfulTrayState(tab) {
2685
2686
  );
2686
2687
  }
2687
2688
 
2689
+ /**
2690
+ * What the tray's auto-close must leave open (tray-auto-close.js), or '': a tab with prompts in its queue that
2691
+ * were never sent ('queue': a paused queue, or one held behind a request or a plan approval), else a tab holding
2692
+ * an unsent draft, its text (in the composer while the tab is the one on screen), images, paths and @ mentions.
2693
+ * The user's X closes it as before. markQueueKeep repaints the mark at every change of a queue.
2694
+ */
2695
+ function autoCloseKeepOf(tab) {
2696
+ if (!tab) return '';
2697
+ if (tab.queue?.length) return 'queue';
2698
+ const input = isActiveTab(tab) ? panelEl('#cxp-input') : null;
2699
+ return composerHoldsDraft(input ? input.value : tab.draft, tab.attachedImages, tab.pendingPaths, tab.pendingMentions) ? 'draft' : '';
2700
+ }
2701
+
2702
+ /** Says a tab's keep reason to its pill: wherever a queue changes, the tab on screen's or one in the background. */
2703
+ function markQueueKeep(tab) {
2704
+ if (tab?.pillEl) markAutoCloseKeep(tab.pillEl, autoCloseKeepOf(tab));
2705
+ }
2706
+
2688
2707
  function hasCustomSessionLabel(tab) {
2689
2708
  const label = normalizeSessionLabel(tab?.pendingSessionLabel || tab?.sessionLabel || '');
2690
2709
  if (!label) return false;
@@ -2769,6 +2788,7 @@ function createTrayPill(tab) {
2769
2788
  pill.className = 'term-minimized-pill cxp-session-pill';
2770
2789
  pill.dataset.tabId = tab.id;
2771
2790
  pill.getAutomationRunId = () => tab.automationRunId;
2791
+ pill.keepFromAutoClose = () => autoCloseKeepOf(tab);
2772
2792
  pill.innerHTML = `
2773
2793
  <span class="term-minimized-pill-icon">${OPENAI_ICON}</span>
2774
2794
  <span class="term-minimized-pill-label">${esc(tab.sessionLabel || 'New session')}</span>
@@ -2814,6 +2834,7 @@ export function renderPills() {
2814
2834
  const name = tab.sessionLabel || 'New session';
2815
2835
  if (label && label.textContent !== name) label.textContent = name;
2816
2836
  paintTrayPill(tab.pillEl, tab);
2837
+ markAutoCloseKeep(tab.pillEl, autoCloseKeepOf(tab));
2817
2838
  const shouldShow = hasMeaningfulTrayState(tab) && (!_getVisible() || tab !== active);
2818
2839
  tab.pillEl.style.display = shouldShow ? '' : 'none';
2819
2840
  }
@@ -7200,6 +7221,7 @@ function tabTurnRunning(tab) {
7200
7221
  export function syncQueueTray() {
7201
7222
  const tab = activeTab();
7202
7223
  if (!tab) return;
7224
+ markQueueKeep(tab);
7203
7225
  const queue = tab.queue || [];
7204
7226
  const count = queue.length;
7205
7227
  const tray = panelEl('#cxp-queue-tray');
@@ -7312,6 +7334,7 @@ export function advanceQueue(tab = activeTab()) {
7312
7334
  if (!sent) {
7313
7335
  // Not sent: it stays first in its tab's queue.
7314
7336
  tab.queue.unshift(next);
7337
+ markQueueKeep(tab);
7315
7338
  syncQueueTray();
7316
7339
  return false;
7317
7340
  }
@@ -7320,6 +7343,8 @@ export function advanceQueue(tab = activeTab()) {
7320
7343
  appendLocalUserMessage(next.text || '', queueImages);
7321
7344
  tab._pendingSendImages = queueImages;
7322
7345
  }
7346
+ // A background tab's pill too: syncQueueTray paints the tab on screen's only.
7347
+ markQueueKeep(tab);
7323
7348
  syncQueueTray();
7324
7349
  return true;
7325
7350
  }
@@ -29,10 +29,10 @@ function fixedText() {
29
29
  put($('es-copy-url'), tx('copyAddress')); put($('es-copy-folder'), tx('copyFolder'));
30
30
  put($('es-folder-label'), tx('folderLabel'));
31
31
  put($('es-reveal'), tx(revealKey(navigator.userAgentData?.platform || navigator.platform || '')));
32
- put($('es-alternatives-title'), tx('alternativesTitle')); put($('es-restart'), tx('restart'));
32
+ put($('es-alternatives-title'), tx('alternativesTitle'));
33
33
  put($('es-back'), tx('backToApp')); put($('es-pin'), tx('pinTip'));
34
34
  put($('es-full-title'), tx('fullTitle')); put($('es-full-help'), tx('fullHelp'));
35
- put($('es-trouble-title'), tx('needHelp')); put($('es-trouble-help'), tx('helpText')); put($('es-policy-help'), tx('policyText'));
35
+ put($('es-trouble-title'), tx('needHelp')); put($('es-trouble-help'), tx('helpText')); put($('es-moved-help'), tx('movedText')); put($('es-policy-help'), tx('policyText'));
36
36
  }
37
37
  function render() {
38
38
  const view = setupView(status, { extensionVersion: extensionSeen(), pairAnswer: pairAnswer() });
@@ -45,6 +45,7 @@ function render() {
45
45
  $('es-status').dataset.tone = view.tone || 'idle';
46
46
  put($('es-status-title'), tx(view.statusTitle));
47
47
  $('es-help').hidden = !view.help; put($('es-help'), view.help ? tx(view.help) : '');
48
+ $('es-progress').hidden = !view.progress; put($('es-progress'), view.progress ? tx('downloadProgress', view.progress) : '');
48
49
  $('es-browser').hidden = !view.browser; put($('es-browser-name'), view.browser);
49
50
  $('es-steps').hidden = !view.showSteps;
50
51
  for (const step of view.steps) {
@@ -67,8 +68,8 @@ function render() {
67
68
  list.append(button);
68
69
  }
69
70
  }
70
- $('es-reload').hidden = !view.reloadNeeded; put($('es-reload'), tx('reloadNeeded', { browser: view.browser }));
71
- $('es-restart').hidden = !view.restart;
71
+ $('es-reload').hidden = !view.reloadNeeded && !view.updateNeeded; put($('es-reload'), tx(view.updateNeeded ? 'updateNeeded' : view.reloadRepaired ? 'reloadRepaired' : 'reloadNeeded', { browser: view.browser }));
72
+ $('es-restart').hidden = !view.restart; put($('es-restart'), tx(view.restartLabel));
72
73
  $('es-back').hidden = !view.back; $('es-pin').hidden = !view.pinTip;
73
74
  // The row is hidden by the code that fills it (never found by a :has(), which every hidden toggle re-checks).
74
75
  $('es-actions').hidden = !view.restart && !view.back;
@@ -80,6 +81,11 @@ async function poll() {
80
81
  busy = true;
81
82
  try {
82
83
  status = await call('status');
84
+ // The extension's content script ran on this page, on this port: the browser runs the folder's manifest for it, so
85
+ // the Reload a port change asked for is done (the server keeps saying "reload" until then). Never for a repair: the
86
+ // copy the browser still runs would answer the same, so this page only says to confirm in SynaBun Settings (and the
87
+ // server ignores `seen` for it anyway).
88
+ if (status.reloadNeeded && !status.reloadRepaired && extensionSeen() && extensionSeen() === status.folderVersion) status = await call('seen', {});
83
89
  if (wantsTicket(status, { extensionVersion: extensionSeen(), pairAnswer: pairAnswer(), offeredAt, tickets })) {
84
90
  tickets++;
85
91
  const ticket = await call('ticket', {});
@@ -1,24 +1,27 @@
1
1
  // The "Connect your browser" page's decisions (public/extension-setup.html; docs/browser-extension-bridge.md →
2
2
  // One-button setup). DOM-free and import-free: node --test loads it. The page (es-page.js) renders what this returns.
3
3
  //
4
- // Page states (data-state on <main>): the server's setup state (idle, waiting-for-extension, pairing, connected,
5
- // unsupported, error), with one page-only refinement: `extension-found` while the server still waits but the
4
+ // Page states (data-state on <main>): the server's setup state (idle, downloading, waiting-for-extension, pairing,
5
+ // connected, unsupported, error), with one page-only refinement: `extension-found` while the server still waits but the
6
6
  // extension's content script has announced itself on this page (it then gets the one-time token and pairs).
7
7
 
8
8
  /** The server's setup states, and the page's own. */
9
- export const SETUP_STATES = Object.freeze(['idle', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
9
+ export const SETUP_STATES = Object.freeze(['idle', 'downloading', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
10
10
  export const PAGE_STATES = Object.freeze([...SETUP_STATES, 'extension-found']);
11
11
  /** What the extension's service worker may answer the content script (setup-content.js writes it to data-synabun-pair). */
12
12
  export const PAIR_ANSWERS = Object.freeze(['sent', 'started', 'ALREADY_CONNECTED', 'ALREADY_PAIRED', 'PAUSED', 'BUSY', 'NOT_OWNED', 'INVALID_MESSAGE', 'REFUSED', 'EXTENSION_UNAVAILABLE']);
13
13
  /** Error codes the page has a sentence for (browserExtension.setup.error<CODE>); any other is `error`. */
14
- export const SETUP_ERRORS = Object.freeze(['SETUP_EXPIRED', 'EXTENSION_FOLDER_FAILED', 'OPEN_FAILED', 'SETUP_NOT_ACTIVE', 'SETUP_TICKETS_USED', 'PAGE_SECRET_REQUIRED', 'PEER_UNAVAILABLE']);
14
+ export const SETUP_ERRORS = Object.freeze(['SETUP_EXPIRED', 'EXTENSION_FOLDER_FAILED', 'EXTENSION_FOLDER_UNSAFE','EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED', 'OPEN_FAILED', 'SETUP_NOT_ACTIVE', 'SETUP_TICKETS_USED', 'PAGE_SECRET_REQUIRED', 'PEER_UNAVAILABLE']);
15
+ /** The errors of the extension's download (the package was not fetched or did not verify): the page offers to try again. */
16
+ export const DOWNLOAD_ERRORS = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED']);
15
17
  /** Answers after which the page asks for a fresh ticket (a new token) once its wait has passed. */
16
18
  const RETRY_AFTER = Object.freeze({ ALREADY_PAIRED: 8000, BUSY: 2500, REFUSED: 5000, EXTENSION_UNAVAILABLE: 5000, started: 20000 });
17
19
 
18
20
  /**
19
21
  * The page's view of a status (GET /api/browser/extension/setup/status) and what the page saw of the extension:
20
22
  * `extensionVersion` (data-synabun-extension, '' when absent) and `pairAnswer` (data-synabun-pair).
21
- * Returns { state, title, lead, steps, browser, extensionsUrl, folder, alternatives, live, tone, reloadNeeded, retry }.
23
+ * Returns { state, title, lead, steps, browser, extensionsUrl, folder, alternatives, live, tone, reloadNeeded, reloadRepaired, updateNeeded,
24
+ * progress, restart, restartLabel }.
22
25
  * Strings are i18n keys under browserExtension.setup (the page translates them); `params` fill their {placeholders}.
23
26
  */
24
27
  export function setupView(status = {}, { extensionVersion = '', pairAnswer = '' } = {}) {
@@ -41,25 +44,37 @@ export function setupView(status = {}, { extensionVersion = '', pairAnswer = ''
41
44
  // "Open in X instead": the installed supported browsers other than the one this setup uses.
42
45
  const alternatives = (status.installedBrowsers || []).filter(b => b?.supported && b.id !== browser?.id).map(b => ({ id: b.id, name: b.name }));
43
46
  const live = {
44
- idle: 'liveIdle', 'waiting-for-extension': 'liveWaiting', 'extension-found': PAIR_ANSWERS.includes(pairAnswer) && pairAnswer !== 'sent' && pairAnswer !== 'started' ? `answer${pairAnswer}` : 'liveFound',
47
+ idle: 'liveIdle', downloading: 'liveDownloading', 'waiting-for-extension': 'liveWaiting', 'extension-found': PAIR_ANSWERS.includes(pairAnswer) && pairAnswer !== 'sent' && pairAnswer !== 'started' ? `answer${pairAnswer}` : 'liveFound',
45
48
  pairing: 'livePairing', connected: 'liveConnected', unsupported: 'liveUnsupported', error: `error${SETUP_ERRORS.includes(status.code) ? status.code : ''}`,
46
49
  }[state];
47
50
  const tone = state === 'connected' ? 'ok' : state === 'error' || state === 'unsupported' ? 'err' : state === 'idle' ? '' : 'warn';
48
- const showSteps = !['unsupported', 'idle'].includes(state) && !(state === 'error' && !status.folder);
51
+ // No steps while the extension is on its way: there is no folder to load yet.
52
+ const showSteps = !['unsupported', 'idle', 'downloading'].includes(state) && !(state === 'error' && !status.folder);
53
+ const downloadFailed = state === 'error' && DOWNLOAD_ERRORS.includes(status.code);
54
+ // The bytes so far, in whole KB (the page shows them beside the status; never in the live region, which would be read out at every poll).
55
+ const kb = n => Math.max(0, Math.round((Number(n) || 0) / 1024));
56
+ const progress = state === 'downloading' && status.download && Number(status.download.total) > 0 ? { received: kb(Math.min(status.download.received, status.download.total)), total: kb(status.download.total) } : null;
49
57
  // The guide (the steps beside the status) while the owner installs; one result card once there is nothing to do there.
50
58
  const layout = showSteps && state !== 'connected' ? 'guide' : 'result';
51
- const statusTitle = { 'waiting-for-extension': 'waitingTitle', 'extension-found': 'foundTitle', pairing: 'pairingTitle', connected: 'titleConnected',
52
- unsupported: 'titleUnsupported', idle: 'idleTitle', error: 'errorTitle' }[state];
59
+ const statusTitle = { downloading: 'downloadingTitle', 'waiting-for-extension': 'waitingTitle', 'extension-found': 'foundTitle', pairing: 'pairingTitle', connected: 'titleConnected',
60
+ unsupported: 'titleUnsupported', idle: 'idleTitle', error: downloadFailed ? 'downloadErrorTitle' : 'errorTitle' }[state];
53
61
  return {
54
62
  layout, statusTitle, eyebrow: name ? 'eyebrow' : '',
55
- help: state === 'connected' ? 'connectedHelp' : '',
63
+ help: state === 'connected' ? 'connectedHelp' : state === 'downloading' ? 'downloadingHelp' : '',
64
+ progress,
56
65
  state, title: state === 'connected' ? 'titleConnected' : state === 'unsupported' ? 'titleUnsupported' : 'title',
57
66
  lead: state === 'unsupported' ? 'leadUnsupported' : 'lead', steps, browser: name, extensionsUrl,
58
67
  folder: typeof status.folder === 'string' ? status.folder : '', alternatives, live, liveParams: { browser: name }, tone,
59
68
  reloadNeeded: status.reloadNeeded === true,
69
+ // SynaBun replaced files that were not its extension: the same Reload, in the words of a repair.
70
+ reloadRepaired: status.reloadNeeded === true && status.reloadRepaired === true,
71
+ // The folder holds an older extension than this release's: SynaBun downloads the new one; a Reload comes after.
72
+ updateNeeded: status.updateNeeded === true && status.reloadNeeded !== true,
60
73
  showSteps,
61
74
  // What the page offers: start again (idle, error), back to SynaBun and the pin tip (connected).
62
75
  restart: ['error', 'idle'].includes(state), back: state === 'connected', pinTip: state === 'connected',
76
+ // A download that failed is tried again by the same button, under its own words.
77
+ restartLabel: downloadFailed ? 'retryDownload' : 'restart',
63
78
  // "Open in X instead" while there is still something to install here; never once pairing began.
64
79
  showAlternatives: alternatives.length > 0 && !['pairing', 'connected'].includes(state),
65
80
  };
@@ -33,6 +33,7 @@ import { dropdownHTML, dropdownOf, setDropdownDisabled, setDropdownItems, wireDr
33
33
  import { renderMarkdown } from '../cp/cp-markdown.js';
34
34
  import { fetchProjects } from '../api.js';
35
35
  import { createStickyScrollController } from '../ui-scroll-follow.js';
36
+ import { composerHoldsDraft, markAutoCloseKeep } from '../tray-auto-close.js';
36
37
 
37
38
  export const PANEL_OWNER = 'maritaca-sidepanel';
38
39
  const ICON = ICONS.mark;
@@ -368,7 +369,7 @@ async function stageFiles(files) {
368
369
  }
369
370
  saveTabs();
370
371
  } catch (error) { showBanner(T('attachmentFailed', { name: '', error: error.message }), 'error'); }
371
- finally { tab.pendingAttachments = false; renderComposer(); }
372
+ finally { tab.pendingAttachments = false; renderComposer(); renderPills(); }
372
373
  }
373
374
 
374
375
  async function copyText(text) {
@@ -738,6 +739,18 @@ async function switchBranch(branch) {
738
739
  await loadBranches(project);
739
740
  }
740
741
  }
742
+ // What the tray's auto-close must leave open (tray-auto-close.js), or '': a tab holding an unsent draft, its text (in
743
+ // the composer while the tab is the one on screen) or its staged attachments, and while a message is being edited the
744
+ // draft and attachments the edit put aside. Its X (closeTab) throws them away; the user's X closes it as before.
745
+ function autoCloseKeepOf(tab) {
746
+ if (!tab) return '';
747
+ const input = tab === activeTab() ? $('.mtc-input') : null;
748
+ const editing = tab.editingIndex != null;
749
+ const held = composerHoldsDraft(input ? input.value : tab.draft, tab.attachments)
750
+ || (editing && composerHoldsDraft(tab.beforeEdit, tab.beforeEditAttachments));
751
+ return held ? 'draft' : '';
752
+ }
753
+
741
754
  function renderPills() {
742
755
  const tray = document.getElementById('term-minimized-tray');
743
756
  for (const tab of _tabs) {
@@ -748,6 +761,7 @@ function renderPills() {
748
761
  pill.dataset.tabId = tab.id;
749
762
  pill.tabIndex = 0;
750
763
  pill.setAttribute('role', 'button');
764
+ pill.keepFromAutoClose = () => autoCloseKeepOf(tab);
751
765
  pill.innerHTML = `<span class="mtc-pill-ring" aria-hidden="true"><i></i></span><span class="term-minimized-pill-icon mtc-mark">${ICON}</span><span class="term-minimized-pill-label"></span><button class="term-minimized-pill-close" data-tooltip="${esc(T('closeTab'))}" aria-label="${esc(T('closeTab'))}">&times;</button>`;
752
766
  // A closed panel goes to this tab first and is shown after: showing it first drew, and loaded the session
753
767
  // of, the tab it was left on before the one that was clicked.
@@ -762,6 +776,7 @@ function renderPills() {
762
776
  const label = tab.pillEl.querySelector('.term-minimized-pill-label');
763
777
  if (label) label.textContent = tabLabel(tab, T);
764
778
  tab.pillEl.classList.toggle('mtc-pill-running', !!tab.running);
779
+ markAutoCloseKeep(tab.pillEl, autoCloseKeepOf(tab));
765
780
  const meaningful = !!(tab.sessionId || tab.running || tab.draft || tab.attachments?.length);
766
781
  tab.pillEl.style.display = meaningful && (!_visible || tab !== activeTab()) ? '' : 'none';
767
782
  }
@@ -1196,7 +1211,7 @@ function wire() {
1196
1211
  $('#mtc-model')?.addEventListener('change', (event) => { const tab = activeTab(); if (!tab) return; tab.model = event.target.value || null; tab.effort = null; saveTabs(); renderComposer(); renderHeader(); renderContextPop(); });
1197
1212
  $('.mtc-attach')?.addEventListener('click', () => $('.mtc-file-input')?.click());
1198
1213
  $('.mtc-file-input')?.addEventListener('change', (event) => { stageFiles([...event.target.files]); event.target.value = ''; });
1199
- $('.mtc-staged')?.addEventListener('click', (event) => { const remove = event.target.closest('[data-remove-attachment]'); const tab = activeTab(); if (!remove || tab?.submitting) return; tab.attachments.splice(Number(remove.dataset.removeAttachment), 1); saveTabs(); renderComposer(); });
1214
+ $('.mtc-staged')?.addEventListener('click', (event) => { const remove = event.target.closest('[data-remove-attachment]'); const tab = activeTab(); if (!remove || tab?.submitting) return; tab.attachments.splice(Number(remove.dataset.removeAttachment), 1); saveTabs(); renderComposer(); renderPills(); });
1200
1215
  input?.addEventListener('paste', (event) => { const files = [...(event.clipboardData?.files || [])]; if (files.length) { event.preventDefault(); stageFiles(files); } });
1201
1216
  let dragDepth = 0;
1202
1217
  _panel.addEventListener('dragenter', (event) => { if (![...(event.dataTransfer?.types || [])].includes('Files')) return; event.preventDefault(); dragDepth++; _panel.classList.add('mtc-dragging'); });
@@ -196,6 +196,11 @@ export function applyEvent(store, eventType, ev = {}, hooks = {}) {
196
196
  hooks.onOutcome?.(store, 'error');
197
197
  break;
198
198
  }
199
+ case 'shell.updated':
200
+ // A tool call's shell command: started, running on after its call (in the
201
+ // background), ended. What it prints is read apart (ocp-v2-shell-logic.js).
202
+ if (ev.shell) store.upsertShell?.(ev.shell);
203
+ break;
199
204
  case 'todo.updated':
200
205
  store.setTodos(ev.todos);
201
206
  break;
@@ -978,6 +978,7 @@ let _lastWaitingPill = null;
978
978
  // when it is first shown.
979
979
  const PILL_API = {
980
980
  sessionStatus: (args) => api.sessionStatus(args),
981
+ shellList: (args) => api.shellList(args),
981
982
  permissionList: (args) => api.permissionList(args),
982
983
  questionList: (args) => api.questionList(args),
983
984
  };
@@ -29,7 +29,7 @@ import {
29
29
  import {
30
30
  forkSession, undoLastTurn, restoreReverted,
31
31
  loadSelectedSession, applySessionSelections, restoreDraftAttachments,
32
- readTranscriptExport, stopForNavigation, createSessionForNavigation, renameSession,
32
+ readTranscriptExport, stopForNavigation, noteAbandoned, createSessionForNavigation, renameSession,
33
33
  navigateAfter, adoptReusableSession, landWithoutTabs, shouldNameCreatedSession, renameBox,
34
34
  } from './ocp-v2-session-actions.js';
35
35
  import { captureBinding, latestFor, createNavigation } from './ocp-v2-binding.js';
@@ -2168,8 +2168,14 @@ function deleteSessionBestEffort(sessionId, { abort = false, context = 'delete'
2168
2168
  if (!sessionId) return Promise.resolve({ ok: true });
2169
2169
  return (async () => {
2170
2170
  if (abort) {
2171
- try { await api.abort(sessionId); }
2171
+ // The tab is going: nobody is left to press Stop again, so a command Stop cannot end is given up on ("Stop
2172
+ // anyway": it is still removed in the background, and its end wakes no model turn).
2173
+ let stopped = null;
2174
+ try { stopped = await api.abort(sessionId, { force: true }); }
2172
2175
  catch (err) { console.warn(`[ocp-v2-panel] abort before ${context} failed`, err); }
2176
+ // What it gave up on may still be running: the panel, still open on another tab, says so.
2177
+ // (Best effort: the notice never holds up the deletion.)
2178
+ try { await noteAbandoned(getDefaultStore(), stopped, t); } catch { /* the close goes on */ }
2173
2179
  }
2174
2180
  let res;
2175
2181
  try { res = await api.sessionDelete(sessionId); }
@@ -2433,6 +2439,7 @@ function createTabPill(sessionId) {
2433
2439
  pill.dataset.sessionId = sessionId;
2434
2440
  pill.getAutomationRunId = () => _automationRunIds.get(sessionId);
2435
2441
  pill.hasQueuedWorkerPrompts = () => _automationRunIds.has(sessionId) && promptsWaitingFor(sessionId).length > 0;
2442
+ pill.detachForAutoClose = () => detachTabForAutoClose(sessionId);
2436
2443
  pill.innerHTML = `
2437
2444
  <span class="ocpv2-pill-ring" aria-hidden="true"><i></i></span>
2438
2445
  <span class="term-minimized-pill-icon">${OPENCODE_ICON}</span>
@@ -2470,6 +2477,20 @@ async function closeTabByUser(sessionId, context, { deleteBeforeClose = false }
2470
2477
  return true;
2471
2478
  }
2472
2479
 
2480
+ // The tray's auto-close toggle, for a session that names no run. Unlike the X,
2481
+ // which deletes the session, this only takes the tab and its pill away: the
2482
+ // session and its transcript stay in OpenCode and the session menu opens them
2483
+ // again. Nobody chose this close, so nobody is asked: a turn that started or a
2484
+ // prompt still waiting keeps the tab. Resolves whether the tab went.
2485
+ async function detachTabForAutoClose(sessionId) {
2486
+ const working = sessionId === getState().sessionId ? !!getState().running : _sessionBusy.get(sessionId) === true;
2487
+ if (!_tabSessionIds.includes(sessionId) || _automationRunIds.has(sessionId) || working
2488
+ || promptsWaitingFor(sessionId).length) return false;
2489
+ try { await handlePillClose(sessionId); }
2490
+ catch (err) { console.warn('[ocp-v2-panel] auto-close detach failed', err); }
2491
+ return true;
2492
+ }
2493
+
2473
2494
  // The end of a worker the Assistant dispatched: its button closes the tab the
2474
2495
  // way the tab's X does (a warm worker that finished its task is completed, one
2475
2496
  // still at work is stopped; its record stays for the Assistant) and shows the
@@ -2776,6 +2797,17 @@ export async function attachOpenCodeAutomation(run, { focus = !!run?.focus, isCa
2776
2797
  _tabInfoCache.set(sessionId, cachedInfo);
2777
2798
  pushError({ message: run.error });
2778
2799
  }
2800
+ // A stop of the run (a worker's, a loop's) that could not end a command in the background: it may still be
2801
+ // running, and the tab says so once (lib/native-loop-runtime.js abandonedCommands; the words are the panel Stop's).
2802
+ if (Array.isArray(run.abandonedCommands) && run.abandonedCommands.length && getState().sessionId === sessionId
2803
+ && !_tabInfoCache.get(sessionId)?._automationAbandonedShown) {
2804
+ const cachedInfo = _tabInfoCache.get(sessionId) || info;
2805
+ cachedInfo._automationAbandonedShown = true;
2806
+ _tabInfoCache.set(sessionId, cachedInfo);
2807
+ const view = await import('../shell-stop-view.js').catch(() => null);
2808
+ const left = view?.describeAbandoned(run.abandonedCommands, t) || null;
2809
+ if (left) pushError({ message: left, kind: 'shell-stop', notice: true });
2810
+ }
2779
2811
  trackWorkerEnd(run, { apply: (view) => showWorkerEnd(sessionId, view) });
2780
2812
  renderPill();
2781
2813
  syncSavedTabWaiting();
@@ -155,7 +155,7 @@ function bindingCheck(store, sessionId, isCurrent) {
155
155
  * that was closed meanwhile. Resolves what it applied, for the caller's log.
156
156
  */
157
157
  export async function rehydrateSessionState(store, api, { sessionId, cwd, hasPanel, isDescendant, isCurrent } = {}) {
158
- const applied = { status: false, permissions: false, questions: false, todos: false };
158
+ const applied = { status: false, permissions: false, questions: false, todos: false, shells: false };
159
159
  if (!sessionId) return applied;
160
160
  const stillBound = bindingCheck(store, sessionId, isCurrent);
161
161
  const revisionOf = (slice) => (typeof store.getRevisions === 'function' ? store.getRevisions()[slice] : 0);
@@ -200,6 +200,12 @@ export async function rehydrateSessionState(store, api, { sessionId, cwd, hasPan
200
200
  () => (api.sessionTodo ? api.sessionTodo({ sessionId, cwd }) : { ok: false }),
201
201
  (res) => (Array.isArray(res.data) ? res.data : undefined),
202
202
  (todos) => store.setTodos(todos)),
203
+ // The commands of the session's tool calls: one that still runs (also after
204
+ // its call ended) is followed again, with its output, from where it is now.
205
+ sync('shells',
206
+ () => (api.shellList && typeof store.setShells === 'function' ? api.shellList({ sessionId, cwd }) : { ok: false }),
207
+ (res) => (Array.isArray(res.data) ? res.data : undefined),
208
+ (shells) => store.setShells(shells)),
203
209
  ]);
204
210
  return applied;
205
211
  }
@@ -42,6 +42,7 @@ import {
42
42
  revertToMessage, restoreReverted, retryFromMessage, forkSession,
43
43
  } from './ocp-v2-session-actions.js';
44
44
  import { synabunToolKey, synabunToolLabel, synabunToolSummary } from '../synabun-tools.js';
45
+ import { renderShellTerminal, retainShellFollowing, shellOutputSupported } from './ocp-v2-shell.js';
45
46
 
46
47
  const _expandedReasoningIds = new Set();
47
48
  const _activeRenderers = new Set();
@@ -117,13 +118,22 @@ export function mountRenderer(containerEl, store = getDefaultStore(), opts = {})
117
118
  // The server listed this session's open permission requests: a reason
118
119
  // typed for one that is no longer among them has no card to come back to.
119
120
  if (event?.type === 'permission:set' && event.listed) settlePermissionReasons(state);
121
+ // What a command printed is drawn by its own terminal block (ocp-v2-shell.js): no card is built again for
122
+ // it. The transcript only keeps its place at the end while the block grows.
123
+ if (event?.type === 'shell:output') {
124
+ requestAnimationFrame(() => { if (_container) scrollController?.scrollToBottom(); });
125
+ return;
126
+ }
120
127
  scheduleRender();
121
128
  });
129
+ // The commands of this panel's session are followed for as long as it is on screen.
130
+ const releaseShells = retainShellFollowing(store);
122
131
 
123
132
  const instance = {
124
133
  render: doRender,
125
134
  unmount: () => {
126
135
  try { unsubscribe(); } catch {}
136
+ try { releaseShells(); } catch {}
127
137
  scrollController?.destroy();
128
138
  rowWatcher.disconnect();
129
139
  _activeRenderers.delete(instance);
@@ -155,6 +165,18 @@ function _partSig(part) {
155
165
  return sig;
156
166
  }
157
167
 
168
+ // A bash card also shows its command as the panel knows it live (running on after the call, ended, its exit
169
+ // code): the card is built again when that changes, never for what the command prints.
170
+ function _shellOf(part, state) {
171
+ if (part?.type !== 'tool') return null;
172
+ const shellId = part.state?.metadata?.shellID;
173
+ return typeof shellId === 'string' && shellId ? state.shells?.get(shellId) || null : null;
174
+ }
175
+ function _shellSig(part, state) {
176
+ const shell = _shellOf(part, state);
177
+ return shell ? `|sh:${shell.status}:${shell.background ? 'b' : ''}:${shell.exit ?? ''}:${shellOutputSupported() ? 'l' : ''}` : '';
178
+ }
179
+
158
180
  function _msgSig(msg) {
159
181
  let sig = `m:${msg.role || 'assistant'}`;
160
182
  for (const part of visibleParts(msg)) sig += '|' + _partSig(part);
@@ -299,7 +321,7 @@ function render(_container, store, opts = {}) {
299
321
  const partKey = part.id || `${part.type}:${part.index ?? ''}`;
300
322
  desired.push({
301
323
  key: `a:${msg.id}:${partKey}`,
302
- sig: `${isContinuation ? 'c' : 'h'}|${msg.info?.summary ? 's' : ''}|${_partSig(part)}`,
324
+ sig: `${isContinuation ? 'c' : 'h'}|${msg.info?.summary ? 's' : ''}|${_partSig(part)}${_shellSig(part, s)}`,
303
325
  build: () => renderAssistantPartBubble(msg, part, isContinuation, store),
304
326
  });
305
327
  prevAssistantId = msg.id;
@@ -1012,6 +1034,9 @@ function renderToolPart(part, store) {
1012
1034
  return holder;
1013
1035
  },
1014
1036
  onOpenChild: _rendererOpts.get(store)?.onOpenChild || null,
1037
+ shell: _shellOf(part, store.getState()),
1038
+ // An older server cannot be asked for a command's output: the card shows what the call returned.
1039
+ terminal: shellOutputSupported() ? (shellId) => renderShellTerminal(store, shellId) : null,
1015
1040
  });
1016
1041
  }
1017
1042