Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/codex-question-typed-recheck.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Fixed
- Codex question cards check that the question is still open before pasting into its notes
editor. They no longer press Enter if a regular or queued question closes or the visible
answer changes before submission.
75 changes: 71 additions & 4 deletions server/codex-question.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, expect, test } from "bun:test";
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
import { createServer, type Socket } from "node:net";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -29,9 +29,10 @@ function root(): string {
}

/** herdr with one Codex pane showing `SCREEN`: the keys sent to it are kept. */
async function herdr(): Promise<{ sent: string[] }> {
async function herdr(onInput: (input: string, screen: string) => string = (_, screen) => screen, initial = SCREEN): Promise<{ sent: string[] }> {
const path = join(root(), "herdr.sock");
const pane = { sent: [] as string[] };
let screen = initial;
const sockets = new Set<Socket>();
const server = createServer((socket) => {
sockets.add(socket);
Expand All @@ -44,12 +45,15 @@ async function herdr(): Promise<{ sent: string[] }> {
const request = JSON.parse(input.split("\n")[0]!) as { id: string; method: string; params: { keys?: string[]; text?: string } };
const answer = (result: unknown) => socket.end(`${JSON.stringify({ id: request.id, result })}\n`);
if (request.method === "session.snapshot") return answer({ snapshot: { panes: [{ pane_id: "p_1", agent: "codex", agent_status: "blocked" }], layouts: [] } });
if (request.method === "pane.read") return answer({ read: { text: SCREEN } });
if (request.method === "pane.read") return answer({ read: { text: screen } });
if (request.method === "pane.process_info") return answer({ process_info: { foreground_processes: [] } });
if (request.method === "pane.get") return answer({ pane: { pane_id: "p_1" } });
if (request.method === "agent.get") return answer({ agent: {} });
if (request.method === "pane.send_keys" || request.method === "pane.send_text") {
pane.sent.push(...(request.params.keys ?? [`text:${request.params.text}`]));
for (const key of request.params.keys ?? [`text:${request.params.text}`]) {
pane.sent.push(key);
screen = onInput(key, screen);
}
return answer({});
}
socket.end(`${JSON.stringify({ id: request.id, error: { code: "not_found", message: request.method } })}\n`);
Expand Down Expand Up @@ -184,3 +188,66 @@ test("leaves a note and several picks to the TUI", () => {
expect(servedAnswers(ask, { pane_id: "p", prompt_id: "x", option_index: 1 })).toBeNull();
expect(servedAnswers(ask, { pane_id: "p", prompt_id: "x", option_indices: [0] })).toBeNull();
});

const COMPOSER = "› An unsent composer draft\n";

test.each([
["the notes editor stays open", (screen: string) => screen, 200],
["the notes footer wraps to two rows", (screen: string) => screen.replace(" | enter to submit answer", "\n enter to submit answer"), 200],
["the visible note changes before Enter", (screen: string) => screen.replace("› green", "› blue"), 409],
["the question closes during the paste", () => COMPOSER, 409],
["another question takes its place", (screen: string) => screen.replace(" Which color do you choose?", " Which color should we avoid?"), 409],
] as const)("rechecks before sending Enter when %s", async (_, redraw, status) => {
const pane = await herdr((key, screen) => {
if (key === "down") return screen.replace(/^ › (\d\..*\n) (?=\d\.)/mu, " $1 › ");
if (key === "tab") return screen.replace(
" tab to add notes | enter to submit answer | esc to interrupt",
" › Add notes\n\n tab or esc to clear notes | enter to submit answer",
);
if (key === "text:green") return redraw(screen.replace(" › Add notes", " › green"));
return screen;
});
const prompt = await card();
const result = await answer(prompt.id, { custom_text: "green" });
const edit = ["down", "down", "tab", "text:green"];
expect([result, pane.sent]).toEqual([status, status === 200 ? [...edit, "enter"] : edit]);
});

test("does not paste into Codex's composer when the question closes after Tab", async () => {
const pane = await herdr((key, screen) => {
if (key === "down") return screen.replace(/^ › (\d\..*\n) (?=\d\.)/mu, " $1 › ");
return key === "tab" ? COMPOSER : screen;
});
const result = await answer((await card()).id, { custom_text: "green" });
expect([result, pane.sent]).toEqual([409, ["down", "down", "tab"]]);
});

test("answers a queued question in the old layout without the queue header", async () => {
const queue = (row: string) => ` Which color?\n 1. red\n 2. blue\n${row}\n enter submit ctrl+] skip alt+↓ main prompt\n`;
const pane = await herdr((key, screen) => key === "text:green" ? queue(" › 3. green") : key === "enter" ? COMPOSER : screen, queue(" › 3. Other"));
const result = await answer((await card()).id, { custom_text: "green" });
expect([result, pane.sent]).toEqual([200, ["text:green", "enter"]]);
});

describe.each([
["free-form", " Type your answer", " green"],
["choice with Other", " 1. red\n 2. blue\n › 3. Other", " 1. red\n 2. blue\n › 3. green"],
] as const)("%s queued question", (_, initial, typed) => {
test.each([
["still open", (row: string) => row, 200],
["closed during paste", () => null, 409],
["answer changed", (row: string) => row.replace("green", "blue"), 409],
["leading space was added", (row: string) => row.replace("green", " green"), 409],
] as const)("checks the input before Enter when %s", async (_, redraw, status) => {
const queue = (row: string) => `• Queued follow-up inputs\n Which color?\n${row}\n enter submit ctrl+] skip alt+↓ main prompt\n`;
const pane = await herdr((key, screen) => {
if (key === "text:green") {
const shown = redraw(typed);
return shown === null ? COMPOSER : queue(shown);
}
return key === "enter" ? COMPOSER : screen;
}, queue(initial));
const result = await answer((await card()).id, { custom_text: "green" });
expect([result, pane.sent]).toEqual([status, ["text:green", ...(status === 200 ? ["enter"] : [])]]);
});
});
62 changes: 57 additions & 5 deletions server/dialogs/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ function parseCodexContinueMenu(screen: string): ParsedPrompt | null {
function parseCodexQuestion(screen: string): ParsedPrompt | null {
const lines = screen.replace(ANSI_RE, "").split(/\r?\n/);
const hintIndex = findLastIndex(lines, (_, index) => CODEX_ASK_HINT_RE.test(wrapped(lines, index)));
return readCodexQuestion(lines, hintIndex, CODEX_NAVIGATE_RE.test(wrapped(lines, hintIndex)));
}

function readCodexQuestion(lines: string[], hintIndex: number, canNavigate: boolean): ParsedPrompt | null {
if (hintIndex < 0) return null;
const rows = menuRows(lines, Math.max(0, hintIndex - 48), hintIndex);
if (!sequentialRows(rows) || rows.filter((row) => row.selected).length !== 1) return null;
Expand All @@ -74,7 +78,7 @@ function parseCodexQuestion(screen: string): ParsedPrompt | null {
// several questions, and the hint says ←/→ move between them without answering: the card's Back and Next
const at = progress ? Number(progress[1]) - 1 : 0;
const total = progress ? Number(progress[2]) : 1;
const navigates = total > 1 && at < total && CODEX_NAVIGATE_RE.test(wrapped(lines, hintIndex));
const navigates = canNavigate && total > 1 && at < total;
return finishPrompt("codex", {
kind: "question", title, question, body: null, options,
multi_select: false, custom_option_index: options.length,
Expand All @@ -87,16 +91,49 @@ function parseCodexQuestion(screen: string): ParsedPrompt | null {
}, { can_step_back: undefined, can_step_next: undefined });
}

// Codex replaces the options footer when Tab opens notes. The menu above the notes
// composer still identifies the question, but the composer itself isn't an option row.
export function parseCodexNotes(screen: string, answer?: string): ParsedPrompt | null {
const lines = screen.replace(ANSI_RE, "").split(/\r?\n/);
const end = findLastIndex(lines, (line) => line.trim() !== "");
const last = cleanLine(lines[end] ?? "");
const before = cleanLine(lines[end - 1] ?? "");
const submit = /^enter to submit (?:answer|all)$/i;
const footer = /^tab or esc to clear notes\s*\|\s*enter to submit (?:answer|all)$/i.test(last) ? end
: before.toLowerCase() === "tab or esc to clear notes" && submit.test(last) ? end - 1 : -1;
if (footer < 0) return null;
const notesRow = findLastIndex(lines.slice(0, footer), (line) => /^\s*›(?: |$)/u.test(line));
if (notesRow < 0) return null;
const parsed = readCodexQuestion(lines, notesRow, false);
if (parsed === null || parsed.selectedIndex !== parsed.customMenuIndex) return null;
if (answer !== undefined) {
const prefix = /^([ \t]*)› /u.exec(lines[notesRow] ?? "");
if (!prefix) return null;
const indent = " ".repeat(prefix[0].length);
const rest = lines.slice(notesRow + 1, footer);
while (rest.length > 0 && rest.at(-1)?.trimEnd() === "") rest.pop();
if (!rest.every((line) => line.trimEnd() === "" || line.startsWith(indent))) return null;
// Don't guess whether a line break is a soft wrap or was typed.
const visible = [lines[notesRow]?.slice(prefix[0].length) ?? "", ...rest.map((line) => line.slice(indent.length))]
.map((line) => line.trimEnd()).join("\n");
if (visible === "Add notes" || visible !== answer) return null;
}
return parsed;
}

/**
* A question from Codex's queue, open: under the queue header, an optional "1 of 2", the
* question (wrapped over as many lines as the pane needs), then its options and a last
* row that takes a typed answer ("Other", or what was typed there). A free-form question
* has no options, only that answer line ("Type your answer").
*/
function parseCodexAsyncQuestion(screen: string): ParsedPrompt | null {
function parseCodexAsyncQuestion(screen: string, answer?: string): ParsedPrompt | null {
const lines = screen.replace(ANSI_RE, "").split(/\r?\n/);
const hintIndex = findLastIndex(lines, (_, index) => CODEX_ASYNC_ASK_HINT_RE.test(wrapped(lines, index)));
const hintIndex = findLastIndex(lines, (line, index) => CODEX_ASYNC_ASK_HINT_RE.test(wrapped(lines, index))
&& (answer === undefined || /^(?:enter|return)\s+submit\b/i.test(cleanLine(line))));
if (hintIndex < 0) return null;
if (answer !== undefined && lines.slice(hintIndex + 1).map(cleanLine).some((line) => line !== ""
&& !/^(?:\S+ (?:skip|main prompt|prev question|next question|queued messages)|option \d+\/\d+)(?:\s|$)/i.test(line))) return null;
const header = findLastIndex(lines.slice(Math.max(0, hintIndex - 48), hintIndex), (line) => CODEX_QUEUE_HEADER_RE.test(cleanLine(line)));
const top = header < 0 ? Math.max(0, hintIndex - 48) : Math.max(0, hintIndex - 48) + header + 1;
const rows = menuRows(lines, top, hintIndex);
Expand All @@ -116,14 +153,25 @@ function parseCodexAsyncQuestion(screen: string): ParsedPrompt | null {
if (header < 0) return null;
const answerLine = findLastIndex(lines.slice(0, hintIndex), (line) => Boolean(cleanLine(line)) && !isDivider(line));
if (answerLine < top) return null;
if (answer !== undefined) {
// The free-form input and the question start in the same column. Remove
// that inset, not spaces a person may have typed into the field.
const firstQuestionRow = lines.slice(top, answerLine).find((line) => line.trim() !== "");
const inset = firstQuestionRow?.match(/^[ \t]*/u)?.[0];
if (inset === undefined || answer === "Type your answer" || lines[answerLine]?.trimEnd() !== inset + answer) return null;
}
question = normalizeText(questionLines(answerLine).join(" ")) || null;
options = [];
menuLabels = [];
selectedIndex = 0;
} else {
if (!sequentialRows(rows) || rows.length < 2 || rows.filter((row) => row.selected).length !== 1) return null;
// an old layout without the header must still end in its "Other" row
if (header < 0 && !/^Other\b/i.test(rows.at(-1)!.label)) return null;
const lastRow = rows.at(-1)!;
if (answer !== undefined && (!lastRow.selected || answer === "Other" || answer === "Other (write an answer)"
|| lines[lastRow.lineIndex]?.trimEnd().replace(/^\s*› *\d+\. /u, "") !== answer
|| text(lastRow.lineIndex + 1, hintIndex).length !== 0)) return null;
// an old layout without the header must still end in its "Other" row, until an answer is typed there
if (header < 0 && answer === undefined && !/^Other\b/i.test(rows.at(-1)!.label)) return null;
// a wrapped option continues on the lines under it: these rows carry no descriptions
const labels = rows.map((row, index) => normalizeText([row.label, ...text(row.lineIndex + 1, rows[index + 1]?.lineIndex ?? hintIndex)].join(" ")));
question = header < 0 ? nearestQuestion(lines, rows[0]!.lineIndex) : normalizeText(questionLines(rows[0]!.lineIndex).join(" ")) || null;
Expand All @@ -143,6 +191,10 @@ function parseCodexAsyncQuestion(screen: string): ParsedPrompt | null {
});
}

export function codexAsyncAnswerMatches(screen: string, expected: ParsedPrompt, answer: string): boolean {
return parseCodexAsyncQuestion(screen, answer)?.id === expected.id;
}

/** The dialogs of an approval Codex asks a client on its app server (server/approvals/codex.ts holds them), by kind. */
const CODEX_REQUEST_DIALOGS: readonly [RegExp, string][] = [
[/^Would you like to run the following command\b/, "command"],
Expand Down
15 changes: 12 additions & 3 deletions server/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { executeInteractionPlan } from "./dialogs/interaction-plan.ts";
import { liveScreen, parsePrompt, promptTailIsActive } from "./dialogs/live.ts";
import { LETTA_SEARCH_MAX, lettaPick, lettaSearchShown } from "./dialogs/letta.ts";
import { agyCustomEditorMatches, agySameQuestion, parseAgyQuestion } from "./dialogs/agy.ts";
import { codexAsyncAnswerMatches, parseCodexNotes } from "./dialogs/codex.ts";
import { dshFreeTextRow, dshTypedText } from "./dialogs/dsh.ts";
import { sameText } from "./dialogs/omo.ts";
import { OMP_REVIEW_HINT_RE, OMP_TABS_HINT_RE, ompCustomEditorMatches } from "./dialogs/omp.ts";
Expand Down Expand Up @@ -2218,7 +2219,8 @@ export async function handlePromptRequest(request: Request, url: URL, options: P
const interaction = body.custom_text === undefined ? reader?.interaction?.(parsed) : undefined;
const checkBeforeText = responder === "fallback-gjc-menu" || responder === "pi-ask-question"
|| responder === "pi-questionnaire-question" || responder === "agy-question";
const editorAnswer = body.custom_text !== undefined && (checkBeforeText || responder === "dsh-question"
const codexTyped = responder === "codex-question" || responder === "codex-async-question";
const editorAnswer = body.custom_text !== undefined && (checkBeforeText || responder === "dsh-question" || codexTyped
|| responder === "claude-question" || responder === "omp-question" || responder === "omo-question" || responder === "omo-review" || responder === "hermes-question"
|| responder === "hermes-input" || responder === "opencode-v1-question")
? { prompt: parsed, text: body.custom_text.trim() } : undefined;
Expand Down Expand Up @@ -2335,26 +2337,33 @@ export async function handlePromptRequest(request: Request, url: URL, options: P
const lettaTyping = committed && responder === "letta-model" && body.custom_text !== undefined;
const claudeDown = responder === "claude-question" && parsed.multi_select && step.keys?.[0] === KEY.down;
const gjcEditorPaste = committed && !customTyped && responder === "fallback-gjc-menu" && step.text !== undefined && parsed.gjcCall !== undefined;
const codexNotesPaste = committed && responder === "codex-question" && step.text !== undefined;
const typedEditor = customTyped && step.keys?.length === 1 && (step.keys[0] === KEY.enter || claudeDown) ? editorAnswer : undefined;
if (!committed || togglesInPlace() || lettaTyping || typedEditor || gjcEditorPaste) {
if (!committed || togglesInPlace() || lettaTyping || typedEditor || gjcEditorPaste || codexNotesPaste) {
const onCursor = !move && (step.keys?.every((key) => key === KEY.enter || key === KEY.space) ?? false);
const { written } = await verifyThenSend(look, guardUntil, Date.now() + SETTLE_MS,
(shown, screen, settled) => {
if (responder === "codex-question" && (codexNotesPaste || typedEditor)) {
if (!asks() || request.signal.aborted) return false;
const notes = parseCodexNotes(screen, typedEditor?.text);
return notes !== null && withServedAsk(body.pane_id, notes).id === parsed.id;
}
if (gjcEditorPaste) {
if (!asks() || request.signal.aborted) return false;
return inlineEditorMatches(shown, screen, "");
}
if (typedEditor) {
if (!asks() || request.signal.aborted) return false;
if (checkBeforeText) return inlineEditorMatches(shown, screen, typedEditor.text);
if (responder === "codex-async-question") return codexAsyncAnswerMatches(screen, parsed, typedEditor.text);
if (responder === "dsh-question") return dshFreeTextRow(screen, parsed, dshTypedText(typedEditor.text)) === "typed";
if (responder === "omp-question") return ompCustomEditorMatches(screen, typedEditor);
if (responder === "opencode-v1-question") return openCodeV1CustomEditorMatches(screen, typedEditor);
return shown?.agent === parsed.agent && shown.customEditorMatches?.(typedEditor, claudeDown ? "editor" : "submit") === true;
}
return lettaTyping ? lettaSearchShown(shown, parsed, lettaSearch) : sameQuestion(shown, screen, onCursor, settled);
}, () => ({ written: write() }),
typedEditor || gjcEditorPaste ? "editor" : interaction !== undefined || responder === "pi-question" || responder === "pi-confirm" || responder.startsWith("fallback"));
typedEditor || gjcEditorPaste || codexNotesPaste ? "editor" : interaction !== undefined || responder === "pi-question" || responder === "pi-confirm" || responder.startsWith("fallback"));
await written;
} else {
const guarding = guardKey(body.pane_id, agent, look);
Expand Down