feat(chat): broker Codex approvals and complete typed tool interactions

This commit is contained in:
2026-10-20 17:41:35 +01:00
parent f31806cfcb
commit 35329e4022
21 changed files with 879 additions and 84 deletions
+2 -1
View File
@@ -2311,7 +2311,8 @@ export function approvalCard(permission, answer) {
actionable: state === APPROVAL_PENDING,
showRisk:
state === APPROVAL_PENDING || (state === APPROVAL_ANSWERED && decision === DECISION_REJECT),
headline: approvalHeadline(state, decision, str(permission.action)),
headline: decision === DECISION_ALWAYS && permission.always_label === "Allow for session"
? "Allowed for session" : approvalHeadline(state, decision, str(permission.action)),
statusLine: approvalStatusLine(state, note),
};
}
+45
View File
@@ -0,0 +1,45 @@
/** Preserve protocol types; false and zero are valid answers, not missing input. */
export function formFieldVisible(field, answers) {
return field?.hidden !== true && (field?.when ?? []).every((condition) =>
condition.op === 'neq' ? answers[condition.key] !== condition.value : answers[condition.key] === condition.value);
}
export function formFieldValue(field, raw) {
if (raw === '') return undefined;
if (field.type === 'boolean') return raw === 'true';
if (field.type === 'number' || field.type === 'integer') return Number(raw);
return raw;
}
export function formAnswerError(fields, answers) {
for (const field of fields ?? []) {
if (!formFieldVisible(field, answers) || field.type === 'external') continue;
const value = answers[field.key];
const missing = value == null || value === '' || (Array.isArray(value) && !value.length);
const label = field.title || field.key;
if (missing) { if (field.required) return `Answer ${label} before sending.`; continue; }
if (['number', 'integer'].includes(field.type)) {
if (typeof value !== 'number' || !Number.isFinite(value) || (field.type === 'integer' && !Number.isInteger(value))) return `${label} needs a valid ${field.type}.`;
if (typeof field.minimum === 'number' && value < field.minimum) return `${label} must be at least ${field.minimum}.`;
if (typeof field.maximum === 'number' && value > field.maximum) return `${label} must be at most ${field.maximum}.`;
}
if (field.type === 'boolean' && typeof value !== 'boolean') return `${label} needs Yes or No.`;
if (typeof value === 'string') {
if (field.min_length != null && value.length < field.min_length) return `${label} is too short.`;
if (field.max_length != null && value.length > field.max_length) return `${label} is too long.`;
}
if (Array.isArray(value)) {
if (field.min_items != null && value.length < field.min_items) return `Select at least ${field.min_items} choices for ${label}.`;
if (field.max_items != null && value.length > field.max_items) return `Select at most ${field.max_items} choices for ${label}.`;
}
}
return '';
}
export function visibleFormAnswers(fields, answers) {
return Object.fromEntries((fields ?? []).filter(f => formFieldVisible(f,answers) && f.type !== 'external' && answers[f.key] !== undefined).map(f => [f.key, answers[f.key]]));
}
export function safeFormURL(raw) {
try { const url=new URL(raw); return ['http:','https:'].includes(url.protocol) ? url.href : null; } catch { return null; }
}
+2 -2
View File
@@ -426,10 +426,10 @@ export class PipelinesRepository {
* the form field key; the server forwards it to the paused tool call and the
* resolved form arrives on the normal chat_event stream.
*/
async answerChatForm(sessionId, formId, answers) {
async answerChatForm(sessionId, formId, answers, action = "") {
return this.#client.call({
type: Protocol.CHAT_ANSWER,
[ChatKeys.ANSWER]: { session_id: sessionId, form_id: formId, answers },
[ChatKeys.ANSWER]: { session_id: sessionId, form_id: formId, answers, ...(action ? {action} : {}) },
});
}
+63 -22
View File
@@ -4,6 +4,7 @@
// in chat.js and markdown.js; this module owns the DOM and the chat wire wiring.
import { backChevronIcon, h } from "../dom.js";
import { formFieldVisible, formFieldValue, formAnswerError, visibleFormAnswers, safeFormURL } from "../chatForms.js";
import { readChatStars, writeChatStars } from "../chatStars.js";
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../chatModels.js";
import { describeError } from "../format.js";
@@ -745,7 +746,9 @@ function refreshChatTranscript(sessionId) {
const running = thread.running === true && !awaiting;
const bar = document.querySelector(".chat-bar");
const jump = bar?.querySelector(".chat-approval-jump");
if (awaiting && bar && !jump) bar.append(approvalJumpButton());
const jumpLabel=chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question";
if (awaiting && bar && !jump) bar.append(approvalJumpButton(jumpLabel));
else if (awaiting && jump) jump.textContent=jumpLabel;
else if (!awaiting) jump?.remove();
captureChatPosition();
// The background-tasks bar sits outside the transcript but is driven by the
@@ -891,10 +894,10 @@ async function answerPermission(sessionId, requestId, decision) {
* field's own key and mirrors OpenCode's form.reply body; the resolved form
* arrives on the stream and clears the card for every watching client.
*/
async function answerChatQuestion(sessionId, form, answers) {
async function answerChatQuestion(sessionId, form, answers, action = "") {
if (!form?.id) return;
try {
await repo.answerChatForm(sessionId, form.id, answers);
await repo.answerChatForm(sessionId, form.id, answers, action);
const current = state.chatThreads.get(sessionId);
if (current) state.chatThreads.set(sessionId, applyChatForm(current, { ...form, resolved: true }));
renderContent();
@@ -2499,7 +2502,7 @@ function renderChatConversation() {
// The approval jump control appears only while a request is actionable, and
// brings its card (the transcript's last item) into view — the one scroll path,
// so a pending request is reached the same way new content is.
if (awaiting) bar.append(approvalJumpButton());
if (awaiting) bar.append(approvalJumpButton(chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question"));
pane.append(bar);
const modelButton = effective ? renderChatModelButton(effective) : null;
if (modelButton) {
@@ -3050,11 +3053,11 @@ function renderChatTranscript(
}
/** The chat pane's approval jump control (C10), naming the pending request. */
function approvalJumpButton() {
function approvalJumpButton(label = WAITING_FOR_APPROVAL_LABEL) {
return h("button", {
class: "ghost chat-approval-jump",
type: "button",
text: WAITING_FOR_APPROVAL_LABEL,
text: label,
onclick: () => {
// The card is the transcript's last item, so the transcript's own end is the
// card; the one scroll path shared with jump-to-latest.
@@ -3113,7 +3116,8 @@ function renderChatApproval(sessionId, card) {
if (card.actionable) {
const controls = h("div", { class: "chat-approval-controls" });
controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary"));
controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
const frame = (state.chatThreads.get(sessionId)?.permissions ?? []).find((entry) => entry.request_id === card.requestId);
controls.append(approvalControl(frame?.always_label || APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId));
node.append(controls);
}
@@ -3144,18 +3148,41 @@ function renderChatQuestion(sessionId, form) {
if (thread && !thread.formAnswers) thread.formAnswers = {};
const answers = thread ? (thread.formAnswers[form.id] ??= {}) : {};
const parts = [];
const fieldNodes = [];
for (const field of form.fields ?? []) {
if (answers[field.key] === undefined && field.default !== undefined) answers[field.key] = field.default;
}
const paintVisibility = () => {
for (const { field, part } of fieldNodes) part.hidden = !formFieldVisible(field, answers);
};
for (const field of form.fields ?? []) {
const key = String(field.key ?? "");
if (key === "") continue;
const options = Array.isArray(field.options) ? field.options : [];
const multi = field.type === "multiselect";
const part = h("div", { class: "chat-question-field" });
fieldNodes.push({field,part});
part.append(
h("div", { class: "chat-question-label", text: field.title || field.description || key }),
);
if (field.description && field.description !== field.title) {
part.append(h("div", { class: "chat-question-desc muted", text: field.description }));
}
if (field.type === "external") {
const url = safeFormURL(field.url);
part.append(url ? h("a", { href: url, target: "_blank", rel: "noopener noreferrer", text: "Open external form" }) : h("div", {role:"alert",text:"This form has an unsupported external URL."}));
parts.push(part);
continue;
}
if (field.type === "boolean") {
const select = h("select", {class:"chat-question-input", "aria-label":field.title || key},
h("option",{value:"",text:"Choose Yes or No"}),h("option",{value:"true",text:"Yes"}),h("option",{value:"false",text:"No"}));
select.value = typeof answers[key] === "boolean" ? String(answers[key]) : "";
select.addEventListener("change",()=>{const value=formFieldValue(field,select.value);if(value===undefined)delete answers[key];else answers[key]=value;paintVisibility();});
part.append(select);
parts.push(part);
continue;
}
if (options.length) {
const rows = h("div", { class: "chat-question-options" });
const buttons = [];
@@ -3194,6 +3221,7 @@ function renderChatQuestion(sessionId, form) {
answers[key] = value;
}
paint();
paintVisibility();
});
buttons.push(button);
rows.append(button);
@@ -3204,21 +3232,33 @@ function renderChatQuestion(sessionId, form) {
if (field.custom === true || options.length === 0) {
const input = h("input", {
class: "chat-question-input",
type: "text",
placeholder: options.length ? "Type another answer" : "Your answer",
type: field.secret ? "password" : ["number","integer"].includes(field.type) ? "number" : field.format === "email" ? "email" : field.format === "uri" ? "url" : field.format === "date" ? "date" : "text",
step: field.type === "number" ? "any" : field.type === "integer" ? "1" : null,
min: typeof field.minimum === "number" ? String(field.minimum) : null,
max: typeof field.maximum === "number" ? String(field.maximum) : null,
minlength: field.min_length ?? null,
maxlength: field.max_length ?? null,
pattern: field.pattern || null,
"aria-label": field.title || key,
placeholder: field.placeholder || (options.length ? "Type another answer" : "Your answer"),
autocomplete: "off",
value: typeof answers[key] === "string" ? answers[key] : "",
value: ["string","number"].includes(typeof answers[key]) ? String(answers[key]) : "",
});
input.addEventListener("input", () => {
const value = input.value.trim();
if (value === "") delete answers[key];
else answers[key] = value;
const value = formFieldValue(field,input.value);
if (value === undefined) delete answers[key];
else if (multi) {
const known=new Set(options.map(option=>String(option.value ?? option.label ?? "")));
answers[key]=[...(Array.isArray(answers[key]) ? answers[key].filter(v=>known.has(v)) : []),...String(value).split(",").map(v=>v.trim()).filter(Boolean)];
} else answers[key] = value;
paintVisibility();
});
part.append(input);
}
parts.push(part);
}
node.append(...parts);
paintVisibility();
const error = h("div", { class: "chat-question-error", role: "alert", hidden: true });
node.append(error);
@@ -3226,27 +3266,28 @@ function renderChatQuestion(sessionId, form) {
const submit = h("button", {
class: "primary chat-question-submit",
type: "button",
text: "Send answer",
text: (form.fields ?? []).every(field=>field.type === "external") ? "Confirm completion" : "Send answer",
});
let sent = false;
submit.addEventListener("click", () => {
if (sent) return;
const missing = (form.fields ?? []).some((field) => {
if (!field.required) return false;
const value = answers[field.key];
return Array.isArray(value) ? value.length === 0 : !value;
});
if (missing) {
const invalidInput=[...node.querySelectorAll('input')].find(input=>!input.closest('.chat-question-field').hidden && !input.checkValidity());
const reason=formAnswerError(form.fields,answers);
if (reason || invalidInput) {
error.hidden = false;
error.textContent = "Answer the required questions before sending.";
error.textContent = reason || invalidInput.validationMessage;
return;
}
sent = true;
submit.disabled = true;
submit.textContent = "Sending…";
answerChatQuestion(sessionId, form, answers);
answerChatQuestion(sessionId, form, visibleFormAnswers(form.fields,answers), form.actions?.includes("accept") ? "accept" : "");
});
controls.append(submit);
for (const action of ["decline","cancel"]) {
if (!form.actions?.includes(action)) continue;
controls.append(h("button",{class:"ghost",type:"button",text:action === "cancel" ? "Cancel question" : "Decline",onclick:()=>answerChatQuestion(sessionId,form,{},action)}));
}
node.append(controls);
return node;
}