Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7120 fix(agent): stop ACP ghost sessions from wedging a conversation forever (#8155)
Bohan Jiang1921d18e142b
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 32fdeac4df..eace8bab72 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -2938,6 +2938,36 @@ func TestShouldRetryWithFreshSession(t *testing.T) {priorSessionID: "stale-id",want: true,},+ {+ // GH #8116 end to end. A qoder chat pinned to a session the CLI+ // never persisted used to reach this gate with ResumeRejected+ // false, because the adapter returned a bare failed Result from+ // session/resume — so the gate read "checked, not a rejection",+ // declined to retry, and the conversation replayed the same dead+ // id on every later message. The adapters now flag it, and this is+ // what that flag has to buy.+ name: "ghost session rejected at session/resume retries",+ result: agent.Result{+ Status: "failed",+ Error: `qoder session/resume failed: session/resume: Invalid session identifier "27d8031c-9fea-4bda-9d42-37c36fa9aebf". (code=-32602)`,+ ResumeRejected: true,+ },+ priorSessionID: "27d8031c-9fea-4bda-9d42-37c36fa9aebf",+ provider: "qoder",+ want: true,+ },+ {+ // The other half of the same contract: an unrecognised resume+ // failure must NOT retry. The adapters answer "not a rejection" by+ // leaving the flag false, and a capable backend's false is an+ // answer, not an absence — retrying here would fork a healthy+ // conversation over a transient MCP or network fault.+ name: "unflagged resume failure does not retry",+ result: agent.Result{Status: "failed", Error: "qoder session/resume failed: session/resume: Invalid params: mcpServers[0] transport unreachable (code=-32602)"},+ priorSessionID: "27d8031c-9fea-4bda-9d42-37c36fa9aebf",+ provider: "qoder",+ want: false,+ },{name: "temporarily busy resume retries without declaring the session dead",result: agent.Result{Status: "failed", Error: "session already in use", ResumeRejectedTransient: true},diff --git a/server/pkg/agent/acp_session.go b/server/pkg/agent/acp_session.gonew file mode 100644index 0000000000..f793a74980--- /dev/null+++ b/server/pkg/agent/acp_session.go@@ -0,0 +1,170 @@+package agent++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "regexp"+ "strings"+ "time"+)++// isACPResumeRejected reports whether an error returned by session/resume or+// session/load means the runtime refused the session id we asked it to restore.+//+// It is deliberately wider than isACPSessionNotFound, and deliberately scoped+// to that one RPC. session/resume and session/load have exactly one job — turn+// a recorded id into a live session — so a rejection there is about the id+// itself far more often than at set_model or prompt time, where the same words+// could be about the model, the provider or the network. Calling this outside+// the resume boundary would lose that context and start discarding healthy+// conversation pointers.+//+// It stays positive evidence, not exclusion. Treating EVERY resume error as a+// rejection is the tempting alternative and it is wrong: session/resume carries+// mcpServers, so an unreachable MCP server fails it, and so do a runtime+// handshake crash, an expired provider credential and a missing cwd. None of+// those is cured by starting over, and shouldRetryWithFreshSession's contract+// is that a false answer means "checked, and this was not a rejection". What+// this widens is the vocabulary, not the burden of proof: instead of three+// literal phrases it accepts any wording that names a session-shaped noun and+// says, right next to it, that the thing is unusable. That is what GH #8116+// slipped through — qodercli answers "Invalid session identifier <id>", which+// no literal in the original set matched, so a conversation pinned to a dead+// id retried it forever.+func isACPResumeRejected(err error) bool {+ var rpcErr *acpRPCError+ if !errors.As(err, &rpcErr) {+ return false+ }+ // No isACPSessionErrorCode gate here, unlike isACPSessionNotFound, and that+ // is a deliberate narrowing of what this fix depends on. The reported+ // qodercli frame is invalid_params (-32602) — inside the accepted set — but+ // that rests on the reporter's capture rather than anything we can+ // re-derive: a qodercli without a login answers session/resume with an auth+ // error long before it ever looks the id up, so the rejection path is+ // unreachable locally. Gating on the code would make the whole fix miss its+ // own bug if a runtime picks a code outside the set, and the code buys+ // nothing at this boundary anyway: a runtime that states the session is+ // unusable has said so whatever number it attaches. The wording carries the+ // decision — which is what isACPSessionNotFound's own doc already concedes+ // about the generic -32000 and -32603.+ //+ // Message and Data only. acpRPCError.Method holds "session/resume", whose+ // own "session" would otherwise satisfy the noun half of every error this+ // RPC can produce and quietly turn the predicate into the exclusion rule+ // the doc above rejects.+ text := strings.ToLower(rpcErr.Message + " " + rpcErr.Data)+ // Delete request-shaped complaints before matching rather than returning+ // false on sight of one. A message can carry both — "invalid session+ // request: session not found" — and vetoing the whole string would throw+ // away a real rejection sitting next to a complaint about our own call.+ //+ // This runs BEFORE both wording checks, which is why the isACPSessionNotFound+ // literals are consulted through acpSessionNotFoundWording rather than by+ // calling the helper on the raw error: "unknown session" is one of those+ // literals, so "unknown session capability requested" would otherwise be+ // answered true before the scrub ever ran.+ text = acpSessionRequestComplaintRe.ReplaceAllString(text, " ")+ return acpSessionNotFoundWording(text) || acpSessionUnusableRe.MatchString(text)+}++// acpSessionUnusableRe matches a runtime saying the session id itself is no+// good. Two shapes, because that is how the wordings actually read:+//+// Invalid session identifier "27d8031c-…" (qodercli — verdict, then noun)+// unknown session <id> (Reasonix — verdict, then noun)+// Session not found (Hermes — noun, then verdict)+// session ses_abc does not exist (noun, id, then verdict)+// No session found with id ses_abc (Kiro — the "no <noun> found" shape)+//+// The verdict-first form demands the noun IMMEDIATELY after the verdict, and the+// noun-first form allows only an "id"/"identifier" word and one id-shaped token+// in between. That tightness is the whole safety argument, and a looser window+// is not a detail: the natural English for errors this RPC really does produce+// puts the same two halves a few words apart while meaning something entirely+// different — "unknown error while loading session", "invalid token for session+// abc", "invalid credentials for this session", "cwd does not exist for session+// abc". Those are auth and infrastructure failures, which Result.ResumeRejected+// is explicitly documented never to flag, and matching one does not merely waste+// a retry: it retires a live conversation's pointer and forks it irreversibly.+// TestIsACPResumeRejected pins every one of them as a negative.+//+// The "no <noun> found" alternative is deliberately spelled out here even+// though isACPSessionNotFound already matches that literal: that helper keeps+// its error-code gate, so relying on it for this shape would quietly reinstate+// the code dependency this predicate exists without. Kiro's real frame is+// -32603 and would pass the gate anyway; the point is that the wording alone+// decides, for every shape and not just the ones in the regex.+var acpSessionUnusableRe = regexp.MustCompile(+ `(no such|unknown|invalid|expired|unrecogni[sz]ed|nonexistent|missing)\s+(session|conversation|thread)` ++ `|no\s+(session|conversation|thread)\s+found` ++ `|(session|conversation|thread)(\s+(id|identifier))?(\s+"?[\w-]+"?)?\s+(is\s+)?(not found|does not exist|doesn't exist|no longer exists|expired|invalid|unknown|unrecogni[sz]ed)`)++// acpSessionRequestComplaintRe matches the one verdict-first shape that is NOT+// about the recorded session: a generic noun after it turns the phrase into a+// complaint about the call we just made. "Invalid session parameters: cwd must+// be absolute", "invalid session request" and "unknown session capability+// requested" all say our request was malformed, not that the transcript is+// gone — and a fresh session would fail identically, after the pointer had+// already been retired. Reaching one of these needs a client-side bug first,+// which is why it is a stop-list rather than a redesign.+var acpSessionRequestComplaintRe = regexp.MustCompile(+ `(no such|unknown|invalid|expired|unrecogni[sz]ed|nonexistent|missing)\s+(session|conversation|thread)\s+(params?|parameters?|request|requests|config|configuration|option|options|capability|capabilities|mode|setup)`)++// setupFailureWithholdsSessionID reports whether a run that failed during setup+// — after session/new, before session/prompt — must report an empty SessionID+// instead of the id it just created.+//+// True exactly when the session is fresh. Such a session has no transcript+// behind it: no prompt was ever sent, so there is no conversation to continue+// and withholding the id costs one extra session/new next turn. Publishing it+// bets that every ACP runtime persists a never-prompted session, and qodercli+// does not — it exits without writing one, leaving the daemon pinned to an id+// that does not exist and every later message in that chat failing to resume it+// forever (GH #8116).+//+// A RESUMED session is the opposite case and keeps today's behaviour: its+// transcript predates this run, so the id stays unless the runtime actively+// rejected it.+func setupFailureWithholdsSessionID(opts ExecOptions) bool {+ return opts.ResumeSessionID == ""+}++// classifyACPResumeFailure turns an error from session/resume or session/load+// into this turn's terminal status, message and resume-rejection flag. Every+// ACP backend that resumes shares it so the six that used to return a bare+// failed Result cannot drift apart from each other again.+//+// Cancellation and timeout are checked FIRST, and that ordering is deliberate.+// A user who cancels mid-resume, or a turn that runs out of budget, must never+// be reported as a rejected session: ResumeRejected licenses the daemon to+// abandon the recorded conversation and re-run the whole task from a fresh one,+// which is the opposite of what a cancel asked for. When a real rejection and a+// cancel race, reading it as a cancel is the recoverable mistake — the pointer+// survives, and the next turn resumes, gets the same rejection with no cancel+// in flight, and self-heals then.+func classifyACPResumeFailure(runCtx context.Context, backend, rpc string, err error, timeout time.Duration, logger *slog.Logger) (status, errText string, rejected bool) {+ switch runCtx.Err() {+ case context.DeadlineExceeded:+ if timeout > 0 {+ return "timeout", fmt.Sprintf("%s timed out after %s during %s", backend, timeout, rpc), false+ }+ return "timeout", fmt.Sprintf("%s timed out during %s", backend, rpc), false+ case context.Canceled:+ return "aborted", "execution cancelled", false+ }+ errText = fmt.Sprintf("%s %s failed: %v", backend, rpc, err)+ if !isACPResumeRejected(err) {+ return "failed", errText, false+ }+ if logger != nil {+ logger.Warn("resumed session rejected by the runtime; the daemon will retry from a fresh session",+ "backend", backend,+ "rpc", rpc,+ "error", err,+ )+ }+ return "failed", errText, true+}diff --git a/server/pkg/agent/acp_session_test.go b/server/pkg/agent/acp_session_test.gonew file mode 100644index 0000000000..12b85ab623--- /dev/null+++ b/server/pkg/agent/acp_session_test.go@@ -0,0 +1,374 @@+package agent++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "path/filepath"+ "testing"+ "time"+)++// TestIsACPResumeRejected pins the widened resume-boundary predicate. The two+// halves that matter are the qodercli frame from GH #8116 — the wording that+// wedged a conversation because no literal in isACPSessionNotFound matched it —+// and the negatives, which are the whole reason this is a phrase predicate and+// not "any error from session/resume".+func TestIsACPResumeRejected(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ err error+ want bool+ }{+ {+ name: "qodercli invalid session identifier",+ // The frame that made GH #8116 permanent: qodercli 1.1.25 answers+ // session/resume for an id it never persisted with invalid_params+ // and this wording. The code was already accepted; only the phrase+ // was missing, so the rejection was invisible to the daemon.+ err: &acpRPCError{+ Method: "session/resume",+ Code: -32602,+ Message: `Invalid session identifier "27d8031c-9fea-4bda-9d42-37c36fa9aebf".`,+ Data: `{"sessionId":"27d8031c-9fea-4bda-9d42-37c36fa9aebf"}`,+ },+ want: true,+ },+ {+ name: "everything isACPSessionNotFound already matched still matches",+ err: &acpRPCError{Method: "session/resume", Code: -32603, Message: "Session not found"},+ want: true,+ },+ {+ name: "session expired",+ err: &acpRPCError{Method: "session/load", Code: -32602, Message: "session expired"},+ want: true,+ },+ {+ name: "session does not exist",+ err: &acpRPCError{Method: "session/load", Code: -32603, Message: "Internal error", Data: "the conversation does not exist"},+ want: true,+ },+ {+ name: "unreachable mcp server whose data echoes the session id",+ // The false positive the adjacency window exists to stop. Both+ // halves are present in the string — "Invalid params" and a+ // sessionId in `data` — but they are not about each other, and+ // discarding the pointer here would fork a healthy conversation+ // over a transient MCP outage.+ err: &acpRPCError{+ Method: "session/resume",+ Code: -32602,+ Message: "Invalid params: mcpServers[0] transport unreachable",+ Data: `{"sessionId":"ses_healthy"}`,+ },+ want: false,+ },+ {+ // The eight below are the shapes a looser adjacency window let+ // through: ordinary English error prose that happens to put a+ // verdict word and the word "session" a few tokens apart while+ // meaning something entirely different. Four are auth or unknown+ // failures, which Result.ResumeRejected is documented never to+ // flag; matching any of them forks a live conversation.+ name: "unknown error while loading session",+ err: &acpRPCError{Method: "session/resume", Code: -32603, Message: "unknown error while loading session"},+ want: false,+ },+ {+ name: "unknown error restoring a named session",+ err: &acpRPCError{Method: "session/resume", Code: -32603, Message: "unknown error restoring session ses_abc"},+ want: false,+ },+ {+ name: "invalid token for session",+ err: &acpRPCError{Method: "session/load", Code: -32602, Message: "invalid token for session ses_abc"},+ want: false,+ },+ {+ name: "invalid credentials for this session",+ err: &acpRPCError{Method: "session/load", Code: -32603, Message: "invalid credentials for this session"},+ want: false,+ },+ {+ name: "sessionid is the wrong type",+ err: &acpRPCError{Method: "session/resume", Code: -32602, Message: "Invalid params: sessionId must be a string"},+ want: false,+ },+ {+ name: "missing cwd reported against a session",+ err: &acpRPCError{Method: "session/load", Code: -32603, Message: "cwd does not exist for session ses_abc"},+ want: false,+ },+ {+ name: "session config option rejected",+ err: &acpRPCError{Method: "session/load", Code: -32602, Message: "session config option invalid"},+ want: false,+ },+ {+ name: "model rejected inside a session",+ err: &acpRPCError{Method: "session/resume", Code: -32602, Message: "session ses_abc: model gpt-x invalid"},+ want: false,+ },+ {+ name: "session id spelled out before the verdict",+ err: &acpRPCError{Method: "session/resume", Code: -32602, Message: "session ses_abc does not exist"},+ want: true,+ },+ {+ name: "provider rate limit during resume",+ err: &acpRPCError{Method: "session/resume", Code: -32603, Message: "Internal error", Data: "upstream provider returned HTTP 429"},+ want: false,+ },+ {+ name: "auth failure during resume keeps the session",+ err: &acpRPCError{Method: "session/load", Code: -32603, Message: "Could not resolve authentication method"},+ want: false,+ },+ {+ // Steve's re-review nit: a generic noun after the verdict turns the+ // phrase into a complaint about the call we just made, not about+ // the recorded session. A fresh session would fail identically —+ // after the pointer had already been retired.+ name: "invalid session parameters is about our request",+ err: &acpRPCError{Method: "session/resume", Code: -32602, Message: "Invalid session parameters: cwd must be absolute"},+ want: false,+ },+ {+ name: "invalid session request is about our request",+ err: &acpRPCError{Method: "session/load", Code: -32602, Message: "invalid session request"},+ want: false,+ },+ {+ name: "unknown session capability is about our request",+ err: &acpRPCError{Method: "session/resume", Code: -32602, Message: "unknown session capability requested"},+ want: false,+ },+ {+ // The stop-list deletes the complaint rather than vetoing the whole+ // message, so a real rejection sitting next to one still counts.+ name: "request complaint alongside a real rejection still counts",+ err: &acpRPCError{Method: "session/resume", Code: -32602, Message: "invalid session request: session not found"},+ want: true,+ },+ {+ // Kiro's wording, under a code OUTSIDE the accepted set. It matches+ // via the regex rather than via isACPSessionNotFound, which keeps+ // its code gate — otherwise this predicate's code-independence+ // would silently not hold for the three inherited literals.+ name: "kiro no-session-found wording under an unusual code",+ err: &acpRPCError{Method: "session/load", Code: -32099, Message: "Internal error", Data: "No session found with id ses_abc"},+ want: true,+ },+ {+ // Captured by hand from qodercli 1.0.20 (`--yolo --acp`, not logged+ // in): session/resume answers with this before it ever looks the id+ // up. Proof that this RPC really does surface errors with nothing to+ // do with the session — under -32000, which IS an accepted+ // session-error code — so the wording, not the code, has to carry+ // the decision.+ name: "qodercli auth gate on session/resume",+ err: &acpRPCError{Method: "session/resume", Code: -32000, Message: "Authentication required: Authentication is required."},+ want: false,+ },+ {+ // Deliberately matches despite an unusual code: gating on the code+ // set would make this fix miss its own bug if qodercli ever moved+ // off -32602, and a runtime naming the session unusable has said so+ // whatever number it attaches.+ name: "rejection wording under an unusual code still counts",+ err: &acpRPCError{Method: "session/resume", Code: -32099, Message: "Invalid session identifier"},+ want: true,+ },+ {+ name: "plain error is never a rejection",+ err: fmt.Errorf("session/resume: Invalid session identifier (code=-32602)"),+ want: false,+ },+ {+ name: "wrapped rpc error",+ err: fmt.Errorf("request failed: %w", &acpRPCError{Method: "session/resume", Code: -32602, Message: "Invalid session identifier"}),+ want: true,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := isACPResumeRejected(tc.err); got != tc.want {+ t.Errorf("isACPResumeRejected(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}++// TestClassifyACPResumeFailureCancelAndTimeoutAreNotRejections pins the+// ordering that keeps a cancel from being read as a dead session.+// ResumeRejected licenses the daemon to abandon the recorded conversation and+// re-run the task from a fresh session — precisely what a user who just hit+// cancel did not ask for.+func TestClassifyACPResumeFailureCancelAndTimeoutAreNotRejections(t *testing.T) {+ t.Parallel()++ rejection := &acpRPCError{Method: "session/resume", Code: -32602, Message: "Invalid session identifier"}++ t.Run("cancelled", func(t *testing.T) {+ t.Parallel()+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ status, _, rejected := classifyACPResumeFailure(ctx, "qoder", "session/resume", rejection, time.Minute, nil)+ if status != "aborted" {+ t.Errorf("status = %q, want aborted", status)+ }+ if rejected {+ t.Error("a cancelled resume must not report ResumeRejected")+ }+ })++ t.Run("deadline exceeded", func(t *testing.T) {+ t.Parallel()+ ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))+ defer cancel()+ status, errText, rejected := classifyACPResumeFailure(ctx, "kiro", "session/load", rejection, 30*time.Second, nil)+ if status != "timeout" {+ t.Errorf("status = %q, want timeout", status)+ }+ if rejected {+ t.Error("a timed-out resume must not report ResumeRejected")+ }+ if errText == "" {+ t.Error("expected a non-empty timeout message")+ }+ })++ t.Run("live context reports the rejection", func(t *testing.T) {+ t.Parallel()+ status, errText, rejected := classifyACPResumeFailure(context.Background(), "qoder", "session/resume", rejection, time.Minute, nil)+ if status != "failed" {+ t.Errorf("status = %q, want failed", status)+ }+ if !rejected {+ t.Error("expected ResumeRejected=true for a rejected session id")+ }+ if want := "qoder session/resume failed: "; len(errText) < len(want) || errText[:len(want)] != want {+ t.Errorf("error text = %q, want it to keep the %q prefix", errText, want)+ }+ })++ t.Run("non-rejection keeps the pointer", func(t *testing.T) {+ t.Parallel()+ netErr := &acpRPCError{Method: "session/resume", Code: -32603, Message: "Internal error", Data: "upstream provider returned HTTP 429"}+ status, _, rejected := classifyACPResumeFailure(context.Background(), "qoder", "session/resume", netErr, time.Minute, nil)+ if status != "failed" {+ t.Errorf("status = %q, want failed", status)+ }+ if rejected {+ t.Error("a rate-limited resume must not discard the conversation pointer")+ }+ })+}++// fakeACPRejectedResumeScript answers initialize (advertising the auth method+// Grok insists on, harmless to the others) and then rejects whichever resume+// RPC the backend uses with qodercli 1.1.25's wording from GH #8116.+//+// The message deliberately carries no inner quotes: `sh` printf mangles+// backslash-escaped quotes inconsistently, and a malformed error frame is+// silently dropped by the ACP client, which shows up as a hung request rather+// than a failed assertion.+func fakeACPRejectedResumeScript(rpc string) 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,"authMethods":[{"id":"xai.api_key","name":"API key"}],"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"authenticate"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"+ ;;+ *'"method":"` + rpc + `"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32602,"message":"Invalid session identifier ses_ghost.","data":{"sessionId":"ses_ghost"}}}\n' "$id"+ ;;+ esac+done+`+}++// TestACPBackendsReportRejectedResume is the end-to-end guard for GH #8116:+// every ACP backend that resumes must turn its runtime's rejection into+// ResumeRejected, because that flag is the ONLY positive evidence+// shouldRetryWithFreshSession accepts. Without it the daemon reads the bare+// failure as "checked, not a rejection", keeps the dead pointer, and every+// later message in that conversation replays the same rejection forever.+//+// Table-driven across all six on purpose. These call sites were six separate+// copies of the same bug, and the neighbouring history in this package — the+// same resume defect fixed one adapter at a time for Kiro, then Kimi, then+// Anthropic — is what happens when one backend gets a regression test and the+// rest do not.+func TestACPBackendsReportRejectedResume(t *testing.T) {+ t.Parallel()++ cases := []struct {+ agentType string+ binary string+ rpc string+ env map[string]string+ }{+ {agentType: "qoder", binary: "qodercli", rpc: "session/resume"},+ {agentType: "hermes", binary: "hermes", rpc: "session/resume"},+ {agentType: "kimi", binary: "kimi", rpc: "session/resume"},+ {agentType: "kiro", binary: "kiro", rpc: "session/load"},+ {agentType: "traecli", binary: "traecli", rpc: "session/load"},+ // Grok refuses to reach session/load without a credential; supply one+ // through Config so the test does not depend on ambient env.+ {agentType: "grok", binary: "grok", rpc: "session/load", env: map[string]string{"XAI_API_KEY": "test-only-key"}},+ }++ for _, tc := range cases {+ t.Run(tc.agentType, func(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), tc.binary)+ writeTestExecutable(t, fakePath, []byte(fakeACPRejectedResumeScript(tc.rpc)))++ backend, err := New(tc.agentType, Config{ExecutablePath: fakePath, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Env: tc.env})+ if err != nil {+ t.Fatalf("new %s backend: %v", tc.agentType, err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 30 * time.Second,+ ResumeSessionID: "ses_ghost",+ })+ 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 != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !result.ResumeRejected {+ t.Fatalf("expected ResumeRejected=true so the daemon retries from a fresh session, got false (error=%q)", result.Error)+ }+ case <-time.After(20 * time.Second):+ t.Fatal("timeout waiting for result")+ }+ })+ }+}diff --git a/server/pkg/agent/dim.go b/server/pkg/agent/dim.goindex 419275e99c..8c36d91ee5 100644--- a/server/pkg/agent/dim.go+++ b/server/pkg/agent/dim.go@@ -503,8 +503,6 @@ func (b *dimBackend) Execute(ctx context.Context, prompt string, opts ExecOption}c.sessionID = sessionID- // Early session pin so a cancelled run still preserves resume pointer.- msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})b.cfg.Logger.Info("dim session ready", "session_id", sessionID, "resumed", !freshSession)// Dim's ACP server hardcodes a read-only permission preset at session@@ -532,6 +530,10 @@ func (b *dimBackend) Execute(ctx context.Context, prompt string, opts ExecOptioncloseCtx, closeCancel := context.WithTimeout(context.Background(), dimSessionCloseTimeout)_, _ = c.request(closeCtx, "session/close", map[string]any{"sessionId": sessionID})closeCancel()+ if setupFailureWithholdsSessionID(opts) {+ // Closed just above, and never prompted either way.+ sessionID = ""+ }resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), SessionID: sessionID, ResumeRejected: resumeRejected}return}@@ -551,6 +553,10 @@ func (b *dimBackend) Execute(ctx context.Context, prompt string, opts ExecOptioncloseCtx, closeCancel := context.WithTimeout(context.Background(), dimSessionCloseTimeout)_, _ = c.request(closeCtx, "session/close", map[string]any{"sessionId": sessionID})closeCancel()+ if setupFailureWithholdsSessionID(opts) {+ // Closed just above, and never prompted either way.+ sessionID = ""+ }resCh <- Result{Status: finalStatus,Error: finalError,@@ -575,6 +581,16 @@ func (b *dimBackend) Execute(ctx context.Context, prompt string, opts ExecOptionuserText = opts.SystemPrompt + "\n\n---\n\n" + prompt}+ // Session pin for the daemon (PinTaskSession keys off+ // MessageStatus+SessionID), deliberately sent only once setup has+ // succeeded and the prompt is about to go out. Pinning right after+ // session creation used to publish the id before set_model could fail,+ // and FailAgentTask merges session_id with COALESCE — so a setup failure+ // could no longer take the id back and left a ghost pointer on the task+ // row for the next turn to resume forever (GH #8116). A cancel between+ // here and the prompt response is still covered: this send happens first.+ msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})+_, err = c.request(runCtx, "session/prompt", map[string]any{"sessionId": sessionID,"prompt": []map[string]any{diff --git a/server/pkg/agent/dim_test.go b/server/pkg/agent/dim_test.goindex 1020923932..e791106884 100644--- a/server/pkg/agent/dim_test.go+++ b/server/pkg/agent/dim_test.go@@ -492,11 +492,21 @@ func TestDimConfigFailClosesSession(t *testing.T) {}}-// TestDimConfigFailThenResumeReestablishes verifies the "first setup fails →-// next run resumes" path (review #4): when the first run's set_config_option-// fails, session/close is sent; a second run that resumes the same session-// re-applies set_config_option (fail-closed) and succeeds.-func TestDimConfigFailThenResumeReestablishes(t *testing.T) {+// TestDimFreshConfigFailureWithholdsSessionID pins the ghost-pointer contract+// (GH #8116) on dim's set_config_option branch: a fresh session that died+// during setup, before any prompt went out, must not be published as a resume+// pointer.+//+// dim is the runtime where this is least obviously necessary and most clearly+// still right. It closes the session on this path and persists early enough+// that the id would in fact still load — but there is no conversation behind+// it, because no prompt was ever sent. Withholding it costs one extra+// session/new on the next turn; publishing it is a bet that every ACP runtime+// persists a never-prompted session, and qodercli does not, which is what+// wedged a conversation forever in the first place. The contract is uniform+// across backends on purpose: making it per-runtime is how the neighbouring+// resume bugs got fixed one adapter at a time while the rest stayed broken.+func TestDimFreshConfigFailureWithholdsSessionID(t *testing.T) {t.Parallel()dir := t.TempDir()requestsFile := filepath.Join(dir, "requests.jsonl")@@ -508,7 +518,44 @@ func TestDimConfigFailThenResumeReestablishes(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()- // Run A: fresh session, set_config_option fails on the first call.+ session, err := b.Execute(ctx, "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ Timeout: 20 * 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("expected status=failed, got %q", result.Status)+ }+ if result.SessionID != "" {+ t.Fatalf("expected the never-prompted session id to be withheld, got %q", result.SessionID)+ }+ if result.ResumeRejected {+ t.Fatal("a fresh session cannot be resume-rejected; the daemon must not re-run this task")+ }+}++// TestDimResumeReappliesConfig pins the fail-closed config re-application on+// resume (review #4): a resumed session re-sends set_config_option instead of+// trusting whatever state the earlier run left behind. It resumes a session+// that completed a prompt — the only kind that now carries a resume pointer.+func TestDimResumeReappliesConfig(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ requestsFile := filepath.Join(dir, "requests.jsonl")+ b := newDimTestBackend(t, requestsFile)++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ // Run A: a fresh run that reaches session/prompt and completes, so it has+ // a real conversation to hand forward.sessionA, err := b.Execute(ctx, "test prompt", ExecOptions{Cwd: t.TempDir(),Timeout: 20 * time.Second,@@ -521,15 +568,14 @@ func TestDimConfigFailThenResumeReestablishes(t *testing.T) {}}()resultA := <-sessionA.Result- if resultA.Status != "failed" {- t.Fatalf("run A: expected status=failed, got %q", resultA.Status)+ if resultA.Status != "completed" {+ t.Fatalf("run A: expected status=completed, got %q (error=%q)", resultA.Status, resultA.Error)}if resultA.SessionID == "" {- t.Fatal("run A: expected a session id despite the config failure")+ t.Fatal("run A: a completed run must publish its session id")}- // Run B: resume the same session. set_config_option should succeed this- // time (DIM_CONFIG_FAIL_ONCE only fails once) and the run should complete.+ // Run B: resume it.sessionB, err := b.Execute(ctx, "test prompt", ExecOptions{Cwd: t.TempDir(),Timeout: 20 * time.Second,@@ -547,19 +593,17 @@ func TestDimConfigFailThenResumeReestablishes(t *testing.T) {t.Fatalf("run B: expected status=completed, got %q (error=%q)", resultB.Status, resultB.Error)}if resultB.ResumeRejected {- t.Fatal("run B: ResumeRejected should be false — the session was loadable after session/close")+ t.Fatal("run B: ResumeRejected should be false — the session was loadable")}- // Verify run B re-applied set_config_option (fail-closed on resume).reqs := readDimRequests(t, requestsFile)if !strings.Contains(reqs, "session/load") {t.Fatal("run B: expected session/load")}- // set_config_option should appear at least 3 times: 1 failed in run A,- // 2 successful in run B (permission + mode).- count := strings.Count(reqs, "set_config_option")- if count < 3 {- t.Fatalf("expected at least 3 set_config_option calls (1 fail + 2 re-apply on resume), got %d", count)+ // set_config_option should appear at least 4 times: 2 in run A and 2+ // re-applied in run B (permission + mode).+ if count := strings.Count(reqs, "set_config_option"); count < 4 {+ t.Fatalf("expected at least 4 set_config_option calls (2 fresh + 2 re-applied on resume), got %d", count)}}diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.goindex 7b63571dd0..0eb52e2ecd 100644--- a/server/pkg/agent/grok.go+++ b/server/pkg/agent/grok.go@@ -330,9 +330,13 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio"mcpServers": mcpServers,})if err != nil {- finalStatus = "failed"- finalError = fmt.Sprintf("grok session/load failed: %v", err)- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ // A runtime that refuses the recorded id has to say so here:+ // without ResumeRejected the daemon reads the bare failure as+ // "checked, not a rejection", keeps the pointer and replays the+ // same dead session on every later turn (GH #8116).+ finalStatus, finalError, resumeRejected = classifyACPResumeFailure(+ runCtx, "grok", "session/load", err, timeout, b.cfg.Logger)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}return}var changed bool@@ -371,8 +375,6 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio}c.sessionID = sessionID- // Early session pin so a cancelled run still preserves resume pointer.- msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})b.cfg.Logger.Info("grok session created", "session_id", sessionID)if opts.Model != "" {@@ -383,7 +385,9 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptiob.cfg.Logger.Warn("grok set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus = "failed"finalError = fmt.Sprintf("grok could not switch to model %q: %v", opts.Model, err)- if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if isACPSessionNotFound(err) {b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh","backend", "grok","session_id", sessionID,@@ -410,6 +414,16 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptiouserText = opts.SystemPrompt + "\n\n---\n\n" + prompt}+ // Session pin for the daemon (PinTaskSession keys off+ // MessageStatus+SessionID), deliberately sent only once setup has+ // succeeded and the prompt is about to go out. Pinning right after+ // session creation used to publish the id before set_model could fail,+ // and FailAgentTask merges session_id with COALESCE — so a setup failure+ // could no longer take the id back and left a ghost pointer on the task+ // row for the next turn to resume forever (GH #8116). A cancel between+ // here and the prompt response is still covered: this send happens first.+ msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})+streamingCurrentTurn.Store(true)_, err = c.request(runCtx, "session/prompt", map[string]any{"sessionId": sessionID,diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex f3e2fe0d06..34c7f2ce18 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -513,9 +513,13 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt"mcpServers": mcpServers,})if err != nil {- finalStatus = "failed"- finalError = fmt.Sprintf("hermes session/resume failed: %v", err)- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ // A runtime that refuses the recorded id has to say so here:+ // without ResumeRejected the daemon reads the bare failure as+ // "checked, not a rejection", keeps the pointer and replays the+ // same dead session on every later turn (GH #8116).+ finalStatus, finalError, resumeRejected = classifyACPResumeFailure(+ runCtx, "hermes", "session/resume", err, timeout, b.cfg.Logger)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}return}sessionResult = result@@ -555,9 +559,6 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptc.sessionID = sessionIDb.cfg.Logger.Info("hermes session created", "session_id", sessionID)- // Mid-flight pin: daemon PinTaskSession keys off MessageStatus+SessionID.- trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})-// 3. If the caller picked a model (via agent.model from the// UI dropdown), ask hermes to switch the session to it// before we send any prompt. Hermes' _build_model_state@@ -599,7 +600,9 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptb.cfg.Logger.Warn("hermes set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus = "failed"finalError = fmt.Sprintf("hermes could not switch to model %q: %v", opts.Model, err)- if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if isACPSessionNotFound(err) {// On a resumed session with a model override, the dead// session surfaces here instead of at session/prompt.// Same fix as the prompt path below: clear the id so@@ -646,6 +649,16 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// just before the request so any history replay flushed during// initialize / session setup stays dropped, but every notification// belonging to this turn is processed.+ // Session pin for the daemon (PinTaskSession keys off+ // MessageStatus+SessionID), deliberately sent only once setup has+ // succeeded and the prompt is about to go out. Pinning right after+ // session creation used to publish the id before set_model could fail,+ // and FailAgentTask merges session_id with COALESCE — so a setup failure+ // could no longer take the id back and left a ghost pointer on the task+ // row for the next turn to resume forever (GH #8116). A cancel between+ // here and the prompt response is still covered: this send happens first.+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})+streamingCurrentTurn.Store(true)_, err = c.request(runCtx, "session/prompt", map[string]any{"sessionId": sessionID,@@ -1371,6 +1384,14 @@ func (e *acpRPCError) Error() string {return fmt.Sprintf("%s: %s (code=%d)", e.Method, e.Message, e.Code)}+// isACPSessionErrorCode reports whether a JSON-RPC error code is one the ACP+// runtimes have been observed to report a lost session under. It is a guard,+// not the decision: -32000 and -32603 are generic, so the wording checks in+// isACPSessionNotFound / isACPResumeRejected are what actually discriminate.+func isACPSessionErrorCode(code int) bool {+ return code == -32603 || code == -32602 || code == -32002 || code == -32000+}+// isACPSessionNotFound reports whether err is the agent rejecting a// session id it no longer knows. Runtimes signal this with codes and// wording that vary — Hermes says "Session not found" under -32603@@ -1389,10 +1410,16 @@ func isACPSessionNotFound(err error) bool {if !errors.As(err, &rpcErr) {return false}- if rpcErr.Code != -32603 && rpcErr.Code != -32602 && rpcErr.Code != -32002 && rpcErr.Code != -32000 {+ if !isACPSessionErrorCode(rpcErr.Code) {return false}- text := strings.ToLower(rpcErr.Message + " " + rpcErr.Data)+ return acpSessionNotFoundWording(strings.ToLower(rpcErr.Message + " " + rpcErr.Data))+}++// acpSessionNotFoundWording is the wording half of isACPSessionNotFound, split+// out so isACPResumeRejected can run it over text it has already scrubbed of+// request-shaped complaints. Callers pass lower-cased Message+Data.+func acpSessionNotFoundWording(text string) bool {return strings.Contains(text, "session not found") ||strings.Contains(text, "no session found") ||strings.Contains(text, "unknown session")diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.goindex 2ce75d1fca..154334a629 100644--- a/server/pkg/agent/kimi.go+++ b/server/pkg/agent/kimi.go@@ -258,9 +258,13 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio"mcpServers": mcpServers,})if err != nil {- finalStatus = "failed"- finalError = fmt.Sprintf("kimi session/resume failed: %v", err)- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ // A runtime that refuses the recorded id has to say so here:+ // without ResumeRejected the daemon reads the bare failure as+ // "checked, not a rejection", keeps the pointer and replays the+ // same dead session on every later turn (GH #8116).+ finalStatus, finalError, resumeRejected = classifyACPResumeFailure(+ runCtx, "kimi", "session/resume", err, timeout, b.cfg.Logger)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}return}var changed bool@@ -313,7 +317,9 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptiob.cfg.Logger.Warn("kimi set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus = "failed"finalError = fmt.Sprintf("kimi could not switch to model %q: %v", opts.Model, err)- if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if isACPSessionNotFound(err) {// On a resumed session with a model override, the dead// session surfaces here instead of at session/prompt.// Same fix as the prompt path below: clear the id sodiff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.goindex 2d32d01817..7bcb365040 100644--- a/server/pkg/agent/kimi_test.go+++ b/server/pkg/agent/kimi_test.go@@ -135,8 +135,13 @@ func TestKimiBackendSetModelFailureFailsTask(t *testing.T) {if !strings.Contains(result.Error, "model not available") {t.Errorf("expected error to surface upstream message, got %q", result.Error)}- if result.SessionID != "ses_fake" {- t.Errorf("expected session id to be preserved on failure, got %q", result.SessionID)+ // A fresh session that never reached session/prompt must NOT be+ // published as a resume pointer: the runtime may never have persisted+ // it, and a pointer to a session that does not exist wedges the whole+ // conversation forever (GH #8116). There is no transcript behind an id+ // that never ran a prompt, so nothing is lost by withholding it.+ if result.SessionID != "" {+ t.Errorf("expected the never-prompted session id to be withheld, got %q", result.SessionID)}case <-time.After(10 * time.Second):t.Fatal("timeout waiting for result")diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex ea6f0b1ba2..c148988c7b 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -268,9 +268,13 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio"mcpServers": mcpServers,})if err != nil {- finalStatus = "failed"- finalError = fmt.Sprintf("kiro session/load failed: %v", err)- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ // A runtime that refuses the recorded id has to say so here:+ // without ResumeRejected the daemon reads the bare failure as+ // "checked, not a rejection", keeps the pointer and replays the+ // same dead session on every later turn (GH #8116).+ finalStatus, finalError, resumeRejected = classifyACPResumeFailure(+ runCtx, "kiro", "session/load", err, timeout, b.cfg.Logger)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}return}// Apply the same defensive resolution kimi/hermes use: if@@ -327,7 +331,9 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiob.cfg.Logger.Warn("kiro set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus = "failed"finalError = fmt.Sprintf("kiro could not switch to model %q: %v", opts.Model, err)- if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if isACPSessionNotFound(err) {// On a resumed session with a model override, the dead// session surfaces here instead of at session/prompt.// Same fix as the prompt path below: clear the id sodiff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.goindex d15560f068..a8dbd2e122 100644--- a/server/pkg/agent/kiro_test.go+++ b/server/pkg/agent/kiro_test.go@@ -147,8 +147,13 @@ func TestKiroBackendSetModelFailureFailsTask(t *testing.T) {if !strings.Contains(result.Error, "model not available") {t.Errorf("expected error to surface upstream message, got %q", result.Error)}- if result.SessionID != "ses_new" {- t.Errorf("expected session id to be preserved on failure, got %q", result.SessionID)+ // A fresh session that never reached session/prompt must NOT be+ // published as a resume pointer: the runtime may never have persisted+ // it, and a pointer to a session that does not exist wedges the whole+ // conversation forever (GH #8116). There is no transcript behind an id+ // that never ran a prompt, so nothing is lost by withholding it.+ if result.SessionID != "" {+ t.Errorf("expected the never-prompted session id to be withheld, got %q", result.SessionID)}case <-time.After(10 * time.Second):t.Fatal("timeout waiting for result")diff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.goindex eed7584daf..e4937c50c9 100644--- a/server/pkg/agent/qoder.go+++ b/server/pkg/agent/qoder.go@@ -259,9 +259,13 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti"mcpServers": mcpServers,})if err != nil {- finalStatus = "failed"- finalError = fmt.Sprintf("qoder session/resume failed: %v", err)- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ // A runtime that refuses the recorded id has to say so here:+ // without ResumeRejected the daemon reads the bare failure as+ // "checked, not a rejection", keeps the pointer and replays the+ // same dead session on every later turn (GH #8116).+ finalStatus, finalError, resumeRejected = classifyACPResumeFailure(+ runCtx, "qoder", "session/resume", err, timeout, b.cfg.Logger)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}return}var changed bool@@ -310,7 +314,9 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOptib.cfg.Logger.Warn("qoder set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus = "failed"finalError = fmt.Sprintf("qoder could not switch to model %q: %v", opts.Model, err)- if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if isACPSessionNotFound(err) {// On a resumed session with a model override, the dead// session surfaces here instead of at session/prompt.// Clear the id so the daemon's resume-failure fallbackdiff --git a/server/pkg/agent/qoder_test.go b/server/pkg/agent/qoder_test.goindex 5c0f967e13..2a6f15922f 100644--- a/server/pkg/agent/qoder_test.go+++ b/server/pkg/agent/qoder_test.go@@ -310,8 +310,13 @@ func TestQoderBackendSetModelFailureFailsTask(t *testing.T) {if !strings.Contains(result.Error, "model not available") {t.Errorf("expected error to surface upstream message, got %q", result.Error)}- if result.SessionID != "ses_fake" {- t.Errorf("expected session id to be preserved on failure, got %q", result.SessionID)+ // A fresh session that never reached session/prompt must NOT be+ // published as a resume pointer: the runtime may never have persisted+ // it, and a pointer to a session that does not exist wedges the whole+ // conversation forever (GH #8116). There is no transcript behind an id+ // that never ran a prompt, so nothing is lost by withholding it.+ if result.SessionID != "" {+ t.Errorf("expected the never-prompted session id to be withheld, got %q", result.SessionID)}case <-time.After(10 * time.Second):t.Fatal("timeout waiting for result")diff --git a/server/pkg/agent/reasonix.go b/server/pkg/agent/reasonix.goindex 880621ffdd..80150249e0 100644--- a/server/pkg/agent/reasonix.go+++ b/server/pkg/agent/reasonix.go@@ -356,7 +356,9 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO}); err != nil {b.cfg.Logger.Warn("reasonix set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus, finalError = reasonixRequestFailure(runCtx, timeout, fmt.Sprintf("reasonix could not switch to model %q: %v", opts.Model, err))- if finalStatus == "failed" && opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if finalStatus == "failed" && isACPSessionNotFound(err) {// On a resumed session with a model override, the dead// session surfaces here instead of at session/prompt.// Same fix as the prompt path below: clear the id sodiff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.goindex 8c437ebaca..3967074e74 100644--- a/server/pkg/agent/traecli.go+++ b/server/pkg/agent/traecli.go@@ -272,9 +272,13 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp"mcpServers": mcpServers,})if err != nil {- finalStatus = "failed"- finalError = fmt.Sprintf("traecli session/load failed: %v", err)- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ // A runtime that refuses the recorded id has to say so here:+ // without ResumeRejected the daemon reads the bare failure as+ // "checked, not a rejection", keeps the pointer and replays the+ // same dead session on every later turn (GH #8116).+ finalStatus, finalError, resumeRejected = classifyACPResumeFailure(+ runCtx, "traecli", "session/load", err, timeout, b.cfg.Logger)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}return}var changed bool@@ -323,7 +327,9 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOpb.cfg.Logger.Warn("traecli set_session_model failed", "error", err, "requested_model", opts.Model)finalStatus = "failed"finalError = fmt.Sprintf("traecli could not switch to model %q: %v", opts.Model, err)- if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ if setupFailureWithholdsSessionID(opts) {+ sessionID = ""+ } else if isACPSessionNotFound(err) {b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh","backend", "traecli","session_id", sessionID,