From afc482838764f563743fcfcb92f1093678220d8f Mon Sep 17 00:00:00 2001 From: tdwd Date: Fri, 18 Sep 2026 12:48:04 +0200 Subject: [PATCH] codex: let the agent ask the user a question item/tool/requestUserInput is codex's analogue of AskUserQuestion. It was answered with -32601, so codex could not ask anything. The shape comes from ToolRequestUserInputParams in the generated schema, not from a probe. Two differences from claude decide the code. codex keys each answer by a question id rather than by position, so the id rides out on the question and back on the reply; claude has only the deny-message channel and ignores that field. And a codex question may offer no options, or be marked secret. The picker chooses between options and cannot take typed input, so those are left out of the answer map, which codex reads as unanswered. Every path to the pane now goes through codexEngine.ask, which owns the two rules that hang a turn when one is missed: the wait runs off the reader goroutine, and one request holds the pane at a time. askUser duplicated both, and a third request kind was free to duplicate them again or forget them. --- README.md | 3 + approvals.go | 5 + codexapproval.go | 73 ++++++++------ codexquestion.go | 118 +++++++++++++++++++++++ codexquestion_test.go | 214 ++++++++++++++++++++++++++++++++++++++++++ keys.go | 16 ++-- question.go | 22 +++++ 7 files changed, 414 insertions(+), 37 deletions(-) create mode 100644 codexquestion.go create mode 100644 codexquestion_test.go diff --git a/README.md b/README.md index 0116dc1..435d777 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,9 @@ The codex backend is newer and narrower than the claude one: - File changes render as real diff cards, in both the unified and side-by-side styles. Other tool calls render as plain cards rather than the typed ones claude gets. +- Either agent can ask you a question, and both use the same picker. A codex + question that offers no options, or asks for a secret, is left unanswered — + the picker chooses between options and cannot take typed input. - `/sysprompt` and `/mcp` are claude-only and are hidden on codex rather than offered and inert. Session replay and `/compact` are claude-only too. - `@path` inserts a path but does not inject the file. Only claude expands an diff --git a/approvals.go b/approvals.go index 2f42de1..05c6314 100644 --- a/approvals.go +++ b/approvals.go @@ -49,6 +49,11 @@ type approvalReq struct { type approvalReply struct { allow bool message string + // answers carries a question's answer as data instead of as denial text, for + // a backend that takes it that way. claude has only the message channel and + // ignores this; codex replies with an answer per question id + // (codexquestion.go). + answers []questionAnswer } const ( diff --git a/codexapproval.go b/codexapproval.go index c83e070..b6f2ee8 100644 --- a/codexapproval.go +++ b/codexapproval.go @@ -22,9 +22,10 @@ import ( // turning a decision back into a JSON-RPC response. // codexApprovalMethods are the server requests that gate an action, and so can -// be answered with a decision. Anything not on this list is answered with a -// JSON-RPC error instead — inventing a reply for a request whose semantics we -// have not established is worse than declining it plainly. +// be answered with a decision. A request that is neither one of these nor a +// question is answered with a JSON-RPC error instead — inventing a reply for a +// request whose semantics we have not established is worse than declining it +// plainly. var codexApprovalMethods = map[string]bool{ "item/commandExecution/requestApproval": true, "item/fileChange/requestApproval": true, @@ -62,47 +63,59 @@ func (e *codexEngine) answerServerRequest(f codexFrame) { if f.ID == nil { return } - if !codexApprovalMethods[f.Method] { - // Not an approval. Answer with the JSON-RPC "method not found" code, - // which is a well-defined way to say "this client cannot do that" and - // leaves the server to decide what happens next. + switch { + case f.Method == codexQuestionMethod: + // A question, not a permission (codexquestion.go). + e.askQuestion(*f.ID, f) + case codexApprovalMethods[f.Method]: + e.askUser(*f.ID, f) + default: + // Neither. Answer with the JSON-RPC "method not found" code, which is a + // well-defined way to say "this client cannot do that" and leaves the + // server to decide what happens next. e.replyError(*f.ID, -32601, "cathode does not implement "+f.Method) e.emitError("unhandled request " + f.Method) - return } - e.askUser(*f.ID, f) } -// askUser puts a gated action in front of the user and answers with what they -// choose. +// ask puts one request in front of the user and answers it with result(reply). +// Every path to the pane goes through here, because the two rules it keeps are +// the ones that hang a turn when one is missed. // -// All of it runs off the reader goroutine, for two separate reasons. The reader -// must keep draining while the pane is up, or the item events that draw the -// very card being approved never arrive. And approvals are admitted one at a -// time: the UI holds a single pending approval, so a second would overwrite the -// first and leave codex waiting on a reply that can no longer be given. -func (e *codexEngine) askUser(id int64, f codexFrame) { - var p codexApprovalParams - _ = json.Unmarshal(f.Params, &p) - +// It runs off the reader goroutine: the reader must keep draining while the +// pane is up, or the item events that draw the very card being decided never +// arrive. And it holds the slot for the whole wait, because the UI has room for +// one request at a time — a second would overwrite the first and leave codex +// waiting on a reply that can no longer be given. +func (e *codexEngine) ask(id int64, req approvalReq, result func(approvalReply) any) { + reply := make(chan approvalReply, 1) + req.reply = reply go func() { e.approvalSlot <- struct{}{} defer func() { <-e.approvalSlot }() - reply := make(chan approvalReply, 1) - e.emitMsg(pendingApprovalMsg{req: approvalReq{ - toolName: codexApprovalLabel(f.Method, p), - toolUseID: p.ItemID, - input: f.Params, - reply: reply, - }}) + e.emitMsg(pendingApprovalMsg{req: req}) + e.replyResult(id, result(<-reply)) + }() +} +// askUser puts a gated action in front of the user and answers with the +// decision they made. +func (e *codexEngine) askUser(id int64, f codexFrame) { + var p codexApprovalParams + _ = json.Unmarshal(f.Params, &p) + + e.ask(id, approvalReq{ + toolName: codexApprovalLabel(f.Method, p), + toolUseID: p.ItemID, + input: f.Params, + }, func(r approvalReply) any { decision := codexRefusal - if (<-reply).allow { + if r.allow { decision = codexApproval } - e.replyResult(id, map[string]any{"decision": decision}) - }() + return map[string]any{"decision": decision} + }) } // codexApprovalLabel names the action on the approval bar. The command itself diff --git a/codexquestion.go b/codexquestion.go new file mode 100644 index 0000000..78ed75c --- /dev/null +++ b/codexquestion.go @@ -0,0 +1,118 @@ +// Copyright 2026 Triple Down AB +// SPDX-License-Identifier: Apache-2.0 + +package main + +import "encoding/json" + +// ---- codex asks the user a question ---- +// +// item/tool/requestUserInput is codex's analogue of claude's AskUserQuestion, +// and it carries the same thing: a list of questions, each offering labelled +// options. So this translates the request into the shape question.go already +// parses, and the chosen labels back into the result codex expects. The picker, +// the one-question-at-a-time flow and the transcript note are all shared. +// +// Two differences shape the code below. codex keys each answer by a question +// id rather than by position, so the id rides out with the question and back +// with the answer. And a codex question may offer no options at all, or be +// marked secret; the picker can do neither, so those questions are left out of +// the answer map. codex reads a missing id as unanswered, which is exactly what +// happened. +// +// Two schema fields are narrowed away on purpose. isOther offers a free-form +// answer beside the options, which the picker has no way to take — the same +// narrowing it already applies to claude's questions. And isBlocking is unread: +// answering is correct either way, and it is not answering that stops a turn. + +const codexQuestionMethod = "item/tool/requestUserInput" + +type codexQuestionOption struct { + Label string `json:"label"` + Description string `json:"description"` +} + +type codexQuestion struct { + ID string `json:"id"` + Header string `json:"header"` + Question string `json:"question"` + Options []codexQuestionOption `json:"options"` + IsSecret bool `json:"isSecret"` +} + +type codexQuestionParams struct { + ItemID string `json:"itemId"` + Questions []codexQuestion `json:"questions"` +} + +// codexAskable reports whether cathode can put this question to the user. It +// needs an id to file the answer under, and at least one option to choose from. +// A secret answer is refused whatever it offers, because the picker prints the +// choice into the transcript. +func codexAskable(q codexQuestion) bool { + return q.ID != "" && len(q.Options) > 0 && !q.IsSecret +} + +// codexAskInput translates the askable questions into the AskUserQuestion input +// that question.go parses. It reports false when none of them are askable, +// which tells the caller to answer with nothing rather than open an empty +// picker. +func codexAskInput(p codexQuestionParams) (json.RawMessage, bool) { + var in askInput + for _, q := range p.Questions { + if !codexAskable(q) { + continue + } + opts := make([]askOption, 0, len(q.Options)) + for _, o := range q.Options { + opts = append(opts, askOption{Label: o.Label, Description: o.Description}) + } + in.Questions = append(in.Questions, askQuestion{ + ID: q.ID, Question: q.Question, Header: q.Header, Options: opts, + }) + } + if len(in.Questions) == 0 { + return nil, false + } + b, err := json.Marshal(in) + if err != nil { + return nil, false + } + return b, true +} + +// codexQuestionResult builds the reply: each answered question id mapped to the +// labels chosen for it. An unanswered id is absent rather than empty. +func codexQuestionResult(answers []questionAnswer) map[string]any { + out := map[string]any{} + for _, a := range answers { + if a.id == "" || len(a.labels) == 0 { + continue + } + out[a.id] = map[string]any{"answers": a.labels} + } + return map[string]any{"answers": out} +} + +// askQuestion puts codex's question to the user and answers with what they +// chose. It goes to the pane through ask, like an approval does. +func (e *codexEngine) askQuestion(id int64, f codexFrame) { + var p codexQuestionParams + _ = json.Unmarshal(f.Params, &p) + + input, ok := codexAskInput(p) + if !ok { + // Nothing here cathode can ask. Answer with no answers, which is the + // dismissed-question case, and say why — a question that never appears + // reads as a bug in the pane rather than a limit of it. + e.replyResult(id, codexQuestionResult(nil)) + e.emitError("unanswered question: cathode can only answer one that offers options and is not secret") + return + } + + e.ask(id, approvalReq{ + toolName: askUserQuestionTool, + toolUseID: p.ItemID, + input: input, + }, func(r approvalReply) any { return codexQuestionResult(r.answers) }) +} diff --git a/codexquestion_test.go b/codexquestion_test.go new file mode 100644 index 0000000..c2b3510 --- /dev/null +++ b/codexquestion_test.go @@ -0,0 +1,214 @@ +// Copyright 2026 Triple Down AB +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +// The request shape is taken from ToolRequestUserInputParams in the codex +// app-server schema (0.153.4), not guessed. +func TestCodexQuestionBecomesTheSharedPicker(t *testing.T) { + in := codexQuestionParams{ItemID: "item-7", Questions: []codexQuestion{{ + ID: "q1", + Header: "Backend", + Question: "Which store should this write to?", + Options: []codexQuestionOption{ + {Label: "sqlite", Description: "a file on disk"}, + {Label: "postgres", Description: "the shared server"}, + }, + }}} + + raw, ok := codexAskInput(in) + if !ok { + t.Fatal("a question with options must be askable") + } + + q, ok := parseAskQuestion(approvalReq{toolName: askUserQuestionTool, input: raw}) + if !ok { + t.Fatal("the translated input must parse as an AskUserQuestion") + } + cur := q.current() + if cur.ID != "q1" { + t.Errorf("id = %q, want the id codex files the answer under", cur.ID) + } + if cur.Question != in.Questions[0].Question || cur.Header != in.Questions[0].Header { + t.Errorf("question = %q / %q, want it carried through", cur.Question, cur.Header) + } + if len(cur.Options) != 2 || cur.Options[1].Description != "the shared server" { + t.Errorf("options = %+v, want both with their descriptions", cur.Options) + } +} + +// A question the picker cannot put to the user is dropped rather than shown +// with no way to answer it. +func TestCodexQuestionSkipsWhatThePickerCannotAsk(t *testing.T) { + opts := []codexQuestionOption{{Label: "yes", Description: ""}} + for _, c := range []struct { + name string + q codexQuestion + }{ + {"free text", codexQuestion{ID: "q", Question: "Name it?"}}, + {"secret", codexQuestion{ID: "q", Question: "Token?", Options: opts, IsSecret: true}}, + {"no id", codexQuestion{Question: "Which?", Options: opts}}, + } { + t.Run(c.name, func(t *testing.T) { + if codexAskable(c.q) { + t.Fatalf("%+v must not be askable", c.q) + } + if _, ok := codexAskInput(codexQuestionParams{Questions: []codexQuestion{c.q}}); ok { + t.Error("a request of only unaskable questions must report none") + } + }) + } + + // Mixed: the askable one is still asked, and the rest are left unanswered. + raw, ok := codexAskInput(codexQuestionParams{Questions: []codexQuestion{ + {ID: "free", Question: "Name it?"}, + {ID: "pick", Question: "Which?", Options: opts}, + }}) + if !ok { + t.Fatal("one askable question is enough to ask") + } + var parsed askInput + if err := json.Unmarshal(raw, &parsed); err != nil { + t.Fatal(err) + } + if len(parsed.Questions) != 1 || parsed.Questions[0].ID != "pick" { + t.Errorf("asked %+v, want only the one with options", parsed.Questions) + } +} + +func TestCodexQuestionResultKeysAnswersByID(t *testing.T) { + got := codexQuestionResult([]questionAnswer{ + {id: "q1", labels: []string{"sqlite"}}, + {id: "q2", labels: []string{"read", "write"}}, + {id: "q3"}, // dismissed: absent, not empty + }) + b, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{`"q1":{"answers":["sqlite"]}`, `"q2":{"answers":["read","write"]}`} { + if !strings.Contains(string(b), want) { + t.Errorf("result %s, want it to contain %s", b, want) + } + } + if strings.Contains(string(b), `"q3"`) { + t.Errorf("result %s, want an unanswered id left out entirely", b) + } +} + +// End to end over the wire: codex asks, the pane answers, and the reply carries +// the chosen label under the question's id. An unanswered request stops the turn +// dead, so the reply reaching the wire is the point of the test. +func TestCodexQuestionRoundTrip(t *testing.T) { + fakeAppServer(t, ` +while IFS= read -r line; do + case "$line" in + *'"initialize"'*) printf '{"method":"item/tool/requestUserInput","id":0,"params":{"itemId":"item-7","threadId":"th-1","turnId":"tu-1","isBlocking":true,"questions":[{"id":"q1","header":"Store","question":"Which store?","options":[{"label":"sqlite","description":"a file"},{"label":"postgres","description":"the server"}]}]}}\n' ;; + *'"answers"'*) printf '{"method":"cathode/test/echo","params":%s}\n' "$line" ;; + esac +done +`) + e, err := newCodexEngine(codexEngineConfig{Mode: "build"}) + if err != nil { + t.Fatal(err) + } + defer e.Close() + + frames := make(chan codexFrame, 16) + other := make(chan tea.Msg, 16) + sinkTo(e, frames, other) + go func() { _, _ = e.call("initialize", map[string]any{}) }() + + req := awaitApproval(t, other) + if req.toolName != askUserQuestionTool { + t.Fatalf("toolName = %q, want the shared question tool so the picker opens", req.toolName) + } + if req.toolUseID != "item-7" { + t.Errorf("toolUseID = %q, want the itemId", req.toolUseID) + } + req.reply <- approvalReply{answers: []questionAnswer{{id: "q1", labels: []string{"postgres"}}}} + + select { + case f := <-frames: + if !strings.Contains(string(f.Params), `"q1":{"answers":["postgres"]}`) { + t.Errorf("sent %s, want the answer under its question id", f.Params) + } + case <-time.After(5 * time.Second): + t.Fatal("no answer was sent; the turn would hang") + } +} + +// Answering must send both forms: the prose claude reads and the ids codex +// reads. They are filled at one call site, so dropping either one leaves the +// other backend's answer empty with nothing else failing. +func TestAnsweringSendsBothFormsOfTheAnswer(t *testing.T) { + raw, ok := codexAskInput(codexQuestionParams{Questions: []codexQuestion{ + {ID: "q1", Question: "Which store?", Options: []codexQuestionOption{{Label: "sqlite"}, {Label: "postgres"}}}, + {ID: "q2", Question: "Which mode?", Options: []codexQuestionOption{{Label: "read"}}}, + }}) + if !ok { + t.Fatal("both questions offer options") + } + reply := make(chan approvalReply, 1) + q, ok := parseAskQuestion(approvalReq{toolName: askUserQuestionTool, input: raw, reply: reply}) + if !ok { + t.Fatal("the translated input must parse") + } + + m, _ := newTestModel(t, "") + m.question = q + m.answerQuestion([]string{"postgres"}) + if m.question == nil { + t.Fatal("two questions were asked; the first answer must not finish them") + } + m.answerQuestion([]string{"read"}) + + got := <-reply + if !strings.Contains(got.message, "postgres") || !strings.Contains(got.message, "read") { + t.Errorf("message = %q, want both answers in the prose claude reads", got.message) + } + b, err := json.Marshal(codexQuestionResult(got.answers)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{`"q1":{"answers":["postgres"]}`, `"q2":{"answers":["read"]}`} { + if !strings.Contains(string(b), want) { + t.Errorf("codex reply %s, want it to contain %s", b, want) + } + } +} + +// A question is asked even in build mode. It is not a permission, so "go +// autonomously" is not an answer to it. +func TestCodexQuestionIsAskedEvenInBuildMode(t *testing.T) { + raw, ok := codexAskInput(codexQuestionParams{ItemID: "i", Questions: []codexQuestion{{ + ID: "q1", Question: "Which?", Options: []codexQuestionOption{{Label: "a"}, {Label: "b"}}, + }}}) + if !ok { + t.Fatal(raw) + } + m, _ := newTestModel(t, "") + m.mode = "build" + reply := make(chan approvalReply, 1) + out, _ := m.Update(pendingApprovalMsg{req: approvalReq{ + toolName: askUserQuestionTool, toolUseID: "i", input: raw, reply: reply, + }}) + got := out.(model) + if got.question == nil || got.picker == nil { + t.Fatal("build mode must still open the question picker") + } + select { + case r := <-reply: + t.Fatalf("build mode auto-answered the question with %+v", r) + default: + } +} diff --git a/keys.go b/keys.go index 39c58b9..6da820d 100644 --- a/keys.go +++ b/keys.go @@ -192,10 +192,11 @@ func (m model) handleApprovalKey(msg tea.KeyMsg) (model, tea.Cmd, bool) { } // answerQuestion records the chosen labels for the current AskUserQuestion, then -// advances to the next question or — once all are answered — replies to claude -// with the combined answer (via the permission deny-message) and re-arms the -// approvals waiter. labels holds one label per marked option: several for a -// multiSelect question, one otherwise. +// advances to the next question or — once all are answered — replies with the +// combined answer and re-arms the approvals waiter. The reply carries both +// forms, because the two backends read different ones: claude the denial text, +// codex the answers keyed by question id. labels holds one label per marked +// option: several for a multiSelect question, one otherwise. func (m *model) answerQuestion(labels []string) tea.Cmd { q := m.question if q == nil || len(labels) == 0 { @@ -207,14 +208,15 @@ func (m *model) answerQuestion(labels []string) tea.Cmd { m.picker = q.picker(m.w, m.h) return nil } - q.req.reply <- approvalReply{message: q.answerMessage()} + q.req.reply <- approvalReply{message: q.answerMessage(), answers: q.answerSet()} m.add(entInfo, "✓ "+q.summary()) m.question = nil return waitApproval(m.approvals) } -// cancelQuestion dismisses the question (Esc): claude is told it went -// unanswered, and the waiter is re-armed. +// cancelQuestion dismisses the question (Esc): the agent is told it went +// unanswered, and the waiter is re-armed. No answers are attached, which is how +// codex reads the same thing. func (m *model) cancelQuestion() tea.Cmd { q := m.question if q == nil { diff --git a/question.go b/question.go index 8b065c7..0340939 100644 --- a/question.go +++ b/question.go @@ -30,6 +30,17 @@ type askQuestion struct { Header string `json:"header"` MultiSelect bool `json:"multiSelect"` Options []askOption `json:"options"` + // ID is the key the backend files this question's answer under. claude + // answers positionally and sends none, so it is empty there; codex keys its + // answer map by id (codexquestion.go). + ID string `json:"id,omitempty"` +} + +// questionAnswer is one answered question: the labels the user chose, against +// the id the backend keys its answers by. +type questionAnswer struct { + id string + labels []string } type askInput struct { @@ -100,6 +111,17 @@ func (q *pendingQuestion) answerMessage() string { return b.String() } +// answerSet is the same answer as data rather than as prose, for a backend that +// takes it that way. The order is the order the questions were asked, so a +// backend that sends no ids can still read it positionally. +func (q *pendingQuestion) answerSet() []questionAnswer { + out := make([]questionAnswer, 0, len(q.answers)) + for i, a := range q.answers { + out = append(out, questionAnswer{id: q.questions[i].ID, labels: a}) + } + return out +} + // summary is the compact transcript note recorded once answered. func (q *pendingQuestion) summary() string { picks := make([]string, 0, len(q.answers))