Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): fail opencode runs whose stream ends without a terminal signal (#5238)
Tran Quang6455d390e25d
diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex d30eb939f3..cca771ce34 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -227,6 +227,11 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO} else if exitErr != nil && scanResult.status == "completed" {scanResult.status = "failed"scanResult.errMsg = fmt.Sprintf("opencode exited with error: %v", exitErr)+ } else if exitErr != nil && scanResult.noTerminalSignal {+ // Status is already "failed" from the terminal-signal guard; append+ // the process exit detail so a mid-step crash still surfaces the+ // signal / exit code that killed it.+ scanResult.errMsg = fmt.Sprintf("%s; opencode exited with error: %v", scanResult.errMsg, exitErr)}b.cfg.Logger.Info("opencode finished", "pid", cmd.Process.Pid, "status", scanResult.status, "duration", duration.Round(time.Millisecond).String())@@ -260,11 +265,12 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO// eventResult holds the accumulated state from processing the event stream.type eventResult struct {- status string- errMsg string- output string- sessionID string- usage TokenUsage // accumulated token usage across all steps+ status string+ errMsg string+ output string+ sessionID string+ usage TokenUsage // accumulated token usage across all steps+ noTerminalSignal bool // guard fired: stream reached EOF before a step or required continuation completed}// processEvents reads JSON lines from r, dispatches events to ch, and returns@@ -276,6 +282,26 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventResfinalStatus := "completed"var finalError string+ // Track step bracketing so a stream that ends mid-step is not mistaken for a+ // clean completion. OpenCode's JSON stream has no terminal result event+ // (unlike Claude's type:"result"), so "no error seen" is not proof the run+ // finished. opencode emits tool_use only on terminal states (completed or+ // error), so a dangling tool call implies an unclosed step — step bracketing+ // is the positive terminal signal. Recovered tool errors (state.status ==+ // "error") are normal in healthy runs and must not affect status.+ //+ // Step bracketing alone is not enough: step_finish carries a reason+ // (FinishReason: "stop", "tool-calls", …), and a run that still has tool+ // results to feed back normally closes its step with reason "tool-calls"+ // before the next step_start. Some providers return "stop" despite emitting+ // tool calls, though, and OpenCode deliberately continues those runs when a+ // non-provider-executed tool result must be fed back to the model. Track both+ // signals so EOF in either continuation gap fails closed. A missing reason+ // retains the older step-bracketing behavior for protocol compatibility.+ openStep := false // between a step_start and its step_finish+ stepHasContinuationTool := false // current step has a local tool result OpenCode must feed back+ awaitingContinuation := false // the last step_finish still required another step+scanner := bufio.NewScanner(r)scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024)@@ -299,11 +325,21 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventResb.handleTextEvent(event, ch, &output)case "tool_use":b.handleToolUseEvent(event, ch)+ if event.Part.Metadata == nil || !event.Part.Metadata.ProviderExecuted {+ stepHasContinuationTool = true+ }case "error":b.handleErrorEvent(event, ch, &finalStatus, &finalError)case "step_start":+ openStep = true+ stepHasContinuationTool = false+ awaitingContinuation = falsetrySend(ch, Message{Type: MessageStatus, Status: "running"})case "step_finish":+ openStep = false+ awaitingContinuation = event.Part.Reason == "tool-calls" ||+ (event.Part.Reason != "" && stepHasContinuationTool)+ stepHasContinuationTool = false// Accumulate token usage from step_finish events.if t := event.Part.Tokens; t != nil {usage.InputTokens += t.Input@@ -325,12 +361,30 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes}}+ // Require a positive terminal signal. A clean EOF while a step is still+ // open — or right after a step that finished with reason "tool-calls",+ // whose continuation step never started — means the run did not finish:+ // its provider stream died and `opencode run` exited without emitting an+ // error event. Fail closed on that structural evidence rather than+ // reporting a false-green completion.+ noTerminalSignal := false+ if finalStatus == "completed" && (openStep || awaitingContinuation) {+ finalStatus = "failed"+ if openStep {+ finalError = "opencode stream ended without a terminal signal (step still open at EOF)"+ } else {+ finalError = "opencode stream ended without a terminal signal (last step required a continuation that never started)"+ }+ noTerminalSignal = true+ }+return eventResult{- status: finalStatus,- errMsg: finalError,- output: output.String(),- sessionID: sessionID,- usage: usage,+ status: finalStatus,+ errMsg: finalError,+ output: output.String(),+ sessionID: sessionID,+ usage: usage,+ noTerminalSignal: noTerminalSignal,}}@@ -490,9 +544,20 @@ type opencodeEventPart struct {Tool string `json:"tool,omitempty"`CallID string `json:"callID,omitempty"`State *opencodeToolState `json:"state,omitempty"`+ // OpenCode excludes provider-executed tools when deciding whether a tool+ // result requires another model step.+ Metadata *opencodePartMetadata `json:"metadata,omitempty"`// step_finish token usageTokens *opencodeTokens `json:"tokens,omitempty"`++ // step_finish reason (FinishReason: "stop", "tool-calls", …). Absent on+ // older opencode versions whose step-finish parts predate the field.+ Reason string `json:"reason,omitempty"`+}++type opencodePartMetadata struct {+ ProviderExecuted bool `json:"providerExecuted,omitempty"`}// opencodeTokens represents token usage in a step_finish event.diff --git a/server/pkg/agent/opencode_test.go b/server/pkg/agent/opencode_test.goindex daa543ef00..47dc0cfb08 100644--- a/server/pkg/agent/opencode_test.go+++ b/server/pkg/agent/opencode_test.go@@ -715,6 +715,275 @@ func TestOpencodeProcessEventsErrorDoesNotRevertToCompleted(t *testing.T) {close(ch)}+func TestOpencodeProcessEventsStreamEndsMidStep(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // Regression for production run B: the provider stream died right after a+ // mid-step planning message. opencode reaches a clean EOF and exits 0 with+ // the step still open (no step_finish, no error event), which previously+ // reported "completed" — a false-green with all work lost.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_midstep","part":{"type":"step-start"}}`,+ `{"type":"text","timestamp":1001,"sessionID":"ses_midstep","part":{"type":"text","text":"Let me plan the work..."}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "failed" {+ t.Errorf("status: got %q, want %q", result.status, "failed")+ }+ if !strings.Contains(result.errMsg, "terminal signal") {+ t.Errorf("errMsg: got %q, want it to mention the missing terminal signal", result.errMsg)+ }+ // Text emitted before the stream died must still be captured.+ if result.output != "Let me plan the work..." {+ t.Errorf("output: got %q", result.output)+ }++ close(ch)+}++func TestOpencodeProcessEventsStreamEndsAfterToolBeforeStepFinish(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // Regression for production run A: the stream died after a tool ran but+ // before the step closed. opencode emits tool_use only on terminal states+ // (here completed), so unfinished work manifests as an unclosed step, not a+ // pending tool — the open step at EOF is what fails the run.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_tool","part":{"type":"step-start"}}`,+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_tool","part":{"type":"tool","tool":"bash","callID":"call_1","state":{"status":"completed","input":{"command":"go test ./..."},"output":"ok\n"}}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "failed" {+ t.Errorf("status: got %q, want %q", result.status, "failed")+ }+ if !strings.Contains(result.errMsg, "terminal signal") {+ t.Errorf("errMsg: got %q, want it to mention the missing terminal signal", result.errMsg)+ }++ close(ch)+}++func TestOpencodeProcessEventsMultiStepHappyPath(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // A full tool loop as it appears on the real wire (live-probed against+ // opencode 1.17.16): the tool step closes with reason "tool-calls", the+ // continuation step opens and closes with the final reason "stop". Must+ // stay "completed" — "stop" is the run-level terminal signal.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_multi","part":{"type":"step-start"}}`,+ `{"type":"text","timestamp":1001,"sessionID":"ses_multi","part":{"type":"text","text":"step one"}}`,+ `{"type":"tool_use","timestamp":1002,"sessionID":"ses_multi","part":{"type":"tool","tool":"bash","callID":"call_1","state":{"status":"completed","input":{"command":"echo ok"},"output":"ok\n"}}}`,+ `{"type":"step_finish","timestamp":1003,"sessionID":"ses_multi","part":{"type":"step-finish","reason":"tool-calls"}}`,+ `{"type":"step_start","timestamp":1004,"sessionID":"ses_multi","part":{"type":"step-start"}}`,+ `{"type":"text","timestamp":1005,"sessionID":"ses_multi","part":{"type":"text","text":" step two"}}`,+ `{"type":"step_finish","timestamp":1006,"sessionID":"ses_multi","part":{"type":"step-finish","reason":"stop"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "completed" {+ t.Errorf("status: got %q, want %q", result.status, "completed")+ }+ if result.output != "step one step two" {+ t.Errorf("output: got %q", result.output)+ }+ if result.errMsg != "" {+ t.Errorf("errMsg: got %q, want empty", result.errMsg)+ }++ close(ch)+}++func TestOpencodeProcessEventsStreamEndsAfterToolCallsStepFinish(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // A step_finish with reason "tool-calls" is not a run-level terminal+ // signal: tool results still have to be fed back in a continuation step.+ // If the stream dies in the gap between that finish and the next+ // step_start, the run did not complete — even though no step is open.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_toolcalls","part":{"type":"step-start"}}`,+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_toolcalls","part":{"type":"tool","tool":"bash","callID":"call_1","state":{"status":"completed","input":{"command":"go test ./..."},"output":"ok\n"}}}`,+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_toolcalls","part":{"type":"step-finish","reason":"tool-calls"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "failed" {+ t.Errorf("status: got %q, want %q", result.status, "failed")+ }+ if !strings.Contains(result.errMsg, "terminal signal") {+ t.Errorf("errMsg: got %q, want it to mention the missing terminal signal", result.errMsg)+ }+ if !result.noTerminalSignal {+ t.Error("noTerminalSignal: got false, want true")+ }++ close(ch)+}++func TestOpencodeProcessEventsStreamEndsAfterToolWithStopFinish(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // Some providers return reason "stop" even when the assistant step contains+ // tool calls. OpenCode still continues the run so it can feed the tool result+ // back to the model. EOF before that continuation step is therefore not a+ // successful run-level terminal signal.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_stop_tool","part":{"type":"step-start"}}`,+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_stop_tool","part":{"type":"tool","tool":"bash","callID":"call_1","state":{"status":"completed","input":{"command":"go test ./..."},"output":"ok\n"}}}`,+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_stop_tool","part":{"type":"step-finish","reason":"stop"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "failed" {+ t.Errorf("status: got %q, want %q", result.status, "failed")+ }+ if !strings.Contains(result.errMsg, "terminal signal") {+ t.Errorf("errMsg: got %q, want it to mention the missing terminal signal", result.errMsg)+ }+ if !result.noTerminalSignal {+ t.Error("noTerminalSignal: got false, want true")+ }++ close(ch)+}++func TestOpencodeProcessEventsToolWithStopFinishThenContinuation(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // The provider-specific "stop" quirk must not false-fail a healthy run once+ // OpenCode starts the continuation step and reaches a real terminal finish.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_stop_continue","part":{"type":"step-start"}}`,+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_stop_continue","part":{"type":"tool","tool":"bash","callID":"call_1","state":{"status":"completed","input":{"command":"echo ok"},"output":"ok\n"}}}`,+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_stop_continue","part":{"type":"step-finish","reason":"stop"}}`,+ `{"type":"step_start","timestamp":1003,"sessionID":"ses_stop_continue","part":{"type":"step-start"}}`,+ `{"type":"text","timestamp":1004,"sessionID":"ses_stop_continue","part":{"type":"text","text":"done"}}`,+ `{"type":"step_finish","timestamp":1005,"sessionID":"ses_stop_continue","part":{"type":"step-finish","reason":"stop"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "completed" {+ t.Errorf("status: got %q, want %q", result.status, "completed")+ }+ if result.errMsg != "" {+ t.Errorf("errMsg: got %q, want empty", result.errMsg)+ }++ close(ch)+}++func TestOpencodeProcessEventsProviderExecutedToolWithStopFinish(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // Provider-executed tools do not require OpenCode to feed a local tool+ // result back to the model, so a "stop" finish remains terminal.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_provider_tool","part":{"type":"step-start"}}`,+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_provider_tool","part":{"type":"tool","tool":"web_search","callID":"call_1","metadata":{"providerExecuted":true},"state":{"status":"completed","input":{"query":"weather"},"output":"sunny"}}}`,+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_provider_tool","part":{"type":"step-finish","reason":"stop"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "completed" {+ t.Errorf("status: got %q, want %q", result.status, "completed")+ }+ if result.errMsg != "" {+ t.Errorf("errMsg: got %q, want empty", result.errMsg)+ }++ close(ch)+}++func TestOpencodeProcessEventsStepFinishWithoutReasonBackcompat(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // Older opencode versions emit step-finish parts without a reason field.+ // A missing (or unknown) reason must be treated as terminal so healthy+ // runs on old protocols are not mass-failed; only an explicit+ // "tool-calls" keeps the run non-terminal.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_noreason","part":{"type":"step-start"}}`,+ `{"type":"text","timestamp":1001,"sessionID":"ses_noreason","part":{"type":"text","text":"legacy run"}}`,+ `{"type":"step_finish","timestamp":1002,"sessionID":"ses_noreason","part":{"type":"step-finish"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "completed" {+ t.Errorf("status: got %q, want %q", result.status, "completed")+ }+ if result.errMsg != "" {+ t.Errorf("errMsg: got %q, want empty", result.errMsg)+ }++ close(ch)+}++func TestOpencodeProcessEventsToolErrorThenCleanFinish(t *testing.T) {+ t.Parallel()++ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 256)++ // A recovered tool error is normal in a healthy run: opencode emits tool_use+ // only on terminal states, and a failed tool arrives with state.status=="error"+ // (real wire shape from `opencode run --format json`). The run continues and+ // closes every step with step_finish, so status must stay "completed". The+ // earlier pending-tool heuristic recorded the error tool's callID, never+ // drained it, and wrongly reported this healthy run as failed.+ lines := strings.Join([]string{+ `{"type":"step_start","timestamp":1000,"sessionID":"ses_toolerr","part":{"type":"step-start"}}`,+ `{"type":"tool_use","timestamp":1001,"sessionID":"ses_toolerr","part":{"type":"tool","tool":"read","callID":"functions.read:1","state":{"status":"error","input":{"filePath":"/nonexistent-path-xyz/also-missing.md"},"error":"File not found: /nonexistent-path-xyz/also-missing.md"}}}`,+ `{"type":"tool_use","timestamp":1002,"sessionID":"ses_toolerr","part":{"type":"tool","tool":"bash","callID":"functions.bash:0","state":{"status":"completed","input":{"command":"echo hi"},"output":"hi\n"}}}`,+ `{"type":"step_finish","timestamp":1003,"sessionID":"ses_toolerr","part":{"type":"step-finish"}}`,+ }, "\n")++ result := b.processEvents(strings.NewReader(lines), ch)++ if result.status != "completed" {+ t.Errorf("status: got %q, want %q (recovered tool error must not fail a healthy run)", result.status, "completed")+ }+ if result.errMsg != "" {+ t.Errorf("errMsg: got %q, want empty", result.errMsg)+ }++ close(ch)+}+// ── Windows native-binary resolution tests ──// fakeStat returns a statFn that reports any path in `present` as existing@@ -1181,6 +1450,118 @@ func TestOpencodeBackendBlocksDirOverride(t *testing.T) {}}+// fakeOpencodeMidToolScript impersonates an `opencode run` whose provider+// stream dies mid-step: it prints a step_start and a terminal-error tool_use,+// then exits 0 on a clean EOF with no step_finish and no error event. This is+// the false-green shape from production — the recovered tool error does not+// rescue the run; the unclosed step is what fails it.+func fakeOpencodeMidToolScript() string {+ return `#!/bin/sh+printf '{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}\n'+printf '{"type":"tool_use","timestamp":2,"sessionID":"ses_fake","part":{"type":"tool","tool":"read","callID":"functions.read:1","state":{"status":"error","input":{"filePath":"/nope.md"},"error":"File not found"}}}\n'+exit 0+`+}++// TestOpencodeBackendFailsOnStreamEndingMidTool proves the terminal-signal+// guard over the full clean-EOF/exit-0 path, not just the scanner loop: a run+// whose stream ends with an open step must surface as Result.Status == "failed"+// even though opencode exited 0 with no error event and its last tool merely+// reported a recovered error.+func TestOpencodeBackendFailsOnStreamEndingMidTool(t *testing.T) {+ t.Parallel()++ tempDir := t.TempDir()+ fakePath := filepath.Join(tempDir, "opencode")+ writeTestExecutable(t, fakePath, []byte(fakeOpencodeMidToolScript()))++ backend, err := New("opencode", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("new opencode backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ if result.Status != "failed" {+ t.Fatalf("result status = %q, error = %q; want failed", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "terminal signal") {+ t.Errorf("result error = %q, want it to mention the missing terminal signal", result.Error)+ }+}++// fakeOpencodeStepThenExit1Script impersonates an `opencode run` that crashes+// mid-step: it opens a step, then the process itself dies nonzero with no+// step_finish and no error event.+func fakeOpencodeStepThenExit1Script() string {+ return `#!/bin/sh+printf '{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}\n'+exit 1+`+}++// TestOpencodeBackendAppendsExitDetailOnMidStepCrash pins the second fix: when+// the terminal-signal guard has already failed the run AND the process exited+// nonzero, the exit detail is appended so the crash signal / exit code is not+// lost — the errMsg carries both the missing-terminal-signal reason and the+// process exit status.+func TestOpencodeBackendAppendsExitDetailOnMidStepCrash(t *testing.T) {+ t.Parallel()++ tempDir := t.TempDir()+ fakePath := filepath.Join(tempDir, "opencode")+ writeTestExecutable(t, fakePath, []byte(fakeOpencodeStepThenExit1Script()))++ backend, err := New("opencode", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("new opencode backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ if result.Status != "failed" {+ t.Fatalf("result status = %q, error = %q; want failed", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "terminal signal") {+ t.Errorf("result error = %q, want it to mention the missing terminal signal", result.Error)+ }+ if !strings.Contains(result.Error, "exit status 1") {+ t.Errorf("result error = %q, want it to include the process exit status", result.Error)+ }+}+func equalStringSlice(a, b []string) bool {if len(a) != len(b) {return false