fix(agent): allow remaining actions for an approved task (#6113)

* fix(agent): allow remaining actions for an approved task

* fix(agent): make approval continuation control-only

* fix(ci): preserve approval taint and cache-buster contract

* fix(ui): keep tool approvals in current chat

* fix(ui): route tool approvals through chat submit

* test(ui): pin approval submit routing

* fix(agent): complete approval denial flow

* fix(ui): avoid duplicate ask-user close icon

* fix(agent): retain approved tool in continuation set

* revert(ui): keep PR 6113 scoped to approval continuation

* fix(agent): add task and chat approval scopes

* fix(ui): prevent duplicate ask-user close icon

* feat(ui): add ask-user option shortcuts

* fix(compare): route ask-user choices per pane

* fix(agent): keep skill-test approvals to a single action

The chat card now reuses the wire value `approve` to mean chat-session
scope, and `consume()` returned `allow_remaining_actions=True` for it
unconditionally. The skill-test approval route was never updated: it still
sends `approve` meaning "once", and its button still reads "Allow once",
but the grant it got back set `approval_gate_bypassed` for the rest of the
resumed run. That surface wraps the skill body and every transcript byte
as untrusted context, so it is the last place where one click should
ungate everything that follows.

Give `consume()` an explicit `allow_continuation` flag. Callers that own a
resumable chat keep the scope the user picked; callers that do not — the
skill tester, unattended audits — get SINGLE_ACTION and the gate re-arms
behind the sealed action, which is what their label promises.

* fix(ui): cache-bust every module the approval click depends on

chatStream.js, compare/index.js and compare/stream.js all changed
behaviour but kept their old `?v=`, while chat.js and chatRenderer.js were
bumped. A returning browser therefore serves the new chat.js — which now
deliberately leaves the composer empty and clicks the send button — next to
the cached chatStream.js that has no interceptor. With an empty composer
that button sits at `data-mode="newchat"`, so the click opens a new chat
and the approval is dropped.

Bump the three, and version compare/stream.js's chatRenderer import to
match everyone else's so the ask_user keydown listener binds to one module
instance instead of two.

* fix(ui): keep the digit shortcuts off tool approval cards

With an approval card on screen and focus anywhere outside an input, a bare
`1` fired `approve_task` — the widest of the three grants — with no
modifier and no confirmation. That card is the one control whose entire
purpose is deliberate consent after untrusted context influenced the run,
and Deny sits at 3.

Label the card with its kind and skip the shortcut for approvals. Ordinary
ask_user questions keep 1-3.

* fix(compare): restore a pane's ask_user card instead of dropping the choice

renderAskUserCard removes the card as soon as onSubmit accepts, but the
resume loop gave up silently after 10s if the originating stream still owned
the pane. The user saw the click land, the card vanish, and nothing happen,
with no way to get it back.

Re-render the card on that deadline and say why. The reroll case still
returns without sending — that choice belongs to a stream that no longer
exists.

* refactor(chat): drop the unreachable deny branch

`if decision != "deny"` is always true — the deny path returns a
StreamingResponse a few lines above. It reads as if deny still falls
through to the toggle restore.

---------

Co-authored-by: Léo <leograndcontact@gmail.com>
This commit is contained in:
RaresKeY
2026-08-19 08:01:34 -06:00
committed by GitHub
co-authored by Léo
parent 5c835014ac
commit 981652358e
20 changed files with 1361 additions and 119 deletions
+3 -3
View File
@@ -10,8 +10,8 @@ import modelsModule from './js/models.js?v=20260715startupcalm2';
import ragModule from './js/rag.js';
import presetsModule from './js/presets.js';
import searchModule from './js/search.js';
import chatModule from './js/chat.js?v=20260815toolapproval4';
import compareModule from './js/compare/index.js?v=20260723compareicon2';
import chatModule from './js/chat.js?v=20260819approvalcontrol1';
import compareModule from './js/compare/index.js?v=20260819approvalcontrol1';
import documentModule from './js/document.js?v=20260815approvalsave1';
import searchChatModule from './js/search-chat.js';
import { makeWindowDraggable } from './js/windowDrag.js';
@@ -22,7 +22,7 @@ import {
settleSessionHydration
} from './js/startupShell.js';
import markdownModule from './js/markdown.js';
import chatRenderer from './js/chatRenderer.js?v=20260815toolapproval4';
import chatRenderer from './js/chatRenderer.js?v=20260819approvalcontrol1';
import sessionModule from './js/sessions.js';
import memoryModule from './js/memory.js?v=20260722memoryloading1';
import voiceRecorderModule from './js/voiceRecorder.js';
+3 -3
View File
@@ -2572,10 +2572,10 @@
<script type="module" src="/static/js/tts-ai.js"></script>
<script type="module" src="/static/js/document.js?v=20260815approvalsave1"></script>
<script type="module" src="/static/js/gallery.js?v=20260708match1"></script>
<script type="module" src="/static/js/chatRenderer.js?v=20260815toolapproval4"></script>
<script type="module" src="/static/js/chatRenderer.js?v=20260819approvalcontrol1"></script>
<script type="module" src="/static/js/codeRunner.js"></script>
<script type="module" src="/static/js/chatStream.js?v=20260815approvalsave1"></script>
<script type="module" src="/static/js/chat.js?v=20260815toolapproval4"></script>
<script type="module" src="/static/js/chatStream.js?v=20260819approvalcontrol1"></script>
<script type="module" src="/static/js/chat.js?v=20260819approvalcontrol1"></script>
<script type="module" src="/static/js/cookbook.js"></script>
<script src="/static/js/cookbookSchedule.js"></script>
<script type="module" src="/static/js/search-chat.js"></script>
+19 -16
View File
@@ -8,8 +8,8 @@
import Storage from './storage.js';
import uiModule from './ui.js';
import sessionModule from './sessions.js';
import chatRenderer from './chatRenderer.js?v=20260815toolapproval4';
import chatStream from './chatStream.js?v=20260815approvalsave1';
import chatRenderer from './chatRenderer.js?v=20260819approvalcontrol1';
import chatStream from './chatStream.js?v=20260819approvalcontrol1';
import { addAITTSButton } from './tts-ai.js';
import markdownModule from './markdown.js';
import spinnerModule from './spinner.js';
@@ -62,20 +62,18 @@ import { loadPanel } from './panels.js';
let _contextHeaderBound = false;
let _pendingToolApproval = null;
function _submitToolApprovalWhenIdle(approvalId, label) {
function _submitToolApprovalWhenIdle(approvalId) {
if (
!_pendingToolApproval
|| _pendingToolApproval.approval_id !== approvalId
) return;
if (isStreaming || _sendInFlight) {
setTimeout(() => _submitToolApprovalWhenIdle(approvalId, label), 120);
setTimeout(() => _submitToolApprovalWhenIdle(approvalId), 120);
return;
}
const input = document.getElementById('message');
if (input) {
_pendingToolApproval.draft = input.value || '';
input.value = label;
input.dispatchEvent(new Event('input', { bubbles: true }));
}
const sendButton = document.querySelector('.send-btn');
if (sendButton) sendButton.click();
@@ -84,16 +82,13 @@ import { loadPanel } from './panels.js';
document.addEventListener('odysseus:tool-approval', (event) => {
const detail = event && event.detail ? event.detail : {};
const decision = String(detail.decision || '').toLowerCase();
if (!detail.approval_id || !['approve', 'deny'].includes(decision)) return;
if (!detail.approval_id || !['approve', 'approve_task', 'deny'].includes(decision)) return;
_pendingToolApproval = {
approval_id: String(detail.approval_id),
decision,
document_id: String(detail.document_id || ''),
};
_submitToolApprovalWhenIdle(
_pendingToolApproval.approval_id,
detail.label || (decision === 'approve' ? 'Allow once' : 'Deny'),
);
_submitToolApprovalWhenIdle(_pendingToolApproval.approval_id);
});
function _fmtContextNumber(n) {
@@ -1309,10 +1304,10 @@ import { loadPanel } from './panels.js';
}
const el = uiModule.el;
const msg = el('message').value;
const msg = approvalForSend ? '' : el('message').value;
// Allow empty text when a regen carries over the original message's
// attachment ids — a photo-only message still has something to send.
if (!msg.trim() && !fileHandlerModule.getPendingCount() && !(_pendingRegenAttachments && _pendingRegenAttachments.length)) { _releaseSendFlag(); return; }
if (!msg.trim() && !approvalForSend && !fileHandlerModule.getPendingCount() && !(_pendingRegenAttachments && _pendingRegenAttachments.length)) { _releaseSendFlag(); return; }
// --- Slash commands: execute directly without AI (no session needed) ---
if (!approvalForSend && isCommand(msg.trim())) {
@@ -1590,7 +1585,7 @@ import { loadPanel } from './panels.js';
const userDisplay = _displayOverride || msg;
_displayOverride = null;
const skipBubble = _hideUserBubble;
const skipBubble = _hideUserBubble || !!approvalForSend;
_hideUserBubble = false;
// Auto-recovery counter: carries across a turn's auto-continues, but resets
// when the user genuinely sends a new message (so each task gets a fresh cap).
@@ -1833,7 +1828,7 @@ import { loadPanel } from './panels.js';
if (_inject.suffix) _finalMsgWithInject = _finalMsgWithInject + ' ' + _inject.suffix;
const fd = new FormData();
fd.append('message', _finalMsgWithInject);
fd.append('message', approvalForSend ? '' : _finalMsgWithInject);
fd.append('session', streamSessionId);
if (approvalForSend) {
fd.append('tool_approval_id', approvalForSend.approval_id);
@@ -2873,7 +2868,7 @@ import { loadPanel } from './panels.js';
if (spinner && spinner.element) spinner.destroy();
break;
}
if (json.delta || json.type === 'agent_prep' || json.type === 'generated_image' || json.type === 'tool_start' || json.type === 'tool_output' || json.type === 'tool_progress' || json.type === 'agent_step' || json.type === 'loop_breaker_triggered' || json.type === 'intent_nudge_exhausted' || json.type === 'doc_stream_open' || json.type === 'doc_stream_delta' || json.type === 'research_progress') {
if (json.delta || json.type === 'agent_prep' || json.type === 'tool_approval_resolved' || json.type === 'generated_image' || json.type === 'tool_start' || json.type === 'tool_output' || json.type === 'tool_progress' || json.type === 'agent_step' || json.type === 'loop_breaker_triggered' || json.type === 'intent_nudge_exhausted' || json.type === 'doc_stream_open' || json.type === 'doc_stream_delta' || json.type === 'research_progress') {
clearResponseTimeout();
clearProcessingProbe();
clearFirstTokenWaitTimers();
@@ -2890,6 +2885,14 @@ import { loadPanel } from './panels.js';
}
continue;
}
if (json.type === 'tool_approval_resolved') {
_cancelThinkingTimer();
_removeThinkingSpinner();
if (spinner && spinner.element) spinner.destroy();
if (!_isBg && roundHolder && roundHolder !== holder) roundHolder.remove();
if (!_isBg && holder) holder.remove();
continue;
}
if (json.delta) {
_cancelThinkingTimer();
_removeThinkingSpinner();
+75 -15
View File
@@ -2327,6 +2327,42 @@ export function removeAskUserCards(root) {
scope.querySelectorAll('.ask-user-card').forEach((node) => node.remove());
}
// While a choice card is visible, let plain 1–3 activate the corresponding
// rendered option. Reuse the option's click path so the question keeps its
// existing submission semantics. Tool approval cards are excluded: that card
// exists to make consent deliberate after untrusted context influenced the
// run, and its first option is the widest grant, so a stray digit must not
// answer it.
function _handleAskUserShortcut(event) {
if (
event.defaultPrevented
|| event.repeat
|| event.isComposing
|| event.ctrlKey
|| event.altKey
|| event.metaKey
|| event.shiftKey
) return;
if (!/^[1-3]$/.test(event.key)) return;
const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
const focusedCard = document.activeElement?.closest?.('.ask-user-card') || null;
const mainCard = document.querySelector('#chat-history .ask-user-card');
const compareCards = document.querySelectorAll('.compare-pane .ask-user-card');
const card = focusedCard || mainCard || (compareCards.length === 1 ? compareCards[0] : null);
if (!card) return;
if (card.dataset.askUserKind === 'tool_approval') return;
const option = card.querySelectorAll('.ask-user-option')[Number(event.key) - 1];
if (!option || option.disabled) return;
event.preventDefault();
option.click();
}
document.addEventListener('keydown', _handleAskUserShortcut);
/**
* Render an ask_user payload as a durable choice card.
*
@@ -2336,11 +2372,15 @@ export function removeAskUserCards(root) {
*/
export function renderAskUserCard(payload, options) {
const aq = payload || {};
if (aq.resolved) return null;
const opts = Array.isArray(aq.options) ? aq.options : [];
const chatBox = document.getElementById('chat-history');
const renderOptions = options || {};
const chatBox = renderOptions.root || document.getElementById('chat-history');
const onSubmit = typeof renderOptions.onSubmit === 'function'
? renderOptions.onSubmit
: null;
if (!chatBox || !aq.question || opts.length < 2) return null;
const renderOptions = options || {};
removeAskUserCards(chatBox);
const card = document.createElement('div');
@@ -2349,6 +2389,7 @@ export function renderAskUserCard(payload, options) {
card.tabIndex = -1;
const multi = !!aq.multi;
const isToolApproval = aq.kind === 'tool_approval' && !!aq.approval_id;
card.dataset.askUserKind = isToolApproval ? 'tool_approval' : 'question';
const emojiText = (value) => svgifyEmoji(uiModule.esc(String(value)));
const head = document.createElement('div');
@@ -2357,7 +2398,6 @@ export function renderAskUserCard(payload, options) {
closeBtn.type = 'button';
closeBtn.className = 'modal-close ask-user-close';
closeBtn.setAttribute('aria-label', 'Dismiss question');
closeBtn.textContent = '×';
closeBtn.addEventListener('click', () => {
card.remove();
const input = uiModule.el('message');
@@ -2400,6 +2440,17 @@ export function renderAskUserCard(payload, options) {
const send = (text) => {
if (!text) return;
if (onSubmit) {
const accepted = onSubmit({
kind: 'answer',
text,
label: text,
payload: aq,
card,
});
if (accepted !== false) card.remove();
return;
}
card.remove();
const input = uiModule.el('message');
if (input) input.value = text;
@@ -2433,17 +2484,26 @@ export function renderAskUserCard(payload, options) {
row.type = 'button';
row.addEventListener('click', () => {
if (isToolApproval) {
card.remove();
document.dispatchEvent(new CustomEvent('odysseus:tool-approval', {
detail: {
approval_id: aq.approval_id,
decision: String((opt && opt.value) || '').toLowerCase(),
label,
document_id: aq.action && aq.action.document_id
? String(aq.action.document_id)
: '',
},
}));
const detail = {
approval_id: aq.approval_id,
decision: String((opt && opt.value) || '').toLowerCase(),
label,
document_id: aq.action && aq.action.document_id
? String(aq.action.document_id)
: '',
};
if (onSubmit) {
const accepted = onSubmit({
kind: 'tool_approval',
...detail,
payload: aq,
card,
});
if (accepted !== false) card.remove();
} else {
card.remove();
document.dispatchEvent(new CustomEvent('odysseus:tool-approval', { detail }));
}
} else {
send(label);
}
@@ -2628,7 +2688,7 @@ export function addMessage(role, content, modelName, metadata) {
box.appendChild(threadWrap);
}
for (const ev of roundTools) {
if (ev.ask_user) pendingAskUser = ev.ask_user;
if (ev.ask_user && !ev.ask_user.resolved) pendingAskUser = ev.ask_user;
const ok = (ev.exit_code === 0 || ev.exit_code == null);
let outHtml = '';
if (ev.output && ev.output.trim()) {
+29
View File
@@ -9,6 +9,35 @@ import markdownModule from './markdown.js';
import sessionModule from './sessions.js';
import documentModule from './document.js?v=20260815approvalsave1';
// Tool approvals are control-plane submits for the current chat. chat.js
// deliberately leaves the composer untouched, then programmatically clicks the
// shared send button after it records the sealed approval id/decision. That
// button is polymorphic: with an empty composer it can mean New chat or Record
// voice instead of Send. Intercept only the programmatic approval click and
// route it through the form submit path, which already reaches chat.js directly.
document.addEventListener('odysseus:tool-approval', () => {
const sendButton = document.querySelector('.send-btn');
const chatForm = document.getElementById('chat-form');
if (!sendButton || !chatForm) return;
const interceptApprovalClick = (event) => {
// A real user click must retain the normal send/new-chat/STT behavior.
if (event.isTrusted) return;
sendButton.removeEventListener('click', interceptApprovalClick, true);
event.preventDefault();
event.stopImmediatePropagation();
if (chatForm.requestSubmit) chatForm.requestSubmit();
else chatForm.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
};
sendButton.addEventListener('click', interceptApprovalClick, true);
// Fail-safe cleanup if the approval continuation never reaches its deferred
// synthetic click (for example because the surrounding view is torn down).
setTimeout(() => {
sendButton.removeEventListener('click', interceptApprovalClick, true);
}, 60000);
}, true);
/**
* Handle a ui_control SSE event — AI-driven UI manipulation.
* Extracted from the duplicated ui_control + tool_output.ui_event handlers.
+12 -7
View File
@@ -21,7 +21,7 @@ import { EVAL_PROMPTS, WAVE_FRAMES,
import { fetchModels, _persistSelections, _modelDisplayNames, getExcludedModels, setExcludedModels } from './models.js';
import { showModelSelector, disableToolToggles, restoreToolToggles, _syncToolbarIndicator } from './selector.js?v=20260723compareicon2';
import { _checkUnprobed, _clearProbeWaves } from './probe.js';
import { streamToPane, _renderSearchResults, _runSynthForPane, _formatMs, registerStreamActions } from './stream.js';
import { streamToPane, _renderSearchResults, _runSynthForPane, _formatMs, registerStreamActions } from './stream.js?v=20260819approvalcontrol1';
import {
stopAll, stopPane, rerollPane, shufflePanePositions, resetCompare,
_addPane, _removePane, toggleExpandPane, togglePanePreview, copyPaneResponse,
@@ -1006,11 +1006,16 @@ async function _executeCompare(message) {
console.error('Compare error:', err);
if (uiModule) uiModule.showError('Compare failed: ' + err.message);
} finally {
state._streaming = false;
_setSendBtn('send');
// Re-enable header buttons
document.querySelectorAll('#compare-shuffle-btn, #compare-check-btn, #compare-add-btn').forEach(b => {
b.disabled = false; b.style.opacity = '0.7'; b.style.pointerEvents = '';
// A pane may have started its own ask_user/approval continuation while the
// original all-pane Promise was settling. Keep Compare busy until every
// pane-owned controller is gone instead of exposing a second broadcast send.
const compareStillStreaming = state._abortControllers.some(Boolean);
state._streaming = compareStillStreaming;
_setSendBtn(compareStillStreaming ? 'stop' : 'send');
document.querySelectorAll('#compare-shuffle-btn, #compare-check-btn, #compare-add-btn').forEach((button) => {
button.disabled = compareStillStreaming;
button.style.opacity = compareStillStreaming ? '0.25' : '0.7';
button.style.pointerEvents = compareStillStreaming ? 'none' : '';
});
}
}
@@ -1514,7 +1519,7 @@ async function showShufflePoolEditor() {
// ────────────────────────────────────────────────────────────────────────────
registerCompareActions({ stopAll, resetCompare });
registerStreamActions({ rerollPane, autoPreviewHtml: _autoPreviewHtml });
registerStreamActions({ rerollPane, autoPreviewHtml: _autoPreviewHtml, setSendBtn: _setSendBtn });
registerPaneActions({ setSendBtn: _setSendBtn, deactivate, streamToPane, renderSearchResults: _renderSearchResults, fetchModels });
// ────────────────────────────────────────────────────────────────────────────
+189 -6
View File
@@ -1,7 +1,7 @@
// compare/stream.js — SSE streaming to panes
import state from './state.js';
import { addFinishBadge } from './vote.js';
import { getModelCost, safeDisplayImageSrc } from '../chatRenderer.js';
import { getModelCost, renderAskUserCard, safeDisplayImageSrc } from '../chatRenderer.js?v=20260819approvalcontrol1';
import markdownModule from '../markdown.js';
import spinnerModule from '../spinner.js';
import uiModule from '../ui.js';
@@ -24,11 +24,157 @@ function _safeHttpHref(raw) {
// ── Lazy-registered functions from compare.js (avoids circular deps) ──
let _rerollPane = null;
let _autoPreviewHtml = null;
let _setSendBtn = null;
/** Register external functions that live in compare.js. */
function registerStreamActions({ rerollPane, autoPreviewHtml }) {
function registerStreamActions({ rerollPane, autoPreviewHtml, setSendBtn }) {
_rerollPane = rerollPane;
_autoPreviewHtml = autoPreviewHtml;
_setSendBtn = setSendBtn;
}
function _paneSessionIsCurrent(paneIdx, sessionId) {
return Boolean(
state.isActive
&& state._paneSessionIds[paneIdx] === sessionId
&& document.getElementById('cmp-history-' + paneIdx)
);
}
function _setCompareBusy(active) {
state._streaming = Boolean(active);
if (_setSendBtn) _setSendBtn(active ? 'stop' : 'send');
document.querySelectorAll('#compare-shuffle-btn, #compare-check-btn, #compare-add-btn').forEach((button) => {
button.disabled = Boolean(active);
button.style.opacity = active ? '0.25' : '0.7';
button.style.pointerEvents = active ? 'none' : '';
});
}
function _syncCompareBusyFromPanes() {
_setCompareBusy((state._abortControllers || []).some(Boolean));
}
function _appendPaneMessage(hist, role, text) {
const message = document.createElement('div');
message.className = 'msg ' + (role === 'user' ? 'msg-user' : 'msg-ai');
const roleEl = document.createElement('div');
roleEl.className = 'role';
roleEl.textContent = role === 'user' ? 'You' : 'AI';
const body = document.createElement('div');
body.className = 'body';
body.textContent = text || '';
message.appendChild(roleEl);
message.appendChild(body);
hist.appendChild(message);
return message;
}
function _createPaneContinuationMessage(hist) {
const message = _appendPaneMessage(hist, 'assistant', '');
const body = message.querySelector('.body');
if (spinnerModule) {
const spinner = spinnerModule.create('Continuing...', 'right');
body.appendChild(spinner.createElement());
spinner.start();
message._spinner = spinner;
}
return message;
}
function _restorePaneAskUserCard(paneIdx, sessionId, submission, originController) {
const hist = document.getElementById('cmp-history-' + paneIdx);
const restored = _renderPaneAskUserCard(
paneIdx,
sessionId,
submission.payload || {},
hist,
null,
originController,
);
if (uiModule) {
uiModule.showError(
restored
? 'This pane is still streaming — choose again once it settles.'
: 'Compare pane is still streaming; the choice was not sent.',
);
}
return restored;
}
function _resumePaneChoiceWhenIdle(paneIdx, sessionId, originController, submission) {
if (!_paneSessionIsCurrent(paneIdx, sessionId)) return false;
const startedAt = Date.now();
const resume = () => {
if (!_paneSessionIsCurrent(paneIdx, sessionId)) return;
const activeController = state._abortControllers[paneIdx];
if (activeController === originController) {
if (Date.now() - startedAt < 10000) {
setTimeout(resume, 25);
return;
}
// The originating stream never released the pane. The card was already
// removed when the choice was accepted, so put it back rather than
// swallowing a decision the user made.
_restorePaneAskUserCard(paneIdx, sessionId, submission, originController);
return;
}
// A reroll/model replacement already owns this pane. Never send the stale
// choice into that replacement stream or session UI.
if (activeController) return;
const hist = document.getElementById('cmp-history-' + paneIdx);
if (!hist) return;
hist.querySelectorAll('.ask-user-card').forEach((card) => card.remove());
const isApproval = submission.kind === 'tool_approval';
const message = isApproval ? '' : String(submission.text || submission.label || '');
if (!isApproval) _appendPaneMessage(hist, 'user', message);
const aiMessage = _createPaneContinuationMessage(hist);
hist.scrollTop = hist.scrollHeight;
const resumeOptions = { skipBadge: true };
if (isApproval) {
resumeOptions.toolApproval = {
approval_id: String(submission.approval_id || ''),
decision: String(submission.decision || '').toLowerCase(),
};
}
_setCompareBusy(true);
streamToPane(paneIdx, sessionId, message, aiMessage, resumeOptions)
.catch((error) => {
console.error('Compare pane continuation failed:', error);
if (uiModule) uiModule.showError('Compare continuation failed: ' + error.message);
})
.finally(_syncCompareBusyFromPanes);
};
setTimeout(resume, 0);
return true;
}
function _renderPaneAskUserCard(paneIdx, sessionId, payload, hist, aiMsgEl, originController) {
if (!hist || !hist.isConnected || !_paneSessionIsCurrent(paneIdx, sessionId)) return null;
if (aiMsgEl && aiMsgEl._spinner) {
if (aiMsgEl._spinner.element) aiMsgEl._spinner.destroy();
aiMsgEl._spinner = null;
}
const card = renderAskUserCard(payload, {
root: hist,
onSubmit: (submission) => _resumePaneChoiceWhenIdle(
paneIdx,
sessionId,
originController,
submission,
),
});
if (card) {
card.dataset.comparePane = String(paneIdx);
card.dataset.compareSession = String(sessionId);
}
return card;
}
/** Format milliseconds as human-readable duration (e.g. "120ms", "1.23s", "4.5s"). */
@@ -164,6 +310,7 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
let metrics = null;
let timedOut = false;
let streamOk = false;
let awaitingChoice = false;
let currentToolBlock = null; // track active agent tool block
// Idle timeout — abort only if no data is received for this many seconds.
// Long generations (SVG, big code) are fine as long as the stream stays
@@ -219,6 +366,10 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
const fd = new FormData();
fd.append('message', message);
fd.append('session', sessionId);
if (opts.toolApproval) {
fd.append('tool_approval_id', opts.toolApproval.approval_id || '');
fd.append('tool_approval_decision', opts.toolApproval.decision || '');
}
// Compare mode determines what tools/features are enabled
const isAgent = state._compareMode === 'agent';
@@ -322,6 +473,36 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
}
}
// ── Pane-local question / approval selector ──
} else if (json.type === 'ask_user') {
awaitingChoice = true;
_renderPaneAskUserCard(
paneIdx,
sessionId,
json.data || {},
hist,
aiMsgEl,
ac,
);
if (hist) hist.scrollTop = hist.scrollHeight;
// Deny ends as a tiny resolution-only stream, so replace the
// continuation spinner with an explicit pane-local result.
} else if (json.type === 'tool_approval_resolved') {
if (aiMsgEl._spinner) {
if (aiMsgEl._spinner.element) aiMsgEl._spinner.destroy();
aiMsgEl._spinner = null;
}
accumulated = json.decision === 'deny' ? 'Denied.' : 'Approval recorded.';
let target = aiMsgEl._textEl;
if (!target) {
target = document.createElement('div');
target.className = 'compare-text-content';
aiBody.appendChild(target);
aiMsgEl._textEl = target;
}
target.textContent = accumulated;
// ── Tool start (bash, web search agent tool) ──
} else if (json.type === 'tool_start') {
// Finalize any accumulated text before the tool block
@@ -640,19 +821,21 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
// TTFT removed from the header per user request — just show total time.
_timerEl.textContent = _formatMs(_totalMs);
}
state._abortControllers[paneIdx] = null;
if (state._abortControllers[paneIdx] === ac) {
state._abortControllers[paneIdx] = null;
}
// Hide stop button, show response action buttons
const _paneElFinal = document.querySelector(`.compare-pane[data-pane="${paneIdx}"]`);
if (_paneElFinal) {
const _stopBtnFinal = _paneElFinal.querySelector('.pane-stop-btn');
if (_stopBtnFinal) _stopBtnFinal.style.display = 'none';
if (accumulated.trim()) {
if (!awaitingChoice && accumulated.trim()) {
_paneElFinal.querySelectorAll('.pane-needs-response').forEach(b => b.style.display = '');
}
}
state._paneMetrics[paneIdx] = metrics;
state._paneElapsed[paneIdx] = _totalMs;
if (!opts.skipBadge) {
if (!opts.skipBadge && !awaitingChoice) {
if (streamOk) {
state._finishOrder++;
if (state._parallel) {
@@ -682,7 +865,7 @@ async function streamToPane(paneIdx, sessionId, message, aiMsgEl, opts) {
}
}
// Auto-grade against expected answer — stamps ✓ or ✗ on the pane header.
if (streamOk && state._expectedAnswer) {
if (streamOk && !awaitingChoice && state._expectedAnswer) {
_stampGradeBadge(paneIdx, accumulated, state._expectedAnswer);
}
// Show copy/reroll buttons now that response exists