Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4824: fail closed on incomplete Claude-style result streams (#5522)
Multica Evecf1fc6467102
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex f038f47361..1fe4e1dfc6 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -285,6 +285,7 @@ type Daemon struct {type profileLaunchSpec struct {path string+ version stringfixedArgs []string}@@ -1082,7 +1083,7 @@ func (d *Daemon) findRuntime(id string) *Runtime {// args resolved for a custom runtime profile. Called from// registerRuntimesForWorkspace. Lazily initializes the map so test fixtures// that build a Daemon literal without seeding every map don't panic.-func (d *Daemon) recordProfileLaunch(profileID, path string, fixedArgs []string) {+func (d *Daemon) recordProfileLaunch(profileID, path, version string, fixedArgs []string) {if profileID == "" || path == "" {return}@@ -1093,6 +1094,7 @@ func (d *Daemon) recordProfileLaunch(profileID, path string, fixedArgs []string)}d.profileLaunchSpecs[profileID] = profileLaunchSpec{path: path,+ version: version,fixedArgs: append([]string(nil), fixedArgs...),}}@@ -1310,7 +1312,7 @@ func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string,if d.cfg.DeviceName != "" {displayName = fmt.Sprintf("%s (%s)", displayName, d.cfg.DeviceName)}- d.recordProfileLaunch(profile.ID, resolved, profile.FixedArgs)+ d.recordProfileLaunch(profile.ID, resolved, version, profile.FixedArgs)d.logger.Info("registering custom runtime profile","workspace_id", workspaceID, "profile_id", profile.ID,"protocol_family", profile.ProtocolFamily, "command_path", resolved)@@ -3756,6 +3758,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar resolvedVersion stringif customSpec, isCustom := d.customProfileLaunchForRuntime(task.RuntimeID); isCustom {entry.Path = customSpec.path+ resolvedVersion = customSpec.versionprofileFixedArgs = customSpec.fixedArgsok = trued.logger.Info("task uses custom runtime profile command",@@ -4179,6 +4182,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ilayerCustomEnvAndHermesHome(agentEnv, agentCustomEnv, env.HermesHome, d.logger)backend, err := agent.New(provider, agent.Config{ExecutablePath: entry.Path,+ CLIVersion: resolvedVersion,Env: agentEnv,Logger: d.logger,})diff --git a/server/internal/daemon/runtime_profile_test.go b/server/internal/daemon/runtime_profile_test.goindex 3ff9dbdfa3..d09d6b339e 100644--- a/server/internal/daemon/runtime_profile_test.go+++ b/server/internal/daemon/runtime_profile_test.go@@ -197,6 +197,9 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {if got.path != "/opt/bin/company-codex" {t.Errorf("profileLaunchSpecs[prof-1].path = %q, want /opt/bin/company-codex", got.path)}+ if got.version != "9.9.9" {+ t.Errorf("profileLaunchSpecs[prof-1].version = %q, want 9.9.9", got.version)+ }if strings.Join(got.fixedArgs, " ") != "--model composer-2.5" {t.Errorf("profileLaunchSpecs[prof-1].fixedArgs = %v, want [--model composer-2.5]", got.fixedArgs)}@@ -395,13 +398,13 @@ func stubProfilePathExecutable(t *testing.T, executable map[string]bool) {func TestCustomCommandPathForRuntime(t *testing.T) {d := freshDaemon("")d.profileLaunchSpecs = map[string]profileLaunchSpec{- "prof-1": {path: "/opt/bin/company-codex", fixedArgs: []string{"--model", "composer-2.5"}},+ "prof-1": {path: "/opt/bin/company-codex", version: "9.8.7", fixedArgs: []string{"--model", "composer-2.5"}},}// rt-custom is a custom-profile runtime; rt-builtin is a normal one.d.runtimeIndex["rt-custom"] = Runtime{ID: "rt-custom", Provider: "codex", ProfileID: "prof-1"}d.runtimeIndex["rt-builtin"] = Runtime{ID: "rt-builtin", Provider: "claude"}- if spec, ok := d.customProfileLaunchForRuntime("rt-custom"); !ok || spec.path != "/opt/bin/company-codex" || strings.Join(spec.fixedArgs, " ") != "--model composer-2.5" {+ if spec, ok := d.customProfileLaunchForRuntime("rt-custom"); !ok || spec.path != "/opt/bin/company-codex" || spec.version != "9.8.7" || strings.Join(spec.fixedArgs, " ") != "--model composer-2.5" {t.Errorf("custom runtime: got (%+v, %v), want profile launch spec", spec, ok)}if spec, ok := d.customProfileLaunchForRuntime("rt-builtin"); ok || spec.path != "" {diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.goindex 2c6bc22bd1..eb2d0ca2ee 100644--- a/server/internal/service/task_complete_race_test.go+++ b/server/internal/service/task_complete_race_test.go@@ -180,6 +180,9 @@ func TestTaskFailureClassifiers(t *testing.T) {{reason: "iteration_limit", wantType: "agent_output", wantResumeOK: false, wantRetry: false},{reason: "api_invalid_request", wantType: "agent_error", wantResumeOK: false, wantRetry: false},{reason: "agent_error", wantType: "agent_error", wantResumeOK: true, wantRetry: false},+ // Missing terminal result errors classify to agent_error.unknown. Keep+ // that deterministic upstream failure outside the auto-retry allowlist.+ {reason: "agent_error.unknown", wantType: "agent_error", wantResumeOK: true, wantRetry: false},}for _, tc := range cases {diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex e6bac24c71..49d84a1269 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -136,7 +136,7 @@ type TokenUsage struct {// Result is the final outcome after an agent session completes.type Result struct {Status string // "completed", "failed", "aborted", "timeout", "cancelled"- Output string // accumulated text output+ Output string // final user-facing output selected by the backendError string // error message if failedDurationMs int64SessionID string@@ -146,6 +146,7 @@ type Result struct {// Config configures a Backend instance.type Config struct {ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, kiro-cli, agy, qodercli, traecli, grok)+ CLIVersion string // detected version paired with ExecutablePath; observation only, never used to choose behaviorEnv map[string]string // extra environment variablesLogger *slog.Logger}diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex bbee94f09d..89de2d2682 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -136,12 +136,17 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}startTime := time.Now()- var output strings.Builder+ var lastAssistantText string+ var finalResultText string+ sawResult := false+ resultIsError := falsevar sessionID string- finalStatus := "completed"- var finalError stringsawAsyncLaunch := falseusage := make(map[string]TokenUsage)+ eventCount := 0+ invalidEventCount := 0+ assistantEventCount := 0+ toolUseCount := 0// Close stdout when the context is cancelled so scanner.Scan() unblocks.go func() {@@ -161,12 +166,23 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptvar msg claudeSDKMessageif err := json.Unmarshal([]byte(line), &msg); err != nil {+ invalidEventCount++continue}+ eventCount++switch msg.Type {case "assistant":- b.handleAssistant(msg, msgCh, &output, usage)+ 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 = ""+ }case "user":if b.handleUser(msg, msgCh) {sawAsyncLaunch = true@@ -177,18 +193,13 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})case "result":+ sawResult = true+ finalResultText = msg.ResultText+ resultIsError = msg.IsErrorsessionID = msg.SessionID- if msg.ResultText != "" {- output.Reset()- output.WriteString(msg.ResultText)- }if resultUsage := claudeResultUsage(msg, opts.Model); len(resultUsage) > 0 {usage = resultUsage}- if msg.IsError {- finalStatus = "failed"- finalError = msg.ResultText- }closeStdin()case "log":if msg.Log != nil {@@ -202,6 +213,13 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptb.handleControlRequest(msg, stdin)}}+ scanErr := scanner.Err()+ if scanErr != nil {+ // Scanner stopped consuming stdout. Close the pipe before Wait so a+ // child still writing a malformed/oversized event cannot deadlock on+ // the full OS pipe; the scanner error remains the primary failure.+ _ = stdout.Close()+ }closeStdin()@@ -213,27 +231,26 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// broken pipe, or been unblocked by the kill that ended cmd.writeErr := <-writeDone- switch {- case runCtx.Err() == context.DeadlineExceeded:- finalStatus = "timeout"- finalError = fmt.Sprintf("claude timed out after %s", timeout)- case runCtx.Err() == context.Canceled:- finalStatus = "aborted"- finalError = "execution cancelled"- case writeErr != nil && finalStatus == "completed" && sessionID == "":- // No result event landed and the prompt write failed — claude- // died before reading the prompt. Surface the write error; the- // stderr tail attached below carries the real reason.- finalStatus = "failed"- finalError = fmt.Sprintf("write claude input: %v", writeErr)- case exitErr != nil && finalStatus == "completed":- finalStatus = "failed"- finalError = fmt.Sprintf("claude exited with error: %v", exitErr)- }- if finalStatus == "completed" && sawAsyncLaunch {- finalStatus = "failed"- finalError = "claude launched an async background task; Multica-managed runs require foreground execution"+ completionGuardError := ""+ if sawAsyncLaunch {+ completionGuardError = "claude launched an async background task; Multica-managed runs require foreground execution"}+ finalStatus, finalOutput, finalError := finalizeStreamResult(+ "claude",+ timeout,+ runCtx.Err(),+ writeErr,+ exitErr,+ sessionID,+ streamTerminalState{+ lastAssistantText: lastAssistantText,+ finalResultText: finalResultText,+ sawResult: sawResult,+ resultIsError: resultIsError,+ scanErr: scanErr,+ },+ completionGuardError,+ )// cmd.Wait() has returned — os/exec's stderr copy goroutine has// observed every byte claude wrote to stderr before exiting, so@@ -244,6 +261,22 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptif finalError != "" {finalError = withAgentStderr(finalError, "claude", stderrTail)}+ logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{+ provider: "claude",+ cliVersion: b.cfg.CLIVersion,+ model: opts.Model,+ exitCode: streamProcessExitCode(exitErr),+ eventCount: eventCount,+ invalidEventCount: invalidEventCount,+ assistantEventCount: assistantEventCount,+ toolUseCount: toolUseCount,+ sawResult: sawResult,+ resultIsError: resultIsError,+ resultBytes: len(finalResultText),+ lastAssistantBytes: len(lastAssistantText),+ scannerError: scanErr != nil,+ anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",+ })b.cfg.Logger.Info("claude finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())@@ -257,7 +290,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptresCh <- Result{Status: finalStatus,- Output: output.String(),+ Output: finalOutput,Error: finalError,DurationMs: duration.Milliseconds(),SessionID: reportedSessionID,@@ -268,11 +301,13 @@ 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, output *strings.Builder, usage map[string]TokenUsage) {+func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage) (string, int) {var content claudeMessageContentif err := json.Unmarshal(msg.Message, &content); err != nil {- return+ return "", 0}+ var assistantText strings.Builder+ toolUseCount := 0// Accumulate token usage per model.if content.Usage != nil && content.Model != "" {@@ -288,7 +323,7 @@ func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message,switch block.Type {case "text":if block.Text != "" {- output.WriteString(block.Text)+ assistantText.WriteString(block.Text)trySend(ch, Message{Type: MessageText, Content: block.Text})}case "thinking":@@ -296,6 +331,7 @@ func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message,trySend(ch, Message{Type: MessageThinking, Content: block.Text})}case "tool_use":+ toolUseCount++var input map[string]anyif block.Input != nil {_ = json.Unmarshal(block.Input, &input)@@ -308,6 +344,7 @@ func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message,})}}+ return assistantText.String(), toolUseCount}func (b *claudeBackend) handleUser(msg claudeSDKMessage, ch chan<- Message) bool {@@ -542,8 +579,8 @@ func trySend(ch chan<- Message, msg Message) {select {case ch <- msg:default:- // Channel full — drop message. Final output is accumulated separately- // in Result.Output, so only streaming consumers are affected.+ // Channel full — drop message. Result.Output is finalized independently,+ // so only live transcript consumers are affected.}}diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.goindex a1c083f12b..7b0a263134 100644--- a/server/pkg/agent/claude_test.go+++ b/server/pkg/agent/claude_test.go@@ -19,7 +19,6 @@ func TestClaudeHandleAssistantText(t *testing.T) {b := &claudeBackend{cfg: Config{Logger: slog.Default()}}ch := make(chan Message, 10)- var output strings.Buildermsg := claudeSDKMessage{Type: "assistant",@@ -31,10 +30,13 @@ func TestClaudeHandleAssistantText(t *testing.T) {}),}- b.handleAssistant(msg, ch, &output, make(map[string]TokenUsage))+ output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))- if output.String() != "Hello world" {- t.Fatalf("expected output 'Hello world', got %q", output.String())+ if output != "Hello world" {+ t.Fatalf("expected output 'Hello world', got %q", output)+ }+ if tools != 0 {+ t.Fatalf("expected no tool uses, got %d", tools)}select {case m := <-ch:@@ -51,7 +53,6 @@ func TestClaudeHandleAssistantToolUse(t *testing.T) {b := &claudeBackend{cfg: Config{Logger: slog.Default()}}ch := make(chan Message, 10)- var output strings.Buildermsg := claudeSDKMessage{Type: "assistant",@@ -68,10 +69,13 @@ func TestClaudeHandleAssistantToolUse(t *testing.T) {}),}- b.handleAssistant(msg, ch, &output, make(map[string]TokenUsage))+ output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))- if output.String() != "" {- t.Fatalf("tool_use should not add to output, got %q", output.String())+ if output != "" {+ t.Fatalf("tool_use should not add to output, got %q", output)+ }+ if tools != 1 {+ t.Fatalf("expected one tool use, got %d", tools)}select {case m := <-ch:@@ -268,7 +272,6 @@ func TestClaudeHandleAssistantInvalidJSON(t *testing.T) {b := &claudeBackend{cfg: Config{Logger: slog.Default()}}ch := make(chan Message, 10)- var output strings.Buildermsg := claudeSDKMessage{Type: "assistant",@@ -276,10 +279,13 @@ func TestClaudeHandleAssistantInvalidJSON(t *testing.T) {}// Should not panic- b.handleAssistant(msg, ch, &output, make(map[string]TokenUsage))+ output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))- if output.String() != "" {- t.Fatalf("expected empty output for invalid JSON, got %q", output.String())+ if output != "" {+ t.Fatalf("expected empty output for invalid JSON, got %q", output)+ }+ if tools != 0 {+ t.Fatalf("expected no tool uses for invalid JSON, got %d", tools)}select {case m := <-ch:diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.goindex 876b03d8f5..c41892e841 100644--- a/server/pkg/agent/codebuddy.go+++ b/server/pkg/agent/codebuddy.go@@ -163,11 +163,16 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec}startTime := time.Now()- var output strings.Builder+ var lastAssistantText string+ var finalResultText string+ sawResult := false+ resultIsError := falsevar sessionID string- finalStatus := "completed"- var finalError stringusage := make(map[string]TokenUsage)+ eventCount := 0+ invalidEventCount := 0+ assistantEventCount := 0+ toolUseCount := 0// Close stdout when the context is cancelled so scanner.Scan() unblocks.go func() {@@ -187,12 +192,23 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Execvar msg codebuddySDKMessageif err := json.Unmarshal([]byte(line), &msg); err != nil {+ invalidEventCount++continue}+ eventCount++switch msg.Type {case "assistant":- b.handleAssistant(msg, msgCh, &output, usage)+ 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 = ""+ }case "user":b.handleUser(msg, msgCh)case "system":@@ -201,18 +217,13 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec}trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})case "result":+ sawResult = true+ finalResultText = msg.ResultText+ resultIsError = msg.IsErrorsessionID = msg.SessionID- if msg.ResultText != "" {- output.Reset()- output.WriteString(msg.ResultText)- }if resultUsage := codebuddyResultUsage(msg, opts.Model); len(resultUsage) > 0 {usage = resultUsage}- if msg.IsError {- finalStatus = "failed"- finalError = msg.ResultText- }closeStdin()case "log":if msg.Log != nil {@@ -226,6 +237,12 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Execb.handleControlRequest(msg, stdin)}}+ scanErr := scanner.Err()+ if scanErr != nil {+ // Stop a malformed/oversized writer from blocking cmd.Wait after the+ // scanner has stopped consuming stdout.+ _ = stdout.Close()+ }closeStdin()@@ -237,27 +254,42 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec// broken pipe, or been unblocked by the kill that ended cmd.writeErr := <-writeDone- switch {- case runCtx.Err() == context.DeadlineExceeded:- finalStatus = "timeout"- finalError = fmt.Sprintf("codebuddy timed out after %s", timeout)- case runCtx.Err() == context.Canceled:- finalStatus = "aborted"- finalError = "execution cancelled"- case writeErr != nil && finalStatus == "completed" && sessionID == "":- // No result event landed and the prompt write failed — codebuddy- // died before reading the prompt. Surface the write error; the- // stderr tail attached below carries the real reason.- finalStatus = "failed"- finalError = fmt.Sprintf("write codebuddy input: %v", writeErr)- case exitErr != nil && finalStatus == "completed":- finalStatus = "failed"- finalError = fmt.Sprintf("codebuddy exited with error: %v", exitErr)- }+ finalStatus, finalOutput, finalError := finalizeStreamResult(+ "codebuddy",+ timeout,+ runCtx.Err(),+ writeErr,+ exitErr,+ sessionID,+ streamTerminalState{+ lastAssistantText: lastAssistantText,+ finalResultText: finalResultText,+ sawResult: sawResult,+ resultIsError: resultIsError,+ scanErr: scanErr,+ },+ "",+ )if finalError != "" {finalError = withAgentStderr(finalError, "codebuddy", stderrBuf.Tail())}+ logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{+ provider: "codebuddy",+ cliVersion: b.cfg.CLIVersion,+ model: opts.Model,+ exitCode: streamProcessExitCode(exitErr),+ eventCount: eventCount,+ invalidEventCount: invalidEventCount,+ assistantEventCount: assistantEventCount,+ toolUseCount: toolUseCount,+ sawResult: sawResult,+ resultIsError: resultIsError,+ resultBytes: len(finalResultText),+ lastAssistantBytes: len(lastAssistantText),+ scannerError: scanErr != nil,+ anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",+ })b.cfg.Logger.Info("codebuddy finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())@@ -271,7 +303,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts ExecresCh <- Result{Status: finalStatus,- Output: output.String(),+ Output: finalOutput,Error: finalError,DurationMs: duration.Milliseconds(),SessionID: reportedSessionID,@@ -282,11 +314,13 @@ 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, output *strings.Builder, usage map[string]TokenUsage) {+func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- Message, usage map[string]TokenUsage) (string, int) {var content codebuddyMessageContentif err := json.Unmarshal(msg.Message, &content); err != nil {- return+ return "", 0}+ var assistantText strings.Builder+ toolUseCount := 0// Accumulate token usage per model.if content.Usage != nil && content.Model != "" {@@ -302,7 +336,7 @@ func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- Meswitch block.Type {case "text":if block.Text != "" {- output.WriteString(block.Text)+ assistantText.WriteString(block.Text)trySend(ch, Message{Type: MessageText, Content: block.Text})}case "thinking":@@ -310,6 +344,7 @@ func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- MetrySend(ch, Message{Type: MessageThinking, Content: block.Text})}case "tool_use":+ toolUseCount++var input map[string]anyif block.Input != nil {_ = json.Unmarshal(block.Input, &input)@@ -322,6 +357,7 @@ func (b *codebuddyBackend) handleAssistant(msg codebuddySDKMessage, ch chan<- Me})}}+ return assistantText.String(), toolUseCount}func (b *codebuddyBackend) handleUser(msg codebuddySDKMessage, ch chan<- Message) {@@ -418,7 +454,7 @@ type codebuddySDKMessage struct {// result fieldsResultText string `json:"result,omitempty"`- IsError bool `json:"is_error,omitempty"`+ IsError bool `json:"is_error,omitempty"`DurationMs float64 `json:"duration_ms,omitempty"`NumTurns int `json:"num_turns,omitempty"`Usage *codebuddyUsage `json:"usage,omitempty"`diff --git a/server/pkg/agent/codebuddy_test.go b/server/pkg/agent/codebuddy_test.goindex e3fccfc22a..a8aeac93ae 100644--- a/server/pkg/agent/codebuddy_test.go+++ b/server/pkg/agent/codebuddy_test.go@@ -319,7 +319,6 @@ func TestCodebuddyHandleAssistantText(t *testing.T) {b := &codebuddyBackend{cfg: Config{Logger: slog.Default()}}ch := make(chan Message, 10)- var output strings.Buildermsg := codebuddySDKMessage{Type: "assistant",@@ -331,10 +330,13 @@ func TestCodebuddyHandleAssistantText(t *testing.T) {}),}- b.handleAssistant(msg, ch, &output, make(map[string]TokenUsage))+ output, tools := b.handleAssistant(msg, ch, make(map[string]TokenUsage))- if output.String() != "codebuddy says hi" {- t.Fatalf("expected output 'codebuddy says hi', got %q", output.String())+ if output != "codebuddy says hi" {+ t.Fatalf("expected output 'codebuddy says hi', got %q", output)+ }+ if tools != 0 {+ t.Fatalf("expected no tool uses, got %d", tools)}select {case m := <-ch:@@ -374,11 +376,11 @@ Options:}checks := map[string]string{"gpt-5.5": "openai",- "gemini-3.1-pro": "google",- "glm-5.1-ioa": "zhipu",- "minimax-m2.7-ioa": "minimax",- "kimi-k2.6-ioa": "kimi",- "hy3-preview-ioa": "hunyuan",+ "gemini-3.1-pro": "google",+ "glm-5.1-ioa": "zhipu",+ "minimax-m2.7-ioa": "minimax",+ "kimi-k2.6-ioa": "kimi",+ "hy3-preview-ioa": "hunyuan","deepseek-v3-2-volc-ioa": "deepseek",}for id, want := range checks {diff --git a/server/pkg/agent/stream_json_final_output_test.go b/server/pkg/agent/stream_json_final_output_test.gonew file mode 100644index 0000000000..134723fda8--- /dev/null+++ b/server/pkg/agent/stream_json_final_output_test.go@@ -0,0 +1,239 @@+package agent++import (+ "bytes"+ "context"+ "log/slog"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++func TestFinalizeStreamResultEmptySuccessWithoutAssistantUsesSafeNotice(t *testing.T) {+ t.Parallel()++ status, output, errMsg := finalizeStreamResult(+ "claude",+ time.Second,+ nil,+ nil,+ nil,+ "session-1",+ streamTerminalState{sawResult: true},+ "",+ )+ if status != "completed" || output != emptySuccessfulStreamResult || errMsg != "" {+ t.Fatalf("finalizeStreamResult() = (%q, %q, %q), want completed safe notice", status, output, errMsg)+ }+}++func TestFinalizeStreamResultPreservesErrorResultWhenContextEnds(t *testing.T) {+ t.Parallel()++ for _, runErr := range []error{context.DeadlineExceeded, context.Canceled} {+ status, output, errMsg := finalizeStreamResult(+ "claude",+ time.Second,+ runErr,+ nil,+ nil,+ "session-1",+ streamTerminalState{+ finalResultText: "provider rejected the request",+ sawResult: true,+ resultIsError: true,+ },+ "",+ )+ if status != "failed" || output != "" || errMsg != "provider rejected the request" {+ t.Errorf("runErr=%v: finalizeStreamResult() = (%q, %q, %q), want failed provider error", runErr, status, output, errMsg)+ }+ }+}++func TestStreamProtocolObservationDoesNotLogContent(t *testing.T) {+ t.Parallel()++ const (+ assistantSecret = "FIRST-TURN PRIVATE NARRATION"+ resultSecret = "FINAL PRIVATE RESULT"+ baseURLSecret = "https://provider.example/private"+ )+ var buf bytes.Buffer+ logger := slog.New(slog.NewTextHandler(&buf, nil))+ logStreamProtocolObservation(logger, streamProtocolObservation{+ provider: "claude",+ cliVersion: "2.1.5",+ model: "glm-4.6",+ exitCode: 0,+ eventCount: 7,+ invalidEventCount: 1,+ assistantEventCount: 2,+ toolUseCount: 1,+ sawResult: true,+ resultBytes: len(resultSecret),+ lastAssistantBytes: len(assistantSecret),+ anthropicBaseURLConfigured: true,+ })++ got := buf.String()+ for _, required := range []string{+ "provider=claude",+ "cli_version=2.1.5",+ "model=glm-4.6",+ "exit_code=0",+ "event_count=7",+ "saw_result=true",+ "result_bytes=20",+ "anthropic_base_url_configured=true",+ } {+ if !strings.Contains(got, required) {+ t.Errorf("observation log %q does not contain %q", got, required)+ }+ }+ for _, forbidden := range []string{assistantSecret, resultSecret, baseURLSecret} {+ if strings.Contains(got, forbidden) {+ t.Errorf("observation log leaked %q: %q", forbidden, got)+ }+ }+}++func TestStreamJSONBackendsFinalOutputBoundaries(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixtures are POSIX-only")+ }++ const multiTurnStream = `printf '%s\n' '{"type":"system","session_id":"sess-boundary"}'+printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"text","text":"FIRST-TURN NARRATION"}]}}'+printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"tool_use","id":"tool-1","name":"Read","input":{"path":"README.md"}}]}}'+printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"TOOL TRACE"}]}}'+printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"text","text":"LAST ASSISTANT ANSWER"}]}}'+`+ const toolLastStream = `printf '%s\n' '{"type":"system","session_id":"sess-boundary"}'+printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"text","text":"PRE-TOOL NARRATION"}]}}'+printf '%s\n' '{"type":"assistant","message":{"role":"assistant","model":"test-model","content":[{"type":"text","text":"I WILL USE A TOOL"},{"type":"tool_use","id":"tool-1","name":"Read","input":{"path":"README.md"}}]}}'+printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"TOOL TRACE"}]}}'+`++ tests := []struct {+ name string+ scriptBody string+ wantStatus string+ wantOutput string+ wantError string+ forbiddenOutput []string+ }{+ {+ name: "non-empty result is authoritative",+ scriptBody: multiTurnStream + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-boundary","result":"AUTHORITATIVE RESULT"}'` + "\n",+ wantStatus: "completed",+ wantOutput: "AUTHORITATIVE RESULT",+ forbiddenOutput: []string{+ "FIRST-TURN NARRATION",+ "TOOL TRACE",+ "LAST ASSISTANT ANSWER",+ },+ },+ {+ name: "empty successful result uses only last assistant message",+ scriptBody: multiTurnStream + `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",+ },+ },+ {+ name: "empty successful result after tool-using turn uses safe notice",+ scriptBody: toolLastStream + `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-boundary","result":""}'` + "\n",+ wantStatus: "completed",+ wantOutput: emptySuccessfulStreamResult,+ forbiddenOutput: []string{+ "PRE-TOOL NARRATION",+ "I WILL USE A TOOL",+ "TOOL TRACE",+ },+ },+ {+ name: "clean exit without result fails closed",+ scriptBody: multiTurnStream,+ wantStatus: "failed",+ wantOutput: "",+ wantError: "stream ended without terminal result",+ forbiddenOutput: []string{+ "FIRST-TURN NARRATION",+ "TOOL TRACE",+ "LAST ASSISTANT ANSWER",+ },+ },+ {+ name: "scanner error fails closed",+ // The production scanner caps a single event at 10 MiB. A larger+ // token produces bufio.ErrTooLong while the child still exits 0.+ scriptBody: `dd if=/dev/zero bs=1048576 count=11 2>/dev/null | tr '\000' x; printf '\n'` + "\n",+ wantStatus: "failed",+ wantOutput: "",+ wantError: "stdout read error",+ },+ }++ for _, provider := range []string{"claude", "codebuddy"} {+ provider := provider+ for _, tt := range tests {+ tt := tt+ t.Run(provider+"/"+tt.name, func(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), provider)+ script := "#!/bin/sh\nIFS= read -r _\n" + tt.scriptBody+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New(provider, Config{+ ExecutablePath: fakePath,+ Env: map[string]string{"IS_SANDBOX": "1"},+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("New(%s): %v", provider, err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "test prompt", ExecOptions{Timeout: 10 * time.Second})+ if err != nil {+ t.Fatalf("Execute(%s): %v", provider, err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != tt.wantStatus {+ t.Fatalf("status = %q, want %q (error=%q, output=%q)", result.Status, tt.wantStatus, result.Error, result.Output)+ }+ if result.Output != tt.wantOutput {+ t.Fatalf("output = %q, want %q", result.Output, tt.wantOutput)+ }+ if tt.wantError != "" && !strings.Contains(result.Error, tt.wantError) {+ t.Fatalf("error = %q, want substring %q", result.Error, tt.wantError)+ }+ for _, forbidden := range tt.forbiddenOutput {+ if strings.Contains(result.Output, forbidden) {+ t.Fatalf("output leaked %q: %q", forbidden, result.Output)+ }+ }+ case <-ctx.Done():+ t.Fatalf("timed out waiting for %s result: %v", provider, ctx.Err())+ }+ })+ }+ }+}diff --git a/server/pkg/agent/stream_json_result.go b/server/pkg/agent/stream_json_result.gonew file mode 100644index 0000000000..e4e35d2426--- /dev/null+++ b/server/pkg/agent/stream_json_result.go@@ -0,0 +1,138 @@+package agent++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os/exec"+ "time"+)++const emptySuccessfulStreamResult = "The agent completed without a final response."++// streamTerminalState keeps the user-facing final answer separate from the+// streamed assistant turns. Assistant messages are still emitted through the+// Session.Messages channel for live progress/transcript storage, but only a+// terminal result (or the last complete assistant message after an explicitly+// successful empty result) may become Result.Output.+type streamTerminalState struct {+ lastAssistantText string+ finalResultText string+ sawResult bool+ resultIsError bool+ scanErr error+}++// finalizeStreamResult applies the shared fail-closed terminal contract used by+// Claude Code and CodeBuddy. A clean process exit is not proof that the+// 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.+func finalizeStreamResult(+ provider string,+ timeout time.Duration,+ runErr error,+ writeErr error,+ exitErr error,+ sessionID string,+ state streamTerminalState,+ completionGuardError string,+) (status, output, errMsg string) {+ status = "completed"+ if state.resultIsError {+ status = "failed"+ errMsg = state.finalResultText+ if errMsg == "" {+ errMsg = provider + " returned an error result without details"+ }+ }++ switch {+ case status == "completed" && errors.Is(runErr, context.DeadlineExceeded):+ status = "timeout"+ errMsg = fmt.Sprintf("%s timed out after %s", provider, timeout)+ case status == "completed" && errors.Is(runErr, context.Canceled):+ status = "aborted"+ errMsg = "execution cancelled"+ case state.scanErr != nil && status == "completed":+ status = "failed"+ errMsg = fmt.Sprintf("%s stdout read error: %v", provider, state.scanErr)+ case writeErr != nil && status == "completed" && sessionID == "":+ status = "failed"+ errMsg = fmt.Sprintf("write %s input: %v", provider, writeErr)+ case exitErr != nil && status == "completed":+ status = "failed"+ errMsg = fmt.Sprintf("%s exited with error: %v", provider, exitErr)+ case !state.sawResult && status == "completed":+ status = "failed"+ errMsg = provider + " stream ended without terminal result"+ }++ if status == "completed" && completionGuardError != "" {+ status = "failed"+ errMsg = completionGuardError+ }++ if status != "completed" {+ return status, "", errMsg+ }+ if state.finalResultText != "" {+ return status, state.finalResultText, ""+ }+ if state.lastAssistantText != "" {+ return status, state.lastAssistantText, ""+ }+ return status, emptySuccessfulStreamResult, ""+}++type streamProtocolObservation struct {+ provider string+ cliVersion string+ model string+ exitCode int+ eventCount int+ invalidEventCount int+ assistantEventCount int+ toolUseCount int+ sawResult bool+ resultIsError bool+ resultBytes int+ lastAssistantBytes int+ scannerError bool+ anthropicBaseURLConfigured bool+}++// logStreamProtocolObservation records only protocol metadata. It deliberately+// excludes assistant/result text, tool input/output, the configured base URL,+// and environment values so diagnosing a missing terminal event cannot leak the+// task transcript or provider credentials into daemon logs.+func logStreamProtocolObservation(logger *slog.Logger, obs streamProtocolObservation) {+ logger.Info("agent stream protocol summary",+ "provider", obs.provider,+ "cli_version", obs.cliVersion,+ "model", obs.model,+ "exit_code", obs.exitCode,+ "event_count", obs.eventCount,+ "invalid_event_count", obs.invalidEventCount,+ "assistant_event_count", obs.assistantEventCount,+ "tool_use_count", obs.toolUseCount,+ "saw_result", obs.sawResult,+ "result_is_error", obs.resultIsError,+ "result_bytes", obs.resultBytes,+ "last_assistant_bytes", obs.lastAssistantBytes,+ "scanner_error", obs.scannerError,+ "anthropic_base_url_configured", obs.anthropicBaseURLConfigured,+ )+}++func streamProcessExitCode(err error) int {+ if err == nil {+ return 0+ }+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ return exitErr.ExitCode()+ }+ return -1+}