Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8240: fix(agent): keep Codex commentary out of output on empty final answer (#9521)
Andreia47a1ced0c71
diff --git a/server/internal/daemon/empty_output_completion_test.go b/server/internal/daemon/empty_output_completion_test.gonew file mode 100644index 0000000000..cd036281ea--- /dev/null+++ b/server/internal/daemon/empty_output_completion_test.go@@ -0,0 +1,70 @@+package daemon++import (+ "context"+ "log/slog"+ "net/http/httptest"+ "sync/atomic"+ "testing"++ "github.com/multica-ai/multica/server/pkg/agent"+)++// narratedEmptyOutputBackend streams narration and then completes with an+// empty Result.Output: the shape the Codex adapter reports when a turn ends+// with an empty final_answer after a commentary message.+type narratedEmptyOutputBackend struct{}++const narratedEmptyOutputText = "Posted the report to the target issue."++func (narratedEmptyOutputBackend) Execute(context.Context, string, agent.ExecOptions) (*agent.Session, error) {+ msgCh := make(chan agent.Message, 1)+ msgCh <- agent.Message{Type: agent.MessageText, Content: narratedEmptyOutputText}+ close(msgCh)+ resCh := make(chan agent.Result, 1)+ resCh <- agent.Result{Status: "completed", Output: ""}+ return &agent.Session{Messages: msgCh, Result: resCh}, nil+}++// The daemon must not rebuild Result.Output from the transcript: narration is+// reported as task messages only, and the completed result keeps its empty+// output.+func TestExecuteAndDrain_EmptyOutputIsNotRebuiltFromNarration(t *testing.T) {+ t.Parallel()++ d, rec := newTranscriptRecorder(t)++ result, _, err := d.executeAndDrain(context.Background(), narratedEmptyOutputBackend{}, "p", agent.ExecOptions{}, slog.Default(), "task-empty-output", "", new(atomic.Int32))+ if err != nil {+ t.Fatalf("executeAndDrain: %v", err)+ }+ if result.Status != "completed" || result.Output != "" {+ t.Fatalf("result = %+v, want completed with empty output", result)+ }+ messages := rec.snapshot()+ if len(messages) != 1 || messages[0].Content != narratedEmptyOutputText {+ t.Fatalf("transcript = %+v, want the narration reported as one task message", messages)+ }+}++// A completed run with no output still reports success, with an empty output+// the server does not turn into a comment.+func TestReportTaskResult_CompletedWithEmptyOutputPostsEmptyOutput(t *testing.T) {+ t.Parallel()++ rec := &reportTaskResultRecorder{}+ srv := httptest.NewServer(rec.handler(t))+ t.Cleanup(srv.Close)++ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}+ d.reportTaskResult(context.Background(), "task-empty", TaskResult{Status: "completed", Comment: ""}, slog.Default())++ rec.mu.Lock()+ defer rec.mu.Unlock()+ if rec.path != "/api/daemon/tasks/task-empty/complete" {+ t.Fatalf("expected /complete endpoint, got %s", rec.path)+ }+ if output, ok := rec.payload["output"]; ok && output != "" {+ t.Fatalf("output = %v, want empty", output)+ }+}diff --git a/server/internal/service/task_complete_delivery_test.go b/server/internal/service/task_complete_delivery_test.gonew file mode 100644index 0000000000..8730d30a4b--- /dev/null+++ b/server/internal/service/task_complete_delivery_test.go@@ -0,0 +1,177 @@+package service++import (+ "context"+ "encoding/json"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// deliveryFixture is a run of agent on source issue A that reports to target+// issue B. It counts the agent's comments on each issue.+type deliveryFixture struct {+ f principalFixture+ s *TaskService+ source pgtype.UUID+ target string+ agentID string+}++func newDeliveryFixture(t *testing.T) deliveryFixture {+ t.Helper()+ f, wake, source, agentID := wakeFixture(t)+ f.Cleanup(t, "DELETE FROM comment WHERE issue_id=$1", source)+ target := f.Issue(t, "Delivery target")+ f.Cleanup(t, "DELETE FROM comment WHERE issue_id=$1", target)+ return deliveryFixture{f: f, s: wake.Tasks, source: source, target: target, agentID: agentID}+}++// runningTask starts a run of the agent on the source issue a minute ago.+func (d deliveryFixture) runningTask(t *testing.T, over testutil.Cols) pgtype.UUID {+ t.Helper()+ cols := testutil.Cols{+ "issue_id": d.source,+ "status": "running",+ "started_at": testutil.Raw("now() - interval '1 minute'"),+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + d.agentID + "')"),+ }+ for k, v := range over {+ cols[k] = v+ }+ return parseTestUUID(t, d.f.Task(t, d.agentID, cols))+}++// reportOnTarget posts the agent's explicit report on the target issue, as+// `multica issue comment add <target>` does during the run.+func (d deliveryFixture) reportOnTarget(t *testing.T) {+ t.Helper()+ d.f.Comment(t, d.target, "Report for the target issue.", testutil.Cols{"author_type": "agent", "author_id": d.agentID})+}++func (d deliveryFixture) agentComments(t *testing.T, issue any) int {+ t.Helper()+ return d.f.Count(t, "SELECT count(*) FROM comment WHERE issue_id=$1 AND author_type='agent' AND author_id=$2", issue, d.agentID)+}++func (d deliveryFixture) complete(t *testing.T, task pgtype.UUID, output string) bool {+ t.Helper()+ result, err := json.Marshal(protocol.TaskCompletedPayload{Output: output})+ if err != nil {+ t.Fatal(err)+ }+ _, transitioned, err := d.s.CompleteTaskWithTransition(context.Background(), task, result, "", "", "", false, "", "")+ if err != nil {+ t.Fatalf("complete task: %v", err)+ }+ return transitioned+}++// A run on issue A that reported on issue B and then produced empty output+// (the Codex adapter's result for an empty final_answer after commentary)+// leaves exactly the one report on B and posts nothing on A, for assignment-+// and comment-triggered runs alike.+func TestCompleteTaskEmptyOutputAfterCrossIssueReportPostsNothingOnSource(t *testing.T) {+ d := newDeliveryFixture(t)++ for _, tc := range []struct {+ name string+ over testutil.Cols+ }{+ {name: "assignment run", over: nil},+ {name: "comment-triggered run", over: testutil.Cols{"trigger_comment_id": d.f.Comment(t, util.UUIDToString(d.source), "please report on B")}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ sourceBefore, targetBefore := d.agentComments(t, d.source), d.agentComments(t, d.target)+ task := d.runningTask(t, tc.over)+ d.reportOnTarget(t)++ if !d.complete(t, task, "") {+ t.Fatal("the first completion callback did not transition the task")+ }+ if got := d.agentComments(t, d.source) - sourceBefore; got != 0 {+ t.Fatalf("source issue got %d agent comments, want none", got)+ }+ if got := d.agentComments(t, d.target) - targetBefore; got != 1 {+ t.Fatalf("target issue has %d new agent comments, want exactly the report", got)+ }+ })+ }+}++// The fallback guard only looks at the source issue, so a non-empty output+// still becomes a comment on A even after an explicit report on B. This pins+// the existing contract: there is no destination or suppression field, and+// the adapter fix does not add one.+func TestCompleteTaskNonEmptyOutputAfterCrossIssueReportStillFallsBackToSource(t *testing.T) {+ d := newDeliveryFixture(t)+ task := d.runningTask(t, nil)+ d.reportOnTarget(t)++ if !d.complete(t, task, "Final answer text.") {+ t.Fatal("the first completion callback did not transition the task")+ }+ if got := d.f.Count(t, "SELECT count(*) FROM comment WHERE issue_id=$1 AND source_task_id=$2", d.source, task); got != 1 {+ t.Fatalf("source issue got %d fallback comments, want 1 under the current contract", got)+ }+ if got := d.agentComments(t, d.target); got != 1 {+ t.Fatalf("target issue has %d agent comments, want exactly the report", got)+ }+}++// A replayed terminal callback (the daemon retries until acknowledged) is an+// idempotent no-op: one completion, one result comment, no new task.+func TestCompleteTaskRepeatedCallbackPostsOneResult(t *testing.T) {+ d := newDeliveryFixture(t)++ for _, tc := range []struct {+ name string+ output string+ wantComments int+ }{+ {name: "non-empty output", output: "Final answer text.", wantComments: 1},+ {name: "empty output", output: "", wantComments: 0},+ } {+ t.Run(tc.name, func(t *testing.T) {+ task := d.runningTask(t, nil)+ if !d.complete(t, task, tc.output) {+ t.Fatal("the first completion callback did not transition the task")+ }+ tasksAfterFirst := d.f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE issue_id=$1", d.source)++ if d.complete(t, task, tc.output) {+ t.Fatal("a replayed completion callback transitioned the task again")+ }+ if got := d.f.Count(t, "SELECT count(*) FROM comment WHERE issue_id=$1 AND source_task_id=$2", d.source, task); got != tc.wantComments {+ t.Fatalf("source issue has %d result comments after the replay, want %d", got, tc.wantComments)+ }+ if got := d.f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE issue_id=$1", d.source); got != tasksAfterFirst {+ t.Fatalf("the replayed callback queued %d new tasks", got-tasksAfterFirst)+ }+ })+ }+}++// A completion callback that arrives after the run already failed or was+// cancelled neither flips the status nor publishes the output.+func TestCompleteTaskAfterFailedOrCancelledPublishesNothing(t *testing.T) {+ d := newDeliveryFixture(t)++ for _, status := range []string{"failed", "cancelled"} {+ t.Run(status, func(t *testing.T) {+ task := d.runningTask(t, testutil.Cols{"status": status, "completed_at": testutil.Raw("now()")})+ if d.complete(t, task, "Late final answer.") {+ t.Fatalf("completion transitioned a %s task", status)+ }+ if got := d.f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE id=$1 AND status=$2", task, status); got != 1 {+ t.Fatalf("task status changed from %s", status)+ }+ if got := d.f.Count(t, "SELECT count(*) FROM comment WHERE source_task_id=$1", task); got != 0 {+ t.Fatalf("late completion of a %s task posted %d comments", status, got)+ }+ })+ }+}diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex d6b4b2c496..9ac4c06970 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -1242,12 +1242,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execvar outputMu sync.Mutex// Result.Output is "final user-facing output selected by the backend"- // (agent.go), so it holds the deliverable only. finalAnswer is the text the- // app-server labelled `phase: "final_answer"`; lastAgentMessage is the- // fallback for the legacy `agent_message` protocol, which carries no phase.+ // (agent.go), so it holds the deliverable only. output tracks the text the+ // app-server labelled `phase: "final_answer"` and, for the legacy+ // `agent_message` protocol which carries no phase, the last agent message.// Every agent message still flows to msgCh, so the transcript is unchanged —// only what the daemon forwards to a chat/channel reply narrows (GH #6006).- var finalAnswer, lastAgentMessage string+ var output codexOutputSelectionvar semanticObserved atomic.BoolturnNotificationGate := &codexTurnNotificationGate{}firstItemWait := &codexFirstItemWaitObservation{}@@ -1310,17 +1310,17 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec// preserving the reader's EOF and cancellation liveness.return trySend(msgCh, msg)},- onAgentMessage: func(text string) {+ onAgentMessage: func(text, phase string) {// Delta events make MessageText incremental. Keep Result.Output's// legacy fallback authoritative by updating it from the completed// agent-message snapshot, not whichever delta happened to arrive last.outputMu.Lock()- lastAgentMessage = text+ output.observeAgentMessage(text, phase)outputMu.Unlock()},onFinalAnswer: func(text string) {outputMu.Lock()- finalAnswer = text+ output.observeFinalAnswer(text)outputMu.Unlock()},onSemanticActivity: func(description string) {@@ -1898,7 +1898,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}outputMu.Lock()- finalOutput := codexDeliverableOutput(finalAnswer, lastAgentMessage)+ finalOutput := codexDeliverableOutput(output)outputMu.Unlock()// Build usage map from accumulated codex usage.@@ -2320,17 +2320,50 @@ func trySendString(ch chan<- string, value string) {}}+// codexOutputSelection records what a turn produced that could become+// Result.Output. The zero value is an empty selection.+type codexOutputSelection struct {+ // finalAnswer is the last non-blank message labelled `phase: "final_answer"`.+ finalAnswer string+ // finalAnswerObserved is set by any final_answer item, including one with+ // empty or whitespace-only text: the app-server explicitly ended the turn+ // without a deliverable, which is different from never labelling one.+ finalAnswerObserved bool+ lastAgentMessage string+ // lastAgentMessagePhase is the phase label of lastAgentMessage; empty for+ // the legacy protocol and for app-servers that do not label phases.+ lastAgentMessagePhase string+}++func (s *codexOutputSelection) observeAgentMessage(text, phase string) {+ s.lastAgentMessage = text+ s.lastAgentMessagePhase = phase+}++func (s *codexOutputSelection) observeFinalAnswer(text string) {+ s.finalAnswerObserved = true+ if strings.TrimSpace(text) != "" {+ s.finalAnswer = text+ }+}+// codexDeliverableOutput picks Result.Output from what the turn produced: the// message the app-server itself labelled `phase: "final_answer"`, or — for the// legacy `agent_message` protocol, which carries no phase — the most recent// agent message. Never every message joined: the intermediate ones narrate the// work between tool calls, which belongs to the transcript and not to a chat or-// IM reply (GH #6006).-func codexDeliverableOutput(finalAnswer, lastAgentMessage string) string {- if finalAnswer != "" {- return finalAnswer+// IM reply (GH #6006). A message explicitly labelled with another phase (for+// example `commentary`) is narration too, so an empty or missing final answer+// after it yields empty output instead of promoting the narration to the+// deliverable.+func codexDeliverableOutput(s codexOutputSelection) string {+ if s.finalAnswer != "" {+ return s.finalAnswer+ }+ if s.finalAnswerObserved || s.lastAgentMessagePhase != "" {+ return ""}- return lastAgentMessage+ return s.lastAgentMessage}func logCodexAgentMessage(logger *slog.Logger, msg Message) {@@ -2394,9 +2427,10 @@ type codexClient struct {// delivered prefix. Unit clients may leave this nil and use onMessage.onAgentMessageChunk func(text string) bool// onAgentMessage receives the authoritative completed text for one agent- // message. onAgentMessageChunk may deliver that text incrementally, so+ // message and its phase label ("" when the protocol carries none).+ // onAgentMessageChunk may deliver that text incrementally, so// Result.Output fallbacks must use this callback rather than the last chunk.- onAgentMessage func(text string)+ onAgentMessage func(text, phase string)onSemanticActivity func(description string)onTurnDone func(aborted bool)guardianRateLimitCircuit *codexGuardianRateLimitCircuit@@ -2404,6 +2438,8 @@ type codexClient struct {// onFinalAnswer fires only for an agent message the app-server itself// labelled `phase: "final_answer"` — the turn's deliverable, as opposed to// the intermediate agent messages that narrate work between tool calls.+ // It fires for an empty final answer too, so the caller can tell "ended+ // without a deliverable" from "never labelled one".// Both still reach onMessage: the transcript keeps the whole timeline, only// Result.Output is narrowed to the deliverable (GH #6006).onFinalAnswer func(text string)@@ -3390,7 +3426,7 @@ func (c *codexClient) handleEvent(msg map[string]any) {c.onMessage(Message{Type: MessageText, Content: text})}if text != "" && c.onAgentMessage != nil {- c.onAgentMessage(text)+ c.onAgentMessage(text, "")}case "exec_command_begin":callID, _ := msg["call_id"].(string)@@ -3797,18 +3833,20 @@ func (c *codexClient) handleItemNotification(method string, params map[string]ancase method == "item/completed" && itemType == "agentMessage":text, _ := item["text"].(string)+ phase, _ := item["phase"].(string)if text != "" && c.onAgentMessage != nil {- c.onAgentMessage(text)+ c.onAgentMessage(text, phase)}c.completeAgentMessage(itemID, text)- phase, _ := item["phase"].(string)if phase == "final_answer" {// The gate exists so a subagent or a replayed history turn cannot// end OUR turn early, and the thread guard at the top of this// function already keeps foreign threads out. A final answer that// arrives before we observed turn/started is still this thread's- // deliverable, and dropping it would fall back to narration.- if text != "" && c.onFinalAnswer != nil {+ // deliverable, and dropping it would fall back to narration. An+ // empty final answer is reported too: it means the turn ended+ // without a deliverable, not that the last narration is one.+ if c.onFinalAnswer != nil {c.onFinalAnswer(text)}// Keep the stream open until turn/completed. A final answer is thediff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 021b536bea..fd29fb7930 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -1558,7 +1558,7 @@ func TestCodexRawItemAgentMessageReconciliation(t *testing.T) {chunks = append(chunks, text)return true}- c.onAgentMessage = func(text string) { completed = text }+ c.onAgentMessage = func(text, _ string) { completed = text }for _, delta := range tt.deltas {c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thr-1","turnId":"turn-1","itemId":"msg-1","delta":%q}}`, delta))@@ -1588,7 +1588,7 @@ func TestCodexRawAgentMessageBelowAggregationThresholdDefersTailUntilCompleted(treturn true}var authoritative string- c.onAgentMessage = func(text string) { authoritative = text }+ c.onAgentMessage = func(text, _ string) { authoritative = text }deltas := []string{"The ", "answer ", "is 42."}completed := strings.Join(deltas, "")@@ -1631,7 +1631,7 @@ func TestCodexRawAgentMessageMismatchRetriesRejectedPendingAtTerminal(t *testingreturn trySend(messages, Message{Type: MessageText, Content: text})}var completed string- c.onAgentMessage = func(text string) { completed = text }+ c.onAgentMessage = func(text, _ string) { completed = text }c.handleLine(`{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"itemId":"msg-1","delta":"Hx"}}`)// Fill the remaining slot after Hx was accepted. The mismatch path's first@@ -1818,43 +1818,102 @@ func TestCodexRawAgentMessageAbnormalEOFFlushesCompleteDeltas(t *testing.T) {// TestCodexDeliverableOutputExcludesNarration pins Result.Output to the turn's// deliverable. Codex used to concatenate every agent message, so a tool-using// run shipped its intermediate narration to Slack and Lark along with the answer-// (GH #6006). The wiring mirrors executeOnce: onAgentMessage tracks the last-// authoritative completed message, onFinalAnswer captures the phase-labelled one, and-// codexDeliverableOutput picks between them.+// (GH #6006). Later, an empty final_answer after a `commentary` message promoted+// that commentary to Result.Output, which the server then posted as the run's+// result comment. The wiring mirrors executeOnce: onAgentMessage+// and onFinalAnswer feed a codexOutputSelection and codexDeliverableOutput picks+// from it.func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {t.Parallel()const (rawNarration = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m1","text":"Let me check the logs."}}}`rawFinal = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m2","text":"The retry loop is the cause.","phase":"final_answer"}}}`+ rawCommentary = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m1","text":"Let me check the logs.","phase":"commentary"}}}`+ rawEmptyFinal = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m3","text":"","phase":"final_answer"}}}`+ rawBlankFinal = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m3","text":" \n\t ","phase":"final_answer"}}}`legacyFirst = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"agent_message","message":"Let me check the logs."}}}`legacySecond = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"agent_message","message":"The retry loop is the cause."}}}`+ narration = "Let me check the logs."wantDeliverabl = "The retry loop is the cause.")cases := []struct {- name string- protocol string- lines []string- want string+ name string+ protocol string+ lines []string+ want string+ wantStreamed []string}{{- name: "raw protocol keeps only the labelled final answer",- protocol: "raw",- lines: []string{rawNarration, rawFinal},- want: wantDeliverabl,+ name: "raw protocol keeps only the labelled final answer",+ protocol: "raw",+ lines: []string{rawNarration, rawFinal},+ want: wantDeliverabl,+ wantStreamed: []string{narration, wantDeliverabl},+ },+ {+ name: "raw protocol keeps the final answer after labelled commentary",+ protocol: "raw",+ lines: []string{rawCommentary, rawFinal},+ want: wantDeliverabl,+ wantStreamed: []string{narration, wantDeliverabl},+ },+ {+ name: "raw protocol without a final_answer falls back to the last message",+ protocol: "raw",+ lines: []string{rawNarration, `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m2","text":"The retry loop is the cause."}}}`},+ want: wantDeliverabl,+ wantStreamed: []string{narration, wantDeliverabl},+ },+ {+ name: "legacy protocol carries no phase and falls back to the last message",+ protocol: "legacy",+ lines: []string{legacyFirst, legacySecond},+ want: wantDeliverabl,+ wantStreamed: []string{narration, wantDeliverabl},},{- name: "raw protocol without a final_answer falls back to the last message",- protocol: "raw",- lines: []string{rawNarration, `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m2","text":"The retry loop is the cause."}}}`},- want: wantDeliverabl,+ name: "empty final answer after commentary yields no output",+ protocol: "raw",+ lines: []string{rawCommentary, rawEmptyFinal},+ want: "",+ wantStreamed: []string{narration},},{- name: "legacy protocol carries no phase and falls back to the last message",- protocol: "legacy",- lines: []string{legacyFirst, legacySecond},- want: wantDeliverabl,+ name: "whitespace-only final answer after commentary yields no output",+ protocol: "raw",+ lines: []string{rawCommentary, rawBlankFinal},+ want: "",+ wantStreamed: []string{narration, " \n\t "},+ },+ {+ name: "empty final answer after a phase-less message yields no output",+ protocol: "raw",+ lines: []string{rawNarration, rawEmptyFinal},+ want: "",+ wantStreamed: []string{narration},+ },+ {+ name: "commentary without a final answer is not the deliverable",+ protocol: "raw",+ lines: []string{rawCommentary},+ want: "",+ wantStreamed: []string{narration},+ },+ {+ name: "a later empty final answer does not erase an earlier one",+ protocol: "raw",+ lines: []string{rawCommentary, rawFinal, rawEmptyFinal},+ want: wantDeliverabl,+ wantStreamed: []string{narration, wantDeliverabl},+ },+ {+ name: "a repeated final answer event keeps the same deliverable",+ protocol: "raw",+ lines: []string{rawCommentary, rawFinal, rawFinal},+ want: wantDeliverabl,+ wantStreamed: []string{narration, wantDeliverabl, wantDeliverabl},},}@@ -1865,32 +1924,53 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {c, _, _ := newTestCodexClient(t)c.notificationProtocol = tc.protocol- var finalAnswer, lastAgentMessage string+ var output codexOutputSelectionvar streamed []stringc.onMessage = func(msg Message) {if msg.Type == MessageText {streamed = append(streamed, msg.Content)}}- c.onAgentMessage = func(text string) { lastAgentMessage = text }- c.onFinalAnswer = func(text string) { finalAnswer = text }+ c.onAgentMessage = output.observeAgentMessage+ c.onFinalAnswer = output.observeFinalAnswerfor _, line := range tc.lines {c.handleLine(line)}- if got := codexDeliverableOutput(finalAnswer, lastAgentMessage); got != tc.want {+ if got := codexDeliverableOutput(output); got != tc.want {t.Fatalf("Result.Output = %q, want %q", got, tc.want)}- // Narrowing delivery must not narrow the transcript: both messages- // still stream to the timeline the Multica UI renders.- if len(streamed) != 2 || streamed[0] != "Let me check the logs." {- t.Fatalf("expected both agent messages streamed, got %q", streamed)+ // Narrowing delivery must not narrow the transcript: every agent+ // message still streams to the timeline the Multica UI renders.+ if !reflect.DeepEqual(streamed, tc.wantStreamed) {+ t.Fatalf("streamed agent messages = %q, want %q", streamed, tc.wantStreamed)}})}}+// An empty final_answer from another thread must not mark this turn as having+// ended without a deliverable: the thread guard keeps it out of the selection.+func TestCodexDeliverableOutputIgnoresForeignThreadEmptyFinalAnswer(t *testing.T) {+ t.Parallel()++ c, _, _ := newTestCodexClient(t)+ c.notificationProtocol = "raw"+ c.threadID = "thr_main"++ var output codexOutputSelection+ c.onAgentMessage = output.observeAgentMessage+ c.onFinalAnswer = output.observeFinalAnswer++ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr_main","item":{"type":"agentMessage","id":"m1","text":"Main answer"}}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr_subagent","item":{"type":"agentMessage","id":"sub-1","text":"","phase":"final_answer"}}}`)++ if got := codexDeliverableOutput(output); got != "Main answer" {+ t.Fatalf("Result.Output = %q, want the main thread's message", got)+ }+}+func TestCodexRawThreadStatusIdleWaitsForTurnCompleted(t *testing.T) {t.Parallel()@@ -4320,6 +4400,51 @@ func TestCodexExecutePhaseLessCompletedMessageRemainsAuthoritative(t *testing.T)}}+// TestCodexExecuteEmptyFinalAnswerAfterCommentaryYieldsNoOutput replays the+// reported event shape end to end: a `commentary` message, then a+// `final_answer` item with empty text, then turn/completed. The run completes+// with empty Result.Output so the server posts no comment built from narration,+// while the commentary still reaches the transcript.+func TestCodexExecuteEmptyFinalAnswerAfterCommentaryYieldsNoOutput(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-empty-final"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-empty-final","turn":{"id":"turn-empty-final"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-empty-final","turnId":"turn-empty-final","item":{"type":"agentMessage","id":"msg-1","text":"Posted the report to the target issue.","phase":"commentary"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-empty-final","turnId":"turn-empty-final","item":{"type":"agentMessage","id":"msg-2","text":"","phase":"final_answer"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-empty-final","turn":{"id":"turn-empty-final","status":"completed"}}}'`+"\n")++ result, messages := executeFakeCodexCollectingMessages(t, fakePath, ExecOptions{+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 5 * time.Second,+ }, 10*time.Second)+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed (error=%q)", result.Status, result.Error)+ }+ if result.Output != "" {+ t.Fatalf("Result.Output = %q, want empty: commentary must not become the deliverable", result.Output)+ }+ var transcript []string+ for _, msg := range messages {+ if msg.Type == MessageText {+ transcript = append(transcript, msg.Content)+ }+ }+ if strings.Join(transcript, "") != "Posted the report to the target issue." {+ t.Fatalf("transcript text = %q, want the commentary preserved", transcript)+ }+}+func TestCodexExecuteSemanticInactivityDoesNotAffectNormalTurnCompletion(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {