fix(codex): reconcile cold connections without resuming queued goals

This commit is contained in:
2026-10-20 18:33:20 +01:00
parent b3bcfa3826
commit d564765ca5
14 changed files with 355 additions and 34 deletions
+8
View File
@@ -273,6 +273,14 @@ protocol shapes are tested. Read-only live Codex validation passed history,
command listing and model listing without starting/resuming a turn or changing
settings. No real Codex command or permission grant was used for testing.
Cold-connection Codex follow-up: live verification reproduced an accepted turn
with no native completion events. Read-only latest-turn reconciliation now asks
the browser to resync authoritative history and delivers completion, guarded by
native turn identity. A real isolated tool-free turn passed after replacing the
owning connection. Browser regressions for both harness identities verify resync
without composer replacement or lost draft; stale terminal events cannot clear
the next turn. No automatic thread resume or queued-goal activation is used.
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
+6 -1
View File
@@ -1208,6 +1208,7 @@ export const EVENT_USAGE = "usage";
export const EVENT_USER = "user";
export const EVENT_SHELL = "shell";
export const EVENT_FORM = "form";
export const EVENT_RESYNC = "resync";
/** ChatStep.Status values. `ended` is the one status that settles a turn. */
export const STEP_ENDED = "ended";
@@ -1603,6 +1604,8 @@ export function applyChatForm(thread, form) {
* targets is created on first sight, so a live turn never gains a second bubble.
*/
export function applyChatEvent(thread, frame, now = Date.now()) {
if (frame?.kind === EVENT_RESYNC) return thread ?? newChatThread(str(frame?.session_id));
if (frame?.kind === EVENT_STEP && frame.step?.status === STEP_ENDED && frame.step?.turn_id && frame.step.turn_id !== thread?.nativeTurnId) return thread ?? newChatThread(str(frame?.session_id));
const current = thread?.queued
? { ...thread, queued: false }
: (thread ?? newChatThread(str(frame?.session_id)));
@@ -1616,7 +1619,9 @@ export function applyChatEvent(thread, frame, now = Date.now()) {
return applyTool(current, frame, now);
case EVENT_STEP:
if (frame?.step?.intermediate) return current;
return setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now);
if (frame?.step?.turn_id && frame.step.status === STEP_ENDED && frame.step.turn_id !== current.nativeTurnId) return current;
return { ...setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now),
nativeTurnId: frame.step?.status === STEP_ENDED ? "" : frame.step?.turn_id || current.nativeTurnId || "" };
// A shell frame only folds its shell into the retained set: it NEVER marks
// the thread running, because a background process is not the turn — a shell
// that outlives the turn keeps showing after the turn's own indicator is gone.
+24 -8
View File
@@ -347,13 +347,16 @@ let pendingComposerFocus = null;
* frame would steal focus and the operator could not type a queued message.
*/
function captureChatFocus() {
const input = document.getElementById("chatInput");
if (!input || document.activeElement !== input) {
const input = document.activeElement;
const question = input?.matches?.(".chat-question-input") ? input.closest(".chat-question") : null;
if (!input || (input !== document.getElementById("chatInput") && !question)) {
pendingComposerFocus = null;
return;
}
pendingComposerFocus = {
sessionId: state.chatActiveId ?? "",
formId: question?.dataset.formId ?? "",
fieldKey: input.dataset.fieldKey ?? "",
start: input.selectionStart,
end: input.selectionEnd,
direction: input.selectionDirection,
@@ -366,7 +369,9 @@ function restoreChatFocus() {
pendingComposerFocus = null;
if (!pending) return;
if (state.chatActiveId !== pending.sessionId) return;
const input = document.getElementById("chatInput");
const input = pending.formId
? document.querySelector(`[data-form-id="${CSS.escape(pending.formId)}"] [data-field-key="${CSS.escape(pending.fieldKey)}"]`)
: document.getElementById("chatInput");
if (!input) return;
input.focus({ preventScroll: true });
try {
@@ -778,6 +783,11 @@ function refreshChatTranscript(sessionId) {
function onChatEvent(frame) {
const sessionId = String(frame?.session_id ?? "").trim();
if (!sessionId || !state.chatThreads.has(sessionId)) return;
if (frame.kind === "resync") {
markBackgroundChatUnseen(sessionId);
scheduleHistorySync(sessionId, "", {force:true});
return;
}
markBackgroundChatUnseen(sessionId);
const thread = state.chatThreads.get(sessionId);
const messageId = String(frame?.message_id ?? "");
@@ -807,10 +817,10 @@ function onChatEvent(frame) {
/** At most one history read per unseen turn, and only for the open conversation. */
const historySyncTimers = new Map();
const historySyncedFor = new Map();
function scheduleHistorySync(sessionId, messageId) {
if (!messageId || state.view !== "chat" || sessionId !== state.chatActiveId) return;
if (historySyncedFor.get(sessionId) === messageId) return;
historySyncedFor.set(sessionId, messageId);
function scheduleHistorySync(sessionId, messageId, {force=false} = {}) {
if ((!messageId && !force) || state.view !== "chat" || sessionId !== state.chatActiveId) return;
if (!force && historySyncedFor.get(sessionId) === messageId) return;
if (!force) historySyncedFor.set(sessionId, messageId);
if (historySyncTimers.has(sessionId)) return;
const timer = setTimeout(() => {
historySyncTimers.delete(sessionId);
@@ -1020,10 +1030,14 @@ async function resyncOpenChat() {
}
/** Load (or reload) a session's newest history page and merge it in. */
const historyReadGenerations = new Map();
async function loadChatHistory(id) {
const generation=(historyReadGenerations.get(id) ?? 0)+1;
historyReadGenerations.set(id,generation);
const previous = state.chatThreads.get(id) ?? newChatThread(id);
try {
const page = await repo.chatHistory(id);
if (historyReadGenerations.get(id)!==generation) return;
// The merged page replaces only the history fields; spreading it over the
// held thread keeps the composer's draft, attachments and flags intact (a
// draft typed while the page was loading is not lost).
@@ -1032,6 +1046,7 @@ async function loadChatHistory(id) {
// the just-delivered interaction (and any draft typed during the read).
setThread(id, mergeHistoryPage(state.chatThreads.get(id) ?? previous, page, { older: false }));
} catch (error) {
if (historyReadGenerations.get(id)!==generation) return;
setThread(id, { loading: false, loaded: true, error: describeError(error) });
}
// A streaming turn triggers this resync after its first unseen message. Keep
@@ -3175,7 +3190,7 @@ function renderChatQuestion(sessionId, form) {
continue;
}
if (field.type === "boolean") {
const select = h("select", {class:"chat-question-input", "aria-label":field.title || key},
const select = h("select", {class:"chat-question-input", "data-field-key":key, "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();});
@@ -3232,6 +3247,7 @@ function renderChatQuestion(sessionId, form) {
if (field.custom === true || options.length === 0) {
const input = h("input", {
class: "chat-question-input",
"data-field-key": key,
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,
+6
View File
@@ -152,6 +152,12 @@ try {
await page.click('.chat-bg-task');
await eventually(()=>page.evaluate("document.querySelector('.chat-bg-task-output')?.textContent==='Controlled background output'"));
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'harness-background-output.png'));
await page.fill('#chatInput','Keep this draft through readback');
await page.evaluate("window.__resyncComposer=document.querySelector('#chatInput')");
assert.equal((await fetch(`http://${target}/fixture-resync`,{method:'POST'})).status,204);
await emit({kind:'resync'});
await eventually(()=>page.evaluate("document.querySelector('#chatTranscript').textContent.includes('Authoritative resync evidence')"));
assert.equal(await page.evaluate("document.querySelector('#chatInput')===window.__resyncComposer && document.querySelector('#chatInput').value==='Keep this draft through readback'"),true);
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 {
+12 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard } from '../src/chat.js';
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard, applyChatEvent } from '../src/chat.js';
test('parallel approvals stay independently actionable and resolve by identity',()=>{
let thread={};
@@ -12,6 +12,17 @@ test('parallel approvals stay independently actionable and resolve by identity',
assert.deepEqual(chatApprovalCards(thread),[]);
});
test('native turn identity rejects late completion and resync preserves queued intent',()=>{
let thread=applyChatEvent({messages:[],queued:true},{kind:'step',step:{status:'started',turn_id:'new'}},1);
thread={...thread,queued:true};
assert.equal(applyChatEvent(thread,{kind:'resync'}),thread);
thread=applyChatEvent(thread,{kind:'step',step:{status:'ended',turn_id:'old'}},2);
assert.equal(thread.running,true);
assert.equal(thread.queued,true);
thread=applyChatEvent(thread,{kind:'step',step:{status:'ended',turn_id:'new'}},3);
assert.equal(thread.running,false);
});
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');