feat(chat): broker Codex approvals and complete typed tool interactions
This commit is contained in:
@@ -247,6 +247,18 @@ to it, but the server never lists it and a reload drops it.
|
||||
|
||||
## Web interaction recovery (2026-10-20)
|
||||
|
||||
Typed-tool follow-up: number/integer/boolean/default/conditional/secret and
|
||||
external-link fields use native controls, preserve JSON types and validate before
|
||||
sending. `typed-question-controls.png` and the scratch browser regression cover
|
||||
false/zero, masked input and hidden-answer omission. OpenCode questions can be
|
||||
cancelled. Codex approvals now reach the normal cards (with explicit session
|
||||
scope); standard MCP elicitation supports Accept/Decline/Cancel. Adapter tests
|
||||
verify exact callback identity, session ownership, transport writes and requested
|
||||
permission bounds. This is not a live grant/command-execution claim: no real
|
||||
permission request was approved for testing. Extended OpenAI elicitation remains
|
||||
unadvertised/unsupported; callback recovery across App Server socket loss is not
|
||||
available. See `docs/chat-backends.md`.
|
||||
|
||||
- C10 approvals are read from the **session-owned** OpenCode endpoint, including
|
||||
turns started in another client/directory. Merely subscribing starts polling;
|
||||
no web prompt is needed. Room recreation no longer suppresses an already-seen
|
||||
|
||||
@@ -1164,6 +1164,7 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
.chat-backend-logo svg { width: 18px; height: 18px; display: block; }
|
||||
.chat-question-field[hidden] { display: none; }
|
||||
.chat-backend-logo[data-activity="streaming"] { color: var(--accent); }
|
||||
.chat-backend-logo[data-activity="new"] { color: var(--ok); }
|
||||
.chat-row .row-head { padding-right: 86px; }
|
||||
|
||||
+2
-1
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
@@ -127,12 +127,25 @@ try {
|
||||
await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===0"));
|
||||
for(const id of ['form_first','form_second']) {
|
||||
await page.fill(`[data-form-id=${id}] .chat-question-input`,'Browser answer');
|
||||
if(id==='form_second') {
|
||||
await page.evaluate("(()=>{const s=document.querySelector('[data-form-id=form_second] select');s.value='true';s.dispatchEvent(new Event('change',{bubbles:true}));})()");
|
||||
await page.fill('[data-form-id=form_second] input[aria-label="Only when enabled"]','must not leak');
|
||||
await page.evaluate("(()=>{const s=document.querySelector('[data-form-id=form_second] select');s.value='false';s.dispatchEvent(new Event('change',{bubbles:true}));})()");
|
||||
await page.fill('[data-form-id=form_second] input[type=number]','0');
|
||||
assert.equal(await page.evaluate("document.querySelector('[data-form-id=form_second] input[aria-label=\"Only when enabled\"]').closest('.chat-question-field').getBoundingClientRect().height"),0);
|
||||
assert.equal(await page.evaluate("document.querySelector('[data-form-id=form_second] input[aria-label=Secret]').type"),'password');
|
||||
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'typed-question-controls.png'));
|
||||
}
|
||||
await emit({message_id:'msg_answer',kind:'text',part:{id:'draft-check',type:'text',text:'unrelated frame'}});
|
||||
await eventually(() => page.evaluate(`document.querySelector('[data-form-id=${id}] .chat-question-input')?.value==='Browser answer'`));
|
||||
await page.evaluate(`document.querySelector('[data-form-id=${id}] .chat-question-submit').click()`);
|
||||
await eventually(() => page.evaluate(`!document.querySelector('[data-form-id=${id}]')`));
|
||||
}
|
||||
await eventually(() => page.evaluate("!document.querySelector('.chat-approval-jump')"));
|
||||
assert.equal((await fetch(`http://${target}/fixture-cancel`,{method:'POST'})).status,204);
|
||||
await page.waitForSelector('[data-form-id=form_cancel]');
|
||||
await page.evaluate("[...document.querySelectorAll('[data-form-id=form_cancel] button')].find(button=>button.textContent==='Cancel question').click()");
|
||||
await eventually(()=>page.evaluate("!document.querySelector('[data-form-id=form_cancel]')"));
|
||||
assert.deepEqual(await page.evaluate("window.__errors"), []);
|
||||
console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration, send-to-bottom and all recovered approvals/questions passed.");
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {formFieldValue,formAnswerError,visibleFormAnswers,safeFormURL} from '../src/chatForms.js';
|
||||
|
||||
test('typed questions preserve false and zero, and reject invalid numeric answers',()=>{
|
||||
const fields=[{key:'yes',type:'boolean',required:true},{key:'count',type:'integer',required:true,minimum:0,maximum:5}];
|
||||
const answers={yes:formFieldValue(fields[0],'false'),count:formFieldValue(fields[1],'0')};
|
||||
assert.deepEqual(answers,{yes:false,count:0});
|
||||
assert.equal(formAnswerError(fields,answers),'');
|
||||
assert.match(formAnswerError(fields,{...answers,count:1.5}),/integer/);
|
||||
assert.match(formAnswerError(fields,{...answers,count:6}),/at most/);
|
||||
assert.match(formAnswerError(fields,{...answers,count:NaN}),/valid/);
|
||||
});
|
||||
|
||||
test('conditional and hidden fields never send stale answers',()=>{
|
||||
const fields=[{key:'yes',type:'boolean'},{key:'extra',type:'string',required:true,when:[{key:'yes',op:'eq',value:true}]},{key:'hidden',hidden:true}];
|
||||
const answers={yes:false,extra:'stale',hidden:'hidden'};
|
||||
assert.deepEqual(visibleFormAnswers(fields,answers),{yes:false});
|
||||
assert.equal(formAnswerError(fields,answers),'');
|
||||
assert.match(formAnswerError(fields,{yes:true}),/extra/);
|
||||
});
|
||||
|
||||
test('external question links accept only explicit HTTP(S) URLs',()=>{
|
||||
assert.equal(safeFormURL('https://example.test/form'),'https://example.test/form');
|
||||
for(const value of ['javascript:alert(1)','file:///etc/passwd','//example.test','bad'])assert.equal(safeFormURL(value),null);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms } from '../src/chat.js';
|
||||
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard } from '../src/chat.js';
|
||||
|
||||
test('parallel approvals stay independently actionable and resolve by identity',()=>{
|
||||
let thread={};
|
||||
@@ -12,6 +12,11 @@ test('parallel approvals stay independently actionable and resolve by identity',
|
||||
assert.deepEqual(chatApprovalCards(thread),[]);
|
||||
});
|
||||
|
||||
test('Codex session-scoped approval is never described as a permanent grant',()=>{
|
||||
const card=approvalCard({request_id:'a',always_label:'Allow for session',resolved:true,decision:'always'},'');
|
||||
assert.equal(card.headline,'Allowed for session');
|
||||
});
|
||||
|
||||
test('parallel questions survive replies and cancellation of a different question',()=>{
|
||||
let thread={};
|
||||
for(const id of ['a','b']) thread=applyChatForm(thread,{id,session_id:'s',fields:[]});
|
||||
|
||||
Reference in New Issue
Block a user