Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): stop reporting Codex narration as a run's result (MUL-10116) (#11472)

Jean Wood3f81d3933031
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 8c79e8d707..e18b6e9b3b 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -1204,9 +1204,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// Result.Output is "final user-facing output selected by the backend"
// (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).
+ // `agent_message` protocol which carries no phase, the last agent message —
+ // which a tool call afterwards clears, because unlabelled text followed by
+ // tool use is narration (GH #6006). Every agent message still flows to
+ // msgCh, so the transcript is unchanged — only what the daemon forwards to a
+ // chat/channel reply narrows.
var output codexOutputSelection
var semanticObserved atomic.Bool
turnNotificationGate := &codexTurnNotificationGate{}
@@ -1253,6 +1255,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
observeMessage(msg)
trySend(msgCh, msg)
},
+ onToolActivity: func(callID string, started bool) {
+ outputMu.Lock()
+ output.observeToolActivity(callID, started)
+ outputMu.Unlock()
+ },
onAgentMessageChunk: func(text string) bool {
msg := Message{Type: MessageText, Content: text}
observeMessage(msg)
@@ -2244,8 +2251,11 @@ type codexOutputSelection struct {
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.
+ // app-servers and gateways that do not label phases.
lastAgentMessagePhase string
+ // startedToolCalls holds the call IDs whose start this turn observed, so
+ // their end can be told apart from an end that arrives without one.
+ startedToolCalls map[string]struct{}
}
func (s *codexOutputSelection) observeAgentMessage(text, phase string) {
@@ -2253,6 +2263,39 @@ func (s *codexOutputSelection) observeAgentMessage(text, phase string) {
s.lastAgentMessagePhase = phase
}
+// observeToolActivity records a tool call starting (started=true) or ending.
+// Unlabelled text followed by a tool call is narration — "Let me check the
+// logs." — so it must not outlive the call as the phase-less fallback: a turn
+// that ends right after a tool call (or whose final `task_complete` carries no
+// message at all) would otherwise hand that sentence to the server as the run's
+// result, and the server synthesizes a comment from it. Same rule as
+// assistantTurn.resolveFallback for the stream-json backends, which drops its
+// candidate when a turn uses a tool.
+//
+// The start of a call is what marks the text before it as narration. The end
+// of a call whose start was seen is not a new action and keeps the candidate:
+// Codex reports a background command's end when the process exits, which can
+// be after the answer the model wrote meanwhile. An end without an observed
+// start still clears, because then it is the only sign that a tool ran after
+// the text.
+//
+// The transcript is untouched: the text already reached the message channel,
+// and the clearing only affects what Result.Output may still adopt.
+func (s *codexOutputSelection) observeToolActivity(callID string, started bool) {
+ if started {
+ if callID != "" {
+ if s.startedToolCalls == nil {
+ s.startedToolCalls = make(map[string]struct{})
+ }
+ s.startedToolCalls[callID] = struct{}{}
+ }
+ } else if _, ok := s.startedToolCalls[callID]; ok && callID != "" {
+ return
+ }
+ s.lastAgentMessage = ""
+ s.lastAgentMessagePhase = ""
+}
+
func (s *codexOutputSelection) observeFinalAnswer(text string) {
s.finalAnswerObserved = true
if strings.TrimSpace(text) != "" {
@@ -2269,6 +2312,10 @@ func (s *codexOutputSelection) observeFinalAnswer(text string) {
// 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.
+//
+// A phase-less message stops being the candidate once the turn calls a tool
+// after it (observeToolActivity): "Let me verify the facts." followed by the
+// tool call is narration, and a run that ends there has no deliverable at all.
func codexDeliverableOutput(s codexOutputSelection) string {
if s.finalAnswer != "" {
return s.finalAnswer
@@ -2366,6 +2413,17 @@ type codexClient struct {
// Both still reach onMessage: the transcript keeps the whole timeline, only
// Result.Output is narrowed to the deliverable (GH #6006).
onFinalAnswer func(text string)
+ // onToolActivity fires when a tool call starts (started=true) or ends, for
+ // every kind of tool the protocol reports — including the ones that never
+ // reach the transcript, such as web search. callID pairs the two ends; it
+ // may be "" when the protocol omits it. Result.Output uses it to tell
+ // narration before a tool call from a deliverable (codexOutputSelection).
+ onToolActivity func(callID string, started bool)
+ // legacyTurnID is the turn_id of this turn's legacy task_started event; ""
+ // until it arrives or when the stream omits it. Legacy tool events carry
+ // their own turn_id, and one from an earlier turn (a background command
+ // that exits now) must not count as tool activity in this one.
+ legacyTurnID string
// acceptNotification isolates the active turn from same-thread history
// replay emitted while thread/resume is restoring prior conversation.
// Unit-level protocol tests leave it nil and exercise dispatch directly.
@@ -2901,6 +2959,7 @@ func (c *codexClient) handleServerRequest(raw map[string]json.RawMessage) {
var method string
_ = json.Unmarshal(raw["method"], &method)
+ c.reportServerRequestToolActivity(method, raw["params"])
// Auto-approve all exec/patch requests in daemon mode
switch method {
@@ -3366,6 +3425,10 @@ func pluralizeFiles(n int) string {
func (c *codexClient) handleEvent(msg map[string]any) {
msgType, _ := msg["type"].(string)
+ if msgType == "task_started" {
+ c.legacyTurnID, _ = msg["turn_id"].(string)
+ }
+ c.reportLegacyToolActivity(msgType, msg)
switch msgType {
case "task_started":
@@ -3374,11 +3437,17 @@ func (c *codexClient) handleEvent(msg map[string]any) {
}
case "agent_message":
text, _ := msg["message"].(string)
+ // Codex copies the item's phase onto the legacy event; gateways that
+ // strip it leave it absent, which keeps the phase-less fallback.
+ phase, _ := msg["phase"].(string)
if text != "" && c.onMessage != nil {
c.onMessage(Message{Type: MessageText, Content: text})
}
if text != "" && c.onAgentMessage != nil {
- c.onAgentMessage(text, "")
+ c.onAgentMessage(text, phase)
+ }
+ if phase == "final_answer" && c.onFinalAnswer != nil {
+ c.onFinalAnswer(text)
}
case "exec_command_begin":
callID, _ := msg["call_id"].(string)
@@ -3465,6 +3534,15 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
}
switch method {
+ case "turn/plan/updated":
+ // The update_plan tool reports only through this notification, never
+ // as a thread item.
+ turnID, _ := params["turnId"].(string)
+ if active := c.activeTurnID(); c.onToolActivity != nil &&
+ (turnID == "" || active == "" || turnID == active) {
+ c.onToolActivity("", true)
+ }
+
case "thread/tokenUsage/updated":
c.updateThreadTokenUsage(params)
@@ -3719,6 +3797,15 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
if item == nil && method != "item/agentMessage/delta" {
return
}
+ if _, ok := codexToolItemTypes[itemType]; ok && c.onToolActivity != nil &&
+ !codexIsUserShellCommand(item["source"]) {
+ switch method {
+ case "item/started":
+ c.onToolActivity(itemID, true)
+ case "item/completed":
+ c.onToolActivity(itemID, false)
+ }
+ }
switch {
case method == "item/agentMessage/delta" && itemType == "agentMessage":
@@ -3870,6 +3957,110 @@ func codexRawTokenUsageFromV2(usage map[string]any) codexRawTokenUsage {
}
}
+// codexToolItemTypes are the v2 thread item types that are tool calls, as
+// opposed to messages, reasoning, plans and review/compaction markers. Several
+// (webSearch, dynamicToolCall, imageGeneration, ...) never reach the
+// transcript, but they still mark the text before them as narration.
+var codexToolItemTypes = map[string]struct{}{
+ "commandExecution": {},
+ "fileChange": {},
+ "mcpToolCall": {},
+ "dynamicToolCall": {},
+ "collabAgentToolCall": {},
+ "webSearch": {},
+ "imageView": {},
+ "imageGeneration": {},
+ "sleep": {},
+}
+
+// reportLegacyToolActivity forwards a legacy codex/event tool event to
+// onToolActivity, skipping a command the user ran (source user_shell) and an
+// event whose turn_id names a turn other than this one.
+func (c *codexClient) reportLegacyToolActivity(msgType string, msg map[string]any) {
+ started, ok := codexLegacyToolEvents[msgType]
+ if !ok || c.onToolActivity == nil || codexIsUserShellCommand(msg["source"]) {
+ return
+ }
+ if turnID, _ := msg["turn_id"].(string); turnID != "" && c.legacyTurnID != "" && turnID != c.legacyTurnID {
+ return
+ }
+ callID, _ := msg["call_id"].(string)
+ if callID == "" {
+ callID, _ = msg["callId"].(string)
+ }
+ c.onToolActivity(callID, started)
+}
+
+// reportServerRequestToolActivity counts an approval request as the start of
+// the tool call it gates. request_permissions is a tool of its own, and an
+// approval may be all a denied or pending call ever reports.
+func (c *codexClient) reportServerRequestToolActivity(method string, rawParams json.RawMessage) {
+ if _, ok := codexToolServerRequests[method]; !ok || c.onToolActivity == nil {
+ return
+ }
+ var params map[string]any
+ _ = json.Unmarshal(rawParams, &params)
+ if c.isNotificationFromOtherThread(params) {
+ return
+ }
+ callID, _ := params["itemId"].(string)
+ if callID == "" {
+ callID, _ = params["callId"].(string)
+ }
+ c.onToolActivity(callID, true)
+}
+
+// codexIsUserShellCommand reports whether a command's source says the user ran
+// it rather than the model: v2 "userShell", legacy "user_shell".
+func codexIsUserShellCommand(source any) bool {
+ s, _ := source.(string)
+ return s == "userShell" || s == "user_shell"
+}
+
+// codexToolServerRequests are the app-server requests that gate a tool call.
+var codexToolServerRequests = map[string]struct{}{
+ "item/commandExecution/requestApproval": {},
+ "item/fileChange/requestApproval": {},
+ "item/permissions/requestApproval": {},
+ "execCommandApproval": {},
+ "applyPatchApproval": {},
+}
+
+// codexLegacyToolEvents maps each legacy codex/event tool event to whether it
+// starts (true) or ends (false) a call. Single-event tools (view_image,
+// update_plan, request_user_input, request_permissions) and approval requests
+// count as a start.
+var codexLegacyToolEvents = map[string]bool{
+ "exec_command_begin": true,
+ "exec_command_end": false,
+ "patch_apply_begin": true,
+ "patch_apply_end": false,
+ "mcp_tool_call_begin": true,
+ "mcp_tool_call_end": false,
+ "web_search_begin": true,
+ "web_search_end": false,
+ "image_generation_begin": true,
+ "image_generation_end": false,
+ "view_image_tool_call": true,
+ "plan_update": true,
+ "request_user_input": true,
+ "request_permissions": true,
+ "exec_approval_request": true,
+ "apply_patch_approval_request": true,
+ "dynamic_tool_call_request": true,
+ "dynamic_tool_call_response": false,
+ "collab_agent_spawn_begin": true,
+ "collab_agent_spawn_end": false,
+ "collab_agent_interaction_begin": true,
+ "collab_agent_interaction_end": false,
+ "collab_waiting_begin": true,
+ "collab_waiting_end": false,
+ "collab_close_begin": true,
+ "collab_close_end": false,
+ "collab_resume_begin": true,
+ "collab_resume_end": false,
+}
+
// isCodexItemProgressActivity reports whether an item notification shows the
// model working. userMessage items are app-server echoing the submitted input,
// which it does before reaching the model service, so they prove nothing about
diff --git a/server/pkg/agent/codex_process.go b/server/pkg/agent/codex_process.go
index 366965ac44..d1bb371852 100644
--- a/server/pkg/agent/codex_process.go
+++ b/server/pkg/agent/codex_process.go
@@ -43,6 +43,7 @@ type codexTurnHooks struct {
onAgentMessageChunk func(text string) bool
onAgentMessage func(text, phase string)
onFinalAnswer func(text string)
+ onToolActivity func(callID string, started bool)
onSemanticActivity func(description string)
onReconnect func(reason string)
onTurnDone func(aborted bool)
@@ -63,6 +64,8 @@ func (c *codexClient) attachTurnHooks(h codexTurnHooks) {
c.onAgentMessageChunk = h.onAgentMessageChunk
c.onAgentMessage = h.onAgentMessage
c.onFinalAnswer = h.onFinalAnswer
+ c.onToolActivity = h.onToolActivity
+ c.legacyTurnID = ""
c.onSemanticActivity = h.onSemanticActivity
c.onReconnect = h.onReconnect
c.onTurnDone = h.onTurnDone
@@ -99,6 +102,8 @@ func (c *codexClient) detachTurnHooks() {
c.onAgentMessageChunk = nil
c.onAgentMessage = nil
c.onFinalAnswer = nil
+ c.onToolActivity = nil
+ c.legacyTurnID = ""
c.onSemanticActivity = nil
c.onReconnect = nil
c.onTurnDone = nil
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index df380c5749..4927004ed8 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -1896,9 +1896,12 @@ func TestCodexRawAgentMessageAbnormalEOFFlushesCompleteDeltas(t *testing.T) {
// run shipped its intermediate narration to Slack and Lark along with the answer
// (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.
+// result comment. The remaining hole was the phase-less protocol: a run whose
+// last event was a tool call left its closing narration — "Let me verify the
+// permission facts for the tcpdump output path." — as the only candidate, and
+// the server synthesized a comment from it. The wiring mirrors executeOnce:
+// onAgentMessage, onFinalAnswer and the tool-event branch of onMessage feed a
+// codexOutputSelection and codexDeliverableOutput picks from it.
func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
t.Parallel()
@@ -1910,6 +1913,31 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
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."}}}`
+ rawToolUse = `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"commandExecution","id":"c1","command":"tcpdump -i any -c 5"}}}`
+ rawToolResult = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"commandExecution","id":"c1","status":"completed","aggregatedOutput":"5 packets captured"}}}`
+ legacyToolUse = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"exec_command_begin","call_id":"c1","command":"tcpdump -i any -c 5"}}}`
+ rawAnswer = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"agentMessage","id":"m2","text":"The retry loop is the cause."}}}`
+ rawSearchStart = `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"webSearch","id":"ws1","query":"codex release notes"}}}`
+ rawSearchEnd = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"webSearch","id":"ws1","query":"codex release notes"}}}`
+ legacyToolEnd = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"exec_command_end","call_id":"c1","output":"5 packets captured"}}}`
+ legacyFinal = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"agent_message","message":"The retry loop is the cause.","phase":"final_answer"}}}`
+ legacyMCPBegin = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"mcp_tool_call_begin","call_id":"mcp1","invocation":{"server":"docs","tool":"search"}}}}`
+ legacyMCPEnd = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"mcp_tool_call_end","call_id":"mcp1","invocation":{"server":"docs","tool":"search"}}}}`
+ legacyWebBegin = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"web_search_begin","call_id":"ws1"}}}`
+ legacyTurnB = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"task_started","turn_id":"turn-b"}}}`
+ legacyEndTurnA = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"exec_command_end","call_id":"bg-a","turn_id":"turn-a","output":"done"}}}`
+ legacyEndTurnB = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"exec_command_end","call_id":"bg-b","turn_id":"turn-b","output":"done"}}}`
+ rawPlanUpdate = `{"jsonrpc":"2.0","method":"turn/plan/updated","params":{"turnId":"t1","plan":[{"step":"Check logs","status":"in_progress"}]}}`
+ legacyPlan = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"plan_update","plan":[{"step":"Check logs","status":"in_progress"}]}}}`
+ rawSleepStart = `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"sleep","id":"sl1","durationMs":1000}}}`
+ rawSleepEnd = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"sleep","id":"sl1","durationMs":1000}}}`
+ rawPermsReq = `{"jsonrpc":"2.0","id":7,"method":"item/permissions/requestApproval","params":{"itemId":"p1","permissions":{}}}`
+ legacyAskUser = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"request_user_input","call_id":"q1","turn_id":"turn-b","questions":[]}}}`
+ legacyAskPerms = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"request_permissions","call_id":"p1","turn_id":"turn-b"}}}`
+ rawUserShell = `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"commandExecution","id":"u1","command":"ls","source":"userShell"}}}`
+ rawUserShellE = `{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"commandExecution","id":"u1","command":"ls","source":"userShell","aggregatedOutput":"a"}}}`
+ legacyUserSh = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"exec_command_begin","call_id":"u1","command":"ls","source":"user_shell"}}}`
+ legacyUserShE = `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"exec_command_end","call_id":"u1","source":"user_shell","output":"a"}}}`
narration = "Let me check the logs."
wantDeliverabl = "The retry loop is the cause."
)
@@ -1991,6 +2019,174 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
want: wantDeliverabl,
wantStreamed: []string{narration, wantDeliverabl, wantDeliverabl},
},
+ {
+ // The reported shape: phase-less narration, then the last event of
+ // the run is a tool call. The narration must not become the run's
+ // result.
+ name: "phase-less narration followed by a tool call yields no output",
+ protocol: "raw",
+ lines: []string{rawNarration, rawToolUse, rawToolResult},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "legacy narration followed by a tool call yields no output",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacyToolUse},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ // A real answer after the tool call is still the deliverable: the
+ // clearing only discards text the turn has since moved past.
+ name: "a message after the tool call is still the deliverable",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacyToolUse, legacySecond},
+ want: wantDeliverabl,
+ wantStreamed: []string{narration, wantDeliverabl},
+ },
+ {
+ // Codex reports a background command's end when the process exits,
+ // which can be after the answer the model wrote while it ran. The
+ // end of a call whose start was seen must not retract that answer.
+ name: "a started command ending after the answer keeps the answer",
+ protocol: "raw",
+ lines: []string{rawToolUse, rawAnswer, rawToolResult},
+ want: wantDeliverabl,
+ wantStreamed: []string{wantDeliverabl},
+ },
+ {
+ name: "a legacy started command ending after the answer keeps the answer",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacyToolUse, legacySecond, legacyToolEnd},
+ want: wantDeliverabl,
+ wantStreamed: []string{narration, wantDeliverabl},
+ },
+ {
+ // An end without an observed start is the only sign that a tool
+ // ran after the text, so it still clears.
+ name: "a tool end without its start still clears narration",
+ protocol: "raw",
+ lines: []string{rawNarration, rawToolResult},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ // Codex copies the phase onto the legacy event.
+ name: "a legacy labelled final answer survives later tool use",
+ protocol: "legacy",
+ lines: []string{legacyFinal, legacyToolUse, legacyToolEnd},
+ want: wantDeliverabl,
+ wantStreamed: []string{wantDeliverabl},
+ },
+ {
+ // Web search never reaches the transcript, but it is still a tool
+ // call after the narration.
+ name: "phase-less narration followed by a web search yields no output",
+ protocol: "raw",
+ lines: []string{rawNarration, rawSearchStart, rawSearchEnd},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "legacy narration followed by an MCP call yields no output",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacyMCPBegin, legacyMCPEnd},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "legacy narration followed by a web search yields no output",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacyWebBegin},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ // A background command from an earlier turn of the same session
+ // exits during this one. Its end names the earlier turn, so it is
+ // not tool activity here and must not retract this turn's answer.
+ name: "an earlier turn's command end keeps this turn's answer",
+ protocol: "legacy",
+ lines: []string{legacyTurnB, legacySecond, legacyEndTurnA},
+ want: wantDeliverabl,
+ wantStreamed: []string{wantDeliverabl},
+ },
+ {
+ name: "this turn's unpaired command end still clears narration",
+ protocol: "legacy",
+ lines: []string{legacyTurnB, legacyFirst, legacyEndTurnB},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ // update_plan reports only through turn/plan/updated.
+ name: "phase-less narration followed by a plan update yields no output",
+ protocol: "raw",
+ lines: []string{rawNarration, rawPlanUpdate},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "legacy narration followed by a plan update yields no output",
+ protocol: "legacy",
+ lines: []string{legacyFirst, legacyPlan},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "phase-less narration followed by a sleep yields no output",
+ protocol: "raw",
+ lines: []string{rawNarration, rawSleepStart, rawSleepEnd},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "phase-less narration followed by a permission request yields no output",
+ protocol: "raw",
+ lines: []string{rawNarration, rawPermsReq},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "legacy narration followed by a user-input request yields no output",
+ protocol: "legacy",
+ lines: []string{legacyTurnB, legacyFirst, legacyAskUser},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ name: "legacy narration followed by a permission request yields no output",
+ protocol: "legacy",
+ lines: []string{legacyTurnB, legacyFirst, legacyAskPerms},
+ want: "",
+ wantStreamed: []string{narration},
+ },
+ {
+ // A command the user ran is not the model calling a tool.
+ name: "a user shell command after the answer keeps the answer",
+ protocol: "raw",
+ lines: []string{rawAnswer, rawUserShell, rawUserShellE},
+ want: wantDeliverabl,
+ wantStreamed: []string{wantDeliverabl},
+ },
+ {
+ name: "a legacy user shell command after the answer keeps the answer",
+ protocol: "legacy",
+ lines: []string{legacySecond, legacyUserSh, legacyUserShE},
+ want: wantDeliverabl,
+ wantStreamed: []string{wantDeliverabl},
+ },
+ {
+ // An explicitly labelled final answer survives later tool use: the
+ // app-server said this is the deliverable, and a post-answer tool
+ // call (e.g. posting the comment itself) does not retract that.
+ name: "a labelled final answer survives later tool use",
+ protocol: "raw",
+ lines: []string{rawNarration, rawFinal, rawToolUse, rawToolResult},
+ want: wantDeliverabl,
+ wantStreamed: []string{narration, wantDeliverabl},
+ },
}
for _, tc := range cases {
@@ -2009,6 +2205,7 @@ func TestCodexDeliverableOutputExcludesNarration(t *testing.T) {
}
c.onAgentMessage = output.observeAgentMessage
c.onFinalAnswer = output.observeFinalAnswer
+ c.onToolActivity = output.observeToolActivity
for _, line := range tc.lines {
c.handleLine(line)
@@ -4340,8 +4537,11 @@ func TestCodexExecuteSemanticInactivityAllowsContinuousMessages(t *testing.T) {
if result.Status != "completed" {
t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
}
- if !strings.Contains(result.Output, "still working") {
- t.Fatalf("expected streamed text in output, got %q", result.Output)
+ // The message precedes a commandExecution, so it is narration and must not
+ // become the deliverable; the run still counts as progressed (which is what
+ // this test is about).
+ if result.Output != "" {
+ t.Fatalf("narration before a tool call became the output: %q", result.Output)
}
}
@@ -4481,6 +4681,92 @@ func TestCodexExecutePhaseLessCompletedMessageRemainsAuthoritative(t *testing.T)
}
}
+// TestCodexExecuteTrailingToolCallYieldsNoOutput replays the reported run end to
+// end: the gateway emits agent text with no phase label, the model's last action
+// is a tool call, and the turn then ends without any further message. The run
+// must complete with empty Result.Output so the server synthesizes no comment,
+// while the narration still reaches the transcript.
+func TestCodexExecuteTrailingToolCallYieldsNoOutput(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const narration = "Let me verify the permission facts for the tcpdump output path."
+
+ 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-trailing-tool"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-trailing-tool","turn":{"id":"turn-trailing-tool"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-trailing-tool","turnId":"turn-trailing-tool","item":{"type":"agentMessage","id":"msg-1","text":"`+narration+`"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"thr-trailing-tool","turnId":"turn-trailing-tool","item":{"type":"commandExecution","id":"cmd-1","command":"tcpdump -i any -c 5"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-trailing-tool","turnId":"turn-trailing-tool","item":{"type":"commandExecution","id":"cmd-1","status":"completed","aggregatedOutput":"5 packets captured"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-trailing-tool","turn":{"id":"turn-trailing-tool","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: text before a tool call is not a deliverable", result.Output)
+ }
+ var transcript []string
+ for _, msg := range messages {
+ if msg.Type == MessageText {
+ transcript = append(transcript, msg.Content)
+ }
+ }
+ if strings.Join(transcript, "") != narration {
+ t.Fatalf("transcript text = %q, want the narration preserved", transcript)
+ }
+}
+
+// TestCodexExecuteBackgroundCommandEndKeepsAnswer replays a background
+// command: Codex reports its end when the process exits, after the phase-less
+// answer the model wrote while it ran. The end of a call whose start was seen
+// is not a new tool call, so the answer stays the run's result.
+func TestCodexExecuteBackgroundCommandEndKeepsAnswer(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ const answer = "The capture finished; port 8080 is the only listener."
+
+ 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-bg"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-bg","turn":{"id":"turn-bg"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"thr-bg","turnId":"turn-bg","item":{"type":"commandExecution","id":"cmd-bg","command":"tcpdump -i any -c 5"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-bg","turnId":"turn-bg","item":{"type":"agentMessage","id":"msg-1","text":"`+answer+`"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-bg","turnId":"turn-bg","item":{"type":"commandExecution","id":"cmd-bg","status":"completed","aggregatedOutput":"5 packets captured"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-bg","turn":{"id":"turn-bg","status":"completed"}}}'`+"\n")
+
+ result, _ := 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 != answer {
+ t.Fatalf("Result.Output = %q, want the answer written before the background command ended", result.Output)
+ }
+}
+
// 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