Skip to content

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

Go

fix(daemon): retry with a fresh session only when the resume was actually rejected (MUL-4966) (#5715)

Bohan Jianga5a42846e665
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 9f823e988e..4e67fb4b98 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4637,10 +4637,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
return TaskResult{}, err
}
- // Fallback: if session resume failed before establishing a session, retry
- // with a fresh session. We check SessionID == "" to distinguish a resume
- // failure (no session established) from a failure during actual execution.
- if result.Status == "failed" && task.PriorSessionID != "" && result.SessionID == "" {
+ if shouldRetryWithFreshSession(result, task.PriorSessionID, tools, provider) {
firstUsage := result.Usage
taskLog.Warn("session resume failed, retrying with fresh session", "error", result.Error)
execOpts.ResumeSessionID = ""
@@ -4835,6 +4832,103 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
}
+// shouldRetryWithFreshSession reports whether a failed run that requested
+// --resume should be retried once from a fresh session.
+//
+// Two independent questions have to both answer yes, and conflating them is
+// how this went wrong before:
+//
+// 1. Would a fresh session even fix this? Only if the resume itself was
+// refused — the transcript is gone, or it belongs to another provider
+// account. result.ResumeRejected is the backend's positive evidence of
+// that, and where a backend can produce it, it is the whole answer.
+// Answering by exclusion alone would invert the burden of proof: the
+// failures a new session cures are a small enumerable set, while the
+// ones it cannot are open-ended. A network drop, a 429, a quota trip or
+// a provider 5xx has nothing to do with the session, so resetting it
+// discards the one recoverable thing — the conversation pointer — and
+// re-runs the task for nothing. provider_network in particular is
+// documented resume-safe in internal/service/task.go (retryableReasons,
+// MUL-4910): the platform's own retry is supposed to inherit the session
+// and continue the truncated conversation.
+//
+// Not every backend can answer, though, and a false ResumeRejected means
+// different things depending on who produced it: "checked, not a
+// rejection" from a capable backend, "could not tell" from one of the
+// five in agent.ResumeRejectionUndetectable. That is why provider is a
+// parameter — without it the compatibility branch below would silently
+// apply to every backend, second-guessing capable ones by exclusion.
+//
+// 2. Is re-running safe? Only if the agent executed no tool. tools == 0 does
+// not prove the run mutated nothing — it proves we observed no tool use,
+// which is the strongest signal available here — but it is what stands
+// between a retry and a duplicated side effect. Comment creation has no
+// idempotency key and a duplicate re-fires its @mention triggers; the
+// retry also reuses the same workdir, which is never reset between
+// attempts, so a retry after real work re-plans on top of its own
+// half-finished commits.
+func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, tools int32, provider string) bool {
+ if result.Status != "failed" || priorSessionID == "" || tools > 0 {
+ return false
+ }
+ // Positive evidence: the backend proved the resume was refused.
+ if result.ResumeRejected {
+ return true
+ }
+ // Everything below is a bounded compatibility path for the backends that
+ // cannot answer question 1 at all. For every other backend a false
+ // ResumeRejected is a real answer — it checked and this was not a
+ // rejection — so the gate stops here rather than second-guessing it by
+ // exclusion.
+ if !agent.ResumeRejectionUndetectable(provider) {
+ return false
+ }
+ // antigravity, copilot, cursor, deveco and opencode scrape SessionID out
+ // of stream output and have no rejection string captured anywhere, so an
+ // empty SessionID is the only thing they can offer. It proves no session
+ // was established this run, which is exactly what the gate relied on for
+ // every backend before ResumeRejected existed; keeping it preserves their
+ // recovery instead of silently removing it.
+ //
+ // Inventing rejection phrases for these five would be the alternative,
+ // and it is worse: no real output has been captured for any of them, and
+ // a false positive discards a recoverable session pointer.
+ return result.SessionID == "" && freshSessionMayHelp(result.Error)
+}
+
+// freshSessionMayHelp reports whether restarting the conversation could
+// plausibly fix errText. It answers "is this failure about the session at
+// all?", so every reason with a defined non-session remedy — wait, back off,
+// top up, re-auth, fix the config, install the binary — is excluded. Those
+// keep the session pointer so the platform's own retry can resume the
+// truncated conversation.
+//
+// What is left through is deliberately narrow: unknown, process failure and
+// unparseable output. A real resume rejection from one of these backends most
+// likely surfaces as exactly that — a non-zero exit or output we cannot
+// parse — since none of them reports one explicitly. Context overflow is also
+// allowed through, as starting over genuinely can clear it.
+func freshSessionMayHelp(errText string) bool {
+ switch taskfailure.Classify(errText) {
+ case taskfailure.ReasonAgentProviderNetwork,
+ taskfailure.ReasonAgentProviderCapacityOrRateLimit,
+ taskfailure.ReasonAgentProviderQuotaLimit,
+ taskfailure.ReasonAgentProviderServerError,
+ taskfailure.ReasonAgentProviderAuthOrAccess,
+ taskfailure.ReasonAgentMissingConfig,
+ taskfailure.ReasonAgentModelNotFoundOrUnavailable,
+ taskfailure.ReasonAgentRuntimeMissingExecutable,
+ taskfailure.ReasonAgentRuntimeVersionUnsupported,
+ // Defensive: a timeout normally carries its own terminal status and
+ // never reaches this gate, but if one is ever classified out of a
+ // "failed" result, re-running the whole task is not the answer.
+ taskfailure.ReasonAgentTimeout:
+ return false
+ default:
+ return true
+ }
+}
+
// executeAndDrain runs a backend, drains its message stream (forwarding to the
// server), and waits for the final result. msgSeq numbers the reported task
// messages and is owned by the caller so a same-task retry continues the
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 5a46831727..efc85d4531 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -1443,7 +1443,7 @@ func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
fb := &fakeBackend{
results: []agent.Result{
- {Status: "failed", Error: "session not found", Usage: map[string]agent.TokenUsage{
+ {Status: "failed", Error: "no conversation found", ResumeRejected: true, Usage: map[string]agent.TokenUsage{
"m1": {InputTokens: 5},
}},
{Status: "completed", Output: "done", SessionID: "new-sess", Usage: map[string]agent.TokenUsage{
@@ -1455,7 +1455,7 @@ func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
// First attempt: resume fails (no SessionID in result).
opts := agent.ExecOptions{ResumeSessionID: "stale-id"}
var msgSeq atomic.Int32
- result, _, err := d.executeAndDrain(ctx, fb, "prompt", opts, taskLog, "task-1", &msgSeq)
+ result, tools, err := d.executeAndDrain(ctx, fb, "prompt", opts, taskLog, "task-1", &msgSeq)
if err != nil {
t.Fatalf("first call error: %v", err)
}
@@ -1463,8 +1463,8 @@ func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
t.Fatalf("expected failed result with empty SessionID, got %+v", result)
}
- // Simulate the retry logic from runTask.
- if result.Status == "failed" && result.SessionID == "" {
+ // Mirrors the retry in runTask, gated on the same production predicate.
+ if shouldRetryWithFreshSession(result, opts.ResumeSessionID, tools, "claude") {
firstUsage := result.Usage
opts.ResumeSessionID = ""
retryResult, _, retryErr := d.executeAndDrain(ctx, fb, "prompt", opts, taskLog, "task-1", &msgSeq)
@@ -1663,7 +1663,7 @@ func TestExecuteAndDrain_ContextCancelled_FlushesPendingTranscript(t *testing.T)
}
}
-func TestExecuteAndDrain_NoRetryWhenSessionEstablished(t *testing.T) {
+func TestExecuteAndDrain_NoRetryAfterToolsExecuted(t *testing.T) {
t.Parallel()
d := newTestDaemon(t)
@@ -1675,21 +1675,334 @@ func TestExecuteAndDrain_NoRetryWhenSessionEstablished(t *testing.T) {
}
opts := agent.ExecOptions{ResumeSessionID: "some-id"}
- result, _, err := d.executeAndDrain(context.Background(), fb, "p", opts, slog.Default(), "t", new(atomic.Int32))
+ result, tools, err := d.executeAndDrain(context.Background(), fb, "p", opts, slog.Default(), "t", new(atomic.Int32))
if err != nil {
t.Fatal(err)
}
- // SessionID is set → session was established → should NOT retry.
- shouldRetry := result.Status == "failed" && result.SessionID == ""
- if shouldRetry {
- t.Fatal("should not retry when SessionID is present")
+ // A run that executed tools may have mutated the world (posted a comment,
+ // opened a PR, written commits into the reused workdir). Re-running it
+ // from scratch would duplicate those side effects, so the fallback must
+ // stay out regardless of what the backend reported as SessionID.
+ if shouldRetryWithFreshSession(result, opts.ResumeSessionID, tools+1, "claude") {
+ t.Fatal("should not retry once tools have executed")
}
if int(fb.idx.Load()) != 1 {
t.Fatalf("expected 1 call, got %d", fb.idx.Load())
}
}
+// A mid-stream provider disconnect on a resumed run must leave the session
+// pointer alone: internal/service/task.go treats provider_network as
+// resume-safe and expects its retry to continue the truncated conversation.
+// If the daemon reset the session first, that contract would be unsatisfiable.
+func TestExecuteAndDrain_NetworkFailureKeepsResumeSession(t *testing.T) {
+ t.Parallel()
+
+ d := newTestDaemon(t)
+
+ fb := &fakeBackend{
+ results: []agent.Result{
+ {
+ Status: "failed",
+ Error: "API Error: Connection closed mid-response",
+ SessionID: "live-sess",
+ },
+ },
+ }
+
+ opts := agent.ExecOptions{ResumeSessionID: "live-sess"}
+ result, tools, err := d.executeAndDrain(context.Background(), fb, "p", opts, slog.Default(), "t", new(atomic.Int32))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if result.ResumeRejected {
+ t.Fatal("a network drop must not be reported as a rejected resume")
+ }
+ if shouldRetryWithFreshSession(result, opts.ResumeSessionID, tools, "claude") {
+ t.Fatal("network failure must not trigger a fresh-session retry")
+ }
+ if int(fb.idx.Load()) != 1 {
+ t.Fatalf("expected exactly 1 call, got %d", fb.idx.Load())
+ }
+ // The pointer the platform retry needs is still intact.
+ if result.SessionID != "live-sess" {
+ t.Fatalf("expected session to survive, got %q", result.SessionID)
+ }
+}
+
+func TestShouldRetryWithFreshSession(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ result agent.Result
+ priorSessionID string
+ tools int32
+ // provider defaults to claude — a backend that CAN detect rejections,
+ // so cases that leave it unset assert the capable-backend contract.
+ provider string
+ want bool
+ }{
+ {
+ name: "rejected resume before any tool retries",
+ result: agent.Result{Status: "failed", Error: "no conversation found", ResumeRejected: true},
+ priorSessionID: "stale-id",
+ want: true,
+ },
+ {
+ // The reported bug: the session belongs to another provider
+ // account and the backend echoes the requested id back on the
+ // rejection, so SessionID stays non-empty. The backend still
+ // reports ResumeRejected, which is what the gate reads now.
+ name: "account rejection echoing session id retries",
+ result: agent.Result{
+ Status: "failed",
+ Error: "400 此 session 已绑定另外的ai账号,请执行 /new 开启新 session",
+ SessionID: "stale-id",
+ ResumeRejected: true,
+ },
+ priorSessionID: "stale-id",
+ want: true,
+ },
+ {
+ // qwen-code 0.20.0's real wording, from
+ // pkg/agent/testdata/qwen-code-0.20.0-resume-not-found.stderr.txt.
+ // The backend reports no session at all here, so before the
+ // phrase was recognised this path silently lost its recovery.
+ name: "qwen stale session rejection retries",
+ result: agent.Result{
+ Status: "failed",
+ Error: "No saved session found with ID session-redacted. Run `qwen --resume` without an ID to choose from existing sessions.",
+ ResumeRejected: true,
+ },
+ priorSessionID: "session-redacted",
+ want: true,
+ },
+ {
+ name: "no resume requested never retries",
+ result: agent.Result{Status: "failed", Error: "boom", ResumeRejected: true},
+ priorSessionID: "",
+ want: false,
+ },
+
+ // The compatibility path for backends that cannot detect a rejection
+ // (antigravity, copilot, cursor, deveco, opencode). An empty
+ // SessionID is all they can offer, and it only proves no session was
+ // established — so it still gates a retry, but only for failures a
+ // fresh session could plausibly cure.
+ {
+ name: "undetectable backend with no session established retries",
+ result: agent.Result{Status: "failed", Error: "agent exited before dispatching"},
+ priorSessionID: "stale-id",
+ provider: "copilot",
+ want: true,
+ },
+ {
+ name: "undetectable backend that established a session does not retry",
+ result: agent.Result{Status: "failed", Error: "agent exited before dispatching", SessionID: "live-sess"},
+ priorSessionID: "stale-id",
+ provider: "copilot",
+ want: false,
+ },
+ {
+ // The regression that motivated the positive signal: without the
+ // classification guard, every unsignalled network blip would
+ // reset the session these backends were about to resume.
+ name: "undetectable backend network drop does not retry",
+ result: agent.Result{Status: "failed", Error: "API Error: Connection closed mid-response"},
+ priorSessionID: "stale-id",
+ provider: "cursor",
+ want: false,
+ },
+ {
+ name: "undetectable backend rate limit does not retry",
+ result: agent.Result{Status: "failed", Error: "API Error: 429 rate limit exceeded"},
+ priorSessionID: "stale-id",
+ provider: "deveco",
+ want: false,
+ },
+
+ // Failures with a defined non-session remedy. Restarting the
+ // conversation cannot fix a missing binary or an unavailable model,
+ // so these must not burn a second run even on the compat path.
+ {
+ name: "missing config does not retry",
+ result: agent.Result{Status: "failed", Error: "missing environment variable: ANTHROPIC_API_KEY"},
+ priorSessionID: "stale-id",
+ provider: "copilot",
+ want: false,
+ },
+ {
+ name: "unavailable model does not retry",
+ result: agent.Result{Status: "failed", Error: "model not found: gpt-99"},
+ priorSessionID: "stale-id",
+ provider: "opencode",
+ want: false,
+ },
+ {
+ name: "missing executable does not retry",
+ result: agent.Result{Status: "failed", Error: "cursor-agent: executable not found"},
+ priorSessionID: "stale-id",
+ provider: "cursor",
+ want: false,
+ },
+ {
+ name: "unsupported runtime version does not retry",
+ result: agent.Result{Status: "failed", Error: "installed CLI is below the minimum supported version"},
+ priorSessionID: "stale-id",
+ provider: "antigravity",
+ want: false,
+ },
+ {
+ name: "successful run never retries",
+ result: agent.Result{Status: "completed", SessionID: "sess"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "failure after a tool ran never retries",
+ result: agent.Result{Status: "failed", Error: "no conversation found", ResumeRejected: true},
+ priorSessionID: "stale-id",
+ tools: 1,
+ want: false,
+ },
+
+ // Failures a fresh session cannot cure. Each of these previously
+ // slipped through the exclusion-based gate and cost a wasted run plus
+ // a destroyed session pointer. provider_network is the sharpest case:
+ // internal/service/task.go marks it resume-safe precisely so the
+ // platform retry can continue the truncated conversation.
+ {
+ name: "provider network drop keeps the session",
+ result: agent.Result{Status: "failed", Error: "API Error: Connection closed mid-response"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "dns failure keeps the session",
+ result: agent.Result{Status: "failed", Error: "dial tcp: lookup api.anthropic.com: no such host"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "rate limit keeps the session",
+ result: agent.Result{Status: "failed", Error: "API Error: 429 rate limit exceeded"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "overloaded keeps the session",
+ result: agent.Result{Status: "failed", Error: "API Error: 529 overloaded_error"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "quota exhaustion keeps the session",
+ result: agent.Result{Status: "failed", Error: "API Error: 402 credit balance is too low"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "provider 5xx keeps the session",
+ result: agent.Result{Status: "failed", Error: "API Error: 500 internal_server_error"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ // Unclassified AND a session was established: nothing suggests
+ // the resume was the problem, so leave the pointer alone.
+ name: "unrecognised failure with a live session keeps it",
+ result: agent.Result{Status: "failed", Error: "exit status 1", SessionID: "live-sess"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ // Bad credentials cannot succeed on a second attempt. A 401
+ // before the first stream message leaves SessionID empty, which
+ // is exactly why an empty id never meant "resume was rejected".
+ name: "provider auth failure does not retry",
+ result: agent.Result{Status: "failed", Error: "API Error: 401 Unauthorized"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "revoked oauth token does not retry",
+ result: agent.Result{Status: "failed", Error: "OAuth access token has been revoked"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ // Mid-execution terminals carry their own status and must never
+ // reach the fallback.
+ name: "idle watchdog terminal does not retry",
+ result: agent.Result{Status: "idle_watchdog", Error: "no activity", ResumeRejected: true},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ {
+ name: "cancelled terminal does not retry",
+ result: agent.Result{Status: "cancelled"},
+ priorSessionID: "stale-id",
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ provider := tt.provider
+ if provider == "" {
+ provider = "claude"
+ }
+ if got := shouldRetryWithFreshSession(tt.result, tt.priorSessionID, tt.tools, provider); got != tt.want {
+ t.Fatalf("shouldRetryWithFreshSession(provider=%q) = %v, want %v", provider, got, tt.want)
+ }
+ })
+ }
+}
+
+// The compatibility path must be reachable ONLY by backends that cannot
+// report a rejection. One identical result, opposite answers: a backend that
+// can detect has already said "not a rejection" by leaving ResumeRejected
+// false, and must be taken at its word rather than second-guessed by
+// exclusion.
+func TestShouldRetryWithFreshSession_CompatPathIsBackendScoped(t *testing.T) {
+ t.Parallel()
+
+ // Unclassified startup failure, no session established — the exact shape
+ // the compat path exists to catch.
+ result := agent.Result{Status: "failed", Error: "exit status 1"}
+
+ undetectable := []string{"antigravity", "copilot", "cursor", "deveco", "opencode"}
+ for _, provider := range undetectable {
+ t.Run(provider+" retries", func(t *testing.T) {
+ t.Parallel()
+ if !shouldRetryWithFreshSession(result, "stale-id", 0, provider) {
+ t.Fatalf("%s cannot detect rejections; it must keep its empty-session recovery", provider)
+ }
+ })
+ }
+
+ detectable := []string{"claude", "codebuddy", "qwen", "codex", "grok", "hermes", "kimi", "kiro", "qoder", "traecli", "pi", "openclaw"}
+ for _, provider := range detectable {
+ t.Run(provider+" does not retry", func(t *testing.T) {
+ t.Parallel()
+ if shouldRetryWithFreshSession(result, "stale-id", 0, provider) {
+ t.Fatalf("%s reports rejections; a false ResumeRejected is an answer, not an absence", provider)
+ }
+ })
+ }
+
+ t.Run("unknown provider fails closed", func(t *testing.T) {
+ t.Parallel()
+ if shouldRetryWithFreshSession(result, "stale-id", 0, "some-future-backend") {
+ t.Fatal("a backend not listed as undetectable must not inherit the compat path")
+ }
+ })
+}
+
func TestExecuteAndDrain_CodexInactivityReportsToolResultTranscript(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fixture is POSIX-only")
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index ac9f932273..91d50dbb18 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -142,6 +142,22 @@ type Result struct {
DurationMs int64
SessionID string
Usage map[string]TokenUsage // keyed by model name
+ // ResumeRejected is positive evidence that this run's requested resume
+ // was itself refused — the transcript is gone, or the session belongs to
+ // another provider account. Only a refused resume can be cured by starting
+ // over, so it is what the daemon's fresh-session fallback looks for first.
+ //
+ // false is NOT evidence of the opposite. For a backend listed in
+ // ResumeRejectionUndetectable it means "could not tell"; for every other
+ // backend it means "checked, and this was not a rejection". The daemon
+ // needs the provider name to tell those apart — see
+ // shouldRetryWithFreshSession in internal/daemon.
+ //
+ // Backends must NOT set it for failures a new session cannot cure:
+ // network drops, rate limits, quota, provider 5xx, or auth errors. Those
+ // keep the session pointer so the platform's own retry can resume the
+ // truncated conversation (see retryableReasons in internal/service/task.go).
+ ResumeRejected bool
// codexInitializeRetrySafe is provider-internal evidence that an
// initialize timeout happened before semantic activity and after the
// process tree was reaped. It is intentionally not part of the public
@@ -210,6 +226,33 @@ func IsSupportedType(agentType string) bool {
return false
}
+// resumeRejectionUndetectable lists the backends that cannot produce
+// Result.ResumeRejected at all. They scrape SessionID out of stream output and
+// have no rejection detection: no phrase match, no structured error code, no
+// internal restart. copilot's own comment documents the hole (a session.error
+// arriving before session.start leaves SessionID empty), and antigravity's
+// conversation-id reader returns "" whenever the CLI exits before dispatching.
+//
+// Membership is deliberately opt-in. A backend absent from this map is treated
+// as capable, so a new backend fails closed — it reports no rejection and gets
+// no fallback — rather than silently inheriting a guess-based retry. Remove an
+// entry as soon as its backend learns to report rejections.
+var resumeRejectionUndetectable = map[string]bool{
+ "antigravity": true,
+ "copilot": true,
+ "cursor": true,
+ "deveco": true,
+ "opencode": true,
+}
+
+// ResumeRejectionUndetectable reports whether agentType is a backend that
+// cannot tell a refused resume from any other startup failure. Callers use it
+// to read a false Result.ResumeRejected correctly: "could not tell" for these,
+// "checked, not a rejection" for everything else.
+func ResumeRejectionUndetectable(agentType string) bool {
+ return resumeRejectionUndetectable[agentType]
+}
+
func New(agentType string, cfg Config) (Backend, error) {
if cfg.Logger == nil {
cfg.Logger = slog.Default()
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index aa80313821..6ba45263a5 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -280,21 +280,25 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
b.cfg.Logger.Info("claude finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
- reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", stderrTail)
- if reportedSessionID != sessionID {
- b.cfg.Logger.Info("claude resume did not land; clearing fresh session id for daemon fallback",
+ // The account-binding 400 arrives in the result event (finalError);
+ // "no conversation found" is printed to stderr. Check both.
+ resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
+ reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
+ if resumeRejected {
+ b.cfg.Logger.Info("claude resume was rejected; dropping session id and signalling fresh-session retry",
"requested_resume", opts.ResumeSessionID,
"emitted_session", sessionID,
)
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: reportedSessionID,
- Usage: usage,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: reportedSessionID,
+ Usage: usage,
+ ResumeRejected: resumeRejected,
}
}()
@@ -678,29 +682,76 @@ func buildClaudeInput(prompt string) ([]byte, error) {
return append(data, '\n'), nil
}
-// resolveSessionID decides which session id to report on the Result. When the
-// caller requested --resume but claude emitted a fresh, different session id
-// AND the run failed, the resume did not land. Claude can also report the
-// requested id while printing "No conversation found with session ID: ..." to
-// stderr. Returning "" in those cases keeps the daemon's retry-with-fresh-
-// session fallback able to trigger instead of persisting the dead resume id.
-func resolveSessionID(requestedResume, emitted string, failed bool, stderrTail ...string) string {
- if failed && requestedResume != "" && claudeNoConversationFound(stderrTail...) {
- return ""
+// resumeRejectedPhrases are the provider messages that positively identify a
+// refused resume, as opposed to a failure that merely happened to occur during
+// a resumed run. Shared by the stream-json backends (claude, codebuddy, qwen);
+// the ACP backends match structured error codes via isACPSessionNotFound
+// instead.
+//
+// Matching must stay tight: a false positive makes the daemon throw away a
+// recoverable session pointer and re-run the task, so anything ambiguous
+// belongs out of this list.
+var resumeRejectedPhrases = []string{
+ // Verified: claude prints this when the transcript named by --resume is
+ // absent. Covered by TestResolveSessionID's existing stderr fixture.
+ "no conversation found",
+ // Verified: qwen-code 0.20.0, captured in
+ // testdata/qwen-code-0.20.0-resume-not-found.stderr.txt — "No saved
+ // session found with ID <id>. Run `qwen --resume` without an ID to
+ // choose from existing sessions."
+ "no saved session found",
+ // Reported verbatim in multica-ai/multica#5704 against Claude Code
+ // 2.1.207 (zh-CN): "400 此 session 已绑定另外的ai账号,请执行 /new 开启新
+ // session". This is the account-switch guardrail this signal exists for.
+ "已绑定另外",
+ // INFERRED, not yet observed: the en-US wording of the same guardrail has
+ // not been captured. These are guesses derived from the zh-CN text and
+ // should be corrected once a real English sample is available. A miss
+ // here degrades to a terminal failure carrying the provider's raw error,
+ // which is diagnosable — it does not silently mis-route the run.
+ "bound to another account",
+ "bound to a different account",
+}
+
+// resumeWasRejected reports whether a failed run's --resume was itself
+// refused. It is the positive-evidence predicate behind Result.ResumeRejected:
+// only a rejected resume can be cured by starting a fresh session.
+//
+// texts should include every place the provider may have written the reason —
+// the final error string and the stderr tail — because the account-binding 400
+// arrives in the stream-json result event while "no conversation found" is
+// printed to stderr.
+func resumeWasRejected(requestedResume, emitted string, failed bool, texts ...string) bool {
+ if !failed || requestedResume == "" {
+ return false
}
- if failed && requestedResume != "" && emitted != "" && emitted != requestedResume {
- return ""
+ for _, text := range texts {
+ lower := strings.ToLower(text)
+ for _, phrase := range resumeRejectedPhrases {
+ if strings.Contains(lower, phrase) {
+ return true
+ }
+ }
}
- return emitted
+ // Claude answered with a different session than the one we asked to
+ // continue: the requested transcript did not load.
+ return emitted != "" && emitted != requestedResume
}
-func claudeNoConversationFound(stderrTail ...string) bool {
- for _, tail := range stderrTail {
- if strings.Contains(strings.ToLower(tail), "no conversation found") {
- return true
- }
+// resolveSessionID decides which session id to report on the Result. A session
+// known to be dead must not be persisted as the resume pointer, so a rejected
+// resume reports "" regardless of what claude echoed back.
+//
+// This is deliberately no longer the signal the daemon reads to decide *why*
+// a run failed — Result.ResumeRejected carries that. An empty SessionID is
+// also produced by any failure before the first stream message (a 401, a
+// missing binary), which is why inferring "the resume was rejected" from it
+// was wrong in both directions.
+func resolveSessionID(requestedResume, emitted string, failed bool, texts ...string) string {
+ if resumeWasRejected(requestedResume, emitted, failed, texts...) {
+ return ""
}
- return false
+ return emitted
}
func buildEnv(extra map[string]string) []string {
diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.go
index 76ee5811d4..0ed99d33a3 100644
--- a/server/pkg/agent/claude_test.go
+++ b/server/pkg/agent/claude_test.go
@@ -811,6 +811,131 @@ func TestWriteMcpConfigToTemp(t *testing.T) {
}
}
+func TestResumeWasRejected(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ requested string
+ emitted string
+ failed bool
+ texts []string
+ want bool
+ }{
+ {
+ // Verbatim from multica-ai/multica#5704 (Claude Code 2.1.207,
+ // zh-CN). This is the failure the whole signal exists for: the
+ // session belongs to the account the user switched away from, and
+ // claude echoes the requested id back rather than a fresh one.
+ name: "account binding 400 echoing the requested id is a rejection",
+ requested: "sess-old",
+ emitted: "sess-old",
+ failed: true,
+ texts: []string{"400 此 session 已绑定另外的ai账号,请执行 /new 开启新 session"},
+ want: true,
+ },
+ {
+ name: "no conversation found on stderr is a rejection",
+ requested: "sess-dead",
+ emitted: "sess-dead",
+ failed: true,
+ texts: []string{"No conversation found with session ID: sess-dead"},
+ want: true,
+ },
+ {
+ name: "a different emitted id means the resume did not land",
+ requested: "sess-dead",
+ emitted: "fresh-new",
+ failed: true,
+ want: true,
+ },
+
+ // Failures a fresh session cannot cure. None of these may set the
+ // flag: doing so would throw away a session the platform's own retry
+ // is expected to resume.
+ {
+ name: "mid-response network drop is not a rejection",
+ requested: "sess-old",
+ emitted: "sess-old",
+ failed: true,
+ texts: []string{"API Error: Connection closed mid-response"},
+ want: false,
+ },
+ {
+ name: "rate limit is not a rejection",
+ requested: "sess-old",
+ emitted: "sess-old",
+ failed: true,
+ texts: []string{"API Error: 429 rate_limit_error: rate limit exceeded"},
+ want: false,
+ },
+ {
+ name: "overloaded is not a rejection",
+ requested: "sess-old",
+ emitted: "sess-old",
+ failed: true,
+ texts: []string{"API Error: 529 overloaded_error"},
+ want: false,
+ },
+ {
+ name: "quota exhaustion is not a rejection",
+ requested: "sess-old",
+ emitted: "sess-old",
+ failed: true,
+ texts: []string{"API Error: 402 credit balance is too low"},
+ want: false,
+ },
+ {
+ // Reported alongside the 400 in #5704 and easy to conflate with
+ // it. This one needs a re-login, not a new session.
+ name: "revoked oauth token is not a rejection",
+ requested: "sess-old",
+ emitted: "sess-old",
+ failed: true,
+ texts: []string{"401 Invalid authentication credentials: OAuth access token has been revoked"},
+ want: false,
+ },
+ {
+ name: "a run that succeeded is never a rejection",
+ requested: "sess-old",
+ emitted: "fresh-new",
+ failed: false,
+ texts: []string{"No conversation found with session ID: sess-old"},
+ want: false,
+ },
+ {
+ name: "no resume requested is never a rejection",
+ requested: "",
+ emitted: "fresh-abc",
+ failed: true,
+ texts: []string{"No conversation found with session ID: whatever"},
+ want: false,
+ },
+ {
+ // A failure before claude emitted anything. Empty is not
+ // evidence of anything, which is why the daemon stopped reading
+ // an empty SessionID as "the resume was rejected".
+ name: "failure with no emitted id and no matching text is not a rejection",
+ requested: "sess-old",
+ emitted: "",
+ failed: true,
+ texts: []string{"exit status 1"},
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got := resumeWasRejected(tc.requested, tc.emitted, tc.failed, tc.texts...)
+ if got != tc.want {
+ t.Fatalf("resumeWasRejected(%q, %q, %v, %q) = %v, want %v",
+ tc.requested, tc.emitted, tc.failed, tc.texts, got, tc.want)
+ }
+ })
+ }
+}
+
func TestResolveSessionID(t *testing.T) {
t.Parallel()
@@ -955,6 +1080,128 @@ func TestClaudeExecuteSurfacesStderrWhenChildExitsEarly(t *testing.T) {
}
}
+// End-to-end through the backend rather than the predicate alone: a fake
+// claude reproduces the account-switch guardrail from #5704 — it echoes the
+// resumed session id back on the init frame, then fails the turn with the
+// 400. The result must carry ResumeRejected so the daemon retries fresh, and
+// must not persist the dead session id.
+func TestClaudeExecuteReportsResumeRejectedOnAccountBinding(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "claude")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `echo '{"type":"system","subtype":"init","session_id":"sess-old"}'` + "\n" +
+ `echo '{"type":"result","subtype":"error","is_error":true,"session_id":"sess-old","result":"400 此 session 已绑定另外的ai账号,请执行 /new 开启新 session"}'` + "\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{"IS_SANDBOX": "1"},
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{
+ ResumeSessionID: "sess-old",
+ 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 != "failed" {
+ t.Fatalf("expected status=failed, got %q", result.Status)
+ }
+ if !result.ResumeRejected {
+ t.Fatalf("expected ResumeRejected for the account-binding 400, got error=%q", result.Error)
+ }
+ // The session belongs to the previous account; keeping it would make
+ // every later dispatch on this (agent, workdir) fail identically.
+ if result.SessionID != "" {
+ t.Fatalf("expected the dead session id to be dropped, got %q", result.SessionID)
+ }
+ // The provider's own wording has to survive so a matcher miss on some
+ // other locale is diagnosable from the failure itself.
+ if !strings.Contains(result.Error, "已绑定另外") {
+ t.Fatalf("expected the raw provider error to be preserved, got %q", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+// The counterpart: a resumed run that dies from a transient network fault
+// must NOT be reported as a rejected resume, and must keep its session id so
+// the platform's resume-safe retry can continue the conversation.
+func TestClaudeExecuteKeepsSessionOnNetworkFailure(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "claude")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `echo '{"type":"system","subtype":"init","session_id":"sess-old"}'` + "\n" +
+ `echo '{"type":"result","subtype":"error","is_error":true,"session_id":"sess-old","result":"API Error: Connection closed mid-response"}'` + "\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{"IS_SANDBOX": "1"},
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{
+ ResumeSessionID: "sess-old",
+ 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.ResumeRejected {
+ t.Fatal("a network drop must not be reported as a rejected resume")
+ }
+ if result.SessionID != "sess-old" {
+ t.Fatalf("expected the session to survive a network failure, got %q", result.SessionID)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
func TestClaudeExecuteRecordsResultModelUsage(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.go
index c41892e841..c2528b4c61 100644
--- a/server/pkg/agent/codebuddy.go
+++ b/server/pkg/agent/codebuddy.go
@@ -293,21 +293,23 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
b.cfg.Logger.Info("codebuddy finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
- reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed")
- if reportedSessionID != sessionID {
- b.cfg.Logger.Info("codebuddy resume did not land; clearing fresh session id for daemon fallback",
+ resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError)
+ reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError)
+ if resumeRejected {
+ b.cfg.Logger.Info("codebuddy resume was rejected; dropping session id and signalling fresh-session retry",
"requested_resume", opts.ResumeSessionID,
"emitted_session", sessionID,
)
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: reportedSessionID,
- Usage: usage,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: reportedSessionID,
+ Usage: usage,
+ ResumeRejected: resumeRejected,
}
}()
diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.go
index 1b834208c8..43fe06b6e1 100644
--- a/server/pkg/agent/grok.go
+++ b/server/pkg/agent/grok.go
@@ -266,6 +266,10 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
finalStatus := "completed"
var finalError string
var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
effectiveModel := strings.TrimSpace(opts.Model)
initResult, err := c.request(runCtx, "initialize", map[string]any{
@@ -385,12 +389,14 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- SessionID: sessionID,
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
}
return
}
@@ -427,6 +433,7 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
}
} else {
@@ -488,12 +495,13 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- Usage: usageMap,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index fc967c968e..10bf1e8dc3 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -341,6 +341,10 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
finalStatus := "completed"
var finalError string
var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
effectiveModel := strings.TrimSpace(opts.Model)
// The model id the runtime reports as current right after
// session/new or session/resume. Used to skip a redundant
@@ -471,12 +475,14 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- SessionID: sessionID,
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
}
return
}
@@ -528,6 +534,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
}
} else {
@@ -608,12 +615,13 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- Usage: usageMap,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index 0402e7605f..821935fb50 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -179,6 +179,10 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
finalStatus := "completed"
var finalError string
var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
// 1. Initialize handshake.
initResult, err := c.request(runCtx, "initialize", map[string]any{
@@ -284,12 +288,14 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- SessionID: sessionID,
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
}
return
}
@@ -331,6 +337,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
}
} else {
@@ -385,12 +392,13 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- Usage: usageMap,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()
diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.go
index 6875b71173..fff9ca4c98 100644
--- a/server/pkg/agent/kiro.go
+++ b/server/pkg/agent/kiro.go
@@ -220,6 +220,10 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
finalStatus := "completed"
var finalError string
var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
effectiveModel := strings.TrimSpace(opts.Model)
initResult, err := c.request(runCtx, "initialize", map[string]any{
@@ -324,12 +328,14 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- SessionID: sessionID,
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
}
return
}
@@ -390,6 +396,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
}
} else {
@@ -446,12 +453,13 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- Usage: usageMap,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()
diff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.go
index b04d49cfe0..6f2d7e241e 100644
--- a/server/pkg/agent/qoder.go
+++ b/server/pkg/agent/qoder.go
@@ -208,6 +208,10 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
finalStatus := "completed"
var finalError string
var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
effectiveModel := strings.TrimSpace(opts.Model)
initResult, err := c.request(runCtx, "initialize", map[string]any{
@@ -304,12 +308,14 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- SessionID: sessionID,
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
}
return
}
@@ -350,6 +356,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
}
} else {
@@ -423,12 +430,13 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- Usage: usageMap,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()
diff --git a/server/pkg/agent/qwen.go b/server/pkg/agent/qwen.go
index 09d11023ae..e67638d83f 100644
--- a/server/pkg/agent/qwen.go
+++ b/server/pkg/agent/qwen.go
@@ -171,7 +171,8 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
b.cfg.Logger.Info("qwen finished", "pid", cmd.Process.Pid, "status", status, "duration", duration.Round(time.Millisecond).String())
resCh <- Result{
Status: status, Output: output, Error: errMsg, DurationMs: duration.Milliseconds(),
- SessionID: resolveSessionID(opts.ResumeSessionID, state.sessionID, status == "failed"), Usage: state.usage,
+ SessionID: resolveSessionID(opts.ResumeSessionID, state.sessionID, status == "failed", errMsg), Usage: state.usage,
+ ResumeRejected: resumeWasRejected(opts.ResumeSessionID, state.sessionID, status == "failed", errMsg),
}
}()
return &Session{Messages: msgCh, Result: resCh}, nil
diff --git a/server/pkg/agent/qwen_test.go b/server/pkg/agent/qwen_test.go
index 2ecc41d5da..3e1fd6876c 100644
--- a/server/pkg/agent/qwen_test.go
+++ b/server/pkg/agent/qwen_test.go
@@ -185,12 +185,17 @@ func TestQwenBackendFailureTimeoutAndCancellation(t *testing.T) {
status string
needle string
wantSession string
+ // wantResumeRejected asserts the daemon gets positive evidence that
+ // the resume itself was refused. Without it the fresh-session
+ // fallback never fires and the user is back to a terminal failure
+ // they have to clear by hand.
+ wantResumeRejected bool
}{
- {"result error", map[string]string{"QWEN_MODE": "error"}, newQwenTestContext, ExecOptions{}, "failed", "synthetic Qwen authentication failure", "sess-error"},
- {"process error", map[string]string{"QWEN_MODE": "exit"}, newQwenTestContext, ExecOptions{}, "failed", "synthetic qwen stderr", ""},
- {"missing resume", map[string]string{"QWEN_MODE": "resume-missing", "QWEN_STDERR_FIXTURE": resumeFixture}, newQwenTestContext, ExecOptions{ResumeSessionID: "session-redacted"}, "failed", "No saved session found", ""},
- {"timeout", map[string]string{"QWEN_MODE": "spin"}, newQwenTestContext, ExecOptions{Timeout: 20 * time.Millisecond}, "timeout", "timed out", ""},
- {"cancel", map[string]string{"QWEN_MODE": "spin"}, newQwenTestContext, ExecOptions{}, "aborted", "cancelled", ""},
+ {"result error", map[string]string{"QWEN_MODE": "error"}, newQwenTestContext, ExecOptions{}, "failed", "synthetic Qwen authentication failure", "sess-error", false},
+ {"process error", map[string]string{"QWEN_MODE": "exit"}, newQwenTestContext, ExecOptions{}, "failed", "synthetic qwen stderr", "", false},
+ {"missing resume", map[string]string{"QWEN_MODE": "resume-missing", "QWEN_STDERR_FIXTURE": resumeFixture}, newQwenTestContext, ExecOptions{ResumeSessionID: "session-redacted"}, "failed", "No saved session found", "", true},
+ {"timeout", map[string]string{"QWEN_MODE": "spin"}, newQwenTestContext, ExecOptions{Timeout: 20 * time.Millisecond}, "timeout", "timed out", "", false},
+ {"cancel", map[string]string{"QWEN_MODE": "spin"}, newQwenTestContext, ExecOptions{}, "aborted", "cancelled", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := tc.ctx()
@@ -207,6 +212,9 @@ func TestQwenBackendFailureTimeoutAndCancellation(t *testing.T) {
if result.Status != tc.status || !strings.Contains(result.Error, tc.needle) || result.SessionID != tc.wantSession {
t.Fatalf("result = %+v, want status=%q error containing %q session=%q", result, tc.status, tc.needle, tc.wantSession)
}
+ if result.ResumeRejected != tc.wantResumeRejected {
+ t.Fatalf("ResumeRejected = %v, want %v (error=%q)", result.ResumeRejected, tc.wantResumeRejected, result.Error)
+ }
})
}
}
diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.go
index 8e39f5eb8c..1fbd2c793f 100644
--- a/server/pkg/agent/traecli.go
+++ b/server/pkg/agent/traecli.go
@@ -225,6 +225,10 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
finalStatus := "completed"
var finalError string
var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
effectiveModel := strings.TrimSpace(opts.Model)
initResult, err := c.request(runCtx, "initialize", map[string]any{
@@ -318,12 +322,14 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
resCh <- Result{
- Status: finalStatus,
- Error: finalError,
- DurationMs: time.Since(startTime).Milliseconds(),
- SessionID: sessionID,
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
}
return
}
@@ -358,6 +364,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
"session_id", sessionID,
)
sessionID = ""
+ resumeRejected = true
}
}
} else {
@@ -426,12 +433,13 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
}
resCh <- Result{
- Status: finalStatus,
- Output: finalOutput,
- Error: finalError,
- DurationMs: duration.Milliseconds(),
- SessionID: sessionID,
- Usage: usageMap,
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
}
}()