Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(agent): share acpDeliverableTracker across ACP backends (MUL-5405) (#6044)
Bohan Jiang962d376fda59
diff --git a/server/pkg/agent/acp_deliverable.go b/server/pkg/agent/acp_deliverable.gonew file mode 100644index 0000000000..1949261285--- /dev/null+++ b/server/pkg/agent/acp_deliverable.go@@ -0,0 +1,68 @@+package agent++import (+ "strings"+ "sync"+)++// acpDeliverableTracker splits an ACP turn's text stream into the final+// user-facing answer and the complete transcript.+//+// Result.Output is "final user-facing output selected by the backend" — it+// becomes the channel reply and the auto-generated issue comment, so interim+// narration ("Let me check the logs first…") must not reach it (#6006). ACP+// runtimes emit narration and the final answer as the same AgentMessageChunk+// type, and a tool call is the only boundary they expose, so the deliverable is+// the text emitted after the latest tool call. That boundary is a heuristic+// until the runtimes mark the final answer explicitly.+//+// The full transcript stays available because provider-error detection must+// keep reading every chunk: adapters inject their terminal "API call failed+// after N retries" give-up message as an ordinary agent turn, which can land+// before a tool call and would be invisible in the deliverable alone.+//+// The zero value is ready to use. A tracker is safe for concurrent use:+// backends call observe from the ACP stdout reader goroutine while the session+// goroutine calls result.+type acpDeliverableTracker struct {+ mu sync.Mutex+ // full is every text chunk of the turn, in arrival order.+ full strings.Builder+ // deliverable is the text accumulated since the latest tool call.+ deliverable strings.Builder+ // lastTextBlock is the most recent non-empty text block a tool call+ // displaced; it is what a tool-terminated turn falls back to.+ lastTextBlock string+}++// observe records one streamed message. Backends pass every message they+// accepted for the current turn; message types other than text and tool use+// carry no deliverable signal and are ignored.+func (t *acpDeliverableTracker) observe(msg Message) {+ t.mu.Lock()+ defer t.mu.Unlock()+ switch msg.Type {+ case MessageText:+ t.full.WriteString(msg.Content)+ t.deliverable.WriteString(msg.Content)+ case MessageToolUse:+ if block := t.deliverable.String(); strings.TrimSpace(block) != "" {+ t.lastTextBlock = block+ }+ t.deliverable.Reset()+ }+}++// result returns the deliverable for Result.Output and the full text stream to+// scan for provider errors. A turn that ends on a tool call leaves no trailing+// text block, so the deliverable falls back to the latest non-empty one rather+// than delivering an empty reply.+func (t *acpDeliverableTracker) result() (deliverable, full string) {+ t.mu.Lock()+ defer t.mu.Unlock()+ deliverable = t.deliverable.String()+ if strings.TrimSpace(deliverable) == "" {+ deliverable = t.lastTextBlock+ }+ return deliverable, t.full.String()+}diff --git a/server/pkg/agent/acp_deliverable_test.go b/server/pkg/agent/acp_deliverable_test.gonew file mode 100644index 0000000000..1c2f796b8e--- /dev/null+++ b/server/pkg/agent/acp_deliverable_test.go@@ -0,0 +1,365 @@+package agent++import (+ "context"+ "log/slog"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++func TestACPDeliverableTracker(t *testing.T) {+ t.Parallel()++ text := func(content string) Message { return Message{Type: MessageText, Content: content} }+ toolUse := Message{Type: MessageToolUse, Tool: "read_file", CallID: "tc-1"}++ tests := []struct {+ name string+ messages []Message+ wantDeliverable string+ wantFull string+ }{+ {+ name: "a turn without tool calls delivers everything",+ messages: []Message{text("The answer "), text("is 42.")},+ wantDeliverable: "The answer is 42.",+ wantFull: "The answer is 42.",+ },+ {+ name: "narration before a tool call is excluded",+ messages: []Message{text("Let me read the file."), toolUse, text("The file is empty.")},+ wantDeliverable: "The file is empty.",+ wantFull: "Let me read the file.The file is empty.",+ },+ {+ name: "only the block after the last tool call survives",+ messages: []Message{+ text("First I check the logs."), toolUse,+ text("Now the config."), toolUse,+ text("Both look fine."),+ },+ wantDeliverable: "Both look fine.",+ wantFull: "First I check the logs.Now the config.Both look fine.",+ },+ {+ name: "a turn ending on a tool call falls back to the last text block",+ messages: []Message{text("Done. Posted the summary."), toolUse},+ wantDeliverable: "Done. Posted the summary.",+ wantFull: "Done. Posted the summary.",+ },+ {+ name: "the fallback is the newest displaced block",+ messages: []Message{+ text("Reading the file."), toolUse,+ text("Done. Posted the summary."), toolUse,+ },+ wantDeliverable: "Done. Posted the summary.",+ wantFull: "Reading the file.Done. Posted the summary.",+ },+ {+ name: "consecutive tool calls keep the fallback",+ messages: []Message{text("Done. Posted the summary."), toolUse, toolUse},+ wantDeliverable: "Done. Posted the summary.",+ wantFull: "Done. Posted the summary.",+ },+ {+ name: "whitespace after the last tool call falls back",+ messages: []Message{text("Done. Posted the summary."), toolUse, text("\n ")},+ wantDeliverable: "Done. Posted the summary.",+ wantFull: "Done. Posted the summary.\n ",+ },+ {+ name: "thinking and tool results carry no deliverable signal",+ messages: []Message{+ {Type: MessageThinking, Content: "the user wants the diagram"},+ text("The diagram shows the architecture."),+ {Type: MessageToolResult, CallID: "tc-1", Output: "<svg />", Status: "completed"},+ {Type: MessageStatus, Status: "running"},+ },+ wantDeliverable: "The diagram shows the architecture.",+ wantFull: "The diagram shows the architecture.",+ },+ {+ name: "a turn with no text at all delivers nothing",+ messages: []Message{toolUse},+ wantDeliverable: "",+ wantFull: "",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ var tracker acpDeliverableTracker+ for _, msg := range tt.messages {+ tracker.observe(msg)+ }+ deliverable, full := tracker.result()+ if deliverable != tt.wantDeliverable {+ t.Errorf("deliverable = %q, want %q", deliverable, tt.wantDeliverable)+ }+ if full != tt.wantFull {+ t.Errorf("full = %q, want %q", full, tt.wantFull)+ }+ })+ }+}++// TestACPDeliverableTrackerIsConcurrencySafe exercises the real access pattern:+// ACP backends call observe from the stdout reader goroutine while the session+// goroutine reads the result. Meaningful under -race.+func TestACPDeliverableTrackerIsConcurrencySafe(t *testing.T) {+ t.Parallel()++ const writers, chunksPerWriter = 4, 200+ var tracker acpDeliverableTracker+ var wg sync.WaitGroup++ for range writers {+ wg.Add(1)+ go func() {+ defer wg.Done()+ for range chunksPerWriter {+ tracker.observe(Message{Type: MessageText, Content: "x"})+ }+ }()+ }+ wg.Add(1)+ go func() {+ defer wg.Done()+ for range chunksPerWriter {+ tracker.observe(Message{Type: MessageToolUse, Tool: "read_file"})+ }+ }()+ wg.Add(1)+ go func() {+ defer wg.Done()+ for range chunksPerWriter {+ tracker.result()+ }+ }()+ wg.Wait()++ if _, full := tracker.result(); len(full) != writers*chunksPerWriter {+ t.Fatalf("full text length = %d, want %d — chunks were lost", len(full), writers*chunksPerWriter)+ }+}++// acpDeliverableCase describes one ACP backend for the shared boundary+// regression test: how New names it, what its executable is called, and which+// session-update dialect its runtime speaks.+type acpDeliverableCase struct {+ backend string+ binary string+ // notification is the JSON-RPC method the runtime pushes updates on.+ notification string+ // camelUpdates selects the CamelCase discriminator (`update.type:+ // "AgentMessageChunk"`) kiro and qoder emit, instead of the snake_case+ // `update.sessionUpdate` form hermes/kimi/traecli/grok emit.+ camelUpdates bool+}++// acpDeliverableCases covers every backend sharing acpDeliverableTracker.+var acpDeliverableCases = []acpDeliverableCase{+ {backend: "hermes", binary: "hermes", notification: "session/update"},+ {backend: "kimi", binary: "kimi", notification: "session/update"},+ {backend: "traecli", binary: "traecli", notification: "session/update"},+ {backend: "grok", binary: "grok", notification: "session/update"},+ {backend: "kiro", binary: "kiro-cli", notification: "session/notification", camelUpdates: true},+ {backend: "qoder", binary: "qodercli", notification: "session/notification", camelUpdates: true},+}++const (+ acpDeliverableNarration = "I will read the diagram first."+ acpDeliverableAnswerHead = "The diagram shows "+ acpDeliverableAnswerTail = "the service architecture."+ acpDeliverableAnswer = acpDeliverableAnswerHead + acpDeliverableAnswerTail+)++// fakeACPDeliverableScript returns a POSIX-sh ACP runtime that plays one turn+// in the shape that leaked process narration into channel replies (#6006):+// interim narration, a tool call, then the user-facing answer.+func fakeACPDeliverableScript(c acpDeliverableCase) string {+ notify := func(update string) string {+ return ` printf '{"jsonrpc":"2.0","method":"` + c.notification ++ `","params":{"sessionId":"ses_deliverable","update":` + update + `}}\n'`+ }+ discriminator := func(snake, camel string) string {+ if c.camelUpdates {+ return `"type":"` + camel + `"`+ }+ return `"sessionUpdate":"` + snake + `"`+ }+ chunk := func(text string) string {+ return `{` + discriminator("agent_message_chunk", "AgentMessageChunk") ++ `,"content":{"type":"text","text":"` + text + `"}}`+ }+ toolCall := func(withArgs bool) string {+ args := ""+ if withArgs {+ args = `,"parameters":{"path":"diagram.svg"}`+ }+ return `{` + discriminator("tool_call", "ToolCall") ++ `,"toolCallId":"tc-read","name":"read_file","status":"pending"` + args + `}`+ }+ toolResult := `{` + discriminator("tool_call_update", "ToolCallUpdate") ++ `,"toolCallId":"tc-read","name":"read_file","status":"completed","output":"<svg />"}`++ return `#!/bin/sh+# Fake ACP runtime shared by the deliverable-boundary regression tests. All+# three text chunks belong in the streamed transcript; only the post-tool-call+# text is the backend's deliverable Result.Output.+#+# ACP_PRE_TOOL_TEXT replaces the pre-tool text, ACP_TOOL_TERMINATED=1 ends the+# turn on the tool call, and ACP_DEFERRED_TOOL=1 withholds the tool arguments so+# the ACP transport defers MessageToolUse to tool completion instead of emitting+# it at the tool call.+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"cached_token","name":"Cached login"},{"id":"xai.api_key","name":"API key"}],"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"authenticate"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_deliverable"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ pre='` + acpDeliverableNarration + `'+ if [ -n "$ACP_PRE_TOOL_TEXT" ]; then+ pre=$ACP_PRE_TOOL_TEXT+ fi+` + notify(chunk("%s")) + ` "$pre"+ if [ "$ACP_DEFERRED_TOOL" = "1" ]; then+` + notify(toolCall(false)) + `+ else+` + notify(toolCall(true)) + `+ fi+` + notify(toolResult) + `+ if [ "$ACP_TOOL_TERMINATED" != "1" ]; then+` + notify(chunk(acpDeliverableAnswerHead)) + `+` + notify(chunk(acpDeliverableAnswerTail)) + `+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++func runACPDeliverableTurn(t *testing.T, c acpDeliverableCase, env map[string]string) (Result, []Message) {+ t.Helper()++ fakePath := filepath.Join(t.TempDir(), c.binary)+ writeTestExecutable(t, fakePath, []byte(fakeACPDeliverableScript(c)))++ backend, err := New(c.backend, Config{ExecutablePath: fakePath, Logger: slog.Default(), Env: env})+ if err != nil {+ t.Fatalf("new %s backend: %v", c.backend, err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "inspect the diagram", ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("execute %s: %v", c.backend, err)+ }++ var streamed []Message+ messagesDone := make(chan struct{})+ go func() {+ defer close(messagesDone)+ for msg := range session.Messages {+ streamed = append(streamed, msg)+ }+ }()++ result := <-session.Result+ <-messagesDone+ return result, streamed+}++// acpDeliverableEmissionPaths covers the two ways the ACP transport surfaces a+// tool call: immediately when the runtime pre-populates the arguments, and+// deferred to tool completion when it streams them. The deliverable boundary+// must hold on both.+var acpDeliverableEmissionPaths = []struct {+ name string+ env map[string]string+}{+ {name: "tool use emitted at start"},+ {name: "tool use deferred until completion", env: map[string]string{"ACP_DEFERRED_TOOL": "1"}},+}++// TestACPBackendsDeliverFinalAnswerWithoutNarration pins the boundary across+// every ACP backend: interim narration stays in the streamed transcript but+// must not reach Result.Output, which becomes the channel reply and the+// auto-generated issue comment (#6006, MUL-5394).+func TestACPBackendsDeliverFinalAnswerWithoutNarration(t *testing.T) {+ t.Parallel()++ for _, c := range acpDeliverableCases {+ for _, path := range acpDeliverableEmissionPaths {+ t.Run(c.backend+"/"+path.name, func(t *testing.T) {+ t.Parallel()++ result, streamed := runACPDeliverableTurn(t, c, path.env)+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed (error=%q output=%q)", result.Status, result.Error, result.Output)+ }+ if result.Output != acpDeliverableAnswer {+ t.Fatalf("Result.Output = %q, want the final answer %q", result.Output, acpDeliverableAnswer)+ }++ var text []string+ for _, msg := range streamed {+ if msg.Type == MessageText {+ text = append(text, msg.Content)+ }+ }+ want := acpDeliverableNarration + "|" + acpDeliverableAnswerHead + "|" + acpDeliverableAnswerTail+ if got := strings.Join(text, "|"); got != want {+ t.Fatalf("transcript text = %q, want narration and final answer %q", got, want)+ }+ })+ }+ }+}++// TestACPBackendsToolTerminatedTurnFallsBackToLatestTextBlock covers the turn+// that ends on a tool call — the agent answers and then posts it with a tool.+// There is no post-tool text, so the deliverable must fall back to the latest+// text block instead of replying with an empty string.+func TestACPBackendsToolTerminatedTurnFallsBackToLatestTextBlock(t *testing.T) {+ t.Parallel()++ const want = "Done. Posted the summary to the issue."++ for _, c := range acpDeliverableCases {+ for _, path := range acpDeliverableEmissionPaths {+ t.Run(c.backend+"/"+path.name, func(t *testing.T) {+ t.Parallel()++ env := map[string]string{+ "ACP_PRE_TOOL_TEXT": want,+ "ACP_TOOL_TERMINATED": "1",+ "ACP_DEFERRED_TOOL": path.env["ACP_DEFERRED_TOOL"],+ }+ result, _ := runACPDeliverableTurn(t, c, env)+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed (error=%q output=%q)", result.Status, result.Error, result.Output)+ }+ if result.Output != want {+ t.Fatalf("Result.Output = %q, want the fallback text block %q", result.Output, want)+ }+ })+ }+ }+}diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.goindex 39f7bff829..0199a1d614 100644--- a/server/pkg/agent/grok.go+++ b/server/pkg/agent/grok.go@@ -190,8 +190,10 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptiomsgStream := newGrokMessageStream(256)resCh := make(chan Result, 1)- var outputMu sync.Mutex- var output strings.Builder+ // Grok streams interim narration and the final answer as the same+ // agent_message_chunk type; the tracker keeps only the post-tool-call block+ // for Result.Output while retaining the full text for error detection.+ var deliverable acpDeliverableTrackervar streamingCurrentTurn atomic.BoolpromptDone := make(chan hermesPromptResult, 1)@@ -220,11 +222,7 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// kimi/traecli do so the UI sees consistent snake_case names.msg.Tool = kimiToolNameFromTitle(msg.Tool)}- if msg.Type == MessageText {- outputMu.Lock()- output.WriteString(msg.Content)- outputMu.Unlock()- }+ deliverable.observe(msg)msgStream.send(msg)},onPromptDone: func(result hermesPromptResult) {@@ -486,13 +484,13 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptiodrainCancel()streamingCurrentTurn.Store(false)- outputMu.Lock()- finalOutput := output.String()- outputMu.Unlock()+ finalOutput, providerErrorOutput := deliverable.result()// Promote completed→failed when stderr or the agent text stream show a- // terminal upstream-LLM failure (auth / rate-limit / HTTP 4xx).- finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)+ // terminal upstream-LLM failure (auth / rate-limit / HTTP 4xx). It reads+ // the full text stream, not the deliverable, so a give-up turn that+ // lands before a tool call stays visible.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)c.usageMu.Lock()u := c.usagediff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex c6658e459b..0b524ce77e 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -259,8 +259,10 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptmsgCh := make(chan Message, 256)resCh := make(chan Result, 1)- var outputMu sync.Mutex- var output strings.Builder+ // Hermes streams interim narration and the final answer as the same+ // agent_message_chunk type; the tracker keeps only the post-tool-call block+ // for Result.Output while retaining the full text for error detection.+ var deliverable acpDeliverableTracker// streamingCurrentTurn gates all session updates so that history// replay (Hermes sends full prior-turn transcripts on session/resume,// and may flush queued chunks before our session/prompt response@@ -289,11 +291,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptif !streamingCurrentTurn.Load() {return}- if msg.Type == MessageText {- outputMu.Lock()- output.WriteString(msg.Content)- outputMu.Unlock()- }+ deliverable.observe(msg)trySend(msgCh, msg)},onPromptDone: func(result hermesPromptResult) {@@ -586,9 +584,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}streamingCurrentTurn.Store(false)- outputMu.Lock()- finalOutput := output.String()- outputMu.Unlock()+ finalOutput, providerErrorOutput := deliverable.result()// Hermes reports stopReason=end_turn even when the upstream// LLM call ultimately fails (HTTP 429 rate-limit, expired@@ -598,7 +594,9 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// warning), the agent text stream contains the synthetic// "API call failed after N retries..." turn the adapter// injects on give-up, or there's no output to fall back on.- finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)+ // It reads the full text stream, not the deliverable, so a+ // give-up turn that lands before a tool call stays visible.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)// Build usage map.c.usageMu.Lock()diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.goindex 821935fb50..1266d15323 100644--- a/server/pkg/agent/kimi.go+++ b/server/pkg/agent/kimi.go@@ -7,7 +7,6 @@ import ("io""os/exec""strings"- "sync""time")@@ -111,8 +110,10 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptiomsgCh := make(chan Message, 256)resCh := make(chan Result, 1)- var outputMu sync.Mutex- var output strings.Builder+ // Kimi streams interim narration and the final answer as the same+ // agent_message_chunk type; the tracker keeps only the post-tool-call block+ // for Result.Output while retaining the full text for error detection.+ var deliverable acpDeliverableTrackerpromptDone := make(chan hermesPromptResult, 1)@@ -134,11 +135,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptioif msg.Type == MessageToolUse {msg.Tool = kimiToolNameFromTitle(msg.Tool)}- if msg.Type == MessageText {- outputMu.Lock()- output.WriteString(msg.Content)- outputMu.Unlock()- }+ deliverable.observe(msg)trySend(msgCh, msg)},onPromptDone: func(result hermesPromptResult) {@@ -366,17 +363,17 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// provider-error sniffer; see hermes.go for the failure mode.<-stderrDone- outputMu.Lock()- finalOutput := output.String()- outputMu.Unlock()+ finalOutput, providerErrorOutput := deliverable.result()// Promote completed→failed when stderr or the agent text// stream show a terminal upstream-LLM failure (HTTP 4xx /// rate-limit / expired token). See the helper docs for the// full signal set; the key safety property is that transient// per-attempt warnings followed by a successful retry stay- // "completed".- finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)+ // "completed". It reads the full text stream, not the+ // deliverable, so a give-up turn that lands before a tool call+ // stays visible.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)c.usageMu.Lock()u := c.usagediff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex b513a838d6..e2faac4873 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -104,8 +104,10 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiomsgCh := make(chan Message, 256)resCh := make(chan Result, 1)- var outputMu sync.Mutex- var output strings.Builder+ // Kiro streams interim narration and the final answer as the same+ // AgentMessageChunk type; the tracker keeps only the post-tool-call block+ // for Result.Output while retaining the full text for error detection.+ var deliverable acpDeliverableTrackervar streamingCurrentTurn atomic.Bool// Completion-preservation state for the -32603 close-handshake guard.//@@ -174,11 +176,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiofinishingMu.Unlock()}}- if msg.Type == MessageText {- outputMu.Lock()- output.WriteString(msg.Content)- outputMu.Unlock()- }+ deliverable.observe(msg)trySend(msgCh, msg)},onPromptDone: func(result hermesPromptResult) {@@ -445,17 +443,17 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// provider-error sniffer; see hermes.go for the failure mode.<-stderrDone- outputMu.Lock()- finalOutput := output.String()- outputMu.Unlock()+ finalOutput, providerErrorOutput := deliverable.result()// Promote completed→failed when stderr or the agent text// stream show a terminal upstream-LLM failure (HTTP 4xx /// rate-limit / expired token). See the helper docs for the// full signal set; the key safety property is that transient// per-attempt warnings followed by a successful retry stay- // "completed".- finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)+ // "completed". It reads the full text stream, not the+ // deliverable, so a give-up turn that lands before a tool call+ // stays visible.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)c.usageMu.Lock()u := c.usagediff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.goindex 032d9ad646..cd64c4e915 100644--- a/server/pkg/agent/qoder.go+++ b/server/pkg/agent/qoder.go@@ -141,15 +141,10 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOptimsgStream := newQoderMessageStream(256)resCh := make(chan Result, 1)- var outputMu sync.Mutex- // Result.Output is the final user-facing output selected by the backend.// Qoder emits interim narration and the final answer as the same ACP- // AgentMessageChunk type, with tool calls as the only reliable boundary.- // Keep the complete text for provider-error detection, while deliverable- // holds only the text block after the latest tool call. This boundary is a- // heuristic until Qoder exposes an explicit final-answer marker.- var fullOutput, deliverableOutput strings.Builder- var lastTextBlock string+ // AgentMessageChunk type; the tracker keeps only the post-tool-call block+ // for Result.Output while retaining the full text for error detection.+ var deliverable acpDeliverableTrackervar streamingCurrentTurn atomic.BoolpromptDone := make(chan hermesPromptResult, 1)@@ -169,18 +164,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOptiif msg.Type == MessageToolUse {msg.Tool = kimiToolNameFromTitle(msg.Tool)}- outputMu.Lock()- switch msg.Type {- case MessageText:- fullOutput.WriteString(msg.Content)- deliverableOutput.WriteString(msg.Content)- case MessageToolUse:- if block := deliverableOutput.String(); strings.TrimSpace(block) != "" {- lastTextBlock = block- }- deliverableOutput.Reset()- }- outputMu.Unlock()+ deliverable.observe(msg)msgStream.send(msg)},onPromptDone: func(result hermesPromptResult) {@@ -419,13 +403,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti// send and close so the late send is dropped instead of panicking.streamingCurrentTurn.Store(false)- outputMu.Lock()- finalOutput := deliverableOutput.String()- if strings.TrimSpace(finalOutput) == "" {- finalOutput = lastTextBlock- }- providerErrorOutput := fullOutput.String()- outputMu.Unlock()+ finalOutput, providerErrorOutput := deliverable.result()// Promote completed→failed when stderr or the agent text stream show a// terminal upstream-LLM failure (HTTP 4xx / rate-limit / expired token).diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.goindex 1fbd2c793f..eb1468d6f4 100644--- a/server/pkg/agent/traecli.go+++ b/server/pkg/agent/traecli.go@@ -158,8 +158,10 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOpmsgStream := newTraecliMessageStream(256)resCh := make(chan Result, 1)- var outputMu sync.Mutex- var output strings.Builder+ // Traecli streams interim narration and the final answer as the same+ // agent_message_chunk type; the tracker keeps only the post-tool-call block+ // for Result.Output while retaining the full text for error detection.+ var deliverable acpDeliverableTrackervar streamingCurrentTurn atomic.BoolpromptDone := make(chan hermesPromptResult, 1)@@ -179,11 +181,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOpif msg.Type == MessageToolUse {msg.Tool = kimiToolNameFromTitle(msg.Tool)}- if msg.Type == MessageText {- outputMu.Lock()- output.WriteString(msg.Content)- outputMu.Unlock()- }+ deliverable.observe(msg)msgStream.send(msg)},onPromptDone: func(result hermesPromptResult) {@@ -410,14 +408,13 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp// late send is dropped instead of panicking.streamingCurrentTurn.Store(false)- outputMu.Lock()- finalOutput := output.String()- outputMu.Unlock()+ finalOutput, providerErrorOutput := deliverable.result()// Promote completed→failed when stderr or the agent text stream show a// terminal upstream-LLM failure (HTTP 4xx / rate-limit / expired token).- // Mirrors hermes/kimi/kiro/qoder.- finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)+ // Mirrors hermes/kimi/kiro/qoder, and reads the full text stream so a+ // give-up turn that lands before a tool call stays visible.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)c.usageMu.Lock()u := c.usage