Skip to content

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

Go

MUL-5631: fix(openclaw): finish at the result boundary when the CLI does not exit (#6276)

VvV547fcca06913
diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.go
index 5ba51adeae..837b8241fa 100644
--- a/server/pkg/agent/openclaw.go
+++ b/server/pkg/agent/openclaw.go
@@ -5,6 +5,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -77,7 +78,23 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
cmd := exec.CommandContext(runCtx, execPath, args...)
hideAgentWindow(cmd)
b.cfg.Logger.Info("agent command", "exec", execPath, "args", args)
- cmd.WaitDelay = 10 * time.Second
+ // 500ms, matching cursor-agent — the other backend whose CLI can deliver a
+ // terminal result while keeping a process alive.
+ //
+ // Note what WaitDelay actually bounds, because it is easy to get wrong: the
+ // timer starts when the context is done OR when Wait observes the child has
+ // exited, whichever comes first. So a *clean* exit reaches it too, whenever
+ // any descendant still holds one of the pipes os/exec manages — and this
+ // backend has such a pipe, since cmd.Stderr below is a plain io.Writer. In
+ // that case Wait returns exec.ErrWaitDelay even though the process exited 0,
+ // which is why the status switch has to special-case it: the result is
+ // already parsed and in hand, and only a tail of stderr logs is lost.
+ //
+ // Lowering the bound is still right. The delay is only reached when someone
+ // is holding a pipe open, and on the cut-short path we deliberately kill a
+ // process that is doing exactly that — a long delay there would add its full
+ // length to every reply.
+ cmd.WaitDelay = 500 * time.Millisecond
if opts.Cwd != "" {
cmd.Dir = opts.Cwd
}
@@ -118,17 +135,50 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
startTime := time.Now()
scanResult := b.processOutput(stdout, msgCh)
+ // openclaw delivered a complete result but would not exit. Cancel the
+ // run context so CommandContext kills it and cmd.Wait can return —
+ // otherwise this goroutine parks forever on an agent that has already
+ // finished, and the reply never reaches the user. Same protocol-boundary
+ // treatment cursor-agent gets on its terminal `result` event.
+ if scanResult.cutShort {
+ b.cfg.Logger.Warn("openclaw delivered its result but did not exit; "+
+ "treating the complete result as the protocol boundary",
+ "pid", cmd.Process.Pid)
+ cancel()
+ }
+
// Wait for process exit.
exitErr := cmd.Wait()
duration := time.Since(startTime)
- if runCtx.Err() == context.DeadlineExceeded {
+ switch {
+ case scanResult.cutShort:
+ // A complete result is the protocol boundary. Ignore the
+ // cancellation and exit error caused by stopping an openclaw that
+ // lingers afterward — the run succeeded, and reporting it as
+ // "aborted" would throw away a reply we already hold.
+ case runCtx.Err() == context.DeadlineExceeded:
scanResult.status = "timeout"
scanResult.errMsg = fmt.Sprintf("openclaw timed out after %s", timeout)
- } else if runCtx.Err() == context.Canceled {
+ case runCtx.Err() == context.Canceled:
scanResult.status = "aborted"
scanResult.errMsg = "execution cancelled"
- } else if exitErr != nil && scanResult.status == "completed" {
+ case errors.Is(exitErr, exec.ErrWaitDelay) && scanResult.status == "completed":
+ // The process itself exited successfully — that is what
+ // ErrWaitDelay means by definition — and only a lingering
+ // descendant kept one of os/exec's pipes open past WaitDelay.
+ // stdout has already been read to EOF and the result parsed, so the
+ // only thing lost is a tail of stderr log lines. Reporting this as
+ // a failure would discard a deliverable reply, which is a worse
+ // outcome than the hang this whole change fixes.
+ //
+ // Not folded into the cutShort case above: that path cancels on
+ // purpose, and a Cancel call makes Wait report the kill instead of
+ // ErrWaitDelay. This case is specifically the clean-exit one.
+ b.cfg.Logger.Warn("openclaw exited cleanly but a descendant held a "+
+ "pipe past WaitDelay; delivering the parsed result and dropping "+
+ "the stderr tail", "pid", cmd.Process.Pid)
+ case exitErr != nil && scanResult.status == "completed":
scanResult.status = "failed"
scanResult.errMsg = fmt.Sprintf("openclaw exited with error: %v", exitErr)
}
@@ -294,6 +344,13 @@ type openclawEventResult struct {
// which for the openclaw backend is the openclaw *agent* name passed
// via `--agent`, not the underlying model.
model string
+ // cutShort is true when the run ended because openclaw had delivered a
+ // complete result but would not exit, rather than because stdout reached
+ // EOF. The caller must cancel the run context before cmd.Wait() in that
+ // case — otherwise it waits on a process that never leaves — and must not
+ // report the resulting cancellation as an abort. Same treatment
+ // cursor-agent's `resultSeen` gets.
+ cutShort bool
}
// processOutput reads the JSON output from openclaw --json stdout and returns
@@ -318,7 +375,7 @@ type openclawEventResult struct {
// the dominant happy path (one pretty-printed JSON blob) deterministic
// while keeping NDJSON event support intact.
func (b *openclawBackend) processOutput(r io.Reader, ch chan<- Message) openclawEventResult {
- buf, readErr := io.ReadAll(r)
+ buf, cutShort, readErr := readOpenclawStdout(r, openclawResultIdleGrace)
if readErr != nil {
return openclawEventResult{status: "failed", errMsg: fmt.Sprintf("read stdout: %v", readErr)}
}
@@ -329,7 +386,9 @@ func (b *openclawBackend) processOutput(r io.Reader, ch chan<- Message) openclaw
// matches, we're done — no need to involve the line scanner at all.
if result, ok := parseWholeBufferOpenclawResult(buf); ok {
var output strings.Builder
- return b.buildOpenclawEventResult(result, ch, &output)
+ res := b.buildOpenclawEventResult(result, ch, &output)
+ res.cutShort = cutShort
+ return res
}
// Fall-back path: NDJSON line scanner. Note that because we already
diff --git a/server/pkg/agent/openclaw_stdout.go b/server/pkg/agent/openclaw_stdout.go
new file mode 100644
index 0000000000..0406e9716f
--- /dev/null
+++ b/server/pkg/agent/openclaw_stdout.go
@@ -0,0 +1,141 @@
+package agent
+
+import (
+ "io"
+ "sync"
+ "time"
+)
+
+// openclawResultIdleGrace is how long stdout must stay silent *after* the
+// buffer already parses as a complete openclaw result before readOpenclawStdout
+// treats the run as finished.
+//
+// Deliberately generous. The cheap check — does the buffer parse as a complete
+// result? — is the real gate; this only guards against declaring victory
+// mid-write if a future openclaw flushes a result and then appends more. 2s is
+// far longer than the gap inside one flush, and it costs nothing in the normal
+// case because a CLI that exits reaches EOF and never consults it.
+const openclawResultIdleGrace = 2 * time.Second
+
+// openclawStdoutPoll is how often the reader re-evaluates its exit conditions.
+const openclawStdoutPoll = 100 * time.Millisecond
+
+// readOpenclawStdout drains r and returns the bytes read. It stops at EOF, or
+// early once the buffer parses as a complete openclaw result AND stdout has
+// been idle for idleGrace — reporting cutShort=true in that second case so the
+// caller can cancel the run before waiting on the process.
+//
+// # Why not io.ReadAll
+//
+// io.ReadAll returns only at EOF, and EOF requires every write end of the pipe
+// to be closed. Observed in production: `openclaw agent --local --json` printed
+// its complete result blob — the agent's reply was fully generated — and then
+// did not exit. The pipe stayed open, so the read never returned, the goroutine
+// never reached cmd.Wait, and the finished reply sat in the daemon's buffer
+// while the task held its execution slot:
+//
+// T+0s openclaw started
+// T+24s the complete result blob was written to stdout
+// T+8min process still alive, slot still held, user saw nothing
+//
+// # Why a complete result is the right boundary
+//
+// This exact hazard is already handled for cursor-agent, whose adapter notes
+// that current versions "can emit the terminal result event but keep a worker
+// process alive" and therefore treats result as the protocol boundary and
+// cancels (see the "result" case in cursor.go). openclaw parses one
+// whole-buffer blob rather than line events, so the equivalent condition is
+// "the buffer is a complete result" instead of "a result line arrived".
+//
+// Both conditions are required. Idle alone is not enough — an agent may pause
+// for minutes while thinking, and cutting off a partial buffer would discard
+// work it has already done, which is worse than the hang. Parseable alone is
+// not enough either, since more output may still be coming.
+//
+// Nothing is cut short before any output appears: idle time is measured from
+// the last byte received, so a silent agent remains governed purely by the
+// caller's context, exactly as before.
+//
+// On the cutShort path the internal read goroutine is still blocked in
+// r.Read. It exits when the caller's cancellation closes r, which openclaw's
+// Execute already arranges. Callers that do not close r on cancellation must
+// not use this function.
+func readOpenclawStdout(r io.Reader, idleGrace time.Duration) (buf []byte, cutShort bool, err error) {
+ if idleGrace <= 0 {
+ idleGrace = openclawResultIdleGrace
+ }
+
+ var (
+ mu sync.Mutex
+ acc []byte
+ lastByte time.Time
+ readErr error
+ atEOF bool
+ )
+
+ finished := make(chan struct{})
+ go func() {
+ defer close(finished)
+ chunk := make([]byte, 32*1024)
+ for {
+ n, rerr := r.Read(chunk)
+ if n > 0 {
+ mu.Lock()
+ acc = append(acc, chunk[:n]...)
+ lastByte = time.Now()
+ mu.Unlock()
+ }
+ if rerr != nil {
+ mu.Lock()
+ if rerr != io.EOF {
+ readErr = rerr
+ }
+ atEOF = true
+ mu.Unlock()
+ return
+ }
+ }
+ }()
+
+ ticker := time.NewTicker(openclawStdoutPoll)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-finished:
+ // The stream ended on its own: the pre-existing behaviour, with the
+ // same buffer io.ReadAll would have produced.
+ mu.Lock()
+ out, rerr := acc, readErr
+ mu.Unlock()
+ return out, false, rerr
+
+ case <-ticker.C:
+ // Check the cheap conditions under the lock first and only copy the
+ // buffer once the silence threshold is actually met. Copying on every
+ // tick would allocate the whole accumulated result ~20 times per wait
+ // window, which for a large result is pure waste.
+ mu.Lock()
+ size := len(acc)
+ last := lastByte
+ done := atEOF
+ mu.Unlock()
+
+ if done {
+ continue // let the <-finished branch report the final state
+ }
+ if size == 0 || time.Since(last) < idleGrace {
+ continue
+ }
+
+ mu.Lock()
+ out := append([]byte(nil), acc...)
+ mu.Unlock()
+
+ if _, ok := parseWholeBufferOpenclawResult(out); !ok {
+ continue
+ }
+ return out, true, nil
+ }
+ }
+}
diff --git a/server/pkg/agent/openclaw_stdout_test.go b/server/pkg/agent/openclaw_stdout_test.go
new file mode 100644
index 0000000000..05a9d4871e
--- /dev/null
+++ b/server/pkg/agent/openclaw_stdout_test.go
@@ -0,0 +1,284 @@
+//go:build !windows
+
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Reproduces the production failure where a chat reply was generated but never
+// delivered. Timeline observed on an OpenClaw host:
+//
+// T+0s openclaw started
+// T+24s the complete result blob was written to stdout
+// T+8min process still alive, task slot still held, user saw nothing
+//
+// processOutput used io.ReadAll, which returns only at EOF, and EOF requires
+// every write end of the pipe to be closed. openclaw had printed its complete
+// result blob but would not exit, so the read never finished, cmd.Wait was
+// never reached, and the finished answer sat in the daemon's buffer.
+
+// completeOpenclawResult is the minimal blob that parses as a final result
+// (payloads + meta.durationMs).
+const completeOpenclawResult = `{"payloads":[{"text":"the agent reply text"}],` +
+ `"meta":{"durationMs":1234,"agentMeta":{"sessionId":"sess-abc","model":"test-model"}}}`
+
+// writeOpenclawStub creates a fake `openclaw` that satisfies the version gate,
+// prints body for the `agent` subcommand, and then either exits or hangs.
+func writeOpenclawStub(t *testing.T, body string, hangAfter bool) string {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "openclaw")
+ tail := "exit 0"
+ if hangAfter {
+ tail = "sleep 300"
+ }
+ script := `#!/bin/sh
+case "$1" in
+ --version) echo "openclaw 2026.5.27"; exit 0 ;;
+esac
+cat <<'JSON'
+` + body + `
+JSON
+` + tail + `
+`
+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
+ t.Fatalf("write openclaw stub: %v", err)
+ }
+ return bin
+}
+
+func newOpenclawTestBackend(bin string) *openclawBackend {
+ return &openclawBackend{cfg: Config{
+ ExecutablePath: bin,
+ Logger: slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})),
+ }}
+}
+
+// TestOpenclawExecuteCompletesWhenCLINeverExits is the assertion that would have
+// caught the undelivered-reply incident.
+func TestOpenclawExecuteCompletesWhenCLINeverExits(t *testing.T) {
+ bin := writeOpenclawStub(t, completeOpenclawResult, true)
+ b := newOpenclawTestBackend(bin)
+
+ // No per-run timeout in ExecOptions, matching production since MUL-3064
+ // made the run timeout opt-in: completion must come from the protocol
+ // boundary, not from a deadline. The ctx bound only keeps the test finite.
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ start := time.Now()
+ session, err := b.Execute(ctx, "are you there", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ for range session.Messages {
+ // drain
+ }
+ result, ok := <-session.Result
+ elapsed := time.Since(start)
+
+ if !ok {
+ t.Fatal("result channel closed without a result")
+ }
+ if result.Status != "completed" {
+ t.Errorf("status = %q (error: %q), want completed — a delivered result "+
+ "must not be reported as aborted just because we killed the "+
+ "lingering process", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "the agent reply text") {
+ t.Errorf("output = %q, lost the agent's reply", result.Output)
+ }
+ if result.SessionID != "sess-abc" {
+ t.Errorf("session id = %q, want sess-abc", result.SessionID)
+ }
+ // Bound only has to be far below the 60s ctx and the stub's 300s sleep: if
+ // the boundary mechanism failed, this takes one of those, not 20s.
+ if elapsed > 20*time.Second {
+ t.Errorf("took %v — waited on a process that never exits", elapsed)
+ }
+}
+
+// TestOpenclawExecuteStillWorksWhenCLIExits guards the normal path: a
+// well-behaved CLI must still be read to EOF and reported correctly.
+//
+// Deliberately no wall-clock assertion here. "A clean exit does not pay the
+// idle grace" is a real property, but this test spawns the stub twice (version
+// gate, then the run), so its elapsed time is dominated by process startup and
+// an elapsed bound would be a CI flake rather than a check on the mechanism.
+// That property is pinned deterministically in
+// TestReadOpenclawStdoutDoesNotWaitForIdleGraceAtEOF instead.
+func TestOpenclawExecuteStillWorksWhenCLIExits(t *testing.T) {
+ bin := writeOpenclawStub(t, completeOpenclawResult, false)
+ b := newOpenclawTestBackend(bin)
+
+ session, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ for range session.Messages {
+ }
+ result, ok := <-session.Result
+
+ if !ok {
+ t.Fatal("result channel closed without a result")
+ }
+ if result.Status != "completed" {
+ t.Errorf("status = %q (error %q), want completed", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "the agent reply text") {
+ t.Errorf("output = %q, lost the reply on the clean-exit path", result.Output)
+ }
+ if result.SessionID != "sess-abc" {
+ t.Errorf("session id = %q, want sess-abc", result.SessionID)
+ }
+}
+
+// TestOpenclawExecuteToleratesLingeringStderrHolder is the regression for the
+// review finding on #6276: lowering WaitDelay must not turn a delivered reply
+// into an error.
+//
+// WaitDelay's timer starts when Wait observes the child has exited, not only on
+// cancellation, so a *clean* exit reaches it whenever a descendant still holds
+// one of the pipes os/exec manages — and cmd.Stderr here is a plain io.Writer,
+// which is exactly such a pipe. Wait then returns exec.ErrWaitDelay despite the
+// process having exited 0, and without the dedicated case that fell through to
+// "openclaw exited with error" and discarded a fully parsed reply.
+//
+// The stub reproduces precisely that shape: stdout reaches EOF when the parent
+// exits (the descendant's own stdout goes to /dev/null so it is not a writer on
+// that pipe), while the descendant keeps stderr open for ~1s, well past the
+// 500ms delay.
+func TestOpenclawExecuteToleratesLingeringStderrHolder(t *testing.T) {
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "openclaw")
+ script := `#!/bin/sh
+case "$1" in
+ --version) echo "openclaw 2026.5.27"; exit 0 ;;
+esac
+# Holds ONLY stderr: its stdout is /dev/null, so the stdout pipe's sole writer
+# is this parent and EOF arrives as soon as it exits.
+( sleep 1 ) >/dev/null &
+cat <<'JSON'
+` + completeOpenclawResult + `
+JSON
+exit 0
+`
+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
+ t.Fatalf("write openclaw stub: %v", err)
+ }
+ b := newOpenclawTestBackend(bin)
+
+ session, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ for range session.Messages {
+ }
+ result, ok := <-session.Result
+ if !ok {
+ t.Fatal("result channel closed without a result")
+ }
+
+ if result.Status != "completed" {
+ t.Errorf("status = %q (error: %q), want completed — the process exited 0 "+
+ "and the result was parsed; a descendant holding stderr past "+
+ "WaitDelay must not discard a deliverable reply", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "the agent reply text") {
+ t.Errorf("output = %q, lost the reply", result.Output)
+ }
+ if result.SessionID != "sess-abc" {
+ t.Errorf("session id = %q, want sess-abc", result.SessionID)
+ }
+}
+
+// TestReadOpenclawStdoutDoesNotWaitForIdleGraceAtEOF pins that the idle grace is
+// only ever paid by a CLI that refuses to exit. A reader that reaches EOF must
+// return immediately even when the grace is set absurdly high.
+//
+// No process is involved, so this is a deterministic check on the mechanism
+// rather than a timing race: a regression that made the reader poll until the
+// grace elapsed would take 10s instead of microseconds.
+func TestReadOpenclawStdoutDoesNotWaitForIdleGraceAtEOF(t *testing.T) {
+ start := time.Now()
+ buf, cutShort, err := readOpenclawStdout(strings.NewReader(completeOpenclawResult), 10*time.Second)
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("readOpenclawStdout: %v", err)
+ }
+ if cutShort {
+ t.Error("cutShort = true for a stream that reached EOF, want false — the " +
+ "caller would cancel and log a warning for a well-behaved CLI")
+ }
+ if string(buf) != completeOpenclawResult {
+ t.Errorf("buf = %q, want the full blob", buf)
+ }
+ if elapsed > time.Second {
+ t.Errorf("took %v with a 10s idle grace — EOF must not wait out the "+
+ "grace", elapsed)
+ }
+}
+
+// TestReadOpenclawStdoutWaitsForCompleteResult pins the safety half of the
+// shortcut: idle output alone is not enough. Cutting off a partial buffer would
+// throw away work the agent has already done, which is worse than the hang this
+// change fixes.
+func TestReadOpenclawStdoutWaitsForCompleteResult(t *testing.T) {
+ pr, pw, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("pipe: %v", err)
+ }
+ defer pr.Close()
+
+ // A partial blob that cannot parse, followed by silence.
+ if _, err := pw.WriteString(`{"payloads":[{"text":"half`); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+
+ type outcome struct {
+ cutShort bool
+ buf string
+ }
+ done := make(chan outcome, 1)
+ go func() {
+ buf, cutShort, _ := readOpenclawStdout(pr, 200*time.Millisecond)
+ done <- outcome{cutShort: cutShort, buf: string(buf)}
+ }()
+
+ // Well past the idle grace: without the parse guard the reader would have
+ // returned cutShort by now.
+ time.Sleep(700 * time.Millisecond)
+ select {
+ case got := <-done:
+ t.Fatalf("returned early on an unparseable buffer (cutShort=%v, buf=%q) "+
+ "— the agent's partial output would be silently discarded",
+ got.cutShort, got.buf)
+ default:
+ }
+
+ // Completing the blob and closing gives the reader a clean EOF.
+ if _, err := pw.WriteString(`"}],"meta":{"durationMs":1}}`); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+ pw.Close()
+
+ select {
+ case got := <-done:
+ if got.cutShort {
+ t.Error("cutShort = true after a clean EOF, want false")
+ }
+ if !strings.Contains(got.buf, `"durationMs":1`) {
+ t.Errorf("buf = %q, lost the bytes written after the pause", got.buf)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("readOpenclawStdout did not return after EOF")
+ }
+}