Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4936: Fix empty replies in resumed Codex and Hermes chats (#5675)
Multica Evef51828f5680e
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex ca5e1ea1f3..369cf200c3 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -778,6 +778,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execvar outputMu sync.Mutexvar output strings.Buildervar semanticObserved atomic.Bool+ turnNotificationGate := &codexTurnNotificationGate{}// turnDone is set before starting the reader goroutine so there is no// race between the lifecycle goroutine writing and the reader reading.@@ -790,6 +791,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecprocessDone: make(chan struct{}),handshakeTimeout: handshakeTimeout,notificationProtocol: "unknown",+ acceptNotification: turnNotificationGate.accept,+ onDiscardedNotification: func(string, map[string]any) {+ // Any app-server notification proves the process made semantic+ // progress, even when it is intentionally excluded from the active+ // turn. Preserve initialize-retry safety without replaying content.+ semanticObserved.Store(true)+ },onMessage: func(msg Message) {logCodexAgentMessage(b.cfg.Logger, msg)if msg.Type == MessageText {@@ -1059,6 +1067,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}}}+ turnNotificationGate.arm()_, err = c.request(runCtx, "turn/start", turnParams)if err != nil {select {@@ -1547,6 +1556,14 @@ type codexClient struct {onMessage func(Message)onSemanticActivity func(description string)onTurnDone func(aborted bool)+ // acceptNotification isolates the active turn from same-thread history+ // replay emitted while thread/resume is restoring prior conversation.+ // Unit-level protocol tests leave it nil and exercise dispatch directly.+ acceptNotification func(method string, params map[string]any) bool+ // onDiscardedNotification preserves out-of-band safety signals (such as+ // suppressing an initialize retry after observed activity) without letting+ // filtered history mutate current-turn output or lifecycle state.+ onDiscardedNotification func(method string, params map[string]any)notificationProtocol string // "unknown", "legacy", "raw"turnStarted bool@@ -1559,6 +1576,72 @@ type codexClient struct {turnError string // captured from turn/completed status=failed or terminal error notifications}+// codexTurnNotificationGate keeps resume-time history replay from mutating the+// output or ending the new turn. Codex app-server can emit notifications before+// the turn/start RPC response, so the gate is armed before that request and uses+// turn/started (or legacy task_started) as the actual current-turn boundary.+// Protocols that omit those start events also omit a reliable current-turn ID;+// for compatibility, their post-arm events remain accepted. We therefore rely+// on the single stdout reader's ordering guarantee that resume history emitted+// before the thread/resume response is processed while the gate is still closed.+// A replay emitted after arm but before a start event cannot be distinguished+// from a valid legacy current-turn event without breaking those older streams.+// Its mutable lifecycle fields are only touched by the stdout reader goroutine;+// armed is atomic because the lifecycle goroutine flips it.+type codexTurnNotificationGate struct {+ armed atomic.Bool+ started bool+ turnID string+}++func (g *codexTurnNotificationGate) arm() {+ g.armed.Store(true)+}++func (g *codexTurnNotificationGate) accept(method string, params map[string]any) bool {+ if !g.armed.Load() {+ return false+ }++ if method == "codex/event" || strings.HasPrefix(method, "codex/event/") {+ msg, _ := params["msg"].(map[string]any)+ msgType, _ := msg["type"].(string)+ if msgType == "task_started" {+ g.started = true+ return true+ }+ // Older Codex event streams can omit task_started. Once turn/start is+ // armed, keep that compatibility; pre-arm replay is still excluded.+ return true+ }++ switch {+ case method == "turn/started":+ g.started = true+ g.turnID = extractNestedString(params, "turn", "id")+ return true+ case method == "turn/completed":+ if !g.started {+ // Older app-server versions can complete a turn without first+ // emitting turn/started. The pre-arm boundary still rejects resume+ // replay, while this keeps those versions functional.+ return true+ }+ turnID := extractNestedString(params, "turn", "id")+ return g.turnID == "" || turnID == "" || turnID == g.turnID+ case method == "thread/status/changed" || strings.HasPrefix(method, "item/"):+ if !g.started {+ return true+ }+ turnID, _ := params["turnId"].(string)+ return g.turnID == "" || turnID == "" || turnID == g.turnID+ default:+ // A terminal error may be the first notification produced by a failed+ // turn/start, so it must remain observable even without turn/started.+ return true+ }+}+func (c *codexClient) setTurnError(msg string) {if msg == "" {return@@ -1914,6 +1997,19 @@ func (c *codexClient) handleNotification(raw map[string]json.RawMessage) {if p, ok := raw["params"]; ok {_ = json.Unmarshal(p, ¶ms)}+ // Filter multiplexed subagent threads before the current-turn gate. The+ // gate mutates started/turnID on turn/started; letting another thread reach+ // it first can replace the main turn ID and make subsequent main-thread+ // items/completion look stale.+ if c.isNotificationFromOtherThread(params) {+ return+ }+ if c.acceptNotification != nil && !c.acceptNotification(method, params) {+ if c.onDiscardedNotification != nil {+ c.onDiscardedNotification(method, params)+ }+ return+ }// Legacy codex/event notificationsif method == "codex/event" || strings.HasPrefix(method, "codex/event/") {@@ -2017,11 +2113,11 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any// same stdio pipe; only our thread should drive turn lifecycle and output.//// The v2 app-server-protocol schema guarantees a top-level threadId on- // every notification, so this dispatch-level guard transparently covers- // every handler below. If a future codex revision introduces notifications- // without threadId, they fall through (ok=false) — re-audit this guard- // when bumping codex.- if threadID, ok := params["threadId"].(string); ok && c.threadID != "" && threadID != c.threadID {+ // every notification. handleNotification performs this guard before the+ // stateful current-turn gate; retain it here as defense in depth for direct+ // callers. If a future codex revision introduces notifications without+ // threadId, they fall through — re-audit this guard when bumping codex.+ if c.isNotificationFromOtherThread(params) {return}@@ -2113,6 +2209,11 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any}}+func (c *codexClient) isNotificationFromOtherThread(params map[string]any) bool {+ threadID, ok := params["threadId"].(string)+ return ok && c.threadID != "" && threadID != c.threadID+}+func (c *codexClient) handleItemNotification(method string, params map[string]any) {item, _ := params["item"].(map[string]any)itemType, _ := item["type"].(string)diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 637aaf631d..ceb5dc0a68 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -496,6 +496,67 @@ func TestCodexRawTurnCompleted(t *testing.T) {}}+func TestCodexTurnNotificationGateDropsResumeReplayAndOtherTurns(t *testing.T) {+ t.Parallel()++ gate := &codexTurnNotificationGate{}+ previousCompleted := map[string]any{+ "threadId": "thr-resumed",+ "turn": map[string]any{+ "id": "turn-previous",+ "status": "completed",+ },+ }+ if gate.accept("turn/completed", previousCompleted) {+ t.Fatal("resume replay must stay blocked before the current turn is armed")+ }++ gate.arm()+ if !gate.accept("turn/completed", previousCompleted) {+ t.Fatal("armed gate must preserve older streams that omit turn/started")+ }+ if !gate.accept("turn/started", map[string]any{+ "threadId": "thr-resumed",+ "turn": map[string]any{"id": "turn-current"},+ }) {+ t.Fatal("current turn/started should open the lifecycle gate")+ }+ if gate.accept("turn/completed", previousCompleted) {+ t.Fatal("completion from another turn must not finish the current turn")+ }+ if !gate.accept("item/completed", map[string]any{+ "threadId": "thr-resumed",+ "turnId": "turn-current",+ }) {+ t.Fatal("current-turn item should pass the gate")+ }+ if !gate.accept("turn/completed", map[string]any{+ "threadId": "thr-resumed",+ "turn": map[string]any{+ "id": "turn-current",+ "status": "completed",+ },+ }) {+ t.Fatal("current turn completion should pass the gate")+ }++ legacy := &codexTurnNotificationGate{}+ legacyComplete := map[string]any{"msg": map[string]any{"type": "task_complete"}}+ if legacy.accept("codex/event", legacyComplete) {+ t.Fatal("legacy resume replay must stay blocked before the current turn is armed")+ }+ legacy.arm()+ if !legacy.accept("codex/event", legacyComplete) {+ t.Fatal("armed gate must preserve legacy streams that omit task_started")+ }+ if !legacy.accept("codex/event", map[string]any{"msg": map[string]any{"type": "task_started"}}) {+ t.Fatal("legacy current task_started should open the lifecycle gate")+ }+ if !legacy.accept("codex/event", legacyComplete) {+ t.Fatal("legacy current task completion should pass the gate")+ }+}+func TestCodexRawTurnCompletedSubtractsCachedInput(t *testing.T) {t.Parallel()@@ -1177,6 +1238,55 @@ func TestCodexRawTurnCompletedFromSubagentIgnored(t *testing.T) {}}+func TestCodexTurnNotificationGateIgnoresSubagentTurnStarted(t *testing.T) {+ t.Parallel()++ gate := &codexTurnNotificationGate{}+ gate.arm()+ c, _, _ := newTestCodexClient(t)+ c.notificationProtocol = "raw"+ c.threadID = "thr_main"+ c.acceptNotification = gate.accept++ var (+ gotText string+ doneCount int+ discardedCount int+ )+ c.onMessage = func(msg Message) {+ if msg.Type == MessageText {+ gotText = msg.Content+ }+ }+ c.onTurnDone = func(aborted bool) {+ doneCount+++ }+ c.onDiscardedNotification = func(string, map[string]any) {+ discardedCount+++ }++ c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr_main","turn":{"id":"turn-main"}}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr_subagent","turn":{"id":"turn-sub"}}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr_main","turnId":"turn-main","item":{"type":"agentMessage","id":"msg-main","text":"Main answer"}}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr_main","turn":{"id":"turn-main","status":"completed"}}}`)++ if gate.turnID != "turn-main" {+ t.Fatalf("subagent turn/started replaced gate turnID: got %q", gate.turnID)+ }+ if c.turnID != "turn-main" {+ t.Fatalf("subagent turn/started replaced client turnID: got %q", c.turnID)+ }+ if gotText != "Main answer" {+ t.Fatalf("main turn text was lost after subagent start: got %q", gotText)+ }+ if doneCount != 1 {+ t.Fatalf("main turn completion count = %d, want 1", doneCount)+ }+ if discardedCount != 0 {+ t.Fatalf("subagent notification should be filtered before the gate, discarded callback count = %d", discardedCount)+ }+}+// Regression for #1181: subagent agentMessage/final_answer must not// trigger turn completion or leak text into the main output stream.func TestCodexRawItemAgentMessageFinalAnswerFromSubagentIgnored(t *testing.T) {@@ -2734,6 +2844,38 @@ func TestCodexExecuteTurnCompletionCanPrecedeTurnStartResponse(t *testing.T) {}}+func TestCodexExecuteResumeIgnoresPreviousTurnCompletion(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ fakePath := writeFakeCodexAppServer(t, ""++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"++ `read line`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-resumed","turn":{"id":"turn-previous","status":"completed"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-resumed"}}}'`+"\n"++ `read line`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-resumed","turn":{"id":"turn-current"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-resumed","turnId":"turn-current","item":{"type":"agentMessage","id":"msg-current","text":"Current answer"}}}'`+"\n"++ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-resumed","turn":{"id":"turn-current","status":"completed"}}}'`+"\n")++ result := executeFakeCodex(t, fakePath, ExecOptions{+ ResumeSessionID: "thr-resumed",+ ResumeExpected: true,+ Timeout: 5 * time.Second,+ SemanticInactivityTimeout: 100 * time.Millisecond,+ })+ if result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ if result.Output != "Current answer" {+ t.Fatalf("expected current-turn output, got %q", result.Output)+ }+}+func writeFakeCodexAppServer(t *testing.T, body string) string {t.Helper()fakePath := filepath.Join(t.TempDir(), "codex")diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex c321387487..c2d00979f7 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -161,6 +161,11 @@ type hermesBackend struct {cfg Config}+var (+ hermesReaderDrainGrace = 2 * time.Second+ hermesNotificationQuietTime = 250 * time.Millisecond+)+func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {execPath := b.cfg.ExecutablePathif execPath == "" {@@ -264,6 +269,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptvar streamingCurrentTurn atomic.BoolpromptDone := make(chan hermesPromptResult, 1)+ activity := make(chan struct{}, 1)c := &hermesClient{cfg: b.cfg,@@ -273,6 +279,12 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptacceptNotification: func(string) bool {return streamingCurrentTurn.Load()},+ onActivity: func() {+ select {+ case activity <- struct{}{}:+ default:+ }+ },onMessage: func(msg Message) {if !streamingCurrentTurn.Load() {return@@ -313,11 +325,15 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// Drive the ACP session lifecycle in a goroutine.go func() {- defer cancel()defer close(msgCh)defer close(resCh)defer func() {stdin.Close()+ // Cancellation must be reachable before Wait. A pathological child+ // can close stdout/stderr (so the pipe drain succeeds) but keep the+ // process alive; waiting first would then block until the overall+ // task timeout and make a later deferred cancel ineffective.+ cancel()_ = cmd.Wait()}()@@ -509,24 +525,37 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptc.usageMu.Unlock()default:}+ waitForHermesNotificationQuiescence(runCtx, activity, readerDone)}duration := time.Since(startTime)b.cfg.Logger.Info("hermes finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())- // Close stdin and cancel context to signal hermes acp to exit.+ // Close stdin first so Hermes can observe EOF and exit cleanly. Keep the+ // process alive while stdout/stderr drain; cancelling at the prompt+ // response boundary can truncate final notifications that arrive just+ // after the response.stdin.Close()- cancel()- // Wait for the reader goroutine to finish so all output is accumulated.- <-readerDone- // Wait for the stderr copier as well so the provider-error sniffer+ // Wait for the stdout reader and stderr copier so all output is+ // accumulated and the provider-error sniffer// has every byte the child wrote before we consult it for failure// promotion. Skipping this leaves a small race where stopReason=// end_turn arrives over stdout while the stderr 429 / usage-limit// lines are still in transit, causing the promoted error message- // to fall through to the synthetic agent-text fallback.- <-stderrDone+ // to fall through to the synthetic agent-text fallback. If Hermes does+ // not honor stdin EOF within the bound, cancel it and join both readers+ // before accessing their buffers.+ if !waitForHermesPipeDrain(readerDone, stderrDone, hermesReaderDrainGrace) {+ b.cfg.Logger.Warn("hermes did not close output pipes after stdin EOF; forcing shutdown",+ "pid", cmd.Process.Pid,+ "grace", hermesReaderDrainGrace.String(),+ )+ cancel()+ <-readerDone+ <-stderrDone+ }+ streamingCurrentTurn.Store(false)outputMu.Lock()finalOutput := output.String()@@ -569,6 +598,55 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptreturn &Session{Messages: msgCh, Result: resCh}, nil}+// waitForHermesNotificationQuiescence gives the stdout reader a bounded chance+// to consume session updates emitted just after session/prompt returns. Hermes+// may deliver the final agent_message_chunk after the response; closing stdin+// or cancelling immediately at that boundary loses the user-visible answer.+func waitForHermesNotificationQuiescence(ctx context.Context, activity <-chan struct{}, readerDone <-chan struct{}) {+ quiet := time.NewTimer(hermesNotificationQuietTime)+ defer quiet.Stop()+ hard := time.NewTimer(hermesReaderDrainGrace)+ defer hard.Stop()++ for {+ select {+ case <-activity:+ if !quiet.Stop() {+ select {+ case <-quiet.C:+ default:+ }+ }+ quiet.Reset(hermesNotificationQuietTime)+ case <-quiet.C:+ return+ case <-readerDone:+ return+ case <-hard.C:+ return+ case <-ctx.Done():+ return+ }+ }+}++func waitForHermesPipeDrain(readerDone, stderrDone <-chan struct{}, timeout time.Duration) bool {+ timer := time.NewTimer(timeout)+ defer timer.Stop()++ for readerDone != nil || stderrDone != nil {+ select {+ case <-readerDone:+ readerDone = nil+ case <-stderrDone:+ stderrDone = nil+ case <-timer.C:+ return false+ }+ }+ return true+}+// ── hermesClient: ACP JSON-RPC 2.0 transport ──type hermesPromptResult struct {@@ -586,8 +664,8 @@ type hermesClient struct {sessionID stringonMessage func(Message)onPromptDone func(hermesPromptResult)- // onActivity observes accepted ACP session updates. Grok uses it to- // retain a short post-response drain window; other ACP backends leave it+ // onActivity observes accepted ACP session updates. Hermes and Grok use it+ // to retain a short post-response drain window; other ACP backends leave it// nil and keep their existing lifecycle behavior.onActivity func()// acceptNotification can drop ACP session updates before dispatching todiff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex d1eda15921..004592985a 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -7,6 +7,7 @@ import ("log/slog""os""path/filepath"+ "runtime""strings""sync""testing"@@ -862,6 +863,131 @@ func TestHermesClientAcceptNotificationGate(t *testing.T) {}}+func TestHermesBackendDrainsLateFinalNotificationAfterPromptResponse(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ fakePath := filepath.Join(t.TempDir(), "hermes")+ script := `#!/bin/sh+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,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_resumed"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"+ sleep 0.05+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_resumed","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Current answer"}}}}\n'+ ;;+ esac+done+`+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new hermes backend: %v", err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt", ExecOptions{+ ResumeSessionID: "ses_resumed",+ Timeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", 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 != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ if result.Output != "Current answer" {+ t.Fatalf("expected late current-turn output, got %q", result.Output)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestHermesBackendCancelsBeforeWaitingForLingeringProcess(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ fakePath := filepath.Join(t.TempDir(), "hermes")+ script := `#!/bin/sh+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,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_lingering"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"+ exec 1>&-+ exec 2>&-+ while :; do :; done+ ;;+ esac+done+`+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new hermes backend: %v", err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", 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 != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("timeout waiting for result")+ }++ select {+ case _, ok := <-session.Result:+ if ok {+ t.Fatal("result channel produced an unexpected second value")+ }+ case <-time.After(2 * time.Second):+ t.Fatal("result channel did not close; cmd.Wait likely ran before cancel")+ }+}+func TestHermesClientHandleAgentThought(t *testing.T) {t.Parallel()