Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): recover from Hermes resumed sessions it refuses without running (MUL-5509) (#6164)
Bohan Jiangd6bd4cf7d5c2
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 29b04b315f..f730688224 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -269,6 +269,11 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// streams) is dropped instead of duplicating the previous answer// into output. We flip it to true only after session/prompt is sent.var streamingCurrentTurn atomic.Bool+ // turnActivity counts the session updates accepted for the current turn.+ // Zero means the agent produced nothing at all — no text, no thought, no+ // tool call — which is what separates a dead-session refusal from a model+ // that genuinely refused the request. See hermesResumeSessionLost.+ var turnActivity atomic.Int64promptDone := make(chan hermesPromptResult, 1)activity := make(chan struct{}, 1)@@ -291,6 +296,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptif !streamingCurrentTurn.Load() {return}+ turnActivity.Add(1)deliverable.observe(msg)trySend(msgCh, msg)},@@ -343,6 +349,10 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// resume. Only that is curable by starting a fresh session, so// handshake/network failures below must leave it false.var resumeRejected bool+ // The stop reason session/prompt reported, when it answered at all.+ // Read once the turn has fully settled — see the resumed-session check+ // after the provider-error promotion below.+ var promptStopReason stringeffectiveModel := strings.TrimSpace(opts.Model)// The model id the runtime reports as current right after// session/new or session/resume. Used to skip a redundant@@ -542,6 +552,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// from the response parsing.select {case pr := <-promptDone:+ promptStopReason = pr.stopReasonif pr.stopReason == "cancelled" {finalStatus = "aborted"finalError = "hermes cancelled the prompt"@@ -600,6 +611,37 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// give-up turn that lands before a tool call stays visible.finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)+ // A resumed session Hermes could not rebuild.+ //+ // Evaluated HERE, not at the quiescence boundary above: the quiet+ // window closing does not end the turn. stdin EOF and the pipe drain+ // do, and Hermes legitimately delivers a turn's final chunk in that+ // gap — TestHermesBackendDrainsLateFinalNotificationAfterPromptResponse+ // exists because of it. Deciding earlier would freeze+ // turnActivity == 0 while a real answer was still in flight and+ // discard a healthy session (plus re-run the turn) for a runtime that+ // merely answered slowly. By this point streamingCurrentTurn is off+ // and every accepted update has been counted, so the reading is final.+ //+ // Runs after the promotion above on purpose: when the sniffer captured+ // why the rebuild failed (e.g. the provider identity the session+ // persisted no longer resolves), that message is far more useful to the+ // user than the generic one here, so we only supply a reason when+ // nothing else did. Without this, such a turn reports "completed" with+ // empty output — a task that silently did nothing at all.+ if hermesResumeSessionLost(opts.ResumeSessionID, promptStopReason, turnActivity.Load()) {+ b.cfg.Logger.Warn("resumed session refused with no agent activity; treating it as gone and clearing the session id so the daemon retries fresh",+ "backend", "hermes",+ "session_id", sessionID,+ )+ if finalStatus == "completed" {+ finalStatus = "failed"+ finalError = hermesResumeLostError+ }+ sessionID = ""+ resumeRejected = true+ }+// Build usage map.c.usageMu.Lock()u := c.usage@@ -1054,6 +1096,35 @@ func isACPSessionNotFound(err error) bool {strings.Contains(text, "no session found")}+// hermesResumeLostError is the fallback reason for a resumed session Hermes+// could not rebuild, used only when nothing more specific was captured.+const hermesResumeLostError = "hermes could not restore the resumed session; it refused the turn without running the agent"++// hermesResumeSessionLost reports whether a *successful* session/prompt+// response means the session we resumed is gone on the agent side.+//+// isACPSessionNotFound cannot answer this, because Hermes never reports an+// unknown session as a JSON-RPC error. Its ACP adapter answers+// `session/prompt` for a session it cannot load with an ordinary success+// frame carrying stopReason=refusal (acp_adapter/server.py, the one place it+// emits that reason), and `session/resume` echoes nothing back — the ACP+// ResumeSessionResponse schema has no sessionId field at all, unlike+// NewSessionResponse — so resolveResumedSessionID keeps the id we asked for.+// Nothing in the exchange is an error, which is why the isACPSessionNotFound+// branches at set_model and prompt time never fire for this runtime and every+// later dispatch on the same (agent, issue) pair loops on the dead session+// (GH #6150).+//+// Both conditions are required. stopReason=refusal alone is a legitimate+// model refusal, and refusing a resumed turn after real work is not a lost+// session — only a refusal with no agent activity whatsoever (no text, no+// thought, no tool call) is Hermes telling us it never had the session. The+// fresh-session retry this unlocks is itself gated on tools == 0 in+// shouldRetryWithFreshSession, so a turn that acted is never re-run.+func hermesResumeSessionLost(resumeSessionID, stopReason string, turnActivity int64) bool {+ return resumeSessionID != "" && stopReason == "refusal" && turnActivity == 0+}+func (c *hermesClient) handleResponse(raw map[string]json.RawMessage) {var id intif err := json.Unmarshal(raw["id"], &id); err != nil {diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex 8711983471..028ff179a2 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -2450,9 +2450,14 @@ func TestIsACPSessionNotFound(t *testing.T) {// fakeHermesACPStaleResumeScript impersonates the failure shape from// GitHub multica#4010: session/resume succeeds and echoes back the-// requested sessionId (hermes' observed behavior even when it no longer-// knows the session), and the subsequent session/prompt then fails with+// requested sessionId, and the subsequent session/prompt then fails with// JSON-RPC -32603 "Session not found".+//+// This is a real ACP shape and isACPSessionNotFound is shared by every ACP+// backend, so it stays covered — but it is NOT what Hermes itself does. Hermes+// reports an unknown session as a *successful* stopReason=refusal and its+// session/resume response carries no sessionId at all; that shape is covered+// by fakeHermesACPRefusedResumeScript below (GH #6150).func fakeHermesACPStaleResumeScript() string {return `#!/bin/shwhile IFS= read -r line; do@@ -3340,3 +3345,242 @@ func TestACPRawText(t *testing.T) {}}}++// TestHermesResumeSessionLost pins the predicate behind the GH #6150 recovery.+// Both conditions are load-bearing: a refusal after real agent activity is a+// model refusal, and a refusal on a fresh session says nothing about resume.+func TestHermesResumeSessionLost(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ resumeID string+ stopReason string+ activity int64+ want bool+ }{+ {name: "resumed refusal with no activity", resumeID: "ses_dead", stopReason: "refusal", want: true},+ {name: "resumed refusal after activity", resumeID: "ses_dead", stopReason: "refusal", activity: 3},+ {name: "fresh session refusal", stopReason: "refusal"},+ {name: "resumed end_turn", resumeID: "ses_ok", stopReason: "end_turn"},+ {name: "resumed cancelled", resumeID: "ses_ok", stopReason: "cancelled"},+ {name: "resumed empty stop reason", resumeID: "ses_ok"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := hermesResumeSessionLost(tc.resumeID, tc.stopReason, tc.activity); got != tc.want {+ t.Errorf("hermesResumeSessionLost(%q, %q, %d) = %v, want %v",+ tc.resumeID, tc.stopReason, tc.activity, got, tc.want)+ }+ })+ }+}++// fakeHermesACPRefusedResumeScript reproduces what real Hermes does with a+// session it cannot load, verified against upstream hermes-agent main by+// driving `hermes acp` over stdio:+//+// session/resume -> success, result carries only _meta/models/modes+// (ACP ResumeSessionResponse has no sessionId field)+// session/prompt -> success, {"stopReason":"refusal"}, no session/update at all+//+// Nothing in the exchange is a JSON-RPC error, which is why isACPSessionNotFound+// cannot see it. Env switches:+//+// ACP_PROVIDER_ERR=1 — also write the stderr Hermes emits when the session's+// persisted provider identity no longer resolves (#6150).+// ACP_ACTIVITY=1 — stream one agent_message_chunk before refusing, the+// legitimate-refusal control case.+// ACP_LATE_ACTIVITY=1 — send that chunk AFTER the refusal and after the+// notification quiet window has elapsed, i.e. in the gap+// between quiescence and stdin EOF that Hermes really+// uses for a turn's final message.+func fakeHermesACPRefusedResumeScript() string {+ return `#!/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":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fresh"}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ if [ "$ACP_PROVIDER_ERR" = "1" ]; then+ echo '2026-07-30 13:46:51 [WARNING] acp_adapter.session: Failed to recreate agent for ACP session ses_dead' >&2+ echo 'RuntimeError: No LLM provider configured. Run hermes model to select a provider.' >&2+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"_meta":{},"models":null,"modes":null}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ sid=$(printf '%s' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p')+ if [ "$ACP_ACTIVITY" = "1" ]; then+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"%s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I will not do that."}}}}\n' "$sid"+ fi+ if [ "$ACP_PROVIDER_ERR" = "1" ]; then+ echo '2026-07-30 13:46:51 [ERROR] acp_adapter.server: prompt: session ses_dead not found' >&2+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"refusal"}}\n' "$id"+ if [ "$ACP_LATE_ACTIVITY" = "1" ]; then+ sleep 0.6+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"%s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Sorry, I will not do that."}}}}\n' "$sid"+ fi+ exit 0+ ;;+ esac+done+`+}++func runHermesRefusedResume(t *testing.T, opts ExecOptions, env map[string]string) Result {+ t.Helper()++ fakePath := filepath.Join(t.TempDir(), "hermes")+ writeTestExecutable(t, fakePath, []byte(fakeHermesACPRefusedResumeScript()))++ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default(), Env: env})+ if err != nil {+ t.Fatalf("new hermes backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ if opts.Timeout == 0 {+ opts.Timeout = 20 * time.Second+ }+ session, err := backend.Execute(ctx, "continue", opts)+ 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")+ }+ return result+ case <-time.After(30 * time.Second):+ t.Fatal("timeout waiting for result")+ }+ return Result{}+}++// TestHermesBackendRecoversFromRefusedResume is the GH #6150 regression. A+// resumed session Hermes cannot rebuild must fail loudly AND surrender the dead+// session id, so shouldRetryWithFreshSession fires once and the id is retired.+// Before the fix this reported status=completed with empty output while handing+// the dead id straight back, so every later comment / approval / @mention on the+// issue re-resumed it and the agent was usable exactly once per issue.+func TestHermesBackendRecoversFromRefusedResume(t *testing.T) {+ t.Parallel()++ result := runHermesRefusedResume(t, ExecOptions{ResumeSessionID: "ses_dead"}, nil)++ if result.Status != "failed" {+ t.Errorf("status = %q, want failed (a turn that ran nothing must not report success)", result.Status)+ }+ if result.Error != hermesResumeLostError {+ t.Errorf("error = %q, want %q", result.Error, hermesResumeLostError)+ }+ if result.SessionID != "" {+ t.Errorf("session id = %q, want empty so the daemon retries fresh", result.SessionID)+ }+ if !result.ResumeRejected {+ t.Error("ResumeRejected = false, want true so shouldRetryWithFreshSession fires")+ }+}++// TestHermesBackendKeepsProviderErrorOnRefusedResume pins the ordering against+// the provider-error promotion: when the sniffer captured WHY Hermes could not+// rebuild the session, that reason is what the user needs to see, so the generic+// fallback must not overwrite it. The recovery signals still apply.+func TestHermesBackendKeepsProviderErrorOnRefusedResume(t *testing.T) {+ t.Parallel()++ result := runHermesRefusedResume(t,+ ExecOptions{ResumeSessionID: "ses_dead"},+ map[string]string{"ACP_PROVIDER_ERR": "1"},+ )++ if result.Status != "failed" {+ t.Errorf("status = %q, want failed", result.Status)+ }+ if !strings.Contains(result.Error, "No LLM provider configured") {+ t.Errorf("error = %q, want the captured provider error rather than the generic fallback", result.Error)+ }+ if result.SessionID != "" {+ t.Errorf("session id = %q, want empty so the daemon retries fresh", result.SessionID)+ }+ if !result.ResumeRejected {+ t.Error("ResumeRejected = false, want true so shouldRetryWithFreshSession fires")+ }+}++// TestHermesBackendKeepsSessionOnRefusalAfterActivity is the false-positive+// guard. A resumed turn that streamed real agent output and then stopped on+// refusal is a model refusal, not a lost session: dropping the session id there+// would discard a healthy conversation pointer and re-run the turn.+func TestHermesBackendKeepsSessionOnRefusalAfterActivity(t *testing.T) {+ t.Parallel()++ result := runHermesRefusedResume(t,+ ExecOptions{ResumeSessionID: "ses_dead"},+ map[string]string{"ACP_ACTIVITY": "1"},+ )++ if result.SessionID != "ses_dead" {+ t.Errorf("session id = %q, want the resumed id preserved", result.SessionID)+ }+ if result.ResumeRejected {+ t.Error("ResumeRejected = true, want false — the agent ran, so a fresh session is not the cure")+ }+}++// TestHermesBackendKeepsSessionOnRefusalWithLateActivity is the timing+// false-positive guard. The notification quiet window closing does not end the+// turn — stdin EOF and the pipe drain do, and Hermes legitimately delivers a+// turn's final chunk in that gap (see+// TestHermesBackendDrainsLateFinalNotificationAfterPromptResponse). Deciding+// "no activity" at the quiescence boundary instead of after the drain would+// discard this healthy session and re-run the turn.+func TestHermesBackendKeepsSessionOnRefusalWithLateActivity(t *testing.T) {+ t.Parallel()++ result := runHermesRefusedResume(t,+ ExecOptions{ResumeSessionID: "ses_dead"},+ map[string]string{"ACP_LATE_ACTIVITY": "1"},+ )++ if result.Output == "" {+ t.Fatal("late chunk never reached the result; the fixture is not exercising the drain gap")+ }+ if result.SessionID != "ses_dead" {+ t.Errorf("session id = %q, want the resumed id preserved", result.SessionID)+ }+ if result.ResumeRejected {+ t.Error("ResumeRejected = true, want false — the agent answered, only late")+ }+}++// TestHermesBackendIgnoresRefusalOnFreshSession is the second false-positive+// guard: with no session to resume there is nothing to declare lost, so the+// fresh session id must survive.+func TestHermesBackendIgnoresRefusalOnFreshSession(t *testing.T) {+ t.Parallel()++ result := runHermesRefusedResume(t, ExecOptions{}, nil)++ if result.SessionID != "ses_fresh" {+ t.Errorf("session id = %q, want ses_fresh", result.SessionID)+ }+ if result.ResumeRejected {+ t.Error("ResumeRejected = true, want false on a fresh session")+ }+}