Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5785 fix(agent): return an empty output when a stream-json run has no final text (#6557)
Bohan Jiang3eff25401dba
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex 99399d0fb2..2d8bc390ca 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -182,6 +182,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptinvalidEventCount := 0assistantEventCount := 0toolUseCount := 0+ unreadableAssistantCount := 0// On cancellation / timeout, terminate claude (and every MCP server and// tool subprocess it spawned) BEFORE unblocking the scanner. EOF stdin@@ -233,15 +234,12 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptswitch msg.Type {case "assistant":assistantEventCount++- assistantText, tools := b.handleAssistant(msg, msgCh, usage)- toolUseCount += tools- if tools == 0 {- lastAssistantText = assistantText- } else {- // A turn that invokes a tool is intermediate even when it also- // contains narration. Do not use it as an empty-result fallback.- lastAssistantText = ""+ turn := b.handleAssistant(msg, msgCh, usage)+ toolUseCount += turn.toolUses+ if !turn.understood {+ unreadableAssistantCount++}+ lastAssistantText = turn.resolveFallback(lastAssistantText)case "user":if b.handleUser(msg, msgCh) {sawAsyncLaunch = true@@ -337,6 +335,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptresultBytes: len(finalResultText),lastAssistantBytes: len(lastAssistantText),scannerError: scanErr != nil,+ unreadableAssistantCount: unreadableAssistantCount,anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",})@@ -367,11 +366,14 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptreturn &Session{Messages: msgCh, Result: resCh}, nil}-func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage) (string, int) {+func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage) assistantTurn {var content claudeMessageContentif err := json.Unmarshal(msg.Message, &content); err != nil {- return "", 0+ // Unreadable body: understood stays false so the caller drops any+ // fallback rather than let an older turn stand in for this one.+ return assistantTurn{}}+ turn := assistantTurn{understood: true}var assistantText strings.BuildertoolUseCount := 0@@ -408,9 +410,17 @@ func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message,CallID: block.ID,Input: input,})+ default:+ // A block type we do not render may be carrying the model's answer+ // in a shape we cannot read, so we must not claim this turn was+ // silent. Recognising a new no-text block is a deliberate one-line+ // addition here, not an accident of falling through.+ turn.understood = false}}- return assistantText.String(), toolUseCount+ turn.text = assistantText.String()+ turn.toolUses = toolUseCount+ return turn}func (b *claudeBackend) handleUser(msg claudeSDKMessage, ch chan<- Message) bool {diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.goindex bd9288f9d0..21ae86c4dc 100644--- a/server/pkg/agent/claude_test.go+++ b/server/pkg/agent/claude_test.go@@ -30,7 +30,8 @@ func TestClaudeHandleAssistantText(t *testing.T) {}),}- output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ turn := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ output, tools := turn.text, turn.toolUsesif output != "Hello world" {t.Fatalf("expected output 'Hello world', got %q", output)@@ -69,7 +70,8 @@ func TestClaudeHandleAssistantToolUse(t *testing.T) {}),}- output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ turn := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ output, tools := turn.text, turn.toolUsesif output != "" {t.Fatalf("tool_use should not add to output, got %q", output)@@ -279,7 +281,8 @@ func TestClaudeHandleAssistantInvalidJSON(t *testing.T) {}// Should not panic- output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ turn := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ output, tools := turn.text, turn.toolUsesif output != "" {t.Fatalf("expected empty output for invalid JSON, got %q", output)diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.goindex af39a8c9d1..240118d2bb 100644--- a/server/pkg/agent/codebuddy.go+++ b/server/pkg/agent/codebuddy.go@@ -187,6 +187,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecinvalidEventCount := 0assistantEventCount := 0toolUseCount := 0+ unreadableAssistantCount := 0// Close stdout when the context is cancelled so scanner.Scan() unblocks.go func() {@@ -213,15 +214,12 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Execswitch msg.Type {case "assistant":assistantEventCount++- assistantText, tools := b.handleAssistant(msg, msgCh, usage)- toolUseCount += tools- if tools == 0 {- lastAssistantText = assistantText- } else {- // A turn that invokes a tool is intermediate even when it also- // contains narration. Do not use it as an empty-result fallback.- lastAssistantText = ""+ turn := b.handleAssistant(msg, msgCh, usage)+ toolUseCount += turn.toolUses+ if !turn.understood {+ unreadableAssistantCount++}+ lastAssistantText = turn.resolveFallback(lastAssistantText)case "user":b.handleUser(msg, msgCh)case "system":@@ -301,6 +299,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecresultBytes: len(finalResultText),lastAssistantBytes: len(lastAssistantText),scannerError: scanErr != nil,+ unreadableAssistantCount: unreadableAssistantCount,anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",})@@ -329,11 +328,14 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Execreturn &Session{Messages: msgCh, Result: resCh}, nil}-func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- Message, usage map[string]TokenUsage) (string, int) {+func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- Message, usage map[string]TokenUsage) assistantTurn {var content codebuddyMessageContentif err := json.Unmarshal(msg.Message, &content); err != nil {- return "", 0+ // Unreadable body: understood stays false so the caller drops any+ // fallback rather than let an older turn stand in for this one.+ return assistantTurn{}}+ turn := assistantTurn{understood: true}var assistantText strings.BuildertoolUseCount := 0@@ -370,9 +372,17 @@ func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- MeCallID: block.ID,Input: input,})+ default:+ // A block type we do not render may be carrying the model's answer+ // in a shape we cannot read, so we must not claim this turn was+ // silent. Recognising a new no-text block is a deliberate one-line+ // addition here, not an accident of falling through.+ turn.understood = false}}- return assistantText.String(), toolUseCount+ turn.text = assistantText.String()+ turn.toolUses = toolUseCount+ return turn}func (b *codebuddyBackend) handleUser(msg codebuddySDKMessage, ch chan<- Message) {diff --git a/server/pkg/agent/codebuddy_test.go b/server/pkg/agent/codebuddy_test.goindex d6497ca4d8..bc2a4888cd 100644--- a/server/pkg/agent/codebuddy_test.go+++ b/server/pkg/agent/codebuddy_test.go@@ -362,7 +362,8 @@ func TestCodebuddyHandleAssistantText(t *testing.T) {}),}- output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ turn := b.handleAssistant(msg, ch, make(map[string]TokenUsage))+ output, tools := turn.text, turn.toolUsesif output != "codebuddy says hi" {t.Fatalf("expected output 'codebuddy says hi', got %q", output)diff --git a/server/pkg/agent/qwen.go b/server/pkg/agent/qwen.goindex 18634a5242..963edc2e93 100644--- a/server/pkg/agent/qwen.go+++ b/server/pkg/agent/qwen.go@@ -177,6 +177,7 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptiotoolUseCount: state.toolUseCount, sawResult: state.sawResult, resultIsError: state.resultIsError,resultBytes: len(state.finalResultText), lastAssistantBytes: len(state.lastAssistantText),scannerError: scanErr != nil, lastEventType: state.lastEventType,+ unreadableAssistantCount: state.unreadableAssistantCount,})b.cfg.Logger.Info("qwen finished", "pid", cmd.Process.Pid, "status", status, "duration", duration.Round(time.Millisecond).String())resCh <- Result{@@ -228,6 +229,7 @@ type qwenStreamState struct {sawResult, resultIsError boolusage map[string]TokenUsageeventCount, invalidEventCount, assistantEventCount, toolUseCount int+ unreadableAssistantCount int}func handleQwenEvent(event qwenStreamEvent, ch chan<- Message, state *qwenStreamState) {@@ -242,16 +244,15 @@ func handleQwenEvent(event qwenStreamEvent, ch chan<- Message, state *qwenStreamtrySend(ch, Message{Type: MessageStatus, Status: "running", SessionID: state.sessionID})case "assistant":state.assistantEventCount++- text, tools, model := handleQwenAssistant(event.Message, ch, state.usage)+ turn, model := handleQwenAssistant(event.Message, ch, state.usage)if model != "" {state.model = model}- state.toolUseCount += tools- if tools == 0 && text != "" {- state.lastAssistantText = text- } else if tools > 0 {- state.lastAssistantText = ""+ state.toolUseCount += turn.toolUses+ if !turn.understood {+ state.unreadableAssistantCount++}+ state.lastAssistantText = turn.resolveFallback(state.lastAssistantText)case "user":handleQwenUser(event.Message, ch)case "result":@@ -275,11 +276,14 @@ func handleQwenEvent(event qwenStreamEvent, ch chan<- Message, state *qwenStream}}-func handleQwenAssistant(raw json.RawMessage, ch chan<- Message, usage map[string]TokenUsage) (string, int, string) {+func handleQwenAssistant(raw json.RawMessage, ch chan<- Message, usage map[string]TokenUsage) (assistantTurn, string) {var message qwenMessageif json.Unmarshal(raw, &message) != nil {- return "", 0, ""+ // Unreadable body: understood stays false so the caller drops any+ // fallback rather than let an older turn stand in for this one.+ return assistantTurn{}, ""}+ turn := assistantTurn{understood: true}if message.Usage != nil && message.Model != "" {usage[message.Model] = qwenTokenUsage(message.Usage)}@@ -303,9 +307,17 @@ func handleQwenAssistant(raw json.RawMessage, ch chan<- Message, usage map[strin_ = json.Unmarshal(block.Input, &input)}trySend(ch, Message{Type: MessageToolUse, Tool: block.Name, CallID: block.ID, Input: input})+ default:+ // A block type we do not render may be carrying the model's answer+ // in a shape we cannot read, so we must not claim this turn was+ // silent. Recognising a new no-text block is a deliberate one-line+ // addition here, not an accident of falling through.+ turn.understood = false}}- return text.String(), tools, message.Model+ turn.text = text.String()+ turn.toolUses = tools+ return turn, message.Model}func handleQwenUser(raw json.RawMessage, ch chan<- Message) {diff --git a/server/pkg/agent/stream_json_final_output_test.go b/server/pkg/agent/stream_json_final_output_test.goindex c395f5e557..3a5580b24f 100644--- a/server/pkg/agent/stream_json_final_output_test.go+++ b/server/pkg/agent/stream_json_final_output_test.go@@ -12,7 +12,11 @@ import ("time")-func TestFinalizeStreamResultEmptySuccessWithoutAssistantUsesSafeNotice(t *testing.T) {+// A successful run that produced no deliverable text must report an EMPTY+// output, never a placeholder sentence. Empty is what the issue / direct-chat /+// channel delivery paths each branch on to pick their own no-response behavior;+// any non-empty prose here defeats all three at once (GH #6462).+func TestFinalizeStreamResultEmptySuccessWithoutAssistantReturnsEmptyOutput(t *testing.T) {t.Parallel()status, output, errMsg := finalizeStreamResult(@@ -25,8 +29,52 @@ func TestFinalizeStreamResultEmptySuccessWithoutAssistantUsesSafeNotice(t *testistreamTerminalState{sawResult: true},"",)- if status != "completed" || output != emptySuccessfulStreamResult || errMsg != "" {- t.Fatalf("finalizeStreamResult() = (%q, %q, %q), want completed safe notice", status, output, errMsg)+ if status != "completed" || output != "" || errMsg != "" {+ t.Fatalf("finalizeStreamResult() = (%q, %q, %q), want completed with empty output", status, output, errMsg)+ }+}++// resolveFallback is the single policy every stream-json backend applies per+// assistant event, so pin all four outcomes here rather than only through the+// per-backend stream fixtures.+func TestAssistantTurnResolveFallback(t *testing.T) {+ t.Parallel()++ const prior = "AN ANSWER THE MODEL ALREADY GAVE"+ tests := []struct {+ name string+ turn assistantTurn+ want string+ }{+ {+ name: "text-only turn becomes the fallback",+ turn: assistantTurn{text: "NEW ANSWER", understood: true},+ want: "NEW ANSWER",+ },+ {+ name: "tool-using turn is intermediate and clears it",+ turn: assistantTurn{text: "I WILL USE A TOOL", toolUses: 1, understood: true},+ want: "",+ },+ {+ name: "understood silent turn leaves it alone",+ turn: assistantTurn{understood: true},+ want: prior,+ },+ {+ name: "unreadable turn clears it",+ turn: assistantTurn{understood: false},+ want: "",+ },+ }+ for _, tt := range tests {+ tt := tt+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ if got := tt.turn.resolveFallback(prior); got != tt.want {+ t.Fatalf("resolveFallback(%q) = %q, want %q", prior, got, tt.want)+ }+ })}}@@ -150,16 +198,58 @@ printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_},},{- name: "empty successful result after tool-using turn uses safe notice",+ name: "empty successful result after tool-using turn returns empty output",scriptBody: toolLastStream + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-boundary","result":""}'` + "\n",wantStatus: "completed",- wantOutput: emptySuccessfulStreamResult,+ wantOutput: "",forbiddenOutput: []string{"PRE-TOOL NARRATION","I WILL USE A TOOL","TOOL TRACE",},},+ {+ // A thinking-only trailing event carries neither an answer nor an+ // intermediacy signal, so it must not discard the answer the model+ // already delivered. Regression for the overwrite that turned a+ // complete reply into a no-response turn.+ name: "text-less trailing assistant event preserves the last answer",+ scriptBody: multiTurnStream + `printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"thinking","text":"SILENT DELIBERATION"}]}}'` + "\n" + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-boundary","result":""}'` + "\n",+ wantStatus: "completed",+ wantOutput: "LAST ASSISTANT ANSWER",+ forbiddenOutput: []string{+ "FIRST-TURN NARRATION",+ "TOOL TRACE",+ "SILENT DELIBERATION",+ },+ },+ {+ // An assistant event whose body does not match the expected shape+ // is unreadable, not silent: the model may have answered inside it.+ // The earlier narration must NOT be promoted to the final answer.+ name: "unparseable trailing assistant event drops the fallback",+ scriptBody: multiTurnStream + `printf '%s\n' '{"type":"assistant","message":"NOT AN OBJECT"}'` + "\n" + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-boundary","result":""}'` + "\n",+ wantStatus: "completed",+ wantOutput: "",+ forbiddenOutput: []string{+ "FIRST-TURN NARRATION",+ "TOOL TRACE",+ "LAST ASSISTANT ANSWER",+ },+ },+ {+ // Same rule for a content block type we do not render: we cannot+ // claim the turn was silent, so the fallback must not survive it.+ name: "unknown content block drops the fallback",+ scriptBody: multiTurnStream + `printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"server_tool_use","id":"st-1","name":"web_search"}]}}'` + "\n" + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-boundary","result":""}'` + "\n",+ wantStatus: "completed",+ wantOutput: "",+ forbiddenOutput: []string{+ "FIRST-TURN NARRATION",+ "TOOL TRACE",+ "LAST ASSISTANT ANSWER",+ },+ },{name: "clean exit without result fails closed",scriptBody: multiTurnStream,diff --git a/server/pkg/agent/stream_json_result.go b/server/pkg/agent/stream_json_result.goindex 65e42e54fb..b7a3b6be5e 100644--- a/server/pkg/agent/stream_json_result.go+++ b/server/pkg/agent/stream_json_result.go@@ -9,7 +9,42 @@ import ("time")-const emptySuccessfulStreamResult = "The agent completed without a final response."+// assistantTurn is the classified outcome of one assistant stream event.+//+// The stream-json backends parse different wire shapes but share one question+// per event: may a fallback answer captured earlier in the run survive it?+type assistantTurn struct {+ text string+ toolUses int+ // understood is false when the event's message body failed to parse, or+ // carried a content block type the backend does not handle. In both cases+ // the backend cannot tell whether the model delivered its answer inside+ // that event, so an earlier fallback must not outlive it.+ understood bool+}++// resolveFallback returns the empty-result fallback after this turn, given the+// fallback held before it. It is the single place the three stream-json+// backends encode which turns may leave an answer behind.+func (t assistantTurn) resolveFallback(prior string) string {+ switch {+ case t.toolUses > 0 || !t.understood:+ // A turn that invokes a tool is intermediate even when it also+ // contains narration. An unreadable turn tells us nothing at all —+ // the model may have answered in a shape we failed to parse. Neither+ // may leave a stale answer behind for the terminal result to adopt:+ // that is how pre-tool narration would reach a user as the final+ // answer (#6006), which the fail-closed contract below exists to stop.+ return ""+ case t.text != "":+ return t.text+ default:+ // Understood, text-less and tool-less — a thinking-only turn. It+ // carries neither an answer nor an intermediacy signal, so it must+ // leave an answer the model already delivered untouched.+ return prior+ }+}// streamTerminalState keeps the user-facing final answer separate from the// streamed assistant turns. Assistant messages are still emitted through the@@ -40,6 +75,17 @@ type streamTerminalState struct {// stream-json protocol completed: success requires a result event. Failed runs// always return an empty output so upstream issue/chat fallbacks can never// mistake a partial transcript for a final answer.+//+// A SUCCESSFUL run with no deliverable text returns an empty output for the same+// reason. Empty is the platform's signal for "this turn produced no final text",+// and every delivery surface already owns a decision keyed on it: an issue task+// skips the synthesized fallback comment, a direct chat writes a localized+// no_response outcome, and a Slack/Lark channel drops the turn rather than push+// a placeholder outward. Returning prose here instead makes the output non-empty+// and silently defeats all three at once — that is how an English sentinel+// reached a Lark thread (GH #6462). Which words a user sees, and in which+// language, belongs to each delivery surface; the stream parser only reports+// whether text exists.func finalizeStreamResult(provider string,timeout time.Duration,@@ -112,10 +158,7 @@ func finalizeStreamResult(if state.finalResultText != "" {return status, state.finalResultText, ""}- if state.lastAssistantText != "" {- return status, state.lastAssistantText, ""- }- return status, emptySuccessfulStreamResult, ""+ return status, state.lastAssistantText, ""}type streamProtocolObservation struct {@@ -149,6 +192,16 @@ type streamProtocolObservation struct {unhandledEventTypeCount intunhandledEventTypes stringunhandledSubtypeCount int+ // unreadableAssistantCount reports assistant events whose message body did+ // not parse, or that carried a content block type the backend does not+ // handle. Unlike unhandledEventTypeCount (a TOP-LEVEL event type we skip),+ // this counts events we accepted and then could not fully read.+ //+ // Non-zero means the run dropped its empty-result fallback defensively, so+ // a task that ended with no final text may have had an answer we could not+ // see. It is the first number to check when a known-good agent starts+ // returning empty outputs after a CLI upgrade.+ unreadableAssistantCount int}// logStreamProtocolObservation records only protocol metadata. It deliberately@@ -174,6 +227,7 @@ func logStreamProtocolObservation(logger *slog.Logger, obs streamProtocolObserva"unhandled_event_type_count", obs.unhandledEventTypeCount,"unhandled_event_types", obs.unhandledEventTypes,"unhandled_subtype_count", obs.unhandledSubtypeCount,+ "unreadable_assistant_count", obs.unreadableAssistantCount,"anthropic_base_url_configured", obs.anthropicBaseURLConfigured,)}